diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -19,17 +19,9 @@
 Then in the root of your project or package:
 
 ```
-git clone https://github.com/simonmar/haskell-buck2.git buck2 -b <version>
 cabal buck2 --enable-tests
 ```
 
-Where `<version>` is the version of `cabal-buck`,
-e.g. `0.2.0.0`. Checking out the branch ensures that you get a
-compatible copy of the Buck2 support code. `cabal buck2` checks that
-`buck2/` is for its release (the `CABAL_BUCK2_VERSION` in
-`buck2/version.bzl`), and so does buck2 when it reads the files that
-`cabal buck2` generated, and the error says which branch to switch to.
-
 Then you can use `buck2` as the build tool, e.g.
 
 ```
@@ -47,7 +39,7 @@
 Note that you need to re-run `cabal buck2 --enable-tests` if you
 modify the `cabal.project` or any of the `.cabal` files.
 
-Not all Cabal features are supported - see [limitations](#limitations).
+Most Cabal features are supported but not all - see [limitations](#limitations).
 
 # Why?
 
@@ -57,9 +49,9 @@
 just using `cabal`? Well, first off let me be clear that you *still
 need Cabal*, because the Buck2 support doesn't know how to solve
 package dependencies or build them. So the workflow consists of first
-running `cabal buck2` to solve and build the dependencies, but once you've
-done that you can switch to `buck2` for building. The idea is that
-`buck2` is a more pleasant experience because:
+running `cabal buck2` to solve and build the dependencies, but once
+you've done that you can switch to `buck2` for building and running
+tests. The idea is that `buck2` is a more pleasant experience because:
 
 * It's [faster than Cabal, particularly for rebuilds](#performance).
 
@@ -67,20 +59,24 @@
   build in `dev` mode (unoptimised with dynamic linking) but adding
   `-m opt` gives you optimisation and static linking. Note that Cabal
   doesn't have a purely dynamic build mode: it always uses `-dynamic-too`
-  for libraries, which has a significant built-time performance cost.
+  for libraries, which has a significant build-time performance cost.
 
+* It works a lot better than Cabal when you have non-Haskell code (e.g. C/C++ or Rust) in your project, because
+  * Buck2 understands dependencies between C/C++ source files and header files (Cabal doesn't: [issue #4306](https://github.com/haskell/cabal/issues/4306)), so when you modify a C/C++ header the correct things are rebuilt.
+  * Buck2 builds C/C++ files in parallel, while Cabal doesn't ([issue #7127](https://github.com/haskell/cabal/issues/7127))
+
+* There is support for using a build cache; see [Sharing build results
+  (a build cache)](#sharing-build-results-a-build-cache). A build
+  cache means that if you need to quickly create a new worktree to
+  work on a new feature or bugfix, for example, the build in the new
+  worktree is mostly fetched from the cache instead of being rebuilt.
+
 * The Buck2 build is extensible. If you have anything that needs to be
   generated as part of your build, or any non-standard tooling, then
   hooking that up using Buck2 is far easier than Cabal.  Furthermore
   Buck2 knows how to rebuild things correctly when either the build
   system or the code generator components change.
 
-* It works a lot better than Cabal when you have non-Haskell code (e.g. C/C++ or Rust) in your project, because
-  * Buck2 understands dependencies between C/C++ source files and header files (Cabal doesn't: [issue #4306](https://github.com/haskell/cabal/issues/4306)), so when you modify a C/C++ header the correct things are rebuilt.
-  * Buck2 builds C/C++ files in parallel, while Cabal doesn't ([issue #7127](https://github.com/haskell/cabal/issues/7127))
-
-* You can use [remote execution and caching](https://buck2.build/docs/users/remote_execution/). There is built-in support for using a build cache, see [Sharing build results (a build cache)](#sharing-build-results-a-build-cache) below.
-
 Finally, if you have an existing codebase using Buck2 then this is the
 basis of something that could "buckify" Cabal packages to integrate
 into your build system. It needs a bit of work to be suitable for that
@@ -91,11 +87,11 @@
 
 # How complete is it?
 
-I've used it to build a few large projects, in particular the Cabal
-project itself which consists of about 16 packages and a few hundred
-source files. It can also build [Glean](https://glean.software), which
-has some complex build requirements including custom codegen, FFI &
-hsc2hs.
+We've used it to build a few large projects, for instance the Cabal
+project itself, the Haskell Language Server, and
+[Amazonka](https://github.com/brendanhay/amazonka). It can also
+build [Glean](https://glean.software), which has some complex build
+requirements including custom codegen, FFI & hsc2hs.
 
 There are a few [limitations](#limitations), however.
 
@@ -110,32 +106,45 @@
 
 2. Generates some files, notably:
 
+   * The `buck2/` directory containing the Buck2 support code;
+
+   * `.buckconfig`, containing build-wide configuration options, and
+     `PACKAGE`, which sets the default build mode. `cabal buck2` only
+     creates these two files if they don't exist, so you can edit
+     them;
+
+   * `.buckconfig.local`, if you use a [build
+     cache](#sharing-build-results-a-build-cache);
+
    * `BUCK` and `BUCK.cabal.bzl` in each package, these are the Buck2
-     build targets
+     build targets;
 
    * `cabal-buck2/autogen` in each package, this is where we put the
      files that Cabal autogenerates, such as `cabal_macros.h` and
-     `Paths_<pkg>.hs`.
+     `Paths_<pkg>.hs`;
 
    * `cabal-buck2/packages.bzl` in the root of the project, which says
-     where each of your packages is. Nothing in a package's
-     `BUCK.cabal.bzl` says where it is or where the packages it depends
-     on are, so moving a package, or building it as part of a bigger
-     project, only changes this file. (All the packages have to be in
-     the one Buck2 cell, the root.)
+     where each of your packages is. The `BUCK.cabal.bzl` files don't
+     say where any package is, so moving a package, or building it as
+     part of a bigger project, only changes this file. (All the
+     packages have to be in the one Buck2 cell, the root.)
 
    * `third-party/haskell`: tells Buck2 about all the prebuilt package
-     dependencies, either in the Cabal store or in GHC's package
-     DB (unless you build the dependencies from source, see below). In here we also record the GHC version you're using, and the
-     paths to any tool dependencies.
+     dependencies, either in GHC's package DB or the Cabal store
+     (unless you [build the dependencies from
+     source](#building-the-dependencies-with-buck2)). In here we also
+     record the GHC version you're using, and the paths to any tool
+     dependencies.
 
 A component that can't be built with buck2 (e.g. `build-type: Custom`)
 is an error: `cabal buck2` lists them and aborts, unless you give the
 `--keep-going` flag in which case it will translate everything it
 can and warn about the missing components.
 
-# Buck2 quick start
+# Using Buck2
 
+## Quick start
+
 To build your code:
 
 ```
@@ -143,20 +152,115 @@
 ```
 
 The `//...` is Buck2's syntax for "all targets recursively below the
-current directory". You can also build specific target(s), for example
+root of the project". You can also build specific target(s), for example
 `buck2 build cabal-install:cabal` would build the `cabal` target in
 the `cabal-install` package. For more details see [Target
 Pattern](https://buck2.build/docs/concepts/target_pattern/) in the
 Buck2 docs.
 
+To see the targets that a package has, run:
+
+```
+buck2 targets //<package>/...
+```
+
 Next you can run your tests:
 
 ```
 buck2 test //...
 ```
 
+## Build modes
+
+The Buck2 build system has the following build mode options, which can
+be selected using `-m` on the Buck2 command line (e.g. `-m opt`)
+
+  * Optimisation:
+    * `dev`: (default) no optimisation, `-g` for C/C++.
+    * `opt`: adds `-O` for Haskell, `-O3 -DNDEBUG` for C/C++, and also enables
+      `static` unless overridden by `shared`.
+  * Linking:
+    * `shared`: (default) shared libraries, dynamic linking
+    * `static`: static linking, but also builds shared libraries using
+    `-dynamic-too` because those are required for Template Haskell.
+  * Profiling:
+    * `prof`: enables Haskell profiling; also forces `static`.
+
+To use any of these modes, add them using `-m` on the command line:
+
+```
+buck2 build my-package:my-program -m opt
+```
+
+# Buck2-specific features in `.cabal`
+
+`cabal buck2` recognises some extra fields in your `.cabal` file which affect how Buck2 builds the package; these are described in the sections below.
+
+## Runtime tool dependencies
+
+Cabal provides a way to indicate build-time tool dependencies with
+`build-tool-depends`, but it also treats these as _runtime_ tool dependencies
+(i.e. it puts them on the `PATH` for test runs and `cabal run`s of executables).
+
+If we don't distinguish these, then all `build-tool-depends` must be
+built in both the build and target configurations, which means they
+will be built twice.
+
+For this reason we provide a way to fill in the "missing" Cabal `run-tool-depends` 
+field (proposed in [haskell/cabal#5411](https://github.com/haskell/cabal/issues/5411)).
+
+This works as follows:
+
+```
+test-suite tests
+  -- So `cabal test` continues to work.
+  build-tool-depends: my-package:my-exe
+  -- Not truly needed to _build_ the test-suite...
+  x-buck2-ignore-build-tool-depends: my-package:my-exe
+  -- Needed when the test suite runs 
+  x-buck2-run-tool-depends: my-package:my-exe
+```
+
+If `x-buck2-run-tool-depends` is present, we assume that it is accurate, and 
+so do not consider `build-tool-depends` to be runtime dependencies. If 
+`x-buck2-run-tool-depends` is not present, we assume that we have to mimic 
+Cabal's behaviour, and so `build-tool-depends` will also be considered runtime dependencies.
+
+## Splice dependencies
+
+With [Per-module compilation](#using-per-module-compilation), modules using Template Haskell
+can only compile once the libraries that they use are linked.
+Cabal's `build-depends` doesn't say which libraries are actually used in TH,
+so by default a Template Haskell module has to wait for all of them.
+
+A component can list the libraries whose code its splices run in
+`x-buck2-splice-depends`. This fills in a "missing" Cabal field, proposed in
+[haskell/cabal#12583](https://github.com/haskell/cabal/issues/12583).
+
+```
+library
+  build-depends: base, aeson, my-codegen
+  -- Only my-codegen's code runs in the splices.
+  x-buck2-splice-depends: my-codegen
+```
+
+The libraries must also be in `build-depends` so that cabal can link them.
+
+If `x-buck2-splice-depends` is present, we assume that it is
+accurate. If the field is not present, we are pessimistic and assume that
+a Template Haskell module may use any of the component's libraries.
+
+
 # Customising the build
 
+`cabal buck2` sets up the project so that Buck2 will build it exactly as Cabal would. However, it also provides various hooks that let you modify and customise the build, and these hooks are designed to survive re-running `cabal buck2` so you can have permanent Buck2-specific customisations in your project if you want.
+
+## Configuring the build
+
+The `.buckconfig` file has the build-wide configuration settings. Some of these are specific to Haskell targets; see the comments in the file for details. Typically this file will be checked-in and contain options that everyone building the project with Buck2 needs, so to set options for your local build only you can use `.buckconfig.local`. 
+
+## Customising the rules
+
 `cabal buck2` will generate all the `BUCK` files if they don't exist,
 but you can also write your own if you want (`cabal buck2` won't
 overwrite them).
@@ -182,8 +286,30 @@
 }
 ```
 
-Re-run `cabal buck2` after adding or removing `cabal-buck2.bzl`.
+`cabal-buck2.bzl` can also give defaults for the generated targets,
+for every package (`"*"`) or for one package. Each package's defaults
+are keyed by the kind of target (`"library"`, `"executable"`,
+`"test-suite"` or `"benchmark"`), or by `"*"` for every kind. For
+example, to compile every target of the project module by module:
 
+```
+DEFAULTS = {
+    # package name or "*" -> kind or "*" -> extra attributes
+    "*": {
+        "*": {"per_module": True},
+    },
+}
+```
+
+The attributes are merged into the generated ones: lists are appended
+to, dicts are merged, and anything else is replaced. The overrides of
+a component win over all of the defaults, and the defaults for a
+package win over the defaults for every package. See
+`cabal_targets()` in `buck2/cabal.bzl` for the details.
+
+Re-run `cabal buck2` after adding or removing `cabal-buck2.bzl`, or
+adding or removing its `OVERRIDES` or `DEFAULTS`.
+
 You can also completely override the generated targets and write a
 `BUCK` file with your own rules, while still making use of the
 pre-built dependencies that `cabal buck2` produces.  For example, the
@@ -227,28 +353,78 @@
 
 You can find docs on how to write `BUCK` files in the Buck2 docs, e.g. [haskell_library](https://buck2.build/docs/prelude/rules/haskell/haskell_library/).
 
-# Build modes
+## Modifying the support code under `buck2/`
 
-The Buck2 build system has the following build mode options, which can
-be selected using `-m` on the Buck2 command line (e.g. `-m opt`)
+If you want to change the support code, or use a version of it that
+isn't released yet, you can use a git checkout of the corresponding
+branch of [haskell-buck2](https://github.com/simonmar/haskell-buck2)
+instead:
 
-  * Optimisation:
-    * `dev`: (default) no optimisation, `-g` for C/C++.
-    * `opt`: adds `-O` for Haskell, `-O3 -DNDEBUG` for C/C++, and also enables
-      `static` unless overridden by `shared`.
-  * Linking:
-    * `shared`: (default) shared libraries, dynamic linking
-    * `static`: static linking, but also builds shared libraries using
-    `-dynamic-too` because those are required for Template Haskell.
-  * Profiling:
-    * `prof`: enables Haskell profiling; also forces `static`.
+```
+git clone https://github.com/simonmar/haskell-buck2.git buck2 -b <version>
+```
 
-To use any of these modes, add them using `-m` on the command line:
+Where `<version>` is the version of `cabal-buck2`, e.g. `0.6.0.0`.
+`cabal buck2` never replaces a `buck2/` that it didn't create
+itself. Instead it checks that `buck2/` is for its release (the
+`CABAL_BUCK2_VERSION` in `buck2/version.bzl`), and so does buck2 when
+it reads the files that `cabal buck2` generated. If they don't match,
+the error says which branch to switch to.
 
+## The compilers
+
+Buck2 builds with the tools that `cabal buck2` found when it last ran, not
+with whatever is on the `PATH` of the shell you run `buck2` in. So after
+changing your tools (a different GHC, or a different Nix shell), re-run
+`cabal buck2`; restarting buck2 isn't needed. (`cabal buck2` puts a symlink to
+each of them in `third-party/haskell/toolchain`.)
+
+* GHC is the one that `cabal` uses (`-w` chooses another), and `ghc-pkg`,
+  `hsc2hs` and `haddock` are those that `cabal` finds (normally next to
+  GHC; use `--with-hsc2hs` and so on choose different ones).
+* The C and C++ compilers, for your packages' C and C++ sources, are:
+  * the C compiler you give `cabal` for `gcc`, with `--with-gcc`, or in
+    `cabal.project` (or `cabal.project.local`):
+    ```
+    program-locations
+      gcc-location: clang
+    ```
+    and the C++ compiler of the same name next to it (`clang++` for `clang`,
+    `g++` for `gcc`, `clang++-18` for `clang-18`...). `cabal` uses the C
+    compiler for the C of the packages it builds too.
+  * otherwise GHC's, if it has an absolute path for "C compiler
+    command" in `ghc --info` (as a GHC built by Nix
+    does);
+  * otherwise `clang` and `clang++`, linking with `g++`. These are the
+    Buck2 toolchain defaults.
+
+# Using per-module compilation
+
+By default Buck2 builds each library and executable using a single `ghc --make`, just as Cabal does. However, it can also compile each module separately which has significant advantages:
+
+* The build can use more parallelism (Buck2 doesn't currently use `--make -j` and it doesn't use GHC's `-jsem`; while it would be easy to support `--make -j` there's no easy way to integrate `-jsem` with Buck2 so each compile would consume a fixed number of cores regardless of how many it actually needed.)
+* Module dependencies ignore package boundaries, so a module's compile can begin as soon as the modules it depends on have been built. This can significantly increase the available parallelism beyond what `--make` could do.
+* Incremental compiles are typically much faster, because a `--make` compile has to re-read interfaces for the whole library.
+* We provide a persistent GHC worker to improve the performance of module-by-module compilation compared with using bare `ghc -c`. This is built automatically by Buck2 and used for per-module compilation unless you say otherwise in `.buckconfig`.
+
+We currently consider per-module compilation as experimental so it has to be enabled explicitly: in your `.buckconfig` add
+
 ```
-buck2 build my-package:my-program -m opt
+[haskell]
+    compile_granularity = module
 ```
 
+to enable per-module compilation for every target. It can also be enabled on a target-by-target basis using `cabal-buck2.bzl`: see [Customising the rules](#customising-the-rules).
+
+The worker is built and used automatically; to disable it, add this to `.buckconfig`:
+
+```
+[haskell]
+    per_module_worker = none
+```
+
+For more details, see [Per-module compilation](https://github.com/simonmar/haskell-buck2/tree/0.6.0.0#per-module-compilation-experimental) in the `haskell-buck2` docs.
+
 # Sharing build results (a build cache)
 
 By default buck2 keeps nothing between runs of its daemon, nor between
@@ -263,9 +439,12 @@
 cabal buck2 --cache=grpc://127.0.0.1:9092
 ```
 
-`--cache` adds a block to `.buckconfig` (between `# >>> cabal buck2: cache`
-and `# <<< cabal buck2: cache <<<`; anything else in the file is left alone),
-which later runs keep. `cabal buck2 --no-cache` removes it. **Run
+`--cache` adds a block to `.buckconfig.local` (between
+`# >>> cabal buck2: cache` and `# <<< cabal buck2: cache <<<`; anything else in
+the file is left alone), which later runs keep. `cabal buck2 --no-cache` removes
+it. `.buckconfig.local` is for the settings of one checkout and isn't usually
+committed (add it to `.gitignore`); a project that wants everyone to use the
+same cache can copy the block into `.buckconfig` instead. **Run
 `buck2 kill` after changing it**: buck2 reads the cache's address when its
 daemon starts, and a daemon that was already running keeps the old settings.
 
@@ -329,56 +508,128 @@
 
 # Performance
 
-I ran some experiments building the Cabal project itself - 16 packages
-and 641 source files (one package, `hackage-security`, is not part of
-the project but has to be built locally nonetheless because it depends
-on `Cabal-syntax` which *is* part of the project).
+We compared cabal and buck2 on three open-source projects:
 
-Buck2 shines when it comes to rebuilds: the dependency graph is cached
-in memory, and it knows when build steps can be omitted because the
-inputs haven't changed.
+* **The [Cabal](https://github.com/haskell/cabal) project** itself
+  (without `cabal-testsuite`, which has `build-type: Custom`).
+* **[haskell-language-server](https://github.com/haskell/haskell-language-server)**,
+  with about 240 library modules in some 35 libraries. It is a chain of
+  libraries from `hls-graph` through `ghcide` to `hls-plugin-api`, and
+  then a library for each plugin.
+* **A subset of [amazonka](https://github.com/brendanhay/amazonka)**
+  with about 4,500 modules. It is `amazonka-core`, `amazonka`, the SSO
+  and STS services that `amazonka` needs, and five of the largest
+  generated services: EC2, SageMaker, QuickSight, S3 and DynamoDB.
 
-![Buck2 vs Cabal build times](https://raw.githubusercontent.com/simonmar/cabal-buck2/refs/heads/master/perf-chart.svg)
+Each project was built in four ways, all without optimisation and with 8
+jobs at once:
 
-**Caveats**
+* **cabal**: `cabal build`, with GHC's `-jsem` semaphore, so that the
+  modules of a package compile in parallel too.
+* **buck2, per component**: buck2 compiling each component with one
+  `ghc --make`, which is the default.
+* **buck2, per module**: buck2 compiling each module in a build step of
+  its own, in the persistent worker.
+* **cabal repl**: `cabal repl --enable-multi-repl` of the project's
+  components, with `:reload` after each edit. A repl loads bytecode and
+  links nothing, so it does less work than the other three. It is here
+  to show how buck2 compares with an edit-and-reload loop.
 
-* Results tend to be +/- a few seconds from run to run
-* I didn't dig into the results in any detail
-* It's just one set of data points. Different projects and different choices of edits could give different results. However, I did perform a similar
-experiment with the [persistent](https://github.com/yesodweb/persistent)
-project, and got similar results.
+For each way, the benchmark timed these builds:
 
-## Raw results and details
+* **clean**: a build from nothing. For buck2, this doesn't include
+  `cabal buck2`, which took about 3 to 15 seconds.
+* **noop**: building again with nothing changed.
+* **hub-comment**: a comment added to a module that most of the project
+  imports. Nothing that imports it should have to compile again.
+* **hub-abi**: a new export added to the same module. Everything that
+  imports it compiles again.
+* **leaf**: a new definition added to a module that nothing imports.
 
-### Clean build
+![Build times for the Cabal project](https://raw.githubusercontent.com/simonmar/cabal-buck2/refs/heads/master/perf/cabal.svg)
 
-* Optimised:
-  * Default Cabal build: **280s**
-    * `cabal build all --enable-tests --enable-benchmarks -j`
-  * Buck2 build (opt mode, including `cabal buck2`): **259s**
-    * `cabal buck2 --enable-tests --enable-benchmarks && buck2 build //... -m opt`
-    * Not much difference here, as we expect.
+![Build times for haskell-language-server](https://raw.githubusercontent.com/simonmar/cabal-buck2/refs/heads/master/perf/hls.svg)
 
-* Unoptimised / dynamic:
-  * Cabal build with -O0 -dynamic: **136s**
-    * `cabal build all --enable-tests --enable-benchmarks -j --disable-optimisation --enable-executable-dynamic`
-  * Buck2 build (dev mode, including `cabal buck2`): **78s**
-    * `cabal buck2 --enable-tests --enable-benchmarks && buck2 build //... -m dev`
-    * Cabal is using `-dynamic-too` for libraries, while Buck2 is building everything purely dynamic.
+![Build times for amazonka](https://raw.githubusercontent.com/simonmar/cabal-buck2/refs/heads/master/perf/amazonka.svg)
 
-### Edit + rebuild
+What the results show:
 
-Next I made a single edit (added an extension to
-`Language.Haskell.Extension`) and rebuilt everything:
+* Per-module buck2 is the fastest of the three ways that build
+  everything, in every scenario but one. The exception is the Cabal
+  project's leaf edit, where both buck2 builds take a fraction of a
+  second. Per-module buck2 does best on haskell-language-server,
+  whose long chain of libraries is where compiling module by module lets
+  a library start before the libraries it depends on are finished.
+* amazonka is buck2's worst case. It has a few large packages, and cabal
+  already compiles the modules of each package in parallel with `-jsem`.
+  Per-module buck2 does about the same work as cabal there, but keeps
+  more CPUs busy, so it is ahead by 10-15% on clean and hub-abi.
+  Per-component buck2 is slower than cabal on amazonka's clean build,
+  because `ghc --make` compiles a component's modules one at a time.
+* cabal's noop and hub-comment times on haskell-language-server are
+  mostly its fixed cost for each of the project's ~70 components, since
+  only one module changes.
 
-* Optimised:
-  * Cabal: **197s**
-  * Buck2: **179s**
+Details of the measurements:
 
-* Unoptimised / dynamic:
-  * Cabal: **85s**
-  * Buck2: **55s**
+* They were made on a laptop with an 8-core AMD Ryzen 7 7840U and 60 GB
+  of memory, with GHC 9.12.4, cabal-install 3.18.1.0, buck2 2026-10-14
+  and an earlier version of the 0.6.0.0 support code. The projects'
+  `.cabal` files were patched to use `x-buck2-run-tool-depends` and
+  `x-buck2-splice-depends` (see [Customising the
+  build](#customising-the-build)) where appropriate.
+* The dependencies of each project were built first and shared by all
+  the ways, so their build isn't timed.
+* The scenarios that take seconds (noop, hub-comment and leaf) ran three
+  times, and the charts show the median. clean and hub-abi ran once,
+  since they vary by only a few percent from run to run. The exception
+  is amazonka's hub-abi, which varied a lot with the laptop's clock speed:
+  cabal took between 167s and 246s for the same work. Its cabal and
+  per-module times are the mean of two runs of each.
+* The repl times for haskell-language-server and the Cabal project come
+  from a later run. Five of haskell-language-server's 74 components are
+  left out of its repl, because they run an executable of the project as
+  a build tool, and a multi-repl can't build that executable while it
+  loads the executable's library.
 
+<details>
+<summary>The results as tables (wall-clock seconds)</summary>
+
+The Cabal project:
+
+| | cabal | buck2, per component | buck2, per module | cabal repl |
+|---|---|---|---|---|
+| `cabal buck2` | | 4.5 | 2.7 | |
+| clean | 108.6 | 90.9 | 70.0 | 39.7 |
+| noop | 2.8 | 0.0 | 0.0 | 0.9 |
+| hub-comment | 22.7 | 7.0 | 2.4 | 1.7 |
+| hub-abi | 47.3 | 30.5 | 20.2 | 5.7 |
+| leaf | 5.9 | 0.2 | 0.3 | 0.9 |
+
+haskell-language-server:
+
+| | cabal | buck2, per component | buck2, per module | cabal repl |
+|---|---|---|---|---|
+| `cabal buck2` | | 14.9 | 15.2 | |
+| clean | 255.4 | 95.3 | 71.3 | 73.5 |
+| noop | 16.1 | 0.0 | 0.0 | 3.6 |
+| hub-comment | 116.4 | 13.1 | 3.1 | 4.6 |
+| hub-abi | 212.8 | 62.9 | 45.6 | 8.0 |
+| leaf | 23.0 | 2.8 | 1.1 | 3.5 |
+
+amazonka:
+
+| | cabal | buck2, per component | buck2, per module | cabal repl |
+|---|---|---|---|---|
+| `cabal buck2` | | 5.7 | 5.6 | |
+| clean | 139.5 | 182.2 | 118.0 | 89.6 |
+| noop | 3.3 | 0.0 | 0.0 | 1.6 |
+| hub-comment | 17.9 | 9.4 | 2.4 | 1.7 |
+| hub-abi | 246.0 | 238.6 | 217.5 | 69.7 |
+| leaf | 6.9 | 0.5 | 0.4 | 1.6 |
+
+</details>
+
 # Limitations
 
 ## It's an external command, not builtin to `cabal-install`
@@ -393,15 +644,6 @@
   `cabal-install` library that `cabal-buck2` was built against. Try to
   make sure they match, or confusion will undoubtedly ensue.
 
-## Builds currently use `--make`
-
-The current Buck2 prelude uses `ghc --make` to build each component
-(library, executable). Ideally we should expose the full per-module
-dependencies to Buck2 so that it can exploit parallelism across
-packages for faster builds/rebuilds. It's entirely possible to do
-this, indeed the functionality already exists in [Tweag's Haskell/Buck2
-integration](https://github.com/tweag/buck2-haskell).
-
 ## Custom build type
 
 Build-type `Custom` isn't supported, and can't be in general, so
@@ -477,10 +719,12 @@
 
 # Acknowledgments
 
+Thanks to [Michael Peyton-Lebed](https://github.com/michaelpj) who added support for per-module compilation and the worker, and many other improvements.
+
 Most of the code and modifications to the standard Buck2 prelude were
-developed with the help of Claude Code using Claude Sonnet 5/5.5.
+developed with the help of Claude Code.
 
-The Haskell support already in the Buck2 prelude was developed by Meta
+The Haskell support in the Buck2 prelude was originally developed by Meta
 and is in production use internally for building
 [Glean](https://glean.software). This project just fixes a few things
 and adds some functionality needed to support building Cabal projects.
diff --git a/buck2/BUCK b/buck2/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/BUCK
@@ -0,0 +1,10 @@
+# Shared helpers used by rules in haskell.bzl - kept in their own BUCK
+# file (rather than folded into an existing one) since they're not
+# specific to any one package, just infrastructure haskell_test() itself
+# depends on.
+
+sh_binary(
+    name = "run_test",
+    main = "run_test.sh",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/LICENSE b/buck2/LICENSE
new file mode 100644
--- /dev/null
+++ b/buck2/LICENSE
@@ -0,0 +1,30 @@
+Copyright (c) 2026, Simon Marlow
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+    * Redistributions in binary form must reproduce the above
+      copyright notice, this list of conditions and the following
+      disclaimer in the documentation and/or other materials provided
+      with the distribution.
+
+    * Neither the name of Simon Marlow nor the names of other
+      contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/buck2/README.md b/buck2/README.md
new file mode 100644
--- /dev/null
+++ b/buck2/README.md
@@ -0,0 +1,229 @@
+# Buck2 prelude for Haskell projects
+
+This is a version of the [Buck2
+prelude](https://github.com/facebook/buck2/tree/main/prelude) with a
+few tweaks (that will hopefully be upstreamed at some point) and some
+support code for building Haskell projects.
+
+You probably don't want this by itself---instead take a look at
+[cabal-buck2](https://hackage.haskell.org/package/cabal-buck2) which
+extends `cabal` with a `buck2` command so that you can use Buck2 as
+the build tool for your Cabal project.
+
+# Build modes
+
+The Buck2 build system has two build modes:
+
+  * `dev`: the default, builds everything with `-O0` and dynamic linking. This is intended to give you the quickest edit-compile-test turnaround.
+  * `opt`: enable `-O` and link statically. This takes longer but the code runs faster.
+
+To build with `opt`, use `-m opt`, e.g.
+
+```
+buck2 build my-package:my-program -m opt
+```
+
+There are other build options that can be selected in a similar way, such as `-m prof` to enable profiling. See `constraints/BUCK` for details.
+
+# Checking without linking
+
+`buck2 build my-package:my-program[interfaces]` compiles a target without
+linking it, which is enough to see its type errors.
+
+# Documentation
+
+`haskell_haddock` builds the haddock for libraries libraries. A library compiled 
+with `-haddock` (in its `compiler_flags` or the toolchain's) will build the documentation 
+from the interfaces on GHC 9.12+, which is more efficient.
+
+# Warnings
+
+buck2 shows warnings only when it runs a compilation action, and not
+when it finds the result in a cache. `buck2 build
+my-package:my-program[diagnostics.txt] --out -` prints all the diagnostics 
+from compiling a target's modules, whether they were compiled in this build or not. 
+
+Only targets compiled with `compile_granularity = "module"` have
+`[diagnostics.txt]`. A target compiled with `--make` compiles only the
+modules that changed, so its diagnostics would be incomplete, and in no
+fixed order.
+
+# Splice dependencies
+
+A Template Haskell splice, quasiquote or `ANN` pragma needs the linked libraries
+of dependencies that it uses. A target must list the local dependencies that it uses 
+in this way in `splice_depends`. The default, an empty list, means that they use none. 
+A splice that runs code of the target's own modules also uses the libraries that
+those modules use, so they must be listed too.
+
+# Per-module compilation (experimental)
+
+By default each `haskell_library()`/`haskell_binary()` is compiled by one
+`ghc --make` action. With `compile_granularity = "module"`, each module is
+compiled by an action of its own. That means that `buck2` can compile a target's
+modules in parallel with everything else it has to do, and rebuilds can
+be more minimal. Notably the dependency graph is cross-package, so modules
+in later packages can start compiling as soon as the specific modules they
+depend on are done, without having to wait for the full package.
+
+To change the default granulariy, set `compile_granularity` in the `[haskell]` 
+section of the buckconfig. This can still be overridden by each target.
+
+Per-module compilation is only tested on Linux.
+
+The main thing that still leads to suboptimal dependency graphs is Template
+Haskell. A module that runs Template Haskell waits for the libraries that
+its target lists in `splice_depends` (see above) to be linked.
+The target's other modules don't wait for them. A splice that runs code of
+a local library that isn't listed fails to compile, saying so. (The
+persistent worker doesn't always catch it. See "Known issues" in
+`prelude/haskell/tools/worker/README.md`.)
+
+On GHC 9.14, a module that uses `ExplicitLevelImports` narrows its target's
+list further, to the dependencies that its `import splice`s come through.
+
+`per_module` is often much faster at rebuilds:
+
+- With `--make`, an edit to any module rebuilds its whole target from
+  scratch, and then the targets that depend on it, since even a comment
+  changes the target's interfaces.
+- With `per_module`, buck2 compiles the edited module, and then only the
+  modules whose imports' ABI changed. After a comment, that's just the
+  edited module. After a new definition, it's that module and the modules
+  that import it.
+
+How much this saves depends on the module structure. It saves the most for
+edits low in the module graph, in large targets, or in targets that much
+else depends on, and the least for edits to a small target that nothing
+depends on. On the worker's bench, rebuilds after such edits took 0.7-1.2s
+with `per_module` and the worker, against 2-9s with `--make` per target
+(see `prelude/haskell/tools/worker/DESIGN.md`).
+
+The main cost of `per_module` is CPU on clean builds. Without the
+persistent worker (below), each module's compile starts a GHC and reads the
+interfaces of its imports, which `--make` does once per target, so a clean
+build takes several times as long. Rebuilds pay that cost only for the
+modules they compile, so they are mostly faster than with `--make` even
+without the worker.
+
+The persistent worker in `prelude/haskell/tools/worker` removes most of that cost by
+sending the compiles to a long-running process that keeps what it has
+read, so a module's imports are read once rather than once per module.
+With it, clean builds on the bench were as fast as with a `--make` per
+target or faster, and much faster where `--make` per target can't use all
+the cores, as in a chain of libraries that each depend on the one before.
+
+`per_module_worker` in the `[haskell]` section of the buckconfig says
+whether to use the worker:
+
+- `builtin`, the default: the toolchain builds the worker with the
+  project's GHC.
+- `none`: no worker.
+
+The worker compiles every module except those that may run one of their
+target's build tools, which are compiled by their own `ghc -c`. Those are
+the modules that GHC runs a build tool for, such as a preprocessor named
+by `-F -pgmF`, and, in a target with build tools, the modules that run
+Template Haskell.
+
+The same section has options for the worker that the targets share:
+
+- `per_module_worker_rts_options`: its RTS options (`-A64m -n4m -qn8 -I5`
+  by default, see the worker's README).
+- `per_module_worker_sessions`: the most sessions it keeps. This bounds its
+  memory only with `make` sessions (see the worker's README).
+- `per_module_worker_session_mode`: how its sessions compile. `auto` is the
+  default, and `make` turns off sharing interfaces between targets (see
+  `prelude/haskell/per_module_worker.bzl`).
+
+The recompilation check used by `per_module` is also currently slightly coarser
+than GHC's, in that GHC also looks at which definitions from a dependency are
+used by a module. We don't do this currently but we could do in future.
+
+With `per_module`, `[interfaces]` (above) doesn't link the target's
+dependencies either, because a module's compile needs only the interfaces of
+its imports.
+
+# Advice
+
+The rules can spot some ways of declaring a target that
+build correctly but slowly, and can report them as advice. 
+To see what there is to act on, run:
+
+```
+cat $(buck2 bxl prelude//haskell/advice.bxl:main -- --targets //...)
+```
+
+The report has a section for each check that found something: what the
+check looks for and what to do about it, then a line for each target that
+it found something in. Checks and targets with nothing to report are left
+out. The report is made from the checks' results alone, so any validation
+whose result has `findings` gets a section too. For example:
+
+```
+haskell_modules_outside_worker (1 target)
+  Modules that compile without the persistent worker, which is slower. A module compiles outside it if it may run build tools (tools), or if its splices may read data files (data_dirs). A module that runs Template Haskell (template_haskell) is assumed to run any of its target's build tools.
+  root//build-tools:own: BT.Own (runs bt-own); BT.OwnSplice (may run bt-own)
+
+haskell_unused_build_tools (2 targets)
+  Build tools that no module's compile runs, though where the target has Template Haskell splices (splices), a splice might. Remove them from build_tool_depends, or, for a program that runs them, move them to run_tool_depends.
+  root//build-tools:unused: bt-copy
+  root//build-tools:unused-splice: bt-copy (unless a splice runs them)
+```
+
+The script builds the targets first if they haven't been built.
+
+For tools, the prelude's `validation/audit_results.bxl` gives the path of
+each check's result, a JSON file whose `data` has a list of `findings`, a
+`message` that sums them up, and an `explanation` of what the check looks
+for and what the findings' fields mean (`buck2 bxl prelude//validation/audit_results.bxl:main --
+--targets //...`; `--take NAME` picks out one check). The checks are:
+
+- `haskell_unused_build_tools`: build tools that are not used by any module's 
+  compilation. If the program uses them at runtime, they belong in
+  `run_tool_depends`; otherwise they can go.
+- `haskell_template_haskell_from_flags`: the target's flags turn on
+  `TemplateHaskell` or `QuasiQuotes`, so every module must be compiled as
+  if it used Template Haskell.
+- `haskell_ann_pragmas`: modules that must be compiled as if they used
+  Template Haskell only because of `ANN` pragmas.
+- `haskell_modules_outside_worker`: modules which must be compiled outside the
+  persistent worker, and an explanation for why.
+
+# Compiler and linker flags from the environment
+
+buck2 runs every build action with a clean environment, so directories that
+a shell makes visible to the compiler and linker through variables such as
+`LIBRARY_PATH` or `CPATH` (a Nix or Homebrew shell, say) are not seen by GHC.
+Give them to the Haskell toolchain through the project's buckconfig instead,
+normally in a `.buckconfig.local` next to the `.buckconfig` at the root of
+the project (it is read in addition to `.buckconfig`, and is for files that
+don't belong in version control):
+
+```
+[haskell]
+  compiler_flags = -I/opt/homebrew/include
+  linker_flags = -L/opt/homebrew/lib -L/opt/zlib/lib
+```
+
+Both are space-separated lists of flags for every GHC invocation;
+`compiler_flags` go to each compile and `linker_flags` to each link.
+
+# Testing this repo
+
+This is the Buck2 support code for
+[cabal-buck2](https://github.com/simonmar/cabal-buck2), which includes it as a
+submodule (`buck2/`) and tests it, with an example project (`example/`:
+Template Haskell, hsc2hs, C++ via FFI and a Hackage dependency) and with its
+own build. Update the submodule there to test a change here.
+
+Some of the rules also have tests of their own, which don't rely
+on cabal-buck2 or Hackage: `tests/rules/run.sh GHC_BIN_DIR`, with `buck2` on
+`PATH`. See [tests/rules/README.md](tests/rules/README.md).
+
+With Nix, `nix flake check -L` runs those and the persistent worker's tests
+(`prelude/haskell/tools/worker`) with each GHC the worker supports, in parallel, and
+`nix develop .#ghc9141` (say) gives a shell with that GHC and cabal.
+
+`template/` has the `.buckconfig` and `PACKAGE` that `cabal buck2` copies to a
+project that doesn't have them.
diff --git a/buck2/alex_happy.bzl b/buck2/alex_happy.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/alex_happy.bzl
@@ -0,0 +1,51 @@
+# Rules for running alex and happy.
+#
+# Unlike hsc2hs, alex/happy don't ship with GHC - they're separate Hackage
+# packages. buck2/gen-haskell-prebuilt.py asks Cabal where it put them
+# (`cabal list-bin alex`/`happy`) and freezes the answer in
+# third-party/haskell/tools.bzl, the same "Cabal identifies/builds it,
+# buck2 just references the frozen result" approach third-party/haskell/BUCK
+# uses for library packages. Re-run that script to pick up a version bump.
+
+load("@third-party-haskell//:tools.bzl", "ALEX", "ALEX_DATA", "ALEX_DATA_ENV", "ALEX_TARGET", "HAPPY", "HAPPY_DATA", "HAPPY_DATA_ENV", "HAPPY_TARGET")
+
+# Either `tool`, a path to an executable that is installed, or `tool_dep`, an
+# executable that buck2 builds (when `cabal buck2 --source-deps` builds the
+# dependencies); then `data_dep` is where the tool finds its templates, which
+# it is told by an environment variable, `data_env`.
+def _run_tool_impl(ctx: AnalysisContext) -> list[Provider]:
+    out = ctx.actions.declare_output(ctx.attrs.out)
+    tool = ctx.attrs.tool_dep[RunInfo] if ctx.attrs.tool_dep else ctx.attrs.tool
+    env = {}
+    if ctx.attrs.data_dep:
+        env[ctx.attrs.data_env] = ctx.attrs.data_dep[DefaultInfo].default_outputs[0]
+    ctx.actions.run(
+        cmd_args(tool, ctx.attrs.flags, ctx.attrs.src, "-o", out.as_output()),
+        category = ctx.attrs.category,
+        env = env,
+    )
+    return [DefaultInfo(default_output = out)]
+
+_run_tool = rule(
+    impl = _run_tool_impl,
+    attrs = {
+        "category": attrs.string(),
+        "data_dep": attrs.option(attrs.dep(), default = None),
+        "data_env": attrs.option(attrs.string(), default = None),
+        "flags": attrs.list(attrs.string(), default = []),
+        "out": attrs.string(),
+        "src": attrs.source(),
+        "tool": attrs.string(),
+        "tool_dep": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+    },
+)
+
+# What Cabal passes for GHC: generate code that uses GHC's primitives.
+_ALEX_FLAGS = ["-g"]
+_HAPPY_FLAGS = ["-agc"]
+
+def alex(name, src, out, **kwargs):
+    _run_tool(name = name, src = src, out = out, tool = ALEX, tool_dep = ALEX_TARGET, data_dep = ALEX_DATA, data_env = ALEX_DATA_ENV, category = "alex", flags = _ALEX_FLAGS, **kwargs)
+
+def happy(name, src, out, **kwargs):
+    _run_tool(name = name, src = src, out = out, tool = HAPPY, tool_dep = HAPPY_TARGET, data_dep = HAPPY_DATA, data_env = HAPPY_DATA_ENV, category = "happy", flags = _HAPPY_FLAGS, **kwargs)
diff --git a/buck2/cabal.bzl b/buck2/cabal.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/cabal.bzl
@@ -0,0 +1,748 @@
+# Creates the buck2 rules for one Cabal package from a "build spec": a plain
+# dict describing the package's components as Cabal sees them, rather than as
+# buck2 rules. `cabal buck2` writes the spec (into the package's
+# BUCK.cabal.bzl); this file turns it into haskell_library()/haskell_binary()/
+# haskell_test() (and, for components with C/C++ sources, cxx_library() and
+# external_pkgconfig_library()) targets, so all of the buck2-specific
+# decisions - target labels, flag assembly, which wrapper to use - live here
+# and can be customised from a BUCK file (see cabal_targets()).
+#
+# Spec schema. Optional keys are omitted when empty.
+#
+#   {
+#     "cabal_buck2": str,                    # the release of cabal-buck2 that wrote this; see version.bzl
+#     "package": {"name": str, "version": str},   # where it lives: see PACKAGES, below
+#     "ghc_options": [str],                   # supplied by the project, not the .cabal file
+#     "data": {"dir": str, "files": [str]},   # the package's data-dir and data-files (patterns)
+#     "extra_source_files": [str],            # the package's extra-source-files (patterns)
+#     "components": [
+#       {
+#         "kind": "library" | "executable" | "test-suite" | "benchmark",
+#         "name": str,                        # also the buck2 target name
+#         "exe_name": str,                    # executables only: the file name, if not the target name
+#         "srcs": {module: src},              # src: package-relative path | {"autogen": name} | {"provided": True}
+#         "boot_srcs": {module: str},         # the .hs-boot file of each module that has one (package-relative)
+#         "main_is": src,                     # not for libraries; module "Main", or C/C++ (see _foreign_main)
+#         "ghc_options": [str], "cpp_options": [str],
+#         "language": str, "extensions": [str],
+#         "extra_libraries": [str],
+#         "ld_options": [str],                # ld-options as configured, so with pkgconfig-depends' other linker flags (-Wl,-rpath, say)
+#         "extra_lib_dirs": [str],            # where to find them: extra-lib-dirs as configured, so with pkgconfig-depends' directories
+#         "deps": [dep],                      # see below
+#         "reexports": [{"module": str, "original": str, "from": dep}],  # libraries only; no "from" for a module of the library itself
+#         "hidden_modules": [str],            # libraries only: the modules the package doesn't expose (other-modules)
+#         "build_tools": [tool],              # the tools needed to build it
+#         "run_tools": [tool],                # the tools it needs on PATH when it runs (not for libraries)
+#         "splice_depends": [dep],  # the libraries whose code its splices run, if known (see haskell_library's splice_depends); otherwise all of its deps
+#         "c_sources": [str], "cc_options": [str],
+#         "cxx_sources": [str], "cxx_options": [str],
+#         "cmm_sources": [str],
+#         "asm_sources": [str], "asm_options": [str],
+#         "include_dirs": [str], "pkgconfig": [str],
+#         "hsc_options": [str],               # defines for hsc2hs's C compiler (the platform)
+#         "install_includes": [install_include],  # libraries only: the headers that what is compiled against the library sees
+#         "exposed": bool,                    # False: the library's package isn't exposed (a library's)
+#         "generated_include_dirs": [str],    # headers that `./configure` generated (relative to the project root)
+#         "test_args": [str],                 # test-suites only
+#       },
+#     ],
+#   }
+#
+# An install_include is {"path": str, "src": str} for a header at that path
+# in the library's include directory, whose file in the package is "src".
+# One without "src" isn't in the package's sources. It is presumably among
+# the headers that `./configure` generated, which what is compiled against
+# the library finds in its generated_include_dirs.
+#
+# A tool is {"exe": str, "package": str} for an executable built by this
+# project, or {"exe": str, "external": True} for an installed one.
+#
+# An "autogen" src names a file generated next to the sources, in the
+# package's cabal-buck2/autogen directory. A dep is {"package": str} for a
+# package's main library, {"package": str, "library": str} for a named
+# sub-library.
+#
+# The spec says nothing about where packages are: that is in PACKAGES, which
+# `cabal buck2` writes for the whole project into cabal-buck2/packages.bzl at
+# the project root, and which maps the name of each package that the project
+# builds to its directory (relative to the root, "." for the root itself). A
+# dependency on one of those is a dependency on a target of this project,
+# anything else is a prebuilt package from @third-party-haskell. So a
+# package's spec is the same wherever in the project the package is, and in
+# whichever project: moving a package only changes packages.bzl. (All of the
+# packages are in the root cell.)
+#
+# DATA_PACKAGES, also in packages.bzl, says which data-files each package
+# needs. It maps the name of a package to the packages that have data-files,
+# out of that package itself and everything it depends on (directly or
+# indirectly) that the project builds. Each of those has a Paths_<pkg> module
+# that must be told where its data-files are (see _data_dirs).
+#
+# A project can customise the generated targets of its packages in a
+# cabal-buck2.bzl at its root, rather than in each package's BUCK file. This is
+# useful when a package's BUCK file isn't the project's to change (when the
+# package is a git submodule, for example). cabal-buck2.bzl can define either
+# or both of these, and packages.bzl passes them on:
+#
+# - OVERRIDES maps the name of a package to the overrides of its components,
+#   in the form that cabal_targets() takes them.
+# - DEFAULTS maps the name of a package, or "*" for every package, to defaults
+#   for its targets, in the form that cabal_targets() takes them. For example,
+#   this compiles every target of the project module by module:
+#
+#       DEFAULTS = {"*": {"*": {"compile_granularity": "module"}}}
+
+# This load has to come before the others: they load more from tools.bzl (the
+# fingerprints, the alex and happy targets...), which a tools.bzl written by
+# another release of cabal-buck2 doesn't have, and then all that buck2 says is
+# that a symbol is missing. This one is in every tools.bzl since 0.3.0.0, so
+# a tools.bzl from an earlier release fails here, on a symbol that says what
+# it is about, and an incompatible one is reported just below.
+load("@third-party-haskell//:tools.bzl", TOOLS_CABAL_BUCK2_VERSION = "CABAL_BUCK2_VERSION")
+load("//buck2:version.bzl", "CABAL_BUCK2_VERSION")
+load("//buck2:cmm.bzl", "cmm_library")
+load("//buck2:cxx.bzl", "cxx_binary", "cxx_library")
+load("//buck2:headers.bzl", "headers_of", "install_include_dir")
+load("//buck2:haskell.bzl", "haskell_binary", "haskell_library", "haskell_test")
+load("//buck2:variant.bzl", "variant")
+load("//cabal-buck2:packages.bzl", "DATA_PACKAGES", "DEFAULTS", "OVERRIDES", "PACKAGES")
+load("@prelude//paths.bzl", "paths")
+load("@prelude//third-party:pkgconfig.bzl", "external_pkgconfig_library")
+
+if TOOLS_CABAL_BUCK2_VERSION != CABAL_BUCK2_VERSION:
+    fail("\n".join([
+        "third-party/haskell was generated by cabal-buck2 {}, but buck2/ is for cabal-buck2 {}.".format(TOOLS_CABAL_BUCK2_VERSION, CABAL_BUCK2_VERSION),
+        "Re-run `cabal buck2` with cabal-buck2 {}, or switch buck2/ to the {} branch of".format(CABAL_BUCK2_VERSION, TOOLS_CABAL_BUCK2_VERSION),
+        "https://github.com/simonmar/haskell-buck2.",
+    ]))
+
+_DEFAULT_RULES = {
+    "library": haskell_library,
+    "executable": haskell_binary,
+    "benchmark": haskell_binary,
+    "test-suite": haskell_test,
+}
+
+def _nub(xs):
+    seen = {}
+    out = []
+    for x in xs:
+        if x not in seen:
+            seen[x] = True
+            out.append(x)
+    return out
+
+def _label(dir, name):
+    return "//" + ("" if dir == "." else dir) + ":" + name
+
+def _this_dir(spec):
+    # The directory of the package being generated. The BUCK file calling
+    # cabal_targets() has to be in it: if it isn't, packages.bzl is out of
+    # date (or this BUCK file was copied from elsewhere).
+    name = spec["package"]["name"]
+    dir = PACKAGES.get(name)
+    if dir == None:
+        fail("package {} isn't in cabal-buck2/packages.bzl (at the root of the project): re-run `cabal buck2`".format(name))
+    here = native.package_name()
+    if here != ("" if dir == "." else dir):
+        fail("package {} is in {} according to cabal-buck2/packages.bzl, but its BUCK file is in {}: re-run `cabal buck2`".format(name, dir, here or "."))
+    return dir
+
+def _third_party_label(name):
+    return "third-party-haskell//:" + name
+
+def _src(pkg_dir, src):
+    if type(src) == type({}):
+        autogen_dir = "cabal-buck2/autogen" if pkg_dir == "." else pkg_dir + "/cabal-buck2/autogen"
+        return _label(autogen_dir, src["autogen"])
+    return src
+
+def _provided(src):
+    return type(src) == type({}) and src.get("provided", False)
+
+# If the Cabal file has `main-is: foo.hs` and `ghc-options: -main-is
+# Foo`, then the only way we can know the module of `foo.hs` is by
+# groveling around in `ghc-options` looking for `-main-is`.
+# This is fragile, but I don't see a better way to do it.
+def _main_module(c):
+    # Note that we have to support `-main-is Mod`, `-main-is Mod.fn` and
+    # `-main-is fn` (the latter is ignored)
+    opts = c.get("ghc_options", [])
+    for i in range(len(opts) - 1):
+        if opts[i] == "-main-is" and opts[i + 1][0].isupper():
+            mod, _, last = opts[i + 1].rpartition(".")
+            return mod if mod and last[0].islower() else opts[i + 1]
+    return "Main"
+
+def _srcs(c, pkg_dir):
+    srcs = {}
+    if "main_is" in c:
+        srcs[_main_module(c)] = _src(pkg_dir, c["main_is"])
+    for module, src in c.get("srcs", {}).items():
+        if not _provided(src):
+            srcs[module] = _src(pkg_dir, src)
+    return srcs
+
+def _check_provided(spec, c, srcs):
+    # A "provided" module is one that the package's Setup.hs would have
+    # generated (`cabal buck2 --enable-custom-setup` doesn't run it), whose
+    # source the project gives instead, in the component's overrides.
+    missing = [m for m, src in c.get("srcs", {}).items() if _provided(src) and m not in srcs]
+    if missing:
+        fail("{}: the Setup.hs of package {} would generate {}, but it isn't run (--enable-custom-setup): give their sources in the component's overrides, e.g. overrides = {{\"{}\": {{\"srcs\": {{\"{}\": ...}}}}}}".format(
+            c["name"],
+            spec["package"]["name"],
+            ", ".join(missing),
+            c["name"],
+            missing[0],
+        ))
+
+def _include_flags(c, pkg_dir):
+    # The -I flags of the component's include directories (see
+    # _include_dirs()), which cabal_targets() made once for the component.
+    return c["_include_flags"]
+
+# The files in an include directory that a C preprocessor may include.
+_HEADER_PATTERNS = ["**/*.h", "**/*.hh", "**/*.hpp", "**/*.hxx", "**/*.inc"]
+
+def _include_dirs(c, pkg_dir):
+    # Returns the -I flags for the component's include directories, and for
+    # where a configure script put the headers it generated. GHC needs them
+    # for CPP and for the C stubs of foreign imports, and the component's C
+    # needs them too. They are only for the component's own compiles. What
+    # is compiled against a library sees its install-includes instead (see
+    # _install_include_dir()).
+    #
+    # Each include directory inside the package's directory becomes a
+    # filegroup of its headers, and its flag names the filegroup's directory
+    # with $(location). So the headers are inputs of every compile that has
+    # the flag, and buck2 compiles it again when one of them changes. The
+    # compiler also sees only those headers, so a compile that includes a
+    # file the filegroup doesn't have fails here, and not only on a remote
+    # executor.
+    #
+    # buck2 can only list the files of a package from its BUCK file, so an
+    # include directory elsewhere in the project (`../include`, say) and the
+    # directories of generated headers (in the build directory) are named by
+    # their paths from the project root, which is where the compilers run.
+    # Their headers aren't inputs. A directory outside the project
+    # (`/usr/include`, say) is the system's.
+    flags = []
+    for i, d in enumerate(c.get("include_dirs", [])):
+        d = paths.normalize(d)
+        if d.startswith("/"):
+            flags.append("-I" + d)
+            continue
+        if d == ".." or d.startswith("../"):
+            flags.append("-I" + paths.normalize(paths.join(pkg_dir, d)))
+            continue
+        prefix = "" if d == "." else d + "/"
+        name = "{}-include-{}".format(c["name"], i)
+        # The filegroup holds symlinks to the headers, not copies. A compile
+        # can reach a header both through the filegroup and by its path in
+        # the source tree: a C file includes a header next to it with
+        # `#include "foo.h"`, say. A header with `#pragma once` is skipped the
+        # second time only if both paths lead to the same file.
+        native.filegroup(
+            name = name,
+            srcs = {f[len(prefix):]: f for f in native.glob([prefix + p for p in _HEADER_PATTERNS])},
+            copy = False,
+            visibility = ["PUBLIC"],
+        )
+        flags.append("-I$(location :{})".format(name))
+    return _nub(flags + ["-I" + d for d in c.get("generated_include_dirs", [])])
+
+def _install_include_dir(c):
+    # Makes the library's include directory as Cabal installs it, with only
+    # its install-includes (see install_include_dir()), and returns its
+    # label. Returns None for a component without install-includes.
+    #
+    # The library depends on this target, which exports the directory to
+    # what is compiled against the library. So that code sees only the
+    # headers that the package installs, as it would see an installed
+    # package, and not the package's private headers. The library's own
+    # compiles have all of its include directories (see _include_dirs()).
+    install = c.get("install_includes", [])
+    if not install:
+        return None
+    name = c["name"] + "-install-include"
+    generated = [h for h in install if "src" not in h]
+    install_include_dir(
+        name = name,
+        srcs = {h["path"]: h["src"] for h in install if "src" in h},
+        exported_include_dirs = c.get("generated_include_dirs", []) if generated else [],
+        visibility = ["PUBLIC"],
+    )
+    return ":" + name
+
+def _this_unit_id(flags):
+    # The unit id that a package's options give its library, as those of a
+    # package that GHC knows by its unit id do (rts, ghc-internal).
+    unit_id = None
+    for i, flag in enumerate(flags):
+        if flag == "-this-unit-id" and i + 1 < len(flags):
+            unit_id = flags[i + 1]
+    return unit_id
+
+def _unit_id(spec, c, name):
+    """
+    The unit id of the library component `c` (named `name`) in the given
+    package spec.
+
+    The unit id is given by a `-this-unit-id` flag if there is one, or
+    otherwise the default Cabal unit id:
+        <package>-<version>-inplace[-<component>]
+    """
+    unit_id = _this_unit_id(list(c.get("ghc_options", [])) + list(spec.get("ghc_options", [])))
+    if unit_id:
+        return unit_id
+    package = spec["package"]
+    unit_id = package["name"] + ("-" + package["version"] if "version" in package else "") + "-inplace"
+    return unit_id if name == package["name"] else unit_id + "-" + name
+
+def cabal_unit_id(spec, name):
+    """
+    The unit id of the component `name` in the given package `spec`
+    """
+    c = [c for c in spec["components"] if c["kind"] == "library" and c["name"] == name][0]
+    return _unit_id(spec, c, name)
+
+def _lib_dir_flags(c, pkg_dir):
+    # Where the linker looks for the component's extra_libraries: its
+    # extra-lib-dirs, which Cabal has already extended with the directories
+    # of its pkgconfig-depends at configure time. Package-relative, like
+    # include_dirs, so made relative to the root of the project the same way.
+    dirs = [d if pkg_dir == "." or d.startswith("/") else pkg_dir + "/" + d for d in c.get("extra_lib_dirs", [])]
+    return _nub(["-L" + d for d in dirs])
+
+def _ld_flags(c):
+    # ld-options are for the linker itself: they reach it from GHC's command
+    # line with -optl.
+    return _nub(["-optl" + f for f in c.get("ld_options", [])])
+
+def _haskell_flags(c, pkg_dir, project_ghc_options):
+    # default-language isn't just documentation: GHC2021/GHC2024 each imply a
+    # bundle of extensions, so leaving it out would silently fall back to
+    # GHC's own default (Haskell2010). Project-supplied options come last, as
+    # in Cabal, so that they can override the component's own.
+    own = list(c.get("ghc_options", [])) + list(c.get("cpp_options", []))
+    if "language" in c:
+        own.append("-X" + c["language"])
+    own += ["-X" + e for e in c.get("extensions", [])]
+    own += _include_flags(c, pkg_dir)
+    return _nub(own) + project_ghc_options
+
+def _linker_flags(c, pkg_dir, project_ghc_options):
+    # haskell_binary and haskell_test pass compiler_flags to each module's
+    # compile step only, not to the final link, whereas Cabal gives a
+    # component's whole ghc-options to every ghc invocation. So anything
+    # link-relevant there (-threaded, -rtsopts) has to reach linker_flags
+    # too; compile-only flags like -Wall are ignored by ghc when linking.
+    own = _lib_dir_flags(c, pkg_dir) + ["-l" + l for l in c.get("extra_libraries", [])] + _ld_flags(c) + list(c.get("ghc_options", []))
+    return _nub(own) + project_ghc_options
+
+def _dep_label(d):
+    # A dependency's target: a library of this project, or an external
+    # package's main library or sub-library.
+    if d["package"] in PACKAGES:
+        return _label(PACKAGES[d["package"]], d.get("library", d["package"]))
+    if "library" in d:
+        # Libraries of different packages have the same names.
+        return _third_party_label(d["package"] + "--" + d["library"])
+    return _third_party_label(d["package"])
+
+def _classify_deps(deps):
+    # `packages` only ever resolves an external package's main library;
+    # everything else (local libraries, external sub-libraries) is a target
+    # label in `deps`.
+    packages = []
+    local = []
+    external_sublibs = []
+    for d in deps:
+        if d["package"] in PACKAGES:
+            local.append(_dep_label(d))
+        elif "library" in d:
+            external_sublibs.append(_dep_label(d))
+        else:
+            packages.append(d["package"])
+    return _nub(packages), _nub(local + external_sublibs)
+
+def _build_tool_depends(build_tools):
+    # Each tool becomes a real dependency that is put on PATH for this rule's
+    # compile actions and, for a test-suite, when the test runs.
+    labels = []
+    for t in build_tools:
+        if "package" in t:
+            labels.append(_label(PACKAGES[t["package"]], t["exe"]))
+        else:
+            labels.append(_third_party_label(t["exe"] + "-exe"))
+    return _nub(labels)
+
+def _pkgconfig_deps(c, pkgconfig_seen):
+    # The targets of the component's pkgconfig-depends, created by the first
+    # component of the package that has them.
+    pkgconfig = _nub(c.get("pkgconfig", []))
+    for p in pkgconfig:
+        if p not in pkgconfig_seen:
+            pkgconfig_seen[p] = True
+            external_pkgconfig_library(name = "pkgconfig-" + p, package = p, visibility = ["PUBLIC"])
+    return [":pkgconfig-" + p for p in pkgconfig]
+
+def _cxx_kwargs(c, pkgconfig_seen, srcs):
+    # The attributes of a C/C++ rule that compiles `srcs` with the
+    # component's options.
+    pkgconfig = _pkgconfig_deps(c, pkgconfig_seen)
+
+    kwargs = {"srcs": srcs, "visibility": ["PUBLIC"]}
+
+    # cc-options are for C and assembler (which GHC also gets the C compiler
+    # to preprocess), cxx-options for C++.
+    cc_options = _nub(c.get("cc_options", []))
+    lang_flags = {
+        "assembler_with_cpp": cc_options + _nub(c.get("asm_options", [])),
+        "c": cc_options,
+        "cxx": _nub(c.get("cxx_options", [])),
+    }
+    kwargs["lang_compiler_flags"] = {lang: flags for lang, flags in lang_flags.items() if flags}
+
+    kwargs["deps"] = pkgconfig
+
+    return kwargs
+
+_PROFILING_DEFINES = select({
+    "root//buck2/constraints:prof": ["-DPROFILING"],
+    "DEFAULT": [],
+})
+
+# To match GHC, we explicitly disable PIC for C compiles (except on
+# MacOS and Windows), in case gcc has it enabled by default. See GHC's
+# picCCOpts. When linking dynamically, the later -fPIC will override
+# this.
+_NO_PIC = select({
+    "config//os:macos": [],
+    "config//os:windows": [],
+    "DEFAULT": ["-fno-PIC"],
+})
+
+def _cxx_library(c, pkg_dir, pkgconfig_seen):
+    # Returns the labels the Haskell rule must additionally depend on.
+    srcs = list(c.get("c_sources", [])) + list(c.get("cxx_sources", [])) + list(c.get("asm_sources", []))
+    if not srcs:
+        return []
+    kwargs = _cxx_kwargs(c, pkgconfig_seen, srcs)
+    name = c["name"] + "-cxx"
+
+    # The C of a Haskell component is compiled as GHC would compile it,
+    # which includes its version header (defining __GLASGOW_HASKELL__) and
+    # makes available its own headers (HsFFI.h) and those of the packages
+    # the component depends on (HsUnixConfig.h, say), and defines PROFILING
+    # when it is profiled.
+    kwargs["compiler_flags"] = ["-include", "ghcversion.h"] + _PROFILING_DEFINES + _NO_PIC
+    packages, labels = _classify_deps(c.get("deps", []))
+    headers = name + "-headers"
+    headers_of(name = headers, deps = _nub([_third_party_label(p) for p in ["rts"] + packages] + labels))
+    kwargs["deps"] = [":" + headers] + kwargs["deps"]
+
+    # The component's include directories are for its own C. What depends on
+    # a library sees its install-includes.
+    include_flags = _include_flags(c, pkg_dir)
+    if include_flags:
+        kwargs["preprocessor_flags"] = include_flags
+    # Like the C of a Cabal package, it is all part of the library of the
+    # component's Haskell code (see `internal_deps` of haskell_library()):
+    # the RTS's C, say, calls hidden functions of its Cmm, which only resolve
+    # within one shared library.
+    kwargs["preferred_linkage"] = "static"
+    kwargs["link_whole"] = True
+    kwargs["use_archive"] = False
+    cxx_library(name = name, **kwargs)
+    return [":" + name]
+
+# The extensions by which Cabal recognises a C or C++ main-is.
+_FOREIGN_MAIN_EXTENSIONS = [".c", ".cpp", ".cxx", ".c++"]
+
+def _foreign_main(c):
+    main = c.get("main_is")
+    return type(main) == type("") and paths.split_extension(main)[1] in _FOREIGN_MAIN_EXTENSIONS
+
+def _cxx_binary(c, pkg_dir, pkgconfig_seen, overrides):
+    # A component whose main-is is C/C++ (as some of GHC's own tools are) is
+    # built as a plain C/C++ program. Cabal would compile it with GHC, which
+    # makes GHC's headers and those of the component's Haskell dependencies
+    # available, and link it with GHC, which links in the RTS. Neither is of
+    # any use to a program without Haskell code in it (which isn't supported
+    # here), so its dependencies on external Haskell packages (base, say)
+    # are ignored.
+    unsupported = []
+    if c["kind"] not in ("executable", "benchmark"):
+        unsupported.append("a " + c["kind"])
+    if c.get("srcs"):
+        unsupported.append("Haskell modules")
+    if c.get("cmm_sources"):
+        unsupported.append("Cmm sources")
+    _, local_deps = _classify_deps(c.get("deps", []))
+    if local_deps:
+        unsupported.append("dependencies on Haskell libraries")
+    if unsupported:
+        fail("{}: a C/C++ main-is ({}) is only supported in an executable without {}".format(
+            c["name"],
+            c["main_is"],
+            " or ".join(unsupported),
+        ))
+    srcs = [c["main_is"]] + list(c.get("c_sources", [])) + list(c.get("cxx_sources", [])) + list(c.get("asm_sources", []))
+    kwargs = _cxx_kwargs(c, pkgconfig_seen, srcs)
+    kwargs["name"] = c["name"]
+    if "exe_name" in c:
+        kwargs["executable_name"] = c["exe_name"]
+    include_flags = _include_flags(c, pkg_dir)
+    if include_flags:
+        kwargs["preprocessor_flags"] = include_flags
+    linker_flags = _lib_dir_flags(c, pkg_dir) + ["-l" + l for l in c.get("extra_libraries", [])] + c.get("ld_options", [])
+    if linker_flags:
+        kwargs["linker_flags"] = _nub(linker_flags)
+    cxx_binary(**_merge(kwargs, overrides))
+
+def _cmm_library(c, spec):
+    # GHC compiles Cmm, given the component's options as for Haskell.
+    if not c.get("cmm_sources"):
+        return []
+    pkg_dir = _this_dir(spec)
+    name = c["name"] + "-cmm"
+    cmm_library(
+        name = name,
+        srcs = list(c["cmm_sources"]),
+        flags = _haskell_flags(c, pkg_dir, list(spec.get("ghc_options", []))),
+        visibility = ["PUBLIC"],
+    )
+    return [":" + name]
+
+def _profiled(label):
+    # `label` (a target of this package) built for profiling.
+    name = label.removeprefix(":") + "-prof"
+    variant(name = name, actual = label, transition = "root//buck2/constraints:to-prof", visibility = ["PUBLIC"])
+    return ":" + name
+
+def _data_dirs(c, spec):
+    # The data_dirs of a component: for each package whose data-files its code
+    # may read, the <pkg>_datadir environment variable that the package's
+    # Paths_<pkg> module looks at, mapped to the package's -data target. This
+    # is what `cabal build` and `cabal run` do too.
+    #
+    # Only packages that the project builds are included. A prebuilt package
+    # from the store has its data-files installed where its Paths_<pkg> module
+    # already expects to find them.
+    #
+    # The data-files of the component's build tools (alex and happy read their
+    # templates this way) are included too. The compile runs a build tool's
+    # binary directly, not through the wrapper script that a haskell_binary
+    # with data_dirs gets for `buck2 run`, so the compile has to set the tool's
+    # variables itself.
+    packages = DATA_PACKAGES.get(spec["package"]["name"], [])
+    for tool in c.get("build_tools", []):
+        if "package" in tool:
+            packages = packages + DATA_PACKAGES.get(tool["package"], [])
+    return {p.replace("-", "_") + "_datadir": _label(PACKAGES[p], p + "-data") for p in packages}
+
+def _haskell_kwargs(c, spec, helpers):
+    # `helpers` are the rules of the component's C/C++/Cmm code.
+    pkg_dir = _this_dir(spec)
+    project_ghc_options = list(spec.get("ghc_options", []))
+    kind = c["kind"]
+    packages, deps = _classify_deps(c.get("deps", []))
+    kwargs = {
+        "name": c["name"],
+        "srcs": _srcs(c, pkg_dir),
+        "boot_srcs": dict(c.get("boot_srcs", {})),
+        "cabal_component": (pkg_dir, c["name"]),
+    }
+    if "exe_name" in c:
+        kwargs["exe_name"] = c["exe_name"]
+    data_dirs = _data_dirs(c, spec)
+    if data_dirs:
+        kwargs["data_dirs"] = data_dirs
+    if kind == "test-suite":
+        kwargs["cwd"] = pkg_dir
+        if c.get("test_args"):
+            kwargs["test_args"] = list(c["test_args"])
+    compiler_flags = _haskell_flags(c, pkg_dir, project_ghc_options)
+    hsc_flags = ["--cflag=" + f for f in c.get("hsc_options", []) + c.get("cc_options", []) + _include_flags(c, pkg_dir)]
+    if hsc_flags:
+        kwargs["hsc_flags"] = hsc_flags
+
+    # hsc2hs compiles C, as in Cabal, unless there is C++ in the component.
+    kwargs["hsc_cxx"] = bool(c.get("cxx_sources") or c.get("cxx_options"))
+    if compiler_flags:
+        kwargs["compiler_flags"] = compiler_flags
+    if kind == "library":
+        kwargs["package_name"] = spec["package"]["name"]
+        if "version" in spec["package"]:
+            kwargs["package_version"] = spec["package"]["version"]
+        kwargs["unit_id"] = _unit_id(spec, c, c["name"])
+        # The code of the helpers is part of the library, as in Cabal, which
+        # compiles it for each way: for the profiled library, as built for
+        # profiling.
+        if helpers:
+            kwargs["internal_deps"] = helpers
+            kwargs["prof_internal_deps"] = [_profiled(h) for h in helpers]
+        kwargs["exposed"] = c.get("exposed", True)
+        if c.get("hidden_modules"):
+            kwargs["hidden_modules"] = list(c["hidden_modules"])
+        if c.get("_install_include_dir"):
+            deps = deps + [c["_install_include_dir"]]
+        if c.get("reexports"):
+            kwargs["reexported_modules"] = {r["module"]: (_dep_label(r["from"]) if "from" in r else None, r["original"]) for r in c["reexports"]}
+        lib_dirs = _lib_dir_flags(c, pkg_dir)
+        # Raw flags: the link of whatever depends on the library hands these
+        # to the linker itself (as -optl) already.
+        exported = _nub(lib_dirs + ["-l" + l for l in c.get("extra_libraries", [])] + c.get("ld_options", []))
+        if exported:
+            kwargs["exported_linker_flags"] = exported
+        # The library's own shared object must link against them too, not
+        # only whatever finally links the library in: GHC loads the .so to
+        # run Template Haskell splices in dependents, and that fails on any
+        # symbol it leaves unresolved. (ld_options reach GHC's command line
+        # with -optl here, unlike the raw flags that dependents are given.)
+        own_link = lib_dirs + ["-l" + l for l in c.get("extra_libraries", [])] + _ld_flags(c)
+        if own_link:
+            kwargs["linker_flags"] = _nub(own_link)
+    else:
+        deps = deps + helpers
+        linker_flags = _linker_flags(c, pkg_dir, project_ghc_options)
+        if linker_flags:
+            kwargs["linker_flags"] = linker_flags
+    if packages:
+        kwargs["packages"] = packages
+    if deps:
+        kwargs["deps"] = deps
+    build_tool_depends = _build_tool_depends(c.get("build_tools", []))
+    if build_tool_depends:
+        kwargs["build_tool_depends"] = build_tool_depends
+
+    run_tool_depends = _build_tool_depends(c.get("run_tools", []))
+    if run_tool_depends:
+        kwargs["run_tool_depends"] = run_tool_depends
+
+    # Cabal lets a component's splices run code from any of its
+    # build-depends. So if the spec doesn't give the list, every dependency
+    # is listed. A list in the spec, even an empty one, is used as it is.
+    th_deps = c["splice_depends"] if "splice_depends" in c else c.get("deps", [])
+    kwargs["splice_depends"] = [_dep_label(d) for d in th_deps]
+    if kind != "test-suite":
+        kwargs["visibility"] = ["PUBLIC"]
+    return kwargs
+
+_LIST_TYPES = (type([]), type(select({"DEFAULT": []})))
+
+def _merge(base, extra):
+    # Lists (or selects of them) are appended to, dicts are merged, anything
+    # else is replaced.
+    out = dict(base)
+    for k, v in extra.items():
+        cur = out.get(k)
+        if type(v) in _LIST_TYPES and type(cur) in _LIST_TYPES:
+            out[k] = cur + v
+        elif type(v) == type({}) and type(cur) == type({}):
+            merged = dict(cur)
+            merged.update(v)
+            out[k] = merged
+        else:
+            out[k] = v
+    return out
+
+def cabal_targets(spec, defaults = {}, overrides = {}, transform = None, rules = {}):
+    """Create the targets described by a build spec.
+
+    Args:
+      spec: the package's build spec (see the top of this file).
+      defaults: extra attributes for every target of a kind, keyed by kind
+          ("library", "executable", "test-suite", "benchmark"), or "*" for all
+          of them. The project's own defaults (DEFAULTS["*"] and
+          DEFAULTS[package] in its cabal-buck2.bzl, if it has one) come
+          before these.
+      overrides: extra attributes for individual components, keyed by
+          component name. The project's own overrides of the package's
+          components (OVERRIDES[package] in its cabal-buck2.bzl, if it has
+          one) come before these.
+      transform: if given, called as transform(kind, component, attrs) with
+          each target's final attributes (the Haskell rule's, not the C/C++
+          helper's), and returns the attributes to use instead - or None to
+          not create the target at all.
+      rules: replacement rule functions to call instead of the defaults,
+          keyed by kind.
+
+    Extra attributes are merged into the generated ones: lists are appended
+    to, dicts merged, anything else replaced. Later sources win. The order is:
+    the project's defaults for every package, then its defaults for this
+    package, then `defaults`, then the project's overrides of the component,
+    then `overrides`, then transform. Within each set of defaults, those for
+    "*" come before those for the kind.
+    An executable whose main-is is C/C++ is a cxx_binary() (see
+    _cxx_binary()), to which only its overrides apply: defaults, transform
+    and rules are for the Haskell rules.
+    """
+    generated_by = spec.get("cabal_buck2")
+    if generated_by != CABAL_BUCK2_VERSION:
+        generator = "cabal-buck2 " + generated_by if generated_by else "an earlier release of cabal-buck2 (0.1.0.0)"
+        fail("\n".join([
+            "This was generated by {}, but buck2/ is for cabal-buck2 {}.".format(generator, CABAL_BUCK2_VERSION),
+            "Re-run `cabal buck2` with cabal-buck2 {}, or switch buck2/ to the {} branch of".format(CABAL_BUCK2_VERSION, generated_by or "0.1.0.0"),
+            "https://github.com/simonmar/haskell-buck2.",
+        ]))
+    pkg_dir = _this_dir(spec)
+    project_overrides = OVERRIDES.get(spec["package"]["name"], {})
+    all_defaults = [DEFAULTS.get("*", {}), DEFAULTS.get(spec["package"]["name"], {}), defaults]
+    pkgconfig_seen = {}
+    for c in spec["components"]:
+        c = dict(c, _include_flags = _include_dirs(c, pkg_dir), _install_include_dir = _install_include_dir(c))
+        if _foreign_main(c):
+            _cxx_binary(c, pkg_dir, pkgconfig_seen, _merge(project_overrides.get(c["name"], {}), overrides.get(c["name"], {})))
+            continue
+        kind = c["kind"]
+        helpers = _cxx_library(c, pkg_dir, pkgconfig_seen) + _cmm_library(c, spec)
+        kwargs = _haskell_kwargs(c, spec, helpers)
+
+        # The helpers' own dependencies are linked with the component's.
+        kwargs["deps"] = kwargs.get("deps", []) + _pkgconfig_deps(c, pkgconfig_seen)
+        for d in all_defaults:
+            kwargs = _merge(kwargs, d.get("*", {}))
+            kwargs = _merge(kwargs, d.get(kind, {}))
+        kwargs = _merge(kwargs, project_overrides.get(c["name"], {}))
+        kwargs = _merge(kwargs, overrides.get(c["name"], {}))
+        if transform:
+            kwargs = transform(kind, c, kwargs)
+            if kwargs == None:
+                continue
+        _check_provided(spec, c, kwargs.get("srcs", {}))
+        rules.get(kind, _DEFAULT_RULES[kind])(**kwargs)
+    _data_files(spec, pkg_dir)
+    _extra_source_files(spec)
+
+def _data_files(spec, pkg_dir):
+    # A target <package>-data for the package's data-files: a directory laid
+    # out like the package's data-dir, so that a file is at the same relative
+    # path as in the package's source. The package's code finds the directory
+    # through its <package>_datadir environment variable, whether it reads the
+    # files at build time or when it runs (see _data_dirs).
+    data = spec.get("data")
+    if not data:
+        return
+    prefix = "" if data["dir"] in ("", ".") else data["dir"].rstrip("/") + "/"
+    files = native.glob([prefix + pattern for pattern in data["files"]])
+    native.filegroup(
+        name = spec["package"]["name"] + "-data",
+        srcs = {f[len(prefix):]: f for f in files},
+        visibility = ["PUBLIC"],
+    )
+
+def _extra_source_files(spec):
+    # The package's extra-source-files, as a directory laid out like the
+    # package, for whatever else in the project needs them: a generator of
+    # its sources, say.
+    patterns = spec.get("extra_source_files")
+    if not patterns:
+        return
+    native.filegroup(
+        name = spec["package"]["name"] + "-extra-source-files",
+        srcs = native.glob(patterns),
+        visibility = ["PUBLIC"],
+    )
diff --git a/buck2/cfg_constructor_if_standalone.bzl b/buck2/cfg_constructor_if_standalone.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/cfg_constructor_if_standalone.bzl
@@ -0,0 +1,67 @@
+# A PACKAGE file (unlike a BUCK/.bzl file) can only contain a flat
+# sequence of top-level calls - no `if`/`def` allowed directly in it
+# ("if cannot be used outside def", then "def is not allowed in this
+# dialect" once wrapped - both confirmed directly). The conditional logic
+# hsthrift/PACKAGE needs (call set_cfg_constructor() only when this
+# checkout is genuinely standalone - see that file's own comment) has to
+# live in a real .bzl file instead, called as a single top-level
+# statement from the PACKAGE file itself.
+#
+# set_cfg_modifiers() itself can't be wrapped the same way, though -
+# unlike set_cfg_constructor() (a builtin, no such restriction), it's a
+# plain prelude .bzl function that inspects its *immediate* caller's own
+# module path (_is_buck_tree_file(), buck2/prelude/cfg/modifier/
+# set_cfg_modifiers.bzl) and requires it to literally end in "/PACKAGE" -
+# confirmed directly (its own docstring claims "or a bzl file
+# transitively loaded by a PACKAGE file" is also fine, but that isn't
+# what the check actually does). Calling it from inside this file's own
+# cfg_constructor_if_standalone() - one frame removed from PACKAGE -
+# fails that check even though PACKAGE is what ultimately triggered it.
+# So PACKAGE has to call set_cfg_modifiers() itself, directly - the
+# standalone-or-not decision instead has to be *returned* from a helper
+# here (dev_modifiers_if_standalone(), below) rather than guarding the
+# call itself.
+load(
+    "@prelude//cfg/modifier/cfg_constructor.bzl",
+    "cfg_constructor_post_constraint_analysis",
+    "cfg_constructor_pre_constraint_analysis",
+)
+load("@prelude//cfg/modifier/common.bzl", "MODIFIER_METADATA_KEY")
+
+def cfg_constructor_if_standalone():
+    # get_base_path() gives the directory of *this* PACKAGE file, relative
+    # to the root - "" when this is the project's own root PACKAGE file
+    # (genuinely standalone), or e.g. "hsthrift" when this checkout is a
+    # subdirectory of another project.
+    if get_base_path() != "":
+        return
+
+    set_cfg_constructor(
+        stage0 = cfg_constructor_pre_constraint_analysis,
+        stage1 = cfg_constructor_post_constraint_analysis,
+        key = MODIFIER_METADATA_KEY,
+        aliases = struct(
+            dev = "root//buck2/constraints:dev",
+            opt = "root//buck2/constraints:opt",
+            prof = "root//buck2/constraints:prof",
+            static = "root//buck2/constraints:static",
+            shared = "root//buck2/constraints:shared",
+            all_ways = "root//buck2/constraints:all_ways",
+        ),
+        extra_data = struct(),
+    )
+
+# `dev` is the default build mode when no -m flag is given, and `clang`
+# is defaulted on too (see the root PACKAGE file's own comment - every
+# machine building this project today lands on clang via
+# system_cxx_toolchain()'s $PATH auto-detection, so this is just always
+# true rather than a per-environment override) - but only when standalone
+# (same reasoning as cfg_constructor_if_standalone() above); when nested,
+# an empty list is the no-op equivalent of "don't call this at all",
+# since set_cfg_modifiers() itself has no comparable once-per-project
+# restriction (it's package-scoped, not project-wide) - unlike
+# set_cfg_constructor(), calling it with `[]` when nested is harmless.
+def dev_modifiers_if_standalone():
+    if get_base_path() != "":
+        return []
+    return ["root//buck2/constraints:dev", "root//buck2/constraints:clang"]
diff --git a/buck2/cmm.bzl b/buck2/cmm.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/cmm.bzl
@@ -0,0 +1,142 @@
+# Compiling Cmm (the `cmm-sources` of a Cabal component) into a library that
+# Haskell libraries can depend on.
+#
+# GHC compiles .cmm files itself, so this runs it on each of them, once for
+# each kind of object that a link needs: ordinary ones for static linking and
+# position-independent ones for shared libraries (dynamic ones, in GHC's
+# terms). The library is the objects themselves, to be linked (all of them)
+# into the library of the component's Haskell code, as in Cabal: see
+# `internal_deps` of haskell_library().
+
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//cxx:preprocessor.bzl", "cxx_inherited_preprocessor_infos", "cxx_merge_cpreprocessors")
+load("@prelude//haskell:library_info.bzl", "HaskellLibraryInfoTSet")
+load("@prelude//haskell:link_info.bzl", "HaskellLinkInfo")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkStyle",
+    "ObjectsLinkable",
+    "create_merged_link_info",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//linking:linkable_graph.bzl", "create_linkable_graph", "create_linkable_graph_node", "create_linkable_node")
+load("@prelude//linking:shared_libraries.bzl", "EMPTY_SHARED_LIBRARY_INFO")
+load("@prelude//decls/toolchains_common.bzl", "toolchains_common")
+load("@prelude//haskell:toolchain.bzl", "HaskellToolchainInfo")
+load("@third-party-haskell//:tools.bzl", "CC_FINGERPRINT", "GHC_FINGERPRINT")
+
+def _package_db_args(ctx: AnalysisContext, link_style: LinkStyle) -> cmd_args:
+    # The package databases of the Haskell libraries among the deps, and of
+    # their own dependencies. GHC needs them because it reads the platform
+    # constants from the rts package. If a library isn't built in this link
+    # style (it is only built shared, say), its packages for another style
+    # are used instead, since they have the same rts.
+    children = []
+    for dep in ctx.attrs.deps:
+        info = dep.get(HaskellLinkInfo)
+        if info:
+            infos = info.prof_info if ctx.attrs.profiling else info.info
+            children.append(infos[link_style] if link_style in infos else infos.values()[0])
+    libs = list(ctx.actions.tset(HaskellLibraryInfoTSet, children = children).traverse())
+    dbs = {lib.db: None for lib in libs}
+    return cmd_args([cmd_args("-package-db", db) for db in dbs])
+
+def _cmm_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    ghc = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+    linker_type = get_cxx_toolchain_info(ctx).linker_info.type
+    pre = cxx_merge_cpreprocessors(ctx.actions, [], cxx_inherited_preprocessor_infos(ctx.attrs.deps))
+    pre_args = cmd_args(pre.set.project_as_args("args"), format = "-optCmmP={}")
+    link_infos = {}
+    for output_style, link_style, flags in (
+        (LibOutputStyle("archive"), LinkStyle("static"), []),
+        (LibOutputStyle("pic_archive"), LinkStyle("shared"), ["-dynamic", "-fPIC"]),
+    ):
+        variant = link_style.value
+        package_db_args = _package_db_args(ctx, link_style)
+        objects = []
+        for entry in ctx.attrs.srcs:
+            src, src_flags = entry if type(entry) == type(()) else (entry, [])
+            obj = ctx.actions.declare_output(variant, src.short_path + ".o")
+            cmd = cmd_args(
+                ghc.compiler,
+                ghc.compiler_flags,
+                ["-prof"] if ctx.attrs.profiling else [],
+                flags,
+                ctx.attrs.flags,
+                package_db_args,
+                pre_args,
+                src_flags,
+                "-c",
+                src,
+                "-o",
+                obj.as_output(),
+            )
+
+            # The fingerprints are not read: they make the GHC installation and
+            # the C toolchain part of the action's cache key (see toolchains/BUCK).
+            ctx.actions.run(
+                cmd,
+                category = "ghc_cmm",
+                identifier = variant + "/" + src.short_path,
+                env = {"CABAL_BUCK2_GHC": GHC_FINGERPRINT, "CABAL_BUCK2_CC": CC_FINGERPRINT},
+            )
+            objects.append(obj)
+
+        # The Cmm code is only reached from Haskell code, by symbol, so every
+        # object has to be kept.
+        link_infos[output_style] = LinkInfos(default = LinkInfo(
+            name = ctx.label.name,
+            linkables = [ObjectsLinkable(objects = objects, linker_type = linker_type, link_whole = True)],
+        ))
+
+    return [
+        DefaultInfo(),
+        create_merged_link_info(ctx, get_cxx_toolchain_info(ctx).pic_behavior, link_infos, preferred_linkage = Linkage("static")),
+        EMPTY_SHARED_LIBRARY_INFO,
+        create_linkable_graph(
+            ctx,
+            node = create_linkable_graph_node(
+                ctx,
+                linkable_node = create_linkable_node(
+                    ctx = ctx,
+                    default_soname = None,
+                    preferred_linkage = Linkage("static"),
+                    link_infos = link_infos,
+                ),
+            ),
+        ),
+    ]
+
+_cmm_library = rule(
+    impl = _cmm_library_impl,
+    attrs = {
+        "deps": attrs.list(attrs.dep(), default = []),
+        "flags": attrs.list(attrs.arg(), default = []),
+        "labels": attrs.list(attrs.string(), default = []),
+        "profiling": attrs.bool(default = False),
+        "srcs": attrs.list(attrs.one_of(attrs.source(), attrs.tuple(attrs.source(), attrs.list(attrs.arg())))),
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_haskell_toolchain": toolchains_common.haskell(),
+    },
+)
+
+_PROFILING = select({
+    "root//buck2/constraints:prof": True,
+    "DEFAULT": False,
+})
+
+def cmm_library(name, srcs, flags = [], deps = [], **kwargs):
+    """A library of Cmm code, to depend on from haskell_library() (as one
+    of its `internal_deps`).
+
+    Args:
+      name: the target name.
+      srcs: the .cmm files, each alone or paired with flags of its own.
+      flags: options for GHC when it compiles them.
+      deps: the libraries whose headers they include: C libraries, and the
+          Haskell libraries of the packages the code depends on.
+    """
+    _cmm_library(name = name, srcs = srcs, flags = flags, deps = deps, profiling = _PROFILING, **kwargs)
diff --git a/buck2/constraints/BUCK b/buck2/constraints/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/constraints/BUCK
@@ -0,0 +1,126 @@
+load("@prelude//transitions:utils.bzl", "transition_utils")
+
+# Build configuration. These options are normally set on the command
+# line via -m, e.g.
+#
+#   buck2 build //some/target -m buck2//constraint:asan
+#
+# Aliases for constraints can be configured in the PACKAGE file.
+# Checking configuration settings is done using select().
+
+# build_mode: selects between
+#   - dev (the default; faster rebuild, more runtime checks, slower execution)
+#   - opt (slower rebuild, fewer runtime checks, faster execution)
+#
+# Usually these are aliased to simply dev/opt, so you can say
+#
+#   buck2 build //some/target -m opt
+#
+# to build with optimisation.
+constraint_setting(
+    name = "build_mode",
+    visibility = ["PUBLIC"],
+)
+
+# build_mode dev: typically
+#    - no optimisation
+#    - assertions enabled
+#    - debug logging enabled
+#    - shared libraries for faster linking
+constraint_value(
+    name = "dev",
+    constraint_setting = ":build_mode",
+    visibility = ["PUBLIC"],
+)
+
+# build_mode opt: typically
+#    - full optimisation
+#    - assertions disabled
+#    - debug logging disabled
+#    - static linking
+constraint_value(
+    name = "opt",
+    constraint_setting = ":build_mode",
+    visibility = ["PUBLIC"],
+)
+
+# Enable address sanitiser (-fsanitize=address) for C/C++ code
+constraint_setting(
+    name = "sanitizer",
+    visibility = ["PUBLIC"],
+)
+
+constraint_value(
+    name = "asan",
+    constraint_setting = ":sanitizer",
+    visibility = ["PUBLIC"],
+)
+
+# The C compiler flavour, used to select flags
+constraint_setting(
+    name = "compiler",
+    visibility = ["PUBLIC"],
+)
+
+constraint_value(
+    name = "clang",
+    constraint_setting = ":compiler",
+    visibility = ["PUBLIC"],
+)
+
+# Enable Haskell profiling. Requires all the Cabal package
+# dependencies to be built for profiling too.
+constraint_setting(
+    name = "profiling",
+    visibility = ["PUBLIC"],
+)
+
+constraint_value(
+    name = "prof",
+    constraint_setting = ":profiling",
+    visibility = ["PUBLIC"],
+)
+
+# To profiling (for the C and Cmm of a profiled library, say).
+transition_utils.modify_constraints_transition(
+    name = "to-prof",
+    add = [":prof"],
+    visibility = ["PUBLIC"],
+)
+
+# linking: how executables are linked against their Haskell libraries, when
+# it isn't the build mode's default (shared for dev, static for opt and prof).
+# Profiling can't be linked shared.
+constraint_setting(
+    name = "linking",
+    visibility = ["PUBLIC"],
+)
+
+constraint_value(
+    name = "static",
+    constraint_setting = ":linking",
+    visibility = ["PUBLIC"],
+)
+
+constraint_value(
+    name = "shared",
+    constraint_setting = ":linking",
+    visibility = ["PUBLIC"],
+)
+
+# libraries: with all_ways, libraries are built both static and shared,
+# whatever the linking of executables. This can be used when building
+# libraries to be installed. A library that is built both ways is compiled
+# once, with -dynamic-too. Profiled libraries don't need a constraint,
+# because a library's profiled variants are built whenever something asks
+# for them.
+constraint_setting(
+    name = "libraries",
+    visibility = ["PUBLIC"],
+)
+
+constraint_value(
+    name = "all_ways",
+    constraint_setting = ":libraries",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/cxx.bzl b/buck2/cxx.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/cxx.bzl
@@ -0,0 +1,54 @@
+_ASAN_CXX_FLAGS = select({
+    "root//buck2/constraints:asan": ["-fsanitize=address"],
+    "DEFAULT": [],
+})
+
+_BUILD_MODE_CXX_FLAGS = select({
+    "root//buck2/constraints:opt": select({
+        "root//buck2/constraints:asan": ["-g"],
+        "DEFAULT": ["-O3", "-DNDEBUG"],
+    }),
+    "DEFAULT": ["-g"],
+})
+
+# Whether actions upload their results to the remote action cache, if there
+# is one, when they say nothing about it (see `cabal buck2 --cache`).
+_DEFAULT_ALLOW_CACHE_UPLOAD = read_root_config("buck2", "default_allow_cache_upload", "false").lower() == "true"
+
+_COMMON_CXX_FLAGS = ["-fno-omit-frame-pointer"] + _ASAN_CXX_FLAGS + _BUILD_MODE_CXX_FLAGS
+
+# The languages of lang_compiler_flags (by their sources' kind).
+_LANGUAGES = ["c", "cxx", "objc", "objcxx", "assembler_with_cpp", "cuda", "hip", "asm_with_cpp"]
+
+def _lang_compiler_flags(lang_compiler_flags):
+    # The build mode's flags come first, so that a target's own win (-Og, or
+    # -fomit-frame-pointer, say): its lang_compiler_flags (a Cabal package's
+    # cc-options), and then its compiler_flags.
+    flags = dict(lang_compiler_flags)
+    for lang in _LANGUAGES:
+        flags[lang] = _COMMON_CXX_FLAGS + flags.get(lang, [])
+    return flags
+
+def cxx_library(name, lang_compiler_flags = {}, linker_flags = [], **kwargs):
+    # A library's shared-library link doesn't leave uploading to
+    # `buck2.default_allow_cache_upload` either, but uploads only if the target
+    # says so. Its result depends on the system linker and libraries, which
+    # buck2 doesn't track, but with a cache the C toolchain's fingerprint is
+    # part of the link's command, and so of its key (see `_run_info` in
+    # prelude/toolchains/cxx.bzl).
+    kwargs.setdefault("allow_cache_upload", _DEFAULT_ALLOW_CACHE_UPLOAD)
+    native.cxx_library(
+        name = name,
+        lang_compiler_flags = _lang_compiler_flags(lang_compiler_flags),
+        # -fsanitize=address has to reach the *linker* too
+        linker_flags = _ASAN_CXX_FLAGS + linker_flags,
+        **kwargs
+    )
+
+def cxx_binary(name, lang_compiler_flags = {}, linker_flags = [], **kwargs):
+    native.cxx_binary(
+        name = name,
+        lang_compiler_flags = _lang_compiler_flags(lang_compiler_flags),
+        linker_flags = _ASAN_CXX_FLAGS + linker_flags,
+        **kwargs
+    )
diff --git a/buck2/haskell.bzl b/buck2/haskell.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/haskell.bzl
@@ -0,0 +1,249 @@
+# Wrappers around the native haskell_library()/haskell_binary() rules, and
+# a haskell_test() rule.
+#
+# These handle:
+#   - build modes: e.g. `-m opt` selects optimisation + static linking
+#   - package deps: `packages = ["text", ...]` instead of explicit
+#     `"@third-party-haskell//:text"` entries in `deps`.
+#   - a standard set of packages (rts) added to every target. A target can
+#     give its own set with `auto_packages`.
+#   - hsc2hs: any `.hsc` file in `srcs` is automatically preprocessed, with
+#     include paths derived from `deps` (see buck2/hsc2hs.bzl) - so a `.hsc`
+#     file that needs a C++ dependency's headers just needs that dependency
+#     listed in `deps`, same as any other buck2 target.
+#   - alex/happy: any `.x`/`.y`/`.ly` file in `srcs` is automatically run through
+#     the corresponding tool (see buck2/alex_happy.bzl).
+#   - boot files: `boot_srcs = {module: file}` gives the .hs-boot file of each
+#     module (of `srcs`, by module name) that has one. That of a generated
+#     module (from a .hsc/.x/.y file) is put next to the generated source,
+#     which is where GHC looks for it.
+#   - support for build rules generated from Cabal packages:
+#     - `cabal_component = (pkg, component)` causes this component's
+#       `cabal_macros.h` file to be included when `{-# LANGUAGE CPP #-}`
+#       is on.
+
+load("//buck2:alex_happy.bzl", "alex", "happy")
+load("//buck2:hsc2hs.bzl", "hsc2hs")
+load("@prelude//paths.bzl", "paths")
+
+# Packages implicitly needed by every Haskell target.
+AUTO_PACKAGES = ["rts"]
+
+def _package_deps(packages, auto_packages):
+    all_pkgs = {p: None for p in (auto_packages + packages)}
+    return [("@third-party-haskell//:" + p) for p in sorted(all_pkgs.keys())]
+
+def _cabal_macros_include_flags(cabal_component):
+    if cabal_component == None:
+        return []
+    pkg, component = cabal_component
+    autogen_dir = "cabal-buck2/autogen" if pkg == "." else pkg + "/cabal-buck2/autogen"
+    label = "//" + autogen_dir + ":" + component + "-cabal-macros"
+    return ["-optP-include", "-optP$(location " + label + ")"]
+
+def _cabal_macros_hsc_flags(cabal_component):
+    # hsc2hs wants the package's macros too (MIN_VERSION_base, say).
+    flags = _cabal_macros_include_flags(cabal_component)
+    return ["--cflag=-include", "--cflag=" + flags[1][len("-optP"):]] if flags else []
+
+# Link style for executables: the linking constraint's (static or shared), or
+# else dynamic, but static for opt, and for prof, which must be static: GHC
+# doesn't support prof/dynamic.
+_BUILD_MODE_LINK_STYLE = select({
+    "root//buck2/constraints:static": "static",
+    "root//buck2/constraints:shared": "shared",
+    "DEFAULT": select({
+        "root//buck2/constraints:prof": "static",
+        "DEFAULT": select({
+            "root//buck2/constraints:opt": "static",
+            "DEFAULT": "shared",
+        }),
+    }),
+})
+
+# Compiler flags are passed in this order: mode flags, target-specific flags
+# The principle is that more specific flags should be able to override less
+# specific, so the build-wide flags come first.
+_BUILD_MODE_HASKELL_FLAGS = select({
+    "root//buck2/constraints:opt": ["-O"],
+    "DEFAULT": [],
+})
+
+# Libraries are built shared when executables are linked shared, and static
+# and shared otherwise (Template Haskell needs a library shared, for a GHC
+# that is itself linked shared). With all_ways, libraries are built both
+# static and shared, whatever the linking of executables.
+#
+# Profiling doesn't change this. A library always has profiled variants,
+# which are only built when a profiled link or compile asks for them.
+_BUILD_MODE_PREFERRED_LINKAGE = select({
+    "root//buck2/constraints:all_ways": "any",
+    "DEFAULT": select({
+        "root//buck2/constraints:static": "any",
+        "root//buck2/constraints:shared": "shared",
+        "DEFAULT": select({
+            "root//buck2/constraints:opt": "any",
+            "DEFAULT": "shared",
+        }),
+    }),
+})
+
+_PROF_ENABLED = select({
+    "root//buck2/constraints:prof": True,
+    "DEFAULT": False,
+})
+
+# Linker flags enabled when building with ASAN
+_ASAN_LINKER_FLAGS = select({
+    "root//buck2/constraints:asan": ["-optc-fsanitize=address", "-optl-fsanitize=address"],
+    "DEFAULT": [],
+})
+
+def hs_module_path(path):
+    for ext in (".hsc", ".x", ".y", ".ly"):
+        if path.endswith(ext):
+            return path[:-len(ext)] + ".hs"
+    return path
+
+def _resolve_src(name, src, deps, hsc_flags, hsc_cxx, common):
+    out = paths.replace_extension(src, ".hs")
+    if src.endswith(".hsc"):
+        rule_name = name + "-hsc-" + out.replace("/", "_")
+        hsc2hs(name = rule_name, hsc_file = src, out = out, deps = deps, extra_flags = hsc_flags, cxx = hsc_cxx, **common)
+        return ":" + rule_name
+    elif src.endswith(".x"):
+        rule_name = name + "-alex-" + out.replace("/", "_")
+        alex(name = rule_name, src = src, out = out, **common)
+        return ":" + rule_name
+    elif src.endswith(".y") or src.endswith(".ly"):
+        rule_name = name + "-happy-" + out.replace("/", "_")
+        happy(name = rule_name, src = src, out = out, **common)
+        return ":" + rule_name
+    else:
+        return src
+
+def _with_boot_impl(ctx: AnalysisContext) -> list[Provider]:
+    boot_path = paths.split_extension(ctx.attrs.path)[0] + paths.split_extension(ctx.attrs.boot.short_path)[1]
+    srcs = ctx.actions.symlinked_dir("srcs", {ctx.attrs.path: ctx.attrs.src, boot_path: ctx.attrs.boot}, has_content_based_path = False)
+    return [DefaultInfo(sub_targets = {
+        "boot": [DefaultInfo(default_output = srcs.project(boot_path))],
+        "src": [DefaultInfo(default_output = srcs.project(ctx.attrs.path))],
+    })]
+
+# A generated source of a module (`path` is where it would be in the package),
+# with the module's boot file next to it, which is where GHC looks for it.
+_with_boot = rule(
+    impl = _with_boot_impl,
+    attrs = {
+        "boot": attrs.source(),
+        "path": attrs.string(),
+        "src": attrs.source(),
+    },
+)
+
+def _resolve_srcs(name, srcs, boot_srcs, deps, hsc_flags, hsc_cxx, kwargs):
+    # The rules that preprocess sources are compatible with the same
+    # configurations as the rule whose sources they are.
+    common = {"target_compatible_with": kwargs["target_compatible_with"]} if "target_compatible_with" in kwargs else {}
+    if type(srcs) != type({}):
+        if boot_srcs:
+            fail("{}: boot_srcs needs srcs to be a dict, by module name".format(name))
+        return [ _resolve_src(name, src, deps, hsc_flags, hsc_cxx, common) for src in srcs ]
+    unknown = [modl for modl in boot_srcs if modl not in srcs]
+    if unknown:
+        fail("{}: boot_srcs for modules not in srcs: {}".format(name, ", ".join(unknown)))
+    resolved = {}
+    for modl, src in srcs.items():
+        resolved_src = _resolve_src(name, src, deps, hsc_flags, hsc_cxx, common)
+        boot = boot_srcs.get(modl)
+        if boot == None:
+            resolved[modl] = resolved_src
+        elif resolved_src == src:
+            resolved[modl] = src
+            resolved[modl + "-boot"] = boot
+        else:
+            rule_name = name + "-boot-" + modl
+            _with_boot(name = rule_name, src = resolved_src, boot = boot, path = paths.replace_extension(src, ".hs"), **common)
+            resolved[modl] = ":" + rule_name + "[src]"
+            resolved[modl + "-boot"] = ":" + rule_name + "[boot]"
+    return resolved
+
+def haskell_library(
+        name,
+        srcs = [],
+        packages = [],
+        deps = [],
+        compiler_flags = [],
+        hsc_flags = [],
+        hsc_cxx = True,
+        cabal_component = None,
+        boot_srcs = {},
+        auto_packages = AUTO_PACKAGES,
+        internal_deps = [],
+        **kwargs):
+    all_deps = deps + _package_deps(packages, auto_packages)
+    kwargs.setdefault("preferred_linkage", _BUILD_MODE_PREFERRED_LINKAGE)
+    native.haskell_library(
+        name = name,
+        srcs = _resolve_srcs(name, srcs, boot_srcs, all_deps + internal_deps, hsc_flags + _cabal_macros_hsc_flags(cabal_component), hsc_cxx, kwargs),
+        compiler_flags = _BUILD_MODE_HASKELL_FLAGS + compiler_flags + _cabal_macros_include_flags(cabal_component),
+        deps = all_deps,
+        internal_deps = internal_deps,
+        **kwargs
+    )
+
+def haskell_binary(
+        name,
+        srcs = [],
+        packages = [],
+        deps = [],
+        compiler_flags = [],
+        hsc_flags = [],
+        hsc_cxx = True,
+        linker_flags = [],
+        cabal_component = None,  # see haskell_library()
+        boot_srcs = {},  # see haskell_library()
+        auto_packages = AUTO_PACKAGES,  # see haskell_library()
+        **kwargs):
+    all_deps = deps + _package_deps(packages, auto_packages)
+    kwargs.setdefault("link_style", _BUILD_MODE_LINK_STYLE)
+    kwargs.setdefault("enable_profiling", _PROF_ENABLED)
+    native.haskell_binary(
+        name = name,
+        srcs = _resolve_srcs(name, srcs, boot_srcs, all_deps, hsc_flags + _cabal_macros_hsc_flags(cabal_component), hsc_cxx, kwargs),
+        compiler_flags = _BUILD_MODE_HASKELL_FLAGS + compiler_flags + _ASAN_LINKER_FLAGS + _cabal_macros_include_flags(cabal_component),
+        deps = all_deps,
+        linker_flags = _ASAN_LINKER_FLAGS + linker_flags,
+        **kwargs
+    )
+
+# `labels` are the test's rather than its binary's, so that `buck2 test
+# --exclude <label>` can leave a test out.
+def haskell_test(name, test_args = [], test_env = {}, cwd = None, labels = [], **kwargs):
+    bin = name + "-bin"
+    haskell_binary(name = bin, **kwargs)
+    test_target = ":" + bin
+    args = test_args
+
+    # This doesn't need to put the test's tools on PATH. The binary's RunInfo
+    # already does that for its run_tool_depends.
+    if cwd != None:
+        test_target = "//buck2:run_test"
+        args = [cwd, "$(exe_target :" + bin + ")"] + test_args
+
+    native.sh_test(
+        name = name,
+        test = test_target,
+        args = args,
+        env = {"LANG": "C.UTF-8"} | test_env,
+        # `LANG` defaults to a UTF-8 locale: unlike `buck2 run` (which
+        # inherits the caller's shell environment, `LANG` included),
+        # `buck2 test` runs actions in a sanitized environment with no
+        # `LANG` at all - so GHC's `hGetContents`/`readFile` fall back
+        # to the POSIX/ASCII encoding and choke on any non-ASCII byte
+        # in a test fixture.
+        labels = labels,
+    )
+
+
+
diff --git a/buck2/headers.bzl b/buck2/headers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/headers.bzl
@@ -0,0 +1,48 @@
+# The headers of other targets, without their libraries: for C code that
+# GHC would have given the include directories of the packages it depends on.
+# Depending on the packages themselves would link them in as well, and in a
+# profiling build, with the wrong libraries.
+
+load("@prelude//cxx:preprocessor.bzl", "CPreprocessor", "CPreprocessorArgs", "cxx_inherited_preprocessor_infos", "cxx_merge_cpreprocessors")
+
+def _headers_of_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        cxx_merge_cpreprocessors(ctx.actions, [], cxx_inherited_preprocessor_infos(ctx.attrs.deps)),
+    ]
+
+headers_of = rule(
+    impl = _headers_of_impl,
+    attrs = {"deps": attrs.list(attrs.dep(), default = [])},
+)
+
+# A library's include directory as Cabal installs it, with each of its
+# install-includes at its path in the directory. `srcs` maps those paths to
+# the files of the package.
+#
+# What is compiled against the library sees the directory, through the
+# preprocessor flags that this target exports, and also sees
+# `exported_include_dirs`. Those are directories that the build doesn't
+# track, such as the one where the package's configure script generated
+# headers.
+#
+# The directory holds symlinks to the headers, not copies. A compile can
+# reach a header both through this directory and by another path: the
+# library's own C, say, includes a header next to it by its path in the
+# source tree. A header with `#pragma once` is skipped the second time only
+# if both paths lead to the same file.
+def _install_include_dir_impl(ctx: AnalysisContext) -> list[Provider]:
+    include = ctx.actions.symlinked_dir("include", ctx.attrs.srcs)
+    flags = [cmd_args(include, format = "-I{}")] + ["-I" + d for d in ctx.attrs.exported_include_dirs]
+    return [
+        DefaultInfo(default_output = include),
+        cxx_merge_cpreprocessors(ctx.actions, [CPreprocessor(args = CPreprocessorArgs(args = flags))], []),
+    ]
+
+install_include_dir = rule(
+    impl = _install_include_dir_impl,
+    attrs = {
+        "exported_include_dirs": attrs.list(attrs.string(), default = []),
+        "srcs": attrs.dict(attrs.string(), attrs.source(), default = {}),
+    },
+)
diff --git a/buck2/hsc2hs.bzl b/buck2/hsc2hs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/hsc2hs.bzl
@@ -0,0 +1,71 @@
+# A rule for running hsc2hs.
+#
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//cxx:preprocessor.bzl", "cxx_inherited_preprocessor_infos", "cxx_merge_cpreprocessors")
+load("@prelude//decls/toolchains_common.bzl", "toolchains_common")
+load("@prelude//haskell:toolchain.bzl", "HaskellToolchainInfo")
+load("@third-party-haskell//:tools.bzl", "CC_FINGERPRINT", "GHC_FINGERPRINT")
+
+def _hsc2hs_include_args(pp_info):
+    return [
+        cmd_args(pp_info.set.project_as_args("include_dirs"), format = "--cflag={}"),
+        cmd_args(pp_info.set.project_as_args("args"), format = "--cflag={}"),
+    ]
+
+def _hsc2hs_impl(ctx: AnalysisContext) -> list[Provider]:
+    out = ctx.actions.declare_output(ctx.attrs.out)
+
+    pp_infos = cxx_inherited_preprocessor_infos(ctx.attrs.deps)
+    merged = cxx_merge_cpreprocessors(ctx.actions, [], pp_infos)
+
+    hsc2hs_tool = ctx.attrs._haskell_toolchain[HaskellToolchainInfo].hsc2hs
+
+    # C++, unless told otherwise: some of the .hsc files need the headers of
+    # C++ code. A package that is only C (Cabal's way) must not be compiled as
+    # C++, which doesn't accept what hsc2hs generates for #alignment.
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    compiler_info = cxx_toolchain.cxx_compiler_info if ctx.attrs.cxx else cxx_toolchain.c_compiler_info
+    compiler = compiler_info.compiler
+
+    # hsc2hs wants a single program, but the compiler is a command (with the
+    # cache, it is `env` setting a fingerprint, then the compiler).
+    cc, cc_hidden = ctx.actions.write("cc.sh", ["#!/bin/sh", cmd_args("exec", compiler, '"$@"', delimiter = " ")], is_executable = True, allow_args = True)
+
+    cmd = cmd_args(
+        hsc2hs_tool,
+        cmd_args("--cc=", cmd_args(cc, hidden = cc_hidden), delimiter = ""),
+        # The project's flags for the language (see default_toolchains()).
+        cmd_args(compiler_info.compiler_flags, format = "--cflag={}"),
+        "-C",
+        "-D__HSC2HS__=1",
+        ctx.attrs.extra_flags,
+        # The hsc file's own package dir, so `#include "foo.h"`/`<foo.h>`
+        # against a local (non-exported) header resolves, same as it would
+        # when compiling a sibling cxx_library() source in this package.
+        "-I" + ("." if ctx.label.package == "" else ctx.label.package),
+        _hsc2hs_include_args(merged),
+        "-o",
+        out.as_output(),
+        ctx.attrs.hsc_file,
+    )
+    # The fingerprints are not read by hsc2hs: they make the GHC installation
+    # and the C toolchain part of the action's cache key (see toolchains/BUCK).
+    ctx.actions.run(cmd, category = "hsc2hs", env = {"CABAL_BUCK2_GHC": GHC_FINGERPRINT, "CABAL_BUCK2_CC": CC_FINGERPRINT})
+
+    return [DefaultInfo(default_output = out)]
+
+# Runs hsc2hs on `hsc_file`, producing `out`. `deps` is used purely to
+# collect C/C++ include paths (via CPreprocessorInfo); it doesn't need to be
+# (and usually isn't) the same as the consuming haskell_library()'s deps.
+hsc2hs = rule(
+    impl = _hsc2hs_impl,
+    attrs = {
+        "cxx": attrs.bool(default = True),
+        "deps": attrs.list(attrs.dep(), default = []),
+        "extra_flags": attrs.list(attrs.arg(), default = []),
+        "hsc_file": attrs.source(),
+        "out": attrs.string(),
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_haskell_toolchain": toolchains_common.haskell(),
+    },
+)
diff --git a/buck2/llvm.bzl b/buck2/llvm.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/llvm.bzl
@@ -0,0 +1,44 @@
+# Discovers this system's LLVM/Clang installation via `llvm-config-
+# <version>`, the same way `buck2/prelude/third-party/pkgconfig.bzl`'s
+# external_pkgconfig_library() discovers a pkg-config-described system
+# library: a couple of genrule()s shelling out to the real tool at build
+# time (its output describes *this machine's* install - absolute paths
+# under e.g. /usr/lib/llvm-15 - not something safe to bake into checked-
+# in BUCK text or share across machines via remote execution, same
+# reasoning pkgconfig.bzl's own comment gives for `remote = False`
+# there), wrapped in a prebuilt_cxx_library() so a consumer just adds it
+# to its own `deps` like any other library, instead of hand-rolling
+# `-I`/`-L`/`-l` flags itself.
+#
+# llvm-config's own `--cxxflags` bundles its include path and defines
+# together with `-std=c++14 -fno-exceptions` - dropped here by keeping
+# only the `-I`/`-D` tokens from that output, not passed through whole
+# (see glean/lang/clang/BUCK's own comment on why: that package's
+# sources need >= C++17 and don't build with exceptions disabled, so
+# whatever it links against can't be pinned to llvm-config's own
+# defaults for those two).
+def external_llvm_config_library(name, version, visibility = ["PUBLIC"]):
+    llvm_config = "llvm-config-{}".format(version)
+
+    cflags = name + "__llvm_config_cflags"
+    native.genrule(
+        name = cflags,
+        out = "out",
+        cmd = "{ll} --cxxflags | tr ' ' '\\n' | grep -E '^-[ID]' | tr '\\n' ' ' > $OUT".format(ll = llvm_config),
+        remote = False,
+    )
+
+    libs = name + "__llvm_config_libs"
+    native.genrule(
+        name = libs,
+        out = "out",
+        cmd = "{ll} --ldflags > $OUT; {ll} --libs >> $OUT; {ll} --system-libs >> $OUT".format(ll = llvm_config),
+        remote = False,
+    )
+
+    native.prebuilt_cxx_library(
+        name = name,
+        visibility = visibility,
+        exported_preprocessor_flags = ["@$(location :{})".format(cflags)],
+        exported_linker_flags = ["@$(location :{})".format(libs)],
+    )
diff --git a/buck2/platforms/BUCK b/buck2/platforms/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/platforms/BUCK
@@ -0,0 +1,103 @@
+load(":defs.bzl", "execution_platform_with_constraints", "execution_platforms")
+
+# Any exec_dep/`$(exe ...)` edge (a build-time tool dependency) gets
+# reconfigured to match whichever execution platform is chosen for it,
+# straight from that platform's own `constraint_values` - it does *not*
+# go through the project's root PACKAGE-level `set_cfg_modifiers()` at
+# all, since that machinery only drives ordinary target-platform
+# configuration. `prelude//platforms:default` (the vendored prelude
+# target every exec_dep falls back to unless it specifically requires
+# `:opt` below) carries none of this project's own constraint values, so
+# without a project-specific default platform of our own, every such
+# edge - and everything it transitively pulls in, e.g. clang-index,
+# hie-indexer, or any Haskell tool linking against glean/rts,
+# glean/rocksdb, hsthrift's folly-clib, ... - silently fell back to the
+# DEFAULT (GCC-flavored) arm of buck2/cxx.bzl's `_COROUTINES_FLAGS`
+# select and re-added `-fcoroutines` to those specific exec-configured
+# copies. Invisible on a dev machine with a newer clang that tolerates
+# the unrecognised flag, but a hard `clang: error: unknown argument:
+# '-fcoroutines'` on CI's older clang. Confirmed by diffing
+# `.cpp.target_cxx_args` across configurations: building
+# `root//glean/rts:rts` by its own label (plain target-platform
+# resolution, no exec_dep edge involved) came out clean, but the *same*
+# target reappeared with `-fcoroutines` under a second, exec-configured
+# configuration as soon as anything reached it via an exec_dep edge -
+# i.e. the full `//glean/...` CI invocation, not a single-target build -
+# and adding `clang` to `:exec-opt` alone (the first fix attempted here)
+# didn't fully clear it, because most of those edges resolve to the
+# *plain* default execution platform, not `:exec-opt` specifically.
+#
+# So `:exec-default` exists purely to be "prelude//platforms:default
+# plus this project's own clang constraint value, plus `dev`" - the
+# actual default every exec_dep edge without a further requirement
+# resolves to. `dev` here isn't load-bearing for the coroutines fix
+# above (absence of `opt`/`prof` already falls through to the same
+# `DEFAULT` arm every `_BUILD_MODE_*` select in buck2/{cxx,haskell}.bzl
+# uses for "dev") - it's here so a select() that ever checks *for*
+# `root//buck2/constraints:dev` positively, rather than treating its
+# absence as the dev case, still gets a real match under this platform
+# too, rather than depending on coincidence. `:exec-opt` is then
+# derived from *this*, not the raw prelude target, so it inherits
+# `clang` too instead of needing its own copy of the same reasoning.
+execution_platform_with_constraints(
+    name = "exec-default",
+    base = "prelude//platforms:default",
+    constraint_values = [
+        "root//buck2/constraints:clang",
+        "root//buck2/constraints:dev",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+# A second execution platform, identical to `:exec-default` except its
+# configuration also carries the `opt` build-mode constraint value
+# instead of `dev` (see `defs.bzl`'s `execution_platform_with_
+# constraints()` - constraint_values passed here for the `build_mode`
+# constraint_setting *replace* whatever `base` already had for that
+# same setting, not add to it, so this doesn't end up with both `dev`
+# and `opt` set at once) - see buck2.md's entry on forcing `opt` for
+# build-time codegen tools. Listed second in `.buckconfig`'s `[build]
+# execution_platforms`, so it's only selected for targets that
+# explicitly opt in via `exec_compatible_with` requiring
+# `root//buck2/constraints:opt` (currently: hsthrift//compiler:
+# thrift-compiler, //glean/schema/gen:gen-schema, //glean/bytecode:
+# gen-bytecode-hs - unconditionally, they always want to run fast
+# regardless of the ambient build mode - and, via buck2/haskell.bzl's
+# `_BUILD_MODE_EXEC_COMPATIBLE_WITH`, every haskell_binary()/
+# haskell_test() *only when the ambient build mode is itself `opt`* -
+# see that file's own comment for why a plain, unconditional
+# `exec_compatible_with` requirement on clang-index/hie-indexer's own
+# targets wouldn't have worked here). Every other exec_dep/`$(exe ...)`
+# edge in the build has no such requirement, so it stays compatible
+# with, and keeps resolving to, `:exec-default`.
+#
+# `root//buck2/constraints:opt`, not a bare `//buck2/constraints:opt` -
+# this needs to be the exact same constraint *value* the project's own
+# dev/opt PACKAGE-level cfg modifier (`root//PACKAGE`) attaches to the
+# *target* configuration, so a `select()` written the usual way (keyed on
+# `root//buck2/constraints:opt`, e.g. buck2/haskell.bzl's `_BUILD_MODE_*`)
+# resolves the same "opt" arm here as it would under a plain `-m opt`
+# build - "root" is a cell alias, not a literal cell name, so this
+# resolves correctly both nested inside another project and when this
+# checkout is standalone (see hsthrift/PACKAGE's own comment on the same
+# convention).
+execution_platform_with_constraints(
+    name = "exec-opt",
+    base = ":exec-default",
+    constraint_values = ["root//buck2/constraints:opt"],
+    visibility = ["PUBLIC"],
+)
+
+# The actual target `.buckconfig`'s `[build] execution_platforms` points
+# at - see defs.bzl's own comment on why this indirection is needed
+# (that buckconfig key takes one target, not a list). Order matters:
+# `:exec-default` first, so anything with no `exec_compatible_with`
+# requirement (almost everything) keeps resolving to it.
+execution_platforms(
+    name = "exec",
+    platforms = [
+        ":exec-default",
+        ":exec-opt",
+    ],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/platforms/defs.bzl b/buck2/platforms/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/platforms/defs.bzl
@@ -0,0 +1,97 @@
+# A tiny wrapper rule that takes an existing execution platform (`base`)
+# and produces a new one identical to it except for extra constraint
+# values merged into its configuration. Used to derive `:exec-opt` from
+# `prelude//platforms:default` below, without having to reimplement that
+# rule's own executor_config (remote-exec settings, path separators,
+# etc.) - we just read it back off `base` and reuse it verbatim, so this
+# stays correct even if that vendored rule's own executor_config logic
+# ever changes.
+load("@prelude//cfg/exec_platform:marker.bzl", "get_exec_platform_marker")
+load("@prelude//haskell:per_module_worker.bzl", "has_per_module_worker")
+
+# The execution platform's executor config. Without a cache or persistent
+# workers, it is the base platform's config. With either, every action runs
+# locally, and nothing runs remotely. With `cache`, the actions' results are
+# looked up in, and uploaded to, a remote action cache (the one that
+# `[buck2_re_client]` in the buckconfig points to). With
+# `persistent_workers`, an action that names a persistent worker may run in
+# that worker.
+def _executor_config(base: ExecutionPlatformInfo, cache: bool, persistent_workers: bool):
+    if not cache and not persistent_workers:
+        return base.executor_config
+    return CommandExecutorConfig(
+        local_enabled = True,
+        remote_enabled = False,
+        remote_cache_enabled = cache,
+        allow_cache_uploads = cache,
+        # Look up the per-module compiles by their dep files too (see Note
+        # [Early cut-off by dep files] in prelude/haskell/compile_per_module.bzl).
+        remote_dep_file_cache_enabled = cache,
+        use_persistent_workers = persistent_workers,
+    )
+
+def _execution_platform_with_constraints_impl(ctx: AnalysisContext) -> list[Provider]:
+    base = ctx.attrs.base[ExecutionPlatformInfo]
+    constraints = dict(base.configuration.constraints)
+    for constraint_value in ctx.attrs.constraint_values:
+        info = constraint_value[ConstraintValueInfo]
+        constraints[info.setting.label] = info
+
+    cfg = ConfigurationInfo(constraints = constraints, values = {})
+    name = ctx.label.raw_target()
+    platform = ExecutionPlatformInfo(
+        label = name,
+        configuration = cfg,
+        executor_config = _executor_config(base, ctx.attrs.cache, ctx.attrs.persistent_workers),
+    )
+
+    return [
+        DefaultInfo(),
+        platform,
+        PlatformInfo(label = str(name), configuration = cfg),
+        ExecutionPlatformRegistrationInfo(
+            platforms = [platform],
+            exec_marker_constraint = get_exec_platform_marker(),
+        ),
+    ]
+
+execution_platform_with_constraints = rule(
+    impl = _execution_platform_with_constraints_impl,
+    attrs = {
+        "base": attrs.dep(providers = [ExecutionPlatformInfo]),
+        "constraint_values": attrs.list(attrs.dep(providers = [ConstraintValueInfo]), default = []),
+        # `[cabal_buck2] cache = true` in the buckconfig (.buckconfig.local,
+        # where `cabal buck2 --cache=ADDRESS` writes it together with the
+        # remote cache's address).
+        "cache": attrs.bool(default = read_root_config("cabal_buck2", "cache", "false") == "true"),
+        # Whether actions may run in persistent workers. This is on when the
+        # buckconfig sets up a worker for the per-module compiles (see
+        # prelude/haskell/per_module_worker.bzl).
+        "persistent_workers": attrs.bool(default = has_per_module_worker()),
+    },
+)
+
+# `.buckconfig`'s `[build] execution_platforms` takes exactly one target
+# pattern, not a list - buck2 gets multiple candidate execution
+# platforms from that *one* target's own `ExecutionPlatformRegistrationInfo.
+# platforms` list instead (confirmed directly: pointing it at two
+# space-separated targets fails to parse as a target pattern at all).
+# This aggregates any number of platform deps into one such list, in the
+# order given - buck2 picks the first one in that order compatible with
+# a given target's `exec_compatible_with`.
+def _execution_platforms_impl(ctx: AnalysisContext) -> list[Provider]:
+    platforms = [p[ExecutionPlatformInfo] for p in ctx.attrs.platforms]
+    return [
+        DefaultInfo(),
+        ExecutionPlatformRegistrationInfo(
+            platforms = platforms,
+            exec_marker_constraint = get_exec_platform_marker(),
+        ),
+    ]
+
+execution_platforms = rule(
+    impl = _execution_platforms_impl,
+    attrs = {
+        "platforms": attrs.list(attrs.dep(providers = [ExecutionPlatformInfo])),
+    },
+)
diff --git a/buck2/prelude/.buckconfig b/buck2/prelude/.buckconfig
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/.buckconfig
@@ -0,0 +1,38 @@
+[repositories]
+prelude = .
+
+# We want to disable the following values when we don't have open source,
+# but our custom config format (yuk) doesn't accept inline comments.
+# Therefore, we hide the name of the group when not open source.
+
+[repository_aliases]
+[not_repository_aliases] # @oss-enable
+config = ovr_config
+
+# Some sort of defaults to make ovrsource macros stop complaining.
+[ovrsource]
+
+[java]
+  bootclasspath_8 = fbsource//xplat/third-party/java/jdk8:jce-stub fbsource//xplat/third-party/java/jdk8:jsse-stub fbsource//xplat/third-party/java/jdk8:rt-stub
+  javacd_dep_files = per_class
+  source_level = 8
+  src_roots = /fbandroid/instrumentation_tests/, src, test, java, javatests, src-gen, src-test, tests, javatestgen, testgen
+  target_level = 8
+
+[kotlin]
+  enable_incremental_compilation = true
+  frontend_compiler = defined_by_target
+  kotlin_home = $(config fbsource.repo_relative_path)/xplat/toolchains/android/sdk/third-party/java/kotlin/$(config kotlin.kotlin_version)
+  kotlin_version = 2.2.0
+  kotlin_version_for_upgrade_only_do_not_use = 2.2.0
+  kotlincd_dep_files = per_class
+  ksp_version = 2.0.2
+  ksp_version_for_upgrade_only_do_not_use=2.0.2
+  min_language_version_for_dcg = 1.9
+  min_language_version_for_jvm_abi_gen = 1.9
+  track_class_usage = true
+
+[http]
+[not_http] # @oss-enable
+  # Internal Maven mirror
+  maven_repo = https://maven.thefacebook.com/nexus/content/groups/public
diff --git a/buck2/prelude/BUCK b/buck2/prelude/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/BUCK
@@ -0,0 +1,69 @@
+load("@prelude//:none.bzl", "none_rule")
+load("@prelude//transitions:constraint_override_registry.bzl", "constraint_override_refs", "constraint_override_registry")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load(":native.bzl", prelude = "native")
+
+oncall("build_infra")
+
+source_listing(
+    exclude = [
+        # Exclude PACKAGE file using modifiers since those are not enabled everywhere yet.
+        "PACKAGE",
+    ]
+)
+
+# Done to avoid triggering a lint rule that replaces glob with an fbcode macro
+globby = glob
+
+srcs = globby(
+    ["**"],
+    # Context: https://fb.workplace.com/groups/buck2users/posts/3121903854732641/
+    exclude = [
+        "**/.pyre_configuration.local",
+        # Unfortunately, using modifiers require loading bzl files in outside of prelude,
+        # and that currently breaks isolated tests that attempt to grab a best-effort prelude
+        # from the filegroup below.
+        # TODO: Switch these tests to use the bundled prelude instead.
+        "PACKAGE",
+    ],
+)
+
+# Re-export filegroups that are behind package boundary violations for
+# Buck2.
+prelude.filegroup(
+    name = "files",
+    srcs = srcs,
+    visibility = ["PUBLIC"],
+)
+
+# Tests want BUCK.v2 instead of TARGETS.v2
+prelude.genrule(
+    name = "copy_android_constraint",
+    out = "BUCK",
+    cmd = "cp $(location prelude//android/constraints:files)/BUCK $OUT",
+    visibility = ["PUBLIC"],
+)
+
+prelude.filegroup(
+    name = "prelude",
+    srcs = {
+        "": ":files",
+        "android/constraints/BUCK": ":copy_android_constraint",
+        # explicitly include files that fall off the glob due to package boundary violations
+        "cfg/exec_platform/marker/BUCK": "//cfg/exec_platform/marker:buck_file",
+        # @oss-disable[end= ]: "python/meta_only/config.bzl": "//python/meta_only:config.bzl",
+        "rust/tools/attrs.bzl": "//rust/tools:attrs.bzl",
+    },
+    visibility = ["PUBLIC"],
+)
+
+none_rule(
+    name = "none",
+    visibility = ["PUBLIC"],
+)
+
+constraint_override_registry(
+    name = "constraint_override_registry",
+    refs = constraint_override_refs(),
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/LICENSE-APACHE b/buck2/prelude/LICENSE-APACHE
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/LICENSE-APACHE
@@ -0,0 +1,201 @@
+Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
diff --git a/buck2/prelude/LICENSE-MIT b/buck2/prelude/LICENSE-MIT
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/LICENSE-MIT
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) Meta Platforms, Inc. and affiliates.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/buck2/prelude/abi/BUCK b/buck2/prelude/abi/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/abi/BUCK
@@ -0,0 +1,29 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+config_setting(
+    name = "gnu",
+    constraint_values = [
+        "prelude//abi/constraints:gnu",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "msvc",
+    constraint_values = [
+        "prelude//abi/constraints:msvc",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "musl",
+    constraint_values = [
+        "prelude//abi/constraints:musl",
+    ],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/abi/constraints/BUCK b/buck2/prelude/abi/constraints/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/abi/constraints/BUCK
@@ -0,0 +1,20 @@
+load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+# Used by open source projects to support `prelude//`
+
+constraint_with_aliases(
+    name = "abi",
+    aliases = {
+        "gnu": "gnu",
+        "msvc": "msvc",
+        "musl": "musl",
+    },
+    default = "unspecified",
+    values = ["gnu", "msvc", "musl", "unspecified"],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/alias.bzl b/buck2/prelude/alias.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/alias.bzl
@@ -0,0 +1,28 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Implementation of aliases build rules.
+
+def alias_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs.actual:
+        return ctx.attrs.actual.providers
+    else:
+        return [DefaultInfo()]
+
+def configured_alias_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs.configured_actual != None and ctx.attrs.fallback_actual != None:
+        fail("cannot set both of `configured_actual` and `fallback_actual`")
+    if ctx.attrs.configured_actual != None:
+        return ctx.attrs.configured_actual.providers
+    if ctx.attrs.fallback_actual != None:
+        return ctx.attrs.fallback_actual.providers
+    fail("must set one of `configured_actual` or `fallback_actual`")
+
+def versioned_alias_impl(_ctx: AnalysisContext) -> list[Provider]:
+    # Should be intercepted in macro stub and converted to `alias`.
+    fail("unsupported")
diff --git a/buck2/prelude/android/aapt2_link.bzl b/buck2/prelude/android/aapt2_link.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/aapt2_link.bzl
@@ -0,0 +1,209 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_providers.bzl", "Aapt2LinkInfo", "AndroidResourceInfo", "RESOURCE_PRIORITY_LOW")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+
+BASE_PACKAGE_ID = 0x7F
+
+def normalize_locale(locale: str) -> str:
+    if locale == "NONE":
+        return "en"
+    if regex("^[a-z][a-z]$").match(locale):
+        return locale
+    if regex("^[a-z][a-z]_[A-Z][A-Z]$").match(locale):
+        # This transforms locales from xx_YY to xx-rYY.
+        # E.g.: like "zh_CN" to "zh-rCN".
+        return locale[:2] + "-r" + locale[-2:]
+    if regex("^[a-z][a-z]-r[A-Z][A-Z]$").match(locale):
+        # Already in xx-rYY format
+        return locale
+    fail("Invalid locale format passed: {} {}".format(locale, regex("/^[a-z][a-z]$/").match(locale)))
+
+def get_aapt2_link(
+    ctx: AnalysisContext,
+    android_toolchain: AndroidToolchainInfo,
+    resource_infos: list[AndroidResourceInfo],
+    android_manifest: Artifact,
+    manifest_entries: dict,
+    includes_vector_drawables: bool,
+    no_resource_removal: bool,
+    should_keep_raw_values: bool,
+    package_id_offset: int,
+    resource_stable_ids: Artifact | None,
+    preferred_density: [str, None],
+    filter_locales: bool,
+    locales: list[str],
+    compiled_resource_apks: list[Artifact],
+    additional_aapt2_params: list[str],
+    extra_filtered_resources: list[str],
+) -> (Aapt2LinkInfo, Aapt2LinkInfo):
+    link_infos = []
+    for use_proto_format in [False, True]:
+        if use_proto_format:
+            identifier = "use_proto"
+        else:
+            identifier = "not_proto"
+
+        aapt2_command = cmd_args(android_toolchain.aapt2)
+        aapt2_command.add("link")
+
+        # aapt2 only supports @ for -R or input files, not for all args, so we pass in all "normal"
+        # args here.
+        resources_apk = ctx.actions.declare_output("{}/resource-apk.ap_".format(identifier), has_content_based_path = False)
+        aapt2_command.add(["-o", resources_apk.as_output()])
+        proguard_config = ctx.actions.declare_output("{}/proguard_config.pro".format(identifier), has_content_based_path = False)
+        aapt2_command.add(["--proguard", proguard_config.as_output()])
+
+        # We don't need the R.java output, but aapt2 won't output R.txt unless we also request R.java.
+        # A drawback of this is that the directory structure for the R.java output is deep, resulting
+        # in long path issues on Windows. The structure is <path to target>/<identifier>/unused-rjava/<package>/R.java
+        # We can declare a custom dummy package to drastically shorten <package>, which is sketchy, but effective
+        r_dot_java = ctx.actions.declare_output("{}/unused-rjava".format(identifier), dir = True, has_content_based_path = False)
+        aapt2_command.add(["--java", r_dot_java.as_output()])
+        aapt2_command.add(["--custom-package", "dummy.package"])
+
+        r_dot_txt = ctx.actions.declare_output("{}/R.txt".format(identifier), has_content_based_path = False)
+        aapt2_command.add(["--output-text-symbols", r_dot_txt.as_output()])
+
+        aapt2_command.add(["--manifest", android_manifest])
+        aapt2_command.add(["-I", android_toolchain.android_jar])
+
+        if includes_vector_drawables:
+            aapt2_command.add("--no-version-vectors")
+        aapt2_command.add("--auto-add-overlay")
+        if use_proto_format:
+            aapt2_command.add("--proto-format")
+        if no_resource_removal:
+            aapt2_command.add("--no-resource-removal")
+        if should_keep_raw_values:
+            aapt2_command.add("--keep-raw-values")
+        if package_id_offset != 0:
+            aapt2_command.add(["--package-id", "0x{}".format(BASE_PACKAGE_ID + package_id_offset)])
+        if resource_stable_ids != None:
+            aapt2_command.add(["--stable-ids", resource_stable_ids])
+        if preferred_density != None:
+            aapt2_command.add(["--preferred-density", preferred_density])
+
+        manifest_entries_min_sdk = manifest_entries.get("min_sdk_version", None)
+        if manifest_entries_min_sdk != None:
+            aapt2_command.add(["--min-sdk-version", str(manifest_entries_min_sdk)])
+        manifest_entries_target_sdk = manifest_entries.get("target_sdk_version", None)
+        if manifest_entries_target_sdk != None:
+            aapt2_command.add(["--target-sdk-version", str(manifest_entries_target_sdk)])
+        manifest_entries_version_code = manifest_entries.get("version_code", None)
+        if manifest_entries_version_code != None:
+            aapt2_command.add(["--version-code", manifest_entries_version_code])
+        manifest_entries_version_name = manifest_entries.get("version_name", None)
+        if manifest_entries_version_name != None:
+            aapt2_command.add(["--version-name", manifest_entries_version_name])
+        manifest_entries_debug_mode = str(manifest_entries.get("debug_mode", "False")).lower() == "true"
+        if manifest_entries_debug_mode:
+            aapt2_command.add(["--debug-mode"])
+
+        if filter_locales and len(locales) > 0:
+            for locale in locales:
+                aapt2_command.add(["-c", normalize_locale(locale)])
+
+        for compiled_resource_apk in compiled_resource_apks:
+            aapt2_command.add(["-I", compiled_resource_apk])
+
+        # put low priority resources first so that they get overwritten by higher priority resources
+        low_priority_aapt2_compile_rules = []
+        normal_priority_aapt2_compile_rules = []
+        for resource_info in resource_infos:
+            if resource_info.aapt2_compile_output:
+                (low_priority_aapt2_compile_rules if resource_info.res_priority == RESOURCE_PRIORITY_LOW else normal_priority_aapt2_compile_rules).append(
+                    resource_info.aapt2_compile_output
+                )
+        aapt2_compile_rules = low_priority_aapt2_compile_rules + normal_priority_aapt2_compile_rules
+
+        aapt2_compile_rules_args_file = ctx.actions.write(
+            "{}/aapt2_compile_rules_args_file".format(identifier), cmd_args(aapt2_compile_rules, delimiter = " "), has_content_based_path = False
+        )
+        aapt2_command.add("-R")
+        aapt2_command.add(
+            cmd_args(
+                aapt2_compile_rules_args_file,
+                format = "@{}",
+                hidden = aapt2_compile_rules,
+            )
+        )
+
+        aapt2_command.add(additional_aapt2_params)
+
+        ctx.actions.run(aapt2_command, category = "aapt2_link", identifier = identifier, allow_cache_upload = True, error_handler = aapt_link_error_handler)
+
+        # The normal resource filtering apparatus is super slow, because it extracts the whole apk,
+        # strips files out of it, then repackages it.
+        #
+        # This is a faster filtering step that just uses zip -d to remove entries from the archive.
+        # It's also superbly dangerous.
+        #
+        # If zip -d returns that there was nothing to do, then we don't fail.
+        if len(extra_filtered_resources) > 0:
+            filtered_resources_apk = ctx.actions.declare_output("{}/filtered-resource-apk.ap_".format(identifier), has_content_based_path = False)
+            filter_resources_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].aapt2_filter_resources)
+            filter_resources_cmd.add(cmd_args(resources_apk, format = "--input-apk={}"))
+            filter_resources_cmd.add(cmd_args(filtered_resources_apk.as_output(), format = "--output-apk={}"))
+            filter_resources_cmd.add(cmd_args(extra_filtered_resources, format = "--extra-filtered-resources={}"))
+            ctx.actions.run(filter_resources_cmd, category = "aapt2_filter_resources", identifier = identifier, allow_cache_upload = True)
+            primary_resources_apk = filtered_resources_apk
+        else:
+            primary_resources_apk = resources_apk
+
+        link_infos.append(
+            Aapt2LinkInfo(
+                primary_resources_apk = primary_resources_apk,
+                proguard_config_file = proguard_config,
+                r_dot_txt = r_dot_txt,
+            )
+        )
+
+    return link_infos[0], link_infos[1]
+
+def get_module_manifest_in_proto_format(
+    ctx: AnalysisContext, android_toolchain: AndroidToolchainInfo, android_manifest: Artifact, primary_resources_apk: Artifact, module_name: str
+) -> Artifact:
+    aapt2_command = cmd_args(android_toolchain.aapt2)
+    aapt2_command.add("link")
+
+    # aapt2 only supports @ for -R or input files, not for all args, so we pass in all "normal"
+    # args here.
+    resources_apk = ctx.actions.declare_output("{}/resource-apk.ap_".format(module_name), has_content_based_path = False)
+    aapt2_command.add(["-o", resources_apk.as_output()])
+    aapt2_command.add(["--manifest", android_manifest])
+    aapt2_command.add(["-I", android_toolchain.android_jar])
+    aapt2_command.add(["-I", primary_resources_apk])
+    aapt2_command.add("--proto-format")
+
+    ctx.actions.run(aapt2_command, category = "aapt2_link", identifier = module_name, allow_cache_upload = True, error_handler = aapt_link_error_handler)
+
+    proto_manifest_dir = ctx.actions.declare_output("{}/proto_format_manifest".format(module_name), has_content_based_path = False)
+    proto_manifest = proto_manifest_dir.project("AndroidManifest.xml")
+    ctx.actions.run(
+        cmd_args(["unzip", resources_apk, "AndroidManifest.xml", "-d", proto_manifest_dir.as_output()]),
+        category = "unzip_proto_format_manifest",
+        identifier = module_name,
+        allow_cache_upload = True,
+    )
+
+    return proto_manifest
+
+def aapt_link_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:
+    errors = []
+    lowercase_stderr = ctx.stderr.lower()
+    if regex(r"failed to write .* to archive").match(lowercase_stderr):
+        errors.append(
+            ctx.new_sub_error(
+                category = "aapt2_link",
+                message = "Most probably there are too many res files in the apk (over 65535). Try filtering out some resources.",
+                show_in_stderr = True,
+            )
+        )
+    return errors
diff --git a/buck2/prelude/android/android.bzl b/buck2/prelude/android/android.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android.bzl
@@ -0,0 +1,43 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":android_aar.bzl", "android_aar_impl")
+load(":android_apk.bzl", "android_apk_impl")
+load(":android_build_config.bzl", "android_build_config_impl")
+load(":android_bundle.bzl", "android_bundle_impl")
+load(":android_instrumentation_apk.bzl", "android_instrumentation_apk_impl")
+load(":android_instrumentation_test.bzl", "android_instrumentation_test_impl")
+load(":android_library.bzl", "android_library_impl")
+load(":android_manifest.bzl", "android_manifest_impl")
+load(":android_prebuilt_aar.bzl", "android_prebuilt_aar_impl")
+load(":android_resource.bzl", "android_resource_impl")
+load(":apk_genrule.bzl", "apk_genrule_impl")
+load(":gen_aidl.bzl", "gen_aidl_impl")
+load(":keystore.bzl", "keystore_impl")
+load(":prebuilt_native_library.bzl", "prebuilt_native_library_impl")
+load(":robolectric_test.bzl", "robolectric_test_impl")
+load(":voltron.bzl", "android_app_modularity_impl")
+
+implemented_rules = {
+    "android_aar": android_aar_impl,
+    "android_app_modularity": android_app_modularity_impl,
+    "android_binary": android_apk_impl,
+    "android_build_config": android_build_config_impl,
+    "android_bundle": android_bundle_impl,
+    "android_instrumentation_apk": android_instrumentation_apk_impl,
+    "android_instrumentation_test": android_instrumentation_test_impl,
+    "android_library": android_library_impl,
+    "android_manifest": android_manifest_impl,
+    "android_prebuilt_aar": android_prebuilt_aar_impl,
+    "android_resource": android_resource_impl,
+    "apk_genrule": apk_genrule_impl,
+    "gen_aidl": gen_aidl_impl,
+    "keystore": keystore_impl,
+    "prebuilt_native_library": prebuilt_native_library_impl,
+    "robolectric_test": robolectric_test_impl,
+}
diff --git a/buck2/prelude/android/android_aar.bzl b/buck2/prelude/android/android_aar.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_aar.bzl
@@ -0,0 +1,203 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_binary.bzl", "get_build_config_java_libraries")
+load("@prelude//android:android_binary_native_library_rules.bzl", "get_android_binary_native_library_info")
+load("@prelude//android:android_binary_resources_rules.bzl", "get_cxx_resources", "get_manifest")
+load(
+    "@prelude//android:android_providers.bzl",
+    "AndroidResourceInfo",
+    "ExportedAndroidResourceInfo",
+    "get_all_android_packageable_targets",
+    "merge_android_packageable_info",
+)
+load("@prelude//android:android_resource.bzl", "get_text_symbols")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:configuration.bzl", "get_deps_by_platform")
+load("@prelude//android:cpu_filters.bzl", "CPU_FILTER_FOR_DEFAULT_PLATFORM", "CPU_FILTER_FOR_PRIMARY_PLATFORM")
+load("@prelude//android:util.bzl", "create_enhancement_context")
+load("@prelude//java:java_providers.bzl", "create_java_packaging_dep", "get_all_java_packaging_deps", "get_all_java_packaging_deps_from_packaging_infos")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//target_stats:target_stats.bzl", "target_stats_aggregate_providers_and_subtargets")
+load("@prelude//utils:argfile.bzl", "argfile")
+load("@prelude//utils:utils.bzl", "flatten")
+
+def android_aar_impl(ctx: AnalysisContext) -> list[Provider]:
+    deps_by_platform = get_deps_by_platform(ctx)
+    primary_platform = CPU_FILTER_FOR_PRIMARY_PLATFORM if CPU_FILTER_FOR_PRIMARY_PLATFORM in deps_by_platform else CPU_FILTER_FOR_DEFAULT_PLATFORM
+    deps = deps_by_platform[primary_platform]
+
+    excluded_java_packaging_deps = get_all_java_packaging_deps(ctx, ctx.attrs.excluded_java_deps)
+    excluded_java_packaging_deps_targets = set([excluded_dep.label.raw_target() for excluded_dep in excluded_java_packaging_deps])
+    java_packaging_deps = [
+        packaging_dep
+        for packaging_dep in get_all_java_packaging_deps(ctx, deps)
+        if packaging_dep.label.raw_target() not in excluded_java_packaging_deps_targets
+    ]
+    android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, deps)
+
+    excluded_android_packageable_targets = set(get_all_android_packageable_targets(ctx.attrs.excluded_java_deps))
+    manifest_infos = android_packageable_info.manifests.traverse(ordering = "topological") if android_packageable_info.manifests else []
+    manifests = [manifest_info.manifest for manifest_info in manifest_infos if manifest_info.target_label not in excluded_android_packageable_targets]
+    android_manifest = get_manifest(ctx, manifests, ctx.attrs.manifest_entries, should_replace_application_id_placeholders = False)
+
+    if ctx.attrs.include_build_config_class:
+        build_config_infos = list(android_packageable_info.build_config_infos.traverse()) if android_packageable_info.build_config_infos else []
+        java_packaging_deps.extend(
+            get_all_java_packaging_deps_from_packaging_infos(
+                ctx,
+                get_build_config_java_libraries(ctx, build_config_infos, package_type = "release", exopackage_modes = []),
+            )
+        )
+
+    enhancement_ctx = create_enhancement_context(ctx)
+    android_binary_native_library_info = get_android_binary_native_library_info(
+        enhancement_ctx,
+        android_packageable_info,
+        deps_by_platform,
+        prebuilt_native_library_dirs_to_exclude = excluded_android_packageable_targets,
+        shared_libraries_to_exclude = excluded_android_packageable_targets,
+        native_library_merge_glue = getattr(ctx.attrs, "native_library_merge_glue", None),
+        native_library_merge_sequence = getattr(ctx.attrs, "native_library_merge_sequence", None),
+        native_library_merge_map = getattr(ctx.attrs, "native_library_merge_map", None),
+        native_library_merge_non_asset_libs = getattr(ctx.attrs, "native_library_merge_non_asset_libs", False),
+        native_library_merge_linker_args = getattr(ctx.attrs, "native_library_merge_linker_args", None),
+        native_library_merge_linker_args_all = getattr(ctx.attrs, "native_library_merge_linker_args_all", None),
+        native_library_merge_code_generator = getattr(ctx.attrs, "native_library_merge_code_generator", None),
+        native_library_merge_sequence_blocklist = getattr(ctx.attrs, "native_library_merge_sequence_blocklist", None),
+    )
+    java_packaging_deps.extend([
+        create_java_packaging_dep(
+            ctx,
+            library_output,
+        )
+        for library_output in android_binary_native_library_info.generated_java_code
+    ])
+
+    jars = [dep.jar for dep in java_packaging_deps if dep.jar]
+    classes_jar = ctx.actions.declare_output("classes.jar", has_content_based_path = False)
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    classes_jar_cmd = cmd_args([
+        java_toolchain.jar_builder,
+        "--entries-to-jar",
+        argfile(actions = ctx.actions, name = "classes_jar_entries.txt", args = jars),
+        "--output",
+        classes_jar.as_output(),
+    ])
+
+    if ctx.attrs.remove_classes:
+        remove_classes_file = ctx.actions.write("remove_classes.txt", ctx.attrs.remove_classes, has_content_based_path = False)
+        classes_jar_cmd.add([
+            "--blocklist-patterns",
+            remove_classes_file,
+            "--blocklist-patterns-matcher",
+            "remove_classes_patterns_matcher",
+        ])
+
+    ctx.actions.run(classes_jar_cmd, category = "create_classes_jar")
+
+    sub_targets = {}
+    dependency_sources_jars = [dep.sources_jar for dep in java_packaging_deps if dep.sources_jar]
+    if dependency_sources_jars:
+        combined_sources_jar = ctx.actions.declare_output("sources.jar", has_content_based_path = False)
+        java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+        combined_sources_jar_cmd = cmd_args([
+            java_toolchain.jar_builder,
+            "--entries-to-jar",
+            argfile(actions = ctx.actions, name = "combined_sources_jar_entries.txt", args = dependency_sources_jars),
+            "--output",
+            combined_sources_jar.as_output(),
+        ])
+
+        if ctx.attrs.remove_classes:
+            remove_classes_file = ctx.actions.write("sources_remove_classes.txt", ctx.attrs.remove_classes, has_content_based_path = False)
+            combined_sources_jar_cmd.add([
+                "--blocklist-patterns",
+                remove_classes_file,
+                "--blocklist-patterns-matcher",
+                "remove_classes_patterns_matcher",
+            ])
+
+        ctx.actions.run(combined_sources_jar_cmd, category = "create_sources_jar")
+        sub_targets["sources.jar"] = [DefaultInfo(default_output = combined_sources_jar)]
+
+    entries = [android_manifest, classes_jar]
+
+    all_resource_infos = list(android_packageable_info.resource_infos.traverse()) if android_packageable_info.resource_infos else []
+    resource_infos = [resource_info for resource_info in all_resource_infos if resource_info.raw_target not in excluded_android_packageable_targets]
+
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+    if resource_infos:
+        res_dirs = [resource_info.res for resource_info in resource_infos if resource_info.res]
+        if ctx.attrs.package_resources and res_dirs:
+            merged_resource_sources_dir = ctx.actions.declare_output("merged_resource_sources_dir/res", dir = True, has_content_based_path = False)
+            merge_resource_sources_cmd = cmd_args([
+                android_toolchain.merge_android_resource_sources[RunInfo],
+                "--resource-paths",
+                argfile(actions = ctx.actions, name = "resource_paths.txt", args = res_dirs),
+                "--output",
+                merged_resource_sources_dir.as_output(),
+            ])
+
+            ctx.actions.run(merge_resource_sources_cmd, category = "merge_android_resource_sources")
+
+            r_dot_txt = get_text_symbols(
+                ctx, merged_resource_sources_dir, [dep for dep in deps if AndroidResourceInfo in dep or ExportedAndroidResourceInfo in dep]
+            )
+            entries.extend([merged_resource_sources_dir, r_dot_txt])
+
+        assets_dirs = flatten([resource_infos.assets for resource_infos in resource_infos])
+        entries.extend(assets_dirs)
+
+    cxx_resources = get_cxx_resources(ctx, deps, dir_name = "assets")
+    if cxx_resources:
+        entries.append(cxx_resources)
+
+    native_libs_file = argfile(actions = ctx.actions, name = "native_libs_entries.txt", args = android_binary_native_library_info.native_libs_for_primary_apk)
+    native_libs_assets_file = argfile(
+        actions = ctx.actions, name = "native_libs_assets_entries.txt", args = android_binary_native_library_info.root_module_native_lib_assets
+    )
+
+    entries_file = ctx.actions.write("entries.txt", entries, has_content_based_path = False)
+
+    aar = ctx.actions.declare_output("{}.aar".format(ctx.label.name), has_content_based_path = False)
+    create_aar_cmd = cmd_args(
+        [
+            android_toolchain.aar_builder,
+            "--output_path",
+            aar.as_output(),
+            "--entries_file",
+            entries_file,
+            "--on_duplicate_entry",
+            "fail",
+            "--native_libs_file",
+            native_libs_file,
+            "--native_libs_assets_file",
+            native_libs_assets_file,
+        ],
+        hidden = [
+            entries,
+        ],
+    )
+    if ctx.attrs.proguard_config:
+        create_aar_cmd.add([
+            "--proguard_config_file",
+            ctx.attrs.proguard_config,
+        ])
+
+    if ctx.attrs.hardcode_permissions_for_deterministic_output == True:
+        create_aar_cmd.add([
+            "--hardcode_permissions_for_deterministic_output",
+        ])
+
+    ctx.actions.run(create_aar_cmd, category = "create_aar")
+
+    target_stats_providers, target_stats_subtargets = target_stats_aggregate_providers_and_subtargets(ctx, deps = deps)
+    sub_targets.update(target_stats_subtargets)
+
+    return [DefaultInfo(default_outputs = [aar], sub_targets = enhancement_ctx.get_sub_targets() | sub_targets)] + target_stats_providers
diff --git a/buck2/prelude/android/android_apk.bzl b/buck2/prelude/android/android_apk.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_apk.bzl
@@ -0,0 +1,335 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")
+load("@prelude//android:android_binary.bzl", "get_binary_info")
+load(
+    "@prelude//android:android_providers.bzl",
+    "AndroidApkExopackageInfo",
+    "AndroidApkInfo",
+    "AndroidApkUnderTestInfo",
+    "AndroidBinaryNativeLibsInfo",
+    "AndroidBinaryPrimaryPlatformInfo",
+    "AndroidBinaryResourcesInfo",
+    "DexFilesInfo",
+    "ExopackageInfo",
+    "KeystoreInfo",
+)
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:util.bzl", "package_validators_decorator")
+load("@prelude//java:class_to_srcs.bzl", "merge_class_to_source_map_from_jar")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")
+load("@prelude//java/utils:java_utils.bzl", "get_class_to_source_map_info")
+load("@prelude//target_stats:target_stats.bzl", "target_stats_aggregate_providers_and_subtargets")
+load("@prelude//utils:argfile.bzl", "argfile")
+load("@prelude//utils:utils.bzl", "flatten")
+
+def android_apk_impl(ctx: AnalysisContext) -> list[Provider]:
+    android_binary_info = get_binary_info(ctx, use_proto_format = False)
+    java_packaging_deps = android_binary_info.java_packaging_deps
+    sub_targets = android_binary_info.sub_targets
+    dex_files_info = android_binary_info.dex_files_info
+    native_library_info = android_binary_info.native_library_info
+    resources_info = android_binary_info.resources_info
+    validation_outputs = android_binary_info.validation_outputs
+
+    wrapped_build_apk = package_validators_decorator(
+        ctx,
+        build_apk,
+        extension = ".apk",
+    )
+
+    keystore = ctx.attrs.keystore[KeystoreInfo]
+    output_apk = wrapped_build_apk(
+        output_filename = ctx.label.name,
+        actions = ctx.actions,
+        android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo],
+        keystore = keystore,
+        dex_files_info = dex_files_info,
+        native_library_info = native_library_info,
+        resources_info = resources_info,
+        compress_resources_dot_arsc = ctx.attrs.resource_compression == "enabled" or ctx.attrs.resource_compression == "enabled_with_strings_as_assets",
+        validation_deps_outputs = get_validation_deps_outputs(ctx) + validation_outputs,
+        packaging_options = ctx.attrs.packaging_options,
+        # Exclude BUCK_BUILD_ID from assets/BuildInfo.json for release builds.
+        include_build_info_file = ctx.attrs.include_build_info_file and ctx.attrs.package_type != "release",
+    )
+
+    if dex_files_info.secondary_dex_exopackage_info or native_library_info.exopackage_info or resources_info.exopackage_info:
+        exopackage_info = ExopackageInfo(
+            secondary_dex_info = dex_files_info.secondary_dex_exopackage_info,
+            native_library_info = native_library_info.exopackage_info,
+            resources_info = resources_info.exopackage_info,
+        )
+        default_output = ctx.actions.write(
+            "{}_exopackage_apk_warning".format(ctx.label.name),
+            "exopackage apks should not be used externally, try buck install or building with exopackage disabled\n",
+            has_content_based_path = False,
+        )
+        sub_targets["exo_apk"] = [DefaultInfo(default_output = output_apk)]  # Used by tests
+    else:
+        exopackage_info = None
+        default_output = output_apk
+
+    class_to_srcs, _, class_to_srcs_subtargets = get_class_to_source_map_info(
+        ctx,
+        outputs = None,
+        deps = android_binary_info.deps_by_platform[android_binary_info.primary_platform],
+    )
+    transitive_class_to_src_map = merge_class_to_source_map_from_jar(
+        actions = ctx.actions,
+        name = ctx.label.name + ".transitive_class_to_src.json",
+        java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo],
+        relative_to = None,
+        deps = [class_to_srcs],
+    )
+    sub_targets["transitive_class_to_src_map"] = [DefaultInfo(default_output = transitive_class_to_src_map)]
+
+    # We can only be sure that an APK has native libs if it has any shared libraries. Prebuilt native libraries dirs can exist but be empty.
+    definitely_has_native_libs = bool(native_library_info.shared_libraries)
+
+    install_info = get_install_info(
+        ctx, output_apk = output_apk, manifest = resources_info.manifest, exopackage_info = exopackage_info, definitely_has_native_libs = definitely_has_native_libs
+    )
+
+    classpath = [dep.jar for dep in java_packaging_deps if dep.jar]
+    sub_targets["classpath"] = [
+        DefaultInfo(default_output = ctx.actions.write("classpath.txt", classpath, has_content_based_path = False), other_outputs = classpath)
+    ]
+    sub_targets["classpath_targets"] = [
+        DefaultInfo(
+            default_output = ctx.actions.write("classpath_targets.txt", list(set([jar.owner.raw_target() for jar in classpath])), has_content_based_path = False)
+        )
+    ]
+
+    # ctx.attrs.deps is split-transitioned here (one Dependency per ABI).
+    target_stats_providers, target_stats_subtargets = target_stats_aggregate_providers_and_subtargets(
+        ctx,
+        deps = android_binary_info.deps_by_platform[android_binary_info.primary_platform],
+    )
+    sub_targets.update(target_stats_subtargets)
+
+    providers = [
+        AndroidApkInfo(
+            apk = output_apk,
+            manifest = resources_info.manifest,
+            materialized_artifacts = android_binary_info.materialized_artifacts,
+            unstripped_shared_libraries = native_library_info.unstripped_shared_libraries,
+        ),
+        AndroidBinaryPrimaryPlatformInfo(
+            primary_platform = android_binary_info.primary_platform,
+        ),
+        AndroidApkUnderTestInfo(
+            java_packaging_deps = set([dep.label.raw_target() for dep in java_packaging_deps]),
+            keystore = keystore,
+            manifest_entries = ctx.attrs.manifest_entries,
+            min_sdk_version = ctx.attrs.min_sdk_version,
+            prebuilt_native_library_dirs = set([native_lib.raw_target for native_lib in native_library_info.prebuilt_native_library_dirs]),
+            platform_configurations = set([str(x.label.configured_target().config()) for x in flatten(android_binary_info.deps_by_platform.values())]),
+            platforms = android_binary_info.deps_by_platform.keys(),
+            primary_platform = android_binary_info.primary_platform,
+            resource_infos = set([info.raw_target for info in resources_info.unfiltered_resource_infos]),
+            r_dot_java_packages = set(
+                [info.specified_r_dot_java_package for info in resources_info.unfiltered_resource_infos if info.specified_r_dot_java_package]
+            ),
+            shared_libraries = set(native_library_info.shared_libraries),
+            # Merge map delegate
+            native_library_merge_sequence = ctx.attrs.native_library_merge_sequence,
+            native_library_merge_code_generator = ctx.attrs.native_library_merge_code_generator,
+            native_library_merge_glue = ctx.attrs.native_library_merge_glue,
+            native_library_merge_linker_args_all = ctx.attrs.native_library_merge_linker_args_all,
+            native_library_merge_linker_args = ctx.attrs.native_library_merge_linker_args,
+            native_library_merge_map = ctx.attrs.native_library_merge_map,
+            native_library_merge_non_asset_libs = ctx.attrs.native_library_merge_non_asset_libs,
+            native_library_merge_sequence_blocklist = ctx.attrs.native_library_merge_sequence_blocklist,
+        ),
+        DefaultInfo(
+            default_output = default_output,
+            other_outputs = install_info.files.values() + android_binary_info.materialized_artifacts,
+            sub_targets = sub_targets | class_to_srcs_subtargets,
+        ),
+        install_info,
+        TemplatePlaceholderInfo(
+            keyed_variables = {
+                "classpath": cmd_args(classpath, delimiter = get_path_separator_for_exec_os(ctx)),
+                "classpath_including_targets_with_no_output": cmd_args(
+                    [dep.output_for_classpath_macro for dep in java_packaging_deps], delimiter = get_path_separator_for_exec_os(ctx)
+                ),
+            },
+        ),
+        class_to_srcs,
+    ] + target_stats_providers
+
+    if android_binary_info.preprocessed_java_classes_info:
+        providers.append(android_binary_info.preprocessed_java_classes_info)
+
+    # Expose the exopackage secondary-dex dir so android_instrumentation_test can push it to the device.
+    if exopackage_info != None and exopackage_info.secondary_dex_info != None:
+        providers.append(
+            AndroidApkExopackageInfo(secondary_dex_directory = exopackage_info.secondary_dex_info.directory),
+        )
+
+    return providers
+
+def build_apk(
+    output_filename: str,
+    actions: AnalysisActions,
+    keystore: KeystoreInfo,
+    android_toolchain: AndroidToolchainInfo,
+    dex_files_info: DexFilesInfo,
+    native_library_info: AndroidBinaryNativeLibsInfo,
+    resources_info: AndroidBinaryResourcesInfo,
+    compress_resources_dot_arsc: bool = False,
+    validation_deps_outputs: [list[Artifact], None] = None,
+    packaging_options: dict | None = None,
+    include_build_info_file: bool = False,
+) -> Artifact:
+    output_apk = actions.declare_output("{}.apk".format(output_filename), has_content_based_path = False)
+
+    apk_builder_args = cmd_args(
+        android_toolchain.apk_builder[RunInfo],
+        "--output-apk",
+        output_apk.as_output(),
+        "--resource-apk",
+        resources_info.primary_resources_apk,
+        "--dex-file",
+        dex_files_info.primary_dex,
+        "--keystore-path",
+        keystore.store,
+        "--keystore-properties-path",
+        keystore.properties,
+        "--zipalign_tool",
+        android_toolchain.zipalign[RunInfo],
+        "--package-meta-inf-version-files" if android_toolchain.package_meta_inf_version_files else [],
+        "--compress-resources-dot-arsc" if compress_resources_dot_arsc else [],
+        # The outputs of validation_deps need to be added as hidden arguments
+        # to an action for the validation_deps targets to be built and enforced.
+        hidden = validation_deps_outputs or [],
+    )
+
+    asset_directories = (
+        native_library_info.root_module_native_lib_assets
+        + native_library_info.non_root_module_native_lib_assets
+        + dex_files_info.root_module_bootstrap_dex_dirs
+        + dex_files_info.root_module_secondary_dex_dirs
+        + dex_files_info.non_root_module_secondary_dex_dirs
+        + resources_info.module_manifests
+    )
+    asset_directories_file = argfile(actions = actions, name = "asset_directories.txt", args = asset_directories)
+    native_library_directories = argfile(actions = actions, name = "native_library_directories", args = native_library_info.native_libs_for_primary_apk)
+    all_zip_files = [resources_info.packaged_string_assets] if resources_info.packaged_string_assets else []
+    zip_files = argfile(actions = actions, name = "zip_files", args = all_zip_files)
+    jar_files_that_may_contain_resources = argfile(
+        actions = actions, name = "jar_files_that_may_contain_resources", args = resources_info.jar_files_that_may_contain_resources
+    )
+
+    apk_builder_args.add([
+        "--asset-directories-list",
+        asset_directories_file,
+        "--native-libraries-directories-list",
+        native_library_directories,
+        "--zip-files-list",
+        zip_files,
+        "--jar-files-that-may-contain-resources-list",
+        jar_files_that_may_contain_resources,
+    ])
+
+    # Invoke the toolchain's build-info generator from this apk packaging action (which already has
+    # every APK input) so the baked BUCK_BUILD_ID refreshes when the APK content changes and
+    # cache-hits otherwise -- no separate action. Its run command is multi-token (java -jar ...), so
+    # pass it via an argfile the apk-builder reads and execs.
+    if include_build_info_file:
+        apk_builder_args.add(
+            "--build-info-generator-args",
+            argfile(
+                actions = actions,
+                name = "build_info_generator_args",
+                args = cmd_args(android_toolchain.build_info_generator[RunInfo]),
+                allow_args = True,
+            ),
+        )
+
+    if packaging_options:
+        for key, value in packaging_options.items():
+            if key == "excluded_resources":
+                apk_builder_args.add("--excluded-resources", actions.write("excluded_resources.txt", value, has_content_based_path = False))
+            elif key == "uncompressed_files":
+                apk_builder_args.add("--uncompressed-files", actions.write("uncompressed_files.txt", value, has_content_based_path = False))
+            else:
+                fail("Only 'excluded_resources' and 'uncompressed_files' are supported in packaging_options right now!")
+
+    actions.run(apk_builder_args, category = "apk_build", allow_cache_upload = True)
+
+    return output_apk
+
+def get_install_info(
+    ctx: AnalysisContext,
+    output_apk: Artifact,
+    manifest: Artifact,
+    exopackage_info: [ExopackageInfo, None],
+    definitely_has_native_libs: bool = True,
+    apex_mode: bool = False,
+) -> InstallInfo:
+    files = {
+        ctx.attrs.name: output_apk,
+        "manifest": manifest,
+        "options": generate_install_config(ctx, apex_mode),
+    }
+
+    if exopackage_info:
+        secondary_dex_exopackage_info = exopackage_info.secondary_dex_info
+        native_library_exopackage_info = exopackage_info.native_library_info
+        resources_info = exopackage_info.resources_info
+    else:
+        secondary_dex_exopackage_info = None
+        native_library_exopackage_info = None
+        resources_info = None
+
+    if secondary_dex_exopackage_info:
+        files["secondary_dex_exopackage_info_directory"] = secondary_dex_exopackage_info.directory
+        files["secondary_dex_exopackage_info_metadata"] = secondary_dex_exopackage_info.metadata
+
+    if native_library_exopackage_info:
+        files["native_library_exopackage_info_directory"] = native_library_exopackage_info.directory
+        files["native_library_exopackage_info_metadata"] = native_library_exopackage_info.metadata
+
+    if resources_info:
+        if resources_info.assets:
+            files["resources_exopackage_assets"] = resources_info.assets
+            files["resources_exopackage_assets_hash"] = resources_info.assets_hash
+
+        files["resources_exopackage_res"] = resources_info.res
+        files["resources_exopackage_res_hash"] = resources_info.res_hash
+
+    if definitely_has_native_libs and hasattr(ctx.attrs, "cpu_filters"):
+        files["cpu_filters"] = ctx.actions.write("cpu_filters.txt", ctx.attrs.cpu_filters, has_content_based_path = False)
+
+    return InstallInfo(
+        installer = ctx.attrs._android_toolchain[AndroidToolchainInfo].installer,
+        files = files,
+    )
+
+def generate_install_config(ctx: AnalysisContext, apex_mode: bool) -> Artifact:
+    data = get_install_config(apex_mode)
+    return ctx.actions.write_json("install_android_options.json", data, has_content_based_path = False)
+
+def get_install_config(apex_mode: bool) -> dict[str, typing.Any]:
+    # TODO: read from toolchains
+    install_config = {
+        "adb_restart_on_failure": read_root_config("adb", "adb_restart_on_failure", "true"),
+        "apex_mode": apex_mode,
+        "multi_install_mode": read_root_config("adb", "multi_install_mode", "false"),
+        "staged_install_mode": read_root_config("adb", "staged_install_mode", None),
+    }
+
+    adb_executable = read_root_config("android", "adb", None)
+    if adb_executable:
+        install_config["adb_executable"] = adb_executable
+
+    return install_config
diff --git a/buck2/prelude/android/android_binary.bzl b/buck2/prelude/android/android_binary.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_binary.bzl
@@ -0,0 +1,315 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_binary_native_library_rules.bzl", "get_android_binary_native_library_info")
+load("@prelude//android:android_binary_resources_rules.bzl", "get_android_binary_resources_info")
+load("@prelude//android:android_build_config.bzl", "generate_android_build_config", "get_build_config_fields")
+load(
+    "@prelude//android:android_providers.bzl",
+    "AndroidBinaryNativeLibsInfo",  # @unused Used as type
+    "AndroidBinaryResourcesInfo",  # @unused Used as type
+    "AndroidBuildConfigInfo",  # @unused Used as type
+    "AndroidPreprocessedJavaClassesInfo",  # @unused Used as type
+    "BuildConfigField",
+    "DexFilesInfo",
+    "merge_android_packageable_info",
+)
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:configuration.bzl", "get_deps_by_platform")
+load("@prelude//android:cpu_filters.bzl", "CPU_FILTER_FOR_DEFAULT_PLATFORM", "CPU_FILTER_FOR_PRIMARY_PLATFORM")
+load("@prelude//android:dex_rules.bzl", "get_multi_dex", "get_single_primary_dex", "get_split_dex_merge_config", "merge_to_single_dex", "merge_to_split_dex")
+load("@prelude//android:duplicate_class_check.bzl", "check_for_duplicate_classes_for_non_pre_dexed_jars", "check_for_duplicate_classes_for_pre_dexed_libs")
+load("@prelude//android:exopackage.bzl", "get_exopackage_flags")
+load("@prelude//android:preprocess_java_classes.bzl", "get_preprocessed_java_classes")
+load("@prelude//android:util.bzl", "create_enhancement_context")
+load("@prelude//android:voltron.bzl", "get_target_to_module_mapping")
+load(
+    "@prelude//java:java_providers.bzl",
+    "JavaPackagingDep",  # @unused Used as type
+    "JavaPackagingInfo",
+    "create_java_packaging_dep",
+    "get_all_java_packaging_deps",
+    "get_all_java_packaging_deps_from_packaging_infos",
+)
+load("@prelude//java:proguard.bzl", "get_proguard_output")
+load("@prelude//utils:expect.bzl", "expect")
+
+AndroidBinaryInfo = record(
+    sub_targets = dict,
+    java_packaging_deps = list[JavaPackagingDep],
+    deps_by_platform = dict,
+    primary_platform = str,
+    dex_files_info = DexFilesInfo,
+    native_library_info = AndroidBinaryNativeLibsInfo,
+    resources_info = AndroidBinaryResourcesInfo,
+    materialized_artifacts = list[Artifact],
+    preprocessed_java_classes_info = AndroidPreprocessedJavaClassesInfo | None,
+    validation_outputs = list[Artifact],
+)
+
+def get_binary_info(ctx: AnalysisContext, use_proto_format: bool) -> AndroidBinaryInfo:
+    sub_targets = {}
+    materialized_artifacts = []
+    preprocessed_java_classes_info = None
+
+    deps_by_platform = get_deps_by_platform(ctx)
+    primary_platform = CPU_FILTER_FOR_PRIMARY_PLATFORM if CPU_FILTER_FOR_PRIMARY_PLATFORM in deps_by_platform else CPU_FILTER_FOR_DEFAULT_PLATFORM
+    deps = deps_by_platform[primary_platform]
+
+    target_to_module_mapping_file = get_target_to_module_mapping(ctx, deps_by_platform)
+
+    no_dx_target_labels = [no_dx_target.label.raw_target() for no_dx_target in ctx.attrs.no_dx]
+    java_packaging_deps = [packaging_dep for packaging_dep in get_all_java_packaging_deps(ctx, deps)]
+
+    android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, deps)
+    build_config_infos = list(android_packageable_info.build_config_infos.traverse()) if android_packageable_info.build_config_infos else []
+
+    build_config_libs = get_build_config_java_libraries(ctx, build_config_infos, ctx.attrs.package_type, ctx.attrs.exopackage_modes)
+    java_packaging_deps += get_all_java_packaging_deps_from_packaging_infos(ctx, build_config_libs)
+
+    has_proguard_config = (
+        ctx.attrs.proguard_config != None or ctx.attrs.android_sdk_proguard_config == "default" or ctx.attrs.android_sdk_proguard_config == "optimized"
+    )
+    should_pre_dex = not ctx.attrs.disable_pre_dex and not has_proguard_config and not ctx.attrs.preprocess_java_classes_bash
+
+    enhancement_ctx = create_enhancement_context(ctx)
+    if target_to_module_mapping_file:
+        enhancement_ctx.debug_output("module.mapping", target_to_module_mapping_file)
+
+    shared_libraries_to_exclude_set = set([label.raw_target() for label in ctx.attrs.shared_libraries_to_exclude])
+    native_library_info = get_android_binary_native_library_info(
+        enhancement_ctx,
+        android_packageable_info,
+        deps_by_platform,
+        apk_module_graph_file = target_to_module_mapping_file,
+        shared_libraries_to_exclude = shared_libraries_to_exclude_set,
+        native_library_merge_glue = getattr(ctx.attrs, "native_library_merge_glue", None),
+        native_library_merge_sequence = getattr(ctx.attrs, "native_library_merge_sequence", None),
+        native_library_merge_map = getattr(ctx.attrs, "native_library_merge_map", None),
+        native_library_merge_non_asset_libs = getattr(ctx.attrs, "native_library_merge_non_asset_libs", False),
+        native_library_merge_linker_args = getattr(ctx.attrs, "native_library_merge_linker_args", None),
+        native_library_merge_linker_args_all = getattr(ctx.attrs, "native_library_merge_linker_args_all", None),
+        native_library_merge_code_generator = getattr(ctx.attrs, "native_library_merge_code_generator", None),
+        native_library_merge_sequence_blocklist = getattr(ctx.attrs, "native_library_merge_sequence_blocklist", None),
+    )
+    java_packaging_deps.extend([
+        create_java_packaging_dep(
+            ctx,
+            library_output,
+        )
+        for library_output in native_library_info.generated_java_code
+    ])
+
+    referenced_resources_lists = (
+        [java_packaging_dep.dex.referenced_resources for java_packaging_dep in java_packaging_deps if java_packaging_dep.dex]
+        if ctx.attrs.trim_resource_ids and should_pre_dex
+        else []
+    )
+    resources_info = get_android_binary_resources_info(
+        ctx,
+        deps,
+        android_packageable_info,
+        java_packaging_deps,
+        apk_module_graph_file = target_to_module_mapping_file,
+        use_proto_format = use_proto_format,
+        referenced_resources_lists = referenced_resources_lists,
+        manifest_entries = ctx.attrs.manifest_entries,
+        generate_strings_and_ids_separately = should_pre_dex,
+        aapt2_preferred_density = ctx.attrs.aapt2_preferred_density,
+    )
+    sub_targets["manifest"] = [DefaultInfo(default_output = resources_info.manifest)]
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+    compiled_r_dot_java_deps = [
+        create_java_packaging_dep(
+            ctx,
+            r_dot_java.library_info.library_output.full_library,
+            dex_weight_factor = android_toolchain.r_dot_java_weight_factor,
+        )
+        for r_dot_java in resources_info.r_dot_java_infos
+    ]
+    java_packaging_deps += compiled_r_dot_java_deps
+    sub_targets["compiled_r_dot_java"] = [
+        DefaultInfo(
+            default_outputs = [compiled_r_dot_java_dep.jar for compiled_r_dot_java_dep in compiled_r_dot_java_deps],
+        ),
+    ]
+    for r_dot_java_info in resources_info.r_dot_java_infos:
+        sub_targets[r_dot_java_info.identifier + "_src"] = [
+            DefaultInfo(
+                default_output = r_dot_java_info.source_zipped,
+            ),
+        ]
+    validation_outputs = list(native_library_info.validation_outputs)
+    dex_java_packaging_deps = [
+        packaging_dep for packaging_dep in java_packaging_deps if packaging_dep.dex and packaging_dep.dex.dex.owner.raw_target() not in no_dx_target_labels
+    ]
+    if should_pre_dex:
+        pre_dexed_libs = [packaging_dep.dex for packaging_dep in dex_java_packaging_deps]
+        if ctx.attrs.duplicate_class_checker_enabled:
+            validation_outputs.append(
+                check_for_duplicate_classes_for_pre_dexed_libs(
+                    ctx,
+                    {str(lib.class_names.owner.raw_target()): lib.class_names for lib in pre_dexed_libs if lib.dex},
+                ),
+            )
+        if ctx.attrs.use_split_dex:
+            dex_files_info = merge_to_split_dex(
+                ctx,
+                android_toolchain,
+                pre_dexed_libs,
+                get_split_dex_merge_config(ctx, android_toolchain),
+                target_to_module_mapping_file,
+                enable_bootstrap_dexes = ctx.attrs.enable_bootstrap_dexes,
+            )
+        else:
+            dex_files_info = merge_to_single_dex(ctx, android_toolchain, pre_dexed_libs)
+    else:
+        jars_to_owners = {packaging_dep.jar: packaging_dep.jar.owner.raw_target() for packaging_dep in dex_java_packaging_deps}
+        if ctx.attrs.duplicate_class_checker_enabled:
+            validation_outputs.append(
+                check_for_duplicate_classes_for_non_pre_dexed_jars(
+                    ctx,
+                    jars_to_owners,
+                ),
+            )
+
+        if ctx.attrs.preprocess_java_classes_bash:
+            jars_to_owners, preprocessed_java_classes_info = get_preprocessed_java_classes(enhancement_ctx, jars_to_owners)
+            if preprocessed_java_classes_info:
+                materialized_artifacts.append(preprocessed_java_classes_info.materialized_artifacts_dir)
+        if has_proguard_config:
+            additional_proguard_configs = (
+                [resources_info.proguard_config_file] if not ctx.attrs.ignore_aapt_proguard_config and resources_info.proguard_config_file else []
+            )
+
+            no_dx_for_additional_jars = [no_dx for no_dx in ctx.attrs.no_dx if no_dx not in ctx.attrs.exclude_duplicate_targets_do_not_use]
+            additional_jars = (
+                android_toolchain.android_bootclasspath
+                + android_toolchain.android_optional_jars
+                + [no_dx[DefaultInfo].default_outputs[0] for no_dx in no_dx_for_additional_jars if len(no_dx[DefaultInfo].default_outputs) == 1]
+            )
+
+            proguard_output = get_proguard_output(
+                ctx,
+                jars_to_owners,
+                java_packaging_deps,
+                additional_proguard_configs,
+                additional_jars,
+                ctx.attrs.android_sdk_proguard_config,
+                android_toolchain.proguard_config,
+                android_toolchain.optimized_proguard_config,
+                android_toolchain.proguard_jar,
+                ctx.attrs.skip_proguard,
+            )
+            materialized_artifacts.extend(proguard_output.proguard_artifacts)
+            jars_to_owners = proguard_output.jars_to_owners
+            dir_srcs = {artifact.basename: artifact for artifact in proguard_output.proguard_artifacts}
+            for i, hidden_artifact in enumerate(proguard_output.proguard_hidden_artifacts):
+                dir_srcs["hidden/{}_{}".format(i, hidden_artifact.basename)] = hidden_artifact
+            sub_targets["proguard_text_output"] = [
+                DefaultInfo(
+                    default_output = ctx.actions.symlinked_dir(
+                        "proguard_text_output",
+                        dir_srcs,
+                        has_content_based_path = False,
+                    ),
+                ),
+            ]
+        else:
+            proguard_output = None
+
+        if ctx.attrs.use_split_dex:
+            dex_files_info = get_multi_dex(
+                ctx,
+                android_toolchain,
+                jars_to_owners,
+                ctx.attrs.primary_dex_patterns,
+                proguard_output.proguard_configuration_output_file if proguard_output else None,
+                proguard_output.proguard_mapping_output_file if proguard_output else None,
+                is_optimized = has_proguard_config,
+                apk_module_graph_file = target_to_module_mapping_file,
+                enable_bootstrap_dexes = ctx.attrs.enable_bootstrap_dexes,
+                multidex_min_api = ctx.attrs.multidex_min_api,
+            )
+        else:
+            dex_files_info = get_single_primary_dex(
+                ctx,
+                android_toolchain,
+                jars_to_owners.keys(),
+                is_optimized = has_proguard_config,
+            )
+
+    sub_targets = sub_targets | enhancement_ctx.get_sub_targets()
+    if resources_info.string_source_map:
+        sub_targets["generate_string_resources"] = [DefaultInfo(default_output = resources_info.string_source_map)]
+
+    if resources_info.voltron_string_source_map:
+        sub_targets["generate_voltron_string_resources"] = [DefaultInfo(default_output = resources_info.voltron_string_source_map)]
+
+    if dex_files_info.primary_dex_class_names:
+        sub_targets["primary_dex_class_names"] = [DefaultInfo(default_output = dex_files_info.primary_dex_class_names)]
+
+    return AndroidBinaryInfo(
+        sub_targets = sub_targets,
+        java_packaging_deps = java_packaging_deps,
+        deps_by_platform = deps_by_platform,
+        primary_platform = primary_platform,
+        dex_files_info = dex_files_info,
+        native_library_info = native_library_info,
+        resources_info = resources_info,
+        materialized_artifacts = materialized_artifacts,
+        preprocessed_java_classes_info = preprocessed_java_classes_info,
+        validation_outputs = validation_outputs,
+    )
+
+def get_build_config_java_libraries(
+    ctx: AnalysisContext, build_config_infos: list[AndroidBuildConfigInfo], package_type: str, exopackage_modes: list[str]
+) -> list[JavaPackagingInfo]:
+    # BuildConfig deps should not be added for instrumented APKs because BuildConfig.class has
+    # already been added to the APK under test.
+    if package_type == "instrumented":
+        return []
+
+    build_config_constants = [
+        BuildConfigField(type = "boolean", name = "DEBUG", value = str(package_type != "release").lower()),
+        BuildConfigField(type = "boolean", name = "IS_EXOPACKAGE", value = str(len(exopackage_modes) > 0).lower()),
+        BuildConfigField(type = "int", name = "EXOPACKAGE_FLAGS", value = str(get_exopackage_flags(exopackage_modes))),
+    ]
+
+    default_build_config_fields = get_build_config_fields(ctx.attrs.build_config_values)
+
+    android_binary_values_file = (
+        ctx.attrs.build_config_values_file[DefaultInfo].default_outputs[0]
+        if isinstance(ctx.attrs.build_config_values_file, Dependency)
+        else ctx.attrs.build_config_values_file
+    )
+
+    java_libraries = []
+    java_packages_seen = []
+    for build_config_info in build_config_infos:
+        java_package = build_config_info.package
+        expect(java_package not in java_packages_seen, "Got the same java_package {} for different AndroidBuildConfigs".format(java_package))
+        java_packages_seen.append(java_package)
+
+        all_build_config_values = {}
+        for build_config_field in build_config_info.build_config_fields + default_build_config_fields + build_config_constants:
+            all_build_config_values[build_config_field.name] = build_config_field
+
+        values_file = android_binary_values_file if android_binary_values_file else build_config_info.values_file
+        java_libraries.append(
+            generate_android_build_config(
+                ctx,
+                java_package,
+                java_package,
+                True,  # use_constant_expressions
+                all_build_config_values.values(),
+                values_file,
+            )[1]
+        )
+
+    return java_libraries
diff --git a/buck2/prelude/android/android_binary_native_library_rules.bzl b/buck2/prelude/android/android_binary_native_library_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_binary_native_library_rules.bzl
@@ -0,0 +1,2927 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//android:android_providers.bzl",
+    "AndroidBinaryNativeLibsInfo",
+    "AndroidPackageableInfo",
+    "ExopackageNativeInfo",
+    "PrebuiltNativeLibraryDir",  # @unused Used as a type
+)
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:cpu_filters.bzl", "CPU_FILTER_FOR_PRIMARY_PLATFORM", "CPU_FILTER_TO_ABI_DIRECTORY")
+load(
+    "@prelude//android:native_build_commands.bzl",
+    "EMIT_NATIVE_BUILD_COMMANDS",
+    "GATORADE_PHASE_SUBTARGETS",
+    "NATIVE_BUILD_COMMAND_KINDS",
+    "native_build_command_entry",
+    "record_link_command",
+)
+load("@prelude//android:relinker_linker_outputs.bzl", "get_extra_relinker_args")
+load("@prelude//android:util.bzl", "EnhancementContext", "merge_extra_linker_args")
+load("@prelude//android:voltron.bzl", "ROOT_MODULE", "all_targets_in_root_module", "get_apk_module_graph_info", "is_root_module")
+# @oss-disable[end= ]: load(
+    # @oss-disable[end= ]: "@prelude//android/meta_only:gatorade.bzl",
+    # @oss-disable[end= ]: "add_gatorade_relinker_args",
+    # @oss-disable[end= ]: "early_gatorade_libraries",
+    # @oss-disable[end= ]: "gatorade_deferred_libs",
+    # @oss-disable[end= ]: "gatorade_libraries",
+    # @oss-disable[end= ]: "is_late_gatorade_enabled",
+    # @oss-disable[end= ]: "middle_gatorade_merge_args",
+    # @oss-disable[end= ]: "relink_for_native_libs",
+# @oss-disable[end= ]: )
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo", "PicBehavior")
+load(
+    "@prelude//cxx:link.bzl",
+    "cxx_link_shared_library",
+)
+load("@prelude//cxx:link_types.bzl", "link_options")
+load(
+    "@prelude//cxx:symbols.bzl",
+    "extract_defined_syms",
+    "extract_undefined_syms",
+)
+load("@prelude//java:java_library.bzl", "compile_to_jar")  # @unused
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference", "get_action_execution_attributes")
+load(
+    "@prelude//linking:link_info.bzl",
+    "ArchiveLinkable",
+    "LibOutputStyle",
+    "LinkArgs",
+    "LinkInfo",
+    "LinkOrdering",
+    "LinkedObject",
+    "ObjectsLinkable",
+    "SharedLibLinkable",
+    "get_lib_output_style",
+    "set_link_info_link_whole",
+    "unpack_link_args",
+    "wrap_link_info",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",  # @unused Used as a type
+    "LinkableNode",  # @unused Used as a type
+    "create_linkable_graph",
+    "get_linkable_graph_node_map_func",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",  # @unused Used as a type
+    "SharedLibraryInfo",  # @unused Used as a type
+    "create_shlib",
+    "get_strip_non_global_flags",
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+    "with_unique_str_sonames",
+)
+load("@prelude//linking:strip.bzl", "strip_object")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//utils:argfile.bzl", "argfile")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:graph_utils.bzl", "post_order_traversal", "pre_order_traversal", "rust_matching_topological_traversal")
+load("@prelude//utils:utils.bzl", "dedupe_by_value")
+
+_GATORADE_PHASE_ORDER = ["early", "middle", "late"]
+
+# Native libraries on Android are built for a particular Application Binary Interface (ABI). We
+# package native libraries for one (or more, for multi-arch builds) ABIs into an Android APK.
+#
+# Our native libraries come from two sources:
+# 1. "Prebuilt native library dirs", which are directory artifacts whose sub-directories are ABIs,
+#    and those ABI subdirectories contain native libraries. These come from `android_prebuilt_aar`s
+#    and `prebuilt_native_library`s, for example.
+# 2. "Native linkables". These are each a single shared library - `.so`s for one particular ABI.
+#
+# Native libraries can be packaged into Android APKs in two ways.
+# 1. As native libraries. This means that they are passed to the APK builder as native libraries,
+#    and the APK builder will package `<ABI>/library.so` into the APK at `libs/<ABI>/library.so`.
+# 2. As assets. These are passed to the APK build as assets, and are stored at
+#    `assets/lib/<ABI>/library.so` In the root module, we only package a native library as an
+#    asset if it is eligible to be an asset (e.g. `can_be_asset` on a `cxx_library`), and
+#    `package_asset_libraries` is set to True for the APK. We create a metadata file at
+#    `assets/libs/metadata.txt` that has a single line entry for each packaged asset consisting of
+#    '<ABI/library_name> <file_size> <sha256>'.
+#
+#    Native libraries that are not part of the root module (i.e. it is part of some other Voltron
+#    module) are controlled by `package_voltron_asset_libraries` and `can_be_asset` flags.
+#    Similarly, the metadata for each module is stored at `assets/<module_name>/libs.txt`.
+
+def _merged_lib_provided_by_apk_under_test(merged_lib, shared_libraries_to_exclude: set) -> bool:
+    # True when every primary constituent of a merged library is provided by the
+    # apk-under-test, so the instrumentation APK can drop its own copy and resolve
+    # the library at runtime from the apk-under-test instead.
+    if not shared_libraries_to_exclude or not merged_lib.primary_constituents:
+        return False
+    for constituent in merged_lib.primary_constituents:
+        if constituent.raw_target() not in shared_libraries_to_exclude:
+            return False
+    return True
+
+def _register_gatorade_phase_evidence(
+    enhance_ctx: EnhancementContext,
+    platforms: list[str],
+    native_library_merge_dir: Artifact | None,
+    middle_gatorade_products: Artifact | None,
+    unstripped_native_libraries_files: Artifact,
+    relinked_libs_output: Artifact | None,
+    defer_relink: bool,
+) -> None:
+    ctx = enhance_ctx.ctx
+    configured = getattr(ctx.attrs, "gatorade_phases", [])
+    configured_phases = [phase for phase in _GATORADE_PHASE_ORDER if phase in configured]
+    phase_outputs = {}
+    phase_dependencies = {}
+    if "early" in configured_phases and native_library_merge_dir != None:
+        phase_outputs["early"] = native_library_merge_dir
+        phase_dependencies["early"] = "merge_sequence"
+    if "middle" in configured_phases and middle_gatorade_products != None:
+        phase_outputs["middle"] = middle_gatorade_products
+        phase_dependencies["middle"] = "middle_products"
+    if "late" in configured_phases:
+        phase_outputs["late"] = relinked_libs_output if defer_relink else unstripped_native_libraries_files
+        phase_dependencies["late"] = "relinked_libraries" if defer_relink else "final_unstripped_libraries"
+    if not phase_outputs:
+        return
+
+    evidence = ctx.actions.declare_output(
+        "gatorade_phase_evidence.json",
+        has_content_based_path = False,
+    )
+    # Preserve the associated inputs so building this manifest also materializes
+    # the phase products it certifies.
+    evidence_inputs = ctx.actions.write_json(
+        evidence,
+        {
+            "configured_phases": configured_phases,
+            "defer_relink": defer_relink,
+            "engaged_phases": [phase for phase in _GATORADE_PHASE_ORDER if phase in phase_outputs],
+            "phase_dependencies": phase_dependencies,
+            "phase_outputs": phase_outputs,
+            "platforms": sorted(platforms),
+            "schema_version": 1,
+            "target": str(ctx.label.raw_target()),
+        },
+        pretty = True,
+        with_inputs = True,
+    )
+    enhance_ctx.debug_output(
+        "gatorade_phase_evidence",
+        evidence,
+        other_outputs = [evidence_inputs],
+    )
+
+def _materialize_middle_gatorade_products(
+    ctx: AnalysisContext,
+    output,
+    products_by_platform: dict[str, Artifact],
+    relinked_libraries_by_platform: dict[str, dict[str, SharedLibrary]],
+) -> None:
+    entries = {}
+    for platform in sorted(products_by_platform):
+        entries["{}/products".format(platform)] = products_by_platform[platform]
+        relinked_libraries = relinked_libraries_by_platform[platform]
+        for soname in sorted(relinked_libraries):
+            entries["{}/relinked/{}".format(platform, soname)] = relinked_libraries[soname].lib.output
+    ctx.actions.symlinked_dir(output, entries)
+
+def get_android_binary_native_library_info(
+    enhance_ctx: EnhancementContext,
+    android_packageable_info: AndroidPackageableInfo,
+    deps_by_platform: dict[str, list[Dependency]],
+    apk_module_graph_file: Artifact | None = None,
+    prebuilt_native_library_dirs_to_exclude: set[TargetLabel] = set(),
+    shared_libraries_to_exclude: set[TargetLabel] = set(),
+    native_library_merge_sequence: list | None = None,
+    native_library_merge_glue: dict | None = None,
+    native_library_merge_map: dict | None = None,
+    native_library_merge_non_asset_libs: bool = False,
+    native_library_merge_linker_args: dict | None = None,
+    native_library_merge_linker_args_all: list | None = None,
+    native_library_merge_code_generator: Dependency | None = None,
+    native_library_merge_sequence_blocklist: list | None = None,
+) -> AndroidBinaryNativeLibsInfo:
+    ctx = enhance_ctx.ctx
+
+    traversed_prebuilt_native_library_dirs = (
+        android_packageable_info.prebuilt_native_library_dirs.traverse() if android_packageable_info.prebuilt_native_library_dirs else []
+    )
+    all_prebuilt_native_library_dirs = [
+        native_lib for native_lib in traversed_prebuilt_native_library_dirs if native_lib.raw_target not in prebuilt_native_library_dirs_to_exclude
+    ]
+
+    included_shared_lib_targets = []
+    original_shared_libs_by_platform = {}  # dict[str, dict[str (soname), list[SharedLibrary]]]
+    for platform, deps in deps_by_platform.items():
+        if platform == CPU_FILTER_FOR_PRIMARY_PLATFORM and platform not in ctx.attrs.cpu_filters and len(ctx.attrs.cpu_filters) != 0:
+            continue
+
+        shared_libs = get_default_shared_libs(ctx, deps, shared_libraries_to_exclude)
+        included_shared_lib_targets.extend([lib.label.raw_target() for lib in shared_libs.values()])
+        original_shared_libs_by_platform[platform] = shared_libs
+
+    if not all_prebuilt_native_library_dirs and not included_shared_lib_targets:
+        enhance_ctx.debug_output("native_libs", ctx.actions.write("native_libs", [], has_content_based_path = False))
+        enhance_ctx.debug_output("linker_argsfiles", ctx.actions.symlinked_dir("linker_argsfiles", {}, has_content_based_path = False))
+        enhance_ctx.debug_output("linker_commands", ctx.actions.write("linker_commands", [], has_content_based_path = False))
+        enhance_ctx.debug_output(
+            "native_build_commands",
+            ctx.actions.write_json("native_build_commands", [], has_content_based_path = False),
+            # Expose the same empty per-kind filter sub_targets as the main path so
+            # TARGET[native_build_commands][<kind>] resolves uniformly (to empty JSON) even on
+            # apps with no native libraries.
+            sub_targets = {
+                kind: [DefaultInfo(default_outputs = [ctx.actions.write_json("native_build_commands.{}.json".format(kind), [], has_content_based_path = False)])]
+                for kind in NATIVE_BUILD_COMMAND_KINDS
+            },
+        )
+        # The top-level Gatorade-phase sub-targets output that phase's produced artifacts (an empty
+        # dir here: an app with no native libraries runs no Gatorade phase), so they resolve
+        # uniformly. See the main path for the populated case.
+        for gatorade_phase in GATORADE_PHASE_SUBTARGETS:
+            enhance_ctx.debug_output(gatorade_phase, ctx.actions.symlinked_dir(gatorade_phase, {}, has_content_based_path = False))
+        enhance_ctx.debug_output("unstripped_native_libraries", ctx.actions.write("unstripped_native_libraries", [], has_content_based_path = False))
+        enhance_ctx.debug_output(
+            "unstripped_native_libraries_json", ctx.actions.write_json("unstripped_native_libraries_json", {}, has_content_based_path = False)
+        )
+        enhance_ctx.debug_output(
+            "unstripped_native_libraries_files", ctx.actions.symlinked_dir("unstripped_native_libraries_files", {}, has_content_based_path = False)
+        )
+        enhance_ctx.debug_output("relinker_extra_outputs", ctx.actions.symlinked_dir("relinker_extra_outputs", {}, has_content_based_path = False))
+        return AndroidBinaryNativeLibsInfo(
+            prebuilt_native_library_dirs = [],
+            shared_libraries = [],
+            native_libs_for_primary_apk = [],
+            exopackage_info = None,
+            root_module_native_lib_assets = [],
+            non_root_module_native_lib_assets = [],
+            generated_java_code = [],
+            unstripped_shared_libraries = None,
+            validation_outputs = [],
+        )
+
+    native_libs = ctx.actions.declare_output("native_libs_symlink", has_content_based_path = False)
+    native_libs_metadata = ctx.actions.declare_output("native_libs_metadata_symlink", has_content_based_path = False)
+    native_libs_always_in_primary_apk = ctx.actions.declare_output("native_libs_always_in_primary_apk_symlink", has_content_based_path = False)
+    native_lib_assets_for_primary_apk = ctx.actions.declare_output("native_lib_assets_for_primary_apk_symlink", has_content_based_path = False)
+    stripped_native_linkable_assets_for_primary_apk = ctx.actions.declare_output(
+        "stripped_native_linkable_assets_for_primary_apk_symlink", has_content_based_path = False
+    )
+    root_module_metadata_assets = ctx.actions.declare_output("root_module_metadata_assets_symlink", has_content_based_path = False)
+    non_root_module_metadata_assets = ctx.actions.declare_output("non_root_module_metadata_assets_symlink", has_content_based_path = False)
+    non_root_module_lib_assets = ctx.actions.declare_output("non_root_module_lib_assets_symlink", has_content_based_path = False)
+
+    linker_argsfiles = ctx.actions.declare_output("linker_argsfiles", dir = True, has_content_based_path = False)
+    linker_commands = ctx.actions.declare_output("linker_commands", has_content_based_path = False)
+    unstripped_native_libraries = ctx.actions.declare_output("unstripped_native_libraries", has_content_based_path = False)
+    unstripped_native_libraries_json = ctx.actions.declare_output("unstripped_native_libraries_json", has_content_based_path = False)
+    unstripped_native_libraries_files = ctx.actions.declare_output("unstripped_native_libraries.links", dir = True, has_content_based_path = False)
+
+    dynamic_outputs = [
+        native_libs,
+        native_libs_metadata,
+        native_libs_always_in_primary_apk,
+        native_lib_assets_for_primary_apk,
+        linker_argsfiles,
+        linker_commands,
+        unstripped_native_libraries,
+        unstripped_native_libraries_json,
+        unstripped_native_libraries_files,
+        stripped_native_linkable_assets_for_primary_apk,
+        root_module_metadata_assets,
+        non_root_module_metadata_assets,
+        non_root_module_lib_assets,
+    ]
+
+    # [native_build_commands] outputs. `native_build_commands` (full) + the per-kind filters are
+    # produced by a final combine action (see below) that merges two fragments: the "base" fragment
+    # (all commands known by the end of the outer dynamic lambda) and the late-Gatorade "codegen"
+    # fragment. The codegen commands (clang --codegen-library) are constructed inside a NESTED
+    # Gatorade dynamic that runs after the outer lambda, so they cannot be folded in by the outer
+    # lambda directly and instead flow through this fragment + combine.
+    native_build_commands = ctx.actions.declare_output("native_build_commands.json", has_content_based_path = False)
+    native_build_commands_by_kind = {
+        kind: ctx.actions.declare_output("native_build_commands.{}.json".format(kind), has_content_based_path = False) for kind in NATIVE_BUILD_COMMAND_KINDS
+    }
+    native_build_commands_base = ctx.actions.declare_output("native_build_commands.base.json", has_content_based_path = False)
+    native_build_commands_codegen = ctx.actions.declare_output("native_build_commands.late_gatorade_codegen.json", has_content_based_path = False)
+    dynamic_outputs.append(native_build_commands_base)
+
+    fake_input = ctx.actions.write("dynamic.trigger", "", has_content_based_path = False)
+
+    # some cases don't actually need to use a dynamic_output, but it's simplest to consistently use it anyway. we need some fake input to allow that.
+    dynamic_inputs = [fake_input]
+    if apk_module_graph_file:
+        dynamic_inputs.append(apk_module_graph_file)
+    split_groups_map = None
+    native_library_merge_dir = None
+    native_merge_debug = None
+    generated_java_code = []
+
+    glue_linkables = None
+    if native_library_merge_glue:
+        glue_linkables = {}
+        for platform, glue in native_library_merge_glue.items():
+            glue_link_graph = glue.get(LinkableGraph)
+            expect(glue_link_graph != None, "native_library_merge_glue (`{}`) should be a linkable target", glue.label)
+            glue_linkable = glue_link_graph.nodes.value.linkable
+            expect(glue_linkable != None, "native_library_merge_glue (`{}`) should be a linkable target", glue.label)
+            expect(glue_linkable.preferred_linkage == Linkage("static"), "buck2 currently only supports preferred_linkage='static' native_library_merge_glue")
+            glue_linkables[platform] = (glue.label, glue_linkable.link_infos[LibOutputStyle("pic_archive")].default)
+
+    linkable_nodes_by_platform = {}
+
+    # Analysis-scope [native_build_commands] entries (e.g. compute_mergemap) that run before the
+    # dynamic lambda. The lambda seeds its own list from a copy of this, then appends the
+    # in-lambda link/bolt commands. Entries created inside the frozen lambda cannot be appended
+    # here, so anything produced at analysis time is collected into this list instead.
+    native_build_command_entries = []
+
+    # TARGET[<phase>] Gatorade-phase product sub-targets. Each outputs the full set of artifacts that
+    # phase's gatorade invocation(s) produce, as a symlinked_dir (like [native_libs]).
+    #  - early runs at analysis scope: early_gatorade_libraries fills this {relpath: artifact} map,
+    #    and early_gatorade_products is built from it below.
+    #  - middle reuses middle_gatorade_products, declared below and materialized inside the dynamic
+    #    lambda when the middle phase runs.
+    #  - late runs inside the nested Gatorade dynamics, so its dir is declared here, appended to
+    #    dynamic_outputs, and bound inside (empty when the phase is off).
+    early_gatorade_product_mapping = {}
+    late_gatorade_products = ctx.actions.declare_output("late_gatorade_products", dir = True, has_content_based_path = False)
+    dynamic_outputs.append(late_gatorade_products)
+
+    has_native_merging = native_library_merge_sequence or native_library_merge_map
+    enable_relinker = getattr(ctx.attrs, "enable_relinker", False)
+    defer_relink = getattr(ctx.attrs, "defer_relink", False) and enable_relinker
+
+    middle_gatorade_products = None
+    if enable_relinker and "middle" in getattr(ctx.attrs, "gatorade_phases", []):
+        middle_gatorade_products = ctx.actions.declare_output(
+            "middle_gatorade_products",
+            dir = True,
+            has_content_based_path = False,
+        )
+        dynamic_outputs.append(middle_gatorade_products)
+
+    # The outer lambda owns the codegen fragment. With late Gatorade, the nested Gatorade dynamic
+    # (gatorade_libraries or gatorade_deferred_libs) binds it through the passed OutputArtifact;
+    # otherwise the outer lambda binds it with an empty list, so the combine always has both inputs.
+    # @oss-disable[end= ]: will_capture_late_gatorade_codegen = is_late_gatorade_enabled(ctx)
+    will_capture_late_gatorade_codegen = False # @oss-enable
+    dynamic_outputs.append(native_build_commands_codegen)
+
+    if has_native_merging or enable_relinker:
+        native_merge_debug = ctx.actions.declare_output("native_merge_debug", dir = True, has_content_based_path = False)
+        dynamic_outputs.append(native_merge_debug)
+
+    # Argsfiles referenced by [native_build_commands][compile] entries, attached as other_outputs
+    # below. Keyed by the Artifact, not short_path: short_path is only the extension-based filename
+    # (e.g. `.cpp.cxx_compile_argsfile`), identical across every library and platform.
+    compile_argsfiles = {}
+
+    # EMIT_NATIVE_BUILD_COMMANDS also needs the node map (compile entries read each node's
+    # compile_cmds), so compile capture works on apps that neither merge nor relink.
+    if has_native_merging or enable_relinker or EMIT_NATIVE_BUILD_COMMANDS:
+        # We serialize info about the linkable graph and the apk module mapping and pass that to an
+        # external subcommand to apply a merge sequence algorithm and return us the merge mapping.
+        for platform, deps in deps_by_platform.items():
+            if platform == CPU_FILTER_FOR_PRIMARY_PLATFORM and platform not in ctx.attrs.cpu_filters and len(ctx.attrs.cpu_filters) != 0:
+                continue
+            linkable_graph = create_linkable_graph(ctx, deps = deps)
+            graph_node_map = get_linkable_graph_node_map_func(linkable_graph)()
+            linkables_debug = ctx.actions.write("linkables." + platform, list(graph_node_map.keys()), has_content_based_path = False)
+            enhance_ctx.debug_output("linkables." + platform, linkables_debug)
+            linkable_nodes_by_platform[platform] = graph_node_map
+            if EMIT_NATIVE_BUILD_COMMANDS:
+                for node in graph_node_map.values():
+                    for cc in node.compile_cmds:
+                        compile_argsfiles[cc.cxx_compile_cmd.argsfile.file] = None
+
+    jni_onload_check_report = None
+    if has_native_merging and ctx.attrs._android_toolchain[AndroidToolchainInfo].jni_onload_check:
+        jni_onload_check_report = ctx.actions.declare_output("jni_onload_check.json", has_content_based_path = False)
+        dynamic_outputs.append(jni_onload_check_report)
+
+    relinked_libs_output = None
+    relinked_libs_manifest = None
+    if defer_relink:
+        relinked_libs_output = ctx.actions.declare_output("relinked_libs", dir = True)
+        relinked_libs_manifest = ctx.actions.declare_output("relinked_libs_manifest.json")
+        dynamic_outputs.append(relinked_libs_output)
+        dynamic_outputs.append(relinked_libs_manifest)
+
+    # Aggregate of every native library before the relinker's dead-code-stripping
+    # pass, exposed as the [unrelinked_libs] sub-target (the pre-relink counterpart
+    # of [relinked_libs]). Only the relinker produces an unrelinked vs relinked
+    # distinction, so this only exists when relinking is enabled.
+    unrelinked_libs_output = None
+    if enable_relinker:
+        unrelinked_libs_output = ctx.actions.declare_output("unrelinked_libs", dir = True)
+        dynamic_outputs.append(unrelinked_libs_output)
+
+    # The `extra_relinker_outputs` of every relinked library, as
+    # <type>/<abi>/<soname>/<file>, exposed as the [relinker_extra_outputs] sub-target so
+    # they can be built (and so put on disk) without knowing their paths. Always
+    # present; empty when nothing is configured or nothing is relinked.
+    relinker_extra_outputs = ctx.actions.declare_output("relinker_extra_outputs", dir = True, has_content_based_path = False)
+    dynamic_outputs.append(relinker_extra_outputs)
+
+    lib_outputs_by_platform = _declare_library_subtargets(
+        ctx, dynamic_outputs, original_shared_libs_by_platform, native_library_merge_map, native_library_merge_sequence, enable_relinker
+    )
+
+    if native_library_merge_sequence:
+        native_library_merge_input_file = ctx.actions.write_json(
+            "mergemap.input",
+            {
+                "linkable_graphs_by_platform": encode_linkable_graph_for_mergemap(linkable_nodes_by_platform),
+                "native_library_merge_sequence": native_library_merge_sequence,
+                "native_library_merge_sequence_blocklist": native_library_merge_sequence_blocklist or [],
+            },
+            has_content_based_path = False,
+        )
+
+        if not "early" in getattr(ctx.attrs, "gatorade_phases", []):
+            mergemap_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].mergemap_tool)
+            mergemap_cmd.add(cmd_args(native_library_merge_input_file, format = "--mergemap-input={}"))
+            if apk_module_graph_file:
+                mergemap_cmd.add(cmd_args(apk_module_graph_file, format = "--apk-module-graph={}"))
+            if native_library_merge_non_asset_libs:
+                mergemap_cmd.add(cmd_args("--merge-non-asset-libs"))
+            native_library_merge_dir = ctx.actions.declare_output("merge_sequence_output", has_content_based_path = False)
+            native_library_merge_map = native_library_merge_dir.project("merge.map")
+            split_groups_map = native_library_merge_dir.project("split_groups.map")
+
+            # Record the mergemap command before adding the output as an `as_output()` (which
+            # cannot be re-serialized by write_json); reference the plain output artifact instead.
+            native_build_command_entries.append(
+                native_build_command_entry(
+                    kind = "mergemap",
+                    category = "compute_mergemap",
+                    arch = None,
+                    soname = None,
+                    output = native_library_merge_dir.short_path,
+                    argv = cmd_args(mergemap_cmd, cmd_args(native_library_merge_dir, format = "--output={}")),
+                )
+            )
+
+            ctx.actions.run(
+                cmd_args(mergemap_cmd, cmd_args(native_library_merge_dir.as_output(), format = "--output={}")),
+                category = "compute_mergemap",
+                allow_cache_upload = True,
+            )
+        else:
+            native_library_merge_dir = ctx.actions.declare_output("merge_sequence_output", dir = True, has_content_based_path = False)
+            native_library_merge_map = native_library_merge_dir.project("merge.map")
+            split_groups_map = native_library_merge_dir.project("split_groups.map")
+
+            # Pass all merge sequence arguments to early_gatorade_libraries
+            # which will handle running either Python or C++ implementation
+            # Prevent Buildifier from moving comments in a way that breaks things.
+            args = [
+                ctx,
+                original_shared_libs_by_platform,
+                linkable_nodes_by_platform,
+                native_library_merge_input_file,
+                apk_module_graph_file,
+                native_library_merge_non_asset_libs,
+                native_library_merge_dir,
+                # @oss-disable[end= ]: native_build_command_entries,
+                # @oss-disable[end= ]: early_gatorade_product_mapping,
+            ]
+            # @oss-disable[end= ]: early_gatorade_libraries(*args)
+
+        enhance_ctx.debug_output("compute_merge_sequence", native_library_merge_dir)
+
+        dynamic_inputs.append(native_library_merge_map)
+        dynamic_inputs.append(split_groups_map)
+
+    mergemap_gencode_jar = None
+
+    if has_native_merging and native_library_merge_code_generator:
+        mergemap_gencode_jar = ctx.actions.declare_output("MergedLibraryMapping.jar", has_content_based_path = False)
+        dynamic_outputs.append(mergemap_gencode_jar)
+        generated_java_code.append(mergemap_gencode_jar)
+
+    def dynamic_native_libs_info(ctx: AnalysisContext, artifacts, outputs):
+        middle_gatorade_outputs_by_platform = {}
+        middle_gatorade_relinked_libraries_by_platform = {}
+        # Seed with the analysis-scope entries (frozen list, read-only copy), then append the
+        # in-lambda link/relink/merge/bolt commands as the pipeline produces them.
+        native_cmd_entries = list(native_build_command_entries)
+        get_module_from_target = all_targets_in_root_module
+        get_module_tdeps = all_targets_in_root_module
+        get_calculated_module_deps = all_targets_in_root_module
+        get_deps_debug_data = None
+        if apk_module_graph_file:
+            apk_module_graph = get_apk_module_graph_info(ctx, apk_module_graph_file, artifacts)
+            get_module_from_target = apk_module_graph.target_to_module_mapping_function
+            get_module_tdeps = apk_module_graph.transitive_module_deps_function
+            get_calculated_module_deps = apk_module_graph.calculated_deps_function
+            get_deps_debug_data = apk_module_graph.get_deps_debug_data
+
+        split_groups = None
+        merged_shared_lib_targets_by_platform = {}  # dict[str, dict[Label, str]]
+        if has_native_merging:
+            native_library_merge_debug_outputs = {}
+
+            # When changing this dynamic_output, the workflow is a lot better if you compute the module graph once and
+            # then set it as the binary's precomputed_apk_module_graph attr.
+            if native_library_merge_sequence:
+                merge_map_by_platform = artifacts[native_library_merge_map].read_json()
+                split_groups = artifacts[split_groups_map].read_json()
+                native_library_merge_debug_outputs["merge_sequence_output"] = native_library_merge_dir
+            elif native_library_merge_map:
+                merge_map_by_platform = {}
+                for platform, linkable_nodes in linkable_nodes_by_platform.items():
+                    merge_map = merge_map_by_platform.setdefault(platform, {})
+                    merge_lib_to_fancy_regexes = {
+                        merge_lib: [regex(pattern, fancy = True) for pattern in patterns] for merge_lib, patterns in native_library_merge_map.items()
+                    }
+                    for target, _node in linkable_nodes.items():
+                        raw_target = str(target.raw_target())
+                        merge_result = None
+                        for merge_lib, fancy_regexes in merge_lib_to_fancy_regexes.items():
+                            for fancy_regex in fancy_regexes:
+                                if fancy_regex.match(raw_target):
+                                    merge_result = merge_lib
+                                    break
+                            if merge_result:
+                                break
+                        if merge_result:
+                            merge_map[str(target)] = merge_result
+                merge_map = ctx.actions.write_json("merge.map", merge_map_by_platform, pretty = True, has_content_based_path = False)
+                native_library_merge_debug_outputs["merge_map_output"] = merge_map
+            else:
+                fail("unreachable")
+
+            shared_object_targets = {}
+            debug_info_by_platform = {}  # dict[str, MergedLinkablesDebugInfo]
+            merged_shared_libs_by_platform = {}  # dict[str, dict[str, MergedSharedLibrary]]
+            jni_onload_check_inputs = [] if jni_onload_check_report else None
+            for platform in original_shared_libs_by_platform:
+                merged_shared_libs, debug_info = _get_merged_linkables_for_platform(
+                    ctx = ctx,
+                    cxx_toolchain = ctx.attrs._cxx_toolchain[platform][CxxToolchainInfo],
+                    platform = platform if len(original_shared_libs_by_platform) > 1 else None,
+                    native_library_merge_linker_args_all = native_library_merge_linker_args_all,
+                    glue_linkable = glue_linkables[platform] if glue_linkables else None,
+                    default_shared_libs = original_shared_libs_by_platform[platform],
+                    linkable_nodes = linkable_nodes_by_platform[platform],
+                    merge_map = merge_map_by_platform[platform],
+                    merge_linker_args = native_library_merge_linker_args or {},
+                    apk_module_graph = get_module_from_target,
+                    jni_onload_check_inputs = jni_onload_check_inputs,
+                )
+                debug_info_by_platform[platform] = debug_info
+                merged_shared_libs_by_platform[platform] = merged_shared_libs
+                merged_shared_lib_targets = {}
+                for soname, lib in merged_shared_libs.items():
+                    shared_object_targets[soname] = [str(target.raw_target()) for target in lib.primary_constituents]
+
+                    for target in lib.primary_constituents:
+                        merged_shared_lib_targets[target] = soname
+                merged_shared_lib_targets_by_platform[platform] = merged_shared_lib_targets
+
+            debug_data_json = ctx.actions.write_json("native_merge_debug.json", debug_info_by_platform, pretty = True, has_content_based_path = False)
+            native_library_merge_debug_outputs["native_merge_debug.json"] = debug_data_json
+
+            shared_object_targets_lines = ""
+            for soname, targets in shared_object_targets.items():
+                shared_object_targets_lines += soname + " " + " ".join(targets) + "\n"
+            shared_object_targets_txt = ctx.actions.write("shared_object_targets.txt", shared_object_targets_lines, has_content_based_path = False)
+            native_library_merge_debug_outputs["shared_object_targets.txt"] = shared_object_targets_txt
+
+            if mergemap_gencode_jar:
+                merged_library_map = write_merged_library_map(ctx, merged_shared_libs_by_platform)
+                mergemap_gencode = run_mergemap_codegen(ctx, native_library_merge_code_generator, merged_library_map)
+                compile_to_jar(ctx, [mergemap_gencode], output = outputs[mergemap_gencode_jar])
+                native_library_merge_debug_outputs["NativeLibraryMergeGeneratedCode.java"] = mergemap_gencode
+                native_library_merge_debug_outputs["merged_library_map.txt"] = merged_library_map
+                native_library_merge_debug_outputs["mergemap_gencode.jar"] = mergemap_gencode_jar
+
+                # Write the JNI_OnLoad mappings file (merged SO name -> constituent targets)
+                jni_on_load_mappings = write_jni_on_load_mappings(ctx, merged_shared_libs_by_platform)
+                native_library_merge_debug_outputs["jni_on_load_mappings.txt"] = jni_on_load_mappings
+
+            ctx.actions.symlinked_dir(outputs[native_merge_debug], native_library_merge_debug_outputs)
+
+            if jni_onload_check_report:
+                # nm is the same across the android platforms in a binary, so
+                # any of them serves for a symbol-table read.
+                check_platform = list(original_shared_libs_by_platform.keys())[0]
+                _run_jni_onload_check(
+                    ctx,
+                    ctx.attrs._cxx_toolchain[check_platform][CxxToolchainInfo],
+                    jni_onload_check_inputs,
+                    outputs[jni_onload_check_report],
+                )
+
+            # Merged libraries are assembled from the full linkable graph, so unlike the
+            # non-merging path (which filters via get_default_shared_libs) they do not
+            # otherwise honor shared_libraries_to_exclude. Drop any merged library whose
+            # primary constituents are all provided by the apk-under-test: re-emitting it
+            # would ship a duplicate merged .so that loads alongside the apk-under-test's
+            # copy in the instrumentation process and re-runs its link_whole static
+            # initializers. shared_libraries_to_exclude is empty for non-instrumentation
+            # binaries, so this is a no-op there.
+            final_shared_libs_by_platform = {
+                platform: {
+                    soname: d.lib for soname, d in merged_shared_libs.items() if not _merged_lib_provided_by_apk_under_test(d, shared_libraries_to_exclude)
+                }
+                for platform, merged_shared_libs in merged_shared_libs_by_platform.items()
+            }
+        elif enable_relinker:
+            final_shared_libs_by_platform, native_library_merge_debug_outputs = _create_all_relinkable_links(
+                ctx,
+                original_shared_libs_by_platform,
+                linkable_nodes_by_platform,
+            )
+            ctx.actions.symlinked_dir(outputs[native_merge_debug], native_library_merge_debug_outputs)
+
+        else:
+            final_shared_libs_by_platform = original_shared_libs_by_platform
+
+        relinked_libs_for_extra_outputs = {}
+
+        # [native_build_commands][merge]: record every per-soname merge link here, once, before any
+        # relink reassigns final_shared_libs_by_platform. This is the single capture point for merge
+        # links across all paths (inline relink, deferred relink, and late-Gatorade), which is why
+        # the finalization step below never labels anything kind=merge.
+        if has_native_merging:
+            for platform, libs in final_shared_libs_by_platform.items():
+                for soname, lib in libs.items():
+                    record_link_command(native_cmd_entries, "merge", platform, soname, lib.lib)
+
+        # [native_build_commands][compile]: emit one entry per source in every linkable node that
+        # carries compile commands (populated only when `-c cxx.emit_native_build_commands=true`, so
+        # this whole block is skipped otherwise). Attribute each to the FINAL merged soname via the
+        # merge map (falling back to the node's own pre-merge soname), keeping the per-library soname
+        # in pre_merge_soname. The soname is best-effort: split groups, static-only nodes, and
+        # late-gatorade code motion make it approximate — consumers should cross-reference merge.map.
+        if EMIT_NATIVE_BUILD_COMMANDS:
+            for platform, node_map in linkable_nodes_by_platform.items():
+                merged_by_label = merged_shared_lib_targets_by_platform.get(platform, {})
+                for node_label, node in node_map.items():
+                    pre_merge_soname = node.default_soname
+                    for cc in node.compile_cmds:
+                        # A source compiled more than once in the same node (different flavors/flags)
+                        # carries a non-None index; append it so those entries get distinct identifiers.
+                        identifier = "{}/{}/{}".format(platform, node_label.raw_target(), cc.src.short_path)
+                        if cc.index != None:
+                            identifier += "/{}".format(cc.index)
+                        native_cmd_entries.append(
+                            native_build_command_entry(
+                                kind = "compile",
+                                category = cc.cxx_compile_cmd.category,
+                                arch = platform,
+                                soname = merged_by_label.get(node_label, pre_merge_soname),
+                                pre_merge_soname = pre_merge_soname,
+                                output = cc.src.short_path,
+                                argv = cmd_args(cc.cxx_compile_cmd.base_compile_cmd, cc.cxx_compile_cmd.argsfile.cmd_form, cc.args),
+                                argsfile = cc.cxx_compile_cmd.argsfile.file,
+                                identifier = identifier,
+                            )
+                        )
+
+        if enable_relinker and not defer_relink:
+            unrelinked_shared_libs_by_platform = final_shared_libs_by_platform
+            final_shared_libs_by_platform, middle_gatorade_outputs_by_platform = _relink_for_native_libs(ctx, final_shared_libs_by_platform, native_cmd_entries)
+            middle_gatorade_relinked_libraries_by_platform = final_shared_libs_by_platform
+            relinked_libs_for_extra_outputs = final_shared_libs_by_platform
+            _link_library_subtargets(
+                ctx,
+                outputs,
+                lib_outputs_by_platform,
+                original_shared_libs_by_platform,
+                unrelinked_shared_libs_by_platform,
+                merged_shared_lib_targets_by_platform,
+                split_groups,
+                native_merge_debug,
+                unrelinked = True,
+            )
+            _write_native_libs_dir_and_manifest(
+                ctx,
+                unrelinked_shared_libs_by_platform,
+                outputs[unrelinked_libs_output],
+                None,
+                stripped = False,
+            )
+
+        if defer_relink:
+            # Run relinking as separate actions that can execute in parallel with other build steps.
+            # The relinked libs are exposed as [relinked_libs] sub-target for the combine genrule.
+            # A JSON manifest listing the <abi>/<soname> entries is produced alongside so that
+            # the combine script knows exactly which libraries to replace without guessing.
+            relinked_libs_by_platform, middle_gatorade_outputs_by_platform = _relink_for_native_libs(ctx, final_shared_libs_by_platform, native_cmd_entries)
+            middle_gatorade_relinked_libraries_by_platform = relinked_libs_by_platform
+            relinked_libs_for_extra_outputs = relinked_libs_by_platform
+
+            if False: # @oss-enable
+            # @oss-disable[end= ]: if is_late_gatorade_enabled(ctx):
+                # Run Gatorade cross-library optimization + codegen + re-link on
+                # the deferred relinked libs. The callback writes the final
+                # Gatorade-processed libs to the relinked_libs_output artifacts.
+                def deferred_gatorade_output(ctx, gatorade_libs_by_platform, dyn_outputs):
+                    _write_native_libs_dir_and_manifest(
+                        ctx, gatorade_libs_by_platform, dyn_outputs[relinked_libs_output], dyn_outputs[relinked_libs_manifest], stripped = True
+                    )
+
+                # @oss-disable[end= ]: gatorade_deferred_libs(
+                    # @oss-disable[end= ]: ctx,
+                    # @oss-disable[end= ]: relinked_libs_by_platform,
+                    # @oss-disable[end= ]: deferred_gatorade_output,
+                    # @oss-disable[end= ]: [outputs[relinked_libs_output], outputs[relinked_libs_manifest]],
+                    # @oss-disable[end= ]: native_cmd_entries,
+                    # @oss-disable[end= ]: outputs[native_build_commands_codegen],
+                    # @oss-disable[end= ]: outputs[late_gatorade_products],
+                # @oss-disable[end= ]: )
+            else:
+                _write_native_libs_dir_and_manifest(
+                    ctx, relinked_libs_by_platform, outputs[relinked_libs_output], outputs[relinked_libs_manifest], stripped = True
+                )
+
+            # Bind unrelinked subtarget outputs (same as final since we skipped inline relinking)
+            _link_library_subtargets(
+                ctx,
+                outputs,
+                lib_outputs_by_platform,
+                original_shared_libs_by_platform,
+                final_shared_libs_by_platform,
+                merged_shared_lib_targets_by_platform,
+                split_groups,
+                native_merge_debug,
+                unrelinked = True,
+            )
+            _write_native_libs_dir_and_manifest(
+                ctx,
+                final_shared_libs_by_platform,
+                outputs[unrelinked_libs_output],
+                None,
+                stripped = False,
+            )
+
+        if middle_gatorade_products != None:
+            _materialize_middle_gatorade_products(
+                ctx,
+                outputs[middle_gatorade_products],
+                middle_gatorade_outputs_by_platform,
+                middle_gatorade_relinked_libraries_by_platform,
+            )
+
+        if ctx.attrs._android_toolchain[AndroidToolchainInfo].cross_module_native_deps_check and (has_native_merging or enable_relinker):
+            # note: can only detect these if linkable_nodes_by_platform is created, ie. if using relinker or merging.
+            # EMIT_NATIVE_BUILD_COMMANDS also builds it on apps that do neither; those apps never ran
+            # this check, so it stays gated on merging/relinking.
+            cross_module_link_errors = []
+            for linkable_nodes in linkable_nodes_by_platform.values():
+                for target, node in linkable_nodes.items():
+                    node_target = str(target.raw_target())
+                    node_module = get_module_from_target(node_target)
+                    for dep in node.deps:
+                        dep_target = str(dep.raw_target())
+                        dep_module = get_module_from_target(dep_target)
+                        if (
+                            not is_root_module(dep_module)
+                            and node_module != dep_module
+                            and dep_module not in get_module_tdeps(node_module)
+                            and dep_module not in get_calculated_module_deps(node_module)
+                        ):
+                            cross_module_link_errors.append("{} (module: {}) -> {} (module: {}) ".format(node_target, node_module, dep_target, dep_module))
+
+            if cross_module_link_errors:
+                cross_module_link_errors.append(get_deps_debug_data())
+                fail(
+                    "Native libraries in modules should only depend on libraries in the same module or the root. Remove these deps:\n"
+                    + "\n".join(cross_module_link_errors)
+                )
+
+        _write_relinker_extra_outputs_dir(ctx, relinked_libs_for_extra_outputs, outputs[relinker_extra_outputs])
+
+        native_lib_dynamic_outputs = {
+            "linker_argsfiles": outputs[linker_argsfiles],
+            "linker_commands": outputs[linker_commands],
+            "native_lib_assets_for_primary_apk": outputs[native_lib_assets_for_primary_apk],
+            "native_libs": outputs[native_libs],
+            "native_libs_always_in_primary_apk": outputs[native_libs_always_in_primary_apk],
+            "native_libs_metadata": outputs[native_libs_metadata],
+            "non_root_module_lib_assets": outputs[non_root_module_lib_assets],
+            "non_root_module_metadata_assets": outputs[non_root_module_metadata_assets],
+            "root_module_metadata_assets": outputs[root_module_metadata_assets],
+            "stripped_native_linkable_assets_for_primary_apk": outputs[stripped_native_linkable_assets_for_primary_apk],
+            "unstripped_native_libraries": outputs[unstripped_native_libraries],
+            "unstripped_native_libraries_files": outputs[unstripped_native_libraries_files],
+            "unstripped_native_libraries_json": outputs[unstripped_native_libraries_json],
+        }
+
+        if False: # @oss-enable
+        # @oss-disable[end= ]: if is_late_gatorade_enabled(ctx) and not defer_relink:
+            # Prevent Buildifier from moving comments in a way that breaks things.
+            # When defer_relink is True, Gatorade runs in the deferred pipeline via
+            # gatorade_deferred_libs() above.
+            args = [
+                ctx,
+                final_shared_libs_by_platform,
+                _post_native_lib_graph_finalization_steps,
+                all_prebuilt_native_library_dirs,
+                get_module_from_target,
+                native_lib_dynamic_outputs,
+                # @oss-disable[end= ]: native_cmd_entries,
+                # @oss-disable[end= ]: outputs[native_build_commands_codegen],
+                # @oss-disable[end= ]: outputs[late_gatorade_products],
+            ]
+            # @oss-disable[end= ]: subtarget_shared_libs_by_platform = gatorade_libraries(*args)
+        else:
+            subtarget_shared_libs_by_platform = _post_native_lib_graph_finalization_steps(
+                ctx,
+                final_shared_libs_by_platform,
+                all_prebuilt_native_library_dirs,
+                get_module_from_target,
+                native_cmd_entries = native_cmd_entries,
+                # Only record the libs finalized here as plain kind=link when the app neither merges
+                # nor relinks; otherwise merge/relink links are already captured at their own sites.
+                record_final_link = not has_native_merging and not enable_relinker,
+                **native_lib_dynamic_outputs,
+            )
+
+        # Subtargets can't be created or changed from within dynamic actions, so the individual
+        # library subtargets can't reflect any changes to the set of libraries made by a dynamic
+        # action. All other logic should be in _post_native_lib_graph_finalization_steps, which
+        # receives the final set of native libraries.
+        _link_library_subtargets(
+            ctx,
+            outputs,
+            lib_outputs_by_platform,
+            original_shared_libs_by_platform,
+            subtarget_shared_libs_by_platform,
+            merged_shared_lib_targets_by_platform,
+            split_groups,
+            native_merge_debug,
+        )
+
+        # Write the "base" fragment: every native-build command known by the end of this lambda.
+        # with_inputs = False embeds each argv/argsfile as text without materializing the produced
+        # .o/.so, matching the linker_commands writer. The final [native_build_commands] JSON and its
+        # per-kind filters are produced by the combine action below (which folds in the late-Gatorade
+        # codegen fragment).
+        ctx.actions.write_json(outputs[native_build_commands_base], native_cmd_entries, with_inputs = False)
+
+        # On paths that don't capture late-Gatorade codegen, bind its fragment here (empty) so the
+        # combine action always has both inputs. On the capturing path the nested Gatorade dynamic
+        # binds it instead.
+        if not will_capture_late_gatorade_codegen:
+            ctx.actions.write_json(outputs[native_build_commands_codegen], [], with_inputs = False)
+
+        # TARGET[late_gatorade] products are bound inside the nested Gatorade dynamic (which knows the
+        # output library graph); on every non-late path the outer lambda binds it empty here, mirroring
+        # the native_build_commands_codegen fragment's ownership.
+        if not will_capture_late_gatorade_codegen:
+            ctx.actions.symlinked_dir(outputs[late_gatorade_products], {})
+
+    ctx.actions.dynamic_output(dynamic = dynamic_inputs, inputs = [], outputs = [o.as_output() for o in dynamic_outputs], f = dynamic_native_libs_info)
+
+    # Combine the base fragment with the late-Gatorade codegen fragment into the final
+    # [native_build_commands] JSON and its per-kind filters. Both fragments were written with
+    # with_inputs = False, so their entries are already-rendered plain JSON; read them back and
+    # re-emit. This runs after the (possibly nested) writers of both fragments complete.
+    def _combine_native_build_commands(ctx: AnalysisContext, artifacts, outputs):
+        entries = artifacts[native_build_commands_base].read_json() + artifacts[native_build_commands_codegen].read_json()
+        ctx.actions.write_json(outputs[native_build_commands], entries)
+        for kind in NATIVE_BUILD_COMMAND_KINDS:
+            ctx.actions.write_json(outputs[native_build_commands_by_kind[kind]], [entry for entry in entries if entry["kind"] == kind])
+
+    ctx.actions.dynamic_output(
+        dynamic = [native_build_commands_base, native_build_commands_codegen],
+        inputs = [],
+        outputs = [native_build_commands.as_output()] + [native_build_commands_by_kind[kind].as_output() for kind in NATIVE_BUILD_COMMAND_KINDS],
+        f = _combine_native_build_commands,
+    )
+    combined_asset_libs = ctx.actions.declare_output("combined_asset_libs", dir = True, has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args([
+            ctx.attrs._android_toolchain[AndroidToolchainInfo].combine_native_library_dirs[RunInfo],
+            "--output-dir",
+            combined_asset_libs.as_output(),
+            "--library-dirs",
+            native_lib_assets_for_primary_apk,
+            stripped_native_linkable_assets_for_primary_apk,
+            "--subdir",
+            "assets/lib",
+        ]),
+        category = "combine_native_asset_libs",
+        allow_cache_upload = True,
+    )
+    all_native_libs = ctx.actions.symlinked_dir(
+        "debug_all_native_libs",
+        {
+            "assets": combined_asset_libs,
+            "others": native_libs,
+            "primary": native_libs_always_in_primary_apk,
+        },
+        has_content_based_path = False,
+    )
+
+    lib_subtargets = _create_library_subtargets(
+        lib_outputs_by_platform,
+        native_libs,
+        # @oss-disable[end= ]: create_default_outputs = not is_late_gatorade_enabled(ctx),
+        create_default_outputs = True, # @oss-enable
+    )
+    enhance_ctx.debug_output("native_libs", all_native_libs, sub_targets = lib_subtargets)
+    if native_merge_debug:
+        enhance_ctx.debug_output("native_merge_debug", native_merge_debug)
+
+    if jni_onload_check_report:
+        # Buildable on its own so the check can be run, and its report read,
+        # without building the whole apk.
+        enhance_ctx.debug_output("jni_onload_check", jni_onload_check_report)
+
+    enhance_ctx.debug_output("linker_argsfiles", linker_argsfiles)
+    enhance_ctx.debug_output("linker_commands", linker_commands)
+    # Materialize the argsfiles a consumer needs to expand an entry's `@argsfile` on disk:
+    #  - link-family kinds (merge/link/relink/bolt) -> the linker_argsfiles symlinked_dir built in
+    #    finalization from every final lib's linker_argsfile;
+    #  - compile -> the per-source compile argsfiles collected at analysis time above.
+    # mergemap has no argsfile; Gatorade argsfiles are recorded by path only (see
+    # native_build_commands.bzl `argsfile` note), so those kinds get no extra outputs here.
+    compile_argsfiles_outputs = list(compile_argsfiles.keys())
+    _kind_argsfile_outputs = {kind: [linker_argsfiles] for kind in ["merge", "link", "relink", "bolt"]}
+    _kind_argsfile_outputs["compile"] = compile_argsfiles_outputs
+    enhance_ctx.debug_output(
+        "native_build_commands",
+        native_build_commands,
+        other_outputs = [linker_argsfiles] + compile_argsfiles_outputs,
+        sub_targets = {
+            kind: [
+                DefaultInfo(
+                    default_outputs = [native_build_commands_by_kind[kind]],
+                    other_outputs = _kind_argsfile_outputs.get(kind, []),
+                )
+            ]
+            for kind in NATIVE_BUILD_COMMAND_KINDS
+        },
+    )
+    # TARGET[<phase>] Gatorade-phase product sub-targets: building one runs that phase and outputs
+    # the artifacts its gatorade invocation(s) produce (a symlinked_dir, like [native_libs]). Early's
+    # products were collected at analysis scope; middle/late were bound inside the dynamic lambda.
+    # middle_gatorade_products is only declared when the middle phase runs, so otherwise the
+    # sub-target resolves to an empty dir.
+    early_gatorade_products = ctx.actions.symlinked_dir("early_gatorade_products", early_gatorade_product_mapping, has_content_based_path = False)
+    gatorade_phase_products = {
+        "early_gatorade": early_gatorade_products,
+        "late_gatorade": late_gatorade_products,
+        "middle_gatorade": middle_gatorade_products or ctx.actions.symlinked_dir("middle_gatorade_products", {}, has_content_based_path = False),
+    }
+    expect(
+        sorted(gatorade_phase_products.keys()) == sorted(GATORADE_PHASE_SUBTARGETS),
+        "gatorade_phase_products must cover exactly GATORADE_PHASE_SUBTARGETS",
+    )
+    for gatorade_phase, products in gatorade_phase_products.items():
+        enhance_ctx.debug_output(gatorade_phase, products)
+    enhance_ctx.debug_output("unstripped_native_libraries", unstripped_native_libraries, other_outputs = [unstripped_native_libraries_files])
+    enhance_ctx.debug_output("unstripped_native_libraries_json", unstripped_native_libraries_json, other_outputs = [unstripped_native_libraries_files])
+    enhance_ctx.debug_output("unstripped_native_libraries_files", unstripped_native_libraries_files)
+    if relinked_libs_output:
+        enhance_ctx.debug_output("relinked_libs", relinked_libs_output)
+    if relinked_libs_manifest:
+        enhance_ctx.debug_output("relinked_libs_manifest", relinked_libs_manifest)
+    if unrelinked_libs_output:
+        enhance_ctx.debug_output("unrelinked_libs", unrelinked_libs_output)
+    enhance_ctx.debug_output("relinker_extra_outputs", relinker_extra_outputs)
+
+    _register_gatorade_phase_evidence(
+        enhance_ctx,
+        original_shared_libs_by_platform.keys(),
+        native_library_merge_dir,
+        middle_gatorade_products,
+        unstripped_native_libraries_files,
+        relinked_libs_output,
+        defer_relink,
+    )
+
+    native_libs_for_primary_apk, exopackage_info = _get_exopackage_info(ctx, native_libs_always_in_primary_apk, native_libs, native_libs_metadata)
+    return AndroidBinaryNativeLibsInfo(
+        prebuilt_native_library_dirs = all_prebuilt_native_library_dirs,
+        shared_libraries = included_shared_lib_targets,
+        native_libs_for_primary_apk = native_libs_for_primary_apk,
+        exopackage_info = exopackage_info,
+        root_module_native_lib_assets = [native_lib_assets_for_primary_apk, stripped_native_linkable_assets_for_primary_apk, root_module_metadata_assets],
+        non_root_module_native_lib_assets = [non_root_module_metadata_assets, non_root_module_lib_assets],
+        generated_java_code = generated_java_code,
+        unstripped_shared_libraries = unstripped_native_libraries_files,
+        validation_outputs = [jni_onload_check_report] if jni_onload_check_report else [],
+    )
+
+_NativeLibSubtargetArtifacts = record(
+    default = Artifact,
+    unrelinked = Artifact | None,
+    linker_command = Artifact | None,
+    linker_argsfile = Artifact | None,
+    # Pre-inline module IR (.ll) emitted by the relink when the `preinline-ir`
+    # extra relinker output is enabled; a comment-only `.ll` otherwise. Surfaced
+    # as the `[preinline_ir]` sub-target so tooling (evt) can fetch it.
+    preinline_ir = Artifact | None,
+)
+
+# Writes a directory of <abi>/<soname> shared libraries, and optionally a JSON
+# manifest listing those entries. Shared by the [relinked_libs] and
+# [unrelinked_libs] sub-targets. [relinked_libs] feeds the combine genrule and
+# wants the packaged (stripped) form plus the manifest (so the combine step
+# knows which libraries to replace); [unrelinked_libs] mirrors the per-library
+# [unrelinked] sub-target, exposing the unstripped linker output, and needs no
+# manifest (pass out_manifest = None).
+def _write_relinker_extra_outputs_dir(ctx: AnalysisContext, libs_by_platform: dict[str, dict[str, SharedLibrary]], out_dir: Artifact):
+    # Only the configured types: the relinker records other things under
+    # `extra_outputs` as well, and they are not for building on their own.
+    output_types = getattr(ctx.attrs, "extra_relinker_outputs", [])
+    files = {}
+    for platform, libs in libs_by_platform.items():
+        abi_directory = CPU_FILTER_TO_ABI_DIRECTORY[platform]
+        for soname, lib in libs.items():
+            for output_type in output_types:
+                for info in lib.extra_outputs.get(output_type, []):
+                    for artifact in info.default_outputs:
+                        # Key by soname as well: two libraries in the same
+                        # abi/type can emit outputs sharing a basename, which
+                        # would otherwise collide and drop one silently.
+                        files["{}/{}/{}/{}".format(output_type, abi_directory, soname, artifact.basename)] = artifact
+    ctx.actions.symlinked_dir(out_dir, files)
+
+def _write_native_libs_dir_and_manifest(ctx, libs_by_platform, out_dir, out_manifest, stripped):
+    lib_files = {}
+    for platform in libs_by_platform:
+        libs = libs_by_platform[platform]
+        abi_directory = CPU_FILTER_TO_ABI_DIRECTORY[platform]
+        for soname in libs:
+            shlib = libs[soname]
+            lib_files["{}/{}".format(abi_directory, soname)] = (shlib.stripped_lib or shlib.lib.output) if stripped else shlib.lib.output
+    ctx.actions.symlinked_dir(out_dir, lib_files)
+    if out_manifest != None:
+        ctx.actions.write_json(out_manifest, sorted(lib_files.keys()))
+
+def _post_native_lib_graph_finalization_steps(
+    ctx: AnalysisContext,
+    final_shared_libs_by_platform: dict[str, dict[str, SharedLibrary]],
+    all_prebuilt_native_library_dirs: list[PrebuiltNativeLibraryDir],
+    get_module_from_target: typing.Callable,
+    linker_argsfiles: Artifact,
+    linker_commands: Artifact,
+    unstripped_native_libraries: Artifact,
+    unstripped_native_libraries_json: Artifact,
+    unstripped_native_libraries_files: Artifact,
+    native_libs: Artifact,
+    native_libs_metadata: Artifact,
+    native_libs_always_in_primary_apk: Artifact,
+    native_lib_assets_for_primary_apk: Artifact,
+    stripped_native_linkable_assets_for_primary_apk: Artifact,
+    root_module_metadata_assets: Artifact,
+    non_root_module_metadata_assets: Artifact,
+    non_root_module_lib_assets: Artifact,
+    native_cmd_entries = None,
+    # True only on apps that neither merge nor relink: then the libs finalized here ARE the plain
+    # per-library links, recorded kind=link. When merging/relinking, those commands are captured at
+    # their own sites (kind=merge / kind=relink) and this must stay False to avoid double-recording.
+    record_final_link: bool = False,
+) -> dict[str, dict[str, SharedLibrary]]:
+    bolt_args = getattr(ctx.attrs, "native_library_bolt_args", None)
+    pre_bolt_libs_by_platform = {}
+    if bolt_args and len(bolt_args) != 0:
+        final_shared_libs_by_platform, pre_bolt_libs_by_platform = _bolt_libraries(
+            ctx, final_shared_libs_by_platform, bolt_args, native_cmd_entries, record_final_link
+        )
+
+    unstripped_libs = {}
+    linker_argsfiles_list = []
+    linker_commands_json = []
+    for platform, libs in final_shared_libs_by_platform.items() + pre_bolt_libs_by_platform.items():
+        for soname, lib in libs.items():
+            unstripped_libs[lib.lib.output] = platform
+            if lib.lib.linker_argsfile:
+                linker_argsfiles_list.append(lib.lib)
+            linker_commands_json.append({
+                "argsfile": lib.lib.linker_argsfile,
+                "command": lib.lib.linker_command,
+                "filename": lib.lib.output.short_path,
+            })
+
+            # Record the plain per-library link for [native_build_commands][link], but only on apps
+            # that neither merge nor relink (record_final_link). Merge and relink links are captured
+            # at their own sites, and on those paths the libs seen here are either already-recorded
+            # (merge/relink outputs) or command-less (late-gatorade dummies), so recording here would
+            # double-count or add null entries.
+            if record_final_link:
+                record_link_command(native_cmd_entries, "link", platform, soname, lib.lib)
+
+    ctx.actions.symlinked_dir(linker_argsfiles, {"{}".format(lib.output.basename): lib.linker_argsfile for lib in linker_argsfiles_list})
+    ctx.actions.write_json(linker_commands, linker_commands_json, with_inputs = False)
+    ctx.actions.write(unstripped_native_libraries, unstripped_libs.keys())
+    ctx.actions.write_json(unstripped_native_libraries_json, unstripped_libs)
+    ctx.actions.symlinked_dir(unstripped_native_libraries_files, {"{}/{}".format(platform, lib.basename): lib for lib, platform in unstripped_libs.items()})
+
+    dynamic_info = _get_native_libs_and_assets(
+        ctx,
+        get_module_from_target,
+        all_prebuilt_native_library_dirs,
+        final_shared_libs_by_platform,
+    )
+
+    # Since we are using a dynamic action, we need to declare the outputs in advance.
+    # Rather than passing the created outputs into `_get_native_libs_and_assets`, we
+    # just symlink to the outputs that function produces.
+    ctx.actions.symlink_file(native_libs, dynamic_info.native_libs)
+    ctx.actions.symlink_file(native_libs_metadata, dynamic_info.native_libs_metadata)
+    ctx.actions.symlink_file(native_libs_always_in_primary_apk, dynamic_info.native_libs_always_in_primary_apk)
+    ctx.actions.symlink_file(
+        native_lib_assets_for_primary_apk,
+        dynamic_info.native_lib_assets_for_primary_apk
+        if dynamic_info.native_lib_assets_for_primary_apk
+        else ctx.actions.symlinked_dir("empty_native_lib_assets", {}, has_content_based_path = False),
+    )
+    ctx.actions.symlink_file(
+        stripped_native_linkable_assets_for_primary_apk,
+        dynamic_info.stripped_native_linkable_assets_for_primary_apk
+        if dynamic_info.stripped_native_linkable_assets_for_primary_apk
+        else ctx.actions.symlinked_dir("empty_stripped_native_linkable_assets", {}, has_content_based_path = False),
+    )
+    ctx.actions.symlink_file(root_module_metadata_assets, dynamic_info.root_module_metadata_assets)
+    ctx.actions.symlink_file(non_root_module_metadata_assets, dynamic_info.non_root_module_metadata_assets)
+    ctx.actions.symlink_file(
+        non_root_module_lib_assets,
+        dynamic_info.non_root_module_lib_assets
+        if dynamic_info.non_root_module_lib_assets
+        else ctx.actions.symlinked_dir("empty_non_root_module_lib_assets", {}, has_content_based_path = False),
+    )
+
+    return final_shared_libs_by_platform
+
+# Merged libraries are dynamic dependencies, but outputs need to be declared in advance to be used by subtargets.
+# This means we have to declare outputs for all possible merged libs (every merged name and every unmerged library name).
+def _declare_library_subtargets(
+    ctx: AnalysisContext,
+    dynamic_outputs: list[Artifact],
+    original_shared_libs_by_platform: dict[str, dict[str, SharedLibrary]],
+    native_library_merge_map,
+    native_library_merge_sequence,
+    enable_relinker: bool,
+) -> dict[str, dict[str, _NativeLibSubtargetArtifacts]]:
+    lib_outputs_by_platform = {}
+    for platform, original_shared_libs in original_shared_libs_by_platform.items():
+        sonames = set()
+        sonames.update(original_shared_libs.keys())
+        if native_library_merge_map:
+            sonames.update(native_library_merge_map.keys())
+        elif native_library_merge_sequence:
+            for entry in native_library_merge_sequence:
+                if type(entry) == "list":
+                    sonames.update([soname for (soname, _) in entry])
+                else:
+                    (soname, _) = entry
+                    sonames.add(soname)
+
+        lib_outputs = {}
+        for soname in sonames:
+            output_path = _platform_output_path(soname, platform if len(original_shared_libs_by_platform) > 1 else None)
+            lib_output = ctx.actions.declare_output(output_path, dir = True, has_content_based_path = False)
+            dynamic_outputs.append(lib_output)
+
+            if enable_relinker:
+                linker_command_output = ctx.actions.declare_output(output_path + ".linker_command", has_content_based_path = False)
+                dynamic_outputs.append(linker_command_output)
+                linker_argsfile_output = ctx.actions.declare_output(output_path + ".linker_argsfile", has_content_based_path = False)
+                dynamic_outputs.append(linker_argsfile_output)
+                preinline_ir_output = ctx.actions.declare_output(output_path + ".preinline.ll", has_content_based_path = False)
+                dynamic_outputs.append(preinline_ir_output)
+
+                output_path = output_path + ".unrelinked"
+                unrelinked_lib_output = ctx.actions.declare_output(output_path, dir = True, has_content_based_path = False)
+                dynamic_outputs.append(unrelinked_lib_output)
+                lib_outputs[soname] = _NativeLibSubtargetArtifacts(
+                    default = lib_output,
+                    unrelinked = unrelinked_lib_output,
+                    linker_command = linker_command_output,
+                    linker_argsfile = linker_argsfile_output,
+                    preinline_ir = preinline_ir_output,
+                )
+            else:
+                lib_outputs[soname] = _NativeLibSubtargetArtifacts(
+                    default = lib_output,
+                    unrelinked = None,
+                    linker_command = None,
+                    linker_argsfile = None,
+                    preinline_ir = None,
+                )
+
+        lib_outputs_by_platform[platform] = lib_outputs
+    return lib_outputs_by_platform
+
+# Bind debug library subtarget outputs to actual outputs.
+# For individual libraries, link to either the unmerged or merged output.
+# For merged libraries, link to either the merged output, or a symlinked dir of all merged split group outputs.
+def _link_library_subtargets(
+    ctx: AnalysisContext,
+    outputs,  # IndexSet[OutputArtifact]
+    lib_outputs_by_platform: dict[str, dict[str, _NativeLibSubtargetArtifacts]],  # dict[platform, dict[soname,  _NativeLibSubtargetArtifacts]]
+    original_shared_libs_by_platform: dict[str, dict[str, SharedLibrary]],
+    final_shared_libs_by_platform: dict[str, dict[str, SharedLibrary]],
+    merged_shared_lib_targets_by_platform: dict[str, dict[Label, str]],
+    split_groups: dict[str, str] | None,
+    native_merge_debug,
+    unrelinked: bool = False,
+):
+    for platform, final_shared_libs in final_shared_libs_by_platform.items():
+        merged_lib_outputs = {}
+        linker_commands_by_soname = {}
+        linker_argsfiles_by_soname = {}
+        preinline_ir_by_soname = {}
+
+        for soname, lib in final_shared_libs.items():
+            base_soname = soname
+            if split_groups and soname in split_groups:
+                base_soname = split_groups[soname]
+
+            group_outputs = merged_lib_outputs.setdefault(base_soname, {})
+            group_outputs[soname] = lib.lib.output
+
+            if not unrelinked:
+                if lib.lib.linker_command:
+                    linker_commands_by_soname[soname] = {
+                        "argsfile": lib.lib.linker_argsfile,
+                        "command": lib.lib.linker_command,
+                        "filename": lib.lib.output.short_path,
+                    }
+                if lib.lib.linker_argsfile:
+                    linker_argsfiles_by_soname[soname] = lib.lib.linker_argsfile
+                preinline_ir = lib.extra_outputs.get("preinline-ir") if lib.extra_outputs else None
+                if preinline_ir:
+                    preinline_ir_outputs = preinline_ir[0].default_outputs
+                    if preinline_ir_outputs:
+                        preinline_ir_by_soname[soname] = preinline_ir_outputs[0]
+
+        for soname, lib_outputs in lib_outputs_by_platform[platform].items():
+            if soname in merged_lib_outputs:
+                group_outputs = merged_lib_outputs[soname]
+            elif soname in original_shared_libs_by_platform[platform]:
+                # link unmerged soname to merged output
+                original_shared_lib = original_shared_libs_by_platform[platform][soname]
+                merged_soname = merged_shared_lib_targets_by_platform[platform][original_shared_lib.label]
+                if split_groups and merged_soname in split_groups:
+                    merged_soname = split_groups[merged_soname]
+                group_outputs = merged_lib_outputs[merged_soname]
+            else:
+                # merged group name has no constituents, link to debug output
+                group_outputs = {soname: native_merge_debug}
+
+            output = lib_outputs.default
+            if unrelinked:
+                output = lib_outputs.unrelinked
+            ctx.actions.symlinked_dir(outputs[output], group_outputs)
+
+            if not unrelinked and lib_outputs.linker_command:
+                if soname in linker_commands_by_soname:
+                    ctx.actions.write_json(outputs[lib_outputs.linker_command], linker_commands_by_soname[soname])
+                else:
+                    ctx.actions.write_json(outputs[lib_outputs.linker_command], {})
+
+                if soname in linker_argsfiles_by_soname:
+                    ctx.actions.symlink_file(outputs[lib_outputs.linker_argsfile], linker_argsfiles_by_soname[soname])
+                else:
+                    ctx.actions.write_json(outputs[lib_outputs.linker_argsfile], {})
+
+                if lib_outputs.preinline_ir:
+                    if soname in preinline_ir_by_soname:
+                        ctx.actions.symlink_file(outputs[lib_outputs.preinline_ir], preinline_ir_by_soname[soname])
+                    else:
+                        # `;` is an LLVM IR line comment, so a consumer that parses this
+                        # unconditionally reads an empty module rather than choking on a
+                        # placeholder that is not IR at all.
+                        ctx.actions.write(
+                            outputs[lib_outputs.preinline_ir],
+                            "; no pre-inline IR for {}: the `preinline_ir` relinker output was not enabled for this library (constraint off, or soname absent from `gator.preinline_ir_sonames`)".format(
+                                soname
+                            ),
+                        )
+
+def _create_library_subtargets(
+    lib_outputs_by_platform: dict[str, dict[str, _NativeLibSubtargetArtifacts]], native_libs: Artifact, create_default_outputs: bool
+):
+    def create_library_subtarget(output: _NativeLibSubtargetArtifacts, create_default_outputs: bool):
+        if not create_default_outputs and not output.unrelinked:
+            fail("create_default_outputs can only be False when relinking")
+
+        sub_targets = {}
+        if output.linker_command:
+            sub_targets["linker_command"] = [DefaultInfo(default_outputs = [output.linker_command])]
+        if output.linker_argsfile:
+            sub_targets["linker_argsfile"] = [DefaultInfo(default_outputs = [output.linker_argsfile])]
+        if output.preinline_ir:
+            sub_targets["preinline_ir"] = [DefaultInfo(default_outputs = [output.preinline_ir])]
+
+        if output.unrelinked:
+            sub_targets["unrelinked"] = [DefaultInfo(default_outputs = [output.unrelinked])]
+            if create_default_outputs:
+                default_outputs = [output.default]
+            else:
+                sub_targets["relinked"] = [DefaultInfo(default_outputs = [output.default])]
+                default_outputs = []
+            return [DefaultInfo(default_outputs = default_outputs, sub_targets = sub_targets)]
+        return [DefaultInfo(default_outputs = [output.default], sub_targets = sub_targets)]
+
+    if len(lib_outputs_by_platform) > 1:
+        return {
+            platform: [
+                DefaultInfo(
+                    default_outputs = [native_libs],
+                    sub_targets = {soname: create_library_subtarget(output, create_default_outputs) for soname, output in lib_outputs.items()},
+                )
+            ]
+            for platform, lib_outputs in lib_outputs_by_platform.items()
+        }
+    elif len(lib_outputs_by_platform) == 1:
+        lib_outputs = list(lib_outputs_by_platform.values())[0]
+        return {soname: create_library_subtarget(output, create_default_outputs) for soname, output in lib_outputs.items()}
+    else:
+        # TODO(ctolliday) at this point we should have thrown an error earlier if no libraries matched cpu_filters
+        # (or returned earlier if there are no native library deps)
+        return {}
+
+# We could just return two artifacts of libs (one for the primary APK, one which can go
+# either into the primary APK or be exopackaged), and one artifact of assets,
+# but we'd need an extra action in order to combine them (we can't use `symlinked_dir` since
+# the paths overlap) so it's easier to just be explicit about exactly what we produce.
+_NativeLibsAndAssetsInfo = record(
+    native_libs = Artifact,
+    native_libs_metadata = Artifact,
+    native_libs_always_in_primary_apk = Artifact,
+    native_lib_assets_for_primary_apk = Artifact | None,
+    stripped_native_linkable_assets_for_primary_apk = Artifact | None,
+    root_module_metadata_assets = Artifact,
+    non_root_module_metadata_assets = Artifact,
+    non_root_module_lib_assets = [Artifact, None],
+)
+
+def _get_exopackage_info(
+    ctx: AnalysisContext, native_libs_always_in_primary_apk: Artifact, native_libs: Artifact, native_libs_metadata: Artifact
+) -> (list[Artifact], [ExopackageNativeInfo, None]):
+    is_exopackage_enabled_for_native_libs = "native_library" in getattr(ctx.attrs, "exopackage_modes", [])
+    if is_exopackage_enabled_for_native_libs:
+        return [native_libs_always_in_primary_apk], ExopackageNativeInfo(directory = native_libs, metadata = native_libs_metadata)
+    else:
+        return [native_libs, native_libs_always_in_primary_apk], None
+
+def _get_native_libs_and_assets(
+    ctx: AnalysisContext,
+    get_module_from_target: typing.Callable,
+    all_prebuilt_native_library_dirs: list[PrebuiltNativeLibraryDir],
+    platform_to_native_linkables: dict[str, dict[str, SharedLibrary]],
+) -> _NativeLibsAndAssetsInfo:
+    is_packaging_native_libs_as_assets_supported = getattr(ctx.attrs, "package_asset_libraries", False)
+    is_voltron_packaging_native_libs_as_assets_supported = getattr(ctx.attrs, "package_voltron_asset_libraries", False)
+
+    prebuilt_native_library_dirs = []
+    prebuilt_native_library_dirs_always_in_primary_apk = []
+    prebuilt_native_library_dir_assets_for_primary_apk = []
+    prebuilt_native_library_dir_module_assets_map = {}
+    prebuilt_native_library_dir_module_libs_map = {}
+    for native_lib in all_prebuilt_native_library_dirs:
+        native_lib_target = str(native_lib.raw_target)
+        module = get_module_from_target(native_lib_target)
+        expect(
+            not native_lib.for_primary_apk or is_root_module(module),
+            "{} which is marked as needing to be in the primary APK cannot be included in non-root-module {}".format(native_lib_target, module),
+        )
+        expect(
+            not native_lib.for_primary_apk or not native_lib.is_asset,
+            "{} which is marked as needing to be in the primary APK cannot be an asset".format(native_lib_target),
+        )
+        if not is_root_module(module):
+            if native_lib.is_asset and is_voltron_packaging_native_libs_as_assets_supported:
+                prebuilt_native_library_dir_module_assets_map.setdefault(module, []).append(native_lib)
+            else:
+                prebuilt_native_library_dir_module_libs_map.setdefault(module, []).append(native_lib)
+        elif native_lib.is_asset and is_packaging_native_libs_as_assets_supported:
+            expect(not native_lib.for_primary_apk, "{} which is marked as needing to be in the primary APK cannot be an asset".format(native_lib_target))
+            prebuilt_native_library_dir_assets_for_primary_apk.append(native_lib)
+        elif native_lib.for_primary_apk:
+            prebuilt_native_library_dirs_always_in_primary_apk.append(native_lib)
+        else:
+            prebuilt_native_library_dirs.append(native_lib)
+
+    native_libs = _filter_prebuilt_native_library_dir(
+        ctx,
+        prebuilt_native_library_dirs,
+        "native_libs",
+    )
+    native_libs_always_in_primary_apk = _filter_prebuilt_native_library_dir(
+        ctx,
+        prebuilt_native_library_dirs_always_in_primary_apk,
+        "native_libs_always_in_primary_apk",
+    )
+    native_lib_assets_for_primary_apk = (
+        _filter_prebuilt_native_library_dir(
+            ctx,
+            prebuilt_native_library_dir_assets_for_primary_apk,
+            "native_lib_assets_for_primary_apk",
+            package_as_assets = True,
+            module = ROOT_MODULE,
+        )
+        if prebuilt_native_library_dir_assets_for_primary_apk
+        else None
+    )
+    native_lib_module_assets_map = {}
+    for module, native_lib_dir in prebuilt_native_library_dir_module_assets_map.items():
+        native_lib_module_assets_map.setdefault(module, []).append(
+            _filter_prebuilt_native_library_dir(
+                ctx,
+                native_lib_dir,
+                "native_lib_assets_for_module_{}".format(module),
+                package_as_assets = True,
+                module = module,
+            )
+        )
+    for module, native_lib_dir in prebuilt_native_library_dir_module_libs_map.items():
+        native_lib_module_assets_map.setdefault(module, []).append(
+            _filter_prebuilt_native_library_dir(
+                ctx,
+                native_lib_dir,
+                "native_lib_libs_for_module_{}".format(module),
+                package_as_assets = False,
+                module = module,
+            )
+        )
+
+    stripped_linkables = _get_native_linkables(
+        ctx,
+        platform_to_native_linkables,
+        get_module_from_target,
+        is_packaging_native_libs_as_assets_supported,
+        is_voltron_packaging_native_libs_as_assets_supported,
+    )
+    for module, native_linkable_assets in stripped_linkables.linkable_module_assets_map.items():
+        native_lib_module_assets_map.setdefault(module, []).append(native_linkable_assets)
+
+    root_module_metadata_srcs = {}
+    non_root_module_metadata_srcs = {}
+    non_root_module_libs_srcs = []
+    assets_for_primary_apk = filter(None, [native_lib_assets_for_primary_apk, stripped_linkables.linkable_assets_for_primary_apk])
+    stripped_linkable_assets_for_primary_apk = stripped_linkables.linkable_assets_for_primary_apk
+    if assets_for_primary_apk:
+        metadata_file = _get_native_libs_as_assets_metadata(ctx, assets_for_primary_apk, ROOT_MODULE)
+        root_module_metadata_srcs[paths.join(_get_native_libs_as_assets_dir(ROOT_MODULE), "metadata.txt")] = metadata_file
+
+    for module, native_lib_assets in native_lib_module_assets_map.items():
+        metadata_file = _get_native_libs_as_assets_metadata(ctx, native_lib_assets, module)
+        libs_metadata_path = paths.join("assets", "libs.txt")
+        non_root_module_metadata_srcs[paths.join(_get_native_libs_as_assets_dir(module), libs_metadata_path)] = metadata_file
+        non_root_module_libs_srcs.extend(native_lib_assets)
+
+    non_root_module_libs = None
+    if non_root_module_libs_srcs:
+        non_root_module_libs = ctx.actions.declare_output("non_root_module_libs", has_content_based_path = False)
+        ctx.actions.run(
+            cmd_args(
+                [
+                    ctx.attrs._android_toolchain[AndroidToolchainInfo].combine_native_library_dirs[RunInfo],
+                    "--output-dir",
+                    non_root_module_libs.as_output(),
+                    "--library-dirs",
+                ]
+                + non_root_module_libs_srcs
+            ),
+            category = "combine_non_root_module_native_libs",
+            allow_cache_upload = True,
+        )
+
+    combined_native_libs = ctx.actions.declare_output("combined_native_libs", dir = True, has_content_based_path = False)
+    native_libs_metadata = ctx.actions.declare_output("native_libs_metadata.txt", has_content_based_path = False)
+    native_library_pick_first = getattr(ctx.attrs, "native_library_pick_first", [])
+    native_library_pick_first_arg = ["--pick-first"] + native_library_pick_first if native_library_pick_first else []
+    ctx.actions.run(
+        cmd_args(
+            [
+                ctx.attrs._android_toolchain[AndroidToolchainInfo].combine_native_library_dirs[RunInfo],
+                "--output-dir",
+                combined_native_libs.as_output(),
+                "--library-dirs",
+                native_libs,
+                stripped_linkables.linkables,
+                "--metadata-file",
+                native_libs_metadata.as_output(),
+            ]
+            + native_library_pick_first_arg
+        ),
+        category = "combine_native_libs",
+        allow_cache_upload = True,
+    )
+
+    combined_native_libs_always_in_primary_apk = ctx.actions.declare_output(
+        "combined_native_libs_always_in_primary_apk", dir = True, has_content_based_path = False
+    )
+    ctx.actions.run(
+        cmd_args([
+            ctx.attrs._android_toolchain[AndroidToolchainInfo].combine_native_library_dirs[RunInfo],
+            "--output-dir",
+            combined_native_libs_always_in_primary_apk.as_output(),
+            "--library-dirs",
+            native_libs_always_in_primary_apk,
+            stripped_linkables.linkables_always_in_primary_apk,
+        ]),
+        category = "combine_native_libs_always_in_primary_apk",
+        allow_cache_upload = True,
+    )
+
+    return _NativeLibsAndAssetsInfo(
+        native_libs = combined_native_libs,
+        native_libs_metadata = native_libs_metadata,
+        native_libs_always_in_primary_apk = combined_native_libs_always_in_primary_apk,
+        native_lib_assets_for_primary_apk = native_lib_assets_for_primary_apk,
+        stripped_native_linkable_assets_for_primary_apk = stripped_linkable_assets_for_primary_apk,
+        root_module_metadata_assets = ctx.actions.symlinked_dir("root_module_metadata_assets", root_module_metadata_srcs, has_content_based_path = False),
+        non_root_module_metadata_assets = ctx.actions.symlinked_dir(
+            "non_root_module_metadata_assets", non_root_module_metadata_srcs, has_content_based_path = False
+        ),
+        non_root_module_lib_assets = non_root_module_libs,
+    )
+
+def _filter_prebuilt_native_library_dir(
+    ctx: AnalysisContext, native_libs: list[PrebuiltNativeLibraryDir], identifier: str, package_as_assets: bool = False, module: str = ROOT_MODULE
+) -> Artifact:
+    cpu_filters = ctx.attrs.cpu_filters or CPU_FILTER_TO_ABI_DIRECTORY.keys()
+    abis = [CPU_FILTER_TO_ABI_DIRECTORY[cpu] for cpu in cpu_filters]
+    filter_tool = ctx.attrs._android_toolchain[AndroidToolchainInfo].filter_prebuilt_native_library_dir[RunInfo]
+    native_libs_dirs_file = argfile(actions = ctx.actions, name = "{}_list.txt".format(identifier), args = [native_lib.dir for native_lib in native_libs])
+    base_output_dir = ctx.actions.declare_output(identifier, dir = True, has_content_based_path = False)
+    if module == ROOT_MODULE:
+        output_dir = base_output_dir.project(_get_native_libs_as_assets_dir(module)) if package_as_assets else base_output_dir
+    elif package_as_assets:
+        output_dir = base_output_dir.project(paths.join(_get_native_libs_as_assets_dir(module), "assets"))
+    else:
+        output_dir = base_output_dir.project(paths.join(_get_native_libs_as_assets_dir(module), "lib"))
+    ctx.actions.run(
+        cmd_args([filter_tool, native_libs_dirs_file, output_dir.as_output(), "--abis"] + abis),
+        category = "filter_prebuilt_native_library_dir",
+        identifier = identifier,
+        allow_cache_upload = True,
+    )
+
+    return base_output_dir
+
+_StrippedNativeLinkables = record(
+    linkables = Artifact,
+    linkables_always_in_primary_apk = Artifact,
+    linkable_assets_for_primary_apk = Artifact | None,
+    linkable_module_assets_map = dict[str, Artifact],
+)
+
+def _get_native_linkables(
+    ctx: AnalysisContext,
+    platform_to_native_linkables: dict[str, dict[str, SharedLibrary]],
+    get_module_from_target: typing.Callable,
+    package_native_libs_as_assets_enabled: bool,
+    package_voltron_native_libs_as_assets_enabled: bool,
+) -> _StrippedNativeLinkables:
+    stripped_native_linkables_srcs = {}
+    stripped_native_linkables_always_in_primary_apk_srcs = {}
+    stripped_native_linkable_assets_for_primary_apk_srcs = {}
+    stripped_native_linkable_module_assets_srcs = {}
+    strip_libraries = getattr(ctx.attrs, "strip_libraries", True)
+
+    cpu_filters = ctx.attrs.cpu_filters
+    for platform, native_linkables in platform_to_native_linkables.items():
+        if cpu_filters and platform not in cpu_filters and platform != CPU_FILTER_FOR_PRIMARY_PLATFORM:
+            fail("Platform `{}` is not in the CPU filters `{}`".format(platform, cpu_filters))
+
+        abi_directory = CPU_FILTER_TO_ABI_DIRECTORY[platform]
+        for so_name, native_linkable in native_linkables.items():
+            native_linkable_target = str(native_linkable.label.raw_target())
+            module = get_module_from_target(native_linkable_target)
+            lib = native_linkable.stripped_lib if strip_libraries else native_linkable.lib.output
+
+            expect(
+                not native_linkable.for_primary_apk or is_root_module(module),
+                "{} which is marked as needing to be in the primary APK cannot be included in non-root-module {}".format(native_linkable_target, module),
+            )
+            expect(
+                not native_linkable.for_primary_apk or not native_linkable.can_be_asset,
+                "{} which is marked as needing to be in the primary APK cannot be an asset".format(native_linkable_target),
+            )
+
+            if is_root_module(module):
+                if native_linkable.can_be_asset and package_native_libs_as_assets_enabled:
+                    native_libs_assets_dir = paths.join(_get_native_libs_as_assets_dir(module))
+                    so_name_path = paths.join(native_libs_assets_dir, abi_directory, so_name)
+                    stripped_native_linkable_assets_for_primary_apk_srcs[so_name_path] = lib
+                else:
+                    so_name_path = paths.join(abi_directory, so_name)
+                    if native_linkable.for_primary_apk:
+                        stripped_native_linkables_always_in_primary_apk_srcs[so_name_path] = lib
+                    else:
+                        stripped_native_linkables_srcs[so_name_path] = lib
+            else:
+                module_dir = "assets" if native_linkable.can_be_asset and package_voltron_native_libs_as_assets_enabled else "lib"
+                so_name_path = paths.join(_get_native_libs_as_assets_dir(module), module_dir, abi_directory, so_name)
+                stripped_native_linkable_module_assets_srcs.setdefault(module, {})[so_name_path] = lib
+
+    stripped_native_linkables = ctx.actions.symlinked_dir(
+        "stripped_native_linkables",
+        stripped_native_linkables_srcs,
+        has_content_based_path = False,
+    )
+    stripped_native_linkables_always_in_primary_apk = ctx.actions.symlinked_dir(
+        "stripped_native_linkables_always_in_primary_apk",
+        stripped_native_linkables_always_in_primary_apk_srcs,
+        has_content_based_path = False,
+    )
+    stripped_native_linkable_assets_for_primary_apk = (
+        ctx.actions.symlinked_dir(
+            "stripped_native_linkables_assets_for_primary_apk",
+            stripped_native_linkable_assets_for_primary_apk_srcs,
+            has_content_based_path = False,
+        )
+        if stripped_native_linkable_assets_for_primary_apk_srcs
+        else None
+    )
+    stripped_native_linkable_module_assets_map = {}
+    for module, srcs in stripped_native_linkable_module_assets_srcs.items():
+        stripped_native_linkable_module_assets_map[module] = ctx.actions.symlinked_dir(
+            "stripped_native_linkable_assets_for_module_{}".format(module),
+            srcs,
+            has_content_based_path = False,
+        )
+
+    return _StrippedNativeLinkables(
+        linkables = stripped_native_linkables,
+        linkables_always_in_primary_apk = stripped_native_linkables_always_in_primary_apk,
+        linkable_assets_for_primary_apk = stripped_native_linkable_assets_for_primary_apk,
+        linkable_module_assets_map = stripped_native_linkable_module_assets_map,
+    )
+
+def _get_native_libs_as_assets_metadata(ctx: AnalysisContext, native_lib_assets: list[Artifact], module: str) -> Artifact:
+    native_lib_assets_file = argfile(
+        actions = ctx.actions,
+        name = "{}/native_lib_assets".format(module),
+        args = [cmd_args([native_lib_asset, _get_native_libs_as_assets_dir(module)], delimiter = "/") for native_lib_asset in native_lib_assets],
+    )
+    metadata_output = ctx.actions.declare_output("{}/native_libs_as_assets_metadata.txt".format(module), has_content_based_path = False)
+    metadata_cmd = cmd_args([
+        ctx.attrs._android_toolchain[AndroidToolchainInfo].native_libs_as_assets_metadata[RunInfo],
+        "--native-library-dirs",
+        native_lib_assets_file,
+        "--metadata-output",
+        metadata_output.as_output(),
+    ])
+    ctx.actions.run(metadata_cmd, category = "get_native_libs_as_assets_metadata", identifier = module, allow_cache_upload = True)
+    return metadata_output
+
+def _get_native_libs_as_assets_dir(module: str) -> str:
+    return "assets/{}".format("lib" if is_root_module(module) else module)
+
+def get_default_shared_libs(ctx: AnalysisContext, deps: list[Dependency], shared_libraries_to_exclude: set) -> dict[str, SharedLibrary]:
+    shared_library_info = merge_shared_libraries(
+        ctx.actions,
+        deps = filter(None, [x.get(SharedLibraryInfo) for x in deps]),
+    )
+
+    # Filter out shared libraries whose label.raw_target() is in shared_libraries_to_exclude
+    # Do it before calling with_unique_str_sonames to skip duplication check for excluded libs
+    shared_libraries = [
+        shared_lib
+        for shared_lib in traverse_shared_library_info(shared_library_info, transformation_provider = None)
+        if (shared_lib.label.raw_target() not in shared_libraries_to_exclude)
+    ]
+    return {soname: shared_lib for soname, shared_lib in with_unique_str_sonames(shared_libraries).items()}
+
+_LinkableSharedNode = record(
+    raw_target = field(str),
+    soname = field(str | None),
+    labels = field(list[str], []),
+    # Linkable deps of this target.
+    deps = field(list[Label], []),
+    can_be_asset = field(bool),
+    force_static = field(bool),
+)
+
+def encode_linkable_graph_for_mergemap(graph_node_map_by_platform: dict[str, dict[Label, LinkableNode]]) -> dict[str, dict[Label, _LinkableSharedNode]]:
+    return {
+        platform: {
+            target: _LinkableSharedNode(
+                raw_target = str(target.raw_target()),
+                soname = node.default_soname,
+                labels = node.labels,
+                deps = node.deps + node.exported_deps,
+                can_be_asset = node.can_be_asset,  # and not node.exclude_from_android_merge
+                force_static = node.preferred_linkage == Linkage("static"),
+            )
+            for target, node in graph_node_map.items()
+        }
+        for platform, graph_node_map in graph_node_map_by_platform.items()
+    }
+
+# Debugging info about the linkables merge process. All of this will be written in one of the outputs of
+# the `[native_merge_debug]` subtarget.
+MergedLinkablesDebugInfo = record(
+    unmerged_statics = list[str],
+    group_debug = dict[str, typing.Any],
+    with_default_soname = list[typing.Any],
+    missing_default_solibs = list[Label],
+)
+
+# As shared lib output of the linkables merge process. This is not necessarily an actually merged node (there
+# may be just one constituent)
+MergedSharedLibrary = record(
+    soname = str,
+    lib = SharedLibrary,
+    apk_module = str,
+    # this only includes solib constituents that are included in the android merge map
+    solib_constituents = list[str],
+    # targets that correspond to solib_constituents (i.e., targets with include_in_android_mergemap = True)
+    solib_constituent_targets = list[Label],
+    is_actually_merged = bool,
+    primary_constituents = list[Label],
+)
+
+# information about a link group derived from the merge mapping
+LinkGroupData = record(
+    group_name = [str, Label],
+    constituents = list[Label],
+    apk_module = str,
+)
+
+# Lookup key for somerge groups, either the soname for shared libraries or the target name for unmerged statics
+GroupLabel = str
+
+# Represents the primary constituents and deps of primary constituents used to create a LinkGroupLinkableNode for a non-prebuilt shared library.
+LinkGroupMergeInfo = record(
+    label = GroupLabel,
+    deps = list[GroupLabel],
+    exported_deps = list[GroupLabel],
+    constituent_link_infos = list[LinkInfo],
+)
+
+# Represents a node in the final merged linkable map. Most of these will be shared libraries, either prebuilt shared libs or
+# libraries that are created below for a node in the link_groups_graph. The exception is for non-merged static-only nodes.
+LinkGroupLinkableNode = record(
+    # The LinkInfo to add to the link line for a node that links against this.
+    link = LinkInfo,
+    deps = list[GroupLabel],
+    exported_deps = list[GroupLabel],
+    shared_lib = [SharedLibrary, None],
+    # linker flags to be exported by any node that links against this. This can only be non-None for non-merged static only nodes (as we don't
+    # propagate exported linker flags through transitive shared lib deps).
+    exported_linker_flags = [(list[typing.Any], list[typing.Any]), None],
+)
+
+def write_merged_library_map(ctx: AnalysisContext, shared_libs_by_platform: dict[str, dict[str, MergedSharedLibrary]]) -> Artifact:
+    """
+    Writes the "merged library map". This is a map of original soname to final soname of the form:
+
+    ```
+    original_soname1 final_soname1
+    original_soname2 final_soname1
+    original_soname3 final_soname2
+    ...
+    ```
+    """
+    solib_map = {}  # dict[final_soname, set[original_soname]]
+    for _, shared_libs in shared_libs_by_platform.items():
+        for soname in shared_libs.keys():
+            merged_shared_lib = shared_libs[soname]
+            if merged_shared_lib.is_actually_merged:
+                solib_map.setdefault(soname, set()).update(merged_shared_lib.solib_constituents)
+
+    lines = []
+    for final_soname in sorted(solib_map.keys()):
+        for original_soname in solib_map[final_soname]:
+            lines.append("{} {}".format(original_soname, final_soname))
+
+    # we wanted it sorted by original_soname
+    return ctx.actions.write("merged_library_map.txt", sorted(lines), has_content_based_path = False)
+
+def run_mergemap_codegen(ctx: AnalysisContext, merge_generator: Dependency, merged_library_map: Artifact) -> Artifact:
+    mapping_java = ctx.actions.declare_output("MergedLibraryMapping.java", has_content_based_path = False)
+    args = cmd_args(merge_generator[RunInfo])
+    args.add([merged_library_map, mapping_java.as_output()])
+    ctx.actions.run(args, category = "mergemap_codegen", allow_cache_upload = True)
+    return mapping_java
+
+def write_jni_on_load_mappings(ctx: AnalysisContext, shared_libs_by_platform: dict[str, dict[str, MergedSharedLibrary]]) -> Artifact:
+    """
+    Writes a mapping from merged library soname to the targets that are included in the android merge map.
+
+    This only includes targets with include_in_android_mergemap = True, which are the same targets
+    that appear in merged_library_map.txt.
+
+    The output format matches the merge sequence format:
+    ```
+    (
+        "libappdrivenaudiomerged.so",
+        [
+            "fbandroid/java/com/facebook/rsys/appdrivenaudio:appdrivenaudio-jni",
+            "fbandroid/java/com/facebook/rsys/audio/frame:frame-jni",
+        ],
+    ),
+    ```
+    """
+    solib_to_targets = {}  # dict[final_soname, list[str]]
+    for shared_libs in shared_libs_by_platform.values():
+        for soname, merged_shared_lib in shared_libs.items():
+            if not merged_shared_lib.is_actually_merged:
+                continue
+
+            # Only use solib_constituent_targets, which are targets with include_in_android_mergemap = True
+            solib_to_targets.setdefault(soname, set()).update(merged_shared_lib.solib_constituent_targets)
+
+    lines = []
+    for soname, targets in sorted(solib_to_targets.items()):
+        sorted_targets = sorted([t.raw_target() for t in targets])
+
+        # Format targets as a list with proper indentation
+        if len(sorted_targets) == 0:
+            targets_str = "[]"
+        elif len(sorted_targets) == 1:
+            targets_str = '["{}"]'.format(sorted_targets[0])
+        else:
+            target_lines = ",\n            ".join(['"{}"'.format(t) for t in sorted_targets])
+            targets_str = "[\n            {},\n        ]".format(target_lines)
+        lines.append('    (\n        "{}",\n        {},\n    ),'.format(soname, targets_str))
+
+    return ctx.actions.write("jni_on_load_mappings.txt", "\n".join(lines), has_content_based_path = False)
+
+# We can't merge a prebuilt shared (that has no archive) and must use it's original info.
+# Ideally this would probably be structured info on the linkablenode.
+def _is_prebuilt_shared(node_data: LinkableNode) -> bool:
+    shared_link_info = node_data.link_infos.get(LibOutputStyle("shared_lib"), None)
+    if not shared_link_info or not shared_link_info.default.linkables:
+        return False
+    pic_archive_info = node_data.link_infos.get(LibOutputStyle("pic_archive"), None)
+    if not pic_archive_info or not pic_archive_info.default.linkables:
+        return True
+    return False
+
+def _has_linkable(node_data: LinkableNode) -> bool:
+    for _, output in node_data.link_infos.items():
+        if output.default.linkables:
+            return True
+    return False
+
+def _platform_output_path(path: str, platform: [str, None] = None):
+    if platform:
+        return platform + "/" + path
+    return path
+
+def _transitive_has_non_prebuilt_linkable_deps(target: Label, linkable_nodes: dict[Label, LinkableNode], transitive_linkable_cache: dict[Label, bool]) -> bool:
+    if target in transitive_linkable_cache:
+        return transitive_linkable_cache[target]
+
+    target_node = linkable_nodes.get(target)
+    for dep in target_node.deps:
+        dep_node = linkable_nodes.get(dep)
+        if (_has_linkable(dep_node) and not _is_prebuilt_shared(dep_node)) or _transitive_has_non_prebuilt_linkable_deps(
+            dep, linkable_nodes, transitive_linkable_cache
+        ):
+            transitive_linkable_cache[target] = True
+            return True
+    for dep in target_node.exported_deps:
+        dep_node = linkable_nodes.get(dep)
+        if (_has_linkable(dep_node) and not _is_prebuilt_shared(dep_node)) or _transitive_has_non_prebuilt_linkable_deps(
+            dep, linkable_nodes, transitive_linkable_cache
+        ):
+            transitive_linkable_cache[target] = True
+            return True
+
+    transitive_linkable_cache[target] = False
+    return False
+
+def _shared_lib_for_prebuilt_shared(
+    ctx: AnalysisContext,
+    cxx_toolchain: CxxToolchainInfo,
+    target: Label,
+    node_data: LinkableNode,
+    linkable_nodes: dict[Label, LinkableNode],
+    transitive_linkable_cache: dict[Label, bool],
+    platform: [str, None] = None,
+) -> SharedLibrary:
+    expect(
+        len(node_data.shared_libs.libraries) == 1,
+        "unexpected shared_libs length for somerge of {} ({})".format(target, node_data.shared_libs),
+    )
+
+    # TODO(cjhopman): We don't currently support prebuilt shared libs with deps on other libs because
+    # we don't compute the shared lib deps of prebuilt shared libs here. That
+    # shouldn't be too hard, but we haven't needed it.
+    expect(
+        not _transitive_has_non_prebuilt_linkable_deps(target, linkable_nodes, transitive_linkable_cache),
+        "prebuilt shared library `{}` with non-prebuilt linkable deps not supported by somerge".format(target),
+    )
+
+    shlib = node_data.shared_libs.libraries[0]
+    soname = shlib.soname.ensure_str()
+    shlib = shlib.lib
+    output_path = _platform_output_path(soname, platform)
+    return create_shlib(
+        lib = shlib,
+        stripped_lib = strip_lib(ctx, cxx_toolchain, shlib.output, output_path),
+        link_args = None,
+        shlib_deps = None,
+        can_be_asset = node_data.can_be_asset,
+        for_primary_apk = False,
+        soname = soname,
+        label = target,
+    )
+
+def _run_jni_onload_check(
+    ctx: AnalysisContext,
+    cxx_toolchain: CxxToolchainInfo,
+    check_inputs: list,
+    output: Artifact,
+):
+    """Verify that no input to a merged library defines JNI_OnLoad.
+
+    A constituent with allow_jni_merging = True has its JNI_OnLoad renamed by
+    jni_lib_merge.h, and the JNI_OnLoad symbol in the merged library is
+    manufactured by -Wl,--defsym. --defsym silently overrides a constituent's
+    own definition rather than colliding with it, so a constituent that has a
+    JNI_OnLoad but did not opt in has it discarded with no diagnostic and is
+    never registered on MergedSoMapping$Invoke_JNI_OnLoad -- an
+    UnsatisfiedLinkError at runtime and nothing at build time.
+
+    This has to inspect the link *inputs*: by the time the merged library
+    exists, --defsym has erased the evidence.
+    """
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+
+    # write_json renders each artifact as its path and, with with_inputs, makes
+    # the objects inputs of the action so they are materialized for the scan.
+    manifest = ctx.actions.write_json(
+        "jni_onload_check_inputs.json",
+        [{"artifact": obj, "merged_lib": soname, "target": target} for soname, target, obj in check_inputs],
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+    ctx.actions.run(
+        cmd_args(
+            android_toolchain.jni_onload_check[RunInfo],
+            "--inputs",
+            manifest,
+            "--nm",
+            cxx_toolchain.binary_utilities_info.nm,
+            "--out",
+            output.as_output(),
+        ),
+        category = "jni_onload_check",
+        # Reads every object that goes into every merged library; running it
+        # remotely avoids shipping them back for a local scan.
+        prefer_remote = True,
+    )
+
+def _link_info_object_artifacts(link_info: LinkInfo) -> list[Artifact]:
+    """The compiled inputs a LinkInfo contributes, for symbol inspection.
+
+    Thin archives are represented by their member objects, which sidesteps the
+    fact that a thin archive's member paths are relative to the archive itself
+    and so cannot be read from an arbitrary working directory.
+    """
+    artifacts = []
+    for linkable in link_info.linkables:
+        if isinstance(linkable, ArchiveLinkable):
+            if linkable.archive.external_objects:
+                artifacts.extend(linkable.archive.external_objects)
+            else:
+                artifacts.append(linkable.archive.artifact)
+        elif isinstance(linkable, ObjectsLinkable):
+            artifacts.extend(linkable.objects or [])
+    return artifacts
+
+def _get_merged_linkables_for_platform(
+    ctx: AnalysisContext,
+    cxx_toolchain: CxxToolchainInfo,
+    native_library_merge_linker_args_all: list,
+    platform: str | None,
+    glue_linkable: [(Label, LinkInfo), None],
+    default_shared_libs: dict[str, SharedLibrary],
+    linkable_nodes: dict[Label, LinkableNode],
+    merge_map: dict[str, [str, None]],
+    merge_linker_args: dict[str, typing.Any],
+    apk_module_graph: typing.Callable,
+    jni_onload_check_inputs: list | None = None,
+) -> (dict[str, MergedSharedLibrary], MergedLinkablesDebugInfo):
+    """
+    This takes the merge mapping and constructs the resulting merged shared libraries.
+
+    This is similar to link_groups used by ios and cxx_binary, but is sufficiently different that it needs its
+    own implementation. Potentially we could find a generalization of them that covers both.
+
+    An overview of how this works:
+
+    The input includes a mapping of target -> link group. This mapping does not need to be comprehensive, a target
+    not in that mapping is assigned to its own link group. The input also contains a mapping of target -> apk module,
+    and this must have a mapping for every target. A link group cannot contain targets in different apk modules.
+
+    Once we have the mapping of link groups, we construct an analog of the LinkableGraph on the new link group graph.
+    This new graph consists of LinkGroupLinkableNodes (in some sense, the merged equivalent of LinkableNode).
+    We traverse this graph from the bottom up, producing link info for each node.
+
+    First, there are some special cases:
+
+    If a target is "not actually merged" (i.e. it's in a link group where it is the only constituent) then it may get
+    special handling if:
+        (1) it is lib with static preferred linkage or it contains no linkables (i.e. no code)
+        (2) a prebuild shared lib
+    For both these cases we will produce a LinkGroupLinkableNode that basically reuses their original information. For
+    every other case we will produce a node that represents a shared library that we define.
+
+    When constructing a LinkableNode for a link group, we will be traversing sort of a hybrid graph, as we will traverse
+    the primary constituents of the link group itself in the original LinkableGraph, but dependencies outside of the link
+    group will be mapped to the corresponding LinkGroupLinkableNode (and potentially then further traversing that node's
+    deps).
+
+    The merge mapping input determines the "primary constituents" of each link group. The "real constituents" of that link
+    group will include all those primary constituents, all of the transitive non-shared lib deps in the linkgroup linkable
+    graph, and then all the shared lib dependencies of all of them (that is describing a traversal similar to the
+    normal link strategies).
+
+    There are some subtle differences in the handling of primary constituents and the statically linked non-primary
+    constituents:
+    1. all primary constituents are public nodes, non primary ones are only public if they are transitively exported_deps
+    of a primary constituent. A public node is linked via "link whole".
+    2. linker_flags of primary constituents are included in the link, for non primary they are not
+    """
+    debug_info = MergedLinkablesDebugInfo(
+        unmerged_statics = [],
+        group_debug = {},
+        with_default_soname = [],
+        missing_default_solibs = [],
+    )
+
+    linkable_nodes_graph = {k: dedupe(v.deps + v.exported_deps) for k, v in linkable_nodes.items()}
+    topo_sorted_targets = pre_order_traversal(linkable_nodes_graph)
+
+    # first we collect basic information about each link group, this will populate the fields in LinkGroupData and
+    # map target labels to their link group name.
+    link_groups = {}
+    target_to_link_group = {}
+
+    # Because we cannot attach this to the LinkableNode after the fact, declare a cache for each platform
+    transitive_linkable_cache = {}
+
+    for target in topo_sorted_targets:
+        expect(target not in target_to_link_group, "prelude internal error, target seen twice?")
+        target_apk_module = apk_module_graph(str(target.raw_target()))
+
+        link_group = merge_map.get(str(target), None)
+        if not link_group:
+            link_group = str(target)
+            link_groups[link_group] = LinkGroupData(
+                group_name = target,
+                constituents = [target],
+                apk_module = target_apk_module,
+            )
+        elif link_group in link_groups:
+            link_group_data = link_groups[link_group]
+
+            # TODO(cjhopman): buck1 provides a more useful error here in that it lists the module mappings for all
+            # constituents of the merge group (rather than just one conflict). That allows users to resolve all the
+            # issues at once. With merge sequence merging (the replacement for merge map), this error shouldn't ever be hit
+            # and so maybe it's not necessary to improve it.
+            expect(
+                link_group_data.apk_module == target_apk_module,
+                "Native library merge of {} has inconsistent application module mappings:\n{} is in module {}\n{} is in module {}",
+                link_group_data.group_name,
+                target,
+                target_apk_module,
+                link_group_data.constituents[0],
+                link_group_data.apk_module,
+            )
+            link_groups[link_group].constituents.append(target)
+        else:
+            link_groups[link_group] = LinkGroupData(
+                group_name = link_group,
+                constituents = [target],
+                apk_module = target_apk_module,
+            )
+
+        target_to_link_group[target] = link_group
+
+    # Now that all targets are assigned to a link group, build up the link group graph.
+    link_groups_graph_builder = {}
+    for target in topo_sorted_targets:
+        target_group = target_to_link_group[target]
+        group_deps = link_groups_graph_builder.setdefault(target_group, {})
+        for dep in linkable_nodes_graph[target]:
+            dep_group = target_to_link_group[dep]
+            if target_group != dep_group and dep_group not in group_deps:
+                # Store one example of why target_group depends on dep_group
+                group_deps[dep_group] = (target, dep)
+    link_groups_graph = {k: list(v.keys()) for k, v in link_groups_graph_builder.items()}
+
+    archive_output_style = LibOutputStyle("pic_archive")
+    shlib_output_style = LibOutputStyle("shared_lib")
+
+    link_group_linkable_nodes = {}
+    group_shared_libs = {}
+    included_default_solibs = {}
+
+    def edge_explainer(src_group, dest_group):
+        """Explains in an error why src_group has a dependency on dest_group"""
+        if src_group not in link_groups_graph_builder or dest_group not in link_groups_graph_builder[src_group]:
+            return ["Unknown"]
+
+        src_target, dest_target = link_groups_graph_builder[src_group][dest_group]
+        return ["   " + str(src_target), "-> " + str(dest_target)]
+
+    # Now we will traverse from the leaves up the graph (the link groups graph). As we traverse, we will produce
+    # a link group linkablenode for each group.
+    for group in post_order_traversal(link_groups_graph, edge_explainer = edge_explainer):
+        group_data = link_groups[group]
+        is_actually_merged = len(group_data.constituents) > 1
+
+        non_asset_constituents = [target for target in group_data.constituents if not linkable_nodes[target].can_be_asset]
+        can_be_asset = len(non_asset_constituents) == 0
+
+        if not is_actually_merged:
+            target = group_data.constituents[0]
+            node_data = linkable_nodes[target]
+
+            if node_data.preferred_linkage == Linkage("static") or not _has_linkable(node_data):
+                debug_info.unmerged_statics.append(target)
+                link_group_linkable_nodes[group] = LinkGroupLinkableNode(
+                    link = node_data.link_infos[archive_output_style].default,
+                    deps = dedupe_by_value([target_to_link_group[t] for t in node_data.deps]),
+                    exported_deps = dedupe_by_value([target_to_link_group[t] for t in node_data.exported_deps]),
+                    shared_lib = None,
+                    exported_linker_flags = (node_data.linker_flags.exported_flags, node_data.linker_flags.exported_post_flags),
+                )
+                continue
+
+            if _is_prebuilt_shared(node_data):
+                shared_lib = _shared_lib_for_prebuilt_shared(
+                    ctx,
+                    cxx_toolchain,
+                    target,
+                    node_data,
+                    linkable_nodes,
+                    transitive_linkable_cache,
+                    platform,
+                )
+                link_group_linkable_nodes[group] = LinkGroupLinkableNode(
+                    link = node_data.link_infos[shlib_output_style].default,
+                    deps = [],
+                    exported_deps = [],
+                    shared_lib = shared_lib,
+                    # exported linker flags for shared libs are in their linkinfo itself and are not exported from dependents
+                    exported_linker_flags = None,
+                )
+                group_shared_libs[shared_lib.soname.ensure_str()] = MergedSharedLibrary(
+                    soname = shared_lib.soname.ensure_str(),
+                    lib = shared_lib,
+                    apk_module = group_data.apk_module,
+                    solib_constituents = [],
+                    solib_constituent_targets = [],
+                    is_actually_merged = False,
+                    primary_constituents = [target],
+                )
+                continue
+
+        exported_linker_flags = []
+        exported_linker_post_flags = []
+        links = []
+
+        if is_actually_merged and glue_linkable:
+            links.append(set_link_info_link_whole(glue_linkable[1]))
+
+        solib_constituents = []
+        solib_constituent_targets = []
+        group_deps = []
+        group_exported_deps = []
+        # (target, object) pairs for the JNI_OnLoad check. Collected here
+        # because the constituents' link infos are not retained anywhere else,
+        # and associated with the soname below once it is known.
+        check_objects = []
+        for key in group_data.constituents:
+            expect(target_to_link_group[key] == group)
+            node = linkable_nodes[key]
+
+            default_solibs = list([shlib.soname.ensure_str() for shlib in node.shared_libs.libraries])
+            if not default_solibs and node.preferred_linkage == Linkage("static"):
+                default_solibs = [node.default_soname]
+
+            for soname in default_solibs:
+                included_default_solibs[soname] = True
+                if node.include_in_android_mergemap:
+                    solib_constituents.append(soname)
+                    solib_constituent_targets.append(key)
+
+            node = linkable_nodes[key]
+            link_info = node.link_infos[archive_output_style].default
+
+            if jni_onload_check_inputs != None:
+                target_str = str(key.raw_target())
+                for obj in _link_info_object_artifacts(link_info):
+                    check_objects.append((target_str, obj))
+
+            # the propagated link info should already be wrapped with exported flags.
+            link_info = wrap_link_info(
+                link_info,
+                pre_flags = node.linker_flags.flags,
+                post_flags = node.linker_flags.post_flags,
+            )
+            exported_linker_flags.extend(node.linker_flags.exported_flags)
+            exported_linker_post_flags.extend(node.linker_flags.exported_post_flags)
+            links.append(set_link_info_link_whole(link_info))
+
+            dep_groups = [target_to_link_group[dep] for dep in node.deps]
+            group_deps.extend([dep_group for dep_group in dep_groups if dep_group != group])
+
+            exported_dep_groups = [target_to_link_group[dep] for dep in node.exported_deps]
+            group_exported_deps.extend([dep_group for dep_group in exported_dep_groups if dep_group != group])
+
+        soname = group
+        if not is_actually_merged:
+            soname = linkable_nodes[group_data.constituents[0]].default_soname
+            debug_info.with_default_soname.append((soname, group_data.constituents[0]))
+
+        # Only groups that are actually merged are checked. A group of one is a
+        # normal standalone library, where defining JNI_OnLoad is correct.
+        if jni_onload_check_inputs != None and is_actually_merged:
+            for target_str, obj in check_objects:
+                jni_onload_check_inputs.append((soname, target_str, obj))
+
+        output_path = _platform_output_path(soname, platform)
+
+        link_merge_info = LinkGroupMergeInfo(
+            label = group,
+            deps = dedupe_by_value(group_deps),
+            exported_deps = dedupe_by_value(group_exported_deps),
+            constituent_link_infos = links,
+        )
+        link_args, shlib_deps, link_deps_graph = _create_merged_link_args(
+            root_target = link_merge_info,
+            linkable_nodes = link_group_linkable_nodes,
+            cxx_toolchain = cxx_toolchain,
+        )
+        link_args = [link_args]
+        if native_library_merge_linker_args_all:
+            link_args += [LinkArgs(flags = native_library_merge_linker_args_all)]
+        if soname in merge_linker_args:
+            link_args += [LinkArgs(flags = merge_linker_args[soname])]
+
+        # Emit the Middle Gatorade container from the merge link; {} when off.
+        # @oss-disable[end= ]: mg_args = middle_gatorade_merge_args(ctx, output_path, cxx_toolchain)
+        shared_lib = create_shared_lib(
+            ctx,
+            output_path = output_path,
+            soname = soname,
+            link_args = link_args,
+            cxx_toolchain = cxx_toolchain,
+            shared_lib_deps = [link_group_linkable_nodes[label].shared_lib.soname.ensure_str() for label in shlib_deps],
+            label = group_data.constituents[0],
+            can_be_asset = can_be_asset,
+            # @oss-disable[end= ]: **mg_args,
+        )
+
+        link_group_linkable_nodes[group] = LinkGroupLinkableNode(
+            link = LinkInfo(
+                name = soname,
+                pre_flags = exported_linker_flags,
+                linkables = [
+                    SharedLibLinkable(
+                        lib = shared_lib.lib.output,
+                    )
+                ],
+                post_flags = exported_linker_post_flags,
+            ),
+            deps = link_merge_info.deps,
+            exported_deps = link_merge_info.exported_deps,
+            shared_lib = shared_lib,
+            # exported linker flags for shared libs are in their linkinfo itself and are not exported from dependents
+            exported_linker_flags = None,
+        )
+        group_shared_libs[soname] = MergedSharedLibrary(
+            soname = soname,
+            lib = shared_lib,
+            apk_module = group_data.apk_module,
+            solib_constituents = solib_constituents,
+            solib_constituent_targets = solib_constituent_targets,
+            is_actually_merged = is_actually_merged,
+            primary_constituents = group_data.constituents,
+        )
+
+        debug_info.group_debug.setdefault(
+            group,
+            struct(
+                soname = soname,
+                merged = is_actually_merged,
+                primary_constituents = group_data.constituents,
+                real_constituents = link_deps_graph.keys(),
+                shlib_deps = shlib_deps,
+                exported_linker_flags = exported_linker_flags,
+                exported_linker_post_flags = exported_linker_post_flags,
+                non_asset_constituents = non_asset_constituents,
+            ),
+        )
+
+    debug_info.missing_default_solibs.extend([d for d in default_shared_libs if d not in included_default_solibs])
+
+    return group_shared_libs, debug_info
+
+# The current default link strategies don't produce enough information in the
+# SharedLibrary objects to perform relinking. To do that best, linking should be based on
+# the LinkableGraph rather than the current approach with MergedLinkInfo.
+# The overall plan for linking is to move to linkable graph-based linking, but for now
+# we can do it just for the case that we need it.
+def _create_all_relinkable_links(
+    ctx: AnalysisContext,
+    platform_to_original_native_linkables: dict[str, dict[str, SharedLibrary]],
+    graph_node_map_by_platform: dict[str, dict[Label, LinkableNode]],
+) -> (dict[str, dict[str, SharedLibrary]], dict[str, typing.Any]):
+    final_platform_to_native_linkables = {}
+    link_graphs_by_platform = {}
+    for platform in platform_to_original_native_linkables:
+        linkables, link_graphs = _create_relinkable_links(
+            ctx,
+            cxx_toolchain = ctx.attrs._cxx_toolchain[platform][CxxToolchainInfo],
+            linkable_nodes = graph_node_map_by_platform[platform],
+            platform = platform,
+        )
+        link_graphs_by_platform[platform] = link_graphs
+        final_platform_to_native_linkables[platform] = linkables
+
+    # sanity check that we produce the same list of linkables that are produced by standard linking.
+    original_sonames = sorted(platform_to_original_native_linkables.keys())
+    final_sonames = sorted(final_platform_to_native_linkables.keys())
+    expect(original_sonames == final_sonames, "Unexpected differences in final sonames! {} {}".format(original_sonames, final_sonames))
+
+    debug_outputs = {}
+
+    # The biggest issue we could run into here is that we produce different link args than the original, so let's make that easy to debug.
+    for platform in platform_to_original_native_linkables:
+        for soname, lib in platform_to_original_native_linkables[platform].items():
+            final = final_platform_to_native_linkables[platform][soname]
+            original_args, _ = ctx.actions.write(
+                "{}/{}/original.args".format(platform, soname),
+                [unpack_link_args(args, LinkOrdering("topological")) for args in lib.link_args] if lib.link_args else "",
+                allow_args = True,
+                has_content_based_path = False,
+            )
+            final_args, _ = ctx.actions.write(
+                "{}/{}/final.args".format(platform, soname),
+                [unpack_link_args(args, LinkOrdering("topological")) for args in final.link_args] if final.link_args else "",
+                allow_args = True,
+                has_content_based_path = False,
+            )
+            debug_outputs["{}/{}/original.args".format(platform, soname)] = original_args
+            debug_outputs["{}/{}/final.args".format(platform, soname)] = final_args
+
+            if lib.label in link_graphs_by_platform[platform]:
+                link_graph = ctx.actions.write_json(
+                    "{}/{}/link.graph".format(platform, soname),
+                    link_graphs_by_platform[platform][lib.label],
+                    pretty = True,
+                    has_content_based_path = False,
+                )
+                debug_outputs["{}/{}/link.graph".format(platform, soname)] = link_graph
+
+            # TODO(cjhopman): should we also just produce a diff here? We could also consider creating sort of a merged diff or a list
+            # of the differing argsfiles.
+            # We can't compare them eagerly because the link args have large tsets that we don't want to traverse at analysis time.
+
+    return final_platform_to_native_linkables, debug_outputs
+
+def _create_relinkable_links(
+    ctx: AnalysisContext, *, cxx_toolchain: CxxToolchainInfo, linkable_nodes: dict[Label, LinkableNode], platform: str
+) -> (dict[str, SharedLibrary], dict[Label, dict[Label, list[Label]]]):
+    linkable_nodes_graph = {target: value.deps + value.exported_deps for target, value in linkable_nodes.items()}
+    shared_libs = {}
+    shared_lib_overrides = {}
+    transitive_linkable_cache = {}
+    debug_link_deps = {}
+    for target in post_order_traversal(linkable_nodes_graph):
+        node = linkable_nodes[target]
+        if node.preferred_linkage == Linkage("static") or not _has_linkable(node):
+            continue
+
+        if _is_prebuilt_shared(node):
+            shared_lib = _shared_lib_for_prebuilt_shared(ctx, cxx_toolchain, target, node, linkable_nodes, transitive_linkable_cache, platform)
+        else:
+            soname = node.default_soname
+            output_path = "relinkable-libs/{}/{}".format(platform, soname)
+            link_args, shlib_deps, link_deps_graph = _create_link_args(
+                cxx_toolchain = cxx_toolchain,
+                root_target = target,
+                node = node,
+                graph = linkable_nodes,
+                shared_lib_overrides = shared_lib_overrides,
+            )
+            debug_link_deps[target] = link_deps_graph
+            shared_lib = create_shared_lib(
+                ctx,
+                output_path = output_path,
+                soname = soname,
+                link_args = [link_args],
+                cxx_toolchain = cxx_toolchain,
+                shared_lib_deps = [shared_lib_overrides[lib].name for lib in shlib_deps if lib in shared_lib_overrides],
+                label = target,
+                can_be_asset = node.can_be_asset,
+            )
+        shared_lib_overrides[target] = LinkInfo(
+            name = shared_lib.soname.ensure_str(),
+            pre_flags = node.linker_flags.exported_flags,
+            linkables = [
+                SharedLibLinkable(
+                    lib = shared_lib.lib.output,
+                )
+            ],
+            post_flags = node.linker_flags.exported_post_flags,
+        )
+        shared_libs[shared_lib.soname.ensure_str()] = shared_lib
+
+    return {lib.soname.ensure_str(): lib for lib in shared_libs.values()}, debug_link_deps
+
+def _create_link_args(
+    *,
+    cxx_toolchain: CxxToolchainInfo,
+    root_target: Label,
+    node: LinkableNode,
+    graph: dict[Label, LinkableNode],
+    shared_lib_overrides: dict[Label, LinkInfo] | None = None,
+) -> (LinkArgs, list[Label], dict[Label, list[Label]]):
+    if LinkOrdering(cxx_toolchain.linker_info.link_ordering) != LinkOrdering("topological"):
+        fail("don't yet support link ordering {}".format(cxx_toolchain.linker_info.link_ordering))
+
+    # TODO(cjhopman): verify picbehavior == pic
+    link_strategy = node.default_link_strategy
+    if not shared_lib_overrides:
+        shared_lib_overrides = {}
+
+    link_traversal_cache = {}
+
+    def link_traversal(label: Label) -> list[Label]:
+        def link_traversal_deps(label):
+            node = graph[label]
+            if label == root_target:
+                return node.deps + node.exported_deps
+            actual_linkable_type = get_lib_output_style(link_strategy, node.preferred_linkage, PicBehavior("supported"))
+            if actual_linkable_type == LibOutputStyle("shared_lib"):
+                return node.exported_deps
+            else:
+                return node.deps + node.exported_deps
+
+        res = link_traversal_cache.get(label, None)
+        if res:
+            return res
+        res = link_traversal_deps(label)
+        link_traversal_cache[label] = res
+        return res
+
+    links = []
+    shlib_deps = []
+    for target in rust_matching_topological_traversal(None, [root_target], link_traversal):
+        is_root = target == root_target
+        node = graph[target]
+        preferred_linkable_type = get_lib_output_style(link_strategy, node.preferred_linkage, PicBehavior("supported"))
+
+        if is_root:
+            link_info = node.link_infos[LibOutputStyle("pic_archive")].default
+            link_info = wrap_link_info(
+                link_info,
+                pre_flags = node.linker_flags.flags,
+                post_flags = node.linker_flags.post_flags,
+            )
+            links.append(set_link_info_link_whole(link_info))
+        elif preferred_linkable_type == LibOutputStyle("shared_lib"):
+            if target in shared_lib_overrides:
+                links.append(shared_lib_overrides[target])
+            else:
+                links.append(node.link_infos[LibOutputStyle("shared_lib")].default)
+            shlib_deps.append(target)
+        else:
+            links.append(node.link_infos[preferred_linkable_type].default)
+
+    extra_runtime_flags = cxx_toolchain.linker_info.shared_dep_runtime_ld_flags or []
+    if extra_runtime_flags:
+        links.append(LinkInfo(pre_flags = extra_runtime_flags))
+    return LinkArgs(infos = links), shlib_deps, link_traversal_cache
+
+# Equivalent to _create_link_args but for somerge
+def _create_merged_link_args(
+    *, cxx_toolchain: CxxToolchainInfo, root_target: LinkGroupMergeInfo, linkable_nodes: dict[GroupLabel, LinkGroupLinkableNode]
+) -> (LinkArgs, list[GroupLabel], dict[GroupLabel, list[GroupLabel]]):
+    if LinkOrdering(cxx_toolchain.linker_info.link_ordering) != LinkOrdering("topological"):
+        fail("don't yet support link ordering {}".format(cxx_toolchain.linker_info.link_ordering))
+
+    link_traversal_cache = {}
+
+    def link_traversal(label: GroupLabel) -> list[GroupLabel]:
+        def link_traversal_deps(label: GroupLabel):
+            if label == root_target.label:
+                return root_target.deps + root_target.exported_deps
+
+            linkable_node = linkable_nodes[label]
+            if linkable_node.shared_lib:
+                return linkable_node.exported_deps
+            else:
+                return linkable_node.deps + linkable_node.exported_deps
+
+        res = link_traversal_cache.get(label, None)
+        if res:
+            return res
+        res = link_traversal_deps(label)
+        link_traversal_cache[label] = res
+        return res
+
+    links = []
+    shlib_deps = []
+    for label in rust_matching_topological_traversal(None, [root_target.label], link_traversal):
+        if label == root_target.label:
+            links.extend(root_target.constituent_link_infos)
+        else:
+            linkable_node = linkable_nodes[label]
+            links.append(linkable_node.link)
+            if linkable_node.shared_lib:
+                shlib_deps.append(label)
+
+    extra_runtime_flags = cxx_toolchain.linker_info.shared_dep_runtime_ld_flags or []
+    if extra_runtime_flags:
+        links.append(LinkInfo(pre_flags = extra_runtime_flags))
+    return LinkArgs(infos = links), shlib_deps, link_traversal_cache
+
+def _bolt_libraries(
+    ctx: AnalysisContext,
+    libraries_by_platform: dict[str, dict[str, SharedLibrary]],
+    bolt_args: dict[str, ArgLike],
+    native_cmd_entries = None,
+    record_underlying_link: bool = False,
+) -> (
+    dict[str, dict[str, SharedLibrary]],
+    dict[str, dict[str, SharedLibrary]],
+):
+    bolted_libraries_by_platform = {}
+    pre_bolt_libraries_by_platform = {}
+
+    for platform, shared_libraries in libraries_by_platform.items():
+        cxx_toolchain = ctx.attrs._cxx_toolchain[platform][CxxToolchainInfo]
+        bolted_libraries = bolted_libraries_by_platform.setdefault(platform, {})
+        pre_bolt_libraries = pre_bolt_libraries_by_platform.setdefault(platform, {})
+
+        for soname, _ in shared_libraries.items():
+            original_shared_library = shared_libraries[soname]
+            if not soname in bolt_args:
+                bolted_libraries[soname] = original_shared_library
+                continue
+
+            # On plain-link apps (record_underlying_link), record the bolted soname's underlying link
+            # BEFORE the swap: the bolted/pre-bolt objects below are command-less, so finalization
+            # skips them and this plain link would otherwise be lost. When merging/relinking, that
+            # underlying command is already captured at the merge/relink site, so skip it here.
+            if record_underlying_link:
+                record_link_command(native_cmd_entries, "link", platform, soname, original_shared_library.lib)
+
+            # Create pre-BOLT copy with .pre_bolt.so suffix
+            pre_bolt_soname = soname.removesuffix(".so") + ".pre_bolt.so"
+            pre_bolt_output_path = "pre-bolt-libs/{}/{}".format(platform, pre_bolt_soname)
+            pre_bolt_copy = ctx.actions.copy_file(pre_bolt_output_path, original_shared_library.lib.output, has_content_based_path = False)
+
+            # Create pre-BOLT SharedLibrary object
+            pre_bolt_linked_object = LinkedObject(
+                output = pre_bolt_copy,
+                unstripped_output = pre_bolt_copy,
+            )
+
+            pre_bolt_shared_lib = create_shlib(
+                lib = pre_bolt_linked_object,
+                stripped_lib = strip_lib(ctx, cxx_toolchain, pre_bolt_linked_object.output),
+                can_be_asset = original_shared_library.can_be_asset,
+                for_primary_apk = False,
+                soname = pre_bolt_soname,
+                label = original_shared_library.label,
+            )
+
+            pre_bolt_libraries[pre_bolt_soname] = pre_bolt_shared_lib
+
+            output_path = "bolt-libs/{}/{}".format(platform, soname)
+
+            bolted_libraries[soname] = _create_bolt_lib(
+                ctx = ctx,
+                cxx_toolchain = cxx_toolchain,
+                prebolt_lib = original_shared_library,
+                output_path = output_path,
+                bolt_args = bolt_args[soname],
+                native_cmd_entries = native_cmd_entries,
+                platform = platform,
+            )
+
+    return bolted_libraries_by_platform, pre_bolt_libraries_by_platform
+
+# When linking shared libraries, by default, all symbols are exported from the library. In a
+# particular application, though, many of those symbols may never be used. Ideally, in each apk,
+# each shared library would only export the minimal set of symbols that are used by other libraries
+# in the apk. This would allow the linker to remove any dead code within the library (the linker
+# can strip all code that is unreachable from the set of exported symbols).
+#
+# The native relinker tries to remedy the situation. When enabled for an apk, the native
+# relinker will take the set of libraries in the apk and relink them in reverse order telling the
+# linker to only export those symbols that are referenced by a higher library.
+#
+# The way this works is that the relinker does a topological traversal of the linked libraries (i.e.
+# top-down, visiting nodes before their dependencies, this is the opposite order of most things we do
+# in a build) and does:
+# 1. extract the set of global symbols by the original lib
+# 2. intersect that with the set of undefined symbols in all transitive dependents (i.e. higher in the graph) and
+#    rules for required symbols (Java_*, Jni_Onload, relinker blocklist)
+# 3. write a version script that says to make public only those symbols from (2)
+# 4. link the lib with the exact same link line + the version script. Note that this means that the relinked libraries each are
+#    actually linked against non-relinked ones. This does mean there's some risk of not detecting missing symbols (though mostly
+#    only if they are caused by the relinker changes themselves).
+# 5. extract the list of undefined symbols in the relinked libs (i.e. those symbols needed from dependencies and what had been
+#    used in (1) above from higher nodes).
+
+def relink_libraries(
+    ctx: AnalysisContext, libraries_by_platform: dict[str, dict[str, SharedLibrary]], native_cmd_entries = None
+) -> dict[str, dict[str, SharedLibrary]]:
+    relinker_extra_deps = getattr(ctx.attrs, "relinker_extra_deps", None)
+    relinker_extra_args = getattr(ctx.attrs, "relinker_extra_args", {})
+    relinker_extra_args_all = getattr(ctx.attrs, "relinker_extra_args_all", [])
+    red_linkables = {}
+    if relinker_extra_deps:
+        for red_elem in relinker_extra_deps:
+            for platform, red in red_elem.items():
+                red_link_graph = red.get(LinkableGraph)
+                expect(red_link_graph != None, "relinker_extra_deps (`{}`) should be a linkable target", red.label)
+                red_linkable = red_link_graph.nodes.value.linkable
+                expect(red_linkable != None, "relinker_extra_deps (`{}`) should be a linkable target", red.label)
+                expect(red_linkable.preferred_linkage == Linkage("static"), "buck2 currently only supports preferred_linkage='static' relinker_extra_deps")
+                if platform not in red_linkables:
+                    red_linkables[platform] = []
+                red_linkables[platform].append((red.label, red_linkable.link_infos[LibOutputStyle("pic_archive")].default))
+
+    relinked_libraries_by_platform = {}
+    for platform, shared_libraries in libraries_by_platform.items():
+        cxx_toolchain = ctx.attrs._cxx_toolchain[platform][CxxToolchainInfo]
+
+        relinked_libraries = relinked_libraries_by_platform.setdefault(platform, {})
+        unsupported_libs = {}
+        shlib_graph = {}
+        rev_shlib_graph = {}
+        for soname, solib in shared_libraries.items():
+            shlib_graph[soname] = []
+            rev_shlib_graph.setdefault(soname, [])
+            if solib.shlib_deps == None or solib.link_args == None:
+                unsupported_libs[soname] = True
+            else:
+                for dep in solib.shlib_deps:
+                    shlib_graph[soname].append(dep)
+                    rev_shlib_graph.setdefault(dep, []).append(soname)
+        needed_symbols_files = {}
+        for soname in pre_order_traversal(shlib_graph):
+            if soname in unsupported_libs:
+                relinked_libraries[soname] = shared_libraries[soname]
+                continue
+
+            original_shared_library = shared_libraries[soname]
+            output_path = "xdso-dce-relinker-libs/{}/{}".format(platform, soname)
+
+            provided_symbols_file = extract_provided_symbols(ctx, cxx_toolchain, original_shared_library.lib.output)
+            needed_symbols_for_this = [needed_symbols_files.get(rdep) for rdep in rev_shlib_graph[soname]]
+            relinker_version_script = ctx.actions.declare_output(output_path + ".relinker.version_script", has_content_based_path = False)
+            create_relinker_version_script(
+                ctx.actions,
+                output = relinker_version_script,
+                relinker_allowlist = [regex(s) for s in ctx.attrs.relinker_whitelist],
+                provided_symbols = provided_symbols_file,
+                needed_symbols = needed_symbols_for_this,
+            )
+            relinker_link_args = (
+                original_shared_library.link_args
+                + [LinkArgs(flags = relinker_extra_args_all)]
+                + ([LinkArgs(infos = [set_link_info_link_whole(red_linkable[1]) for red_linkable in red_linkables[platform]])] if len(red_linkables) > 0 else [])
+                +
+                # Add per-library linker args from relinker_extra_args attribute
+                ([LinkArgs(flags = relinker_extra_args[soname])] if soname in relinker_extra_args else [])
+                +
+                # We add the version script last to allow easy post-processing if needed.
+                [LinkArgs(flags = [cmd_args(relinker_version_script, format = "-Wl,--version-script={}")])]
+            )
+
+            extra_args = {} # @oss-enable
+            # @oss-disable[end= ]: extra_args = add_gatorade_relinker_args(ctx, cxx_toolchain, output_path, soname, platform)
+            relinker_output_args = get_extra_relinker_args(ctx, output_path, soname)
+            extra_args = merge_extra_linker_args([extra_args, relinker_output_args])
+            shared_lib = create_shared_lib(
+                ctx,
+                output_path = output_path,
+                soname = soname,
+                link_args = relinker_link_args,
+                cxx_toolchain = cxx_toolchain,
+                shared_lib_deps = original_shared_library.shlib_deps,
+                label = original_shared_library.label,
+                can_be_asset = original_shared_library.can_be_asset,
+                **extra_args,
+            )
+            needed_symbols_from_this = extract_undefined_symbols(ctx, cxx_toolchain, shared_lib.lib.output)
+            unioned_needed_symbols_file = ctx.actions.declare_output(output_path + ".all_needed_symbols", has_content_based_path = False)
+            union_needed_symbols(ctx.actions, unioned_needed_symbols_file, needed_symbols_for_this + [needed_symbols_from_this])
+            needed_symbols_files[soname] = unioned_needed_symbols_file
+
+            relinked_libraries[soname] = shared_lib
+            record_link_command(native_cmd_entries, "relink", platform, soname, shared_lib.lib)
+
+    return relinked_libraries_by_platform
+
+def _relink_for_native_libs(ctx: AnalysisContext, libraries_by_platform: dict[str, dict[str, SharedLibrary]], native_cmd_entries = None) -> tuple:
+    return (relink_libraries(ctx, libraries_by_platform, native_cmd_entries), {}) # @oss-enable
+    # @oss-disable[end= ]: return relink_for_native_libs(ctx, libraries_by_platform, relink_libraries, create_shared_lib, native_cmd_entries)
+
+def extract_provided_symbols(ctx: AnalysisContext, toolchain: CxxToolchainInfo, lib: Artifact) -> Artifact:
+    return extract_defined_syms(ctx, toolchain, lib, "relinker_extract_provided_symbols")
+
+def create_relinker_version_script(
+    actions: AnalysisActions, relinker_allowlist: list[regex], output: Artifact, provided_symbols: Artifact, needed_symbols: list[Artifact]
+):
+    def create_version_script(ctx, artifacts, outputs):
+        all_needed_symbols = {}
+        for symbols_file in needed_symbols:
+            for line in artifacts[symbols_file].read_string().splitlines():
+                all_needed_symbols[line] = True
+
+        symbols_to_keep = []
+        for symbol in artifacts[provided_symbols].read_string().splitlines():
+            keep_symbol = False
+            if symbol in all_needed_symbols:
+                keep_symbol = True
+            elif symbol == "JNI_OnLoad":
+                keep_symbol = True
+            elif symbol.startswith("Java_"):
+                keep_symbol = True
+            else:
+                for pattern in relinker_allowlist:
+                    if pattern.match(symbol):
+                        keep_symbol = True
+                        break
+
+            if keep_symbol:
+                symbols_to_keep.append(symbol)
+
+        version_script = "{\n"
+        # @oss-disable[end= ]: if is_late_gatorade_enabled(ctx):
+            # @oss-disable[end= ]: symbols_to_keep.append("*_Gatorade_Thunk")
+        if symbols_to_keep:
+            version_script += "global:\n"
+        for symbol in symbols_to_keep:
+            version_script += "  {};\n".format(symbol)
+        version_script += "local: *;\n"
+        version_script += "};\n"
+        ctx.actions.write(outputs[output], version_script)
+
+    actions.dynamic_output(dynamic = needed_symbols + [provided_symbols], inputs = [], outputs = [output.as_output()], f = create_version_script)
+
+def extract_undefined_symbols(ctx: AnalysisContext, toolchain: CxxToolchainInfo, lib: Artifact) -> Artifact:
+    return extract_undefined_syms(ctx, toolchain, lib, "relinker_extract_undefined_symbols")
+
+def union_needed_symbols(actions: AnalysisActions, output: Artifact, needed_symbols: list[Artifact]):
+    def compute_union(ctx, artifacts, outputs):
+        unioned_symbols = {}
+        for symbols_file in needed_symbols:
+            for line in artifacts[symbols_file].read_string().splitlines():
+                unioned_symbols[line] = True
+        symbols = sorted(unioned_symbols.keys())
+        ctx.actions.write(outputs[output], symbols)
+
+    actions.dynamic_output(dynamic = needed_symbols, inputs = [], outputs = [output.as_output()], f = compute_union)
+
+def strip_lib(ctx: AnalysisContext, cxx_toolchain: CxxToolchainInfo, shlib: Artifact, output_path: [str, None] = None):
+    strip_flags = cmd_args(get_strip_non_global_flags(cxx_toolchain))
+    return strip_object(
+        ctx,
+        cxx_toolchain,
+        shlib,
+        strip_flags,
+        output_path = output_path,
+        allow_cache_upload = True,
+    )
+
+def create_shared_lib(
+    ctx: AnalysisContext,
+    *,
+    output_path: str,
+    soname: str,
+    link_args: list[LinkArgs],
+    cxx_toolchain: CxxToolchainInfo,
+    shared_lib_deps: list[str],
+    label: Label,
+    can_be_asset: bool,
+    extra_linker_outputs_factory: typing.Callable | None = None,
+    extra_linker_outputs_flags_factory: typing.Callable | None = None,
+) -> SharedLibrary:
+    for link_arg in link_args:
+        flags = link_arg.flags or []
+        for info in link_arg.infos or []:
+            flags += info.pre_flags or []
+            flags += info.post_flags or []
+        for flag in flags:
+            flag = str(flag)
+            if flag.endswith("--exclude-libs,ALL") or flag.endswith("--exclude-libs=ALL"):
+                fail(
+                    "The behavior of --exclude-libs,ALL is not predictable when building Android binaries and may cause runtime crashes, remove it from {} (or its merged constituents)".format(
+                        label
+                    )
+                )
+    link_result = cxx_link_shared_library(
+        ctx = ctx,
+        output = output_path,
+        name = soname,
+        opts = link_options(
+            links = link_args,
+            link_execution_preference = LinkExecutionPreference("any"),
+            identifier = output_path,
+            strip = False,
+            cxx_toolchain = cxx_toolchain,
+            extra_linker_outputs_factory = extra_linker_outputs_factory,
+            extra_linker_outputs_flags_factory = extra_linker_outputs_flags_factory,
+            allow_cache_upload = True,
+        ),
+    )
+
+    shlib = link_result.linked_object
+    return create_shlib(
+        lib = shlib,
+        stripped_lib = strip_lib(ctx, cxx_toolchain, shlib.output),
+        shlib_deps = shared_lib_deps,
+        link_args = link_args,
+        can_be_asset = can_be_asset,
+        for_primary_apk = False,
+        soname = soname,
+        label = label,
+        extra_outputs = link_result.extra_outputs,
+    )
+
+def _create_bolt_lib(
+    ctx: AnalysisContext,
+    cxx_toolchain: CxxToolchainInfo,
+    prebolt_lib: SharedLibrary,
+    output_path: str,
+    bolt_args: list[ArgLike],
+    native_cmd_entries = None,
+    platform = None,
+) -> SharedLibrary:
+    soname = prebolt_lib.soname.ensure_str()
+    bolt_output = ctx.actions.declare_output(output_path, has_content_based_path = False)
+    action_execution_properties = get_action_execution_attributes(LinkExecutionPreference("any"))
+
+    args = cmd_args(
+        cmd_args(cxx_toolchain.binary_utilities_info.bolt),
+        prebolt_lib.lib.output,
+        "-o",
+        bolt_output.as_output(),
+        bolt_args,
+    )
+
+    ctx.actions.run(
+        args,
+        category = "bolt",
+        prefer_local = action_execution_properties.prefer_local,
+        prefer_remote = action_execution_properties.prefer_remote,
+        local_only = action_execution_properties.local_only,
+        identifier = output_path,
+        allow_cache_upload = True,
+    )
+
+    # Record the bolt command for [native_build_commands], referencing the plain output artifact
+    # (not `as_output()`, which cannot be re-serialized by write_json).
+    if native_cmd_entries != None:
+        native_cmd_entries.append(
+            native_build_command_entry(
+                kind = "bolt",
+                category = "bolt",
+                arch = platform,
+                soname = soname,
+                output = bolt_output.short_path,
+                argv = cmd_args(
+                    cmd_args(cxx_toolchain.binary_utilities_info.bolt),
+                    prebolt_lib.lib.output,
+                    "-o",
+                    bolt_output,
+                    bolt_args,
+                ),
+                identifier = output_path,
+            )
+        )
+
+    linked_object = LinkedObject(
+        output = bolt_output,
+        unstripped_output = bolt_output,
+    )
+
+    return create_shlib(
+        lib = linked_object,
+        stripped_lib = strip_lib(ctx, cxx_toolchain, linked_object.output),
+        can_be_asset = prebolt_lib.can_be_asset,
+        for_primary_apk = False,
+        soname = soname,
+        label = prebolt_lib.label,
+    )
diff --git a/buck2/prelude/android/android_binary_resources_rules.bzl b/buck2/prelude/android/android_binary_resources_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_binary_resources_rules.bzl
@@ -0,0 +1,696 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:resources.bzl", "gather_resources")
+load("@prelude//android:aapt2_link.bzl", "get_aapt2_link", "get_module_manifest_in_proto_format")
+load("@prelude//android:android_manifest.bzl", "generate_android_manifest")
+load(
+    "@prelude//android:android_providers.bzl",
+    "AndroidBinaryResourcesInfo",
+    "AndroidPackageableInfo",
+    "AndroidResourceInfo",
+    "ExopackageResourcesInfo",
+    "ManifestTSet",  # @unused Used as type
+)
+load("@prelude//android:android_resource.bzl", "aapt2_compile")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:r_dot_java.bzl", "generate_r_dot_javas")
+load("@prelude//android:voltron.bzl", "ROOT_MODULE", "get_apk_module_graph_info", "is_root_module")
+load("@prelude//decls:android_rules.bzl", "RType")
+load(
+    "@prelude//java:java_providers.bzl",
+    "JavaPackagingDep",  # @unused Used as type
+)
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "flatten")
+
+_FilteredResourcesOutput = record(
+    resource_infos = list[AndroidResourceInfo],
+    voltron_res = list[Artifact],
+    override_symbols = Artifact | None,
+    string_files_list = Artifact | None,
+    string_files_res_dirs = list[Artifact],
+)
+
+def get_android_binary_resources_info(
+    ctx: AnalysisContext,
+    deps: list[Dependency],
+    android_packageable_info: AndroidPackageableInfo,
+    java_packaging_deps: list[JavaPackagingDep],
+    use_proto_format: bool,
+    referenced_resources_lists: list[Artifact],
+    apk_module_graph_file: Artifact | None = None,
+    manifest_entries: dict = {},
+    resource_infos_to_exclude: set[TargetLabel] = set(),
+    r_dot_java_packages_to_exclude: set[str] = set(),
+    generate_strings_and_ids_separately: [bool, None] = True,
+    aapt2_preferred_density: [str, None] = None,
+) -> AndroidBinaryResourcesInfo:
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+
+    # Use reverse topological sort in resource merging to make sure a resource target will overwrite its dependencies.
+    unfiltered_resource_infos = reversed([
+        resource_info
+        for resource_info in list(
+            android_packageable_info.resource_infos.traverse(ordering = "topological") if android_packageable_info.resource_infos else []
+        )
+        if resource_info.raw_target not in resource_infos_to_exclude
+    ])
+    filtered_resources_output = _maybe_filter_resources(
+        ctx,
+        unfiltered_resource_infos,
+        android_toolchain,
+    )
+    resource_infos = filtered_resources_output.resource_infos
+
+    android_manifest = get_manifest(ctx, android_packageable_info.manifests, manifest_entries, should_replace_application_id_placeholders = True)
+
+    non_proto_format_aapt2_link_info, proto_format_aapt2_link_info = get_aapt2_link(
+        ctx,
+        ctx.attrs._android_toolchain[AndroidToolchainInfo],
+        resource_infos,
+        android_manifest,
+        manifest_entries = getattr(ctx.attrs, "manifest_entries", {}),
+        includes_vector_drawables = getattr(ctx.attrs, "includes_vector_drawables", False),
+        no_resource_removal = True,
+        package_id_offset = 0,
+        should_keep_raw_values = getattr(ctx.attrs, "aapt2_keep_raw_values", False),
+        resource_stable_ids = getattr(ctx.attrs, "resource_stable_ids", None),
+        compiled_resource_apks = getattr(ctx.attrs, "compiled_resource_apks", []),
+        additional_aapt2_params = getattr(ctx.attrs, "additional_aapt_params", []),
+        extra_filtered_resources = getattr(ctx.attrs, "extra_filtered_resources", []),
+        locales = getattr(ctx.attrs, "locales", []) or getattr(ctx.attrs, "locales_for_binary_resources", []),
+        filter_locales = getattr(ctx.attrs, "aapt2_locale_filtering", False) or bool(getattr(ctx.attrs, "locales_for_binary_resources", [])),
+        preferred_density = aapt2_preferred_density,
+    )
+
+    module_manifests = _get_module_manifests(
+        ctx,
+        manifest_entries,
+        apk_module_graph_file,
+        use_proto_format,
+        non_proto_format_aapt2_link_info.primary_resources_apk,
+    )
+
+    aapt2_link_info = proto_format_aapt2_link_info if use_proto_format else non_proto_format_aapt2_link_info
+
+    prebuilt_jars = [packaging_dep.jar for packaging_dep in java_packaging_deps if packaging_dep.is_prebuilt_jar]
+
+    cxx_resources = get_cxx_resources(ctx, deps)
+    is_exopackaged_enabled_for_resources = "resources" in getattr(ctx.attrs, "exopackage_modes", [])
+    primary_resources_apk, exopackaged_assets, exopackaged_assets_hash, module_assets_apks_dir = _merge_assets(
+        ctx,
+        is_exopackaged_enabled_for_resources,
+        aapt2_link_info.primary_resources_apk,
+        resource_infos,
+        cxx_resources,
+        use_proto_format,  # indicates that this is a .aab build
+        apk_module_graph_file,
+    )
+
+    if is_exopackaged_enabled_for_resources:
+        r_dot_txt = ctx.actions.declare_output("after_exo/R.txt", has_content_based_path = False)
+        primary_resources_apk = ctx.actions.declare_output("after_exo/primary_resources_apk.apk", has_content_based_path = False)
+        exo_resources = ctx.actions.declare_output("exo_resources.apk", has_content_based_path = False)
+        exo_resources_hash = ctx.actions.declare_output("exo_resources.apk.hash", has_content_based_path = False)
+        ctx.actions.run(
+            cmd_args([
+                android_toolchain.exo_resources_rewriter[RunInfo],
+                "--original-r-dot-txt",
+                aapt2_link_info.r_dot_txt,
+                "--new-r-dot-txt",
+                r_dot_txt.as_output(),
+                "--original-primary-apk-resources",
+                aapt2_link_info.primary_resources_apk,
+                "--new-primary-apk-resources",
+                primary_resources_apk.as_output(),
+                "--exo-resources",
+                exo_resources.as_output(),
+                "--exo-resources-hash",
+                exo_resources_hash.as_output(),
+            ]),
+            category = "write_exo_resources",
+            allow_cache_upload = True,
+        )
+
+        exopackage_info = ExopackageResourcesInfo(
+            assets = exopackaged_assets,
+            assets_hash = exopackaged_assets_hash,
+            res = exo_resources,
+            res_hash = exo_resources_hash,
+        )
+    else:
+        exopackage_info = None
+        r_dot_txt = aapt2_link_info.r_dot_txt
+
+    override_symbols_paths = [filtered_resources_output.override_symbols] if filtered_resources_output.override_symbols else []
+    resources = [resource for resource in resource_infos if resource.res != None]
+    r_dot_java_infos = generate_r_dot_javas(
+        ctx,
+        ctx.attrs._android_toolchain[AndroidToolchainInfo].merge_android_resources[RunInfo],
+        resources,
+        get_effective_banned_duplicate_resource_types(
+            getattr(ctx.attrs, "duplicate_resource_behavior", "allow_by_default"),
+            getattr(ctx.attrs, "allowed_duplicate_resource_types", []),
+            getattr(ctx.attrs, "banned_duplicate_resource_types", []),
+        ),
+        [r_dot_txt],
+        override_symbols_paths,
+        getattr(ctx.attrs, "duplicate_resource_whitelist", None),
+        referenced_resources_lists,
+        generate_strings_and_ids_separately = generate_strings_and_ids_separately,
+        remove_classes = ["{}.R".format(r_dot_java_package) for r_dot_java_package in r_dot_java_packages_to_exclude],
+    )
+    string_source_map = _maybe_generate_string_source_map(
+        ctx.actions,
+        getattr(ctx.attrs, "build_string_source_map", False),
+        [resource.res for resource in resources if resource.res != None],
+        android_toolchain,
+    )
+    voltron_string_source_map = _maybe_generate_string_source_map(
+        ctx.actions,
+        getattr(ctx.attrs, "is_voltron_language_pack_enabled", False),
+        filtered_resources_output.voltron_res,
+        android_toolchain,
+        is_voltron_string_source_map = True,
+    )
+
+    packaged_string_assets = _maybe_package_strings_as_assets(
+        ctx,
+        filtered_resources_output.string_files_list,
+        filtered_resources_output.string_files_res_dirs,
+        r_dot_txt,
+        android_toolchain,
+    )
+
+    return AndroidBinaryResourcesInfo(
+        exopackage_info = exopackage_info,
+        manifest = android_manifest,
+        module_manifests = module_manifests,
+        module_assets = module_assets_apks_dir,
+        packaged_string_assets = packaged_string_assets,
+        primary_resources_apk = primary_resources_apk,
+        proguard_config_file = aapt2_link_info.proguard_config_file,
+        r_dot_java_infos = r_dot_java_infos,
+        string_source_map = string_source_map,
+        voltron_string_source_map = voltron_string_source_map,
+        jar_files_that_may_contain_resources = prebuilt_jars,
+        unfiltered_resource_infos = unfiltered_resource_infos,
+    )
+
+def _maybe_filter_resources(ctx: AnalysisContext, resources: list[AndroidResourceInfo], android_toolchain: AndroidToolchainInfo) -> _FilteredResourcesOutput:
+    resources_filter_strings = getattr(ctx.attrs, "resource_filter", [])
+    resources_filter = _get_resources_filter(resources_filter_strings)
+    resource_compression_mode = getattr(ctx.attrs, "resource_compression", "disabled")
+    is_store_strings_as_assets = _is_store_strings_as_assets(resource_compression_mode)
+    locales = getattr(ctx.attrs, "locales", None)
+    use_aapt2_locale_filtering = getattr(ctx.attrs, "aapt2_locale_filtering", False)
+    needs_resource_filtering_for_locales = locales != None and len(locales) > 0 and not use_aapt2_locale_filtering
+    post_filter_resources_cmd = getattr(ctx.attrs, "post_filter_resources_cmd", None)
+
+    needs_resource_filtering = (
+        resources_filter != None or is_store_strings_as_assets or needs_resource_filtering_for_locales or post_filter_resources_cmd != None
+    )
+
+    if not needs_resource_filtering:
+        return _FilteredResourcesOutput(
+            resource_infos = resources,
+            voltron_res = [resource.res for resource in resources if resource.res != None],
+            override_symbols = None,
+            string_files_list = None,
+            string_files_res_dirs = [],
+        )
+
+    res_to_out_res_dir = {}
+    voltron_res_to_out_res_dir = {}
+    res_infos_with_no_res = []
+    skip_crunch_pngs = getattr(ctx.attrs, "skip_crunch_pngs", None) or False
+    is_voltron_language_pack_enabled = getattr(ctx.attrs, "is_voltron_language_pack_enabled", False)
+    for i, resource in enumerate(resources):
+        if resource.res == None:
+            res_infos_with_no_res.append(resource)
+        else:
+            filtered_res = ctx.actions.declare_output("filtered_res_{}".format(i), dir = True, has_content_based_path = True)
+            res_to_out_res_dir[resource.res] = filtered_res
+
+            if is_voltron_language_pack_enabled:
+                filtered_res_for_voltron = ctx.actions.declare_output("filtered_res_for_voltron_{}".format(i), dir = True, has_content_based_path = True)
+                voltron_res_to_out_res_dir[resource.res] = filtered_res_for_voltron
+
+    filter_resources_cmd = cmd_args(android_toolchain.filter_resources[RunInfo])
+    in_res_dirs = res_to_out_res_dir.keys()
+    filter_resources_cmd.add(
+        cmd_args(
+            hidden = in_res_dirs + [out_res.as_output() for out_res in res_to_out_res_dir.values()],
+        )
+    )
+    filter_resources_cmd.add([
+        "--in-res-dir-to-out-res-dir-map",
+        ctx.actions.write_json(
+            "in_res_dir_to_out_res_dir_map",
+            {"res_dir_map": {res: out_res.as_output() for (res, out_res) in res_to_out_res_dir.items()}},
+            has_content_based_path = False,
+        ),
+    ])
+
+    if is_voltron_language_pack_enabled:
+        filter_resources_cmd.add(cmd_args(hidden = [out_res.as_output() for out_res in voltron_res_to_out_res_dir.values()]))
+        filter_resources_cmd.add([
+            "--voltron-in-res-dir-to-out-res-dir-map",
+            ctx.actions.write_json(
+                "voltron_in_res_dir_to_out_res_dir_map",
+                {"res_dir_map": {voltron_res: out_res.as_output() for (voltron_res, out_res) in voltron_res_to_out_res_dir.items()}},
+                has_content_based_path = False,
+            ),
+        ])
+
+    if resources_filter:
+        filter_resources_cmd.add([
+            "--target-densities",
+            ",".join(resources_filter.densities),
+        ])
+
+    all_strings_files_list = None
+    all_strings_files_res_dirs = []
+    if is_store_strings_as_assets:
+        all_strings_files_list = ctx.actions.declare_output("all_strings_files", has_content_based_path = False)
+        all_strings_files_res_dirs = in_res_dirs
+        filter_resources_cmd.add([
+            "--enable-string-as-assets-filtering",
+            "--string-files-list-output",
+            all_strings_files_list.as_output(),
+        ])
+
+        packaged_locales = getattr(ctx.attrs, "packaged_locales", [])
+        if packaged_locales:
+            filter_resources_cmd.add([
+                "--packaged-locales",
+                ",".join(packaged_locales),
+            ])
+
+        not_filtered_string_dirs = [resource.res for resource in resources if not resource.allow_strings_as_assets_resource_filtering]
+        if not_filtered_string_dirs:
+            filter_resources_cmd.add([
+                "--not-filtered-string-dirs",
+                ctx.actions.write("not_filtered_string_dirs", not_filtered_string_dirs, has_content_based_path = False),
+            ])
+
+        allowlisted_locales = {resource.res: resource.allowlisted_locales for resource in resources if resource.allowlisted_locales}
+        filter_resources_cmd.add([
+            "--allowlisted-locales",
+            ctx.actions.write_json("allowlisted_locales", allowlisted_locales, has_content_based_path = False),
+        ])
+
+    if needs_resource_filtering_for_locales:
+        filter_resources_cmd.add([
+            "--locales",
+            ",".join(locales),
+        ])
+
+    override_symbols_artifact = None
+    if post_filter_resources_cmd != None:
+        override_symbols_artifact = ctx.actions.declare_output("post_filter_resources_cmd/R.json", has_content_based_path = False)
+        filter_resources_cmd.add([
+            "--post-filter-resources-cmd",
+            post_filter_resources_cmd,
+            "--post-filter-resources-cmd-override-symbols-output",
+            override_symbols_artifact.as_output(),
+        ])
+
+    ctx.actions.run(
+        filter_resources_cmd,
+        local_only = post_filter_resources_cmd != None and "run_post_filter_resources_cmd_locally" in ctx.attrs.labels,
+        category = "filter_resources",
+        allow_cache_upload = True,
+    )
+
+    filtered_resource_infos = []
+    for i, resource in enumerate(resources):
+        if resource.res == None:
+            continue
+
+        filtered_res = res_to_out_res_dir[resource.res]
+        filtered_aapt2_compile_output = aapt2_compile(
+            ctx,
+            filtered_res,
+            android_toolchain,
+            skip_crunch_pngs = skip_crunch_pngs,
+            identifier = "filtered_res_{}".format(i),
+        )
+        filtered_resource = AndroidResourceInfo(
+            raw_target = resource.raw_target,
+            aapt2_compile_output = filtered_aapt2_compile_output,
+            assets = resource.assets,
+            manifest_file = resource.manifest_file,
+            r_dot_java_package = resource.r_dot_java_package,
+            res = filtered_res,
+            text_symbols = resource.text_symbols,
+            unused_resource_dep_validation_has_non_xml_resources = resource.unused_resource_dep_validation_has_non_xml_resources,
+        )
+        filtered_resource_infos.append(filtered_resource)
+
+    return _FilteredResourcesOutput(
+        resource_infos = res_infos_with_no_res + filtered_resource_infos,
+        voltron_res = voltron_res_to_out_res_dir.values(),
+        override_symbols = override_symbols_artifact,
+        string_files_list = all_strings_files_list,
+        string_files_res_dirs = all_strings_files_res_dirs,
+    )
+
+ResourcesFilter = record(
+    densities = list[str],
+)
+
+def _get_resources_filter(resources_filter_strings: list[str]) -> [ResourcesFilter, None]:
+    if not resources_filter_strings:
+        return None
+
+    return ResourcesFilter(densities = resources_filter_strings)
+
+def _maybe_generate_string_source_map(
+    actions: AnalysisActions,
+    should_build_source_string_map: bool,
+    res_dirs: list[Artifact],
+    android_toolchain: AndroidToolchainInfo,
+    is_voltron_string_source_map: bool = False,
+) -> Artifact | None:
+    if not should_build_source_string_map or len(res_dirs) == 0:
+        return None
+
+    prefix = "voltron_" if is_voltron_string_source_map else ""
+    output = actions.declare_output("{}string_source_map".format(prefix), dir = True, has_content_based_path = False)
+    res_dirs_file = actions.write("resource_dirs_for_{}string_source_map".format(prefix), res_dirs, has_content_based_path = False)
+    generate_string_source_map_cmd = cmd_args(
+        [
+            android_toolchain.copy_string_resources[RunInfo],
+            "--res-dirs",
+            res_dirs_file,
+            "--output",
+            output.as_output(),
+        ],
+        hidden = res_dirs,
+    )
+
+    if is_voltron_string_source_map:
+        generate_string_source_map_cmd.add("--is-voltron")
+
+    actions.run(generate_string_source_map_cmd, category = "generate_{}string_source_map".format(prefix), allow_cache_upload = True)
+
+    return output
+
+def _maybe_package_strings_as_assets(
+    ctx: AnalysisContext,
+    string_files_list: Artifact | None,
+    string_files_res_dirs: list[Artifact],
+    r_dot_txt: Artifact,
+    android_toolchain: AndroidToolchainInfo,
+) -> Artifact | None:
+    resource_compression_mode = getattr(ctx.attrs, "resource_compression", "disabled")
+    is_store_strings_as_assets = _is_store_strings_as_assets(resource_compression_mode)
+    expect(is_store_strings_as_assets == (string_files_list != None))
+
+    if not is_store_strings_as_assets:
+        return None
+
+    string_assets_dir = ctx.actions.declare_output("package_strings_as_assets/string_assets", dir = True, has_content_based_path = False)
+    string_assets_zip = ctx.actions.declare_output("package_strings_as_assets/string_assets_zip.zip", has_content_based_path = False)
+    all_locales_string_assets_zip = ctx.actions.declare_output("package_strings_as_assets/all_locales_string_assets_zip.zip", has_content_based_path = False)
+
+    locales = getattr(ctx.attrs, "locales", [])
+
+    package_strings_as_assets_cmd = cmd_args(
+        [
+            android_toolchain.package_strings_as_assets[RunInfo],
+            "--string-files-list",
+            string_files_list,
+            "--r-dot-txt",
+            r_dot_txt,
+            "--string-assets-dir",
+            string_assets_dir.as_output(),
+            "--string-assets-zip",
+            string_assets_zip.as_output(),
+            "--all-locales-string-assets-zip",
+            all_locales_string_assets_zip.as_output(),
+        ],
+        hidden = string_files_res_dirs,
+    )
+
+    if locales:
+        package_strings_as_assets_cmd.add("--locales", ",".join(locales))
+
+    ctx.actions.run(package_strings_as_assets_cmd, category = "package_strings_as_assets", allow_cache_upload = True)
+
+    return string_assets_zip
+
+def get_manifest(
+    ctx: AnalysisContext, manifests: [ManifestTSet, list[Artifact], None], manifest_entries: dict, should_replace_application_id_placeholders: bool
+) -> Artifact:
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+    if ctx.attrs.manifest:
+        expect(getattr(ctx.attrs, "manifest_skeleton", None) == None, "Only one of manifest and manifest_skeleton should be declared")
+        if isinstance(ctx.attrs.manifest, Dependency):
+            android_manifest = ctx.attrs.manifest[DefaultInfo].default_outputs[0]
+        else:
+            android_manifest = ctx.attrs.manifest
+    else:
+        expect(ctx.attrs.manifest_skeleton != None, "Must declare one of manifest and manifest_skeleton")
+        if isinstance(ctx.attrs.manifest_skeleton, Dependency):
+            manifest_skeleton = ctx.attrs.manifest_skeleton[DefaultInfo].default_outputs[0]
+        else:
+            manifest_skeleton = ctx.attrs.manifest_skeleton
+
+        android_manifest, _ = generate_android_manifest(
+            ctx,
+            android_toolchain.generate_manifest[RunInfo],
+            manifest_skeleton,
+            ROOT_MODULE,
+            manifests,
+            manifest_entries.get("placeholders", {}),
+        )
+
+    if should_replace_application_id_placeholders:
+        android_manifest_with_replaced_application_id = ctx.actions.declare_output("replaced/AndroidManifest.xml", has_content_based_path = False)
+        replace_application_id_placeholders_cmd = cmd_args([
+            ctx.attrs._android_toolchain[AndroidToolchainInfo].replace_application_id_placeholders[RunInfo],
+            "--manifest",
+            android_manifest,
+            "--output",
+            android_manifest_with_replaced_application_id.as_output(),
+            "--sanity-check-placeholders",
+        ])
+
+        ctx.actions.run(replace_application_id_placeholders_cmd, category = "replace_application_id_placeholders", allow_cache_upload = True)
+        return android_manifest_with_replaced_application_id
+    else:
+        return android_manifest
+
+def _get_module_manifests(
+    ctx: AnalysisContext, manifest_entries: dict, apk_module_graph_file: Artifact | None, use_proto_format: bool, primary_resources_apk: Artifact
+) -> list[Artifact]:
+    if not apk_module_graph_file:
+        return []
+
+    default_module_manifest_skeleton = getattr(ctx.attrs, "default_module_manifest_skeleton", None)
+    if use_proto_format:
+        if not ctx.attrs.module_manifests:
+            fail("module_manifests required for a voltron enabled AAB build")
+        elif default_module_manifest_skeleton:
+            fail("default_module_manifest_skeleton cannot be provided for a voltron enabled AAB build")
+    elif not default_module_manifest_skeleton:
+        return []
+
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+
+    module_manifests_dir = ctx.actions.declare_output("module_manifests_dir", dir = True, has_content_based_path = False)
+
+    def get_manifests_modular(ctx: AnalysisContext, artifacts, outputs):
+        apk_module_graph_info = get_apk_module_graph_info(ctx, apk_module_graph_file, artifacts)
+
+        merged_module_manifests = {}
+        for module_name in apk_module_graph_info.module_list:
+            if is_root_module(module_name):
+                continue
+            if use_proto_format:
+                module_manifest = ctx.attrs.module_manifests[DefaultInfo].default_outputs[0]
+                if not module_manifest:
+                    fail("Module {} does not have a manifest".format(module_name))
+                module_manifest = module_manifest.project(module_name + "/AndroidManifest.xml")
+            else:
+                module_manifest = default_module_manifest_skeleton
+
+            merged_module_manifest, _ = generate_android_manifest(
+                ctx,
+                android_toolchain.generate_manifest[RunInfo],
+                module_manifest,
+                module_name,
+                # Note - the expectation of voltron modules is that the AndroidManifest entries are merged into the base APK's manifest.
+                None,
+                manifest_entries.get("placeholders", {}),
+            )
+
+            if use_proto_format:
+                merged_module_manifest = get_module_manifest_in_proto_format(
+                    ctx,
+                    android_toolchain,
+                    merged_module_manifest,
+                    primary_resources_apk,
+                    module_name,
+                )
+
+            merged_module_manifests["assets/{}/AndroidManifest.xml".format(module_name)] = merged_module_manifest
+
+        ctx.actions.symlinked_dir(outputs[module_manifests_dir], merged_module_manifests)
+
+    ctx.actions.dynamic_output(
+        dynamic = [apk_module_graph_file],
+        inputs = [],
+        outputs = [module_manifests_dir.as_output()],
+        f = get_manifests_modular,
+    )
+
+    return [module_manifests_dir]
+
+# Returns the "primary resources APK" (i.e. the resource that are packaged into the primary APK),
+# and optionally an "exopackaged assets APK" and the hash for that APK.
+def _merge_assets(
+    ctx: AnalysisContext,
+    is_exopackaged_enabled_for_resources: bool,
+    base_apk: Artifact,
+    resource_infos: list[AndroidResourceInfo],
+    cxx_resources: Artifact | None,
+    is_bundle_build: bool,
+    apk_module_graph_file: Artifact | None,
+) -> (Artifact, Artifact | None, Artifact | None, Artifact | None):
+    expect(
+        not (is_exopackaged_enabled_for_resources and is_bundle_build),
+        "Cannot use exopackage-for-resources with AAB builds.",
+    )
+    expect(
+        not (is_exopackaged_enabled_for_resources and apk_module_graph_file),
+        "Cannot use exopackage-for-resources with Voltron builds.",
+    )
+    asset_resource_infos = [resource_info for resource_info in resource_infos if resource_info.assets]
+    if not asset_resource_infos and not cxx_resources:
+        return base_apk, None, None, None
+
+    merged_assets_output = ctx.actions.declare_output("merged_assets.ap_", has_content_based_path = False)
+
+    def get_common_merge_assets_cmd(ctx: AnalysisContext, output_apk: Artifact) -> (cmd_args, Artifact | None):
+        merge_assets_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].merge_assets[RunInfo])
+        merge_assets_cmd.add(["--output-apk", output_apk.as_output()])
+
+        if getattr(ctx.attrs, "extra_no_compress_asset_extensions", None):
+            merge_assets_cmd.add("--extra-no-compress-asset-extensions")
+            merge_assets_cmd.add(ctx.attrs.extra_no_compress_asset_extensions)
+
+        if getattr(ctx.attrs, "extra_no_compress_asset_regex", None):
+            merge_assets_cmd.add("--extra_no_compress_asset_regex")
+            merge_assets_cmd.add(ctx.attrs.extra_no_compress_asset_regex)
+
+        if is_exopackaged_enabled_for_resources:
+            merged_assets_output_hash = ctx.actions.declare_output("merged_assets.ap_.hash", has_content_based_path = False)
+            merge_assets_cmd.add(["--output-apk-hash", merged_assets_output_hash.as_output()])
+        else:
+            merge_assets_cmd.add(["--base-apk", base_apk])
+            merged_assets_output_hash = None
+
+        merge_assets_cmd.add("--binary-type", "aab" if is_bundle_build else "apk")
+
+        return merge_assets_cmd, merged_assets_output_hash
+
+    if apk_module_graph_file:
+        declared_outputs = [merged_assets_output]
+        if is_bundle_build:
+            # For Voltron AAB builds, we need to put assets into a separate "APK" for each module.
+            module_assets_apks_dir = ctx.actions.declare_output("module_assets_apks", has_content_based_path = False)
+            declared_outputs.append(module_assets_apks_dir)
+        else:
+            module_assets_apks_dir = None
+
+        def merge_assets_modular(ctx: AnalysisContext, artifacts, outputs):
+            apk_module_graph_info = get_apk_module_graph_info(ctx, apk_module_graph_file, artifacts)
+
+            module_to_assets_dirs = {}
+            if cxx_resources != None:
+                module_to_assets_dirs.setdefault(ROOT_MODULE, []).extend([cxx_resources])
+            for asset_resource_info in asset_resource_infos:
+                module_name = apk_module_graph_info.target_to_module_mapping_function(str(asset_resource_info.raw_target))
+                module_to_assets_dirs.setdefault(module_name, []).extend(asset_resource_info.assets)
+
+            merge_assets_cmd, _ = get_common_merge_assets_cmd(ctx, outputs[merged_assets_output])
+
+            if is_bundle_build:
+                merge_assets_cmd.add(["--module-assets-apks-dir", outputs[module_assets_apks_dir].as_output()])
+
+            assets_dirs_file = ctx.actions.write_json("assets_dirs.json", module_to_assets_dirs, has_content_based_path = False)
+            merge_assets_cmd.add(["--assets-dirs", assets_dirs_file])
+            merge_assets_cmd.add(cmd_args(hidden = flatten(module_to_assets_dirs.values())))
+
+            ctx.actions.run(merge_assets_cmd, category = "merge_assets", allow_cache_upload = True)
+
+        ctx.actions.dynamic_output(
+            dynamic = [apk_module_graph_file],
+            inputs = [],
+            outputs = [o.as_output() for o in declared_outputs],
+            f = merge_assets_modular,
+        )
+
+        return merged_assets_output, None, None, module_assets_apks_dir
+
+    else:
+        merge_assets_cmd, merged_assets_output_hash = get_common_merge_assets_cmd(ctx, merged_assets_output)
+
+        assets_dirs = flatten([resource_info.assets for resource_info in asset_resource_infos])
+        if cxx_resources:
+            assets_dirs.extend([cxx_resources])
+        assets_dirs_file = ctx.actions.write_json("assets_dirs.json", {ROOT_MODULE: assets_dirs}, has_content_based_path = False)
+        merge_assets_cmd.add(["--assets-dirs", assets_dirs_file])
+        merge_assets_cmd.add(cmd_args(hidden = assets_dirs))
+
+        ctx.actions.run(merge_assets_cmd, category = "merge_assets", allow_cache_upload = True)
+
+        if is_exopackaged_enabled_for_resources:
+            return base_apk, merged_assets_output, merged_assets_output_hash, None
+        else:
+            return merged_assets_output, None, None, None
+
+def get_effective_banned_duplicate_resource_types(
+    duplicate_resource_behavior: str, allowed_duplicate_resource_types: list[str], banned_duplicate_resource_types: list[str]
+) -> list[str]:
+    if duplicate_resource_behavior == "allow_by_default":
+        expect(
+            len(allowed_duplicate_resource_types) == 0,
+            "Cannot set allowed_duplicate_resource_types if duplicate_resource_behaviour is allow_by_default",
+        )
+        return banned_duplicate_resource_types
+    elif duplicate_resource_behavior == "ban_by_default":
+        expect(
+            len(banned_duplicate_resource_types) == 0,
+            "Cannot set banned_duplicate_resource_types if duplicate_resource_behaviour is ban_by_default",
+        )
+        return [rtype for rtype in RType if rtype not in allowed_duplicate_resource_types]
+    else:
+        fail("Unrecognized duplicate_resource_behavior: {}".format(duplicate_resource_behavior))
+
+def get_cxx_resources(ctx: AnalysisContext, deps: list[Dependency], dir_name: str = "cxx_resources_dir") -> Artifact | None:
+    cxx_resources = gather_resources(
+        label = ctx.label,
+        resources = {},
+        deps = deps,
+    )
+
+    symlink_tree_dict = {}
+    resource_maps = cxx_resources.values()
+    for resource_map in resource_maps:
+        for name, resource in resource_map.items():
+            symlink_tree_dict["cxx-resources/{}".format(name)] = resource.default_output
+
+    return ctx.actions.symlinked_dir(dir_name, symlink_tree_dict, has_content_based_path = False) if symlink_tree_dict else None
+
+def _is_store_strings_as_assets(resource_compression: str) -> bool:
+    return resource_compression == "enabled_strings_only" or resource_compression == "enabled_with_strings_as_assets"
diff --git a/buck2/prelude/android/android_build_config.bzl b/buck2/prelude/android/android_build_config.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_build_config.bzl
@@ -0,0 +1,128 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//java:java_library.bzl", "compile_to_jar")
+load(
+    "@prelude//java:java_providers.bzl",
+    "JavaCompileOutputs",  # @unused Used as a type
+    "JavaLibraryInfo",
+    "JavaPackagingDepTSet",
+    "JavaPackagingInfo",
+    "create_java_packaging_dep",
+    "single_library_compiling_deps",
+)
+load(":android_providers.bzl", "AndroidBuildConfigInfo", "BuildConfigField", "merge_android_packageable_info")
+
+def android_build_config_impl(ctx: AnalysisContext) -> list[Provider]:
+    providers = []
+
+    default_build_config_fields = get_build_config_fields(ctx.attrs.values)
+    android_build_config_info = AndroidBuildConfigInfo(
+        package = ctx.attrs.package, build_config_fields = default_build_config_fields, values_file = ctx.attrs.values_file
+    )
+    providers.append(android_build_config_info)
+    providers.append(merge_android_packageable_info(ctx.label, ctx.actions, deps = [], build_config_info = android_build_config_info))
+
+    build_config_dot_java_library, java_packaging_info, build_config_dot_java = generate_android_build_config(
+        ctx,
+        ctx.attrs.name,
+        ctx.attrs.package,
+        False,
+        default_build_config_fields,
+        ctx.attrs.values_file,
+    )
+
+    providers.append(java_packaging_info)
+    providers.append(build_config_dot_java_library)
+
+    providers.append(
+        DefaultInfo(
+            default_output = build_config_dot_java_library.library_output.full_library,
+            sub_targets = {
+                "build_config_dot_java": [DefaultInfo(default_output = build_config_dot_java)],
+            },
+        ),
+    )
+    return providers
+
+def generate_android_build_config(
+    ctx: AnalysisContext, source: str, java_package: str, use_constant_expressions: bool, default_values: list[BuildConfigField], values_file: Artifact | None
+) -> (JavaLibraryInfo, JavaPackagingInfo, Artifact):
+    build_config_dot_java = _generate_build_config_dot_java(ctx, source, java_package, use_constant_expressions, default_values, values_file)
+
+    compiled_build_config_dot_java = _compile_and_package_build_config_dot_java(ctx, java_package, build_config_dot_java)
+    library_output = compiled_build_config_dot_java.classpath_entry
+
+    packaging_deps_kwargs = {"value": create_java_packaging_dep(ctx, library_output.full_library)}
+    packaging_deps = ctx.actions.tset(JavaPackagingDepTSet, **packaging_deps_kwargs)
+    return (
+        JavaLibraryInfo(
+            compiling_deps = single_library_compiling_deps(ctx.actions, library_output),
+            library_output = library_output,
+            output_for_classpath_macro = library_output.full_library,
+        ),
+        JavaPackagingInfo(
+            packaging_deps = packaging_deps,
+        ),
+        build_config_dot_java,
+    )
+
+def _generate_build_config_dot_java(
+    ctx: AnalysisContext, source: str, java_package: str, use_constant_expressions: bool, default_values: list[BuildConfigField], values_file: Artifact | None
+) -> Artifact:
+    generate_build_config_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].generate_build_config[RunInfo])
+    generate_build_config_cmd.add([
+        "--source",
+        source,
+        "--java-package",
+        java_package,
+        "--use-constant-expressions",
+        str(use_constant_expressions),
+    ])
+
+    default_values_file = ctx.actions.write(
+        _get_output_name(java_package, "default_values"),
+        ["{} {} = {}".format(x.type, x.name, x.value) for x in default_values],
+        has_content_based_path = True,
+    )
+    generate_build_config_cmd.add(["--default-values-file", default_values_file])
+    if values_file:
+        generate_build_config_cmd.add(["--values-file", values_file])
+
+    build_config_dot_java = ctx.actions.declare_output(
+        _get_output_name(java_package, "BuildConfig.java"),
+        has_content_based_path = True,
+    )
+    generate_build_config_cmd.add(["--output", build_config_dot_java.as_output()])
+
+    ctx.actions.run(
+        generate_build_config_cmd,
+        category = "android_generate_build_config",
+        identifier = java_package,
+    )
+
+    return build_config_dot_java
+
+def _compile_and_package_build_config_dot_java(ctx: AnalysisContext, java_package: str, build_config_dot_java: Artifact) -> JavaCompileOutputs:
+    return compile_to_jar(
+        ctx,
+        actions_identifier = "build_config_{}".format(java_package.replace(".", "_")),
+        srcs = [build_config_dot_java],
+    )
+
+def get_build_config_fields(lines: list[str]) -> list[BuildConfigField]:
+    return [_get_build_config_field(line) for line in lines]
+
+def _get_build_config_field(line: str) -> BuildConfigField:
+    type_and_name, value = [x.strip() for x in line.split("=", 1)]
+    field_type, name = type_and_name.split()
+    return BuildConfigField(type = field_type, name = name, value = value)
+
+def _get_output_name(java_package: str, output_filename: str) -> str:
+    return "android_build_config/{}/{}".format(java_package.replace(".", "_"), output_filename)
diff --git a/buck2/prelude/android/android_bundle.bzl b/buck2/prelude/android/android_bundle.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_bundle.bzl
@@ -0,0 +1,190 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")
+load("@prelude//android:android_apk.bzl", "get_install_info")
+load("@prelude//android:android_binary.bzl", "get_binary_info")
+load(
+    "@prelude//android:android_providers.bzl",
+    "AndroidAabInfo",
+    "AndroidBinaryNativeLibsInfo",
+    "AndroidBinaryPrimaryPlatformInfo",
+    "AndroidBinaryResourcesInfo",
+    "AndroidDerivedApkInfo",
+    "DexFilesInfo",
+    "KeystoreInfo",
+)
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:bundletool_util.bzl", "derive_universal_apk")
+load("@prelude//android:util.bzl", "package_validators_decorator")
+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")
+load("@prelude//target_stats:target_stats.bzl", "target_stats_aggregate_providers_and_subtargets")
+load("@prelude//utils:argfile.bzl", "argfile")
+
+def android_bundle_impl(ctx: AnalysisContext) -> list[Provider]:
+    android_binary_info = get_binary_info(ctx, use_proto_format = True)
+    native_library_info = android_binary_info.native_library_info
+
+    wrapped_build_bundle = package_validators_decorator(
+        ctx,
+        build_bundle,
+        extension = ".aab",
+    )
+
+    output_bundle = wrapped_build_bundle(
+        output_filename = ctx.label.name,
+        actions = ctx.actions,
+        android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo],
+        dex_files_info = android_binary_info.dex_files_info,
+        native_library_info = native_library_info,
+        resources_info = android_binary_info.resources_info,
+        bundle_config = ctx.attrs.bundle_config_file,
+        validation_deps_outputs = get_validation_deps_outputs(ctx),
+        packaging_options = ctx.attrs.packaging_options,
+    )
+
+    extra_providers = []
+    if android_binary_info.preprocessed_java_classes_info:
+        extra_providers.append(android_binary_info.preprocessed_java_classes_info)
+    sub_targets = {}
+    sub_targets.update(android_binary_info.sub_targets)
+    if ctx.attrs.use_derived_apk:
+        keystore = ctx.attrs.keystore[KeystoreInfo]
+        default_output = derive_universal_apk(
+            ctx,
+            android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo],
+            app_bundle = output_bundle,
+            keystore = keystore,
+        )
+        extra_providers.append(AndroidDerivedApkInfo(apk = default_output))
+        extra_providers.append(
+            get_install_info(
+                ctx,
+                exopackage_info = None,
+                manifest = android_binary_info.resources_info.manifest,
+                output_apk = default_output,
+            ),
+        )
+        sub_targets["aab"] = [
+            DefaultInfo(
+                default_outputs = [output_bundle],
+            )
+        ]
+    else:
+        default_output = output_bundle
+
+    target_stats_providers, target_stats_subtargets = target_stats_aggregate_providers_and_subtargets(
+        ctx,
+        deps = android_binary_info.deps_by_platform[android_binary_info.primary_platform],
+    )
+    sub_targets.update(target_stats_subtargets)
+
+    java_packaging_deps = android_binary_info.java_packaging_deps
+    return (
+        [
+            DefaultInfo(default_output = default_output, other_outputs = android_binary_info.materialized_artifacts, sub_targets = sub_targets),
+            AndroidAabInfo(
+                aab = output_bundle,
+                manifest = android_binary_info.resources_info.manifest,
+                materialized_artifacts = android_binary_info.materialized_artifacts,
+                unstripped_shared_libraries = native_library_info.unstripped_shared_libraries,
+            ),
+            AndroidBinaryPrimaryPlatformInfo(
+                primary_platform = android_binary_info.primary_platform,
+            ),
+            TemplatePlaceholderInfo(
+                keyed_variables = {
+                    "classpath": cmd_args([dep.jar for dep in java_packaging_deps if dep.jar], delimiter = get_path_separator_for_exec_os(ctx)),
+                    "classpath_including_targets_with_no_output": cmd_args(
+                        [dep.output_for_classpath_macro for dep in java_packaging_deps], delimiter = get_path_separator_for_exec_os(ctx)
+                    ),
+                },
+            ),
+        ]
+        + extra_providers
+        + target_stats_providers
+    )
+
+def build_bundle(
+    output_filename: str,
+    actions: AnalysisActions,
+    android_toolchain: AndroidToolchainInfo,
+    dex_files_info: DexFilesInfo,
+    native_library_info: AndroidBinaryNativeLibsInfo,
+    resources_info: AndroidBinaryResourcesInfo,
+    bundle_config: Artifact | None,
+    validation_deps_outputs: [list[Artifact], None] = None,
+    packaging_options: dict | None = None,
+) -> Artifact:
+    output_bundle = actions.declare_output("{}.aab".format(output_filename), has_content_based_path = False)
+
+    bundle_builder_args = cmd_args(
+        android_toolchain.bundle_builder[RunInfo],
+        "--output-bundle",
+        output_bundle.as_output(),
+        "--resource-apk",
+        resources_info.primary_resources_apk,
+        "--dex-file",
+        dex_files_info.primary_dex,
+        # The outputs of validation_deps need to be added as hidden arguments
+        # to an action for the validation_deps targets to be built and enforced.
+        hidden = validation_deps_outputs or [],
+    )
+
+    if bundle_config:
+        bundle_builder_args.add(["--path-to-bundle-config-file", bundle_config])
+
+    if android_toolchain.package_meta_inf_version_files:
+        bundle_builder_args.add("--package-meta-inf-version-files")
+
+    root_module_asset_directories = (
+        native_library_info.root_module_native_lib_assets + dex_files_info.root_module_bootstrap_dex_dirs + dex_files_info.root_module_secondary_dex_dirs
+    )
+    root_module_asset_directories_file = argfile(actions = actions, name = "root_module_asset_directories.txt", args = root_module_asset_directories)
+
+    non_root_module_asset_directories = resources_info.module_manifests + dex_files_info.non_root_module_secondary_dex_dirs
+    non_root_module_asset_directories_file = argfile(actions = actions, name = "non_root_module_asset_directories.txt", args = non_root_module_asset_directories)
+    non_root_module_asset_native_lib_directories = argfile(
+        actions = actions, name = "non_root_module_asset_native_lib_directories.txt", args = native_library_info.non_root_module_native_lib_assets
+    )
+
+    native_library_directories = argfile(actions = actions, name = "native_library_directories", args = native_library_info.native_libs_for_primary_apk)
+    all_zip_files = [resources_info.packaged_string_assets] if resources_info.packaged_string_assets else []
+    zip_files = argfile(actions = actions, name = "zip_files", args = all_zip_files)
+    jar_files_that_may_contain_resources = argfile(
+        actions = actions, name = "jar_files_that_may_contain_resources", args = resources_info.jar_files_that_may_contain_resources
+    )
+
+    if resources_info.module_assets:
+        bundle_builder_args.add(["--module-assets-dir", resources_info.module_assets])
+
+    bundle_builder_args.add([
+        "--root-module-asset-directories-list",
+        root_module_asset_directories_file,
+        "--non-root-module-asset-directories-list",
+        non_root_module_asset_directories_file,
+        "--non-root-module-asset-native-lib-directories-list",
+        non_root_module_asset_native_lib_directories,
+        "--native-libraries-directories-list",
+        native_library_directories,
+        "--zip-files-list",
+        zip_files,
+        "--jar-files-that-may-contain-resources-list",
+        jar_files_that_may_contain_resources,
+    ])
+
+    if packaging_options:
+        for key, value in packaging_options.items():
+            if key != "excluded_resources":
+                fail("Only 'excluded_resources' is supported in packaging_options right now!")
+            else:
+                bundle_builder_args.add("--excluded-resources", actions.write("excluded_resources.txt", value, has_content_based_path = False))
+
+    actions.run(bundle_builder_args, category = "bundle_build")
+
+    return output_bundle
diff --git a/buck2/prelude/android/android_cpu_transitioned_dep.bzl b/buck2/prelude/android/android_cpu_transitioned_dep.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_cpu_transitioned_dep.bzl
@@ -0,0 +1,30 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""A rule that applies the android_binary CPU transition to a dependency.
+
+This is useful for targets that need to be configured with the same CPU
+platform as an android_binary's deps, but are referenced from genrules
+that run in the binary's parent (arch-agnostic) configuration.
+"""
+
+load("@prelude//android:configuration.bzl", "CPU_TRANSITION_ATTRS", "cpu_transition")
+load("@prelude//decls:core_rules.bzl", "TargetCpuType")
+
+def _android_cpu_transitioned_dep_impl(ctx: AnalysisContext) -> list[Provider]:
+    return ctx.attrs.dep.providers
+
+android_cpu_transitioned_dep = rule(
+    impl = _android_cpu_transitioned_dep_impl,
+    attrs = {
+        "cpu_filters": attrs.list(attrs.enum(TargetCpuType), default = []),
+        "dep": attrs.transition_dep(cfg = cpu_transition),
+        "min_sdk_version": attrs.option(attrs.int(), default = None),
+    }
+    | CPU_TRANSITION_ATTRS,
+)
diff --git a/buck2/prelude/android/android_instrumentation_apk.bzl b/buck2/prelude/android/android_instrumentation_apk.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_instrumentation_apk.bzl
@@ -0,0 +1,193 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_apk.bzl", "build_apk")
+load("@prelude//android:android_binary_native_library_rules.bzl", "get_android_binary_native_library_info")
+load("@prelude//android:android_binary_resources_rules.bzl", "get_android_binary_resources_info")
+load("@prelude//android:android_providers.bzl", "AndroidApkInfo", "AndroidApkUnderTestInfo", "AndroidInstrumentationApkInfo", "merge_android_packageable_info")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:configuration.bzl", "get_deps_by_platform")
+load("@prelude//android:dex_rules.bzl", "get_multi_dex", "get_single_primary_dex", "get_split_dex_merge_config", "merge_to_single_dex", "merge_to_split_dex")
+load("@prelude//android:preprocess_java_classes.bzl", "get_preprocessed_java_classes")
+load("@prelude//android:util.bzl", "create_enhancement_context")
+load("@prelude//java:class_to_srcs.bzl", "merge_class_to_source_map_from_jar")
+load("@prelude//java:java_providers.bzl", "create_java_packaging_dep", "get_all_java_packaging_deps")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//java/utils:java_utils.bzl", "get_class_to_source_map_info")
+load("@prelude//target_stats:target_stats.bzl", "target_stats_aggregate_providers_and_subtargets")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "flatten")
+
+def android_instrumentation_apk_impl(ctx: AnalysisContext):
+    # jar preprocessing cannot be used when the jars were dexed already, so we have to disable predex when we want to preprocess the jars.
+    disable_pre_dex = ctx.attrs.disable_pre_dex or ctx.attrs.preprocess_java_classes_bash
+
+    apk_under_test_info = ctx.attrs.apk[AndroidApkUnderTestInfo]
+
+    expect(
+        ctx.attrs.min_sdk_version == apk_under_test_info.min_sdk_version,
+        """
+Android instrumentation APK must have the same min_sdk_version as the APK-under-test!
+This is important because the min_sdk_version affects the configuration of all deps.
+Instrumentation APK min_sdk_version: {}, APK-under-test min_sdk_version: {}""".format(
+            ctx.attrs.min_sdk_version,
+            apk_under_test_info.min_sdk_version,
+        ),
+    )
+
+    # android_instrumentation_apk uses the same platforms as the APK-under-test
+    unfiltered_deps_by_platform = get_deps_by_platform(ctx)
+    for platform in apk_under_test_info.platforms:
+        expect(
+            platform in unfiltered_deps_by_platform,
+            "Android instrumentation APK must have any platforms that are in the APK-under-test!",
+        )
+
+    test_apk_platform_configurations = set([str(x.label.configured_target().config()) for x in flatten(unfiltered_deps_by_platform.values())])
+    for platform_configuration in apk_under_test_info.platform_configurations:
+        expect(
+            platform_configuration in test_apk_platform_configurations,
+            """
+APK-under-test has deps that are configured in a different manner than the Android instrumentation APK!
+This will lead to overbuilding and is not supported. Configuration {} not found in {}""".format(platform_configuration, test_apk_platform_configurations),
+        )
+    filtered_deps_by_platform = {platform: deps for platform, deps in unfiltered_deps_by_platform.items() if platform in apk_under_test_info.platforms}
+
+    # We use the deps that don't have _build_only_native_code = True
+    deps = unfiltered_deps_by_platform.values()[0]
+
+    is_self_instrumenting = ctx.attrs.is_self_instrumenting
+
+    all_java_packaging_deps = [packaging_dep for packaging_dep in get_all_java_packaging_deps(ctx, deps) if packaging_dep.dex]
+    java_packaging_deps = [
+        packaging_dep
+        for packaging_dep in all_java_packaging_deps
+        if is_self_instrumenting or packaging_dep.label.raw_target() not in apk_under_test_info.java_packaging_deps
+    ]
+    desugar_classpath_jars = [
+        packaging_dep.jar
+        for packaging_dep in all_java_packaging_deps
+        if not is_self_instrumenting and packaging_dep.label.raw_target() in apk_under_test_info.java_packaging_deps
+    ]
+
+    android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, deps)
+
+    resources_info = get_android_binary_resources_info(
+        ctx,
+        deps,
+        android_packageable_info,
+        java_packaging_deps = java_packaging_deps,
+        use_proto_format = False,
+        referenced_resources_lists = [],
+        manifest_entries = apk_under_test_info.manifest_entries,
+        resource_infos_to_exclude = apk_under_test_info.resource_infos if not is_self_instrumenting else set(),
+        r_dot_java_packages_to_exclude = apk_under_test_info.r_dot_java_packages if not is_self_instrumenting else set(),
+    )
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+    java_packaging_deps += [
+        create_java_packaging_dep(
+            ctx,
+            r_dot_java.library_info.library_output.full_library,
+            dex_weight_factor = android_toolchain.r_dot_java_weight_factor,
+        )
+        for r_dot_java in resources_info.r_dot_java_infos
+    ]
+
+    enhance_ctx = create_enhancement_context(ctx)
+    sub_targets = enhance_ctx.get_sub_targets()
+    materialized_artifacts = []
+    preprocessed_java_classes_info = None
+    if not disable_pre_dex:
+        pre_dexed_libs = [java_packaging_dep.dex for java_packaging_dep in java_packaging_deps]
+        if ctx.attrs.use_split_dex:
+            dex_merge_config = get_split_dex_merge_config(ctx, android_toolchain)
+            dex_files_info = merge_to_split_dex(
+                ctx,
+                android_toolchain,
+                pre_dexed_libs,
+                dex_merge_config,
+                enable_bootstrap_dexes = ctx.attrs.enable_bootstrap_dexes,
+            )
+        else:
+            dex_files_info = merge_to_single_dex(ctx, android_toolchain, pre_dexed_libs)
+    else:
+        jars_to_owners = {packaging_dep.jar: packaging_dep.jar.owner.raw_target() for packaging_dep in java_packaging_deps}
+        if ctx.attrs.preprocess_java_classes_bash:
+            jars_to_owners, preprocessed_java_classes_info = get_preprocessed_java_classes(enhance_ctx, jars_to_owners)
+            if preprocessed_java_classes_info:
+                materialized_artifacts.append(preprocessed_java_classes_info.materialized_artifacts_dir)
+        if ctx.attrs.use_split_dex:
+            dex_files_info = get_multi_dex(
+                ctx,
+                ctx.attrs._android_toolchain[AndroidToolchainInfo],
+                jars_to_owners,
+                ctx.attrs.primary_dex_patterns,
+                enable_bootstrap_dexes = ctx.attrs.enable_bootstrap_dexes,
+                multidex_min_api = ctx.attrs.multidex_min_api,
+                classpath_jars = desugar_classpath_jars,
+            )
+        else:
+            dex_files_info = get_single_primary_dex(
+                ctx,
+                ctx.attrs._android_toolchain[AndroidToolchainInfo],
+                jars_to_owners.keys(),
+                classpath_jars = desugar_classpath_jars,
+            )
+    native_library_info = get_android_binary_native_library_info(
+        enhance_ctx,
+        android_packageable_info,
+        filtered_deps_by_platform,
+        prebuilt_native_library_dirs_to_exclude = apk_under_test_info.prebuilt_native_library_dirs if not is_self_instrumenting else set(),
+        shared_libraries_to_exclude = apk_under_test_info.shared_libraries if not is_self_instrumenting else set(),
+        native_library_merge_glue = apk_under_test_info.native_library_merge_glue,
+        native_library_merge_code_generator = apk_under_test_info.native_library_merge_code_generator,
+        native_library_merge_linker_args_all = apk_under_test_info.native_library_merge_linker_args_all,
+        native_library_merge_linker_args = apk_under_test_info.native_library_merge_linker_args,
+        native_library_merge_map = apk_under_test_info.native_library_merge_map,
+        native_library_merge_non_asset_libs = apk_under_test_info.native_library_merge_non_asset_libs,
+        native_library_merge_sequence = apk_under_test_info.native_library_merge_sequence,
+        native_library_merge_sequence_blocklist = apk_under_test_info.native_library_merge_sequence_blocklist,
+    )
+
+    output_apk = build_apk(
+        output_filename = ctx.label.name,
+        actions = ctx.actions,
+        android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo],
+        keystore = apk_under_test_info.keystore,
+        dex_files_info = dex_files_info,
+        native_library_info = native_library_info,
+        resources_info = resources_info,
+    )
+
+    class_to_srcs, _, class_to_srcs_subtargets = get_class_to_source_map_info(
+        ctx,
+        outputs = None,
+        deps = deps,
+    )
+    transitive_class_to_src_map = merge_class_to_source_map_from_jar(
+        actions = ctx.actions,
+        name = ctx.label.name + ".transitive_class_to_src.json",
+        java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo],
+        relative_to = None,
+        deps = [class_to_srcs],
+    )
+    sub_targets["transitive_class_to_src_map"] = [DefaultInfo(default_output = transitive_class_to_src_map)]
+
+    target_stats_providers, target_stats_subtargets = target_stats_aggregate_providers_and_subtargets(ctx, deps = deps)
+    sub_targets.update(target_stats_subtargets)
+
+    return (
+        [
+            AndroidApkInfo(apk = output_apk, materialized_artifacts = materialized_artifacts, manifest = resources_info.manifest),
+            AndroidInstrumentationApkInfo(apk_under_test = ctx.attrs.apk[AndroidApkInfo].apk, is_self_instrumenting = is_self_instrumenting),
+            DefaultInfo(default_output = output_apk, other_outputs = materialized_artifacts, sub_targets = sub_targets | class_to_srcs_subtargets),
+            class_to_srcs,
+        ]
+        + ([preprocessed_java_classes_info] if preprocessed_java_classes_info else [])
+        + target_stats_providers
+    )
diff --git a/buck2/prelude/android/android_instrumentation_test.bzl b/buck2/prelude/android/android_instrumentation_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_instrumentation_test.bzl
@@ -0,0 +1,360 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_providers.bzl", "AndroidApkExopackageInfo", "AndroidApkInfo", "AndroidInstrumentationApkInfo")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//java:class_to_srcs.bzl", "JavaClassToSourceMapInfo")
+load("@prelude//java:java_providers.bzl", "JavaPackagingInfo", "get_all_java_packaging_deps_tset")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "create_shlib_symlink_tree",
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+)
+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")
+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+load("@prelude//tests:test_listing.bzl", "TestListingInfo")
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load("@prelude//utils:expect.bzl", "expect")
+
+ANDROID_EMULATOR_ABI_LABEL_PREFIX = "tpx-re-config::"
+DEFAULT_ANDROID_SUBPLATFORM = "android-30"
+DEFAULT_ANDROID_PLATFORM = "android-emulator"
+DEFAULT_ANDROID_INSTRUMENTATION_TESTS_USE_CASE = "instrumentation-tests"
+RIOT_USE_CASES = [
+    "foundation-diff",
+    "horizon-experiences-diff",
+    "horizon-os-codemod-diff",
+    "horizon-os-diff",
+    "horizon-os-human-lease",
+    "horizon-os-other",
+    "vr-diff",
+    "wearables-diff",
+    "wearables-human-lease",
+    "wearables-other",
+]
+SUPPORTED_POOLS = ["EUREKA_POOL", "HOLLYWOOD_POOL", "STAGE_DELPHI_POOL", "PANTHER_POOL", "SEACLIFF_POOL"]
+SUPPORTED_PLATFORMS = ["riot", "android-emulator", "rl-emulator"]
+SUPPORTED_USE_CASES = RIOT_USE_CASES + [DEFAULT_ANDROID_INSTRUMENTATION_TESTS_USE_CASE]
+
+def android_instrumentation_test_impl(ctx: AnalysisContext):
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+
+    cmd = [ctx.attrs._java_test_toolchain[JavaToolchainInfo].java_for_tests]
+
+    classpath = android_toolchain.instrumentation_test_runner_classpath
+
+    classpath_args = cmd_args()
+    classpath_args.add("-classpath")
+    env = ctx.attrs.env or {}
+    extra_classpath = []
+    if ctx.attrs.instrumentation_test_listener != None:
+        extra_classpath.extend([
+            get_all_java_packaging_deps_tset(ctx, java_packaging_infos = [ctx.attrs.instrumentation_test_listener[JavaPackagingInfo]]).project_as_args(
+                "full_jar_args", ordering = "bfs"
+            ),
+        ])
+
+        shared_library_info = merge_shared_libraries(
+            ctx.actions,
+            deps = [ctx.attrs.instrumentation_test_listener[SharedLibraryInfo]],
+        )
+
+        cxx_library_symlink_tree = create_shlib_symlink_tree(
+            actions = ctx.actions,
+            out = "cxx_library_symlink_tree",
+            shared_libs = traverse_shared_library_info(shared_library_info, transformation_provider = None),
+        )
+
+        env["BUCK_LD_SYMLINK_TREE"] = cxx_library_symlink_tree
+    classpath_args.add(cmd_args(extra_classpath + classpath, delimiter = get_path_separator_for_exec_os(ctx)))
+    cmd.append(at_argfile(actions = ctx.actions, name = "classpath_args_file", args = classpath_args))
+
+    cmd.append(android_toolchain.instrumentation_test_runner_main_class)
+
+    apk_info = ctx.attrs.apk.get(AndroidApkInfo)
+    expect(apk_info != None, "Provided APK must have AndroidApkInfo!")
+
+    instrumentation_apk_info = ctx.attrs.apk.get(AndroidInstrumentationApkInfo)
+    # A self-instrumenting apk already bundles the app-under-test's contents, and its manifest's
+    # targetPackage is the self apk itself rather than the un-merged app-under-test apk's package,
+    # so there is no separate app-under-test to install.
+    if instrumentation_apk_info != None and not instrumentation_apk_info.is_self_instrumenting:
+        cmd.extend(["--apk-under-test-path", instrumentation_apk_info.apk_under_test])
+    if ctx.attrs.is_self_instrumenting:
+        cmd.extend(["--is-self-instrumenting"])
+    extra_instrumentation_args = ctx.attrs.extra_instrumentation_args
+    if extra_instrumentation_args:
+        for arg_name, arg_value in extra_instrumentation_args.items():
+            cmd.extend(
+                [
+                    "--extra-instrumentation-argument",
+                    cmd_args([arg_name, arg_value], delimiter = "="),
+                ],
+            )
+
+    target_package_file = ctx.actions.declare_output("target_package_file", has_content_based_path = False)
+    package_file = ctx.actions.declare_output("package_file", has_content_based_path = False)
+    test_runner_file = ctx.actions.declare_output("test_runner_file", has_content_based_path = False)
+    manifest_utils_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].manifest_utils[RunInfo])
+    manifest_utils_cmd.add([
+        "--manifest-path",
+        apk_info.manifest,
+        "--package-output",
+        package_file.as_output(),
+        "--target-package-output",
+        target_package_file.as_output(),
+        "--instrumentation-test-runner-output",
+        test_runner_file.as_output(),
+    ])
+    ctx.actions.run(manifest_utils_cmd, category = "get_manifest_info")
+    cmd.extend(
+        [
+            "--test-package-name",
+            cmd_args(package_file, format = "@{}"),
+            "--target-package-name",
+            cmd_args(target_package_file, format = "@{}"),
+            "--test-runner",
+            cmd_args(test_runner_file, format = "@{}"),
+        ],
+    )
+
+    if ctx.attrs.instrumentation_test_listener_class != None:
+        cmd.extend(["--extra-instrumentation-test-listener", ctx.attrs.instrumentation_test_listener_class])
+
+    if ctx.attrs.clear_package_data:
+        cmd.append("--clear-package-data")
+
+    if ctx.attrs.disable_animations:
+        cmd.append("--disable-animations")
+
+    if ctx.attrs.collect_tombstones:
+        cmd.append("--collect-tombstones")
+    if ctx.attrs.record_video:
+        cmd.append("--record-video")
+    if android_toolchain.collect_perfetto:
+        cmd.append("--collect-perfetto")
+    if ctx.attrs.log_extractors:
+        for arg_name, arg_value in ctx.attrs.log_extractors.items():
+            cmd.extend(
+                [
+                    "--log-extractor",
+                    cmd_args([arg_name, arg_value], delimiter = "="),
+                ],
+            )
+
+    cmd.extend(
+        [
+            "--adb-executable-path",
+            "required_but_unused",
+            "--instrumentation-apk-path",
+            apk_info.apk,
+        ],
+    )
+
+    # Exopackage secondary dexes live out-of-band, not in base.apk. Pass the build's secondary-dex
+    # dir so the runner pushes them to /data/local/tmp/exopackage/<pkg>/secondary-dex before
+    # Application init; otherwise classes in those dexes (e.g. com.facebook.R$style) hit NoClassDefFoundError on RE.
+    apk_exopackage_info = ctx.attrs.apk.get(AndroidApkExopackageInfo)
+    if apk_exopackage_info != None:
+        cmd.extend([
+            "--exopackage-secondary-dex-local-dir",
+            apk_exopackage_info.secondary_dex_directory,
+        ])
+
+    listing_info = ctx.attrs._android_toolchain[TestListingInfo]
+
+    list_tests = listing_info.list_tests
+    if list_tests != None and "tpx:supports_static_listing=true" in ctx.attrs.labels and "tpx:supports_static_listing=false" not in ctx.attrs.labels:
+        list_tests_command = cmd_args([
+            list_tests[RunInfo],
+            "list-tests",
+            "--sources-file",
+            ctx.actions.write("source_files.txt", ctx.attrs._test_srcs, with_inputs = True, has_content_based_path = False),
+        ])
+        env["TPX_LIST_TESTS_COMMAND"] = list_tests_command
+
+    labels = ctx.attrs.labels
+    if "tpx:supports-test-result-output-spec" not in labels:
+        labels.append("tpx:supports-test-result-output-spec")
+
+    test_info = ExternalRunnerTestInfo(
+        type = "android_instrumentation",
+        command = cmd,
+        env = env,
+        labels = labels,
+        contacts = ctx.attrs.contacts,
+        run_from_project_root = True,
+        use_project_relative_paths = True,
+        executor_overrides = _compute_executor_overrides(ctx, android_toolchain.instrumentation_test_can_run_locally),
+        local_resources = {
+            "android_emulator": None if ctx.attrs._android_emulators == None else ctx.attrs._android_emulators.label,
+        },
+        required_local_resources = [RequiredTestLocalResource("android_emulator", listing = True, execution = True)],
+    )
+
+    classmap_source_info = [ctx.attrs.apk[JavaClassToSourceMapInfo]] if JavaClassToSourceMapInfo in ctx.attrs.apk else []
+
+    test_info, run_info = inject_test_run_info(ctx, test_info)
+
+    target_stats_providers = []
+    target_stats_subtargets = {}
+    if TARGET_STATS_ENABLED:
+        target_stats_tools = android_toolchain.target_stats_tools
+        if target_stats_tools != None:
+            target_stats_deps = [ctx.attrs.apk]
+            if ctx.attrs.instrumentation_test_listener != None:
+                target_stats_deps.append(ctx.attrs.instrumentation_test_listener)
+            target_stats_providers, target_stats_subtargets = target_stats_providers_and_subtargets(
+                ctx,
+                tools = target_stats_tools,
+                srcs = {src.short_path: src for src in ctx.attrs._test_srcs},
+                deps = target_stats_deps,
+                cycle_mode = CycleMode("package"),
+                module_name = ctx.label.name,
+            )
+
+    # We append additional args so that "buck2 run" will work with sane defaults
+    run_info.args.add(cmd_args(["--auto-run-on-connected-device", "--output", ".", "--adb-executable-path", "adb"]))
+    return (
+        [
+            test_info,
+            run_info,
+            DefaultInfo(sub_targets = target_stats_subtargets),
+        ]
+        + classmap_source_info
+        + target_stats_providers
+    )
+
+def _compute_executor_overrides(ctx: AnalysisContext, instrumentation_test_can_run_locally: bool) -> dict[str, CommandExecutorConfig]:
+    remote_execution_properties = {
+        "platform": _compute_emulator_platform(ctx.attrs.labels or []),
+        "subplatform": _compute_emulator_subplatform(ctx.attrs.labels or []),
+    }
+
+    re_emulator_abi = _compute_emulator_abi(ctx.attrs.labels or [])
+    if re_emulator_abi != None:
+        remote_execution_properties["abi"] = re_emulator_abi
+
+    default_executor_override = CommandExecutorConfig(
+        local_enabled = instrumentation_test_can_run_locally,
+        remote_enabled = True,
+        remote_execution_properties = remote_execution_properties,
+        remote_execution_use_case = _compute_re_use_case(ctx.attrs.labels or []),
+    )
+    dynamic_listing_executor_override = default_executor_override
+    test_execution_executor_override = default_executor_override
+
+    if ctx.attrs.re_caps and ctx.attrs.re_use_case:
+        if "dynamic-listing" in ctx.attrs.re_caps and "dynamic-listing" in ctx.attrs.re_use_case:
+            _validate_executor_override_re_config(ctx.attrs.re_caps["dynamic-listing"], ctx.attrs.re_use_case["dynamic-listing"])
+            dynamic_listing_executor_override = CommandExecutorConfig(
+                local_enabled = instrumentation_test_can_run_locally,
+                remote_enabled = True,
+                remote_execution_properties = ctx.attrs.re_caps["dynamic-listing"],
+                remote_execution_use_case = ctx.attrs.re_use_case["dynamic-listing"],
+                meta_internal_extra_params = ctx.attrs.meta_internal_extra_params,
+            )
+        if "test-execution" in ctx.attrs.re_caps and "test-execution" in ctx.attrs.re_use_case:
+            _validate_executor_override_re_config(ctx.attrs.re_caps["test-execution"], ctx.attrs.re_use_case["test-execution"])
+            test_execution_executor_override = CommandExecutorConfig(
+                local_enabled = instrumentation_test_can_run_locally,
+                remote_enabled = True,
+                remote_execution_properties = ctx.attrs.re_caps["test-execution"],
+                remote_execution_use_case = ctx.attrs.re_use_case["test-execution"],
+                meta_internal_extra_params = ctx.attrs.meta_internal_extra_params,
+            )
+
+    return {
+        "android-emulator": default_executor_override,
+        "dynamic-listing": dynamic_listing_executor_override,
+        "static-listing": CommandExecutorConfig(
+            ## This was set to True as some point and it was causing listing to happen locally,
+            ## which is one of the contributing factors to S504068.
+            local_enabled = instrumentation_test_can_run_locally,
+            remote_enabled = True,
+            remote_execution_properties = {
+                "platform": "linux-remote-execution",
+            },
+            remote_execution_use_case = "buck2-default",
+        ),
+        "test-execution": test_execution_executor_override,
+    }
+
+def _compute_emulator_abi(labels: list[str]):
+    emulator_abi_labels = [label for label in labels if label.startswith(ANDROID_EMULATOR_ABI_LABEL_PREFIX)]
+    expect(
+        len(emulator_abi_labels) <= 1,
+        "multiple '{}' labels were found:[{}], there must be only one!".format(ANDROID_EMULATOR_ABI_LABEL_PREFIX, ", ".join(emulator_abi_labels)),
+    )
+    if len(emulator_abi_labels) == 0:
+        return None
+    else:  # len(emulator_abi_labels) == 1:
+        return emulator_abi_labels[0].replace(ANDROID_EMULATOR_ABI_LABEL_PREFIX, "")
+
+# replicating the logic in https://fburl.com/code/1fqowxu4 to match buck1's behavior
+def _compute_emulator_subplatform(labels: list[str]) -> str:
+    emulator_subplatform_labels = [label for label in labels if label.startswith("re_emulator_")]
+    expect(
+        len(emulator_subplatform_labels) <= 1,
+        "multiple 're_emulator_' labels were found:[{}], there must be only one!".format(", ".join(emulator_subplatform_labels)),
+    )
+    if len(emulator_subplatform_labels) == 0:
+        return DEFAULT_ANDROID_SUBPLATFORM
+    else:  # len(emulator_subplatform_labels) == 1:
+        return emulator_subplatform_labels[0].replace("re_emulator_", "")
+
+def _compute_emulator_platform(labels: list[str]) -> str:
+    emulator_platform_labels = [label for label in labels if label.startswith("re_platform_")]
+    expect(
+        len(emulator_platform_labels) <= 1,
+        "multiple 're_platform_' labels were found:[{}], there must be only one!".format(", ".join(emulator_platform_labels)),
+    )
+    if len(emulator_platform_labels) == 0:
+        subplatform = _compute_emulator_subplatform(labels)
+        if "aarch64" in subplatform:
+            return "android-emulator-aarch64"
+        if subplatform == "android-33-google-arm64":
+            return "android-emulator-mac"
+        return DEFAULT_ANDROID_PLATFORM
+    else:  # len(emulator_platform_labels) == 1:
+        return emulator_platform_labels[0].replace("re_platform_", "")
+
+def _compute_re_use_case(labels: list[str]) -> str:
+    re_use_case_labels = [label for label in labels if label.startswith("re_opts_use_case=")]
+    expect(len(re_use_case_labels) <= 1, "multiple 're_opts_use_case' labels were found:[{}], there must be only one!".format(", ".join(re_use_case_labels)))
+    if len(re_use_case_labels) == 0:
+        return DEFAULT_ANDROID_INSTRUMENTATION_TESTS_USE_CASE
+    else:  # len(re_use_case_labels) == 1:
+        return re_use_case_labels[0].replace("re_opts_use_case=", "")
+
+def _validate_executor_override_re_config(re_caps: dict[str, str], re_use_case: str):
+    expect(
+        re_use_case in SUPPORTED_USE_CASES,
+        "Unexpected {} use case found, value is expected to be on of the following: {}",
+        re_use_case,
+        ", ".join(SUPPORTED_USE_CASES),
+    )
+    if "pool" in re_caps:
+        expect(
+            re_caps["pool"] in SUPPORTED_POOLS,
+            "Unexpected {} pool found, value is expected to be on of the following: {}",
+            re_caps["pool"],
+            ", ".join(SUPPORTED_POOLS),
+        )
+    if "platform" in re_caps:
+        expect(
+            re_caps["platform"] in SUPPORTED_PLATFORMS,
+            "Unexpected {} platform found, value is expected to be on of the following: {}",
+            re_caps["platform"],
+            ", ".join(SUPPORTED_PLATFORMS),
+        )
diff --git a/buck2/prelude/android/android_library.bzl b/buck2/prelude/android/android_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_library.bzl
@@ -0,0 +1,223 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")
+load(
+    "@prelude//android:android_providers.bzl",
+    "AndroidLibraryIntellijInfo",
+    "AndroidResourceInfo",
+    "merge_android_packageable_info",
+    "merge_exported_android_resource_info",
+)
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:r_dot_java.bzl", "get_dummy_r_dot_java")
+load("@prelude//capabilities:capabilities_registration.bzl", "capabilities_registration_providers")
+load("@prelude//graphql:graphql.bzl", "graphql_providers")
+load("@prelude//java:java_library.bzl", "build_java_library")
+load(
+    "@prelude//java:java_providers.bzl",
+    "JavaLibraryInfo",
+    "JavaProviders",  # @unused Used as type
+    "create_native_providers",
+    "to_list",
+)
+load(
+    "@prelude//java/utils:java_utils.bzl",
+    "CustomJdkInfo",
+    "get_java_version_attributes",
+    "get_string_concat_inline_javac_args",
+)
+load("@prelude//kotlin:kotlin_library.bzl", "build_kotlin_library")
+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")
+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:label_provider.bzl", "LabelInfo")
+
+def get_custom_jdk_info(ctx: AnalysisContext) -> CustomJdkInfo:
+    bootclasspath_entries = [] + ctx.attrs._android_toolchain[AndroidToolchainInfo].android_bootclasspath + optional_jars(ctx)
+    bootclasspath_snapshots = [] + ctx.attrs._android_toolchain[AndroidToolchainInfo].android_bootclasspath_snapshots + optional_abi_jar_snapshots(ctx)
+
+    return CustomJdkInfo(
+        bootclasspath = bootclasspath_entries,
+        bootclasspath_jar_snapshots = bootclasspath_snapshots,
+        system_image = ctx.attrs._android_toolchain[AndroidToolchainInfo].jdk_system_image,
+    )
+
+def android_target_stats(ctx: AnalysisContext) -> (list[Provider], dict[str, list[Provider]]):
+    if not TARGET_STATS_ENABLED:
+        return [], {}
+    tools = ctx.attrs._android_toolchain[AndroidToolchainInfo].target_stats_tools
+    if tools == None:
+        return [], {}
+    return target_stats_providers_and_subtargets(
+        ctx,
+        tools = tools,
+        srcs = {src.short_path: src for src in ctx.attrs.srcs},
+        # Target stats cover the compile graph, including non-packaged provided deps.
+        deps = (ctx.attrs.deps + ctx.attrs.exported_deps + ctx.attrs.runtime_deps + ctx.attrs.provided_deps + ctx.attrs.exported_provided_deps),
+        cycle_mode = CycleMode("package"),
+        module_name = ctx.label.name,
+    )
+
+def android_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    packaging_deps = ctx.attrs.deps + ctx.attrs.exported_deps + ctx.attrs.runtime_deps
+    if ctx.attrs._build_only_native_code:
+        shared_library_info, cxx_resource_info, linkable_graph = create_native_providers(ctx, ctx.label, packaging_deps)
+        return [
+            merge_android_packageable_info(ctx.label, ctx.actions, packaging_deps),
+            shared_library_info,
+            cxx_resource_info,
+            linkable_graph,
+            # Add an unused default output in case this target is used as an attr.source() anywhere.
+            DefaultInfo(
+                default_output = ctx.actions.write("{}/unused.jar".format(ctx.label.name), [], has_content_based_path = False),
+                sub_targets = {
+                    "generated_sources": [
+                        DefaultInfo(default_output = ctx.actions.write("{}/generated_sources".format(ctx.label.name), [], has_content_based_path = False)),
+                    ],
+                },
+            ),
+            TemplatePlaceholderInfo(
+                keyed_variables = {
+                    "classpath": "unused_but_needed_for_analysis",
+                },
+            ),
+        ]
+
+    target_stats_providers, target_stats_subtargets = android_target_stats(ctx)
+
+    java_providers, android_library_intellij_info = build_android_library(
+        ctx = ctx,
+        validation_deps_outputs = get_validation_deps_outputs(ctx),
+        extra_sub_targets = target_stats_subtargets,
+    )
+    android_providers = [android_library_intellij_info] if android_library_intellij_info else []
+
+    return (
+        to_list(java_providers)
+        + [
+            merge_android_packageable_info(
+                ctx.label,
+                ctx.actions,
+                packaging_deps,
+                manifest = ctx.attrs.manifest,
+            ),
+            merge_exported_android_resource_info(ctx.attrs.exported_deps),
+        ]
+        + android_providers
+        + [LabelInfo(labels = ctx.attrs.labels)]
+        + graphql_providers(ctx)
+        + capabilities_registration_providers(ctx)
+        + target_stats_providers
+    )
+
+def optional_jars(ctx: AnalysisContext) -> list[Artifact]:
+    if not ctx.attrs.android_optional_jars:
+        return []
+
+    result = []
+    for dep in ctx.attrs.android_optional_jars:
+        java_library_info = dep.get(JavaLibraryInfo)
+        expect(
+            java_library_info != None and java_library_info.library_output != None,
+            "Only targets producing a Java bytecode output can be added as 'android_optional_jars'!",
+        )
+        result.append(java_library_info.library_output.full_library)
+
+    return result
+
+def optional_abi_jar_snapshots(ctx: AnalysisContext) -> list[Artifact]:
+    if not ctx.attrs.android_optional_jars:
+        return []
+
+    result = []
+    for dep in ctx.attrs.android_optional_jars:
+        java_library_info = dep.get(JavaLibraryInfo)
+        expect(
+            java_library_info != None and java_library_info.library_output != None,
+            "Only targets producing a Java bytecode output can be added as 'android_optional_jars'!",
+        )
+
+        if java_library_info.library_output.abi_jar_snapshot:
+            result.append(java_library_info.library_output.abi_jar_snapshot)
+
+    return result
+
+def build_android_library(
+    ctx: AnalysisContext,
+    r_dot_java: JavaLibraryInfo | None = None,
+    extra_sub_targets = {},
+    validation_deps_outputs: [list[Artifact], None] = None,
+) -> (JavaProviders, [AndroidLibraryIntellijInfo, None]):
+    custom_jdk_info = get_custom_jdk_info(ctx)
+    dummy_r_dot_java_info, android_library_intellij_info = _get_dummy_r_dot_java(ctx)
+    extra_sub_targets = dict(extra_sub_targets)
+
+    if r_dot_java:
+        additional_classpath_entries = r_dot_java.compiling_deps
+    elif dummy_r_dot_java_info:
+        additional_classpath_entries = dummy_r_dot_java_info.compiling_deps
+        extra_sub_targets["dummy_r_dot_java"] = [DefaultInfo(default_output = dummy_r_dot_java_info.library_output.full_library)]
+    else:
+        additional_classpath_entries = None
+
+    source_level, _ = get_java_version_attributes(ctx)
+    extra_arguments = get_string_concat_inline_javac_args(source_level)
+
+    if ctx.attrs.patches_system_module:
+        extra_arguments += [
+            "--patch-module",
+            "java.base=.",
+        ]
+
+    if ctx.attrs.language != None and ctx.attrs.language.lower() == "kotlin":
+        return build_kotlin_library(
+            ctx,
+            additional_classpath_entries = additional_classpath_entries,
+            custom_jdk_info = custom_jdk_info,
+            extra_sub_targets = extra_sub_targets,
+            validation_deps_outputs = validation_deps_outputs,
+            extra_arguments = extra_arguments,
+        ), android_library_intellij_info
+    else:
+        return build_java_library(
+            ctx,
+            ctx.attrs.srcs,
+            additional_classpath_entries = additional_classpath_entries,
+            custom_jdk_info = custom_jdk_info,
+            extra_sub_targets = extra_sub_targets,
+            validation_deps_outputs = validation_deps_outputs,
+            extra_arguments = extra_arguments,
+        ), android_library_intellij_info
+
+def _get_dummy_r_dot_java(ctx: AnalysisContext) -> (JavaLibraryInfo | None, [AndroidLibraryIntellijInfo, None]):
+    android_resources = dedupe([
+        resource
+        for resource in filter(
+            None,
+            [x.get(AndroidResourceInfo) for x in ctx.attrs.deps + ctx.attrs.provided_deps + (getattr(ctx.attrs, "provided_deps_query", []) or [])],
+        )
+        if resource.res != None
+    ])
+    if len(android_resources) == 0:
+        return (None, None)
+
+    dummy_r_dot_java_info = get_dummy_r_dot_java(
+        ctx,
+        ctx.attrs._android_toolchain[AndroidToolchainInfo].merge_android_resources[RunInfo],
+        android_resources,
+    )
+
+    dummy_r_dot_java = dummy_r_dot_java_info.library_output
+    return (
+        dummy_r_dot_java_info,
+        AndroidLibraryIntellijInfo(
+            dummy_r_dot_java = dummy_r_dot_java.abi,
+            android_resource_deps = android_resources,
+        ),
+    )
diff --git a/buck2/prelude/android/android_manifest.bzl b/buck2/prelude/android/android_manifest.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_manifest.bzl
@@ -0,0 +1,89 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//android:android_providers.bzl",
+    "AndroidManifestInfo",
+    "ManifestTSet",  # @unused Used as type
+    "merge_android_packageable_info",
+)
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:voltron.bzl", "ROOT_MODULE")
+load("@prelude//utils:argfile.bzl", "argfile")
+
+def android_manifest_impl(ctx: AnalysisContext) -> list[Provider]:
+    output, merge_report = generate_android_manifest(
+        ctx,
+        ctx.attrs._android_toolchain[AndroidToolchainInfo].generate_manifest[RunInfo],
+        ctx.attrs.skeleton,
+        ROOT_MODULE,
+        _get_manifests_from_deps(ctx),
+        {},
+    )
+
+    return [
+        AndroidManifestInfo(manifest = output, merge_report = merge_report),
+        DefaultInfo(default_output = output, other_outputs = [merge_report]),
+    ]
+
+def generate_android_manifest(
+    ctx: AnalysisContext,
+    generate_manifest: RunInfo,
+    manifest_skeleton: Artifact,
+    module_name: str,
+    manifests: [ManifestTSet, list[Artifact], None],
+    placeholder_entries: dict,
+) -> (Artifact, Artifact):
+    generate_manifest_cmd = cmd_args(generate_manifest)
+    generate_manifest_cmd.add([
+        "--skeleton-manifest",
+        manifest_skeleton,
+        "--module-name",
+        module_name,
+    ])
+
+    if not manifests:
+        manifests = []
+    elif isinstance(manifests, TransitiveSet):
+        # Manifests are usually resolved only at the binary level, so resolving
+        # projection nodes throughout the dependency graph is wasteful.
+        manifests = [entry.manifest for entry in manifests.traverse(ordering = "topological")]
+
+    library_manifest_paths_file = argfile(actions = ctx.actions, name = "{}/library_manifest_paths_file".format(module_name), args = manifests)
+
+    generate_manifest_cmd.add(["--library-manifests-list", library_manifest_paths_file])
+
+    placeholder_entries_args = cmd_args()
+    for key, val in placeholder_entries.items():
+        placeholder_entries_args.add(cmd_args(str(key), str(val), delimiter = " "))
+    placeholder_entries_file = ctx.actions.write("{}/placeholder_entries_file".format(module_name), placeholder_entries_args, has_content_based_path = False)
+
+    generate_manifest_cmd.add(["--placeholder-entries-list", placeholder_entries_file])
+
+    output = ctx.actions.declare_output("{}/AndroidManifest.xml".format(module_name), has_content_based_path = False)
+    merge_report = ctx.actions.declare_output("{}/merge-report.txt".format(module_name), has_content_based_path = False)
+    preprocess_log = ctx.actions.declare_output("{}/preprocess-log.txt".format(module_name), has_content_based_path = False)
+    generate_manifest_cmd.add([
+        "--output",
+        output.as_output(),
+        "--merge-report",
+        merge_report.as_output(),
+        "--preprocess-log",
+        preprocess_log.as_output(),
+    ])
+
+    ctx.actions.run(generate_manifest_cmd, category = "generate_manifest", identifier = module_name)
+
+    return (output, merge_report)
+
+def _get_manifests_from_deps(ctx: AnalysisContext) -> [ManifestTSet, None]:
+    if len(ctx.attrs.deps) == 0:
+        return None
+
+    android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, ctx.attrs.deps)
+    return android_packageable_info.manifests
diff --git a/buck2/prelude/android/android_prebuilt_aar.bzl b/buck2/prelude/android/android_prebuilt_aar.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_prebuilt_aar.bzl
@@ -0,0 +1,172 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//android:android_providers.bzl",
+    "AndroidResourceInfo",
+    "AndroidResourceRDotInfo",
+    "PrebuiltNativeLibraryDir",
+    "RESOURCE_PRIORITY_LOW",
+    "merge_android_packageable_info",
+)
+load("@prelude//android:android_resource.bzl", "aapt2_compile", "extract_package_from_manifest")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:r_dot_java.bzl", "get_dummy_r_dot_java")
+load(
+    "@prelude//java:java_providers.bzl",
+    "ClasspathSnapshotGranularity",
+    "JavaClasspathEntry",
+    "create_abi",
+    "create_java_library_providers",
+    "generate_java_classpath_snapshot",
+)
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+
+def android_prebuilt_aar_impl(ctx: AnalysisContext) -> list[Provider]:
+    manifest = ctx.actions.declare_output("AndroidManifest.xml", has_content_based_path = True)
+    all_classes_jar = ctx.actions.declare_output("classes.jar", has_content_based_path = True)
+    r_dot_txt = ctx.actions.declare_output("R.txt", has_content_based_path = True)
+    res = ctx.actions.declare_output("res", dir = True, has_content_based_path = True)
+    assets = ctx.actions.declare_output("assets", dir = True, has_content_based_path = True)
+    jni = ctx.actions.declare_output("jni", dir = True, has_content_based_path = True)
+    annotation_jars_dir = ctx.actions.declare_output("annotation_jars", dir = True, has_content_based_path = True)
+    proguard_config = ctx.actions.declare_output("proguard.txt", has_content_based_path = True)
+    lint_jar = ctx.actions.declare_output("lint.jar", has_content_based_path = True)
+
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+    unpack_aar_tool = android_toolchain.unpack_aar[RunInfo]
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    jar_builder_tool = cmd_args(java_toolchain.jar_builder, delimiter = " ")
+
+    unpack_aar_cmd = [
+        unpack_aar_tool,
+        "--aar",
+        ctx.attrs.aar,
+        "--manifest-path",
+        manifest.as_output(),
+        "--all-classes-jar-path",
+        all_classes_jar.as_output(),
+        "--r-dot-txt-path",
+        r_dot_txt.as_output(),
+        "--res-path",
+        res.as_output(),
+        "--assets-path",
+        assets.as_output(),
+        "--jni-path",
+        jni.as_output(),
+        "--annotation-jars-dir",
+        annotation_jars_dir.as_output(),
+        "--proguard-config-path",
+        proguard_config.as_output(),
+        "--jar-builder-tool",
+        jar_builder_tool,
+        "--lint-jar-path",
+        lint_jar.as_output(),
+    ]
+
+    ctx.actions.run(unpack_aar_cmd, category = "android_unpack_aar")
+
+    resource_info = AndroidResourceInfo(
+        raw_target = ctx.label.raw_target(),
+        aapt2_compile_output = aapt2_compile(ctx, res, android_toolchain),
+        allow_strings_as_assets_resource_filtering = True,
+        assets = [assets],
+        manifest_file = manifest,
+        r_dot_java_package = extract_package_from_manifest(ctx, manifest),
+        res = res,
+        res_priority = RESOURCE_PRIORITY_LOW,
+        text_symbols = r_dot_txt,
+        unused_resource_dep_validation_has_non_xml_resources = True,
+    )
+
+    dummy_r_dot_java_info = get_dummy_r_dot_java(
+        ctx,
+        android_toolchain.merge_android_resources[RunInfo],
+        [resource_info],
+    )
+
+    android_resource_r_dot_info = AndroidResourceRDotInfo(
+        dummy_r_dot_java = dummy_r_dot_java_info.library_output.abi,
+    )
+
+    abi = None if java_toolchain.is_bootstrap_toolchain else create_abi(ctx.actions, java_toolchain.class_abi_generator, all_classes_jar)
+    abi_jar_snapshot = generate_java_classpath_snapshot(
+        ctx.actions, java_toolchain.cp_snapshot_generator, ClasspathSnapshotGranularity("CLASS_LEVEL"), abi or all_classes_jar, ""
+    )
+
+    library_output_classpath_entry = JavaClasspathEntry(
+        full_library = all_classes_jar,
+        abi = abi or all_classes_jar,
+        abi_as_dir = None,
+        required_for_source_only_abi = ctx.attrs.required_for_source_only_abi,
+        abi_jar_snapshot = abi_jar_snapshot,
+    )
+
+    (
+        java_library_info,
+        java_packaging_info,
+        global_code_info,
+        shared_library_info,
+        linkable_graph,
+        cxx_resource_info,
+        template_placeholder_info,
+        java_library_intellij_info,
+    ) = create_java_library_providers(
+        ctx = ctx,
+        library_output = library_output_classpath_entry,
+        global_code_config = java_toolchain.global_code_config,
+        exported_deps = ctx.attrs.deps,
+        provided_deps = ctx.attrs.desugar_deps,
+        is_prebuilt_jar = True,
+        annotation_jars_dir = annotation_jars_dir,
+        proguard_config = proguard_config,
+        lint_jar = lint_jar,
+        sources_jar = ctx.attrs.source_jar,
+        dex_weight_factor = ctx.attrs.dex_weight_factor,
+    )
+
+    native_library = PrebuiltNativeLibraryDir(
+        raw_target = ctx.label.raw_target(),
+        dir = jni,
+        for_primary_apk = ctx.attrs.use_system_library_loader,
+        is_asset = False,
+    )
+
+    return [
+        java_library_info,
+        java_packaging_info,
+        global_code_info,
+        shared_library_info,
+        cxx_resource_info,
+        linkable_graph,
+        template_placeholder_info,
+        java_library_intellij_info,
+        android_resource_r_dot_info,
+        merge_android_packageable_info(
+            ctx.label,
+            ctx.actions,
+            ctx.attrs.deps,
+            manifest = manifest,
+            prebuilt_native_library_dir = native_library,
+            resource_info = resource_info,
+            for_primary_apk = ctx.attrs.for_primary_apk,
+        ),
+        resource_info,
+        DefaultInfo(
+            default_output = all_classes_jar,
+            other_outputs = [
+                manifest,
+                r_dot_txt,
+                res,
+                assets,
+                jni,
+                annotation_jars_dir,
+                proguard_config,
+            ],
+        ),
+    ]
diff --git a/buck2/prelude/android/android_providers.bzl b/buck2/prelude/android/android_providers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_providers.bzl
@@ -0,0 +1,401 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_providers.bzl", "JavaLibraryInfo")
+
+Aapt2LinkInfo = record(
+    # "APK" containing resources to be used by the Android binary
+    primary_resources_apk = Artifact,
+    # proguard config needed to retain used resources
+    proguard_config_file = Artifact,
+    # R.txt containing all the linked resources
+    r_dot_txt = Artifact,
+)
+
+PrebuiltNativeLibraryDir = record(
+    raw_target = TargetLabel,
+    dir = Artifact,  # contains subdirectories for different ABIs.
+    for_primary_apk = bool,
+    is_asset = bool,
+)
+
+ExopackageDexInfo = record(
+    metadata = Artifact,
+    directory = Artifact,
+)
+
+ExopackageNativeInfo = record(
+    metadata = Artifact,
+    directory = Artifact,
+)
+
+ExopackageResourcesInfo = record(
+    assets = Artifact | None,
+    assets_hash = Artifact | None,
+    res = Artifact,
+    res_hash = Artifact,
+)
+
+RDotJavaInfo = record(
+    identifier = str,
+    library_info = JavaLibraryInfo,
+    source_zipped = Artifact,
+)
+
+AndroidBinaryNativeLibsInfo = record(
+    prebuilt_native_library_dirs = list[PrebuiltNativeLibraryDir],
+    # Indicates which shared lib producing targets are included in the binary. Used by instrumentation tests
+    # to exclude those from the test apk.
+    shared_libraries = list[TargetLabel],
+    exopackage_info = [ExopackageNativeInfo, None],
+    root_module_native_lib_assets = list[Artifact],
+    non_root_module_native_lib_assets = list[Artifact],
+    native_libs_for_primary_apk = list[Artifact],
+    generated_java_code = list[Artifact],
+    unstripped_shared_libraries = [Artifact, None],
+    # Artifacts that must be produced for the binary to be valid. Threaded into
+    # the apk's validation_deps_outputs, so a failing check fails the build.
+    validation_outputs = list[Artifact],
+)
+
+AndroidBinaryResourcesInfo = record(
+    # Optional information about resources that should be exopackaged
+    exopackage_info = [ExopackageResourcesInfo, None],
+    # manifest to be used by the APK
+    manifest = Artifact,
+    # per-module manifests (packaged as assets)
+    module_manifests = list[Artifact],
+    # per-module assets APKs (for .aabs only)
+    module_assets = Artifact | None,
+    # zip containing any strings packaged as assets
+    packaged_string_assets = Artifact | None,
+    # "APK" containing resources to be used by the Android binary
+    primary_resources_apk = Artifact,
+    # proguard config needed to retain used resources
+    proguard_config_file = Artifact,
+    # R.java jars containing all the linked resources
+    r_dot_java_infos = list[RDotJavaInfo],
+    # directory containing filtered string resources files
+    string_source_map = Artifact | None,
+    # directory containing filtered string resources files for Voltron language packs
+    voltron_string_source_map = Artifact | None,
+    # list of jars that could contain resources that should be packaged into the APK
+    jar_files_that_may_contain_resources = list[Artifact],
+    # The resource infos that are used in this APK
+    unfiltered_resource_infos = list,  # list[AndroidResourceInfo]
+)
+
+# Information about an `android_build_config`
+BuildConfigField = record(
+    type = str,
+    name = str,
+    value = str,
+)
+
+AndroidBuildConfigInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "package": str,
+        "build_config_fields": list[BuildConfigField],
+        "values_file": provider_field(Artifact | None, default = None),
+    },
+)
+
+# Information about an `android_manifest`
+AndroidManifestInfo = provider(
+    fields = {
+        "manifest": provider_field(Artifact),
+        "merge_report": provider_field(Artifact),
+    },
+)
+
+AndroidApkInfo = provider(
+    fields = {
+        "apk": provider_field(Artifact),
+        "manifest": provider_field(Artifact),
+        "materialized_artifacts": provider_field(list[Artifact]),
+        "unstripped_shared_libraries": provider_field(Artifact | None, default = None),
+    },
+)
+
+AndroidPreprocessedJavaClassesInfo = provider(
+    fields = {
+        "input_dir": provider_field(Artifact),
+        "materialized_artifacts_dir": provider_field(Artifact),
+    },
+)
+
+# Exopackage secondary-dex dir (metadata.txt + secondary-N.dex.jar) so android_instrumentation_test
+# can push it to the device. Only set when the apk is built with exopackage secondary_dex mode.
+AndroidApkExopackageInfo = provider(
+    fields = {
+        "secondary_dex_directory": provider_field(Artifact),
+    },
+)
+
+AndroidAabInfo = provider(
+    fields = {
+        "aab": provider_field(Artifact),
+        "manifest": provider_field(Artifact),
+        "materialized_artifacts": provider_field(list[Artifact]),
+        "unstripped_shared_libraries": provider_field(Artifact | None, default = None),
+    },
+)
+
+AndroidDerivedApkInfo = provider(
+    fields = {
+        "apk": provider_field(Artifact),
+    },
+)
+
+AndroidBinaryPrimaryPlatformInfo = provider(
+    fields = {
+        "primary_platform": provider_field(typing.Any, default = None),  # str
+    },
+)
+
+AndroidApkUnderTestInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "java_packaging_deps": provider_field(typing.Any, default = None),  # set(TargetLabel)
+        "keystore": provider_field(typing.Any, default = None),  # "KeystoreInfo"
+        "manifest_entries": provider_field(typing.Any, default = None),  # dict
+        "min_sdk_version": provider_field(typing.Any, default = None),  # int
+        "platform_configurations": provider_field(typing.Any, default = None),  # [str]
+        "platforms": provider_field(typing.Any, default = None),  # [str]
+        "prebuilt_native_library_dirs": provider_field(typing.Any, default = None),  # set(TargetLabel)
+        "primary_platform": provider_field(typing.Any, default = None),  # str
+        "resource_infos": provider_field(typing.Any, default = None),  # set(TargetLabel)
+        "r_dot_java_packages": provider_field(typing.Any, default = None),  # set(str)
+        "shared_libraries": provider_field(typing.Any, default = None),  # set(TargetLabel)
+        # Merge map delegate
+        "native_library_merge_code_generator": provider_field(typing.Any, default = None),
+        "native_library_merge_glue": provider_field(typing.Any, default = None),
+        "native_library_merge_linker_args_all": provider_field(typing.Any, default = None),
+        "native_library_merge_map": provider_field(typing.Any, default = None),
+        "native_library_merge_non_asset_libs": provider_field(typing.Any, default = False),
+        "native_library_merge_linker_args": provider_field(typing.Any, default = None),
+        "native_library_merge_sequence": provider_field(typing.Any, default = None),
+        "native_library_merge_sequence_blocklist": provider_field(typing.Any, default = None),
+    },
+)
+
+AndroidInstrumentationApkInfo = provider(
+    fields = {
+        "apk_under_test": provider_field(typing.Any, default = None),  # "artifact"
+        "is_self_instrumenting": provider_field(bool, default = False),
+    },
+)
+
+KeystoreInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "store": provider_field(Artifact),
+        "properties": provider_field(Artifact),
+    },
+)
+
+ManifestInfo = record(
+    target_label = TargetLabel,
+    manifest = Artifact,
+)
+
+def _artifacts(value: ManifestInfo):
+    return value.manifest
+
+AndroidBuildConfigInfoTSet = transitive_set()
+AndroidDepsTSet = transitive_set()
+ManifestTSet = transitive_set(args_projections = {"artifacts": _artifacts})
+PrebuiltNativeLibraryDirTSet = transitive_set()
+ResourceInfoTSet = transitive_set()
+
+DepsInfo = record(
+    name = TargetLabel,
+    deps = list[TargetLabel],
+    for_primary_apk = bool,
+)
+
+AndroidPackageableInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "target_label": provider_field(typing.Any, default = None),  # "target_label"
+        "build_config_infos": provider_field(typing.Any, default = None),  # ["AndroidBuildConfigInfoTSet", None]
+        "deps": provider_field(typing.Any, default = None),  # ["AndroidDepsTSet", None]
+        "manifests": provider_field(typing.Any, default = None),  # ["ManifestTSet", None]
+        "prebuilt_native_library_dirs": provider_field(typing.Any, default = None),  # ["PrebuiltNativeLibraryDirTSet", None]
+        "resource_infos": provider_field(typing.Any, default = None),  # ["AndroidResourceInfoTSet", None]
+    },
+)
+
+RESOURCE_PRIORITY_NORMAL = "normal"
+RESOURCE_PRIORITY_LOW = "low"
+
+# Information about an `android_resource`
+AndroidResourceInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        # Target that produced this provider
+        "raw_target": provider_field(typing.Any, default = None),  # TargetLabel
+        # output of running `aapt2_compile` on the resources, if resources are present
+        "aapt2_compile_output": provider_field(Artifact | None, default = None),
+        # locales that should always be included in the APK for this resource
+        "allowlisted_locales": provider_field(typing.Any, default = []),  # List
+        #  if False, then the "res" are not affected by the strings-as-assets resource filter
+        "allow_strings_as_assets_resource_filtering": provider_field(typing.Any, default = None),  # bool
+        # assets defined by this rule. May be empty
+        "assets": provider_field(list[Artifact], default = []),
+        # manifest file used by the resources, if resources are present
+        "manifest_file": provider_field(Artifact | None, default = None),
+        # the package specified by the android_resource rule itself
+        "specified_r_dot_java_package": provider_field(typing.Any, default = None),  # str | None
+        # package used for R.java, if resources are present
+        "r_dot_java_package": provider_field(Artifact | None, default = None),
+        # resources defined by this rule. May be empty
+        "res": provider_field(Artifact | None, default = None),
+        # whether this resource contains non-XML resources
+        "unused_resource_dep_validation_has_non_xml_resources": provider_field(bool, default = False),
+        # priority of the resources, may be 'low' or 'normal'
+        "res_priority": provider_field(typing.Any, default = None),  # str
+        # symbols defined by the resources, if resources are present
+        "text_symbols": provider_field(Artifact | None, default = None),
+    },
+)
+
+# `AndroidResourceInfos` that are exposed via `exported_deps`
+ExportedAndroidResourceInfo = provider(
+    fields = {
+        "resource_infos": provider_field(typing.Any, default = None),  # ["AndroidResourceInfo"]
+    },
+)
+
+DexFilesInfo = record(
+    primary_dex = Artifact,
+    primary_dex_class_names = Artifact | None,
+    root_module_bootstrap_dex_dirs = list[Artifact],
+    root_module_secondary_dex_dirs = list[Artifact],
+    non_root_module_secondary_dex_dirs = list[Artifact],
+    secondary_dex_exopackage_info = [ExopackageDexInfo, None],
+    proguard_text_files_path = Artifact | None,
+)
+
+ExopackageInfo = record(
+    secondary_dex_info = [ExopackageDexInfo, None],
+    native_library_info = [ExopackageNativeInfo, None],
+    resources_info = [ExopackageResourcesInfo, None],
+)
+
+AndroidLibraryIntellijInfo = provider(
+    # @unsorted-dict-items
+    doc = "Information about android library that is required for Intellij project generation",
+    fields = {
+        "android_resource_deps": provider_field(typing.Any, default = None),  # ["AndroidResourceInfo"]
+        "dummy_r_dot_java": provider_field(Artifact | None, default = None),
+    },
+)
+
+AndroidResourceRDotInfo = provider(
+    # @unsorted-dict-items
+    doc = "Exposes the compiled R.jar for android_prebuilt_aar and android_resource targets",
+    fields = {
+        "dummy_r_dot_java": provider_field(Artifact | None, default = None),
+    },
+)
+
+def merge_android_packageable_info(
+    label: Label,
+    actions: AnalysisActions,
+    deps: list[Dependency],
+    build_config_info: [AndroidBuildConfigInfo, None] = None,
+    manifest: Artifact | None = None,
+    prebuilt_native_library_dir: [PrebuiltNativeLibraryDir, None] = None,
+    resource_info: [AndroidResourceInfo, None] = None,
+    for_primary_apk: bool = False,
+) -> AndroidPackageableInfo:
+    android_packageable_deps = filter(None, [x.get(AndroidPackageableInfo) for x in deps])
+
+    build_config_infos = _get_transitive_set(
+        actions,
+        filter(None, [dep.build_config_infos for dep in android_packageable_deps]),
+        build_config_info,
+        AndroidBuildConfigInfoTSet,
+    )
+
+    deps = _get_transitive_set(
+        actions,
+        filter(None, [dep.deps for dep in android_packageable_deps]),
+        DepsInfo(
+            name = label.raw_target(),
+            deps = [dep.target_label for dep in android_packageable_deps],
+            for_primary_apk = for_primary_apk,
+        ),
+        AndroidDepsTSet,
+    )
+
+    manifests = _get_transitive_set(
+        actions,
+        filter(None, [dep.manifests for dep in android_packageable_deps]),
+        ManifestInfo(
+            target_label = label.raw_target(),
+            manifest = manifest,
+        )
+        if manifest
+        else None,
+        ManifestTSet,
+    )
+
+    prebuilt_native_library_dirs = _get_transitive_set(
+        actions,
+        filter(None, [dep.prebuilt_native_library_dirs for dep in android_packageable_deps]),
+        prebuilt_native_library_dir,
+        PrebuiltNativeLibraryDirTSet,
+    )
+
+    resource_infos = _get_transitive_set(
+        actions,
+        filter(None, [dep.resource_infos for dep in android_packageable_deps]),
+        resource_info,
+        ResourceInfoTSet,
+    )
+
+    return AndroidPackageableInfo(
+        target_label = label.raw_target(),
+        build_config_infos = build_config_infos,
+        deps = deps,
+        manifests = manifests,
+        prebuilt_native_library_dirs = prebuilt_native_library_dirs,
+        resource_infos = resource_infos,
+    )
+
+def _get_transitive_set(
+    actions: AnalysisActions, children: list[TransitiveSet], node: typing.Any, transitive_set_definition: TransitiveSetDefinition
+) -> [TransitiveSet, None]:
+    kwargs = {}
+    if children:
+        kwargs["children"] = children
+    if node:
+        kwargs["value"] = node
+
+    return actions.tset(transitive_set_definition, **kwargs) if kwargs else None
+
+def merge_exported_android_resource_info(exported_deps: list[Dependency]) -> ExportedAndroidResourceInfo:
+    exported_android_resource_infos = []
+    for exported_dep in exported_deps:
+        exported_resource_info = exported_dep.get(ExportedAndroidResourceInfo)
+        if exported_resource_info:
+            exported_android_resource_infos += exported_resource_info.resource_infos
+
+        android_resource = exported_dep.get(AndroidResourceInfo)
+        if android_resource:
+            exported_android_resource_infos.append(android_resource)
+
+    return ExportedAndroidResourceInfo(resource_infos = dedupe(exported_android_resource_infos))
+
+def get_all_android_packageable_targets(deps: list[Dependency]) -> list[TargetLabel]:
+    android_packageable_infos = filter(None, [dep.get(AndroidPackageableInfo) for dep in deps])
+    android_deps_tsets = filter(None, [dep.deps for dep in android_packageable_infos])
+    return [deps_info.name for android_deps_tset in android_deps_tsets for deps_info in android_deps_tset.traverse()]
diff --git a/buck2/prelude/android/android_resource.bzl b/buck2/prelude/android/android_resource.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_resource.bzl
@@ -0,0 +1,199 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_providers.bzl", "derive_compiling_deps_wrapper", "get_global_code_info", "get_java_packaging_info")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//utils:argfile.bzl", "argfile")
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    ":android_providers.bzl",
+    "AndroidResourceInfo",
+    "AndroidResourceRDotInfo",
+    "ExportedAndroidResourceInfo",
+    "RESOURCE_PRIORITY_NORMAL",
+    "merge_android_packageable_info",
+)
+load(":android_toolchain.bzl", "AndroidToolchainInfo")
+load(":r_dot_java.bzl", "get_dummy_r_dot_java")
+
+JAVA_PACKAGE_FILENAME = "java_package.txt"
+
+def _convert_to_artifact_dir(ctx: AnalysisContext, attr: [Dependency, dict, Artifact, None], attr_name: str) -> Artifact | None:
+    if isinstance(attr, Dependency):
+        expect(len(attr[DefaultInfo].default_outputs) == 1, "Expect one default output from build dep of attr {}!".format(attr_name))
+        return attr[DefaultInfo].default_outputs[0]
+    elif type(attr) == "dict":
+        return None if len(attr) == 0 else ctx.actions.symlinked_dir(attr_name, attr, has_content_based_path = True)
+    else:
+        return attr
+
+def android_resource_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs._build_only_native_code:
+        return [DefaultInfo()]
+
+    sub_targets = {}
+    providers = []
+    default_output = None
+
+    res = _convert_to_artifact_dir(ctx, ctx.attrs.res, "res")
+    asset = _convert_to_artifact_dir(ctx, ctx.attrs.assets, "assets")
+    assets = [asset] if asset else []
+    unused_resource_dep_validation_has_non_xml_resources = ctx.attrs.unused_resource_dep_validation_has_non_xml_resources
+    if unused_resource_dep_validation_has_non_xml_resources == None:
+        unused_resource_dep_validation_has_non_xml_resources = ctx.attrs.res != None
+    unused_resource_dep_validation_has_non_xml_resources = unused_resource_dep_validation_has_non_xml_resources or bool(assets) or ctx.attrs.manifest != None
+
+    if res:
+        aapt2_compile_output = aapt2_compile(ctx, res, ctx.attrs._android_toolchain[AndroidToolchainInfo])
+
+        sub_targets["aapt2_compile"] = [DefaultInfo(default_output = aapt2_compile_output)]
+
+        r_dot_txt_output = get_text_symbols(ctx, res, ctx.attrs.deps)
+        default_output = r_dot_txt_output
+
+        r_dot_java_package = _get_package(ctx, ctx.attrs.package, ctx.attrs.manifest)
+        resource_info = AndroidResourceInfo(
+            raw_target = ctx.label.raw_target(),
+            aapt2_compile_output = aapt2_compile_output,
+            allowlisted_locales = ctx.attrs.allowlisted_locales,
+            allow_strings_as_assets_resource_filtering = not ctx.attrs.has_whitelisted_strings,
+            assets = assets,
+            manifest_file = ctx.attrs.manifest,
+            specified_r_dot_java_package = ctx.attrs.package,
+            r_dot_java_package = r_dot_java_package,
+            res = res,
+            res_priority = RESOURCE_PRIORITY_NORMAL,
+            text_symbols = r_dot_txt_output,
+            unused_resource_dep_validation_has_non_xml_resources = unused_resource_dep_validation_has_non_xml_resources,
+        )
+    else:
+        resource_info = AndroidResourceInfo(
+            raw_target = ctx.label.raw_target(),
+            aapt2_compile_output = None,
+            allowlisted_locales = ctx.attrs.allowlisted_locales,
+            allow_strings_as_assets_resource_filtering = not ctx.attrs.has_whitelisted_strings,
+            assets = assets,
+            manifest_file = ctx.attrs.manifest,
+            specified_r_dot_java_package = None,
+            r_dot_java_package = None,
+            res = None,
+            res_priority = RESOURCE_PRIORITY_NORMAL,
+            text_symbols = None,
+            unused_resource_dep_validation_has_non_xml_resources = unused_resource_dep_validation_has_non_xml_resources,
+        )
+    providers.append(resource_info)
+    providers.append(merge_android_packageable_info(ctx.label, ctx.actions, ctx.attrs.deps, manifest = ctx.attrs.manifest, resource_info = resource_info))
+    providers.append(get_java_packaging_info(ctx, ctx.attrs.deps))
+
+    # Generate R.jar for autodeps support if we have resources
+    if res and resource_info.text_symbols:
+        android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+        dummy_r_dot_java_info = get_dummy_r_dot_java(
+            ctx,
+            android_toolchain.merge_android_resources[RunInfo],
+            [resource_info],
+        )
+        android_resource_r_dot_info = AndroidResourceRDotInfo(
+            dummy_r_dot_java = dummy_r_dot_java_info.library_output.abi,
+        )
+        providers.append(android_resource_r_dot_info)
+
+    providers.append(DefaultInfo(default_output = default_output, sub_targets = sub_targets))
+    compiling_deps = derive_compiling_deps_wrapper(ctx.actions, None, ctx.attrs.deps)
+    providers.append(
+        get_global_code_info(
+            ctx,
+            ctx.attrs.deps,
+            ctx.attrs.deps,
+            None,
+            compiling_deps,
+            [compiling_deps] if compiling_deps else [],
+            ctx.attrs._java_toolchain[JavaToolchainInfo].global_code_config,
+        )
+    )
+
+    return providers
+
+def aapt2_compile(
+    ctx: AnalysisContext, resources_dir: Artifact, android_toolchain: AndroidToolchainInfo, skip_crunch_pngs: bool = False, identifier: [str, None] = None
+) -> Artifact:
+    aapt2_command = [cmd_args(android_toolchain.aapt2)]
+    aapt2_command.append("compile")
+    aapt2_command.append("--legacy")
+    if skip_crunch_pngs:
+        aapt2_command.append("--no-crunch")
+    aapt2_command.extend(["--dir", resources_dir])
+    aapt2_output = ctx.actions.declare_output(
+        "{}_resources.flata".format(identifier) if identifier else "resources.flata",
+        has_content_based_path = True,
+    )
+    aapt2_command.extend(["-o", aapt2_output.as_output()])
+
+    ctx.actions.run(cmd_args(aapt2_command), category = "aapt2_compile", identifier = identifier, allow_cache_upload = True)
+
+    return aapt2_output
+
+def _get_package(ctx: AnalysisContext, package: [str, None], manifest: Artifact | None) -> Artifact:
+    if package:
+        return ctx.actions.write(JAVA_PACKAGE_FILENAME, package, has_content_based_path = True)
+    else:
+        expect(manifest != None, "if package is not declared then a manifest must be")
+        return extract_package_from_manifest(ctx, manifest)
+
+def extract_package_from_manifest(ctx: AnalysisContext, manifest: Artifact) -> Artifact:
+    r_dot_java_package = ctx.actions.declare_output(JAVA_PACKAGE_FILENAME, has_content_based_path = True)
+    extract_package_cmd = cmd_args(
+        ctx.attrs._android_toolchain[AndroidToolchainInfo].manifest_utils[RunInfo],
+        "--manifest-path",
+        manifest,
+        "--package-output",
+        r_dot_java_package.as_output(),
+    )
+
+    ctx.actions.run(extract_package_cmd, category = "android_extract_package")
+
+    return r_dot_java_package
+
+def get_text_symbols(ctx: AnalysisContext, res: Artifact, deps: list[Dependency], identifier: [str, None] = None):
+    mini_aapt_cmd = cmd_args(ctx.attrs._android_toolchain[AndroidToolchainInfo].mini_aapt[RunInfo])
+
+    mini_aapt_cmd.add(["--resource-paths", res])
+
+    dep_symbols = _get_dep_symbols(deps)
+    dep_symbol_paths_file = argfile(
+        actions = ctx.actions,
+        name = "{}_dep_symbol_paths_file".format(identifier) if identifier else "dep_symbol_paths_file",
+        args = dep_symbols,
+        has_content_based_path = True,
+    )
+
+    mini_aapt_cmd.add(["--dep-symbol-paths", dep_symbol_paths_file])
+
+    text_symbols = ctx.actions.declare_output("{}_R.txt".format(identifier) if identifier else "R.txt", has_content_based_path = True)
+    mini_aapt_cmd.add(["--output-path", text_symbols.as_output()])
+
+    ctx.actions.run(mini_aapt_cmd, category = "mini_aapt", identifier = identifier)
+
+    return text_symbols
+
+def _get_dep_symbols(deps: list[Dependency]) -> list[Artifact]:
+    dep_symbols = []
+    for dep in deps:
+        android_resource_info = dep.get(AndroidResourceInfo)
+        exported_android_resource_info = dep.get(ExportedAndroidResourceInfo)
+        expect(
+            android_resource_info != None or exported_android_resource_info != None,
+            "Dependencies of `android_resource` rules should be `android_resource`s or `android_library`s ({})",
+            dep,
+        )
+        if android_resource_info and android_resource_info.text_symbols:
+            dep_symbols.append(android_resource_info.text_symbols)
+        if exported_android_resource_info:
+            dep_symbols += [resource_info.text_symbols for resource_info in exported_android_resource_info.resource_infos if resource_info.text_symbols]
+
+    return dedupe(dep_symbols)
diff --git a/buck2/prelude/android/android_toolchain.bzl b/buck2/prelude/android/android_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/android_toolchain.bzl
@@ -0,0 +1,83 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+AndroidPlatformInfo = provider(
+    fields = {
+        "name": provider_field(typing.Any, default = None),
+    }
+)
+
+AidlToolchainInfo = provider(
+    fields = {
+        "aidl": provider_field(typing.Any, default = None),
+        "framework_aidl_file": provider_field(typing.Any, default = None),
+    }
+)
+
+AndroidToolchainInfo = provider(
+    fields = {
+        "aapt2": provider_field(typing.Any, default = None),
+        "aapt2_filter_resources": provider_field(typing.Any, default = None),
+        "aar_builder": provider_field(typing.Any, default = None),
+        "adb": provider_field(typing.Any, default = None),
+        "android_bootclasspath": provider_field(typing.Any, default = None),
+        "android_bootclasspath_snapshots": provider_field(typing.Any, default = []),
+        "android_error_handler": provider_field(typing.Any, default = None),
+        "android_jar": provider_field(typing.Any, default = None),
+        "android_optional_jars": provider_field(typing.Any, default = None),
+        "apk_builder": provider_field(typing.Any, default = None),
+        "apk_module_graph": provider_field(typing.Any, default = None),
+        "app_without_resources_stub": provider_field(typing.Any, default = None),
+        "build_info_generator": provider_field(typing.Any, default = None),
+        "bundle_apks_builder": provider_field(typing.Any, default = None),
+        "bundle_builder": provider_field(typing.Any, default = None),
+        "collect_perfetto": provider_field(typing.Any, default = None),
+        "combine_native_library_dirs": provider_field(typing.Any, default = None),
+        "consolidate_class_names": provider_field(typing.Any, default = None),
+        "copy_string_resources": provider_field(typing.Any, default = None),
+        "cross_module_native_deps_check": provider_field(typing.Any, default = None),
+        "d8_command": provider_field(typing.Any, default = None),
+        "duplicate_class_checker": provider_field(typing.Any, default = None),
+        "exo_resources_rewriter": provider_field(typing.Any, default = None),
+        "filter_dex_class_names": provider_field(typing.Any, default = None),
+        "filter_prebuilt_native_library_dir": provider_field(typing.Any, default = None),
+        "filter_resources": provider_field(typing.Any, default = None),
+        # @oss-disable[end= ]: "gatorade_mergemap_tool": provider_field(typing.Any, default = None),
+        "generate_build_config": provider_field(typing.Any, default = None),
+        "generate_manifest": provider_field(typing.Any, default = None),
+        "installer": provider_field(typing.Any, default = None),
+        "instrumentation_test_can_run_locally": provider_field(typing.Any, default = None),
+        "instrumentation_test_runner_classpath": provider_field(typing.Any, default = None),
+        "instrumentation_test_runner_main_class": provider_field(typing.Any, default = None),
+        "jar_splitter_command": provider_field(typing.Any, default = None),
+        "jdk_system_image": provider_field(typing.Any, default = None),
+        "jni_onload_check": provider_field(typing.Any, default = None),
+        "manifest_utils": provider_field(typing.Any, default = None),
+        "merge_android_resource_sources": provider_field(typing.Any, default = None),
+        "merge_android_resources": provider_field(typing.Any, default = None),
+        "merge_assets": provider_field(typing.Any, default = None),
+        "mergemap_tool": provider_field(typing.Any, default = None),
+        "mini_aapt": provider_field(typing.Any, default = None),
+        "multi_dex_command": provider_field(typing.Any, default = None),
+        "native_libs_as_assets_metadata": provider_field(typing.Any, default = None),
+        "optimized_proguard_config": provider_field(typing.Any, default = None),
+        "p7zip": provider_field(typing.Any, default = None),
+        "package_meta_inf_version_files": provider_field(typing.Any, default = None),
+        "package_strings_as_assets": provider_field(typing.Any, default = None),
+        "proguard_config": provider_field(typing.Any, default = None),
+        "proguard_jar": provider_field(typing.Any, default = None),
+        "r_dot_java_weight_factor": provider_field(typing.Any, default = None),
+        "replace_application_id_placeholders": provider_field(typing.Any, default = None),
+        "secondary_dex_compression_command": provider_field(typing.Any, default = None),
+        "secondary_dex_weight_limit": provider_field(typing.Any, default = None),
+        "sort_pre_dexed_files": provider_field(typing.Any),
+        "target_stats_tools": provider_field(typing.Any, default = None),
+        "unpack_aar": provider_field(typing.Any, default = None),
+        "zipalign": provider_field(typing.Any, default = None),
+    },
+)
diff --git a/buck2/prelude/android/apk_genrule.bzl b/buck2/prelude/android/apk_genrule.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/apk_genrule.bzl
@@ -0,0 +1,251 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:genrule.bzl", "process_genrule")
+load("@prelude//android:android_apk.bzl", "get_install_info")
+load(
+    "@prelude//android:android_providers.bzl",
+    "AndroidAabInfo",
+    "AndroidApkInfo",
+    "AndroidApkUnderTestInfo",
+    "AndroidDerivedApkInfo",
+    "AndroidPreprocessedJavaClassesInfo",
+    "KeystoreInfo",
+)
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:bundletool_util.bzl", "derive_universal_apk")
+load("@prelude//android:native_build_commands.bzl", "GATORADE_PHASE_SUBTARGETS")
+load("@prelude//java:class_to_srcs.bzl", "JavaClassToSourceMapInfo")
+load("@prelude//utils:expect.bzl", "expect")
+
+# Native-library debug sub-targets forwarded through the apk_genrule wrapper only if present on the
+# wrapped android_apk/android_aab. These exist only in certain configurations (e.g. relinked_libs
+# and native_merge_debug require the relinker or native merging). Always-present sub-targets like
+# native_libs, linker_commands and native_build_commands are forwarded in the required set below.
+_OPTIONAL_NATIVE_LIB_SUBTARGETS = [
+    "gatorade_phase_evidence",
+    "native_merge_debug",
+    "relinked_libs",
+    "relinked_libs_manifest",
+    "relinker_extra_outputs",
+    "unrelinked_libs",
+]
+
+def _forward_optional_native_lib_subtargets(input_subtargets: dict) -> dict:
+    return {name: [input_subtargets[name][DefaultInfo]] for name in _OPTIONAL_NATIVE_LIB_SUBTARGETS if name in input_subtargets}
+
+# The top-level Gatorade-phase sub-targets (`TARGET[early_gatorade]` etc.) are always present on the
+# wrapped android_apk/android_aab, so forward them in the required set at every wrapper site.
+def _forward_gatorade_phase_subtargets(input_subtargets: dict) -> dict:
+    return {name: [input_subtargets[name][DefaultInfo]] for name in GATORADE_PHASE_SUBTARGETS}
+
+def apk_genrule_impl(ctx: AnalysisContext) -> list[Provider]:
+    expect((ctx.attrs.apk == None) != (ctx.attrs.aab == None), "Exactly one of 'apk' and 'aab' must be specified")
+
+    input_android_apk_under_test_info = None
+    input_android_apk_subtargets = None
+    input_android_apk_template_placeholder_info = None
+    input_android_aab_subtargets = None
+    input_preprocessed_java_classes_info = None
+    if ctx.attrs.apk != None:
+        # TODO(T104150125) The underlying APK should not have exopackage enabled
+        input_android_apk_info = ctx.attrs.apk[AndroidApkInfo]
+        expect(input_android_apk_info != None, "'apk' attribute must be an Android APK!")
+        input_apk = input_android_apk_info.apk
+        input_manifest = input_android_apk_info.manifest
+        input_materialized_artifacts = input_android_apk_info.materialized_artifacts
+        input_unstripped_shared_libraries = input_android_apk_info.unstripped_shared_libraries
+        input_android_apk_under_test_info = ctx.attrs.apk[AndroidApkUnderTestInfo]
+        input_android_apk_subtargets = ctx.attrs.apk[DefaultInfo].sub_targets
+        input_android_apk_template_placeholder_info = ctx.attrs.apk[TemplatePlaceholderInfo].keyed_variables
+        if AndroidPreprocessedJavaClassesInfo in ctx.attrs.apk:
+            input_preprocessed_java_classes_info = ctx.attrs.apk[AndroidPreprocessedJavaClassesInfo]
+
+        env_vars = {
+            "APK": cmd_args(input_apk),
+        }
+    else:
+        input_android_aab_info = ctx.attrs.aab[AndroidAabInfo]
+        expect(input_android_aab_info != None, "'aab' attribute must be an Android Bundle!")
+
+        # It's not an APK, but buck1 does this so we do it too for compatibility
+        input_apk = input_android_aab_info.aab
+        input_manifest = input_android_aab_info.manifest
+        input_materialized_artifacts = input_android_aab_info.materialized_artifacts
+        input_android_aab_subtargets = ctx.attrs.aab[DefaultInfo].sub_targets
+        input_unstripped_shared_libraries = input_android_aab_info.unstripped_shared_libraries
+        if AndroidPreprocessedJavaClassesInfo in ctx.attrs.aab:
+            input_preprocessed_java_classes_info = ctx.attrs.aab[AndroidPreprocessedJavaClassesInfo]
+
+        env_vars = {
+            "AAB": cmd_args(input_apk),
+        }
+
+    genrule_providers = process_genrule(
+        ctx,
+        ctx.attrs.out,
+        ctx.attrs.outs,
+        env_vars,
+        other_outputs = input_materialized_artifacts,
+        genrule_error_handler = ctx.attrs._android_toolchain[AndroidToolchainInfo].android_error_handler,
+    )
+
+    genrule_default_info = filter(lambda x: isinstance(x, DefaultInfo), genrule_providers)
+
+    expect(
+        len(genrule_default_info) == 1,
+        "Expecting a single DefaultInfo, but got {}",
+        genrule_default_info,
+    )
+
+    genrule_default_output = genrule_default_info[0].default_outputs[0]
+    genrule_default_output_is_aab = genrule_default_output.extension == ".aab"
+    genrule_default_output_is_apk = genrule_default_output.extension == ".apk"
+
+    expect(
+        genrule_default_output_is_aab or genrule_default_output_is_apk,
+        "apk_genrule must output a '.apk' or '.aab' file, but got {}",
+        genrule_default_info,
+    )
+
+    if ctx.attrs.aab:
+        if genrule_default_output_is_aab:
+            output_aab_info = AndroidAabInfo(
+                aab = genrule_default_output,
+                manifest = input_manifest,
+                materialized_artifacts = input_materialized_artifacts,
+                unstripped_shared_libraries = input_unstripped_shared_libraries,
+            )
+            output_apk = None
+        else:
+            output_aab_info = None
+            output_apk = genrule_default_output
+
+        if ctx.attrs.use_derived_apk:
+            expect(genrule_default_output_is_aab, "Default genrule output must end in '.aab' if use_derived_apk is True.")
+
+            output_apk = derive_universal_apk(
+                ctx = ctx,
+                android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo],
+                app_bundle = genrule_default_output,
+                keystore = ctx.attrs.keystore[KeystoreInfo] if ctx.attrs.keystore else None,
+            )
+            default_providers = [
+                DefaultInfo(
+                    default_output = output_apk,
+                    other_outputs = input_materialized_artifacts + genrule_default_info[0].other_outputs,
+                    sub_targets = {
+                        "aab": [
+                            DefaultInfo(
+                                default_outputs = [genrule_default_output],
+                            )
+                        ],
+                        "linker_argsfiles": [input_android_aab_subtargets["linker_argsfiles"][DefaultInfo]],
+                        "linker_commands": [input_android_aab_subtargets["linker_commands"][DefaultInfo]],
+                        "native_build_commands": [input_android_aab_subtargets["native_build_commands"][DefaultInfo]],
+                        "native_libs": [input_android_aab_subtargets["native_libs"][DefaultInfo]],
+                        "unstripped_native_libraries": [input_android_aab_subtargets["unstripped_native_libraries"][DefaultInfo]],
+                        "unstripped_native_libraries_files": [input_android_aab_subtargets["unstripped_native_libraries_files"][DefaultInfo]],
+                        "unstripped_native_libraries_json": [input_android_aab_subtargets["unstripped_native_libraries_json"][DefaultInfo]],
+                    }
+                    | _forward_gatorade_phase_subtargets(input_android_aab_subtargets)
+                    | _forward_optional_native_lib_subtargets(input_android_aab_subtargets),
+                ),
+                AndroidDerivedApkInfo(
+                    apk = output_apk,
+                ),
+            ] + filter(lambda x: not isinstance(x, DefaultInfo), genrule_providers)
+        else:
+            sub_targets = {k: [v[DefaultInfo]] for k, v in genrule_default_info[0].sub_targets.items()}
+            sub_targets.update(
+                {
+                    "linker_argsfiles": [input_android_aab_subtargets["linker_argsfiles"][DefaultInfo]],
+                    "linker_commands": [input_android_aab_subtargets["linker_commands"][DefaultInfo]],
+                    "native_build_commands": [input_android_aab_subtargets["native_build_commands"][DefaultInfo]],
+                    "native_libs": [input_android_aab_subtargets["native_libs"][DefaultInfo]],
+                    "unstripped_native_libraries": [input_android_aab_subtargets["unstripped_native_libraries"][DefaultInfo]],
+                    "unstripped_native_libraries_files": [input_android_aab_subtargets["unstripped_native_libraries_files"][DefaultInfo]],
+                    "unstripped_native_libraries_json": [input_android_aab_subtargets["unstripped_native_libraries_json"][DefaultInfo]],
+                }
+                | _forward_gatorade_phase_subtargets(input_android_aab_subtargets)
+                | _forward_optional_native_lib_subtargets(input_android_aab_subtargets)
+            )
+            default_providers = [
+                DefaultInfo(
+                    default_output = genrule_default_output,
+                    other_outputs = genrule_default_info[0].other_outputs,
+                    sub_targets = sub_targets,
+                ),
+            ] + filter(lambda x: not isinstance(x, DefaultInfo), genrule_providers)
+
+    else:
+        sub_targets = {k: [v[DefaultInfo]] for k, v in genrule_default_info[0].sub_targets.items()}
+        sub_targets.update(
+            {
+                "classpath": [input_android_apk_subtargets["classpath"][DefaultInfo]],
+                "classpath_targets": [input_android_apk_subtargets["classpath_targets"][DefaultInfo]],
+                "linker_argsfiles": [input_android_apk_subtargets["linker_argsfiles"][DefaultInfo]],
+                "linker_commands": [input_android_apk_subtargets["linker_commands"][DefaultInfo]],
+                "manifest": [input_android_apk_subtargets["manifest"][DefaultInfo]],
+                "native_build_commands": [input_android_apk_subtargets["native_build_commands"][DefaultInfo]],
+                "native_libs": [input_android_apk_subtargets["native_libs"][DefaultInfo]],
+                "unstripped_native_libraries": [input_android_apk_subtargets["unstripped_native_libraries"][DefaultInfo]],
+                "unstripped_native_libraries_files": [input_android_apk_subtargets["unstripped_native_libraries_files"][DefaultInfo]],
+                "unstripped_native_libraries_json": [input_android_apk_subtargets["unstripped_native_libraries_json"][DefaultInfo]],
+            }
+            | _forward_gatorade_phase_subtargets(input_android_apk_subtargets)
+            | _forward_optional_native_lib_subtargets(input_android_apk_subtargets)
+        )
+        expect(
+            len(filter(lambda x: isinstance(x, TemplatePlaceholderInfo), genrule_providers)) == 0,
+            "TemplatePlaceholderInfo from genrule_providers needs to be merged",
+        )
+        templace_placeholder_info = TemplatePlaceholderInfo(
+            keyed_variables = {
+                "classpath": input_android_apk_template_placeholder_info["classpath"],
+                "classpath_including_targets_with_no_output": input_android_apk_template_placeholder_info["classpath_including_targets_with_no_output"],
+            },
+        )
+        expect(genrule_default_output_is_apk, "apk_genrule output must end in '.apk'")
+        output_apk = genrule_default_output
+        output_aab_info = None
+        default_providers = [
+            DefaultInfo(
+                default_output = output_apk,
+                other_outputs = genrule_default_info[0].other_outputs,
+                sub_targets = sub_targets,
+            ),
+            templace_placeholder_info,
+        ] + filter(lambda x: not isinstance(x, DefaultInfo), genrule_providers)
+
+    class_to_src_map = [ctx.attrs.apk[JavaClassToSourceMapInfo]] if (ctx.attrs.apk and JavaClassToSourceMapInfo in ctx.attrs.apk) else []
+
+    if output_apk:
+        apk_providers = [
+            AndroidApkInfo(
+                apk = output_apk,
+                manifest = input_manifest,
+                materialized_artifacts = input_materialized_artifacts,
+                unstripped_shared_libraries = input_unstripped_shared_libraries,
+            ),
+            get_install_info(
+                ctx,
+                output_apk = output_apk,
+                manifest = input_manifest,
+                exopackage_info = None,
+            ),
+        ]
+    else:
+        apk_providers = []
+
+    aab_providers = filter(None, [output_aab_info])
+    apk_under_test_providers = filter(None, [input_android_apk_under_test_info])
+
+    preprocessed_java_classes_providers = filter(None, [input_preprocessed_java_classes_info])
+
+    return default_providers + apk_providers + aab_providers + apk_under_test_providers + preprocessed_java_classes_providers + class_to_src_map
diff --git a/buck2/prelude/android/build_only_native_code.bzl b/buck2/prelude/android/build_only_native_code.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/build_only_native_code.bzl
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def is_build_only_native_code():
+    return select(
+        {
+            "DEFAULT": False,
+            "prelude//android/constraints:maybe_build_only_native_code[build_only_native_code]": True,
+        },
+    )
diff --git a/buck2/prelude/android/bundletool_util.bzl b/buck2/prelude/android/bundletool_util.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/bundletool_util.bzl
@@ -0,0 +1,41 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_providers.bzl", "KeystoreInfo")  # @unused used as type
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+
+def derive_universal_apk(ctx: AnalysisContext, android_toolchain: AndroidToolchainInfo, app_bundle: Artifact, keystore: [KeystoreInfo, None]) -> Artifact:
+    output_apk = ctx.actions.declare_output("universal.apk", has_content_based_path = False)
+
+    bundle_apks_builder_args = cmd_args([
+        android_toolchain.bundle_apks_builder[RunInfo],
+        "--input-bundle",
+        app_bundle,
+        "--p7zip",
+        android_toolchain.p7zip,
+        "--aapt2",
+        android_toolchain.aapt2,
+        "--zipalign",
+        android_toolchain.zipalign[RunInfo],
+        "--output-apk",
+        output_apk.as_output(),
+    ])
+
+    if keystore:
+        bundle_apks_builder_args.add(
+            cmd_args([
+                "--keystore",
+                keystore.store,
+                "--keystore-properties",
+                keystore.properties,
+            ])
+        )
+
+    ctx.actions.run(bundle_apks_builder_args, category = "bundle_build", identifier = "build_universal_apk")
+
+    return output_apk
diff --git a/buck2/prelude/android/configuration.bzl b/buck2/prelude/android/configuration.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/configuration.bzl
@@ -0,0 +1,204 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:cpu_filters.bzl", "ALL_CPU_FILTERS", "CPU_FILTER_FOR_DEFAULT_PLATFORM", "CPU_FILTER_FOR_PRIMARY_PLATFORM")
+load("@prelude//android:min_sdk_version.bzl", "get_min_sdk_version_constraint_value_name", "get_min_sdk_version_range")
+load("@prelude//cfg/modifier:name.bzl", "cfg_name")
+load("@prelude//utils:expect.bzl", "expect")
+
+# Android binaries (APKs or AABs) can be built for one or more different platforms. buck2 supports
+# building Android binaries for arm32, arm64, x86, and x86_64. The platform(s) that we are building
+# for are specified by the `cpu_filters` attribute on the binary rule.
+
+# In order to build our native libraries for the correct platform(s), we do a (split) transition
+# (https://www.internalfb.com/intern/staticdocs/buck2/docs/rule_authors/configuration_transitions)
+# on the `deps` of the binary, and have each of the resulting configured sub-graphs be responsible
+# for building the native libraries for one of the specified platforms.
+
+# We always create an "arm64" configured sub-graph and use it to build the non-native libraries (so
+# that we get cache hits for the non-native libraries even if we're building for different
+# platforms). We only use the "arm64" native libraries if it is one of the specified platforms. We
+# "throw away" the non-native libraries for all other configured sub-graphs.
+
+_REFS = {
+    "arm64": "config//cpu/constraints:arm64",
+    "armv7": "config//cpu/constraints:arm32",
+    "build_only_native_code": "prelude//android/constraints:maybe_build_only_native_code[build_only_native_code]",
+    "building_android_binary": "prelude//os:building_android_binary",
+    "cpu": "config//cpu/constraints:cpu",
+    "maybe_build_only_native_code": "prelude//android/constraints:maybe_build_only_native_code",
+    "maybe_building_android_binary": "prelude//os:maybe_building_android_binary",
+    "min_sdk_version": "prelude//android/constraints:min_sdk_version",
+    "x86": "config//cpu/constraints:x86_32",
+    "x86_64": "config//cpu/constraints:x86_64",
+}
+
+_DEFAULT_PLATFORM = read_root_config("android", "primary_platform_for_build", None)
+if _DEFAULT_PLATFORM:
+    _REFS["default_platform"] = _DEFAULT_PLATFORM
+
+for min_sdk in get_min_sdk_version_range():
+    constraint_value_name = get_min_sdk_version_constraint_value_name(min_sdk)
+    _REFS[constraint_value_name] = "prelude//android/constraints:{}".format(constraint_value_name)
+
+def _cpu_split_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> dict[str, PlatformInfo]:
+    cpu_filters = attrs.cpu_filters or ALL_CPU_FILTERS
+    if attrs._is_force_single_cpu:
+        cpu_filters = [CPU_FILTER_FOR_PRIMARY_PLATFORM]
+    elif attrs._is_force_single_default_cpu:
+        cpu_filters = ["default"]
+
+    return _cpu_split_transition(
+        platform,
+        refs,
+        cpu_filters,
+        attrs.min_sdk_version,
+    )
+
+def _cpu_split_transition(platform: PlatformInfo, refs: struct, cpu_filters: list[str], min_sdk_version: [int, None]) -> dict[str, PlatformInfo]:
+    cpu = refs.cpu
+    x86 = refs.x86[ConstraintValueInfo]
+    x86_64 = refs.x86_64[ConstraintValueInfo]
+    armv7 = refs.armv7[ConstraintValueInfo]
+    arm64 = refs.arm64[ConstraintValueInfo]
+
+    if len(cpu_filters) == 1 and cpu_filters[0] == "default":
+        default_platform = getattr(refs, "default_platform", None)
+        expect(
+            default_platform != None,
+            "Cannot specify 'is_force_single_default_cpu' but not specify a default platform!",
+        )
+
+        default = default_platform[PlatformInfo]
+
+        # Use `cfg_name` function from modifier resolution so that we get the same cfg as default cfg
+        # of android libraries.
+        default = PlatformInfo(
+            label = cfg_name(default.configuration),
+            configuration = default.configuration,
+        )
+        return {CPU_FILTER_FOR_DEFAULT_PLATFORM: default}
+
+    expect(CPU_FILTER_FOR_PRIMARY_PLATFORM == "arm64")
+    cpu_name_to_cpu_constraint = {"arm64": arm64}
+    for cpu_filter in cpu_filters:
+        if cpu_filter == "x86":
+            cpu_name_to_cpu_constraint["x86"] = x86
+        elif cpu_filter == "armv7":
+            cpu_name_to_cpu_constraint["armv7"] = armv7
+        elif cpu_filter == "x86_64":
+            cpu_name_to_cpu_constraint["x86_64"] = x86_64
+        elif cpu_filter == "arm64":
+            # Always included as the primary platform
+            pass
+        else:
+            fail("Unexpected cpu_filter: {}".format(cpu_filter))
+
+    base_constraints = {
+        constraint_setting_label: constraint_setting_value
+        for (constraint_setting_label, constraint_setting_value) in platform.configuration.constraints.items()
+        if constraint_setting_label != cpu[ConstraintSettingInfo].label
+        and constraint_setting_label != refs.maybe_build_only_native_code[ConstraintSettingInfo].label
+    }
+
+    base_constraints[refs.maybe_building_android_binary[ConstraintSettingInfo].label] = refs.building_android_binary[ConstraintValueInfo]
+
+    if min_sdk_version:
+        base_constraints[refs.min_sdk_version[ConstraintSettingInfo].label] = _get_min_sdk_constraint_value(min_sdk_version, refs)
+
+    new_configs = {}
+    for platform_name, cpu_constraint in cpu_name_to_cpu_constraint.items():
+        updated_constraints = dict(base_constraints)
+        updated_constraints[refs.cpu[ConstraintSettingInfo].label] = cpu_constraint
+        if len(new_configs) > 0:
+            updated_constraints[refs.maybe_build_only_native_code[ConstraintSettingInfo].label] = refs.build_only_native_code[ConstraintValueInfo]
+
+        cfg_info = ConfigurationInfo(
+            constraints = updated_constraints,
+            values = platform.configuration.values,
+        )
+
+        # Use `cfg_name` function from modifier resolution so that we get the same cfg as default cfg
+        # of android libraries.
+        new_configs[platform_name] = PlatformInfo(
+            label = cfg_name(cfg_info),
+            configuration = cfg_info,
+        )
+
+    return new_configs
+
+def _cpu_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:
+    return _cpu_split_transition_impl(platform, refs, attrs).values()[0]
+
+cpu_split_transition = transition(
+    impl = _cpu_split_transition_impl,
+    refs = _REFS,
+    attrs = [
+        "cpu_filters",
+        "min_sdk_version",
+        "_is_force_single_cpu",
+        "_is_force_single_default_cpu",
+    ],
+    split = True,
+)
+
+# If our deps have been split-transitioned by CPU then we are already analyzing the dependency
+# graph using the resulting configurations. If there are any other attributes on the same target
+# that also need to analyze the dependency graph, then we want to use one of the configurations
+# from the split transition so that we don't end up analyzing the graph again using a different
+# configuration. This rule just picks the first configuration from the split-transition.
+#
+# This is used for the `manifest` attribute of `android_binary`.
+cpu_transition = transition(
+    impl = _cpu_transition_impl,
+    refs = _REFS,
+    attrs = [
+        "cpu_filters",
+        "min_sdk_version",
+        "_is_force_single_cpu",
+        "_is_force_single_default_cpu",
+    ],
+)
+
+FORCE_SINGLE_CPU = read_root_config("buck2", "android_force_single_cpu") in ("True", "true")
+FORCE_SINGLE_DEFAULT_CPU = read_root_config("buck2", "android_force_single_default_cpu") in ("True", "true")
+
+# Common attributes required by any rule that uses cpu_transition or cpu_split_transition.
+CPU_TRANSITION_ATTRS = {
+    "_is_force_single_cpu": attrs.default_only(attrs.bool(default = FORCE_SINGLE_CPU)),
+    "_is_force_single_default_cpu": attrs.default_only(attrs.bool(default = FORCE_SINGLE_DEFAULT_CPU)),
+}
+
+def get_deps_by_platform(ctx: AnalysisContext) -> dict[str, list[Dependency]]:
+    deps_by_platform = {}
+    for dep_dict in ctx.attrs.deps:
+        for platform, dep in dep_dict.items():
+            deps = deps_by_platform.get(platform, [])
+            deps.append(dep)
+            deps_by_platform[platform] = deps
+
+    return deps_by_platform
+
+def _get_min_sdk_constraint_value(min_sdk_version: int, refs: struct) -> ConstraintValueInfo:
+    constraint_name = get_min_sdk_version_constraint_value_name(min_sdk_version)
+    constraint = getattr(refs, constraint_name, None)
+    if not constraint:
+        fail("Unsupported min_sdk_version {}, please report!".format(min_sdk_version))
+
+    return constraint[ConstraintValueInfo]
+
+def _is_building_android_binary() -> Select:
+    return select(
+        {
+            "DEFAULT": False,
+            "prelude//os:building_android_binary": True,
+        },
+    )
+
+def is_building_android_binary_attr() -> Attr:
+    return attrs.default_only(attrs.bool(default = _is_building_android_binary()))
diff --git a/buck2/prelude/android/constraints/BUCK b/buck2/prelude/android/constraints/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/constraints/BUCK
@@ -0,0 +1,56 @@
+load("@prelude//android:min_sdk_version.bzl", "get_min_sdk_version_constraint_value_name", "get_min_sdk_version_range")
+load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native  # Avoid warnings and auto-formatters
+
+constraint_with_aliases(
+    name = "maybe_build_only_native_code",
+    aliases = {
+        "build_only_native_code": "build_only_native_code",
+    },
+    default = "unspecified",
+    values = [
+        "build_only_native_code",
+        "unspecified",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+constraint_with_aliases(
+    name = "maybe_merge_native_libraries",
+    aliases = {
+        "merge_native_libraries": "merge_native_libraries",
+    },
+    default = "unspecified",
+    values = [
+        "merge_native_libraries",
+        "unspecified",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+prelude.filegroup(
+    name = "files",
+    srcs = glob(
+        ["**"],
+    ),
+    visibility = ["PUBLIC"],
+)
+
+prelude.constraint_setting(
+    name = "min_sdk_version",
+    visibility = ["PUBLIC"],
+)
+
+[
+    prelude.constraint_value(
+        name = get_min_sdk_version_constraint_value_name(min_sdk),
+        constraint_setting = ":min_sdk_version",
+    )
+    for min_sdk in get_min_sdk_version_range()
+]
diff --git a/buck2/prelude/android/cpu_filters.bzl b/buck2/prelude/android/cpu_filters.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/cpu_filters.bzl
@@ -0,0 +1,25 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+CPU_FILTER_TO_ABI_DIRECTORY = {
+    "arm64": "arm64-v8a",
+    "armv7": "armeabi-v7a",
+    "x86": "x86",
+    "x86_64": "x86_64",
+}
+
+ALL_CPU_FILTERS = CPU_FILTER_TO_ABI_DIRECTORY.keys()
+
+CPU_FILTER_FOR_DEFAULT_PLATFORM = "arm64"
+
+# The "primary platform" is the one that we use for all
+# the non-native targets. We keep this consistent regardless
+# of which cpus the native libraries are built for so that
+# we get cache hits for the non-native targets across all
+# possible cpu filters.
+CPU_FILTER_FOR_PRIMARY_PLATFORM = "arm64"
diff --git a/buck2/prelude/android/dex_rules.bzl b/buck2/prelude/android/dex_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/dex_rules.bzl
@@ -0,0 +1,975 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//android:android_providers.bzl", "DexFilesInfo", "ExopackageDexInfo")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:voltron.bzl", "ROOT_MODULE", "get_apk_module_graph_info", "get_root_module_only_apk_module_graph_info", "is_root_module")
+load("@prelude//java:dex.bzl", "DexLibraryInfo", "get_dex_produced_from_java_library")
+load("@prelude//java:dex_toolchain.bzl", "DexToolchainInfo")
+load("@prelude//java:java_library.bzl", "compile_to_jar")
+load("@prelude//utils:argfile.bzl", "argfile", "at_argfile")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "flatten")
+
+# Android builds use a tool called `d8` to compile Java bytecode is DEX (Dalvik EXecutable)
+# bytecode that runs on Android devices. Our Android builds have two distinct ways of
+# doing that:
+# 1) With pre-dexing enabled (this is the most common case for debug builds). That means that
+#    d8 runs on every individual .jar file (to produce a .jar.dex file), and then at the APK
+#    level we run d8 again to combine all the individual .jar.dex files.
+# 2) With pre-dexing disabled (this is the case if it is explicitly disabled, we are running
+#    proguard, or we preprocess the java classes at the APK level). This means that we run
+#    d8 at the APK level on all the .jar files.
+#
+# The .dex files that we package into the APK consist of a single classes.dex "primary DEX"
+# file, and N secondary DEX files. The classes that are put into the primary DEX are those
+# that are required at startup, and are specified via `primary_dex_patterns` (classes which
+# match one of those patterns are put into the primary DEX).
+#
+# The primary DEX is always stored in the root directory of the APK as `classes.dex`.
+#
+# We have 4 different ways of storing our secondary DEX files, which are specified via the
+# `dex_compression` attribute:
+# 1) `raw` compression. This means that we create `classes2.dex`, `classes3.dex`, ...,
+#    `classesN.dex` and store each of them in the root directory of the APK.
+# 2) `raw_subdir` compression. We store each secondary DEX file uncompressed at
+#    `assets/secondary-program-dex-jars/secondary-I.dex`. This is like `raw` in
+#    the sense that secondary DEX files are included in the APK without
+#    additional compression. However, those raw DEXes are written to the
+#    secondary dex subdirectory instead of to the root directory of the APK.
+# 3) `jar` compression. For each secondary DEX file, we put a `classes.dex` entry into a
+#    JAR file, and store it as an asset at `assets/secondary-program-dex-jars/secondary-I.dex.jar`
+# 4) `xzs` compression. We do the same as `jar` compression, then concatenate all the jars
+#    together and do `xz` compression on the result to produce a single
+#    `assets/secondary-program-dex-jars/secondary.dex.jar.xzs`.
+#
+# For all compression types, we also package a `assets/secondary-program-dex-jars/metadata.txt`,
+# which has an entry for each secondary DEX file:
+# <secondary DEX file name> <sha1 hash of secondary DEX> <canary class name>
+#
+# A "canary class" is a Java class that we add to every secondary DEX. It is a known class that
+# can be used for DEX verification when loading the DEX on a device.
+#
+# For compression types other than raw, we also include a metadata file per secondary DEX, which
+# consists of a single line of the form:
+# jar:<size of secondary dex jar (in bytes)> dex:<size of uncompressed dex file (in bytes)>
+#
+# If an APK has Voltron modules, then we produce a separate group of secondary DEX files for each
+# module, and we put them into `assets/<module_name>` instead of `assets/secondary-program-dex-jars`.
+# We produce a `metadata.txt` file for each Voltron module.
+
+_DEX_MERGE_OPTIONS = ["--no-desugar", "--no-optimize"]
+
+SplitDexMergeConfig = record(
+    dex_compression = str,
+    primary_dex_patterns = list[str],
+    secondary_dex_weight_limit_bytes = int,
+)
+
+def _get_dex_compression(ctx: AnalysisContext) -> str:
+    is_exopackage_enabled_for_secondary_dexes = _is_exopackage_enabled_for_secondary_dex(ctx)
+    default_dex_compression = "jar" if is_exopackage_enabled_for_secondary_dexes else "raw"
+    dex_compression = getattr(ctx.attrs, "dex_compression", None) or default_dex_compression
+    expect(
+        dex_compression in ["raw", "raw_subdir", "jar", "xzs"],
+        "Only 'raw', 'raw_subdir', 'jar' and 'xzs' dex compression are supported at this time!",
+    )
+
+    return dex_compression
+
+def get_split_dex_merge_config(ctx: AnalysisContext, android_toolchain: AndroidToolchainInfo) -> SplitDexMergeConfig:
+    secondary_dex_weight_limit = getattr(ctx.attrs, "secondary_dex_weight_limit", None) or android_toolchain.secondary_dex_weight_limit
+    return SplitDexMergeConfig(
+        dex_compression = _get_dex_compression(ctx),
+        primary_dex_patterns = ctx.attrs.primary_dex_patterns,
+        secondary_dex_weight_limit_bytes = secondary_dex_weight_limit,
+    )
+
+def get_single_primary_dex(
+    ctx: AnalysisContext,
+    android_toolchain: AndroidToolchainInfo,
+    java_library_jars: list[Artifact],
+    is_optimized: bool = False,
+    classpath_jars: list[Artifact] = [],
+) -> DexFilesInfo:
+    expect(
+        not _is_exopackage_enabled_for_secondary_dex(ctx),
+        "It doesn't make sense to enable secondary dex exopackage for single dex builds!",
+    )
+    d8_cmd = cmd_args(android_toolchain.d8_command[RunInfo])
+
+    output_dex_file = ctx.actions.declare_output("classes.dex", has_content_based_path = False)
+    d8_cmd.add(["--output-dex-file", output_dex_file.as_output()])
+
+    jar_to_dex_file = argfile(actions = ctx.actions, name = "jar_to_dex_file.txt", args = java_library_jars)
+    d8_cmd.add(["--files-to-dex-list", jar_to_dex_file])
+    if classpath_jars:
+        classpath_file = argfile(actions = ctx.actions, name = "classpath_jars.txt", args = classpath_jars)
+        d8_cmd.add(["--classpath-files", classpath_file])
+
+    d8_cmd.add(["--android-jar", android_toolchain.android_jar])
+    if not is_optimized:
+        d8_cmd.add("--no-optimize")
+
+    ctx.actions.run(
+        d8_cmd,
+        category = "get_single_primary_dex",
+        identifier = "{}:{}".format(ctx.label.package, ctx.label.name),
+        allow_cache_upload = True,
+        error_handler = android_toolchain.android_error_handler,
+    )
+
+    return DexFilesInfo(
+        primary_dex = output_dex_file,
+        root_module_bootstrap_dex_dirs = [],
+        root_module_secondary_dex_dirs = [],
+        non_root_module_secondary_dex_dirs = [],
+        secondary_dex_exopackage_info = None,
+        proguard_text_files_path = None,
+        primary_dex_class_names = None,
+    )
+
+def get_multi_dex(
+    ctx: AnalysisContext,
+    android_toolchain: AndroidToolchainInfo,
+    input_artifacts_to_owners: dict[Artifact, TargetLabel],
+    primary_dex_patterns: list[str],
+    proguard_configuration_output_file: Artifact | None = None,
+    proguard_mapping_output_file: Artifact | None = None,
+    is_optimized: bool = False,
+    apk_module_graph_file: Artifact | None = None,
+    enable_bootstrap_dexes = False,
+    multidex_min_api: str | None = None,
+    pre_dexed_inputs: bool = False,
+    classpath_jars: list[Artifact] = [],
+) -> DexFilesInfo:
+    expect(
+        not _is_exopackage_enabled_for_secondary_dex(ctx),
+        "secondary dex exopackage can only be enabled on pre-dexed builds!",
+    )
+    expect(
+        not pre_dexed_inputs or (multidex_min_api and int(multidex_min_api) > 21),
+        "Pre-dexed native multidex inputs require multidex_min_api > 21",
+    )
+    expect(
+        not pre_dexed_inputs or not primary_dex_patterns,
+        "Pre-dexed native multidex inputs cannot honor primary_dex_patterns, because D8 rejects a main-dex list above min SDK 21",
+    )
+    primary_dex_file = ctx.actions.declare_output("classes.dex", has_content_based_path = False)
+    primary_dex_class_names = ctx.actions.declare_output("primary_dex_class_names.txt", has_content_based_path = False)
+    root_module_secondary_dex_output_dir = ctx.actions.declare_output("root_module_secondary_dex_output_dir", dir = True, has_content_based_path = False)
+    secondary_dex_dir = ctx.actions.declare_output("secondary_dex_output_dir", dir = True, has_content_based_path = False)
+
+    # dynamic actions are not valid with no input, but it's easier to use the same code regardless,
+    # so just create an empty input.
+    inputs = (
+        [apk_module_graph_file]
+        if apk_module_graph_file
+        else [ctx.actions.write("empty_artifact_for_multi_dex_dynamic_action", [], has_content_based_path = False)]
+    )
+    outputs = [primary_dex_file, primary_dex_class_names, root_module_secondary_dex_output_dir, secondary_dex_dir]
+    root_module_bootstrap_dex_output_dir = None
+    if enable_bootstrap_dexes:
+        root_module_bootstrap_dex_output_dir = ctx.actions.declare_output("root_module_bootstrap_dex_output_dir", dir = True, has_content_based_path = False)
+        outputs.append(root_module_bootstrap_dex_output_dir)
+
+    def do_multi_dex(ctx: AnalysisContext, artifacts, outputs):
+        apk_module_graph_info = (
+            get_apk_module_graph_info(ctx, apk_module_graph_file, artifacts) if apk_module_graph_file else get_root_module_only_apk_module_graph_info()
+        )
+        target_to_module_mapping_function = apk_module_graph_info.target_to_module_mapping_function
+        module_to_inputs = {}
+        for input_artifact, owner in input_artifacts_to_owners.items():
+            module = target_to_module_mapping_function(str(owner))
+            module_to_inputs.setdefault(module, []).append(input_artifact)
+
+        secondary_dex_dir_srcs = {}
+        all_inputs = flatten(module_to_inputs.values())
+        all_inputs_list = argfile(actions = ctx.actions, name = "all_inputs_classpath.txt", args = all_inputs + classpath_jars)
+        classpath_jars_list = argfile(actions = ctx.actions, name = "classpath_jars.txt", args = classpath_jars) if classpath_jars else None
+        for module, module_inputs in module_to_inputs.items():
+            multi_dex_cmd = cmd_args(android_toolchain.multi_dex_command[RunInfo])
+            secondary_dex_compression_cmd = cmd_args(android_toolchain.secondary_dex_compression_command[RunInfo])
+
+            uncompressed_secondary_dex_output_dir = ctx.actions.declare_output(
+                "uncompressed_secondary_dex_output_dir_for_module_{}".format(module), dir = True, has_content_based_path = False
+            )
+            multi_dex_cmd.add("--secondary-dex-output-dir", uncompressed_secondary_dex_output_dir.as_output())
+            secondary_dex_compression_cmd.add("--raw-secondary-dexes-dir", uncompressed_secondary_dex_output_dir)
+            if is_root_module(module):
+                primary_dex_patterns_file = ctx.actions.write("primary_dex_patterns", primary_dex_patterns, has_content_based_path = True)
+
+                if pre_dexed_inputs:
+                    expect(
+                        not getattr(ctx.attrs, "minimize_primary_dex_size", False) and not enable_bootstrap_dexes,
+                        "Pre-dexed native multidex inputs do not support primary dex sculpting",
+                    )
+                    inputs_to_dex = module_inputs
+                elif getattr(ctx.attrs, "minimize_primary_dex_size", False) or enable_bootstrap_dexes:
+                    primary_dex_inputs, inputs_to_dex = _get_primary_dex_and_secondary_dex_jars(
+                        ctx,
+                        module_inputs,
+                        input_artifacts_to_owners,
+                        primary_dex_patterns_file,
+                        proguard_configuration_output_file,
+                        proguard_mapping_output_file,
+                        android_toolchain,
+                    )
+
+                    primary_dex_input_file = argfile(actions = ctx.actions, name = "primary_dex_inputs_for_root_module.txt", args = primary_dex_inputs)
+                    multi_dex_cmd.add("--primary-dex-files-to-dex-list", primary_dex_input_file)
+                    multi_dex_cmd.add("--minimize-primary-dex")
+
+                    # Tells the multidex command to allow primary dex pattern matches to be spread across several dex files if needed
+                    if enable_bootstrap_dexes:
+                        multi_dex_cmd.add("--enable-bootstrap-dexes")
+                        multi_dex_cmd.add("--bootstrap-dex-output-dir", outputs[root_module_bootstrap_dex_output_dir].as_output())
+                        secondary_dex_compression_cmd.add("--bootstrap-dexes-dir", outputs[root_module_bootstrap_dex_output_dir])
+                else:
+                    inputs_to_dex = module_inputs
+                    multi_dex_cmd.add("--primary-dex-patterns-path", primary_dex_patterns_file)
+
+                multi_dex_cmd.add("--primary-dex", outputs[primary_dex_file].as_output())
+                multi_dex_cmd.add("--primary-dex-class-names", outputs[primary_dex_class_names].as_output())
+                secondary_dex_compression_cmd.add("--secondary-dex-output-dir", outputs[root_module_secondary_dex_output_dir].as_output())
+            else:
+                secondary_dex_dir_for_module = ctx.actions.declare_output(
+                    "secondary_dex_output_dir_for_module_{}".format(module), dir = True, has_content_based_path = False
+                )
+                secondary_dex_subdir = secondary_dex_dir_for_module.project(_get_secondary_dex_subdir(module))
+                secondary_dex_dir_srcs[_get_secondary_dex_subdir(module)] = secondary_dex_subdir
+                secondary_dex_compression_cmd.add(
+                    "--module-deps",
+                    ctx.actions.write(
+                        "module_deps_for_{}".format(module), apk_module_graph_info.module_to_module_deps_function(module), has_content_based_path = False
+                    ),
+                )
+                secondary_dex_compression_cmd.add("--secondary-dex-output-dir", secondary_dex_dir_for_module.as_output())
+                inputs_to_dex = module_inputs
+            if not pre_dexed_inputs:
+                if is_root_module(module):
+                    if classpath_jars_list:
+                        multi_dex_cmd.add("--classpath-files", classpath_jars_list)
+                else:
+                    multi_dex_cmd.add("--classpath-files", all_inputs_list)
+
+            multi_dex_cmd.add("--module", module)
+            multi_dex_cmd.add("--canary-class-name", apk_module_graph_info.module_to_canary_class_name_function(module))
+            secondary_dex_compression_cmd.add("--module", module)
+            secondary_dex_compression_cmd.add("--canary-class-name", apk_module_graph_info.module_to_canary_class_name_function(module))
+
+            inputs_to_dex_file = argfile(actions = ctx.actions, name = "inputs_to_dex_file_for_module_{}.txt".format(module), args = inputs_to_dex)
+            multi_dex_cmd.add("--files-to-dex-list", inputs_to_dex_file)
+            if pre_dexed_inputs:
+                multi_dex_cmd.add("--pre-dexed-inputs")
+
+            multi_dex_cmd.add("--android-jar", android_toolchain.android_jar)
+            if multidex_min_api:
+                multi_dex_cmd.add("--min-sdk-version", multidex_min_api)
+
+            if not is_optimized:
+                multi_dex_cmd.add("--no-optimize")
+
+            if proguard_configuration_output_file:
+                multi_dex_cmd.add("--proguard-configuration-file", proguard_configuration_output_file)
+                multi_dex_cmd.add("--proguard-mapping-file", proguard_mapping_output_file)
+
+            ctx.actions.run(
+                multi_dex_cmd,
+                category = "multi_dex",
+                identifier = "{}:{}_module_{}".format(ctx.label.package, ctx.label.name, module),
+                allow_cache_upload = True,
+                error_handler = android_toolchain.android_error_handler,
+            )
+
+            secondary_dex_compression_cmd.add("--compression", _get_dex_compression(ctx))
+            secondary_dex_compression_cmd.add("--xz-compression-level", str(getattr(ctx.attrs, "xz_compression_level", 4)))
+
+            ctx.actions.run(
+                secondary_dex_compression_cmd,
+                category = "secondary_dex_compression",
+                identifier = "{}:{}_module_{}".format(ctx.label.package, ctx.label.name, module),
+                allow_cache_upload = True,
+                error_handler = android_toolchain.android_error_handler,
+            )
+
+        ctx.actions.symlinked_dir(outputs[secondary_dex_dir], secondary_dex_dir_srcs)
+
+    ctx.actions.dynamic_output(dynamic = inputs, inputs = [], outputs = [o.as_output() for o in outputs], f = do_multi_dex)
+
+    return DexFilesInfo(
+        primary_dex = primary_dex_file,
+        root_module_bootstrap_dex_dirs = [root_module_bootstrap_dex_output_dir] if root_module_bootstrap_dex_output_dir else [],
+        root_module_secondary_dex_dirs = [root_module_secondary_dex_output_dir],
+        non_root_module_secondary_dex_dirs = [secondary_dex_dir],
+        secondary_dex_exopackage_info = None,
+        proguard_text_files_path = None,
+        primary_dex_class_names = primary_dex_class_names,
+    )
+
+def _get_primary_dex_and_secondary_dex_jars(
+    ctx: AnalysisContext,
+    jars: list[Artifact],
+    java_library_jars_to_owners: dict[Artifact, TargetLabel],
+    primary_dex_patterns_file: Artifact,
+    proguard_configuration_output_file: Artifact | None,
+    proguard_mapping_output_file: Artifact | None,
+    android_toolchain: AndroidToolchainInfo,
+) -> (list[Artifact], list[Artifact]):
+    primary_dex_jars = []
+    secondary_dex_jars = []
+    for jar in jars:
+        jar_splitter_cmd = cmd_args(android_toolchain.jar_splitter_command[RunInfo])
+        owner = java_library_jars_to_owners[jar]
+        identifier = "{}/{}/{}".format(owner.package, owner.name, jar.short_path)
+        primary_dex_jar = ctx.actions.declare_output("root_module_primary_dex_jars/{}".format(identifier), has_content_based_path = True)
+        secondary_dex_jar = ctx.actions.declare_output("root_module_secondary_dex_jars/{}".format(identifier), has_content_based_path = True)
+        jar_splitter_cmd.add([
+            "--input-jar",
+            jar,
+            "--primary-dex-patterns",
+            primary_dex_patterns_file,
+            "--primary-dex-classes-jar",
+            primary_dex_jar.as_output(),
+            "--secondary-dex-classes-jar",
+            secondary_dex_jar.as_output(),
+        ])
+        if proguard_configuration_output_file:
+            jar_splitter_cmd.add("--proguard-configuration-file", proguard_configuration_output_file)
+            jar_splitter_cmd.add("--proguard-mapping-file", proguard_mapping_output_file)
+
+        ctx.actions.run(
+            jar_splitter_cmd,
+            category = "jar_splitter",
+            identifier = identifier,
+            allow_cache_upload = True,
+            error_handler = android_toolchain.android_error_handler,
+        )
+
+        primary_dex_jars.append(primary_dex_jar)
+        secondary_dex_jars.append(secondary_dex_jar)
+
+    return primary_dex_jars, secondary_dex_jars
+
+def merge_to_single_dex(ctx: AnalysisContext, android_toolchain: AndroidToolchainInfo, pre_dexed_libs: list[DexLibraryInfo]) -> DexFilesInfo:
+    expect(
+        not _is_exopackage_enabled_for_secondary_dex(ctx),
+        "It doesn't make sense to enable secondary dex exopackage for single dex builds!",
+    )
+    output_dex_file = ctx.actions.declare_output("classes.dex", has_content_based_path = False)
+    pre_dexed_artifacts_to_dex_file = ctx.actions.declare_output("pre_dexed_artifacts_to_dex_file.txt", has_content_based_path = False)
+    pre_dexed_artifacts = [pre_dexed_lib.dex for pre_dexed_lib in pre_dexed_libs if pre_dexed_lib.dex != None]
+    _merge_dexes(ctx.actions, android_toolchain, output_dex_file, pre_dexed_artifacts, pre_dexed_artifacts_to_dex_file)
+
+    return DexFilesInfo(
+        primary_dex = output_dex_file,
+        root_module_bootstrap_dex_dirs = [],
+        root_module_secondary_dex_dirs = [],
+        non_root_module_secondary_dex_dirs = [],
+        secondary_dex_exopackage_info = None,
+        proguard_text_files_path = None,
+        primary_dex_class_names = None,
+    )
+
+DexInputWithSpecifiedClasses = record(
+    lib = DexLibraryInfo,
+    dex_class_names = list[str],
+)
+
+DexInputsWithClassNamesAndWeightEstimatesFile = record(
+    libs = list[DexLibraryInfo],
+    weight_estimate_and_filtered_class_names_file = Artifact,
+)
+
+# When using jar compression, the secondary dex directory consists of N secondary dex jars, each
+# of which has a corresponding .meta file (the secondary_dex_metadata_file) containing a single
+# line of the form:
+# jar:<size of secondary dex jar (in bytes)> dex:<size of uncompressed dex file (in bytes)>
+#
+# It also contains a metadata.txt file, which consists on N lines, one for each secondary dex
+# jar. Those lines consist of:
+# <secondary dex file name> <sha1 hash of secondary dex> <canary class>
+#
+# We write the line that needs to be added to metadata.txt for this secondary dex jar to
+# secondary_dex_metadata_line, and we use the secondary_dex_canary_class_name for the
+# <canary class>.
+#
+# When we have finished building all of the secondary dexes, we read each of the
+# secondary_dex_metadata_line artifacts and write them to a single metadata.txt file.
+# We do that for raw compression too, since it also has a metadata.txt file.
+SecondaryDexMetadataConfig = record(
+    secondary_dex_compression = str,
+    secondary_dex_metadata_path = [str, None],
+    secondary_dex_metadata_file = Artifact | None,
+    secondary_dex_metadata_line = Artifact,
+    secondary_dex_canary_class_name = str,
+)
+
+def _get_secondary_dex_jar_metadata_config(
+    actions: AnalysisActions, secondary_dex_path: str, module: str, module_to_canary_class_name_function: typing.Callable, index: int
+) -> SecondaryDexMetadataConfig:
+    secondary_dex_metadata_path = secondary_dex_path + ".meta"
+    return SecondaryDexMetadataConfig(
+        secondary_dex_compression = "jar",
+        secondary_dex_metadata_path = secondary_dex_metadata_path,
+        secondary_dex_metadata_file = actions.declare_output(secondary_dex_metadata_path, has_content_based_path = False),
+        secondary_dex_metadata_line = actions.declare_output("metadata_line_artifacts/{}/{}".format(module, index + 1), has_content_based_path = False),
+        secondary_dex_canary_class_name = _get_fully_qualified_canary_class_name(module, module_to_canary_class_name_function, index + 1),
+    )
+
+def _get_secondary_dex_raw_metadata_config(
+    actions: AnalysisActions, module: str, module_to_canary_class_name_function: typing.Callable, index: int
+) -> SecondaryDexMetadataConfig:
+    return SecondaryDexMetadataConfig(
+        secondary_dex_compression = "raw",
+        secondary_dex_metadata_path = None,
+        secondary_dex_metadata_file = None,
+        secondary_dex_metadata_line = actions.declare_output("metadata_line_artifacts/{}/{}".format(module, index + 1), has_content_based_path = False),
+        secondary_dex_canary_class_name = _get_fully_qualified_canary_class_name(module, module_to_canary_class_name_function, index + 1),
+    )
+
+def _get_filter_dex_batch_size() -> int:
+    return 100
+
+def _filter_pre_dexed_libs(
+    actions: AnalysisActions,
+    android_toolchain: AndroidToolchainInfo,
+    primary_dex_patterns_file: Artifact,
+    pre_dexed_libs: list[DexLibraryInfo],
+    batch_number: int,
+) -> DexInputsWithClassNamesAndWeightEstimatesFile:
+    weight_estimate_and_filtered_class_names_file = actions.declare_output(
+        "class_names_and_weight_estimates_for_batch_{}".format(batch_number), has_content_based_path = False
+    )
+
+    filter_dex_cmd_args = cmd_args([
+        "--primary-dex-patterns",
+        primary_dex_patterns_file,
+        "--dex-target-identifiers",
+        [lib.identifier for lib in pre_dexed_libs],
+        "--class-names",
+        [lib.class_names for lib in pre_dexed_libs],
+        "--weight-estimates",
+        [lib.weight_estimate for lib in pre_dexed_libs],
+        "--ref-counts",
+        [lib.ref_count for lib in pre_dexed_libs],
+        "--synthetic-contexts",
+        [lib.synthetic_contexts for lib in pre_dexed_libs],
+        "--output",
+        weight_estimate_and_filtered_class_names_file.as_output(),
+    ])
+
+    filter_dex_cmd = cmd_args([
+        android_toolchain.filter_dex_class_names[RunInfo],
+        at_argfile(
+            actions = actions,
+            name = "filter_dex_cmd_args_{}".format(batch_number),
+            args = filter_dex_cmd_args,
+        ),
+    ])
+    actions.run(
+        filter_dex_cmd,
+        category = "filter_dex",
+        identifier = "batch_{}".format(batch_number),
+        allow_cache_upload = True,
+        error_handler = android_toolchain.android_error_handler,
+    )
+
+    return DexInputsWithClassNamesAndWeightEstimatesFile(
+        libs = pre_dexed_libs, weight_estimate_and_filtered_class_names_file = weight_estimate_and_filtered_class_names_file
+    )
+
+_SortedPreDexedInputs = record(
+    module = str,
+    primary_dex_inputs = list[list[DexInputWithSpecifiedClasses]],
+    secondary_dex_inputs = list[list[DexInputWithSpecifiedClasses]],
+)
+
+def write_metadata_dot_txts_impl(
+    actions: AnalysisActions, metadata_lines: list[str], metadata_line_artifacts: list[ArtifactValue], metadata_dot_txt_output: OutputArtifact
+):
+    actions.write(metadata_dot_txt_output, metadata_lines + [a.read_string().strip() for a in metadata_line_artifacts])
+    return []
+
+_write_metadata_dot_txts_dynamic_action = dynamic_actions(
+    impl = write_metadata_dot_txts_impl,
+    attrs = {
+        "metadata_dot_txt_output": dynattrs.output(),
+        "metadata_line_artifacts": dynattrs.list(dynattrs.artifact_value()),
+        "metadata_lines": dynattrs.list(dynattrs.value(str)),
+    },
+)
+
+def merge_to_split_dex(
+    ctx: AnalysisContext,
+    android_toolchain: AndroidToolchainInfo,
+    pre_dexed_libs: list[DexLibraryInfo],
+    split_dex_merge_config: SplitDexMergeConfig,
+    apk_module_graph_file: Artifact | None = None,
+    enable_bootstrap_dexes: bool = False,
+) -> DexFilesInfo:
+    is_exopackage_enabled_for_secondary_dex = _is_exopackage_enabled_for_secondary_dex(ctx)
+    if is_exopackage_enabled_for_secondary_dex:
+        supported_dex_compression = ["jar", "raw"]
+        expect(
+            split_dex_merge_config.dex_compression in supported_dex_compression,
+            "Exopackage can only be enabled for secondary dexes when the dex compression is {}, but the dex compression is '{}'".format(
+                supported_dex_compression, split_dex_merge_config.dex_compression
+            ),
+        )
+    primary_dex_patterns_file = ctx.actions.write("primary_dex_patterns_file", split_dex_merge_config.primary_dex_patterns, has_content_based_path = False)
+
+    pre_dexed_libs_with_class_names_and_weight_estimates_files = []
+
+    batch_size = _get_filter_dex_batch_size()
+    for batch_number, start_index in enumerate(range(0, len(pre_dexed_libs), batch_size)):
+        end_index = min(start_index + batch_size, len(pre_dexed_libs))
+        pre_dexed_libs_with_class_names_and_weight_estimates_files.append(
+            _filter_pre_dexed_libs(
+                ctx.actions,
+                android_toolchain,
+                primary_dex_patterns_file,
+                pre_dexed_libs[start_index:end_index],
+                batch_number,
+            ),
+        )
+
+    # Create lib metadata mapping: identifier -> owner target label.
+    # This is used by the sort tool to determine which module each lib belongs to.
+    lib_metadata = {}
+    for lib in pre_dexed_libs:
+        if lib.dex:
+            lib_metadata[lib.identifier] = str(lib.dex.owner.raw_target())
+    lib_metadata_file = ctx.actions.write_json("pre_dexed_libs_metadata.json", lib_metadata, has_content_based_path = False)
+
+    filter_dex_output_files = [input.weight_estimate_and_filtered_class_names_file for input in pre_dexed_libs_with_class_names_and_weight_estimates_files]
+    dex_plan_file = ctx.actions.declare_output("dex_plan.json", has_content_based_path = False)
+    sort_cmd = cmd_args([
+        android_toolchain.sort_pre_dexed_files[RunInfo],
+        "--lib-metadata",
+        lib_metadata_file,
+        "--weight-limit",
+        str(split_dex_merge_config.secondary_dex_weight_limit_bytes),
+        "--output",
+        dex_plan_file.as_output(),
+    ])
+    sort_cmd.add("--filter-dex-outputs")
+    sort_cmd.add(filter_dex_output_files)
+    if apk_module_graph_file:
+        sort_cmd.add("--module-graph")
+        sort_cmd.add(apk_module_graph_file)
+    if enable_bootstrap_dexes:
+        sort_cmd.add("--enable-bootstrap-dexes")
+    ctx.actions.run(
+        sort_cmd,
+        category = "sort_pre_dexed_files",
+        allow_cache_upload = True,
+    )
+
+    input_artifacts = [dex_plan_file]
+    if apk_module_graph_file:
+        input_artifacts.append(apk_module_graph_file)
+    primary_dex_artifact_list = ctx.actions.declare_output("pre_dexed_artifacts_for_primary_dex.txt", has_content_based_path = False)
+    primary_dex_output = ctx.actions.declare_output("classes.dex", has_content_based_path = False)
+    primary_dex_class_names_list = ctx.actions.declare_output("primary_dex_class_names_list.txt", has_content_based_path = False)
+    root_module_bootstrap_dexes_dir = ctx.actions.declare_output("root_module_bootstrap_dexes_dir", dir = True, has_content_based_path = False)
+    root_module_secondary_dexes_dir = ctx.actions.declare_output("root_module_secondary_dexes_dir", dir = True, has_content_based_path = False)
+    root_module_secondary_dexes_subdir = root_module_secondary_dexes_dir.project(_get_secondary_dex_subdir(ROOT_MODULE))
+    root_module_secondary_dexes_metadata = root_module_secondary_dexes_dir.project(paths.join(_get_secondary_dex_subdir(ROOT_MODULE), "metadata.txt"))
+    non_root_module_secondary_dexes_dir = ctx.actions.declare_output("non_root_module_secondary_dexes_dir", dir = True, has_content_based_path = False)
+
+    outputs = [
+        primary_dex_output,
+        primary_dex_artifact_list,
+        primary_dex_class_names_list,
+        root_module_bootstrap_dexes_dir,
+        root_module_secondary_dexes_dir,
+        non_root_module_secondary_dexes_dir,
+    ]
+
+    def merge_pre_dexed_libs(ctx: AnalysisContext, artifacts, outputs):
+        # We still need the module graph info for metadata.txt generation (module deps).
+        apk_module_graph_info = (
+            get_apk_module_graph_info(ctx, apk_module_graph_file, artifacts) if apk_module_graph_file else get_root_module_only_apk_module_graph_info()
+        )
+        module_to_canary_class_name_function = apk_module_graph_info.module_to_canary_class_name_function
+
+        plan = artifacts[dex_plan_file].read_json()
+
+        # Build a lookup from identifier to DexLibraryInfo for resolving dex artifacts.
+        libs_by_id = {}
+        for batch in pre_dexed_libs_with_class_names_and_weight_estimates_files:
+            for lib in batch.libs:
+                libs_by_id[lib.identifier] = lib
+
+        def resolve_plan_groups(groups):
+            resolved = []
+            class_names_list = []
+            for group in groups:
+                inputs_for_group = []
+                for lib_id in group["lib_ids"]:
+                    inputs_for_group.append(
+                        DexInputWithSpecifiedClasses(
+                            lib = libs_by_id[lib_id],
+                            dex_class_names = [],  # class names come from the plan
+                        )
+                    )
+                resolved.append(inputs_for_group)
+                class_names_list.append(group["class_names"])
+            return resolved, class_names_list
+
+        sorted_pre_dexed_inputs = []
+        plan_class_names = {}
+        for module_plan in plan["modules"]:
+            module = module_plan["module"]
+            primary_groups, primary_class_names_list = resolve_plan_groups(module_plan["primary_groups"])
+            secondary_groups, secondary_class_names_list = resolve_plan_groups(module_plan["secondary_groups"])
+
+            sorted_pre_dexed_inputs.append(
+                _SortedPreDexedInputs(
+                    module = module,
+                    primary_dex_inputs = primary_groups,
+                    secondary_dex_inputs = secondary_groups,
+                )
+            )
+
+            for i, class_names in enumerate(primary_class_names_list):
+                plan_class_names[("primary", module, i)] = class_names
+            for i, class_names in enumerate(secondary_class_names_list):
+                plan_class_names[("secondary", module, i)] = class_names
+
+        root_module_secondary_dexes_for_symlinking = {}
+        root_module_bootstrap_dexes_for_symlinking = {}
+        non_root_module_secondary_dexes_for_symlinking = {}
+        metadata_line_artifacts_by_module = {}
+        metadata_dot_txt_files_by_module = {}
+        base_apk_dex_files_count = 0
+
+        for sorted_pre_dexed_input in sorted_pre_dexed_inputs:
+            module = sorted_pre_dexed_input.module
+            secondary_dexes_for_symlinking = (
+                root_module_secondary_dexes_for_symlinking if is_root_module(module) else non_root_module_secondary_dexes_for_symlinking
+            )
+
+            # Unpack since primary_dex_inputs is a list of lists (which may be a single list for status-quo behaviors)
+            primary_dex_inputs = sorted_pre_dexed_input.primary_dex_inputs[0] if sorted_pre_dexed_input.primary_dex_inputs else []
+            additional_base_apk_dex_inputs = sorted_pre_dexed_input.primary_dex_inputs[1:]
+            pre_dexed_artifacts = [primary_dex_input.lib.dex for primary_dex_input in primary_dex_inputs if primary_dex_input.lib.dex]
+            if pre_dexed_artifacts:
+                expect(is_root_module(module), "module {} should not have a primary dex!".format(module))
+                primary_class_names = plan_class_names[("primary", module, 0)]
+                ctx.actions.write(
+                    outputs[primary_dex_class_names_list].as_output(),
+                    primary_class_names,
+                )
+
+                _merge_dexes(
+                    ctx.actions,
+                    android_toolchain,
+                    outputs[primary_dex_output],
+                    pre_dexed_artifacts,
+                    outputs[primary_dex_artifact_list],
+                    class_names_to_include = primary_dex_class_names_list,
+                )
+                base_apk_dex_files_count += 1
+
+                # If primary dex classes were spread to many based on weight, merge additional dex files here.
+                for bootstrap_idx, bootstrap_dex_input_list in enumerate(additional_base_apk_dex_inputs):
+                    this_dex_number = base_apk_dex_files_count + 1
+                    bootstrap_class_names = plan_class_names[("primary", module, bootstrap_idx + 1)]
+                    bootstrap_dex_class_list = ctx.actions.write(
+                        "class_list_for_bootstrap_dex_{}.txt".format(this_dex_number),
+                        bootstrap_class_names,
+                        has_content_based_path = False,
+                    )
+
+                    # Figure out the name of this file and prepare its location for symlinking in final output dir.
+                    dex_file_name = "classes{}.dex".format(this_dex_number)
+                    bootstrap_dex_artifact_list = ctx.actions.declare_output(
+                        "pre_dexed_artifacts_for_bootstrap_dex_{}.txt".format(this_dex_number), has_content_based_path = False
+                    )
+                    bootstrap_dex_output = ctx.actions.declare_output(dex_file_name, has_content_based_path = False)
+                    root_module_bootstrap_dexes_for_symlinking[dex_file_name] = bootstrap_dex_output
+                    bootstrap_dex_artifacts = [bootstrap_dex_input.lib.dex for bootstrap_dex_input in bootstrap_dex_input_list]
+
+                    _merge_dexes(
+                        ctx.actions,
+                        android_toolchain,
+                        bootstrap_dex_output,
+                        bootstrap_dex_artifacts,
+                        bootstrap_dex_artifact_list,
+                        class_names_to_include = bootstrap_dex_class_list,
+                    )
+                    base_apk_dex_files_count += 1
+
+            else:
+                expect(
+                    not is_root_module(module),
+                    "No primary dex classes were specified! Please add primary_dex_patterns to ensure that at least one class exists in the primary dex.",
+                )
+
+            secondary_dex_inputs = sorted_pre_dexed_input.secondary_dex_inputs
+            raw_secondary_dexes_for_compressing = {}
+            for i in range(len(secondary_dex_inputs)):
+                if split_dex_merge_config.dex_compression in ["jar", "raw", "raw_subdir"]:
+                    if split_dex_merge_config.dex_compression == "jar":
+                        secondary_dex_path = _get_secondary_dex_subdir_path(i, module)
+                        secondary_dex_metadata_config = _get_secondary_dex_jar_metadata_config(
+                            ctx.actions, secondary_dex_path, module, module_to_canary_class_name_function, i
+                        )
+                        secondary_dexes_for_symlinking[secondary_dex_metadata_config.secondary_dex_metadata_path] = (
+                            secondary_dex_metadata_config.secondary_dex_metadata_file
+                        )
+                    else:
+                        secondary_dex_path = _get_raw_secondary_dex_path(
+                            i,
+                            module,
+                            base_apk_dex_files_count,
+                            is_exopackage_enabled_for_secondary_dex or split_dex_merge_config.dex_compression == "raw_subdir",
+                        )
+                        secondary_dex_metadata_config = _get_secondary_dex_raw_metadata_config(ctx.actions, module, module_to_canary_class_name_function, i)
+
+                    secondary_dex_output = ctx.actions.declare_output(secondary_dex_path, has_content_based_path = False)
+                    secondary_dexes_for_symlinking[secondary_dex_path] = secondary_dex_output
+                    metadata_line_artifacts_by_module.setdefault(module, []).append(secondary_dex_metadata_config.secondary_dex_metadata_line)
+                else:
+                    secondary_dex_name = _get_raw_secondary_dex_name(i, module, base_apk_dex_files_count)
+                    secondary_dex_output = ctx.actions.declare_output("{}/{}".format(module, secondary_dex_name), has_content_based_path = False)
+                    raw_secondary_dexes_for_compressing[secondary_dex_name] = secondary_dex_output
+                    secondary_dex_metadata_config = None
+
+                this_dex_number = i + (base_apk_dex_files_count + 1 if is_root_module(module) else 2)
+                secondary_dex_artifact_list = ctx.actions.declare_output(
+                    "pre_dexed_artifacts_for_secondary_dex_{}_for_module_{}.txt".format(this_dex_number, module), has_content_based_path = False
+                )
+
+                canary_dex_input = _create_canary_class(
+                    ctx,
+                    i + 1,
+                    module,
+                    module_to_canary_class_name_function,
+                    ctx.attrs._dex_toolchain[DexToolchainInfo],
+                )
+                all_class_names = canary_dex_input.dex_class_names + plan_class_names[("secondary", module, i)]
+                secondary_dex_class_list = ctx.actions.write(
+                    "class_list_for_secondary_dex_{}_for_module_{}.txt".format(this_dex_number, module),
+                    all_class_names,
+                    has_content_based_path = False,
+                )
+                pre_dexed_artifacts = [canary_dex_input.lib.dex] if canary_dex_input.lib.dex else []
+                pre_dexed_artifacts.extend([dex_input.lib.dex for dex_input in secondary_dex_inputs[i] if dex_input.lib.dex])
+
+                _merge_dexes(
+                    ctx.actions,
+                    android_toolchain,
+                    secondary_dex_output,
+                    pre_dexed_artifacts,
+                    secondary_dex_artifact_list,
+                    class_names_to_include = secondary_dex_class_list,
+                    secondary_dex_metadata_config = secondary_dex_metadata_config,
+                )
+
+            if split_dex_merge_config.dex_compression in ["jar", "raw", "raw_subdir"]:
+                metadata_dot_txt_path = "{}/metadata.txt".format(_get_secondary_dex_subdir(module))
+                metadata_dot_txt_file = ctx.actions.declare_output(metadata_dot_txt_path, has_content_based_path = False)
+                secondary_dexes_for_symlinking[metadata_dot_txt_path] = metadata_dot_txt_file
+                metadata_dot_txt_files_by_module[module] = metadata_dot_txt_file
+            else:
+                raw_secondary_dexes_dir = ctx.actions.symlinked_dir(
+                    "raw_secondary_dexes_dir_for_module_{}".format(module), raw_secondary_dexes_for_compressing, has_content_based_path = False
+                )
+                secondary_dex_dir_for_module = ctx.actions.declare_output("secondary_dexes_dir_for_{}".format(module), dir = True, has_content_based_path = False)
+                secondary_dex_subdir = secondary_dex_dir_for_module.project(_get_secondary_dex_subdir(module))
+
+                multi_dex_cmd = cmd_args(android_toolchain.secondary_dex_compression_command[RunInfo])
+                multi_dex_cmd.add("--secondary-dex-output-dir", secondary_dex_dir_for_module.as_output())
+                multi_dex_cmd.add("--raw-secondary-dexes-dir", raw_secondary_dexes_dir)
+                multi_dex_cmd.add("--compression", _get_dex_compression(ctx))
+                multi_dex_cmd.add("--xz-compression-level", str(ctx.attrs.xz_compression_level))
+                multi_dex_cmd.add("--module", module)
+                multi_dex_cmd.add("--canary-class-name", module_to_canary_class_name_function(module))
+                if not is_root_module(module):
+                    multi_dex_cmd.add(
+                        "--module-deps",
+                        ctx.actions.write(
+                            "module_deps_for_{}".format(module), apk_module_graph_info.module_to_module_deps_function(module), has_content_based_path = False
+                        ),
+                    )
+
+                ctx.actions.run(
+                    multi_dex_cmd,
+                    category = "multi_dex_from_raw_dexes",
+                    identifier = "{}:{}_module_{}".format(ctx.label.package, ctx.label.name, module),
+                    allow_cache_upload = True,
+                    error_handler = android_toolchain.android_error_handler,
+                )
+
+                secondary_dexes_for_symlinking[_get_secondary_dex_subdir(module)] = secondary_dex_subdir
+
+        for voltron_module, metadata_dot_txt in metadata_dot_txt_files_by_module.items():
+            metadata_line_artifacts = metadata_line_artifacts_by_module[voltron_module]
+            expect(metadata_line_artifacts != None, "Should have metadata lines!")
+
+            metadata_lines = [".id {}".format(voltron_module)]
+            metadata_lines.extend([".requires {}".format(module_dep) for module_dep in apk_module_graph_info.module_to_module_deps_function(voltron_module)])
+            if split_dex_merge_config.dex_compression == "raw" and is_root_module(voltron_module) and not is_exopackage_enabled_for_secondary_dex:
+                metadata_lines.append(".root_relative")
+            ctx.actions.dynamic_output_new(
+                _write_metadata_dot_txts_dynamic_action(
+                    metadata_dot_txt_output = metadata_dot_txt.as_output(),
+                    metadata_line_artifacts = metadata_line_artifacts,
+                    metadata_lines = metadata_lines,
+                ),
+            )
+
+        ctx.actions.symlinked_dir(
+            outputs[root_module_secondary_dexes_dir],
+            root_module_secondary_dexes_for_symlinking,
+        )
+        ctx.actions.symlinked_dir(
+            outputs[root_module_bootstrap_dexes_dir],
+            root_module_bootstrap_dexes_for_symlinking,
+        )
+        ctx.actions.symlinked_dir(
+            outputs[non_root_module_secondary_dexes_dir],
+            non_root_module_secondary_dexes_for_symlinking,
+        )
+
+    ctx.actions.dynamic_output(dynamic = input_artifacts, inputs = [], outputs = [o.as_output() for o in outputs], f = merge_pre_dexed_libs)
+
+    if is_exopackage_enabled_for_secondary_dex:
+        root_module_secondary_dex_dirs = []
+        secondary_dex_exopackage_info = ExopackageDexInfo(
+            metadata = root_module_secondary_dexes_metadata,
+            directory = root_module_secondary_dexes_subdir,
+        )
+    else:
+        root_module_secondary_dex_dirs = [root_module_secondary_dexes_dir]
+        secondary_dex_exopackage_info = None
+
+    return DexFilesInfo(
+        primary_dex = primary_dex_output,
+        root_module_bootstrap_dex_dirs = [root_module_bootstrap_dexes_dir],
+        root_module_secondary_dex_dirs = root_module_secondary_dex_dirs,
+        non_root_module_secondary_dex_dirs = [non_root_module_secondary_dexes_dir],
+        secondary_dex_exopackage_info = secondary_dex_exopackage_info,
+        proguard_text_files_path = None,
+        primary_dex_class_names = primary_dex_class_names_list,
+    )
+
+def _merge_dexes(
+    actions: AnalysisActions,
+    android_toolchain: AndroidToolchainInfo,
+    output_dex_file: Artifact,
+    pre_dexed_artifacts: list[Artifact],
+    pre_dexed_artifacts_file: Artifact,
+    class_names_to_include: Artifact | None = None,
+    secondary_output_dex_file: Artifact | None = None,
+    secondary_dex_metadata_config: [SecondaryDexMetadataConfig, None] = None,
+):
+    d8_cmd = cmd_args(android_toolchain.d8_command[RunInfo])
+    d8_cmd.add(["--output-dex-file", output_dex_file.as_output()])
+
+    pre_dexed_artifacts_to_dex_file = argfile(actions = actions, name = pre_dexed_artifacts_file, args = pre_dexed_artifacts)
+    d8_cmd.add(["--files-to-dex-list", pre_dexed_artifacts_to_dex_file])
+
+    d8_cmd.add(["--android-jar", android_toolchain.android_jar])
+    d8_cmd.add(_DEX_MERGE_OPTIONS)
+
+    if class_names_to_include:
+        d8_cmd.add(["--primary-dex-class-names-path", class_names_to_include])
+
+    if secondary_output_dex_file:
+        d8_cmd.add(["--secondary-output-dex-file", secondary_output_dex_file.as_output()])
+
+    if secondary_dex_metadata_config:
+        d8_cmd.add(["--secondary-dex-compression", secondary_dex_metadata_config.secondary_dex_compression])
+        if secondary_dex_metadata_config.secondary_dex_metadata_file:
+            d8_cmd.add(["--secondary-dex-metadata-file", secondary_dex_metadata_config.secondary_dex_metadata_file.as_output()])
+        d8_cmd.add(["--secondary-dex-metadata-line", secondary_dex_metadata_config.secondary_dex_metadata_line.as_output()])
+        d8_cmd.add(["--secondary-dex-canary-class-name", secondary_dex_metadata_config.secondary_dex_canary_class_name])
+
+    actions.run(
+        d8_cmd,
+        category = "merge_dexes",
+        identifier = output_dex_file.short_path,
+        allow_cache_upload = True,
+        error_handler = android_toolchain.android_error_handler,
+    )
+
+def _get_raw_secondary_dex_name(index: int, module: str, base_apk_dex_count: int) -> str:
+    # Root module begins at 2 (primary classes.dex is 1)
+    # Non-root module begins at 1 (classes.dex)
+    if is_root_module(module):
+        return "classes{}.dex".format(index + base_apk_dex_count + 1)
+    elif index == 0:
+        return "classes.dex"
+    else:
+        return "classes{}.dex".format(index + 1)
+
+def _get_raw_secondary_dex_path(index: int, module: str, base_apk_dex_count: int, store_raw_secondary_dexes_in_secondary_dex_subdir: bool):
+    if is_root_module(module):
+        if store_raw_secondary_dexes_in_secondary_dex_subdir:
+            return _get_secondary_dex_subdir_path(index, module, "dex")
+        return _get_raw_secondary_dex_name(index, module, base_apk_dex_count)
+    else:
+        return "assets/{}/{}".format(module, _get_raw_secondary_dex_name(index, module, base_apk_dex_count))
+
+def _get_secondary_dex_subdir_path(index: int, module: str, suffix: str = "dex.jar"):
+    return "{}/{}-{}.{}".format(
+        _get_secondary_dex_subdir(module),
+        "secondary" if is_root_module(module) else module,
+        index + 1,
+        suffix,
+    )
+
+def _get_secondary_dex_subdir(module: str):
+    return "assets/{}".format("secondary-program-dex-jars" if is_root_module(module) else module)
+
+# We create "canary" classes and add them to each secondary dex jar to ensure each jar has a class
+# that can be safely loaded on any system. This class is used during secondary dex verification.
+_CANARY_FULLY_QUALIFIED_CLASS_NAME_TEMPLATE = "{}.dex{}.Canary"
+_CANARY_FILE_NAME_TEMPLATE = "canary_classes/{}/dex{}/Canary.java"
+_CANARY_CLASS_PACKAGE_TEMPLATE = "package {}.dex{};\n"
+_CANARY_CLASS_INTERFACE_DEFINITION = "public interface Canary {}"
+
+def _create_canary_class(
+    ctx: AnalysisContext, index: int, module: str, module_to_canary_class_name_function: typing.Callable, dex_toolchain: DexToolchainInfo
+) -> DexInputWithSpecifiedClasses:
+    prefix = module_to_canary_class_name_function(module)
+    index_string = str(index)
+    if len(index_string) == 1:
+        index_string = "0" + index_string
+    canary_class_java_file = ctx.actions.write(
+        _CANARY_FILE_NAME_TEMPLATE.format(prefix, index_string),
+        [_CANARY_CLASS_PACKAGE_TEMPLATE.format(prefix, index_string), _CANARY_CLASS_INTERFACE_DEFINITION],
+        has_content_based_path = True,
+    )
+    canary_class_jar = ctx.actions.declare_output(
+        "canary_classes/{}/canary_jar_{}.jar".format(prefix, index_string),
+        has_content_based_path = True,
+    )
+    compile_to_jar(ctx, [canary_class_java_file], output = canary_class_jar, actions_identifier = "{}_canary_class{}".format(prefix, index_string))
+
+    dex_library_info = get_dex_produced_from_java_library(ctx, dex_toolchain = dex_toolchain, jar_to_dex = canary_class_jar)
+
+    return DexInputWithSpecifiedClasses(
+        lib = dex_library_info,
+        dex_class_names = [_get_fully_qualified_canary_class_name(module, module_to_canary_class_name_function, index).replace(".", "/") + ".class"],
+    )
+
+def _get_fully_qualified_canary_class_name(module: str, module_to_canary_class_name_function: typing.Callable, index: int) -> str:
+    prefix = module_to_canary_class_name_function(module)
+    index_string = str(index)
+    if len(index_string) == 1:
+        index_string = "0" + index_string
+    return _CANARY_FULLY_QUALIFIED_CLASS_NAME_TEMPLATE.format(prefix, index_string)
+
+def _is_exopackage_enabled_for_secondary_dex(ctx: AnalysisContext) -> bool:
+    return "secondary_dex" in getattr(ctx.attrs, "exopackage_modes", [])
diff --git a/buck2/prelude/android/duplicate_class_check.bzl b/buck2/prelude/android/duplicate_class_check.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/duplicate_class_check.bzl
@@ -0,0 +1,134 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+
+# Number of batches to split the class name files into.
+# This reduces the number of hidden inputs from 40K+ files to NUM_BATCHES files.
+_NUM_BATCHES = 32
+
+def check_for_duplicate_classes_for_pre_dexed_libs(ctx: AnalysisContext, target_name_to_class_name_mapping: dict[str, Artifact]) -> Artifact:
+    """
+    Check for duplicate class names across pre-dexed libraries.
+
+    To optimize performance, this function:
+    1. Splits the class name files into batches
+    2. Consolidates each batch into a single JSON file
+    3. Runs the duplicate class checker on the consolidated files
+
+    This reduces the number of hidden inputs from O(N) individual files to
+    O(NUM_BATCHES) consolidated files, significantly improving action
+    materialization time in remote execution.
+    """
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+
+    # Convert to list for batching
+    items = list(target_name_to_class_name_mapping.items())
+    num_items = len(items)
+
+    if num_items == 0:
+        # No class names to check, just create empty validation output
+        validation_output = ctx.actions.declare_output("validation_output.txt", has_content_based_path = False)
+        ctx.actions.write(validation_output, "No duplicate class names found")
+        return validation_output
+
+    # Calculate batch size
+    batch_size = max(1, (num_items + _NUM_BATCHES - 1) // _NUM_BATCHES)
+
+    # Create consolidated files for each batch
+    consolidated_files = []
+    for batch_idx in range(0, num_items, batch_size):
+        batch_end = min(batch_idx + batch_size, num_items)
+        batch_items = items[batch_idx:batch_end]
+        batch_mapping = {k: v for k, v in batch_items}
+
+        batch_num = batch_idx // batch_size
+        consolidated_file = _consolidate_class_names_batch(
+            ctx,
+            android_toolchain,
+            batch_mapping,
+            batch_num,
+        )
+        consolidated_files.append(consolidated_file)
+
+    # Run duplicate class checker on consolidated files
+    validation_output = ctx.actions.declare_output("validation_output.txt", has_content_based_path = False)
+    consolidated_files_list = ctx.actions.declare_output("consolidated_files_list.txt", has_content_based_path = False)
+    ctx.actions.write(
+        consolidated_files_list,
+        consolidated_files,
+    )
+
+    ctx.actions.run(
+        cmd_args(
+            android_toolchain.duplicate_class_checker[RunInfo],
+            "--mode",
+            "pre-dexed-libs",
+            "--validation-output",
+            validation_output.as_output(),
+            "--consolidated-files-list",
+            consolidated_files_list,
+            hidden = consolidated_files,
+        ),
+        category = "check_duplicate_classes_pre_dexed_libs",
+        allow_cache_upload = True,
+    )
+    return validation_output
+
+def _consolidate_class_names_batch(
+    ctx: AnalysisContext, android_toolchain: AndroidToolchainInfo, target_name_to_class_name_mapping: dict[str, Artifact], batch_num: int
+) -> Artifact:
+    """Consolidate a batch of class name files into a single JSON file."""
+    input_mapping_file = ctx.actions.declare_output(
+        "consolidate_batch_{}_input.json".format(batch_num),
+        has_content_based_path = False,
+    )
+    ctx.actions.write_json(input_mapping_file, target_name_to_class_name_mapping)
+
+    consolidated_output = ctx.actions.declare_output(
+        "consolidated_class_names_batch_{}.json".format(batch_num),
+        has_content_based_path = False,
+    )
+
+    ctx.actions.run(
+        cmd_args(
+            android_toolchain.consolidate_class_names[RunInfo],
+            "--input-mapping-file",
+            input_mapping_file,
+            "--output-file",
+            consolidated_output.as_output(),
+            hidden = target_name_to_class_name_mapping.values(),
+        ),
+        category = "consolidate_class_names",
+        identifier = "batch_{}".format(batch_num),
+        allow_cache_upload = True,
+    )
+    return consolidated_output
+
+def check_for_duplicate_classes_for_non_pre_dexed_jars(ctx: AnalysisContext, jar_to_owning_target_mapping: dict[Artifact, TargetLabel]) -> Artifact:
+    validation_output = ctx.actions.declare_output("validation_output.txt", has_content_based_path = False)
+    jar_to_owning_target_map_file = ctx.actions.declare_output("jar_to_owning_target_map_file.txt", has_content_based_path = False)
+    ctx.actions.write_json(
+        jar_to_owning_target_map_file,
+        jar_to_owning_target_mapping,
+    )
+
+    ctx.actions.run(
+        cmd_args(
+            ctx.attrs._android_toolchain[AndroidToolchainInfo].duplicate_class_checker[RunInfo],
+            "--mode",
+            "non-pre-dexed-jars",
+            "--jar-to-owning-target-map-file",
+            jar_to_owning_target_map_file,
+            "--validation-output",
+            validation_output.as_output(),
+            hidden = jar_to_owning_target_mapping.keys(),
+        ),
+        category = "check_duplicate_classes_non_pre_dexed_jars",
+    )
+    return validation_output
diff --git a/buck2/prelude/android/exopackage.bzl b/buck2/prelude/android/exopackage.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/exopackage.bzl
@@ -0,0 +1,31 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:expect.bzl", "expect")
+
+SECONDARY_DEX = 1
+NATIVE_LIBRARY = 2
+RESOURCES = 4
+MODULES = 8
+ARCH64 = 16
+
+def get_exopackage_flags(exopackage_modes: list[str]) -> int:
+    expect("modules" not in exopackage_modes, "Modular exopackage is not supported!")
+    flags = 0
+
+    for name, flag in [
+        ("secondary_dex", SECONDARY_DEX),
+        ("native_library", NATIVE_LIBRARY),
+        ("resources", RESOURCES),
+        ("modules", MODULES),
+        ("arch64", ARCH64),
+    ]:
+        if name in exopackage_modes:
+            flags += flag
+
+    return flags
diff --git a/buck2/prelude/android/gen_aidl.bzl b/buck2/prelude/android/gen_aidl.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/gen_aidl.bzl
@@ -0,0 +1,80 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load(":android_toolchain.bzl", "AidlToolchainInfo")
+
+_AidlSourceInfo = provider(
+    fields = {
+        "srcs": provider_field(typing.Any, default = None),
+    }
+)
+
+def gen_aidl_impl(ctx: AnalysisContext) -> list[Provider]:
+    aidl_toolchain = ctx.attrs._aidl_toolchain[AidlToolchainInfo]
+    aidl_cmd = cmd_args(
+        [aidl_toolchain.aidl]
+        + ["-p", aidl_toolchain.framework_aidl_file]
+        + ["-I", ctx.attrs.import_path]
+        + [a for path in ctx.attrs.import_paths for a in ["-I", path]],
+        # We need the `aidl_srcs` files - otherwise the search on the `import_path` won't find anything.
+        hidden = ctx.attrs.aidl_srcs,
+    )
+
+    # Allow gen_aidl rules to depend on other gen_aidl rules, and make the source files from the
+    # deps accessible in this context. This is an alternative to adding dependent files in
+    # aidl_srcs.
+    dep_srcs = []
+    for dep in ctx.attrs.deps:
+        source_info = dep.get(_AidlSourceInfo)
+        if source_info != None:
+            dep_srcs += source_info.srcs
+        else:
+            warning("`{}` dependency `{}` is not a `gen_aidl` rule and will be ignored".format(ctx.label, dep.label))
+
+    aidl_cmd.add(cmd_args(hidden = dep_srcs))
+
+    aidl_out = ctx.actions.declare_output("aidl_output", dir = True, has_content_based_path = True)
+    aidl_cmd.add("-o", aidl_out.as_output())
+    aidl_cmd.add(ctx.attrs.aidl)
+
+    # Aidl does not create any output for parcelables. Therefore, we always initialize the output
+    # directory so that we don't get an "Action failed to produce outputs" error.
+    if ctx.attrs._exec_os_type[OsLookup].os == Os("windows"):
+        sh_cmd = cmd_args([
+            cmd_args(["cmd.exe", "/c", cmd_args([aidl_out.as_output()], format = "if not exist {} md {}")]),
+            "&&",
+            aidl_cmd,
+        ])
+    else:
+        sh_cmd = cmd_args([
+            "sh",
+            "-c",
+            "mkdir -p $1 && $2",
+            "--",
+            aidl_out.as_output(),
+            cmd_args(aidl_cmd, delimiter = " "),
+        ])
+
+    ctx.actions.run(sh_cmd, category = "aidl")
+
+    # Put the generated Java files into a zip file to be used as srcs to other rules.
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    jar_cmd = cmd_args(java_toolchain.jar)
+    jar_cmd.add("-cfM")
+    out = ctx.actions.declare_output("{}_aidl_java_output.src.zip".format(ctx.attrs.name), has_content_based_path = True)
+    jar_cmd.add(out.as_output())
+    jar_cmd.add(aidl_out)
+
+    ctx.actions.run(jar_cmd, category = "aidl_jar")
+
+    return [
+        DefaultInfo(default_output = out),
+        _AidlSourceInfo(srcs = [ctx.attrs.aidl] + ctx.attrs.aidl_srcs + dep_srcs),
+    ]
diff --git a/buck2/prelude/android/keystore.bzl b/buck2/prelude/android/keystore.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/keystore.bzl
@@ -0,0 +1,19 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":android_providers.bzl", "KeystoreInfo")
+
+def keystore_impl(ctx: AnalysisContext) -> list[Provider]:
+    sub_targets = {}
+    sub_targets["keystore"] = [DefaultInfo(default_output = ctx.attrs.store)]
+    sub_targets["properties"] = [DefaultInfo(default_output = ctx.attrs.properties)]
+
+    return [
+        KeystoreInfo(store = ctx.attrs.store, properties = ctx.attrs.properties),
+        DefaultInfo(default_outputs = [ctx.attrs.store, ctx.attrs.properties], sub_targets = sub_targets),
+    ]
diff --git a/buck2/prelude/android/min_sdk_version.bzl b/buck2/prelude/android/min_sdk_version.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/min_sdk_version.bzl
@@ -0,0 +1,16 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+_MIN_SDK_VERSION = 19
+_MAX_SDK_VERSION = 36
+
+def get_min_sdk_version_constraint_value_name(min_sdk: int) -> str:
+    return "min_sdk_version_{}".format(min_sdk)
+
+def get_min_sdk_version_range() -> range:
+    return range(_MIN_SDK_VERSION, _MAX_SDK_VERSION)
diff --git a/buck2/prelude/android/native_build_commands.bzl b/buck2/prelude/android/native_build_commands.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/native_build_commands.bzl
@@ -0,0 +1,124 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Shared schema for the [native_build_commands] sub-target, used by both
+# android_binary_native_library_rules.bzl and meta_only/gatorade.bzl. This lives in a leaf module
+# because gatorade.bzl is loaded by android_binary_native_library_rules.bzl and so cannot import the
+# entry helper back from there.
+
+# Whether to capture per-source compile commands (the expensive [native_build_commands][compile]
+# kind). Off by default; enable with `-c cxx.emit_native_build_commands=true`. Follows the
+# FORCE_SINGLE_CPU config-backed-attr pattern. Single source of truth for both the cxx_library attr
+# that carries compile commands onto the linkable graph (rules_impl.bzl) and the app-side compile
+# emission (android_binary_native_library_rules.bzl).
+EMIT_NATIVE_BUILD_COMMANDS = read_root_config("cxx", "emit_native_build_commands") in ("True", "true")
+
+# Command "kinds" collected by the [native_build_commands] sub-target. Each kind also gets its own
+# filtered sub-target, e.g. `TARGET[native_build_commands][relink]`. Note `mergemap` (the one
+# whole-graph merge-map PLAN computation) is distinct from `merge` (the per-soname merge link that
+# combines constituent libraries), and `link` is reserved for a plain per-library link on apps that
+# neither merge nor relink.
+NATIVE_BUILD_COMMAND_KINDS = [
+    "compile",
+    "mergemap",
+    "merge",
+    "link",
+    "relink",
+    "early_gatorade",
+    "middle_gatorade",
+    "late_gatorade",
+    "bolt",
+]
+
+# The Gatorade phases exposed as top-level product sub-targets on Android app targets: building
+# `TARGET[early_gatorade]` runs that phase and outputs the artifacts its gatorade invocation(s)
+# produce, as a directory (like [native_libs]). Kept in this leaf module as the single source of
+# truth for both the app rule that registers them and apk_genrule.bzl that forwards them through the
+# redex/repack/resign wrapper. (Unrelated to NATIVE_BUILD_COMMAND_KINDS above, which is the separate
+# [native_build_commands] JSON schema; these names coincide with those Gatorade kinds only by
+# convention.)
+GATORADE_PHASE_SUBTARGETS = [
+    "early_gatorade",
+    "middle_gatorade",
+    "late_gatorade",
+]
+
+# One entry in the [native_build_commands] JSON. `argv` is embedded as an ArgLike via
+# write_json(with_inputs = False) so an entry renders its command without materializing the produced
+# artifact, and `argsfile` lets a consumer expand the full flag list when the argv references an
+# @argsfile. This shape is intentionally its own thing, not a compile_commands.json entry nor the
+# [linker_commands] shape: it spans compile/link/merge/relink/gatorade/bolt uniformly, so consumers
+# should key off `kind` rather than assume any single tool's schema.
+#
+# `argv` must not contain any `.as_output()` reference: write_json cannot re-serialize an output
+# artifact, and doing so would also make this entry's writer a second producer of that artifact.
+# Pass the plain output artifact instead.
+#
+# Field notes:
+#  - `argv`: for link/merge/relink/bolt/gatorade kinds this is the real executed command. For
+#    kind=compile it is the compile_commands.json-style invocation (compiler + @argsfile + source),
+#    NOT the exact object-producing action (it omits `-o`, LTO/bitcode flavor flags, dep-file and
+#    compiler-wrapper args); it mirrors what comp_db.bzl emits for a source. Use it to reproduce a
+#    representative compile, not to byte-match the build action.
+#  - `soname`: for per-library kinds, the FINAL shipped/merged soname the command contributes to.
+#    Best-effort for kind=compile: the compile->merged-soname map is built from each merged lib's
+#    PRIMARY constituents (matching shared_object_targets.txt), so an object that lands in a merged
+#    .so only as a non-primary / transitively-linked-static constituent is reported under its own
+#    `pre_merge_soname` rather than the merged soname. Split groups and late-gatorade code motion also
+#    make it approximate — cross-reference the app's merge.map / shared_object_targets.txt when an
+#    authoritative object->soname mapping is needed. None for whole-graph steps (e.g. compute_mergemap).
+#  - `pre_merge_soname`: for kind=compile, the per-cxx_library (pre-merge) soname the object was
+#    built for; None for other kinds.
+#  - `output`: the produced artifact's short_path for link/merge/relink/bolt/gatorade kinds; for
+#    kind=compile it is the compiled SOURCE path (the produced object is not available here — the
+#    full per-source attribution lives in `identifier`).
+#  - `argsfile`: the @argsfile the command references, if any. The sub-target MATERIALIZES it on disk
+#    for the link-family (merge/link/relink/bolt) and compile kinds, so a consumer that builds
+#    TARGET[native_build_commands] (or a per-kind filter) can read the flags. Gatorade argsfiles
+#    (early's input-containers list, late codegen and tmp-link) are recorded by PATH only, not
+#    materialized by the sub-target — build the app itself to obtain those files on disk.
+def native_build_command_entry(kind, category, arch, soname, output, argv, argsfile = None, identifier = None, pre_merge_soname = None):
+    if kind not in NATIVE_BUILD_COMMAND_KINDS:
+        fail("native_build_command_entry: unknown kind {!r}; expected one of {}".format(kind, NATIVE_BUILD_COMMAND_KINDS))
+    return {
+        "arch": arch,
+        "argsfile": argsfile,
+        "argv": argv,
+        "category": category,
+        "identifier": identifier,
+        "kind": kind,
+        "output": output,
+        "pre_merge_soname": pre_merge_soname,
+        "soname": soname,
+    }
+
+# Record a link-family entry (link/merge/relink/bolt) for a LinkedObject, deduplicating the identical
+# guard+append that otherwise gets copy-pasted at every capture site. No-op when recording is off
+# (native_cmd_entries == None) or the object carries no reified linker command (prebuilt copies,
+# pre-bolt/late-gatorade dummy objects, and DistLTO all have none). `linked_object` is accepted
+# untyped to keep this a leaf module (no prelude/linking import); it must expose the LinkedObject
+# fields `output`, `linker_command`, and `linker_argsfile`.
+#
+# Intentionally NOT built on linking's make_link_command_debug_output: that helper also requires an
+# argsfile and drops the command otherwise, which would silently lose links that inline all flags —
+# unacceptable for a capture-everything sub-target. Here argsfile is optional (recorded as None).
+def record_link_command(native_cmd_entries, kind, arch, soname, linked_object, category = "cxx_link", pre_merge_soname = None):
+    if native_cmd_entries == None or not linked_object.linker_command:
+        return
+    native_cmd_entries.append(
+        native_build_command_entry(
+            kind = kind,
+            category = category,
+            arch = arch,
+            soname = soname,
+            output = linked_object.output.short_path,
+            argv = linked_object.linker_command,
+            argsfile = linked_object.linker_argsfile,
+            pre_merge_soname = pre_merge_soname,
+        ),
+    )
diff --git a/buck2/prelude/android/prebuilt_native_library.bzl b/buck2/prelude/android/prebuilt_native_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/prebuilt_native_library.bzl
@@ -0,0 +1,39 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//android:android_providers.bzl",
+    "PrebuiltNativeLibraryDir",
+    "merge_android_packageable_info",
+)
+
+def prebuilt_native_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs.is_asset and ctx.attrs.has_wrap_script:
+        fail("Cannot use `is_asset` and `has_wrap_script` in the same rule")
+
+    prebuilt_native_library_dir = PrebuiltNativeLibraryDir(
+        raw_target = ctx.label.raw_target(),
+        dir = ctx.attrs.native_libs,
+        for_primary_apk = ctx.attrs.has_wrap_script,
+        is_asset = ctx.attrs.is_asset,
+    )
+    android_packageable_info = merge_android_packageable_info(
+        ctx.label,
+        ctx.actions,
+        ctx.attrs.deps,
+        prebuilt_native_library_dir = prebuilt_native_library_dir,
+    )
+    return [
+        # Buck1 copies the input directory and returns it as the output path. We don't
+        # copy; we could just return the input directory itself as the output path, but
+        # we're avoiding that (due to potential confusion from the output path being an
+        # input directory) until we have an actual need for prebuilt_native_library
+        # having an output path.
+        DefaultInfo(),
+        android_packageable_info,
+    ]
diff --git a/buck2/prelude/android/preprocess_java_classes.bzl b/buck2/prelude/android/preprocess_java_classes.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/preprocess_java_classes.bzl
@@ -0,0 +1,84 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_providers.bzl", "AndroidPreprocessedJavaClassesInfo")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//android:util.bzl", "EnhancementContext")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")
+load("@prelude//utils:expect.bzl", "expect")
+
+def get_preprocessed_java_classes(
+    enhance_ctx: EnhancementContext,
+    input_jars: dict[Artifact, TargetLabel],
+) -> (dict[Artifact, TargetLabel], AndroidPreprocessedJavaClassesInfo | None):
+    if not input_jars:
+        return {}, None
+
+    ctx = enhance_ctx.ctx
+
+    input_srcs = {}
+    output_jars_to_owners = {}
+    output_dir = ctx.actions.declare_output("preprocessed_java_classes/output_dir", has_content_based_path = False)
+    input_jars_to_owners = {}
+
+    for i, (input_jar, target_label) in enumerate(input_jars.items()):
+        expect(input_jar.extension == ".jar", "Expected {} to have extension .jar!".format(input_jar))
+        jar_name = "{}_{}".format(i, input_jar.basename)
+        input_srcs[jar_name] = input_jar
+        input_jars_to_owners[jar_name] = target_label
+        output_jar = output_dir.project(jar_name)
+        output_jars_to_owners[output_jar] = target_label
+
+    input_dir = ctx.actions.symlinked_dir("preprocessed_java_classes/input_dir", input_srcs, has_content_based_path = False)
+    input_jars_map = ctx.actions.write_json("preprocessed_java_classes/input_jars_map.json", input_jars_to_owners, has_content_based_path = False)
+    materialized_artifacts_dir = ctx.actions.declare_output("preprocessed_java_classes/materialized_artifacts", has_content_based_path = False)
+
+    android_toolchain = ctx.attrs._android_toolchain[AndroidToolchainInfo]
+    env = {
+        "ANDROID_BOOTCLASSPATH": cmd_args(
+            android_toolchain.android_bootclasspath + android_toolchain.android_optional_jars,
+            delimiter = get_path_separator_for_exec_os(ctx),
+        ),
+        "IN_JARS_DIR": cmd_args(input_dir),
+        "IN_JARS_MAP": cmd_args(input_jars_map),
+        "MATERIALIZED_ARTIFACTS_DIR": materialized_artifacts_dir.as_output(),
+        "OUT_JARS_DIR": output_dir.as_output(),
+        "PREPROCESS": ctx.attrs.preprocess_java_classes_bash,
+        "ZIP_SCRUBBER": ctx.attrs._java_toolchain[JavaToolchainInfo].zip_scrubber,
+    }
+
+    output_jars = output_jars_to_owners.keys()
+    output_jars_file = ctx.actions.write("preprocessed_java_classes/output_jars.txt", output_jars, has_content_based_path = False)
+
+    preprocess_cmd = [
+        "/usr/bin/env",
+        "bash",
+        "-c",
+        # Note: ZIP_SCRUBBER might expand to multiple words, so no quoting there.
+        'mkdir -p "$OUT_JARS_DIR" && mkdir -p "$MATERIALIZED_ARTIFACTS_DIR" && eval "$PREPROCESS" && $ZIP_SCRUBBER --paths-to-scrub "$@"',
+        "--",
+        output_jars_file,
+    ]
+
+    preprocess_cmd = cmd_args(
+        preprocess_cmd,
+        hidden = [output_jar.as_output() for output_jar in output_jars]
+        + [dep[DefaultInfo].default_outputs + dep[DefaultInfo].other_outputs for dep in ctx.attrs.preprocess_java_classes_deps],
+    )
+
+    ctx.actions.run(preprocess_cmd, env = env, category = "preprocess_java_classes")
+
+    enhance_ctx.debug_output("preprocess_java_classes_input_dir", input_dir)
+    enhance_ctx.debug_output("preprocess_java_classes_input_jars_map", input_jars_map)
+    enhance_ctx.debug_output("preprocess_java_classes_materialized_artifacts_dir", materialized_artifacts_dir)
+
+    return output_jars_to_owners, AndroidPreprocessedJavaClassesInfo(
+        input_dir = input_dir,
+        materialized_artifacts_dir = materialized_artifacts_dir,
+    )
diff --git a/buck2/prelude/android/r_dot_java.bzl b/buck2/prelude/android/r_dot_java.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/r_dot_java.bzl
@@ -0,0 +1,206 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_providers.bzl", "AndroidResourceInfo", "RDotJavaInfo")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//java:java_library.bzl", "compile_to_jar")
+load("@prelude//java:java_providers.bzl", "JavaLibraryInfo", "single_library_compiling_deps")
+load("@prelude//utils:argfile.bzl", "argfile")
+
+RDotJavaSourceCode = record(
+    r_dot_java_source_code_dir = Artifact,
+    r_dot_java_source_code_zipped = Artifact,
+    strings_source_code_dir = Artifact | None,
+    strings_source_code_zipped = Artifact | None,
+    ids_source_code_dir = Artifact | None,
+    ids_source_code_zipped = Artifact | None,
+)
+
+def get_dummy_r_dot_java(ctx: AnalysisContext, merge_android_resources_tool: RunInfo, android_resources: list[AndroidResourceInfo]) -> JavaLibraryInfo:
+    r_dot_java_source_code = _generate_r_dot_java_source_code(ctx, merge_android_resources_tool, android_resources, "dummy_r_dot_java")
+    return _compile_r_dot_java(
+        ctx,
+        r_dot_java_source_code.r_dot_java_source_code_zipped,
+        "dummy_r_dot_java",
+    ).library_info
+
+def generate_r_dot_javas(
+    ctx: AnalysisContext,
+    merge_android_resources_tool: RunInfo,
+    android_resources: list[AndroidResourceInfo],
+    banned_duplicate_resource_types: list[str],
+    uber_r_dot_txt_files: list[Artifact],
+    override_symbols_paths: list[Artifact],
+    duplicate_resources_allowlist: Artifact | None,
+    referenced_resources_lists: list[Artifact],
+    generate_strings_and_ids_separately: [bool, None] = True,
+    remove_classes: list[str] = [],
+) -> list[RDotJavaInfo]:
+    if not android_resources:
+        # d8 will fail if its input contains no classes. Rather than add empty input handling in multiple places,
+        # like buck1 we just generate a stub class if we have no resources.  This will be stripped from release
+        # builds and have minimal impact on debug builds.
+        return [
+            _compile_r_dot_java(
+                ctx,
+                ctx.attrs._android_toolchain[AndroidToolchainInfo].app_without_resources_stub,
+                "main_r_dot_java",
+            ),
+        ]
+
+    r_dot_java_source_code = _generate_r_dot_java_source_code(
+        ctx,
+        merge_android_resources_tool,
+        android_resources,
+        "r_dot_java",
+        generate_strings_and_ids_separately = generate_strings_and_ids_separately,
+        force_final_resources_ids = True,
+        banned_duplicate_resource_types = banned_duplicate_resource_types,
+        uber_r_dot_txt_files = uber_r_dot_txt_files,
+        override_symbols_paths = override_symbols_paths,
+        duplicate_resources_allowlist = duplicate_resources_allowlist,
+        referenced_resources_lists = referenced_resources_lists,
+    )
+
+    library_infos = [
+        _compile_r_dot_java(
+            ctx,
+            r_dot_java_source_code.r_dot_java_source_code_zipped,
+            "main_r_dot_java",
+            remove_classes = remove_classes,
+        ),
+    ]
+    if generate_strings_and_ids_separately:
+        library_infos += [
+            _compile_r_dot_java(
+                ctx,
+                r_dot_java_source_code.strings_source_code_zipped,
+                "strings_r_dot_java",
+                remove_classes = remove_classes + [".R$"],
+            ),
+            _compile_r_dot_java(
+                ctx,
+                r_dot_java_source_code.ids_source_code_zipped,
+                "ids_r_dot_java",
+                remove_classes = remove_classes + [".R$"],
+            ),
+        ]
+
+    return library_infos
+
+def _generate_r_dot_java_source_code(
+    ctx: AnalysisContext,
+    merge_android_resources_tool: RunInfo,
+    android_resources: list[AndroidResourceInfo],
+    identifier: str,
+    force_final_resources_ids = False,
+    generate_strings_and_ids_separately = False,
+    banned_duplicate_resource_types: list[str] = [],
+    uber_r_dot_txt_files: list[Artifact] = [],
+    override_symbols_paths: list[Artifact] = [],
+    duplicate_resources_allowlist: Artifact | None = None,
+    referenced_resources_lists: list[Artifact] = [],
+) -> RDotJavaSourceCode:
+    merge_resources_cmd = cmd_args(merge_android_resources_tool)
+
+    r_dot_txt_info = cmd_args()
+    deduped_android_resources = set(
+        [(android_resource.text_symbols, android_resource.r_dot_java_package, android_resource.raw_target) for android_resource in android_resources]
+    )
+    for text_symbols, r_dot_java_package, raw_target in deduped_android_resources:
+        r_dot_txt_info.add(cmd_args([text_symbols, r_dot_java_package, raw_target], delimiter = " "))
+
+    r_dot_txt_info_file = ctx.actions.write("r_dot_txt_info_file_for_{}.txt".format(identifier), r_dot_txt_info, has_content_based_path = True)
+    merge_resources_cmd.add(["--symbol-file-info", r_dot_txt_info_file])
+    merge_resources_cmd.add(
+        cmd_args(
+            hidden = [android_resource.r_dot_java_package for android_resource in android_resources]
+            + [android_resource.text_symbols for android_resource in android_resources],
+        )
+    )
+
+    output_dir = ctx.actions.declare_output("{}_source_code".format(identifier), dir = True, has_content_based_path = True)
+    merge_resources_cmd.add(["--output-dir", output_dir.as_output()])
+    output_dir_zipped = ctx.actions.declare_output("{}.src.zip".format(identifier), has_content_based_path = True)
+    merge_resources_cmd.add(["--output-dir-zipped", output_dir_zipped.as_output()])
+
+    if generate_strings_and_ids_separately:
+        strings_output_dir = ctx.actions.declare_output("strings_source_code", dir = True, has_content_based_path = True)
+        merge_resources_cmd.add(["--strings-output-dir", strings_output_dir.as_output()])
+        strings_output_dir_zipped = ctx.actions.declare_output("strings.src.zip", has_content_based_path = True)
+        merge_resources_cmd.add(["--strings-output-dir-zipped", strings_output_dir_zipped.as_output()])
+        ids_output_dir = ctx.actions.declare_output("ids_source_code", dir = True, has_content_based_path = True)
+        merge_resources_cmd.add(["--ids-output-dir", ids_output_dir.as_output()])
+        ids_output_dir_zipped = ctx.actions.declare_output("ids.src.zip", has_content_based_path = True)
+        merge_resources_cmd.add(["--ids-output-dir-zipped", ids_output_dir_zipped.as_output()])
+    else:
+        strings_output_dir = None
+        strings_output_dir_zipped = None
+        ids_output_dir = None
+        ids_output_dir_zipped = None
+
+    if force_final_resources_ids:
+        merge_resources_cmd.add("--force-final-resource-ids")
+
+    if len(banned_duplicate_resource_types) > 0:
+        banned_duplicate_resource_types_file = ctx.actions.write(
+            "banned_duplicate_resource_types_file", banned_duplicate_resource_types, has_content_based_path = True
+        )
+        merge_resources_cmd.add(["--banned-duplicate-resource-types", banned_duplicate_resource_types_file])
+
+    if len(uber_r_dot_txt_files) > 0:
+        uber_r_dot_txt_files_list = argfile(actions = ctx.actions, name = "uber_r_dot_txt_files_list", args = uber_r_dot_txt_files, has_content_based_path = True)
+        merge_resources_cmd.add(["--uber-r-dot-txt", uber_r_dot_txt_files_list])
+
+    if len(override_symbols_paths) > 0:
+        override_symbols_paths_list = argfile(actions = ctx.actions, name = "override_symbols_paths_list", args = override_symbols_paths, has_content_based_path = True)
+        merge_resources_cmd.add(["--override-symbols", override_symbols_paths_list])
+
+    if duplicate_resources_allowlist != None:
+        merge_resources_cmd.add(["--duplicate-resource-allowlist-path", duplicate_resources_allowlist])
+
+    if referenced_resources_lists:
+        referenced_resources_file = argfile(
+            actions = ctx.actions, name = "referenced_resources_lists", args = referenced_resources_lists, has_content_based_path = True
+        )
+        merge_resources_cmd.add(["--referenced-resources-lists", referenced_resources_file])
+
+    ctx.actions.run(merge_resources_cmd, category = "r_dot_java_merge_resources", identifier = identifier)
+
+    return RDotJavaSourceCode(
+        r_dot_java_source_code_dir = output_dir,
+        r_dot_java_source_code_zipped = output_dir_zipped,
+        strings_source_code_dir = strings_output_dir,
+        strings_source_code_zipped = strings_output_dir_zipped,
+        ids_source_code_dir = ids_output_dir,
+        ids_source_code_zipped = ids_output_dir_zipped,
+    )
+
+def _compile_r_dot_java(ctx: AnalysisContext, r_dot_java_source_code_zipped: Artifact, identifier: str, remove_classes: list[str] = []) -> RDotJavaInfo:
+    r_dot_java_out = ctx.actions.declare_output("{}.jar".format(identifier), has_content_based_path = True)
+    outputs = compile_to_jar(
+        ctx,
+        output = r_dot_java_out,
+        actions_identifier = identifier,
+        javac_tool = None,
+        srcs = [r_dot_java_source_code_zipped],
+        remove_classes = remove_classes,
+        required_for_source_only_abi = True,
+    )
+
+    library_output = outputs.classpath_entry
+
+    return RDotJavaInfo(
+        identifier = identifier,
+        library_info = JavaLibraryInfo(
+            compiling_deps = single_library_compiling_deps(ctx.actions, library_output),
+            library_output = library_output,
+            output_for_classpath_macro = library_output.full_library,
+        ),
+        source_zipped = r_dot_java_source_code_zipped,
+    )
diff --git a/buck2/prelude/android/readme.md b/buck2/prelude/android/readme.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/readme.md
@@ -0,0 +1,448 @@
+# Buck2 Android Prelude
+
+## 1. 🧭 Overview
+
+The Buck2 Android Prelude is a comprehensive build system for Android
+applications and libraries within Meta's Buck2 build system. It provides a
+complete set of build rules, toolchain integrations, and utilities for building
+Android APKs, AABs (Android App Bundles), libraries, and running tests.
+
+### Key Features
+
+- **Complete Android Build Pipeline**: From Java/Kotlin source code to signed
+  APKs and AABs
+- **Multi-DEX Support**: Advanced DEX file splitting and optimization with
+  multiple compression strategies
+- **Resource Processing**: AAPT2-based resource compilation and linking with
+  R.java generation
+- **Native Library Integration**: Support for native libraries across multiple
+  CPU architectures
+- **Exopackage Support**: Dynamic loading of DEX files, native libraries, and
+  resources for faster development
+- **Voltron Modularity**: Support for modular Android applications with dynamic
+  feature modules
+- **Testing Framework**: Comprehensive testing support including instrumentation
+  tests and Robolectric
+- **Toolchain Integration**: Deep integration with Android SDK tools, ProGuard,
+  and D8/R8
+
+### Technologies Used
+
+- **Language**: Starlark (Buck2's build language), Python (utility tools), Java
+  (toolchain components)
+- **Framework**: Buck2 build system with Android SDK integration
+- **Tools**: AAPT2, D8/R8, ProGuard, Android SDK tools, zipalign
+- **Infrastructure**: Remote execution support, caching, and distributed builds
+
+---
+
+## 2. 🧱 High-Level Architecture Diagram
+
+```mermaid
+graph TB
+    subgraph "Build Rules Layer"
+        APK[android_apk]
+        LIB[android_library]
+        RES[android_resource]
+        AAR[android_aar]
+        BUNDLE[android_bundle]
+        TEST[android_instrumentation_test]
+    end
+
+    subgraph "Processing Layer"
+        DEX[DEX Processing<br/>dex_rules.bzl]
+        RESOURCES[Resource Processing<br/>aapt2_link.bzl]
+        NATIVE[Native Library<br/>Processing]
+        MANIFEST[Manifest<br/>Processing]
+    end
+
+    subgraph "Provider Layer"
+        PROVIDERS[Android Providers<br/>android_providers.bzl]
+        JAVA_PROVIDERS[Java Providers]
+    end
+
+    subgraph "Toolchain Layer"
+        ANDROID_TC[Android Toolchain<br/>android_toolchain.bzl]
+        JAVA_TC[Java Toolchain]
+        DEX_TC[DEX Toolchain]
+    end
+
+    subgraph "Utility Tools"
+        PY_TOOLS[Python Tools<br/>tools/]
+        JAVA_TOOLS[Java Tools]
+    end
+
+    subgraph "External Dependencies"
+        ANDROID_SDK[Android SDK]
+        AAPT2[AAPT2]
+        D8[D8/R8]
+        PROGUARD[ProGuard]
+    end
+
+    APK --> DEX
+    APK --> RESOURCES
+    APK --> NATIVE
+    APK --> MANIFEST
+
+    LIB --> JAVA_PROVIDERS
+    RES --> RESOURCES
+
+    DEX --> PROVIDERS
+    RESOURCES --> PROVIDERS
+    NATIVE --> PROVIDERS
+
+    PROVIDERS --> ANDROID_TC
+    ANDROID_TC --> ANDROID_SDK
+    ANDROID_TC --> AAPT2
+    ANDROID_TC --> D8
+    ANDROID_TC --> PROGUARD
+
+    DEX --> PY_TOOLS
+    RESOURCES --> PY_TOOLS
+    NATIVE --> PY_TOOLS
+```
+
+### Component Explanations
+
+- **Build Rules Layer**: High-level build rules that developers use in their
+  BUCK files
+- **Processing Layer**: Core logic for transforming inputs (Java bytecode,
+  resources, native libs) into Android-specific formats
+- **Provider Layer**: Data structures that pass information between build rules
+  and processing steps
+- **Toolchain Layer**: Configuration and integration with external Android
+  development tools
+- **Utility Tools**: Python and Java utilities that perform specific processing
+  tasks
+- **External Dependencies**: Android SDK tools and third-party tools integrated
+  into the build process
+
+---
+
+## 3. 🔎 Component Breakdown
+
+### Component: Build Rules (`android.bzl`)
+
+**Purpose**: Defines the main Android build rules that developers use in BUCK
+files. Acts as the entry point and orchestrates the entire Android build
+process.
+
+**Key Elements**:
+
+- `android_apk_impl`: Builds signed APK files from Java code, resources, and
+  native libraries
+- `android_library_impl`: Compiles Java/Kotlin code into libraries with
+  Android-specific processing
+- `android_resource_impl`: Processes Android resources (layouts, strings,
+  drawables) using AAPT2
+- `android_aar_impl`: Creates Android Archive (AAR) files for library
+  distribution
+- `android_bundle_impl`: Generates Android App Bundles (AAB) for Play Store
+  distribution
+
+**Depends On**:
+
+- Internal: All processing modules, providers, toolchain configurations
+- External: Android SDK, Java toolchain, native toolchains
+
+### Component: Android Providers (`android_providers.bzl`)
+
+**Purpose**: Defines data structures and providers that carry information
+between different build rules and processing steps. Ensures type safety and
+structured data flow.
+
+**Key Elements**:
+
+- `AndroidApkInfo`: Contains APK artifact, manifest, and metadata
+- `AndroidResourceInfo`: Resource compilation outputs, R.java packages, AAPT2
+  artifacts
+- `AndroidBinaryNativeLibsInfo`: Native library directories, shared libraries,
+  exopackage info
+- `DexFilesInfo`: Primary and secondary DEX files with compression metadata
+- `AndroidPackageableInfo`: Transitive dependency information for packaging
+
+**Depends On**:
+
+- Internal: Java providers, transitive set utilities
+- External: Buck2 provider framework
+
+### Component: DEX Processing (`dex_rules.bzl`)
+
+**Purpose**: Handles conversion of Java bytecode to Android DEX format with
+sophisticated multi-DEX splitting, compression, and optimization strategies.
+
+**Key Elements**:
+
+- `get_multi_dex()`: Creates primary and secondary DEX files with weight-based
+  splitting
+- `merge_to_split_dex()`: Merges pre-dexed libraries into split DEX
+  configuration
+- `get_single_primary_dex()`: Simple single DEX file generation for smaller apps
+- DEX compression strategies: raw, jar, xz, xzs formats
+
+**Depends On**:
+
+- Internal: Android toolchain, Voltron module system, Java DEX utilities
+- External: D8/R8 compiler, Android runtime
+
+### Component: Resource Processing (`aapt2_link.bzl`, `android_resource.bzl`)
+
+**Purpose**: Processes Android resources using AAPT2, generates R.java files,
+handles resource merging and filtering.
+
+**Key Elements**:
+
+- `aapt2_link()`: Links compiled resources into APK-ready format
+- Resource compilation and optimization
+- R.java generation with package management
+- Asset processing and filtering
+
+**Depends On**:
+
+- Internal: Android toolchain, manifest processing
+- External: AAPT2, Android SDK
+
+### Component: Android Toolchain (`android_toolchain.bzl`)
+
+**Purpose**: Configures and provides access to all Android SDK tools and
+utilities needed for the build process.
+
+**Key Elements**:
+
+- `AndroidToolchainInfo`: Provider containing all tool references
+- Tool configurations: aapt2, d8_command, zipalign, adb, aidl
+- Build configuration: android_jar, proguard_jar, framework files
+- Utility tools: apk_builder, bundle_builder, duplicate_class_checker
+
+**Depends On**:
+
+- Internal: None (leaf component)
+- External: Android SDK, build tools, platform tools
+
+### Component: Python Utility Tools (`tools/`)
+
+**Purpose**: Provides specialized Python scripts for various Android build
+processing tasks that require complex logic or file manipulation.
+
+**Key Elements**:
+
+- `duplicate_class_checker.py`: Validates no duplicate classes in DEX files
+- `filter_dex.py`: Filters DEX files based on patterns and weight limits
+- `unpack_aar.py`: Extracts and processes AAR file contents
+- `combine_native_library_dirs.py`: Merges native library directories
+- `native_libs_as_assets_metadata.py`: Generates metadata for native libraries
+  stored as assets
+
+**Depends On**:
+
+- Internal: Build system file I/O
+- External: Python standard library, zipfile, json modules
+
+### Component: Testing Framework (`android_instrumentation_test.bzl`, `robolectric_test.bzl`)
+
+**Purpose**: Provides comprehensive testing capabilities for Android
+applications including on-device instrumentation tests and JVM-based Robolectric
+tests.
+
+**Key Elements**:
+
+- `android_instrumentation_test_impl`: On-device testing with APK installation
+- `robolectric_test_impl`: Fast JVM-based testing with Android framework
+  simulation
+- Test APK generation and signing
+- Test runner integration and result processing
+
+**Depends On**:
+
+- Internal: APK building, Android toolchain, Java testing framework
+- External: Android testing framework, Robolectric, ADB
+
+---
+
+## 4. 🔁 Data Flow & Call Flow Examples
+
+### Example Flow: APK Build Process
+
+**Description**: Complete end-to-end process of building a signed APK from
+source code, resources, and dependencies. This represents the most common and
+comprehensive workflow in the Android build system.
+
+**Sequence Diagram**:
+
+```mermaid
+sequenceDiagram
+    participant Dev as Developer
+    participant Buck as Buck2 Engine
+    participant APK as android_apk_impl
+    participant Binary as get_binary_info
+    participant DEX as DEX Processing
+    participant RES as Resource Processing
+    participant Tools as Android Tools
+    participant SDK as Android SDK
+
+    Dev->>Buck: buck build //app:my_app
+    Buck->>APK: Execute android_apk rule
+    APK->>Binary: get_binary_info(ctx)
+
+    par Parallel Processing
+        Binary->>DEX: Process Java bytecode to DEX
+        DEX->>Tools: Run D8 compiler
+        Tools->>SDK: Execute d8 command
+        SDK-->>Tools: DEX files + metadata
+        Tools-->>DEX: Compiled DEX artifacts
+        DEX-->>Binary: DexFilesInfo
+    and
+        Binary->>RES: Process Android resources
+        RES->>Tools: Run AAPT2 compile/link
+        Tools->>SDK: Execute aapt2 commands
+        SDK-->>Tools: Compiled resources APK
+        Tools-->>RES: Resource artifacts + R.java
+        RES-->>Binary: AndroidBinaryResourcesInfo
+    end
+
+    Binary-->>APK: Complete binary info
+    APK->>Tools: build_apk() with all artifacts
+    Tools->>SDK: Run apk_builder + zipalign
+    SDK-->>Tools: Signed APK
+    Tools-->>APK: Final APK artifact
+    APK-->>Buck: APK + install info
+    Buck-->>Dev: Build complete
+```
+
+### Example Flow: Multi-DEX Processing
+
+**Description**: Process of splitting Java bytecode into primary and secondary
+DEX files based on patterns and weight limits, with support for different
+compression strategies.
+
+**Sequence Diagram**:
+
+```mermaid
+sequenceDiagram
+    participant Build as Build Rule
+    participant MultiDex as get_multi_dex
+    participant Filter as filter_dex_class_names
+    participant D8 as D8 Tool
+    participant Compress as Compression Tool
+
+    Build->>MultiDex: Java library JARs + patterns
+    MultiDex->>Filter: Filter classes by primary_dex_patterns
+    Filter-->>MultiDex: Primary vs secondary class lists
+
+    par Primary DEX
+        MultiDex->>D8: Compile primary classes
+        D8-->>MultiDex: classes.dex
+    and Secondary DEX Processing
+        loop For each secondary DEX
+            MultiDex->>D8: Compile secondary classes batch
+            D8-->>MultiDex: classes2.dex, classes3.dex, etc.
+            MultiDex->>Compress: Apply compression (jar/xz/xzs)
+            Compress-->>MultiDex: Compressed secondary DEX
+        end
+    end
+
+    MultiDex-->>Build: DexFilesInfo with all DEX files
+```
+
+---
+
+## 5. 🗃️ Data Models (Entities)
+
+### Entity: AndroidApkInfo
+
+- **Provider**: AndroidApkInfo
+- **Fields**:
+  - `apk: Artifact` – The final signed APK file
+  - `manifest: Artifact` – Processed AndroidManifest.xml
+  - `materialized_artifacts: list[Artifact]` – All build artifacts for debugging
+  - `unstripped_shared_libraries: Artifact` – Debug symbols for native libraries
+
+- **Relations**:
+  - Used by installation and testing rules
+  - Contains references to all build artifacts
+
+- **Notes**: Primary output provider for android_apk and android_binary rules
+
+### Entity: AndroidResourceInfo
+
+- **Provider**: AndroidResourceInfo
+- **Fields**:
+  - `raw_target: TargetLabel` – Target that produced this resource
+  - `aapt2_compile_output: Artifact` – Compiled resource artifacts from AAPT2
+  - `res: Artifact` – Raw resource directory or mapping
+  - `assets: Artifact` – Asset files directory or mapping
+  - `r_dot_java_package: str` – Package name for R.java generation
+  - `text_symbols: Artifact` – Symbol definitions for resource linking
+  - `manifest_file: Artifact` – Associated AndroidManifest.xml
+
+- **Relations**:
+  - Aggregated by AndroidPackageableInfo
+  - Used by resource linking process
+  - Referenced by APK and AAR generation
+
+- **Notes**: Represents processed Android resources with AAPT2 compilation
+  outputs
+
+### Entity: DexFilesInfo
+
+- **Record**: DexFilesInfo
+- **Fields**:
+  - `primary_dex: Artifact` – Main classes.dex file
+  - `primary_dex_class_names: Artifact` – List of classes in primary DEX
+  - `root_module_secondary_dex_dirs: list[Artifact]` – Secondary DEX directories
+    for root module
+  - `non_root_module_secondary_dex_dirs: list[Artifact]` – Secondary DEX for
+    feature modules
+  - `secondary_dex_exopackage_info: ExopackageDexInfo` – Exopackage metadata for
+    dynamic loading
+  - `proguard_text_files_path: Artifact` – ProGuard mapping files
+
+- **Relations**:
+  - Used by APK building process
+  - Contains exopackage information for dynamic loading
+  - References ProGuard optimization outputs
+
+- **Notes**: Central data structure for DEX file management with multi-DEX and
+  exopackage support
+
+### Entity: AndroidPackageableInfo
+
+- **Provider**: AndroidPackageableInfo
+- **Fields**:
+  - `target_label: TargetLabel` – Target producing this info
+  - `build_config_infos: AndroidBuildConfigInfoTSet` – Transitive build
+    configurations
+  - `deps: AndroidDepsTSet` – Transitive dependency information
+  - `manifests: ManifestTSet` – Transitive manifest files
+  - `resource_infos: ResourceInfoTSet` – Transitive resource information
+  - `prebuilt_native_library_dirs: PrebuiltNativeLibraryDirTSet` – Transitive
+    native libraries
+
+- **Relations**:
+  - Aggregates information from all transitive dependencies
+  - Used by binary rules for packaging decisions
+  - Contains transitive sets for efficient dependency management
+
+- **Notes**: Core provider for dependency aggregation using Buck2's transitive
+  set system
+
+### Entity: AndroidToolchainInfo
+
+- **Provider**: AndroidToolchainInfo
+- **Fields**:
+  - `aapt2: RunInfo` – AAPT2 resource compiler tool
+  - `d8_command: RunInfo` – D8 DEX compiler
+  - `android_jar: Artifact` – Android SDK JAR file
+  - `apk_builder: RunInfo` – APK assembly and signing tool
+  - `zipalign: RunInfo` – APK optimization tool
+  - `proguard_jar: Artifact` – ProGuard obfuscation tool
+  - `duplicate_class_checker: RunInfo` – Validation tool for duplicate classes
+  - `installer: RunInfo` – APK installation tool
+
+- **Relations**:
+  - Used by all Android build rules
+  - Provides access to external Android SDK tools
+  - Configured by toolchain setup rules
+
+- **Notes**: Central configuration point for all Android development tools and
+  SDK integration
diff --git a/buck2/prelude/android/relinker_linker_outputs.bzl b/buck2/prelude/android/relinker_linker_outputs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/relinker_linker_outputs.bzl
@@ -0,0 +1,115 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Extra relinker outputs support (e.g., LLVM stats).
+
+Reads from ctx.attrs.extra_relinker_outputs attribute (not buck config directly).
+Buck config is read at macro level and translated to attribute value.
+"""
+
+load("@prelude//linking:link_info.bzl", "ExtraLinkerOutputs")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+
+def _llvm_stats_outputs_factory(output_path: str) -> typing.Callable:
+    """Factory for relinker LLVM stats outputs."""
+
+    def factory(ctx: AnalysisContext) -> ExtraLinkerOutputs:
+        stats_file = ctx.actions.declare_output(output_path + ".stats", has_content_based_path = False)
+        return ExtraLinkerOutputs(
+            artifacts = {"llvm-stats": stats_file},
+            providers = {"llvm-stats": [DefaultInfo(default_output = stats_file)]},
+        )
+
+    return factory
+
+def _llvm_stats_flags_factory() -> typing.Callable:
+    """Factory for relinker LLVM stats linker flags."""
+
+    def factory(_ctx: AnalysisContext, outputs: dict[str, Artifact]) -> list[ArgLike]:
+        return [
+            cmd_args(outputs["llvm-stats"].as_output(), format = "-Wl,-plugin-opt=stats-file={}"),
+        ]
+
+    return factory
+
+def _preinline_ir_outputs_factory(output_path: str) -> typing.Callable:
+    """Factory for the relinker pre-inline IR (.ll) output."""
+
+    def factory(ctx: AnalysisContext) -> ExtraLinkerOutputs:
+        ir_file = ctx.actions.declare_output(output_path + ".preinline.ll", has_content_based_path = False)
+        return ExtraLinkerOutputs(
+            artifacts = {"preinline-ir": ir_file},
+            providers = {"preinline-ir": [DefaultInfo(default_output = ir_file)]},
+        )
+
+    return factory
+
+def _preinline_ir_flags_factory() -> typing.Callable:
+    """Factory for the relinker pre-inline IR linker flags.
+
+    Threads the gator `-full-lto-postlink-preinline-ir-dump=<file>` mllvm option
+    into the LTO backend. `.as_output()` is what registers the linker-written
+    file as a tracked, materializable buck output (a bare `-Wl,-mllvm` string
+    would be discarded by RE)."""
+
+    def factory(_ctx: AnalysisContext, outputs: dict[str, Artifact]) -> list[ArgLike]:
+        return [
+            cmd_args(
+                outputs["preinline-ir"].as_output(),
+                format = "-Wl,-mllvm,-full-lto-postlink-preinline-ir-dump={}",
+            ),
+        ]
+
+    return factory
+
+def _get_extra_relinker_output_types(ctx: AnalysisContext) -> list[str]:
+    """Get list of enabled extra relinker output types from attribute."""
+    return getattr(ctx.attrs, "extra_relinker_outputs", [])
+
+def get_extra_relinker_args(ctx: AnalysisContext, output_path: str, soname: str = "") -> dict[str, typing.Any]:
+    """Get extra linker outputs factory dict for all enabled relinker outputs.
+
+    `soname` scopes the (multi-GB) pre-inline IR dump: when `preinline_ir_sonames`
+    is set, only libraries in that allowlist emit the dump output+flag, so a whole
+    -app build does not dump every library. An empty allowlist keeps legacy
+    behavior (every relinked library dumps)."""
+    output_types = _get_extra_relinker_output_types(ctx)
+    allowlist = getattr(ctx.attrs, "preinline_ir_sonames", [])
+    if allowlist and "preinline-ir" in output_types and soname not in allowlist:
+        output_types = [t for t in output_types if t != "preinline-ir"]
+    if not output_types:
+        return {}
+
+    def combined_outputs_factory(ctx: AnalysisContext) -> ExtraLinkerOutputs:
+        artifacts = {}
+        providers = {}
+        for output_type in output_types:
+            if output_type == "llvm-stats":
+                result = _llvm_stats_outputs_factory(output_path)(ctx)
+                artifacts |= result.artifacts
+                providers |= result.providers
+            elif output_type == "preinline-ir":
+                result = _preinline_ir_outputs_factory(output_path)(ctx)
+                artifacts |= result.artifacts
+                providers |= result.providers
+        return ExtraLinkerOutputs(artifacts = artifacts, providers = providers)
+
+    def combined_flags_factory(ctx: AnalysisContext, outputs: dict[str, Artifact]) -> list[ArgLike]:
+        flags = []
+        for output_type in output_types:
+            if output_type == "llvm-stats":
+                flags += _llvm_stats_flags_factory()(ctx, outputs)
+            elif output_type == "preinline-ir":
+                flags += _preinline_ir_flags_factory()(ctx, outputs)
+        return flags
+
+    return {
+        "extra_linker_outputs_factory": combined_outputs_factory,
+        "extra_linker_outputs_flags_factory": combined_flags_factory,
+    }
diff --git a/buck2/prelude/android/robolectric_test.bzl b/buck2/prelude/android/robolectric_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/robolectric_test.bzl
@@ -0,0 +1,158 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_binary_resources_rules.bzl", "get_android_binary_resources_info")
+load("@prelude//android:android_library.bzl", "android_target_stats", "build_android_library", "optional_jars")
+load("@prelude//android:android_providers.bzl", "merge_android_packageable_info")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//java:java_providers.bzl", "JavaLibraryInfo")
+load("@prelude//java:java_test.bzl", "build_junit_test")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+load("@prelude//utils:expect.bzl", "expect")
+
+def _target_build_file_path(target):
+    cell = "" if target.cell in ["", "fbsource"] else target.cell + "/"
+    package = target.package + "/" if target.package else ""
+    return cell + package + "BUCK"
+
+def robolectric_test_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs._build_only_native_code:
+        return [DefaultInfo()]
+
+    extra_cmds = []
+
+    # Force robolectric to only use local dependency resolution.
+    extra_cmds.append("-Drobolectric.offline=true")
+    if ctx.attrs.robolectric_runtime_dependency:
+        runtime_dependencies_dir = ctx.attrs.robolectric_runtime_dependency
+    elif ctx.attrs.robolectric_runtime_dependencies:
+        runtime_dependencies_dir = ctx.actions.symlinked_dir(
+            "runtime_dependencies",
+            {runtime_dep.basename: runtime_dep for runtime_dep in ctx.attrs.robolectric_runtime_dependencies},
+            has_content_based_path = False,
+        )
+    else:
+        runtime_dependencies_dir = None
+
+    if runtime_dependencies_dir:
+        extra_cmds.append(cmd_args(runtime_dependencies_dir, format = "-Drobolectric.dependency.dir={}"))
+
+    all_packaging_deps = ctx.attrs.deps + ctx.attrs.exported_deps + ctx.attrs.runtime_deps
+    android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, all_packaging_deps)
+    resources_info = get_android_binary_resources_info(
+        ctx,
+        all_packaging_deps,
+        android_packageable_info,
+        java_packaging_deps = [],  # Only used for third-party jar resources, which we don't care about here.
+        use_proto_format = False,
+        referenced_resources_lists = [],
+        generate_strings_and_ids_separately = False,
+        aapt2_preferred_density = ctx.attrs.preferred_density_for_binary_resources,
+        manifest_entries = ctx.attrs.manifest_entries,
+    )
+
+    resource_source_map = None
+    resource_source_map_jar = ctx.attrs.env.get("ROBOLECTRIC_RESOURCE_SOURCE_MAP_JAR")
+    if resource_source_map_jar:
+        resource_infos = [resource for resource in resources_info.unfiltered_resource_infos if resource.res != None]
+        resource_dirs = [cmd_args([resource.res, _target_build_file_path(resource.raw_target)], delimiter = "\t") for resource in resource_infos]
+        resource_dirs_file = ctx.actions.write("resource_source_map_resource_dirs", resource_dirs, has_content_based_path = False)
+        asset_infos = [
+            (asset, _target_build_file_path(resource.raw_target)) for resource in resources_info.unfiltered_resource_infos for asset in resource.assets
+        ]
+        asset_dirs = [cmd_args([asset, owner_build_file], delimiter = "\t") for asset, owner_build_file in asset_infos]
+        asset_dirs_file = ctx.actions.write("resource_source_map_asset_dirs", asset_dirs, has_content_based_path = False)
+        resource_source_map = ctx.actions.declare_output("resource_source_map.tsv", has_content_based_path = False)
+        resource_source_map_cmd = cmd_args([
+            ctx.attrs._java_toolchain[JavaToolchainInfo].java[RunInfo],
+            "-jar",
+            resource_source_map_jar,
+            "--resource-dirs",
+            resource_dirs_file,
+            "--asset-dirs",
+            asset_dirs_file,
+            "--output",
+            resource_source_map.as_output(),
+        ])
+        resource_source_map_cmd.add(cmd_args(hidden = [resource.res for resource in resource_infos] + [asset for asset, _ in asset_infos]))
+        ctx.actions.run(resource_source_map_cmd, category = "robolectric_resource_source_map", allow_cache_upload = True)
+
+    test_config_properties_file = ctx.actions.write(
+        "test_config.properties",
+        [
+            # Replace \ with \\ for Windows compatibility
+            cmd_args(["android_resource_apk", resources_info.primary_resources_apk], delimiter = "=", replace_regex = ("\\\\\\b", "\\\\")),
+            cmd_args(["android_merged_manifest", resources_info.manifest], delimiter = "=", replace_regex = ("\\\\\\b", "\\\\")),
+        ]
+        + (
+            [cmd_args(["robolectric_resource_source_map", resource_source_map], delimiter = "=", replace_regex = ("\\\\\\b", "\\\\"))]
+            if resource_source_map
+            else []
+        ),
+        has_content_based_path = False,
+    )
+
+    # Robolectric looks for a file named /com/android/tools/test_config.properties on the classpath
+    test_config_symlinked_dir = ctx.actions.symlinked_dir(
+        "test_config_symlinked_dir", {"com/android/tools/test_config.properties": test_config_properties_file}, has_content_based_path = False
+    )
+    test_config_properties_jar = ctx.actions.declare_output("test_config_properties.jar", has_content_based_path = False)
+    jar_cmd = cmd_args([
+        ctx.attrs._java_toolchain[JavaToolchainInfo].jar,
+        "-cfM",  # -c: create new archive, -f: specify the file name, -M: do not create a manifest
+        test_config_properties_jar.as_output(),
+        "-C",
+        test_config_symlinked_dir,
+        ".",
+    ])
+    ctx.actions.run(jar_cmd, category = "test_config_properties_jar_cmd")
+    extra_cmds.append(cmd_args(hidden = [resources_info.primary_resources_apk, resources_info.manifest] + ([resource_source_map] if resource_source_map else [])))
+
+    r_dot_javas = [r_dot_java.library_info for r_dot_java in resources_info.r_dot_java_infos if r_dot_java.library_info.library_output]
+    expect(len(r_dot_javas) <= 1, "android_library only works with single R.java")
+
+    target_stats_providers, extra_sub_targets = android_target_stats(ctx)
+    if resource_source_map:
+        extra_sub_targets["resource_source_map"] = [DefaultInfo(default_output = resource_source_map)]
+    if r_dot_javas:
+        r_dot_java = r_dot_javas[0]
+        extra_sub_targets["r_dot_java"] = [DefaultInfo(default_output = r_dot_java.library_output.full_library)]
+    else:
+        r_dot_java = None
+    java_providers, _ = build_android_library(ctx, r_dot_java = r_dot_java, extra_sub_targets = extra_sub_targets)
+
+    extra_classpath_entries = [test_config_properties_jar] + ctx.attrs._android_toolchain[AndroidToolchainInfo].android_bootclasspath + optional_jars(ctx)
+    extra_classpath_entries.extend([r_dot_java.library_output.full_library for r_dot_java in r_dot_javas])
+    external_runner_test_info = build_junit_test(
+        ctx,
+        java_providers.java_library_info,
+        java_providers.java_packaging_info,
+        java_providers.class_to_src_map,
+        extra_cmds = extra_cmds,
+        extra_classpath_entries = extra_classpath_entries,
+    )
+
+    providers = inject_test_run_info(ctx, external_runner_test_info) + [
+        java_providers.java_library_intellij_info,
+        java_providers.java_packaging_info,
+        java_providers.template_placeholder_info,
+        java_providers.default_info,
+        java_providers.class_to_src_map,
+        java_providers.java_global_code_info,
+    ]
+
+    java_library_without_compiling_deps = JavaLibraryInfo(
+        compiling_deps = None,
+        library_output = java_providers.java_library_info.library_output,
+        output_for_classpath_macro = java_providers.java_library_info.output_for_classpath_macro,
+    )
+    providers.append(java_library_without_compiling_deps)
+    providers.extend(target_stats_providers)
+
+    return providers
diff --git a/buck2/prelude/android/tools/BUCK b/buck2/prelude/android/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/BUCK
@@ -0,0 +1,133 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native  # Avoid warnings and auto-formatters
+
+prelude.python_bootstrap_binary(
+    name = "duplicate_class_checker",
+    main = "duplicate_class_checker.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//java/tools:utils_lib",
+    ],
+)
+
+prelude.python_bootstrap_binary(
+    name = "consolidate_class_names",
+    main = "consolidate_class_names.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "unpack_aar",
+    main = "unpack_aar.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//java/tools:utils_lib",
+    ],
+)
+
+prelude.python_bootstrap_binary(
+    name = "filter_dex",
+    main = "filter_dex.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_library(
+    name = "filter_dex_lib",
+    srcs = ["filter_dex.py"],
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "sort_pre_dexed_files",
+    main = "sort_pre_dexed_files.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_library(
+    name = "sort_pre_dexed_files_lib",
+    srcs = ["sort_pre_dexed_files.py"],
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "combine_native_library_dirs",
+    main = "combine_native_library_dirs.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "filter_prebuilt_native_library_dir",
+    main = "filter_prebuilt_native_library_dir.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "native_libs_as_assets_metadata",
+    main = "native_libs_as_assets_metadata.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "compute_merge_sequence",
+    main = "merge_sequence.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "filter_extra_resources",
+    main = "filter_extra_resources.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//java/tools:utils_lib",
+    ],
+)
+
+prelude.zip_file(
+    name = "app_without_resources_stub",
+    srcs = ["com/facebook/buck_generated/AppWithoutResourcesStub.java"],
+    out = "app_without_resources_stub.src.zip",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "create_jdk_system_image",
+    main = "create_jdk_system_image.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "combine_apk_with_relinked_libs",
+    main = "combine_apk_with_relinked_libs.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_library(
+    name = "combine_apk_with_relinked_libs_lib",
+    srcs = ["combine_apk_with_relinked_libs.py"],
+    visibility = ["PUBLIC"],
+)
+
+# Type checking target for Python tool scripts
+prelude.python_library(
+    name = "scripts-typing",
+    srcs = [
+        "combine_apk_with_relinked_libs.py",
+        "combine_native_library_dirs.py",
+        "consolidate_class_names.py",
+        "create_jdk_system_image.py",
+        "duplicate_class_checker.py",
+        "filter_dex.py",
+        "filter_extra_resources.py",
+        "filter_prebuilt_native_library_dir.py",
+        "merge_sequence.py",
+        "native_libs_as_assets_metadata.py",
+        "sort_pre_dexed_files.py",
+        "unpack_aar.py",
+    ],
+    typing = True,
+)
diff --git a/buck2/prelude/android/tools/com/facebook/buck_generated/AppWithoutResourcesStub.java b/buck2/prelude/android/tools/com/facebook/buck_generated/AppWithoutResourcesStub.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/com/facebook/buck_generated/AppWithoutResourcesStub.java
@@ -0,0 +1,13 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck_generated;
+
+final class AppWithoutResourcesStub {}
diff --git a/buck2/prelude/android/tools/combine_apk_with_relinked_libs.py b/buck2/prelude/android/tools/combine_apk_with_relinked_libs.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/combine_apk_with_relinked_libs.py
@@ -0,0 +1,192 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Combine an APK/AAB with relinked native libraries.
+
+Replaces the un-relinked .so files in the input APK/AAB with their
+relinked counterparts. A JSON mapping file specifies which libraries
+to replace, keyed by <abi>/<soname> (e.g. "arm64-v8a/libfoo.so").
+
+The mapping is produced by the build system and consumed here, so the
+script doesn't need to discover or infer what to replace.
+
+Handles .so files at all possible packaging locations:
+  - lib/<abi>/<soname>                        (standard)
+  - assets/lib/<abi>/<soname>                 (asset libraries)
+  - assets/<module>/lib/<abi>/<soname>        (Voltron module libs)
+  - assets/<module>/assets/<abi>/<soname>     (Voltron module assets)
+  - Inside nested ZIP/JAR files               (module containers)
+
+Usage:
+    combine_apk_with_relinked_libs.py \
+        --input input.apk \
+        --relinked-libs-dir /path/to/relinked_libs \
+        --mapping /path/to/mapping.json \
+        --output output.apk
+"""
+
+import argparse
+import io
+import json
+import os
+import shutil
+import zipfile
+
+
+def _build_relinked_lookup(
+    mapping: list[str],
+    relinked_libs_dir: str,
+) -> dict[str, str]:
+    """Build a lookup dict from the mapping list.
+
+    Args:
+        mapping: List of "<abi>/<soname>" strings from the build system.
+        relinked_libs_dir: Base directory containing the relinked .so files.
+
+    Returns:
+        Dict mapping "<abi>/<soname>" to the absolute filesystem path.
+    """
+    lookup = {}
+    for abi_soname in mapping:
+        path = os.path.join(relinked_libs_dir, abi_soname)
+        if not os.path.isfile(path):
+            raise RuntimeError(
+                "Relinked library not found: {} (expected at {})".format(
+                    abi_soname, path
+                )
+            )
+        lookup[abi_soname] = path
+    return lookup
+
+
+def _find_matching_key(
+    zip_entry: str,
+    relinked_lookup: dict[str, str],
+) -> str | None:
+    """Find the mapping key that matches a ZIP entry path.
+
+    Keys are always <abi>/<soname> (exactly two path components), so we
+    extract the last two components of the zip entry and do a direct
+    dict lookup — O(1) per entry instead of O(M) linear scan.
+
+    Note: suffix matching is intentional — the same <abi>/<soname> may appear
+    at multiple packaging locations (lib/, assets/lib/, assets/<module>/lib/,
+    etc.) and all occurrences should be replaced with the same relinked binary.
+    """
+    parts = zip_entry.rsplit("/", 2)
+    if len(parts) >= 2:
+        candidate = parts[-2] + "/" + parts[-1]
+        if candidate in relinked_lookup:
+            return candidate
+    return None
+
+
+def _maybe_rebuild_inner_zip(
+    inner_bytes: bytes,
+    relinked_lookup: dict[str, str],
+) -> tuple[bytes, set[str]] | None:
+    """Rebuild a nested ZIP, replacing any .so entries with relinked versions.
+
+    Returns a tuple of (rebuilt bytes, set of replaced keys) if any
+    replacements were made, or None if the inner ZIP has no matching
+    entries (or is not a valid ZIP). This avoids parsing the same ZIP
+    twice (once to check, once to rebuild).
+    """
+    try:
+        buf = io.BytesIO(inner_bytes)
+        with zipfile.ZipFile(buf, "r") as zin:
+            has_match = any(
+                _find_matching_key(info.filename, relinked_lookup)
+                for info in zin.infolist()
+            )
+            if not has_match:
+                return None
+            inner_replaced: set[str] = set()
+            out = io.BytesIO()
+            with zipfile.ZipFile(out, "w") as zout:
+                for info in zin.infolist():
+                    key = _find_matching_key(info.filename, relinked_lookup)
+                    if key is not None:
+                        with open(relinked_lookup[key], "rb") as f:
+                            zout.writestr(info, f.read())
+                        inner_replaced.add(key)
+                    else:
+                        zout.writestr(info, zin.read(info.filename))
+            return out.getvalue(), inner_replaced
+    except zipfile.BadZipFile:
+        return None
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Replace .so files in an APK/AAB with relinked versions."
+    )
+    parser.add_argument(
+        "--input",
+        required=True,
+        help="Path to the input APK/AAB",
+    )
+    parser.add_argument(
+        "--relinked-libs-dir",
+        required=True,
+        help="Path to directory containing relinked .so files (structure: <abi>/<soname>)",
+    )
+    parser.add_argument(
+        "--mapping",
+        required=True,
+        help="Path to JSON file listing <abi>/<soname> entries to replace",
+    )
+    parser.add_argument(
+        "--output",
+        required=True,
+        help="Path to write the combined output APK/AAB",
+    )
+    args = parser.parse_args()
+
+    with open(args.mapping) as f:
+        mapping = json.load(f)
+
+    relinked_lookup = _build_relinked_lookup(mapping, args.relinked_libs_dir)
+
+    if not relinked_lookup:
+        shutil.copy2(args.input, args.output)
+        return
+
+    replaced: set[str] = set()
+    with zipfile.ZipFile(args.input, "r") as zin:
+        with zipfile.ZipFile(args.output, "w") as zout:
+            for info in zin.infolist():
+                key = _find_matching_key(info.filename, relinked_lookup)
+                if key is not None:
+                    with open(relinked_lookup[key], "rb") as f:
+                        data = f.read()
+                    zout.writestr(info, data)
+                    replaced.add(key)
+                elif info.filename.endswith((".jar", ".zip")):
+                    inner_bytes = zin.read(info.filename)
+                    result = _maybe_rebuild_inner_zip(inner_bytes, relinked_lookup)
+                    if result is not None:
+                        rebuilt, inner_replaced = result
+                        zout.writestr(info, rebuilt)
+                        replaced.update(inner_replaced)
+                    else:
+                        zout.writestr(info, inner_bytes)
+                else:
+                    zout.writestr(info, zin.read(info.filename))
+
+    not_replaced = set(relinked_lookup.keys()) - replaced
+    if not_replaced:
+        raise RuntimeError(
+            "Relinked libraries not found in input: {}".format(
+                ", ".join(sorted(not_replaced))
+            )
+        )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/android/tools/combine_native_library_dirs.py b/buck2/prelude/android/tools/combine_native_library_dirs.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/combine_native_library_dirs.py
@@ -0,0 +1,97 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import hashlib
+import os
+from pathlib import Path
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Combine the native libraries in different directories into a single symlink"
+    )
+    parser.add_argument(
+        "--library-dirs",
+        type=Path,
+        nargs="+",
+        help="Paths to the dirs that should be combined",
+        required=True,
+    )
+    parser.add_argument(
+        "--subdir",
+        type=Path,
+        help="The subdirectory inside the dirs to combine",
+    )
+    parser.add_argument(
+        "--output-dir",
+        type=Path,
+        required=True,
+    )
+    parser.add_argument(
+        "--metadata-file",
+        type=Path,
+        required=False,
+    )
+    parser.add_argument(
+        "--pick-first",
+        type=str,
+        nargs="+",
+        help="Library names to pick the first if duplicated",
+    )
+    args = parser.parse_args()
+
+    metadata_lines = []
+
+    args.output_dir.mkdir(parents=True)
+    for library_dir in args.library_dirs:
+        if args.subdir:
+            library_dir = library_dir / args.subdir
+        all_libs = library_dir.glob("**/*.s[o|h]")
+        for lib in all_libs:
+            relative_path = lib.relative_to(library_dir)
+            output_path = args.output_dir / relative_path
+
+            if output_path.exists():
+                if (
+                    args.pick_first
+                    and os.path.basename(relative_path) in args.pick_first
+                ):
+                    continue
+                else:
+                    raise AssertionError(
+                        "Duplicate library name: {}! Source1: {}, source2: {}".format(
+                            output_path.name,
+                            os.path.realpath(output_path),
+                            lib,
+                        )
+                    )
+
+            output_path.parent.mkdir(exist_ok=True, parents=True)
+            relative_path_to_lib = os.path.relpath(
+                os.path.realpath(lib),
+                start=os.path.realpath(os.path.dirname(output_path)),
+            )
+            output_path.symlink_to(relative_path_to_lib)
+
+            if args.metadata_file:
+                with open(lib, "rb") as f:
+                    metadata_lines.append(
+                        "{} {}".format(
+                            relative_path, hashlib.sha1(f.read()).hexdigest()
+                        )
+                    )
+
+    if args.metadata_file:
+        with open(args.metadata_file, "w") as f:
+            f.write("\n".join(metadata_lines))
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/android/tools/consolidate_class_names.py b/buck2/prelude/android/tools/consolidate_class_names.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/consolidate_class_names.py
@@ -0,0 +1,103 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Consolidates multiple class name files into a single JSON file.
+
+This tool reads a mapping of target names to class name file paths,
+reads each file, and outputs a consolidated JSON containing all
+class names directly. This reduces the number of file reads required
+by downstream tools.
+
+Additionally, this tool builds a reverse map (class -> target) to detect
+duplicate classes within the batch. If duplicates are found, it fails fast
+with an error message. This allows earlier detection of duplicate classes
+compared to waiting for the global duplicate_class_checker.py to run.
+
+Input format (JSON):
+{
+    "target_name1": "path/to/class_names1.txt",
+    "target_name2": "path/to/class_names2.txt",
+    ...
+}
+
+Output format (JSON):
+{
+    "target_name1": ["com/example/Class1", "com/example/Class2"],
+    "target_name2": ["com/other/Class3"],
+    ...
+}
+"""
+
+import argparse
+import json
+from pathlib import Path
+from typing import Dict, List
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Consolidate multiple class name files into a single JSON file."
+    )
+    parser.add_argument(
+        "--input-mapping-file",
+        type=Path,
+        required=True,
+        help="JSON file mapping target names to class name file paths.",
+    )
+    parser.add_argument(
+        "--output-file",
+        type=Path,
+        required=True,
+        help="Output JSON file with consolidated class names.",
+    )
+    args = parser.parse_args()
+
+    # Read the input mapping
+    with open(args.input_mapping_file) as f:
+        target_to_file_map: Dict[str, str] = json.load(f)
+
+    # Read each class names file and build consolidated mapping
+    # Also build reverse map to detect duplicates within this batch
+    consolidated: Dict[str, List[str]] = {}
+    class_to_target: Dict[str, str] = {}
+    duplicates: Dict[str, List[str]] = {}
+
+    for target_name, file_path in target_to_file_map.items():
+        with open(file_path) as f:
+            # Read class names, stripping whitespace
+            class_names = [line.strip() for line in f if line.strip()]
+            consolidated[target_name] = class_names
+
+            # Check for duplicates within this batch
+            # Skip inner classes and module-info (same filtering as duplicate_class_checker.py)
+            for class_name in class_names:
+                if "$" in class_name or "module-info" in class_name:
+                    continue
+                if class_name in class_to_target:
+                    # Found a duplicate
+                    if class_name not in duplicates:
+                        duplicates[class_name] = [class_to_target[class_name]]
+                    duplicates[class_name].append(target_name)
+                else:
+                    class_to_target[class_name] = target_name
+
+    # Fail fast if duplicates found within this batch
+    if duplicates:
+        error_lines = ["Duplicate class names found within batch:"]
+        for class_name, targets in sorted(duplicates.items()):
+            error_lines.append(f"  {class_name} exists in: {', '.join(targets)}")
+        raise SystemExit("\n".join(error_lines))
+
+    # Write consolidated output
+    with open(args.output_file, "w") as f:
+        json.dump(consolidated, f)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/android/tools/create_jdk_system_image.py b/buck2/prelude/android/tools/create_jdk_system_image.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/create_jdk_system_image.py
@@ -0,0 +1,302 @@
+#!/usr/bin/python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Converts core-for-system-modules.jar from Android SDK release to a Java system image
+given to the --system flag for when compiling for Java target 9+.
+
+This entire script is translated from Gradle:
+https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:build-system/gradle-core/src/main/java/com/android/build/gradle/internal/dependency/JdkImageTransformDelegate.kt
+
+See also the equivalent feature in Bazel Android build rules:
+https://github.com/bazelbuild/rules_android/commit/20c8e5bef957a2334346490934bf3dc54942457c
+
+New comments are marked with "META:"
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import zipfile
+from pathlib import Path
+from typing import List
+
+
+# META: Translation of ProcessBuilder. Note some tools print error to stdout so print both
+# stdout+stderr on failure.
+def run_subprocess(args: List[str]) -> bytes:
+    try:
+        return subprocess.check_output(args, stderr=subprocess.PIPE)
+    except subprocess.CalledProcessError as e:
+        print(f"Failed to run {args}: exit code={e.returncode}", file=sys.stderr)
+        if e.stdout:
+            print("stdout:", file=sys.stderr)
+            print(e.stdout.decode("utf-8"), file=sys.stderr)
+        if e.stderr:
+            print("stderr:", file=sys.stderr)
+            print(e.stderr.decode("utf-8"), file=sys.stderr)
+        sys.exit(1)
+
+
+class JdkImageTransformDelegate:
+    def __init__(
+        self,
+        system_modules_jar: Path,
+        work_dir: Path,
+        out_dir: Path,
+        jdk_tools: JdkTools,
+    ):
+        self.system_modules_jar = system_modules_jar
+        self.work_dir = work_dir
+        self.out_dir = out_dir
+        self.jdk_tools = jdk_tools
+
+    def run(self):
+        """
+        Links a JDK Image from [system_modules_jar] in [out_dir], using [work_dir]
+        for the output of any intermediate operations. This is done via the "jlink" tool
+        as exposed by [jdk_tools].
+        """
+
+        # jlink takes a directory of JMOD files as inputs
+        jmod_file = self.make_jmod_file()
+        jmod_dir = jmod_file.parent
+
+        self.jdk_tools.link_jmods_into_jdk_image(jmod_dir, "java.base", self.out_dir)
+
+        copy_jrt_fs_jar(self.out_dir, self.jdk_tools)
+
+    def make_module_descriptor_java(self) -> Path:
+        """
+        Creates a "module-info.java" file describing the contents of system_modules_jar
+        """
+        module_info_java_content = generate_module_descriptor(
+            "java.base", [self.system_modules_jar]
+        )
+        module_info_java = self.work_dir / "module-info.java"
+        with open(module_info_java, "w") as f:
+            f.write(module_info_java_content)
+
+        return module_info_java
+
+    def make_module_info_class(self) -> Path:
+        """
+        Creates and compiles a "module-info.class" file describing the contents of system_modules_jar
+        """
+        module_info_java = self.make_module_descriptor_java()
+        self.jdk_tools.compile_module_descriptor(
+            module_info_java, self.system_modules_jar, self.work_dir
+        )
+
+        module_info_class = self.work_dir / "module-info.class"
+        assert module_info_class.exists(), (
+            f"Expected compiled module descriptor file to be created at {module_info_class}"
+        )
+
+        return module_info_class
+
+    def make_module_jar(self, work_dir: Path) -> Path:
+        """
+        Creates a Modular Jar from [system_modules_jar] by compiling and adding a module descriptor
+        """
+        module_info_class = self.make_module_info_class()
+
+        module_jar = work_dir / "module.jar"
+        create_jar(
+            self.jdk_tools.java,
+            self.jdk_tools.jar_builder,
+            module_info_class,
+            [self.system_modules_jar],
+            module_jar,
+        )
+
+        return module_jar
+
+    def make_jmod_file(self) -> Path:
+        module_name = "java.base"
+        jlink_version = self.jdk_tools.jlink_version()
+        jmod_dir = self.work_dir / "jmod"
+        os.mkdir(jmod_dir)
+        jmod_file = jmod_dir / f"{module_name}.jmod"
+
+        module_jar = self.make_module_jar(self.work_dir)
+
+        self.jdk_tools.create_jmod_from_modular_jar(
+            jmod_file, jlink_version, module_jar
+        )
+
+        return jmod_file
+
+
+class JdkTools:
+    def __init__(
+        self,
+        java: Path,
+        javac: Path,
+        jlink: Path,
+        jmod: Path,
+        jrt_fs_jar: Path,
+        jar_builder: Path,
+    ):
+        self.java = java
+        self.javac = javac
+        self.jlink = jlink
+        self.jmod = jmod
+        self.jrt_fs_location = jrt_fs_jar
+        self.jar_builder = jar_builder
+
+    def jlink_version(self):
+        return run_subprocess([self.jlink, "--version"]).decode("utf-8").strip()
+
+    def compile_module_descriptor(
+        self, module_info_java: Path, system_modules_jar: Path, out_dir: Path
+    ):
+        classpath_arg_value = str(system_modules_jar)
+
+        run_subprocess(
+            [
+                self.javac,
+                "--system=none",
+                f"--patch-module=java.base={classpath_arg_value}",
+                "-d",
+                out_dir,
+                module_info_java,
+            ]
+        )
+
+    def create_jmod_from_modular_jar(
+        self, jmod_file: Path, jlink_version: str, module_jar: Path
+    ):
+        run_subprocess(
+            [
+                self.jmod,
+                "create",
+                "--module-version",
+                jlink_version,
+                # Use LINUX-OTHER to be compatible with JDK 21+ b/294137077
+                "--target-platform",
+                "LINUX-OTHER",
+                "--class-path",
+                module_jar,
+                jmod_file,
+            ]
+        )
+
+    def link_jmods_into_jdk_image(
+        self, jmod_dir: Path, module_name: str, out_dir: Path
+    ):
+        run_subprocess(
+            [
+                self.jlink,
+                "--module-path",
+                jmod_dir,
+                "--add-modules",
+                module_name,
+                "--output",
+                out_dir,
+                "--disable-plugin",
+                "system-modules",
+            ]
+        )
+
+
+def generate_module_descriptor(moduleName: str, jars: List[Path]) -> str:
+    string_builder = ""
+    string_builder += f"module {moduleName} {{\n"
+    package_name_regex = r"(.*)/[^/]*.class"
+    for jar in jars:
+        with zipfile.ZipFile(jar) as jar_zip:
+            entry_names = [entry.filename for entry in jar_zip.infolist()]
+        package_names = set()
+        for entry in entry_names:
+            match = re.match(package_name_regex, entry)
+            if match:
+                package = match.group(1).replace("/", ".")
+                package_names.add(package)
+        for package in sorted(package_names):
+            string_builder += f"    exports {package};\n"
+    string_builder += "}\n"
+    return string_builder
+
+
+def create_jar(
+    java: Path,
+    jar_builder: Path,
+    module_info_class: Path,
+    in_jars: List[Path],
+    output_jar: Path,
+):
+    # META: Our JarBuilder is similar to JarFlinger
+    run_subprocess(
+        [
+            java,
+            "-jar",
+            jar_builder,
+            "--class-files",
+            f"{module_info_class.name}:{module_info_class}",
+            # META: Our jar builder only supports one append-jar
+            "--append-jar",
+            in_jars[0],
+            "--output",
+            output_jar,
+        ]
+    )
+
+
+def copy_jrt_fs_jar(out_dir: Path, jdk_tools: JdkTools):
+    source = jdk_tools.jrt_fs_location
+
+    copied_libs_dir = out_dir / "lib"
+    os.makedirs(copied_libs_dir, exist_ok=True)
+    destination = copied_libs_dir / source.name
+
+    # META: Skip manifest.mf filtering since it is not applicable to us
+    shutil.copy(source, destination)
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--core-for-system-modules-jar", required=True)
+    parser.add_argument("--java", required=True)
+    parser.add_argument("--javac", required=True)
+    parser.add_argument("--jlink", required=True)
+    parser.add_argument("--jmod", required=True)
+    parser.add_argument("--jrt-fs-jar", required=True)
+    parser.add_argument("--jar-builder", required=True)
+    parser.add_argument("--output", required=True)
+    args = parser.parse_args()
+
+    jdk_tools = JdkTools(
+        args.java,
+        Path(args.javac),
+        Path(args.jlink),
+        Path(args.jmod),
+        Path(args.jrt_fs_jar),
+        Path(args.jar_builder),
+    )
+
+    work_dir = tempfile.mkdtemp()
+    JdkImageTransformDelegate(
+        args.core_for_system_modules_jar,
+        Path(work_dir),
+        Path(args.output),
+        jdk_tools,
+    ).run()
+
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/buck2/prelude/android/tools/duplicate_class_checker.py b/buck2/prelude/android/tools/duplicate_class_checker.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/duplicate_class_checker.py
@@ -0,0 +1,168 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+import sys
+import zipfile
+from pathlib import Path
+from typing import Dict, List, Set
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Check whether the provided list of files contains any duplicate class names in them."
+    )
+    parser.add_argument(
+        "--jar-to-owning-target-map-file",
+        type=Path,
+        help="A file that contains the mapping between jar paths and the owning target.",
+        required=False,
+    )
+    parser.add_argument(
+        "--validation-output",
+        type=Path,
+        required=True,
+    )
+    parser.add_argument(
+        "--consolidated-files-list",
+        type=Path,
+        help="A file containing a list of consolidated JSON files (one path per line).",
+        required=False,
+    )
+    parser.add_argument(
+        "--mode",
+        type=str,
+        choices=["pre-dexed-libs", "non-pre-dexed-jars"],
+        required=True,
+    )
+    args = parser.parse_args()
+
+    if args.mode == "pre-dexed-libs":
+        class_to_targets_map = get_class_to_target_mapping_from_consolidated_files(
+            args.consolidated_files_list
+        )
+    elif args.mode == "non-pre-dexed-jars":
+        class_to_targets_map = get_class_to_target_mapping_from_jars(
+            args.jar_to_owning_target_map_file
+        )
+    else:
+        raise ValueError(f"Unknown mode: {args.mode}")
+
+    duplicate_classes = {
+        class_name: target_name_list
+        for class_name, target_name_list in class_to_targets_map.items()
+        if len(target_name_list) > 1
+    }
+
+    print(build_validation_message(duplicate_classes), file=sys.stderr)
+    if duplicate_classes:
+        sys.exit(1)
+    else:
+        with open(args.validation_output, "w") as f:
+            f.write("No duplicate class names found")
+        sys.exit(0)
+
+
+def get_class_to_target_mapping_from_consolidated_files(
+    consolidated_files_list: Path,
+) -> Dict[str, List[str]]:
+    """
+    Reads consolidated JSON files and builds a mapping from class names to targets.
+
+    Each consolidated file is a JSON object mapping target names to lists of class names.
+    This is much faster than reading individual files because:
+    1. Fewer files to open (32 batches instead of 40K+ files)
+    2. Consolidated files are already in the optimal format
+
+    Note: Batch-level duplicate detection is already done in consolidate_class_names.py,
+    so duplicates within a single batch will fail fast at consolidation time.
+    This function only needs to detect cross-batch duplicates.
+    """
+    # Read the list of consolidated files
+    with open(consolidated_files_list) as f:
+        consolidated_files = [line.strip() for line in f if line.strip()]
+
+    class_to_target_mapping: Dict[str, List[str]] = {}
+
+    # Read each consolidated file and merge the results
+    for consolidated_file in consolidated_files:
+        with open(consolidated_file) as f:
+            target_to_classes: Dict[str, List[str]] = json.load(f)
+
+        for target_name, class_names in target_to_classes.items():
+            for class_name in class_names:
+                if "$" not in class_name and "module-info" not in class_name:
+                    class_to_target_mapping.setdefault(class_name, []).append(
+                        target_name
+                    )
+
+    return class_to_target_mapping
+
+
+def get_class_to_target_mapping_from_jars(
+    jar_to_owning_target_map_file: Path,
+) -> Dict[str, List[str]]:
+    """
+    Reads a JSON file that maps JAR file paths to their owning targets,
+    extracts class names from each JAR file, and builds a mapping
+    from class names to the targets that contain them.
+    """
+    with open(jar_to_owning_target_map_file) as f:
+        target_to_jar_file_map = json.loads(f.read())
+
+    class_to_target_mapping: Dict[str, List[str]] = {}
+    for jar_path, target_name in target_to_jar_file_map.items():
+        class_names = extract_class_names_from_jar(jar_path)
+        for class_name in class_names:
+            if "$" in class_name or "module-info" in class_name:
+                continue
+            class_to_target_mapping.setdefault(class_name, []).append(target_name)
+
+    return class_to_target_mapping
+
+
+def extract_class_names_from_jar(jar_path: str) -> Set[str]:
+    """
+    Extracts class names from a JAR file.
+    Returns a set of fully qualified class names.
+    """
+    class_names = set()
+    with zipfile.ZipFile(jar_path, "r") as jar:
+        for entry in jar.namelist():
+            if entry.endswith(".class"):
+                # Convert path/to/ClassName.class to path.to.ClassName
+                class_name = entry.replace("/", ".").replace(".class", "")
+                class_names.add(class_name)
+    return class_names
+
+
+def build_validation_message(
+    duplicate_classes: Dict[str, List[str]],
+) -> str:
+    if not duplicate_classes:
+        return "No duplicate class names found"
+
+    messages = []
+    for class_name, targets in duplicate_classes.items():
+        targets_str = ", ".join(sorted(targets))
+        messages.append(
+            f"* {class_name} exists in the following targets: {targets_str}\n",
+        )
+    return f"""
+Duplicate class name(s) found:
+
+This means multiple copies of the same class is being included in the final apk.
+Check the class names and the target names listed below and make sure to only include one copy of each class.
+Run `buck cquery allpaths(<apk_target>, <library_target>)` or `arc deppy explain-dep <apk_target> <library_target>` to find the dependency paths.
+{"".join(messages)}
+        """
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/android/tools/filter_dex.py b/buck2/prelude/android/tools/filter_dex.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/filter_dex.py
@@ -0,0 +1,264 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import json
+import pathlib
+import re
+
+PREFIX_MARKER = "^"
+SUFFIX_MARKER = "^"
+REGEX_MARKER = "^-"
+
+
+class ClassNameFilter:
+    def __init__(self, primary_dex_patterns):
+        prefixes = []
+        suffixes = []
+        substrings = []
+        exact_matches = []
+        regular_expressions = []
+
+        for pattern in primary_dex_patterns:
+            if pattern.startswith(REGEX_MARKER):
+                regular_expressions.append(pattern[2:])
+            else:
+                is_prefix = pattern[0] == PREFIX_MARKER
+                is_suffix = pattern[-1] == SUFFIX_MARKER
+                if is_prefix and is_suffix:
+                    exact_matches.append(pattern[1:-1])
+                elif is_prefix:
+                    prefixes.append(pattern[1:])
+                elif is_suffix:
+                    suffixes.append(pattern[:-1])
+                else:
+                    substrings.append(pattern)
+
+        self.prefixes = prefixes
+        self.suffixes = suffixes
+        self.substrings = substrings
+        self.exact_matches = exact_matches
+        self.regular_expressions = [
+            re.compile(regular_expression) for regular_expression in regular_expressions
+        ]
+
+    def class_name_matches_filter(self, class_name):
+        if class_name in self.exact_matches:
+            return True
+
+        for prefix in self.prefixes:
+            if class_name.startswith(prefix):
+                return True
+
+        for suffix in self.suffixes:
+            if class_name.endswith(suffix):
+                return True
+
+        for substring in self.substrings:
+            if substring in class_name:
+                return True
+
+        for regular_expression in self.regular_expressions:
+            if regular_expression.match(class_name):
+                return True
+
+        return False
+
+
+def _parse_args():
+    parser = argparse.ArgumentParser(
+        description="Tool to filter a dex for primary class names.",
+        fromfile_prefix_chars="@",
+    )
+
+    parser.add_argument(
+        "--primary-dex-patterns",
+        type=pathlib.Path,
+        required=True,
+        help="a path to a list of primary dex patterns",
+    )
+    parser.add_argument(
+        "--dex-target-identifiers",
+        type=str,
+        required=True,
+        nargs="+",
+        help="a list of dex target identifiers",
+    )
+    parser.add_argument(
+        "--class-names",
+        type=pathlib.Path,
+        required=True,
+        nargs="+",
+        help="a path to a list of class names",
+    )
+    parser.add_argument(
+        "--weight-estimates",
+        type=pathlib.Path,
+        required=True,
+        nargs="+",
+        help="a path to a weight estimate",
+    )
+    parser.add_argument(
+        "--ref-counts",
+        type=pathlib.Path,
+        required=True,
+        nargs="+",
+        help="a path to a ref count file (format: '<method_count> <field_count> <type_count>')",
+    )
+    parser.add_argument(
+        "--synthetic-contexts",
+        type=pathlib.Path,
+        nargs="+",
+        default=[],
+        help="a path to a synthetic-to-context file (one '<synthetic> <context>' pair per line)",
+    )
+    parser.add_argument(
+        "--output",
+        type=pathlib.Path,
+        required=True,
+        help="a path to an output. The output is a JSON mapping of dex target names to a map of primary dex classes, secondary dex classes, and weight estimate.",
+    )
+
+    return parser.parse_args()
+
+
+def _parse_ref_counts(ref_count_path):
+    """Parse a ref count file containing '<method_count> <field_count> <type_count>'."""
+    with open(ref_count_path) as ref_count_file:
+        parts = ref_count_file.read().strip().split()
+        if len(parts) != 3:
+            raise ValueError(
+                f"Expected 3 values (method field type) in ref count file "
+                f"{ref_count_path}, got {len(parts)}: {parts!r}"
+            )
+        return parts[0], parts[1], parts[2]
+
+
+def _parse_synthetic_contexts(synthetic_contexts_path):
+    """Parse '<synthetic> <context>' lines, as written by the pre-dex step, into a dict."""
+    synthetic_to_context = {}
+    with open(synthetic_contexts_path) as synthetic_contexts_file:
+        for line in synthetic_contexts_file:
+            line = line.strip()
+            if not line:
+                continue
+            synthetic, _, context = line.partition(" ")
+            if not context:
+                raise ValueError(
+                    f"Malformed line in {synthetic_contexts_path}: {line!r}"
+                )
+            synthetic_to_context[synthetic] = context
+    return synthetic_to_context
+
+
+def _resolve_synthesizing_context(java_class, synthetic_to_context):
+    """Follow a synthetic back to the class it was synthesized from.
+
+    D8 can synthesize from a synthetic, so the chain is walked to its end. The seen-set guards
+    against a cycle in D8's output, which would otherwise hang the build.
+    """
+    seen = set()
+    while java_class in synthetic_to_context and java_class not in seen:
+        seen.add(java_class)
+        java_class = synthetic_to_context[java_class]
+    return java_class
+
+
+def _belongs_in_primary_dex(java_class, class_name_filter, synthetic_to_context):
+    if class_name_filter.class_name_matches_filter(java_class):
+        return True
+
+    # A synthetic has to land in the same dex as the class it was synthesized from, which
+    # references it directly. Splitting them puts the reference across a dex boundary that the
+    # primary dex cannot resolve. primary_dex_patterns are written against real class names, so
+    # match the context rather than the synthetic's mangled name.
+    context = _resolve_synthesizing_context(java_class, synthetic_to_context)
+    return context != java_class and class_name_filter.class_name_matches_filter(
+        context
+    )
+
+
+def main():
+    args = _parse_args()
+
+    primary_dex_patterns_path = args.primary_dex_patterns
+    with open(primary_dex_patterns_path) as primary_dex_patterns_file:
+        all_primary_dex_patterns = [line.rstrip() for line in primary_dex_patterns_file]
+
+    class_name_filter = ClassNameFilter(all_primary_dex_patterns)
+
+    dex_target_identifiers = args.dex_target_identifiers
+    class_names_paths = args.class_names
+    weight_estimate_paths = args.weight_estimates
+    ref_count_paths = args.ref_counts
+    synthetic_contexts_paths = args.synthetic_contexts
+    output = args.output
+
+    assert len(dex_target_identifiers) == len(class_names_paths), (
+        "Must provide same number of class names files as dex target identifiers!"
+    )
+
+    assert len(dex_target_identifiers) == len(weight_estimate_paths), (
+        "Must provide same number of weight estimate files as dex target identifiers!"
+    )
+
+    assert len(dex_target_identifiers) == len(ref_count_paths), (
+        "Must provide same number of ref count files as dex target identifiers!"
+    )
+
+    assert not synthetic_contexts_paths or len(dex_target_identifiers) == len(
+        synthetic_contexts_paths
+    ), "Must provide same number of synthetic context files as dex target identifiers!"
+
+    json_output = {}
+    for i in range(len(dex_target_identifiers)):
+        dex_target_name = dex_target_identifiers[i]
+        weight_estimate_path = weight_estimate_paths[i]
+        with open(weight_estimate_path) as weight_estimate_file:
+            weight_estimate = weight_estimate_file.read().strip()
+
+        method_ref_count, field_ref_count, type_ref_count = _parse_ref_counts(
+            ref_count_paths[i]
+        )
+
+        class_names_path = class_names_paths[i]
+        with open(class_names_path) as class_names_file:
+            all_class_names = [line.rstrip() for line in class_names_file]
+
+        synthetic_to_context = (
+            _parse_synthetic_contexts(synthetic_contexts_paths[i])
+            if synthetic_contexts_paths
+            else {}
+        )
+
+        primary_dex_class_names = []
+        secondary_dex_class_names = []
+        for java_class in all_class_names:
+            if _belongs_in_primary_dex(
+                java_class, class_name_filter, synthetic_to_context
+            ):
+                primary_dex_class_names.append(java_class + ".class")
+            else:
+                secondary_dex_class_names.append(java_class + ".class")
+
+        json_output[dex_target_name] = {
+            "primary_dex_class_names": primary_dex_class_names,
+            "secondary_dex_class_names": secondary_dex_class_names,
+            "weight_estimate": weight_estimate,
+            "method_ref_count": method_ref_count,
+            "field_ref_count": field_ref_count,
+            "type_ref_count": type_ref_count,
+        }
+
+    with open(output, "w") as output_file:
+        json.dump(json_output, output_file, indent=4)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/android/tools/filter_extra_resources.py b/buck2/prelude/android/tools/filter_extra_resources.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/filter_extra_resources.py
@@ -0,0 +1,63 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import pathlib
+import shutil
+
+import utils
+
+ZIP_NOTHING_TO_DO_EXIT_CODE = 12
+
+
+def _parse_args():
+    parser = argparse.ArgumentParser(
+        description="Tool to remove extra resources from apk."
+    )
+    parser.add_argument(
+        "--input-apk",
+        type=pathlib.Path,
+        required=True,
+        help="a path to the original apk",
+    )
+    parser.add_argument(
+        "--output-apk",
+        type=pathlib.Path,
+        required=True,
+        help="a path to the output apk with removed resources",
+    )
+    parser.add_argument(
+        "--extra-filtered-resources",
+        type=str,
+        action="append",
+        required=True,
+        help="list of patterns of files to filter out from the input apk",
+    )
+    return parser.parse_args()
+
+
+def main():
+    args = _parse_args()
+    shutil.copyfile(args.input_apk, args.output_apk)
+    utils.execute_command(["chmod", "644", args.output_apk])
+
+    # The normal resource filtering apparatus is super slow because it extracts the whole apk,
+    # strips files out of it, then repackages it.
+    #
+    # This is a faster filtering step that just uses zip -d to remove entries from the archive.
+    # It's also superbly dangerous.
+    #
+    # If zip -d returns that there was nothing to do, then we don't fail.
+    utils.execute_command_ignore_exit_codes(
+        ["zip", "-d", str(args.output_apk)] + args.extra_filtered_resources,
+        [ZIP_NOTHING_TO_DO_EXIT_CODE],
+    )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/android/tools/filter_prebuilt_native_library_dir.py b/buck2/prelude/android/tools/filter_prebuilt_native_library_dir.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/filter_prebuilt_native_library_dir.py
@@ -0,0 +1,57 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import os
+from pathlib import Path
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Filter the ABIs in a prebuilt native library directory"
+    )
+    parser.add_argument(
+        "library_dirs",
+        type=Path,
+        help="A file that lists directories containing ABI subdirectories",
+    )
+    parser.add_argument(
+        "output_dir",
+        type=Path,
+        help="Symlinks to the filtered ABIs will be created here",
+    )
+    parser.add_argument(
+        "--abis",
+        required=True,
+        nargs="+",
+        help="The ABIs to filter",
+    )
+    args = parser.parse_args()
+
+    args.output_dir.mkdir(parents=True)
+    with open(args.library_dirs, "r") as f:
+        for line in f:
+            library_dir = Path(line.rstrip())
+            for abi in args.abis:
+                abi_path = library_dir / abi
+                if abi_path.exists():
+                    abi_output_path = args.output_dir / abi
+                    abi_output_path.mkdir(exist_ok=True)
+                    for source_path in abi_path.iterdir():
+                        # This should be a directory, but files will be silently ignored by APK
+                        # packaging, so we don't need to error here. We use os.path.relpath because
+                        # pathlib.Path.relative_to only works if the paths have a common prefix.
+                        (abi_output_path / source_path.name).symlink_to(
+                            os.path.relpath(source_path, start=abi_output_path),
+                            target_is_directory=source_path.is_dir(),
+                        )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/android/tools/jdk_system_image.bzl b/buck2/prelude/android/tools/jdk_system_image.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/jdk_system_image.bzl
@@ -0,0 +1,47 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+
+def _jdk_system_image_impl(ctx: AnalysisContext) -> list[Provider]:
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+
+    output = ctx.actions.declare_output("image", has_content_based_path = False)
+    cmd = cmd_args([
+        ctx.attrs.create_jdk_system_image[RunInfo],
+        "--core-for-system-modules-jar",
+        ctx.attrs.core_for_system_modules_jar,
+        "--java",
+        java_toolchain.java[RunInfo],
+        "--javac",
+        java_toolchain.javac[RunInfo],
+        "--jlink",
+        java_toolchain.jlink[RunInfo],
+        "--jmod",
+        java_toolchain.jmod[RunInfo],
+        "--jrt-fs-jar",
+        java_toolchain.jrt_fs_jar,
+        "--jar-builder",
+        ctx.attrs.jar_builder,
+        "--output",
+        output.as_output(),
+    ])
+    ctx.actions.run(cmd, category = "create_jdk_system_image")
+
+    return [DefaultInfo(default_output = output)]
+
+jdk_system_image = rule(
+    impl = _jdk_system_image_impl,
+    attrs = {
+        "core_for_system_modules_jar": attrs.source(),
+        "create_jdk_system_image": attrs.exec_dep(default = "prelude//android/tools:create_jdk_system_image"),
+        "jar_builder": attrs.source(default = "prelude//toolchains/android/src/com/facebook/buck/util/zip:jar_builder"),
+        "_java_toolchain": toolchains_common.java_for_android(),
+    },
+)
diff --git a/buck2/prelude/android/tools/merge_sequence.py b/buck2/prelude/android/tools/merge_sequence.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/merge_sequence.py
@@ -0,0 +1,815 @@
+#!/usr/bin/python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Applies the merge sequence to the linkable_graph and module graph to produce merged libraries.
+
+The merge sequence is a list of "merge entries". Each entry is comprised of "merge specs", each of which have a name and
+a list of roots. A merge entry may be a merge spec or a list of merge specs.
+
+For example:
+
+```
+[
+    ("libgroup1.so", [//group1:root1, //group1:root2]),
+    ("libgroup2.so", [//group2:root]),
+    (
+        ("libgroup3lib1.so": [//group3:root1]),
+        ("libgroup3lib2.so": [//group3:root2]),
+    ),
+    ...
+]
+```
+
+We use this sequence to assign each target in the linkable graph to a "merge group". The list is processed in order and
+each entry defines a new merge group. That group consists of all the roots in the entry and all of the transitive
+dependencies of those roots, except for nodes that have already been assigned a merge group.
+
+We then need to split that merge group into "split groups" for four reasons: avoiding unwanted dependencies between
+libraries, defining valid libraries, avoiding adding implicit module dependencies to targets, and excluding targets that
+shouldn't be merged. That imposes these constraints:
+1. Libraries defined by specs in the same entry should not depend on one another, so any shared dependencies must be
+   split into separate libraries.
+2. Targets in a split group will all be in the same module. A library cannot span multiple modules.
+3. For split groups in the root module, all targets will have the same set of transitive module dependencies (including
+   through targets in other merge groups). A non-root module cannot be loaded without loading all of its module
+   dependencies, but if a JNI entry-point target is in the root module and has module dependencies, those dependencies
+   would have to be loaded explicitly in advance, or the library load for the target will fail. Making any such target
+   depend on *more* modules in merged-library builds would therefore risk merged-build-only runtime crashes.
+4. Some targets are excluded from merging (explicitly via a blocklist, or implicitly because they cannot be packaged as
+   assets). Non-asset targets are rare, often cause issues when merged, and complicate split-group "layering" as
+   described below, so it significantly simplifies merge sequence configuration and mechanics to exclude them.
+
+Finally, we need to prevent dependency cycles between merged libraries. This only requires additional effort at the
+split group level; there cannot be any cycles between merge groups because, by definition, any transitive dependency of
+a target in a previous merge group is already in a previous merge group.
+
+To ensure there are no cycles, we further split the split groups into "layers" by how many times their dependents in the
+current merge group reenter the same split group. There cannot be a cycle between any pair of split group layers,
+regardless of whether the layers are from the same split group. If dependency chains exist in both directions between
+two split group layers:
+- The layers must share the same transitive module dependencies.
+- The layers must have different dependent reentry counts or be in different modules, or else they'd be the same layer.
+- If the layers are in the same module, there are dependency chains in both directions between different layers of the
+  same split group. But those layers have different dependent reentry counts into that split group, so this is
+  impossible. The layers are in different modules.
+- One layer must be in the root module, or else there would be a module dependency cycle. (As a special case, cycles
+  between the root module and non-root modules are allowed.)
+- Every target in the root-module layer in the dependency chain starting from the non-root module layer must be a
+  non-asset target, or else the module would have included each such target, since they're transitive dependencies and
+  no other non-root module includes them.
+- But we do not merge non-asset targets. There is no cycle.
+
+Further, the number of layers in a split group is the minimal number of libraries that can be merged from that split
+group without causing a cycle. There exists a dependency chain between each pair of layers in a split group that exits
+the split group at one layer and reenters it at the other, so any library merging two layers of the same split group
+transitively depends on itself.
+
+The split group layering determines the final library constituents.
+
+We perform a bottom-up traversal to identify transitive module dependencies, then a top-down traversal to assign split
+groups, compute dependent split-group reentry counts, and finalize split group layers. While we could avoid the second
+traversal by instead layering based on *dependency* reentry count, using *dependent* reentry count produces better
+target distribution between layers.
+- Optimal target distribution would maximize the number of targets in the largest layer. For a fixed number of
+  libraries, build size varies depending on how many symbols need to be exposed in order to facilitate linkage across
+  libraries, and so reducing the number of satellite targets will in general improve build size.
+- Split-group-reentrant dependency chains are rare, so targets without split-group-reentrant dependencies or dependents
+  are common. Similarly, short split-group-reentrant dependency chains are more common than longer ones.
+- So if we want to maximize the size of the largest layer, we want the targets without reentrant dependencies to merge
+  with the targets at the heads of reentrant dependency chains, the most common targets in such chains.
+
+Once we've done the split group layering, the split group and layer identify the "final library" for each target. The
+one remaining thing to do is to produce a name for each final library. Ideally, each merge group will end up with a
+single library and the naming is simple. If it ends up having multiple libraries, we give each a unique name by adding
+suffixes.
+
+We aim to minimize the suffixing of the largest, most central layers, so we apply the following rules:
+1. Library names start with the names of the merge specs from the current entry whose roots include or depend on the
+   library's targets. This is just the spec name if there is only one, or `lib_shared_` plus the underscore-separated
+   list of spec names if there are multiple.
+2. If a merge spec includes targets from multiple modules, each library in a non-root module will be suffixed with that
+   module name.
+3. We perform a topological traversal of the final library graph, maintaining counters of times we've encountered each
+   (possibly module-suffixed) library name. Each final library after the first encountered for its library name will be
+   further suffixed with that library name's counter value.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import pathlib
+import re
+import sys
+import typing
+from collections import defaultdict
+from typing import Optional
+
+Label = typing.NewType("Label", str)
+
+
+class LinkableGraphNode(typing.NamedTuple):
+    """
+    A node in the linkable graph input
+    """
+
+    raw_target: str
+    soname: str
+    deps: list[Label]
+    can_be_asset: bool
+    force_static: bool
+    labels: list[str]
+
+    @staticmethod
+    def parse(json: dict[str, object]) -> LinkableGraphNode:
+        deps = [Label(x) for x in json.pop("deps")]  # pyre-ignore
+        return LinkableGraphNode(deps=deps, **json)  # pyre-ignore
+
+
+class MergemapInput(typing.NamedTuple):
+    """
+    Parsed form of the mergemap input file
+    """
+
+    merge_sequence: list[MergeSequenceGroupSpec]
+    blocklist: list[re.Pattern[str]]
+    nodes_by_platform: dict[str, dict[Label, LinkableGraphNode]]
+
+    @staticmethod
+    def parse(mergemap_input: dict[str, typing.Any]) -> MergemapInput:
+        merge_sequence = [
+            MergeSequenceGroupSpec(x)
+            for x in mergemap_input["native_library_merge_sequence"]
+        ]
+        blocklist = [
+            re.compile(x)
+            for x in mergemap_input["native_library_merge_sequence_blocklist"]
+        ]
+        nodes_by_platform = {}
+        for platform, linkable_graph_spec in mergemap_input[
+            "linkable_graphs_by_platform"
+        ].items():
+            nodes = {}
+            for target, node_data in linkable_graph_spec.items():
+                target = Label(target)
+                node_data = LinkableGraphNode.parse(node_data)
+                nodes[target] = node_data
+            nodes_by_platform[platform] = nodes
+
+        return MergemapInput(
+            merge_sequence=merge_sequence,
+            blocklist=blocklist,
+            nodes_by_platform=nodes_by_platform,
+        )
+
+
+class ApkModuleGraph:
+    """
+    Parsed form of the optional apk module graph input
+    """
+
+    def __init__(self, target_to_module_mapping: Optional[dict[str, str]]) -> None:
+        self.target_to_module_mapping = target_to_module_mapping
+
+    def module_for_target(self, target: str) -> str:
+        if self.target_to_module_mapping:
+            module = self.target_to_module_mapping[target]
+            return module
+        else:
+            return ROOT_MODULE
+
+
+class SplitGroupKey(typing.NamedTuple):
+    """
+    Identifies a single "split group"
+    """
+
+    # If excluded, this holds the targets label
+    excluded: typing.Optional[Label]
+    module: str
+    current_merge_group: int
+    # Holds the set of names of specs in the entry that depend on the targets.
+    # This will contain only one string for most targets/entries.
+    merge_subgroup: set[str]
+    # For the root module, holds the structified set of transitively reachable modules
+    transitive_module_key: typing.Optional[frozenset[str]]
+
+    def get_base_name(self) -> str:
+        if self.excluded:
+            return self.excluded
+
+        assert len(self.merge_subgroup) > 0
+
+        dependent_spec_names = sorted(self.merge_subgroup)
+
+        if len(dependent_spec_names) == 1:
+            return dependent_spec_names[0]
+        else:
+            base_name = "lib_shared"
+            for dependent_spec_name in dependent_spec_names:
+                base_name += f"_{dependent_spec_name[3:-3]}"
+            base_name += ".so"
+            return base_name
+
+
+class NodeData(typing.NamedTuple):
+    base_library_name: str
+    could_be_root_for: list[str]
+    module: str
+    merge_group: int
+    is_excluded: bool
+    final_lib_key: FinalLibKey
+    dependent_included_split_group_entry_counts: dict[int, int]
+
+    def debug(self) -> object:
+        return self._asdict()
+
+
+class FinalLibKey(typing.NamedTuple):
+    split_group: int
+    cycle_breaker: typing.Hashable
+
+
+class FinalLibData(typing.NamedTuple):
+    module: str
+    merge_group: int
+    # this will be either the merge group spec name or come from the label for an excluded lib.
+    base_library_name: str
+    is_excluded: bool
+    key: FinalLibKey
+    deps: set[FinalLibKey]
+    entry_point_targets: set[str]
+
+
+class FinalLibGraph:
+    """The "final lib graph" is traversed to produce the final lib names"""
+
+    graph: dict[FinalLibKey, FinalLibData]
+
+    def __init__(self) -> None:
+        self.graph = {}
+
+    def _ensure_lib_data(self, node_data: NodeData) -> FinalLibData:
+        lib_key = node_data.final_lib_key
+        lib_data = self.graph.get(lib_key, None)
+        if not lib_data:
+            lib_data = self.graph.setdefault(
+                lib_key,
+                FinalLibData(
+                    module=node_data.module,
+                    merge_group=node_data.merge_group,
+                    base_library_name=node_data.base_library_name,
+                    is_excluded=node_data.is_excluded,
+                    key=lib_key,
+                    deps=set(),
+                    entry_point_targets=set(),
+                ),
+            )
+        else:
+            assert lib_data.module == node_data.module, (lib_data, node_data)
+            assert lib_data.merge_group == node_data.merge_group, (lib_data, node_data)
+
+        return lib_data
+
+    def add_node(
+        self,
+        node_data: NodeData,
+        deps: list[str],
+        deps_data: list[NodeData],
+    ) -> None:
+        lib_data = self._ensure_lib_data(node_data)
+
+        for dep, dep_data in zip(deps, deps_data):
+            if dep_data.final_lib_key != node_data.final_lib_key:
+                lib_data.deps.add(dep_data.final_lib_key)
+                dep_lib_data = self._ensure_lib_data(dep_data)
+                dep_lib_data.entry_point_targets.add(dep)
+
+    def dump_lib_edges(self, names: dict[FinalLibKey, str]) -> dict[str, list[str]]:
+        return {
+            names[k]: [names[d] for d in node.deps] for k, node in self.graph.items()
+        }
+
+    def dump_entry_point_targets(
+        self, names: dict[FinalLibKey, str]
+    ) -> dict[str, list[str]]:
+        return {
+            names[k]: list(node.entry_point_targets) for k, node in self.graph.items()
+        }
+
+    def assign_names(
+        self, merge_group_module_constituents: list[set[str]]
+    ) -> dict[FinalLibKey, str]:
+        final_lib_graph = {}
+        for key, dep_data in self.graph.items():
+            final_lib_graph[key] = list(dep_data.deps)
+
+        # this topo_sort also verifies that we produced an acyclic final lib graph
+        sorted_final_lib_keys = topo_sort(
+            final_lib_graph, lambda x: self.graph[x].module if self.graph[x] else str(x)
+        )
+
+        name_counters = {}
+        final_lib_names: dict[FinalLibKey, str] = {}
+        for key in sorted_final_lib_keys:
+            dep_data = self.graph[key]
+            if dep_data.is_excluded:
+                final_lib_names[key] = dep_data.base_library_name
+            else:
+                lib_name, ext = os.path.splitext(dep_data.base_library_name)
+                if len(
+                    merge_group_module_constituents[dep_data.merge_group]
+                ) > 1 and not is_root_module(dep_data.module):
+                    lib_name += "_" + dep_data.module
+
+                count = name_counters.setdefault(lib_name, 0) + 1
+                name_counters[lib_name] = count
+                if count > 1:
+                    lib_name += "_{}".format(count - 1)
+                final_lib_names[key] = lib_name + ext
+        return final_lib_names
+
+
+# Older python has poor typing support, so we need to use coarser types there (but pyre wants the exact ones)
+if sys.version_info >= (3, 9):
+    MergeSubgroupMapping = typing.Callable[[Label], typing.Optional[set[str]]]
+    MergeGroupSpecDef = typing.Tuple[str, list[str]]
+else:
+    MergeSubgroupMapping = typing.Callable
+    MergeGroupSpecDef = typing.Tuple
+
+
+class MergeSequenceGroupSpec:
+    # These lists run parallel to one another; the group_roots_patterns
+    # entry for a given index contains all the root patterns for the
+    # group_specs entry at the same index.
+    group_specs: list[MergeGroupSpecDef]
+    group_roots_patterns: list[list[re.Pattern[str]]]
+
+    def __init__(
+        self, group_specs: typing.Union[MergeGroupSpecDef, list[MergeGroupSpecDef]]
+    ) -> None:
+        self.group_specs = (
+            [group_specs] if isinstance(group_specs[0], str) else group_specs
+        )
+
+        for group_spec in self.group_specs:
+            library_name = group_spec[0]
+            assert library_name.startswith("lib"), (
+                f"native merge library name {library_name} does not begin with 'lib'"
+            )
+            assert library_name.endswith(".so"), (
+                f"native merge library name {library_name} does not end with '.so'"
+            )
+
+        self.group_roots_patterns = [
+            [re.compile(x) for x in spec[1]] for spec in self.group_specs
+        ]
+
+    def get_rooted_specs(self, raw_target: str) -> set[str]:
+        result = set()
+        for patterns, group_spec in zip(self.group_roots_patterns, self.group_specs):
+            for p in patterns:
+                if p.search(raw_target):
+                    result.add(group_spec[0])
+                    break
+
+        return result
+
+    def compute_merge_subgroup_mapping(
+        self,
+        group_roots: dict[Label, set[str]],
+        post_ordered_targets: list[Label],
+        graph_map: dict[Label, LinkableGraphNode],
+    ) -> MergeSubgroupMapping:
+        merge_specs_with_reachable_roots = defaultdict(set)
+
+        for target, rooted_specs in group_roots.items():
+            merge_specs_with_reachable_roots[target].update(rooted_specs)
+
+        for target in post_ordered_targets[::-1]:
+            node = graph_map.get(target)
+            assert node is not None
+            roots_to_add = merge_specs_with_reachable_roots[target]
+            for child in node.deps:
+                merge_specs_with_reachable_roots[child].update(roots_to_add)
+
+        return lambda x: frozenset(merge_specs_with_reachable_roots[x])
+
+
+def get_native_linkables_by_merge_sequence(  # noqa: C901
+    graph_node_map: dict[Label, LinkableGraphNode],
+    native_library_merge_sequence: list[MergeSequenceGroupSpec],
+    native_library_merge_sequence_blocklist: list[typing.Pattern],
+    apk_module_graph: ApkModuleGraph,
+    native_library_merge_non_asset_libs: bool,
+) -> typing.Tuple[dict[Label, NodeData], dict[FinalLibKey, str], FinalLibGraph]:
+    final_lib_graph = FinalLibGraph()
+    node_data: dict[Label, NodeData] = {}
+    transitive_module_deps_map: dict[Label, frozenset[str]] = {}
+
+    dependents_in_current_merge_group_map: dict[Label, list[Label]] = {}
+
+    def check_is_excluded(target: Label) -> bool:
+        node = graph_node_map[target]
+        if not native_library_merge_non_asset_libs and not node.can_be_asset:
+            return True
+
+        raw_target = node.raw_target
+        for x in native_library_merge_sequence_blocklist:
+            if x.search(raw_target):
+                return True
+
+        # TODO(cjhopman): This logic does not explicitly exclude targets that are used_by_wrap_script. D38377593
+        # enforces that such targets never can_be_asset and are therefore implicitly excluded, but D38845949 still
+        # explicitly excludes them for Buck 1.
+        return False
+
+    def get_children_without_merge_group(label: Label) -> list[Label]:
+        node = graph_node_map[label]
+        group_deps = [child for child in node.deps if child not in node_data]
+
+        # In addition to applying an ordering to targets, this traversal identifies within-merge-group dependents.
+        for group_dep in group_deps:
+            dependents_in_current_merge_group_map.setdefault(group_dep, []).append(
+                label
+            )
+
+        return group_deps
+
+    current_merge_group = 0
+
+    split_groups: dict[SplitGroupKey, int] = {}
+
+    merge_group_module_constituents: list[set[str]] = []
+
+    for current_merge_group in range(len(native_library_merge_sequence)):
+        dependents_in_current_merge_group_map = {}
+
+        merge_group_module_constituents.append(set())
+        group_specs: MergeSequenceGroupSpec = native_library_merge_sequence[
+            current_merge_group
+        ]
+        group_roots = {}
+        for label, node in graph_node_map.items():
+            if label not in node_data:
+                rooted_specs = group_specs.get_rooted_specs(node.raw_target)
+                if rooted_specs:
+                    group_roots[label] = rooted_specs
+
+        post_ordered_targets = post_order_traversal_by(
+            group_roots.keys(), get_children_without_merge_group
+        )
+
+        merge_subgroup_mapping = group_specs.compute_merge_subgroup_mapping(
+            group_roots, post_ordered_targets, graph_node_map
+        )
+
+        def get_split_group(
+            label: Label,
+            transitive_module_deps: frozenset[str],
+            module: str,
+            current_merge_group: int = current_merge_group,
+            merge_subgroup_mapping: MergeSubgroupMapping = merge_subgroup_mapping,
+        ) -> typing.Tuple[bool, int, str]:
+            excluded = None
+            if check_is_excluded(label):
+                excluded = label
+
+            merge_subgroup = merge_subgroup_mapping(label)
+
+            if is_root_module(module):
+                transitive_module_key = transitive_module_deps
+            else:
+                transitive_module_key = None
+
+            split_group_key = SplitGroupKey(
+                excluded=excluded,
+                module=module,
+                current_merge_group=current_merge_group,
+                merge_subgroup=merge_subgroup,
+                transitive_module_key=transitive_module_key,
+            )
+            return (
+                excluded is not None,
+                split_groups.setdefault(split_group_key, len(split_groups)),
+                split_group_key.get_base_name(),
+            )
+
+        # Bottom-up traversal (compute transitive module dependencies)
+        for target in post_ordered_targets:
+            assert target not in node_data, "{}: {}".format(
+                target, post_ordered_targets
+            )
+
+            node = graph_node_map[target]
+            module = apk_module_graph.module_for_target(node.raw_target)
+
+            merge_group_module_constituents[current_merge_group].add(module)
+
+            transitive_module_deps = {module}
+            for dep in node.deps:
+                transitive_module_deps.update(transitive_module_deps_map[dep])
+            transitive_module_deps_map[target] = frozenset(transitive_module_deps)
+
+        # Top-down traversal (determine split groups, compute dependent split group reentry counts, finalize layers)
+        for target in reversed(post_ordered_targets):
+            assert target not in node_data, "{}: {}".format(
+                target, post_ordered_targets
+            )
+
+            node = graph_node_map[target]
+            module = apk_module_graph.module_for_target(node.raw_target)
+
+            is_excluded, split_group, base_library_name = get_split_group(
+                target, transitive_module_deps_map[target], module
+            )
+
+            dependent_included_split_group_entry_counts: dict[int, int] = {}
+
+            for dependent_in_group in dependents_in_current_merge_group_map.get(
+                target, []
+            ):
+                dependent_in_group_data = node_data[dependent_in_group]
+                dependent_split_group = (
+                    dependent_in_group_data.final_lib_key.split_group
+                )
+                is_included_split_group_entry = (
+                    split_group != dependent_split_group
+                    and not dependent_in_group_data.is_excluded
+                )
+
+                # dependent_included_split_group_entry_counts do not count entry into a target's own split group layer,
+                # so we have to ensure that its dependencies record an entry count of at least 1 for that split group.
+                if (
+                    is_included_split_group_entry
+                    and dependent_split_group
+                    not in dependent_included_split_group_entry_counts
+                ):
+                    dependent_included_split_group_entry_counts[
+                        dependent_split_group
+                    ] = 1
+
+                for (
+                    group,
+                    entry_count,
+                ) in dependent_in_group_data.dependent_included_split_group_entry_counts.items():
+                    if group == dependent_split_group and is_included_split_group_entry:
+                        entry_count += 1
+
+                    curr_entry_count = dependent_included_split_group_entry_counts.get(
+                        group, 0
+                    )
+                    if entry_count > curr_entry_count:
+                        dependent_included_split_group_entry_counts[group] = entry_count
+
+            this_node_data = NodeData(
+                base_library_name=base_library_name,
+                could_be_root_for=list(group_roots.get(target, set())),
+                module=module,
+                merge_group=current_merge_group,
+                final_lib_key=FinalLibKey(
+                    split_group=split_group,
+                    cycle_breaker=dependent_included_split_group_entry_counts.get(
+                        split_group, 0
+                    ),
+                ),
+                is_excluded=is_excluded,
+                dependent_included_split_group_entry_counts=dependent_included_split_group_entry_counts,
+            )
+            node_data[target] = this_node_data
+
+        for target in post_ordered_targets:
+            node = graph_node_map[target]
+            deps_data = [node_data[dep] for dep in node.deps]
+            final_lib_graph.add_node(node_data[target], node.deps, deps_data)
+
+    final_lib_names = final_lib_graph.assign_names(merge_group_module_constituents)
+    return node_data, final_lib_names, final_lib_graph
+
+
+T = typing.TypeVar("T")
+
+
+def post_order_traversal_by(
+    roots: list[T],
+    get_nodes_to_traverse_func: typing.Callable[[T], list[T]],
+    get_node_str: typing.Callable[[T], str] = None,
+) -> list[T]:
+    """
+    Returns the post-order sorted list of the nodes in the traversal.
+
+    This implementation simply performs a dfs. We maintain a work stack here.
+    When visiting a node, we first add an item to the work stack to output that
+    node, and then add items to visit all the children. While a work item for a
+    child will not be added if it has already been visited, if there's an item in
+    the stack for that child it will still be added. When popping the visit, if
+    the node had been visited, it's ignored. This ensures that a node's children are
+    all visited before we output that node.
+    """
+    ordered = []
+    visited = {}
+    OUTPUT = 1
+    VISIT = 2
+    current_parents = []
+    work = [(VISIT, n) for n in roots]
+    while work:
+        kind, node = work.pop()
+        if kind == VISIT:
+            if node not in visited:
+                visited[node] = True
+                current_parents.append(node)
+
+                work.append((OUTPUT, node))
+                for dep in get_nodes_to_traverse_func(node):
+                    if dep in current_parents:
+                        current_parents_strs = []
+                        for k in current_parents:
+                            current_parents_strs.append(
+                                get_node_str(k) if get_node_str else str(k)
+                            )
+                        raise AssertionError(
+                            "detected cycle: {}".format(
+                                " -> ".join(
+                                    current_parents_strs
+                                    + [get_node_str(dep) if get_node_str else str(dep)]
+                                )
+                            )
+                        )
+
+                    if dep not in visited:
+                        work.append((VISIT, dep))
+        else:
+            ordered.append(node)
+            current_parents.pop()
+    return ordered
+
+
+ROOT_MODULE = "dex"
+
+
+def is_root_module(module: str) -> bool:
+    return module == ROOT_MODULE
+
+
+def topo_sort(
+    graph: dict[T, list[T]], get_node_str: typing.Callable[[T], str] = None
+) -> list[T]:
+    """
+    Topo-sort the given graph.
+    """
+    in_degrees = {node: 0 for node in graph}
+    for _node, deps in graph.items():
+        assert len(deps) == len(set(deps))
+        for dep in deps:
+            in_degrees[dep] += 1
+
+    roots = []
+
+    for node, in_degree in in_degrees.items():
+        if in_degree == 0:
+            roots.append(node)
+
+    postordered = post_order_traversal_by(roots, lambda x: graph[x], get_node_str)
+    postordered.reverse()
+
+    return postordered
+
+
+def read_apk_module_graph(path: Optional[str]) -> ApkModuleGraph:
+    if not path:
+        return ApkModuleGraph(None)
+
+    target_to_module_mapping = {}
+    # the format of this file is, the first line contains an integer, then follows that many lines describing dependencies
+    # between modules. Each line is of the form: <module_name> <dep_name1> <dep_name2> ...
+    # after that, all target->module mappings are listed, one on each line.
+    # Each line has the form: <raw_target> <module_name>
+    with open(path) as modules_in:
+        lines = modules_in.read().splitlines()
+        module_lines = int(lines[0])
+        for line in lines[module_lines + 1 :]:
+            target, module = line.split()
+            target_to_module_mapping[target] = module
+    return ApkModuleGraph(target_to_module_mapping)
+
+
+def read_mergemap_input(path: str) -> MergemapInput:
+    with open(path) as mergemap_input:
+        mergemap_input = json.load(mergemap_input)
+        return MergemapInput.parse(mergemap_input)
+
+
+def main() -> int:  # noqa: C901
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--mergemap-input", required=True)
+    parser.add_argument("--apk-module-graph")
+    parser.add_argument("--output")
+    parser.add_argument("--merge-non-asset-libs", action="store_true")
+    args = parser.parse_args()
+
+    apk_module_graph = read_apk_module_graph(args.apk_module_graph)
+
+    final_result = {}
+    debug_results = {}
+    split_groups = {}
+    mergemap_input = read_mergemap_input(args.mergemap_input)
+    for platform, nodes in mergemap_input.nodes_by_platform.items():
+        (
+            node_data,
+            final_lib_names,
+            final_lib_graph,
+        ) = get_native_linkables_by_merge_sequence(
+            nodes,
+            mergemap_input.merge_sequence,
+            mergemap_input.blocklist,
+            apk_module_graph,
+            args.merge_non_asset_libs,
+        )
+
+        final_mapping = {}
+        for target in nodes.keys():
+            if target in node_data:
+                node = node_data[target]
+                if node.is_excluded:
+                    final_mapping[target] = None
+                else:
+                    final_mapping[target] = final_lib_names[node.final_lib_key]
+                    split_groups[final_lib_names[node.final_lib_key]] = (
+                        node.base_library_name
+                    )
+            else:
+                final_mapping[target] = str(target)
+        debug_results[platform] = (
+            # Target name -> various information
+            {k: v.debug() for k, v in node_data.items()},
+            # Serialized FinalLibKey -> final library name
+            {str(k): v for k, v in final_lib_names.items()},
+            # Final library name -> final names of direct library dependencies
+            final_lib_graph.dump_lib_edges(final_lib_names),
+            # Final library name -> entry point targets
+            final_lib_graph.dump_entry_point_targets(final_lib_names),
+        )
+        final_result[platform] = final_mapping
+
+    if args.output:
+        pathlib.Path(args.output).mkdir(parents=True, exist_ok=True)
+        with open(os.path.join(args.output, "merge.map"), "w") as outfile:
+            json.dump(final_result, outfile, indent=2, sort_keys=True)
+        with open(os.path.join(args.output, "split_groups.map"), "w") as outfile:
+            json.dump(split_groups, outfile, indent=2, sort_keys=True)
+
+        # When writing an output dir we also produce some debugging information.
+        for platform, result in final_result.items():
+
+            def set_default(obj: object) -> object:
+                if isinstance(obj, frozenset):
+                    return list(obj)
+                raise TypeError
+
+            with open(
+                os.path.join(args.output, "{}.debug".format(platform)), "w"
+            ) as outfile:
+                json.dump(
+                    debug_results[platform], outfile, indent=2, default=set_default
+                )
+
+            # The "inverted" map just provides a much simpler human-readable form of the merge mapping of the form:
+            # libfoo.so
+            #    target1
+            #    target2
+            # libfoo2.so
+            # ...
+            inverted = defaultdict(set)
+            for label, lib in result.items():
+                if not lib:
+                    lib = label
+                inverted[lib].add(label)
+            with open(
+                os.path.join(args.output, "{}.inverted".format(platform)),
+                "w",
+            ) as outfile:
+                lines = []
+                for lib in sorted(inverted.keys()):
+                    lines.append(lib + "\n")
+                    for label in sorted(inverted[lib]):
+                        lines.append("  " + str(label) + "\n")
+                outfile.writelines(lines)
+    else:
+        json.dump(final_result, sys.stdout, indent=2)
+
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/buck2/prelude/android/tools/native_libs_as_assets_metadata.py b/buck2/prelude/android/tools/native_libs_as_assets_metadata.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/native_libs_as_assets_metadata.py
@@ -0,0 +1,84 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import hashlib
+import os
+from pathlib import Path
+from typing import NamedTuple
+
+
+class NativeLibrary(NamedTuple):
+    full_path: Path
+    relative_path: Path
+    size: int
+    sha256: str
+
+
+def _get_native_library(path: Path, relative_path: Path) -> NativeLibrary:
+    if not (path.name == "wrap.sh" or path.suffix == ".so"):
+        raise Exception("Unexpected path {} in native library directory!".format(path))
+
+    with open(path, "rb") as f:
+        file_size = os.path.getsize(path)
+        sha256 = hashlib.sha256(f.read()).hexdigest()
+
+        return NativeLibrary(path, relative_path, file_size, sha256)
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Writes out metadata relating to native libraries"
+    )
+    parser.add_argument(
+        "--native-library-dirs",
+        type=Path,
+        help="A file of directories containing native libraries",
+    )
+    parser.add_argument(
+        "--metadata-output",
+        type=Path,
+        help="Metadata is written to this file",
+    )
+    args = parser.parse_args()
+
+    native_libraries = []
+    with open(args.native_library_dirs) as f:
+        for line in f:
+            native_library_dir = Path(line.strip())
+            for full_path in native_library_dir.rglob("*"):
+                if full_path.is_file():
+                    native_libraries.append(
+                        _get_native_library(
+                            full_path, full_path.relative_to(native_library_dir)
+                        )
+                    )
+
+    # buck1 sorts native libraries in decreasing file size order, so we do the same.
+    native_libraries.sort(
+        key=lambda native_lib: (-native_lib.size, native_lib.relative_path)
+    )
+
+    with open(args.metadata_output, "w") as f:
+        f.write(
+            "\n".join(
+                [
+                    "{} {} {}".format(
+                        str(native_lib.relative_path),
+                        str(native_lib.size),
+                        str(native_lib.sha256),
+                    )
+                    for native_lib in native_libraries
+                ]
+            )
+        )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/android/tools/sort_pre_dexed_files.py b/buck2/prelude/android/tools/sort_pre_dexed_files.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/sort_pre_dexed_files.py
@@ -0,0 +1,457 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Sorts pre-dexed libraries into primary/secondary dex groups for an Android APK.
+
+This tool replaces the _sort_pre_dexed_files Starlark function that previously
+ran inside the merge_pre_dexed_libs dynamic_output lambda, taking ~3-4 seconds
+in the Starlark interpreter. By running as a compiled Python tool, this
+completes in ~10-50ms.
+
+It reads:
+  - All filter_dex JSON outputs (one per batch)
+  - The APK module graph file (for Voltron builds)
+  - A lib metadata JSON mapping identifier -> owner target label
+
+It outputs a dex_plan.json that the simplified lambda reads to declare
+merge_dexes actions.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import pathlib
+from typing import Optional, TypedDict
+
+
+ROOT_MODULE: str = "dex"
+
+# DEX 64K limit enforcement.
+#
+# Each DEX file is limited to 65536 method_ids, field_ids, and type_ids.
+# Per-library ref counts from the DEX header are summed as a conservative
+# upper bound — the actual merged DEX has fewer refs because shared
+# dependencies are deduplicated.
+#
+# The merge step uses ["--no-desugar", "--no-optimize"], so D8 performs a
+# pure mechanical merge with no synthetic generation. Merged refs are
+# always <= sum of input refs, never more.
+DEX_REF_LIMIT: int = 65536
+
+# Type aliases for the data structures used throughout.
+# A single entry in a dex group: {"id": <lib_id>, "class_names": [<class>, ...]}
+DexEntry = dict[str, object]
+# A group is a list of DexEntry dicts that will be merged into one .dex file.
+DexGroup = list[DexEntry]
+# Per-module sorting result before flattening.
+ModuleSortResult = dict[str, list[DexGroup]]
+
+
+class FilterDexInfo(TypedDict):
+    primary_dex_class_names: list[str]
+    secondary_dex_class_names: list[str]
+    weight_estimate: str
+    method_ref_count: str
+    field_ref_count: str
+    type_ref_count: str
+
+
+# Filter dex data: identifier -> filter info
+FilterDexData = dict[str, FilterDexInfo]
+# Lib metadata: identifier -> owner target label
+LibMetadata = dict[str, str]
+# Target to module mapping
+TargetToModule = dict[str, str]
+# Module metadata: module_name -> {"canary_class_name": ..., "module_deps": [...]}
+ModuleMetadata = dict[str, dict[str, object]]
+# Flattened group for JSON output: {"lib_ids": [...], "class_names": [...]}
+FlatGroup = dict[str, list[str]]
+
+
+def _parse_args() -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description="Sort pre-dexed files into dex merge groups.",
+        fromfile_prefix_chars="@",
+    )
+    parser.add_argument(
+        "--filter-dex-outputs",
+        type=pathlib.Path,
+        nargs="+",
+        required=True,
+        help="Paths to filter_dex JSON output files",
+    )
+    parser.add_argument(
+        "--lib-metadata",
+        type=pathlib.Path,
+        required=True,
+        help="JSON file mapping identifier -> owner target label",
+    )
+    parser.add_argument(
+        "--module-graph",
+        type=pathlib.Path,
+        default=None,
+        help="APK module graph file (for Voltron builds)",
+    )
+    parser.add_argument(
+        "--weight-limit",
+        type=int,
+        required=True,
+        help="Secondary dex weight limit in bytes",
+    )
+    parser.add_argument(
+        "--enable-bootstrap-dexes",
+        action="store_true",
+        default=False,
+        help="Whether to enable bootstrap dexes",
+    )
+    parser.add_argument(
+        "--output",
+        type=pathlib.Path,
+        required=True,
+        help="Output dex plan JSON file",
+    )
+    return parser.parse_args()
+
+
+def _parse_module_graph(
+    module_graph_path: Optional[pathlib.Path],
+) -> tuple[TargetToModule, ModuleMetadata]:
+    """Parse the APK module graph file, returning target-to-module mapping and module metadata."""
+    if module_graph_path is None:
+        return {}, {}
+
+    with open(module_graph_path) as f:
+        lines = f.read().split("\n")
+
+    module_count = int(lines[0])
+    module_infos = lines[1 : module_count + 1]
+    target_to_module_lines = lines[module_count + 1 : -1]
+
+    target_to_module: TargetToModule = {}
+    module_metadata: ModuleMetadata = {}
+
+    for line in module_infos:
+        parts = line.split(" ")
+        module_name = parts[0]
+        canary_class_name = parts[1]
+        module_deps = [dep for dep in parts[2:] if dep]
+        module_metadata[module_name] = {
+            "canary_class_name": canary_class_name,
+            "module_deps": module_deps,
+        }
+
+    for line in target_to_module_lines:
+        if not line:
+            continue
+        target, module = line.split(" ")
+        target_to_module[target] = module
+
+    return target_to_module, module_metadata
+
+
+def _assign_to_dex(
+    dest: list[DexGroup],
+    module: str,
+    lib_id: str,
+    weight_estimate: int,
+    dex_class_names: list[str],
+    current_size_map: dict[str, int],
+    current_inputs_map: dict[str, DexGroup],
+    dex_weight_limit: Optional[int],
+    method_ref_count: int,
+    field_ref_count: int,
+    type_ref_count: int,
+    current_method_refs_map: dict[str, int],
+    current_field_refs_map: dict[str, int],
+    current_type_refs_map: dict[str, int],
+) -> None:
+    """Assign a lib's classes to a dex group, starting a new group if limits exceeded."""
+    if len(dex_class_names) == 0:
+        return
+
+    current_size = current_size_map.get(module, 0)
+    current_method_refs = current_method_refs_map.get(module, 0)
+    current_field_refs = current_field_refs_map.get(module, 0)
+    current_type_refs = current_type_refs_map.get(module, 0)
+
+    should_start_new_dex = False
+    if dex_weight_limit is not None:
+        if current_size + weight_estimate > dex_weight_limit:
+            should_start_new_dex = True
+        if current_method_refs + method_ref_count > DEX_REF_LIMIT:
+            should_start_new_dex = True
+        if current_field_refs + field_ref_count > DEX_REF_LIMIT:
+            should_start_new_dex = True
+        if current_type_refs + type_ref_count > DEX_REF_LIMIT:
+            should_start_new_dex = True
+
+    # Guard: only split when dex_weight_limit is not None.
+    # For primary dex without bootstrap, dex_weight_limit is None.
+    # Extra primary groups become bootstrap dexes in assets/
+    # (dex_rules.bzl primary_dex_inputs[1:]), without bootstrap
+    # classloader -> ClassNotFoundException, metadata numbering
+    # wrong -> mismatched filenames.
+    if should_start_new_dex:
+        current_size = 0
+        current_method_refs = 0
+        current_field_refs = 0
+        current_type_refs = 0
+        current_inputs_map[module] = []
+
+    current_inputs = current_inputs_map.setdefault(module, [])
+    if len(current_inputs) == 0:
+        dest.append(current_inputs)
+
+    current_size_map[module] = current_size + weight_estimate
+    current_method_refs_map[module] = current_method_refs + method_ref_count
+    current_field_refs_map[module] = current_field_refs + field_ref_count
+    current_type_refs_map[module] = current_type_refs + type_ref_count
+    current_inputs.append({"id": lib_id, "class_names": dex_class_names})
+
+
+def _organize_lib(
+    dest: list[DexGroup],
+    module: str,
+    lib_id: str,
+    weight_estimate: int,
+    dex_class_names: list[str],
+    current_size_map: dict[str, int],
+    current_inputs_map: dict[str, DexGroup],
+    dex_weight_limit: Optional[int],
+    method_ref_count: int,
+    field_ref_count: int,
+    type_ref_count: int,
+    current_method_refs_map: dict[str, int],
+    current_field_refs_map: dict[str, int],
+    current_type_refs_map: dict[str, int],
+) -> None:
+    """Organize a lib into dex groups, chunking classes if weight or ref counts exceed limits."""
+    if len(dex_class_names) == 0:
+        return
+
+    is_oversized = False
+    if dex_weight_limit is not None:
+        if weight_estimate > dex_weight_limit:
+            is_oversized = True
+        if method_ref_count > DEX_REF_LIMIT:
+            is_oversized = True
+        if field_ref_count > DEX_REF_LIMIT:
+            is_oversized = True
+        if type_ref_count > DEX_REF_LIMIT:
+            is_oversized = True
+
+    if is_oversized:
+        num_classes = len(dex_class_names)
+        chunks = max(
+            weight_estimate / dex_weight_limit if dex_weight_limit else 1,
+            method_ref_count / DEX_REF_LIMIT if method_ref_count > DEX_REF_LIMIT else 1,
+            field_ref_count / DEX_REF_LIMIT if field_ref_count > DEX_REF_LIMIT else 1,
+            type_ref_count / DEX_REF_LIMIT if type_ref_count > DEX_REF_LIMIT else 1,
+        )
+        chunk_size = max(1, int(num_classes // chunks))
+        for start_index in range(0, num_classes, chunk_size):
+            end_index = min(start_index + chunk_size, num_classes)
+            chunked = dex_class_names[start_index:end_index]
+            _assign_to_dex(
+                dest,
+                module,
+                lib_id,
+                weight_estimate,
+                chunked,
+                current_size_map,
+                current_inputs_map,
+                dex_weight_limit,
+                method_ref_count,
+                field_ref_count,
+                type_ref_count,
+                current_method_refs_map,
+                current_field_refs_map,
+                current_type_refs_map,
+            )
+    else:
+        _assign_to_dex(
+            dest,
+            module,
+            lib_id,
+            weight_estimate,
+            dex_class_names,
+            current_size_map,
+            current_inputs_map,
+            dex_weight_limit,
+            method_ref_count,
+            field_ref_count,
+            type_ref_count,
+            current_method_refs_map,
+            current_field_refs_map,
+            current_type_refs_map,
+        )
+
+
+def _sort_pre_dexed_files(
+    filter_dex_data: FilterDexData,
+    lib_metadata: LibMetadata,
+    target_to_module: TargetToModule,
+    weight_limit: int,
+    enable_bootstrap_dexes: bool,
+) -> dict[str, ModuleSortResult]:
+    """
+    Sort pre-dexed files into primary and secondary dex groups per module.
+
+    This is a Python port of the _sort_pre_dexed_files Starlark function
+    from dex_rules.bzl.
+    """
+    sorted_inputs: dict[str, ModuleSortResult] = {}
+
+    current_primary_dex_size: dict[str, int] = {}
+    current_primary_dex_inputs: dict[str, DexGroup] = {}
+    current_secondary_dex_size: dict[str, int] = {}
+    current_secondary_dex_inputs: dict[str, DexGroup] = {}
+
+    current_primary_method_refs: dict[str, int] = {}
+    current_primary_field_refs: dict[str, int] = {}
+    current_primary_type_refs: dict[str, int] = {}
+    current_secondary_method_refs: dict[str, int] = {}
+    current_secondary_field_refs: dict[str, int] = {}
+    current_secondary_type_refs: dict[str, int] = {}
+
+    # Process libs in the same order as the original Starlark code, which iterates
+    # pre_dexed_libs in order. lib_metadata preserves this order (written from
+    # pre_dexed_libs iteration). We iterate lib_metadata keys and look up filter data.
+    for identifier in lib_metadata:
+        filter_info = filter_dex_data.get(identifier)
+        if filter_info is None:
+            continue
+        owner_target = lib_metadata[identifier]
+
+        module = target_to_module.get(owner_target, ROOT_MODULE)
+        if module not in sorted_inputs:
+            sorted_inputs[module] = {
+                "primary_groups": [],
+                "secondary_groups": [],
+            }
+
+        primary_dex_class_names: list[str] = filter_info["primary_dex_class_names"]
+        secondary_dex_class_names: list[str] = filter_info["secondary_dex_class_names"]
+        weight_estimate = int(filter_info["weight_estimate"])
+        lib_method_refs = int(filter_info["method_ref_count"])
+        lib_field_refs = int(filter_info["field_ref_count"])
+        lib_type_refs = int(filter_info["type_ref_count"])
+
+        module_inputs = sorted_inputs[module]
+
+        if len(primary_dex_class_names) > 0 and module != ROOT_MODULE:
+            # Non-root modules shouldn't have primary dex classes; move to secondary
+            secondary_dex_class_names = (
+                secondary_dex_class_names + primary_dex_class_names
+            )
+            primary_dex_class_names = []
+
+        # Organize primary dex classes
+        _organize_lib(
+            module_inputs["primary_groups"],
+            module,
+            identifier,
+            weight_estimate,
+            primary_dex_class_names,
+            current_primary_dex_size,
+            current_primary_dex_inputs,
+            weight_limit if enable_bootstrap_dexes else None,
+            lib_method_refs,
+            lib_field_refs,
+            lib_type_refs,
+            current_primary_method_refs,
+            current_primary_field_refs,
+            current_primary_type_refs,
+        )
+
+        # Organize secondary dex classes
+        _organize_lib(
+            module_inputs["secondary_groups"],
+            module,
+            identifier,
+            weight_estimate,
+            secondary_dex_class_names,
+            current_secondary_dex_size,
+            current_secondary_dex_inputs,
+            weight_limit,
+            lib_method_refs,
+            lib_field_refs,
+            lib_type_refs,
+            current_secondary_method_refs,
+            current_secondary_field_refs,
+            current_secondary_type_refs,
+        )
+
+    return sorted_inputs
+
+
+def _flatten_groups(groups: list[DexGroup]) -> list[FlatGroup]:
+    """Convert list of [{id, class_names}, ...] to {lib_ids: [...], class_names: [...]}."""
+    result: list[FlatGroup] = []
+    for group in groups:
+        lib_ids: list[str] = [str(entry["id"]) for entry in group]
+        class_names: list[str] = []
+        for entry in group:
+            # pyre-ignore[6]: entry["class_names"] is always list[str]
+            class_names.extend(entry["class_names"])
+        result.append({"lib_ids": lib_ids, "class_names": class_names})
+    return result
+
+
+def main() -> None:
+    args = _parse_args()
+
+    # Read all filter_dex JSON outputs and merge them
+    merged_filter_data: FilterDexData = {}
+    for filter_output_path in args.filter_dex_outputs:
+        with open(filter_output_path) as f:
+            batch_data = json.load(f)
+        merged_filter_data.update(batch_data)
+
+    # Read lib metadata (identifier -> owner target label)
+    with open(args.lib_metadata) as f:
+        lib_metadata: LibMetadata = json.load(f)
+
+    # Parse module graph
+    target_to_module, module_metadata = _parse_module_graph(args.module_graph)
+
+    # Sort pre-dexed files into groups
+    sorted_inputs = _sort_pre_dexed_files(
+        merged_filter_data,
+        lib_metadata,
+        target_to_module,
+        args.weight_limit,
+        args.enable_bootstrap_dexes,
+    )
+
+    # Flatten groups for JSON output
+    modules_output = []
+    for module, data in sorted_inputs.items():
+        modules_output.append(
+            {
+                "module": module,
+                "primary_groups": _flatten_groups(data["primary_groups"]),
+                "secondary_groups": _flatten_groups(data["secondary_groups"]),
+            }
+        )
+
+    plan = {
+        "modules": modules_output,
+        "module_metadata": module_metadata,
+    }
+
+    with open(args.output, "w") as f:
+        json.dump(plan, f)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/android/tools/tests/BUCK b/buck2/prelude/android/tools/tests/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/tests/BUCK
@@ -0,0 +1,31 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+prelude = native
+
+prelude.python_test(
+    name = "test_sort_pre_dexed_files",
+    srcs = ["test_sort_pre_dexed_files.py"],
+    deps = [
+        "prelude//android/tools:sort_pre_dexed_files_lib",
+    ],
+)
+
+prelude.python_test(
+    name = "test_filter_dex",
+    srcs = ["test_filter_dex.py"],
+    deps = [
+        "prelude//android/tools:filter_dex_lib",
+    ],
+)
+
+prelude.python_test(
+    name = "test_combine_apk_with_relinked_libs",
+    srcs = ["test_combine_apk_with_relinked_libs.py"],
+    deps = [
+        "prelude//android/tools:combine_apk_with_relinked_libs_lib",
+    ],
+)
diff --git a/buck2/prelude/android/tools/tests/test_combine_apk_with_relinked_libs.py b/buck2/prelude/android/tools/tests/test_combine_apk_with_relinked_libs.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/tests/test_combine_apk_with_relinked_libs.py
@@ -0,0 +1,284 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Tests for combine_apk_with_relinked_libs.py.
+
+Covers the core replacement logic: flat ZIP .so replacement, nested ZIP/JAR
+replacement, error on unreplaced libraries, and the empty-mapping passthrough.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import os
+import tempfile
+import unittest
+import zipfile
+
+from android.tools.combine_apk_with_relinked_libs import (
+    _build_relinked_lookup,
+    _find_matching_key,
+    _maybe_rebuild_inner_zip,
+    main,
+)
+
+
+def _make_so_bytes(tag: str) -> bytes:
+    """Return distinguishable fake .so content."""
+    return f"ELF-{tag}".encode()
+
+
+class BuildRelinkedLookupTest(unittest.TestCase):
+    """Tests for _build_relinked_lookup."""
+
+    def test_maps_existing_files(self) -> None:
+        with tempfile.TemporaryDirectory() as d:
+            abi_dir = os.path.join(d, "arm64-v8a")
+            os.makedirs(abi_dir)
+            so_path = os.path.join(abi_dir, "libfoo.so")
+            with open(so_path, "wb") as f:
+                f.write(b"data")
+
+            result = _build_relinked_lookup(["arm64-v8a/libfoo.so"], d)
+            self.assertEqual(result, {"arm64-v8a/libfoo.so": so_path})
+
+    def test_raises_on_missing_files(self) -> None:
+        with tempfile.TemporaryDirectory() as d:
+            with self.assertRaises(RuntimeError):
+                _build_relinked_lookup(["arm64-v8a/libmissing.so"], d)
+
+    def test_empty_mapping(self) -> None:
+        with tempfile.TemporaryDirectory() as d:
+            result = _build_relinked_lookup([], d)
+            self.assertEqual(result, {})
+
+
+class FindMatchingKeyTest(unittest.TestCase):
+    """Tests for _find_matching_key."""
+
+    def test_exact_match(self) -> None:
+        lookup = {"arm64-v8a/libfoo.so": "/path"}
+        self.assertEqual(
+            _find_matching_key("arm64-v8a/libfoo.so", lookup), "arm64-v8a/libfoo.so"
+        )
+
+    def test_suffix_match(self) -> None:
+        lookup = {"arm64-v8a/libfoo.so": "/path"}
+        self.assertEqual(
+            _find_matching_key("lib/arm64-v8a/libfoo.so", lookup),
+            "arm64-v8a/libfoo.so",
+        )
+
+    def test_deep_suffix_match(self) -> None:
+        lookup = {"arm64-v8a/libfoo.so": "/path"}
+        self.assertEqual(
+            _find_matching_key("assets/module/lib/arm64-v8a/libfoo.so", lookup),
+            "arm64-v8a/libfoo.so",
+        )
+
+    def test_no_match(self) -> None:
+        lookup = {"arm64-v8a/libfoo.so": "/path"}
+        self.assertIsNone(_find_matching_key("arm64-v8a/libbar.so", lookup))
+
+    def test_partial_name_no_false_match(self) -> None:
+        lookup = {"arm64-v8a/libfoo.so": "/path"}
+        # "xarm64-v8a/libfoo.so" should NOT match because "/" separator is required
+        self.assertIsNone(_find_matching_key("xarm64-v8a/libfoo.so", lookup))
+
+
+class MaybeRebuildInnerZipTest(unittest.TestCase):
+    """Tests for _maybe_rebuild_inner_zip."""
+
+    def test_returns_none_when_no_match(self) -> None:
+        buf = io.BytesIO()
+        with zipfile.ZipFile(buf, "w") as zf:
+            zf.writestr("lib/arm64-v8a/libbar.so", b"data")
+        lookup = {"arm64-v8a/libfoo.so": "/path"}
+        self.assertIsNone(_maybe_rebuild_inner_zip(buf.getvalue(), lookup))
+
+    def test_returns_none_for_bad_zip(self) -> None:
+        lookup = {"arm64-v8a/libfoo.so": "/path"}
+        self.assertIsNone(_maybe_rebuild_inner_zip(b"not a zip", lookup))
+
+    def test_replaces_matching_entry(self) -> None:
+        original = _make_so_bytes("original")
+        relinked = _make_so_bytes("relinked")
+
+        buf = io.BytesIO()
+        with zipfile.ZipFile(buf, "w") as zf:
+            zf.writestr("lib/arm64-v8a/libfoo.so", original)
+            zf.writestr("classes.dex", b"dex-data")
+
+        with tempfile.TemporaryDirectory() as d:
+            abi_dir = os.path.join(d, "arm64-v8a")
+            os.makedirs(abi_dir)
+            with open(os.path.join(abi_dir, "libfoo.so"), "wb") as f:
+                f.write(relinked)
+
+            lookup = {"arm64-v8a/libfoo.so": os.path.join(abi_dir, "libfoo.so")}
+            result = _maybe_rebuild_inner_zip(buf.getvalue(), lookup)
+
+        self.assertIsNotNone(result)
+        result_bytes, replaced = result
+        self.assertIn("arm64-v8a/libfoo.so", replaced)
+
+        with zipfile.ZipFile(io.BytesIO(result_bytes), "r") as zout:
+            self.assertEqual(zout.read("lib/arm64-v8a/libfoo.so"), relinked)
+            self.assertEqual(zout.read("classes.dex"), b"dex-data")
+
+
+class MainIntegrationTest(unittest.TestCase):
+    """Integration tests for the main() entry point."""
+
+    def _run_combine(
+        self,
+        tmpdir: str,
+        input_entries: dict[str, bytes],
+        mapping: list[str],
+        relinked_files: dict[str, bytes],
+    ) -> str:
+        """Build input APK, mapping JSON, relinked libs dir, run main(), return output path."""
+        # Create input APK
+        input_path = os.path.join(tmpdir, "input.apk")
+        with zipfile.ZipFile(input_path, "w") as zf:
+            for name, data in input_entries.items():
+                zf.writestr(name, data)
+
+        # Create relinked libs directory
+        relinked_dir = os.path.join(tmpdir, "relinked_libs")
+        for rel_path, data in relinked_files.items():
+            full_path = os.path.join(relinked_dir, rel_path)
+            os.makedirs(os.path.dirname(full_path), exist_ok=True)
+            with open(full_path, "wb") as f:
+                f.write(data)
+
+        # Create mapping JSON
+        mapping_path = os.path.join(tmpdir, "mapping.json")
+        with open(mapping_path, "w") as f:
+            json.dump(mapping, f)
+
+        output_path = os.path.join(tmpdir, "output.apk")
+
+        import sys
+
+        old_argv = sys.argv
+        sys.argv = [
+            "combine_apk_with_relinked_libs.py",
+            "--input",
+            input_path,
+            "--relinked-libs-dir",
+            relinked_dir,
+            "--mapping",
+            mapping_path,
+            "--output",
+            output_path,
+        ]
+        try:
+            main()
+        finally:
+            sys.argv = old_argv
+
+        return output_path
+
+    def test_flat_so_replacement(self) -> None:
+        """Standard lib/<abi>/<soname> entries are replaced."""
+        original = _make_so_bytes("original")
+        relinked = _make_so_bytes("relinked")
+
+        with tempfile.TemporaryDirectory() as tmpdir:
+            output = self._run_combine(
+                tmpdir,
+                input_entries={
+                    "lib/arm64-v8a/libfoo.so": original,
+                    "classes.dex": b"dex-data",
+                },
+                mapping=["arm64-v8a/libfoo.so"],
+                relinked_files={"arm64-v8a/libfoo.so": relinked},
+            )
+
+            with zipfile.ZipFile(output, "r") as zf:
+                self.assertEqual(zf.read("lib/arm64-v8a/libfoo.so"), relinked)
+                self.assertEqual(zf.read("classes.dex"), b"dex-data")
+
+    def test_nested_jar_replacement(self) -> None:
+        """Libraries inside nested JARs are replaced."""
+        original = _make_so_bytes("original")
+        relinked = _make_so_bytes("relinked")
+
+        inner_jar = io.BytesIO()
+        with zipfile.ZipFile(inner_jar, "w") as zf:
+            zf.writestr("lib/arm64-v8a/libfoo.so", original)
+
+        with tempfile.TemporaryDirectory() as tmpdir:
+            output = self._run_combine(
+                tmpdir,
+                input_entries={
+                    "module.jar": inner_jar.getvalue(),
+                    "classes.dex": b"dex-data",
+                },
+                mapping=["arm64-v8a/libfoo.so"],
+                relinked_files={"arm64-v8a/libfoo.so": relinked},
+            )
+
+            with zipfile.ZipFile(output, "r") as zf:
+                inner_bytes = zf.read("module.jar")
+                with zipfile.ZipFile(io.BytesIO(inner_bytes), "r") as inner:
+                    self.assertEqual(inner.read("lib/arm64-v8a/libfoo.so"), relinked)
+
+    def test_empty_mapping_copies_input(self) -> None:
+        """When the mapping is empty, the output should be a copy of the input."""
+        with tempfile.TemporaryDirectory() as tmpdir:
+            input_path = os.path.join(tmpdir, "input.apk")
+            with zipfile.ZipFile(input_path, "w") as zf:
+                zf.writestr("classes.dex", b"dex-data")
+
+            mapping_path = os.path.join(tmpdir, "mapping.json")
+            with open(mapping_path, "w") as f:
+                json.dump([], f)
+
+            # Create an empty relinked dir
+            relinked_dir = os.path.join(tmpdir, "relinked_libs")
+            os.makedirs(relinked_dir)
+
+            output_path = os.path.join(tmpdir, "output.apk")
+
+            import sys
+
+            old_argv = sys.argv
+            sys.argv = [
+                "combine_apk_with_relinked_libs.py",
+                "--input",
+                input_path,
+                "--relinked-libs-dir",
+                relinked_dir,
+                "--mapping",
+                mapping_path,
+                "--output",
+                output_path,
+            ]
+            try:
+                main()
+            finally:
+                sys.argv = old_argv
+
+            with zipfile.ZipFile(output_path, "r") as zf:
+                self.assertEqual(zf.read("classes.dex"), b"dex-data")
+
+    def test_unreplaced_library_raises(self) -> None:
+        """If a mapped library is not found in the input APK, a RuntimeError is raised."""
+        with tempfile.TemporaryDirectory() as tmpdir:
+            with self.assertRaises(RuntimeError):
+                self._run_combine(
+                    tmpdir,
+                    input_entries={
+                        "classes.dex": b"dex-data",
+                    },
+                    mapping=["arm64-v8a/libfoo.so"],
+                    relinked_files={"arm64-v8a/libfoo.so": b"relinked"},
+                )
diff --git a/buck2/prelude/android/tools/tests/test_filter_dex.py b/buck2/prelude/android/tools/tests/test_filter_dex.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/tests/test_filter_dex.py
@@ -0,0 +1,114 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Tests for filter_dex.py.
+
+Covers primary-dex membership for the synthetic classes D8 creates. The synthetic names used
+here deliberately do not resemble D8's actual mangling -- membership must come from the
+synthetic-to-context map D8 reports, never from the shape of the name.
+"""
+
+from __future__ import annotations
+
+import os
+import tempfile
+import unittest
+
+from android.tools.filter_dex import (
+    _belongs_in_primary_dex,
+    _parse_synthetic_contexts,
+    _resolve_synthesizing_context,
+    ClassNameFilter,
+)
+
+
+class ParseSyntheticContextsTest(unittest.TestCase):
+    def _parse(self, contents: str) -> dict[str, str]:
+        with tempfile.TemporaryDirectory() as tmp:
+            path = os.path.join(tmp, "synthetic_contexts.txt")
+            with open(path, "w") as f:
+                f.write(contents)
+            return _parse_synthetic_contexts(path)
+
+    def test_parses_pairs(self) -> None:
+        self.assertEqual(
+            self._parse("a/zzz0 a/Foo\nb/zzz1 b/Bar\n"),
+            {"a/zzz0": "a/Foo", "b/zzz1": "b/Bar"},
+        )
+
+    def test_empty_file_yields_empty_map(self) -> None:
+        self.assertEqual(self._parse(""), {})
+
+    def test_blank_lines_are_skipped(self) -> None:
+        self.assertEqual(self._parse("\na/zzz0 a/Foo\n\n"), {"a/zzz0": "a/Foo"})
+
+    def test_line_without_context_is_rejected(self) -> None:
+        with self.assertRaises(ValueError):
+            self._parse("a/zzz0\n")
+
+
+class ResolveSynthesizingContextTest(unittest.TestCase):
+    def test_non_synthetic_resolves_to_itself(self) -> None:
+        self.assertEqual(_resolve_synthesizing_context("a/Foo", {}), "a/Foo")
+
+    def test_single_hop(self) -> None:
+        self.assertEqual(
+            _resolve_synthesizing_context("a/zzz0", {"a/zzz0": "a/Foo"}), "a/Foo"
+        )
+
+    def test_chained_synthetics_resolve_to_the_root_context(self) -> None:
+        # D8 can synthesize from a synthetic, so the chain has to be walked to its end.
+        chain = {"a/zzz1": "a/zzz0", "a/zzz0": "a/Foo"}
+        self.assertEqual(_resolve_synthesizing_context("a/zzz1", chain), "a/Foo")
+
+    def test_cycle_terminates(self) -> None:
+        cycle = {"a/zzz0": "a/zzz1", "a/zzz1": "a/zzz0"}
+        self.assertIn(_resolve_synthesizing_context("a/zzz0", cycle), cycle)
+
+
+class BelongsInPrimaryDexTest(unittest.TestCase):
+    def _belongs(self, java_class, patterns, synthetic_to_context=None) -> bool:
+        return _belongs_in_primary_dex(
+            java_class, ClassNameFilter(patterns), synthetic_to_context or {}
+        )
+
+    def test_class_matching_a_prefix_pattern(self) -> None:
+        self.assertTrue(self._belongs("a/Foo", ["^a/"]))
+
+    def test_class_matching_a_suffix_pattern(self) -> None:
+        self.assertTrue(self._belongs("a/Foo", ["Foo^"]))
+
+    def test_class_matching_a_substring_pattern(self) -> None:
+        self.assertTrue(self._belongs("a/Foo", ["/Fo"]))
+
+    def test_class_matching_a_regex_pattern(self) -> None:
+        self.assertTrue(self._belongs("a/Foo", ["^-a/F.*"]))
+
+    def test_unmatched_class_stays_out(self) -> None:
+        self.assertFalse(self._belongs("b/Bar", ["^a/"]))
+
+    def test_synthetic_follows_its_context_into_the_primary_dex(self) -> None:
+        self.assertTrue(self._belongs("b/zzz0", ["^a/"], {"b/zzz0": "a/Foo"}))
+
+    def test_synthetic_of_a_secondary_class_stays_out(self) -> None:
+        self.assertFalse(self._belongs("b/zzz0", ["^a/"], {"b/zzz0": "b/Bar"}))
+
+    def test_chained_synthetic_follows_its_root_context(self) -> None:
+        chain = {"b/zzz1": "b/zzz0", "b/zzz0": "a/Foo"}
+        self.assertTrue(self._belongs("b/zzz1", ["^a/"], chain))
+
+    def test_pattern_naming_a_synthetic_directly_still_matches(self) -> None:
+        # Some primary_dex_patterns name a D8 synthetic outright. Those must keep working even
+        # though the synthetic's context is not itself in the primary dex.
+        self.assertTrue(
+            self._belongs(
+                "androidx/Foo$ExternalSyntheticLambda0",
+                ["^androidx/Foo$ExternalSyntheticLambda0^"],
+                {"androidx/Foo$ExternalSyntheticLambda0": "androidx/Foo"},
+            )
+        )
diff --git a/buck2/prelude/android/tools/tests/test_sort_pre_dexed_files.py b/buck2/prelude/android/tools/tests/test_sort_pre_dexed_files.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/tests/test_sort_pre_dexed_files.py
@@ -0,0 +1,725 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Tests for sort_pre_dexed_files.py — the Python tool that replaces the
+_sort_pre_dexed_files Starlark function in dex_rules.bzl.
+
+The tool reads filter_dex JSON outputs and a lib metadata JSON, then sorts
+pre-dexed libraries into primary/secondary dex groups per module, producing
+a dex_plan.json consumed by the merge_pre_dexed_libs dynamic lambda.
+
+Test structure:
+  - SortPreDexedFilesTest: unit tests for the core sorting logic
+  - ParseModuleGraphTest: unit tests for module graph file parsing
+  - EndToEndToolTest: integration tests running the tool as a subprocess
+"""
+
+import json
+import os
+import subprocess
+import tempfile
+import unittest
+
+from android.tools.sort_pre_dexed_files import (
+    _flatten_groups,
+    _parse_module_graph,
+    _sort_pre_dexed_files,
+)
+
+# Path to the tool script, relative to the link-tree layout
+_TOOL_MODULE_PATH = os.path.join(
+    os.path.dirname(__file__), "..", "sort_pre_dexed_files.py"
+)
+
+_DEFAULT_WEIGHT_LIMIT = 12 * 1024 * 1024  # 12 MiB, matches Buck default
+
+_DEFAULT_REF_COUNTS = {
+    "method_ref_count": "0",
+    "field_ref_count": "0",
+    "type_ref_count": "0",
+}
+
+
+def _add_default_ref_counts(filter_data):
+    """Add default zero ref counts to any filter_data entries missing them."""
+    for info in filter_data.values():
+        for key, default_val in _DEFAULT_REF_COUNTS.items():
+            if key not in info:
+                info[key] = default_val
+    return filter_data
+
+
+def _sort(filter_data, lib_metadata, target_to_module=None, **kwargs):
+    """Convenience wrapper with defaults for _sort_pre_dexed_files."""
+    _add_default_ref_counts(filter_data)
+    return _sort_pre_dexed_files(
+        filter_data,
+        lib_metadata,
+        target_to_module or {},
+        weight_limit=kwargs.get("weight_limit", _DEFAULT_WEIGHT_LIMIT),
+        enable_bootstrap_dexes=kwargs.get("enable_bootstrap_dexes", False),
+    )
+
+
+class SortPreDexedFilesTest(unittest.TestCase):
+    """Unit tests for _sort_pre_dexed_files — the core sorting logic.
+
+    The function takes:
+      - filter_data: merged filter_dex JSON (identifier -> class names + weight)
+      - lib_metadata: identifier -> owner target label (controls iteration order)
+      - target_to_module: target -> module name (from module graph)
+      - weight_limit: max bytes per dex group before spilling
+      - enable_bootstrap_dexes: whether to apply weight limit to primary dex too
+
+    It returns: module -> {primary_groups: [...], secondary_groups: [...]}
+    where each group is a list of {id, class_names} entries.
+    """
+
+    # --- Basic grouping ---
+
+    def test_single_lib_primary_and_secondary(self):
+        """A single lib with both primary and secondary classes produces one
+        group in each category under the root module ("dex")."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": ["com.example.Main"],
+                "secondary_dex_class_names": ["com.example.Helper"],
+                "weight_estimate": "1000",
+            },
+        }
+        result = _sort(filter_data, {"lib1": "//apps:lib1"})
+
+        self.assertIn("dex", result)
+        self.assertEqual(len(result["dex"]["primary_groups"]), 1)
+        self.assertEqual(len(result["dex"]["secondary_groups"]), 1)
+        self.assertEqual(
+            result["dex"]["primary_groups"][0][0]["class_names"], ["com.example.Main"]
+        )
+        self.assertEqual(
+            result["dex"]["secondary_groups"][0][0]["class_names"],
+            ["com.example.Helper"],
+        )
+
+    def test_multiple_libs_grouped_under_weight_limit(self):
+        """Multiple small libs whose combined weight is under the limit should
+        land in the same secondary dex group."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.A"],
+                "weight_estimate": "100",
+            },
+            "lib2": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.B"],
+                "weight_estimate": "100",
+            },
+        }
+        result = _sort(filter_data, {"lib1": "//apps:lib1", "lib2": "//apps:lib2"})
+
+        self.assertEqual(len(result["dex"]["secondary_groups"]), 1)
+        self.assertEqual(len(result["dex"]["secondary_groups"][0]), 2)
+
+    def test_empty_class_names_produce_no_groups(self):
+        """Libs with empty primary and secondary class names should not create
+        any dex groups — they are effectively no-ops."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": [],
+                "weight_estimate": "0",
+            },
+        }
+        result = _sort(filter_data, {"lib1": "//apps:lib1"})
+
+        self.assertEqual(len(result.get("dex", {}).get("primary_groups", [])), 0)
+        self.assertEqual(len(result.get("dex", {}).get("secondary_groups", [])), 0)
+
+    # --- Weight-based splitting ---
+
+    def test_weight_limit_splits_secondary_groups(self):
+        """When cumulative weight of libs exceeds the limit, subsequent libs
+        should spill into a new secondary dex group."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.A"],
+                "weight_estimate": "600",
+            },
+            "lib2": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.B"],
+                "weight_estimate": "600",
+            },
+        }
+        result = _sort(
+            filter_data,
+            {"lib1": "//apps:lib1", "lib2": "//apps:lib2"},
+            weight_limit=1000,
+        )
+
+        # lib1 (600) + lib2 (600) = 1200 > 1000 limit
+        self.assertEqual(len(result["dex"]["secondary_groups"]), 2)
+
+    def test_bootstrap_dexes_applies_weight_limit_to_primary(self):
+        """With enable_bootstrap_dexes=True, the weight limit also applies to
+        primary dex groups, splitting them when exceeded."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": ["com.A"],
+                "secondary_dex_class_names": [],
+                "weight_estimate": "600",
+            },
+            "lib2": {
+                "primary_dex_class_names": ["com.B"],
+                "secondary_dex_class_names": [],
+                "weight_estimate": "600",
+            },
+        }
+        result = _sort(
+            filter_data,
+            {"lib1": "//apps:lib1", "lib2": "//apps:lib2"},
+            weight_limit=1000,
+            enable_bootstrap_dexes=True,
+        )
+
+        # 600 + 600 = 1200 > 1000 -> splits into 2 primary groups
+        self.assertEqual(len(result["dex"]["primary_groups"]), 2)
+
+    def test_large_lib_classes_chunked_across_groups(self):
+        """A single lib whose weight exceeds the limit should have its classes
+        chunked across multiple groups. All classes must be preserved."""
+        classes = ["com.Class{}".format(i) for i in range(10)]
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": classes,
+                "weight_estimate": "2500",
+            },
+        }
+        result = _sort(filter_data, {"lib1": "//apps:lib1"}, weight_limit=1000)
+
+        # 2500 > 1000 -> classes chunked across multiple groups
+        self.assertGreater(len(result["dex"]["secondary_groups"]), 1)
+        all_classes = []
+        for group in result["dex"]["secondary_groups"]:
+            for entry in group:
+                all_classes.extend(entry["class_names"])
+        self.assertCountEqual(all_classes, classes)
+
+    # --- Module assignment ---
+
+    def test_non_root_module_primary_classes_moved_to_secondary(self):
+        """Primary dex classes assigned to a non-root module are relocated to
+        that module's secondary dex. Only the root module ("dex") may have
+        primary dex classes."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": ["com.feature.Primary"],
+                "secondary_dex_class_names": ["com.feature.Secondary"],
+                "weight_estimate": "1000",
+            },
+        }
+        result = _sort(
+            filter_data,
+            {"lib1": "//apps:lib1"},
+            target_to_module={"//apps:lib1": "feature_module"},
+        )
+
+        self.assertIn("feature_module", result)
+        self.assertEqual(len(result["feature_module"]["primary_groups"]), 0)
+        all_secondary_classes = []
+        for group in result["feature_module"]["secondary_groups"]:
+            for entry in group:
+                all_secondary_classes.extend(entry["class_names"])
+        self.assertIn("com.feature.Primary", all_secondary_classes)
+        self.assertIn("com.feature.Secondary", all_secondary_classes)
+
+    def test_multiple_modules_separated(self):
+        """Libs assigned to different modules via the target-to-module mapping
+        should be placed in separate module entries."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": ["com.main.Main"],
+                "secondary_dex_class_names": [],
+                "weight_estimate": "1000",
+            },
+            "lib2": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.feature.Impl"],
+                "weight_estimate": "1000",
+            },
+        }
+        result = _sort(
+            filter_data,
+            {"lib1": "//apps:lib1", "lib2": "//apps:lib2"},
+            target_to_module={"//apps:lib1": "dex", "//apps:lib2": "feature1"},
+        )
+
+        self.assertIn("dex", result)
+        self.assertIn("feature1", result)
+        self.assertEqual(len(result["dex"]["primary_groups"]), 1)
+        self.assertEqual(len(result["feature1"]["secondary_groups"]), 1)
+
+    def test_unmapped_target_defaults_to_root_module(self):
+        """Libs whose owner target is not in the target-to-module mapping
+        should default to the root module ("dex")."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.Unknown"],
+                "weight_estimate": "100",
+            },
+        }
+        # target_to_module has an entry for a different target, not lib1's owner
+        result = _sort(
+            filter_data,
+            {"lib1": "//apps:lib1"},
+            target_to_module={"//other:target": "feature1"},
+        )
+
+        self.assertIn("dex", result)
+        self.assertNotIn("feature1", result)
+        self.assertEqual(len(result["dex"]["secondary_groups"]), 1)
+
+    # --- Ref-count-based splitting ---
+
+    def test_ref_count_splits_secondary_groups(self):
+        """When cumulative method ref count exceeds DEX_REF_LIMIT (65536),
+        subsequent libs should spill into a new secondary dex group, even
+        if weight is well under the weight limit."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.A"],
+                "weight_estimate": "100",
+                "method_ref_count": "40000",
+                "field_ref_count": "0",
+                "type_ref_count": "0",
+            },
+            "lib2": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.B"],
+                "weight_estimate": "100",
+                "method_ref_count": "40000",
+                "field_ref_count": "0",
+                "type_ref_count": "0",
+            },
+        }
+        result = _sort(
+            filter_data,
+            {"lib1": "//apps:lib1", "lib2": "//apps:lib2"},
+            weight_limit=_DEFAULT_WEIGHT_LIMIT,
+        )
+
+        # 40000 + 40000 = 80000 > 65536 -> splits into 2 secondary groups
+        self.assertEqual(len(result["dex"]["secondary_groups"]), 2)
+
+    def test_high_ref_counts_do_not_split_primary_without_bootstrap(self):
+        """Without enable_bootstrap_dexes, primary dex groups must NOT be
+        split even when ref counts exceed the limit. Splitting primary
+        without the bootstrap classloader causes ClassNotFoundException."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": ["com.A"],
+                "secondary_dex_class_names": [],
+                "weight_estimate": "100",
+                "method_ref_count": "40000",
+                "field_ref_count": "0",
+                "type_ref_count": "0",
+            },
+            "lib2": {
+                "primary_dex_class_names": ["com.B"],
+                "secondary_dex_class_names": [],
+                "weight_estimate": "100",
+                "method_ref_count": "40000",
+                "field_ref_count": "0",
+                "type_ref_count": "0",
+            },
+        }
+        result = _sort(
+            filter_data,
+            {"lib1": "//apps:lib1", "lib2": "//apps:lib2"},
+            weight_limit=_DEFAULT_WEIGHT_LIMIT,
+            enable_bootstrap_dexes=False,
+        )
+
+        # Without bootstrap, primary must stay in a single group
+        self.assertEqual(len(result["dex"]["primary_groups"]), 1)
+
+    def test_large_lib_chunked_by_ref_count(self):
+        """A single lib whose method ref count exceeds DEX_REF_LIMIT should
+        have its classes chunked across multiple groups, similar to
+        weight-based chunking."""
+        classes = ["com.Class{}".format(i) for i in range(10)]
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": classes,
+                "weight_estimate": "100",
+                "method_ref_count": "200000",
+                "field_ref_count": "0",
+                "type_ref_count": "0",
+            },
+        }
+        result = _sort(
+            filter_data, {"lib1": "//apps:lib1"}, weight_limit=_DEFAULT_WEIGHT_LIMIT
+        )
+
+        # 200000 > 65536 -> classes chunked across multiple groups
+        self.assertGreater(len(result["dex"]["secondary_groups"]), 1)
+        all_classes = []
+        for group in result["dex"]["secondary_groups"]:
+            for entry in group:
+                all_classes.extend(entry["class_names"])
+        self.assertCountEqual(all_classes, classes)
+
+    # --- Ordering and skipping ---
+
+    def test_iteration_order_follows_lib_metadata_keys(self):
+        """Libs should be processed in lib_metadata key insertion order, not
+        filter_data order. This is critical for deterministic dex assignment."""
+        filter_data = {
+            "lib_b": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.B"],
+                "weight_estimate": "600",
+            },
+            "lib_a": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.A"],
+                "weight_estimate": "600",
+            },
+        }
+        # lib_a first in metadata -> processed first -> gets first group
+        lib_metadata = {"lib_a": "//apps:lib_a", "lib_b": "//apps:lib_b"}
+        result = _sort(filter_data, lib_metadata, weight_limit=1000)
+
+        self.assertEqual(len(result["dex"]["secondary_groups"]), 2)
+        self.assertEqual(
+            result["dex"]["secondary_groups"][0][0]["class_names"], ["com.A"]
+        )
+        self.assertEqual(
+            result["dex"]["secondary_groups"][1][0]["class_names"], ["com.B"]
+        )
+
+    def test_lib_in_metadata_but_not_filter_data_skipped(self):
+        """Libs present in lib_metadata but absent from filter_data (e.g.,
+        libs with no dex output) should be silently skipped."""
+        filter_data = {
+            "lib1": {
+                "primary_dex_class_names": [],
+                "secondary_dex_class_names": ["com.A"],
+                "weight_estimate": "100",
+            },
+        }
+        # lib2 in metadata but not in filter_data
+        result = _sort(filter_data, {"lib1": "//apps:lib1", "lib2": "//apps:lib2"})
+
+        self.assertEqual(len(result["dex"]["secondary_groups"]), 1)
+        self.assertEqual(result["dex"]["secondary_groups"][0][0]["id"], "lib1")
+
+
+class FlattenGroupsTest(unittest.TestCase):
+    """Unit tests for _flatten_groups — converts the internal per-entry
+    representation [{id, class_names}, ...] into the plan JSON format
+    {lib_ids: [...], class_names: [...]} per group."""
+
+    def test_single_group_single_entry(self):
+        groups = [[{"id": "lib1", "class_names": ["com.A", "com.B"]}]]
+        result = _flatten_groups(groups)
+        self.assertEqual(len(result), 1)
+        self.assertEqual(result[0]["lib_ids"], ["lib1"])
+        self.assertEqual(result[0]["class_names"], ["com.A", "com.B"])
+
+    def test_single_group_multiple_entries(self):
+        """Multiple entries in one group should have their lib_ids and
+        class_names concatenated in order."""
+        groups = [
+            [
+                {"id": "lib1", "class_names": ["com.A"]},
+                {"id": "lib2", "class_names": ["com.B", "com.C"]},
+            ]
+        ]
+        result = _flatten_groups(groups)
+        self.assertEqual(result[0]["lib_ids"], ["lib1", "lib2"])
+        self.assertEqual(result[0]["class_names"], ["com.A", "com.B", "com.C"])
+
+    def test_multiple_groups(self):
+        groups = [
+            [{"id": "lib1", "class_names": ["com.A"]}],
+            [{"id": "lib2", "class_names": ["com.B"]}],
+        ]
+        result = _flatten_groups(groups)
+        self.assertEqual(len(result), 2)
+        self.assertEqual(result[0]["lib_ids"], ["lib1"])
+        self.assertEqual(result[1]["lib_ids"], ["lib2"])
+
+    def test_empty_groups(self):
+        self.assertEqual(_flatten_groups([]), [])
+
+
+class ParseModuleGraphTest(unittest.TestCase):
+    """Unit tests for _parse_module_graph.
+
+    The module graph file format is:
+      Line 0: <module_count>
+      Lines 1..module_count: <module_name> <canary_class> <dep1> <dep2> ...
+      Remaining lines: <target> <module>
+      Last line: empty (trailing newline)
+    """
+
+    def _write_module_graph(self, content):
+        """Write content to a temp file and return its path."""
+        f = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False)
+        f.write(content)
+        f.close()
+        self.addCleanup(os.unlink, f.name)
+        return f.name
+
+    def test_none_returns_empty_dicts(self):
+        target_to_module, module_metadata = _parse_module_graph(None)
+        self.assertEqual(target_to_module, {})
+        self.assertEqual(module_metadata, {})
+
+    def test_simple_graph(self):
+        """Parse a graph with 2 modules and 2 target mappings."""
+        path = self._write_module_graph(
+            "2\n"
+            "dex com/facebook/CanaryClass dex\n"
+            "feature1 com/facebook/feature1/Canary dex\n"
+            "//apps:lib1 dex\n"
+            "//apps:lib2 feature1\n"
+        )
+        target_to_module, module_metadata = _parse_module_graph(path)
+
+        self.assertEqual(
+            target_to_module,
+            {
+                "//apps:lib1": "dex",
+                "//apps:lib2": "feature1",
+            },
+        )
+        self.assertEqual(
+            module_metadata["dex"]["canary_class_name"], "com/facebook/CanaryClass"
+        )
+        self.assertEqual(module_metadata["dex"]["module_deps"], ["dex"])
+        self.assertEqual(module_metadata["feature1"]["module_deps"], ["dex"])
+
+    def test_modules_only_no_target_mappings(self):
+        """A module graph with modules defined but no target-to-module mappings
+        should produce empty target_to_module but populated module_metadata."""
+        path = self._write_module_graph("1\ndex com/CanaryClass dex\n")
+        target_to_module, module_metadata = _parse_module_graph(path)
+
+        self.assertEqual(target_to_module, {})
+        self.assertIn("dex", module_metadata)
+
+    def test_trailing_newline_does_not_drop_last_mapping(self):
+        """The file format ends with a trailing newline. The [:-1] slice in
+        _parse_module_graph strips this empty last line. Verify the last
+        real target mapping is preserved."""
+        path = self._write_module_graph(
+            "1\ndex com/CanaryClass dex\n//apps:last_target dex\n"
+        )
+        target_to_module, _ = _parse_module_graph(path)
+
+        self.assertIn("//apps:last_target", target_to_module)
+        self.assertEqual(target_to_module["//apps:last_target"], "dex")
+
+
+class EndToEndToolTest(unittest.TestCase):
+    """Integration tests running sort_pre_dexed_files.py as a subprocess.
+
+    These verify the full pipeline: arg parsing, file I/O, sorting, and JSON
+    output. They complement the unit tests which test internal functions directly.
+    """
+
+    def _run_tool(
+        self,
+        tmpdir,
+        filter_data_files,
+        lib_metadata,
+        weight_limit=_DEFAULT_WEIGHT_LIMIT,
+        module_graph=None,
+        enable_bootstrap_dexes=False,
+    ):
+        """Write inputs, run the tool, return parsed plan JSON."""
+        # Write filter_dex outputs
+        filter_paths = []
+        for i, data in enumerate(filter_data_files):
+            _add_default_ref_counts(data)
+            path = os.path.join(tmpdir, "filter_output_{}.json".format(i))
+            with open(path, "w") as f:
+                json.dump(data, f)
+            filter_paths.append(path)
+
+        # Write lib metadata
+        metadata_path = os.path.join(tmpdir, "lib_metadata.json")
+        with open(metadata_path, "w") as f:
+            json.dump(lib_metadata, f)
+
+        # Build command
+        output_path = os.path.join(tmpdir, "plan.json")
+        cmd = [
+            "python3",
+            _TOOL_MODULE_PATH,
+            "--filter-dex-outputs",
+            *filter_paths,
+            "--lib-metadata",
+            metadata_path,
+            "--weight-limit",
+            str(weight_limit),
+            "--output",
+            output_path,
+        ]
+        if module_graph:
+            graph_path = os.path.join(tmpdir, "module_graph.txt")
+            with open(graph_path, "w") as f:
+                f.write(module_graph)
+            cmd.extend(["--module-graph", graph_path])
+        if enable_bootstrap_dexes:
+            cmd.append("--enable-bootstrap-dexes")
+
+        result = subprocess.run(cmd, capture_output=True, text=True)
+        self.assertEqual(result.returncode, 0, "Tool failed: {}".format(result.stderr))
+
+        with open(output_path) as f:
+            return json.load(f)
+
+    def test_basic_plan_output(self):
+        """Two libs with primary and secondary classes produce a valid plan
+        with correct lib_ids and class_names."""
+        with tempfile.TemporaryDirectory() as tmpdir:
+            plan = self._run_tool(
+                tmpdir,
+                filter_data_files=[
+                    {
+                        "lib1": {
+                            "primary_dex_class_names": ["com.Main"],
+                            "secondary_dex_class_names": ["com.Helper"],
+                            "weight_estimate": "1000",
+                        },
+                        "lib2": {
+                            "primary_dex_class_names": [],
+                            "secondary_dex_class_names": ["com.Utils"],
+                            "weight_estimate": "2000",
+                        },
+                    }
+                ],
+                lib_metadata={"lib1": "//apps:lib1", "lib2": "//apps:lib2"},
+            )
+
+            self.assertEqual(len(plan["modules"]), 1)
+            module = plan["modules"][0]
+            self.assertEqual(module["module"], "dex")
+            self.assertEqual(module["primary_groups"][0]["lib_ids"], ["lib1"])
+            self.assertEqual(module["primary_groups"][0]["class_names"], ["com.Main"])
+            self.assertEqual(len(module["secondary_groups"]), 1)
+            self.assertIn("lib1", module["secondary_groups"][0]["lib_ids"])
+            self.assertIn("lib2", module["secondary_groups"][0]["lib_ids"])
+
+    def test_with_module_graph(self):
+        """Libs are correctly assigned to different modules when a module
+        graph file is provided."""
+        with tempfile.TemporaryDirectory() as tmpdir:
+            plan = self._run_tool(
+                tmpdir,
+                filter_data_files=[
+                    {
+                        "lib1": {
+                            "primary_dex_class_names": ["com.Main"],
+                            "secondary_dex_class_names": [],
+                            "weight_estimate": "1000",
+                        },
+                        "lib2": {
+                            "primary_dex_class_names": [],
+                            "secondary_dex_class_names": ["com.Feature"],
+                            "weight_estimate": "1000",
+                        },
+                    }
+                ],
+                lib_metadata={"lib1": "//apps:lib1", "lib2": "//apps:lib2"},
+                module_graph=(
+                    "2\n"
+                    "dex com/CanaryClass dex\n"
+                    "feature1 com/feature1/Canary dex\n"
+                    "//apps:lib1 dex\n"
+                    "//apps:lib2 feature1\n"
+                ),
+            )
+
+            modules_by_name = {m["module"]: m for m in plan["modules"]}
+            self.assertIn("dex", modules_by_name)
+            self.assertIn("feature1", modules_by_name)
+            self.assertEqual(
+                modules_by_name["dex"]["primary_groups"][0]["lib_ids"], ["lib1"]
+            )
+            self.assertEqual(
+                modules_by_name["feature1"]["secondary_groups"][0]["lib_ids"], ["lib2"]
+            )
+            self.assertIn("feature1", plan["module_metadata"])
+
+    def test_multiple_filter_dex_batches(self):
+        """The tool should merge multiple --filter-dex-outputs files. Each
+        file represents a batch of libs processed by filter_dex in parallel."""
+        with tempfile.TemporaryDirectory() as tmpdir:
+            batch1 = {
+                "lib1": {
+                    "primary_dex_class_names": ["com.A"],
+                    "secondary_dex_class_names": [],
+                    "weight_estimate": "100",
+                },
+            }
+            batch2 = {
+                "lib2": {
+                    "primary_dex_class_names": [],
+                    "secondary_dex_class_names": ["com.B"],
+                    "weight_estimate": "100",
+                },
+            }
+            plan = self._run_tool(
+                tmpdir,
+                filter_data_files=[batch1, batch2],
+                lib_metadata={"lib1": "//apps:lib1", "lib2": "//apps:lib2"},
+            )
+
+            module = plan["modules"][0]
+            # lib1 in primary, lib2 in secondary — both batches merged
+            self.assertEqual(module["primary_groups"][0]["lib_ids"], ["lib1"])
+            self.assertEqual(module["secondary_groups"][0]["lib_ids"], ["lib2"])
+
+    def test_bootstrap_dexes_cli_flag(self):
+        """The --enable-bootstrap-dexes flag should apply weight limit to
+        primary dex groups, splitting them when exceeded."""
+        with tempfile.TemporaryDirectory() as tmpdir:
+            plan = self._run_tool(
+                tmpdir,
+                filter_data_files=[
+                    {
+                        "lib1": {
+                            "primary_dex_class_names": ["com.A"],
+                            "secondary_dex_class_names": [],
+                            "weight_estimate": "600",
+                        },
+                        "lib2": {
+                            "primary_dex_class_names": ["com.B"],
+                            "secondary_dex_class_names": [],
+                            "weight_estimate": "600",
+                        },
+                    }
+                ],
+                lib_metadata={"lib1": "//apps:lib1", "lib2": "//apps:lib2"},
+                weight_limit=1000,
+                enable_bootstrap_dexes=True,
+            )
+
+            module = plan["modules"][0]
+            # 600 + 600 > 1000 -> 2 primary groups
+            self.assertEqual(len(module["primary_groups"]), 2)
diff --git a/buck2/prelude/android/tools/unpack_aar.py b/buck2/prelude/android/tools/unpack_aar.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/tools/unpack_aar.py
@@ -0,0 +1,195 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import pathlib
+import platform
+import shutil
+import zipfile
+from tempfile import TemporaryDirectory
+
+import utils
+
+
+CLASSES_JAR_FILE_NAME = "classes.jar"
+ANNOTATIONS_ZIP_FILE_NAME = "annotations.zip"
+LIBS_DIR_NAME = "libs"
+
+
+def _parse_args():
+    parser = argparse.ArgumentParser(
+        description="Tool to unpack an aar for android_prebuilt_aar."
+    )
+
+    parser.add_argument(
+        "--aar", type=pathlib.Path, required=True, help="a path to the aar to unpack"
+    )
+    parser.add_argument(
+        "--manifest-path",
+        type=pathlib.Path,
+        required=True,
+        help="a path to the manifest that is unpacked",
+    )
+    parser.add_argument(
+        "--all-classes-jar-path",
+        type=pathlib.Path,
+        required=True,
+        help="a path to the single output jar containing all the Java classes that this aar contains",
+    )
+    parser.add_argument(
+        "--r-dot-txt-path",
+        type=pathlib.Path,
+        required=True,
+        help="a path to the R.txt that is unpacked",
+    )
+    parser.add_argument(
+        "--res-path",
+        type=pathlib.Path,
+        required=True,
+        help="a path to the resources that are unpacked",
+    )
+    parser.add_argument(
+        "--assets-path",
+        type=pathlib.Path,
+        required=True,
+        help="a path to the assets that are unpacked",
+    )
+    parser.add_argument(
+        "--jni-path",
+        type=pathlib.Path,
+        required=True,
+        help="a path to the native lib directory that is unpacked",
+    )
+    parser.add_argument(
+        "--annotation-jars-dir",
+        type=pathlib.Path,
+        required=True,
+        help="a path to a directory where the external annotations.zip may be copied if present",
+    )
+    parser.add_argument(
+        "--proguard-config-path",
+        type=pathlib.Path,
+        required=True,
+        help="a path to the proguard config that is unpacked",
+    )
+    parser.add_argument(
+        "--lint-jar-path",
+        type=pathlib.Path,
+        required=True,
+        help="a path to the lint jar file that is unpacked",
+    )
+    parser.add_argument(
+        "--jar-builder-tool",
+        type=str,
+        required=True,
+        help="tool for building jars",
+    )
+
+    return parser.parse_args()
+
+
+def main():
+    args = _parse_args()
+
+    aar_path = args.aar
+    manifest_path = args.manifest_path
+    all_classes_path = args.all_classes_jar_path
+    res_path = args.res_path
+    assets_path = args.assets_path
+    jni_path = args.jni_path
+    r_dot_txt_path = args.r_dot_txt_path
+    annotation_jars_dir = args.annotation_jars_dir
+    proguard_config_path = args.proguard_config_path
+    lint_jar_path = args.lint_jar_path
+    jar_builder_tool = args.jar_builder_tool
+
+    with TemporaryDirectory() as temp_dir:
+        unpack_dir = pathlib.Path(temp_dir)
+        with zipfile.ZipFile(aar_path, "r") as aar_zip:
+            aar_zip.extractall(unpack_dir)
+
+        if platform.system() != "Windows":
+            # If the zip file was built on e.g. Windows, then it might not have
+            # correct permissions (which means we can't read any of the files), so
+            # make sure we actually read everything here.
+            utils.execute_command(["chmod", "-R", "+rX", unpack_dir])
+
+        unpacked_manifest = unpack_dir / "AndroidManifest.xml"
+        assert unpacked_manifest.exists()
+        shutil.copyfile(unpacked_manifest, manifest_path)
+
+        unpacked_res = unpack_dir / "res"
+        if unpacked_res.exists():
+            shutil.copytree(unpacked_res, res_path)
+        else:
+            res_path.mkdir()
+
+        unpacked_assets = unpack_dir / "assets"
+        if unpacked_assets.exists():
+            shutil.copytree(unpacked_assets, assets_path)
+        else:
+            assets_path.mkdir()
+
+        unpacked_jni = unpack_dir / "jni"
+        if unpacked_jni.exists():
+            shutil.copytree(unpacked_jni, jni_path)
+        else:
+            jni_path.mkdir()
+
+        unpacked_r_dot_txt = unpack_dir / "R.txt"
+        if unpacked_r_dot_txt.exists():
+            shutil.copyfile(unpacked_r_dot_txt, r_dot_txt_path)
+        else:
+            r_dot_txt_path.touch()
+
+        annotation_jars_dir.mkdir()
+        annotations_zip_path = unpack_dir / ANNOTATIONS_ZIP_FILE_NAME
+        if annotations_zip_path.exists():
+            shutil.copy(annotations_zip_path, annotation_jars_dir)
+
+        unpacked_proguard_config = unpack_dir / "proguard.txt"
+        if unpacked_proguard_config.exists():
+            shutil.copyfile(unpacked_proguard_config, proguard_config_path)
+        else:
+            proguard_config_path.touch()
+
+        unpacked_lint_jar = unpack_dir / "lint.jar"
+        if unpacked_lint_jar.exists():
+            shutil.copyfile(unpacked_lint_jar, lint_jar_path)
+        else:
+            lint_jar_path.touch()
+
+        # Java .class files can exist at `classes.jar` or any jar file in /libs,
+        # so combine them into a single `.jar` file.
+        all_jars = []
+        classes_jar = unpack_dir / CLASSES_JAR_FILE_NAME
+        if classes_jar.exists():
+            all_jars.append(classes_jar)
+
+        libs_dir = unpack_dir / LIBS_DIR_NAME
+        if libs_dir.exists():
+            libs = [lib for lib in libs_dir.iterdir() if lib.suffix == ".jar"]
+            all_jars += libs
+
+        jars_list = unpack_dir / "jars_list.txt"
+        with open(jars_list, "w") as f:
+            f.write("\n".join([str(jar) for jar in all_jars]))
+
+        combine_all_jars_cmd = utils.shlex_split(jar_builder_tool) + [
+            "--entries-to-jar",
+            jars_list,
+            "--output",
+            all_classes_path,
+        ]
+
+        utils.execute_command(combine_all_jars_cmd)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/android/user/android_emulators.bzl b/buck2/prelude/android/user/android_emulators.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/user/android_emulators.bzl
@@ -0,0 +1,29 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//user:rule_spec.bzl", "RuleRegistrationSpec")
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        LocalResourceInfo(
+            setup = cmd_args([ctx.attrs.broker[RunInfo]] + ctx.attrs.args),
+            resource_env_vars = {
+                "ANDROID_SERIAL": "serial_number",
+            },
+        ),
+    ]
+
+registration_spec = RuleRegistrationSpec(
+    name = "android_emulators",
+    impl = _impl,
+    attrs = {
+        "args": attrs.list(attrs.arg(), default = []),
+        "broker": attrs.exec_dep(providers = [RunInfo]),
+    },
+)
diff --git a/buck2/prelude/android/util.bzl b/buck2/prelude/android/util.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/util.bzl
@@ -0,0 +1,149 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//linking:link_info.bzl",
+    "ExtraLinkerOutputs",
+)
+
+def merge_extra_linker_args(arg_dicts: list[dict[str, typing.Any]]) -> dict[str, typing.Any]:
+    """Merge multiple extra linker output factory dicts.
+
+    This function combines multiple extra linker output configurations into a single
+    configuration. It handles both the outputs factory (which produces artifacts and
+    providers) and the flags factory (which produces linker flags).
+
+    Args:
+        arg_dicts: A list of dicts, each potentially containing:
+            - "extra_linker_outputs_factory": A function (ctx) -> ExtraLinkerOutputs
+            - "extra_linker_outputs_flags_factory": A function (ctx, outputs) -> list
+
+    Returns:
+        A merged dict with combined factory functions, or an empty dict if no
+        non-empty dicts were provided.
+    """
+    non_empty = [d for d in arg_dicts if d]
+    if len(non_empty) == 0:
+        return {}
+    if len(non_empty) == 1:
+        return non_empty[0]
+
+    def combined_outputs_factory(ctx: AnalysisContext) -> ExtraLinkerOutputs:
+        artifacts = {}
+        providers = {}
+        for arg_dict in non_empty:
+            if "extra_linker_outputs_factory" in arg_dict:
+                result = arg_dict["extra_linker_outputs_factory"](ctx)
+                artifacts |= result.artifacts
+                providers |= result.providers
+        return ExtraLinkerOutputs(artifacts = artifacts, providers = providers)
+
+    def combined_flags_factory(ctx: AnalysisContext, outputs: dict[str, Artifact]) -> list:
+        flags = []
+        for arg_dict in non_empty:
+            if "extra_linker_outputs_flags_factory" in arg_dict:
+                flags += arg_dict["extra_linker_outputs_flags_factory"](ctx, outputs)
+        return flags
+
+    return {
+        "extra_linker_outputs_factory": combined_outputs_factory,
+        "extra_linker_outputs_flags_factory": combined_flags_factory,
+    }
+
+def package_validators_decorator(ctx: AnalysisContext, build_func, extension: str):
+    package_validators = ctx.attrs.package_validators
+    if not package_validators:
+        return build_func
+
+    def wrapped_build_func(**build_kwargs):
+        final_filename = build_kwargs["output_filename"]
+        build_kwargs["output_filename"] = final_filename + "_pre_validation"
+        output = build_func(**build_kwargs)
+
+        validation_outputs = _get_package_validation_outputs(
+            actions = ctx.actions,
+            package_validators = package_validators,
+            package_output = output,
+        )
+        final_output = ctx.actions.declare_output(
+            final_filename + extension,
+            has_content_based_path = False,
+        )
+        ctx.actions.run(
+            cmd_args(
+                [
+                    "cp",
+                    output,
+                    final_output.as_output(),
+                ],
+                hidden = validation_outputs,
+            ),
+            category = "package_validators",
+            identifier = "symlink_original_output",
+        )
+
+        return final_output
+
+    return wrapped_build_func
+
+def _get_package_validation_outputs(actions: AnalysisActions, package_validators: list, package_output: Artifact) -> list[Artifact]:
+    if not package_validators:
+        return []
+
+    outputs = []
+    for idx, validator in enumerate(package_validators):
+        validator, validator_args = validator
+
+        output = actions.declare_output(validator.label.name + "_package_validator_{}".format(idx), has_content_based_path = False)
+        outputs.append(output)
+
+        actions.run(
+            cmd_args([
+                validator[RunInfo],
+                "--package",
+                package_output,
+                "--output-path",
+                output.as_output(),
+                validator_args,
+            ]),
+            category = "package_validator",
+            identifier = str(idx),
+        )
+
+    return outputs
+
+# A wrapper around AnalysisContext that makes it easier to define subtargets without needing to pass information
+# for them all the way back to the outermost analysis impl.
+EnhancementContext = record(
+    ctx = AnalysisContext,
+    actions = AnalysisActions,
+    attrs = typing.Any,
+    label = Label,
+    # methods
+    debug_output = typing.Callable,
+    get_sub_targets = typing.Callable,
+)
+
+def create_enhancement_context(ctx: AnalysisContext) -> EnhancementContext:
+    extra_sub_targets = {}
+
+    def debug_output(name: str, output: Artifact, other_outputs = [], sub_targets: dict[str, typing.Any] = {}):
+        """Adds a subtarget to expose debugging outputs."""
+        extra_sub_targets[name] = [DefaultInfo(default_outputs = [output], other_outputs = other_outputs, sub_targets = sub_targets)]
+
+    def get_sub_targets():
+        return extra_sub_targets
+
+    return EnhancementContext(
+        ctx = ctx,
+        actions = ctx.actions,
+        attrs = ctx.attrs,
+        label = ctx.label,
+        debug_output = debug_output,
+        get_sub_targets = get_sub_targets,
+    )
diff --git a/buck2/prelude/android/voltron.bzl b/buck2/prelude/android/voltron.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/android/voltron.bzl
@@ -0,0 +1,343 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_providers.bzl", "AndroidPackageableInfo", "merge_android_packageable_info")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//java:java_providers.bzl", "get_all_java_packaging_deps")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",  # @unused Used as type
+    "SharedLibraryInfo",
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+)
+load("@prelude//utils:argfile.bzl", "argfile")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "flatten")
+
+# "Voltron" gives us the ability to split our Android APKs into different "modules". These
+# modules can then be downloaded on demand rather than shipped with the "main" APK.
+#
+# The module corresponding to the "main" APK is called the "root" module.
+#
+# Voltron support comes in two main parts:
+# (1) Constructing the Voltron module graph (assigning targets to each module). This is done
+# by constructing a "target graph" and then delegating to buck1 to produce the module graph.
+# (2) Using the Voltron module graph while building our APK.
+#
+# For (1), in order to calculate which targets belong to each module, we reconstruct a "target
+# graph" from "deps" information that is propagated up through AndroidPackageableInfo.
+# In buck1 we use the underlying "TargetGraph" object that is based on the raw target
+# definitions. This results in some slightly different behavior for `provided_deps` - in
+# buck2, we (correctly) ignore `provided_deps`, since they do not influence the packaging of
+# the APK, whereas in `buck1`, we treat `provided_deps` the same as `deps`.
+# In practice, this rarely affects the module assignments, but can mean that `buck2` will
+# put a target inside a module whereas `buck1` will put it into the main APK (since `buck1`
+# can find a path from an "always in main APK seed" to the target via some `provided_dep`,
+# whereas `buck2` does not).
+#
+# For (2), we package up secondary DEX files and native libs into `assets/module_name` (see
+# dex_rules.bzl and android_binary_native_rules.bzl for more information on how we do that).
+# It is worth noting that we still put all of the non-root modules into the final APK. If
+# the module should be downloaded on demand, then it is removed from the final APK in a
+# subsequent post-processing step.
+#
+# There is also an `android_app_modularity` rule that just prints out details of the Voltron
+# module graph and is used for any subsequent verification.
+def android_app_modularity_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs._build_only_native_code:
+        return [
+            # Add an unused default output in case this target is used as an attr.source() anywhere.
+            DefaultInfo(default_output = ctx.actions.write("{}/unused.txt".format(ctx.label.name), [], has_content_based_path = False)),
+        ]
+
+    all_deps = ctx.attrs.deps + flatten(ctx.attrs.application_module_configs.values())
+    android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, all_deps)
+
+    shared_library_info = merge_shared_libraries(
+        ctx.actions,
+        deps = filter(None, [x.get(SharedLibraryInfo) for x in all_deps]),
+    )
+    traversed_shared_library_info = traverse_shared_library_info(shared_library_info, transformation_provider = None)
+
+    cmd, output = _get_base_cmd_and_output(
+        ctx.actions,
+        ctx.label,
+        [android_packageable_info],
+        traversed_shared_library_info,
+        ctx.attrs._android_toolchain[AndroidToolchainInfo],
+        ctx.attrs.application_module_configs,
+        ctx.attrs.application_module_dependencies,
+        ctx.attrs.application_module_blocklist,
+    )
+
+    if ctx.attrs.should_include_classes:
+        no_dx_target_labels = [no_dx_target.label.raw_target() for no_dx_target in ctx.attrs.no_dx]
+        java_packaging_deps = [
+            packaging_dep
+            for packaging_dep in get_all_java_packaging_deps(ctx, all_deps)
+            if packaging_dep.dex and packaging_dep.dex.dex.owner.raw_target() not in no_dx_target_labels
+        ]
+        targets_to_jars_args = [cmd_args([str(packaging_dep.label.raw_target()), packaging_dep.jar], delimiter = " ") for packaging_dep in java_packaging_deps]
+        targets_to_jars = argfile(actions = ctx.actions, name = "targets_to_jars.txt", args = targets_to_jars_args)
+        cmd.add([
+            "--targets-to-jars",
+            targets_to_jars,
+        ])
+
+    if ctx.attrs.should_include_libraries:
+        targets_to_so_names_args = [
+            cmd_args([str(shared_lib.label.raw_target()), shared_lib.soname.ensure_str()], delimiter = " ") for shared_lib in traversed_shared_library_info
+        ]
+        targets_to_so_names = argfile(actions = ctx.actions, name = "targets_to_so_names.txt", args = targets_to_so_names_args)
+        cmd.add([
+            "--targets-to-so-names",
+            targets_to_so_names,
+        ])
+
+        traversed_prebuilt_native_library_dirs = (
+            android_packageable_info.prebuilt_native_library_dirs.traverse() if android_packageable_info.prebuilt_native_library_dirs else []
+        )
+        targets_to_non_assets_prebuilt_native_library_dirs_args = [
+            cmd_args(prebuilt_native_library_dir.raw_target, prebuilt_native_library_dir.dir, delimiter = " ")
+            for prebuilt_native_library_dir in traversed_prebuilt_native_library_dirs
+            if not prebuilt_native_library_dir.is_asset and not prebuilt_native_library_dir.for_primary_apk
+        ]
+        targets_to_non_assets_prebuilt_native_library_dirs = argfile(
+            actions = ctx.actions,
+            name = "targets_to_non_assets_prebuilt_native_library_dirs.txt",
+            args = targets_to_non_assets_prebuilt_native_library_dirs_args,
+        )
+        cmd.add([
+            "--targets-to-non-asset-prebuilt-native-library-dirs",
+            targets_to_non_assets_prebuilt_native_library_dirs,
+        ])
+
+    ctx.actions.run(cmd, category = "apk_module_graph")
+
+    return [DefaultInfo(default_output = output)]
+
+def get_target_to_module_mapping(ctx: AnalysisContext, deps_by_platform: dict[str, list[Dependency]]) -> Artifact | None:
+    if not ctx.attrs.application_module_configs:
+        return None
+
+    android_packageable_infos = []
+    shared_libraries = []
+    for deps in deps_by_platform.values() + [flatten(ctx.attrs.application_module_configs.values())]:
+        android_packageable_infos.append(merge_android_packageable_info(ctx.label, ctx.actions, deps))
+        shared_library_info = merge_shared_libraries(
+            ctx.actions,
+            deps = filter(None, [x.get(SharedLibraryInfo) for x in deps]),
+        )
+        shared_libraries.extend(traverse_shared_library_info(shared_library_info, transformation_provider = None))
+
+    cmd, output = _get_base_cmd_and_output(
+        ctx.actions,
+        ctx.label,
+        android_packageable_infos,
+        shared_libraries,
+        ctx.attrs._android_toolchain[AndroidToolchainInfo],
+        ctx.attrs.application_module_configs,
+        ctx.attrs.application_module_dependencies,
+        ctx.attrs.application_module_blocklist,
+    )
+
+    cmd.add("--output-module-info-and-target-to-module-only")
+
+    ctx.actions.run(cmd, category = "apk_module_graph")
+
+    return output
+
+def _get_base_cmd_and_output(
+    actions: AnalysisActions,
+    label: Label,
+    android_packageable_infos: list[AndroidPackageableInfo],
+    shared_libraries: list[SharedLibrary],
+    android_toolchain: AndroidToolchainInfo,
+    application_module_configs: dict[str, list[Dependency]],
+    application_module_dependencies: [dict[str, list[str]], None],
+    application_module_blocklist: [list[Dependency], None],
+) -> (cmd_args, Artifact):
+    deps_map = {}
+    primary_apk_deps = set()
+    for android_packageable_info in android_packageable_infos:
+        if android_packageable_info.deps:
+            for deps_info in android_packageable_info.deps.traverse():
+                deps = deps_map.setdefault(deps_info.name, [])
+                deps_map[deps_info.name] = dedupe(deps + deps_info.deps)
+                if deps_info.for_primary_apk:
+                    primary_apk_deps.add(deps_info.name)
+
+    target_graph_file = actions.write_json("target_graph.json", deps_map, has_content_based_path = False)
+    application_module_configs_map = {
+        module_name: [seed.get(AndroidPackageableInfo).target_label for seed in seeds if seed.get(AndroidPackageableInfo)]
+        for module_name, seeds in application_module_configs.items()
+    }
+    application_module_configs_file = actions.write_json("application_module_configs.json", application_module_configs_map, has_content_based_path = False)
+    application_module_dependencies_file = actions.write_json(
+        "application_module_dependencies.json", application_module_dependencies or {}, has_content_based_path = False
+    )
+    output = actions.declare_output("apk_module_metadata.txt", has_content_based_path = False)
+
+    cmd = cmd_args([
+        android_toolchain.apk_module_graph[RunInfo],
+        "--root-target",
+        str(label.raw_target()),
+        "--target-graph",
+        target_graph_file,
+        "--seed-config-map",
+        application_module_configs_file,
+        "--app-module-dependencies-map",
+        application_module_dependencies_file,
+        "--output",
+        output.as_output(),
+    ])
+
+    # Anything that is used by a wrap script needs to go into the primary APK, as do all
+    # of their deps.
+    used_by_wrap_script_libs = [str(shared_lib.label.raw_target()) for shared_lib in shared_libraries if shared_lib.for_primary_apk]
+    prebuilt_native_library_dirs = flatten([
+        list(android_packageable_info.prebuilt_native_library_dirs.traverse()) if android_packageable_info.prebuilt_native_library_dirs else []
+        for android_packageable_info in android_packageable_infos
+    ])
+    prebuilt_native_library_targets_for_primary_apk = dedupe(
+        [str(native_lib_dir.raw_target) for native_lib_dir in prebuilt_native_library_dirs if native_lib_dir.for_primary_apk]
+    )
+    if application_module_blocklist or used_by_wrap_script_libs or prebuilt_native_library_targets_for_primary_apk or len(primary_apk_deps) > 0:
+        all_blocklisted_deps = used_by_wrap_script_libs + prebuilt_native_library_targets_for_primary_apk + list(primary_apk_deps)
+        if application_module_blocklist:
+            all_blocklisted_deps.extend([str(blocklisted_dep.label.raw_target()) for blocklisted_dep in application_module_blocklist])
+
+        application_module_blocklist_file = actions.write(
+            "application_module_blocklist.txt",
+            all_blocklisted_deps,
+            has_content_based_path = False,
+        )
+        cmd.add([
+            "--always-in-main-apk-seeds",
+            application_module_blocklist_file,
+        ])
+
+    return cmd, output
+
+ROOT_MODULE = "dex"
+
+def is_root_module(module: str) -> bool:
+    return module == ROOT_MODULE
+
+def all_targets_in_root_module(_module: str) -> str:
+    return ROOT_MODULE
+
+APKModuleGraphInfo = record(
+    module_list = list[str],
+    target_to_module_mapping_function = typing.Callable,
+    module_to_canary_class_name_function = typing.Callable,
+    module_to_module_deps_function = typing.Callable,
+    transitive_module_deps_function = typing.Callable,
+    calculated_deps_function = typing.Callable,
+    get_deps_debug_data = typing.Callable,
+)
+
+def get_root_module_only_apk_module_graph_info() -> APKModuleGraphInfo:
+    def root_module_canary_class_name(module: str):
+        expect(is_root_module(module))
+        return "secondary"
+
+    def root_module_deps(module: str):
+        expect(is_root_module(module))
+        return []
+
+    return APKModuleGraphInfo(
+        module_list = [ROOT_MODULE],
+        target_to_module_mapping_function = all_targets_in_root_module,
+        module_to_canary_class_name_function = root_module_canary_class_name,
+        module_to_module_deps_function = root_module_deps,
+        transitive_module_deps_function = root_module_deps,
+        calculated_deps_function = root_module_deps,
+        get_deps_debug_data = root_module_deps,
+    )
+
+def get_apk_module_graph_info(ctx: AnalysisContext, apk_module_graph_file: Artifact, artifacts) -> APKModuleGraphInfo:
+    apk_module_graph_lines = artifacts[apk_module_graph_file].read_string().split("\n")
+    module_count = int(apk_module_graph_lines[0])
+    module_infos = apk_module_graph_lines[1 : module_count + 1]
+    target_to_module_lines = apk_module_graph_lines[module_count + 1 : -1]
+    expect(apk_module_graph_lines[-1] == "", "Expect last line to be an empty string!")
+
+    module_to_canary_class_name_map = {}
+    module_to_module_deps_map = {}
+    transitive_module_deps_map = {}
+    calculated_deps_map = {}
+    shared_module_rdeps = {}
+    for line in module_infos:
+        line_data = line.split(" ")
+        module_name = line_data[0]
+        canary_class_name = line_data[1]
+        module_deps = [module_dep for module_dep in line_data[2:] if module_dep]
+        module_to_canary_class_name_map[module_name] = canary_class_name
+        module_to_module_deps_map[module_name] = module_deps
+        shared_modules = [module_dep for module_dep in module_deps if module_dep.startswith("s_")]
+        for shared_module in shared_modules:
+            rdeps = shared_module_rdeps.get(shared_module, set())
+            rdeps.add(module_name)
+            shared_module_rdeps[shared_module] = rdeps
+
+    target_to_module_mapping = {str(ctx.label.raw_target()): ROOT_MODULE}
+    for line in target_to_module_lines:
+        target, module = line.split(" ")
+        target_to_module_mapping[target] = module
+
+    for module, deps in module_to_module_deps_map.items():
+        visited_modules = set()
+        queue = [d for d in deps]
+        for _ in range(1, 1000):  # represents a while loop since while loops dont exist in starlark
+            if len(queue) == 0:
+                transitive_module_deps_map[module] = visited_modules
+                continue
+            node = queue.pop()
+            visited_modules.add(node)
+            for d in module_to_module_deps_map[node]:
+                if d not in visited_modules:
+                    queue.append(d)
+    for shared_module, rdeps in shared_module_rdeps.items():
+        rdeps_list = list(rdeps)
+        head = rdeps_list[0]
+        intersection = transitive_module_deps_map[head]
+        for rdep in rdeps_list[1:]:
+            intersection = intersection & transitive_module_deps_map[rdep]
+        calculated_deps_map[shared_module] = intersection | rdeps
+
+    def target_to_module_mapping_function(raw_target: str) -> str:
+        mapped_module = target_to_module_mapping.get(raw_target)
+        expect(mapped_module != None, "No module found for target {}!".format(raw_target))
+        return mapped_module
+
+    def module_to_canary_class_name_function(voltron_module: str) -> str:
+        return module_to_canary_class_name_map.get(voltron_module)
+
+    def module_to_module_deps_function(voltron_module: str) -> list:
+        return module_to_module_deps_map.get(voltron_module)
+
+    def transitive_module_deps_function(voltron_module: str) -> set[str]:
+        return transitive_module_deps_map.get(voltron_module)
+
+    def calculated_deps_function(voltron_module: str) -> set[str]:
+        return calculated_deps_map.get(voltron_module) if voltron_module in calculated_deps_map else set()
+
+    def get_deps_debug_data() -> str:
+        return "tdeps - {} \n calculated deps - {}".format(transitive_module_deps_map, calculated_deps_map)
+
+    return APKModuleGraphInfo(
+        module_list = module_to_canary_class_name_map.keys(),
+        target_to_module_mapping_function = target_to_module_mapping_function,
+        module_to_canary_class_name_function = module_to_canary_class_name_function,
+        module_to_module_deps_function = module_to_module_deps_function,
+        transitive_module_deps_function = transitive_module_deps_function,
+        calculated_deps_function = calculated_deps_function,
+        get_deps_debug_data = get_deps_debug_data,
+    )
diff --git a/buck2/prelude/aosp/aosp_providers.bzl b/buck2/prelude/aosp/aosp_providers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/aosp/aosp_providers.bzl
@@ -0,0 +1,17 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+AospJarInfo = provider(
+    fields = {
+        # Optional ART profile source (a text HSPL class/method listing) for this jar.
+        # When the jar is placed on an APEX systemserverclasspath, the APEX rule compiles
+        # this against the jar with profman to produce a profile-guided .prof for
+        # dexpreopt/odrefresh. None if the jar has no profile.
+        "profile": provider_field(typing.Any, default = None),
+    },
+)
diff --git a/buck2/prelude/apple/apple_app_intents.bzl b/buck2/prelude/apple/apple_app_intents.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_app_intents.bzl
@@ -0,0 +1,16 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def apple_app_intents_impl(_ctx: AnalysisContext) -> list[Provider]:
+    """
+    Implementation for apple_appintents rule.
+    This is a bare-bones implementation that will be expanded as needed.
+    """
+
+    # TODO: Add actual implementation logic
+    return []
diff --git a/buck2/prelude/apple/apple_asset_catalog.bzl b/buck2/prelude/apple/apple_asset_catalog.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_asset_catalog.bzl
@@ -0,0 +1,153 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load(
+    "@prelude//ide_integrations/xcode:data.bzl",
+    "XCODE_DATA_SUB_TARGET",
+    "XcodeDataInfoKeys",
+    "generate_xcode_data",
+)
+load("@prelude//utils:utils.bzl", "flatten")
+load(
+    ":apple_asset_catalog_compilation_options.bzl", "AppleAssetCatalogsCompilationOptions", "get_apple_asset_catalogs_compilation_options"
+)  # @unused Used as a type
+load(":apple_asset_catalog_types.bzl", "AppleAssetCatalogResult", "AppleAssetCatalogSpec", "StringWithSourceTarget")
+load(":apple_bundle_utility.bzl", "get_bundle_min_target_version", "get_bundle_resource_processing_options")
+load(":apple_sdk.bzl", "get_apple_sdk_name")
+load(":apple_sdk_metadata.bzl", "get_apple_sdk_metadata_for_sdk_name")
+load(":resource_groups.bzl", "create_resource_graph")
+
+def apple_asset_catalog_impl(ctx: AnalysisContext) -> list[Provider]:
+    spec = AppleAssetCatalogSpec(
+        app_icon = StringWithSourceTarget(source = ctx.label, value = ctx.attrs.app_icon) if ctx.attrs.app_icon != None else None,
+        dirs = ctx.attrs.dirs,
+        launch_image = StringWithSourceTarget(source = ctx.label, value = ctx.attrs.launch_image) if ctx.attrs.launch_image != None else None,
+    )
+    graph = create_resource_graph(
+        ctx = ctx,
+        labels = ctx.attrs.labels,
+        deps = [],
+        exported_deps = [],
+        asset_catalog_spec = spec,
+    )
+
+    xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "apple_asset_catalog", None, _xcode_populate_attributes)
+
+    return [
+        DefaultInfo(
+            sub_targets = {
+                XCODE_DATA_SUB_TARGET: xcode_data_default_info,
+            },
+        ),
+        graph,
+        xcode_data_info,
+    ]
+
+def compile_apple_asset_catalog(ctx: AnalysisContext, specs: list[AppleAssetCatalogSpec]) -> [AppleAssetCatalogResult, None]:
+    single_spec = _merge_asset_catalog_specs(ctx, specs)
+    if len(single_spec.dirs) == 0:
+        return None
+    plist = ctx.actions.declare_output("AssetCatalog.plist", has_content_based_path = False)
+    catalog = ctx.actions.declare_output("AssetCatalogCompiled", dir = True, has_content_based_path = False)
+    processing_options = get_bundle_resource_processing_options(ctx)
+    compilation_options = get_apple_asset_catalogs_compilation_options(ctx)
+    command = _get_actool_command(ctx, single_spec, catalog.as_output(), plist.as_output(), compilation_options)
+    ctx.actions.run(
+        command,
+        prefer_local = processing_options.prefer_local,
+        prefer_remote = processing_options.prefer_remote,
+        allow_cache_upload = processing_options.allow_cache_upload,
+        category = "apple_asset_catalog",
+    )
+    return AppleAssetCatalogResult(compiled_catalog = catalog, catalog_plist = plist)
+
+def _merge_asset_catalog_specs(ctx: AnalysisContext, xs: list[AppleAssetCatalogSpec]) -> AppleAssetCatalogSpec:
+    app_icon = _get_at_most_one_attribute(ctx, xs, "app_icon")
+    launch_image = _get_at_most_one_attribute(ctx, xs, "launch_image")
+    dirs = dedupe(flatten([x.dirs for x in xs]))
+    return AppleAssetCatalogSpec(app_icon = app_icon, dirs = dirs, launch_image = launch_image)
+
+def _get_at_most_one_attribute(ctx: AnalysisContext, xs: list[typing.Any], attr_name: str) -> [StringWithSourceTarget, None]:
+    all_values = dedupe(filter(None, [getattr(x, attr_name) for x in xs]))
+    if len(all_values) > 1:
+        fail(
+            "At most one asset catalog in the dependencies of `{}` can have an `{}` attribute. At least 2 catalogs are providing it: `{}` and `{}`.".format(
+                _get_target(ctx), attr_name, all_values[0].source, all_values[1].source
+            )
+        )
+    elif len(all_values) == 1:
+        return all_values[0]
+    else:
+        return None
+
+def _get_target(ctx: AnalysisContext) -> str:
+    return ctx.label.package + ":" + ctx.label.name
+
+def _get_actool_command(
+    ctx: AnalysisContext,
+    info: AppleAssetCatalogSpec,
+    catalog_output: OutputArtifact,
+    plist_output: OutputArtifact,
+    compilation_options: AppleAssetCatalogsCompilationOptions,
+) -> cmd_args:
+    external_name = get_apple_sdk_name(ctx)
+    sdk_metadata = get_apple_sdk_metadata_for_sdk_name(external_name)
+    target_device = sdk_metadata.target_device_flags
+
+    actool_platform = sdk_metadata.actool_platform_override
+    if not actool_platform:
+        actool_platform = external_name
+
+    actool = ctx.attrs._apple_toolchain[AppleToolchainInfo].actool
+    actool_command = cmd_args(
+        [
+            actool,
+            "--platform",
+            actool_platform,
+            "--minimum-deployment-target",
+            get_bundle_min_target_version(ctx, ctx.attrs.binary),
+            "--compile",
+            '"$TMPDIR"',
+            "--output-partial-info-plist",
+            plist_output,
+        ]
+        + target_device
+        + (["--app-icon", info.app_icon.value] if info.app_icon else [])
+        + (["--launch-image", info.launch_image.value] if info.launch_image else [])
+        + (["--notices"] if compilation_options.enable_notices else [])
+        + (["--warnings"] if compilation_options.enable_warnings else [])
+        + (["--errors"] if compilation_options.enable_errors else [])
+        + (["--compress-pngs"] if compilation_options.compress_pngs else [])
+        + ["--optimization", compilation_options.optimization]
+        + ["--output-format", compilation_options.output_format]
+        + compilation_options.extra_flags
+        + info.dirs
+    )
+
+    # `actool` expects the output directory to be present.
+    # Use the wrapper script to create the directory first and then actually call `actool`.
+    wrapper_script, _ = ctx.actions.write(
+        "actool_wrapper.sh",
+        [
+            cmd_args("set -euo pipefail"),
+            cmd_args('ACTOOL_INPUT_ROOT="$PWD"'),
+            cmd_args('export TMPDIR="$(mktemp -d)"'),
+            cmd_args('cd "$TMPDIR"'),
+            cmd_args(actool_command, absolute_prefix = "$ACTOOL_INPUT_ROOT/", delimiter = " "),
+            cmd_args(catalog_output, format = 'mkdir -p {} && cp -r "$TMPDIR"/ {}', absolute_prefix = "$ACTOOL_INPUT_ROOT/"),
+        ],
+        allow_args = True,
+        has_content_based_path = False,
+    )
+    command = cmd_args(["/bin/sh", wrapper_script], hidden = [actool_command, catalog_output])
+    return command
+
+def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:
+    data = {XcodeDataInfoKeys.EXTRA_XCODE_FILES: ctx.attrs.dirs}
+    return data
diff --git a/buck2/prelude/apple/apple_asset_catalog_compilation_options.bzl b/buck2/prelude/apple/apple_asset_catalog_compilation_options.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_asset_catalog_compilation_options.bzl
@@ -0,0 +1,30 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+AppleAssetCatalogsCompilationOptions = record(
+    enable_notices = field(bool),
+    enable_warnings = field(bool),
+    enable_errors = field(bool),
+    compress_pngs = field(bool),
+    optimization = field(str),
+    output_format = field(str),
+    extra_flags = field(list[str]),
+)
+
+def get_apple_asset_catalogs_compilation_options(ctx: AnalysisContext) -> AppleAssetCatalogsCompilationOptions:
+    options = ctx.attrs.asset_catalogs_compilation_options
+
+    return AppleAssetCatalogsCompilationOptions(
+        enable_notices = options.get("notices", True),
+        enable_warnings = options.get("warnings", True),
+        enable_errors = options.get("errors", True),
+        compress_pngs = options.get("compress_pngs", True),
+        optimization = options.get("optimization", "space"),
+        output_format = options.get("output_format", "human-readable-text"),
+        extra_flags = options.get("extra_flags", []),
+    )
diff --git a/buck2/prelude/apple/apple_asset_catalog_types.bzl b/buck2/prelude/apple/apple_asset_catalog_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_asset_catalog_types.bzl
@@ -0,0 +1,31 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+StringWithSourceTarget = record(
+    # Target providing the string value
+    source = field(Label),
+    value = field(str),
+)
+
+AppleAssetCatalogSpec = record(
+    # At most one per given `apple_bundle` (including all transitive catalog dependencies),
+    # optional reference in a form of a name (extension omitted) of an .appiconset which
+    # contains an image set representing an application icon.
+    # This set should be contained in one of catalogs referenced by `dirs` attribute.
+    app_icon = field([StringWithSourceTarget, None]),
+    dirs = field(list[Artifact]),
+    # Same as `app_icon` but with an application launch image semantics.
+    launch_image = field([StringWithSourceTarget, None]),
+)
+
+AppleAssetCatalogResult = record(
+    # Directory which contains compiled assets ready to be copied into application bundle
+    compiled_catalog = field(Artifact),
+    # .plist file to be merged into main application Info.plist file, containing information about compiled assets
+    catalog_plist = field(Artifact),
+)
diff --git a/buck2/prelude/apple/apple_binary.bzl b/buck2/prelude/apple/apple_binary.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_binary.bzl
@@ -0,0 +1,423 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")
+load("@prelude//apple:apple_stripping.bzl", "apple_strip_args")
+load("@prelude//apple:apple_utility.bzl", "get_module_name")
+load(
+    "@prelude//apple:modularization_dependency_graph.bzl",
+    "create_modularization_dep_graph_subtargets_and_provider",
+)
+load("@prelude//apple:xcassets_asset_symbols.bzl", "meta_xcassets_asset_symbol_usage_providers_and_subtargets")
+# @oss-disable[end= ]: load(
+    # @oss-disable[end= ]: "@prelude//apple/meta_only:linker_outputs.bzl",
+    # @oss-disable[end= ]: "extra_distributed_thin_lto_opt_outputs_merger",
+    # @oss-disable[end= ]: "get_extra_linker_output_flags",
+    # @oss-disable[end= ]: "get_extra_linker_outputs",
+# @oss-disable[end= ]: )
+load(
+    "@prelude//apple/swift:swift_compilation.bzl",
+    "compile_swift",
+    "get_swift_anonymous_targets",
+    "get_swift_debug_infos",
+    "get_swift_dependency_info",
+    "get_swiftmodule_linkable",
+)
+load("@prelude//apple/swift:swift_helpers.bzl", "uses_explicit_modules")
+load(
+    "@prelude//apple/swift:swift_incremental_support.bzl",
+    "get_uses_content_based_paths",
+)
+load("@prelude//apple/swift:swift_types.bzl", "SWIFT_EXTENSION")
+load(
+    "@prelude//cxx:argsfiles.bzl",
+    "CompileArgsfiles",
+)
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//cxx:cxx_executable.bzl", "cxx_executable")
+load("@prelude//cxx:cxx_library_utility.bzl", "cxx_attr_deps", "cxx_attr_exported_deps", "cxx_attr_link_style")
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",  # @unused Used as a type
+    "get_srcs_with_flags",
+)
+load(
+    "@prelude//cxx:cxx_transitive_diagnostics.bzl",
+    "cxx_transitive_diagnostics_combine",
+)
+load(
+    "@prelude//cxx:cxx_types.bzl",
+    "CxxRuleAdditionalParams",
+    "CxxRuleConstructorParams",
+    "CxxRuleSubTargetParams",
+    "xcode_data_enabled",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load(
+    "@prelude//cxx:headers.bzl",
+    "HeaderMode",
+    "cxx_attr_headers",
+    "cxx_attr_headers_list",
+    "cxx_get_regular_cxx_headers_layout",
+    "prepare_headers",
+)
+load("@prelude//cxx:index_store.bzl", "create_index_store_subtargets_and_provider")
+load(
+    "@prelude//cxx:link_groups.bzl",
+    "get_link_group_info",
+)
+load("@prelude//cxx:link_types.bzl", "ExtraLinkerOutputCategory")
+load(
+    "@prelude//linking:link_info.bzl",
+    "CxxSanitizerRuntimeInfo",
+    "ExtraLinkerOutputs",
+    "LinkCommandDebugOutputInfo",
+    "UnstrippedLinkOutputInfo",
+    "to_link_strategy",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",
+)
+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")
+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load("@prelude//utils:utils.bzl", "filter_and_map_idx", "map_val")
+load(":apple_bundle_types.bzl", "AppleBundleLinkerMapInfo", "AppleMinDeploymentVersionInfo")
+load(":apple_bundle_utility.bzl", "get_bundle_infos_from_graph", "merge_bundle_linker_maps_info")
+load(":apple_code_signing_types.bzl", "AppleEntitlementsInfo")
+load(":apple_dsym.bzl", "DSYM_SUBTARGET", "get_apple_dsym")
+load(":apple_entitlements.bzl", "entitlements_link_flags")
+load(":apple_error_handler.bzl", "apple_build_error_handler", "cxx_error_deserializer", "cxx_error_handler")
+load(":apple_frameworks.bzl", "get_framework_search_path_flags")
+load(":apple_rpaths.bzl", "get_rpath_flags_for_apple_binary")
+load(":apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")
+load(":apple_utility.bzl", "get_apple_cxx_headers_layout", "get_apple_stripped_attr_value_with_default_fallback", "target_stats_header_name")
+load(":debug.bzl", "AppleDebuggableInfo")
+load(":resource_groups.bzl", "create_resource_graph")
+load(":xcode.bzl", "apple_populate_xcode_attributes")
+
+def apple_binary_impl(ctx: AnalysisContext) -> [list[Provider], Promise]:
+    def get_apple_binary_providers(deps_providers) -> list[Provider]:
+        # FIXME: Ideally we'd like to remove the support of "bridging header",
+        # cause it affects build time and in general considered a bad practise.
+        # But we need it for now to achieve compatibility with BUCK1.
+        objc_bridging_header_flags = _get_bridging_header_flags(ctx)
+
+        cxx_srcs, swift_srcs = _filter_swift_srcs(ctx)
+        contains_swift_sources = len(swift_srcs) > 0
+
+        module_name = get_module_name(ctx)
+
+        framework_search_path_flags = get_framework_search_path_flags(ctx)
+        swift_compile_result = compile_swift(
+            ctx,
+            swift_srcs,
+            False,  # parse_as_library
+            deps_providers,
+            module_name,
+            [],
+            None,
+            framework_search_path_flags,
+            objc_bridging_header_flags,
+        )
+        swift_compile = swift_compile_result.swift_compilation
+        swift_object_files = swift_compile.object_files if swift_compile else []
+        swift_preprocessor = [swift_compile.pre] if swift_compile else []
+        extra_link_flags = get_rpath_flags_for_apple_binary(ctx) + entitlements_link_flags(ctx)
+
+        # Extensions have custom entry points and API restrictions
+        extension_compiler_flags = []
+        if ctx.attrs.application_extension:
+            extra_link_flags += [
+                "-fapplication-extension",
+                "-e",
+                "_NSExtensionMain",
+            ]
+            extension_compiler_flags = ["-fapplication-extension"]
+
+        swift_dependency_info = swift_compile.dependency_info if swift_compile else get_swift_dependency_info(ctx, None, deps_providers, False)
+        swift_debug_info = get_swift_debug_infos(
+            ctx,
+            swift_dependency_info,
+            swift_compile,
+        )
+
+        link_strategy = to_link_strategy(cxx_attr_link_style(ctx))
+        link_group_info = get_link_group_info(
+            ctx,
+            filter_and_map_idx(LinkableGraph, cxx_attr_deps(ctx)),
+            link_strategy,
+        )
+        binary_subtargets = {
+            "swift-compilation-database": [
+                DefaultInfo(
+                    default_output = swift_compile.compilation_database.db if swift_compile else None,
+                    other_outputs = [swift_compile.compilation_database.other_outputs] if swift_compile else [],
+                ),
+            ],
+        }
+
+        validation_deps_outputs = get_validation_deps_outputs(ctx)
+        stripped = get_apple_stripped_attr_value_with_default_fallback(ctx)
+        constructor_params = CxxRuleConstructorParams(
+            rule_type = "apple_binary",
+            generate_sub_targets = CxxRuleSubTargetParams(xcode_data = xcode_data_enabled()),
+            headers_layout = get_apple_cxx_headers_layout(ctx),
+            extra_link_flags = extra_link_flags,
+            extra_hidden = validation_deps_outputs,
+            srcs = cxx_srcs,
+            additional = CxxRuleAdditionalParams(
+                srcs = swift_srcs,
+                argsfiles = swift_compile.argsfiles if swift_compile else CompileArgsfiles(),
+                # We need to add any swift modules that we include in the link, as
+                # these will end up as `N_AST` entries that `dsymutil` will need to
+                # follow.
+                static_external_debug_info = swift_debug_info.static,
+                shared_external_debug_info = swift_debug_info.shared,
+                subtargets = binary_subtargets,
+            ),
+            extra_link_input = swift_object_files,
+            extra_link_input_has_external_debug_info = True,
+            extra_preprocessors = swift_preprocessor,
+            strip_executable = stripped,
+            strip_args_factory = apple_strip_args,
+            cxx_populate_xcode_attributes_func = lambda local_ctx, **kwargs: apple_populate_xcode_attributes(
+                local_ctx, contains_swift_sources = contains_swift_sources, **kwargs
+            ),
+            link_group_info = link_group_info,
+            prefer_stripped_objects = ctx.attrs.prefer_stripped_objects,
+            # Some apple rules rely on `static` libs *not* following dependents.
+            link_groups_force_static_follows_dependents = False,
+            swiftmodule_linkable = get_swiftmodule_linkable(swift_compile),
+            compiler_flags = ctx.attrs.compiler_flags + extension_compiler_flags,
+            lang_compiler_flags = ctx.attrs.lang_compiler_flags,
+            preprocessor_flags = ctx.attrs.preprocessor_flags,
+            lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,
+            error_handler = cxx_error_handler if cxx_error_deserializer(ctx) else apple_build_error_handler,
+            index_stores = [swift_compile.index_store] if swift_compile else None,
+            executable_name = ctx.attrs.executable_name,
+            extra_linker_outputs_factory = _get_extra_linker_outputs,
+            extra_linker_outputs_flags_factory = _get_extra_linker_outputs_flags,
+            extra_distributed_thin_lto_opt_outputs_merger = _extra_distributed_thin_lto_opt_outputs_merger,
+            allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),
+            precompiled_header = ctx.attrs.precompiled_header,
+            prefix_header = ctx.attrs.prefix_header,
+            use_content_based_paths = get_uses_content_based_paths(ctx),
+        )
+        cxx_output = cxx_executable(ctx, constructor_params)
+
+        if stripped:
+            unstripped_binary = cxx_output.unstripped_binary
+        else:
+            unstripped_binary = cxx_output.binary
+        cxx_output.sub_targets["unstripped"] = [DefaultInfo(default_output = unstripped_binary)]
+
+        dsym_artifact = get_apple_dsym(
+            ctx = ctx,
+            executable = unstripped_binary,
+            debug_info = cxx_output.external_debug_info_artifacts,
+            action_identifier = unstripped_binary.short_path,
+        )
+        cxx_output.sub_targets[DSYM_SUBTARGET] = [DefaultInfo(default_output = dsym_artifact)]
+
+        min_version = get_min_deployment_version_for_node(ctx)
+        min_version_providers = [AppleMinDeploymentVersionInfo(version = min_version)]
+
+        non_exported_deps = cxx_attr_deps(ctx)
+        exported_deps = cxx_attr_exported_deps(ctx)
+        resource_graph = create_resource_graph(
+            ctx = ctx,
+            labels = ctx.attrs.labels,
+            deps = non_exported_deps,
+            exported_deps = exported_deps,
+        )
+        bundle_infos = get_bundle_infos_from_graph(resource_graph)
+        if cxx_output.linker_map_data:
+            bundle_infos.append(AppleBundleLinkerMapInfo(linker_maps = [cxx_output.linker_map_data.map]))
+
+        link_command_providers = []
+        if cxx_output.link_command_debug_output:
+            link_command_providers.append(LinkCommandDebugOutputInfo(debug_outputs = [cxx_output.link_command_debug_output]))
+
+        sanitizer_runtime_providers = []
+        if cxx_output.sanitizer_runtime_files:
+            sanitizer_runtime_providers.append(CxxSanitizerRuntimeInfo(runtime_files = cxx_output.sanitizer_runtime_files))
+
+        index_stores = []
+        swift_index_stores = []
+
+        if swift_compile:
+            swift_index_stores.append(swift_compile.index_store)
+            index_stores.append(swift_compile.index_store)
+
+        index_stores.extend(cxx_output.index_stores)
+
+        all_deps = non_exported_deps + exported_deps
+
+        meta_xcassets_usage_providers, meta_xcassets_usage_subtargets = meta_xcassets_asset_symbol_usage_providers_and_subtargets(ctx, cxx_srcs, swift_srcs)
+        cxx_output.sub_targets.update(meta_xcassets_usage_subtargets)
+
+        index_store_subtargets, index_store_info = create_index_store_subtargets_and_provider(ctx, index_stores, swift_index_stores, all_deps)
+        cxx_output.sub_targets.update(index_store_subtargets)
+
+        # Modularization dependency graphs. Unlike apple_library (which routes
+        # through cxx_library), binaries go through cxx_executable, which does
+        # not create this provider -- so build it here. Without it the tset is
+        # severed at the binary and apple_bundle collects nothing from the
+        # libraries beneath it.
+        mod_dep_graph_subtargets, mod_dep_graph_info = create_modularization_dep_graph_subtargets_and_provider(
+            ctx,
+            swift_compile.modularization_dependency_graph if swift_compile else None,
+            all_deps,
+        )
+        cxx_output.sub_targets.update(mod_dep_graph_subtargets)
+
+        target_stats_providers = []
+        if TARGET_STATS_ENABLED:
+            target_stats_tools = get_cxx_toolchain_info(ctx).target_stats_tools
+            if target_stats_tools != None:
+                # Headers as well as srcs: file_cycles derives its ObjC import
+                # edges from the header entries, so without them a binary can
+                # never report a cycle.
+                target_stats_srcs = {src.file.short_path: src.file for src in cxx_srcs + swift_srcs}
+                target_stats_srcs.update({
+                    target_stats_header_name(header): header.artifact
+                    for header in cxx_attr_headers_list(ctx, ctx.attrs.headers, get_apple_cxx_headers_layout(ctx))
+                })
+                target_stats_providers, target_stats_subtargets = target_stats_providers_and_subtargets(
+                    ctx,
+                    tools = target_stats_tools,
+                    srcs = target_stats_srcs,
+                    deps = all_deps,
+                    cycle_mode = CycleMode("file"),
+                    module_name = module_name,
+                    swift_dot = swift_compile.modularization_dependency_graph if swift_compile else None,
+                )
+                cxx_output.sub_targets.update(target_stats_subtargets)
+
+        validation_providers = [ValidationInfo(validations = cxx_output.validation_specs)] if cxx_output.validation_specs else []
+
+        all_diagnostics = []
+        if swift_compile:
+            all_diagnostics.append(swift_compile.typecheck_file)
+        if cxx_output.diagnostics:
+            all_diagnostics.append(cxx_output.diagnostics)
+
+        diagnostics_providers = [
+            cxx_transitive_diagnostics_combine(
+                ctx = ctx,
+                diagnostics = all_diagnostics,
+                # TODO: We might be able to use all_deps, but, this changes the iteration order of deps.
+                deps = exported_deps + non_exported_deps,
+            ),
+        ]
+
+        providers = (
+            filter(
+                None,
+                [
+                    DefaultInfo(default_output = cxx_output.binary, sub_targets = cxx_output.sub_targets),
+                    RunInfo(args = cmd_args(cxx_output.binary, hidden = cxx_output.runtime_files)),
+                    AppleEntitlementsInfo(entitlements_file = ctx.attrs.entitlements_file),
+                    AppleDebuggableInfo(dsyms = [dsym_artifact], binaries = [unstripped_binary], debug_info_tset = cxx_output.external_debug_info),
+                    cxx_output.xcode_data,
+                    cxx_output.compilation_db,
+                    merge_bundle_linker_maps_info(bundle_infos),
+                    UnstrippedLinkOutputInfo(artifact = unstripped_binary),
+                    index_store_info,
+                    mod_dep_graph_info,
+                    swift_dependency_info,
+                ],
+            )
+            + [resource_graph]
+            + min_version_providers
+            + link_command_providers
+            + sanitizer_runtime_providers
+            + validation_providers
+            + diagnostics_providers
+            + target_stats_providers
+            + meta_xcassets_usage_providers
+        )
+
+        if cxx_output.xplugins_debug_artifacts_info:
+            providers.append(cxx_output.xplugins_debug_artifacts_info)
+
+        return providers
+
+    if uses_explicit_modules(ctx):
+        return get_swift_anonymous_targets(ctx, get_apple_binary_providers)
+    else:
+        return get_apple_binary_providers([])
+
+def _get_extra_linker_outputs(
+    ctx: AnalysisContext, extra_linker_output_category: ExtraLinkerOutputCategory = ExtraLinkerOutputCategory("produced-during-local-link")
+) -> ExtraLinkerOutputs:
+    _ = ctx  # buildifier: disable=unused-variable
+    # @oss-disable[end= ]: return get_extra_linker_outputs(ctx, extra_linker_output_category)
+    return ExtraLinkerOutputs() # @oss-enable
+
+def _get_extra_linker_outputs_flags(
+    ctx: AnalysisContext,
+    outputs: dict[str, Artifact],
+    extra_linker_output_category: ExtraLinkerOutputCategory = ExtraLinkerOutputCategory("produced-during-local-link"),
+) -> list[ArgLike]:
+    _ = ctx  # buildifier: disable=unused-variable
+    # @oss-disable[end= ]: return get_extra_linker_output_flags(ctx, outputs, extra_linker_output_category)
+    return [] # @oss-enable
+
+def _extra_distributed_thin_lto_opt_outputs_merger(ctx: AnalysisContext, outputs_to_bind: dict[str, Artifact], outputs_to_merge: list[dict[str, Artifact]]):
+    # @oss-disable[end= ]: return extra_distributed_thin_lto_opt_outputs_merger(ctx, outputs_to_bind, outputs_to_merge)
+    return # @oss-enable
+
+def _filter_swift_srcs(ctx: AnalysisContext) -> (list[CxxSrcWithFlags], list[CxxSrcWithFlags]):
+    cxx_srcs = []
+    swift_srcs = []
+    for s in get_srcs_with_flags(ctx):
+        if s.file.extension == SWIFT_EXTENSION:
+            swift_srcs.append(s)
+        else:
+            cxx_srcs.append(s)
+    return cxx_srcs, swift_srcs
+
+def _get_bridging_header_flags(ctx: AnalysisContext) -> list[ArgLike]:
+    if ctx.attrs.bridging_header:
+        objc_bridging_header_flags = [
+            # Disable bridging header -> PCH compilation to mitigate an issue in Xcode 13 beta.
+            "-disable-bridging-pch",
+            "-import-objc-header",
+            cmd_args(ctx.attrs.bridging_header),
+        ]
+
+        headers_layout = cxx_get_regular_cxx_headers_layout(ctx)
+        headers = cxx_attr_headers(ctx, headers_layout)
+        header_map = {paths.join(h.namespace, h.name): h.artifact for h in headers}
+
+        # We need to expose private headers to swift-compile action, in case something is imported to bridging header.
+        cxx_toolchain_info = get_cxx_toolchain_info(ctx)
+        header_mode = map_val(HeaderMode, getattr(ctx.attrs, "header_mode", None))
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs)
+        uses_content_based_paths = get_uses_content_based_paths(ctx)
+        header_root = prepare_headers(
+            ctx.actions,
+            cxx_toolchain_info,
+            header_map,
+            "apple-binary-private-headers",
+            header_mode = header_mode,
+            allow_cache_upload = allow_cache_upload,
+            uses_content_based_paths = uses_content_based_paths,
+        )
+        if header_root != None:
+            private_headers_args = [cmd_args("-I"), header_root.include_path]
+        else:
+            private_headers_args = []
+
+        return objc_bridging_header_flags + private_headers_args
+    else:
+        return []
diff --git a/buck2/prelude/apple/apple_bundle.bzl b/buck2/prelude/apple/apple_bundle.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_bundle.bzl
@@ -0,0 +1,717 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",  # @unused Used as a type
+    "make_artifact_tset",
+    "project_artifacts",
+)
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")
+load("@prelude//apple:apple_test_frameworks_utility.bzl", "get_test_frameworks_bundle_parts")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")
+load("@prelude//apple:debug.bzl", "AppleSelectiveDebuggableMetadata")
+load(
+    "@prelude//apple:modularization_dependency_graph.bzl",
+    "ModularizationDependencyGraphInfo",  # @unused Used as a type
+    "create_modularization_dep_graph_subtargets_and_provider",
+)
+# @oss-disable[end= ]: load("@prelude//apple/meta_only:linker_outputs.bzl", "subtargets_for_apple_bundle_extra_outputs")
+load("@prelude//apple/user:apple_selected_debug_path_file.bzl", "SELECTED_DEBUG_PATH_FILE_NAME")
+load("@prelude//apple/user:apple_selective_debugging.bzl", "AppleSelectiveDebuggingInfo")
+load("@prelude//apple/validation:required_reasons.bzl", "get_required_reasons_validator_output")
+load("@prelude//apple/validation:swiftmodule_change_analysis.bzl", "get_swiftmodule_change_analysis_output")
+load(
+    "@prelude//cxx:cxx_transitive_diagnostics.bzl",
+    "cxx_transitive_diagnostics_combine",
+)
+load(
+    "@prelude//cxx:index_store.bzl",
+    "IndexStoreInfo",  # @unused Used as a type
+    "create_index_store_subtargets_and_provider",
+)
+load(
+    "@prelude//ide_integrations/xcode:data.bzl",
+    "XCODE_DATA_SUB_TARGET",
+    "XcodeDataInfoKeys",
+    "generate_xcode_data",
+)
+load(
+    "@prelude//linking:execution_preference.bzl",
+    "LinkExecutionPreference",
+    "LinkExecutionPreferenceInfo",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkCommandDebugOutputInfo",  # @unused Used as a type
+    "UnstrippedLinkOutputInfo",
+    "make_link_command_debug_output_json_info",
+)
+load("@prelude//target_stats:target_stats.bzl", "target_stats_aggregate_providers_and_subtargets")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load("@prelude//utils:lazy.bzl", "lazy")
+load(
+    "@prelude//utils:utils.bzl",
+    "flatten",
+)
+load(
+    "@prelude//xplugins:debug_artifacts.bzl",
+    "xplugins_get_debug_artifacts_info",
+    "xplugins_get_debug_artifacts_subtargets",
+    "xplugins_get_function_mapping_manifest_info",
+)
+load(":apple_bundle_destination.bzl", "AppleBundleDestination")
+load(
+    ":apple_bundle_part.bzl",
+    "AppleBundleCodesignManifestTreePart",
+    "AppleBundlePart",
+    "AppleBundleSigningContextTreePart",
+    "SwiftStdlibArguments",
+    "assemble_bundle",
+    "bundle_output",
+    "get_apple_bundle_part_relative_destination_path",
+    "get_bundle_dir_name",
+)
+load(":apple_bundle_resources.bzl", "get_apple_bundle_resource_part_list")
+load(
+    ":apple_bundle_types.bzl",
+    "AppleBinaryExtraOutputsInfo",
+    "AppleBundleBinaryOutput",
+    "AppleBundleExtraOutputsInfo",
+    "AppleBundleInfo",
+    "AppleBundleLinkerMapInfo",
+    "AppleBundleResourceInfo",
+    "AppleBundleType",
+    "AppleBundleTypeDefault",
+    "AppleInfoPlistInfo",
+)
+load(":apple_bundle_utility.bzl", "get_bundle_min_target_version", "get_default_binary_dep", "get_flattened_binary_deps", "get_product_name")
+load(":apple_code_signing_types.bzl", "CodeSignConfiguration", "get_code_signing_configuration_attr_value")
+load(
+    ":apple_dsym.bzl",
+    "DSYM_INFO_SUBTARGET",
+    "DSYM_SUBTARGET",
+    "EXTENDED_DSYM_INFO_SUBTARGET",
+    "get_apple_dsym",
+    "get_apple_dsym_ext",
+    "get_apple_dsym_info_json",
+    "get_deps_debuggable_infos",
+)
+load(":apple_sdk.bzl", "get_apple_sdk_name")
+load(
+    ":apple_sdk_metadata.bzl",
+    "MacOSXCatalystSdkMetadata",
+    "MacOSXSdkMetadata",
+)
+load(":apple_universal_binaries.bzl", "create_universal_binary")
+load(
+    ":debug.bzl",
+    "AggregatedAppleDebugInfo",
+    "AppleDebuggableInfo",
+    "get_aggregated_debug_info",
+)
+load(":xcode.bzl", "apple_xcode_data_add_xctoolchain")
+
+_INSTALL_DATA_FILE_NAME = "install_apple_data.json"
+
+_PLIST = "plist"
+
+_XCTOOLCHAIN_SUB_TARGET = "xctoolchain"
+
+AppleBundleDebuggableInfo = record(
+    binary_info = field(AppleDebuggableInfo),
+    # Debugable info of all bundle deps
+    dep_infos = field(list[AppleDebuggableInfo]),
+    # Concat of `binary_info` and `dep_infos`
+    all_infos = field(list[AppleDebuggableInfo]),
+)
+
+AppleBundlePartListConstructorParams = record(
+    # The binaries/executables, required to create a bundle
+    binaries = field(list[AppleBundlePart]),
+)
+
+AppleBundlePartListOutput = record(
+    # The parts to be copied into an Apple bundle, *including* binaries
+    parts = field(list[AppleBundlePart]),
+    # Part that holds the info.plist
+    info_plist_part = field(AppleBundlePart),
+    # Codesign manifest parts for inner bundles
+    codesign_manifest_parts = field(list[AppleBundleCodesignManifestTreePart]),
+    # Signing context parts for inner bundles
+    signing_context_parts = field(list[AppleBundleSigningContextTreePart]),
+)
+
+_AppleBundleBinaryParts = record(
+    all_parts = field(list[AppleBundlePart]),
+    primary_part = field(AppleBundlePart),
+    sub_targets = field(dict[str, list[DefaultInfo]]),
+)
+
+def _get_binary(ctx: AnalysisContext) -> AppleBundleBinaryOutput:
+    binary_deps = get_flattened_binary_deps(ctx.attrs.binary)
+    if len(binary_deps) > 1:
+        if ctx.attrs.selective_debugging != None:
+            fail("Selective debugging is not supported for universal binaries.")
+        return create_universal_binary(
+            ctx = ctx,
+            binary_deps = ctx.attrs.binary,
+            binary_name = "{}-UniversalBinary".format(get_product_name(ctx)),
+            dsym_bundle_name = _get_bundle_dsym_name(ctx),
+            split_arch_dsym = ctx.attrs.split_arch_dsym,
+        )
+    else:
+        binary_dep = binary_deps[0]
+        if len(binary_dep[DefaultInfo].default_outputs) != 1:
+            fail("Expected single output artifact. Make sure the implementation of rule from `binary` attribute is correct.")
+
+        return _maybe_scrub_binary(ctx, binary_dep)
+
+def _get_bundle_dsym_name(ctx: AnalysisContext) -> str:
+    return paths.replace_extension(get_bundle_dir_name(ctx), ".dSYM")
+
+def _scrub_binary(
+    ctx,
+    binary: Artifact,
+    binary_execution_preference_info: None | LinkExecutionPreferenceInfo,
+    focused_targets_labels: list[Label] = [],
+    identifier: None | str = None,
+) -> Artifact:
+    # If fast adhoc code signing is enabled, we need to resign the binary as it won't be signed later.
+    code_signing_configuration = get_code_signing_configuration_attr_value(ctx)
+    if code_signing_configuration == CodeSignConfiguration("fast-adhoc"):
+        apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]
+        adhoc_codesign_tool = apple_tools.adhoc_codesign_tool
+    else:
+        adhoc_codesign_tool = None
+
+    selective_debugging_info = ctx.attrs.selective_debugging[AppleSelectiveDebuggingInfo]
+    preference = binary_execution_preference_info.preference if binary_execution_preference_info else LinkExecutionPreference("any")
+    return selective_debugging_info.scrub_binary(ctx, binary, preference, adhoc_codesign_tool, focused_targets_labels, identifier = identifier)
+
+def _maybe_scrub_binary(ctx, binary_dep: Dependency) -> AppleBundleBinaryOutput:
+    binary = binary_dep[DefaultInfo].default_outputs[0]
+    unstripped_binary = binary_dep.get(UnstrippedLinkOutputInfo).artifact if binary_dep.get(UnstrippedLinkOutputInfo) != None else None
+    debuggable_info = binary_dep.get(AppleDebuggableInfo)
+    if ctx.attrs.selective_debugging == None:
+        return AppleBundleBinaryOutput(binary = binary, unstripped_binary = unstripped_binary, debuggable_info = debuggable_info)
+
+    if debuggable_info:
+        if debuggable_info.selective_metadata:
+            fail("Binary cannot contain selective metadata, as it only gets scrubbed when embedded in a bundle")
+
+        # If we have debuggable info for this binary, create the scrubed dsym for the binary and filter debug info.
+        debug_info_tset = debuggable_info.debug_info_tset
+
+        # The traversal is intentionally designed to be topological, allowing us to skip
+        # portions of the debug info that are not transitive in relation to the focused targets.
+        all_debug_info = debug_info_tset._tset.traverse(ordering = "topological")
+        selective_debugging_info = ctx.attrs.selective_debugging[AppleSelectiveDebuggingInfo]
+        filtered_debug_info = selective_debugging_info.filter(ctx, all_debug_info)
+
+        filtered_external_debug_info = make_artifact_tset(
+            actions = ctx.actions,
+            label = ctx.label,
+            infos = filtered_debug_info.infos,
+        )
+
+        # For debug symbols we take the unstripped unscrubbed binary
+        debug_binaries = [unstripped_binary] if unstripped_binary else [binary]
+        binary = _scrub_binary(ctx, binary, binary_dep.get(LinkExecutionPreferenceInfo), filtered_debug_info.swift_modules_labels)
+        dsym_artifact = _get_scrubbed_binary_dsym(ctx, binary, debug_info_tset)
+
+        filtered_map = {}
+        for selected_target_info in filtered_debug_info.selected_target_infos:
+            filtered_map.setdefault(selected_target_info.label, []).extend(selected_target_info.artifacts)
+
+        debuggable_info = AppleDebuggableInfo(
+            dsyms = [dsym_artifact],
+            binaries = debug_binaries,
+            debug_info_tset = filtered_external_debug_info,
+            filtered_map = filtered_map,
+            selective_metadata = [
+                AppleSelectiveDebuggableMetadata(
+                    dsym = dsym_artifact,
+                    metadata = filtered_debug_info.metadata,
+                ),
+            ],
+        )
+        return AppleBundleBinaryOutput(binary = binary, unstripped_binary = unstripped_binary, debuggable_info = debuggable_info)
+    else:
+        binary = _scrub_binary(ctx, binary, binary_dep.get(LinkExecutionPreferenceInfo))
+        return AppleBundleBinaryOutput(binary = binary, unstripped_binary = unstripped_binary)
+
+def _get_scrubbed_binary_dsym(ctx, binary: Artifact, debug_info_tset: ArtifactTSet) -> Artifact:
+    debug_info = project_artifacts(
+        actions = ctx.actions,
+        tsets = debug_info_tset,
+    )
+    dsym_artifact = get_apple_dsym(
+        ctx = ctx,
+        executable = binary,
+        debug_info = debug_info,
+        action_identifier = binary.short_path,
+    )
+    return dsym_artifact
+
+def _get_binary_bundle_parts(
+    ctx: AnalysisContext, binary_output: AppleBundleBinaryOutput, aggregated_debug_info: AggregatedAppleDebugInfo
+) -> _AppleBundleBinaryParts:
+    """Returns a tuple of all binary bundle parts and the primary bundle binary."""
+    result = []
+
+    primary_binary_part = AppleBundlePart(source = binary_output.binary, destination = AppleBundleDestination("executables"), new_name = get_product_name(ctx))
+    result.append(primary_binary_part)
+
+    selected_debug_target_part = _get_selected_debug_targets_part(ctx, aggregated_debug_info)
+    if selected_debug_target_part:
+        result.append(selected_debug_target_part)
+
+    sub_targets = {
+        "selected-debug-paths": [DefaultInfo(default_output = selected_debug_target_part.source if selected_debug_target_part else None)],
+    }
+
+    return _AppleBundleBinaryParts(
+        all_parts = result,
+        primary_part = primary_binary_part,
+        sub_targets = sub_targets,
+    )
+
+def _get_dsym_input_binary_arg(ctx: AnalysisContext, binary_output: AppleBundleBinaryOutput, primary_binary_path_arg: cmd_args) -> cmd_args:
+    # We've already scrubbed the default binary, we only want to scrub the unstripped one if present.
+    unstripped_binary = binary_output.unstripped_binary
+    if unstripped_binary:
+        if ctx.attrs.selective_debugging != None:
+            unstripped_binary = _scrub_binary(
+                ctx, unstripped_binary, get_default_binary_dep(ctx.attrs.binary).get(LinkExecutionPreferenceInfo), identifier = "unstripped"
+            )
+        renamed_unstripped_binary = ctx.actions.copy_file(get_product_name(ctx), unstripped_binary, has_content_based_path = False)
+        return cmd_args(renamed_unstripped_binary)
+    else:
+        return primary_binary_path_arg
+
+def _apple_bundle_run_validity_checks(ctx: AnalysisContext):
+    if ctx.attrs.extension == None:
+        fail("`extension` attribute is required")
+
+def _get_deps_selective_metadata(deps_debuggable_infos: list[AppleDebuggableInfo]) -> list[AppleSelectiveDebuggableMetadata]:
+    all_metadatas = []
+    for debuggable_info in deps_debuggable_infos:
+        all_metadatas.extend(debuggable_info.selective_metadata)
+    return all_metadatas
+
+def _get_bundle_binary_dsym_artifacts(ctx: AnalysisContext, binary_output: AppleBundleBinaryOutput, executable_arg: ArgLike) -> list[Artifact]:
+    if not ctx.attrs.split_arch_dsym:
+        # Calling `dsymutil` on the correctly named binary in the _final bundle_ to yield dsym files
+        # with naming convention compatible with Meta infra.
+        binary_debuggable_info = binary_output.debuggable_info
+        bundle_binary_dsym_artifact = get_apple_dsym_ext(
+            ctx = ctx,
+            executable = executable_arg,
+            debug_info = project_artifacts(
+                actions = ctx.actions,
+                tsets = binary_debuggable_info.debug_info_tset if binary_debuggable_info else [],
+            ),
+            action_identifier = get_bundle_dir_name(ctx),
+            output_path = _get_bundle_dsym_name(ctx),
+        )
+        return [bundle_binary_dsym_artifact]
+    else:
+        return binary_output.debuggable_info.dsyms
+
+def _get_all_agg_debug_info(
+    ctx: AnalysisContext, binary_output: AppleBundleBinaryOutput, deps_debuggable_infos: list[AppleDebuggableInfo]
+) -> AggregatedAppleDebugInfo:
+    all_debug_infos = deps_debuggable_infos + ([binary_output.debuggable_info] if binary_output.debuggable_info else [])
+    return get_aggregated_debug_info(ctx, all_debug_infos)
+
+def _maybe_scrub_selected_debug_paths_file(ctx: AnalysisContext, package_names: list[str]) -> Artifact:
+    if not ctx.attrs.selective_debugging:
+        return ctx.actions.write(SELECTED_DEBUG_PATH_FILE_NAME, sorted(set(package_names)), has_content_based_path = False)
+
+    selective_debugging_info = ctx.attrs.selective_debugging[AppleSelectiveDebuggingInfo]
+    return selective_debugging_info.scrub_selected_debug_paths_file(ctx, package_names, SELECTED_DEBUG_PATH_FILE_NAME)
+
+def _get_selected_debug_targets_part(ctx: AnalysisContext, agg_debug_info: AggregatedAppleDebugInfo) -> [AppleBundlePart, None]:
+    # Only app bundles need this. This file is searched by FBReport via
+    # METAGetFocusedDebugPaths() which uses NSBundle URLForResource:
+    if ctx.attrs.extension == "app" and agg_debug_info.debug_info.filtered_map:
+        package_names = [label.package for label in agg_debug_info.debug_info.filtered_map.keys()]
+        output = _maybe_scrub_selected_debug_paths_file(ctx, package_names)
+        return AppleBundlePart(source = output, destination = AppleBundleDestination("resources"), new_name = SELECTED_DEBUG_PATH_FILE_NAME)
+    else:
+        return None
+
+def get_apple_bundle_part_list(ctx: AnalysisContext, params: AppleBundlePartListConstructorParams) -> AppleBundlePartListOutput:
+    resource_part_list = None
+    if hasattr(ctx.attrs, "_resource_bundle") and ctx.attrs._resource_bundle != None:
+        resource_info = ctx.attrs._resource_bundle[AppleBundleResourceInfo]
+        if resource_info != None:
+            resource_part_list = resource_info.resource_output
+
+    if resource_part_list == None:
+        resource_part_list = get_apple_bundle_resource_part_list(ctx)
+
+    test_frameworks_parts = []
+    if getattr(ctx.attrs, "embed_xctest_frameworks", False):
+        if getattr(ctx.attrs, "extension", "") == "app":
+            # XCTest frameworks should only be enabled for the top-level app,
+            # not for any other bundles in the dep graph
+            test_frameworks_parts = get_test_frameworks_bundle_parts(
+                ctx,
+                # It's not possible to pass information down the graph whether
+                # the `apple_test()` rdep needs Swift support, so just assume
+                # it does, in the future, Obj-C only test targets would be rare.
+                swift_support_needed = True,
+            )
+
+    return AppleBundlePartListOutput(
+        parts = resource_part_list.resource_parts + params.binaries + test_frameworks_parts,
+        info_plist_part = resource_part_list.info_plist_part,
+        codesign_manifest_parts = resource_part_list.codesign_manifest_parts,
+        signing_context_parts = resource_part_list.signing_context_parts,
+    )
+
+def _infer_apple_bundle_type(ctx: AnalysisContext) -> AppleBundleType:
+    if ctx.attrs.bundle_type != None:
+        return AppleBundleType(ctx.attrs.bundle_type)
+
+    return AppleBundleTypeDefault
+
+def apple_bundle_impl(ctx: AnalysisContext) -> list[Provider]:
+    _apple_bundle_run_validity_checks(ctx)
+
+    binary_outputs = _get_binary(ctx)
+
+    deps_debuggable_infos = get_deps_debuggable_infos(ctx)
+    aggregated_debug_info = _get_all_agg_debug_info(ctx, binary_outputs, deps_debuggable_infos)
+
+    binary_parts = _get_binary_bundle_parts(ctx, binary_outputs, aggregated_debug_info)
+    apple_bundle_part_list_output = get_apple_bundle_part_list(ctx, AppleBundlePartListConstructorParams(binaries = binary_parts.all_parts))
+
+    bundle = bundle_output(ctx)
+
+    primary_binary_rel_path = get_apple_bundle_part_relative_destination_path(ctx, binary_parts.primary_part)
+
+    validation_deps_outputs = get_validation_deps_outputs(ctx)
+
+    incremental_bundling_override = None
+    sdk_name = get_apple_sdk_name(ctx)
+    if sdk_name == MacOSXSdkMetadata.name or sdk_name == MacOSXCatalystSdkMetadata.name:
+        incremental_bundling_override = False
+
+    bundle_result = assemble_bundle(
+        ctx,
+        bundle,
+        apple_bundle_part_list_output.parts,
+        apple_bundle_part_list_output.codesign_manifest_parts,
+        apple_bundle_part_list_output.signing_context_parts,
+        apple_bundle_part_list_output.info_plist_part,
+        SwiftStdlibArguments(primary_binary_rel_path = primary_binary_rel_path),
+        validation_deps_outputs,
+        incremental_bundling_override = incremental_bundling_override,
+    )
+    sub_targets = bundle_result.sub_targets
+    sub_targets.update(aggregated_debug_info.sub_targets)
+    sub_targets.update(binary_parts.sub_targets)
+
+    primary_binary_path = cmd_args([bundle, primary_binary_rel_path], delimiter = "/")
+    primary_binary_path_arg = cmd_args(primary_binary_path, hidden = bundle)
+
+    deps_with_binary = ctx.attrs.deps + get_flattened_binary_deps(ctx.attrs.binary)
+
+    linker_maps_directory, linker_map_info = _linker_maps_data(ctx.actions, deps_with_binary)
+    sub_targets["linker-maps"] = [DefaultInfo(default_output = linker_maps_directory)]
+
+    xplugins_debug_info = xplugins_get_debug_artifacts_info(ctx, deps_with_binary)
+    app_binary = get_default_binary_dep(ctx.attrs.binary) if ctx.attrs.extension == "app" and xplugins_debug_info else None
+    xplugins_function_mapping_manifest_info = xplugins_get_function_mapping_manifest_info(
+        ctx.actions,
+        app_binary.label if app_binary else None,
+        xplugins_debug_info,
+    )
+    sub_targets["xplugins"] = xplugins_get_debug_artifacts_subtargets(xplugins_function_mapping_manifest_info)
+
+    link_cmd_debug_file, link_cmd_debug_info = _link_command_debug_data(ctx.actions, deps_with_binary)
+    sub_targets["linker.command"] = [DefaultInfo(default_outputs = filter(None, [link_cmd_debug_file]))]
+
+    # dsyms
+    dsym_input_binary_arg = _get_dsym_input_binary_arg(ctx, binary_outputs, primary_binary_path_arg)
+    binary_dsym_artifacts = _get_bundle_binary_dsym_artifacts(ctx, binary_outputs, dsym_input_binary_arg)
+    # The same dSYM can reach a bundle through multiple dependency paths.
+    dep_dsym_artifacts = set()
+    for info in deps_debuggable_infos:
+        dep_dsym_artifacts.update(info.dsyms)
+    dep_dsym_artifacts = list(dep_dsym_artifacts)
+
+    dsym_artifacts = binary_dsym_artifacts + dep_dsym_artifacts
+    if dsym_artifacts:
+        sub_targets[DSYM_SUBTARGET] = [DefaultInfo(default_outputs = dsym_artifacts)]
+
+    dsym_json_info = get_apple_dsym_info_json(binary_dsym_artifacts, dep_dsym_artifacts)
+    dsym_info = ctx.actions.write_json("dsym-info.json", dsym_json_info.json_object, pretty = True, has_content_based_path = False)
+    sub_targets[DSYM_INFO_SUBTARGET] = [
+        DefaultInfo(default_output = dsym_info, other_outputs = dsym_json_info.outputs),
+    ]
+
+    deps_selective_metadata = _get_deps_selective_metadata(deps_debuggable_infos)
+    binary_selective_metadata = []
+    if binary_outputs.debuggable_info and binary_outputs.debuggable_info.selective_metadata:
+        if len(binary_outputs.debuggable_info.selective_metadata) > 1:
+            fail("Binary cannot have multiple selective metadata")
+
+        # `AppleSelectiveDebuggableMetadata` for the binary is computed here because
+        # the dSYMs for the bundle get regenerated (via call to `_get_bundle_binary_dsym_artifacts()`).
+        # To ensure we have the correct dSYM path, metadata needs to be created here, as otherwise
+        # the map will contain the value of the dSYM for the standalone binary, not for the binary
+        # as part of the bundle.
+        binary_selective_metadata = [
+            AppleSelectiveDebuggableMetadata(dsym = binary_dsym, metadata = binary_outputs.debuggable_info.selective_metadata[0].metadata)
+            for binary_dsym in binary_dsym_artifacts
+        ]
+    all_selective_metadata = binary_selective_metadata + deps_selective_metadata
+
+    extended_dsym_json_info = get_apple_dsym_info_json(binary_dsym_artifacts, dep_dsym_artifacts, all_selective_metadata)
+    extended_dsym_info = ctx.actions.write_json("extended-dsym-info.json", extended_dsym_json_info.json_object, pretty = True, has_content_based_path = False)
+    sub_targets[EXTENDED_DSYM_INFO_SUBTARGET] = [
+        DefaultInfo(default_output = extended_dsym_info, other_outputs = extended_dsym_json_info.outputs),
+    ]
+
+    binary_name = get_product_name(ctx)
+
+    # Debug binaries used for symbolication without dSYMs.
+    # Create a symlink such that the basename of the exposed debug artifact
+    # matches the name the binary has within the bundle (`binary_name`) instead
+    # of the basename of the linker output. That's needed since GSYM upload
+    # has to know the filename under which the binary ends up in the bundle.
+    unstripped_binary_artifact = binary_outputs.unstripped_binary if binary_outputs.unstripped_binary else binary_outputs.binary
+    renamed_unstripped_binary = ctx.actions.symlink_file(
+        ctx.actions.declare_output("__unstripped_binaries__", binary_name),
+        unstripped_binary_artifact,
+    )
+    binary_debug_artifacts = [renamed_unstripped_binary] + flatten([info.binaries for info in deps_debuggable_infos])
+
+    sub_targets[_PLIST] = [DefaultInfo(default_output = apple_bundle_part_list_output.info_plist_part.source)]
+    info_plist_info = AppleInfoPlistInfo(info_plist = apple_bundle_part_list_output.info_plist_part.source)
+
+    sub_targets[_XCTOOLCHAIN_SUB_TARGET] = ctx.attrs._apple_xctoolchain.providers
+
+    # Define the xcode data sub target
+    plist_bundle_relative_path = get_apple_bundle_part_relative_destination_path(ctx, apple_bundle_part_list_output.info_plist_part)
+    xcode_data_default_info, xcode_data_info = generate_xcode_data(
+        ctx,
+        "apple_bundle",
+        bundle,
+        _xcode_populate_attributes,
+        processed_info_plist = apple_bundle_part_list_output.info_plist_part.source,
+        info_plist_relative_path = plist_bundle_relative_path,
+    )
+    sub_targets[XCODE_DATA_SUB_TARGET] = xcode_data_default_info
+
+    install_data = generate_install_data(ctx, plist_bundle_relative_path)
+
+    # Collect extra bundle outputs
+    extra_output_provider = _extra_output_provider(ctx)
+    # @oss-disable[end= ]: extra_output_subtargets = subtargets_for_apple_bundle_extra_outputs(ctx, extra_output_provider)
+    # @oss-disable[end= ]: sub_targets.update(extra_output_subtargets)
+
+    # index store
+    index_store_subtargets, index_store_info = _index_store_data(ctx, deps_with_binary)
+    sub_targets.update(index_store_subtargets)
+
+    # modularization dependency graphs
+    mod_dep_graph_subtargets, mod_dep_graph_info = _modularization_dep_graph_data(ctx, deps_with_binary)
+    sub_targets.update(mod_dep_graph_subtargets)
+
+    target_stats_providers, target_stats_subtargets = target_stats_aggregate_providers_and_subtargets(ctx, deps = deps_with_binary)
+    sub_targets.update(target_stats_subtargets)
+
+    bundle_and_dsym_info_json = {
+        "bundle": bundle,
+        "dsym": dsym_json_info.json_object,
+    }
+    bundle_and_dsym_info = ctx.actions.write_json("bundle-and-dsym-info.json", bundle_and_dsym_info_json, has_content_based_path = False)
+    sub_targets["bundle-and-dsym-info"] = [
+        DefaultInfo(
+            default_output = bundle_and_dsym_info,
+            other_outputs = [bundle] + dsym_json_info.outputs,
+        ),
+    ]
+
+    required_reasons_validator_output = get_required_reasons_validator_output(
+        ctx,
+        aggregated_debug_info.debug_info.debug_info_tset,
+    )
+    if required_reasons_validator_output != None:
+        sub_targets["required-reasons-validation"] = [
+            DefaultInfo(default_output = required_reasons_validator_output),
+        ]
+        validation_providers = [
+            ValidationInfo(
+                validations = [
+                    ValidationSpec(
+                        name = "required_reasons_usage",
+                        validation_result = required_reasons_validator_output,
+                    ),
+                ],
+            ),
+        ]
+    else:
+        validation_providers = []
+
+    diagnostics_info = cxx_transitive_diagnostics_combine(
+        ctx = ctx,
+        diagnostics = [],
+        deps = deps_with_binary,
+    )
+    transitive_diagnostic_artifacts = project_artifacts(
+        actions = ctx.actions,
+        tsets = diagnostics_info.transitive_diagnostics,
+    )
+    sub_targets["check"] = [DefaultInfo(default_output = None, other_outputs = transitive_diagnostic_artifacts)]
+
+    sub_targets["swiftmodule-change-analysis"] = [DefaultInfo(default_output = get_swiftmodule_change_analysis_output(ctx, deps_with_binary))]
+
+    providers = (
+        [
+            DefaultInfo(default_output = bundle, sub_targets = sub_targets),
+            AppleBundleInfo(
+                bundle = bundle,
+                bundle_type = _infer_apple_bundle_type(ctx),
+                binary_name = binary_name,
+                contains_watchapp = lazy.is_any(lambda part: part.destination == AppleBundleDestination("watchapp"), apple_bundle_part_list_output.parts),
+                skip_copying_swift_stdlib = ctx.attrs.skip_copying_swift_stdlib,
+                codesign_manifest_tree = bundle_result.codesign_manifest_tree,
+                signing_context_tree = bundle_result.signing_context_tree,
+                signing_info = bundle_result.signing_info,
+            ),
+            AppleDebuggableInfo(
+                dsyms = dsym_artifacts,
+                binaries = binary_debug_artifacts,
+                debug_info_tset = aggregated_debug_info.debug_info.debug_info_tset,
+                filtered_map = aggregated_debug_info.debug_info.filtered_map,
+                selective_metadata = all_selective_metadata,
+            ),
+            InstallInfo(
+                installer = ctx.attrs._apple_toolchain[AppleToolchainInfo].installer,
+                files = {
+                    "app_bundle": bundle,
+                    "options": install_data,
+                },
+            ),
+            RunInfo(args = primary_binary_path_arg),
+            linker_map_info,
+            xcode_data_info,
+            extra_output_provider,
+            link_cmd_debug_info,
+            index_store_info,
+            mod_dep_graph_info,
+            info_plist_info,
+        ]
+        + target_stats_providers
+        + bundle_result.providers
+        + validation_providers
+    )
+    if xplugins_debug_info:
+        providers.append(xplugins_debug_info)
+    providers.append(xplugins_function_mapping_manifest_info)
+
+    return providers
+
+def _xcode_populate_attributes(ctx, processed_info_plist: Artifact, info_plist_relative_path: str) -> dict[str, typing.Any]:
+    data = {
+        XcodeDataInfoKeys.BUNDLE_TYPE: _infer_apple_bundle_type(ctx),
+        XcodeDataInfoKeys.DEPLOYMENT_VERSION: get_bundle_min_target_version(ctx, get_default_binary_dep(ctx.attrs.binary)),
+        XcodeDataInfoKeys.INFO_PLIST: ctx.attrs.info_plist,
+        XcodeDataInfoKeys.PROCESSED_INFO_PLIST: processed_info_plist,
+        XcodeDataInfoKeys.INFO_PLIST_RELATIVE_PATH: info_plist_relative_path,
+        XcodeDataInfoKeys.PRODUCT_NAME: get_product_name(ctx),
+        XcodeDataInfoKeys.SDK: get_apple_sdk_name(ctx),
+        XcodeDataInfoKeys.APP_EXTENSION_DEPENDENCIES: _app_extension_deps(ctx),
+    }
+
+    apple_xcode_data_add_xctoolchain(ctx, data)
+    return data
+
+def _linker_maps_data(actions: AnalysisActions, deps_with_binary: list[Dependency]) -> (Artifact, AppleBundleLinkerMapInfo):
+    deps_linker_map_infos = filter(
+        None,
+        [dep.get(AppleBundleLinkerMapInfo) for dep in deps_with_binary],
+    )
+    deps_linker_maps = flatten([info.linker_maps for info in deps_linker_map_infos])
+    all_maps = {map.basename: map for map in deps_linker_maps}
+    directory = actions.copied_dir(
+        "LinkMap",
+        all_maps,
+        has_content_based_path = False,
+    )
+    provider = AppleBundleLinkerMapInfo(linker_maps = all_maps.values())
+    return (directory, provider)
+
+def _link_command_debug_data(actions: AnalysisActions, deps_with_binary: list[Dependency]) -> (Artifact, LinkCommandDebugOutputInfo):
+    debug_output_infos = filter(
+        None,
+        [dep.get(LinkCommandDebugOutputInfo) for dep in deps_with_binary],
+    )
+    all_debug_infos = flatten([debug_info.debug_outputs for debug_info in debug_output_infos])
+    link_cmd_debug_output_file = make_link_command_debug_output_json_info(actions, all_debug_infos)
+    return link_cmd_debug_output_file, LinkCommandDebugOutputInfo(debug_outputs = all_debug_infos)
+
+def _index_store_data(ctx: AnalysisContext, deps_with_binary: list[Dependency]) -> (dict[str, list[Provider]], IndexStoreInfo):
+    index_store_subtargets, index_store_info = create_index_store_subtargets_and_provider(ctx, [], [], deps_with_binary)
+    return index_store_subtargets, index_store_info
+
+def _modularization_dep_graph_data(ctx: AnalysisContext, deps_with_binary: list[Dependency]) -> (dict[str, list[Provider]], ModularizationDependencyGraphInfo):
+    subtargets, info = create_modularization_dep_graph_subtargets_and_provider(ctx, None, deps_with_binary)
+    return subtargets, info
+
+def _extra_output_provider(ctx: AnalysisContext) -> AppleBundleExtraOutputsInfo:
+    # Collect the sub_targets for this bundle's binary that are extra_linker_outputs.
+    extra_outputs = []
+    for binary_dep in get_flattened_binary_deps(ctx.attrs.binary):
+        linker_outputs = ctx.attrs._apple_toolchain[AppleToolchainInfo].extra_linker_outputs
+        binary_outputs = {k: v[DefaultInfo].default_outputs for k, v in binary_dep[DefaultInfo].sub_targets.items() if k in linker_outputs}
+        extra_outputs.append(
+            AppleBinaryExtraOutputsInfo(
+                name = get_product_name(ctx),
+                default_output = binary_dep[DefaultInfo].default_outputs[0],
+                extra_outputs = binary_outputs,
+            )
+        )
+
+    # Collect the transitive extra bundle outputs from the deps.
+    for dep in ctx.attrs.deps:
+        if AppleBundleExtraOutputsInfo in dep:
+            extra_outputs.extend(dep[AppleBundleExtraOutputsInfo].extra_outputs)
+
+    return AppleBundleExtraOutputsInfo(extra_outputs = extra_outputs)
+
+def _app_extension_deps(ctx: AnalysisContext) -> list[str]:
+    app_extension_deps = []
+    for dep in ctx.attrs.deps:
+        apple_bundle_info = dep.get(AppleBundleInfo)
+        if apple_bundle_info and paths.split_extension(apple_bundle_info.bundle.short_path)[1] == ".appex":
+            app_extension_deps.append(str(dep.label.raw_target()))
+    return app_extension_deps
+
+def generate_install_data(ctx: AnalysisContext, plist_path: str, populate_rule_specific_attributes_func: [typing.Callable, None] = None, **kwargs) -> Artifact:
+    data = {
+        "fullyQualifiedName": ctx.label,
+        "info_plist": plist_path,
+        "platform_name": get_apple_sdk_name(ctx),
+        ## TODO(T110665037): read from .buckconfig
+        # We require the user to have run `xcode-select` and `/var/db/xcode_select_link` to symlink
+        # to the selected Xcode. e.g: `/Applications/Xcode_14.2.app/Contents/Developer`
+        "xcode_developer_path": "/var/db/xcode_select_link",
+    }
+
+    if populate_rule_specific_attributes_func:
+        data.update(populate_rule_specific_attributes_func(ctx, **kwargs))
+
+    return ctx.actions.write_json(_INSTALL_DATA_FILE_NAME, data, has_content_based_path = False)
diff --git a/buck2/prelude/apple/apple_bundle_config.bzl b/buck2/prelude/apple/apple_bundle_config.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_bundle_config.bzl
@@ -0,0 +1,56 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:buckconfig.bzl", "read_bool")
+load(":apple_code_signing_types.bzl", "CodeSignConfiguration")
+
+def _read_bool(config: str, default: [None, bool] = None) -> [None, bool]:
+    return read_bool("apple", config, default = default, required = False, root_cell = True)
+
+def _get_code_signing_configuration() -> str:
+    is_dry_run = _read_bool("dry_run_code_signing", False)
+
+    # This is a kill switch for the feature, it can also be disabled by setting
+    # `apple.fast_adhoc_signing_enabled=false` in a global buckconfig file.
+    is_fast_adhoc_signing_enabled = _read_bool("fast_adhoc_signing_enabled", True)
+
+    is_codesign_execution_bypass_enabled = _read_bool("codesign_execution_bypass", False)
+    if is_dry_run and is_codesign_execution_bypass_enabled:
+        fail("Dry run and execution bypass are mutually exclusive, pick one")
+
+    if is_dry_run:
+        return CodeSignConfiguration("dry-run").value
+    elif is_codesign_execution_bypass_enabled:
+        # Fast adhoc only makes sense if we're executing codesign commands,
+        # hence execution bypass takes precedence
+        return CodeSignConfiguration("execution-bypass").value
+    elif is_fast_adhoc_signing_enabled:
+        return CodeSignConfiguration("fast-adhoc").value
+    else:
+        return CodeSignConfiguration("none").value
+
+def apple_bundle_config() -> dict[str, typing.Any]:
+    return {
+        "_bundling_cache_buster": read_root_config("apple", "bundling_cache_buster", None),
+        "_bundling_log_file_enabled": _read_bool("bundling_log_file_enabled", True),
+        "_bundling_log_file_level": read_root_config("apple", "bundling_log_file_level", None),
+        "_code_signing_configuration": _get_code_signing_configuration(),
+        "_codesign_command_override": read_root_config("apple", "codesign_command_override", None),
+        "_codesign_identities_command_override": read_root_config("apple", "codesign_identities_command_override", None),
+        "_codesign_type": read_root_config("apple", "codesign_type_override", None),
+        "_compile_resources_locally_override": _read_bool("compile_resources_locally_override"),
+        "_embed_provisioning_profile_when_adhoc_code_signing": _read_bool("embed_provisioning_profile_when_adhoc_code_signing"),
+        "_fast_adhoc_signing_probe_enabled": _read_bool("fast_adhoc_signing_probe_enabled", False),
+        "_fast_provisioning_profile_parsing_enabled": _read_bool("fast_provisioning_profile_parsing_enabled", False),
+        "_incremental_bundling_enabled": _read_bool("incremental_bundling_enabled", True),
+        "_info_plist_identify_build_system_default": _read_bool("info_plist_identify_build_system", True),
+        "_no_check_certificates": _read_bool("no_check_certificates", False),
+        "_profile_bundling_enabled": _read_bool("profile_bundling_enabled", False),
+        "_skip_adhoc_resigning_scrubbed_frameworks_override": _read_bool("skip_adhoc_resigning_scrubbed_frameworks_override"),
+        "_use_entitlements_when_adhoc_code_signing": _read_bool("use_entitlements_when_adhoc_code_signing"),
+    }
diff --git a/buck2/prelude/apple/apple_bundle_destination.bzl b/buck2/prelude/apple/apple_bundle_destination.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_bundle_destination.bzl
@@ -0,0 +1,159 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(":apple_bundle_utility.bzl", "get_apple_versioned_macos_bundle_value_primitive")
+
+# Abstraction of a place in a resulting bundle where file or directory will be copied. Actual value
+# of path relative to bundle root depends on a platform. This class is an implementation detail and
+# is not exposed to user unlike `AppleResourceDestination`.
+# v1 code is `com/facebook/buck/apple/AppleBundleDestination.java`
+AppleBundleDestination = enum(
+    "resources",
+    "frameworks",
+    "executables",
+    "plugins",
+    "xpcservices",
+    "metadata",
+    "watchapp",
+    "headers",
+    "modules",
+    "quicklook",
+    "bundleroot",
+    "loginitems",
+    "launchagents",
+    "appclips",
+    "extensionkit_extensions",
+)
+
+AppleBundleDestinationPaths = record(
+    resources = field(str, ""),
+    frameworks = field(str, ""),
+    executables = field(str, ""),
+    plugins = field(str, ""),
+    xpcservices = field(str, ""),
+    metadata = field(str, ""),
+    watchapp = field(str, ""),
+    headers = field(str, ""),
+    modules = field(str, ""),
+    quicklook = field(str, ""),
+    bundleroot = field(str, ""),
+    loginitems = field(str, ""),
+    launchagents = field(str, ""),
+    appclips = field(str, ""),
+    extensionkit_extensions = field(str, ""),
+)
+
+_IOSBundleDestinationPaths = AppleBundleDestinationPaths(
+    frameworks = "Frameworks",
+    plugins = "PlugIns",
+    xpcservices = "XPCServices",
+    watchapp = "Watch",
+    quicklook = "Library/QuickLook",
+    appclips = "AppClips",
+    extensionkit_extensions = "Extensions",
+)
+
+_IOSFrameworkBundleDestinationPaths = AppleBundleDestinationPaths(
+    frameworks = "Frameworks",
+    xpcservices = "XPCServices",
+    headers = "Headers",
+    modules = "Modules",
+)
+
+macOS_content_path = "Contents"
+_MacOSBundleDestinationPaths = AppleBundleDestinationPaths(
+    resources = paths.join(macOS_content_path, "Resources"),
+    frameworks = paths.join(macOS_content_path, "Frameworks"),
+    executables = paths.join(macOS_content_path, "MacOS"),
+    plugins = paths.join(macOS_content_path, "PlugIns"),
+    xpcservices = paths.join(macOS_content_path, "XPCServices"),
+    metadata = macOS_content_path,
+    watchapp = macOS_content_path,
+    headers = macOS_content_path,
+    modules = macOS_content_path,
+    quicklook = paths.join(macOS_content_path, "Library/QuickLook"),
+    bundleroot = macOS_content_path,
+    loginitems = paths.join(macOS_content_path, "Library/LoginItems"),
+    launchagents = paths.join(macOS_content_path, "Library/LaunchAgents"),
+)
+
+_MacOSFrameworkBundleDestinationPaths = AppleBundleDestinationPaths(
+    resources = "Resources",
+    frameworks = "Frameworks",
+    plugins = "PlugIns",
+    xpcservices = "XPCServices",
+    metadata = "Resources",
+    headers = "Headers",
+    modules = "Modules",
+)
+
+macOS_versioned_path = "Versions/A"
+_MacOSVersionedFrameworkBundleDestinationPaths = AppleBundleDestinationPaths(
+    resources = paths.join(macOS_versioned_path, "Resources"),
+    frameworks = paths.join(macOS_versioned_path, "Frameworks"),
+    plugins = paths.join(macOS_versioned_path, "PlugIns"),
+    xpcservices = paths.join(macOS_versioned_path, "XPCServices"),
+    metadata = paths.join(macOS_versioned_path, "Resources"),
+    headers = paths.join(macOS_versioned_path, "Headers"),
+    modules = paths.join(macOS_versioned_path, "Modules"),
+    executables = macOS_versioned_path,
+)
+
+def _get_apple_bundle_destinations_for_sdk_name(name: str) -> AppleBundleDestinationPaths:
+    if name == "macosx" or name == "maccatalyst":
+        return _MacOSBundleDestinationPaths
+    else:
+        return _IOSBundleDestinationPaths
+
+def _get_apple_framework_bundle_destinations_for_sdk_name(name: str, versioned_macos_bundle: bool) -> AppleBundleDestinationPaths:
+    if name.startswith("mac"):
+        if get_apple_versioned_macos_bundle_value_primitive(name, versioned_macos_bundle):
+            return _MacOSVersionedFrameworkBundleDestinationPaths
+        else:
+            return _MacOSFrameworkBundleDestinationPaths
+    else:
+        return _IOSFrameworkBundleDestinationPaths
+
+def bundle_relative_path_for_destination(destination: AppleBundleDestination, sdk_name: str, extension: str, versioned_macos_bundle: bool) -> str:
+    if extension == "framework":
+        bundle_destinations = _get_apple_framework_bundle_destinations_for_sdk_name(sdk_name, versioned_macos_bundle)
+    else:
+        bundle_destinations = _get_apple_bundle_destinations_for_sdk_name(sdk_name)
+
+    if destination == AppleBundleDestination("resources"):
+        return bundle_destinations.resources
+    elif destination == AppleBundleDestination("frameworks"):
+        return bundle_destinations.frameworks
+    elif destination == AppleBundleDestination("executables"):
+        return bundle_destinations.executables
+    elif destination == AppleBundleDestination("extensionkit_extensions"):
+        return bundle_destinations.extensionkit_extensions
+    elif destination == AppleBundleDestination("plugins"):
+        return bundle_destinations.plugins
+    elif destination == AppleBundleDestination("xpcservices"):
+        return bundle_destinations.xpcservices
+    elif destination == AppleBundleDestination("metadata"):
+        return bundle_destinations.metadata
+    elif destination == AppleBundleDestination("watchapp"):
+        return bundle_destinations.watchapp
+    elif destination == AppleBundleDestination("headers"):
+        return bundle_destinations.headers
+    elif destination == AppleBundleDestination("modules"):
+        return bundle_destinations.modules
+    elif destination == AppleBundleDestination("quicklook"):
+        return bundle_destinations.quicklook
+    elif destination == AppleBundleDestination("bundleroot"):
+        return bundle_destinations.bundleroot
+    elif destination == AppleBundleDestination("loginitems"):
+        return bundle_destinations.loginitems
+    elif destination == AppleBundleDestination("launchagents"):
+        return bundle_destinations.launchagents
+    elif destination == AppleBundleDestination("appclips"):
+        return bundle_destinations.appclips
+    fail("Unsupported Apple bundle destination {}".format(destination))
diff --git a/buck2/prelude/apple/apple_bundle_part.bzl b/buck2/prelude/apple/apple_bundle_part.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_bundle_part.bzl
@@ -0,0 +1,666 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_provisioning_profile_sources.bzl", "AppleProvisioningProfileSourcesInfo")
+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftToolchainInfo")
+load("@prelude//utils:utils.bzl", "value_or")
+load(":apple_bundle_destination.bzl", "AppleBundleDestination", "bundle_relative_path_for_destination")
+load(
+    ":apple_bundle_types.bzl",
+    "AppleBundleCodesignManifestTree",
+    "AppleBundleManifest",
+    "AppleBundleManifestInfo",
+    "AppleBundleManifestLogFiles",
+    "AppleBundleSigningContextTree",
+)
+load(":apple_bundle_utility.bzl", "get_extension_attr", "get_product_name")
+load(":apple_code_signing_types.bzl", "CodeSignConfiguration", "CodeSignType", "get_code_signing_configuration_attr_value")
+load(":apple_entitlements.bzl", "get_entitlements_codesign_args", "should_include_entitlements")
+load(":apple_error_handler.bzl", "apple_build_error_handler")
+load(":apple_sdk.bzl", "get_apple_sdk_name")
+load(":apple_sdk_metadata.bzl", "get_apple_sdk_metadata_for_sdk_name")
+load(":apple_swift_stdlib.bzl", "should_copy_swift_stdlib")
+load(":apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")
+
+# Must match the null case returned by `serialize_signing_context_data`:
+# https://www.internalfb.com/code/fbsource/fbcode/buck2/prelude/apple/tools/bundling/signing_context_data.py?lines=39%2C58
+_EMPTY_SIGNING_CONTEXT_DATA = {
+    "provisioning_profile_data_base64": None,
+    "selected_identity": None,
+    "signing_context": None,
+    "version": 1,
+}
+
+# Defines where and what should be copied into
+AppleBundlePart = record(
+    # A file or directory which content should be copied
+    source = field(Artifact),
+    # Where the source should be copied, the actual destination directory
+    # inside bundle depends on target platform
+    destination = AppleBundleDestination,
+    # New file name if it should be renamed before copying.
+    # Empty string value is applicable only when `source` is a directory,
+    # in such case only content of the directory will be copied, as opposed to the directory itself.
+    # When value is `None`, directory or file will be copied as it is, without renaming.
+    new_name = field([str, None], None),
+    # Marks parts which should be code signed separately from the whole bundle.
+    codesign_on_copy = field(bool, False),
+    # Entitlements to use when this part is code signed separately.
+    codesign_entitlements = field(Artifact | None, None),
+    # If present, override the codesign flags with these flags, when this part is code signed separately.
+    codesign_flags_override = field([list[str], None], None),
+    # If present, additional paths to be codesigned when copying.
+    extra_codesign_paths = field([list[str], None], None),
+)
+
+# Represents an `AppleBundlePart` which has an associated codesign manifest
+AppleBundleCodesignManifestTreePart = record(
+    bundle_part = field(AppleBundlePart),
+    codesign_manifest_tree = field(AppleBundleCodesignManifestTree),
+)
+
+# Represents an `AppleBundlePart` which has an associated signing context
+AppleBundleSigningContextTreePart = record(
+    bundle_part = field(AppleBundlePart),
+    signing_context_tree = field(AppleBundleSigningContextTree),
+)
+
+SwiftStdlibArguments = record(
+    primary_binary_rel_path = field(str),
+)
+
+AppleBundleConstructionResult = record(
+    providers = field(list[Provider]),
+    sub_targets = field(dict[str, list[Provider]]),
+    codesign_manifest_tree = field(AppleBundleCodesignManifestTree),
+    signing_context_tree = field(AppleBundleSigningContextTree),
+    signing_info = field(Artifact),
+)
+
+def bundle_output(ctx: AnalysisContext) -> Artifact:
+    bundle_dir_name = get_bundle_dir_name(ctx)
+    output = ctx.actions.declare_output(bundle_dir_name, has_content_based_path = False)
+    return output
+
+def _bundling_log_args(ctx: AnalysisContext, output_name: str):
+    if not ctx.attrs._bundling_log_file_enabled:
+        return ([], None)
+
+    output = ctx.actions.declare_output(output_name, has_content_based_path = False)
+    args = ["--log-file", output.as_output()]
+    if ctx.attrs._bundling_log_file_level:
+        args.extend(["--log-level-file", ctx.attrs._bundling_log_file_level])
+    return (args, output)
+
+def assemble_bundle(
+    ctx: AnalysisContext,
+    bundle: Artifact,
+    parts: list[AppleBundlePart],
+    codesign_manifest_parts: list[AppleBundleCodesignManifestTreePart],
+    signing_context_parts: list[AppleBundleSigningContextTreePart],
+    info_plist_part: [AppleBundlePart, None],
+    swift_stdlib_args: [SwiftStdlibArguments, None],
+    extra_hidden: list[Artifact] = [],
+    skip_adhoc_signing: bool = False,
+    incremental_bundling_override = None,
+) -> AppleBundleConstructionResult:
+    """
+    Returns extra subtargets related to bundling.
+    """
+    all_parts = parts + [info_plist_part] if info_plist_part else []
+    codesign_type = _detect_codesign_type(ctx, skip_adhoc_signing)
+    spec_file = _bundle_spec_json(ctx, all_parts, codesign_type)
+
+    tools = ctx.attrs._apple_tools[AppleToolsInfo]
+    tool = tools.assemble_bundle
+
+    codesign_selection_args = []
+    codesign_execution_args = []
+    codesign_bundle_extra_args = []
+
+    codesign_tool = ctx.attrs._apple_toolchain[AppleToolchainInfo].codesign
+    if ctx.attrs._codesign_command_override:
+        codesign_tool = ctx.attrs._codesign_command_override[RunInfo]
+
+    code_signing_configuration = get_code_signing_configuration_attr_value(ctx)
+    if code_signing_configuration == CodeSignConfiguration("dry-run"):
+        codesign_configuration_args = ["--codesign-configuration", "dry-run"]
+        codesign_tool = tools.dry_codesign_tool
+    elif code_signing_configuration == CodeSignConfiguration("execution-bypass"):
+        codesign_configuration_args = ["--codesign-configuration", "execution-bypass"]
+    elif code_signing_configuration == CodeSignConfiguration("fast-adhoc"):
+        if _get_fast_adhoc_signing_enabled(ctx):
+            codesign_configuration_args = ["--codesign-configuration", "fast-adhoc"]
+            if getattr(ctx.attrs, "_fast_adhoc_signing_probe_enabled", False):
+                codesign_configuration_args = codesign_configuration_args + ["--fast-adhoc-signing-probe-enabled"]
+        else:
+            codesign_configuration_args = []
+    elif code_signing_configuration == CodeSignConfiguration("none"):
+        codesign_configuration_args = []
+    else:
+        fail("Code signing configuration `{}` not supported".format(code_signing_configuration))
+
+    codesign_required = codesign_type != CodeSignType("skip")
+    swift_support_required = swift_stdlib_args and (not ctx.attrs.skip_copying_swift_stdlib) and should_copy_swift_stdlib(bundle.extension)
+
+    sdk_name = get_apple_sdk_name(ctx)
+    if codesign_required or swift_support_required:
+        platform_args = ["--platform", sdk_name]
+    else:
+        platform_args = []
+
+    if swift_support_required:
+        swift_args = [
+            "--binary-destination",
+            swift_stdlib_args.primary_binary_rel_path,
+            "--frameworks-destination",
+            bundle_relative_path_for_destination(AppleBundleDestination("frameworks"), sdk_name, ctx.attrs.extension, ctx.attrs.versioned_macos_bundle),
+            "--plugins-destination",
+            bundle_relative_path_for_destination(AppleBundleDestination("plugins"), sdk_name, ctx.attrs.extension, ctx.attrs.versioned_macos_bundle),
+            "--extensionkit-extensions-destination",
+            bundle_relative_path_for_destination(
+                AppleBundleDestination("extensionkit_extensions"), sdk_name, ctx.attrs.extension, ctx.attrs.versioned_macos_bundle
+            ),
+            "--appclips-destination",
+            bundle_relative_path_for_destination(AppleBundleDestination("appclips"), sdk_name, ctx.attrs.extension, ctx.attrs.versioned_macos_bundle),
+            "--swift-stdlib-command",
+            cmd_args(ctx.attrs._apple_toolchain[SwiftToolchainInfo].swift_stdlib_tool, delimiter = " ", quote = "shell"),
+            "--sdk-root",
+            ctx.attrs._apple_toolchain[SwiftToolchainInfo].sdk_path,
+        ]
+    else:
+        swift_args = []
+
+    if codesign_required:
+        codesign_execution_args += [
+            "--codesign",
+        ]
+
+        codesign_bundle_extra_args += [
+            "--codesign-tool",
+            codesign_tool,
+        ]
+
+        profile_selection_required = _should_embed_provisioning_profile(ctx, codesign_type)
+        if profile_selection_required:
+            sources_info = ctx.attrs._provisioning_profile_sources[AppleProvisioningProfileSourcesInfo]
+            for i, source in enumerate(sources_info.sources):
+                if source.profiles:
+                    profiles_dir = ctx.actions.symlinked_dir(
+                        "provisioning_profile_source_{}".format(i),
+                        {profile.short_path: profile for profile in source.profiles},
+                        has_content_based_path = False,
+                    )
+                    codesign_selection_args.extend(["--profiles-dir", profiles_dir])
+                elif source.directory:
+                    codesign_selection_args.extend(["--profiles-dir", source.directory])
+
+            identities_command = ctx.attrs._apple_toolchain[AppleToolchainInfo].codesign_identities_command
+            if ctx.attrs._codesign_identities_command_override:
+                identities_command = ctx.attrs._codesign_identities_command_override[RunInfo]
+            identities_command_args = ["--codesign-identities-command", cmd_args(identities_command)] if identities_command else []
+            codesign_selection_args.extend(identities_command_args)
+
+        if codesign_type == CodeSignType("adhoc"):
+            codesign_selection_args.append("--ad-hoc")
+            if ctx.attrs.codesign_identity:
+                codesign_selection_args.extend(["--ad-hoc-codesign-identity", ctx.attrs.codesign_identity])
+            if profile_selection_required:
+                codesign_selection_args.append("--embed-provisioning-profile-when-signing-ad-hoc")
+
+        entitlements_args = get_entitlements_codesign_args(ctx, codesign_type)
+        codesign_execution_args += entitlements_args
+
+        if getattr(ctx.attrs, "entitlements_suffixed_key_map", None):
+            arg = ["--entitlements-suffixed-key-map", json.encode(ctx.attrs.entitlements_suffixed_key_map)]
+            codesign_execution_args += arg
+        if getattr(ctx.attrs, "entitlements_removed_keys", None):
+            arg = ["--entitlements-removed-keys", json.encode(ctx.attrs.entitlements_removed_keys)]
+            codesign_execution_args += arg
+        if getattr(ctx.attrs, "entitlements_removed_values_map", None):
+            arg = ["--entitlements-removed-values-map", json.encode(ctx.attrs.entitlements_removed_values_map)]
+            codesign_execution_args += arg
+        codesign_bundle_extra_args += _get_extra_codesign_args(ctx)
+
+        info_plist_args = (
+            [
+                "--info-plist-source",
+                info_plist_part.source,
+                "--info-plist-destination",
+                get_apple_bundle_part_relative_destination_path(ctx, info_plist_part),
+            ]
+            if info_plist_part
+            else []
+        )
+        codesign_execution_args.extend(info_plist_args)
+
+        if ctx.attrs.provisioning_profile_filter:
+            arg = [
+                "--provisioning-profile-filter",
+                ctx.attrs.provisioning_profile_filter,
+            ]
+            codesign_selection_args.extend(arg)
+
+        strict_provisioning_profile_search = value_or(ctx.attrs.strict_provisioning_profile_search, ctx.attrs._strict_provisioning_profile_search_default)
+        if strict_provisioning_profile_search:
+            codesign_selection_args.append("--strict-provisioning-profile-search")
+
+        if ctx.attrs._fast_provisioning_profile_parsing_enabled:
+            codesign_selection_args.append("--fast-provisioning-profile-parsing")
+
+        if ctx.attrs._no_check_certificates:
+            codesign_selection_args.append("--no-check-certificates")
+
+        if ctx.attrs.entitlements_verification_check_enabled:
+            codesign_selection_args.append("--verify-entitlements")
+
+    elif codesign_type == CodeSignType("skip"):
+        pass
+    else:
+        fail("Code sign type `{}` not supported".format(codesign_type))
+
+    force_local_bundling = codesign_required
+    env = {}
+    cache_buster = ctx.attrs._bundling_cache_buster
+    if cache_buster:
+        env["BUCK2_BUNDLING_CACHE_BUSTER"] = cache_buster
+
+    if codesign_required:
+        signing_context_path = ctx.actions.declare_output("signing_context.json", has_content_based_path = False)
+        resolve_command = [
+            tools.resolve_signing_context,
+            "--output",
+            signing_context_path.as_output(),
+        ]
+        resolution_log_args, resolution_log_output = _bundling_log_args(ctx, "signing_context_resolution_log.txt")
+        resolve_command.extend(resolution_log_args)
+        ctx.actions.run(
+            cmd_args(
+                resolve_command + platform_args + codesign_selection_args + codesign_execution_args,
+            ),
+            local_only = force_local_bundling,
+            prefer_local = not force_local_bundling,
+            category = "apple_resolve_signing_context",
+            env = env,
+            error_handler = apple_build_error_handler,
+        )
+        signing_context_path_arg = ["--signing-context-path", signing_context_path]
+
+        signing_info_output = ctx.actions.declare_output("signing-info.json", has_content_based_path = False)
+        ctx.actions.run(
+            cmd_args(
+                [
+                    tools.signing_info,
+                    "--signing-context-path",
+                    signing_context_path,
+                    "--output",
+                    signing_info_output.as_output(),
+                ],
+            ),
+            category = "apple_signing_info",
+            error_handler = apple_build_error_handler,
+        )
+    else:
+        resolution_log_output = None
+        # Avoid adding a resolver action to every unsigned bundle target.
+        signing_context_path = ctx.actions.write_json(
+            "signing_context.json",
+            _EMPTY_SIGNING_CONTEXT_DATA,
+        )
+        signing_context_path_arg = ["--signing-context-path", signing_context_path]
+        signing_info_output = ctx.actions.write_json("signing-info.json", {})
+
+    # - Always request codesign manifest, even if signing not required.
+    #   Removes the need for conditional subtargets and fields in JSON output.
+    #  - Manifest file name reflects whether signing is required or not.
+    #    Useful for debugging purposes.
+    codesign_manifest_file_name = "codesign_manifest.json" if codesign_required else "placeholder_codesign_manifest.json"
+    codesign_manifest = ctx.actions.declare_output(codesign_manifest_file_name, has_content_based_path = False)
+    codesign_bundle_extra_args += [
+        "--codesign-manifest",
+        codesign_manifest.as_output(),
+    ]
+
+    extra_context_args = [
+        "--resources-destination",
+        bundle_relative_path_for_destination(AppleBundleDestination("resources"), sdk_name, ctx.attrs.extension, ctx.attrs.versioned_macos_bundle),
+    ]
+
+    command = cmd_args(
+        [
+            tool,
+            "--output",
+            bundle.as_output(),
+            "--spec",
+            spec_file,
+        ]
+        + codesign_execution_args
+        + codesign_bundle_extra_args
+        + platform_args
+        + swift_args
+        + extra_context_args
+        + signing_context_path_arg,
+        hidden = [part.source for part in all_parts]
+        + [part.codesign_entitlements for part in all_parts if part.codesign_entitlements]
+        +
+        # Ensures any genrule deps get built, such targets are used for validation
+        extra_hidden,
+    )
+    run_incremental_args = {}
+    incremental_state = ctx.actions.declare_output("incremental_state.json", has_content_based_path = False).as_output()
+
+    # Fallback to value from buckconfig
+    incremental_bundling_enabled = ctx.attrs.incremental_bundling_enabled or ctx.attrs._incremental_bundling_enabled
+    if incremental_bundling_override != None:
+        incremental_bundling_enabled = incremental_bundling_override
+
+    if incremental_bundling_enabled:
+        command.add("--incremental-state", incremental_state)
+        run_incremental_args = {
+            "metadata_env_var": "ACTION_METADATA",
+            "metadata_path": "action_metadata.json",
+            "no_outputs_cleanup": True,
+        }
+        category = "apple_assemble_bundle_incremental"
+    else:
+        # overwrite file with incremental state so if previous and next builds are incremental
+        # (as opposed to the current non-incremental one), next one won't assume there is a
+        # valid incremental state.
+        command.add(cmd_args(hidden = ctx.actions.write_json(incremental_state, {})))
+        category = "apple_assemble_bundle"
+
+    if ctx.attrs._profile_bundling_enabled:
+        profile_output = ctx.actions.declare_output("bundling_profile.txt", has_content_based_path = False).as_output()
+        command.add("--profile-output", profile_output)
+
+    subtargets = {}
+    if resolution_log_output:
+        subtargets["signing-context-resolution-log"] = [DefaultInfo(default_output = resolution_log_output)]
+    bundling_log_args, bundling_log_output = _bundling_log_args(ctx, "bundling_log.txt")
+    command.add(bundling_log_args)
+    if bundling_log_output:
+        subtargets["bundling-log"] = [DefaultInfo(default_output = bundling_log_output)]
+
+    command.add("--check-conflicts")
+    if ctx.attrs.versioned_macos_bundle:
+        command.add("--versioned-if-macos")
+    if getattr(ctx.attrs, "include_build_info_file", False):
+        extension_allowed = ctx.attrs.extension in ctx.attrs.include_build_info_file_in_bundles_with_extensions
+        if extension_allowed:
+            command.add("--include-build-info-file")
+    command.add(codesign_configuration_args)
+
+    bundle_telemetry_logger = tools.bundle_telemetry_logger
+    if bundle_telemetry_logger:
+        command.add("--bundle-telemetry-logger", bundle_telemetry_logger)
+
+    ctx.actions.run(
+        command,
+        local_only = force_local_bundling,
+        prefer_local = not force_local_bundling,
+        category = category,
+        env = env,
+        error_handler = apple_build_error_handler,
+        **run_incremental_args,
+    )
+
+    command_json = ctx.actions.declare_output("bundling_command.json", has_content_based_path = False)
+    command_json_cmd_args = ctx.actions.write_json(command_json, command, with_inputs = True, pretty = True)
+    subtargets["command"] = [DefaultInfo(default_output = command_json, other_outputs = [command_json_cmd_args])]
+
+    bundle_manifest_log_file_map = {
+        ctx.label: AppleBundleManifestLogFiles(
+            command_file = command_json,
+            spec_file = spec_file,
+            log_file = bundling_log_output,
+        ),
+    }
+
+    if hasattr(ctx.attrs, "deps"):
+        for dep in ctx.attrs.deps:
+            dep_manifest_info = dep.get(AppleBundleManifestInfo)
+            if dep_manifest_info:
+                bundle_manifest_log_file_map.update(dep_manifest_info.manifest.log_file_map)
+
+    bundle_manifest = AppleBundleManifest(log_file_map = bundle_manifest_log_file_map)
+    bundle_manifest_json_object = _convert_bundle_manifest_to_json_object(bundle_manifest)
+
+    bundle_manifest_json_file = ctx.actions.declare_output("bundle_manifest.json", has_content_based_path = False)
+    bundle_manifest_cmd_args = ctx.actions.write_json(bundle_manifest_json_file, bundle_manifest_json_object, with_inputs = True, pretty = True)
+    subtargets["manifest"] = [DefaultInfo(default_output = bundle_manifest_json_file, other_outputs = [bundle_manifest_cmd_args])]
+
+    providers = [AppleBundleManifestInfo(manifest = bundle_manifest)]
+
+    codesign_manifest_tree = _make_codesign_manifest_tree(ctx, codesign_manifest, codesign_manifest_parts)
+    codesign_manifest_tree_json = _get_codesign_manifest_tree_as_json(codesign_manifest_tree)
+    codesign_manifest_tree_json_file = ctx.actions.declare_output("codesign_manifest_tree.json", has_content_based_path = False)
+    codesign_manifest_tree_json_cmd_args = ctx.actions.write_json(
+        codesign_manifest_tree_json_file,
+        codesign_manifest_tree_json,
+        with_inputs = True,
+        pretty = True,
+    )
+
+    tools = ctx.attrs._apple_tools[AppleToolsInfo]
+    manifest_tree_postprocessor = tools.codesign_manifest_tree_postprocessor
+
+    postprocessed_codesign_manifest_tree = ctx.actions.declare_output("postprocessed_codesign_manifest_tree.json", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(
+            [
+                manifest_tree_postprocessor,
+                "--codesign-manifest-tree",
+                codesign_manifest_tree_json_cmd_args,
+                "--output",
+                postprocessed_codesign_manifest_tree.as_output(),
+            ],
+        ),
+        category = "codesign_manifest_tree_postprocess",
+    )
+
+    subtargets["codesign-manifest"] = [
+        DefaultInfo(
+            default_output = postprocessed_codesign_manifest_tree,
+        ),
+    ]
+
+    signing_context_output = ctx.actions.declare_output("provisioning-manifest.json", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(
+            [
+                tools.provisioning_manifest,
+                "--output",
+                signing_context_output.as_output(),
+            ]
+            + signing_context_path_arg,
+        ),
+        category = "apple_provisioning_manifest",
+        error_handler = apple_build_error_handler,
+    )
+
+    signing_context_tree = _make_signing_context_tree(ctx, signing_context_output, signing_context_parts)
+    signing_context_tree_json = _get_signing_context_tree_as_json(signing_context_tree)
+    signing_context_tree_json_file = ctx.actions.declare_output("provisioning-manifest-tree.json", has_content_based_path = False)
+    signing_context_tree_json_cmd_args = ctx.actions.write_json(
+        signing_context_tree_json_file,
+        signing_context_tree_json,
+        with_inputs = True,
+        pretty = True,
+    )
+
+    postprocessed_signing_context_tree = ctx.actions.declare_output("postprocessed-provisioning-manifest-tree.json", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(
+            [
+                tools.signing_context_tree_postprocessor,
+                "--signing-context-tree",
+                signing_context_tree_json_cmd_args,
+                "--output",
+                postprocessed_signing_context_tree.as_output(),
+            ],
+        ),
+        category = "apple_provisioning_manifest_tree_postprocess",
+    )
+
+    subtargets["provisioning-manifest"] = [DefaultInfo(default_output = postprocessed_signing_context_tree)]
+    subtargets["signing-info"] = [DefaultInfo(default_output = signing_info_output)]
+
+    return AppleBundleConstructionResult(
+        sub_targets = subtargets,
+        providers = providers,
+        codesign_manifest_tree = codesign_manifest_tree,
+        signing_context_tree = signing_context_tree,
+        signing_info = signing_info_output,
+    )
+
+def _make_codesign_manifest_tree(
+    ctx: AnalysisContext, codesign_manifest: Artifact, inner_parts: list[AppleBundleCodesignManifestTreePart]
+) -> AppleBundleCodesignManifestTree:
+    inner_manifest_trees = {}
+
+    for codesign_manifest_tree_part in inner_parts:
+        relative_path = get_apple_bundle_part_relative_destination_path(ctx, codesign_manifest_tree_part.bundle_part)
+        inner_manifest_trees[relative_path] = codesign_manifest_tree_part.codesign_manifest_tree
+
+    return AppleBundleCodesignManifestTree(
+        codesign_manifest = codesign_manifest,
+        inner_codesign_manifests = inner_manifest_trees,
+    )
+
+def _get_codesign_manifest_tree_as_json(codesign_manifest_tree: AppleBundleCodesignManifestTree) -> dict[str, typing.Any]:
+    json_obj = {
+        "codesign_manifest": codesign_manifest_tree.codesign_manifest,
+    }
+
+    inner_manifests = {}
+    for relative_path, inner_codesign_manifest_tree in codesign_manifest_tree.inner_codesign_manifests.items():
+        inner_manifests[relative_path] = _get_codesign_manifest_tree_as_json(inner_codesign_manifest_tree)
+
+    json_obj["inner_codesign_manifests"] = inner_manifests
+    return json_obj
+
+def _make_signing_context_tree(
+    ctx: AnalysisContext, signing_context: Artifact, inner_parts: list[AppleBundleSigningContextTreePart]
+) -> AppleBundleSigningContextTree:
+    inner_context_trees = {}
+
+    for signing_context_tree_part in inner_parts:
+        relative_path = get_apple_bundle_part_relative_destination_path(ctx, signing_context_tree_part.bundle_part)
+        inner_context_trees[relative_path] = signing_context_tree_part.signing_context_tree
+
+    return AppleBundleSigningContextTree(
+        signing_context = signing_context,
+        inner_signing_contexts = inner_context_trees,
+    )
+
+def _get_signing_context_tree_as_json(signing_context_tree: AppleBundleSigningContextTree) -> dict[str, typing.Any]:
+    json_obj = {
+        "signing_context": signing_context_tree.signing_context,
+    }
+
+    inner_contexts = {}
+    for relative_path, inner_signing_context_tree in signing_context_tree.inner_signing_contexts.items():
+        inner_contexts[relative_path] = _get_signing_context_tree_as_json(inner_signing_context_tree)
+
+    json_obj["inner_signing_contexts"] = inner_contexts
+    return json_obj
+
+def get_bundle_dir_name(ctx: AnalysisContext) -> str:
+    return paths.replace_extension(get_product_name(ctx), "." + get_extension_attr(ctx))
+
+def get_apple_bundle_part_relative_destination_path(ctx: AnalysisContext, part: AppleBundlePart) -> str:
+    bundle_relative_path = bundle_relative_path_for_destination(
+        part.destination, get_apple_sdk_name(ctx), ctx.attrs.extension, ctx.attrs.versioned_macos_bundle
+    )
+    destination_file_or_directory_name = part.new_name if part.new_name != None else part.source.basename
+    return paths.join(bundle_relative_path, destination_file_or_directory_name)
+
+# Returns JSON to be passed into bundle assembling tool. It should contain a dictionary which maps bundle relative destination paths to source paths."
+def _bundle_spec_json(ctx: AnalysisContext, parts: list[AppleBundlePart], codesign_type: CodeSignType) -> Artifact:
+    specs = []
+    include_entitlements = should_include_entitlements(ctx, codesign_type)
+
+    for part in parts:
+        part_spec = {
+            "dst": get_apple_bundle_part_relative_destination_path(ctx, part),
+            "src": part.source,
+        }
+        if part.codesign_on_copy:
+            part_spec["codesign_on_copy"] = True
+            if include_entitlements and part.codesign_entitlements:
+                part_spec["codesign_entitlements"] = part.codesign_entitlements
+            if part.codesign_flags_override:
+                part_spec["codesign_flags_override"] = part.codesign_flags_override
+            if part.extra_codesign_paths:
+                part_spec["extra_codesign_paths"] = part.extra_codesign_paths
+        specs.append(part_spec)
+
+    return ctx.actions.write_json("bundle_spec.json", specs, pretty = True, has_content_based_path = False)
+
+def _get_codesign_type_from_attribs(ctx: AnalysisContext) -> [CodeSignType, None]:
+    # Target-level attribute takes highest priority
+    if ctx.attrs.codesign_type:
+        return CodeSignType(ctx.attrs.codesign_type)
+
+    # Config-based global default
+    if ctx.attrs._codesign_type:
+        return CodeSignType(ctx.attrs._codesign_type)
+    return None
+
+def _detect_codesign_type(ctx: AnalysisContext, skip_adhoc_signing: bool) -> CodeSignType:
+    def compute_codesign_type():
+        if ctx.attrs.extension not in ["app", "appex", "xctest", "driver"]:
+            # Only code sign application bundles, extensions and test bundles
+            return CodeSignType("skip")
+
+        codesign_type_attrib = _get_codesign_type_from_attribs(ctx)
+        if codesign_type_attrib != None:
+            return codesign_type_attrib
+
+        sdk_name = get_apple_sdk_name(ctx)
+        is_ad_hoc_sufficient = get_apple_sdk_metadata_for_sdk_name(sdk_name).is_ad_hoc_code_sign_sufficient
+        return CodeSignType("adhoc" if is_ad_hoc_sufficient else "distribution")
+
+    codesign_type = compute_codesign_type()
+    if skip_adhoc_signing and codesign_type == CodeSignType("adhoc"):
+        codesign_type = CodeSignType("skip")
+
+    return codesign_type
+
+def _get_extra_codesign_args(ctx: AnalysisContext) -> list[str]:
+    codesign_args = ctx.attrs.codesign_flags if hasattr(ctx.attrs, "codesign_flags") else []
+    return ["--codesign-args={}".format(flag) for flag in codesign_args]
+
+def _should_embed_provisioning_profile(ctx: AnalysisContext, codesign_type: CodeSignType) -> bool:
+    if codesign_type == CodeSignType("distribution"):
+        return True
+
+    if codesign_type == CodeSignType("adhoc"):
+        # The config-based override value takes priority over target value
+        if ctx.attrs._embed_provisioning_profile_when_adhoc_code_signing != None:
+            return ctx.attrs._embed_provisioning_profile_when_adhoc_code_signing
+        return ctx.attrs.embed_provisioning_profile_when_adhoc_code_signing
+
+    return False
+
+def _convert_bundle_manifest_to_json_object(manifest: AppleBundleManifest) -> dict[Label, typing.Any]:
+    manifest_dict = {}
+    for target_label, logs in manifest.log_file_map.items():
+        manifest_dict[target_label] = {
+            "command": logs.command_file,
+            "log": logs.log_file,
+            "spec": logs.spec_file,
+        }
+    return manifest_dict
+
+def _get_fast_adhoc_signing_enabled(ctx: AnalysisContext) -> bool:
+    fast_adhoc_signing_enabled = ctx.attrs.fast_adhoc_signing_enabled
+    if fast_adhoc_signing_enabled != None:
+        return fast_adhoc_signing_enabled
+    return ctx.attrs._fast_adhoc_signing_enabled_default
diff --git a/buck2/prelude/apple/apple_bundle_resources.bzl b/buck2/prelude/apple/apple_bundle_resources.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_bundle_resources.bzl
@@ -0,0 +1,635 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifacts.bzl", "single_artifact")
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load("@prelude//cxx:headers.bzl", "CHeader")
+load(
+    "@prelude//linking:link_info.bzl",
+    "CxxSanitizerRuntimeInfo",
+)
+load("@prelude//utils:utils.bzl", "flatten_dict")
+load(
+    ":apple_asset_catalog.bzl",
+    "compile_apple_asset_catalog",
+)
+load(":apple_bundle_destination.bzl", "AppleBundleDestination")
+load(":apple_bundle_part.bzl", "AppleBundleCodesignManifestTreePart", "AppleBundlePart", "AppleBundleSigningContextTreePart")
+load(
+    ":apple_bundle_types.bzl",
+    "AppleBundleInfo",
+    "AppleBundleTypeAppClip",
+    "AppleBundleTypeDefault",
+    "AppleBundleTypeExtensionKitExtension",
+    "AppleBundleTypeWatchApp",
+)
+load(
+    ":apple_bundle_utility.bzl",
+    "get_bundle_resource_processing_options",
+    "get_default_binary_dep",
+    "get_extension_attr",
+    "get_flattened_binary_deps",
+    "get_is_watch_bundle",
+    "get_product_name",
+)
+load(":apple_core_data.bzl", "compile_apple_core_data")
+load(":apple_info_plist.bzl", "process_info_plist", "process_plist")
+load(":apple_library.bzl", "AppleLibraryForDistributionInfo")
+load(":apple_library_types.bzl", "AppleLibraryInfo")
+load(
+    ":apple_resource_types.bzl",
+    "AppleResourceDestination",
+    "AppleResourceSelectionOutput",
+    "AppleResourceSpec",  # @unused Used as a type
+)
+load(":apple_resource_utility.bzl", "apple_bundle_destination_from_resource_destination")
+load(":modulemap.bzl", "create_modulemap")
+load(
+    ":resource_groups.bzl",
+    "create_resource_graph",
+    "get_filtered_resources",
+    "get_resource_graph_node_map_func",
+    "get_resource_group_info",
+)
+load(":scene_kit_assets.bzl", "compile_scene_kit_assets")
+
+AppleBundleResourcePartListOutput = record(
+    # Resource parts to be copied into an Apple bundle, *excluding* binaries
+    resource_parts = field(list[AppleBundlePart]),
+    # Part that holds the info.plist
+    info_plist_part = field(AppleBundlePart),
+    # Parts which have an associated codesign manifest, it would contain
+    # a _subset_ of the `resource_parts` parts.
+    codesign_manifest_parts = field(list[AppleBundleCodesignManifestTreePart]),
+    # Parts which have an associated signing context, it would contain
+    # a _subset_ of the `resource_parts` parts.
+    signing_context_parts = field(list[AppleBundleSigningContextTreePart]),
+)
+
+def get_apple_bundle_resource_part_list(ctx: AnalysisContext) -> AppleBundleResourcePartListOutput:
+    parts = []
+
+    parts.extend(_create_pkg_info_if_needed(ctx))
+    parts.extend(_copy_privacy_manifest_if_needed(ctx))
+
+    selection = _select_resources(ctx)
+
+    # If we've pulled in native/C++ resources from deps, inline them into the
+    # bundle under the `CxxResources` namespace.
+    cxx_resources = flatten_dict([s.resources for s in selection.cxx_resource_specs])
+    if cxx_resources:
+        cxx_res_dir = ctx.actions.copied_dir(
+            "CxxResources",
+            {name: resource.default_output for name, resource in cxx_resources.items()},
+            has_content_based_path = False,
+        )
+        selection.resource_specs.append(
+            AppleResourceSpec(
+                dirs = [cxx_res_dir],
+                destination = AppleResourceDestination("resources"),
+            ),
+        )
+
+    cxx_sanitizer_runtime_info = get_default_binary_dep(ctx.attrs.binary).get(CxxSanitizerRuntimeInfo) if ctx.attrs.binary else None
+    if cxx_sanitizer_runtime_info and get_extension_attr(ctx) != "appex":
+        runtime_resource_spec = AppleResourceSpec(
+            files = cxx_sanitizer_runtime_info.runtime_files,
+            destination = AppleResourceDestination("frameworks"),
+            # Sanitizer dylibs require signing, for hardened runtime on macOS and iOS device builds
+            codesign_files_on_copy = True,
+        )
+        selection.resource_specs.append(runtime_resource_spec)
+
+    asset_catalog_result = compile_apple_asset_catalog(ctx, selection.asset_catalog_specs)
+    if asset_catalog_result != None:
+        asset_catalog_part = AppleBundlePart(
+            source = asset_catalog_result.compiled_catalog,
+            destination = AppleBundleDestination("resources"),
+            # We only interested in directory contents
+            new_name = "",
+        )
+        parts.append(asset_catalog_part)
+
+    extra_plist = asset_catalog_result.catalog_plist if asset_catalog_result != None else None
+    info_plist_part = process_info_plist(ctx = ctx, override_input = extra_plist)
+
+    core_data_result = compile_apple_core_data(ctx, selection.core_data_specs, get_product_name(ctx))
+    if core_data_result != None:
+        core_data_part = AppleBundlePart(
+            source = core_data_result,
+            destination = AppleBundleDestination("resources"),
+            # We only interested in directory contents
+            new_name = "",
+        )
+        parts.append(core_data_part)
+
+    scene_kit_assets_result = compile_scene_kit_assets(ctx, selection.scene_kit_assets_spec)
+    if scene_kit_assets_result != None:
+        scene_kit_assets_part = AppleBundlePart(
+            source = scene_kit_assets_result,
+            destination = AppleBundleDestination("resources"),
+            # We only interested in directory contents
+            new_name = "",
+        )
+        parts.append(scene_kit_assets_part)
+
+    parts.extend(_copy_resources(ctx, selection.resource_specs))
+    first_level_parts, first_level_codesign_manifest_parts, first_level_signing_context_parts = _copy_first_level_bundles(ctx)
+    parts.extend(first_level_parts)
+    parts.extend(_copy_public_headers(ctx))
+    parts.extend(_copy_module_map(ctx))
+    parts.extend(_copy_swift_library_evolution_support(ctx))
+
+    return AppleBundleResourcePartListOutput(
+        resource_parts = parts,
+        info_plist_part = info_plist_part,
+        codesign_manifest_parts = first_level_codesign_manifest_parts,
+        signing_context_parts = first_level_signing_context_parts,
+    )
+
+# Same logic as in v1, see `buck_client/src/com/facebook/buck/apple/ApplePkgInfo.java`
+def _create_pkg_info_if_needed(ctx: AnalysisContext) -> list[AppleBundlePart]:
+    extension = get_extension_attr(ctx)
+    if extension == "xpc" or extension == "qlgenerator":
+        return []
+    artifact = ctx.actions.write("PkgInfo", "APPLWRUN\n", has_content_based_path = False)
+    return [AppleBundlePart(source = artifact, destination = AppleBundleDestination("metadata"))]
+
+def _copy_privacy_manifest_if_needed(ctx: AnalysisContext) -> list[AppleBundlePart]:
+    privacy_manifest = ctx.attrs.privacy_manifest
+    if privacy_manifest == None:
+        return []
+
+    # According to apple docs, privacy manifest has to be named as `PrivacyInfo.xcprivacy`
+    if privacy_manifest.short_path.split("/", 1)[-1] == "PrivacyInfo.xcprivacy":
+        artifact = privacy_manifest
+    else:
+        output = ctx.actions.declare_output("PrivacyInfo.xcprivacy", has_content_based_path = False)
+        artifact = ctx.actions.copy_file(output.as_output(), privacy_manifest)
+    return [AppleBundlePart(source = artifact, destination = AppleBundleDestination("resources"))]
+
+def _select_resources(ctx: AnalysisContext) -> AppleResourceSelectionOutput:
+    resource_group_info = get_resource_group_info(ctx)
+    if resource_group_info:
+        resource_groups_deps = resource_group_info.resource_group_to_implicit_deps_mapping.get(ctx.attrs.resource_group, []) if ctx.attrs.resource_group else []
+        resource_group_mappings = resource_group_info.mappings
+    else:
+        resource_groups_deps = []
+        resource_group_mappings = {}
+
+    resource_graph = create_resource_graph(
+        ctx = ctx,
+        labels = [],
+        bundle_binary = get_default_binary_dep(ctx.attrs.binary),
+        deps = ctx.attrs.deps + resource_groups_deps,
+        exported_deps = [],
+    )
+    resource_graph_node_map_func = get_resource_graph_node_map_func(resource_graph)
+    return get_filtered_resources(ctx.label, resource_graph_node_map_func, ctx.attrs.resource_group, resource_group_mappings)
+
+def _copy_swift_library_evolution_support(ctx: AnalysisContext) -> list[AppleBundlePart]:
+    extension = get_extension_attr(ctx)
+    if not extension == "framework":
+        return []
+
+    binary_deps = getattr(ctx.attrs, "binary")
+    if binary_deps == None:
+        return []
+
+    swiftmodule_files = {}
+
+    module_name = None
+    for binary in get_flattened_binary_deps(binary_deps):
+        apple_library_for_distribution_info = binary.get(AppleLibraryForDistributionInfo)
+        if apple_library_for_distribution_info == None:
+            continue
+        module_name = apple_library_for_distribution_info.module_name
+        if apple_library_for_distribution_info.swiftinterface != None:
+            swiftmodule_files.update({
+                apple_library_for_distribution_info.target_triple + ".swiftinterface": apple_library_for_distribution_info.swiftinterface,
+            })
+            if not getattr(ctx.attrs, "skip_private_swiftinterface", False):
+                swiftmodule_files.update({
+                    apple_library_for_distribution_info.target_triple
+                    + ".private.swiftinterface": apple_library_for_distribution_info.private_swiftinterface,
+                })
+        if apple_library_for_distribution_info.swiftdoc != None:
+            swiftmodule_files.update({
+                apple_library_for_distribution_info.target_triple + ".swiftdoc": apple_library_for_distribution_info.swiftdoc,
+            })
+
+    if len(swiftmodule_files) == 0 or module_name == None:
+        return []
+
+    framework_module_dir = ctx.actions.declare_output(module_name + "framework.swiftmodule", dir = True, has_content_based_path = False)
+    ctx.actions.copied_dir(framework_module_dir.as_output(), swiftmodule_files)
+    return [AppleBundlePart(source = framework_module_dir, destination = AppleBundleDestination("modules"), new_name = module_name + ".swiftmodule")]
+
+def _public_headers(ctx: AnalysisContext) -> list[Artifact]:
+    if not ctx.attrs.copy_public_framework_headers:
+        return []
+    binary_deps = getattr(ctx.attrs, "binary")
+    if binary_deps == None:
+        return []
+
+    binary = get_default_binary_dep(binary_deps)
+    apple_library_info = binary.get(AppleLibraryInfo)
+    if apple_library_info == None:
+        return []
+    tset = apple_library_info.public_framework_headers
+
+    headers = []
+    if tset._tset:
+        for public_framework_headers in tset._tset.traverse():
+            for public_framework_header in public_framework_headers:
+                for artifact in public_framework_header.artifacts:
+                    headers.append(artifact)
+
+    return headers
+
+def _copy_public_headers(ctx: AnalysisContext) -> list[AppleBundlePart]:
+    if not ctx.attrs.copy_public_framework_headers:
+        return []
+    binary_deps = getattr(ctx.attrs, "binary")
+    if binary_deps == None:
+        return []
+
+    binary = get_default_binary_dep(binary_deps)
+    apple_library_info = binary.get(AppleLibraryInfo)
+    if apple_library_info == None:
+        return []
+    tset = apple_library_info.public_framework_headers
+
+    bundle_parts = []
+    if tset._tset:
+        for public_framework_headers in tset._tset.traverse():
+            for public_framework_header in public_framework_headers:
+                for artifact in public_framework_header.artifacts:
+                    bundle_parts.append(AppleBundlePart(source = artifact, destination = AppleBundleDestination("headers")))
+
+    if apple_library_info.swift_header:
+        bundle_parts.append(AppleBundlePart(source = apple_library_info.swift_header, destination = AppleBundleDestination("headers")))
+
+    return bundle_parts
+
+def _create_framework_module_map(ctx: AnalysisContext) -> Artifact:
+    binary = get_default_binary_dep(ctx.attrs.binary)
+    apple_library_for_distribution_info = binary.get(AppleLibraryForDistributionInfo)
+    if apple_library_for_distribution_info == None:
+        fail("Tried to generate an automatic modulemap for an unsupported binary dep. Please make sure it is a modular apple_library")
+    headers = _public_headers(ctx)
+    cheaders = []
+    for header in headers:
+        cheaders.append(
+            CHeader(
+                artifact = header,
+                name = header.basename,
+                namespace = "",
+                named = False,
+            )
+        )
+
+    module_name = apple_library_for_distribution_info.module_name
+    preprocessor_info = create_modulemap(
+        ctx,
+        name = "module",
+        module_name = module_name,
+        headers = cheaders,
+        is_framework = True,
+    )
+    return preprocessor_info.modulemap_artifact
+
+def _copy_module_map(ctx: AnalysisContext) -> list[AppleBundlePart]:
+    extension = get_extension_attr(ctx)
+    if not extension == "framework":
+        return []
+    module_map = ctx.attrs.module_map
+    if module_map == None:
+        return []
+    if module_map == "auto":
+        module_map = _create_framework_module_map(ctx)
+
+    return [AppleBundlePart(source = module_map, destination = AppleBundleDestination("modules"))]
+
+def _copy_resources(ctx: AnalysisContext, specs: list[AppleResourceSpec]) -> list[AppleBundlePart]:
+    result = []
+
+    for spec in specs:
+        bundle_destination = apple_bundle_destination_from_resource_destination(spec.destination)
+        result += [
+            _process_apple_resource_file_if_needed(
+                ctx = ctx,
+                file = single_artifact(x).default_output,
+                destination = bundle_destination,
+                destination_relative_path = None,
+                codesign_on_copy = spec.codesign_files_on_copy,
+                codesign_entitlements = spec.codesign_entitlements,
+                codesign_flags_override = spec.codesign_flags_override,
+            )
+            for x in spec.files
+        ]
+        result += _bundle_parts_for_dirs(spec.dirs, bundle_destination, False)
+        result += _bundle_parts_for_dirs(spec.content_dirs, bundle_destination, True)
+        result += _bundle_parts_for_variant_files(ctx, spec)
+
+    return result
+
+def _copy_first_level_bundles(
+    ctx: AnalysisContext,
+) -> (list[AppleBundlePart], list[AppleBundleCodesignManifestTreePart], list[AppleBundleSigningContextTreePart]):
+    first_level_bundle_infos = filter(None, [dep.get(AppleBundleInfo) for dep in ctx.attrs.deps])
+
+    bundle_parts = []
+    codesign_manifest_parts = []
+    signing_context_parts = []
+    for bundle_info in first_level_bundle_infos:
+        first_level_part = _copied_bundle_spec(bundle_info)
+        if first_level_part != None:
+            bundle_parts.append(first_level_part)
+            if bundle_info.codesign_manifest_tree:
+                codesign_manifest_parts.append(
+                    AppleBundleCodesignManifestTreePart(
+                        bundle_part = first_level_part,
+                        codesign_manifest_tree = bundle_info.codesign_manifest_tree,
+                    )
+                )
+            if bundle_info.signing_context_tree:
+                signing_context_parts.append(
+                    AppleBundleSigningContextTreePart(
+                        bundle_part = first_level_part,
+                        signing_context_tree = bundle_info.signing_context_tree,
+                    )
+                )
+
+    return bundle_parts, codesign_manifest_parts, signing_context_parts
+
+def _copied_bundle_spec(bundle_info: AppleBundleInfo) -> [None, AppleBundlePart]:
+    bundle = bundle_info.bundle
+    bundle_extension = paths.split_extension(bundle.short_path)[1]
+    if bundle_extension == ".framework":
+        destination = AppleBundleDestination("frameworks")
+        codesign_on_copy = True
+    elif bundle_extension == ".app":
+        app_destination_type = "plugins"
+        if bundle_info.bundle_type == AppleBundleTypeWatchApp:
+            app_destination_type = "watchapp"
+        elif bundle_info.bundle_type == AppleBundleTypeAppClip:
+            app_destination_type = "appclips"
+        elif bundle_info.bundle_type != AppleBundleTypeDefault:
+            fail("Unhandled bundle type `{}`".format(bundle_info.bundle_type))
+        destination = AppleBundleDestination(app_destination_type)
+        codesign_on_copy = False
+    elif bundle_extension == ".appex":
+        # We have two types of extensions: App Extensions and ExtensionKit Extensions
+        #
+        # +----------------------+-------------------------------+-------------------------------+
+        # |                      |        App Extension          |   ExtensionKit Extension      |
+        # +----------------------+-------------------------------+-------------------------------+
+        # | xcode project type   | com.apple.product-type.app-   | com.apple.product-type.       |
+        # |                      | extension                     | extensionkit-extension        |
+        # +----------------------+-------------------------------+-------------------------------+
+        # | Info.plist           | NSExtensions                  | EXAppExtensionAttributes      |
+        # +----------------------+-------------------------------+-------------------------------+
+        # | bundle folder        | *.app/PlugIns                 | *.app/Extensions              |
+        # +----------------------+-------------------------------+-------------------------------+
+        #
+        if bundle_info.bundle_type == AppleBundleTypeExtensionKitExtension:
+            destination = AppleBundleDestination("extensionkit_extensions")
+        else:
+            destination = AppleBundleDestination("plugins")
+        codesign_on_copy = False
+    elif bundle_extension == ".qlgenerator":
+        destination = AppleBundleDestination("quicklook")
+        codesign_on_copy = True
+    elif bundle_extension == ".xpc":
+        destination = AppleBundleDestination("xpcservices")
+        codesign_on_copy = True
+    elif bundle_extension == ".bundle":
+        destination = AppleBundleDestination("plugins")
+        codesign_on_copy = True
+    else:
+        fail("Extension `{}` is not yet supported.".format(bundle_extension))
+    return AppleBundlePart(
+        source = bundle,
+        destination = destination,
+        codesign_on_copy = codesign_on_copy,
+        extra_codesign_paths = bundle_info.extra_codesign_paths,
+    )
+
+def _bundle_parts_for_dirs(generated_dirs: list[Artifact], destination: AppleBundleDestination, copy_contents_only: bool) -> list[AppleBundlePart]:
+    return [
+        AppleBundlePart(
+            source = generated_dir,
+            destination = destination,
+            new_name = "" if copy_contents_only else None,
+        )
+        for generated_dir in generated_dirs
+    ]
+
+def _bundle_parts_for_variant_files(ctx: AnalysisContext, spec: AppleResourceSpec) -> list[AppleBundlePart]:
+    result = []
+
+    # By definition, all variant files go into the resources destination
+    bundle_destination = AppleBundleDestination("resources")
+    for variant_file in spec.variant_files:
+        variant_dest_subpath = _get_dest_subpath_for_variant_file(variant_file)
+        bundle_part = _process_apple_resource_file_if_needed(
+            ctx = ctx,
+            file = variant_file,
+            destination = bundle_destination,
+            destination_relative_path = variant_dest_subpath,
+        )
+        result.append(bundle_part)
+
+    for locale, variant_files in spec.named_variant_files.items():
+        if not locale.endswith(".lproj"):
+            fail("Keys for named variant files have to end with '.lproj' suffix, got {}".format(locale))
+        result += [
+            _process_apple_resource_file_if_needed(
+                ctx = ctx,
+                file = variant_file,
+                destination = bundle_destination,
+                destination_relative_path = paths.join(locale, variant_file.basename),
+            )
+            for variant_file in variant_files
+        ]
+
+    return result
+
+def _run_ibtool(
+    ctx: AnalysisContext,
+    raw_file: Artifact,
+    output: OutputArtifact,
+    action_flags: list[str],
+    target_device: [None, str],
+    command_for_identifier: str,
+    output_is_dir: bool,
+) -> None:
+    # TODO(T110378103): detect and add minimum deployment target automatically
+    # TODO(T110378113): add support for ibtool modules (turned on by `ibtool_module_flag` field of `apple_bundle` rule)
+
+    # Equivalent of `AppleProcessResources::BASE_IBTOOL_FLAGS` from v1
+    base_flags = ["--output-format", "human-readable-text", "--notices", "--warnings", "--errors"]
+    ibtool = ctx.attrs._apple_toolchain[AppleToolchainInfo].ibtool
+    ibtool_flags = getattr(ctx.attrs, "ibtool_flags", None) or []
+    ibtool_command = [ibtool] + base_flags + ibtool_flags
+    if target_device != None:
+        ibtool_command.extend(["--target-device", target_device])
+    ibtool_command.extend(action_flags)
+    if output_is_dir:
+        ibtool_command.append('"$TMPDIR"')
+        copy_back = cmd_args(output, format = 'mkdir -p {} && cp -r "$TMPDIR"/ {}')
+    else:
+        output_for_tool_invocation = '"$TMPDIR"/"' + output.basename + '"'
+        ibtool_command.append(output_for_tool_invocation)
+        copy_back = cmd_args(output, format = "cp " + output_for_tool_invocation + " {}")
+    ibtool_command.append(cmd_args(raw_file, format = '"$EXEC_ROOT"/{}'))
+
+    # Sandboxing and fs isolation on RE machines results in Xcode tools failing
+    # when those are working in freshly created directories in buck-out.
+    # See https://fb.workplace.com/groups/1042353022615812/permalink/1872164996301273/
+    # As a workaround create a directory in tmp, use it for Xcode tools, then
+    # copy the result to buck-out.
+    script_lines = [
+        cmd_args("set -euo pipefail"),
+        cmd_args('EXEC_ROOT="$PWD"'),
+        cmd_args('TMPDIR="$(mktemp -d)"'),
+        cmd_args(ibtool_command, delimiter = " "),
+        copy_back,
+    ]
+
+    wrapper_script, _ = ctx.actions.write(
+        "ibtool_wrapper_" + _wrapper_suffix(command_for_identifier, raw_file) + ".sh",
+        script_lines,
+        allow_args = True,
+        has_content_based_path = False,
+    )
+    command = cmd_args(["/bin/sh", wrapper_script], hidden = [ibtool_command, output])
+    action_identifier = _ibtool_identifier(command_for_identifier, raw_file)
+    processing_options = get_bundle_resource_processing_options(ctx)
+    ctx.actions.run(
+        command,
+        prefer_local = processing_options.prefer_local,
+        prefer_remote = processing_options.prefer_remote,
+        allow_cache_upload = processing_options.allow_cache_upload,
+        category = "apple_ibtool",
+        identifier = action_identifier,
+    )
+
+def _identifier_parts(raw_file: Artifact) -> list[str]:
+    identifier_parts = []
+    variant_dirname = _get_variant_dirname(raw_file)
+    if variant_dirname:
+        # variant_name is like "zh_TW.lproj", and we only want "zh_TW"
+        variant_name = paths.replace_extension(variant_dirname, "")
+        identifier_parts.append(variant_name)
+    identifier_parts += [raw_file.basename]
+    return identifier_parts
+
+def _ibtool_identifier(action: str, raw_file: Artifact) -> str:
+    "*.xib files can live in .lproj folders and have the same name, so we need to split the id"
+    identifier_parts = _identifier_parts(raw_file)
+    return "ibtool_" + action + " " + "/".join(identifier_parts)
+
+def _wrapper_suffix(action: str, raw_file: Artifact) -> str:
+    return "_".join([action] + _identifier_parts(raw_file))
+
+def _compile_ui_resource(
+    ctx: AnalysisContext, raw_file: Artifact, output: OutputArtifact, target_device: [None, str] = None, output_is_dir: bool = False
+) -> None:
+    _run_ibtool(
+        ctx = ctx,
+        raw_file = raw_file,
+        output = output,
+        action_flags = ["--compile"],
+        target_device = target_device,
+        command_for_identifier = "compile",
+        output_is_dir = output_is_dir,
+    )
+
+def _link_ui_resource(ctx: AnalysisContext, raw_file: Artifact, output: OutputArtifact, target_device: [None, str] = None, output_is_dir: bool = False) -> None:
+    _run_ibtool(
+        ctx = ctx,
+        raw_file = raw_file,
+        output = output,
+        action_flags = ["--link"],
+        target_device = target_device,
+        command_for_identifier = "link",
+        output_is_dir = output_is_dir,
+    )
+
+def _process_apple_resource_file_if_needed(
+    ctx: AnalysisContext,
+    file: Artifact,
+    destination: AppleBundleDestination,
+    destination_relative_path: [str, None],
+    codesign_on_copy: bool = False,
+    codesign_entitlements: Artifact | None = None,
+    codesign_flags_override: list[str] | None = None,
+) -> AppleBundlePart:
+    output_dir = "_ProcessedResources"
+    basename = file.basename
+    output_is_contents_dir = False
+    if basename.endswith(".plist") or basename.endswith(".stringsdict"):
+        processed = ctx.actions.declare_output(paths.join(output_dir, file.short_path), has_content_based_path = False)
+        process_plist(
+            ctx = ctx,
+            input = file,
+            output = processed.as_output(),
+            action_id = destination_relative_path,
+        )
+    elif basename.endswith(".storyboard"):
+        if destination_relative_path:
+            destination_relative_path = paths.replace_extension(destination_relative_path, ".storyboardc")
+        compiled = ctx.actions.declare_output(
+            paths.join(output_dir, paths.replace_extension(file.short_path, ".storyboardc")), dir = True, has_content_based_path = False
+        )
+        if get_is_watch_bundle(ctx):
+            output_is_contents_dir = True
+            _compile_ui_resource(ctx = ctx, raw_file = file, output = compiled.as_output(), target_device = "watch", output_is_dir = True)
+            processed = ctx.actions.declare_output(
+                paths.join(output_dir, paths.replace_extension(file.short_path, "_linked_storyboard")), dir = True, has_content_based_path = False
+            )
+            _link_ui_resource(ctx = ctx, raw_file = compiled, output = processed.as_output(), target_device = "watch", output_is_dir = True)
+        else:
+            processed = compiled
+            _compile_ui_resource(ctx, file, processed.as_output(), output_is_dir = True)
+    elif basename.endswith(".xib"):
+        if destination_relative_path:
+            destination_relative_path = paths.replace_extension(destination_relative_path, ".nib")
+        processed = ctx.actions.declare_output(paths.join(output_dir, paths.replace_extension(file.short_path, ".nib")), has_content_based_path = False)
+        _compile_ui_resource(ctx, file, processed.as_output())
+    else:
+        processed = file
+
+    # When name is empty string only content of the directory will be copied, as opposed to the directory itself.
+    # When name is `None`, directory or file will be copied as it is, without renaming.
+    new_name = destination_relative_path if destination_relative_path else ("" if output_is_contents_dir else None)
+    return AppleBundlePart(
+        source = processed,
+        destination = destination,
+        new_name = new_name,
+        codesign_on_copy = codesign_on_copy,
+        codesign_entitlements = codesign_entitlements,
+        codesign_flags_override = codesign_flags_override,
+    )
+
+# Returns a path relative to the _parent_ of the lproj dir.
+# For example, given a variant file with a short path of`XX/YY.lproj/ZZ`
+# it would return `YY.lproj/ZZ`.
+def _get_dest_subpath_for_variant_file(variant_file: Artifact) -> str:
+    dir_name = _get_variant_dirname(variant_file)
+    if not dir_name:
+        fail("Variant files have to be in a directory with name ending in '.lproj' but `{}` was not.".format(variant_file.short_path))
+    file_name = variant_file.basename
+    return paths.join(dir_name, file_name)
+
+def _get_variant_dirname(variant_file: Artifact) -> str | None:
+    dir_name = paths.basename(paths.dirname(variant_file.short_path))
+    return dir_name if dir_name.endswith("lproj") else None
diff --git a/buck2/prelude/apple/apple_bundle_types.bzl b/buck2/prelude/apple/apple_bundle_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_bundle_types.bzl
@@ -0,0 +1,144 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":debug.bzl", "AppleDebuggableInfo")
+
+AppleBundleType = enum(
+    "default",
+    # Bundle was built for watchOS Apple platform
+    "watchapp",
+    # Bundle represents an App Clip to be embedded
+    "appclip",
+    # Bundle represents an ExtensionKit extension to be embedded
+    "extensionkit_extension",
+)
+
+ApplePackageExtension = enum(
+    "ipa",
+    "pkg",
+    "dmg",
+    "zip",
+)
+
+AppleBundleManifestLogFiles = record(
+    command_file = field(Artifact),
+    spec_file = field(Artifact),
+    log_file = field([Artifact, None], None),
+)
+
+AppleBundleManifest = record(
+    log_file_map = dict[Label, AppleBundleManifestLogFiles],
+)
+
+AppleBundleCodesignManifestTree = record(
+    # Codesign manifest for the bundle itself
+    codesign_manifest = field(Artifact),
+    # Codesign manifest for inner bundles.
+    # Maps from relative bundle destination -> AppleBundleCodesignManifestTree
+    inner_codesign_manifests = field(dict[str, typing.Any]),
+)
+
+AppleBundleSigningContextTree = record(
+    # Signing context for the bundle itself
+    signing_context = field(Artifact),
+    # Signing contexts for inner bundles.
+    # Maps from relative bundle destination -> AppleBundleSigningContextTree
+    inner_signing_contexts = field(dict[str, typing.Any]),
+)
+
+AppleBundleManifestInfo = provider(
+    fields = {
+        "manifest": provider_field(AppleBundleManifest),
+    },
+)
+
+# Provider flagging that result of the rule contains Apple bundle.
+# It might be copied into main bundle to appropriate place if rule
+# with this provider is a dependency of `apple_bundle`.
+AppleBundleInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        # Result bundle
+        "bundle": provider_field(Artifact),
+        "bundle_type": provider_field(AppleBundleType),
+        # The name of the executable within the bundle.
+        "binary_name": provider_field([str, None], default = None),
+        # If the bundle contains a Watch bundle, we have to update the packaging.
+        # Similar to `is_watchos`, this might be omitted for certain types of bundles which don't depend on it.
+        "contains_watchapp": provider_field([bool, None]),
+        # By default, non-framework, non-appex binaries copy Swift libraries into the final
+        # binary. This is the opt-out for that.
+        "skip_copying_swift_stdlib": provider_field([bool, None]),
+        # List of extra paths (relative to bundle root) to be codesigned.
+        "extra_codesign_paths": provider_field([list[str], None], default = None),
+        "codesign_manifest_tree": provider_field(AppleBundleCodesignManifestTree | None, default = None),
+        "signing_context_tree": provider_field(AppleBundleSigningContextTree | None, default = None),
+        "signing_info": provider_field(Artifact | None, default = None),
+    },
+)
+
+# Provider which helps to propagate minimum deployment version up the target graph.
+AppleMinDeploymentVersionInfo = provider(
+    fields = {
+        "version": provider_field([str, None]),
+    }
+)
+
+AppleBundleResourceInfo = provider(
+    fields = {
+        "resource_output": provider_field(typing.Any, default = None),  # AppleBundleResourcePartListOutput
+    }
+)
+
+AppleBundleLinkerMapInfo = provider(
+    fields = {
+        "linker_maps": provider_field(list[Artifact]),
+    }
+)
+
+# Providers used to merge extra linker outputs as a top level output
+# of an application bundle.
+AppleBinaryExtraOutputsInfo = provider(
+    fields = {
+        "default_output": provider_field(Artifact),
+        "extra_outputs": provider_field(dict[str, list[Artifact]]),
+        "name": provider_field(str),
+    }
+)
+
+AppleBundleExtraOutputsInfo = provider(
+    fields = {
+        "extra_outputs": provider_field(list[AppleBinaryExtraOutputsInfo]),
+    }
+)
+
+AppleBundleBinaryOutput = record(
+    binary = field(Artifact),
+    # If `unstripped_binary` is `None`, then `binary` is unstripped.
+    # Otherwise, `unstripped_binary` is distinct from `binary` and is unstripped.
+    unstripped_binary = field([Artifact, None]),
+    debuggable_info = field([AppleDebuggableInfo, None], None),
+)
+
+AppleBundleTypeDefault = AppleBundleType("default")
+AppleBundleTypeWatchApp = AppleBundleType("watchapp")
+AppleBundleTypeAppClip = AppleBundleType("appclip")
+AppleBundleTypeExtensionKitExtension = AppleBundleType("extensionkit_extension")
+
+# Represents the user-visible type which is distinct from the internal one (`AppleBundleType`)
+AppleBundleTypeAttributeType = enum(
+    "appclip",
+    "extensionkit_extension",
+    "watchapp",
+)
+
+AppleInfoPlistInfo = provider(
+    fields = {
+        "info_plist": provider_field(Artifact),
+    }
+)
diff --git a/buck2/prelude/apple/apple_bundle_utility.bzl b/buck2/prelude/apple/apple_bundle_utility.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_bundle_utility.bzl
@@ -0,0 +1,115 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:utils.bzl", "flatten", "value_or")
+load(":apple_bundle_types.bzl", "AppleBundleLinkerMapInfo", "AppleMinDeploymentVersionInfo")
+load(":apple_library.bzl", "AppleLibraryForDistributionInfo")
+load(":apple_resource_types.bzl", "AppleResourceProcessingOptions")
+load(":apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")
+load(":apple_toolchain_types.bzl", "AppleToolchainInfo")
+load(":resource_groups.bzl", "ResourceGraphInfo")
+
+# `ctx` in all functions below is expected to be of `apple_bundle` or `apple_test` rule
+
+def get_is_watch_bundle(ctx: AnalysisContext) -> bool:
+    return ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_name.startswith("watch")
+
+def _get_bundle_target_name(ctx: AnalysisContext):
+    if hasattr(ctx.attrs, "_bundle_target_name"):
+        # `apple_resource_bundle` rules are proxies for the real rules,
+        # so make sure we return the real target name rather the proxy one
+        return ctx.attrs._bundle_target_name
+    return ctx.attrs.name
+
+def get_product_name(ctx: AnalysisContext) -> str:
+    if hasattr(ctx.attrs, "product_name") and ctx.attrs.product_name != None:
+        return ctx.attrs.product_name
+    if getattr(ctx.attrs, "product_name_from_module_name", False):
+        apple_library_info = get_default_binary_dep(ctx.attrs.binary).get(AppleLibraryForDistributionInfo)
+        if apple_library_info != None:
+            return apple_library_info.module_name
+    return _get_bundle_target_name(ctx)
+
+def get_extension_attr(ctx: AnalysisContext) -> typing.Any:
+    return ctx.attrs.extension
+
+def get_default_binary_dep(binary_deps: [dict[str, Dependency], Dependency, None]) -> [Dependency, None]:
+    if not type(binary_deps) == "dict":
+        return binary_deps
+
+    if len(binary_deps.items()) == 1:
+        return binary_deps.values()[0]
+
+    return binary_deps["arm64"] if "arm64" in binary_deps else binary_deps["x86_64"]
+
+def get_flattened_binary_deps(binary_deps: dict[str, Dependency]) -> list[Dependency]:
+    return binary_deps.values()
+
+# Derives the effective deployment target for the bundle. It's
+# usually the deployment target of the binary if present,
+# otherwise it falls back to other values (see implementation).
+def get_bundle_min_target_version(ctx: AnalysisContext, binary_or_binaries: [dict[str, Dependency], Dependency, None]) -> str:
+    binary = get_default_binary_dep(binary_or_binaries)
+
+    binary_min_version = None
+
+    # apple_xcuitest bundles do not have a binary
+    if binary != None:
+        min_version_info = binary[AppleMinDeploymentVersionInfo] if AppleMinDeploymentVersionInfo in binary else None
+        if min_version_info != None:
+            binary_min_version = min_version_info.version
+
+    fallback_min_version = get_min_deployment_version_for_node(ctx)
+    min_version = binary_min_version or fallback_min_version
+
+    if min_version != None:
+        return min_version
+
+    # TODO(T110378109): support default value from SDK `Info.plist`
+    fail("Could not determine min target sdk version for bundle: {}".format(ctx.label))
+
+def get_bundle_resource_processing_options(ctx: AnalysisContext) -> AppleResourceProcessingOptions:
+    compile_resources_locally = value_or(
+        ctx.attrs._compile_resources_locally_override, ctx.attrs._apple_toolchain[AppleToolchainInfo].compile_resources_locally
+    )
+    is_watch_bundle = get_is_watch_bundle(ctx)
+    return AppleResourceProcessingOptions(
+        prefer_local = compile_resources_locally and (not is_watch_bundle),
+        # TODO: Remote execution preference should be part of `apple_toolchain()`, same as `compile_resources_locally`
+        prefer_remote = is_watch_bundle,
+        allow_cache_upload = compile_resources_locally,
+    )
+
+def get_bundle_infos_from_graph(graph: ResourceGraphInfo) -> list[AppleBundleLinkerMapInfo]:
+    bundle_infos = []
+    for node in graph.nodes.traverse():
+        if not node.resource_spec:
+            continue
+
+        resource_spec = node.resource_spec
+        for artifact in resource_spec.files:
+            if not isinstance(artifact, Dependency):
+                continue
+
+            bundle_info = artifact.get(AppleBundleLinkerMapInfo)
+            if bundle_info:
+                bundle_infos.append(bundle_info)
+
+    return bundle_infos
+
+def merge_bundle_linker_maps_info(infos: list[AppleBundleLinkerMapInfo]) -> AppleBundleLinkerMapInfo:
+    return AppleBundleLinkerMapInfo(
+        linker_maps = flatten([info.linker_maps for info in infos]),
+    )
+
+def get_apple_versioned_macos_bundle_value_primitive(name: str, versioned_macos_bundle: bool) -> bool:
+    # versioned_macos_bundle only makes sense on mac, disregard value otherwise
+    if name == "macosx" or name == "maccatalyst":
+        return versioned_macos_bundle
+    else:
+        return False
diff --git a/buck2/prelude/apple/apple_code_signing_types.bzl b/buck2/prelude/apple/apple_code_signing_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_code_signing_types.bzl
@@ -0,0 +1,34 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Provider which exposes a field from `apple_binary` to `apple_bundle` as it might be used during code signing.
+AppleEntitlementsInfo = provider(
+    fields = {
+        "entitlements_file": provider_field(Artifact | None, default = None),
+    }
+)
+
+CodeSignType = enum(
+    "skip",
+    "adhoc",
+    "distribution",
+)
+
+CodeSignConfiguration = enum(
+    # Produces plists inside the app bundle which contains codesign args
+    "dry-run",
+    # Runs all codesigning logic except invoking the actual codesign commands
+    "execution-bypass",
+    # Skips adhoc codesigning when it's not strictly required
+    "fast-adhoc",
+    "none",
+)
+
+def get_code_signing_configuration_attr_value(ctx: AnalysisContext) -> [CodeSignConfiguration, None]:
+    configuration_value = ctx.attrs.code_signing_configuration or ctx.attrs._code_signing_configuration
+    return CodeSignConfiguration(configuration_value)
diff --git a/buck2/prelude/apple/apple_common.bzl b/buck2/prelude/apple/apple_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_common.bzl
@@ -0,0 +1,516 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load(":apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")
+
+def _headers_arg():
+    return {
+        "headers": attrs.named_set(
+            attrs.source(),
+            sorted = True,
+            default = [],
+            doc = """
+    The set of header files that are made available for inclusion to the source files in this
+     target. These should be specified as either a list of header files or a dictionary of header names
+     to header files. The header names can contain forward slashes (`/`). If a list of
+     header files is specified, the headers can be imported
+     with `#import "$HEADER_PATH_PREFIX/$HEADER_NAME"` or `#import
+     "$HEADER_NAME"`, where `$HEADER_PATH_PREFIX` is the value of
+     the target's `header_path_prefix` attribute, and `$HEADER_NAME` is
+     the filename of the header file. If a dictionary is specified, each header can be imported
+     with `#import "$HEADER_NAME"`, where `$HEADER_NAME` is the key
+     corresponding to this file. In this case, the `header_path_prefix` attribute is
+     ignored. In either case, quotes in the import statements can be replaced with angle brackets.
+""",
+        ),
+    }
+
+def _exported_headers_arg():
+    return {
+        "exported_headers": attrs.named_set(
+            attrs.source(),
+            sorted = True,
+            default = [],
+            doc = """
+    The set of header files that are made available for inclusion to the source files in this
+     target and all targets that transitively depend on this one. These should be specified as
+     either a list of header files or a dictionary of header names
+     to header files. The header names can contain forward slashes (`/`). If a list of
+     header files is specified, the headers can be imported
+     with `#import "$HEADER_PATH_PREFIX/$HEADER_NAME"` or, if a header file that belongs to
+     the same rule is being imported, with `#import
+     "$HEADER_NAME"`, where `$HEADER_PATH_PREFIX` is the value of
+     the target's `header_path_prefix` attribute, and `$HEADER_NAME` is
+     the filename of the header file. If a dictionary is specified, each header can be imported
+     with `#import "$HEADER_NAME"`, where `$HEADER_NAME` is the key
+     corresponding to this file. In this case, the `header_path_prefix` attribute is
+     ignored. In either case, quotes in the import statements can be replaced with angle brackets.
+""",
+        ),
+    }
+
+def _header_path_prefix_arg():
+    return {
+        "header_path_prefix": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    A path prefix when including headers of this target. For example, headers from a library defined
+     using
+
+    ```
+    apple_library(
+        name = "Library",
+        headers = glob(["**/*.h"]),
+        header_path_prefix = "Lib",
+    )
+    ```
+
+    can be imported using following mapping
+
+    ```
+    Library/SubDir/Header1.h -> Lib/Header1.h
+    Library/Header2.h -> Lib/Header2.h
+    ```
+
+    Defaults to the short name of the target. Can contain forward slashes (`/`), but
+     cannot start with one. See `headers` for more information.
+""",
+        ),
+    }
+
+def _frameworks_arg():
+    return {
+        "frameworks": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    A list of system frameworks that the code in this target uses. Each entry should be a path
+     starting with `$SDKROOT` or `$PLATFORM_DIR` to denote that the rest of the
+     path is relative to the root of the SDK used for the build or to the platform toolchain
+     directory.
+""",
+        ),
+    }
+
+def _target_sdk_version():
+    return {
+        "target_sdk_version": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    The minimum OS version that the library target should support, overriding the minimum set in
+     `.buckconfig`. When set, Buck will automatically add flags to both Objective-C and
+     Swift compilation that will allow the use of the new APIs without guarding code inside availability
+     checks.
+""",
+        ),
+    }
+
+def _info_plist_arg():
+    return {
+        "info_plist": attrs.source(
+            doc = """
+    A path to an `Info.plist` file that will be placed in the bundle. The specified file
+     will be processed by substituting variable names with their values
+     (see `info_plist_substitutions` for more information).
+"""
+        ),
+    }
+
+def _info_plist_substitutions_arg():
+    return {
+        "info_plist_substitutions": attrs.dict(
+            key = attrs.string(),
+            value = attrs.string(),
+            sorted = False,
+            default = {},
+            doc = """
+    A dictionary that assigns variable names to their values. It is used for variable
+     substitution when processing the file specified in `info_plist`. For example if this
+     argument is set to `{\'VAR\': \'MyValue\'}`, then each occurrence of `$(VAR)` or `${VAR}` in the file will be replaced by `MyValue`.
+""",
+        ),
+    }
+
+def _extra_xcode_sources():
+    return {
+        "extra_xcode_sources": attrs.list(
+            attrs.source(allow_directory = True),
+            default = [],
+            doc = """
+    When the project is generated, this is the list of files that will added to the build phase
+     "Compile Sources" of the given target.
+""",
+        ),
+    }
+
+def _extra_xcode_files():
+    return {
+        "extra_xcode_files": attrs.list(
+            attrs.source(),
+            default = [],
+            doc = """
+    When the project is generated, this is the list of files that will added to the project.
+     Those files won't be added to the build phase "Compile Sources".
+""",
+        ),
+    }
+
+def _privacy_manifest_arg():
+    return {
+        "privacy_manifest": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+    A path to an `.xcprivacy` file that will be placed in the bundle.
+""",
+        ),
+    }
+
+def _serialize_debugging_options_arg():
+    return {
+        # Need ability to distinguish between no value provided by users
+        # vs value explicitly set to `True` (in the latter case, we should
+        # show warning if value cannot be respected in mixed modules while
+        # in the former, we do not show a warning).
+        #
+        # Lack of value defaults to enabling serialized debugging options.
+        "serialize_debugging_options": attrs.option(attrs.bool(), default = None),
+    }
+
+def _uses_explicit_modules_arg():
+    return {
+        "uses_explicit_modules": attrs.bool(default = False),
+    }
+
+def _meta_apple_library_validation_enabled_default_value():
+    if not is_full_meta_repo():
+        return False
+
+    meta_apple_library_validation_enabled_default = read_root_config("apple", "meta_apple_library_validation", "false").lower() == "true"
+
+    is_arvr_build = read_root_config("fb", "arvr_build", "false").lower() == "true"
+    if is_arvr_build:
+        # Not all arvr builds have `arvr_mode_enabled` constraint, so under arvr
+        # build mode, always disable suffixing checks as those graphs are not suffixed
+        return False
+
+    return select({
+        "DEFAULT": select({
+            "DEFAULT": meta_apple_library_validation_enabled_default,
+            "config//features/apple:fb_xplat_suffixing_check_disabled": False,
+            "config//features/apple:fb_xplat_suffixing_check_enabled": True,
+        }),
+        # arvr targets do not use suffixed targets, as any xplat target deps
+        # get rewritten without the Apple-specific suffixes.
+        "config//build_mode:arvr_mode[enabled]": False,
+    })
+
+def _meta_apple_library_validation_enabled_arg():
+    return {
+        "_meta_apple_library_validation_enabled": attrs.bool(default = _meta_apple_library_validation_enabled_default_value()),
+    }
+
+def _skip_universal_resource_dedupe_default_value():
+    if not is_full_meta_repo():
+        return False
+
+    return select({
+        "DEFAULT": False,
+        "config//features/apple:skip_universal_resource_dedupe_disabled": False,
+        "config//features/apple:skip_universal_resource_dedupe_enabled": True,
+    })
+
+def _skip_universal_resource_dedupe_arg():
+    return {
+        "skip_universal_resource_dedupe": attrs.bool(default = _skip_universal_resource_dedupe_default_value()),
+    }
+
+def _apple_sanitizer_compatibility_arg():
+    if not is_full_meta_repo():
+        return {}
+
+    return {
+        "_sanitizer_compatibility": attrs.default_only(attrs.dep(default = "fbsource//tools/build_defs/apple/sanitizers:sanitizer_compatibility")),
+    }
+
+def _apple_tools_arg():
+    return {
+        "_apple_tools": attrs.dep(default = "prelude//apple/tools:apple-tools", providers = [AppleToolsInfo]),
+    }
+
+def _product_name_from_module_name_arg():
+    return {
+        "product_name_from_module_name": attrs.bool(default = False),
+    }
+
+def _executable_name_for_universal_arg():
+    return {
+        "executable_name": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+                    By default, the name of the universal executable is same as the name of the binary
+                    from the `binary` target attribute. Set `executable_name` to override the default.
+                """,
+        ),
+    }
+
+def _executable_name_arg():
+    return {
+        "executable_name": attrs.option(attrs.string(), default = None),
+    }
+
+def _apple_toolchain_arg():
+    return {
+        "_apple_toolchain": attrs.toolchain_dep(default = "toolchains//:apple-default", providers = [AppleToolchainInfo]),
+    }
+
+def _asset_catalogs_compilation_options_arg():
+    return {
+        "asset_catalogs_compilation_options": attrs.dict(
+            key = attrs.string(),
+            value = attrs.any(),
+            default = {},
+            doc = """
+                A dict holding parameters for asset catalogs compiler (actool). Its options include:
+
+                * `notices` (defaults to `True`)
+                * `warnings` (defaults to `True`)
+                * `errors` (defaults to `True`)
+                * `compress_pngs` (defaults to `True`)
+                * `optimization` (defaults to `'space'`)
+                * `output_format` (defaults to `'human-readable-text'`)
+                * `extra_flags` (defaults to `[]`)
+            """,
+        ),
+    }
+
+def _apple_installer_arg():
+    installer_target = "fbsource//xplat/buck2/platform/apple/python_installer:apple_installer"
+    return {
+        "installer": attrs.default_only(attrs.exec_dep(default = installer_target)),
+    }
+
+def _enforce_minimum_os_plist_key():
+    return {
+        "enforce_minimum_os_plist_key": attrs.bool(default = False),
+    }
+
+def _default_platform_arg():
+    return {"default_platform": attrs.option(attrs.string(), default = None)}
+
+def _codesign_flags_arg():
+    return {"codesign_flags": attrs.list(attrs.string(), default = [])}
+
+def _codesign_identity_arg():
+    return {"codesign_identity": attrs.option(attrs.string(), default = None)}
+
+def _defaults_arg():
+    return {"defaults": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {})}
+
+def _deps_arg():
+    return {"deps": attrs.list(attrs.dep(), default = [])}
+
+def _devirt_enabled_arg():
+    return {"devirt_enabled": attrs.bool(default = False)}
+
+def _diagnostics_arg():
+    return {"diagnostics": attrs.dict(key = attrs.string(), value = attrs.source(), sorted = False, default = {})}
+
+def _enable_cxx_interop_arg():
+    return {"enable_cxx_interop": attrs.bool(default = False)}
+
+def _fat_lto_arg():
+    return {"fat_lto": attrs.bool(default = False)}
+
+def _ibtool_flags_arg():
+    return {"ibtool_flags": attrs.option(attrs.list(attrs.string()), default = None)}
+
+def _libraries_arg():
+    return {"libraries": attrs.list(attrs.string(), default = [])}
+
+def _link_group_arg():
+    return {"link_group": attrs.option(attrs.string(), default = None)}
+
+def _minimum_os_version_arg():
+    return {"minimum_os_version": attrs.option(attrs.string(), default = None)}
+
+def _modular_arg():
+    return {"modular": attrs.bool(default = False)}
+
+def _module_name_arg():
+    return {"module_name": attrs.option(attrs.string(), default = None)}
+
+def _module_requires_cxx_arg():
+    return {"module_requires_cxx": attrs.bool(default = False)}
+
+def _product_name_arg():
+    return {"product_name": attrs.option(attrs.string(), default = None)}
+
+def _resource_group_arg():
+    return {"resource_group": attrs.option(attrs.string(), default = None)}
+
+def _sdk_modules_arg():
+    return {"sdk_modules": attrs.list(attrs.string(), default = [])}
+
+def _static_library_basename_arg():
+    return {"static_library_basename": attrs.option(attrs.string(), default = None)}
+
+def _strip_level_arg():
+    return {
+        "strip_level": attrs.enum(
+            ["unstripped", "all", "non_global", "debug"],
+            default = read_root_config("apple", "strip_level", "unstripped"),
+        )
+    }
+
+def _swift_module_skip_function_bodies_arg():
+    return {"swift_module_skip_function_bodies": attrs.bool(default = True)}
+
+def _disable_generated_umbrella_header_arg():
+    # When True, the Swift compilation will not auto-generate an umbrella
+    # header for mixed ObjC/Swift modules. Modules that opt in must provide
+    # their own umbrella header (or an empty one) named after the module so
+    # that `#import <ModuleName/ModuleName.h>` emitted in the -Swift.h header
+    # still resolves.
+    return {"disable_generated_umbrella_header": attrs.bool(default = True)}
+
+def _swift_package_name_arg():
+    return {"swift_package_name": attrs.option(attrs.string(), default = None)}
+
+def _skip_private_swiftinterface_arg():
+    return {"skip_private_swiftinterface": attrs.bool(default = False)}
+
+def _thin_lto_arg():
+    return {"thin_lto": attrs.bool(default = False)}
+
+def _use_submodules_arg():
+    return {"use_submodules": attrs.bool(default = True)}
+
+def _uses_cxx_explicit_modules_arg():
+    return {"uses_cxx_explicit_modules": attrs.bool(default = False)}
+
+def _uses_modules_arg():
+    return {"uses_modules": attrs.bool(default = False)}
+
+def _xcode_product_type_arg():
+    return {"xcode_product_type": attrs.option(attrs.string(), default = None)}
+
+def _entitlements_suffixed_key_map_arg():
+    return {
+        "entitlements_suffixed_key_map": attrs.dict(
+            key = attrs.string(),
+            value = attrs.string(),
+            sorted = False,
+            default = {},
+            doc = """
+    A map of entitlement key to suffix string. For each entry, the corresponding value(s) in the
+     entitlements plist will have the suffix appended. Values can be a single string or a list of
+     strings; both are handled. For example, `{"keychain-access-groups": ".suffix"}` will append
+     `.suffix` to every value under the `keychain-access-groups` key.
+""",
+        ),
+    }
+
+def _entitlements_removed_keys_arg():
+    return {
+        "entitlements_removed_keys": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    A list of entitlement keys to remove from the entitlements plist. Any key present in this list
+     will be deleted from the final entitlements before code signing. For example,
+     `["com.apple.developer.icloud-services"]` will remove the `com.apple.developer.icloud-services`
+     key from the entitlements.
+""",
+        ),
+    }
+
+def _entitlements_removed_values_map_arg():
+    return {
+        "entitlements_removed_values_map": attrs.dict(
+            key = attrs.string(),
+            value = attrs.list(attrs.string()),
+            sorted = False,
+            default = {},
+            doc = """
+    A map of entitlement keys to a list of values to remove from that key's value in the
+     entitlements plist. If the entitlement value is a list, the specified values are removed
+     from it. If the entitlement value is a dict, the specified values are removed as keys
+     from it. For example, `{"keychain-access-groups": ["group1"]}` will remove "group1"
+     from the `keychain-access-groups` list.
+""",
+        ),
+    }
+
+apple_common = struct(
+    headers_arg = _headers_arg,
+    exported_headers_arg = _exported_headers_arg,
+    header_path_prefix_arg = _header_path_prefix_arg,
+    frameworks_arg = _frameworks_arg,
+    target_sdk_version = _target_sdk_version,
+    info_plist_arg = _info_plist_arg,
+    info_plist_substitutions_arg = _info_plist_substitutions_arg,
+    extra_xcode_sources = _extra_xcode_sources,
+    extra_xcode_files = _extra_xcode_files,
+    privacy_manifest_arg = _privacy_manifest_arg,
+    serialize_debugging_options_arg = _serialize_debugging_options_arg,
+    uses_explicit_modules_arg = _uses_explicit_modules_arg,
+    meta_apple_library_validation_enabled_arg = _meta_apple_library_validation_enabled_arg,
+    skip_universal_resource_dedupe_arg = _skip_universal_resource_dedupe_arg,
+    apple_sanitizer_compatibility_arg = _apple_sanitizer_compatibility_arg,
+    apple_tools_arg = _apple_tools_arg,
+    product_name_from_module_name_arg = _product_name_from_module_name_arg,
+    executable_name_for_universal_arg = _executable_name_for_universal_arg,
+    executable_name_arg = _executable_name_arg,
+    apple_toolchain_arg = _apple_toolchain_arg,
+    asset_catalogs_compilation_options_arg = _asset_catalogs_compilation_options_arg,
+    apple_installer_arg = _apple_installer_arg,
+    enforce_minimum_os_plist_key = _enforce_minimum_os_plist_key,
+    default_platform_arg = _default_platform_arg,
+    codesign_flags_arg = _codesign_flags_arg,
+    codesign_identity_arg = _codesign_identity_arg,
+    defaults_arg = _defaults_arg,
+    deps_arg = _deps_arg,
+    devirt_enabled_arg = _devirt_enabled_arg,
+    diagnostics_arg = _diagnostics_arg,
+    enable_cxx_interop_arg = _enable_cxx_interop_arg,
+    fat_lto_arg = _fat_lto_arg,
+    ibtool_flags_arg = _ibtool_flags_arg,
+    libraries_arg = _libraries_arg,
+    link_group_arg = _link_group_arg,
+    minimum_os_version_arg = _minimum_os_version_arg,
+    modular_arg = _modular_arg,
+    module_name_arg = _module_name_arg,
+    module_requires_cxx_arg = _module_requires_cxx_arg,
+    product_name_arg = _product_name_arg,
+    resource_group_arg = _resource_group_arg,
+    sdk_modules_arg = _sdk_modules_arg,
+    static_library_basename_arg = _static_library_basename_arg,
+    strip_level_arg = _strip_level_arg,
+    swift_module_skip_function_bodies_arg = _swift_module_skip_function_bodies_arg,
+    disable_generated_umbrella_header_arg = _disable_generated_umbrella_header_arg,
+    swift_package_name_arg = _swift_package_name_arg,
+    skip_private_swiftinterface_arg = _skip_private_swiftinterface_arg,
+    thin_lto_arg = _thin_lto_arg,
+    use_submodules_arg = _use_submodules_arg,
+    uses_cxx_explicit_modules_arg = _uses_cxx_explicit_modules_arg,
+    uses_modules_arg = _uses_modules_arg,
+    xcode_product_type_arg = _xcode_product_type_arg,
+    entitlements_suffixed_key_map_arg = _entitlements_suffixed_key_map_arg,
+    entitlements_removed_keys_arg = _entitlements_removed_keys_arg,
+    entitlements_removed_values_map_arg = _entitlements_removed_values_map_arg,
+)
diff --git a/buck2/prelude/apple/apple_core_data.bzl b/buck2/prelude/apple/apple_core_data.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_core_data.bzl
@@ -0,0 +1,122 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load(
+    "@prelude//ide_integrations/xcode:data.bzl",
+    "XCODE_DATA_SUB_TARGET",
+    "XcodeDataInfoKeys",
+    "generate_xcode_data",
+)
+load(":apple_bundle_utility.bzl", "get_bundle_min_target_version", "get_bundle_resource_processing_options")
+load(":apple_core_data_types.bzl", "AppleCoreDataSpec")
+load(":apple_sdk.bzl", "get_apple_sdk_name")
+load(":apple_target_sdk_version.bzl", "get_platform_name_for_sdk", "get_platform_version_for_sdk_version")
+load(":resource_groups.bzl", "create_resource_graph")
+
+def apple_core_data_impl(ctx: AnalysisContext) -> list[Provider]:
+    spec = AppleCoreDataSpec(
+        module = ctx.attrs.module,
+        path = ctx.attrs.path,
+    )
+    graph = create_resource_graph(
+        ctx = ctx,
+        labels = ctx.attrs.labels,
+        deps = [],
+        exported_deps = [],
+        core_data_spec = spec,
+    )
+
+    xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "core_data_model", None, _xcode_populate_attributes)
+
+    return [
+        DefaultInfo(
+            sub_targets = {
+                XCODE_DATA_SUB_TARGET: xcode_data_default_info,
+            },
+        ),
+        graph,
+        xcode_data_info,
+    ]
+
+def compile_apple_core_data(ctx: AnalysisContext, specs: list[AppleCoreDataSpec], product_name: str) -> Artifact | None:
+    if len(specs) == 0:
+        return None
+
+    output = ctx.actions.declare_output("AppleCoreDataCompiled", has_content_based_path = False)
+
+    # Aggregate all the coredata momc and mapc commands together
+    tool_commands = []
+    for spec in specs:
+        tool, output_path = _get_model_args(ctx, spec)
+        tool_command = _get_tool_command(ctx, spec, product_name, tool, output_path)
+        tool_commands.append(tool_command)
+
+    # Sandboxing and fs isolation on RE machines results in Xcode tools failing
+    # when those are working in freshly created directories in buck-out.
+    # See https://fb.workplace.com/groups/1042353022615812/permalink/1872164996301273/
+    # As a workaround create a directory in tmp, use it for Xcode tools, then
+    # copy the result to buck-out.
+    wrapper_script, _ = ctx.actions.write(
+        "tool_wrapper.sh",
+        [
+            cmd_args("set -euo pipefail"),
+            cmd_args('export TMPDIR="$(mktemp -d)"'),
+            cmd_args(tool_commands),
+            cmd_args(output, format = 'mkdir -p {} && cp -r "$TMPDIR"/ {}'),
+        ],
+        allow_args = True,
+        has_content_based_path = False,
+    )
+    combined_command = cmd_args(["/bin/sh", wrapper_script], hidden = tool_commands + [output.as_output()])
+    processing_options = get_bundle_resource_processing_options(ctx)
+    ctx.actions.run(
+        combined_command,
+        prefer_local = processing_options.prefer_local,
+        prefer_remote = processing_options.prefer_remote,
+        allow_cache_upload = processing_options.allow_cache_upload,
+        category = "apple_core_data",
+    )
+    return output
+
+def _get_model_args(ctx: AnalysisContext, core_data_spec: AppleCoreDataSpec):
+    toolchain = ctx.attrs._apple_toolchain[AppleToolchainInfo]
+
+    if core_data_spec.path.extension == ".xcmappingmodel":
+        filename = paths.replace_extension(core_data_spec.path.basename, ".cdm")
+        return toolchain.mapc, cmd_args("$TMPDIR/" + filename)
+    else:
+        return toolchain.momc, cmd_args("$TMPDIR")
+
+def _get_tool_command(ctx: AnalysisContext, core_data_spec: AppleCoreDataSpec, product_name: str, tool: RunInfo, output: cmd_args) -> cmd_args:
+    sdk_name = get_apple_sdk_name(ctx)
+    deployment_target = get_platform_version_for_sdk_version(
+        sdk_name = sdk_name,
+        sdk_version = get_bundle_min_target_version(ctx, ctx.attrs.binary),
+    )
+
+    return cmd_args(
+        [
+            tool,
+            "--sdkroot",
+            ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_path,
+            "--" + get_platform_name_for_sdk(sdk_name) + "-deployment-target",
+            deployment_target,
+            "--module",
+            core_data_spec.module if core_data_spec.module else product_name,
+            cmd_args(core_data_spec.path, format = "./{}"),
+            output,
+        ],
+        delimiter = " ",
+        hidden = core_data_spec.path,
+    )
+
+def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:
+    data = {XcodeDataInfoKeys.EXTRA_XCODE_FILES: [ctx.attrs.path]}
+    return data
diff --git a/buck2/prelude/apple/apple_core_data_types.bzl b/buck2/prelude/apple/apple_core_data_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_core_data_types.bzl
@@ -0,0 +1,12 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+AppleCoreDataSpec = record(
+    module = field(str | None),
+    path = field(Artifact),
+)
diff --git a/buck2/prelude/apple/apple_dsym.bzl b/buck2/prelude/apple/apple_dsym.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_dsym.bzl
@@ -0,0 +1,92 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+load(":apple_toolchain_types.bzl", "AppleToolchainInfo")
+load(":debug.bzl", "AppleDebuggableInfo", "AppleSelectiveDebuggableMetadata")  # @unused Used as a type
+
+DSYM_SUBTARGET = "dsym"
+DSYM_INFO_SUBTARGET = "dsym-info"
+EXTENDED_DSYM_INFO_SUBTARGET = "extended-dsym-info"
+DWARF_AND_DSYM_SUBTARGET = "dwarf-and-dsym"
+
+def get_apple_dsym(
+    ctx: AnalysisContext, executable: Artifact, debug_info: list[ArgLike], action_identifier: str, output_path_override: [str, None] = None
+) -> Artifact:
+    output_path = output_path_override or "{}.dSYM".format(executable.short_path)
+    return get_apple_dsym_ext(ctx, executable, debug_info, action_identifier, output_path)
+
+# TODO(T110672942): Things which are still unsupported:
+# - oso_prefix
+def get_apple_dsym_ext(ctx: AnalysisContext, executable: [ArgLike, Artifact], debug_info: list[ArgLike], action_identifier: str, output_path: str) -> Artifact:
+    dsymutil = ctx.attrs._apple_toolchain[AppleToolchainInfo].dsymutil
+    output = ctx.actions.declare_output(output_path, dir = True, has_content_based_path = False)
+    cmd = cmd_args(
+        [
+            dsymutil,
+            # Reproducers are not useful, we can reproduce from the action digest.
+            "--reproducer=Off",
+        ],
+        # Mach-O executables don't contain DWARF data.
+        # Instead, they contain paths to the object files which themselves contain DWARF data.
+        # So, those object files are needed for dsymutil to be to create the dSYM bundle.
+        hidden = debug_info,
+    )
+    cmd.add(
+        "-o",
+        output.as_output(),
+        executable,
+    )
+    ctx.actions.run(cmd, category = "apple_dsym", identifier = action_identifier)
+    return output
+
+AppleDsymJsonInfo = record(
+    # JSON object containing the list of dSYMs
+    json_object = field(dict[str, typing.Any]),
+    # A list of all artifacts referenced in `json_object`
+    outputs = field(list[Artifact]),
+)
+
+def get_apple_dsym_info_json(
+    binary_dsyms: list[Artifact], dep_dsyms: list[Artifact], metadata: list[AppleSelectiveDebuggableMetadata] | None = None
+) -> AppleDsymJsonInfo:
+    dsym_info = {}
+
+    if len(binary_dsyms) == 1:
+        dsym_info["binary"] = binary_dsyms[0]
+    else:
+        fail("There can only be one binary dSYM")
+
+    if dep_dsyms:
+        # `dedupe` needed as it's possible for the same dSYM to bubble up
+        # through multiple paths in a graph (e.g., including both a binary
+        # + bundle in the `deps` field of a parent bundle).
+        dsym_info["deps"] = dedupe(dep_dsyms)
+
+    metadata_dsym_outputs = []
+    if metadata != None:
+        metadata_json_obj = {}
+        for debuggable_metadata in metadata:
+            metadata_json_obj[debuggable_metadata.dsym] = debuggable_metadata.metadata
+            metadata_dsym_outputs += [debuggable_metadata.dsym, debuggable_metadata.metadata]
+        dsym_info["selective_metadata"] = metadata_json_obj
+
+    return AppleDsymJsonInfo(
+        json_object = dsym_info,
+        outputs = binary_dsyms + dep_dsyms + metadata_dsym_outputs,
+    )
+
+def get_deps_debuggable_infos(ctx: AnalysisContext) -> list[AppleDebuggableInfo]:
+    binary_labels = filter(None, [getattr(binary_dep, "label", None) for binary_dep in (ctx.attrs.binary.values() if ctx.attrs.binary else {})])
+    deps_debuggable_infos = filter(
+        None,
+        # It's allowed for `ctx.attrs.binary` to appear in `ctx.attrs.deps` as well,
+        # in this case, do not duplicate the debugging info for the binary coming from two paths.
+        [dep.get(AppleDebuggableInfo) for dep in ctx.attrs.deps if dep.label not in binary_labels],
+    )
+    return deps_debuggable_infos
diff --git a/buck2/prelude/apple/apple_entitlements.bzl b/buck2/prelude/apple/apple_entitlements.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_entitlements.bzl
@@ -0,0 +1,71 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+load(":apple_bundle_utility.bzl", "get_default_binary_dep")
+load(":apple_code_signing_types.bzl", "AppleEntitlementsInfo", "CodeSignType")
+load(":apple_sdk_metadata.bzl", "IPhoneSimulatorSdkMetadata", "MacOSXCatalystSdkMetadata")
+load(":apple_toolchain_types.bzl", "AppleToolchainInfo")
+
+def get_entitlements_codesign_args(ctx: AnalysisContext, codesign_type: CodeSignType) -> list[ArgLike]:
+    include_entitlements = should_include_entitlements(ctx, codesign_type)
+    maybe_entitlements = _entitlements_file(ctx) if include_entitlements else None
+    entitlements_args = ["--entitlements", maybe_entitlements] if maybe_entitlements else []
+    return entitlements_args
+
+def should_include_entitlements(ctx: AnalysisContext, codesign_type: CodeSignType) -> bool:
+    if codesign_type == CodeSignType("distribution"):
+        return True
+
+    if codesign_type == CodeSignType("adhoc"):
+        # The config-based override value takes priority over target value
+        if ctx.attrs._use_entitlements_when_adhoc_code_signing != None:
+            return ctx.attrs._use_entitlements_when_adhoc_code_signing
+        return ctx.attrs.use_entitlements_when_adhoc_code_signing
+
+    return False
+
+def _entitlements_file(ctx: AnalysisContext) -> Artifact | None:
+    if hasattr(ctx.attrs, "entitlements_file"):
+        # Bundling `apple_test` which doesn't have a binary to provide the entitlements, so they are provided via `entitlements_file` attribute directly.
+        return ctx.attrs.entitlements_file
+
+    if not ctx.attrs.binary:
+        return None
+
+    # The `binary` attribute can be either an apple_binary or a dynamic library from apple_library
+    binary_entitlement_info = get_default_binary_dep(ctx.attrs.binary).get(AppleEntitlementsInfo)
+    if binary_entitlement_info and binary_entitlement_info.entitlements_file:
+        return binary_entitlement_info.entitlements_file
+
+    return ctx.attrs._codesign_entitlements
+
+_SDK_NAMES_NEED_ENTITLEMENTS_IN_BINARY = [
+    IPhoneSimulatorSdkMetadata.name,
+    MacOSXCatalystSdkMetadata.name,
+]
+
+def _needs_entitlements_in_binary(ctx: AnalysisContext) -> bool:
+    apple_toolchain_info = ctx.attrs._apple_toolchain[AppleToolchainInfo]
+    return apple_toolchain_info.sdk_name in _SDK_NAMES_NEED_ENTITLEMENTS_IN_BINARY
+
+def entitlements_link_flags(ctx: AnalysisContext) -> list[typing.Any]:
+    return (
+        [
+            "-Xlinker",
+            "-sectcreate",
+            "-Xlinker",
+            "__TEXT",
+            "-Xlinker",
+            "__entitlements",
+            "-Xlinker",
+            ctx.attrs.entitlements_file,
+        ]
+        if (ctx.attrs.entitlements_file and _needs_entitlements_in_binary(ctx))
+        else []
+    )
diff --git a/buck2/prelude/apple/apple_error_handler.bzl b/buck2/prelude/apple/apple_error_handler.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_error_handler.bzl
@@ -0,0 +1,229 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# @oss-disable[end= ]: load(
+    # @oss-disable[end= ]: "@prelude//apple/meta_only:apple_extra_error_categories.bzl",
+    # @oss-disable[end= ]: "APPLE_CXX_FLAG_MESSAGES",
+    # @oss-disable[end= ]: "APPLE_CXX_MESSAGE_CATEGORIES",
+    # @oss-disable[end= ]: "APPLE_CXX_STDERR_CATEGORIES",
+    # @oss-disable[end= ]: "APPLE_META_STDERR_ERROR_CATEGORIES",
+    # @oss-disable[end= ]: "SWIFT_CATEGORY_REMEDIATION",
+    # @oss-disable[end= ]: "SWIFT_STDERR_CATEGORIES",
+# @oss-disable[end= ]: )
+load("@prelude//apple/swift:swift_toolchain.bzl", "get_swift_toolchain_info")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//error_handler:error_enricher_types.bzl", "ErrorEnricher")
+
+APPLE_CXX_FLAG_MESSAGES = {} # @oss-enable
+APPLE_CXX_MESSAGE_CATEGORIES = [] # @oss-enable
+APPLE_CXX_STDERR_CATEGORIES = [] # @oss-enable
+APPLE_META_STDERR_ERROR_CATEGORIES = [] # @oss-enable
+SWIFT_CATEGORY_REMEDIATION = {} # @oss-enable
+SWIFT_STDERR_CATEGORIES = [] # @oss-enable
+
+_APPLE_STDERR_ERROR_CATEGORIES = [
+    # STOP! @oss-disable
+    # If you work at Meta, you probably want to include things in APPLE_META_STDERR_ERROR_CATEGORIES   @oss-disable
+    # so you can include a link to an internal resource (wiki, task, etc)                              @oss-disable
+    # I would only add additional categories here if you think someone in open-source would benefit    @oss-disable
+    # codesigning issues
+    ErrorEnricher(matcher = "codesignprovisioningerror", category = "code_sign_error"), # @oss-enable
+    ErrorEnricher(matcher = "the timestamp service is not available", category = "code_sign_error"),
+    # compilation issues
+    ErrorEnricher(matcher = "failed to emit precompiled module", category = "pcm_compilation_failure"),
+    ErrorEnricher(matcher = "please rebuild precompiled header", category = "pcm_compilation_failure"),
+    ErrorEnricher(matcher = "llvm-lipo", category = "lipo_failure"),
+    ErrorEnricher(matcher = ".modulemap:", category = "modulemap_compilation_failure"),
+    ErrorEnricher(matcher = "missing required modules", category = "missing_required_modules_error"),
+    ErrorEnricher(matcher = "has a minimum deployment target", category = "deployment_target_error"),
+    # toolchain / genrule issues
+    ErrorEnricher(matcher = "stack dump:", category = "binary_execution_failure"),
+    ErrorEnricher(matcher = "thread 'main' panicked", category = "binary_execution_failure"),
+    ErrorEnricher(matcher = "error while loading shared libraries", category = "binary_execution_failure"),
+    ErrorEnricher(matcher = "traceback (most recent call last)", category = "python_execution_failure"),
+    ErrorEnricher(matcher = "command not found", category = "command_not_found_failure"),
+    ErrorEnricher(matcher = "command timed out", category = "timeout_failure"),
+    ErrorEnricher(matcher = "no such file or directory", category = "no_such_file_failure"),
+    # user errors
+    ErrorEnricher(matcher = "unknown target", category = "unknown_buck_target_failure"),
+    # buck configuration issues
+    ErrorEnricher(matcher = "unknown cell alias", category = "unknown_cell_alias_failure"),
+]
+
+def _match(matcher: str | BuckRegex, lowercase_stderr: str) -> bool:
+    if isinstance(matcher, str):
+        return matcher in lowercase_stderr
+    elif isinstance(matcher, BuckRegex):
+        return matcher.match(lowercase_stderr)
+    else:
+        fail("Unknown matcher type: {}", type(matcher))
+
+def _add_category_strings(ctx: ActionErrorCtx, lowercase_stderr: str, errors: list[ActionSubError], source: list[ErrorEnricher]):
+    for enricher in source:
+        if not _match(enricher.matcher, lowercase_stderr):
+            continue
+
+        subcategory = None
+        remediation = None
+        if enricher.subcategory_extractor:
+            subcategory = enricher.subcategory_extractor(lowercase_stderr)
+            if subcategory and enricher.subcategory_remediations and subcategory in enricher.subcategory_remediations:
+                remediation = enricher.subcategory_remediations[subcategory]
+
+        errors.append(
+            ctx.new_sub_error(
+                category = "apple_" + enricher.category,
+                message = enricher.message,
+                subcategory = subcategory,
+                remediation = remediation,
+                show_in_stderr = remediation != None,
+            )
+        )
+
+def _category_match(message: str, path: str, categories: list[ErrorEnricher]) -> ErrorEnricher | None:
+    for error_category in categories:
+        if error_category.file_matcher and error_category.file_matcher not in path:
+            continue
+
+        if _match(error_category.matcher, message):
+            return error_category
+
+    return None
+
+def apple_build_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:
+    errors = []
+
+    lowercase_stderr = ctx.stderr.lower()
+    _add_category_strings(ctx, lowercase_stderr, errors, _APPLE_STDERR_ERROR_CATEGORIES)
+    _add_category_strings(ctx, lowercase_stderr, errors, APPLE_META_STDERR_ERROR_CATEGORIES)
+
+    return errors
+
+def cxx_error_deserializer(ctx: AnalysisContext) -> RunInfo | None:
+    return get_cxx_toolchain_info(ctx).binary_utilities_info.custom_tools.get("serialized-diags-to-json", None)
+
+def swift_error_deserializer(ctx: AnalysisContext) -> RunInfo | None:
+    return get_swift_toolchain_info(ctx).serialized_diags_to_json
+
+def _valid_error(error: dict) -> bool:
+    return "path" in error and "line" in error and "message" in error and "severity" in error
+
+def cxx_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:
+    errors = []
+    for val in ctx.output_artifacts.values():
+        for error_json in val.read_json():
+            if not _valid_error(error_json):
+                continue
+
+            # Clang optionally populates a category and flag field. We are only
+            # interested in the flag for now, which helps to know which flag to
+            # disable to bypass an error.
+            remediation = None
+            postfix = ""
+            subcategory = None
+            error_flag = error_json.get("flag", None)
+            if error_flag:
+                subcategory = error_flag.replace("-", "_")
+                remediation = APPLE_CXX_FLAG_MESSAGES.get(error_flag, None)
+                postfix = " [-W{}]".format(error_flag)
+
+            # Fall back to per-error message matching when no flag-based
+            # remediation matched, mirroring swift_error_handler.
+            if remediation == None:
+                custom_category = _category_match(
+                    message = error_json["message"],
+                    path = error_json["path"],
+                    categories = APPLE_CXX_MESSAGE_CATEGORIES,
+                )
+                if custom_category:
+                    subcategory = custom_category.category
+                    if custom_category.message:
+                        remediation = custom_category.message
+
+            errors.append(
+                ctx.new_sub_error(
+                    category = "apple_cxx_" + error_json["severity"],
+                    message = error_json["message"] + postfix,
+                    file = error_json["path"],
+                    lnum = error_json["line"],
+                    col = error_json["col"],
+                    remediation = remediation,
+                    show_in_stderr = remediation != None,
+                    subcategory = subcategory,
+                ),
+            )
+
+    # The cxx error handler is also used for linking, which will not have any
+    # serialzed diagnostics, so go through the stderr matcher here.
+    if not ctx.output_artifacts.values():
+        _add_category_strings(ctx, ctx.stderr.lower(), errors, APPLE_CXX_STDERR_CATEGORIES)
+
+    return errors
+
+def _get_error_type(severity: str) -> str | None:
+    error_type = None
+    if severity == "error":
+        error_type = "E"
+    elif severity == "warning":
+        error_type = "W"
+    elif severity == "note":
+        error_type = "N"
+
+    return error_type
+
+def swift_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:
+    errors = []
+    for val in ctx.output_artifacts.values():
+        for error_json in val.read_json():
+            if not _valid_error(error_json):
+                continue
+
+            severity = error_json["severity"]
+            message = error_json["message"]
+            remediation = None
+            subcategory = None
+
+            # Swift serializes the category in the form:
+            # SendableClosureCaptures@https://docs.swift.org/compiler/documentation/diagnostics/sendable-closure-captures
+            category = error_json.get("category", "")
+            if "@" in category:
+                # Convert to markdown links for phabricator
+                components = error_json["category"].split("@")
+                message += " [{}]({})".format(components[0], components[1])
+                subcategory = components[0].lower()
+                if components[0] in SWIFT_CATEGORY_REMEDIATION:
+                    remediation = SWIFT_CATEGORY_REMEDIATION[components[0]]
+            elif category in SWIFT_CATEGORY_REMEDIATION:
+                remediation = SWIFT_CATEGORY_REMEDIATION[category]
+            else:
+                # With no category in the error itself we categorise based on
+                # the message content.
+                custom_category = _category_match(
+                    message = message,
+                    path = error_json["path"],
+                    categories = SWIFT_STDERR_CATEGORIES,
+                )
+                if custom_category:
+                    subcategory = custom_category.category
+                    if custom_category.message:
+                        remediation = custom_category.message
+            errors.append(
+                ctx.new_sub_error(
+                    category = "swift_" + severity,
+                    message = message,
+                    file = error_json["path"],
+                    lnum = error_json["line"],
+                    col = error_json["col"],
+                    error_type = _get_error_type(severity),
+                    remediation = remediation,
+                    show_in_stderr = remediation != None,
+                    subcategory = subcategory,
+                ),
+            )
+
+    return errors
diff --git a/buck2/prelude/apple/apple_finalize_codesign.bzl b/buck2/prelude/apple/apple_finalize_codesign.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_finalize_codesign.bzl
@@ -0,0 +1,68 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//xplugins:types.bzl", "XPluginsFunctionMappingManifestInfo")
+load(
+    ":apple_bundle_types.bzl",
+    "AppleBundleInfo",
+    "AppleBundleLinkerMapInfo",
+    "AppleInfoPlistInfo",
+)
+load(
+    ":debug.bzl",
+    "AppleDebuggableInfo",
+)
+
+def _apple_finalize_bundle_impl(ctx):
+    original_bundle = ctx.attrs.bundle
+    original_bundle_info = original_bundle[AppleBundleInfo]
+    bundle_artifact = original_bundle_info.bundle
+    finalized_bundle = ctx.actions.declare_output(bundle_artifact.basename, has_content_based_path = False)
+
+    cmd = cmd_args([
+        ctx.attrs.finalizer[RunInfo],
+        "--input-bundle-path",
+        bundle_artifact,
+        "--output-bundle-path",
+        finalized_bundle.as_output(),
+        "--sign-key",
+        ctx.attrs.sign_key,
+    ])
+    ctx.actions.run(
+        cmd,
+        category = "apple_finalize_bundle",
+        identifier = bundle_artifact.basename,
+    )
+
+    finalized_bundle_info = AppleBundleInfo(
+        bundle = finalized_bundle,
+        bundle_type = original_bundle_info.bundle_type,
+        binary_name = original_bundle_info.binary_name,
+        contains_watchapp = original_bundle_info.contains_watchapp,
+        skip_copying_swift_stdlib = original_bundle_info.skip_copying_swift_stdlib,
+        signing_info = original_bundle_info.signing_info,
+    )
+
+    forwarded_providers = [original_bundle[AppleDebuggableInfo], original_bundle[AppleInfoPlistInfo], original_bundle[AppleBundleLinkerMapInfo]]
+    xplugins_function_mapping_manifest_info = original_bundle.get(XPluginsFunctionMappingManifestInfo)
+    if xplugins_function_mapping_manifest_info:
+        forwarded_providers.append(xplugins_function_mapping_manifest_info)
+
+    return [
+        DefaultInfo(default_output = finalized_bundle),
+        finalized_bundle_info,
+    ] + forwarded_providers
+
+apple_finalize_bundle = rule(
+    attrs = {
+        "bundle": attrs.dep(providers = [AppleBundleInfo]),
+        "finalizer": attrs.exec_dep(providers = [RunInfo]),
+        "sign_key": attrs.string(default = "fbios-debug"),
+    },
+    impl = _apple_finalize_bundle_impl,
+)
diff --git a/buck2/prelude/apple/apple_framework_versions.bzl b/buck2/prelude/apple/apple_framework_versions.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_framework_versions.bzl
@@ -0,0 +1,1195 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":apple_sdk.bzl", "get_apple_sdk_name")
+load(":apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")
+load(":apple_utility.bzl", "has_apple_toolchain")
+
+FRAMEWORK_INTRODUCED_VERSIONS = {
+    "AGL": {"macosx": (10, 0, 0)},
+    "ARKit": {"iphoneos": (11, 0, 0), "maccatalyst": (14, 0, 0)},
+    "AVFAudio": {
+        "appletvos": (14, 5, 0),
+        "iphoneos": (14, 5, 0),
+        "maccatalyst": (14, 5, 0),
+        "macosx": (11, 3, 0),
+        "watchos": (9, 0, 0),
+    },
+    "AVFoundation": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 2, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 7, 0),
+        "watchos": (3, 0, 0),
+    },
+    "AVKit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 9, 0),
+        "watchos": (9, 0, 0),
+    },
+    "AVRouting": {
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (13, 0, 0),
+    },
+    "Accelerate": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (4, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 3, 0),
+        "watchos": (2, 0, 0),
+    },
+    "Accessibility": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+        "watchos": (7, 0, 0),
+    },
+    "AccessoryNotifications": {
+        "iphoneos": (26, 4, 0),
+    },
+    "AccessorySetupKit": {
+        "iphoneos": (18, 0, 0),
+    },
+    "AccessoryTransportExtension": {
+        "iphoneos": (26, 2, 0),
+    },
+    "Accounts": {
+        "iphoneos": (5, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 8, 0),
+    },
+    "ActivityKit": {"iphoneos": (16, 1, 0), "maccatalyst": (16, 1, 0)},
+    "AdServices": {
+        "iphoneos": (14, 3, 0),
+        "maccatalyst": (14, 3, 0),
+        "macosx": (11, 1, 0),
+    },
+    "AdSupport": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (6, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 14, 0),
+    },
+    "AddressBook": {
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (10, 2, 0),
+    },
+    "AddressBookUI": {"iphoneos": (2, 0, 0), "maccatalyst": (14, 0, 0)},
+    "AlarmKit": {"iphoneos": (26, 0, 0)},
+    "AppClip": {"iphoneos": (14, 0, 0), "maccatalyst": (14, 0, 0)},
+    "AppIntents": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (9, 0, 0),
+    },
+    "AppKit": {"maccatalyst": (13, 0, 0), "macosx": (10, 0, 0)},
+    "AppMigrationKit": {"iphoneos": (26, 1, 0)},
+    "AppTrackingTransparency": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+    },
+    "AppleScriptKit": {"macosx": (10, 0, 0)},
+    "AppleScriptObjC": {"macosx": (10, 6, 0)},
+    "ApplicationServices": {"maccatalyst": (13, 0, 0), "macosx": (10, 0, 0)},
+    "AssetsLibrary": {"iphoneos": (4, 0, 0), "maccatalyst": (14, 0, 0)},
+    "AudioToolbox": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 0, 0),
+    },
+    "AudioUnit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 0, 0),
+    },
+    "AudioVideoBridging": {"macosx": (10, 8, 0)},
+    "AuthenticationServices": {
+        "appletvos": (13, 0, 0),
+        "iphoneos": (12, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+        "watchos": (6, 0, 0),
+    },
+    "AutomatedDeviceEnrollment": {"iphoneos": (16, 1, 0)},
+    "AutomaticAssessmentConfiguration": {
+        "iphoneos": (13, 4, 0),
+        "maccatalyst": (13, 4, 0),
+        "macosx": (10, 15, 4),
+    },
+    "Automator": {"maccatalyst": (14, 0, 0), "macosx": (10, 4, 0)},
+    "BackgroundAssets": {
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (13, 0, 0),
+    },
+    "BackgroundTasks": {
+        "appletvos": (13, 0, 0),
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+    },
+    "BusinessChat": {"iphoneos": (11, 3, 0), "macosx": (10, 13, 4)},
+    "CFNetwork": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 8, 0),
+    },
+    "CalendarStore": {"macosx": (10, 5, 0)},
+    "CallKit": {
+        "iphoneos": (10, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (9, 0, 0),
+    },
+    "CarKey": {"iphoneos": (16, 0, 0), "maccatalyst": (16, 0, 0)},
+    "CarPlay": {"iphoneos": (12, 0, 0), "maccatalyst": (14, 0, 0)},
+    "Carbon": {"macosx": (10, 0, 0)},
+    "Charts": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (9, 0, 0),
+    },
+    "ClassKit": {
+        "iphoneos": (11, 4, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+    },
+    "ClockKit": {
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "watchos": (2, 0, 0),
+    },
+    "CloudKit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 10, 0),
+        "watchos": (3, 0, 0),
+    },
+    "Cocoa": {"macosx": (10, 0, 0)},
+    "Collaboration": {"macosx": (10, 5, 0)},
+    "ColorSync": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 13, 0),
+        "watchos": (9, 0, 0),
+    },
+    "Combine": {
+        "appletvos": (13, 0, 0),
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+        "watchos": (6, 0, 0),
+    },
+    "ContactProvider": {
+        "iphoneos": (18, 0, 0),
+    },
+    "Contacts": {
+        "iphoneos": (9, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 11, 0),
+        "watchos": (2, 0, 0),
+    },
+    "ContactsUI": {
+        "iphoneos": (9, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 11, 0),
+    },
+    "CoreAudio": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 0, 0),
+        "watchos": (3, 0, 0),
+    },
+    "CoreAudioKit": {
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 4, 0),
+    },
+    "CoreAudioTypes": {
+        "appletvos": (13, 0, 0),
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+        "watchos": (6, 0, 0),
+    },
+    "CoreBluetooth": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (5, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 10, 0),
+        "watchos": (4, 0, 0),
+    },
+    "CoreData": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (3, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 4, 0),
+        "watchos": (2, 0, 0),
+    },
+    "CoreDisplay": {
+        "macosx": (10, 8, 0),
+    },
+    "CoreFoundation": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 0, 0),
+        "watchos": (2, 0, 0),
+    },
+    "CoreGraphics": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 8, 0),
+        "watchos": (2, 0, 0),
+    },
+    "CoreHID": {
+        "macosx": (15, 0, 0),
+    },
+    "CoreHaptics": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+    },
+    "CoreImage": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (5, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 11, 0),
+    },
+    "CoreLocation": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 6, 0),
+        "watchos": (2, 0, 0),
+    },
+    "CoreLocationUI": {
+        "iphoneos": (15, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "watchos": (8, 0, 0),
+    },
+    "CoreMIDI": {
+        "appletvos": (15, 0, 0),
+        "iphoneos": (4, 2, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 0, 0),
+        "watchos": (8, 0, 0),
+    },
+    "CoreML": {
+        "appletvos": (11, 0, 0),
+        "iphoneos": (11, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 13, 0),
+        "watchos": (4, 0, 0),
+    },
+    "CoreMedia": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (4, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 7, 0),
+        "watchos": (6, 0, 0),
+    },
+    "CoreMediaIO": {"maccatalyst": (13, 0, 0), "macosx": (10, 7, 0)},
+    "CoreMotion": {
+        "iphoneos": (4, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+        "watchos": (2, 0, 0),
+    },
+    "CoreNFC": {"iphoneos": (11, 0, 0), "maccatalyst": (13, 0, 0)},
+    "CoreServices": {
+        "appletvos": (12, 0, 0),
+        "iphoneos": (12, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 0, 0),
+        "watchos": (5, 0, 0),
+    },
+    "CoreSpotlight": {
+        "iphoneos": (9, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 13, 0),
+    },
+    "CoreTelephony": {
+        "iphoneos": (4, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (10, 10, 0),
+    },
+    "CoreText": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (3, 2, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 8, 0),
+        "watchos": (2, 0, 0),
+    },
+    "CoreTransferable": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (9, 0, 0),
+    },
+    "CoreVideo": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (4, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 4, 0),
+        "watchos": (4, 0, 0),
+    },
+    "CoreWLAN": {"maccatalyst": (13, 0, 0), "macosx": (10, 6, 0)},
+    "CreateML": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (15, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (10, 14, 0),
+    },
+    "CreateMLComponents": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (16, 0, 0),
+        "macosx": (13, 0, 0),
+    },
+    "CryptoKit": {
+        "appletvos": (15, 0, 0),
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (10, 15, 0),
+        "watchos": (8, 0, 0),
+    },
+    "CryptoTokenKit": {
+        "appletvos": (13, 0, 0),
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 10, 0),
+        "watchos": (8, 0, 0),
+    },
+    "DVDPlayback": {"macosx": (10, 3, 0)},
+    "DataDetection": {
+        "appletvos": (15, 0, 0),
+        "iphoneos": (15, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (12, 0, 0),
+        "watchos": (8, 0, 0),
+    },
+    "DeclaredAgeRange": {
+        "iphoneos": (26, 0, 0),
+        "maccatalyst": (26, 0, 0),
+        "macosx": (26, 0, 0),
+    },
+    "DeveloperToolsSupport": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+        "watchos": (7, 0, 0),
+    },
+    "DeviceActivity": {"iphoneos": (15, 0, 0), "maccatalyst": (15, 0, 0)},
+    "DeviceCheck": {
+        "appletvos": (11, 0, 0),
+        "iphoneos": (11, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+        "watchos": (9, 0, 0),
+    },
+    "DeviceDiscoveryExtension": {"iphoneos": (16, 0, 0)},
+    "DeviceDiscoveryUI": {"appletvos": (16, 0, 0)},
+    "DirectoryService": {"macosx": (10, 0, 0)},
+    "DiscRecording": {"macosx": (10, 2, 0)},
+    "DiscRecordingUI": {"macosx": (10, 2, 0)},
+    "DiskArbitration": {"maccatalyst": (13, 0, 0), "macosx": (10, 4, 0)},
+    "DriverKit": {"iphoneos": (16, 0, 0), "macosx": (10, 15, 0)},
+    "EventKit": {
+        "iphoneos": (4, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 8, 0),
+        "watchos": (2, 0, 0),
+    },
+    "EventKitUI": {"iphoneos": (4, 0, 0), "maccatalyst": (13, 0, 0)},
+    "ExceptionHandling": {"maccatalyst": (13, 0, 0), "macosx": (10, 0, 0)},
+    "ExecutionPolicy": {"maccatalyst": (13, 0, 0), "macosx": (10, 15, 0)},
+    "ExposureNotification": {
+        "iphoneos": (13, 5, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (12, 0, 0),
+    },
+    "ExtensionFoundation": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (9, 0, 0),
+    },
+    "ExtensionKit": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (16, 1, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (9, 0, 0),
+    },
+    "ExternalAccessory": {
+        "appletvos": (10, 0, 0),
+        "iphoneos": (3, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 13, 0),
+    },
+    "FSKit": {
+        "macosx": (15, 0, 0),
+    },
+    "FamilyControls": {"iphoneos": (15, 0, 0), "maccatalyst": (15, 0, 0)},
+    "FileProvider": {"iphoneos": (11, 0, 0), "macosx": (10, 15, 0)},
+    "FileProviderUI": {
+        "iphoneos": (11, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (10, 15, 0),
+    },
+    "FinderSync": {"macosx": (10, 10, 0)},
+    "ForceFeedback": {"maccatalyst": (13, 0, 0), "macosx": (10, 2, 0)},
+    "Foundation": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 0, 0),
+        "watchos": (2, 0, 0),
+    },
+    "FoundationModels": {
+        "iphoneos": (26, 0, 0),
+        "maccatalyst": (26, 0, 0),
+        "macosx": (26, 0, 0),
+    },
+    "GLKit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (5, 0, 0),
+        "macosx": (10, 8, 0),
+    },
+    "GLUT": {"macosx": (10, 0, 0)},
+    "GSS": {
+        "iphoneos": (5, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 14, 0),
+    },
+    "GameController": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (7, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 9, 0),
+    },
+    "GameKit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (3, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 8, 0),
+        "watchos": (3, 0, 0),
+    },
+    "GameplayKit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (9, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 11, 0),
+    },
+    "GroupActivities": {
+        "appletvos": (15, 0, 0),
+        "iphoneos": (15, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (12, 0, 0),
+    },
+    "HealthKit": {
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (2, 0, 0),
+    },
+    "HealthKitUI": {
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (2, 0, 0),
+    },
+    "HomeKit": {
+        "appletvos": (10, 0, 0),
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "watchos": (2, 0, 0),
+    },
+    "Hypervisor": {"macosx": (10, 10, 0)},
+    "ICADevices": {"macosx": (10, 3, 0)},
+    "IMServicePlugIn": {"macosx": (10, 7, 0)},
+    "IOBluetooth": {"maccatalyst": (13, 0, 0), "macosx": (10, 2, 0)},
+    "IOBluetoothUI": {"maccatalyst": (14, 0, 0), "macosx": (10, 2, 0)},
+    "IOKit": {
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 0, 0),
+    },
+    "IOSurface": {
+        "appletvos": (11, 0, 0),
+        "iphoneos": (11, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 6, 0),
+    },
+    "IOUSBHost": {"maccatalyst": (14, 0, 0), "macosx": (10, 15, 0)},
+    "IdentityLookup": {
+        "iphoneos": (11, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+    },
+    "IdentityLookupUI": {
+        "iphoneos": (11, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+    },
+    "ImageCaptureCore": {
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 6, 0),
+    },
+    "ImageIO": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (4, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 8, 0),
+        "watchos": (2, 0, 0),
+    },
+    "ImagePlayground": {
+        "iphoneos": (18, 1, 0),
+        "maccatalyst": (18, 1, 0),
+        "macosx": (15, 1, 0),
+    },
+    "InputMethodKit": {"macosx": (10, 5, 0)},
+    "InstallerPlugins": {"macosx": (10, 4, 0)},
+    "InstantMessage": {"macosx": (10, 4, 0)},
+    "Intents": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (10, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (12, 0, 0),
+        "watchos": (3, 2, 0),
+    },
+    "IntentsUI": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (10, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (12, 0, 0),
+        "watchos": (3, 2, 0),
+    },
+    "JavaNativeFoundation": {"macosx": (11, 0, 0)},
+    "JavaRuntimeSupport": {"macosx": (11, 0, 0)},
+    "JavaScriptCore": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (7, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 5, 0),
+    },
+    "Kerberos": {"macosx": (10, 0, 0)},
+    "Kernel": {"macosx": (10, 0, 0)},
+    "KernelManagement": {"maccatalyst": (14, 2, 0), "macosx": (11, 0, 0)},
+    "LDAP": {"macosx": (10, 0, 0)},
+    "LatentSemanticMapping": {"maccatalyst": (13, 0, 0), "macosx": (10, 5, 0)},
+    "LinkPresentation": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+    },
+    "LiveCommunicationKit": {
+        "iphoneos": (17, 4, 0),
+        "maccatalyst": (17, 4, 0),
+        "visionos": (1, 1, 0),
+        "watchos": (10, 4, 0),
+    },
+    "LocalAuthentication": {
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 10, 0),
+        "watchos": (9, 0, 0),
+    },
+    "LocalAuthenticationEmbeddedUI": {
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (12, 0, 0),
+    },
+    "LockedCameraCapture": {
+        "iphoneos": (18, 0, 0),
+        "maccatalyst": (18, 0, 0),
+    },
+    "MLCompute": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+    },
+    "MailKit": {"macosx": (12, 0, 0)},
+    "ManagedSettings": {"iphoneos": (15, 0, 0)},
+    "ManagedSettingsUI": {"iphoneos": (15, 0, 0)},
+    "MapKit": {
+        "appletvos": (9, 2, 0),
+        "iphoneos": (3, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 9, 0),
+        "watchos": (2, 0, 0),
+    },
+    "MarketplaceKit": {"iphoneos": (17, 4, 0)},
+    "Matter": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 1, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (9, 0, 0),
+    },
+    "MatterSupport": {"iphoneos": (16, 1, 0)},
+    "MediaAccessibility": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (7, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 9, 0),
+    },
+    "MediaExtension": {
+        "maccatalyst": (18, 0, 0),
+        "macosx": (15, 0, 0),
+    },
+    "MediaLibrary": {"maccatalyst": (13, 0, 0), "macosx": (10, 9, 0)},
+    "MediaPlayer": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (5, 0, 0),
+    },
+    "MediaSetup": {"iphoneos": (14, 0, 0), "maccatalyst": (15, 4, 0)},
+    "MediaToolbox": {
+        "iphoneos": (6, 0, 0),
+        "macosx": (10, 9, 0),
+    },
+    "MessageUI": {"iphoneos": (3, 0, 0), "maccatalyst": (13, 0, 0)},
+    "Messages": {"iphoneos": (10, 0, 0), "maccatalyst": (14, 0, 0)},
+    "Metal": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 11, 0),
+    },
+    "MetalFX": {
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (13, 0, 0),
+    },
+    "MetalKit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (9, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 11, 0),
+    },
+    "MetalPerformanceShaders": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (9, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 13, 0),
+    },
+    "MetalPerformanceShadersGraph": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+    },
+    "MetricKit": {
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (12, 0, 0),
+    },
+    "MobileCoreServices": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "watchos": (1, 0, 0),
+    },
+    "ModelIO": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (9, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 11, 0),
+    },
+    "MultipeerConnectivity": {
+        "appletvos": (10, 0, 0),
+        "iphoneos": (7, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 10, 0),
+    },
+    "MusicKit": {
+        "appletvos": (15, 0, 0),
+        "iphoneos": (15, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (12, 0, 0),
+        "watchos": (8, 0, 0),
+    },
+    "NaturalLanguage": {
+        "appletvos": (12, 0, 0),
+        "iphoneos": (12, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 14, 0),
+        "watchos": (5, 0, 0),
+    },
+    "NearbyInteraction": {
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+        "watchos": (8, 0, 0),
+    },
+    "NetFS": {"macosx": (10, 6, 0)},
+    "Network": {
+        "appletvos": (12, 0, 0),
+        "iphoneos": (12, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 14, 0),
+        "watchos": (6, 0, 0),
+    },
+    "NetworkExtension": {
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 10, 0),
+        "watchos": (7, 0, 0),
+    },
+    "NewsstandKit": {"iphoneos": (5, 0, 0)},
+    "NotificationCenter": {"iphoneos": (8, 0, 0), "macosx": (10, 10, 0)},
+    "OSAKit": {"macosx": (10, 4, 0)},
+    "OSLog": {
+        "appletvos": (15, 0, 0),
+        "iphoneos": (15, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (10, 15, 0),
+        "watchos": (8, 0, 0),
+    },
+    "Observation": {
+        "iphoneos": (17, 0, 0),
+        "maccatalyst": (17, 0, 0),
+        "macosx": (14, 0, 0),
+        "tvos": (17, 0, 0),
+        "visionos": (1, 0, 0),
+        "watchos": (10, 0, 0),
+    },
+    "OpenCL": {"macosx": (10, 6, 0)},
+    "OpenDirectory": {"maccatalyst": (13, 0, 0), "macosx": (10, 6, 0)},
+    "OpenGL": {"macosx": (10, 0, 0)},
+    "OpenGLES": {"appletvos": (9, 0, 0), "iphoneos": (2, 0, 0)},
+    "PCSC": {"macosx": (10, 0, 0)},
+    "PDFKit": {"iphoneos": (11, 0, 0), "macosx": (10, 4, 0)},
+    "PHASE": {
+        "appletvos": (15, 0, 0),
+        "iphoneos": (15, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (12, 0, 0),
+    },
+    "ParavirtualizedGraphics": {
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+    },
+    "PassKit": {
+        "iphoneos": (6, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (11, 0, 0),
+        "watchos": (2, 0, 0),
+    },
+    "PencilKit": {
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+    },
+    "Photos": {
+        "appletvos": (10, 0, 0),
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 11, 0),
+        "watchos": (9, 0, 0),
+    },
+    "PhotosUI": {
+        "appletvos": (10, 0, 0),
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 11, 0),
+        "watchos": (9, 0, 0),
+    },
+    "PreferencePanes": {"maccatalyst": (14, 0, 0), "macosx": (10, 1, 0)},
+    "ProximitReaderStub": {
+        "maccatalyst": (18, 0, 0),
+        "macosx": (15, 0, 0),
+    },
+    "ProximityReader": {"iphoneos": (15, 4, 0), "maccatalyst": (15, 4, 0)},
+    "PushKit": {
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+        "watchos": (6, 0, 0),
+    },
+    "PushToTalk": {"iphoneos": (16, 0, 0)},
+    "Quartz": {"macosx": (10, 4, 0)},
+    "QuartzCore": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 3, 0),
+    },
+    "QuickLook": {
+        "iphoneos": (4, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 5, 0),
+    },
+    "QuickLookThumbnailing": {
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+    },
+    "QuickLookUI": {"macosx": (12, 0, 0)},
+    "RealityKit": {
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+    },
+    "ReplayKit": {
+        "appletvos": (10, 0, 0),
+        "iphoneos": (9, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (11, 0, 0),
+    },
+    "RoomPlan": {"iphoneos": (16, 0, 0), "maccatalyst": (16, 0, 0)},
+    "Ruby": {"macosx": (10, 5, 0)},
+    "SafariServices": {
+        "iphoneos": (7, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 12, 0),
+    },
+    "SafetyKit": {
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 1, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (9, 1, 0),
+    },
+    "SceneKit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 8, 0),
+        "watchos": (3, 0, 0),
+    },
+    "ScreenCaptureKit": {"maccatalyst": (15, 4, 0), "macosx": (12, 3, 0)},
+    "ScreenSaver": {"macosx": (10, 0, 0)},
+    "ScreenTime": {
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+    },
+    "ScriptingBridge": {"maccatalyst": (13, 0, 0), "macosx": (10, 5, 0)},
+    "Security": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 0, 0),
+        "watchos": (2, 0, 0),
+    },
+    "SecurityFoundation": {"maccatalyst": (13, 0, 0), "macosx": (10, 3, 0)},
+    "SecurityInterface": {"macosx": (10, 3, 0)},
+    "SensitiveContentAnalysis": {
+        "iphoneos": (17, 0, 0),
+        "maccatalyst": (17, 0, 0),
+        "macosx": (14, 0, 0),
+    },
+    "SensorKit": {
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (12, 3, 0),
+    },
+    "ServiceManagement": {
+        "appletvos": (12, 1, 0),
+        "iphoneos": (12, 1, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 6, 0),
+        "watchos": (5, 1, 0),
+    },
+    "SharedWithYou": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (13, 0, 0),
+    },
+    "ShazamKit": {
+        "appletvos": (15, 0, 0),
+        "iphoneos": (15, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (12, 0, 0),
+        "watchos": (8, 0, 0),
+    },
+    "Social": {
+        "iphoneos": (6, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 8, 0),
+    },
+    "SoundAnalysis": {
+        "appletvos": (13, 0, 0),
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+        "watchos": (9, 0, 0),
+    },
+    "Speech": {
+        "iphoneos": (10, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+    },
+    "SpriteKit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (7, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 9, 0),
+        "watchos": (3, 0, 0),
+    },
+    "StateReporting": {
+        "appletvos": (27, 0, 0),
+        "iphoneos": (27, 0, 0),
+        "macosx": (27, 0, 0),
+        "visionos": (27, 0, 0),
+        "watchos": (27, 0, 0),
+    },
+    "StickerKit": {
+        "iphoneos": (18, 0, 0),
+        "macosx": (15, 0, 0),
+    },
+    "StoreKit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (3, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 7, 0),
+        "watchos": (6, 2, 0),
+    },
+    "StoreKitTest": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+        "watchos": (7, 4, 0),
+    },
+    "SwiftData": {
+        "appletvos": (17, 0, 0),
+        "iphoneos": (17, 0, 0),
+        "maccatalyst": (17, 0, 0),
+        "macosx": (14, 0, 0),
+        "watchos": (10, 0, 0),
+    },
+    "SwiftUI": {
+        "appletvos": (13, 0, 0),
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 15, 0),
+        "watchos": (6, 0, 0),
+    },
+    "SyncServices": {"macosx": (10, 4, 0)},
+    "Synchronization": {
+        "iphoneos": (18, 0, 0),
+        "maccatalyst": (18, 0, 0),
+        "macosx": (15, 0, 0),
+        "tvos": (18, 0, 0),
+        "visionos": (2, 0, 0),
+        "watchos": (11, 0, 0),
+    },
+    "System": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+        "watchos": (7, 0, 0),
+    },
+    "SystemConfiguration": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 1, 0),
+    },
+    "SystemExtensions": {"macosx": (10, 15, 0)},
+    "TVMLKit": {"appletvos": (9, 0, 0)},
+    "TVServices": {"appletvos": (9, 0, 0)},
+    "TVUIKit": {"appletvos": (12, 0, 0)},
+    "TWAIN": {"macosx": (10, 2, 0)},
+    "TabletopKit": {
+        "visionos": (2, 0, 0),
+    },
+    "TabularData": {
+        "appletvos": (15, 0, 0),
+        "iphoneos": (15, 0, 0),
+        "maccatalyst": (15, 0, 0),
+        "macosx": (12, 0, 0),
+        "watchos": (8, 0, 0),
+    },
+    "Tcl": {"macosx": (10, 3, 0)},
+    "ThreadNetwork": {
+        "iphoneos": (15, 0, 0),
+        "maccatalyst": (16, 1, 0),
+        "macosx": (13, 0, 0),
+    },
+    "Tk": {"macosx": (10, 4, 0)},
+    "Translation": {
+        "iphoneos": (17, 4, 0),
+        "maccatalyst": (26, 0, 0),
+        "macosx": (14, 4, 0),
+    },
+    "UIKit": {
+        "appletvos": (9, 0, 0),
+        "iphoneos": (2, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "watchos": (2, 0, 0),
+    },
+    "UniformTypeIdentifiers": {
+        "appletvos": (14, 0, 0),
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+        "watchos": (7, 0, 0),
+    },
+    "UserNotifications": {
+        "appletvos": (10, 0, 0),
+        "iphoneos": (10, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 14, 0),
+        "watchos": (3, 0, 0),
+    },
+    "UserNotificationsUI": {
+        "iphoneos": (10, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+    },
+    "VideoDecodeAcceleration": {"macosx": (10, 7, 0)},
+    "VideoSubscriberAccount": {
+        "appletvos": (10, 0, 0),
+        "iphoneos": (10, 0, 0),
+        "macosx": (10, 14, 0),
+    },
+    "VideoToolbox": {
+        "appletvos": (10, 2, 0),
+        "iphoneos": (6, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 8, 0),
+    },
+    "Virtualization": {"macosx": (11, 0, 0)},
+    "Vision": {
+        "appletvos": (11, 0, 0),
+        "iphoneos": (11, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 13, 0),
+    },
+    "VisionKit": {
+        "iphoneos": (13, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (13, 0, 0),
+    },
+    "WatchConnectivity": {
+        "iphoneos": (9, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "watchos": (2, 0, 0),
+    },
+    "WatchKit": {"watchos": (2, 0, 0)},
+    "WeatherKit": {
+        "appletvos": (16, 0, 0),
+        "iphoneos": (16, 0, 0),
+        "maccatalyst": (16, 0, 0),
+        "macosx": (13, 0, 0),
+        "watchos": (9, 0, 0),
+    },
+    "WebKit": {
+        "iphoneos": (8, 0, 0),
+        "maccatalyst": (13, 0, 0),
+        "macosx": (10, 2, 0),
+    },
+    "WiFiAware": {
+        "iphoneos": (26, 0, 0),
+    },
+    "WidgetKit": {
+        "iphoneos": (14, 0, 0),
+        "maccatalyst": (14, 0, 0),
+        "macosx": (11, 0, 0),
+        "watchos": (9, 0, 0),
+    },
+    "iAd": {"iphoneos": (4, 0, 0), "maccatalyst": (13, 0, 0)},
+    "iTunesLibrary": {"maccatalyst": (14, 0, 0), "macosx": (10, 13, 0)},
+    "vecLib": {"macosx": (10, 0, 0)},
+    "vmnet": {"maccatalyst": (13, 0, 0), "macosx": (10, 10, 0)},
+}
+
+def _parse_version(version: str) -> (int, int, int):
+    result = [0, 0, 0]
+    components = [int(x) if x != "0" else 0 for x in version.split(".")]
+    for i in range(0, len(components)):
+        result[i] = components[i]
+    return (result[0], result[1], result[2])
+
+def validate_sdk_frameworks(frameworks: list[str]) -> None:
+    for framework in frameworks:
+        if framework.startswith("$SDKROOT/System/Library/Frameworks"):
+            framework_name = framework[len("$SDKROOT/System/Library/Frameworks/") : -len(".framework")]
+            if framework_name not in FRAMEWORK_INTRODUCED_VERSIONS:
+                fail("Framework {} is missing version information".format(framework_name))
+
+def get_framework_linker_args(ctx: AnalysisContext, framework_names: list[str]) -> cmd_args:
+    if not has_apple_toolchain(ctx):
+        return _get_unchecked_framework_linker_args(framework_names)
+
+    # Convert deployment target string into tuple of ints for easier comparison
+    deployment_target_str = get_min_deployment_version_for_node(ctx)
+    if not deployment_target_str:
+        return _get_unchecked_framework_linker_args(framework_names)
+
+    deployment_target = _parse_version(deployment_target_str)
+
+    # Simulator and device platforms have the same framework versions
+    sdk_name = get_apple_sdk_name(ctx)
+    if sdk_name.endswith("simulator"):
+        sdk_name = sdk_name[: -len("simulator")] + "os"
+
+    weak_frameworks = []
+    strong_frameworks = []
+
+    args = cmd_args()
+    for name in framework_names:
+        is_weak = False
+        versions = FRAMEWORK_INTRODUCED_VERSIONS.get(name, None)
+        if versions:
+            introduced = versions.get(sdk_name, None)
+            if not introduced:
+                message = "SDK framework {} is not compatible with platform {}".format(name, sdk_name)
+                # @oss-disable[end= ]: message += "\n\nFor help, see: https://fburl.com/apple_build_errors/sdk_framework_is_not_compatible\n"
+                fail(message)
+
+            if _version_is_greater_than(introduced, deployment_target):
+                is_weak = True
+
+        if is_weak:
+            weak_frameworks.append(name)
+        else:
+            strong_frameworks.append(name)
+
+    if strong_frameworks:
+        args.add(cmd_args(strong_frameworks, prepend = "-framework"))
+    if weak_frameworks:
+        args.add(cmd_args(weak_frameworks, prepend = "-weak_framework"))
+
+    return args
+
+def _get_unchecked_framework_linker_args(framework_names: list[str]) -> cmd_args:
+    return cmd_args(framework_names, prepend = "-framework")
+
+def _version_is_greater_than(x: (int, int, int), y: (int, int, int)) -> bool:
+    return x[0] > y[0] or (x[0] == y[0] and x[1] > y[1]) or (x[0] == y[0] and x[1] == y[1] and x[2] > y[2])
diff --git a/buck2/prelude/apple/apple_frameworks.bzl b/buck2/prelude/apple/apple_frameworks.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_frameworks.bzl
@@ -0,0 +1,239 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple/swift:swift_compilation.bzl", "extract_swiftmodule_linkables", "get_swiftmodule_linker_flags")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo", "LinkerType")
+load(
+    "@prelude//cxx:transformation_spec.bzl",
+    "TransformationSpecContext",  # @unused Used as a type
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "FrameworksLinkable",
+    "LinkArgs",
+    "LinkInfo",
+    "LinkStrategy",  # @unused Used as a type
+    "MergedLinkInfo",
+    "SwiftmoduleLinkable",  # @unused Used as a type
+    "get_link_args_for_strategy",
+    "has_framework_linkable",
+    "merge_swiftmodule_linkables",
+)
+load("@prelude//utils:expect.bzl", "expect")
+load(":apple_framework_versions.bzl", "get_framework_linker_args", "validate_sdk_frameworks")
+load(":apple_toolchain_types.bzl", "AppleToolchainInfo")
+load(":apple_utility.bzl", "has_apple_toolchain")
+
+_IMPLICIT_SDKROOT_FRAMEWORK_SEARCH_PATHS = [
+    "$SDKROOT/Library/Frameworks",
+    "$SDKROOT/System/Library/Frameworks",
+    "$SDKROOT/System/Library/PrivateFrameworks",
+]
+
+def apple_create_frameworks_linkable(ctx: AnalysisContext) -> [FrameworksLinkable, None]:
+    if not ctx.attrs.libraries and not ctx.attrs.frameworks:
+        return None
+
+    return FrameworksLinkable(
+        libraries = ctx.attrs.libraries,
+        frameworks = ctx.attrs.frameworks,
+    )
+
+def _has_darwin_linker(ctx: AnalysisContext) -> bool:
+    return has_apple_toolchain(ctx) or ctx.attrs._cxx_toolchain[CxxToolchainInfo].linker_info.type == LinkerType("darwin")
+
+def _get_apple_frameworks_linker_flags(ctx: AnalysisContext, linkables: list[[FrameworksLinkable, None]]) -> cmd_args:
+    if not has_framework_linkable(linkables):
+        return cmd_args()
+
+    frameworks = set()
+    libraries = set()
+    for linkable in linkables:
+        if not linkable:
+            continue
+
+        frameworks.update(linkable.frameworks)
+        libraries.update(linkable.libraries)
+
+    framework_names = [to_framework_name(framework) for framework in frameworks]
+    unresolved_framework_paths = _get_non_sdk_unresolved_framework_directories(frameworks)
+
+    expanded_frameworks_paths = _expand_sdk_framework_paths(ctx, unresolved_framework_paths)
+    flags = _get_framework_search_path_flags(expanded_frameworks_paths)
+    flags.add(get_framework_linker_args(ctx, framework_names))
+    flags.add(cmd_args([_library_name(library) for library in libraries], format = "-l{}"))
+
+    return flags
+
+def get_framework_search_path_flags(ctx: AnalysisContext) -> cmd_args:
+    if not _has_darwin_linker(ctx):
+        return cmd_args()
+
+    validate_sdk_frameworks(ctx.attrs.frameworks)
+    unresolved_framework_dirs = _get_non_sdk_unresolved_framework_directories(ctx.attrs.frameworks)
+    expanded_framework_dirs = _expand_sdk_framework_paths(ctx, unresolved_framework_dirs)
+    return _get_framework_search_path_flags(expanded_framework_dirs)
+
+def _get_framework_search_path_flags(frameworks: list[cmd_args]) -> cmd_args:
+    flags = cmd_args()
+    for directory in frameworks:
+        flags.add(cmd_args(directory, format = "-F{}"))
+
+    return flags
+
+def _get_non_sdk_unresolved_framework_directories(frameworks: typing.Iterable) -> set[str]:
+    # We don't want to include SDK directories as those are already added via `isysroot` flag in toolchain definition.
+    # Adding those directly via `-F` will break building Catalyst applications as frameworks from support directory
+    # won't be found and those for macOS platform will be used.
+    directories = set()
+    for framework in frameworks:
+        directory = _non_sdk_unresolved_framework_directory(framework)
+        if directory:
+            directories.add(directory)
+
+    return directories
+
+def to_framework_name(framework_path: str) -> str:
+    name, ext = paths.split_extension(paths.basename(framework_path))
+    expect(ext == ".framework", "framework `{}` missing `.framework` suffix", framework_path)
+    return name
+
+def _library_name(library: str) -> str:
+    if ":" in library:
+        fail("Invalid library: {}. Use the field 'linker_flags' with $(location ) macro if you want to pass in a BUCK target for libraries.".format(library))
+
+    name = paths.basename(library)
+    if not name.startswith("lib"):
+        fail("unexpected library: {}".format(library))
+    return paths.split_extension(name[3:])[0]
+
+def _expand_sdk_framework_paths(ctx: AnalysisContext, unresolved_framework_paths: set[str]) -> list[cmd_args]:
+    # When _apple_toolchain is not available (e.g., cxx_library used as apple_library swap),
+    # we cannot expand $PLATFORM_DIR or $SDKROOT paths. Skip those paths gracefully.
+    if not hasattr(ctx.attrs, "_apple_toolchain"):
+        return [cmd_args(p) for p in unresolved_framework_paths if not p.startswith("$")]
+    return [_expand_sdk_framework_path(ctx, unresolved_framework_path) for unresolved_framework_path in unresolved_framework_paths]
+
+def _expand_sdk_framework_path(ctx: AnalysisContext, framework_path: str) -> cmd_args:
+    apple_toolchain_info = ctx.attrs._apple_toolchain[AppleToolchainInfo]
+    path_expansion_map = {
+        "$PLATFORM_DIR/": apple_toolchain_info.platform_path,
+        "$SDKROOT/": apple_toolchain_info.sdk_path,
+    }
+
+    for trailing_path_variable, path_value in path_expansion_map.items():
+        (before, separator, relative_path) = framework_path.partition(trailing_path_variable)
+        if separator == trailing_path_variable:
+            if len(before) > 0:
+                fail("Framework symbolic path not anchored at the beginning, tried expanding `{}`".format(framework_path))
+            if relative_path.count("$") > 0:
+                fail("Framework path contains multiple symbolic paths, tried expanding `{}`".format(framework_path))
+            if len(relative_path) == 0:
+                fail(
+                    "Framework symbolic path contains no relative path to expand, tried expanding `{}`, relative path: `{}`, before: `{}`, separator `{}`".format(
+                        framework_path, relative_path, before, separator
+                    )
+                )
+
+            return cmd_args([path_value, relative_path], delimiter = "/")
+
+    if framework_path.find("$") == 0:
+        fail("Failed to expand framework path: {}".format(framework_path))
+
+    return cmd_args(framework_path)
+
+def _non_sdk_unresolved_framework_directory(framework_path: str) -> [str, None]:
+    # We must only drop any framework paths that are part of the implicit
+    # framework search paths in the linker + compiler, all other paths
+    # must be expanded and included as part of the command.
+    for implicit_search_path in _IMPLICIT_SDKROOT_FRAMEWORK_SEARCH_PATHS:
+        if framework_path.find(implicit_search_path) == 0:
+            return None
+    return paths.dirname(framework_path)
+
+def apple_build_link_args_with_deduped_flags(
+    ctx: AnalysisContext,
+    deps_merged_link_infos: list[MergedLinkInfo],
+    frameworks_linkable: [FrameworksLinkable, None],
+    link_strategy: LinkStrategy,
+    transformation_spec_context: TransformationSpecContext | None,
+    swiftmodule_linkable: [SwiftmoduleLinkable, None] = None,
+    prefer_stripped: bool = False,
+) -> LinkArgs:
+    if _has_darwin_linker(ctx):
+        frameworks_linkables = [x.frameworks[link_strategy] for x in deps_merged_link_infos] + [frameworks_linkable]
+        swiftmodule_linkables = [x.swiftmodules[link_strategy] for x in deps_merged_link_infos] + [swiftmodule_linkable]
+        link_info = _apple_link_info_from_linkables(
+            ctx,
+            frameworks_linkables,
+            swiftmodule_linkables,
+        )
+    else:
+        link_info = None
+
+    return get_link_args_for_strategy(
+        ctx.actions,
+        ctx.label,
+        get_cxx_toolchain_info(ctx).linker_info,
+        deps_merged_link_infos,
+        link_strategy,
+        prefer_stripped,
+        transformation_spec_context,
+        additional_link_info = link_info,
+    )
+
+def apple_get_link_info_by_deduping_link_infos(
+    ctx: AnalysisContext,
+    infos: list[[LinkInfo, None]],
+    framework_linkable: [FrameworksLinkable, None] = None,
+    swiftmodule_linkable: [SwiftmoduleLinkable, None] = None,
+) -> [LinkInfo, None]:
+    if not _has_darwin_linker(ctx):
+        return None
+
+    # When building a framework or executable, all frameworks used by the statically-linked
+    # deps in the subtree need to be linked.
+    #
+    # Without deduping, we've seen the linking step fail because the argsfile
+    # exceeds the acceptable size by the linker.
+    framework_linkables = _extract_framework_linkables(infos)
+    if framework_linkable:
+        framework_linkables.append(framework_linkable)
+
+    swiftmodule_linkables = extract_swiftmodule_linkables(infos)
+    swiftmodule_linkables.append(swiftmodule_linkable)
+
+    return _apple_link_info_from_linkables(ctx, framework_linkables, swiftmodule_linkables)
+
+def _extract_framework_linkables(link_infos: [list[LinkInfo], None]) -> list[FrameworksLinkable]:
+    linkables = []
+    for merged in link_infos:
+        for linkable in merged.linkables:
+            if isinstance(linkable, FrameworksLinkable):
+                linkables.append(linkable)
+
+    return linkables
+
+def _apple_link_info_from_linkables(
+    ctx: AnalysisContext, framework_linkables: list[[FrameworksLinkable, None]], swiftmodule_linkables: list[[SwiftmoduleLinkable, None]] = []
+) -> [LinkInfo, None]:
+    """
+    Returns a LinkInfo for the frameworks, swiftmodules, and swiftruntimes or None if there's none of those.
+    """
+    framework_link_args = _get_apple_frameworks_linker_flags(ctx, framework_linkables)
+    sdk_swift_module_link_args = get_swiftmodule_linker_flags(ctx, merge_swiftmodule_linkables(ctx, swiftmodule_linkables))
+
+    return (
+        LinkInfo(
+            pre_flags = [framework_link_args, sdk_swift_module_link_args],
+        )
+        if (framework_link_args or sdk_swift_module_link_args)
+        else None
+    )
diff --git a/buck2/prelude/apple/apple_info_plist.bzl b/buck2/prelude/apple/apple_info_plist.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_info_plist.bzl
@@ -0,0 +1,223 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":apple_bundle_destination.bzl", "AppleBundleDestination")
+load(":apple_bundle_part.bzl", "AppleBundlePart")
+load(":apple_bundle_utility.bzl", "get_bundle_min_target_version", "get_default_binary_dep", "get_product_name")
+load(":apple_sdk.bzl", "get_apple_sdk_name")
+load(
+    ":apple_sdk_metadata.bzl",
+    "AppleSdkMetadata",  # @unused Used as a type
+    "MacOSXCatalystSdkMetadata",
+    "MacOSXSdkMetadata",
+    "WatchOSSdkMetadata",
+    "WatchSimulatorSdkMetadata",
+    "get_apple_sdk_metadata_for_sdk_name",
+)
+load(":apple_target_sdk_version.bzl", "get_platform_name_for_sdk", "get_platform_version_for_sdk_version")
+load(":apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")
+
+UpdateOperations = enum("set", "insert")
+MergeOperations = enum("merge")
+RestrictedMergeOperations = enum("copy")
+
+def process_info_plist(ctx: AnalysisContext, override_input: Artifact | None) -> AppleBundlePart:
+    input = _preprocess_info_plist(ctx)
+    output = ctx.actions.declare_output("Info.plist", has_content_based_path = False)
+    additional_keys = _additional_keys_as_json_file(ctx)
+    override_keys = _override_keys_as_json_file(ctx)
+    process_plist(
+        ctx = ctx,
+        input = input,
+        output = output.as_output(),
+        override_input = override_input,
+        additional_keys = additional_keys,
+        override_keys = override_keys,
+    )
+    return AppleBundlePart(source = output, destination = AppleBundleDestination("metadata"))
+
+def _get_plist_run_options() -> dict[str, bool]:
+    return {
+        # Output is deterministic, so can be cached
+        "allow_cache_upload": True,
+        # plist generation is cheap and fast, RE network overhead not worth it
+        "prefer_local": True,
+    }
+
+def _preprocess_info_plist(ctx: AnalysisContext) -> Artifact:
+    input = ctx.attrs.info_plist
+    output = ctx.actions.declare_output("PreprocessedInfo.plist", has_content_based_path = False)
+    substitutions_json = _plist_substitutions_as_json_file(ctx)
+    apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]
+    processor = apple_tools.info_plist_processor
+    command = cmd_args([
+        processor,
+        "preprocess",
+        "--input",
+        input,
+        "--output",
+        output.as_output(),
+        "--product-name",
+        get_product_name(ctx),
+    ])
+    if substitutions_json != None:
+        command.add(["--substitutions-json", substitutions_json])
+    if getattr(ctx.attrs, "enforce_minimum_os_plist_key", False):
+        sdk_name = get_apple_sdk_name(ctx)
+        sdk_metadata = get_apple_sdk_metadata_for_sdk_name(sdk_name)
+        command.add(["--enforce-minimum-os-plist-key", sdk_metadata.min_version_plist_info_key])
+
+    ctx.actions.run(command, category = "apple_preprocess_info_plist", **_get_plist_run_options())
+    return output
+
+def _plist_substitutions_as_json_file(ctx: AnalysisContext) -> Artifact | None:
+    info_plist_substitutions = ctx.attrs.info_plist_substitutions
+    if not info_plist_substitutions:
+        return None
+
+    substitutions_json = ctx.actions.write_json("plist_substitutions.json", info_plist_substitutions, has_content_based_path = False)
+    return substitutions_json
+
+def process_plist(
+    ctx: AnalysisContext,
+    input: Artifact,
+    output: OutputArtifact,
+    override_input: Artifact | None = None,
+    additional_keys: Artifact | None = None,
+    override_keys: Artifact | None = None,
+    action_id: [str, None] = None,
+):
+    apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]
+    processor = apple_tools.info_plist_processor
+    override_input_arguments = ["--override-input", override_input] if override_input != None else []
+    additional_keys_arguments = ["--additional-keys", additional_keys] if additional_keys != None else []
+    override_keys_arguments = ["--override-keys", override_keys] if override_keys != None else []
+    command = cmd_args(
+        [
+            processor,
+            "process",
+            "--input",
+            input,
+            "--output",
+            output,
+        ]
+        + override_input_arguments
+        + additional_keys_arguments
+        + override_keys_arguments
+    )
+    ctx.actions.run(command, category = "apple_process_info_plist", identifier = action_id or input.basename, **_get_plist_run_options())
+
+def _additional_keys_as_json_file(ctx: AnalysisContext) -> Artifact:
+    additional_keys = _info_plist_additional_keys(ctx)
+    return ctx.actions.write_json("plist_additional.json", additional_keys, has_content_based_path = False)
+
+def _info_plist_additional_keys(ctx: AnalysisContext) -> dict[str, typing.Any]:
+    sdk_name = get_apple_sdk_name(ctx)
+    platform_name = get_platform_name_for_sdk(sdk_name)
+    sdk_metadata = get_apple_sdk_metadata_for_sdk_name(sdk_name)
+    result = _extra_mac_info_plist_keys(sdk_metadata, ctx.attrs.extension)
+    result["CFBundleSupportedPlatforms"] = sdk_metadata.info_plist_supported_platforms_values
+    result["DTPlatformName"] = platform_name
+    sdk_version = ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_version
+    if sdk_version:
+        platform_version = get_platform_version_for_sdk_version(
+            sdk_name = sdk_name,
+            sdk_version = sdk_version,
+        )
+        result["DTPlatformVersion"] = platform_version
+        result["DTSDKName"] = platform_name + platform_version
+    sdk_build_version = ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_build_version
+    if sdk_build_version:
+        result["DTPlatformBuild"] = sdk_build_version
+        result["DTSDKBuild"] = sdk_build_version
+    xcode_build_version = ctx.attrs._apple_toolchain[AppleToolchainInfo].xcode_build_version
+    if xcode_build_version:
+        result["DTXcodeBuild"] = xcode_build_version
+    xcode_version = ctx.attrs._apple_toolchain[AppleToolchainInfo].xcode_version
+    if xcode_version:
+        result["DTXcode"] = xcode_version
+    result[sdk_metadata.min_version_plist_info_key] = get_platform_version_for_sdk_version(
+        sdk_name = sdk_name,
+        sdk_version = get_bundle_min_target_version(ctx, get_default_binary_dep(ctx.attrs.binary)),
+    )
+
+    identify_build_system = ctx.attrs._info_plist_identify_build_system_default
+    if ctx.attrs.info_plist_identify_build_system != None:
+        identify_build_system = ctx.attrs.info_plist_identify_build_system
+    if identify_build_system and ctx.attrs.extension == "app":
+        # Only top-level .app bundle will contain special key.
+        result["FBBuck2"] = True
+
+    return result
+
+def _extra_mac_info_plist_keys(sdk_metadata: AppleSdkMetadata, extension: str) -> dict[str, typing.Any]:
+    if sdk_metadata.name == MacOSXSdkMetadata.name and extension != "xpc":
+        return {
+            "NSHighResolutionCapable": True,
+            "NSSupportsAutomaticGraphicsSwitching": True,
+        }
+    else:
+        return {}
+
+def _override_keys_as_json_file(ctx: AnalysisContext) -> Artifact:
+    override_keys = _info_plist_override_keys(ctx)
+    return ctx.actions.write_json("plist_override.json", override_keys, has_content_based_path = False)
+
+def _info_plist_override_keys(ctx: AnalysisContext) -> dict[str, typing.Any]:
+    sdk_name = get_apple_sdk_name(ctx)
+    result = {}
+    if sdk_name == MacOSXSdkMetadata.name:
+        if ctx.attrs.extension != "xpc":
+            result["LSRequiresIPhoneOS"] = False
+    elif sdk_name in [WatchOSSdkMetadata.name, WatchSimulatorSdkMetadata.name]:
+        result["UIDeviceFamily"] = [4]
+        result["WKApplication"] = True
+    elif sdk_name not in [MacOSXCatalystSdkMetadata.name]:
+        result["LSRequiresIPhoneOS"] = True
+    return result
+
+def apple_info_plist_impl(ctx: AnalysisContext) -> list[Provider]:
+    """
+    Implementation for the apple_info_plist rule.
+
+    This rule takes a source plist file and processes it to create an output plist.
+    """
+    apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]
+    processor = apple_tools.info_plist_processor
+
+    input_plist = ctx.attrs.src
+    output_plist = ctx.actions.declare_output("Info.plist", has_content_based_path = False)
+
+    # Basic plist processing command
+    command = cmd_args([
+        processor,
+        "process",
+        "--input",
+        input_plist,
+        "--output",
+        output_plist.as_output(),
+    ])
+
+    if ctx.attrs.xml:
+        command = cmd_args(command, ["--output-xml"])
+
+    # Add mutations if provided
+    if ctx.attrs.mutations:
+        mutations_file = ctx.actions.write_json("mutations.json", ctx.attrs.mutations, has_content_based_path = False)
+        command.add("--mutations")
+        command.add(mutations_file)
+        for mutation in ctx.attrs.mutations:
+            operation = mutation[0]
+            if operation in MergeOperations.values() or operation in RestrictedMergeOperations.values():
+                command.add(cmd_args(hidden = mutation[1]))
+
+    ctx.actions.run(command, category = "apple_info_plist", identifier = input_plist.basename, **_get_plist_run_options())
+
+    return [
+        DefaultInfo(default_output = output_plist),
+    ]
diff --git a/buck2/prelude/apple/apple_info_plist_substitutions_parsing.bzl b/buck2/prelude/apple/apple_info_plist_substitutions_parsing.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_info_plist_substitutions_parsing.bzl
@@ -0,0 +1,68 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:selects.bzl", "selects")
+
+# `apple_bundle.info_plist_substitutions` might contain `CODE_SIGN_ENTITLEMENTS` key which (as per v1 documentation):
+#
+# > Code signing will embed entitlements pointed to by the entitlements_file arg in the bundle's apple_binary.
+# > This is the preferred way to specify entitlements when building with Buck.
+# > If the entitlements file is not present, it falls back to the CODE_SIGN_ENTITLEMENTS entry in info_plist_substitutions.
+#
+# In order to properly depend on this fallback entitlements file (and manipulate it) we have to convert this text entry into the source artifact.
+# We only can do that on macro layer, hence the purpose of the following code.
+
+_SOURCE_ROOT_PREFIX = "$(SOURCE_ROOT)/"
+_CODE_SIGN_ENTITLEMENTS_KEY = "CODE_SIGN_ENTITLEMENTS"
+
+def _find_first_variable(string: str) -> [(str, (str, str)), None]:
+    """
+    If variable like `$(FOO)` is not found in `string` returns `None`, else returns tuple
+    with first element equal to variable name (e.g. `FOO`) and second element equal to tuple
+    of part before and after this variable.
+    """
+    expansion_start = "$("
+    expansion_end = ")"
+    variable_start = string.find(expansion_start)
+    if variable_start == -1:
+        return None
+    variable_end = string.find(expansion_end, variable_start)
+    if variable_end == -1:
+        fail("Expected variable expansion in string: `{}`".format(string))
+    variable = string[variable_start + len(expansion_start) : variable_end - len(expansion_end) + 1]
+    prefix = string[:variable_start]
+    suffix = string[variable_end + 1 :]
+    return (variable, (prefix, suffix))
+
+def _expand_codesign_entitlements_path(info_plist_substitutions: dict[str, str | Select], path: str) -> str:
+    path = path.strip()
+    for _ in range(100):
+        if path.startswith(_SOURCE_ROOT_PREFIX):
+            path = path[len(_SOURCE_ROOT_PREFIX) :]
+        maybe_variable = _find_first_variable(path)
+        if not maybe_variable:
+            return path
+        (key, (prefix, suffix)) = maybe_variable
+        maybe_value = info_plist_substitutions.get(key)
+        if not maybe_value:
+            fail("Expected to find value for `{}` in `info_plist_substitutions` dictionary `{}`".format(key, info_plist_substitutions))
+        path = prefix + maybe_value + suffix
+    fail("Too many iteration (loop might be present) to expand `{}` with substitutions `{}`".format(path, info_plist_substitutions))
+
+def parse_codesign_entitlements(info_plist_substitutions: [dict | Select, None]) -> [str | Select, None]:
+    if not info_plist_substitutions:
+        return None
+    return selects.apply(info_plist_substitutions, _parse_codesign_entitlements)
+
+def _parse_codesign_entitlements(info_plist_substitutions: [dict, None]) -> [str | Select, None]:
+    if not info_plist_substitutions:
+        return None
+    maybe_path = info_plist_substitutions.get(_CODE_SIGN_ENTITLEMENTS_KEY)
+    if not maybe_path:
+        return None
+    return selects.apply(maybe_path, lambda maybe_path: _expand_codesign_entitlements_path(info_plist_substitutions, maybe_path))
diff --git a/buck2/prelude/apple/apple_library.bzl b/buck2/prelude/apple/apple_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_library.bzl
@@ -0,0 +1,771 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "make_artifact_tset",
+    "project_artifacts",
+)
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")
+load("@prelude//apple:apple_dsym.bzl", "DSYM_SUBTARGET", "get_apple_dsym")
+load("@prelude//apple:apple_stripping.bzl", "apple_strip_args")
+load("@prelude//apple:xcassets_asset_symbols.bzl", "meta_xcassets_asset_symbol_usage_providers_and_subtargets")
+# @oss-disable[end= ]: load("@prelude//apple/meta_only:apple_library_meta_validation.bzl", "apple_library_validate_for_meta_restrictions")
+# @oss-disable[end= ]: load(
+    # @oss-disable[end= ]: "@prelude//apple/meta_only:linker_outputs.bzl",
+    # @oss-disable[end= ]: "extra_distributed_thin_lto_opt_outputs_merger",
+    # @oss-disable[end= ]: "get_extra_linker_output_flags",
+    # @oss-disable[end= ]: "get_extra_linker_outputs",
+# @oss-disable[end= ]: )
+load(
+    "@prelude//apple/mockingbird:mockingbird_types.bzl",
+    "MockingbirdLibraryInfo",
+    "MockingbirdLibraryInfoTSet",
+    "MockingbirdLibraryRecord",
+    "MockingbirdSourcesInfo",
+    "MockingbirdTargetType",
+)
+load(
+    "@prelude//apple/swift:swift_compilation.bzl",
+    "SwiftLibraryForDistributionOutput",  # @unused Used as a type
+    "compile_swift",
+    "get_swift_anonymous_targets",
+    "get_swift_debug_infos",
+    "get_swift_dependency_info",
+    "get_swift_pcm_uncompile_info",
+    "get_swiftmodule_linkable",
+)
+load("@prelude//apple/swift:swift_helpers.bzl", "uses_explicit_modules")
+load(
+    "@prelude//apple/swift:swift_incremental_support.bzl",
+    "get_uses_content_based_paths",
+)
+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftToolchainInfo")
+load("@prelude//apple/swift:swift_types.bzl", "SWIFT_EXTENSION")
+load(
+    "@prelude//cxx:argsfiles.bzl",
+    "CompileArgsfile",  # @unused Used as a type
+    "CompileArgsfiles",
+)
+load(
+    "@prelude//cxx:compile_types.bzl",
+    "AsmExtensions",
+    "CxxSrcCompileCommand",  # @unused Used as a type
+    "DeclaredIndexStore",
+    "IndexStoreFactory",
+)
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_library.bzl",
+    "CxxLibraryOutput",  # @unused Used as a type
+    "cxx_library_parameterized",
+)
+load(
+    "@prelude//cxx:cxx_library_utility.bzl",
+    "cxx_attr_deps",
+    "cxx_attr_exported_deps",
+    "cxx_attr_link_style",
+)
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",  # @unused Used as a type
+    "get_srcs_with_flags",
+)
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",  # @unused Used as type
+    "LinkerType",
+)
+load(
+    "@prelude//cxx:cxx_types.bzl",
+    "CxxRuleAdditionalParams",
+    "CxxRuleConstructorParams",
+    "CxxRuleProviderParams",
+    "CxxRuleSubTargetParams",
+    "xcode_data_enabled",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load("@prelude//cxx:headers.bzl", "cxx_attr_exported_headers", "cxx_attr_headers_list")
+load(
+    "@prelude//cxx:link_groups.bzl",
+    "get_link_group_info",
+)
+load("@prelude//cxx:link_types.bzl", "ExtraLinkerOutputCategory")
+load(
+    "@prelude//cxx:linker.bzl",
+    "LINKERS",
+    "SharedLibraryFlagOverrides",
+)
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorInfo",  # @unused Used as a type
+    "EMPTY_CPREPROCESSOR",
+)
+load("@prelude//cxx:target_sdk_version.bzl", "get_unversioned_target_triple")
+load("@prelude//graphql:graphql.bzl", "graphql_providers")
+load(
+    "@prelude//linking:link_info.bzl",
+    "ExtraLinkerOutputs",
+    "LibOutputStyle",
+    "to_link_strategy",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",
+)
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load(
+    "@prelude//utils:utils.bzl",
+    "filter_and_map_idx",
+)
+load(":apple_bundle_types.bzl", "AppleBundleLinkerMapInfo", "AppleMinDeploymentVersionInfo")
+load(":apple_error_handler.bzl", "apple_build_error_handler", "cxx_error_deserializer", "cxx_error_handler")
+load(":apple_frameworks.bzl", "get_framework_search_path_flags")
+load(":apple_library_types.bzl", "AppleLibraryInfo")
+load(":apple_modular_utility.bzl", "MODULE_CACHE_PATH")
+load(":apple_rpaths.bzl", "get_rpath_flags_for_library")
+load(":apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")
+load(":apple_utility.bzl", "get_apple_cxx_headers_layout", "get_apple_stripped_attr_value_with_default_fallback", "get_module_name", "target_stats_header_name")
+load(
+    ":debug.bzl",
+    "AppleDebuggableInfo",
+    "DEBUGINFO_SUBTARGET",
+)
+load(":modulemap.bzl", "create_modulemap")
+load(":resource_groups.bzl", "create_resource_graph")
+load(":xcode.bzl", "apple_populate_xcode_attributes")
+load(":xctest_swift_support.bzl", "xctest_swift_support_info")
+
+AppleSharedLibraryMachOFileType = enum(
+    # dynamically bound shared library file
+    "dylib",
+    # dynamically bound bundle file aka Mach-O bundle
+    "bundle",
+)
+
+AppleLibraryAdditionalParams = record(
+    # Name of the top level rule utilizing the apple_library rule.
+    rule_type = str,
+    # Extra flags to be passed to the linker.
+    extra_exported_link_flags = field(list[ArgLike], []),
+    # Extra flags to be passed to the Swift compiler.
+    extra_swift_compiler_flags = field(list[ArgLike], []),
+    # Linker flags that tell the linker to create shared libraries, overriding the default shared library flags.
+    # e.g. when building Apple tests, we want to link with `-bundle` instead of `-shared` to allow
+    # linking against the bundle loader.
+    shared_library_flags = field([SharedLibraryFlagOverrides, None], None),
+    # Function to use for setting Xcode attributes for the Xcode data sub target.
+    populate_xcode_attributes_func = field(typing.Callable, apple_populate_xcode_attributes),
+    # Define which sub targets to generate.
+    generate_sub_targets = field(CxxRuleSubTargetParams, CxxRuleSubTargetParams()),
+    # Define which providers to generate.
+    generate_providers = field(CxxRuleProviderParams, CxxRuleProviderParams()),
+    # Forces link group linking logic, even when there's no mapping. Link group linking
+    # without a mapping is equivalent to statically linking the whole transitive dep graph.
+    force_link_group_linking = field(bool, False),
+)
+
+AppleLibraryForDistributionInfo = provider(
+    fields = {
+        "module_name": str,
+        "private_swiftinterface": [Artifact, None],
+        "provider_type": provider_field(str, default = "AppleLibraryForDistributionInfo"),
+        "swiftdoc": [Artifact, None],
+        "swiftinterface": [Artifact, None],
+        "target_triple": str,
+    },
+)
+
+def apple_library_impl(ctx: AnalysisContext) -> [Promise, list[Provider]]:
+    # @oss-disable[end= ]: apple_library_validate_for_meta_restrictions(ctx)
+
+    def get_apple_library_providers(deps_providers) -> list[Provider]:
+        shared_type = AppleSharedLibraryMachOFileType(ctx.attrs.shared_library_macho_file_type)
+        if shared_type == AppleSharedLibraryMachOFileType("bundle"):
+            shared_library_flags_overrides = SharedLibraryFlagOverrides(
+                # When `-bundle` is used we can't use the `-install_name` args, thus we keep this field empty.
+                shared_library_name_linker_flags_format = [],
+                shared_library_flags = ["-bundle"] + get_rpath_flags_for_library(ctx),
+            )
+        elif shared_type == AppleSharedLibraryMachOFileType("dylib"):
+            # Copying the default value and appending from cxx/linker.bzl
+            linker = LINKERS[LinkerType("darwin")]
+            shared_library_flags_overrides = SharedLibraryFlagOverrides(
+                shared_library_name_linker_flags_format = linker.shared_library_name_linker_flags_format,
+                shared_library_flags = linker.shared_library_flags + get_rpath_flags_for_library(ctx),
+            )
+        else:
+            fail("Unsupported `shared_library_macho_file_type` attribute value: `{}`".format(shared_type))
+        constructor_params = apple_library_rule_constructor_params_and_swift_providers(
+            ctx,
+            AppleLibraryAdditionalParams(
+                rule_type = "apple_library",
+                generate_sub_targets = CxxRuleSubTargetParams(xcode_data = xcode_data_enabled()),
+                generate_providers = CxxRuleProviderParams(
+                    java_packaging_info = False,
+                    java_global_code_info = False,
+                    android_packageable_info = False,
+                    omnibus_root = False,
+                    # We generate a provider on our own, disable to avoid several providers of same type.
+                    cxx_resources_as_apple_resources = False,
+                    transitive_diagnostics = True,
+                ),
+                shared_library_flags = shared_library_flags_overrides,
+            ),
+            deps_providers,
+        )
+        output = cxx_library_parameterized(ctx, constructor_params)
+
+        return output.providers + _make_mockingbird_library_info_provider(ctx) + graphql_providers(ctx)
+
+    if uses_explicit_modules(ctx):
+        providers = get_swift_anonymous_targets(ctx, get_apple_library_providers)
+    else:
+        providers = get_apple_library_providers([])
+    if hasattr(ctx.attrs, "distribution_dep"):
+        # Rule is apple_library_for_distribution
+        providers = _create_apple_library_for_distribution_providers(ctx, providers)
+    return providers
+
+def _declare_index_store(actions: AnalysisActions, src_compile_cmd: CxxSrcCompileCommand) -> DeclaredIndexStore | None:
+    """
+    Declare index store output artifact upfront during analysis.
+    This is called before the dynamic action is created.
+    """
+    if src_compile_cmd.src.extension in AsmExtensions.values():
+        return None
+
+    identifier = src_compile_cmd.src.short_path
+    if src_compile_cmd.index != None:
+        # Add a unique postfix if we have duplicate source files with different flags
+        identifier = identifier + "_" + str(src_compile_cmd.index)
+    filename_base = identifier
+
+    index_store = actions.declare_output(paths.join("__indexstore__", filename_base, "index_store"), dir = True, has_content_based_path = False)
+    return DeclaredIndexStore(
+        output = index_store,
+        filename_base = filename_base,
+    )
+
+def _compile_index_store(
+    actions: AnalysisActions, target_label: Label, index_store_output: OutputArtifact, filename_base: str, toolchain: CxxToolchainInfo, compile_cmd: cmd_args
+) -> None:
+    """
+    Compile index store inside the dynamic action.
+    This is called after outputs are declared, during execution.
+    """
+    identifier = filename_base + " (index_store)"
+
+    # Use remap_cwd.py to set -ffile-prefix-map, so we have paths relative to the
+    # working directory.
+    cmd = cmd_args(toolchain.internal_tools.remap_cwd)
+    cmd.add(compile_cmd)
+
+    # We use `-fsyntax-only` flag, so output will be not generated.
+    # The output here is used for the identifier of the index unit file
+    output_name = paths.join(
+        target_label.cell,
+        target_label.package,
+        target_label.name,
+        "{}.{}".format(filename_base, toolchain.linker_info.object_file_extension),
+    )
+    cmd.add(["-o", output_name])
+
+    # Haven't use `-fdebug-prefix-map` for now, will use index-import to remap the path. But it's not ideal.
+    cmd.add([
+        "-fsyntax-only",
+        "-index-ignore-system-symbols",
+        "-index-store-path",
+        index_store_output,
+    ])
+
+    actions.run(
+        cmd,
+        category = "apple_cxx_index_store",
+        identifier = identifier,
+        allow_cache_upload = False,
+        local_only = True,
+    )
+
+def _make_apple_library_for_distribution_info_provider(
+    ctx: AnalysisContext, swift_library_for_distribution: [None, SwiftLibraryForDistributionOutput]
+) -> list[AppleLibraryForDistributionInfo]:
+    return [
+        AppleLibraryForDistributionInfo(
+            target_triple = get_unversioned_target_triple(ctx).replace("macosx", "macos"),
+            swiftinterface = swift_library_for_distribution.swiftinterface if swift_library_for_distribution else None,
+            private_swiftinterface = swift_library_for_distribution.private_swiftinterface if swift_library_for_distribution else None,
+            swiftdoc = swift_library_for_distribution.swiftdoc if swift_library_for_distribution else None,
+            module_name = get_module_name(ctx),
+        )
+    ]
+
+def _make_apple_library_info_provider(ctx: AnalysisContext, swift_header: [None, Artifact]) -> list[AppleLibraryInfo]:
+    public_framework_headers = cxx_attr_headers_list(ctx, ctx.attrs.public_framework_headers, get_apple_cxx_headers_layout(ctx))
+    all_deps = cxx_attr_deps(ctx) + cxx_attr_exported_deps(ctx)
+    apple_library_infos = filter(None, [dep.get(AppleLibraryInfo) for dep in all_deps])
+
+    public_framework_header_tset = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        artifacts = [header.artifact for header in public_framework_headers],
+        children = [apple_library.public_framework_headers for apple_library in apple_library_infos],
+    )
+
+    return [
+        AppleLibraryInfo(
+            public_framework_headers = public_framework_header_tset,
+            swift_header = swift_header,
+            target = ctx.label,
+            labels = ctx.attrs.labels,
+        )
+    ]
+
+def _make_mockingbird_library_info_provider(ctx: AnalysisContext) -> list[MockingbirdLibraryInfo]:
+    _, swift_sources = _filter_swift_srcs(ctx)
+
+    if len(swift_sources) == 0:
+        return []
+
+    mockingbird_module_name = get_module_name(ctx)
+    deps_mockingbird_infos = filter(None, [dep.get(MockingbirdLibraryInfo) for dep in cxx_attr_deps(ctx)])
+    exported_deps_mockingbird_infos = filter(None, [dep.get(MockingbirdLibraryInfo) for dep in cxx_attr_exported_deps(ctx)])
+
+    children = []
+    dep_module_names = []
+    exported_dep_module_names = []
+    for info in deps_mockingbird_infos:
+        dep_module_names.append(info.name)
+        children.append(info.tset)
+
+    for info in exported_deps_mockingbird_infos:
+        exported_dep_module_names.append(info.name)
+        children.append(info.tset)
+
+    mockingbird_srcs_folder = ctx.actions.declare_output("mockingbird_srcs_" + ctx.attrs.name, dir = True, has_content_based_path = False)
+
+    ctx.actions.symlinked_dir(
+        mockingbird_srcs_folder,
+        {source.file.basename: source.file for source in swift_sources},
+    )
+
+    mockingbird_record = MockingbirdLibraryRecord(
+        name = mockingbird_module_name,
+        srcs = [src.file for src in swift_sources],
+        dep_names = dep_module_names,
+        exported_dep_names = exported_dep_module_names,
+        type = MockingbirdTargetType("library"),
+        src_dir = mockingbird_srcs_folder,
+    )
+
+    mockingbird_tset = ctx.actions.tset(MockingbirdLibraryInfoTSet, value = mockingbird_record, children = children)
+
+    return [
+        MockingbirdLibraryInfo(
+            name = mockingbird_module_name,
+            tset = mockingbird_tset,
+        )
+    ]
+
+def apple_library_rule_constructor_params_and_swift_providers(
+    ctx: AnalysisContext, params: AppleLibraryAdditionalParams, deps_providers: list = [], is_test_target: bool = False
+) -> CxxRuleConstructorParams:
+    mockingbird_gen_sources = []
+    if not "dummy_library" in ctx.attrs.labels:
+        for dep in cxx_attr_deps(ctx) + cxx_attr_exported_deps(ctx):
+            if MockingbirdSourcesInfo in dep:
+                for src in dep[MockingbirdSourcesInfo].srcs:
+                    mockingbird_gen_sources.append(src)
+
+    cxx_srcs, swift_srcs = _filter_swift_srcs(ctx, mockingbird_gen_sources)
+
+    header_layout = get_apple_cxx_headers_layout(ctx)
+    exported_hdrs = cxx_attr_exported_headers(ctx, header_layout)
+
+    module_name = get_module_name(ctx)
+
+    # First create a modulemap if necessary. This is required for importing
+    # ObjC code in Swift so must be done before Swift compilation.
+    if ctx.attrs.modular or swift_srcs:
+        modulemap_name = module_name
+        exported_modulemap_pre = (
+            create_modulemap(
+                ctx,
+                name = modulemap_name,
+                module_name = module_name,
+                headers = exported_hdrs,
+                swift_header = None,
+            )
+            if exported_hdrs
+            else None
+        )
+    else:
+        exported_modulemap_pre = None
+
+    framework_search_paths_flags = get_framework_search_path_flags(ctx)
+    swift_compile_result = compile_swift(
+        ctx,
+        swift_srcs,
+        True,  # parse_as_library
+        deps_providers,
+        module_name,
+        exported_hdrs,
+        exported_modulemap_pre,
+        framework_search_paths_flags,
+        params.extra_swift_compiler_flags,
+    )
+    swift_compile = swift_compile_result.swift_compilation
+    objc_swift_interface = swift_compile_result.objc_swift_interface
+    swift_object_files = swift_compile.object_files if swift_compile else []
+
+    swift_pre = EMPTY_CPREPROCESSOR
+    if swift_compile:
+        # If we have Swift we export the extended modulemap that includes
+        # the ObjC exported headers and the -Swift.h header.
+        exported_pre = swift_compile.exported_pre
+
+        # We also include the -Swift.h header to this libraries preprocessor
+        # info, so that we can import it unprefixed in this module.
+        swift_pre = swift_compile.pre
+    elif exported_modulemap_pre:
+        # Otherwise if this library is modular we export a modulemap of
+        # the ObjC exported headers.
+        exported_pre = exported_modulemap_pre
+    else:
+        exported_pre = None
+
+    swift_dependency_info = swift_compile.dependency_info if swift_compile else get_swift_dependency_info(ctx, None, deps_providers, False)
+    swift_debug_info = get_swift_debug_infos(
+        ctx,
+        swift_dependency_info,
+        swift_compile,
+    )
+
+    swift_toolchain = ctx.attrs._apple_toolchain[SwiftToolchainInfo]
+    if swift_toolchain and swift_toolchain.supports_relative_resource_dir:
+        resource_dir_args = []
+    else:
+        # We have to use this hack to make compilation work when Clang modules
+        # are enabled and using toolchains that don't support relative resource
+        # directories correctly. The builtin headers will be embedded relative
+        # to the CWD, so need to add . to be located correctly.
+        resource_dir_args = ["-I."]
+
+    modular_pre = CPreprocessor(
+        uses_modules = ctx.attrs.uses_modules,
+        modular_args = [
+            "-fcxx-modules",
+            "-fmodules",
+            "-fmodule-name=" + get_module_name(ctx),
+            "-fmodules-cache-path=" + MODULE_CACHE_PATH,
+        ]
+        + resource_dir_args,
+    )
+
+    contains_swift_sources = bool(swift_srcs)
+    xctest_swift_support_provider = xctest_swift_support_info(ctx, contains_swift_sources, is_test_target)
+
+    def additional_providers_factory(propagated_exported_preprocessor_info: [CPreprocessorInfo, None]) -> list[Provider]:
+        # Expose `SwiftPCMUncompiledInfo` which represents the ObjC part of a target,
+        # if a target also has a Swift part, the provider will expose the generated `-Swift.h` header.
+        # This is used for Swift Explicit Modules, and allows compiling a PCM file out of the exported headers.
+        swift_pcm_uncompile_info = get_swift_pcm_uncompile_info(
+            ctx,
+            propagated_exported_preprocessor_info,
+            exported_pre,
+        )
+        providers = [swift_pcm_uncompile_info] if swift_pcm_uncompile_info else []
+        providers.append(swift_dependency_info)
+        providers.append(xctest_swift_support_provider)
+
+        return providers
+
+    validation_deps_outputs = get_validation_deps_outputs(ctx)
+    if swift_compile:
+        swift_objc_header = swift_compile.exported_swift_header
+        swift_library_for_distribution_output = swift_compile.swift_library_for_distribution_output
+    else:
+        swift_objc_header = None
+        swift_library_for_distribution_output = None
+
+    extra_apple_providers = []
+    if not is_test_target:
+        extra_apple_providers = _make_apple_library_info_provider(ctx, swift_objc_header) + _make_apple_library_for_distribution_info_provider(
+            ctx, swift_library_for_distribution_output
+        )
+    meta_xcassets_usage_providers, meta_xcassets_usage_subtargets = (
+        ([], {}) if is_test_target else meta_xcassets_asset_symbol_usage_providers_and_subtargets(ctx, cxx_srcs, swift_srcs)
+    )
+    extra_apple_providers += meta_xcassets_usage_providers
+
+    # Always provide a valid JSON object, so that tooling can depend on its existance
+    modulemap_info_json = {"modulemap": exported_pre.modulemap_artifact} if (exported_pre and exported_pre.modulemap_artifact) else {}
+    modulemap_info_json_file = ctx.actions.declare_output("modulemap-info.json", has_content_based_path = False)
+    modulemap_info_json_cmd_args = ctx.actions.write_json(modulemap_info_json_file, modulemap_info_json, with_inputs = True, pretty = True)
+    modulemap_info_providers = [DefaultInfo(default_output = modulemap_info_json_file, other_outputs = [modulemap_info_json_cmd_args])]
+
+    subtargets = {
+        "ast": [DefaultInfo(default_output = swift_compile_result.ast)],
+        "modulemap-info": modulemap_info_providers,
+        "objc-swift-interface": [objc_swift_interface],
+        "swift-compilation-database": [DefaultInfo(default_output = None)],
+        "swift-compile": [DefaultInfo(default_output = None)],
+        "swiftinterface": [DefaultInfo(default_output = swift_compile_result.swiftinterface)],
+        "swiftmodule": [DefaultInfo(default_output = None)],
+    }
+    subtargets.update(meta_xcassets_usage_subtargets)
+    if swift_compile and swift_compile.compiled_underlying_pcm_artifact:
+        subtargets["underlying-pcm"] = [DefaultInfo(default_output = swift_compile.compiled_underlying_pcm_artifact)]
+
+    if swift_compile:
+        subtargets["swift-compilation-database"] = [
+            DefaultInfo(
+                default_output = swift_compile.compilation_database.db,
+                other_outputs = [swift_compile.compilation_database.other_outputs],
+            ),
+        ]
+        subtargets["swift-compile"] = [
+            DefaultInfo(
+                default_output = swift_compile.object_files[0],
+                other_outputs = swift_compile.object_files[1:],
+            ),
+        ]
+
+        if swift_compile.output_map_artifact:
+            subtargets["swift-output-file-map"] = [DefaultInfo(default_output = swift_compile.output_map_artifact)]
+
+        if swift_compile.swift_module_map_artifact:
+            subtargets["swift-module-map"] = [DefaultInfo(default_output = swift_compile.swift_module_map_artifact)]
+
+        if swift_compile.swiftdeps:
+            subtargets["swiftdeps"] = [
+                DefaultInfo(
+                    default_output = swift_compile.swiftdeps[0],
+                    other_outputs = swift_compile.swiftdeps[1:],
+                ),
+            ]
+
+        subtargets["swiftmodule"] = [DefaultInfo(default_output = swift_compile.swiftmodule)]
+        subtargets["swift-objc-header"] = [DefaultInfo(default_output = swift_compile.exported_swift_header)]
+
+    # Always provide the subtarget, so that clients don't need to handle conditional existence
+    subtargets["swift.check"] = [DefaultInfo(default_output = swift_compile.typecheck_file if swift_compile else None)]
+
+    swift_sources_list = ctx.actions.write(
+        "swift-sources.txt",
+        [s.file for s in swift_srcs],
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+    subtargets["swift-sources"] = [DefaultInfo(default_output = swift_sources_list)]
+
+    link_strategy = to_link_strategy(cxx_attr_link_style(ctx))
+    link_group_info = get_link_group_info(
+        ctx,
+        filter_and_map_idx(LinkableGraph, cxx_attr_deps(ctx)),
+        link_strategy,
+    )
+
+    return CxxRuleConstructorParams(
+        rule_type = params.rule_type,
+        is_test = (params.rule_type == "apple_test"),
+        headers_layout = get_apple_cxx_headers_layout(ctx),
+        extra_exported_link_flags = params.extra_exported_link_flags,
+        extra_hidden = validation_deps_outputs,
+        extra_link_input = swift_object_files,
+        extra_link_input_has_external_debug_info = True,
+        extra_preprocessors = [swift_pre, modular_pre],
+        extra_exported_preprocessors = filter(None, [exported_pre]),
+        srcs = cxx_srcs,
+        target_stats_cycle_mode = "file",
+        target_stats_module_name = get_module_name(ctx),
+        target_stats_extra_srcs = {
+            target_stats_header_name(header): header.artifact for header in cxx_attr_headers_list(ctx, ctx.attrs.headers, header_layout) + exported_hdrs
+        },
+        target_stats_swift_dot = swift_compile.modularization_dependency_graph if swift_compile else None,
+        additional = CxxRuleAdditionalParams(
+            srcs = swift_srcs,
+            argsfiles = swift_compile.argsfiles if swift_compile else CompileArgsfiles(),
+            # We need to add any swift modules that we include in the link, as
+            # these will end up as `N_AST` entries that `dsymutil` will need to
+            # follow.
+            static_external_debug_info = swift_debug_info.static,
+            shared_external_debug_info = swift_debug_info.shared,
+            subtargets = subtargets,
+            additional_providers_factory = additional_providers_factory,
+        ),
+        build_empty_so = hasattr(ctx.attrs, "distribution_dep"),
+        output_style_sub_targets_and_providers_factory = _get_link_style_sub_targets_and_providers(
+            extra_providers = extra_apple_providers,
+        ),
+        shared_library_flags = params.shared_library_flags,
+        # apple_library's 'stripped' arg only applies to shared subtargets, or,
+        # targets with 'preferred_linkage = "shared"'
+        strip_executable = get_apple_stripped_attr_value_with_default_fallback(ctx),
+        strip_args_factory = apple_strip_args,
+        force_link_group_linking = params.force_link_group_linking,
+        cxx_populate_xcode_attributes_func = lambda local_ctx, **kwargs: _xcode_populate_attributes(
+            ctx = local_ctx, populate_xcode_attributes_func = params.populate_xcode_attributes_func, contains_swift_sources = contains_swift_sources, **kwargs
+        ),
+        generate_sub_targets = params.generate_sub_targets,
+        generate_providers = params.generate_providers,
+        # Some apple rules rely on `static` libs *not* following dependents.
+        link_groups_force_static_follows_dependents = False,
+        link_group_info = link_group_info,
+        extra_linker_outputs_factory = _get_extra_linker_outputs,
+        extra_linker_outputs_flags_factory = _get_extra_linker_outputs_flags,
+        extra_distributed_thin_lto_opt_outputs_merger = _extra_distributed_thin_lto_opt_outputs_merger,
+        swiftmodule_linkable = get_swiftmodule_linkable(swift_compile),
+        compiler_flags = ctx.attrs.compiler_flags,
+        lang_compiler_flags = ctx.attrs.lang_compiler_flags,
+        preprocessor_flags = ctx.attrs.preprocessor_flags,
+        lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,
+        swift_objc_header = swift_objc_header,
+        error_handler = cxx_error_handler if cxx_error_deserializer(ctx) else apple_build_error_handler,
+        index_store_factory = IndexStoreFactory(declare = _declare_index_store, compile = _compile_index_store),
+        index_stores = [swift_compile.index_store] if swift_compile else None,
+        modularization_dependency_graph = swift_compile.modularization_dependency_graph if swift_compile else None,
+        extra_transitive_diagnostics = [swift_compile.typecheck_file] if swift_compile else [],
+        extra_diagnostics = {"swift": swift_compile.typecheck_file} if swift_compile else None,
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),
+        precompiled_header = ctx.attrs.precompiled_header,
+        prefix_header = ctx.attrs.prefix_header,
+        use_content_based_paths = get_uses_content_based_paths(ctx),
+    )
+
+def _get_extra_linker_outputs(
+    ctx: AnalysisContext, extra_linker_output_category: ExtraLinkerOutputCategory = ExtraLinkerOutputCategory("produced-during-local-link")
+) -> ExtraLinkerOutputs:
+    _ = ctx  # buildifier: disable=unused-variable
+    # @oss-disable[end= ]: return get_extra_linker_outputs(ctx, extra_linker_output_category)
+    return ExtraLinkerOutputs() # @oss-enable
+
+def _get_extra_linker_outputs_flags(
+    ctx: AnalysisContext,
+    outputs: dict[str, Artifact],
+    extra_linker_output_category: ExtraLinkerOutputCategory = ExtraLinkerOutputCategory("produced-during-local-link"),
+) -> list[ArgLike]:
+    _ = ctx  # buildifier: disable=unused-variable
+    # @oss-disable[end= ]: return get_extra_linker_output_flags(ctx, outputs, extra_linker_output_category)
+    return [] # @oss-enable
+
+def _extra_distributed_thin_lto_opt_outputs_merger(ctx: AnalysisContext, outputs_to_bind: dict[str, Artifact], outputs_to_merge: list[dict[str, Artifact]]):
+    # @oss-disable[end= ]: return extra_distributed_thin_lto_opt_outputs_merger(ctx, outputs_to_bind, outputs_to_merge)
+    return # @oss-enable
+
+def _filter_swift_srcs(ctx: AnalysisContext, additional_srcs: list = []) -> (list[CxxSrcWithFlags], list[CxxSrcWithFlags]):
+    cxx_srcs = []
+    swift_srcs = []
+    for s in get_srcs_with_flags(ctx, additional_srcs):
+        if s.file.extension == SWIFT_EXTENSION:
+            swift_srcs.append(s)
+        else:
+            cxx_srcs.append(s)
+
+    return cxx_srcs, swift_srcs
+
+def _get_link_style_sub_targets_and_providers(extra_providers: list[Provider]) -> typing.Callable:
+    def get_link_style_sub_targets_impl(
+        output_style: LibOutputStyle, ctx: AnalysisContext, output: [CxxLibraryOutput, None]
+    ) -> (dict[str, list[Provider]], list[Provider]):
+        # We always propagate a resource graph regardless of link style or empty output
+        resource_graph = create_resource_graph(
+            ctx = ctx,
+            labels = ctx.attrs.labels,
+            deps = cxx_attr_deps(ctx),
+            exported_deps = cxx_attr_exported_deps(ctx),
+            # Shared libraries should not propagate their resources to rdeps,
+            # they should only be contained in their frameworks apple_bundle.
+            should_propagate = output_style != LibOutputStyle("shared_lib"),
+        )
+
+        if output_style != LibOutputStyle("shared_lib") or output == None:
+            static_providers = [resource_graph] + extra_providers
+            return ({}, static_providers)
+
+        min_version = get_min_deployment_version_for_node(ctx)
+        min_version_providers = [AppleMinDeploymentVersionInfo(version = min_version)]
+
+        debug_info = project_artifacts(
+            actions = ctx.actions,
+            tsets = output.external_debug_info,
+        )
+
+        if get_apple_stripped_attr_value_with_default_fallback(ctx):
+            dsym_executable = output.unstripped
+        else:
+            dsym_executable = output.default
+
+        dsym_artifact = get_apple_dsym(
+            ctx = ctx,
+            executable = dsym_executable,
+            debug_info = debug_info,
+            action_identifier = dsym_executable.short_path,
+        )
+        debug_info_artifacts_manifest = ctx.actions.write(
+            "debuginfo.artifacts",
+            debug_info,
+            with_inputs = True,
+            has_content_based_path = False,
+        )
+        subtargets = {
+            DSYM_SUBTARGET: [DefaultInfo(default_output = dsym_artifact)],
+            DEBUGINFO_SUBTARGET: [DefaultInfo(default_output = debug_info_artifacts_manifest)],
+        }
+
+        providers = (
+            [
+                AppleDebuggableInfo(dsyms = [dsym_artifact], binaries = [dsym_executable], debug_info_tset = output.external_debug_info),
+                resource_graph,
+            ]
+            + min_version_providers
+            + extra_providers
+        )
+
+        if output.linker_map != None:
+            subtargets["linker-map"] = [DefaultInfo(default_output = output.linker_map.map, other_outputs = [output.linker_map.binary])]
+            providers += [AppleBundleLinkerMapInfo(linker_maps = [output.linker_map.map])]
+
+        return (subtargets, providers)
+
+    return get_link_style_sub_targets_impl
+
+def _xcode_populate_attributes(
+    ctx,
+    srcs: list[CxxSrcWithFlags],
+    argsfiles: dict[str, CompileArgsfile],
+    populate_xcode_attributes_func: typing.Callable,
+    contains_swift_sources: bool,
+    **_kwargs,
+) -> dict[str, typing.Any]:
+    # Overwrite the product name
+    data = populate_xcode_attributes_func(ctx, srcs = srcs, argsfiles = argsfiles, product_name = ctx.attrs.name, contains_swift_sources = contains_swift_sources)
+    return data
+
+def _create_apple_library_for_distribution_providers(ctx: AnalysisContext, providers: list[Provider]) -> list[Provider]:
+    appleLibraryForDistributionInfo = ctx.attrs.distribution_dep.get(AppleLibraryForDistributionInfo)
+    appleLibraryInfo = ctx.attrs.distribution_dep.get(AppleLibraryInfo)
+
+    merged_providers = [appleLibraryForDistributionInfo]
+
+    for provider in providers:
+        if not getattr(provider, "provider_type", "") == "AppleLibraryForDistributionInfo":
+            if getattr(provider, "provider_type", "") == "AppleLibraryInfo":
+                merged_provider = AppleLibraryInfo(
+                    labels = provider.labels,
+                    public_framework_headers = appleLibraryInfo.public_framework_headers,
+                    swift_header = appleLibraryInfo.swift_header,
+                    target = provider.target,
+                )
+                merged_providers.append(merged_provider)
+            else:
+                merged_providers.append(provider)
+
+    return merged_providers
diff --git a/buck2/prelude/apple/apple_library_types.bzl b/buck2/prelude/apple/apple_library_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_library_types.bzl
@@ -0,0 +1,22 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+)
+
+AppleLibraryInfo = provider(
+    fields = {
+        "labels": list[str],
+        "provider_type": provider_field(str, default = "AppleLibraryInfo"),
+        "public_framework_headers": ArtifactTSet,
+        "swift_header": [Artifact, None],
+        "target": Label,
+    },
+)
diff --git a/buck2/prelude/apple/apple_macro_layer.bzl b/buck2/prelude/apple/apple_macro_layer.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_macro_layer.bzl
@@ -0,0 +1,154 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple/user:apple_ipa_package.bzl", "make_apple_ipa_package_target")
+load("@prelude//utils:selects.bzl", "selects")
+load(":apple_bundle_config.bzl", "apple_bundle_config")
+load(":apple_info_plist_substitutions_parsing.bzl", "parse_codesign_entitlements")
+load(":apple_package_config.bzl", "apple_package_config")
+load(":apple_resource_bundle.bzl", "make_resource_bundle_rule")
+load(
+    ":apple_rules_impl_utility.bzl",
+    "APPLE_ARCHIVE_OBJECTS_LOCALLY_OVERRIDE_ATTR_NAME",
+)
+
+AppleBuckConfigAttributeOverride = record(
+    name = field(str),
+    section = field(str, default = "apple"),
+    key = field(str),
+    positive_values = field([list[str], list[bool]], default = ["True", "true"]),
+    value_if_true = field([str, bool, None], default = True),
+    value_if_false = field([str, bool, None], default = False),
+    skip_if_false = field(bool, default = False),
+)
+
+APPLE_LINK_LIBRARIES_LOCALLY_OVERRIDE = AppleBuckConfigAttributeOverride(
+    name = "link_execution_preference",
+    key = "link_libraries_locally_override",
+    value_if_true = "local",
+    skip_if_false = True,
+)
+
+APPLE_LINK_LIBRARIES_REMOTELY_OVERRIDE = AppleBuckConfigAttributeOverride(
+    name = "link_execution_preference",
+    key = "link_libraries_remotely_override",
+    value_if_true = "remote",
+    skip_if_false = True,
+)
+
+_APPLE_LIBRARY_LOCAL_EXECUTION_OVERRIDES = [
+    APPLE_LINK_LIBRARIES_LOCALLY_OVERRIDE,
+    APPLE_LINK_LIBRARIES_REMOTELY_OVERRIDE,
+    AppleBuckConfigAttributeOverride(name = APPLE_ARCHIVE_OBJECTS_LOCALLY_OVERRIDE_ATTR_NAME, key = "archive_objects_locally_override"),
+]
+
+# If both configs are set the last one wins
+_APPLE_BINARY_EXECUTION_OVERRIDES = [
+    AppleBuckConfigAttributeOverride(
+        name = "link_execution_preference",
+        key = "link_binaries_locally_override",
+        value_if_true = "local",
+        skip_if_false = True,
+    ),
+    AppleBuckConfigAttributeOverride(
+        name = "link_execution_preference",
+        key = "link_binaries_remotely_override",
+        value_if_true = "remote",
+        skip_if_false = True,
+    ),
+]
+
+_APPLE_TEST_LOCAL_EXECUTION_OVERRIDES = [
+    APPLE_LINK_LIBRARIES_LOCALLY_OVERRIDE,
+    APPLE_LINK_LIBRARIES_REMOTELY_OVERRIDE,
+]
+
+def apple_macro_layer_set_bool_override_attrs_from_config(overrides: list[AppleBuckConfigAttributeOverride]) -> dict[str, Select]:
+    attribs = {}
+    for override in overrides:
+        config_value = read_root_config(override.section, override.key, None)
+        if config_value != None:
+            config_is_true = config_value in override.positive_values
+            if not config_is_true and override.skip_if_false:
+                continue
+            attribs[override.name] = select({
+                "DEFAULT": override.value_if_true if config_is_true else override.value_if_false,
+                # Do not set attribute value for host tools
+                "ovr_config//platform/execution/constraints:execution-platform-transitioned": None,
+            })
+    return attribs
+
+def apple_test_macro_impl(apple_test_rule, apple_resource_bundle_rule, **kwargs):
+    kwargs.update(apple_bundle_config())
+    kwargs.update(apple_macro_layer_set_bool_override_attrs_from_config(_APPLE_TEST_LOCAL_EXECUTION_OVERRIDES))
+
+    # `extension` is used both by `apple_test` and `apple_resource_bundle`, so provide default here
+    kwargs["extension"] = kwargs.pop("extension", "xctest")
+
+    apple_test_rule(_resource_bundle = make_resource_bundle_rule(apple_resource_bundle_rule, **kwargs), **kwargs)
+
+def apple_xcuitest_macro_impl(apple_xcuitest_rule, **kwargs):
+    kwargs.update(apple_bundle_config())
+    apple_xcuitest_rule(**kwargs)
+
+def apple_bundle_macro_impl(apple_bundle_rule, apple_resource_bundle_rule, **kwargs):
+    info_plist_substitutions = kwargs.get("info_plist_substitutions")
+    kwargs.update(apple_bundle_config())
+    codesign_entitlements = selects.apply(info_plist_substitutions, parse_codesign_entitlements)
+
+    apple_bundle_rule(_codesign_entitlements = codesign_entitlements, _resource_bundle = make_resource_bundle_rule(apple_resource_bundle_rule, **kwargs), **kwargs)
+
+def apple_library_macro_impl(apple_library_rule = None, **kwargs):
+    kwargs.update(apple_macro_layer_set_bool_override_attrs_from_config(_APPLE_LIBRARY_LOCAL_EXECUTION_OVERRIDES))
+    apple_library_rule(**kwargs)
+
+def apple_metal_library_macro_impl(apple_metal_library_rule = None, **kwargs):
+    if "exec_compatible_with" in kwargs:
+        fail("Cannot set `exec_compatible_with` for apple_metal_library()")
+    kwargs["exec_compatible_with"] = [
+        # It's possible a buck2 daemon host machine has the correct Xcode
+        # version selected but does not have the Metal toolchain installed.
+        # Because this would lead to a build failure, we have to send actions
+        # remotely where we it's guaranteed the Metal toolchain will be
+        # installed alongside Xcode.
+        "prelude//platforms:runs_only_remote",
+    ]
+    apple_metal_library_rule(**kwargs)
+
+def apple_library_for_distribution_macro_impl(apple_library_for_distribution_rule = None, **kwargs):
+    apple_library_macro_impl(apple_library_rule = apple_library_for_distribution_rule, **kwargs)
+
+def prebuilt_apple_framework_macro_impl(prebuilt_apple_framework_rule = None, **kwargs):
+    prebuilt_apple_framework_rule(**kwargs)
+
+def apple_binary_macro_impl(apple_binary_rule = None, apple_universal_executable = None, **kwargs):
+    kwargs.update(apple_macro_layer_set_bool_override_attrs_from_config(_APPLE_BINARY_EXECUTION_OVERRIDES))
+
+    original_binary_name = kwargs.pop("name")
+
+    if kwargs.pop("supports_universal", False):
+        binary_name = original_binary_name + "ThinBinary"
+        apple_universal_executable(
+            name = original_binary_name,
+            executable = ":" + binary_name,
+            executable_name = original_binary_name,
+            labels = kwargs.get("labels"),
+            visibility = kwargs.get("visibility"),
+            default_target_platform = kwargs.get("default_target_platform"),
+        )
+    else:
+        binary_name = original_binary_name
+
+    apple_binary_rule(name = binary_name, **kwargs)
+
+def apple_package_macro_impl(apple_package_rule = None, apple_ipa_package_rule = None, **kwargs):
+    kwargs.update(apple_package_config())
+    apple_package_rule(_ipa_package = make_apple_ipa_package_target(apple_ipa_package_rule, **kwargs), **kwargs)
+
+def apple_universal_executable_macro_impl(apple_universal_executable_rule = None, **kwargs):
+    apple_universal_executable_rule(**kwargs)
diff --git a/buck2/prelude/apple/apple_metal_library.bzl b/buck2/prelude/apple/apple_metal_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_metal_library.bzl
@@ -0,0 +1,194 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_platform_info")
+load("@prelude//cxx:target_sdk_version.bzl", "get_versioned_metal_target_triple")
+load(
+    "@prelude//ide_integrations/xcode:data.bzl",
+    "XCODE_DATA_SUB_TARGET",
+    "XcodeDataInfoKeys",
+    "generate_xcode_data",
+)
+load(":apple_resource_types.bzl", "AppleResourceDestination", "AppleResourceSpec")
+load(":apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")
+load(":resource_groups.bzl", "create_resource_graph")
+
+def apple_metal_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    metallib_archive = _compile_apple_metal_library(ctx)
+    resource_spec = AppleResourceSpec(
+        files = [metallib_archive],
+        destination = AppleResourceDestination("resources"),
+    )
+    resource_graph = create_resource_graph(
+        ctx = ctx,
+        labels = ctx.attrs.labels,
+        deps = [],
+        exported_deps = [],
+        resource_spec = resource_spec,
+    )
+
+    xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "apple_metal_library", None, _xcode_populate_attributes)
+
+    return [
+        DefaultInfo(
+            sub_targets = {
+                XCODE_DATA_SUB_TARGET: xcode_data_default_info,
+            },
+            default_output = metallib_archive,
+        ),
+        resource_graph,
+        xcode_data_info,
+    ]
+
+# Versioning extracted from Metal spec https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf
+_IOS_MIN_OS_TO_METAL_VERSION = {
+    "10": "1.2",
+    "11": "2.0",
+    "12": "2.1",
+    "13": "2.2",
+    "14": "2.3",
+    "15": "2.4",
+    "16": "3.0",
+    "17": "3.1",
+    "18": "3.2",
+    "26": "4.0",
+    "8": "1.0",
+    "9": "1.1",
+}
+
+_MACOS_MIN_OS_TO_METAL_VERSION = {
+    "10.11": "1.1",
+    "10.12": "1.2",
+    "10.13": "2.0",
+    "10.14": "2.1",
+    "10.15": "2.2",
+    "11": "2.3",
+    "12": "2.4",
+    "13": "3.0",
+    "14": "3.1",
+    "15": "3.2",
+    "26": "4.0",
+}
+
+def _derive_metal_version_from_min_os_version(ctx: AnalysisContext, min_os_version: str) -> str | None:
+    platform_info = get_cxx_platform_info(ctx)
+    version_components = min_os_version.split(".")
+    if "macosx" in platform_info.name:
+        major = version_components[0]
+        if major == "10":
+            minor = version_components[1] if len(version_components) > 1 else "0"
+            key = "{major}.{minor}".format(
+                major = major,
+                minor = minor,
+            )
+        else:
+            key = major
+        return _MACOS_MIN_OS_TO_METAL_VERSION.get(key)
+    if "iphone" in platform_info.name or "maccatalyst" in platform_info.name:
+        # Mac Catalyst uses iOS versioning numbers
+        return _IOS_MIN_OS_TO_METAL_VERSION.get(version_components[0])
+    return None
+
+# Reference: `-std=` section in https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf
+def _compute_metal_std_compiler_arg(ctx: AnalysisContext, min_os_version: str) -> list[str]:
+    version = ctx.attrs.metal_version or _derive_metal_version_from_min_os_version(ctx, min_os_version)
+    if version == None:
+        return []
+
+    if "." not in version:
+        version = version + ".0"
+
+    is_version_before_unification = version.startswith("1") or version.startswith("2")
+    if is_version_before_unification:
+        platform_info = get_cxx_platform_info(ctx)
+
+        # Mac Catalyst, i.e., `maccatalyst`, is using iOS args
+        is_mac = "macosx" in platform_info.name
+        platform_name = "macos" if is_mac else "ios"
+        return [
+            "-std={platform}-metal{version}".format(
+                platform = platform_name,
+                version = version,
+            )
+        ]
+
+    return ["-std=metal{version}".format(version = version)]
+
+def _compile_apple_metal_library(ctx: AnalysisContext) -> Artifact:
+    toolchain = ctx.attrs._apple_toolchain[AppleToolchainInfo]
+    if toolchain.metal == None or toolchain.metallib == None:
+        fail("apple_metal_library can only be built with the metal compiler available in the apple bundle toolchain")
+
+    header_map = {}
+    for header_artifact in ctx.attrs.headers:
+        import_paths = [
+            # Support including via both direct filename and relative-to-target path
+            header_artifact.basename,
+            header_artifact.short_path,
+        ]
+        for import_path in import_paths:
+            if import_path in header_map:
+                fail("Header file duplicate import path conflict: `{}`".format(import_path))
+            header_map[import_path] = header_artifact
+
+    header_symlink_tree = None
+    if len(header_map):
+        header_symlink_tree = ctx.actions.symlinked_dir(str(ctx.label.name) + "_header_symlink_tree", header_map, has_content_based_path = False)
+
+    sysroot = ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_path
+    air_files = []
+
+    min_os_version = get_min_deployment_version_for_node(ctx)
+    compile_std_arg = _compute_metal_std_compiler_arg(ctx, min_os_version)
+    for metal_file in ctx.attrs.srcs:
+        air_output = ctx.actions.declare_output(paths.replace_extension(ctx.attrs.name + "_" + metal_file.basename, ".air"), has_content_based_path = False)
+        air_compile_cmd = cmd_args(toolchain.metal)
+        air_compile_cmd.add("-target", get_versioned_metal_target_triple(ctx, min_os_version))
+        air_compile_cmd.add(compile_std_arg)
+        air_compile_cmd.add("-isysroot", sysroot)
+        if header_symlink_tree:
+            air_compile_cmd.add("-I", header_symlink_tree)
+        air_compile_cmd.add("-c", metal_file)
+        air_compile_cmd.add(ctx.attrs.metal_compiler_flags)
+        air_compile_cmd.add("-o", air_output.as_output())
+        ctx.actions.run(air_compile_cmd, category = "apple_metal_air_compile", identifier = "compile_" + ctx.attrs.name + "_" + metal_file.basename)
+        air_files.append(air_output)
+
+    if ctx.attrs.out != None:
+        if not ctx.attrs.out.endswith(".metallib"):
+            fail("Metal library output name must end in `.metallib`")
+        output_name = ctx.attrs.out
+    else:
+        output_name = ctx.attrs.name + ".metallib"
+    output = ctx.actions.declare_output(output_name, has_content_based_path = False)
+    metallib_compile = cmd_args(toolchain.metallib)
+    for air_file in air_files:
+        metallib_compile.add(air_file)
+    metallib_compile.add(ctx.attrs.metal_linker_flags)
+    metallib_compile.add("-o", output.as_output())
+
+    ctx.actions.run(
+        metallib_compile,
+        category = "apple_metallib_link",
+        identifier = "link_metallib_" + ctx.attrs.name,
+        # It's possible a local machine has the correct Xcode version selected
+        # but does not have the Metal toolchain installed. Because this would
+        # lead to a build failure, we have to send actions remotely where we
+        # it's guaranteed the Metal toolchain will be installed alongside Xcode.
+        prefer_remote = True,
+    )
+
+    return output
+
+def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:
+    return {
+        XcodeDataInfoKeys.SRCS: ctx.attrs.srcs,
+        XcodeDataInfoKeys.HEADERS: ctx.attrs.headers,
+    }
diff --git a/buck2/prelude/apple/apple_modular_utility.bzl b/buck2/prelude/apple/apple_modular_utility.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_modular_utility.bzl
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# We use a fixed module cache location. This works around issues with
+# multi-user setups with MobileOnDemand and allows us to share the
+# module cache with Xcode, LLDB and arc focus.
+#
+# TODO(T123737676): This needs to be changed to use $TMPDIR in a
+# wrapper for modular clang compilation.
+MODULE_CACHE_PATH = "/tmp/buck-module-cache"
diff --git a/buck2/prelude/apple/apple_native.bzl b/buck2/prelude/apple/apple_native.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_native.bzl
@@ -0,0 +1,100 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:prelude.bzl", "native")
+load(
+    "@prelude//platforms/apple:constants.bzl",
+    "apple_sdks",
+)
+load("@prelude//platforms/apple:platforms.bzl", "config_backed_apple_target_platform", "get_default_target_platform_for_platform", "set_apple_platforms")
+load("@prelude//platforms/apple:platforms_map.bzl", "APPLE_SDK_DEFAULT_PLATFORM_MAP")
+load("@prelude//utils:buckconfig.bzl", "read")
+
+def _apple_library(**kwargs):
+    kwargs = _update_platforms(**kwargs)
+    native.apple_library(**kwargs)
+
+def _apple_asset_catalog(**kwargs):
+    kwargs = _update_platforms(**kwargs)
+    native.apple_asset_catalog(**kwargs)
+
+def _apple_binary(**kwargs):
+    kwargs = _update_platforms(**kwargs)
+    native.apple_binary(**kwargs)
+
+def _apple_bundle(**kwargs):
+    kwargs = _update_platforms(**kwargs)
+    native.apple_bundle(**kwargs)
+
+def _apple_watchos_bundle(**kwargs):
+    kwargs = _update_platforms(**kwargs)
+    native.apple_watchos_bundle(**kwargs)
+
+def _apple_package(**kwargs):
+    kwargs = _update_platforms(**kwargs)
+    native.apple_package(**kwargs)
+
+def _apple_resource(**kwargs):
+    kwargs = _update_platforms(**kwargs)
+    native.apple_resource(**kwargs)
+
+def _apple_test(**kwargs):
+    kwargs = _update_platforms(**kwargs)
+    native.apple_test(**kwargs)
+
+def _apple_xcuitest(**kwargs):
+    kwargs = _update_platforms(**kwargs)
+    native.apple_xcuitest(**kwargs)
+
+def _apple_xcframework(**kwargs):
+    kwargs = _update_platforms(**kwargs)
+    native.apple_xcframework(**kwargs)
+
+def _update_platforms(**kwargs):
+    sdk = kwargs.pop("sdk", apple_sdks.IOS)
+    platform = _get_default_platform(sdk)
+
+    default_target_platform = kwargs.pop("default_target_platform", None)
+    base_config_backed_target_platform = kwargs.pop("config_backed_target_platform", None)
+
+    if default_target_platform != None and base_config_backed_target_platform != None:
+        name = kwargs.get("name", "UNKNOWN_TARGET")
+        fail("{} has both a default_target_platform and a config_backed_target_platform, which is not allowed".format(name))
+
+    supported_build_modes = kwargs.pop("supported_build_modes", None)
+
+    if base_config_backed_target_platform != None:
+        default_target_platform = config_backed_apple_target_platform(base_config_backed_target_platform, platform, supported_build_modes = supported_build_modes)
+    elif default_target_platform == None:
+        default_target_platform = get_default_target_platform_for_platform(platform)
+
+    if default_target_platform != None:
+        kwargs["default_target_platform"] = default_target_platform
+
+    kwargs = set_apple_platforms(platform, base_config_backed_target_platform, kwargs, supported_build_modes)
+
+    return kwargs
+
+def _get_default_platform(sdk: str) -> str:
+    config_platform = read("cxx", "default_platform")
+    if config_platform != None:
+        return config_platform
+    return APPLE_SDK_DEFAULT_PLATFORM_MAP.get(sdk)
+
+apple_native = struct(
+    apple_asset_catalog = _apple_asset_catalog,
+    apple_binary = _apple_binary,
+    apple_bundle = _apple_bundle,
+    apple_watchos_bundle = _apple_watchos_bundle,
+    apple_library = _apple_library,
+    apple_package = _apple_package,
+    apple_resource = _apple_resource,
+    apple_test = _apple_test,
+    apple_xcuitest = _apple_xcuitest,
+    apple_xcframework = _apple_xcframework,
+)
diff --git a/buck2/prelude/apple/apple_package.bzl b/buck2/prelude/apple/apple_package.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_package.bzl
@@ -0,0 +1,144 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")
+load("@prelude//xplugins:types.bzl", "XPluginsFunctionMappingManifestInfo")
+load(
+    ":apple_bundle_types.bzl",
+    "AppleBundleInfo",
+    "AppleBundleLinkerMapInfo",
+    "AppleInfoPlistInfo",
+    "ApplePackageExtension",
+)
+load(":apple_package_config.bzl", "IpaCompressionLevel")
+load(":apple_package_types.bzl", "ApplePackageInfo")
+load(
+    ":debug.bzl",
+    "AppleDebuggableInfo",
+)
+
+def apple_package_impl(ctx: AnalysisContext) -> list[Provider]:
+    package_name = ctx.attrs.package_name if ctx.attrs.package_name else ctx.attrs.bundle.label.name
+    package = ctx.actions.declare_output("{}.{}".format(package_name, ctx.attrs.ext), has_content_based_path = False)
+
+    contents = ctx.attrs.bundle[DefaultInfo].default_outputs[0] if ctx.attrs.packager else _get_ipa_contents(ctx)
+    if ctx.attrs.packager:
+        process_ipa_cmd = cmd_args([
+            ctx.attrs.packager[RunInfo],
+            "--app-bundle-path",
+            contents,
+            "--output-path",
+            package.as_output(),
+            ctx.attrs.packager_args,
+        ])
+        category = "apple_package_make_custom"
+    else:
+        process_ipa_cmd = _get_default_package_cmd(
+            ctx,
+            contents,
+            package.as_output(),
+        )
+        category = "apple_package_make"
+
+    sub_targets = {
+        "bundle": ctx.attrs.bundle.providers,
+    }
+
+    prepackaged_validators_artifacts = _get_prepackaged_validators_outputs(ctx, contents)
+    if prepackaged_validators_artifacts:
+        # Add the artifacts to packaging cmd so that they are run.
+        process_ipa_cmd.add(cmd_args(hidden = prepackaged_validators_artifacts))
+        sub_targets["prepackaged_validators"] = [
+            DefaultInfo(default_outputs = prepackaged_validators_artifacts),
+        ]
+
+    ctx.actions.run(process_ipa_cmd, category = category)
+
+    providers = [
+        DefaultInfo(
+            default_output = package,
+            sub_targets = sub_targets,
+        ),
+        ApplePackageInfo(
+            name = package_name,
+            bundle_info = ctx.attrs.bundle[AppleBundleInfo],
+            extension = ApplePackageExtension(ctx.attrs.ext),
+            package = package,
+            dsyms = ctx.attrs.bundle[AppleDebuggableInfo].dsyms,
+            info_plist = ctx.attrs.bundle[AppleInfoPlistInfo].info_plist,
+            linker_maps = ctx.attrs.bundle[AppleBundleLinkerMapInfo].linker_maps,
+            unstripped_binaries = ctx.attrs.bundle[AppleDebuggableInfo].binaries,
+        ),
+    ]
+    xplugins_function_mapping_manifest_info = ctx.attrs.bundle.get(XPluginsFunctionMappingManifestInfo)
+    if xplugins_function_mapping_manifest_info:
+        providers.append(xplugins_function_mapping_manifest_info)
+    return providers
+
+def _get_ipa_contents(ctx: AnalysisContext) -> Artifact:
+    ipa_package_dep = ctx.attrs._ipa_package
+    default_outputs = ipa_package_dep[DefaultInfo].default_outputs
+    if len(default_outputs) != 1:
+        fail("Expect exactly one output for .ipa package")
+    return default_outputs[0]
+
+def _get_default_package_cmd(ctx: AnalysisContext, unprocessed_ipa_contents: Artifact, output: OutputArtifact) -> cmd_args:
+    apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]
+    process_ipa_cmd = cmd_args([
+        apple_tools.ipa_package_maker,
+        "--ipa-contents-dir",
+        unprocessed_ipa_contents,
+        "--ipa-output-path",
+        output,
+        "--compression-level",
+        _compression_level_arg(IpaCompressionLevel(ctx.attrs._ipa_compression_level)),
+    ])
+
+    return process_ipa_cmd
+
+def _compression_level_arg(compression_level: IpaCompressionLevel) -> str:
+    if compression_level == IpaCompressionLevel("none"):
+        return "0"
+    elif compression_level == IpaCompressionLevel("default"):
+        return "6"
+    elif compression_level == IpaCompressionLevel("min"):
+        return "1"
+    elif compression_level == IpaCompressionLevel("max"):
+        return "9"
+    else:
+        fail("Unknown .ipa compression level: " + str(compression_level))
+
+def _get_prepackaged_validators_outputs(ctx: AnalysisContext, prepackaged_contents: Artifact) -> list[Artifact]:
+    if not ctx.attrs.prepackaged_validators:
+        return []
+
+    outputs = []
+    for idx, validator in enumerate(ctx.attrs.prepackaged_validators):
+        if type(validator) == "tuple":
+            validator, validator_args = validator
+        else:
+            validator = validator
+            validator_args = []
+
+        output = ctx.actions.declare_output(validator.label.name + "_{}".format(idx), has_content_based_path = False)
+        outputs.append(output)
+
+        ctx.actions.run(
+            cmd_args([
+                validator[RunInfo],
+                "--contents-dir",
+                prepackaged_contents,
+                "--output-path",
+                output.as_output(),
+                validator_args,
+            ]),
+            category = "prepackaged_validator",
+            identifier = str(idx),
+        )
+
+    return outputs
diff --git a/buck2/prelude/apple/apple_package_config.bzl b/buck2/prelude/apple/apple_package_config.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_package_config.bzl
@@ -0,0 +1,19 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+IpaCompressionLevel = enum(
+    "min",
+    "max",
+    "default",
+    "none",
+)
+
+def apple_package_config() -> dict[str, typing.Any]:
+    return {
+        "_ipa_compression_level": read_root_config("apple", "ipa_compression_level", IpaCompressionLevel("default").value),
+    }
diff --git a/buck2/prelude/apple/apple_package_types.bzl b/buck2/prelude/apple/apple_package_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_package_types.bzl
@@ -0,0 +1,22 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":apple_bundle_types.bzl", "AppleBundleInfo", "ApplePackageExtension")
+
+ApplePackageInfo = provider(
+    fields = {
+        "bundle_info": provider_field(AppleBundleInfo),
+        "dsyms": provider_field(list[Artifact]),
+        "extension": provider_field(ApplePackageExtension),
+        "info_plist": provider_field(Artifact),
+        "linker_maps": provider_field(list[Artifact]),
+        "name": provider_field(str),
+        "package": provider_field(Artifact),
+        "unstripped_binaries": provider_field(list[Artifact]),
+    },
+)
diff --git a/buck2/prelude/apple/apple_platforms.bzl b/buck2/prelude/apple/apple_platforms.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_platforms.bzl
@@ -0,0 +1,9 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+APPLE_PLATFORMS_KEY = "_apple_platforms"
diff --git a/buck2/prelude/apple/apple_provisioning_profile_sources.bzl b/buck2/prelude/apple/apple_provisioning_profile_sources.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_provisioning_profile_sources.bzl
@@ -0,0 +1,53 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifacts.bzl", "ArtifactGroupInfo")
+
+AppleProvisioningProfileSourceInfo = record(
+    # Individual profile files, populated when the source is a filegroup
+    # that provides ArtifactGroupInfo. None means this source uses a
+    # directory instead. An empty list means the source has no profiles.
+    profiles = field([list[Artifact], None], None),
+    # A directory containing profiles, populated when the source is a
+    # genrule that only provides DefaultInfo (e.g. compressed profiles
+    # decompressed at build time).
+    directory = field([Artifact, None], None),
+)
+
+AppleProvisioningProfileSourcesInfo = provider(
+    fields = {
+        "sources": provider_field(list[AppleProvisioningProfileSourceInfo]),
+    },
+)
+
+def apple_provisioning_profile_sources_impl(ctx: AnalysisContext) -> list[Provider]:
+    sources = []
+    for dep in ctx.attrs.sources:
+        artifact_group_info = dep.get(ArtifactGroupInfo)
+        if artifact_group_info:
+            # This handles the case where a filegroup defines the set of profiles
+            sources.append(
+                AppleProvisioningProfileSourceInfo(
+                    profiles = artifact_group_info.artifacts,
+                )
+            )
+        else:
+            # This handles the case where a genrule produces a directory of profiles
+            default_info = dep[DefaultInfo]
+            if default_info.default_outputs:
+                sources.append(
+                    AppleProvisioningProfileSourceInfo(
+                        directory = default_info.default_outputs[0],
+                    )
+                )
+    return [
+        DefaultInfo(default_outputs = []),
+        AppleProvisioningProfileSourcesInfo(
+            sources = sources,
+        ),
+    ]
diff --git a/buck2/prelude/apple/apple_resource.bzl b/buck2/prelude/apple/apple_resource.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_resource.bzl
@@ -0,0 +1,77 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//ide_integrations/xcode:data.bzl",
+    "XCODE_DATA_SUB_TARGET",
+    "XcodeDataInfoKeys",
+    "generate_xcode_data",
+)
+load(":apple_resource_types.bzl", "AppleResourceDestination", "AppleResourceSpec")
+load(":resource_groups.bzl", "create_resource_graph")
+
+def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:
+    extra_xcode_files = []
+
+    # ctx.attrs.files can contain Dependency
+    for file in ctx.attrs.files:
+        if isinstance(file, Dependency):
+            extra_xcode_files.extend(file[DefaultInfo].default_outputs)
+        else:
+            extra_xcode_files.append(file)
+
+    extra_xcode_files += ctx.attrs.dirs + ctx.attrs.variants
+
+    # Named varients map a str to a set, so we need to add the values from the set
+    for val in ctx.attrs.named_variants.values():
+        extra_xcode_files.extend(val)
+
+    data = {}
+    if extra_xcode_files:
+        data[XcodeDataInfoKeys.EXTRA_XCODE_FILES] = extra_xcode_files
+
+    return data
+
+def apple_resource_impl(ctx: AnalysisContext) -> list[Provider]:
+    destination = ctx.attrs.destination or "resources"
+    resource_spec = AppleResourceSpec(
+        files = ctx.attrs.files,
+        dirs = ctx.attrs.dirs,
+        content_dirs = ctx.attrs.content_dirs,
+        destination = AppleResourceDestination(destination),
+        variant_files = ctx.attrs.variants or [],
+        named_variant_files = ctx.attrs.named_variants or {},
+        codesign_files_on_copy = ctx.attrs.codesign_on_copy,
+        codesign_entitlements = ctx.attrs.codesign_entitlements,
+        codesign_flags_override = ctx.attrs.codesign_flags_override,
+    )
+
+    # `files` can contain `apple_library()` which in turn can have `apple_resource()` deps
+    file_deps = [file_or_dep for file_or_dep in ctx.attrs.files if isinstance(file_or_dep, Dependency)]
+    deps = file_deps + ctx.attrs.resources_from_deps
+    graph = create_resource_graph(
+        ctx = ctx,
+        labels = ctx.attrs.labels,
+        deps = deps,
+        exported_deps = [],
+        resource_spec = resource_spec,
+    )
+    xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "apple_resource", None, _xcode_populate_attributes)
+
+    return [
+        DefaultInfo(
+            sub_targets = {
+                "headers": [
+                    DefaultInfo(default_outputs = []),
+                ],
+                XCODE_DATA_SUB_TARGET: xcode_data_default_info,
+            },
+        ),
+        graph,
+        xcode_data_info,
+    ]
diff --git a/buck2/prelude/apple/apple_resource_bundle.bzl b/buck2/prelude/apple/apple_resource_bundle.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_resource_bundle.bzl
@@ -0,0 +1,97 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Splitting the resource compilation into another rule means we can have
+# different exec platforms for the resource compilation and for the rest
+# of the bundling process. This allows us to send resource compilations
+# directly to RE.
+#
+# +-------------------------------------------------+
+# |                 apple_bundle()                  |
+# |           Exec Platform: macOS/Linux            |
+# |   +--------+  +--------+ +------------------+   |
+# +---+ binary +--+  deps  +-+ _resource_bundle +---+
+#     +--------+  +--------+ +------------------+
+#          |           |               |
+#          |           |               |
+#          |           |               +---------------+
+#          |           |                               |
+#          |           |                               |
+#          |           |                               v
+#          |           |              +---------------------------------+
+#          |           +-----+        |     apple_resource_bundle()     |
+#          |                 |        |    Exec Platform: macOS-only    |
+#          |                 |        |     +--------+  +--------+      |
+#          |                 |        +-----+ binary +--+  deps  +------+
+#          |                 |              +--------+  +--------+
+#          |                 |                   |           |
+#          |                 |                   |           |
+#          |                 v                   |           |
+#          |       +-------------------+         |           |
+#          |       |   Dependencies    |<--------+-----------+
+#          |       +-------------------+         |
+#          |       +-------------------+         |
+#          +------>|      Binary       |<--------+
+#                  +-------------------+
+
+load("@prelude//apple:apple_rules_impl_utility.bzl", "get_apple_info_plist_build_system_identification_attrs")
+
+_RESOURCE_BUNDLE_FIELDS = [
+    "asset_catalogs_compilation_options",
+    "binary",
+    "copy_public_framework_headers",
+    "default_target_platform",
+    "deps",
+    "extension",
+    "ibtool_flags",
+    "info_plist",
+    "info_plist_substitutions",
+    "module_map",
+    "product_name",
+    "privacy_manifest",
+    "resource_group",
+    "resource_group_map",
+    "within_view",
+    "visibility",
+] + get_apple_info_plist_build_system_identification_attrs().keys()
+
+def _is_resources_toolchain_enabled() -> bool:
+    is_xplat_query_mode = read_root_config("mode", "is_xplat_mode_query") in ("True", "true")
+    if is_xplat_query_mode:
+        # Avoid returning buck2-only targets
+        return False
+
+    return read_root_config("apple", "resources_toolchain_enabled", "true").lower() == "true"
+
+def make_resource_bundle_rule(apple_resource_bundle_rule, **kwargs) -> [None, str]:
+    # The `apple_resource_bundle()` target will _always_ be Xcode-based, so resources can always be used
+    # from there. `resources_toolchain_enabled` exists only as a killswitch (or for testing/debugging purposes).
+    # By default, we consistently get all resources from `apple_resource_bundle()` target across all OSes and
+    # toolchains.
+    resources_toolchain_enabled = _is_resources_toolchain_enabled()
+    if not resources_toolchain_enabled:
+        return None
+
+    resource_bundle_name = kwargs["name"] + "__ResourceBundle_Private"
+    resource_bundle_kwargs = {
+        "compatible_with": kwargs.get("compatible_with"),
+        "exec_compatible_with": kwargs.get("exec_compatible_with"),
+        "labels": ["generated"],
+        "product_name_from_module_name": kwargs.get("product_name_from_module_name"),
+        "skip_private_swiftinterface": kwargs.get("skip_private_swiftinterface"),
+        "target_compatible_with": kwargs.get("target_compatible_with"),
+        "_bundle_target_name": kwargs["name"],
+        "_compile_resources_locally_override": kwargs["_compile_resources_locally_override"],
+    }
+    for field_name in _RESOURCE_BUNDLE_FIELDS:
+        resource_bundle_kwargs[field_name] = kwargs.get(field_name)
+
+    # TODO(T125269558): Remove usage of apple_resource_bundle() once we have exec groups.
+    apple_resource_bundle_rule(name = resource_bundle_name, **resource_bundle_kwargs)
+
+    return ":{}".format(resource_bundle_name)
diff --git a/buck2/prelude/apple/apple_resource_dedupe_alias.bzl b/buck2/prelude/apple/apple_resource_dedupe_alias.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_resource_dedupe_alias.bzl
@@ -0,0 +1,10 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def apple_resource_dedupe_alias_impl(ctx: AnalysisContext) -> list[Provider]:
+    return ctx.attrs.actual.providers
diff --git a/buck2/prelude/apple/apple_resource_types.bzl b/buck2/prelude/apple/apple_resource_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_resource_types.bzl
@@ -0,0 +1,70 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifacts.bzl", "ArtifactOutputs")
+load(":apple_asset_catalog_types.bzl", "AppleAssetCatalogSpec")
+load(":apple_core_data_types.bzl", "AppleCoreDataSpec")
+load(":scene_kit_assets_types.bzl", "SceneKitAssetsSpec")
+load(":xcassets_asset_symbols.bzl", "MetaXcassetsAssetSymbolSpec")
+
+# Represents the values for the `destination` field of `apple_resource`
+#
+# Not every destination is meaningful for every bundle kind: like `loginitems`, `launchagents`
+# only has a path in macOS application bundles, and resolves to the bundle root elsewhere.
+AppleResourceDestination = enum(
+    "executables",
+    "extensionkit_extensions",
+    "frameworks",
+    "launchagents",
+    "loginitems",
+    "plugins",
+    "resources",
+    "xpcservices",
+)
+
+# Defines _where_ resources need to be placed in an `apple_bundle`
+AppleResourceSpec = record(
+    files = field(list[[Artifact, Dependency]], []),
+    dirs = field(list[Artifact], []),
+    content_dirs = field(list[Artifact], []),
+    destination = AppleResourceDestination,
+    variant_files = field(list[Artifact], []),
+    # Map from locale to list of files for that locale, e.g.
+    # `{ "ru.lproj" : ["Localizable.strings"] }`
+    named_variant_files = field(dict[str, list[Artifact]], {}),
+    codesign_files_on_copy = field(bool, False),
+    codesign_entitlements = field(Artifact | None, None),
+    codesign_flags_override = field(list[str] | None, None),
+)
+
+# Used when invoking `ibtool`, `actool`, `mapc` and `momc`
+AppleResourceProcessingOptions = record(
+    prefer_local = field(bool, False),
+    prefer_remote = field(bool, False),
+    allow_cache_upload = field(bool, False),
+)
+
+CxxResourceSpec = record(
+    resources = field(dict[str, ArtifactOutputs], {}),
+)
+
+# A selected asset catalog with the resource-graph target that provided it.
+SelectedAppleAssetCatalogSpec = record(
+    asset_catalog_spec = field(AppleAssetCatalogSpec),
+    xcassets_symbol_spec = field([MetaXcassetsAssetSymbolSpec, None], None),
+    target = field(Label),
+)
+
+AppleResourceSelectionOutput = record(
+    resource_specs = field(list[AppleResourceSpec]),
+    asset_catalog_specs = field(list[AppleAssetCatalogSpec]),
+    selected_asset_catalog_specs = field(list[SelectedAppleAssetCatalogSpec], []),
+    core_data_specs = field(list[AppleCoreDataSpec]),
+    scene_kit_assets_spec = field(list[SceneKitAssetsSpec]),
+    cxx_resource_specs = field(list[CxxResourceSpec]),
+)
diff --git a/buck2/prelude/apple/apple_resource_utility.bzl b/buck2/prelude/apple/apple_resource_utility.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_resource_utility.bzl
@@ -0,0 +1,16 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":apple_bundle_destination.bzl", "AppleBundleDestination")
+load(
+    ":apple_resource_types.bzl",
+    "AppleResourceDestination",  # @unused Used as a type
+)
+
+def apple_bundle_destination_from_resource_destination(res_destination: AppleResourceDestination) -> AppleBundleDestination:
+    return AppleBundleDestination(res_destination.value)
diff --git a/buck2/prelude/apple/apple_rpaths.bzl b/buck2/prelude/apple/apple_rpaths.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_rpaths.bzl
@@ -0,0 +1,121 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_platform_info")
+load("@prelude//cxx:target_sdk_version.bzl", "get_target_sdk_version", "version_is_greater")
+
+def _rpath_flags_for_paths(paths: list[str]) -> list[str]:
+    return ["-Wl,-rpath," + p for p in paths]
+
+_MACOS_BINARY_RPATHS = _rpath_flags_for_paths([
+    # @executable_path = MyApp.app/Contents/MacOS
+    "@executable_path/../Frameworks",
+])
+
+_MACOS_EXTENSION_RPATHS = _MACOS_BINARY_RPATHS + _rpath_flags_for_paths([
+    # @executable_path = MyApp.app/Contents/PlugIns/MyExtension.appex/Contents/MacOS
+    "@executable_path/../../../../Frameworks",
+])
+
+_MACOS_LIBRARY_RPATHS = _rpath_flags_for_paths([
+    # @executable_path = MyApp.app/Contents/MacOS
+    "@executable_path/../Frameworks",
+    # @loader_path = MyApp.app/Contents/Frameworks/MyFramework.framework
+    "@loader_path/Frameworks",
+])
+
+_MACOS_TEST_RPATHS = _rpath_flags_for_paths([
+    # loader_path = MyApp.app/Contents/PlugIns/TestBundle.xctest/Contents/MacOS
+    "@loader_path/../Frameworks",
+    # executable_path = MyApp.app/Contents/MacOS
+    "@executable_path/../Frameworks",
+])
+
+_IOS_BINARY_RPATHS = _rpath_flags_for_paths([
+    # @executable_path = MyApp.app
+    "@executable_path/Frameworks",
+])
+
+_IOS_EXTENSION_RPATHS = _IOS_BINARY_RPATHS + _rpath_flags_for_paths([
+    # @executable_path = MyApp.app/PlugIns/MyExtension.appex
+    "@executable_path/../../Frameworks",
+])
+
+_IOS_LIBRARY_RPATHS = _rpath_flags_for_paths([
+    # @executable_path = MyApp.app
+    "@executable_path/Frameworks",
+    # @loader_path = MyApp.app/Frameworks/MyFramework.framework
+    "@loader_path/Frameworks",
+])
+
+_IOS_TEST_RPATHS = _rpath_flags_for_paths([
+    # loader_path = MyApp.app/PlugIns/TestBundle.xctest
+    "@loader_path/Frameworks",
+    # executable_path = MyApp.app
+    "@executable_path/Frameworks",
+])
+
+_SWIFT_LIB_RPATHS = _rpath_flags_for_paths([
+    # Required for concurrency backport compatibility pre iOS 15.0
+    "/usr/lib/swift",
+])
+
+_CONCURRENCY_INTRODUCED_VERSIONS = {
+    # https://github.com/DougGregor/swift/blob/ebd7b4975558ae00e7f42ea0597ad91ab05ca4ca/stdlib/private/StdlibUnittest/CMakeLists.txt#L26
+    "appletvos": "15.0",
+    "appletvsimulator": "15.0",
+    "iphoneos": "15.0",
+    "iphonesimulator": "15.0",
+    "maccatalyst": "15.0",
+    "macosx": "12.0",
+    "visionos": "1.0",
+    "visionsimulator": "1.0",
+    "watchos": "8.0",
+    "watchsimulator": "8.0",
+}
+
+def _get_platform_name(ctx: AnalysisContext) -> str:
+    return get_cxx_platform_info(ctx).name.split("-")[0]
+
+def _is_mac_binary(platform: str) -> bool:
+    return platform.startswith("mac")
+
+def _swift_lib_rpaths(ctx: AnalysisContext, platform: str) -> list[str]:
+    target_sdk_version = get_target_sdk_version(ctx)
+    concurrency_introduced_version = _CONCURRENCY_INTRODUCED_VERSIONS[platform]
+
+    if version_is_greater(concurrency_introduced_version, target_sdk_version):
+        return _SWIFT_LIB_RPATHS
+    else:
+        return []
+
+def get_rpath_flags_for_apple_binary(ctx: AnalysisContext) -> list[str]:
+    platform = _get_platform_name(ctx)
+    if _is_mac_binary(platform):
+        if ctx.attrs.application_extension:
+            return _swift_lib_rpaths(ctx, platform) + _MACOS_EXTENSION_RPATHS
+        else:
+            return _swift_lib_rpaths(ctx, platform) + _MACOS_BINARY_RPATHS
+    elif ctx.attrs.application_extension:
+        return _swift_lib_rpaths(ctx, platform) + _IOS_EXTENSION_RPATHS
+    else:
+        return _swift_lib_rpaths(ctx, platform) + _IOS_BINARY_RPATHS
+
+def get_rpath_flags_for_library(ctx: AnalysisContext) -> list[str]:
+    platform = _get_platform_name(ctx)
+    if _is_mac_binary(platform):
+        return _swift_lib_rpaths(ctx, platform) + _MACOS_LIBRARY_RPATHS
+    else:
+        return _swift_lib_rpaths(ctx, platform) + _IOS_LIBRARY_RPATHS
+
+def get_rpath_flags_for_tests(ctx: AnalysisContext) -> list[str]:
+    platform = _get_platform_name(ctx)
+    if _is_mac_binary(platform):
+        return _swift_lib_rpaths(ctx, platform) + _MACOS_TEST_RPATHS
+    else:
+        return _swift_lib_rpaths(ctx, platform) + _IOS_TEST_RPATHS
diff --git a/buck2/prelude/apple/apple_rules_decls.bzl b/buck2/prelude/apple/apple_rules_decls.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_rules_decls.bzl
@@ -0,0 +1,1909 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//:attrs_validators.bzl", "validation_common")
+load("@prelude//:validation_deps.bzl", "VALIDATION_DEPS_ATTR_NAME", "VALIDATION_DEPS_ATTR_TYPE")
+load("@prelude//apple:apple_common.bzl", "apple_common")
+load("@prelude//apple:apple_info_plist.bzl", "MergeOperations", "RestrictedMergeOperations", "UpdateOperations", "apple_info_plist_impl")
+load("@prelude//apple:apple_metal_library.bzl", "apple_metal_library_impl")
+load("@prelude//apple:apple_platforms.bzl", "APPLE_PLATFORMS_KEY")
+load("@prelude//apple:apple_provisioning_profile_sources.bzl", "apple_provisioning_profile_sources_impl")
+load("@prelude//apple:apple_resource_dedupe_alias.bzl", "apple_resource_dedupe_alias_impl")
+load("@prelude//apple:apple_resource_types.bzl", "AppleResourceDestination")
+load(
+    "@prelude//apple:apple_rules_impl_utility.bzl",
+    "AppleFrameworkBundleModuleMapType",
+    "apple_bundle_extra_attrs",
+    "apple_test_extra_attrs",
+    "get_apple_info_plist_build_system_identification_attrs",
+)
+load("@prelude//apple:apple_simulators.bzl", "apple_simulators_impl")
+load("@prelude//apple:apple_static_archive.bzl", "apple_static_archive_impl")
+load("@prelude//apple:apple_test_host_app_transition.bzl", "apple_test_host_app_transition")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")
+load("@prelude//apple:apple_tools.bzl", "apple_tools_impl")
+load("@prelude//apple:apple_universal_executable.bzl", "apple_universal_executable_impl")
+load("@prelude//apple:cxx_universal_executable.bzl", "cxx_universal_executable_impl")
+load("@prelude//apple:resource_groups.bzl", "RESOURCE_GROUP_MAP_ATTR")
+load("@prelude//apple/mockingbird:mockingbird_mock.bzl", "mockingbird_mock_attrs", "mockingbird_mock_impl")
+load("@prelude//apple/swift:swift_incremental_support.bzl", "SwiftCompilationMode")
+load("@prelude//apple/swift:swift_toolchain.bzl", "swift_toolchain_impl")
+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftObjectFormat")
+load("@prelude//apple/swift:swift_types.bzl", "SwiftMacroPlugin", "SwiftVersion")
+load("@prelude//apple/user:apple_ipa_package.bzl", "apple_ipa_package_attribs", "apple_ipa_package_impl")
+load("@prelude//apple/user:apple_macos_bundle.bzl", "apple_macos_bundle_impl")
+load("@prelude//apple/user:apple_resource_bundle.bzl", "apple_resource_bundle_impl")
+load("@prelude//apple/user:apple_resource_transition.bzl", "apple_resource_transition")
+load("@prelude//apple/user:apple_selective_debugging.bzl", "SelectiveDebuggingJsonTypes", "apple_selective_debugging_impl")
+load("@prelude//apple/user:apple_spm_package.bzl", "apple_spm_package_impl")
+load("@prelude//apple/user:apple_watchos_bundle.bzl", "apple_watchos_bundle_impl")
+load("@prelude//apple/user:apple_xcframework.bzl", "apple_xcframework_impl", "framework_split_transition")
+load("@prelude//apple/user:cpu_split_transition.bzl", "cpu_split_transition")
+load("@prelude//apple/user:macos_transition.bzl", "macos_transition")
+load("@prelude//apple/user:resource_group_map.bzl", "resource_group_map_impl")
+load("@prelude//apple/user:target_sdk_version_transition.bzl", "apple_test_target_sdk_version_transition", "target_sdk_version_transition")
+load("@prelude//apple/user:watch_transition.bzl", "watch_transition")
+load("@prelude//apple/validation:required_reasons_tools.bzl", "RequiredReasonsToolsInfo", "required_reasons_tools_impl")
+load("@prelude//cxx:groups_types.bzl", "GroupFilterInfo", "Traversal")
+load("@prelude//cxx:headers.bzl", "CPrecompiledHeaderInfo", "HeaderMode")
+load("@prelude//cxx:link_groups_types.bzl", "LINK_GROUP_MAP_ATTR")
+load("@prelude//decls:common.bzl", "CxxRuntimeType", "CxxSourceType", "HeadersAsRawHeadersMode", "LinkableDepType", "buck", "prelude_rule")
+load("@prelude//decls:cxx_common.bzl", "cxx_common")
+load("@prelude//decls:native_common.bzl", "native_common")
+load("@prelude//decls:test_common.bzl", "test_common")
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//linking:execution_preference.bzl", "link_execution_preference_attr")
+load("@prelude//linking:link_info.bzl", "LinkOrdering")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")
+load("@prelude//utils:buckconfig.bzl", "read_bool")
+load("@prelude//xplugins:attrs.bzl", "xplugins_common")
+load(":apple_app_intents.bzl", "apple_app_intents_impl")
+load(":apple_asset_catalog.bzl", "apple_asset_catalog_impl")
+load(":apple_binary.bzl", "apple_binary_impl")
+load(":apple_bundle.bzl", "apple_bundle_impl")
+load(":apple_bundle_types.bzl", "AppleBundleInfo", "ApplePackageExtension")
+load(":apple_core_data.bzl", "apple_core_data_impl")
+load(":apple_library.bzl", "AppleSharedLibraryMachOFileType", "apple_library_impl")
+load(":apple_package.bzl", "apple_package_impl")
+load(":apple_package_config.bzl", "IpaCompressionLevel")
+load(":apple_resource.bzl", "apple_resource_impl")
+load(
+    ":apple_rules_impl_utility.bzl",
+    "APPLE_ARCHIVE_OBJECTS_LOCALLY_OVERRIDE_ATTR_NAME",
+    "apple_xcuitest_extra_attrs",
+    "get_apple_resources_toolchain_attr",
+    "get_apple_xctoolchain_attr",
+    "get_apple_xctoolchain_bundle_id_attr",
+    "get_enable_library_evolution",
+    "get_incremental_split_actions_attrs",
+    "get_incremental_swiftmodule_action_attrs",
+    "get_skip_swift_incremental_outputs_attrs",
+    "get_swift_incremental_file_hashing_attrs",
+    "get_swift_incremental_logging_attrs",
+    "get_swift_incremental_remote_outputs_attrs",
+)
+load(":apple_test.bzl", "apple_test_impl")
+load(":apple_toolchain.bzl", "apple_toolchain_impl")
+load(":apple_xcuitest.bzl", "apple_xcuitest_impl")
+load(":prebuilt_apple_framework.bzl", "prebuilt_apple_framework_impl")
+load(":scene_kit_assets.bzl", "scene_kit_assets_impl")
+
+AdditionalActions = ["pre_scheme_actions", "post_scheme_actions"]
+
+AppleBundleExtension = ["app", "framework", "appex", "plugin", "bundle", "xctest", "dsym", "xpc", "prefpane", "qlgenerator"]
+
+LaunchStyle = ["auto", "wait"]
+
+SchemeActionType = ["build", "launch", "test", "profile", "analyze", "archive"]
+
+WatchInterface = ["main", "complication", "dynamic_notification", "static_notification"]
+
+SWIFT_VERSION_FEATURE_MAP = {
+    "5": [],
+    "6": [],
+}
+
+def apple_bundle_base_attrs():
+    return (
+        apple_common.product_name_from_module_name_arg()
+        | apple_common.asset_catalogs_compilation_options_arg()
+        | apple_common.info_plist_substitutions_arg()
+        | buck.contacts_arg()
+        | apple_common.default_platform_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | apple_common.codesign_flags_arg()
+        | apple_common.codesign_identity_arg()
+        | apple_common.deps_arg()
+        | apple_common.ibtool_flags_arg()
+        | apple_common.product_name_arg()
+        | apple_common.resource_group_arg()
+        | apple_common.xcode_product_type_arg()
+        | apple_common.skip_private_swiftinterface_arg()
+        | {
+            "extension": attrs.one_of(attrs.enum(AppleBundleExtension), attrs.string()),
+            "incremental_bundling_enabled": attrs.option(attrs.bool(), default = None),
+            "info_plist": attrs.source(),
+            "resource_group_map": attrs.option(RESOURCE_GROUP_MAP_ATTR, default = None),
+            "skip_copying_swift_stdlib": attrs.option(attrs.bool(), default = None),
+        }
+    )
+
+def apple_bundle_default_attrs():
+    attributes = {}
+    attributes.update(apple_bundle_base_attrs())
+    attributes.update(apple_bundle_extra_attrs())
+    attributes.update({
+        APPLE_PLATFORMS_KEY: attrs.dict(key = attrs.string(), value = attrs.dep(), sorted = False, default = {}),
+    })
+    return attributes
+
+def apple_macos_bundle_attrs():
+    attributes = apple_bundle_default_attrs()
+    attributes.update({
+        "bundle_type": attrs.string(default = "default"),
+    })
+    return attributes
+
+def apple_watchos_bundle_attrs():
+    attributes = apple_bundle_default_attrs()
+    attributes.update({
+        "bundle_type": attrs.string(default = "watchapp"),
+    })
+    return attributes
+
+apple_asset_catalog = prelude_rule(
+    name = "apple_asset_catalog",
+    docs = """
+        An `apple_asset_catalog()` rule contains resources stored in Apple asset catalog
+        directories. This rule does not have any output on its own and can be built only as a dependency
+        (either direct or transitive) of an `apple_bundle()` rule, in which case all `apple_asset_catalog()` rules
+        that the bundle rule depends on are merged and placed into the final output bundle together.
+    """,
+    examples = """
+        ```
+
+        apple_asset_catalog(
+          name = 'MyAssetCatalog',
+          dirs = [
+            'MyResources.xcassets',
+          ],
+        )
+
+        # A asset catalog with a app icon and launch image
+        apple_asset_catalog(
+          name = 'AssetCatalog',
+          dirs = [ 'AssetCatalog.xcassets' ],
+          app_icon = 'Icon',
+          launch_image = 'LaunchImage',
+        )
+
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.contacts_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | {
+            "app_icon": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                An optional reference to a `.appiconset` containing a image set representing an
+                 application icon. (The extension itself should not be included.) This parameter
+                 may be specified at most once in a given `apple_bundle`'s transitive dependencies.
+            """,
+            ),
+            "dirs": attrs.list(
+                attrs.source(allow_directory = True),
+                default = [],
+                doc = """
+                Set of paths of Apple asset catalogs contained by this rule. All paths have to end with the `.xcassets` extension and be compatible with the asset catalog format used by Xcode.
+            """,
+            ),
+            "launch_image": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                An optional reference to a `.launchimage` containing a image set representing an
+                 application launch image. (The extension itself should not be included.) This parameter
+                 may be specified at most once in a given `apple_bundle`'s transitive dependencies.
+            """,
+            ),
+        }
+        | apple_common.skip_universal_resource_dedupe_arg()
+    ),
+    impl = apple_asset_catalog_impl,
+    cfg = apple_resource_transition,
+)
+
+apple_app_intents = prelude_rule(
+    name = "apple_app_intents",
+    docs = "An `apple_app_intents()` rule represents App Intents definitions for Apple platforms.",
+    examples = None,
+    further = None,
+    attrs = (buck.contacts_arg() | buck.labels_arg() | buck.licenses_arg()),
+    impl = apple_app_intents_impl,
+)
+
+apple_binary = prelude_rule(
+    name = "apple_binary",
+    docs = """
+        An `apple_binary()` rule builds a native executable - such as an iOS or OSX app - from
+        the supplied set of Objective-C/C++ source files and dependencies. It is similar to
+        a `cxx_binary()` rule with which it shares many attributes. In addition
+        to those common attributes, `apple_binary()` has a some additional attributes
+        that are specific to binaries intended to be built using the Apple toolchain.
+        Note, however, that `apple_binary()` and `cxx_binary()` differ
+        in the way that they import header files, in order to better accommodate existing conventions.
+        See the sections for the `headers` and `exported_headers` attributes for more details.
+
+        Buck enables you to override components of the Apple toolchain with
+        alternate tools, either from the Xcode search paths or from directories
+        that you specify.
+        See `.buckconfig`
+        and `.buckconfig`
+        for more information.
+    """,
+    examples = """
+        ```
+
+        apple_binary(
+          name = 'MyBinary',
+          deps = [
+            ':MyLibrary',
+            '//Libraries:AnotherLibrary',
+          ],
+          preprocessor_flags = ['-fobjc-arc'],
+          headers = [
+            'MyHeader.h',
+          ],
+          srcs = [
+            'MySource.m',
+          ],
+          frameworks = [
+            '$SDKROOT/System/Library/Frameworks/UIKit.framework',
+            '$SDKROOT/System/Library/Frameworks/Foundation.framework',
+          ],
+        )
+
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        cxx_common.srcs_arg()
+        | apple_common.headers_arg()
+        | {
+            "entitlements_file": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                An optional name of a plist file to be embedded in the binary. Some platforms like
+                 `iphonesimulator` require this to run properly.
+            """,
+            ),
+        }
+        | apple_common.apple_tools_arg()
+        | apple_common.apple_toolchain_arg()
+        | apple_common.exported_headers_arg()
+        | apple_common.header_path_prefix_arg()
+        | apple_common.frameworks_arg()
+        | cxx_common.preprocessor_flags_arg()
+        | cxx_common.exported_preprocessor_flags_arg(exported_preprocessor_flags_type = attrs.list(attrs.arg(), default = []))
+        | cxx_common.compiler_flags_arg()
+        | cxx_common.linker_extra_outputs_arg()
+        | cxx_common.linker_flags_arg()
+        | cxx_common.exported_linker_flags_arg()
+        | native_common.link_style()
+        | native_common.link_group_public_deps_label()
+        | apple_common.target_sdk_version()
+        | apple_common.extra_xcode_sources()
+        | apple_common.extra_xcode_files()
+        | apple_common.serialize_debugging_options_arg()
+        | apple_common.uses_explicit_modules_arg()
+        | apple_common.apple_sanitizer_compatibility_arg()
+        | apple_common.executable_name_arg()
+        | apple_common.info_plist_substitutions_arg()
+        | cxx_common.supported_platforms_regex_arg()
+        | buck.contacts_arg()
+        | apple_common.default_platform_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | apple_common.defaults_arg()
+        | apple_common.deps_arg()
+        | apple_common.devirt_enabled_arg()
+        | apple_common.diagnostics_arg()
+        | apple_common.enable_cxx_interop_arg()
+        | cxx_common.exported_header_style_arg()
+        | apple_common.fat_lto_arg()
+        | cxx_common.header_namespace_arg()
+        | cxx_common.include_directories_arg()
+        | apple_common.libraries_arg()
+        | apple_common.link_group_arg()
+        | apple_common.minimum_os_version_arg()
+        | apple_common.modular_arg()
+        | apple_common.module_name_arg()
+        | apple_common.module_requires_cxx_arg()
+        | cxx_common.public_include_directories_arg()
+        | cxx_common.public_system_include_directories_arg()
+        | apple_common.sdk_modules_arg()
+        | native_common.soname()
+        | apple_common.static_library_basename_arg()
+        | apple_common.strip_level_arg()
+        | apple_common.swift_module_skip_function_bodies_arg()
+        | apple_common.disable_generated_umbrella_header_arg()
+        | apple_common.swift_package_name_arg()
+        | apple_common.thin_lto_arg()
+        | apple_common.use_submodules_arg()
+        | apple_common.uses_cxx_explicit_modules_arg()
+        | apple_common.uses_modules_arg()
+        | {
+            "application_extension": attrs.bool(default = False),
+            "binary_linker_flags": attrs.list(attrs.arg(), default = []),
+            "bridging_header": attrs.option(attrs.source(), default = None),
+            "can_be_asset": attrs.option(attrs.bool(), default = None),
+            "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),
+            "dist_thin_lto_codegen_flags": attrs.list(attrs.arg(), default = []),
+            "enable_distributed_thinlto": attrs.bool(
+                default = select({
+                    "DEFAULT": False,
+                    "config//build_mode/constraints:distributed-thin-lto[enabled]": True,
+                })
+            ),
+            "enable_library_evolution": attrs.option(attrs.bool(), default = None),
+            "exported_lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "focused_list_target": attrs.option(attrs.dep(), default = None),
+            "force_static": attrs.option(attrs.bool(), default = None),
+            "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),
+            "info_plist": attrs.option(attrs.source(), default = None),
+            "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "link_execution_preference": link_execution_preference_attr(),
+            "link_group_map": LINK_GROUP_MAP_ATTR,
+            "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),
+            "link_whole": attrs.option(attrs.bool(), default = None),
+            "post_linker_flags": attrs.list(attrs.arg(), default = []),
+            "precompiled_header": attrs.option(attrs.dep(providers = [CPrecompiledHeaderInfo]), default = None),
+            "prefer_stripped_objects": attrs.bool(default = False),
+            "preferred_linkage": attrs.enum(Linkage.values(), default = "any"),
+            "prefix_header": attrs.option(attrs.source(), default = None),
+            "raw_headers": attrs.set(attrs.source(), sorted = True, default = []),
+            "reexport_all_header_dependencies": attrs.option(attrs.bool(), default = None),
+            "sanitizer_runtime_enabled": attrs.option(attrs.bool(), default = None),
+            "supports_merged_linking": attrs.option(attrs.bool(), default = None),
+            "swift_compilation_mode": attrs.enum(SwiftCompilationMode.values(), default = "wmo"),
+            "swift_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "swift_interface_compilation_enabled": attrs.bool(default = False),
+            "swift_version": attrs.enum(SwiftVersion, default = SwiftVersion[0]),
+            "_apple_xctoolchain": get_apple_xctoolchain_attr(),
+            "_apple_xctoolchain_bundle_id": get_apple_xctoolchain_bundle_id_attr(),
+            "_enable_library_evolution": get_enable_library_evolution(),
+            "_swift_enable_testing": attrs.default_only(attrs.bool(default = False)),
+            VALIDATION_DEPS_ATTR_NAME: VALIDATION_DEPS_ATTR_TYPE,
+        }
+        | buck.allow_cache_upload_arg()
+        | validation_common.attrs_validators_arg()
+        | constraint_overrides.attributes
+        | get_skip_swift_incremental_outputs_attrs()
+        | xplugins_common.debug_artifacts_arg
+    ),
+    impl = apple_binary_impl,
+    cfg = target_sdk_version_transition,
+)
+
+apple_bundle = prelude_rule(
+    name = "apple_bundle",
+    docs = """
+        An `apple_bundle()` rule takes an Apple binary and all of the resources and asset
+        catalogs in the rule's transitive dependencies and generates a bundle containing all of those files.
+        Optionally the generated bundle can also be signed using specified provisioning profiles.
+
+        Code signing will embed entitlements pointed to by the `entitlements_file` arg in
+        the bundle's `apple_binary`. This is the preferred way to specify entitlements
+        when building with Buck.
+
+        If the entitlements file is not present, it falls back to the `CODE_SIGN_ENTITLEMENTS` entry in
+         `info_plist_substitutions`.
+
+        If after these checks, an entitlements file is still not specified, it will be derived based
+        on the entitlements of the selected provisioning profile. Provisioning profiles will be selected
+        from profiles pointed to by `apple.provisioning_profile_search_path`, based on a
+        non-expired profile that matches the bundle id and entitlements.
+
+        Code signing will embed entitlements pointed to by the `CODE_SIGN_ENTITLEMENTS` entry in
+        `info_plist_substitutions`. If an entitlements file is omitted, it will be derived based
+        on the entitlements of the selected provisioning profile. Provisioning profiles will be selected
+        from profiles pointed to by `apple.provisioning_profile_search_path`, based on a
+        non-expired profile that matches the bundle id and entitlements.
+    """,
+    examples = """
+        ```
+
+        apple_bundle(
+          name = 'AppBundle',
+          binary = ':MyBinary',
+          extension = 'app',
+          info_plist = 'Info.plist',
+        )
+
+        ```
+
+        ```
+
+        # iOS app with embedded WatchOS 2.0 app/extension
+        apple_bundle(
+          name = 'DemoWatchAppExtension',
+          binary = ':DemoWatchAppExtensionBinary',
+          extension = 'appex',
+          info_plist = 'WatchExtension/Resources/Info.plist',
+        )
+
+        apple_bundle(
+          name = 'DemoWatchApp',
+          binary = ':DemoWatchAppBinary',
+          deps = [':DemoWatchAppResources', ':DemoWatchAppExtension'],
+          extension = 'app',
+          info_plist = 'WatchApplication/Info.plist',
+        )
+
+        apple_bundle(
+          name = 'DemoApp',
+          binary = ':DemoAppBinary',
+          deps = [':DemoWatchApp#watch'],
+          extension = 'app',
+          info_plist = 'Info.plist',
+        )
+
+        ```
+
+        ```
+
+        # iOS app using safeAreaInsets delivering to iOS 9.x
+        apple_bundle(
+          name = 'DemoIBApp',
+          binary = ':DemoIBAppBinary',
+          deps = [':DemoIBAppResources'],
+          extension = 'app',
+          ibtool_flags = ["--minimum-deployment-target", "9.0"],
+          info_plist = 'Info.plist',
+        )
+
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                A list of dependencies of this bundle as build targets. You can embed application
+                 extensions by specifying the extension's bundle target. To include a WatchKit app, append the
+                 flavor `#watch` to the target specification. Buck will automatically substitute the appropriate
+                 platform flavor (either `watchsimulator` or `watchos`) based on the parent.
+            """,
+            ),
+            "product_name": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The name of the resulting bundle and binary. The setting behaves like PRODUCT\\_NAME Xcode build setting.
+                 For example, if your rule is named "MyApp" and extension is "app", by default buck will generate MyApp.app bundle.
+                 But if you will set product name to "SuperApp", bundle will get "SuperApp.app" name.
+            """,
+            ),
+            "extension": attrs.one_of(
+                attrs.enum(AppleBundleExtension),
+                attrs.string(),
+                doc = """
+                The extension of the generated bundle. For example `'app'` for an application bundle
+                 or `'appex'` for an application extension bundle.
+            """,
+            ),
+            "binary": attrs.option(
+                attrs.dep(),
+                default = None,
+                doc = """
+                A `build target` identifying
+                 an `apple_binary()` rule or
+                 an `apple_library()` or `apple_libary_for_distribution()` rule whose output will
+                 be used as the main executable binary of the generated bundle. The required rule type depends
+                 on the value in the `extension` attribute. For example, application bundles expect
+                 a binary (e.g. `'//Apps/MyApp:MyApp'`), application extension bundles expect a shared
+                 library (e.g. `'//Libraries/MyLibrary:MyLibrary#shared'`).
+            """,
+            ),
+        }
+        | apple_common.info_plist_arg()
+        | apple_common.info_plist_substitutions_arg()
+        | apple_common.privacy_manifest_arg()
+        | apple_common.product_name_from_module_name_arg()
+        | apple_common.asset_catalogs_compilation_options_arg()
+        | buck.contacts_arg()
+        | apple_common.default_platform_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | apple_common.codesign_flags_arg()
+        | apple_common.codesign_identity_arg()
+        | apple_common.resource_group_arg()
+        | apple_common.xcode_product_type_arg()
+        | apple_common.skip_private_swiftinterface_arg()
+        | {
+            "ibtool_flags": attrs.option(
+                attrs.list(attrs.string()),
+                default = None,
+                doc = """
+                List of flags to be passed to ibtool during interface builder file compilation.
+            """,
+            ),
+            "incremental_bundling_enabled": attrs.option(attrs.bool(), default = None),
+            "platform_binary": attrs.option(attrs.list(attrs.tuple(attrs.regex(), attrs.dep())), default = None),
+            "resource_group_map": attrs.option(RESOURCE_GROUP_MAP_ATTR, default = None),
+            "skip_copying_swift_stdlib": attrs.option(attrs.bool(), default = None),
+        }
+        | apple_bundle_extra_attrs()
+    ),
+    impl = apple_bundle_impl,
+    cfg = target_sdk_version_transition,
+)
+
+apple_library = prelude_rule(
+    name = "apple_library",
+    docs = """
+        An `apple_library()` rule represents a set of Objective-C/C++/Swift
+        source files and is similar to a `cxx_library()` rule with which it shares many
+        attributes. In addition to those common attributes, `apple_library()` has a some additional attributes
+        that are specific to binaries intended to be built using the Apple toolchain.
+        Note, however, that `apple_library()` and `cxx_library()` differ
+        in the way that they import header files, in order to better accommodate existing conventions.
+        See the sections for the `headers` and `exported_headers` attributes for more details.
+
+        Buck enables you to override components of the Apple toolchain with
+        alternate tools, either from the Xcode search paths or from directories
+        that you specify.
+        See `.buckconfig`
+        and `.buckconfig`
+        for more information.
+    """,
+    examples = """
+        ```
+
+        apple_library(
+          name = 'MyLibrary',
+          deps = [
+            ':OtherLibrary',
+            '//Libraries:YetAnotherLibrary',
+          ],
+          preprocessor_flags = ['-fobjc-arc'],
+          headers = [
+            'MyHeader.h',
+          ],
+          srcs = [
+            'MySource.m',
+            'MySource.swift',
+          ],
+          frameworks = [
+            '$SDKROOT/System/Library/Frameworks/UIKit.framework',
+            '$SDKROOT/System/Library/Frameworks/Foundation.framework',
+          ],
+        )
+
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        cxx_common.srcs_arg()
+        | apple_common.headers_arg()
+        | apple_common.exported_headers_arg()
+        | apple_common.header_path_prefix_arg()
+        | cxx_common.header_namespace_arg()
+        | apple_common.frameworks_arg()
+        | cxx_common.preprocessor_flags_arg()
+        | cxx_common.exported_preprocessor_flags_arg(exported_preprocessor_flags_type = attrs.list(attrs.arg(), default = []))
+        | cxx_common.compiler_flags_arg()
+        | cxx_common.linker_extra_outputs_arg()
+        | cxx_common.linker_flags_arg()
+        | cxx_common.exported_linker_flags_arg()
+        | apple_common.target_sdk_version()
+        | native_common.preferred_linkage(preferred_linkage_type = attrs.option(attrs.enum(Linkage.values()), default = None))
+        | native_common.link_style()
+        | native_common.link_whole(link_whole_type = attrs.option(attrs.bool(), default = None))
+        | cxx_common.reexport_all_header_dependencies_arg()
+        | cxx_common.exported_deps_arg()
+        | cxx_common.raw_headers_arg()
+        | cxx_common.include_directories_arg()
+        | cxx_common.public_include_directories_arg()
+        | cxx_common.public_system_include_directories_arg()
+        | cxx_common.raw_headers_as_headers_mode_arg()
+        | apple_common.extra_xcode_sources()
+        | apple_common.extra_xcode_files()
+        | apple_common.serialize_debugging_options_arg()
+        | apple_common.uses_explicit_modules_arg()
+        | apple_common.meta_apple_library_validation_enabled_arg()
+        | apple_common.executable_name_arg()
+        | apple_common.info_plist_substitutions_arg()
+        | cxx_common.supported_platforms_regex_arg()
+        | apple_common.apple_tools_arg()
+        | apple_common.apple_toolchain_arg()
+        | validation_common.attrs_validators_arg()
+        | buck.contacts_arg()
+        | apple_common.default_platform_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | apple_common.defaults_arg()
+        | apple_common.deps_arg()
+        | apple_common.devirt_enabled_arg()
+        | apple_common.diagnostics_arg()
+        | apple_common.enable_cxx_interop_arg()
+        | cxx_common.exported_header_style_arg()
+        | apple_common.fat_lto_arg()
+        | apple_common.libraries_arg()
+        | apple_common.link_group_arg()
+        | apple_common.minimum_os_version_arg()
+        | apple_common.modular_arg()
+        | apple_common.module_name_arg()
+        | apple_common.module_requires_cxx_arg()
+        | apple_common.sdk_modules_arg()
+        | native_common.soname()
+        | apple_common.static_library_basename_arg()
+        | apple_common.strip_level_arg()
+        | apple_common.swift_module_skip_function_bodies_arg()
+        | apple_common.disable_generated_umbrella_header_arg()
+        | apple_common.swift_package_name_arg()
+        | apple_common.thin_lto_arg()
+        | apple_common.use_submodules_arg()
+        | apple_common.uses_cxx_explicit_modules_arg()
+        | apple_common.uses_modules_arg()
+        | {
+            "bridging_header": attrs.option(attrs.source(), default = None),
+            "can_be_asset": attrs.option(attrs.bool(), default = None),
+            "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),
+            "dist_thin_lto_codegen_flags": attrs.list(attrs.arg(), default = []),
+            "enable_distributed_thinlto": attrs.bool(
+                default = select({
+                    "DEFAULT": False,
+                    "config//build_mode/constraints:distributed-thin-lto[enabled]": True,
+                })
+            ),
+            "enable_library_evolution": attrs.option(attrs.bool(), default = None),
+            "exported_lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "exported_post_linker_flags": attrs.list(attrs.arg(), default = []),
+            "focused_list_target": attrs.option(attrs.dep(), default = None),
+            "force_static": attrs.option(attrs.bool(), default = None),
+            "has_content_based_path": attrs.option(attrs.bool(), default = None),
+            "header_mode": attrs.option(attrs.enum(HeaderMode.values()), default = None),
+            "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),
+            "info_plist": attrs.option(attrs.source(), default = None),
+            "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "link_execution_preference": link_execution_preference_attr(),
+            "link_group_map": LINK_GROUP_MAP_ATTR,
+            "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),
+            "post_linker_flags": attrs.list(attrs.arg(), default = []),
+            "precompiled_header": attrs.option(attrs.dep(providers = [CPrecompiledHeaderInfo]), default = None),
+            "preferred_linkage": attrs.enum(Linkage.values(), default = "any"),
+            "prefix_header": attrs.option(attrs.source(), default = None),
+            "public_framework_headers": attrs.named_set(attrs.source(), sorted = True, default = []),
+            # Mach-O file type for binary when the target is built as a shared library.
+            "shared_library_macho_file_type": attrs.enum(AppleSharedLibraryMachOFileType.values(), default = "dylib"),
+            "supports_header_symlink_subtarget": attrs.bool(default = False),
+            "supports_merged_linking": attrs.option(attrs.bool(), default = None),
+            "supports_shlib_interfaces": attrs.bool(default = True),
+            "swift_compilation_mode": attrs.enum(SwiftCompilationMode.values(), default = "wmo"),
+            "swift_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "swift_dump_ast_subtarget_enabled": attrs.bool(default = read_bool("apple", "swift_dump_ast_subtarget_enabled", default = False, root_cell = True)),
+            "swift_interface_compilation_enabled": attrs.bool(default = True),
+            "swift_macro_deps": attrs.list(attrs.plugin_dep(kind = SwiftMacroPlugin), default = []),
+            "swift_version": attrs.enum(SwiftVersion, default = SwiftVersion[0]),
+            "swiftinterface_subtarget_enabled": attrs.bool(default = read_bool("apple", "swiftinterface_subtarget_enabled", default = False, root_cell = True)),
+            "use_archive": attrs.option(attrs.bool(), default = None),
+            "_apple_xctoolchain": get_apple_xctoolchain_attr(),
+            "_apple_xctoolchain_bundle_id": get_apple_xctoolchain_bundle_id_attr(),
+            "_enable_library_evolution": get_enable_library_evolution(),
+            "_swift_enable_testing": attrs.bool(
+                default = select({
+                    "DEFAULT": False,
+                    "config//features/apple:swift_enable_testing_enabled": True,
+                })
+            ),
+            APPLE_ARCHIVE_OBJECTS_LOCALLY_OVERRIDE_ATTR_NAME: attrs.option(attrs.bool(), default = None),
+            VALIDATION_DEPS_ATTR_NAME: VALIDATION_DEPS_ATTR_TYPE,
+        }
+        | buck.allow_cache_upload_arg()
+        | get_swift_incremental_file_hashing_attrs()
+        | get_swift_incremental_logging_attrs()
+        | get_swift_incremental_remote_outputs_attrs()
+        | get_skip_swift_incremental_outputs_attrs()
+        | xplugins_common.debug_artifacts_arg
+        | get_incremental_split_actions_attrs()
+        | get_incremental_swiftmodule_action_attrs()
+    ),
+    uses_plugins = [SwiftMacroPlugin],
+    impl = apple_library_impl,
+    cfg = target_sdk_version_transition,
+)
+
+apple_library_for_distribution = prelude_rule(
+    name = "apple_library_for_distribution",
+    docs = """
+        An `apple_library_for_distribution()` rule creates a library for distribution
+        (for instance via a Framework or Xcframework) with link group support.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        apple_library.attrs
+        | {
+            "distribution_dep": attrs.dep(),
+        }
+    ),
+    uses_plugins = [SwiftMacroPlugin],
+    impl = apple_library_impl,
+    cfg = target_sdk_version_transition,
+)
+
+apple_metal_library = prelude_rule(
+    name = "apple_metal_library",
+    impl = apple_metal_library_impl,
+    docs = """
+        An `apple_metal_library()` rule contains .metal and .h source files
+        to be bundled together to create a .metallib
+    """,
+    examples = """
+        ```
+
+        apple_metal_library(
+          name = 'MyShaderLibrary',
+          srcs = [
+              MyShaderFile.metal,
+              SharedShaderHelpers.metal,
+          ],
+          headers = [ SharedShaderHelpers.h ],
+        )
+
+        ```
+    """,
+    further = None,
+    attrs = (
+        buck.labels_arg()
+        | buck.contacts_arg()
+        | {
+            "headers": attrs.list(attrs.source(), default = []),
+            "metal_compiler_flags": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                Flags to use when compiling Metal sources.
+            """,
+            ),
+            "metal_linker_flags": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                Flags to use when linking Metal `.air` files using `metallib`.
+            """,
+            ),
+            "metal_version": attrs.option(attrs.string(), default = None),
+            "out": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The name of the compiled library (must end in `.metallib`). Defaults to the target's name.
+            """,
+            ),
+            "srcs": attrs.list(attrs.source(), default = []),
+            "_apple_toolchain": get_apple_resources_toolchain_attr(),
+        }
+    ),
+)
+
+apple_package = prelude_rule(
+    name = "apple_package",
+    docs = """
+        An `apple_package()` rule takes the output of
+        an `apple_bundle()` rule and compresses it in
+        an IPA (iOS App Store Package) file.
+
+        This rule can be customized using the config options `.buckconfig`
+        and `.buckconfig`
+        .
+    """,
+    examples = """
+        ```
+
+        apple_package(
+          name = 'AppPackage',
+          bundle = ':AppBundle',
+        )
+
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.contacts_arg()
+        | apple_common.default_platform_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | {
+            "bundle": attrs.dep(
+                providers = [AppleBundleInfo],
+                doc = """
+                A build target identifying
+                 an `apple_bundle()` rule whose output will
+                 be stored in the IPA package generated by this rule.
+            """,
+            ),
+            "ext": attrs.enum(ApplePackageExtension.values(), default = "ipa"),
+            "include_app_symbols": attrs.bool(default = False),
+            "package_name": attrs.option(attrs.string(), default = None),
+            "packager": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "packager_args": attrs.list(attrs.arg(), default = []),
+            "prepackaged_validators": attrs.list(
+                attrs.one_of(
+                    attrs.exec_dep(providers = [RunInfo]),
+                    attrs.tuple(attrs.exec_dep(providers = [RunInfo]), attrs.list(attrs.arg())),
+                ),
+                default = [],
+            ),
+            "_ipa_compression_level": attrs.enum(IpaCompressionLevel.values()),
+            "_ipa_package": attrs.dep(),
+        }
+        | apple_common.apple_tools_arg()
+    ),
+    impl = apple_package_impl,
+)
+
+apple_resource = prelude_rule(
+    name = "apple_resource",
+    docs = """
+        An `apple_resource()` rule contains sets of resource directories, files and file variants
+        that can be bundled in an application bundle. This rule does not have any output on its own and can
+        be built only as a dependency (either direct or transitive) of
+        an `apple_bundle()` rule.
+    """,
+    examples = """
+        ```
+
+        apple_resource(
+          name = 'Images',
+          files = glob([
+            '*.png',
+          ]),
+          dirs = [
+            'PrettyImages',
+          ],
+        )
+
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "dirs": attrs.list(
+                attrs.source(allow_directory = True),
+                default = [],
+                doc = """
+                Set of paths of resource directories that should be placed in an application bundle.
+            """,
+            ),
+            "content_dirs": attrs.list(
+                attrs.source(allow_directory = True),
+                default = [],
+                doc = """
+                Set of paths of directories containing resource files that should be placed in an application bundle. Unlike `dirs`, the directories themselves are not placed in the bundle.
+            """,
+            ),
+            "files": attrs.list(
+                attrs.one_of(attrs.dep(), attrs.source()),
+                default = [],
+                doc = """
+                Set of paths of resource files that should be placed in an application bundle.
+            """,
+            ),
+            "variants": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Set of paths of resource file variants that should be placed in an application bundle. The files
+                 mentioned here should be placed in a directory named `$VARIANT_NAME.lproj`,
+                 where `$VARIANT_NAME` is the name of the variant
+                 (e.g. `Base`, `en`). This argument makes it possible to use different
+                 resource files based on the active locale.
+            """,
+            ),
+            "named_variants": attrs.dict(
+                key = attrs.string(),
+                value = attrs.set(attrs.source(), sorted = False),
+                sorted = False,
+                default = {},
+                doc = """
+                Mapping from a variant name to the list of resource file paths which should be placed in an application bundle. Those files
+                 will be placed in a directory with name equal to the corresponding key in this mapping. Keys should end with `.lproj` suffix.
+                 (e.g. `Base.lproj`, `en.lproj`).
+            """,
+            ),
+            "resources_from_deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Set of build targets whose transitive `apple_resource`s should be considered as part of
+                 the current resource when collecting resources for bundles.
+
+                 Usually, an `apple_bundle` collects all `apple_resource` rules transitively
+                 reachable through apple\\_library rules. This field allows for resources which are not reachable
+                 using the above traversal strategy to be considered for inclusion in the bundle.
+            """,
+            ),
+            "destination": attrs.option(
+                attrs.enum(AppleResourceDestination.values()),
+                default = None,
+                doc = """
+                Specifies the destination in the final application bundle where resource will be copied. Possible
+                 values: "resources", "frameworks", "executables", "plugins", "xpcservices", "loginitems",
+                 "launchagents" (macOS `Contents/Library/LaunchAgents`), "extensionkit_extensions".
+            """,
+            ),
+            "codesign_on_copy": attrs.bool(
+                default = False,
+                doc = """
+                Indicates whether the files specified in the files arg in this resource should be code signed with the identity used to sign the overall bundle. This is useful for e.g.
+                 dylibs or other additional binaries copied into the bundle. The caller is responsible to ensure that the file format is valid for codesigning.
+            """,
+            ),
+            "codesign_entitlements": attrs.option(attrs.source(), default = None),
+            "codesign_flags_override": attrs.option(attrs.list(attrs.string()), default = None),
+        }
+        | buck.contacts_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | apple_common.skip_universal_resource_dedupe_arg()
+    ),
+    impl = apple_resource_impl,
+    cfg = apple_resource_transition,
+)
+
+apple_test = prelude_rule(
+    name = "apple_test",
+    docs = """
+        An `apple_test()` rule contains Objective-C/C++ code which can be built and used to test
+        code contained in other rules. The tests can be executed by running `buck test`.
+    """,
+    examples = """
+        ```
+
+        apple_test(
+          name = 'MyTest',
+          info_plist = 'MyTest-Info.plist',
+          preprocessor_flags = ['-fobjc-arc'],
+          srcs = [
+            'MyTest.m',
+          ],
+          deps = [
+            ':MyLibrary',
+          ],
+          frameworks = [
+            '$SDKROOT/System/Library/Frameworks/Foundation.framework',
+            '$SDKROOT/System/Library/Frameworks/UIKit.framework',
+            '$PLATFORM_DIR/Developer/Library/Frameworks/XCTest.framework',
+          ],
+        )
+
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        apple_common.info_plist_arg()
+        | apple_common.info_plist_substitutions_arg()
+        | {
+            "embed_xctest_frameworks_in_test_host_app": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Controls whether a marker constraint is added to the `test_host_app`.
+            """,
+            ),
+            "test_host_app": attrs.option(
+                attrs.transition_dep(cfg = apple_test_host_app_transition),
+                default = None,
+                doc = """
+                A build target identifying
+                 an `apple_bundle()` rule that builds an
+                 application bundle. Output of the specified rule will be used as a test host of this test. This
+                 implies `run_test_separately`.
+                 Since symbols that are defined in the test host application and its dependencies will not be
+                 linked into the test binary, to make those symbols accessible to the test target they need
+                 to be specified as a dependency of this target and `['-undefined', 'dynamic_lookup']`  needs to be added to this target's `linker_flags` (this will suppress undefined
+                 reference errors during compilation, but if the symbols do not exist, it might result in runtime
+                 crashes).
+            """,
+            ),
+        }
+        | cxx_common.srcs_arg()
+        | apple_common.headers_arg()
+        | apple_common.header_path_prefix_arg()
+        | apple_common.frameworks_arg()
+        | cxx_common.preprocessor_flags_arg()
+        | cxx_common.compiler_flags_arg()
+        | cxx_common.linker_flags_arg()
+        | apple_common.target_sdk_version()
+        | buck.run_test_separately_arg(run_test_separately_type = attrs.bool(default = False))
+        | buck.test_label_arg()
+        | apple_common.extra_xcode_sources()
+        | apple_common.extra_xcode_files()
+        | apple_common.serialize_debugging_options_arg()
+        | apple_common.uses_explicit_modules_arg()
+        | apple_common.apple_sanitizer_compatibility_arg()
+        | apple_common.executable_name_arg()
+        | apple_common.asset_catalogs_compilation_options_arg()
+        | cxx_common.supported_platforms_regex_arg()
+        | buck.contacts_arg()
+        | apple_common.default_platform_arg()
+        | buck.licenses_arg()
+        | apple_common.codesign_flags_arg()
+        | apple_common.codesign_identity_arg()
+        | apple_common.defaults_arg()
+        | apple_common.deps_arg()
+        | cxx_common.exported_deps_arg()
+        | apple_common.devirt_enabled_arg()
+        | apple_common.diagnostics_arg()
+        | apple_common.enable_cxx_interop_arg()
+        | cxx_common.exported_header_style_arg()
+        | apple_common.fat_lto_arg()
+        | cxx_common.header_namespace_arg()
+        | cxx_common.include_directories_arg()
+        | apple_common.libraries_arg()
+        | apple_common.link_group_arg()
+        | apple_common.modular_arg()
+        | apple_common.module_name_arg()
+        | apple_common.module_requires_cxx_arg()
+        | cxx_common.public_include_directories_arg()
+        | cxx_common.public_system_include_directories_arg()
+        | apple_common.sdk_modules_arg()
+        | native_common.soname()
+        | apple_common.static_library_basename_arg()
+        | apple_common.swift_module_skip_function_bodies_arg()
+        | apple_common.disable_generated_umbrella_header_arg()
+        | apple_common.thin_lto_arg()
+        | apple_common.use_submodules_arg()
+        | apple_common.uses_cxx_explicit_modules_arg()
+        | apple_common.uses_modules_arg()
+        | apple_common.xcode_product_type_arg()
+        | {
+            "bridging_header": attrs.option(attrs.source(), default = None),
+            "can_be_asset": attrs.option(attrs.bool(), default = None),
+            "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),
+            "destination_specifier": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),
+            "entitlements_file": attrs.option(attrs.source(), default = None),
+            "env": attrs.option(attrs.dict(key = attrs.string(), value = attrs.arg(), sorted = False), default = None),
+            # Need to keep both `exported_headers` and `headers` for Swift mixed modules
+            # to hide C++ code importing.
+            "exported_headers": attrs.named_set(attrs.source(), sorted = True, default = []),
+            "exported_lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "exported_linker_flags": attrs.list(attrs.arg(), default = []),
+            "exported_post_linker_flags": attrs.list(attrs.arg(), default = []),
+            "exported_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+            "focused_list_target": attrs.option(attrs.dep(), default = None),
+            "force_static": attrs.option(attrs.bool(), default = None),
+            "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),
+            "incremental_bundling_enabled": attrs.option(attrs.bool(), default = None),
+            "is_ui_test": attrs.bool(default = False),
+            "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "link_group_map": LINK_GROUP_MAP_ATTR,
+            # Used to create the shared test library. Any library deps whose `preferred_linkage` isn't "shared" will
+            # be treated as "static" deps and linked into the shared test library.
+            "link_style": attrs.enum(LinkableDepType, default = "static"),
+            "link_whole": attrs.option(attrs.bool(), default = None),
+            "linker_extra_outputs": attrs.list(attrs.string(), default = []),
+            "post_linker_flags": attrs.list(attrs.arg(), default = []),
+            # The test source code and lib dependencies should be built into a shared library.
+            "preferred_linkage": attrs.enum(Linkage.values(), default = "shared"),
+            "prefix_header": attrs.option(attrs.source(), default = None),
+            "raw_headers": attrs.set(attrs.source(), sorted = True, default = []),
+            "reexport_all_header_dependencies": attrs.option(attrs.bool(), default = None),
+            "runner": attrs.option(attrs.dep(), default = None),
+            "skip_copying_swift_stdlib": attrs.option(attrs.bool(), default = None),
+            "snapshot_reference_images_path": attrs.option(attrs.one_of(attrs.source(), attrs.string()), default = None),
+            "specs": attrs.option(attrs.arg(json = True), default = None),
+            "supports_merged_linking": attrs.option(attrs.bool(), default = None),
+            "swift_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "swift_interface_compilation_enabled": attrs.bool(default = False),
+            "swift_macro_deps": attrs.list(attrs.plugin_dep(kind = SwiftMacroPlugin), default = []),
+            "swift_version": attrs.enum(SwiftVersion, default = SwiftVersion[0]),
+            "test_rule_timeout_ms": attrs.option(attrs.int(), default = None),
+            "ui_test_target_app": attrs.option(attrs.dep(), default = None),
+        }
+        | buck.allow_cache_upload_arg()
+        | buck.inject_test_env_arg()
+        | apple_test_extra_attrs()
+        | test_common.attributes()
+        | xplugins_common.debug_artifacts_arg
+        | constraint_overrides.attributes
+    ),
+    uses_plugins = [SwiftMacroPlugin],
+    impl = apple_test_impl,
+    cfg = apple_test_target_sdk_version_transition,
+)
+
+apple_toolchain = prelude_rule(
+    name = "apple_toolchain",
+    docs = """
+        An `apple_toolchain()` rule defines the set of tools and settings used to build Apple targets.
+        It specifies paths to compilers, linkers, code signing utilities, resource compilers, and other
+        tools from the Apple SDK and Xcode. Rules such as `apple_binary()`, `apple_library()`, and
+        `apple_bundle()` reference an `apple_toolchain()` to determine which tools and SDK to use
+        during compilation, linking, and bundling.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        buck.contacts_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | {
+            "actool": attrs.exec_dep(providers = [RunInfo]),
+            "app_intents_metadata_processor": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "app_intents_nl_training_processor": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "architecture": attrs.string(default = ""),
+            "build_version": attrs.option(attrs.string(), default = None),
+            "codesign": attrs.exec_dep(providers = [RunInfo]),
+            "codesign_allocate": attrs.exec_dep(providers = [RunInfo]),
+            "codesign_identities_command": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            # Controls invocations of `ibtool`, `actool` `mapc` and `momc`
+            "compile_resources_locally": attrs.bool(default = False),
+            "copy_scene_kit_assets": attrs.exec_dep(providers = [RunInfo]),
+            "cxx_toolchain": attrs.toolchain_dep(),
+            "developer_path": attrs.option(attrs.source(), default = None),
+            "dsymutil": attrs.exec_dep(providers = [RunInfo]),
+            "dsymutil_flags": attrs.list(attrs.string(), default = []),
+            "dwarfdump": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "extra_linker_outputs": attrs.set(attrs.string(), default = []),
+            "ibtool": attrs.exec_dep(providers = [RunInfo]),
+            "libtool": attrs.exec_dep(providers = [RunInfo]),
+            "lipo": attrs.exec_dep(providers = [RunInfo]),
+            "mapc": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "merge_index_store": attrs.default_only(attrs.dep(providers = [RunInfo], default = "prelude//apple/tools/index:merge_index_store")),
+            "metal": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "metallib": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "min_version": attrs.string(default = ""),
+            "momc": attrs.exec_dep(providers = [RunInfo]),
+            "objdump": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            # A placeholder tool that can be used to set up toolchain constraints.
+            # Useful when fat and thin toolchains share the same underlying tools via `command_alias()`,
+            # which requires setting up separate platform-specific aliases with the correct constraints.
+            "placeholder_tool": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "platform_path": attrs.option(attrs.source(), default = None),  # Mark as optional until we remove `_internal_platform_path`
+            "required_reasons_tools": attrs.exec_dep(providers = [RequiredReasonsToolsInfo]),
+            # Defines whether the Xcode project generator needs to check
+            # that the selected Xcode version matches the one defined
+            # by the `xcode_build_version` fields.
+            "requires_xcode_version_match": attrs.bool(default = False),
+            "sdk_environment": attrs.option(attrs.string(), default = None),
+            "sdk_name": attrs.string(default = ""),
+            "sdk_path": attrs.option(attrs.source(), default = None),  # Mark as optional until we remove `_internal_sdk_path`
+            "swift_toolchain": attrs.option(attrs.toolchain_dep(), default = None),
+            "version": attrs.option(attrs.string(), default = None),
+            "watch_kit_stub_binary": attrs.option(attrs.source(), default = None),
+            "work_around_dsymutil_lto_stack_overflow_bug": attrs.option(attrs.bool(), default = None),
+            "xcode_build_version": attrs.option(attrs.string(), default = None),
+            "xcode_version": attrs.string(),
+            "xctest": attrs.exec_dep(providers = [RunInfo]),
+            # TODO(T111858757): Mirror of `platform_path` but treated as a string. It allows us to
+            #                   pass abs paths during development and using the currently selected Xcode.
+            "_internal_platform_path": attrs.option(attrs.string(), default = None),
+            # TODO(T111858757): Mirror of `sdk_path` but treated as a string. It allows us to
+            #                   pass abs paths during development and using the currently selected Xcode.
+            "_internal_sdk_path": attrs.option(attrs.string(), default = None),
+        }
+        | apple_common.apple_installer_arg()
+    ),
+    impl = apple_toolchain_impl,
+)
+
+required_reasons_tools = prelude_rule(
+    name = "required_reasons_tools",
+    docs = """
+        A `required_reasons_tools()` rule bundles the tools used to validate Apple
+        Required Reasons API (RRAPI) usage against a bundle's `.xcprivacy` privacy manifest.
+        It is referenced by `apple_toolchain()` and provides the per-target `analyzer`, the
+        bundle-level `validator`.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        buck.contacts_arg()
+        | buck.labels_arg()
+        | {
+            "analyzer": attrs.exec_dep(providers = [RunInfo]),
+            "validator": attrs.exec_dep(providers = [RunInfo]),
+        }
+    ),
+    impl = required_reasons_tools_impl,
+)
+
+core_data_model = prelude_rule(
+    name = "core_data_model",
+    docs = """
+        An `core_data_model()` rule contains models for Apple's Core Data framework. This rule does not have any output on its own and can be built only as a dependency
+        (either direct or transitive) of an `apple_bundle()` rule in which case all `core_data_model()` rules
+        that the bundle rule depends on are merged and placed into the final output bundle together.
+    """,
+    examples = """
+        ```
+
+        core_data_model(
+          name = 'MyCoreDataModel',
+          path = 'MyCoreDataModel.xcdatamodeld',
+        )
+
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.contacts_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | {
+            "module": attrs.option(attrs.string(), default = None),
+            "path": attrs.source(
+                allow_directory = True,
+                doc = """
+                Relative path of the .xcdatamodeld package directory.
+            """,
+            ),
+        }
+    ),
+    impl = apple_core_data_impl,
+)
+
+prebuilt_apple_framework = prelude_rule(
+    name = "prebuilt_apple_framework",
+    docs = """
+        A `prebuilt_apple_framework()` rule represents a set of
+         Objective-C/C++ source files and is very similar to a `prebuilt_cxx_library()` rule.
+    """,
+    examples = """
+        ```
+
+        prebuilt_apple_framework(
+          name = 'MyPrebuiltFramework',
+          framework = 'myPrebuiltFramework.framework',
+          preferred_linkage = 'static',
+          visibility = [
+            'PUBLIC'
+          ]
+        )
+
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.contacts_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | apple_common.deps_arg()
+        | apple_common.libraries_arg()
+        | apple_common.sdk_modules_arg()
+        | apple_common.strip_level_arg()
+        | {
+            "binary": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+              Optional name for the binary contained in the framework. Otherwise the framework name is used.
+              Therefore, if your framework binary is named something like `libFrameworkName-iPhone.a` instead
+              of `FrameworkName`, you can declare this here.
+            """,
+            ),
+            "contains_swift": attrs.bool(default = False),
+            "dsyms": attrs.list(attrs.source(allow_directory = True), default = []),
+            "exported_linker_flags": attrs.list(attrs.string(), default = []),
+            "extra_codesign_paths": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                A list of extra paths, relative to the framework root, that will be codesigned.
+                """,
+            ),
+            "framework": attrs.option(attrs.source(allow_directory = True), default = None),
+            "frameworks": attrs.list(attrs.string(), default = []),
+            "modular": attrs.bool(default = True),
+            "preferred_linkage": attrs.enum(
+                Linkage.values(),
+                default = "any",
+                doc = """
+                How to link to a binary: use `dynamic` for a dynamic
+                 framework, and `static` for old universal static
+                 frameworks manually lipo-ed together. `dynamic` will
+                 copy the frameworks into the `Frameworks` directory
+                 of an Apple bundle, and configure framework search paths and linker flags.
+                 `static` will copy the resources of the framework into
+                 an Apple bundle.
+            """,
+            ),
+        }
+        | apple_common.apple_tools_arg()
+        | apple_common.apple_toolchain_arg()
+        | cxx_common.supported_platforms_regex_arg()
+    ),
+    impl = prebuilt_apple_framework_impl,
+)
+
+scene_kit_assets = prelude_rule(
+    name = "scene_kit_assets",
+    docs = """
+        A `scene_kit_assets()` rule specifies a SceneKit asset catalog (`.scnassets` directory)
+        to be included in an `apple_bundle()`. The assets are compiled using the
+        `copy_scene_kit_assets` tool from the Apple toolchain during bundling.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.contacts_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | {
+            "path": attrs.source(allow_directory = True),
+        }
+    ),
+    impl = scene_kit_assets_impl,
+)
+
+swift_toolchain = prelude_rule(
+    name = "swift_toolchain",
+    docs = """
+        A `swift_toolchain()` rule defines the Swift compiler and associated tools used to build
+        Swift code in Apple targets. It specifies the `swiftc` compiler, standard library tools,
+        module paths, SDK paths, and compiler flags. An `apple_toolchain()` references a
+        `swift_toolchain()` via its `swift_toolchain` attribute to enable Swift compilation.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        buck.contacts_arg()
+        | buck.labels_arg()
+        | buck.licenses_arg()
+        | {
+            "architecture": attrs.string(),
+            "enforce_dedupe_eligibility": attrs.bool(default = False),
+            "make_swift_comp_db": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//apple/tools:make_swift_comp_db")),
+            "make_swift_interface": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//apple/tools:make_swift_interface")),
+            "object_format": attrs.enum(SwiftObjectFormat.values(), default = "object"),
+            # A placeholder tool that can be used to set up toolchain constraints.
+            # Useful when fat and thin toolchahins share the same underlying tools via `command_alias()`,
+            # which requires setting up separate platform-specific aliases with the correct constraints.
+            "placeholder_tool": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "platform_path": attrs.option(attrs.source(), default = None),
+            # Prioritizes the Swift critical path by preferring swiftmodule emits
+            # locally, disabling low-pass gating for swiftmodule and PCM actions,
+            # and increasing bulk Swift object-compile weight.
+            "prioritize_swift_critical_path": attrs.bool(default = False),
+            "provide_swift_debug_info": attrs.bool(default = True),
+            "resource_dir": attrs.option(attrs.source(), default = None),
+            "runtime_paths_for_bundling": attrs.list(attrs.string(), default = []),
+            "runtime_paths_for_linking": attrs.list(attrs.string(), default = []),
+            "sdk_module_path_prefixes": attrs.dict(key = attrs.string(), value = attrs.source(), default = {}),
+            "sdk_modules": attrs.list(attrs.exec_dep(), default = []),  # A list or a root target that represent a graph of sdk modules (e.g Frameworks)
+            "sdk_path": attrs.option(attrs.source(), default = None),  # Mark as optional until we remove `_internal_sdk_path`
+            "serialized_diags_to_json": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "supports_explicit_module_debug_serialization": attrs.bool(default = False),
+            "supports_incremental_file_hashing": attrs.bool(default = False),
+            # Only the Pika toolchain's swiftc understands
+            # -emit-modularization-dependency-dot-graph.
+            "supports_modularization_dependency_graph": attrs.bool(default = False),
+            "supports_modulemaps_with_hmaps": attrs.bool(default = False),
+            "supports_relative_resource_dir": attrs.bool(default = False),
+            "swift_experimental_features": attrs.dict(
+                key = attrs.enum(SwiftVersion), value = attrs.list(attrs.string()), sorted = False, default = SWIFT_VERSION_FEATURE_MAP
+            ),
+            "swift_ide_test_tool": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "swift_stdlib_tool": attrs.exec_dep(providers = [RunInfo]),
+            "swift_stdlib_tool_flags": attrs.list(attrs.arg(), default = []),
+            "swift_upcoming_features": attrs.dict(
+                key = attrs.enum(SwiftVersion), value = attrs.list(attrs.string()), sorted = False, default = SWIFT_VERSION_FEATURE_MAP
+            ),
+            "swiftc": attrs.exec_dep(providers = [RunInfo]),
+            "swiftc_flags": attrs.list(attrs.arg(), default = []),
+            "use_depsfiles": attrs.bool(default = False),
+            "uses_content_based_paths": attrs.bool(default = False),
+            # TODO(T111858757): Mirror of `sdk_path` but treated as a string. It allows us to
+            #                   pass abs paths during development and using the currently selected Xcode.
+            "_internal_sdk_path": attrs.option(attrs.string(), default = None),
+            "_swiftc_wrapper": attrs.exec_dep(providers = [RunInfo], default = "prelude//apple/tools:swift_exec"),
+        }
+    ),
+    impl = swift_toolchain_impl,
+)
+
+apple_universal_executable = prelude_rule(
+    name = "apple_universal_executable",
+    impl = apple_universal_executable_impl,
+    docs = """
+        An `apple_universal_executable()` rule takes a target via its
+        `binary` attribute, builds it for multiple architectures and
+        combines the result into a single binary using `lipo`.
+
+        The output of the rule is a universal binary:
+        - If `config//cpu/constraints:universal-enabled` is present in the target platform.
+        - If the `universal` attribute is set to `True`.
+
+        If none of the conditions are met, then the rule acts as a nop `alias()`.
+
+        The `universal` attribute, if present, takes precedence over constraint.
+        For example, if `universal = False`, then the presence of the constraint
+        would not affect the output.
+
+        `apple_bundle()` supports building of universal binaries,
+        `apple_universal_executable()` is only needed if you have a standalone
+        binary target which is not embedded in an `apple_bundle()` (usually a
+        CLI tool).
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        buck.labels_arg()
+        | buck.contacts_arg()
+        | {
+            "executable": attrs.split_transition_dep(
+                cfg = cpu_split_transition,
+                doc = """
+                    A build target identifying the binary which will be built for multiple architectures.
+                    The target will be transitioned into different configurations, with distinct architectures.
+
+                    The target can be one of:
+                    - `apple_binary()` and `cxx_binary()`
+                    - `[shared]` subtarget of `apple_library()` and `cxx_library()`
+                    - `apple_library()` and `cxx_library()` which have `preferred_linkage = shared` attribute
+                """,
+            ),
+            "split_arch_dsym": attrs.bool(
+                default = False,
+                doc = """
+                    If enabled, each architecture gets its own dSYM binary. Use this if the combined
+                    universal dSYM binary exceeds 4GiB.
+                """,
+            ),
+            "universal": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                    Controls whether the output is universal binary. Any value overrides the presence
+                    of the `config//cpu/constraints:universal-enabled` constraint. Read the rule docs
+                    for more information on resolution.
+                """,
+            ),
+        }
+        | apple_common.executable_name_for_universal_arg()
+        | apple_common.apple_toolchain_arg()
+        | apple_common.apple_tools_arg()
+    ),
+)
+
+apple_provisioning_profile_sources = prelude_rule(
+    name = "apple_provisioning_profile_sources",
+    docs = """
+        An `apple_provisioning_profile_sources()` rule specifies a set of provisioning profile
+        targets that are available for code signing Apple bundles. These profiles are used during
+        the signing step of `apple_bundle()` to match a valid, non-expired profile to the bundle
+        identifier and entitlements.
+    """,
+    impl = apple_provisioning_profile_sources_impl,
+    examples = None,
+    further = None,
+    attrs = {
+        "sources": attrs.list(attrs.dep(), default = []),
+    },
+)
+
+apple_simulators = prelude_rule(
+    name = "apple_simulators",
+    docs = """
+        An `apple_simulators()` rule configures the Apple simulator environment used for
+        running tests. It specifies the simulator broker, device type, OS version, and
+        setup parameters needed to launch and manage iOS/watchOS/tvOS simulators during
+        test execution.
+    """,
+    impl = apple_simulators_impl,
+    examples = None,
+    further = None,
+    attrs = {
+        "args": attrs.list(attrs.string(), default = []),
+        "broker": attrs.exec_dep(providers = [RunInfo]),
+        "idb_targets": attrs.exec_dep(providers = [RunInfo]),
+        "setup_timeout_seconds": attrs.option(attrs.int(), default = None),
+        "_simulator_device": attrs.default_only(attrs.string(default = read_root_config("apple", "simulator_device", ""))),
+        "_simulator_os_version": attrs.default_only(attrs.string(default = read_root_config("apple", "simulator_os_version", ""))),
+    },
+)
+
+apple_tools = prelude_rule(
+    name = "apple_tools",
+    impl = apple_tools_impl,
+    docs = """
+        The `apple_tools` rule exposes a set of supplementary tools
+        required by the Apple rules _internally_. Such tools are not
+        toolchain/SDK specific, they're just internal helper tools.
+    """,
+    examples = None,
+    further = None,
+    attrs = {
+        "adhoc_codesign_tool": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "assemble_bundle": attrs.exec_dep(providers = [RunInfo]),
+        "bundle_telemetry_logger": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "codesign_manifest_tree_postprocessor": attrs.exec_dep(providers = [RunInfo]),
+        "dedupe_swift_module_map": attrs.exec_dep(providers = [RunInfo]),
+        "dry_codesign_tool": attrs.exec_dep(providers = [RunInfo]),
+        "framework_sanitizer": attrs.exec_dep(providers = [RunInfo]),
+        "info_plist_processor": attrs.exec_dep(providers = [RunInfo]),
+        "ipa_package_maker": attrs.exec_dep(providers = [RunInfo]),
+        "make_modulemap": attrs.exec_dep(providers = [RunInfo]),
+        "make_vfsoverlay": attrs.exec_dep(providers = [RunInfo]),
+        "provisioning_manifest": attrs.exec_dep(providers = [RunInfo]),
+        "resolve_signing_context": attrs.exec_dep(providers = [RunInfo]),
+        "selective_debugging_scrubber": attrs.exec_dep(providers = [RunInfo]),
+        "signing_context_tree_postprocessor": attrs.exec_dep(providers = [RunInfo]),
+        "signing_info": attrs.exec_dep(providers = [RunInfo]),
+        "split_arch_combine_dsym_bundles_tool": attrs.exec_dep(providers = [RunInfo]),
+        "spm_packager": attrs.exec_dep(providers = [RunInfo]),
+        "static_archive_linker": attrs.exec_dep(providers = [RunInfo]),
+        "swiftmodule_change_analysis": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "xcframework_maker": attrs.exec_dep(providers = [RunInfo]),
+    },
+)
+
+cxx_universal_executable = prelude_rule(
+    name = "cxx_universal_executable",
+    impl = cxx_universal_executable_impl,
+    docs = """
+        A `cxx_universal_executable()` rule takes a target via its
+        `binary` attribute, builds it for multiple architectures and
+        combines the result into a single binary using `lipo`.
+
+        The output of the rule is a universal binary:
+        - If `config//cpu/constraints:universal-enabled` is present in the target platform.
+        - If the `universal` attribute is set to `True`.
+
+        If none of the conditions are met, then the rule acts as a nop `alias()`.
+
+        The `universal` attribute, if present, takes precedence over constraint.
+        For example, if `universal = False`, then the presence of the constraint
+        would not affect the output.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        buck.labels_arg()
+        | buck.contacts_arg()
+        | {
+            "executable": attrs.split_transition_dep(
+                cfg = cpu_split_transition,
+                doc = """
+                    A build target identifying the binary which will be built for multiple architectures.
+                    The target will be transitioned into different configurations, with distinct architectures.
+
+                    The target can be one of:
+                    - `cxx_binary()`
+                    - `[shared]` subtarget `cxx_library()`
+                    - `cxx_library()` which have `preferred_linkage = shared` attribute
+                """,
+            ),
+            "universal": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                    Controls whether the output is universal binary. Any value overrides the presence
+                    of the `config//cpu/constraints:universal-enabled` constraint. Read the rule docs
+                    for more information on resolution.
+                """,
+            ),
+            "_cxx_toolchain": toolchains_common.cxx(),
+        }
+        | apple_common.executable_name_for_universal_arg()
+    ),
+)
+
+apple_ipa_package = prelude_rule(
+    name = "apple_ipa_package",
+    docs = """
+        An `apple_ipa_package()` rule packages an `apple_bundle()` into an IPA file
+        for distribution. The IPA is a compressed archive containing the application
+        bundle in the standard format expected by App Store Connect and ad-hoc
+        distribution workflows.
+    """,
+    impl = apple_ipa_package_impl,
+    attrs = apple_ipa_package_attribs(),
+)
+
+apple_xcframework = prelude_rule(
+    name = "apple_xcframework",
+    docs = """
+        An `apple_xcframework()` rule packages a framework target built for multiple platforms
+        (e.g., iOS device, iOS simulator, macOS) into a single `.xcframework` bundle that can
+        be distributed and consumed by Xcode projects or other build systems. The framework is
+        built per-platform via a split transition and then combined.
+    """,
+    impl = apple_xcframework_impl,
+    attrs = buck.labels_arg()
+    | buck.contacts_arg()
+    | {
+        "framework": attrs.split_transition_dep(cfg = framework_split_transition),
+        "framework_name": attrs.option(attrs.string(), default = None),
+        "framework_name_from_product_name": attrs.bool(default = False),
+        "include_dsym": attrs.option(attrs.bool(), default = None),
+        "platforms": attrs.list(attrs.string(), default = []),
+    }
+    | apple_common.apple_tools_arg(),
+)
+
+apple_spm_package = prelude_rule(
+    name = "apple_spm_package",
+    docs = """
+        An `apple_spm_package()` rule packages a set of dependencies into a Swift Package
+        Manager (SPM) compatible package. This enables distributing buck2-built libraries
+        in a format that can be consumed by SPM-based projects.
+    """,
+    impl = apple_spm_package_impl,
+    attrs = (
+        apple_common.deps_arg()
+        | {
+            "package_name": attrs.string(),
+            "_apple_tools": attrs.exec_dep(default = "prelude//apple/tools:apple-tools", providers = [AppleToolsInfo]),
+        }
+    ),
+)
+
+apple_static_archive = prelude_rule(
+    name = "apple_static_archive",
+    docs = """
+        An `apple_static_archive()` rule combines one or more Apple libraries into a single
+        static archive (`.a` file). This is useful for distributing prebuilt libraries
+        where multiple object files need to be bundled together.
+    """,
+    impl = apple_static_archive_impl,
+    attrs = (
+        buck.labels_arg()
+        | buck.contacts_arg()
+        | apple_common.deps_arg()
+        | {
+            "archive_name": attrs.option(attrs.string(), default = None),
+            "distribution_flat_dep": attrs.option(attrs.dep(), default = None),
+            "flat_deps": attrs.list(attrs.dep(), default = []),
+            VALIDATION_DEPS_ATTR_NAME: VALIDATION_DEPS_ATTR_TYPE,
+        }
+        | apple_common.apple_tools_arg()
+        | apple_common.apple_toolchain_arg()
+    ),
+)
+
+apple_selective_debugging = prelude_rule(
+    name = "apple_selective_debugging",
+    docs = """
+        An `apple_selective_debugging()` rule configures which targets have debug information
+        included in the final binary. By specifying include/exclude patterns for build targets
+        or regular expressions, you can reduce binary size by stripping debug info from
+        dependencies you don't need to debug.
+    """,
+    impl = apple_selective_debugging_impl,
+    attrs = {
+        "exclude_build_target_patterns": attrs.list(attrs.string(), default = []),
+        "exclude_regular_expressions": attrs.list(attrs.string(), default = []),
+        "include_build_target_patterns": attrs.list(attrs.string(), default = []),
+        "include_regular_expressions": attrs.list(attrs.string(), default = []),
+        "json_type": attrs.enum(SelectiveDebuggingJsonTypes),
+        "targets_json_file": attrs.option(attrs.source(), default = None),
+    }
+    | apple_common.apple_tools_arg(),
+)
+
+apple_macos_bundle = prelude_rule(
+    name = "apple_macos_bundle",
+    docs = """
+        An `apple_macos_bundle()` rule generates a macOS application bundle. It applies
+        the macOS platform transition automatically, so the binary and its dependencies
+        are built for macOS regardless of the default target platform. Use case is Mac
+        Catalyst apps which want to include an AppKit framework.
+    """,
+    impl = apple_macos_bundle_impl,
+    attrs = apple_macos_bundle_attrs(),
+    cfg = macos_transition,
+)
+
+apple_watchos_bundle = prelude_rule(
+    name = "apple_watchos_bundle",
+    docs = """
+        An `apple_watchos_bundle()` rule generates a watchOS application bundle. It applies
+        the watchOS platform transition automatically, so the binary and its dependencies
+        are built for watchOS regardless of the default target platform.
+    """,
+    impl = apple_watchos_bundle_impl,
+    attrs = apple_watchos_bundle_attrs(),
+    cfg = watch_transition,
+)
+
+apple_resource_bundle = prelude_rule(
+    name = "apple_resource_bundle",
+    docs = """
+        An `apple_resource_bundle()` is a rule that exists for internal implementation reasons to compile resources for the Apple platform. It's used by the Apple rules and not for public consumption.
+    """,
+    impl = apple_resource_bundle_impl,
+    attrs = (
+        buck.labels_arg()
+        | buck.contacts_arg()
+        | apple_common.deps_arg()
+        | apple_common.ibtool_flags_arg()
+        | apple_common.product_name_arg()
+        | apple_common.resource_group_arg()
+        | {
+            "binary": attrs.option(attrs.split_transition_dep(cfg = cpu_split_transition), default = None),
+            "copy_public_framework_headers": attrs.option(attrs.bool(), default = None),
+            "extension": attrs.one_of(attrs.enum(AppleBundleExtension), attrs.string()),
+            "info_plist": attrs.source(),
+            "module_map": attrs.option(attrs.one_of(attrs.enum(AppleFrameworkBundleModuleMapType), attrs.source()), default = None),
+            "privacy_manifest": attrs.option(attrs.source(), default = None),
+            "product_name_from_module_name": attrs.bool(default = False),
+            "resource_group_map": RESOURCE_GROUP_MAP_ATTR,
+            "universal": attrs.option(attrs.bool(), default = None),
+            # Only include macOS hosted toolchains, so we compile resources directly on Mac RE
+            "_apple_toolchain": get_apple_resources_toolchain_attr(),
+            # Because `apple_resource_bundle` is a proxy for `apple_bundle`, we need to get `name`
+            # field of the `apple_bundle`, as it's used as a fallback value in Info.plist.
+            "_bundle_target_name": attrs.string(),
+            "_compile_resources_locally_override": attrs.option(attrs.bool(), default = None),
+        }
+        | get_apple_info_plist_build_system_identification_attrs()
+        | apple_common.apple_tools_arg()
+        | apple_common.asset_catalogs_compilation_options_arg()
+        | apple_common.info_plist_substitutions_arg()
+        | apple_common.enforce_minimum_os_plist_key()
+        | apple_common.skip_private_swiftinterface_arg()
+    ),
+)
+
+apple_resource_dedupe_alias = prelude_rule(
+    name = "apple_resource_dedupe_alias",
+    docs = """
+        An `apple_resource_dedupe_alias()` rule creates an alias for a resource target
+        with a resource configuration transition applied. This enables the resource
+        deduplication pipeline to dedupe the same resources across arch-transitions (i.e., universal binaries - x86 + arm64).
+    """,
+    impl = apple_resource_dedupe_alias_impl,
+    attrs = {
+        "actual": attrs.transition_dep(cfg = apple_resource_transition),
+    }
+    | apple_common.skip_universal_resource_dedupe_arg(),
+)
+
+mockingbird_mock = prelude_rule(
+    name = "mockingbird_mock",
+    docs = """
+        A `mockingbird_mock()` rule generates mock implementations using the Mockingbird
+        mocking framework. The generated mocks can be used in `apple_test()` targets for
+        unit testing Swift and Objective-C code.
+    """,
+    impl = mockingbird_mock_impl,
+    attrs = mockingbird_mock_attrs(),
+)
+
+resource_group_map = prelude_rule(
+    name = "resource_group_map",
+    docs = """
+        A `resource_group_map()` rule defines a mapping of resource groups for an
+        `apple_bundle()`. Each group specifies which dependencies' resources should be
+        placed together, enabling fine-grained control over how resources are partitioned
+        across bundles in a multi-bundle application (e.g., app extensions, plugins).
+    """,
+    impl = resource_group_map_impl,
+    attrs = {
+        "map": attrs.list(
+            attrs.tuple(
+                attrs.string(),
+                attrs.list(
+                    attrs.tuple(
+                        attrs.one_of(attrs.dep(), attrs.list(attrs.dep())),
+                        attrs.enum(Traversal.values()),
+                        attrs.option(attrs.one_of(attrs.dep(providers = [GroupFilterInfo]), attrs.string())),
+                    ),
+                ),
+            ),
+        ),
+    },
+)
+
+apple_xcuitest = prelude_rule(
+    name = "apple_xcuitest",
+    docs = """
+        An `apple_xcuitest()` rule defines an XCUITest UI test target. It builds a test
+        runner bundle that launches the application under test and executes UI automation
+        tests using Apple's XCTest UI testing framework.
+    """,
+    impl = apple_xcuitest_impl,
+    attrs = apple_xcuitest_extra_attrs(),
+)
+
+apple_info_plist = prelude_rule(
+    name = "apple_info_plist",
+    docs = """
+        An `apple_info_plist()` rule defines mutations to apply to an `Info.plist` file.
+        It supports update, merge, and restricted merge operations, allowing you to
+        programmatically set, override, or combine plist entries during the build.
+    """,
+    impl = apple_info_plist_impl,
+    attrs = {
+        "mutations": attrs.list(
+            attrs.one_of(
+                attrs.tuple(
+                    attrs.enum(UpdateOperations.values()),
+                    attrs.dict(key = attrs.string(), value = attrs.one_of(attrs.string(), attrs.bool(), attrs.int())),
+                ),
+                attrs.tuple(attrs.enum(MergeOperations.values()), attrs.source()),
+                attrs.tuple(
+                    attrs.enum(RestrictedMergeOperations.values()),
+                    attrs.source(),
+                    attrs.dict(key = attrs.string(), value = attrs.one_of(attrs.string(), attrs.bool())),
+                ),
+            )
+        ),
+        "src": attrs.source(),
+        "xml": attrs.bool(default = False),
+        "_apple_tools": attrs.exec_dep(default = "prelude//apple/tools:apple-tools", providers = [AppleToolsInfo]),
+    },
+)
+
+apple_rules = struct(
+    apple_app_intents = apple_app_intents,
+    apple_asset_catalog = apple_asset_catalog,
+    apple_binary = apple_binary,
+    apple_bundle = apple_bundle,
+    apple_info_plist = apple_info_plist,
+    apple_library = apple_library,
+    apple_library_for_distribution = apple_library_for_distribution,
+    apple_macos_bundle = apple_macos_bundle,
+    apple_metal_library = apple_metal_library,
+    apple_package = apple_package,
+    apple_ipa_package = apple_ipa_package,
+    apple_provisioning_profile_sources = apple_provisioning_profile_sources,
+    apple_resource = apple_resource,
+    apple_test = apple_test,
+    apple_toolchain = apple_toolchain,
+    apple_tools = apple_tools,
+    apple_resource_bundle = apple_resource_bundle,
+    apple_resource_dedupe_alias = apple_resource_dedupe_alias,
+    apple_selective_debugging = apple_selective_debugging,
+    apple_simulators = apple_simulators,
+    apple_spm_package = apple_spm_package,
+    apple_static_archive = apple_static_archive,
+    apple_universal_executable = apple_universal_executable,
+    apple_watchos_bundle = apple_watchos_bundle,
+    apple_xcframework = apple_xcframework,
+    apple_xcuitest = apple_xcuitest,
+    core_data_model = core_data_model,
+    cxx_universal_executable = cxx_universal_executable,
+    mockingbird_mock = mockingbird_mock,
+    prebuilt_apple_framework = prebuilt_apple_framework,
+    required_reasons_tools = required_reasons_tools,
+    resource_group_map = resource_group_map,
+    scene_kit_assets = scene_kit_assets,
+    swift_toolchain = swift_toolchain,
+)
diff --git a/buck2/prelude/apple/apple_rules_impl.bzl b/buck2/prelude/apple/apple_rules_impl.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_rules_impl.bzl
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# @oss-disable[end= ]: load("@prelude//apple/meta_only:meta_only_rules.bzl", "meta_only_apple_rule_attributes", "meta_only_apple_rule_implementations")
+
+# @oss-disable[end= ]: implemented_rules = {} | meta_only_apple_rule_implementations()
+implemented_rules = {} # @oss-enable
+
+# @oss-disable[end= ]: extra_attributes = {} | meta_only_apple_rule_attributes()
+extra_attributes = {} # @oss-enable
diff --git a/buck2/prelude/apple/apple_rules_impl_utility.bzl b/buck2/prelude/apple/apple_rules_impl_utility.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_rules_impl_utility.bzl
@@ -0,0 +1,306 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:attrs_validators.bzl", "validation_common")
+load("@prelude//apple:apple_bundle_types.bzl", "AppleBundleResourceInfo", "AppleBundleTypeAttributeType")
+load("@prelude//apple:apple_code_signing_types.bzl", "CodeSignConfiguration", "CodeSignType")
+load("@prelude//apple:apple_common.bzl", "apple_common")
+load("@prelude//apple:apple_test_device_types.bzl", "AppleTestDeviceType")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load("@prelude//apple:resource_groups.bzl", "RESOURCE_GROUP_MAP_ATTR")
+load("@prelude//apple/swift:swift_incremental_support.bzl", "SwiftCompilationMode")
+load("@prelude//apple/user:apple_selective_debugging.bzl", "AppleSelectiveDebuggingInfo")
+load("@prelude//apple/user:cpu_split_transition.bzl", "cpu_split_transition")
+load("@prelude//cxx:headers.bzl", "CPrecompiledHeaderInfo")
+load("@prelude//ide_integrations/xcode:scheme_settings.bzl", "XCODE_SCHEME_SETTINGS_ATTR_NAME", "XCODE_SCHEME_SETTINGS_ATTR_TYPE")
+load("@prelude//linking:execution_preference.bzl", "link_execution_preference_attr")
+load("@prelude//linking:link_info.bzl", "LinkOrdering")
+load("@prelude//utils:buckconfig.bzl", "read_bool")
+load("@prelude//utils:clear_platform.bzl", "clear_platform_transition")
+
+AppleFrameworkBundleModuleMapType = ["auto"]
+
+def get_apple_bundle_toolchain_attr():
+    return attrs.toolchain_dep(default = "toolchains//:apple-bundle", providers = [AppleToolchainInfo])
+
+def get_apple_resources_toolchain_attr():
+    return attrs.toolchain_dep(default = "toolchains//:apple-resources", providers = [AppleToolchainInfo])
+
+def get_apple_xctoolchain_attr():
+    return attrs.toolchain_dep(default = "toolchains//:apple-xctoolchain")
+
+def get_apple_xctoolchain_bundle_id_attr():
+    return attrs.toolchain_dep(default = "toolchains//:apple-xctoolchain-bundle-id")
+
+def get_enable_library_evolution():
+    return attrs.bool(
+        default = select({
+            "DEFAULT": False,
+            "config//features/apple:swift_library_evolution_enabled": True,
+        })
+    )
+
+def _strict_provisioning_profile_search_default_attr():
+    default_value = read_root_config("apple", "strict_provisioning_profile_search", "true").lower() == "true"
+    return attrs.bool(
+        default = select({
+            "DEFAULT": default_value,
+            "config//features/apple:strict_provisioning_profile_search_enabled": True,
+        })
+    )
+
+def _fast_adhoc_signing_enabled_default_attr():
+    return attrs.bool(
+        default = select({
+            "DEFAULT": True,
+            "config//features/apple:fast_adhoc_signing_disabled": False,
+            "config//features/apple:fast_adhoc_signing_enabled": True,
+        })
+    )
+
+def _skip_adhoc_resigning_scrubbed_frameworks_default_attr():
+    default_value = read_root_config("apple", "skip_adhoc_resigning_scrubbed_frameworks", "").lower() == "true"
+    return attrs.bool(
+        default = select({
+            "DEFAULT": default_value,
+            "config//features/apple/constraints:skip_adhoc_resigning_scrubbed_frameworks_disabled": False,
+            "config//features/apple/constraints:skip_adhoc_resigning_scrubbed_frameworks_enabled": True,
+        })
+    )
+
+def _versioned_macos_bundle_default_value():
+    return select({
+        "DEFAULT": False,
+        "config//features/apple/constraints:versioned_macos_bundle_false": False,
+        "config//features/apple/constraints:versioned_macos_bundle_true": True,
+    })
+
+def _include_build_info_file_default_value():
+    return select({
+        "DEFAULT": select({
+            "DEFAULT": read_root_config("apple", "include_build_info_file", "false").lower() == "true",
+            # Unless explicitly requested, production builds (aka App Store/Developer ID) do not include internal build info file
+            "config//build_mode/apple/constraints:build_mode[production]": False,
+        }),
+        "config//features/apple/constraints:include_build_info_file[disabled]": False,
+        "config//features/apple/constraints:include_build_info_file[enabled]": True,
+    })
+
+APPLE_ARCHIVE_OBJECTS_LOCALLY_OVERRIDE_ATTR_NAME = "_archive_objects_locally_override"
+APPLE_USE_ENTITLEMENTS_WHEN_ADHOC_CODE_SIGNING_CONFIG_OVERRIDE_ATTR_NAME = "_use_entitlements_when_adhoc_code_signing"
+APPLE_USE_ENTITLEMENTS_WHEN_ADHOC_CODE_SIGNING_ATTR_NAME = "use_entitlements_when_adhoc_code_signing"
+APPLE_EMBED_PROVISIONING_PROFILE_WHEN_ADHOC_CODE_SIGNING_CONFIG_OVERRIDE_ATTR_NAME = "_embed_provisioning_profile_when_adhoc_code_signing"
+APPLE_EMBED_PROVISIONING_PROFILE_WHEN_ADHOC_CODE_SIGNING_ATTR_NAME = "embed_provisioning_profile_when_adhoc_code_signing"
+
+APPLE_VALIDATION_DEPS_ATTR_NAME = "validation_deps"
+APPLE_VALIDATION_DEPS_ATTR_TYPE = attrs.set(attrs.dep(), sorted = True, default = [])
+
+def get_apple_info_plist_build_system_identification_attrs():
+    return {
+        "info_plist_identify_build_system": attrs.option(attrs.bool(), default = None),
+        "_info_plist_identify_build_system_default": attrs.bool(default = False),
+    }
+
+def get_skip_swift_incremental_outputs_attrs():
+    return {
+        "_skip_swift_incremental_outputs": attrs.bool(default = read_bool("apple", "skip_swift_incremental_outputs", False, False, True)),
+    }
+
+def get_swift_incremental_file_hashing_attrs():
+    return {
+        "swift_incremental_file_hashing": attrs.bool(default = read_bool("apple", "swift_incremental_file_hashing", False, False, True)),
+    }
+
+def get_swift_incremental_remote_outputs_attrs():
+    return {
+        "incremental_remote_outputs": attrs.bool(default = read_bool("apple", "incremental_remote_outputs", False, False, True)),
+    }
+
+def get_swift_incremental_logging_attrs():
+    return {
+        "swift_incremental_logging": attrs.bool(default = read_bool("apple", "swift_incremental_logging_enabled", False, False, True)),
+    }
+
+def get_incremental_split_actions_attrs():
+    return {
+        "_swift_incremental_split_actions": attrs.bool(default = read_bool("apple", "swift_incremental_split_actions", False, False, True)),
+    }
+
+def get_incremental_swiftmodule_action_attrs():
+    return {
+        "_swift_incremental_swiftmodule_action": attrs.bool(default = read_bool("apple", "swift_incremental_swiftmodule_action", False, False, True)),
+    }
+
+def _apple_bundle_like_common_attrs():
+    # `apple_bundle()` and `apple_test()` share a common set of extra attrs
+    attribs = {
+        # Target-level attribute always takes precedence over buckconfigs.
+        "code_signing_configuration": attrs.option(attrs.enum(CodeSignConfiguration.values()), default = None),
+        "codesign_type": attrs.option(attrs.enum(CodeSignType.values()), default = None),
+        "entitlements_verification_check_enabled": attrs.bool(
+            default = select({
+                "DEFAULT": read_bool("apple", "entitlements_verification_check_enabled", default = True, root_cell = True),
+                "config//features/apple:entitlements_verification_check_disabled": False,
+                "config//features/apple:entitlements_verification_check_enabled": True,
+            })
+        ),
+        "fast_adhoc_signing_enabled": attrs.option(attrs.bool(), default = None),
+        "include_build_info_file": attrs.bool(default = _include_build_info_file_default_value()),
+        "include_build_info_file_in_bundles_with_extensions": attrs.list(attrs.string(), default = ["app"]),
+        "provisioning_profile_filter": attrs.option(attrs.string(), default = None),
+        "skip_adhoc_resigning_scrubbed_frameworks": attrs.option(attrs.bool(), default = None),
+        "strict_provisioning_profile_search": attrs.option(attrs.bool(), default = None),
+        "versioned_macos_bundle": attrs.bool(default = _versioned_macos_bundle_default_value()),
+        "_apple_xctoolchain": get_apple_xctoolchain_attr(),
+        "_apple_xctoolchain_bundle_id": get_apple_xctoolchain_bundle_id_attr(),
+        "_bundling_cache_buster": attrs.option(attrs.string(), default = None),
+        "_bundling_log_file_enabled": attrs.bool(default = False),
+        "_bundling_log_file_level": attrs.option(attrs.string(), default = None),
+        "_code_signing_configuration": attrs.option(attrs.enum(CodeSignConfiguration.values()), default = None),
+        "_codesign_command_override": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "_codesign_identities_command_override": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "_codesign_type": attrs.option(attrs.enum(CodeSignType.values()), default = None),
+        "_compile_resources_locally_override": attrs.option(attrs.bool(), default = None),
+        "_fast_adhoc_signing_enabled_default": _fast_adhoc_signing_enabled_default_attr(),
+        "_fast_adhoc_signing_probe_enabled": attrs.bool(default = False),
+        "_fast_provisioning_profile_parsing_enabled": attrs.bool(default = False),
+        "_incremental_bundling_enabled": attrs.bool(default = False),
+        "_no_check_certificates": attrs.bool(default = False),
+        "_profile_bundling_enabled": attrs.bool(default = False),
+        "_provisioning_profile_sources": attrs.dep(default = "fbsource//xplat/buck2/platform/apple:provisioning_profile_sources"),
+        "_resource_bundle": attrs.option(attrs.dep(providers = [AppleBundleResourceInfo]), default = None),
+        "_skip_adhoc_resigning_scrubbed_frameworks_default": _skip_adhoc_resigning_scrubbed_frameworks_default_attr(),
+        "_skip_adhoc_resigning_scrubbed_frameworks_override": attrs.option(attrs.bool(), default = None),
+        "_strict_provisioning_profile_search_default": _strict_provisioning_profile_search_default_attr(),
+        APPLE_USE_ENTITLEMENTS_WHEN_ADHOC_CODE_SIGNING_CONFIG_OVERRIDE_ATTR_NAME: attrs.option(attrs.bool(), default = None),
+        APPLE_USE_ENTITLEMENTS_WHEN_ADHOC_CODE_SIGNING_ATTR_NAME: attrs.bool(default = False),
+        APPLE_EMBED_PROVISIONING_PROFILE_WHEN_ADHOC_CODE_SIGNING_CONFIG_OVERRIDE_ATTR_NAME: attrs.option(attrs.bool(), default = None),
+        APPLE_EMBED_PROVISIONING_PROFILE_WHEN_ADHOC_CODE_SIGNING_ATTR_NAME: attrs.bool(default = False),
+        APPLE_VALIDATION_DEPS_ATTR_NAME: APPLE_VALIDATION_DEPS_ATTR_TYPE,
+        XCODE_SCHEME_SETTINGS_ATTR_NAME: XCODE_SCHEME_SETTINGS_ATTR_TYPE,
+    }
+    attribs.update(get_apple_info_plist_build_system_identification_attrs())
+    attribs.update(apple_common.apple_tools_arg())
+    attribs.update(apple_common.enforce_minimum_os_plist_key())
+    return attribs
+
+def apple_test_extra_attrs():
+    # To build an `apple_test`, one needs to first build a shared `apple_library` then
+    # wrap this test library into an `apple_bundle`. Because of this, `apple_test` has attributes
+    # from both `apple_library` and `apple_bundle`.
+    attribs = {
+        # Expected by `apple_bundle`, for `apple_test` this field is always None.
+        "binary": attrs.option(attrs.dep(), default = None),
+        "enable_library_evolution": attrs.option(attrs.bool(), default = None),
+        # The resulting test bundle should have .xctest extension.
+        "extension": attrs.string(),
+        "link_execution_preference": link_execution_preference_attr(),
+        "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),
+        "precompiled_header": attrs.option(attrs.dep(providers = [CPrecompiledHeaderInfo]), default = None),
+        # Expected by `apple_bundle`, for `apple_test` this field is always None.
+        "resource_group": attrs.option(attrs.string(), default = None),
+        # Expected by `apple_bundle`, for `apple_test` this field is always None.
+        "resource_group_map": attrs.option(attrs.string(), default = None),
+        "sanitizer_runtime_enabled": attrs.option(attrs.bool(), default = None),
+        # Tests default to unstripped so they can be debugged.
+        "strip_level": attrs.default_only(attrs.string(default = "unstripped")),
+        "swift_compilation_mode": attrs.enum(SwiftCompilationMode.values(), default = "wmo"),
+        "swift_package_name": attrs.option(attrs.string(), default = None),
+        "swift_testing": attrs.bool(default = False),
+        "test_device_type": attrs.enum(AppleTestDeviceType.values(), default = "default"),
+        "test_re_capabilities": attrs.option(
+            attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False),
+            default = None,
+            doc = """
+            An optional dictionary with the RE capabilities for the test execution.
+            Overrides a default selection mechanism.
+        """,
+        ),
+        "test_re_use_case": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+            An optional name of the RE use case for the test execution.
+            Overrides a default selection mechanism.
+        """,
+        ),
+        "_enable_library_evolution": get_enable_library_evolution(),
+        "_ipad_simulator": attrs.transition_dep(
+            cfg = clear_platform_transition, default = "fbsource//xplat/buck2/platform/apple:ipad_simulator", providers = [LocalResourceInfo]
+        ),
+        "_iphone_booted_simulator": attrs.transition_dep(
+            cfg = clear_platform_transition, default = "fbsource//xplat/buck2/platform/apple:iphone_booted_simulator", providers = [LocalResourceInfo]
+        ),
+        "_iphone_unbooted_simulator": attrs.transition_dep(
+            cfg = clear_platform_transition, default = "fbsource//xplat/buck2/platform/apple:iphone_unbooted_simulator", providers = [LocalResourceInfo]
+        ),
+        "_swift_enable_testing": attrs.default_only(attrs.bool(default = True)),
+        "_watch_simulator": attrs.transition_dep(
+            cfg = clear_platform_transition, default = "fbsource//xplat/buck2/platform/apple:watch_simulator", providers = [LocalResourceInfo]
+        ),
+    } | validation_common.attrs_validators_arg()
+    attribs.update(apple_common.apple_toolchain_arg())
+    attribs.update(apple_common.minimum_os_version_arg())
+    attribs.update(_apple_bundle_like_common_attrs())
+    attribs.update(get_swift_incremental_file_hashing_attrs())
+    attribs.update(get_swift_incremental_logging_attrs())
+    attribs.update(get_skip_swift_incremental_outputs_attrs())
+    attribs.update(get_incremental_split_actions_attrs())
+    attribs.update(get_incremental_swiftmodule_action_attrs())
+    return attribs
+
+def apple_xcuitest_extra_attrs():
+    attribs = {
+        # This is ignored, but required for info plist processing.
+        "binary": attrs.option(attrs.source(), default = None),
+        "codesign_identity": attrs.option(attrs.string(), default = None),
+        "enable_library_evolution": attrs.option(attrs.bool(), default = None),
+        "entitlements_file": attrs.option(attrs.source(), default = None),
+        "extension": attrs.default_only(attrs.string(default = "app")),
+        "incremental_bundling_enabled": attrs.bool(default = False),
+        "info_plist": attrs.source(),
+        "info_plist_substitutions": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),
+        # The test bundle to package in the UI test runner app.
+        "test_bundle": attrs.dep(),
+        "_enable_library_evolution": get_enable_library_evolution(),
+    }
+    attribs.update(apple_common.target_sdk_version())
+    attribs.update(apple_common.apple_toolchain_arg())
+    attribs.update(_apple_bundle_like_common_attrs())
+
+    return attribs
+
+def _embed_xctest_frameworks_default_value():
+    return select({
+        "DEFAULT": False,
+        # Xcode copies XCTest frameworks to test host apps, required when the
+        # selected Xcode version != Xcode version used to build an app under test
+        "config//marker/apple/constraints:embed_xctest_frameworks[enabled]": True,
+    })
+
+def apple_bundle_extra_attrs():
+    attribs = {
+        "binary": attrs.option(attrs.split_transition_dep(cfg = cpu_split_transition), default = None),
+        "bundle_type": attrs.option(attrs.enum(AppleBundleTypeAttributeType.values()), default = None),
+        "copy_public_framework_headers": attrs.option(attrs.bool(), default = None),
+        "embed_xctest_frameworks": attrs.bool(default = _embed_xctest_frameworks_default_value()),
+        "module_map": attrs.option(attrs.one_of(attrs.enum(AppleFrameworkBundleModuleMapType), attrs.source()), default = None),
+        "resource_group_map": RESOURCE_GROUP_MAP_ATTR,
+        "selective_debugging": attrs.option(attrs.dep(providers = [AppleSelectiveDebuggingInfo]), default = None),
+        "split_arch_dsym": attrs.bool(default = False),
+        "universal": attrs.option(attrs.bool(), default = None),
+        "validate_rrapi_usage": attrs.bool(default = False),
+        "_apple_toolchain": get_apple_bundle_toolchain_attr(),
+        "_codesign_entitlements": attrs.option(attrs.source(), default = None),
+    }
+    attribs.update(_apple_bundle_like_common_attrs())
+    attribs.update(apple_common.entitlements_suffixed_key_map_arg())
+    attribs.update(apple_common.entitlements_removed_keys_arg())
+    attribs.update(apple_common.entitlements_removed_values_map_arg())
+    attribs.update(apple_common.minimum_os_version_arg())
+    return attribs
diff --git a/buck2/prelude/apple/apple_sdk.bzl b/buck2/prelude/apple/apple_sdk.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_sdk.bzl
@@ -0,0 +1,16 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+
+def get_apple_sdk_name(ctx: AnalysisContext) -> str:
+    """
+    Get the SDK defined on the toolchain.
+    Will throw if the `_apple_toolchain` is not present.
+    """
+    return ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_name
diff --git a/buck2/prelude/apple/apple_sdk_metadata.bzl b/buck2/prelude/apple/apple_sdk_metadata.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_sdk_metadata.bzl
@@ -0,0 +1,105 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+AppleSdkMetadata = record(
+    name = field(str),
+    target_device_flags = field(list[str], []),
+    is_ad_hoc_code_sign_sufficient = field(bool),
+    info_plist_supported_platforms_values = field(list[str]),
+    min_version_plist_info_key = field(str),
+    actool_platform_override = field([str, None], None),
+)
+
+IPhoneOSSdkMetadata = AppleSdkMetadata(
+    name = "iphoneos",
+    target_device_flags = ["--target-device", "iphone", "--target-device", "ipad"],
+    is_ad_hoc_code_sign_sufficient = False,
+    info_plist_supported_platforms_values = ["iPhoneOS"],
+    min_version_plist_info_key = "MinimumOSVersion",
+)
+
+IPhoneSimulatorSdkMetadata = AppleSdkMetadata(
+    name = "iphonesimulator",
+    target_device_flags = ["--target-device", "iphone", "--target-device", "ipad"],
+    is_ad_hoc_code_sign_sufficient = True,
+    info_plist_supported_platforms_values = ["iPhoneSimulator"],
+    min_version_plist_info_key = "MinimumOSVersion",
+)
+
+TVOSSdkMetadata = AppleSdkMetadata(
+    name = "appletvos",
+    target_device_flags = ["--target-device", "tv"],
+    is_ad_hoc_code_sign_sufficient = False,
+    info_plist_supported_platforms_values = ["AppleTVOS"],
+    min_version_plist_info_key = "MinimumOSVersion",
+)
+
+TVSimulatorSdkMetadata = AppleSdkMetadata(
+    name = "appletvsimulator",
+    target_device_flags = ["--target-device", "tv"],
+    is_ad_hoc_code_sign_sufficient = True,
+    info_plist_supported_platforms_values = ["AppleTVSimulator"],
+    min_version_plist_info_key = "MinimumOSVersion",
+)
+
+WatchOSSdkMetadata = AppleSdkMetadata(
+    name = "watchos",
+    target_device_flags = ["--target-device", "watch"],
+    is_ad_hoc_code_sign_sufficient = False,
+    info_plist_supported_platforms_values = ["WatchOS"],
+    min_version_plist_info_key = "MinimumOSVersion",
+)
+
+WatchSimulatorSdkMetadata = AppleSdkMetadata(
+    name = "watchsimulator",
+    target_device_flags = ["--target-device", "watch"],
+    is_ad_hoc_code_sign_sufficient = True,
+    info_plist_supported_platforms_values = ["WatchSimulator"],
+    min_version_plist_info_key = "MinimumOSVersion",
+)
+
+MacOSXSdkMetadata = AppleSdkMetadata(
+    name = "macosx",
+    target_device_flags = ["--target-device", "mac"],
+    is_ad_hoc_code_sign_sufficient = True,
+    info_plist_supported_platforms_values = ["MacOSX"],
+    min_version_plist_info_key = "LSMinimumSystemVersion",
+)
+
+MacOSXCatalystSdkMetadata = AppleSdkMetadata(
+    name = "maccatalyst",
+    target_device_flags = [
+        "--target-device",
+        # TODO(T112097815): Support for macOS idiom
+        "ipad",
+        # Needed so that `actool` works generates app icons correctly
+        "--ui-framework-family",
+        "uikit",
+    ],
+    is_ad_hoc_code_sign_sufficient = True,
+    info_plist_supported_platforms_values = ["MacOSX"],
+    min_version_plist_info_key = "LSMinimumSystemVersion",
+    actool_platform_override = "macosx",
+)
+
+_SDK_MAP = {
+    IPhoneOSSdkMetadata.name: IPhoneOSSdkMetadata,
+    IPhoneSimulatorSdkMetadata.name: IPhoneSimulatorSdkMetadata,
+    TVOSSdkMetadata.name: TVOSSdkMetadata,
+    TVSimulatorSdkMetadata.name: TVSimulatorSdkMetadata,
+    WatchOSSdkMetadata.name: WatchOSSdkMetadata,
+    WatchSimulatorSdkMetadata.name: WatchSimulatorSdkMetadata,
+    MacOSXSdkMetadata.name: MacOSXSdkMetadata,
+    MacOSXCatalystSdkMetadata.name: MacOSXCatalystSdkMetadata,
+}
+
+def get_apple_sdk_metadata_for_sdk_name(name: str) -> AppleSdkMetadata:
+    sdk = _SDK_MAP.get(name)
+    if sdk == None:
+        fail("unrecognized sdk name: `{}`".format(name))
+    return sdk
diff --git a/buck2/prelude/apple/apple_simulators.bzl b/buck2/prelude/apple/apple_simulators.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_simulators.bzl
@@ -0,0 +1,27 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def apple_simulators_impl(ctx: AnalysisContext) -> list[Provider]:
+    cmd_args_list = [ctx.attrs.broker[RunInfo], "--simulator-manager", ctx.attrs.idb_targets[RunInfo]] + ctx.attrs.args
+    simulator_os_version = ctx.attrs._simulator_os_version
+    simulator_device = ctx.attrs._simulator_device
+    if simulator_os_version:
+        cmd_args_list += ["--os_version", simulator_os_version]
+    if simulator_device:
+        cmd_args_list += ["--device", simulator_device]
+    return [
+        DefaultInfo(),
+        LocalResourceInfo(
+            setup = cmd_args(cmd_args_list),
+            resource_env_vars = {
+                "DEVICE_SET_PATH": "device_set_path",
+                "DEVICE_UDID": "udid",
+            },
+            setup_timeout_seconds = ctx.attrs.setup_timeout_seconds,
+        ),
+    ]
diff --git a/buck2/prelude/apple/apple_static_archive.bzl b/buck2/prelude/apple/apple_static_archive.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_static_archive.bzl
@@ -0,0 +1,110 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifact_tset.bzl", "make_artifact_tset")
+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")
+load("@prelude//apple:apple_library.bzl", "AppleLibraryForDistributionInfo")
+load("@prelude//apple:apple_library_types.bzl", "AppleLibraryInfo")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//linking:link_info.bzl", "LinkStrategy", "get_link_args_for_strategy", "unpack_link_args_object_files_and_lazy_archives_only")
+load("@prelude//linking:linkables.bzl", "linkables")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+
+def apple_static_archive_impl(ctx: AnalysisContext) -> list[Provider]:
+    libtool = ctx.attrs._apple_toolchain[AppleToolchainInfo].libtool
+    static_archive_linker = ctx.attrs._apple_tools[AppleToolsInfo].static_archive_linker
+    archive_name = ctx.attrs.name if ctx.attrs.archive_name == None else ctx.attrs.archive_name
+    output = ctx.actions.declare_output(archive_name, has_content_based_path = False)
+
+    link_args = _get_static_link_args(ctx)
+    validation_deps_outputs = get_validation_deps_outputs(ctx)
+
+    # TODO(T193127271): Support thin archives
+    cmd = cmd_args([static_archive_linker, "--libtool", libtool, "--output", output.as_output(), link_args], hidden = validation_deps_outputs or [])
+    ctx.actions.run(cmd, category = "static_archive_linker", identifier = output.short_path)
+
+    providers = [DefaultInfo(default_output = output), _get_apple_library_info(ctx)] + _get_apple_library_for_distribution_info(ctx)
+
+    return providers
+
+def _get_apple_library_for_distribution_info(ctx: AnalysisContext) -> list[AppleLibraryForDistributionInfo]:
+    if ctx.attrs.distribution_flat_dep != None:
+        apple_library_for_distribution = ctx.attrs.distribution_flat_dep.get(AppleLibraryForDistributionInfo)
+        if apple_library_for_distribution != None:
+            return [apple_library_for_distribution]
+    return []
+
+def _get_apple_library_info(ctx: AnalysisContext) -> AppleLibraryInfo:
+    all_flat_deps = filter(None, ctx.attrs.flat_deps + [ctx.attrs.distribution_flat_dep])
+    flat_apple_library_infos = filter(None, [dep.get(AppleLibraryInfo) for dep in all_flat_deps])
+    flat_public_framework_headers = []
+    for apple_library_info in flat_apple_library_infos:
+        tset = apple_library_info.public_framework_headers._tset
+        if tset != None and tset.value:
+            for headers in tset.value:
+                flat_public_framework_headers += headers.artifacts
+
+    flat_header_tset = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        artifacts = flat_public_framework_headers,
+    )
+
+    apple_library_infos = filter(None, [dep.get(AppleLibraryInfo) for dep in ctx.attrs.deps])
+    public_framework_header_tset = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        children = [apple_library.public_framework_headers for apple_library in apple_library_infos] + [flat_header_tset],
+    )
+
+    swift_header = None
+    if ctx.attrs.distribution_flat_dep != None:
+        distribution_flat_dep_apple_library_info = ctx.attrs.distribution_flat_dep.get(AppleLibraryInfo)
+        if distribution_flat_dep_apple_library_info:
+            swift_header = distribution_flat_dep_apple_library_info.swift_header
+
+    return AppleLibraryInfo(
+        public_framework_headers = public_framework_header_tset,
+        swift_header = swift_header,
+        target = ctx.label,
+        labels = ctx.attrs.labels,
+    )
+
+def _get_static_link_args(ctx: AnalysisContext) -> list[ArgLike]:
+    args = []
+
+    for dep in ctx.attrs.flat_deps:
+        default_info = dep.get(DefaultInfo)
+        if default_info == None:
+            continue
+        default_outputs = default_info.default_outputs
+        if len(default_outputs) > 0:
+            args.append(default_outputs[0])
+
+    if ctx.attrs.distribution_flat_dep:
+        default_info = ctx.attrs.distribution_flat_dep.get(DefaultInfo)
+        if default_info != None:
+            default_outputs = default_info.default_outputs
+            if len(default_outputs) > 0:
+                args.append(default_outputs[0])
+
+    args = dedupe(args)
+
+    transitive_link_args = get_link_args_for_strategy(
+        ctx.actions,
+        ctx.label,
+        get_cxx_toolchain_info(ctx).linker_info,
+        [x.merged_link_info for x in linkables(ctx.attrs.deps)],
+        LinkStrategy("static"),
+        prefer_stripped = False,
+        transformation_spec_context = None,
+    )
+    args.append(unpack_link_args_object_files_and_lazy_archives_only(transitive_link_args))
+
+    return args
diff --git a/buck2/prelude/apple/apple_stripping.bzl b/buck2/prelude/apple/apple_stripping.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_stripping.bzl
@@ -0,0 +1,24 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//utils:expect.bzl", "expect")
+
+def apple_strip_args(ctx: AnalysisContext) -> cmd_args:
+    strip_flags_info = get_cxx_toolchain_info(ctx).strip_flags_info
+    if ctx.attrs.strip_level == "non_global":
+        flags = strip_flags_info.strip_non_global_flags
+    elif ctx.attrs.strip_level == "all":
+        flags = strip_flags_info.strip_all_flags
+    elif ctx.attrs.strip_level == "debug":
+        flags = strip_flags_info.strip_debug_flags
+    else:
+        fail("Unexpected strip level: " + ctx.attrs.strip_level)
+
+    expect(flags != None, "Strip flags are missing on toolchain")
+    return cmd_args(flags)
diff --git a/buck2/prelude/apple/apple_swift_stdlib.bzl b/buck2/prelude/apple/apple_swift_stdlib.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_swift_stdlib.bzl
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+_SKIP_COPYING_SWIFT_STDLIB_EXTENSIONS = [
+    ".framework",
+    ".appex",
+]
+
+def should_copy_swift_stdlib(bundle_extension: str) -> bool:
+    return bundle_extension not in _SKIP_COPYING_SWIFT_STDLIB_EXTENSIONS
diff --git a/buck2/prelude/apple/apple_target_sdk_version.bzl b/buck2/prelude/apple/apple_target_sdk_version.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_target_sdk_version.bzl
@@ -0,0 +1,96 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:versions.bzl", "TARGET_SDK_VERSIONS")
+load("@prelude//cxx:target_sdk_version.bzl", "get_target_sdk_version")
+
+# Taken from SDKSettings.json[VersionMap][iOSMac_macOS]
+_MACCATALYST_IOS_TO_MACOS_VERSION_MAP = {
+    "13.0": "10.15",  # Catalina
+    "13.1": "10.15",
+    "13.2": "10.15.1",
+    "13.3": "10.15.2",
+    "13.3.1": "10.15.3",
+    "13.4": "10.15.4",
+    "13.5": "10.15.5",
+    "13.6": "10.15.5",  # Xcode reported 10.15
+    "14.0": "11.0",  # Big Sur
+    "14.1": "11.0",
+    "14.2": "11.0",
+    "14.3": "11.1",
+    "14.4": "11.2",
+    "14.5": "11.3",
+    "14.6": "11.4",
+    "14.7": "11.5",
+    "15.0": "12.0",  # Monterey
+    "15.1": "12.1",  # Xcode reported 10.15
+    "15.2": "12.1",
+    "15.3": "12.2",
+    "15.4": "12.3",
+    "15.5": "12.4",
+    "15.6": "12.5",
+    "16.0": "13.0",  # Ventura
+    "16.1": "13.0",
+    "16.2": "13.1",
+    "16.3": "13.2",
+    "16.4": "13.3",
+    "16.5": "13.4",
+    "16.6": "13.5",
+    "17.0": "14.0",  # Sonoma
+    "17.1": "14.1",
+    "17.2": "14.2",
+    "17.3": "14.3",
+    "17.4": "14.4",
+    "17.5": "14.5",
+    "18.0": "15.0",  # Sequoia
+    "18.1": "15.1",
+    "18.2": "15.2",
+    "18.3": "15.3",
+    "18.4": "15.4",
+    "18.5": "15.5",
+    "18.6": "15.6",
+    "19.0": "16.0",  # Tahoe
+}
+
+_SDK_NAME_TO_PLATFORM_NAME_OVERRIDE_MAP = {
+    "maccatalyst": "macosx",
+}
+
+def get_target_sdk_version_map() -> dict[str, str]:
+    return {
+        maccatalyst_version: "config//version:constraint-value-target-sdk-version-{}".format(macos_version)
+        for maccatalyst_version, macos_version in _MACCATALYST_IOS_TO_MACOS_VERSION_MAP.items()
+        if macos_version in TARGET_SDK_VERSIONS
+    }
+
+def get_platform_version_for_sdk_version(sdk_name: str, sdk_version: str) -> str:
+    if sdk_name == "maccatalyst":
+        sdk_major, _ = sdk_version.split(".", 2)
+
+        # Version numbers are aligned from 26 and up
+        if int(sdk_major) >= 26:
+            return sdk_version
+
+        macos_version = _MACCATALYST_IOS_TO_MACOS_VERSION_MAP.get(sdk_version, None)
+        if macos_version == None:
+            fail("No macos version for maccatalyst version {}".format(sdk_version))
+        return macos_version
+
+    return sdk_version
+
+def get_platform_name_for_sdk(sdk_name: str) -> str:
+    return _SDK_NAME_TO_PLATFORM_NAME_OVERRIDE_MAP.get(sdk_name, sdk_name)
+
+# Returns the target_sdk_version specified for this build, falling
+# back to the toolchain version when unset.
+def get_min_deployment_version_for_node(ctx: AnalysisContext) -> str:
+    version = get_target_sdk_version(ctx)
+    if version == None:
+        fail("No target_sdk_version set on target or toolchain")
+
+    return version
diff --git a/buck2/prelude/apple/apple_test.bzl b/buck2/prelude/apple/apple_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_test.bzl
@@ -0,0 +1,421 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "project_artifacts",
+)
+load("@prelude//apple:apple_library.bzl", "AppleLibraryAdditionalParams", "apple_library_rule_constructor_params_and_swift_providers")
+load("@prelude//apple:apple_test_device_types.bzl", "AppleTestDeviceType", "get_default_test_device", "tpx_label_for_test_device_type")
+load("@prelude//apple:apple_test_frameworks_utility.bzl", "get_test_frameworks_bundle_parts")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+# @oss-disable[end= ]: load("@prelude//apple/meta_only:apple_test_local_execution.bzl", "local_test_execution_is_available")
+# @oss-disable[end= ]: load("@prelude//apple/meta_only:apple_test_re_capabilities.bzl", "apple_test_re_capabilities")
+# @oss-disable[end= ]: load("@prelude//apple/meta_only:apple_test_re_use_case.bzl", "apple_test_re_use_case")
+load("@prelude//apple/swift:swift_compilation.bzl", "get_swift_anonymous_targets")
+load("@prelude//apple/swift:swift_helpers.bzl", "uses_explicit_modules")
+load(
+    "@prelude//cxx:argsfiles.bzl",
+    "CompileArgsfile",  # @unused Used as a type
+)
+load("@prelude//cxx:cxx_library.bzl", "cxx_library_parameterized")
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",  # @unused Used as a type
+)
+load("@prelude//cxx:cxx_types.bzl", "CxxRuleProviderParams", "CxxRuleSubTargetParams", "xcode_data_enabled")
+load(
+    "@prelude//cxx:linker.bzl",
+    "SharedLibraryFlagOverrides",
+)
+load("@prelude//ide_integrations/xcode:data.bzl", "XcodeDataInfoKeys")
+load("@prelude//target_stats:target_stats_types.bzl", "TargetStatsInfo")
+load(
+    "@prelude//utils:dicts.bzl",
+    "flatten_x",
+)
+load("@prelude//utils:expect.bzl", "expect")
+load(":apple_bundle.bzl", "AppleBundlePartListConstructorParams", "get_apple_bundle_part_list")
+load(":apple_bundle_destination.bzl", "AppleBundleDestination", "bundle_relative_path_for_destination")
+load(":apple_bundle_part.bzl", "AppleBundlePart", "assemble_bundle", "bundle_output", "get_bundle_dir_name")
+load(":apple_bundle_types.bzl", "AppleBundleInfo")
+load(":apple_bundle_utility.bzl", "get_product_name")
+load(
+    ":apple_dsym.bzl",
+    "DSYM_SUBTARGET",
+    "DWARF_AND_DSYM_SUBTARGET",
+    "EXTENDED_DSYM_INFO_SUBTARGET",
+    "get_apple_dsym",
+    "get_apple_dsym_info_json",
+    "get_deps_debuggable_infos",
+)
+load(":apple_entitlements.bzl", "entitlements_link_flags")
+load(":apple_rpaths.bzl", "get_rpath_flags_for_tests")
+load(":apple_sdk.bzl", "get_apple_sdk_name")
+load(":apple_sdk_metadata.bzl", "WatchSimulatorSdkMetadata")
+load(":debug.bzl", "AppleDebuggableInfo")
+load(":xcode.bzl", "apple_populate_xcode_attributes")
+load(":xctest_swift_support.bzl", "XCTestSwiftSupportInfo")
+
+_XCTOOLCHAIN_SUB_TARGET = "xctoolchain"
+
+def apple_test_impl(ctx: AnalysisContext) -> [list[Provider], Promise]:
+    def get_apple_test_providers(deps_providers) -> list[Provider]:
+        xctest_bundle = bundle_output(ctx)
+
+        test_host_app_bundle = _get_test_host_app_bundle(ctx)
+        test_host_app_binary = _get_test_host_app_binary(ctx, test_host_app_bundle)
+        ui_test_target_app_bundle = _get_ui_test_target_app_bundle(ctx)
+
+        objc_bridging_header_flags = (
+            [
+                # Disable bridging header -> PCH compilation to mitigate an issue in Xcode 13 beta.
+                "-disable-bridging-pch",
+                "-import-objc-header",
+                cmd_args(ctx.attrs.bridging_header),
+            ]
+            if ctx.attrs.bridging_header
+            else []
+        )
+
+        shared_library_flags = ["-bundle"]
+
+        # Embedding entitlements (if present) means that we can skip adhoc codesigning
+        # any xctests altogether, provided the test dylib is adhoc signed
+        shared_library_flags += entitlements_link_flags(ctx) + get_rpath_flags_for_tests(ctx)
+
+        # The linker will include adhoc signature for ARM64 by default, lets
+        # ensure we always have an adhoc signature regardless of arch/linker logic.
+        shared_library_flags += ["-Wl,-adhoc_codesign"]
+
+        constructor_params = apple_library_rule_constructor_params_and_swift_providers(
+            ctx,
+            AppleLibraryAdditionalParams(
+                rule_type = "apple_test",
+                extra_exported_link_flags = get_test_framework_linker_flags(ctx) + _get_bundle_loader_flags(test_host_app_binary),
+                extra_swift_compiler_flags = _get_test_framework_search_paths_flags(ctx) + objc_bridging_header_flags,
+                shared_library_flags = SharedLibraryFlagOverrides(
+                    # When `-bundle` is used we can't use the `-install_name` args, thus we keep this field empty.
+                    shared_library_name_linker_flags_format = [],
+                    # When building Apple tests, we want to link with `-bundle` instead of `-shared` to allow
+                    # linking against the bundle loader.
+                    shared_library_flags = shared_library_flags,
+                ),
+                generate_sub_targets = CxxRuleSubTargetParams(
+                    compilation_database = True,
+                    headers = False,
+                    link_group_map = False,
+                    xcode_data = xcode_data_enabled(),
+                ),
+                generate_providers = CxxRuleProviderParams(
+                    compilation_database = True,
+                    default = False,
+                    linkable_graph = False,
+                    link_style_outputs = True,
+                    merged_native_link_info = False,
+                    omnibus_root = False,
+                    preprocessors = False,
+                    resources = False,
+                    shared_libraries = False,
+                    template_placeholders = False,
+                ),
+                populate_xcode_attributes_func = lambda local_ctx, **kwargs: _xcode_populate_attributes(
+                    ctx = local_ctx, xctest_bundle = xctest_bundle, test_host_app_binary = test_host_app_binary, test_host_app_bundle = test_host_app_bundle, **kwargs
+                ),
+                # We want to statically link the transitive dep graph of the apple_test()
+                # which we can achieve by forcing link group linking with
+                # an empty mapping (i.e., default mapping).
+                force_link_group_linking = True,
+            ),
+            deps_providers,
+            is_test_target = True,
+        )
+
+        cxx_library_output = cxx_library_parameterized(ctx, constructor_params)
+
+        # Locate the temporary binary that is bundled into the xctest in a binaries directory. When Xcode loads the test out of the target's output dir,
+        # it will utilize a binary with the test name from the output dir instead of the xctest bundle. Which then results in paths to test resources
+        # being incorrect. Locating the temporary binary elsewhere works around this issue.
+        test_binary_output = ctx.actions.declare_output("__binaries__", get_product_name(ctx), has_content_based_path = False)
+
+        # Rename in order to generate dSYM with correct binary name (dsymutil doesn't provide a way to control binary name in output dSYM bundle).
+        test_binary = ctx.actions.copy_file(test_binary_output, cxx_library_output.default_output.default)
+
+        binary_part = AppleBundlePart(source = test_binary, destination = AppleBundleDestination("executables"), new_name = ctx.attrs.name)
+        part_list_output = get_apple_bundle_part_list(ctx, AppleBundlePartListConstructorParams(binaries = [binary_part]))
+
+        xctest_swift_support_needed = None
+        debug_info = None
+        cxx_providers = []
+        for p in cxx_library_output.providers:
+            if isinstance(p, XCTestSwiftSupportInfo):
+                xctest_swift_support_needed = p.support_needed
+            elif isinstance(p, AppleDebuggableInfo):
+                debug_info = project_artifacts(ctx.actions, p.debug_info_tset)
+            elif isinstance(p, TargetStatsInfo):
+                cxx_providers.append(p)
+            elif isinstance(p, ValidationInfo):
+                cxx_providers.append(p)
+        expect(xctest_swift_support_needed != None, "Expected `XCTestSwiftSupportInfo` provider to be present")
+        expect(debug_info != None, "Expected `AppleDebuggableInfo` provider to be present")
+
+        bundle_parts = part_list_output.parts
+        if not ctx.attrs.embed_xctest_frameworks_in_test_host_app and get_apple_sdk_name(ctx) != WatchSimulatorSdkMetadata.name:
+            # The XCTest frameworks should only be embedded in a single place,
+            # either the test host (as per Xcode) or in the test itself
+            if test_host_app_bundle != None or read_root_config("apple", "exclude_xctest_libraries", "false").lower() != "true":
+                bundle_parts += get_test_frameworks_bundle_parts(ctx, xctest_swift_support_needed)
+
+        for sanitizer_runtime_dylib in cxx_library_output.sanitizer_runtime_files:
+            frameworks_destination = AppleBundleDestination("frameworks")
+            bundle_parts.append(
+                AppleBundlePart(
+                    source = sanitizer_runtime_dylib,
+                    destination = frameworks_destination,
+                    codesign_on_copy = True,
+                ),
+            )
+
+        bundle_result = assemble_bundle(
+            ctx,
+            xctest_bundle,
+            bundle_parts,
+            part_list_output.codesign_manifest_parts,
+            part_list_output.signing_context_parts,
+            part_list_output.info_plist_part,
+            None,  # swift_stdlib_args
+            # Adhoc signing can be skipped because the test executable is adhoc signed
+            # + includes any entitlements if present.
+            skip_adhoc_signing = True,
+            incremental_bundling_override = False,
+        )
+        sub_targets = bundle_result.sub_targets
+        sub_targets.update(cxx_library_output.sub_targets)
+
+        dsym_artifact = get_apple_dsym(
+            ctx = ctx,
+            executable = test_binary,
+            debug_info = debug_info,
+            action_identifier = "generate_apple_test_dsym",
+            output_path_override = get_bundle_dir_name(ctx) + ".dSYM",
+        )
+        sub_targets[DSYM_SUBTARGET] = [DefaultInfo(default_output = dsym_artifact)]
+
+        deps_debuggable_infos = get_deps_debuggable_infos(ctx)
+        dep_dsym_artifacts = []
+        for debuggable_info in deps_debuggable_infos:
+            dep_dsym_artifacts.extend(debuggable_info.dsyms)
+
+        dsym_json_info = get_apple_dsym_info_json([dsym_artifact], dep_dsym_artifacts)
+        dsym_info = ctx.actions.write_json("extended-dsym-info.json", dsym_json_info.json_object, pretty = True, has_content_based_path = False)
+        sub_targets[EXTENDED_DSYM_INFO_SUBTARGET] = [
+            DefaultInfo(default_output = dsym_info, other_outputs = dsym_json_info.outputs),
+        ]
+
+        # If the test has a test host and a ui test target, add the subtargets to build the app bundles.
+        sub_targets["test-host"] = [DefaultInfo(default_output = test_host_app_bundle)] if test_host_app_bundle else [DefaultInfo()]
+        sub_targets["ui-test-target"] = [DefaultInfo(default_output = ui_test_target_app_bundle)] if ui_test_target_app_bundle else [DefaultInfo()]
+
+        sub_targets[DWARF_AND_DSYM_SUBTARGET] = [
+            DefaultInfo(
+                default_output = xctest_bundle, other_outputs = [dsym_artifact], sub_targets = {_XCTOOLCHAIN_SUB_TARGET: ctx.attrs._apple_xctoolchain.providers}
+            ),
+            _get_test_info(ctx, xctest_bundle, test_host_app_bundle, dsym_artifact, ui_test_target_app_bundle),
+        ]
+
+        sub_targets[_XCTOOLCHAIN_SUB_TARGET] = ctx.attrs._apple_xctoolchain.providers
+
+        return (
+            filter(
+                None,
+                [
+                    DefaultInfo(default_output = xctest_bundle, sub_targets = sub_targets),
+                    _get_test_info(ctx, xctest_bundle, test_host_app_bundle, ui_test_target_app_bundle = ui_test_target_app_bundle),
+                    cxx_library_output.index_store_info,
+                    cxx_library_output.xcode_data_info,
+                    cxx_library_output.cxx_compilationdb_info,
+                ],
+            )
+            + bundle_result.providers
+            + cxx_providers
+        )
+
+    if uses_explicit_modules(ctx):
+        return get_swift_anonymous_targets(ctx, get_apple_test_providers)
+    else:
+        return get_apple_test_providers([])
+
+def _get_test_info(
+    ctx: AnalysisContext,
+    xctest_bundle: Artifact,
+    test_host_app_bundle: Artifact | None,
+    dsym_artifact: Artifact | None = None,
+    ui_test_target_app_bundle: Artifact | None = None,
+) -> Provider:
+    # When interacting with Tpx, we just pass our various inputs via env vars,
+    # since Tpx basically wants structured output for this.
+
+    xctest_bundle = cmd_args(xctest_bundle, hidden = dsym_artifact) if dsym_artifact else xctest_bundle
+    env = {"XCTEST_BUNDLE": xctest_bundle}
+
+    if test_host_app_bundle == None:
+        tpx_label = "tpx:apple_test:buck2:logicTest"
+    else:
+        env["HOST_APP_BUNDLE"] = test_host_app_bundle
+        tpx_label = "tpx:apple_test:buck2:appTest"
+
+    if ui_test_target_app_bundle != None:
+        env["TARGET_APP_BUNDLE"] = ui_test_target_app_bundle
+        tpx_label = "tpx:apple_test:buck2:uiTest"
+
+    labels = ctx.attrs.labels
+    labels.append(tpx_label)
+
+    test_device_type = AppleTestDeviceType(ctx.attrs.test_device_type)
+    if test_device_type == AppleTestDeviceType("default"):
+        # determine the device type from the sdk and platform
+        sdk_name = get_apple_sdk_name(ctx)
+        test_device_type = get_default_test_device(sdk = sdk_name, platform = ctx.attrs.default_target_platform)
+    labels.append(tpx_label_for_test_device_type(test_device_type))
+
+    remote_execution_properties = None # @oss-enable
+    remote_execution_use_case = None # @oss-enable
+
+    # @oss-disable[end= ]: if ctx.attrs.test_re_capabilities:
+        # @oss-disable[end= ]: remote_execution_properties = ctx.attrs.test_re_capabilities
+    # @oss-disable[end= ]: else:
+        # @oss-disable[end= ]: uses_test_host = test_host_app_bundle != None or ui_test_target_app_bundle != None
+        # @oss-disable[end= ]: remote_execution_properties = apple_test_re_capabilities(test_device_type = test_device_type, uses_test_host = uses_test_host)
+    # @oss-disable[end= ]: remote_execution_use_case = ctx.attrs.test_re_use_case or apple_test_re_use_case(test_device_type = test_device_type)
+
+    # @oss-disable[end= ]: if local_test_execution_is_available():
+        # @oss-disable[end= ]: labels.append("tpx:apple_test:local_execution_available")
+
+    return ExternalRunnerTestInfo(
+        type = "apple_test",
+        command = ["false"],  # Tpx makes up its own args, we just pass params via the env.
+        env = flatten_x([ctx.attrs.env or {}, env]),
+        labels = labels,
+        use_project_relative_paths = True,
+        run_from_project_root = True,
+        contacts = ctx.attrs.contacts,
+        executor_overrides = {
+            "ios-simulator-local": CommandExecutorConfig(
+                local_enabled = True,
+                remote_enabled = False,
+                remote_execution_properties = None,
+                remote_execution_use_case = None,
+            ),
+            "ios-simulator-remote": CommandExecutorConfig(
+                local_enabled = False,
+                remote_enabled = True,
+                remote_execution_properties = remote_execution_properties,
+                remote_execution_use_case = remote_execution_use_case,
+            ),
+            "static-listing": CommandExecutorConfig(local_enabled = True, remote_enabled = False),
+        },
+        local_resources = {
+            "ipad_simulator": ctx.attrs._ipad_simulator.label,
+            "iphone_booted_simulator": ctx.attrs._iphone_booted_simulator.label,
+            "iphone_unbooted_simulator": ctx.attrs._iphone_unbooted_simulator.label,
+            "watch_simulator": ctx.attrs._watch_simulator.label,
+        },
+    )
+
+def _get_test_host_app_bundle(ctx: AnalysisContext) -> Artifact | None:
+    """Get the bundle for the test host app, if one exists for this test."""
+    if ctx.attrs.test_host_app:
+        # Copy the test host app bundle into test's output directory
+        original_bundle = ctx.attrs.test_host_app[AppleBundleInfo].bundle
+        test_host_app_bundle = ctx.actions.declare_output(original_bundle.basename, has_content_based_path = False)
+        ctx.actions.copy_file(test_host_app_bundle, original_bundle)
+        return test_host_app_bundle
+
+    return None
+
+def _get_test_host_app_binary(ctx: AnalysisContext, test_host_app_bundle: Artifact | None) -> [cmd_args, None]:
+    """Reference to the binary with the test host app bundle, if one exists for this test. Captures the bundle as an artifact in the cmd_args."""
+    if ctx.attrs.test_host_app == None:
+        return None
+
+    parts = [test_host_app_bundle]
+    rel_path = bundle_relative_path_for_destination(AppleBundleDestination("executables"), get_apple_sdk_name(ctx), ctx.attrs.extension, False)
+    if len(rel_path) > 0:
+        parts.append(rel_path)
+    parts.append(ctx.attrs.test_host_app[AppleBundleInfo].binary_name)
+    return cmd_args(parts, delimiter = "/")
+
+def _get_ui_test_target_app_bundle(ctx: AnalysisContext) -> Artifact | None:
+    """Get the bundle for the ui test target app, if one exists for this test."""
+    if ctx.attrs.ui_test_target_app:
+        # Copy the ui test target app bundle into test's output directory
+        original_bundle = ctx.attrs.ui_test_target_app[AppleBundleInfo].bundle
+        ui_test_target_app_bundle = ctx.actions.declare_output(original_bundle.basename, has_content_based_path = False)
+        ctx.actions.copy_file(ui_test_target_app_bundle, original_bundle)
+        return ui_test_target_app_bundle
+
+    return None
+
+def _get_bundle_loader_flags(binary: [cmd_args, None]) -> list[typing.Any]:
+    if binary:
+        # During linking we need to link the test shared lib against the test host binary. The
+        # test host binary doesn't need to be embedded in an `apple_bundle`.
+        return ["-bundle_loader", binary]
+
+    return []
+
+def _xcode_populate_attributes(
+    ctx: AnalysisContext,
+    srcs: list[CxxSrcWithFlags],
+    argsfiles: dict[str, CompileArgsfile],
+    xctest_bundle: Artifact,
+    test_host_app_binary: [cmd_args, None],
+    test_host_app_bundle: Artifact | None,
+    **_kwargs,
+) -> dict[str, typing.Any]:
+    data = apple_populate_xcode_attributes(ctx = ctx, srcs = srcs, argsfiles = argsfiles, product_name = ctx.attrs.name)
+    data[XcodeDataInfoKeys.OUTPUT] = xctest_bundle
+
+    # TODO: We should be able to extract this information in BXL. XcodeData is primarily necessary for derived data from the rules.
+    if ctx.attrs.ui_test_target_app:
+        data[XcodeDataInfoKeys.TEST_TYPE] = "ui-test"
+        data[XcodeDataInfoKeys.TEST_TARGET] = ctx.attrs.ui_test_target_app.label.raw_target()
+    else:
+        data[XcodeDataInfoKeys.TEST_TYPE] = "unit-test"
+        if test_host_app_binary:
+            data[XcodeDataInfoKeys.TEST_HOST_APP_BINARY] = test_host_app_binary
+            data[XcodeDataInfoKeys.TEST_HOST_APP_BUNDLE] = test_host_app_bundle
+            data[XcodeDataInfoKeys.TEST_HOST_APP_TARGET] = ctx.attrs.test_host_app.label.raw_target()
+    return data
+
+def _get_test_framework_search_paths(ctx: AnalysisContext) -> (cmd_args, cmd_args):
+    toolchain = ctx.attrs._apple_toolchain[AppleToolchainInfo]
+    test_swiftmodule_search_path = cmd_args([toolchain.platform_path, "Developer/usr/lib"], delimiter = "/")
+    test_framework_search_path = cmd_args([toolchain.platform_path, "Developer/Library/Frameworks"], delimiter = "/")
+    return (test_swiftmodule_search_path, test_framework_search_path)
+
+def _get_test_framework_search_paths_flags(ctx: AnalysisContext) -> list[[cmd_args, str]]:
+    test_swiftmodule_search_path, test_framework_search_path = _get_test_framework_search_paths(ctx)
+    return [
+        "-I",
+        test_swiftmodule_search_path,
+        "-F",
+        test_framework_search_path,
+    ]
+
+def get_test_framework_linker_flags(ctx: AnalysisContext) -> list[[cmd_args, str]]:
+    test_swiftmodule_search_path, test_framework_search_path = _get_test_framework_search_paths(ctx)
+    linker_flags = [
+        "-L",
+        test_swiftmodule_search_path,
+        "-F",
+        test_framework_search_path,
+    ]
+    if ctx.attrs.swift_testing:
+        linker_flags += ["-lXCTestSwiftSupport"]
+    return linker_flags
diff --git a/buck2/prelude/apple/apple_test_device_types.bzl b/buck2/prelude/apple/apple_test_device_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_test_device_types.bzl
@@ -0,0 +1,46 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":apple_sdk_metadata.bzl", "MacOSXSdkMetadata", "WatchSimulatorSdkMetadata")
+
+apple_test_device_types = struct(
+    DEFAULT = "default",
+    CATALYST = "catalyst",
+    IPAD = "ipad",
+    IPHONE = "iphone",
+    MAC = "mac",
+    WATCH = "watch",
+)
+
+AppleTestDeviceType = enum(
+    apple_test_device_types.DEFAULT,
+    apple_test_device_types.CATALYST,
+    apple_test_device_types.IPAD,
+    apple_test_device_types.IPHONE,
+    apple_test_device_types.MAC,
+    apple_test_device_types.WATCH,
+)
+
+def get_default_test_device(sdk: str, platform: str) -> AppleTestDeviceType:
+    if sdk == MacOSXSdkMetadata.name:
+        return AppleTestDeviceType("mac")
+    elif sdk == WatchSimulatorSdkMetadata.name:
+        return AppleTestDeviceType("watch")
+    elif "catalyst" in platform:
+        return AppleTestDeviceType("catalyst")
+    else:
+        return AppleTestDeviceType("iphone")
+
+def tpx_label_for_test_device_type(test_device_type: AppleTestDeviceType) -> str:
+    if test_device_type in (AppleTestDeviceType("catalyst"), AppleTestDeviceType("mac")):
+        return "tpx:apple_test:device_type:mac"
+    elif test_device_type == AppleTestDeviceType("ipad"):
+        return "tpx:apple_test:device_type:ipad"
+    elif test_device_type == AppleTestDeviceType("watch"):
+        return "tpx:apple_test:device_type:watch"
+    return "tpx:apple_test:device_type:iphone"
diff --git a/buck2/prelude/apple/apple_test_frameworks_utility.bzl b/buck2/prelude/apple/apple_test_frameworks_utility.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_test_frameworks_utility.bzl
@@ -0,0 +1,60 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_bundle_destination.bzl", "AppleBundleDestination")
+load("@prelude//apple:apple_bundle_part.bzl", "AppleBundlePart")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+
+def get_test_frameworks_bundle_parts(ctx: AnalysisContext, swift_support_needed: bool) -> list[AppleBundlePart]:
+    xcode_version = int(ctx.attrs._apple_toolchain[AppleToolchainInfo].xcode_version)
+    paths = [
+        _get_object_from_platform_path(ctx, "Developer/Library/Frameworks/XCTest.framework"),
+        _get_object_from_platform_path(ctx, "Developer/Library/PrivateFrameworks/XCTAutomationSupport.framework"),
+        _get_object_from_platform_path(ctx, "Developer/Library/PrivateFrameworks/XCTestCore.framework"),
+        _get_object_from_platform_path(ctx, "Developer/Library/PrivateFrameworks/XCTestSupport.framework"),
+        _get_object_from_platform_path(ctx, "Developer/Library/PrivateFrameworks/XCUnit.framework"),
+        _get_object_from_platform_path(ctx, "Developer/usr/lib/libXCTestBundleInject.dylib"),
+    ]
+
+    # From Xcode 16.3 XCUIAutomation is in Frameworks, not PrivateFrameworks
+    if xcode_version >= 1630:
+        paths.append(_get_object_from_platform_path(ctx, "Developer/Library/Frameworks/XCUIAutomation.framework"))
+    else:
+        paths.append(_get_object_from_platform_path(ctx, "Developer/Library/PrivateFrameworks/XCUIAutomation.framework"))
+
+    if swift_support_needed or ctx.attrs.swift_testing:
+        paths.append(_get_object_from_platform_path(ctx, "Developer/usr/lib/libXCTestSwiftSupport.dylib"))
+
+        # T201426509: Xcode 16 introduces the Swift Testing framework
+        # that is a load dependency of libXCTestSwiftSupport.dylib
+        if xcode_version >= 1600:
+            paths.append(_get_object_from_platform_path(ctx, "Developer/Library/Frameworks/Testing.framework"))
+        if xcode_version >= 2600:
+            paths.append(_get_object_from_platform_path(ctx, "Developer/Library/Frameworks/_Testing_Foundation.framework"))
+
+        # Xcode 26.4 makes Testing.framework load lib_TestingInterop.dylib at runtime.
+        if xcode_version >= 2640:
+            paths.append(_get_object_from_platform_path(ctx, "Developer/usr/lib/lib_TestingInterop.dylib"))
+
+    return paths
+
+def _get_object_from_platform_path(ctx: AnalysisContext, platform_relative_path: str) -> AppleBundlePart:
+    toolchain = ctx.attrs._apple_toolchain[AppleToolchainInfo]
+    copied_framework = ctx.actions.declare_output(paths.basename(platform_relative_path), has_content_based_path = False)
+
+    # We have to copy because:
+    # 1) Platform path might be a string (e.g. for Xcode toolchains)
+    # 2) It's not possible to project artifact which is not produced by different target (and platform path is a separate target for distributed toolchains).
+    ctx.actions.run(
+        ["cp", "-PR", cmd_args(toolchain.platform_path, platform_relative_path, delimiter = "/"), copied_framework.as_output()],
+        category = "extract_framework",
+        identifier = platform_relative_path,
+    )
+
+    return AppleBundlePart(source = copied_framework, destination = AppleBundleDestination("frameworks"), codesign_on_copy = True)
diff --git a/buck2/prelude/apple/apple_test_host_app_transition.bzl b/buck2/prelude/apple/apple_test_host_app_transition.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_test_host_app_transition.bzl
@@ -0,0 +1,39 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _apple_test_host_app_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:
+    if not attrs.embed_xctest_frameworks_in_test_host_app:
+        return platform
+
+    updated_constraints = dict(platform.configuration.constraints)
+
+    test_host_marker_setting_label = refs.embed_xctest_frameworks_constraint_setting[ConstraintSettingInfo].label
+    if test_host_marker_setting_label in updated_constraints:
+        return platform
+
+    test_host_marker_value_info = refs.embed_xctest_frameworks_marker_constraint_value[ConstraintValueInfo]
+    updated_constraints[test_host_marker_setting_label] = test_host_marker_value_info
+
+    return PlatformInfo(
+        label = platform.label + "-test-host-app",
+        configuration = ConfigurationInfo(
+            constraints = updated_constraints,
+            values = platform.configuration.values,
+        ),
+    )
+
+apple_test_host_app_transition = transition(
+    impl = _apple_test_host_app_transition_impl,
+    refs = {
+        "embed_xctest_frameworks_constraint_setting": "config//marker/apple/constraints:embed_xctest_frameworks",
+        "embed_xctest_frameworks_marker_constraint_value": "config//marker/apple/constraints:embed_xctest_frameworks[enabled]",
+    },
+    attrs = [
+        "embed_xctest_frameworks_in_test_host_app",
+    ],
+)
diff --git a/buck2/prelude/apple/apple_toolchain.bzl b/buck2/prelude/apple/apple_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_toolchain.bzl
@@ -0,0 +1,62 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftToolchainInfo")
+load("@prelude//apple/validation:required_reasons_tools.bzl", "RequiredReasonsToolsInfo")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxPlatformInfo", "CxxToolchainInfo")
+
+def apple_toolchain_impl(ctx: AnalysisContext) -> list[Provider]:
+    sdk_path = ctx.attrs._internal_sdk_path or ctx.attrs.sdk_path
+    platform_path = ctx.attrs._internal_platform_path or ctx.attrs.platform_path
+    dsymutil_cmd = cmd_args(ctx.attrs.dsymutil[RunInfo].args)
+    dsymutil_cmd.add(ctx.attrs.dsymutil_flags)
+
+    providers = [
+        DefaultInfo(),
+        AppleToolchainInfo(
+            actool = ctx.attrs.actool[RunInfo],
+            app_intents_metadata_processor = ctx.attrs.app_intents_metadata_processor[RunInfo] if ctx.attrs.app_intents_metadata_processor else None,
+            app_intents_nl_training_processor = ctx.attrs.app_intents_nl_training_processor[RunInfo] if ctx.attrs.app_intents_nl_training_processor else None,
+            architecture = ctx.attrs.architecture,
+            codesign = ctx.attrs.codesign[RunInfo],
+            codesign_allocate = ctx.attrs.codesign_allocate[RunInfo],
+            codesign_identities_command = ctx.attrs.codesign_identities_command[RunInfo] if ctx.attrs.codesign_identities_command else None,
+            compile_resources_locally = ctx.attrs.compile_resources_locally,
+            copy_scene_kit_assets = ctx.attrs.copy_scene_kit_assets[RunInfo],
+            cxx_platform_info = ctx.attrs.cxx_toolchain[CxxPlatformInfo],
+            cxx_toolchain_info = ctx.attrs.cxx_toolchain[CxxToolchainInfo],
+            dsymutil = RunInfo(args = dsymutil_cmd),
+            dwarfdump = ctx.attrs.dwarfdump[RunInfo] if ctx.attrs.dwarfdump else None,
+            extra_linker_outputs = ctx.attrs.extra_linker_outputs,
+            ibtool = ctx.attrs.ibtool[RunInfo],
+            installer = ctx.attrs.installer.label,
+            installer_tool = ctx.attrs.installer[RunInfo],
+            libtool = ctx.attrs.libtool[RunInfo],
+            lipo = ctx.attrs.lipo[RunInfo],
+            mapc = ctx.attrs.mapc[RunInfo] if ctx.attrs.mapc else None,
+            merge_index_store = ctx.attrs.merge_index_store[RunInfo],
+            metal = ctx.attrs.metal[RunInfo] if ctx.attrs.metal else None,
+            metallib = ctx.attrs.metallib[RunInfo] if ctx.attrs.metallib else None,
+            momc = ctx.attrs.momc[RunInfo],
+            objdump = ctx.attrs.objdump[RunInfo] if ctx.attrs.objdump else None,
+            platform_path = platform_path,
+            required_reasons_tools = ctx.attrs.required_reasons_tools[RequiredReasonsToolsInfo],
+            sdk_build_version = ctx.attrs.build_version,
+            sdk_name = ctx.attrs.sdk_name,
+            sdk_path = sdk_path,
+            sdk_version = ctx.attrs.version,
+            xcode_build_version = ctx.attrs.xcode_build_version,
+            xcode_version = ctx.attrs.xcode_version,
+            xctest = ctx.attrs.xctest[RunInfo],
+        ),
+    ]
+    if ctx.attrs.swift_toolchain:
+        providers.append(ctx.attrs.swift_toolchain[SwiftToolchainInfo])
+
+    return providers
diff --git a/buck2/prelude/apple/apple_toolchain_types.bzl b/buck2/prelude/apple/apple_toolchain_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_toolchain_types.bzl
@@ -0,0 +1,79 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple/validation:required_reasons_tools.bzl", "RequiredReasonsToolsInfo")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxPlatformInfo", "CxxToolchainInfo")
+
+AppleToolchainInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "actool": provider_field(RunInfo),
+        "app_intents_metadata_processor": provider_field(RunInfo | None, default = None),
+        "app_intents_nl_training_processor": provider_field(RunInfo | None, default = None),
+        "architecture": provider_field(str),
+        "codesign_allocate": provider_field(RunInfo),
+        "codesign_identities_command": provider_field(RunInfo | None, default = None),
+        "codesign": provider_field(RunInfo),
+        "compile_resources_locally": provider_field(bool),
+        "copy_scene_kit_assets": provider_field(RunInfo),
+        "cxx_platform_info": provider_field(CxxPlatformInfo),
+        "cxx_toolchain_info": provider_field(CxxToolchainInfo),
+        "dsymutil": provider_field(RunInfo),
+        "dwarfdump": provider_field(RunInfo | None, default = None),
+        "extra_linker_outputs": provider_field(list[str]),
+        "ibtool": provider_field(RunInfo),
+        "installer": provider_field(Label),
+        "installer_tool": provider_field(RunInfo),
+        "libtool": provider_field(RunInfo),
+        "lipo": provider_field(RunInfo),
+        "mapc": provider_field(RunInfo | None, default = None),
+        "merge_index_store": provider_field(RunInfo),
+        "metal": provider_field(RunInfo | None, default = None),
+        "metallib": provider_field(RunInfo | None, default = None),
+        "momc": provider_field(RunInfo),
+        "objdump": provider_field(RunInfo | None, default = None),
+        "platform_path": provider_field(str | Artifact),
+        "required_reasons_tools": provider_field(RequiredReasonsToolsInfo),
+        "sdk_build_version": provider_field(str | None, default = None),
+        # SDK name to be passed to tools (e.g. actool), equivalent to ApplePlatform::getExternalName() in v1.
+        "sdk_name": provider_field(str),
+        "sdk_path": provider_field(str | Artifact),
+        # TODO(T124581557) Make it non-optional once there is no "selected xcode" toolchain
+        "sdk_version": provider_field(str | None, default = None),
+        "xcode_build_version": provider_field(str | None, default = None),
+        "xcode_version": provider_field(str),
+        "xctest": provider_field(RunInfo),
+    },
+)
+
+AppleToolsInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "assemble_bundle": provider_field(RunInfo),
+        "provisioning_manifest": provider_field(RunInfo),
+        "resolve_signing_context": provider_field(RunInfo),
+        "signing_info": provider_field(RunInfo),
+        "split_arch_combine_dsym_bundles_tool": provider_field(RunInfo),
+        "dry_codesign_tool": provider_field(RunInfo),
+        "adhoc_codesign_tool": provider_field(RunInfo),
+        "codesign_manifest_tree_postprocessor": provider_field(RunInfo),
+        "dedupe_swift_module_map": provider_field(RunInfo),
+        "signing_context_tree_postprocessor": provider_field(RunInfo),
+        "selective_debugging_scrubber": provider_field(RunInfo),
+        "info_plist_processor": provider_field(RunInfo),
+        "ipa_package_maker": provider_field(RunInfo),
+        "make_modulemap": provider_field(RunInfo),
+        "make_vfsoverlay": provider_field(RunInfo),
+        "framework_sanitizer": provider_field(RunInfo),
+        "xcframework_maker": provider_field(RunInfo),
+        "static_archive_linker": provider_field(RunInfo),
+        "spm_packager": provider_field(RunInfo),
+        "bundle_telemetry_logger": provider_field(RunInfo | None, default = None),
+        "swiftmodule_change_analysis": provider_field(RunInfo | None, default = None),
+    },
+)
diff --git a/buck2/prelude/apple/apple_tools.bzl b/buck2/prelude/apple/apple_tools.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_tools.bzl
@@ -0,0 +1,37 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")
+
+def apple_tools_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        AppleToolsInfo(
+            assemble_bundle = ctx.attrs.assemble_bundle[RunInfo],
+            provisioning_manifest = ctx.attrs.provisioning_manifest[RunInfo],
+            resolve_signing_context = ctx.attrs.resolve_signing_context[RunInfo],
+            signing_info = ctx.attrs.signing_info[RunInfo],
+            split_arch_combine_dsym_bundles_tool = ctx.attrs.split_arch_combine_dsym_bundles_tool[RunInfo],
+            dry_codesign_tool = ctx.attrs.dry_codesign_tool[RunInfo],
+            adhoc_codesign_tool = ctx.attrs.adhoc_codesign_tool[RunInfo],
+            codesign_manifest_tree_postprocessor = ctx.attrs.codesign_manifest_tree_postprocessor[RunInfo],
+            dedupe_swift_module_map = ctx.attrs.dedupe_swift_module_map[RunInfo],
+            signing_context_tree_postprocessor = ctx.attrs.signing_context_tree_postprocessor[RunInfo],
+            info_plist_processor = ctx.attrs.info_plist_processor[RunInfo],
+            ipa_package_maker = ctx.attrs.ipa_package_maker[RunInfo],
+            make_modulemap = ctx.attrs.make_modulemap[RunInfo],
+            make_vfsoverlay = ctx.attrs.make_vfsoverlay[RunInfo],
+            selective_debugging_scrubber = ctx.attrs.selective_debugging_scrubber[RunInfo],
+            xcframework_maker = ctx.attrs.xcframework_maker[RunInfo],
+            framework_sanitizer = ctx.attrs.framework_sanitizer[RunInfo],
+            static_archive_linker = ctx.attrs.static_archive_linker[RunInfo],
+            spm_packager = ctx.attrs.spm_packager[RunInfo],
+            bundle_telemetry_logger = ctx.attrs.bundle_telemetry_logger[RunInfo] if ctx.attrs.bundle_telemetry_logger else None,
+            swiftmodule_change_analysis = ctx.attrs.swiftmodule_change_analysis[RunInfo] if ctx.attrs.swiftmodule_change_analysis else None,
+        ),
+    ]
diff --git a/buck2/prelude/apple/apple_universal_binaries.bzl b/buck2/prelude/apple/apple_universal_binaries.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_universal_binaries.bzl
@@ -0,0 +1,108 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifact_tset.bzl", "make_artifact_tset")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load("@prelude//linking:link_info.bzl", "UnstrippedLinkOutputInfo")
+load(":apple_bundle_types.bzl", "AppleBundleBinaryOutput")
+load(":apple_toolchain_types.bzl", "AppleToolsInfo")
+load(":debug.bzl", "AppleDebuggableInfo")
+
+def get_universal_binary_name(ctx: AnalysisContext) -> str:
+    if ctx.attrs.executable_name:
+        return ctx.attrs.executable_name
+    binary_deps = ctx.attrs.executable
+
+    # Because `binary_deps` is a split transition of the same target,
+    # the filenames would be identical, so we just pick the first one.
+    first_binary_dep = binary_deps.values()[0]
+    first_binary_artifact = first_binary_dep[DefaultInfo].default_outputs[0]
+
+    # The universal executable should have the same name as the base/thin ones
+    return first_binary_artifact.short_path
+
+def lipo_binary_artifacts(ctx: AnalysisContext, binaries: list[Artifact], binary_name: [str, None], lipo: RunInfo, identifier: str) -> Artifact:
+    binary_output = ctx.actions.declare_output("UniversalBinary" if binary_name == None else binary_name, dir = False, has_content_based_path = False)
+    lipo_cmd = [lipo] + binaries
+
+    lipo_cmd.extend(["-create", "-output", binary_output.as_output()])
+    ctx.actions.run(cmd_args(lipo_cmd), category = "lipo", identifier = identifier)
+
+    return binary_output
+
+def lipo_binaries(ctx: AnalysisContext, binary_deps: dict[str, Dependency], binary_name: [str, None], lipo: RunInfo) -> Artifact:
+    binaries = [binary[DefaultInfo].default_outputs[0] for binary in binary_deps.values()]
+    return lipo_binary_artifacts(ctx, binaries, binary_name, lipo, "default")
+
+def _get_unstripped_binaries(binary_deps: dict[str, Dependency]) -> list[Artifact]:
+    unstripped_binaries = []
+    for binary_dep in binary_deps.values():
+        default_binary = binary_dep[DefaultInfo].default_outputs[0]
+        unstripped_binary = binary_dep.get(UnstrippedLinkOutputInfo).artifact if binary_dep.get(UnstrippedLinkOutputInfo) != None else None
+        if unstripped_binary != None and unstripped_binary != default_binary:
+            unstripped_binaries.append(unstripped_binary)
+
+    if len(unstripped_binaries) > 0 and len(unstripped_binaries) != len(binary_deps):
+        fail("Inconsistent unstripped binaries, only certain archs provided unstripped binary versions")
+
+    return unstripped_binaries
+
+def create_universal_binary(
+    ctx: AnalysisContext, binary_deps: dict[str, Dependency], binary_name: [str, None], dsym_bundle_name: [str, None], split_arch_dsym: bool
+) -> AppleBundleBinaryOutput:
+    binary_output = lipo_binaries(ctx, binary_deps, binary_name, ctx.attrs._apple_toolchain[AppleToolchainInfo].lipo)
+
+    unstripped_binaries = _get_unstripped_binaries(binary_deps)
+    unstripped_binary_output = None
+    if unstripped_binaries:
+        unstripped_binary_name = "unstripped/{}".format(binary_name) if binary_name else "UniversalBinary-Unstripped"
+        unstripped_binary_output = lipo_binary_artifacts(
+            ctx, unstripped_binaries, unstripped_binary_name, ctx.attrs._apple_toolchain[AppleToolchainInfo].lipo, "unstripped"
+        )
+
+    # Universal binaries can be created out of plain `cxx_binary()` / `cxx_library()`
+    # which lack the `AppleDebuggableInfo` provider.
+    # TODO(T174234334): Uniformly support debuggable info for apple_*/cxx_*
+    contains_full_debuggable_info = _all_binaries_have_apple_debuggable_info(binary_deps)
+
+    dsym_output = None
+    if split_arch_dsym and contains_full_debuggable_info:
+        dsym_output = ctx.actions.declare_output(
+            "UniversalBinary.dSYM" if dsym_bundle_name == None else dsym_bundle_name, dir = True, has_content_based_path = False
+        )
+        dsym_combine_cmd = [ctx.attrs._apple_tools[AppleToolsInfo].split_arch_combine_dsym_bundles_tool]
+
+        for arch, binary in binary_deps.items():
+            dsym_combine_cmd.extend(["--dsym-bundle", cmd_args(binary.get(AppleDebuggableInfo).dsyms[0]), "--arch", arch])
+        dsym_combine_cmd.extend(["--output", dsym_output.as_output()])
+        ctx.actions.run(cmd_args(dsym_combine_cmd), category = "universal_binaries_dsym")
+
+    all_debug_info_tsets = []
+    if contains_full_debuggable_info:
+        all_debug_info_tsets = [binary.get(AppleDebuggableInfo).debug_info_tset for binary in binary_deps.values()]
+
+    return AppleBundleBinaryOutput(
+        binary = binary_output,
+        unstripped_binary = unstripped_binary_output,
+        debuggable_info = AppleDebuggableInfo(
+            dsyms = [dsym_output] if dsym_output != None else [],
+            binaries = [unstripped_binary_output] if unstripped_binary_output else [binary_output],
+            debug_info_tset = make_artifact_tset(
+                actions = ctx.actions,
+                label = ctx.label,
+                children = filter(None, all_debug_info_tsets),
+            ),
+        ),
+    )
+
+def _all_binaries_have_apple_debuggable_info(binary_deps: dict[str, Dependency]) -> bool:
+    for binary in binary_deps.values():
+        info = binary.get(AppleDebuggableInfo)
+        if info == None:
+            return False
+    return True
diff --git a/buck2/prelude/apple/apple_universal_executable.bzl b/buck2/prelude/apple/apple_universal_executable.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_universal_executable.bzl
@@ -0,0 +1,104 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "project_artifacts",
+)
+load(":apple_bundle_types.bzl", "AppleBundleLinkerMapInfo", "AppleMinDeploymentVersionInfo")
+load(":apple_bundle_utility.bzl", "get_default_binary_dep", "get_flattened_binary_deps", "merge_bundle_linker_maps_info")
+load(":apple_code_signing_types.bzl", "AppleEntitlementsInfo")
+load(":apple_dsym.bzl", "DSYM_SUBTARGET", "get_apple_dsym_ext")
+load(":apple_universal_binaries.bzl", "create_universal_binary", "get_universal_binary_name")
+load(":debug.bzl", "AppleDebuggableInfo", "DEBUGINFO_SUBTARGET")
+load(":resource_groups.bzl", "ResourceGraphInfo")
+
+_FORWARDED_PROVIDER_TYPES = [
+    AppleMinDeploymentVersionInfo,
+    AppleEntitlementsInfo,
+    ResourceGraphInfo,
+]
+
+_MERGED_PROVIDER_TYPES = [
+    AppleDebuggableInfo,
+    AppleBundleLinkerMapInfo,
+]
+
+def apple_universal_executable_impl(ctx: AnalysisContext) -> list[Provider]:
+    dsym_name = ctx.attrs.name + ".dSYM"
+    binary_outputs = create_universal_binary(
+        ctx = ctx,
+        binary_deps = ctx.attrs.executable,
+        binary_name = get_universal_binary_name(ctx),
+        dsym_bundle_name = dsym_name,
+        split_arch_dsym = ctx.attrs.split_arch_dsym,
+    )
+
+    debug_info = project_artifacts(
+        actions = ctx.actions,
+        tsets = binary_outputs.debuggable_info.debug_info_tset,
+    )
+
+    sub_targets = {}
+    if ctx.attrs.split_arch_dsym:
+        dsyms = binary_outputs.debuggable_info.dsyms
+    else:
+        dsyms = [
+            get_apple_dsym_ext(
+                ctx = ctx,
+                executable = binary_outputs.binary,
+                debug_info = debug_info,
+                action_identifier = ctx.attrs.name + "_dsym",
+                output_path = dsym_name,
+            )
+        ]
+    sub_targets[DSYM_SUBTARGET] = [DefaultInfo(default_outputs = dsyms)]
+
+    debug_info_artifacts_manifest = ctx.actions.write(
+        "debuginfo.artifacts",
+        debug_info,
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+    sub_targets[DEBUGINFO_SUBTARGET] = [DefaultInfo(default_output = debug_info_artifacts_manifest)]
+
+    default_binary = get_default_binary_dep(ctx.attrs.executable)
+    forwarded_providers = []
+    for forward_provider_type in _FORWARDED_PROVIDER_TYPES:
+        provider = default_binary.get(forward_provider_type)
+        if provider != None:
+            forwarded_providers += [provider]
+
+    merged_providers = []
+    all_binarys = get_flattened_binary_deps(ctx.attrs.executable)
+    for merged_provider_type in _MERGED_PROVIDER_TYPES:
+        if default_binary.get(merged_provider_type) == None:
+            continue
+        if merged_provider_type == AppleDebuggableInfo:
+            merged_providers += [
+                AppleDebuggableInfo(
+                    dsyms = dsyms,
+                    binaries = binary_outputs.debuggable_info.binaries,
+                    debug_info_tset = binary_outputs.debuggable_info.debug_info_tset,
+                ),
+            ]
+        elif merged_provider_type == AppleBundleLinkerMapInfo:
+            merged_providers += [
+                merge_bundle_linker_maps_info([binary[AppleBundleLinkerMapInfo] for binary in all_binarys]),
+            ]
+        else:
+            fail("Unhandled provider type: {}".format(merged_provider_type))
+
+    return (
+        [
+            DefaultInfo(default_output = binary_outputs.binary, sub_targets = sub_targets),
+            RunInfo(args = cmd_args(binary_outputs.binary)),
+        ]
+        + forwarded_providers
+        + merged_providers
+    )
diff --git a/buck2/prelude/apple/apple_utility.bzl b/buck2/prelude/apple/apple_utility.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_utility.bzl
@@ -0,0 +1,82 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftToolchainInfo")
+load("@prelude//cxx:headers.bzl", "CHeader", "CxxHeadersLayout", "CxxHeadersNaming")
+load("@prelude//utils:utils.bzl", "value_or")
+
+def target_stats_header_name(header: CHeader) -> str:
+    """The path a target refers to a header by.
+
+    A header given as a dict is named by its key, which is the only thing
+    separating two files that share a basename. A plain list keeps its
+    package-relative path: Apple's naming would flatten it to the basename,
+    which loses the sub-directory for no benefit here.
+    """
+    return header.name if header.named else header.artifact.short_path
+
+def get_apple_cxx_headers_layout(ctx: AnalysisContext) -> CxxHeadersLayout:
+    namespace = value_or(ctx.attrs.header_path_prefix, ctx.attrs.name)
+    return CxxHeadersLayout(namespace = namespace, naming = CxxHeadersNaming("apple"))
+
+def get_module_name(ctx: AnalysisContext) -> str:
+    return ctx.attrs.module_name or ctx.attrs.header_path_prefix or ctx.attrs.name
+
+def has_apple_toolchain(ctx: AnalysisContext) -> bool:
+    return hasattr(ctx.attrs, "_apple_toolchain")
+
+def get_apple_architecture(ctx: AnalysisContext) -> str:
+    return ctx.attrs._apple_toolchain[AppleToolchainInfo].architecture
+
+def get_apple_stripped_attr_value_with_default_fallback(ctx: AnalysisContext) -> bool:
+    return ctx.attrs.strip_level != "unstripped"
+
+def expand_relative_prefixed_sdk_path(swift_toolchain_info: SwiftToolchainInfo, path_to_expand: str) -> cmd_args:
+    if not path_to_expand.startswith("$"):
+        fail("Expanding path {} that does not start with a variable".format(path_to_expand))
+
+    path_expansion_map = swift_toolchain_info.sdk_module_path_prefixes
+    path_variable = path_to_expand[: path_to_expand.find("/")]
+    if path_variable not in path_expansion_map:
+        fail("Missing sdk_module_path_prefixes entry for {}".format(path_variable))
+
+    path_val = path_expansion_map[path_variable]
+    return cmd_args([path_val, path_to_expand[len(path_variable) :]], delimiter = "")
+
+def get_disable_pch_validation_flags() -> list[str]:
+    """
+    We need to disable PCH validation for some actions like Swift compilation and Swift PCM generation.
+    Currently, we don't have a mechanism to compile with enabled pch validation and Swift explicit modules,
+    which we need to be able to do while we are waiting for Anonymous targets which will allow us to solve this problem properly.
+    """
+    return [
+        "-Xcc",
+        "-Xclang",
+        "-Xcc",
+        "-fno-validate-pch",
+    ]
+
+def get_base_swiftinterface_compilation_flags(module_name: str) -> cmd_args:
+    cmd = cmd_args([
+        "-frontend",
+        "-compile-module-from-interface",
+        "-disable-implicit-swift-modules",
+        "-serialize-parseable-module-interface-dependency-hashes",
+        "-disable-modules-validate-system-headers",
+        "-suppress-warnings",
+        "-module-name",
+        module_name,
+        "-Xcc",
+        "-fno-implicit-modules",
+        "-Xcc",
+        "-fno-implicit-module-maps",
+    ])
+    cmd.add(get_disable_pch_validation_flags())
+
+    return cmd
diff --git a/buck2/prelude/apple/apple_xcuitest.bzl b/buck2/prelude/apple/apple_xcuitest.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/apple_xcuitest.bzl
@@ -0,0 +1,104 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load(":apple_bundle_destination.bzl", "AppleBundleDestination")
+load(":apple_bundle_part.bzl", "AppleBundlePart", "assemble_bundle")
+load(":apple_bundle_types.bzl", "AppleBundleInfo", "AppleBundleType")
+load(":apple_info_plist.bzl", "process_info_plist")
+load(":apple_utility.bzl", "get_apple_architecture")
+
+def apple_xcuitest_impl(ctx: AnalysisContext) -> [list[Provider], Promise]:
+    # The XCUITest runner app bundle copies the application from the platform
+    # directory, and includes the UI test bundle in the PlugIns folder.
+    output_bundle = ctx.actions.declare_output(ctx.attrs.name + "." + ctx.attrs.extension, has_content_based_path = False)
+    bundle_parts = [
+        _get_xctrunner_binary(ctx),
+        _get_uitest_bundle(ctx),
+    ] + _get_xctrunner_frameworks(ctx)
+    bundle_result = assemble_bundle(
+        ctx = ctx,
+        bundle = output_bundle,
+        info_plist_part = process_info_plist(ctx, override_input = None),
+        parts = bundle_parts,
+        codesign_manifest_parts = [],
+        signing_context_parts = [],
+        swift_stdlib_args = None,
+    )
+
+    return [
+        DefaultInfo(default_output = output_bundle),
+        AppleBundleInfo(
+            bundle = output_bundle,
+            bundle_type = AppleBundleType("default"),
+            binary_name = ctx.attrs.name,
+            contains_watchapp = False,
+            # The test runner binary does not contain Swift
+            skip_copying_swift_stdlib = True,
+        ),
+    ] + bundle_result.providers
+
+def _get_uitest_bundle(ctx: AnalysisContext) -> AppleBundlePart:
+    return AppleBundlePart(
+        source = ctx.attrs.test_bundle[DefaultInfo].default_outputs[0],
+        destination = AppleBundleDestination("plugins"),
+    )
+
+def _get_xctrunner_binary(ctx: AnalysisContext) -> AppleBundlePart:
+    arch = get_apple_architecture(ctx)
+    lipo = ctx.attrs._apple_toolchain[AppleToolchainInfo].lipo
+    platform_path = ctx.attrs._apple_toolchain[AppleToolchainInfo].platform_path
+    thin_binary = ctx.actions.declare_output(ctx.attrs.name, has_content_based_path = False)
+    xctrunner_path = cmd_args(platform_path, "Developer/Library/Xcode/Agents/XCTRunner.app/XCTRunner", delimiter = "/")
+    ctx.actions.run(
+        [
+            lipo,
+            xctrunner_path,
+            "-extract",
+            arch,
+            "-output",
+            thin_binary.as_output(),
+        ],
+        category = "copy_xctrunner",
+    )
+
+    return AppleBundlePart(
+        source = thin_binary,
+        destination = AppleBundleDestination("executables"),
+    )
+
+def _get_xctrunner_frameworks(ctx: AnalysisContext) -> list[AppleBundlePart]:
+    # We need to copy the framework as AppleBundlePart requires an artifact.
+    # It would be nicer to make this an arglike and avoid the copies.
+    # It would also be nicer to exclude the headers.
+    def copy_platform_framework(platform_relative_path: str) -> AppleBundlePart:
+        copied_framework = ctx.actions.declare_output(paths.basename(platform_relative_path), has_content_based_path = False)
+        path = cmd_args(ctx.attrs._apple_toolchain[AppleToolchainInfo].platform_path, platform_relative_path, delimiter = "/")
+        ctx.actions.run(["cp", "-PR", path, copied_framework.as_output()], category = "copy_framework", identifier = platform_relative_path)
+        return AppleBundlePart(
+            source = copied_framework,
+            destination = AppleBundleDestination("frameworks"),
+            codesign_on_copy = True,
+        )
+
+    runner_frameworks = [
+        "Developer/Library/Frameworks/XCTest.framework",
+        "Developer/Library/PrivateFrameworks/XCTAutomationSupport.framework",
+        "Developer/Library/PrivateFrameworks/XCTestCore.framework",
+        "Developer/Library/PrivateFrameworks/XCTestSupport.framework",
+        "Developer/Library/PrivateFrameworks/XCUnit.framework",
+    ]
+
+    # From Xcode 16.3 XCUIAutomation is in Frameworks, not PrivateFrameworks
+    xcode_version = int(ctx.attrs._apple_toolchain[AppleToolchainInfo].xcode_version)
+    if xcode_version >= 1630:
+        runner_frameworks.append("Developer/Library/Frameworks/XCUIAutomation.framework")
+    else:
+        runner_frameworks.append("Developer/Library/PrivateFrameworks/XCUIAutomation.framework")
+    return [copy_platform_framework(p) for p in runner_frameworks]
diff --git a/buck2/prelude/apple/arch.bzl b/buck2/prelude/apple/arch.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/arch.bzl
@@ -0,0 +1,16 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+_APPLE_ARCHES = [
+    "arm64",
+    "arm64e",
+    "arm64_32",
+    "x86_64",
+]
+
+AppleArch = enum(*_APPLE_ARCHES)
diff --git a/buck2/prelude/apple/cxx_universal_executable.bzl b/buck2/prelude/apple/cxx_universal_executable.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/cxx_universal_executable.bzl
@@ -0,0 +1,32 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_universal_binaries.bzl", "get_universal_binary_name", "lipo_binaries")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+
+def cxx_universal_executable_impl(ctx: AnalysisContext) -> list[Provider]:
+    lipo = ctx.attrs._cxx_toolchain[CxxToolchainInfo].lipo
+    if not lipo:
+        fail("`cxx_toolchain()` target does not have a valid `lipo` tool: {}".format(ctx.attrs._cxx_toolchain.label))
+
+    universal_binary = lipo_binaries(
+        ctx = ctx,
+        binary_deps = ctx.attrs.executable,
+        binary_name = get_universal_binary_name(ctx),
+        lipo = lipo,
+    )
+
+    sub_targets = {arch: [DefaultInfo(default_output = binary[DefaultInfo].default_outputs[0])] for arch, binary in ctx.attrs.executable.items()}
+
+    return [
+        DefaultInfo(
+            default_output = universal_binary,
+            sub_targets = sub_targets,
+        ),
+        RunInfo(args = cmd_args(universal_binary)),
+    ]
diff --git a/buck2/prelude/apple/debug.bzl b/buck2/prelude/apple/debug.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/debug.bzl
@@ -0,0 +1,113 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+    "make_artifact_tset",
+    "project_artifacts",
+)
+
+DEBUGINFO_SUBTARGET = "debuginfo"
+DEBUGINFO_DB_SUBTARGET = "debuginfo-db"
+
+AppleDebugInfo = TransitiveSetArgsProjection
+
+AppleSelectiveDebuggableMetadata = record(
+    # dSYM which the metadata applies for.
+    dsym = field(Artifact),
+    # JSON file containing metadata about the dSYM.
+    #
+    # This must be an artifact because there's no access to the focused targets
+    # JSON file at analysis time.
+    metadata = field(Artifact),
+)
+
+# Represents Apple debug info from both executables and bundles.
+AppleDebuggableInfo = provider(
+    fields = {
+        "binaries": provider_field(list[Artifact], default = []),
+        # Tset containing ArtifactInfos with either
+        # a. the owning library target to artifacts, or
+        # b. the owning bundle target to filtered artifacts
+        "debug_info_tset": provider_field(ArtifactTSet),
+        "dsyms": provider_field(list[Artifact]),
+        # In the case of b above, contains the map of library target to artifacts, else None
+        "filtered_map": provider_field([dict[Label, list[Artifact]], None], default = None),
+        "selective_metadata": provider_field(list[AppleSelectiveDebuggableMetadata], default = []),
+    },
+)
+
+_AppleDebugInfo = record(
+    debug_info_tset = ArtifactTSet,
+    filtered_map = field([dict[Label, list[Artifact]], None]),
+)
+
+AggregatedAppleDebugInfo = record(
+    debug_info = field(_AppleDebugInfo),
+    # debug_info_tset = field(ArtifactTSet),
+    sub_targets = field(dict[str, list[DefaultInfo]]),
+)
+
+def get_aggregated_debug_info(ctx: AnalysisContext, debug_infos: list[AppleDebuggableInfo]) -> AggregatedAppleDebugInfo:
+    all_debug_info_tsets = []
+    full_debug_info_tsets = []
+    debug_info_map = {}
+
+    # If the AppleDebuggableInfo has a filtered map, the tset contains filtered info with a label equivalent to the bundle that propagated the
+    # artifacts. Thus, we need to track whether any of the infos have a filtered map, and if so propagate the filtered map.
+    any_info_has_filtered_map = False
+    for info in debug_infos:
+        all_debug_info_tsets.append(info.debug_info_tset)
+
+        if info.filtered_map:
+            debug_info_map.update(info.filtered_map)
+            any_info_has_filtered_map = True
+        else:
+            full_debug_info_tsets.append(info.debug_info_tset)
+
+    debug_info_tset = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        children = all_debug_info_tsets,
+    )
+    sub_targets = {}
+    sub_targets[DEBUGINFO_SUBTARGET] = [
+        DefaultInfo(
+            default_output = ctx.actions.write(
+                "debuginfo.artifacts",
+                project_artifacts(
+                    actions = ctx.actions,
+                    tsets = debug_info_tset,
+                ),
+                with_inputs = True,
+                has_content_based_path = False,
+            )
+        ),
+    ]
+
+    full_debug_info_tset = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        children = full_debug_info_tsets,
+    )
+    if full_debug_info_tset._tset:
+        debug_info_map.update({info.label: info.artifacts for infos in full_debug_info_tset._tset.traverse() for info in infos})
+
+    sub_targets[DEBUGINFO_DB_SUBTARGET] = [
+        DefaultInfo(
+            default_output = ctx.actions.write_json(DEBUGINFO_DB_SUBTARGET, debug_info_map, has_content_based_path = False),
+        ),
+    ]
+    return AggregatedAppleDebugInfo(
+        debug_info = _AppleDebugInfo(
+            debug_info_tset = debug_info_tset,
+            filtered_map = debug_info_map if any_info_has_filtered_map else None,
+        ),
+        sub_targets = sub_targets,
+    )
diff --git a/buck2/prelude/apple/mockingbird/mockingbird_mock.bzl b/buck2/prelude/apple/mockingbird/mockingbird_mock.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/mockingbird/mockingbird_mock.bzl
@@ -0,0 +1,191 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_platforms.bzl", "APPLE_PLATFORMS_KEY")
+load(
+    ":mockingbird_types.bzl",
+    "MockingbirdLibraryInfo",
+    "MockingbirdLibraryRecord",
+    "MockingbirdSourcesInfo",
+    "MockingbirdToolchainInfo",
+)
+
+def mockingbird_mock_impl(ctx: AnalysisContext) -> list[Provider]:
+    if not MockingbirdLibraryInfo in ctx.attrs.module:
+        fail("This module does not contain any swift files. Mockingbird only creates generated mock files for swift code.")
+
+    mockingbird_info = ctx.attrs.module[MockingbirdLibraryInfo]
+
+    dep_names = [dep[MockingbirdLibraryInfo].name for dep in ctx.attrs.deps]
+    included_srcs = [src.basename for src in ctx.attrs.srcs]
+    excluded_srcs = [src.basename for src in ctx.attrs.excluded_srcs]
+
+    for src_name in included_srcs:
+        if not src_name.endswith(".swift"):
+            fail("srcs should only specify Swift files. Other source files, such as {}, do not need to be included.".format(src_name))
+
+    for src_name in excluded_srcs:
+        if not src_name.endswith(".swift"):
+            fail("excluded_srcs should only specify Swift files. Other source files, such as {}, do not need to be included.".format(src_name))
+
+    (json_project_description, src_dirs) = _get_mockingbird_json_project_description(
+        info = mockingbird_info, included_srcs = included_srcs, excluded_srcs = excluded_srcs, dep_names = dep_names
+    )
+    json_project_description_output = ctx.actions.declare_output("mockingbird_project.json", has_content_based_path = True)
+    ctx.actions.write_json(json_project_description_output.as_output(), json_project_description)
+
+    mockingbird_source = ctx.actions.declare_output(mockingbird_info.name + "Mocks.generated.swift", dir = False, has_content_based_path = True)
+    cmd = cmd_args(
+        hidden = src_dirs,
+    )
+
+    params = [
+        ctx.attrs._mockingbird_toolchain[MockingbirdToolchainInfo].bin,
+        "generate",
+        "--target",
+        mockingbird_info.name,
+        "--project",
+        json_project_description_output,
+        "--output",
+        mockingbird_source.as_output(),
+        "--support",
+        ctx.attrs._mockingbird_toolchain[MockingbirdToolchainInfo].support,
+        "--verbose",
+        "--disable-cache",
+    ]
+
+    if ctx.attrs.only_protocols:
+        params.append("--only-protocols")
+
+    cmd.add(params)
+
+    ctx.actions.run(
+        cmd,
+        category = "mockingbird",
+        local_only = True,  # Mockingbird creates sockets for interprocess communication, which is deliberately blocked on RE.
+        allow_cache_upload = True,
+    )
+
+    return [
+        DefaultInfo(mockingbird_source),
+        MockingbirdSourcesInfo(srcs = [mockingbird_source]),
+    ]
+
+def mockingbird_mock_attrs():
+    attribs = {
+        ## If the superclass for an object being mocked is in another module add it as a dep so mockingbird can find the implementation.
+        "deps": attrs.list(attrs.dep(), default = []),
+        ## The list of source files to exclude. Only the name of the file, excluding the path, should be set. If set, the srcs attribute will be ignored.
+        "excluded_srcs": attrs.set(attrs.source(), sorted = True, default = []),
+        ## The module to generate mocks for.
+        "module": attrs.dep(),
+        ## Whether to only generate mocks for Swift protocols.
+        "only_protocols": attrs.bool(default = False),
+        ## A list of source files to include. Only the name of the file, excluding the path, should be set. By default all source files are included and this doesn't need to be specified.
+        "srcs": attrs.set(attrs.source(), sorted = True, default = []),
+        "_mockingbird_toolchain": attrs.toolchain_dep(providers = [MockingbirdToolchainInfo], default = "toolchains//:mockingbird"),
+        APPLE_PLATFORMS_KEY: attrs.dict(key = attrs.string(), value = attrs.dep(), sorted = False, default = {}),
+    }
+    return attribs
+
+# Produce JSON project description for Mockingbird codegen
+# https://mockingbirdswift.com/json-project-description
+# {
+#   "targets": [
+#     {
+#       "name": "MyLibrary",
+#       "type": "library",
+#       "path": "/path/to/MyLibrary",
+#       "dependencies": [],
+#       "sources": [
+#         "SourceFileA.swift",
+#         "SourceFileB.swift"
+#       ]
+#     },
+#     {
+#       "name": "MyOtherLibrary",
+#       "type": "library",
+#       "path": "/path/to/MyOtherLibrary",
+#       "dependencies": [
+#         "MyLibrary"
+#       ],
+#       "sources": [
+#         "SourceFileA.swift",
+#         "SourceFileB.swift"
+#       ]
+#     },
+#     {
+#       "name": "MyLibraryTests",
+#       "type": "test",
+#       "path": "/path/to/MyLibraryTests",
+#       "dependencies": [
+#         "MyLibrary"
+#       ],
+#       "sources": [
+#         "SourceFileA.swift",
+#         "SourceFileB.swift"
+#       ]
+#     }
+#   ]
+# }
+def _get_mockingbird_json_project_description(
+    info: MockingbirdLibraryInfo, included_srcs: list[str], excluded_srcs: list[str], dep_names: list[str]
+) -> (dict, list):
+    targets = []
+    src_dirs = []
+    for record in info.tset.traverse():
+        if record.name == info.name:
+            targets.append(
+                _target_dict_for_mockingbird_record(record = record, included_srcs = included_srcs, excluded_srcs = excluded_srcs, include_non_exported_deps = True)
+            )
+            src_dirs.append(record.src_dir)
+        elif record.name in dep_names:
+            targets.append(_target_dict_for_mockingbird_record(record = record, included_srcs = [], excluded_srcs = [], include_non_exported_deps = False))
+            src_dirs.append(record.src_dir)
+    json = {
+        "targets": targets,
+    }
+
+    return (json, src_dirs)
+
+def _target_dict_for_mockingbird_record(
+    record: MockingbirdLibraryRecord, included_srcs: list[str], excluded_srcs: list[str], include_non_exported_deps: bool
+) -> dict:
+    srcs = []
+    if len(included_srcs) > 0 and len(excluded_srcs) > 0:
+        fail("Included srcs and excluded srcs cannot both be set at the same time")
+
+    record_src_names = [src.basename for src in record.srcs]
+
+    for specified_src in included_srcs + excluded_srcs:
+        if specified_src not in record_src_names:
+            fail("The source file {} does not exist in target {}".format(specified_src, record.name))
+
+    if len(included_srcs) > 0:
+        for src_name in record_src_names:
+            if src_name in included_srcs:
+                srcs.append(src_name)
+    elif len(excluded_srcs) > 0:
+        for src_name in record_src_names:
+            if src_name not in excluded_srcs:
+                srcs.append(src_name)
+    else:
+        srcs = record_src_names
+
+    deps = record.exported_dep_names
+
+    if include_non_exported_deps:
+        deps = deps + record.dep_names
+
+    return {
+        "dependencies": deps,
+        "name": record.name,
+        "path": record.src_dir,
+        "sources": srcs,
+        "type": record.type,
+    }
diff --git a/buck2/prelude/apple/mockingbird/mockingbird_types.bzl b/buck2/prelude/apple/mockingbird/mockingbird_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/mockingbird/mockingbird_types.bzl
@@ -0,0 +1,50 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+MockingbirdLibraryInfoTSet = transitive_set()
+
+MockingbirdTargetType = enum("library", "test")
+
+MockingbirdLibraryInfo = provider(
+    fields = {
+        # The Swift module name.
+        "name": provider_field(str),
+        # Contains a tset with this module's MockingbirdLibraryRecord as the value
+        # and all of its dependencies' MockingbirdLibraryRecord in the children.
+        "tset": provider_field(MockingbirdLibraryInfoTSet),
+    },
+)
+
+MockingbirdLibraryRecord = record(
+    # The Swift module names of this module's dependencies.
+    dep_names = field(list[str]),
+    # The Swift module names of this module's exported dependencies.
+    exported_dep_names = field(list[str]),
+    # The Swift module name.
+    name = str,
+    # Swift sources in this target.
+    srcs = field(list[Artifact]),
+    # Whether this is a library or a test.
+    type = field(MockingbirdTargetType),
+    # Symlinked directory containing the source files.
+    src_dir = field(Artifact),
+)
+
+MockingbirdSourcesInfo = provider(
+    fields = {
+        # Source files containing the auto generated mocks produced by mockingbird-cli.
+        "srcs": provider_field(list[Artifact]),
+    },
+)
+
+MockingbirdToolchainInfo = provider(
+    fields = {
+        "bin": cmd_args,
+        "support": Artifact,
+    }
+)
diff --git a/buck2/prelude/apple/modularization_dependency_graph.bzl b/buck2/prelude/apple/modularization_dependency_graph.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/modularization_dependency_graph.bzl
@@ -0,0 +1,55 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+    "make_artifact_tset",
+    "project_artifacts",
+)
+
+ModularizationDependencyGraphInfo = provider(
+    fields = {
+        "tset": provider_field(ArtifactTSet),
+    },
+)
+
+def create_modularization_dep_graph_subtargets_and_provider(
+    ctx: AnalysisContext,
+    modularization_dependency_graph: Artifact | None,
+    deps: list[Dependency],
+) -> (dict[str, list[Provider]], ModularizationDependencyGraphInfo):
+    children = [info.tset for info in filter(None, [dep.get(ModularizationDependencyGraphInfo) for dep in deps])]
+
+    tset = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label if modularization_dependency_graph else None,
+        artifacts = [modularization_dependency_graph] if modularization_dependency_graph else [],
+        children = children,
+    )
+
+    all_graphs = project_artifacts(actions = ctx.actions, tsets = tset)
+
+    sub_targets = {
+        "all-modularization-dependency-graphs": [
+            DefaultInfo(
+                default_output = None,
+                other_outputs = all_graphs,
+            ),
+        ],
+        "modularization-dependency-graph": [
+            DefaultInfo(
+                default_output = modularization_dependency_graph,
+                other_outputs = all_graphs,
+            ),
+        ],
+    }
+
+    info = ModularizationDependencyGraphInfo(tset = tset)
+
+    return (sub_targets, info)
diff --git a/buck2/prelude/apple/modulemap.bzl b/buck2/prelude/apple/modulemap.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/modulemap.bzl
@@ -0,0 +1,111 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")
+load(
+    "@prelude//apple/swift:swift_incremental_support.bzl",
+    "get_uses_content_based_paths",
+)
+load("@prelude//apple/swift:swift_toolchain.bzl", "supports_modulemaps_with_hmaps")
+load(
+    "@prelude//cxx:headers.bzl",
+    "CHeader",  # @unused Used as a type
+)
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "CPreprocessor",
+)
+
+def create_modulemap(
+    ctx: AnalysisContext, name: str, module_name: str, headers: list[CHeader], swift_header: Artifact | None = None, is_framework: bool = False
+) -> CPreprocessor:
+    # We don't want to name this module.modulemap to avoid implicit importing
+    if name == "module" and not is_framework:
+        fail("Don't use the name `module` for modulemaps, this will allow for implicit importing.")
+
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+    use_relative_paths = supports_modulemaps_with_hmaps(ctx)
+
+    # Create a map of header import path to artifact location
+    header_map = {}
+    for h in headers:
+        if h.namespace:
+            header_map["{}/{}".format(h.namespace, h.name)] = h.artifact
+        else:
+            header_map[h.name] = h.artifact
+
+    swift_header_name = None
+    if swift_header:
+        # We need to include the Swift header in the symlink tree too
+        swift_header_name = "{}/{}-Swift.h".format(module_name, module_name)
+        header_map[swift_header_name] = swift_header
+
+    if use_relative_paths:
+        symlink_tree = None
+    else:
+        # Create a symlink dir for the headers to import
+        symlink_tree_name = name.replace(".", "_") + "_symlink_tree"
+        symlink_tree = ctx.actions.symlinked_dir(symlink_tree_name, header_map, has_content_based_path = uses_content_based_paths)
+
+    output = ctx.actions.declare_output(name + ".modulemap", has_content_based_path = uses_content_based_paths)
+    cmd = cmd_args(ctx.attrs._apple_tools[AppleToolsInfo].make_modulemap)
+    cmd.add(
+        "--output",
+        output.as_output(),
+        "--name",
+        module_name,
+    )
+
+    if swift_header:
+        cmd.add(
+            "--swift-header",
+            swift_header if use_relative_paths else cmd_args(symlink_tree, format = "{}/" + swift_header_name),
+        )
+
+    if getattr(ctx.attrs, "use_submodules", False):
+        cmd.add("--use-submodules")
+
+    if is_framework:
+        cmd.add("--framework")
+
+    for include_path in sorted(header_map.keys()):
+        # Don't include the Swift header in the mappings, this is handled separately.
+        if include_path == swift_header_name:
+            continue
+
+        if is_framework:
+            # Framework headers are the same as their include paths, they are
+            # compiled relative to the framework's Headers folder.
+            cmd.add(include_path)
+            cmd.add(include_path)
+        elif use_relative_paths:
+            # The path to the header artifact is relative to the containing
+            # folder of the modulemap. We can't get the paths in the prelude,
+            # the relativizing is done in the generation tool.
+            cmd.add(include_path)
+            cmd.add(header_map[include_path])
+        else:
+            # With symlink trees the include path should match the symlink name
+            # nested in the symlink tree root.
+            cmd.add(include_path)
+            cmd.add(cmd_args(symlink_tree, format = "{}/" + include_path))
+
+    ctx.actions.run(cmd, category = "modulemap", identifier = name)
+
+    header_artifacts = header_map.values()
+    modular_args = [cmd_args(output, format = "-fmodule-map-file={}", hidden = header_artifacts)]
+    if not use_relative_paths and not is_framework:
+        # When using relative paths we rely on the hmaps provided by regular
+        # cxx preprocessor.
+        modular_args.append(cmd_args(symlink_tree, format = "-I{}"))
+        header_artifacts.append(symlink_tree)
+
+    return CPreprocessor(
+        modular_args = modular_args,
+        modulemap_artifact = output.with_associated_artifacts(header_artifacts),
+    )
diff --git a/buck2/prelude/apple/prebuilt_apple_framework.bzl b/buck2/prelude/apple/prebuilt_apple_framework.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/prebuilt_apple_framework.bzl
@@ -0,0 +1,340 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactInfoTag",
+    "ArtifactTSet",
+    "make_artifact_tset",
+)
+load("@prelude//apple:apple_stripping.bzl", "apple_strip_args")
+load("@prelude//apple:apple_utility.bzl", "get_base_swiftinterface_compilation_flags")
+load("@prelude//apple/swift:apple_sdk_modules_utility.bzl", "is_sdk_modules_provided")
+load(
+    "@prelude//apple/swift:swift_compilation.bzl",
+    "create_swift_dependency_info",
+    "get_external_debug_info_tsets",
+    "get_external_swift_ast_dump_tsets",
+    "get_external_swiftmodule_change_analysis_tsets",
+    "get_swift_anonymous_targets_for_prebuilt_framework",
+)
+load(
+    "@prelude//apple/swift:swift_incremental_support.bzl",
+    "get_uses_content_based_paths",
+)
+load("@prelude//apple/swift:swift_pcm_compilation.bzl", "compile_framework_pcm")
+load(
+    "@prelude//apple/swift:swift_pcm_compilation_types.bzl",
+    "SwiftPCMUncompiledInfo",
+)
+load("@prelude//apple/swift:swift_swiftinterface_compilation.bzl", "compile_swiftinterface_common")
+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftCompiledModuleTset", "SwiftToolchainInfo")
+load("@prelude//apple/swift:swift_types.bzl", "FrameworkImplicitSearchPathInfo", "SwiftDependencyInfo", "get_implicit_framework_search_path_providers")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_library_utility.bzl",
+    "cxx_attr_preferred_linkage",
+    "cxx_platform_supported",
+)
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorArgs",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+)
+load("@prelude//cxx:target_sdk_version.bzl", "get_target_triple", "get_unversioned_target_triple")
+load(
+    "@prelude//linking:link_groups.bzl",
+    "merge_link_group_lib_info",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "Archive",
+    "ArchiveLinkable",
+    "LibOutputStyle",
+    "LinkInfo",
+    "LinkInfos",
+    "SharedLibLinkable",
+    "create_merged_link_info",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+    "create_linkable_node",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "merge_shared_libraries",
+)
+load("@prelude//linking:strip.bzl", "strip_object")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//utils:utils.bzl", "filter_and_map_idx")
+load(":apple_bundle_types.bzl", "AppleBundleInfo", "AppleBundleTypeDefault")
+load(":apple_dsym.bzl", "DSYM_SUBTARGET")
+load(":apple_frameworks.bzl", "to_framework_name")
+load(":apple_toolchain_types.bzl", "AppleToolsInfo")
+load(":apple_utility.bzl", "get_apple_stripped_attr_value_with_default_fallback")
+load(":debug.bzl", "AppleDebuggableInfo")
+
+def _get_compiled_swift_deps_tset(ctx: AnalysisContext, deps_providers: list) -> SwiftCompiledModuleTset:
+    deps = [d[SwiftDependencyInfo].exported_swiftmodules for d in deps_providers if SwiftDependencyInfo in d]
+    return ctx.actions.tset(SwiftCompiledModuleTset, children = deps)
+
+def prebuilt_apple_framework_impl(ctx: AnalysisContext) -> [list[Provider], Promise]:
+    def get_prebuilt_apple_framework_providers(deps_providers) -> list[Provider]:
+        providers = []
+
+        framework_directory_artifact = ctx.attrs.framework
+        framework_name = to_framework_name(framework_directory_artifact.basename)
+        framework_binary_name = ctx.attrs.binary if ctx.attrs.binary else framework_name
+        framework_library_artifact = framework_directory_artifact.project(framework_binary_name)
+
+        # Check this rule's `supported_platforms_regex` with the current platform.
+        if cxx_platform_supported(ctx):
+            uses_content_based_path = get_uses_content_based_paths(ctx)
+
+            # Sandbox the framework, to avoid leaking other frameworks via search paths.
+            framework_dir = ctx.actions.symlinked_dir(
+                "Frameworks",
+                {framework_name + ".framework": framework_directory_artifact},
+                has_content_based_path = uses_content_based_path,
+            )
+
+            # Add framework & pp info from deps.
+            inherited_pp_info = cxx_inherited_preprocessor_infos(ctx.attrs.deps)
+            providers.append(
+                cxx_merge_cpreprocessors(
+                    ctx.actions,
+                    [CPreprocessor(args = CPreprocessorArgs(args = ["-F", framework_dir]))],
+                    inherited_pp_info,
+                )
+            )
+
+            if cxx_attr_preferred_linkage(ctx) == Linkage("static"):
+                linkable = ArchiveLinkable(
+                    archive = Archive(artifact = framework_library_artifact),
+                    linker_type = get_cxx_toolchain_info(ctx).linker_info.type,
+                )
+            else:
+                # If unspecified we default to "shared".
+                linkable = SharedLibLinkable(
+                    lib = framework_library_artifact,
+                )
+
+            link = LinkInfo(
+                name = framework_name,
+                linkables = [linkable],
+                pre_flags = [ctx.attrs.exported_linker_flags],
+            )
+            link_info = LinkInfos(default = link)
+
+            providers.append(
+                create_merged_link_info(
+                    ctx,
+                    get_cxx_toolchain_info(ctx).pic_behavior,
+                    {output_style: link_info for output_style in LibOutputStyle},
+                )
+            )
+
+            # Create, augment and provide the linkable graph.
+            linkable_graph = create_linkable_graph(
+                ctx,
+                node = create_linkable_graph_node(
+                    ctx,
+                    linkable_node = create_linkable_node(
+                        ctx,
+                        link_infos = {output_style: link_info for output_style in LibOutputStyle},
+                        # TODO(cjhopman): this should be set to non-None
+                        default_soname = None,
+                    ),
+                    excluded = {ctx.label: None},
+                ),
+            )
+            providers.append(linkable_graph)
+
+        providers.append(merge_link_group_lib_info(deps = ctx.attrs.deps))
+        providers.append(merge_shared_libraries(ctx.actions, deps = filter_and_map_idx(SharedLibraryInfo, ctx.attrs.deps)))
+
+        # The default output is the provided framework.
+        sub_targets = {
+            "distribution": _sanitize_framework_for_app_distribution(ctx, framework_directory_artifact) + providers,
+        }
+
+        if ctx.attrs.dsyms:
+            sub_targets[DSYM_SUBTARGET] = [DefaultInfo(default_outputs = ctx.attrs.dsyms)]
+            providers.append(AppleDebuggableInfo(dsyms = ctx.attrs.dsyms, debug_info_tset = ArtifactTSet()))
+
+        providers.append(DefaultInfo(default_output = framework_directory_artifact, sub_targets = sub_targets))
+        providers.append(
+            AppleBundleInfo(
+                bundle = framework_directory_artifact,
+                bundle_type = AppleBundleTypeDefault,
+                skip_copying_swift_stdlib = True,
+                contains_watchapp = None,
+                extra_codesign_paths = ctx.attrs.extra_codesign_paths,
+            )
+        )
+
+        if ctx.attrs.modular:
+            pcm_provider = _create_uncompiled_pcm_module_info(ctx, framework_directory_artifact, framework_name)
+            providers.append(pcm_provider)
+
+            # Since not all frameworks expose a swiftinterface, we use the `contains_swift` attribute to determine if one is available.
+            if ctx.attrs.contains_swift:
+                swift_dependency_info = _compile_swiftinterface(
+                    ctx,
+                    framework_name,
+                    pcm_provider,
+                    deps_providers,
+                    framework_directory_artifact,
+                )
+                providers.append(swift_dependency_info)
+
+        implicit_search_path_tset = get_implicit_framework_search_path_providers(
+            ctx,
+            cmd_args("-F", cmd_args(framework_directory_artifact, parent = 1)),
+            ctx.attrs.deps,
+        )
+
+        providers.append(
+            FrameworkImplicitSearchPathInfo(tset = implicit_search_path_tset),
+        )
+
+        return providers
+
+    # We cannot determine whether Swift Explicit modules are enabled at this point.
+    # Therefore, we always return providers for both Implicit and Explicit modules, if SDK modules are available.
+    # This approach is safe and won't trigger compilation of swiftinterfaces or pcm modules,
+    # as no upper-level targets will depend on the artifacts from these compilations.
+    swift_toolchain = ctx.attrs._apple_toolchain[SwiftToolchainInfo]
+    if is_sdk_modules_provided(swift_toolchain):
+        return get_swift_anonymous_targets_for_prebuilt_framework(ctx, get_prebuilt_apple_framework_providers)
+    else:
+        return get_prebuilt_apple_framework_providers([])
+
+def _create_uncompiled_pcm_module_info(ctx: AnalysisContext, framework_directory_artifact: Artifact, framework_name: str) -> SwiftPCMUncompiledInfo:
+    modulemap_artifact = framework_directory_artifact.project("Modules/module.modulemap").with_associated_artifacts([framework_directory_artifact])
+    clang_importer_args = cmd_args(framework_directory_artifact, parent = 1, format = "-F{}")
+    return SwiftPCMUncompiledInfo(
+        clang_importer_args = cmd_args(),
+        exported_clang_importer_args = clang_importer_args,
+        exported_deps = ctx.attrs.deps,
+        is_transient = False,
+        modulemap_artifact = modulemap_artifact,
+        name = framework_name,
+        uncompiled_sdk_modules = ctx.attrs.sdk_modules,
+    )
+
+def _compile_swiftinterface(
+    ctx: AnalysisContext, framework_name: str, pcm_provider: SwiftPCMUncompiledInfo, deps_providers, framework_directory_artifact: Artifact
+) -> SwiftDependencyInfo:
+    # To compile the framework's swiftinterface, the PCM module must be precompiled first.
+    compiled_underlying_pcm = compile_framework_pcm(
+        ctx,
+        framework_name,
+        pcm_provider,
+        deps_providers,
+        ["-target", get_target_triple(ctx)],
+    )
+
+    partial_cmd = get_base_swiftinterface_compilation_flags(framework_name)
+
+    swiftinterface_path = cmd_args(
+        framework_directory_artifact,
+        "/Modules/",
+        framework_name,
+        ".swiftmodule/" + get_unversioned_target_triple(ctx) + ".swiftinterface",
+        delimiter = "",
+    )
+
+    swift_third_party_deps = _get_compiled_swift_deps_tset(ctx, ctx.attrs.deps)
+
+    swift_compiled_module, _ = compile_swiftinterface_common(
+        ctx,
+        ctx.attrs.deps,
+        True,  # is_framework
+        framework_name,
+        partial_cmd,
+        deps_providers,
+        swiftinterface_path,
+        "prebuilt_framework_swiftinterface_compilation",
+        compiled_underlying_pcm,
+        additional_compiled_swiftmodules = swift_third_party_deps,
+    )
+
+    debug_info_tset = make_artifact_tset(
+        actions = ctx.actions,
+        artifacts = [swift_compiled_module.output_artifact, compiled_underlying_pcm.output_artifact],
+        children = get_external_debug_info_tsets(False, ctx.attrs.deps),
+        label = ctx.label,
+        tags = [ArtifactInfoTag("swift_debug_info")],
+    )
+
+    swiftmodule_change_analysis_tset = make_artifact_tset(
+        actions = ctx.actions,
+        # Just the swiftmodule, not the underlying PCM (unlike debug_info_tset
+        # above): PCM-only changes aren't swiftmodule changes, and including it
+        # would re-run this analysis action whenever the PCM changes for no
+        # reason.
+        artifacts = [swift_compiled_module.output_artifact],
+        children = get_external_swiftmodule_change_analysis_tsets(False, ctx.attrs.deps),
+        label = ctx.label,
+    )
+
+    swift_ast_dump_tset = make_artifact_tset(
+        actions = ctx.actions,
+        children = get_external_swift_ast_dump_tsets(False, ctx.attrs.deps),
+        label = ctx.label,
+    )
+
+    swift_dependency_info = create_swift_dependency_info(
+        ctx,
+        ctx.attrs.deps,
+        deps_providers,
+        swift_compiled_module,
+        debug_info_tset,
+        swiftmodule_change_analysis_tset,
+        swift_ast_dump_tset,
+        False,
+    )
+
+    return swift_dependency_info
+
+def _sanitize_framework_for_app_distribution(ctx: AnalysisContext, framework_directory_artifact: Artifact) -> list[Provider]:
+    framework_name = to_framework_name(framework_directory_artifact.basename)
+    bundle_for_app_distribution = ctx.actions.declare_output(framework_name + ".framework", dir = True, has_content_based_path = False)
+
+    apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]
+    framework_sanitize_command = cmd_args([
+        apple_tools.framework_sanitizer,
+        "--input",
+        framework_directory_artifact,
+        "--output",
+        bundle_for_app_distribution.as_output(),
+    ])
+
+    if get_apple_stripped_attr_value_with_default_fallback(ctx):
+        strip_args = apple_strip_args(ctx)
+        stripped = strip_object(ctx, get_cxx_toolchain_info(ctx), framework_directory_artifact.project(framework_name), strip_args, "framework_distribution")
+        framework_sanitize_command.add("--replacement-binary", stripped)
+
+    ctx.actions.run(framework_sanitize_command, category = "sanitize_prebuilt_apple_framework")
+    providers = [DefaultInfo(default_output = bundle_for_app_distribution)]
+    providers.append(
+        AppleBundleInfo(
+            bundle = bundle_for_app_distribution,
+            bundle_type = AppleBundleTypeDefault,
+            skip_copying_swift_stdlib = True,
+            contains_watchapp = None,
+            extra_codesign_paths = ctx.attrs.extra_codesign_paths,
+        )
+    )
+    return providers
diff --git a/buck2/prelude/apple/prebuilt_apple_xcframework_macro_impl.bzl b/buck2/prelude/apple/prebuilt_apple_xcframework_macro_impl.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/prebuilt_apple_xcframework_macro_impl.bzl
@@ -0,0 +1,276 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:arch.bzl", "AppleArch")
+load("@prelude//utils:glob_defs.bzl", "subdir_glob")
+load("@prelude//utils:selects.bzl", "selects")
+
+def _generate_framework_and_dsym_select_maps(prebuilt_xcframework_args, platform_filter, default_arch, default_target_platform, genrule):
+    """
+    Generate genrules for frameworks and dsyms, and return select maps for the attributes.
+    Returns a tuple of (framework_select_map, dsym_select_map) where each maps config conditions to targets/artifacts.
+    """
+    name = prebuilt_xcframework_args.name
+    platforms = prebuilt_xcframework_args.platforms
+    xcframework = prebuilt_xcframework_args.xcframework
+    framework_name = prebuilt_xcframework_args.framework_name
+    framework_platforms_to_dsym_filenames = prebuilt_xcframework_args.framework_platforms_to_dsym_filenames
+
+    framework_select_map = {}
+    dsym_select_map = {}
+
+    for platform in platforms:
+        if platform_filter(platform):
+            bash_cmd = "mkdir $OUT && cp -R $(location {})/{}/{}.framework/* $OUT/".format(xcframework, platform["folder"], framework_name)
+            assemble_name = "{}-{}-assemble".format(name, platform["folder"])
+            genrule(
+                name = assemble_name,
+                bash = bash_cmd,
+                out = framework_name + ".framework",
+                default_target_platform = default_target_platform,
+                has_content_based_path = True,
+            )
+
+            dsym_artifacts = selects.apply(
+                framework_platforms_to_dsym_filenames,
+                partial(_generate_dsym_artifacts, name, platform["folder"], xcframework, default_target_platform, genrule),
+            )
+
+            for arch in platform["archs"]:
+                if arch not in ["arm64", "arm64e", "x86_64"]:
+                    fail("Unsupported " + platform["platform"] + " arch: " + arch)
+
+                config_key = "ovr_config//cpu:" + arch
+                framework_select_map[config_key] = ":" + assemble_name
+                dsym_select_map[config_key] = dsym_artifacts
+
+                # We want to set DEFAULT if
+                #  - We have specified a default_arch and it matches
+                #  - We haven't specified a default_arch in which case
+                #    we take the first match
+                if (default_arch != None and AppleArch(arch) == default_arch) or framework_select_map.get("DEFAULT") == None:
+                    framework_select_map["DEFAULT"] = ":" + assemble_name
+                    dsym_select_map["DEFAULT"] = dsym_artifacts
+
+    return (framework_select_map, dsym_select_map)
+
+def _generate_dsym_artifacts(name, platform_folder, xcframework, default_target_platform, genrule, framework_platforms_to_dsym_filenames):
+    return [
+        _generate_dsym_artifact(name, platform_folder, xcframework, default_target_platform, dsym_filename, genrule)
+        for dsym_filename in framework_platforms_to_dsym_filenames.get(platform_folder, [])
+    ]
+
+def _generate_dsym_artifact(name, platform_folder, xcframework, default_target_platform, dsym_filename, genrule):
+    bash_cmd_dsyms = "mkdir $OUT && cp -R $(location {})/{}/dSYMs/{}/* $OUT/".format(xcframework, platform_folder, dsym_filename)
+    dsym_name = "{}-{}-dsym".format(name, platform_folder)
+    genrule(
+        name = dsym_name,
+        bash = bash_cmd_dsyms,
+        out = dsym_filename,
+        default_target_platform = default_target_platform,
+        has_content_based_path = True,
+    )
+    return ":" + dsym_name
+
+def _generate_iphonesimulator_select_maps(prebuilt_xcframework_args, **kwargs):
+    return _generate_framework_and_dsym_select_maps(
+        prebuilt_xcframework_args = prebuilt_xcframework_args,
+        platform_filter = lambda platform: platform["platform"] == "ios" and platform["isSimulator"] and not platform["isCatalyst"],
+        default_arch = AppleArch("arm64"),
+        default_target_platform = "ovr_config//platform/iphoneos:iphonesimulator-arm64",
+        **kwargs,
+    )
+
+def _generate_iphone_select_maps(prebuilt_xcframework_args, **kwargs):
+    return _generate_framework_and_dsym_select_maps(
+        prebuilt_xcframework_args = prebuilt_xcframework_args,
+        platform_filter = lambda platform: platform["platform"] == "ios" and not platform["isSimulator"] and not platform["isCatalyst"],
+        default_arch = None,
+        default_target_platform = "ovr_config//platform/iphoneos:iphoneos-arm64",
+        **kwargs,
+    )
+
+def _generate_mac_select_maps(prebuilt_xcframework_args, **kwargs):
+    return _generate_framework_and_dsym_select_maps(
+        prebuilt_xcframework_args = prebuilt_xcframework_args,
+        platform_filter = lambda platform: platform["platform"] == "macos",
+        default_arch = None,
+        default_target_platform = "ovr_config//platform/macos:arm64-fbsource",
+        **kwargs,
+    )
+
+def _generate_maccatalyst_select_maps(prebuilt_xcframework_args, **kwargs):
+    return _generate_framework_and_dsym_select_maps(
+        prebuilt_xcframework_args = prebuilt_xcframework_args,
+        platform_filter = lambda platform: platform["platform"] == "ios" and not platform["isSimulator"] and platform["isCatalyst"],
+        default_arch = None,
+        default_target_platform = "ovr_config//platform/macos:arm64-catalyst",
+        **kwargs,
+    )
+
+def prebuilt_apple_xcframework_macro_impl(
+    prebuilt_apple_framework_rule,
+    filegroup_rule,
+    name,
+    xcframework,
+    framework_name,
+    framework_platforms,
+    framework_platforms_to_dsym_filenames = {},
+    default_target_platform = None,
+    **kwargs,
+):
+    compatible_with = kwargs.pop("compatible_with", None)
+
+    parsed_platforms = [_parse_platform(platform) for platform in framework_platforms]
+
+    # The xcframework is not required to be on disk, so we must make the folder path compatible with getting it from another target
+    if ":" in xcframework:
+        xcframework_target = xcframework
+    else:
+        xcframework_target = ":" + xcframework
+        filegroup_rule(
+            name = xcframework,
+            srcs = subdir_glob(
+                [
+                    (xcframework, "**/*"),
+                ],
+            ),
+        )
+
+    prebuilt_xcframework_args = struct(
+        name = name,
+        platforms = parsed_platforms,
+        xcframework = xcframework_target,
+        framework_name = framework_name,
+        framework_platforms_to_dsym_filenames = framework_platforms_to_dsym_filenames,
+    )
+
+    genrule = kwargs.pop("genrule", None)
+    if genrule == None:
+        fail("genrule must be provided")
+
+    # Generate framework/dsym genrules and get select maps for each platform
+    iphonesimulator_framework_map, iphonesimulator_dsym_map = _generate_iphonesimulator_select_maps(prebuilt_xcframework_args, genrule = genrule)
+    iphone_framework_map, iphone_dsym_map = _generate_iphone_select_maps(prebuilt_xcframework_args, genrule = genrule)
+    mac_framework_map, mac_dsym_map = _generate_mac_select_maps(prebuilt_xcframework_args, genrule = genrule)
+    maccatalyst_framework_map, maccatalyst_dsym_map = _generate_maccatalyst_select_maps(prebuilt_xcframework_args, genrule = genrule)
+
+    # Determine default platform's maps (priority: iphonesimulator > iphone > mac > maccatalyst)
+    default_framework_map = None
+    default_dsym_map = None
+
+    if len(iphonesimulator_framework_map) > 0:
+        default_framework_map = iphonesimulator_framework_map
+        default_dsym_map = iphonesimulator_dsym_map
+    elif len(iphone_framework_map) > 0:
+        default_framework_map = iphone_framework_map
+        default_dsym_map = iphone_dsym_map
+    elif len(mac_framework_map) > 0:
+        default_framework_map = mac_framework_map
+        default_dsym_map = mac_dsym_map
+    elif len(maccatalyst_framework_map) > 0:
+        default_framework_map = maccatalyst_framework_map
+        default_dsym_map = maccatalyst_dsym_map
+
+    if default_framework_map == None:
+        fail("No valid platforms found in xcframework")
+
+    # Build combined maps for iphonesimulator+maccatalyst (used for ovr_config//os:iphoneos and iphonesimulator SDK)
+    iphonesimulator_and_maccatalyst_framework_map = iphonesimulator_framework_map
+    iphonesimulator_and_maccatalyst_dsym_map = iphonesimulator_dsym_map
+    if len(maccatalyst_framework_map) > 0:
+        if len(iphonesimulator_framework_map) > 0:
+            iphonesimulator_and_maccatalyst_framework_map = {
+                "DEFAULT": select(iphonesimulator_framework_map),
+                "ovr_config//runtime/constraints:maccatalyst": select(maccatalyst_framework_map),
+            }
+            iphonesimulator_and_maccatalyst_dsym_map = {
+                "DEFAULT": select(iphonesimulator_dsym_map),
+                "ovr_config//runtime/constraints:maccatalyst": select(maccatalyst_dsym_map),
+            }
+        else:
+            iphonesimulator_and_maccatalyst_framework_map = maccatalyst_framework_map
+            iphonesimulator_and_maccatalyst_dsym_map = maccatalyst_dsym_map
+
+    # Build combined maps for iphone+maccatalyst (used for iphoneos SDK)
+    iphone_and_maccatalyst_framework_map = iphone_framework_map
+    iphone_and_maccatalyst_dsym_map = iphone_dsym_map
+    if len(maccatalyst_framework_map) > 0:
+        if len(iphone_framework_map) > 0:
+            iphone_and_maccatalyst_framework_map = {
+                "DEFAULT": select(iphone_framework_map),
+                "ovr_config//runtime/constraints:maccatalyst": select(maccatalyst_framework_map),
+            }
+            iphone_and_maccatalyst_dsym_map = {
+                "DEFAULT": select(iphone_dsym_map),
+                "ovr_config//runtime/constraints:maccatalyst": select(maccatalyst_dsym_map),
+            }
+        else:
+            iphone_and_maccatalyst_framework_map = maccatalyst_framework_map
+            iphone_and_maccatalyst_dsym_map = maccatalyst_dsym_map
+
+    # Build the nested select for framework attribute
+    framework_select_map = {"DEFAULT": select(default_framework_map)}
+    dsym_select_map = {"DEFAULT": select(default_dsym_map)}
+
+    if len(iphonesimulator_and_maccatalyst_framework_map) > 0:
+        framework_select_map["ovr_config//os:iphoneos"] = select(iphonesimulator_and_maccatalyst_framework_map)
+        framework_select_map["ovr_config//os/sdk/apple:iphonesimulator"] = select(iphonesimulator_and_maccatalyst_framework_map)
+        dsym_select_map["ovr_config//os:iphoneos"] = select(iphonesimulator_and_maccatalyst_dsym_map)
+        dsym_select_map["ovr_config//os/sdk/apple:iphonesimulator"] = select(iphonesimulator_and_maccatalyst_dsym_map)
+
+    if len(iphone_and_maccatalyst_framework_map) > 0:
+        framework_select_map["ovr_config//os/sdk/apple:iphoneos"] = select(iphone_and_maccatalyst_framework_map)
+        dsym_select_map["ovr_config//os/sdk/apple:iphoneos"] = select(iphone_and_maccatalyst_dsym_map)
+
+    if len(mac_framework_map) > 0:
+        framework_select_map["ovr_config//os:macos"] = select(mac_framework_map)
+        dsym_select_map["ovr_config//os:macos"] = select(mac_dsym_map)
+
+    # Create a single prebuilt_apple_framework with select() for framework and dsyms
+    prebuilt_apple_framework_rule(
+        name = name,
+        framework = select(framework_select_map),
+        dsyms = select(dsym_select_map),
+        default_target_platform = default_target_platform,
+        compatible_with = compatible_with,
+        **kwargs,
+    )
+
+def _parse_platform(name):
+    # parse metadata from conventional xcframework folders
+    # produced by xcodebuild -create-xcframework
+    #
+    # examples:
+    #
+    # ios-arm64
+    # ios-arm64_x86_64-simulator
+    # ios-arm64_x86_64-maccatalyst
+    # macos-arm64_x86_64
+    substrings = name.split("-")
+    isCatalyst = False
+    isSimulator = False
+    if len(substrings) > 2:
+        isSimulator = substrings[2] == "simulator"
+        isCatalyst = substrings[2] == "maccatalyst"
+    archs = []
+    remaining = substrings[1]
+    for arch in ["arm64e", "arm64_32", "arm64", "x86_64"]:
+        if arch in remaining:
+            archs.append(arch)
+            remaining = remaining.replace(arch, "")
+    if not archs:
+        fail("Failed to parse architectures for xcframework platform " + name)
+
+    return {
+        "archs": archs,
+        "folder": name,
+        "isCatalyst": isCatalyst,
+        "isSimulator": isSimulator,
+        "platform": substrings[0],
+    }
diff --git a/buck2/prelude/apple/resource_groups.bzl b/buck2/prelude/apple/resource_groups.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/resource_groups.bzl
@@ -0,0 +1,226 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:groups_types.bzl", "Group", "MATCH_ALL_LABEL")
+load(
+    "@prelude//utils:graph_utils.bzl",
+    "depth_first_traversal_by",
+)
+load(":apple_asset_catalog_types.bzl", "AppleAssetCatalogSpec")
+load(":apple_core_data_types.bzl", "AppleCoreDataSpec")
+load(":apple_resource_types.bzl", "AppleResourceSelectionOutput", "AppleResourceSpec", "CxxResourceSpec", "SelectedAppleAssetCatalogSpec")
+load(":scene_kit_assets_types.bzl", "SceneKitAssetsSpec")
+load(":xcassets_asset_symbols.bzl", "MetaXcassetsAssetSymbolSpec")
+
+ResourceGroupInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "groups": provider_field(list[Group]),
+        "groups_hash": provider_field(int),
+        "mappings": provider_field(dict[Label, str]),
+        # Additional deps needed to cover labels referenced by the groups above.
+        # This is useful in cases where the consumer of this provider won't already
+        # have deps covering these.
+        # NOTE(agallagher): We do this to maintain existing behavior w/ the
+        # standalone `resource_group_map()` rule, but it's not clear if it's
+        # actually desirable behavior.
+        "resource_group_to_implicit_deps_mapping": provider_field(dict[str, list[Dependency]]),
+    },
+)
+
+RESOURCE_GROUP_MAP_ATTR = attrs.option(attrs.dep(providers = [ResourceGroupInfo]), default = None)
+
+ResourceGraphNode = record(
+    label = field(Label),
+    # Attribute labels on the target.
+    labels = field(list[str], []),
+    # Deps of this target which might have resources transitively.
+    deps = field(list[Label], []),
+    # Exported deps of this target which might have resources transitively.
+    exported_deps = field(list[Label], []),
+    # Actual resource data, present when node corresponds to `apple_resource` target.
+    resource_spec = field([AppleResourceSpec, None], None),
+    # Actual asset catalog data, present when node corresponds to `apple_asset_catalog` target.
+    asset_catalog_spec = field([AppleAssetCatalogSpec, None], None),
+    # Actual core data, present when node corresponds to `core_data_model` target
+    core_data_spec = field([AppleCoreDataSpec, None], None),
+    # Actual scene kit assets, present when node corresponds to `scene_kit_assets` target
+    scene_kit_assets_spec = field([SceneKitAssetsSpec, None], None),
+    # Actual resource data, present when node corresponds to `cxx_library` target containing resources.
+    cxx_resource_spec = field([CxxResourceSpec, None], None),
+    # Asset symbol metadata from an asset catalog opted into trimming. Carries the
+    # producer and catalog identity through bundle-level resource selection.
+    xcassets_symbol_spec = field([MetaXcassetsAssetSymbolSpec, None], None),
+)
+
+ResourceGraphTSet = transitive_set()
+
+ResourceGraphInfo = provider(
+    fields = {
+        "label": provider_field(Label),
+        "nodes": provider_field(ResourceGraphTSet),
+        "should_propagate": provider_field(bool),
+    }
+)
+
+def create_resource_graph(
+    ctx: AnalysisContext,
+    labels: list[str],
+    deps: list[Dependency],
+    exported_deps: list[Dependency],
+    bundle_binary: [Dependency, None] = None,
+    resource_spec: [AppleResourceSpec, None] = None,
+    asset_catalog_spec: [AppleAssetCatalogSpec, None] = None,
+    core_data_spec: [AppleCoreDataSpec, None] = None,
+    scene_kit_assets_spec: [SceneKitAssetsSpec, None] = None,
+    cxx_resource_spec: [CxxResourceSpec, None] = None,
+    xcassets_symbol_spec: [MetaXcassetsAssetSymbolSpec, None] = None,
+    should_propagate: bool = True,
+) -> ResourceGraphInfo:
+    # Collect deps and exported_deps with resources that should propagate.
+    dep_labels, dep_graphs = _filtered_labels_and_graphs(deps)
+    exported_dep_labels, exported_dep_graphs = _filtered_labels_and_graphs(exported_deps)
+
+    # Bundle binary targets always propagate resources to their bundle.
+    # The bundle target will not pass up a ResourceGraphInfo provider itself
+    # so the resources do not propagate outside the bundle folder.
+    if bundle_binary and ResourceGraphInfo in bundle_binary:
+        dep_graphs.append(bundle_binary[ResourceGraphInfo])
+
+        # We use ResourceGraphInfo.label here to ensure the graph lookup works
+        # when we have binary targets specified with the [shared] subtarget.
+        dep_labels.append(bundle_binary[ResourceGraphInfo].label)
+
+    node = ResourceGraphNode(
+        label = ctx.label,
+        labels = labels,
+        deps = dep_labels,
+        exported_deps = exported_dep_labels,
+        resource_spec = resource_spec,
+        asset_catalog_spec = asset_catalog_spec,
+        core_data_spec = core_data_spec,
+        scene_kit_assets_spec = scene_kit_assets_spec,
+        cxx_resource_spec = cxx_resource_spec,
+        xcassets_symbol_spec = xcassets_symbol_spec,
+    )
+    children = [child_node.nodes for child_node in dep_graphs + exported_dep_graphs]
+    return ResourceGraphInfo(
+        label = ctx.label,
+        nodes = ctx.actions.tset(ResourceGraphTSet, value = node, children = children),
+        should_propagate = should_propagate,
+    )
+
+def get_resource_graph_node_map_func(graph: ResourceGraphInfo):
+    def get_resource_graph_node_map() -> dict[Label, ResourceGraphNode]:
+        nodes = graph.nodes.traverse()
+        return {node.label: node for node in filter(None, nodes)}
+
+    return get_resource_graph_node_map
+
+def _filtered_labels_and_graphs(deps: list[Dependency]) -> (list[Label], list[ResourceGraphInfo]):
+    """
+    Filters dependencies and returns only those which are relevant
+    to working with resources i.e. those which contains resource graph provider
+    and that should propagate.
+    """
+    resource_labels = []
+    resource_deps = []
+    for d in deps:
+        graph = d.get(ResourceGraphInfo)
+        if graph and graph.should_propagate:
+            resource_deps.append(graph)
+            resource_labels.append(graph.label)
+
+    return resource_labels, resource_deps
+
+def get_resource_group_info(ctx: AnalysisContext) -> [ResourceGroupInfo, None]:
+    """
+    Parses the currently analyzed context for any resource group definitions
+    and returns a list of all resource groups with their mappings.
+    """
+    resource_group_map = ctx.attrs.resource_group_map
+
+    if not resource_group_map:
+        return None
+
+    if isinstance(resource_group_map, Dependency):
+        return resource_group_map[ResourceGroupInfo]
+
+    fail("Resource group maps must be provided as a resource_group_map rule dependency.")
+
+def get_filtered_resources(
+    root: Label, resource_graph_node_map_func, resource_group: [str, None], resource_group_mappings: [dict[Label, str], None]
+) -> AppleResourceSelectionOutput:
+    """
+    Walks the provided DAG and collects resources matching resource groups definition.
+    """
+
+    resource_graph_node_map = resource_graph_node_map_func()
+
+    def get_traversed_deps(target: Label) -> list[Label]:
+        node = resource_graph_node_map[target]  # buildifier: disable=uninitialized
+        return node.exported_deps + node.deps
+
+    targets = depth_first_traversal_by(
+        resource_graph_node_map,
+        get_traversed_deps(root),
+        get_traversed_deps,
+    )
+
+    resource_specs = []
+    asset_catalog_specs = []
+    selected_asset_catalog_specs = []
+    core_data_specs = []
+    scene_kit_assets_specs = []
+    cxx_resource_specs = []
+
+    for target in targets:
+        target_resource_group = resource_group_mappings.get(target)
+
+        # Ungrouped targets belong to the unlabeled bundle
+        if (
+            (not target_resource_group and not resource_group)
+            or
+            # Does it match special "MATCH_ALL" mapping?
+            target_resource_group == MATCH_ALL_LABEL
+            or
+            # Does it match currently evaluated group?
+            target_resource_group == resource_group
+        ):
+            node = resource_graph_node_map[target]
+            resource_spec = node.resource_spec
+            if resource_spec:
+                resource_specs.append(resource_spec)
+            asset_catalog_spec = node.asset_catalog_spec
+            if asset_catalog_spec:
+                asset_catalog_specs.append(asset_catalog_spec)
+                selected_asset_catalog_specs.append(
+                    SelectedAppleAssetCatalogSpec(
+                        asset_catalog_spec = asset_catalog_spec,
+                        xcassets_symbol_spec = node.xcassets_symbol_spec,
+                        target = target,
+                    ),
+                )
+            core_data_spec = node.core_data_spec
+            if core_data_spec:
+                core_data_specs.append(core_data_spec)
+            scene_kit_assets_spec = node.scene_kit_assets_spec
+            if scene_kit_assets_spec:
+                scene_kit_assets_specs.append(scene_kit_assets_spec)
+            cxx_resource_spec = node.cxx_resource_spec
+            if cxx_resource_spec:
+                cxx_resource_specs.append(cxx_resource_spec)
+
+    return AppleResourceSelectionOutput(
+        resource_specs = resource_specs,
+        asset_catalog_specs = asset_catalog_specs,
+        selected_asset_catalog_specs = selected_asset_catalog_specs,
+        core_data_specs = core_data_specs,
+        scene_kit_assets_spec = scene_kit_assets_specs,
+        cxx_resource_specs = cxx_resource_specs,
+    )
diff --git a/buck2/prelude/apple/scene_kit_assets.bzl b/buck2/prelude/apple/scene_kit_assets.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/scene_kit_assets.bzl
@@ -0,0 +1,99 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load(
+    "@prelude//ide_integrations/xcode:data.bzl",
+    "XCODE_DATA_SUB_TARGET",
+    "XcodeDataInfoKeys",
+    "generate_xcode_data",
+)
+load(":apple_bundle_utility.bzl", "get_bundle_min_target_version", "get_bundle_resource_processing_options")
+load(":apple_sdk.bzl", "get_apple_sdk_name")
+load(":resource_groups.bzl", "create_resource_graph")
+load(":scene_kit_assets_types.bzl", "SceneKitAssetsSpec")
+
+def scene_kit_assets_impl(ctx: AnalysisContext) -> list[Provider]:
+    spec = SceneKitAssetsSpec(
+        path = ctx.attrs.path,
+    )
+    graph = create_resource_graph(
+        ctx = ctx,
+        labels = ctx.attrs.labels,
+        deps = [],
+        exported_deps = [],
+        scene_kit_assets_spec = spec,
+    )
+
+    xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "apple_asset_catalog", None, _xcode_populate_attributes)
+
+    return [
+        DefaultInfo(
+            sub_targets = {
+                XCODE_DATA_SUB_TARGET: xcode_data_default_info,
+            },
+        ),
+        graph,
+        xcode_data_info,
+    ]
+
+def compile_scene_kit_assets(ctx: AnalysisContext, specs: list[SceneKitAssetsSpec]) -> Artifact | None:
+    if len(specs) == 0:
+        return None
+
+    output = ctx.actions.declare_output("SceneKitAssetsCompiled", has_content_based_path = False)
+
+    copy_scene_kit_assets_cmds = []
+    for spec in specs:
+        copy_scene_kit_assets_cmd = _get_copy_scene_kit_assets_cmd(ctx, spec)
+        copy_scene_kit_assets_cmds.append(copy_scene_kit_assets_cmd)
+
+    # Sandboxing and fs isolation on RE machines results in Xcode tools failing
+    # when those are working in freshly created directories in buck-out.
+    # See https://fb.workplace.com/groups/1042353022615812/permalink/1872164996301273/
+    # As a workaround create a directory in tmp, use it for Xcode tools, then
+    # copy the result to buck-out.
+    wrapper_script, _ = ctx.actions.write(
+        "copy_scene_kit_assets_wrapper.sh",
+        [
+            cmd_args("set -euo pipefail"),
+            cmd_args('export TMPDIR="$(mktemp -d)"'),
+            cmd_args(copy_scene_kit_assets_cmds),
+            cmd_args(output, format = 'mkdir -p {} && cp -r "$TMPDIR"/ {}'),
+        ],
+        allow_args = True,
+        has_content_based_path = False,
+    )
+    combined_command = cmd_args(["/bin/sh", wrapper_script], hidden = copy_scene_kit_assets_cmds + [output.as_output()])
+    processing_options = get_bundle_resource_processing_options(ctx)
+    ctx.actions.run(
+        combined_command,
+        prefer_local = processing_options.prefer_local,
+        prefer_remote = processing_options.prefer_remote,
+        allow_cache_upload = processing_options.allow_cache_upload,
+        category = "scene_kit_assets",
+    )
+    return output
+
+def _get_copy_scene_kit_assets_cmd(ctx: AnalysisContext, scene_kit_assets_spec: SceneKitAssetsSpec) -> cmd_args:
+    scnassets_folder = scene_kit_assets_spec.path.basename
+    return cmd_args(
+        [
+            ctx.attrs._apple_toolchain[AppleToolchainInfo].copy_scene_kit_assets,
+            scene_kit_assets_spec.path,
+            "-o",
+            cmd_args(scnassets_folder, format = "$TMPDIR/{}"),
+            "--target-platform=" + get_apple_sdk_name(ctx),
+            "--target-version=" + get_bundle_min_target_version(ctx, ctx.attrs.binary),
+        ],
+        delimiter = " ",
+    )
+
+def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:
+    data = {XcodeDataInfoKeys.EXTRA_XCODE_FILES: [ctx.attrs.path]}
+    return data
diff --git a/buck2/prelude/apple/scene_kit_assets_types.bzl b/buck2/prelude/apple/scene_kit_assets_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/scene_kit_assets_types.bzl
@@ -0,0 +1,11 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+SceneKitAssetsSpec = record(
+    path = field(Artifact),
+)
diff --git a/buck2/prelude/apple/swift/apple_sdk_clang_module.bzl b/buck2/prelude/apple/swift/apple_sdk_clang_module.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/apple_sdk_clang_module.bzl
@@ -0,0 +1,49 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":swift_sdk_pcm_compilation.bzl", "get_shared_pcm_compilation_args")
+load(":swift_toolchain_types.bzl", "SdkSwiftOverlayInfo", "SdkUncompiledModuleInfo")
+
+def apple_sdk_clang_module_impl(ctx: AnalysisContext) -> list[Provider]:
+    cmd = get_shared_pcm_compilation_args(ctx.attrs.module_name)
+    overlays = []
+    if ctx.attrs.overlays:
+        overlays = [SdkSwiftOverlayInfo(overlays = ctx.attrs.overlays)]
+
+    module_info = SdkUncompiledModuleInfo(
+        module_name = ctx.attrs.module_name,
+        is_framework = ctx.attrs.is_framework,
+        is_swiftmodule = False,
+        partial_cmd = cmd,
+        input_relative_path = ctx.attrs.modulemap_relative_path,
+        deps = ctx.attrs.deps,
+        cxx_deps = ctx.attrs.cxx_deps,
+        overlays_transitive_deps = ctx.attrs.overlays_transitive_deps,
+    )
+
+    return [
+        DefaultInfo(),
+        module_info,
+    ] + overlays
+
+# This rule represent a Clang module from SDK and forms a graph of dependencies between such modules.
+apple_sdk_clang_module = rule(
+    impl = apple_sdk_clang_module_impl,
+    attrs = {
+        "cxx_deps": attrs.list(attrs.dep(), default = []),
+        "deps": attrs.list(attrs.dep(), default = []),
+        "is_framework": attrs.bool(default = False),
+        # This is a real module name, contrary to `name`
+        # which has a special suffix to distinguish Swift and Clang modules with the same name
+        "module_name": attrs.string(),
+        "modulemap_relative_path": attrs.string(),
+        "overlays": attrs.dict(key = attrs.string(), value = attrs.list(attrs.string(), default = []), sorted = False, default = {}),
+        # Transitive closure filtered to overlay owners and underlyings.
+        "overlays_transitive_deps": attrs.list(attrs.string(), default = []),
+    },
+)
diff --git a/buck2/prelude/apple/swift/apple_sdk_modules_utility.bzl b/buck2/prelude/apple/swift/apple_sdk_modules_utility.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/apple_sdk_modules_utility.bzl
@@ -0,0 +1,93 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    ":swift_toolchain_types.bzl",
+    "SdkSwiftOverlayInfo",
+    "SdkUncompiledModuleInfo",
+    "SwiftCompiledModuleTset",
+    "SwiftToolchainInfo",  # @unused Used as a type
+    "WrappedSdkCompiledModuleInfo",
+)
+
+def is_sdk_modules_provided(toolchain: SwiftToolchainInfo) -> bool:
+    has_swift_modules = bool(toolchain.uncompiled_swift_sdk_modules_deps)
+    has_clang_modules = bool(toolchain.uncompiled_clang_sdk_modules_deps)
+    return has_swift_modules or has_clang_modules
+
+def get_compiled_sdk_clang_deps_tset(ctx: AnalysisContext, deps_providers: list) -> SwiftCompiledModuleTset:
+    sdk_deps = [
+        d[WrappedSdkCompiledModuleInfo].clang_deps
+        for d in deps_providers
+        if WrappedSdkCompiledModuleInfo in d and d[WrappedSdkCompiledModuleInfo].clang_deps != None
+    ]
+    return ctx.actions.tset(SwiftCompiledModuleTset, children = sdk_deps)
+
+def get_compiled_sdk_swift_deps_tset(ctx: AnalysisContext, deps_providers: list) -> SwiftCompiledModuleTset:
+    sdk_deps = [
+        d[WrappedSdkCompiledModuleInfo].swift_deps
+        for d in deps_providers
+        if WrappedSdkCompiledModuleInfo in d and d[WrappedSdkCompiledModuleInfo].swift_deps != None
+    ]
+    return ctx.actions.tset(SwiftCompiledModuleTset, children = sdk_deps)
+
+def get_uncompiled_sdk_deps(sdk_modules: list[str], required_modules: list[str], toolchain: SwiftToolchainInfo) -> list[Dependency]:
+    if not is_sdk_modules_provided(toolchain):
+        fail("SDK deps are not set for swift_toolchain")
+
+    swift_map = toolchain.uncompiled_swift_sdk_modules_deps
+    clang_map = toolchain.uncompiled_clang_sdk_modules_deps
+
+    direct_names = set(sdk_modules + required_modules)
+
+    sdk_deps = []
+    for sdk_module_dep_name in list(direct_names):
+        if sdk_module_dep_name in swift_map:
+            sdk_deps.append(swift_map[sdk_module_dep_name])
+        if sdk_module_dep_name in clang_map:
+            sdk_deps.append(clang_map[sdk_module_dep_name])
+
+    # ModuleA declares a cross-import overlay on ModuleADependency, which the
+    # compiler auto-loads whenever both are visible, even if ModuleADependency
+    # only arrives transitively. Match overlays against the precomputed
+    # overlay-filtered transitive closure, not just the direct sdk_modules.
+    reachable = set(direct_names)
+    for sdk_module_dep_name in list(direct_names):
+        for uncompiled_sdk_modules_map in (swift_map, clang_map):
+            if sdk_module_dep_name not in uncompiled_sdk_modules_map:
+                continue
+            sdk_dep = uncompiled_sdk_modules_map[sdk_module_dep_name]
+            if SdkUncompiledModuleInfo not in sdk_dep:
+                continue
+            transitive_names = sdk_dep[SdkUncompiledModuleInfo].overlays_transitive_deps or []
+            for transitive_name in transitive_names:
+                reachable.add(transitive_name)
+
+    sdk_overlays = []
+    # Seed with the direct deps: an overlay listed explicitly in sdk_modules
+    # is already in sdk_deps above and must not be added a second time.
+    seen_overlays = set(direct_names)
+    for reachable_name in list(reachable):
+        for uncompiled_sdk_modules_map in (swift_map, clang_map):
+            if reachable_name not in uncompiled_sdk_modules_map:
+                continue
+            sdk_dep = uncompiled_sdk_modules_map[reachable_name]
+            if SdkSwiftOverlayInfo not in sdk_dep:
+                continue
+            overlay_info = sdk_dep[SdkSwiftOverlayInfo]
+            for underlying_module, overlay_modules in overlay_info.overlays.items():
+                # Only add a cross import SDK overlay if both modules associated with the overlay are required
+                if underlying_module in reachable:
+                    # Cross import overlays themselves are always Swift modules, but the underlying module
+                    # can be a Swift module or a Clang module
+                    for overlay_name in overlay_modules:
+                        if overlay_name in swift_map and overlay_name not in seen_overlays:
+                            seen_overlays.add(overlay_name)
+                            sdk_overlays.append(swift_map[overlay_name])
+
+    return sdk_deps + sdk_overlays
diff --git a/buck2/prelude/apple/swift/apple_sdk_swift_module.bzl b/buck2/prelude/apple/swift/apple_sdk_swift_module.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/apple_sdk_swift_module.bzl
@@ -0,0 +1,66 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_utility.bzl", "get_base_swiftinterface_compilation_flags")
+load(":swift_toolchain_types.bzl", "SdkSwiftOverlayInfo", "SdkUncompiledModuleInfo")
+
+def apple_sdk_swift_module_impl(ctx: AnalysisContext) -> list[Provider]:
+    module_name = ctx.attrs.module_name
+    cmd = get_base_swiftinterface_compilation_flags(module_name)
+
+    if module_name == "Swift" or module_name == "SwiftOnoneSupport":
+        cmd.add([
+            "-parse-stdlib",
+        ])
+
+    overlays = []
+    if ctx.attrs.overlays:
+        overlays = [SdkSwiftOverlayInfo(overlays = ctx.attrs.overlays)]
+
+    # The target triple varies in swiftinterface files to use either
+    # macos or macosx. To avoid unnecessary module compilation we align
+    # on macosx.
+    target = ctx.attrs.target
+    if "macos" in target and "macosx" not in target:
+        target = target.replace("macos", "macosx")
+
+    module_info = SdkUncompiledModuleInfo(
+        cxx_deps = ctx.attrs.cxx_deps,
+        deps = ctx.attrs.deps,
+        input_relative_path = ctx.attrs.swiftinterface_relative_path,
+        is_framework = ctx.attrs.is_framework,
+        is_swiftmodule = True,
+        module_name = ctx.attrs.module_name,
+        overlays_transitive_deps = ctx.attrs.overlays_transitive_deps,
+        partial_cmd = cmd,
+        target = target,
+    )
+
+    return [
+        DefaultInfo(),
+        module_info,
+    ] + overlays
+
+# This rule represent a Swift module from SDK and forms a graph of dependencies between such modules.
+apple_sdk_swift_module = rule(
+    impl = apple_sdk_swift_module_impl,
+    attrs = {
+        "cxx_deps": attrs.list(attrs.dep(), default = []),
+        "deps": attrs.list(attrs.dep(), default = []),
+        "is_framework": attrs.bool(default = False),
+        # This is a real module name, contrary to `name`
+        # which has a special suffix to distinguish Swift and Clang modules with the same name
+        "module_name": attrs.string(),
+        "overlays": attrs.dict(key = attrs.string(), value = attrs.list(attrs.string(), default = []), sorted = False, default = {}),
+        # Transitive closure filtered to overlay owners and underlyings.
+        "overlays_transitive_deps": attrs.list(attrs.string(), default = []),
+        # A prefixed path ($SDKROOT/$PLATFORM_DIR) to swiftinterface textual file.
+        "swiftinterface_relative_path": attrs.option(attrs.string(), default = None),  # if `swiftinterface` is None represents a Root node.
+        "target": attrs.string(),
+    },
+)
diff --git a/buck2/prelude/apple/swift/swift_compilation.bzl b/buck2/prelude/apple/swift/swift_compilation.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_compilation.bzl
@@ -0,0 +1,1727 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactInfoTag",
+    "ArtifactTSet",  # @unused Used as a type
+    "make_artifact_tset",
+    "project_artifacts",
+)
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_error_handler.bzl", "apple_build_error_handler")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load("@prelude//apple:apple_utility.bzl", "get_disable_pch_validation_flags", "get_module_name")
+load("@prelude//apple:modulemap.bzl", "create_modulemap")
+load("@prelude//apple/swift:swift_helpers.bzl", "compile_with_argsfile", "compile_with_argsfile_cmd", "uses_explicit_modules")
+load(
+    "@prelude//apple/swift:swift_types.bzl",
+    "EXPLICIT_MODULES_CATEGORY_SUFFIX",
+    "SWIFTMODULE_COMPILE_CATEGORY",
+    "SWIFTMODULE_EXTENSION",
+    "SWIFT_COMPILE_CATEGORY",
+    "SWIFT_EXTENSION",
+    "SwiftDependencyInfo",
+    "SwiftMacroPlugin",
+    "get_implicit_framework_search_path_providers",
+)
+load("@prelude//cxx:argsfiles.bzl", "CompileArgsfile", "CompileArgsfiles")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_platform_info", "get_cxx_toolchain_info")
+load("@prelude//cxx:cxx_library_utility.bzl", "cxx_attr_deps", "cxx_attr_exported_deps")
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",  # @unused Used as a type
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load(
+    "@prelude//cxx:headers.bzl",
+    "CHeader",
+    "HeaderMode",
+    "prepare_headers",
+)
+load(
+    "@prelude//cxx:link_groups.bzl",
+    "get_link_group",
+)
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorArgs",
+    "CPreprocessorInfo",  # @unused Used as a type
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+)
+load("@prelude//cxx:target_sdk_version.bzl", "get_target_triple")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkInfo",  # @unused Used as a type
+    "SwiftmoduleLinkable",  # @unused Used as a type
+)
+load("@prelude//utils:actions.bzl", "ActionExecutionAttributes")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load(
+    ":apple_sdk_modules_utility.bzl",
+    "get_compiled_sdk_clang_deps_tset",
+    "get_compiled_sdk_swift_deps_tset",
+    "get_uncompiled_sdk_deps",
+    "is_sdk_modules_provided",
+)
+load(
+    ":swift_debug_info_utils.bzl",
+    "extract_and_merge_clang_debug_infos",
+    "extract_and_merge_swift_debug_infos",
+)
+load(
+    ":swift_incremental_support.bzl",
+    "INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE",
+    "INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS",
+    "IncrementalCompilationInput",
+    "get_incremental_file_hashing_enabled",
+    "get_incremental_object_compilation_flags",
+    "get_incremental_remote_outputs_enabled",
+    "get_incremental_split_actions",
+    "get_incremental_swiftmodule_compilation_flags",
+    "get_uses_content_based_paths",
+    "should_build_swift_incrementally",
+    "should_build_swiftmodule_incrementally",
+)
+load(":swift_module_map.bzl", "write_swift_module_map_with_deps")
+load(":swift_output_file_map.bzl", "add_dependencies_output", "get_modularization_dependency_graph_output_map")
+load(":swift_pcm_compilation.bzl", "compile_underlying_pcm", "get_compiled_pcm_deps_tset", "get_swift_pcm_anon_targets")
+load(
+    ":swift_pcm_compilation_types.bzl",
+    "SwiftPCMUncompiledInfo",
+)
+load(":swift_sdk_flags.bzl", "get_sdk_flags")
+load(":swift_sdk_pcm_compilation.bzl", "get_swift_sdk_pcm_anon_targets")
+load(":swift_swiftinterface_compilation.bzl", "get_swift_interface_anon_targets")
+load(":swift_toolchain.bzl", "get_swift_toolchain_info", "include_path_for_relative_module_map_paths", "supports_modulemaps_with_hmaps")
+load(
+    ":swift_toolchain_types.bzl",
+    "SwiftCompiledModuleInfo",
+    "SwiftCompiledModuleTset",
+    "SwiftObjectFormat",
+    "SwiftToolchainInfo",
+    "clang_module_file_args",
+)
+
+SwiftCompilationDatabase = record(
+    db = field(Artifact),
+    other_outputs = field(ArgLike),
+)
+
+SwiftObjectOutput = record(
+    object_files = field(list[Artifact]),
+    argsfiles = field(CompileArgsfiles),
+    output_map_artifact = field(Artifact | None),
+    swiftdeps = field(list[Artifact]),
+)
+
+SwiftLibraryForDistributionOutput = record(
+    swiftinterface = field(Artifact),
+    private_swiftinterface = field(Artifact),
+    swiftdoc = field(Artifact),
+)
+
+SwiftCompilationOutput = record(
+    # The object file output from compilation.
+    object_files = field(list[Artifact]),
+    object_format = field(SwiftObjectFormat),
+    # The swiftmodule file output from compilation.
+    swiftmodule = field(Artifact),
+    # Stderr output when running `-typecheck`
+    typecheck_file = field(Artifact),
+    # The dependency info provider that contains the swiftmodule
+    # search paths required for compilation and linking.
+    dependency_info = field(SwiftDependencyInfo),
+    # Preprocessor info required for ObjC compilation of this library.
+    pre = field(CPreprocessor),
+    # Exported preprocessor info required for ObjC compilation of rdeps.
+    exported_pre = field(CPreprocessor),
+    # Exported -Swift.h header
+    exported_swift_header = field(Artifact),
+    # Argsfiles used to compile object files.
+    argsfiles = field(CompileArgsfiles),
+    # A tset of (SDK/first-party) swiftmodule artifacts required to be linked into binary.
+    # Different outputs of Swift compilation actions might contain duplicates of SDK swiftmodule artifacts.
+    swift_debug_info = field(ArtifactTSet),
+    # A tset of PCM artifacts used to compile a Swift module.
+    clang_debug_info = field(ArtifactTSet),
+    # Info required for `[swift-compilation-database]` subtarget.
+    compilation_database = field(SwiftCompilationDatabase),
+    # An artifact that represent the Swift module map for this target.
+    output_map_artifact = field(Artifact | None),
+    # The JSON file passed to swiftc via -explicit-swift-module-map-file that
+    # describes all transitive Swift module dependencies. Only populated when
+    # explicit modules are enabled.
+    swift_module_map_artifact = field(Artifact | None, None),
+    # An optional artifact with files that support consuming the generated library with later versions of the swift compiler.
+    swift_library_for_distribution_output = field(SwiftLibraryForDistributionOutput | None),
+    # A list of artifacts that stores the index data
+    index_store = field(Artifact),
+    # A list of artifacts of the swiftdeps files produced during incremental compilation.
+    swiftdeps = field(list[Artifact]),
+    compiled_underlying_pcm_artifact = field(Artifact | None),
+    # Modularization dependency dot graph
+    modularization_dependency_graph = field(Artifact | None),
+)
+
+SwiftCompileResult = record(
+    swift_compilation = field(SwiftCompilationOutput | None),
+    objc_swift_interface = field(DefaultInfo),
+    swiftinterface = field(Artifact | None),
+    ast = field(Artifact | None),
+)
+
+SwiftDebugInfo = record(
+    static = list[ArtifactTSet],
+    shared = list[ArtifactTSet],
+)
+
+_REQUIRED_SDK_MODULES = ["Swift", "SwiftOnoneSupport", "Darwin", "_Concurrency", "_StringProcessing"]
+
+_REQUIRED_SDK_CXX_MODULES = _REQUIRED_SDK_MODULES + ["std"]
+
+_INDEX_SYSTEM_MODULES = read_root_config("swift", "index_system_modules", "false").lower() == "true"
+
+def _get_target_flags(ctx) -> list[str]:
+    if get_cxx_platform_info(ctx).name.startswith("linux"):
+        # Linux triples are unversioned
+        return ["-target", "{}-unknown-linux-gnu".format(get_swift_toolchain_info(ctx).architecture)]
+    else:
+        return ["-target", get_target_triple(ctx)]
+
+def get_swift_anonymous_targets_for_prebuilt_framework(ctx: AnalysisContext, get_providers: typing.Callable) -> Promise:
+    # Get SDK deps from direct dependencies,
+    # all transitive deps will be compiled recursively.
+    direct_uncompiled_sdk_deps = get_uncompiled_sdk_deps(
+        ctx.attrs.sdk_modules,
+        _REQUIRED_SDK_MODULES,
+        get_swift_toolchain_info(ctx),
+    )
+
+    # Recursively compiling headers of direct and transitive deps as PCM modules,
+    # prebuilt_apple_framework rule doesn't support custom compiler_flags, so we pass only target triple.
+    pcm_targets = get_swift_pcm_anon_targets(
+        ctx,
+        ctx.attrs.deps,
+        _get_target_flags(ctx),
+        False,  # C++ Interop is disabled for now.
+    )
+
+    # Recursively compiling SDK's Clang dependencies,
+    # prebuilt_apple_framework rule doesn't support custom compiler_flags, so we pass only target triple.
+    sdk_pcm_targets = get_swift_sdk_pcm_anon_targets(
+        ctx,
+        False,
+        direct_uncompiled_sdk_deps,
+        _get_target_flags(ctx),
+    )
+
+    # Recursively compile SDK and prebuilt_apple_framework's Swift dependencies.
+    swift_interface_anon_targets = get_swift_interface_anon_targets(
+        ctx,
+        direct_uncompiled_sdk_deps,
+    )
+    return ctx.actions.anon_targets(pcm_targets + sdk_pcm_targets + swift_interface_anon_targets).promise.map(get_providers)
+
+def get_swift_anonymous_targets(ctx: AnalysisContext, get_apple_library_providers: typing.Callable) -> Promise:
+    swift_cxx_flags = get_swift_cxx_flags(ctx)
+
+    # Get SDK deps from direct dependencies,
+    # all transitive deps will be compiled recursively.
+    direct_uncompiled_sdk_deps = get_uncompiled_sdk_deps(
+        ctx.attrs.sdk_modules,
+        _REQUIRED_SDK_CXX_MODULES if ctx.attrs.enable_cxx_interop else _REQUIRED_SDK_MODULES,
+        get_swift_toolchain_info(ctx),
+    )
+
+    # Recursively compiling headers of direct and transitive deps as PCM modules,
+    # passing apple_library's cxx flags through that must be used for all downward PCM compilations.
+    pcm_targets = get_swift_pcm_anon_targets(
+        ctx,
+        ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", []),
+        swift_cxx_flags,
+        ctx.attrs.enable_cxx_interop,
+    )
+
+    # Recursively compiling SDK's Clang dependencies,
+    # passing apple_library's cxx flags through that must be used for all downward PCM compilations.
+    sdk_pcm_targets = get_swift_sdk_pcm_anon_targets(
+        ctx,
+        ctx.attrs.enable_cxx_interop,
+        direct_uncompiled_sdk_deps,
+        swift_cxx_flags,
+    )
+
+    # Recursively compiling SDK's Swift dependencies,
+    # passing apple_library's cxx flags through that must be used for all downward PCM compilations.
+    swift_interface_anon_targets = get_swift_interface_anon_targets(
+        ctx,
+        direct_uncompiled_sdk_deps,
+    )
+    return ctx.actions.anon_targets(pcm_targets + sdk_pcm_targets + swift_interface_anon_targets).promise.map(get_apple_library_providers)
+
+def get_swift_cxx_flags(ctx: AnalysisContext) -> list[str]:
+    """Iterates through `swift_compiler_flags` and returns a list of flags that might affect Clang compilation"""
+    gather, next = ([], False)
+
+    # Each target needs to propagate the compilers target triple.
+    # This can vary depending on the deployment target of each library.
+    gather += _get_target_flags(ctx)
+
+    for f in ctx.attrs.swift_compiler_flags:
+        if next:
+            gather.append("-Xcc")
+            gather.append(str(f).replace('"', ""))
+            next = False
+        elif str(f) == '"-Xcc"':
+            next = True
+        elif str(f) == '"-warnings-as-errors"':
+            gather.append("-warnings-as-errors")
+        elif str(f) == '"-no-warnings-as-errors"':
+            gather.append("-no-warnings-as-errors")
+
+    if ctx.attrs.enable_cxx_interop:
+        gather += ["-cxx-interoperability-mode=default"]
+
+    gather += ["-swift-version", ctx.attrs.swift_version]
+
+    return gather
+
+def _get_compiled_underlying_pcm(
+    ctx: AnalysisContext,
+    module_name: str,
+    module_pp_info: CPreprocessor | None,
+    exported_headers: list[CHeader],
+    deps_providers: list,
+    swift_cxx_flags: list[str],
+    framework_search_paths: cmd_args,
+) -> SwiftCompiledModuleInfo | None:
+    if supports_modulemaps_with_hmaps(ctx):
+        # We need to provide a headermap pointing to the exported headers of
+        # this target. Normally this would be passed through from the cxx
+        # layer, but the underlying module compilation happens before the cxx
+        # header map is generated, so we need to create one specifically for
+        # this module.
+        exported_headers_dict = {paths.join(h.namespace, h.name): h.artifact for h in exported_headers}
+        header_map = prepare_headers(
+            ctx.actions,
+            get_cxx_toolchain_info(ctx),
+            exported_headers_dict,
+            "swift-underlying-headers",
+            HeaderMode("header_map_only"),
+            allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs),
+        )
+        header_map_args = cmd_args(header_map.include_path, format = "-I{}")
+
+        # We need to collect the preprocessor info from exported_deps for their
+        # header map search paths.
+        preprocessor_info = cxx_merge_cpreprocessors(
+            ctx.actions,
+            [CPreprocessor(args = CPreprocessorArgs(args = [header_map_args]))],
+            cxx_inherited_preprocessor_infos(ctx.attrs.exported_deps),
+        )
+    else:
+        preprocessor_info = None
+
+    underlying_swift_pcm_uncompiled_info = get_swift_pcm_uncompile_info(
+        ctx,
+        preprocessor_info,
+        module_pp_info,
+    )
+    if not underlying_swift_pcm_uncompiled_info:
+        return None
+
+    return compile_underlying_pcm(
+        ctx,
+        module_name,
+        underlying_swift_pcm_uncompiled_info,
+        deps_providers,
+        swift_cxx_flags,
+        framework_search_paths,
+    )
+
+def _generate_umbrella_header(ctx: AnalysisContext, module_name: str, exported_headers: list[CHeader], uses_content_based_paths: bool) -> [CHeader, None]:
+    """Auto-generate an umbrella header for mixed ObjC/Swift modules.
+
+    The -Swift.h generated by the compiler may contain
+    `#import <ModuleName/ModuleName.h>`. If no manually-created umbrella
+    header exists, we generate one that #imports all exported ObjC headers
+    so that import resolves correctly.
+    """
+    umbrella_header_name = module_name + ".h"
+    umbrella_import_path = module_name + "/" + umbrella_header_name
+    for h in exported_headers:
+        if h.namespace:
+            header_import_path = h.namespace + "/" + h.name
+        else:
+            header_import_path = h.name
+        if header_import_path == umbrella_import_path:
+            return None
+
+    umbrella_content = "// Auto-generated umbrella header for {}\n".format(module_name)
+    for h in exported_headers:
+        if h.namespace:
+            umbrella_content += "#import <{}/{}>\n".format(h.namespace, h.name)
+        else:
+            umbrella_content += "#import <{}/{}>\n".format(module_name, h.name)
+    umbrella_artifact = ctx.actions.declare_output(
+        "__{}_umbrella__/{}".format(module_name, umbrella_header_name),
+        has_content_based_path = uses_content_based_paths,
+    )
+    ctx.actions.write(umbrella_artifact.as_output(), umbrella_content)
+    return CHeader(
+        artifact = umbrella_artifact,
+        name = umbrella_header_name,
+        namespace = module_name,
+        named = False,
+    )
+
+def compile_swift(
+    ctx: AnalysisContext,
+    srcs: list[CxxSrcWithFlags],
+    parse_as_library: bool,
+    deps_providers: list,
+    module_name: str,
+    exported_headers: list[CHeader],
+    exported_objc_modulemap_pp_info: [CPreprocessor, None],
+    framework_search_paths_flags: cmd_args,
+    extra_search_paths_flags: list[ArgLike] = [],
+    compile_category = SWIFT_COMPILE_CATEGORY,
+    compile_swiftmodule_category = SWIFTMODULE_COMPILE_CATEGORY,
+    is_macro = False,
+) -> SwiftCompileResult:
+    # If this target imports XCTest we need to pass the search path to its swiftmodule.
+    framework_search_paths = cmd_args()
+    framework_search_paths.add(_get_xctest_swiftmodule_search_path(ctx))
+
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+
+    # Pass the framework search paths to the driver and clang importer. This is required
+    # for pcm compilation, which does not pass through driver search paths.
+    framework_search_paths.add(framework_search_paths_flags)
+    framework_search_paths.add(cmd_args(framework_search_paths_flags, prepend = "-Xcc"))
+
+    # If a target exports ObjC headers and Swift explicit modules are enabled,
+    # we need to precompile a PCM of the underlying module and supply it to the Swift compilation.
+    swift_cxx_flags = get_swift_cxx_flags(ctx)
+    if uses_explicit_modules(ctx):
+        exported_compiled_underlying_pcm = (
+            _get_compiled_underlying_pcm(
+                ctx,
+                module_name,
+                exported_objc_modulemap_pp_info,
+                exported_headers,
+                deps_providers,
+                swift_cxx_flags,
+                framework_search_paths,
+            )
+            if exported_objc_modulemap_pp_info
+            else None
+        )
+    else:
+        exported_compiled_underlying_pcm = None
+
+    # We always track inputs for dependency file tracking, but optionally set
+    # the tag on the action depending on the use_depsfiles config.
+    inputs_tag = ctx.actions.artifact_tag()
+
+    shared_flags, swift_module_map_artifact = _get_shared_flags(
+        ctx = ctx,
+        deps_providers = deps_providers,
+        parse_as_library = parse_as_library,
+        public_module = exported_compiled_underlying_pcm,
+        module_name = module_name,
+        public_modulemap_pp_info = exported_objc_modulemap_pp_info,
+        extra_search_paths_flags = extra_search_paths_flags,
+        inputs_tag = inputs_tag,
+        is_macro = is_macro,
+    )
+    shared_flags.add(framework_search_paths)
+    objc_swift_interface_info = _create_objc_swift_interface(ctx, shared_flags, module_name)
+
+    if not srcs:
+        return SwiftCompileResult(swift_compilation = None, objc_swift_interface = objc_swift_interface_info, swiftinterface = None, ast = None)
+
+    # Content-based path hashing and Swift incremental compilation are incompatible.
+    if uses_content_based_paths and should_build_swift_incrementally(ctx):
+        fail("Content-based path hashing and Swift incremental compilation cannot be enabled at the same time.")
+
+    toolchain = get_swift_toolchain_info(ctx)
+    output_header = ctx.actions.declare_output(module_name + "-Swift.h", has_content_based_path = uses_content_based_paths)
+    output_swiftmodule = ctx.actions.declare_output(module_name + SWIFTMODULE_EXTENSION, has_content_based_path = uses_content_based_paths)
+
+    swift_framework_output = None
+    output_swiftinterface = None
+    swiftinterface_subtarget_enabled = getattr(ctx.attrs, "swiftinterface_subtarget_enabled", False)
+
+    if _should_compile_with_evolution(ctx):
+        swift_framework_output = SwiftLibraryForDistributionOutput(
+            swiftinterface = ctx.actions.declare_output(module_name + ".swiftinterface", has_content_based_path = uses_content_based_paths),
+            private_swiftinterface = ctx.actions.declare_output(module_name + ".private.swiftinterface", has_content_based_path = uses_content_based_paths),
+            swiftdoc = ctx.actions.declare_output(
+                module_name + ".swiftdoc", has_content_based_path = uses_content_based_paths
+            ),  # this is generated automatically once we pass -emit-module-info, so must have this name
+        )
+        if swiftinterface_subtarget_enabled:
+            output_swiftinterface = swift_framework_output.swiftinterface
+    elif swiftinterface_subtarget_enabled:
+        output_swiftinterface = ctx.actions.declare_output(module_name + ".swiftinterface", has_content_based_path = uses_content_based_paths)
+        _compile_swiftinterface(
+            ctx,
+            toolchain,
+            shared_flags,
+            srcs,
+            output_swiftinterface,
+        )
+
+    output_ast = None
+    if getattr(ctx.attrs, "swift_dump_ast_subtarget_enabled", False):
+        output_ast = ctx.actions.declare_output(module_name + "-ast-dump", dir = True, has_content_based_path = uses_content_based_paths)
+        _compile_dump_ast(
+            ctx,
+            toolchain,
+            shared_flags,
+            srcs,
+            output_ast,
+        )
+
+    # When compiling with WMO or incremental with split actions enabled, we compile
+    # the swiftmodule separately. In pure incremental mode, we generate the swiftmodule
+    # as part of the compile action to make use of incrementality.
+    if not should_build_swift_incrementally(ctx) or get_incremental_split_actions(ctx):
+        _compile_swiftmodule(
+            ctx,
+            toolchain,
+            shared_flags,
+            srcs,
+            output_swiftmodule,
+            output_header,
+            swift_framework_output,
+            inputs_tag,
+            compile_swiftmodule_category,
+        )
+
+    object_output = _compile_object(
+        ctx = ctx,
+        toolchain = toolchain,
+        shared_flags = shared_flags,
+        srcs = srcs,
+        output_swiftmodule = output_swiftmodule,
+        output_header = output_header,
+        inputs_tag = inputs_tag,
+        category = compile_category,
+    )
+
+    typecheck_file = _compile_typecheck_diagnostics(
+        ctx = ctx,
+        toolchain = toolchain,
+        shared_flags = shared_flags,
+        srcs = srcs,
+    )
+
+    modularization_dependency_graph = _compile_modularization_dependency_graph(ctx, toolchain, shared_flags, srcs)
+
+    index_store = _compile_index_store(ctx, toolchain, shared_flags, srcs)
+
+    generated_umbrella_header = (
+        _generate_umbrella_header(
+            ctx,
+            module_name,
+            exported_headers,
+            uses_content_based_paths,
+        )
+        if exported_headers and not getattr(ctx.attrs, "disable_generated_umbrella_header", True)
+        else None
+    )
+
+    # Swift libraries extend the ObjC modulemaps to include the -Swift.h header
+    modulemap_pp_info = create_modulemap(
+        ctx,
+        name = "swift-extended",
+        module_name = module_name,
+        headers = exported_headers,
+        swift_header = output_header,
+    )
+    exported_swift_header = CHeader(
+        artifact = output_header,
+        name = output_header.basename,
+        namespace = module_name,
+        named = False,
+    )
+    exported_pp_info = CPreprocessor(
+        headers = [exported_swift_header] + ([generated_umbrella_header] if generated_umbrella_header else []),
+        modular_args = modulemap_pp_info.modular_args,
+        args = CPreprocessorArgs(args = modulemap_pp_info.args.args),
+        modulemap_artifact = modulemap_pp_info.modulemap_artifact,
+    )
+
+    # We also need to include the unprefixed -Swift.h header in this libraries preprocessor info
+    swift_header = CHeader(
+        artifact = output_header,
+        name = output_header.basename,
+        namespace = "",
+        named = False,
+    )
+    pre = CPreprocessor(headers = [swift_header])
+
+    clang_debug_artifacts = [exported_pp_info.modulemap_artifact]
+    if exported_compiled_underlying_pcm:
+        # The compiled PCM of the underlying clang module
+        clang_debug_artifacts.append(exported_compiled_underlying_pcm.output_artifact)
+
+        # The modulemap and headers excluding the Swift header
+        clang_debug_artifacts.append(exported_objc_modulemap_pp_info.modulemap_artifact)
+
+    # Pass up the swiftmodule paths for this module and its exported_deps
+    return SwiftCompileResult(
+        swift_compilation = SwiftCompilationOutput(
+            output_map_artifact = object_output.output_map_artifact,
+            swift_module_map_artifact = swift_module_map_artifact,
+            object_files = object_output.object_files,
+            object_format = toolchain.object_format,
+            swiftmodule = output_swiftmodule,
+            typecheck_file = typecheck_file,
+            compiled_underlying_pcm_artifact = exported_compiled_underlying_pcm.output_artifact if exported_compiled_underlying_pcm else None,
+            dependency_info = get_swift_dependency_info(
+                ctx,
+                output_swiftmodule,
+                deps_providers,
+                is_macro,
+                swift_ast_dump_artifacts = filter(None, [output_ast]),
+            ),
+            pre = pre,
+            exported_pre = exported_pp_info,
+            exported_swift_header = exported_swift_header.artifact,
+            argsfiles = object_output.argsfiles,
+            swift_debug_info = extract_and_merge_swift_debug_infos(ctx, deps_providers, [output_swiftmodule]),
+            clang_debug_info = extract_and_merge_clang_debug_infos(
+                ctx,
+                deps_providers,
+                clang_debug_artifacts,
+            ),
+            compilation_database = _create_compilation_database(ctx, srcs, object_output.argsfiles.relative[SWIFT_EXTENSION]),
+            swift_library_for_distribution_output = swift_framework_output,
+            index_store = index_store,
+            swiftdeps = object_output.swiftdeps,
+            modularization_dependency_graph = modularization_dependency_graph,
+        ),
+        objc_swift_interface = objc_swift_interface_info,
+        swiftinterface = output_swiftinterface,
+        ast = output_ast,
+    )
+
+def _compile_swiftinterface(
+    ctx: AnalysisContext, toolchain: SwiftToolchainInfo, shared_flags: cmd_args, srcs: list[CxxSrcWithFlags], output_swiftinterface: Artifact
+):
+    swiftinterface_argsfile = cmd_args(shared_flags)
+    swiftinterface_argsfile.add([
+        # Required as emitting a swiftinterface without library evolution
+        # produces a warning.
+        "-no-warnings-as-errors",
+        # Workaround to avoid producing swiftdoc and other auxiliary outputs.
+        "-typecheck",
+        "-wmo",
+    ])
+    swiftinterface_cmd = cmd_args([
+        "-emit-module-interface",
+        "-emit-module-interface-path",
+        output_swiftinterface.as_output(),
+        "-Xwrapper",
+        "-remove-module-prefixes",
+    ])
+    _compile_with_argsfile(
+        ctx = ctx,
+        category = "emit_swiftinterface",
+        shared_flags = swiftinterface_argsfile,
+        srcs = srcs,
+        additional_flags = swiftinterface_cmd,
+        toolchain = toolchain,
+        supports_serialized_errors = False,
+    )
+
+def _compile_dump_ast(ctx: AnalysisContext, toolchain: SwiftToolchainInfo, shared_flags: cmd_args, srcs: list[CxxSrcWithFlags], output_ast_dir: Artifact):
+    ast_output = output_ast_dir.as_output()
+    output_file_map = {}
+    for src in srcs:
+        # safe_name includes path in case basenames clash
+        safe_name = src.file.short_path.replace("/", "_")
+        output_file_map[src.file] = {
+            "ast-dump": cmd_args(ast_output, format = "{}/" + safe_name + ".ast", delimiter = ""),
+        }
+
+    argfile_cmd = cmd_args(shared_flags)
+    if ctx.attrs.swift_module_skip_function_bodies:
+        argfile_cmd.add([
+            "-Xfrontend",
+            "-experimental-skip-non-inlinable-function-bodies-without-types",
+        ])
+
+    additional_flags = cmd_args(["-dump-ast"])
+    additional_flags.add(cmd_args(hidden = ast_output))
+
+    # `-dump-ast` disables `-wmo`. Without an explicit `-j`, those jobs run
+    # serially over each file in larger modules, becoming potential bottlenecks.
+    additional_flags.add([
+        "-enable-batch-mode",
+        "-driver-batch-size-limit",
+        str(INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE),
+        "-j",
+        str(INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS),
+    ])
+
+    _compile_with_argsfile(
+        ctx = ctx,
+        category = "dump_ast",
+        shared_flags = argfile_cmd,
+        srcs = srcs,
+        additional_flags = additional_flags,
+        toolchain = toolchain,
+        num_threads = INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS,
+        output_file_map = output_file_map,
+        supports_serialized_errors = False,
+        incremental_build_allowed = False,
+    )
+
+# We use separate actions for swiftmodule and object file output. This
+# improves build parallelism at the cost of duplicated work, but by disabling
+# type checking in function bodies the swiftmodule compilation can be done much
+# faster than object file output.
+def _compile_swiftmodule(
+    ctx: AnalysisContext,
+    toolchain: SwiftToolchainInfo,
+    shared_flags: cmd_args,
+    srcs: list[CxxSrcWithFlags],
+    output_swiftmodule: Artifact,
+    output_header: Artifact,
+    swift_framework_output: SwiftLibraryForDistributionOutput | None,
+    inputs_tag: ArtifactTag,
+    category: str,
+) -> CompileArgsfiles:
+    # The incremental swiftmodule action is opt-in and only supported when
+    # we are not emitting library evolution outputs (which require WMO).
+    build_swiftmodule_incrementally = should_build_swiftmodule_incrementally(ctx) and swift_framework_output == None
+
+    argfile_cmd = cmd_args(shared_flags)
+    argfile_cmd.add("-disable-cmo")
+
+    # Shared between WMO and incremental swiftmodule actions: emit the
+    # `.swiftmodule` + generated ObjC header, set up the include path for
+    # relative module map paths, and (when requested) skip non-inlinable
+    # function bodies for faster swiftmodule emission.
+    cmd = cmd_args(
+        "-emit-objc-header",
+        "-emit-objc-header-path",
+        output_header.as_output(),
+        "-emit-module",
+        "-emit-module-path",
+        output_swiftmodule.as_output(),
+    )
+    cmd.add(include_path_for_relative_module_map_paths(ctx))
+    if ctx.attrs.swift_module_skip_function_bodies:
+        argfile_cmd.add([
+            "-Xfrontend",
+            "-experimental-skip-non-inlinable-function-bodies-without-types",
+        ])
+
+    output_file_map = {}
+    incremental_artifacts = None
+    skip_incremental_outputs = False
+
+    if build_swiftmodule_incrementally:
+        incremental_compilation_output = get_incremental_swiftmodule_compilation_flags(ctx, srcs)
+        cmd.add(incremental_compilation_output.incremental_flags_cmd)
+        output_file_map = incremental_compilation_output.output_file_map
+        skip_incremental_outputs = incremental_compilation_output.skip_incremental_outputs
+        incremental_artifacts = IncrementalCompilationInput(
+            depfiles = incremental_compilation_output.depfiles,
+            swiftdeps = incremental_compilation_output.swiftdeps,
+            swiftdoc = None,
+        )
+    else:
+        argfile_cmd.add([
+            "-wmo",
+        ])
+
+        if swift_framework_output:
+            argfile_cmd.add([
+                "-enable-library-evolution",
+            ])
+            cmd.add([
+                "-emit-module-interface",
+                "-emit-module-interface-path",
+                swift_framework_output.swiftinterface.as_output(),
+                "-emit-private-module-interface-path",
+                swift_framework_output.private_swiftinterface.as_output(),
+                # Module verification fails here as the clang modules
+                # are not loaded correctly.
+                "-no-verify-emitted-module-interface",
+            ])
+
+            # There is no driver flag to specify the swiftdoc output path
+            # TODO: use an output file map for this.
+            cmd.add(cmd_args(hidden = swift_framework_output.swiftdoc.as_output()))
+
+    dep_files = {}
+    # With -skip-incremental-output the output_file_map is an output, so we
+    # cannot support depsfiles. With incremental file hashing the dep_file
+    # is also unnecessary.
+    emit_depsfiles = (
+        toolchain.use_depsfiles and not skip_incremental_outputs and not (build_swiftmodule_incrementally and get_incremental_file_hashing_enabled(ctx))
+    )
+    if emit_depsfiles:
+        add_dependencies_output(ctx, output_file_map, cmd, "swiftmodule", inputs_tag)
+        dep_files["swiftmodule"] = inputs_tag
+
+    ret, _ = _compile_with_argsfile(
+        ctx = ctx,
+        category = category,
+        extension = SWIFTMODULE_EXTENSION,
+        shared_flags = argfile_cmd,
+        srcs = srcs,
+        additional_flags = cmd,
+        toolchain = toolchain,
+        num_threads = 1,
+        dep_files = dep_files,
+        output_file_map = output_file_map,
+        artifact_tag = inputs_tag,
+        incremental_build_allowed = build_swiftmodule_incrementally,
+        skip_incremental_outputs = skip_incremental_outputs,
+        objects = [],
+        incremental_artifacts = incremental_artifacts,
+    )
+    return ret
+
+def _compile_typecheck_diagnostics(ctx: AnalysisContext, toolchain: SwiftToolchainInfo, shared_flags: cmd_args, srcs: list[CxxSrcWithFlags]) -> Artifact:
+    category = "swift_typecheck"
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+
+    if uses_explicit_modules(ctx):
+        category += "_with_explicit_mods"
+
+    additional_flags = cmd_args([
+        "-typecheck",
+        "-wmo",
+    ])
+
+    swift_cmd_output = compile_with_argsfile_cmd(
+        ctx = ctx,
+        category = category,
+        shared_flags = shared_flags,
+        srcs = srcs,
+        additional_flags = additional_flags,
+        toolchain = toolchain,
+        output_file_map = {},
+        supports_output_file_map = True,
+        supports_serialized_errors = False,
+        skip_incremental_outputs = True,
+        incremental_remote_outputs = False,
+        objects = [],
+        incremental_artifacts = None,
+        artifact_tag = None,
+    )
+
+    typecheck_file = ctx.actions.declare_output("swift-typecheck-stderr", has_content_based_path = uses_content_based_paths)
+
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    typecheck_cmd = cmd_args([
+        cxx_toolchain.internal_tools.stderr_to_file,
+        cmd_args(typecheck_file.as_output(), format = "--out={}"),
+        swift_cmd_output.cmd,
+    ])
+
+    ctx.actions.run(
+        typecheck_cmd,
+        category = category,
+    )
+
+    return typecheck_file
+
+def _compile_object(
+    ctx: AnalysisContext,
+    toolchain: SwiftToolchainInfo,
+    shared_flags: cmd_args,
+    srcs: list[CxxSrcWithFlags],
+    output_swiftmodule: Artifact,
+    output_header: Artifact,
+    inputs_tag: ArtifactTag,
+    category: str,
+) -> SwiftObjectOutput:
+    dep_files = {}
+    output_file_map = {}
+    emit_depsfiles = toolchain.use_depsfiles and not get_incremental_file_hashing_enabled(ctx) and not get_incremental_split_actions(ctx)
+    skip_incremental_outputs = False
+    module_name = get_module_name(ctx)
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+
+    if should_build_swift_incrementally(ctx):
+        output_swiftdoc = None
+        if not get_incremental_split_actions(ctx):
+            # define this here as we will only have an artifact for the purposes of incremental rebuilds.
+            output_swiftdoc = ctx.actions.declare_output(module_name + ".swiftdoc", has_content_based_path = uses_content_based_paths)
+
+        incremental_compilation_output = get_incremental_object_compilation_flags(ctx, srcs, output_swiftmodule, output_swiftdoc, output_header)
+        cmd = incremental_compilation_output.incremental_flags_cmd
+
+        # With -skip-incremental-output the output_file_map is an output, so
+        # we cannot support depsfiles.
+        emit_depsfiles = emit_depsfiles and not incremental_compilation_output.skip_incremental_outputs
+        num_threads = incremental_compilation_output.num_threads
+        objects = incremental_compilation_output.artifacts
+        output_file_map = incremental_compilation_output.output_file_map
+        skip_incremental_outputs = incremental_compilation_output.skip_incremental_outputs
+        swiftdeps = incremental_compilation_output.swiftdeps
+        depfiles = incremental_compilation_output.depfiles
+        incremental_artifacts = IncrementalCompilationInput(depfiles = depfiles, swiftdeps = swiftdeps, swiftdoc = output_swiftdoc)
+    else:
+        num_threads = 1
+        swiftdeps = []
+        output_object = ctx.actions.declare_output(module_name + SWIFT_EXTENSION + ".o", has_content_based_path = uses_content_based_paths)
+        objects = [output_object]
+        object_format = toolchain.object_format.value
+        embed_bitcode = False
+        if toolchain.object_format == SwiftObjectFormat("object-embed-bitcode"):
+            object_format = "object"
+            embed_bitcode = True
+
+        cmd = cmd_args([
+            "-emit-{}".format(object_format),
+            "-o",
+            output_object.as_output(),
+            "-wmo",
+        ])
+        incremental_artifacts = None
+
+        if embed_bitcode:
+            cmd.add("--embed-bitcode")
+
+    if emit_depsfiles:
+        add_dependencies_output(ctx, output_file_map, cmd, "object", inputs_tag)
+        dep_files["object"] = inputs_tag
+
+    if _should_compile_with_evolution(ctx):
+        cmd.add(["-enable-library-evolution"])
+
+    argsfiles, output_map_artifact = _compile_with_argsfile(
+        ctx = ctx,
+        category = category,
+        extension = SWIFT_EXTENSION,
+        shared_flags = shared_flags,
+        srcs = srcs,
+        additional_flags = cmd,
+        toolchain = toolchain,
+        num_threads = num_threads,
+        dep_files = dep_files,
+        output_file_map = output_file_map,
+        skip_incremental_outputs = skip_incremental_outputs,
+        objects = objects,
+        incremental_artifacts = incremental_artifacts,
+        artifact_tag = inputs_tag,
+    )
+
+    return SwiftObjectOutput(
+        object_files = objects,
+        argsfiles = argsfiles,
+        output_map_artifact = output_map_artifact,
+        swiftdeps = swiftdeps,
+    )
+
+def _compile_modularization_dependency_graph(
+    ctx: AnalysisContext, toolchain: SwiftToolchainInfo, shared_flags: cmd_args, srcs: list[CxxSrcWithFlags]
+) -> Artifact | None:
+    # -emit-modularization-dependency-dot-graph is only understood by the Pika
+    # toolchain's swiftc; Xcode's fails the action with "unknown argument".
+    if not toolchain.supports_modularization_dependency_graph:
+        return None
+
+    modularization_dependecy_graph_output = ctx.actions.declare_output(
+        "__modularization_dependency_graph__/swift_{}.dot".format(get_module_name(ctx)), has_content_based_path = False
+    )
+    cmd = cmd_args(
+        "-emit-modularization-dependency-dot-graph",
+        modularization_dependecy_graph_output.as_output(),
+        "-emit-object",
+        "-enable-batch-mode",
+        "-driver-batch-size-limit",
+        str(INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE),
+        "-j",
+        str(INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS),
+    )
+
+    category = "modularization_dependency_graph_compile"
+
+    output_file_map, output_objects, output_modularization_dependency_graph_shards = get_modularization_dependency_graph_output_map(ctx, srcs)
+    for object in output_objects:
+        cmd.add(cmd_args(hidden = object.as_output()))
+
+    for shard in output_modularization_dependency_graph_shards:
+        cmd.add(cmd_args(hidden = shard.as_output()))
+
+    _compile_with_argsfile(
+        ctx = ctx,
+        category = category,
+        extension = SWIFT_EXTENSION,
+        shared_flags = shared_flags,
+        srcs = srcs,
+        additional_flags = cmd,
+        toolchain = toolchain,
+        num_threads = INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS,
+        output_file_map = output_file_map,
+        skip_incremental_outputs = False,
+        objects = output_objects,
+    )
+    return modularization_dependecy_graph_output
+
+def _compile_index_store(ctx: AnalysisContext, toolchain: SwiftToolchainInfo, shared_flags: cmd_args, srcs: list[CxxSrcWithFlags]) -> Artifact:
+    module_name = get_module_name(ctx)
+
+    # Create a directory where we can write .o files and ignore them.
+    #
+    # In index store directories, the hash used in the unit file name is derived from
+    # the output path. E.g. if the output path is dir1/Foo.o, our unit file is
+    # Foo.swift-ABC123. If the output path changes to dir2/Foo.o, our unit file is now
+    # Foo.swift-DEF456.
+    #
+    # See this part of the index-while-building talk from the 2017 LLVM developer
+    # meeting: https://www.youtube.com/watch?v=jGJhnIT-D2M&t=279s
+    #
+    # swiftc also requires that all output paths are unique, so we can't just use
+    # /dev/null as the output path.
+    #
+    # Buck requires that all declared outputs are created when the rule succeeds, but we
+    # want to create an index store even if there are errors in the source files.
+    #
+    # We solve this by declaring a directory as the buck output, and telling swiftc that
+    # we want all our .o files there. Our target will then succeed whether or not we
+    # create a .o file.
+    objects_dir = ctx.actions.declare_output("__indexstore__/objects", dir = True, has_content_based_path = False)
+
+    sh_cmd = cmd_args([
+        "mkdir",
+        "-p",
+        objects_dir.as_output(),
+    ])
+    ctx.actions.run(
+        sh_cmd,
+        category = "swift_compilation_database",
+    )
+
+    # We need an output file map with index-unit-output-path entries to be able
+    # to index all of the srcs in a single pass.
+    output_file_map = {}
+    for src in srcs:
+        output_file_map[src.file] = {
+            "diagnostics": cmd_args(objects_dir, format = "{}/" + src.file.basename + ".dia", delimiter = ""),
+            # The output here is only used for the identifier of the index unit file
+            "index-unit-output-path": src.file,
+            "object": cmd_args(objects_dir, format = "{}/" + src.file.basename + ".o", delimiter = ""),
+        }
+
+    index_store_output = ctx.actions.declare_output("__indexstore__/swift_{}".format(module_name), dir = True, has_content_based_path = False)
+    additional_flags = cmd_args(
+        ([] if _INDEX_SYSTEM_MODULES else ["-index-ignore-system-modules"])
+        + [
+            "-index-store-path",
+            index_store_output.as_output(),
+            "-c",
+            "-disable-batch-mode",
+            "-Xwrapper",
+            "-ignore-errors",
+        ]
+    )
+
+    _compile_with_argsfile(
+        ctx = ctx,
+        category = "swift_index_compile",
+        shared_flags = shared_flags,
+        srcs = srcs,
+        additional_flags = additional_flags,
+        toolchain = toolchain,
+        cacheable = True,
+        # Incremental builds are never cached, but caching the index store build is very useful
+        # when building all the transitive index stores (e.g. during the Glean indexer).
+        incremental_build_allowed = False,
+        output_file_map = output_file_map,
+    )
+
+    return index_store_output
+
+def _compile_with_argsfile(
+    ctx: AnalysisContext,
+    category: str,
+    shared_flags: cmd_args,
+    srcs: list[CxxSrcWithFlags],
+    additional_flags: cmd_args,
+    toolchain: SwiftToolchainInfo,
+    extension: str | None = None,
+    num_threads: int = 1,
+    dep_files: dict[str, ArtifactTag] = {},
+    output_file_map: dict = {},
+    cacheable = True,
+    skip_incremental_outputs = False,
+    supports_serialized_errors = True,
+    incremental_build_allowed = True,
+    objects = [],
+    incremental_artifacts: IncrementalCompilationInput | None = None,
+    artifact_tag: ArtifactTag | None = None,
+) -> (CompileArgsfiles | None, Artifact | None):
+    build_swift_incrementally = incremental_build_allowed and should_build_swift_incrementally(ctx)
+
+    explicit_modules_enabled = uses_explicit_modules(ctx)
+
+    # The main compilation actions add a category suffix when explicit modules
+    # are enabled for debugging and telemetry reasons. This is very important,
+    # so do not be tempted to remove the suffixing.
+    if extension and explicit_modules_enabled:
+        category += EXPLICIT_MODULES_CATEGORY_SUFFIX
+
+    allow_cache_upload, action_execution_attributes = _get_action_properties(toolchain, cacheable, build_swift_incrementally, explicit_modules_enabled)
+
+    argsfile, output_file_map = compile_with_argsfile(
+        ctx = ctx,
+        category = category,
+        shared_flags = shared_flags,
+        srcs = srcs,
+        additional_flags = additional_flags,
+        toolchain = toolchain,
+        num_threads = num_threads,
+        dep_files = dep_files,
+        output_file_map = output_file_map,
+        allow_cache_upload = allow_cache_upload,
+        local_only = action_execution_attributes.local_only,
+        prefer_local = action_execution_attributes.prefer_local,
+        # We need to preserve the action outputs for incremental compilation.
+        no_outputs_cleanup = build_swift_incrementally,
+        # Skip incremental outputs requires an empty output file map, so is not
+        # compatible with serialized diagnostics.
+        supports_serialized_errors = (not skip_incremental_outputs) and supports_serialized_errors,
+        skip_incremental_outputs = skip_incremental_outputs,
+        objects = objects,
+        incremental_artifacts = incremental_artifacts,
+        artifact_tag = artifact_tag,
+        incremental_remote_outputs = get_incremental_remote_outputs_enabled(ctx) and build_swift_incrementally,
+    )
+
+    if extension:
+        # Swift correctly handles relative paths and we can utilize the relative argsfile for Xcode.
+        return CompileArgsfiles(relative = {extension: argsfile}, xcode = {extension: argsfile}), output_file_map
+    else:
+        return None, output_file_map
+
+def _get_action_properties(
+    toolchain: SwiftToolchainInfo, cacheable: bool, build_swift_incrementally: bool, explicit_modules_enabled: bool
+) -> (bool, ActionExecutionAttributes):  # (allow_cache_upload, ActionExecutionAttributes)
+    # By default, we allow Buck and any command line arguments to determine execution preference.
+    # However, based upon certain functionality or execution environments, we modify these
+    # default properties for cacheability and performance.
+
+    # If we prefer to execute locally (e.g., for perf reasons), ensure we upload to the cache so
+    # that CI builds populate caches used by developer machines.
+    allow_cache_upload = True
+
+    local_only = False
+
+    # Swift compilation on RE without explicit modules is impractically expensive because there's
+    # no shared module cache across different libraries.
+    prefer_local = not explicit_modules_enabled
+
+    if build_swift_incrementally:
+        # When Swift code is built incrementally, the swift-driver embeds absolute paths into the
+        # artifacts without relative resource dir support. In this case we can only build locally.
+        if not toolchain.supports_relative_resource_dir:
+            allow_cache_upload = False
+            local_only = True
+            prefer_local = False
+
+    if not cacheable:
+        allow_cache_upload = False
+        local_only = True
+        prefer_local = False
+
+    return (allow_cache_upload, ActionExecutionAttributes(prefer_local = prefer_local, local_only = local_only))
+
+def _get_serialize_debugging_options(ctx: AnalysisContext, uses_explicit_modules: bool):
+    if ctx.attrs.serialize_debugging_options == False:
+        return False
+
+    if uses_explicit_modules:
+        # If the toolchain supports explicit modules we can
+        # enable, regardless if this is a mixed library or not
+        return get_swift_toolchain_info(ctx).supports_explicit_module_debug_serialization
+
+    # Serialized debugging options contain absolute paths until
+    # https://github.com/swiftlang/swift/pull/84112
+    return False
+
+def _get_shared_flags(
+    ctx: AnalysisContext,
+    deps_providers: list,
+    parse_as_library: bool,
+    public_module: SwiftCompiledModuleInfo | None,
+    module_name: str,
+    public_modulemap_pp_info: CPreprocessor | None,
+    extra_search_paths_flags: list[ArgLike],
+    inputs_tag: ArtifactTag,
+    is_macro: bool,
+) -> (cmd_args, Artifact | None):
+    toolchain = get_swift_toolchain_info(ctx)
+    cmd = cmd_args()
+
+    if not toolchain.supports_relative_resource_dir:
+        # Setting this to empty will get the driver to make all paths absolute when
+        # passed to the frontend. We later debug prefix these to ensure relative paths
+        # in the debug info.
+        cmd.add(["-working-directory="])
+
+    cmd.add(get_sdk_flags(ctx))
+    cmd.add(_get_target_flags(ctx))
+    cmd.add(
+        "-swift-version",
+        ctx.attrs.swift_version,
+        # Always use color, consistent with clang.
+        "-color-diagnostics",
+        # Unset the working directory in the debug information.
+        "-file-compilation-dir",
+        ".",
+        "-module-name",
+        module_name,
+        "-Xfrontend",
+        "-enable-cross-import-overlays",
+        "-Xfrontend",
+        "-disable-cxx-interop-requirement-at-import",
+        "-Xfrontend",
+        "-emit-clang-header-nonmodular-includes",
+        # RE actions are run in a sandbox, which will fail to run macros as
+        # you cannot nest sandbox actions.
+        # https://github.com/swiftlang/swift/pull/70079
+        "-disable-sandbox",
+    )
+
+    if parse_as_library:
+        cmd.add([
+            "-parse-as-library",
+        ])
+
+    if ctx.attrs.swift_package_name != None:
+        cmd.add([
+            "-package-name",
+            ctx.attrs.swift_package_name,
+        ])
+
+    explicit_modules_enabled = uses_explicit_modules(ctx)
+    if explicit_modules_enabled:
+        cmd.add([
+            "-Xcc",
+            "-Xclang",
+            "-Xcc",
+            # We set -fmodule-file-home-is-cwd as this is used to correctly
+            # set the working directory of modules when generating debug info.
+            "-fmodule-file-home-is-cwd",
+            "-Xcc",
+            "-Xclang",
+            "-Xcc",
+            # This is the default for compilation, but not in sourcekitd.
+            # Set it explicitly here so that indexing will not fail with
+            # invalid module format errors.
+            "-fmodule-format=obj",
+        ])
+        cmd.add(get_disable_pch_validation_flags())
+    else:
+        # Clang module breadcrumbs include module hashes and temporary paths
+        # and need to be excluded for deterministic build output.
+        cmd.add("-Xfrontend", "-no-clang-module-breadcrumbs")
+
+    if toolchain.resource_dir:
+        cmd.add([
+            "-resource-dir",
+            toolchain.resource_dir,
+        ])
+
+    if ctx.attrs.enable_cxx_interop:
+        cmd.add(["-cxx-interoperability-mode=default"])
+
+    if _get_serialize_debugging_options(ctx, explicit_modules_enabled):
+        cmd.add([
+            "-Xfrontend",
+            "-serialize-debugging-options",
+            "-Xfrontend",
+            "-prefix-serialized-debugging-options",
+        ])
+    else:
+        cmd.add([
+            "-Xfrontend",
+            "-no-serialize-debugging-options",
+        ])
+
+    upcoming_features = toolchain.swift_upcoming_features[ctx.attrs.swift_version]
+    experimental_features = toolchain.swift_experimental_features[ctx.attrs.swift_version]
+
+    for feature in upcoming_features:
+        cmd.add([
+            "-Xfrontend",
+            "-enable-upcoming-feature",
+            "-Xfrontend",
+            feature,
+        ])
+
+    for feature in experimental_features:
+        cmd.add([
+            "-Xfrontend",
+            "-enable-experimental-feature",
+            "-Xfrontend",
+            feature,
+        ])
+
+    if ctx.attrs._swift_enable_testing:
+        cmd.add("-enable-testing")
+
+    if getattr(ctx.attrs, "application_extension", False):
+        cmd.add("-application-extension")
+
+    # Only apple_library and apple_test has swift_macro_deps
+    swift_macros = getattr(ctx.attrs, "swift_macro_deps", [])
+    if swift_macros:
+        for m in ctx.plugins[SwiftMacroPlugin]:
+            macro_artifact = m[DefaultInfo].default_outputs[0]
+            cmd.add([
+                "-load-plugin-executable",
+                cmd_args(inputs_tag.tag_artifacts(macro_artifact), format = "{}#" + macro_artifact.basename),
+            ])
+
+    pcm_deps_tset = get_compiled_pcm_deps_tset(ctx, deps_providers)
+
+    # If Swift Explicit Modules are enabled, a few things must be provided to a compilation job:
+    # 1. Direct and transitive SDK deps from `sdk_modules` attribute.
+    # 2. Direct and transitive user-defined deps.
+    # 3. Transitive SDK deps of user-defined deps.
+    # (This is the case, when a user-defined dep exports a type from SDK module,
+    # thus such SDK module should be implicitly visible to consumers of that custom dep)
+    swift_module_map_artifact = None
+    if uses_explicit_modules(ctx):
+        sdk_clang_deps_tset = get_compiled_sdk_clang_deps_tset(ctx, deps_providers)
+        sdk_swift_deps_tset = get_compiled_sdk_swift_deps_tset(ctx, deps_providers)
+        swift_module_map_artifact = _add_swift_module_map_args(
+            ctx = ctx,
+            sdk_swiftmodule_deps_tset = sdk_swift_deps_tset,
+            pcm_deps_tset = pcm_deps_tset,
+            sdk_deps_tset = sdk_clang_deps_tset,
+            inputs_tag = inputs_tag,
+            cmd = cmd,
+            is_macro = is_macro,
+        )
+
+    _add_clang_deps_flags(ctx, pcm_deps_tset, cmd, inputs_tag)
+    _add_swift_deps_flags(ctx, cmd, is_macro)
+
+    # Add flags for importing the ObjC part of this library
+    _add_mixed_library_flags_to_cmd(
+        ctx,
+        cmd,
+        public_module,
+        public_modulemap_pp_info,
+    )
+
+    # Add toolchain and target flags last to allow for overriding defaults
+    cmd.add(toolchain.compiler_flags)
+    cmd.add(ctx.attrs.swift_compiler_flags)
+    cmd.add(extra_search_paths_flags)
+
+    return (cmd, swift_module_map_artifact)
+
+def _add_swift_module_map_args(
+    ctx: AnalysisContext,
+    sdk_swiftmodule_deps_tset: SwiftCompiledModuleTset,
+    pcm_deps_tset: SwiftCompiledModuleTset,
+    sdk_deps_tset: SwiftCompiledModuleTset,
+    inputs_tag: ArtifactTag,
+    cmd: cmd_args,
+    is_macro: bool,
+) -> Artifact:
+    module_name = get_module_name(ctx)
+    sdk_swiftmodule_deps_tset = [sdk_swiftmodule_deps_tset] if sdk_swiftmodule_deps_tset else []
+    all_deps_tset = ctx.actions.tset(
+        SwiftCompiledModuleTset,
+        children = _get_swift_paths_tsets(is_macro, ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", []))
+        + [pcm_deps_tset, sdk_deps_tset]
+        + sdk_swiftmodule_deps_tset,
+    )
+    swift_module_map_artifact, swift_module_map_args = write_swift_module_map_with_deps(
+        ctx,
+        module_name,
+        all_deps_tset,
+    )
+    cmd.add([
+        "-Xfrontend",
+        "-explicit-swift-module-map-file",
+        "-Xfrontend",
+        inputs_tag.tag_artifacts(swift_module_map_args),
+    ])
+    return swift_module_map_artifact
+
+def _add_swift_deps_flags(ctx: AnalysisContext, cmd: cmd_args, is_macro: bool):
+    if uses_explicit_modules(ctx):
+        cmd.add([
+            "-Xcc",
+            "-fno-implicit-modules",
+            "-Xcc",
+            "-fno-implicit-module-maps",
+            "-Xfrontend",
+            "-disable-implicit-swift-modules",
+        ])
+    else:
+        depset = ctx.actions.tset(SwiftCompiledModuleTset, children = _get_swift_paths_tsets(is_macro, ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", [])))
+        cmd.add(depset.project_as_args("module_search_path"))
+
+        implicit_search_path_tset = get_implicit_framework_search_path_providers(
+            ctx,
+            None,
+            ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", []),
+        )
+        cmd.add(implicit_search_path_tset.project_as_args("swift_framework_implicit_search_paths_args"))
+
+def _add_clang_deps_flags(ctx: AnalysisContext, pcm_deps_tset: SwiftCompiledModuleTset, cmd: cmd_args, inputs_tag: ArtifactTag) -> None:
+    if uses_explicit_modules(ctx):
+        clang_flags = pcm_deps_tset.project_as_args("clang_importer_flags")
+        cmd.add(inputs_tag.tag_artifacts(clang_flags))
+    else:
+        inherited_preprocessor_infos = cxx_inherited_preprocessor_infos(ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", []))
+        preprocessors = cxx_merge_cpreprocessors(ctx.actions, [], inherited_preprocessor_infos)
+        cmd.add(cmd_args(preprocessors.set.project_as_args("args"), prepend = "-Xcc"))
+        cmd.add(cmd_args(preprocessors.set.project_as_args("modular_args"), prepend = "-Xcc"))
+
+def _add_mixed_library_flags_to_cmd(
+    ctx: AnalysisContext, cmd: cmd_args, underlying_module: SwiftCompiledModuleInfo | None, public_modulemap_pp_info: CPreprocessor | None
+) -> None:
+    if uses_explicit_modules(ctx):
+        if underlying_module:
+            cmd.add(underlying_module.clang_importer_args)
+            cmd.add(clang_module_file_args(underlying_module))
+            cmd.add("-import-underlying-module")
+        return
+
+    for objc_modulemap_pp_info in filter(None, [public_modulemap_pp_info]):
+        # TODO(T99100029): We cannot use VFS overlays to mask this import from
+        # the debugger as they require absolute paths. Instead we will enforce
+        # that mixed libraries do not have serialized debugging info and rely on
+        # rdeps to serialize the correct paths.
+        for arg in objc_modulemap_pp_info.args.args:
+            cmd.add("-Xcc")
+            cmd.add(arg)
+
+        for arg in objc_modulemap_pp_info.modular_args:
+            cmd.add("-Xcc")
+            cmd.add(arg)
+
+    if public_modulemap_pp_info:
+        cmd.add("-import-underlying-module")
+
+def _get_swift_dependency_info(is_macro: bool, deps: list[Dependency]) -> list[SwiftDependencyInfo]:
+    ret = []
+    for d in deps:
+        if SwiftDependencyInfo in d:
+            if d[SwiftDependencyInfo].is_macro != is_macro:
+                fail(
+                    "Cannot have a {} dep in a {} target".format(
+                        "macro" if d[SwiftDependencyInfo].is_macro else "non-macro",
+                        "macro" if is_macro else "non-macro",
+                    )
+                )
+            ret.append(d[SwiftDependencyInfo])
+
+    return ret
+
+def _get_swift_paths_tsets(is_macro: bool, deps: list[Dependency]) -> list[SwiftCompiledModuleTset]:
+    return [d.exported_swiftmodules for d in _get_swift_dependency_info(is_macro, deps)]
+
+def get_external_debug_info_tsets(is_macro: bool, deps: list[Dependency]) -> list[ArtifactTSet]:
+    return [d.debug_info_tset for d in _get_swift_dependency_info(is_macro, deps)]
+
+def get_external_swiftmodule_change_analysis_tsets(is_macro: bool, deps: list[Dependency]) -> list[ArtifactTSet]:
+    return [d.swiftmodule_change_analysis_tset for d in _get_swift_dependency_info(is_macro, deps)]
+
+def get_external_swift_ast_dump_tsets(is_macro: bool, deps: list[Dependency]) -> list[ArtifactTSet]:
+    return [d.swift_ast_dump_tset for d in _get_swift_dependency_info(is_macro, deps)]
+
+def get_swift_pcm_uncompile_info(
+    ctx: AnalysisContext, propagated_exported_preprocessor_info: [CPreprocessorInfo, None], exported_pre: [CPreprocessor, None]
+) -> [SwiftPCMUncompiledInfo, None]:
+    swift_toolchain = get_swift_toolchain_info(ctx)
+
+    if is_sdk_modules_provided(swift_toolchain):
+        clang_importer_args = cmd_args()
+        if propagated_exported_preprocessor_info:
+            # We need to include exported preprocessor from exported_deps to
+            # handle misconfigured targets that have non-modular exported_deps
+            clang_importer_args.add(cmd_args(propagated_exported_preprocessor_info.set.project_as_args("args"), prepend = "-Xcc"))
+
+        exported_clang_importer_args = cmd_args()
+        if exported_pre:
+            if supports_modulemaps_with_hmaps(ctx):
+                # The cxx preprocessor info will not include the modular args,
+                # so include the required modulemap flags for this target only.
+                # The deps modular args will be included via projections on the
+                # deps SwiftCompiledModuleTsets.
+                clang_importer_args.add(cmd_args(exported_pre.modular_args, prepend = "-Xcc"))
+            else:
+                # We need special handling for our own exported_pre, which
+                # contains the header search path flags for the modules header
+                # symlink tree. This needs to be propagated to rdeps.
+                exported_clang_importer_args.add(cmd_args(exported_pre.modular_args, prepend = "-Xcc"))
+
+        return SwiftPCMUncompiledInfo(
+            clang_importer_args = clang_importer_args,
+            exported_clang_importer_args = exported_clang_importer_args,
+            exported_deps = _exported_deps(ctx),
+            is_transient = not ctx.attrs.modular or not exported_pre,
+            modulemap_artifact = exported_pre.modulemap_artifact if exported_pre else None,
+            name = get_module_name(ctx),
+            uncompiled_sdk_modules = ctx.attrs.sdk_modules,
+        )
+    return None
+
+def create_swift_dependency_info(
+    ctx: AnalysisContext,
+    deps,
+    deps_providers: list,
+    compiled_info: [SwiftCompiledModuleInfo, None],
+    debug_info_tset: ArtifactTSet,
+    swiftmodule_change_analysis_tset: ArtifactTSet,
+    swift_ast_dump_tset: ArtifactTSet,
+    is_macro: bool,
+):
+    # We pass through the SDK swiftmodules here to match Buck 1 behaviour. This is
+    # pretty loose, but it matches Buck 1 behavior so cannot be improved until
+    # migration is complete.
+    transitive_swiftmodule_deps = _get_swift_paths_tsets(is_macro, deps) + [get_compiled_sdk_swift_deps_tset(ctx, deps_providers)]
+
+    if compiled_info:
+        exported_swiftmodules = ctx.actions.tset(SwiftCompiledModuleTset, value = compiled_info, children = transitive_swiftmodule_deps)
+    else:
+        exported_swiftmodules = ctx.actions.tset(SwiftCompiledModuleTset, children = transitive_swiftmodule_deps)
+
+    return SwiftDependencyInfo(
+        debug_info_tset = debug_info_tset,
+        exported_swiftmodules = exported_swiftmodules,
+        # prebuilt_apple_framework do not have exported_headers, we can exclude
+        # them from validation safely.
+        has_exported_headers = len(getattr(ctx.attrs, "exported_headers", [])) > 0,
+        is_modular = ctx.attrs.modular,
+        is_macro = is_macro,
+        swift_ast_dump_tset = swift_ast_dump_tset,
+        swiftmodule_change_analysis_tset = swiftmodule_change_analysis_tset,
+    )
+
+def get_swift_dependency_info(
+    ctx: AnalysisContext,
+    output_module: Artifact | None,
+    deps_providers: list,
+    is_macro: bool,
+    swift_ast_dump_artifacts: list[Artifact] = [],
+) -> SwiftDependencyInfo:
+    exported_deps = _exported_deps(ctx)
+
+    if output_module:
+        compiled_info = SwiftCompiledModuleInfo(
+            is_framework = False,
+            is_sdk_module = False,
+            is_swiftmodule = True,
+            module_name = get_module_name(ctx),
+            output_artifact = output_module,
+        )
+    else:
+        compiled_info = None
+
+    all_deps = ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", [])
+
+    debug_info_tset = make_artifact_tset(
+        actions = ctx.actions,
+        artifacts = filter(None, [output_module]),
+        children = get_external_debug_info_tsets(is_macro, all_deps),
+        label = ctx.label,
+        tags = [ArtifactInfoTag("swift_debug_info")],
+    )
+
+    # Deliberately broader than `all_deps` above (also covers toolchain
+    # `default_deps` and `deps_query`, via `cxx_attr_deps`/`cxx_attr_exported_deps`):
+    # this tset is new, so widening it to match the rest of the codebase's
+    # convention has no existing behavior to preserve. `debug_info_tset` and
+    # `swift_ast_dump_tset` predate this and keep the narrower `all_deps` to
+    # avoid changing their already-shipped output.
+    swiftmodule_change_analysis_deps = cxx_attr_deps(ctx) + cxx_attr_exported_deps(ctx)
+
+    swiftmodule_change_analysis_tset = make_artifact_tset(
+        actions = ctx.actions,
+        artifacts = filter(None, [output_module]),
+        children = get_external_swiftmodule_change_analysis_tsets(is_macro, swiftmodule_change_analysis_deps),
+        label = ctx.label,
+    )
+
+    swift_ast_dump_tset = make_artifact_tset(
+        actions = ctx.actions,
+        artifacts = swift_ast_dump_artifacts,
+        children = get_external_swift_ast_dump_tsets(is_macro, all_deps),
+        label = ctx.label,
+    )
+
+    return create_swift_dependency_info(
+        ctx,
+        exported_deps,
+        deps_providers,
+        compiled_info,
+        debug_info_tset,
+        swiftmodule_change_analysis_tset,
+        swift_ast_dump_tset,
+        is_macro,
+    )
+
+def get_swiftmodule_linkable(swift_compile_output: [SwiftCompilationOutput, None]) -> [SwiftmoduleLinkable, None]:
+    return SwiftmoduleLinkable(swiftmodules = swift_compile_output.swift_debug_info) if swift_compile_output else None
+
+def extract_swiftmodule_linkables(link_infos: [list[LinkInfo], None]) -> list[SwiftmoduleLinkable]:
+    linkables = []
+    for info in link_infos:
+        for linkable in info.linkables:
+            if isinstance(linkable, SwiftmoduleLinkable):
+                linkables.append(linkable)
+
+    return linkables
+
+def get_swiftmodule_linker_flags(ctx: AnalysisContext, swiftmodule_linkable: [SwiftmoduleLinkable, None]) -> cmd_args:
+    if swiftmodule_linkable:
+        tset = swiftmodule_linkable.swiftmodules
+        artifacts = project_artifacts(
+            actions = ctx.actions,
+            tsets = tset,
+        )
+        return cmd_args([cmd_args(swiftmodule, format = "-Wl,-add_ast_path,{}") for swiftmodule in artifacts])
+    return cmd_args()
+
+def _get_xctest_swiftmodule_search_path(ctx: AnalysisContext) -> cmd_args:
+    # With explicit modules we don't need to search at all.
+    if uses_explicit_modules(ctx):
+        return cmd_args()
+
+    for fw in ctx.attrs.frameworks:
+        if fw.endswith("XCTest.framework"):
+            toolchain = ctx.attrs._apple_toolchain[AppleToolchainInfo]
+            return cmd_args(toolchain.platform_path, format = "-I{}/Developer/usr/lib")
+
+    return cmd_args()
+
+def get_swift_debug_infos(
+    ctx: AnalysisContext, swift_dependency_info: [SwiftDependencyInfo, None], swift_output: [SwiftCompilationOutput, None]
+) -> SwiftDebugInfo:
+    # When determining the debug info for shared libraries, if the shared library is a link group, we rely on the link group links to
+    # obtain the debug info for linked libraries and only need to provide any swift debug info for this library itself. Otherwise
+    # if linking standard shared, we need to obtain the transitive debug info.
+    if get_link_group(ctx):
+        swift_shared_debug_info = []
+    else:
+        swift_shared_debug_info = _get_swift_shared_debug_info(swift_dependency_info) if swift_dependency_info else []
+
+    clang_debug_info = [swift_output.clang_debug_info] if swift_output else []
+    swift_debug_info = [swift_output.swift_debug_info] if swift_output else []
+
+    return SwiftDebugInfo(
+        static = clang_debug_info + swift_debug_info,
+        shared = swift_shared_debug_info + clang_debug_info + swift_debug_info,
+    )
+
+def _get_swift_shared_debug_info(swift_dependency_info: SwiftDependencyInfo) -> list[ArtifactTSet]:
+    return [swift_dependency_info.debug_info_tset] if swift_dependency_info.debug_info_tset else []
+
+def _get_project_root_file(ctx) -> Artifact:
+    content = cmd_args(ctx.label.project_root)
+    return ctx.actions.write("project_root_file", content, absolute = True, has_content_based_path = False)
+
+def _create_compilation_database(ctx: AnalysisContext, srcs: list[CxxSrcWithFlags], argfile: CompileArgsfile) -> SwiftCompilationDatabase:
+    module_name = get_module_name(ctx)
+
+    swift_toolchain = get_swift_toolchain_info(ctx)
+    mk_comp_db = swift_toolchain.mk_swift_comp_db
+
+    identifier = module_name + ".swift_comp_db.json"
+    cdb_artifact = ctx.actions.declare_output(identifier, has_content_based_path = False)
+
+    srcs_args = cmd_args([s.file for s in srcs])
+
+    cmd = cmd_args(mk_comp_db)
+    cmd.add(cmd_args(cdb_artifact.as_output(), format = "--output={}"))
+    cmd.add(cmd_args(_get_project_root_file(ctx), format = "--project-root-file={}"))
+    cmd.add("--files", srcs_args)
+
+    cmd.add("--")
+
+    cmd_form_and_srcs = cmd_args(argfile.cmd_form, srcs_args)
+    cmd.add(cmd_form_and_srcs)
+
+    ctx.actions.run(
+        cmd,
+        category = "swift_compilation_database",
+        identifier = identifier,
+        error_handler = apple_build_error_handler,
+    )
+
+    return SwiftCompilationDatabase(db = cdb_artifact, other_outputs = cmd_form_and_srcs)
+
+def _create_objc_swift_interface(ctx: AnalysisContext, shared_flags: cmd_args, module_name: str) -> DefaultInfo:
+    """Generates the Swift interface representation of a modular Obj-C(++) target."""
+    swift_toolchain = get_swift_toolchain_info(ctx)
+    swift_ide_test_tool = swift_toolchain.swift_ide_test_tool
+    if not swift_ide_test_tool:
+        return DefaultInfo()
+    mk_swift_interface = swift_toolchain.mk_swift_interface
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+
+    identifier = module_name + ".swift_interface"
+
+    argsfile, _ = ctx.actions.write(
+        identifier + "_argsfile",
+        shared_flags,
+        allow_args = True,
+        has_content_based_path = uses_content_based_paths,
+    )
+    interface_artifact = ctx.actions.declare_output(identifier, has_content_based_path = uses_content_based_paths)
+
+    mk_swift_args = cmd_args(
+        mk_swift_interface,
+        "--swift-ide-test-tool",
+        swift_ide_test_tool,
+        "--module",
+        module_name,
+        "--out",
+        interface_artifact.as_output(),
+        "--",
+        cmd_args(cmd_args(argsfile, format = "@{}", delimiter = ""), hidden = [shared_flags]),
+    )
+
+    ctx.actions.run(
+        mk_swift_args,
+        category = "mk_swift_interface",
+        identifier = identifier,
+        error_handler = apple_build_error_handler,
+    )
+
+    return DefaultInfo(
+        default_output = interface_artifact,
+        other_outputs = [
+            argsfile,
+        ],
+    )
+
+def _exported_deps(ctx) -> list[Dependency]:
+    if ctx.attrs.reexport_all_header_dependencies:
+        return getattr(ctx.attrs, "exported_deps", []) + ctx.attrs.deps
+    else:
+        return getattr(ctx.attrs, "exported_deps", [])
+
+def _should_compile_with_evolution(ctx) -> bool:
+    if ctx.attrs.enable_library_evolution != None:
+        return ctx.attrs.enable_library_evolution
+    return ctx.attrs._enable_library_evolution
diff --git a/buck2/prelude/apple/swift/swift_debug_info_utils.bzl b/buck2/prelude/apple/swift/swift_debug_info_utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_debug_info_utils.bzl
@@ -0,0 +1,60 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactInfoTag",
+    "ArtifactTSet",
+    "make_artifact_tset",
+)
+load(":swift_pcm_compilation_types.bzl", "WrappedSwiftPCMCompiledInfo")
+load(":swift_toolchain.bzl", "get_swift_toolchain_info")
+load(
+    ":swift_toolchain_types.bzl",
+    "WrappedSdkCompiledModuleInfo",
+)
+
+def extract_and_merge_swift_debug_infos(ctx: AnalysisContext, compiled_pcm_deps_providers, artifacts: list[Artifact] = []) -> ArtifactTSet:
+    provide_swift_debug_info = get_swift_toolchain_info(ctx).provide_swift_debug_info
+    swift_debug_tsets = (
+        [
+            d[WrappedSdkCompiledModuleInfo].swift_debug_info
+            for d in compiled_pcm_deps_providers
+            if WrappedSdkCompiledModuleInfo in d and d[WrappedSdkCompiledModuleInfo].swift_debug_info != None
+        ]
+        if provide_swift_debug_info
+        else []
+    )
+
+    return make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        artifacts = artifacts if provide_swift_debug_info else [],
+        children = swift_debug_tsets,
+        tags = [ArtifactInfoTag("swift_debug_info")],
+    )
+
+def extract_and_merge_clang_debug_infos(ctx: AnalysisContext, compiled_pcm_deps_providers, pcms_and_modulemaps: list[Artifact] = []) -> ArtifactTSet:
+    clang_debug_tsets = []
+    for d in compiled_pcm_deps_providers:
+        if WrappedSdkCompiledModuleInfo in d and d[WrappedSdkCompiledModuleInfo].clang_debug_info != None:
+            clang_debug_tsets.append(d[WrappedSdkCompiledModuleInfo].clang_debug_info)
+        if WrappedSwiftPCMCompiledInfo in d:
+            clang_debug_tsets.append(d[WrappedSwiftPCMCompiledInfo].clang_debug_info)
+
+    swift_toolchain = get_swift_toolchain_info(ctx)
+    swift_toolchain_debug_info_tsets = [swift_toolchain.sdk_debug_info] if swift_toolchain.sdk_debug_info else []
+
+    return make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        # Even with explicit modules, lldb requires the presence of the modulemaps.
+        artifacts = pcms_and_modulemaps,
+        children = clang_debug_tsets + swift_toolchain_debug_info_tsets,
+        tags = [ArtifactInfoTag("swift_debug_info")],
+    )
diff --git a/buck2/prelude/apple/swift/swift_helpers.bzl b/buck2/prelude/apple/swift/swift_helpers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_helpers.bzl
@@ -0,0 +1,298 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_error_handler.bzl", "apple_build_error_handler", "swift_error_deserializer", "swift_error_handler")
+load("@prelude//apple/swift:apple_sdk_modules_utility.bzl", "is_sdk_modules_provided")
+load("@prelude//cxx:argsfiles.bzl", "CompileArgsfile")
+load("@prelude//cxx:cxx_sources.bzl", "CxxSrcWithFlags")
+load(
+    ":swift_incremental_support.bzl",
+    "IncrementalCompilationInput",  # @unused Used as a type
+    "get_incremental_split_actions",
+    "get_uses_content_based_paths",
+    "should_build_swift_incrementally",
+)
+load(":swift_output_file_map.bzl", "add_output_file_map_flags", "add_serialized_diagnostics_output")
+load(":swift_toolchain.bzl", "get_swift_toolchain_info")
+load(":swift_toolchain_types.bzl", "SwiftToolchainInfo")
+load(
+    ":swift_types.bzl",
+    "EXPLICIT_MODULES_CATEGORY_SUFFIX",
+    "SWIFTMODULE_COMPILE_CATEGORY",
+    "SWIFT_COMPILE_CATEGORY",
+)
+
+CompileWithArgsFileCmdOutput = record(
+    cmd = field(cmd_args),
+    argsfile = field(Artifact),
+    argsfile_cmd_form = field(cmd_args),
+    shell_quoted_args = field(cmd_args),
+    error_outputs = field(list[OutputArtifact]),
+    output_file_map_artifact = field(Artifact | None),
+    error_deserializer = field(RunInfo | None),
+)
+
+ENFORCED_CATEGORIES = [
+    SWIFTMODULE_COMPILE_CATEGORY + EXPLICIT_MODULES_CATEGORY_SUFFIX,
+    SWIFTMODULE_COMPILE_CATEGORY,
+    SWIFT_COMPILE_CATEGORY + EXPLICIT_MODULES_CATEGORY_SUFFIX,
+    SWIFT_COMPILE_CATEGORY,
+]
+
+# def _get_should_expect_eligible_for_dedupe(ctx: AnalysisContext, category: str) -> bool:
+#     uses_content_based_paths = get_uses_content_based_paths(ctx)
+#     toolchain = get_swift_toolchain_info(ctx)
+#
+#     expect_eligible_for_dedupe = toolchain.enforce_dedupe_eligibility and uses_content_based_paths and category in ENFORCED_CATEGORIES
+#
+#     return expect_eligible_for_dedupe
+
+def _is_swiftmodule_emit_category(category: str) -> bool:
+    return "swiftmodule" in category
+
+def _is_swiftmodule_or_pcm_category(category: str) -> bool:
+    # Matches swiftmodule_compile[_with_explicit_mods] and every *pcm_compile
+    # category (swift_pcm_compile, swift_underlying_pcm_compile,
+    # swift_prebuilt_framework_pcm_compile).
+    return _is_swiftmodule_emit_category(category) or "pcm_compile" in category
+
+def _is_swift_object_category(category: str) -> bool:
+    # Bulk Swift object compiles (not swiftmodule/pcm).
+    return category in (SWIFT_COMPILE_CATEGORY, SWIFT_COMPILE_CATEGORY + EXPLICIT_MODULES_CATEGORY_SUFFIX)
+
+def _low_pass_filter_for_category(category: str, prioritized: bool) -> bool:
+    # Disable low-pass gating for prioritized swiftmodule and PCM actions.
+    if prioritized and _is_swiftmodule_or_pcm_category(category):
+        return False
+    return True
+
+def _prefer_local_for_category(
+    category: str,
+    prioritized: bool,
+    local_only: bool,
+    prefer_local: bool,
+) -> bool:
+    if local_only:
+        return prefer_local
+
+    if prioritized and _is_swiftmodule_emit_category(category):
+        return True
+    return prefer_local
+
+def compile_with_argsfile_cmd(
+    ctx: AnalysisContext,
+    category: str,
+    shared_flags: cmd_args,
+    srcs: list[CxxSrcWithFlags],
+    additional_flags: cmd_args,
+    toolchain: SwiftToolchainInfo,
+    output_file_map: dict,
+    supports_output_file_map: bool,
+    supports_serialized_errors: bool,
+    skip_incremental_outputs: bool,
+    incremental_remote_outputs: bool,
+    objects: list[Artifact],
+    incremental_artifacts: IncrementalCompilationInput | None,
+    artifact_tag: ArtifactTag | None,
+) -> CompileWithArgsFileCmdOutput:
+    object_outputs = [obj.as_output() for obj in objects]
+
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+
+    writable_incremental_args = []
+    if incremental_artifacts:
+        writable_incremental_args.extend(object_outputs)
+        writable_incremental_args.extend([swiftdep.as_output() for swiftdep in incremental_artifacts.swiftdeps])
+        writable_incremental_args.extend([depfile.as_output() for depfile in incremental_artifacts.depfiles])
+        if incremental_artifacts.swiftdoc:
+            writable_incremental_args.append(incremental_artifacts.swiftdoc.as_output())
+
+    cmd = cmd_args(toolchain.compiler)
+    cmd.add(additional_flags)
+
+    # Hack to make output_file_map mutable when the default is used.
+    output_file_map = output_file_map or {}
+
+    # Assemble argsfile with compiler flags. We don't use `with_inputs` in the
+    # write action as this strips tagged values and breaks dependency file
+    # input tracking.
+    shell_quoted_args = cmd_args(shared_flags, quote = "shell")
+
+    if artifact_tag != None and uses_content_based_paths:
+        # This is a little bit convoluted due to the way that content-based paths affect argfiles.
+        # If an unused tagged input changes, we don't want to re-run the action, but if it is a
+        # content-based input that is written to the argfile, then the argfile will also change
+        # and that would cause a re-run.
+        #
+        # We therefore write the argfile twice: the "real" argfile, which is used in the action
+        # and tagged as unused so that it is not used for dep-file comparison, and an argfile
+        # that uses placeholders instead of content-based paths, which is not tagged for dep-files
+        # and therefore causes a dep-file miss if it changes.
+        argsfile, _ = ctx.actions.write(".{}_argsfile".format(category), shell_quoted_args, allow_args = True, has_content_based_path = uses_content_based_paths)
+        placeholder_argsfile, _ = ctx.actions.write(
+            ".{}_argsfile_placeholder".format(category),
+            shell_quoted_args,
+            allow_args = True,
+            use_dep_files_placeholder_for_content_based_paths = True,
+            has_content_based_path = uses_content_based_paths,
+        )
+        cmd.add(cmd_args(hidden = placeholder_argsfile))
+        argsfile_cmd_form = cmd_args(artifact_tag.tag_artifacts(argsfile), format = "@{}", delimiter = "", hidden = shared_flags)
+    else:
+        argsfile, _ = ctx.actions.write(".{}_argsfile".format(category), shell_quoted_args, allow_args = True, has_content_based_path = uses_content_based_paths)
+        argsfile_cmd_form = cmd_args(argsfile, format = "@{}", delimiter = "", hidden = shared_flags)
+    cmd.add(argsfile_cmd_form)
+
+    # Assemble argsfile with Swift source files.
+    if srcs:
+        swift_quoted_files = cmd_args([s.file for s in srcs], quote = "shell")
+
+        # This path needs to be kept in sync with the _SWIFT_FILES_ARGSFILE
+        # variable in swift_exec.py.
+        swift_files, _ = ctx.actions.write(
+            ".{}_swift_srcs".format(category), swift_quoted_files, allow_args = True, has_content_based_path = uses_content_based_paths
+        )
+        swift_files_cmd_form = cmd_args(swift_files, format = "@{}", delimiter = "", hidden = swift_quoted_files)
+        cmd.add(swift_files_cmd_form)
+
+    # If the toolchain supports serialized error output, add the output files
+    # to deserialize the errors. This uses the output file map if supported,
+    # otherwise will pass frontend flags.
+    error_deserializer = swift_error_deserializer(ctx)
+    error_outputs = []
+
+    if supports_serialized_errors and error_deserializer:
+        json_error_output = ctx.actions.declare_output("__diagnostics__/{}.json".format(category), has_content_based_path = uses_content_based_paths).as_output()
+        error_outputs.append(json_error_output)
+        is_incremental = incremental_artifacts != None
+        add_serialized_diagnostics_output(
+            ctx = ctx,
+            output_file_map = output_file_map if supports_output_file_map else None,
+            cmd = cmd,
+            diagnostics_output = json_error_output,
+            is_incremental = is_incremental,
+            skip_incremental_outputs = skip_incremental_outputs,
+            split_actions = get_incremental_split_actions(ctx),
+        )
+        cmd.add(
+            "-Xwrapper",
+            cmd_args(error_deserializer, format = "-serialized-diagnostics-to-json={}"),
+            "-Xwrapper",
+            cmd_args(json_error_output, format = "-json-error-output-path={}"),
+        )
+        if incremental_remote_outputs and should_build_swift_incrementally(ctx) and not skip_incremental_outputs:
+            # Serialized diagnostics in Swift incremental mode will produce a
+            # .dia output for each .o output. These need to be made writable.
+            for obj in objects:
+                name_without_extension, _ = paths.split_extension(obj.short_path)
+                diag_output = ctx.actions.declare_output("{}.dia".format(name_without_extension), has_content_based_path = uses_content_based_paths)
+                cmd.add(cmd_args(hidden = diag_output.as_output()))
+                writable_incremental_args.append(diag_output.as_output())
+
+    # If an output file map is provided, serialize it and add to the command.
+    if output_file_map:
+        if not supports_output_file_map:
+            fail("Output file maps are not supported for {}".format(category))
+        output_file_map_artifact = add_output_file_map_flags(ctx, output_file_map, cmd, category)
+    else:
+        output_file_map_artifact = None
+
+    if writable_incremental_args and incremental_remote_outputs:
+        cmd.add(["-Xwrapper", "--writable-incremental-paths"])
+        for flag in writable_incremental_args:
+            cmd.add(["-Xwrapper", flag])
+
+    return CompileWithArgsFileCmdOutput(
+        cmd = cmd,
+        argsfile = argsfile,
+        argsfile_cmd_form = argsfile_cmd_form,
+        shell_quoted_args = shell_quoted_args,
+        error_outputs = error_outputs,
+        output_file_map_artifact = output_file_map_artifact,
+        error_deserializer = error_deserializer,
+    )
+
+def compile_with_argsfile(
+    ctx: AnalysisContext,
+    category: str,
+    shared_flags: cmd_args,
+    srcs: list[CxxSrcWithFlags],
+    additional_flags: cmd_args,
+    toolchain: SwiftToolchainInfo,
+    num_threads: int = 1,
+    dep_files: dict[str, ArtifactTag] = {},
+    output_file_map: dict = {},
+    allow_cache_upload = False,
+    local_only = False,
+    prefer_local = False,
+    no_outputs_cleanup = False,
+    supports_output_file_map = True,
+    supports_serialized_errors = True,
+    skip_incremental_outputs = False,
+    incremental_remote_outputs = False,
+    objects = [],
+    incremental_artifacts: IncrementalCompilationInput | None = None,
+    artifact_tag: ArtifactTag | None = None,
+) -> (CompileArgsfile, Artifact | None):
+    cmd_output = compile_with_argsfile_cmd(
+        ctx = ctx,
+        category = category,
+        shared_flags = shared_flags,
+        srcs = srcs,
+        additional_flags = additional_flags,
+        toolchain = toolchain,
+        output_file_map = output_file_map,
+        supports_output_file_map = supports_output_file_map,
+        supports_serialized_errors = supports_serialized_errors,
+        skip_incremental_outputs = skip_incremental_outputs,
+        incremental_remote_outputs = incremental_remote_outputs,
+        objects = objects,
+        incremental_artifacts = incremental_artifacts,
+        artifact_tag = artifact_tag,
+    )
+
+    # TODO(xcshen): Re-enable when content-based paths for PCMs no longer
+    # leak into .swiftmodule files, breaking @_implementationOnly blast radius.
+    expect_eligible_for_dedupe = False  # _get_should_expect_eligible_for_dedupe(ctx, category)
+    if toolchain.prioritize_swift_critical_path and _is_swift_object_category(category):
+        # Empirically tuned to preserve local capacity for prioritized swiftmodule
+        # emits. Re-benchmark builds before changing.
+        weight = num_threads * 4
+    else:
+        weight = num_threads
+    ctx.actions.run(
+        cmd_output.cmd,
+        allow_cache_upload = allow_cache_upload,
+        allow_dep_file_cache_upload = (len(dep_files) > 0),
+        category = category,
+        dep_files = dep_files,
+        error_handler = swift_error_handler if cmd_output.error_deserializer else apple_build_error_handler,
+        local_only = local_only,
+        low_pass_filter = _low_pass_filter_for_category(category, toolchain.prioritize_swift_critical_path),
+        no_outputs_cleanup = no_outputs_cleanup,
+        incremental_remote_outputs = incremental_remote_outputs,
+        outputs_for_error_handler = cmd_output.error_outputs,
+        prefer_local = _prefer_local_for_category(category, toolchain.prioritize_swift_critical_path, local_only, prefer_local),
+        unique_input_inodes = True,
+        weight = weight,
+        expect_eligible_for_dedupe = expect_eligible_for_dedupe,
+    )
+
+    argsfile = CompileArgsfile(
+        file = cmd_output.argsfile,
+        cmd_form = cmd_output.argsfile_cmd_form,
+        args = cmd_output.shell_quoted_args,
+        args_without_file_prefix_args = shared_flags,
+    )
+
+    return argsfile, cmd_output.output_file_map_artifact
+
+def uses_explicit_modules(ctx: AnalysisContext) -> bool:
+    swift_toolchain = get_swift_toolchain_info(ctx)
+    return ctx.attrs.uses_explicit_modules and is_sdk_modules_provided(swift_toolchain)
diff --git a/buck2/prelude/apple/swift/swift_incremental_support.bzl b/buck2/prelude/apple/swift/swift_incremental_support.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_incremental_support.bzl
@@ -0,0 +1,380 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftObjectFormat")
+load("@prelude//apple/swift:swift_types.bzl", "SwiftCompilationModes")
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",  # @unused Used as a type
+)
+load(":swift_toolchain.bzl", "get_swift_toolchain_info", "include_path_for_relative_module_map_paths")
+
+_OutputFileMapData = record(
+    artifacts = field(list[Artifact]),
+    outputs = field(list[Artifact]),
+    output_file_map = field(dict),
+    swiftdeps = field(list[Artifact]),
+    depfiles = field(list[Artifact]),
+)
+
+IncrementalCompilationOutput = record(
+    artifacts = field(list[Artifact]),
+    incremental_flags_cmd = field(cmd_args),
+    num_threads = field(int),
+    output_file_map = field(dict),
+    skip_incremental_outputs = field(bool),
+    incremental_remote_outputs = field(bool),
+    swiftdeps = field(list[Artifact]),
+    depfiles = field(list[Artifact]),
+    swiftdoc = field(Artifact | None),
+)
+
+IncrementalCompilationInput = record(
+    swiftdeps = field(list[Artifact]),
+    depfiles = field(list[Artifact]),
+    swiftdoc = field(Artifact | None),
+)
+
+SwiftmoduleIncrementalCompilationOutput = record(
+    # Driver flags specific to the incremental swiftmodule action. The caller
+    # composes this with the shared emit-module / emit-objc-header / include-
+    # path / skip-function-bodies flags it built itself.
+    incremental_flags_cmd = field(cmd_args),
+    output_file_map = field(dict),
+    skip_incremental_outputs = field(bool),
+    swiftdeps = field(list[Artifact]),
+    depfiles = field(list[Artifact]),
+)
+
+SwiftCompilationMode = enum(*SwiftCompilationModes)
+
+# The maxmium number of threads, we don't use
+# host_info to prevent cache misses across
+# different hardware models.
+INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS = 6
+
+# This is the default, but specifying it explicitly
+# is clearer.
+INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE = 25
+
+def should_build_swift_incrementally(ctx: AnalysisContext) -> bool:
+    toolchain = get_swift_toolchain_info(ctx)
+
+    # Incremental builds are only supported when object files are generated.
+    if toolchain.object_format != SwiftObjectFormat("object"):
+        return False
+
+    return SwiftCompilationMode(ctx.attrs.swift_compilation_mode) == SwiftCompilationMode("incremental")
+
+def get_incremental_object_compilation_flags(
+    ctx: AnalysisContext, srcs: list[CxxSrcWithFlags], output_swiftmodule: Artifact, output_swiftdoc: Artifact | None, output_header: Artifact
+) -> IncrementalCompilationOutput:
+    output_file_map_data = _get_output_file_map(ctx, srcs)
+    return _get_incremental_compilation_flags_and_objects(
+        ctx,
+        output_file_map_data,
+        output_swiftmodule,
+        output_swiftdoc,
+        output_header,
+        len(srcs),
+    )
+
+def get_incremental_swiftmodule_compilation_flags(ctx: AnalysisContext, srcs: list[CxxSrcWithFlags]) -> SwiftmoduleIncrementalCompilationOutput:
+    """Returns the incremental-driver-only flags + per-target incremental
+    state (output file map, swiftdeps) for the incremental swiftmodule
+    action. The shared emit-module / emit-objc-header / include-path /
+    skip-function-bodies flags are intentionally NOT included here — the
+    caller (\`_compile_swiftmodule\`) builds them once and shares them with
+    the WMO path.
+    """
+    output_file_map_data = _get_swiftmodule_output_file_map(ctx, srcs)
+
+    # The emit-module-separately job is a single driver task, so we don't
+    # pass `-j` or `-driver-batch-size-limit` — the driver picks defaults.
+    cmd = cmd_args(
+        [
+            "-enable-batch-mode",
+            "-enable-incremental-imports",
+            "-experimental-emit-module-separately",
+            "-incremental",
+        ],
+        hidden = [output.as_output() for output in output_file_map_data.outputs],
+    )
+
+    skip_incremental_outputs = _get_skip_swift_incremental_outputs(ctx)
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+    if get_swift_incremental_logging_enabled(ctx):
+        cmd.add([
+            "-driver-show-incremental",
+            "-driver-show-job-lifecycle",
+        ])
+
+    if skip_incremental_outputs:
+        # When skipping incremental outputs, we write the contents of the
+        # output_file_map in the swift wrapper and need to ensure this is
+        # an output file (vs being an input in normal cases)
+        output_map_artifact = ctx.actions.declare_output("__swift_module_incremental__/output_file_map.json", has_content_based_path = uses_content_based_paths)
+        cmd.add(
+            "-Xwrapper",
+            "-skip-incremental-outputs",
+            "-output-file-map",
+            output_map_artifact.as_output(),
+        )
+    elif get_incremental_file_hashing_enabled(ctx):
+        cmd.add(
+            "-enable-incremental-file-hashing",
+            "-avoid-emit-module-source-info",
+        )
+    if get_incremental_remote_outputs_enabled(ctx):
+        cmd.add(
+            "-Xwrapper",
+            "--no-file-prefix-map",
+            "-dwarf-version=5",
+            "-Xcc",
+            "-working-directory",
+            "-Xcc",
+            ".",
+        )
+
+    return SwiftmoduleIncrementalCompilationOutput(
+        incremental_flags_cmd = cmd,
+        output_file_map = output_file_map_data.output_file_map,
+        skip_incremental_outputs = skip_incremental_outputs,
+        swiftdeps = output_file_map_data.swiftdeps,
+        depfiles = output_file_map_data.depfiles,
+    )
+
+def _get_incremental_num_threads(num_srcs: int) -> int:
+    if num_srcs == 0:
+        return 1
+
+    src_threads = (num_srcs + INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE - 1) // INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE
+    return min(INCREMENTAL_SWIFT_COMPILE_MAX_NUM_THREADS, src_threads)
+
+def _get_skip_swift_incremental_outputs(ctx: AnalysisContext):
+    return getattr(ctx.attrs, "_skip_swift_incremental_outputs", False)
+
+def get_incremental_file_hashing_enabled(ctx: AnalysisContext):
+    toolchain = get_swift_toolchain_info(ctx)
+    return toolchain.supports_incremental_file_hashing and getattr(ctx.attrs, "swift_incremental_file_hashing", False) and should_build_swift_incrementally(ctx)
+
+def get_swift_incremental_logging_enabled(ctx: AnalysisContext):
+    return getattr(ctx.attrs, "swift_incremental_logging", False)
+
+def get_incremental_split_actions(ctx: AnalysisContext):
+    return getattr(ctx.attrs, "_swift_incremental_split_actions", False)
+
+def get_incremental_swiftmodule_action(ctx: AnalysisContext):
+    return getattr(ctx.attrs, "_swift_incremental_swiftmodule_action", False)
+
+def should_build_swiftmodule_incrementally(ctx: AnalysisContext) -> bool:
+    # The new incremental swiftmodule action requires:
+    #  * Swift built incrementally
+    #  * Split actions on (the object action is what we split from)
+    #  * The new opt-in attribute on
+    return should_build_swift_incrementally(ctx) and get_incremental_split_actions(ctx) and get_incremental_swiftmodule_action(ctx)
+
+def get_incremental_remote_outputs_enabled(ctx: AnalysisContext):
+    return getattr(ctx.attrs, "incremental_remote_outputs", False)
+
+def get_uses_content_based_paths(ctx):
+    if getattr(ctx.attrs, "has_content_based_path", None) != None:
+        return ctx.attrs.has_content_based_path
+
+    toolchain = get_swift_toolchain_info(ctx)
+    return toolchain.uses_content_based_paths
+
+def _get_incremental_compilation_flags_and_objects(
+    ctx: AnalysisContext,
+    output_file_map_data: _OutputFileMapData,
+    output_swiftmodule: Artifact,
+    output_swiftdoc: Artifact | None,
+    output_header: Artifact,
+    num_srcs: int,
+) -> IncrementalCompilationOutput:
+    extra_hidden = [output_swiftdoc.as_output()] if output_swiftdoc else []
+
+    # Match the driver -j to the Buck `weight` (num_threads) so the frontend-thread count matches
+    # the permits Buck reserves. Otherwise -j was always 6 while weight could be 1, oversubscribing
+    # up to ~6x and under-counting CPU in the (weight-based) low-pass-filter capacity.
+    num_threads = _get_incremental_num_threads(num_srcs)
+    cmd = cmd_args(
+        [
+            "-disable-cmo",
+            "-emit-object",
+            "-enable-batch-mode",
+            "-enable-incremental-imports",
+            "-experimental-emit-module-separately",
+            "-incremental",
+            "-j",
+            str(num_threads),
+            "-driver-batch-size-limit",
+            str(INCREMENTAL_SWIFT_COMPILE_BATCH_SIZE),
+        ],
+        hidden = [output.as_output() for output in output_file_map_data.outputs] + extra_hidden,
+    )
+    cmd.add(include_path_for_relative_module_map_paths(ctx))
+
+    if not get_incremental_split_actions(ctx):
+        cmd.add(
+            [
+                "-emit-objc-header",
+                "-emit-objc-header-path",
+                output_header.as_output(),
+                "-emit-module",
+                "-emit-module-path",
+                output_swiftmodule.as_output(),
+            ],
+        )
+
+    skip_incremental_outputs = _get_skip_swift_incremental_outputs(ctx)
+    incremental_remote_outputs = False
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+    if get_swift_incremental_logging_enabled(ctx):
+        cmd.add([
+            "-driver-show-incremental",
+            "-driver-show-job-lifecycle",
+        ])
+
+    if skip_incremental_outputs:
+        # When skipping incremental outputs, we write the contents of the
+        # output_file_map in the swift wrapper and need to ensure this is
+        # an output file (vs being an input in normal cases)
+        output_map_artifact = ctx.actions.declare_output("__swift_incremental__/output_file_map.json", has_content_based_path = uses_content_based_paths)
+        cmd.add(
+            "-Xwrapper",
+            "-skip-incremental-outputs",
+            "-output-file-map",
+            output_map_artifact.as_output(),
+        )
+    elif get_incremental_file_hashing_enabled(ctx):
+        cmd.add(
+            "-enable-incremental-file-hashing",
+            "-avoid-emit-module-source-info",
+        )
+    if get_incremental_remote_outputs_enabled(ctx):
+        incremental_remote_outputs = True
+        cmd.add(
+            "-Xwrapper",
+            "--no-file-prefix-map",
+            "-dwarf-version=5",
+            "-Xcc",
+            "-working-directory",
+            "-Xcc",
+            ".",
+        )
+
+    return IncrementalCompilationOutput(
+        artifacts = output_file_map_data.artifacts,
+        incremental_flags_cmd = cmd,
+        num_threads = num_threads,
+        output_file_map = output_file_map_data.output_file_map,
+        skip_incremental_outputs = skip_incremental_outputs,
+        swiftdeps = output_file_map_data.swiftdeps,
+        depfiles = output_file_map_data.depfiles,
+        incremental_remote_outputs = incremental_remote_outputs,
+        swiftdoc = output_swiftdoc,
+    )
+
+def _get_output_file_map(ctx: AnalysisContext, srcs: list[CxxSrcWithFlags]) -> _OutputFileMapData:
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+    if _get_skip_swift_incremental_outputs(ctx):
+        all_outputs = []
+        swiftdeps = []
+        artifacts = []
+        depfiles = []
+        output_file_map = {}
+
+        for src in srcs:
+            file_name = src.file.basename
+            output_artifact = ctx.actions.declare_output("__swift_incremental__/objects/" + file_name + ".o", has_content_based_path = uses_content_based_paths)
+            artifacts.append(output_artifact)
+            all_outputs.append(output_artifact)
+    else:
+        # swift-driver doesn't respect extension for root swiftdeps file and it always has to be `.priors`.
+        module_swiftdeps = ctx.actions.declare_output(
+            "__swift_incremental__/swiftdeps/module-build-record.priors", has_content_based_path = uses_content_based_paths
+        )
+        output_file_map = {
+            "": {
+                "swift-dependencies": module_swiftdeps,
+            },
+        }
+        all_outputs = [module_swiftdeps]
+        swiftdeps = [module_swiftdeps]
+        artifacts = []
+        depfiles = []
+        toolchain = get_swift_toolchain_info(ctx)
+
+        for src in srcs:
+            file_name = src.file.basename
+            output_artifact = ctx.actions.declare_output("__swift_incremental__/objects/" + file_name + ".o", has_content_based_path = uses_content_based_paths)
+            artifacts.append(output_artifact)
+            all_outputs.append(output_artifact)
+            swiftdeps_artifact = ctx.actions.declare_output(
+                "__swift_incremental__/swiftdeps/" + file_name + ".swiftdeps", has_content_based_path = uses_content_based_paths
+            )
+            output_file_map[src.file] = {
+                "object": output_artifact,
+                "swift-dependencies": swiftdeps_artifact,
+            }
+            swiftdeps.append(swiftdeps_artifact)
+            all_outputs.append(swiftdeps_artifact)
+            if toolchain.use_depsfiles and not get_incremental_file_hashing_enabled(ctx):
+                deps_artifact = ctx.actions.declare_output("__swift_incremental__/objects/" + file_name + ".d", has_content_based_path = uses_content_based_paths)
+                depfiles.append(deps_artifact)
+                all_outputs.append(deps_artifact)
+
+    return _OutputFileMapData(
+        artifacts = artifacts,
+        outputs = all_outputs,
+        output_file_map = output_file_map,
+        swiftdeps = swiftdeps,
+        depfiles = depfiles,
+    )
+
+def _get_swiftmodule_output_file_map(ctx: AnalysisContext, srcs: list[CxxSrcWithFlags]) -> _OutputFileMapData:
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+    if _get_skip_swift_incremental_outputs(ctx):
+        return _OutputFileMapData(
+            artifacts = [],
+            outputs = [],
+            output_file_map = {},
+            swiftdeps = [],
+            depfiles = [],
+        )
+
+    module_swiftdeps = ctx.actions.declare_output(
+        "__swift_module_incremental__/swiftdeps/module-build-record.priors", has_content_based_path = uses_content_based_paths
+    )
+    output_file_map = {
+        "": {
+            "swift-dependencies": module_swiftdeps,
+        },
+    }
+
+    # For incremental swiftmodule generation, we need to capture the set of
+    # incremental output files they produce.
+    per_source_dir = ctx.actions.declare_output(
+        "__swift_module_incremental__/per_source_incremental", dir = True, has_content_based_path = uses_content_based_paths
+    )
+    for src in srcs:
+        file_name = src.file.basename
+        output_file_map[src.file] = {
+            "diagnostics": cmd_args(per_source_dir, format = "{}/" + file_name + ".dia", delimiter = ""),
+            "swift-dependencies": cmd_args(per_source_dir, format = "{}/" + file_name + ".swiftdeps", delimiter = ""),
+            "swiftmodule": cmd_args(per_source_dir, format = "{}/" + file_name + ".swiftmodule", delimiter = ""),
+        }
+
+    return _OutputFileMapData(
+        artifacts = [],
+        outputs = [module_swiftdeps, per_source_dir],
+        output_file_map = output_file_map,
+        swiftdeps = [module_swiftdeps, per_source_dir],
+        depfiles = [],
+    )
diff --git a/buck2/prelude/apple/swift/swift_module_map.bzl b/buck2/prelude/apple/swift/swift_module_map.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_module_map.bzl
@@ -0,0 +1,52 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+load(
+    ":swift_incremental_support.bzl",
+    "get_uses_content_based_paths",
+)
+load(":swift_toolchain_types.bzl", "SwiftCompiledModuleTset")
+
+def write_swift_module_map_with_deps(ctx: AnalysisContext, module_name: str, all_deps: SwiftCompiledModuleTset) -> (Artifact, ArgLike):
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+    artifact = ctx.actions.declare_output(
+        module_name + ".swift_module_map.json",
+        has_content_based_path = uses_content_based_paths,
+    )
+    args = ctx.actions.write_json(
+        artifact.as_output(),
+        all_deps.project_as_json("swift_module_map"),
+        pretty = True,
+        with_inputs = True,
+    )
+
+    # There are cases where we can see duplicate entries in the modulemaps.
+    # This happens when there's different execution platforms across
+    # `apple_library()` targets. For more info, see `get_swift_interface_anon_targets()`.
+    deduplicated_artifact = ctx.actions.declare_output(
+        module_name + ".deduplicated.swift_module_map.json",
+        has_content_based_path = uses_content_based_paths,
+    )
+    ctx.actions.run(
+        cmd_args(
+            ctx.attrs._apple_tools[AppleToolsInfo].dedupe_swift_module_map,
+            "--input",
+            artifact,
+            "--output",
+            deduplicated_artifact.as_output(),
+        ),
+        category = "swift_module_map_dedupe",
+        identifier = module_name,
+    )
+
+    # The de-duplicated map holds the same module artifact paths as the original,
+    # so carry those inputs along for downstream consumers to materialize.
+    deduplicated_args = cmd_args(deduplicated_artifact, hidden = args)
+    return (deduplicated_artifact, deduplicated_args)
diff --git a/buck2/prelude/apple/swift/swift_output_file_map.bzl b/buck2/prelude/apple/swift/swift_output_file_map.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_output_file_map.bzl
@@ -0,0 +1,95 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_utility.bzl", "get_module_name")
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",  # @unused Used as a type
+)
+load(
+    ":swift_incremental_support.bzl",
+    "get_uses_content_based_paths",
+)
+
+def add_dependencies_output(ctx: AnalysisContext, output_file_map: dict, cmd: cmd_args, category: str, inputs_tag: ArtifactTag) -> None:
+    # Add a Makefile style dependency file output. This output is not tracked,
+    # we need to process it first.
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+    buck_dep_file = ctx.actions.declare_output(
+        "__depfiles__/{}-{}.d".format(ctx.attrs.name, category), has_content_based_path = uses_content_based_paths
+    ).as_output()
+    map = output_file_map.setdefault("", {})
+    map["dependencies"] = cmd_args(buck_dep_file, delimiter = "", format = "{}.raw")
+    map["emit-module-dependencies"] = cmd_args(buck_dep_file, delimiter = "", format = "{}.raw")
+    cmd.add("-emit-dependencies")
+
+    # Add the flags for the wrapper to process the dependency file to Buck format.
+    cmd.add(
+        "-Xwrapper",
+        cmd_args(inputs_tag.tag_artifacts(buck_dep_file), format = "-dependencies-file-output={}"),
+    )
+
+def add_serialized_diagnostics_output(
+    ctx: AnalysisContext,
+    output_file_map: dict | None,
+    cmd: cmd_args,
+    diagnostics_output: OutputArtifact,
+    is_incremental: bool = False,
+    split_actions: bool = False,
+    skip_incremental_outputs: bool = False,
+) -> None:
+    if output_file_map == None:
+        # Some actions, eg -emit-pcm, do not support output file maps. In this
+        # case we need to pass the frontend flags directly.
+        cmd.add(
+            "-Xfrontend",
+            cmd_args(diagnostics_output, format = "-serialize-diagnostics-path={}.dia"),
+        )
+    else:
+        map = output_file_map.setdefault("", {})
+        map["diagnostics"] = cmd_args(diagnostics_output, delimiter = "", format = "{}.dia")
+        cmd.add(cmd_args("-serialize-diagnostics", hidden = [diagnostics_output]))
+
+        if is_incremental and not skip_incremental_outputs and not split_actions:
+            uses_content_based_paths = get_uses_content_based_paths(ctx)
+            module_name = get_module_name(ctx)
+            module_dia = ctx.actions.declare_output(
+                "__swift_incremental__/swiftdeps/" + module_name + ".emit-module.dia", has_content_based_path = uses_content_based_paths
+            )
+            map["emit-module-diagnostics"] = module_dia
+            cmd.add(cmd_args(hidden = [module_dia.as_output()]))
+
+def add_output_file_map_flags(ctx: AnalysisContext, output_file_map: dict, cmd: cmd_args, category: str) -> Artifact:
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+    output_file_map_json = ctx.actions.write_json(
+        "{}_output_file_map.json".format(category),
+        output_file_map,
+        pretty = True,
+        has_content_based_path = uses_content_based_paths,
+    )
+    cmd.add("-output-file-map", output_file_map_json)
+    return output_file_map_json
+
+def get_modularization_dependency_graph_output_map(ctx: AnalysisContext, srcs: list[CxxSrcWithFlags]):
+    output_file_map = {}
+    output_modularization_dependency_graph_shards = []
+    output_objects = []
+    for src in srcs:
+        file_name = src.file.basename
+        object_file_artifact = ctx.actions.declare_output("__swift_modularization___/objects/" + file_name + ".o", has_content_based_path = False)
+        modularization_dependency_graph_artifact = ctx.actions.declare_output(
+            "__swift_modularization___/dependency_graphs/" + file_name + ".modularizationdependencygraph", has_content_based_path = False
+        )
+        output_file_map[src.file] = {
+            "modularization-dependency-graph": modularization_dependency_graph_artifact,
+            "object": object_file_artifact,
+        }
+        output_objects.append(object_file_artifact)
+        output_modularization_dependency_graph_shards.append(modularization_dependency_graph_artifact)
+
+    return output_file_map, output_objects, output_modularization_dependency_graph_shards
diff --git a/buck2/prelude/apple/swift/swift_pcm_compilation.bzl b/buck2/prelude/apple/swift/swift_pcm_compilation.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_pcm_compilation.bzl
@@ -0,0 +1,290 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple/swift:swift_helpers.bzl", "compile_with_argsfile")
+load(
+    ":apple_sdk_modules_utility.bzl",
+    "get_compiled_sdk_clang_deps_tset",
+    "get_uncompiled_sdk_deps",
+)
+load(
+    ":swift_debug_info_utils.bzl",
+    "extract_and_merge_clang_debug_infos",
+)
+load(":swift_pcm_compilation_types.bzl", "SwiftPCMUncompiledInfo", "WrappedSwiftPCMCompiledInfo")
+load(":swift_sdk_flags.bzl", "get_sdk_flags")
+load(":swift_sdk_pcm_compilation.bzl", "get_shared_pcm_compilation_args", "get_swift_sdk_pcm_anon_targets")
+load(":swift_toolchain.bzl", "get_swift_toolchain_info", "get_swift_toolchain_info_dep")
+load(":swift_toolchain_types.bzl", "SwiftCompiledModuleInfo", "SwiftCompiledModuleTset", "SwiftToolchainInfo", "WrappedSdkCompiledModuleInfo")
+
+_REQUIRED_SDK_MODULES = ["Foundation"]
+
+_REQUIRED_SDK_CXX_MODULES = _REQUIRED_SDK_MODULES + ["std"]
+
+def get_compiled_pcm_deps_tset(ctx: AnalysisContext, pcm_deps_providers: list) -> SwiftCompiledModuleTset:
+    pcm_deps = [
+        pcm_deps_provider[WrappedSwiftPCMCompiledInfo].clang_deps
+        for pcm_deps_provider in pcm_deps_providers
+        if WrappedSwiftPCMCompiledInfo in pcm_deps_provider
+    ]
+    return ctx.actions.tset(SwiftCompiledModuleTset, children = pcm_deps)
+
+def get_swift_pcm_anon_targets(ctx: AnalysisContext, uncompiled_deps: list[Dependency], swift_cxx_args: list[str], enable_cxx_interop: bool):
+    deps = []
+    for uncompiled_dep in uncompiled_deps:
+        if SwiftPCMUncompiledInfo not in uncompiled_dep:
+            continue
+
+        # T209485965: workaround for depagg to avoid duplicate clang modules
+        # when traversing deps through the base target and [headers] subtarget.
+        # By always requesting the [headers] subtarget we should use the same
+        # anon actions for both paths.
+        if "headers" in uncompiled_dep[DefaultInfo].sub_targets:
+            uncompiled_dep = uncompiled_dep.sub_target("headers")
+
+        deps.append(
+            (
+                _swift_pcm_compilation,
+                {
+                    "dep": uncompiled_dep,
+                    "enable_cxx_interop": enable_cxx_interop,
+                    "has_content_based_path": False,
+                    "name": uncompiled_dep.label,
+                    "swift_cxx_args": swift_cxx_args,
+                    "_swift_toolchain": get_swift_toolchain_info_dep(ctx),
+                },
+            )
+        )
+
+    return deps
+
+def _compiled_module_info(module_name: str, pcm_output: Artifact, pcm_info: SwiftPCMUncompiledInfo) -> SwiftCompiledModuleInfo:
+    return SwiftCompiledModuleInfo(
+        clang_importer_args = pcm_info.exported_clang_importer_args,
+        clang_modulemap_path = cmd_args(pcm_info.modulemap_artifact),
+        is_framework = False,
+        is_sdk_module = False,
+        is_swiftmodule = False,
+        module_name = module_name,
+        output_artifact = pcm_output,
+    )
+
+def _swift_pcm_compilation_impl(ctx: AnalysisContext) -> [Promise, list[Provider]]:
+    def k(compiled_pcm_deps_providers) -> list[Provider]:
+        uncompiled_pcm_info = ctx.attrs.dep[SwiftPCMUncompiledInfo]
+
+        # `compiled_pcm_deps_providers` will contain `WrappedSdkCompiledModuleInfo` providers
+        # from direct SDK deps and transitive deps that export sdk deps.
+        sdk_deps_tset = get_compiled_sdk_clang_deps_tset(ctx, compiled_pcm_deps_providers)
+
+        # To compile a pcm we only use the exported_deps as those are the only
+        # ones that should be transitively exported through public headers
+        pcm_deps_tset = get_compiled_pcm_deps_tset(ctx, compiled_pcm_deps_providers)
+
+        # We don't need to compile non-modular or targets that do not export any headers,
+        # but for the sake of BUCK1 compatibility, we need to pass them up,
+        # in case they re-export some dependencies.
+        if uncompiled_pcm_info.is_transient:
+            return [
+                DefaultInfo(),
+                WrappedSwiftPCMCompiledInfo(
+                    clang_deps = pcm_deps_tset,
+                    clang_debug_info = extract_and_merge_clang_debug_infos(ctx, compiled_pcm_deps_providers),
+                ),
+                WrappedSdkCompiledModuleInfo(
+                    clang_deps = sdk_deps_tset,
+                    clang_debug_info = extract_and_merge_clang_debug_infos(ctx, compiled_pcm_deps_providers),
+                ),
+            ]
+
+        module_name = uncompiled_pcm_info.name
+        swift_toolchain_info = ctx.attrs._swift_toolchain[SwiftToolchainInfo]
+        cmd, additional_cmd, pcm_output = _get_base_pcm_flags(
+            ctx,
+            module_name,
+            swift_toolchain_info,
+            uncompiled_pcm_info,
+            sdk_deps_tset,
+            pcm_deps_tset,
+            ctx.attrs.swift_cxx_args,
+        )
+
+        compile_with_argsfile(
+            ctx,
+            category = "swift_pcm_compile",
+            shared_flags = cmd,
+            srcs = [],
+            additional_flags = additional_cmd,
+            toolchain = swift_toolchain_info,
+            supports_output_file_map = False,
+        )
+        pcm_info = _compiled_module_info(module_name, pcm_output, uncompiled_pcm_info)
+        debug_artifacts = [
+            pcm_info.output_artifact,
+            uncompiled_pcm_info.modulemap_artifact,
+        ]
+
+        return [
+            DefaultInfo(default_outputs = [pcm_output]),
+            WrappedSwiftPCMCompiledInfo(
+                clang_deps = ctx.actions.tset(SwiftCompiledModuleTset, value = pcm_info, children = [pcm_deps_tset]),
+                clang_debug_info = extract_and_merge_clang_debug_infos(ctx, compiled_pcm_deps_providers, debug_artifacts),
+            ),
+            WrappedSdkCompiledModuleInfo(
+                clang_deps = sdk_deps_tset,
+                # No need to further propagate debug info, it will be included
+                # in WrappedSwiftPCMCompiledInfo.
+            ),
+        ]
+
+    required_sdk_modules = _REQUIRED_SDK_CXX_MODULES if ctx.attrs.enable_cxx_interop else _REQUIRED_SDK_MODULES
+    direct_uncompiled_sdk_deps = get_uncompiled_sdk_deps(
+        ctx.attrs.dep[SwiftPCMUncompiledInfo].uncompiled_sdk_modules,
+        required_sdk_modules,
+        ctx.attrs._swift_toolchain[SwiftToolchainInfo],
+    )
+
+    # Recursively compiling SDK's Clang dependencies
+    sdk_pcm_deps_anon_targets = get_swift_sdk_pcm_anon_targets(
+        ctx,
+        ctx.attrs.enable_cxx_interop,
+        direct_uncompiled_sdk_deps,
+        ctx.attrs.swift_cxx_args,
+    )
+
+    # Recursively compile PCMs of transitevely visible exported_deps
+    swift_pcm_anon_targets = get_swift_pcm_anon_targets(
+        ctx,
+        ctx.attrs.dep[SwiftPCMUncompiledInfo].exported_deps,
+        ctx.attrs.swift_cxx_args,
+        ctx.attrs.enable_cxx_interop,
+    )
+    return ctx.actions.anon_targets(sdk_pcm_deps_anon_targets + swift_pcm_anon_targets).promise.map(k)
+
+_swift_pcm_compilation = rule(
+    impl = _swift_pcm_compilation_impl,
+    attrs = {
+        "dep": attrs.dep(),
+        "enable_cxx_interop": attrs.bool(),
+        "has_content_based_path": attrs.bool(),
+        "swift_cxx_args": attrs.list(attrs.string(), default = []),
+        "_swift_toolchain": attrs.dep(),
+    },
+)
+
+def _compile_pcm(
+    ctx: AnalysisContext,
+    action_name: str,
+    module_name: str,
+    uncompiled_pcm_info: SwiftPCMUncompiledInfo,
+    compiled_pcm_deps_providers,
+    swift_cxx_args: list[str],
+    additional_args: cmd_args,
+) -> SwiftCompiledModuleInfo:
+    # `compiled_pcm_deps_providers` will contain `WrappedSdkCompiledModuleInfo` providers
+    # from direct SDK deps and transitive deps that export sdk deps.
+    sdk_deps_tset = get_compiled_sdk_clang_deps_tset(ctx, compiled_pcm_deps_providers)
+
+    # To compile a pcm we only use the exported_deps as those are the only
+    # ones that should be transitively exported through public headers
+    pcm_deps_tset = get_compiled_pcm_deps_tset(ctx, compiled_pcm_deps_providers)
+
+    swift_toolchain_info = get_swift_toolchain_info(ctx)
+    cmd, additional_cmd, pcm_output = _get_base_pcm_flags(
+        ctx,
+        module_name,
+        swift_toolchain_info,
+        uncompiled_pcm_info,
+        sdk_deps_tset,
+        pcm_deps_tset,
+        swift_cxx_args,
+    )
+    cmd.add(additional_args)
+    compile_with_argsfile(
+        ctx,
+        category = action_name,
+        shared_flags = cmd,
+        srcs = [],
+        additional_flags = additional_cmd,
+        toolchain = swift_toolchain_info,
+        supports_output_file_map = False,
+    )
+    return _compiled_module_info(module_name, pcm_output, uncompiled_pcm_info)
+
+def compile_framework_pcm(
+    ctx: AnalysisContext, module_name: str, uncompiled_pcm_info: SwiftPCMUncompiledInfo, compiled_pcm_deps_providers, swift_cxx_args: list[str]
+) -> SwiftCompiledModuleInfo:
+    return _compile_pcm(
+        ctx,
+        "swift_prebuilt_framework_pcm_compile",
+        module_name,
+        uncompiled_pcm_info,
+        compiled_pcm_deps_providers,
+        swift_cxx_args,
+        cmd_args(),
+    )
+
+def compile_underlying_pcm(
+    ctx: AnalysisContext,
+    module_name: str,
+    uncompiled_pcm_info: SwiftPCMUncompiledInfo,
+    compiled_pcm_deps_providers,
+    swift_cxx_args: list[str],
+    framework_search_path_flags: cmd_args,
+) -> SwiftCompiledModuleInfo:
+    return _compile_pcm(
+        ctx,
+        "swift_underlying_pcm_compile",
+        module_name,
+        uncompiled_pcm_info,
+        compiled_pcm_deps_providers,
+        swift_cxx_args,
+        framework_search_path_flags,
+    )
+
+def _get_base_pcm_flags(
+    ctx: AnalysisContext,
+    module_name: str,
+    swift_toolchain_info: SwiftToolchainInfo,
+    uncompiled_pcm_info: SwiftPCMUncompiledInfo,
+    sdk_deps_tset: SwiftCompiledModuleTset,
+    pcm_deps_tset: SwiftCompiledModuleTset,
+    swift_cxx_args: list[str],
+) -> (cmd_args, cmd_args, Artifact):
+    uses_content_based_paths = False
+    pcm_output = ctx.actions.declare_output(module_name + ".pcm", has_content_based_path = uses_content_based_paths)
+    cmd = cmd_args(
+        get_shared_pcm_compilation_args(module_name),
+        get_sdk_flags(ctx),
+        swift_toolchain_info.compiler_flags,
+        (
+            [
+                "-resource-dir",
+                swift_toolchain_info.resource_dir,
+            ]
+            if swift_toolchain_info.resource_dir
+            else []
+        ),
+        sdk_deps_tset.project_as_args("clang_module_file_flags"),
+        pcm_deps_tset.project_as_args("clang_module_file_flags"),
+        pcm_deps_tset.project_as_args("clang_importer_flags"),
+        # Order is important here, we need to add the symlink tree search paths
+        # before the headermaps to avoid mixing include paths.
+        uncompiled_pcm_info.exported_clang_importer_args,
+        uncompiled_pcm_info.clang_importer_args,
+    )
+
+    cmd.add(swift_cxx_args)
+
+    additional_cmd = cmd_args(
+        "-o",
+        pcm_output.as_output(),
+        uncompiled_pcm_info.modulemap_artifact,
+    )
+
+    return (cmd, additional_cmd, pcm_output)
diff --git a/buck2/prelude/apple/swift/swift_pcm_compilation_types.bzl b/buck2/prelude/apple/swift/swift_pcm_compilation_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_pcm_compilation_types.bzl
@@ -0,0 +1,38 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+)
+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftCompiledModuleTset")
+
+SwiftPCMUncompiledInfo = provider(
+    fields = {
+        # Compiler args required to compile this module.
+        "clang_importer_args": provider_field(cmd_args),
+        # Compiler args required by rdeps of this module, such as search paths for
+        # header symlink trees or framework bundles.
+        "exported_clang_importer_args": provider_field(cmd_args),
+        "exported_deps": provider_field(list[Dependency], default = []),
+        # If True represents an apple_library target that can't be compiled into a
+        # pcm, but which can re-export modular deps.
+        "is_transient": provider_field(bool, default = False),
+        # For non-transient modules, the artifact of this module's modulemap.
+        "modulemap_artifact": provider_field(Artifact | None, default = None),
+        "name": provider_field(str),
+        "uncompiled_sdk_modules": provider_field(list[str], default = []),
+    }
+)
+
+WrappedSwiftPCMCompiledInfo = provider(
+    fields = {
+        "clang_debug_info": provider_field(ArtifactTSet),
+        "clang_deps": provider_field(SwiftCompiledModuleTset),  # Tset of `SwiftCompiledModuleInfo`
+    }
+)
diff --git a/buck2/prelude/apple/swift/swift_sdk_flags.bzl b/buck2/prelude/apple/swift/swift_sdk_flags.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_sdk_flags.bzl
@@ -0,0 +1,17 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load(":swift_toolchain.bzl", "get_swift_toolchain_info")
+
+def get_sdk_flags(ctx: AnalysisContext) -> list[ArgLike]:
+    swift_toolchain_info = get_swift_toolchain_info(ctx)
+    if swift_toolchain_info.sdk_path:
+        return ["-sdk", swift_toolchain_info.sdk_path]
+    else:
+        return []
diff --git a/buck2/prelude/apple/swift/swift_sdk_pcm_compilation.bzl b/buck2/prelude/apple/swift/swift_sdk_pcm_compilation.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_sdk_pcm_compilation.bzl
@@ -0,0 +1,256 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_error_handler.bzl", "apple_build_error_handler")
+load("@prelude//apple:apple_utility.bzl", "expand_relative_prefixed_sdk_path", "get_disable_pch_validation_flags")
+load(":apple_sdk_modules_utility.bzl", "get_compiled_sdk_clang_deps_tset")
+load(
+    ":swift_debug_info_utils.bzl",
+    "extract_and_merge_clang_debug_infos",
+)
+load(":swift_sdk_flags.bzl", "get_sdk_flags")
+load(":swift_toolchain.bzl", "get_swift_toolchain_info_dep")
+load(
+    ":swift_toolchain_types.bzl",
+    "SdkUncompiledModuleInfo",
+    "SwiftCompiledModuleInfo",
+    "SwiftCompiledModuleTset",
+    "SwiftToolchainInfo",
+    "WrappedSdkCompiledModuleInfo",
+)
+
+def get_shared_pcm_compilation_args(module_name: str) -> cmd_args:
+    cmd = cmd_args()
+    cmd.add([
+        "-emit-pcm",
+        "-module-name",
+        module_name,
+        "-Xfrontend",
+        "-disable-implicit-swift-modules",
+        "-Xcc",
+        "-fno-implicit-modules",
+        "-Xcc",
+        "-fno-implicit-module-maps",
+        # Embed all input files into the PCM so we don't need to include module map files when
+        # building remotely.
+        # https://github.com/apple/llvm-project/commit/fb1e7f7d1aca7bcfc341e9214bda8b554f5ae9b6
+        "-Xcc",
+        "-Xclang",
+        "-Xcc",
+        "-fmodules-embed-all-files",
+        # Set the base directory of the pcm file to the working directory, which ensures
+        # all paths serialized in the PCM are relative.
+        "-Xcc",
+        "-Xclang",
+        "-Xcc",
+        "-fmodule-file-home-is-cwd",
+        # We cannot set an empty Swift working directory as that would end up serializing
+        # absolute header search paths in the PCM. Instead unset the clang working directory
+        # to avoid serializing it as an absolute path.
+        "-Xcc",
+        "-working-directory=",
+        # AssetsLibrary is shipping with a #warning, which we shouldn't error on when compiling
+        # the SDK module. I don't think this is actually avoidable or removable until the next xcode major version
+        "-Xcc",
+        "-Wno-error=#warnings",
+        # When compiling PCMs with the new Swift driver, we need to manually set -file-compilation-dir.
+        # If not defined, the driver will append this path automatically,
+        # resulting in the emission of absolute paths in the PCMs.
+        "-file-compilation-dir",
+        ".",
+    ])
+
+    cmd.add(get_disable_pch_validation_flags())
+
+    return cmd
+
+def _remove_path_components_from_right(path: str, count: int):
+    path_components = path.split("/")
+    removed_path = "/".join(path_components[0:-count])
+    return removed_path
+
+def _add_sdk_module_search_path(cmd, uncompiled_sdk_module_info, swift_toolchain_info):
+    modulemap_path = uncompiled_sdk_module_info.input_relative_path
+
+    # If this input is a framework we need to search above the
+    # current framework location, otherwise we include the
+    # modulemap root.
+    if uncompiled_sdk_module_info.is_framework:
+        frameworks_dir_path = _remove_path_components_from_right(modulemap_path, 3)
+        expanded_path = expand_relative_prefixed_sdk_path(swift_toolchain_info, frameworks_dir_path)
+    else:
+        module_root_path = _remove_path_components_from_right(modulemap_path, 1)
+        expanded_path = expand_relative_prefixed_sdk_path(swift_toolchain_info, module_root_path)
+    cmd.add(
+        "-Xcc",
+        ("-F" if uncompiled_sdk_module_info.is_framework else "-I"),
+        "-Xcc",
+        expanded_path,
+    )
+
+def get_swift_sdk_pcm_anon_targets(ctx: AnalysisContext, enable_cxx_interop: bool, uncompiled_sdk_deps: list[Dependency], swift_cxx_args: list[str]):
+    # We include the Swift deps here too as we need
+    # to include their transitive clang deps.
+    return [
+        (
+            _swift_sdk_pcm_compilation,
+            {
+                "dep": module_dep,
+                "enable_cxx_interop": enable_cxx_interop,
+                "has_content_based_path": False,
+                "name": module_dep.label,
+                "swift_cxx_args": swift_cxx_args,
+                "_swift_toolchain": get_swift_toolchain_info_dep(ctx),
+            },
+        )
+        for module_dep in uncompiled_sdk_deps
+    ]
+
+def _swift_sdk_pcm_compilation_impl(ctx: AnalysisContext) -> [Promise, list[Provider]]:
+    def k(sdk_pcm_deps_providers) -> list[Provider]:
+        uncompiled_sdk_module_info = ctx.attrs.dep[SdkUncompiledModuleInfo]
+        sdk_deps_tset = get_compiled_sdk_clang_deps_tset(ctx, sdk_pcm_deps_providers)
+        uses_content_based_paths = False
+
+        # We pass in Swift and Clang SDK module deps to get the transitive
+        # Clang dependencies compiled with the correct Swift cxx args. For
+        # Swift modules we just want to pass up the clang deps.
+        if uncompiled_sdk_module_info.is_swiftmodule:
+            return [
+                DefaultInfo(),
+                WrappedSdkCompiledModuleInfo(
+                    clang_deps = sdk_deps_tset,
+                    clang_debug_info = extract_and_merge_clang_debug_infos(ctx, sdk_pcm_deps_providers),
+                ),
+            ]
+
+        module_name = uncompiled_sdk_module_info.module_name
+        swift_toolchain = ctx.attrs._swift_toolchain[SwiftToolchainInfo]
+        cmd = cmd_args(swift_toolchain.compiler)
+        argsfile_cmd = cmd_args(uncompiled_sdk_module_info.partial_cmd)
+        argsfile_cmd.add(get_sdk_flags(ctx))
+        argsfile_cmd.add(swift_toolchain.compiler_flags)
+
+        if swift_toolchain.resource_dir:
+            argsfile_cmd.add([
+                "-resource-dir",
+                swift_toolchain.resource_dir,
+            ])
+
+        if not swift_toolchain.supports_relative_resource_dir:
+            # When the compiler does not correctly serialize builtin header paths
+            # we need to specify the CWD as a search path to find the headers.
+            argsfile_cmd.add([
+                "-Xcc",
+                "-I.",
+            ])
+
+        argsfile_cmd.add(sdk_deps_tset.project_as_args("clang_module_file_flags"))
+
+        # For SDK modules we need to set a few more args
+        argsfile_cmd.add([
+            "-Xcc",
+            "-Xclang",
+            "-Xcc",
+            "-emit-module",
+            "-Xcc",
+            "-Xclang",
+            "-Xcc",
+            "-fsystem-module",
+        ])
+
+        argsfile_cmd.add(ctx.attrs.swift_cxx_args)
+
+        if ctx.attrs.enable_cxx_interop:
+            # The stdlib headers have deprecation warnings set when targeting
+            # more recent versions. These warnings get serialized in the
+            # modules and make it impossible to import the std module, so
+            # suppress them during compilation instead.
+            argsfile_cmd.add([
+                "-Xcc",
+                "-D_LIBCPP_DISABLE_DEPRECATION_WARNINGS",
+            ])
+
+            if module_name == "Darwin":
+                # The Darwin module requires special handling with cxx interop
+                # to ensure that it does not include the c++ headers. The module
+                # is marked with [no_undeclared_includes] which will prevent
+                # including headers declared in other modulemaps. So that the
+                # cxx modules are visible we need to pass the module map path
+                # without the corresponding module file, which we cannot build
+                # until the Darwin module is available.
+                argsfile_cmd.add([
+                    "-Xcc",
+                    cmd_args(swift_toolchain.sdk_path, format = "-fmodule-map-file={}/usr/include/c++/v1/module.modulemap"),
+                ])
+
+        _add_sdk_module_search_path(argsfile_cmd, uncompiled_sdk_module_info, swift_toolchain)
+
+        shell_quoted_args = cmd_args(argsfile_cmd, quote = "shell")
+        argsfile, _ = ctx.actions.write("sdk_pcm_compile_argsfile", shell_quoted_args, allow_args = True, has_content_based_path = uses_content_based_paths)
+        cmd.add(cmd_args(argsfile, format = "@{}", delimiter = ""))
+        cmd.add(cmd_args(hidden = [argsfile_cmd]))
+
+        expanded_modulemap_path_cmd = expand_relative_prefixed_sdk_path(
+            swift_toolchain,
+            uncompiled_sdk_module_info.input_relative_path,
+        )
+        pcm_output = ctx.actions.declare_output(module_name + ".pcm", has_content_based_path = uses_content_based_paths)
+        cmd.add([
+            "-o",
+            pcm_output.as_output(),
+            expanded_modulemap_path_cmd,
+        ])
+
+        ctx.actions.run(
+            cmd,
+            category = "sdk_swift_pcm_compile",
+            identifier = module_name,
+            # Swift compiler requires unique inodes for all input files.
+            unique_input_inodes = True,
+            error_handler = apple_build_error_handler,
+        )
+
+        compiled_sdk = SwiftCompiledModuleInfo(
+            clang_modulemap_path = expanded_modulemap_path_cmd,
+            is_framework = uncompiled_sdk_module_info.is_framework,
+            is_sdk_module = True,
+            is_swiftmodule = False,
+            module_name = module_name,
+            output_artifact = pcm_output,
+        )
+
+        return [
+            DefaultInfo(),
+            WrappedSdkCompiledModuleInfo(
+                clang_deps = ctx.actions.tset(SwiftCompiledModuleTset, value = compiled_sdk, children = [sdk_deps_tset]),
+                clang_debug_info = extract_and_merge_clang_debug_infos(ctx, sdk_pcm_deps_providers, [pcm_output]),
+            ),
+        ]
+
+    # Compile the transitive clang module deps of this target.
+    deps = ctx.attrs.dep[SdkUncompiledModuleInfo].cxx_deps if ctx.attrs.enable_cxx_interop else ctx.attrs.dep[SdkUncompiledModuleInfo].deps
+    clang_module_deps = get_swift_sdk_pcm_anon_targets(
+        ctx,
+        ctx.attrs.enable_cxx_interop,
+        deps,
+        ctx.attrs.swift_cxx_args,
+    )
+
+    return ctx.actions.anon_targets(clang_module_deps).promise.map(k)
+
+_swift_sdk_pcm_compilation = rule(
+    impl = _swift_sdk_pcm_compilation_impl,
+    attrs = {
+        "dep": attrs.dep(),
+        "enable_cxx_interop": attrs.bool(),
+        "has_content_based_path": attrs.bool(),
+        "swift_cxx_args": attrs.list(attrs.string(), default = []),
+        "_swift_toolchain": attrs.dep(),
+    },
+)
diff --git a/buck2/prelude/apple/swift/swift_swiftinterface_compilation.bzl b/buck2/prelude/apple/swift/swift_swiftinterface_compilation.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_swiftinterface_compilation.bzl
@@ -0,0 +1,190 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")
+load("@prelude//apple:apple_utility.bzl", "expand_relative_prefixed_sdk_path")
+load("@prelude//apple/swift:swift_pcm_compilation.bzl", "get_compiled_pcm_deps_tset")
+load("@prelude//apple/swift:swift_types.bzl", "SWIFTMODULE_EXTENSION")
+load(":apple_sdk_modules_utility.bzl", "get_compiled_sdk_clang_deps_tset", "get_compiled_sdk_swift_deps_tset")
+load(
+    ":swift_debug_info_utils.bzl",
+    "extract_and_merge_clang_debug_infos",
+    "extract_and_merge_swift_debug_infos",
+)
+load(
+    ":swift_incremental_support.bzl",
+    "get_uses_content_based_paths",
+)
+load(":swift_module_map.bzl", "write_swift_module_map_with_deps")
+load(":swift_sdk_flags.bzl", "get_sdk_flags")
+load(":swift_sdk_pcm_compilation.bzl", "get_swift_sdk_pcm_anon_targets")
+load(":swift_toolchain.bzl", "get_swift_toolchain_info", "get_swift_toolchain_info_dep")
+load(
+    ":swift_toolchain_types.bzl",
+    "SdkUncompiledModuleInfo",
+    "SwiftCompiledModuleInfo",
+    "SwiftCompiledModuleTset",
+    "SwiftToolchainInfo",
+    "WrappedSdkCompiledModuleInfo",
+)
+
+def get_swift_interface_anon_targets(ctx: AnalysisContext, uncompiled_sdk_deps: list[Dependency]):
+    return [
+        (
+            _swift_interface_compilation,
+            {
+                # There's an "implicit" arg being passed - the execution platform
+                # of the rule that's requesting the anon-targets. In this case,
+                # callers of `get_swift_interface_anon_targets()` will call
+                # `ctx.actions.anon_targets()`, so the exec platform will get
+                # inherited.
+                #
+                # This has an important implication - the exact same SDK target
+                # might get duplicated if it's requested `apple_library()`
+                # targets which have different execution platforms, even if
+                # everything else is the same - including the same toolchain.
+                #
+                # Because Swift compilation aggregates SDK modules from deps
+                # and SDK modules from the target itself, a duplication of the
+                # same compiled SDK module can occur in the module map.
+                "dep": d,
+                "has_content_based_path": True,
+                "name": d.label,
+                "_apple_tools": ctx.attrs._apple_tools,
+                "_swift_toolchain": get_swift_toolchain_info_dep(ctx),
+            },
+        )
+        for d in uncompiled_sdk_deps
+        if d[SdkUncompiledModuleInfo].is_swiftmodule
+    ]
+
+def compile_swiftinterface_common(
+    ctx,
+    deps,
+    is_framework,
+    uncompiled_module_info_name,
+    partial_cmd,
+    sdk_deps_providers,
+    expanded_swiftinterface_cmd,
+    category,
+    additional_compiled_pcm,
+    additional_compiled_swiftmodules = None,
+):
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+    swift_toolchain = get_swift_toolchain_info(ctx)
+    cmd = cmd_args(swift_toolchain.compiler)
+    cmd.add(partial_cmd)
+    cmd.add(get_sdk_flags(ctx))
+
+    if swift_toolchain.resource_dir:
+        cmd.add([
+            "-resource-dir",
+            swift_toolchain.resource_dir,
+        ])
+
+    pcm_deps_tset = get_compiled_pcm_deps_tset(ctx, sdk_deps_providers)
+
+    if additional_compiled_pcm:
+        pcm_deps_tset = ctx.actions.tset(SwiftCompiledModuleTset, value = additional_compiled_pcm, children = [pcm_deps_tset])
+
+    clang_deps_tset = get_compiled_sdk_clang_deps_tset(ctx, sdk_deps_providers)
+    swift_deps_tset = get_compiled_sdk_swift_deps_tset(ctx, sdk_deps_providers + deps)
+
+    #'additional_compiled_swiftmodules' in practice will be third-party frameworks
+    if additional_compiled_swiftmodules:
+        swift_deps_tset = ctx.actions.tset(SwiftCompiledModuleTset, children = [swift_deps_tset, additional_compiled_swiftmodules])
+
+    all_deps_tset = ctx.actions.tset(
+        SwiftCompiledModuleTset,
+        children = [pcm_deps_tset, clang_deps_tset, swift_deps_tset],
+    )
+
+    _, swift_module_map_args = write_swift_module_map_with_deps(ctx, uncompiled_module_info_name, all_deps_tset)
+    cmd.add([
+        "-explicit-swift-module-map-file",
+        swift_module_map_args,
+    ])
+
+    swiftmodule_output = ctx.actions.declare_output(uncompiled_module_info_name + SWIFTMODULE_EXTENSION, has_content_based_path = uses_content_based_paths)
+    cmd.add([
+        "-o",
+        swiftmodule_output.as_output(),
+        expanded_swiftinterface_cmd,
+    ])
+
+    ctx.actions.run(
+        cmd,
+        category = category,
+        identifier = uncompiled_module_info_name,
+    )
+
+    return SwiftCompiledModuleInfo(
+        is_framework = is_framework,
+        is_sdk_module = True,
+        is_swiftmodule = True,
+        module_name = uncompiled_module_info_name,
+        output_artifact = swiftmodule_output,
+    ), swift_deps_tset
+
+def _swift_interface_compilation_impl(ctx: AnalysisContext) -> [Promise, list[Provider]]:
+    def k(sdk_deps_providers) -> list[Provider]:
+        uncompiled_sdk_module_info = ctx.attrs.dep[SdkUncompiledModuleInfo]
+        uncompiled_module_info_name = uncompiled_sdk_module_info.module_name
+        swift_toolchain = ctx.attrs._swift_toolchain[SwiftToolchainInfo]
+
+        expanded_swiftinterface_cmd = expand_relative_prefixed_sdk_path(
+            swift_toolchain,
+            uncompiled_sdk_module_info.input_relative_path,
+        )
+
+        compiled_sdk, swift_deps_tset = compile_swiftinterface_common(
+            ctx,
+            [],
+            uncompiled_sdk_module_info.is_framework,
+            uncompiled_module_info_name,
+            uncompiled_sdk_module_info.partial_cmd,
+            sdk_deps_providers,
+            expanded_swiftinterface_cmd,
+            "sdk_swiftinterface_compile",
+            None,
+        )
+
+        wrapped_sdk_compiled_module_info = WrappedSdkCompiledModuleInfo(
+            swift_deps = ctx.actions.tset(SwiftCompiledModuleTset, value = compiled_sdk, children = [swift_deps_tset]),
+            swift_debug_info = extract_and_merge_swift_debug_infos(ctx, sdk_deps_providers, [compiled_sdk.output_artifact]),
+            clang_debug_info = extract_and_merge_clang_debug_infos(ctx, sdk_deps_providers),
+        )
+
+        return [
+            DefaultInfo(),
+            wrapped_sdk_compiled_module_info,
+        ]
+
+    # For each swiftinterface compile its transitive clang deps with the provided target.
+    module_info = ctx.attrs.dep[SdkUncompiledModuleInfo]
+    clang_module_deps = get_swift_sdk_pcm_anon_targets(
+        ctx,
+        False,
+        module_info.deps,
+        ["-target", module_info.target],
+    )
+
+    # Compile the transitive swiftmodule deps.
+    swift_module_deps = get_swift_interface_anon_targets(ctx, module_info.deps)
+
+    return ctx.actions.anon_targets(clang_module_deps + swift_module_deps).promise.map(k)
+
+_swift_interface_compilation = rule(
+    impl = _swift_interface_compilation_impl,
+    attrs = {
+        "dep": attrs.dep(),
+        "has_content_based_path": attrs.bool(),
+        "_apple_tools": attrs.dep(providers = [AppleToolsInfo]),
+        "_swift_toolchain": attrs.dep(),
+    },
+)
diff --git a/buck2/prelude/apple/swift/swift_toolchain.bzl b/buck2/prelude/apple/swift/swift_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_toolchain.bzl
@@ -0,0 +1,143 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactInfoTag",
+    "make_artifact_tset",
+)
+load(":swift_toolchain_types.bzl", "SdkUncompiledModuleInfo", "SwiftObjectFormat", "SwiftToolchainInfo")
+
+def get_swift_toolchain_info(ctx: AnalysisContext) -> SwiftToolchainInfo:
+    if hasattr(ctx.attrs, "_swift_toolchain"):
+        return ctx.attrs._swift_toolchain[SwiftToolchainInfo]
+    else:
+        return ctx.attrs._apple_toolchain[SwiftToolchainInfo]
+
+def get_swift_toolchain_info_dep(ctx: AnalysisContext) -> Dependency:
+    if hasattr(ctx.attrs, "_swift_toolchain"):
+        return ctx.attrs._swift_toolchain
+    else:
+        return ctx.attrs._apple_toolchain
+
+def supports_modulemaps_with_hmaps(ctx: AnalysisContext) -> bool:
+    return get_swift_toolchain_info(ctx).supports_modulemaps_with_hmaps
+
+def include_path_for_relative_module_map_paths(ctx: AnalysisContext) -> list[str]:
+    if supports_modulemaps_with_hmaps(ctx):
+        # modulemap paths are relative to the modulemap file, but the compiler
+        # needs search paths to be able to find the headers themselves. When
+        # EmitClangHeaderWithNonModularIncludes is enabled, we need to be able
+        # to resolve these paths back to something that is in a headermap. The
+        # headermaps contain two forms:
+        #  1. <ModuleName/HeaderName.h>
+        #  2. <repo/relative/path/to/header.h>
+        # We can use the latter in every case by adding the repo root as a
+        # header search path for the ClangImporter when emitting ObjC headers.
+        return ["-Xcc", "-I."]
+    else:
+        return []
+
+def _traverse_sdk_modules_graph(
+    swift_sdk_module_name_to_deps: dict[str, Dependency], clang_sdk_module_name_to_deps: dict[str, Dependency], sdk_module_dep: Dependency
+):
+    if SdkUncompiledModuleInfo not in sdk_module_dep:
+        return
+
+    uncompiled_sdk_module_info = sdk_module_dep[SdkUncompiledModuleInfo]
+
+    # If input_relative_path is None then this module represents a root node of SDK modules graph.
+    # In such case, we need to handle only its deps.
+    if uncompiled_sdk_module_info.input_relative_path == None:
+        for uncompiled_dep in uncompiled_sdk_module_info.deps:
+            _traverse_sdk_modules_graph(swift_sdk_module_name_to_deps, clang_sdk_module_name_to_deps, uncompiled_dep)
+        return
+
+    # return if dep is already in dict
+    if uncompiled_sdk_module_info.is_swiftmodule and uncompiled_sdk_module_info.module_name in swift_sdk_module_name_to_deps:
+        return
+    elif not uncompiled_sdk_module_info.is_swiftmodule and uncompiled_sdk_module_info.module_name in clang_sdk_module_name_to_deps:
+        return
+
+    for uncompiled_dep in uncompiled_sdk_module_info.deps + uncompiled_sdk_module_info.cxx_deps:
+        _traverse_sdk_modules_graph(swift_sdk_module_name_to_deps, clang_sdk_module_name_to_deps, uncompiled_dep)
+
+    if uncompiled_sdk_module_info.is_swiftmodule:
+        swift_sdk_module_name_to_deps[uncompiled_sdk_module_info.module_name] = sdk_module_dep
+    else:
+        clang_sdk_module_name_to_deps[uncompiled_sdk_module_info.module_name] = sdk_module_dep
+
+def compute_sdk_module_graph(sdk_module_deps: list[Dependency]) -> (dict[str, Dependency], dict[str, Dependency]):
+    # All Clang's PCMs need to be compiled with cxx flags of the target that imports them,
+    # because of that, we expose `dependency`s of SDK modules,
+    # which might be accessed from apple_library/apple_test rules and compiled there.
+    uncompiled_swift_sdk_modules_deps = {}
+    uncompiled_clang_sdk_modules_deps = {}
+
+    for sdk_module_dep in sdk_module_deps:
+        _traverse_sdk_modules_graph(
+            uncompiled_swift_sdk_modules_deps,
+            uncompiled_clang_sdk_modules_deps,
+            sdk_module_dep,
+        )
+
+    return uncompiled_swift_sdk_modules_deps, uncompiled_clang_sdk_modules_deps
+
+def swift_toolchain_impl(ctx):
+    uncompiled_swift_sdk_modules_deps, uncompiled_clang_sdk_modules_deps = compute_sdk_module_graph(ctx.attrs.sdk_modules)
+
+    # Module map files can live in the SDK or the toolchain resource dir.
+    # We need to pass through both to ensure the debuginfo target
+    # materializes them.
+    debug_info_artifacts = []
+    if ctx.attrs.sdk_path:
+        debug_info_artifacts.append(ctx.attrs.sdk_path)
+    if ctx.attrs.resource_dir:
+        debug_info_artifacts.append(ctx.attrs.resource_dir)
+
+    sdk_debug_info = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        artifacts = debug_info_artifacts,
+        tags = [ArtifactInfoTag("swift_debug_info")],
+    )
+
+    return [
+        DefaultInfo(),
+        SwiftToolchainInfo(
+            architecture = ctx.attrs.architecture,
+            compiler = cmd_args(ctx.attrs._swiftc_wrapper[RunInfo]).add(ctx.attrs.swiftc[RunInfo]),
+            compiler_flags = ctx.attrs.swiftc_flags,
+            mk_swift_comp_db = ctx.attrs.make_swift_comp_db[RunInfo],
+            mk_swift_interface = cmd_args(ctx.attrs._swiftc_wrapper[RunInfo]).add(ctx.attrs.make_swift_interface[RunInfo]),
+            object_format = SwiftObjectFormat(ctx.attrs.object_format) if ctx.attrs.object_format else SwiftObjectFormat("object"),
+            platform_path = ctx.attrs.platform_path,
+            prioritize_swift_critical_path = ctx.attrs.prioritize_swift_critical_path,
+            provide_swift_debug_info = ctx.attrs.provide_swift_debug_info,
+            resource_dir = ctx.attrs.resource_dir,
+            sdk_module_path_prefixes = ctx.attrs.sdk_module_path_prefixes,
+            sdk_path = ctx.attrs._internal_sdk_path or ctx.attrs.sdk_path,
+            sdk_debug_info = sdk_debug_info,
+            serialized_diags_to_json = ctx.attrs.serialized_diags_to_json[RunInfo] if ctx.attrs.serialized_diags_to_json else None,
+            supports_explicit_module_debug_serialization = ctx.attrs.supports_explicit_module_debug_serialization,
+            supports_incremental_file_hashing = ctx.attrs.supports_incremental_file_hashing,
+            supports_modularization_dependency_graph = ctx.attrs.supports_modularization_dependency_graph,
+            supports_modulemaps_with_hmaps = ctx.attrs.supports_modulemaps_with_hmaps,
+            supports_relative_resource_dir = ctx.attrs.supports_relative_resource_dir,
+            swift_ide_test_tool = ctx.attrs.swift_ide_test_tool[RunInfo] if ctx.attrs.swift_ide_test_tool else None,
+            swift_stdlib_tool = ctx.attrs.swift_stdlib_tool[RunInfo],
+            swift_stdlib_tool_flags = ctx.attrs.swift_stdlib_tool_flags,
+            swift_experimental_features = ctx.attrs.swift_experimental_features,
+            swift_upcoming_features = ctx.attrs.swift_upcoming_features,
+            uncompiled_clang_sdk_modules_deps = uncompiled_clang_sdk_modules_deps,
+            uncompiled_swift_sdk_modules_deps = uncompiled_swift_sdk_modules_deps,
+            enforce_dedupe_eligibility = ctx.attrs.enforce_dedupe_eligibility,
+            use_depsfiles = ctx.attrs.use_depsfiles,
+            uses_content_based_paths = ctx.attrs.uses_content_based_paths,
+        ),
+    ]
diff --git a/buck2/prelude/apple/swift/swift_toolchain_macro_layer.bzl b/buck2/prelude/apple/swift/swift_toolchain_macro_layer.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_toolchain_macro_layer.bzl
@@ -0,0 +1,22 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def swift_toolchain_macro_impl(swift_toolchain_rule = None, **kwargs):
+    bitcode = read_root_config("swift", "bitcode")
+    if bitcode != None:
+        kwargs["object_format"] = "object"
+        if bitcode.lower() == "true":
+            kwargs["object_format"] = "bc"
+        elif bitcode.lower() == "ir":
+            kwargs["object_format"] = "ir"
+        elif bitcode.lower() == "irgen":
+            kwargs["object_format"] = "irgen"
+        elif bitcode.lower() in ["embed", "embed-bitcode", "object-embed-bitcode"]:
+            kwargs["object_format"] = "object-embed-bitcode"
+
+    swift_toolchain_rule(**kwargs)
diff --git a/buck2/prelude/apple/swift/swift_toolchain_types.bzl b/buck2/prelude/apple/swift/swift_toolchain_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_toolchain_types.bzl
@@ -0,0 +1,198 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+#####################################################################
+# Providers
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",  # @unused Used as a type
+)
+load("@prelude//utils:arglike.bzl", "ArgLike")
+
+SwiftObjectFormat = enum(
+    "object",
+    "bc",
+    "ir",
+    "irgen",
+    "object-embed-bitcode",
+)
+
+SwiftToolchainInfo = provider(
+    fields = {
+        "architecture": provider_field(str),
+        "compiler": provider_field(cmd_args),
+        "compiler_flags": provider_field(list[ArgLike]),
+        "enforce_dedupe_eligibility": provider_field(bool, default = False),
+        "mk_swift_comp_db": provider_field(RunInfo),
+        "mk_swift_interface": provider_field(cmd_args),
+        "object_format": provider_field(SwiftObjectFormat),
+        "platform_path": provider_field([Artifact, str, None]),
+        # Prioritizes the Swift critical path by preferring swiftmodule emits
+        # locally, disabling low-pass gating for swiftmodule and PCM actions,
+        # and increasing bulk Swift object-compile weight.
+        "prioritize_swift_critical_path": provider_field(bool, default = False),
+        "provide_swift_debug_info": provider_field(bool, default = True),
+        "resource_dir": provider_field([Artifact, None]),
+        "sdk_debug_info": provider_field([ArtifactTSet, None]),
+        "sdk_module_path_prefixes": provider_field(dict[str, Artifact]),
+        "sdk_path": provider_field([Artifact, str, None]),
+        "serialized_diags_to_json": provider_field([RunInfo, None], default = None),
+        "supports_explicit_module_debug_serialization": provider_field(bool, default = False),
+        "supports_incremental_file_hashing": provider_field(bool, default = False),
+        # Whether swiftc supports -emit-modularization-dependency-dot-graph.
+        # Only the Pika toolchain does; Xcode's swiftc errors with
+        # "unknown argument", so this defaults off.
+        "supports_modularization_dependency_graph": provider_field(bool, default = False),
+        "supports_modulemaps_with_hmaps": provider_field(bool, default = False),
+        "supports_relative_resource_dir": provider_field(bool),
+        "swift_experimental_features": provider_field(dict[str, list[str]]),  # { "5": [], "6", [] }
+        "swift_ide_test_tool": provider_field([RunInfo, None], default = None),
+        "swift_stdlib_tool": provider_field(RunInfo),
+        "swift_stdlib_tool_flags": provider_field(list[ArgLike]),
+        "swift_upcoming_features": provider_field(dict[str, list[str]]),  # { "5": [], "6", [] }
+        "uncompiled_clang_sdk_modules_deps": provider_field(dict[str, Dependency]),
+        "uncompiled_swift_sdk_modules_deps": provider_field(dict[str, Dependency]),
+        "use_depsfiles": provider_field(bool, default = False),
+        "uses_content_based_paths": provider_field(bool, default = False),
+    }
+)
+
+# A provider that represents a non-yet-compiled SDK (Swift or Clang) module,
+# and doesn't contain any artifacts because Swift toolchain isn't resolved yet.
+SdkUncompiledModuleInfo = provider(
+    fields = {
+        # [Dependency]
+        "cxx_deps": provider_field(typing.Any, default = None),
+        # [Dependency]
+        "deps": provider_field(typing.Any, default = None),
+        # A relative prefixed path to a textual swiftinterface/modulemap file within an SDK.
+        "input_relative_path": provider_field(typing.Any, default = None),
+        # This is mostly needed for the generated Swift module map file.
+        "is_framework": provider_field(typing.Any, default = None),
+        # If True then represents a swiftinterface, otherwise Clang's modulemap.
+        "is_swiftmodule": provider_field(typing.Any, default = None),
+        # A real name of a module, without distinguishing suffixes.
+        "module_name": provider_field(typing.Any, default = None),
+        # Transitive closure filtered to overlay owners and underlyings.
+        "overlays_transitive_deps": provider_field(typing.Any, default = None),
+        # Partial arguments, required to compile a particular SDK module.
+        "partial_cmd": provider_field(typing.Any, default = None),
+        # A string of the compiler target triple to use for clang module deps, eg arm64-apple-ios16.4
+        "target": provider_field(typing.Any, default = None),
+    }
+)
+
+WrappedSdkCompiledModuleInfo = provider(
+    fields = {
+        # A tset of PCM artifacts
+        "clang_debug_info": provider_field(typing.Any, default = None),
+        # A SwiftCompiledModuleTset of SwiftCompiledModuleInfo of transitive clang deps
+        "clang_deps": provider_field(typing.Any, default = None),
+        # A tset of swiftmodule artifacts
+        "swift_debug_info": provider_field(typing.Any, default = None),
+        # A SwiftCompiledModuleTset of SwiftCompiledModuleInfo of transitive swift deps
+        "swift_deps": provider_field(typing.Any, default = None),
+    }
+)
+
+SdkSwiftOverlayInfo = provider(
+    fields = {
+        "overlays": provider_field(typing.Any, default = None),  # {str: [str]} A mapping providing a list of overlay module names for each underlying module
+    }
+)
+
+SwiftCompiledModuleInfo = provider(
+    fields = {
+        # Additional flags for the clang importer.
+        "clang_importer_args": provider_field(cmd_args | None, default = None),
+        # Clang modulemap path, required for generation of swift_module_map. We use
+        # cmd_args here to expand SDK relative paths.
+        "clang_modulemap_path": provider_field(cmd_args | None, default = None),
+        "is_framework": provider_field(bool),
+        "is_sdk_module": provider_field(bool),
+        # If True then contains a compiled swiftmodule, otherwise Clang's pcm.
+        "is_swiftmodule": provider_field(bool),
+        # A real name of a module, without distinguishing suffixes.
+        "module_name": provider_field(str),
+        # Compiled artifact either swiftmodule or pcm.
+        "output_artifact": provider_field(Artifact),
+    }
+)
+
+def clang_module_file_args(module_info: SwiftCompiledModuleInfo) -> cmd_args:
+    return cmd_args(
+        "-Xcc",
+        cmd_args(
+            "-fmodule-file=",
+            module_info.module_name,
+            "=",
+            module_info.output_artifact,
+            delimiter = "",
+        ),
+        "-Xcc",
+        cmd_args(
+            "-fmodule-map-file=",
+            module_info.clang_modulemap_path,
+            delimiter = "",
+        ),
+    )
+
+def _add_swiftmodule_search_path(module_info: SwiftCompiledModuleInfo):
+    # We need to import the containing folder, not the file itself.
+    # We skip SDK modules as those are found via the -sdk flag.
+    if module_info.is_swiftmodule and not module_info.is_sdk_module:
+        return ["-I", cmd_args(module_info.output_artifact, parent = 1)]
+
+    return []
+
+def _add_clang_module_file_flags(module_info: SwiftCompiledModuleInfo):
+    if module_info.is_swiftmodule:
+        return []
+    else:
+        return [clang_module_file_args(module_info)]
+
+def _add_clang_importer_flags(module_info: SwiftCompiledModuleInfo):
+    if module_info.is_swiftmodule:
+        return []
+    else:
+        return [module_info.clang_importer_args] if module_info.clang_importer_args else []
+
+def _swift_module_map_struct(module_info: SwiftCompiledModuleInfo):
+    if module_info.is_swiftmodule:
+        # Swiftmodule files compiled from swiftinterface files embed the paths
+        # which are verified during compilation of rdeps, so we need to add
+        # the swiftinterface files as hidden inputs.
+        module_path = cmd_args(
+            module_info.output_artifact,
+            delimiter = "",
+        )
+
+        return struct(
+            isFramework = module_info.is_framework,
+            moduleName = module_info.module_name,
+            modulePath = module_path,
+        )
+    else:
+        return struct(
+            isFramework = module_info.is_framework,
+            moduleName = module_info.module_name,
+            clangModulePath = module_info.output_artifact,
+            clangModuleMapPath = cmd_args(module_info.clang_modulemap_path, delimiter = ""),
+        )
+
+SwiftCompiledModuleTset = transitive_set(
+    args_projections = {
+        "clang_importer_flags": _add_clang_importer_flags,  # Additional clang flags required for compilation.
+        "clang_module_file_flags": _add_clang_module_file_flags,  # Projects pcm modules as cli flags.
+        "module_search_path": _add_swiftmodule_search_path,
+    },
+    json_projections = {
+        "swift_module_map": _swift_module_map_struct,
+    },
+)
diff --git a/buck2/prelude/apple/swift/swift_types.bzl b/buck2/prelude/apple/swift/swift_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/swift/swift_types.bzl
@@ -0,0 +1,75 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",  # @unused Used as a type
+)
+load(":swift_toolchain_types.bzl", "SwiftCompiledModuleTset")
+
+SWIFT_EXTENSION = ".swift"
+
+SWIFTMODULE_EXTENSION = ".swiftmodule"
+
+# Base action categories for Swift compiles. When explicit modules are enabled,
+# EXPLICIT_MODULES_CATEGORY_SUFFIX is appended (see swift_compilation.bzl).
+SWIFT_COMPILE_CATEGORY = "swift_compile"
+
+SWIFTMODULE_COMPILE_CATEGORY = "swiftmodule_compile"
+
+EXPLICIT_MODULES_CATEGORY_SUFFIX = "_with_explicit_mods"
+
+SwiftCompilationModes = ("wmo", "incremental", "auto")
+
+SwiftMacroPlugin = plugins.kind()
+
+SwiftVersion = ("5", "6")
+
+SwiftDependencyInfo = provider(
+    fields = {
+        "debug_info_tset": provider_field(ArtifactTSet),
+        # Includes modules through exported_deps, used for compilation
+        "exported_swiftmodules": provider_field(SwiftCompiledModuleTset),
+        # If this target has exported_headers, used to validate non-modular dep exports
+        "has_exported_headers": provider_field(bool),
+        # Macro deps cannot be mixed with apple_library deps
+        "is_macro": provider_field(bool),
+        # If this target provides a clang module, used to validate non-modular dep exports
+        "is_modular": provider_field(bool),
+        # Tset of this target's own `-dump-ast` output directory (see the `[ast]`
+        # subtarget) merged with the same tset from all deps.
+        "swift_ast_dump_tset": provider_field(ArtifactTSet),
+        # Tset of this target's own `.swiftmodule` output merged with the
+        # same tsets from all deps.
+        "swiftmodule_change_analysis_tset": provider_field(ArtifactTSet),
+    }
+)
+
+def _swift_framework_implicit_search_paths_args(args: cmd_args):
+    return args
+
+FrameworkImplicitSearchPathInfoTSet = transitive_set(
+    args_projections = {
+        "swift_framework_implicit_search_paths_args": _swift_framework_implicit_search_paths_args,
+    },
+)
+
+FrameworkImplicitSearchPathInfo = provider(
+    fields = {
+        "tset": provider_field(typing.Any, default = None),  # A tset of FrameworkImplicitSearchPathInfoTSet
+    }
+)
+
+def get_implicit_framework_search_path_providers(ctx: AnalysisContext, value: [cmd_args, None], deps: list[Dependency]) -> FrameworkImplicitSearchPathInfoTSet:
+    deps_infos = [
+        d[FrameworkImplicitSearchPathInfo].tset for d in deps if FrameworkImplicitSearchPathInfo in d and d[FrameworkImplicitSearchPathInfo].tset != None
+    ]
+    if value:
+        return ctx.actions.tset(FrameworkImplicitSearchPathInfoTSet, value = value, children = deps_infos)
+    else:
+        return ctx.actions.tset(FrameworkImplicitSearchPathInfoTSet, children = deps_infos)
diff --git a/buck2/prelude/apple/tools/BUCK b/buck2/prelude/apple/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/BUCK
@@ -0,0 +1,150 @@
+# @noautodeps
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load(":defs.bzl", "apple_oso_scrubber_target", "bundle_telemetry_logger_target", "swiftmodule_change_analysis_target")
+
+oncall("build_infra")
+
+source_listing()
+
+apple_tools(
+    name = "apple-tools",
+    adhoc_codesign_tool = None, # @oss-enable
+    # @oss-disable[end= ]: adhoc_codesign_tool = "prelude//apple/tools/meta_only/codesign_rust:adhoc-signer",
+    assemble_bundle = "prelude//apple/tools/bundling:assemble_bundle",
+    bundle_telemetry_logger = bundle_telemetry_logger_target(),
+    codesign_manifest_tree_postprocessor = "prelude//apple/tools/codesign_manifest_tree_postprocessor:codesign_manifest_tree_postprocessor",
+    dedupe_swift_module_map = ":dedupe_swift_module_map",
+    dry_codesign_tool = ":dry_codesign_tool",
+    framework_sanitizer = ":framework_sanitizer",
+    info_plist_processor = "prelude//apple/tools/info_plist_processor:tool",
+    ipa_package_maker = ":ipa_package_maker",
+    make_modulemap = ":make_modulemap",
+    make_vfsoverlay = ":make_vfsoverlay",
+    provisioning_manifest = "prelude//apple/tools/bundling:provisioning_manifest",
+    resolve_signing_context = "prelude//apple/tools/bundling:resolve_signing_context",
+    selective_debugging_scrubber = apple_oso_scrubber_target(),
+    signing_context_tree_postprocessor = "prelude//apple/tools/signing_context_tree_postprocessor:signing_context_tree_postprocessor",
+    signing_info = "prelude//apple/tools/bundling:signing_info",
+    split_arch_combine_dsym_bundles_tool = ":split_arch_combine_dsym_bundles_tool",
+    spm_packager = ":spm_packager",
+    static_archive_linker = ":static_archive_linker",
+    swiftmodule_change_analysis = swiftmodule_change_analysis_target(),
+    visibility = ["PUBLIC"],
+    xcframework_maker = ":xcframework_maker",
+)
+
+python_binary(
+    name = "framework_sanitizer",
+    main = "framework_sanitizer.py",
+    visibility = ["PUBLIC"],
+)
+
+python_binary(
+    name = "xcframework_maker",
+    main = "xcframework_maker.py",
+    visibility = ["PUBLIC"],
+)
+
+python_binary(
+    name = "dry_codesign_tool",
+    main = "dry_codesign_tool.py",
+    visibility = ["PUBLIC"],
+)
+
+python_binary(
+    name = "ipa_package_maker",
+    main = "ipa_package_maker.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//apple/tools/re_compatibility_utils:re_compatibility_utils",
+    ],
+)
+
+python_bootstrap_binary(
+    name = "dedupe_swift_module_map",
+    main = "dedupe_swift_module_map.py",
+    visibility = ["PUBLIC"],
+)
+
+python_bootstrap_binary(
+    name = "make_modulemap",
+    main = "make_modulemap.py",
+    visibility = ["PUBLIC"],
+)
+
+python_bootstrap_binary(
+    name = "make_swift_comp_db",
+    main = "make_swift_comp_db.py",
+    visibility = ["PUBLIC"],
+)
+
+python_bootstrap_binary(
+    name = "make_swift_interface",
+    main = "make_swift_interface.py",
+    visibility = ["PUBLIC"],
+)
+
+python_bootstrap_binary(
+    name = "make_vfsoverlay",
+    main = "make_vfsoverlay.py",
+    visibility = ["PUBLIC"],
+)
+
+python_library(
+    name = "plistlib_utils",
+    srcs = ["plistlib_utils.py"],
+    visibility = ["PUBLIC"],
+)
+
+python_binary(
+    name = "split_arch_combine_dsym_bundles_tool",
+    main = "split_arch_combine_dsym_bundles_tool.py",
+    visibility = ["PUBLIC"],
+)
+
+python_bootstrap_binary(
+    name = "swift_exec",
+    has_content_based_path = True,
+    main = "swift_exec.py",
+    visibility = ["PUBLIC"],
+    deps = ["prelude//apple/tools/re_compatibility_utils:bootstrap_re_compatibility_utils"],
+)
+
+python_binary(
+    name = "static_archive_linker",
+    main = "static_archive_linker.py",
+    visibility = ["PUBLIC"],
+)
+
+python_binary(
+    name = "spm_packager",
+    main = "spm_packager.py",
+    visibility = ["PUBLIC"],
+)
+
+export_file(
+    name = "empty.c",
+    visibility = ["PUBLIC"],
+)
+
+# Type checking target for Python tool scripts
+python_library(
+    name = "scripts-typing",
+    srcs = [
+        "dedupe_swift_module_map.py",
+        "dry_codesign_tool.py",
+        "framework_sanitizer.py",
+        "ipa_package_maker.py",
+        "make_modulemap.py",
+        "make_swift_comp_db.py",
+        "make_swift_interface.py",
+        "make_vfsoverlay.py",
+        "plistlib_utils.py",
+        "split_arch_combine_dsym_bundles_tool.py",
+        "spm_packager.py",
+        "static_archive_linker.py",
+        "swift_exec.py",
+        "xcframework_maker.py",
+    ],
+    typing = True,
+)
diff --git a/buck2/prelude/apple/tools/bundling/BUCK b/buck2/prelude/apple/tools/bundling/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/BUCK
@@ -0,0 +1,83 @@
+load("@prelude//apple/tools:defs.bzl", "meta_python_test")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+python_binary(
+    name = "assemble_bundle",
+    main = "main.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//apple/tools/code_signing:lib",
+        "prelude//apple/tools/re_compatibility_utils:re_compatibility_utils",
+        ":lib",
+    ],
+)
+
+python_binary(
+    name = "provisioning_manifest",
+    main = "provisioning_manifest_main.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":lib",
+    ],
+)
+
+python_binary(
+    name = "resolve_signing_context",
+    main = "resolve_signing_context_main.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":lib",
+    ],
+)
+
+python_binary(
+    name = "signing_info",
+    main = "signing_info_main.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":lib",
+    ],
+)
+
+python_library(
+    name = "scripts-typing",
+    srcs = [
+        "resolve_signing_context_main.py",
+        "signing_info_main.py",
+    ],
+    typing = True,
+    deps = [":lib"],
+)
+
+python_library(
+    name = "lib",
+    srcs = glob(
+        [
+            "*.py",
+        ],
+        exclude = [
+            "*_test.py",
+            "*main.py",
+        ],
+    ),
+    deps = [
+        "prelude//apple/tools/code_signing:lib",
+        "prelude//apple/tools/re_compatibility_utils:re_compatibility_utils",
+    ],
+)
+
+meta_python_test(
+    name = "bundling_test",
+    srcs = glob(["*_test.py"]),
+    resources = glob([
+        "test_resources/*",
+    ]),
+    deps = [
+        "fbsource//third-party/pypi/setuptools:setuptools",
+        ":lib",
+    ],
+)
diff --git a/buck2/prelude/apple/tools/bundling/action_metadata.py b/buck2/prelude/apple/tools/bundling/action_metadata.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/action_metadata.py
@@ -0,0 +1,78 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import json
+import os
+from dataclasses import dataclass
+from io import TextIOBase
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+_METADATA_VERSION = 1
+
+
+@dataclass
+class _Item:
+    path: Path
+    digest: str
+
+
+@dataclass
+class _Metadata:
+    version: int
+    digests: List[_Item]
+
+
+def _object_hook(dict: Dict[str, Any]) -> Union[_Item, _Metadata]:
+    if "version" in dict:
+        return _Metadata(**dict)
+    else:
+        dict["path"] = Path(dict.pop("path"))
+        return _Item(**dict)
+
+
+def parse_action_metadata(data: TextIOBase) -> Optional[Dict[Path, str]]:
+    """
+    Returns:
+        Mapping from project relative path to hash digest for every file present action metadata.
+    """
+    start_stream_position = data.tell()
+    try:
+        metadata = json.load(data, object_hook=_object_hook)
+    except BaseException:
+        data.seek(start_stream_position)
+        version = json.load(data)["version"]
+        if version != _METADATA_VERSION:
+            raise RuntimeError(
+                f"Expected metadata version to be `{_METADATA_VERSION}` got `{version}`."
+            )
+        else:
+            raise
+    return {item.path: item.digest for item in metadata.digests}
+
+
+def action_metadata_if_present(
+    environment_variable_key: str,
+) -> Optional[Dict[Path, str]]:
+    """
+    Returns:
+        Mapping from project relative path to hash digest for every file present action metadata.
+    """
+    environment_variable = os.getenv(environment_variable_key)
+    if environment_variable is None:
+        return None
+    path = Path(environment_variable)
+    if not path.exists():
+        raise RuntimeError(
+            "Expected file with action metadata to exist given related environment variable is set."
+        )
+    else:
+        with path.open() as f:
+            return parse_action_metadata(f)
diff --git a/buck2/prelude/apple/tools/bundling/action_metadata_test.py b/buck2/prelude/apple/tools/bundling/action_metadata_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/action_metadata_test.py
@@ -0,0 +1,48 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import importlib.resources
+import unittest
+from json import JSONDecodeError
+from pathlib import Path
+
+from .action_metadata import parse_action_metadata
+
+
+class TestActionMetadata(unittest.TestCase):
+    def _resource_content(self, filename):
+        resources = importlib.resources.files(__package__) / "test_resources"
+        return resources / filename
+
+    def test_valid_metadata_is_parsed_successfully(self):
+        path = self._resource_content("valid_action_metadata.json")
+        with path.open() as file_content:
+            result = parse_action_metadata(file_content)
+        self.assertEqual(
+            result,
+            {
+                Path("repo/foo.txt"): "foo_digest",
+                Path("buck-out/bar.txt"): "bar_digest",
+            },
+        )
+
+    def test_error_when_invalid_metadata(self):
+        path = self._resource_content("the.broken_json")
+        with self.assertRaises(JSONDecodeError):
+            with path.open() as file_content:
+                _ = parse_action_metadata(file_content)
+
+    def test_user_friendly_error_when_metadata_with_newer_version(self):
+        path = self._resource_content("newer_version_action_metadata.json")
+        with self.assertRaises(Exception) as context:
+            with path.open() as file_content:
+                _ = parse_action_metadata(file_content)
+            self.assertEqual(
+                context.exception,
+                RuntimeError("Expected metadata version to be `1` got `2`."),
+            )
diff --git a/buck2/prelude/apple/tools/bundling/assemble_bundle.py b/buck2/prelude/apple/tools/bundling/assemble_bundle.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/assemble_bundle.py
@@ -0,0 +1,277 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import filecmp
+import logging
+import os
+import shutil
+from pathlib import Path
+from typing import Any, cast, Dict, List, Optional
+
+from .assemble_bundle_types import BundleSpecItem, IncrementalContext
+from .incremental_state import IncrementalState, IncrementalStateItem
+from .incremental_utils import (
+    calculate_incremental_state,
+    should_assemble_incrementally,
+)
+
+_LOGGER: logging.Logger = logging.getLogger(__name__)
+
+
+def assemble_bundle(
+    spec: List[BundleSpecItem],
+    bundle_path: Path,
+    incremental_context: Optional[IncrementalContext],
+    check_conflicts: bool,
+    versioned_if_macos: bool,
+) -> Optional[List[IncrementalStateItem]]:
+    incremental_result = None
+    if incremental_context:
+        if should_assemble_incrementally(spec, incremental_context):
+            incremental_result = _assemble_incrementally(
+                bundle_path,
+                spec,
+                incremental_context.metadata,
+                cast(IncrementalState, incremental_context.state),
+                check_conflicts,
+                versioned_if_macos,
+            )
+        else:
+            _assemble_non_incrementally(
+                bundle_path, spec, check_conflicts, versioned_if_macos
+            )
+            incremental_result = calculate_incremental_state(
+                spec, incremental_context.metadata
+            )
+    else:
+        _assemble_non_incrementally(
+            bundle_path, spec, check_conflicts, versioned_if_macos
+        )
+
+    # External tooling (e.g., Xcode) might depend on the timestamp of the bundle
+    bundle_path.touch()
+
+    return incremental_result
+
+
+def _cleanup_output(incremental: bool, path: Path) -> None:
+    if not incremental and path.exists():
+        shutil.rmtree(path)
+    path.mkdir(parents=True, exist_ok=True)
+
+
+def _assemble_non_incrementally(
+    bundle_path: Path,
+    spec: List[BundleSpecItem],
+    check_conflicts: bool,
+    versioned_if_macos: bool,
+) -> None:
+    _LOGGER.info("Assembling bundle non-incrementally.")
+    _cleanup_output(incremental=False, path=bundle_path)
+
+    copied_contents: Dict[Path, str] = {}
+
+    def _copy(src: str, dst: Path, **kwargs: Any) -> None:
+        if check_conflicts:
+            if dst in copied_contents:
+                if filecmp.cmp(src, str(dst), shallow=False):
+                    _LOGGER.info(
+                        f"Found a conflict for destination `{os.path.relpath(dst, bundle_path)}` but the files are identical. Treating as a non-conflict as this can normally happen for universal builds."
+                    )
+                    return
+
+                raise RuntimeError(
+                    f"Found a conflict for destination `{os.path.relpath(dst, bundle_path)}`: `{src}` conflicts with `{copied_contents[dst]}`"
+                )
+        shutil.copy2(src, dst, follow_symlinks=False)
+        if check_conflicts:
+            copied_contents[dst] = src
+
+    symlinks = set()
+
+    for spec_item in spec:
+        source_path = spec_item.src
+        destination_path = bundle_path / spec_item.dst
+
+        destination_path.parent.mkdir(parents=True, exist_ok=True)
+        if spec_item.dst.startswith("Versions/A") and versioned_if_macos:
+            parts = Path(spec_item.dst).parts
+            if len(parts) <= 2:
+                raise RuntimeError(
+                    "Versioned bundles cannot be created from a single copy directly to Versions/A"
+                )
+            symlinks.add(parts[2])
+
+        if os.path.isdir(source_path):
+            shutil.copytree(
+                source_path,
+                destination_path,
+                symlinks=True,
+                dirs_exist_ok=True,
+                copy_function=_copy,
+            )
+        else:
+            _copy(source_path, destination_path)
+
+    _create_symlinks(symlinks, bundle_path)
+
+
+def _create_symlinks(symlinks: set[str], bundle_path: Path) -> None:
+    if symlinks and not Path.exists(bundle_path / "Versions/Current"):
+        os.symlink("A", bundle_path / "Versions/Current")
+    for dir_to_link in symlinks:
+        if not Path.exists(bundle_path / dir_to_link):
+            os.symlink("Versions/Current/" + dir_to_link, bundle_path / dir_to_link)
+
+
+def _assemble_incrementally(
+    bundle_path: Path,
+    spec: List[BundleSpecItem],
+    action_metadata: Dict[Path, str],
+    incremental_state: IncrementalState,
+    check_conflicts: bool,
+    versioned_if_macos: bool,
+) -> List[IncrementalStateItem]:
+    _LOGGER.info("Assembling bundle incrementally.")
+    _cleanup_output(incremental=True, path=bundle_path)
+    _delete_swift_stdlib_files(bundle_path, incremental_state.swift_stdlib_paths)
+    paths_to_delete = {
+        i.destination_relative_to_bundle for i in incremental_state.items
+    }
+    old_digests = {
+        item.destination_relative_to_bundle: item.digest
+        for item in incremental_state.items
+        if item.digest is not None
+    }
+    old_symlink_destinations = {
+        item.destination_relative_to_bundle: item.resolved_symlink
+        for item in incremental_state.items
+        if item.resolved_symlink is not None
+    }
+
+    new_incremental_state = calculate_incremental_state(spec, action_metadata)
+
+    if check_conflicts:
+        _check_path_conflicts(new_incremental_state)
+
+    # Still need to run filtering even when check_conflicts is set, for removing the conflicts with same files
+    new_incremental_state = _filter_conflicting_paths(new_incremental_state)
+
+    new_symlinks = set()
+    versioned_subdir = Path("Versions/A")
+
+    for item in new_incremental_state:
+        # Added file might not be present in old result, need to check first.
+        dst = item.destination_relative_to_bundle
+        if dst in paths_to_delete:
+            paths_to_delete.remove(dst)
+        project_relative_dst = bundle_path / dst
+        if item.digest is not None:
+            new_digest = item.digest
+            old_digest = old_digests.get(dst, None)
+            is_changed = new_digest != old_digest
+        else:
+            assert item.resolved_symlink is not None, (
+                "Expected item to represent a symlink when digest is missing"
+            )
+            new_resolved_symlink = item.resolved_symlink
+            old_resolved_symlink = old_symlink_destinations.get(dst, None)
+            is_changed = new_resolved_symlink != old_resolved_symlink
+            if is_changed:
+                project_relative_dst.unlink()
+        if is_changed:
+            _LOGGER.debug(
+                f"Bundle item at path `{dst}` changed, updating with `{item.source}`."
+            )
+            project_relative_dst.parent.mkdir(parents=True, exist_ok=True)
+            shutil.copy2(item.source, project_relative_dst, follow_symlinks=False)
+            if Path(dst).is_relative_to(versioned_subdir):
+                symlink = Path(dst).relative_to(versioned_subdir).parts[0]
+                new_symlinks.add(symlink)
+
+    if versioned_if_macos:
+        _create_symlinks(new_symlinks, bundle_path)
+
+    for path in paths_to_delete:
+        (bundle_path / path).unlink()
+
+    _cleanup_empty_redundant_directories(
+        bundle_path, incremental_state.items, new_incremental_state
+    )
+
+    return new_incremental_state
+
+
+def _check_path_conflicts(incremental_state: List[IncrementalStateItem]) -> None:
+    """
+    Throws an exception if there are multiple items with the same destination path, and those are different files.
+    """
+    checked = {}
+    for item in incremental_state:
+        dst = item.destination_relative_to_bundle
+        if dst in checked:
+            if item.digest != checked[dst].digest:
+                raise RuntimeError(
+                    f"Found a conflict for destination `{dst}`: `{item.source}` conflicts with `{checked[dst].source}`"
+                )
+            else:
+                _LOGGER.info(
+                    f"Found a conflict for destination `{dst}` but the files are identical. Treating as a non-conflict as this can normally happen for universal builds."
+                )
+        checked[dst] = item
+
+
+def _filter_conflicting_paths(
+    incremental_state: List[IncrementalStateItem],
+) -> List[IncrementalStateItem]:
+    """
+    Filter out conflicting paths leaving only the last item from the conflicting items. That practically means that the last item overrides all other conflicting items which makes:
+    1) incremental build deterministic even when there are multiple conflicting destination paths
+    2) bundling result has the same structure as in Buck1 even when there are multiple conflicting destination paths
+    WARNING: This logic is tightly coupled with how spec items are sorted in `assemble_bundle` method. Don't change unless you fully understand what is going on here.
+    """
+    result = {}
+    for item in incremental_state:
+        dst = item.destination_relative_to_bundle
+        # Keep the same ordering of elements as in incremental state.
+        # That means we don't just overwrite the item for existing key, but need to delete it first.
+        if dst in result:
+            result.pop(dst)
+        result[dst] = item
+    return list(result.values())
+
+
+def _delete_swift_stdlib_files(
+    bundle_path: Path, swift_stdlib_paths: List[Path]
+) -> None:
+    for p in swift_stdlib_paths:
+        path = bundle_path / p
+        if path.is_dir():
+            shutil.rmtree(path)
+        else:
+            path.unlink(missing_ok=True)
+
+
+def _cleanup_empty_redundant_directories(
+    bundle_path: Path,
+    old_state: List[IncrementalStateItem],
+    new_state: List[IncrementalStateItem],
+) -> None:
+    old_directories = {
+        p for item in old_state for p in item.destination_relative_to_bundle.parents
+    }
+    new_directories = {
+        p for item in new_state for p in item.destination_relative_to_bundle.parents
+    }
+    versioned_subdir = Path("Versions/A")
+    for redundant_directory in old_directories - new_directories:
+        shutil.rmtree(bundle_path / redundant_directory, ignore_errors=True)
+        if redundant_directory.parent == versioned_subdir:
+            Path.unlink(bundle_path / redundant_directory.name)
diff --git a/buck2/prelude/apple/tools/bundling/assemble_bundle_types.py b/buck2/prelude/apple/tools/bundling/assemble_bundle_types.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/assemble_bundle_types.py
@@ -0,0 +1,123 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+import functools
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Dict, List, Optional
+
+from apple.tools.code_signing.codesign_bundle import CodesignConfiguration
+
+from .incremental_state import IncrementalState
+
+
+@functools.total_ordering
+@dataclass
+class BundleSpecItem:
+    src: str
+    # Should be bundle relative path, empty string means the root of the bundle
+    dst: str
+    codesign_on_copy: bool = False
+    codesign_entitlements: Optional[str] = None
+    codesign_flags_override: Optional[List[str]] = None
+    extra_codesign_paths: Optional[List[str]] = None
+
+    def __eq__(self: BundleSpecItem, other: Optional[BundleSpecItem]) -> bool:
+        return (
+            other is not None
+            and self.src == other.src
+            and self.dst == other.dst
+            and self.codesign_on_copy == other.codesign_on_copy
+            and self.codesign_entitlements == other.codesign_entitlements
+            and self.codesign_flags_override == other.codesign_flags_override
+            and self.extra_codesign_paths == other.extra_codesign_paths
+        )
+
+    def __ne__(self: BundleSpecItem, other: BundleSpecItem) -> bool:
+        return not self.__eq__(other)
+
+    def __hash__(self: BundleSpecItem) -> int:
+        return hash(
+            (
+                self.src,
+                self.dst,
+                self.codesign_on_copy,
+                self.codesign_entitlements,
+                (
+                    tuple(self.codesign_flags_override)
+                    if self.codesign_flags_override is not None
+                    else hash(None)
+                ),
+                (
+                    tuple(self.extra_codesign_paths)
+                    if self.extra_codesign_paths is not None
+                    else hash(None)
+                ),
+            )
+        )
+
+    def __lt__(self: BundleSpecItem, other: BundleSpecItem) -> bool:
+        return (
+            self.src < other.src
+            or self.dst < other.dst
+            or self.codesign_on_copy < other.codesign_on_copy
+            or (
+                self.codesign_entitlements < other.codesign_entitlements
+                if (
+                    self.codesign_entitlements is not None
+                    and other.codesign_entitlements is not None
+                )
+                else (
+                    self.codesign_entitlements is None
+                    and other.codesign_entitlements is not None
+                )
+            )
+            or (
+                self.codesign_flags_override < other.codesign_flags_override
+                if (
+                    self.codesign_flags_override is not None
+                    and other.codesign_flags_override is not None
+                )
+                else (
+                    self.codesign_flags_override is None
+                    and other.codesign_flags_override is not None
+                )
+            )
+            or (
+                self.extra_codesign_paths < other.extra_codesign_paths
+                if (
+                    self.extra_codesign_paths is not None
+                    and other.extra_codesign_paths is not None
+                )
+                else (
+                    self.extra_codesign_paths is None
+                    and other.extra_codesign_paths is not None
+                )
+            )
+        )
+
+
+@dataclass
+class IncrementalContext:
+    """
+    Additional data you need to bundle incrementally (extra vs when non-incrementally).
+    """
+
+    # Maps buck-project relative path to hash digest of the input file.
+    metadata: Dict[Path, str]
+    # Present when there is a valid incremental state on disk (i.e. previous build produced it).
+    state: Optional[IncrementalState]
+    codesigned: bool
+    codesign_configuration: Optional[CodesignConfiguration]
+    codesign_identity: Optional[str]
+    codesign_arguments: List[str]
+    versioned_if_macos: bool
diff --git a/buck2/prelude/apple/tools/bundling/incremental_state.py b/buck2/prelude/apple/tools/bundling/incremental_state.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/incremental_state.py
@@ -0,0 +1,178 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from io import TextIOBase
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+from apple.tools.code_signing.codesign_bundle import CodesignConfiguration
+
+_VERSION = 8
+
+
+@dataclass
+class IncrementalStateItem:
+    source: Path
+    """
+    Path relative to buck project
+    """
+    destination_relative_to_bundle: Path
+    digest: Optional[str]
+    """
+    Required when the source file is not a symlink
+    """
+    resolved_symlink: Optional[Path]
+    """
+    Required when the source file is a symlink
+    """
+
+
+@dataclass
+class CodesignedOnCopy:
+    path: Path
+    """
+    Path relative to bundle root which needs to be codesigned
+    """
+    entitlements_digest: Optional[str]
+    """
+    Digest of entitlements used when the given path is codesigned on copy
+    """
+    codesign_flags_override: Optional[List[str]]
+    """
+    If present, overrides codesign arguments (which are used for root bundle) when the given path is codesigned on copy
+    """
+    extra_codesign_paths: Optional[List[str]]
+    """
+    If present, a list of extra paths to be codesigned on copy
+    """
+
+    def __hash__(self: CodesignedOnCopy) -> int:
+        return hash(
+            (
+                self.path,
+                self.entitlements_digest,
+                (
+                    tuple(self.codesign_flags_override)
+                    if self.codesign_flags_override is not None
+                    else hash(None)
+                ),
+                (
+                    tuple(self.extra_codesign_paths)
+                    if self.extra_codesign_paths is not None
+                    else hash(None)
+                ),
+            )
+        )
+
+
+@dataclass
+class IncrementalState:
+    """
+    Describes a bundle output from a previous run of this bundling script.
+    """
+
+    items: List[IncrementalStateItem]
+    codesigned: bool
+    codesign_configuration: CodesignConfiguration
+    codesigned_on_copy: List[CodesignedOnCopy]
+    codesign_identity: Optional[str]
+    codesign_arguments: List[str]
+    swift_stdlib_paths: List[Path]
+    versioned_if_macos: bool
+    version: int = _VERSION
+
+
+class IncrementalStateJSONEncoder(json.JSONEncoder):
+    def default(self, o: object) -> object:
+        if isinstance(o, IncrementalState):
+            return {
+                "items": [self.default(i) for i in o.items],
+                "codesigned": o.codesigned,
+                "codesign_configuration": (
+                    o.codesign_configuration.value if o.codesign_configuration else None
+                ),
+                "codesigned_on_copy": [self.default(i) for i in o.codesigned_on_copy],
+                "codesign_identity": o.codesign_identity,
+                "swift_stdlib_paths": [str(p) for p in o.swift_stdlib_paths],
+                "version": o.version,
+                "codesign_arguments": o.codesign_arguments,
+                "versioned_if_macos": o.versioned_if_macos,
+            }
+        elif isinstance(o, IncrementalStateItem):
+            result = {
+                "source": str(o.source),
+                "destination_relative_to_bundle": str(o.destination_relative_to_bundle),
+            }
+            if o.digest is not None:
+                result["digest"] = o.digest
+            if o.resolved_symlink is not None:
+                result["resolved_symlink"] = str(o.resolved_symlink)
+            return result
+        elif isinstance(o, CodesignedOnCopy):
+            result = {}
+            result["path"] = str(o.path)
+            if o.entitlements_digest is not None:
+                result["entitlements_digest"] = str(o.entitlements_digest)
+            if o.codesign_flags_override is not None:
+                result["codesign_flags_override"] = o.codesign_flags_override
+            if o.extra_codesign_paths is not None:
+                result["extra_codesign_paths"] = o.extra_codesign_paths
+            return result
+        else:
+            return super().default(o)
+
+
+def _object_hook(
+    dict: Dict[str, Any],
+) -> Union[IncrementalState, IncrementalStateItem, CodesignedOnCopy]:
+    if "version" in dict:
+        codesign_configuration = dict.pop("codesign_configuration")
+        dict["codesign_configuration"] = (
+            CodesignConfiguration(codesign_configuration)
+            if codesign_configuration
+            else None
+        )
+        dict["swift_stdlib_paths"] = [Path(p) for p in dict.pop("swift_stdlib_paths")]
+        return IncrementalState(**dict)
+    elif "destination_relative_to_bundle" in dict:
+        dict["source"] = Path(dict.pop("source"))
+        dict["destination_relative_to_bundle"] = Path(
+            dict.pop("destination_relative_to_bundle")
+        )
+        dict["digest"] = dict.pop("digest", None)
+        resolved_symlink = dict.pop("resolved_symlink", None)
+        dict["resolved_symlink"] = Path(resolved_symlink) if resolved_symlink else None
+        return IncrementalStateItem(**dict)
+    else:
+        dict["path"] = Path(dict.pop("path"))
+        dict["entitlements_digest"] = dict.pop("entitlements_digest", None)
+        dict["codesign_flags_override"] = dict.pop("codesign_flags_override", None)
+        dict["extra_codesign_paths"] = dict.pop("extra_codesign_paths", None)
+        return CodesignedOnCopy(**dict)
+
+
+def parse_incremental_state(data: TextIOBase) -> IncrementalState:
+    start_stream_position = data.tell()
+    try:
+        incremental_state = json.load(data, object_hook=_object_hook)
+    except BaseException:
+        data.seek(start_stream_position)
+        version = json.load(data)["version"]
+        if version != _VERSION:
+            raise RuntimeError(
+                f"Expected incremental state version to be `{_VERSION}` got `{version}`."
+            )
+        else:
+            raise
+    return incremental_state
diff --git a/buck2/prelude/apple/tools/bundling/incremental_state_test.py b/buck2/prelude/apple/tools/bundling/incremental_state_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/incremental_state_test.py
@@ -0,0 +1,167 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import importlib.resources
+import io
+import json
+import unittest
+from pathlib import Path
+
+from .incremental_state import (
+    CodesignedOnCopy,
+    IncrementalState,
+    IncrementalStateItem,
+    IncrementalStateJSONEncoder,
+    parse_incremental_state,
+)
+
+
+class TestIncrementalState(unittest.TestCase):
+    def test_state_serialization_and_deserialization(self):
+        expected = IncrementalState(
+            items=[
+                IncrementalStateItem(
+                    source=Path("repo/foo.txt"),
+                    destination_relative_to_bundle=Path("foo.txt"),
+                    digest="foo_digest",
+                    resolved_symlink=None,
+                ),
+                IncrementalStateItem(
+                    source=Path("buck-out/bar.txt"),
+                    destination_relative_to_bundle=Path("Resources/bar.txt"),
+                    digest="bar_digest",
+                    resolved_symlink=None,
+                ),
+            ],
+            codesigned=True,
+            codesign_configuration=None,
+            codesigned_on_copy=[
+                CodesignedOnCopy(
+                    path=Path("Resources/bar.txt"),
+                    entitlements_digest=None,
+                    codesign_flags_override=None,
+                    extra_codesign_paths=None,
+                ),
+                CodesignedOnCopy(
+                    path=Path("Resources/baz.txt"),
+                    entitlements_digest="abc",
+                    codesign_flags_override=None,
+                    extra_codesign_paths=None,
+                ),
+                CodesignedOnCopy(
+                    path=Path("Resources/qux.txt"),
+                    entitlements_digest=None,
+                    codesign_flags_override=["--deep", "--force"],
+                    extra_codesign_paths=None,
+                ),
+                CodesignedOnCopy(
+                    path=Path("Resources/Parent.framework"),
+                    entitlements_digest=None,
+                    codesign_flags_override=None,
+                    extra_codesign_paths=["Frameworks/Base.framework"],
+                ),
+            ],
+            codesign_identity="Johnny Appleseed",
+            codesign_arguments=[
+                "--force",
+            ],
+            swift_stdlib_paths=[Path("Frameworks/libswiftCore.dylib")],
+            versioned_if_macos=False,
+        )
+        json_result = json.dumps(expected, cls=IncrementalStateJSONEncoder)
+        result = parse_incremental_state(io.StringIO(json_result))
+        self.assertEqual(
+            result,
+            expected,
+        )
+
+    def _resource_content(self, filename):
+        resources = importlib.resources.files(__package__) / "test_resources"
+        return resources / filename
+
+    def test_valid_state_is_parsed_successfully(self):
+        path = self._resource_content("valid_incremental_state.json")
+        with path.open() as file_content:
+            result = parse_incremental_state(file_content)
+        expected = IncrementalState(
+            items=[
+                IncrementalStateItem(
+                    source=Path("repo/foo.txt"),
+                    destination_relative_to_bundle=Path("foo.txt"),
+                    digest="foo_digest",
+                    resolved_symlink=None,
+                ),
+                IncrementalStateItem(
+                    source=Path("buck-out/bar.txt"),
+                    destination_relative_to_bundle=Path("Resources/bar.txt"),
+                    digest="bar_digest",
+                    resolved_symlink=None,
+                ),
+                IncrementalStateItem(
+                    source=Path("buck-out/bar"),
+                    destination_relative_to_bundle=Path("Resources/bar"),
+                    digest=None,
+                    resolved_symlink=Path("bar.txt"),
+                ),
+            ],
+            codesigned=True,
+            codesign_configuration=None,
+            codesigned_on_copy=[
+                CodesignedOnCopy(
+                    path=Path("Resources/bar.txt"),
+                    entitlements_digest=None,
+                    codesign_flags_override=None,
+                    extra_codesign_paths=None,
+                ),
+                CodesignedOnCopy(
+                    path=Path("Resources/baz.txt"),
+                    entitlements_digest="abc",
+                    codesign_flags_override=None,
+                    extra_codesign_paths=None,
+                ),
+                CodesignedOnCopy(
+                    path=Path("Resources/qux.txt"),
+                    entitlements_digest=None,
+                    codesign_flags_override=["--deep", "--force"],
+                    extra_codesign_paths=None,
+                ),
+                CodesignedOnCopy(
+                    path=Path("Resources/Parent.framework"),
+                    entitlements_digest=None,
+                    codesign_flags_override=None,
+                    extra_codesign_paths=["Frameworks/Base.framework"],
+                ),
+            ],
+            codesign_identity="Johny Appleseed",
+            codesign_arguments=[
+                "--force",
+                "--deep",
+            ],
+            swift_stdlib_paths=[Path("Frameworks/libswiftCore.dylib")],
+            versioned_if_macos=True,
+        )
+        self.assertEqual(
+            result,
+            expected,
+        )
+
+    def test_error_when_invalid_metadata(self):
+        path = self._resource_content("the.broken_json")
+        with self.assertRaises(json.JSONDecodeError):
+            with path.open() as file_content:
+                _ = parse_incremental_state(file_content)
+
+    def test_user_friendly_error_when_metadata_with_newer_version(self):
+        path = self._resource_content("newer_version_incremental_state.json")
+        with self.assertRaises(Exception) as context:
+            with path.open() as file_content:
+                _ = parse_incremental_state(file_content)
+            self.assertEqual(
+                context.exception,
+                RuntimeError("Expected incremental state version to be `2` got `3`."),
+            )
diff --git a/buck2/prelude/apple/tools/bundling/incremental_utils.py b/buck2/prelude/apple/tools/bundling/incremental_utils.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/incremental_utils.py
@@ -0,0 +1,251 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import hashlib
+import logging
+import os
+from pathlib import Path
+from typing import Dict, List, Optional, Set, Tuple
+
+from .assemble_bundle_types import BundleSpecItem, IncrementalContext
+from .incremental_state import CodesignedOnCopy, IncrementalStateItem
+
+FILES_TO_BE_IGNORED: Set[str] = {
+    # Storage of Finder settings, which shouldn't be added when enumerating files from sources
+    ".DS_Store",
+}
+
+
+def should_assemble_incrementally(
+    spec: List[BundleSpecItem], incremental_context: IncrementalContext
+) -> bool:
+    previous_run_state = incremental_context.state
+    if previous_run_state is None:
+        logging.getLogger(__name__).info(
+            "Decided not to assemble incrementally — no incremental state for previous build."
+        )
+        return False
+    if previous_run_state.versioned_if_macos != incremental_context.versioned_if_macos:
+        logging.getLogger(__name__).info(
+            "Decided not to assemble incrementally — current build and previous build have different versioned_if_macos settings."
+        )
+        return False
+
+    previously_codesigned = previous_run_state.codesigned
+    # If previously bundle was not code signed there should be no problems with code signing
+    # currently in incremental mode. Existing binaries could be code signed "on
+    # top" if that's needed.
+    if not previously_codesigned:
+        logging.getLogger(__name__).info(
+            "Decided to assemble incrementally — previous build is not codesigned."
+        )
+        return True
+    # For simplicity and correctness purposes instead of stripping code signatures we
+    # perform non-incremental run.
+    if not incremental_context.codesigned:
+        logging.getLogger(__name__).info(
+            "Decided not to assemble incrementally — current build is not codesigned, while previous build is codesigned."
+        )
+        return False
+    # If previous identity is different from the current one also perform non-incremental run.
+    if previous_run_state.codesign_identity != incremental_context.codesign_identity:
+        logging.getLogger(__name__).info(
+            "Decided not to assemble incrementally — previous vs current builds have mismatching codesigning identities."
+        )
+        return False
+    # If previous codesign arguments are different from the current ones also perform non-incremental run.
+    if previous_run_state.codesign_arguments != incremental_context.codesign_arguments:
+        logging.getLogger(__name__).info(
+            "Decided not to assemble incrementally — previous vs current builds have mismatching codesigning arguments."
+        )
+        return False
+    # If bundle from previous run was signed in a different configuration vs the current run (e.g. dry code signed while now regular code signing is required) perform non-incremental run.
+    if (
+        previous_run_state.codesign_configuration
+        != incremental_context.codesign_configuration
+    ):
+        logging.getLogger(__name__).info(
+            "Decided not to assemble incrementally — previous vs current builds have mismatching codesigning configurations."
+        )
+        return False
+    # If there is an artifact that was code signed on copy in previous run which is
+    # present in current run and not code signed on copy, we should perform
+    # non-incremental run for simplicity and correctness reasons.
+    current_codesigned_on_copy_items = {
+        codesigned_on_copy_item(
+            path=Path(i.dst),
+            entitlements=(
+                Path(i.codesign_entitlements) if i.codesign_entitlements else None
+            ),
+            incremental_context=incremental_context,
+            codesign_flags_override=i.codesign_flags_override,
+            extra_codesign_paths=i.extra_codesign_paths,
+        )
+        for i in spec
+        if i.codesign_on_copy
+    }
+
+    codesigned_on_copy_paths_from_previous_build_which_are_present_in_current_build = _codesigned_on_copy_paths_from_previous_build_which_are_present_in_current_build(
+        previous_run_state.codesigned_on_copy,
+        {Path(i.dst) for i in spec},
+    )
+    codesign_on_copy_paths_are_compatible = codesigned_on_copy_paths_from_previous_build_which_are_present_in_current_build.issubset(
+        current_codesigned_on_copy_items
+    )
+    if not codesign_on_copy_paths_are_compatible:
+        logging.getLogger(__name__).info(
+            f"Decided not to assemble incrementally — there is at least one artifact `{list(codesigned_on_copy_paths_from_previous_build_which_are_present_in_current_build - current_codesigned_on_copy_items)[0]}` that was code signed on copy in previous build which is present in current run and not code signed on copy (or codesigned but with a different set of entitlements, flags or extra paths.)."
+        )
+    return codesign_on_copy_paths_are_compatible
+
+
+def _codesigned_on_copy_paths_from_previous_build_which_are_present_in_current_build(
+    previously_codesigned_on_copy: List[CodesignedOnCopy],
+    all_input_files: Set[Path],
+) -> Set[CodesignedOnCopy]:
+    all_input_files_and_directories = all_input_files | {
+        i for file in all_input_files for i in file.parents
+    }
+    return {
+        i
+        for i in previously_codesigned_on_copy
+        if i.path in all_input_files_and_directories
+    }
+
+
+def _get_new_digest(action_metadata: Dict[Path, str], path: Path) -> str:
+    # A spec source is normally an action input recorded under exactly this
+    # path, and this runs once per file in the bundle, so try the lookup before
+    # resolving: `Path.resolve()` walks and stats every component of the path.
+    digest = action_metadata.get(path)
+    if digest is not None:
+        return digest
+
+    # While a resource file can be in a symlinked folder, like the `ghi/def` example below,
+    # ```
+    # project_root
+    #           ├── abc
+    #           │    └── def
+    #           └── ghi -> abc
+    # ```
+    # In this case, Python would say `ghi/abc` not a symlink. However the `action_metadata` comes
+    # with the actual resolved path (`abc/def`). We need to resolve the path then.
+    # Given Python doesn't think it's a symlink, the `readlink` API wouldn't work either
+    resolved_path = path.resolve()
+
+    cwd = Path.cwd()
+    try:
+        path_relative_to_cwd = resolved_path.relative_to(cwd)
+    except ValueError:
+        # Synthesized paths are those generated by the bundling script itself
+        # (i.e., not an input to the action).
+        #
+        # Need to handle the case where synthesized path (usually in a temp dir)
+        # cannot be relativized against the cwd
+        path_relative_to_cwd = None
+
+    if path_relative_to_cwd and path_relative_to_cwd in action_metadata:
+        return action_metadata[path_relative_to_cwd]
+
+    # The bundler synthesizes some files itself (e.g. build info) rather than
+    # them being action inputs, so they have no entry in the action metadata.
+    hasher = hashlib.sha256()
+    with open(resolved_path, "rb") as f:
+        for chunk in iter(lambda: f.read(1024 * 1024), b""):
+            hasher.update(chunk)
+    return hasher.hexdigest()
+
+
+def calculate_incremental_state(
+    spec: List[BundleSpecItem], action_metadata: Dict[Path, str]
+) -> List[IncrementalStateItem]:
+    """
+    `action_metadata` maps Buck project relative paths to hash digest
+    for every input file of the action which executes this script
+    """
+    result = []
+    source_with_destination_files = _source_with_destination_files(spec)
+    for src, dst in source_with_destination_files:
+        is_symlink = src.is_symlink()
+        new_digest = _get_new_digest(action_metadata, src) if not is_symlink else None
+        resolved_symlink = Path(os.readlink(src)) if is_symlink else None
+        result.append(
+            IncrementalStateItem(
+                source=src,
+                destination_relative_to_bundle=dst,
+                digest=new_digest,
+                resolved_symlink=resolved_symlink,
+            )
+        )
+    return result
+
+
+def _source_with_destination_files(
+    spec: List[BundleSpecItem],
+) -> List[Tuple[Path, Path]]:
+    """
+    Returns:
+        Ordered mapping from source path to destination path (relative to bundle) for every file
+        present in a bundle. Directories that were parts of the spec are split into actual files.
+    """
+    result = []
+    for spec_item in spec:
+        file_or_dir = Path(spec_item.src)
+        if file_or_dir.is_file():
+            if not spec_item.dst:
+                raise RuntimeError(
+                    f'Invalid input bundle spec. File located at {file_or_dir} should not have `""` destination (only directories are allowed to have such value).'
+                )
+            result.append((file_or_dir, Path(spec_item.dst)))
+        elif file_or_dir.is_dir():
+            result.extend(
+                [
+                    (file, spec_item.dst / file.relative_to(file_or_dir))
+                    for file in _list_directory_deterministically(file_or_dir)
+                ]
+            )
+        else:
+            raise RuntimeError(
+                f"Path {file_or_dir} is not a file and not a dir, don't know how to handle it."
+            )
+
+    return [(src, dst) for src, dst in result if src.name not in FILES_TO_BE_IGNORED]
+
+
+def _list_directory_deterministically(directory: Path) -> List[Path]:
+    result = []
+    for current_dir_path, dir_names, file_names in os.walk(directory):
+        result += [Path(os.path.join(current_dir_path, f)) for f in sorted(file_names)]
+        # Sort in order for walk to be deterministic.
+        dir_names.sort()
+    return result
+
+
+def codesigned_on_copy_item(
+    path: Path,
+    entitlements: Optional[Path],
+    incremental_context: IncrementalContext,
+    codesign_flags_override: Optional[List[str]],
+    extra_codesign_paths: Optional[List[str]],
+) -> CodesignedOnCopy:
+    if entitlements is not None:
+        digest = incremental_context.metadata.get(entitlements)
+        if digest is None:
+            raise RuntimeError(
+                f"Expected digest for entitlements file path `{entitlements}` to be present in action metadata."
+            )
+    else:
+        digest = None
+    return CodesignedOnCopy(
+        path=path,
+        entitlements_digest=digest,
+        codesign_flags_override=codesign_flags_override,
+        extra_codesign_paths=extra_codesign_paths,
+    )
diff --git a/buck2/prelude/apple/tools/bundling/incremental_utils_test.py b/buck2/prelude/apple/tools/bundling/incremental_utils_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/incremental_utils_test.py
@@ -0,0 +1,672 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from typing import Generator
+from unittest.mock import patch
+
+from apple.tools.code_signing.codesign_bundle import CodesignConfiguration
+
+from .assemble_bundle_types import BundleSpecItem
+from .incremental_state import CodesignedOnCopy, IncrementalState, IncrementalStateItem
+from .incremental_utils import (
+    calculate_incremental_state,
+    IncrementalContext,
+    should_assemble_incrementally,
+)
+
+try:
+    from contextlib import chdir  # pyre-ignore[21], Python 3.11+
+except ImportError:
+    from contextlib import contextmanager
+
+    @contextmanager
+    def chdir(path: os.PathLike) -> Generator[None, None, None]:
+        cwd = os.getcwd()
+        try:
+            os.chdir(path)
+            yield
+        finally:
+            os.chdir(cwd)
+
+
+class TestIncrementalUtils(unittest.TestCase):
+    maxDiff = None
+
+    def test_not_run_incrementally_when_previous_build_not_incremental(self):
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+                codesign_on_copy=False,
+            )
+        ]
+        incremental_context = IncrementalContext(
+            metadata={Path("foo"): "digest"},
+            state=None,
+            codesigned=False,
+            codesign_configuration=None,
+            codesign_identity=None,
+            codesign_arguments=[],
+            versioned_if_macos=True,
+        )
+        self.assertFalse(should_assemble_incrementally(spec, incremental_context))
+
+    def test_run_incrementally_when_previous_build_not_codesigned(self):
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+                codesign_on_copy=False,
+            )
+        ]
+        incremental_context = IncrementalContext(
+            metadata={Path("foo"): "digest"},
+            state=IncrementalState(
+                items=[
+                    IncrementalStateItem(
+                        source=Path("src/foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="digest",
+                        resolved_symlink=None,
+                    )
+                ],
+                codesigned=False,
+                codesign_configuration=None,
+                codesigned_on_copy=[],
+                codesign_identity=None,
+                codesign_arguments=[],
+                versioned_if_macos=True,
+                swift_stdlib_paths=[],
+            ),
+            codesigned=True,
+            codesign_configuration=None,
+            codesign_identity=None,
+            codesign_arguments=[],
+            versioned_if_macos=True,
+        )
+        self.assertTrue(should_assemble_incrementally(spec, incremental_context))
+
+    def test_not_run_incrementally_when_previous_build_codesigned_and_current_is_not(
+        self,
+    ):
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+                codesign_on_copy=False,
+            )
+        ]
+        incremental_context = IncrementalContext(
+            metadata={Path("foo"): "digest"},
+            state=IncrementalState(
+                items=[
+                    IncrementalStateItem(
+                        source=Path("src/foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="digest",
+                        resolved_symlink=None,
+                    )
+                ],
+                codesigned=True,
+                codesign_configuration=None,
+                codesigned_on_copy=[],
+                codesign_identity=None,
+                codesign_arguments=[],
+                versioned_if_macos=True,
+                swift_stdlib_paths=[],
+            ),
+            codesigned=False,
+            codesign_configuration=None,
+            codesign_identity=None,
+            codesign_arguments=[],
+            versioned_if_macos=True,
+        )
+        self.assertFalse(should_assemble_incrementally(spec, incremental_context))
+        # Check that behavior changes when both builds are codesigned
+        incremental_context.codesigned = True
+        self.assertTrue(should_assemble_incrementally(spec, incremental_context))
+
+    def test_not_run_incrementally_when_previous_build_codesigned_with_different_identity(
+        self,
+    ):
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+                codesign_on_copy=False,
+            )
+        ]
+        incremental_context = IncrementalContext(
+            metadata={Path("foo"): "digest"},
+            state=IncrementalState(
+                items=[
+                    IncrementalStateItem(
+                        source=Path("src/foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="digest",
+                        resolved_symlink=None,
+                    )
+                ],
+                codesigned=True,
+                codesign_configuration=None,
+                codesigned_on_copy=[],
+                codesign_identity="old_identity",
+                codesign_arguments=[],
+                versioned_if_macos=True,
+                swift_stdlib_paths=[],
+            ),
+            codesigned=True,
+            codesign_configuration=None,
+            codesign_identity="new_identity",
+            codesign_arguments=[],
+            versioned_if_macos=True,
+        )
+        self.assertFalse(should_assemble_incrementally(spec, incremental_context))
+        # Check that behavior changes when identities are same
+        incremental_context.state.codesign_identity = "same_identity"
+        incremental_context.codesign_identity = "same_identity"
+        self.assertTrue(should_assemble_incrementally(spec, incremental_context))
+
+    def test_run_incrementally_when_codesign_on_copy_paths_match(self):
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+                codesign_on_copy=True,
+            ),
+            BundleSpecItem(
+                src="src/bar",
+                dst="bar",
+                codesign_on_copy=True,
+            ),
+            BundleSpecItem(
+                src="src/baz",
+                dst="baz",
+                codesign_on_copy=True,
+                codesign_entitlements="entitlements.plist",
+            ),
+        ]
+        incremental_context = IncrementalContext(
+            metadata={
+                Path("src/foo"): "digest",
+                Path("src/baz"): "digest2",
+                Path("entitlements.plist"): "entitlements_digest",
+            },
+            state=IncrementalState(
+                items=[
+                    IncrementalStateItem(
+                        source=Path("src/foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="digest",
+                        resolved_symlink=None,
+                    ),
+                    IncrementalStateItem(
+                        source=Path("src/baz"),
+                        destination_relative_to_bundle=Path("baz"),
+                        digest="digest2",
+                        resolved_symlink=None,
+                    ),
+                ],
+                codesigned=True,
+                codesign_configuration=None,
+                codesigned_on_copy=[
+                    CodesignedOnCopy(
+                        path=Path("foo"),
+                        entitlements_digest=None,
+                        codesign_flags_override=None,
+                        extra_codesign_paths=None,
+                    ),
+                    CodesignedOnCopy(
+                        path=Path("baz"),
+                        entitlements_digest="entitlements_digest",
+                        codesign_flags_override=None,
+                        extra_codesign_paths=None,
+                    ),
+                ],
+                codesign_identity="same_identity",
+                codesign_arguments=[],
+                versioned_if_macos=True,
+                swift_stdlib_paths=[],
+            ),
+            codesigned=True,
+            codesign_configuration=None,
+            codesign_identity="same_identity",
+            codesign_arguments=[],
+            versioned_if_macos=True,
+        )
+        self.assertTrue(should_assemble_incrementally(spec, incremental_context))
+
+    def test_not_run_incrementally_when_codesign_on_copy_paths_mismatch(self):
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+                # want it to be not codesigned in new build
+                codesign_on_copy=False,
+            )
+        ]
+        incremental_context = IncrementalContext(
+            metadata={Path("src/foo"): "digest"},
+            state=IncrementalState(
+                items=[
+                    IncrementalStateItem(
+                        source=Path("src/foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="digest",
+                        resolved_symlink=None,
+                    )
+                ],
+                codesigned=True,
+                codesign_configuration=None,
+                # but it was codesigned in old build
+                codesigned_on_copy=[
+                    CodesignedOnCopy(
+                        path=Path("foo"),
+                        entitlements_digest=None,
+                        codesign_flags_override=None,
+                        extra_codesign_paths=None,
+                    )
+                ],
+                codesign_identity="same_identity",
+                codesign_arguments=[],
+                versioned_if_macos=True,
+                swift_stdlib_paths=[],
+            ),
+            codesigned=True,
+            codesign_configuration=None,
+            codesign_identity="same_identity",
+            codesign_arguments=[],
+            versioned_if_macos=True,
+        )
+        self.assertFalse(should_assemble_incrementally(spec, incremental_context))
+        spec[0].codesign_on_copy = True
+        self.assertTrue(should_assemble_incrementally(spec, incremental_context))
+
+    def test_not_run_incrementally_when_codesign_on_copy_entitlements_mismatch(self):
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+                codesign_on_copy=True,
+                codesign_entitlements="baz/entitlements.plist",
+            )
+        ]
+        incremental_context = IncrementalContext(
+            metadata={
+                Path("src/foo"): "digest",
+                Path("baz/entitlements.plist"): "new_digest",
+            },
+            state=IncrementalState(
+                items=[
+                    IncrementalStateItem(
+                        source=Path("src/foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="digest",
+                        resolved_symlink=None,
+                    )
+                ],
+                codesigned=True,
+                codesign_configuration=None,
+                codesigned_on_copy=[
+                    CodesignedOnCopy(
+                        path=Path("foo"),
+                        entitlements_digest="old_digest",
+                        codesign_flags_override=None,
+                        extra_codesign_paths=None,
+                    )
+                ],
+                codesign_identity="same_identity",
+                codesign_arguments=[],
+                versioned_if_macos=True,
+                swift_stdlib_paths=[],
+            ),
+            codesigned=True,
+            codesign_configuration=None,
+            codesign_identity="same_identity",
+            codesign_arguments=[],
+            versioned_if_macos=True,
+        )
+        self.assertFalse(should_assemble_incrementally(spec, incremental_context))
+        incremental_context.metadata[Path("baz/entitlements.plist")] = "old_digest"
+        self.assertTrue(should_assemble_incrementally(spec, incremental_context))
+
+    def test_not_run_incrementally_when_codesign_on_copy_flags_mismatch(self):
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+                codesign_on_copy=True,
+                codesign_flags_override=["--force"],
+            )
+        ]
+        incremental_context = IncrementalContext(
+            metadata={
+                Path("src/foo"): "digest",
+            },
+            state=IncrementalState(
+                items=[
+                    IncrementalStateItem(
+                        source=Path("src/foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="digest",
+                        resolved_symlink=None,
+                    )
+                ],
+                codesigned=True,
+                codesign_configuration=None,
+                codesigned_on_copy=[
+                    CodesignedOnCopy(
+                        path=Path("foo"),
+                        entitlements_digest=None,
+                        codesign_flags_override=["--force", "--deep"],
+                        extra_codesign_paths=None,
+                    )
+                ],
+                codesign_identity="same_identity",
+                codesign_arguments=[],
+                versioned_if_macos=True,
+                swift_stdlib_paths=[],
+            ),
+            codesigned=True,
+            codesign_configuration=None,
+            codesign_identity="same_identity",
+            codesign_arguments=[],
+            versioned_if_macos=True,
+        )
+        self.assertFalse(should_assemble_incrementally(spec, incremental_context))
+        incremental_context.state.codesigned_on_copy[0].codesign_flags_override = [
+            "--force"
+        ]
+        self.assertTrue(should_assemble_incrementally(spec, incremental_context))
+
+    def test_not_run_incrementally_when_extra_codesign_paths_mismatch(self):
+        extra_codesign_paths_before = ["Frameworks/Base.framework"]
+        extra_codesign_paths_after = [
+            "Frameworks/Base.framework",
+            "Frameworks/Extra.framework",
+        ]
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+                codesign_on_copy=True,
+                extra_codesign_paths=extra_codesign_paths_after,
+            )
+        ]
+        incremental_context = IncrementalContext(
+            metadata={
+                Path("src/foo"): "digest",
+            },
+            state=IncrementalState(
+                items=[
+                    IncrementalStateItem(
+                        source=Path("src/foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="digest",
+                        resolved_symlink=None,
+                    )
+                ],
+                codesigned=True,
+                codesign_configuration=None,
+                codesigned_on_copy=[
+                    CodesignedOnCopy(
+                        path=Path("foo"),
+                        entitlements_digest=None,
+                        codesign_flags_override=None,
+                        extra_codesign_paths=extra_codesign_paths_before,
+                    )
+                ],
+                codesign_identity="same_identity",
+                codesign_arguments=[],
+                versioned_if_macos=True,
+                swift_stdlib_paths=[],
+            ),
+            codesigned=True,
+            codesign_configuration=None,
+            codesign_identity="same_identity",
+            codesign_arguments=[],
+            versioned_if_macos=True,
+        )
+        self.assertFalse(should_assemble_incrementally(spec, incremental_context))
+        incremental_context.state.codesigned_on_copy[
+            0
+        ].extra_codesign_paths = extra_codesign_paths_after
+        self.assertTrue(should_assemble_incrementally(spec, incremental_context))
+
+    def test_not_run_incrementally_when_codesign_arguments_mismatch(self):
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+            )
+        ]
+        incremental_context = IncrementalContext(
+            metadata={
+                Path("src/foo"): "digest",
+            },
+            state=IncrementalState(
+                items=[
+                    IncrementalStateItem(
+                        source=Path("src/foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="digest",
+                        resolved_symlink=None,
+                    )
+                ],
+                codesigned=True,
+                codesign_configuration=None,
+                codesigned_on_copy=[],
+                codesign_identity="same_identity",
+                codesign_arguments=["--force"],
+                swift_stdlib_paths=[],
+                versioned_if_macos=True,
+            ),
+            codesigned=True,
+            codesign_configuration=None,
+            codesign_identity="same_identity",
+            codesign_arguments=["--force", "--deep"],
+            versioned_if_macos=True,
+        )
+        self.assertFalse(should_assemble_incrementally(spec, incremental_context))
+        incremental_context.codesign_arguments = ["--force"]
+        self.assertTrue(should_assemble_incrementally(spec, incremental_context))
+
+    def test_not_run_incrementally_when_codesign_configurations_mismatch(self):
+        spec = [
+            BundleSpecItem(
+                src="src/foo",
+                dst="foo",
+                codesign_on_copy=True,
+            )
+        ]
+        incremental_context = IncrementalContext(
+            metadata={Path("src/foo"): "digest"},
+            state=IncrementalState(
+                items=[
+                    IncrementalStateItem(
+                        source=Path("src/foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="digest",
+                        resolved_symlink=None,
+                    )
+                ],
+                codesigned=True,
+                # Dry codesigned in old build
+                codesign_configuration=CodesignConfiguration.dryRun,
+                codesigned_on_copy=[
+                    CodesignedOnCopy(
+                        path=Path("foo"),
+                        entitlements_digest=None,
+                        codesign_flags_override=None,
+                        extra_codesign_paths=None,
+                    )
+                ],
+                codesign_identity="same_identity",
+                codesign_arguments=[],
+                versioned_if_macos=True,
+                swift_stdlib_paths=[],
+            ),
+            codesigned=True,
+            codesign_configuration=CodesignConfiguration.dryRun,
+            codesign_identity="same_identity",
+            codesign_arguments=[],
+            versioned_if_macos=True,
+        )
+        # Canary
+        self.assertTrue(should_assemble_incrementally(spec, incremental_context))
+        # Now we want a regular signing in new build
+        incremental_context.codesign_configuration = None
+        self.assertFalse(should_assemble_incrementally(spec, incremental_context))
+
+    def test_calculate_incremental_state(self):
+        with tempfile.TemporaryDirectory() as project_root, chdir(project_root):
+            # project_root
+            #           ├── foo
+            #           ├── bar
+            #           │    ├── baz
+            #           │    └── qux -> baz
+            #           ├── abc
+            #           │    └── def
+            #           └── ghi -> abc
+            Path("foo").write_text("hello")
+            bar_path = Path("bar")
+            bar_path.mkdir()
+            (bar_path / "baz").write_text("world")
+            (bar_path / "qux").symlink_to("baz")
+            abc_path = Path("abc")
+            abc_path.mkdir()
+            (abc_path / "def").write_text("yo")
+            Path("ghi").symlink_to("abc")
+
+            action_metadata = {
+                Path("foo"): "hash(foo)",
+                Path("bar/baz"): "hash(baz)",
+                Path("abc/def"): "hash(def)",
+            }
+            spec = [
+                BundleSpecItem(
+                    src="foo",
+                    dst="foo",
+                    codesign_on_copy=False,
+                ),
+                BundleSpecItem(
+                    src="bar",
+                    dst="tux",
+                    codesign_on_copy=True,
+                ),
+                BundleSpecItem(
+                    src="ghi",
+                    dst="ghi",
+                    codesign_on_copy=True,
+                ),
+            ]
+            state = calculate_incremental_state(spec, action_metadata)
+            self.assertEqual(
+                state,
+                [
+                    IncrementalStateItem(
+                        source=Path("foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="hash(foo)",
+                        resolved_symlink=None,
+                    ),
+                    IncrementalStateItem(
+                        source=Path("bar/baz"),
+                        destination_relative_to_bundle=Path("tux/baz"),
+                        digest="hash(baz)",
+                        resolved_symlink=None,
+                    ),
+                    IncrementalStateItem(
+                        source=Path("bar/qux"),
+                        destination_relative_to_bundle=Path("tux/qux"),
+                        digest=None,
+                        resolved_symlink=Path("baz"),
+                    ),
+                    IncrementalStateItem(
+                        source=Path("ghi/def"),
+                        destination_relative_to_bundle=Path("ghi/def"),
+                        digest="hash(def)",
+                        resolved_symlink=None,
+                    ),
+                ],
+            )
+
+    def test_calculate_incremental_state_prefers_action_metadata_to_resolving(
+        self,
+    ) -> None:
+        with tempfile.TemporaryDirectory() as project_root, chdir(project_root):
+            Path("foo").write_text("hello")
+            action_metadata = {Path("foo"): "hash(foo)"}
+            spec = [BundleSpecItem(src="foo", dst="foo")]
+            with patch.object(
+                Path, "resolve", side_effect=AssertionError("path was resolved")
+            ):
+                state = calculate_incremental_state(spec, action_metadata)
+            self.assertEqual(
+                state,
+                [
+                    IncrementalStateItem(
+                        source=Path("foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="hash(foo)",
+                        resolved_symlink=None,
+                    ),
+                ],
+            )
+
+    def test_calculate_incremental_state_with_ds_store(self) -> None:
+        with tempfile.TemporaryDirectory() as project_root, chdir(project_root):
+            # project_root
+            #           ├── foo
+            #           └── bar
+            #                ├── baz
+            #                └── .DS_Store
+            Path("foo").write_text("hello")
+            bar_path = Path("bar")
+            bar_path.mkdir()
+            (bar_path / "baz").write_text("world")
+            (bar_path / ".DS_Store").touch()
+
+            action_metadata = {
+                Path("foo"): "hash(foo)",
+                Path("bar/baz"): "hash(baz)",
+            }
+            spec = [
+                BundleSpecItem(
+                    src="foo",
+                    dst="foo",
+                    codesign_on_copy=False,
+                ),
+                BundleSpecItem(
+                    src="bar",
+                    dst="bar",
+                    codesign_on_copy=True,
+                ),
+            ]
+            state = calculate_incremental_state(spec, action_metadata)
+            self.assertEqual(
+                state,
+                [
+                    IncrementalStateItem(
+                        source=Path("foo"),
+                        destination_relative_to_bundle=Path("foo"),
+                        digest="hash(foo)",
+                        resolved_symlink=None,
+                    ),
+                    IncrementalStateItem(
+                        source=Path("bar/baz"),
+                        destination_relative_to_bundle=Path("bar/baz"),
+                        digest="hash(baz)",
+                        resolved_symlink=None,
+                    ),
+                ],
+            )
diff --git a/buck2/prelude/apple/tools/bundling/logging_utils.py b/buck2/prelude/apple/tools/bundling/logging_utils.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/logging_utils.py
@@ -0,0 +1,62 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+from __future__ import annotations
+
+import logging
+import sys
+from pathlib import Path
+
+
+def configure_logging(
+    stderr_level: int,
+    file_level: int,
+    log_path: Path | None,
+) -> None:
+    stderr_handler = logging.StreamHandler()
+    stderr_handler.setLevel(stderr_level)
+    log_format = (
+        "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
+    )
+    stderr_handler.setFormatter(
+        _ColoredLogFormatter(log_format)
+        if sys.stderr.isatty()
+        else logging.Formatter(log_format)
+    )
+
+    handlers: list[logging.Handler] = [stderr_handler]
+    if log_path is not None:
+        # Declared log outputs must exist even when no messages are emitted, and
+        # incremental runs must not retain messages from an earlier invocation.
+        log_path.write_text("")
+        file_handler = logging.FileHandler(log_path, encoding="utf-8")
+        file_handler.setFormatter(logging.Formatter(log_format))
+        file_handler.setLevel(file_level)
+        handlers.append(file_handler)
+
+    logging.basicConfig(level=logging.DEBUG, handlers=handlers)
+
+
+class _ColoredLogFormatter(logging.Formatter):
+    _colors: dict[int, str] = {
+        logging.DEBUG: "\x1b[m",
+        logging.INFO: "\x1b[37m",
+        logging.WARNING: "\x1b[33m",
+        logging.ERROR: "\x1b[31m",
+        logging.CRITICAL: "\x1b[1;31m",
+    }
+    _reset_color = "\x1b[0m"
+
+    def __init__(self, text_format: str) -> None:
+        self.text_format = text_format
+
+    def format(self, record: logging.LogRecord) -> str:
+        formatter = logging.Formatter(
+            self._colors.get(record.levelno, "") + self.text_format + self._reset_color
+        )
+        return formatter.format(record)
diff --git a/buck2/prelude/apple/tools/bundling/main.py b/buck2/prelude/apple/tools/bundling/main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/main.py
@@ -0,0 +1,748 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+from __future__ import annotations
+
+import argparse
+import cProfile
+import json
+import logging
+import os
+import pstats
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import List, Optional
+
+from apple.tools.code_signing.codesign_bundle import (
+    codesign_bundle,
+    CodesignConfiguration,
+    CodesignedPath,
+    write_empty_codesign_manifest,
+)
+from apple.tools.code_signing.signing_context_types import (
+    AdhocSigningContext,
+    selection_profile_context_from_signing_context,
+    SigningContextWithProfileSelection,
+)
+from apple.tools.re_compatibility_utils.writable import make_dir_recursively_writable
+
+from .action_metadata import action_metadata_if_present
+from .assemble_bundle import assemble_bundle
+from .assemble_bundle_types import BundleSpecItem, IncrementalContext
+from .incremental_state import (
+    IncrementalState,
+    IncrementalStateItem,
+    IncrementalStateJSONEncoder,
+    parse_incremental_state,
+)
+from .incremental_utils import codesigned_on_copy_item
+from .logging_utils import configure_logging
+from .signing_context import (
+    add_args_for_bundling_execution,
+    add_args_for_signing_context_path,
+)
+from .signing_context_data import (
+    load_signing_context_data_from_file,
+    SigningContextData,
+)
+from .swift_support import run_swift_stdlib_tool, SwiftSupportArguments
+
+
+_METADATA_PATH_KEY = "ACTION_METADATA"
+
+
+def _args_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(
+        description="Tool which assembles the Apple bundle."
+    )
+    parser.add_argument(
+        "--output",
+        metavar="</path/to/app.bundle>",
+        type=Path,
+        required=True,
+        help="Absolute path to Apple bundle result.",
+    )
+    parser.add_argument(
+        "--spec",
+        metavar="<Spec.json>",
+        type=Path,
+        required=True,
+        help="Path to file with JSON representing the bundle contents. It should contain a dictionary which maps bundle relative destination paths to source paths.",
+    )
+    parser.add_argument(
+        "--codesign-tool",
+        metavar="<codesign>",
+        type=Path,
+        required=False,
+        help="Path to code signing utility. If not provided standard `codesign` tool will be used.",
+    )
+    parser.add_argument(
+        "--codesign-manifest",
+        metavar="<manifest_file>",
+        type=Path,
+        required=False,
+        help="Path to a file containing codesign invocations.",
+    )
+    parser.add_argument(
+        "--codesign-args",
+        type=str,
+        default=[],
+        required=False,
+        action="append",
+        help="Add additional args to pass during codesigning. Pass as`--codesign-args=ARG` to ensure correct arg parsing.",
+    )
+    parser.add_argument(
+        "--codesign-configuration",
+        required=False,
+        type=CodesignConfiguration,
+        choices=[e.value for e in CodesignConfiguration],
+        help=f"""
+            Augments how code signing is run.
+            Pass `{CodesignConfiguration.fastAdhoc}` to skip adhoc signing bundles if the executables are already adhoc signed.
+            Pass `{CodesignConfiguration.executionBypass}` to skip executing the actual codesigning commands.
+            Pass `{CodesignConfiguration.dryRun}` for code signing to be run in dry mode (instead of actual signing only .plist
+            files with signing parameters will be generated in the root of each signed bundle).
+        """,
+    )
+    parser.add_argument(
+        "--fast-adhoc-signing-probe-enabled",
+        action="store_true",
+        help="Allow fast-adhoc signing to consult the bundled signature probe tool when it is available.",
+    )
+    parser.add_argument(
+        "--incremental-state",
+        metavar="<IncrementalState.json>",
+        type=Path,
+        required=False,
+        help="Required if script is run in incremental mode. Path to file with JSON which describes the contents of bundle built previously.",
+    )
+    parser.add_argument(
+        "--profile-output",
+        metavar="<ProfileOutput.txt>",
+        type=Path,
+        required=False,
+        help="Path to the profiling output. If present profiling will be enabled.",
+    )
+    parser.add_argument(
+        "--log-level-stderr",
+        choices=["debug", "info", "warning", "error", "critical"],
+        type=str,
+        required=False,
+        default="warning",
+        help="Logging level for messages written to stderr.",
+    )
+    parser.add_argument(
+        "--log-level-file",
+        choices=["debug", "info", "warning", "error", "critical"],
+        type=str,
+        required=False,
+        default="info",
+        help="Logging level for messages written to a log file.",
+    )
+    parser.add_argument(
+        "--binary-destination",
+        metavar="<Binary>",
+        type=Path,
+        required=False,
+        help="Required if swift support was requested. Bundle relative destination path to bundle binary.",
+    )
+    parser.add_argument(
+        "--frameworks-destination",
+        metavar="<Frameworks>",
+        type=Path,
+        required=False,
+        help="Required if swift support was requested. Bundle relative destination path to frameworks directory.",
+    )
+    parser.add_argument(
+        "--extensionkit-extensions-destination",
+        metavar="<ExtensionKitExtensions>",
+        type=Path,
+        required=False,
+        help="Required if swift support was requested. Bundle relative destination path to ExtensionKit Extensions directory.",
+    )
+    parser.add_argument(
+        "--plugins-destination",
+        metavar="<Plugins>",
+        type=Path,
+        required=False,
+        help="Required if swift support was requested. Bundle relative destination path to plugins directory.",
+    )
+    parser.add_argument(
+        "--resources-destination",
+        metavar="<Resources>",
+        type=Path,
+        required=False,
+        help="Required if swift support was requested. Bundle relative destination path to resources directory.",
+    )
+    parser.add_argument(
+        "--appclips-destination",
+        metavar="<AppClips>",
+        type=Path,
+        required=False,
+        help="Required if swift support was requested. Bundle relative destination path to appclips directory.",
+    )
+    parser.add_argument(
+        "--sdk-root",
+        metavar="<path/to/SDK>",
+        type=Path,
+        required=False,
+        help="Required if swift support was requested. Path to SDK root.",
+    )
+    parser.add_argument(
+        "--swift-stdlib-command",
+        metavar='<"/swift/stdlib/tool --foo bar/qux">',
+        type=str,
+        required=False,
+        help="Swift stdlib command prefix. If present, output bundle will contain needed Swift standard libraries (to support the lack of ABI stability or certain backports usage).",
+    )
+    parser.add_argument(
+        "--check-conflicts",
+        action="store_true",
+        help="Check there are no path conflicts between different source parts of the bundle if enabled.",
+    )
+    parser.add_argument(
+        "--versioned-if-macos",
+        action="store_true",
+        help="Create symlinks for versioned macOS bundle",
+    )
+    parser.add_argument(
+        "--include-build-info-file",
+        action="store_true",
+        help="Include the build info file in the assembled bundle.",
+    )
+    parser.add_argument(
+        "--bundle-telemetry-logger",
+        metavar="<path/to/logger>",
+        type=Path,
+        required=False,
+        help="Path to bundle telemetry logger tool. If provided, will be invoked after bundle assembly completes.",
+    )
+
+    add_args_for_bundling_execution(parser)
+    add_args_for_signing_context_path(parser)
+
+    return parser
+
+
+def _get_codesigned_paths_for_spec_item(
+    bundle_path: CodesignedPath,
+    args: argparse.Namespace,
+    item: BundleSpecItem,
+    codesign_configuration: Optional[CodesignConfiguration],
+) -> List[CodesignedPath]:
+    if not item.codesign_on_copy:
+        return []
+
+    entitlements = (
+        Path(item.codesign_entitlements) if item.codesign_entitlements else None
+    )
+    flags = (
+        item.codesign_flags_override
+        if (item.codesign_flags_override is not None)
+        else args.codesign_args
+    )
+
+    codesigned_paths = []
+    extra_file_paths = []
+
+    is_dry_run = codesign_configuration is CodesignConfiguration.dryRun
+    extra_codesign_paths = item.extra_codesign_paths or []
+    for extra_codesign_path in extra_codesign_paths:
+        path = bundle_path.path / item.dst / extra_codesign_path
+        if not path.exists():
+            raise RuntimeError(
+                f"Found non-existing extra path to codesign: {extra_codesign_path} for {item.src}"
+            )
+
+        if path.is_file() and is_dry_run:
+            # In dry-run mode, non-bundle items should be signed as part of the containing bundle.
+            extra_file_paths.append(extra_codesign_path)
+        else:
+            codesigned_paths.append(
+                CodesignedPath(
+                    path=path,
+                    entitlements=entitlements,
+                    flags=flags,
+                    extra_file_paths=None,
+                )
+            )
+
+    codesigned_paths.append(
+        CodesignedPath(
+            path=bundle_path.path / item.dst,
+            entitlements=entitlements,
+            flags=flags,
+            extra_file_paths=extra_file_paths,
+        )
+    )
+
+    return codesigned_paths
+
+
+def _get_codesigned_paths_from_spec(
+    bundle_path: CodesignedPath,
+    args: argparse.Namespace,
+    spec: List[BundleSpecItem],
+) -> List[CodesignedPath]:
+    codesigned_paths = []
+    for item in spec:
+        codesigned_paths += _get_codesigned_paths_for_spec_item(
+            bundle_path=bundle_path,
+            args=args,
+            item=item,
+            codesign_configuration=args.codesign_configuration,
+        )
+    return codesigned_paths
+
+
+def _load_signing_context(
+    args: argparse.Namespace,
+    temp_dir: Path,
+) -> tuple[AdhocSigningContext | SigningContextWithProfileSelection | None, str | None]:
+    if not args.codesign:
+        return None, None
+
+    signing_context_data = load_signing_context_data_from_file(
+        args.signing_context_path
+    )
+    _materialize_selected_profile(signing_context_data, temp_dir)
+    return signing_context_data.signing_context, signing_context_data.selected_identity
+
+
+def _main(spec_temp_dir: str) -> None:
+    args_parser = _args_parser()
+    args = args_parser.parse_args()
+
+    uname_info = os.uname()
+    sysname = uname_info.sysname
+    major_release = int(uname_info.release.split(".")[0])
+
+    # macOS 26.0.0 Tahoe no longer supports SHA1 as an option in the codesign tool.
+    # Note: This is safe to remove along with the code that adds the digest-algorithm code
+    # in apple_bundle_wrapping_rule.bzl once we are migrated to macOS 26.0.
+    if (
+        "--digest-algorithm=sha1" in args.codesign_args
+        and sysname == "Darwin"
+        and major_release
+        >= 25  # Darwin kernel release 25.0.0 corresponds to macOS 26.0.0 Tahoe
+    ):
+        args.codesign_args.remove("--digest-algorithm=sha1")
+
+    configure_logging(
+        stderr_level=getattr(logging, args.log_level_stderr.upper()),
+        file_level=getattr(logging, args.log_level_file.upper()),
+        log_path=args.log_file,
+    )
+
+    pr = cProfile.Profile()
+    profiling_enabled = args.profile_output is not None
+    if profiling_enabled:
+        pr.enable()
+
+    signing_context, selected_identity_argument = _load_signing_context(
+        args,
+        Path(spec_temp_dir),
+    )
+
+    with args.spec.open(mode="rb") as spec_file:
+        spec = json.load(spec_file, object_hook=lambda d: BundleSpecItem(**d))
+        spec = _deduplicate_spec(spec)
+
+    incremental_context = _incremental_context(
+        incremenatal_state_path=args.incremental_state,
+        codesigned=args.codesign,
+        codesign_configuration=args.codesign_configuration,
+        codesign_identity=selected_identity_argument,
+        codesign_arguments=args.codesign_args,
+        versioned_if_macos=args.versioned_if_macos,
+    )
+
+    if args.include_build_info_file:
+        _amend_spec_with_build_uuid(
+            spec=spec,
+            resources_destination=args.resources_destination,
+            tmp_dir=Path(spec_temp_dir),
+        )
+
+    incremental_state = assemble_bundle(
+        spec=spec,
+        bundle_path=args.output,
+        incremental_context=incremental_context,
+        check_conflicts=args.check_conflicts,
+        versioned_if_macos=args.versioned_if_macos,
+    )
+
+    swift_support_args = _swift_support_arguments(
+        args_parser,
+        args,
+    )
+
+    if swift_support_args:
+        swift_stdlib_paths = run_swift_stdlib_tool(
+            bundle_path=args.output,
+            args=swift_support_args,
+        )
+    else:
+        swift_stdlib_paths = []
+
+    prepared_entitlements_path: Optional[Path] = None
+    telemetry_tmp_dir: Optional[tempfile.TemporaryDirectory[str]] = None
+
+    if args.codesign:
+        # Vendored frameworks/bundles could already be pre-signed, in which case,
+        # re-signing them requires modifying them. On RE, the umask is such that
+        # copied files (when constructing the bundle) are not writable.
+        make_dir_recursively_writable(args.output)
+        if signing_context is None:
+            raise RuntimeError(
+                "Expected signing context to be created before bundling is done if codesign is requested."
+            )
+
+        bundle_path = CodesignedPath(
+            path=args.output,
+            entitlements=args.entitlements,
+            flags=args.codesign_args,
+            extra_file_paths=None,
+        )
+        codesign_on_copy_paths = _get_codesigned_paths_from_spec(
+            bundle_path=bundle_path, spec=spec, args=args
+        ) + [
+            CodesignedPath(
+                path=bundle_path.path / path,
+                entitlements=None,
+                flags=args.codesign_args,
+                extra_file_paths=None,
+            )
+            for path in swift_stdlib_paths
+        ]
+
+        if args.bundle_telemetry_logger:
+            telemetry_tmp_dir = tempfile.TemporaryDirectory()
+            prepared_entitlements_path = (
+                Path(telemetry_tmp_dir.name) / "prepared_entitlements.plist"
+            )
+
+        codesign_bundle(
+            bundle_path=bundle_path,
+            signing_context=signing_context,
+            platform=args.platform,
+            codesign_on_copy_paths=codesign_on_copy_paths,
+            codesign_tool=args.codesign_tool,
+            codesign_configuration=args.codesign_configuration,
+            fast_adhoc_signing_probe_enabled=args.fast_adhoc_signing_probe_enabled,
+            codesign_manifest_path=args.codesign_manifest,
+            entitlements_suffixed_key_map=args.entitlements_suffixed_key_map,
+            entitlements_removed_keys=args.entitlements_removed_keys,
+            entitlements_removed_values_map=args.entitlements_removed_values_map,
+            prepared_entitlements_output_path=prepared_entitlements_path,
+        )
+    elif args.codesign_manifest:
+        # Always write the codesign manifest file, even when unsigned
+        write_empty_codesign_manifest(
+            codesign_manifest_path=args.codesign_manifest,
+            bundle_path=args.output,
+        )
+
+    if incremental_state:
+        if incremental_context is None:
+            raise RuntimeError(
+                "Expected incremental context to be present when incremental state is non-null."
+            )
+        _write_incremental_state(
+            spec=spec,
+            items=incremental_state,
+            path=args.incremental_state,
+            codesigned=args.codesign,
+            codesign_configuration=args.codesign_configuration,
+            selected_codesign_identity=selected_identity_argument,
+            codesign_arguments=args.codesign_args,
+            swift_stdlib_paths=swift_stdlib_paths,
+            versioned_if_macos=args.versioned_if_macos,
+            incremental_context=incremental_context,
+        )
+
+    if profiling_enabled:
+        pr.disable()
+        with open(args.profile_output, "w") as s:
+            sortby = pstats.SortKey.CUMULATIVE
+            ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
+            ps.print_stats()
+
+    if args.bundle_telemetry_logger:
+        selected_profile_path = _get_selected_profile_path(signing_context)
+        info_plist_in_bundle = (
+            (args.output / args.info_plist_destination)
+            if args.info_plist_destination
+            else None
+        )
+        _run_bundle_telemetry_logger(
+            logger_path=args.bundle_telemetry_logger,
+            bundle_path=args.output,
+            info_plist=info_plist_in_bundle,
+            entitlements=prepared_entitlements_path,
+            selected_provisioning_profile=selected_profile_path,
+        )
+
+    if telemetry_tmp_dir is not None:
+        telemetry_tmp_dir.cleanup()
+
+
+def _materialize_selected_profile(
+    signing_context_data: SigningContextData,
+    output_dir: Path,
+) -> None:
+    profile_context = selection_profile_context_from_signing_context(
+        signing_context_data.signing_context
+    )
+    if profile_context is None:
+        return
+    if signing_context_data.provisioning_profile_data is None:
+        raise ValueError("Signing context is missing profile data")
+
+    profile = profile_context.selected_profile_info.profile
+    materialized_path = output_dir / profile.file_path.name
+    materialized_path.write_bytes(signing_context_data.provisioning_profile_data)
+    profile.file_path = materialized_path
+
+
+def _get_selected_profile_path(
+    signing_context: Optional[object],
+) -> Optional[Path]:
+    if signing_context is None:
+        return None
+
+    signing_context_with_profile: Optional[SigningContextWithProfileSelection] = None
+    if isinstance(signing_context, SigningContextWithProfileSelection):
+        signing_context_with_profile = signing_context
+    if isinstance(signing_context, AdhocSigningContext):
+        signing_context_with_profile = signing_context.profile_selection_context
+
+    return (
+        signing_context_with_profile.selected_profile_info.profile.file_path
+        if signing_context_with_profile
+        else None
+    )
+
+
+def _run_bundle_telemetry_logger(
+    logger_path: Path,
+    bundle_path: Path,
+    info_plist: Optional[Path],
+    entitlements: Optional[Path],
+    selected_provisioning_profile: Optional[Path],
+) -> None:
+    cmd: List[str] = [str(logger_path), "--bundle", str(bundle_path)]
+    if info_plist:
+        cmd.extend(["--info-plist", str(info_plist)])
+    if entitlements:
+        cmd.extend(["--entitlements", str(entitlements)])
+    if selected_provisioning_profile:
+        cmd.extend(["--provisioning-profile", str(selected_provisioning_profile)])
+    try:
+        subprocess.run(cmd, check=False)
+    except Exception:
+        # Telemetry is best-effort, never fail the build
+        logging.getLogger(__name__).debug(
+            "Failed to run bundle telemetry logger",
+            exc_info=True,
+        )
+
+
+def _incremental_context(
+    incremenatal_state_path: Optional[Path],
+    codesigned: bool,
+    codesign_configuration: CodesignConfiguration,
+    codesign_identity: Optional[str],
+    codesign_arguments: List[str],
+    versioned_if_macos: bool,
+) -> Optional[IncrementalContext]:
+    action_metadata = action_metadata_if_present(_METADATA_PATH_KEY)
+    if action_metadata is None:
+        # Environment variable not set, running in non-incremental mode.
+        return None
+    # If there is no incremental state or we failed to parse it (maybe because of a format change)
+    # do a clean (non-incremental) assemble right now but generate proper state for next run.
+    incremental_state = (
+        _read_incremental_state(incremenatal_state_path)
+        if incremenatal_state_path
+        else None
+    )
+    return IncrementalContext(
+        metadata=action_metadata,
+        state=incremental_state,
+        codesigned=codesigned,
+        codesign_configuration=codesign_configuration,
+        codesign_identity=codesign_identity,
+        codesign_arguments=codesign_arguments,
+        versioned_if_macos=versioned_if_macos,
+    )
+
+
+def _read_incremental_state(path: Path) -> Optional[IncrementalState]:
+    logging.getLogger(__name__).info(f"Will read incremental state from `{path}`.")
+    if not path.exists():
+        logging.getLogger(__name__).warning(
+            f"File with incremental state doesn't exist at `{path}`."
+        )
+        return None
+    try:
+        with path.open() as f:
+            return parse_incremental_state(f)
+    except Exception:
+        logging.getLogger(__name__).exception("Failed to read incremental state")
+        return None
+    finally:
+        # If something goes wrong and we don't delete the file
+        # we probably end up in faulty state where incremental state
+        # doesn't match the output. Hence delete it early.
+        path.unlink()
+
+
+def _swift_support_arguments(
+    parser: argparse.ArgumentParser,
+    args: argparse.Namespace,
+) -> Optional[SwiftSupportArguments]:
+    if not args.swift_stdlib_command:
+        return None
+    if not args.binary_destination:
+        parser.error(
+            "Expected `--binary-destination` argument to be specified when `--swift-stdlib-command` is present."
+        )
+    if not args.appclips_destination:
+        parser.error(
+            "Expected `--appclips-destination` argument to be specified when `--swift-stdlib-command` is present."
+        )
+    if not args.frameworks_destination:
+        parser.error(
+            "Expected `--frameworks-destination` argument to be specified when `--swift-stdlib-command` is present."
+        )
+    if not args.extensionkit_extensions_destination:
+        parser.error(
+            "Expected `--extensionkit-extensions-destination` argument to be specified when `--swift-stdlib-command` is present."
+        )
+    if not args.plugins_destination:
+        parser.error(
+            "Expected `--plugins-destination` argument to be specified when `--swift-stdlib-command` is present."
+        )
+    if not args.platform:
+        parser.error(
+            "Expected `--platform` argument to be specified when `--swift-stdlib-command` is present."
+        )
+    if not args.sdk_root:
+        parser.error(
+            "Expected `--sdk-root` argument to be specified when `--swift-stdlib-command` is present."
+        )
+    return SwiftSupportArguments(
+        swift_stdlib_command=args.swift_stdlib_command,
+        binary_destination=args.binary_destination,
+        appclips_destination=args.appclips_destination,
+        frameworks_destination=args.frameworks_destination,
+        extensionkit_extensions_destination=args.extensionkit_extensions_destination,
+        plugins_destination=args.plugins_destination,
+        platform=args.platform,
+        sdk_root=args.sdk_root,
+    )
+
+
+def _write_incremental_state(
+    spec: List[BundleSpecItem],
+    items: List[IncrementalStateItem],
+    path: Path,
+    codesigned: bool,
+    codesign_configuration: CodesignConfiguration,
+    selected_codesign_identity: Optional[str],
+    codesign_arguments: List[str],
+    swift_stdlib_paths: List[Path],
+    versioned_if_macos: bool,
+    incremental_context: IncrementalContext,
+) -> None:
+    state = IncrementalState(
+        items,
+        codesigned=codesigned,
+        codesign_configuration=codesign_configuration,
+        codesigned_on_copy=[
+            codesigned_on_copy_item(
+                path=Path(i.dst),
+                entitlements=(
+                    Path(i.codesign_entitlements) if i.codesign_entitlements else None
+                ),
+                incremental_context=incremental_context,
+                codesign_flags_override=i.codesign_flags_override,
+                extra_codesign_paths=i.extra_codesign_paths,
+            )
+            for i in spec
+            if i.codesign_on_copy
+        ],
+        codesign_identity=selected_codesign_identity,
+        codesign_arguments=codesign_arguments,
+        swift_stdlib_paths=swift_stdlib_paths,
+        versioned_if_macos=versioned_if_macos,
+    )
+    path.touch()
+    try:
+        with path.open(mode="w") as f:
+            json.dump(state, f, cls=IncrementalStateJSONEncoder)
+    except Exception:
+        path.unlink()
+        raise
+
+
+def _amend_spec_with_build_uuid(
+    spec: List[BundleSpecItem],
+    resources_destination: Optional[Path],
+    tmp_dir: Path,
+) -> None:
+    build_id = os.environ.get("BUCK_BUILD_ID")
+    if not build_id:
+        return
+
+    if resources_destination is None:
+        raise RuntimeError(
+            "`--resources-destination` is required when `--include-build-info-file` is set."
+        )
+
+    # There caveats when the build info would be updated - specifically, it would
+    # be updated whenever the action runs. When the action runs is more tricky
+    # to precisely specify but practically speaking, if the bundling action does
+    # not run due to behing a cache hit, the build uuid would be from the last
+    # build that produced the cache value.
+    #
+    # For example, if you did the following:
+    #  - `buck build //my:app` (build uuid X)
+    #  - `buck build //my:app` (build uuid Y)
+    #
+    # Build Y runs no actions at all (nothing invalidated because synthesized
+    # files are not inputs to the action), so `BuildInfo.json` would contain
+    # uuid X.
+    src = tmp_dir / "BuildInfo.json"
+    src.write_text(json.dumps({"build_uuid": build_id}, indent=2))
+    dst = str(resources_destination / "BuildInfo.json")
+
+    spec.append(BundleSpecItem(src=str(src), dst=dst))
+
+
+def _deduplicate_spec(spec: List[BundleSpecItem]) -> List[BundleSpecItem]:
+    # It's possible to have the same spec multiple times as different
+    # apple_resource() targets can refer to the _same_ resource file.
+    #
+    # On RE, we're not allowed to overwrite files, so prevent doing
+    # identical file copies.
+    #
+    # Do not reorder spec items to achieve determinism.
+    # Rely on the fact that `dict` preserves key order.
+    deduplicated_spec = list(dict.fromkeys(spec))
+    # Force same sorting as in Buck1 for `SourcePathWithAppleBundleDestination`
+    # WARNING: This logic is tightly coupled with how spec filtering is done in `_filter_conflicting_paths` method during incremental bundling. Don't change unless you fully understand what is going on here.
+    deduplicated_spec.sort()
+    return deduplicated_spec
+
+
+if __name__ == "__main__":
+    with tempfile.TemporaryDirectory() as spec_temp_dir:
+        _main(spec_temp_dir)
diff --git a/buck2/prelude/apple/tools/bundling/provisioning_manifest_main.py b/buck2/prelude/apple/tools/bundling/provisioning_manifest_main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/provisioning_manifest_main.py
@@ -0,0 +1,85 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+from __future__ import annotations
+
+import argparse
+import base64
+import json
+from pathlib import Path
+
+from apple.tools.code_signing.signing_context_types import (
+    selection_profile_context_from_signing_context,
+)
+
+from .signing_context_data import load_signing_context_data_from_file
+
+
+def _main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Generate a provisioning manifest from a signing context.",
+    )
+    parser.add_argument(
+        "--output",
+        required=True,
+        type=Path,
+        help="Path to the output JSON file.",
+    )
+    parser.add_argument(
+        "--signing-context-path",
+        type=Path,
+        required=True,
+        help="Path to the precomputed signing context JSON.",
+    )
+
+    args = parser.parse_args()
+    signing_context_data = load_signing_context_data_from_file(
+        args.signing_context_path
+    )
+    selection_profile_context = selection_profile_context_from_signing_context(
+        signing_context_data.signing_context
+    )
+
+    with open(args.output, "w") as output_file:
+        signing_context_json_obj = {
+            "version": 1,
+        }
+
+        if signing_context_data.selected_identity:
+            # Ad hoc and Developer ID signing use the human-readable identity;
+            # profile-based signing uses the certificate fingerprint.
+            signing_context_json_obj["codesign_identity"] = (
+                signing_context_data.selected_identity
+            )
+
+        if selection_profile_context:
+            selected_profile_info = selection_profile_context.selected_profile_info
+            profile_metadata = selected_profile_info.profile
+            profile_data = signing_context_data.provisioning_profile_data
+            if profile_data is None:
+                raise ValueError("Signing context is missing profile data")
+
+            signing_context_json_obj["provisioning_profile"] = {
+                "uuid": profile_metadata.uuid,
+                "identity": {
+                    "fingerprint": selected_profile_info.identity.fingerprint,
+                    "subject_common_name": selected_profile_info.identity.subject_common_name,
+                },
+                "file_name": profile_metadata.file_path.name,
+                "file_data_base64": base64.b64encode(profile_data).decode(),
+            }
+
+        json.dump(
+            signing_context_json_obj,
+            output_file,
+            indent=4,
+        )
+
+
+if __name__ == "__main__":
+    _main()
diff --git a/buck2/prelude/apple/tools/bundling/resolve_signing_context_main.py b/buck2/prelude/apple/tools/bundling/resolve_signing_context_main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/resolve_signing_context_main.py
@@ -0,0 +1,75 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import logging
+from pathlib import Path
+
+from .logging_utils import configure_logging
+from .signing_context import (
+    add_args_for_signing_context,
+    signing_context_and_selected_identity_from_args,
+)
+from .signing_context_data import write_signing_context_data_to_file
+
+
+def _args_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(
+        description="Tool which resolves signing context and caches it for downstream bundling and signing_context tools.",
+    )
+    parser.add_argument(
+        "--output",
+        required=True,
+        type=Path,
+        help="Path to the output JSON file containing the signing context.",
+    )
+    parser.add_argument(
+        "--log-level-stderr",
+        choices=["debug", "info", "warning", "error", "critical"],
+        type=str,
+        required=False,
+        default="warning",
+        help="Logging level for messages written to stderr.",
+    )
+    parser.add_argument(
+        "--log-level-file",
+        choices=["debug", "info", "warning", "error", "critical"],
+        type=str,
+        required=False,
+        default="info",
+        help="Logging level for messages written to a log file.",
+    )
+
+    add_args_for_signing_context(parser)
+
+    return parser
+
+
+def _main() -> None:
+    parser = _args_parser()
+    args = parser.parse_args()
+
+    configure_logging(
+        stderr_level=getattr(logging, args.log_level_stderr.upper()),
+        file_level=getattr(logging, args.log_level_file.upper()),
+        log_path=args.log_file,
+    )
+
+    signing_context, selected_identity = (
+        signing_context_and_selected_identity_from_args(args)
+    )
+
+    write_signing_context_data_to_file(
+        path=args.output,
+        signing_context=signing_context,
+        selected_identity=selected_identity,
+    )
+
+
+if __name__ == "__main__":
+    _main()
diff --git a/buck2/prelude/apple/tools/bundling/signing_context.py b/buck2/prelude/apple/tools/bundling/signing_context.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/signing_context.py
@@ -0,0 +1,261 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+from __future__ import annotations
+
+import argparse
+import json
+import shlex
+from pathlib import Path
+
+from apple.tools.code_signing.apple_platform import ApplePlatform
+from apple.tools.code_signing.codesign_bundle import (
+    signing_context_with_profile_selection,
+)
+from apple.tools.code_signing.list_codesign_identities import (
+    AdHocListCodesignIdentities,
+    ListCodesignIdentities,
+)
+from apple.tools.code_signing.signing_context_types import (
+    AdhocSigningContext,
+    SigningContextWithProfileSelection,
+)
+
+
+def add_args_for_signing_context_path(parser: argparse.ArgumentParser) -> None:
+    parser.add_argument(
+        "--signing-context-path",
+        metavar="<SigningContext.json>",
+        type=Path,
+        required=True,
+        help="Path to the precomputed signing context JSON.",
+    )
+
+
+def add_args_for_bundling_execution(parser: argparse.ArgumentParser) -> None:
+    _add_common_execution_args(parser)
+
+
+def _add_common_execution_args(parser: argparse.ArgumentParser) -> None:
+    parser.add_argument(
+        "--codesign",
+        action="store_true",
+        help="Should the final bundle be codesigned.",
+    )
+    parser.add_argument(
+        "--entitlements",
+        metavar="<Entitlements.plist>",
+        type=Path,
+        required=False,
+        help="Path to file with entitlements to be used during code signing. If it's not provided the minimal entitlements are going to be generated.",
+    )
+    parser.add_argument(
+        "--entitlements-suffixed-key-map",
+        type=json.loads,
+        required=False,
+        default={},
+        help="JSON map of entitlement key to suffix to append to its values.",
+    )
+    parser.add_argument(
+        "--entitlements-removed-keys",
+        type=json.loads,
+        required=False,
+        default=[],
+        help="JSON list of entitlement keys to remove from the entitlements.",
+    )
+    parser.add_argument(
+        "--entitlements-removed-values-map",
+        type=json.loads,
+        required=False,
+        default={},
+        help="JSON map of entitlement keys to list of values to remove from that key.",
+    )
+    parser.add_argument(
+        "--info-plist-source",
+        metavar="</prepared/Info.plist>",
+        type=Path,
+        required=False,
+        help="Path to Info.plist source file which is used only to make code signing decisions (to be bundled `Info.plist` should be present in spec parameter). Required if code signing is requested.",
+    )
+    parser.add_argument(
+        "--info-plist-destination",
+        metavar="<Info.plist>",
+        type=Path,
+        required=False,
+        help="Required if code signing is requested. Bundle relative destination path to Info.plist file if it is present in bundle.",
+    )
+    parser.add_argument(
+        "--platform",
+        metavar="<apple platform>",
+        type=ApplePlatform,
+        required=False,
+        help="Required if code signing or Swift support is requested. Apple platform for which the bundle is built.",
+    )
+    parser.add_argument(
+        "--log-file",
+        type=Path,
+        required=False,
+        help="Path to a log file. If present logging will be directed to this file in addition to stderr.",
+    )
+
+
+def add_args_for_signing_context_selection(
+    parser: argparse.ArgumentParser,
+) -> None:
+    parser.add_argument(
+        "--ad-hoc",
+        action="store_true",
+        help="Perform ad-hoc signing if set.",
+    )
+    parser.add_argument(
+        "--ad-hoc-codesign-identity",
+        metavar="<identity>",
+        type=str,
+        required=False,
+        help="Codesign identity to use when ad-hoc signing is performed. Should be present when selection of provisioining profile is requested for ad-hoc signing.",
+    )
+    parser.add_argument(
+        "--codesign-identities-command",
+        metavar='<"/signing/identities --available">',
+        type=str,
+        required=False,
+        help="Command listing available code signing identities. If it's not provided `security` utility is assumed to be available and is used.",
+    )
+    parser.add_argument(
+        "--profiles-dir",
+        metavar="</provisioning/profiles/directory>",
+        type=Path,
+        required=False,
+        action="append",
+        help="Required if non-ad-hoc code signing is requested. Path to directory with provisioning profile files. Can be specified multiple times.",
+    )
+    parser.add_argument(
+        "--embed-provisioning-profile-when-signing-ad-hoc",
+        action="store_true",
+        help="Perform selection of provisioining profile and embed it into final bundle when ad-hoc signing if set.",
+    )
+    parser.add_argument(
+        "--fast-provisioning-profile-parsing",
+        action="store_true",
+        help="Uses experimental faster provisioning profile parsing.",
+    )
+    parser.add_argument(
+        "--strict-provisioning-profile-search",
+        action="store_true",
+        required=False,
+        help="Fail code signing if more than one matching profile found.",
+    )
+    parser.add_argument(
+        "--provisioning-profile-filter",
+        metavar="<regex>",
+        type=str,
+        required=False,
+        help="Regex to disambiguate multiple matching profiles, evaluated against provisioning profile filename.",
+    )
+    parser.add_argument(
+        "--verify-entitlements",
+        action="store_true",
+        help="Verify that the entitlements match the provisioning profile.",
+    )
+    parser.add_argument(
+        "--no-check-certificates",
+        action="store_true",
+        required=False,
+        help="Skip the check on code signing identities when selecting provisioning profile.",
+    )
+
+
+def add_args_for_signing_context(parser: argparse.ArgumentParser) -> None:
+    _add_common_execution_args(parser)
+    add_args_for_signing_context_selection(parser)
+
+
+def signing_context_and_selected_identity_from_args(
+    args: argparse.Namespace,
+) -> tuple[AdhocSigningContext | SigningContextWithProfileSelection | None, str | None]:
+    if args.codesign:
+        if not args.info_plist_source:
+            raise RuntimeError(
+                "Paths to Info.plist source file should be set when code signing is required."
+            )
+        if not args.info_plist_destination:
+            raise RuntimeError(
+                "Info.plist destination path should be set when code signing is required."
+            )
+        if not args.platform:
+            raise RuntimeError(
+                "Apple platform should be set when code signing is required."
+            )
+        list_codesign_identities = (
+            ListCodesignIdentities.override(
+                shlex.split(args.codesign_identities_command)
+            )
+            if args.codesign_identities_command
+            else ListCodesignIdentities.default()
+        )
+        if args.ad_hoc:
+            if args.embed_provisioning_profile_when_signing_ad_hoc:
+                if not args.profiles_dir:
+                    raise RuntimeError(
+                        "Path to directory with provisioning profile files should be set when selection of provisioining profile is enabled for ad-hoc code signing."
+                    )
+                if not args.ad_hoc_codesign_identity:
+                    raise RuntimeError(
+                        "Code signing identity should be set when selection of provisioining profile is enabled for ad-hoc code signing."
+                    )
+                profile_selection_context = signing_context_with_profile_selection(
+                    info_plist_source=args.info_plist_source,
+                    info_plist_destination=args.info_plist_destination,
+                    provisioning_profiles_dirs=args.profiles_dir,
+                    entitlements_path=args.entitlements,
+                    platform=args.platform,
+                    list_codesign_identities=AdHocListCodesignIdentities(
+                        original=list_codesign_identities,
+                        subject_common_name=args.ad_hoc_codesign_identity,
+                    ),
+                    log_file_path=args.log_file,
+                    should_use_fast_provisioning_profile_parsing=args.fast_provisioning_profile_parsing,
+                    strict_provisioning_profile_search=args.strict_provisioning_profile_search,
+                    provisioning_profile_filter=args.provisioning_profile_filter,
+                    should_verify_entitlements=args.verify_entitlements,
+                    no_check_certificates=args.no_check_certificates,
+                )
+            else:
+                profile_selection_context = None
+            signing_context = AdhocSigningContext(
+                codesign_identity=args.ad_hoc_codesign_identity,
+                profile_selection_context=profile_selection_context,
+            )
+            selected_identity_argument = args.ad_hoc_codesign_identity
+        else:
+            if not args.profiles_dir:
+                raise RuntimeError(
+                    "Path to directory with provisioning profile files should be set when signing is not ad-hoc."
+                )
+            signing_context = signing_context_with_profile_selection(
+                info_plist_source=args.info_plist_source,
+                info_plist_destination=args.info_plist_destination,
+                provisioning_profiles_dirs=args.profiles_dir,
+                entitlements_path=args.entitlements,
+                platform=args.platform,
+                list_codesign_identities=list_codesign_identities,
+                log_file_path=args.log_file,
+                should_use_fast_provisioning_profile_parsing=args.fast_provisioning_profile_parsing,
+                strict_provisioning_profile_search=args.strict_provisioning_profile_search,
+                provisioning_profile_filter=args.provisioning_profile_filter,
+                should_verify_entitlements=args.verify_entitlements,
+                no_check_certificates=args.no_check_certificates,
+            )
+            selected_identity_argument = (
+                signing_context.selected_profile_info.identity.fingerprint
+            )
+    else:
+        signing_context = None
+        selected_identity_argument = None
+
+    return signing_context, selected_identity_argument
diff --git a/buck2/prelude/apple/tools/bundling/signing_context_data.py b/buck2/prelude/apple/tools/bundling/signing_context_data.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/signing_context_data.py
@@ -0,0 +1,157 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+from __future__ import annotations
+
+import base64
+import binascii
+import json
+from dataclasses import dataclass
+from pathlib import Path
+
+from apple.tools.code_signing.serialization import (
+    expect_dict,
+    expect_keys,
+    expect_optional_str,
+    expect_str,
+)
+from apple.tools.code_signing.signing_context_types import (
+    AdhocSigningContext,
+    selection_profile_context_from_signing_context,
+    SigningContextWithProfileSelection,
+)
+
+_VERSION = 1
+
+SigningContext = AdhocSigningContext | SigningContextWithProfileSelection
+
+
+@dataclass(frozen=True)
+class SigningContextData:
+    signing_context: SigningContext | None
+    selected_identity: str | None
+    provisioning_profile_data: bytes | None
+
+
+def serialize_signing_context_data(
+    signing_context: SigningContext | None,
+    selected_identity: str | None,
+) -> dict[str, object]:
+    profile_context = selection_profile_context_from_signing_context(signing_context)
+    profile_data = (
+        profile_context.selected_profile_info.profile.file_path.read_bytes()
+        if profile_context is not None
+        else None
+    )
+    return {
+        "version": _VERSION,
+        "selected_identity": selected_identity,
+        "signing_context": _serialize_signing_context(signing_context),
+        "provisioning_profile_data_base64": (
+            base64.b64encode(profile_data).decode()
+            if profile_data is not None
+            else None
+        ),
+    }
+
+
+def _serialize_signing_context(
+    signing_context: SigningContext | None,
+) -> dict[str, object] | None:
+    if signing_context is None:
+        return None
+    if isinstance(signing_context, SigningContextWithProfileSelection):
+        return {"kind": "distribution", "distribution": signing_context.to_dict()}
+    if isinstance(signing_context, AdhocSigningContext):
+        return {"kind": "adhoc", "adhoc": signing_context.to_dict()}
+    raise ValueError(f"Unexpected signing context type: {type(signing_context)}")
+
+
+def deserialize_signing_context_data(value: object) -> SigningContextData:
+    data = expect_dict(value, "SigningContextData")
+    expect_keys(
+        data,
+        "SigningContextData",
+        frozenset(
+            {
+                "version",
+                "selected_identity",
+                "signing_context",
+                "provisioning_profile_data_base64",
+            }
+        ),
+    )
+    version = data["version"]
+    if type(version) is not int or version != _VERSION:
+        raise ValueError(f"Expected signing context version {_VERSION}, got {version}")
+
+    signing_context = _deserialize_signing_context(data["signing_context"])
+    profile_data = _decode_profile_data(data["provisioning_profile_data_base64"])
+    profile_context = selection_profile_context_from_signing_context(signing_context)
+    if (profile_context is None) != (profile_data is None):
+        raise ValueError(
+            "provisioning_profile_data_base64 must be present exactly when a "
+            "provisioning profile is selected"
+        )
+
+    return SigningContextData(
+        signing_context=signing_context,
+        selected_identity=expect_optional_str(
+            data["selected_identity"], "SigningContextData.selected_identity"
+        ),
+        provisioning_profile_data=profile_data,
+    )
+
+
+def _deserialize_signing_context(value: object) -> SigningContext | None:
+    if value is None:
+        return None
+    data = expect_dict(value, "SigningContextData.signing_context")
+    kind = expect_str(data.get("kind"), "SigningContextData.signing_context.kind")
+    if kind == "distribution":
+        expect_keys(
+            data,
+            "SigningContextData.signing_context",
+            frozenset({"kind", "distribution"}),
+        )
+        return SigningContextWithProfileSelection.from_dict(data["distribution"])
+    if kind == "adhoc":
+        expect_keys(
+            data,
+            "SigningContextData.signing_context",
+            frozenset({"kind", "adhoc"}),
+        )
+        return AdhocSigningContext.from_dict(data["adhoc"])
+    raise ValueError(f"Unknown signing context kind: {kind}")
+
+
+def _decode_profile_data(value: object) -> bytes | None:
+    encoded = expect_optional_str(
+        value, "SigningContextData.provisioning_profile_data_base64"
+    )
+    if encoded is None:
+        return None
+    try:
+        return base64.b64decode(encoded, validate=True)
+    except binascii.Error as error:
+        raise ValueError("Invalid provisioning profile base64 data") from error
+
+
+def write_signing_context_data_to_file(
+    path: Path,
+    signing_context: SigningContext | None,
+    selected_identity: str | None,
+) -> None:
+    data = serialize_signing_context_data(signing_context, selected_identity)
+    with path.open("w") as output:
+        json.dump(data, output, indent=4)
+
+
+def load_signing_context_data_from_file(path: Path) -> SigningContextData:
+    with path.open() as source:
+        return deserialize_signing_context_data(json.load(source))
diff --git a/buck2/prelude/apple/tools/bundling/signing_context_data_test.py b/buck2/prelude/apple/tools/bundling/signing_context_data_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/signing_context_data_test.py
@@ -0,0 +1,219 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import datetime
+import json
+import unittest
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from apple.tools.code_signing.identity import CodeSigningIdentity
+from apple.tools.code_signing.info_plist_metadata import InfoPlistMetadata
+from apple.tools.code_signing.provisioning_profile_metadata import (
+    ProvisioningProfileMetadata,
+)
+from apple.tools.code_signing.provisioning_profile_selection import (
+    SelectedProvisioningProfileInfo,
+)
+from apple.tools.code_signing.signing_context_types import (
+    AdhocSigningContext,
+    SigningContextWithProfileSelection,
+)
+
+from .signing_context_data import (
+    deserialize_signing_context_data,
+    serialize_signing_context_data,
+)
+
+
+class TestSigningContextData(unittest.TestCase):
+    def setUp(self) -> None:
+        self.temp_dir = TemporaryDirectory()
+        self.profile_path = Path(self.temp_dir.name) / "profile.mobileprovision"
+        self.profile_path.write_bytes(b"profile data")
+
+    def tearDown(self) -> None:
+        self.temp_dir.cleanup()
+
+    def test_null_context(self):
+        data = serialize_signing_context_data(None, None)
+        context_data = deserialize_signing_context_data(data)
+        self.assertIsNone(context_data.signing_context)
+        self.assertIsNone(context_data.selected_identity)
+        self.assertIsNone(context_data.provisioning_profile_data)
+
+    def test_adhoc_without_profile(self):
+        ctx = AdhocSigningContext(codesign_identity="-", profile_selection_context=None)
+        data = serialize_signing_context_data(ctx, "-")
+        json_str = json.dumps(data)
+        loaded = json.loads(json_str)
+        context_data = deserialize_signing_context_data(loaded)
+        ctx2 = context_data.signing_context
+        self.assertEqual(context_data.selected_identity, "-")
+        self.assertIsNone(context_data.provisioning_profile_data)
+        assert isinstance(ctx2, AdhocSigningContext)
+        self.assertEqual(ctx2.codesign_identity, "-")
+        self.assertIsNone(ctx2.profile_selection_context)
+
+    def test_distribution_context(self):
+        expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)
+        creation = datetime.datetime(2024, 1, 1, 12, 0, 0)
+        profile = ProvisioningProfileMetadata(
+            file_path=self.profile_path,
+            uuid="UUID-1234",
+            expiration_date=expiration,
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(
+                ["ABCDEF1234567890ABCDEF1234567890ABCDEF12"]
+            ),
+            entitlements={"application-identifier": "TEAM.com.test.app"},
+            creation_date=creation,
+            provisions_all_devices=False,
+            provisioned_devices=["device1"],
+        )
+        identity = CodeSigningIdentity(
+            fingerprint="ABCDEF1234567890ABCDEF1234567890ABCDEF12",
+            subject_common_name="Apple Development: Test",
+        )
+        selected_info = SelectedProvisioningProfileInfo(
+            profile=profile, identity=identity
+        )
+        info_plist_metadata = InfoPlistMetadata(
+            bundle_id="com.test.app", bundle_type="APPL", is_watchos_app=False
+        )
+        ctx = SigningContextWithProfileSelection(
+            info_plist_source=Path("/tmp/Info.plist"),
+            info_plist_destination=Path("Info.plist"),
+            info_plist_metadata=info_plist_metadata,
+            selected_profile_info=selected_info,
+        )
+        data = serialize_signing_context_data(ctx, identity.fingerprint)
+        json_str = json.dumps(data)
+        loaded = json.loads(json_str)
+        context_data = deserialize_signing_context_data(loaded)
+        ctx2 = context_data.signing_context
+        assert isinstance(ctx2, SigningContextWithProfileSelection)
+        self.assertEqual(context_data.selected_identity, identity.fingerprint)
+        self.assertEqual(context_data.provisioning_profile_data, b"profile data")
+        self.assertEqual(ctx2.info_plist_source, Path("/tmp/Info.plist"))
+        self.assertEqual(ctx2.info_plist_destination, Path("Info.plist"))
+        self.assertEqual(ctx2.info_plist_metadata.bundle_id, "com.test.app")
+        self.assertEqual(ctx2.selected_profile_info.profile.uuid, "UUID-1234")
+        self.assertEqual(
+            ctx2.selected_profile_info.profile.file_path,
+            self.profile_path,
+        )
+        self.assertEqual(
+            ctx2.selected_profile_info.identity.fingerprint, identity.fingerprint
+        )
+        self.assertEqual(
+            ctx2.selected_profile_info.profile.provisions_all_devices, False
+        )
+        self.assertEqual(
+            ctx2.selected_profile_info.profile.provisioned_devices, ["device1"]
+        )
+
+    def test_adhoc_with_profile(self):
+        expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)
+        profile = ProvisioningProfileMetadata(
+            file_path=self.profile_path,
+            uuid="UUID-5678",
+            expiration_date=expiration,
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(
+                ["AAAABBBBCCCCDDDDEEEEFFFF0000111122223333"]
+            ),
+            entitlements={},
+            creation_date=None,
+            provisions_all_devices=True,
+            provisioned_devices=None,
+        )
+        identity = CodeSigningIdentity(
+            fingerprint="AAAABBBBCCCCDDDDEEEEFFFF0000111122223333",
+            subject_common_name="Apple Development: Adhoc",
+        )
+        selected_info = SelectedProvisioningProfileInfo(
+            profile=profile, identity=identity
+        )
+        info_plist_metadata = InfoPlistMetadata(
+            bundle_id="com.test.app", bundle_type="APPL", is_watchos_app=False
+        )
+        distribution_ctx = SigningContextWithProfileSelection(
+            info_plist_source=Path("/tmp/Info.plist"),
+            info_plist_destination=Path("Info.plist"),
+            info_plist_metadata=info_plist_metadata,
+            selected_profile_info=selected_info,
+        )
+        adhoc_ctx = AdhocSigningContext(
+            codesign_identity="Apple Development: Adhoc",
+            profile_selection_context=distribution_ctx,
+        )
+        data = serialize_signing_context_data(adhoc_ctx, "Apple Development: Adhoc")
+        json_str = json.dumps(data)
+        loaded = json.loads(json_str)
+        context_data = deserialize_signing_context_data(loaded)
+        ctx2 = context_data.signing_context
+        assert isinstance(ctx2, AdhocSigningContext)
+        self.assertEqual(ctx2.codesign_identity, "Apple Development: Adhoc")
+        assert ctx2.profile_selection_context is not None
+        self.assertEqual(
+            ctx2.profile_selection_context.selected_profile_info.profile.uuid,
+            "UUID-5678",
+        )
+        self.assertEqual(context_data.selected_identity, "Apple Development: Adhoc")
+        self.assertEqual(context_data.provisioning_profile_data, b"profile data")
+
+    def test_version_mismatch_raises(self):
+        bad_data = {
+            "version": 999,
+            "selected_identity": None,
+            "signing_context": None,
+            "provisioning_profile_data_base64": None,
+        }
+        with self.assertRaises(ValueError) as cm:
+            deserialize_signing_context_data(bad_data)
+
+        msg = str(cm.exception)
+        self.assertIn("Expected signing context version", msg)
+        self.assertIn("999", msg)
+
+        bad_data_old = {
+            "version": 2,
+            "selected_identity": "-",
+            "signing_context": {
+                "kind": "adhoc",
+                "adhoc": {"codesign_identity": "-", "profile_selection_context": None},
+            },
+            "provisioning_profile_data_base64": None,
+        }
+        with self.assertRaises(ValueError):
+            deserialize_signing_context_data(bad_data_old)
+
+    def test_profile_context_requires_profile_data(self):
+        profile = ProvisioningProfileMetadata(
+            file_path=self.profile_path,
+            uuid="UUID",
+            expiration_date=datetime.datetime(2025, 1, 1),
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(["ABC"]),
+            entitlements={},
+        )
+        context = SigningContextWithProfileSelection(
+            info_plist_source=Path("/tmp/Info.plist"),
+            info_plist_destination=Path("Info.plist"),
+            info_plist_metadata=InfoPlistMetadata("com.test", "APPL", False),
+            selected_profile_info=SelectedProvisioningProfileInfo(
+                profile=profile,
+                identity=CodeSigningIdentity("ABC", "Developer"),
+            ),
+        )
+        data = serialize_signing_context_data(context, "ABC")
+        data["provisioning_profile_data_base64"] = None
+
+        with self.assertRaisesRegex(ValueError, "must be present exactly"):
+            deserialize_signing_context_data(data)
diff --git a/buck2/prelude/apple/tools/bundling/signing_info.py b/buck2/prelude/apple/tools/bundling/signing_info.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/signing_info.py
@@ -0,0 +1,77 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from apple.tools.code_signing.signing_context_types import (
+    AdhocSigningContext,
+    selection_profile_context_from_signing_context,
+    SigningContextWithProfileSelection,
+)
+
+from .signing_context_data import load_signing_context_data_from_file
+
+
+def build_signing_info(
+    signing_context: AdhocSigningContext | SigningContextWithProfileSelection | None,
+    selected_identity: str | None,
+) -> dict[str, Any]:
+    if signing_context is None:
+        return {}
+
+    if isinstance(signing_context, AdhocSigningContext):
+        codesign_type = "adhoc"
+    elif isinstance(signing_context, SigningContextWithProfileSelection):
+        codesign_type = "distribution"
+    else:
+        raise RuntimeError(f"Unexpected signing context type: {type(signing_context)}")
+
+    signing_info: dict[str, Any] = {
+        "codesign_type": codesign_type,
+    }
+
+    if selected_identity:
+        signing_info["codesign_identity"] = selected_identity
+
+    selection_profile_context = selection_profile_context_from_signing_context(
+        signing_context
+    )
+
+    if selection_profile_context:
+        selected_profile_info = selection_profile_context.selected_profile_info
+        profile_metadata = selected_profile_info.profile
+        if profile_metadata.provisioned_devices is not None:
+            provisioned_devices = "list"
+        elif profile_metadata.provisions_all_devices:
+            provisioned_devices = "all"
+        else:
+            provisioned_devices = "none"
+
+        signing_info["provisioning_profile"] = {
+            "uuid": profile_metadata.uuid,
+            "file_name": profile_metadata.file_path.name,
+            "provisioned_devices": provisioned_devices,
+        }
+        signing_info["signing_certificate"] = {
+            "fingerprint": selected_profile_info.identity.fingerprint,
+            "subject_common_name": selected_profile_info.identity.subject_common_name,
+        }
+
+    return signing_info
+
+
+def build_signing_info_from_file(path: Path) -> dict[str, Any]:
+    signing_context_data = load_signing_context_data_from_file(path)
+    return build_signing_info(
+        signing_context_data.signing_context,
+        signing_context_data.selected_identity,
+    )
diff --git a/buck2/prelude/apple/tools/bundling/signing_info_main.py b/buck2/prelude/apple/tools/bundling/signing_info_main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/signing_info_main.py
@@ -0,0 +1,44 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+from pathlib import Path
+
+from .signing_info import build_signing_info_from_file
+
+
+def _main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Tool which outputs signing-info JSON from a precomputed signing context. "
+        "This is cheap (no profile directory scan, no security tool) and allows the "
+        "[signing-info] subtarget to be built without running bundling.",
+    )
+    parser.add_argument(
+        "--signing-context-path",
+        type=Path,
+        required=True,
+        help="Path to precomputed signing context JSON.",
+    )
+    parser.add_argument(
+        "--output",
+        type=Path,
+        required=True,
+        help="Path to the output signing-info JSON file.",
+    )
+
+    args = parser.parse_args()
+
+    signing_info = build_signing_info_from_file(args.signing_context_path)
+
+    with open(args.output, "w") as f:
+        json.dump(signing_info, f, indent=4)
+
+
+if __name__ == "__main__":
+    _main()
diff --git a/buck2/prelude/apple/tools/bundling/signing_info_test.py b/buck2/prelude/apple/tools/bundling/signing_info_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/signing_info_test.py
@@ -0,0 +1,130 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import datetime
+import unittest
+from pathlib import Path
+
+from apple.tools.code_signing.identity import CodeSigningIdentity
+from apple.tools.code_signing.info_plist_metadata import InfoPlistMetadata
+from apple.tools.code_signing.provisioning_profile_metadata import (
+    ProvisioningProfileMetadata,
+)
+from apple.tools.code_signing.provisioning_profile_selection import (
+    SelectedProvisioningProfileInfo,
+)
+from apple.tools.code_signing.signing_context_types import (
+    AdhocSigningContext,
+    SigningContextWithProfileSelection,
+)
+
+from .signing_info import build_signing_info
+
+
+class TestSigningInfo(unittest.TestCase):
+    def test_no_signing_context(self):
+        info = build_signing_info(None, None)
+        self.assertEqual(info, {})
+
+    def test_adhoc_without_profile(self):
+        ctx = AdhocSigningContext(codesign_identity="-", profile_selection_context=None)
+        info = build_signing_info(ctx, "-")
+        self.assertEqual(info["codesign_type"], "adhoc")
+        self.assertEqual(info["codesign_identity"], "-")
+        self.assertNotIn("provisioning_profile", info)
+
+    def test_distribution_with_devices_list(self):
+        expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)
+        profile = ProvisioningProfileMetadata(
+            file_path=Path("/tmp/my.mobileprovision"),
+            uuid="UUID-123",
+            expiration_date=expiration,
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(["ABC"]),
+            entitlements={},
+            creation_date=None,
+            provisions_all_devices=False,
+            provisioned_devices=["dev1", "dev2"],
+        )
+        identity = CodeSigningIdentity(
+            fingerprint="ABC", subject_common_name="Apple Dev"
+        )
+        selected = SelectedProvisioningProfileInfo(profile=profile, identity=identity)
+        metadata = InfoPlistMetadata(
+            bundle_id="com.test", bundle_type="APPL", is_watchos_app=False
+        )
+        ctx = SigningContextWithProfileSelection(
+            info_plist_source=Path("/tmp/Info.plist"),
+            info_plist_destination=Path("Info.plist"),
+            info_plist_metadata=metadata,
+            selected_profile_info=selected,
+        )
+        info = build_signing_info(ctx, "ABC")
+        self.assertEqual(info["codesign_type"], "distribution")
+        self.assertEqual(info["codesign_identity"], "ABC")
+        self.assertEqual(info["provisioning_profile"]["uuid"], "UUID-123")
+        self.assertEqual(
+            info["provisioning_profile"]["file_name"], "my.mobileprovision"
+        )
+        self.assertEqual(info["provisioning_profile"]["provisioned_devices"], "list")
+        self.assertEqual(info["signing_certificate"]["fingerprint"], "ABC")
+
+    def test_provisioned_devices_all_and_none(self):
+        expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)
+
+        profile_all = ProvisioningProfileMetadata(
+            file_path=Path("/tmp/all.mobileprovision"),
+            uuid="UUID-ALL",
+            expiration_date=expiration,
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(["ABC"]),
+            entitlements={},
+            creation_date=None,
+            provisions_all_devices=True,
+            provisioned_devices=None,
+        )
+        identity = CodeSigningIdentity(fingerprint="ABC", subject_common_name="Dev")
+        selected_all = SelectedProvisioningProfileInfo(
+            profile=profile_all, identity=identity
+        )
+        metadata = InfoPlistMetadata(
+            bundle_id="com.test", bundle_type="APPL", is_watchos_app=False
+        )
+        ctx_all = SigningContextWithProfileSelection(
+            info_plist_source=Path("/tmp/Info.plist"),
+            info_plist_destination=Path("Info.plist"),
+            info_plist_metadata=metadata,
+            selected_profile_info=selected_all,
+        )
+        info_all = build_signing_info(ctx_all, "ABC")
+        self.assertEqual(info_all["provisioning_profile"]["provisioned_devices"], "all")
+
+        profile_none = ProvisioningProfileMetadata(
+            file_path=Path("/tmp/none.mobileprovision"),
+            uuid="UUID-NONE",
+            expiration_date=expiration,
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(["ABC"]),
+            entitlements={},
+            creation_date=None,
+            provisions_all_devices=False,
+            provisioned_devices=None,
+        )
+        selected_none = SelectedProvisioningProfileInfo(
+            profile=profile_none, identity=identity
+        )
+        ctx_none = SigningContextWithProfileSelection(
+            info_plist_source=Path("/tmp/Info.plist"),
+            info_plist_destination=Path("Info.plist"),
+            info_plist_metadata=metadata,
+            selected_profile_info=selected_none,
+        )
+        info_none = build_signing_info(ctx_none, "ABC")
+        self.assertEqual(
+            info_none["provisioning_profile"]["provisioned_devices"], "none"
+        )
diff --git a/buck2/prelude/apple/tools/bundling/swift_support.py b/buck2/prelude/apple/tools/bundling/swift_support.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/swift_support.py
@@ -0,0 +1,85 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import logging
+import os
+import shlex
+import shutil
+import subprocess
+import tempfile
+from dataclasses import dataclass
+from pathlib import Path
+from typing import List, Union
+
+_LOGGER: logging.Logger = logging.getLogger(__name__)
+
+
+@dataclass
+class SwiftSupportArguments:
+    swift_stdlib_command: str
+    binary_destination: Path
+    appclips_destination: Path
+    frameworks_destination: Path
+    extensionkit_extensions_destination: Path
+    plugins_destination: Path
+    platform: str
+    sdk_root: Path
+
+
+def run_swift_stdlib_tool(bundle_path: Path, args: SwiftSupportArguments) -> List[Path]:
+    # TODO(T181556849) when incremental bundling is on, binary, frameworks and plugins are not changed, signing identity is unchanged skip this step.
+    bundle_relative_output_paths = []
+    with tempfile.TemporaryDirectory() as tmp_dir:
+        # When signing, swift-stdlib-tool needs a proper PATH environment variable.
+        # Assume the current environment has it already.
+        env = os.environ.copy()
+        # xcrun doesn't like relative paths
+        env["SDKROOT"] = os.path.abspath(args.sdk_root)
+        cmd = _execution_command(bundle_path, args, tmp_dir)
+        _LOGGER.info(
+            f"Running Swift stdlib tool with command: `{cmd}` and environment `{env}`."
+        )
+        result = subprocess.run(cmd, env=env)
+        result.check_returncode()
+        outputs = sorted(os.listdir(tmp_dir))
+        frameworks_path = bundle_path / args.frameworks_destination
+        if outputs:
+            frameworks_path.mkdir(exist_ok=True)
+        for output in outputs:
+            shutil.move(os.path.join(tmp_dir, output), frameworks_path)
+        bundle_relative_output_paths = [
+            args.frameworks_destination / o for o in outputs
+        ]
+    return bundle_relative_output_paths
+
+
+def _execution_command(
+    bundle_path: Path,
+    args: SwiftSupportArguments,
+    tmp_dir: str,
+) -> List[Union[str, Path]]:
+    return shlex.split(args.swift_stdlib_command) + [
+        "--copy",
+        "--strip-bitcode",
+        "--scan-executable",
+        bundle_path / args.binary_destination,
+        "--scan-executable",
+        bundle_path / args.appclips_destination,
+        "--scan-folder",
+        bundle_path / args.frameworks_destination,
+        "--scan-folder",
+        bundle_path / args.extensionkit_extensions_destination,
+        "--scan-folder",
+        bundle_path / args.plugins_destination,
+        "--destination",
+        tmp_dir,
+        "--platform",
+        args.platform,
+    ]
diff --git a/buck2/prelude/apple/tools/bundling/test_resources/newer_version_action_metadata.json b/buck2/prelude/apple/tools/bundling/test_resources/newer_version_action_metadata.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/test_resources/newer_version_action_metadata.json
@@ -0,0 +1,6 @@
+{
+  "version": 2,
+  "data": {
+    "something": []
+  }
+}
diff --git a/buck2/prelude/apple/tools/bundling/test_resources/newer_version_incremental_state.json b/buck2/prelude/apple/tools/bundling/test_resources/newer_version_incremental_state.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/test_resources/newer_version_incremental_state.json
@@ -0,0 +1,6 @@
+{
+  "version": 7,
+  "data": {
+    "something": []
+  }
+}
diff --git a/buck2/prelude/apple/tools/bundling/test_resources/the.broken_json b/buck2/prelude/apple/tools/bundling/test_resources/the.broken_json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/test_resources/the.broken_json
@@ -0,0 +1,2 @@
+{
+  "version":
diff --git a/buck2/prelude/apple/tools/bundling/test_resources/valid_action_metadata.json b/buck2/prelude/apple/tools/bundling/test_resources/valid_action_metadata.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/test_resources/valid_action_metadata.json
@@ -0,0 +1,13 @@
+{
+  "version": 1,
+  "digests": [
+    {
+      "path": "repo/foo.txt",
+      "digest": "foo_digest"
+    },
+    {
+      "path": "buck-out/bar.txt",
+      "digest": "bar_digest"
+    }
+  ]
+}
diff --git a/buck2/prelude/apple/tools/bundling/test_resources/valid_incremental_state.json b/buck2/prelude/apple/tools/bundling/test_resources/valid_incremental_state.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/bundling/test_resources/valid_incremental_state.json
@@ -0,0 +1,48 @@
+{
+  "items": [
+    {
+      "source": "repo/foo.txt",
+      "destination_relative_to_bundle": "foo.txt",
+      "digest": "foo_digest"
+    },
+    {
+      "source": "buck-out/bar.txt",
+      "destination_relative_to_bundle": "Resources/bar.txt",
+      "digest": "bar_digest"
+    },
+    {
+      "source": "buck-out/bar",
+      "destination_relative_to_bundle": "Resources/bar",
+      "resolved_symlink": "bar.txt"
+    }
+  ],
+  "codesign_configuration": null,
+  "codesigned": true,
+  "codesigned_on_copy": [
+    {
+      "path": "Resources/bar.txt"
+    },
+    {
+      "path": "Resources/baz.txt",
+      "entitlements_digest": "abc"
+    },
+    {
+      "path": "Resources/qux.txt",
+      "codesign_flags_override": ["--deep", "--force"]
+    },
+    {
+      "path": "Resources/Parent.framework",
+      "extra_codesign_paths": ["Frameworks/Base.framework"]
+    }
+  ],
+  "codesign_identity": "Johny Appleseed",
+  "codesign_arguments": [
+    "--force",
+    "--deep"
+  ],
+  "versioned_if_macos": true,
+  "swift_stdlib_paths": [
+    "Frameworks/libswiftCore.dylib"
+  ],
+  "version": 8
+}
diff --git a/buck2/prelude/apple/tools/code_signing/BUCK b/buck2/prelude/apple/tools/code_signing/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/BUCK
@@ -0,0 +1,89 @@
+load("@prelude//apple/tools:defs.bzl", "meta_python_test")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+configured_alias(
+    name = "dummy_binary_for_signing_configured",
+    actual = ":dummy_binary_for_signing",
+    platform = "config//platform/macos:base",
+)
+
+platform(
+    name = "dummy_binary_for_signing_platform",
+    constraint_values = [
+        "config//cpu/constraints:arm64",
+    ],
+    deps = [
+        "config//platform/macos:base",
+    ],
+)
+
+cxx_binary(
+    name = "dummy_binary_for_signing",
+    srcs = ["dummy_binary_for_signing.c"],
+    default_target_platform = ":dummy_binary_for_signing_platform",
+)
+
+python_library(
+    name = "apple_platform_lib",
+    srcs = ["apple_platform.py"],
+    visibility = ["PUBLIC"],
+)
+
+python_library(
+    name = "serialization",
+    srcs = ["serialization.py"],
+    typing = True,
+    visibility = ["PUBLIC"],
+)
+
+python_library(
+    name = "lib",
+    srcs = glob(
+        [
+            "*.py",
+        ],
+        exclude = [
+            "*_test.py",
+            "main.py",
+            "apple_platform.py",
+            "serialization.py",
+        ],
+    ),
+    resources = [":dummy_binary_for_signing_configured"],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//apple/tools:plistlib_utils",
+        "prelude//apple/tools/info_plist_processor:process",
+        # @oss-disable[end= ]: "prelude//apple/tools/meta_only:codesign_diagnostics_text_lib",
+        # @oss-disable[end= ]: "prelude//apple/tools/meta_only/codesign_rust:check_adhoc_signature_lib",
+        # @oss-disable[end= ]: "prelude//apple/tools/meta_only/entitlements_mismatch:check_entitlements_lib",
+        ":apple_platform_lib",
+        ":serialization",
+    ],
+)
+
+meta_python_test(
+    name = "tests",
+    srcs = glob(["*_test.py"]),
+    resources = glob([
+        "test_resources/*",
+    ]),
+    deps = [
+        "fbsource//third-party/pypi/setuptools:setuptools",
+        ":lib",
+    ],
+)
+
+python_binary(
+    name = "codesign_bundle",
+    main = "main.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        "fbsource//third-party/pypi/typed-argument-parser:typed-argument-parser",
+        ":lib",
+    ],
+)
diff --git a/buck2/prelude/apple/tools/code_signing/app_id.py b/buck2/prelude/apple/tools/code_signing/app_id.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/app_id.py
@@ -0,0 +1,74 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any, Dict, Optional
+
+
+@dataclass
+class AppId:
+    team_id: str
+    bundle_id: str
+
+    class _ReGroupName(str, Enum):
+        team_id = "team_id"
+        bundle_id = "bundle_id"
+
+    _re_string: str = "^(?P<{team_id}>[A-Z0-9]{{10}})\\.(?P<{bundle_id}>.+)$".format(
+        team_id=_ReGroupName.team_id.value,
+        bundle_id=_ReGroupName.bundle_id.value,
+    )
+    _re_pattern: re.Pattern[str] = re.compile(_re_string)
+
+    # Takes a application identifier and splits it into Team ID and bundle ID.
+    # Prefix is always a ten-character alphanumeric sequence. Bundle ID may be a fully-qualified name or a wildcard ending in *.
+    @classmethod
+    def from_string(cls, string: str) -> AppId:
+        match = re.match(cls._re_pattern, string)
+        if not match:
+            raise RuntimeError(
+                "Malformed app ID string: '{}'. "
+                "We expected a prefix of a ten-character alphanumeric sequence and a Bundle ID which may be a fully-qualified name or a wildcard ending in '*'.".format(
+                    string
+                )
+            )
+        return AppId(
+            match.group(cls._ReGroupName.team_id.value),
+            match.group(cls._ReGroupName.bundle_id.value),
+        )
+
+    # Returns the App ID if it can be inferred from keys in the entitlement. Otherwise, it returns `None`.
+    @staticmethod
+    def infer_from_entitlements(entitlements: Dict[str, Any]) -> Optional[AppId]:
+        try:
+            keychain_access_groups = entitlements.get("keychain-access-groups")
+            if keychain_access_groups:
+                app_id_string = keychain_access_groups[0]
+                return AppId.from_string(app_id_string)
+
+            application_identifier = entitlements.get("application-identifier")
+            if application_identifier:
+                return AppId.from_string(application_identifier)
+
+            team_identifier = entitlements.get("com.apple.developer.team-identifier")
+            bundle_id = entitlements.get("CFBundleIdentifier")
+            if team_identifier and bundle_id:
+                app_id_string = f"{team_identifier}.{bundle_id}"
+                return AppId.from_string(app_id_string)
+
+            return None
+        except Exception as e:
+            raise RuntimeError(
+                "Error when parsing the entitlements for the app ID: {}".format(e)
+            )
diff --git a/buck2/prelude/apple/tools/code_signing/app_id_test.py b/buck2/prelude/apple/tools/code_signing/app_id_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/app_id_test.py
@@ -0,0 +1,64 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import importlib.resources
+import plistlib
+import unittest
+
+from .app_id import AppId
+
+
+class TestAppId(unittest.TestCase):
+    def test_string_parsing(self):
+        result = AppId.from_string("ABCDE12345.com.example.TestApp")
+        expected = AppId("ABCDE12345", "com.example.TestApp")
+        self.assertEqual(expected, result)
+
+        result = AppId.from_string("ABCDE12345.*")
+        expected = AppId("ABCDE12345", "*")
+        self.assertEqual(expected, result)
+
+        with self.assertRaisesRegex(
+            RuntimeError,
+            "Malformed app ID string: 'invalid.'. We expected a prefix of a ten-character alphanumeric sequence and a Bundle ID which may be a fully-qualified name or a wildcard ending in '*'.",
+        ):
+            _ = AppId.from_string("invalid.")
+
+    def test_entitlements_parsing(self):
+        expected = AppId("ABCDE12345", "com.example.TestApp")
+        test_plist_files = [
+            "test_resources/test1.plist",
+            "test_resources/test2.plist",
+            "test_resources/test3.plist",
+        ]
+
+        package = importlib.resources.files(__package__)
+        for file in test_plist_files:
+            with (package / file).open("rb") as f:
+                entitlements = plistlib.load(f)
+                result = AppId.infer_from_entitlements(entitlements)
+                self.assertEqual(expected, result)
+
+        invalid_file = b"""<?xml version="1.0" encoding="UTF-8"?>
+                            <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+                            <plist version="1.0">
+                            <dict>
+                                <key>keychain-access-groups</key>
+                                <array>
+                                    <string>com.facebook.CommonTestHost</string>
+                                </array>p
+                            </dict>
+                            </plist>"""
+
+        invalid_entitlement = plistlib.loads(invalid_file)
+        with self.assertRaisesRegex(
+            RuntimeError,
+            "Error when parsing the entitlements for the app ID: Malformed app ID string: 'com.facebook.CommonTestHost'. "
+            "We expected a prefix of a ten-character alphanumeric sequence and a Bundle ID which may be a fully-qualified name or a wildcard ending in '*'.",
+        ):
+            AppId.infer_from_entitlements(invalid_entitlement)
diff --git a/buck2/prelude/apple/tools/code_signing/apple_platform.py b/buck2/prelude/apple/tools/code_signing/apple_platform.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/apple_platform.py
@@ -0,0 +1,50 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from enum import Enum
+from typing import Optional
+
+
+class ApplePlatform(str, Enum):
+    macos = "macosx"
+    ios_device = "iphoneos"
+    ios_simulator = "iphonesimulator"
+    watch_device = "watchos"
+    watch_simulator = "watchsimulator"
+    tv_device = "appletvos"
+    tv_simulator = "appletvsimulator"
+    mac_catalyst = "maccatalyst"
+    driver_kit = "driverkit"
+
+    def is_desktop(self) -> bool:
+        return self == ApplePlatform.macos or self == ApplePlatform.mac_catalyst
+
+    def provisioning_profile_name(self) -> Optional[str]:
+        """
+        Returns:
+           The platform name as it could be found inside provisioning profiles and used to match them.
+           Not all platforms use provisioning profiles, those will return `None`.
+        """
+        if self == ApplePlatform.ios_device or self == ApplePlatform.watch_device:
+            return "iOS"
+        elif self == ApplePlatform.tv_device:
+            return "tvOS"
+        else:
+            return None
+
+    def embedded_provisioning_profile_path(self) -> str:
+        """
+        Returns:
+           The name of the provisioning profile in the final application bundle.
+        """
+        if self.is_desktop():
+            return "Contents/embedded.provisionprofile"
+        else:
+            return "embedded.mobileprovision"
diff --git a/buck2/prelude/apple/tools/code_signing/codesign_bundle.py b/buck2/prelude/apple/tools/code_signing/codesign_bundle.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/codesign_bundle.py
@@ -0,0 +1,914 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import asyncio
+import importlib.resources
+import json
+import logging
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import uuid
+from contextlib import ExitStack
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+from typing import Any, cast, Dict, List, Optional, Union
+
+from apple.tools.plistlib_utils import detect_format_and_load
+
+# @oss-disable[end= ]: from ..meta_only.codesign_diagnostics_text import (
+    # @oss-disable[end= ]: CodesignDiagnosticsText,
+# @oss-disable[end= ]: )
+# @oss-disable[end= ]: from ..meta_only.entitlements_mismatch.check_entitlements import (
+    # @oss-disable[end= ]: verify_entitlements,
+# @oss-disable[end= ]: )
+from .apple_platform import ApplePlatform
+from .codesign_command_factory import (
+    DefaultCodesignCommandFactory,
+    DryRunCodesignCommandFactory,
+    generate_codesign_manifest,
+    ICodesignCommandFactory,
+    ManifestCodesignCommandFactory,
+)
+
+from .codesign_diagnostics_text import CodesignDiagnosticsText # @oss-enable
+from .fast_adhoc import is_fast_adhoc_codesign_allowed, should_skip_adhoc_signing_path
+from .identity import CodeSigningIdentity
+from .info_plist_metadata import InfoPlistMetadata
+from .list_codesign_identities import IListCodesignIdentities
+from .prepare_code_signing_entitlements import (
+    postprocess_entitlements,
+    prepare_code_signing_entitlements,
+)
+from .prepare_info_plist import prepare_info_plist
+from .provisioning_profile_diagnostics import (
+    interpret_provisioning_profile_diagnostics,
+    IProvisioningProfileDiagnostics,
+)
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+from .provisioning_profile_selection import (
+    CodeSignProvisioningError,
+    select_best_provisioning_profile_core,
+    SelectedProvisioningProfileInfo,
+)
+from .read_provisioning_profile_command_factory import (
+    DefaultReadProvisioningProfileCommandFactory,
+    IReadProvisioningProfileCommandFactory,
+)
+from .signing_context_types import (
+    AdhocSigningContext,
+    selection_profile_context_from_signing_context,
+    SigningContextWithProfileSelection,
+)
+
+_default_read_provisioning_profile_command_factory = (
+    DefaultReadProvisioningProfileCommandFactory()
+)
+
+_LOGGER: logging.Logger = logging.getLogger(__name__)
+
+
+@dataclass
+class CodesignedPath:
+    path: Path
+    """
+    Path relative to bundle root which needs to be codesigned
+    """
+    entitlements: Optional[Path]
+    """
+    Path to entitlements to be used when codesigning, relative to buck project
+    """
+    flags: List[str]
+    """
+    Flags to be passed to codesign command when codesigning this particular path
+    """
+    extra_file_paths: Optional[List[Path]]
+    """
+    Extra paths to be codesign. Applicable to dry-run codesigning only.
+    """
+
+
+def _verify_entitlements(
+    entitlements_path: Optional[Path],
+    profile_path: Path,
+    platform: ApplePlatform,
+) -> None:
+    result = verify_entitlements(
+        entitlements_path,
+        profile_path,
+        platform=platform,
+    )
+    if result == 1:
+        sys.exit(1)
+
+
+def _log_codesign_identities(
+    list_codesign_identities: IListCodesignIdentities,
+    identities: List[CodeSigningIdentity],
+) -> None:
+    if len(identities) == 0:
+        _LOGGER.warning("ZERO codesign identities available")
+        _LOGGER.warning(
+            f"Identities were retrieved by command: {list_codesign_identities.raw_command()}"
+        )
+    else:
+        _LOGGER.info("Listing available codesign identities")
+        for identity in identities:
+            _LOGGER.info(
+                f"    Subject Common Name: {identity.subject_common_name}, Fingerprint: {identity.fingerprint}"
+            )
+
+
+def _read_profiles_from_dir(
+    profiles_dir: Path,
+    should_use_fast_provisioning_profile_parsing: bool,
+) -> List[ProvisioningProfileMetadata]:
+    read_provisioning_profile_command_factory = (
+        _default_read_provisioning_profile_command_factory
+    )
+    if should_use_fast_provisioning_profile_parsing:
+        return asyncio.run(
+            _fast_read_provisioning_profiles_async(
+                profiles_dir,
+                read_provisioning_profile_command_factory,
+            )
+        )
+    else:
+        return _read_provisioning_profiles(
+            profiles_dir,
+            read_provisioning_profile_command_factory,
+        )
+
+
+def _try_select_from_profiles_dir(
+    profiles_dir: Path,
+    info_plist_metadata: InfoPlistMetadata,
+    identities: List[CodeSigningIdentity],
+    entitlements: Optional[Dict[str, Any]],
+    platform: ApplePlatform,
+    should_use_fast_provisioning_profile_parsing: bool,
+    strict_provisioning_profile_search: bool,
+    provisioning_profile_filter: Optional[str],
+    no_check_certificates: bool,
+) -> tuple[
+    Optional[SelectedProvisioningProfileInfo],
+    Optional[List[ProvisioningProfileMetadata]],
+    Optional[List[IProvisioningProfileDiagnostics]],
+]:
+    provisioning_profiles = _read_profiles_from_dir(
+        profiles_dir,
+        should_use_fast_provisioning_profile_parsing,
+    )
+    if not provisioning_profiles:
+        return None, None, None
+    selected_profile_info, mismatches = select_best_provisioning_profile_core(
+        info_plist_metadata,
+        identities,
+        provisioning_profiles,
+        entitlements,
+        platform,
+        strict_provisioning_profile_search,
+        provisioning_profile_filter,
+        no_check_certificates,
+    )
+    return selected_profile_info, provisioning_profiles, mismatches
+
+
+def _select_best_provisioning_profile(
+    info_plist_metadata: InfoPlistMetadata,
+    provisioning_profiles_dirs: List[Path],
+    entitlements_path: Optional[Path],
+    platform: ApplePlatform,
+    list_codesign_identities: IListCodesignIdentities,
+    should_use_fast_provisioning_profile_parsing: bool,
+    strict_provisioning_profile_search: bool,
+    provisioning_profile_filter: Optional[str],
+    no_check_certificates: bool = False,
+    log_file_path: Optional[Path] = None,
+) -> SelectedProvisioningProfileInfo:
+    if no_check_certificates:
+        identities = []
+        _LOGGER.info(
+            "no_check_certificates is set to True, so we will ignore codesign identities"
+        )
+    else:
+        identities = list_codesign_identities.list_codesign_identities()
+        _log_codesign_identities(list_codesign_identities, identities)
+    _LOGGER.info(
+        f"Fast provisioning profile parsing enabled: {should_use_fast_provisioning_profile_parsing}"
+    )
+    entitlements = _read_entitlements_file(entitlements_path)
+
+    # Try each profiles directory in order, returning as soon as a match is found
+    all_mismatches: List[IProvisioningProfileDiagnostics] = []
+    has_profiles = False
+    for profiles_dir in provisioning_profiles_dirs:
+        selected_profile_info, profiles, mismatches = _try_select_from_profiles_dir(
+            profiles_dir=profiles_dir,
+            info_plist_metadata=info_plist_metadata,
+            identities=identities,
+            entitlements=entitlements,
+            platform=platform,
+            should_use_fast_provisioning_profile_parsing=should_use_fast_provisioning_profile_parsing,
+            strict_provisioning_profile_search=strict_provisioning_profile_search,
+            provisioning_profile_filter=provisioning_profile_filter,
+            no_check_certificates=no_check_certificates,
+        )
+        if selected_profile_info is not None:
+            return selected_profile_info
+        if profiles is not None:
+            has_profiles = True
+            if mismatches:
+                all_mismatches.extend(mismatches)
+        _LOGGER.info(
+            f"No matching profile found in '{profiles_dir}', trying next source"
+        )
+
+    # No profile found in any directory — generate diagnostics
+    if not has_profiles:
+        dirs_msg = ", ".join(f"'{d}'" for d in provisioning_profiles_dirs)
+        raise CodeSignProvisioningError(
+            f"\n\nFailed to find any provisioning profiles. Please make sure to install required provisioning profiles and make sure they are located at {dirs_msg}.\n\n"
+            + CodesignDiagnosticsText.NO_PROFILES_REMEDIATION
+        )
+
+    if not all_mismatches:
+        dirs_msg = ", ".join(f"`{d}`" for d in provisioning_profiles_dirs)
+        raise RuntimeError(
+            f"Expected diagnostics information for at least one mismatching provisioning profile when {dirs_msg} directories are not empty."
+        )
+    raise CodeSignProvisioningError(
+        interpret_provisioning_profile_diagnostics(
+            diagnostics=all_mismatches,
+            bundle_id=info_plist_metadata.bundle_id,
+            provisioning_profiles_dirs=provisioning_profiles_dirs,
+            identities=identities,
+            log_file_path=log_file_path,
+        )
+    )
+
+
+def signing_context_with_profile_selection(
+    info_plist_source: Path,
+    info_plist_destination: Path,
+    provisioning_profiles_dirs: List[Path],
+    entitlements_path: Optional[Path],
+    platform: ApplePlatform,
+    list_codesign_identities: IListCodesignIdentities,
+    log_file_path: Optional[Path] = None,
+    should_use_fast_provisioning_profile_parsing: bool = False,
+    strict_provisioning_profile_search: bool = False,
+    provisioning_profile_filter: Optional[str] = None,
+    no_check_certificates: bool = False,
+    should_verify_entitlements: bool = False,
+) -> SigningContextWithProfileSelection:
+    with open(info_plist_source, mode="rb") as info_plist_file:
+        info_plist_metadata = InfoPlistMetadata.from_file(info_plist_file)
+    selected_profile_info = _select_best_provisioning_profile(
+        info_plist_metadata=info_plist_metadata,
+        provisioning_profiles_dirs=provisioning_profiles_dirs,
+        entitlements_path=entitlements_path,
+        platform=platform,
+        list_codesign_identities=list_codesign_identities,
+        log_file_path=log_file_path,
+        should_use_fast_provisioning_profile_parsing=should_use_fast_provisioning_profile_parsing,
+        strict_provisioning_profile_search=strict_provisioning_profile_search,
+        provisioning_profile_filter=provisioning_profile_filter,
+        no_check_certificates=no_check_certificates,
+    )
+
+    profile_path = selected_profile_info.profile.file_path
+    # @oss-disable[end= ]: if should_verify_entitlements:
+        # @oss-disable[end= ]: _verify_entitlements(entitlements_path, profile_path, platform)
+
+    return SigningContextWithProfileSelection(
+        info_plist_source,
+        info_plist_destination,
+        info_plist_metadata,
+        selected_profile_info,
+    )
+
+
+# IMPORTANT: This enum is a part of incremental API, amend carefully.
+class CodesignConfiguration(str, Enum):
+    fastAdhoc = "fast-adhoc"
+    executionBypass = "execution-bypass"
+    dryRun = "dry-run"
+
+
+def write_empty_codesign_manifest(codesign_manifest_path: Path, bundle_path: Path):
+    with open(codesign_manifest_path, "w") as codesign_manifest_file:
+        codesign_manifest = generate_codesign_manifest(
+            bundle_path, codesign_invocations=[]
+        )
+        json.dump(codesign_manifest, codesign_manifest_file, indent=4)
+
+
+def _postprocess_entitlements_if_needed_for_adhoc_signed_bundle(
+    bundle_path: CodesignedPath,
+    tmp_dir: str,
+    entitlements_suffixed_key_map: Optional[Dict[str, str]] = None,
+    entitlements_removed_keys: Optional[List[str]] = None,
+    entitlements_removed_values_map: Optional[Dict[str, List[str]]] = None,
+) -> CodesignedPath:
+    if bundle_path.entitlements:
+        fd, postprocessed_path = tempfile.mkstemp(dir=tmp_dir)
+        os.close(fd)
+        shutil.copy2(bundle_path.entitlements, postprocessed_path)
+        postprocess_entitlements(
+            postprocessed_path,
+            entitlements_suffixed_key_map=entitlements_suffixed_key_map,
+            entitlements_removed_keys=entitlements_removed_keys,
+            entitlements_removed_values_map=entitlements_removed_values_map,
+        )
+        return CodesignedPath(
+            path=bundle_path.path,
+            entitlements=Path(postprocessed_path),
+            flags=bundle_path.flags,
+            extra_file_paths=bundle_path.extra_file_paths,
+        )
+    return bundle_path
+
+
+def codesign_bundle(
+    bundle_path: CodesignedPath,
+    signing_context: Union[AdhocSigningContext, SigningContextWithProfileSelection],
+    platform: ApplePlatform,
+    codesign_on_copy_paths: List[CodesignedPath],
+    codesign_tool: Optional[Path] = None,
+    codesign_configuration: Optional[CodesignConfiguration] = None,
+    fast_adhoc_signing_probe_enabled: bool = False,
+    codesign_manifest_path: Optional[Path] = None,
+    entitlements_suffixed_key_map: Optional[Dict[str, str]] = None,
+    entitlements_removed_keys: Optional[List[str]] = None,
+    entitlements_removed_values_map: Optional[Dict[str, List[str]]] = None,
+    prepared_entitlements_output_path: Optional[Path] = None,
+) -> None:
+    codesign_on_copy_paths = sorted(
+        codesign_on_copy_paths,
+        key=lambda codesigned_path: codesigned_path.path,
+        # Paths must be signed inside out (i.e., deepest first)
+        reverse=True,
+    )
+
+    with tempfile.TemporaryDirectory() as tmp_dir:
+        selection_profile_context = selection_profile_context_from_signing_context(
+            signing_context
+        )
+        if selection_profile_context:
+            bundle_path_with_prepared_entitlements = (
+                _prepare_entitlements_and_info_plist(
+                    bundle_path=bundle_path,
+                    platform=platform,
+                    signing_context=selection_profile_context,
+                    tmp_dir=tmp_dir,
+                    entitlements_suffixed_key_map=entitlements_suffixed_key_map,
+                    entitlements_removed_keys=entitlements_removed_keys,
+                    entitlements_removed_values_map=entitlements_removed_values_map,
+                )
+            )
+            selected_identity = selection_profile_context.selected_profile_info.identity
+        else:
+            if not isinstance(signing_context, AdhocSigningContext):
+                raise AssertionError(
+                    f"Expected `AdhocSigningContext`, got `{type(signing_context)}` instead."
+                )
+            if signing_context.profile_selection_context:
+                raise AssertionError(
+                    "Expected no profile selection context in `AdhocSigningContext` when `selection_profile_context` is `None`."
+                )
+            bundle_path_with_prepared_entitlements = (
+                _postprocess_entitlements_if_needed_for_adhoc_signed_bundle(
+                    bundle_path,
+                    tmp_dir,
+                    entitlements_suffixed_key_map,
+                    entitlements_removed_keys,
+                    entitlements_removed_values_map,
+                )
+            )
+            selected_identity = signing_context.identity()
+
+        if codesign_configuration is CodesignConfiguration.dryRun:
+            if codesign_tool is None:
+                raise RuntimeError(
+                    "Expected codesign tool not to be the default one when dry run codesigning is requested."
+                )
+            manifest_codesign_factory = ManifestCodesignCommandFactory(
+                DryRunCodesignCommandFactory(
+                    codesign_tool,
+                    selected_identity.subject_common_name,
+                )
+            )
+            _dry_codesign_everything(
+                root=bundle_path_with_prepared_entitlements,
+                codesign_on_copy_paths=codesign_on_copy_paths,
+                identity=selected_identity,
+                tmp_dir=tmp_dir,
+                codesign_command_factory=manifest_codesign_factory,
+                platform=platform,
+            )
+        else:
+            fast_adhoc_signing_enabled = (
+                codesign_configuration is CodesignConfiguration.fastAdhoc
+                and is_fast_adhoc_codesign_allowed(fast_adhoc_signing_probe_enabled)
+            )
+            codesign_execution_bypass_enabled = (
+                codesign_configuration is CodesignConfiguration.executionBypass
+            )
+            underlying_codesign_factory = (
+                DefaultCodesignCommandFactory(codesign_tool)
+                if (not codesign_execution_bypass_enabled)
+                else None
+            )
+            manifest_codesign_factory = ManifestCodesignCommandFactory(
+                underlying_codesign_factory
+            )
+            _codesign_everything(
+                root=bundle_path_with_prepared_entitlements,
+                codesign_on_copy_paths=codesign_on_copy_paths,
+                identity_fingerprint=selected_identity.fingerprint,
+                tmp_dir=tmp_dir,
+                codesign_command_factory=manifest_codesign_factory,
+                platform=platform,
+                fast_adhoc_signing=fast_adhoc_signing_enabled,
+            )
+
+        if codesign_manifest_path:
+            with open(codesign_manifest_path, "w") as codesign_manifest_file:
+                codesign_manifest = (
+                    manifest_codesign_factory.generate_codesign_manifest(
+                        bundle_path.path
+                    )
+                )
+                json.dump(codesign_manifest, codesign_manifest_file, indent=4)
+
+        if (
+            prepared_entitlements_output_path
+            and bundle_path_with_prepared_entitlements.entitlements
+        ):
+            shutil.copy2(
+                bundle_path_with_prepared_entitlements.entitlements,
+                prepared_entitlements_output_path,
+            )
+
+
+def _prepare_entitlements_and_info_plist(
+    bundle_path: CodesignedPath,
+    platform: ApplePlatform,
+    signing_context: SigningContextWithProfileSelection,
+    tmp_dir: str,
+    entitlements_suffixed_key_map: Optional[Dict[str, str]] = None,
+    entitlements_removed_keys: Optional[List[str]] = None,
+    entitlements_removed_values_map: Optional[Dict[str, List[str]]] = None,
+) -> CodesignedPath:
+    info_plist_metadata = signing_context.info_plist_metadata
+    selected_profile = signing_context.selected_profile_info.profile
+    prepared_entitlements_path = prepare_code_signing_entitlements(
+        bundle_path.entitlements,
+        info_plist_metadata.bundle_id,
+        selected_profile,
+        tmp_dir,
+        entitlements_suffixed_key_map=entitlements_suffixed_key_map,
+        entitlements_removed_keys=entitlements_removed_keys,
+        entitlements_removed_values_map=entitlements_removed_values_map,
+    )
+    prepared_info_plist_path = prepare_info_plist(
+        signing_context.info_plist_source,
+        info_plist_metadata,
+        selected_profile,
+        tmp_dir,
+    )
+    os.replace(
+        prepared_info_plist_path,
+        bundle_path.path / signing_context.info_plist_destination,
+    )
+    shutil.copy2(
+        selected_profile.file_path,
+        bundle_path.path / platform.embedded_provisioning_profile_path(),
+    )
+    return CodesignedPath(
+        path=bundle_path.path,
+        entitlements=prepared_entitlements_path,
+        flags=bundle_path.flags,
+        extra_file_paths=None,
+    )
+
+
+async def _fast_read_provisioning_profiles_async(
+    dirpath: Path,
+    read_provisioning_profile_command_factory: IReadProvisioningProfileCommandFactory,
+) -> List[ProvisioningProfileMetadata]:
+    tasks = []
+    for f in os.listdir(dirpath):
+        if f.endswith(".mobileprovision") or f.endswith(".provisionprofile"):
+            filepath = dirpath / f
+            tasks.append(
+                _provisioning_profile_from_file_path_async(
+                    filepath,
+                    read_provisioning_profile_command_factory,
+                    should_use_fast_provisioning_profile_parsing=True,
+                )
+            )
+    results = await asyncio.gather(*tasks)
+    return cast(List[ProvisioningProfileMetadata], results)
+
+
+async def _provisioning_profile_from_file_path_async(
+    path: Path,
+    read_provisioning_profile_command_factory: IReadProvisioningProfileCommandFactory,
+    should_use_fast_provisioning_profile_parsing: bool,
+) -> ProvisioningProfileMetadata:
+    loop = asyncio.get_running_loop()
+    return await loop.run_in_executor(
+        None,
+        _provisioning_profile_from_file_path,
+        path,
+        read_provisioning_profile_command_factory,
+        should_use_fast_provisioning_profile_parsing,
+    )
+
+
+def _read_provisioning_profiles(
+    dirpath: Path,
+    read_provisioning_profile_command_factory: IReadProvisioningProfileCommandFactory,
+) -> List[ProvisioningProfileMetadata]:
+    return [
+        _provisioning_profile_from_file_path(
+            dirpath / f,
+            read_provisioning_profile_command_factory,
+            should_use_fast_provisioning_profile_parsing=False,
+        )
+        for f in os.listdir(dirpath)
+        if (f.endswith(".mobileprovision") or f.endswith(".provisionprofile"))
+    ]
+
+
+def read_provisioning_profile_using_plist_marker(path: Path) -> Optional[bytes]:
+    # Provisioning profiles have a plist embedded in them that we can extract directly.
+    # This is much faster than calling an external command like openssl.
+    with open(path, "rb") as f:
+        content = f.read()
+    start_index = content.find(b"<plist")
+    end_index = content.find(b"</plist>", start_index) + len(b"</plist>")
+    if start_index >= 0 and end_index >= 0:
+        return content[start_index:end_index]
+    return None
+
+
+def _provisioning_profile_from_file_path(
+    path: Path,
+    read_provisioning_profile_command_factory: IReadProvisioningProfileCommandFactory,
+    should_use_fast_provisioning_profile_parsing: bool,
+) -> ProvisioningProfileMetadata:
+    if should_use_fast_provisioning_profile_parsing:
+        plist_data = read_provisioning_profile_using_plist_marker(path)
+        if plist_data is not None:
+            return ProvisioningProfileMetadata.from_provisioning_profile_file_content(
+                path, plist_data
+            )
+        else:
+            _LOGGER.warning(
+                f"Failed to find plist in provisioning profile at {path}. Falling back to slow parsing."
+            )
+
+    # Fallback to slow parsing if fast parsing is disabled or fails
+    return _provisioning_profile_from_file_path_using_factory(
+        path, read_provisioning_profile_command_factory
+    )
+
+
+def _provisioning_profile_from_file_path_using_factory(
+    path: Path,
+    read_provisioning_profile_command_factory: IReadProvisioningProfileCommandFactory,
+) -> ProvisioningProfileMetadata:
+    output: bytes = subprocess.check_output(
+        read_provisioning_profile_command_factory.read_provisioning_profile_command(
+            path
+        ),
+        stderr=subprocess.DEVNULL,
+    )
+    return ProvisioningProfileMetadata.from_provisioning_profile_file_content(
+        path, output
+    )
+
+
+def _read_entitlements_file(path: Optional[Path]) -> Optional[Dict[str, Any]]:
+    if not path:
+        return None
+    with open(path, mode="rb") as f:
+        return detect_format_and_load(f)
+
+
+def _dry_codesign_everything(
+    root: CodesignedPath,
+    codesign_on_copy_paths: List[CodesignedPath],
+    identity: CodeSigningIdentity,
+    tmp_dir: str,
+    codesign_command_factory: ICodesignCommandFactory,
+    platform: ApplePlatform,
+) -> None:
+    codesign_on_copy_directory_paths = [
+        p for p in codesign_on_copy_paths if p.path.is_dir()
+    ]
+
+    # First sign codesign-on-copy directory paths
+    _codesign_paths(
+        paths=codesign_on_copy_directory_paths,
+        identity_fingerprint=identity.fingerprint,
+        tmp_dir=tmp_dir,
+        codesign_command_factory=codesign_command_factory,
+        platform=platform,
+    )
+
+    # Dry codesigning creates a .plist inside every directory it signs.
+    # That approach doesn't work for files so those files are written into .plist for root bundle.
+    codesign_on_copy_file_paths = [
+        p.path.relative_to(root.path)
+        for p in codesign_on_copy_paths
+        if p.path.is_file()
+    ]
+
+    if root.extra_file_paths:
+        raise RuntimeError(
+            f"Root path contains extra file paths: `{root.extra_file_paths}`"
+        )
+
+    root_with_extra_paths = CodesignedPath(
+        path=root.path,
+        entitlements=root.entitlements,
+        flags=root.flags,
+        extra_file_paths=codesign_on_copy_file_paths,
+    )
+
+    # Lastly sign whole bundle
+    _codesign_paths(
+        paths=[root_with_extra_paths],
+        identity_fingerprint=identity.fingerprint,
+        tmp_dir=tmp_dir,
+        codesign_command_factory=codesign_command_factory,
+        platform=platform,
+    )
+
+
+def _codesign_everything(
+    root: CodesignedPath,
+    codesign_on_copy_paths: List[CodesignedPath],
+    identity_fingerprint: str,
+    tmp_dir: str,
+    codesign_command_factory: ICodesignCommandFactory,
+    platform: ApplePlatform,
+    fast_adhoc_signing: bool,
+) -> None:
+    # First sign codesign-on-copy paths
+    codesign_on_copy_filtered_paths = _filter_out_fast_adhoc_paths(
+        paths=codesign_on_copy_paths,
+        identity_fingerprint=identity_fingerprint,
+        platform=platform,
+        fast_adhoc_signing=fast_adhoc_signing,
+    )
+    # If we have > 1 paths to sign (including root bundle), access keychain first to avoid user playing whack-a-mole
+    # with permission grant dialog windows.
+    if codesign_on_copy_filtered_paths:
+        obtain_keychain_permissions(
+            identity_fingerprint, tmp_dir, codesign_command_factory
+        )
+    _codesign_paths(
+        codesign_on_copy_filtered_paths,
+        identity_fingerprint,
+        tmp_dir,
+        codesign_command_factory,
+        platform,
+    )
+    # Lastly sign whole bundle
+    root_filtered_paths = _filter_out_fast_adhoc_paths(
+        paths=[root],
+        identity_fingerprint=identity_fingerprint,
+        platform=platform,
+        fast_adhoc_signing=fast_adhoc_signing,
+    )
+    _codesign_paths(
+        root_filtered_paths,
+        identity_fingerprint,
+        tmp_dir,
+        codesign_command_factory,
+        platform,
+    )
+
+
+@dataclass
+class ParallelProcess:
+    process: subprocess.Popen[bytes]
+    stdout_path: Optional[str]
+    stderr_path: str
+
+    def check_result(self) -> None:
+        if self.process.returncode == 0:
+            return
+        with ExitStack() as stack:
+            command = f"\ncommand:\n{self.process.args}\n"
+            stderr = stack.enter_context(open(self.stderr_path, encoding="utf8"))
+            stderr_string = f"\nstderr:\n{stderr.read()}\n"
+            stdout = (
+                stack.enter_context(open(self.stdout_path, encoding="utf8"))
+                if self.stdout_path
+                else None
+            )
+            stdout_string = f"\nstdout:\n{stdout.read()}\n" if stdout else ""
+            raise RuntimeError(f"{command}{stdout_string}{stderr_string}")
+
+
+def _spawn_process(
+    command: List[Union[str, Path]],
+    tmp_dir: str,
+    stack: ExitStack,
+    pipe_stdout: bool = False,
+) -> ParallelProcess:
+    if pipe_stdout:
+        stdout_path = None
+        stdout = subprocess.PIPE
+    else:
+        stdout_path = os.path.join(tmp_dir, uuid.uuid4().hex)
+        stdout = stack.enter_context(open(stdout_path, "w"))
+    stderr_path = os.path.join(tmp_dir, uuid.uuid4().hex)
+    stderr = stack.enter_context(open(stderr_path, "w"))
+    _LOGGER.info(f"Executing command: {command}")
+    process = subprocess.Popen(command, stdout=stdout, stderr=stderr)
+    return ParallelProcess(
+        process,
+        stdout_path,
+        stderr_path,
+    )
+
+
+def _spawn_codesign_process(
+    path: CodesignedPath,
+    identity_fingerprint: str,
+    tmp_dir: str,
+    codesign_command_factory: ICodesignCommandFactory,
+    stack: ExitStack,
+) -> ParallelProcess:
+    command = codesign_command_factory.codesign_command(
+        path.path,
+        identity_fingerprint,
+        path.entitlements,
+        path.flags,
+        path.extra_file_paths,
+    )
+    return _spawn_process(command=command, tmp_dir=tmp_dir, stack=stack)
+
+
+def _codesign_paths_serially(
+    paths: List[CodesignedPath],
+    identity_fingerprint: str,
+    tmp_dir: str,
+    codesign_command_factory: ICodesignCommandFactory,
+    platform: ApplePlatform,
+) -> None:
+    with ExitStack() as stack:
+        for path in paths:
+            p = _spawn_codesign_process(
+                path=path,
+                identity_fingerprint=identity_fingerprint,
+                tmp_dir=tmp_dir,
+                codesign_command_factory=codesign_command_factory,
+                stack=stack,
+            )
+            p.process.wait()
+            p.check_result()
+
+
+def _codesign_paths_in_parallel(
+    paths: List[CodesignedPath],
+    identity_fingerprint: str,
+    tmp_dir: str,
+    codesign_command_factory: ICodesignCommandFactory,
+    platform: ApplePlatform,
+) -> None:
+    """Codesigns several paths in parallel."""
+    processes: List[ParallelProcess] = []
+    with ExitStack() as stack:
+        for path in paths:
+            process = _spawn_codesign_process(
+                path=path,
+                identity_fingerprint=identity_fingerprint,
+                tmp_dir=tmp_dir,
+                codesign_command_factory=codesign_command_factory,
+                stack=stack,
+            )
+            processes.append(process)
+        for p in processes:
+            p.process.wait()
+    for p in processes:
+        p.check_result()
+
+
+def _can_codesign_paths_in_parallel(codesigned_paths: List[CodesignedPath]) -> bool:
+    # To enable parallel signing, there must be no nesting of any codesigned paths,
+    # as codesigning must be performed "inside out" - deeper items signed first,
+    # as parent items need to seal the contained items as part of their signature.
+    #
+    # To detect nesting, we reverse sort all paths and only need to check
+    # neighboring elements. For example, imagine the following elements:
+    # `a/b/c`
+    # `a/b`
+    # `b`
+    # `c`
+    #
+    # For each element, check if the element is a prefix of the previous element.
+    # In the example above, checking if `a/b` is a prefix of `a/b/c` means its
+    # unsafe to codesign in parallel.
+    paths = sorted([str(path.path) for path in codesigned_paths], reverse=True)
+    for index, current_path in enumerate(paths):
+        if index == 0:
+            continue
+        previous_path = paths[index - 1]
+        if previous_path.startswith(current_path):
+            _LOGGER.warning(
+                f"Found overlapping codesigned paths: {previous_path}, {current_path}"
+            )
+            return False
+    return True
+
+
+def _codesign_paths(
+    paths: List[CodesignedPath],
+    identity_fingerprint: str,
+    tmp_dir: str,
+    codesign_command_factory: ICodesignCommandFactory,
+    platform: ApplePlatform,
+) -> None:
+    can_codesign_in_parallel = _can_codesign_paths_in_parallel(paths)
+    signing_function = (
+        _codesign_paths_in_parallel
+        if can_codesign_in_parallel
+        else _codesign_paths_serially
+    )
+    signing_function(
+        paths=paths,
+        identity_fingerprint=identity_fingerprint,
+        tmp_dir=tmp_dir,
+        codesign_command_factory=codesign_command_factory,
+        platform=platform,
+    )
+
+
+def _filter_out_fast_adhoc_paths(
+    paths: List[CodesignedPath],
+    identity_fingerprint: str,
+    platform: ApplePlatform,
+    fast_adhoc_signing: bool,
+) -> List[CodesignedPath]:
+    if not fast_adhoc_signing:
+        return paths
+    # TODO(T149863217): Make skip checks run in parallel, they're usually fast (~15ms)
+    # but if we have many of them (e.g., 30+ frameworks), it can add about ~0.5s.'
+    return [
+        p
+        for p in paths
+        if not should_skip_adhoc_signing_path(
+            p.path,
+            identity_fingerprint,
+            p.entitlements,
+            platform,
+        )
+    ]
+
+
+def obtain_keychain_permissions(
+    identity_fingerprint: str,
+    tmp_dir: str,
+    codesign_command_factory: ICodesignCommandFactory,
+) -> None:
+    with (
+        ExitStack() as stack,
+        importlib.resources.path(
+            __package__, "dummy_binary_for_signing"
+        ) as dummy_binary_path,
+    ):
+        # Copy the binary to avoid races vs other bundling actions
+        dummy_binary_copied = os.path.join(tmp_dir, "dummy_binary_for_signing")
+        shutil.copyfile(dummy_binary_path, dummy_binary_copied, follow_symlinks=True)
+        p = _spawn_codesign_process(
+            path=CodesignedPath(
+                path=Path(dummy_binary_copied),
+                entitlements=None,
+                flags=["--timestamp=none"],
+                extra_file_paths=None,
+            ),
+            identity_fingerprint=identity_fingerprint,
+            tmp_dir=tmp_dir,
+            codesign_command_factory=codesign_command_factory,
+            stack=stack,
+        )
+        p.process.wait()
+    p.check_result()
diff --git a/buck2/prelude/apple/tools/code_signing/codesign_command_factory.py b/buck2/prelude/apple/tools/code_signing/codesign_command_factory.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/codesign_command_factory.py
@@ -0,0 +1,172 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import base64
+import dataclasses
+from abc import ABCMeta, abstractmethod
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+
+@dataclasses.dataclass
+class CodesignInvocation:
+    path: Path
+    identity_fingerprint: str
+    entitlements: Optional[Path]
+    codesign_args: List[str]
+    extra_file_paths: Optional[List[Path]]
+
+    def as_json(self, base_path: Path) -> Optional[Dict[str, Any]]:
+        if not self.path.is_relative_to(base_path):
+            # The dummy binary to be signed is not part of the bundle,
+            # so it can be ignored
+            return None
+
+        invocation = {
+            "path": str(self.path.relative_to(base_path)),
+            "identity_fingerprint": self.identity_fingerprint,
+            "codesign_args": self.codesign_args,
+        }
+        if self.entitlements:
+            with open(self.entitlements, "rb") as entitlements_file:
+                # We cannot rely on the presence of the entitlements file by
+                # any consumers of the manifest because the file might not
+                # be materialized or might be a temp file prepared by the
+                # bundling script.
+                entitlements_bytes = base64.b64encode(entitlements_file.read())
+                invocation["entitlements"] = entitlements_bytes.decode("utf-8")
+        if self.extra_file_paths:
+            invocation["extra_file_paths"] = [
+                str(extra_path) for extra_path in self.extra_file_paths
+            ]
+        return invocation
+
+
+def generate_codesign_manifest(
+    base_path: Path, codesign_invocations: list[CodesignInvocation]
+) -> Dict[str, Any]:
+    json_invocations = [
+        invocation.as_json(base_path) for invocation in codesign_invocations
+    ]
+    valid_json_invocations = list(filter(lambda x: x is not None, json_invocations))
+    return {
+        "bundle_name": base_path.name,
+        "invocations": valid_json_invocations,
+    }
+
+
+class ICodesignCommandFactory(metaclass=ABCMeta):
+    @abstractmethod
+    def codesign_command(
+        self,
+        path: Path,
+        identity_fingerprint: str,
+        entitlements: Optional[Path],
+        codesign_args: List[str],
+        extra_file_paths: Optional[List[Path]],
+    ) -> List[Union[str, Path]]:
+        raise NotImplementedError
+
+
+class ManifestCodesignCommandFactory(ICodesignCommandFactory):
+    def __init__(self, underlying: Optional[ICodesignCommandFactory]):
+        self.underlying = underlying
+        self.invocations = []
+
+    def codesign_command(
+        self,
+        path: Path,
+        identity_fingerprint: str,
+        entitlements: Optional[Path],
+        codesign_args: List[str],
+        extra_file_paths: Optional[List[Path]],
+    ) -> List[Union[str, Path]]:
+        self.invocations.append(
+            CodesignInvocation(
+                path=path,
+                identity_fingerprint=identity_fingerprint,
+                entitlements=entitlements,
+                codesign_args=codesign_args,
+                extra_file_paths=extra_file_paths,
+            )
+        )
+        if self.underlying:
+            return self.underlying.codesign_command(
+                path=path,
+                identity_fingerprint=identity_fingerprint,
+                entitlements=entitlements,
+                codesign_args=codesign_args,
+                extra_file_paths=extra_file_paths,
+            )
+        return ["/usr/bin/true"]
+
+    def generate_codesign_manifest(self, base_path: Path) -> Dict[str, Any]:
+        return generate_codesign_manifest(base_path, self.invocations)
+
+
+class DefaultCodesignCommandFactory(ICodesignCommandFactory):
+    codesign_tool: Path
+    _command_args: List[str] = ["--force", "--sign"]
+
+    def __init__(self, codesign_tool: Optional[Path]) -> None:
+        self.codesign_tool = codesign_tool or Path("codesign")
+
+    def codesign_command(
+        self,
+        path: Path,
+        identity_fingerprint: str,
+        entitlements: Optional[Path],
+        codesign_args: List[str],
+        extra_file_paths: Optional[List[Path]],
+    ) -> List[Union[str, Path]]:
+        if extra_file_paths:
+            raise RuntimeError(
+                f"Extra codesign paths unsupported for non-dry signing (path: `{path}`, extra paths: `{extra_file_paths}`)"
+            )
+        entitlements_args = ["--entitlements", entitlements] if entitlements else []
+        return (
+            [self.codesign_tool]
+            + DefaultCodesignCommandFactory._command_args
+            + [identity_fingerprint]
+            + codesign_args
+            + entitlements_args
+            + [path]
+        )
+
+
+class DryRunCodesignCommandFactory(ICodesignCommandFactory):
+    codesign_tool: Path
+    subject_common_name: str
+
+    def __init__(self, codesign_tool: Path, subject_common_name: str) -> None:
+        self.codesign_tool = codesign_tool
+        self.subject_common_name = subject_common_name
+
+    def codesign_command(
+        self,
+        path: Path,
+        identity_fingerprint: str,
+        entitlements: Optional[Path],
+        codesign_args: List[str],
+        extra_file_paths: Optional[List[Path]],
+    ) -> List[Union[str, Path]]:
+        args = [
+            path,
+            "--identity",
+            identity_fingerprint,
+            "--subject-common-name",
+            self.subject_common_name,
+        ]
+        if entitlements:
+            args += ["--entitlements", entitlements] if entitlements else []
+        if extra_file_paths:
+            args += ["--extra-paths-to-sign"]
+            args += extra_file_paths
+        return [self.codesign_tool] + args
diff --git a/buck2/prelude/apple/tools/code_signing/codesign_diagnostics_text.py b/buck2/prelude/apple/tools/code_signing/codesign_diagnostics_text.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/codesign_diagnostics_text.py
@@ -0,0 +1,26 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+class CodesignDiagnosticsText:
+    """Generic remediation text for codesigning diagnostic messages.
+
+    In Meta builds, this class is replaced by the Meta-specific version from
+    meta_only/codesign_diagnostics_text.py via @oss-disable/@oss-enable.
+    """
+
+    CERT_REMEDIATION: str = "Check that your signing certificate is installed in your keychain and has not expired. Re-download from the Apple Developer Portal if needed."
+    ENTITLEMENTS_REMEDIATION: str = "Download and install the latest provisioning profile with the correct entitlements from the Apple Developer Portal."
+    PLATFORM_LINK: str = (
+        "you would need to download and install it from the Apple Developer Portal"
+    )
+    PROFILES_DOWNLOAD: str = (
+        "Download the latest provisioning profiles from the Apple Developer Portal."
+    )
+    DEVICE_LINK: str = ""
+    NO_PROFILES_REMEDIATION: str = "Download and install the required provisioning profiles from the Apple Developer Portal.\n"
diff --git a/buck2/prelude/apple/tools/code_signing/dummy_binary_for_signing.c b/buck2/prelude/apple/tools/code_signing/dummy_binary_for_signing.c
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/dummy_binary_for_signing.c
@@ -0,0 +1,13 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+int main() {
+  return 0;
+}
diff --git a/buck2/prelude/apple/tools/code_signing/fast_adhoc.py b/buck2/prelude/apple/tools/code_signing/fast_adhoc.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/fast_adhoc.py
@@ -0,0 +1,202 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import logging
+import os
+import plistlib
+import subprocess
+import sys
+from pathlib import Path
+from typing import List, Optional, Tuple, Union
+
+# @oss-disable[end= ]: from ..meta_only.codesign_rust.check_adhoc_signature import (
+    # @oss-disable[end= ]: read_signature_info,
+# @oss-disable[end= ]: )
+from .apple_platform import ApplePlatform
+
+_LOGGER: logging.Logger = logging.getLogger(__name__)
+
+
+def _find_executable_for_signed_path(path: Path, platform: ApplePlatform) -> Path:
+    extension = path.suffix
+    if extension not in [".app", ".appex", ".framework"]:
+        return path
+
+    contents_subdir = "Contents/MacOS" if platform.is_desktop() else ""
+    contents_dir = path / contents_subdir
+
+    # Read binary name from Info.plist
+    info_plist_path = path / (
+        "Contents/Info.plist" if platform.is_desktop() else "Info.plist"
+    )
+    with open(info_plist_path, "rb") as file:
+        plist = plistlib.load(file)
+    executable_name = plist["CFBundleExecutable"]
+
+    return contents_dir / executable_name
+
+
+def _logged_subprocess_run(
+    name: str, why: str, args: List[Union[str, Path]]
+) -> subprocess.CompletedProcess[str]:
+    _LOGGER.info(f"  Calling {name} to {why}: `{args}`")
+    result = subprocess.run(
+        args,
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+        encoding="utf-8",
+    )
+
+    _LOGGER.info(f"  {name} exit code: {result.returncode}")
+    if result.stdout:
+        _LOGGER.info(f"  {name} stdout:")
+        _LOGGER.info(
+            "\n" + "\n".join([f"    {line}" for line in result.stdout.split("\n")])
+        )
+    if result.stderr:
+        _LOGGER.info(f"  {name} stderr:")
+        _LOGGER.info(
+            "\n" + "\n".join([f"    {line}" for line in result.stderr.split("\n")])
+        )
+
+    return result
+
+
+def is_fast_adhoc_codesign_allowed(probe_enabled: bool) -> bool:
+    if sys.platform == "darwin":
+        # Xcode's active-developer-dir symlink is /var/db/xcode_select_link on
+        # older macOS and /var/select/developer_dir on Sonoma+/Xcode 15+.
+        if not os.path.exists("/var/db/xcode_select_link") and not os.path.exists(
+            "/var/select/developer_dir"
+        ):
+            _LOGGER.info(
+                "Developer tools do not exist, cannot use `otool`, fast adhoc signing not allowed"
+            )
+            return False
+        return True
+    # @oss-disable[end= ]: if probe_enabled:
+        # @oss-disable[end= ]: return True
+    _LOGGER.info(f"Running on {sys.platform}, fast adhoc signing not allowed")
+    return False
+
+
+def _read_signature_info_macos(
+    path: Path,
+    platform: ApplePlatform,
+    check_entitlements: bool,
+) -> Optional[Tuple[bool, bool]]:
+    """Reads adhoc/entitlements info via `/usr/bin/codesign` and `/usr/bin/otool`.
+
+    The entitlements probe runs only when `check_entitlements=True` and the path
+    is adhoc-signed; a non-adhoc path is never skipped, so its entitlements are
+    never inspected and we return early to avoid a wasted `otool` subprocess.
+    """
+    codesign_args: List[Union[str, Path]] = ["codesign", "-d", "-v", path]
+    codesign_result = _logged_subprocess_run(
+        "codesign", "check pre-existing signature", codesign_args
+    )
+
+    # Anything that's _already_ adhoc signed can be skipped.
+    # On ARM64 systems, the linker will already codesign using adhoc,
+    # so performing the signing twice is unnecessary.
+    is_adhoc = "Signature=adhoc" in codesign_result.stderr
+
+    if not is_adhoc:
+        return (False, False)
+
+    has_entitlements_section = False
+    if check_entitlements:
+        # Adhoc entitlements do not require postprocessing, so we just need to check existence
+        binary_path = _find_executable_for_signed_path(path, platform)
+        otool_arg: List[Union[str, Path]] = [
+            "/usr/bin/otool",
+            "-s",
+            "__TEXT",
+            "__entitlements",
+            binary_path,
+        ]
+        otool_result = _logged_subprocess_run(
+            "otool", "check entitlements presence in binary", otool_arg
+        )
+        has_entitlements_section = (
+            "Contents of (__TEXT,__entitlements) section" in otool_result.stdout
+        )
+
+    return (is_adhoc, has_entitlements_section)
+
+
+def _read_signature_info(
+    path: Path,
+    platform: ApplePlatform,
+    check_entitlements: bool,
+) -> Optional[Tuple[bool, bool]]:
+    """Platform-dispatching read of signature info.
+
+    Returns None on unsupported platforms; should_skip_adhoc_signing_path
+    treats None as "could not verify, do not skip".
+    """
+    if sys.platform == "darwin":
+        return _read_signature_info_macos(path, platform, check_entitlements)
+    # @oss-disable[end= ]: elif sys.platform == "linux":
+        # @oss-disable[end= ]: binary = _find_executable_for_signed_path(path, platform)
+        # @oss-disable[end= ]: return read_signature_info(binary, check_entitlements)
+    return None
+
+
+def should_skip_adhoc_signing_path(
+    path: Path,
+    identity_fingerprint: str,
+    entitlements_path: Optional[Path],
+    platform: ApplePlatform,
+) -> bool:
+    logging.getLogger(__name__).info(
+        f"Checking if should skip adhoc signing path `{path}` with identity `{identity_fingerprint}` and entitlements `{entitlements_path}` for platform `{platform}`"
+    )
+
+    if identity_fingerprint != "-":
+        # Non-adhoc environments _always_ code sign
+        _LOGGER.info("  Requested non-adhoc signing, not adhoc skipping signing")
+        return False
+
+    if "libclang_rt" in str(path):
+        # Sanitizer runtime dylibs require re-signing, even though they're already pre-signed.
+        # Otherwise, `codesign` fails to sign the top-level bundle (as the adhoc pre-signed
+        # sanitizer dylibs have been signed within a different context).
+        return False
+
+    info = _read_signature_info(
+        path, platform, check_entitlements=entitlements_path is not None
+    )
+
+    if info is None:
+        _LOGGER.info("  Could not read signature info, not skipping adhoc signing")
+        return False
+
+    is_adhoc, has_entitlements_section = info
+    if not is_adhoc:
+        _LOGGER.info("  Path is not adhoc signed, not skipping adhoc signing")
+        return False
+
+    # The entitlements file can be ignored under adhoc signing because:
+    #
+    # - Frameworks/dylibs do not need entitlements (they operate under the entitlements of their loading binary)
+    # - Apps (+ app extensions) have binaries which embed the entitlements via __entitlements section at link time
+    #
+    # Note that certain features require non-adhoc signing (e.g., app groups) while other features like keychain
+    # and "Sign in with Apple" just need the entitlements present in the binary (which it will per the above).
+    if entitlements_path and not has_entitlements_section:
+        binary_path = _find_executable_for_signed_path(path, platform)
+        _LOGGER.info(
+            f"  Binary path `{binary_path}` does not contain entitlements, not skipping adhoc signing"
+        )
+        return False
+
+    _LOGGER.info(f"  All checks passed for `{path}`, skipping adhoc signing")
+    return True
diff --git a/buck2/prelude/apple/tools/code_signing/identity.py b/buck2/prelude/apple/tools/code_signing/identity.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/identity.py
@@ -0,0 +1,69 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from enum import Enum
+from typing import List
+
+from .serialization import expect_dict, expect_keys, expect_str
+
+
+@dataclass
+class CodeSigningIdentity:
+    fingerprint: str
+    subject_common_name: str
+
+    class _ReGroupName(str, Enum):
+        fingerprint = "fingerprint"
+        subject_common_name = "subject_common_name"
+
+    _re_string: str = '(?P<{fingerprint}>[A-F0-9]{{40}}) "(?P<{subject_common_name}>.+)"(?!.*CSSMERR_.+)'.format(
+        fingerprint=_ReGroupName.fingerprint.value,
+        subject_common_name=_ReGroupName.subject_common_name.value,
+    )
+
+    _pattern: re.Pattern[str] = re.compile(_re_string)
+
+    @classmethod
+    def parse_security_stdout(cls, text: str) -> List[CodeSigningIdentity]:
+        return [
+            CodeSigningIdentity(
+                match.group(cls._ReGroupName.fingerprint.value),
+                match.group(cls._ReGroupName.subject_common_name.value),
+            )
+            for match in re.finditer(cls._pattern, text)
+        ]
+
+    def to_dict(self) -> dict[str, str]:
+        return {
+            "fingerprint": self.fingerprint,
+            "subject_common_name": self.subject_common_name,
+        }
+
+    @staticmethod
+    def from_dict(value: object) -> CodeSigningIdentity:
+        data = expect_dict(value, "CodeSigningIdentity")
+        expect_keys(
+            data,
+            "CodeSigningIdentity",
+            frozenset({"fingerprint", "subject_common_name"}),
+        )
+        return CodeSigningIdentity(
+            fingerprint=expect_str(
+                data["fingerprint"], "CodeSigningIdentity.fingerprint"
+            ),
+            subject_common_name=expect_str(
+                data["subject_common_name"],
+                "CodeSigningIdentity.subject_common_name",
+            ),
+        )
diff --git a/buck2/prelude/apple/tools/code_signing/identity_test.py b/buck2/prelude/apple/tools/code_signing/identity_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/identity_test.py
@@ -0,0 +1,47 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import unittest
+
+from .identity import CodeSigningIdentity
+
+
+class TestParse(unittest.TestCase):
+    def test_multiple_certificates_are_parsed(self):
+        text = r"""
+  1) 5C5E14F66E6B3C2697107764C9D728EE5AB393B9 "Apple Development: Johnny Appleseed (B4H6M5LP3J)"
+  2) 3348E051F7E7E1ED509D2D620567BAF796210C36 "iPhone Developer: Johnny Appleseed (B4H6M5LP3J)"
+     2 valid identities found
+"""
+        expected = [
+            CodeSigningIdentity(
+                "5C5E14F66E6B3C2697107764C9D728EE5AB393B9",
+                "Apple Development: Johnny Appleseed (B4H6M5LP3J)",
+            ),
+            CodeSigningIdentity(
+                "3348E051F7E7E1ED509D2D620567BAF796210C36",
+                "iPhone Developer: Johnny Appleseed (B4H6M5LP3J)",
+            ),
+        ]
+        result = CodeSigningIdentity.parse_security_stdout(text)
+        self.assertEqual(expected, result)
+
+    def test_expired_certificates_are_ignored(self):
+        text = r"""
+  1) 5C5E14F66E6B3C2697107764C9D728EE5AB393B9 "Apple Development: Johnny Appleseed (B4H6M5LP3J)"
+  2) 3348E051F7E7E1ED509D2D620567BAF796210C36 "iPhone Developer: Johnny Appleseed (B4H6M5LP3J)" (CSSMERR_TP_CERT_EXPIRED)
+     2 valid identities found
+"""
+        expected = [
+            CodeSigningIdentity(
+                "5C5E14F66E6B3C2697107764C9D728EE5AB393B9",
+                "Apple Development: Johnny Appleseed (B4H6M5LP3J)",
+            ),
+        ]
+        result = CodeSigningIdentity.parse_security_stdout(text)
+        self.assertEqual(expected, result)
diff --git a/buck2/prelude/apple/tools/code_signing/info_plist_metadata.py b/buck2/prelude/apple/tools/code_signing/info_plist_metadata.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/info_plist_metadata.py
@@ -0,0 +1,65 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import IO, Optional
+
+from apple.tools.plistlib_utils import detect_format_and_load
+
+from .serialization import (
+    expect_bool,
+    expect_dict,
+    expect_keys,
+    expect_optional_str,
+    expect_str,
+)
+
+
+@dataclass
+class InfoPlistMetadata:
+    bundle_id: str
+    bundle_type: Optional[str]
+    is_watchos_app: bool
+
+    @staticmethod
+    def from_file(info_plist_file: IO[bytes]) -> InfoPlistMetadata:
+        root = detect_format_and_load(info_plist_file)
+        return InfoPlistMetadata(
+            root["CFBundleIdentifier"],
+            root.get("CFBundlePackageType"),
+            root.get("WKApplication", False),
+        )
+
+    def to_dict(self) -> dict[str, object]:
+        return {
+            "bundle_id": self.bundle_id,
+            "bundle_type": self.bundle_type,
+            "is_watchos_app": self.is_watchos_app,
+        }
+
+    @staticmethod
+    def from_dict(value: object) -> InfoPlistMetadata:
+        data = expect_dict(value, "InfoPlistMetadata")
+        expect_keys(
+            data,
+            "InfoPlistMetadata",
+            frozenset({"bundle_id", "bundle_type", "is_watchos_app"}),
+        )
+        return InfoPlistMetadata(
+            bundle_id=expect_str(data["bundle_id"], "InfoPlistMetadata.bundle_id"),
+            bundle_type=expect_optional_str(
+                data["bundle_type"], "InfoPlistMetadata.bundle_type"
+            ),
+            is_watchos_app=expect_bool(
+                data["is_watchos_app"], "InfoPlistMetadata.is_watchos_app"
+            ),
+        )
diff --git a/buck2/prelude/apple/tools/code_signing/info_plist_metadata_test.py b/buck2/prelude/apple/tools/code_signing/info_plist_metadata_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/info_plist_metadata_test.py
@@ -0,0 +1,68 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import io
+import unittest
+
+from .info_plist_metadata import InfoPlistMetadata
+
+
+class TestParse(unittest.TestCase):
+    def test_canary(self):
+        plist = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>CFBundleIdentifier</key>
+    <string>com.company.application</string>
+    <key>CFBundlePackageType</key>
+    <string>APPL</string>
+    <key>WKApplication</key>
+    <false/>
+</dict>
+</plist>
+"""
+        )
+        expected = InfoPlistMetadata("com.company.application", "APPL", False)
+        result = InfoPlistMetadata.from_file(plist)
+        self.assertEqual(expected, result)
+
+    def test_not_watch_application_by_default(self):
+        plist = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>CFBundleIdentifier</key>
+    <string>com.company.application</string>
+    <key>CFBundlePackageType</key>
+    <string>APPL</string>
+</dict>
+</plist>
+"""
+        )
+        expected = InfoPlistMetadata("com.company.application", "APPL", False)
+        result = InfoPlistMetadata.from_file(plist)
+        self.assertEqual(expected, result)
+
+    def test_package_type_can_be_omitted(self):
+        plist = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>CFBundleIdentifier</key>
+    <string>com.company.application</string>
+</dict>
+</plist>
+"""
+        )
+        expected = InfoPlistMetadata("com.company.application", None, False)
+        result = InfoPlistMetadata.from_file(plist)
+        self.assertEqual(expected, result)
diff --git a/buck2/prelude/apple/tools/code_signing/list_codesign_identities.py b/buck2/prelude/apple/tools/code_signing/list_codesign_identities.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/list_codesign_identities.py
@@ -0,0 +1,85 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+import subprocess
+from abc import ABCMeta, abstractmethod
+from typing import List
+
+from .identity import CodeSigningIdentity
+
+
+class IListCodesignIdentities(metaclass=ABCMeta):
+    @abstractmethod
+    def list_codesign_identities(self) -> List[CodeSigningIdentity]:
+        raise NotImplementedError
+
+    @abstractmethod
+    def raw_command(self) -> str:
+        raise NotImplementedError
+
+
+class ListCodesignIdentities(IListCodesignIdentities):
+    _default_command = ["security", "find-identity", "-v", "-p", "codesigning"]
+
+    def __init__(self, command: List[str]) -> None:
+        self.command = command
+
+    @classmethod
+    def default(cls) -> IListCodesignIdentities:
+        return cls(cls._default_command)
+
+    @classmethod
+    def override(cls, command: List[str]) -> IListCodesignIdentities:
+        return cls(command)
+
+    def list_codesign_identities(self) -> List[CodeSigningIdentity]:
+        return _list_identities(self.command)
+
+    def raw_command(self) -> str:
+        return " ".join(self.command)
+
+
+def _list_identities(
+    command: List[str],
+) -> List[CodeSigningIdentity]:
+    output = subprocess.check_output(
+        command,
+        encoding="utf-8",
+    )
+    return CodeSigningIdentity.parse_security_stdout(output)
+
+
+class AdHocListCodesignIdentities(IListCodesignIdentities):
+    def __init__(
+        self, original: IListCodesignIdentities, subject_common_name: str
+    ) -> None:
+        self.original = original
+        self.subject_common_name = subject_common_name
+
+    def list_codesign_identities(self) -> List[CodeSigningIdentity]:
+        unfiltered_identities = self.original.list_codesign_identities()
+        identity = next(
+            (
+                i
+                for i in unfiltered_identities
+                if i.subject_common_name == self.subject_common_name
+            ),
+            None,
+        )
+        if not identity:
+            raise RuntimeError(
+                f"No identity found with subject common name `{self.subject_common_name}`"
+            )
+        return [identity]
+
+    def raw_command(self) -> str:
+        return self.original.raw_command()
diff --git a/buck2/prelude/apple/tools/code_signing/main.py b/buck2/prelude/apple/tools/code_signing/main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/main.py
@@ -0,0 +1,215 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import pathlib
+import sys
+from typing import List, Optional
+
+from tap import Tap
+
+from .apple_platform import ApplePlatform
+from .codesign_bundle import (
+    AdhocSigningContext,
+    codesign_bundle,
+    CodesignedPath,
+    signing_context_with_profile_selection,
+)
+from .list_codesign_identities import ListCodesignIdentities
+from .provisioning_profile_selection import CodeSignProvisioningError
+
+
+class Arguments(Tap):
+    """
+    Tool which code signs the Apple bundle. `Info.plist` file is amended as a part of it.
+    """
+
+    # pyre-fixme[13]: Attribute `bundle_path` is never initialized.
+    bundle_path: pathlib.Path
+    # pyre-fixme[13]: Attribute `info_plist` is never initialized.
+    info_plist: pathlib.Path
+    entitlements: Optional[pathlib.Path] = None
+    profiles_dir: Optional[pathlib.Path] = None
+    ad_hoc: bool = False
+    ad_hoc_codesign_identity: Optional[str] = None
+    # pyre-fixme[13]: Attribute `platform` is never initialized.
+    platform: ApplePlatform
+    codesign_on_copy: Optional[List[pathlib.Path]] = None
+    fast_provisioning_profile_parsing: bool = False
+    strict_provisioning_profile_search: bool = False
+    provisioning_profile_filter: Optional[str] = None
+    only_select_provisioning_profile: bool = False
+    no_check_certificates: bool = False
+
+    def configure(self) -> None:
+        """
+        Configure the arguments.
+        """
+        self.add_argument(
+            "--bundle-path",
+            metavar="</path/to/app.bundle>",
+            type=pathlib.Path,
+            required=True,
+            help="Absolute path to Apple bundle result.",
+        )
+        self.add_argument(
+            "--info-plist",
+            metavar="<Info.plist>",
+            type=pathlib.Path,
+            required=True,
+            help="Bundle relative destination path to Info.plist file if it is present in bundle.",
+        )
+        self.add_argument(
+            "--entitlements",
+            metavar="<Entitlements.plist>",
+            type=pathlib.Path,
+            required=False,
+            help="Path to file with entitlements to be used during code signing. If it's not provided the minimal entitlements are going to be generated.",
+        )
+        self.add_argument(
+            "--profiles-dir",
+            metavar="</provisioning/profiles/directory>",
+            type=pathlib.Path,
+            required=False,
+            action="append",
+            help="Path to directory with provisioning profile files. Required if code signing is not ad-hoc. Can be specified multiple times.",
+        )
+        self.add_argument(
+            "--ad-hoc",
+            action="store_true",
+            required=False,
+            help="Perform ad-hoc signing if set.",
+        )
+        self.add_argument(
+            "--ad-hoc-codesign-identity",
+            metavar="<identity>",
+            type=str,
+            required=False,
+            help="Codesign identity to use when ad-hoc signing is performed.",
+        )
+        self.add_argument(
+            "--platform",
+            metavar="<apple platform>",
+            type=ApplePlatform,
+            required=True,
+            help="Apple platform for which the bundle was built.",
+        )
+        self.add_argument(
+            "--codesign-on-copy",
+            metavar="<codesign/this/path>",
+            type=pathlib.Path,
+            action="append",
+            required=False,
+            help="Bundle relative path that should be codesigned prior to result bundle.",
+        )
+        self.add_argument(
+            "--fast-provisioning-profile-parsing",
+            action="store_true",
+            required=False,
+            help="Uses experimental faster provisioning profile parsing.",
+        )
+        self.add_argument(
+            "--strict-provisioning-profile-search",
+            action="store_true",
+            required=False,
+            help="Fail code signing if more than one matching profile found.",
+        )
+        self.add_argument(
+            "--provisioning-profile-filter",
+            metavar="<regex>",
+            type=str,
+            required=False,
+            help="Regex to disambiguate multiple matching profiles, evaluated against provisioning profile filename.",
+        )
+        self.add_argument(
+            "--only-select-provisioning-profile",
+            action="store_true",
+            required=False,
+            help="Skip codesigning and just output the path to the selected provisioning profile to stdout.",
+        )
+        self.add_argument(
+            "--no-check-certificates",
+            action="store_true",
+            required=False,
+            help="Skip the check on code signing identities when selecting provisioning profile.",
+        )
+
+
+# Add emoji to beginning of actionable error message so it stands out more.
+def decorate_error_message(message: str) -> str:
+    return " ".join(["❗️", message])
+
+
+def _main() -> None:
+    args = Arguments().parse_args()
+    try:
+        if args.ad_hoc:
+            if args.only_select_provisioning_profile:
+                print(
+                    "No provisioning profile is selected for ad-hoc signing.",
+                    file=sys.stderr,
+                )
+                exit(1)
+            signing_context = AdhocSigningContext(
+                codesign_identity=args.ad_hoc_codesign_identity
+            )
+        else:
+            assert args.profiles_dir, (
+                "Path to directory with provisioning profile files should be set when signing is not ad-hoc."
+            )
+            signing_context = signing_context_with_profile_selection(
+                info_plist_source=args.bundle_path / args.info_plist,
+                info_plist_destination=args.info_plist,
+                provisioning_profiles_dirs=args.profiles_dir,
+                entitlements_path=args.entitlements,
+                list_codesign_identities=ListCodesignIdentities.default(),
+                platform=args.platform,
+                should_use_fast_provisioning_profile_parsing=args.fast_provisioning_profile_parsing,
+                strict_provisioning_profile_search=args.strict_provisioning_profile_search,
+                provisioning_profile_filter=args.provisioning_profile_filter,
+                no_check_certificates=args.no_check_certificates,
+            )
+
+            if args.only_select_provisioning_profile:
+                print(signing_context.selected_profile_info.profile.file_path)
+                return
+
+        bundle_path = CodesignedPath(
+            path=args.bundle_path,
+            entitlements=args.entitlements,
+            flags=[],
+            extra_file_paths=None,
+        )
+        codesign_on_copy_paths = (
+            [
+                CodesignedPath(
+                    path=bundle_path.path / path,
+                    entitlements=None,
+                    flags=[],
+                    extra_file_paths=None,
+                )
+                for path in args.codesign_on_copy
+            ]
+            if args.codesign_on_copy
+            else []
+        )
+
+        codesign_bundle(
+            bundle_path=bundle_path,
+            signing_context=signing_context,
+            platform=args.platform,
+            codesign_on_copy_paths=codesign_on_copy_paths,
+        )
+    except CodeSignProvisioningError as e:
+        print(decorate_error_message(str(e)), file=sys.stderr)
+        exit(1)
+
+
+if __name__ == "__main__":
+    _main()
diff --git a/buck2/prelude/apple/tools/code_signing/prepare_code_signing_entitlements.py b/buck2/prelude/apple/tools/code_signing/prepare_code_signing_entitlements.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/prepare_code_signing_entitlements.py
@@ -0,0 +1,104 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import copy
+import os
+import plistlib
+import tempfile
+from pathlib import Path
+from typing import Dict, List, Optional
+
+from apple.tools.info_plist_processor.process import process as process_info_plist
+
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+
+
+def postprocess_entitlements(
+    output_path: str,
+    entitlements_suffixed_key_map: Optional[Dict[str, str]] = None,
+    entitlements_removed_keys: Optional[List[str]] = None,
+    entitlements_removed_values_map: Optional[Dict[str, List[str]]] = None,
+) -> None:
+    if (
+        not entitlements_suffixed_key_map
+        and not entitlements_removed_keys
+        and not entitlements_removed_values_map
+    ):
+        return
+
+    with open(output_path, "rb") as f:
+        entitlements = plistlib.load(f)
+    original = copy.deepcopy(entitlements)
+
+    if entitlements_removed_keys:
+        for key in entitlements_removed_keys:
+            entitlements.pop(key, None)
+
+    if entitlements_removed_values_map:
+        for key, values_to_remove in entitlements_removed_values_map.items():
+            if key in entitlements:
+                current = entitlements[key]
+                if isinstance(current, list):
+                    entitlements[key] = [
+                        v for v in current if v not in values_to_remove
+                    ]
+                elif isinstance(current, dict):
+                    for v in values_to_remove:
+                        current.pop(v, None)
+
+    if entitlements_suffixed_key_map:
+        for key, suffix in entitlements_suffixed_key_map.items():
+            if key in entitlements:
+                value = entitlements[key]
+                if isinstance(value, str):
+                    entitlements[key] = value + suffix
+                elif isinstance(value, list):
+                    entitlements[key] = [v + suffix for v in value]
+
+    if entitlements != original:
+        with open(output_path, "wb") as f:
+            plistlib.dump(entitlements, f, fmt=plistlib.FMT_XML)
+
+
+# Buck v1 corresponding code is in `ProvisioningProfileCopyStep::execute` in `ProvisioningProfileCopyStep.java`
+def prepare_code_signing_entitlements(
+    entitlements_path: Optional[Path],
+    bundle_id: str,
+    profile: ProvisioningProfileMetadata,
+    tmp_dir: str,
+    entitlements_suffixed_key_map: Optional[Dict[str, str]] = None,
+    entitlements_removed_keys: Optional[List[str]] = None,
+    entitlements_removed_values_map: Optional[Dict[str, List[str]]] = None,
+) -> Path:
+    fd, output_path = tempfile.mkstemp(dir=tmp_dir)
+    with os.fdopen(fd, mode="wb") as output:
+        if entitlements_path:
+            with open(entitlements_path, "rb") as entitlements_file:
+                process_info_plist(
+                    input_file=entitlements_file,
+                    output_file=output,
+                    additional_keys=profile.get_mergeable_entitlements(),
+                    output_format=plistlib.FMT_XML,
+                )
+        else:
+            app_id = profile.get_app_id().team_id + "." + bundle_id
+            entitlements = profile.get_mergeable_entitlements()
+            entitlements["application-identifier"] = app_id
+            entitlements["keychain-access-groups"] = [app_id]
+            plistlib.dump(entitlements, output, fmt=plistlib.FMT_XML)
+
+    postprocess_entitlements(
+        output_path,
+        entitlements_suffixed_key_map=entitlements_suffixed_key_map,
+        entitlements_removed_keys=entitlements_removed_keys,
+        entitlements_removed_values_map=entitlements_removed_values_map,
+    )
+
+    return Path(output_path)
diff --git a/buck2/prelude/apple/tools/code_signing/prepare_code_signing_entitlements_test.py b/buck2/prelude/apple/tools/code_signing/prepare_code_signing_entitlements_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/prepare_code_signing_entitlements_test.py
@@ -0,0 +1,437 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import os
+import plistlib
+import tempfile
+import unittest
+from datetime import datetime
+from pathlib import Path
+
+from .prepare_code_signing_entitlements import prepare_code_signing_entitlements
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+
+
+class Test(unittest.TestCase):
+    def test_minimal_entitlements_generated_based_on_provisioning_profile(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                {
+                    "application-identifier": "ABCDEFGHIJ.*",
+                    "com.apple.developer.aps-environment": "development",
+                },
+            )
+            result = prepare_code_signing_entitlements(
+                None, "com.company.application", profile, tmp_dir
+            )
+            with open(result, mode="rb") as result_file:
+                self.assertEqual(
+                    plistlib.load(result_file),
+                    {
+                        "application-identifier": "ABCDEFGHIJ.com.company.application",
+                        "com.apple.developer.aps-environment": "development",
+                        "keychain-access-groups": [
+                            "ABCDEFGHIJ.com.company.application"
+                        ],
+                    },
+                )
+
+    def test_suffix_applied_to_auto_generated_entitlements(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                {
+                    "application-identifier": "ABCDEFGHIJ.*",
+                    "com.apple.developer.aps-environment": "development",
+                },
+            )
+            result = prepare_code_signing_entitlements(
+                None,
+                "com.company.application",
+                profile,
+                tmp_dir,
+                entitlements_suffixed_key_map={"keychain-access-groups": ".suffix"},
+            )
+            with open(result, mode="rb") as result_file:
+                self.assertEqual(
+                    plistlib.load(result_file),
+                    {
+                        "application-identifier": "ABCDEFGHIJ.com.company.application",
+                        "com.apple.developer.aps-environment": "development",
+                        "keychain-access-groups": [
+                            "ABCDEFGHIJ.com.company.application.suffix"
+                        ],
+                    },
+                )
+
+    def test_suffix_applied_to_user_provided_entitlements(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            entitlements = {
+                "foo": "bar",
+                "keychain-access-groups": ["group1", "group2"],
+            }
+            entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")
+            with open(entitlements_path, mode="wb") as entitlements_file:
+                plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                {
+                    "application-identifier": "ABCDEFGHIJ.com.company.application",
+                    "com.apple.developer.aps-environment": "development",
+                    "should.be.ignored": "dummy",
+                },
+            )
+            result = prepare_code_signing_entitlements(
+                entitlements_path,
+                "com.company.application",
+                profile,
+                tmp_dir,
+                entitlements_suffixed_key_map={"keychain-access-groups": ".mysuffix"},
+            )
+            with open(result, "rb") as result_file:
+                self.assertEqual(
+                    plistlib.load(result_file),
+                    {
+                        "foo": "bar",
+                        "application-identifier": "ABCDEFGHIJ.com.company.application",
+                        "com.apple.developer.aps-environment": "development",
+                        "keychain-access-groups": [
+                            "group1.mysuffix",
+                            "group2.mysuffix",
+                        ],
+                    },
+                )
+
+    def test_no_modification_when_suffix_is_none(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                {
+                    "application-identifier": "ABCDEFGHIJ.*",
+                    "com.apple.developer.aps-environment": "development",
+                },
+            )
+            result = prepare_code_signing_entitlements(
+                None,
+                "com.company.application",
+                profile,
+                tmp_dir,
+                entitlements_suffixed_key_map={},
+            )
+            with open(result, mode="rb") as result_file:
+                self.assertEqual(
+                    plistlib.load(result_file),
+                    {
+                        "application-identifier": "ABCDEFGHIJ.com.company.application",
+                        "com.apple.developer.aps-environment": "development",
+                        "keychain-access-groups": [
+                            "ABCDEFGHIJ.com.company.application"
+                        ],
+                    },
+                )
+
+    def test_no_modification_when_keychain_access_groups_absent(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            entitlements = {"foo": "bar"}
+            entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")
+            with open(entitlements_path, mode="wb") as entitlements_file:
+                plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                {
+                    "application-identifier": "ABCDEFGHIJ.com.company.application",
+                },
+            )
+            result = prepare_code_signing_entitlements(
+                entitlements_path,
+                "com.company.application",
+                profile,
+                tmp_dir,
+                entitlements_suffixed_key_map={"keychain-access-groups": ".suffix"},
+            )
+            with open(result, "rb") as result_file:
+                self.assertEqual(
+                    plistlib.load(result_file),
+                    {
+                        "foo": "bar",
+                        "application-identifier": "ABCDEFGHIJ.com.company.application",
+                    },
+                )
+
+    def test_suffix_applied_to_string_entitlement_value(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            entitlements = {
+                "com.apple.developer.ubiquity-kvstore-identifier": "ABCDEFGHIJ.com.company.application",
+            }
+            entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")
+            with open(entitlements_path, mode="wb") as entitlements_file:
+                plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                {
+                    "application-identifier": "ABCDEFGHIJ.com.company.application",
+                },
+            )
+            result = prepare_code_signing_entitlements(
+                entitlements_path,
+                "com.company.application",
+                profile,
+                tmp_dir,
+                entitlements_suffixed_key_map={
+                    "com.apple.developer.ubiquity-kvstore-identifier": ".mysuffix"
+                },
+            )
+            with open(result, "rb") as result_file:
+                self.assertEqual(
+                    plistlib.load(result_file),
+                    {
+                        "application-identifier": "ABCDEFGHIJ.com.company.application",
+                        "com.apple.developer.ubiquity-kvstore-identifier": "ABCDEFGHIJ.com.company.application.mysuffix",
+                    },
+                )
+
+    def test_removed_keys_removes_existing_keys(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            entitlements = {
+                "foo": "bar",
+                "keychain-access-groups": ["group1", "group2"],
+                "com.apple.developer.icloud-services": ["CloudDocuments"],
+            }
+            entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")
+            with open(entitlements_path, mode="wb") as entitlements_file:
+                plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                {
+                    "application-identifier": "ABCDEFGHIJ.com.company.application",
+                },
+            )
+            result = prepare_code_signing_entitlements(
+                entitlements_path,
+                "com.company.application",
+                profile,
+                tmp_dir,
+                entitlements_removed_keys=["com.apple.developer.icloud-services"],
+            )
+            with open(result, "rb") as result_file:
+                self.assertEqual(
+                    plistlib.load(result_file),
+                    {
+                        "foo": "bar",
+                        "application-identifier": "ABCDEFGHIJ.com.company.application",
+                        "keychain-access-groups": ["group1", "group2"],
+                    },
+                )
+
+    def test_removed_keys_no_modification_when_key_absent(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            entitlements = {
+                "foo": "bar",
+            }
+            entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")
+            with open(entitlements_path, mode="wb") as entitlements_file:
+                plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                {
+                    "application-identifier": "ABCDEFGHIJ.com.company.application",
+                },
+            )
+            result = prepare_code_signing_entitlements(
+                entitlements_path,
+                "com.company.application",
+                profile,
+                tmp_dir,
+                entitlements_removed_keys=["nonexistent-key"],
+            )
+            with open(result, "rb") as result_file:
+                self.assertEqual(
+                    plistlib.load(result_file),
+                    {
+                        "foo": "bar",
+                        "application-identifier": "ABCDEFGHIJ.com.company.application",
+                    },
+                )
+
+    def test_entitlements_enriched_by_profile(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            entitlements = {"foo": "bar"}
+            entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")
+            with open(entitlements_path, mode="wb") as entitlements_file:
+                plistlib.dump(entitlements, entitlements_file, fmt=plistlib.FMT_XML)
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                {
+                    "application-identifier": "ABCDEFGHIJ.com.company.application",
+                    "com.apple.developer.aps-environment": "development",
+                    "should.be.ignored": "dummy",
+                },
+            )
+            result = prepare_code_signing_entitlements(
+                entitlements_path, "com.company.application", profile, tmp_dir
+            )
+            with open(result, "rb") as result_file:
+                self.assertEqual(
+                    plistlib.load(result_file),
+                    {
+                        "foo": "bar",
+                        "application-identifier": "ABCDEFGHIJ.com.company.application",
+                        "com.apple.developer.aps-environment": "development",
+                    },
+                )
+
+    def _assert_prepared_entitlements(
+        self, input_entitlements, expected, profile_entitlements=None, **kwargs
+    ):
+        if profile_entitlements is None:
+            profile_entitlements = {
+                "application-identifier": "ABCDEFGHIJ.com.company.application",
+            }
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            if input_entitlements is not None:
+                entitlements_path = os.path.join(tmp_dir, "Entitlements.plist")
+                with open(entitlements_path, mode="wb") as f:
+                    plistlib.dump(input_entitlements, f, fmt=plistlib.FMT_XML)
+            else:
+                entitlements_path = None
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                profile_entitlements,
+            )
+            result = prepare_code_signing_entitlements(
+                entitlements_path,
+                "com.company.application",
+                profile,
+                tmp_dir,
+                **kwargs,
+            )
+            with open(result, "rb") as f:
+                self.assertEqual(plistlib.load(f), expected)
+
+    def test_removed_values_map_removes_from_list(self):
+        self._assert_prepared_entitlements(
+            input_entitlements={
+                "foo": "bar",
+                "keychain-access-groups": ["group1", "group2", "group3"],
+            },
+            expected={
+                "foo": "bar",
+                "application-identifier": "ABCDEFGHIJ.com.company.application",
+                "keychain-access-groups": ["group2"],
+            },
+            entitlements_removed_values_map={
+                "keychain-access-groups": ["group1", "group3"]
+            },
+        )
+
+    def test_removed_values_map_removes_from_dict(self):
+        self._assert_prepared_entitlements(
+            input_entitlements={
+                "foo": "bar",
+                "com.apple.developer.icloud-container-environment": {
+                    "Production": True,
+                    "Development": True,
+                    "Staging": True,
+                },
+            },
+            expected={
+                "foo": "bar",
+                "application-identifier": "ABCDEFGHIJ.com.company.application",
+                "com.apple.developer.icloud-container-environment": {
+                    "Production": True,
+                },
+            },
+            entitlements_removed_values_map={
+                "com.apple.developer.icloud-container-environment": [
+                    "Development",
+                    "Staging",
+                ]
+            },
+        )
+
+    def test_removed_values_map_no_modification_when_key_absent(self):
+        self._assert_prepared_entitlements(
+            input_entitlements={"foo": "bar"},
+            expected={
+                "foo": "bar",
+                "application-identifier": "ABCDEFGHIJ.com.company.application",
+            },
+            entitlements_removed_values_map={"nonexistent-key": ["value1"]},
+        )
+
+    def test_removed_values_map_no_modification_when_value_absent(self):
+        self._assert_prepared_entitlements(
+            input_entitlements={
+                "foo": "bar",
+                "keychain-access-groups": ["group1", "group2"],
+            },
+            expected={
+                "foo": "bar",
+                "application-identifier": "ABCDEFGHIJ.com.company.application",
+                "keychain-access-groups": ["group1", "group2"],
+            },
+            entitlements_removed_values_map={
+                "keychain-access-groups": ["nonexistent-value"]
+            },
+        )
+
+    def test_removed_values_map_empty_map(self):
+        self._assert_prepared_entitlements(
+            input_entitlements=None,
+            expected={
+                "application-identifier": "ABCDEFGHIJ.com.company.application",
+                "com.apple.developer.aps-environment": "development",
+                "keychain-access-groups": ["ABCDEFGHIJ.com.company.application"],
+            },
+            profile_entitlements={
+                "application-identifier": "ABCDEFGHIJ.*",
+                "com.apple.developer.aps-environment": "development",
+            },
+            entitlements_removed_values_map={},
+        )
diff --git a/buck2/prelude/apple/tools/code_signing/prepare_info_plist.py b/buck2/prelude/apple/tools/code_signing/prepare_info_plist.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/prepare_info_plist.py
@@ -0,0 +1,51 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import os
+import tempfile
+from pathlib import Path
+from typing import Any, Dict
+
+from apple.tools.info_plist_processor.process import process as process_info_plist
+
+from .info_plist_metadata import InfoPlistMetadata
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+
+
+# Buck v1 corresponding code is in `ProvisioningProfileCopyStep::execute` in `ProvisioningProfileCopyStep.java`
+def prepare_info_plist(
+    info_plist: Path,
+    info_plist_metadata: InfoPlistMetadata,
+    profile: ProvisioningProfileMetadata,
+    tmp_dir: str,
+) -> Path:
+    fd, output_path = tempfile.mkstemp(dir=tmp_dir)
+    with open(info_plist, "rb") as input, os.fdopen(fd, mode="wb") as output:
+        additional_keys = _additional_keys(info_plist_metadata, profile)
+        process_info_plist(
+            input_file=input, output_file=output, additional_keys=additional_keys
+        )
+    return Path(output_path)
+
+
+# Equivalent Buck v1 code is in `ProvisioningProfileCopyStep.java` in `ProvisioningProfileCopyStep::getInfoPlistAdditionalKeys` method.
+def _additional_keys(
+    info_plist_metadata: InfoPlistMetadata, profile: ProvisioningProfileMetadata
+) -> Dict[str, Any]:
+    result = {}
+    # Restrict additional keys based on bundle type. Skip additional keys for watchOS bundles (property keys whitelist).
+    if (
+        info_plist_metadata.bundle_type == "APPL"
+        and not info_plist_metadata.is_watchos_app
+    ):
+        # Construct AppID using the Provisioning Profile info (app prefix)
+        app_id = profile.get_app_id().team_id + "." + info_plist_metadata.bundle_id
+        result["ApplicationIdentifier"] = app_id
+    return result
diff --git a/buck2/prelude/apple/tools/code_signing/prepare_info_plist_test.py b/buck2/prelude/apple/tools/code_signing/prepare_info_plist_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/prepare_info_plist_test.py
@@ -0,0 +1,75 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import os
+import plistlib
+import tempfile
+import unittest
+from datetime import datetime
+from pathlib import Path
+
+from .info_plist_metadata import InfoPlistMetadata
+from .prepare_info_plist import prepare_info_plist
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+
+
+class Test(unittest.TestCase):
+    def test_app_id_set_for_non_watchos_apps(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            profile = ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {},
+                {
+                    "application-identifier": "ABCDEFGHIJ.*",
+                },
+            )
+            info_plist = {
+                "CFBundleIdentifier": "com.facebook.test",
+                "CFBundlePackageType": "APPL",
+            }
+            info_plist_path, info_plist_metadata = _write_info_plist(
+                info_plist, tmp_dir, "Info.plist"
+            )
+            result = prepare_info_plist(
+                info_plist_path, info_plist_metadata, profile, tmp_dir
+            )
+            with open(result, "rb") as result_file:
+                self.assertEqual(
+                    plistlib.load(result_file),
+                    {
+                        "CFBundleIdentifier": "com.facebook.test",
+                        "CFBundlePackageType": "APPL",
+                        "ApplicationIdentifier": "ABCDEFGHIJ.com.facebook.test",
+                    },
+                )
+            # Same but for watchOS Info.plist
+            info_plist = {
+                "CFBundleIdentifier": "com.facebook.test",
+                "CFBundlePackageType": "APPL",
+                "WKApplication": True,
+            }
+            info_plist_path, info_plist_metadata = _write_info_plist(
+                info_plist, tmp_dir, "Info.plist"
+            )
+            result = prepare_info_plist(
+                info_plist_path, info_plist_metadata, profile, tmp_dir
+            )
+            with open(result, "rb") as result_file:
+                self.assertNotIn("ApplicationIdentifier", plistlib.load(result_file))
+
+
+def _write_info_plist(plist, tmp_dir, name):
+    path = os.path.join(tmp_dir, "Info.plist")
+    with open(path, mode="wb") as file:
+        plistlib.dump(plist, file, fmt=plistlib.FMT_XML)
+    with open(path, mode="rb") as file:
+        metadata = InfoPlistMetadata.from_file(file)
+        return (path, metadata)
diff --git a/buck2/prelude/apple/tools/code_signing/provisioning_profile_diagnostics.py b/buck2/prelude/apple/tools/code_signing/provisioning_profile_diagnostics.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/provisioning_profile_diagnostics.py
@@ -0,0 +1,259 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from abc import ABCMeta, abstractmethod
+from pathlib import Path
+from typing import List, Optional, Type, TypeVar
+
+# Remediation text for diagnostic messages. Meta builds import from
+# meta_only/codesign_diagnostics_text.py (arc ios-certs doctor + internal links);
+# OSS builds use the generic Apple Developer Portal defaults from
+# codesign_diagnostics_text.py in this directory.
+# @oss-disable[end= ]: from ..meta_only.codesign_diagnostics_text import (
+    # @oss-disable[end= ]: CodesignDiagnosticsText,
+# @oss-disable[end= ]: )
+from .apple_platform import ApplePlatform
+from .identity import CodeSigningIdentity
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+from .codesign_diagnostics_text import CodesignDiagnosticsText # @oss-enable
+
+
+class IProvisioningProfileDiagnostics(metaclass=ABCMeta):
+    profile: ProvisioningProfileMetadata
+
+    def __init__(self, profile: ProvisioningProfileMetadata) -> None:
+        self.profile = profile
+
+    @abstractmethod
+    def log_message(self) -> str:
+        raise NotImplementedError
+
+
+class TeamIdMismatch(IProvisioningProfileDiagnostics):
+    team_id: str
+    team_id_constraint: str
+
+    def __init__(
+        self,
+        profile: ProvisioningProfileMetadata,
+        team_id: str,
+        team_id_constraint: str,
+    ) -> None:
+        super().__init__(profile)
+        self.team_id = team_id
+        self.team_id_constraint = team_id_constraint
+
+    def log_message(self) -> str:
+        return f"Profile team ID `{self.team_id}` is not matching constraint `{self.team_id_constraint}`"
+
+
+class BundleIdMismatch(IProvisioningProfileDiagnostics):
+    bundle_id: str
+    bundle_id_constraint: str
+
+    def __init__(
+        self,
+        profile: ProvisioningProfileMetadata,
+        bundle_id: str,
+        bundle_id_constraint: str,
+    ) -> None:
+        super().__init__(profile)
+        self.bundle_id = bundle_id
+        self.bundle_id_constraint = bundle_id_constraint
+
+    def log_message(self) -> str:
+        return f"Bundle ID `{self.bundle_id}` is not matching constraint `{self.bundle_id_constraint}`"
+
+
+class ProfileExpired(IProvisioningProfileDiagnostics):
+    bundle_id_match_length: int
+
+    def __init__(
+        self,
+        profile: ProvisioningProfileMetadata,
+        bundle_id_match_length: int,
+    ) -> None:
+        super().__init__(profile)
+        self.bundle_id_match_length = bundle_id_match_length
+
+    def log_message(self) -> str:
+        return "Provisioning profile expired."
+
+
+class UnsupportedPlatform(IProvisioningProfileDiagnostics):
+    bundle_id_match_length: int
+    platform_constraint: str
+
+    def __init__(
+        self,
+        profile: ProvisioningProfileMetadata,
+        bundle_id_match_length: int,
+        platform_constraint: ApplePlatform,
+    ) -> None:
+        super().__init__(profile)
+        self.bundle_id_match_length = bundle_id_match_length
+        self.platform_constraint = platform_constraint
+
+    def log_message(self) -> str:
+        supported_profile_platforms = ", ".join(self.profile.platforms)
+        return f"Requested platform `{self.platform_constraint}` is not in provisioning profile's supported platforms `{supported_profile_platforms}`."
+
+
+class EntitlementsMismatch(IProvisioningProfileDiagnostics):
+    bundle_id_match_length: int
+    mismatched_key: str
+    mismatched_value: str
+
+    def __init__(
+        self,
+        profile: ProvisioningProfileMetadata,
+        bundle_id_match_length: int,
+        mismatched_key: str,
+        mismatched_value: str,
+    ) -> None:
+        super().__init__(profile)
+        self.bundle_id_match_length = bundle_id_match_length
+        self.mismatched_key = mismatched_key
+        self.mismatched_value = mismatched_value
+
+    def log_message(self) -> str:
+        return f"Expected entitlement item key `{self.mismatched_key}` with value `{self.mismatched_value}` not found in provisioning profile."
+
+
+class DeveloperCertificateMismatch(IProvisioningProfileDiagnostics):
+    bundle_id_match_length: int
+
+    def __init__(
+        self,
+        profile: ProvisioningProfileMetadata,
+        bundle_id_match_length: int,
+    ) -> None:
+        super().__init__(profile)
+        self.bundle_id_match_length = bundle_id_match_length
+
+    def log_message(self) -> str:
+        certificate_fingerprints = ", ".join(
+            self.profile.developer_certificate_fingerprints
+        )
+        return f"Expected identity fingerprint not found in profile's certificate fingerprints `{certificate_fingerprints}`."
+
+
+_T = TypeVar("T")
+
+
+def interpret_provisioning_profile_diagnostics(
+    diagnostics: List[IProvisioningProfileDiagnostics],
+    bundle_id: str,
+    provisioning_profiles_dirs: List[Path],
+    identities: List[CodeSigningIdentity],
+    log_file_path: Optional[Path] = None,
+) -> str:
+    if not diagnostics:
+        raise RuntimeError(
+            "Expected diagnostics information for at least one mismatching provisioning profile."
+        )
+    if not provisioning_profiles_dirs:
+        raise RuntimeError("Expected at least one provisioning profiles directory.")
+
+    dirs_msg = ", ".join(f"`{d}`" for d in provisioning_profiles_dirs)
+    header = f"Failed to find provisioning profile in directories {dirs_msg} that is suitable for code signing. Here is the best guess for how to fix it:\n\n⚠️  "
+    footer = CodesignDiagnosticsText.DEVICE_LINK
+    if log_file_path:
+        non_bundle_id_mismatches = [
+            f"`{mismatch.profile.file_path.name}`: {mismatch.log_message()}"
+            for mismatch in diagnostics
+            if not isinstance(mismatch, BundleIdMismatch)
+        ]
+        if non_bundle_id_mismatches:
+            provisioning_profile_errors = "\n\n".join(non_bundle_id_mismatches)
+            footer += f" Mismatched profiles:\n\n{provisioning_profile_errors}\n"
+        else:
+            footer += f" All mismatches were due to Bundle ID `{bundle_id}` not matching any provisioning profile.\n"
+        footer += (
+            f" Full list of mismatched profiles can be found at `{log_file_path}`.\n"
+        )
+    else:
+        provisioning_profile_errors = "\n\n".join(
+            [
+                f"`{mismatch.profile.file_path.name}`: {mismatch.log_message()}"
+                for mismatch in diagnostics
+            ]
+        )
+        footer += f" Full list of mismatched profiles:{provisioning_profile_errors}\n"
+
+    def find_mismatch(class_type: Type[_T]) -> Optional[_T]:
+        return next(
+            iter(
+                sorted(
+                    filter(lambda d: isinstance(d, class_type), diagnostics),
+                    key=lambda d: d.bundle_id_match_length,
+                    reverse=True,
+                )
+            ),
+            None,
+        )
+
+    if mismatch := find_mismatch(DeveloperCertificateMismatch):
+        identities_description = (
+            "WARNING: NO SIGNING IDENTITIES FOUND!"
+            if len(identities) == 0
+            else f"List of signing identities: `{identities}`."
+        )
+        return "\n".join(
+            [
+                header,
+                f"The provisioning profile `{mismatch.profile.file_path.name}` satisfies all constraints, but no matching certificates were found in your keychain. ",
+                identities_description,
+                CodesignDiagnosticsText.CERT_REMEDIATION,
+                footer,
+            ]
+        )
+
+    if mismatch := find_mismatch(EntitlementsMismatch):
+        return "".join(
+            [
+                header,
+                f"The provisioning profile `{mismatch.profile.file_path.name}` is the best match, but it doesn't contain all the needed entitlements. ",
+                f"Expected entitlement item with key `{mismatch.mismatched_key}` and value `{mismatch.mismatched_value}` is missing. ",
+                f"Usually that means the application entitlements were changed recently, provisioning profile was updated and you need to download & install the latest version of provisioning profile for Bundle ID `{bundle_id}`.",
+                CodesignDiagnosticsText.ENTITLEMENTS_REMEDIATION,
+                footer,
+            ]
+        )
+
+    if mismatch := find_mismatch(UnsupportedPlatform):
+        supported_platforms = ", ".join([f"`{p}`" for p in mismatch.profile.platforms])
+        return "".join(
+            [
+                header,
+                f"The provisioning profile `{mismatch.profile.file_path.name}` is the best match, but it only supports the following platforms: {supported_platforms}. Unfortunately, it doesn't include the requested platform, `{mismatch.platform_constraint}`. ",
+                f"This could indicate two possibilities: either the provisioning profile was recently updated to include the needed platform, or there is a separate profile supporting the required platform that you are missing. In the latter case, {CodesignDiagnosticsText.PLATFORM_LINK}",
+                footer,
+            ]
+        )
+
+    if mismatch := find_mismatch(ProfileExpired):
+        return "".join(
+            [
+                header,
+                f"The provisioning profile `{mismatch.profile.file_path.name}` is the best match; however, it has expired",
+                CodesignDiagnosticsText.PROFILES_DOWNLOAD,
+                footer,
+            ]
+        )
+
+    return "".join(
+        [
+            header,
+            f"No provisioning profile matching the Bundle ID `{bundle_id}` was found. ",
+            CodesignDiagnosticsText.PROFILES_DOWNLOAD,
+            footer,
+        ]
+    )
diff --git a/buck2/prelude/apple/tools/code_signing/provisioning_profile_diagnostics_test.py b/buck2/prelude/apple/tools/code_signing/provisioning_profile_diagnostics_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/provisioning_profile_diagnostics_test.py
@@ -0,0 +1,110 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import unittest
+from datetime import datetime
+from pathlib import Path
+from unittest.mock import patch
+
+from .apple_platform import ApplePlatform
+from .codesign_bundle import _try_select_from_profiles_dir
+from .identity import CodeSigningIdentity
+from .info_plist_metadata import InfoPlistMetadata
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+
+
+def _make_profile(
+    file_path: str = "/profiles/test.mobileprovision",
+    bundle_id: str = "AAAAAAAAAA.com.company.app",
+    fingerprint: str = "fingerprint",
+    expired: bool = False,
+) -> ProvisioningProfileMetadata:
+    return ProvisioningProfileMetadata(
+        Path(file_path),
+        "00000000-0000-0000-0000-000000000000",
+        datetime.min if expired else datetime.max,
+        {"iOS"},
+        {fingerprint},
+        {"application-identifier": bundle_id},
+    )
+
+
+def _make_identity(
+    fingerprint: str = "fingerprint",
+) -> CodeSigningIdentity:
+    return CodeSigningIdentity(fingerprint, "name")
+
+
+class TestTrySelectFromProfilesDir(unittest.TestCase):
+    """Tests for _try_select_from_profiles_dir helper."""
+
+    def test_empty_dir_returns_none_tuple(self):
+        with patch(
+            "apple.tools.code_signing.codesign_bundle._read_profiles_from_dir",
+            return_value=[],
+        ):
+            selected, profiles, mismatches = _try_select_from_profiles_dir(
+                profiles_dir=Path("/empty"),
+                info_plist_metadata=InfoPlistMetadata("com.company.app", None, False),
+                identities=[_make_identity()],
+                entitlements={},
+                platform=ApplePlatform.ios_device,
+                should_use_fast_provisioning_profile_parsing=False,
+                strict_provisioning_profile_search=False,
+                provisioning_profile_filter=None,
+                no_check_certificates=False,
+            )
+        self.assertIsNone(selected)
+        self.assertIsNone(profiles)
+        self.assertIsNone(mismatches)
+
+    def test_matching_profile_returns_selection(self):
+        identity = _make_identity()
+        profile = _make_profile()
+        with patch(
+            "apple.tools.code_signing.codesign_bundle._read_profiles_from_dir",
+            return_value=[profile],
+        ):
+            selected, profiles, mismatches = _try_select_from_profiles_dir(
+                profiles_dir=Path("/profiles"),
+                info_plist_metadata=InfoPlistMetadata("com.company.app", None, False),
+                identities=[identity],
+                entitlements={},
+                platform=ApplePlatform.ios_device,
+                should_use_fast_provisioning_profile_parsing=False,
+                strict_provisioning_profile_search=False,
+                provisioning_profile_filter=None,
+                no_check_certificates=False,
+            )
+        self.assertIsNotNone(selected)
+        self.assertEqual(selected.profile, profile)
+        self.assertEqual(len(profiles), 1)
+
+    def test_no_match_returns_diagnostics(self):
+        identity = _make_identity(fingerprint="other_fingerprint")
+        profile = _make_profile()
+        with patch(
+            "apple.tools.code_signing.codesign_bundle._read_profiles_from_dir",
+            return_value=[profile],
+        ):
+            selected, profiles, mismatches = _try_select_from_profiles_dir(
+                profiles_dir=Path("/profiles"),
+                info_plist_metadata=InfoPlistMetadata("com.company.app", None, False),
+                identities=[identity],
+                entitlements={},
+                platform=ApplePlatform.ios_device,
+                should_use_fast_provisioning_profile_parsing=False,
+                strict_provisioning_profile_search=False,
+                provisioning_profile_filter=None,
+                no_check_certificates=False,
+            )
+        self.assertIsNone(selected)
+        self.assertIsNotNone(profiles)
+        self.assertEqual(len(profiles), 1)
+        self.assertIsNotNone(mismatches)
+        self.assertGreater(len(mismatches), 0)
diff --git a/buck2/prelude/apple/tools/code_signing/provisioning_profile_metadata.py b/buck2/prelude/apple/tools/code_signing/provisioning_profile_metadata.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/provisioning_profile_metadata.py
@@ -0,0 +1,267 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+from dataclasses import dataclass
+from datetime import datetime
+from pathlib import Path
+from typing import Any, cast, Optional
+
+from apple.tools.plistlib_utils import detect_format_and_loads
+
+from .app_id import AppId
+from .serialization import (
+    expect_dict,
+    expect_keys,
+    expect_optional_bool,
+    expect_optional_str_list,
+    expect_str,
+    expect_str_list,
+)
+
+_ENTITLEMENTS_BYTES_MARKER = "__apple_code_signing_bytes_b64__"
+_ENTITLEMENTS_DATETIME_MARKER = "__apple_code_signing_datetime_iso__"
+_ENTITLEMENTS_ESCAPED_DICT_MARKER = "__apple_code_signing_escaped_dict__"
+_ENTITLEMENTS_RESERVED_MARKERS = (
+    _ENTITLEMENTS_BYTES_MARKER,
+    _ENTITLEMENTS_DATETIME_MARKER,
+    _ENTITLEMENTS_ESCAPED_DICT_MARKER,
+)
+
+
+def _serialize_datetime(dt: Optional[datetime]) -> Optional[str]:
+    if dt is None:
+        return None
+    return dt.isoformat()
+
+
+def _deserialize_datetime(value: object, path: str) -> Optional[datetime]:
+    if value is None:
+        return None
+    return datetime.fromisoformat(expect_str(value, path))
+
+
+def _make_entitlements_json_safe(obj: Any) -> Any:
+    """Encode plist-only scalar types as tagged JSON objects."""
+    if isinstance(obj, bytes):
+        return {_ENTITLEMENTS_BYTES_MARKER: base64.standard_b64encode(obj).decode()}
+    if isinstance(obj, datetime):
+        return {_ENTITLEMENTS_DATETIME_MARKER: obj.isoformat()}
+    if isinstance(obj, dict):
+        encoded = {k: _make_entitlements_json_safe(v) for k, v in obj.items()}
+        # A marker-shaped dictionary is valid plist data and must not be
+        # mistaken for one of the tagged scalar representations when decoded.
+        if len(obj) == 1 and next(iter(obj)) in _ENTITLEMENTS_RESERVED_MARKERS:
+            return {_ENTITLEMENTS_ESCAPED_DICT_MARKER: encoded}
+        return encoded
+    if isinstance(obj, (list, tuple)):
+        return [_make_entitlements_json_safe(x) for x in obj]
+    return obj
+
+
+def _restore_entitlements_from_json_safe(obj: object) -> Any:
+    if isinstance(obj, dict):
+        data = expect_dict(obj, "entitlements")
+        if set(data) == {_ENTITLEMENTS_BYTES_MARKER}:
+            raw = obj[_ENTITLEMENTS_BYTES_MARKER]
+            encoded = expect_str(raw, f"entitlements.{_ENTITLEMENTS_BYTES_MARKER}")
+            try:
+                return base64.b64decode(encoded, validate=True)
+            except binascii.Error as error:
+                raise ValueError("Invalid base64 entitlement value") from error
+        if set(data) == {_ENTITLEMENTS_DATETIME_MARKER}:
+            raw = obj[_ENTITLEMENTS_DATETIME_MARKER]
+            return datetime.fromisoformat(
+                expect_str(raw, f"entitlements.{_ENTITLEMENTS_DATETIME_MARKER}")
+            )
+        if set(data) == {_ENTITLEMENTS_ESCAPED_DICT_MARKER}:
+            escaped = expect_dict(
+                data[_ENTITLEMENTS_ESCAPED_DICT_MARKER],
+                f"entitlements.{_ENTITLEMENTS_ESCAPED_DICT_MARKER}",
+            )
+            return {
+                key: _restore_entitlements_from_json_safe(value)
+                for key, value in escaped.items()
+            }
+        return {
+            key: _restore_entitlements_from_json_safe(value)
+            for key, value in data.items()
+        }
+    if isinstance(obj, list):
+        return [_restore_entitlements_from_json_safe(value) for value in obj]
+    if obj is None or isinstance(obj, (bool, int, float, str)):
+        return obj
+    raise ValueError(f"Unsupported entitlement JSON value: {type(obj).__name__}")
+
+
+@dataclass
+class ProvisioningProfileMetadata:
+    # Path to the provisioning profile file
+    file_path: Path
+    uuid: str
+    # Naïve object with ignored timezone, see https://bugs.python.org/msg110249
+    expiration_date: datetime
+    platforms: frozenset[str]
+    # Let's agree they are uppercased
+    developer_certificate_fingerprints: frozenset[str]
+    entitlements: dict[str, Any]
+    # Naïve object with ignored timezone (same as expiration_date)
+    creation_date: Optional[datetime] = None
+    provisions_all_devices: Optional[bool] = None
+    provisioned_devices: Optional[list[str]] = None
+
+    _mergeable_entitlements_keys: frozenset[str] = frozenset(
+        [
+            "application-identifier",
+            "beta-reports-active",
+            "get-task-allow",
+            "com.apple.developer.aps-environment",
+            "com.apple.developer.team-identifier",
+        ]
+    )
+
+    # See `ProvisioningProfileMetadataFactory::getAppIDFromEntitlements` from `ProvisioningProfileMetadataFactory.java` in Buck v1
+    def get_app_id(self) -> AppId:
+        maybe_app_id = self.entitlements.get(
+            "application-identifier"
+        ) or self.entitlements.get("com.apple.application-identifier")
+        if not maybe_app_id:
+            raise RuntimeError(
+                f"Entitlements do not contain app ID: {self.entitlements}"
+            )
+        return AppId.from_string(maybe_app_id)
+
+    # See `ProvisioningProfileMetadata::getMergeableEntitlements` from `ProvisioningProfileMetadata.java` in Buck v1
+    def get_mergeable_entitlements(self) -> dict[str, Any]:
+        return {
+            k: v
+            for k, v in self.entitlements.items()
+            if k in ProvisioningProfileMetadata._mergeable_entitlements_keys
+        }
+
+    # See `ProvisioningProfileMetadataFactory::fromProvisioningProfilePath` from `ProvisioningProfileMetadataFactory.java` in Buck v1
+    @staticmethod
+    def from_provisioning_profile_file_content(
+        file_path: Path, content: bytes
+    ) -> ProvisioningProfileMetadata:
+        root = detect_format_and_loads(content)
+        developer_certificate_fingerprints = {
+            hashlib.sha1(c).hexdigest().upper() for c in root["DeveloperCertificates"]
+        }
+        assert len(developer_certificate_fingerprints) > 0, (
+            "Expected at least one suitable certificate."
+        )
+        return ProvisioningProfileMetadata(
+            file_path=file_path,
+            uuid=root["UUID"],
+            expiration_date=root["ExpirationDate"],
+            platforms=frozenset(root["Platform"]),
+            developer_certificate_fingerprints=frozenset(
+                developer_certificate_fingerprints
+            ),
+            entitlements=root["Entitlements"],
+            creation_date=root.get("CreationDate"),
+            provisions_all_devices=root.get("ProvisionsAllDevices"),
+            provisioned_devices=root.get("ProvisionedDevices"),
+        )
+
+    def __hash__(self) -> int:
+        return hash(
+            (
+                self.file_path,
+                self.uuid,
+                self.expiration_date,
+                self.platforms,
+                self.developer_certificate_fingerprints,
+            )
+        )
+
+    def to_dict(self) -> dict[str, object]:
+        return {
+            "file_path": str(self.file_path),
+            "uuid": self.uuid,
+            "expiration_date": _serialize_datetime(self.expiration_date),
+            "creation_date": _serialize_datetime(self.creation_date),
+            "platforms": sorted(self.platforms),
+            "developer_certificate_fingerprints": sorted(
+                self.developer_certificate_fingerprints
+            ),
+            "entitlements": _make_entitlements_json_safe(self.entitlements),
+            "provisions_all_devices": self.provisions_all_devices,
+            "provisioned_devices": self.provisioned_devices,
+        }
+
+    @staticmethod
+    def from_dict(value: object) -> ProvisioningProfileMetadata:
+        data = expect_dict(value, "ProvisioningProfileMetadata")
+        expect_keys(
+            data,
+            "ProvisioningProfileMetadata",
+            frozenset(
+                {
+                    "file_path",
+                    "uuid",
+                    "expiration_date",
+                    "creation_date",
+                    "platforms",
+                    "developer_certificate_fingerprints",
+                    "entitlements",
+                    "provisions_all_devices",
+                    "provisioned_devices",
+                }
+            ),
+        )
+        expiration = _deserialize_datetime(
+            data["expiration_date"], "ProvisioningProfileMetadata.expiration_date"
+        )
+        if expiration is None:
+            raise ValueError(
+                "ProvisioningProfileMetadata.expiration_date must be a string"
+            )
+        creation = _deserialize_datetime(
+            data["creation_date"], "ProvisioningProfileMetadata.creation_date"
+        )
+        entitlements = _restore_entitlements_from_json_safe(data["entitlements"])
+        if not isinstance(entitlements, dict):
+            raise ValueError(
+                "ProvisioningProfileMetadata.entitlements must be an object"
+            )
+        return ProvisioningProfileMetadata(
+            file_path=Path(
+                expect_str(data["file_path"], "ProvisioningProfileMetadata.file_path")
+            ),
+            uuid=expect_str(data["uuid"], "ProvisioningProfileMetadata.uuid"),
+            expiration_date=expiration,
+            platforms=frozenset(
+                expect_str_list(
+                    data["platforms"], "ProvisioningProfileMetadata.platforms"
+                )
+            ),
+            developer_certificate_fingerprints=frozenset(
+                expect_str_list(
+                    data["developer_certificate_fingerprints"],
+                    "ProvisioningProfileMetadata.developer_certificate_fingerprints",
+                )
+            ),
+            entitlements=cast(dict[str, Any], entitlements),
+            creation_date=creation,
+            provisions_all_devices=expect_optional_bool(
+                data["provisions_all_devices"],
+                "ProvisioningProfileMetadata.provisions_all_devices",
+            ),
+            provisioned_devices=expect_optional_str_list(
+                data["provisioned_devices"],
+                "ProvisioningProfileMetadata.provisioned_devices",
+            ),
+        )
diff --git a/buck2/prelude/apple/tools/code_signing/provisioning_profile_metadata_test.py b/buck2/prelude/apple/tools/code_signing/provisioning_profile_metadata_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/provisioning_profile_metadata_test.py
@@ -0,0 +1,69 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import datetime
+import importlib.resources
+import unittest
+from pathlib import Path
+
+from .app_id import AppId
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+
+
+class TestParse(unittest.TestCase):
+    def test_canary(self):
+        path = Path("test_resources/sample.mobileprovision")
+        file_content = (importlib.resources.files(__package__) / path).read_bytes()
+        metadata = ProvisioningProfileMetadata.from_provisioning_profile_file_content(
+            path, file_content
+        )
+        self.assertEqual(metadata.uuid, "00000000-0000-0000-0000-000000000000")
+        self.assertEqual(
+            metadata.get_app_id(), AppId("ABCDE12345", "com.example.TestApp")
+        )
+        self.assertEqual(
+            metadata.expiration_date,
+            datetime.datetime.fromisoformat("9999-03-05T01:33:40"),
+        )
+        self.assertEqual(
+            metadata.developer_certificate_fingerprints,
+            {"BE16FC419BFB6B59A86BC08755BA0F332EC574FB"},
+        )
+        self.assertEqual(
+            metadata.platforms,
+            {"iOS"},
+        )
+
+    def test_qualified_entitlements_parsed(self):
+        path = Path("test_resources/sample.mobileprovision")
+        file_content = (importlib.resources.files(__package__) / path).read_bytes()
+        metadata = ProvisioningProfileMetadata.from_provisioning_profile_file_content(
+            path, file_content
+        )
+        self.assertEqual(
+            metadata.get_app_id(), AppId("ABCDE12345", "com.example.TestApp")
+        )
+
+    def test_filtered_entitlements_stripped_out(self):
+        path = Path("test_resources/sample.mobileprovision")
+        file_content = (importlib.resources.files(__package__) / path).read_bytes()
+        metadata = ProvisioningProfileMetadata.from_provisioning_profile_file_content(
+            path, file_content
+        )
+        self.assertIn(
+            "com.apple.developer.icloud-container-development-container-identifiers",
+            metadata.entitlements,
+        )
+        self.assertEqual(
+            metadata.get_mergeable_entitlements(),
+            {
+                "application-identifier": "ABCDE12345.com.example.TestApp",
+                "get-task-allow": False,
+                "com.apple.developer.team-identifier": "12345ABCDE",
+            },
+        )
diff --git a/buck2/prelude/apple/tools/code_signing/provisioning_profile_selection.py b/buck2/prelude/apple/tools/code_signing/provisioning_profile_selection.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/provisioning_profile_selection.py
@@ -0,0 +1,389 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+import datetime
+import logging
+import re
+from collections import defaultdict
+from dataclasses import dataclass
+from typing import Any, cast, Optional
+
+from .app_id import AppId
+from .apple_platform import ApplePlatform
+from .identity import CodeSigningIdentity
+from .info_plist_metadata import InfoPlistMetadata
+from .provisioning_profile_diagnostics import (
+    BundleIdMismatch,
+    DeveloperCertificateMismatch,
+    EntitlementsMismatch,
+    IProvisioningProfileDiagnostics,
+    ProfileExpired,
+    TeamIdMismatch,
+    UnsupportedPlatform,
+)
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+from .serialization import expect_dict, expect_keys
+
+_LOGGER: logging.Logger = logging.getLogger(__name__)
+
+
+class CodeSignProvisioningError(Exception):
+    pass
+
+
+def _parse_team_id_from_entitlements(
+    entitlements: Optional[dict[str, Any]],
+) -> Optional[str]:
+    if not entitlements:
+        return None
+    maybe_app_id = AppId.infer_from_entitlements(entitlements)
+    if not maybe_app_id:
+        return None
+    return maybe_app_id.team_id
+
+
+def _matches_or_array_is_subset_of(
+    entitlement_name: str,
+    expected_value: object,
+    actual_value: object,
+    platform: ApplePlatform,
+) -> bool:
+    if expected_value is None:
+        return actual_value is None
+    if actual_value == "*":
+        # Certain entitlements have a wildcard value, which means any value is allowed.
+        return True
+    if (
+        actual_value is None
+        and platform.is_desktop()
+        and entitlement_name.startswith("com.apple.security")
+    ):
+        # For macOS apps, including Catalyst, the provisioning profile would _not_ have entries for
+        # the sandbox entitlements, so any value matches.
+        return True
+    if isinstance(expected_value, list) and isinstance(actual_value, list):
+        return set(expected_value).issubset(set(actual_value))
+    return actual_value == expected_value
+
+
+def _bundle_match_length(expected_bundle_id: str, bundle_id_pattern: str) -> int:
+    if bundle_id_pattern.endswith("*"):
+        # Chop the ending * if wildcard.
+        bundle_id_without_wildcard = bundle_id_pattern[:-1]
+        if expected_bundle_id.startswith(bundle_id_without_wildcard):
+            return len(bundle_id_without_wildcard)
+    elif expected_bundle_id == bundle_id_pattern:
+        return len(bundle_id_pattern)
+    return -1
+
+
+# For those keys let the tooling decide if code signing should fail or succeed (every other key
+# mismatch results in provisioning profile being skipped).
+_IGNORE_MISMATCH_ENTITLEMENTS_KEYS = {
+    "keychain-access-groups",
+    "application-identifier",
+    "com.apple.developer.associated-domains",
+    "com.apple.developer.icloud-container-development-container-identifiers",
+    "com.apple.developer.icloud-container-environment",
+    "com.apple.developer.icloud-container-identifiers",
+    "com.apple.developer.icloud-services",
+    "com.apple.developer.ubiquity-container-identifiers",
+    "com.apple.developer.ubiquity-kvstore-identifier",
+}
+
+
+def _check_entitlements_match(
+    expected_entitlements: Optional[dict[str, Any]],
+    profile: ProvisioningProfileMetadata,
+    platform: ApplePlatform,
+    bundle_id_match_length: int,
+) -> tuple[bool, Optional[EntitlementsMismatch]]:
+    if expected_entitlements is None:
+        return (True, None)
+    for key, value in expected_entitlements.items():
+        profile_entitlement = profile.entitlements.get(key)
+        if (key not in _IGNORE_MISMATCH_ENTITLEMENTS_KEYS) and (
+            not _matches_or_array_is_subset_of(
+                key, value, profile_entitlement, platform
+            )
+        ):
+            return (
+                False,
+                EntitlementsMismatch(
+                    profile=profile,
+                    bundle_id_match_length=bundle_id_match_length,
+                    mismatched_key=key,
+                    mismatched_value=value,
+                ),
+            )
+    return (True, None)
+
+
+def _check_developer_certificates_match(
+    profile: ProvisioningProfileMetadata,
+    identities: list[CodeSigningIdentity],
+    bundle_id_match_length: int,
+) -> tuple[Optional[CodeSigningIdentity], Optional[DeveloperCertificateMismatch]]:
+    for identity in identities:
+        if identity.fingerprint in profile.developer_certificate_fingerprints:
+            return (identity, None)
+    return (
+        None,
+        DeveloperCertificateMismatch(
+            profile=profile, bundle_id_match_length=bundle_id_match_length
+        ),
+    )
+
+
+def _make_multiple_matching_profiles_message(
+    profiles: list[ProvisioningProfileMetadata],
+    strict_search: bool,
+) -> str:
+    messages = [f"Found MULTIPLE matching profiles: {len(profiles)}"]
+    messages += [
+        f"    Matching Profile = UUID:{profile.uuid}, creation date: {profile.creation_date}, file path: {profile.file_path}"
+        for profile in profiles
+    ]
+
+    if strict_search:
+        messages += [
+            "Strict provisioning profile search is ENABLED, build will FAIL due to ambiguous provisioning profile search results.",
+            "To resolve the problem, ensure only a single profile matches.",
+            "To unblock, you have two options:",
+            "Option 1: Disable strict provisioning profile search for the targets failing to build.",
+            "    If the target failing to build is an `apple_bundle()`, set the `strict_provisioning_profile_search` attribute to `False`.",
+            "    If the target failing to build is produced by `ios_binary()`, set the `bundle_strict_provisioning_profile_search` attribute to `False`.",
+            "    You can commit such a change, so that the issue can be investigated without blocking other developers.",
+            "    NB: This is a TEMPORARY WORKAROUND, as it only disables the strict checking, it does not resolve the ambiguity.",
+            "Option 2: Pass `--config apple.strict_provisioning_profile_search=false` as part of your build command.",
+            "    DO NOT COMMIT such a change by adding this to any CI configs.",
+        ]
+
+    return "\n".join(messages)
+
+
+@dataclass
+class SelectedProvisioningProfileInfo:
+    profile: ProvisioningProfileMetadata
+    identity: CodeSigningIdentity
+
+    def to_dict(self) -> dict[str, Any]:
+        return {
+            "identity": self.identity.to_dict(),
+            "profile": self.profile.to_dict(),
+        }
+
+    @staticmethod
+    def from_dict(value: object) -> SelectedProvisioningProfileInfo:
+        data = expect_dict(value, "SelectedProvisioningProfileInfo")
+        expect_keys(
+            data,
+            "SelectedProvisioningProfileInfo",
+            frozenset({"identity", "profile"}),
+        )
+        return SelectedProvisioningProfileInfo(
+            profile=ProvisioningProfileMetadata.from_dict(data["profile"]),
+            identity=CodeSigningIdentity.from_dict(data["identity"]),
+        )
+
+
+def _filter_matching_selected_provisioning_profile_infos(
+    selected_profile_infos: list[SelectedProvisioningProfileInfo],
+    provisioning_profile_filter: Optional[str],
+) -> list[SelectedProvisioningProfileInfo]:
+    if len(selected_profile_infos) <= 1 or (not provisioning_profile_filter):
+        return selected_profile_infos
+
+    preference_regex = re.compile(provisioning_profile_filter)
+    return [
+        matching_profile_info
+        for matching_profile_info in selected_profile_infos
+        if preference_regex.search(matching_profile_info.profile.file_path.name)
+    ]
+
+
+# See `ProvisioningProfileStore::getBestProvisioningProfile` in `ProvisioningProfileStore.java` for Buck v1 equivalent
+# This function operates on data types only without performing any IO or process invocation.
+def select_best_provisioning_profile_core(
+    info_plist_metadata: InfoPlistMetadata,
+    code_signing_identities: list[CodeSigningIdentity],
+    provisioning_profiles: list[ProvisioningProfileMetadata],
+    entitlements: Optional[dict[str, Any]],
+    platform: ApplePlatform,
+    strict_search: bool,
+    provisioning_profile_filter: Optional[str],
+    no_check_certificates: bool = False,
+) -> tuple[
+    Optional[SelectedProvisioningProfileInfo], list[IProvisioningProfileDiagnostics]
+]:
+    """Selects the best provisioning profile and certificate to use when code signing the bundle.
+       Such profile could be successfully used to sign the bundle taking into account
+       different constraints like entitlements or bundle ID. Given several profiles
+       could be successfully used to sign the bundle the "best" one is considered
+       to be a profile which matches bundle ID  from `Info.plist` the most
+       (i.e. profiles with specific bundle ID are preferred to wildcard bundle IDs).
+    Args:
+       info_plist_metadata: Object representing `Info.plist` file in the bundle.
+       code_signing_identities: Code signing identities to choose from.
+       provisioning_profiles: Provisioning profiles to choose from.
+       entitlements: Code signing entitlements if any.
+       platform: Apple platform which the bundle is built for.
+    Returns:
+       Provisioning profile and certificate pair to use for code signing.
+    """
+    maybe_team_id_constraint = _parse_team_id_from_entitlements(entitlements)
+
+    best_match_length = -1
+
+    # Used for error messages
+    diagnostics: list[IProvisioningProfileDiagnostics] = []
+
+    def log_mismatched_profile(mismatch: IProvisioningProfileDiagnostics) -> None:
+        diagnostics.append(mismatch)
+        _LOGGER.info(
+            f"Skipping provisioning profile `{mismatch.profile.file_path.name}`: {mismatch.log_message()}"
+        )
+
+    selected_profile_infos_for_match_length = defaultdict(list)
+
+    for profile in provisioning_profiles:
+        app_id = profile.get_app_id()
+        bundle_id = app_id.bundle_id
+        current_match_length = _bundle_match_length(
+            info_plist_metadata.bundle_id, bundle_id
+        )
+        if current_match_length < 0:
+            log_mismatched_profile(
+                BundleIdMismatch(
+                    profile=profile,
+                    bundle_id=app_id.bundle_id,
+                    bundle_id_constraint=info_plist_metadata.bundle_id,
+                )
+            )
+            continue
+
+        if maybe_team_id_constraint and maybe_team_id_constraint != app_id.team_id:
+            log_mismatched_profile(
+                TeamIdMismatch(
+                    profile=profile,
+                    team_id=app_id.team_id,
+                    team_id_constraint=maybe_team_id_constraint,
+                )
+            )
+            continue
+
+        if datetime.datetime.now() > profile.expiration_date:
+            log_mismatched_profile(
+                ProfileExpired(
+                    profile=profile, bundle_id_match_length=current_match_length
+                )
+            )
+            continue
+
+        maybe_provisioning_profile_name = platform.provisioning_profile_name()
+        if (
+            maybe_provisioning_profile_name
+            and maybe_provisioning_profile_name not in profile.platforms
+        ):
+            log_mismatched_profile(
+                UnsupportedPlatform(
+                    profile=profile,
+                    bundle_id_match_length=current_match_length,
+                    platform_constraint=platform,
+                )
+            )
+            continue
+
+        entitlements_matched, mismatch = _check_entitlements_match(
+            expected_entitlements=entitlements,
+            profile=profile,
+            platform=platform,
+            bundle_id_match_length=current_match_length,
+        )
+        if not entitlements_matched:
+            log_mismatched_profile(cast(EntitlementsMismatch, mismatch))
+            continue
+
+        if no_check_certificates:
+            certificate = CodeSigningIdentity(
+                fingerprint=next(iter(profile.developer_certificate_fingerprints)),
+                subject_common_name="Unknown",
+            )
+        else:
+            certificate, mismatch = _check_developer_certificates_match(
+                profile=profile,
+                identities=code_signing_identities,
+                bundle_id_match_length=current_match_length,
+            )
+            if not certificate:
+                log_mismatched_profile(cast(DeveloperCertificateMismatch, mismatch))
+                continue
+
+        _LOGGER.info(
+            f"Matching provisioning profile `{profile.file_path.name}` with score {current_match_length}"
+        )
+
+        selected_profile_info = SelectedProvisioningProfileInfo(profile, certificate)
+        selected_profile_infos_for_match_length[current_match_length] += [
+            selected_profile_info
+        ]
+
+        if current_match_length > best_match_length:
+            best_match_length = current_match_length
+
+    all_matching_selected_profile_infos = selected_profile_infos_for_match_length.get(
+        best_match_length, []
+    )
+
+    all_matching_selected_profile_infos = (
+        _filter_matching_selected_provisioning_profile_infos(
+            all_matching_selected_profile_infos, provisioning_profile_filter
+        )
+    )
+
+    if len(all_matching_selected_profile_infos) > 1:
+        all_matching_profiles = [
+            selected_profile_info.profile
+            for selected_profile_info in all_matching_selected_profile_infos
+        ]
+        multiple_profiles_message = _make_multiple_matching_profiles_message(
+            all_matching_profiles,
+            strict_search,
+        )
+        _LOGGER.info(multiple_profiles_message)
+        if strict_search:
+            raise CodeSignProvisioningError(multiple_profiles_message)
+
+    result = (
+        # If there are multiple matching profiles, pick the one with expiration date furthest in the future
+        max(
+            all_matching_selected_profile_infos,
+            key=lambda profile_info: profile_info.profile.expiration_date,
+        )
+        if all_matching_selected_profile_infos
+        else None
+    )
+
+    if result:
+        _LOGGER.info(
+            f"Found matching provisioning profile and identity\n"
+            f"  Selected Identity: {result.identity}\n"
+            f"  Provisioning Profile: `{result.profile.file_path.name}`\n"
+            f"    UUID: {result.profile.uuid}\n"
+            f"    File: {result.profile.file_path}\n"
+            f"    Expiration: {result.profile.expiration_date}\n"
+            f"    Platforms: {result.profile.platforms}\n"
+            f"    Fingerprints: {result.profile.developer_certificate_fingerprints}\n"
+            f"    Entitlements: {result.profile.entitlements}"
+        )
+
+    return result, diagnostics
diff --git a/buck2/prelude/apple/tools/code_signing/provisioning_profile_selection_test.py b/buck2/prelude/apple/tools/code_signing/provisioning_profile_selection_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/provisioning_profile_selection_test.py
@@ -0,0 +1,659 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import copy
+import unittest
+from datetime import datetime, timedelta
+from pathlib import Path
+
+from .apple_platform import ApplePlatform
+from .identity import CodeSigningIdentity
+from .info_plist_metadata import InfoPlistMetadata
+from .provisioning_profile_diagnostics import IProvisioningProfileDiagnostics
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+from .provisioning_profile_selection import (
+    select_best_provisioning_profile_core,
+    SelectedProvisioningProfileInfo,
+)
+
+
+class TestSelection(unittest.TestCase):
+    def verify_diagnostic_info_candidate_profile(
+        self,
+        diagnostic_info: list[IProvisioningProfileDiagnostics],
+        reason: str,
+    ):
+        self.assertEqual(len(diagnostic_info), 1)
+        candidate_profile = diagnostic_info[0]
+        self.assertEqual(
+            candidate_profile.log_message(),
+            reason,
+        )
+
+    def test_expired_profiles_are_ignored(self):
+        info_plist = InfoPlistMetadata("com.company.application", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        expired_provisioning_profile = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.min,
+            {"iOS"},
+            {identity.fingerprint},
+            {"application-identifier": "ABCDEFGHIJ.com.company.application"},
+        )
+        selected, diagnostic_info = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=[expired_provisioning_profile],
+            entitlements={},
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertIsNone(selected)
+        self.verify_diagnostic_info_candidate_profile(
+            diagnostic_info,
+            "Provisioning profile expired.",
+        )
+
+        fresh_provisioning_profiles = copy.copy(expired_provisioning_profile)
+        fresh_provisioning_profiles.expiration_date = datetime.max
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=[fresh_provisioning_profiles],
+            entitlements={},
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertIsNotNone(selected)
+
+    def test_multiple_matching_profiles_strict_mode(self):
+        info_plist = InfoPlistMetadata("com.company.application", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        first = ProvisioningProfileMetadata(
+            Path("/foo.first"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {"application-identifier": "AAAAAAAAAA.*"},
+        )
+        second = ProvisioningProfileMetadata(
+            Path("/foo.second"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {"application-identifier": "AAAAAAAAAA.*"},
+        )
+        profiles = [
+            first,
+            second,
+        ]
+
+        selection_failed = False
+        try:
+            _, _ = select_best_provisioning_profile_core(
+                info_plist_metadata=info_plist,
+                code_signing_identities=[identity],
+                provisioning_profiles=profiles,
+                entitlements={"keychain-access-groups": ["AAAAAAAAAA.*"]},
+                platform=ApplePlatform.ios_device,
+                strict_search=True,
+                provisioning_profile_filter=None,
+            )
+        except Exception:
+            selection_failed = True
+
+        self.assertTrue(selection_failed)
+
+    def test_multiple_matching_profiles_with_preference(self):
+        info_plist = InfoPlistMetadata("com.company.application", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        first = ProvisioningProfileMetadata(
+            Path("/foo.first"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {"application-identifier": "AAAAAAAAAA.*"},
+        )
+        second = ProvisioningProfileMetadata(
+            Path("/foo.second"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {"application-identifier": "AAAAAAAAAA.*"},
+        )
+        third = ProvisioningProfileMetadata(
+            Path("/foo.third"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {"application-identifier": "AAAAAAAAAA.*"},
+        )
+        profiles = [
+            first,
+            second,
+            third,
+        ]
+
+        selection_failed = False
+        try:
+            _, _ = select_best_provisioning_profile_core(
+                info_plist_metadata=info_plist,
+                code_signing_identities=[identity],
+                provisioning_profiles=profiles,
+                entitlements={"keychain-access-groups": ["AAAAAAAAAA.*"]},
+                platform=ApplePlatform.ios_device,
+                strict_search=True,
+                provisioning_profile_filter=None,
+            )
+        except Exception:
+            selection_failed = True
+
+        # Check selection fails without preference
+        self.assertTrue(selection_failed)
+
+        selected_profile_info, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=profiles,
+            entitlements={"keychain-access-groups": ["AAAAAAAAAA.*"]},
+            platform=ApplePlatform.ios_device,
+            strict_search=True,
+            provisioning_profile_filter=".+second",
+        )
+        # Check the middle profile got chosen (i.e., not first or last)
+        self.assertEqual(selected_profile_info.profile, second)
+
+    def test_multiple_matching_profiles_nonstrict_mode(self):
+        info_plist = InfoPlistMetadata("com.company.application", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        first = ProvisioningProfileMetadata(
+            Path("/foo.first"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max - timedelta(days=2),
+            {"iOS"},
+            {identity.fingerprint},
+            {"application-identifier": "AAAAAAAAAA.*"},
+        )
+        second = ProvisioningProfileMetadata(
+            Path("/foo.second"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max - timedelta(days=1),
+            {"iOS"},
+            {identity.fingerprint},
+            {"application-identifier": "AAAAAAAAAA.*"},
+        )
+        third = ProvisioningProfileMetadata(
+            Path("/foo.third"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max - timedelta(days=3),
+            {"iOS"},
+            {identity.fingerprint},
+            {"application-identifier": "AAAAAAAAAA.*"},
+        )
+        profiles = [
+            first,
+            second,
+            third,
+        ]
+
+        selected_profile_info, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=profiles,
+            entitlements={"keychain-access-groups": ["AAAAAAAAAA.*"]},
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+
+        # Check that we selected the profile with the latest expiration date
+        # given multiple matches in non-strict mode
+        self.assertEqual(selected_profile_info.profile, second)
+
+    def test_prefix_override(self):
+        info_plist = InfoPlistMetadata("com.company.application", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        expected = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {"application-identifier": "AAAAAAAAAA.*"},
+        )
+        profiles = [
+            expected,
+            ProvisioningProfileMetadata(
+                Path("/foo"),
+                "00000000-0000-0000-0000-000000000000",
+                datetime.max,
+                {"iOS"},
+                {identity.fingerprint},
+                {"application-identifier": "BBBBBBBBBB.com.company.application"},
+            ),
+        ]
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=profiles,
+            entitlements={"keychain-access-groups": ["AAAAAAAAAA.*"]},
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))
+
+    def test_entitlement_keys_are_matched(self):
+        info_plist = InfoPlistMetadata("com.company.application", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        expected = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "11111111-1111-1111-1111-111111111111",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {
+                "application-identifier": "AAAAAAAAAA.com.company.application",
+                "keychain-access-groups": ["AAAAAAAAAA.*"],
+                "aps-environment": "production",
+                "com.apple.security.application-groups": ["foo", "bar", "baz"],
+            },
+        )
+        unexpected = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {
+                "application-identifier": "AAAAAAAAAA.com.company.application",
+                "keychain-access-groups": ["AAAAAAAAAA.*"],
+                "aps-environment": "development",
+                "com.apple.security.application-groups": ["foo", "bar"],
+            },
+        )
+        profiles = [
+            expected,
+            unexpected,
+        ]
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=profiles,
+            entitlements={
+                "keychain-access-groups": ["AAAAAAAAAA.*"],
+                "aps-environment": "production",
+                "com.apple.security.application-groups": ["foo", "bar"],
+            },
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))
+
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=profiles,
+            entitlements={
+                "aps-environment": "production",
+                "com.apple.security.application-groups": ["foo", "bar"],
+            },
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))
+
+        selected, diagnostic_info = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=[unexpected],
+            entitlements={
+                "aps-environment": "production",
+                "com.apple.security.application-groups": ["foo", "xxx"],
+            },
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertIsNone(selected)
+        self.verify_diagnostic_info_candidate_profile(
+            diagnostic_info,
+            "Expected entitlement item key `aps-environment` with value `production` not found in provisioning profile.",
+        )
+
+    def test_only_profiles_containing_valid_fingerprints_are_matched(self):
+        info_plist = InfoPlistMetadata("com.company.application", None, False)
+        valid_identity = CodeSigningIdentity(
+            "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
+            "iPhone Developer: Foo Bar (54321EDCBA)",
+        )
+        other_identity = CodeSigningIdentity(
+            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+            "iPhone Developer: Foo Bar (ABCDE12345)",
+        )
+        expected = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "11111111-1111-1111-1111-111111111111",
+            datetime.max,
+            {"iOS"},
+            {valid_identity.fingerprint, other_identity.fingerprint},
+            {
+                "application-identifier": "AAAAAAAAAA.*",
+            },
+        )
+        unexpected = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {other_identity.fingerprint},
+            {
+                "application-identifier": "AAAAAAAAAA.com.company.application",
+            },
+        )
+
+        profiles = [expected, unexpected]
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[valid_identity],
+            provisioning_profiles=profiles,
+            entitlements={},
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertEqual(
+            selected, SelectedProvisioningProfileInfo(expected, valid_identity)
+        )
+        selected, diagnostic_info = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[valid_identity],
+            provisioning_profiles=[unexpected],
+            entitlements={},
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertIsNone(selected)
+        self.verify_diagnostic_info_candidate_profile(
+            diagnostic_info,
+            "Expected identity fingerprint not found in profile's certificate fingerprints `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`.",
+        )
+
+    def test_matches_specific_app(self):
+        info_plist = InfoPlistMetadata("com.facebook.test", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        expected = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {
+                "application-identifier": "BBBBBBBBBB.com.facebook.test",
+            },
+        )
+        profiles = [
+            expected,
+            ProvisioningProfileMetadata(
+                Path("/foo"),
+                "11111111-1111-1111-1111-111111111111",
+                datetime.max,
+                {"iOS"},
+                {identity.fingerprint},
+                {
+                    "application-identifier": "BBBBBBBBBB.com.facebook.*",
+                },
+            ),
+        ]
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=profiles,
+            entitlements={},
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))
+
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=reversed(profiles),
+            entitlements={},
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))
+
+    def test_matches_wildcard(self):
+        info_plist = InfoPlistMetadata("com.facebook.test", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        expected = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {
+                "application-identifier": "BBBBBBBBBB.*",
+            },
+        )
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=[expected],
+            entitlements=None,
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertEqual(selected, SelectedProvisioningProfileInfo(expected, identity))
+
+    def test_force_included_app_entitlements(self):
+        info_plist = InfoPlistMetadata("com.facebook.test", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        profile = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {
+                "application-identifier": "AAAAAAAAAA.com.facebook.test",
+                "keychain-access-groups": ["AAAAAAAAAA.*"],
+                "aps-environment": "production",
+            },
+        )
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=[profile],
+            entitlements={
+                # Force included key, even if not present in the profile
+                "application-identifier": "AAAAAAAAAA.com.facebook.BuckApp",
+                "keychain-access-groups": ["AAAAAAAAAA.*"],
+                "aps-environment": "production",
+            },
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertIsNotNone(selected)
+
+    def test_unmatched_app_entitlement(self):
+        info_plist = InfoPlistMetadata("com.facebook.test", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        profile = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {
+                "application-identifier": "AAAAAAAAAA.com.facebook.test",
+                "keychain-access-groups": ["AAAAAAAAAA.*"],
+                "aps-environment": "production",
+            },
+        )
+        selected, diagnostic_info = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=[profile],
+            entitlements={
+                "keychain-access-groups": ["AAAAAAAAAA.*"],
+                "aps-environment": "production",
+                "com.made.up.entitlement": "buck",
+            },
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertIsNone(selected)
+        self.verify_diagnostic_info_candidate_profile(
+            diagnostic_info,
+            "Expected entitlement item key `com.made.up.entitlement` with value `buck` not found in provisioning profile.",
+        )
+
+    def test_wildcard_app_entitlement_matches_any_value(self):
+        info_plist = InfoPlistMetadata("com.facebook.test", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        profile = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {
+                "application-identifier": "AAAAAAAAAA.com.facebook.test",
+                "keychain-access-groups": ["AAAAAAAAAA.*"],
+                "aps-environment": "production",
+                "com.apple.security.hardened-process.enhanced-security-version": "*",
+                "com.apple.security.hardened-process.platform-restrictions": "*",
+            },
+        )
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=[profile],
+            entitlements={
+                "com.apple.security.hardened-process.enhanced-security-version": "1",
+                "com.apple.security.hardened-process.platform-restrictions": "2",
+            },
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertEqual(selected, SelectedProvisioningProfileInfo(profile, identity))
+
+    def test_unmatched_wildcard_app_entitlement(self):
+        info_plist = InfoPlistMetadata("com.facebook.test", None, False)
+        identity = CodeSigningIdentity(
+            "fingerprint",
+            "name",
+        )
+        profile = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {identity.fingerprint},
+            {
+                "application-identifier": "AAAAAAAAAA.com.facebook.test",
+                "keychain-access-groups": ["AAAAAAAAAA.*"],
+                "aps-environment": "production",
+            },
+        )
+        selected, diagnostic_info = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[identity],
+            provisioning_profiles=[profile],
+            entitlements={
+                "com.apple.security.hardened-process.enhanced-security-version": "1",
+                "com.apple.security.hardened-process.platform-restrictions": "2",
+            },
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+        )
+        self.assertIsNone(selected)
+        self.verify_diagnostic_info_candidate_profile(
+            diagnostic_info,
+            "Expected entitlement item key `com.apple.security.hardened-process.enhanced-security-version` with value `1` not found in provisioning profile.",
+        )
+
+    def test_no_check_certificates_skips_identity_matching(self):
+        info_plist = InfoPlistMetadata("com.company.application", None, False)
+        profile = ProvisioningProfileMetadata(
+            Path("/foo"),
+            "00000000-0000-0000-0000-000000000000",
+            datetime.max,
+            {"iOS"},
+            {"some_fingerprint"},
+            {"application-identifier": "AAAAAAAAAA.com.company.application"},
+        )
+        # Empty identities list - would fail without no_check_certificates
+        selected, _ = select_best_provisioning_profile_core(
+            info_plist_metadata=info_plist,
+            code_signing_identities=[],
+            provisioning_profiles=[profile],
+            entitlements={},
+            platform=ApplePlatform.ios_device,
+            strict_search=False,
+            provisioning_profile_filter=None,
+            no_check_certificates=True,
+        )
+        self.assertIsNotNone(selected)
+        self.assertEqual(selected.profile, profile)
+        self.assertEqual(selected.identity.fingerprint, "some_fingerprint")
+        self.assertEqual(selected.identity.subject_common_name, "Unknown")
diff --git a/buck2/prelude/apple/tools/code_signing/read_provisioning_profile_command_factory.py b/buck2/prelude/apple/tools/code_signing/read_provisioning_profile_command_factory.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/read_provisioning_profile_command_factory.py
@@ -0,0 +1,39 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from abc import ABCMeta, abstractmethod
+from pathlib import Path
+from typing import Union
+
+
+class IReadProvisioningProfileCommandFactory(metaclass=ABCMeta):
+    @abstractmethod
+    def read_provisioning_profile_command(self, path: Path) -> list[Union[str, Path]]:
+        raise NotImplementedError
+
+
+# See `DEFAULT_READ_COMMAND` in `AppleConfig.java` in Buck v1
+OPENSSL_PROV_PROFILE_READ_COMMAND = [
+    "openssl",
+    "smime",
+    "-inform",
+    "der",
+    "-verify",
+    "-noverify",
+    "-nosigs",
+    "-in",
+]
+
+
+class DefaultReadProvisioningProfileCommandFactory(
+    IReadProvisioningProfileCommandFactory
+):
+    def read_provisioning_profile_command(self, path: Path) -> list[Union[str, Path]]:
+        return OPENSSL_PROV_PROFILE_READ_COMMAND + [path]
diff --git a/buck2/prelude/apple/tools/code_signing/serialization.py b/buck2/prelude/apple/tools/code_signing/serialization.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/serialization.py
@@ -0,0 +1,67 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+from typing import cast
+
+
+def expect_dict(value: object, path: str) -> dict[str, object]:
+    if not isinstance(value, dict) or not all(
+        isinstance(key, str) for key in value.keys()
+    ):
+        raise ValueError(f"{path} must be an object")
+    return cast(dict[str, object], value)
+
+
+def expect_keys(
+    data: dict[str, object],
+    path: str,
+    expected: frozenset[str],
+) -> None:
+    actual = frozenset(data)
+    if actual != expected:
+        missing = sorted(expected - actual)
+        unexpected = sorted(actual - expected)
+        raise ValueError(
+            f"{path} has invalid keys: missing={missing}, unexpected={unexpected}"
+        )
+
+
+def expect_str(value: object, path: str) -> str:
+    if not isinstance(value, str):
+        raise ValueError(f"{path} must be a string")
+    return value
+
+
+def expect_optional_str(value: object, path: str) -> str | None:
+    if value is None:
+        return None
+    return expect_str(value, path)
+
+
+def expect_bool(value: object, path: str) -> bool:
+    if not isinstance(value, bool):
+        raise ValueError(f"{path} must be a boolean")
+    return value
+
+
+def expect_optional_bool(value: object, path: str) -> bool | None:
+    if value is None:
+        return None
+    return expect_bool(value, path)
+
+
+def expect_str_list(value: object, path: str) -> list[str]:
+    if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
+        raise ValueError(f"{path} must be a list of strings")
+    return cast(list[str], value)
+
+
+def expect_optional_str_list(value: object, path: str) -> list[str] | None:
+    if value is None:
+        return None
+    return expect_str_list(value, path)
diff --git a/buck2/prelude/apple/tools/code_signing/signing_context_types.py b/buck2/prelude/apple/tools/code_signing/signing_context_types.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/signing_context_types.py
@@ -0,0 +1,143 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional, Union
+
+from .identity import CodeSigningIdentity
+from .info_plist_metadata import InfoPlistMetadata
+from .provisioning_profile_selection import SelectedProvisioningProfileInfo
+from .serialization import expect_dict, expect_keys, expect_str
+
+
+@dataclass
+class SigningContextWithProfileSelection:
+    info_plist_source: Path
+    info_plist_destination: Path
+    info_plist_metadata: InfoPlistMetadata
+    selected_profile_info: SelectedProvisioningProfileInfo
+
+    def to_dict(self) -> dict[str, object]:
+        return {
+            "info_plist_source": str(self.info_plist_source),
+            "info_plist_destination": str(self.info_plist_destination),
+            "info_plist_metadata": self.info_plist_metadata.to_dict(),
+            "selected_profile_info": self.selected_profile_info.to_dict(),
+        }
+
+    @staticmethod
+    def from_dict(value: object) -> SigningContextWithProfileSelection:
+        data = expect_dict(value, "SigningContextWithProfileSelection")
+        expect_keys(
+            data,
+            "SigningContextWithProfileSelection",
+            frozenset(
+                {
+                    "info_plist_source",
+                    "info_plist_destination",
+                    "info_plist_metadata",
+                    "selected_profile_info",
+                }
+            ),
+        )
+        return SigningContextWithProfileSelection(
+            info_plist_source=Path(
+                expect_str(
+                    data["info_plist_source"],
+                    "SigningContextWithProfileSelection.info_plist_source",
+                )
+            ),
+            info_plist_destination=Path(
+                expect_str(
+                    data["info_plist_destination"],
+                    "SigningContextWithProfileSelection.info_plist_destination",
+                )
+            ),
+            info_plist_metadata=InfoPlistMetadata.from_dict(
+                data["info_plist_metadata"]
+            ),
+            selected_profile_info=SelectedProvisioningProfileInfo.from_dict(
+                data["selected_profile_info"]
+            ),
+        )
+
+
+@dataclass
+class AdhocSigningContext:
+    codesign_identity: str
+    profile_selection_context: Optional[SigningContextWithProfileSelection]
+
+    def __init__(
+        self,
+        codesign_identity: Optional[str] = None,
+        profile_selection_context: Optional[SigningContextWithProfileSelection] = None,
+    ) -> None:
+        self.codesign_identity = codesign_identity or "-"
+        self.profile_selection_context = profile_selection_context
+
+    def identity(self) -> CodeSigningIdentity:
+        if self.profile_selection_context:
+            return self.profile_selection_context.selected_profile_info.identity
+        return CodeSigningIdentity(
+            fingerprint=self.codesign_identity,
+            subject_common_name="",
+        )
+
+    def to_dict(self) -> dict[str, object]:
+        return {
+            "codesign_identity": self.codesign_identity,
+            "profile_selection_context": (
+                self.profile_selection_context.to_dict()
+                if self.profile_selection_context
+                else None
+            ),
+        }
+
+    @staticmethod
+    def from_dict(value: object) -> AdhocSigningContext:
+        data = expect_dict(value, "AdhocSigningContext")
+        expect_keys(
+            data,
+            "AdhocSigningContext",
+            frozenset({"codesign_identity", "profile_selection_context"}),
+        )
+        psc_data = data["profile_selection_context"]
+        psc = (
+            SigningContextWithProfileSelection.from_dict(psc_data)
+            if psc_data is not None
+            else None
+        )
+        return AdhocSigningContext(
+            codesign_identity=expect_str(
+                data["codesign_identity"], "AdhocSigningContext.codesign_identity"
+            ),
+            profile_selection_context=psc,
+        )
+
+
+def selection_profile_context_from_signing_context(
+    signing_context: Optional[
+        Union[AdhocSigningContext, SigningContextWithProfileSelection]
+    ],
+) -> Optional[SigningContextWithProfileSelection]:
+    if signing_context:
+        if isinstance(signing_context, SigningContextWithProfileSelection):
+            selection_profile_context = signing_context
+        elif isinstance(signing_context, AdhocSigningContext):
+            selection_profile_context = signing_context.profile_selection_context
+        else:
+            raise RuntimeError(
+                f"Unexpected type of signing context `{type(signing_context)}`"
+            )
+        return selection_profile_context
+    return None
diff --git a/buck2/prelude/apple/tools/code_signing/signing_context_types_test.py b/buck2/prelude/apple/tools/code_signing/signing_context_types_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/signing_context_types_test.py
@@ -0,0 +1,316 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import datetime
+import json
+import unittest
+from pathlib import Path
+
+from .identity import CodeSigningIdentity
+from .info_plist_metadata import InfoPlistMetadata
+from .provisioning_profile_metadata import ProvisioningProfileMetadata
+from .provisioning_profile_selection import SelectedProvisioningProfileInfo
+from .signing_context_types import (
+    AdhocSigningContext,
+    SigningContextWithProfileSelection,
+)
+
+
+class TestIdentitySerialization(unittest.TestCase):
+    def test_round_trip(self):
+        identity = CodeSigningIdentity(
+            fingerprint="ABCDEF1234567890ABCDEF1234567890ABCDEF12",
+            subject_common_name="Apple Development: Test",
+        )
+        data = identity.to_dict()
+        restored = CodeSigningIdentity.from_dict(data)
+        self.assertEqual(identity, restored)
+        json_str = json.dumps(data)
+        loaded = json.loads(json_str)
+        restored2 = CodeSigningIdentity.from_dict(loaded)
+        self.assertEqual(identity, restored2)
+
+    def test_rejects_unknown_fields(self):
+        with self.assertRaisesRegex(ValueError, "unexpected=.*team_id"):
+            CodeSigningIdentity.from_dict(
+                {
+                    "fingerprint": "ABC",
+                    "subject_common_name": "Developer",
+                    "team_id": "TEAM",
+                }
+            )
+
+    def test_rejects_invalid_field_type(self):
+        with self.assertRaisesRegex(ValueError, "fingerprint must be a string"):
+            CodeSigningIdentity.from_dict(
+                {"fingerprint": 123, "subject_common_name": "Developer"}
+            )
+
+
+class TestInfoPlistMetadataSerialization(unittest.TestCase):
+    def test_round_trip(self):
+        metadata = InfoPlistMetadata(
+            bundle_id="com.test.app", bundle_type="APPL", is_watchos_app=False
+        )
+        data = metadata.to_dict()
+        restored = InfoPlistMetadata.from_dict(data)
+        self.assertEqual(metadata, restored)
+
+    def test_optional_fields(self):
+        data = {"bundle_id": "com.test", "bundle_type": None, "is_watchos_app": False}
+        restored = InfoPlistMetadata.from_dict(data)
+        self.assertEqual(restored.bundle_id, "com.test")
+        self.assertIsNone(restored.bundle_type)
+
+    def test_requires_watchos_field(self):
+        with self.assertRaisesRegex(ValueError, "missing=.*is_watchos_app"):
+            InfoPlistMetadata.from_dict({"bundle_id": "com.test", "bundle_type": None})
+
+
+class TestProvisioningProfileMetadataSerialization(unittest.TestCase):
+    def test_round_trip_basic(self):
+        expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)
+        creation = datetime.datetime(2024, 1, 1, 12, 0, 0)
+        profile = ProvisioningProfileMetadata(
+            file_path=Path("/tmp/profile.mobileprovision"),
+            uuid="UUID-1234",
+            expiration_date=expiration,
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(["ABCDEF1234567890"]),
+            entitlements={"application-identifier": "TEAM.com.test.app"},
+            creation_date=creation,
+            provisions_all_devices=False,
+            provisioned_devices=["device1"],
+        )
+        data = profile.to_dict()
+        restored = ProvisioningProfileMetadata.from_dict(data)
+        self.assertEqual(restored.uuid, profile.uuid)
+        self.assertEqual(restored.expiration_date, profile.expiration_date)
+        self.assertEqual(restored.creation_date, profile.creation_date)
+        self.assertEqual(restored.platforms, profile.platforms)
+        self.assertEqual(
+            restored.developer_certificate_fingerprints,
+            profile.developer_certificate_fingerprints,
+        )
+        self.assertEqual(restored.entitlements, profile.entitlements)
+
+    def test_bytes_and_datetime_entitlements(self):
+        expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)
+        profile = ProvisioningProfileMetadata(
+            file_path=Path("/tmp/profile.mobileprovision"),
+            uuid="UUID-BYTES",
+            expiration_date=expiration,
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(["ABC"]),
+            entitlements={
+                "data-key": b"\x00\x01\x02binary",
+                "date-key": datetime.datetime(2024, 6, 1, 10, 0, 0),
+                "nested": {"inner-bytes": b"inner"},
+            },
+            creation_date=None,
+            provisions_all_devices=False,
+            provisioned_devices=None,
+        )
+        data = profile.to_dict()
+        json_str = json.dumps(data)
+        loaded = json.loads(json_str)
+        restored = ProvisioningProfileMetadata.from_dict(loaded)
+        self.assertEqual(restored.entitlements["data-key"], b"\x00\x01\x02binary")
+        self.assertEqual(
+            restored.entitlements["date-key"],
+            datetime.datetime(2024, 6, 1, 10, 0, 0),
+        )
+        self.assertEqual(restored.entitlements["nested"]["inner-bytes"], b"inner")
+
+    def test_rejects_missing_fields(self):
+        profile = self._profile()
+        data = profile.to_dict()
+        del data["platforms"]
+        with self.assertRaisesRegex(ValueError, "missing=.*platforms"):
+            ProvisioningProfileMetadata.from_dict(data)
+
+    def test_rejects_malformed_entitlement_marker(self):
+        profile = self._profile()
+        data = profile.to_dict()
+        data["entitlements"] = {"data-key": {"__apple_code_signing_bytes_b64__": 123}}
+        with self.assertRaisesRegex(ValueError, "must be a string"):
+            ProvisioningProfileMetadata.from_dict(data)
+
+    def test_marker_shaped_entitlement_dicts_round_trip(self):
+        profile = self._profile()
+        profile.entitlements = {
+            "bytes-marker": {"__apple_code_signing_bytes_b64__": "YWJj"},
+            "datetime-marker": {
+                "__apple_code_signing_datetime_iso__": "2025-01-01T12:00:00"
+            },
+            "escape-marker": {
+                "__apple_code_signing_escaped_dict__": {"nested": "value"}
+            },
+        }
+
+        serialized = json.loads(json.dumps(profile.to_dict()))
+        restored = ProvisioningProfileMetadata.from_dict(serialized)
+
+        self.assertEqual(profile.entitlements, restored.entitlements)
+
+    def _profile(self) -> ProvisioningProfileMetadata:
+        return ProvisioningProfileMetadata(
+            file_path=Path("/tmp/profile.mobileprovision"),
+            uuid="UUID-STRICT",
+            expiration_date=datetime.datetime(2025, 1, 1, 12, 0, 0),
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(["ABC"]),
+            entitlements={},
+            creation_date=None,
+            provisions_all_devices=False,
+            provisioned_devices=None,
+        )
+
+
+class TestSelectedProvisioningProfileInfoSerialization(unittest.TestCase):
+    def test_round_trip(self):
+        expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)
+        profile = ProvisioningProfileMetadata(
+            file_path=Path("/tmp/profile.mobileprovision"),
+            uuid="UUID-1234",
+            expiration_date=expiration,
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(["ABC"]),
+            entitlements={},
+            creation_date=None,
+            provisions_all_devices=False,
+            provisioned_devices=None,
+        )
+        identity = CodeSigningIdentity(
+            fingerprint="ABC", subject_common_name="Apple Development: Test"
+        )
+        data_no_file = {
+            "identity": identity.to_dict(),
+            "profile": profile.to_dict(),
+        }
+        json_str = json.dumps(data_no_file)
+        loaded = json.loads(json_str)
+        restored = SelectedProvisioningProfileInfo.from_dict(loaded)
+        self.assertEqual(restored.profile.uuid, "UUID-1234")
+        self.assertEqual(restored.identity.fingerprint, "ABC")
+
+
+class TestSigningContextWithProfileSelectionSerialization(unittest.TestCase):
+    def test_round_trip(self):
+        expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)
+        profile = ProvisioningProfileMetadata(
+            file_path=Path("/tmp/profile.mobileprovision"),
+            uuid="UUID-1234",
+            expiration_date=expiration,
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(["ABC"]),
+            entitlements={},
+            creation_date=None,
+            provisions_all_devices=False,
+            provisioned_devices=None,
+        )
+        identity = CodeSigningIdentity(fingerprint="ABC", subject_common_name="Dev")
+        selected = SelectedProvisioningProfileInfo(profile=profile, identity=identity)
+        metadata = InfoPlistMetadata(
+            bundle_id="com.test.app", bundle_type="APPL", is_watchos_app=False
+        )
+        ctx = SigningContextWithProfileSelection(
+            info_plist_source=Path("/tmp/Info.plist"),
+            info_plist_destination=Path("Info.plist"),
+            info_plist_metadata=metadata,
+            selected_profile_info=selected,
+        )
+        dict_without_file = {
+            "info_plist_source": str(ctx.info_plist_source),
+            "info_plist_destination": str(ctx.info_plist_destination),
+            "info_plist_metadata": metadata.to_dict(),
+            "selected_profile_info": {
+                "identity": identity.to_dict(),
+                "profile": profile.to_dict(),
+            },
+        }
+        json_str = json.dumps(dict_without_file)
+        loaded = json.loads(json_str)
+        restored = SigningContextWithProfileSelection.from_dict(loaded)
+        self.assertEqual(restored.info_plist_source, Path("/tmp/Info.plist"))
+        self.assertEqual(restored.info_plist_metadata.bundle_id, "com.test.app")
+        self.assertEqual(restored.selected_profile_info.profile.uuid, "UUID-1234")
+
+
+class TestAdhocSigningContextSerialization(unittest.TestCase):
+    def test_adhoc_without_profile(self):
+        ctx = AdhocSigningContext(codesign_identity="-", profile_selection_context=None)
+        data = ctx.to_dict()
+        self.assertIsNone(data["profile_selection_context"])
+        json_str = json.dumps(data)
+        loaded = json.loads(json_str)
+        restored = AdhocSigningContext.from_dict(loaded)
+        self.assertEqual(restored.codesign_identity, "-")
+        self.assertIsNone(restored.profile_selection_context)
+
+    def test_rejects_null_codesign_identity(self):
+        with self.assertRaisesRegex(ValueError, "codesign_identity must be a string"):
+            AdhocSigningContext.from_dict(
+                {
+                    "codesign_identity": None,
+                    "profile_selection_context": None,
+                }
+            )
+
+    def test_adhoc_with_profile_explicit_none_check(self):
+        # Ensures from_dict uses `is not None` check, not truthiness, so empty dict case would be preserved if ever occurs
+        expiration = datetime.datetime(2025, 1, 1, 12, 0, 0)
+        profile = ProvisioningProfileMetadata(
+            file_path=Path("/tmp/profile.mobileprovision"),
+            uuid="UUID-5678",
+            expiration_date=expiration,
+            platforms=frozenset(["iOS"]),
+            developer_certificate_fingerprints=frozenset(["AAA"]),
+            entitlements={},
+            creation_date=None,
+            provisions_all_devices=True,
+            provisioned_devices=None,
+        )
+        identity = CodeSigningIdentity(fingerprint="AAA", subject_common_name="Adhoc")
+        selected = SelectedProvisioningProfileInfo(profile=profile, identity=identity)
+        metadata = InfoPlistMetadata(
+            bundle_id="com.test.app", bundle_type="APPL", is_watchos_app=False
+        )
+        distribution = SigningContextWithProfileSelection(
+            info_plist_source=Path("/tmp/Info.plist"),
+            info_plist_destination=Path("Info.plist"),
+            info_plist_metadata=metadata,
+            selected_profile_info=selected,
+        )
+        adhoc = AdhocSigningContext(
+            codesign_identity="Apple Development: Adhoc",
+            profile_selection_context=distribution,
+        )
+        data = adhoc.to_dict()
+        json_str = json.dumps(
+            {
+                "codesign_identity": data["codesign_identity"],
+                "profile_selection_context": {
+                    "info_plist_source": str(distribution.info_plist_source),
+                    "info_plist_destination": str(distribution.info_plist_destination),
+                    "info_plist_metadata": metadata.to_dict(),
+                    "selected_profile_info": {
+                        "identity": identity.to_dict(),
+                        "profile": profile.to_dict(),
+                    },
+                },
+            }
+        )
+        loaded = json.loads(json_str)
+        restored = AdhocSigningContext.from_dict(loaded)
+        self.assertEqual(restored.codesign_identity, "Apple Development: Adhoc")
+        assert restored.profile_selection_context is not None
+        self.assertEqual(
+            restored.profile_selection_context.selected_profile_info.profile.uuid,
+            "UUID-5678",
+        )
diff --git a/buck2/prelude/apple/tools/code_signing/test_resources/qualified_sample.mobileprovision b/buck2/prelude/apple/tools/code_signing/test_resources/qualified_sample.mobileprovision
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/test_resources/qualified_sample.mobileprovision
@@ -0,0 +1,78 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>AppIDName</key>
+	<string>Example</string>
+	<key>ApplicationIdentifierPrefix</key>
+	<array>
+	<string>ABCDE12345</string>
+	</array>
+	<key>CreationDate</key>
+	<date>2015-07-08T20:27:14Z</date>
+	<key>Platform</key>
+	<array>
+		<string>iOS</string>
+	</array>
+	<key>DeveloperCertificates</key>
+	<array>
+    <data>
+      MIIDSzCCAjOgAwIBAgIBATANBgkqhkiG9w0BAQsFADBTMSAwHgYDVQQDDBdCdWNrIFRlc3QgQ29kZXNp
+      Z24gQ2VydDELMAkGA1UEBhMCVVMxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wHhcN
+      MTUxMDIzMjAwNzI1WhcNMzIwMzI3MjAwNzI1WjBTMSAwHgYDVQQDDBdCdWNrIFRlc3QgQ29kZXNpZ24g
+      Q2VydDELMAkGA1UEBhMCVVMxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wggEiMA0G
+      CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrmmMdeV17d72ihmdbB0MTn5v3iu9LSGVYlbnJbI+FNmDJ
+      1U/0PAR7aLIPux0puN3N1Rob5VMdSZCG+SvsjV5zUNyepiRYlhf1jMyYTGDuoF8EOtfE94w9kr1EH9gl
+      aKRqir4770oXrFywbOaDO1iLPkpiVnfKVkkoU4dM0UD3YEtXoM70LIpYouGtVvNyc0Sx9/emvyiMH3iA
+      yQz5erVdfJQ2O85eyXz+U6rrcsNQpE0AuyQNnBnm0irSvtvnoPxlCsf0EbLnmnkDlv8yTrgCxzj/jmys
+      0zs+EZFAjYCX/I2ef63Ll+Wm7ilh7CjwNaRMIQmL0QpJIR9kUYnp3v33AgMBAAGjKjAoMA4GA1UdDwEB
+      /wQEAwIHgDAWBgNVHSUBAf8EDDAKBggrBgEFBQcDAzANBgkqhkiG9w0BAQsFAAOCAQEATpWzY5IXhyb4
+      PXiRS64Q6Sh2YXj6Dot2srWC+FJwWngGbF6J8aQfoymsRTkgTa+69WinMefmdRkEzysmXvAUfD1iWpBX
+      jRREQXkUhmt2FwqKp8pWbYSlgOTaQMojQn3DdvDu8l5ZFIrU+8Z8X4g/aggvffoIOygHvhbwkcgrA6Lq
+      TziJssmKd56+QKfVfx52vg6pv1Ok03pmVsQ8semHTJr53juc4QutADhtJBXe9inVs1evosO15At0N731
+      Lz37Bzwedpu8DSEr4PIdwF5yBDRbQoyAF29zQaJgO/mU2G4i9wYTZJrj75BD/qr2ukjQOYOtz4IVNUuz
+      kPu+rDPz4A==
+    </data>
+	</array>
+	<key>Entitlements</key>
+	<dict>
+		<key>keychain-access-groups</key>
+		<array>
+			<string>ABCDE12345.*</string>
+		</array>
+		<key>com.apple.security.get-task-allow</key>
+		<false/>
+		<key>com.apple.application-identifier</key>
+		<string>ABCDE12345.com.example.TestApp</string>
+		<key>com.apple.security.application-groups</key>
+		<array>
+			<string>group.com.example</string>
+		</array>
+		<key>com.apple.developer.team-identifier</key>
+		<string>12345ABCDE</string>
+    <key>com.apple.developer.icloud-container-development-container-identifiers</key>
+    <array>
+      <string>iCloud.com.appleseedinc.MyProject</string>
+      <string>iCloud.com.appleseedinc.container1</string>
+    </array>
+	</dict>
+	<key>ExpirationDate</key>
+	<date>9999-03-05T01:33:40Z</date>
+	<key>Name</key>
+	<string>Example</string>
+	<key>ProvisionsAllDevices</key>
+	<true/>
+	<key>TeamIdentifier</key>
+	<array>
+		<string>12345ABCDE</string>
+	</array>
+	<key>TeamName</key>
+	<string>Example</string>
+	<key>TimeToLive</key>
+	<integer>240</integer>
+	<key>UUID</key>
+	<string>00000000-0000-0000-0000-000000000000</string>
+	<key>Version</key>
+	<integer>1</integer>
+</dict>
+</plist>
diff --git a/buck2/prelude/apple/tools/code_signing/test_resources/sample.mobileprovision b/buck2/prelude/apple/tools/code_signing/test_resources/sample.mobileprovision
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/test_resources/sample.mobileprovision
@@ -0,0 +1,78 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>AppIDName</key>
+	<string>Example</string>
+	<key>ApplicationIdentifierPrefix</key>
+	<array>
+	<string>ABCDE12345</string>
+	</array>
+	<key>CreationDate</key>
+	<date>2015-07-08T20:27:14Z</date>
+	<key>Platform</key>
+	<array>
+		<string>iOS</string>
+	</array>
+	<key>DeveloperCertificates</key>
+	<array>
+    <data>
+      MIIDSzCCAjOgAwIBAgIBATANBgkqhkiG9w0BAQsFADBTMSAwHgYDVQQDDBdCdWNrIFRlc3QgQ29kZXNp
+      Z24gQ2VydDELMAkGA1UEBhMCVVMxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wHhcN
+      MTUxMDIzMjAwNzI1WhcNMzIwMzI3MjAwNzI1WjBTMSAwHgYDVQQDDBdCdWNrIFRlc3QgQ29kZXNpZ24g
+      Q2VydDELMAkGA1UEBhMCVVMxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wggEiMA0G
+      CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrmmMdeV17d72ihmdbB0MTn5v3iu9LSGVYlbnJbI+FNmDJ
+      1U/0PAR7aLIPux0puN3N1Rob5VMdSZCG+SvsjV5zUNyepiRYlhf1jMyYTGDuoF8EOtfE94w9kr1EH9gl
+      aKRqir4770oXrFywbOaDO1iLPkpiVnfKVkkoU4dM0UD3YEtXoM70LIpYouGtVvNyc0Sx9/emvyiMH3iA
+      yQz5erVdfJQ2O85eyXz+U6rrcsNQpE0AuyQNnBnm0irSvtvnoPxlCsf0EbLnmnkDlv8yTrgCxzj/jmys
+      0zs+EZFAjYCX/I2ef63Ll+Wm7ilh7CjwNaRMIQmL0QpJIR9kUYnp3v33AgMBAAGjKjAoMA4GA1UdDwEB
+      /wQEAwIHgDAWBgNVHSUBAf8EDDAKBggrBgEFBQcDAzANBgkqhkiG9w0BAQsFAAOCAQEATpWzY5IXhyb4
+      PXiRS64Q6Sh2YXj6Dot2srWC+FJwWngGbF6J8aQfoymsRTkgTa+69WinMefmdRkEzysmXvAUfD1iWpBX
+      jRREQXkUhmt2FwqKp8pWbYSlgOTaQMojQn3DdvDu8l5ZFIrU+8Z8X4g/aggvffoIOygHvhbwkcgrA6Lq
+      TziJssmKd56+QKfVfx52vg6pv1Ok03pmVsQ8semHTJr53juc4QutADhtJBXe9inVs1evosO15At0N731
+      Lz37Bzwedpu8DSEr4PIdwF5yBDRbQoyAF29zQaJgO/mU2G4i9wYTZJrj75BD/qr2ukjQOYOtz4IVNUuz
+      kPu+rDPz4A==
+    </data>
+	</array>
+	<key>Entitlements</key>
+	<dict>
+		<key>keychain-access-groups</key>
+		<array>
+			<string>ABCDE12345.*</string>
+		</array>
+		<key>get-task-allow</key>
+		<false/>
+		<key>application-identifier</key>
+		<string>ABCDE12345.com.example.TestApp</string>
+		<key>com.apple.security.application-groups</key>
+		<array>
+			<string>group.com.example</string>
+		</array>
+		<key>com.apple.developer.team-identifier</key>
+		<string>12345ABCDE</string>
+    <key>com.apple.developer.icloud-container-development-container-identifiers</key>
+    <array>
+      <string>iCloud.com.appleseedinc.MyProject</string>
+      <string>iCloud.com.appleseedinc.container1</string>
+    </array>
+	</dict>
+	<key>ExpirationDate</key>
+	<date>9999-03-05T01:33:40Z</date>
+	<key>Name</key>
+	<string>Example</string>
+	<key>ProvisionsAllDevices</key>
+	<true/>
+	<key>TeamIdentifier</key>
+	<array>
+		<string>12345ABCDE</string>
+	</array>
+	<key>TeamName</key>
+	<string>Example</string>
+	<key>TimeToLive</key>
+	<integer>240</integer>
+	<key>UUID</key>
+	<string>00000000-0000-0000-0000-000000000000</string>
+	<key>Version</key>
+	<integer>1</integer>
+</dict>
+</plist>
diff --git a/buck2/prelude/apple/tools/code_signing/test_resources/test1.plist b/buck2/prelude/apple/tools/code_signing/test_resources/test1.plist
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/test_resources/test1.plist
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>keychain-access-groups</key>
+	<array>
+		<string>ABCDE12345.com.example.TestApp</string>
+	</array>
+</dict>
+</plist>
diff --git a/buck2/prelude/apple/tools/code_signing/test_resources/test2.plist b/buck2/prelude/apple/tools/code_signing/test_resources/test2.plist
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/test_resources/test2.plist
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>application-identifier</key>
+	<string>ABCDE12345.com.example.TestApp</string>
+</dict>
+</plist>
diff --git a/buck2/prelude/apple/tools/code_signing/test_resources/test3.plist b/buck2/prelude/apple/tools/code_signing/test_resources/test3.plist
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/code_signing/test_resources/test3.plist
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>com.apple.developer.team-identifier</key>
+    <string>ABCDE12345</string>
+    <key>CFBundleIdentifier</key>
+    <string>com.example.TestApp</string>
+</dict>
+</plist>
diff --git a/buck2/prelude/apple/tools/codesign_manifest_tree_postprocessor/BUCK b/buck2/prelude/apple/tools/codesign_manifest_tree_postprocessor/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/codesign_manifest_tree_postprocessor/BUCK
@@ -0,0 +1,11 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("ios_devx")
+
+source_listing()
+
+python_binary(
+    name = "codesign_manifest_tree_postprocessor",
+    main = "main.py",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/apple/tools/codesign_manifest_tree_postprocessor/main.py b/buck2/prelude/apple/tools/codesign_manifest_tree_postprocessor/main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/codesign_manifest_tree_postprocessor/main.py
@@ -0,0 +1,97 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+import os
+from pathlib import Path
+
+
+def _extract_codesign_invocations_from_codesign_manifest_tree(
+    current_path, codesign_manifest_tree, invocations
+):
+    inner_manifests = codesign_manifest_tree.get("inner_codesign_manifests", {})
+    for inner_rel_path, inner_codesign_manifest_tree in inner_manifests.items():
+        inner_path = os.path.join(current_path, inner_rel_path)
+        # Process inner bundles first (i.e., inside out), as signing outer bundles
+        # requires inner bundles to have already been signed (otherwise the outer
+        # signature would be invalidated if the inner bundle is signed afterwards).
+        _extract_codesign_invocations_from_codesign_manifest_tree(
+            current_path=inner_path,
+            codesign_manifest_tree=inner_codesign_manifest_tree,
+            invocations=invocations,
+        )
+
+    codesign_manifest_path = codesign_manifest_tree.get("codesign_manifest")
+    if codesign_manifest_path:
+        with open(codesign_manifest_path, "r") as codesign_manifest_file:
+            codesign_manifest = json.load(codesign_manifest_file)
+            codesign_manifest_invocations = codesign_manifest.get("invocations", [])
+            for original_manifest_invocation in codesign_manifest_invocations:
+                original_invocation_path = original_manifest_invocation["path"]
+                updated_invocation_path = (
+                    os.path.join(current_path, original_invocation_path)
+                    if original_invocation_path != "."
+                    else current_path
+                )
+
+                updated_manifest_invocation = dict(original_manifest_invocation)
+                updated_manifest_invocation["path"] = updated_invocation_path
+
+                invocations.append(updated_manifest_invocation)
+
+
+def _args_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(
+        description="Tool which postprocesses a codesign manifest tree."
+    )
+    parser.add_argument(
+        "--codesign-manifest-tree",
+        metavar="<codesign_manifest_tree.json>",
+        type=Path,
+        required=True,
+        help="Path to the [codesign-manifest-tree] subtarget output.",
+    )
+    parser.add_argument(
+        "--output",
+        metavar="<output.json>",
+        type=Path,
+        required=True,
+        help="Path to the postprocessed file.",
+    )
+
+    return parser
+
+
+def _main() -> None:
+    args_parser = _args_parser()
+    args = args_parser.parse_args()
+
+    with open(args.codesign_manifest_tree, "r") as codesign_manifest_tree_file:
+        codesign_manifest_tree = json.load(codesign_manifest_tree_file)
+
+        invocations = []
+        _extract_codesign_invocations_from_codesign_manifest_tree(
+            current_path="",
+            codesign_manifest_tree=codesign_manifest_tree,
+            invocations=invocations,
+        )
+
+        with open(args.output, "w") as output_file:
+            json.dump(
+                {
+                    "version": 1,
+                    "invocations": invocations,
+                },
+                output_file,
+                indent=4,
+            )
+
+
+if __name__ == "__main__":
+    _main()
diff --git a/buck2/prelude/apple/tools/dedupe_swift_module_map.py b/buck2/prelude/apple/tools/dedupe_swift_module_map.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/dedupe_swift_module_map.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+
+
+def _dedupe_entries(entries: list) -> list:
+    # swiftc rejects an explicit module map with two entries for the same module
+    # name reached via distinct tset nodes. The dedup key is
+    # (moduleName, is_swiftmodule); in the projected JSON, swiftmodule entries
+    # have a modulePath field while clang pcm entries have a clangModulePath
+    # field, so the presence of modulePath reproduces is_swiftmodule exactly.
+    seen = set()
+    deduped = []
+    for entry in entries:
+        if "modulePath" in entry:
+            key = (entry["moduleName"], True)
+        elif "clangModulePath" in entry:
+            key = (entry["moduleName"], False)
+        else:
+            raise RuntimeError(f"Unrecognized module map entry: {entry}")
+
+        if key in seen:
+            continue
+        seen.add(key)
+        deduped.append(entry)
+
+    return deduped
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="De-duplicate entries in a Swift explicit module map."
+    )
+    parser.add_argument(
+        "--input",
+        required=True,
+        help="Path to the input Swift module map JSON.",
+    )
+    parser.add_argument(
+        "--output",
+        required=True,
+        help="Path to write the de-duplicated Swift module map JSON.",
+    )
+    args = parser.parse_args()
+
+    with open(args.input) as f:
+        entries = json.load(f)
+
+    deduped = _dedupe_entries(entries)
+
+    with open(args.output, "w") as f:
+        json.dump(deduped, f, indent=2)
+        f.write("\n")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/defs.bzl b/buck2/prelude/apple/tools/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/defs.bzl
@@ -0,0 +1,51 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# @oss-disable[end= ]: load("@fbsource//tools/build_defs:python_platform.bzl", "set_platform_decorator_for_python")
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load("@prelude//:native.bzl", _native = "native")
+
+set_platform_decorator_for_python = lambda **kwargs: kwargs # @oss-enable
+
+def meta_python_test(name, **kwargs):
+    # Set the platform attributes as needed for proper exec platform resolution
+    kwargs = set_platform_decorator_for_python(
+        # @oss-disable[end= ]: set_python_constraint_overrides = True,
+        **kwargs,
+    )
+
+    _native.python_test(name = name, **kwargs)
+
+_PYTHON_SCRUBBER = "prelude//apple/tools/selective_debugging:tool"
+_NATIVE_SCRUBBER = "prelude//apple/tools/meta_only/prebuilt_native_oso_scrubber:prebuilt_native_oso_scrubber"
+
+def apple_oso_scrubber_target():
+    if not is_full_meta_repo():
+        return _PYTHON_SCRUBBER
+
+    native_oso_scrubber_enabled_override = read_root_config("apple", "native_oso_scrubber_enabled_override", None)
+    if native_oso_scrubber_enabled_override != None:
+        # Override buckconfig takes precedence over everything else
+        native_oso_scrubber_enabled = native_oso_scrubber_enabled_override.lower() == "true"
+        return _NATIVE_SCRUBBER if native_oso_scrubber_enabled else _PYTHON_SCRUBBER
+
+    native_oso_scrubber_enabled = read_root_config("apple", "native_oso_scrubber_enabled", "").lower() == "true"
+    default_scrubber = _NATIVE_SCRUBBER if native_oso_scrubber_enabled else _PYTHON_SCRUBBER
+
+    return select({
+        "DEFAULT": default_scrubber,
+        "ovr_config//features/apple/constraints:native_oso_scrubber_disabled": _PYTHON_SCRUBBER,
+        "ovr_config//features/apple/constraints:native_oso_scrubber_enabled": _NATIVE_SCRUBBER,
+    })
+
+def bundle_telemetry_logger_target():
+    return read_root_config("apple", "bundle_telemetry_logger", None)
+
+def swiftmodule_change_analysis_target():
+    # Overridable via buckconfig either way.
+    return read_root_config("apple", "swiftmodule_change_analysis", None)
diff --git a/buck2/prelude/apple/tools/distributed_thin_lto/BUCK b/buck2/prelude/apple/tools/distributed_thin_lto/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/distributed_thin_lto/BUCK
@@ -0,0 +1,36 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("ios_pika")
+
+source_listing()
+
+cxx_binary(
+    name = "native_dist_lto_planner",
+    srcs = [
+        "dist_lto_planner.cpp",
+    ],
+    compiler_flags = [
+        "-Wno-deprecated-declarations",
+        "-O2",
+    ],
+    linker_flags = [
+        "-lc",
+    ],
+    tests = [
+        "fbsource//xplat/buck2/tests/apple/rules/dist_lto:main-alias-iphonesimulator-arm64-pika-fat-lld-platform-distributed-thin-lto",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "fbcode//common/files:files",
+        "fbcode//folly:file_util",
+        "fbcode//folly:json",
+        "fbcode//folly:subprocess",
+        "fbcode//folly/coro:blocking_wait",
+        "fbcode//folly/coro:collect",
+        "fbcode//folly/coro:shared_mutex",
+        "fbcode//folly/coro:task",
+        "fbcode//folly/executors:global_executor",
+        "fbcode//folly/executors:io_thread_pool_executor",
+        "fbcode//folly/init:init",
+    ],
+)
diff --git a/buck2/prelude/apple/tools/distributed_thin_lto/dist_lto_planner.cpp b/buck2/prelude/apple/tools/distributed_thin_lto/dist_lto_planner.cpp
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/distributed_thin_lto/dist_lto_planner.cpp
@@ -0,0 +1,468 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+#include <folly/DynamicConverter.h>
+#include <folly/Subprocess.h>
+#include <folly/coro/BlockingWait.h>
+#include <folly/coro/Collect.h>
+#include <folly/coro/SharedMutex.h>
+#include <folly/coro/Task.h>
+#include <folly/executors/GlobalExecutor.h>
+#include <folly/executors/IOThreadPoolExecutor.h>
+#include <folly/init/Init.h>
+#include <folly/json.h>
+#include <string.h>
+#include <algorithm>
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <memory>
+#include <optional>
+#include <sstream>
+#include <string>
+#include <vector>
+#include "common/files/FileUtil.h"
+
+namespace {
+
+static std::string metaFileInputPath;
+static std::string indexFileOutputPath;
+static std::string linkPlanFileOutputPath;
+static bool enablePreMerger = false;
+static bool dumpLinkerInvocation = false;
+static std::vector<std::string> linkerInvocationCommand;
+folly::coro::SharedMutex absorbedBitcodeFilesMutex;
+folly::coro::SharedMutex nonLTOObjectFilesMutex;
+
+struct ObjectFileRecord {
+  const std::string inputObjectFilePath;
+  const int starlarkArrayIndex;
+  const std::string outputPlanFilePath;
+  const std::string outputIndexShardFilePath;
+  const std::optional<std::string> outputPremergedBitcodeFilePath;
+
+  ObjectFileRecord(
+      const std::string& inputObjectFilePath,
+      const std::string& outputIndexShardFilePath,
+      const std::string& outputPremergedBitcodeFilePath,
+      const std::string& outputPlanFilePath,
+      const int starlarkArrayIndex)
+      : inputObjectFilePath(inputObjectFilePath),
+        starlarkArrayIndex(starlarkArrayIndex),
+        outputPlanFilePath(outputPlanFilePath),
+        outputIndexShardFilePath(outputIndexShardFilePath),
+        outputPremergedBitcodeFilePath(outputPremergedBitcodeFilePath) {}
+};
+
+enum class BitcodeMergeState {
+  Standalone,
+  Absorbed,
+  Root,
+  NotLoaded,
+};
+
+static const folly::json::serialization_opts jsonSerializationOptions = []() {
+  folly::json::serialization_opts sorted;
+  sorted.sort_keys = true;
+  return sorted;
+}();
+
+static void parseArgs(int argc, char** argv) {
+  int position = 1;
+  const auto boundsCheckFlag = [&](const std::string& flag) {
+    if (position + 1 >= argc) {
+      std::cerr << "Missing argument for flag: " << flag << std::endl;
+      std::abort();
+    }
+  };
+
+  while (position < argc) {
+    if (strcmp(argv[position], "--meta") == 0) {
+      boundsCheckFlag("--meta");
+      metaFileInputPath = argv[position + 1];
+      position += 2;
+    } else if (strcmp(argv[position], "--index") == 0) {
+      boundsCheckFlag("--index");
+      indexFileOutputPath = argv[position + 1];
+      position += 2;
+    } else if (strcmp(argv[position], "--link-plan") == 0) {
+      boundsCheckFlag("--link-plan");
+      linkPlanFileOutputPath = argv[position + 1];
+      position += 2;
+    } else if (strcmp(argv[position], "--enable-premerger") == 0) {
+      enablePreMerger = true;
+      position += 1;
+    } else if (strcmp(argv[position], "--dump-linker-invocation") == 0) {
+      dumpLinkerInvocation = true;
+      position += 1;
+    } else if (strcmp(argv[position], "--") == 0) {
+      for (position++; position < argc; position++) {
+        linkerInvocationCommand.emplace_back(argv[position]);
+      }
+    } else {
+      std::cerr << "Could not recognize argument: " << argv[position]
+                << std::endl;
+      std::abort();
+    }
+  }
+}
+
+enum class MetaFileRecordType {
+  ArchiveMember,
+  ObjectFile,
+};
+
+constexpr std::string_view MERGED_BITCODE_SUFFIX = ".merged.bc";
+constexpr std::string_view SUMMARY_SHARD_SUFFIX = ".thinlto.bc";
+constexpr std::string_view IMPORTS_FILE_SUFFIX = ".imports";
+
+using ObjectFileRecordsMapTy =
+    std::unordered_map<std::string, std::shared_ptr<const ObjectFileRecord>>;
+
+static void parseMetaFileRecords(ObjectFileRecordsMapTy& objectFileRecordsMap) {
+  std::ifstream metaFile(metaFileInputPath);
+  if (!metaFile.is_open()) {
+    std::cerr << "Failed to open file: " << metaFileInputPath << std::endl;
+    std::abort();
+  }
+  std::stringstream buffer;
+  buffer << metaFile.rdbuf();
+  try {
+    auto jsonData = folly::parseJson(buffer.str());
+    for (const auto& record : jsonData) {
+      const std::string emptyString;
+      const std::string outputPremergedBitcodeFilePath = enablePreMerger
+          ? record["output_premerged_bitcode_file_path"].getString()
+          : emptyString;
+      std::shared_ptr<const ObjectFileRecord> parsedObjectFileRecord =
+          std::make_shared<ObjectFileRecord>(
+              record["input_object_file_path"].getString(),
+              record["output_index_shard_file_path"].getString(),
+              outputPremergedBitcodeFilePath,
+              record["output_plan_file_path"].getString(),
+              record["starlark_array_index"].getInt());
+      objectFileRecordsMap[parsedObjectFileRecord->inputObjectFilePath] =
+          parsedObjectFileRecord;
+    }
+  } catch (const folly::json::parse_error& e) {
+    std::cerr << "Error parsing JSON: " << e.what() << std::endl;
+    std::abort();
+  }
+}
+
+static void populatePreMergerPathConversionMaps(
+    const ObjectFileRecordsMapTy& objectFileRecordsMap,
+    std::unordered_map<std::string, std::string>& preMergeToPostMerge,
+    std::unordered_map<std::string, std::string>& postMergeToPreMerge) {
+  for (const auto& [preMergePath, objectFileRecord] : objectFileRecordsMap) {
+    std::string postMergePath;
+    postMergePath = objectFileRecord->outputPremergedBitcodeFilePath.value();
+    preMergeToPostMerge[preMergePath] = postMergePath;
+    postMergeToPreMerge[postMergePath] = preMergePath;
+  }
+}
+
+static void runThinLink(
+    const std::unordered_map<std::string, std::string>& preMergeToPostMerge) {
+  if (enablePreMerger) {
+    // Buck requires actions write output files to a location set by the build
+    // system.  When toolchain binaries cannot for whatever reason easily
+    // produce output files at known locations configurable locations, the usual
+    // approach is to use a wrapper Python script such as this one to place the
+    // files at the locations buck expects.  In this case, this will not work as
+    // sharded summaries embed paths to other bitcode files within the bitcode.
+    // That means the toolchain must write the merged bitcode files to locations
+    // buck expects in the first place. This json document is parsed by the
+    // linker and communicates the locations at which the toolchain must write
+    // the merged bitcode files.
+    facebook::files::TemporaryFile preMergerOutputFileMappingFile(
+        nullptr, "premergerOutputMap", /* keep */ true);
+    std::ofstream stream(preMergerOutputFileMappingFile.filename());
+    stream << folly::toJson(folly::toDynamic(preMergeToPostMerge));
+    stream.flush();
+    std::string preMergerMapFlag = "-Wl,-mllvm,-premerger-output-map=";
+    preMergerMapFlag += preMergerOutputFileMappingFile.filename();
+    linkerInvocationCommand.push_back((preMergerMapFlag));
+  }
+
+  if (dumpLinkerInvocation) {
+    for (const auto& argument : linkerInvocationCommand) {
+      std::cout << argument << " ";
+    }
+    std::cout << "\n";
+    return;
+  }
+
+  folly::Subprocess subprocess(
+      linkerInvocationCommand, folly::Subprocess::Options().usePath());
+  subprocess.waitChecked();
+}
+
+static std::filesystem::path thinLTOPrefixReplacedPath(
+    const std::filesystem::path& path) {
+  // The linker is passed --thinlto-prefix-replace=";<indexFileOutPath>" which
+  // instructs the linker to prefix various paths with the value of
+  // <indexFileOutPath>.
+  return std::filesystem::path(indexFileOutputPath) / path;
+}
+
+static std::unordered_map<std::string, uint> parseLoadedObjectFiles() {
+  std::unordered_map<std::string, uint> loadedObjectFilesPositions;
+  std::ifstream stream(thinLTOPrefixReplacedPath("index.full"));
+  std::string line;
+  uint position = 0;
+  while (std::getline(stream, line)) {
+    // Paths to bitcode files will be prefixed with the argument to
+    // --thinlto-prefix-replace, so we need to remove that prefix first to get a
+    // normalized path.
+    if (line.size() >= indexFileOutputPath.size() &&
+        line.substr(0, indexFileOutputPath.size()) == indexFileOutputPath) {
+      std::string normalizedPath = line.substr(indexFileOutputPath.size() + 1);
+      loadedObjectFilesPositions[normalizedPath] = position;
+    } else {
+      loadedObjectFilesPositions[line] = position;
+    }
+    position++;
+  }
+  return loadedObjectFilesPositions;
+}
+
+static const std::vector<std::string> readImportsFile(
+    const std::string& importsFilePath,
+    const std::unordered_map<std::string, std::string>& postMergeToPreMerge) {
+  std::ifstream stream(importsFilePath);
+  std::string line;
+  std::vector<std::string> imports;
+  while (std::getline(stream, line)) {
+    if (enablePreMerger) {
+      if (line.ends_with(MERGED_BITCODE_SUFFIX)) {
+        imports.push_back(postMergeToPreMerge.at(line));
+      } else {
+        imports.push_back(line);
+      }
+    } else {
+      imports.push_back(line);
+    }
+  }
+  return imports;
+}
+
+static std::string getBitcodeMergeStateSpelling(const BitcodeMergeState state) {
+  switch (state) {
+    case BitcodeMergeState::Standalone:
+      return "STANDALONE";
+    case BitcodeMergeState::Absorbed:
+      return "ABSORBED";
+    case BitcodeMergeState::Root:
+      return "ROOT";
+    case BitcodeMergeState::NotLoaded:
+      return "NOT_LOADED";
+  }
+}
+
+static bool isFileLLVMBitcodeWrapperFile(const std::string& filePath) {
+  const uint32_t LLVM_BITCODE_WRAPPER_FILE_MAGIC = 0xB17C0DE;
+  std::ifstream stream(filePath, std::ios::binary);
+  uint32_t magic;
+  char buffer[sizeof(magic)];
+  if (stream.read(buffer, sizeof(magic))) {
+    memcpy(&magic, buffer, sizeof(magic));
+    return magic == LLVM_BITCODE_WRAPPER_FILE_MAGIC;
+  } else {
+    std::cerr << "Failed to read magic number from file: " << filePath
+              << std::endl;
+    std::abort();
+  }
+}
+
+static BitcodeMergeState readMergedBitcodeFile(
+    const std::string& mergedBitcodePath) {
+  if (!std::filesystem::file_size(mergedBitcodePath)) {
+    return BitcodeMergeState::NotLoaded;
+  }
+
+  if (isFileLLVMBitcodeWrapperFile(mergedBitcodePath)) {
+    return BitcodeMergeState::Root;
+  }
+
+  std::ifstream stream(mergedBitcodePath);
+  std::string line;
+  while (std::getline(stream, line)) {
+    if (line == "standalone") {
+      return BitcodeMergeState::Standalone;
+    }
+    if (line == "absorbed") {
+      return BitcodeMergeState::Absorbed;
+    }
+  }
+
+  std::cerr << "Ill-formatted merged bitcode file: " << mergedBitcodePath
+            << std::endl;
+  std::abort();
+}
+
+static void writeObjectFileOptimizationPlanToJSONFile(
+    const std::vector<int>& objectFileImports,
+    const bool isBitcode,
+    const std::optional<BitcodeMergeState> bitcodeMergeState,
+    const bool loadedByLinker,
+    const std::string& outputPath,
+    const int finalLinkLinePosition) {
+  std::ofstream stream(outputPath);
+  folly::dynamic json = folly::dynamic::object();
+  json["imports"] = folly::toDynamic(objectFileImports);
+  json["is_bitcode"] = isBitcode;
+  if (bitcodeMergeState) {
+    json["merge_state"] =
+        getBitcodeMergeStateSpelling(bitcodeMergeState.value());
+  }
+  json["loaded_by_linker"] = loadedByLinker;
+  json["final_link_line_position"] = finalLinkLinePosition;
+  stream << folly::json::serialize(json, jsonSerializationOptions);
+}
+
+static void writeLinkPlan(std::vector<int>& nonLTOObjectFiles) {
+  std::ofstream stream(linkPlanFileOutputPath);
+  folly::dynamic json = folly::dynamic::object;
+  folly::dynamic nonLTOObjectsJson = folly::dynamic::object();
+  for (const auto starlarkIndex : nonLTOObjectFiles) {
+    nonLTOObjectsJson[std::to_string(starlarkIndex)] = 1;
+  }
+  json["non_lto_objects"] = nonLTOObjectsJson;
+  stream << folly::json::serialize(json, jsonSerializationOptions);
+}
+
+static folly::coro::Task<void> writeOptimizationPlanForObjectFile(
+    const std::string& inputObjectFilePath,
+    const ObjectFileRecord* objectFile,
+    const ObjectFileRecordsMapTy& objectFileRecordsMap,
+    const std::unordered_map<std::string, std::string>& postMergeToPreMerge,
+    const std::unordered_map<std::string, uint>& loadedObjectFilesPositions,
+    std::unordered_set<std::string>& absorbedBitcodeFiles,
+    std::vector<int>& nonLTOObjectFiles) {
+  co_await folly::coro::co_reschedule_on_current_executor;
+
+  std::filesystem::create_directories(
+      std::filesystem::path(objectFile->outputIndexShardFilePath)
+          .parent_path());
+
+  const std::string temporaryIndexShardFilePath =
+      thinLTOPrefixReplacedPath(objectFile->inputObjectFilePath)
+          .concat(SUMMARY_SHARD_SUFFIX);
+
+  const std::string importsFilePath =
+      thinLTOPrefixReplacedPath(objectFile->inputObjectFilePath)
+          .concat(IMPORTS_FILE_SUFFIX);
+
+  int finalLinkLinePosition = -1;
+  auto it = loadedObjectFilesPositions.find(inputObjectFilePath);
+  if (it != loadedObjectFilesPositions.end()) {
+    finalLinkLinePosition = it->second;
+  }
+
+  if (std::filesystem::exists(importsFilePath)) {
+    std::filesystem::rename(
+        temporaryIndexShardFilePath, objectFile->outputIndexShardFilePath);
+
+    const auto imports = readImportsFile(importsFilePath, postMergeToPreMerge);
+
+    std::vector<int> objectFileImports;
+    for (const auto& importPath : imports) {
+      const auto& objectFileRecord = objectFileRecordsMap.at(importPath);
+      objectFileImports.push_back(objectFileRecord->starlarkArrayIndex);
+    }
+
+    std::optional<BitcodeMergeState> bitcodeMergeState;
+    if (enablePreMerger) {
+      bitcodeMergeState = readMergedBitcodeFile(
+          objectFile->outputPremergedBitcodeFilePath.value());
+      if (bitcodeMergeState == BitcodeMergeState::Absorbed) {
+        co_await absorbedBitcodeFilesMutex.co_lock();
+        absorbedBitcodeFiles.insert(objectFile->inputObjectFilePath);
+        absorbedBitcodeFilesMutex.unlock();
+      }
+    }
+
+    writeObjectFileOptimizationPlanToJSONFile(
+        objectFileImports,
+        /* isBitcode */ true,
+        bitcodeMergeState,
+        /* loadedByLinker */
+        loadedObjectFilesPositions.contains(inputObjectFilePath),
+        objectFile->outputPlanFilePath,
+        finalLinkLinePosition);
+  } else {
+    co_await nonLTOObjectFilesMutex.co_lock();
+    nonLTOObjectFiles.push_back(objectFile->starlarkArrayIndex);
+    nonLTOObjectFilesMutex.unlock();
+    // The linker will not generate an index shard, or a merged bitcode file if
+    // the input is not bitcode. Buck still expects the output, so write empty
+    // files.
+    std::ofstream(objectFile->outputIndexShardFilePath).close();
+
+    if (enablePreMerger) {
+      std::ofstream(objectFile->outputPremergedBitcodeFilePath.value()).close();
+    }
+
+    writeObjectFileOptimizationPlanToJSONFile(
+        /* objectFileImports */ {},
+        /* isBitcode */ false,
+        // Native object files do no participate in bitcode merging
+        /* bitcodeMergeState */ std::nullopt,
+        loadedObjectFilesPositions.contains(inputObjectFilePath),
+        objectFile->outputPlanFilePath,
+        finalLinkLinePosition);
+  }
+  co_return;
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+  int fakeArgc = 1;
+  folly::Init init(&fakeArgc, &argv);
+  parseArgs(argc, argv);
+  ObjectFileRecordsMapTy objectFileRecordsMap;
+  parseMetaFileRecords(objectFileRecordsMap);
+  std::unordered_map<std::string, std::string> preMergeToPostMerge;
+  std::unordered_map<std::string, std::string> postMergeToPreMerge;
+  if (enablePreMerger) {
+    populatePreMergerPathConversionMaps(
+        objectFileRecordsMap, preMergeToPostMerge, postMergeToPreMerge);
+  }
+  runThinLink(preMergeToPostMerge);
+  if (dumpLinkerInvocation) {
+    return 0;
+  }
+
+  std::unordered_map<std::string, uint> loadedObjectFilesPositions =
+      parseLoadedObjectFiles();
+
+  std::unordered_set<std::string> absorbedBitcodeFiles;
+  std::vector<int> nonLTOObjectFiles;
+  std::vector<folly::coro::Task<void>> tasks;
+  for (const auto& [inputObjectFilePath, objectFileRecord] :
+       objectFileRecordsMap) {
+    tasks.push_back(writeOptimizationPlanForObjectFile(
+        inputObjectFilePath,
+        objectFileRecord.get(),
+        objectFileRecordsMap,
+        postMergeToPreMerge,
+        loadedObjectFilesPositions,
+        absorbedBitcodeFiles,
+        nonLTOObjectFiles));
+  }
+
+  folly::coro::blockingWait(co_withExecutor(
+      folly::getGlobalCPUExecutor(),
+      folly::coro::collectAllRange(std::move(tasks))));
+
+  writeLinkPlan(nonLTOObjectFiles);
+}
diff --git a/buck2/prelude/apple/tools/dry_codesign_tool.py b/buck2/prelude/apple/tools/dry_codesign_tool.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/dry_codesign_tool.py
@@ -0,0 +1,82 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import plistlib
+import shutil
+from pathlib import Path
+
+_CODE_SIGN_DRY_RUN_ARGS_FILE = "BUCK_code_sign_args.plist"
+_CODE_SIGN_DRY_RUN_ENTITLEMENTS_FILE = "BUCK_code_sign_entitlements.plist"
+
+
+def _args_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(
+        description="""
+            Tool which implements `DryCodeSignStep` class from buck1.
+            Instead of code signing the bundle it just creates a file named `BUCK_code_sign_args.plist` inside,
+             which contains all parameters needed to perform a deferred signing later.
+        """
+    )
+    parser.add_argument(
+        "root",
+        type=Path,
+    )
+    parser.add_argument(
+        "--entitlements",
+        metavar="<Entitlements.plist>",
+        type=Path,
+        required=False,
+        help="Path to file with entitlements to be used during code signing.",
+    )
+    parser.add_argument(
+        "--identity",
+        type=str,
+        required=True,
+    )
+    parser.add_argument(
+        "--subject-common-name",
+        type=str,
+        required=True,
+    )
+    parser.add_argument(
+        "--extra-paths-to-sign",
+        type=str,
+        nargs="*",
+    )
+
+    return parser
+
+
+def _main() -> None:
+    args = _args_parser().parse_args()
+    content = {
+        # This is always empty string if you check `DryCodeSignStep` class usages in buck1
+        "relative-path-to-sign": "",
+        "use-entitlements": args.entitlements is not None,
+        "debug-info": {
+            "identity": args.identity,
+            "subject-common-name": args.subject_common_name,
+        },
+    }
+    if args.extra_paths_to_sign:
+        content["extra-paths-to-sign"] = args.extra_paths_to_sign
+    with open(args.root / _CODE_SIGN_DRY_RUN_ARGS_FILE, "wb") as f:
+        # Do not sort to keep the ordering same as in buck1.
+        plistlib.dump(content, f, sort_keys=False, fmt=plistlib.FMT_XML)
+    if args.entitlements:
+        shutil.copy2(
+            args.entitlements,
+            args.root / _CODE_SIGN_DRY_RUN_ENTITLEMENTS_FILE,
+        )
+
+
+if __name__ == "__main__":
+    _main()
diff --git a/buck2/prelude/apple/tools/empty.c b/buck2/prelude/apple/tools/empty.c
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/empty.c
diff --git a/buck2/prelude/apple/tools/framework_sanitizer.py b/buck2/prelude/apple/tools/framework_sanitizer.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/framework_sanitizer.py
@@ -0,0 +1,72 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Removes files from a framework that are not necessary when distributing
+inside app bundles. Specifically Modules/* Headers/* and Documentation/*
+
+Example Usage:
+xcframework_sanitizer.py --input original/Foo.framework \
+--output output/Foo.framework 
+"""
+
+import argparse
+import os
+import re
+import shutil
+from pathlib import Path
+from typing import Callable, Iterable
+
+
+def _should_ignore(
+    framework_root: str,
+) -> Callable[[str, list[str]], Iterable[str]]:
+    prohibited: list[str] = ["Modules", "Headers", "Documentation"]
+
+    def _should_ignore_impl(root: str, contents: list[str]) -> Iterable[str]:
+        if re.sub(r"/Versions/[A-Z]", "", root) == framework_root:
+            return prohibited
+        return []
+
+    return _should_ignore_impl
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Prepare a framework for distribution by removing unnecessary files."
+    )
+
+    parser.add_argument("--input", required=True)
+    parser.add_argument("--output", required=True)
+    parser.add_argument("--replacement-binary")
+    args = parser.parse_args()
+
+    out_path = Path(args.output)
+
+    shutil.copytree(
+        args.input,
+        out_path,
+        symlinks=True,
+        dirs_exist_ok=False,
+        ignore=_should_ignore(args.input),
+    )
+
+    if args.replacement_binary:
+        framework_name = os.path.splitext(os.path.basename(out_path))[0]
+        # Use realpath() because for macOS versioned bundles
+        # we may need to follow a symlink:
+        framework_binary_path = os.path.realpath(out_path / framework_name)
+        os.chmod(framework_binary_path, 0o644)
+
+        shutil.copy(args.replacement_binary, framework_binary_path)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/index/BUCK b/buck2/prelude/apple/tools/index/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/index/BUCK
@@ -0,0 +1,27 @@
+load("@prelude//apple/tools:defs.bzl", "meta_python_test")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("apple_build_infra")
+
+source_listing()
+
+python_bootstrap_binary(
+    name = "merge_index_store",
+    main = "merge_index_store.py",
+    visibility = ["PUBLIC"],
+)
+
+python_bootstrap_library(
+    name = "merge_index_store_lib",
+    srcs = ["merge_index_store.py"],
+    tests = [":merge_index_store_tests"],
+    visibility = ["PUBLIC"],
+)
+
+meta_python_test(
+    name = "merge_index_store_tests",
+    srcs = [
+        "merge_index_store.py",
+        "merge_index_store_tests.py",
+    ],
+)
diff --git a/buck2/prelude/apple/tools/index/merge_index_store.py b/buck2/prelude/apple/tools/index/merge_index_store.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/index/merge_index_store.py
@@ -0,0 +1,102 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import os
+import subprocess
+import sys
+from argparse import Namespace
+from concurrent.futures import as_completed, ThreadPoolExecutor
+from pathlib import Path
+
+MAX_WORKERS = 8
+
+
+def parse_arguments() -> Namespace:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("-d", "--dest", type=str, required=True)
+    parser.add_argument("-s", "--sources", nargs="+", type=str, required=True)
+    return parser.parse_args()
+
+
+def merge_directory(source: str, destination: str) -> None:
+    if os.path.isdir(source):
+        print(f"Merging {source} to {destination}", file=sys.stderr)
+        if not source.endswith("/"):
+            source = source + "/"
+
+        # Each index store is a directory containing record and unit files.
+        #
+        # $ ls my_index_store
+        # v5/records/93/scope6_var.h-3KOUVOFGN7X93
+        # v5/records/93/ShareViewController.swift-336T0RUILP193
+        # v5/records/95/host_security.h-NRLXTM4VIC95
+        # v5/units/ShareViewController.swift-5TSSN9QOIJ15
+        #
+        # We want a single destination directory containing all the record and unit
+        # files from all the source directories.
+        #
+        # There's no built-in way to merge directories in buck. In Python, there is
+        # `shutil.copytree(source, dest, dirs_exist_ok=True)` but that overwrites
+        # files in the destination when there are multiple sources with the same
+        # file. That's slower.
+        #
+        # Instead, use rsync to merge the directories.
+        #
+        # Use `--no-owner` to ensure the files in the destination directory are
+        # owned by the current user, even if some of the input files were owned by
+        # root.
+        result = subprocess.run(
+            [
+                "rsync",
+                "-a",
+                "--ignore-existing",
+                "--no-owner",
+                "--no-group",
+                source,
+                destination,
+            ],
+            stderr=subprocess.PIPE,
+            text=True,
+        )
+        if result.returncode != 0:
+            raise Exception(
+                f"Failed to merge {source} to {destination}:\n\t{result.stderr}"
+            )
+    else:
+        raise Exception(f"Directory {source} does not exist or is not a directory")
+
+
+def main() -> None:
+    args = parse_arguments()
+    destination = args.dest
+
+    directories = []
+    for source in args.sources:
+        if source.startswith("@"):
+            with open(source[1:]) as f:
+                for line in f.readlines():
+                    directories.append(line.strip())
+        else:
+            directories.append(source)
+
+    Path(destination).mkdir(parents=True, exist_ok=True)
+
+    with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
+        futures = [
+            executor.submit(merge_directory, index_dir, destination)
+            for index_dir in directories
+        ]
+        for future in as_completed(futures):
+            future.result()  # This will raise any exceptions that occurred
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/index/merge_index_store_tests.py b/buck2/prelude/apple/tools/index/merge_index_store_tests.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/index/merge_index_store_tests.py
@@ -0,0 +1,69 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import subprocess
+import unittest
+from unittest.mock import MagicMock, patch
+
+from .merge_index_store import merge_directory, parse_arguments
+
+
+class TestMergeIndexStore(unittest.TestCase):
+    def test_parse_arguments(self) -> None:
+        test_args = ["-d", "destination", "-s", "source1", "source2"]
+        with patch("sys.argv", ["script"] + test_args):
+            args = parse_arguments()
+            self.assertEqual(args.dest, "destination")
+            self.assertEqual(args.sources, ["source1", "source2"])
+
+    @patch("os.path.isdir")
+    @patch("subprocess.run")
+    def test_merge_directories(
+        self, mock_run: MagicMock, mock_isdir: MagicMock
+    ) -> None:
+        mock_isdir.return_value = True
+        mock_run.return_value = MagicMock(returncode=0, stderr="")
+
+        merge_directory("source", "destination")
+        mock_run.assert_called_once_with(
+            [
+                "rsync",
+                "-a",
+                "--ignore-existing",
+                "--no-owner",
+                "--no-group",
+                "source/",
+                "destination",
+            ],
+            stderr=subprocess.PIPE,
+            text=True,
+        )
+
+    @patch("os.path.isdir")
+    @patch("subprocess.run")
+    def test_merge_directories_failure(
+        self, mock_run: MagicMock, mock_isdir: MagicMock
+    ) -> None:
+        mock_isdir.return_value = True
+        mock_run.return_value = MagicMock(returncode=1, stderr="Error")
+
+        with self.assertRaises(Exception) as context:
+            merge_directory("source", "destination")
+        self.assertTrue("Failed to merge" in str(context.exception))
+
+    @patch("os.path.isdir")
+    def test_merge_non_existing_directory(self, mock_isdir: MagicMock) -> None:
+        mock_isdir.return_value = False
+        with self.assertRaises(Exception) as context:
+            merge_directory("source", "destination")
+        self.assertTrue(
+            "Directory source does not exist or is not a directory"
+            in str(context.exception)
+        )
diff --git a/buck2/prelude/apple/tools/info_plist_processor/BUCK b/buck2/prelude/apple/tools/info_plist_processor/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/info_plist_processor/BUCK
@@ -0,0 +1,40 @@
+load("@prelude//apple/tools:defs.bzl", "meta_python_test")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+python_library(
+    name = "preprocess",
+    srcs = ["preprocess.py"],
+)
+
+meta_python_test(
+    name = "preprocess_test",
+    srcs = ["preprocess_test.py"],
+    deps = [":preprocess"],
+)
+
+python_library(
+    name = "process",
+    srcs = ["process.py"],
+    visibility = ["PUBLIC"],
+    deps = ["prelude//apple/tools:plistlib_utils"],
+)
+
+meta_python_test(
+    name = "process_test",
+    srcs = ["process_test.py"],
+    deps = [":process"],
+)
+
+python_binary(
+    name = "tool",
+    main = "main.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":preprocess",
+        ":process",
+    ],
+)
diff --git a/buck2/prelude/apple/tools/info_plist_processor/main.py b/buck2/prelude/apple/tools/info_plist_processor/main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/info_plist_processor/main.py
@@ -0,0 +1,194 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import io
+import plistlib
+from contextlib import ExitStack
+from enum import Enum
+from pathlib import Path
+
+from apple.tools.plistlib_utils import detect_format_and_load
+
+from .preprocess import preprocess
+from .process import process
+
+
+class _SubcommandName(str, Enum):
+    preprocess = "preprocess"
+    process = "process"
+
+
+def _create_preprocess_subparser(
+    subparsers: "argparse._SubParsersAction[argparse.ArgumentParser]",
+) -> None:
+    parser = subparsers.add_parser(
+        _SubcommandName.preprocess.value,
+        description="Sub-command to expand macro variables in parametrized Info.plist files. It's the Buck v2 equivalent of what `FindAndReplaceStep` and `InfoPlistSubstitution` do.",
+    )
+    parser.add_argument(
+        "--input",
+        metavar="<Input.plist>",
+        type=Path,
+        required=True,
+        help="Path to the input which is a .plist file ",
+    )
+    parser.add_argument(
+        "--output",
+        metavar="<Output.plist>",
+        type=Path,
+        required=True,
+        help="Path where the output, .plist with applied substitutions, should be written to",
+    )
+    parser.add_argument(
+        "--product-name",
+        metavar="<Product Name>",
+        type=str,
+        required=True,
+        help="Product name, the value of `apple_bundle().product_name` attribute to be used in substitutions",
+    )
+    parser.add_argument(
+        "--substitutions-json",
+        metavar="<Substitutions JSON File>",
+        type=Path,
+        help="JSON file containing substitutions mapping",
+    )
+    parser.add_argument(
+        "--enforce-minimum-os-plist-key",
+        metavar="<Minimum OS Version Key>",
+        type=str,
+        help="Key for minimum OS version that should not be present in the plist file",
+    )
+
+
+def _create_process_subparser(
+    subparsers: "argparse._SubParsersAction[argparse.ArgumentParser]",
+) -> None:
+    parser = subparsers.add_parser(
+        _SubcommandName.process.value,
+        description="Sub-command to do the final processing of the Info.plist before it's copied to the application bundle. It's the Buck v2 equivalent of what `PlistProcessStep` does in v1.",
+    )
+    parser.add_argument(
+        "--input",
+        metavar="<Input.plist>",
+        type=Path,
+        required=True,
+        help="Path to unprocessed .plist file",
+    )
+    parser.add_argument(
+        "--override-input",
+        metavar="<OverrideInput.plist>",
+        type=Path,
+        help="Path to the additional .plist file which should be merged into final result overriding keys present in unprocessed file or any other --additional-* argument.",
+    )
+    parser.add_argument(
+        "--additional-keys",
+        metavar="<AdditionalKeys.json>",
+        type=Path,
+        help="Path to .json file containing additional data which should be merged into the final result if keys are not yet present in unprocessed file.",
+    )
+    parser.add_argument(
+        "--override-keys",
+        metavar="<OverrideKeys.json>",
+        type=Path,
+        help="Path to .json file with additional data which should be merged into the final result overriding keys present in unprocessed file or any other --additional-* or --override-* argument.",
+    )
+    parser.add_argument(
+        "--output",
+        metavar="<Output.plist>",
+        type=Path,
+        required=True,
+        help="Path where processed .plist file should be placed",
+    )
+    parser.add_argument(
+        "--output-xml",
+        action="store_true",
+        help="Output as XML",
+    )
+    parser.add_argument(
+        "--mutations",
+        metavar="<Mutations.json>",
+        type=Path,
+        help="Path to .json file containing mutation operations to apply to the plist",
+    )
+
+
+def _parse_args() -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description="Tool to process Info.plist file before it is placed into the bundle. It's the Buck v2 equivalent of what `AppleInfoPlist` build rule from v1 does."
+    )
+    subparsers = parser.add_subparsers(dest="subcommand_name")
+    _create_preprocess_subparser(subparsers)
+    _create_process_subparser(subparsers)
+    return parser.parse_args()
+
+
+def main() -> None:
+    args = _parse_args()
+    if args.subcommand_name == _SubcommandName.preprocess:
+        with ExitStack() as stack:
+            with args.input.open(mode="rb") as binary_file:
+                plist_data = detect_format_and_load(binary_file)
+                xml_content = plistlib.dumps(plist_data, fmt=plistlib.FMT_XML).decode(
+                    "utf-8"
+                )
+                input_file = io.StringIO(xml_content)
+
+            output_file = stack.enter_context(args.output.open(mode="w"))
+            substitutions_json = (
+                stack.enter_context(args.substitutions_json.open(mode="r"))
+                if args.substitutions_json is not None
+                else None
+            )
+            preprocess(
+                input_file,
+                output_file,
+                substitutions_json,
+                args.product_name,
+                args.enforce_minimum_os_plist_key,
+            )
+    elif args.subcommand_name == _SubcommandName.process:
+        with ExitStack() as stack:
+            input_file = stack.enter_context(args.input.open(mode="rb"))
+            output_file = stack.enter_context(args.output.open(mode="wb"))
+            override_input = (
+                stack.enter_context(args.override_input.open(mode="rb"))
+                if args.override_input is not None
+                else None
+            )
+            additional_keys = (
+                stack.enter_context(args.additional_keys.open(mode="rb"))
+                if args.additional_keys is not None
+                else None
+            )
+            override_keys = (
+                stack.enter_context(args.override_keys.open(mode="rb"))
+                if args.override_keys is not None
+                else None
+            )
+            output_format = plistlib.FMT_XML if args.output_xml else plistlib.FMT_BINARY
+            mutations_file = (
+                stack.enter_context(args.mutations.open(mode="r"))
+                if args.mutations is not None
+                else None
+            )
+            process(
+                input_file=input_file,
+                output_file=output_file,
+                override_input_file=override_input,
+                additional_keys_file=additional_keys,
+                override_keys_file=override_keys,
+                output_format=output_format,
+                mutations_file=mutations_file,
+            )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/info_plist_processor/preprocess.py b/buck2/prelude/apple/tools/info_plist_processor/preprocess.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/info_plist_processor/preprocess.py
@@ -0,0 +1,99 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import json
+import re
+import sys
+from enum import Enum
+from typing import Optional, TextIO
+
+
+class _ReGroupName(str, Enum):
+    openparen = "openparen"
+    variable = "variable"
+    modifier = "modifier"
+    closeparen = "closeparen"
+
+    def __format__(self, spec):
+        return f"{self.value}"
+
+
+_re_string: str = "\\$(?P<{openparen}>[\\{{\\(])(?P<{variable}>[^\\}}\\):]+)(?::(?P<{modifier}>[^\\}}\\)]+))?(?P<{closeparen}>[\\}}\\)])".format(
+    openparen=_ReGroupName.openparen,
+    variable=_ReGroupName.variable,
+    modifier=_ReGroupName.modifier,
+    closeparen=_ReGroupName.closeparen,
+)
+
+
+def _make_substitution_dict(
+    substitutions_json_file: TextIO, product_name: str
+) -> dict[str, str]:
+    result = {
+        "EXECUTABLE_NAME": product_name,
+        "PRODUCT_NAME": product_name,
+    }
+    if substitutions_json_file is not None:
+        # JSON file take precedence over default substitutions
+        result.update(json.load(substitutions_json_file))
+    return result
+
+
+def _process_line(
+    line: str,
+    pattern: re.Pattern[str],
+    substitutions: dict[str, str],
+    minimum_os_version_key: Optional[str],
+) -> str:
+    if (
+        minimum_os_version_key is not None
+        and line.strip() == f"<key>{minimum_os_version_key}</key>"
+    ):
+        print("Found minimum OS version key in plist file", file=sys.stderr)
+        sys.exit(1)
+
+    result = line
+    pos = 0
+    substituted_keys = set()
+    while True:
+        match = pattern.search(result, pos)
+        if match is None:
+            break
+        key = match.group(_ReGroupName.variable)
+        if key in substituted_keys:
+            raise RuntimeError(f"Recursive plist variable: ... -> {key} -> ...")
+        if key in substitutions:
+            result = (
+                result[: match.start()] + substitutions[key] + result[match.end() :]
+            )
+            substituted_keys.add(key)
+            # Keep the same position to handle the situation when variable was expanded into another variable
+            new_pos = match.start()
+        else:
+            new_pos = match.end()
+        if new_pos != pos:
+            substituted_keys = set()
+            pos = new_pos
+    return result
+
+
+def preprocess(
+    input_file: TextIO,
+    output_file: TextIO,
+    substitutions_file: TextIO,
+    product_name: str,
+    minimum_os_version_key: Optional[str] = None,
+) -> None:
+    pattern = re.compile(_re_string)
+    substitutions = _make_substitution_dict(substitutions_file, product_name)
+    for line in input_file:
+        output_file.write(
+            _process_line(line, pattern, substitutions, minimum_os_version_key)
+        )
diff --git a/buck2/prelude/apple/tools/info_plist_processor/preprocess_test.py b/buck2/prelude/apple/tools/info_plist_processor/preprocess_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/info_plist_processor/preprocess_test.py
@@ -0,0 +1,91 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import io
+import unittest
+
+from .preprocess import preprocess
+
+
+class TestPreprocess(unittest.TestCase):
+    def test_default_substitution_values(self):
+        input_file = io.StringIO(
+            r"""
+<string>${PRODUCT_NAME}</string>
+<string>${EXECUTABLE_NAME}</string>
+"""
+        )
+        expected = r"""
+<string>my_product_name</string>
+<string>my_product_name</string>
+"""
+        substitutions_file = io.StringIO(r"{}")
+        output_file = io.StringIO("")
+        preprocess(input_file, output_file, substitutions_file, "my_product_name")
+        self.assertEqual(output_file.getvalue(), expected)
+
+    def test_json_substitution_values_precede_default_ones(self):
+        input_file = io.StringIO(
+            r"""
+<string>${PRODUCT_NAME}</string>
+<string>${EXECUTABLE_NAME}</string>
+"""
+        )
+        expected = r"""
+<string>foo</string>
+<string>bar</string>
+"""
+        substitutions_file = io.StringIO(
+            r"""
+{
+    "PRODUCT_NAME": "foo",
+    "EXECUTABLE_NAME": "bar"
+}
+"""
+        )
+        output_file = io.StringIO("")
+        preprocess(input_file, output_file, substitutions_file, "my_product_name")
+        self.assertEqual(output_file.getvalue(), expected)
+
+    def test_chained_substitutions(self):
+        input_file = io.StringIO(r"<string>${foo}</string>")
+        expected = r"<string>baz</string>"
+        substitutions_file = io.StringIO(
+            r"""
+{
+    "foo": "${bar}",
+    "bar": "baz"
+}
+"""
+        )
+        output_file = io.StringIO("")
+        preprocess(input_file, output_file, substitutions_file, "my_product_name")
+        self.assertEqual(output_file.getvalue(), expected)
+
+    def test_recursive_substitutions_throws(self):
+        input_file = io.StringIO(r"<string>${foo}</string>")
+        substitutions_file = io.StringIO(
+            r"""
+{
+    "foo": "${bar}",
+    "bar": "${foo}"
+}
+"""
+        )
+        output_file = io.StringIO("")
+        with self.assertRaises(Exception) as context:
+            preprocess(input_file, output_file, substitutions_file, "my_product_name")
+        self.assertTrue("Recursive" in str(context.exception))
+
+    def test_variable_with_modifier(self):
+        input_file = io.StringIO(r"<string>${foo:modifier}</string>")
+        expected = r"<string>bar</string>"
+        substitutions_file = io.StringIO(r'{"foo":"bar"}')
+        output_file = io.StringIO("")
+        preprocess(input_file, output_file, substitutions_file, "my_product_name")
+        self.assertEqual(output_file.getvalue(), expected)
diff --git a/buck2/prelude/apple/tools/info_plist_processor/process.py b/buck2/prelude/apple/tools/info_plist_processor/process.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/info_plist_processor/process.py
@@ -0,0 +1,269 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import json
+import plistlib
+import sys
+from typing import Any, IO, Optional, TextIO
+
+from apple.tools.plistlib_utils import detect_format_and_load
+
+
+def _deepmerge_plist_dicts(source: dict[str, Any], destination: dict[str, Any]):
+    for key in source:
+        if key not in destination:
+            destination[key] = source[key]
+        elif isinstance(source[key], dict) and isinstance(destination[key], dict):
+            _deepmerge_plist_dicts(source[key], destination[key])
+        elif isinstance(source[key], list) and isinstance(destination[key], list):
+            for item in source[key]:
+                if item not in destination[key]:
+                    destination[key].append(item)
+        elif destination[key] == source[key]:
+            pass
+        else:
+            print(
+                f'Cannot merge value "{source[key]}" into "{destination[key]}" at "{key}"',
+                file=sys.stderr,
+            )
+            exit(3)
+
+
+# Corresponding v1 code is contained in `com/facebook/buck/apple/PlistProcessStep.java`, `PlistProcessStep::execute` method.
+def _merge_plist_dicts(
+    source: dict[str, Any],
+    destination: dict[str, Any],
+    override: bool = False,
+) -> None:
+    for key, value in source.items():
+        if key not in destination:
+            destination[key] = value
+        elif isinstance(value, dict) and isinstance(destination[key], dict):
+            destination[key].update(value)
+        elif override:
+            # override the value
+            destination[key] = value
+
+
+def _apply_merge(plist_data: dict[str, Any], merge_path: str) -> None:
+    """Apply a merge mutation to plist data."""
+    try:
+        # Load the plist file to merge
+        with open(merge_path, "rb") as merge_file:
+            merge_data = detect_format_and_load(merge_file)
+            # Merge the data into the main plist
+            _deepmerge_plist_dicts(
+                source=merge_data,
+                destination=plist_data,
+            )
+    except OSError:
+        # If the file can't be found or read, skip this merge operation
+        # This maintains compatibility with the current behavior
+        pass
+
+
+def _traverse_keypath(
+    plist_data: dict[str, Any],
+    keypath_str: str,
+    insert_arrays=True,
+) -> tuple[str | int, Any]:
+    """Return the internal object in plist_data found at the keypath_str, save
+    for the last component.
+
+    keypath_str is a key-value coding key path, extended to allow a numerical
+    element to index in an array. As a consequence, we can return an int or a
+    str for the last component.
+    """
+
+    keypath = keypath_str.split(".")
+    plist_pointer = plist_data
+
+    for key in keypath[:-1]:
+        if isinstance(plist_pointer, list):
+            found = False
+            for elem in plist_pointer:
+                if key in elem:
+                    plist_pointer = elem
+                    found = True
+                    break
+            if not found:
+                new_object = {key: []}
+                plist_pointer.append(new_object)
+                plist_pointer = new_object
+        if key.endswith("]"):
+            key, indexstr = key[:-1].split("[")
+            index = int(indexstr)
+            plist_pointer = plist_pointer[key][index]
+        else:
+            if key not in plist_pointer and insert_arrays:
+                plist_pointer[key] = []
+            plist_pointer = plist_pointer[key]
+    final_key = keypath[-1]
+    if final_key.endswith("]"):
+        key, indexstr = final_key[:-1].split("[")
+        plist_pointer = plist_pointer[key]
+        final_key = int(indexstr)
+
+    return final_key, plist_pointer
+
+
+def _apply_insert(plist_data: dict[str, Any], insert_params: dict[str, Any]) -> None:
+    """Apply an insert mutation to plist data.
+    Sample data:
+    <key>CFBundleURLTypes</key>
+        <array>
+                <dict>
+                        <key>CFBundleURLSchemes</key>
+                        <array>
+                                <string>spotify</string>
+                        </array>
+                </dict>
+                …
+        </array>
+    </key>
+
+    Sample mutation:
+    {"keypath": "CFBundleURLTypes.CFBundleURLSchemes", "value": "fb-messenger-public"}
+
+    Result:
+    <key>CFBundleURLTypes</key>
+        <array>
+                <dict>
+                        <key>CFBundleURLSchemes</key>
+                        <array>
+                                <string>spotify</string>
+                                <string>fb-messenger-public</string>
+                        </array>
+                </dict>
+                …
+        </array>
+    </key>
+    """
+    keypath = insert_params["keypath"]
+    value = insert_params["value"]
+    key, plist_pointer = _traverse_keypath(plist_data, keypath)
+
+    if isinstance(plist_pointer, list):
+        # e.g. See example above where CFBundleURLSchemes is contained in a
+        # list inside a dict.
+        found = False
+        for element in plist_pointer:
+            if key in element:
+                plist_pointer = element
+                found = True
+                break
+
+        if not found:
+            new_dict = {key: []}
+            plist_pointer.append(new_dict)
+            plist_pointer = new_dict
+
+    if not isinstance(plist_pointer, dict):
+        print(
+            f"Expected dictionary at keypath {keypath}, but found: {type(plist_pointer)}",
+            file=sys.stderr,
+        )
+        exit(3)
+    if key not in plist_pointer:
+        plist_pointer[key] = []
+    plist_pointer = plist_pointer[key]
+
+    if value not in plist_pointer:
+        plist_pointer.insert(0, value)
+
+
+def _apply_set(plist_data: dict[str, Any], set_params: dict[str, Any]) -> None:
+    """Apply a set mutation to plist data."""
+    keypath = set_params["keypath"]
+    value = set_params["value"]
+    key, plist_pointer = _traverse_keypath(plist_data, keypath)
+    plist_pointer[key] = value
+
+
+def _apply_copy(
+    plist_data: dict[str, Any], source_path: str, copy_params: list[str]
+) -> None:
+    """Copy an element from a source plist to the target plist"""
+    source_keypath = copy_params["source_keypath"]
+    target_keypath = copy_params["target_keypath"]
+    ignore_missing_source = copy_params.get("ignore_missing_source", False)
+    with open(source_path, "rb") as source_file:
+        source_data = detect_format_and_load(source_file)
+        target_key, target_element = _traverse_keypath(plist_data, target_keypath)
+        try:
+            source_key, source_element = _traverse_keypath(
+                source_data, source_keypath, insert_arrays=False
+            )
+            target_element[target_key] = source_element[source_key]
+        except (KeyError, IndexError) as e:
+            print(
+                f"source plist doesn't contain keypath {source_keypath} for copy",
+                file=sys.stderr,
+            )
+            if ignore_missing_source:
+                return
+            raise e
+
+
+def _apply_mutations(
+    plist_data: dict[str, Any], mutations: list[tuple[str, str] | tuple[str, dict]]
+) -> None:
+    """Apply a list of mutation operations to plist data."""
+    for mutation in mutations:
+        operation = mutation[0]
+        if operation == "merge":
+            _apply_merge(plist_data, mutation[1])
+        elif operation == "insert":
+            _apply_insert(plist_data, mutation[1])
+        elif operation == "set":
+            _apply_set(plist_data, mutation[1])
+        elif operation == "copy":
+            _apply_copy(plist_data, mutation[1], mutation[2])
+        else:
+            print(
+                f"Attempting to apply unknown plist mutation operation {operation}",
+                file=sys.stderr,
+            )
+            sys.exit(2)
+
+
+def process(
+    input_file: IO[bytes],
+    output_file: IO[bytes],
+    override_input_file: Optional[IO[bytes]] = None,
+    additional_keys: Optional[dict[str, Any]] = None,
+    additional_keys_file: Optional[TextIO] = None,
+    override_keys_file: Optional[TextIO] = None,
+    mutations_file: Optional[TextIO] = None,
+    output_format: plistlib.PlistFormat = plistlib.FMT_BINARY,
+) -> None:
+    root = detect_format_and_load(input_file)
+    if override_input_file is not None:
+        extra = detect_format_and_load(override_input_file)
+        # Overriding here for backwards compatibility with v1,
+        # see `PlistProcessStep::execute` implementation
+        _merge_plist_dicts(source=extra, destination=root, override=True)
+    if additional_keys is not None:
+        _merge_plist_dicts(source=additional_keys, destination=root)
+    if additional_keys_file is not None:
+        additional_keys_from_file = json.load(additional_keys_file)
+        _merge_plist_dicts(source=additional_keys_from_file, destination=root)
+    if override_keys_file is not None:
+        override_keys_from_file = json.load(override_keys_file)
+        _merge_plist_dicts(
+            source=override_keys_from_file, destination=root, override=True
+        )
+
+    # Apply mutations if provided
+    if mutations_file is not None:
+        mutations = [tuple(item) for item in json.load(mutations_file)]
+        _apply_mutations(root, mutations)
+
+    plistlib.dump(root, output_file, fmt=output_format)
diff --git a/buck2/prelude/apple/tools/info_plist_processor/process_test.py b/buck2/prelude/apple/tools/info_plist_processor/process_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/info_plist_processor/process_test.py
@@ -0,0 +1,464 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import io
+import plistlib
+import unittest
+
+from .process import _apply_insert, _apply_merge, _apply_set, process
+
+
+class TestProcess(unittest.TestCase):
+    def test_canary(self):
+        input_file = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>foo</key>
+    <string>bar</string>
+</dict>
+</plist>
+"""
+        )
+        output_file = io.BytesIO()
+        process(input_file, output_file)
+        self.assertTrue(len(output_file.getvalue()) > 0)
+
+    def test_additional_input_given_no_keys_conflict(self):
+        input_file = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>foo</key>
+    <string>bar</string>
+</dict>
+</plist>
+"""
+        )
+        override_input_file = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>baz</key>
+    <string>qux</string>
+</dict>
+</plist>
+"""
+        )
+        output_file = io.BytesIO()
+        process(input_file, output_file, override_input_file)
+        output_file.seek(0)
+        root = plistlib.load(output_file)
+        self.assertEqual(root, {"foo": "bar", "baz": "qux"})
+
+    def test_additional_input_given_keys_conflict(self):
+        input_file = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>foo</key>
+    <string>bar</string>
+    <key>qux</key>
+    <dict>
+        <key>a</key>
+        <string>b</string>
+        <key>b</key>
+        <string>c</string>
+    </dict>
+    <key>foobar</key>
+    <dict>
+        <key>hello</key>
+        <string>world</string>
+    </dict>
+</dict>
+</plist>
+"""
+        )
+        override_input_file = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>foo</key>
+    <string>baz</string>
+    <key>qux</key>
+    <dict>
+        <key>a</key>
+        <string>z</string>
+        <key>c</key>
+        <string>x</string>
+    </dict>
+    <key>foobar</key>
+    <string>zanzibar</string>
+</dict>
+</plist>
+"""
+        )
+        output_file = io.BytesIO()
+        process(input_file, output_file, override_input_file)
+        output_file.seek(0)
+        root = plistlib.load(output_file)
+        self.assertEqual(
+            root,
+            {"foo": "baz", "qux": {"a": "z", "b": "c", "c": "x"}, "foobar": "zanzibar"},
+        )
+
+    def test_additional_keys(self):
+        input_file = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>foo</key>
+    <string>bar</string>
+</dict>
+</plist>
+"""
+        )
+        additional_keys = {"baz": "qux"}
+        output_file = io.BytesIO()
+        process(input_file, output_file, additional_keys=additional_keys)
+        output_file.seek(0)
+        root = plistlib.load(output_file)
+        self.assertEqual(root, {"foo": "bar", "baz": "qux"})
+
+    def test_additional_keys_do_not_override(self):
+        input_file = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>foo</key>
+    <string>bar</string>
+</dict>
+</plist>
+"""
+        )
+        additional_keys = {"foo": "baz"}
+        output_file = io.BytesIO()
+        process(input_file, output_file, additional_keys=additional_keys)
+        output_file.seek(0)
+        root = plistlib.load(output_file)
+        self.assertEqual(root, {"foo": "bar"})
+
+    def test_additional_keys_from_file(self):
+        input_file = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>foo</key>
+    <string>bar</string>
+</dict>
+</plist>
+"""
+        )
+        additional_keys_file = io.BytesIO(b"""{"baz": "qux"}""")
+        output_file = io.BytesIO()
+        process(input_file, output_file, additional_keys_file=additional_keys_file)
+        output_file.seek(0)
+        root = plistlib.load(output_file)
+        self.assertEqual(root, {"foo": "bar", "baz": "qux"})
+
+    def test_override_keys_from_file(self):
+        input_file = io.BytesIO(
+            b"""<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+    <key>foo</key>
+    <string>bar</string>
+</dict>
+</plist>
+"""
+        )
+        override_keys_file = io.BytesIO(b"""{"foo": "baz"}""")
+        output_file = io.BytesIO()
+        process(input_file, output_file, override_keys_file=override_keys_file)
+        output_file.seek(0)
+        root = plistlib.load(output_file)
+        self.assertEqual(root, {"foo": "baz"})
+
+    def test_apply_set_string(self):
+        """Test _apply_set with a string value."""
+        plist_data = {"ExistingKey": "ExistingValue"}
+        set_params = {"keypath": "TestKey", "value": "TestValue"}
+        _apply_set(plist_data, set_params)
+        self.assertEqual(plist_data["TestKey"], "TestValue")
+        self.assertEqual(plist_data["ExistingKey"], "ExistingValue")
+
+    def test_apply_set_integer(self):
+        """Test _apply_set with an integer value."""
+        plist_data = {"ExistingKey": "ExistingValue"}
+        set_params = {"keypath": "TestKey", "value": 42}
+        _apply_set(plist_data, set_params)
+        self.assertEqual(plist_data["TestKey"], 42)
+        self.assertIsInstance(plist_data["TestKey"], int)
+
+    def test_apply_set_boolean(self):
+        """Test _apply_set with a boolean value."""
+        plist_data = {"ExistingKey": "ExistingValue"}
+        set_params = {"keypath": "TestKey", "value": True}
+        _apply_set(plist_data, set_params)
+        self.assertEqual(plist_data["TestKey"], True)
+        self.assertIsInstance(plist_data["TestKey"], bool)
+
+    def test_apply_set_override(self):
+        """Test _apply_set overriding an existing key."""
+        plist_data = {"TestKey": "OldValue"}
+        set_params = {"keypath": "TestKey", "value": "NewValue"}
+        _apply_set(plist_data, set_params)
+        self.assertEqual(plist_data["TestKey"], "NewValue")
+
+    def test_apply_insert_simple(self):
+        """Test _apply_insert with a simple list."""
+        plist_data = {"TestList": ["existing_value"]}
+        insert_params = {"keypath": "TestList", "value": "new_value"}
+        _apply_insert(plist_data, insert_params)
+        self.assertEqual(plist_data["TestList"], ["new_value", "existing_value"])
+
+    def test_apply_insert_create_list(self):
+        """Test _apply_insert creating a new list."""
+        plist_data = {}
+        insert_params = {"keypath": "NewList", "value": "new_value"}
+        _apply_insert(plist_data, insert_params)
+        self.assertEqual(plist_data["NewList"], ["new_value"])
+
+    def test_apply_insert_nested(self):
+        """Test _apply_insert with a nested list structure."""
+        plist_data = {"CFBundleURLTypes": [{"CFBundleURLSchemes": ["existing_scheme"]}]}
+        insert_params = {
+            "keypath": "CFBundleURLTypes.CFBundleURLSchemes",
+            "value": "new_scheme",
+        }
+        _apply_insert(plist_data, insert_params)
+        expected = {
+            "CFBundleURLTypes": [
+                {"CFBundleURLSchemes": ["new_scheme", "existing_scheme"]}
+            ]
+        }
+        self.assertEqual(plist_data, expected)
+
+    def test_apply_insert_nested_create(self):
+        """Test _apply_insert creating a nested structure."""
+        plist_data = {"CFBundleURLTypes": []}
+        insert_params = {
+            "keypath": "CFBundleURLTypes.CFBundleURLSchemes",
+            "value": "new_scheme",
+        }
+        _apply_insert(plist_data, insert_params)
+        expected = {"CFBundleURLTypes": [{"CFBundleURLSchemes": ["new_scheme"]}]}
+        self.assertEqual(plist_data, expected)
+
+    def test_apply_insert_with_type(self):
+        """Test _apply_insert with type conversion."""
+        plist_data = {"NumberList": []}
+        insert_params = {"keypath": "NumberList", "value": 42}
+        _apply_insert(plist_data, insert_params)
+        self.assertEqual(plist_data["NumberList"], [42])
+        self.assertIsInstance(plist_data["NumberList"][0], int)
+
+    def test_apply_merge(self):
+        """Test _apply_merge with a temporary file."""
+        import tempfile
+
+        # Create a temporary plist file to merge
+        with tempfile.NamedTemporaryFile(mode="wb", delete=False) as temp_file:
+            merge_data = {
+                "MergedKey": "MergedValue",
+                "NestedDict": {"SubKey2": "SubValue2"},
+                "MergedList": ["item1", "item2"],
+            }
+            plistlib.dump(merge_data, temp_file)
+            temp_path = temp_file.name
+
+        try:
+            # Test merging the file
+            plist_data = {
+                "ExistingKey": "ExistingValue",
+                "NestedDict": {
+                    "SubKey1": "OriginalValue",
+                    "ExistingSubKey": "KeepThis",
+                },
+                "MergedList": ["existing_item"],
+            }
+
+            _apply_merge(plist_data, temp_path)
+
+            # Verify the results
+            self.assertEqual(plist_data["MergedKey"], "MergedValue")
+            self.assertEqual(plist_data["ExistingKey"], "ExistingValue")
+
+            # Check deep merge of nested dictionary
+            self.assertEqual(plist_data["NestedDict"]["SubKey1"], "OriginalValue")
+            self.assertEqual(plist_data["NestedDict"]["SubKey2"], "SubValue2")
+            self.assertEqual(plist_data["NestedDict"]["ExistingSubKey"], "KeepThis")
+
+            # Check list merging
+            self.assertEqual(len(plist_data["MergedList"]), 3)
+            self.assertIn("item1", plist_data["MergedList"])
+            self.assertIn("item2", plist_data["MergedList"])
+            self.assertIn("existing_item", plist_data["MergedList"])
+        finally:
+            # Clean up the temporary file
+            import os
+
+            os.unlink(temp_path)
+
+    def test_apply_merge_nonexistent_file(self):
+        """Test _apply_merge with a nonexistent file (should not raise an error)."""
+        plist_data = {"ExistingKey": "ExistingValue"}
+        # This should not raise an exception
+        _apply_merge(plist_data, "/nonexistent/file/path.plist")
+        # Data should remain unchanged
+        self.assertEqual(plist_data, {"ExistingKey": "ExistingValue"})
+
+    def test_apply_merge_nested_list_of_dicts(self):
+        """Test _apply_merge with a nested list of dictionaries."""
+        import tempfile
+
+        # Create a temporary plist file to merge with nested list of dicts
+        with tempfile.NamedTemporaryFile(mode="wb", delete=False) as temp_file:
+            merge_data = {
+                "NestedListOfDicts": [
+                    {"SubKey1": "SubValue1", "SubKey2": "SubValue2"},
+                    {"SubKey3": "SubValue3"},
+                ]
+            }
+            plistlib.dump(merge_data, temp_file)
+            temp_path = temp_file.name
+
+        try:
+            # Test merging the file
+            plist_data = {
+                "NestedListOfDicts": [
+                    {"SubKey1": "OriginalValue", "UniqueKey": "KeepThis"},
+                    {"SubKey4": "SubValue4"},
+                ]
+            }
+
+            _apply_merge(plist_data, temp_path)
+
+            # Verify the results
+            self.assertEqual(len(plist_data["NestedListOfDicts"]), 4)
+
+            # Check that the original items are preserved
+            self.assertIn(
+                {"SubKey1": "OriginalValue", "UniqueKey": "KeepThis"},
+                plist_data["NestedListOfDicts"],
+            )
+            self.assertIn({"SubKey4": "SubValue4"}, plist_data["NestedListOfDicts"])
+
+            # Check that the new items are added
+            self.assertIn(
+                {"SubKey1": "SubValue1", "SubKey2": "SubValue2"},
+                plist_data["NestedListOfDicts"],
+            )
+            self.assertIn({"SubKey3": "SubValue3"}, plist_data["NestedListOfDicts"])
+        finally:
+            # Clean up the temporary file
+            import os
+
+            os.unlink(temp_path)
+
+    def test_apply_insert_complex_keypath(self):
+        """Test _apply_insert with a complex keypath including array indexing."""
+        # Create a non-trivial plist_data structure with nested dictionaries and arrays
+        plist_data = {
+            "Root": {
+                "Level1": [
+                    {"Name": "Item0", "Values": ["a", "b", "c"]},
+                    {"Name": "Item1", "Values": ["d", "e", "f"]},
+                    {"Name": "Item2", "Values": ["g", "h", "i"]},
+                    {
+                        "Name": "Item3",
+                        "Values": ["j", "k", "l"],
+                        "Nested": {
+                            "Config": [
+                                {"Type": "Type1", "Options": ["opt1", "opt2"]},
+                                {"Type": "Type2", "Options": ["opt3", "opt4"]},
+                            ]
+                        },
+                    },
+                ]
+            }
+        }
+
+        # Insert a new option at a complex keypath with array indexing
+        insert_params = {
+            "keypath": "Root.Level1[3].Nested.Config[1].Options",
+            "value": "new_option",
+        }
+        _apply_insert(plist_data, insert_params)
+
+        # Verify that the value was inserted at the correct location
+        expected_options = ["new_option", "opt3", "opt4"]
+        self.assertEqual(
+            plist_data["Root"]["Level1"][3]["Nested"]["Config"][1]["Options"],
+            expected_options,
+        )
+
+        # Verify that other parts of the structure remain unchanged
+        self.assertEqual(plist_data["Root"]["Level1"][0]["Name"], "Item0")
+        self.assertEqual(plist_data["Root"]["Level1"][3]["Values"], ["j", "k", "l"])
+        self.assertEqual(
+            plist_data["Root"]["Level1"][3]["Nested"]["Config"][0]["Options"],
+            ["opt1", "opt2"],
+        )
+
+    def test_apply_set_complex_keypath(self):
+        """Test _apply_set with a complex keypath including array indexing."""
+        # Create a non-trivial plist_data structure with nested dictionaries and arrays
+        plist_data = {
+            "Root": {
+                "Level1": [
+                    {"Name": "Item0", "Values": ["a", "b", "c"]},
+                    {"Name": "Item1", "Values": ["d", "e", "f"]},
+                    {"Name": "Item2", "Values": ["g", "h", "i"]},
+                    {
+                        "Name": "Item3",
+                        "Values": ["j", "k", "l"],
+                        "Nested": {
+                            "Config": [
+                                {"Type": "Type1", "Settings": {"Enabled": False}},
+                                {"Type": "Type2", "Settings": {"Enabled": False}},
+                            ]
+                        },
+                    },
+                ]
+            }
+        }
+
+        # Set a value at a complex keypath with array indexing
+        set_params = {
+            "keypath": "Root.Level1[3].Nested.Config[0].Settings.Enabled",
+            "value": True,
+        }
+        _apply_set(plist_data, set_params)
+
+        # Verify that the value was set at the correct location
+        self.assertEqual(
+            plist_data["Root"]["Level1"][3]["Nested"]["Config"][0]["Settings"][
+                "Enabled"
+            ],
+            True,
+        )
+
+        # Verify that other parts of the structure remain unchanged
+        self.assertEqual(plist_data["Root"]["Level1"][0]["Name"], "Item0")
+        self.assertEqual(plist_data["Root"]["Level1"][3]["Values"], ["j", "k", "l"])
+        self.assertEqual(
+            plist_data["Root"]["Level1"][3]["Nested"]["Config"][1]["Settings"][
+                "Enabled"
+            ],
+            False,
+        )
diff --git a/buck2/prelude/apple/tools/ipa_package_maker.py b/buck2/prelude/apple/tools/ipa_package_maker.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/ipa_package_maker.py
@@ -0,0 +1,113 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import os
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+
+from apple.tools.re_compatibility_utils.writable import make_dir_recursively_writable
+
+
+def _copy_ipa_contents(ipa_contents_dir: Path, output_dir: Path) -> None:
+    if os.path.exists(output_dir):
+        shutil.rmtree(output_dir, ignore_errors=False)
+    shutil.copytree(ipa_contents_dir, output_dir, symlinks=True, dirs_exist_ok=False)
+
+
+def _delete_empty_SwiftSupport_dir(output_dir: Path) -> None:
+    swiftSupportDir = output_dir / "SwiftSupport"
+    if not swiftSupportDir.exists():
+        return
+
+    swiftSupportDirHasFiles = False
+    for _, _, files in os.walk(swiftSupportDir):
+        if files:
+            swiftSupportDirHasFiles = True
+            break
+
+    if not swiftSupportDirHasFiles:
+        shutil.rmtree(swiftSupportDir)
+
+
+def _package_ipa_contents(
+    ipa_contents_dir: Path,
+    ipa_output_path: Path,
+    compression_level: int,
+) -> None:
+    with tempfile.TemporaryDirectory() as processed_package_dir:
+        processed_package_dir_path = Path(processed_package_dir)
+        _copy_ipa_contents(ipa_contents_dir, processed_package_dir_path)
+
+        # Apple requires SwiftSupport dir to be non-empty
+        _delete_empty_SwiftSupport_dir(processed_package_dir_path)
+
+        # Apple requires all executable files in an `.ipa` to be _writable_, otherwise App Store validation fails with:
+        #   "Asset validation failed (90711) Invalid executable permissions. The executable $X does not have its writable bit set."
+        # Furthermore, there's additional internal infra that needs certain files to be writable.
+        #
+        # In normal development outside Meta, all files in an .ipa will be user writable, so let's just the sensible thing
+        # and mirror behavior which Apple expects, so we're future-proof.
+        make_dir_recursively_writable(str(processed_package_dir_path))
+
+        with open(ipa_output_path, "wb") as ipa_file:
+            zip_cmd = [
+                "zip",
+                "-X",
+                "-n",
+                "zst",  # avoid deflating already compressed files
+                "-r",
+                f"-{compression_level}",
+                "-",
+                ".",
+            ]
+            subprocess.run(
+                zip_cmd,
+                # .ipa zip file requires to be created relative to the package dir,
+                # zip command has no way to express apart from changing cwd
+                cwd=processed_package_dir_path,
+                stdout=ipa_file,
+                check=True,
+            )
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(description="Tool to make an .ipa package file.")
+    parser.add_argument(
+        "--ipa-contents-dir",
+        required=True,
+        type=Path,
+        help="The directory which has the contents of the .ipa file.",
+    )
+    parser.add_argument(
+        "--ipa-output-path",
+        required=True,
+        type=Path,
+        help="The path to the output .ipa file.",
+    )
+    parser.add_argument(
+        "--compression-level",
+        type=int,
+        required=True,
+        help="The compression level to use for 'zip'.",
+    )
+
+    args = parser.parse_args()
+    _package_ipa_contents(
+        args.ipa_contents_dir,
+        args.ipa_output_path,
+        args.compression_level,
+    )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/make_modulemap.py b/buck2/prelude/apple/tools/make_modulemap.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/make_modulemap.py
@@ -0,0 +1,209 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import os
+import re
+from io import TextIOWrapper
+
+
+_RESERVED_KEYWORDS: frozenset[str] = frozenset(
+    [
+        "config_macros",
+        "conflict",
+        "exclude",
+        "explicit",
+        "extern",
+        "export_as",
+        "export",
+        "framework",
+        "header",
+        "link",
+        "module",
+        "private",
+        "requires",
+        "textual",
+        "umbrella",
+        "use",
+    ]
+)
+
+
+class Module:
+    def __init__(self, name: str, is_framework: bool) -> None:
+        self.name: str = name
+        self.headers: list[str] = []
+        self.submodules: dict[str, Module] = {}
+        self.is_framework: bool = is_framework
+
+    def add_header(self, src: str) -> None:
+        self.headers.append(src)
+
+    def get_submodule(self, name: str, is_framework: bool) -> "Module":
+        if name not in self.submodules:
+            self.submodules[name] = Module(name, is_framework)
+
+        return self.submodules[name]
+
+    def render(self, f: TextIOWrapper, indent: int = 0) -> None:
+        space = " " * indent
+        name = self.name
+        if name in _RESERVED_KEYWORDS:
+            name = f"{name}_"
+        if self.is_framework:
+            f.write(f"{space}framework module {name} {{\n")
+        else:
+            f.write(f"{space}module {name} {{\n")
+
+        submodule_names = set()
+        for submodule_name in sorted(self.submodules.keys()):
+            submodule = self.submodules[submodule_name]
+
+            # remove any extensions for readability
+            sanitized_name = os.path.splitext(submodule_name)[0]
+
+            # module names can only be ascii or _
+            sanitized_name = re.sub(r"[^A-Za-z0-9_]", "_", sanitized_name)
+            if sanitized_name[0].isdigit():
+                sanitized_name = "_" + sanitized_name
+
+            # avoid any collisions with other files
+            while sanitized_name in submodule_names:
+                sanitized_name += "_"
+
+            submodule_names.add(sanitized_name)
+            submodule.name = sanitized_name
+            submodule.render(f, indent + 4)
+
+        header_space = " " * (indent + 4)
+        for h in sorted(self.headers):
+            f.write(f'{header_space}header "{h}"\n')
+
+        if self.headers:
+            f.write(f"{header_space}export *\n")
+
+        f.write(f"{space}}}\n")
+
+
+def _write_single_module(
+    f: TextIOWrapper,
+    name: str,
+    headers: dict[str, str],
+    is_framework: bool,
+) -> None:
+    module = Module(name, is_framework)
+    for path in headers.values():
+        module.add_header(path)
+
+    module.render(f)
+
+
+def _write_submodules(
+    f: TextIOWrapper,
+    name: str,
+    headers: dict[str, str],
+    is_framework: bool,
+) -> None:
+    # Create a tree of nested modules, one for each path component.
+    root_module = Module(name, is_framework)
+    for include_path, disk_path in headers.items():
+        module = root_module
+        for i, component in enumerate(include_path.split(os.sep)):
+            if i == 0 and component == name:
+                # The common case is we have a single header path prefix that matches the module name.
+                # In this case we add the headers directly to the root module.
+                pass
+            else:
+                module = module.get_submodule(component, is_framework)
+
+        module.add_header(disk_path)
+
+    root_module.render(f)
+
+
+def _write_swift_header(f: TextIOWrapper, name: str, swift_header_path: str) -> None:
+    f.write(
+        f"""
+module {name}.Swift {{
+    header "{swift_header_path}"
+    requires objc
+}}
+"""
+    )
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--output", required=True, help="The path to write the modulemap to"
+    )
+    parser.add_argument("--name", required=True, help="The name of the module")
+    parser.add_argument(
+        "--swift-header", help="If this is a mixed module extend with this Swift header"
+    )
+    parser.add_argument(
+        "--use-submodules",
+        action="store_true",
+        help="If set produce a modulemap with per-header submodules",
+    )
+    parser.add_argument(
+        "--framework",
+        help="This modulemap is for embedding in a framework.",
+        action="store_true",
+    )
+    parser.add_argument(
+        "mappings",
+        nargs="*",
+        default=[],
+        help="A list of tuples of include path to disk paths",
+    )
+    args = parser.parse_args()
+
+    if len(args.mappings) % 2 != 0:
+        raise RuntimeError(
+            "Mappings must be a list of pairs of include path to disk path"
+        )
+
+    headers = {}
+    for i in range(0, len(args.mappings), 2):
+        path = args.mappings[i + 1]
+        if args.framework:
+            pass
+        else:
+            # We need to relativize the path to the modulemap file
+            path = os.path.relpath(path, os.path.dirname(args.output))
+
+        headers[args.mappings[i]] = path
+
+    with open(args.output, "w") as f:
+        if args.use_submodules:
+            _write_submodules(
+                f,
+                args.name,
+                headers,
+                args.framework,
+            )
+        else:
+            _write_single_module(
+                f,
+                args.name,
+                headers,
+                args.framework,
+            )
+
+        if args.swift_header:
+            _write_swift_header(
+                f,
+                args.name,
+                os.path.relpath(args.swift_header, os.path.dirname(args.output)),
+            )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/make_swift_comp_db.py b/buck2/prelude/apple/tools/make_swift_comp_db.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/make_swift_comp_db.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Utility to create Swift's compilation DBs
+
+$ make_swift_comp_db.py gen --output=entry.json foo.swift -- -I /path/ -Xcc -fno-implicit-modules
+"""
+
+import argparse
+import json
+import shlex
+import sys
+
+
+def gen(args):
+    with open(args.project_root_file, "r") as project_root_file:
+        project_root = project_root_file.read().replace("\n", "")
+
+    entry = {}
+    entry["files"] = list(args.files)
+    entry["directory"] = project_root
+
+    arguments = []
+    for arg in args.arguments:
+        if arg.startswith("@"):
+            with open(arg[1:]) as argsfile:
+                for line in argsfile:
+                    # The argsfile's arguments are separated by newlines; we
+                    # don't want those included in the argument list.
+                    arguments.append(" ".join(shlex.split(line)))
+        else:
+            arguments.append(arg)
+    entry["arguments"] = arguments
+
+    json.dump([entry], args.output, indent=2)
+    args.output.close()
+
+
+def main(argv):
+    parser = argparse.ArgumentParser()
+
+    parser.add_argument("--output", type=argparse.FileType("w"), default=sys.stdout)
+    parser.add_argument("--files", nargs="*")
+    # A path to a file that contains project root
+    parser.add_argument("--project-root-file")
+    parser.add_argument("arguments", nargs="*")
+
+    args = parser.parse_args(argv[1:])
+
+    gen(args)
+
+
+sys.exit(main(sys.argv))
diff --git a/buck2/prelude/apple/tools/make_swift_interface.py b/buck2/prelude/apple/tools/make_swift_interface.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/make_swift_interface.py
@@ -0,0 +1,290 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Remaps swiftc arguments to be usable by swift-ide-test, and invokes
+swift-ide-test with said arguments.
+"""
+
+import argparse
+import dataclasses
+import optparse
+import pathlib
+import subprocess as proc
+import sys
+from collections.abc import Iterable
+from contextlib import contextmanager
+from typing import Optional
+
+
+@dataclasses.dataclass
+class SwiftIDETestArguments:
+    sdk: Optional[str]
+    target: Optional[str]
+    xcc: Iterable[str]
+    defines: Iterable[str]
+    frameworks: Iterable[str]
+    includes: Iterable[str]
+    resource_dir: str
+    enable_cxx_interop: bool
+    cxx_interoperability_mode: Optional[str]
+    upcoming_features: Iterable[str]
+    explicit_swift_module_map: Optional[str]
+    swift_version: Optional[str]
+
+    def to_args(self) -> list[str]:
+        args = []
+        if self.target:
+            args.append("--target")
+            args.append(self.target)
+
+        if self.sdk:
+            args.append("--sdk")
+            args.append(self.sdk)
+
+        for define in self.defines:
+            args.append("-D")
+            args.append(define)
+
+        for include in self.includes:
+            args.append("-I")
+            args.append(include)
+
+        for framework in self.frameworks:
+            args.append("-F")
+            args.append(framework)
+
+        for xcc in self.xcc:
+            args.append("--Xcc")
+            args.append(xcc)
+
+        args.append("--resource-dir")
+        args.append(self.resource_dir)
+
+        if self.enable_cxx_interop:
+            args.append("-enable-experimental-cxx-interop")
+
+        if self.cxx_interoperability_mode:
+            # swift-ide-test only understands -enable-experimental-cxx-interop,
+            # not the versioned -cxx-interoperability-mode=.
+            args.append("-enable-experimental-cxx-interop")
+
+        if self.upcoming_features:
+            for feature in self.upcoming_features:
+                args.append("-enable-upcoming-feature")
+                args.append(feature)
+
+        if self.explicit_swift_module_map:
+            args.append("--explicit-swift-module-map-file")
+            args.append(self.explicit_swift_module_map)
+
+        if self.swift_version:
+            args.append("-swift-version")
+            args.append(self.swift_version)
+        return args
+
+
+class LongSingleDashOpt(optparse.Option):
+    """
+    This Option subclass allows for long arguments specified with single dashes,
+    e.g. -sdk (the default implementation only allows long options with two
+    dashes)
+    """
+
+    def _set_opt_strings(self, opts):
+        for opt in opts:
+            if len(opt) < 2:
+                raise optparse.OptionError(
+                    "invalid option string %r: "
+                    "must be at least two characters long" % opt,
+                    self,
+                )
+            elif len(opt) == 2:
+                self._short_opts.append(opt)
+            else:
+                self._long_opts.append(opt)
+
+
+class IgnoreUnknownLongSingleDashOptParser(optparse.OptionParser):
+    """
+    This OptionParser subclass allows for
+    (a) long arguments specified with single dashes (e.g. -sdk)
+    (b) ignoring unknown arguments
+    The default OptionParser doesn't have either of these behaviors.
+    """
+
+    def __init__(self, *args, **kwargs):
+        kwargs["option_class"] = LongSingleDashOpt
+        super().__init__(*args, **kwargs)
+
+    def _process_args(self, largs, rargs, values):
+        while rargs:
+            try:
+                arg = rargs[0]
+                if arg == "--":
+                    del rargs[0]
+                    return
+                elif arg[0:2] == "--":
+                    self._process_long_opt(rargs, values)
+                elif arg[:1] == "-" and len(arg) > 1:
+                    if len(arg) > 2:
+                        self._process_long_opt(rargs, values)
+                    else:
+                        self._process_short_opts(rargs, values)
+                elif self.allow_interspersed_args:
+                    largs.append(arg)
+                    del rargs[0]
+                else:
+                    return
+            except optparse.BadOptionError:
+                continue
+
+
+def parse_swiftc_args(arguments: list[str]) -> SwiftIDETestArguments:  # noqa: C901
+    """
+    We can't use argparse to do our parsing because arguments like -Xcc
+    need to accept arguments that are prefixed with `-`.
+
+    optparse can handle this, and it's only soft deprecated (i.e. it should
+    stay around, just not actively developed), so we should be safe to use it.
+
+    Additionally, our subclasses above are safe, since optparse is no longer
+    actively developed.
+    """
+    parser = IgnoreUnknownLongSingleDashOptParser()
+
+    parser.add_option("-sdk", dest="sdk")
+    parser.add_option("-target", dest="target")
+    parser.add_option("-Xcc", action="append", default=[], dest="xcc")
+    parser.add_option("-D", dest="defines", action="append", default=[])
+    parser.add_option("-F", dest="frameworks", action="append", default=[])
+    parser.add_option("-I", dest="includes", action="append", default=[])
+    parser.add_option("-resource-dir", dest="resource_dir")
+    parser.add_option(
+        "-enable-experimental-cxx-interop",
+        action="store_true",
+        default=False,
+        dest="enable_experimental_cxx_interop",
+    )
+    parser.add_option("-Xfrontend", action="append", default=[], dest="xfrontend")
+    parser.add_option("-swift-version", dest="swift_version")
+    parser.add_option("-cxx-interoperability-mode", dest="cxx_interoperability_mode")
+
+    options, leftovers = parser.parse_args(arguments)
+
+    frontend_parser = IgnoreUnknownLongSingleDashOptParser()
+    frontend_parser.add_option(
+        "-enable-upcoming-feature",
+        dest="enable_upcoming_feature",
+        action="append",
+        default=[],
+    )
+    frontend_parser.add_option(
+        "-explicit-swift-module-map-file", dest="explicit_swift_module_map"
+    )
+    frontend_options = frontend_parser.parse_args(options.xfrontend)[0]
+
+    resource_dir = options.resource_dir
+    if not resource_dir:
+        # If an explicit resource dir was not provided, we need to figure out
+        # which resource id would have been used, which, in the case of Xcode,
+        # is relative to the swiftc used.
+        assert len(leftovers) >= 1
+        compiler_path = pathlib.Path(leftovers[0])
+        assert compiler_path.name == "swiftc"
+        resource_dir_path = compiler_path.parents[1] / "lib" / "swift"
+        assert resource_dir_path.exists()
+        resource_dir = str(resource_dir_path)
+
+    return SwiftIDETestArguments(
+        options.sdk,
+        options.target,
+        options.xcc,
+        options.defines,
+        options.frameworks,
+        options.includes,
+        resource_dir,
+        options.enable_experimental_cxx_interop,
+        options.cxx_interoperability_mode,
+        frontend_options.enable_upcoming_feature,
+        frontend_options.explicit_swift_module_map,
+        options.swift_version,
+    )
+
+
+def parse_args() -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description="Uses swift-ide-test to generate a swift interface",
+        fromfile_prefix_chars="@",
+    )
+    parser.add_argument(
+        "--swift-ide-test-tool",
+        required=True,
+        help="Path to swift-ide-test binary.",
+    )
+    parser.add_argument(
+        "--module",
+        required=True,
+        help="Name of the module to generate the interface for.",
+    )
+    parser.add_argument(
+        "--out",
+        help="Path to output file.",
+        default="-",
+    )
+    parser.add_argument(
+        "arguments",
+        nargs="*",
+        default=[],
+        help="File containing compiler arguments to use to invoke"
+        + " swift-ide-test. Note these arguments should be in the format CC"
+        + " expects, not swift-ide-test, as this tool converts the arguments"
+        + " as needed",
+    )
+    return parser.parse_args()
+
+
+@contextmanager
+def open_or_stdout(out):
+    if out == "-":
+        yield sys.stdout
+    else:
+        with open(out, "w") as f:
+            yield f
+
+
+def main() -> None:
+    args = parse_args()
+
+    parsed = parse_swiftc_args(args.arguments)
+    with open_or_stdout(args.out) as out:
+        try:
+            proc.run(
+                [
+                    args.swift_ide_test_tool,
+                    "--source-filename=x",
+                    "--print-module",
+                    "--module-to-print",
+                    args.module,
+                    "--module-print-submodules",
+                ]
+                + parsed.to_args(),
+                stdout=out,
+                stderr=proc.PIPE,
+                check=True,
+                text=True,
+            )
+        except proc.CalledProcessError as exc:
+            print("swift-ide-test error:", file=sys.stderr)
+            sys.stderr.write(exc.stderr)
+            sys.exit(exc.returncode)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/make_vfsoverlay.py b/buck2/prelude/apple/tools/make_vfsoverlay.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/make_vfsoverlay.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import itertools
+import json
+import os
+from typing import TypedDict
+
+# Example VFS overlay in JSON format
+# ----------------------------------
+# {
+#   'version': 0,
+#   'roots': [
+#     { 'name': 'OUT_DIR', 'type': 'directory',
+#       'contents': [
+#         { 'name': 'module.map', 'type': 'file',
+#           'external-contents': 'INPUT_DIR/actual_module2.map'
+#         }
+#       ]
+#     }
+#   ]
+# }
+
+
+class OverlayRoot(TypedDict):
+    name: str
+    type: str
+    contents: list[dict[str, str]]
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--output", required=True, help="The path to write the VFS overlay to"
+    )
+    parser.add_argument(
+        "mappings", nargs="*", default=[], help="A list of virtual paths to real paths"
+    )
+    args = parser.parse_args()
+
+    if len(args.mappings) % 2 != 0:
+        parser.error("mappings must be dest-source pairs")
+
+    # Group the mappings by containing directory
+    mappings: dict[str, list[tuple[str, str]]] = {}
+    for src, dst in itertools.zip_longest(*([iter(args.mappings)] * 2)):
+        folder, basename = os.path.split(src)
+        mappings.setdefault(folder, []).append((basename, dst))
+
+    with open(args.output, "w") as f:
+        json.dump(
+            {
+                "version": 0,
+                "roots": _get_roots(mappings),
+            },
+            f,
+            sort_keys=True,
+            indent=4,
+        )
+        f.write("\n")
+        f.flush()
+
+
+def _get_roots(mappings: dict[str, list[tuple[str, str]]]) -> list[OverlayRoot]:
+    roots = []
+    for folder, file_maps in mappings.items():
+        contents = []
+        for src, dst in file_maps:
+            contents.append(
+                {
+                    "name": src,
+                    "type": "file",
+                    "external-contents": dst,
+                }
+            )
+
+        roots.append(
+            {
+                "name": folder,
+                "type": "directory",
+                "contents": contents,
+            }
+        )
+
+    return roots
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/plistlib_utils.py b/buck2/prelude/apple/tools/plistlib_utils.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/plistlib_utils.py
@@ -0,0 +1,32 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import plistlib
+from io import BytesIO
+from typing import Any, IO
+
+
+def _is_fmt_binary(header: bytes) -> bool:
+    return header[:8] == b"bplist00"
+
+
+def detect_format_and_load(fp: IO[bytes]) -> dict[str, Any]:
+    header = fp.read(32)
+    fp.seek(0)
+    if _is_fmt_binary(header):
+        fmt = plistlib.FMT_BINARY
+    else:
+        fmt = plistlib.FMT_XML
+    return plistlib.load(fp, fmt=fmt)
+
+
+def detect_format_and_loads(value: bytes) -> dict[str, Any]:
+    fp = BytesIO(value)
+    return detect_format_and_load(fp)
diff --git a/buck2/prelude/apple/tools/re_compatibility_utils/BUCK b/buck2/prelude/apple/tools/re_compatibility_utils/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/re_compatibility_utils/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_library(
+    name = "re_compatibility_utils",
+    srcs = [
+        "writable.py",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_library(
+    name = "bootstrap_re_compatibility_utils",
+    srcs = [
+        "writable.py",
+    ],
+    has_content_based_path = True,
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/apple/tools/re_compatibility_utils/writable.py b/buck2/prelude/apple/tools/re_compatibility_utils/writable.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/re_compatibility_utils/writable.py
@@ -0,0 +1,54 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import os
+import pathlib
+import platform
+import stat
+import sys
+
+
+def make_path_user_writable(path: str) -> None:
+    # On Linux, `os.chmod()` does not support setting the permissions on a symlink.
+    # `chmod` manpage says:
+    #   > AT_SYMLINK_NOFOLLOW     If pathname is a symbolic link, do not
+    #   >     dereference it: instead operate on the link itself.
+    #   >     This flag is not currently implemented.
+    #
+    # In Python, an exception will be thrown:
+    # > NotImplementedError: chmod: follow_symlinks unavailable on this platform
+    #
+    # Darwin supports permission setting on symlinks.
+    follow_symlinks = platform.system() != "Darwin"
+    st = os.stat(path, follow_symlinks=False)
+
+    try:
+        os.chmod(path, st.st_mode | stat.S_IWUSR, follow_symlinks=follow_symlinks)
+    except FileNotFoundError as e:
+        path_obj = pathlib.Path(path)
+        if path_obj.is_symlink():
+            resolved_path_obj = path_obj.resolve()
+            if not resolved_path_obj.exists():
+                # On Linux systems, all symlinks are followed when `chmod`-ing
+                # (see comment above about `AT_SYMLINK_NOFOLLOW`). If that happens,
+                # we can ignore the `chmod` error as its harmless.
+                print(
+                    f"Tried setting permission on a symlink to a non-existing path, ignoring error... {e}",
+                    file=sys.stderr,
+                )
+                return
+        raise e
+
+
+def make_dir_recursively_writable(dir: str) -> None:
+    for dirpath, _, filenames in os.walk(dir):
+        make_path_user_writable(dirpath)
+        for filename in filenames:
+            make_path_user_writable(os.path.join(dirpath, filename))
diff --git a/buck2/prelude/apple/tools/resource_broker/BUCK b/buck2/prelude/apple/tools/resource_broker/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/resource_broker/BUCK
@@ -0,0 +1,38 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+python_binary(
+    name = "resource_broker",
+    main = "main.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":main",
+    ],
+)
+
+python_library(
+    name = "main",
+    srcs = ["main.py"],
+    deps = [
+        ":lib",
+    ],
+)
+
+python_library(
+    name = "lib",
+    srcs = glob(
+        [
+            "*.py",
+        ],
+        exclude = [
+            "main.py",
+        ],
+    ),
+    deps = [
+        "fbsource//third-party/pypi/dataclasses-json:dataclasses-json",
+        "fbsource//third-party/pypi/packaging:packaging",
+    ],
+)
diff --git a/buck2/prelude/apple/tools/resource_broker/debug.py b/buck2/prelude/apple/tools/resource_broker/debug.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/resource_broker/debug.py
@@ -0,0 +1,31 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import os
+import shlex
+import sys
+
+REPLAY_ENVS_TO_REMOVE = [
+    "DUMP_REPLAY",
+]
+
+
+def debug_dump_replay() -> None:
+    if os.environ.get("DUMP_REPLAY") is None:
+        return
+    filtered_envs = dict(os.environ)
+    for env in REPLAY_ENVS_TO_REMOVE:
+        filtered_envs.pop(env, None)
+    envs = " ".join(
+        f"{key}={shlex.quote(value)}" for key, value in sorted(filtered_envs.items())
+    )
+    command = shlex.join(sys.argv)
+    replay_file = "/tmp/resource_broker_replay.sh"
+    with open(replay_file, "w") as f:
+        f.write(f"{envs} {command}\n")
+    os.chmod(replay_file, 0o755)
diff --git a/buck2/prelude/apple/tools/resource_broker/ios.py b/buck2/prelude/apple/tools/resource_broker/ios.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/resource_broker/ios.py
@@ -0,0 +1,319 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import os
+from dataclasses import dataclass
+from typing import Optional
+
+from packaging.version import Version
+
+from .simctl_runtime import list_runtimes, XCSimRuntime
+from .simulator import (
+    managed_simulators_list_from_stdout,
+    Simulator,
+    SimulatorInfo,
+    SimulatorState,
+    SimulatorType,
+)
+from .timeouts import SIMULATOR_BOOT_TIMEOUT
+from .utils import execute_generic_text_producing_command
+
+
+@dataclass(frozen=True)
+class SimulatorSpec:
+    device: str
+    os_version: str
+
+
+def _device_set_path() -> str:
+    return os.path.expanduser("~/Library/Developer/Buck2IdbDeviceSet")
+
+
+def _list_managed_simulators_command(simulator_manager: str) -> list[str]:
+    return [
+        simulator_manager,
+        "list",
+        "--device-set-path",
+        _device_set_path(),
+        "--only",
+        "simulator",
+    ]
+
+
+def _create_simulator_command(simulator_manager: str, sim_spec: str) -> list[str]:
+    return [
+        simulator_manager,
+        "create",
+        "--device-set-path",
+        _device_set_path(),
+        "--configuration",
+        sim_spec,
+    ]
+
+
+def _boot_simulator_command(simulator_manager: str, udid: str) -> list[str]:
+    return [
+        simulator_manager,
+        "boot",
+        "--device-set-path",
+        _device_set_path(),
+        udid,
+    ]
+
+
+def _compatible_device_type_from_runtime(
+    runtime: XCSimRuntime, simulator_type: SimulatorType, device: Optional[str]
+) -> Optional[str]:
+    device_types = list(runtime.supported_device_types)
+    device_types = [
+        device_type
+        for device_type in device_types
+        if simulator_type.matches_device_identifier(device_type.identifier)
+    ]
+    if device:
+        if device.startswith("com.apple."):
+            # filter by device type identifier
+            device_types = [
+                device_type
+                for device_type in device_types
+                if device_type.identifier == device
+            ]
+        else:
+            # filter by device name
+            device_types = [
+                device_type
+                for device_type in device_types
+                if device_type.name == device
+            ]
+    if not device_types:
+        return None
+    selected_device = next(
+        (
+            device_type.name
+            for device_type in device_types
+            if device_type.name == simulator_type.default_device()
+        ),
+        device_types[0].name,
+    )
+    return selected_device
+
+
+def _select_simulator_spec(
+    runtimes: list[XCSimRuntime],
+    simulator_type: SimulatorType,
+    os_version: Optional[str],
+    device: Optional[str],
+) -> SimulatorSpec:
+    runtimes = [
+        runtime
+        for runtime in runtimes
+        if any(
+            simulator_type.matches_device_identifier(device_type.identifier)
+            for device_type in runtime.supported_device_types
+        )
+    ]
+    runtimes.sort(key=lambda x: Version(x.version), reverse=True)
+
+    if os_version:
+        runtimes = [x for x in runtimes if x.name == os_version]
+    for runtime in runtimes:
+        device_type = _compatible_device_type_from_runtime(
+            runtime=runtime, simulator_type=simulator_type, device=device
+        )
+        if device_type:
+            return SimulatorSpec(device_type, f"{runtime.platform} {runtime.version}")
+    raise RuntimeError(
+        "No Xcode simctl compatible os runtime and device available. Try to `sudo xcode-select -s <path_to_xcode>` and *open Xcode to install all required components*."
+    )
+
+
+async def _generic_managed_simulators_list_command(
+    name: str, cmd: list[str]
+) -> list[Simulator]:
+    stdout = await execute_generic_text_producing_command(name=name, cmd=cmd)
+    return managed_simulators_list_from_stdout(stdout)
+
+
+async def _list_managed_simulators(simulator_manager: str) -> list[Simulator]:
+    list_cmd = _list_managed_simulators_command(simulator_manager=simulator_manager)
+    return await _generic_managed_simulators_list_command(
+        name="list managed simulators", cmd=list_cmd
+    )
+
+
+def normalize_os_version(os_version: str) -> Version:
+    # os version should be in the format "iOS 17.2.0" or "iOS 17.2"
+    return Version(os_version.split(" ")[1])
+
+
+def choose_simulators(
+    simulators: list[Simulator],
+    simulator_type: SimulatorType,
+    os_version: Optional[str],
+    device: Optional[str],
+) -> list[Simulator]:
+    # If no device or os_version is specified, filter by simulator type
+    if not device and not os_version:
+        simulators = list(
+            filter(
+                lambda s: (s.is_type(simulator_type)),
+                simulators,
+            )
+        )
+
+    # Check if device is a device type identifier
+    device_type_identifier: Optional[str] = None
+    if device is not None and device.startswith("com.apple."):
+        device_type_identifier = device
+        device = None
+
+    filtered_simulators = filter(
+        lambda simulator: (
+            (
+                normalize_os_version(simulator.os_version).major
+                == normalize_os_version(os_version).major
+                and normalize_os_version(simulator.os_version).minor
+                == normalize_os_version(os_version).minor
+                if os_version
+                else True
+            )
+            and (
+                simulator.device_type_identifier == device_type_identifier
+                if device_type_identifier is not None
+                else True
+            )
+            and (simulator.name == device if device is not None else True)
+        ),
+        simulators,
+    )
+
+    return list(filtered_simulators)
+
+
+async def _create_simulator(
+    simulator_manager: str,
+    simulator_type: SimulatorType,
+    os_version: Optional[str] = None,
+    device: Optional[str] = None,
+) -> None:
+    runtimes = await list_runtimes()
+    spec = _select_simulator_spec(runtimes, simulator_type, os_version, device)
+    spec_str = f"{spec.device},{spec.os_version}"
+    create_cmd = _create_simulator_command(
+        simulator_manager=simulator_manager, sim_spec=spec_str
+    )
+    await execute_generic_text_producing_command(
+        name="create simulators", cmd=create_cmd
+    )
+
+
+async def _get_managed_simulators_create_if_needed(
+    simulator_manager: str,
+    simulator_type: SimulatorType,
+    os_version: Optional[str] = None,
+    device: Optional[str] = None,
+) -> list[Simulator]:
+    managed_simulators = await _get_managed_simulators(
+        simulator_manager=simulator_manager,
+        simulator_type=simulator_type,
+        os_version=os_version,
+        device=device,
+    )
+    if managed_simulators:
+        return managed_simulators
+
+    await _create_simulator(
+        simulator_manager=simulator_manager,
+        simulator_type=simulator_type,
+        os_version=os_version,
+        device=device,
+    )
+    managed_simulators = await _get_managed_simulators(
+        simulator_manager=simulator_manager,
+        simulator_type=simulator_type,
+        os_version=os_version,
+        device=device,
+    )
+    if managed_simulators:
+        return managed_simulators
+
+    raise RuntimeError(
+        "Failed to create a simulator. Try to `sudo xcode-select -s <path_to_xcode>` and *open Xcode to install all required components*."
+    )
+
+
+async def _get_managed_simulators(
+    simulator_manager: str,
+    simulator_type: SimulatorType,
+    os_version: Optional[str] = None,
+    device: Optional[str] = None,
+) -> list[Simulator]:
+    managed_simulators = await _list_managed_simulators(
+        simulator_manager=simulator_manager
+    )
+    return choose_simulators(managed_simulators, simulator_type, os_version, device)
+
+
+def _select_simulator(
+    only_booted: bool, all_simulators: list[Simulator]
+) -> Optional[Simulator]:
+    return next(
+        filter(
+            lambda s: s.state == SimulatorState.booted if only_booted else True,
+            iter(all_simulators),
+        ),
+        None,
+    )
+
+
+def _select_simulator_with_preference(
+    prefer_booted: bool, all_simulators: list[Simulator]
+) -> Simulator:
+    simulator = _select_simulator(
+        only_booted=prefer_booted, all_simulators=all_simulators
+    )
+    if not simulator and prefer_booted:
+        simulator = _select_simulator(only_booted=False, all_simulators=all_simulators)
+    if not simulator:
+        raise RuntimeError("Expected at least unbooted simulator entity to be selected")
+    return simulator
+
+
+async def prepare_simulator(
+    simulator_manager: str,
+    simulator_type: SimulatorType,
+    os_version: Optional[str] = None,
+    device: Optional[str] = None,
+) -> SimulatorInfo:
+    managed_simulators = await _get_managed_simulators_create_if_needed(
+        simulator_manager=simulator_manager,
+        simulator_type=simulator_type,
+        os_version=os_version,
+        device=device,
+    )
+
+    simulator = _select_simulator_with_preference(
+        prefer_booted=simulator_type.booted(), all_simulators=managed_simulators
+    )
+
+    if simulator.state != SimulatorState.booted and simulator_type.booted():
+        boot_cmd = _boot_simulator_command(
+            simulator_manager=simulator_manager, udid=simulator.udid
+        )
+        await execute_generic_text_producing_command(
+            name="boot simulator",
+            cmd=boot_cmd,
+            timeout=SIMULATOR_BOOT_TIMEOUT,
+        )
+
+    return SimulatorInfo(
+        udid=simulator.udid,
+        device_set_path=_device_set_path(),
+    )
diff --git a/buck2/prelude/apple/tools/resource_broker/main.py b/buck2/prelude/apple/tools/resource_broker/main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/resource_broker/main.py
@@ -0,0 +1,84 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import asyncio
+import json
+import sys
+
+from .debug import debug_dump_replay
+from .ios import prepare_simulator
+from .simulator import SimulatorType
+
+
+def _args_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(
+        description="Utility to set up simulators which are used by buck to run tests locally."
+    )
+    parser.add_argument(
+        "--simulator-manager",
+        required=True,
+        type=str,
+        help="Tool to manage simulators and their lifecycle. Required.",
+    )
+    parser.add_argument(
+        "--type",
+        metavar="<TYPE>",
+        type=SimulatorType,
+        choices=[e.value for e in SimulatorType],
+        required=True,
+        help=f"""
+            Type of required resources.
+            Pass `{SimulatorType.iphoneUnbooted}` to get an unbooted iPhone simulator.
+            Pass `{SimulatorType.iphoneBooted}` to get a booted iPhone simulator.
+            Pass `{SimulatorType.ipad}` to get an iPad simulator.
+            Pass `{SimulatorType.watch}` to get an Apple Watch simulator.
+        """,
+    )
+    parser.add_argument(
+        "--os_version",
+        required=False,
+        type=str,
+        help="OS version to use for simulator",
+    )
+    parser.add_argument(
+        "--device",
+        required=False,
+        type=str,
+        help="Device to use for simulator",
+    )
+    return parser
+
+
+def main() -> None:
+    debug_dump_replay()
+    args = _args_parser().parse_args()
+    device = args.device if args.device else args.type.default_device()
+    sim = asyncio.run(
+        prepare_simulator(
+            simulator_manager=args.simulator_manager,
+            simulator_type=args.type,
+            os_version=args.os_version,
+            device=device,
+        )
+    )
+    result = {
+        "resources": [
+            {
+                "udid": sim.udid,
+                "device_set_path": sim.device_set_path,
+            }
+        ]
+    }
+    json.dump(result, sys.stdout)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/resource_broker/simctl_runtime.py b/buck2/prelude/apple/tools/resource_broker/simctl_runtime.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/resource_broker/simctl_runtime.py
@@ -0,0 +1,68 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import json
+from dataclasses import dataclass, field
+from typing import Optional
+
+from dataclasses_json import config, dataclass_json
+
+from .utils import execute_generic_text_producing_command
+
+
+@dataclass_json
+@dataclass
+class XCSimDevice:
+    name: str
+    identifier: str
+    product_family: str = field(metadata=config(field_name="productFamily"))
+
+
+@dataclass_json
+@dataclass
+class XCSimRuntime:
+    name: str
+    platform: str
+    version: str
+    supported_device_types: list[XCSimDevice] = field(
+        metadata=config(field_name="supportedDeviceTypes")
+    )
+
+
+@dataclass_json
+@dataclass
+class _XCSimRuntimes:
+    runtimes: list[XCSimRuntime]
+
+
+def _list_runtimes_command() -> list[str]:
+    return [
+        "xcrun",
+        "simctl",
+        "list",
+        "runtimes",
+        "available",
+        "--json",
+    ]
+
+
+def _simctl_runtimes_from_stdout(stdout: Optional[str]) -> list[XCSimRuntime]:
+    if not stdout:
+        return []
+    data = json.loads(stdout)
+    # pyre-ignore[16]: `from_dict` is dynamically provided by `dataclass_json`
+    return _XCSimRuntimes.from_dict(data).runtimes
+
+
+async def list_runtimes() -> list[XCSimRuntime]:
+    stdout = await execute_generic_text_producing_command(
+        name="list runtimes", cmd=_list_runtimes_command()
+    )
+    return _simctl_runtimes_from_stdout(stdout)
diff --git a/buck2/prelude/apple/tools/resource_broker/simulator.py b/buck2/prelude/apple/tools/resource_broker/simulator.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/resource_broker/simulator.py
@@ -0,0 +1,96 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import json
+from dataclasses import dataclass
+from enum import Enum
+from typing import Optional
+
+from dataclasses_json import dataclass_json
+
+
+class SimulatorState(str, Enum):
+    booted = "Booted"
+    booting = "Booting"
+    creating = "Creating"
+    shutdown = "Shutdown"
+    shutting_down = "Shutting Down"
+    unknown = "Unknown"
+
+
+class SimulatorType(str, Enum):
+    iphoneUnbooted = "iphone_unbooted_simulator"
+    iphoneBooted = "iphone_booted_simulator"
+    ipad = "ipad_simulator"
+    watch = "watch_simulator"
+
+    def booted(self) -> bool:
+        return self in (
+            SimulatorType.iphoneBooted,
+            SimulatorType.ipad,
+            SimulatorType.watch,
+        )
+
+    def default_device(self) -> str:
+        return {
+            SimulatorType.iphoneUnbooted: "iPhone 11",
+            SimulatorType.iphoneBooted: "iPhone 11",
+            SimulatorType.ipad: "iPad (A16)",
+            SimulatorType.watch: "Apple Watch Series 10 (46mm)",
+        }[self]
+
+    def matches_device_identifier(self, identifier: str) -> bool:
+        identifier_prefix = {
+            SimulatorType.iphoneUnbooted: "iPhone",
+            SimulatorType.iphoneBooted: "iPhone",
+            SimulatorType.ipad: "iPad",
+            SimulatorType.watch: "Apple-Watch",
+        }[self]
+        return identifier_prefix in identifier
+
+
+@dataclass_json
+@dataclass
+class Simulator:
+    name: str = ""
+    device_type_identifier: str = ""
+    os_version: str = ""
+    udid: str = ""
+    state: SimulatorState = SimulatorState.shutdown
+
+    def is_type(self, simulator_type: SimulatorType) -> bool:
+        return simulator_type.matches_device_identifier(self.device_type_identifier)
+
+    def is_valid(self):
+        return self.os_version != "" and self.udid != ""
+
+
+@dataclass
+class SimulatorInfo:
+    udid: str
+    device_set_path: str
+
+
+def managed_simulator_from_stdout(stdout: Optional[str]) -> Simulator:
+    if not stdout:
+        return None
+    # pyre-ignore[16]: `from_dict` is dynamically provided by `dataclass_json`
+    return Simulator.from_dict(json.loads(stdout))
+
+
+def managed_simulators_list_from_stdout(stdout: Optional[str]) -> list[Simulator]:
+    if not stdout:
+        return []
+    targets = map(
+        # pyre-ignore[16]: `from_dict` is dynamically provided by `dataclass_json`
+        Simulator.from_dict,
+        json.loads(stdout),
+    )
+    return list(filter(lambda target: target.is_valid(), targets))
diff --git a/buck2/prelude/apple/tools/resource_broker/timeouts.py b/buck2/prelude/apple/tools/resource_broker/timeouts.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/resource_broker/timeouts.py
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+DEFAULT_OPERATION_TIMEOUT = 10
+
+# Simulator boot is an expensive command and can take a long time to complete
+# depending on machine configuration and current machine load.
+SIMULATOR_BOOT_TIMEOUT = 90
diff --git a/buck2/prelude/apple/tools/resource_broker/utils.py b/buck2/prelude/apple/tools/resource_broker/utils.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/resource_broker/utils.py
@@ -0,0 +1,46 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import asyncio
+import json
+import shlex
+
+from .timeouts import DEFAULT_OPERATION_TIMEOUT
+
+
+async def _read_until_valid_json(stream: asyncio.StreamReader) -> object:
+    buffer = b""
+    while True:
+        data = await stream.readuntil(b"}")
+        buffer += data
+        try:
+            return json.loads(buffer.decode())
+        except json.JSONDecodeError:
+            pass
+    raise RuntimeError(
+        "Should not be reachable since either the valid JSON is there or `asyncio.IncompleteReadError` is raised."
+    )
+
+
+async def execute_generic_text_producing_command(
+    name: str, cmd: list[str], timeout: float = DEFAULT_OPERATION_TIMEOUT
+) -> str:
+    process = await asyncio.create_subprocess_exec(
+        *cmd,
+        stdin=asyncio.subprocess.DEVNULL,
+        stdout=asyncio.subprocess.PIPE,
+        stderr=asyncio.subprocess.PIPE,
+    )
+    stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
+    if process.returncode != 0:
+        raise RuntimeError(
+            f"Failed to {name} with command:\n```\n{shlex.join(cmd)}\n```\nstdout:\n```\n{stdout.decode(errors='ignore')}\n```\nstdout:\n```\n{stderr.decode(errors='ignore')}\n```\n"
+        )
+    return stdout.decode()
diff --git a/buck2/prelude/apple/tools/selective_debugging/BUCK b/buck2/prelude/apple/tools/selective_debugging/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/BUCK
@@ -0,0 +1,44 @@
+load("@prelude//apple/tools:defs.bzl", "meta_python_test")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+python_library(
+    name = "lib",
+    srcs = [
+        "macho.py",
+        "macho_parser.py",
+        "scrubber.py",
+        "spec.py",
+        "utils.py",
+    ],
+    deps = [
+        "prelude//apple/tools/re_compatibility_utils:re_compatibility_utils",
+    ],
+)
+
+python_binary(
+    name = "tool",
+    main = "main.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":lib",
+    ],
+)
+
+meta_python_test(
+    name = "tests",
+    srcs = [
+        "scrubber_test.py",
+        "spec_test.py",
+    ],
+    resources = glob([
+        "test_resources/*",
+    ]),
+    deps = [
+        "fbsource//third-party/pypi/importlib-resources:importlib-resources",
+        ":lib",
+    ],
+)
diff --git a/buck2/prelude/apple/tools/selective_debugging/macho.py b/buck2/prelude/apple/tools/selective_debugging/macho.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/macho.py
@@ -0,0 +1,84 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from dataclasses import dataclass
+
+MH_MAGIC = 0xFEEDFACE
+MH_CIGAM = 0xCEFAEDFE
+MH_MAGIC_64 = 0xFEEDFACF
+MH_CIGAM_64 = 0xCFFAEDFE
+
+LC_CODE_SIGNATURE = 0x1D
+LC_SEGMENT_64 = 0x19
+LC_SYMTAB = 0x02
+
+N_OSO = 0x66
+
+
+class MachO:
+    def __str__(self) -> str:
+        props = {}
+        for k, v in self.__dict__.items():
+            props[k] = hex(v)
+        return str(props)
+
+
+@dataclass
+class MachOHeader(MachO):
+    magic: int
+    cpu_type: int
+    cpu_subtype: int
+    file_type: int
+    n_cmds: int
+    size_of_cmds: int
+    flags: int
+    reserved: int
+
+    @property
+    def is_valid(self) -> bool:
+        return self.magic in (MH_CIGAM_64, MH_MAGIC_64)
+
+
+@dataclass
+class LoadCommand(MachO):
+    cmd: int
+    cmd_size: int
+
+
+@dataclass
+class LinkEditCommand(LoadCommand):
+    segment_name: bytes
+    VM_addr: int
+    VM_size: int
+    file_offset: int
+    file_size: int
+    maximum_VM_protection: int
+    initial_VM_protection: int
+    n_sections: int
+    flags: int
+
+
+@dataclass
+class SymtabCommand(LoadCommand):
+    cmd: int
+    cmd_size: int
+    symtab_offset: int
+    n_symbols: int
+    strtab_offset: int
+    strtab_size: int
+
+
+@dataclass
+class Symbol(MachO):
+    strtab_index: int
+    sym_type: int
+    section_index: int
+    desc: int
+    value: int
diff --git a/buck2/prelude/apple/tools/selective_debugging/macho_parser.py b/buck2/prelude/apple/tools/selective_debugging/macho_parser.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/macho_parser.py
@@ -0,0 +1,136 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import struct
+import sys
+from typing import BinaryIO, Optional
+
+from .macho import (
+    LC_CODE_SIGNATURE,
+    LC_SEGMENT_64,
+    LC_SYMTAB,
+    LinkEditCommand,
+    MachOHeader,
+    N_OSO,
+    Symbol,
+    SymtabCommand,
+)
+
+"""
+// Each LC_SYMTAB entry consists of the following fields:
+// - String Index: 4 bytes, offset into the string table (I == unsigned int)
+// - Type: 1 byte (B == unsigned char)
+// - Section: 1 byte, (B == unsigned char)
+// - Description: 2 bytes (H == unsigned short)
+// - Value: 8 bytes on 64bit, 4 bytes on 32bit (Q == unsigned long long)
+// - Everything is little-endian representation (denoted by <)
+"""
+_LC_SYMTAB_STRUCT = struct.Struct("<IBBHQ")
+
+
+def _read_bytes(f: BinaryIO, n_bytes: int) -> int:
+    b = f.read(n_bytes)
+    return int.from_bytes(b, "little")
+
+
+def load_header(f: BinaryIO, offset: int) -> tuple[MachOHeader, int]:
+    f.seek(offset)
+    magic = _read_bytes(f, 4)
+    cpu_type = _read_bytes(f, 4)
+    cpu_sub_type = _read_bytes(f, 4)
+    file_type = _read_bytes(f, 4)
+    cmd_cnt = _read_bytes(f, 4)
+    cmd_size = _read_bytes(f, 4)
+    flags = _read_bytes(f, 4)
+    reserved = _read_bytes(f, 4)
+    header = MachOHeader(
+        magic, cpu_type, cpu_sub_type, file_type, cmd_cnt, cmd_size, flags, reserved
+    )
+    return header, f.tell()
+
+
+def load_commands(
+    f: BinaryIO, offset: int, n_cmds: int
+) -> tuple[Optional[LinkEditCommand], Optional[SymtabCommand]]:
+    """
+    The OSO entries are identified in segments named __LINKEDIT.
+    If no segment is found with that name, there is nothing to scrub.
+    """
+    lc_linkedit = None
+    lc_symtab = None
+    f.seek(offset)
+    for _ in range(n_cmds):
+        pos = f.tell()
+        cmd = _read_bytes(f, 4)
+        size = _read_bytes(f, 4)
+        if cmd == LC_SEGMENT_64:
+            name = f.read(16)
+            if "LINKEDIT" in name.decode():
+                vm_addr = _read_bytes(f, 8)
+                vm_size = _read_bytes(f, 8)
+                file_offset = _read_bytes(f, 8)
+                file_size = _read_bytes(f, 8)
+                maximum_vm_protection = _read_bytes(f, 4)
+                initial_vm_protection = _read_bytes(f, 4)
+                sections = _read_bytes(f, 4)
+                flags = _read_bytes(f, 4)
+                lc_linkedit = LinkEditCommand(
+                    cmd,
+                    size,
+                    name,
+                    vm_addr,
+                    vm_size,
+                    file_offset,
+                    file_size,
+                    maximum_vm_protection,
+                    initial_vm_protection,
+                    sections,
+                    flags,
+                )
+                continue
+        elif cmd == LC_SYMTAB:
+            symtab_offset = _read_bytes(f, 4)
+            n_symbols = _read_bytes(f, 4)
+            strtab_offset = _read_bytes(f, 4)
+            strtab_size = _read_bytes(f, 4)
+            lc_symtab = SymtabCommand(
+                cmd, size, symtab_offset, n_symbols, strtab_offset, strtab_size
+            )
+            continue
+        elif cmd == LC_CODE_SIGNATURE:
+            print("[Focused Debugging][Warning] Code signature found.", file=sys.stderr)
+
+        f.seek(pos)
+        f.seek(size, 1)
+    return lc_linkedit, lc_symtab
+
+
+def load_debug_symbols(f: BinaryIO, offset: int, n_symbol: int) -> list[Symbol]:
+    """
+    // Each LC_SYMTAB entry consists of the following fields:
+    // - String Index: 4 bytes (offset into the string table)
+    // - Type: 1 byte
+    // - Section: 1 byte
+    // - Description: 2 bytes
+    // - Value: 8 bytes on 64bit, 4 bytes on 32bit
+    """
+    f.seek(offset)
+    data = f.read(n_symbol * _LC_SYMTAB_STRUCT.size)
+    return [
+        Symbol(strtab_index, sym_type, section_idx, desc, value)
+        for (
+            strtab_index,
+            sym_type,
+            section_idx,
+            desc,
+            value,
+        ) in _LC_SYMTAB_STRUCT.iter_unpack(data)
+        if sym_type == N_OSO
+    ]
diff --git a/buck2/prelude/apple/tools/selective_debugging/main.py b/buck2/prelude/apple/tools/selective_debugging/main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/main.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import sys
+
+from .scrubber import scrub
+
+
+def _parse_args() -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description="Tool to postprocess executables/dylibs."
+    )
+    parser.add_argument(
+        "--input",
+        required=True,
+        help="Path to the input which is an executable/dylib file.",
+    )
+    parser.add_argument("--output", required=True, help="Path to the output file.")
+    group = parser.add_mutually_exclusive_group(required=True)
+    group.add_argument(
+        "--targets-file",
+        help="Path to a json file which contains user-focused Buck targets",
+    )
+    group.add_argument(
+        "--spec-file",
+        help="Path to a json file which contains user-focused include/exclude specs",
+    )
+    parser.add_argument(
+        "--adhoc-codesign-tool",
+        help="An adhoc codesign tool to use to re-sign the executables/dylibs, if provided.",
+    )
+    parser.add_argument(
+        "--persisted-targets-file",
+        help="A JSON file with additional targets that must be preserved by the scrubber.",
+    )
+    return parser.parse_args()
+
+
+def main() -> None:
+    args = _parse_args()
+    try:
+        scrub(
+            input_file=args.input,
+            output_file=args.output,
+            persisted_targets_file=args.persisted_targets_file,
+            targets_file=args.targets_file,
+            spec_file=args.spec_file,
+            adhoc_codesign_tool=args.adhoc_codesign_tool,
+        )
+    except Exception as e:
+        print(f"Focused debugging failed: {e}")
+        sys.exit(1)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/selective_debugging/scrubber.py b/buck2/prelude/apple/tools/selective_debugging/scrubber.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/scrubber.py
@@ -0,0 +1,250 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import json
+import os
+import shutil
+import subprocess
+from collections.abc import Callable
+from typing import BinaryIO, Optional
+
+from apple.tools.re_compatibility_utils.writable import make_path_user_writable
+
+from .macho import Symbol
+from .macho_parser import load_commands, load_debug_symbols, load_header
+from .spec import Spec
+from .utils import MachOException
+
+
+FAKE_PATH = b"fake/path"
+# buck-out/isolation_dir/gen/project_cell/{hash}/....
+NUM_OF_COMPONENTS_IN_BUCK2_OUTPUT_PATH_BEFORE_PROJECT_PATH = 5
+# buck-out/isolation_dir/gen/project_cell//X/Y/__name__/{hash}/....
+NUM_OF_COMPONENTS_IN_BUCK2_OUTPUT_PATH_BEFORE_PROJECT_PATH_WITH_CONTENT_BASED_PATH = 4
+
+
+def _always_scrub(_: str) -> bool:
+    return True
+
+
+# Visible for testing
+def load_focused_targets_output_paths(json_file_path: str) -> set[str]:
+    if json_file_path is None or not os.path.exists(json_file_path):
+        return set()
+    with open(json_file_path) as f:
+        content = f.read()
+        if not content:
+            return set()
+        data = json.loads(content)
+        output_paths = set()
+        for target in data["targets"]:
+            _, package_and_name = target.split("//")
+            package, name = package_and_name.split(":")
+            # This assumes the output path created by buck2, which if
+            # modified, would break this logic.
+            output_directory = f"{package}/__{name}__"
+            output_paths.add(output_directory)
+    return output_paths
+
+
+# This function converts buck-out/isolation_dir/gen/project_cell/{hash}/X/Y/__name__/libFoo.a
+# into X/Y/__name__ to match the focus target output path created by load_focused_targets_output_paths
+# Visible for testing
+def _get_target_output_path_from_debug_file_path(
+    debug_target_path: str,
+) -> str:
+    # This function assumes the debug file path created by buck2 in one of the following formats:
+    # Without content based path:
+    # buck-out/isolation_dir/gen/project_cell/{hash}/.../__name__/libFoo.a
+    # buck-out/isolation_dir/gen/project_cell/{hash}/.../__name__/__objects__/bar.o
+    # buck-out/isolation_dir/gen/project_cell/{hash}/.../__name__/swift_object_file.swift.o
+    # With content based path:
+    # buck-out/isolation_dir/gen/project_cell/.../__name__/{hash}/libFoo.a
+    # buck-out/isolation_dir/gen/project_cell/.../__name__/__objects__/{hash}/bar.o
+    # buck-out/isolation_dir/gen/project_cell/.../__name__/{hash}/swift_object_file.swift.o
+    parts = debug_target_path.split("/")
+
+    # We are doing the traverse in reverse order because this way we'll find the first
+    # target directory sooner. _should_scrub can get called many times, so it's
+    # important that we make it as efficient as possible.
+    i = 1
+    while i <= len(parts):
+        # We are looking for the path component that matches __name__ in the examples above, and if we don't explicitly skip __objects__, we'll get the wrong path
+        if (
+            parts[-i].startswith("__")
+            and parts[-i].endswith("__")
+            and parts[-i] != "__objects__"
+        ):
+            break
+        i += 1
+    if i > len(parts):
+        raise Exception(
+            f"Unrecognized format for debug file path : {debug_target_path}"
+        )
+
+    # This handles the two cases, one with content based path, and one without
+    return "/".join(
+        parts[NUM_OF_COMPONENTS_IN_BUCK2_OUTPUT_PATH_BEFORE_PROJECT_PATH : -i + 1]
+    ), "/".join(
+        parts[
+            NUM_OF_COMPONENTS_IN_BUCK2_OUTPUT_PATH_BEFORE_PROJECT_PATH_WITH_CONTENT_BASED_PATH : -i
+            + 1
+        ]
+    )
+
+
+# Visible for testing
+def should_scrub_with_focused_targets_output_paths(
+    focused_targets_output_paths: set[str], debug_file_path: str
+) -> bool:
+    # All paths to be scrubbed when no focused target is specified
+    if len(focused_targets_output_paths) == 0:
+        return True
+
+    # debug_file_path usually have the format x/y/z/libFoo.a(bar.m.o)
+    if "(" in debug_file_path:
+        debug_target_path = debug_file_path.split("(")[0]
+    else:
+        debug_target_path = debug_file_path
+
+    if debug_file_path.startswith("buck-out/"):
+        target_output_path, target_output_content_based_path = (
+            _get_target_output_path_from_debug_file_path(debug_target_path)
+        )
+        return (
+            target_output_path not in focused_targets_output_paths
+            and target_output_content_based_path not in focused_targets_output_paths
+        )
+    else:
+        # occasionally archive file can be directly from source.
+        (package, name) = os.path.split(debug_file_path)
+        while package != "" and package != "/":
+            if f"{package}/__{name}__" in focused_targets_output_paths:
+                return False
+            (package, name) = os.path.split(package)
+
+        return True
+
+
+def _should_scrub_with_targets_file(
+    json_file_path: str, additional_labels: set[str]
+) -> Callable[[str], bool]:
+    focused_targets_output_paths = load_focused_targets_output_paths(json_file_path)
+    return lambda debug_file_path: should_scrub_with_focused_targets_output_paths(
+        focused_targets_output_paths.union(additional_labels), debug_file_path
+    )
+
+
+def _should_scrub_with_spec_file(
+    json_file_path: str, additional_labels: set[str]
+) -> Callable[[str], bool]:
+    spec = Spec(json_file_path)
+    return lambda debug_file_path: should_scrub_with_focused_targets_output_paths(
+        additional_labels, debug_file_path
+    ) and spec.scrub_debug_file_path(debug_file_path)
+
+
+def _scrub(
+    f: BinaryIO,
+    strtab_offset: int,
+    symbols: list[Symbol],
+    scrub_handler: Callable[[str], bool],
+) -> list[tuple[str, str]]:
+    """
+    Return a list of tuples.
+    Each tuple contains a pair of the original path and the rewritten path
+    """
+    results = []
+    for symbol in symbols:
+        f.seek(strtab_offset)
+        f.seek(symbol.strtab_index, 1)
+
+        # Read a byte at a time until we reach the end of the path, denoted by Hex 0.
+        start = end = f.tell()
+        path = b""
+        b = f.read(1)
+        while b != b"\x00":
+            path += b
+            end += 1
+            b = f.read(1)
+        str_len = end - start
+
+        path_str = path.decode()
+        if scrub_handler(path_str):
+            f.seek(start)
+            # We don't want to modify the length of the path, so pad the replacement
+            # path with spaces
+            buffer = FAKE_PATH + b" " * (str_len - len(FAKE_PATH))
+            f.write(buffer)
+            results.append((path_str, buffer.decode()))
+        else:
+            results.append((path_str, path_str))
+    return results
+
+
+def scrub(
+    input_file: str,
+    output_file: str,
+    persisted_targets_file: str,
+    targets_file: Optional[str] = None,
+    spec_file: Optional[str] = None,
+    adhoc_codesign_tool: Optional[str] = None,
+) -> list[tuple[str, str]]:
+    additional_labels = load_focused_targets_output_paths(persisted_targets_file)
+    if targets_file and spec_file:
+        raise Exception(
+            "Only one of a targets file or spec file is supported, not both!"
+        )
+    elif targets_file:
+        scrub_handler = _should_scrub_with_targets_file(targets_file, additional_labels)
+    elif spec_file:
+        scrub_handler = _should_scrub_with_spec_file(spec_file, additional_labels)
+    else:
+        scrub_handler = _always_scrub
+
+    shutil.copy2(input_file, output_file)
+    # Make it RE-compatible
+    make_path_user_writable(output_file)
+
+    results = []
+    with open(output_file, "r+b") as f:
+        header, offset = load_header(f, 0)
+        if not header.is_valid:
+            raise MachOException("Invalid macho format!")
+        lc_linkedit, lc_symtab = load_commands(f, offset, header.n_cmds)
+        if lc_linkedit is None:
+            return []
+        if lc_symtab is None:
+            raise MachOException("LC_SYMTAB command not found")
+        if lc_symtab.strtab_size == 0 or lc_symtab.n_symbols == 0:
+            return []
+        if lc_linkedit.file_size == 0:
+            raise MachOException("LC_SEGMENT_64 command for string table not found")
+        f.seek(lc_symtab.strtab_offset)
+        """
+        ld64 deliberately burns the first byte with the space character, so that zero is never a
+        valid string index and writes 0x00 at offset 1, so that it's always the empty string.
+        The code for this in ld64 is in LinkEditClassic.hpp (StringPoolAtom::StringPoolAtom).
+        """
+        if f.read(1) != b"\x20":
+            raise MachOException("First character in the string table is not a space")
+        if f.read(1) != b"\x00":
+            raise MachOException("Second character in the string table is not a NUL")
+
+        symbols = load_debug_symbols(f, lc_symtab.symtab_offset, lc_symtab.n_symbols)
+        results = _scrub(f, lc_symtab.strtab_offset, symbols, scrub_handler)
+
+    if adhoc_codesign_tool:
+        subprocess.run(
+            [adhoc_codesign_tool, "--binary", output_file],
+            check=True,
+        )
+
+    return results
diff --git a/buck2/prelude/apple/tools/selective_debugging/scrubber_test.py b/buck2/prelude/apple/tools/selective_debugging/scrubber_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/scrubber_test.py
@@ -0,0 +1,330 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import pathlib
+import unittest
+from tempfile import NamedTemporaryFile
+from typing import Optional
+from unittest.mock import call, patch
+
+import importlib_resources as resources
+
+from .scrubber import (
+    load_focused_targets_output_paths,
+    scrub,
+    should_scrub_with_focused_targets_output_paths,
+)
+
+FAKE_PATH = "fake/path"
+
+
+class Test(unittest.TestCase):
+    def test_no_focused_targets(self):
+        results, _ = _get_scrubber_results(targets_json_file_path=None)
+        for _, rewrite_path in results:
+            # We expect all paths to be scrubbed
+            self.assertEqual(rewrite_path.strip(), FAKE_PATH)
+
+    def test_empty_focused_targets(self):
+        results, _ = _get_scrubber_results(
+            targets_json_file_path="focused_targets_empty.json"
+        )
+        for _, rewrite_path in results:
+            # We expect all paths to be scrubbed
+            self.assertEqual(rewrite_path.strip(), FAKE_PATH)
+
+    def test_focused_targets(self):
+        with resources.as_file(
+            _get_test_resource_file("focused_targets.json")
+        ) as targets_json_file:
+            output_paths = load_focused_targets_output_paths(str(targets_json_file))
+
+        results, _ = _get_scrubber_results(
+            targets_json_file_path="focused_targets.json"
+        )
+
+        focused_paths = []
+        scrubbed_paths = []
+
+        for orig_path, rewrite_path in results:
+            for output_path in output_paths:
+                if output_path in orig_path:
+                    # Ensure we didn't scrub the path
+                    focused_paths.append(orig_path)
+                    self.assertEqual(orig_path, rewrite_path)
+                else:
+                    # Ensure we scrubbed the path
+                    scrubbed_paths.append(orig_path)
+                    self.assertEqual(rewrite_path.strip(), FAKE_PATH)
+
+        self.assertEqual(
+            focused_paths,
+            [
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__Foo__/libFoo.a(Foo.mm.o)",
+            ],
+        )
+        self.assertEqual(
+            scrubbed_paths,
+            [
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/AppDelegate.m.o",
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/RootViewController.m.o",
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/main.m.o",
+            ],
+        )
+
+    def test_spec_targets(self):
+        focused_paths, scrubbed_paths = _get_focused_and_scrubbed_paths(
+            spec_json_file_path="focused_spec.json"
+        )
+
+        self.assertEqual(
+            focused_paths,
+            [
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__Foo__/libFoo.a(Foo.mm.o)",
+            ],
+        )
+        self.assertEqual(
+            scrubbed_paths,
+            [
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/AppDelegate.m.o",
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/RootViewController.m.o",
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/main.m.o",
+            ],
+        )
+
+    @patch("subprocess.run")
+    def test_codesigning(self, subprocess):
+        subprocess.return_value = [0, 0]
+        results, output_file = _get_scrubber_results(
+            spec_json_file_path="focused_spec.json",
+            adhoc_codesign_tool="/usr/fake/codesign",
+        )
+        expected_calls = [
+            call(
+                [
+                    "/usr/fake/codesign",
+                    "--binary",
+                    output_file,
+                ],
+                check=True,
+            ),
+        ]
+        subprocess.assert_has_calls(expected_calls)
+
+    def test_load_focused_targets_output_paths(self):
+        with resources.as_file(
+            _get_test_resource_file("focused_targets.json")
+        ) as targets_json_file:
+            output_paths = load_focused_targets_output_paths(str(targets_json_file))
+
+        self.assertEqual(
+            output_paths, {"fbobjc/buck2/samples/focused_debugging/__Foo__"}
+        )
+
+    def test_spec_targets_regex_all(self):
+        focused_paths, scrubbed_paths = _get_focused_and_scrubbed_paths(
+            spec_json_file_path="focused_spec_regex_all.json"
+        )
+        self.assertEqual(
+            focused_paths,
+            [
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/AppDelegate.m.o",
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/RootViewController.m.o",
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/main.m.o",
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__Foo__/libFoo.a(Foo.mm.o)",
+            ],
+        )
+        self.assertEqual(
+            scrubbed_paths,
+            [],
+        )
+
+    def test_spec_targets_regex_none(self):
+        focused_paths, scrubbed_paths = _get_focused_and_scrubbed_paths(
+            spec_json_file_path="focused_spec_regex_none.json"
+        )
+
+        self.assertEqual(
+            focused_paths,
+            [],
+        )
+        self.assertEqual(
+            scrubbed_paths,
+            [
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/AppDelegate.m.o",
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/RootViewController.m.o",
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__HelloWorld__/__objects__/srcs/main.m.o",
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/buck2/samples/focused_debugging/__Foo__/libFoo.a(Foo.mm.o)",
+            ],
+        )
+
+    def test_should_scrub_with_focused_targets_output_paths(self):
+        focused_targets_output_paths = {
+            "fbobjc/some/path/__foo__",
+            "xplat/some/path/__foo__",
+        }
+        self.assertEqual(
+            True,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__baz__/libbar.a(baz.mm.o)",
+            ),
+        )
+        self.assertEqual(
+            True,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__baz__/__objects__/baz.mm.o",
+            ),
+        )
+        self.assertEqual(
+            True,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "buck-out/v2/gen/fbsource/fbobjc/some/path/__baz__/__objects__/56628b5feecfab0a/baz.mm.o",
+            ),
+        )
+        self.assertEqual(
+            False,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__foo__/libbar.a(baz.mm.o)",
+            ),
+        )
+        self.assertEqual(
+            False,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__foo__/__objects__/baz.mm.o",
+            ),
+        )
+        self.assertEqual(
+            False,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__foo__/lib.a",
+            ),
+        )
+        self.assertEqual(
+            False,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "buck-out/v2/gen/fbsource/fbobjc/some/path/__foo__/56628b5feecfab0a/lib.a",
+            ),
+        )
+        self.assertEqual(
+            False,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "buck-out/v2/gen/fbsource/56628b5feecfab0a/fbobjc/some/path/__foo__/__objects__/bar.o",
+            ),
+        )
+        self.assertEqual(
+            False,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "xplat/some/path/foo/lib/prebuilt_lib.a(baz.m.o)",
+            ),
+        )
+        self.assertEqual(
+            True,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "xplat/some/path/fooo/prebuilt_lib.a(baz.m.o)",
+            ),
+        )
+        self.assertEqual(
+            True,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "/tmp/lto.tmp",
+            ),
+        )
+        self.assertEqual(
+            True,
+            should_scrub_with_focused_targets_output_paths(
+                focused_targets_output_paths,
+                "/",
+            ),
+        )
+
+
+def _get_focused_and_scrubbed_paths(
+    targets_json_file_path: Optional[str] = None,
+    spec_json_file_path: Optional[str] = None,
+    adhoc_codesign_tool: Optional[str] = None,
+) -> (list[str], list[str]):
+    results, _ = _get_scrubber_results(
+        targets_json_file_path=targets_json_file_path,
+        spec_json_file_path=spec_json_file_path,
+        adhoc_codesign_tool=adhoc_codesign_tool,
+    )
+
+    focused_paths = []
+    scrubbed_paths = []
+
+    for orig_path, rewrite_path in results:
+        if rewrite_path.strip() == FAKE_PATH:
+            scrubbed_paths.append(orig_path)
+        elif orig_path == rewrite_path:
+            focused_paths.append(orig_path)
+        else:
+            raise Exception(
+                f"Rewrite path is neither the fake path nor the original path: {rewrite_path}"
+            )
+
+    return (focused_paths, scrubbed_paths)
+
+
+@patch(
+    "apple.tools.selective_debugging.scrubber.make_path_user_writable",
+    return_value=None,
+)
+def _get_scrubber_results(
+    make_path_user_writable_mock,
+    targets_json_file_path: Optional[str] = None,
+    spec_json_file_path: Optional[str] = None,
+    adhoc_codesign_tool: Optional[str] = None,
+) -> tuple[list[tuple[str, str]], str]:
+    with resources.as_file(_get_test_resource_file("HelloWorld")) as test_binary_file:
+        with NamedTemporaryFile() as out_file:
+            if targets_json_file_path:
+                with resources.as_file(
+                    _get_test_resource_file(targets_json_file_path)
+                ) as targets_json_file:
+                    return (
+                        scrub(
+                            str(test_binary_file),
+                            out_file.name,
+                            None,
+                            targets_file=str(targets_json_file),
+                            adhoc_codesign_tool=adhoc_codesign_tool,
+                        ),
+                        out_file.name,
+                    )
+            elif spec_json_file_path:
+                with resources.as_file(
+                    _get_test_resource_file(spec_json_file_path),
+                ) as spec_json_file:
+                    return (
+                        scrub(
+                            str(test_binary_file),
+                            out_file.name,
+                            None,
+                            spec_file=str(spec_json_file),
+                            adhoc_codesign_tool=adhoc_codesign_tool,
+                        ),
+                        out_file.name,
+                    )
+            else:
+                return scrub(str(test_binary_file), out_file.name, None), out_file.name
+
+
+def _get_test_resource_file(name) -> pathlib.Path:
+    path = resources.files(__package__).joinpath(f"test_resources/{name}")
+    return path
diff --git a/buck2/prelude/apple/tools/selective_debugging/spec.py b/buck2/prelude/apple/tools/selective_debugging/spec.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/spec.py
@@ -0,0 +1,115 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import json
+import re
+from dataclasses import dataclass, field
+
+
+@dataclass
+class BuildTargetPatternOutputPathMatcher:
+    pattern: str
+    output_path: str = field(init=False)
+
+    def __post_init__(self) -> None:
+        _, package_and_name = self.pattern.split("//")
+        if package_and_name.endswith("..."):
+            # recursive pattern
+            output_path, _ = package_and_name.split("...")
+        elif package_and_name.endswith(":"):
+            # package pattern
+            package, _ = package_and_name.split(":")
+            # This assumes the output path created by buck2, which if
+            # modified, would break this logic.
+            output_path = f"{package}/__"
+        else:
+            # target pattern
+            package, name = package_and_name.split(":")
+            # This assumes the output path created by buck2, which if
+            # modified, would break this logic.
+            output_path = f"{package}/__{name}__"
+
+        self.output_path = output_path
+
+    def match_path(self, debug_file_path: str) -> bool:
+        return self.output_path in debug_file_path
+
+
+@dataclass
+class Spec:
+    spec_path: str
+    include_build_target_patterns: list[BuildTargetPatternOutputPathMatcher] = field(
+        init=False
+    )
+    include_regular_expressions: list[re.Pattern[str]] = field(init=False)
+    exclude_build_target_patterns: list[BuildTargetPatternOutputPathMatcher] = field(
+        init=False
+    )
+    exclude_regular_expressions: list[re.Pattern[str]] = field(init=False)
+
+    def __post_init__(self) -> None:
+        with open(self.spec_path) as f:
+            data = json.load(f)
+
+        self.include_build_target_patterns = [
+            BuildTargetPatternOutputPathMatcher(entry)
+            for entry in data["include_build_target_patterns"]
+        ]
+        self.include_regular_expressions = [
+            re.compile(_sanitize_regex_pattern(entry))
+            for entry in data["include_regular_expressions"]
+        ]
+        self.exclude_build_target_patterns = [
+            BuildTargetPatternOutputPathMatcher(entry)
+            for entry in data["exclude_build_target_patterns"]
+        ]
+        self.exclude_regular_expressions = [
+            re.compile(_sanitize_regex_pattern(entry))
+            for entry in data["exclude_regular_expressions"]
+        ]
+
+    def scrub_debug_file_path(self, debug_file_path: str) -> bool:
+        if self.include_build_target_patterns or self.include_regular_expressions:
+            is_included = _path_matches_pattern_or_expression(
+                debug_file_path,
+                self.include_build_target_patterns,
+                self.include_regular_expressions,
+            )
+        else:
+            is_included = True
+
+        # If the path is included (and not excluded), do not scrub
+        return not (
+            is_included
+            and not _path_matches_pattern_or_expression(
+                debug_file_path,
+                self.exclude_build_target_patterns,
+                self.exclude_regular_expressions,
+            )
+        )
+
+
+def _sanitize_regex_pattern(pattern: str) -> str:
+    double_slash_index = pattern.find("//")
+    return pattern[double_slash_index + 1 :] if double_slash_index != -1 else pattern
+
+
+def _path_matches_pattern_or_expression(
+    debug_file_path: str,
+    patterns: list[BuildTargetPatternOutputPathMatcher],
+    expressions: list[re.Pattern[str]],
+) -> bool:
+    for pattern in patterns:
+        if pattern.match_path(debug_file_path):
+            return True
+    for expression in expressions:
+        if expression.search(debug_file_path):
+            return True
+    return False
diff --git a/buck2/prelude/apple/tools/selective_debugging/spec_test.py b/buck2/prelude/apple/tools/selective_debugging/spec_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/spec_test.py
@@ -0,0 +1,104 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import json
+import unittest
+from tempfile import NamedTemporaryFile
+
+from .spec import BuildTargetPatternOutputPathMatcher, Spec
+
+FAKE_PATH = "fake/path"
+
+
+class Test(unittest.TestCase):
+    def test_build_target_pattern_matcher(self):
+        target = BuildTargetPatternOutputPathMatcher("cell//foo:bar")
+        self.assertTrue(target.match_path("foo/__bar__"))
+        self.assertFalse(target.match_path("foo/__baz__"))
+
+        package = BuildTargetPatternOutputPathMatcher("cell//foo:")
+        self.assertTrue(package.match_path("foo/__bar__"))
+        self.assertTrue(package.match_path("foo/__baz__"))
+        self.assertFalse(target.match_path("foo/bar/__baz__"))
+
+        recursive = BuildTargetPatternOutputPathMatcher("cell//foo/...")
+        self.assertTrue(recursive.match_path("foo/__bar__"))
+        self.assertTrue(recursive.match_path("foo/bar/__baz__"))
+        self.assertFalse(recursive.match_path("bar/__baz__"))
+
+    def test_spec_with_includes(self):
+        test_spec = _base_spec()
+        test_spec["include_build_target_patterns"] = [
+            "cell//foo:",
+        ]
+
+        spec = _get_spec(test_spec)
+
+        # We expect to not scrub anything with "foo/__"
+        self.assertFalse(spec.scrub_debug_file_path("foo/__bar__"))
+        self.assertFalse(spec.scrub_debug_file_path("foo/__baz__"))
+        self.assertTrue(spec.scrub_debug_file_path("foo/bar/__baz__"))
+
+    def test_spec_with_include_regex(self):
+        test_spec = _base_spec()
+        test_spec["include_regular_expressions"] = [
+            "foo",
+        ]
+
+        spec = _get_spec(test_spec)
+
+        # We expect to not scrub anything with "foo"
+        self.assertFalse(spec.scrub_debug_file_path("foo/__bar__"))
+        self.assertFalse(spec.scrub_debug_file_path("foo/__baz__"))
+        self.assertTrue(spec.scrub_debug_file_path("bar/bar/__baz__"))
+
+    def test_spec_with_exclude_regex(self):
+        test_spec = _base_spec()
+        test_spec["exclude_regular_expressions"] = [
+            "foo",
+        ]
+
+        spec = _get_spec(test_spec)
+
+        # We expect to scrub anything with "foo"
+        self.assertTrue(spec.scrub_debug_file_path("foo/__bar__"))
+        self.assertTrue(spec.scrub_debug_file_path("foo/__baz__"))
+        self.assertFalse(spec.scrub_debug_file_path("bar/bar/__baz__"))
+
+    def test_spec_with_both(self):
+        test_spec = _base_spec()
+        test_spec["include_build_target_patterns"] = [
+            "cell//foo:",
+        ]
+        test_spec["exclude_regular_expressions"] = [
+            "bar",
+        ]
+
+        spec = _get_spec(test_spec)
+
+        # We expect to scrub anything with "bar", and not scrub anything with "foo/__"
+        self.assertTrue(spec.scrub_debug_file_path("foo/__bar__"))
+        self.assertFalse(spec.scrub_debug_file_path("foo/__baz__"))
+        self.assertTrue(spec.scrub_debug_file_path("bar/bar/__baz__"))
+
+
+def _get_spec(test_spec) -> Spec:
+    with NamedTemporaryFile(mode="w+") as tmp:
+        json.dump(test_spec, tmp)
+        tmp.flush()
+
+        return Spec(tmp.name)
+
+
+def _base_spec() -> dict[str, list[str]]:
+    return {
+        "include_build_target_patterns": [],
+        "include_regular_expressions": [],
+        "exclude_build_target_patterns": [],
+        "exclude_regular_expressions": [],
+    }
diff --git a/buck2/prelude/apple/tools/selective_debugging/test_resources/HelloWorld b/buck2/prelude/apple/tools/selective_debugging/test_resources/HelloWorld
new file mode 100644
Binary files /dev/null and b/buck2/prelude/apple/tools/selective_debugging/test_resources/HelloWorld differ
diff --git a/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec.json b/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec.json
@@ -0,0 +1,8 @@
+{
+    "include_build_target_patterns": [
+        "//fbobjc/buck2/samples/focused_debugging:Foo"
+    ],
+    "include_regular_expressions": [],
+    "exclude_build_target_patterns": [],
+    "exclude_regular_expressions": []
+}
diff --git a/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec_regex_all.json b/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec_regex_all.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec_regex_all.json
@@ -0,0 +1,6 @@
+{
+    "include_build_target_patterns": [],
+    "include_regular_expressions": ["fbsource//fbobjc/buck2/samples/focused_debugging:*"],
+    "exclude_build_target_patterns": [],
+    "exclude_regular_expressions": []
+}
diff --git a/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec_regex_none.json b/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec_regex_none.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_spec_regex_none.json
@@ -0,0 +1,6 @@
+{
+    "include_build_target_patterns": [],
+    "include_regular_expressions": ["fbsource//fbobjc/buck2/samples/focused_debugging:*"],
+    "exclude_build_target_patterns": [],
+    "exclude_regular_expressions": ["//fbobjc/buck2/samples/focused_debugging:*"]
+}
diff --git a/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_targets.json b/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_targets.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_targets.json
@@ -0,0 +1,5 @@
+{
+    "targets": [
+        "//fbobjc/buck2/samples/focused_debugging:Foo"
+    ]
+}
diff --git a/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_targets_empty.json b/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_targets_empty.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/test_resources/focused_targets_empty.json
@@ -0,0 +1,4 @@
+{
+    "targets": [
+    ]
+}
diff --git a/buck2/prelude/apple/tools/selective_debugging/utils.py b/buck2/prelude/apple/tools/selective_debugging/utils.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/selective_debugging/utils.py
@@ -0,0 +1,13 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+class MachOException(Exception):
+    pass
diff --git a/buck2/prelude/apple/tools/signing_context_tree_postprocessor/BUCK b/buck2/prelude/apple/tools/signing_context_tree_postprocessor/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/signing_context_tree_postprocessor/BUCK
@@ -0,0 +1,11 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("apple_workflows")
+
+source_listing()
+
+python_binary(
+    name = "signing_context_tree_postprocessor",
+    main = "main.py",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/apple/tools/signing_context_tree_postprocessor/main.py b/buck2/prelude/apple/tools/signing_context_tree_postprocessor/main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/signing_context_tree_postprocessor/main.py
@@ -0,0 +1,96 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+import os
+from pathlib import Path
+
+_FORMAT_VERSION = 1
+
+
+def _flatten_signing_contexts_from_signing_context_tree(
+    current_path, signing_context_tree, flattened_contexts
+):
+    inner_contexts = signing_context_tree.get("inner_signing_contexts", {})
+    for inner_rel_path, inner_signing_context_tree in inner_contexts.items():
+        inner_path = os.path.join(current_path, inner_rel_path)
+        # Process inner bundles first (i.e., inside out) for consistency with codesigning manifest tree
+        _flatten_signing_contexts_from_signing_context_tree(
+            current_path=inner_path,
+            signing_context_tree=inner_signing_context_tree,
+            flattened_contexts=flattened_contexts,
+        )
+
+    signing_context_path = signing_context_tree.get("signing_context")
+    if signing_context_path:
+        with open(signing_context_path, "r") as signing_context_file:
+            signing_context = json.load(signing_context_file)
+
+            signing_context_version = signing_context["version"]
+            if signing_context_version != _FORMAT_VERSION:
+                raise RuntimeError(
+                    f"Expected format version {_FORMAT_VERSION} but got {signing_context_version}"
+                )
+            if len(signing_context) > 1:
+                # Skip inclusion of empty contexts
+                processed_signing_context = dict(signing_context)
+                processed_signing_context.pop("version")
+                processed_signing_context["path"] = current_path
+                flattened_contexts.append(processed_signing_context)
+
+
+def _args_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(
+        description="Tool which postprocesses a signing context tree to include all information inline."
+    )
+    parser.add_argument(
+        "--signing-context-tree",
+        metavar="<signing-context-tree.json>",
+        type=Path,
+        required=True,
+        help="Path to the preprocessed signing context.",
+    )
+    parser.add_argument(
+        "--output",
+        metavar="<output.json>",
+        type=Path,
+        required=True,
+        help="Path to the postprocessed file.",
+    )
+
+    return parser
+
+
+def _main() -> None:
+    args_parser = _args_parser()
+    args = args_parser.parse_args()
+
+    with open(args.signing_context_tree, "r") as signing_context_tree_file:
+        signing_context_tree = json.load(signing_context_tree_file)
+
+        flattened_contexts = []
+        _flatten_signing_contexts_from_signing_context_tree(
+            current_path="",
+            signing_context_tree=signing_context_tree,
+            flattened_contexts=flattened_contexts,
+        )
+
+        with open(args.output, "w") as output_file:
+            json.dump(
+                {
+                    "version": _FORMAT_VERSION,
+                    "provisioned_bundles": flattened_contexts,
+                },
+                output_file,
+                indent=4,
+            )
+
+
+if __name__ == "__main__":
+    _main()
diff --git a/buck2/prelude/apple/tools/split_arch_combine_dsym_bundles_tool.py b/buck2/prelude/apple/tools/split_arch_combine_dsym_bundles_tool.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/split_arch_combine_dsym_bundles_tool.py
@@ -0,0 +1,63 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import os
+import shutil
+from pathlib import Path
+
+
+def _args_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(
+        description="""
+            Tool for combining multiple dsym bundles into a single one for Universal Binaries when the
+            split_arch_dsym is enabled.
+        """
+    )
+    parser.add_argument("--dsym-bundle", action="append", type=str)
+    parser.add_argument("--arch", action="append", type=str)
+    parser.add_argument(
+        "--output",
+        type=Path,
+        required=True,
+        help="Path where the output bundle should be written to",
+    )
+
+    return parser
+
+
+def _main() -> None:
+    args = _args_parser().parse_args()
+
+    output_dwarf_path = os.path.join(args.output, "Contents/Resources/DWARF")
+    os.makedirs(output_dwarf_path)
+
+    if len(args.arch) != len(args.dsym_bundle):
+        raise Exception(
+            f"Need to specify an architecture for every dsym bundle, archs:{args.arch}, dsyms:{args.dsym_bundle}"
+        )
+    for i in range(len(args.dsym_bundle)):
+        dwarf_files_dir = os.path.join(args.dsym_bundle[i], "Contents/Resources/DWARF")
+        dwarf_files = os.listdir(dwarf_files_dir)
+        for dwarf_file in dwarf_files:
+            shutil.copy2(
+                os.path.join(dwarf_files_dir, dwarf_file),
+                os.path.join(output_dwarf_path, f"{dwarf_file}.{args.arch[i]}"),
+            )
+
+    # pick one of the Info.plist and copy it to the output bundle.
+    shutil.copy2(
+        os.path.join(args.dsym_bundle[0], "Contents/Info.plist"),
+        os.path.join(args.output, "Contents/Info.plist"),
+    )
+
+
+if __name__ == "__main__":
+    _main()
diff --git a/buck2/prelude/apple/tools/spm_packager.py b/buck2/prelude/apple/tools/spm_packager.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/spm_packager.py
@@ -0,0 +1,96 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import os
+import shutil
+import string
+
+BINARY_TARGET_TEMPLATE = string.Template(
+    """    .binaryTarget(name: "$name", path: "$path")"""
+)
+
+PACKAGE_TEMPLATE = string.Template(
+    """// swift-tools-version:6.0
+
+import PackageDescription
+
+let package = Package(
+  name: "$name",
+  products: [
+    .library(
+      name: "$name",
+      targets: [$targets]),
+  ],
+  targets: [
+$binary_targets,
+  ]
+)
+"""
+)
+
+FRAMEWORKS_SUBDIR = "Frameworks"
+
+
+def _main() -> None:
+    parser = argparse.ArgumentParser(
+        description="""
+            Tool which accepts a list of XCFramework binaries to generate
+            an SPM package that wraps them all.
+        """
+    )
+    parser.add_argument(
+        "--xcframework",
+        action="append",
+        nargs=2,
+        required=True,
+        help="Name and path to an XCFramework to include.",
+    )
+    parser.add_argument(
+        "--output-path",
+        action="store",
+        required=True,
+        help="Output dir to write package inside",
+    )
+    parser.add_argument(
+        "--package-name",
+        action="store",
+        required=True,
+        help="Name to use for package in Package.swift",
+    )
+    args = parser.parse_args()
+
+    os.mkdir(args.output_path)
+    os.mkdir(os.path.join(args.output_path, FRAMEWORKS_SUBDIR))
+
+    binary_targets = []
+    targets = []
+
+    for framework in args.xcframework:
+        name, path = framework
+        relative_path = os.path.join(FRAMEWORKS_SUBDIR, os.path.basename(path))
+        package_path = os.path.join(args.output_path, relative_path)
+        shutil.copytree(path, package_path, symlinks=True)
+        binary_targets.append(
+            BINARY_TARGET_TEMPLATE.substitute({"name": name, "path": relative_path})
+        )
+        targets.append(f'"{name}"')
+
+    swift_source = PACKAGE_TEMPLATE.substitute(
+        {
+            "name": args.package_name,
+            "targets": ", ".join(targets),
+            "binary_targets": ",\n".join(binary_targets),
+        }
+    )
+    with open(os.path.join(args.output_path, "Package.swift"), "w") as package_swift:
+        package_swift.write(swift_source)
+
+
+if __name__ == "__main__":
+    _main()
diff --git a/buck2/prelude/apple/tools/static_archive_linker.py b/buck2/prelude/apple/tools/static_archive_linker.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/static_archive_linker.py
@@ -0,0 +1,67 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import subprocess
+import sys
+
+
+def _filter_files(args):
+    # Filter out any arg that starts with '-'.  Also filter out passed arg
+    # pairs like '-framework Cocoa'. Assumes that other args are files that
+    # should be passed to libtool.
+    # Rationale: There's no way of checking if an arg is intended to be a file.
+    # Having a filter that checks if a file with a given path exists will
+    # silently remove the arg in the event of an error where arg is a file and
+    # the file does not exist.
+    filtered_args = []
+    skip_next = False
+    for arg in args:
+        if skip_next:
+            skip_next = False
+            continue
+        if arg.startswith("-"):
+            if arg == "-framework":
+                skip_next = True
+            continue
+        filtered_args.append(arg)
+    return filtered_args
+
+
+def _main() -> None:
+    parser = argparse.ArgumentParser(
+        description="""
+            Tool which accepts a list of link argments and passes only the
+            files to `libtool` to create a static archive of only those
+            files for distribuion.
+        """
+    )
+    # the libtool executable that is passed in can be mulitple args
+    # i.e. it can be a run.sh wrapper followed by a supplementary arg
+    # hence nargs="+"
+    parser.add_argument(
+        "--libtool", nargs="+", action="extend", required=True, help="path to libtool"
+    )
+    parser.add_argument("--output", required=True, help="path to output")
+    parser.add_argument("args", nargs=argparse.REMAINDER)
+
+    args = parser.parse_args()
+    file_args = _filter_files(args.args)
+    result = subprocess.run(
+        args.libtool + ["-static", "-o", args.output] + file_args,
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+        encoding=sys.stdout.encoding,
+    )
+    print(result.stdout, file=sys.stdout, end="")
+    print(result.stderr, file=sys.stderr, end="")
+    sys.exit(result.returncode)
+
+
+if __name__ == "__main__":
+    _main()
diff --git a/buck2/prelude/apple/tools/swift_exec.py b/buck2/prelude/apple/tools/swift_exec.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/swift_exec.py
@@ -0,0 +1,459 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+import os
+import pathlib
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+
+from writable import make_dir_recursively_writable, make_path_user_writable
+
+_RE_TMPDIR_ENV_VAR = "TMPDIR"
+_FILE_WRITE_FAILURE_MARKER = "could not write"
+
+
+def _expand_args(command):
+    for arg in command:
+        if arg.startswith("@"):
+            with open(arg[1:]) as argsfile:
+                return [line.rstrip() for line in argsfile.readlines()]
+
+    return []
+
+
+def _get_modulemap(args):
+    for i in range(len(args)):
+        if args[i].startswith("-explicit-swift-module-map-file"):
+            if args[i + 1].startswith("-Xfrontend"):
+                path = args[i + 2]
+            else:
+                path = args[i + 1]
+
+            with open(path.strip()) as modulemap:
+                return json.load(modulemap)
+
+    return None
+
+
+def _get_modulename(args):
+    return args[args.index("-module-name") + 1]
+
+
+def _get_modules(command):
+    args = _expand_args(command)
+    modules = set()
+    modules.add(_get_modulename(args))
+    modulemap = _get_modulemap(args)
+    if modulemap is None:
+        return modules
+
+    for entry in modulemap:
+        # We only remove prefixes from first party modules.
+        if "sdk_deps" in entry.get("clangModulePath", ""):
+            pass
+        elif "sdk_deps" in entry.get("modulePath", ""):
+            pass
+        else:
+            modules.add(entry["moduleName"])
+
+    return modules
+
+
+def _remove_swiftinterface_module_prefixes(command):
+    interface_path = command[command.index("-emit-module-interface-path") + 1]
+    modules = _get_modules(command)
+    pattern = re.compile(r"(\w+)\.([\w.]+)")
+
+    def replace_module_prefixes(match):
+        if match.group(1) in modules:
+            return match.group(2)
+        else:
+            return match.group(0)
+
+    with open(interface_path, "r+") as f:
+        interface = f.read()
+        f.seek(0)
+        f.write(pattern.sub(replace_module_prefixes, interface))
+        f.truncate()
+
+
+def _make_path_user_writable(path: str) -> None:
+    # Ensure the path is writable by the user. This is required for Swift
+    # Incremental Remote Actions, where this path may or may not be
+    # pre-populated from a previous action. We need to check because we won't
+    # know if we have these paths populated until runtime.
+    if "INSIDE_RE_WORKER" not in os.environ:
+        return
+
+    if not os.path.exists(path):
+        return
+
+    backup_path = f"{path}.bak"
+    shutil.move(path, backup_path)
+    if os.path.isdir(backup_path):
+        shutil.copytree(backup_path, path)
+        make_dir_recursively_writable(path)
+        # Remove the original dir. Unlinking its files needs write
+        # permission on parent dir
+        for dirpath, _dirnames, _filenames in os.walk(backup_path):
+            make_path_user_writable(dirpath)
+        shutil.rmtree(backup_path)
+    else:
+        shutil.copy2(backup_path, path)
+        pathlib.Path(backup_path).unlink()
+        make_path_user_writable(path)
+
+
+def _rewrite_dependency_file(command, out_path):
+    if not out_path:
+        raise RuntimeError("-emit-dependencies requires -dependencies-file-output")
+
+    # The compiler will output d files in Makefile format with abolute paths,
+    # Buck expects line separated relative paths with no input prefix.
+    output_file_map_path = command[command.index("-output-file-map") + 1]
+    with open(output_file_map_path) as f:
+        output_file_map = json.load(f)
+
+    deps_file_path = output_file_map[""]["dependencies"]
+    with open(deps_file_path, encoding="utf-8") as f:
+        for line in f:
+            # We have multiple entries for the supplementary outputs of the
+            # compilation action. We have two cases we care about:
+            #  1. swiftmodule output
+            #  2. object file output
+            # Other supplemenatary outputs like swiftsourceinfo are not
+            # tracked.
+            output, inputs = line.split(" : ")
+            if output.endswith(".swiftmodule") or output.endswith(".o"):
+                dependencies = shlex.split(inputs)
+                break
+
+    # Sanity check that we only track relative paths
+    relative_paths = []
+    for path in dependencies:
+        if "/usr/lib/swift/host/" in path:
+            # We don't track toolchain internal paths.
+            continue
+        elif path.startswith("/"):
+            # This can occur for Xcode toolchain plugins like libSwiftUIMacros.dylib
+            print(f"Dependency file contains absolute path: {path}", file=sys.stderr)
+        else:
+            relative_paths.append(os.path.normpath(path))
+
+    _make_path_user_writable(out_path)
+    with open(out_path, "w") as f:
+        f.write("\n".join(sorted(relative_paths)))
+        f.write("\n")
+
+
+def _get_output_file_map(args):
+    try:
+        i = args.index("-output-file-map")
+        filename = args[i + 1]
+    except (ValueError, IndexError):
+        raise RuntimeError("Failed to find -output-file-map in args")
+
+    with open(filename) as f:
+        return json.load(f)
+
+
+def _get_serialized_diagnostics_frontend_flag(args):
+    for a in args:
+        if a.startswith("-serialize-diagnostics-path="):
+            return a
+    return None
+
+
+def _get_serialized_diagnostics_path(args):
+    # The diagnostics can be specified via frontend args or in the output file
+    # map.
+    frontend_arg = _get_serialized_diagnostics_frontend_flag(args)
+    if frontend_arg:
+        return frontend_arg.split("=")[1]
+
+    output_file_map = _get_output_file_map(args)
+    module_entries = output_file_map.get("", {})
+    if "diagnostics" in module_entries:
+        return module_entries["diagnostics"]
+    else:
+        raise RuntimeError("Failed to find diagnostics in output file map")
+
+
+def _parse_wrapper_args(
+    allargs: list[str],
+) -> tuple[list[str], argparse.ArgumentParser]:
+    driver_args = []
+    wrapper_args = []
+    i = 0
+    while i < len(allargs):
+        arg = allargs[i]
+        if arg == "-Xwrapper":
+            if i == len(allargs) - 1:
+                raise RuntimeError("Missing argument to -Xwrapper")
+
+            wrapper_args.append(allargs[i + 1])
+            i += 2
+        else:
+            driver_args.append(arg)
+            i += 1
+
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "-dependencies-file-output",
+        help="Path to write Buck format dependencies file to",
+    )
+    parser.add_argument(
+        "-ignore-errors",
+        action="store_true",
+        help="Used to ignore errors during index store generation",
+    )
+    parser.add_argument(
+        "-json-error-output-path",
+        help="Path to write error output in JSON format",
+    )
+    parser.add_argument(
+        "-remove-module-prefixes",
+        action="store_true",
+        help="Hack to remove module prefixes from swiftinterface output",
+    )
+    parser.add_argument(
+        "-serialized-diagnostics-to-json",
+        help="Path to serialized diagnostics to JSON transformer",
+    )
+    parser.add_argument(
+        "-skip-incremental-outputs",
+        action="store_true",
+        help="Hack to skip writing incremental outputs to avoid cache invalidation",
+    )
+    parser.add_argument(
+        "--writable-incremental-paths",
+        nargs="*",
+        help="Paths that should be made writable for incremental compilation",
+    )
+    parser.add_argument(
+        "--no-file-prefix-map",
+        action="store_true",
+        help="Don't use -file-prefix-map or -coverage-prefix-map options",
+    )
+    parsed_args = parser.parse_args(wrapper_args)
+
+    if (
+        parsed_args.json_error_output_path
+        and not parsed_args.serialized_diagnostics_to_json
+    ):
+        raise RuntimeError(
+            "-json-error-output-path requires -serialized-diagnostics-to-json to transform the serialized diagnostics."
+        )
+
+    return driver_args, parsed_args
+
+
+def main():
+    env = os.environ.copy()
+    if "INSIDE_RE_WORKER" in env and _RE_TMPDIR_ENV_VAR in env:
+        # Use $TMPDIR for the module cache location. This
+        # will be set to a unique location for each RE action
+        # which will avoid sharing modules across RE actions.
+        # This is necessary as the inputs to the modules will
+        # be transient and can be removed at any point, causing
+        # module validation errors to fail builds.
+        # https://github.com/llvm/llvm-project/blob/main/clang/lib/Driver/ToolChains/Clang.cpp#L3709
+        env["CLANG_MODULE_CACHE_PATH"] = os.path.join(
+            env[_RE_TMPDIR_ENV_VAR], "buck-module-cache"
+        )
+    else:
+        # For local actions use a shared module cache location.
+        # This should be safe to share across the other local
+        # compilation actions.
+        env["CLANG_MODULE_CACHE_PATH"] = "/tmp/buck-module-cache"
+
+    # Separate the driver args from the wrapper args
+    command, wrapper_args = _parse_wrapper_args(sys.argv[1:])
+
+    # Use relative paths for debug information and index information,
+    # so we generate relocatable files.
+    #
+    # We need to use the path where the action is run (both locally and on RE),
+    # which is not known when we define the action.
+    if not wrapper_args.no_file_prefix_map:
+        command += [
+            # Macro expansions get materialized in the temporary directory, which
+            # varies between local and remote actions. For local actions this will
+            # be a subdir of the CWD, so this needs to be the first map entry.
+            # We also need this prefix for the clang module cache path if we are
+            # not using explicit modules with remote actions.
+            "-file-prefix-map",
+            f"{env.get(_RE_TMPDIR_ENV_VAR, '/tmp').rstrip('/')}=/tmp",
+            "-file-prefix-map",
+            f"{os.getcwd()}/=",
+            "-file-prefix-map",
+            f"{os.getcwd()}=.",
+        ]
+
+        # Apply a coverage prefix map for the current directory
+        # to make file path metadata relocatable stripping
+        # the current directory from it.
+        #
+        # This overrides -file-prefix-map.
+        command += [
+            "-coverage-prefix-map",
+            f"{os.getcwd()}=.",
+        ]
+
+    if wrapper_args.skip_incremental_outputs:
+        command = _process_skip_incremental_outputs(command)
+
+    writable_args = ["-emit-objc-header-path", "-emit-module-path"]
+
+    for arg in writable_args:
+        if arg in command:
+            idx = command.index(arg)
+            file_path = command[idx + 1]
+            _make_path_user_writable(file_path)
+
+    if wrapper_args.writable_incremental_paths:
+        for file_path in wrapper_args.writable_incremental_paths:
+            _make_path_user_writable(file_path)
+        output_file_map_path = command[command.index("-output-file-map") + 1]
+        with open(output_file_map_path) as f:
+            output_file_map = json.load(f)
+            for value in output_file_map.values():
+                for subkey in [
+                    "swift-dependencies",
+                    "dependencies",
+                    "emit-module-dependencies",
+                    "emit-module-diagnostics",
+                    "diagnostics",
+                    "object",
+                ]:
+                    maybe_path = value.get(subkey, None)
+                    if maybe_path:
+                        _make_path_user_writable(maybe_path)
+
+    # Ensure the directories referenced by the output file map exist.
+    # This can happen for Swift Incremental mode where there's no
+    # previous incremental action available
+    if "-output-file-map" in command:
+        with open(command[command.index("-output-file-map") + 1]) as f:
+            for entry in json.load(f).values():
+                for maybe_path in entry.values():
+                    if isinstance(maybe_path, str) and os.path.dirname(maybe_path):
+                        os.makedirs(os.path.dirname(maybe_path), exist_ok=True)
+
+    result = subprocess.run(
+        command,
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+        encoding=sys.stdout.encoding,
+        env=env,
+    )
+
+    print(result.stdout, file=sys.stdout, end="")
+    print(result.stderr, file=sys.stderr, end="")
+
+    if wrapper_args.json_error_output_path:
+        _make_path_user_writable(wrapper_args.json_error_output_path)
+        with open(wrapper_args.json_error_output_path, "w") as json_out:
+            # Don't bother running the diagnostics deserializer if compilation
+            # succeeded as the output will never be used.
+            if result.returncode == 0 or wrapper_args.ignore_errors:
+                json_out.write("[]")
+            else:
+                # Get the serialized diagnostics output from the output file map.
+                serialized_diags = _get_serialized_diagnostics_path(command)
+
+                # Convert the diagnostics to JSON for the Buck error handler.
+                subprocess.run(
+                    [wrapper_args.serialized_diagnostics_to_json, serialized_diags],
+                    stdout=json_out,
+                    check=True,
+                )
+
+    if result.returncode == 0:
+        # The Swift compiler will return an exit code of 0 and warn when it
+        # cannot write auxiliary files. Detect and error so that the action
+        # is not cached.
+        failed_write = (
+            _FILE_WRITE_FAILURE_MARKER in result.stdout
+            or _FILE_WRITE_FAILURE_MARKER in result.stderr
+        )
+        if failed_write:
+            print(
+                "Detected Swift compiler file write error but compiler exited with code 0, failing command..."
+            )
+            sys.exit(1)
+
+        # Rewrite .d files for the format that Buck requires.
+        if "-emit-dependencies" in command:
+            _rewrite_dependency_file(command, wrapper_args.dependencies_file_output)
+
+        # https://github.com/swiftlang/swift/issues/56573
+        if wrapper_args.remove_module_prefixes:
+            _remove_swiftinterface_module_prefixes(command)
+
+    if wrapper_args.ignore_errors:
+        sys.exit(0)
+    else:
+        sys.exit(result.returncode)
+
+
+_SWIFT_FILES_ARGSFILE = "_swift_srcs"
+
+
+def _process_skip_incremental_outputs(command):
+    output_file_map = command[command.index("-output-file-map") + 1]
+    output_dir = os.path.dirname(os.path.dirname(output_file_map))
+
+    module_swiftdeps = (
+        f"{output_dir}/__swift_incremental__/swiftdeps/module-build-record.priors"
+    )
+    output_file_map_content = {
+        "": {
+            "swift-dependencies": module_swiftdeps,
+        },
+    }
+
+    swift_files = _get_swift_files_to_compile(command)
+    for swift_file in swift_files:
+        file_name = swift_file.split("/")[-1]
+        output_artifact = f"{output_dir}/__swift_incremental__/objects/{file_name}.o"
+        swiftdeps_artifact = (
+            f"{output_dir}/__swift_incremental__/swiftdeps/{file_name}.swiftdeps"
+        )
+        output_file_map_content[swift_file] = {
+            "object": output_artifact,
+            "swift-dependencies": swiftdeps_artifact,
+        }
+
+    with open(output_file_map, "w") as f:
+        json.dump(output_file_map_content, f, indent=2)
+
+    return command
+
+
+def _get_swift_files_to_compile(command):
+    for arg in command:
+        if arg.endswith(_SWIFT_FILES_ARGSFILE):
+            path = arg[1:]  # Remove leading @
+            with open(path) as swift_files:
+                return [
+                    line.rstrip().strip('"').strip("'")
+                    for line in swift_files.readlines()
+                ]
+
+    raise Exception(f"No {_SWIFT_FILES_ARGSFILE} found!")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/tools/xcframework_maker.py b/buck2/prelude/apple/tools/xcframework_maker.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/tools/xcframework_maker.py
@@ -0,0 +1,162 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Packages given input files into the correct format for an XCFramework, and generates
+the required Info.plist.
+
+Example Usage:
+xcframework_maker.py --name FooKit --output_path /tmp/FooKit.xcframework \
+        --framework_path ios-arm64 input/ios/FooKit.xcframework \
+        --dsym_path ios-arm64 input/ios/dSYM \
+        --framework_path ios-arm64_x86_64-simulator input/ios-simulator/FooKit.xcframework \
+        --dsym_path ios-arm64_x86_64-simulator input/ios-simulator/dSYM 
+"""
+
+import argparse
+import plistlib
+import shutil
+from pathlib import Path
+from typing import Any, Optional
+
+# functions that take architecture specifiers as 'item'.
+# Examples:
+# ios-arm64_x86_64-simulator
+# -> supported platform: ios
+# -> supported architectures [arm64, x86_64]
+# -> supported platform variant: simulator
+# watchos-arm64_arm64_32
+# -> supported platform: watchos
+# -> supported architectures: [arm64, arm64_32]
+# -> supported platform variant: None
+
+
+def _supported_architectures(item: str) -> list[str]:
+    archs = []
+    # order is important so that we can
+    # consume 'arm64_32' first to prevent it
+    # later matching arm64
+    for arch in ["arm64_32", "arm64", "x86_64"]:
+        if arch in item:
+            archs.append(arch)
+            item = item.replace(arch, "")
+    return archs
+
+
+def _supported_platform(item: str) -> str:
+    return item.split("-")[0]
+
+
+def _supported_platform_variant(item: str) -> Optional[str]:
+    components = item.split("-")
+    if len(components) > 2:
+        return components[2]
+    else:
+        return None
+
+
+def _make_plist_entry(
+    item: str, binary_path: str, library_path: str, dsym_path: Optional[str]
+) -> dict[str, Any]:
+    entry = {
+        "BinaryPath": binary_path,
+        "LibraryIdentifier": item,
+        "LibraryPath": library_path,
+        "SupportedArchitectures": _supported_architectures(item),
+        "SupportedPlatform": _supported_platform(item),
+    }
+    variant = _supported_platform_variant(item)
+    if variant is not None:
+        entry["SupportedPlatformVariant"] = variant
+
+    if dsym_path is not None:
+        entry["DebugSymbolsPath"] = dsym_path
+
+    return entry
+
+
+def _make_plist(
+    items: list[str],
+    binary_paths: list[str],
+    library_path: str,
+    dsym_paths: list[Optional[str]],
+) -> bytes:
+    d = {}
+    d["AvailableLibraries"] = [
+        _make_plist_entry(item, binary_path, library_path, dsym_path)
+        for (item, binary_path, dsym_path) in zip(items, binary_paths, dsym_paths)
+    ]
+    d["CFBundlePackageType"] = "XFWK"
+    d["XCFrameworkFormatVersion"] = "1.0"
+    return plistlib.dumps(d)
+
+
+def _find_binary_path(framework_fullpath: str, binary_name: str) -> str:
+    fullpath = Path(framework_fullpath)
+    versioned_binary_paths = sorted(fullpath.glob("Versions/Current/" + binary_name))
+    if len(versioned_binary_paths) > 0:
+        return versioned_binary_paths[-1].relative_to(fullpath.parents[0]).as_posix()
+    return fullpath.name + "/" + binary_name
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(description="Tool to make an xcframework bundle.")
+    parser.add_argument("--output-path")
+    parser.add_argument("--name")
+    parser.add_argument("--framework-path", action="append", nargs="+")
+    parser.add_argument(
+        "--dsym-path", action="append", nargs="+", default=[], required=False
+    )
+    args = parser.parse_args()
+
+    out_path = Path(args.output_path)
+    out_path.mkdir(parents=True, exist_ok=False)
+
+    plist_path = out_path / "Info.plist"
+    items = [fp_args[0] for fp_args in args.framework_path]
+    binary_paths = []
+    dsym_path_map = {}
+
+    for framework_path in args.framework_path:
+        # args are structured like this
+        # --framework_path ios-arm64 buck-out/path/to/MyPkg.framework
+
+        framework_arch = framework_path[0]
+        framework_fullpath = framework_path[1]
+        framework_basename = Path(framework_fullpath).name
+
+        shutil.copytree(
+            framework_fullpath,
+            out_path / framework_arch / framework_basename,
+            symlinks=True,
+            dirs_exist_ok=False,
+        )
+
+        binary_paths.append(_find_binary_path(framework_fullpath, args.name))
+
+    for dsym_path in args.dsym_path:
+        dsym_arch = dsym_path[0]
+        dsym_fullpath = dsym_path[1]
+        shutil.copytree(
+            dsym_fullpath,
+            out_path / dsym_arch / "dSYMs" / (args.name + ".framework.dSYM"),
+            symlinks=True,
+            dirs_exist_ok=False,
+        )
+        dsym_path_map[dsym_arch] = "dSYMs"
+
+    dsym_paths = [dsym_path_map.get(arch) for arch in items]
+
+    library_path = args.name + ".framework"
+    plist_path.write_bytes(_make_plist(items, binary_paths, library_path, dsym_paths))
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/apple/user/apple_ipa_package.bzl b/buck2/prelude/apple/user/apple_ipa_package.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/apple_ipa_package.bzl
@@ -0,0 +1,286 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_bundle_destination.bzl", "AppleBundleDestination", "bundle_relative_path_for_destination")
+load("@prelude//apple:apple_bundle_types.bzl", "AppleBundleInfo", "ApplePackageExtension")
+load("@prelude//apple:apple_common.bzl", "apple_common")
+load("@prelude//apple:apple_package_config.bzl", "IpaCompressionLevel")
+load("@prelude//apple:apple_rules_impl_utility.bzl", "get_apple_bundle_toolchain_attr")
+load("@prelude//apple:apple_sdk.bzl", "get_apple_sdk_name")
+load("@prelude//apple:apple_swift_stdlib.bzl", "should_copy_swift_stdlib")
+load("@prelude//apple:debug.bzl", "AppleDebuggableInfo")
+load("@prelude//apple/swift:swift_toolchain_types.bzl", "SwiftToolchainInfo")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+
+# Produced by the `apple_app_symbols` target. It carries the App Store `<UUID>.symbols`
+# directory and the Swift stdlib dir.
+AppleAppSymbolsInfo = provider(
+    fields = {
+        "swift_support_dir": provider_field(Artifact | None, default = None),
+        "symbols_dir": provider_field(Artifact),
+    },
+)
+
+def apple_ipa_package_impl(ctx: AnalysisContext) -> list[Provider]:
+    ipa_package = _get_ipa_contents(ctx)
+    return [DefaultInfo(default_output = ipa_package)]
+
+def apple_ipa_package_attribs():
+    attribs = {
+        "bundle": attrs.dep(providers = [AppleBundleInfo]),
+        "ext": attrs.enum(ApplePackageExtension.values(), default = "ipa"),
+        "include_app_symbols": attrs.bool(default = False),
+        "labels": attrs.list(attrs.string(), default = []),
+        "package_name": attrs.option(attrs.string(), default = None),
+        "_app_symbols": attrs.option(attrs.dep(providers = [AppleAppSymbolsInfo]), default = None),
+        "_apple_toolchain": get_apple_bundle_toolchain_attr(),
+        "_ipa_compression_level": attrs.enum(IpaCompressionLevel.values()),
+    }
+    attribs.update(apple_common.apple_tools_arg())
+    return attribs
+
+_IPA_PACKAGE_FORWARDED_FIELDS = [
+    "bundle",
+    "ext",
+    "include_app_symbols",
+    "package_name",
+    "_ipa_compression_level",
+    "compatible_with",
+    "exec_compatible_with",
+    "target_compatible_with",
+    "default_target_platform",
+    "within_view",
+    "visibility",
+]
+
+def make_apple_ipa_package_target(apple_ipa_package_rule, **kwargs) -> [None, str]:
+    ipa_package_kwargs = {
+        "labels": ["generated"],
+    }
+    for field_name in _IPA_PACKAGE_FORWARDED_FIELDS:
+        ipa_package_kwargs[field_name] = kwargs.get(field_name)
+
+    # Only define the symbols target when app symbols are requested, either when set to
+    # True or we have a select to evaluate.
+    if kwargs.get("include_app_symbols"):
+        app_symbols_target_name = kwargs["name"] + "__AppSymbols_Private"
+        apple_app_symbols_rule(
+            name = app_symbols_target_name,
+            bundle = kwargs.get("bundle"),
+            include_app_symbols = kwargs.get("include_app_symbols"),
+            labels = ["generated"],
+            exec_compatible_with = ["config//os:macos"],
+            compatible_with = kwargs.get("compatible_with"),
+            target_compatible_with = kwargs.get("target_compatible_with"),
+            default_target_platform = kwargs.get("default_target_platform"),
+            within_view = kwargs.get("within_view"),
+            visibility = kwargs.get("visibility"),
+        )
+        ipa_package_kwargs["_app_symbols"] = ":{}".format(app_symbols_target_name)
+
+    ipa_package_target_name = kwargs["name"] + "__IPA_Package_Private"
+    apple_ipa_package_rule(name = ipa_package_target_name, **ipa_package_kwargs)
+
+    return ":{}".format(ipa_package_target_name)
+
+def _get_ipa_contents(ctx: AnalysisContext) -> Artifact:
+    bundle = ctx.attrs.bundle
+    app = bundle[DefaultInfo].default_outputs[0]
+
+    contents = {
+        paths.join("Payload", app.basename): app,
+    }
+
+    apple_bundle_info = bundle[AppleBundleInfo]
+    swift_needed = (not apple_bundle_info.skip_copying_swift_stdlib) and should_copy_swift_stdlib(app.extension)
+
+    app_symbols_info = ctx.attrs._app_symbols[AppleAppSymbolsInfo] if ctx.attrs._app_symbols else None
+    if ctx.attrs.include_app_symbols and app_symbols_info != None:
+        # App symbols requested: the macOS-only apple_app_symbols target already
+        # produced the Swift stdlib dir (computed once, there) and the populated
+        # Symbols/ dir. Copy both in; no Mac-only action runs in this rule.
+        if swift_needed:
+            contents[paths.join("SwiftSupport", get_apple_sdk_name(ctx))] = app_symbols_info.swift_support_dir
+        contents["Symbols"] = app_symbols_info.symbols_dir
+    else:
+        if swift_needed:
+            contents[paths.join("SwiftSupport", get_apple_sdk_name(ctx))] = _get_swift_support_dir(ctx, app, apple_bundle_info)
+
+        # watchOS IPAs require a top-level (possibly empty) Symbols/ dir to exist.
+        if apple_bundle_info.contains_watchapp:
+            contents["Symbols"] = _empty_symbols_dir(ctx)
+
+    return ctx.actions.copied_dir(
+        "__unzipped_ipa_contents__",
+        contents,
+        has_content_based_path = False,
+    )
+
+def _empty_symbols_dir(ctx) -> Artifact:
+    symbols_dir = ctx.actions.declare_output("__symbols__", dir = True, has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(["mkdir", "-p", symbols_dir.as_output()]),
+        category = "watchos_symbols_dir",
+    )
+    return symbols_dir
+
+def _apple_app_symbols_impl(ctx: AnalysisContext) -> list[Provider]:
+    bundle = ctx.attrs.bundle
+    app = bundle[DefaultInfo].default_outputs[0]
+    apple_bundle_info = bundle[AppleBundleInfo]
+
+    # When include_app_symbols resolves False for this configuration, produce an
+    # empty dir (unconsumed by the IPA package, so its action never runs) and skip
+    # the Swift stdlib work — the IPA package computes Swift support itself in that
+    # path, so the stdlib tool is still only ever run once.
+    if not ctx.attrs.include_app_symbols:
+        symbols_dir = _empty_symbols_dir(ctx)
+        return [
+            DefaultInfo(default_output = symbols_dir),
+            AppleAppSymbolsInfo(symbols_dir = symbols_dir),
+        ]
+
+    swift_support_dir = None
+    if (not apple_bundle_info.skip_copying_swift_stdlib) and should_copy_swift_stdlib(app.extension):
+        swift_support_dir = _get_swift_support_dir(ctx, app, apple_bundle_info)
+
+    symbols_dir = _build_app_symbols_dir(ctx, swift_support_dir)
+    return [
+        DefaultInfo(default_output = symbols_dir),
+        AppleAppSymbolsInfo(
+            symbols_dir = symbols_dir,
+            swift_support_dir = swift_support_dir,
+        ),
+    ]
+
+def _build_app_symbols_dir(ctx, swift_support_dir) -> Artifact:
+    # Emit one <UUID>.symbols per Mach-O slice from the bundle's dSYMs (and bundled
+    # Swift stdlib dylibs).
+    symbols_dir = ctx.actions.declare_output("__symbols__", dir = True, has_content_based_path = False)
+    dsyms = ctx.attrs.bundle[AppleDebuggableInfo].dsyms
+
+    script_lines = [
+        cmd_args("set -euo pipefail"),
+        cmd_args(symbols_dir, format = "mkdir -p {}"),
+    ]
+    symbol_inputs = []
+    if dsyms:
+        script_lines.append(
+            cmd_args(
+                ["symbols", "-arch", "all", "-symbolsPackageDir", symbols_dir] + dsyms,
+                delimiter = " ",
+                quote = "shell",
+            )
+        )
+        symbol_inputs.extend(dsyms)
+    if swift_support_dir != None:
+        script_lines.append(
+            cmd_args(
+                [
+                    "symbols",
+                    "-arch",
+                    "all",
+                    "-symbolsPackageDir",
+                    symbols_dir,
+                    cmd_args(swift_support_dir, format = "{}/*"),
+                    "||",
+                    "echo",
+                    "'warning: swift stdlib symbols packaging failed'",
+                    ">&2",
+                ],
+                delimiter = " ",
+                quote = "shell",
+            )
+        )
+        symbol_inputs.append(swift_support_dir)
+
+    script, _ = ctx.actions.write(
+        "build_app_symbols.sh",
+        script_lines,
+        allow_args = True,
+        has_content_based_path = False,
+    )
+    ctx.actions.run(
+        cmd_args(["/bin/sh", script], hidden = symbol_inputs + [symbols_dir.as_output()]),
+        category = "app_symbols_dir",
+    )
+
+    return symbols_dir
+
+apple_app_symbols_rule = rule(
+    impl = _apple_app_symbols_impl,
+    attrs = {
+        "bundle": attrs.dep(providers = [AppleBundleInfo, AppleDebuggableInfo]),
+        "include_app_symbols": attrs.bool(default = False),
+        "labels": attrs.list(attrs.string(), default = []),
+        "_apple_toolchain": get_apple_bundle_toolchain_attr(),
+    },
+)
+
+def _get_swift_support_dir(ctx, bundle_output: Artifact, bundle_info: AppleBundleInfo) -> Artifact:
+    stdlib_tool = ctx.attrs._apple_toolchain[SwiftToolchainInfo].swift_stdlib_tool
+    sdk_name = get_apple_sdk_name(ctx)
+
+    # .app -> app
+    # This is the way the input is expected.
+    extension = bundle_output.extension[1:]
+    swift_support_dir = ctx.actions.declare_output("__swift_dylibs__", dir = True, has_content_based_path = False)
+    script, _ = ctx.actions.write(
+        "build_swift_support.sh",
+        [
+            cmd_args("set -euo pipefail"),
+            cmd_args(swift_support_dir, format = "mkdir -p {}"),
+            cmd_args(
+                [
+                    stdlib_tool,
+                    # If you're debugging, you can pass the '--verbose' flag here.
+                    "--copy",
+                    "--scan-executable",
+                    cmd_args(
+                        [
+                            bundle_output,
+                            bundle_relative_path_for_destination(AppleBundleDestination("executables"), sdk_name, extension, False),
+                            bundle_info.binary_name,
+                        ],
+                        delimiter = "/",
+                    ),
+                    _get_scan_folder_args(AppleBundleDestination("plugins"), bundle_output, sdk_name, extension),
+                    _get_scan_folder_args(AppleBundleDestination("extensionkit_extensions"), bundle_output, sdk_name, extension),
+                    _get_scan_folder_args(AppleBundleDestination("frameworks"), bundle_output, sdk_name, extension),
+                    _get_scan_folder_args(AppleBundleDestination("appclips"), bundle_output, sdk_name, extension),
+                    "--destination",
+                    swift_support_dir,
+                ],
+                delimiter = " ",
+                quote = "shell",
+            ),
+        ],
+        allow_args = True,
+        has_content_based_path = False,
+    )
+    ctx.actions.run(
+        cmd_args(["/bin/sh", script], hidden = [stdlib_tool, bundle_output, swift_support_dir.as_output()]),
+        category = "copy_swift_stdlibs",
+    )
+
+    return swift_support_dir
+
+def _get_scan_folder_args(dest: AppleBundleDestination, bundle_output: Artifact, sdk_name, extension) -> ArgLike:
+    return cmd_args(
+        [
+            "--scan-folder",
+            cmd_args(
+                [
+                    bundle_output,
+                    bundle_relative_path_for_destination(dest, sdk_name, extension, False),
+                ],
+                delimiter = "/",
+            ),
+        ],
+    )
diff --git a/buck2/prelude/apple/user/apple_macos_bundle.bzl b/buck2/prelude/apple/user/apple_macos_bundle.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/apple_macos_bundle.bzl
@@ -0,0 +1,14 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_bundle.bzl", "apple_bundle_impl")
+
+def apple_macos_bundle_impl(ctx: AnalysisContext) -> list[Provider]:
+    # This rule is _equivalent_ to `apple_bundle` except it applies
+    # an incoming macOS transition.
+    return apple_bundle_impl(ctx)
diff --git a/buck2/prelude/apple/user/apple_resource_bundle.bzl b/buck2/prelude/apple/user/apple_resource_bundle.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/apple_resource_bundle.bzl
@@ -0,0 +1,48 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//apple:apple_bundle_resources.bzl",
+    "AppleBundleResourcePartListOutput",  # @unused Used as a type
+    "get_apple_bundle_resource_part_list",
+)
+load("@prelude//apple:apple_bundle_types.bzl", "AppleBundleResourceInfo")
+
+def _extract_all_resources(part_list: AppleBundleResourcePartListOutput) -> list[Artifact]:
+    all_resources = [resource_bundle_part.source for resource_bundle_part in part_list.resource_parts]
+    all_resources.append(part_list.info_plist_part.source)
+    return all_resources
+
+def apple_resource_bundle_impl(ctx: AnalysisContext) -> list[Provider]:
+    resource_output = get_apple_bundle_resource_part_list(ctx)
+
+    all_resources = _extract_all_resources(resource_output)
+    all_resources_json = {"resources": all_resources}
+    all_resources_json_file = ctx.actions.declare_output("resources.json", has_content_based_path = False)
+    all_resources_json_cmd_args = ctx.actions.write_json(
+        all_resources_json_file,
+        all_resources_json,
+        with_inputs = True,
+        pretty = True,
+    )
+
+    return [
+        DefaultInfo(
+            sub_targets = {
+                "resources": [
+                    DefaultInfo(
+                        default_output = all_resources_json_file,
+                        other_outputs = [all_resources_json_cmd_args],
+                    )
+                ],
+            }
+        ),
+        AppleBundleResourceInfo(
+            resource_output = resource_output,
+        ),
+    ]
diff --git a/buck2/prelude/apple/user/apple_resource_transition.bzl b/buck2/prelude/apple/user/apple_resource_transition.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/apple_resource_transition.bzl
@@ -0,0 +1,41 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _is_universal(platform: PlatformInfo, refs: struct) -> bool:
+    universal = platform.configuration.constraints.get(refs.universal[ConstraintSettingInfo].label)
+    return universal.label == refs.universal_enabled[ConstraintValueInfo].label if universal != None else False
+
+def _apple_resource_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:
+    if attrs.skip_universal_resource_dedupe or not _is_universal(platform, refs):
+        return platform
+    else:
+        cpu_constraint_label = refs.cpu[ConstraintSettingInfo].label
+        filtered_constraints = {
+            constraint_setting_label: constraint_setting_value
+            for (constraint_setting_label, constraint_setting_value) in platform.configuration.constraints.items()
+            if constraint_setting_label != cpu_constraint_label
+        }
+        return PlatformInfo(
+            label = "apple_universal_deduped_resource",
+            configuration = ConfigurationInfo(
+                constraints = filtered_constraints,
+                values = platform.configuration.values,
+            ),
+        )
+
+apple_resource_transition = transition(
+    impl = _apple_resource_transition_impl,
+    refs = {
+        "cpu": "config//cpu/constraints:cpu",
+        "universal": "config//cpu/constraints:universal",
+        "universal_enabled": "config//cpu/constraints:universal-enabled",
+    },
+    attrs = [
+        "skip_universal_resource_dedupe",
+    ],
+)
diff --git a/buck2/prelude/apple/user/apple_selected_debug_path_file.bzl b/buck2/prelude/apple/user/apple_selected_debug_path_file.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/apple_selected_debug_path_file.bzl
@@ -0,0 +1,11 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# The file name used to store the user's selected debug path in selective debugging
+# Will save to the root of app bundle
+SELECTED_DEBUG_PATH_FILE_NAME = "SelectedDebugPaths.txt"
diff --git a/buck2/prelude/apple/user/apple_selective_debugging.bzl b/buck2/prelude/apple/user/apple_selective_debugging.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/apple_selective_debugging.bzl
@@ -0,0 +1,350 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactInfo",
+    "ArtifactInfoTag",
+)
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo", "AppleToolsInfo")
+load(
+    "@prelude//linking:execution_preference.bzl",
+    "LinkExecutionPreference",
+    "LinkExecutionPreferenceDeterminatorInfo",
+    "LinkExecutionPreferenceInfo",  # @unused Used as a type
+    "get_action_execution_attributes",
+)
+load(
+    "@prelude//utils:build_target_pattern.bzl",
+    "BuildTargetPattern",  # @unused Used as a type
+    "parse_build_target_pattern",
+)
+load("@prelude//utils:lazy.bzl", "lazy")
+
+_SelectionCriteria = record(
+    include_build_target_patterns = field(list[BuildTargetPattern], []),
+    include_regular_expressions = field(list[regex], []),
+    exclude_build_target_patterns = field(list[BuildTargetPattern], []),
+    exclude_regular_expressions = field(list[regex], []),
+)
+
+AppleSelectiveDebuggingInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "scrub_binary": provider_field(typing.Callable),
+        "filter": provider_field(typing.Callable),
+        "scrub_selected_debug_paths_file": provider_field(typing.Callable),
+    },
+)
+
+AppleSelectiveDebuggingFilteredDebugInfo = record(
+    # Contains all artifacts, including those required for debugging (e.g., `.swiftmodule` files)
+    infos = field(list[ArtifactInfo]),
+    # Contains only artifacts for _selected_ targets, excluding any others
+    selected_target_infos = field(list[ArtifactInfo]),
+    swift_modules_labels = field(list[Label]),
+    metadata = field(Artifact),
+)
+
+# The type of selective debugging json input to utilze.
+SelectiveDebuggingJsonTypes = [
+    # Use a targets json file containing all targets to include.
+    "targets",
+    # Use a spec json file specifying the targets to include
+    # and exclude via build target patterns and regular expressions.
+    "spec",
+]
+
+_SelectiveDebuggingJsonType = enum(*SelectiveDebuggingJsonTypes)
+
+_LOCAL_LINK_THRESHOLD = 0.2
+
+_OBJECT_FILE_EXTENSIONS = [
+    ".o",
+    ".a",
+]
+
+def _apple_skip_adhoc_resigning_scrubbed_frameworks_attr_value(bundle_ctx: AnalysisContext) -> bool:
+    override_value = bundle_ctx.attrs._skip_adhoc_resigning_scrubbed_frameworks_override
+    if override_value != None:
+        # Override takes precedence over any other value
+        return override_value
+
+    skip = bundle_ctx.attrs.skip_adhoc_resigning_scrubbed_frameworks
+    return skip if skip != None else bundle_ctx.attrs._skip_adhoc_resigning_scrubbed_frameworks_default
+
+def _should_skip_adhoc_sign_after_scrubbing(bundle_ctx: AnalysisContext) -> bool:
+    sdk_name = bundle_ctx.attrs._apple_toolchain[AppleToolchainInfo].sdk_name
+    if bundle_ctx.attrs.extension == "framework" and "iphonesimulator" in sdk_name:
+        # While scrubbing invalidates the code signature, the signature of frameworks
+        # are generally not checked by the system (unless running against the hardened
+        # runtime for macOS apps). Re-signing scrubbed frameworks can take non-trivial
+        # time, so skip it if it's not needed.
+        return _apple_skip_adhoc_resigning_scrubbed_frameworks_attr_value(bundle_ctx)
+    return False
+
+def _generate_metadata_json_object(is_any_selected_target_linked: bool) -> dict[str, typing.Any]:
+    return {
+        "contains_focused_targets": is_any_selected_target_linked,
+    }
+
+def apple_selective_debugging_impl(ctx: AnalysisContext) -> list[Provider]:
+    json_type = _SelectiveDebuggingJsonType(ctx.attrs.json_type)
+
+    # process inputs and provide them up the graph with typing
+    include_build_target_patterns = [parse_build_target_pattern(pattern) for pattern in ctx.attrs.include_build_target_patterns]
+    include_regular_expressions = [
+        # TODO(nga): fancy is probably not needed here.
+        regex(expression, fancy = True)
+        for expression in ctx.attrs.include_regular_expressions
+    ]
+    exclude_build_target_patterns = [parse_build_target_pattern(pattern) for pattern in ctx.attrs.exclude_build_target_patterns]
+    exclude_regular_expressions = [
+        # TODO(nga): fancy is probably not needed here.
+        regex(expression, fancy = True)
+        for expression in ctx.attrs.exclude_regular_expressions
+    ]
+
+    scrubber = ctx.attrs._apple_tools[AppleToolsInfo].selective_debugging_scrubber
+
+    targets_json_file = None
+    cmd = cmd_args(scrubber)
+    if json_type == _SelectiveDebuggingJsonType("targets"):
+        targets_json_file = ctx.attrs.targets_json_file or ctx.actions.write_json("targets.json", {"targets": []}, has_content_based_path = False)
+
+        # If a targets json file is not provided, write an empty json file:
+        cmd.add("--targets-file")
+        cmd.add(targets_json_file)
+    elif json_type == _SelectiveDebuggingJsonType("spec"):
+        json_data = {
+            "exclude_build_target_patterns": ctx.attrs.exclude_build_target_patterns,
+            "exclude_regular_expressions": ctx.attrs.exclude_regular_expressions,
+            "include_build_target_patterns": ctx.attrs.include_build_target_patterns,
+            "include_regular_expressions": ctx.attrs.include_regular_expressions,
+        }
+        spec_file = ctx.actions.write_json("selective_debugging_spec.json", json_data, has_content_based_path = False)
+        cmd.add("--spec-file")
+        cmd.add(spec_file)
+    else:
+        fail("Expected json_type to be either `targets` or `spec`.")
+
+    selection_criteria = _SelectionCriteria(
+        include_build_target_patterns = include_build_target_patterns,
+        include_regular_expressions = include_regular_expressions,
+        exclude_build_target_patterns = exclude_build_target_patterns,
+        exclude_regular_expressions = exclude_regular_expressions,
+    )
+
+    def scrub_selected_debug_paths_file(inner_ctx: AnalysisContext, package_names: list[str], output_name: str) -> Artifact:
+        # In the event that _SelectiveDebuggingJsonType was "spec", we expect that `package_names`
+        # was already filtered as part of scrubbing the binary in the apple_bundle.
+        #
+        # See `_maybe_scrub_binary()` in apple_bundle.bzl
+        if json_type != _SelectiveDebuggingJsonType("targets"):
+            return inner_ctx.actions.write(output_name, sorted(set(package_names)), has_content_based_path = False)
+
+        def scrub_selected_debug_paths_action(dynamic_ctx: AnalysisContext, artifacts, outputs):
+            packages = [
+                # "cell//path/to/some/thing:target" -> "path/to/some/thing"
+                target.split("//")[1].split(":")[0]
+                for target in artifacts[targets_json_file].read_json()["targets"]
+            ]
+            dynamic_ctx.actions.write(
+                outputs.values()[0],
+                sorted(set(filter(lambda p: p in packages, package_names))),
+            )
+
+        output = inner_ctx.actions.declare_output(output_name, has_content_based_path = False)
+        inner_ctx.actions.dynamic_output(
+            dynamic = [targets_json_file],
+            inputs = [],
+            outputs = [output.as_output()],
+            f = scrub_selected_debug_paths_action,
+        )
+
+        return output
+
+    def scrub_binary(
+        inner_ctx,
+        executable: Artifact,
+        executable_link_execution_preference: LinkExecutionPreference,
+        adhoc_codesign_tool: [RunInfo, None],
+        focused_targets_labels: list[Label],
+        identifier: None | str = None,
+    ) -> Artifact:
+        inner_cmd = cmd_args(cmd)
+        subdir = "{}/".format(identifier) if identifier else ""
+        output = inner_ctx.actions.declare_output("debug_scrubbed/{}{}".format(subdir, executable.short_path), has_content_based_path = False)
+
+        action_execution_properties = get_action_execution_attributes(executable_link_execution_preference)
+
+        # If we're provided a codesign tool, provider it to the scrubber binary so that it may sign
+        # the binary after scrubbing.
+        if adhoc_codesign_tool and (not _should_skip_adhoc_sign_after_scrubbing(inner_ctx)):
+            inner_cmd.add(["--adhoc-codesign-tool", adhoc_codesign_tool])
+        inner_cmd.add(["--input", executable])
+        inner_cmd.add(["--output", output.as_output()])
+        if len(focused_targets_labels) > 0:
+            additional_labels_json = inner_ctx.actions.write_json(
+                inner_ctx.attrs.name + ".additional_labels.json",
+                {"targets": [label.raw_target() for label in focused_targets_labels]},
+                has_content_based_path = False,
+            )
+            inner_cmd.add(["--persisted-targets-file", additional_labels_json])
+        inner_ctx.actions.run(
+            inner_cmd,
+            category = "scrub_binary",
+            identifier = output.short_path,
+            prefer_local = action_execution_properties.prefer_local,
+            prefer_remote = action_execution_properties.prefer_remote,
+            local_only = action_execution_properties.local_only,
+            force_full_hybrid_if_capable = action_execution_properties.full_hybrid,
+        )
+        return output
+
+    def filter_debug_info(inner_ctx: AnalysisContext, debug_info: TransitiveSetIterator) -> AppleSelectiveDebuggingFilteredDebugInfo:
+        artifact_infos = []
+        selected_target_infos = []
+        linked_targets = set()
+        is_any_selected_target_linked = False
+        is_using_spec = json_type == _SelectiveDebuggingJsonType("spec")
+        selected_targets_contain_swift = False
+        for infos in debug_info:
+            for info in infos:
+                is_swift_debug_info = ArtifactInfoTag("swift_debug_info") in info.tags
+                is_label_included = _is_label_included(info.label, selection_criteria)
+
+                is_any_selected_target_linked_when_using_spec = is_using_spec and is_any_selected_target_linked
+                if not is_any_selected_target_linked_when_using_spec:
+                    # When using spec mode and there's already a selected target, there's no need
+                    # to continue the search whether a selected target is linked - we know at least
+                    # one is already linked. So, the if statement acts as a short-circuit for perf
+                    # reasons to avoid unnecessary work.
+                    #
+                    # In targets mode (i.e., non-spec mode), the full list of `linked_targets` must
+                    # be computed, as that value is used behind a dynamic output, so it's not possible
+                    # terminate the search early (as we cannot determine whether a selected target is linked
+                    # as the list of selected targets is stored in the targets JSON file, which is not available
+                    # at analysis time, only avail behind a dynamic output).
+                    debug_artifact_contains_object_code = lazy.is_any(
+                        lambda debug_artifact: debug_artifact.extension in _OBJECT_FILE_EXTENSIONS, info.artifacts
+                    )
+                    if debug_artifact_contains_object_code:
+                        if is_using_spec and is_label_included:
+                            is_any_selected_target_linked = True
+                        if not is_using_spec:
+                            # `linked_targets` only used in targets mode, avoid costs in all other modes
+                            linked_targets.add(info.label)
+
+                if is_label_included:
+                    # `selected_target_infos` should only include targets explicitly selected by the user,
+                    # not anything included in addition to support the debugger (e.g., `.swiftmodule` files)
+                    selected_target_infos.append(info)
+                if is_label_included or (selected_targets_contain_swift and is_swift_debug_info):
+                    # There might be a few ArtifactInfo corresponding to the same Label,
+                    # so to avoid overwriting, we need to preserve all artifacts.
+                    artifact_infos.append(info)
+                    selected_targets_contain_swift = selected_targets_contain_swift or ArtifactInfoTag("swift_debug_info") in info.tags
+
+        if json_type == _SelectiveDebuggingJsonType("spec"):
+            metadata_output = inner_ctx.actions.write_json(
+                "selective_metadata_with_spec.json",
+                _generate_metadata_json_object(is_any_selected_target_linked),
+                pretty = True,
+                has_content_based_path = False,
+            )
+        elif json_type == _SelectiveDebuggingJsonType("targets"):
+
+            def generate_metadata_output(dynamic_ctx: AnalysisContext, artifacts, outputs):
+                targets = artifacts[targets_json_file].read_json()["targets"]
+                is_any_selected_target_linked_inner = False
+                for target in targets:
+                    cell, package_with_target_name = target.split("//")
+                    package, target_name = package_with_target_name.split(":")
+
+                    is_any_selected_target_linked_inner = lazy.is_any(
+                        lambda linked_target: linked_target.cell == cell and linked_target.package == package and linked_target.name == target_name,
+                        linked_targets,
+                    )
+                    if is_any_selected_target_linked_inner:
+                        break
+
+                dynamic_ctx.actions.write_json(
+                    outputs.values()[0],
+                    _generate_metadata_json_object(is_any_selected_target_linked_inner),
+                    pretty = True,
+                )
+
+            metadata_output = inner_ctx.actions.declare_output("selective_metadata_with_targets_file.json", has_content_based_path = False)
+            inner_ctx.actions.dynamic_output(
+                dynamic = [targets_json_file],
+                inputs = [],
+                outputs = [metadata_output.as_output()],
+                f = generate_metadata_output,
+            )
+        else:
+            fail("Unexpected type: {}".format(json_type))
+
+        return AppleSelectiveDebuggingFilteredDebugInfo(
+            infos = artifact_infos,
+            selected_target_infos = selected_target_infos,
+            swift_modules_labels = [],
+            metadata = metadata_output,
+        )
+
+    def preference_for_links(links: list[Label], deps_preferences: list[LinkExecutionPreferenceInfo]) -> LinkExecutionPreference:
+        # If any dependent links were run locally, prefer that the current link is also performed locally,
+        # to avoid needing to upload the previous link.
+        dep_prefered_local = lazy.is_any(lambda info: info.preference == LinkExecutionPreference("local"), deps_preferences)
+        if dep_prefered_local:
+            return LinkExecutionPreference("local")
+
+        # If we're not provided a list of links, we can't make an informed determination.
+        if not links:
+            return LinkExecutionPreference("any")
+
+        matching_links = filter(None, [link for link in links if _is_label_included(link, selection_criteria)])
+
+        # If more than 20% of targets being linked are also downloaded for debugging, perform the
+        # link locally, as we'd need to download the object files anyway (and can skip downloading the link output).
+        # Otherwise, perform the link remotely, and we'll just download the debug data separately.
+        if len(matching_links) / len(links) >= _LOCAL_LINK_THRESHOLD:
+            return LinkExecutionPreference("local")
+        return LinkExecutionPreference("remote")
+
+    return [
+        DefaultInfo(),
+        AppleSelectiveDebuggingInfo(
+            scrub_binary = scrub_binary,
+            filter = filter_debug_info,
+            scrub_selected_debug_paths_file = scrub_selected_debug_paths_file,
+        ),
+        LinkExecutionPreferenceDeterminatorInfo(preference_for_links = preference_for_links),
+    ]
+
+def _is_label_included(label: Label, selection_criteria: _SelectionCriteria) -> bool:
+    # If no include criteria are provided, we then include everything, as long as it is not excluded.
+    if selection_criteria.include_build_target_patterns or selection_criteria.include_regular_expressions:
+        if not _check_if_label_matches_patterns_or_expressions(
+            label, selection_criteria.include_build_target_patterns, selection_criteria.include_regular_expressions
+        ):
+            return False
+
+    # If included (above snippet), ensure that this target is not excluded.
+    return not _check_if_label_matches_patterns_or_expressions(
+        label, selection_criteria.exclude_build_target_patterns, selection_criteria.exclude_regular_expressions
+    )
+
+def _check_if_label_matches_patterns_or_expressions(label: Label, patterns: list[BuildTargetPattern], expressions: list[regex]) -> bool:
+    for pattern in patterns:
+        if pattern.matches(label):
+            return True
+    for expression in expressions:
+        if expression.match(str(label)):
+            return True
+    return False
diff --git a/buck2/prelude/apple/user/apple_spm_package.bzl b/buck2/prelude/apple/user/apple_spm_package.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/apple_spm_package.bzl
@@ -0,0 +1,38 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")
+load("@prelude//apple/user:apple_xcframework.bzl", "XCFrameworkInfo")
+load("@prelude//utils:utils.bzl", "flatten")
+
+def apple_spm_package_impl(ctx: AnalysisContext) -> list[Provider]:
+    apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]
+
+    spm_packager = apple_tools.spm_packager
+
+    output_dir = ctx.actions.declare_output(ctx.attrs.name, dir = True, has_content_based_path = False)
+
+    xcframework_binaries = [dep for dep in ctx.attrs.deps if dep.get(XCFrameworkInfo)]
+    binary_args = flatten([["--xcframework", dep[XCFrameworkInfo].name, dep[DefaultInfo].default_outputs[0]] for dep in xcframework_binaries])
+
+    spm_command = cmd_args(
+        [
+            spm_packager,
+            "--output-path",
+            output_dir.as_output(),
+            "--package-name",
+            ctx.attrs.package_name,
+        ]
+        + binary_args
+    )
+
+    ctx.actions.run(spm_command, category = "assemble_spm_package")
+
+    return [
+        DefaultInfo(default_output = output_dir),
+    ]
diff --git a/buck2/prelude/apple/user/apple_watchos_bundle.bzl b/buck2/prelude/apple/user/apple_watchos_bundle.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/apple_watchos_bundle.bzl
@@ -0,0 +1,14 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_bundle.bzl", "apple_bundle_impl")
+
+def apple_watchos_bundle_impl(ctx: AnalysisContext) -> list[Provider]:
+    # This rule is _equivalent_ to `apple_bundle` except it applies
+    # an incoming watchOS transition.
+    return apple_bundle_impl(ctx)
diff --git a/buck2/prelude/apple/user/apple_xcframework.bzl b/buck2/prelude/apple/user/apple_xcframework.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/apple_xcframework.bzl
@@ -0,0 +1,201 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_bundle_types.bzl", "AppleBundleInfo")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")
+
+# Metadata about XCFramework
+XCFrameworkInfo = provider(
+    fields = {
+        # Name of supplied framework. For frameworks that define
+        # modules this should be the name of the module
+        "name": provider_field(str),
+    },
+)
+
+def _get_any_framework_dep(framework_deps: [dict[str, Dependency], Dependency, None]) -> [Dependency, None]:
+    if not type(framework_deps) == "dict":
+        return framework_deps
+    if len(framework_deps) == 0:
+        return None
+    return sorted(framework_deps.items())[0][1]
+
+def _get_framework_name(ctx: AnalysisContext) -> str:
+    if ctx.attrs.framework_name != None:
+        return ctx.attrs.framework_name
+    if ctx.attrs.framework_name_from_product_name:
+        framework = _get_any_framework_dep(ctx.attrs.framework)
+        if framework == None:
+            fail("Cannot find framework name")
+        return framework[AppleBundleInfo].binary_name
+    fail("Cannot find framework name")
+
+def apple_xcframework_impl(ctx: AnalysisContext) -> list[Provider]:
+    apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]
+    framework_name = _get_framework_name(ctx)
+
+    xcframework_dir = ctx.actions.declare_output(framework_name + ".xcframework", dir = True, has_content_based_path = False)
+    xcframework_command = cmd_args([
+        apple_tools.xcframework_maker,
+        "--output-path",
+        xcframework_dir.as_output(),
+        "--name",
+        framework_name,
+    ])
+
+    for arch in ctx.attrs.framework:
+        framework_dep = ctx.attrs.framework[arch]
+        framework_paths = framework_dep[DefaultInfo].default_outputs
+        if len(framework_paths) > 1:
+            fail("xcframework's framework target {} must only produce one output".format(framework_dep.label))
+
+        xcframework_command.add("--framework-path")
+        xcframework_command.add(arch)
+        xcframework_command.add(framework_paths[0])
+
+        if ctx.attrs.include_dsym:
+            dsym_dep = framework_dep[DefaultInfo].sub_targets["dsym"]
+            dsym_path = dsym_dep[DefaultInfo].default_outputs
+            xcframework_command.add("--dsym-path")
+            xcframework_command.add(arch)
+            xcframework_command.add(dsym_path)
+
+    ctx.actions.run(xcframework_command, category = "apple_xcframework")
+    return [
+        DefaultInfo(default_output = xcframework_dir),
+        XCFrameworkInfo(name = framework_name),
+    ]
+
+def _strip_os_sdk_and_runtime_constraints(platform: PlatformInfo, refs: struct) -> dict[TargetLabel, ConstraintValueInfo]:
+    return {
+        constraint_setting_label: constraint_setting_value
+        for (constraint_setting_label, constraint_setting_value) in platform.configuration.constraints.items()
+        if constraint_setting_label
+        not in [
+            refs.os[ConstraintSettingInfo].label,
+            refs.sdk[ConstraintSettingInfo].label,
+            refs.universal[ConstraintSettingInfo].label,
+            refs.runtime[ConstraintSettingInfo].label,
+        ]
+    }
+
+# provides a map of os-platform to cpu architectures
+# so we can identify when universal binaries can be created instead of
+# two separate frameworks
+#
+# e.g. input of ["ios-arm64", "iphonesimulator-x86_64", "iphonesimulator-arm64"]
+# will produce {"ios": ["arm64"], "iphonesimulator": ["arm64", "x86_64"]}
+
+def _normalize_platforms(platforms: list[str]) -> dict[str, list[str]]:
+    result = {}
+    for platform in platforms:
+        plat_list = platform.split("-")
+        plat_type = plat_list[0]
+        plat_archs = plat_list[1:]
+        previous_archs = result.get(plat_type, [])
+        result[plat_type] = sorted(plat_archs + previous_archs)
+
+    return result
+
+def _apple_xcframework_framework_attrib_split_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> dict[str, PlatformInfo]:
+    result = {}
+
+    new_platforms = _normalize_platforms(attrs.platforms).items()
+    for os_value, cpu_values in new_platforms:
+        updated_constraints = _strip_os_sdk_and_runtime_constraints(platform, refs)
+
+        canonical_platform_suffix = ""
+
+        if os_value == "macos":
+            canonical_platform_prefix = "macos"
+            updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.macos[ConstraintValueInfo]
+        elif os_value == "iphoneos":
+            canonical_platform_prefix = "ios"
+            updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.ios[ConstraintValueInfo]
+            updated_constraints[refs.sdk[ConstraintSettingInfo].label] = refs.ios_device_sdk[ConstraintValueInfo]
+        elif os_value == "watchos":
+            canonical_platform_prefix = "watchos"
+            updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.watchos[ConstraintValueInfo]
+            updated_constraints[refs.sdk[ConstraintSettingInfo].label] = refs.watchos_device_sdk[ConstraintValueInfo]
+        elif os_value == "iphonesimulator":
+            canonical_platform_prefix = "ios"
+            canonical_platform_suffix = "simulator"
+            updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.ios[ConstraintValueInfo]
+            updated_constraints[refs.sdk[ConstraintSettingInfo].label] = refs.ios_simulator_sdk[ConstraintValueInfo]
+        elif os_value == "watchossimulator":
+            canonical_platform_prefix = "watchos"
+            canonical_platform_suffix = "simulator"
+            updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.watchos[ConstraintValueInfo]
+            updated_constraints[refs.sdk[ConstraintSettingInfo].label] = refs.watchos_simulator_sdk[ConstraintValueInfo]
+        elif os_value == "maccatalyst":
+            canonical_platform_prefix = "ios"
+            canonical_platform_suffix = "maccatalyst"
+            updated_constraints[refs.os[ConstraintSettingInfo].label] = refs.ios[ConstraintValueInfo]
+            updated_constraints[refs.sdk[ConstraintSettingInfo].label] = refs.maccatalyst_sdk[ConstraintValueInfo]
+            updated_constraints[refs.runtime[ConstraintSettingInfo].label] = refs.maccatalyst_runtime[ConstraintValueInfo]
+        else:
+            fail("Unsupported OS value {} in apple_xcframework() platforms.".format(os_value))
+
+        cpu_constraint_name = refs.cpu[ConstraintSettingInfo].label
+
+        if len(cpu_values) > 1:
+            updated_constraints[refs.universal[ConstraintSettingInfo].label] = refs.universal_enabled[ConstraintValueInfo]
+        elif cpu_values[0] == "arm64":
+            updated_constraints[cpu_constraint_name] = refs.arm64[ConstraintValueInfo]
+        elif cpu_values[0] == "x86_64":
+            updated_constraints[cpu_constraint_name] = refs.x86_64[ConstraintValueInfo]
+        else:
+            fail("Unsupported CPU value {} in apple_xcframework().".format(cpu_values[0]))
+
+        new_cfg = ConfigurationInfo(
+            constraints = updated_constraints,
+            values = platform.configuration.values,
+        )
+
+        canonical_platform_name = canonical_platform_prefix + "-" + "_".join(cpu_values)
+        if len(canonical_platform_suffix) > 0:
+            canonical_platform_name += "-" + canonical_platform_suffix
+
+        result.update({
+            canonical_platform_name: PlatformInfo(
+                label = canonical_platform_name + "_transition",
+                configuration = new_cfg,
+            )
+        })
+
+    return result
+
+framework_split_transition = transition(
+    impl = _apple_xcframework_framework_attrib_split_transition_impl,
+    refs = {
+        "arm32": "config//cpu/constraints:arm32",
+        "arm64": "config//cpu/constraints:arm64",
+        "cpu": "config//cpu/constraints:cpu",
+        "ios": "config//os/constraints:iphoneos",
+        "ios_device_sdk": "config//os/sdk/apple/constraints:iphoneos",
+        "ios_simulator_sdk": "config//os/sdk/apple/constraints:iphonesimulator",
+        "maccatalyst_runtime": "config//runtime/constraints:maccatalyst",
+        "maccatalyst_sdk": "config//os/sdk/apple/constraints:maccatalyst",
+        "macos": "config//os/constraints:macos",
+        "os": "config//os/constraints:os",
+        "runtime": "config//runtime/constraints:runtime",
+        "sdk": "config//os/sdk/apple/constraints:_",
+        "swift_library_evolution": "config//features/apple/constraints:swift_library_evolution",
+        "swift_library_evolution_enabled": "config//features/apple/constraints:swift_library_evolution_enabled",
+        "universal": "config//cpu/constraints:universal",
+        "universal_enabled": "config//cpu/constraints:universal-enabled",
+        "watchos": "config//os/constraints:watchos",
+        "watchos_device_sdk": "config//os/sdk/apple/constraints:watchos",
+        "watchos_simulator_sdk": "config//os/sdk/apple/constraints:watchsimulator",
+        "x86_64": "config//cpu/constraints:x86_64",
+    },
+    attrs = [
+        "platforms",
+    ],
+    split = True,
+)
diff --git a/buck2/prelude/apple/user/cpu_split_transition.bzl b/buck2/prelude/apple/user/cpu_split_transition.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/cpu_split_transition.bzl
@@ -0,0 +1,123 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _os_constraint_value(platform: PlatformInfo, refs: struct) -> [None, ConstraintValueInfo]:
+    return platform.configuration.constraints.get(refs.os[ConstraintSettingInfo].label)
+
+def _sdk_constraint_value(platform: PlatformInfo, refs: struct) -> [None, ConstraintValueInfo]:
+    return platform.configuration.constraints.get(refs.sdk[ConstraintSettingInfo].label)
+
+def _cpu_constraint_readable_value(platform: PlatformInfo, refs: struct) -> [None, str]:
+    cpu = platform.configuration.constraints.get(refs.cpu[ConstraintSettingInfo].label)
+    if cpu == None:
+        return platform.label
+
+    if cpu.label == refs.arm64[ConstraintValueInfo].label:
+        return "arm64"
+    elif cpu.label == refs.x86_64[ConstraintValueInfo].label:
+        return "x86_64"
+    else:
+        return platform.label
+
+def _universal_constraint_value(platform: PlatformInfo, refs: struct) -> [None, bool]:
+    universal = platform.configuration.constraints.get(refs.universal[ConstraintSettingInfo].label)
+    return universal.label == refs.universal_enabled[ConstraintValueInfo].label if universal != None else False
+
+def _filter_incompatible_constraints(platform_name: str, constraints: dict[TargetLabel, ConstraintValueInfo]) -> dict[TargetLabel, ConstraintValueInfo]:
+    filtered = dict()
+    for constraint_setting_label, constraint_value_info in constraints.items():
+        incompatible_constraint_name = "//cpu/x86" if platform_name == "arm64" else "//cpu/arm"
+        if incompatible_constraint_name in str(constraint_value_info.label):
+            continue
+        filtered[constraint_setting_label] = constraint_value_info
+    return filtered
+
+def _cpu_split_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> dict[str, PlatformInfo]:
+    universal = attrs.universal if attrs.universal != None else _universal_constraint_value(platform, refs)
+    os = _os_constraint_value(platform, refs)
+    if not universal or os == None:
+        # Don't do the splitting, since we don't know what OS type this is.
+        return {_cpu_constraint_readable_value(platform, refs): platform}
+
+    os_label = os.label
+    sdk = _sdk_constraint_value(platform, refs)
+    sdk_label = sdk.label if sdk != None else None
+
+    cpu_name_to_cpu_constraint = {}
+    if os_label == refs.ios[ConstraintValueInfo].label:
+        if sdk == None or sdk_label == refs.ios_simulator_sdk[ConstraintValueInfo].label or sdk_label == refs.maccatalyst_sdk[ConstraintValueInfo].label:
+            # default to simulator if SDK is not specified
+            cpu_name_to_cpu_constraint["arm64"] = refs.arm64[ConstraintValueInfo]
+            cpu_name_to_cpu_constraint["x86_64"] = refs.x86_64[ConstraintValueInfo]
+        elif sdk_label == refs.ios_device_sdk[ConstraintValueInfo].label:
+            return {"arm64": platform}
+        else:
+            fail("Unsupported SDK {} for IPhoneOS".format(sdk_label))
+    elif os_label == refs.watchos[ConstraintValueInfo].label:
+        if sdk == None or sdk_label == refs.watchos_simulator_sdk[ConstraintValueInfo].label:
+            cpu_name_to_cpu_constraint["arm64"] = refs.arm64[ConstraintValueInfo]
+        elif sdk_label == refs.watchos_device_sdk[ConstraintValueInfo].label:
+            cpu_name_to_cpu_constraint["arm64"] = refs.arm64[ConstraintValueInfo]
+            cpu_name_to_cpu_constraint["arm64_32"] = refs.arm64_32[ConstraintValueInfo]
+        else:
+            fail("Unsupported SDK {} for WatchOS".format(sdk_label))
+    elif os_label == refs.macos[ConstraintValueInfo].label:
+        cpu_name_to_cpu_constraint["arm64"] = refs.arm64[ConstraintValueInfo]
+        cpu_name_to_cpu_constraint["x86_64"] = refs.x86_64[ConstraintValueInfo]
+    else:
+        fail("Unsupported OS: {}".format(os_label))
+
+    cpu_constraint_name = refs.cpu[ConstraintSettingInfo].label
+    base_constraints = {
+        constraint_setting_label: constraint_value_info
+        for (constraint_setting_label, constraint_value_info) in platform.configuration.constraints.items()
+        if constraint_setting_label != cpu_constraint_name
+    }
+
+    new_configs = {}
+    for platform_name, cpu_constraint in cpu_name_to_cpu_constraint.items():
+        updated_constraints = dict(base_constraints)
+        updated_constraints[cpu_constraint_name] = cpu_constraint
+        updated_constraints = _filter_incompatible_constraints(platform_name, updated_constraints)
+
+        new_configs[platform_name] = PlatformInfo(
+            label = platform_name,
+            configuration = ConfigurationInfo(
+                constraints = updated_constraints,
+                values = platform.configuration.values,
+            ),
+        )
+
+    return new_configs
+
+cpu_split_transition = transition(
+    impl = _cpu_split_transition_impl,
+    refs = {
+        "arm32": "config//cpu/constraints:arm32",
+        "arm64": "config//cpu/constraints:arm64",
+        "arm64_32": "config//cpu/constraints:arm64_32",
+        "cpu": "config//cpu/constraints:cpu",
+        "ios": "config//os/constraints:iphoneos",
+        "ios_device_sdk": "config//os/sdk/apple/constraints:iphoneos",
+        "ios_simulator_sdk": "config//os/sdk/apple/constraints:iphonesimulator",
+        "maccatalyst_sdk": "config//os/sdk/apple/constraints:maccatalyst",
+        "macos": "config//os/constraints:macos",
+        "os": "config//os/constraints:os",
+        "sdk": "config//os/sdk/apple/constraints:_",
+        "universal": "config//cpu/constraints:universal",
+        "universal_enabled": "config//cpu/constraints:universal-enabled",
+        "watchos": "config//os/constraints:watchos",
+        "watchos_device_sdk": "config//os/sdk/apple/constraints:watchos",
+        "watchos_simulator_sdk": "config//os/sdk/apple/constraints:watchsimulator",
+        "x86_64": "config//cpu/constraints:x86_64",
+    },
+    attrs = [
+        "universal",
+    ],
+    split = True,
+)
diff --git a/buck2/prelude/apple/user/enable_testing_transition.bzl b/buck2/prelude/apple/user/enable_testing_transition.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/enable_testing_transition.bzl
@@ -0,0 +1,39 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Apply a constraint that sets -enable-testing in Swift compilation.
+"""
+
+def enable_testing_transition_impl(platform: PlatformInfo, refs: struct) -> PlatformInfo:
+    enable_testing_config = refs.enable_testing_setting[ConstraintSettingInfo].label
+    enable_testing_constraint = refs.enable_testing_value[ConstraintValueInfo]
+    if enable_testing_config in platform.configuration.constraints:
+        # Don't apply the transition more than once
+        return platform
+
+    updated_constraints = platform.configuration.constraints
+    updated_constraints[enable_testing_config] = enable_testing_constraint
+    new_cfg = ConfigurationInfo(
+        constraints = updated_constraints,
+        values = platform.configuration.values,
+    )
+    return PlatformInfo(
+        label = platform.label + "-enable-testing",
+        configuration = new_cfg,
+    )
+
+enable_testing_transition_refs = {
+    "enable_testing_setting": "config//features/apple/constraints:swift_enable_testing",
+    "enable_testing_value": "config//features/apple/constraints:swift_enable_testing_enabled",
+}
+
+enable_testing_transition = transition(
+    impl = enable_testing_transition_impl,
+    refs = enable_testing_transition_refs,
+)
diff --git a/buck2/prelude/apple/user/macos_transition.bzl b/buck2/prelude/apple/user/macos_transition.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/macos_transition.bzl
@@ -0,0 +1,76 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_target_sdk_version.bzl", "get_target_sdk_version_map")
+load("@prelude//transitions:utils.bzl", "transition_utils")
+load("@prelude//utils:expect.bzl", "expect")
+
+"""
+Transition from catalyst SDK to macOS SDK. Used for AppKit extension bundle rules.
+Transforms both OS and SDK constraints.
+Only sanity check for source configuration is done.
+"""
+
+def _macos_transition_impl(platform: PlatformInfo, refs: struct) -> PlatformInfo:
+    # This functions operates in the following way:
+    #  - Start with all the constraints from the platform and filter out the constraints for OS and SDK.
+    #  - Always set the new OS constraint to macOS.
+    #  - If the old SDK constraint was macCatalyst, replace with the equivalent macOS constraint.
+    #  - Return a new platform with the updated constraints.
+    constraint_os = refs.os[ConstraintSettingInfo]
+    is_os_macos = platform.configuration.constraints[constraint_os.label] == refs.os_macos[ConstraintValueInfo]
+    constraint_sdk = refs.sdk[ConstraintSettingInfo]
+    is_sdk_macos = platform.configuration.constraints.get(constraint_sdk.label) == refs.sdk_macos[ConstraintValueInfo]
+    if is_os_macos and is_sdk_macos:
+        # Don't apply the transition more than once
+        return platform
+
+    updated_constraints = transition_utils.filtered_platform_constraints(platform, [constraint_os.label, constraint_sdk.label])
+
+    # Update OS constraint
+    updated_constraints[constraint_os.label] = refs.os_macos[ConstraintValueInfo]
+
+    # Update SDK constraint
+    old_sdk = transition_utils.get_constraint_value(platform, constraint_sdk)
+    maccatalyst_sdk = refs.sdk_maccatalyst[ConstraintValueInfo]
+
+    if old_sdk != None:
+        expect(
+            old_sdk.label == maccatalyst_sdk.label,
+            "If present, SDK transitioned non-identically to macOS should be `macCatalyst`, got {}".format(old_sdk.label),
+        )
+    updated_constraints[constraint_sdk.label] = refs.sdk_macos[ConstraintValueInfo]
+
+    constraint_target_sdk_version = refs.target_sdk_version[ConstraintSettingInfo]
+    old_target_sdk_version = transition_utils.get_constraint_value(platform, constraint_target_sdk_version)
+    if old_target_sdk_version != None:
+        # Get last part of constraint as macCatalyst version
+        maccatalyst_version = str(old_target_sdk_version.label).split("-")[-1]
+
+        # Replace target-sdk-version constraint with macOS equivalent from mapping
+        updated_constraints[constraint_target_sdk_version.label] = getattr(refs, maccatalyst_version)[ConstraintValueInfo]
+
+    new_cfg = ConfigurationInfo(
+        constraints = updated_constraints,
+        values = platform.configuration.values,
+    )
+    return PlatformInfo(
+        label = "macos_transition",
+        configuration = new_cfg,
+    )
+
+refs = {
+    "os": "config//os/constraints:os",
+    "os_macos": "config//os/constraints:macos",
+    "sdk": "config//os/sdk/apple/constraints:_",
+    "sdk_maccatalyst": "config//os/sdk/apple/constraints:maccatalyst",
+    "sdk_macos": "config//os/sdk/apple/constraints:macosx",
+    "target_sdk_version": "config//version:constraint-setting-target-sdk-version",
+}
+refs.update(get_target_sdk_version_map())
+macos_transition = transition(impl = _macos_transition_impl, refs = refs)
diff --git a/buck2/prelude/apple/user/resource_group_map.bzl b/buck2/prelude/apple/user/resource_group_map.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/resource_group_map.bzl
@@ -0,0 +1,91 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//apple:resource_groups.bzl",
+    "ResourceGraphNode",  # @unused Used as a type
+    "ResourceGroupInfo",
+    "create_resource_graph",
+    "get_resource_graph_node_map_func",
+)
+load(
+    "@prelude//cxx:groups.bzl",
+    "compute_mappings",
+    "create_group",
+    "get_roots_from_mapping",
+    "make_info_subtarget_providers",
+    "parse_groups_definitions",
+)
+load(
+    "@prelude//cxx:groups_types.bzl",
+    "GroupMapping",  # @unused Used as a type
+)
+load("@prelude//utils:utils.bzl", "flatten")
+
+def resource_group_map_impl(ctx: AnalysisContext) -> list[Provider]:
+    resource_groups = parse_groups_definitions(ctx.attrs.map, lambda root: root.label)
+
+    resource_group_to_implicit_deps_mapping = {group: flatten([get_roots_from_mapping(mapping) for mapping in mappings]) for group, mappings in ctx.attrs.map}
+    flattend_resource_group_deps = flatten(resource_group_to_implicit_deps_mapping.values())
+
+    resource_graph = create_resource_graph(
+        ctx = ctx,
+        labels = [],
+        deps = flattend_resource_group_deps,
+        exported_deps = [],
+    )
+    resource_graph_node_map = get_resource_graph_node_map_func(resource_graph)()
+    mappings = compute_mappings(
+        groups_map = {
+            group.name: create_group(
+                group = group,
+                # User provided mappings may contain entries that don't support
+                # ResourceGraphInfo, which `create_resource_graph` removes above.
+                # So make sure we remove them from the mappings too, otherwise
+                # `compute_mappings` crashes on the inconsistency.
+                mappings = filter(
+                    None,
+                    [_fixup_mapping_to_only_include_roots_in_the_map(m, resource_graph_node_map) for m in group.mappings],
+                ),
+            )
+            for group in resource_groups
+        },
+        graph_map = resource_graph_node_map,
+    )
+    return [
+        DefaultInfo(
+            sub_targets = {
+                "info": make_info_subtarget_providers(ctx, resource_groups, mappings),
+            }
+        ),
+        ResourceGroupInfo(
+            groups = resource_groups,
+            groups_hash = hash(str(resource_groups)),
+            mappings = mappings,
+            # The consumer of this info may not have deps that cover that labels
+            # referenced in our roots, so propagate them here.
+            # NOTE(agallagher): We do this to maintain existing behavior here
+            # but it's not clear if it's actually desirable behavior.
+            resource_group_to_implicit_deps_mapping = resource_group_to_implicit_deps_mapping,
+        ),
+    ]
+
+def _fixup_mapping_to_only_include_roots_in_the_map(mapping: GroupMapping, node_map: dict[Label, ResourceGraphNode]) -> GroupMapping | None:
+    if not mapping.roots:
+        return mapping
+
+    filtered_roots = [root for root in mapping.roots if root in node_map]
+    if not filtered_roots:
+        return None
+
+    return GroupMapping(
+        roots = filtered_roots,
+        traversal = mapping.traversal,
+        filters = mapping.filters,
+        preferred_linkage = mapping.preferred_linkage,
+    )
diff --git a/buck2/prelude/apple/user/target_sdk_version_transition.bzl b/buck2/prelude/apple/user/target_sdk_version_transition.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/target_sdk_version_transition.bzl
@@ -0,0 +1,67 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Apply a constraint if the minimum_os_version attribute is set.
+This overrides any existing target_sdk_version select.
+"""
+
+load("@prelude//apple:versions.bzl", "TARGET_SDK_VERSIONS")
+load("@prelude//apple/user:enable_testing_transition.bzl", "enable_testing_transition_impl", "enable_testing_transition_refs")
+
+def _target_sdk_version_transition_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:
+    target_sdk_version = attrs.minimum_os_version
+    if not target_sdk_version:
+        return platform
+
+    constraint_label = refs.version[ConstraintSettingInfo].label
+    constraint_value = platform.configuration.constraints.get(constraint_label)
+    version_provider = getattr(refs, target_sdk_version, None)
+    if version_provider == None:
+        fail("target sdk version {} is missing constraints".format(target_sdk_version))
+
+    version_constraint = version_provider[ConstraintValueInfo]
+    if constraint_value == version_constraint:
+        return platform
+
+    updated_constraints = platform.configuration.constraints
+    updated_constraints[constraint_label] = version_constraint
+    new_cfg = ConfigurationInfo(
+        constraints = updated_constraints,
+        values = platform.configuration.values,
+    )
+    return PlatformInfo(
+        label = platform.label + "_target_sdk_version_" + target_sdk_version,
+        configuration = new_cfg,
+    )
+
+def _target_sdk_version_and_enable_testing_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:
+    platform_info = _target_sdk_version_transition_impl(platform, refs, attrs)
+    platform_info = enable_testing_transition_impl(platform_info, refs)
+    return platform_info
+
+_target_sdk_version_transition_refs = {version: "@config//version:constraint-value-target-sdk-version-" + version for version in TARGET_SDK_VERSIONS} | {
+    "version": "@config//version:constraint-setting-target-sdk-version"
+}
+
+_target_sdk_version_attrs = ["minimum_os_version"]
+
+target_sdk_version_transition = transition(
+    impl = _target_sdk_version_transition_impl,
+    refs = _target_sdk_version_transition_refs,
+    attrs = _target_sdk_version_attrs,
+)
+
+# apple_test requires both enable_testing and target_sdk_version
+# applied as an incoming transition, so we chain the transitions
+# in this implementation.
+apple_test_target_sdk_version_transition = transition(
+    impl = _target_sdk_version_and_enable_testing_impl,
+    refs = enable_testing_transition_refs | _target_sdk_version_transition_refs,
+    attrs = _target_sdk_version_attrs,
+)
diff --git a/buck2/prelude/apple/user/watch_transition.bzl b/buck2/prelude/apple/user/watch_transition.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/user/watch_transition.bzl
@@ -0,0 +1,84 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Transition from iOS to watchOS. Used for watchOS bundle rule.
+Transforms both OS and SDK constraints.
+Only sanity check for source configuration is done.
+"""
+
+load("@prelude//transitions:utils.bzl", "transition_utils")
+load("@prelude//utils:expect.bzl", "expect")
+
+def _watch_transition_impl(platform: PlatformInfo, refs: struct) -> PlatformInfo:
+    # This functions operates in the following way:
+    #  - Start with all the constraints from the platform and filter out the constraints for OS and SDK.
+    #  - If the old OS constraint was iOS or watchOS, set the new constraint to be always watchOS.
+    #  - If the old SDK constraint was iOS, replace with the equivalent watchOS constraint.
+    #  - Return a new platform with the updated constraints.
+    constraint_settings_to_remove = [
+        refs.os[ConstraintSettingInfo].label,
+        refs.sdk[ConstraintSettingInfo].label,
+    ]
+    # @oss-disable[end= ]: constraint_settings_to_remove.append(refs.memory_profiler[ConstraintValueInfo].setting.label)
+    updated_constraints = transition_utils.filtered_platform_constraints(platform, constraint_settings_to_remove)
+
+    # Update OS constraint
+    old_os = transition_utils.get_constraint_value(platform, refs.os[ConstraintSettingInfo])
+    watchos = refs.watchos[ConstraintValueInfo]
+    ios = refs.ios[ConstraintValueInfo]
+    if old_os != None:
+        expect(
+            old_os.label in [watchos.label, ios.label],
+            "If present, OS transitioned non-identically to watchOS should be `iphoneos`, got {}".format(old_os.label),
+        )
+    updated_constraints[refs.os[ConstraintSettingInfo].label] = watchos
+
+    # Update SDK constraint
+    old_sdk = transition_utils.get_constraint_value(platform, refs.sdk[ConstraintSettingInfo])
+    watchos_device_sdk = refs.watchos_device_sdk[ConstraintValueInfo]
+    watchos_simulator_sdk = refs.watchos_simulator_sdk[ConstraintValueInfo]
+    ios_device_sdk = refs.ios_device_sdk[ConstraintValueInfo]
+    ios_simulator_sdk = refs.ios_simulator_sdk[ConstraintValueInfo]
+    is_simulator = True
+    if old_sdk != None:
+        if old_sdk.label == watchos_simulator_sdk.label:
+            pass
+        elif old_sdk.label == watchos_device_sdk.label:
+            is_simulator = False
+        elif old_sdk.label == ios_simulator_sdk.label:
+            pass
+        elif old_sdk.label == ios_device_sdk.label:
+            is_simulator = False
+        else:
+            fail("If present, SDK transitioned non-identically to watchOS should be either `iphoneos` or `iphonesimulator`, got {}".format(old_sdk.label))
+    updated_constraints[refs.sdk[ConstraintSettingInfo].label] = watchos_simulator_sdk if is_simulator else watchos_device_sdk
+
+    new_cfg = ConfigurationInfo(
+        constraints = updated_constraints,
+        values = platform.configuration.values,
+    )
+    return PlatformInfo(
+        label = "watch_transition",
+        configuration = new_cfg,
+    )
+
+watch_transition = transition(
+    impl = _watch_transition_impl,
+    refs = {
+        "ios": "config//os/constraints:iphoneos",
+        "ios_device_sdk": "config//os/sdk/apple/constraints:iphoneos",
+        "ios_simulator_sdk": "config//os/sdk/apple/constraints:iphonesimulator",
+        # @oss-disable[end= ]: "memory_profiler": "config//build_mode/apple/constraints:enable-memory-profiler-constraint-value",
+        "os": "config//os/constraints:os",
+        "sdk": "config//os/sdk/apple/constraints:_",
+        "watchos": "config//os/constraints:watchos",
+        "watchos_device_sdk": "config//os/sdk/apple/constraints:watchos",
+        "watchos_simulator_sdk": "config//os/sdk/apple/constraints:watchsimulator",
+    },
+)
diff --git a/buck2/prelude/apple/validation/required_reasons.bzl b/buck2/prelude/apple/validation/required_reasons.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/validation/required_reasons.bzl
@@ -0,0 +1,103 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",  # @unused Used as a type
+)
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+
+_AnalysisInput = record(
+    argsfile = field(Artifact),
+    identifier = field(int),
+)
+
+def get_required_reasons_validator_output(ctx, artifacts: ArtifactTSet) -> Artifact | None:
+    if not ctx.attrs.validate_rrapi_usage:
+        return None
+
+    label_to_input_artifacts = _get_analysis_input_artifacts(ctx, artifacts)
+    if not label_to_input_artifacts:
+        return None
+
+    required_reasons_tools = ctx.attrs._apple_toolchain[AppleToolchainInfo].required_reasons_tools
+    label_to_analysis_artifacts = _analyze_artifacts(
+        ctx,
+        "required_reasons_usage",
+        required_reasons_tools.analyzer,
+        label_to_input_artifacts,
+    )
+    return _validate_analysis_artifacts(
+        ctx,
+        "required_reasons_usage",
+        required_reasons_tools.validator,
+        label_to_analysis_artifacts,
+    )
+
+def _get_analysis_input_artifacts(ctx, artifacts: ArtifactTSet) -> dict[Label, list[_AnalysisInput]]:
+    underlying_tset = artifacts._tset
+    if underlying_tset == None:
+        return {}
+
+    results = {}
+    identifier = 0
+    for infos in underlying_tset.traverse():
+        for info in infos:
+            argsfile = ctx.actions.write(
+                "artifacts-{}.txt".format(identifier),
+                info.artifacts,
+                with_inputs = True,
+                has_content_based_path = False,
+            )
+            results.setdefault(info.label, []).append(
+                _AnalysisInput(argsfile = argsfile, identifier = identifier),
+            )
+            identifier += 1
+    return results
+
+def _analyze_artifacts(ctx, key: str, analysis_tool: RunInfo, label_to_artifacts: dict[Label, list[_AnalysisInput]]) -> dict[Label, list[Artifact]]:
+    label_to_analysis = {}
+    for label, inputs in label_to_artifacts.items():
+        for input in inputs:
+            output = ctx.actions.declare_output("{}_{}.json".format(key, input.identifier), has_content_based_path = False)
+            ctx.actions.run(
+                cmd_args([
+                    analysis_tool,
+                    "--artifacts",
+                    cmd_args(input.argsfile, format = "@{}"),
+                    "--output",
+                    output.as_output(),
+                ]),
+                category = "{}_analysis".format(key),
+                identifier = "{}_{}".format(ctx.attrs.name, input.identifier),
+            )
+            label_to_analysis.setdefault(label, []).append(output)
+
+    return label_to_analysis
+
+def _validate_analysis_artifacts(ctx, key: str, validator_tool: RunInfo, label_to_artifacts: dict[Label, list[Artifact]]) -> Artifact:
+    input_json = ctx.actions.write_json(
+        "{}_validator_args.json".format(key),
+        label_to_artifacts,
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+
+    output = ctx.actions.declare_output("{}.json".format(key), has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args([
+            validator_tool,
+            "--analysis-json-path",
+            input_json,
+            "--output",
+            output.as_output(),
+        ]),
+        category = "{}_validate".format(key),
+        identifier = ctx.attrs.name,
+    )
+    return output
diff --git a/buck2/prelude/apple/validation/required_reasons_tools.bzl b/buck2/prelude/apple/validation/required_reasons_tools.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/validation/required_reasons_tools.bzl
@@ -0,0 +1,31 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Tools used to validate Apple Required Reasons API (RRAPI) usage against the
+# declared `.xcprivacy` privacy manifest. Whether they run is decided by the
+# consuming rule.
+RequiredReasonsToolsInfo = provider(
+    fields = {
+        # Consumes a target's own debug artifacts and emits a per-target
+        # analysis JSON of the RRAPI symbols it references.
+        "analyzer": provider_field(RunInfo),
+        # Consumes the per-target analysis JSONs surviving in a bundle and
+        # emits a single ValidationSpec result, applying the allowlist /
+        # exemption checks.
+        "validator": provider_field(RunInfo),
+    },
+)
+
+def required_reasons_tools_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        RequiredReasonsToolsInfo(
+            analyzer = ctx.attrs.analyzer[RunInfo],
+            validator = ctx.attrs.validator[RunInfo],
+        ),
+    ]
diff --git a/buck2/prelude/apple/validation/swiftmodule_change_analysis.bzl b/buck2/prelude/apple/validation/swiftmodule_change_analysis.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/validation/swiftmodule_change_analysis.bzl
@@ -0,0 +1,125 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "make_artifact_tset",
+    "stringify_artifact_label",
+)
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolsInfo")
+load("@prelude//apple/swift:swift_types.bzl", "SwiftDependencyInfo")
+
+# Backs the apple_bundle `[swiftmodule-change-analysis]` subtarget
+def get_swiftmodule_change_analysis_output(ctx: AnalysisContext, deps: list[Dependency]) -> Artifact | None:
+    apple_tools = ctx.attrs._apple_tools[AppleToolsInfo]
+
+    if apple_tools.swiftmodule_change_analysis == None:
+        return None
+
+    swiftmodule_change_analysis_tsets = [dep[SwiftDependencyInfo].swiftmodule_change_analysis_tset for dep in deps if SwiftDependencyInfo in dep]
+    if not swiftmodule_change_analysis_tsets:
+        return None
+
+    tset = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        children = swiftmodule_change_analysis_tsets,
+    )
+    if tset._tset == None:
+        return None
+
+    label_to_artifacts = {}
+    for infos in tset._tset.traverse():
+        for info in infos:
+            label_to_artifacts.setdefault(stringify_artifact_label(info.label), []).extend(info.artifacts)
+
+    if not label_to_artifacts:
+        return None
+
+    manifest = ctx.actions.write_json(
+        "swiftmodule_change_analysis/manifest.json",
+        label_to_artifacts,
+        # with_inputs = True here means any change to a dependency's
+        # swiftmodule will re-trigger this action.
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+
+    # Only populated when `apple.swift_dump_ast_subtarget_enabled` is set, so
+    # this is `None` for the vast majority of builds. Ignored by the default
+    # bootstrap tool; consumed by richer out-of-tree implementations (see
+    # `apple.swiftmodule_change_analysis` buckconfig) that classify changes
+    # via AST diffing instead of a raw `.swiftinterface` text diff.
+    ast_dump_tsets = [dep[SwiftDependencyInfo].swift_ast_dump_tset for dep in deps if SwiftDependencyInfo in dep]
+    ast_tset = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        children = ast_dump_tsets,
+    )
+    ast_manifest = None
+    if ast_tset._tset != None:
+        label_to_ast_artifacts = {}
+        for infos in ast_tset._tset.traverse():
+            for info in infos:
+                if info.artifacts:
+                    label_to_ast_artifacts.setdefault(stringify_artifact_label(info.label), []).extend(info.artifacts)
+
+        if label_to_ast_artifacts:
+            ast_manifest = ctx.actions.write_json(
+                "swiftmodule_change_analysis/ast_manifest.json",
+                label_to_ast_artifacts,
+                with_inputs = True,
+                has_content_based_path = False,
+            )
+
+    # Not content-addressed, and `no_outputs_cleanup` below keeps this file
+    # around across runs, so the checker can compare the current state
+    # against what it saw the last time this action ran.
+    state = ctx.actions.declare_output("swiftmodule_change_analysis/state.json", has_content_based_path = False)
+    output = ctx.actions.declare_output("swiftmodule_change_analysis/differences.json", has_content_based_path = False)
+
+    swiftmodule_change_analysis_tool = apple_tools.swiftmodule_change_analysis
+
+    command = cmd_args([
+        swiftmodule_change_analysis_tool,
+        "--target",
+        stringify_artifact_label(ctx.label),
+        "--manifest",
+        manifest,
+        "--state",
+        state.as_output(),
+        "--output",
+        output.as_output(),
+    ])
+
+    if ast_manifest:
+        command.add("--ast-manifest", ast_manifest)
+
+    # The manifest only bakes in each artifact's *path*; without also listing
+    # them as hidden inputs here, Buck2 wouldn't know this action actually
+    # depends on their content, and `metadata_path` below wouldn't include
+    # their digests.
+    command.add(cmd_args(hidden = [artifact for artifacts in label_to_artifacts.values() for artifact in artifacts]))
+
+    ctx.actions.run(
+        command,
+        category = "swiftmodule_change_analysis",
+        identifier = ctx.attrs.name,
+        # prefer_local as only the local action will do anything useful
+        prefer_local = True,
+        allow_cache_upload = False,
+        no_outputs_cleanup = True,
+        # Buck2 already knows a content digest for every one of this
+        # action's inputs (it needs one for its own caching); this hands
+        # them to the tool as a `path -> digest` JSON file so it can compare
+        # digests instead of reading and hashing `.swiftmodule` files itself.
+        metadata_env_var = "SWIFTMODULE_CHANGE_ANALYSIS_METADATA",
+        metadata_path = "swiftmodule_change_analysis/action_metadata.json",
+    )
+
+    return output
diff --git a/buck2/prelude/apple/versions.bzl b/buck2/prelude/apple/versions.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/versions.bzl
@@ -0,0 +1,47 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# All the target SDK versions currently in use.
+TARGET_SDK_VERSIONS = [
+    "1.0",
+    "4.0",
+    "7.0",
+    "8.0",
+    "9.0",
+    "10.0",
+    "10.10",
+    "10.12",
+    "10.13",
+    "10.14",
+    "10.15",
+    "11.0",
+    "11.3",
+    "12.0",
+    "12.1",
+    "12.4",
+    "13.0",
+    "13.1",
+    "13.3",
+    "13.4",
+    "14.0",
+    "14.2",
+    "15.0",
+    "15.1",
+    "15.2",
+    "15.5",
+    "16.0",
+    "16.1",
+    "16.3",
+    "17.0",
+    "17.2",
+    "17.4",
+    "18.0",
+    "18.4",
+    "26.0",
+    "26.1",
+]
diff --git a/buck2/prelude/apple/xcassets_asset_symbols.bzl b/buck2/prelude/apple/xcassets_asset_symbols.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/xcassets_asset_symbols.bzl
@@ -0,0 +1,25 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# @oss-disable[end= ]: # Asset symbol hooks implemented in meta_only; open source gets no-op stubs.
+
+# @oss-disable[end= ]: load("@prelude//apple/meta_only:meta_xcassets_asset_symbol_spec.bzl", _MetaXcassetsAssetSymbolSpec = "MetaXcassetsAssetSymbolSpec")
+# @oss-disable[end= ]: load(
+    # @oss-disable[end= ]: "@prelude//apple/meta_only:meta_xcassets_asset_symbol_usage.bzl",
+    # @oss-disable[end= ]: _usage_providers_and_subtargets = "meta_xcassets_asset_symbol_usage_providers_and_subtargets",
+# @oss-disable[end= ]: )
+load("@prelude//cxx:cxx_sources.bzl", "CxxSrcWithFlags")
+
+# @oss-disable[end= ]: MetaXcassetsAssetSymbolSpec = _MetaXcassetsAssetSymbolSpec
+MetaXcassetsAssetSymbolSpec = record() # @oss-enable
+
+def meta_xcassets_asset_symbol_usage_providers_and_subtargets(
+    ctx: AnalysisContext, cxx_srcs: list[CxxSrcWithFlags], swift_srcs: list[CxxSrcWithFlags]
+) -> (list[Provider], dict[str, list[Provider]]):
+    # @oss-disable[end= ]: return _usage_providers_and_subtargets(ctx, cxx_srcs, swift_srcs)
+    return [], {} # @oss-enable
diff --git a/buck2/prelude/apple/xcode.bzl b/buck2/prelude/apple/xcode.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/xcode.bzl
@@ -0,0 +1,69 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_sdk.bzl", "get_apple_sdk_name")
+load("@prelude//apple:apple_target_sdk_version.bzl", "get_min_deployment_version_for_node")
+load("@prelude//apple:apple_utility.bzl", "get_apple_architecture", "has_apple_toolchain")
+load(
+    "@prelude//cxx:argsfiles.bzl",
+    "CompileArgsfile",  # @unused Used as a type
+)
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",  # @unused Used as a type
+)
+load("@prelude//cxx:xcode.bzl", "cxx_populate_xcode_attributes")
+load("@prelude//ide_integrations/xcode:data.bzl", "XcodeDataInfoKeys")
+load("@prelude//utils:expect.bzl", "expect")
+
+def apple_populate_xcode_attributes(
+    ctx, srcs: list[CxxSrcWithFlags], argsfiles: dict[str, CompileArgsfile], product_name: str, contains_swift_sources: bool = False
+) -> dict[str, typing.Any]:
+    data = cxx_populate_xcode_attributes(ctx = ctx, srcs = srcs, argsfiles = argsfiles, product_name = product_name)
+
+    data[XcodeDataInfoKeys.CONTAINS_SWIFT_SOURCES] = contains_swift_sources
+
+    if has_apple_toolchain(ctx):
+        data[XcodeDataInfoKeys.ARCH] = get_apple_architecture(ctx)
+        data[XcodeDataInfoKeys.SDK] = get_apple_sdk_name(ctx)
+        data[XcodeDataInfoKeys.DEPLOYMENT_VERSION] = get_min_deployment_version_for_node(ctx)
+
+    if hasattr(ctx.attrs, "swift_version"):
+        swift_version = ctx.attrs.swift_version
+        if swift_version != None:
+            data[XcodeDataInfoKeys.SWIFT_VERSION] = swift_version
+
+    apple_xcode_data_add_xctoolchain(ctx, data)
+    return data
+
+def apple_xcode_data_add_xctoolchain(ctx: AnalysisContext, data: dict[str, typing.Any]):
+    _add_label_for_attr(ctx, "_apple_xctoolchain_bundle_id", "xctoolchain_bundle_id_target", data)
+    _add_output_for_attr(ctx, "_apple_xctoolchain_bundle_id", "xctoolchain_bundle_id", data)
+    _add_label_for_attr(ctx, "_apple_xctoolchain", "xctoolchain_bundle_target", data)
+
+def _add_label_for_attr(ctx: AnalysisContext, attr_name: str, field_name: str, data: dict[str, typing.Any]):
+    xctoolchain_dep = _get_attribute_with_output(ctx, attr_name)
+    if xctoolchain_dep:
+        data[field_name] = xctoolchain_dep.label
+
+def _add_output_for_attr(ctx: AnalysisContext, attr_name: str, field_name: str, data: dict[str, typing.Any]):
+    xctoolchain_dep = _get_attribute_with_output(ctx, attr_name)
+    if xctoolchain_dep:
+        default_info = xctoolchain_dep[DefaultInfo]
+        expect(len(default_info.default_outputs) == 1, "Expected only one output, got {}", len(default_info.default_outputs))
+        data[field_name] = default_info.default_outputs[0]
+
+def _get_attribute_with_output(ctx: AnalysisContext, attr_name: str) -> [Dependency, None]:
+    if hasattr(ctx.attrs, attr_name):
+        dep = getattr(ctx.attrs, attr_name)
+        default_info = dep[DefaultInfo]
+        if len(default_info.default_outputs) > 0:
+            # When there's no xctoolchain, there will be an empty `DefaultInfo`.
+            # So, an empty `DefaultInfo` basically signifies that there's no xctoolchain.
+            return dep
+    return None
diff --git a/buck2/prelude/apple/xctest_swift_support.bzl b/buck2/prelude/apple/xctest_swift_support.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/apple/xctest_swift_support.bzl
@@ -0,0 +1,37 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_library_utility.bzl", "cxx_attr_deps", "cxx_attr_exported_deps")
+load(":apple_frameworks.bzl", "to_framework_name")
+
+# Provider which helps to propagate the info if XCTest Swift support is needed up the target graph.
+XCTestSwiftSupportInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "support_needed": provider_field(bool),
+        # Value is unused, needed only to detect a provider type
+    },
+)
+
+def xctest_swift_support_info(ctx: AnalysisContext, contains_swift_sources: bool, is_test_target: bool) -> XCTestSwiftSupportInfo:
+    if contains_swift_sources and (is_test_target or _depends_on_xctest(ctx)):
+        return XCTestSwiftSupportInfo(support_needed = True)
+    else:
+        return _inherited_xctest_swift_support_info(ctx)
+
+def _inherited_xctest_swift_support_info(ctx: AnalysisContext) -> XCTestSwiftSupportInfo:
+    all_deps = cxx_attr_deps(ctx) + cxx_attr_exported_deps(ctx)
+    for dep in all_deps:
+        if XCTestSwiftSupportInfo in dep:
+            info = dep[XCTestSwiftSupportInfo]
+            if info.support_needed:
+                return info
+    return XCTestSwiftSupportInfo(support_needed = False)
+
+def _depends_on_xctest(ctx: AnalysisContext) -> bool:
+    return "XCTest" in [to_framework_name(x) for x in ctx.attrs.frameworks]
diff --git a/buck2/prelude/artifact_tset.bzl b/buck2/prelude/artifact_tset.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/artifact_tset.bzl
@@ -0,0 +1,114 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:type_defs.bzl", "is_list")
+load(
+    "@prelude//utils:utils.bzl",
+    "flatten",
+)
+
+# Generic tag to provide more information about the artifact
+ArtifactInfoTag = enum(
+    # Describes artifacts required for debugging Swift code, including
+    # swiftmodule files, swiftinterface files, clang modules and modulemaps.
+    "swift_debug_info",
+)
+
+ArtifactInfo = record(
+    label = field(Label),
+    artifacts = field(list[Artifact]),
+    tags = field(list[ArtifactInfoTag]),
+)
+
+def stringify_artifact_label(value: Label | str) -> str:
+    if type(value) == "string":
+        return value
+    return str(value.raw_target())
+
+def _get_artifacts(entries: list[ArtifactInfo]) -> list[Artifact]:
+    return flatten([entry.artifacts for entry in entries])
+
+_ArtifactTSet = transitive_set(
+    args_projections = {
+        "artifacts": _get_artifacts,
+    },
+)
+
+ArtifactTSet = record(
+    _tset = field([_ArtifactTSet, None], None),
+)
+
+# Simple empty `ArtifactTSet` that is shared to reduce memory usage.
+EmptyArtifactTSet = ArtifactTSet()
+
+def make_artifact_tset(
+    actions: AnalysisActions,
+    # Must be non-`None` if artifacts are passed in to `artifacts`.
+    label: Label | None = None,
+    artifacts: list[Artifact] = [],
+    infos: list[ArtifactInfo] = [],
+    children: list[ArtifactTSet] = [],
+    tags: list[ArtifactInfoTag] = [],
+) -> ArtifactTSet:
+    expect(
+        label != None or not artifacts,
+        "must pass in `label` to associate with artifacts",
+    )
+
+    single_child = None  # type: ArtifactTSet | None
+    children_orig = children
+    children = []  # type: list[_ArtifactTSet]
+    for c in children_orig:
+        # As a convenience for our callers, filter our `None` children.
+        if c._tset != None:
+            children.append(c._tset)
+            single_child = c
+
+    has_values = artifacts or infos
+    if not has_values and not children:
+        return EmptyArtifactTSet
+
+    if not has_values and len(children) == 1:
+        # If we have a single child, just return it
+        # rather than allocating and retaining additional memory.
+        return single_child
+
+    # Build list of all non-child values.
+    values = []
+    if artifacts:
+        values.append(ArtifactInfo(label = label, artifacts = artifacts, tags = tags))
+    values.extend(infos)
+
+    # We only build a `_ArtifactTSet` if there's something to package.
+    kwargs = {}
+    if values:
+        kwargs["value"] = values
+    if children:
+        kwargs["children"] = children
+    return ArtifactTSet(
+        _tset = actions.tset(_ArtifactTSet, **kwargs),
+    )
+
+def project_artifacts(actions: AnalysisActions, tsets: ArtifactTSet | list[ArtifactTSet] = []) -> list[TransitiveSetArgsProjection]:
+    """
+    Helper to project a list of optional tsets.
+    """
+
+    if is_list(tsets):
+        tset = make_artifact_tset(
+            actions = actions,
+            children = tsets,
+        )
+    else:
+        tset = tsets
+
+    if tset._tset == None:
+        return []
+
+    return [tset._tset.project_as_args("artifacts")]
diff --git a/buck2/prelude/artifacts.bzl b/buck2/prelude/artifacts.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/artifacts.bzl
@@ -0,0 +1,176 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//dist:dist_info.bzl", "DistInfo")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+load("@prelude//utils:expect.bzl", "expect")
+
+# A group of artifacts.
+ArtifactGroupInfo = provider(
+    fields = {
+        "artifacts": provider_field(typing.Any, default = None),  # ["artifact"]
+    },
+)
+
+ArtifactOutputs = record(
+    # Single output. This is the artifact whose path would go into the resources
+    # JSON when this artifact is used as a resource.
+    default_output = field(Artifact),
+    # Other artifacts which need to be present in order to run the resource as
+    # an executable. This includes shared library dependencies and resources.
+    nondebug_runtime_files = field(list[ArgLike]),
+    # Other outputs that would be materialized if this artifact is the output of
+    # a build, or generally in any context where a user might run this artifact
+    # in a debugger.
+    #
+    # This is a superset of nondebug_runtime_files and also includes external
+    # debuginfo.
+    other_outputs = field(list[ArgLike]),
+)
+
+# Wrapper to support wrapping `Artifact`s referencing paths behind external
+# symlinks.
+ArtifactExt = record(
+    artifact = field(Artifact),
+    # If the `artifact` above is a symlink referencing an external path, this
+    # is an optional sub-path to append when accessing the path.
+    sub_path = field(str | None, None),
+    # Returns the resolved path as a `cmd_arg()`, with the optional sub-path
+    # appended.
+    as_arg = field(typing.Callable),
+    join = field(typing.Callable),
+)
+
+# A Provider that mirrors `DefaultInfo` for `Artifact` outputs, but allows
+# specifying an `ArtifactExt` as it's default output.
+DefaultOutputExt = provider(
+    fields = dict(
+        default_output = provider_field(ArtifactExt),
+    ),
+)
+
+def single_artifact(dep: Artifact | Dependency) -> ArtifactOutputs:
+    if isinstance(dep, Artifact):
+        return ArtifactOutputs(
+            default_output = dep,
+            nondebug_runtime_files = [],
+            other_outputs = [],
+        )
+
+    if DefaultInfo in dep:
+        info = dep[DefaultInfo]
+        expect(
+            len(info.default_outputs) == 1,
+            "expected exactly one default output from {} ({})".format(dep, info.default_outputs),
+        )
+        default_output = info.default_outputs[0]
+        other_outputs = info.other_outputs
+
+        dist_info = dep.get(DistInfo)
+        nondebug_runtime_files = dist_info.nondebug_runtime_files if dist_info else other_outputs
+
+        return ArtifactOutputs(
+            default_output = default_output,
+            nondebug_runtime_files = nondebug_runtime_files,
+            other_outputs = other_outputs,
+        )
+
+    fail("unexpected dependency type: {}".format(type(dep)))
+
+def unpack_artifacts(artifacts: list[Artifact | Dependency]) -> list[ArtifactOutputs]:
+    """
+    Unpack a heterogeneous list of Artifact and ArtifactGroupInfo into a list
+    representing their outputs.
+    """
+
+    out = []
+
+    for artifact in artifacts:
+        if isinstance(artifact, Artifact):
+            out.append(
+                ArtifactOutputs(
+                    default_output = artifact,
+                    nondebug_runtime_files = [],
+                    other_outputs = [],
+                )
+            )
+            continue
+
+        if ArtifactGroupInfo in artifact:
+            for artifact in artifact[ArtifactGroupInfo].artifacts:
+                out.append(
+                    ArtifactOutputs(
+                        default_output = artifact,
+                        nondebug_runtime_files = [],
+                        other_outputs = [],
+                    )
+                )
+            continue
+
+        out.append(single_artifact(artifact))
+
+    return out
+
+def unpack_artifact_map(artifacts: dict[str, Artifact | Dependency]) -> dict[str, ArtifactOutputs]:
+    """
+    Unpack a heterogeneous dict of Artifact and ArtifactGroupInfo into a dict
+    representing their outputs.
+    """
+
+    out = {}
+
+    for name, artifact in artifacts.items():
+        if isinstance(artifact, Artifact):
+            out[name] = ArtifactOutputs(
+                default_output = artifact,
+                nondebug_runtime_files = [],
+                other_outputs = [],
+            )
+            continue
+
+        if ArtifactGroupInfo in artifact:
+            for artifact in artifact[ArtifactGroupInfo].artifacts:
+                out[paths.join(name, artifact.short_path)] = ArtifactOutputs(
+                    default_output = artifact,
+                    nondebug_runtime_files = [],
+                    other_outputs = [],
+                )
+            continue
+
+        out[name] = single_artifact(artifact)
+
+    return out
+
+def _as_arg(artifact: Artifact, sub_path: str | None) -> ArgLike:
+    if sub_path == None:
+        return artifact
+    return cmd_args(artifact, format = "{{}}/{}".format(sub_path))
+
+def artifact_ext(artifact: Artifact, sub_path: str | None = None) -> ArtifactExt:
+    return ArtifactExt(
+        artifact = artifact,
+        sub_path = sub_path,
+        as_arg = lambda: _as_arg(artifact, sub_path),
+        join = lambda p: artifact_ext(
+            artifact = artifact,
+            sub_path = p if sub_path == None else paths.join(sub_path, p),
+        ),
+    )
+
+def to_artifact_ext(src: Artifact | Dependency) -> ArtifactExt:
+    if isinstance(src, Dependency):
+        ext = src.get(DefaultOutputExt)
+        if ext != None:
+            return ext.default_output
+        else:
+            (src,) = src[DefaultInfo].default_outputs
+    return artifact_ext(src)
+
+def to_arglike(src: Artifact | Dependency) -> ArgLike:
+    return to_artifact_ext(src).as_arg()
diff --git a/buck2/prelude/asserts.bzl b/buck2/prelude/asserts.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/asserts.bzl
@@ -0,0 +1,34 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _equals(expected, actual, msg = None):
+    if expected != actual:
+        if msg == None:
+            fail("expected: {}, got: {}".format(expected, actual))
+        else:
+            fail("{}: expected: {}, got: {}".format(msg, expected, actual))
+
+def _true(condition, msg = None):
+    if not condition:
+        if msg != None:
+            fail(msg)
+        else:
+            fail("Condition is not met")
+
+def _false(condition, msg = None):
+    if condition:
+        if msg != None:
+            fail(msg)
+        else:
+            fail("Condition is expected to be false")
+
+asserts = struct(
+    equals = _equals,
+    true = _true,
+    false = _false,
+)
diff --git a/buck2/prelude/attributes.bzl b/buck2/prelude/attributes.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/attributes.bzl
@@ -0,0 +1,9 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# The specs you are looking for have moved into the prelude/decls directory
diff --git a/buck2/prelude/attrs_validators.bzl b/buck2/prelude/attrs_validators.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/attrs_validators.bzl
@@ -0,0 +1,60 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+_ATTRS_VALIDATORS_NAME = "attrs_validators"
+
+AttrsValidatorsInfo = provider(
+    fields = {
+        "func": typing.Callable[[AnalysisActions, Label, struct], dict[str, Artifact]],
+    },
+)
+
+def get_attrs_validation_specs(ctx: AnalysisContext) -> list[ValidationSpec]:
+    validators = getattr(ctx.attrs, _ATTRS_VALIDATORS_NAME, [])
+    if not validators:
+        return []
+
+    specs = []
+    for validator in validators:
+        for name, output in validator[AttrsValidatorsInfo].func(ctx.actions, ctx.label, ctx.attrs).items():
+            specs.append(ValidationSpec(name = name, validation_result = output))
+
+    return specs
+
+def _attrs_validators_arg():
+    return {
+        _ATTRS_VALIDATORS_NAME: attrs.option(
+            attrs.list(attrs.dep(providers = [AttrsValidatorsInfo])),
+            default = None,
+        ),
+    }
+
+def _validation_specs_arg():
+    return {
+        "validation_specs": attrs.dict(
+            attrs.string(),
+            attrs.source(
+                doc = """
+                An artifact pointing to a JSON file that will be used in ValidationSpec.
+                {
+                  "version": 1,
+                  "data": {
+                    "message": "What goes in stderr",
+                    "status": "success" | "failure",
+                  }
+                } 
+            """
+            ),
+            default = {},
+        ),
+    }
+
+validation_common = struct(
+    attrs_validators_arg = _attrs_validators_arg,
+    validation_specs_arg = _validation_specs_arg,
+)
diff --git a/buck2/prelude/build_mode/BUCK b/buck2/prelude/build_mode/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/build_mode/BUCK
@@ -0,0 +1,12 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+# No-op in OSS.
+
+config_setting(
+    name = "arvr_mode",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/bxl/ensure.bxl b/buck2/prelude/bxl/ensure.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/bxl/ensure.bxl
@@ -0,0 +1,32 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Utils functions for working with `ctx.output.ensure/ensure_multiple` in bxl.
+"""
+
+def ensure_default_info(ctx: bxl.Context, default_info: DefaultInfo, with_other_outputs: bool = False) -> None:
+    """
+    Ensures all outputs of the given DefaultInfo.
+
+    Parameters:
+    - `ctx`: The bxl context.
+    - `default_info`: The `DefaultInfo` to ensure.
+    - `with_other_outputs`: Whether to also ensure the `other_outputs` of the `DefaultInfo`.
+
+    Example:
+    ```python
+    load("@prelude//bxl:ensure.bxl", "ensure_default_info")
+    def _impl(ctx):
+        target = ctx.cli_args.target
+        default_info = ctx.analysis(target).providers()[DefaultInfo].sub_targets["dwp"][DefaultInfo]
+        ensure_default_info(ctx, default_info)
+    ```
+    """
+    other_outputs = default_info.other_outputs or [] if with_other_outputs else []
+    ctx.output.ensure_multiple(cmd_args(default_info.default_outputs, hidden = other_outputs))
diff --git a/buck2/prelude/bxl/lazy.bxl b/buck2/prelude/bxl/lazy.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/bxl/lazy.bxl
@@ -0,0 +1,206 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Utils functions for working with bxl.Lazy objects.
+"""
+
+def catch_resolve_lazy_dict(bxl_ctx: bxl.Context, lazy_dict: dict[typing.Any, bxl.Lazy]) -> dict[typing.Any, bxl.Result]:
+    """
+    Resolves a dictionary of bxl.Lazy operations in parallel while capturing errors.
+
+     Parameters:
+    - `bxl_ctx`: BXL context
+    - `lazy_dict`: Dictionary to resolve, where values must be `bxl.Lazy` instances
+
+    Returns:
+    A new dictionary preserving original keys, with values as `bxl.Result` objects.
+
+    Example:
+    ```python
+    def _impl(ctx):
+        lazy_dict = {
+            "app": ctx.lazy.configured_targets("cell//:app"),
+            "lib": ctx.lazy.configured_targets("cell//:lib")
+        }
+
+        # Batch resolve and process
+        results = catch_resolve_lazy_dict(ctx, lazy_dict)
+        for name, res in results.items():
+            if res.is_ok():
+                ctx.output.print(f"{name}: {res.unwrap()}")
+            else:
+                ctx.output.print(f"{name} failed: {res.unwrap_err()}")
+    ```
+    """
+    keys = lazy_dict.keys()
+    lazies = [lazy.catch() for lazy in lazy_dict.values()]
+    values = bxl_ctx.lazy.join_all(lazies).resolve()
+    return dict(zip(keys, values))
+
+def batch_apply_lazy(bxl_ctx: bxl.Context, lazy_func: typing.Callable[[typing.Any], bxl.Lazy], args: list[typing.Any]) -> list[typing.Any]:
+    """
+    Applies a lazy function to a list of arguments, resolves them in parallel, and returns raw results.
+    It will cause bxl fail immediately if any operation fails (no error catching).
+
+    Parameters:
+    - `bxl_ctx` (`bxl.Context`): The BXL context object.
+    - `lazy_func` (`typing.Callable[[Any], bxl.Lazy]`): A function that takes a single argument and returns a `bxl.Lazy`
+      (e.g., `ctx.lazy.analysis`, `ctx.lazy.configured_target_node`, or any other functon/lambda you defined).
+    - `args` (`list[typing.Any]`): List of arguments to apply to `lazy_func`.
+
+    Returns:
+    - A list of resolved values. If any operation fails, the bxl script will fail.
+
+    Example:
+    ```python
+    def _impl(ctx):
+        targets = [
+            "cell//:valid_target1",
+            "cell//:valid_target2"
+        ]
+
+        # Resolve to all configured target nodes without error catching
+        nodes = batch_apply_lazy(ctx, ctx.lazy.configured_target_node, targets)
+        ctx.output.print(f"All configured target nodes: {nodes}")
+    ```
+    """
+    lazies = [lazy_func(arg) for arg in args]
+    return bxl_ctx.lazy.join_all(lazies).resolve()
+
+def batch_apply_lazy_catch_each(bxl_ctx: bxl.Context, lazy_func: typing.Callable[[typing.Any], bxl.Lazy], args: list[typing.Any]) -> list[bxl.Result]:
+    """
+    Applies a lazy function to a list of arguments, resolves them in parallel, and returns individual `Result`
+    objects for each operation. Errors are isolated per item.
+
+    Parameters:
+    - `bxl_ctx` (`bxl.Context`): The BXL context object.
+    - `lazy_func` (`typing.Callable[[typing.Any], bxl.Lazy]`): A function that returns a `bxl.Lazy`
+      (e.g., `ctx.lazy.analysis`, `ctx.lazy.configured_target_node`, or any other functon/lambda you defined)..
+    - `args` (`list[typing.Any]`): List of arguments to apply to `lazy_func`.
+
+    Returns:
+    - `list[bxl.Result]`: A list of `Result` objects in the same order as `args`. Each `Result` can be
+      `Ok(value)` or `Err(error)`.
+
+    Example:
+    ```python
+    def _impl(ctx):
+        targets = [
+            "cell//:valid_target1",
+            "cell//:valid_target2"
+            "cell//:invalid_target1",
+        ]
+
+        # Resolve analyses with per-item error handling
+        results = batch_apply_lazy_catch_each(ctx, ctx.lazy.configured_target_node, targets)
+
+        for target, res in zip(targets, results):
+            if res.is_ok():
+                node = res.unwrap()
+                ctx.output.print(f"Get configured target node for {target} SUCCESS: {node}")
+            else:
+                error = res.unwrap_err()
+                ctx.output.print(f"Get configured target node for {target} FAILED: {error}")
+    ```
+    """
+    lazies = [lazy_func(arg).catch() for arg in args]  # Catch per item
+    return bxl_ctx.lazy.join_all(lazies).resolve()
+
+def batch_apply_lazy_catch_all(bxl_ctx: bxl.Context, lazy_func: typing.Callable[[typing.Any], bxl.Lazy], args: list[typing.Any]) -> bxl.Result:
+    """
+    Applies a lazy function to a list of arguments, joins them into a single batch operation, and resolves
+    with a global error catch. Returns either all successes or the first error encountered.
+
+    Parameters:
+    - `bxl_ctx` (`bxl.Context`): The BXL context object.
+    - `lazy_func` (`typing.Callable[[typing.Any], bxl.Lazy]`): A function that returns a `bxl.Lazy`
+      (e.g., `ctx.lazy.analysis`, `ctx.lazy.configured_target_node`, or any other functon/lambda you defined)..
+    - `args` (`list[typing.Any]`): List of arguments to apply to `lazy_func`.
+
+    Returns:
+    - `bxl.Result`:
+      - `Ok(list)`: If all operations succeed, returns the list of resolved values.
+      - `Err(error)`: If any operation fails, returns the first error encountered.
+
+    Example:
+    ```python
+    def _impl(ctx):
+        targets = [
+            "cell//:valid_target1",
+            "cell//:valid_target2"
+            "cell//:invalid_target1",
+        ]
+
+        # Resolve as a single batch with global error handling
+        batch_result = batch_apply_lazy_catch_all(ctx, ctx.lazy.configured_target_node, targets)
+
+        if batch_result.is_ok():
+            res = batch_result.unwrap()
+            ctx.output.print(f"All succeeded: {len(res)}")
+        else:
+            error = batch_result.unwrap_err()
+            ctx.output.print(f"Batch failed: {error}")
+    ```
+    """
+    lazies = [lazy_func(arg) for arg in args]
+    joined = bxl_ctx.lazy.join_all(lazies)
+    return joined.catch().resolve()  # Catch at batch level
+
+def partition_results(results: list[bxl.Result]) -> (list[typing.Any], list[bxl.Error]):
+    """
+    Splits Results into successful values and errors.
+
+    Parameters:
+    - `results`: List of `bxl.Result` objects
+
+    Returns:
+    A tuple of two lists: `(successes, errors)`
+
+    Example:
+    ```python
+    successes, errors = partition_results(results)
+    ctx.output.print(f"Successes: {len(successes)}, Errors: {len(errors)}")
+    ```
+    """
+    oks, errs = [], []
+    for res in results:
+        if res.is_ok():
+            oks.append(res.unwrap())
+        else:
+            errs.append(res.unwrap_err())
+    return oks, errs
+
+def partition_results_dict(results_dict: dict[typing.Any, bxl.Result]) -> (dict[typing.Any, typing.Any], dict[typing.Any, bxl.Error]):
+    """
+    Splits a dictionary of `bxl.Result` into two dictionaries:
+    - Successful key-value pairs (unwrapped values)
+    - Errored key-value pairs (error objects)
+
+    Parameters:
+    - `results_dict`: Dictionary with values of type `bxl.Result`
+
+    Returns:
+    Tuple of `(success_dict, error_dict)` where:
+    - `success_dict`: Original keys mapped to unwrapped `Ok` values
+    - `error_dict`: Original keys mapped to `bxl.Error` objects
+
+    Example:
+    ```python
+    results = {"app": res1, "lib": res2, "test": res3}
+    successes, errors = split_results_dict_by_status(results)
+    ```
+    """
+    success_dict = {}
+    error_dict = {}
+    for key, res in results_dict.items():
+        if res.is_ok():
+            success_dict[key] = res.unwrap()
+        else:
+            error_dict[key] = res.unwrap_err()
+    return success_dict, error_dict
diff --git a/buck2/prelude/cache_mode.bzl b/buck2/prelude/cache_mode.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cache_mode.bzl
@@ -0,0 +1,11 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+CacheModeInfo = provider(
+    fields = {"allow_cache_uploads": provider_field(typing.Any, default = None), "cache_bust_genrules": provider_field(typing.Any, default = None)}
+)
diff --git a/buck2/prelude/capabilities/capabilities_registration.bzl b/buck2/prelude/capabilities/capabilities_registration.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/capabilities/capabilities_registration.bzl
@@ -0,0 +1,82 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Capabilities registration provider and tset for build graph propagation.
+
+CapabilitiesRegistrationInfo is a provider that carries capability metadata
+through the dependency graph via a transitive set (tset). Each library with
+capability declarations creates a tset entry and merges it with its deps'
+tsets. At binary build time, a manifest rule projects the final tset into
+a support manifest JSON.
+"""
+
+def _project_as_manifest_json(entry):
+    """Project a CapabilitiesRegistrationEntry to its manifest JSON representation."""
+    result = {
+        "kind": entry.kind,
+        "style_id": entry.style_id,
+    }
+    if entry.props:
+        result["props"] = entry.props
+    if entry.features:
+        result["features"] = entry.features
+    return result
+
+CapabilitiesRegistrationEntry = record(
+    style_id = field(str),
+    kind = field(str),
+    props = field(dict[str, typing.Any], {}),
+    features = field(dict[str, typing.Any], {}),
+)
+
+CapabilitiesRegistrationTSet = transitive_set(
+    json_projections = {
+        "manifest_entries": _project_as_manifest_json,
+    },
+)
+
+CapabilitiesRegistrationInfo = provider(
+    fields = {
+        "tset": provider_field(CapabilitiesRegistrationTSet | None, default = None),
+    }
+)
+
+def capabilities_registration_providers(ctx) -> list:
+    """Collect CapabilitiesRegistrationInfo from deps and create tset entry if this target has registrations."""
+    children = []
+    for dep in ctx.attrs.deps + ctx.attrs.exported_deps:
+        info = dep.get(CapabilitiesRegistrationInfo)
+        if info and info.tset:
+            children.append(info.tset)
+
+    registrations = getattr(ctx.attrs, "capabilities_registrations", None)
+    entries = []
+    if registrations:
+        for reg in registrations:
+            entries.append(
+                CapabilitiesRegistrationEntry(
+                    style_id = reg["style_id"],
+                    kind = reg["kind"],
+                    props = reg.get("props", {}),
+                    features = reg.get("features", {}),
+                )
+            )
+
+    if not entries and not children:
+        return []
+
+    if entries:
+        for entry in entries:
+            tset = ctx.actions.tset(CapabilitiesRegistrationTSet, value = entry, children = children)
+            children = [tset]
+        tset = children[0]
+    else:
+        tset = ctx.actions.tset(CapabilitiesRegistrationTSet, children = children)
+
+    return [CapabilitiesRegistrationInfo(tset = tset)]
diff --git a/buck2/prelude/cfg/exec_platform/marker.bzl b/buck2/prelude/cfg/exec_platform/marker.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/exec_platform/marker.bzl
@@ -0,0 +1,24 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Default exec platform marker constraint value.
+# This is the constraint value that gets injected into all execution platforms.
+_DEFAULT_EXEC_PLATFORM_MARKER = "prelude//cfg/exec_platform/marker:is_exec_platform[true]"
+
+def get_exec_platform_marker() -> str:
+    """
+    Get the exec platform marker constraint value target.
+
+    This reads from buckconfig `[build].exec_platform_marker` and defaults to
+    `prelude//cfg/exec_platform/marker:is_exec_platform[true]`.
+
+    Returns:
+        The target label string for the exec platform marker constraint value,
+        unless the buckconfig doesn't exist, then `_DEFAULT_EXEC_PLATFORM_MARKER`.
+    """
+    return read_root_config("build", "exec_platform_marker", _DEFAULT_EXEC_PLATFORM_MARKER)
diff --git a/buck2/prelude/cfg/exec_platform/marker/BUCK b/buck2/prelude/cfg/exec_platform/marker/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/exec_platform/marker/BUCK
@@ -0,0 +1,38 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:native.bzl", prelude = "native")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+# Execution platform marker constraint.
+# This constraint is used to distinguish execution platforms from target platforms.
+# When configuring exec deps, this marker will be present in the configuration,
+# allowing modifiers with execution_modifier=False to skip applying.
+
+# This constraint should be registered in the ExecutionPlatformRegistrationInfo
+
+exec_platform_marker_constraint(
+    name = "is_exec_platform",
+    default = "false",
+    values = [
+        "true",
+        "false",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+# Export BUCK file for inclusion in prelude//:prelude filegroup
+prelude.export_file(
+    name = "buck_file",
+    src = "BUCK",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/cfg/modifier/alias.bzl b/buck2/prelude/cfg/modifier/alias.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/modifier/alias.bzl
@@ -0,0 +1,29 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Modifier aliases that can be used on the CLI, ex. after `--modifier=` or in `?`.
+
+These aliases are ones we share between internal and OSS usages.
+All constraints used in these aliases must also be available in OSS.
+"""
+
+# It's represented as a struct where the attribute name is the alias and the string
+# for the attribute is the fully qualified target. Defining aliases in a struct
+# helps enforce that the alias names do not contain any bad character we cannot use on CLI.
+#
+# We define aliases for modifiers here rather than reusing `alias` section of buckconfig for
+# several reasons.
+# 1. `alias` buckconconfig is not well-designed. It only supports aliases in a cell and not
+# global aliases and users can override aliases in modefiles.
+# 2. Modifier aliases can point to conditional modifiers, which `alias` buckconfig does not
+# suppport.
+# 3. It's unlikely a user has to ever define an alias twice in both the `alias` buckconfig
+# and in modifier aliases because a modifier alias is a constraint value/config setting
+# and those don't typically get built on CLI.
+OSS_ALIASES = struct()
diff --git a/buck2/prelude/cfg/modifier/asserts.bzl b/buck2/prelude/cfg/modifier/asserts.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/modifier/asserts.bzl
@@ -0,0 +1,32 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cfg/modifier:types.bzl", "Modifier", "is_modifiers_match")
+
+def verify_normalized_target(target: str):
+    # Do some basic checks that target looks reasonably valid and normalized
+    # Targets should always be fully qualified to improve readability.
+    if "//" not in target or target.startswith("//") or ":" not in target:
+        fail(
+            "Must specify fully qualified target (ex. `cell//foo:bar`). Found `{}`".format(
+                target,
+            ),
+        )
+
+def verify_normalized_modifier(modifier: Modifier):
+    if modifier == None:
+        pass
+    elif is_modifiers_match(modifier):
+        # TODO(scottcao): Add a test case for this once `bxl_test` supports testing failures
+        for key, sub_modifier in modifier.items():
+            if key != "_type":
+                verify_normalized_modifier(sub_modifier)
+    elif isinstance(modifier, str):
+        verify_normalized_target(modifier)
+    else:
+        fail("Found unexpected modifier `{}` type `{}`".format(modifier, type(modifier)))
diff --git a/buck2/prelude/cfg/modifier/buckconfig_backed_modifiers.bzl b/buck2/prelude/cfg/modifier/buckconfig_backed_modifiers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/modifier/buckconfig_backed_modifiers.bzl
@@ -0,0 +1,130 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:buckconfig.bzl", "read_bool")
+load("@prelude//utils:type_defs.bzl", "is_bool")
+load(":types.bzl", "BuckconfigBackedModifierInfo", "ConditionalModifierInfo")
+
+def _convert_to_conditional_modifier_infos(modifiers: list[Dependency]) -> list[ConditionalModifierInfo]:
+    return [modifier[ConditionalModifierInfo] for modifier in modifiers]
+
+def _platform_deps_to_conditional_modifier_infos(platform_deps: list[Dependency]) -> list[ConditionalModifierInfo]:
+    result = []
+    for dep in platform_deps:
+        platform_info = dep[PlatformInfo]
+        for constraint_setting, constraint_value_info in platform_info.configuration.constraints.items():
+            result.append(
+                ConditionalModifierInfo(
+                    inner = constraint_value_info,
+                    key = constraint_setting,
+                )
+            )
+    return result
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    pre_platform_modifiers = _platform_deps_to_conditional_modifier_infos(ctx.attrs.pre_platform_platforms) + _convert_to_conditional_modifier_infos(
+        ctx.attrs.pre_platform_modifiers
+    )
+    post_platform_modifiers = _platform_deps_to_conditional_modifier_infos(ctx.attrs.post_platform_platforms) + _convert_to_conditional_modifier_infos(
+        ctx.attrs.post_platform_modifiers
+    )
+    pre_cli_modifiers = _platform_deps_to_conditional_modifier_infos(ctx.attrs.pre_cli_platforms) + _convert_to_conditional_modifier_infos(
+        ctx.attrs.pre_cli_modifiers
+    )
+
+    return [
+        DefaultInfo(),
+        BuckconfigBackedModifierInfo(
+            pre_platform_modifiers = pre_platform_modifiers, post_platform_modifiers = post_platform_modifiers, pre_cli_modifiers = pre_cli_modifiers
+        ),
+    ]
+
+_buckconfig_backed_modifiers = rule(
+    impl = _impl,
+    is_configuration_rule = True,
+    attrs = {
+        "post_platform_modifiers": attrs.list(attrs.dep(providers = [ConditionalModifierInfo])),
+        "post_platform_platforms": attrs.list(attrs.dep(providers = [PlatformInfo]), default = []),
+        "pre_cli_modifiers": attrs.list(attrs.dep(providers = [ConditionalModifierInfo])),
+        "pre_cli_platforms": attrs.list(attrs.dep(providers = [PlatformInfo]), default = []),
+        "pre_platform_modifiers": attrs.list(attrs.dep(providers = [ConditionalModifierInfo])),
+        "pre_platform_platforms": attrs.list(attrs.dep(providers = [PlatformInfo]), default = []),
+    },
+)
+
+# Supports specifying one or more modifiers or platforms that can be enabled by a buckconfig.
+BuckconfigBackedModifier = record(
+    section = str,
+    property = str,
+    value = str | bool | None,
+    modifiers = field(list[str], default = []),
+    platforms = field(list[str], default = []),
+    oncall = str,
+)
+
+IS_SET_VALUE = "__is_set__"
+
+def _buckconfig_matches(entry: BuckconfigBackedModifier) -> bool:
+    if is_bool(entry.value):
+        return read_bool(entry.section, entry.property, required = False) == entry.value
+    elif entry.value == IS_SET_VALUE:
+        return read_config(entry.section, entry.property) != None
+    else:
+        return read_config(entry.section, entry.property) == entry.value
+
+def _convert_to_modifiers(entries: list[BuckconfigBackedModifier]) -> list[str]:
+    modifiers = []
+    for entry in entries:
+        if _buckconfig_matches(entry):
+            modifiers += entry.modifiers
+    return modifiers
+
+def _convert_to_platforms(entries: list[BuckconfigBackedModifier]) -> list[str]:
+    platforms = []
+    for entry in entries:
+        if _buckconfig_matches(entry):
+            platforms += entry.platforms
+    return platforms
+
+def buckconfig_backed_modifiers(
+    name: str, pre_platform: list[BuckconfigBackedModifier], post_platform: list[BuckconfigBackedModifier], pre_cli: list[BuckconfigBackedModifier]
+):
+    """
+    Enable buckconfigs to become modifiers.
+    We need this so that we can migrate `read_config`s to selects without having to worry about
+    having all builds specifying these buckconfigs to specify modifiers for them instead.
+
+    Buckconfigs are read from `toolchains` cell in order to identify buckconfigs
+    specified in modefiles on CLI, as opposed to buckconfigs specified in .buckconfig files per cells.
+
+    Each `BuckconfigBackedModifier` entry can specify `modifiers` (individual constraint value targets)
+    and/or `platforms` (platform targets whose constraints are applied). At least one must be non-empty.
+
+    Args:
+    `pre_platform`: These modifiers apply before the legacy target
+        platform, so they can get overriden by the legacy platform + every modifier specified.
+    `post_platform`: These modifiers apply after the legacy target platform, so they can override
+        the legacy platform but PACKAGE/target/CLI modifiers all override them.
+    `pre_cli`: These modifiers apply before the CLI modifiers, so they can override PACKAGE
+        and target modifiers but still can be overriden by CLI modifiers.
+
+    """
+    for entries in (pre_platform, post_platform, pre_cli):
+        for entry in entries:
+            if not entry.modifiers and not entry.platforms:
+                fail("BuckconfigBackedModifier for {}.{} must specify at least one of `modifiers` or `platforms`".format(entry.section, entry.property))
+
+    _buckconfig_backed_modifiers(
+        name = name,
+        pre_platform_modifiers = _convert_to_modifiers(pre_platform),
+        post_platform_modifiers = _convert_to_modifiers(post_platform),
+        pre_cli_modifiers = _convert_to_modifiers(pre_cli),
+        pre_platform_platforms = _convert_to_platforms(pre_platform),
+        post_platform_platforms = _convert_to_platforms(post_platform),
+        pre_cli_platforms = _convert_to_platforms(pre_cli),
+    )
diff --git a/buck2/prelude/cfg/modifier/cfg_constructor.bzl b/buck2/prelude/cfg/modifier/cfg_constructor.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/modifier/cfg_constructor.bzl
@@ -0,0 +1,196 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    ":common.bzl",
+    "apply_buckconfig_backed_modifiers",
+    "get_and_insert_modifier_info",
+    "json_to_tagged_modifiers",
+    "modifier_to_refs",
+    "resolve_alias",
+    "resolve_configuration",
+)
+load(
+    ":types.bzl",
+    "BuckconfigBackedModifierInfo",
+    "Modifier",  # @unused
+    "ModifierCliLocation",
+    "ModifierTargetLocation",
+    "TaggedModifiers",
+)
+
+PostConstraintAnalysisParams = record(
+    legacy_platform = PlatformInfo | None,
+    package_modifiers = list[TaggedModifiers],
+    target_modifiers = list[Modifier],
+    cli_modifiers = list[Modifier],
+    extra_data = struct,
+    configuring_exec_dep = bool,
+)
+
+def _get_buckconfig_backed_modifiers(extra_data: struct, configuring_exec_dep: bool) -> str | None:
+    # If we are configuring an exec dep, we don't want to apply any modifiers from buckconfig.
+    if configuring_exec_dep:
+        return None
+    return getattr(extra_data, "buckconfig_backed_modifiers", None)
+
+def _has_buckconfig_backed_modifiers(refs: dict[str, ProviderCollection], target: str | None) -> bool:
+    if not target:
+        return False
+    info = refs[target][BuckconfigBackedModifierInfo]
+    return bool(info.pre_platform_modifiers or info.post_platform_modifiers or info.pre_cli_modifiers)
+
+def cfg_constructor_pre_constraint_analysis(
+    *,
+    legacy_platform: PlatformInfo | None,
+    # dict[str, typing.Any] is JSON dictionary form of `TaggedModifier` passed from buck2 core
+    package_modifiers: list[dict[str, typing.Any]] | None,
+    # typing.Any is JSON form of modifier
+    target_modifiers: list[Modifier] | None,
+    cli_modifiers: list[str],
+    rule_name: str,
+    aliases: struct,
+    extra_data: struct,
+    configuring_exec_dep: bool,
+    **_kwargs,
+) -> (list[str], PostConstraintAnalysisParams):
+    """
+    First stage of cfg constructor for modifiers.
+
+    Args:
+        legacy_platform:
+            PlatformInfo from legacy target platform resolution, if one is specified
+        package_modifiers:
+            A list of modifiers specified from all parent PACKAGE files
+        target_modifiers:
+            A list of modifiers specified from buildfile via `metadata` attribute.
+        cli_modifiers:
+            modifiers specified from `--modifier` flag, `?modifier`, or BXL
+        aliases:
+            A struct that contains mapping of modifier aliases to modifier.
+        extra_data:
+            Some extra data that is for extra logging/validation for our internal modifier implementation.
+        configuring_exec_dep (bool):
+            Indicates whether this target is being configured as an execution dependency (exec_dep).
+            When True, this flag enables the cfg_constructor to apply exec-specific modifier resolution logic.
+
+    Returns `(refs, PostConstraintAnalysisParams)`, where `refs` is a list of fully qualified configuration
+    targets we need providers for.
+    """
+    package_modifiers = package_modifiers or []
+    target_modifiers = target_modifiers or []
+
+    # Convert JSONs back to TaggedModifiers
+    package_modifiers = [json_to_tagged_modifiers(modifier_json) for modifier_json in package_modifiers]
+
+    # Filter PACKAGE modifiers based on rule name.
+    # This only filters out PACKAGE modifiers from `extra_cfg_modifiers_per_rule` argument of `set_cfg_modifiers` function.
+    package_modifiers = [
+        tagged_modifiers for tagged_modifiers in package_modifiers if tagged_modifiers.rule_name == None or tagged_modifiers.rule_name == rule_name
+    ]
+
+    # Resolve all aliases in CLI modifiers
+    cli_modifiers = [resolved_modifier for modifier in cli_modifiers for resolved_modifier in resolve_alias(modifier, aliases)]
+
+    refs = []
+    buckconfig_backed_modifiers = _get_buckconfig_backed_modifiers(extra_data, configuring_exec_dep)
+    if buckconfig_backed_modifiers:
+        refs.append(buckconfig_backed_modifiers)
+
+    for tagged_modifiers in package_modifiers:
+        for modifier in tagged_modifiers.modifiers:
+            refs.extend(modifier_to_refs(modifier, tagged_modifiers.location))
+    for modifier in target_modifiers:
+        refs.extend(modifier_to_refs(modifier, ModifierTargetLocation()))
+    for modifier in cli_modifiers:
+        refs.extend(modifier_to_refs(modifier, ModifierCliLocation()))
+
+    return refs, PostConstraintAnalysisParams(
+        legacy_platform = legacy_platform,
+        package_modifiers = package_modifiers,
+        target_modifiers = target_modifiers,
+        cli_modifiers = cli_modifiers,
+        extra_data = extra_data,
+        configuring_exec_dep = configuring_exec_dep,
+    )
+
+def cfg_constructor_post_constraint_analysis(*, refs: dict[str, ProviderCollection], params: PostConstraintAnalysisParams) -> PlatformInfo:
+    """
+    Second stage of cfg constructor for modifiers.
+
+    Args:
+        refs: a dictionary of fully qualified target labels for configuration targets with their providers
+        params: `PostConstraintAnalysisParams` returned from first stage of cfg constructor
+
+    Returns a PlatformInfo
+    """
+
+    buckconfig_backed_modifiers = _get_buckconfig_backed_modifiers(params.extra_data, params.configuring_exec_dep)
+    if not (params.package_modifiers or params.target_modifiers or params.cli_modifiers or _has_buckconfig_backed_modifiers(refs, buckconfig_backed_modifiers)):
+        # If there is no modifier and legacy platform is specified,
+        # then return the legacy platform as is without changing the label or
+        # configuration.
+        return params.legacy_platform or PlatformInfo(
+            # Empty configuration
+            label = "<empty>",
+            configuration = ConfigurationInfo(
+                constraints = {},
+                values = {},
+            ),
+        )
+
+    constraint_setting_to_modifier_infos = {}
+
+    if buckconfig_backed_modifiers:
+        apply_buckconfig_backed_modifiers(
+            constraint_setting_to_modifier_infos, refs[buckconfig_backed_modifiers][BuckconfigBackedModifierInfo].pre_platform_modifiers
+        )
+
+    if params.legacy_platform:
+        for constraint_setting, constraint_value_info in params.legacy_platform.configuration.constraints.items():
+            constraint_setting_to_modifier_infos[constraint_setting] = [constraint_value_info]
+
+    if buckconfig_backed_modifiers:
+        apply_buckconfig_backed_modifiers(
+            constraint_setting_to_modifier_infos, refs[buckconfig_backed_modifiers][BuckconfigBackedModifierInfo].post_platform_modifiers
+        )
+
+    for tagged_modifiers in params.package_modifiers:
+        for modifier in tagged_modifiers.modifiers:
+            if modifier:
+                get_and_insert_modifier_info(
+                    constraint_setting_to_modifier_infos = constraint_setting_to_modifier_infos,
+                    refs = refs,
+                    modifier = modifier,
+                    location = tagged_modifiers.location,
+                )
+
+    for modifier in params.target_modifiers:
+        if modifier:
+            get_and_insert_modifier_info(
+                constraint_setting_to_modifier_infos = constraint_setting_to_modifier_infos,
+                refs = refs,
+                modifier = modifier,
+                location = ModifierTargetLocation(),
+            )
+
+    if buckconfig_backed_modifiers:
+        apply_buckconfig_backed_modifiers(
+            constraint_setting_to_modifier_infos, refs[buckconfig_backed_modifiers][BuckconfigBackedModifierInfo].pre_cli_modifiers
+        )
+
+    for modifier in params.cli_modifiers:
+        if modifier:
+            get_and_insert_modifier_info(
+                constraint_setting_to_modifier_infos = constraint_setting_to_modifier_infos,
+                refs = refs,
+                modifier = modifier,
+                location = ModifierCliLocation(),
+            )
+
+    return resolve_configuration(constraint_setting_to_modifier_infos)
diff --git a/buck2/prelude/cfg/modifier/common.bzl b/buck2/prelude/cfg/modifier/common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/modifier/common.bzl
@@ -0,0 +1,310 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:asserts.bzl", "asserts")
+load("@prelude//utils:graph_utils.bzl", "post_order_traversal")
+load(":asserts.bzl", "verify_normalized_modifier")
+load(":name.bzl", "cfg_name")
+load(
+    ":types.bzl",
+    "ConditionalModifierInfo",
+    "Modifier",
+    "ModifierBuckconfigLocation",
+    "ModifierCliLocation",
+    "ModifierInfo",
+    "ModifierLocation",
+    "ModifierPackageLocation",
+    "ModifierTargetLocation",
+    "ModifiersMatchInfo",
+    "TaggedModifiers",
+    "is_modifiers_match",
+)
+
+# Key under which `set_cfg_modifiers()` writes its PACKAGE-level cfg modifiers
+# (consumed by `set_cfg_constructor(key = MODIFIER_METADATA_KEY, ...)`). The
+# string value collides with the historical per-target `metadata["buck.cfg_modifiers"]`
+# key, which is no longer supported - per-target modifiers must use the first-class
+# `modifiers` attribute.
+MODIFIER_METADATA_KEY = "buck.cfg_modifiers"
+
+_TARGET_LOCATION_STR = "`modifiers` attribute of target"
+_CLI_LOCATION_STR = "command line"
+
+def location_to_string(location: ModifierLocation) -> str:
+    if isinstance(location, ModifierPackageLocation):
+        return location.package_path
+    if isinstance(location, ModifierTargetLocation):
+        return _TARGET_LOCATION_STR
+    if isinstance(location, ModifierCliLocation):
+        return _CLI_LOCATION_STR
+    if isinstance(location, ModifierBuckconfigLocation):
+        return "buckconfig {}.{}".format(location.section, location.property)
+    fail("Internal error. Unrecognized location type `{}` for location `{}`".format(type(location), location))
+
+def get_tagged_modifiers(
+    cfg_modifiers: list[Modifier], extra_cfg_modifiers_per_rule: dict[str, list[Modifier]], location: ModifierLocation
+) -> list[TaggedModifiers]:
+    for modifier in cfg_modifiers:
+        verify_normalized_modifier(modifier)
+    for _, modifiers in extra_cfg_modifiers_per_rule.items():
+        for modifier in modifiers:
+            verify_normalized_modifier(modifier)
+
+    # Aggreggate all tagged modifiers in a PACKAGE in a single list.
+    # Per-rule modifiers come the global modifiers so that they are processed later.
+    return [
+        TaggedModifiers(
+            modifiers = cfg_modifiers,
+            location = location,
+            rule_name = None,
+        ),
+    ] + [
+        TaggedModifiers(
+            modifiers = modifiers,
+            location = location,
+            rule_name = rule_name,
+        )
+        for rule_name, modifiers in extra_cfg_modifiers_per_rule.items()
+    ]
+
+def get_constraint_setting(constraint_settings: set[TargetLabel], modifier: Modifier, location: ModifierLocation) -> TargetLabel:
+    if len(constraint_settings) == 0:
+        fail("`modifiers.match` cannot be empty. Found empty `modifiers.match` at `{}`".format(location_to_string(location)))
+    if len(constraint_settings) > 1:
+        fail(
+            "A single modifier can only modify a single constraint setting.\n"
+            + "Modifier `{}` from `{}` is found to modify the following constraint settings:\n".format(
+                modifier,
+                location_to_string(location),
+            )
+            + "\n".join([str(k) for k in constraint_settings]),
+        )
+    return list(constraint_settings)[0]
+
+def get_modifier_info(refs: dict[str, ProviderCollection], modifier: Modifier, location: ModifierLocation) -> (TargetLabel, ModifierInfo) | None:
+    # Gets a modifier info from a modifier based on providers from `refs`.
+    if modifier == None:
+        return None
+    if is_modifiers_match(modifier):
+        default = None
+        modifiers_match_info = []
+        constraint_settings = set()
+        for key, sub_modifier in modifier.items():
+            if key == "DEFAULT":
+                if sub_modifier:
+                    default_constraint_setting, default = get_modifier_info(refs, sub_modifier, location)
+                    constraint_settings.add(default_constraint_setting)
+                else:
+                    default = None
+            elif key != "_type":
+                cfg_info = refs[key][ConfigurationInfo]
+                root_values = cfg_info.root_values
+                if cfg_info.values or root_values:
+                    buckconfig_values = cfg_info.values | root_values
+                    soft_error(
+                        "starlark_config_setting_non_empty_buckconfig_values_in_conditional_modifier",
+                        "config_setting `{}` defines buckconfig values {} which are NOT supported in conditional modifiers.\n".format(key, buckconfig_values)
+                        + "These buckconfig values are being IGNORED.\n\n"
+                        + "Action required: Remove the `values` and `root_values` parameters from this config_setting {} and use only `constraint_values` instead.\n".format(
+                            key
+                        )
+                        + "Note: This may become a hard error in the future to prevent silent misconfiguration.",
+                        quiet = True,
+                        stack = False,
+                    )
+                if sub_modifier:
+                    sub_constraint_setting, sub_modifier_info = get_modifier_info(refs, sub_modifier, location)
+                    constraint_settings.add(sub_constraint_setting)
+                else:
+                    sub_modifier_info = None
+                modifiers_match_info.append((cfg_info, sub_modifier_info))
+
+        constraint_setting = get_constraint_setting(constraint_settings, modifier, location)
+
+        return constraint_setting, ModifiersMatchInfo(
+            default = default,
+            selector = modifiers_match_info,
+        )
+    if isinstance(modifier, str):
+        modifier_info = refs[modifier]
+        if ConditionalModifierInfo in modifier_info:
+            conditional_modifier_info = modifier_info[ConditionalModifierInfo]
+            return conditional_modifier_info.key, conditional_modifier_info.inner
+        cfg_info = modifier_info[ConfigurationInfo]
+        asserts.true(len(cfg_info.constraints) == 1, "Modifier should only be a single constraint value. Found multiple or none in `{}`".format(modifier))
+        fail(
+            "Internal error: Modifer (`{}` type `{}`) with single constraint value should have ConditionalModifierInfo provider.".format(
+                modifier_info, type(modifier_info)
+            )
+        )
+    fail("Internal error: Found unexpected modifier `{}` type `{}`".format(modifier, type(modifier)))
+
+def _is_subset(a: ConfigurationInfo, b: ConfigurationInfo) -> bool:
+    for _constraint_setting, a_constraint_value in a.constraints.items():
+        setting_info = a_constraint_value.setting
+        b_constraint_value = b.get(setting_info)
+        if a_constraint_value != b_constraint_value:
+            return False
+    return True
+
+def resolve_modifier(cfg: ConfigurationInfo, modifier: ModifierInfo) -> ConstraintValueInfo | None:
+    # Resolve the modifier and return the constraint value to add to the configuration, if there is one
+    if modifier == None:
+        return None
+    if isinstance(modifier, ModifiersMatchInfo):
+        for key, sub_modifier in modifier.selector:
+            if _is_subset(key, cfg):
+                # If constraints in key of the select are a subset of the constraints in the
+                # current configuration, then it's a match.
+                return resolve_modifier(cfg, sub_modifier)
+        if modifier.default:
+            return resolve_modifier(cfg, modifier.default)
+        return None
+    if isinstance(modifier, ConstraintValueInfo):
+        return modifier
+    fail("Internal error: Found unexpected modifier `{}` type `{}`".format(modifier, type(modifier)))
+
+def resolve_configuration(constraint_setting_to_modifier_infos: dict[TargetLabel, list[ModifierInfo]]) -> PlatformInfo:
+    # Modifiers are resolved in topological ordering of modifier selects. For example, if the CPU modifier
+    # is a modifier_select on OS constraint, then the OS modifier must be resolved before the CPU modifier.
+    # To determine this order, we first construct a dep graph of constraint settings based on the modifier
+    # selects. Then we perform a post order traversal of the said graph.
+    modifier_dep_graph = {
+        constraint_setting: [dep for modifier_info in modifier_infos for dep in get_constraint_setting_deps(modifier_info)]
+        for constraint_setting, modifier_infos in constraint_setting_to_modifier_infos.items()
+    }
+
+    # For topo-sort, we need to fill in empty edges for nodes that have no deps
+    for deps in modifier_dep_graph.values():
+        for dep in deps:
+            if dep not in modifier_dep_graph:
+                modifier_dep_graph[dep] = []
+
+    constraint_setting_order = post_order_traversal(modifier_dep_graph)
+
+    cfg = ConfigurationInfo(
+        constraints = {},
+        values = {},
+    )
+
+    for constraint_setting in constraint_setting_order:
+        for modifier_info in constraint_setting_to_modifier_infos.get(constraint_setting) or ():
+            constraint_value = resolve_modifier(cfg, modifier_info)
+            if constraint_value:
+                cfg.constraints[constraint_setting] = constraint_value
+
+    name = cfg_name(cfg)
+    return PlatformInfo(
+        label = name,
+        configuration = cfg,
+    )
+
+def modifier_to_refs(modifier: Modifier, location: ModifierLocation) -> list[str]:
+    # Obtain a list of targets to analyze from a modifier.
+    refs = []
+    if modifier == None:
+        pass
+    elif is_modifiers_match(modifier):
+        for key, sub_modifier in modifier.items():
+            if key != "_type":
+                if key != "DEFAULT":
+                    refs.append(key)
+                refs.extend(modifier_to_refs(sub_modifier, location))
+    elif isinstance(modifier, str):
+        refs.append(modifier)
+    else:
+        fail("Internal error: Found unexpected modifier `{}` type `{}`".format(modifier, type(modifier)))
+    return refs
+
+def tagged_modifiers_to_json(tagged_modifiers: TaggedModifiers) -> dict[str, typing.Any]:
+    return {
+        "location": _location_to_json(tagged_modifiers.location),
+        "modifiers": tagged_modifiers.modifiers,
+        "rule_name": tagged_modifiers.rule_name,
+        "_type": "TaggedModifiers",
+    }
+
+def _location_to_json(location: ModifierLocation) -> dict[str, str]:
+    if isinstance(location, ModifierPackageLocation):
+        return {"package_path": location.package_path, "_type": "ModifierPackageLocation"}
+    if isinstance(location, ModifierTargetLocation):
+        return {"_type": "ModifierTargetLocation"}
+    fail("Internal error: unknown location `{}` with type `{}`".format(location, type(location)))
+
+def json_to_tagged_modifiers(j: dict[str, typing.Any]) -> TaggedModifiers:
+    if j["_type"] != "TaggedModifiers":
+        fail("Internal error: `{}` is not a `TaggedModifiers`".format(j))
+    return TaggedModifiers(
+        location = _json_to_location(j["location"]),
+        modifiers = j["modifiers"],
+        rule_name = j["rule_name"],
+    )
+
+def _json_to_location(j: dict[str, str]) -> ModifierLocation:
+    modifier_type = j.pop("_type")
+    if modifier_type == "ModifierPackageLocation":
+        return ModifierPackageLocation(package_path = j["package_path"])
+    if modifier_type == "ModifierTargetLocation":
+        return ModifierTargetLocation()
+    fail("Internal error: cannot deserialize location `{}`".format(j))
+
+def resolve_alias(modifier: Modifier, aliases: struct) -> list[Modifier]:
+    if isinstance(modifier, ModifiersMatchInfo):
+        fail("It should not be possible to specify a conditional modifier from command line")
+    if ":" in modifier:
+        # This is a target and not an alias
+        return [modifier]
+    resolved = getattr(aliases, modifier, None)
+    if resolved:
+        return resolved if isinstance(resolved, list) else [resolved]
+    fail("Found invalid modifier alias `{}`. A list of valid modifier aliases is in buck2/cfg/experimental/alias.bzl".format(modifier))
+
+def _get_constraint_setting_deps(modifier_info: ModifierInfo) -> list[TargetLabel]:
+    deps = []
+    if isinstance(modifier_info, ModifiersMatchInfo):
+        for key, sub_modifier in modifier_info.selector:
+            for constraint_setting in key.constraints:
+                deps.append(constraint_setting)
+            deps += _get_constraint_setting_deps(sub_modifier)
+        if modifier_info.default:
+            deps += _get_constraint_setting_deps(modifier_info.default)
+    return deps
+
+def get_constraint_setting_deps(modifier_info: ModifierInfo) -> list[TargetLabel]:
+    # Get all constraint settings depended on by a modifier (from keys of `modifier_select`). The modifiers
+    # for these constraint settings must be resolved before this modifier can be resolved.
+    return dedupe(_get_constraint_setting_deps(modifier_info))
+
+def add_to_constraint_setting_to_modifier_infos(
+    constraint_setting_to_modifier_infos: dict[TargetLabel, list[ModifierInfo]], constraint_setting_label: TargetLabel, modifier_info: ModifierInfo
+):
+    modifier_infos = constraint_setting_to_modifier_infos.get(constraint_setting_label) or []
+    modifier_infos.append(modifier_info)
+    constraint_setting_to_modifier_infos[constraint_setting_label] = modifier_infos
+
+def get_and_insert_modifier_info(
+    constraint_setting_to_modifier_infos: dict[TargetLabel, list[ModifierInfo]],
+    refs: dict[str, ProviderCollection],
+    modifier: Modifier,
+    location: ModifierLocation,
+) -> (TargetLabel, ModifierInfo):
+    constraint_setting_label, modifier_info = get_modifier_info(
+        refs = refs,
+        modifier = modifier,
+        location = location,
+    )
+    add_to_constraint_setting_to_modifier_infos(constraint_setting_to_modifier_infos, constraint_setting_label, modifier_info)
+    return (constraint_setting_label, modifier_info)
+
+def apply_buckconfig_backed_modifiers(constraint_setting_to_modifier_infos: dict[TargetLabel, list[ModifierInfo]], modifiers: list[ConditionalModifierInfo]):
+    for conditional_modifier_info in modifiers:
+        add_to_constraint_setting_to_modifier_infos(
+            constraint_setting_to_modifier_infos = constraint_setting_to_modifier_infos,
+            constraint_setting_label = conditional_modifier_info.key,
+            modifier_info = conditional_modifier_info.inner,
+        )
diff --git a/buck2/prelude/cfg/modifier/conditional_modifier.bzl b/buck2/prelude/cfg/modifier/conditional_modifier.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/modifier/conditional_modifier.bzl
@@ -0,0 +1,163 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":types.bzl", "ConditionalModifierInfo", "Modifier", "ModifiersMatch", "ModifiersMatchInfo")
+
+def _get_constraint_setting(constraint_settings: set[TargetLabel], modifier: ModifiersMatch) -> TargetLabel:
+    if len(constraint_settings) == 0:
+        fail("Conditional modifier cannot be empty. Found empty modifier `{}`".format(modifier))
+    if len(constraint_settings) > 1:
+        fail(
+            "A single modifier can only modify a single constraint setting.\n"
+            + "Modifier `{}` is found to modify the following constraint settings:\n".format(
+                modifier,
+            )
+            + "\n".join([str(k) for k in constraint_settings]),
+        )
+    return list(constraint_settings)[0]
+
+def _get_modifier_info(
+    modifier: Modifier, key_to_provider: dict[str, ConfigurationInfo], value_to_provider: dict[str, ConditionalModifierInfo]
+) -> ConditionalModifierInfo | None:
+    """
+    Converts a modifier to a provider based on providers for keys and values.
+    """
+    if modifier == None:
+        return None
+
+    if isinstance(modifier, str):
+        return value_to_provider[modifier]
+
+    default = None
+    modifiers_match_info = []
+    constraint_settings = set()
+
+    for key, sub_modifier in modifier.items():
+        if key == "DEFAULT":
+            if sub_modifier:
+                sub_modifier_info = _get_modifier_info(sub_modifier, key_to_provider, value_to_provider)
+                constraint_settings.add(sub_modifier_info.key)
+                default = sub_modifier_info.inner
+        else:
+            cfg_info = key_to_provider[key]
+            if sub_modifier:
+                sub_modifier_info = _get_modifier_info(sub_modifier, key_to_provider, value_to_provider)
+                constraint_settings.add(sub_modifier_info.key)
+                sub_modifier_info = sub_modifier_info.inner
+            else:
+                sub_modifier_info = None
+            modifiers_match_info.append((cfg_info, sub_modifier_info))
+
+    constraint_setting = _get_constraint_setting(constraint_settings, modifier)
+    return ConditionalModifierInfo(
+        key = constraint_setting,
+        inner = ModifiersMatchInfo(
+            default = default,
+            selector = modifiers_match_info,
+        ),
+    )
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    key_to_provider = {k: dep.get(ConfigurationInfo) for k, dep in ctx.attrs._conditional_keys.items()}
+    value_to_provider = {k: dep.get(ConditionalModifierInfo) for k, dep in ctx.attrs._conditional_values.items()}
+    conditional_modifier_info = _get_modifier_info(ctx.attrs.modifier, key_to_provider, value_to_provider)
+    return [DefaultInfo(), conditional_modifier_info]
+
+_conditional_modifier = rule(
+    impl = _impl,
+    doc = """
+        A `_conditional_modifier` rule instantiates a conditional modifier that can be set on a target.
+        This is a private rule. You want to instantiate it through  the `conditional_modifier` function wrapper.
+
+        The conditional modifier allows one to express a modifier in a dictionary form similar to a select, where
+        each key in the dictionary is a set of constraints to match on and each value in the dictionary is a modifier.
+
+        For example, below is a modifier for expressing "msvc if windows else clang".
+
+        ```python
+        conditional_modifier(
+            name = "clang-msvc",
+            modifier = {
+                "DEFAULT": "prelude//constraints/compiler:clang",
+                "prelude//constraints/os:windows": "prelude//constraints/compiler:msvc",
+            },
+        )
+        ```
+
+        A conditional modifier can be nested similar to a nested select.
+
+        ```python
+        conditional_modifier(
+            name = "clang-msvc-gcc",
+            modifier = {
+                "DEFAULT": {
+                    "DEFAULT": "prelude//constraints/compiler:clang",
+                    "prelude//constraints/os:linux": "prelude//constraints/compiler:gcc",
+                },
+                "prelude//constraints/os:windows": "prelude//constraints/compiler:msvc",
+            },
+        )
+        ```
+
+        A conditional modifier can also take in another conditional modifier. For example, the modifier from the
+        previous example can also be expressed as follows.
+
+        ```python
+        conditional_modifier(
+            name = "clang-msvc-gcc2",
+            modifier = {
+                "DEFAULT": ":clang-msvc":
+                "prelude//constraints/os:linux": "prelude//constraints/compiler:gcc",
+            }
+        )
+        ```
+    """,
+    attrs = {
+        "modifier": attrs.any(doc = "A conditional modifier to set"),
+        # _conditional_keys maps original modifier keys to resolved providers
+        # We preserve the original key strings because they are matched against
+        # unmodified strings in the conditional modifier. Deriving the expected
+        # string from dep.label fails when cell aliases are used.
+        "_conditional_keys": attrs.dict(attrs.string(), attrs.dep(providers = [ConfigurationInfo]), doc = "internal attribute"),
+        # _conditional_values maps original modifier values to resolved providers.
+        # Reasoning for using a dict is the same as for _conditional_keys.
+        "_conditional_values": attrs.dict(attrs.string(), attrs.dep(providers = [ConditionalModifierInfo]), doc = "internal attribute"),
+    },
+    is_configuration_rule = True,
+)
+
+def _get_conditional_keys(modifier: ModifiersMatch) -> dict[str, str]:
+    result = {k: k for k in modifier.keys() if k != "DEFAULT"}
+    for v in modifier.values():
+        if isinstance(v, dict):
+            result.update(_get_conditional_keys(v))
+        elif v and not isinstance(v, str):
+            fail("`{}` is not a valid modifier".format(v))
+    return result
+
+def _get_conditional_values(modifier: ModifiersMatch) -> dict[str, str]:
+    result = {}
+    for v in modifier.values():
+        if isinstance(v, dict):
+            result.update(_get_conditional_values(v))
+        elif isinstance(v, str):
+            result[v] = v
+        elif v:
+            fail("`{}` is not a valid modifier".format(v))
+    return result
+
+def conditional_modifier(name: str, modifier: ModifiersMatch):
+    _conditional_modifier(
+        name = name,
+        _conditional_keys = _get_conditional_keys(modifier),
+        _conditional_values = _get_conditional_values(modifier),
+        modifier = modifier,
+    )
+
+# Exported for testing purposes only. Do not use in production code.
+get_modifier_info_for_testing = _get_modifier_info
diff --git a/buck2/prelude/cfg/modifier/constraint_modifier_info.bzl b/buck2/prelude/cfg/modifier/constraint_modifier_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/modifier/constraint_modifier_info.bzl
@@ -0,0 +1,84 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Functions for constructing ConditionalModifierInfo for constraint rules.
+
+This module provides utilities to create ConditionalModifierInfo instances
+with proper handling of execution platform modifiers. When a constraint has
+execution_modifier=False, its modifier will be wrapped in a conditional that
+skips it when configuring exec deps.
+"""
+
+load(":types.bzl", "ConditionalModifierInfo", "ModifierInfo", "ModifiersMatchInfo")
+
+def _maybe_wrap_for_exec_platform(
+    constraint_value: ConstraintValueInfo, execution_modifier: bool, exec_platform_marker_configuration_info: ConfigurationInfo | None
+) -> ModifierInfo:
+    """
+    When execution_modifier=False, wrap the constraint value in a conditional
+    modifier that returns None (skips) when the exec platform marker
+    (ovr_config//platform/execution/constraints:execution-platform-transitioned)
+    is present in the configuration. This means modifiers with
+    execution_modifier=False won't apply when configuring exec deps.
+
+    Args:
+        constraint_value: The constraint value to potentially wrap.
+        execution_modifier: If True, the modifier applies to exec deps, so no wrapping needed.
+        exec_platform_marker_configuration_info: The ConfigurationInfo for the exec platform marker.
+                                                  If None, no wrapping is done.
+
+    Returns:
+        Either the original constraint_value (if execution_modifier=True or no marker),
+        or a ModifiersMatchInfo that conditionally skips on exec platforms.
+    """
+    if execution_modifier:
+        # This modifier should apply on exec platforms, no wrapping needed
+        return constraint_value
+
+    if exec_platform_marker_configuration_info == None:
+        # No marker constraint available (e.g., for the marker constraint itself)
+        return constraint_value
+
+    # Wrap in a conditional: when exec marker is present -> None (skip), otherwise -> apply
+    return ModifiersMatchInfo(
+        selector = [(exec_platform_marker_configuration_info, None)],  # Skip when on exec platform
+        default = constraint_value,  # Apply on target platform
+    )
+
+def make_constraint_modifier_info(
+    constraint_value: ConstraintValueInfo, key: TargetLabel, execution_modifier: bool, exec_platform_marker_configuration_info: ConfigurationInfo | None
+) -> ConditionalModifierInfo:
+    """
+    Creates a ConditionalModifierInfo for a constraint value with proper
+    handling of execution platform modifiers.
+
+    When execution_modifier=False and exec_platform_marker_configuration_info is provided,
+    the inner value will be wrapped in a ModifiersMatchInfo that causes the
+    modifier to be skipped when configuring exec deps.
+
+    Args:
+        constraint_value: The constraint value this modifier represents.
+        key: The constraint setting's target label (used as the modifier key).
+        execution_modifier: Whether this modifier should apply on exec platforms.
+        exec_platform_marker_configuration_info: The ConfigurationInfo for the exec platform marker.
+                                                  Pass None for the marker constraint itself to avoid cycles.
+
+    Returns:
+        A ConditionalModifierInfo with the appropriate inner value.
+    """
+    wrapped_inner = _maybe_wrap_for_exec_platform(
+        constraint_value = constraint_value,
+        execution_modifier = execution_modifier,
+        exec_platform_marker_configuration_info = exec_platform_marker_configuration_info,
+    )
+
+    return ConditionalModifierInfo(
+        inner = wrapped_inner,
+        key = key,
+    )
diff --git a/buck2/prelude/cfg/modifier/name.bzl b/buck2/prelude/cfg/modifier/name.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/modifier/name.bzl
@@ -0,0 +1,70 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# This is an ordered dictionary of constraint setting target to an optional transform.
+# The constraint settings listed below are used to name the configuration, where the first
+# constraint settings are named first in the configuration. The transform, if specified,
+# can change how the name appears in the configuration. By default, if there is no transform,
+# we just use name of the constraint value in the configuration name. If transform is
+# specified, the transform will be applied on the existing constraint value name to return a
+# new string to be used in the configuration.
+# @unsorted-dict-items
+NAMED_CONSTRAINT_SETTINGS = {
+    # TODO(scottcao): Add OSS constraints as well
+    "ovr_config//build_mode/constraints:core_build_mode": (lambda label: str(label.sub_target[0])),
+    "ovr_config//os/constraints:os": (lambda label: str(label.sub_target[0])),
+    "ovr_config//cpu/constraints:cpu": None,
+    "ovr_config//runtime/constraints:runtime": None,
+    "ovr_config//runtime/constraints:runtime_version": None,
+    "ovr_config//os/sdk/apple/constraints:_": (lambda label: str(label.sub_target[0])),
+    "ovr_config//os/sdk/android/ndk/constraints:version": None,
+    "ovr_config//os/version/android/constraints:api-level": (lambda label: "api" + str(label.name).split("-")[-1]),
+    "ovr_config//toolchain/clang/constraints:clang-toolchain-version": (lambda label: "clang" + str(label.name)),
+    "ovr_config//build_mode:sanitizer_type": (lambda label: str(label.sub_target[0])),
+    "fbcode//fdo/constraints:fdo": (lambda label: str(label.name)),
+    "ovr_config//build_mode/default_opt_cxx:default_opt_cxx_setting": (lambda label: "opt-by-default" if str(label.sub_target[0]) == "enabled" else None),
+    "ovr_config//build_mode:arvr_mode": (lambda label: "arvr" if str(label.sub_target[0]) == "enabled" else None),
+}
+
+# A project's own constraint settings to name configurations by, after those
+# above, by the names of their values: `named_constraint_settings` in the
+# `cfg` section of its .buckconfig, a comma-separated list of (fully
+# qualified) labels.
+_PROJECT_NAMED_CONSTRAINT_SETTINGS = [
+    setting.strip()
+    for setting in (read_root_config("cfg", "named_constraint_settings") or "").split(",")
+    if setting.strip()
+]
+
+# Mark all modifier generated configurations with a `cfg:` prefix.
+# We do this so that we can easily recognize which configuration is generated
+# by modifiers and query for it in Scuba.
+_CFG_PREFIX = "cfg:"
+_EMPTY_CFG_NAME = _CFG_PREFIX + "<empty>"
+
+def cfg_name(cfg: ConfigurationInfo) -> str:
+    """Derives a reasonable name for a ConfigurationInfo"""
+
+    name_list = []
+    constraints = {str(key): value for key, value in cfg.constraints.items()}
+    for constraint_setting, transform in list(NAMED_CONSTRAINT_SETTINGS.items()) + [(s, None) for s in _PROJECT_NAMED_CONSTRAINT_SETTINGS]:
+        constraint_name = None
+        if constraint_setting in constraints:
+            constraint_value_label = constraints[constraint_setting].label
+            if transform:
+                constraint_name = transform(constraint_value_label)
+            else:
+                constraint_name = str(constraint_value_label.name)
+        if constraint_name:
+            name_list.append(constraint_name)
+
+    if len(name_list) == 0:
+        name = _EMPTY_CFG_NAME
+    else:
+        name = _CFG_PREFIX + "-".join(name_list)
+    return name
diff --git a/buck2/prelude/cfg/modifier/set_cfg_modifiers.bzl b/buck2/prelude/cfg/modifier/set_cfg_modifiers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/modifier/set_cfg_modifiers.bzl
@@ -0,0 +1,66 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":common.bzl", "get_tagged_modifiers", "tagged_modifiers_to_json")
+load(":types.bzl", "Modifier", "ModifierPackageLocation")  # @unused Used in type annotation
+
+def set_cfg_modifiers(cfg_modifiers: list[Modifier] | None = None, extra_cfg_modifiers_per_rule: dict[str, list[Modifier]] | None = None):
+    """
+    Sets a configuration modifier for all targets under this PACKAGE file. This can only be called from a PACKAGE file context
+    (e.g. a PACKAGE file or a bzl file transitively loaded by a PACKAGE file).
+
+    Args:
+        cfg_modifiers:
+            A list of modifiers to set. The simplest modifier is a constraint value target.
+            For example, to change the OS to linux in fbsource, this can be specified as `["ovr_config//os/constraints:linux"]`.
+        extra_cfg_modifiers_per_rule:
+            A dictionary of rule name to a list of modifiers to set. This is applied on top of modifiers from `cfg_modifiers` parameter
+            if a target's rule name matches the key, so it can override any modifier from `cfg_modifiers` parameter in the same PACKAGE.
+            For example, if this dictionary is `{"python_binary": ["ovr_config//os/constraints:macos"]}`,
+            then all python_binary targets covered will have the macos constraint added to their configurations.
+    """
+
+    # To ensure that modifiers set in PACKAGE files are easily codemoddable
+    # We want to enforce that `set_cfg_modifiers` is only invokable from a PACKAGE file and not a bzl file
+    frame1 = call_stack_frame(1)
+    if not _is_buck_tree_file(frame1.module_path):
+        # Now check the old bzl file for `set_cfg_modifiers` in case it is invoked through that one.
+        frame2 = call_stack_frame(2)
+        if not (frame2 and frame1.module_path.endswith("fbcode/buck2/cfg/experimental/set_cfg_modifiers.bzl") and _is_buck_tree_file(frame2.module_path)):
+            if not "third-party-buck" in frame2.module_path:
+                fail("set_cfg_modifiers is only allowed to be used from a PACKAGE or BUCK_TREE file, not a bzl file.")
+
+    cfg_modifiers = cfg_modifiers or []
+    extra_cfg_modifiers_per_rule = extra_cfg_modifiers_per_rule or {}
+
+    merged_modifier_jsons = get_parent_modifiers()
+
+    # `get_parent_modifiers` returns immutable values. `list()` makes it mutable.
+    merged_modifier_jsons = list(merged_modifier_jsons) if merged_modifier_jsons else []
+
+    tagged_modifiers_list = get_tagged_modifiers(
+        cfg_modifiers,
+        extra_cfg_modifiers_per_rule,
+        ModifierPackageLocation(package_path = _get_package_path()),
+    )
+    merged_modifier_jsons += [tagged_modifiers_to_json(tagged_modifiers) for tagged_modifiers in tagged_modifiers_list]
+
+    set_modifiers(
+        merged_modifier_jsons,
+    )
+
+def _get_package_path() -> str:
+    """
+    Returns the cell-relative path of the current PACKAGE file.
+    Ex. `foo//bar/PACKAGE`
+    """
+
+    return "{}//{}/PACKAGE".format(get_cell_name(), get_base_path())
+
+def _is_buck_tree_file(path: str) -> bool:
+    return path.endswith(("/PACKAGE", "/BUCK_TREE")) or path in ("PACKAGE", "BUCK_TREE")
diff --git a/buck2/prelude/cfg/modifier/types.bzl b/buck2/prelude/cfg/modifier/types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cfg/modifier/types.bzl
@@ -0,0 +1,81 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(scottcao): Annotate these types with comments once implementation is complete
+
+# Metadata types for where cfg modifier is defined. We need to track this to give users error messages
+# that include where the bad modifier comes from.
+
+# Modifier defined in a PACKAGE file. We track path of that PACKAGE file.
+ModifierPackageLocation = record(package_path = str)
+
+# Modifier defined on the target in buildfile.
+ModifierTargetLocation = record()
+
+# Modifier specified via command line from the user
+ModifierCliLocation = record()
+
+# Modifier specified from buckconfig
+ModifierBuckconfigLocation = record(
+    section = str,
+    property = str,
+)
+
+# This is a handy way of specifying a rust-style enum in Starlark.
+ModifierLocation = ModifierPackageLocation | ModifierTargetLocation | ModifierCliLocation | ModifierBuckconfigLocation
+
+# Modifier types as how they appear to the user via `set_cfg_modifier` or `cfg_modifier` function.
+
+ModifiersMatch = dict[str, typing.Any]
+
+Modifier = str | ModifiersMatch | None
+
+TaggedModifiers = record(
+    modifiers = list[Modifier],
+    location = ModifierLocation,
+    rule_name = str | None,
+)
+
+# Modifier types after analysis of configuration rules.
+# There is an equivalent post-constraint-analysis type for every modifier type listed above.
+# An "Info" is added to the type name to denote post-constraint-analysis version of the
+# modifier type.
+
+ModifiersMatchInfo = record(
+    # should be list[(ConfigurationInfo, "ModifierInfo")] once recursive types are supported
+    selector = list[(ConfigurationInfo, typing.Any)],
+    default = typing.Any,  # should be "ModifierInfo" | None with recursive types
+)
+
+ModifierInfo = ConstraintValueInfo | ModifiersMatchInfo | None
+
+# A provider for conditional modifier used by cfg constructor function when constructing the
+# configuration
+ConditionalModifierInfo = provider(
+    fields = {
+        "inner": ModifierInfo,
+        "key": TargetLabel,
+    }
+)
+
+BuckconfigBackedModifierInfo = provider(
+    fields = {
+        "post_platform_modifiers": list[ConditionalModifierInfo],
+        "pre_cli_modifiers": list[ConditionalModifierInfo],
+        "pre_platform_modifiers": list[ConditionalModifierInfo],
+    }
+)
+
+def is_modifiers_match(modifier: Modifier) -> bool:
+    if modifier == None or isinstance(modifier, str):
+        return False
+    if isinstance(modifier, dict):
+        if modifier["_type"] != "ModifiersMatch":
+            fail("Found unknown dictionary `{}` for modifier".format(modifier))
+        return True
+    fail("Modifier should either be None, a string, or dict. Found `{}`".format(modifier))
diff --git a/buck2/prelude/command_alias.bzl b/buck2/prelude/command_alias.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/command_alias.bzl
@@ -0,0 +1,262 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup", "ScriptLanguage")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused: Used as a type
+
+def command_alias_impl(ctx: AnalysisContext):
+    target_os = ctx.attrs._target_os_type[OsLookup]
+
+    if target_os.os == Os("fat_mac_linux") and len(ctx.attrs.platform_exe) > 0:
+        base = {
+            "Darwin": _get_os_base(ctx, Os("macos")),
+            "Linux": _get_os_base(ctx, Os("linux")),
+        }
+    else:
+        base = _get_os_base(ctx, target_os.os)
+
+    output = command_alias(
+        actions = ctx.actions,
+        path = ctx.attrs.executable_name,
+        target_os = target_os,
+        base = base,
+        args = cmd_args(ctx.attrs.args),
+        env = ctx.attrs.env,
+        labels = ctx.attrs.labels,
+    )
+
+    default_info = DefaultInfo(
+        default_output = output.output.default_outputs[0],
+        other_outputs = list(output.output.other_outputs) + ctx.attrs.resources,
+    )
+
+    # FIXME(JakobDegen): We should not accept `platform_exe` as meaning `run_using_single_arg`, but
+    # there are things that depend on that
+    #
+    # FIXME(JakobDegen): It's easy to end up depending on either one of these behaviors. Life would
+    # probably be easier if we just always went the `output.cmd` route
+    if (
+        output.maybe_directly_runnable == None
+        or ctx.attrs.run_using_single_arg
+        or ctx.attrs.executable_name != None
+        or (len(ctx.attrs.platform_exe) > 0 and target_os.script == ScriptLanguage("sh"))
+    ):
+        run_info = RunInfo(args = output.cmd)
+    else:
+        run_info = RunInfo(args = output.maybe_directly_runnable)
+
+    run_info_with_resources = RunInfo(
+        args = cmd_args(run_info, hidden = ctx.attrs.resources),
+    )
+
+    return [default_info, run_info_with_resources]
+
+def _get_os_base(ctx: AnalysisContext, os: Os) -> RunInfo:
+    exe = ctx.attrs.platform_exe.get(os.value)
+    if exe == None:
+        exe = ctx.attrs.exe
+
+    if exe == None:
+        return RunInfo()
+
+    if isinstance(exe, Artifact):
+        return RunInfo(args = cmd_args(exe))
+
+    run_info = exe.get(RunInfo)
+    if run_info == None:
+        run_info = RunInfo(
+            args = exe[DefaultInfo].default_outputs,
+        )
+
+    return run_info
+
+CommandAliasOutput = record(
+    # A batch or sh script representing the command alias
+    #
+    # `DefaultInfo` instead of `Artifact` because the `other_outputs` will usually need to be
+    # included as hidden somewhere
+    output = DefaultInfo,
+    # The output wrapped into a `cmd_args` in the obvious way
+    cmd = cmd_args,
+    # For some values of the arguments to `command_alias` it is possible to represent the
+    # command_alias entirely within a `cmd_args`, without needing to write out a script. If that is
+    # the case, those args are made available here.
+    maybe_directly_runnable = cmd_args | None,
+)
+
+def command_alias(
+    *,
+    actions: AnalysisActions,
+    # The path at which to write the output to, without an extension - that will be added
+    path: str | None,
+    # The target where this script should be able to run (this may actually be your exec platform)
+    target_os: OsLookup,
+    # Either the `RunInfo` to use, or in the case of a fat platform, the choice of `RunInfo`
+    # depending on `uname`
+    base: RunInfo | dict[str, RunInfo],
+    args: cmd_args,
+    env: dict[str, ArgLike],
+    labels: list[str],
+    has_content_based_path: bool = False,
+) -> CommandAliasOutput:
+    if path == "":
+        fail("Path cannot be empty string")
+
+    if path != None:
+        # Custom paths are usually provided for binaries that are searched for with a particular
+        # name. On Windows, the .bat extension is required, and well-behaved tools will respect the
+        # PATHEXT environment variable (which contains that extension). On Unix, no extension is
+        # expected for executables, and searches would likely fail if we added one.
+        unix_trampoline_path = path
+        windows_trampoline_path = path + ".bat"
+    else:
+        # Preserve the `.sh` extension in the default path, since many places have it hard-coded.
+        unix_trampoline_path = "__command_alias_trampoline.sh"
+        windows_trampoline_path = "__command_alias_trampoline.bat"
+
+    if target_os.script == ScriptLanguage("sh"):
+        trampoline, hidden = _command_alias_write_trampoline_unix(actions, unix_trampoline_path, base, args, env, has_content_based_path)
+    elif target_os.script == ScriptLanguage("bat"):
+        trampoline, hidden = _command_alias_write_trampoline_windows(actions, windows_trampoline_path, base, args, env, labels, has_content_based_path)
+    else:
+        fail("Unsupported script language: {}".format(target_os.script))
+
+    if len(env) > 0 or isinstance(base, dict):
+        maybe_directly_runnable = None
+    else:
+        maybe_directly_runnable = cmd_args(base.args, args)
+
+    return CommandAliasOutput(
+        output = DefaultInfo(
+            default_output = trampoline,
+            other_outputs = [hidden],
+        ),
+        cmd = cmd_args(trampoline, hidden = hidden),
+        maybe_directly_runnable = maybe_directly_runnable,
+    )
+
+def _command_alias_write_trampoline_unix(
+    actions: AnalysisActions, path: str, base: RunInfo | dict[str, RunInfo], args: cmd_args, env: dict[str, ArgLike], has_content_based_path: bool
+) -> (Artifact, cmd_args):
+    trampoline_args = cmd_args()
+    trampoline_args.add("#!/usr/bin/env bash")
+    trampoline_args.add("set -euo pipefail")
+
+    if isinstance(base, dict):
+        trampoline_args.add('case "$(uname)" in')
+        for uname, run_info in base.items():
+            trampoline_args.add("    {})".format(uname))
+            _add_args_declaration_to_trampoline_args(trampoline_args, run_info, args)
+            trampoline_args.add("        ;;")
+        trampoline_args.add("esac")
+    else:
+        _add_args_declaration_to_trampoline_args(trampoline_args, base, args)
+
+    # We can't use cwd relative paths (since we don't know the cwd when this script is run) and so
+    # we instead use paths relative to the script itself. However, we can't just naively stick a
+    # `$(...)` into `absolute_prefix`, since we must also shell quote paths, and that expression
+    # would be shell quoted.
+    #
+    # Instead, we use `BUCK_COMMAND_ALIAS_ABSOLUTE_PREFIX/`, verbatim, as an absolute prefix on the
+    # cmd_args, and then replace that with the actual path of the script at runtime
+    #
+    # Resolve symlinks first to handle execution via symlinks (e.g., in link-trees)
+    trampoline_args.add(
+        """
+SCRIPT_PATH="$0"
+if [ -L "$SCRIPT_PATH" ]; then
+    TARGET="$(readlink "$SCRIPT_PATH")"
+    SCRIPT_PATH="$(dirname "$SCRIPT_PATH")/$TARGET"
+fi
+""",
+    )
+
+    # Calculate the base path and process arguments with the resolved path.
+    trampoline_args.add(
+        """
+BASE=$(cd -- "$(dirname "$SCRIPT_PATH")" >/dev/null 2>&1 ; pwd -P)
+R_ARGS=()
+for arg in "${ARGS[@]}"; do
+    # Normalize Windows-style backslash path separators to forward slashes for
+    # artifact paths (identified by the prefix placeholder). This handles the case
+    # where Buck2 runs on Windows but this trampoline executes on Linux via RE.
+    if [[ "$arg" == *BUCK_COMMAND_ALIAS_ABSOLUTE_PREFIX* ]]; then arg="${arg//\\\\//}"; fi
+    R_ARGS+=("${arg//BUCK_COMMAND_ALIAS_ABSOLUTE_PREFIX/$BASE}")
+done
+""",
+    )
+
+    for k, v in env.items():
+        # TODO(akozhevnikov): maybe check environment variable is not conflicting with pre-existing one
+        trampoline_args.add(cmd_args("export ", k, "=", cmd_args(v, quote = "shell"), delimiter = ""))
+        trampoline_args.add(cmd_args("export ", k, '="${', k, '//BUCK_COMMAND_ALIAS_ABSOLUTE_PREFIX/$BASE}"', delimiter = ""))
+
+    trampoline_args.add('exec "${R_ARGS[@]}" "$@"')
+
+    trampoline = actions.declare_output(path, has_content_based_path = has_content_based_path)
+    trampoline_args = cmd_args(
+        trampoline_args,
+        relative_to = (trampoline, 1),
+        absolute_prefix = "BUCK_COMMAND_ALIAS_ABSOLUTE_PREFIX/",
+    )
+    actions.write(
+        trampoline.as_output(),
+        trampoline_args,
+        allow_args = True,
+        is_executable = True,
+        has_content_based_path = has_content_based_path,
+    )
+
+    return trampoline, trampoline_args
+
+def _command_alias_write_trampoline_windows(
+    actions: AnalysisActions, path: str, base: RunInfo, args: cmd_args, env: dict[str, ArgLike], labels: list[str], has_content_based_path: bool
+) -> (Artifact, cmd_args):
+    trampoline_args = cmd_args()
+    trampoline_args.add("@echo off")
+
+    if "close_stdin" in labels:
+        # Avoids waiting for input on the "Terminate batch job (Y/N)?" prompt.
+        # The prompt itself is unavoidable, but we can avoid having to wait for input.
+        # This will call the same trampoline batch file with stdin disabled
+        trampoline_args.add("if not defined STDIN_CLOSED (set STDIN_CLOSED=1 & CALL <NUL %0 %* & GOTO :EOF)")
+
+    # Set BUCK_COMMAND_ALIAS_ABSOLUTE to the drive and full path of the script being created here
+    # We use this below to prefix any artifacts being referenced in the script
+    trampoline_args.add("set BUCK_COMMAND_ALIAS_ABSOLUTE=%~dp0")
+
+    # Handle envs
+    for k, v in env.items():
+        # TODO(akozhevnikov): maybe check environment variable is not conflicting with pre-existing one
+        trampoline_args.add(cmd_args(["set ", k, "=", v], delimiter = ""))
+
+    # FIXME(JakobDegen): This should be batch quoting, not shell quoting
+    cmd = cmd_args(cmd_args(base.args, args, quote = "shell"), "%*", delimiter = " ")
+
+    trampoline_args.add(cmd)
+
+    trampoline = actions.declare_output(path, has_content_based_path = has_content_based_path)
+    trampoline_args = cmd_args(
+        trampoline_args,
+        relative_to = (trampoline, 1),
+        absolute_prefix = "%BUCK_COMMAND_ALIAS_ABSOLUTE%/",
+    )
+    actions.write(
+        trampoline.as_output(),
+        trampoline_args,
+        allow_args = True,
+        is_executable = True,
+        has_content_based_path = has_content_based_path,
+    )
+
+    return trampoline, trampoline_args
+
+def _add_args_declaration_to_trampoline_args(trampoline_args: cmd_args, base: RunInfo, args: cmd_args):
+    trampoline_args.add("ARGS=(")
+    trampoline_args.add(cmd_args(base.args, args, quote = "shell"))
+    trampoline_args.add(")")
diff --git a/buck2/prelude/configurations/constraint_alias.bzl b/buck2/prelude/configurations/constraint_alias.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/configurations/constraint_alias.bzl
@@ -0,0 +1,114 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:native.bzl", "native")
+
+"""
+Macros to help migrate from constraint_setting/constraint_value to the unified constraint() rule.
+
+Usage:
+
+    load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")
+
+    # Simple case: all values get aliases with the same name
+    constraint_with_aliases(
+        name = "os",
+        values = ["linux", "macos", "windows", "none"],
+        default = "none",
+        visibility = ["PUBLIC"],
+    )
+    # Creates:
+    #   - constraint(name = "os", values = [...], default = "none")
+    #   - configuration_alias(name = "linux", actual = ":os[linux]")
+    #   - configuration_alias(name = "macos", actual = ":os[macos]")
+    #   - etc.
+
+    # Custom aliases: map old target names to new subtarget values
+    constraint_with_aliases(
+        name = "cgo_enabled",
+        values = ["true", "false"],
+        default = "false",
+        aliases = {
+            "cgo_enabled_true": "true",
+            "cgo_enabled_false": "false",
+        },
+        visibility = ["PUBLIC"],
+    )
+    # Creates:
+    #   - constraint(name = "cgo_enabled", values = ["true", "false"], default = "false")
+    #   - configuration_alias(name = "cgo_enabled_true", actual = ":cgo_enabled[true]")
+    #   - configuration_alias(name = "cgo_enabled_false", actual = ":cgo_enabled[false]")
+"""
+
+def constraint_with_aliases(
+    name: str, values: list[str], default: str, visibility: list[str] = ["PUBLIC"], aliases: dict[str, str] | None = None, execution_modifier: bool = False
+):
+    """
+    Creates a unified constraint rule with backwards-compatible configuration aliases.
+
+    Args:
+        name: The name of the constraint setting
+        values: List of constraint values
+        default: The default value (must be in values)
+        visibility: Visibility for the constraint and aliases
+        aliases: Optional mapping of alias target names to value names.
+                 If None, creates aliases for all values using the value name as the alias name.
+                 Example: {"old_name": "new_value"} creates alias "old_name" pointing to ":name[new_value]"
+        execution_modifier: If True, enables exec modifier resolution for this constraint.
+    """
+    native.constraint(
+        name = name,
+        values = values,
+        default = default,
+        visibility = visibility,
+        execution_modifier = execution_modifier,
+    )
+
+    if aliases == None:
+        # Default: create aliases for all values with the same name
+        for value in values:
+            native.configuration_alias(
+                name = value,
+                actual = ":{}[{}]".format(name, value),
+                visibility = visibility,
+            )
+    else:
+        # Custom aliases: use the provided mapping
+        for alias_name, value in aliases.items():
+            native.configuration_alias(
+                name = alias_name,
+                actual = ":{}[{}]".format(name, value),
+                visibility = visibility,
+            )
+
+def generate_constraint_aliases(constraint_name: str, aliases: dict[str, str] | list[str], visibility: list[str] = ["PUBLIC"]):
+    """
+    Generates configuration aliases for an existing constraint.
+
+    Args:
+        constraint_name: The name of the constraint setting (without leading colon)
+        aliases: Either a list of value names (aliases will have the same name),
+                 or a dict mapping alias names to value names.
+        visibility: Visibility for the aliases
+    """
+    if type(aliases) == type([]):
+        # List of values: alias name equals value name
+        for value in aliases:
+            native.configuration_alias(
+                name = value,
+                actual = ":{}[{}]".format(constraint_name, value),
+                visibility = visibility,
+            )
+    else:
+        # Dict mapping alias names to values
+        for alias_name, value in aliases.items():
+            native.configuration_alias(
+                name = alias_name,
+                actual = ":{}[{}]".format(constraint_name, value),
+                visibility = visibility,
+            )
diff --git a/buck2/prelude/configurations/rules.bzl b/buck2/prelude/configurations/rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/configurations/rules.bzl
@@ -0,0 +1,211 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cfg/modifier:constraint_modifier_info.bzl", "make_constraint_modifier_info")
+load("@prelude//cfg/modifier:types.bzl", "ConditionalModifierInfo")
+load(":util.bzl", "util")
+
+_ExecutionModifierInfo = provider(
+    fields = {
+        "execution_modifier": bool,
+    }
+)
+
+def config_setting_impl(ctx):
+    subinfos = [util.constraint_values_to_configuration(ctx.attrs.constraint_values)]
+    subinfos.append(
+        util.configuration_info(
+            constraints = {},
+            values = ctx.attrs.values,
+            root_values = ctx.attrs.root_values,
+        )
+    )
+    cfg_info = util.configuration_info_union(subinfos)
+    providers = [DefaultInfo(), cfg_info]
+    if len(ctx.attrs.constraint_values) == 1:
+        # When only have one constraint, we return an additional ConditionalModifierInfo provider for
+        # conditional modifier
+        conditional_modifier_info = ctx.attrs.constraint_values[0][ConditionalModifierInfo]
+        providers.append(conditional_modifier_info)
+    return providers
+
+def constraint_setting_impl(ctx):
+    return [
+        DefaultInfo(),
+        ConstraintSettingInfo(label = ctx.label.raw_target()),
+        # In order for the constraint_value to access the execution modifier info, we need to provide an additional provider here.
+        _ExecutionModifierInfo(execution_modifier = ctx.attrs.execution_modifier),
+    ]
+
+def constraint_value_impl(ctx):
+    constraint_value = ConstraintValueInfo(
+        setting = ctx.attrs.constraint_setting[ConstraintSettingInfo],
+        label = ctx.label.raw_target(),
+    )
+    execution_modifier_info = ctx.attrs.constraint_setting[_ExecutionModifierInfo]
+
+    return [
+        DefaultInfo(),
+        constraint_value,
+        # Provide `ConfigurationInfo` from `constraint_value` so it could be used as select key.
+        ConfigurationInfo(
+            constraints = {
+                constraint_value.setting.label: constraint_value,
+            },
+            values = {},
+        ),
+        make_constraint_modifier_info(
+            constraint_value = constraint_value,
+            key = constraint_value.setting.label,
+            execution_modifier = execution_modifier_info.execution_modifier,
+            exec_platform_marker_configuration_info = ctx.attrs._exec_platform_marker[ConfigurationInfo],
+        ),
+    ]
+
+def constraint_impl(ctx):
+    # Validate values are unique and non-empty
+    values = ctx.attrs.values
+
+    min_values = 1 if ctx.attrs.allow_trivial_constraint else 2
+    if len(values) < min_values:
+        if ctx.attrs.allow_trivial_constraint:
+            fail("constraint() rule must have at least one value.")
+        else:
+            fail(
+                "constraint() rule must have at least two values. "
+                + "A single-value constraint has no selectivity: it can't express a choice between alternatives "
+                + "(e.g., 'linux' vs 'macos', 'enabled' vs 'disabled'), which is the whole point of a constraint. "
+                + "If you don't need to select between alternatives, you likely don't need a constraint at all.\n\n"
+                + "Set allow_trivial_constraint = True only if your constraint legitimately has just one value "
+                + "most of the time and may temporarily gain alternatives (e.g., versioned packages "
+                + "that pick up an extra value during an upgrade and drop it once the upgrade lands).",
+            )
+
+    default = ctx.attrs.default
+
+    # Value-name reservations:
+    # - 'DEFAULT' is always reserved, to avoid visual confusion with the special `[default]` subtarget.
+    # - 'default' is allowed only when it is itself the default value, in which case it coincides with the
+    #   `[default]` subtarget added below. Otherwise `[default]` would be ambiguous, so it is rejected.
+    seen = set()
+    for v in values:
+        if v == "DEFAULT":
+            fail("'DEFAULT' is a reserved keyword and cannot be used as a constraint value. Use a different name to avoid confusion.")
+        if v == "default" and default != "default":
+            fail(
+                "'default' can be used as a constraint value only when it is also the default value "
+                + "(i.e. default = \"default\"); otherwise ':{}[default]' is ambiguous between the value ".format(ctx.label.name)
+                + "named 'default' and the default value '{}'.".format(default),
+            )
+        if v in seen:
+            fail("Duplicate value '{}' in constraint()".format(v))
+        seen.add(v)
+
+    # Validate default is one of the declared values.
+    if default not in seen:
+        fail("default value '{}' must be one of the declared values: {}".format(default, values))
+
+    # Main target provides the constraint setting
+    main_label = ctx.label.raw_target()
+    constraint_setting = ConstraintSettingInfo(
+        label = main_label,
+        default = main_label.with_sub_target(default),
+    )
+
+    # exec_platform_marker_constraint() and constraint() rule both use this impl,
+    # but only constraint() has this attribute.
+    exec_platform_marker_configuration_info = None
+    if hasattr(ctx.attrs, "_exec_platform_marker"):
+        exec_platform_marker_configuration_info = ctx.attrs._exec_platform_marker[ConfigurationInfo]
+
+    execution_modifier = False
+    if hasattr(ctx.attrs, "execution_modifier"):
+        execution_modifier = ctx.attrs.execution_modifier
+
+    # Create subtargets for each value
+    sub_targets = {}
+    for value_name in values:
+        # Create a constraint value for this subtarget
+        constraint_value = ConstraintValueInfo(
+            setting = constraint_setting,
+            label = main_label.with_sub_target(value_name),
+        )
+
+        sub_targets[value_name] = [
+            DefaultInfo(),
+            constraint_value,
+            ConfigurationInfo(
+                constraints = {
+                    main_label: constraint_value,
+                },
+                values = {},
+            ),
+            make_constraint_modifier_info(
+                constraint_value = constraint_value,
+                key = main_label,
+                execution_modifier = execution_modifier,
+                exec_platform_marker_configuration_info = exec_platform_marker_configuration_info,
+            ),
+        ]
+
+    # Add 'default' subtarget that aliases to the actual default value
+    sub_targets["default"] = sub_targets[default]
+
+    # Validate and register user-defined aliases.
+    # Each alias becomes an additional subtarget pointing to an existing value's providers.
+    reserved_keywords = ["default", "DEFAULT"]
+    aliases = ctx.attrs.aliases
+    for alias_name, alias_value in aliases.items():
+        if alias_name in reserved_keywords:
+            fail("alias '{}' is a reserved keyword and cannot be used as a constraint alias.".format(alias_name))
+        if alias_name in seen:
+            fail("alias '{}' conflicts with a declared constraint value.".format(alias_name))
+        if alias_value not in seen:
+            fail("alias '{}' targets value '{}' which is not declared in values: {}".format(alias_name, alias_value, values))
+        sub_targets[alias_name] = sub_targets[alias_value]
+
+    return [
+        DefaultInfo(sub_targets = sub_targets),
+        constraint_setting,
+    ]
+
+def platform_impl(ctx):
+    subinfos = [dep[PlatformInfo].configuration for dep in ctx.attrs.deps] + [util.constraint_values_to_configuration(ctx.attrs.constraint_values)]
+    return [
+        DefaultInfo(),
+        PlatformInfo(
+            label = str(ctx.label.raw_target()),
+            # TODO(nga): current behavior is the last constraint value for constraint setting wins.
+            #   This allows overriding constraint values from dependencies, and moreover,
+            #   it allows overriding constraint values from constraint values listed
+            #   in the same `constraint_values` attribute earlier.
+            #   If this is intentional, state it explicitly.
+            #   Otherwise, fix it.
+            configuration = util.configuration_info_union(subinfos),
+        ),
+    ]
+
+def configuration_alias_impl(ctx: AnalysisContext) -> list[Provider]:
+    return ctx.attrs.actual.providers
+
+# TODO(cjhopman): Update the attributes for these ruletypes to declare the types of providers that they expect in their references.
+extra_attributes = {
+    "platform": {
+        "constraint_values": attrs.list(attrs.dep(providers = [ConstraintValueInfo]), default = []),
+    },
+}
+
+implemented_rules = {
+    "config_setting": config_setting_impl,
+    "configuration_alias": configuration_alias_impl,
+    "constraint": constraint_impl,
+    "constraint_setting": constraint_setting_impl,
+    "constraint_value": constraint_value_impl,
+    "exec_platform_marker_constraint": constraint_impl,
+    "platform": platform_impl,
+}
diff --git a/buck2/prelude/configurations/util.bzl b/buck2/prelude/configurations/util.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/configurations/util.bzl
@@ -0,0 +1,43 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _configuration_info(constraints, values, root_values = None):
+    return ConfigurationInfo(
+        constraints = constraints,
+        values = values,
+        root_values = root_values or {},
+    )
+
+def _configuration_info_union(infos):
+    if len(infos) == 0:
+        return _configuration_info(
+            constraints = {},
+            values = {},
+        )
+    if len(infos) == 1:
+        return infos[0]
+    constraints = {k: v for info in infos for (k, v) in info.constraints.items()}
+    values = {k: v for info in infos for (k, v) in info.values.items()}
+    root_values = {k: v for info in infos for (k, v) in info.root_values.items()}
+    return _configuration_info(
+        constraints = constraints,
+        values = values,
+        root_values = root_values,
+    )
+
+def _constraint_values_to_configuration(values):
+    return _configuration_info(
+        constraints = {info[ConstraintValueInfo].setting.label: info[ConstraintValueInfo] for info in values},
+        values = {},
+    )
+
+util = struct(
+    configuration_info = _configuration_info,
+    configuration_info_union = _configuration_info_union,
+    constraint_values_to_configuration = _constraint_values_to_configuration,
+)
diff --git a/buck2/prelude/content_based_dist.bzl b/buck2/prelude/content_based_dist.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/content_based_dist.bzl
@@ -0,0 +1,73 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def make_content_based_dist(ctx: AnalysisContext, name: str, exe: Artifact, copies: dict = {}, symlinks: dict = {}) -> (Artifact, Artifact):
+    """
+    Package a relocatable executable that depends on adjacent files into a single
+    content-based directory, so it is self-contained at a content-addressed
+    buck-out path. A content change re-hashes the whole directory to a new path
+    while the old one persists -- the property that lets a long-running `buck2
+    run` binary survive concurrent rebuilds.
+
+    `exe` is COPIED into the directory. Its self-relative lookups -- an `$ORIGIN`
+    RPATH, a `current_exe`-relative `.resources.json`, an inplace-PAR
+    `$(dirname $(readlink -f $0))`-relative `#link-tree`, etc. -- only resolve
+    inside the directory if the exe physically lives there; a symlinked exe would
+    resolve them against its realpath instead. Entries in `copies` are laid out
+    as real bytes (use for small generated files the bundle should own, e.g. a
+    relocatable resource DB); entries in `symlinks` are symlinks to their source
+    artifacts (use for large dependencies, to avoid duplicating bytes).
+
+    THE IMMUTABILITY CONTRACT IS PER-ENTRY: the bundle's content hash captures
+    copied entries' BYTES but only symlinked entries' TARGET PATHS. A COPIED
+    entry is therefore always trample-safe. A SYMLINKED entry is trample-safe
+    IFF its target artifact is itself content-based (immutable path); a
+    symlink to a config-based artifact keeps pointing at a path whose bytes a
+    rebuild rewrites in place -- without re-hashing this bundle. Callers must
+    route mutable inputs through `copies` (or make them content-based) when
+    they need whole-bundle immutability.
+
+    `copies` and `symlinks` are dicts of path-in-dir (string, relative to the
+    result directory) to a bound `artifact`.
+
+    Returns `(bundle_dir, exe)` where `exe` is the copied exe projected back out
+    of the bundle, for use as a `RunInfo` command and/or `DefaultInfo` output.
+    """
+    # Feature-detected (getattr, not a static reference) so this module still
+    # LOADS under a buck2 that predates `assembled_dir` (D107250277) -- the
+    # static type-checker rejects unknown globals/methods at module-load time,
+    # which would break every rust_binary analysis on older binaries. Reaching
+    # this function without the API (i.e. actually opting a target in) is a
+    # hard, explicit error instead.
+    entry_ctors = getattr(__buck2_builtins__, "assembled_dir", None)
+    make_assembled_dir = getattr(ctx.actions, "assembled_dir", None)
+    if entry_ctors == None or make_assembled_dir == None:
+        fail(
+            "content-based dist bundles require a buck2 with " + "`ctx.actions.assembled_dir` (D107250277); this buck2 predates it",
+        )
+
+    exe_rel = exe.short_path
+    contents = {exe_rel: entry_ctors.copy(exe)}
+
+    # Duplicate destinations would silently overwrite dict entries here --
+    # including the exe's own entry -- before `assembled_dir`'s non-overlap
+    # validation ever sees them. Reject them loudly instead.
+    for path, artifact in copies.items():
+        if path in contents:
+            fail("make_content_based_dist: duplicate bundle destination `{}` (copies)".format(path))
+        contents[path] = entry_ctors.copy(artifact)
+    for path, artifact in symlinks.items():
+        if path in contents:
+            fail("make_content_based_dist: duplicate bundle destination `{}` (symlinks)".format(path))
+        contents[path] = entry_ctors.symlink(artifact)
+    bundle = make_assembled_dir(
+        name + "__dist",
+        contents = contents,
+        has_content_based_path = True,
+    )
+    return (bundle, bundle.project(exe_rel))
diff --git a/buck2/prelude/cpu/BUCK b/buck2/prelude/cpu/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cpu/BUCK
@@ -0,0 +1,53 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+config_setting(
+    name = "x86_64",
+    constraint_values = [
+        "prelude//cpu/constraints:cpu[x86_64]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "x86_32",
+    constraint_values = [
+        "prelude//cpu/constraints:cpu[x86_32]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "arm64",
+    constraint_values = [
+        "prelude//cpu/constraints:cpu[arm64]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "arm32",
+    constraint_values = [
+        "prelude//cpu/constraints:cpu[arm32]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "wasm32",
+    constraint_values = [
+        "prelude//cpu/constraints:cpu[wasm32]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "riscv64",
+    constraint_values = [
+        "prelude//cpu/constraints:cpu[riscv64]",
+    ],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/cpu/constraints/BUCK b/buck2/prelude/cpu/constraints/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cpu/constraints/BUCK
@@ -0,0 +1,30 @@
+load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+# Used by open source projects to support `prelude//`
+
+constraint_with_aliases(
+    name = "cpu",
+    aliases = {
+        "arm32": "arm32",
+        "arm64": "arm64",
+        "x86_32": "x86_32",
+        "x86_64": "x86_64",
+    },
+    default = "unspecified",
+    values = [
+        "x86_64",
+        "x86_32",
+        "arm64",
+        "arm64_32",
+        "arm32",
+        "wasm32",
+        "riscv64",
+        "unspecified",
+    ],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/csharp/csharp.bzl b/buck2/prelude/csharp/csharp.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/csharp/csharp.bzl
@@ -0,0 +1,85 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":csharp_providers.bzl", "DllDepTSet", "DllReference", "DotNetLibraryInfo", "generate_target_tset_children")
+load(":toolchain.bzl", "CSharpToolchainInfo")
+
+def csharp_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    toolchain = ctx.attrs._csharp_toolchain[CSharpToolchainInfo]
+
+    # Automatically set the output dll_name to this target's name if the caller did not specify a
+    # custom name.
+    dll_name = "{}.dll".format(ctx.attrs.name) if not ctx.attrs.dll_name else ctx.attrs.dll_name
+
+    # Declare that this rule will produce a dll.
+    library = ctx.actions.declare_output(dll_name, has_content_based_path = False)
+
+    # Create a command invoking a wrapper script that calls csc.exe to compile the .dll.
+    cmd = [toolchain.csc]
+
+    # Add caller specified compiler flags.
+    cmd.append(ctx.attrs.compiler_flags)
+
+    # Set the output target as a .NET library.
+    cmd.append("/target:library")
+    cmd.append(
+        cmd_args(
+            library.as_output(),
+            format = "/out:{}",
+        )
+    )
+
+    # Don't include any default .NET framework assemblies like "mscorlib" or "System" unless
+    # explicitly requested with `/reference:{}`. This flag also stops injection of other
+    # default compiler flags.
+    cmd.append("/noconfig")
+
+    # Don't reference mscorlib.dll unless asked for. This is required for targets that target
+    # embedded platforms such as Silverlight or WASM. (Originally for Buck1 compatibility.)
+    cmd.append("/nostdlib")
+
+    # Don't search any paths for .NET libraries unless explicitly referenced with `/lib:{}`.
+    cmd.append("/nosdkpath")
+
+    # Let csc know the directory path where it can find system assemblies. This is the path
+    # that is searched by `/reference:{libname}` if `libname` is just a DLL name.
+    cmd.append(cmd_args(toolchain.framework_dirs[ctx.attrs.framework_ver], format = "/lib:{}"))
+
+    # Add a `/reference:{name}` argument for each dependency.
+    # Buck target refs should be absolute paths and system assemblies just the DLL name.
+    child_deps = generate_target_tset_children(ctx.attrs.deps, ctx)
+    deps_tset = ctx.actions.tset(DllDepTSet, children = child_deps)
+
+    cmd.append(deps_tset.project_as_args("reference"))
+
+    # Specify the C# source code files that should be compiled into this target.
+    # NOTE: This must happen after /out and /target!
+    cmd.append(ctx.attrs.srcs)
+
+    # Run the C# compiler to produce the output artifact.
+    ctx.actions.run(cmd, category = "csharp_compile")
+
+    return [
+        DefaultInfo(default_output = library),
+        DotNetLibraryInfo(
+            name = ctx.attrs.dll_name,
+            object = library,
+            dll_deps = ctx.actions.tset(DllDepTSet, value = DllReference(reference = library), children = child_deps),
+        ),
+    ]
+
+def prebuilt_dotnet_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    # Prebuilt libraries are just passed through since they are already built.
+    return [
+        DefaultInfo(default_output = ctx.attrs.assembly),
+        DotNetLibraryInfo(
+            name = ctx.attrs.name,
+            object = ctx.attrs.assembly,
+            dll_deps = ctx.actions.tset(DllDepTSet, value = DllReference(reference = ctx.attrs.assembly)),
+        ),
+    ]
diff --git a/buck2/prelude/csharp/csharp_providers.bzl b/buck2/prelude/csharp/csharp_providers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/csharp/csharp_providers.bzl
@@ -0,0 +1,63 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Stores a reference to a Buck .NET DLL target (`Artifact`) or the name of an assembly dll (`str`)
+# that can be found in the .NET framework SDK directory
+DllReference = record(
+    # `str` -> Path to a .NET framework DLL on the local machine.
+    # `Artifact` -> Buck target dependency.
+    reference = field([Artifact, str]),
+)
+
+def _args_for_dll_reference(dllref: DllReference) -> cmd_args:
+    """Projects values in a `DllDepTSet` to csc.exe /reference:{dllname} arguments."""
+    return cmd_args(dllref.reference, format = "/reference:{}")
+
+# A transitive set of DLL references required to build a .NET library.
+#
+# The transitive set attribute `value` references the outputting assembly, and the children are a
+# list of the dependencies required to build it.
+DllDepTSet = transitive_set(
+    args_projections = {
+        # Projects "/reference:{}" arguments for `csc.exe`.
+        "reference": _args_for_dll_reference,
+    },
+)
+
+def generate_target_tset_children(deps: list[typing.Any], ctx: AnalysisContext) -> list[DllDepTSet]:
+    """Convert a C# target's dependencies list into an array of transitive dependencies."""
+
+    tset_children = []
+
+    if deps:
+        for dep in deps:
+            if isinstance(dep, str):
+                # Name of a .NET framework DLL (eg "System.Drawing.dll").
+                tset_children.append(
+                    ctx.actions.tset(DllDepTSet, value = DllReference(reference = dep)),
+                )
+            else:
+                # Buck target dependency (eg "//buck/path/to:foobar").
+                # Adds all of the dependencies of the Buck target dependency to the tset.
+                tset_children.append(dep.get(DotNetLibraryInfo).dll_deps)
+
+    return tset_children
+
+DotNetLibraryInfo = provider(
+    doc = "Information about a .NET library and its dependencies",
+    fields = {
+        # A tset of DLLs (System or Buck targets) this library depends on. The
+        # `.value` is a reference to the outputting assembly artifact, and the
+        # children are the dependencies required to build it.
+        "dll_deps": provider_field(DllDepTSet),
+        # The output file name of the library.
+        "name": provider_field(str),
+        # The generated .dll artifact that will need to be linked into an .exe.
+        "object": provider_field(Artifact),
+    },
+)
diff --git a/buck2/prelude/csharp/toolchain.bzl b/buck2/prelude/csharp/toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/csharp/toolchain.bzl
@@ -0,0 +1,14 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+CSharpToolchainInfo = provider(
+    fields = [
+        "csc",
+        "framework_dirs",
+    ]
+)
diff --git a/buck2/prelude/cxx/anon_link.bzl b/buck2/prelude/cxx/anon_link.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/anon_link.bzl
@@ -0,0 +1,282 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactInfo",
+    "make_artifact_tset",
+)
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",
+    "LinkerType",
+)
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference")
+load(
+    "@prelude//linking:link_info.bzl",
+    "Archive",
+    "ArchiveContentsType",
+    "ArchiveLinkable",
+    "DepMetadata",
+    "LinkArgs",
+    "LinkInfo",  # @unused Used as a type
+    "ObjectsLinkable",
+    "SharedLibLinkable",
+)
+load(
+    ":link_types.bzl",
+    "CxxLinkResultType",
+    "LinkOptions",
+    "link_options",
+)
+
+# The link recipe is encoded as one JSON string of pure scalars/counts plus two
+# flat streams (flags and artifacts) that both sides walk in the same traversal
+# order. Encoding each linkable as nested attr tuples instead costs the daemon
+# ~1KiB of coerced-attr nodes per linkable, which dominates buck2 memory on
+# large link-group graphs (measured ~1GiB retained on a 14-target fbcode dev
+# cohort); the artifacts must remain real `attrs.source()` values for input
+# tracking, but everything else can live in the string.
+#
+# The anon target identity therefore hashes (recipe, flags, artifacts), which
+# discriminates exactly like the nested encoding, except that external debug
+# info labels are no longer part of the identity: deserialization always
+# discarded them, so they only served to split otherwise-identical identities.
+
+_LINK_ARGS_FLAGS_TAG = 0
+_LINK_ARGS_INFOS_TAG = 1
+
+_LINKABLE_ARCHIVE_TAG = 0
+_LINKABLE_OBJECTS_TAG = 1
+_LINKABLE_SHARED_TAG = 2
+
+def _encode_linkable(linkable, artifacts: list[Artifact]):
+    if isinstance(linkable, ArchiveLinkable):
+        artifacts.append(linkable.archive.artifact)
+        artifacts.extend(linkable.archive.external_objects)
+        return [
+            _LINKABLE_ARCHIVE_TAG,
+            len(linkable.archive.external_objects),
+            linkable.archive.archive_contents_type.value,
+            linkable.link_whole,
+            linkable.linker_type.value,
+            linkable.supports_lto,
+        ]
+
+    if isinstance(linkable, ObjectsLinkable):
+        artifacts.extend(linkable.objects)
+        return [
+            _LINKABLE_OBJECTS_TAG,
+            len(linkable.objects),
+            linkable.link_whole,
+            linkable.linker_type.value,
+        ]
+
+    if isinstance(linkable, SharedLibLinkable):
+        artifacts.append(linkable.lib)
+        return [
+            _LINKABLE_SHARED_TAG,
+            linkable.link_without_soname,
+        ]
+
+    fail('cannot serialize linkable "{}"'.format(str(linkable)))
+
+def _encode_link_info(info: LinkInfo, flags: list, artifacts: list[Artifact]):
+    external_debug_artifacts = []
+    if info.external_debug_info._tset != None:
+        external_debug_infos = []
+        for tset_infos in info.external_debug_info._tset.traverse():
+            external_debug_infos.extend(tset_infos)
+        for artifact_info in dedupe(external_debug_infos):
+            external_debug_artifacts.extend(artifact_info.artifacts)
+
+    flags.extend(info.pre_flags)
+    flags.extend(info.post_flags)
+    linkables = [_encode_linkable(linkable, artifacts) for linkable in info.linkables]
+    artifacts.extend(external_debug_artifacts)
+
+    return [
+        len(info.pre_flags),
+        len(info.post_flags),
+        linkables,
+        len(external_debug_artifacts),
+        [m.version for m in info.metadata],
+    ]
+
+def _anon_link_flags(values: list) -> list:
+    result = []
+    for value in values:
+        if isinstance(value, TransitiveSetArgsProjection) and value.projection_name == "linker_flags":
+            # Anonymous attrs accept resolved macros, but not transitive-set projections.
+            for shared_flags in value.transitive_set.traverse(ordering = "postorder"):
+                result.extend(shared_flags.linker_flags)
+        else:
+            result.append(value)
+    return result
+
+def serialize_anon_attrs(output: str, result_type: CxxLinkResultType, opts: LinkOptions) -> dict[str, typing.Any]:
+    # Anonymous links cannot run distributed ThinLTO (its dynamic outputs are
+    # unsupported in anon targets; every anonymous caller disables it), and the
+    # encoding relies on that: `LinkInfo.name` is not serialized, and dist
+    # ThinLTO planning is the one consumer that reads it.
+    if opts.enable_distributed_thinlto:
+        fail("anonymous links do not support distributed ThinLTO")
+
+    recipe = []
+    flags = []
+    artifacts = []
+    for link in opts.links:
+        if link.flags != None:
+            link_flags = _anon_link_flags(link.flags)
+            recipe.append([_LINK_ARGS_FLAGS_TAG, len(link_flags)])
+            flags.extend(link_flags)
+        elif link.infos != None:
+            recipe.append([_LINK_ARGS_INFOS_TAG, [_encode_link_info(info, flags, artifacts) for info in link.infos]])
+        else:
+            fail("cannot serialize link args")
+
+    return dict(
+        links_recipe = json.encode(recipe),
+        links_flags = flags,
+        links_artifacts = artifacts,
+        output = output,
+        import_library = opts.import_library,
+        link_execution_preference = opts.link_execution_preference.value,
+        dwp_execution_preference = opts.dwp_execution_preference.value if opts.dwp_execution_preference != None else None,
+        enable_distributed_thinlto = opts.enable_distributed_thinlto,
+        identifier = opts.identifier,
+        category_suffix = opts.category_suffix,
+        result_type = result_type.value,
+        allow_cache_upload = opts.allow_cache_upload,
+    )
+
+def _decode_linkable(spec, artifacts, artifact_cursor: list[int]) -> typing.Any:
+    kind = spec[0]
+
+    if kind == _LINKABLE_ARCHIVE_TAG:
+        _, num_external_objects, archive_contents_type, link_whole, linker_type, supports_lto = spec
+        archive_artifact = artifacts[artifact_cursor[0]]
+        external_objects = artifacts[artifact_cursor[0] + 1 : artifact_cursor[0] + 1 + num_external_objects]
+        artifact_cursor[0] += 1 + num_external_objects
+        return ArchiveLinkable(
+            archive = Archive(
+                artifact = archive_artifact,
+                external_objects = external_objects,
+                archive_contents_type = ArchiveContentsType(archive_contents_type),
+            ),
+            link_whole = link_whole,
+            linker_type = LinkerType(linker_type),
+            supports_lto = supports_lto,
+        )
+
+    if kind == _LINKABLE_OBJECTS_TAG:
+        _, num_objects, link_whole, linker_type = spec
+        objects = artifacts[artifact_cursor[0] : artifact_cursor[0] + num_objects]
+        artifact_cursor[0] += num_objects
+        return ObjectsLinkable(
+            objects = objects,
+            link_whole = link_whole,
+            linker_type = LinkerType(linker_type),
+        )
+
+    if kind == _LINKABLE_SHARED_TAG:
+        _, link_without_soname = spec
+        lib = artifacts[artifact_cursor[0]]
+        artifact_cursor[0] += 1
+        return SharedLibLinkable(
+            lib = lib,
+            link_without_soname = link_without_soname,
+        )
+
+    fail("Invalid linkable kind: {}".format(kind))
+
+def _decode_link_info(actions: AnalysisActions, label: Label, spec, flags, flag_cursor: list[int], artifacts, artifact_cursor: list[int]) -> LinkInfo:
+    num_pre_flags, num_post_flags, linkable_specs, num_external_debug_artifacts, metadata = spec
+
+    pre_flags = flags[flag_cursor[0] : flag_cursor[0] + num_pre_flags]
+    post_flags = flags[flag_cursor[0] + num_pre_flags : flag_cursor[0] + num_pre_flags + num_post_flags]
+    flag_cursor[0] += num_pre_flags + num_post_flags
+
+    linkables = [_decode_linkable(linkable_spec, artifacts, artifact_cursor) for linkable_spec in linkable_specs]
+
+    external_debug_artifacts = artifacts[artifact_cursor[0] : artifact_cursor[0] + num_external_debug_artifacts]
+    artifact_cursor[0] += num_external_debug_artifacts
+
+    return LinkInfo(
+        name = None,
+        pre_flags = pre_flags,
+        post_flags = post_flags,
+        linkables = linkables,
+        external_debug_info = make_artifact_tset(
+            actions = actions,
+            infos = [ArtifactInfo(label = label, artifacts = external_debug_artifacts, tags = [])] if external_debug_artifacts else [],
+        ),
+        metadata = [DepMetadata(version = v) for v in metadata],
+    )
+
+def deserialize_anon_attrs(actions: AnalysisActions, label: Label, attrs: struct) -> (str, CxxLinkResultType, LinkOptions):
+    flag_cursor = [0]
+    artifact_cursor = [0]
+    links = []
+    for entry in json.decode(attrs.links_recipe):
+        if entry[0] == _LINK_ARGS_FLAGS_TAG:
+            num_flags = entry[1]
+            links.append(LinkArgs(flags = attrs.links_flags[flag_cursor[0] : flag_cursor[0] + num_flags]))
+            flag_cursor[0] += num_flags
+        elif entry[0] == _LINK_ARGS_INFOS_TAG:
+            links.append(
+                LinkArgs(
+                    infos = [_decode_link_info(actions, label, spec, attrs.links_flags, flag_cursor, attrs.links_artifacts, artifact_cursor) for spec in entry[1]]
+                )
+            )
+        else:
+            fail("Invalid link args kind: {}".format(entry[0]))
+
+    if flag_cursor[0] != len(attrs.links_flags) or artifact_cursor[0] != len(attrs.links_artifacts):
+        fail(
+            "anon link recipe did not consume its flag/artifact streams exactly (flags {}/{}, artifacts {}/{})".format(
+                flag_cursor[0],
+                len(attrs.links_flags),
+                artifact_cursor[0],
+                len(attrs.links_artifacts),
+            )
+        )
+
+    opts = link_options(
+        links = links,
+        import_library = attrs.import_library,
+        link_execution_preference = LinkExecutionPreference(attrs.link_execution_preference),
+        dwp_execution_preference = LinkExecutionPreference(attrs.dwp_execution_preference) if attrs.dwp_execution_preference != None else None,
+        category_suffix = attrs.category_suffix,
+        identifier = attrs.identifier,
+        enable_distributed_thinlto = attrs.enable_distributed_thinlto,
+        allow_cache_upload = attrs.allow_cache_upload,
+    )
+
+    result_type = CxxLinkResultType(attrs.result_type)
+
+    return (attrs.output, result_type, opts)
+
+# The attributes -- and their serialized types -- that can be passed to an
+# anonymous link. See the module docblock for the stream encoding contract.
+ANON_ATTRS = {
+    "allow_cache_upload": attrs.bool(),
+    "category_suffix": attrs.string(),
+    "dwp_execution_preference": attrs.option(attrs.enum(LinkExecutionPreference.values()), default = None),
+    "enable_distributed_thinlto": attrs.bool(),
+    "identifier": attrs.option(attrs.string(), default = None),
+    "import_library": attrs.option(attrs.source(), default = None),
+    "link_execution_preference": attrs.enum(LinkExecutionPreference.values()),
+    "links_artifacts": attrs.list(attrs.source(), default = []),
+    "links_flags": attrs.list(attrs.arg(), default = []),
+    "links_recipe": attrs.string(default = "[]"),
+    "output": attrs.string(),
+    "result_type": attrs.enum(CxxLinkResultType.values()),
+    "separate_debug_info": attrs.bool(default = False),
+    "_cxx_toolchain": attrs.dep(providers = [CxxToolchainInfo]),
+}
diff --git a/buck2/prelude/cxx/archive.bzl b/buck2/prelude/cxx/archive.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/archive.bzl
@@ -0,0 +1,155 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerInfo", "LinkerType")
+load("@prelude//linking:link_info.bzl", "Archive", "ArchiveContentsType")
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load("@prelude//utils:utils.bzl", "value_or")
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+
+def archive_flags(archiver_type: str, linker_type: LinkerType, use_archiver_flags: bool, symbol_table: bool, thin: bool) -> list[str]:
+    if not use_archiver_flags:
+        return []
+
+    if archiver_type == "windows":
+        if thin:
+            fail("'windows' archiver doesn't support thin archives")
+        return ["/Brepro", "/d2threads1"]
+    elif archiver_type == "windows_clang":
+        return ["/llvmlibthin"] if thin else []
+    elif archiver_type == "amdclang":
+        # amdclang can be used to create archives with --emit-static-lib, so let's
+        # prefer to let the toolchain define the args instead of hardcoding them here.
+        return []
+    flags = ""
+
+    # Operate in quick append mode, so that objects with identical basenames
+    # won't overwrite one another.
+    flags += "q"
+
+    # Suppress warning about creating a new archive.
+    flags += "c"
+
+    # Run ranlib to generate symbol index for faster linking if requested.
+    flags += "s" if symbol_table else "S"
+
+    # Generate thin archives.
+    if thin:
+        flags += "T"
+
+    # GNU archivers support generating deterministic archives.
+    if linker_type == LinkerType("gnu"):
+        flags += "D"
+
+    return [flags]
+
+_ARCHIVE_ENV = {"ZERO_AR_DATE": "1"}
+
+# Create a static library from a list of object files.
+def _archive(
+    ctx: AnalysisContext, name: str, args: cmd_args, thin: bool, prefer_local: bool, allow_cache_upload: bool, force_disable_content_based_path: bool = False
+) -> Artifact:
+    toolchain = get_cxx_toolchain_info(ctx)
+    has_content_based_path = (toolchain.linker_info.supports_content_based_paths_for_archiving == True) and not force_disable_content_based_path
+    archive_output = ctx.actions.declare_output(name, has_content_based_path = has_content_based_path)
+    command = cmd_args(toolchain.linker_info.archiver)
+    archiver_type = toolchain.linker_info.archiver_type
+    command.add(
+        archive_flags(
+            archiver_type,
+            toolchain.linker_info.type,
+            toolchain.linker_info.use_archiver_flags,
+            toolchain.linker_info.archive_symbol_table,
+            thin,
+        )
+    )
+    if archiver_type == "windows" or archiver_type == "windows_clang":
+        command.add([cmd_args(archive_output.as_output(), format = "/OUT:{}")])
+    elif archiver_type == "amdclang":
+        command.add(["-o", archive_output.as_output()])
+    else:
+        command.add([archive_output.as_output()])
+
+    if toolchain.linker_info.archiver_supports_argfiles:
+        shell_quoted_args = cmd_args(args, quote = "shell")
+        if toolchain.linker_info.use_archiver_flags and toolchain.linker_info.archiver_flags != None:
+            shell_quoted_args.add(toolchain.linker_info.archiver_flags)
+
+        command.add(
+            at_argfile(
+                actions = ctx.actions,
+                name = name + ".cxx_archive_argsfile",
+                args = shell_quoted_args,
+                allow_args = True,
+                has_content_based_path = has_content_based_path,
+            )
+        )
+    else:
+        command.add(args)
+
+    # By default, the archive header produced by `ar q` embeds the current unix
+    # timestamp. With the GNU archiver we use `ar qD` (above in _archive_flags)
+    # to make it produce a deterministic archive by zeroing the timestamp, but
+    # other archivers do not support such a flag. Some implementations, notably
+    # Xcode's, instead support zeroing the timestamp by way of an environment
+    # variable.
+    env = _ARCHIVE_ENV
+
+    category = "archive"
+    if thin:
+        category = "archive_thin"
+    ctx.actions.run(
+        command,
+        category = category,
+        identifier = name,
+        env = env,
+        prefer_local = prefer_local,
+        allow_cache_upload = allow_cache_upload,
+    )
+    return archive_output
+
+def _archive_locally(ctx: AnalysisContext, linker_info: LinkerInfo) -> bool:
+    archive_locally = linker_info.archive_objects_locally
+    if hasattr(ctx.attrs, "_archive_objects_locally_override"):
+        return value_or(ctx.attrs._archive_objects_locally_override, archive_locally)
+    return archive_locally
+
+def _archive_allow_cache_upload(ctx: AnalysisContext) -> bool:
+    return getattr(ctx.attrs, "archive_allow_cache_upload", False)
+
+# Creates a static library given a list of object files.
+def make_archive(
+    ctx: AnalysisContext, name: str, objects: list[Artifact], hidden: list[Artifact] = [], force_disable_content_based_path: bool = False
+) -> Archive:
+    if len(objects) == 0:
+        fail("no objects to archive")
+
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    thin = linker_info.archive_contents == "thin"
+    object_args = cmd_args(objects)
+    args = cmd_args(object_args, hidden = hidden)
+    archive = _archive(
+        ctx,
+        name,
+        args,
+        thin = thin,
+        prefer_local = _archive_locally(ctx, linker_info),
+        allow_cache_upload = _archive_allow_cache_upload(ctx),
+        force_disable_content_based_path = force_disable_content_based_path,
+    )
+
+    # TODO(T110378125): use argsfiles for GNU archiver for long lists of objects.
+    # TODO(T110378123): for BSD archiver, split long args over multiple invocations.
+    # TODO(T110378100): We need to scrub the static library (timestamps, permissions, etc) as those are
+    # sources of non-determinism. See `ObjectFileScrubbers.createDateUidGidScrubber()` in Buck v1.
+
+    return Archive(
+        artifact = archive,
+        archive_contents_type = ArchiveContentsType(linker_info.archive_contents),
+        external_objects = objects,
+    )
diff --git a/buck2/prelude/cxx/argsfiles.bzl b/buck2/prelude/cxx/argsfiles.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/argsfiles.bzl
@@ -0,0 +1,50 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+ARGSFILES_SUBTARGET = "argsfiles"
+
+# Information on argsfiles created for compilation.
+CompileArgsfile = record(
+    # The generated argsfile (does not contain dependent inputs).
+    file = field(Artifact),
+    # This argsfile as a command form that would use the argsfile (includes dependent inputs).
+    cmd_form = field(cmd_args),
+    # Command form for the NVCC dry run: the argsfile, the argsfiles it
+    # references and the header maps the flags name, but not the header trees
+    # or other artifacts behind the flags. Only built for CUDA sources.
+    cmd_form_cuda_dryrun = field(cmd_args | None, None),
+    # Args as written to the argsfile (with shell quoting applied).
+    args = field(cmd_args),
+    # Args aggregated for the argsfile excluding file prefix args (excludes shell quoting).
+    args_without_file_prefix_args = field(cmd_args),
+    # The generated GCC specs file carrying the file-prefix-map flags, when the
+    # compiler takes them that way. None for compilers given the flags directly.
+    file_prefix_specs = field(Artifact | None, None),
+)
+
+CompileArgsfiles = record(
+    # Relative path argsfiles used for build actions, mapped by extension.
+    relative = field(dict[str, CompileArgsfile], default = {}),
+    # Argsfiles used for Xcode integration, mapped by extension.
+    xcode = field(dict[str, CompileArgsfile], default = {}),
+)
+
+def get_argsfiles_output(ctx: AnalysisContext, argsfile_by_ext: dict[str, CompileArgsfile], summary_name: str) -> DefaultInfo:
+    argsfiles = []
+    dependent_outputs = []
+    for _, argsfile in argsfile_by_ext.items():
+        argsfiles.append(argsfile.file)
+
+        # To materialize the dependent `Artifact`s of `CompileArgsfile#file`,
+        # `CompileArgsfile#cmd_form` is returned in `DefaultInfo#other_outputs`,
+        # because it tracks the dependents through the `cmd_args` API.
+        dependent_outputs.append(argsfile.cmd_form)
+
+    argsfiles_summary = ctx.actions.write(summary_name, argsfiles, has_content_based_path = False)
+
+    return DefaultInfo(default_outputs = [argsfiles_summary], other_outputs = argsfiles + dependent_outputs)
diff --git a/buck2/prelude/cxx/attr_selection.bzl b/buck2/prelude/cxx/attr_selection.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/attr_selection.bzl
@@ -0,0 +1,66 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def cxx_by_language_ext(x: dict[typing.Any, typing.Any], ext: str) -> list[typing.Any]:
+    # lang_preprocessor_flags is indexed by c/cxx
+    # lang_compiler_flags is indexed by c_cpp_output/cxx_cpp_output
+    # so write a function that can do either
+    #
+    # === Buck v1 Compatibility ===
+    #
+    # `lang_compiler_flags` keys are coerced to CxxSource,
+    # so the allowable values are the lowercase versions of the enum values.
+    #
+    # The keys themselves should be the _output_ type of the language. For example,
+    # for Obj-C, that would be OBJC_CPP_OUTPUT.
+    #
+    # The actual lookup for `lang_compiler_flags` happens in
+    # CxxSourceRuleFactory::getRuleCompileFlags().
+    #
+    # `lang_preprocessor_flags` keys are also coerced to CxxSource.
+    # The keys are the _input_ type of the language. For example, for Obj-C,
+    # that would be OBJC.
+    if ext == ".c":
+        key_pp = "c"
+
+        # TODO(gabrielrc): v1 docs have other keys
+        # https://buck.build/rule/cxx_library.html#lang_compiler_flags
+        # And you can see them in java code, but somehow it works with
+        # this one, which is seem across the repo. Find out what's happening.
+        key_compiler = "c_cpp_output"
+    elif ext in (".cpp", ".cc", ".cl", ".cxx", ".c++", ".bc"):
+        key_pp = "cxx"
+        key_compiler = "cxx_cpp_output"
+    elif ext == ".m":
+        key_pp = "objc"
+        key_compiler = "objc_cpp_output"
+    elif ext == ".mm":
+        key_pp = "objcxx"
+        key_compiler = "objcxx_cpp_output"
+    elif ext in (".s", ".sx", ".S"):
+        key_pp = "assembler_with_cpp"
+        key_compiler = "assembler"
+    elif ext == ".cu":
+        key_pp = "cuda"
+        key_compiler = "cuda_cpp_output"
+    elif ext == ".hip":
+        key_pp = "hip"
+        key_compiler = "hip_cpp_output"
+    elif ext in (".asm", ".asmpp"):
+        key_pp = "asm_with_cpp"
+        key_compiler = "asm"
+    elif ext in (".h", ".hpp", ".hh", ".hxx", ".h++"):
+        fail("Not allowed to have header files in the `srcs` attribute - put them in `headers`")
+    else:
+        fail("Unexpected file extension: " + ext)
+    res = []
+    if key_pp in x:
+        res += x[key_pp]
+    if key_compiler in x:
+        res += x[key_compiler]
+    return res
diff --git a/buck2/prelude/cxx/bitcode.bzl b/buck2/prelude/cxx/bitcode.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/bitcode.bzl
@@ -0,0 +1,92 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerInfo")
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load("@prelude//utils:utils.bzl", "value_or")
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+
+BitcodeBundle = record(
+    artifact = field(Artifact),
+)
+
+BitcodeTSet = transitive_set()
+
+BitcodeBundleInfo = provider(
+    fields = {
+        "bitcode": provider_field(typing.Any, default = None),
+        "bitcode_bundle": provider_field(typing.Any, default = None),
+    }
+)
+
+def _bundle_locally(ctx: AnalysisContext, linker_info: LinkerInfo) -> bool:
+    archive_locally = linker_info.archive_objects_locally
+    if hasattr(ctx.attrs, "_archive_objects_locally_override"):
+        return value_or(ctx.attrs._archive_objects_locally_override, archive_locally)
+    return archive_locally
+
+def _bundle(ctx: AnalysisContext, name: str, args: cmd_args, prefer_local: bool) -> Artifact:
+    llvm_link = get_cxx_toolchain_info(ctx).llvm_link
+    if llvm_link == None:
+        fail("Bitcode generation not supported when no LLVM linker, the `cxx_toolchain` has no `llvm_link`.")
+
+    bundle_output = ctx.actions.declare_output(name, has_content_based_path = False)
+
+    command = at_argfile(
+        actions = ctx.actions,
+        name = name + ".cxx_bitcode_argsfile",
+        args = args,
+        allow_args = True,
+    )
+    llvm_cmd = cmd_args(
+        llvm_link,
+        command,
+        "-v",
+        "-o",
+        bundle_output.as_output(),
+    )
+
+    ctx.actions.run(llvm_cmd, category = "bitcode_bundle", identifier = name, prefer_local = prefer_local)
+    return bundle_output
+
+# Creates a static library given a list of object files.
+def make_bitcode_bundle(ctx: AnalysisContext, name: str, objects: list[Artifact], ignore_native: bool = False, override: bool = False) -> [BitcodeBundle, None]:
+    if len(objects) == 0:
+        fail("no objects to archive")
+
+    llvm_link = get_cxx_toolchain_info(ctx).llvm_link
+    if llvm_link == None:
+        return None
+
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+
+    args = cmd_args(quote = "shell")
+    if ignore_native:
+        args.add("--ignore-non-bitcode")
+
+    if override and len(objects) > 1:
+        args.add(objects[0])
+        overrides = cmd_args(objects[1:], format = "--override={}")
+        args.add(overrides)
+    else:
+        args.add(objects)
+
+    bundle = _bundle(ctx, name, args, _bundle_locally(ctx, linker_info))
+
+    return BitcodeBundle(artifact = bundle)
+
+def llvm_link_bitcode_impl(ctx: AnalysisContext) -> list[Provider]:
+    llvm_link = get_cxx_toolchain_info(ctx).llvm_link
+    if llvm_link == None:
+        fail("llvm-link is not provided by toolchain.")
+
+    result = make_bitcode_bundle(ctx, ctx.attrs.name, ctx.attrs.srcs)
+    if result != None:
+        return [DefaultInfo(default_output = result.artifact), BitcodeBundleInfo(bitcode_bundle = result)]
+    else:
+        return [DefaultInfo()]
diff --git a/buck2/prelude/cxx/clang_profile_list.bzl b/buck2/prelude/cxx/clang_profile_list.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/clang_profile_list.bzl
@@ -0,0 +1,63 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+ClangProfileListInfo = provider(
+    fields = {
+        "profile_list": provider_field(Artifact),
+    }
+)
+
+def get_coverage_profile_list_artifact(dep: [Dependency, None]) -> [Artifact, None]:
+    """Extract the profile list artifact from a clang_profile_list dependency."""
+    if dep == None:
+        return None
+    info = dep.get(ClangProfileListInfo)
+    if info == None:
+        return None
+    return info.profile_list
+
+def _clang_profile_list_impl(ctx: AnalysisContext) -> list[Provider]:
+    """
+    Generates a clang profile list file for use with -fprofile-list.
+
+    When `srcs` is non-empty (selective coverage), generates a file that
+    instruments only the listed source files:
+        [clang]
+        source:<path>=allow
+        ...
+        default:skip
+
+    When `srcs` is empty (whole coverage), generates a file that instruments
+    everything:
+        [clang]
+        default:allow
+    """
+    lines = ["[clang]"]
+    for src_path in ctx.attrs.srcs:
+        # Use wildcard prefix to match both direct source paths (fbcode/path/to/file.cpp)
+        # and symlink tree paths (buck-out/.../buck-headers/path/to/file.h)
+        lines.append("source:*{}=allow".format(src_path))
+    if ctx.attrs.srcs:
+        lines.append("default:skip")
+    else:
+        lines.append("default:allow")
+    lines.append("")
+
+    profile_list = ctx.actions.write("profile_list.txt", "\n".join(lines), has_content_based_path = True)
+
+    return [
+        DefaultInfo(default_output = profile_list),
+        ClangProfileListInfo(profile_list = profile_list),
+    ]
+
+clang_profile_list = rule(
+    impl = _clang_profile_list_impl,
+    attrs = {
+        "srcs": attrs.list(attrs.string(), default = []),
+    },
+)
diff --git a/buck2/prelude/cxx/comp_db.bzl b/buck2/prelude/cxx/comp_db.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/comp_db.bzl
@@ -0,0 +1,133 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxInternalTools", "CxxPlatformInfo", "CxxToolchainInfo")
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load(
+    ":compile_types.bzl",
+    "CxxSrcCompileCommand",  # @unused Used as a type
+)
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+load(":cxx_library_utility.bzl", "EMPTY_DEFAULT_INFO")
+
+# Provider that exposes the compilation database information
+CxxCompilationDbInfo = provider(
+    fields = {
+        "info": provider_field(typing.Any, default = None),  # A map of the file (an `Artifact`) to its corresponding `CxxSrcCompileCommand`
+        "platform": provider_field(typing.Any, default = None),  # platform for this compilation database
+        "toolchain": provider_field(typing.Any, default = None),  # toolchain for this compilation database
+    }
+)
+
+def make_compilation_db_info(
+    src_compile_cmds: list[CxxSrcCompileCommand], toolchainInfo: CxxToolchainInfo, platformInfo: CxxPlatformInfo
+) -> CxxCompilationDbInfo:
+    info = {}
+    for src_compile_cmd in src_compile_cmds:
+        info.update({src_compile_cmd.src: src_compile_cmd})
+
+    return CxxCompilationDbInfo(info = info, toolchain = toolchainInfo, platform = platformInfo)
+
+def _comp_database_entry_path(identifier: str, src_path: str) -> str:
+    return paths.join(identifier, "__comp_db__", src_path + ".comp_db.json")
+
+def _create_comp_database_impl(
+    actions: AnalysisActions,
+    internal_tools: CxxInternalTools,
+    identifier: str,
+    src_compile_cmds: list[CxxSrcCompileCommand],
+    db: OutputArtifact,
+    entries: dict[str, OutputArtifact],
+) -> list[Provider]:
+    mk_comp_db = internal_tools.make_comp_db
+
+    # Generate the per-source compilation DB entries.
+    entries_as_input = []
+    for src_compile_cmd in src_compile_cmds:
+        cdb_path = _comp_database_entry_path(identifier, src_compile_cmd.src.short_path)
+        entry = entries.pop(cdb_path, None)
+        if entry:
+            cmd = cmd_args(
+                mk_comp_db,
+                "gen",
+                cmd_args(entry, format = "--output={}"),
+                src_compile_cmd.src.basename,
+                cmd_args(src_compile_cmd.src, parent = 1),
+                "--",
+                src_compile_cmd.cxx_compile_cmd.base_compile_cmd,
+                src_compile_cmd.cxx_compile_cmd.argsfile.cmd_form,
+                src_compile_cmd.args,
+            )
+            entry_identifier = paths.join(identifier, src_compile_cmd.src.short_path)
+            actions.run(cmd, category = "cxx_compilation_database", identifier = entry_identifier)
+            entries_as_input.append(entry.as_input())
+
+    # Merge all entries into the actual compilation DB.
+    cmd = cmd_args(mk_comp_db)
+    cmd.add("merge")
+    cmd.add(cmd_args(db, format = "--output={}"))
+
+    cmd.add(
+        at_argfile(
+            actions = actions,
+            name = identifier + ".cxx_comp_db_argsfile",
+            args = entries_as_input,
+        )
+    )
+
+    actions.run(cmd, category = "cxx_compilation_database_merge", identifier = identifier)
+
+    return [EMPTY_DEFAULT_INFO]
+
+_dynamic_compilation_database_rule = dynamic_actions(
+    impl = _create_comp_database_impl,
+    attrs = {
+        "db": dynattrs.output(),
+        "entries": dynattrs.dict(str, dynattrs.output()),
+        "identifier": dynattrs.value(str),
+        "internal_tools": dynattrs.value(CxxInternalTools),
+        "src_compile_cmds": dynattrs.list(dynattrs.value(CxxSrcCompileCommand)),
+    },
+)
+
+def create_compilation_database(ctx: AnalysisContext, src_compile_cmds: list[CxxSrcCompileCommand], identifier: str) -> DefaultInfo:
+    actions = ctx.actions
+
+    # Generate the per-source compilation DB entries.
+    entries = {}
+    other_outputs = []
+
+    for src_compile_cmd in src_compile_cmds:
+        cdb_path = _comp_database_entry_path(identifier, src_compile_cmd.src.short_path)
+        if cdb_path not in entries:
+            entry = actions.declare_output(cdb_path, has_content_based_path = False)
+
+            # Add all inputs the command uses to runtime files.
+            other_outputs.append(entry)
+            other_outputs.append(src_compile_cmd.src)
+            other_outputs.append(src_compile_cmd.cxx_compile_cmd.base_compile_cmd)
+            other_outputs.append(src_compile_cmd.cxx_compile_cmd.argsfile.cmd_form)
+            entries[cdb_path] = entry.as_output()
+
+    # Merge all entries into the actual compilation DB.
+    db = actions.declare_output(paths.join(identifier, "compile_commands.json"), has_content_based_path = False)
+
+    # We don't have any dynamic inputs here and use dynamic action purely as an optimization
+    # so we don't occupy memory in analysis graph until we actually need compilation database.
+    actions.dynamic_output_new(
+        _dynamic_compilation_database_rule(
+            db = db.as_output(),
+            entries = entries,
+            identifier = identifier,
+            internal_tools = get_cxx_toolchain_info(ctx).internal_tools,
+            src_compile_cmds = src_compile_cmds,
+        ),
+    )
+
+    return DefaultInfo(default_output = db, other_outputs = other_outputs)
diff --git a/buck2/prelude/cxx/compilation_database_labels.bzl b/buck2/prelude/cxx/compilation_database_labels.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/compilation_database_labels.bzl
@@ -0,0 +1,73 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Handles labels used to provide compilation database information for filegroup() and genrule() targets.
+
+Our language services need to know how to compile files owned solely by filegroup() or genrule() targets like:
+* Regular generated sources, that then end up being compiled by regular cxx_ or apple_ targets.
+* Manually declared mixin files, that are always compiled by multiple other targets spread across the codebase.
+* Files built by external build systems wrapped in genrules(), where compile_commands.json is produced by yet another genrule().
+
+Prior approach for the former two cases was to run rdeps() queries to find a compilable target that would have a compile_commands.json entry for the file.
+It suffered from reliability and performance issues, as the universe for rdeps() queries had to be quite broad and with no guarantee that there isn't even a single broken target within it.
+And for external build system wrappers where there is no compilable target, we could define a rule that would effectively wrap two genrules and expose one of them as [compilation-database] subtarget,
+but that wouldn't solve the problem with mixins which is still relevant with external build systems and would put us in the same suboptimal spot in terms of performance and reliability.
+
+As the IDE needs to operate in O(changes) instead of O(repo), and open files even if some other corner of the repo is broken.
+We need to make things both reliable and performant in an ever-growing codebase with a CI that explicitly cannot guarantee that the entire repo is green, and where rdeps() queries are thus flaky and slow.
+
+And as the IDE needs to react to any local changes and act consistently with local checkout, we cannot simply use a remote cache for rdeps() queries that are slow and flaky.
+
+So the solution is instead to localize the required information within the target, and directly point to the build system rules that provide compile_commands.json for the target.
+"""
+
+def compilation_database_rules(source_mapping: dict[str, list[str]] | list[str]) -> list[str]:
+    """
+    Takes a mapping from sources to the rules to be used to build compilation databases for those sources.
+
+    Tooling like IDEs needs to obtain compile commands for source files that are exported by filegroup() to be built as part of another target, or are built with an external build system wrapped in a genrule().
+    Labels provide a convenient way to link the non-compileable target with a rule that produces a compilation database for its sources:
+    ```
+    load("@prelude//cxx:compilation_database_labels.bzl", "compilation_database_rules")
+
+    # The shorthand way for most cases:
+    export_file(
+        name = "gadget_to_be_compiled_as_part_of_another_target.cpp",
+        labels = compilation_database_rules([
+            "//path/to/some/dependent:target",
+            "//path/to/another/dependent:target",
+        ])
+    )
+
+    # A per-source mapping for cases when the generated files from one genrule() are compiled in different targets and never together:
+    genrule(
+        name = "multiple_gadgets_for_different_purposes",
+        labels = compilation_database_rules({
+            "server_gen.cpp": ["//path/to/dependent/module:server"],
+            "client_gen.cpp": ["//path/to/dependent/module:client"],
+        })
+    )
+    ```
+    The tooling can use a BXL script to check the target kind and extract the compilation database rule from its labels. And then iterate over the resulting compilation database and resolve the symlinks in 'file' entries in order to find the matching entry for the original source.
+
+    :param dict[str,str]|list[str] source_mapping: A mapping with source file name regex as key and target as value. The target has to be either a target with [compilation-database] subtarget, or a genrule that produces compile_commands.json (for wrapping external build systems).
+    """
+    if not isinstance(source_mapping, dict):
+        source_mapping = {".*": source_mapping}
+    return ["compilation_database_rules=" + json.encode(source_mapping)]
+
+def get_compilation_database_rules(labels = list[str]) -> dict[str, list[str]] | None:
+    """
+    Retrieves and decodes compilation database targets from target labels, if any.
+    """
+    for label in labels:
+        value = label.removeprefix("compilation_database_rules=")
+        if value != label:
+            return json.decode(value)
+    return None
diff --git a/buck2/prelude/cxx/compile.bzl b/buck2/prelude/cxx/compile.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/compile.bzl
@@ -0,0 +1,2754 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//cxx:compile_types.bzl",
+    "AsmExtensions",
+    "CudaDistributedCompileOutput",
+    "CxxCompileCommand",
+    "CxxCompileCommandOutput",
+    "CxxCompileFlavor",
+    "CxxCompileOutput",
+    "CxxExtension",
+    "CxxSrcCompileCommand",
+    "CxxSrcPrecompileCommand",
+    "DepFileType",
+    "HeaderExtension",
+    "HeadersDepFiles",
+    "IndexStoreFactory",
+    "UseHeaderUnitsMode",
+)
+load(
+    "@prelude//cxx:cuda.bzl",
+    "CudaCompileInfo",
+    "CudaCompileStyle",  # @unused Used as a type
+    "CudaDistributedCompileSpec",  # @unused Used as a type
+    "create_cuda_distributed_compiles",
+    "cuda_compile",
+    "declare_cuda_dist_compile_output",
+)
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("@prelude//cxx:hip_debug_extract.bzl", "hip_debug_extract_available", "hip_debug_extract_compile_object")
+load(
+    "@prelude//ide_integrations/xcode:argsfiles.bzl",
+    "XCODE_ARG_SUBSTITUTIONS",
+)
+load("@prelude//linking:lto.bzl", "LtoMode")
+load("@prelude//utils:argfile.bzl", "argsfile_with_artifacts", _mk_argsfile = "mk_argsfile")
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    "@prelude//utils:utils.bzl",
+    "as_output",
+    "flatten",
+    "map_val",
+)
+load(":argsfiles.bzl", "CompileArgsfile", "CompileArgsfiles")
+load(":attr_selection.bzl", "cxx_by_language_ext")
+load(
+    ":compiler.bzl",
+    "get_flags_for_colorful_output",
+    "get_flags_for_reproducible_build",
+    "get_headers_dep_files_flags_factory",
+    "get_output_flags",
+)
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    ":cxx_flags.bzl",
+    "CxxFlagsInfo",
+    "cxx_flags_projection_name",
+    "cxx_flags_tset",
+)
+load(":cxx_library_utility.bzl", "EMPTY_DEFAULT_INFO")
+load(":cxx_sources.bzl", "CxxSrcWithFlags")
+load(":cxx_toolchain_types.bzl", "CxxObjectFormat", "DepTrackingMode", "compiler_info_with_argsfiles")
+load(":cxx_types.bzl", "CxxRuleConstructorParams")
+load(":debug.bzl", "SplitDebugMode")
+load(
+    ":headers.bzl",
+    "CHeader",
+    "CPrecompiledHeaderInfo",
+    "CxxPrecompiledHeader",  # @unused Used in type annotation
+    "add_headers_dep_files",
+)
+load(
+    ":preprocessor.bzl",
+    "CPreprocessor",  # @unused Used as a type
+    "CPreprocessorInfo",  # @unused Used as a type
+    "HeaderUnit",  # @unused Used as a type
+    "cxx_merge_cpreprocessors",
+    "get_flags_for_compiler_type",
+)
+
+# Output folder shared by every per-source object declaration; the shared CUDA
+# plan must declare its outputs under the same folder as the objects it feeds.
+_OBJECTS_FOLDER = "__objects__"
+
+_CUDA_DRYRUN_SOURCE_PLACEHOLDER = "__buck2_cuda_dryrun_placeholder__.cu"
+
+# Record containing compile info that will be passed to the dynamic action
+CxxCompileInfo = record(
+    src = field(Artifact),
+    args = field(list[typing.Any]),
+    short_path = field(str),
+    filename_base = field(str),
+    index_store_base = field(str | None),  # filename_base for index store compilation
+    identifier = field(str),
+    folder_name = field(str),
+)
+
+CxxSharedCompileInfo = record(
+    cxx_compile_cmd = field(CxxCompileCommand),
+    index_store_factory = field(IndexStoreFactory | None),
+    error_handler = field([typing.Callable, None]),
+    expect_eligible_for_dedupe = field(bool),
+)
+
+# Input for a single CXX compilation - declared artifacts and compile info
+CxxCompileInput = record(
+    declared_artifacts = field(CxxCompileOutput),
+    info = field(CxxCompileInfo),
+)
+
+CxxSharedCompileCommandArgs = record(
+    before_src = field(cmd_args),
+    after_src = field(cmd_args),
+)
+
+def _project_clang_traces_as_args(traces: list[Artifact]):
+    return cmd_args(traces)
+
+ClangTracesTSet = transitive_set(
+    args_projections = {
+        "clang_traces": _project_clang_traces_as_args,
+    },
+)
+
+ClangTracesInfo = provider(
+    fields = {
+        "clang_traces": provider_field(typing.Any, default = None),  # "ClangTracesTSet"
+    }
+)
+PicClangTracesInfo = provider(
+    fields = {
+        "clang_traces": provider_field(typing.Any, default = None),  # "ClangTracesTSet"
+    }
+)
+
+def get_source_extension_for_header(header_extension: str, default: CxxExtension) -> CxxExtension:
+    """
+    Which source file extension to use to get compiler flags for the header.
+    """
+    if header_extension in (".hpp", ".hh", ".h++", ".hxx"):
+        return CxxExtension(".cpp")
+    elif header_extension == ".cuh":
+        return CxxExtension(".cu")
+    elif header_extension not in HeaderExtension.values():
+        return CxxExtension(header_extension)  # a file in `headers` has a source extension
+    else:
+        return default
+
+def get_source_extension(src: CxxSrcWithFlags, default_for_headers: CxxExtension) -> CxxExtension:
+    """
+    Which source files extension to use for a source or a header file. We want
+    headers to appear as though they are source files.
+    """
+    if src.is_header:
+        return get_source_extension_for_header(src.file.extension, default_for_headers)
+    else:
+        return CxxExtension(src.file.extension)
+
+def collect_extensions(srcs: list[CxxSrcWithFlags]) -> set[CxxExtension]:
+    """
+    Collect extensions of source files while doing light normalization.
+    """
+
+    duplicates = {
+        ".c++": ".cpp",
+        ".cc": ".cpp",
+        ".cxx": ".cpp",
+    }
+
+    extensions = set([CxxExtension(duplicates.get(src.file.extension, src.file.extension)) for src in srcs])
+    return extensions
+
+def default_source_extension_for_plain_header(rule_type: str) -> CxxExtension:
+    """
+    Returns default source file extension to use to get get compiler flags for plain .h headers.
+    """
+
+    # Default to (Objective-)C++ instead of plain (Objective-)C as it is more likely to be compatible with both.
+    return CxxExtension(".mm") if rule_type.startswith("apple_") else CxxExtension(".cpp")
+
+def detect_source_extension_for_plain_headers(exts: set[CxxExtension], rule_type: str) -> CxxExtension:
+    """
+    For a given list source files determine which source file extension
+    to use to get compiler flags for plain .h headers.
+    """
+
+    # Assembly doesn't need any special handling as included files tend to have .asm extension themselves.
+    # And the presence of assembly in the target doesn't tell us anything about the language of .h files.
+    for asm_ext in AsmExtensions:
+        exts.discard(asm_ext)
+
+    if len(exts) == 0:
+        return default_source_extension_for_plain_header(rule_type)
+
+    if len(exts) == 1:
+        return exts.pop()
+    if CxxExtension(".hip") in exts:
+        return CxxExtension(".hip")
+    if CxxExtension(".cu") in exts:
+        return CxxExtension(".cu")
+    if CxxExtension(".mm") in exts:
+        return CxxExtension(".mm")
+    if CxxExtension(".cpp") in exts and CxxExtension(".m") in exts:
+        return CxxExtension(".mm")
+    if CxxExtension(".cpp") in exts:
+        return CxxExtension(".cpp")
+    if CxxExtension(".m") in exts:
+        return CxxExtension(".m")
+    return CxxExtension(".c")
+
+def collect_source_extensions(srcs: list[CxxSrcWithFlags], default_for_headers: CxxExtension) -> set[CxxExtension]:
+    """
+    Return unique source extensions from a list of source and header files where
+    header extensions are mapped to corresponding source extensions.
+    """
+    source_extensions = set([get_source_extension(src, default_for_headers) for src in srcs])
+    return source_extensions
+
+def get_header_language_mode(source_extension: CxxExtension) -> str | None:
+    """
+    Returns the header mode to use for plain .h headers based on the
+    source file extension used to obtain the compiler flags for them.
+    """
+
+    # Note: CUDA doesn't have its own header language mode, but the headers have distinct .cuh extension.
+    modes = {
+        CxxExtension(".cpp"): "c++-header",
+        CxxExtension(".m"): "objective-c-header",
+        CxxExtension(".mm"): "objective-c++-header",
+    }
+    return modes.get(source_extension)
+
+def create_compile_cmds(
+    actions: AnalysisActions,
+    target_label: Label,
+    toolchain: CxxToolchainInfo,
+    impl_params: CxxRuleConstructorParams,
+    own_preprocessors: list[CPreprocessor],
+    inherited_preprocessor_infos: list[CPreprocessorInfo],
+    add_coverage_instrumentation_compiler_flags: bool,
+    compile_pch: CxxPrecompiledHeader | None = None,
+    filename_prefix: str = "",
+) -> CxxCompileCommandOutput:
+    """
+    Forms the CxxSrcCompileCommand to use for each source file based on it's extension
+    and optional source file flags. Returns CxxCompileCommandOutput containing an array
+    of the generated compile commands and argsfile output.
+    """
+
+    if compile_pch:
+        srcs_extensions = set([CxxExtension(compile_pch.clanguage)])
+    else:
+        srcs_extensions = collect_extensions(impl_params.srcs)
+    extension_for_plain_headers = detect_source_extension_for_plain_headers(srcs_extensions, impl_params.rule_type)
+
+    srcs_with_flags = []  # type: [CxxSrcWithFlags]
+
+    for src in impl_params.srcs:
+        srcs_with_flags.append(src)
+
+    # Some targets have .cpp files in their `headers` lists, see D46195628
+    # todo: should this be prohibited or expanded to allow all source extensions?
+    artifact_extensions = HeaderExtension.values() + [".cpp"]
+    all_headers = flatten([x.headers for x in own_preprocessors])
+    for header in all_headers:
+        if header.artifact.extension in artifact_extensions:
+            srcs_with_flags.append(CxxSrcWithFlags(file = header.artifact, is_header = True))
+
+    all_raw_headers = flatten([x.raw_headers for x in own_preprocessors])
+    for header in all_raw_headers:
+        if header.extension in HeaderExtension.values():
+            srcs_with_flags.append(CxxSrcWithFlags(file = header, is_header = True))
+
+    if len(srcs_with_flags) == 0:
+        return CxxCompileCommandOutput()
+
+    # TODO(T110378129): Buck v1 validates *all* headers used by a compilation
+    # at compile time, but that doing that here/eagerly might be expensive (but
+    # we should figure out something).
+    _validate_target_headers(target_label, own_preprocessors)
+
+    # Combine all preprocessor info and prepare it for compilations.
+    pre = cxx_merge_cpreprocessors(
+        actions,
+        filter(None, own_preprocessors + impl_params.extra_preprocessors),
+        inherited_preprocessor_infos,
+    )
+
+    headers_tag = actions.artifact_tag()
+
+    src_compile_cmds = []
+    hdr_compile_cmds = []
+    cxx_compile_cmd_by_ext = {}  # type: dict[CxxExtension, CxxCompileCommand]
+    argsfile_by_ext = {}  # type: dict[str, CompileArgsfile]
+    xcode_argsfile_by_ext = {}  # type: dict[str, CompileArgsfile]
+    if compile_pch:
+        src_extensions = [CxxExtension(compile_pch.clanguage)]
+    else:
+        src_extensions = collect_source_extensions(srcs_with_flags, extension_for_plain_headers)
+
+    # Deduplicate shared arguments to save memory. If we compile multiple files
+    # of the same extension they will have some of the same flags. Save on
+    # allocations by caching and reusing these objects.
+    for ext in src_extensions:
+        cmd = _generate_base_compile_command(
+            actions,
+            target_label,
+            toolchain,
+            impl_params,
+            pre,
+            headers_tag,
+            ext,
+            filename_prefix = filename_prefix,
+        )
+        cxx_compile_cmd_by_ext[ext] = cmd
+        argsfile_by_ext[ext.value] = cmd.argsfile
+        if cmd.xcode_argsfile != None:
+            xcode_argsfile_by_ext[ext.value] = cmd.xcode_argsfile
+
+    # Add -fprofile-list for selective coverage instrumentation.
+    # The profile list file is generated by a clang_profile_list rule and tells
+    # clang which source files to instrument, reducing overhead.
+    coverage_profile_list_args = []
+    if add_coverage_instrumentation_compiler_flags and impl_params.coverage_profile_list:
+        coverage_profile_list_args = [cmd_args(impl_params.coverage_profile_list, format = "-fprofile-list={}")]
+
+    for src in srcs_with_flags:
+        src_args = []
+        src_args.extend(src.flags)
+
+        if compile_pch:
+            ext = CxxExtension(compile_pch.clanguage)
+        else:
+            ext = get_source_extension(src, extension_for_plain_headers)
+
+        cxx_compile_cmd = cxx_compile_cmd_by_ext[ext]
+
+        if add_coverage_instrumentation_compiler_flags and cxx_compile_cmd.compiler_type != "gcc":
+            src_args.extend(impl_params.coverage_instrumentation_compiler_flags)
+            src_args.extend(coverage_profile_list_args)
+
+        if src.is_header or compile_pch:
+            if cxx_compile_cmd.compiler_type in ["clang", "clang_windows", "gcc"]:
+                language_mode = get_header_language_mode(ext)
+                src_args.extend(["-x", language_mode] if language_mode else [])
+            elif cxx_compile_cmd.compiler_type in ["clang_cl", "windows", "windows_ml64"] and ext == CxxExtension(".cpp"):
+                src_args.append("/TP")
+
+        if cxx_compile_cmd.compiler_type != "nasm":
+            src_args.append("-c")
+
+        src_args.append(src.file)
+
+        src_compile_command = CxxSrcCompileCommand(
+            src = src.file,
+            cxx_compile_cmd = cxx_compile_cmd,
+            args = src_args,
+            index = src.index,
+            is_header = src.is_header,
+            uses_content_based_paths = cxx_compile_cmd.allow_content_based_paths,
+            index_store_factory = impl_params.index_store_factory,
+            error_handler = impl_params.error_handler,
+            expect_eligible_for_dedupe = impl_params.expect_eligible_for_dedupe,
+        )
+
+        if src.is_header:
+            hdr_compile_cmds.append(src_compile_command)
+        else:
+            src_compile_cmds.append(src_compile_command)
+
+    argsfile_by_ext.update(impl_params.additional.argsfiles.relative)
+    xcode_argsfile_by_ext.update(impl_params.additional.argsfiles.xcode)
+
+    return CxxCompileCommandOutput(
+        src_compile_cmds = src_compile_cmds,
+        base_compile_cmds = cxx_compile_cmd_by_ext,
+        argsfiles = CompileArgsfiles(
+            relative = argsfile_by_ext,
+            xcode = xcode_argsfile_by_ext,
+        ),
+        comp_db_compile_cmds = src_compile_cmds + hdr_compile_cmds,
+    )
+
+COMMON_PREPROCESSOR_OUTPUT_ARGS = cmd_args("-E", "-dD")
+
+def _prepare_cxx_compilation(
+    actions: AnalysisActions,
+    toolchain: CxxToolchainInfo,
+    default_object_format: CxxObjectFormat,
+    src_compile_cmd: CxxSrcCompileCommand,
+    flavors: set[CxxCompileFlavor],
+    provide_syntax_only: bool,
+    use_header_units: UseHeaderUnitsMode,
+    separate_debug_info: bool,
+    cuda_compile_style: CudaCompileStyle | None,
+    shared_cuda_dist_output: CudaDistributedCompileOutput | None,
+    compile_pch: CxxPrecompiledHeader | None,
+) -> CxxCompileInput:
+    """
+    DECLARATION PHASE: Declares all output artifacts for a single source file compilation.
+    """
+    short_path = src_compile_cmd.src.short_path
+    if src_compile_cmd.index != None:
+        # Add a unique postfix if we have duplicate source files with different flags
+        short_path = short_path + "_" + str(src_compile_cmd.index)
+
+    filename_base = short_path
+    identifier = short_path
+
+    if (
+        src_compile_cmd.cxx_compile_cmd.category == "cxx_compile"
+        and use_header_units == UseHeaderUnitsMode("pcm")
+        and src_compile_cmd.cxx_compile_cmd.header_units_argsfile
+    ):
+        identifier += " (modular)"
+
+    for flavor in flavors:
+        filename_base = "{}.{}".format(filename_base, flavor.value)
+        identifier = "{} ({})".format(identifier, flavor.value)
+
+    content_based = src_compile_cmd.uses_content_based_paths
+    folder_name = _OBJECTS_FOLDER
+    compiler_type = src_compile_cmd.cxx_compile_cmd.compiler_type
+
+    # Declare main object output
+    object = actions.declare_output(
+        folder_name,
+        "{}.{}".format(filename_base, toolchain.linker_info.object_file_extension),
+        has_content_based_path = content_based,
+    )
+
+    # Diagnostics
+    diagnostics = None
+    clang_tidy_diagnostics = None
+    if compiler_type == "clang" and provide_syntax_only:
+        diagnostics = actions.declare_output(
+            "__diagnostics__",
+            "{}.diag.txt".format(short_path),
+            has_content_based_path = False,
+        )
+        if toolchain.binary_utilities_info.custom_tools.get("clang-tidy"):
+            clang_tidy_diagnostics = actions.declare_output(
+                "__diagnostics__",
+                "{}.clang-tidy.txt".format(short_path),
+                has_content_based_path = False,
+            )
+
+    # Declare index store upfront using factory.declare() if available
+    index_store = None
+    index_store_base = None
+    if CxxCompileFlavor("pic") in flavors and src_compile_cmd.index_store_factory:
+        factory = src_compile_cmd.index_store_factory
+        declared_index_store = factory.declare(actions, src_compile_cmd)
+        if declared_index_store:
+            index_store = declared_index_store.output
+            index_store_base = declared_index_store.filename_base
+
+    # Clang LLVM statistics
+    clang_llvm_statistics = None
+    if toolchain.clang_llvm_statistics and compiler_type == "clang":
+        clang_llvm_statistics = actions.declare_output(
+            paths.join("__objects__", "{}.stats".format(filename_base)),
+            has_content_based_path = content_based,
+        )
+
+    # GCNO file
+    gcno_file = None
+    if toolchain.gcno_files and src_compile_cmd.src.extension not in (".S", ".sx"):
+        gcno_file = actions.declare_output(
+            paths.join("__objects__", "{}.gcno".format(filename_base)),
+            has_content_based_path = content_based,
+        )
+
+    # Clang remarks
+    clang_remarks = None
+    if toolchain.clang_remarks and compiler_type == "clang":
+        clang_remarks = actions.declare_output(
+            paths.join("__objects__", "{}.opt.yaml".format(filename_base)),
+            has_content_based_path = content_based,
+        )
+
+    # Generate pre-processed sources
+    preproc = actions.declare_output(
+        "__preprocessed__",
+        "{}.{}".format(filename_base, "i"),
+        has_content_based_path = content_based,
+    )
+
+    # External debug info
+    external_debug_info = None
+    extension_supports_external_debug_info = src_compile_cmd.src.extension not in (".hip")
+    use_external_debug_info = (
+        separate_debug_info and toolchain.split_debug_mode == SplitDebugMode("split") and compiler_type == "clang" and extension_supports_external_debug_info
+    )
+    if use_external_debug_info:
+        external_debug_info = actions.declare_output(
+            folder_name,
+            "{}.{}".format(filename_base, "dwo"),
+            has_content_based_path = content_based,
+        )
+
+    # .S extension is native assembly code (machine level, processor specific)
+    # and clang will happily compile them to .o files, but the object are always
+    # native even if we ask for bitcode.  If we don't mark the output format,
+    # other tools would try and parse the .o file as LLVM-IR and fail.
+    if src_compile_cmd.src.extension in [".S", ".s"]:
+        object_format = CxxObjectFormat("native")
+    else:
+        object_format = default_object_format
+
+    assembly = _declare_assembly(
+        actions = actions,
+        compiler_type = compiler_type,
+        object_format = object_format,
+        filename_base = filename_base,
+        content_based = content_based,
+    )
+
+    # If we're building with split debugging, where the debug info is in the
+    # original object, then add the object as external debug info
+    # FIXME: ThinLTO generates debug info in a separate dwo dir, but we still
+    # need to track object files if the object file is not compiled to bitcode.
+    # We should track whether ThinLTO is used on a per-object basis rather than
+    # globally on a toolchain level.
+    object_has_external_debug_info = toolchain.split_debug_mode == SplitDebugMode("single")
+
+    clang_trace = _declare_clang_trace_output(toolchain, compiler_type, actions, filename_base, content_based)
+
+    # Only declare CUDA distributed compile outputs for CUDA source files
+    cuda_dist_output = None
+    if src_compile_cmd.src.extension == ".cu" and cuda_compile_style == CudaCompileStyle("dist"):
+        cuda_dist_output = shared_cuda_dist_output or declare_cuda_dist_compile_output(
+            actions,
+            CudaCompileInfo(
+                filename = filename_base,
+                identifier = identifier,
+                output_prefix = folder_name,
+                uses_content_based_paths = content_based,
+            ),
+        )
+
+    # Declare PCH object output for Windows compiler
+    pch_object = None
+    if compiler_type == "windows" and compile_pch:
+        pch_object = actions.declare_output(
+            folder_name,
+            "{}.pch.o".format(filename_base),
+            has_content_based_path = content_based,
+        )
+
+    # JSON error output
+    json_error = None
+    serialized_diags_to_json = toolchain.binary_utilities_info.custom_tools.get("serialized-diags-to-json", None)
+    if serialized_diags_to_json and src_compile_cmd.error_handler and compiler_type == "clang" and src_compile_cmd.src.extension != ".cu":
+        json_error = actions.declare_output(
+            "__diagnostics__/{}.json".format(filename_base),
+            has_content_based_path = content_based,
+        )
+
+    hip_device_debug = src_compile_cmd.src.extension == ".hip" and toolchain.hip_device_debug_extract
+
+    declared_artifacts = CxxCompileOutput(
+        object = object,
+        object_format = object_format,
+        object_has_external_debug_info = object_has_external_debug_info,
+        external_debug_info = external_debug_info,
+        clang_remarks = clang_remarks,
+        clang_llvm_statistics = clang_llvm_statistics,
+        clang_trace = clang_trace,
+        gcno_file = gcno_file,
+        index_store = index_store,
+        assembly = assembly,
+        diagnostics = diagnostics,
+        clang_tidy_diagnostics = clang_tidy_diagnostics,
+        preproc = preproc,
+        dist_cuda = cuda_dist_output,
+        pch_object = pch_object,
+        json_error = json_error,
+        hip_device_debug = hip_device_debug,
+    )
+
+    info = CxxCompileInfo(
+        src = src_compile_cmd.src,
+        args = src_compile_cmd.args,
+        short_path = short_path,
+        filename_base = filename_base,
+        index_store_base = index_store_base,
+        identifier = identifier,
+        folder_name = folder_name,
+    )
+
+    return CxxCompileInput(
+        declared_artifacts = declared_artifacts,
+        info = info,
+    )
+
+def _compile_single_cxx(
+    actions: AnalysisActions,
+    label: Label,
+    toolchain: CxxToolchainInfo,
+    flavors: set[CxxCompileFlavor],
+    compile_pch: CxxPrecompiledHeader | None,
+    precompiled_header: Dependency | None,
+    cuda_compile_style: CudaCompileStyle | None,
+    # CxxCompileInfo fields
+    info: CxxCompileInfo,
+    shared_info: CxxSharedCompileInfo,
+    # Output artifacts
+    object: OutputArtifact,
+    external_debug_info: OutputArtifact | None,
+    clang_remarks: OutputArtifact | None,
+    clang_llvm_statistics: OutputArtifact | None,
+    clang_trace: OutputArtifact | None,
+    gcno_file: OutputArtifact | None,
+    assembly: OutputArtifact | None,
+    diagnostics: OutputArtifact | None,
+    clang_tidy_diagnostics: OutputArtifact | None,
+    preproc: OutputArtifact,
+    index_store: OutputArtifact | None,
+    dist_cuda: CudaDistributedCompileOutput | None,
+    prepare_cuda_dist: bool,
+    cuda_shared_plan_identifier: str | None,
+    shared_compile_args: CxxSharedCompileCommandArgs,
+    shared_auxiliary_args: CxxSharedCompileCommandArgs,
+    shared_dryrun_args: CxxSharedCompileCommandArgs | None,
+    pch_object: OutputArtifact | None,
+    json_error: OutputArtifact | None,
+) -> CudaDistributedCompileSpec | None:
+    """
+    EXECUTION PHASE: Creates compilation actions for a single source file.
+
+    This function runs INSIDE the dynamic action callback (`_cxx_dynamic_compile`),
+    meaning it only executes when Buck2 determines the compilation is actually needed.
+
+    ## Relationship to Declaration Phase
+    The output artifacts passed here were declared earlier by `_prepare_cxx_compilation`
+    during the analysis phase.
+    """
+
+    # Extract info fields
+    src = info.src
+    src_args = info.args
+    filename_base = info.filename_base
+    index_store_base = info.index_store_base
+    identifier = info.identifier
+    folder_name = info.folder_name
+    short_path = info.short_path
+    cxx_compile_cmd = shared_info.cxx_compile_cmd
+
+    # Get compiler type
+    compiler_type = cxx_compile_cmd.compiler_type
+    content_based = cxx_compile_cmd.allow_content_based_paths
+
+    cuda_dist_spec = None
+    if src.extension == ".cu":
+        output_args = None
+    elif compile_pch:
+        if compiler_type == "windows":
+            output_args = [
+                cmd_args(object, format = "/Fp{}"),
+                cmd_args(pch_object, format = "/Fo{}"),
+                cmd_args(compile_pch.path, format = "/Yc{}"),
+            ]
+        else:
+            output_args = [
+                get_output_flags(compiler_type, object),
+                "-Xclang",
+                "-emit-pch",
+                "-Xclang",
+                "-fno-pch-timestamp",
+                "-fpch-instantiate-templates",
+            ]
+    else:
+        output_args = get_output_flags(compiler_type, object)
+
+    base_compile_cmd_override = None
+    if src.extension == ".cu" and cuda_compile_style == CudaCompileStyle("dist"):
+        compiler_for_dryrun = getattr(toolchain.cuda_compiler_info, "compiler_for_dryrun", None)
+        if compiler_for_dryrun != None:
+            base_compile_cmd_override = _get_compile_base(
+                toolchain,
+                toolchain.cuda_compiler_info,
+                use_wrapper = False,
+                compiler_override = compiler_for_dryrun,
+            )
+
+    cmd = _get_base_compile_cmd(
+        src = src,
+        src_args = src_args,
+        cxx_compile_cmd = cxx_compile_cmd,
+        output_args = output_args,
+        base_compile_cmd_override = base_compile_cmd_override,
+        shared_args = shared_compile_args,
+    )
+    cuda_prepare_cmd = None
+    if prepare_cuda_dist:
+        expect(shared_dryrun_args != None, "distributed CUDA prepare requires dry-run compile args")
+        cuda_prepare_cmd = _get_base_compile_cmd(
+            src = src,
+            src_args = src_args,
+            cxx_compile_cmd = cxx_compile_cmd,
+            base_compile_cmd_override = base_compile_cmd_override,
+            source_override = _CUDA_DRYRUN_SOURCE_PLACEHOLDER,
+            shared_args = shared_dryrun_args,
+        )
+
+    if index_store:
+        compile_index_store_cmd = _get_base_compile_cmd(
+            src = src,
+            src_args = src_args,
+            cxx_compile_cmd = cxx_compile_cmd,
+            shared_args = shared_auxiliary_args,
+        )
+        shared_info.index_store_factory.compile(
+            actions,
+            label,
+            index_store,
+            index_store_base,
+            toolchain,
+            compile_index_store_cmd,
+        )
+
+    if precompiled_header and precompiled_header[CPrecompiledHeaderInfo] and precompiled_header[CPrecompiledHeaderInfo].compiled:
+        pch_info = precompiled_header[DefaultInfo].sub_targets["pch"]
+        pch_subtargets = pch_info.get(DefaultInfo).sub_targets
+
+        pch_flavor = "default"
+        for flavor in flavors:
+            pch_flavor = flavor.value if flavor.value else pch_flavor
+
+        target = pch_subtargets[pch_flavor].get(CPrecompiledHeaderInfo)
+        cmd.add(_get_use_pch_args(src, cxx_compile_cmd, target, precompiled_header[CPrecompiledHeaderInfo]))
+
+    action_dep_files = {}
+
+    headers_dep_files = cxx_compile_cmd.headers_dep_files
+
+    # CUDA compilation attaches dep files itself (see cuda_mono_compile and
+    # cuda_distributed_compile), because the flags have to land on the real
+    # compile sub-command rather than on the nvcc driver command we dryrun here.
+    if src.extension == ".cu":
+        headers_dep_files = None
+
+    if headers_dep_files:
+        cmd = add_headers_dep_files(
+            actions,
+            cmd,
+            headers_dep_files,
+            src,
+            filename_base,
+            action_dep_files,
+        )
+
+    if clang_remarks:
+        cmd.add(["-fsave-optimization-record", "-fdiagnostics-show-hotness", "-foptimization-record-passes=" + toolchain.clang_remarks])
+        cmd.add(cmd_args(hidden = clang_remarks))
+
+    if clang_llvm_statistics:
+        # Use stderr_to_file to capture clang statistics output
+        cmd = cmd_args(
+            toolchain.internal_tools.stderr_to_file,
+            cmd_args(clang_llvm_statistics, format = "--out={}"),
+            cmd,
+            ["-mllvm", "-stats"],
+        )
+
+    if clang_trace:
+        cmd.add(["-ftime-trace"])
+        cmd.add(cmd_args(hidden = clang_trace))
+
+    if gcno_file:
+        cmd.add(["--coverage"])
+        cmd.add(cmd_args(hidden = gcno_file))
+
+    if external_debug_info:
+        cmd.add(cmd_args(external_debug_info, format = "--fbcc-create-external-debug-info={}"))
+
+    outputs_for_error_handler = []
+    if json_error:
+        # We need to wrap the entire compile to provide serialized diagnostics
+        # output and on error convert it to JSON.
+        serialized_diags_to_json = toolchain.binary_utilities_info.custom_tools.get("serialized-diags-to-json", None)
+        outputs_for_error_handler.append(json_error)
+        cmd = cmd_args(
+            toolchain.internal_tools.serialized_diagnostics_to_json_wrapper,
+            serialized_diags_to_json,
+            json_error,
+            cmd,
+        )
+
+    if src.extension == ".cu":
+        expect(cuda_compile_style != None, "CUDA compile style should be configured for targets with .cu sources")
+        cuda_compile_info = CudaCompileInfo(
+            filename = filename_base,
+            identifier = identifier,
+            output_prefix = folder_name,
+            uses_content_based_paths = content_based,
+        )
+
+        cuda_dist_spec = cuda_compile(
+            actions,
+            cmd,
+            object,
+            src,
+            cxx_compile_cmd,
+            cuda_compile_info,
+            action_dep_files,
+            allow_dep_file_cache_upload = False,
+            error_handler = shared_info.error_handler,
+            cuda_compile_style = cuda_compile_style,
+            cuda_dist_output = dist_cuda,
+            cuda_prepare_cmd = cuda_prepare_cmd,
+            shared_plan_identifier = cuda_shared_plan_identifier,
+        )
+    else:
+        is_producing_compiled_pch = bool(compile_pch)
+        is_consuming_compiled_pch = bool(precompiled_header and precompiled_header[CPrecompiledHeaderInfo].compiled)
+        actions.run(
+            cmd,
+            category = cxx_compile_cmd.category,
+            identifier = identifier,
+            dep_files = action_dep_files,
+            allow_cache_upload = cxx_compile_cmd.allow_cache_upload,
+            allow_dep_file_cache_upload = False,
+            error_handler = shared_info.error_handler,
+            outputs_for_error_handler = outputs_for_error_handler,
+            local_only = is_producing_compiled_pch or is_consuming_compiled_pch,
+            expect_eligible_for_dedupe = shared_info.expect_eligible_for_dedupe,
+        )
+
+    # Generate asm for compiler which accept `-S` (TODO: support others)
+    if assembly:
+        assembly_cmd = _get_base_compile_cmd(
+            src = src,
+            src_args = src_args,
+            cxx_compile_cmd = cxx_compile_cmd,
+            output_args = ["-S"] + get_output_flags(compiler_type, assembly),
+            shared_args = shared_auxiliary_args,
+        )
+        actions.run(
+            assembly_cmd,
+            category = cxx_compile_cmd.category,
+            identifier = identifier + " (assembly)",
+            allow_cache_upload = cxx_compile_cmd.allow_cache_upload,
+            allow_dep_file_cache_upload = False,
+            error_handler = shared_info.error_handler,
+        )
+
+    if diagnostics:
+        syntax_only_cmd = _get_base_compile_cmd(
+            src = src,
+            src_args = src_args,
+            cxx_compile_cmd = cxx_compile_cmd,
+            output_args = ["-fsyntax-only"],
+            shared_args = shared_auxiliary_args,
+        )
+        diagnostics_dep_files = {}
+        if headers_dep_files:
+            syntax_only_cmd = add_headers_dep_files(
+                actions = actions,
+                cmd = syntax_only_cmd,
+                headers_dep_files = headers_dep_files,
+                src = src,
+                filename_base = "{}.check".format(filename_base),
+                action_dep_files = diagnostics_dep_files,
+            )
+        actions.run(
+            [
+                toolchain.internal_tools.stderr_to_file,
+                cmd_args(diagnostics, format = "--out={}"),
+                syntax_only_cmd,
+            ],
+            category = "check",
+            identifier = short_path,
+            dep_files = diagnostics_dep_files,
+            allow_cache_upload = cxx_compile_cmd.allow_cache_upload,
+            allow_dep_file_cache_upload = False,
+            error_handler = shared_info.error_handler,
+        )
+
+    if clang_tidy_diagnostics:
+        clang_tidy_tool = toolchain.binary_utilities_info.custom_tools["clang-tidy"]
+        actions.run(
+            [
+                toolchain.internal_tools.clang_tidy_wrapper,
+                cmd_args(clang_tidy_diagnostics, format = "--output={}"),
+                cmd_args(clang_tidy_tool, format = "--clang-tidy={}"),
+                cmd_args(src, format = "--source={}"),
+                "--",
+                cxx_compile_cmd.base_compile_cmd,
+                cxx_compile_cmd.argsfile.cmd_form,
+                src_args,
+            ],
+            category = "clang_tidy",
+            identifier = short_path,
+            allow_cache_upload = cxx_compile_cmd.allow_cache_upload,
+            allow_dep_file_cache_upload = False,
+            error_handler = shared_info.error_handler,
+        )
+
+    # Generate pre-processed sources
+    preproc_cmd = _get_base_compile_cmd(
+        src = src,
+        src_args = src_args,
+        cxx_compile_cmd = cxx_compile_cmd,
+        output_args = [COMMON_PREPROCESSOR_OUTPUT_ARGS, get_output_flags(compiler_type, preproc)],
+        shared_args = shared_auxiliary_args,
+    )
+    actions.run(
+        preproc_cmd,
+        category = cxx_compile_cmd.category,
+        identifier = identifier + " (preprocessor)",
+        allow_cache_upload = cxx_compile_cmd.allow_cache_upload,
+        allow_dep_file_cache_upload = False,
+        error_handler = shared_info.error_handler,
+    )
+
+    return cuda_dist_spec
+
+def _get_base_compile_cmd(
+    src: Artifact,
+    src_args: list[typing.Any],
+    cxx_compile_cmd: CxxCompileCommand,
+    shared_args: CxxSharedCompileCommandArgs,
+    output_args: list | None = None,
+    base_compile_cmd_override = None,
+    source_override: str | None = None,
+) -> cmd_args:
+    """
+    Construct a compile command for a single CXX source from its
+    `cxx_compile_cmd`, the extension-shared `shared_args`, and other
+    compilation options.
+    """
+    cmd = cmd_args(base_compile_cmd_override if base_compile_cmd_override != None else cxx_compile_cmd.base_compile_cmd)
+    if output_args:
+        cmd.add(output_args)
+
+    cmd.add(shared_args.before_src)
+
+    if source_override == None:
+        cmd.add(src_args)
+    else:
+        expect(
+            src_args and src_args[-1] == src,
+            "source override requires the source artifact to be the final compile argument",
+        )
+        cmd.add(src_args[:-1])
+        cmd.add(source_override)
+
+    cmd.add(shared_args.after_src)
+
+    return cmd
+
+def _get_shared_compile_command_args(
+    bitcode_args: cmd_args | list,
+    cxx_compile_cmd: CxxCompileCommand,
+    flavors: set[CxxCompileFlavor],
+    flavor_flags: dict[str, list[str]],
+    use_header_units: UseHeaderUnitsMode = UseHeaderUnitsMode("none"),
+    cuda_dryrun: bool = False,
+) -> CxxSharedCompileCommandArgs:
+    before_src = cmd_args()
+
+    if use_header_units == UseHeaderUnitsMode("pcm") and cxx_compile_cmd.header_units_argsfile:
+        before_src.add(cxx_compile_cmd.header_units_argsfile.cmd_form)
+    elif use_header_units == UseHeaderUnitsMode("stub") and cxx_compile_cmd.header_unit_stubs_argsfile:
+        before_src.add(cmd_args(hidden = cxx_compile_cmd.header_unit_stubs_argsfile.file))
+
+    if cuda_dryrun:
+        dryrun_form = cxx_compile_cmd.argsfile.cmd_form_cuda_dryrun
+        expect(dryrun_form != None, "compile argsfile has no CUDA dry-run form")
+        before_src.add(dryrun_form)
+    else:
+        before_src.add(cxx_compile_cmd.argsfile.cmd_form)
+
+    for flavor in flavors:
+        flags = flavor_flags.get(flavor.value)
+        if flags:
+            before_src.add(flags)
+
+    return CxxSharedCompileCommandArgs(
+        before_src = before_src,
+        after_src = cmd_args(bitcode_args),
+    )
+
+def toolchain_supports_flavor(toolchain: CxxToolchainInfo, flavor: CxxCompileFlavor) -> bool:
+    return flavor.value in toolchain.supported_compile_flavors and toolchain.compiler_flavor_flags.get(flavor.value) != None
+
+# Fallback when the toolchain configures no flavor flags at all, for clang and
+# gcc. Ideally this would be a default value in the toolchain definition itself,
+# but it is compiler-dependent so we can't have it there. Module-level so every
+# per-source compile record shares one frozen value instead of allocating a
+# fresh dict+list per TU.
+_DEFAULT_PIC_FLAVOR_FLAGS = {CxxCompileFlavor("pic").value: ["-fPIC"]}
+
+def build_flavor_flags(flavor_flags: dict[str, typing.Any], compiler_type: str) -> dict[str, typing.Any]:
+    if not flavor_flags and compiler_type in ["clang", "gcc"]:
+        return _DEFAULT_PIC_FLAVOR_FLAGS
+
+    return flavor_flags
+
+def _cxx_dynamic_compile(
+    actions: AnalysisActions,
+    label: Label,
+    toolchain: CxxToolchainInfo,
+    bitcode_args: list[str],
+    flavors: list[CxxCompileFlavor],
+    use_header_units: UseHeaderUnitsMode,
+    precompiled_header: Dependency | None,
+    compile_pch: CxxPrecompiledHeader | None,
+    cuda_compile_style: CudaCompileStyle | None,
+    infos: list[CxxCompileInfo],
+    shared_infos: dict[str, CxxSharedCompileInfo],
+    object: list[OutputArtifact],
+    external_debug_info: dict[int, OutputArtifact],
+    clang_remarks: dict[int, OutputArtifact],
+    clang_llvm_statistics: dict[int, OutputArtifact],
+    clang_trace: dict[int, OutputArtifact],
+    gcno_file: dict[int, OutputArtifact],
+    assembly: list[OutputArtifact | None],
+    diagnostics: list[OutputArtifact | None],
+    clang_tidy_diagnostics: dict[int, OutputArtifact],
+    preproc: list[OutputArtifact],
+    index_store: dict[int, OutputArtifact],
+    dist_cuda: dict[int, (OutputArtifact, OutputArtifact, OutputArtifact)],
+    shared_dist_cuda: (OutputArtifact, OutputArtifact, OutputArtifact) | None,
+    pch_object: dict[int, OutputArtifact],
+    json_error: dict[int, OutputArtifact],
+) -> list[Provider]:
+    """
+    DYNAMIC ACTION CALLBACK: The bridge between declaration and execution phases.
+
+    This function is the implementation for Buck2's `dynamic_output_new` API. It runs
+    LAZILY—only when Buck2 determines that one or more of the declared outputs are
+    actually needed by the build. This is the key to memory optimization: action
+    graphs are not materialized until necessary.
+
+    ## How This Fits
+    ```
+    compile_cxx()                          # ANALYSIS PHASE
+        │
+        ├─► for each source file:
+        │       _prepare_cxx_compilation() # Declares outputs (Artifact)
+        │       collect declared artifacts
+        │
+        └─► actions.dynamic_output_new()   # Registers this callback
+                    │
+                    ▼
+            _cxx_dynamic_compile()         # EXECUTION PHASE (called lazily)
+                    │
+                    └─► for each source:
+                            _compile_single_cxx()  # Creates actual actions
+    ```
+
+    ## Why Batched Dynamic Actions?
+    All source files are compiled in a single `dynamic_output_new` call rather than
+    one per source file.
+    """
+    flavors_set = set(flavors)
+    shared_cuda_specs = []
+    shared_cuda_dist_output = None
+    shared_cuda_plan_src_idx = None
+    if shared_dist_cuda != None:
+        shared_cuda_dist_output = CudaDistributedCompileOutput(
+            nvcc_dag = shared_dist_cuda[0].as_input(),
+            nvcc_env = shared_dist_cuda[1].as_input(),
+            hostcc_argsfile = shared_dist_cuda[2].as_input(),
+        )
+    cuda_shared_plan_identifier = _cuda_plan_identifier(flavors_set) if shared_cuda_dist_output != None else None
+    shared_compile_args = {}
+    shared_auxiliary_args = {}
+    shared_dryrun_args = {}
+    for extension, shared_info in shared_infos.items():
+        flavor_flags = build_flavor_flags(toolchain.compiler_flavor_flags, shared_info.cxx_compile_cmd.compiler_type)
+        shared_compile_args[extension] = _get_shared_compile_command_args(
+            bitcode_args = bitcode_args,
+            cxx_compile_cmd = shared_info.cxx_compile_cmd,
+            flavors = flavors_set,
+            flavor_flags = flavor_flags,
+            use_header_units = use_header_units,
+        )
+        shared_auxiliary_args[extension] = _get_shared_compile_command_args(
+            bitcode_args = bitcode_args,
+            cxx_compile_cmd = shared_info.cxx_compile_cmd,
+            flavors = flavors_set,
+            flavor_flags = toolchain.compiler_flavor_flags,
+        )
+        if extension == ".cu" and cuda_compile_style == CudaCompileStyle("dist"):
+            shared_dryrun_args[extension] = _get_shared_compile_command_args(
+                bitcode_args = bitcode_args,
+                cxx_compile_cmd = shared_info.cxx_compile_cmd,
+                flavors = flavors_set,
+                flavor_flags = flavor_flags,
+                use_header_units = use_header_units,
+                cuda_dryrun = True,
+            )
+    for i in range(len(infos)):
+        extension = infos[i].src.extension
+        is_cuda = extension == ".cu"
+
+        # Exactly one prepare action must bind the shared plan outputs. Any
+        # shared CUDA source is a valid representative, since sharing requires
+        # identical plan-affecting args across sources; use the first one.
+        if is_cuda and shared_cuda_dist_output != None and shared_cuda_plan_src_idx == None:
+            shared_cuda_plan_src_idx = i
+        source_dist_cuda = shared_cuda_dist_output if is_cuda else None
+        source_dist_cuda_outputs = dist_cuda.get(i)
+        if source_dist_cuda == None and source_dist_cuda_outputs != None:
+            source_dist_cuda = CudaDistributedCompileOutput(
+                nvcc_dag = source_dist_cuda_outputs[0].as_input(),
+                nvcc_env = source_dist_cuda_outputs[1].as_input(),
+                hostcc_argsfile = source_dist_cuda_outputs[2].as_input(),
+            )
+        prepare_cuda_dist = source_dist_cuda != None and (shared_cuda_dist_output == None or i == shared_cuda_plan_src_idx)
+        cuda_dist_spec = _compile_single_cxx(
+            actions = actions,
+            label = label,
+            toolchain = toolchain,
+            flavors = flavors_set,
+            compile_pch = compile_pch,
+            precompiled_header = precompiled_header,
+            cuda_compile_style = cuda_compile_style,
+            info = infos[i],
+            shared_info = shared_infos[extension],
+            object = object[i],
+            external_debug_info = external_debug_info.get(i),
+            clang_remarks = clang_remarks.get(i),
+            clang_llvm_statistics = clang_llvm_statistics.get(i),
+            clang_trace = clang_trace.get(i),
+            gcno_file = gcno_file.get(i),
+            assembly = assembly[i],
+            diagnostics = diagnostics[i],
+            clang_tidy_diagnostics = clang_tidy_diagnostics.get(i),
+            preproc = preproc[i],
+            index_store = index_store.get(i),
+            dist_cuda = source_dist_cuda,
+            prepare_cuda_dist = prepare_cuda_dist,
+            cuda_shared_plan_identifier = cuda_shared_plan_identifier,
+            shared_compile_args = shared_compile_args[extension],
+            shared_auxiliary_args = shared_auxiliary_args[extension],
+            shared_dryrun_args = shared_dryrun_args.get(extension),
+            pch_object = pch_object.get(i),
+            json_error = json_error.get(i),
+        )
+        if cuda_dist_spec != None:
+            if shared_cuda_dist_output != None:
+                shared_cuda_specs.append(cuda_dist_spec)
+            else:
+                cxx_compile_cmd = shared_infos[extension].cxx_compile_cmd
+                create_cuda_distributed_compiles(
+                    actions,
+                    toolchain,
+                    source_dist_cuda,
+                    [cuda_dist_spec],
+                    cxx_compile_cmd.allow_cache_upload,
+                    # The argsfile closure carries the file-prefix specs file
+                    # that replayed host compiles reference by path.
+                    cmd_args(cxx_compile_cmd.base_compile_cmd, hidden = cxx_compile_cmd.argsfile.cmd_form),
+                    cxx_compile_cmd.headers_dep_files,
+                )
+
+    if shared_cuda_specs:
+        cxx_compile_cmd = shared_infos[".cu"].cxx_compile_cmd
+        expect(
+            shared_cuda_plan_src_idx != None,
+            "shared CUDA plan outputs were declared but no .cu source is present to bind them",
+        )
+        create_cuda_distributed_compiles(
+            actions,
+            toolchain,
+            shared_cuda_dist_output,
+            shared_cuda_specs,
+            cxx_compile_cmd.allow_cache_upload,
+            cmd_args(cxx_compile_cmd.base_compile_cmd, hidden = cxx_compile_cmd.argsfile.cmd_form),
+            cxx_compile_cmd.headers_dep_files,
+        )
+
+    return [EMPTY_DEFAULT_INFO]
+
+# https://buck2.build/docs/api/build/AnalysisActions/#analysisactionsdynamic_output_new
+# Dynamic actions factory for batch CXX compilation
+_dynamic_compile_rule = dynamic_actions(
+    impl = _cxx_dynamic_compile,
+    attrs = {
+        "assembly": dynattrs.list(dynattrs.option(dynattrs.output())),
+        "bitcode_args": dynattrs.value(list[str]),
+        "clang_llvm_statistics": dynattrs.dict(int, dynattrs.output()),
+        "clang_remarks": dynattrs.dict(int, dynattrs.output()),
+        "clang_tidy_diagnostics": dynattrs.dict(int, dynattrs.output()),
+        "clang_trace": dynattrs.dict(int, dynattrs.output()),
+        "compile_pch": dynattrs.option(dynattrs.value(CxxPrecompiledHeader)),
+        "cuda_compile_style": dynattrs.option(dynattrs.value(CudaCompileStyle)),
+        "diagnostics": dynattrs.list(dynattrs.option(dynattrs.output())),
+        "dist_cuda": dynattrs.dict(int, dynattrs.tuple(dynattrs.output(), dynattrs.output(), dynattrs.output())),
+        "external_debug_info": dynattrs.dict(int, dynattrs.output()),
+        "flavors": dynattrs.value(list[CxxCompileFlavor]),
+        "gcno_file": dynattrs.dict(int, dynattrs.output()),
+        "index_store": dynattrs.dict(int, dynattrs.output()),
+        "infos": dynattrs.value(list[CxxCompileInfo]),
+        "json_error": dynattrs.dict(int, dynattrs.output()),
+        "label": dynattrs.value(Label),
+        "object": dynattrs.list(dynattrs.output()),
+        "pch_object": dynattrs.dict(int, dynattrs.output()),
+        "precompiled_header": dynattrs.option(dynattrs.value(Dependency)),
+        "preproc": dynattrs.list(dynattrs.output()),
+        "shared_dist_cuda": dynattrs.option(dynattrs.tuple(dynattrs.output(), dynattrs.output(), dynattrs.output())),
+        "shared_infos": dynattrs.dict(str, dynattrs.value(CxxSharedCompileInfo)),
+        "toolchain": dynattrs.value(CxxToolchainInfo),
+        "use_header_units": dynattrs.value(UseHeaderUnitsMode),
+    },
+)
+
+def _cuda_plan_flavor(flavors: set[CxxCompileFlavor]) -> str:
+    return ".".join(sorted([flavor.value for flavor in flavors])) or "default"
+
+def _cuda_plan_identifier(flavors: set[CxxCompileFlavor]) -> str:
+    return "cuda_compile_plan ({})".format(_cuda_plan_flavor(flavors))
+
+def maybe_get_shared_cuda_dist_output(
+    actions: AnalysisActions,
+    src_compile_cmds: list[CxxSrcCompileCommand],
+    cuda_compile_style: CudaCompileStyle | None,
+    flavors: set[CxxCompileFlavor],
+) -> CudaDistributedCompileOutput | None:
+    cuda_src_compile_cmds = [cmd for cmd in src_compile_cmds if cmd.src.extension == ".cu"]
+    if cuda_compile_style != CudaCompileStyle("dist") or not cuda_src_compile_cmds:
+        return None
+
+    for cmd in cuda_src_compile_cmds:
+        # Same-extension sources already share one `cxx_compile_cmd`, so per-source
+        # args, duplicate-basename disambiguation (`index`), and path style are the
+        # only sharing hazards.
+        # create_compile_cmds appends source flags before "-c" and the source artifact.
+        # Only commands with no source-specific flags can share an NVCC plan.
+        if len(cmd.args) != 2 or cmd.args[0] != "-c" or cmd.args[1] != cmd.src or cmd.index != None:
+            return None
+        if cmd.uses_content_based_paths != cuda_src_compile_cmds[0].uses_content_based_paths:
+            return None
+
+    # Plan outputs are named per flavor set: callers invoke compile_cxx at most
+    # once per flavor set within a target, and a collision fails analysis loudly.
+    cuda_plan_flavor = _cuda_plan_flavor(flavors)
+    return declare_cuda_dist_compile_output(
+        actions,
+        CudaCompileInfo(
+            filename = "cuda_compile_plan.{}".format(cuda_plan_flavor),
+            identifier = _cuda_plan_identifier(flavors),
+            output_prefix = _OBJECTS_FOLDER,
+            uses_content_based_paths = cuda_src_compile_cmds[0].uses_content_based_paths,
+        ),
+    )
+
+def compile_cxx(
+    actions: AnalysisActions,
+    target_label: Label,
+    toolchain: CxxToolchainInfo,
+    src_compile_cmds: list[CxxSrcCompileCommand],
+    flavors: set[CxxCompileFlavor],
+    provide_syntax_only: bool,
+    separate_debug_info: bool,
+    use_header_units: UseHeaderUnitsMode = UseHeaderUnitsMode("none"),
+    precompiled_header: Dependency | None = None,
+    cuda_compile_style: CudaCompileStyle | None = None,
+    compile_pch: CxxPrecompiledHeader | None = None,
+) -> list[CxxCompileOutput]:
+    """
+    MAIN ENTRY POINT: Compiles a list of C/C++ source files.
+
+    This function implements a two-phases that separates output
+    declaration (analysis phase) from action creation (execution phase).
+    """
+    linker_info = toolchain.linker_info
+
+    # Resolve the output format, which is a tristate of native (default being mach-o/elf/pe)
+    # bitcode (being LLVM-IR, which is also produced if any link time optimization flags are
+    # enabled) or the third hybrid state where the bitcode is embedded into a section of the
+    # native code, allowing the file to be used as either (but at twice the size)
+    default_object_format = toolchain.object_format or CxxObjectFormat("native")
+    bitcode_args = []
+    if linker_info.lto_mode == LtoMode("none"):
+        if toolchain.object_format == CxxObjectFormat("bitcode"):
+            bitcode_args.append("-emit-llvm")
+            default_object_format = CxxObjectFormat("bitcode")
+        elif toolchain.object_format == CxxObjectFormat("embedded-bitcode"):
+            bitcode_args.append("-fembed-bitcode")
+            default_object_format = CxxObjectFormat("embedded-bitcode")
+    else:
+        # LTO always produces bitcode object in any mode (thin, full, etc)
+        default_object_format = CxxObjectFormat("bitcode")
+
+    objects = []
+
+    # Dynamic action inputs
+    infos = []
+    object_outputs = []
+    external_debug_info_outputs = {}
+    clang_remarks_outputs = {}
+    clang_llvm_statistics_outputs = {}
+    clang_trace_outputs = {}
+    gcno_file_outputs = {}
+    assembly_outputs = []
+    diagnostics_outputs = []
+    clang_tidy_diagnostics_outputs = {}
+    preproc_outputs = []
+    index_store_outputs = {}
+    dist_cuda_outputs = {}
+    pch_object_outputs = {}
+    json_error_outputs = {}
+    shared_infos = {}
+
+    for src_compile_cmd in src_compile_cmds:
+        extension = src_compile_cmd.src.extension
+        shared_info = shared_infos.get(extension)
+        if shared_info == None:
+            shared_infos[extension] = CxxSharedCompileInfo(
+                cxx_compile_cmd = src_compile_cmd.cxx_compile_cmd,
+                index_store_factory = src_compile_cmd.index_store_factory,
+                error_handler = src_compile_cmd.error_handler,
+                expect_eligible_for_dedupe = src_compile_cmd.expect_eligible_for_dedupe,
+            )
+        else:
+            expect(
+                src_compile_cmd.cxx_compile_cmd == shared_info.cxx_compile_cmd
+                and src_compile_cmd.index_store_factory == shared_info.index_store_factory
+                and src_compile_cmd.error_handler == shared_info.error_handler
+                and src_compile_cmd.expect_eligible_for_dedupe == shared_info.expect_eligible_for_dedupe,
+                "sources with the same extension must share compile command inputs",
+            )
+
+    shared_cuda_dist_output = maybe_get_shared_cuda_dist_output(
+        actions,
+        src_compile_cmds,
+        cuda_compile_style,
+        flavors,
+    )
+
+    for source_index, src_compile_cmd in enumerate(src_compile_cmds):
+        cxx_compile_input = _prepare_cxx_compilation(
+            actions = actions,
+            toolchain = toolchain,
+            default_object_format = default_object_format,
+            src_compile_cmd = src_compile_cmd,
+            flavors = flavors,
+            provide_syntax_only = provide_syntax_only,
+            use_header_units = use_header_units,
+            separate_debug_info = separate_debug_info,
+            cuda_compile_style = cuda_compile_style,
+            shared_cuda_dist_output = shared_cuda_dist_output,
+            compile_pch = compile_pch,
+        )
+
+        # Collect info (metadata without artifacts)
+        infos.append(cxx_compile_input.info)
+
+        # Collect outputs - call .as_output() on each artifact
+        declared = cxx_compile_input.declared_artifacts
+        object_outputs.append(declared.object.as_output())
+        if declared.external_debug_info:
+            external_debug_info_outputs[source_index] = declared.external_debug_info.as_output()
+        if declared.clang_remarks:
+            clang_remarks_outputs[source_index] = declared.clang_remarks.as_output()
+        if declared.clang_llvm_statistics:
+            clang_llvm_statistics_outputs[source_index] = declared.clang_llvm_statistics.as_output()
+        if declared.clang_trace:
+            clang_trace_outputs[source_index] = declared.clang_trace.as_output()
+        if declared.gcno_file:
+            gcno_file_outputs[source_index] = declared.gcno_file.as_output()
+        assembly_outputs.append(map_val(as_output, declared.assembly))
+        diagnostics_outputs.append(map_val(as_output, declared.diagnostics))
+        if declared.clang_tidy_diagnostics:
+            clang_tidy_diagnostics_outputs[source_index] = declared.clang_tidy_diagnostics.as_output()
+        preproc_outputs.append(declared.preproc.as_output())
+        if declared.index_store:
+            index_store_outputs[source_index] = declared.index_store.as_output()
+        if shared_cuda_dist_output == None and declared.dist_cuda:
+            dist_cuda_outputs[source_index] = (
+                declared.dist_cuda.nvcc_dag.as_output(),
+                declared.dist_cuda.nvcc_env.as_output(),
+                declared.dist_cuda.hostcc_argsfile.as_output(),
+            )
+        if declared.pch_object:
+            pch_object_outputs[source_index] = declared.pch_object.as_output()
+        if declared.json_error:
+            json_error_outputs[source_index] = declared.json_error.as_output()
+
+        objects.append(declared)
+
+    actions.dynamic_output_new(
+        _dynamic_compile_rule(
+            assembly = assembly_outputs,
+            bitcode_args = bitcode_args,
+            clang_llvm_statistics = clang_llvm_statistics_outputs,
+            clang_remarks = clang_remarks_outputs,
+            clang_tidy_diagnostics = clang_tidy_diagnostics_outputs,
+            clang_trace = clang_trace_outputs,
+            compile_pch = compile_pch,
+            cuda_compile_style = cuda_compile_style,
+            diagnostics = diagnostics_outputs,
+            dist_cuda = dist_cuda_outputs,
+            external_debug_info = external_debug_info_outputs,
+            flavors = list(flavors),
+            gcno_file = gcno_file_outputs,
+            index_store = index_store_outputs,
+            infos = infos,
+            json_error = json_error_outputs,
+            label = target_label,
+            object = object_outputs,
+            pch_object = pch_object_outputs,
+            precompiled_header = precompiled_header,
+            preproc = preproc_outputs,
+            shared_dist_cuda = map_val(lambda d: (d.nvcc_dag.as_output(), d.nvcc_env.as_output(), d.hostcc_argsfile.as_output()), shared_cuda_dist_output),
+            shared_infos = shared_infos,
+            toolchain = toolchain,
+            use_header_units = use_header_units,
+        )
+    )
+
+    # Strip per-arch device DWARF from each .hip TU's `.o` into
+    # sidecars. Replaces `.object` with the stripped artifact; downstream
+    # linker concatenates the stripped bundles into the final
+    # `.hip_fatbin`.
+    if hip_debug_extract_available(toolchain):
+        processed = []
+        for i, out in enumerate(objects):
+            if out.hip_device_debug:
+                hip_outs = hip_debug_extract_compile_object(
+                    actions = actions,
+                    toolchain = toolchain,
+                    obj = out.object,
+                    identifier = infos[i].identifier,
+                )
+                processed.append(
+                    CxxCompileOutput(
+                        object = hip_outs.patched_output,
+                        object_format = out.object_format,
+                        object_has_external_debug_info = out.object_has_external_debug_info,
+                        external_debug_info = out.external_debug_info,
+                        clang_remarks = out.clang_remarks,
+                        clang_llvm_statistics = out.clang_llvm_statistics,
+                        clang_trace = out.clang_trace,
+                        gcno_file = out.gcno_file,
+                        index_store = out.index_store,
+                        assembly = out.assembly,
+                        diagnostics = out.diagnostics,
+                        clang_tidy_diagnostics = out.clang_tidy_diagnostics,
+                        preproc = out.preproc,
+                        dist_cuda = out.dist_cuda,
+                        pch_object = out.pch_object,
+                        json_error = out.json_error,
+                        hip_device_debug = out.hip_device_debug,
+                        hip_arch_debug_files = hip_outs.arch_debug_files,
+                    )
+                )
+            else:
+                processed.append(out)
+        return processed
+
+    return objects
+
+def _compiler_supports_header_units(compiler_info: typing.Any):
+    return "clang" in compiler_info.compiler_type and compiler_info.supports_two_phase_compilation
+
+def _get_module_name(target_label: Label, group_name: str) -> str:
+    return paths.normalize(
+        paths.join(
+            "__header_units__",
+            target_label.package,
+            "{}{}.h".format(target_label.name, group_name),
+        )
+    )
+
+def _get_import_filename(target_label: Label, group_name: str) -> str:
+    return paths.normalize(
+        paths.join(
+            target_label.package,
+            "__import__{}{}.h".format(target_label.name, group_name),
+        )
+    )
+
+def _is_standalone_header(header: CHeader) -> bool:
+    if header.artifact.extension not in HeaderExtension.values():
+        return False
+    if header.name.endswith("-inl.h") or header.name.endswith("-inl.hpp"):
+        return False
+    if header.name.endswith(".tcc"):
+        return False
+    if header.name.endswith("-pre.h") or header.name.endswith("-pre.hpp"):
+        return False
+    if header.name.endswith("-post.h") or header.name.endswith("-post.hpp"):
+        return False
+    return True
+
+def _convert_raw_header(target_label: Label, raw_header: Artifact, include_dirs: list[CellPath]) -> CHeader:
+    full_path = str(target_label.path) + "/" + raw_header.short_path
+    best_dir = None
+    for d in include_dirs:
+        abs_dir = str(d)
+        if paths.starts_with(full_path, abs_dir) and (best_dir == None or len(abs_dir) > len(best_dir)):
+            best_dir = abs_dir
+    if best_dir != None:
+        ns = paths.dirname(paths.relativize(full_path, best_dir))
+    else:
+        ns = paths.dirname(raw_header.short_path)
+    return CHeader(
+        artifact = raw_header,
+        name = raw_header.basename,
+        namespace = ns,
+        named = False,
+    )
+
+def _get_raw_header_include_dirs(preprocessors: list[CPreprocessor]) -> list[CellPath]:
+    return flatten([x.include_dirs for x in preprocessors]) + flatten(
+        [x.system_include_dirs.include_dirs for x in preprocessors if x.system_include_dirs != None]
+    )
+
+def _create_precompile_cmd(
+    actions: AnalysisActions,
+    target_label: Label,
+    compiler_info: typing.Any,
+    preprocessors: list[CPreprocessor],
+    header_group: str | None,
+    group_name: str,
+    extra_preprocessors: list[CPreprocessor],
+    cmd: CxxCompileCommand,
+) -> CxxSrcPrecompileCommand:
+    include_dirs = _get_raw_header_include_dirs(preprocessors)
+    converted_headers = [_convert_raw_header(target_label, raw_header, include_dirs) for raw_header in flatten([x.raw_headers for x in preprocessors])]
+    header_group_regex = regex(header_group, fancy = False) if header_group else None
+
+    header_paths = [
+        paths.normalize(paths.join(header.namespace, header.name))
+        for header in flatten([x.headers for x in preprocessors]) + converted_headers
+        if (_is_standalone_header(header) if header_group_regex == None else header_group_regex.match(header.name))
+    ]
+
+    input_header_contents = cmd_args(header_paths, format = '#include "{}"')
+
+    module_name = _get_module_name(target_label, group_name)
+    import_name = _get_import_filename(target_label, group_name)
+
+    input_header = actions.write(
+        module_name,
+        cmd_args(input_header_contents, cmd_args(["\n"])),
+        has_content_based_path = True,
+    )
+
+    import_stub = actions.write(
+        import_name,
+        """
+#ifdef FACEBOOK_CPP_HEADER_UNIT
+export
+#endif
+import \"{}\";
+""".format(module_name),
+        has_content_based_path = True,
+    )
+
+    symlinked_files = {}
+    for path in header_paths:
+        symlinked_files[path] = import_stub
+
+    modulemap_content = """
+module "{}" {{
+  header "{}"
+  export *
+}}
+""".format(module_name, module_name)
+    modulemap_file = actions.write(
+        "module.modulemap" + group_name,
+        modulemap_content,
+        has_content_based_path = True,
+    )
+
+    src_dir = actions.symlinked_dir(
+        "header-unit" + group_name,
+        symlinked_files
+        | {
+            module_name: input_header,
+            import_name: import_stub,
+            "module.modulemap": modulemap_file,
+        },
+        has_content_based_path = True,
+    )
+
+    args = []
+    args.extend([
+        # TODO(nml): Fix warning bugs.
+        "-Wno-uninitialized",
+        "-Wno-conversion",
+        "-Wno-zero-as-null-pointer-constant",
+        "-Wno-c++98-compat-extra-semi",
+    ])
+
+    extra_argsfile = None
+    if extra_preprocessors:
+        extra_argsfile = _mk_header_units_argsfile(
+            actions = actions,
+            compiler_info = compiler_info,
+            preprocessor = cxx_merge_cpreprocessors(actions, extra_preprocessors, []),
+            ext = CxxExtension(".cpp"),
+            has_content_based_path = True,
+            filename_prefix = "export{}_".format(group_name),
+        )
+
+    args.extend(["-xc++-user-header", "-fmodule-header"])
+    args.extend(["-fmodule-name={}".format(module_name)])
+    args.extend(["-Xclang", "-fmodule-file-home-is-cwd"])
+
+    # check_args: same setup but -fsyntax-only instead of --precompile, and
+    # without -DFACEBOOK_CPP_HEADER_UNIT=1 (the `export` keyword in import
+    # stubs is only valid inside module purview set up by --precompile).
+    check_args = list(args)
+
+    args.extend(["-Xclang", cmd_args(input_header, format = "-fmodules-embed-file={}")])
+    args.extend(["-DFACEBOOK_CPP_HEADER_UNIT=1", "--precompile", input_header])
+
+    check_args.extend(["-fsyntax-only", input_header])
+
+    return CxxSrcPrecompileCommand(
+        src = src_dir,
+        cxx_compile_cmd = cmd,
+        args = args,
+        check_args = check_args,
+        extra_argsfile = extra_argsfile,
+    )
+
+def _precompile_single_cxx(
+    actions: AnalysisActions,
+    target_label: Label,
+    toolchain: CxxToolchainInfo,
+    impl_params: CxxRuleConstructorParams,
+    group_name: str,
+    src_compile_cmd: CxxSrcPrecompileCommand,
+) -> HeaderUnit:
+    identifier = src_compile_cmd.src.short_path
+    cxx_cmd = src_compile_cmd.cxx_compile_cmd
+
+    filename = "{}.pcm".format(identifier)
+    module = actions.declare_output(
+        "__pcm_files__",
+        filename,
+        has_content_based_path = True,
+    )
+
+    # Declare stub artifact
+    stub_filename = "{}.pcm.stub".format(identifier)
+    stub = actions.declare_output(
+        "__pcm_files__",
+        stub_filename,
+        has_content_based_path = True,
+    )
+
+    # Build actual header units
+    # TODO(nml): We don't meaningfully support dep files. See T225373444.
+    cmd = cmd_args(cxx_cmd.base_compile_cmd)
+    if cxx_cmd.header_units_argsfile:
+        cmd.add(cxx_cmd.header_units_argsfile.cmd_form)
+    if src_compile_cmd.extra_argsfile:
+        cmd.add(src_compile_cmd.extra_argsfile.cmd_form)
+    cmd.add(cxx_cmd.argsfile.cmd_form)
+    cmd.add(src_compile_cmd.args)
+    cmd.add("-o", module.as_output())
+
+    clang_trace = None
+    if toolchain.clang_trace and toolchain.cxx_compiler_info.compiler_type == "clang":
+        clang_trace = actions.declare_output(
+            paths.join("__pcm_files__", "{}.json".format(identifier)),
+            has_content_based_path = True,
+        )
+        cmd.add(cmd_args("-ftime-trace", hidden = clang_trace.as_output()))
+
+    actions.run(
+        cmd,
+        category = "cxx_modules_precompile",
+        identifier = identifier,
+        allow_cache_upload = cxx_cmd.allow_cache_upload,
+        low_pass_filter = False,
+    )
+
+    # Diagnostics: run -fsyntax-only variant for [check] subtarget.
+    # This is cheaper than --precompile because it skips module serialization.
+    # We must remove -DFACEBOOK_CPP_HEADER_UNIT=1 because that macro gates
+    # `export` keywords in import stubs, which are only valid inside module
+    # purview (set up by --precompile but not -fsyntax-only).
+    diagnostics = None
+    if cxx_cmd.compiler_type == "clang":
+        diagnostics = actions.declare_output(
+            "__diagnostics__",
+            "{}.header-unit.diag.txt".format(identifier),
+            has_content_based_path = False,
+        )
+        check_cmd = cmd_args(cxx_cmd.base_compile_cmd)
+        if cxx_cmd.header_units_argsfile:
+            check_cmd.add(cxx_cmd.header_units_argsfile.cmd_form)
+        if src_compile_cmd.extra_argsfile:
+            check_cmd.add(src_compile_cmd.extra_argsfile.cmd_form)
+        check_cmd.add(cxx_cmd.argsfile.cmd_form)
+
+        # Add all precompile args except --precompile and -DFACEBOOK_CPP_HEADER_UNIT=1
+        check_cmd.add(src_compile_cmd.check_args)
+        actions.run(
+            [
+                toolchain.internal_tools.stderr_to_file,
+                cmd_args(diagnostics.as_output(), format = "--out={}"),
+                check_cmd,
+            ],
+            category = "check",
+            identifier = identifier + " (header-unit)",
+            allow_cache_upload = cxx_cmd.allow_cache_upload,
+            low_pass_filter = False,
+        )
+
+    # Build the stub artifact using the stub_header_unit tool
+    stub_cmd = cmd_args(toolchain.internal_tools.stub_header_unit)
+    stub_cmd.add(cxx_cmd.base_compile_cmd)
+    if cxx_cmd.header_unit_stubs_argsfile:
+        stub_cmd.add(cmd_args(hidden = cxx_cmd.header_unit_stubs_argsfile.file))
+    stub_cmd.add(cxx_cmd.argsfile.cmd_form)
+    stub_cmd.add(src_compile_cmd.args)
+    stub_cmd.add("-o", stub.as_output())
+
+    actions.run(
+        stub_cmd,
+        category = "cxx_modules_precompile_stub",
+        identifier = identifier,
+        allow_cache_upload = cxx_cmd.allow_cache_upload,
+        low_pass_filter = False,
+    )
+
+    return HeaderUnit(
+        name = _get_module_name(target_label, group_name),
+        module = module,
+        stub = stub,
+        include_dir = src_compile_cmd.src,
+        import_include = _get_import_filename(target_label, group_name) if impl_params.export_header_unit == "preload" else None,
+        clang_trace = clang_trace,
+        diagnostics = diagnostics,
+    )
+
+def precompile_cxx(
+    actions: AnalysisActions,
+    target_label: Label,
+    toolchain: CxxToolchainInfo,
+    impl_params: CxxRuleConstructorParams,
+    preprocessors: list[CPreprocessor],
+    header_preprocessor_info: CPreprocessorInfo,
+) -> list[CPreprocessor]:
+    """
+    Produces header units for the target and returns a list of preprocessors enabling
+    them; depending on those preprocessors will allow the corresponding module to load.
+    """
+    compiler_info = toolchain.cxx_compiler_info
+    if not _compiler_supports_header_units(compiler_info):
+        return []
+
+    def mk_base_cmd():
+        base_compile_cmd = _get_compile_base(toolchain, compiler_info, use_wrapper = True)
+        ext = CxxExtension(".cpp")
+        headers_tag = actions.artifact_tag()  # Currently ignored
+        argsfile = _mk_argsfiles(
+            actions,
+            target_label,
+            impl_params,
+            compiler_info,
+            header_preprocessor_info,
+            ext,
+            headers_tag,
+            is_xcode_argsfile = False,
+            is_precompile = True,
+            uses_content_based_paths = True,
+            filename_prefix = "pre_",
+        )
+        header_units_argsfile = _mk_header_units_argsfile(
+            actions,
+            compiler_info,
+            header_preprocessor_info,
+            ext,
+            has_content_based_path = True,
+            filename_prefix = "pre_",
+            stub = False,
+        )
+        header_unit_stubs_argsfile = _mk_header_units_argsfile(
+            actions,
+            compiler_info,
+            header_preprocessor_info,
+            ext,
+            has_content_based_path = True,
+            filename_prefix = "pre_",
+            stub = True,
+        )
+        return CxxCompileCommand(
+            base_compile_cmd = base_compile_cmd,
+            argsfile = argsfile,
+            xcode_argsfile = argsfile,  # Unused
+            header_units_argsfile = header_units_argsfile,
+            header_unit_stubs_argsfile = header_unit_stubs_argsfile,
+            headers_dep_files = None,
+            compiler_type = compiler_info.compiler_type,
+            category = "cxx_modules_precompile",
+            allow_cache_upload = impl_params.allow_cache_upload,
+            allow_content_based_paths = True,  # Unused: we always use content-based paths for precompile
+        )
+
+    cmd = mk_base_cmd()
+
+    header_unit_preprocessors = []
+    if len(impl_params.export_header_unit_filter) <= 1:
+        group = None
+        if impl_params.export_header_unit_filter:
+            group = impl_params.export_header_unit_filter[0]
+        precompile_cmd = _create_precompile_cmd(
+            actions = actions,
+            target_label = target_label,
+            compiler_info = toolchain.cxx_compiler_info,
+            preprocessors = preprocessors,
+            header_group = group,
+            group_name = "",
+            extra_preprocessors = [],
+            cmd = cmd,
+        )
+        header_unit = _precompile_single_cxx(actions, target_label, toolchain, impl_params, "", precompile_cmd)
+        header_unit_preprocessors.append(CPreprocessor(header_units = [header_unit]))
+    else:
+        # Chain preprocessors in order.
+        i = 0
+        for header_group in impl_params.export_header_unit_filter:
+            name = ".{}".format(i)
+            precompile_cmd = _create_precompile_cmd(
+                actions = actions,
+                target_label = target_label,
+                compiler_info = toolchain.cxx_compiler_info,
+                preprocessors = preprocessors,
+                header_group = header_group,
+                group_name = name,
+                extra_preprocessors = header_unit_preprocessors,
+                cmd = cmd,
+            )
+            header_unit = _precompile_single_cxx(actions, target_label, toolchain, impl_params, name, precompile_cmd)
+            header_unit_preprocessors.append(CPreprocessor(header_units = [header_unit]))
+            i += 1
+
+    return header_unit_preprocessors
+
+def cxx_objects_sub_targets(outs: list[CxxCompileOutput]) -> dict[str, list[Provider]]:
+    objects_sub_targets = {}
+    for obj in outs:
+        sub_targets = {}
+        if obj.clang_trace:
+            sub_targets["clang-trace"] = [DefaultInfo(obj.clang_trace)]
+        if obj.clang_remarks:
+            sub_targets["clang-remarks"] = [DefaultInfo(obj.clang_remarks)]
+        if obj.clang_llvm_statistics:
+            sub_targets["clang-llvm-statistics"] = [DefaultInfo(obj.clang_llvm_statistics)]
+        if obj.assembly:
+            sub_targets["assembly"] = [DefaultInfo(obj.assembly)]
+        if obj.preproc:
+            sub_targets["preprocessed"] = [DefaultInfo(obj.preproc)]
+        if obj.dist_cuda:
+            sub_targets["nvcc-dag"] = [DefaultInfo(obj.dist_cuda.nvcc_dag)]
+            sub_targets["nvcc-env"] = [DefaultInfo(obj.dist_cuda.nvcc_env)]
+        objects_sub_targets[obj.object.short_path] = [
+            DefaultInfo(
+                obj.object,
+                sub_targets = sub_targets,
+            )
+        ]
+    return objects_sub_targets
+
+def _validate_target_headers(label: Label, preprocessor: list[CPreprocessor]):
+    path_to_artifact = {}
+    all_headers = flatten([x.headers for x in preprocessor])
+    for header in all_headers:
+        header_path = paths.join(header.namespace, header.name)
+        artifact = path_to_artifact.get(header_path)
+        if artifact != None:
+            if artifact != header.artifact:
+                fail("Conflicting headers {} and {} map to {} in target {}".format(artifact, header.artifact, header_path, label))
+        else:
+            path_to_artifact[header_path] = header.artifact
+
+def _get_compiler_info(toolchain: CxxToolchainInfo, ext: CxxExtension) -> typing.Any:
+    compiler_info = None
+    if ext.value in (".cpp", ".cc", ".cl", ".cxx", ".c++", ".h", ".hpp", ".hh", ".h++", ".hxx", ".bc"):
+        compiler_info = toolchain.cxx_compiler_info
+    elif ext.value == ".c":
+        compiler_info = toolchain.c_compiler_info
+    elif ext.value == ".m":
+        compiler_info = toolchain.objc_compiler_info
+    elif ext.value == ".mm":
+        compiler_info = toolchain.objcxx_compiler_info
+    elif ext.value in (".s", ".sx", ".S"):
+        compiler_info = toolchain.as_compiler_info
+    elif ext.value == ".cu":
+        compiler_info = toolchain.cuda_compiler_info
+    elif ext.value == ".hip":
+        compiler_info = toolchain.hip_compiler_info
+    elif ext.value in (".asm", ".asmpp"):
+        compiler_info = toolchain.asm_compiler_info
+    else:
+        # This should be unreachable as long as we handle all enum values
+        fail("Unknown C++ extension: " + ext.value)
+
+    if not compiler_info:
+        fail("Could not find compiler for extension `{ext}`".format(ext = ext.value))
+
+    return compiler_info
+
+def _get_category(ext: CxxExtension) -> str:
+    if ext.value in (".cpp", ".cc", ".cl", ".cxx", ".c++", ".h", ".hpp", ".hh", ".h++", ".hxx"):
+        return "cxx_compile"
+    if ext.value == ".c":
+        return "c_compile"
+    if ext.value == ".m":
+        return "objc_compile"
+    if ext.value == ".mm":
+        return "objcxx_compile"
+    elif ext.value in (".s", ".sx", ".S", ".asm", ".asmpp"):
+        return "asm_compile"
+    elif ext.value == ".cu":
+        return "cuda_compile"
+    elif ext.value == ".hip":
+        return "hip_compile"
+    elif ext.value == ".bc":
+        return "bitcode_compile"
+    else:
+        # This should be unreachable as long as we handle all enum values
+        fail("Unknown extension: " + ext.value)
+
+def _get_compile_base(toolchain: CxxToolchainInfo, compiler_info: typing.Any, use_wrapper, compiler_override = None) -> cmd_args:
+    """
+    Given a compiler info returned by _get_compiler_info, form the base compile args.
+
+    `compiler_override` substitutes the compiler executable while keeping the
+    toolchain-level wrapping (e.g. cwd remapping) that all compiles of this
+    compiler type must run under.
+    """
+    if compiler_override != None:
+        compiler = compiler_override
+    else:
+        compiler = compiler_info.compiler_with_wrapper if compiler_info.compiler_with_wrapper and use_wrapper else compiler_info.compiler
+
+    if toolchain.remap_cwd and compiler_info.compiler_type in ["clang", "clang_windows", "clang_cl", "gcc"]:
+        return cmd_args(toolchain.internal_tools.remap_cwd, compiler)
+    else:
+        return cmd_args(compiler)
+
+def _dep_file_type(ext: CxxExtension) -> [DepFileType, None]:
+    # Raw assembly doesn't make sense to capture dep files for.
+    # .S is preprocessed assembly, but some builds use it with
+    # assemblers that don't support -MF, so leave depfiles off.
+    if ext.value in (".s", ".S", ".asm"):
+        return None
+    elif ext.value == ".hip":
+        # TODO (T118797886): HipCompilerInfo doesn't have dep files processor.
+        # Should it?
+        return None
+    elif ext.value == ".bc":
+        # Bitcode doesn't have depfiles
+        return None
+
+    # Return the file type as well
+    if ext.value in (".cpp", ".cc", ".cl", ".mm", ".cxx", ".c++", ".h", ".hpp", ".hh", ".h++", ".hxx"):
+        return DepFileType("cpp")
+    elif ext.value in (".c", ".m"):
+        return DepFileType("c")
+    elif ext.value == ".cu":
+        return DepFileType("cuda")
+    elif ext.value in (".asmpp", ".sx"):
+        return DepFileType("asm")
+    else:
+        # This should be unreachable as long as we handle all enum values
+        fail("Unknown C++ extension: " + ext.value)
+
+def _add_compiler_info_flags(compiler_info: typing.Any) -> list:
+    cmd = []
+    cmd.append(compiler_info.preprocessor_flags or [])
+    cmd.append(compiler_info.compiler_flags or [])
+
+    return cmd
+
+def mk_toolchain_precompile_argsfile(actions: AnalysisActions, name: str, argsfile: cmd_args, filter_argsfile: RunInfo) -> cmd_args:
+    """
+    Copy a toolchain argsfile with flags that are invalid for C++20 module
+    precompilation filtered out. One filter action per toolchain, run only if
+    a precompile demands it. `argsfile` is an `argsfile_with_artifacts()`
+    value; the filtered copy carries everything the original carried.
+    """
+    filtered = actions.declare_output(name + "_toolchain_args_precompile", has_content_based_path = True)
+    actions.run(
+        [filter_argsfile, _PRECOMPILE_OPTION_IGNORE_REGEX_STR, argsfile, filtered.as_output()],
+        category = "filter_modules_precompile_argsfile",
+        identifier = name,
+    )
+    return argsfile_with_artifacts(filtered, argsfile)
+
+def compiler_info_with_toolchain_argsfiles(
+    actions: AnalysisActions, name: str, ctor: typing.Callable, compiler_info: typing.Any, precompile_filter: RunInfo | None = None
+) -> typing.Any:
+    """
+    Given a compiler_info that can have a new version made with ctor, this
+    will generate new `argsfile`/`argsfile_xcode` containing the compiler_info's
+    preprocessor and compiler flags. Compile commands use these per-toolchain
+    files, so targets using the toolchain don't each write their own
+    `{ext}.toolchain_cxx_args` copy of the same flags. With `precompile_filter`,
+    also generate `argsfile_precompile`.
+    """
+    if compiler_info == None:
+        return None
+    is_nasm = compiler_info.compiler_type == "nasm"
+    flags = _add_compiler_info_flags(compiler_info)
+    content_based = bool(compiler_info.supports_content_based_paths)
+    argsfile = _mk_argsfile(
+        actions = actions,
+        name = name + "_toolchain_args",
+        args = create_cmd_args(is_nasm, False, flags),
+        has_content_based_path = content_based,
+    )
+    argsfile_xcode = _mk_argsfile(
+        actions = actions,
+        name = name + "_toolchain_args_xcode",
+        args = create_cmd_args(is_nasm, True, flags),
+        has_content_based_path = content_based,
+    )
+    argsfile_precompile = None
+    if precompile_filter != None:
+        argsfile_precompile = mk_toolchain_precompile_argsfile(actions, name, argsfile, precompile_filter)
+    return compiler_info_with_argsfiles(
+        compiler_info,
+        ctor,
+        argsfile,
+        argsfile_xcode,
+        argsfile_precompile,
+    )
+
+def _add_compiler_type_flags(target_label: Label, compiler_type: str, ext: CxxExtension) -> list:
+    cmd = []
+    cmd.append(get_flags_for_reproducible_build(target_label, compiler_type))
+
+    if ext.value not in (".asm", ".asmpp"):
+        # Clang's asm compiler doesn't support colorful output, so we skip this there.
+        cmd.append(get_flags_for_colorful_output(compiler_type))
+
+    return cmd
+
+def _compiler_type_flags_anon_impl(ctx: AnalysisContext):
+    is_nasm = ctx.attrs.compiler_type == "nasm"
+    args = _add_compiler_type_flags(ctx.label, ctx.attrs.compiler_type, CxxExtension(ctx.attrs.src_extension))
+    content = create_cmd_args(is_nasm, ctx.attrs.is_xcode_argsfile, *args)
+    argsfile_artifact, _ = ctx.actions.write("compiler_type_args", content, allow_args = True, has_content_based_path = True)
+
+    return [DefaultInfo(default_outputs = [argsfile_artifact])]
+
+_compiler_type_flags_anon_rule = anon_rule(
+    impl = _compiler_type_flags_anon_impl,
+    attrs = {
+        "compiler_type": attrs.string(doc = "The compiler type. Examples: clang, gcc, nasm"),
+        "is_xcode_argsfile": attrs.bool(doc = "Apply xcode specific formatting to the argsfile."),
+        "src_extension": attrs.string(doc = "The extension of the source file being compiled. See `CxxExtension` enum."),
+    },
+    artifact_promise_mappings = {
+        "argsfile": lambda x: x[DefaultInfo].default_outputs[0],
+    },
+    doc = "Creates compiler flags argsfile for a given compiler type. " + "The argsfile is shared between targets, thus reducing resource usage.",
+)
+
+def create_cmd_args(is_nasm: bool, is_xcode_argsfile: bool, *args) -> cmd_args:
+    if is_xcode_argsfile:
+        return cmd_args(replace_regex = XCODE_ARG_SUBSTITUTIONS, *args)
+    elif is_nasm:
+        return cmd_args(*args)
+    else:
+        return cmd_args(quote = "shell", *args)
+
+_PRECOMPILE_OPTION_IGNORE_REGEX_STR = (
+    "^(?:"
+    + "|".join([
+        # Debug flags, which only affect debug symbols in the backend.
+        "-f(?:no-)?debug-types-section",
+        "-g(?:no-)?pubnames",
+        "-g(?:no-)?record-gcc-switches",
+        "-g(?:no-)?simple-template-names",
+        "-g(?:no-)?split-dwarf(?:=.*)?",
+        "-g[0-3]",
+        "-gdwarf.*",
+        # Profiling flags, used for PGO in the backend.
+        "-fdebug-info-for-profiling",
+        "-fprofile-sample-use=.*",
+    ])
+    + ")$"
+)
+
+_PRECOMPILE_OPTION_IGNORE_REGEX = regex(_PRECOMPILE_OPTION_IGNORE_REGEX_STR)
+
+def _filter_precompile_args(args: list[typing.Any]) -> list[typing.Any]:
+    def should_ignore(s):
+        return _PRECOMPILE_OPTION_IGNORE_REGEX.match(repr(s)[1:-1])
+
+    return filter(
+        None,
+        [_filter_precompile_args(arg) if type(arg) == type([]) else arg if not should_ignore(arg) else None for arg in args],
+    )
+
+def _cxx_flags_args(flags, ext: str, is_precompile: bool):
+    if not is_precompile:
+        return flags.project_as_args(
+            cxx_flags_projection_name(ext),
+            ordering = "postorder",
+        )
+
+    values = flags.traverse(ordering = "postorder")
+    args = [
+        [
+            value.preprocessor_flags,
+            cxx_by_language_ext(value.lang_preprocessor_flags, ext),
+            cxx_by_language_ext(value.lang_compiler_flags, ext),
+            value.compiler_flags,
+        ]
+        for value in values
+    ]
+    return _filter_precompile_args(args)
+
+def _cxx_flags_argsfile_anon_impl(ctx: AnalysisContext):
+    flags = cxx_flags_tset(ctx.actions, ctx.attrs.flags)
+    if flags == None:
+        fail("cxx flags argsfile requires at least one `cxx_flags` target")
+    args = _cxx_flags_args(flags, ctx.attrs.src_extension, ctx.attrs.is_precompile)
+    content = create_cmd_args(ctx.attrs.is_nasm, ctx.attrs.is_xcode_argsfile, args)
+    argsfile, _ = ctx.actions.write("cxx_flags_args", content, allow_args = True, has_content_based_path = True)
+    return [DefaultInfo(default_outputs = [argsfile])]
+
+_cxx_flags_argsfile_anon_rule = anon_rule(
+    impl = _cxx_flags_argsfile_anon_impl,
+    attrs = {
+        "flags": attrs.list(attrs.dep(providers = [CxxFlagsInfo])),
+        "is_nasm": attrs.bool(),
+        "is_precompile": attrs.bool(),
+        "is_xcode_argsfile": attrs.bool(),
+        "src_extension": attrs.string(),
+    },
+    artifact_promise_mappings = {
+        "argsfile": lambda x: x[DefaultInfo].default_outputs[0],
+    },
+    doc = "Creates a shared argsfile from one or more nested `cxx_flags` targets.",
+)
+
+def _filter_precompile_argsfile_anon_impl(ctx: AnalysisContext):
+    argsfile = ctx.actions.declare_output("filtered_args", has_content_based_path = True)
+    ctx.actions.run(
+        [
+            ctx.attrs._cxx_toolchain[CxxToolchainInfo].internal_tools.filter_argsfile,
+            _PRECOMPILE_OPTION_IGNORE_REGEX_STR,
+            ctx.attrs.src,
+            argsfile.as_output(),
+        ],
+        category = "filter_modules_precompile_argsfile",
+        allow_cache_upload = ctx.attrs.allow_cache_upload,
+    )
+    return [DefaultInfo(default_outputs = [argsfile])]
+
+_filter_precompile_argsfile_anon_rule = anon_rule(
+    impl = _filter_precompile_argsfile_anon_impl,
+    attrs = {
+        "allow_cache_upload": attrs.bool(),
+        "src": attrs.source(),
+        "_cxx_toolchain": attrs.dep(),
+    },
+    artifact_promise_mappings = {
+        "argsfile": lambda x: x[DefaultInfo].default_outputs[0],
+    },
+)
+
+def _mk_argsfiles(
+    actions: AnalysisActions,
+    target_label: Label,
+    impl_params: CxxRuleConstructorParams,
+    compiler_info: typing.Any,
+    preprocessor: CPreprocessorInfo,
+    ext: CxxExtension,
+    headers_tag: ArtifactTag,
+    is_xcode_argsfile: bool,
+    is_precompile: bool = False,
+    filename_prefix: str = "",
+    uses_content_based_paths: bool = False,
+) -> CompileArgsfile:
+    """
+    Generate and return an {ext}.argsfile artifact and command args that utilize the argsfile.
+    """
+    is_nasm = compiler_info.compiler_type == "nasm"
+
+    # prefix example: .cpp.xcode_
+    filename_prefix = "{src_file_extension}.{xcode_prefix}{filename_prefix}".format(
+        src_file_extension = ext.value,
+        xcode_prefix = "xcode_" if is_xcode_argsfile else "",
+        filename_prefix = filename_prefix,
+    )
+
+    argsfiles = []
+    args_list = []
+
+    def mk_argsfile(filename: str, args, absolute: bool = False, use_dep_files_placeholder_for_content_based_paths: bool = False) -> Artifact:
+        content = create_cmd_args(is_nasm, is_xcode_argsfile, args)
+        argsfile, _ = actions.write(
+            filename,
+            content,
+            allow_args = True,
+            absolute = absolute,
+            has_content_based_path = uses_content_based_paths,
+            use_dep_files_placeholder_for_content_based_paths = use_dep_files_placeholder_for_content_based_paths,
+        )
+        return argsfile
+
+    def write_for_dep_file_filtering(filename: str, content, absolute: bool = False) -> (Artifact, Artifact | None):
+        # Dep-file filtering needs two versions of the file:
+        # - The first is a tagged file with the optionally content-based paths, which
+        #   will be passed to the compiler as usual, but will NOT be marked used, so
+        #   whether the paths in it change or not, the action will NOT rerun.
+        # - The second is an untagged file with the same content except content-based
+        #   paths are replaced by placeholders. This file is not read by the compiler,
+        #   but is passed as a hidden input of the compiler action, so that if
+        #   something OTHER than paths in the file changes, this redacted version will
+        #   change and trigger a rerun.
+        output, _ = actions.write(
+            filename,
+            content,
+            allow_args = True,
+            absolute = absolute,
+            has_content_based_path = uses_content_based_paths,
+        )
+        # Precompile actions do not filter inputs with dep files, so the real
+        # argsfile already tracks flag changes.
+        if is_precompile:
+            return (output, None)
+
+        redacted_output, _ = actions.write(
+            filename + "_redacted",
+            content,
+            allow_args = True,
+            absolute = absolute,
+            has_content_based_path = uses_content_based_paths,
+            use_dep_files_placeholder_for_content_based_paths = True,
+        )
+        return (output, redacted_output)
+
+    def mk_argsfile_for_dep_file_filtering(filename: str, args, absolute: bool = False) -> (Artifact, Artifact | None):
+        return write_for_dep_file_filtering(
+            filename,
+            create_cmd_args(is_nasm, is_xcode_argsfile, args),
+            absolute = absolute,
+        )
+
+    def make_toolchain_argsfile():
+        compiler_info_flags = _add_compiler_info_flags(compiler_info)
+
+        if is_precompile:
+            if impl_params._cxx_toolchain == None:
+                # TODO(nml): Compared to get_cxx_toolchain_info(), we don't support
+                # AppleToolchain for C++20 modules. Update this if that changes.
+                fail("C++20 modules are not supported for AppleToolchain")
+
+            if compiler_info.argsfile_precompile and not is_xcode_argsfile:
+                compiler_info_argsfile = compiler_info.argsfile_precompile
+            else:
+                # The anon filter takes an `attrs.source()` argsfile, so write
+                # a per-target copy of the flags for it.
+                unfiltered_argsfile = mk_argsfile(filename_prefix + "toolchain_cxx_args", compiler_info_flags)
+                filtered_info_argsfile = actions.anon_target(
+                    _filter_precompile_argsfile_anon_rule,
+                    {
+                        "allow_cache_upload": impl_params.allow_cache_upload,
+                        "src": unfiltered_argsfile,
+                        "_cxx_toolchain": impl_params._cxx_toolchain,
+                    },
+                ).artifact("argsfile")
+
+                # The promise artifact doesn't carry the artifacts the flags
+                # reference forward automatically for us; re-pair them.
+                compiler_info_argsfile = argsfile_with_artifacts(
+                    actions.assert_has_content_based_path(filtered_info_argsfile),
+                    compiler_info_flags,
+                )
+        elif compiler_info.argsfile and not is_xcode_argsfile:
+            compiler_info_argsfile = compiler_info.argsfile
+        elif compiler_info.argsfile_xcode and is_xcode_argsfile:
+            compiler_info_argsfile = compiler_info.argsfile_xcode
+        else:
+            # filename example: .cpp.toolchain_cxx_args
+            compiler_info_filename = filename_prefix + "toolchain_cxx_args"
+            compiler_info_argsfile = mk_argsfile(compiler_info_filename, compiler_info_flags)
+
+        argsfiles.append(compiler_info_argsfile)
+        args_list.append(compiler_info_flags)
+
+    make_toolchain_argsfile()
+
+    def make_compiler_type_argsfile():
+        compiler_type_flags = _add_compiler_type_flags(target_label, compiler_info.compiler_type, ext)
+
+        if impl_params.anon_targets_allowed:
+            compiler_type_flags_anon_target = actions.anon_target(
+                _compiler_type_flags_anon_rule,
+                {
+                    "compiler_type": compiler_info.compiler_type,
+                    "is_xcode_argsfile": is_xcode_argsfile,
+                    "src_extension": ext.value,
+                },
+            )
+            compiler_type_argsfile_artifact = actions.assert_has_content_based_path(compiler_type_flags_anon_target.artifact("argsfile"))
+        else:
+            compiler_type_argsfile_artifact = mk_argsfile(
+                filename_prefix + "compiler_type_args",
+                compiler_type_flags,
+            )
+        argsfiles.append(compiler_type_argsfile_artifact)
+        args_list.append(compiler_type_flags)
+
+    make_compiler_type_argsfile()
+
+    def make_cxx_flags_argsfile():
+        flag_deps = impl_params.cxx_flags
+        if not flag_deps:
+            return
+
+        flags = cxx_flags_tset(actions, flag_deps)
+        projection = flags.project_as_args(
+            cxx_flags_projection_name(ext.value),
+            ordering = "postorder",
+        )
+        if impl_params.anon_targets_allowed:
+            argsfile = actions.anon_target(
+                _cxx_flags_argsfile_anon_rule,
+                {
+                    "flags": flag_deps,
+                    "is_nasm": is_nasm,
+                    "is_precompile": is_precompile,
+                    "is_xcode_argsfile": is_xcode_argsfile,
+                    "src_extension": ext.value,
+                },
+            ).artifact("argsfile")
+            argsfile = actions.assert_has_content_based_path(argsfile)
+        else:
+            argsfile = mk_argsfile(
+                filename_prefix + "cxx_flags_args",
+                _cxx_flags_args(flags, ext.value, is_precompile),
+            )
+
+        argsfiles.append(argsfile_with_artifacts(argsfile, projection))
+        args_list.append(projection)
+
+    make_cxx_flags_argsfile()
+
+    def make_deps_argsfile():
+        deps_args = []
+        if is_precompile:
+            # TODO(nml): We don't support dep files for now in precompile.
+            deps_args.append(preprocessor.set.project_as_args("precompile_args"))
+        else:
+            deps_args.append(headers_tag.tag_artifacts(preprocessor.set.project_as_args("args")))
+
+        # Different preprocessors will contain whether to use modules,
+        # and the modulemap to use, so we need to get the final outcome.
+        if preprocessor.set.reduce("uses_modules"):
+            deps_args.append(headers_tag.tag_artifacts(preprocessor.set.project_as_args("modular_args")))
+
+        # filename example: .cpp.deps_cxx_args, .cpp.deps_cxx_args_redacted
+        deps_argsfile_for_compiler, deps_argsfile_for_buck_action_rerun = mk_argsfile_for_dep_file_filtering(filename_prefix + "deps_cxx_args", deps_args)
+        argsfiles.append(
+            cmd_args(
+                headers_tag.tag_artifacts(deps_argsfile_for_compiler),
+                hidden = [deps_argsfile_for_buck_action_rerun] if deps_argsfile_for_buck_action_rerun != None else [],
+            )
+        )
+        args_list.extend(deps_args)
+
+    make_deps_argsfile()
+
+    def make_target_argsfile():
+        target_args = [
+            # preprocessor
+            impl_params.preprocessor_flags,
+            cxx_by_language_ext(impl_params.lang_preprocessor_flags, ext.value),
+            get_flags_for_compiler_type(compiler_info.compiler_type),
+            # compiler
+            cxx_by_language_ext(impl_params.lang_compiler_flags, ext.value),
+            # ctx.attrs.compiler_flags need to come last to preserve buck1 ordering, this prevents compiler
+            # flags ordering-dependent build errors
+            impl_params.compiler_flags,
+            headers_tag.tag_artifacts(preprocessor.set.project_as_args("include_dirs")),
+        ]
+        if is_precompile:
+            target_args = _filter_precompile_args(target_args)
+        target_args = cmd_args(target_args)
+
+        # Workaround as that's not precompiled, but working just as prefix header.
+        # Another thing is that it's clang specific, should be generalized.
+        if impl_params.precompiled_header != None and not impl_params.precompiled_header[CPrecompiledHeaderInfo].compiled:
+            target_args.add(["-include", headers_tag.tag_artifacts(impl_params.precompiled_header[CPrecompiledHeaderInfo].header)])
+        if impl_params.prefix_header != None:
+            target_args.add(["-include", headers_tag.tag_artifacts(impl_params.prefix_header)])
+
+        # filename example: .cpp.target_cxx_args
+        target_argsfile_filename = filename_prefix + "target_cxx_args"
+        argsfiles.append(mk_argsfile(target_argsfile_filename, target_args))
+        args_list.append(target_args)
+
+    make_target_argsfile()
+
+    # Create a copy of the args so that we can continue to modify it later.
+    args_without_file_prefix_args = cmd_args(args_list)
+
+    # Holder, because the closure below cannot bind an enclosing name.
+    file_prefix_specs = []
+
+    def make_file_prefix_argsfile():
+        if is_precompile:
+            # The precompile_args field overrides these.
+            return
+
+        if compiler_info.compiler_type in ("nasm", "windows_ml64"):
+            # NASM/MASM don't understand -ffile-prefix-map. .s/.sx/.S go through the gcc/clang
+            # driver (as_compiler_info) and do accept these flags.
+            return
+
+        if not preprocessor.set.reduce("has_file_prefix_args"):
+            return
+
+        # Put file_prefix_args in argsfile, make sure they do not appear when evaluating $(cxxppflags)
+        # to avoid "argument too long" errors
+        file_prefix_args = headers_tag.tag_artifacts(preprocessor.set.project_as_args("file_prefix_args"))
+
+        if ext.value == ".cu":
+            # NVCC passes argsfile flags to device sub-tools (cicc, ptxas) which don't
+            # understand -ffile-prefix-map.
+            file_prefix_args = cmd_args(file_prefix_args, replace_regex = ("-ffile-prefix-map=", "-fdebug-prefix-map="))
+        elif compiler_info.compiler_type == "clang":
+            # -fcoverage-prefix-map is only supported by clang. Include coverage prefix args
+            # only for clang to avoid breaking non-clang compilers that receive flags from
+            # dependencies via the preprocessor set.
+            coverage_prefix_args = headers_tag.tag_artifacts(preprocessor.set.project_as_args("coverage_prefix_args"))
+            file_prefix_args = cmd_args(file_prefix_args, coverage_prefix_args)
+
+        file_prefix_args_filename = filename_prefix + "file_prefix_cxx_args"
+
+        # GCC copies all flags into COLLECT_GCC_OPTIONS env var before exec'ing cc1. This single
+        # string can exceed Linux's 128KB MAX_ARG_STRLEN limit when there are hundreds of prefix-map
+        # flags.
+        #
+        # Delivering via -specs injects flags directly into cc1 without touching
+        # COLLECT_GCC_OPTIONS.
+        #
+        # Assembly may report compiler_type=="gcc" via as_compiler_info even on Clang toolchains;
+        # -specs= is GCC-driver-only so skip it for assembly.
+        if compiler_info.compiler_type == "gcc" and _get_category(ext) != "asm_compile":
+            specs_content = cmd_args(
+                "*cc1:\n+ ",
+                file_prefix_args,
+                delimiter = " ",
+            )
+            specs_file, specs_file_for_buck_action_rerun = write_for_dep_file_filtering(
+                file_prefix_args_filename + ".specs",
+                specs_content,
+            )
+            prefix_ref = cmd_args(
+                headers_tag.tag_artifacts(specs_file),
+                format = "-specs={}",
+                hidden = specs_file_for_buck_action_rerun,
+            )
+            file_prefix_specs.append(specs_file)
+        else:
+            prefix_ref = file_prefix_args
+
+        file_prefix_argsfile_for_compiler, file_prefix_argsfile_for_buck_action_rerun = mk_argsfile_for_dep_file_filtering(
+            file_prefix_args_filename,
+            prefix_ref,
+        )
+        argsfiles.append(
+            cmd_args(
+                headers_tag.tag_artifacts(file_prefix_argsfile_for_compiler),
+                hidden = file_prefix_argsfile_for_buck_action_rerun,
+            )
+        )
+        args_list.append(prefix_ref)
+
+    make_file_prefix_argsfile()
+
+    if is_xcode_argsfile:
+        file_args = cmd_args(argsfiles, format = "@{}")
+    elif is_nasm:
+        file_args = cmd_args(argsfiles, format = "-@{}")
+    else:
+        file_args = cmd_args(argsfiles, format = "@{}", quote = "shell")
+
+    # filename example: .cpp.cxx_compile_argsfile
+    file_name = filename_prefix + "cxx_compile_argsfile"
+
+    # For Xcode to parse argsfiles of argsfiles, the paths in the former must be absolute.
+    argsfile, argsfile_for_buck_action_rerun = write_for_dep_file_filtering(
+        file_name,
+        file_args,
+        absolute = is_xcode_argsfile,
+    )
+
+    args = create_cmd_args(is_nasm, is_xcode_argsfile, args_list)
+    input_args = [args, file_args]
+    if argsfile_for_buck_action_rerun != None:
+        input_args.append(argsfile_for_buck_action_rerun)
+
+    argsfile_format = "-@{}" if is_nasm else "@{}"
+    cmd_form = cmd_args(
+        headers_tag.tag_artifacts(argsfile),
+        format = argsfile_format,
+        hidden = input_args,
+    )
+
+    # The NVCC dry run expands the flags and reads header maps, nothing else behind them.
+    cmd_form_cuda_dryrun = None
+    if ext.value == ".cu":
+        cmd_form_cuda_dryrun = cmd_args(
+            argsfile,
+            format = argsfile_format,
+            hidden = [file_args, preprocessor.set.project_as_args("header_maps")],
+        )
+    return CompileArgsfile(
+        file = argsfile,
+        cmd_form = cmd_form,
+        cmd_form_cuda_dryrun = cmd_form_cuda_dryrun,
+        args = args,
+        args_without_file_prefix_args = args_without_file_prefix_args,
+        file_prefix_specs = file_prefix_specs[0] if file_prefix_specs else None,
+    )
+
+def _mk_header_units_argsfile(
+    actions: AnalysisActions,
+    compiler_info: typing.Any,
+    preprocessor: CPreprocessorInfo,
+    ext: CxxExtension,
+    filename_prefix: str = "",
+    has_content_based_path: bool = False,
+    stub: bool = False,
+) -> CompileArgsfile | None:
+    """
+    Generate and return an argsfile artifact containing all header unit options, and
+    command args that utilize the argsfile.
+    """
+    if not preprocessor.set:
+        return None
+    if _get_category(ext) != "cxx_compile":
+        return None
+    if not _compiler_supports_header_units(compiler_info):
+        return None
+    if not preprocessor.set.reduce("has_header_units_args"):
+        return None
+
+    file_name = "{}.{}header_unit{}_args".format(ext.value, filename_prefix, "_stubs" if stub else "s")
+    args = cmd_args()
+    args.add([
+        # TODO(nml): We only support Clang 17+, which don't need/want the extra -f
+        # arguments when compiling C++20. Clang 15 is too buggy to work properly, but if
+        # you wanted to try, you would need the below options at the very least, to get
+        # started:
+        # "-fmodules",
+        # "-fno-implicit-modules",
+        # "-fno-implicit-module-maps",
+        "-Wno-experimental-header-units",
+        "-Wno-ambiguous-macro",
+    ])
+
+    # TODO(nml): Tag args with headers_tag.tag_artifacts() once -MD -MF reports correct
+    # usage of PCMs. See T225373444 and _mk_header_units_argsfile() below.
+    projection_name = "header_unit_stubs_args" if stub else "header_units_args"
+    args.add(preprocessor.set.project_as_args(projection_name))
+    file_args = cmd_args(args, quote = "shell")
+    argsfile, _ = actions.write(
+        file_name,
+        file_args,
+        allow_args = True,
+        has_content_based_path = has_content_based_path,
+    )
+    cmd_form = cmd_args(argsfile, format = "@{}", hidden = file_args)
+
+    return CompileArgsfile(
+        file = argsfile,
+        cmd_form = cmd_form,
+        args = file_args,
+        args_without_file_prefix_args = args,
+    )
+
+def _get_dep_tracking_mode(toolchain: Provider, file_type: DepFileType) -> DepTrackingMode:
+    if file_type == DepFileType("cpp") or file_type == DepFileType("c"):
+        return toolchain.cpp_dep_tracking_mode
+    elif file_type == DepFileType("cuda"):
+        return toolchain.cuda_dep_tracking_mode
+    else:
+        return DepTrackingMode("makefile")
+
+def get_compiler_type(ctx: AnalysisContext, ext: CxxExtension) -> typing.Any:
+    toolchain = get_cxx_toolchain_info(ctx)
+    compiler_info = _get_compiler_info(toolchain, ext)
+    return compiler_info.compiler_type
+
+def _generate_base_compile_command(
+    actions: AnalysisActions,
+    target_label: Label,
+    toolchain: CxxToolchainInfo,
+    impl_params: CxxRuleConstructorParams,
+    pre: CPreprocessorInfo,
+    headers_tag: ArtifactTag,
+    ext: CxxExtension,
+    filename_prefix: str = "",
+) -> CxxCompileCommand:
+    """
+    Generate a common part of a compile command that is shared by all sources
+    with a given extension.
+    """
+    compiler_info = _get_compiler_info(toolchain, ext)
+
+    base_compile_cmd = _get_compile_base(toolchain, compiler_info, impl_params.use_fbcc_rust_wrapper)
+    category = _get_category(ext)
+
+    headers_dep_files = None
+    dep_file_file_type_hint = _dep_file_type(ext)
+    if dep_file_file_type_hint != None and toolchain.use_dep_files:
+        tracking_mode = _get_dep_tracking_mode(toolchain, dep_file_file_type_hint)
+        mk_dep_files_flags = get_headers_dep_files_flags_factory(tracking_mode)
+        if mk_dep_files_flags:
+            headers_dep_files = HeadersDepFiles(
+                processor = cmd_args(toolchain.internal_tools.dep_file_processor),
+                mk_flags = mk_dep_files_flags,
+                tag = headers_tag,
+                dep_tracking_mode = tracking_mode,
+            )
+
+    def gen_argsfiles(is_xcode_argsfile):
+        return _mk_argsfiles(
+            actions,
+            target_label,
+            impl_params,
+            compiler_info,
+            pre,
+            ext,
+            headers_tag,
+            is_precompile = False,
+            filename_prefix = filename_prefix,
+            uses_content_based_paths = not is_xcode_argsfile,
+            is_xcode_argsfile = is_xcode_argsfile,
+        )
+
+    argsfile = gen_argsfiles(is_xcode_argsfile = False)
+
+    # The Xcode argsfile is consumed only by the `xcode-argsfiles` sub-target and
+    # `XcodeDataInfo`, both of which are Xcode/IDE features gated on `xcode_data`.
+    # Skip generating it (per source extension, per target) otherwise, saving
+    # memory on non-IDE builds.
+    if impl_params.generate_sub_targets.xcode_data:
+        xcode_argsfile = gen_argsfiles(is_xcode_argsfile = True)
+    else:
+        xcode_argsfile = None
+
+    header_units_argsfile = _mk_header_units_argsfile(
+        actions,
+        compiler_info,
+        pre,
+        ext,
+        filename_prefix,
+        has_content_based_path = True,
+        stub = False,
+    )
+
+    header_unit_stubs_argsfile = _mk_header_units_argsfile(
+        actions,
+        compiler_info,
+        pre,
+        ext,
+        filename_prefix,
+        has_content_based_path = True,
+        stub = True,
+    )
+
+    allow_content_based_paths = bool(compiler_info.supports_content_based_paths and impl_params.use_content_based_paths)
+    return CxxCompileCommand(
+        base_compile_cmd = base_compile_cmd,
+        argsfile = argsfile,
+        xcode_argsfile = xcode_argsfile,
+        header_units_argsfile = header_units_argsfile,
+        header_unit_stubs_argsfile = header_unit_stubs_argsfile,
+        headers_dep_files = headers_dep_files,
+        compiler_type = compiler_info.compiler_type,
+        category = category,
+        allow_cache_upload = impl_params.allow_cache_upload,
+        allow_content_based_paths = allow_content_based_paths,
+    )
+
+def _get_use_pch_args(
+    src: Artifact,
+    cxx_compile_cmd: CxxCompileCommand,
+    compile_with_pch: CPrecompiledHeaderInfo,
+    precompiled_header: CPrecompiledHeaderInfo,
+) -> cmd_args:
+    if precompiled_header.clanguage != src.extension:
+        return cmd_args()
+
+    pch_args = cmd_args()
+    if cxx_compile_cmd.compiler_type in ["windows"]:
+        pch_args.add(cmd_args(compile_with_pch.basename, format = "/Yu{}"))
+        pch_args.add(cmd_args(compile_with_pch.basename, format = "/FI{}"))
+        pch_args.add(cmd_args(compile_with_pch.header, format = "/Fp{}"))
+    elif cxx_compile_cmd.compiler_type in ["clang"]:
+        pch_args.add("-Xclang", "-include-pch", "-Xclang", compile_with_pch.header)
+    else:
+        fail(
+            "Warning: Unsupported compiler type for precompiled header usage: {}".format(
+                cxx_compile_cmd.compiler_type,
+            )
+        )
+
+    return pch_args
+
+def _declare_clang_trace_output(
+    toolchain: CxxToolchainInfo, compiler_type: str, actions: AnalysisActions, filename_base: str, content_based: bool
+) -> Artifact | None:
+    """
+    Declares an output artifact for clang trace JSON file.
+    """
+    if toolchain.clang_trace and compiler_type == "clang":
+        return actions.declare_output(
+            paths.join("__objects__", "{}.json".format(filename_base)),
+            has_content_based_path = content_based,
+        )
+    return None
+
+def _declare_assembly(actions: AnalysisActions, compiler_type: str, object_format: CxxObjectFormat, filename_base: str, content_based: bool) -> Artifact | None:
+    """
+    Declares an output artifact for assembly or LLVM IR output file.
+    Returns None for compilers that don't support the -S flag.
+    """
+    if compiler_type not in ["clang", "gcc"]:
+        return None
+
+    # Generate assembler or llvm bitcode output file
+    assembly_extension = "s"
+    if compiler_type == "clang" and object_format == CxxObjectFormat("bitcode"):
+        assembly_extension = "ll"
+
+    return actions.declare_output(
+        "__assembly__",
+        "{}.{}".format(filename_base, assembly_extension),
+        has_content_based_path = content_based,
+    )
diff --git a/buck2/prelude/cxx/compile_types.bzl b/buck2/prelude/cxx/compile_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/compile_types.bzl
@@ -0,0 +1,202 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load(":argsfiles.bzl", "CompileArgsfile", "CompileArgsfiles")
+load(":cxx_toolchain_types.bzl", "CxxObjectFormat", "DepTrackingMode")
+
+# Supported assembly extensions
+AsmExtensions = enum(
+    ".s",
+    ".sx",
+    ".S",
+    ".asm",
+    ".asmpp",
+)
+
+# Supported Cxx file extensions
+CxxExtension = enum(".cpp", ".cc", ".cl", ".cxx", ".c++", ".c", ".m", ".mm", ".cu", ".hip", ".h", ".hpp", ".hh", ".h++", ".hxx", ".bc", *AsmExtensions.values())
+
+# Header files included in compilation databases
+HeaderExtension = enum(
+    ".h",
+    ".hpp",
+    ".hh",
+    ".h++",
+    ".hxx",
+    ".cuh",
+)
+
+# Mode for using header units in compilation
+UseHeaderUnitsMode = enum(
+    # Don't use header units
+    "none",
+    # Use full precompiled modules (.pcm files)
+    "pcm",
+    # Use module stubs (.pcm.stub files): those are not directly used in the compilation
+    # command line; instead, they are inert stand-ins that behave like real PCM files,
+    # cache-wise (i.e. expected to be cached when real PCM files would be cached, and
+    # rebuilt when PCM files would be). You can enable these to trace and model the
+    # behaviour of module-enabled builds before actually migrating to them. This steps
+    # helps estimate the overhead of precompiling modules in terms of additional
+    # uncached Buck actions.
+    "stub",
+)
+
+# File types for dep files
+DepFileType = enum(
+    "cpp",
+    "c",
+    "cuda",
+    "asm",
+)
+
+HeadersDepFiles = record(
+    # An executable to wrap the actual command with for post-processing of dep
+    # files into the format that Buck2 recognizes (i.e. one artifact per line).
+    processor = field(cmd_args),
+    # The tag that was added to headers.
+    tag = field(ArtifactTag),
+    # A function that produces new cmd_args to append to the compile command to
+    # get it to emit the dep file. This will receive the output dep file as an
+    # input.
+    mk_flags = field(typing.Callable),
+    # Dependency tracking mode to know how to generate dep file
+    dep_tracking_mode = field(DepTrackingMode),
+)
+
+# Output from CUDA distributed compilation
+CudaDistributedCompileOutput = record(
+    # Dependency graph of the NVCC sub-commands.
+    nvcc_dag = field(Artifact),
+    # Environment variables for the NVCC sub-commands.
+    nvcc_env = field(Artifact),
+    # Argsfile for the host compiler.
+    hostcc_argsfile = field(Artifact),
+)
+
+# Information about how to compile a source file of particular extension.
+CxxCompileCommand = record(
+    # The compiler and any args which are independent of the rule.
+    base_compile_cmd = field(cmd_args),
+    # The argsfile of arguments from the rule and it's dependencies.
+    argsfile = field(CompileArgsfile),
+    # The argsfile to use for Xcode integration. Requires xcode_data subtarget.
+    xcode_argsfile = field(CompileArgsfile | None),
+    # The argsfile containing header units args.
+    header_units_argsfile = field(CompileArgsfile | None),
+    # The argsfile containing header unit stubs args.
+    header_unit_stubs_argsfile = field(CompileArgsfile | None),
+    headers_dep_files = field([HeadersDepFiles, None]),
+    compiler_type = field(str),
+    # The action category
+    category = field(str),
+    allow_cache_upload = field(bool),
+    allow_content_based_paths = field(bool),
+)
+
+# Declared index store output and metadata
+DeclaredIndexStore = record(
+    output = field(Artifact),
+    filename_base = field(str),
+)
+
+# Factory for creating and compiling index stores
+# - declare: Called during analysis to declare the output artifact
+# - compile: Called during execution (inside dynamic action) to run the compilation
+IndexStoreFactory = record(
+    declare = field(typing.Callable[[AnalysisActions, typing.Any], DeclaredIndexStore | None]),
+    compile = field(typing.Callable[[AnalysisActions, Label, OutputArtifact, str, CxxToolchainInfo, cmd_args], None]),
+)
+
+# Information about how to compile a source file.
+CxxSrcCompileCommand = record(
+    # Source file to compile.
+    src = field(Artifact),
+    # If we have multiple source entries with same files but different flags,
+    # specify an index so we can differentiate them. Otherwise, use None.
+    index = field([int, None], None),
+    # The CxxCompileCommand to use to compile this file.
+    cxx_compile_cmd = field(CxxCompileCommand),
+    # Arguments specific to the source file.
+    args = field(list[typing.Any]),
+    # Is this a header file?
+    is_header = field(bool, False),
+    # Whether to use content-based paths for the outputs of the compilation command.
+    uses_content_based_paths = field(bool),
+    # The index store factory to use to generate index store for this source file.
+    index_store_factory = field(IndexStoreFactory | None, None),
+    error_handler = field([typing.Callable, None], None),
+    # Whether to set expect_eligible_for_dedupe on compile actions.
+    expect_eligible_for_dedupe = field(bool, False),
+)
+
+CxxSrcPrecompileCommand = record(
+    # Source file to compile.
+    src = field(Artifact),
+    # The CxxCompileCommand to use to compile this file.
+    cxx_compile_cmd = field(CxxCompileCommand),
+    # Arguments specific to the source file.
+    args = field(list[typing.Any]),
+    # Arguments for -fsyntax-only check (args without --precompile and
+    # -DFACEBOOK_CPP_HEADER_UNIT=1, with -fsyntax-only instead).
+    check_args = field(list[typing.Any], []),
+    # Extra argsfile to include after any other header units argsfile but before the
+    # main argsfiles.
+    extra_argsfile = field([CompileArgsfile, None], None),
+)
+
+# Output of creating compile commands for Cxx source files.
+CxxCompileCommandOutput = record(
+    # List of compile commands for each source file.
+    src_compile_cmds = field(list[CxxSrcCompileCommand], default = []),
+    # Base compile commands for each source file extension.
+    base_compile_cmds = field(dict[CxxExtension, CxxCompileCommand], default = {}),
+    # Argsfiles generated for compiling these source files.
+    argsfiles = field(CompileArgsfiles, default = CompileArgsfiles()),
+    # List of compile commands for use in compilation database generation.
+    comp_db_compile_cmds = field(list[CxxSrcCompileCommand], default = []),
+)
+
+CxxCompileOutput = record(
+    # The compiled `.o` file.
+    object = field(Artifact),
+    object_format = field(CxxObjectFormat, CxxObjectFormat("native")),
+    object_has_external_debug_info = field(bool, False),
+    # Externally referenced debug info, which doesn't get linked with the
+    # object (e.g. the above `.o` when using `-gsplit-dwarf=single` or the
+    # the `.dwo` when using `-gsplit-dwarf=split`).
+    external_debug_info = field(Artifact | None, None),
+    clang_remarks = field(Artifact | None, None),
+    clang_llvm_statistics = field(Artifact | None, None),
+    clang_trace = field(Artifact | None, None),
+    gcno_file = field(Artifact | None, None),
+    index_store = field(Artifact | None, None),
+    assembly = field(Artifact | None, None),
+    diagnostics = field(Artifact | None, None),
+    clang_tidy_diagnostics = field(Artifact | None, None),
+    preproc = field(Artifact | None, None),
+    dist_cuda = field(CudaDistributedCompileOutput | None, None),
+    pch_object = field(Artifact | None, None),
+    json_error = field(Artifact | None, None),
+    # True for HIP TUs under the device-debug-extract modifier.
+    hip_device_debug = field(bool, False),
+    # Per-arch sidecar .debug files from hip_debug_extract_compile_object.
+    hip_arch_debug_files = field(dict[str, Artifact], {}),
+)
+
+CxxCompileFlavor = enum(
+    # Produces position independent compile outputs
+    "pic",
+    # Produces position independent compile outputs
+    # using optimization flags from toolchain
+    "optimized",
+    # Produces position independent compile outputs
+    # using debug flags from toolchain
+    "debug",
+)
diff --git a/buck2/prelude/cxx/compiler.bzl b/buck2/prelude/cxx/compiler.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/compiler.bzl
@@ -0,0 +1,87 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//utils:utils.bzl",
+    "as_output",
+)
+load(":cxx_toolchain_types.bzl", "DepTrackingMode")
+
+# TODO(T110378132): Added here for compat with v1, but this might make more
+# sense on the toolchain definition.
+def get_flags_for_reproducible_build(target_label: Label, compiler_type: str) -> list[[str, cmd_args]]:
+    """
+    Return flags needed to make compilations reproducible (e.g. avoiding
+    embedding the working directory into debug info.
+    """
+
+    flags = []
+
+    if compiler_type in ["clang_cl", "windows"]:
+        flags.extend(["/Brepro", "/d2threads1"])
+
+    if compiler_type in ["clang", "clang_windows", "clang_cl"]:
+        flags.extend(["-Xclang", "-fdebug-compilation-dir", "-Xclang", cmd_args(target_label.project_root)])
+
+    if compiler_type == "clang_windows":
+        flags.append("-mno-incremental-linker-compatible")
+
+    return flags
+
+def get_flags_for_colorful_output(compiler_type: str) -> list[str]:
+    """
+    Return flags for enabling colorful diagnostic output.
+    """
+    flags = []
+    if compiler_type in ["clang", "clang_windows", "clang_cl"]:
+        # https://clang.llvm.org/docs/UsersManual.html
+        flags.append("-fcolor-diagnostics")
+    elif compiler_type == "gcc":
+        # https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Message-Formatting-Options.html
+        flags.append("-fdiagnostics-color=always")
+
+    return flags
+
+# These functions return two values: wrapper_args and compiler_args
+# wrapper_args -> the arguments used by the dep_file_processor to determine how to process the dep files
+# compiler_args -> args passed to the compiler when generating dependencies
+
+def cc_dep_files(actions: AnalysisActions, filename_base: str, _input_file: Artifact) -> (cmd_args, cmd_args):
+    intermediary_dep_file = actions.declare_output(
+        paths.join("__dep_files_intermediaries__", filename_base),
+        has_content_based_path = True,
+    ).as_output()
+
+    return (cmd_args(intermediary_dep_file), cmd_args(["-MD", "-MF", intermediary_dep_file]))
+
+def tree_style_cc_dep_files(_actions: AnalysisActions, _filename_base: str, input_file: Artifact) -> (cmd_args, cmd_args):
+    # If we use color diagnostics, then error messages come through in color, which messes up parsing of the
+    # -H output in `show_headers_to_dep_file.py`.  So make sure to pass -fno-color-diagnostics.
+    return (cmd_args(input_file), cmd_args(["-H", "-fno-color-diagnostics"]))
+
+def windows_cc_dep_files(_actions: AnalysisActions, _filename_base: str, input_file: Artifact) -> (cmd_args, cmd_args):
+    return (cmd_args(input_file), cmd_args(["/showIncludes"]))
+
+def get_headers_dep_files_flags_factory(dep_tracking_mode: DepTrackingMode) -> [typing.Callable, None]:
+    if dep_tracking_mode.value == "makefile":
+        return cc_dep_files
+
+    if dep_tracking_mode.value == "show_includes":
+        return windows_cc_dep_files
+
+    if dep_tracking_mode.value == "show_headers":
+        return tree_style_cc_dep_files
+
+    return None
+
+def get_output_flags(compiler_type: str, output: Artifact | OutputArtifact) -> list[typing.Any]:
+    if compiler_type in ["windows", "clang_cl", "windows_ml64"]:
+        return [cmd_args(as_output(output), format = "/Fo{}")]
+    else:
+        return ["-o", as_output(output)]
diff --git a/buck2/prelude/cxx/cuda.bzl b/buck2/prelude/cxx/cuda.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cuda.bzl
@@ -0,0 +1,603 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:compile_types.bzl", "CudaDistributedCompileOutput", "CxxCompileCommand", "HeadersDepFiles")
+load("@prelude//cxx:compiler.bzl", "get_output_flags")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("@prelude//cxx:headers.bzl", "add_headers_dep_files")
+load(
+    "@prelude//utils:utils.bzl",
+    "as_output",
+)
+
+CudaCompileInfo = record(
+    # Output base filename without extension
+    filename = field(str),
+    # Buck action identifier
+    identifier = field(str),
+    # Output sub-directory where all CUDA compilation artifacts will go to
+    output_prefix = field(str),
+    uses_content_based_paths = field(bool),
+)
+
+CudaCompileStyle = enum(
+    # Use NVCC as the compiler driver and compile a CUDA file in a single Buck
+    # action.
+    "mono",
+    # NVCC provides the compilation plan, but use one Buck action per compilation
+    # sub-command.
+    "dist",
+)
+
+CudaDistributedCompileSpec = record(
+    cuda_compile_info = field(CudaCompileInfo),
+    original_cmd = field(cmd_args),
+    argsfile_args = field(cmd_args),
+    file_prefix_specs = field(Artifact | None),
+    output_declared_artifact = field(OutputArtifact),
+    src = field(Artifact),
+)
+
+PreparedCudaCommand = record(
+    cmd_node = field(dict[str, typing.Any]),
+    exe = field(str),
+    parts = field(list[typing.Any]),
+)
+
+def declare_cuda_dist_compile_output(actions: AnalysisActions, cuda_compile_info: CudaCompileInfo) -> CudaDistributedCompileOutput:
+    """
+    Declare output artifacts for CUDA distributed compilation upfront.
+    This should be called during analysis before the dynamic action.
+    """
+    content_based = cuda_compile_info.uses_content_based_paths
+
+    # Create the following files for each CUDA file:
+    # - Envvars to run the NVCC sub-commands with.
+    # - A dependency graph of the NVCC sub-commands.
+    # - Argsfile for the host compiler.
+    env = actions.declare_output(
+        cuda_compile_info.output_prefix,
+        "{}.env".format(cuda_compile_info.filename),
+        has_content_based_path = content_based,
+    )
+    subcmds = actions.declare_output(
+        cuda_compile_info.output_prefix,
+        "{}.json".format(cuda_compile_info.filename),
+        has_content_based_path = content_based,
+    )
+    hostcc_argsfile = actions.declare_output(
+        cuda_compile_info.output_prefix,
+        "{}.hostcc_argsfile".format(cuda_compile_info.filename),
+        has_content_based_path = content_based,
+    )
+    return CudaDistributedCompileOutput(
+        nvcc_dag = subcmds,
+        nvcc_env = env,
+        hostcc_argsfile = hostcc_argsfile,
+    )
+
+def cuda_mono_compile(
+    actions: AnalysisActions,
+    cmd: cmd_args,
+    object: OutputArtifact,
+    src: Artifact,
+    cxx_compile_cmd: CxxCompileCommand,
+    cuda_compile_info: CudaCompileInfo,
+    action_dep_files: dict[str, ArtifactTag],
+    allow_dep_file_cache_upload: bool,
+    error_handler: [typing.Callable, None],
+) -> None:
+    """
+    Compile a CUDA file monolithically using NVCC as the compiler driver.
+    All compilation happens in a single Buck action.
+    """
+
+    # Bind the object output for monolithic NVCC compilation.
+    cmd.add(get_output_flags(cxx_compile_cmd.compiler_type, object))
+    headers_dep_files = cxx_compile_cmd.headers_dep_files
+    if headers_dep_files:
+        cmd = add_headers_dep_files(
+            actions,
+            cmd,
+            headers_dep_files,
+            src,
+            cuda_compile_info.filename,
+            action_dep_files,
+        )
+    actions.run(
+        cmd,
+        category = cxx_compile_cmd.category,
+        identifier = cuda_compile_info.identifier,
+        dep_files = action_dep_files,
+        allow_cache_upload = cxx_compile_cmd.allow_cache_upload,
+        allow_dep_file_cache_upload = allow_dep_file_cache_upload,
+        error_handler = error_handler,
+    )
+
+def cuda_distributed_compile(
+    actions: AnalysisActions,
+    cmd: cmd_args,
+    object: OutputArtifact,
+    cuda_dist_output: CudaDistributedCompileOutput,
+    src: Artifact,
+    cxx_compile_cmd: CxxCompileCommand,
+    cuda_compile_info: CudaCompileInfo,
+    cuda_prepare_cmd: cmd_args | None,
+    shared_plan_identifier: str | None,
+) -> CudaDistributedCompileSpec:
+    """
+    Set up distributed compilation for a CUDA file: optionally register the
+    nvcc -dryrun prepare action that produces the target's shared compilation
+    plan, and return the spec from which create_cuda_distributed_compiles
+    later creates one Buck action per NVCC sub-command.
+
+    Compilation modes that require a whole-program device link step are NOT
+    supported here: relocatable device code (-rdc=true / --device-c), device
+    LTO (-dlto), and PTX-only codegen all make nvcc -dryrun emit an nvlink
+    sub-command that dist NVCC cannot distribute. Such targets must set
+    cuda_compile_style = "mono". If one of these modes reaches this path, the
+    dryrun parser (tools/build/cuda/nvcc_dryrun.py) fails the
+    cuda_compile_prepare action with an actionable error that names the source
+    .cu and points to the mono escape hatch.
+    """
+    hostcc_argsfile = cuda_dist_output.hostcc_argsfile
+
+    # The object is produced by the replayed plan sub-actions, not by this
+    # command, so embed its path as a string rather than binding the output.
+    cmd_with_output = cmd_args(cmd, ["-o", object.short_path])
+    original_cmd = cmd_args(
+        cmd_with_output,
+        hidden = [
+            cxx_compile_cmd.base_compile_cmd,
+            cxx_compile_cmd.argsfile.cmd_form,
+        ],
+    )
+
+    # The dry run never opens this file. It matches the flag, echoed as one
+    # `-specs=<path>` token, so the plan can carry a placeholder in place of a
+    # path that moves with the header closure.
+    file_prefix_specs = cxx_compile_cmd.argsfile.file_prefix_specs
+
+    if cuda_prepare_cmd != None:
+        prepare_cmd = cmd_args(
+            cuda_prepare_cmd,
+            ["-o", object.short_path],
+            [
+                "-_NVCC_DRYRUN_",
+                "-_NVCC_HOSTCC_ARGSFILE_",
+                as_output(hostcc_argsfile),
+                "-_NVCC_DRYRUN_ENV_OUT_",
+                as_output(cuda_dist_output.nvcc_env),
+                "-_NVCC_DRYRUN_DAG_OUT_",
+                as_output(cuda_dist_output.nvcc_dag),
+            ],
+        )
+        if file_prefix_specs != None:
+            prepare_cmd.add(
+                "-_NVCC_FILE_PREFIX_SPECS_",
+                cmd_args(file_prefix_specs, format = "-specs={}"),
+            )
+
+        # Run nvcc with -dryrun to create the inputs needed for dist nvcc.
+        actions.run(prepare_cmd, category = "cuda_compile_prepare", identifier = shared_plan_identifier or cuda_compile_info.identifier)
+
+    return CudaDistributedCompileSpec(
+        cuda_compile_info = cuda_compile_info,
+        original_cmd = original_cmd,
+        argsfile_args = cxx_compile_cmd.argsfile.args,
+        file_prefix_specs = file_prefix_specs,
+        output_declared_artifact = object,
+        src = src,
+    )
+
+# Keep the old cuda_compile function for backward compatibility
+def cuda_compile(
+    actions: AnalysisActions,
+    cmd: cmd_args,
+    object: OutputArtifact,
+    src: Artifact,
+    cxx_compile_cmd: CxxCompileCommand,
+    cuda_compile_info: CudaCompileInfo,
+    action_dep_files: dict[str, ArtifactTag],
+    allow_dep_file_cache_upload: bool,
+    error_handler: [typing.Callable, None],
+    cuda_compile_style: CudaCompileStyle | None,
+    cuda_dist_output: CudaDistributedCompileOutput | None = None,
+    cuda_prepare_cmd: cmd_args | None = None,
+    shared_plan_identifier: str | None = None,
+) -> CudaDistributedCompileSpec | None:
+    """
+    Compile a CUDA file using either monolithic or distributed compilation.
+    This is a convenience function that dispatches to the appropriate implementation.
+    """
+    if cuda_compile_style == CudaCompileStyle("mono"):
+        cuda_mono_compile(
+            actions,
+            cmd,
+            object,
+            src,
+            cxx_compile_cmd,
+            cuda_compile_info,
+            action_dep_files,
+            allow_dep_file_cache_upload,
+            error_handler,
+        )
+        return None
+    elif cuda_compile_style == CudaCompileStyle("dist"):
+        if cuda_dist_output == None:
+            fail("cuda_dist_output is required for distributed CUDA compilation")
+        return cuda_distributed_compile(
+            actions,
+            cmd,
+            object,
+            cuda_dist_output,
+            src,
+            cxx_compile_cmd,
+            cuda_compile_info,
+            cuda_prepare_cmd,
+            shared_plan_identifier,
+        )
+    else:
+        fail("Unsupported CUDA compile style: {}".format(cuda_compile_style))
+
+def create_cuda_distributed_compiles(
+    actions: AnalysisActions,
+    toolchain: CxxToolchainInfo,
+    cuda_dist_output: CudaDistributedCompileOutput,
+    specs: list[CudaDistributedCompileSpec],
+    allow_cache_upload: bool,
+    cuda_cxx_compile_inputs: cmd_args,
+    headers_dep_files: HeadersDepFiles | None,
+) -> None:
+    if not specs:
+        return
+
+    # The argsfile is shared by the target's sources, so one fingerprint covers
+    # them all. It carries the same flags with content-based paths rendered as a
+    # placeholder: it moves when a flag really changes, not when a path does.
+    hostcc_argsfile_fingerprint = None
+    if headers_dep_files != None:
+        hostcc_argsfile_fingerprint, _ = actions.write(
+            "__redacted__/{}.hostcc_argsfile_fingerprint".format(specs[0].cuda_compile_info.filename),
+            cmd_args(specs[0].original_cmd, specs[0].argsfile_args, quote = "shell"),
+            allow_args = True,
+            has_content_based_path = specs[0].cuda_compile_info.uses_content_based_paths,
+            use_dep_files_placeholder_for_content_based_paths = True,
+        )
+
+    actions.dynamic_output_new(
+        _nvcc_dynamic_compile_rule(
+            toolchain = toolchain,
+            cuda_compile_infos = [spec.cuda_compile_info for spec in specs],
+            srcs = [spec.src for spec in specs],
+            allow_cache_upload = allow_cache_upload,
+            cuda_cxx_compile_inputs = cuda_cxx_compile_inputs,
+            headers_dep_files = headers_dep_files,
+            original_cmds = [spec.original_cmd for spec in specs],
+            hostcc_argsfile = cuda_dist_output.hostcc_argsfile,
+            hostcc_argsfile_fingerprint = hostcc_argsfile_fingerprint,
+            file_prefix_specs = specs[0].file_prefix_specs,
+            plan_artifact = cuda_dist_output.nvcc_dag,
+            env_artifact = cuda_dist_output.nvcc_env,
+            output_declared_artifacts = [spec.output_declared_artifact for spec in specs],
+        )
+    )
+
+def _create_file_to_artifact_map(
+    actions: AnalysisActions,
+    plan_json: list[dict[str, typing.Any]],
+    src: Artifact,
+    cuda_compile_info: CudaCompileInfo,
+    output_declared_artifact: OutputArtifact,
+    uses_content_based_paths: bool,
+) -> dict[str, Artifact | OutputArtifact]:
+    # Create artifacts for all intermediate input and output files.
+    file2artifact = {}
+    for cmd_node in plan_json:
+        node_inputs = cmd_node["inputs"]
+        node_outputs = cmd_node["outputs"]
+        for input in node_inputs:
+            if input not in file2artifact:
+                if input.endswith(".cu"):
+                    file2artifact[input] = src
+                else:
+                    input_artifact = actions.declare_output(
+                        "__cuda_intermediates__",
+                        "{}/{}".format(cuda_compile_info.filename, input),
+                        has_content_based_path = uses_content_based_paths,
+                    )
+                    file2artifact[input] = input_artifact
+        for output in node_outputs:
+            if output not in file2artifact:
+                if output.endswith(".o"):
+                    file2artifact[output] = output_declared_artifact
+                else:
+                    output_artifact = actions.declare_output(
+                        "__cuda_intermediates__",
+                        "{}/{}".format(cuda_compile_info.filename, output),
+                        has_content_based_path = uses_content_based_paths,
+                    )
+                    file2artifact[output] = output_artifact
+    return file2artifact
+
+def _create_nvcc_subcmd_env(env_artifact: ArtifactValue) -> dict[str, str]:
+    # Create the nvcc envvars for the sub-commands.
+    subcmd_env = {}
+    for line in env_artifact.read_string().splitlines():
+        key, value = line.split("=", 1)
+        subcmd_env[key] = value
+    return subcmd_env
+
+def _include_symlinked_stubs_dir(
+    actions: AnalysisActions,
+    cuda_compile_info: CudaCompileInfo,
+    file2artifact: dict[str, typing.Any],
+    subcmd: cmd_args,
+) -> None:
+    """
+    .cudafe1.stub.c and .fatbin.c files are hardcoded into the cudafe1.cpp file
+    and its includes like below:
+
+    #include "add.cu.o.compute_90a.cudafe1.stub.c"
+
+    Before content-based hashing, this worked fine because all outputs were under
+    the same directory. However, with content-based hashing this no longer works
+    because the output files are put under the output_artifacts sub-directory.
+
+    Fix this by creating a directory containing symlinks to the actual stubs, and
+    adding it to the cuda_cxx_compile include search path.
+    """
+    stubs_dir = actions.declare_output(
+        "__stubs__",
+        cuda_compile_info.filename,
+        dir = True,
+        has_content_based_path = True,
+    )
+    stubs = {}
+    for file, artifact in file2artifact.items():
+        if file.endswith(".cudafe1.stub.c") or file.endswith(".fatbin.c"):
+            # Remove the parent paths because the includes are the filenames only.
+            # Each stubs directory is scoped to one CUDA source file.
+            stubs[artifact.basename] = artifact
+    symlinked_dir = actions.symlinked_dir(
+        stubs_dir,
+        stubs,
+        has_content_based_path = True,
+    )
+    subcmd.add(cmd_args(symlinked_dir, format = "-I{}"))
+
+def _prepare_cuda_command(cmd_node: dict[str, typing.Any], hostcc_wp_form: cmd_args, specs_form: cmd_args | None) -> PreparedCudaCommand:
+    parts = []
+    common = cmd_args()
+    for token in cmd_node["cmd"][1:]:
+        placeholder = None
+        if "{input}" in token:
+            placeholder = "input"
+        elif "{output}" in token:
+            placeholder = "output"
+        elif "{source_path}" in token:
+            placeholder = "source_path"
+
+        if placeholder != None:
+            parts.append(("common", common))
+            left, right = token.split("{" + placeholder + "}", 1)
+
+            # Replay substitutes exactly one placeholder per token; a second
+            # one would be passed through literally.
+            for kind in ("input", "output", "source_path"):
+                if "{" + kind + "}" in left + right:
+                    fail("plan token carries multiple placeholders: {}".format(token))
+            parts.append((placeholder, (left, right)))
+            common = cmd_args()
+        elif token.startswith("-Wp,@"):
+            common.add(hostcc_wp_form)
+        elif token == "{file_prefix_specs}":
+            if specs_form == None:
+                fail("CUDA plan references file-prefix specs without a specs artifact")
+            common.add(specs_form)
+        else:
+            common.add(token)
+    parts.append(("common", common))
+    return PreparedCudaCommand(cmd_node = cmd_node, exe = cmd_node["cmd"][0], parts = parts)
+
+def _cuda_replay_input_kind(category: str) -> str:
+    # Device phase categories appear both arch-suffixed (`cuda_opt_sm90a`) and
+    # bare: the plan parser emits the bare form whenever an intermediate file
+    # name carries no compute_{arch} component, e.g. for arch suffixes its
+    # normalization does not recognize.
+    if category == "cuda_host_preproc" or category == "cuda_device_preproc" or category.startswith("cuda_device_preproc_"):
+        return "preprocess"
+    if category == "cuda_cxx_compile":
+        return "host_compile"
+    if category in ("cudafepp", "cuda_fatbin", "cuda_opt", "cuda_cubin_lower") or category.startswith("cuda_opt_") or category.startswith("cuda_cubin_lower_"):
+        return "cuda_tool"
+    fail("Unsupported distributed CUDA phase category `{}`; update its input policy".format(category))
+
+def _nvcc_dynamic_compile(
+    actions: AnalysisActions,
+    toolchain: CxxToolchainInfo,
+    cuda_compile_infos: list[CudaCompileInfo],
+    srcs: list[Artifact],
+    allow_cache_upload: bool,
+    cuda_cxx_compile_inputs: cmd_args,
+    headers_dep_files: HeadersDepFiles | None,
+    original_cmds: list[cmd_args],
+    hostcc_argsfile: Artifact,
+    hostcc_argsfile_fingerprint: Artifact | None,
+    file_prefix_specs: Artifact | None,
+    plan_artifact: ArtifactValue,
+    env_artifact: ArtifactValue,
+    output_declared_artifacts: list[OutputArtifact],
+) -> list[Provider]:
+    num_sources = len(cuda_compile_infos)
+    if len(srcs) != num_sources or len(original_cmds) != num_sources or len(output_declared_artifacts) != num_sources:
+        fail(
+            "per-source dist CUDA lists must be the same length, got {}/{}/{}/{}".format(
+                len(cuda_compile_infos),
+                len(srcs),
+                len(original_cmds),
+                len(output_declared_artifacts),
+            )
+        )
+
+    plan = plan_artifact.read_json()
+    subcmd_env = _create_nvcc_subcmd_env(env_artifact)
+
+    # The plan is shared across the target's sources, so these references are
+    # built once from the representative source. Tagging lets dep-file filtering
+    # drop their paths from each sub-action key; the untagged fingerprint is what
+    # still reruns the sub-actions when a flag changes.
+    if headers_dep_files != None and hostcc_argsfile_fingerprint != None:
+        hostcc_wp_form = cmd_args(
+            headers_dep_files.tag.tag_artifacts(hostcc_argsfile),
+            format = "-Wp,@{}",
+            hidden = [hostcc_argsfile_fingerprint],
+        )
+    else:
+        hostcc_wp_form = cmd_args(hostcc_argsfile, format = "-Wp,@{}")
+
+    specs_form = None
+    if file_prefix_specs != None:
+        if headers_dep_files != None:
+            specs_form = cmd_args(
+                headers_dep_files.tag.tag_artifacts(file_prefix_specs),
+                format = "-specs={}",
+            )
+        else:
+            specs_form = cmd_args(file_prefix_specs, format = "-specs={}")
+
+    prepared_commands = [_prepare_cuda_command(cmd_node, hostcc_wp_form, specs_form) for cmd_node in plan]
+    cuda_toolchain = getattr(toolchain.cuda_compiler_info, "compiler_for_dryrun", None) or toolchain.cuda_compiler_info.compiler
+    cuda_tool_inputs = cmd_args(hidden = [cuda_toolchain])
+
+    for cuda_compile_info, src, original_cmd, output_declared_artifact in zip(
+        cuda_compile_infos,
+        srcs,
+        original_cmds,
+        output_declared_artifacts,
+    ):
+        content_based = cuda_compile_info.uses_content_based_paths
+        file2artifact = _create_file_to_artifact_map(
+            actions,
+            plan,
+            src,
+            cuda_compile_info,
+            output_declared_artifact,
+            content_based,
+        )
+
+        category_counts = {}
+        for prepared in prepared_commands:
+            cmd_node = prepared.cmd_node
+            subcmd = cmd_args()
+            exe = prepared.exe
+            input_kind = _cuda_replay_input_kind(cmd_node["category"])
+            if input_kind == "preprocess":
+                subcmd.add(cmd_args(hidden = original_cmd))
+            elif input_kind == "host_compile":
+                subcmd.add(cmd_args(hidden = cuda_cxx_compile_inputs))
+            else:
+                subcmd.add(cuda_tool_inputs)
+
+            if "ptxas" in exe:
+                # Ptxas occasionally produces an empty output. The root cause
+                # is unknown as we're unable to reproduce it locally. Check the
+                # output is not empty
+                subcmd.add(toolchain.internal_tools.check_nonempty_output)
+            subcmd.add(exe)
+
+            # The stubs directory must lead the include path so its generated
+            # stub files shadow any same-named file in later include dirs.
+            if content_based and cmd_node["category"] == "cuda_cxx_compile":
+                _include_symlinked_stubs_dir(actions, cuda_compile_info, file2artifact, subcmd)
+
+            input_index = 0
+            output_index = 0
+            for kind, value in prepared.parts:
+                if kind == "common":
+                    subcmd.add(value)
+                elif kind == "input":
+                    input = cmd_node["inputs"][input_index]
+                    input_index += 1
+                    subcmd.add(cmd_args([value[0], file2artifact[input], value[1]], delimiter = ""))
+                elif kind == "output":
+                    output = cmd_node["outputs"][output_index]
+                    output_index += 1
+                    artifact = file2artifact[output]
+                    bindable = artifact.as_output() if isinstance(artifact, Artifact) else artifact
+                    subcmd.add(cmd_args([value[0], bindable, value[1]], delimiter = ""))
+                elif kind == "source_path":
+                    # The contents of the `source_path` files are not actually
+                    # used as inputs to the sub-action, they are used primarily
+                    # to name the actual source path for inclusion in things like
+                    # DWARF information. However, artifacts with content-based-paths
+                    # can't know their paths until their content is known, so they
+                    # cannot be included as ignore_artifacts=True
+                    # TODO(jtbraun): when has_content_based_path is available,
+                    # use that as the condition here
+                    if src.is_source:
+                        subcmd.add(cmd_args([value[0], src, value[1]], delimiter = "", ignore_artifacts = True))
+                    else:
+                        subcmd.add(cmd_args([value[0], src, value[1]], delimiter = ""))
+                else:
+                    fail("unhandled placeholder kind: {}".format(kind))
+
+            # Some nodes have hidden dependencies (deps that don't appear in
+            # the cmd). Add them to the hidden field of cmd_args.
+            if cmd_node["hidden"]:
+                subcmd.add(cmd_args(hidden = [file2artifact[f] for f in cmd_node["hidden"]]))
+
+            # Host-compiler sub-actions pin a declared header closure; dep files
+            # let the compiler report what it actually read so buck can prune the
+            # rest from the action key.
+            action_dep_files = {}
+            if input_kind != "cuda_tool" and headers_dep_files != None:
+                # Categories can repeat within a plan, so disambiguate with a
+                # per-category ordinal.
+                ordinal = category_counts.get(cmd_node["category"], 0)
+                category_counts[cmd_node["category"]] = ordinal + 1
+                subcmd = add_headers_dep_files(
+                    actions,
+                    subcmd,
+                    headers_dep_files,
+                    src,
+                    "{}/{}/{}".format(cuda_compile_info.filename, cmd_node["category"], ordinal),
+                    action_dep_files,
+                )
+
+            actions.run(
+                subcmd,
+                category = cmd_node["category"],
+                env = subcmd_env,
+                identifier = cuda_compile_info.identifier,
+                dep_files = action_dep_files,
+                allow_cache_upload = allow_cache_upload,
+                allow_dep_file_cache_upload = False,
+                prefer_remote = True if "preproc" in cmd_node["category"] else False,
+            )
+
+    return [DefaultInfo()]
+
+_nvcc_dynamic_compile_rule = dynamic_actions(
+    impl = _nvcc_dynamic_compile,
+    attrs = {
+        "allow_cache_upload": dynattrs.value(bool),
+        "cuda_compile_infos": dynattrs.list(dynattrs.value(CudaCompileInfo)),
+        "cuda_cxx_compile_inputs": dynattrs.value(cmd_args),
+        "env_artifact": dynattrs.artifact_value(),
+        "file_prefix_specs": dynattrs.option(dynattrs.value(Artifact)),
+        "headers_dep_files": dynattrs.option(dynattrs.value(HeadersDepFiles)),
+        "hostcc_argsfile": dynattrs.value(Artifact),
+        "hostcc_argsfile_fingerprint": dynattrs.option(dynattrs.value(Artifact)),
+        "original_cmds": dynattrs.list(dynattrs.value(cmd_args)),
+        "output_declared_artifacts": dynattrs.list(dynattrs.output()),
+        "plan_artifact": dynattrs.artifact_value(),
+        "srcs": dynattrs.list(dynattrs.value(Artifact)),
+        "toolchain": dynattrs.value(CxxToolchainInfo),
+    },
+)
diff --git a/buck2/prelude/cxx/cxx.bzl b/buck2/prelude/cxx/cxx.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx.bzl
@@ -0,0 +1,1168 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//:resources.bzl",
+    "gather_resources",
+    "make_resource_info",
+)
+load(
+    "@prelude//android:android_providers.bzl",
+    "merge_android_packageable_info",
+)
+load("@prelude//apple:resource_groups.bzl", "create_resource_graph")
+load(
+    "@prelude//cxx:compile_types.bzl",
+    "UseHeaderUnitsMode",
+)
+load(
+    "@prelude//cxx:cuda.bzl",
+    "CudaCompileStyle",
+)
+load("@prelude//cxx:cxx_flags.bzl", "cxx_attr_flags")
+load("@prelude//cxx:cxx_sources.bzl", "get_srcs_with_flags")
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "RuntimeDependencyHandling",
+    "ShlibInterfacesMode",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload", "cxx_attrs_use_fbcc_rust_wrapper")
+load(
+    "@prelude//cxx:link_groups_types.bzl",
+    "LinkGroupInfo",  # @unused Used as a type
+)
+# @oss-disable[end= ]: load("@prelude//cxx/meta_only:linker_outputs.bzl", "get_extra_linker_output_flags", "get_extra_linker_outputs")
+load("@prelude//graphql:graphql.bzl", "graphql_providers")
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference")
+load(
+    "@prelude//linking:link_groups.bzl",
+    "merge_link_group_lib_info",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "Archive",
+    "ArchiveLinkable",
+    "CxxSanitizerRuntimeInfo",
+    "LibOutputStyle",
+    "LinkArgs",
+    "LinkCommandDebugOutputInfo",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkStrategy",
+    "LinkedObject",
+    "SharedLibLinkable",
+    "create_merged_link_info",
+    "create_merged_link_info_for_propagation",
+    "get_lib_output_style",
+    "get_link_args_for_strategy",
+    "get_output_styles_for_linkage",
+    "subtarget_for_output_style",
+    "to_link_strategy",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "DLOPENABLE_LIBRARY_INFO_MARKER",
+    "LinkableGraph",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+    "create_linkable_node",
+)
+load(
+    "@prelude//linking:linkables.bzl",
+    "linkables",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraries",
+    "SharedLibraryInfo",
+    "create_shlib_from_ctx",
+    "extract_soname_from_shlib",
+    "merge_shared_libraries",
+    "to_soname",
+)
+load("@prelude//linking:strip.bzl", "strip_debug_info")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//python:manifest.bzl", "create_manifest_for_entries")
+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")
+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+load(
+    "@prelude//tests:re_utils.bzl",
+    "get_re_executors_from_props",
+)
+load(
+    "@prelude//third-party:build.bzl",
+    "create_third_party_build_info",
+)
+load(
+    "@prelude//third-party:providers.bzl",
+    "ThirdPartyBuildInfo",
+)
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    "@prelude//utils:utils.bzl",
+    "filter_and_map_idx",
+    "value_or",
+)
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+load(":cxx_executable.bzl", "cxx_executable")
+load(
+    ":cxx_library.bzl",
+    "CxxLibraryOutput",  # @unused Used as a type
+    "cxx_library_parameterized",
+)
+load(
+    ":cxx_library_utility.bzl",
+    "cxx_attr_dep_metadata",
+    "cxx_attr_deps",
+    "cxx_attr_exported_deps",
+    "cxx_attr_link_style",
+    "cxx_attr_linker_flags_all",
+    "cxx_attr_preferred_linkage",
+    "cxx_attr_use_content_based_paths",
+    "cxx_inherited_link_info",
+    "cxx_platform_supported",
+    "cxx_use_shlib_intfs_mode",
+)
+load(
+    ":cxx_types.bzl",
+    "CxxRuleConstructorParams",
+    "CxxRuleProviderParams",
+    "CxxRuleSubTargetParams",
+    "LinkPreference",
+    "xcode_data_enabled",
+)
+load(":gcno.bzl", "GcnoFilesInfo")
+load(
+    ":groups_types.bzl",
+    "Group",
+    "MATCH_ALL_LABEL",
+    "NO_MATCH_LABEL",
+)
+load(
+    ":headers.bzl",
+    "CPrecompiledHeaderInfo",
+    "cxx_attr_headers_list",
+    "cxx_get_regular_cxx_headers_layout",
+)
+load(
+    ":link.bzl",
+    "cxx_link_shared_library",
+)
+load(
+    ":link_groups.bzl",
+    "LinkGroupLibSpec",
+    "get_link_group_info",
+)
+load(
+    ":link_types.bzl",
+    "link_options",
+)
+load(
+    ":linker.bzl",
+    "DUMPBIN_SUB_TARGET",
+    "IMPORT_LIBRARY_SUB_TARGET",
+    "PDB_SUB_TARGET",
+    "get_dumpbin_providers",
+    "get_link_whole_args",
+    "get_pdb_providers",
+    "get_shared_library_name",
+    "get_shared_library_name_for_param",
+    "sandbox_exported_linker_flags",
+)
+load(
+    ":omnibus.bzl",
+    "create_linkable_root",
+)
+load(
+    ":preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorArgs",
+    "cxx_exported_preprocessor_info",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+    "format_system_include_arg",
+)
+load(
+    ":shared_library_interface.bzl",
+    "shared_library_interface",
+)
+
+#####################################################################
+# Operations
+
+def _get_use_header_units_mode(use_header_units: bool | str) -> UseHeaderUnitsMode:
+    """Convert the use_header_units attribute to UseHeaderUnitsMode enum."""
+    if use_header_units == True:
+        return UseHeaderUnitsMode("pcm")
+    elif use_header_units == "stub":
+        return UseHeaderUnitsMode("stub")
+    else:
+        return UseHeaderUnitsMode("none")
+
+def _get_shared_link_style_sub_targets_and_providers(
+    output_style: LibOutputStyle, ctx: AnalysisContext, output: [CxxLibraryOutput, None]
+) -> (dict[str, list[Provider]], list[Provider]):
+    if output_style != LibOutputStyle("shared_lib") or output == None:
+        return ({}, [])
+    sub_targets = {}
+    providers = []
+    if output.dwp != None:
+        sub_targets["dwp"] = [DefaultInfo(default_output = output.dwp)]
+    if output.hip_arch_debug_files:
+        all_files = [f for files in output.hip_arch_debug_files.values() for f in files]
+        sub_targets["hip_debug"] = [
+            DefaultInfo(
+                default_outputs = all_files,
+                sub_targets = {arch: [DefaultInfo(default_outputs = files)] for arch, files in output.hip_arch_debug_files.items()},
+            ),
+        ]
+    if output.pdb != None:
+        sub_targets[PDB_SUB_TARGET] = get_pdb_providers(pdb = output.pdb, binary = output.default)
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    if cxx_toolchain.dumpbin_toolchain_path != None:
+        sub_targets[DUMPBIN_SUB_TARGET] = get_dumpbin_providers(ctx, output.default, cxx_toolchain.dumpbin_toolchain_path)
+    if output.linker_map != None:
+        sub_targets["linker-map"] = [DefaultInfo(default_output = output.linker_map.map, other_outputs = [output.linker_map.binary])]
+    if output.implib != None:
+        sub_targets[IMPORT_LIBRARY_SUB_TARGET] = [DefaultInfo(default_output = output.implib)]
+    return (sub_targets, providers)
+
+def cxx_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    return cxx_library_generate(ctx, "cxx_library")
+
+def cxx_library_generate(ctx: AnalysisContext, rule_type: str) -> list[Provider]:
+    if ctx.attrs.can_be_asset and ctx.attrs.used_by_wrap_script:
+        fail("Cannot use `can_be_asset` and `used_by_wrap_script` in the same rule")
+
+    if ctx.attrs._is_building_android_binary:
+        sub_target_params, provider_params = _get_params_for_android_binary_cxx_library()
+    else:
+        sub_target_params = CxxRuleSubTargetParams(xcode_data = xcode_data_enabled())
+        provider_params = CxxRuleProviderParams(
+            third_party_build = True,
+        )
+
+    params = CxxRuleConstructorParams(
+        rule_type = rule_type,
+        headers_layout = cxx_get_regular_cxx_headers_layout(ctx),
+        srcs = get_srcs_with_flags(ctx),
+        output_style_sub_targets_and_providers_factory = _get_shared_link_style_sub_targets_and_providers,
+        generate_sub_targets = sub_target_params,
+        generate_providers = provider_params,
+        compiler_flags = ctx.attrs.compiler_flags,
+        cxx_flags = cxx_attr_flags(ctx),
+        lang_compiler_flags = ctx.attrs.lang_compiler_flags,
+        preprocessor_flags = ctx.attrs.preprocessor_flags,
+        lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,
+        use_header_units = _get_use_header_units_mode(ctx.attrs.use_header_units),
+        export_header_unit = ctx.attrs.export_header_unit,
+        export_header_unit_filter = ctx.attrs.export_header_unit_filter,
+        error_handler = get_cxx_toolchain_info(ctx).cxx_error_handler,
+        extra_dwp_flags = ctx.attrs.extra_dwp_flags,
+        use_fbcc_rust_wrapper = cxx_attrs_use_fbcc_rust_wrapper(ctx.attrs),
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),
+        precompiled_header = ctx.attrs.precompiled_header,
+        prefix_header = ctx.attrs.prefix_header,
+        _cxx_toolchain = ctx.attrs._cxx_toolchain,
+        use_content_based_paths = cxx_attr_use_content_based_paths(ctx),
+        coverage_instrumentation_compiler_flags = ctx.attrs.coverage_instrumentation_compiler_flags,
+        coverage_profile_list = ctx.attrs.coverage_profile_list[DefaultInfo].default_outputs[0] if ctx.attrs.coverage_profile_list else None,
+        separate_debug_info = ctx.attrs.separate_debug_info,
+        cuda_compile_style = CudaCompileStyle(ctx.attrs.cuda_compile_style),
+        # @oss-disable[end= ]: extra_linker_outputs_factory = get_extra_linker_outputs,
+        # @oss-disable[end= ]: extra_linker_outputs_flags_factory = get_extra_linker_output_flags,
+        supports_stripping = ctx.attrs.supports_stripping,
+        expect_eligible_for_dedupe = getattr(ctx.attrs, "expect_eligible_for_dedupe", False),
+    )
+    output = cxx_library_parameterized(ctx, params)
+    return output.providers + graphql_providers(ctx)
+
+def _only_shared_mappings(group: Group) -> bool:
+    """
+    Return whether this group only has explicit "shared" linkage mappings,
+    which indicates a group that re-uses pre-linked libs.
+    """
+    for mapping in group.mappings:
+        if mapping.preferred_linkage != Linkage("shared"):
+            return False
+    return True
+
+def create_shared_lib_link_group_specs(ctx: AnalysisContext, link_group_definitions: list[Group]) -> list[LinkGroupLibSpec]:
+    specs = []
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    for group in link_group_definitions:
+        if group.name in (MATCH_ALL_LABEL, NO_MATCH_LABEL):
+            continue
+
+        # TODO(agallagher): We should probably add proper handling for "provided"
+        # system handling to avoid needing this special case.
+        if _only_shared_mappings(group):
+            continue
+        specs.append(
+            LinkGroupLibSpec(
+                name = get_shared_library_name(linker_info, group.name, apply_default_prefix = True),
+                is_shared_lib = True,
+                group = group,
+            ),
+        )
+    return specs
+
+def get_auto_link_group_specs(ctx: AnalysisContext, link_group_info: [LinkGroupInfo, None]) -> [list[LinkGroupLibSpec], None]:
+    if link_group_info == None or not ctx.attrs.auto_link_groups:
+        return None
+    return create_shared_lib_link_group_specs(ctx, link_group_info.groups.values())
+
+def cxx_binary_impl(ctx: AnalysisContext) -> list[Provider]:
+    link_strategy = to_link_strategy(cxx_attr_link_style(ctx))
+    link_group_info = get_link_group_info(
+        ctx,
+        filter_and_map_idx(LinkableGraph, cxx_attr_deps(ctx)),
+        link_strategy,
+    )
+    params = CxxRuleConstructorParams(
+        rule_type = "cxx_binary",
+        generate_sub_targets = CxxRuleSubTargetParams(xcode_data = xcode_data_enabled()),
+        executable_name = ctx.attrs.executable_name,
+        headers_layout = cxx_get_regular_cxx_headers_layout(ctx),
+        srcs = get_srcs_with_flags(ctx),
+        link_group_info = link_group_info,
+        auto_link_group_specs = get_auto_link_group_specs(ctx, link_group_info),
+        prefer_stripped_objects = ctx.attrs.prefer_stripped_objects,
+        exe_allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs),
+        extra_link_roots = linkables(ctx.attrs.link_group_deps),
+        compiler_flags = ctx.attrs.compiler_flags,
+        cxx_flags = cxx_attr_flags(ctx),
+        lang_compiler_flags = ctx.attrs.lang_compiler_flags,
+        preprocessor_flags = ctx.attrs.preprocessor_flags,
+        lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,
+        use_header_units = _get_use_header_units_mode(ctx.attrs.use_header_units),
+        runtime_dependency_handling = RuntimeDependencyHandling(ctx.attrs.runtime_dependency_handling)
+        if ctx.attrs.runtime_dependency_handling
+        else get_cxx_toolchain_info(ctx).runtime_dependency_handling,
+        error_handler = get_cxx_toolchain_info(ctx).cxx_error_handler,
+        extra_dwp_flags = ctx.attrs.extra_dwp_flags,
+        use_fbcc_rust_wrapper = cxx_attrs_use_fbcc_rust_wrapper(ctx.attrs),
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),
+        precompiled_header = ctx.attrs.precompiled_header,
+        prefix_header = ctx.attrs.prefix_header,
+        _cxx_toolchain = ctx.attrs._cxx_toolchain,
+        use_content_based_paths = cxx_attr_use_content_based_paths(ctx),
+        coverage_instrumentation_compiler_flags = ctx.attrs.coverage_instrumentation_compiler_flags,
+        coverage_profile_list = ctx.attrs.coverage_profile_list[DefaultInfo].default_outputs[0] if ctx.attrs.coverage_profile_list else None,
+        separate_debug_info = ctx.attrs.separate_debug_info,
+        cuda_compile_style = CudaCompileStyle(ctx.attrs.cuda_compile_style),
+        link_preference = LinkPreference(ctx.attrs.link_preference),
+        # @oss-disable[end= ]: extra_linker_outputs_factory = get_extra_linker_outputs,
+        # @oss-disable[end= ]: extra_linker_outputs_flags_factory = get_extra_linker_output_flags,
+    )
+    output = cxx_executable(ctx, params)
+
+    extra_providers = []
+    if output.link_command_debug_output:
+        extra_providers.append(LinkCommandDebugOutputInfo(debug_outputs = [output.link_command_debug_output]))
+    if output.sanitizer_runtime_files:
+        extra_providers.append(CxxSanitizerRuntimeInfo(runtime_files = output.sanitizer_runtime_files))
+    if output.validation_specs:
+        extra_providers.append(ValidationInfo(validations = output.validation_specs))
+    if output.xplugins_debug_artifacts_info:
+        extra_providers.append(output.xplugins_debug_artifacts_info)
+
+    if get_cxx_toolchain_info(ctx).gcno_files and output.gcno_files:
+        extra_providers.append(GcnoFilesInfo(gcno_files = output.gcno_files))
+
+    # Unix env provider.
+    extra_providers.append(
+        create_unix_env_info(
+            actions = ctx.actions,
+            env = UnixEnv(
+                label = ctx.label,
+                binaries = [
+                    create_manifest_for_entries(
+                        ctx = ctx,
+                        name = "unix_env",
+                        entries = [
+                            (ctx.label.name, output.binary, ""),
+                        ],
+                    ),
+                ],
+            ),
+            # TODO(agallagher): We only want to traverse deps when dynamically
+            # linking.
+            # deps = ctx.attrs.deps,
+        ),
+    )
+
+    # When an executable is the output of a build, also materialize all the
+    # unpacked external debuginfo that goes with it. This makes `buck2 build
+    # :main` equivalent to `buck2 build :main :main[debuginfo]`.
+    #
+    # This is wasted work if we are building an executable together with its dwp
+    # subtarget (`buck2 build :main :main[dwp]`) in which case a large number of
+    # unpacked debuginfo files can end up being materialized redundantly. LLDB
+    # will ignore them and obtain debuginfo via the single packed debuginfo file
+    # instead.
+    #
+    # But materializing unpacked debuginfo is usually the right tradeoff
+    # because it means the output of `buck2 build :main` is always immediately
+    # usable in a debugger. Toolchains whose debugging workflow materializes
+    # debuginfo on demand instead (via the `[debuginfo]` or `[dwp]`
+    # sub-targets) can opt out with `materialize_external_debug_info = False`.
+    #
+    # External debuginfo is *not* materialized when an executable is depended on
+    # by another rule, such as by $(exe ...) or exec_dep.
+    other_outputs = output.runtime_files + (output.external_debug_info_artifacts if get_cxx_toolchain_info(ctx).materialize_external_debug_info else [])
+
+    return (
+        filter(
+            None,
+            [
+                DefaultInfo(
+                    default_output = output.binary,
+                    other_outputs = other_outputs,
+                    sub_targets = output.sub_targets,
+                ),
+                RunInfo(args = cmd_args(output.binary, hidden = output.runtime_files)),
+                output.compilation_db,
+                output.xcode_data,
+                output.dist_info,
+            ],
+        )
+        + extra_providers
+    )
+
+def _prebuilt_item(_ctx: AnalysisContext, item: [typing.Any, None]) -> [typing.Any, None]:
+    """
+    Return the item if it's set.
+    """
+    return item
+
+def _prebuilt_linkage(ctx: AnalysisContext) -> Linkage:
+    """
+    Construct the preferred linkage to use for the given prebuilt library.
+    """
+    if ctx.attrs.header_only:
+        return Linkage("any")
+    if ctx.attrs.force_static:
+        return Linkage("static")
+    preferred_linkage = cxx_attr_preferred_linkage(ctx)
+    if preferred_linkage != Linkage("any"):
+        return preferred_linkage
+    if ctx.attrs.provided:
+        return Linkage("shared")
+    return Linkage("any")
+
+def _create_prebuilt_library_outputs(
+    ctx: AnalysisContext,
+    static_lib,
+    static_pic_lib,
+    shared_lib,
+    static_lib_stripped,
+    static_pic_lib_stripped,
+    soname,
+    linker_type,
+    linker_flags,
+    inherited_exported_link,
+    header_dirs,
+    propagated_preprocessor,
+    propagate_shared_libs: bool,
+):
+    """
+    Create outputs for all output styles of a prebuilt library.
+
+    Returns a struct with:
+      - outputs: dict of output_style -> artifact
+      - libraries: dict of output_style -> LinkInfos
+      - solibs: list of shared libraries
+      - sub_targets: dict of sub-target names -> providers
+      - generated_shared_lib: whether the shared lib was created via a link rule
+
+    Args:
+        propagate_shared_libs: Whether to propagate shared libraries via SharedLibraryInfo.
+            Should be True only if the library's preferred linkage allows shared linking.
+    """
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+
+    # Gather link infos, outputs, and shared libs for all output styles.
+    outputs = {}
+    libraries = {}
+    solibs = []
+    sub_targets = {}
+    generated_shared_lib = False  # whether the shared lib is created via a link rule
+
+    # Generate outputs for ALL output styles (not just those for a specific preferred_linkage)
+    for output_style in [LibOutputStyle("archive"), LibOutputStyle("pic_archive"), LibOutputStyle("shared_lib")]:
+        out = None
+        linkable = None
+        linkable_stripped = None
+
+        # If we have sources to compile, generate the necessary libraries and
+        # add them to the exported link info.
+        if not ctx.attrs.header_only:
+
+            def archive_linkable(lib):
+                return ArchiveLinkable(
+                    archive = Archive(artifact = lib),
+                    linker_type = linker_type,
+                    link_whole = ctx.attrs.link_whole,
+                    supports_lto = ctx.attrs.supports_lto,
+                )
+
+            if output_style == LibOutputStyle("archive"):
+                if static_lib:
+                    out = static_lib
+                    linkable = archive_linkable(static_lib)
+                    linkable_stripped = archive_linkable(static_lib_stripped) if static_lib_stripped else None
+            elif output_style == LibOutputStyle("pic_archive"):
+                lib = static_pic_lib or static_lib
+                if lib:
+                    out = lib
+                    linkable = archive_linkable(lib)
+                    linkable_stripped = (
+                        archive_linkable(static_pic_lib_stripped or static_lib_stripped) if (static_pic_lib_stripped or static_lib_stripped) else None
+                    )
+            else:  # shared
+                # If no shared library was provided, link one from the static libraries.
+                if shared_lib != None:
+                    shared_lib = LinkedObject(output = shared_lib, unstripped_output = shared_lib)
+                else:
+                    lib = static_pic_lib or static_lib
+                    if lib:
+                        shlink_args = []
+
+                        # TODO(T110378143): Support post link flags properly.
+                        shlink_args.extend(linker_flags.exported_flags)
+                        shlink_args.extend(linker_flags.flags)
+                        shlink_args.extend(get_link_whole_args(linker_type, [lib]))
+
+                        # TODO(T110378118): As per v1, we always link against "shared"
+                        # dependencies when building a shaerd library.
+                        shared_link_args = get_link_args_for_strategy(
+                            ctx.actions,
+                            ctx.label,
+                            linker_info,
+                            inherited_exported_link,
+                            LinkStrategy("shared"),
+                            prefer_stripped = False,
+                            transformation_spec_context = None,
+                        )
+                        link_result = cxx_link_shared_library(
+                            ctx = ctx,
+                            output = soname.ensure_str(),
+                            name = soname.ensure_str(),
+                            opts = link_options(
+                                links = [
+                                    LinkArgs(flags = shlink_args),
+                                    shared_link_args,
+                                ],
+                                link_execution_preference = LinkExecutionPreference("any"),
+                            ),
+                        )
+                        shared_lib = link_result.linked_object
+                        generated_shared_lib = True
+
+                if shared_lib:
+                    out = shared_lib.output
+
+                    shared_lib_for_linking = shared_lib.output
+
+                    # Generate a shared library interface if the rule supports it.
+                    # TODO: We should not permit both modes, but to keep builds green we have to for now.
+                    if ctx.attrs.supports_shared_library_interface and (
+                        cxx_use_shlib_intfs_mode(ctx, ShlibInterfacesMode("defined_only"))
+                        or cxx_use_shlib_intfs_mode(ctx, ShlibInterfacesMode("stub_from_library"))
+                    ):
+                        shared_lib_for_linking = shared_library_interface(
+                            ctx = ctx,
+                            shared_lib = shared_lib.output,
+                        )
+                    if ctx.attrs._target_os_type[OsLookup].os == Os("windows"):
+                        shared_lib_for_linking = ctx.attrs.import_lib
+
+                    linkable = None
+                    if shared_lib_for_linking != None:
+                        linkable = SharedLibLinkable(
+                            lib = shared_lib_for_linking,
+                            # Some prebuilt shared libs don't set a SONAME (e.g.
+                            # IntelComposerXE), so we can't link them via just the shared
+                            # lib (otherwise, we may embed build-time paths in `DT_NEEDED`
+                            # tags).
+                            link_without_soname = ctx.attrs.link_without_soname,
+                        )
+
+                    # Provided means something external to the build will provide
+                    # the libraries, so we don't need to propagate anything.
+                    if not ctx.attrs.provided and propagate_shared_libs:
+                        solibs.append(
+                            create_shlib_from_ctx(
+                                ctx = ctx,
+                                lib = shared_lib,
+                                soname = soname,
+                            ),
+                        )
+
+                    # Provide a sub-target that always provides the shared lib
+                    # using the soname.
+                    if soname and soname.is_str and shared_lib.output.basename != paths.basename(soname.ensure_str()):
+                        soname_lib = ctx.actions.copy_file(soname.ensure_str(), shared_lib.output, has_content_based_path = False)
+                    else:
+                        soname_lib = shared_lib.output
+                    sub_targets["soname-lib"] = [DefaultInfo(default_output = soname_lib)]
+
+                    if shared_lib.pdb:
+                        sub_targets[PDB_SUB_TARGET] = get_pdb_providers(pdb = shared_lib.pdb, binary = shared_lib.output)
+                    dumpbin_toolchain_path = get_cxx_toolchain_info(ctx).dumpbin_toolchain_path
+                    if dumpbin_toolchain_path != None:
+                        sub_targets[DUMPBIN_SUB_TARGET] = get_dumpbin_providers(ctx, shared_lib.output, dumpbin_toolchain_path)
+                    if shared_lib.dwp != None:
+                        sub_targets["dwp"] = [DefaultInfo(default_output = shared_lib.dwp)]
+                    if shared_lib.hip_arch_debug_files:
+                        all_files = [f for files in shared_lib.hip_arch_debug_files.values() for f in files]
+                        sub_targets["hip_debug"] = [
+                            DefaultInfo(
+                                default_outputs = all_files,
+                                sub_targets = {arch: [DefaultInfo(default_outputs = files)] for arch, files in shared_lib.hip_arch_debug_files.items()},
+                            ),
+                        ]
+
+        # TODO(cjhopman): is it okay that we sometimes don't have a linkable?
+        outputs[output_style] = out
+        dep_metadata = cxx_attr_dep_metadata(ctx)
+        exported_flags, exported_post_flags = sandbox_exported_linker_flags(
+            linker_info,
+            linker_flags.exported_flags,
+            linker_flags.exported_post_flags,
+        )
+        libraries[output_style] = LinkInfos(
+            default = LinkInfo(
+                name = ctx.attrs.name,
+                pre_flags = exported_flags,
+                post_flags = exported_post_flags,
+                linkables = [linkable] if linkable else [],
+                metadata = dep_metadata,
+            ),
+            stripped = None
+            if linkable_stripped == None
+            else LinkInfo(
+                name = ctx.attrs.name,
+                pre_flags = exported_flags,
+                post_flags = exported_post_flags,
+                linkables = [linkable_stripped],
+                metadata = dep_metadata,
+            ),
+        )
+
+        sub_targets[subtarget_for_output_style(output_style)] = [
+            DefaultInfo(
+                default_output = outputs[output_style],
+            )
+        ]
+
+    # Third-party provider.
+    shared_libs_for_third_party = SharedLibraries(libraries = solibs)
+    if ctx.attrs.third_party_build != None:
+        third_party_build_info = create_third_party_build_info(
+            ctx = ctx,
+            shared_libs = shared_libs_for_third_party.libraries if generated_shared_lib else [],
+            children = [ctx.attrs.third_party_build[ThirdPartyBuildInfo]],
+            deps = ctx.attrs.deps + cxx_attr_exported_deps(ctx),
+        )
+    else:
+        third_party_build_info = create_third_party_build_info(
+            ctx = ctx,
+            paths = [] if header_dirs == None else [(d.short_path, d) for d in header_dirs],
+            cxx_headers = [propagated_preprocessor],
+            shared_libs = shared_libs_for_third_party.libraries,
+            cxx_header_dirs = ["include"] + ([] if header_dirs == None else [d.short_path for d in header_dirs]),
+            deps = ctx.attrs.deps + cxx_attr_exported_deps(ctx),
+        )
+
+    return struct(
+        outputs = outputs,
+        libraries = libraries,
+        solibs = solibs,
+        sub_targets = sub_targets,
+        generated_shared_lib = generated_shared_lib,
+        third_party_build_info = third_party_build_info,
+    )
+
+def _create_prebuilt_library_providers(
+    ctx: AnalysisContext,
+    input_providers: list[Provider],
+    preferred_linkage: Linkage,
+    library_outputs,
+    static_lib,
+    static_pic_lib,
+    soname,
+    linker_type,
+    linker_flags,
+    inherited_exported_link,
+    inherited_link,
+    first_order_deps,
+    exported_first_order_deps,
+):
+    """
+    Create and return providers for a prebuilt library with a specific preferred linkage.
+
+    Takes the providers list constructed so far and library_outputs from _create_prebuilt_library_outputs,
+    and appends link-related providers.
+    Returns a tuple of (providers, sub_targets, default_output).
+    """
+
+    providers = list(input_providers)
+
+    # Extract data from library_outputs for the output styles relevant to this preferred_linkage
+    outputs = library_outputs.outputs
+    libraries = {}
+    for output_style in get_output_styles_for_linkage(preferred_linkage):
+        libraries[output_style] = library_outputs.libraries[output_style]
+
+    solibs = library_outputs.solibs
+    sub_targets = dict(library_outputs.sub_targets)
+
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    pic_behavior = cxx_toolchain.pic_behavior
+
+    # Propagate link info provider.
+    providers.append(
+        create_merged_link_info(
+            ctx,
+            pic_behavior,
+            # Add link info for each link style,
+            libraries,
+            preferred_linkage = preferred_linkage,
+            # Export link info from non-exported deps (when necessary).
+            deps = inherited_link,
+            # Export link info from out (exported) deps.
+            exported_deps = inherited_exported_link,
+        )
+    )
+
+    # Propagate shared libraries up the tree.
+    shared_libs = SharedLibraries(libraries = solibs)
+    providers.append(
+        merge_shared_libraries(
+            ctx.actions,
+            shared_libs,
+            filter_and_map_idx(SharedLibraryInfo, exported_first_order_deps),
+        )
+    )
+
+    providers.append(
+        create_unix_env_info(
+            actions = ctx.actions,
+            env = UnixEnv(
+                label = ctx.label,
+                native_libs = [shared_libs],
+            ),
+            deps = ctx.attrs.deps + ctx.attrs.exported_deps,
+        ),
+    )
+
+    # Third-party provider (already created in library_outputs)
+    third_party_build_info = library_outputs.third_party_build_info
+    providers.append(third_party_build_info)
+    sub_targets["third-party-build"] = [
+        DefaultInfo(
+            default_output = third_party_build_info.build.root.artifact,
+            sub_targets = dict(
+                manifest = [DefaultInfo(default_output = third_party_build_info.build.manifest)],
+            ),
+        ),
+    ]
+
+    # Create the default output for the library rule given it's link style and preferred linkage
+    link_strategy = to_link_strategy(cxx_toolchain.linker_info.link_style)
+    actual_output_style = get_lib_output_style(link_strategy, preferred_linkage, pic_behavior)
+    default_output = outputs[actual_output_style]
+
+    # Omnibus root provider.
+    if LibOutputStyle("pic_archive") in libraries and (static_pic_lib or static_lib) and not ctx.attrs.header_only and soname.is_str:
+        # TODO(cjhopman): This doesn't support thin archives
+        linkable_root = create_linkable_root(
+            label = ctx.label,
+            name = soname.ensure_str(),
+            link_infos = LinkInfos(
+                default = LinkInfo(
+                    name = soname.ensure_str(),
+                    pre_flags = (linker_flags.exported_flags + linker_flags.flags),
+                    linkables = [
+                        ArchiveLinkable(
+                            archive = Archive(
+                                artifact = static_pic_lib or static_lib,
+                            ),
+                            linker_type = linker_type,
+                            link_whole = True,
+                        )
+                    ],
+                    post_flags = linker_flags.exported_post_flags,
+                    metadata = cxx_attr_dep_metadata(ctx),
+                )
+            ),
+            deps = exported_first_order_deps,
+        )
+        providers.append(linkable_root)
+
+        # Mark libraries that support `dlopen`.
+        if ctx.attrs.supports_python_dlopen:
+            providers.append(DLOPENABLE_LIBRARY_INFO_MARKER)
+
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            linkable_node = create_linkable_node(
+                ctx = ctx,
+                default_soname = soname.as_str(),
+                preferred_linkage = preferred_linkage,
+                default_link_strategy = to_link_strategy(cxx_toolchain.linker_info.link_style),
+                exported_deps = exported_first_order_deps,
+                # If we don't have link input for this link style, we pass in `None` so
+                # that omnibus knows to avoid it.
+                link_infos = libraries,
+                shared_libs = shared_libs,
+                linker_flags = linker_flags,
+                can_be_asset = getattr(ctx.attrs, "can_be_asset", False) or False,
+                stub = getattr(ctx.attrs, "stub", False),
+            ),
+            excluded = {ctx.label: None} if not value_or(ctx.attrs.supports_merged_linking, True) else {},
+        ),
+        deps = exported_first_order_deps,
+    )
+
+    providers.append(linkable_graph)
+
+    providers.append(
+        merge_link_group_lib_info(
+            deps = first_order_deps + exported_first_order_deps,
+        ),
+    )
+
+    # TODO(T107163344) this shouldn't be in prebuilt_cxx_library itself, use overlays to remove it.
+    providers.append(merge_android_packageable_info(ctx.label, ctx.actions, first_order_deps + exported_first_order_deps))
+
+    apple_resource_graph = create_resource_graph(
+        ctx = ctx,
+        labels = ctx.attrs.labels,
+        deps = first_order_deps,
+        exported_deps = exported_first_order_deps,
+    )
+    providers += [apple_resource_graph]
+
+    return (providers, sub_targets, default_output)
+
+def prebuilt_cxx_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    # Versioned params should be intercepted and converted away via the stub.
+    expect(not ctx.attrs.versioned_exported_lang_preprocessor_flags)
+    expect(not ctx.attrs.versioned_exported_preprocessor_flags)
+    expect(not ctx.attrs.versioned_header_dirs)
+    expect(not ctx.attrs.versioned_shared_lib)
+    expect(not ctx.attrs.versioned_static_lib)
+    expect(not ctx.attrs.versioned_static_pic_lib)
+
+    if not cxx_platform_supported(ctx):
+        return [DefaultInfo(default_output = None)]
+
+    providers = []
+
+    toolchain_info = get_cxx_toolchain_info(ctx)
+    linker_info = toolchain_info.linker_info
+    linker_type = linker_info.type
+
+    # Parse library parameters.
+    static_lib = _prebuilt_item(
+        ctx,
+        ctx.attrs.static_lib,
+    )
+    static_pic_lib = _prebuilt_item(
+        ctx,
+        ctx.attrs.static_pic_lib,
+    )
+    shared_lib = _prebuilt_item(
+        ctx,
+        ctx.attrs.shared_lib,
+    )
+    header_dirs = _prebuilt_item(
+        ctx,
+        ctx.attrs.header_dirs,
+    )
+    preferred_linkage = _prebuilt_linkage(ctx)
+
+    # Prepare the stripped static lib.
+    static_lib_stripped = None
+    if not ctx.attrs.prestripped and static_lib != None:
+        static_lib_stripped = strip_debug_info(
+            ctx.actions, static_lib.short_path, static_lib, toolchain_info, has_content_based_path = cxx_attr_use_content_based_paths(ctx)
+        )
+
+    # Prepare the stripped static PIC lib.  If the static PIC lib is the same
+    # artifact as the static lib, then just re-use the stripped static lib.
+    static_pic_lib_stripped = None
+    if not ctx.attrs.prestripped:
+        if static_lib == static_pic_lib:
+            static_pic_lib_stripped = static_lib_stripped
+        elif static_pic_lib != None:
+            static_pic_lib_stripped = strip_debug_info(
+                ctx.actions, static_pic_lib.short_path, static_pic_lib, toolchain_info, has_content_based_path = cxx_attr_use_content_based_paths(ctx)
+            )
+
+    if ctx.attrs.soname != None:
+        soname = get_shared_library_name_for_param(linker_info, ctx.attrs.soname)
+    elif shared_lib != None and ctx.attrs.extract_soname:
+        soname = extract_soname_from_shlib(
+            actions = ctx.actions,
+            name = "__soname__.txt",
+            shared_lib = shared_lib,
+        )
+    else:
+        soname = get_shared_library_name(linker_info, ctx.label.name, apply_default_prefix = True)
+    soname = to_soname(soname)
+
+    # Use ctx.attrs.deps instead of cxx_attr_deps, since prebuilt rules don't have platform_deps.
+    first_order_deps = ctx.attrs.deps
+    exported_first_order_deps = cxx_attr_exported_deps(ctx)
+
+    # Exported preprocessor info.
+    inherited_pp_infos = cxx_inherited_preprocessor_infos(exported_first_order_deps)
+    generic_exported_pre = cxx_exported_preprocessor_info(ctx, cxx_get_regular_cxx_headers_layout(ctx), [])
+    args = []
+    compiler_type = get_cxx_toolchain_info(ctx).cxx_compiler_info.compiler_type
+    if header_dirs != None:
+        for x in header_dirs:
+            args.append(format_system_include_arg(cmd_args(x), compiler_type))
+    exported_items = [generic_exported_pre]
+    if args:
+        exported_items.append(CPreprocessor(args = CPreprocessorArgs(args = args, precompile_args = args)))
+    propagated_preprocessor = cxx_merge_cpreprocessors(
+        ctx.actions,
+        exported_items,
+        inherited_pp_infos,
+    )
+    providers.append(propagated_preprocessor)
+
+    inherited_link = cxx_inherited_link_info(first_order_deps)
+    inherited_exported_link = cxx_inherited_link_info(exported_first_order_deps)
+
+    linker_flags = cxx_attr_linker_flags_all(ctx)
+
+    # Generate outputs for all output styles once
+    # Only propagate shared libs if the preferred linkage allows shared linking
+    propagate_shared_libs = LibOutputStyle("shared_lib") in get_output_styles_for_linkage(preferred_linkage)
+    library_outputs = _create_prebuilt_library_outputs(
+        ctx,
+        static_lib,
+        static_pic_lib,
+        shared_lib,
+        static_lib_stripped,
+        static_pic_lib_stripped,
+        soname,
+        linker_type,
+        linker_flags,
+        inherited_exported_link,
+        header_dirs,
+        propagated_preprocessor,
+        propagate_shared_libs,
+    )
+
+    # Create link-related providers.
+    linkage_providers = {}
+    for linkage in Linkage:
+        linkage_providers[linkage] = _create_prebuilt_library_providers(
+            ctx,
+            providers,
+            linkage,
+            library_outputs,
+            static_lib,
+            static_pic_lib,
+            soname,
+            linker_type,
+            linker_flags,
+            inherited_exported_link,
+            inherited_link,
+            first_order_deps,
+            exported_first_order_deps,
+        )
+
+    providers, sub_targets, output = linkage_providers[preferred_linkage]
+    for linkage in (Linkage("static"), Linkage("shared")):
+        lproviders, lsub_targets, loutput = linkage_providers[linkage]
+        lproviders_with_default = list(lproviders)
+        lproviders_with_default.append(
+            DefaultInfo(
+                default_output = loutput,
+                sub_targets = lsub_targets,
+            )
+        )
+        sub_targets["prefer-{}".format(linkage.value)] = lproviders_with_default
+    providers.append(
+        DefaultInfo(
+            default_output = output,
+            sub_targets = sub_targets,
+        )
+    )
+
+    providers.append(
+        make_resource_info(
+            gather_resources(
+                label = ctx.label,
+                deps = first_order_deps + exported_first_order_deps,
+            ),
+        ),
+    )
+
+    return providers
+
+def cxx_precompiled_header_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs.compile_pch_file:
+        ctx.attrs.srcs.append(ctx.attrs.src)
+        return cxx_library_generate(ctx, "cxx_precompiled_header")
+
+    inherited_pp_infos = cxx_inherited_preprocessor_infos(ctx.attrs.deps)
+    inherited_link = cxx_inherited_link_info(ctx.attrs.deps)
+    return [
+        DefaultInfo(default_output = ctx.attrs.src),
+        cxx_merge_cpreprocessors(ctx.actions, [], inherited_pp_infos),
+        create_merged_link_info_for_propagation(ctx, inherited_link),
+        CPrecompiledHeaderInfo(header = ctx.attrs.src, compiled = False),
+    ]
+
+def cxx_test_impl(ctx: AnalysisContext) -> list[Provider]:
+    link_strategy = to_link_strategy(cxx_attr_link_style(ctx))
+    link_group_info = get_link_group_info(
+        ctx,
+        filter_and_map_idx(LinkableGraph, cxx_attr_deps(ctx)),
+        link_strategy,
+    )
+
+    # TODO(T110378115): have the runinfo contain the correct test running args
+    headers_layout = cxx_get_regular_cxx_headers_layout(ctx)
+    srcs = get_srcs_with_flags(ctx)
+    params = CxxRuleConstructorParams(
+        rule_type = "cxx_test",
+        generate_sub_targets = CxxRuleSubTargetParams(xcode_data = xcode_data_enabled()),
+        headers_layout = headers_layout,
+        srcs = srcs,
+        link_group_info = link_group_info,
+        auto_link_group_specs = get_auto_link_group_specs(ctx, link_group_info),
+        prefer_stripped_objects = ctx.attrs.prefer_stripped_objects,
+        extra_link_roots = linkables(ctx.attrs.link_group_deps),
+        compiler_flags = ctx.attrs.compiler_flags,
+        cxx_flags = cxx_attr_flags(ctx),
+        lang_compiler_flags = ctx.attrs.lang_compiler_flags,
+        preprocessor_flags = ctx.attrs.preprocessor_flags,
+        lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,
+        use_header_units = _get_use_header_units_mode(ctx.attrs.use_header_units),
+        runtime_dependency_handling = RuntimeDependencyHandling(ctx.attrs.runtime_dependency_handling)
+        if ctx.attrs.runtime_dependency_handling
+        else get_cxx_toolchain_info(ctx).runtime_dependency_handling,
+        error_handler = get_cxx_toolchain_info(ctx).cxx_error_handler,
+        extra_dwp_flags = ctx.attrs.extra_dwp_flags,
+        use_fbcc_rust_wrapper = cxx_attrs_use_fbcc_rust_wrapper(ctx.attrs),
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),
+        precompiled_header = ctx.attrs.precompiled_header,
+        prefix_header = ctx.attrs.prefix_header,
+        _cxx_toolchain = ctx.attrs._cxx_toolchain,
+        use_content_based_paths = cxx_attr_use_content_based_paths(ctx),
+        coverage_instrumentation_compiler_flags = ctx.attrs.coverage_instrumentation_compiler_flags,
+        coverage_profile_list = ctx.attrs.coverage_profile_list[DefaultInfo].default_outputs[0] if ctx.attrs.coverage_profile_list else None,
+        separate_debug_info = ctx.attrs.separate_debug_info,
+        cuda_compile_style = CudaCompileStyle(ctx.attrs.cuda_compile_style),
+        link_preference = LinkPreference(ctx.attrs.link_preference),
+    )
+    output = cxx_executable(ctx, params, is_cxx_test = True)
+
+    target_stats_providers = []
+    if TARGET_STATS_ENABLED:
+        target_stats_tools = get_cxx_toolchain_info(ctx).target_stats_tools
+        if target_stats_tools != None:
+            target_stats_srcs = {src.file.short_path: src.file for src in srcs}
+            target_stats_srcs.update({
+                # Named headers use the dict key; list headers retain their
+                # package-relative path. This matches the collector and avoids
+                # collisions between headers with the same basename.
+                (header.name if header.named else header.artifact.short_path): header.artifact
+                for header in cxx_attr_headers_list(ctx, ctx.attrs.headers, headers_layout)
+            })
+            target_stats_providers, target_stats_subtargets = target_stats_providers_and_subtargets(
+                ctx,
+                tools = target_stats_tools,
+                srcs = target_stats_srcs,
+                deps = cxx_attr_deps(ctx),
+                cycle_mode = CycleMode("file"),
+                module_name = ctx.label.name,
+            )
+            output.sub_targets.update(target_stats_subtargets)
+
+    command = [cmd_args(output.binary, hidden = output.runtime_files)] + ctx.attrs.args
+
+    # Setup RE executors based on the `remote_execution` param.
+    re_executors = get_re_executors_from_props(ctx)
+
+    providers = [
+        DefaultInfo(
+            default_output = output.binary,
+            other_outputs = output.runtime_files + (output.external_debug_info_artifacts if get_cxx_toolchain_info(ctx).materialize_external_debug_info else []),
+            sub_targets = output.sub_targets,
+        ),
+        output.compilation_db,
+        output.dist_info,
+    ]
+    if output.xcode_data:
+        providers.append(output.xcode_data)
+    providers.extend(
+        inject_test_run_info(
+            ctx,
+            ExternalRunnerTestInfo(
+                type = "gtest",
+                command = command,
+                env = ctx.attrs.env,
+                labels = ctx.attrs.labels,
+                contacts = ctx.attrs.contacts,
+                default_executor = re_executors.default_executor,
+                executor_overrides = re_executors.executor_overrides,
+                # We implicitly make this test via the project root, instead of
+                # the cell root (e.g. fbcode root). `network_access` is carried on
+                # the executor config (see `get_re_executors_from_props`).
+                run_from_project_root = ("buck2_run_from_project_root" in (ctx.attrs.labels or []) or re_executors.run_from_project_root),
+                use_project_relative_paths = re_executors.use_project_relative_paths,
+                supports_test_execution_caching = ctx.attrs.supports_test_execution_caching,
+            ),
+        )
+    )
+    if output.validation_specs:
+        providers.append(ValidationInfo(validations = output.validation_specs))
+
+    if get_cxx_toolchain_info(ctx).gcno_files and output.gcno_files:
+        providers.append(GcnoFilesInfo(gcno_files = output.gcno_files))
+
+    providers.extend(target_stats_providers)
+
+    return providers
+
+def _get_params_for_android_binary_cxx_library() -> (CxxRuleSubTargetParams, CxxRuleProviderParams):
+    sub_target_params = CxxRuleSubTargetParams(
+        argsfiles = False,
+        compilation_database = False,
+        headers = False,
+        link_group_map = False,
+        xcode_data = False,
+        clang_traces = False,
+        objects = False,
+        bitcode_bundle = False,
+    )
+    provider_params = CxxRuleProviderParams(
+        compilation_database = False,
+        omnibus_root = False,
+        preprocessor_for_tests = False,
+        cxx_resources_as_apple_resources = False,
+    )
+
+    return sub_target_params, provider_params
diff --git a/buck2/prelude/cxx/cxx_apple_linker_flags.bzl b/buck2/prelude/cxx/cxx_apple_linker_flags.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_apple_linker_flags.bzl
@@ -0,0 +1,96 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+_PLATFORM_TARGET_TRIPLE_MAP = {
+    "appletvos": "{architecture}-apple-tvos{version}",
+    "appletvsimulator": "{architecture}-apple-tvos{version}-simulator",
+    "iphoneos": "{architecture}-apple-ios{version}",
+    "iphonesimulator": "{architecture}-apple-ios{version}-simulator",
+    "maccatalyst": "{architecture}-apple-ios{version}-macabi",
+    "macosx": "{architecture}-apple-macosx{version}",
+    "visionos": "{architecture}-apple-xros{version}",
+    "visionsimulator": "{architecture}-apple-xros{version}-simulator",
+    "watchos": "{architecture}-apple-watchos{version}",
+    "watchsimulator": "{architecture}-apple-watchos{version}-simulator",
+}
+
+# - Metal arch is always `air64`, regardless of target arch
+# - watchOS does not support targeting Metal
+_METAL_PLATFORM_TARGET_TRIPLE_MAP = {
+    "appletvos": "air64-apple-tvos{version}",
+    "appletvsimulator": "air64-apple-tvos{version}-simulator",
+    "iphoneos": "air64-apple-ios{version}",
+    "iphonesimulator": "air64-apple-ios{version}-simulator",
+    "maccatalyst": "air64-apple-ios{version}-macabi",
+    "macosx": "air64-apple-macosx{version}",
+    "visionos": "air64-apple-xros{version}",
+    "visionsimulator": "air64-apple-xros{version}-simulator",
+}
+
+def is_valid_apple_platform_name(platform_name: str | None) -> bool:
+    platform_components = (platform_name or "").split("-")
+    return platform_components[0] in _PLATFORM_TARGET_TRIPLE_MAP and len(platform_components) == 2
+
+def apple_format_target_triple(platform_name: str, version: str) -> str:
+    platform_components = platform_name.split("-")
+    if platform_components[0] not in _PLATFORM_TARGET_TRIPLE_MAP:
+        fail("missing target triple for {} ({})".format(platform_components[0], platform_name))
+
+    triple_format_str = _PLATFORM_TARGET_TRIPLE_MAP[platform_components[0]]
+    return triple_format_str.format(architecture = platform_components[1], version = version)
+
+def apple_format_metal_target_triple(platform: str, version: str) -> str:
+    platform_name_and_arch_components = platform.split("-")
+    platform_name = platform_name_and_arch_components[0]
+    if platform_name not in _METAL_PLATFORM_TARGET_TRIPLE_MAP:
+        fail("Missing Metal target triple for {} ({})".format(platform_name, platform))
+
+    metal_triple_format_str = _METAL_PLATFORM_TARGET_TRIPLE_MAP[platform_name]
+    return metal_triple_format_str.format(version = version)
+
+def apple_target_triple_flags(target_triple: str | None) -> list[str]:
+    return (
+        [
+            "-target",
+            target_triple,
+        ]
+        if target_triple
+        else []
+    )
+
+def apple_extra_darwin_linker_flags(target_triple: str | None) -> list[str]:
+    """
+    Returns a list of linker flags that should be used for all links with a Darwin toolchain.
+    """
+
+    # Darwin requires a target triple specified to
+    # control the deployment target being linked for.
+    extra_linker_flags = apple_target_triple_flags(target_triple)
+
+    # On Apple platforms, DWARF data is contained in the object files
+    # and executables contains paths to the object files (N_OSO stab).
+    #
+    # By default, ld64 will use absolute file paths in N_OSO entries
+    # which machine-dependent executables. Such executables would not
+    # be debuggable on any host apart from the host which performed
+    # the linking. Instead, we want produce machine-independent
+    # hermetic executables, so we need to relativize those paths.
+    #
+    # This is accomplished by passing the `oso-prefix` flag to ld64,
+    # which will strip the provided prefix from the N_OSO paths.
+    #
+    # The flag accepts a special value, `.`, which means it will
+    # use the current workding directory. This will make all paths
+    # relative to the parent of `buck-out`.
+    #
+    # Because all actions in Buck2 are run from the project root
+    # and `buck-out` is always inside the project root, we can
+    # safely pass `.` as the `-oso_prefix` without having to
+    # write a wrapper script to compute it dynamically.
+    extra_linker_flags.append("-Wl,-oso_prefix,.")
+    return extra_linker_flags
diff --git a/buck2/prelude/cxx/cxx_bolt.bzl b/buck2/prelude/cxx/cxx_bolt.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_bolt.bzl
@@ -0,0 +1,104 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# BOLT (Binary Optimization Layout Tool) is a post link profile guided optimizer used for
+# performance-critical services in fbcode: https://www.internalfb.com/intern/wiki/HHVM-BOLT/
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+    "project_artifacts",
+)
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+
+PRE_BOLT_SUFFIX = "-wrapper"
+
+CxxBoltOutput = record(
+    output = field(Artifact),
+    dwo_output = field(Artifact | None),
+)
+
+def cxx_use_bolt(ctx: AnalysisContext) -> bool:
+    cxx_toolchain_info = get_cxx_toolchain_info(ctx)
+    return cxx_toolchain_info.bolt_enabled and ctx.attrs.bolt_profile != None
+
+def bolt(
+    ctx: AnalysisContext,
+    prebolt_output: Artifact,
+    external_debug_info: ArtifactTSet,
+    identifier: [str, None],
+    generate_dwp: bool,
+    allow_cache_upload: bool = False,
+) -> CxxBoltOutput:
+    output_name = prebolt_output.short_path.removesuffix(PRE_BOLT_SUFFIX)
+    postbolt_output = ctx.actions.declare_output(output_name, has_content_based_path = False)
+    dwo_output = None
+    cxx_toolchain_info = get_cxx_toolchain_info(ctx)
+    bolt_tool = cxx_toolchain_info.binary_utilities_info.bolt
+
+    if not bolt_tool or not cxx_use_bolt(ctx):
+        fail("Cannot use bolt if bolt tool is not available or bolt profile is not available")
+
+    materialized_external_debug_info = project_artifacts(ctx.actions, external_debug_info)
+
+    # bolt command format:
+    # {llvm_bolt} {input_bin} -o $OUT -data={fdata} {args}
+    args = cmd_args(
+        bolt_tool,
+        prebolt_output,
+        "-o",
+        postbolt_output.as_output(),
+        cmd_args(ctx.attrs.bolt_profile, format = "-data={}"),
+        ctx.attrs.bolt_flags,
+        hidden = materialized_external_debug_info,
+    )
+
+    if generate_dwp:
+        dwo_output = ctx.actions.declare_output(output_name + ".dwo.d", dir = True, has_content_based_path = False)
+        args.add(cmd_args(dwo_output.as_output(), format = "--dwarf-output-path={}"))
+        args = cmd_args(
+            "/bin/sh",
+            "-c",
+            cmd_args(dwo_output.as_output(), format = 'mkdir -p {}; "$@"'),
+            '""',
+            args,
+        )
+
+    strip_stapsdt = hasattr(ctx.attrs, "strip_stapsdt") and ctx.attrs.strip_stapsdt
+    ctx.actions.run(
+        args,
+        category = "bolt",
+        identifier = identifier,
+        local_only = get_cxx_toolchain_info(ctx).linker_info.link_binaries_locally,
+        allow_cache_upload = allow_cache_upload and not strip_stapsdt,
+    )
+
+    output = postbolt_output
+
+    if strip_stapsdt:
+        stripped_postbolt_output = ctx.actions.declare_output(output_name + "-nostapsdt", has_content_based_path = False)
+        ctx.actions.run(
+            # We --rename-section instead of --remove-section because objcopy's processing
+            # in an invalid ELF file
+            cmd_args([
+                get_cxx_toolchain_info(ctx).binary_utilities_info.objcopy,
+                "--rename-section",
+                ".stapsdt.base=.deleted_stapsdt_base_section",
+                postbolt_output,
+                stripped_postbolt_output.as_output(),
+            ]),
+            category = "bolt_strip_stapsdt",
+            identifier = identifier,
+            # This can execute in RE, but is cheaper to do locally especially for large binaries that
+            # are already locally materialized
+            prefer_local = True,
+            allow_cache_upload = allow_cache_upload,
+        )
+        output = stripped_postbolt_output
+
+    return CxxBoltOutput(output = output, dwo_output = dwo_output)
diff --git a/buck2/prelude/cxx/cxx_context.bzl b/buck2/prelude/cxx/cxx_context.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_context.bzl
@@ -0,0 +1,44 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxPlatformInfo", "CxxToolchainInfo")
+
+# The functions below allow the Cxx rules to find toolchain providers
+# from different rule contexts. For example, the Cxx functions are
+# re-used by non-`cxx_` rules (e.g., the Apple rules) but the toolchain
+# setup on such rules might/would be different.
+#
+# The functions should be used throughout the Cxx rules to get
+# the required providers instead of going via the `_cxx_toolchain`
+# field of the `ctx`.
+#
+# In an ideal world, we would have been injecting all these from
+# the top level but as part of the transition to support
+# `apple_toolchain`, we want to make progress now.
+
+def get_cxx_platform_info(ctx: AnalysisContext) -> CxxPlatformInfo:
+    apple_toolchain = getattr(ctx.attrs, "_apple_toolchain", None)
+    if apple_toolchain:
+        return apple_toolchain[AppleToolchainInfo].cxx_platform_info
+    return ctx.attrs._cxx_toolchain[CxxPlatformInfo]
+
+def get_opt_cxx_toolchain_info(ctx: AnalysisContext) -> CxxToolchainInfo | None:
+    apple_toolchain = getattr(ctx.attrs, "_apple_toolchain", None)
+    if apple_toolchain:
+        return apple_toolchain[AppleToolchainInfo].cxx_toolchain_info
+    cxx_toolchain = getattr(ctx.attrs, "_cxx_toolchain", None)
+    if cxx_toolchain:
+        return cxx_toolchain.get(CxxToolchainInfo)
+    return None
+
+def get_cxx_toolchain_info(ctx: AnalysisContext) -> CxxToolchainInfo:
+    info = get_opt_cxx_toolchain_info(ctx)
+    if not info:
+        fail("no cxx toolchain info in this ctx")
+    return info
diff --git a/buck2/prelude/cxx/cxx_error_handler.bzl b/buck2/prelude/cxx/cxx_error_handler.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_error_handler.bzl
@@ -0,0 +1,201 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+CxxGenericErrorType = record(
+    matcher = str | BuckRegex,
+    category_suffix = str,
+)
+
+def make_error_type(matcher = None, category_suffix = str) -> CxxGenericErrorType:
+    return CxxGenericErrorType(
+        matcher = matcher,
+        category_suffix = category_suffix,
+    )
+
+def _match(matcher: str | BuckRegex, lowercase_stderr: str) -> bool:
+    if isinstance(matcher, str):
+        return matcher in lowercase_stderr
+    elif isinstance(matcher, BuckRegex):
+        return matcher.match(lowercase_stderr)
+    else:
+        fail("Unknown matcher type: {}", type(matcher))
+
+# Not applied automatically by the prelude; add them in your toolchain if you want them
+#
+# FIXME(JakobDegen): Change that?
+def cxx_generic_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:
+    structured_error = ctx.parse_with_errorformat(
+        category = "cxx_compiler_error",
+        error = ctx.stderr,
+        # reference partially: https://github.com/neovim/neovim/blob/07915941014307b054cbbb131369377647b7fb06/runtime/compiler/gcc.vim#L19-L37
+        errorformats = [
+            "%f:%l:%c:\\ %trror:\\ %m",
+            "%f:%l:%c:\\ %tarning:\\ %m",
+            "%f(%l,%c):\\ %trror:\\ %m",
+            "%f(%l,%c):\\ %tarning:\\ %m",
+            "%f:%l:\\ %trror:\\ %m",
+            "%f:%l:\\ %tarning:\\ %m",
+        ],
+    )
+
+    for e in structured_error:
+        if e.error_type != None and e.error_type.lower() == "w":
+            e.category = "cxx_compiler_warning"
+        else:
+            for error_type in CXX_GENERIC_ERROR_TYPES:
+                if _match(error_type.matcher, e.message.lower()):
+                    e.category = "cxx_{}".format(error_type.category_suffix)
+                    break
+
+    # If we didn't match any of the structured errors, try to get the category from the error message
+    categories = []
+    if len(structured_error) == 0:
+        for error_type in CXX_GENERIC_ERROR_TYPES:
+            if _match(error_type.matcher, ctx.stderr.lower()):
+                categories.append(
+                    ctx.new_sub_error(
+                        category = "cxx_{}".format(error_type.category_suffix),
+                    )
+                )
+
+    return structured_error + categories
+
+# PLEASE READ BEFORE ADDING NEW ERROR TYPES!
+#
+# Error types added here should be generic across all cxx toolchains, toolchain/platform specific errors
+# should be defined in a separate toolchain and provided accordingly, these generic errors will automatically
+# be added to all types. If you wish to add messages, it must be applicable to ALL scenarios, including OSS.
+CXX_GENERIC_ERROR_TYPES = [
+    # linker errors
+    make_error_type(
+        matcher = "error: duplicate symbol",
+        category_suffix = "linker_duplicate_symbol",
+    ),
+    make_error_type(
+        matcher = "error: undefined symbol",
+        category_suffix = "linker_undefined_symbol",
+    ),
+    make_error_type(
+        matcher = "error: unable to find library",
+        category_suffix = "linker_missing_library",
+    ),
+    make_error_type(
+        matcher = "cannot be used against local symbol",
+        category_suffix = "linker_relocation",
+    ),
+    # compilation errors
+    make_error_type(
+        matcher = "file not found",
+        category_suffix = "file_not_found",
+    ),
+    make_error_type(
+        matcher = "extra-semi",
+        category_suffix = "extra_semicolon",
+    ),
+    make_error_type(
+        matcher = "cannot open file",
+        category_suffix = "cannot_open_file",
+    ),
+    make_error_type(
+        matcher = "too few arguments to function call",
+        category_suffix = "too_few_arguments",
+    ),
+    make_error_type(
+        matcher = "use of undeclared identifier",
+        category_suffix = "undeclared_identifier",
+    ),
+    make_error_type(
+        matcher = "macro redefined",
+        category_suffix = "macro_redefined",
+    ),
+    make_error_type(
+        matcher = "no type named",
+        category_suffix = "missing_type",
+    ),
+    make_error_type(
+        matcher = "no template named",
+        category_suffix = "missing_template",
+    ),
+    make_error_type(
+        matcher = "no matching function for call",
+        category_suffix = "missing_function",
+    ),
+    make_error_type(
+        matcher = "a type specifier is required for all declarations",
+        category_suffix = "type_specifier_required",
+    ),
+    make_error_type(
+        matcher = "definition of implicit copy constructor for",
+        category_suffix = "definition_deprecated",
+    ),
+    make_error_type(
+        matcher = "Permission denied",
+        category_suffix = "permission_denied",
+    ),
+    make_error_type(
+        matcher = "incomplete type",
+        category_suffix = "incomplete_type",
+    ),
+    make_error_type(
+        matcher = "C2440",
+        category_suffix = "type_conversion_failed",
+    ),
+    make_error_type(
+        matcher = "cannot initialize a member subobject of type",
+        category_suffix = "type_mismatch",
+    ),
+    make_error_type(
+        matcher = "no matching member function",
+        category_suffix = "missing_member_function",
+    ),
+    make_error_type(
+        matcher = "unused variable",
+        category_suffix = "unused_variable",
+    ),
+    make_error_type(
+        matcher = "Wheader-hygiene",
+        category_suffix = "header_hygiene_violated",
+    ),
+    make_error_type(
+        matcher = "call to non-static member function",
+        category_suffix = "non_static_member_function_call",
+    ),
+    make_error_type(
+        matcher = "too many template arguments for class template",
+        category_suffix = "too_many_template_arguments",
+    ),
+    make_error_type(
+        matcher = "possible misuse of comma operator",
+        category_suffix = "comma_operator_misuse",
+    ),
+    make_error_type(
+        matcher = "no such file or directory",
+        category_suffix = "no_such_file_or_directory",
+    ),
+    make_error_type(
+        matcher = "Wpadded",
+        category_suffix = "padding_error",
+    ),
+    # compiler errors matched by regex
+    make_error_type(
+        matcher = regex("no member named '.+' in"),
+        category_suffix = "missing_member",
+    ),
+    make_error_type(
+        matcher = regex("reference to '.+' is ambiguous"),
+        category_suffix = "ambiguous_reference",
+    ),
+    make_error_type(
+        matcher = regex("use of overloaded operator '.+' is ambiguous"),
+        category_suffix = "ambiguous_overload_operator",
+    ),
+    make_error_type(
+        matcher = regex("call to constructor of '.+' is ambiguous"),
+        category_suffix = "ambiguous_constructor_call",
+    ),
+]
diff --git a/buck2/prelude/cxx/cxx_executable.bzl b/buck2/prelude/cxx/cxx_executable.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_executable.bzl
@@ -0,0 +1,1262 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+    "make_artifact_tset",
+    "project_artifacts",
+)
+load("@prelude//:attrs_validators.bzl", "get_attrs_validation_specs")
+load("@prelude//:local_only.bzl", "get_resolved_cxx_binary_link_execution_preference")
+load(
+    "@prelude//:resources.bzl",
+    "create_relocatable_resources_info",
+    "create_resource_db",
+    "gather_resources",
+)
+load(
+    "@prelude//apple:apple_frameworks.bzl",
+    "apple_build_link_args_with_deduped_flags",
+    "apple_create_frameworks_linkable",
+    "apple_get_link_info_by_deduping_link_infos",
+    "get_framework_search_path_flags",
+)
+load(
+    "@prelude//cxx:cxx_bolt.bzl",
+    "PRE_BOLT_SUFFIX",
+    "cxx_use_bolt",
+)
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "IncrementalLinkingMode",
+    "PicBehavior",
+    "RuntimeDependencyHandling",
+)
+load(
+    "@prelude//cxx:hip_debug_extract.bzl",
+    "PRE_EXTRACT_SUFFIX",
+    "hip_debug_extract_available",
+)
+load(
+    "@prelude//cxx:link_groups_types.bzl",
+    "LinkGroupsDebugLinkInfo",
+    "LinkGroupsDebugLinkableItem",
+)
+load("@prelude//cxx:transformation_spec.bzl", "TransformationKind", "build_transformation_spec_context")
+load(
+    "@prelude//dist:dist_info.bzl",
+    "DistInfo",
+)
+load(
+    "@prelude//ide_integrations/xcode:argsfiles.bzl",
+    "XCODE_ARGSFILES_SUB_TARGET",
+)
+load(
+    "@prelude//ide_integrations/xcode:data.bzl",
+    "XCODE_DATA_SUB_TARGET",
+    "XcodeDataInfo",
+    "generate_xcode_data",
+)
+load("@prelude//linking:add_elf_sections.bzl", "PRE_ADD_ELF_SECTIONS_SUFFIX", "get_elf_sections")
+load(
+    "@prelude//linking:generated_build_info.bzl",
+    "compile_generated_build_info",
+    "generate_build_info",
+    "generate_build_info_shared_library",
+    "generated_build_info_is_shared_library",
+)
+load(
+    "@prelude//linking:link_groups.bzl",
+    "gather_link_group_libs",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkArgs",
+    "LinkCommandDebugOutput",
+    "LinkInfo",
+    "LinkOrdering",  # @unused Used as a type
+    "LinkStrategy",
+    "LinkedObject",  # @unused Used as a type
+    "ObjectsLinkable",
+    "get_lib_output_style",
+    "make_link_command_debug_output",
+    "make_link_command_debug_output_json_info",
+    "process_link_strategy_for_pic_behavior",
+    "to_link_strategy",
+    "unpack_link_args",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",  # @unused Used as a type
+    "create_linkable_graph",
+    "get_linkable_graph_node_map_func",
+    "reduce_linkable_graph",
+)
+load(
+    "@prelude//linking:linkables.bzl",
+    "LinkableProviders",  # @unused Used as a type
+    "linkables",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",  # @unused Used as a type
+    "SharedLibraryInfo",  # @unused Used as a type
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+)
+load("@prelude//linking:stamp_build_info.bzl", "PRE_STAMPED_SUFFIX", "cxx_stamp_build_info")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+load(
+    "@prelude//utils:build_graph_pattern.bzl",
+    "new_build_graph_info",
+)
+load("@prelude//utils:lazy.bzl", "lazy")
+load(
+    "@prelude//utils:utils.bzl",
+    "flatten",
+    "flatten_dict",
+    "map_val",
+)
+load("@prelude//xplugins:debug_artifacts.bzl", "xplugins_get_debug_artifacts_info")
+load(
+    "@prelude//xplugins:types.bzl",
+    "XPluginsDebugArtifactsInfo",
+)
+load(
+    ":argsfiles.bzl",
+    "ARGSFILES_SUBTARGET",
+    "get_argsfiles_output",
+)
+load(
+    ":comp_db.bzl",
+    "CxxCompilationDbInfo",  # @unused Used as a type
+    "create_compilation_database",
+    "make_compilation_db_info",
+)
+load(
+    ":compile.bzl",
+    "ClangTracesInfo",
+    "ClangTracesTSet",
+    "PicClangTracesInfo",
+    "compile_cxx",
+    "create_compile_cmds",
+    "cxx_objects_sub_targets",
+)
+load(":compile_types.bzl", "CxxCompileFlavor")
+load(":cxx_context.bzl", "get_cxx_platform_info", "get_cxx_toolchain_info")
+load(
+    ":cxx_instrumentation.bzl",
+    "is_coverage_enabled_by_any_dep",
+)
+load(
+    ":cxx_library_utility.bzl",
+    "OBJECTS_SUBTARGET",
+    "cxx_attr_deps",
+    "cxx_attr_link_style",
+    "cxx_attr_linker_flags",
+    "cxx_attr_resources",
+    "cxx_is_gnu",
+)
+load(
+    ":cxx_link_utility.bzl",
+    "executable_shared_lib_arguments",
+)
+load(
+    ":cxx_types.bzl",
+    "CxxRuleConstructorParams",  # @unused Used as a type
+    "LinkPreference",
+)
+load(":diagnostics.bzl", "check_sub_target")
+load(":gcno.bzl", "GcnoFilesInfo")
+load(":groups.bzl", "get_dedupped_roots_from_groups")
+load(
+    ":link.bzl",
+    "CxxGcSectionsData",
+    "CxxLinkerMapData",
+    "collect_hip_debug_from_links",
+    "cxx_link_into",
+    "link_args_have_hip_device_debug",
+)
+load(
+    ":link_groups.bzl",
+    "BuildLinkGroupsContext",
+    "FinalLabelsToLinks",
+    "LINK_GROUP_MAPPINGS_FILENAME_SUFFIX",
+    "LINK_GROUP_MAPPINGS_SUB_TARGET",
+    "LINK_GROUP_MAP_DATABASE_SUB_TARGET",
+    "LinkGroupContext",
+    "build_shared_libs_for_symlink_tree",
+    "collect_linkables",
+    "create_debug_linkable_entries",
+    "create_link_groups",
+    "find_relevant_roots",
+    "get_filtered_labels_to_links_map",
+    "get_filtered_links",
+    "get_filtered_targets",
+    "get_link_group",
+    "get_link_group_map_json",
+    "get_link_group_preferred_linkage",
+    "get_public_link_group_nodes",
+    "get_transitive_deps_matching_labels",
+)
+load(
+    ":link_types.bzl",
+    "CxxLinkResultType",
+    "LinkOptions",
+    "link_options",
+    "merge_link_options",
+)
+load(
+    ":linker.bzl",
+    "DUMPBIN_SUB_TARGET",
+    "PDB_SUB_TARGET",
+    "get_dumpbin_providers",
+    "get_pdb_providers",
+    "get_shared_library_name",
+)
+load(
+    ":preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorArgs",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_private_preprocessor_info",
+)
+
+CxxExecutableOutput = record(
+    binary = Artifact,
+    unstripped_binary = Artifact,
+    bitcode_bundle = field(Artifact | None, None),
+    diagnostics = field(Artifact | None),
+    dwp = field(Artifact | None),
+    # Files that must be present for the executable to run successfully. These
+    # are always materialized, whether the executable is the output of a build
+    # or executed as a host tool. They become hidden= arguments when executing
+    # the executable via RunInfo().
+    runtime_files = list[ArgLike],
+    sub_targets = dict[str, list[DefaultInfo]],
+    # The LinkArgs used to create the final executable in 'binary'.
+    link_args = list[LinkArgs],
+    # External components needed to debug the executable.
+    external_debug_info = field(ArtifactTSet, ArtifactTSet()),
+    # The projection of `external_debug_info`. These files need to be
+    # materialized when this executable is the output of a build, not when it is
+    # used by other rules. They become other_outputs on DefaultInfo.
+    external_debug_info_artifacts = list[TransitiveSetArgsProjection],
+    shared_libs = list[SharedLibrary],
+    # All link group links that were generated in the executable.
+    auto_link_groups = field(dict[str, LinkedObject], {}),
+    compilation_db = CxxCompilationDbInfo,
+    xcode_data = [XcodeDataInfo, None],
+    linker_map_data = [CxxLinkerMapData, None],
+    gc_sections_data = [CxxGcSectionsData, None],
+    link_command_debug_output = field([LinkCommandDebugOutput, None], None),
+    dist_info = DistInfo,
+    sanitizer_runtime_files = field(list[Artifact], []),
+    index_stores = field(list[Artifact], []),
+    validation_specs = field(list[ValidationSpec], []),
+    gcno_files = field(list[Artifact], []),
+    xplugins_debug_artifacts_info = field(XPluginsDebugArtifactsInfo | None, None),
+    build_info_manifest_entries = field(Artifact | None, None),
+)
+
+def cxx_executable(ctx: AnalysisContext, impl_params: CxxRuleConstructorParams, is_cxx_test: bool = False) -> CxxExecutableOutput:
+    # Gather preprocessor inputs.
+    preprocessor_deps = cxx_attr_deps(ctx) + filter(None, [impl_params.precompiled_header])
+    (own_preprocessor_info, test_preprocessor_infos) = cxx_private_preprocessor_info(
+        ctx,
+        impl_params.headers_layout,
+        raw_headers = ctx.attrs.raw_headers,
+        extra_preprocessors = impl_params.extra_preprocessors,
+        non_exported_deps = preprocessor_deps,
+        is_test = is_cxx_test,
+    )
+    inherited_preprocessor_infos = cxx_inherited_preprocessor_infos(preprocessor_deps) + impl_params.extra_preprocessors_info
+
+    # Add framework search paths if frameworks attribute is set.
+    # This is needed for the apple_test/apple_binary -> cxx_test/cxx_binary swap.
+    frameworks = getattr(ctx.attrs, "frameworks", [])
+    framework_search_path_pre = None
+    if frameworks:
+        framework_search_paths_flags = get_framework_search_path_flags(ctx)
+        framework_search_path_pre = CPreprocessor(
+            args = CPreprocessorArgs(args = [framework_search_paths_flags]),
+        )
+
+    # The link style to use.
+    link_strategy = to_link_strategy(cxx_attr_link_style(ctx))
+    link_strategy = process_link_strategy_for_pic_behavior(link_strategy, get_cxx_toolchain_info(ctx).pic_behavior)
+
+    sub_targets = {}
+
+    # Compile objects.
+    own_preprocessors = [own_preprocessor_info] + test_preprocessor_infos
+    if framework_search_path_pre:
+        own_preprocessors.insert(0, framework_search_path_pre)
+    compile_cmd_output = create_compile_cmds(
+        ctx.actions,
+        ctx.label,
+        get_cxx_toolchain_info(ctx),
+        impl_params,
+        own_preprocessors,
+        inherited_preprocessor_infos,
+        is_coverage_enabled_by_any_dep(ctx, preprocessor_deps),
+    )
+    cxx_deps = cxx_attr_deps(ctx)
+    build_graph_info = new_build_graph_info(ctx, cxx_deps)
+    transformation_spec_context = build_transformation_spec_context(ctx, build_graph_info)
+    compile_flavors = set([CxxCompileFlavor("pic")]) if link_strategy != LinkStrategy("static") else set()
+
+    if transformation_spec_context:
+        transformation_kind = transformation_spec_context.provider.determine_transformation(ctx.label, transformation_spec_context.graph_info)
+        if transformation_kind == TransformationKind("debug"):
+            compile_flavors.add(CxxCompileFlavor("debug"))
+        elif transformation_kind == TransformationKind("optimized"):
+            compile_flavors.add(CxxCompileFlavor("optimized"))
+
+    cxx_outs = compile_cxx(
+        actions = ctx.actions,
+        target_label = ctx.label,
+        toolchain = get_cxx_toolchain_info(ctx),
+        src_compile_cmds = compile_cmd_output.src_compile_cmds,
+        flavors = compile_flavors,
+        provide_syntax_only = True,
+        separate_debug_info = impl_params.separate_debug_info,
+        use_header_units = impl_params.use_header_units,
+        cuda_compile_style = impl_params.cuda_compile_style,
+    )
+
+    gcno_files = [out.gcno_file for out in cxx_outs if out.gcno_file]
+    if get_cxx_toolchain_info(ctx).gcno_files:
+        gcno_files += flatten([dep[GcnoFilesInfo].gcno_files for dep in cxx_deps if GcnoFilesInfo in dep])
+
+    if impl_params.generate_sub_targets.argsfiles:
+        sub_targets[ARGSFILES_SUBTARGET] = [get_argsfiles_output(ctx, compile_cmd_output.argsfiles.relative, ARGSFILES_SUBTARGET)]
+    if impl_params.generate_sub_targets.xcode_data:
+        sub_targets[XCODE_ARGSFILES_SUB_TARGET] = [get_argsfiles_output(ctx, compile_cmd_output.argsfiles.xcode, XCODE_ARGSFILES_SUB_TARGET)]
+    sub_targets[OBJECTS_SUBTARGET] = [DefaultInfo(sub_targets = cxx_objects_sub_targets(cxx_outs))]
+
+    if impl_params.generate_sub_targets and impl_params.generate_sub_targets.clang_traces:
+        traces = [out.clang_trace for out in cxx_outs if out.clang_trace != None]
+        sub_targets["clang-trace"] = [
+            DefaultInfo(
+                default_outputs = traces,
+            )
+        ]
+
+        clang_traces_tset = ctx.actions.tset(
+            ClangTracesTSet,
+            value = traces,
+            children = [
+                info.clang_traces
+                for info in filter(None, [x.get(PicClangTracesInfo) if link_strategy != LinkStrategy("static") else x.get(ClangTracesInfo) for x in cxx_deps])
+            ],
+        )
+
+        clang_traces_args = clang_traces_tset.project_as_args("clang_traces")
+        all_traces = ctx.actions.write(
+            ctx.actions.declare_output("recursive_clang_traces.txt", has_content_based_path = False),
+            clang_traces_args,
+        )
+
+        sub_targets["clang-traces"] = [
+            DefaultInfo(
+                default_output = all_traces,
+                other_outputs = [clang_traces_args],
+            )
+        ]
+
+    diagnostics = {
+        compile_cmd.src.short_path: out.diagnostics for compile_cmd, out in zip(compile_cmd_output.src_compile_cmds, cxx_outs) if out.diagnostics != None
+    }
+    clang_tidy_diagnostics = {
+        compile_cmd.src.short_path + ".clang-tidy": out.clang_tidy_diagnostics
+        for compile_cmd, out in zip(compile_cmd_output.src_compile_cmds, cxx_outs)
+        if out.clang_tidy_diagnostics != None
+    }
+    all_diagnostics = None
+    if len(diagnostics) > 0:
+        sub_targets["check"], all_diagnostics = check_sub_target(
+            ctx,
+            diagnostics,
+            error_handler = impl_params.error_handler,
+            extra_sub_targets = clang_tidy_diagnostics,
+        )
+    if len(clang_tidy_diagnostics) > 0:
+        check_all_diagnostics = dict(diagnostics)
+        check_all_diagnostics.update(clang_tidy_diagnostics)
+        check_all_subtarget_result = check_sub_target(
+            ctx,
+            check_all_diagnostics,
+            error_handler = impl_params.error_handler,
+            output_name = "all_diagnostics.txt",
+        )
+        sub_targets["check-all"] = check_all_subtarget_result[0]
+
+    # Compilation DB.
+    comp_db = create_compilation_database(ctx, compile_cmd_output.src_compile_cmds, "compilation-database")
+    sub_targets["compilation-database"] = [comp_db]
+
+    # Compilation DB including headers.
+    comp_db = create_compilation_database(ctx, compile_cmd_output.comp_db_compile_cmds, "full-compilation-database")
+    sub_targets["full-compilation-database"] = [comp_db]
+
+    # comp_db_compile_cmds can include header files being compiled as C++ which should not be exposed in the [compilation-database] subtarget
+    comp_db_info = make_compilation_db_info(compile_cmd_output.comp_db_compile_cmds, get_cxx_toolchain_info(ctx), get_cxx_platform_info(ctx))
+
+    # Index Stores created by cxx compile
+    index_stores = [out.index_store for out in cxx_outs if out.index_store]
+
+    # Link deps
+    link_deps = linkables(cxx_deps) + impl_params.extra_link_deps
+
+    # Link Groups
+    link_group = get_link_group(ctx)
+    link_group_info = impl_params.link_group_info
+
+    if link_group_info:
+        link_groups = link_group_info.groups
+        link_group_mappings = link_group_info.mappings
+        link_group_deps = [link_group_info.graph]
+    else:
+        link_groups = {}
+        link_group_mappings = {}
+        link_group_deps = []
+    link_group_preferred_linkage = get_link_group_preferred_linkage(link_groups.values())
+
+    # Create the linkable graph with the binary's deps and any link group deps.
+    linkable_graph = create_linkable_graph(
+        ctx,
+        deps = filter(
+            None,
+            # Some subtargets (like :Foo[headers]) do not have a linkable_graph.
+            [d.linkable_graph for d in link_deps]
+            +
+            # We also need to include additional link roots, so that we find
+            # deps that might need to be linked into the main executable.
+            [d.linkable_graph for d in impl_params.extra_link_roots]
+            +
+            # For non-auto-link-group cases, also search the targets specified
+            # in the link group mappings, as they won't be available in other
+            # ways.
+            link_group_deps,
+        ),
+    )
+
+    # Gather link inputs.
+    own_link_flags = (
+        get_cxx_toolchain_info(ctx).linker_info.binary_linker_flags
+        + cxx_attr_linker_flags(ctx, impl_params.cxx_flags)
+        + impl_params.extra_link_flags
+        + impl_params.extra_exported_link_flags
+    )
+
+    own_exe_link_flags = impl_params.extra_binary_link_flags + own_link_flags
+    deps_merged_link_infos = [d.merged_link_info for d in link_deps]
+    frameworks_linkable = apple_create_frameworks_linkable(ctx)
+    swiftmodule_linkable = impl_params.swiftmodule_linkable
+
+    # Link group libs.
+    link_group_libs = {}
+
+    # Target label to which link group it was included
+    targets_consumed_by_link_groups = {}
+    auto_link_groups = {}
+
+    # Linker map data for link group shared libraries, keyed by group name.
+    link_group_linker_map_data = {}
+    labels_to_links = FinalLabelsToLinks(
+        map = {},
+    )
+
+    if not link_group_mappings:
+        # We cannot support deriving link execution preference off the included links, as we've already
+        # lost the information on what is in the link.
+        # TODO(T152860998): Derive link_execution_preference based upon the included links
+        link_execution_preference = get_resolved_cxx_binary_link_execution_preference(ctx, [], impl_params.force_full_hybrid_if_capable)
+
+        dep_links = apple_build_link_args_with_deduped_flags(
+            ctx,
+            deps_merged_link_infos,
+            frameworks_linkable,
+            link_strategy,
+            transformation_spec_context,
+            swiftmodule_linkable,
+            prefer_stripped = impl_params.prefer_stripped_objects,
+        )
+    else:
+        reduced_linkable_graph = reduce_linkable_graph(linkable_graph)
+        linkable_graph_node_map = reduced_linkable_graph.nodes
+
+        # Although these aren't really deps, we need to search from the
+        # extra link group roots to make sure we find additional libs
+        # that should be linked into the main link group.
+        link_group_extra_link_roots = [d.linkable_graph.nodes.value.label for d in impl_params.extra_link_roots if d.linkable_graph != None]
+
+        exec_dep_roots = [d.linkable_graph.nodes.value.label for d in link_deps if d.linkable_graph != None]
+
+        # If we're using auto-link-groups, where we generate the link group links
+        # in the prelude, the link group map will give us the link group libs.
+        # Otherwise, pull them from the `LinkGroupLibInfo` provider from out deps.
+
+        public_link_group_nodes = get_public_link_group_nodes(
+            linkable_graph_node_map,
+            link_group_mappings,
+            exec_dep_roots + link_group_extra_link_roots,
+            link_group,
+        )
+        link_group_libs_debug_info = {}
+        if impl_params.auto_link_group_specs != None:
+            linked_link_groups = create_link_groups(
+                ctx = ctx,
+                link_groups = link_groups,
+                link_strategy = link_strategy,
+                linkable_graph = reduced_linkable_graph,
+                link_group_mappings = link_group_mappings,
+                link_group_preferred_linkage = link_group_preferred_linkage,
+                executable_deps = exec_dep_roots,
+                linker_flags = own_link_flags,
+                link_group_specs = impl_params.auto_link_group_specs,
+                other_roots = link_group_extra_link_roots,
+                prefer_stripped_objects = impl_params.prefer_stripped_objects,
+                anonymous = ctx.attrs.anonymous_link_groups,
+                allow_cache_upload = impl_params.exe_allow_cache_upload,
+                public_nodes = public_link_group_nodes,
+                transformation_spec_context = transformation_spec_context,
+                error_handler = impl_params.error_handler,
+            )
+            link_group_libs_debug_info = linked_link_groups.libs_debug_info
+            for name, linked_link_group in linked_link_groups.libs.items():
+                auto_link_groups[name] = linked_link_group.artifact
+                if linked_link_group.library != None:
+                    link_group_libs[name] = linked_link_group.library
+                if linked_link_group.linker_map_data != None:
+                    link_group_linker_map_data[name] = linked_link_group.linker_map_data
+            own_exe_link_flags += linked_link_groups.symbol_ldflags
+            targets_consumed_by_link_groups = linked_link_groups.targets_consumed_by_link_groups
+
+        else:
+            # NOTE(agallagher): We don't use version scripts and linker scripts
+            # for non-auto-link-group flow, as it's note clear it's useful (e.g.
+            # it's mainly for supporting dlopen-enabled libs and extensions).
+            link_group_libs = gather_link_group_libs(
+                children = [d.link_group_lib_info for d in link_deps],
+            )
+
+        pic_behavior = get_cxx_toolchain_info(ctx).pic_behavior
+
+        roots = set(
+            exec_dep_roots
+            + find_relevant_roots(
+                link_group = link_group,
+                linkable_graph_node_map = linkable_graph_node_map,
+                link_group_mappings = link_group_mappings,
+                roots = link_group_extra_link_roots,
+            ),
+        )
+        is_executable_link = True
+        exec_linkables = collect_linkables(
+            reduced_linkable_graph,
+            is_executable_link,
+            link_strategy,
+            link_group_preferred_linkage,
+            pic_behavior,
+            roots,
+        )
+
+        build_context = BuildLinkGroupsContext(
+            public_nodes = public_link_group_nodes,
+            linkable_graph = reduced_linkable_graph,
+            link_groups = link_groups,
+            link_group_mappings = link_group_mappings,
+            link_group_preferred_linkage = link_group_preferred_linkage,
+            link_strategy = link_strategy,
+            pic_behavior = pic_behavior,
+            link_group_libs = {name: (lib.label, lib.shared_link_infos) for name, lib in link_group_libs.items()},
+            prefer_stripped = impl_params.prefer_stripped_objects,
+            prefer_optimized = False,
+            transformation_spec_context = transformation_spec_context,
+        )
+
+        # TODO(T110378098): Similar to shared libraries, we need to identify all the possible
+        # scenarios for which we need to propagate up link info and simplify this logic. For now
+        # base which links to use based on whether link groups are defined.
+        labels_to_links = get_filtered_labels_to_links_map(
+            link_group,
+            linkables = exec_linkables,
+            is_executable_link = is_executable_link,
+            build_context = build_context,
+            force_static_follows_dependents = impl_params.link_groups_force_static_follows_dependents,
+        )
+
+        link_groups_binary_debug_info = LinkGroupsDebugLinkableItem(
+            ordered_linkables = create_debug_linkable_entries(labels_to_links.map, root = None),
+        )
+        link_groups_debug_info = LinkGroupsDebugLinkInfo(
+            binary = link_groups_binary_debug_info,
+            libs = link_group_libs_debug_info,
+        )
+        link_groups_libs_sub_targets = {}
+        for name, lib in link_group_libs_debug_info.items():
+            link_groups_libs_sub_targets[name] = [
+                DefaultInfo(
+                    default_output = ctx.actions.write_json(
+                        ctx.label.name + ".link-groups-info.libs.{}.json".format(name),
+                        lib,
+                        has_content_based_path = False,
+                    ),
+                ),
+            ]
+        sub_targets["link-groups-info"] = [
+            DefaultInfo(
+                default_output = ctx.actions.write_json(
+                    ctx.label.name + ".link-groups-info.json",
+                    link_groups_debug_info,
+                    has_content_based_path = False,
+                ),
+                sub_targets = {
+                    "bin": [
+                        DefaultInfo(
+                            default_output = ctx.actions.write_json(
+                                ctx.label.name + ".link-groups-info.bin.json",
+                                link_groups_binary_debug_info,
+                                has_content_based_path = False,
+                            ),
+                        )
+                    ],
+                    "shared-libraries": [DefaultInfo(sub_targets = link_groups_libs_sub_targets)],
+                },
+            )
+        ]
+
+        if is_cxx_test and link_group != None:
+            # if a cpp_unittest is part of the link group, we need to traverse through all deps
+            # from the root again to ensure we link in gtest deps
+            roots = set([d.linkable_graph.nodes.value.label for d in link_deps])
+            exec_linkables = collect_linkables(
+                linkable_graph_node_map,
+                is_executable_link,
+                link_strategy,
+                link_group_preferred_linkage,
+                pic_behavior,
+                roots,
+            )
+            labels_to_links_to_merge = get_filtered_labels_to_links_map(
+                link_group = None,
+                linkables = exec_linkables,
+                is_executable_link = False,
+                build_context = build_context,
+            )
+            labels_to_links.map |= labels_to_links_to_merge.map
+
+        # NOTE: Our Haskell DLL support impl currently links transitive haskell
+        # deps needed by DLLs which get linked into the main executable as link-
+        # whole.  To emulate this, we mark Haskell rules with a special label
+        # and traverse this to find all the nodes we need to link whole.
+        public_nodes = []
+        if ctx.attrs.link_group_public_deps_label != None:
+            public_nodes = get_transitive_deps_matching_labels(
+                linkable_graph_node_map = linkable_graph_node_map,
+                label = ctx.attrs.link_group_public_deps_label,
+                roots = get_dedupped_roots_from_groups(link_group_info.groups.values()),
+            )
+
+        filtered_links = get_filtered_links(labels_to_links.map, set(public_nodes))
+        filtered_targets = get_filtered_targets(labels_to_links.map)
+
+        link_execution_preference = get_resolved_cxx_binary_link_execution_preference(ctx, labels_to_links.map.keys(), impl_params.force_full_hybrid_if_capable)
+
+        # Unfortunately, link_groups does not use MergedLinkInfo to represent the args
+        # for the resolved nodes in the graph.
+        # Thus, we have no choice but to traverse all the nodes to dedupe the framework linker args.
+        additional_links = apple_get_link_info_by_deduping_link_infos(ctx, filtered_links, frameworks_linkable, swiftmodule_linkable)
+        if additional_links:
+            filtered_links.append(additional_links)
+
+        dep_links = LinkArgs(infos = filtered_links)
+        sub_targets[LINK_GROUP_MAP_DATABASE_SUB_TARGET] = [get_link_group_map_json(ctx, filtered_targets)]
+
+    gnu_use_link_groups = cxx_is_gnu(ctx) and len(link_group_mappings) > 0
+    shlib_deps = _get_shared_library_symlink_deps(
+        ctx,
+        gnu_use_link_groups,
+        impl_params,
+        link_strategy,
+        link_deps,
+        linkable_graph,
+    )
+
+    shlib_info = merge_shared_libraries(ctx.actions, deps = shlib_deps)
+
+    link_group_ctx = LinkGroupContext(
+        link_group_mappings = link_group_mappings,
+        link_group_libs = link_group_libs,
+        link_group_preferred_linkage = link_group_preferred_linkage,
+        labels_to_links_map = labels_to_links.map,
+        targets_consumed_by_link_groups = targets_consumed_by_link_groups,
+    )
+
+    # Set up shared libraries symlink tree only when needed
+    shared_libs = build_shared_libs_for_symlink_tree(
+        gnu_use_link_groups,
+        link_group_ctx,
+        link_strategy,
+        traverse_shared_library_info(shlib_info, transformation_provider = transformation_spec_context),
+        impl_params.extra_shared_libs,
+    )
+
+    toolchain_info = get_cxx_toolchain_info(ctx)
+    linker_info = toolchain_info.linker_info
+    generated_build_info_external_debug_info = []
+    binary_linker_flags = ctx.attrs.binary_linker_flags
+    generated_build_info_args = []
+    if getattr(ctx.attrs, "_generated_build_info_enabled", False):
+        generated_build_info_args = [flag for flag in binary_linker_flags if _is_build_info_linker_flag(flag)]
+        binary_linker_flags = [flag for flag in binary_linker_flags if not _is_build_info_linker_flag(flag)]
+    generated_build_info_invalidation_inputs = (
+        [out.object for out in cxx_outs]
+        + [unpack_link_args(dep_links)]
+        + [shared_lib.lib.output for shared_lib in shared_libs]
+        + impl_params.generated_build_info_invalidation_inputs
+    )
+    generated_build_info_shared_library = None
+    if generated_build_info_is_shared_library(ctx):
+        binary_linker_flags += ["--build-info=none"]
+        generated_build_info_shared_library = generate_build_info_shared_library(
+            ctx,
+            dep_links,
+            generator_args = generated_build_info_args,
+            invalidation_inputs = generated_build_info_invalidation_inputs,
+        )
+        if generated_build_info_shared_library:
+            shared_libs.append(generated_build_info_shared_library.library)
+            sub_targets["generated_build_info"] = [
+                DefaultInfo(default_output = generated_build_info_shared_library.library.lib.output),
+            ]
+    else:
+        generated_build_info = generate_build_info(
+            ctx,
+            generator_args = generated_build_info_args,
+            invalidation_inputs = generated_build_info_invalidation_inputs,
+        )
+        if generated_build_info:
+            generated_build_info_compile_output = compile_generated_build_info(ctx, generated_build_info)
+            generated_build_info_external_debug_info = generated_build_info_compile_output.external_debug_info
+            binary_linker_flags += generated_build_info_compile_output.objects + generated_build_info.linker_flags
+
+    links = [
+        LinkArgs(
+            infos = [
+                LinkInfo(
+                    dist_thin_lto_codegen_flags = getattr(ctx.attrs, "dist_thin_lto_codegen_flags", []),
+                    pre_flags = own_exe_link_flags,
+                    linkables = [
+                        ObjectsLinkable(
+                            objects = [out.object for out in cxx_outs] + impl_params.extra_link_input,
+                            linker_type = linker_info.type,
+                            link_whole = True,
+                        )
+                    ],
+                    external_debug_info = make_artifact_tset(
+                        actions = ctx.actions,
+                        label = ctx.label,
+                        artifacts = (
+                            [out.object for out in cxx_outs if out.object_has_external_debug_info]
+                            + [out.external_debug_info for out in cxx_outs if out.external_debug_info != None]
+                            + generated_build_info_external_debug_info
+                            + (impl_params.extra_link_input if impl_params.extra_link_input_has_external_debug_info else [])
+                        ),
+                    ),
+                ),
+            ]
+        ),
+    ]
+    if generated_build_info_shared_library:
+        links.append(generated_build_info_shared_library.link_args)
+    links += [dep_links] + impl_params.extra_link_args
+
+    # If there are hidden dependencies to this target then add them as
+    # hidden link args.
+    if impl_params.extra_hidden:
+        links.append(
+            LinkArgs(flags = cmd_args(hidden = impl_params.extra_hidden)),
+        )
+
+    incremental_linking_mode = IncrementalLinkingMode(linker_info.incremental_linking)
+    if impl_params.link_preference == LinkPreference("incremental"):
+        incremental_link = incremental_linking_mode != IncrementalLinkingMode("disabled")
+    elif impl_params.link_preference == LinkPreference("full"):
+        incremental_link = False
+    else:
+        incremental_link = incremental_linking_mode == IncrementalLinkingMode("enabled")
+
+    has_hip_device_debug = lazy.is_any(lambda out: out.hip_device_debug, cxx_outs) or link_args_have_hip_device_debug(links)
+    link_result = _link_into_executable(
+        ctx,
+        # If shlib lib tree generation is enabled, pass in the shared libs (which
+        # will trigger the necessary link tree and link args).
+        shared_libs if impl_params.exe_shared_libs_link_tree else [],
+        impl_params.executable_name,
+        linker_info.binary_extension,
+        binary_linker_flags,
+        link_options(
+            links = links,
+            link_weight = linker_info.link_weight,
+            link_ordering = map_val(LinkOrdering, ctx.attrs.link_ordering),
+            link_execution_preference = link_execution_preference,
+            enable_distributed_thinlto = ctx.attrs.enable_distributed_thinlto,
+            strip = impl_params.strip_executable,
+            strip_args_factory = impl_params.strip_args_factory,
+            category_suffix = impl_params.exe_category_suffix,
+            allow_cache_upload = impl_params.exe_allow_cache_upload,
+            error_handler = impl_params.error_handler,
+            extra_linker_outputs_factory = impl_params.extra_linker_outputs_factory,
+            extra_linker_outputs_flags_factory = impl_params.extra_linker_outputs_flags_factory,
+            extra_distributed_thin_lto_opt_outputs_merger = impl_params.extra_distributed_thin_lto_opt_outputs_merger,
+            incremental_link = incremental_link,
+            has_hip_device_debug = has_hip_device_debug,
+        ),
+        build_info_json = (generated_build_info_shared_library.json if generated_build_info_shared_library else None),
+    )
+    binary = link_result.exe
+    runtime_files = link_result.runtime_files
+    shared_libs_symlink_tree = link_result.shared_libs_symlink_tree
+    linker_map_data = link_result.linker_map_data
+    gc_sections_data = link_result.gc_sections_data
+
+    # Define the xcode data sub target
+    xcode_data_info = None
+    if impl_params.generate_sub_targets.xcode_data:
+        xcode_data_default_info, xcode_data_info = generate_xcode_data(
+            ctx,
+            rule_type = impl_params.rule_type,
+            output = binary.output,
+            populate_rule_specific_attributes_func = impl_params.cxx_populate_xcode_attributes_func,
+            srcs = impl_params.srcs + impl_params.additional.srcs,
+            argsfiles = compile_cmd_output.argsfiles.xcode,
+            product_name = get_cxx_executable_product_name(ctx, has_hip_device_debug),
+        )
+        sub_targets[XCODE_DATA_SUB_TARGET] = xcode_data_default_info
+
+    # Info about dynamic-linked libraries for fbpkg integration:
+    # - the symlink dir that's part of RPATH
+    # - sub-sub-targets that reference shared library dependencies and their respective dwp
+    # - [shared-libraries] - a json map that references the above rules.
+    if isinstance(shared_libs_symlink_tree, Artifact):
+        sub_targets["rpath-tree"] = [
+            DefaultInfo(
+                default_output = shared_libs_symlink_tree,
+                other_outputs = [shlib.lib.output for shlib in shared_libs] + [shlib.lib.dwp for shlib in shared_libs if shlib.lib.dwp],
+            )
+        ]
+
+    # TODO(agallagher) There appears to be pre-existing soname conflicts
+    # when building this (when using link groups), which prevents using
+    # `with_unique_str_sonames`.
+    str_soname_shlibs = {shlib.soname.ensure_str(): shlib for shlib in shared_libs if shlib.soname.is_str}
+
+    readable_mappings = {}
+    soname_to_group_mappings = {}
+    if link_group_mappings:
+        for node, group in link_group_mappings.items():
+            soname = get_shared_library_name(linker_info, group, True)
+            soname_to_group_mappings[soname] = group
+            readable_mappings.setdefault(group, []).append(node.raw_target())
+
+        sub_targets[LINK_GROUP_MAPPINGS_SUB_TARGET] = [
+            DefaultInfo(
+                default_output = ctx.actions.write_json(
+                    binary.output.basename + LINK_GROUP_MAPPINGS_FILENAME_SUFFIX,
+                    readable_mappings,
+                    has_content_based_path = False,
+                ),
+            )
+        ]
+
+        linkable_graph_node_map = get_linkable_graph_node_map_func(linkable_graph)()
+        sub_targets["binary_node_count"] = [
+            DefaultInfo(
+                default_output = ctx.actions.write_json(
+                    binary.output.basename + ".binary_node_count.json",
+                    {
+                        "binary_node_count": len(linkable_graph_node_map),
+                    },
+                    has_content_based_path = False,
+                ),
+            )
+        ]
+
+    shared_libraries_sub_targets = {}
+    for soname, shlib in str_soname_shlibs.items():
+        targets = {"dwp": [DefaultInfo(default_output = shlib.lib.dwp)]} if shlib.lib.dwp else {}
+
+        group = soname_to_group_mappings.get(soname)
+        if group in readable_mappings:
+            output_json_file = binary.output.basename + "." + group + LINK_GROUP_MAPPINGS_FILENAME_SUFFIX
+            targets[LINK_GROUP_MAPPINGS_SUB_TARGET] = [
+                DefaultInfo(
+                    default_output = ctx.actions.write_json(
+                        output_json_file,
+                        {group: readable_mappings[group]},
+                        has_content_based_path = False,
+                    ),
+                )
+            ]
+        if group in link_group_linker_map_data:
+            lm_data = link_group_linker_map_data[group]
+            targets["linker-map"] = [DefaultInfo(default_output = lm_data.map, other_outputs = [lm_data.binary])]
+        shared_libraries_sub_targets[soname] = [
+            DefaultInfo(
+                default_output = shlib.lib.output,
+                sub_targets = targets,
+            )
+        ]
+
+    sub_targets["shared-libraries"] = [
+        DefaultInfo(
+            default_output = ctx.actions.write_json(
+                binary.output.basename + ".shared-libraries.json",
+                {
+                    "libraries": ["{}:{}[shared-libraries][{}]".format(ctx.label.path, ctx.label.name, soname) for soname in str_soname_shlibs],
+                    "librariesdwp": [
+                        "{}:{}[shared-libraries][{}][dwp]".format(ctx.label.path, ctx.label.name, soname)
+                        for soname, shlib in str_soname_shlibs.items()
+                        if shlib.lib.dwp
+                    ],
+                    "rpathtree": ["{}:{}[rpath-tree]".format(ctx.label.path, ctx.label.name)] if shared_libs_symlink_tree else [],
+                },
+                has_content_based_path = False,
+            ),
+            sub_targets = shared_libraries_sub_targets,
+        )
+    ]
+
+    # If we have some resources, write it to the resources JSON file and add
+    # it and all resources to "runtime_files" so that we make to materialize
+    # them with the final binary.
+    resources = flatten_dict(
+        gather_resources(
+            label = ctx.label,
+            resources = cxx_attr_resources(ctx),
+            deps = cxx_attr_deps(ctx),
+        ).values()
+    )
+    relocatable_resources_json = None
+    relocatable_resources_contents = None
+    if resources:
+        runtime_files.append(
+            create_resource_db(
+                ctx = ctx,
+                name = binary.output.basename + ".resources.json",
+                binary = binary.output,
+                resources = resources,
+            )
+        )
+        for resource in resources.values():
+            runtime_files.append(resource.default_output)
+            runtime_files.extend(resource.other_outputs)
+        relocatable_resources_json, relocatable_resources_contents = create_relocatable_resources_info(
+            ctx = ctx,
+            name = ctx.label.name,
+            resources = resources,
+        )
+
+    if binary.dwp:
+        # A `dwp` sub-target which generates the `.dwp` file for this binary and its shared lib dependencies.
+        shared_libraries_dwp = [shlib.lib.dwp for shlib in shared_libs if shlib.lib.dwp] + (
+            [link_result.dwp_symlink_tree] if link_result.dwp_symlink_tree else []
+        )
+
+        sub_targets["dwp"] = [
+            DefaultInfo(
+                default_output = binary.dwp,
+                other_outputs = shared_libraries_dwp,
+            ),
+        ]
+
+    # Own TU sidecars + transitive deps' sidecars.
+    hip_all_debug_files = {}
+    for out in cxx_outs:
+        for arch, debug_file in out.hip_arch_debug_files.items():
+            hip_all_debug_files.setdefault(arch, [])
+            hip_all_debug_files[arch].append(debug_file)
+    for arch, files in collect_hip_debug_from_links(links).items():
+        hip_all_debug_files.setdefault(arch, [])
+        hip_all_debug_files[arch].extend(files)
+
+    if hip_all_debug_files:
+        per_arch_debug_subs = {arch: [DefaultInfo(default_outputs = files)] for arch, files in hip_all_debug_files.items()}
+        all_files = [f for files in hip_all_debug_files.values() for f in files]
+        hip_debug_manifest = ctx.actions.write(
+            "__hip_debug_manifest__.txt",
+            cmd_args(all_files, delimiter = "\n"),
+        )
+        sub_targets["hip_debug"] = [
+            DefaultInfo(
+                default_output = hip_debug_manifest,
+                other_outputs = all_files,
+                sub_targets = per_arch_debug_subs,
+            ),
+        ]
+
+    if binary.pdb:
+        # A `pdb` sub-target which generates the `.pdb` file for this binary.
+        sub_targets[PDB_SUB_TARGET] = get_pdb_providers(pdb = binary.pdb, binary = binary.output)
+
+    if binary.ilk:
+        sub_targets["ilk"] = [DefaultInfo(default_output = binary.ilk)]
+
+    if toolchain_info.dumpbin_toolchain_path:
+        sub_targets[DUMPBIN_SUB_TARGET] = get_dumpbin_providers(ctx, binary.output, toolchain_info.dumpbin_toolchain_path)
+
+    # If bolt is not ran, binary.prebolt_output will be the same as binary.output. Only
+    # expose binary.prebolt_output if cxx_use_bolt(ctx) is True to avoid confusion
+    if cxx_use_bolt(ctx):
+        sub_targets["prebolt"] = [DefaultInfo(default_output = binary.prebolt_output)]
+
+    if linker_map_data:
+        sub_targets["linker-map"] = [DefaultInfo(default_output = linker_map_data.map, other_outputs = [linker_map_data.binary])]
+
+    if gc_sections_data:
+        sub_targets["gc-sections"] = [DefaultInfo(default_output = gc_sections_data.gc_sections, other_outputs = [gc_sections_data.binary])]
+
+    sub_targets["linker.argsfile"] = [
+        DefaultInfo(
+            default_output = binary.linker_argsfile,
+        )
+    ]
+
+    link_cmd_debug_output = make_link_command_debug_output(binary)
+    if link_cmd_debug_output != None:
+        link_cmd_debug_output_file = make_link_command_debug_output_json_info(ctx.actions, [link_cmd_debug_output])
+        sub_targets["linker.command"] = [
+            DefaultInfo(
+                default_outputs = filter(None, [link_cmd_debug_output_file]),
+            )
+        ]
+
+    if linker_info.supports_distributed_thinlto and ctx.attrs.enable_distributed_thinlto:
+        sub_targets["index.argsfile"] = [
+            DefaultInfo(
+                default_output = binary.index_argsfile,
+            )
+        ]
+
+    # Provide a debug info target to make sure unpacked external debug info
+    # (dwo) is materialized.
+    external_debug_info = make_artifact_tset(
+        actions = ctx.actions,
+        children = ([binary.external_debug_info] + [s.lib.external_debug_info for s in shared_libs] + impl_params.additional.static_external_debug_info),
+    )
+    external_debug_info_artifacts = project_artifacts(ctx.actions, external_debug_info)
+    materialize_external_debug_info = ctx.actions.write(
+        "debuginfo.artifacts",
+        external_debug_info_artifacts,
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+    sub_targets["debuginfo"] = [
+        DefaultInfo(
+            default_output = materialize_external_debug_info,
+        )
+    ]
+    sub_targets["debug_coverage_instrumentation"] = [
+        DefaultInfo(
+            default_output = materialize_external_debug_info,
+        )
+    ]
+
+    sub_targets["exe"] = [
+        DefaultInfo(
+            default_output = binary.output,
+            other_outputs = runtime_files,
+        )
+    ]
+
+    for additional_subtarget, subtarget_providers in impl_params.additional.subtargets.items():
+        sub_targets[additional_subtarget] = subtarget_providers
+
+    sub_targets.update(link_result.extra_outputs)
+
+    xplugins_debug_artifacts_info = xplugins_get_debug_artifacts_info(ctx, cxx_deps)
+
+    return CxxExecutableOutput(
+        binary = binary.output,
+        unstripped_binary = binary.unstripped_output,
+        dwp = binary.dwp,
+        runtime_files = runtime_files,
+        sub_targets = sub_targets,
+        link_args = links,
+        external_debug_info = external_debug_info,
+        external_debug_info_artifacts = external_debug_info_artifacts,
+        shared_libs = shared_libs,
+        auto_link_groups = auto_link_groups,
+        compilation_db = comp_db_info,
+        xcode_data = xcode_data_info,
+        linker_map_data = linker_map_data,
+        gc_sections_data = gc_sections_data,
+        link_command_debug_output = link_cmd_debug_output,
+        dist_info = DistInfo(
+            shared_libs = shlib_info.set,
+            nondebug_runtime_files = runtime_files,
+            relocatable_resources_json = relocatable_resources_json,
+            relocatable_resources_contents = relocatable_resources_contents,
+        ),
+        sanitizer_runtime_files = link_result.sanitizer_runtime_files,
+        index_stores = index_stores,
+        diagnostics = all_diagnostics,
+        validation_specs = get_attrs_validation_specs(ctx),
+        gcno_files = dedupe(gcno_files),
+        xplugins_debug_artifacts_info = xplugins_debug_artifacts_info,
+        build_info_manifest_entries = (generated_build_info_shared_library.manifest_entries if generated_build_info_shared_library else None),
+    )
+
+_CxxLinkExecutableResult = record(
+    # The resulting executable
+    exe = LinkedObject,
+    # Files that must be present for the executable to run successfully. These
+    # are always materialized, whether the executable is the output of a build
+    # or executed as a host tool.
+    runtime_files = list[ArgLike],
+    # Files needed to debug the executable. These need to be materialized when
+    # this executable is the output of a build, but not when it is used by other
+    # rules.
+    external_debug_info = list[TransitiveSetArgsProjection],
+    dwp_symlink_tree = field(list[Artifact] | Artifact | None),
+    # Optional shared libs symlink tree symlinked_dir action
+    shared_libs_symlink_tree = [list[Artifact], Artifact, None],
+    linker_map_data = [CxxLinkerMapData, None],
+    gc_sections_data = [CxxGcSectionsData, None],
+    sanitizer_runtime_files = list[Artifact],
+    # Extra output providers produced by extra_linker_outputs_factory
+    extra_outputs = dict[str, list[DefaultInfo]],
+)
+
+def _get_shared_library_symlink_deps(
+    ctx: AnalysisContext,
+    gnu_use_link_groups: bool,
+    impl_params: CxxRuleConstructorParams,
+    link_strategy: LinkStrategy,
+    link_deps: list[LinkableProviders],
+    linkable_graph: LinkableGraph,
+) -> list[SharedLibraryInfo]:
+    """
+    Determine which shared library deps need a symlink tree alongside the executable.
+    """
+
+    # Only setup a shared library symlink tree when shared linkage or link_groups is used
+    shlib_deps = []
+    if link_strategy == LinkStrategy("shared") or gnu_use_link_groups:
+        shlib_deps = [d.shared_library_info for d in link_deps] + [d.shared_library_info for d in impl_params.extra_link_roots]
+    elif impl_params.runtime_dependency_handling == RuntimeDependencyHandling("no_symlink"):
+        # Do not create a shared library symlink tree alongside the executable.
+        pass
+    elif impl_params.runtime_dependency_handling == RuntimeDependencyHandling("symlink"):
+        # Include all transitive runtime shared library deps in a symlink tree.
+        for linkable_node in linkable_graph.nodes.traverse():
+            if linkable_node.linkable == None:
+                continue
+            preferred_linkage = linkable_node.linkable.preferred_linkage
+            output_style = get_lib_output_style(link_strategy, preferred_linkage, PicBehavior("supported"))
+            if output_style == LibOutputStyle("shared_lib") and not linkable_node.linkable.stub:
+                shlib_deps.append(merge_shared_libraries(ctx.actions, node = linkable_node.linkable.shared_libs))
+    elif impl_params.runtime_dependency_handling == RuntimeDependencyHandling("symlink_single_level_only"):
+        # Include only first-level (direct) runtime shared library deps in a symlink tree.
+        for d in link_deps + impl_params.extra_link_roots:
+            if d.linkable_graph == None:
+                continue
+            preferred_linkage = d.linkable_graph.nodes.value.linkable.preferred_linkage
+            output_style = get_lib_output_style(link_strategy, preferred_linkage, PicBehavior("supported"))
+            if output_style == LibOutputStyle("shared_lib"):
+                shlib_deps.append(d.shared_library_info)
+
+    return shlib_deps
+
+def _link_into_executable(
+    ctx: AnalysisContext,
+    shared_libs: list[SharedLibrary],
+    executable_name: [str, None],
+    binary_extension: str,
+    binary_linker_flags: list[typing.Any],
+    opts: LinkOptions,
+    build_info_json: Artifact | None = None,
+) -> _CxxLinkExecutableResult:
+    if executable_name and binary_extension and executable_name.endswith(binary_extension):
+        # don't append .exe if it already is .exe
+        output_name = executable_name
+    else:
+        output_name = "{}{}".format(
+            executable_name if executable_name else get_cxx_executable_product_name(ctx, opts.has_hip_device_debug),
+            "." + binary_extension if binary_extension else "",
+        )
+    output = ctx.actions.declare_output(output_name, has_content_based_path = False)
+    executable_args = executable_shared_lib_arguments(
+        ctx,
+        get_cxx_toolchain_info(ctx),
+        output,
+        shared_libs,
+    )
+
+    link_result = cxx_link_into(
+        ctx = ctx,
+        output = output,
+        result_type = CxxLinkResultType("executable"),
+        # Binary linker flags should come after default link flags so they can override default settings.
+        opts = merge_link_options(
+            opts,
+            binary_links = [
+                LinkArgs(
+                    infos = [
+                        LinkInfo(
+                            pre_flags = binary_linker_flags,
+                        ),
+                    ]
+                ),
+            ],
+            links = [LinkArgs(flags = executable_args.extra_link_args)] + opts.links,
+        ),
+        build_info_json = build_info_json,
+    )
+
+    return _CxxLinkExecutableResult(
+        exe = link_result.linked_object,
+        runtime_files = executable_args.runtime_files + link_result.sanitizer_runtime_files,
+        external_debug_info = executable_args.external_debug_info,
+        shared_libs_symlink_tree = executable_args.shared_libs_symlink_tree,
+        dwp_symlink_tree = executable_args.dwp_symlink_tree,
+        linker_map_data = link_result.linker_map_data,
+        gc_sections_data = link_result.gc_sections_data,
+        sanitizer_runtime_files = link_result.sanitizer_runtime_files,
+        extra_outputs = link_result.extra_outputs if link_result.extra_outputs else {},
+    )
+
+def get_cxx_post_link_suffix(ctx: AnalysisContext, has_hip_device_debug: bool = False) -> str:
+    """
+    The suffix the linker's output must carry so that each post-link stage of
+    `cxx_link_into` can strip the part it owns, leaving the canonical name.
+
+    Appended in reverse of the order the stages run, so the outermost suffix
+    belongs to the stage that runs first.
+    """
+    suffix = ""
+    if cxx_stamp_build_info(ctx):
+        suffix += PRE_STAMPED_SUFFIX
+    if get_elf_sections(ctx):
+        suffix += PRE_ADD_ELF_SECTIONS_SUFFIX
+    if has_hip_device_debug and hip_debug_extract_available(get_cxx_toolchain_info(ctx)):
+        suffix += PRE_EXTRACT_SUFFIX
+    if cxx_use_bolt(ctx):
+        suffix += PRE_BOLT_SUFFIX
+    return suffix
+
+def get_cxx_executable_product_name(ctx: AnalysisContext, has_hip_device_debug: bool = False) -> str:
+    return ctx.label.name + get_cxx_post_link_suffix(ctx, has_hip_device_debug)
+
+def _is_build_info_linker_flag(flag) -> bool:
+    return flag.startswith("--build-info")
diff --git a/buck2/prelude/cxx/cxx_flags.bzl b/buck2/prelude/cxx/cxx_flags.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_flags.bzl
@@ -0,0 +1,113 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":attr_selection.bzl", "cxx_by_language_ext")
+
+CxxFlags = record(
+    compiler_flags = field(list[typing.Any], []),
+    lang_compiler_flags = field(dict[typing.Any, typing.Any], {}),
+    lang_preprocessor_flags = field(dict[typing.Any, typing.Any], {}),
+    linker_flags = field(list[typing.Any], []),
+    preprocessor_flags = field(list[typing.Any], []),
+)
+
+def _compiler_flags(flags: CxxFlags):
+    return cmd_args(flags.compiler_flags)
+
+def _linker_flags(flags: CxxFlags):
+    return cmd_args(flags.linker_flags)
+
+def _preprocessor_flags(flags: CxxFlags):
+    return cmd_args(flags.preprocessor_flags)
+
+def _flags_for_ext(ext: str):
+    def project(flags: CxxFlags):
+        return cmd_args(
+            flags.preprocessor_flags,
+            cxx_by_language_ext(flags.lang_preprocessor_flags, ext),
+            cxx_by_language_ext(flags.lang_compiler_flags, ext),
+            flags.compiler_flags,
+        )
+
+    return project
+
+CxxFlagsTSet = transitive_set(
+    args_projections = {
+        "asm": _flags_for_ext(".asm"),
+        "asmpp": _flags_for_ext(".S"),
+        "c": _flags_for_ext(".c"),
+        "compiler_flags": _compiler_flags,
+        "cuda": _flags_for_ext(".cu"),
+        "cxx": _flags_for_ext(".cpp"),
+        "hip": _flags_for_ext(".hip"),
+        "linker_flags": _linker_flags,
+        "objc": _flags_for_ext(".m"),
+        "objcxx": _flags_for_ext(".mm"),
+        "preprocessor_flags": _preprocessor_flags,
+    },
+)
+
+CxxFlagsInfo = provider(
+    fields = {
+        "flags": provider_field(typing.Any),  # CxxFlagsTSet
+    },
+)
+
+def cxx_flags_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        CxxFlagsInfo(
+            flags = ctx.actions.tset(
+                CxxFlagsTSet,
+                value = CxxFlags(
+                    compiler_flags = ctx.attrs.compiler_flags,
+                    lang_compiler_flags = ctx.attrs.lang_compiler_flags,
+                    lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,
+                    linker_flags = ctx.attrs.linker_flags,
+                    preprocessor_flags = ctx.attrs.preprocessor_flags,
+                ),
+                children = [dep[CxxFlagsInfo].flags for dep in ctx.attrs.deps],
+            ),
+        ),
+    ]
+
+def cxx_attr_flags(ctx: AnalysisContext) -> list[Dependency]:
+    return getattr(ctx.attrs, "flags", [])
+
+def cxx_flags_tset(actions: AnalysisActions, flag_deps: list[Dependency]):
+    if not flag_deps:
+        return None
+    return actions.tset(
+        CxxFlagsTSet,
+        children = [dep[CxxFlagsInfo].flags for dep in flag_deps],
+    )
+
+def cxx_flags_projection_name(ext: str) -> str:
+    if ext == ".c":
+        return "c"
+    elif ext in (".cpp", ".cc", ".cl", ".cxx", ".c++", ".bc"):
+        return "cxx"
+    elif ext == ".m":
+        return "objc"
+    elif ext == ".mm":
+        return "objcxx"
+    elif ext in (".s", ".sx", ".S"):
+        return "asmpp"
+    elif ext == ".cu":
+        return "cuda"
+    elif ext == ".hip":
+        return "hip"
+    elif ext in (".asm", ".asmpp"):
+        return "asm"
+    fail("Unexpected file extension: " + ext)
+
+def cxx_flags_linker_flags(actions: AnalysisActions, flag_deps: list[Dependency]) -> list[typing.Any]:
+    flags = cxx_flags_tset(actions, flag_deps)
+    if flags == None:
+        return []
+    return [flags.project_as_args("linker_flags", ordering = "postorder")]
diff --git a/buck2/prelude/cxx/cxx_instrumentation.bzl b/buck2/prelude/cxx/cxx_instrumentation.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_instrumentation.bzl
@@ -0,0 +1,42 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def needs_instrumentation(children: list[bool], contains_headers_selected_for_coverage_instrumentation: bool) -> bool:
+    return contains_headers_selected_for_coverage_instrumentation or any(children)
+
+CxxExportedNeedsCoverageInstrumentationTSet = transitive_set(
+    reductions = {
+        "needs_instrumentation": needs_instrumentation,
+    },
+)
+
+CxxExportedNeedsCoverageInstrumentation = provider(
+    fields = {
+        "nodes": CxxExportedNeedsCoverageInstrumentationTSet,
+    }
+)
+
+def build_needs_coverage_tset(ctx: AnalysisContext, deps: list[Dependency]) -> CxxExportedNeedsCoverageInstrumentationTSet:
+    return ctx.actions.tset(
+        CxxExportedNeedsCoverageInstrumentationTSet,
+        value = ctx.attrs.exported_needs_coverage_instrumentation if hasattr(ctx.attrs, "exported_needs_coverage_instrumentation") else False,
+        children = [d.get(CxxExportedNeedsCoverageInstrumentation).nodes for d in deps if d.get(CxxExportedNeedsCoverageInstrumentation) != None],
+    )
+
+def build_exported_needs_coverage(ctx: AnalysisContext, deps: list[Dependency]) -> CxxExportedNeedsCoverageInstrumentation:
+    return CxxExportedNeedsCoverageInstrumentation(
+        nodes = build_needs_coverage_tset(ctx, deps),
+    )
+
+def is_coverage_enabled_by_any_dep(ctx: AnalysisContext, deps: list[Dependency]) -> bool:
+    tset = build_needs_coverage_tset(ctx, deps)
+
+    return tset.reduce("needs_instrumentation")
+
+def needs_coverage(cxx_exported_needs_coverage: CxxExportedNeedsCoverageInstrumentation) -> bool:
+    return cxx_exported_needs_coverage.nodes.reduce("needs_instrumentation")
diff --git a/buck2/prelude/cxx/cxx_library.bzl b/buck2/prelude/cxx/cxx_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_library.bzl
@@ -0,0 +1,2566 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",  # @unused Used as a type
+    "make_artifact_tset",
+)
+load("@prelude//:attrs_validators.bzl", "get_attrs_validation_specs")
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//:resources.bzl",
+    "gather_resources",
+    "make_resource_info",
+)
+load(
+    "@prelude//android:android_providers.bzl",
+    "merge_android_packageable_info",
+)
+load(
+    "@prelude//apple:apple_frameworks.bzl",
+    "apple_build_link_args_with_deduped_flags",
+    "apple_create_frameworks_linkable",
+    "apple_get_link_info_by_deduping_link_infos",
+    "get_framework_search_path_flags",
+)
+load(
+    "@prelude//apple:apple_resource_types.bzl",
+    "CxxResourceSpec",
+)
+load(
+    "@prelude//apple:modularization_dependency_graph.bzl",
+    "ModularizationDependencyGraphInfo",
+    "create_modularization_dep_graph_subtargets_and_provider",
+)
+load("@prelude//apple:resource_groups.bzl", "create_resource_graph")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load(
+    "@prelude//cxx:headers.bzl",
+    "CPrecompiledHeaderInfo",
+    "CxxPrecompiledHeader",
+    "cxx_attr_precompiled_headers",
+)
+load(
+    "@prelude//ide_integrations/xcode:argsfiles.bzl",
+    "XCODE_ARGSFILES_SUB_TARGET",
+)
+load(
+    "@prelude//ide_integrations/xcode:data.bzl",
+    "XCODE_DATA_SUB_TARGET",
+    "XcodeDataInfo",
+    "generate_xcode_data",
+)
+load(
+    "@prelude//java:java_providers.bzl",
+    "get_java_packaging_info",
+    "propagate_global_code_info",
+)
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference", "get_link_execution_preference")
+load(
+    "@prelude//linking:link_groups.bzl",
+    "EMPTY_LINK_GROUP_LIB_INFO",
+    "LinkGroupLib",  # @unused Used as a type
+    "gather_link_group_libs",
+    "merge_link_group_lib_info",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "ArchiveContentsType",
+    "ArchiveLinkable",
+    "FrameworksLinkable",  # @unused Used as a type
+    "LibOutputStyle",
+    "LinkArgs",
+    "LinkCommandDebugOutputInfo",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkOrdering",
+    "LinkStrategy",
+    "LinkableFlavor",  # @unused Used as a type
+    "LinkedObject",
+    "ObjectsLinkable",
+    "SharedLibLinkable",
+    "SwiftmoduleLinkable",  # @unused Used as a type
+    "UnstrippedLinkOutputInfo",
+    "create_merged_link_info",
+    "get_lib_output_style",
+    "get_link_args_for_strategy",
+    "get_output_styles_for_linkage",
+    "make_link_command_debug_output",
+    "make_link_command_debug_output_json_info",
+    "process_link_strategy_for_pic_behavior",
+    "subtarget_for_output_style",
+    "to_link_strategy",
+    "unpack_link_args",
+    "wrap_link_info",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "DLOPENABLE_LIBRARY_INFO_MARKER",
+    "LinkableRootInfo",
+    "ReducedLinkableGraph",  # @unused used as a type
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+    "create_linkable_node",
+    "linkable_deps",
+    "reduce_linkable_graph",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "EMPTY_SHARED_LIBRARY_INFO",
+    "NamedLinkedObject",
+    "SharedLibraryInfo",
+    "create_flavored_shared_libraries",
+    "merge_shared_libraries",
+)
+load("@prelude//linking:strip.bzl", "strip_debug_info")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")
+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")
+load(
+    "@prelude//third-party:build.bzl",
+    "create_third_party_build_info",
+)
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:lazy.bzl", "lazy")
+load(
+    "@prelude//utils:utils.bzl",
+    "filter_and_map_idx",
+    "flatten",
+    "map_val",
+    "value_or",
+)
+load("@prelude//xplugins:debug_artifacts.bzl", "xplugins_get_debug_artifacts_info")
+load("@prelude//xplugins:utils.bzl", "get_xplugins_usage_info")
+load(":archive.bzl", "make_archive")
+load(
+    ":argsfiles.bzl",
+    "ARGSFILES_SUBTARGET",
+    "get_argsfiles_output",
+)
+load(":bitcode.bzl", "BitcodeBundle", "BitcodeBundleInfo", "BitcodeTSet", "make_bitcode_bundle")
+load(
+    ":comp_db.bzl",
+    "CxxCompilationDbInfo",
+    "create_compilation_database",
+    "make_compilation_db_info",
+)
+load(
+    ":compile.bzl",
+    "ClangTracesInfo",
+    "ClangTracesTSet",
+    "PicClangTracesInfo",
+    "compile_cxx",
+    "create_compile_cmds",
+    "cxx_objects_sub_targets",
+    "precompile_cxx",
+    "toolchain_supports_flavor",
+)
+load(
+    ":compile_types.bzl",
+    "CxxCompileCommandOutput",
+    "CxxCompileFlavor",
+    "CxxCompileOutput",  # @unused Used as a type
+    "CxxExtension",
+    "CxxSrcCompileCommand",
+)
+load(":cxx_context.bzl", "get_cxx_platform_info", "get_cxx_toolchain_info")
+load(":cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load(
+    ":cxx_instrumentation.bzl",
+    "build_exported_needs_coverage",
+    "needs_coverage",
+)
+load(
+    ":cxx_library_utility.bzl",
+    "EMPTY_DEFAULT_INFO",
+    "OBJECTS_SUBTARGET",
+    "cxx_attr_dep_metadata",
+    "cxx_attr_deps",
+    "cxx_attr_exported_deps",
+    "cxx_attr_link_style",
+    "cxx_attr_linker_flags_all",
+    "cxx_attr_preferred_linkage",
+    "cxx_attr_resources",
+    "cxx_inherited_link_info",
+    "cxx_is_gnu",
+    "cxx_platform_supported",
+    "cxx_use_shlib_intfs",
+)
+load(":cxx_sources.bzl", "CxxSrcWithFlags")
+load(
+    ":cxx_toolchain_types.bzl",
+    "LinkerType",
+    "ShlibInterfacesMode",
+    "is_bitcode_format",
+)
+load(
+    ":cxx_transitive_diagnostics.bzl",
+    "cxx_transitive_diagnostics_combine",
+)
+load(
+    ":cxx_types.bzl",
+    "CxxLibraryInfo",
+    "CxxRuleConstructorParams",  # @unused Used as a type
+)
+load(":diagnostics.bzl", "check_sub_target")
+load(":gcno.bzl", "GcnoFilesInfo")
+load(":hip_debug_extract.bzl", "PRE_EXTRACT_SUFFIX", "hip_debug_extract_available")
+load(":index_store.bzl", "IndexStoreInfo", "create_index_store_subtargets_and_provider")
+load(
+    ":link.bzl",
+    "CxxLinkResult",  # @unused Used as a type
+    "CxxLinkerMapData",
+    "cxx_link_shared_library",
+    "link_args_have_hip_device_debug",
+)
+load(
+    ":link_groups.bzl",
+    "BuildLinkGroupsContext",
+    "LINK_GROUP_MAP_DATABASE_SUB_TARGET",
+    "collect_linkables",
+    "get_filtered_labels_to_links_map",
+    "get_filtered_links",
+    "get_filtered_targets",
+    "get_link_group",
+    "get_link_group_info",
+    "get_link_group_map_json",
+    "get_link_group_preferred_linkage",
+)
+load(
+    ":link_types.bzl",
+    "link_options",
+)
+load(
+    ":linker.bzl",
+    "get_default_shared_library_name",
+    "get_ignore_undefined_symbols_flags",
+    "get_shared_library_name",
+    "get_shared_library_name_for_param",
+    "sandbox_exported_linker_flags",
+)
+load(
+    ":omnibus.bzl",
+    "create_linkable_root",
+)
+load(
+    ":preprocessor.bzl",
+    "CPreprocessor",  # @unused Used as a type
+    "CPreprocessorArgs",
+    "CPreprocessorForTestsInfo",
+    "CPreprocessorInfo",  # @unused Used as a type
+    "cxx_exported_preprocessor_info",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+    "cxx_private_preprocessor_info",
+)
+load(
+    ":shared_library_interface.bzl",
+    "shared_library_interface",
+)
+
+# A possible output of a `cxx_library`. This could be an archive or a shared library. Generally for an archive
+# it represents just the sources of the library target itself, while a shared library will bundle multiple libraries
+# together.
+CxxLibraryOutput = record(
+    # The output style of this output.
+    output_style = field(LibOutputStyle),
+    # The main output.
+    default = field(Artifact),
+    unstripped = field(Artifact),
+    # Additional outputs that are implicitly used along with the above output
+    # (e.g. external object files referenced by a thin archive).
+    #
+    # Note: It's possible that this can contain some of the artifacts which are
+    # also present in object_files.
+    other = field(list[Artifact], []),
+    # The bitcode bundle. This only available for archive outputs.
+    # TODO(cjhopman): always available? when is it/is it not available?
+    bitcode_bundle = field([BitcodeBundle, None], None),
+    # Additional debug info which referenced by but not included in the library output.
+    external_debug_info = field(ArtifactTSet, ArtifactTSet()),
+    # A shared shared library may have an associated dwp file with
+    # its corresponding DWARF debug info.
+    # May be None when Split DWARF is disabled, for static/static-pic libraries,
+    # for some types of synthetic link objects or for pre-built shared libraries.
+    dwp = field(Artifact | None, None),
+    hip_arch_debug_files = field(dict[str, list[Artifact]], {}),
+    # A shared shared library may have an associated PDB file with
+    # its corresponding Windows debug info.
+    pdb = field(Artifact | None, None),
+    # The import library is the linkable output of a Windows shared library build.
+    implib = field(Artifact | None, None),
+    # Data about the linker map, only available on shared libraries
+    # TODO(cjhopman): always available? when is it/is it not available?
+    linker_map = field([CxxLinkerMapData, None], None),
+    # Extra sub targets to be returned as outputs of this rule, by link style.
+    sub_targets = field(dict[str, list[DefaultInfo]]),
+    # The object files used to create the artifact in `default`. This only includes the object files
+    # for this library itself, so it's not particularly meaningful for a shared lib output.
+    object_files = field(list[Artifact], []),
+)
+
+# The outputs of either archiving or linking the outputs of the library
+_CxxAllLibraryOutputs = record(
+    # The outputs for each lib output style.
+    # For 'static'/'static_pic', these will be archives containing just this library's object files.
+    # For 'shared', the output as a shared library. That output will be built using either this library's link_strategy link strategy
+    # or via the link group strategy if this library has link group mapping.
+    # A header-only lib won't produce any outputs (but it may still provide LinkInfos below).
+    # TODO(cjhopman): make library-level link_group shared lib not put its output here
+    outputs = field(dict[LibOutputStyle, dict[LinkableFlavor, CxxLibraryOutput]]),
+    # The link infos for linking against this lib of each output style. It's possible for a library to
+    # add link_infos even when it doesn't produce an output itself.
+    link_infos = field(dict[LibOutputStyle, LinkInfos]),
+    # Extra providers to be returned consumers of this rule.
+    providers = field(list[Provider], default = []),
+    # Shared object name to shared library mapping if this target produces a shared library.
+    solibs = field(dict[LinkableFlavor, NamedLinkedObject]),
+    sanitizer_runtime_files = field(list[Artifact], []),
+)
+
+_CxxLibraryCompileOutput = record(
+    # object files
+    objects = field(list[Artifact]),
+    # linkable object files from pch compilation
+    pch_object_output = field(list[Artifact]),
+    # object files stripped of debug information
+    stripped_objects = field(list[Artifact]),
+    # Those outputs which are bitcode
+    bitcode_objects = field([list[Artifact], None]),
+    # yaml file with optimization remarks about clang compilation
+    clang_remarks = field([list[Artifact], None]),
+    # llvm statistics about clang compilation
+    clang_llvm_statistics = field([list[Artifact], None]),
+    gcno_files = field([list[Artifact], None]),
+    # json file with trace information about clang compilation
+    clang_traces = field(list[Artifact]),
+    # Externally referenced debug info, which doesn't get linked with the
+    # object (e.g. the above `.o` when using `-gsplit-dwarf=single` or the
+    # the `.dwo` when using `-gsplit-dwarf=split`).
+    external_debug_info = field(list[Artifact]),
+    # Whether there is any debug info
+    objects_have_external_debug_info = field(bool),
+    # sub_target for each object
+    objects_sub_targets = field(dict[str, list[DefaultInfo]]),
+    # the generated index stores
+    index_stores = field(list[Artifact]),
+    # diagnostics produced by a typecheck-only build (-fsyntax-only)
+    diagnostics = field(dict[str, Artifact]),
+    # diagnostics produced by clang-tidy
+    clang_tidy_diagnostics = field(dict[str, Artifact]),
+    has_hip_device_debug = field(bool, False),
+    hip_arch_debug_files = field(dict[str, list[Artifact]], {}),
+)
+
+# The output of compiling all the source files in the library, containing
+# the commands use to compile them and all the object file variants.
+_CxxCompiledSourcesOutput = record(
+    # Compile commands used to compile the source files or generate object files
+    compile_cmds = field(CxxCompileCommandOutput),
+    # PIC compile outputs
+    pic = field(_CxxLibraryCompileOutput),
+    # PIC optimized compile outputs
+    pic_optimized = field([_CxxLibraryCompileOutput, None]),
+    # PIC debuggable compile outputs
+    pic_debuggable = field([_CxxLibraryCompileOutput, None]),
+    # Non PIC compile outputs
+    non_pic = field([_CxxLibraryCompileOutput, None]),
+    # Header unit outputs
+    header_unit_preprocessors = field(list[CPreprocessor]),
+)
+
+# The outputs of a cxx_library_parameterized rule.
+_CxxLibraryParameterizedOutput = record(
+    # The default output of a cxx library rule
+    default_output = field([CxxLibraryOutput, None], None),
+    # The other outputs available
+    all_outputs = field([_CxxAllLibraryOutputs, None], None),
+    # Any generated sub targets as requested by impl_params. Most of these will just be a
+    # DefaultInfo to expose outputs to be consumed or built individually, but some (like "headers")
+    # will have richer providers.
+    sub_targets = field(dict[str, list[Provider]]),
+    # A bundle of all bitcode files as a subtarget
+    bitcode_bundle = field([BitcodeBundle, None], None),
+    # Any generated providers as requested by impl_params.
+    providers = field(list[Provider]),
+    # XcodeDataInfo provider, returned separately as we cannot check
+    # provider type from providers above
+    xcode_data_info = field([XcodeDataInfo, None], None),
+    # IndexStoreInfo provider, so we can access the paths of all the index stores
+    # or Swift-specific index stores.
+    index_store_info = field([IndexStoreInfo, None], None),
+    # ModularizationDependencyGraphInfo provider for transitive modularization graphs.
+    modularization_dep_graph_info = field([ModularizationDependencyGraphInfo, None], None),
+    # CxxCompilationDbInfo provider, returned separately as we cannot check
+    # provider type from providers above
+    cxx_compilationdb_info = field([CxxCompilationDbInfo, None], None),
+    # LinkableRootInfo provider, same as above.
+    linkable_root = field([LinkableRootInfo, None], None),
+    # List of shared libraries for the sanitizer runtime linked into the library
+    sanitizer_runtime_files = field(list[Artifact], []),
+)
+
+def valid_pch_clanguage(val: typing.Any) -> bool:
+    if not val:
+        return False
+    return val in [ext.value for ext in CxxExtension]
+
+# FIXME(JakobDegen): This is used in place of `cxx_attr_link_style` in some places in a way that
+# makes no sense to me and is not really in keeping with the rest of this API. But we rely on it.
+# If you can justify it, replace with a comment.
+def _link_strategy_for_some_shared_links(attrs: typing.Any) -> LinkStrategy:
+    value = attrs.link_style if attrs.link_style != None else "shared"
+    if value == "static":
+        value = "static_pic"
+    return LinkStrategy(value)
+
+def cxx_library_parameterized(ctx: AnalysisContext, impl_params: CxxRuleConstructorParams) -> _CxxLibraryParameterizedOutput:
+    """
+    Defines the outputs for a cxx library, return the default output and any subtargets and providers based upon the requested params.
+    """
+    if not cxx_platform_supported(ctx):
+        sub_targets = {}
+
+        # Needed to handle cases of the named output (e.g. [static-pic]) being called directly.
+        for output_style in get_output_styles_for_linkage(cxx_attr_preferred_linkage(ctx)):
+            sub_targets[subtarget_for_output_style(output_style)] = [DefaultInfo(default_output = None)]
+
+        return _CxxLibraryParameterizedOutput(
+            providers = [
+                DefaultInfo(default_output = None, sub_targets = sub_targets),
+                EMPTY_SHARED_LIBRARY_INFO,
+            ],
+            sub_targets = sub_targets,
+        )
+
+    non_exported_deps = cxx_attr_deps(ctx)
+    exported_deps = cxx_attr_exported_deps(ctx)
+    deps_all_exported_first = exported_deps + non_exported_deps
+    deps_all_non_exported_first = non_exported_deps + exported_deps
+
+    compile_pch = None
+    pch_clanguage = None
+    if impl_params.rule_type == "cxx_precompiled_header":
+        if len(ctx.attrs.srcs) != 1:
+            fail("cxx_precompiled_header must have exactly one source file, got: {}".format(len(ctx.attrs.srcs)))
+
+        pch_clanguage = ctx.attrs.pch_clanguage
+        if not valid_pch_clanguage(pch_clanguage):
+            fail("pch_clanguage was: {}, must be one of: {}".format(pch_clanguage, [ext.value for ext in CxxExtension]))
+
+        pch_artifact = ctx.attrs.srcs[0]
+        pch_header = cxx_attr_precompiled_headers(ctx, impl_params.headers_layout)
+        basename = "{}{}".format(pch_artifact.basename, pch_clanguage)
+        path = paths.join(pch_header.namespace, pch_header.name)
+
+        pch_wrapper = ctx.actions.declare_output("pch_wrapper.cpp", has_content_based_path = False)
+        ctx.actions.write(pch_wrapper, '#include "{}"'.format(path))
+
+        ctx.attrs.headers.append(pch_artifact)
+        impl_params.srcs[0] = CxxSrcWithFlags(file = pch_wrapper)
+
+        compile_pch = CxxPrecompiledHeader(
+            header = ctx.attrs.srcs[0],
+            basename = basename,
+            basename_src = pch_artifact.basename,
+            path = path,
+            namespace = pch_header.namespace,
+            clanguage = pch_clanguage,
+        )
+
+    # TODO(T110378095) right now we implement reexport of exported_* flags manually, we should improve/automate that in the macro layer
+
+    # Gather preprocessor inputs.
+    (own_non_exported_preprocessor_info, test_preprocessor_infos) = cxx_private_preprocessor_info(
+        ctx = ctx,
+        raw_headers = ctx.attrs.raw_headers,
+        headers_layout = impl_params.headers_layout,
+        extra_preprocessors = impl_params.extra_preprocessors,
+        non_exported_deps = non_exported_deps,
+        is_test = impl_params.is_test,
+    )
+    own_exported_preprocessor_info = cxx_exported_preprocessor_info(
+        ctx,
+        impl_params.headers_layout,
+        extra_preprocessors = impl_params.extra_exported_preprocessors,
+    )
+    own_preprocessors = [own_non_exported_preprocessor_info, own_exported_preprocessor_info] + test_preprocessor_infos
+    own_exported_preprocessors = [own_exported_preprocessor_info]
+
+    # Add framework search paths to exported preprocessors if frameworks attribute is set.
+    # This is needed for the apple_library -> cxx_library swap in fb_xplat_cxx_library.
+    frameworks = getattr(ctx.attrs, "frameworks", [])
+    if frameworks:
+        framework_search_paths_flags = get_framework_search_path_flags(ctx)
+        framework_search_path_pre = CPreprocessor(
+            args = CPreprocessorArgs(args = [framework_search_paths_flags]),
+        )
+        own_exported_preprocessors.insert(0, framework_search_path_pre)
+        own_preprocessors.insert(0, framework_search_path_pre)
+
+    inherited_non_exported_preprocessor_infos = cxx_inherited_preprocessor_infos(
+        # Legacy precompiled_header implementation is not exported. Proper precompiled headers can have exported linkables.
+        non_exported_deps
+        + filter(
+            None,
+            [
+                impl_params.precompiled_header
+                if impl_params.precompiled_header and not impl_params.precompiled_header[CPrecompiledHeaderInfo].compiled
+                else None
+            ],
+        ),
+    )
+    inherited_exported_preprocessor_infos = cxx_inherited_preprocessor_infos(exported_deps)
+
+    preferred_linkage = cxx_attr_preferred_linkage(ctx)
+
+    exported_needs_coverage = build_exported_needs_coverage(ctx, deps_all_exported_first)
+    compiled_srcs = cxx_compile_srcs(
+        actions = ctx.actions,
+        target_label = ctx.label,
+        cxx_toolchain_info = get_cxx_toolchain_info(ctx),
+        impl_params = impl_params,
+        own_preprocessors = own_preprocessors,
+        own_exported_preprocessors = own_exported_preprocessors,
+        inherited_non_exported_preprocessor_infos = inherited_non_exported_preprocessor_infos,
+        inherited_exported_preprocessor_infos = inherited_exported_preprocessor_infos,
+        preferred_linkage = preferred_linkage,
+        compile_pch = compile_pch,
+        add_coverage_instrumentation_compiler_flags = needs_coverage(exported_needs_coverage),
+    )
+
+    sub_targets = {}
+    providers = []
+
+    attr_validation_specs = get_attrs_validation_specs(ctx)
+    if attr_validation_specs:
+        providers.append(ValidationInfo(validations = attr_validation_specs))
+
+    if compile_pch:
+        pch_provider = CPrecompiledHeaderInfo(
+            header = compile_pch.header,
+            basename = compile_pch.basename,
+            compiled = True,
+            clanguage = pch_clanguage,
+        )
+
+        sub_targets["pch"] = [
+            DefaultInfo(
+                sub_targets = {
+                    "default": [
+                        CPrecompiledHeaderInfo(header = compiled_srcs.non_pic.objects[0], basename = compile_pch.basename, compiled = True, clanguage = pch_clanguage)
+                    ]
+                    if compiled_srcs.non_pic
+                    else [],
+                    CxxCompileFlavor("pic").value: [
+                        CPrecompiledHeaderInfo(header = compiled_srcs.pic.objects[0], basename = compile_pch.basename, compiled = True, clanguage = pch_clanguage)
+                    ]
+                    if compiled_srcs.pic
+                    else [],
+                    CxxCompileFlavor("debug").value: [
+                        CPrecompiledHeaderInfo(
+                            header = compiled_srcs.pic_debuggable.objects[0], basename = compile_pch.basename, compiled = True, clanguage = pch_clanguage
+                        )
+                    ]
+                    if compiled_srcs.pic_debuggable
+                    else [],
+                    CxxCompileFlavor("optimized").value: [
+                        CPrecompiledHeaderInfo(
+                            header = compiled_srcs.pic_optimized.objects[0], basename = compile_pch.basename, compiled = True, clanguage = pch_clanguage
+                        )
+                    ]
+                    if compiled_srcs.pic_optimized
+                    else [],
+                },
+            )
+        ]
+
+        providers.append(pch_provider)
+
+    providers.append(exported_needs_coverage)
+
+    if len(ctx.attrs.tests) > 0 and impl_params.generate_providers.preprocessor_for_tests:
+        providers.append(
+            CPreprocessorForTestsInfo(
+                test_names = [test_target.name for test_target in ctx.attrs.tests],
+                own_non_exported_preprocessor = own_non_exported_preprocessor_info,
+            ),
+        )
+
+    if impl_params.generate_sub_targets.argsfiles:
+        sub_targets[ARGSFILES_SUBTARGET] = [get_argsfiles_output(ctx, compiled_srcs.compile_cmds.argsfiles.relative, ARGSFILES_SUBTARGET)]
+    if impl_params.generate_sub_targets.xcode_data:
+        sub_targets[XCODE_ARGSFILES_SUB_TARGET] = [get_argsfiles_output(ctx, compiled_srcs.compile_cmds.argsfiles.xcode, XCODE_ARGSFILES_SUB_TARGET)]
+
+    if impl_params.generate_sub_targets.clang_remarks:
+        if compiled_srcs.non_pic and compiled_srcs.non_pic.clang_remarks:
+            sub_targets["clang-remarks"] = [
+                DefaultInfo(
+                    default_outputs = compiled_srcs.non_pic.clang_remarks,
+                )
+            ]
+
+        if compiled_srcs.pic.clang_remarks:
+            sub_targets["pic-clang-remarks"] = [
+                DefaultInfo(
+                    default_outputs = compiled_srcs.pic.clang_remarks,
+                )
+            ]
+
+    if impl_params.generate_sub_targets.clang_llvm_statistics:
+        if compiled_srcs.non_pic and compiled_srcs.non_pic.clang_llvm_statistics:
+            sub_targets["clang-llvm-statistics"] = [
+                DefaultInfo(
+                    default_outputs = compiled_srcs.non_pic.clang_llvm_statistics,
+                )
+            ]
+
+        if compiled_srcs.pic.clang_llvm_statistics:
+            sub_targets["pic-clang-llvm-statistics"] = [
+                DefaultInfo(
+                    default_outputs = compiled_srcs.pic.clang_llvm_statistics,
+                )
+            ]
+
+    if impl_params.generate_sub_targets.clang_traces:
+        traces = []
+        if compiled_srcs.non_pic and compiled_srcs.non_pic.clang_traces:
+            traces = compiled_srcs.non_pic.clang_traces
+            sub_targets["clang-trace"] = [
+                DefaultInfo(
+                    default_outputs = traces,
+                )
+            ]
+
+        clang_traces_tset = ctx.actions.tset(
+            ClangTracesTSet,
+            value = traces,
+            children = [info.clang_traces for info in filter_and_map_idx(ClangTracesInfo, deps_all_exported_first)],
+        )
+        providers.append(ClangTracesInfo(clang_traces = clang_traces_tset))
+
+        clang_traces_args = clang_traces_tset.project_as_args("clang_traces")
+        all_traces = ctx.actions.write(
+            ctx.actions.declare_output("recursive_clang_traces.txt", has_content_based_path = False),
+            clang_traces_args,
+        )
+
+        sub_targets["clang-traces"] = [
+            DefaultInfo(
+                default_output = all_traces,
+                other_outputs = [clang_traces_args],
+            )
+        ]
+
+        pic_traces = []
+        if compiled_srcs.pic.clang_traces:
+            pic_traces = compiled_srcs.pic.clang_traces
+            sub_targets["pic-clang-trace"] = [
+                DefaultInfo(
+                    default_outputs = pic_traces,
+                )
+            ]
+
+        pic_clang_traces_tset = ctx.actions.tset(
+            ClangTracesTSet,
+            value = pic_traces,
+            children = [info.clang_traces for info in filter_and_map_idx(PicClangTracesInfo, deps_all_exported_first)],
+        )
+        providers.append(PicClangTracesInfo(clang_traces = pic_clang_traces_tset))
+
+        pic_clang_traces_args = pic_clang_traces_tset.project_as_args("clang_traces")
+        all_pic_traces = ctx.actions.write(
+            ctx.actions.declare_output("recursive_pic_clang_traces.txt", has_content_based_path = False),
+            pic_clang_traces_args,
+        )
+
+        sub_targets["pic-clang-traces"] = [
+            DefaultInfo(
+                default_output = all_pic_traces,
+                other_outputs = [pic_clang_traces_args],
+            )
+        ]
+
+    all_diagnostics = None
+
+    # Collect source diagnostics; defer check_sub_target until after header-unit diagnostics
+    input_diagnostics = {}
+    input_clang_tidy_diagnostics = {}
+    if impl_params.generate_sub_targets.objects:
+        objects_sub_targets = compiled_srcs.pic.objects_sub_targets
+        if compiled_srcs.non_pic:
+            objects_sub_targets = objects_sub_targets | compiled_srcs.non_pic.objects_sub_targets
+        sub_targets[OBJECTS_SUBTARGET] = [DefaultInfo(sub_targets = objects_sub_targets)]
+        contains_extra_diagnostics = impl_params.extra_diagnostics and len(impl_params.extra_diagnostics) > 0
+        if len(compiled_srcs.pic.diagnostics) > 0 or contains_extra_diagnostics or impl_params.export_header_unit:
+            input_diagnostics = compiled_srcs.pic.diagnostics
+            if contains_extra_diagnostics or impl_params.export_header_unit:
+                # Avoid creation of merged dict unless needed, for efficiency reasons
+                input_diagnostics = dict(input_diagnostics)
+                if contains_extra_diagnostics:
+                    input_diagnostics.update(impl_params.extra_diagnostics)
+        input_clang_tidy_diagnostics = compiled_srcs.pic.clang_tidy_diagnostics
+
+    # Compilation DB.
+    if impl_params.generate_sub_targets.compilation_database:
+        comp_db = create_compilation_database(ctx, compiled_srcs.compile_cmds.src_compile_cmds, "compilation-database")
+        sub_targets["compilation-database"] = [comp_db]
+
+        # Compilation DB including headers.
+        comp_db = create_compilation_database(ctx, compiled_srcs.compile_cmds.comp_db_compile_cmds, "full-compilation-database")
+        sub_targets["full-compilation-database"] = [comp_db]
+
+    # comp_db_compile_cmds can include header files being compiled as C++ which should not be exposed in the [compilation-database] subtarget
+    comp_db_info = None
+    if impl_params.generate_providers.compilation_database:
+        comp_db_info = make_compilation_db_info(compiled_srcs.compile_cmds.comp_db_compile_cmds, get_cxx_toolchain_info(ctx), get_cxx_platform_info(ctx))
+        providers.append(comp_db_info)
+
+    # Link Groups
+    link_group = get_link_group(ctx)
+    link_group_info = impl_params.link_group_info or get_link_group_info(ctx)
+
+    if link_group_info:
+        link_groups = link_group_info.groups
+        link_group_mappings = link_group_info.mappings
+        link_group_deps = [link_group_info.graph]
+        link_group_libs = gather_link_group_libs(
+            deps = deps_all_non_exported_first,
+        )
+        providers.append(link_group_info)
+    else:
+        link_groups = {}
+        link_group_mappings = {}
+        link_group_deps = []
+        link_group_libs = {}
+    link_group_preferred_linkage = get_link_group_preferred_linkage(link_groups.values())
+
+    # Create the linkable graph from the library's deps, exported deps and any link group deps.
+    linkable_graph_deps = deps_all_non_exported_first + link_group_deps
+    deps_linkable_graph = create_linkable_graph(
+        ctx,
+        deps = linkable_graph_deps,
+    )
+
+    frameworks_linkable = apple_create_frameworks_linkable(ctx)
+    swiftmodule_linkable = impl_params.swiftmodule_linkable
+    dep_infos, link_group_map, link_execution_preference = _get_shared_library_links(
+        ctx,
+        partial(reduce_linkable_graph, deps_linkable_graph),
+        link_group,
+        link_group_mappings,
+        link_group_preferred_linkage,
+        link_group_libs,
+        exported_deps,
+        non_exported_deps,
+        impl_params.force_link_group_linking,
+        frameworks_linkable,
+        swiftmodule_linkable,
+        force_static_follows_dependents = impl_params.link_groups_force_static_follows_dependents,
+    )
+    if impl_params.generate_sub_targets.link_group_map and link_group_map:
+        sub_targets[LINK_GROUP_MAP_DATABASE_SUB_TARGET] = [link_group_map]
+
+    extra_static_linkables = []
+    if frameworks_linkable:
+        extra_static_linkables.append(frameworks_linkable)
+    if swiftmodule_linkable:
+        extra_static_linkables.append(swiftmodule_linkable)
+
+    library_outputs = _form_library_outputs(
+        ctx = ctx,
+        impl_params = impl_params,
+        compiled_srcs = compiled_srcs,
+        preferred_linkage = preferred_linkage,
+        dep_infos = dep_infos,
+        extra_static_linkables = extra_static_linkables,
+        gnu_use_link_groups = cxx_is_gnu(ctx) and bool(link_group_mappings),
+        link_execution_preference = link_execution_preference,
+        compile_pch = compile_pch,
+    )
+    shared_libs = create_flavored_shared_libraries(ctx, library_outputs.solibs)
+
+    for link_style_output in library_outputs.outputs.values():
+        if LinkableFlavor("default") not in link_style_output:
+            continue
+
+        for key in link_style_output[LinkableFlavor("default")].sub_targets.keys():
+            if key in sub_targets:
+                fail("The subtarget `{}` already exists!".format(key))
+        sub_targets.update(link_style_output[LinkableFlavor("default")].sub_targets)
+
+    providers.extend(library_outputs.providers)
+
+    pic_behavior = get_cxx_toolchain_info(ctx).pic_behavior
+
+    # This is the output style for the library's own link_strategy+preferred_linkage.
+    default_output_style = get_lib_output_style(to_link_strategy(cxx_attr_link_style(ctx)), preferred_linkage, pic_behavior)
+
+    # Output sub-targets for all output-styles.
+    if impl_params.generate_sub_targets.link_style_outputs or impl_params.generate_providers.link_style_outputs:
+        default_output_style_providers = []
+        for output_style in get_output_styles_for_linkage(preferred_linkage):
+            output = library_outputs.outputs.get(output_style, {}).get(LinkableFlavor("default"), None)
+            output_style_sub_targets, output_style_providers = impl_params.output_style_sub_targets_and_providers_factory(
+                output_style,
+                ctx,
+                output,
+            )
+            if output != None and output.unstripped != None:
+                output_style_providers.append(
+                    UnstrippedLinkOutputInfo(artifact = output.unstripped),
+                )
+
+            if output:
+                # Add any subtargets for this output style.
+                output_style_sub_targets.update(output.sub_targets)
+
+            if impl_params.generate_sub_targets.link_style_outputs:
+                if output:
+                    sub_targets[subtarget_for_output_style(output_style)] = [
+                        DefaultInfo(
+                            default_output = output.default,
+                            other_outputs = output.other,
+                            sub_targets = output_style_sub_targets,
+                        )
+                    ] + (output_style_providers if output_style_providers else [])
+
+                if output_style == default_output_style:
+                    # If we have additional providers for the current link style,
+                    # add them to the list of default providers
+                    # TODO(cjhopman): This looks like a bug, adding to providers probably shouldn't depend on generate_sub_target.link_style_outputs
+                    default_output_style_providers += output_style_providers
+
+                    # In addition, ensure any subtargets for the active link style
+                    # can be accessed as a default subtarget
+                    for output_style_sub_target_name, output_style_sub_target_providers in output_style_sub_targets.items():
+                        sub_targets[output_style_sub_target_name] = output_style_sub_target_providers
+
+        if impl_params.generate_providers.link_style_outputs:
+            providers += default_output_style_providers
+
+    # Create the default output for the library rule given it's link style and preferred linkage
+    # It's possible for a library to not produce any output, for example, a header only library doesn't produce any archive or shared lib
+    default_output = library_outputs.outputs.get(default_output_style, {}).get(LinkableFlavor("default"), None)
+
+    if default_output and default_output.bitcode_bundle:
+        sub_targets["bitcode"] = [DefaultInfo(default_output = default_output.bitcode_bundle.artifact)]
+
+    # Define the xcode data sub target
+    xcode_data_info = None
+    if impl_params.generate_sub_targets.xcode_data:
+        xcode_data_default_info, xcode_data_info = generate_xcode_data(
+            ctx,
+            rule_type = impl_params.rule_type,
+            output = default_output.default if default_output else None,
+            populate_rule_specific_attributes_func = impl_params.cxx_populate_xcode_attributes_func,
+            srcs = impl_params.srcs + impl_params.additional.srcs,
+            argsfiles = compiled_srcs.compile_cmds.argsfiles.xcode,
+            product_name = get_default_cxx_library_product_name(ctx, impl_params),
+        )
+        sub_targets[XCODE_DATA_SUB_TARGET] = xcode_data_default_info
+        providers.append(xcode_data_info)
+
+    # Propagate link info provider.
+    if impl_params.generate_providers.merged_native_link_info or impl_params.generate_providers.template_placeholders:
+        # Gather link inputs.
+        # Windows needs to include a linkable PCH object, this is not required for other platforms
+        inherited_non_exported_link = cxx_inherited_link_info(non_exported_deps + filter(None, [impl_params.precompiled_header]))
+        inherited_exported_link = cxx_inherited_link_info(exported_deps)
+
+        merged_native_link_info = create_merged_link_info(
+            ctx,
+            pic_behavior,
+            # Add link info for each link style,
+            library_outputs.link_infos,
+            preferred_linkage = preferred_linkage,
+            # Export link info from non-exported deps (when necessary).
+            deps = inherited_non_exported_link,
+            # Export link info from out (exported) deps.
+            exported_deps = inherited_exported_link,
+            frameworks_linkable = frameworks_linkable,
+            swiftmodule_linkable = swiftmodule_linkable,
+        )
+        if impl_params.generate_providers.merged_native_link_info:
+            providers.append(merged_native_link_info)
+    else:
+        # This code sets merged_native_link_info only in some cases, leaving it unassigned in others.
+        # Add a fake definition set to None so the assignment checker is satisfied.
+        merged_native_link_info = None
+        inherited_non_exported_link = None
+        inherited_exported_link = None
+
+    # Propagate shared libraries up the tree.
+    if impl_params.generate_providers.shared_libraries:
+        providers.append(
+            merge_shared_libraries(
+                ctx.actions,
+                shared_libs,
+                filter_and_map_idx(SharedLibraryInfo, deps_all_non_exported_first),
+            )
+        )
+        providers.append(
+            create_unix_env_info(
+                actions = ctx.actions,
+                env = UnixEnv(
+                    label = ctx.label,
+                    native_libs = [shared_libs],
+                ),
+                deps = deps_all_exported_first,
+            ),
+        )
+
+    propagated_preprocessor_merge_list = inherited_exported_preprocessor_infos
+    if _attr_reexport_all_header_dependencies(ctx):
+        propagated_preprocessor_merge_list = inherited_non_exported_preprocessor_infos + propagated_preprocessor_merge_list
+
+    # Header unit PCM.
+    header_unit_diagnostics = {}
+    if impl_params.generate_sub_targets.header_unit:
+        if compiled_srcs.header_unit_preprocessors:
+            header_unit_preprocessors = []
+            header_unit_sub_targets = []
+            header_unit_clang_traces = []
+
+            def header_unit_clang_trace_sub_target(clang_traces):
+                if impl_params.generate_sub_targets.clang_traces:
+                    return {
+                        "clang-trace": [
+                            DefaultInfo(default_outputs = clang_traces),
+                        ],
+                    }
+                else:
+                    return {}
+
+            def add_header_unit_clang_trace_sub_target(clang_traces):
+                header_unit_clang_traces.extend(clang_traces)
+                return header_unit_clang_trace_sub_target(clang_traces)
+
+            def add_header_unit_check_sub_target(group_diagnostics, header_unit_group_idx):
+                if group_diagnostics:
+                    header_unit_diagnostics.update(group_diagnostics)
+                    group_check_providers, _ = check_sub_target(
+                        ctx,
+                        group_diagnostics,
+                        error_handler = impl_params.error_handler,
+                        output_name = "header_unit{}.diagnostics.txt".format(header_unit_group_idx),
+                    )
+                    return {
+                        "check": group_check_providers,
+                    }
+                else:
+                    return {}
+
+            header_unit_group_idx = 0
+            for x in compiled_srcs.header_unit_preprocessors:
+                header_unit_preprocessors.append(x)
+                header_unit_group_idx += 1
+                header_unit_sub_targets.append([
+                    DefaultInfo(
+                        default_outputs = [h.module for h in x.header_units],
+                        sub_targets = (
+                            add_header_unit_clang_trace_sub_target(filter(None, [h.clang_trace for h in x.header_units]))
+                            | add_header_unit_check_sub_target(
+                                {h.name: h.diagnostics for h in x.header_units if h.diagnostics != None}, header_unit_group_idx
+                            )
+                        ),
+                    ),
+                    cxx_merge_cpreprocessors(
+                        ctx.actions,
+                        own_exported_preprocessors + header_unit_preprocessors,
+                        propagated_preprocessor_merge_list,
+                    ),
+                ])
+
+            # Build [header-unit][check] from all header unit diagnostics
+            header_unit_check_sub = {}
+            if header_unit_diagnostics:
+                header_unit_check_providers, _ = check_sub_target(
+                    ctx,
+                    header_unit_diagnostics,
+                    error_handler = impl_params.error_handler,
+                    output_name = "header_unit_diagnostics.txt",
+                )
+                header_unit_check_sub["check"] = header_unit_check_providers
+            sub_targets["header-unit"] = [
+                DefaultInfo(
+                    default_outputs = [h.module for x in header_unit_preprocessors for h in x.header_units],
+                    sub_targets = {str(i): x for i, x in enumerate(header_unit_sub_targets)}
+                    | header_unit_clang_trace_sub_target(header_unit_clang_traces)
+                    | header_unit_check_sub,
+                ),
+                header_unit_sub_targets[-1][1],
+            ]
+            if impl_params.export_header_unit:
+                own_exported_preprocessors.extend(header_unit_preprocessors)
+        else:
+            sub_targets["header-unit"] = [
+                EMPTY_DEFAULT_INFO,
+                cxx_merge_cpreprocessors(
+                    ctx.actions,
+                    own_exported_preprocessors,
+                    propagated_preprocessor_merge_list,
+                ),
+            ]
+
+    # Build [check]: syntax diagnostics + header unit diagnostics in default output.
+    # Clang-tidy diagnostics are accessible as per-file sub_targets only.
+    if impl_params.export_header_unit:
+        input_diagnostics.update(header_unit_diagnostics)
+    if len(input_diagnostics) > 0:
+        sub_targets["check"], all_diagnostics = check_sub_target(
+            ctx,
+            input_diagnostics,
+            error_handler = impl_params.error_handler,
+            extra_sub_targets = input_clang_tidy_diagnostics,
+        )
+
+    # Build [check-all]: syntax + clang-tidy + header unit diagnostics
+    # (always includes header-unit diagnostics regardless of export_header_unit).
+    check_all_diagnostics = dict(input_diagnostics)
+    check_all_diagnostics.update(input_clang_tidy_diagnostics)
+    if header_unit_diagnostics:
+        check_all_diagnostics.update(header_unit_diagnostics)
+    if len(check_all_diagnostics) > len(input_diagnostics):
+        check_all_subtarget_result = check_sub_target(
+            ctx,
+            check_all_diagnostics,
+            error_handler = impl_params.error_handler,
+            output_name = "all_diagnostics.txt",
+        )
+        sub_targets["check-all"] = check_all_subtarget_result[0]
+
+    propagated_preprocessor = cxx_merge_cpreprocessors(
+        ctx.actions,
+        own_exported_preprocessors,
+        propagated_preprocessor_merge_list,
+    )
+    if impl_params.generate_providers.preprocessors:
+        providers.append(propagated_preprocessor)
+
+    # Propagated_exported_preprocessor_info is used for pcm compilation, which isn't possible for non-modular targets.
+    propagated_exported_preprocessor_info = propagated_preprocessor if impl_params.rule_type == "apple_library" and ctx.attrs.modular else None
+    additional_providers = (
+        impl_params.additional.additional_providers_factory(propagated_exported_preprocessor_info)
+        if impl_params.additional.additional_providers_factory
+        else []
+    )
+
+    if impl_params.generate_providers.third_party_build:
+        third_party_build_info = create_third_party_build_info(
+            ctx = ctx,
+            cxx_headers = [propagated_preprocessor],
+            shared_libs = shared_libs.libraries,
+            deps = deps_all_exported_first,
+            project = ctx.attrs.third_party_project,
+        )
+        providers.append(third_party_build_info)
+        sub_targets["third-party-build"] = [
+            DefaultInfo(
+                default_output = third_party_build_info.build.root.artifact,
+                sub_targets = dict(
+                    manifest = [DefaultInfo(default_output = third_party_build_info.build.manifest)],
+                ),
+            ),
+        ]
+
+    # For v1's `#headers` functionality.
+    if impl_params.generate_sub_targets.headers:
+        sub_targets["headers"] = [
+            propagated_preprocessor,
+            create_merged_link_info(
+                ctx,
+                pic_behavior = pic_behavior,
+                preferred_linkage = Linkage("static"),
+                frameworks_linkable = frameworks_linkable,
+                swiftmodule_linkable = swiftmodule_linkable,
+            ),
+            EMPTY_LINK_GROUP_LIB_INFO,
+            EMPTY_SHARED_LIBRARY_INFO,
+        ] + additional_providers
+
+    if getattr(ctx.attrs, "supports_header_symlink_subtarget", False):
+        package_prefix = str(ctx.label.path)
+        header_symlink_mapping = {}
+        for records in propagated_preprocessor.set.traverse():
+            for record in records:
+                for header in record.headers:
+                    header_path = header.name
+                    if header.namespace:
+                        header_path = paths.join(header.namespace, header_path)
+                    header_symlink_mapping[paths.normalize(header_path)] = header.artifact
+
+                all_include_dirs = record.include_dirs + (record.system_include_dirs.include_dirs if record.system_include_dirs else [])
+                for header in record.raw_headers:
+                    full_header_path = paths.join(package_prefix, header.short_path)
+                    for include_dir in all_include_dirs:
+                        include_dir_path = str(include_dir)
+
+                        if not paths.starts_with(full_header_path, include_dir_path):
+                            continue
+
+                        mapping_path = paths.relativize(full_header_path, include_dir_path)
+                        header_symlink_mapping[mapping_path] = header
+
+        sub_targets["header-symlink-tree"] = [
+            DefaultInfo(
+                default_output = ctx.actions.symlinked_dir("header_symlink_tree", header_symlink_mapping, has_content_based_path = False),
+            )
+        ]
+
+    for additional_subtarget, subtarget_providers in impl_params.additional.subtargets.items():
+        sub_targets[additional_subtarget] = subtarget_providers
+
+    index_stores = []
+    swift_index_stores = []
+    if impl_params.index_stores:
+        # Index store from swift compile
+        index_stores.extend(impl_params.index_stores)
+        swift_index_stores.extend(impl_params.index_stores)
+
+    # Index stores from cxx compile. We only generate the index store for pic
+    if compiled_srcs.pic:
+        index_stores.extend(compiled_srcs.pic.index_stores)
+
+    index_store_subtargets, index_store_info = create_index_store_subtargets_and_provider(ctx, index_stores, swift_index_stores, deps_all_non_exported_first)
+    sub_targets.update(index_store_subtargets)
+    providers.append(index_store_info)
+
+    mod_dep_graph_subtargets, mod_dep_graph_info = create_modularization_dep_graph_subtargets_and_provider(
+        ctx,
+        impl_params.modularization_dependency_graph,
+        deps_all_non_exported_first,
+    )
+    sub_targets.update(mod_dep_graph_subtargets)
+    providers.append(mod_dep_graph_info)
+
+    linker_flags = cxx_attr_linker_flags_all(ctx, impl_params.cxx_flags)
+
+    # Omnibus root provider.
+    linkable_root = None
+    if impl_params.generate_providers.omnibus_root:
+        if impl_params.use_soname:
+            soname = _soname(ctx, impl_params)
+        else:
+            soname = None
+        linker_type = get_cxx_toolchain_info(ctx).linker_info.type
+        linkable_root = create_linkable_root(
+            label = ctx.label,
+            name = soname,
+            link_infos = LinkInfos(
+                default = LinkInfo(
+                    pre_flags = linker_flags.flags + linker_flags.exported_flags,
+                    post_flags = linker_flags.post_flags + linker_flags.exported_post_flags,
+                    linkables = [
+                        ObjectsLinkable(
+                            objects = compiled_srcs.pic.objects,
+                            linker_type = linker_type,
+                            link_whole = True,
+                        )
+                    ],
+                    external_debug_info = make_artifact_tset(
+                        actions = ctx.actions,
+                        label = ctx.label,
+                        artifacts = (
+                            compiled_srcs.pic.external_debug_info + (compiled_srcs.pic.objects if compiled_srcs.pic.objects_have_external_debug_info else [])
+                        ),
+                        children = impl_params.additional.static_external_debug_info,
+                    ),
+                    has_hip_device_debug = compiled_srcs.pic.has_hip_device_debug,
+                    hip_arch_debug_files = compiled_srcs.pic.hip_arch_debug_files,
+                    metadata = cxx_attr_dep_metadata(ctx),
+                ),
+                stripped = LinkInfo(
+                    pre_flags = linker_flags.flags + linker_flags.exported_flags,
+                    post_flags = linker_flags.post_flags + linker_flags.exported_post_flags,
+                    linkables = [
+                        ObjectsLinkable(
+                            objects = compiled_srcs.pic.stripped_objects,
+                            linker_type = linker_type,
+                            link_whole = True,
+                        )
+                    ],
+                    has_hip_device_debug = compiled_srcs.pic.has_hip_device_debug,
+                    hip_arch_debug_files = compiled_srcs.pic.hip_arch_debug_files,
+                    metadata = cxx_attr_dep_metadata(ctx),
+                ),
+            ),
+            deps = deps_all_non_exported_first,
+        )
+        providers.append(linkable_root)
+
+        # Mark libraries that support `dlopen`.
+        if getattr(ctx.attrs, "supports_python_dlopen", False):
+            providers.append(DLOPENABLE_LIBRARY_INFO_MARKER)
+
+    # Augment and provide the linkable graph.
+    if impl_params.generate_providers.linkable_graph:
+        merged_linkable_graph = create_linkable_graph(
+            ctx,
+            node = create_linkable_graph_node(
+                ctx,
+                linkable_node = create_linkable_node(
+                    ctx = ctx,
+                    default_soname = _soname(ctx, impl_params),
+                    preferred_linkage = preferred_linkage,
+                    default_link_strategy = _link_strategy_for_some_shared_links(ctx.attrs),
+                    deps = non_exported_deps,
+                    exported_deps = exported_deps,
+                    # If we don't have link input for this link style, we pass in `None` so
+                    # that omnibus knows to avoid it.
+                    include_in_android_mergemap = getattr(ctx.attrs, "include_in_android_merge_map_output", True) and default_output != None,
+                    # Attach this library's per-source compile commands so app rules can aggregate a
+                    # native compile-command database. Gated (default off) to keep this off the graph
+                    # for normal builds; see _emit_native_build_commands.
+                    compile_cmds = compiled_srcs.compile_cmds.src_compile_cmds if getattr(ctx.attrs, "_emit_native_build_commands", False) else [],
+                    link_infos = library_outputs.link_infos,
+                    shared_libs = shared_libs,
+                    linker_flags = linker_flags,
+                    can_be_asset = getattr(ctx.attrs, "can_be_asset", False) or False,
+                    stub = getattr(ctx.attrs, "stub", False),
+                ),
+                excluded = {ctx.label: None} if not value_or(ctx.attrs.supports_merged_linking, True) else {},
+            ),
+            deps = linkable_graph_deps,
+        )
+        providers.append(merged_linkable_graph)
+
+    # C++ resource.
+    if impl_params.generate_providers.resources:
+        resources = cxx_attr_resources(ctx)
+        providers.append(
+            make_resource_info(
+                gather_resources(
+                    label = ctx.label,
+                    resources = resources,
+                    deps = deps_all_non_exported_first,
+                ),
+            ),
+        )
+        if impl_params.generate_providers.cxx_resources_as_apple_resources:
+            apple_resource_graph = create_resource_graph(
+                ctx = ctx,
+                labels = ctx.attrs.labels,
+                deps = non_exported_deps,
+                exported_deps = exported_deps,
+                cxx_resource_spec = CxxResourceSpec(resources = resources) if resources else None,
+            )
+            providers.append(apple_resource_graph)
+
+    if impl_params.generate_providers.template_placeholders:
+        templ_vars = {}
+
+        # Some rules, e.g. fbcode//thrift/lib/cpp:thrift-core-module
+        # define preprocessor flags as things like: -DTHRIFT_PLATFORM_CONFIG=<thrift/facebook/PlatformConfig.h>
+        # and unless they get quoted, they break shell syntax.
+        cxx_compiler_info = get_cxx_toolchain_info(ctx).cxx_compiler_info
+        cxx_preprocessor_flags = cmd_args(
+            cmd_args(cxx_compiler_info.preprocessor_flags or [], quote = "shell"),
+            cmd_args(propagated_preprocessor.set.project_as_args("args"), quote = "shell"),
+            propagated_preprocessor.set.project_as_args("include_dirs"),
+        )
+        templ_vars["cxxppflags"] = cxx_preprocessor_flags
+
+        c_compiler_info = get_cxx_toolchain_info(ctx).c_compiler_info
+        c_preprocessor_flags = cmd_args(
+            cmd_args(c_compiler_info.preprocessor_flags or [], quote = "shell"),
+            cmd_args(propagated_preprocessor.set.project_as_args("args"), quote = "shell"),
+            propagated_preprocessor.set.project_as_args("include_dirs"),
+        )
+        templ_vars["cppflags"] = c_preprocessor_flags
+
+        # Add in ldflag macros.
+        for link_strategy in (LinkStrategy("static"), LinkStrategy("static_pic")):
+            name = "ldflags-" + link_strategy.value.replace("_", "-")
+            args = []
+            linker_info = get_cxx_toolchain_info(ctx).linker_info
+            args.append(linker_info.linker_flags or [])
+
+            # Normally, we call get_link_args_for_strategy for getting the args for our own link from our
+            # deps. This case is a bit different as we are effectively trying to get the args for how this library
+            # would be represented on a dependent's link line and so it is appropriate to use our own merged_native_link_info.
+            link_args = get_link_args_for_strategy(
+                ctx.actions,
+                ctx.label,
+                get_cxx_toolchain_info(ctx).linker_info,
+                [merged_native_link_info],
+                link_strategy,
+                prefer_stripped = False,
+                transformation_spec_context = None,
+            )
+            args.append(unpack_link_args(link_args))
+            templ_vars[name] = cmd_args(args)
+
+        # TODO(T110378127): To implement `$(ldflags-shared ...)` properly, we'd need
+        # to setup a symink tree rule for all transitive shared libs.  Since this
+        # currently would be pretty costly (O(N^2)?), and since it's not that
+        # commonly used anyway, just use `static-pic` instead.  Longer-term, once
+        # v1 is gone, macros that use `$(ldflags-shared ...)` (e.g. Haskell's
+        # hsc2hs) can move to a v2 rules-based API to avoid needing this macro.
+        templ_vars["ldflags-shared"] = templ_vars["ldflags-static-pic"]
+
+        providers.append(TemplatePlaceholderInfo(keyed_variables = templ_vars))
+
+    # It is possible (e.g. in a java binary or an Android APK) to have C++ libraries that depend
+    # upon Java libraries (through JNI). In some cases those Java libraries are not depended upon
+    # anywhere else, so we need to expose them here to ensure that they are packaged into the
+    # final binary.
+    if impl_params.generate_providers.java_packaging_info:
+        providers.append(get_java_packaging_info(ctx, deps_all_non_exported_first))
+
+    if impl_params.generate_providers.java_global_code_info:
+        providers.append(propagate_global_code_info(ctx, ctx.attrs.deps + getattr(ctx.attrs, "exported_deps", [])))
+
+    # TODO(T107163344) this shouldn't be in cxx_library itself, use overlays to remove it.
+    if impl_params.generate_providers.android_packageable_info:
+        providers.append(merge_android_packageable_info(ctx.label, ctx.actions, deps_all_non_exported_first))
+
+    bitcode_bundle = default_output.bitcode_bundle if default_output != None else None
+    if bitcode_bundle:
+        bc_provider = BitcodeBundleInfo(bitcode = bitcode_bundle, bitcode_bundle = ctx.actions.tset(BitcodeTSet, value = bitcode_bundle))
+        additional_providers.append(bc_provider)
+
+    # Add prefer-static and prefer-shared sub-targets for dependent-specific linkage control.
+    # These expose the library with different preferred linkages, allowing dependents to
+    # explicitly choose static or shared linking regardless of the library's default.
+    if impl_params.generate_providers.merged_native_link_info:
+        for linkage in (Linkage("static"), Linkage("shared")):
+            # Get the appropriate output for this linkage
+            linkage_output_style = get_lib_output_style(to_link_strategy(cxx_attr_link_style(ctx)), linkage, pic_behavior)
+            linkage_output = library_outputs.outputs.get(linkage_output_style, {}).get(LinkableFlavor("default"), None)
+
+            # Create MergedLinkInfo with this linkage (reuses inherited_*_link from above)
+            linkage_merged_link_info = create_merged_link_info(
+                ctx,
+                pic_behavior,
+                library_outputs.link_infos,
+                preferred_linkage = linkage,
+                deps = inherited_non_exported_link,
+                exported_deps = inherited_exported_link,
+                frameworks_linkable = frameworks_linkable,
+                swiftmodule_linkable = swiftmodule_linkable,
+            )
+
+            # Check if we have the required output styles for this linkage
+            required_output_styles = get_output_styles_for_linkage(linkage)
+            has_required_outputs = True
+            for style in required_output_styles:
+                if style not in library_outputs.link_infos:
+                    has_required_outputs = False
+                    break
+
+            # Include all providers needed for this sub-target to be usable as a dependency
+            linkage_providers = [
+                linkage_merged_link_info,
+                propagated_preprocessor,
+                EMPTY_LINK_GROUP_LIB_INFO,
+                EMPTY_SHARED_LIBRARY_INFO,
+            ]
+
+            # Only create LinkableGraph if we have all required output styles for this linkage
+            if has_required_outputs and impl_params.generate_providers.linkable_graph:
+                linkage_linkable_graph = create_linkable_graph(
+                    ctx,
+                    node = create_linkable_graph_node(
+                        ctx,
+                        linkable_node = create_linkable_node(
+                            ctx = ctx,
+                            default_soname = _soname(ctx, impl_params),
+                            preferred_linkage = linkage,
+                            default_link_strategy = _link_strategy_for_some_shared_links(ctx.attrs),
+                            deps = non_exported_deps,
+                            exported_deps = exported_deps,
+                            include_in_android_mergemap = getattr(ctx.attrs, "include_in_android_merge_map_output", True) and default_output != None,
+                            compile_cmds = compiled_srcs.compile_cmds.src_compile_cmds if getattr(ctx.attrs, "_emit_native_build_commands", False) else [],
+                            link_infos = library_outputs.link_infos,
+                            shared_libs = shared_libs,
+                            linker_flags = linker_flags,
+                            can_be_asset = getattr(ctx.attrs, "can_be_asset", False) or False,
+                            stub = getattr(ctx.attrs, "stub", False),
+                        ),
+                        excluded = {ctx.label: None} if not value_or(ctx.attrs.supports_merged_linking, True) else {},
+                    ),
+                    deps = linkable_graph_deps,
+                )
+                linkage_providers.append(linkage_linkable_graph)
+            if linkage_output:
+                linkage_providers.append(
+                    DefaultInfo(
+                        default_output = linkage_output.default,
+                    )
+                )
+            sub_targets["prefer-{}".format(linkage.value)] = linkage_providers
+
+    xplugins_usage_info = get_xplugins_usage_info(ctx.actions, deps_all_non_exported_first)
+    if xplugins_usage_info:
+        providers.append(xplugins_usage_info)
+
+    xplugins_debug_info = xplugins_get_debug_artifacts_info(
+        ctx,
+        deps_all_non_exported_first,
+    )
+    if xplugins_debug_info:
+        providers.append(xplugins_debug_info)
+
+    if TARGET_STATS_ENABLED:
+        target_stats_tools = get_cxx_toolchain_info(ctx).target_stats_tools
+        if target_stats_tools != None:
+            # Keyed by each file's path within the target, which is what a
+            # consumer can line up against the target's own source list.
+            target_stats_srcs = {src.file.short_path: src.file for src in impl_params.srcs + impl_params.additional.srcs}
+            target_stats_srcs.update(impl_params.target_stats_extra_srcs)
+            target_stats_providers, target_stats_subtargets = target_stats_providers_and_subtargets(
+                ctx,
+                tools = target_stats_tools,
+                srcs = target_stats_srcs,
+                deps = non_exported_deps + exported_deps,
+                cycle_mode = CycleMode(impl_params.target_stats_cycle_mode),
+                module_name = impl_params.target_stats_module_name or ctx.label.name,
+                swift_dot = impl_params.target_stats_swift_dot,
+            )
+            providers.extend(target_stats_providers)
+            sub_targets.update(target_stats_subtargets)
+
+    if impl_params.generate_providers.default:
+        if False:
+            # TODO(nga): `default_output.unstripped` is never `None`.
+            def unknown():
+                pass
+
+            default_output = unknown()
+
+        default_info = DefaultInfo(
+            default_output = default_output.default if default_output != None else None,
+            other_outputs = default_output.other if default_output != None else [],
+            sub_targets = sub_targets,
+        )
+        providers.append(default_info)
+
+    # Propagate all transitive link group lib roots up the tree, so that the
+    # final executable can use them.
+    if impl_params.generate_providers.merged_native_link_info:
+        providers.append(
+            merge_link_group_lib_info(
+                label = ctx.label,
+                name = link_group,
+                shared_libs = shared_libs,
+                shared_link_infos = library_outputs.link_infos.get(LibOutputStyle("shared_lib")),
+                deps = deps_all_exported_first,
+            ),
+        )
+
+    if impl_params.generate_providers.transitive_diagnostics:
+        providers.append(
+            cxx_transitive_diagnostics_combine(
+                ctx = ctx,
+                diagnostics = filter(None, [all_diagnostics]) + impl_params.extra_transitive_diagnostics,
+                deps = deps_all_exported_first,
+            )
+        )
+
+    if getattr(ctx.attrs, "_meta_apple_library_validation_enabled", False):
+        providers.append(
+            CxxLibraryInfo(
+                target = ctx.label,
+                labels = ctx.attrs.labels,
+            ),
+        )
+
+    providers.extend(additional_providers)
+
+    return _CxxLibraryParameterizedOutput(
+        default_output = default_output,
+        all_outputs = library_outputs,
+        sub_targets = sub_targets,
+        bitcode_bundle = bitcode_bundle,
+        providers = providers,
+        index_store_info = index_store_info,
+        modularization_dep_graph_info = mod_dep_graph_info,
+        xcode_data_info = xcode_data_info,
+        cxx_compilationdb_info = comp_db_info,
+        linkable_root = linkable_root,
+        sanitizer_runtime_files = library_outputs.sanitizer_runtime_files,
+    )
+
+def get_default_cxx_library_product_name(ctx, impl_params) -> str:
+    preferred_linkage = cxx_attr_preferred_linkage(ctx)
+    output_style = get_lib_output_style(
+        to_link_strategy(cxx_attr_link_style(ctx)),
+        preferred_linkage,
+        get_cxx_toolchain_info(ctx).pic_behavior,
+    )
+    if output_style == LibOutputStyle("shared_lib"):
+        return _soname(ctx, impl_params)
+    else:
+        return _base_static_library_name(ctx, optimized = False, debuggable = False, stripped = False)
+
+def _collect_hip_arch_debug_files(outs: list[CxxCompileOutput]) -> dict[str, list[Artifact]]:
+    result = {}
+    for out in outs:
+        for arch, f in out.hip_arch_debug_files.items():
+            result.setdefault(arch, [])
+            result[arch].append(f)
+    return result
+
+def _get_library_compile_output(
+    actions: AnalysisActions,
+    cxx_toolchain_info: CxxToolchainInfo,
+    src_compile_cmds: list[CxxSrcCompileCommand],
+    outs: list[CxxCompileOutput],
+    extra_link_input: list[Artifact],
+    supports_stripping: bool,
+    has_content_based_path: bool,
+) -> _CxxLibraryCompileOutput:
+    objects = [out.object for out in outs]
+    stripped_objects = _strip_objects(actions, cxx_toolchain_info, outs, supports_stripping, has_content_based_path)
+
+    pch_object_output = [out.pch_object for out in outs if out.pch_object]
+
+    bitcode_objects = [out.object for out in outs if is_bitcode_format(out.object_format)]
+    if len(bitcode_objects) == 0:
+        bitcode_objects = None
+
+    objects_sub_targets = cxx_objects_sub_targets(outs)
+
+    # add this after setting up sub_targets
+    objects += extra_link_input
+    stripped_objects += extra_link_input
+
+    index_stores = [out.index_store for out in outs if out.index_store]
+
+    diagnostics = {compile_cmd.src.short_path: out.diagnostics for compile_cmd, out in zip(src_compile_cmds, outs) if out.diagnostics != None}
+    clang_tidy_diagnostics = {
+        compile_cmd.src.short_path + ".clang-tidy": out.clang_tidy_diagnostics
+        for compile_cmd, out in zip(src_compile_cmds, outs)
+        if out.clang_tidy_diagnostics != None
+    }
+
+    return _CxxLibraryCompileOutput(
+        objects = objects,
+        pch_object_output = pch_object_output,
+        stripped_objects = stripped_objects,
+        bitcode_objects = bitcode_objects,
+        clang_traces = [out.clang_trace for out in outs if out.clang_trace != None],
+        clang_remarks = [out.clang_remarks for out in outs if out.clang_remarks != None],
+        clang_llvm_statistics = [out.clang_llvm_statistics for out in outs if out.clang_llvm_statistics != None],
+        gcno_files = [out.gcno_file for out in outs if out.gcno_file != None],
+        external_debug_info = [out.external_debug_info for out in outs if out.external_debug_info != None],
+        objects_have_external_debug_info = lazy.is_any(lambda out: out.object_has_external_debug_info, outs),
+        has_hip_device_debug = lazy.is_any(lambda out: out.hip_device_debug, outs),
+        hip_arch_debug_files = _collect_hip_arch_debug_files(outs),
+        objects_sub_targets = objects_sub_targets,
+        index_stores = index_stores,
+        diagnostics = diagnostics,
+        clang_tidy_diagnostics = clang_tidy_diagnostics,
+    )
+
+_CxxSharedLibraryResult = record(
+    # Result from link, includes the shared lib, linker map data etc
+    link_result = CxxLinkResult,
+    # Shared library name (e.g. SONAME)
+    soname = str,
+    # `LinkInfo` used to link against the shared library.
+    info = LinkInfo,
+)
+
+def cxx_compile_srcs(
+    actions: AnalysisActions,
+    target_label: Label,
+    cxx_toolchain_info: CxxToolchainInfo,
+    impl_params: CxxRuleConstructorParams,
+    own_preprocessors: list[CPreprocessor],
+    inherited_non_exported_preprocessor_infos: list[CPreprocessorInfo],
+    inherited_exported_preprocessor_infos: list[CPreprocessorInfo],
+    preferred_linkage: Linkage,
+    add_coverage_instrumentation_compiler_flags: bool,
+    compile_pch: CxxPrecompiledHeader | None = None,
+    own_exported_preprocessors: list[CPreprocessor] = [],
+    filename_prefix: str = "",
+) -> _CxxCompiledSourcesOutput:
+    """
+    Compile objects we'll need for archives and shared libraries.
+    """
+
+    # Create the commands and argsfiles to use for compiling each source file
+    compile_cmd_output = create_compile_cmds(
+        actions = actions,
+        target_label = target_label,
+        toolchain = cxx_toolchain_info,
+        impl_params = impl_params,
+        own_preprocessors = own_preprocessors,
+        inherited_preprocessor_infos = inherited_non_exported_preprocessor_infos + inherited_exported_preprocessor_infos,
+        add_coverage_instrumentation_compiler_flags = add_coverage_instrumentation_compiler_flags,
+        compile_pch = compile_pch,
+        filename_prefix = filename_prefix,
+    )
+
+    # Define header unit.
+    header_unit_preprocessors = []
+    if own_exported_preprocessors:
+        header_preprocessor_info = cxx_merge_cpreprocessors(
+            actions,
+            own_exported_preprocessors,
+            inherited_exported_preprocessor_infos,
+        )
+        header_unit_preprocessors.extend(
+            precompile_cxx(
+                actions = actions,
+                target_label = target_label,
+                toolchain = cxx_toolchain_info,
+                impl_params = impl_params,
+                preprocessors = own_exported_preprocessors,
+                header_preprocessor_info = header_preprocessor_info,
+            )
+        )
+
+    # Define object files.
+    pic_cxx_outs = compile_cxx(
+        actions = actions,
+        target_label = target_label,
+        toolchain = cxx_toolchain_info,
+        src_compile_cmds = compile_cmd_output.src_compile_cmds,
+        flavors = set([CxxCompileFlavor("pic")]),
+        provide_syntax_only = True,
+        separate_debug_info = impl_params.separate_debug_info,
+        use_header_units = impl_params.use_header_units,
+        precompiled_header = impl_params.precompiled_header,
+        compile_pch = compile_pch,
+        cuda_compile_style = impl_params.cuda_compile_style,
+    )
+    pic = _get_library_compile_output(
+        actions = actions,
+        cxx_toolchain_info = cxx_toolchain_info,
+        src_compile_cmds = compile_cmd_output.src_compile_cmds,
+        outs = pic_cxx_outs,
+        extra_link_input = impl_params.extra_link_input,
+        supports_stripping = impl_params.supports_stripping,
+        has_content_based_path = impl_params.use_content_based_paths,
+    )
+
+    non_pic = None
+    pic_optimized = None
+    if preferred_linkage != Linkage("shared"):
+        non_pic_cxx_outs = compile_cxx(
+            actions = actions,
+            target_label = target_label,
+            toolchain = cxx_toolchain_info,
+            src_compile_cmds = compile_cmd_output.src_compile_cmds,
+            flavors = set(),
+            # Diagnostics from the pic and non-pic compilation would be
+            # identical. We can avoid instantiating a second set of actions.
+            provide_syntax_only = False,
+            separate_debug_info = impl_params.separate_debug_info,
+            compile_pch = compile_pch,
+            precompiled_header = impl_params.precompiled_header,
+            use_header_units = impl_params.use_header_units,
+            cuda_compile_style = impl_params.cuda_compile_style,
+        )
+        non_pic = _get_library_compile_output(
+            actions = actions,
+            cxx_toolchain_info = cxx_toolchain_info,
+            src_compile_cmds = compile_cmd_output.src_compile_cmds,
+            outs = non_pic_cxx_outs,
+            extra_link_input = impl_params.extra_link_input,
+            supports_stripping = impl_params.supports_stripping,
+            has_content_based_path = impl_params.use_content_based_paths,
+        )
+
+        if toolchain_supports_flavor(cxx_toolchain_info, CxxCompileFlavor("optimized")):
+            optimized_cxx_outs = compile_cxx(
+                actions = actions,
+                target_label = target_label,
+                toolchain = cxx_toolchain_info,
+                src_compile_cmds = compile_cmd_output.src_compile_cmds,
+                flavors = set([CxxCompileFlavor("pic"), CxxCompileFlavor("optimized")]),
+                # Diagnostics from the pic and non-pic compilation would be
+                # identical. We can avoid instantiating a second set of actions.
+                provide_syntax_only = False,
+                separate_debug_info = impl_params.separate_debug_info,
+                use_header_units = impl_params.use_header_units,
+                cuda_compile_style = impl_params.cuda_compile_style,
+            )
+            pic_optimized = _get_library_compile_output(
+                actions = actions,
+                cxx_toolchain_info = cxx_toolchain_info,
+                src_compile_cmds = compile_cmd_output.src_compile_cmds,
+                outs = optimized_cxx_outs,
+                extra_link_input = impl_params.extra_link_input,
+                supports_stripping = impl_params.supports_stripping,
+                has_content_based_path = impl_params.use_content_based_paths,
+            )
+
+    pic_debuggable = None
+    if toolchain_supports_flavor(cxx_toolchain_info, CxxCompileFlavor("debug")):
+        debuggable_cxx_outs = compile_cxx(
+            actions = actions,
+            target_label = target_label,
+            toolchain = cxx_toolchain_info,
+            src_compile_cmds = compile_cmd_output.src_compile_cmds,
+            flavors = set([CxxCompileFlavor("pic"), CxxCompileFlavor("debug")]),
+            # Diagnostics from the pic and non-pic compilation would be
+            # identical. We can avoid instantiating a second set of actions.
+            provide_syntax_only = False,
+            separate_debug_info = impl_params.separate_debug_info,
+            use_header_units = impl_params.use_header_units,
+            cuda_compile_style = impl_params.cuda_compile_style,
+        )
+        pic_debuggable = _get_library_compile_output(
+            actions = actions,
+            cxx_toolchain_info = cxx_toolchain_info,
+            src_compile_cmds = compile_cmd_output.src_compile_cmds,
+            outs = debuggable_cxx_outs,
+            extra_link_input = impl_params.extra_link_input,
+            supports_stripping = impl_params.supports_stripping,
+            has_content_based_path = impl_params.use_content_based_paths,
+        )
+    return _CxxCompiledSourcesOutput(
+        compile_cmds = compile_cmd_output,
+        pic = pic,
+        pic_optimized = pic_optimized,
+        pic_debuggable = pic_debuggable,
+        non_pic = non_pic,
+        header_unit_preprocessors = header_unit_preprocessors,
+    )
+
+def _form_library_outputs(
+    ctx: AnalysisContext,
+    impl_params: CxxRuleConstructorParams,
+    compiled_srcs: _CxxCompiledSourcesOutput,
+    preferred_linkage: Linkage,
+    dep_infos: LinkArgs,
+    extra_static_linkables: list[[FrameworksLinkable, SwiftmoduleLinkable]],
+    gnu_use_link_groups: bool,
+    link_execution_preference: LinkExecutionPreference,
+    compile_pch: CxxPrecompiledHeader | None,
+) -> _CxxAllLibraryOutputs:
+    # Build static/shared libs and the link info we use to export them to dependents.
+    outputs = {}
+    solibs = {}
+    link_infos = {}
+    providers = []
+    sanitizer_runtime_files = []
+    gcno_files = []
+
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    linker_flags = cxx_attr_linker_flags_all(ctx, impl_params.cxx_flags)
+
+    # Add in exported linker flags.
+    def ldflags(inner: LinkInfo) -> LinkInfo:
+        exported_flags, exported_post_flags = sandbox_exported_linker_flags(
+            linker_info,
+            linker_flags.exported_flags,
+            linker_flags.exported_post_flags,
+        )
+        return wrap_link_info(
+            inner = inner,
+            pre_flags = exported_flags,
+            post_flags = exported_post_flags,
+        )
+
+    def build_static_library(
+        compile_output: _CxxLibraryCompileOutput | None, pic: bool, optimized: bool, debuggable: bool, pch: bool, stripped: bool
+    ) -> (CxxLibraryOutput | None, LinkInfo | None):
+        if not compile_output:
+            return (None, None)
+
+        objects = compile_output.pch_object_output if pch else compile_output.stripped_objects if stripped else compile_output.objects
+
+        if not objects:
+            return (None, None)
+
+        return _static_library(
+            ctx,
+            impl_params,
+            objects,
+            objects_have_external_debug_info = compile_output.objects_have_external_debug_info,
+            external_debug_info = make_artifact_tset(
+                ctx.actions,
+                label = ctx.label,
+                artifacts = compile_output.external_debug_info,
+                children = impl_params.additional.static_external_debug_info,
+            ),
+            pic = pic,
+            optimized = optimized,
+            debuggable = debuggable,
+            stripped = stripped,
+            extra_linkables = extra_static_linkables,
+            bitcode_objects = compile_output.bitcode_objects,
+            has_hip_device_debug = compile_output.has_hip_device_debug,
+            hip_arch_debug_files = compile_output.hip_arch_debug_files,
+        )
+
+    def build_shared_library(
+        compile_output: _CxxLibraryCompileOutput, flavor: LinkableFlavor
+    ) -> (CxxLibraryOutput, _CxxSharedLibraryResult, NamedLinkedObject):
+        external_debug_artifacts = compile_output.external_debug_info
+        if compile_output.objects_have_external_debug_info:
+            external_debug_artifacts.extend(compile_output.objects)
+        if impl_params.extra_link_input_has_external_debug_info:
+            external_debug_artifacts.extend(impl_params.extra_link_input)
+        external_debug_info = make_artifact_tset(
+            actions = ctx.actions,
+            label = ctx.label,
+            artifacts = external_debug_artifacts,
+            children = impl_params.additional.shared_external_debug_info,
+            tags = impl_params.additional.external_debug_info_tags,
+        )
+
+        result = _shared_library(
+            ctx = ctx,
+            impl_params = impl_params,
+            objects = compile_output.objects,
+            external_debug_info = external_debug_info,
+            dep_infos = dep_infos,
+            gnu_use_link_groups = gnu_use_link_groups,
+            link_ordering = map_val(LinkOrdering, ctx.attrs.link_ordering),
+            link_execution_preference = link_execution_preference,
+            flavor = flavor,
+            has_hip_device_debug = compile_output.has_hip_device_debug,
+        )
+        shlib = result.link_result.linked_object
+
+        hip_debug = compile_output.hip_arch_debug_files
+        if hip_debug:
+            shlib = LinkedObject(
+                output = shlib.output,
+                bitcode_bundle = shlib.bitcode_bundle,
+                unstripped_output = shlib.unstripped_output,
+                prebolt_output = shlib.prebolt_output,
+                link_args = shlib.link_args,
+                dwp = shlib.dwp,
+                hip_arch_debug_files = hip_debug,
+                external_debug_info = shlib.external_debug_info,
+                linker_argsfile = shlib.linker_argsfile,
+                linker_command = shlib.linker_command,
+                index_argsfile = shlib.index_argsfile,
+                import_library = shlib.import_library,
+                pdb = shlib.pdb,
+                split_debug_output = shlib.split_debug_output,
+            )
+
+        extra_outputs = result.link_result.extra_outputs
+
+        link_cmd_debug_output_file = None
+        link_cmd_debug_output = make_link_command_debug_output(shlib)
+        if link_cmd_debug_output != None and flavor == LinkableFlavor("default"):
+            link_cmd_debug_output_file = make_link_command_debug_output_json_info(ctx.actions, [link_cmd_debug_output])
+            providers.append(LinkCommandDebugOutputInfo(debug_outputs = [link_cmd_debug_output]))
+
+        unstripped = shlib.unstripped_output
+        output = CxxLibraryOutput(
+            output_style = LibOutputStyle("shared_lib"),
+            default = shlib.output,
+            unstripped = unstripped,
+            object_files = compile_output.objects,
+            external_debug_info = shlib.external_debug_info,
+            dwp = shlib.dwp,
+            hip_arch_debug_files = hip_debug,
+            linker_map = result.link_result.linker_map_data,
+            sub_targets = extra_outputs
+            | {
+                "linker.argsfile": [
+                    DefaultInfo(
+                        default_output = shlib.linker_argsfile,
+                    )
+                ],
+                "linker.command": [
+                    DefaultInfo(
+                        default_outputs = filter(None, [link_cmd_debug_output_file]),
+                    )
+                ],
+                "unstripped": [
+                    DefaultInfo(
+                        default_output = unstripped,
+                    )
+                ],
+            },
+            pdb = shlib.pdb,
+            implib = shlib.import_library,
+        )
+
+        solib = NamedLinkedObject(
+            soname = result.soname,
+            linked_object = shlib,
+            extra_outputs = extra_outputs,
+        )
+
+        return (output, result, solib)
+
+    # We don't know which outputs consumers may want, so we define all the possibilities given our preferred linkage.
+    for output_style in get_output_styles_for_linkage(preferred_linkage):
+        outputs_for_style = {}
+        optimized_info = None
+        debuggable_info = None
+        stripped = None
+        info = None
+
+        # Generate the necessary libraries and
+        # add them to the exported link info.
+        if output_style != LibOutputStyle("shared_lib"):
+            pic = _use_pic(output_style)
+            lib_compile_output = compiled_srcs.pic
+            if not pic:
+                lib_compile_output = compiled_srcs.non_pic
+                if not lib_compile_output:
+                    fail("output_style {} requires non_pic compiled srcs, but didn't have any in {}".format(output_style, compiled_srcs))
+
+            gcno_files += lib_compile_output.gcno_files
+
+            # FYI(patskovn): Note that we are using `pic` in optimized and debuggable transformations here.
+            #                Ideal way to set it up would be to expose whole matrix of debuggable/optimized/pic instead.
+            #                But it increases retained memory (not much really, but still) so in the mean time I decied
+            #                to not do it. As a downside, if transformation spec is used to build a binary statically
+            #                without -fPIE, we are still using pic objects for it. I haven't found any real world impact
+            #                of that though. Another point is: transformation specs are not used for building for production
+            #                and only affect local development so we can do this experiment first. I may revisit that decision.
+            optimized_output, optimized_info = build_static_library(
+                compile_output = compiled_srcs.pic_optimized,
+                pic = pic,
+                optimized = True,
+                debuggable = False,
+                pch = False,
+                stripped = False,
+            )
+            if optimized_output:
+                outputs_for_style[LinkableFlavor("optimized")] = optimized_output
+
+            debuggable_output, debuggable_info = build_static_library(
+                compile_output = compiled_srcs.pic_debuggable,
+                pic = pic,
+                optimized = False,
+                debuggable = True,
+                pch = False,
+                stripped = False,
+            )
+            if debuggable_output:
+                outputs_for_style[LinkableFlavor("debug")] = debuggable_output
+
+            # Only generate an archive if we have objects to include
+            if lib_compile_output.objects or (compile_pch and lib_compile_output.pch_object_output):
+                default_output, info = build_static_library(
+                    compile_output = lib_compile_output,
+                    pic = pic,
+                    optimized = False,
+                    debuggable = False,
+                    pch = bool(compile_pch),
+                    stripped = False,
+                )
+                stripped_output, stripped = _static_library(
+                    ctx,
+                    impl_params,
+                    lib_compile_output.stripped_objects,
+                    pic = pic,
+                    stripped = True,
+                    optimized = False,
+                    debuggable = False,
+                    extra_linkables = extra_static_linkables,
+                    bitcode_objects = lib_compile_output.bitcode_objects,
+                    has_hip_device_debug = lib_compile_output.has_hip_device_debug,
+                    hip_arch_debug_files = lib_compile_output.hip_arch_debug_files,
+                )
+                if default_output:
+                    outputs_for_style[LinkableFlavor("default")] = default_output
+                if stripped_output:
+                    outputs_for_style[LinkableFlavor("stripped")] = stripped_output
+            else:
+                # Header only libraries can have `extra_static_linkables`
+                info = LinkInfo(
+                    name = ctx.label.name,
+                    linkables = extra_static_linkables,
+                    metadata = cxx_attr_dep_metadata(ctx),
+                )
+        else:  # shared
+            # Bare-metal toolchains don't support shared libraries (ld lacks -shared).
+            # Provide the pic_archive as fallback to satisfy the linkable graph.
+            if not get_cxx_toolchain_info(ctx).linker_info.supports_shared_libraries:
+                if preferred_linkage == Linkage("shared"):
+                    fail("{}: cannot build shared library for a toolchain that does not support shared libraries".format(ctx.label))
+                link_infos[output_style] = link_infos[LibOutputStyle("pic_archive")]
+                continue
+
+            # If requested (by build_empty_so), we still generate a shared library even if there's no source objects.
+            # This could be useful because it can still point to dependencies.
+            # i.e. a rust_python_extension is an empty .so depending on a rust shared object
+            compile_output = compiled_srcs.pic
+            if compile_output.objects or impl_params.build_empty_so:
+                gcno_files += compile_output.gcno_files
+
+                default_output, result, solib = build_shared_library(
+                    compile_output = compiled_srcs.pic,
+                    flavor = LinkableFlavor("default"),
+                )
+                info = result.info
+                outputs_for_style[LinkableFlavor("default")] = default_output
+                solibs[LinkableFlavor("default")] = solib
+
+                providers.append(result.link_result.link_execution_preference_info)
+
+                link_sanitizer_runtime_files = result.link_result.sanitizer_runtime_files
+                if link_sanitizer_runtime_files:
+                    if sanitizer_runtime_files:
+                        fail("Cannot specify sanitizer runtime files multiple times")
+                    sanitizer_runtime_files = link_sanitizer_runtime_files
+
+            if compiled_srcs.pic_optimized and (compiled_srcs.pic_optimized.objects or impl_params.build_empty_so):
+                optimized_output, optimized_result, optimized_solib = build_shared_library(
+                    compile_output = compiled_srcs.pic_optimized,
+                    flavor = LinkableFlavor("optimized"),
+                )
+                optimized_info = optimized_result.info
+                outputs_for_style[LinkableFlavor("optimized")] = optimized_output
+                solibs[LinkableFlavor("optimized")] = optimized_solib
+
+            if compiled_srcs.pic_debuggable and (compiled_srcs.pic_debuggable.objects or impl_params.build_empty_so):
+                debug_output, debug_result, debug_solib = build_shared_library(
+                    compile_output = compiled_srcs.pic_debuggable,
+                    flavor = LinkableFlavor("debug"),
+                )
+                debuggable_info = debug_result.info
+                outputs_for_style[LinkableFlavor("debug")] = debug_output
+                solibs[LinkableFlavor("debug")] = debug_solib
+
+        if outputs_for_style:
+            outputs[output_style] = outputs_for_style
+
+        # you cannot link against header only libraries so create an empty link info
+        info = info if info != None else LinkInfo()
+        link_infos[output_style] = LinkInfos(
+            label = ctx.label,
+            default = ldflags(info),
+            optimized = ldflags(optimized_info) if optimized_info != None else None,
+            debuggable = ldflags(debuggable_info) if debuggable_info != None else None,
+            stripped = ldflags(stripped) if stripped != None else None,
+        )
+
+    if get_cxx_toolchain_info(ctx).gcno_files:
+        deps_gcno_files = [x[GcnoFilesInfo].gcno_files for x in ctx.attrs.deps + ctx.attrs.exported_deps if GcnoFilesInfo in x]
+        providers.append(
+            GcnoFilesInfo(
+                gcno_files = dedupe(flatten(deps_gcno_files) + gcno_files),
+            )
+        )
+
+    return _CxxAllLibraryOutputs(
+        outputs = outputs,
+        link_infos = link_infos,
+        providers = providers,
+        solibs = solibs,
+        sanitizer_runtime_files = sanitizer_runtime_files,
+    )
+
+def _strip_objects(
+    actions: AnalysisActions, cxx_toolchain_info: CxxToolchainInfo, outs: list[CxxCompileOutput], supports_stripping: bool, has_content_based_path: bool
+) -> list[Artifact]:
+    """
+    Return new objects with debug info stripped.
+    """
+
+    # Stripping is not supported on Windows
+    linker_type = cxx_toolchain_info.linker_info.type
+    if linker_type == LinkerType("windows"):
+        return [out.object for out in outs]
+
+    # Disable stripping if no `strip` binary was provided by the toolchain.
+    if cxx_toolchain_info.binary_utilities_info == None or cxx_toolchain_info.binary_utilities_info.strip == None:
+        return [out.object for out in outs]
+
+    # Disable stripping if library opted out from it
+    if not supports_stripping:
+        return [out.object for out in outs]
+
+    stripped_objects = []
+
+    for out in outs:
+        obj = out.object
+        if out.hip_device_debug:
+            # hip_debug_extract already rewrote the embedded GPU code objects;
+            # a second strip invalidates ELF extended section indexes.
+            stripped_objects.append(obj)
+            continue
+        base, ext = paths.split_extension(obj.short_path)
+        expect(ext == ".o")
+        stripped_objects.append(strip_debug_info(actions, base + ".stripped.o", obj, cxx_toolchain_info, has_content_based_path = has_content_based_path))
+
+    return stripped_objects
+
+def _get_shared_library_links(
+    ctx: AnalysisContext,
+    reduce_linkable_graph_func: typing.Callable[[], ReducedLinkableGraph],
+    link_group: [str, None],
+    link_group_mappings: [dict[Label, str], None],
+    link_group_preferred_linkage: dict[Label, Linkage],
+    link_group_libs: dict[str, LinkGroupLib],
+    exported_deps: list[Dependency],
+    non_exported_deps: list[Dependency],
+    force_link_group_linking,
+    frameworks_linkable: [FrameworksLinkable, None],
+    swiftmodule_linkable: [SwiftmoduleLinkable, None],
+    force_static_follows_dependents: bool = True,
+) -> (LinkArgs, [DefaultInfo, None], LinkExecutionPreference):
+    """
+    Returns LinkArgs with the content to link, and a link group map json output if applicable.
+
+    TODO(T110378116): Omnibus linking always creates shared libraries by linking
+    against shared dependencies. This is not true for link groups and possibly
+    other forms of shared libraries. Ideally we consolidate this logic and
+    propagate up only the expected links. Until we determine the comprehensive
+    logic here, simply diverge behavior on whether link groups are defined.
+    """
+
+    pic_behavior = get_cxx_toolchain_info(ctx).pic_behavior
+
+    # If we're not filtering for link groups, link against the shared dependencies
+    if not link_group_mappings and not force_link_group_linking:
+        deps = dedupe(flatten([non_exported_deps, exported_deps]))
+        deps_merged_link_infos = cxx_inherited_link_info(deps)
+
+        link_strategy = _link_strategy_for_some_shared_links(ctx.attrs)
+
+        # We cannot support deriving link execution preference off the included links, as we've already
+        # lost the information on what is in the link.
+        # TODO(T152860998): Derive link_execution_preference based upon the included links
+        # Not all rules calling `cxx_library_parameterized` have `link_execution_preference`. Notably `cxx_python_extension`.
+        link_execution_preference = (
+            get_link_execution_preference(ctx, []) if hasattr(ctx.attrs, "link_execution_preference") else LinkExecutionPreference("any")
+        )
+
+        return (
+            apple_build_link_args_with_deduped_flags(
+                ctx,
+                deps_merged_link_infos,
+                frameworks_linkable,
+                # fPIC behaves differently on various combinations of toolchains + platforms.
+                # To get the link_strategy, we have to check the link_strategy against the toolchain's pic_behavior.
+                #
+                # For more info, check the PicBehavior docs.
+                process_link_strategy_for_pic_behavior(link_strategy, pic_behavior),
+                None,
+                swiftmodule_linkable,
+            ),
+            None,
+            link_execution_preference,
+        )
+
+    # Else get filtered link group links
+    prefer_stripped = cxx_is_gnu(ctx) and ctx.attrs.prefer_stripped_objects
+
+    # TODO(cjhopman): Why is this different than where we compute just above for the non link-group case?
+    link_strategy = to_link_strategy(cxx_attr_link_style(ctx))
+    if link_strategy == LinkStrategy("static"):
+        link_strategy = LinkStrategy("static_pic")
+    link_strategy = process_link_strategy_for_pic_behavior(link_strategy, pic_behavior)
+    reduced_linkable_graph = reduce_linkable_graph_func()
+
+    roots = set(linkable_deps(non_exported_deps + exported_deps))
+    is_executable_link = False
+    lib_linkables = collect_linkables(
+        reduced_linkable_graph,
+        is_executable_link,
+        link_strategy,
+        link_group_preferred_linkage,
+        pic_behavior,
+        roots,
+    )
+
+    build_context = BuildLinkGroupsContext(
+        public_nodes = set(),
+        linkable_graph = reduced_linkable_graph,
+        link_groups = {},
+        link_group_mappings = link_group_mappings,
+        link_group_preferred_linkage = link_group_preferred_linkage,
+        link_strategy = link_strategy,
+        pic_behavior = pic_behavior,
+        link_group_libs = {name: (lib.label, lib.shared_link_infos) for name, lib in link_group_libs.items()},
+        prefer_stripped = prefer_stripped,
+        prefer_optimized = False,
+    )
+
+    filtered_labels_to_links = get_filtered_labels_to_links_map(
+        link_group = link_group,
+        linkables = lib_linkables,
+        is_executable_link = False,
+        build_context = build_context,
+        force_static_follows_dependents = force_static_follows_dependents,
+    )
+    filtered_links = get_filtered_links(filtered_labels_to_links.map)
+    filtered_targets = get_filtered_targets(filtered_labels_to_links.map)
+
+    link_execution_preference = get_link_execution_preference(ctx, filtered_labels_to_links.map.keys())
+
+    # Unfortunately, link_groups does not use MergedLinkInfo to represent the args
+    # for the resolved nodes in the graph.
+    additional_links = apple_get_link_info_by_deduping_link_infos(ctx, filtered_links, frameworks_linkable, swiftmodule_linkable)
+    if additional_links:
+        filtered_links.append(additional_links)
+
+    return LinkArgs(infos = filtered_links), get_link_group_map_json(ctx, filtered_targets), link_execution_preference
+
+def _use_pic(output_style: LibOutputStyle) -> bool:
+    """
+    Whether this output style requires PIC objects.
+    """
+    return output_style != LibOutputStyle("archive")
+
+# Create the objects/archive to use for static linking this rule.
+# Returns a tuple of objects/archive to use as the default output for the link
+# style(s) it's used in and the `LinkInfo` to export to dependents.
+def _static_library(
+    ctx: AnalysisContext,
+    impl_params: CxxRuleConstructorParams,
+    objects: list[Artifact],
+    pic: bool,
+    optimized: bool,
+    debuggable: bool,
+    stripped: bool,
+    extra_linkables: list[[FrameworksLinkable, SwiftmoduleLinkable]],
+    objects_have_external_debug_info: bool = False,
+    external_debug_info: ArtifactTSet = ArtifactTSet(),
+    bitcode_objects: [list[Artifact], None] = None,
+    has_hip_device_debug: bool = False,
+    hip_arch_debug_files: dict[str, list[Artifact]] = {},
+) -> (CxxLibraryOutput, LinkInfo):
+    if optimized and debuggable:
+        fail("Pls pick optimized OR debuggable")
+    if len(objects) == 0:
+        fail("empty objects")
+
+    # No reason to create a static library with just a single object file. We
+    # still want to create a static lib to expose as the default output because
+    # it's the contract/expectation of external clients of the cmd line
+    # interface. Any tools consuming `buck build` outputs should get a
+    # consistent output type when building a library, not static lib or object
+    # file depending on number of source files.
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    linker_type = linker_info.type
+
+    base_name = _base_static_library_name(ctx, optimized, debuggable, stripped)
+    name = _archive_name(base_name, pic = pic, extension = linker_info.static_library_extension)
+
+    # If we have extra hidden deps of this target add them to the archive action
+    # so they are forced to build for static library output.
+    archive = make_archive(ctx, name, objects, impl_params.extra_hidden)
+
+    bitcode_bundle = _bitcode_bundle(ctx, bitcode_objects, optimized, debuggable, pic, stripped)
+    if False:
+        # TODO(nga): bitcode_bundle.artifact
+        def unknown():
+            pass
+
+        bitcode_bundle = unknown()
+    if bitcode_bundle != None and bitcode_bundle.artifact != None:
+        bitcode_artifact = bitcode_bundle.artifact
+    else:
+        bitcode_artifact = None
+
+    if use_archives(ctx):
+        linkable = ArchiveLinkable(
+            archive = archive,
+            bitcode_bundle = bitcode_artifact,
+            linker_type = linker_type,
+            link_whole = _attr_link_whole(ctx),
+        )
+    else:
+        linkable = ObjectsLinkable(
+            objects = objects,
+            bitcode_bundle = bitcode_artifact,
+            linker_type = linker_type,
+            link_whole = _attr_link_whole(ctx),
+        )
+
+    post_flags = []
+
+    if pic:
+        post_flags.extend(linker_info.static_pic_dep_runtime_ld_flags or [])
+    else:
+        post_flags.extend(linker_info.static_dep_runtime_ld_flags or [])
+
+    # On darwin, the linked output references the archive that contains the
+    # object files instead of the originating objects.
+    object_external_debug_info = []
+    if linker_type == LinkerType("darwin"):
+        if archive.archive_contents_type == ArchiveContentsType("virtual"):
+            # If using thin archives or passing archives --start-lib --end-lib style (virtual), we only need to provide the underlying objects
+            object_external_debug_info.extend(archive.external_objects)
+        elif archive.archive_contents_type == ArchiveContentsType("thin"):
+            # If passing the archive to the linker conventionally, we need to provide both the thin archive
+            # and the underlying object files if using thin archives
+            object_external_debug_info.append(archive.artifact)
+            object_external_debug_info.extend(archive.external_objects)
+        else:
+            # And only the archive if using regular archives
+            object_external_debug_info.append(archive.artifact)
+    elif archive.archive_contents_type == ArchiveContentsType("thin") and objects_have_external_debug_info:
+        object_external_debug_info.extend(objects)
+
+    all_external_debug_info = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        artifacts = object_external_debug_info,
+        children = [external_debug_info],
+        tags = impl_params.additional.external_debug_info_tags,
+    )
+
+    return (
+        CxxLibraryOutput(
+            output_style = LibOutputStyle("pic_archive") if pic else LibOutputStyle("archive"),
+            default = archive.artifact,
+            unstripped = archive.artifact,
+            object_files = objects,
+            bitcode_bundle = bitcode_bundle,
+            other = (archive.external_objects if archive.archive_contents_type == ArchiveContentsType("thin") else []),
+            sub_targets = {},
+        ),
+        LinkInfo(
+            name = name,
+            # We're propagating object code for linking up the dep tree,
+            # so we need to also propagate any necessary link flags required for
+            # the object code.
+            pre_flags = impl_params.extra_exported_link_flags,
+            post_flags = post_flags,
+            # Extra linkables are propagated here so they are available to link_groups
+            # when they are deducing linker args.
+            linkables = [linkable] + extra_linkables,
+            external_debug_info = all_external_debug_info,
+            has_hip_device_debug = has_hip_device_debug,
+            hip_arch_debug_files = hip_arch_debug_files,
+            metadata = cxx_attr_dep_metadata(ctx),
+        ),
+    )
+
+# A bitcode bundle is very much like a static library and is generated from object file
+# inputs, except the output is a combined bitcode file, which is not machine code.
+def _bitcode_bundle(
+    ctx: AnalysisContext, objects: [list[Artifact], None], optimized: bool, debuggable: bool, pic: bool, stripped: bool, name_extra = ""
+) -> [BitcodeBundle, None]:
+    if objects == None or len(objects) == 0:
+        return None
+
+    base_name = _base_static_library_name(ctx, optimized, debuggable, stripped = False)
+    name = name_extra + _bitcode_bundle_name(base_name, pic, stripped)
+    return make_bitcode_bundle(ctx, name, objects)
+
+def _shared_library(
+    ctx: AnalysisContext,
+    impl_params: CxxRuleConstructorParams,
+    objects: list[Artifact],
+    external_debug_info: ArtifactTSet,
+    dep_infos: LinkArgs,
+    gnu_use_link_groups: bool,
+    link_execution_preference: LinkExecutionPreference,
+    link_ordering: [LinkOrdering, None],
+    flavor: LinkableFlavor,
+    has_hip_device_debug: bool = False,
+) -> _CxxSharedLibraryResult:
+    """
+    Generate a shared library and the associated native link info used by
+    dependents to link against it.
+    """
+
+    def flavored_output(output: str, separator: str = "/") -> str:
+        if flavor != LinkableFlavor("default"):
+            return flavor.value + separator + output
+        return output
+
+    soname = _soname(ctx, impl_params)
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    linker_info = cxx_toolchain.linker_info
+
+    local_bitcode_bundle = _bitcode_bundle(
+        ctx,
+        objects,
+        optimized = flavor == LinkableFlavor("optimized"),
+        debuggable = flavor == LinkableFlavor("debug"),
+        pic = False,
+        stripped = flavor == LinkableFlavor("stripped"),
+        name_extra = "objects-",
+    )
+
+    # NOTE(agallagher): We add exported link flags here because it's what v1
+    # does, but the intent of exported link flags are to wrap the link output
+    # that we propagate up the tree, rather than being used locally when
+    # generating a link product.
+    linker_flags = cxx_attr_linker_flags_all(ctx, impl_params.cxx_flags)
+    link_info = LinkInfo(
+        dist_thin_lto_codegen_flags = getattr(ctx.attrs, "dist_thin_lto_codegen_flags", []),
+        pre_flags = (linker_flags.flags + linker_flags.exported_flags + getattr(ctx.attrs, "local_linker_flags", [])),
+        linkables = [
+            ObjectsLinkable(
+                objects = objects,
+                bitcode_bundle = local_bitcode_bundle.artifact if local_bitcode_bundle else None,
+                linker_type = linker_info.type,
+                link_whole = True,
+            )
+        ],
+        post_flags = (
+            impl_params.extra_exported_link_flags + impl_params.extra_link_flags + linker_flags.post_flags + (linker_info.shared_dep_runtime_ld_flags or [])
+            # TODO(cjhopman): Why doesn't this add exported_linker_flags.post_flags?
+        ),
+        external_debug_info = external_debug_info,
+        metadata = cxx_attr_dep_metadata(ctx),
+    )
+
+    # If we have extra hidden deps here, add them as hidden inputs
+    # to the link action so that they are forced to build before linking.
+    links = [LinkArgs(infos = [link_info]), dep_infos]
+    if impl_params.extra_hidden:
+        links.append(
+            LinkArgs(flags = cmd_args(hidden = impl_params.extra_hidden)),
+        )
+
+    # shared library interface generation can be disabled at the target level
+    effective_shlib_interfaces_mode = ShlibInterfacesMode("disabled")
+    if cxx_use_shlib_intfs(ctx):
+        effective_shlib_interfaces_mode = get_cxx_toolchain_info(ctx).linker_info.shlib_interfaces
+        if effective_shlib_interfaces_mode == ShlibInterfacesMode("defined_only") and gnu_use_link_groups:
+            # TODO(agallagher): There's a bug in shlib intfs interacting with link
+            # groups, where we don't include the symbols we're meant to export from
+            # deps that get statically linked in.
+            effective_shlib_interfaces_mode = ShlibInterfacesMode("disabled")
+
+    needs_extract = hip_debug_extract_available(cxx_toolchain) and (has_hip_device_debug or link_args_have_hip_device_debug(links))
+    link_output = flavored_output(soname) + PRE_EXTRACT_SUFFIX if needs_extract else flavored_output(soname)
+
+    link_result = cxx_link_shared_library(
+        ctx = ctx,
+        output = link_output,
+        opts = link_options(
+            enable_distributed_thinlto = getattr(ctx.attrs, "enable_distributed_thinlto", False),
+            links = links,
+            identifier = flavored_output(soname, separator = "_"),
+            # As for a cxx_binary's link (exe_allow_cache_upload).
+            allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs),
+            link_ordering = link_ordering,
+            strip = impl_params.strip_executable,
+            strip_args_factory = impl_params.strip_args_factory,
+            link_execution_preference = link_execution_preference,
+            error_handler = impl_params.error_handler,
+            extra_linker_outputs_factory = impl_params.extra_linker_outputs_factory,
+            extra_linker_outputs_flags_factory = impl_params.extra_linker_outputs_flags_factory,
+            extra_distributed_thin_lto_opt_outputs_merger = impl_params.extra_distributed_thin_lto_opt_outputs_merger,
+            produce_shared_library_interface = effective_shlib_interfaces_mode == ShlibInterfacesMode("stub_from_linker_invocation"),
+            has_hip_device_debug = has_hip_device_debug,
+        ),
+        name = soname if impl_params.use_soname else None,
+        shared_library_flags = impl_params.shared_library_flags,
+    )
+    exported_shlib = link_result.linked_object.output
+
+    if effective_shlib_interfaces_mode == ShlibInterfacesMode("stub_from_linker_invocation"):
+        exported_shlib = link_result.shared_library_interface
+    elif effective_shlib_interfaces_mode == ShlibInterfacesMode("stub_from_library"):
+        # Generate a library interface from the linked library output.
+        # This will prevent relinking rdeps when changes do not affect
+        # the library symbols.
+        exported_shlib = shared_library_interface(
+            ctx = ctx,
+            shared_lib = exported_shlib,
+        )
+    elif effective_shlib_interfaces_mode == ShlibInterfacesMode("defined_only"):
+        link_info = LinkInfo(
+            pre_flags = link_info.pre_flags,
+            linkables = link_info.linkables,
+            post_flags = (
+                (link_info.post_flags or [])
+                + get_ignore_undefined_symbols_flags(linker_info.type)
+                + (linker_info.independent_shlib_interface_linker_flags or [])
+            ),
+            external_debug_info = link_info.external_debug_info,
+            metadata = cxx_attr_dep_metadata(ctx),
+        )
+        intf_link_result = cxx_link_shared_library(
+            ctx = ctx,
+            output = flavored_output(
+                get_shared_library_name(
+                    linker_info,
+                    ctx.label.name + "-for-interface",
+                    apply_default_prefix = True,
+                )
+            ),
+            opts = link_options(
+                category_suffix = "interface",
+                link_ordering = link_ordering,
+                links = [LinkArgs(infos = [link_info])],
+                identifier = flavored_output(soname + "-interface", separator = "_"),
+                link_execution_preference = link_execution_preference,
+                strip = impl_params.strip_executable,
+                error_handler = impl_params.error_handler,
+            ),
+            name = soname,
+        )
+        exported_shlib = shared_library_interface(
+            ctx = ctx,
+            shared_lib = intf_link_result.linked_object.output,
+        )
+
+    # Link against import library on Windows.
+    if link_result.linked_object.import_library:
+        exported_shlib = link_result.linked_object.import_library
+
+    return _CxxSharedLibraryResult(
+        link_result = link_result,
+        soname = soname,
+        info = LinkInfo(
+            name = soname,
+            linkables = [
+                SharedLibLinkable(
+                    lib = exported_shlib,
+                )
+            ],
+            has_hip_device_debug = has_hip_device_debug,
+            metadata = cxx_attr_dep_metadata(ctx),
+        ),
+    )
+
+def _attr_reexport_all_header_dependencies(ctx: AnalysisContext) -> bool:
+    return value_or(ctx.attrs.reexport_all_header_dependencies, False)
+
+def _soname(ctx: AnalysisContext, impl_params) -> str:
+    """
+    Get the shared library name to set for the given C++ library.
+    """
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    explicit_soname = value_or(ctx.attrs.soname, impl_params.soname)
+    if explicit_soname != None:
+        return get_shared_library_name_for_param(linker_info, explicit_soname)
+    return get_default_shared_library_name(linker_info, ctx.label)
+
+def _base_static_library_name(ctx: AnalysisContext, optimized: bool, debuggable: bool, stripped: bool) -> str:
+    return "{}{}{}{}".format(ctx.label.name, ".optimized" if optimized else "", ".debuggable" if debuggable else "", ".stripped" if stripped else "")
+
+def _archive_name(name: str, pic: bool, extension: str) -> str:
+    return "lib{}{}.{}".format(name, ".pic" if pic else "", extension)
+
+def _bitcode_bundle_name(name: str, pic: bool, stripped: bool = False) -> str:
+    return "{}{}{}.bc".format(name, ".pic" if pic else "", ".stripped" if stripped else "")
+
+def _attr_link_whole(ctx: AnalysisContext) -> bool:
+    return value_or(ctx.attrs.link_whole, False)
+
+def use_archives(ctx: AnalysisContext) -> bool:
+    """
+    Whether this rule should use archives to package objects when producing
+    link input for dependents.
+    """
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    requires_archives = linker_info.requires_archives
+    requires_objects = linker_info.requires_objects
+
+    if requires_archives and requires_objects:
+        fail("In cxx linker_info, only one of `requires_archives` and `requires_objects` can be enabled")
+
+    # If the toolchain requires them, then always use them.
+    if requires_archives:
+        return True
+
+    if requires_objects:
+        return False
+
+    # Otherwise, fallback to the rule-specific setting.
+    return value_or(getattr(ctx.attrs, "use_archive", True), True)
diff --git a/buck2/prelude/cxx/cxx_library_utility.bzl b/buck2/prelude/cxx/cxx_library_utility.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_library_utility.bzl
@@ -0,0 +1,207 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifacts.bzl",
+    "ArtifactOutputs",  # @unused Used as a type
+    "single_artifact",
+)
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//linking:link_info.bzl",
+    "DepMetadata",
+    "LinkStyle",
+    "LinkerFlags",
+    "MergedLinkInfo",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load(
+    "@prelude//utils:utils.bzl",
+    "filter_and_map_idx",
+    "from_named_set",
+)
+load(":cxx_context.bzl", "get_cxx_platform_info", "get_cxx_toolchain_info")
+load(":cxx_flags.bzl", "cxx_flags_linker_flags")
+load(
+    ":cxx_toolchain_types.bzl",
+    "LinkerType",
+    "ShlibInterfacesMode",
+)
+
+OBJECTS_SUBTARGET = "objects"
+
+EMPTY_DEFAULT_INFO = DefaultInfo()
+
+# The dependencies, and the default deps (if selected)
+def cxx_attr_deps(ctx: AnalysisContext) -> list[Dependency]:
+    deps = ctx.attrs.deps
+
+    if getattr(ctx.attrs, "default_deps", "") == "deps":
+        toolchain_info = get_cxx_toolchain_info(ctx)
+        if toolchain_info.default_deps:
+            deps.extend(toolchain_info.default_deps)
+
+    deps_query_attr = getattr(ctx.attrs, "deps_query", None)
+    if deps_query_attr:
+        return deps + deps_query_attr
+
+    # Avoid making a copy of deps if deps_query is not set.
+    return deps
+
+# The exported dependencies, and the default deps (if selected)
+def cxx_attr_exported_deps(ctx: AnalysisContext) -> list[Dependency]:
+    exported_deps = []
+
+    exported_deps_attr = getattr(ctx.attrs, "exported_deps", None)
+    if exported_deps_attr:
+        exported_deps.extend(exported_deps_attr)
+
+    if getattr(ctx.attrs, "default_deps", "") == "exported_deps":
+        toolchain_info = get_cxx_toolchain_info(ctx)
+        if toolchain_info.default_deps:
+            exported_deps.extend(toolchain_info.default_deps)
+
+    return exported_deps
+
+def cxx_attr_linker_flags_all(ctx: AnalysisContext, cxx_flags: list[Dependency] = []) -> LinkerFlags:
+    flags = cxx_attr_linker_flags(ctx, cxx_flags)
+
+    local_linker_script_flags_attr = getattr(ctx.attrs, "local_linker_script_flags", None)
+    if local_linker_script_flags_attr:
+        flags.extend(local_linker_script_flags_attr)
+
+    post_flags = getattr(ctx.attrs, "post_linker_flags", [])
+
+    return LinkerFlags(
+        flags = flags,
+        post_flags = post_flags,
+        exported_flags = ctx.attrs.exported_linker_flags,
+        exported_post_flags = ctx.attrs.exported_post_linker_flags,
+    )
+
+def cxx_inherited_link_info(first_order_deps: list[Dependency]) -> list[MergedLinkInfo]:
+    """
+    Returns the list of MergedLinkInfo from the dependencies, filtering out those without a MergedLinkInfo
+    """
+
+    # We filter out nones because some non-cxx rule without such providers could be a dependency, for example
+    # cxx_binary "fbcode//one_world/cli/util/process_wrapper:process_wrapper" depends on
+    # python_library "fbcode//third-party-buck/$platform/build/glibc:__project__"
+    return filter_and_map_idx(MergedLinkInfo, first_order_deps)
+
+# Linker flags
+def cxx_attr_linker_flags(ctx: AnalysisContext, cxx_flags: list[Dependency] = []) -> list[typing.Any]:
+    linker_flags = cxx_flags_linker_flags(ctx.actions, cxx_flags) + ctx.attrs.linker_flags
+    return linker_flags
+
+def cxx_attr_link_style(ctx: AnalysisContext) -> LinkStyle:
+    if ctx.attrs.link_style != None:
+        return LinkStyle(ctx.attrs.link_style)
+    if ctx.attrs.defaults != None:
+        # v1 equivalent code is in CxxConstructorArg::getDefaultFlavors and ParserWithConfigurableAttributes::applyDefaultFlavors
+        # Only values in the map are used by v1 as flavors, copy this behavior and return the first value which is compatible with link style.
+        v1_flavors = ctx.attrs.defaults.values()
+        for s in [LinkStyle("static"), LinkStyle("static_pic"), LinkStyle("shared")]:
+            if s.value in v1_flavors:
+                return s
+    return get_cxx_toolchain_info(ctx).linker_info.link_style
+
+def cxx_attr_preferred_linkage(ctx: AnalysisContext) -> Linkage:
+    preferred_linkage = ctx.attrs.preferred_linkage
+
+    # force_static is deprecated, but it has precedence over preferred_linkage
+    if getattr(ctx.attrs, "force_static", False):
+        preferred_linkage = "static"
+
+    return Linkage(preferred_linkage)
+
+def cxx_attr_resources(ctx: AnalysisContext) -> dict[str, ArtifactOutputs]:
+    """
+    Return the resources provided by this rule, as a map of resource name to
+    a tuple of the resource artifact and any "other" outputs exposed by it.
+    """
+
+    resources = {}
+
+    resources_attr = getattr(ctx.attrs, "resources", None)
+    if resources_attr:
+        # Resource keys prefix with `header_namespace`. Unset (None) falls
+        # back to package; explicit "" means "no prefix" UNLESS `raw_headers`
+        # is also set, which signals the xplat macros (`_unified_cxx_library`
+        # / `_fbcode_cpp_common_wrapper`) clobbered `header_namespace=""` to
+        # suppress #include namespace mangling — fall back to package in that
+        # case so consumers (e.g. `kBuckPrefix + "manifest.json"`) keep
+        # working. Idempotent: keys already prefixed (by ACME, snapshots) are
+        # left alone.
+        namespace = ctx.attrs.header_namespace
+        if namespace == None:
+            namespace = ctx.label.package
+        elif namespace == "" and getattr(ctx.attrs, "raw_headers", None):
+            namespace = ctx.label.package
+        prefix = namespace + "/" if namespace else None
+
+        # Use getattr, as apple rules don't have a `resources` parameter.
+        for name, resource in from_named_set(resources_attr).items():
+            if not namespace:
+                key = name
+            elif name == namespace or name.startswith(prefix):
+                key = name
+            else:
+                key = paths.join(namespace, name)
+            resources[key] = single_artifact(resource)
+
+    return resources
+
+def cxx_is_gnu(ctx: AnalysisContext) -> bool:
+    return get_cxx_toolchain_info(ctx).linker_info.type == LinkerType("gnu")
+
+def cxx_use_shlib_intfs(ctx: AnalysisContext) -> bool:
+    """
+    Return whether we should use shared library interfaces for linking.
+    """
+
+    # Per-rule opt-out.
+    if not getattr(ctx.attrs, "supports_shlib_interfaces", True):
+        return False
+
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    return linker_info.shlib_interfaces != ShlibInterfacesMode("disabled")
+
+def cxx_use_shlib_intfs_mode(ctx: AnalysisContext, mode: ShlibInterfacesMode) -> bool:
+    """
+    Verify we are using a specific shared library interface mode.
+    """
+    return cxx_use_shlib_intfs(ctx) and get_cxx_toolchain_info(ctx).linker_info.shlib_interfaces == mode
+
+def cxx_platform_supported(ctx: AnalysisContext) -> bool:
+    """
+    Return whether this rule's `supported_platforms_regex` matches the current
+    platform name.
+    """
+
+    if ctx.attrs.supported_platforms_regex == None:
+        return True
+
+    return regex_match(
+        ctx.attrs.supported_platforms_regex,
+        get_cxx_platform_info(ctx).name,
+    )
+
+def cxx_attr_dep_metadata(ctx: AnalysisContext) -> list[DepMetadata]:
+    """
+    Return a `DepMetadata` structure with a meaningful version identifier.
+    """
+    if not getattr(ctx.attrs, "version", None):
+        return []
+    return [DepMetadata(version = ctx.attrs.version)]
+
+def cxx_attr_use_content_based_paths(ctx: AnalysisContext) -> bool:
+    """
+    Return whether this rule should use content-based paths.
+    """
+    return getattr(ctx.attrs, "use_content_based_paths", False)
diff --git a/buck2/prelude/cxx/cxx_link_utility.bzl b/buck2/prelude/cxx/cxx_link_utility.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_link_utility.bzl
@@ -0,0 +1,363 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifact_tset.bzl", "project_artifacts")
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_apple_linker_flags.bzl", "apple_extra_darwin_linker_flags")
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",
+    "LinkerType",
+)
+load("@prelude//cxx:debug.bzl", "SplitDebugMode")
+load("@prelude//cxx:linker.bzl", "get_rpath_origin")
+load("@prelude//cxx:target_sdk_version.bzl", "get_target_triple")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkArgs",
+    "LinkOrdering",  # @unused Used as a type
+    "link_info_to_args",
+    "unpack_link_args",
+    "unpack_link_args_excluding_object_files_and_lazy_archives",
+    "unpack_link_args_object_files_and_lazy_archives_only",
+)
+load("@prelude//linking:lto.bzl", "LtoMode")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",  # @unused Used as a type
+    "create_shlib_dwp_tree",
+    "create_shlib_symlink_tree",
+)
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+load(
+    "@prelude//utils:utils.bzl",
+    "map_val",
+)
+
+def generates_split_debug(toolchain: CxxToolchainInfo):
+    """
+    Whether linking generates split debug outputs.
+    """
+
+    if toolchain.split_debug_mode == SplitDebugMode("none"):
+        return False
+
+    if toolchain.linker_info.lto_mode == LtoMode("none"):
+        return False
+
+    return True
+
+def linker_supports_linker_maps(linker_type: LinkerType) -> bool:
+    """
+    Returns whether the given linker type supports generating linker maps.
+    """
+    return linker_type in [LinkerType("darwin"), LinkerType("gnu")]
+
+def linker_map_args(toolchain: CxxToolchainInfo, linker_map) -> LinkArgs:
+    linker_type = toolchain.linker_info.type
+    if linker_type == LinkerType("darwin"):
+        flags = [
+            "-Xlinker",
+            "-map",
+            "-Xlinker",
+            linker_map,
+        ]
+    elif linker_type == LinkerType("gnu"):
+        flags = [
+            "-Xlinker",
+            "-Map",
+            "-Xlinker",
+            linker_map,
+        ]
+    else:
+        fail("Linker type {} not supported for linker maps".format(linker_type))
+    return LinkArgs(flags = flags)
+
+def gc_sections_args(toolchain: CxxToolchainInfo, gc_sections_output) -> LinkArgs:
+    """Generate linker args for gc-sections output file."""
+    linker_type = toolchain.linker_info.type
+    if linker_type == LinkerType("gnu"):
+        # The linker wrapper (ld.py) handles --write-gc-sections-output flag
+        flags = [
+            "--write-gc-sections-output",
+            gc_sections_output,
+        ]
+    else:
+        fail("gc-sections output is only supported for GNU linker, got: {}".format(linker_type))
+    return LinkArgs(flags = flags)
+
+LinkArgsOutput = record(
+    link_args = ArgLike,
+    hidden = list[typing.Any],
+    pdb_artifact = Artifact | None,
+)
+
+def get_extra_darwin_linker_flags(ctx: AnalysisContext) -> cmd_args:
+    target_triple = get_target_triple(ctx)
+    return cmd_args(apple_extra_darwin_linker_flags(target_triple))
+
+def make_link_args(
+    ctx: AnalysisContext,
+    actions: AnalysisActions,
+    cxx_toolchain_info: CxxToolchainInfo,
+    links: list[LinkArgs],
+    output_short_path: [str, None] = None,
+    link_ordering: [LinkOrdering, None] = None,
+    has_content_based_path: bool = False,
+) -> LinkArgsOutput:
+    """
+    Merges LinkArgs. Returns the args, files that must be present for those
+    args to work when passed to a linker, and optionally an artifact where DWO
+    outputs will be written to.
+    """
+    args = cmd_args()
+    hidden = []
+
+    linker_info = cxx_toolchain_info.linker_info
+    linker_type = linker_info.type
+
+    link_ordering = link_ordering or map_val(LinkOrdering, linker_info.link_ordering)
+
+    if linker_type == LinkerType("darwin"):
+        args.add(get_extra_darwin_linker_flags(ctx))
+
+    pdb_artifact = None
+    if linker_info.is_pdb_generated and output_short_path != None:
+        pdb_filename = paths.replace_extension(output_short_path, ".pdb")
+        pdb_artifact = actions.declare_output(pdb_filename, has_content_based_path = has_content_based_path)
+        hidden.append(pdb_artifact.as_output())
+
+    if linker_type == LinkerType("darwin"):
+        # We order inputs partially for binary size, and partially for historical
+        # reasons. It is important that lazy object file (non link-whole archives)
+        # be listed last on the command line so they are not unnecessarily loaded.
+        # Some applications implicitly rely upon this ordering, so it is difficult
+        # to change.  Note link_ordering configuration is not respected. The
+        # link_metadata_flag is also ignored as that is a flag to the GNU linker wrapper,
+        # which does not apply to Darwin.
+        args.add(filter(None, [unpack_link_args_excluding_object_files_and_lazy_archives(link) for link in links]))
+        args.add(filter(None, [unpack_link_args_object_files_and_lazy_archives_only(link) for link in links]))
+    else:
+        args.add(filter(None, [unpack_link_args(link, link_ordering = link_ordering, link_metadata_flag = linker_info.link_metadata_flag) for link in links]))
+
+    return LinkArgsOutput(
+        link_args = args,
+        hidden = [args] + hidden,
+        pdb_artifact = pdb_artifact,
+    )
+
+def shared_libs_symlink_tree_name(output: Artifact | str) -> str:
+    if isinstance(output, Artifact):
+        output = output.short_path
+    return "__{}__shared_libs_symlink_tree".format(output)
+
+def _dwp_symlink_tree_name(output: Artifact) -> str:
+    return "__{}__dwp_symlink_tree".format(output.short_path)
+
+ExecutableSharedLibArguments = record(
+    extra_link_args = field(list[ArgLike], []),
+    # Files that must be present for the executable to run successfully. These
+    # are always materialized, whether the executable is the output of a build
+    # or executed as a host tool.
+    runtime_files = field(list[ArgLike], []),
+    # Files needed to debug the executable. These need to be materialized when
+    # this executable is the output of a build, but not when it is used by other
+    # rules.
+    external_debug_info = field(list[TransitiveSetArgsProjection], []),
+    # Optional shared libs symlink tree symlinked_dir action.
+    shared_libs_symlink_tree = field(list[Artifact] | Artifact | None, None),
+    dwp_symlink_tree = field(list[Artifact] | Artifact | None, None),
+)
+
+CxxSanitizerRuntimeArguments = record(
+    extra_link_args = field(list[ArgLike], []),
+    sanitizer_runtime_files = field(list[Artifact], []),
+)
+
+# @executable_path/Frameworks
+
+def cxx_sanitizer_runtime_arguments(ctx: AnalysisContext, cxx_toolchain: CxxToolchainInfo, output: Artifact) -> CxxSanitizerRuntimeArguments:
+    linker_info = cxx_toolchain.linker_info
+    target_sanitizer_runtime_enabled = ctx.attrs.sanitizer_runtime_enabled if hasattr(ctx.attrs, "sanitizer_runtime_enabled") else None
+    sanitizer_runtime_enabled = target_sanitizer_runtime_enabled if target_sanitizer_runtime_enabled != None else linker_info.sanitizer_runtime_enabled
+    if not sanitizer_runtime_enabled:
+        return CxxSanitizerRuntimeArguments()
+
+    if not linker_info.sanitizer_runtime_files:
+        fail("C++ sanitizer runtime enabled but there are no runtime files")
+
+    if linker_info.type == LinkerType("darwin"):
+        # ignore_artifacts as the runtime directory is not required at _link_ time
+        runtime_rpath = cmd_args(ignore_artifacts = True)
+        runtime_files = linker_info.sanitizer_runtime_files
+        for runtime_shared_lib in runtime_files:
+            # Rpath-relative dylibs have an install name of `@rpath/libName.dylib`,
+            # which means we need to add the parent dir of the dylib as an rpath.
+            runtime_shared_lib_dir = cmd_args(runtime_shared_lib, parent = 1)
+
+            # The parent dir of the runtime shared lib must appear as a path
+            # relative to the parent dir of the binary. `@executable_path`
+            # represents the parent dir of the binary, not the binary itself.
+            runtime_shared_lib_rpath = cmd_args(runtime_shared_lib_dir, format = "-Wl,-rpath,@executable_path/{}", relative_to = (output, 1))
+            runtime_rpath.add(runtime_shared_lib_rpath)
+
+        return CxxSanitizerRuntimeArguments(
+            extra_link_args = [runtime_rpath],
+            sanitizer_runtime_files = runtime_files,
+        )
+
+    return CxxSanitizerRuntimeArguments()
+
+def cxx_runtime_library_arguments(cxx_toolchain: CxxToolchainInfo) -> list[ArgLike]:
+    # Runtime-library files (e.g. compiler-rt builtins) the toolchain provides are
+    # linked here, toward the end of the link line, to match the Clang driver's
+    # placement of compiler-rt. The consumer is responsible for stopping the driver
+    # from also injecting these (e.g. `-nodefaultlibs`).
+    linker_info = cxx_toolchain.linker_info
+    link_infos = linker_info.runtime_library_files
+    if not link_infos:
+        return []
+    if linker_info.type != LinkerType("gnu"):
+        fail("runtime_library_files is only supported for the gnu linker, got {}".format(linker_info.type))
+    return [link_info_to_args(link_info) for link_info in link_infos]
+
+def executable_shared_lib_arguments(
+    ctx: AnalysisContext, cxx_toolchain: CxxToolchainInfo, output: Artifact, shared_libs: list[SharedLibrary]
+) -> ExecutableSharedLibArguments:
+    def create_external_debug_info() -> list[TransitiveSetArgsProjection]:
+        return project_artifacts(
+            actions = ctx.actions,
+            tsets = [shlib.lib.external_debug_info for shlib in shared_libs],
+        )
+
+    def create_shared_libs_symlink_tree_windows() -> list[Artifact]:
+        return [
+            ctx.actions.symlink_file(
+                shlib.lib.output.basename,
+                shlib.lib.output,
+                has_content_based_path = False,
+            )
+            for shlib in shared_libs
+        ]
+
+    def create_shared_libs_symlink_trees(shared_libs_symlink_tree_name_arg: str, dwp_symlink_tree_name_arg: str) -> (Artifact, Artifact) | None:
+        if not shared_libs:
+            return None
+
+        shared_libs_symlink_tree = create_shlib_symlink_tree(
+            actions = ctx.actions,
+            out = shared_libs_symlink_tree_name_arg,
+            shared_libs = shared_libs,
+        )
+        dwp_symlink_tree = create_shlib_dwp_tree(ctx.actions, dwp_symlink_tree_name_arg, shared_libs)
+        return (shared_libs_symlink_tree, dwp_symlink_tree)
+
+    return executable_shared_lib_arguments_template(
+        cxx_toolchain,
+        output,
+        create_external_debug_info,
+        create_shared_libs_symlink_trees,
+        create_shared_libs_symlink_tree_windows,
+    )
+
+def executable_shared_lib_arguments_template(
+    cxx_toolchain: CxxToolchainInfo,
+    output: Artifact,
+    create_external_debug_info: typing.Callable[[], list[TransitiveSetArgsProjection]],
+    create_shared_libs_symlink_trees: typing.Callable[[str, str], (Artifact, Artifact) | None],
+    create_shared_libs_symlink_tree_windows: typing.Callable[[], list[Artifact]],
+) -> ExecutableSharedLibArguments:
+    """A generic/templated version of `executable_shared_lib_arguments` that takes in `Callable`s for constructing
+    the shared libs symlink tree and external debug info.
+
+    The shared libs symlink tree is constructed differently depending on if the SharedLibraries are stored in a `record`
+    or in a `TransitiveSet`.
+    """
+
+    extra_link_args = []
+    runtime_files = []
+    shared_libs_symlink_tree = None
+
+    # External debug info is materialized only when the executable is the output
+    # of a build. Do not add to runtime_files.
+    external_debug_info = create_external_debug_info()
+
+    linker_type = cxx_toolchain.linker_info.type
+
+    dwp_symlink_tree = None
+    if linker_type == LinkerType("windows"):
+        shared_libs_symlink_tree = create_shared_libs_symlink_tree_windows()
+        runtime_files.extend(shared_libs_symlink_tree)
+        # Windows doesn't support rpath.
+
+    else:
+        symlink_trees = create_shared_libs_symlink_trees(
+            shared_libs_symlink_tree_name(output),
+            _dwp_symlink_tree_name(output),
+        )
+
+        if symlink_trees:
+            shared_libs_symlink_tree, dwp_symlink_tree = symlink_trees
+            runtime_files.append(shared_libs_symlink_tree)
+            rpath_reference = get_rpath_origin(linker_type)
+
+            # We ignore_artifacts here since we don't want the symlink tree to actually be there for the link.
+            rpath_arg = cmd_args(
+                shared_libs_symlink_tree,
+                format = "-Wl,-rpath,{}/{{}}".format(rpath_reference),
+                ignore_artifacts = True,
+                relative_to = (output, 1),
+            )
+            extra_link_args.append(rpath_arg)
+
+    return ExecutableSharedLibArguments(
+        extra_link_args = extra_link_args,
+        runtime_files = runtime_files,
+        external_debug_info = external_debug_info,
+        shared_libs_symlink_tree = shared_libs_symlink_tree,
+        dwp_symlink_tree = dwp_symlink_tree,
+    )
+
+LinkCmdParts = record(
+    linker = [RunInfo, cmd_args],
+    linker_flags = cmd_args,
+    post_linker_flags = cmd_args,
+    # linker + linker_flags, for convenience
+    link_cmd = cmd_args,
+)
+
+def cxx_link_cmd_parts(toolchain: CxxToolchainInfo, executable: bool) -> LinkCmdParts:
+    # `toolchain_linker_flags` can either be a list of strings, `cmd_args` or `None`,
+    # so we need to do a bit more work to satisfy the type checker
+    toolchain_linker_flags = toolchain.linker_info.linker_flags
+    toolchain_post_linker_flags = toolchain.linker_info.post_linker_flags
+    if toolchain_linker_flags == None:
+        toolchain_linker_flags = cmd_args()
+    elif not type(toolchain_linker_flags) == "cmd_args":
+        toolchain_linker_flags = cmd_args(toolchain_linker_flags)
+
+    if executable:
+        toolchain_linker_flags = cmd_args(
+            toolchain_linker_flags,
+            toolchain.linker_info.executable_linker_flags,
+        )
+
+    if toolchain_post_linker_flags == None:
+        toolchain_post_linker_flags = cmd_args()
+    elif not type(toolchain_post_linker_flags) == "cmd_args":
+        toolchain_post_linker_flags = cmd_args(toolchain_post_linker_flags)
+
+    link_cmd = cmd_args(toolchain.linker_info.linker)
+    link_cmd.add(toolchain_linker_flags)
+
+    return LinkCmdParts(
+        linker = toolchain.linker_info.linker,
+        linker_flags = toolchain_linker_flags,
+        post_linker_flags = toolchain_post_linker_flags,
+        link_cmd = link_cmd,
+    )
diff --git a/buck2/prelude/cxx/cxx_sources.bzl b/buck2/prelude/cxx/cxx_sources.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_sources.bzl
@@ -0,0 +1,46 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# An input to cxx compilation, consisting of a file to compile and optional
+# file specific flags to compile with.
+CxxSrcWithFlags = record(
+    file = field(Artifact),
+    flags = field(list[[ResolvedStringWithMacros, str]], []),
+    # If we have multiple source entries with same files but different flags,
+    # specify an index so we can differentiate them. Otherwise, use None.
+    index = field([int, None], None),
+    is_header = field(bool, False),
+)
+
+# The source files
+def get_srcs_with_flags(ctx: AnalysisContext, additional_srcs: list = []) -> list[CxxSrcWithFlags]:
+    all_srcs = ctx.attrs.srcs + additional_srcs
+
+    # src -> flags_hash -> flags
+    flags_sets_by_src = {}
+    for x in all_srcs:
+        if type(x) == type(()):
+            artifact = x[0]
+            flags = x[1]
+        else:
+            artifact = x
+            flags = []
+
+        flags_hash = hash(str(flags))
+        flag_sets = flags_sets_by_src.setdefault(artifact, {})
+        flag_sets[flags_hash] = flags
+
+    # Go through collected (source, flags) pair and set the index field if there are duplicate source files
+    cxx_src_with_flags_records = []
+    for artifact, flag_sets in flags_sets_by_src.items():
+        needs_indices = len(flag_sets) > 1
+        for i, flags in enumerate(flag_sets.values()):
+            index = i if needs_indices else None
+            cxx_src_with_flags_records.append(CxxSrcWithFlags(file = artifact, flags = flags, index = index))
+
+    return cxx_src_with_flags_records
diff --git a/buck2/prelude/cxx/cxx_toolchain.bzl b/buck2/prelude/cxx/cxx_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_toolchain.bzl
@@ -0,0 +1,482 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load("@prelude//cxx:compile.bzl", "compiler_info_with_toolchain_argsfiles")
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "AsCompilerInfo",
+    "AsmCompilerInfo",
+    "BinaryUtilitiesInfo",
+    "CCompilerInfo",
+    "CudaCompilerInfo",
+    "CvtresCompilerInfo",
+    "CxxCompilerInfo",
+    "CxxInternalTools",
+    "CxxObjectFormat",
+    "DepTrackingMode",
+    "HipCompilerInfo",
+    "IncrementalLinkingMode",
+    "LinkerInfo",
+    "LinkerType",
+    "ObjcCompilerInfo",
+    "ObjcxxCompilerInfo",
+    "PicBehavior",
+    "RcCompilerInfo",
+    "ShlibInterfacesMode",
+    "StripFlagsInfo",
+    "cxx_toolchain_infos",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_toolchain_allow_cache_upload_args")
+load("@prelude//cxx:debug.bzl", "SplitDebugMode")
+load("@prelude//cxx:headers.bzl", "HeaderMode", "HeadersAsRawHeadersMode", "RawHeadersAsHeadersMode")
+load("@prelude//cxx:linker.bzl", "LINKERS", "is_pdb_generated")
+load("@prelude//decls:cxx_rules.bzl", "cxx_rules")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkOrdering",
+    "LinkStyle",
+)
+load("@prelude//linking:linkable_graph.bzl", "LinkableGraph")
+load("@prelude//linking:lto.bzl", "LtoMode", "lto_compiler_flags")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+)
+load("@prelude//target_stats:target_stats_tools.bzl", "TargetStatsToolsInfo")
+load("@prelude//utils:utils.bzl", "flatten", "value_or")
+
+def cxx_toolchain_impl(ctx):
+    c_compiler = _get_maybe_wrapped_msvc(
+        ctx.attrs.c_compiler[RunInfo], ctx.attrs.c_compiler_type or ctx.attrs.compiler_type, ctx.attrs._msvc_hermetic_exec[RunInfo]
+    )
+
+    lto_mode = LtoMode(ctx.attrs.lto_mode)
+    if lto_mode != LtoMode("none"):
+        object_format = "bitcode"
+    else:
+        object_format = ctx.attrs.object_format if ctx.attrs.object_format else "native"
+
+    c_lto_flags = lto_compiler_flags(lto_mode)
+
+    c_info = CCompilerInfo(
+        compiler = c_compiler,
+        compiler_type = ctx.attrs.c_compiler_type or ctx.attrs.compiler_type,
+        compiler_flags = cmd_args(ctx.attrs.c_compiler_flags, c_lto_flags),
+        preprocessor = c_compiler,
+        preprocessor_flags = cmd_args(ctx.attrs.c_preprocessor_flags),
+        allow_cache_upload = ctx.attrs.c_compiler_allow_cache_upload,
+        supports_content_based_paths = ctx.attrs.supports_content_based_paths,
+    )
+    objc_info = ObjcCompilerInfo(
+        compiler = c_compiler,
+        compiler_type = ctx.attrs.c_compiler_type or ctx.attrs.compiler_type,
+        compiler_flags = cmd_args(ctx.attrs.c_compiler_flags, c_lto_flags, ctx.attrs.objc_compiler_flags),
+        preprocessor = c_compiler,
+        preprocessor_flags = cmd_args(ctx.attrs.c_preprocessor_flags),
+        allow_cache_upload = ctx.attrs.c_compiler_allow_cache_upload,
+        supports_content_based_paths = ctx.attrs.supports_content_based_paths,
+    )
+    cxx_compiler = _get_maybe_wrapped_msvc(
+        ctx.attrs.cxx_compiler[RunInfo], ctx.attrs.cxx_compiler_type or ctx.attrs.compiler_type, ctx.attrs._msvc_hermetic_exec[RunInfo]
+    )
+    cxx_info = CxxCompilerInfo(
+        compiler = cxx_compiler,
+        compiler_type = ctx.attrs.cxx_compiler_type or ctx.attrs.compiler_type,
+        compiler_flags = cmd_args(ctx.attrs.cxx_compiler_flags, c_lto_flags),
+        preprocessor = cxx_compiler,
+        preprocessor_flags = cmd_args(ctx.attrs.cxx_preprocessor_flags),
+        allow_cache_upload = ctx.attrs.cxx_compiler_allow_cache_upload,
+        supports_two_phase_compilation = ctx.attrs.supports_two_phase_compilation,
+        supports_content_based_paths = ctx.attrs.supports_content_based_paths,
+    )
+    objcxx_info = ObjcxxCompilerInfo(
+        compiler = cxx_compiler,
+        compiler_type = ctx.attrs.cxx_compiler_type or ctx.attrs.compiler_type,
+        compiler_flags = cmd_args(ctx.attrs.cxx_compiler_flags, c_lto_flags, ctx.attrs.objcxx_compiler_flags),
+        preprocessor = cxx_compiler,
+        preprocessor_flags = cmd_args(ctx.attrs.cxx_preprocessor_flags),
+        allow_cache_upload = ctx.attrs.cxx_compiler_allow_cache_upload,
+        supports_content_based_paths = ctx.attrs.supports_content_based_paths,
+    )
+    asm_info = (
+        AsmCompilerInfo(
+            compiler = ctx.attrs.asm_compiler[RunInfo],
+            compiler_type = ctx.attrs.asm_compiler_type or ctx.attrs.compiler_type,
+            compiler_flags = cmd_args(ctx.attrs.asm_compiler_flags),
+            preprocessor_flags = cmd_args(ctx.attrs.asm_preprocessor_flags),
+            supports_content_based_paths = ctx.attrs.supports_content_based_paths,
+        )
+        if ctx.attrs.asm_compiler
+        else None
+    )
+    as_info = (
+        AsCompilerInfo(
+            compiler = ctx.attrs.assembler[RunInfo],
+            compiler_type = ctx.attrs.assembler_type or ctx.attrs.compiler_type,
+            compiler_flags = cmd_args(ctx.attrs.assembler_flags),
+            preprocessor_flags = cmd_args(ctx.attrs.assembler_preprocessor_flags),
+            supports_content_based_paths = ctx.attrs.supports_content_based_paths,
+        )
+        if ctx.attrs.assembler
+        else None
+    )
+    cuda_info = (
+        CudaCompilerInfo(
+            compiler = ctx.attrs.cuda_compiler[RunInfo],
+            compiler_for_dryrun = ctx.attrs.cuda_compiler_for_dryrun[RunInfo] if ctx.attrs.cuda_compiler_for_dryrun else None,
+            compiler_type = ctx.attrs.cuda_compiler_type or ctx.attrs.compiler_type,
+            compiler_flags = cmd_args(ctx.attrs.cuda_compiler_flags),
+            preprocessor_flags = cmd_args(ctx.attrs.cuda_preprocessor_flags),
+            allow_cache_upload = ctx.attrs.cuda_compiler_allow_cache_upload,
+            supports_content_based_paths = ctx.attrs.supports_content_based_paths,
+        )
+        if ctx.attrs.cuda_compiler
+        else None
+    )
+    hip_info = (
+        HipCompilerInfo(
+            compiler = ctx.attrs.hip_compiler[RunInfo],
+            compiler_type = ctx.attrs.hip_compiler_type or ctx.attrs.compiler_type,
+            compiler_flags = cmd_args(ctx.attrs.hip_compiler_flags),
+            preprocessor_flags = cmd_args(ctx.attrs.hip_preprocessor_flags),
+        )
+        if ctx.attrs.hip_compiler
+        else None
+    )
+    cvtres_info = (
+        CvtresCompilerInfo(
+            compiler = ctx.attrs.cvtres_compiler[RunInfo],
+            compiler_type = ctx.attrs.cvtres_compiler_type or ctx.attrs.compiler_type,
+            compiler_flags = cmd_args(ctx.attrs.cvtres_compiler_flags),
+            preprocessor_flags = cmd_args(ctx.attrs.cvtres_preprocessor_flags),
+        )
+        if ctx.attrs.cvtres_compiler
+        else None
+    )
+    rc_info = (
+        RcCompilerInfo(
+            compiler = ctx.attrs.rc_compiler[RunInfo],
+            compiler_type = ctx.attrs.rc_compiler_type or ctx.attrs.compiler_type,
+            compiler_flags = cmd_args(ctx.attrs.rc_compiler_flags),
+            preprocessor_flags = cmd_args(ctx.attrs.rc_preprocessor_flags),
+        )
+        if ctx.attrs.rc_compiler
+        else None
+    )
+
+    c_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "c", CCompilerInfo, c_info)
+    objc_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "objc", ObjcCompilerInfo, objc_info)
+    cxx_info = compiler_info_with_toolchain_argsfiles(
+        ctx.actions,
+        "cxx",
+        CxxCompilerInfo,
+        cxx_info,
+        # Only the cxx info can be precompiled for C++20 modules.
+        precompile_filter = ctx.attrs.internal_tools[CxxInternalTools].filter_argsfile,
+    )
+    objcxx_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "objcxx", ObjcxxCompilerInfo, objcxx_info)
+    asm_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "asm", AsmCompilerInfo, asm_info)
+    as_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "as", AsCompilerInfo, as_info)
+    cuda_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "cuda", CudaCompilerInfo, cuda_info)
+    hip_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "hip", HipCompilerInfo, hip_info)
+    cvtres_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "cvtres", CvtresCompilerInfo, cvtres_info)
+    rc_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "rc", RcCompilerInfo, rc_info)
+
+    linker_type = LinkerType(ctx.attrs.linker_type)
+    linker_info = LinkerInfo(
+        archiver = ctx.attrs.archiver[RunInfo],
+        archiver_flags = cmd_args(ctx.attrs.archiver_flags),
+        archiver_reads_inputs = ctx.attrs.archiver_reads_inputs,
+        archiver_supports_argfiles = ctx.attrs.archiver_supports_argfiles,
+        archiver_type = ctx.attrs.archiver_type,
+        archive_contents = ctx.attrs.archive_contents,
+        archive_objects_locally = False,
+        archive_symbol_table = ctx.attrs.archive_symbol_table,
+        binary_extension = value_or(ctx.attrs.binary_extension, ""),
+        extra_outputs = ctx.attrs.extra_linker_outputs,
+        generate_linker_maps = ctx.attrs.generate_linker_maps,
+        generate_gc_sections = ctx.attrs.generate_gc_sections,
+        is_pdb_generated = is_pdb_generated(linker_type, ctx.attrs.linker_flags),
+        link_binaries_locally = not value_or(ctx.attrs.cache_links, True),
+        link_libraries_locally = False,
+        link_style = LinkStyle(ctx.attrs.link_style),
+        link_weight = ctx.attrs.link_weight,
+        link_ordering = ctx.attrs.link_ordering,
+        linker = ctx.attrs.linker[RunInfo],
+        linker_flags = cmd_args(ctx.attrs.linker_flags, c_lto_flags),
+        executable_linker_flags = ctx.attrs.executable_linker_flags,
+        binary_linker_flags = ctx.attrs.binary_linker_flags,
+        dist_thin_lto_codegen_flags = cmd_args(ctx.attrs.dist_thin_lto_codegen_flags) if ctx.attrs.dist_thin_lto_codegen_flags else cmd_args(),
+        post_linker_flags = cmd_args(ctx.attrs.post_linker_flags),
+        link_metadata_flag = ctx.attrs.link_metadata_flag,
+        lto_mode = lto_mode,
+        mk_shlib_intf = ctx.attrs.shared_library_interface_producer,
+        object_file_extension = ctx.attrs.object_file_extension or "o",
+        shlib_interfaces = ShlibInterfacesMode(ctx.attrs.shared_library_interface_mode),
+        independent_shlib_interface_linker_flags = ctx.attrs.shared_library_interface_flags,
+        requires_archives = value_or(ctx.attrs.requires_archives, True),
+        requires_objects = value_or(ctx.attrs.requires_objects, False),
+        sanitizer_runtime_enabled = ctx.attrs.sanitizer_runtime_enabled,
+        sanitizer_runtime_files = flatten([runtime_file[DefaultInfo].default_outputs for runtime_file in ctx.attrs.sanitizer_runtime_files]),
+        runtime_library_files = [
+            dep[LinkableGraph].nodes.value.linkable.link_infos[LibOutputStyle("pic_archive")].default for dep in ctx.attrs.runtime_library_files
+        ],
+        supports_distributed_thinlto = ctx.attrs.supports_distributed_thinlto,
+        shared_dep_runtime_ld_flags = ctx.attrs.shared_dep_runtime_ld_flags,
+        shared_library_name_default_prefix = _get_shared_library_name_default_prefix(ctx),
+        shared_library_name_format = _get_shared_library_name_format(ctx),
+        shared_library_versioned_name_format = _get_shared_library_versioned_name_format(ctx),
+        static_dep_runtime_ld_flags = ctx.attrs.static_dep_runtime_ld_flags,
+        static_library_extension = ctx.attrs.static_library_extension or "a",
+        static_pic_dep_runtime_ld_flags = ctx.attrs.static_pic_dep_runtime_ld_flags,
+        thin_lto_premerger_enabled = ctx.attrs.thin_lto_premerger_enabled,
+        thin_lto_double_codegen_enabled = ctx.attrs.thin_lto_double_codegen_enabled,
+        type = linker_type,
+        use_archiver_flags = ctx.attrs.use_archiver_flags,
+        incremental_linking = ctx.attrs.incremental_linking,
+        supports_content_based_paths_for_archiving = ctx.attrs.supports_content_based_paths_for_archiving,
+        supports_shared_libraries = ctx.attrs.supports_shared_libraries,
+    )
+
+    utilities_info = BinaryUtilitiesInfo(
+        bolt = ctx.attrs.bolt[RunInfo] if ctx.attrs.bolt else None,
+        custom_tools = {name: dep[RunInfo] for name, dep in ctx.attrs.custom_tools.items()},
+        elf_stamp = ctx.attrs.elf_stamp[RunInfo] if ctx.attrs.elf_stamp else None,
+        nm = ctx.attrs.nm[RunInfo],
+        objcopy = ctx.attrs.objcopy_for_shared_library_interface[RunInfo],
+        objdump = ctx.attrs.objdump[RunInfo] if ctx.attrs.objdump else None,
+        ranlib = ctx.attrs.ranlib[RunInfo] if ctx.attrs.ranlib else None,
+        strip = ctx.attrs.strip[RunInfo],
+        dwp = ctx.attrs.dwp[RunInfo] if ctx.attrs.dwp else None,
+    )
+
+    strip_flags_info = StripFlagsInfo(
+        strip_debug_flags = ctx.attrs.strip_debug_flags,
+        strip_non_global_flags = ctx.attrs.strip_non_global_flags,
+        strip_all_flags = ctx.attrs.strip_all_flags,
+    )
+
+    platform_name = ctx.attrs.platform_name or ctx.attrs.name
+    return [
+        DefaultInfo(),
+    ] + cxx_toolchain_infos(
+        as_compiler_info = as_info,
+        asm_compiler_info = asm_info,
+        binary_utilities_info = utilities_info,
+        bolt_enabled = value_or(ctx.attrs.bolt_enabled, False),
+        cell_to_path_prefix_map = ctx.attrs.cell_to_path_prefix_map,
+        c_compiler_info = c_info,
+        clang_remarks = ctx.attrs.clang_remarks,
+        clang_llvm_statistics = value_or(ctx.attrs.clang_llvm_statistics, False),
+        clang_trace = value_or(ctx.attrs.clang_trace, False),
+        cpp_dep_tracking_mode = DepTrackingMode(ctx.attrs.cpp_dep_tracking_mode),
+        cuda_compiler_info = cuda_info,
+        cuda_dep_tracking_mode = DepTrackingMode(ctx.attrs.cuda_dep_tracking_mode),
+        cvtres_compiler_info = cvtres_info,
+        cxx_compiler_info = cxx_info,
+        dumpbin_toolchain_path = ctx.attrs._dumpbin_toolchain_path[DefaultInfo].default_outputs[0] if ctx.attrs._dumpbin_toolchain_path else None,
+        gcno_files = value_or(ctx.attrs.gcno_files, False),
+        header_mode = _get_header_mode(ctx),
+        headers_as_raw_headers_mode = HeadersAsRawHeadersMode(ctx.attrs.headers_as_raw_headers_mode) if ctx.attrs.headers_as_raw_headers_mode != None else None,
+        hip_compiler_info = hip_info,
+        internal_tools = ctx.attrs.internal_tools[CxxInternalTools],
+        libclang = ctx.attrs.libclang,
+        linker_info = linker_info,
+        lipo = ctx.attrs.lipo[RunInfo] if ctx.attrs.lipo else None,
+        llvm_cgdata = ctx.attrs.llvm_cgdata[RunInfo] if ctx.attrs.llvm_cgdata else None,
+        llvm_link = ctx.attrs.llvm_link[RunInfo] if ctx.attrs.llvm_link else None,
+        objc_compiler_info = objc_info,
+        objcxx_compiler_info = objcxx_info,
+        object_format = CxxObjectFormat(object_format),
+        pass_plugin = ctx.attrs.pass_plugin[DefaultInfo].default_outputs[0] if ctx.attrs.pass_plugin else None,
+        compiler_flavor_flags = ctx.attrs.compiler_flavor_flags,
+        pic_behavior = PicBehavior(ctx.attrs.pic_behavior),
+        platform_deps_aliases = ctx.attrs.platform_deps_aliases,
+        platform_name = platform_name,
+        raw_headers_as_headers_mode = RawHeadersAsHeadersMode(ctx.attrs.raw_headers_as_headers_mode) if ctx.attrs.raw_headers_as_headers_mode != None else None,
+        rc_compiler_info = rc_info,
+        remap_cwd = ctx.attrs.remap_cwd,
+        materialize_external_debug_info = ctx.attrs.materialize_external_debug_info,
+        split_debug_mode = SplitDebugMode(ctx.attrs.split_debug_mode),
+        strip_flags_info = strip_flags_info,
+        minimum_os_version = ctx.attrs.minimum_os_version,
+        # TODO(T138705365): Turn on dep files by default
+        use_dep_files = value_or(ctx.attrs.use_dep_files, _get_default_use_dep_files(platform_name)),
+        default_deps = ctx.attrs.default_deps,
+        target_stats_tools = ctx.attrs.target_stats_tools[TargetStatsToolsInfo] if ctx.attrs.target_stats_tools else None,
+    )
+
+def cxx_toolchain_extra_attributes(is_toolchain_rule):
+    dep_type = attrs.exec_dep if is_toolchain_rule else attrs.dep
+    return {
+        "archive_symbol_table": attrs.bool(default = True),
+        "archiver": dep_type(providers = [RunInfo]),
+        "archiver_reads_inputs": attrs.bool(default = True),
+        "archiver_supports_argfiles": attrs.bool(default = False),
+        "asm_compiler": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "asm_preprocessor": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "assembler": dep_type(providers = [RunInfo]),
+        "assembler_preprocessor": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "bolt": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "bolt_enabled": attrs.bool(default = False),
+        "c_compiler": dep_type(providers = [RunInfo]),
+        "cell_to_path_prefix_map": attrs.dict(key = attrs.string(), value = attrs.string(), default = {}),
+        "clang_llvm_statistics": attrs.option(attrs.bool(), default = None),
+        "clang_remarks": attrs.option(attrs.string(), default = None),
+        "clang_trace": attrs.option(attrs.bool(), default = None),
+        "compiler_flavor_flags": attrs.dict(key = attrs.string(), value = attrs.list(attrs.string()), default = {}),
+        "cpp_dep_tracking_mode": attrs.enum(DepTrackingMode.values(), default = "makefile"),
+        "cuda_compiler": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "cuda_compiler_for_dryrun": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "cuda_dep_tracking_mode": attrs.enum(DepTrackingMode.values(), default = "makefile"),
+        "custom_tools": attrs.dict(key = attrs.string(), value = dep_type(providers = [RunInfo]), default = {}),
+        "cvtres_compiler": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "cxx_compiler": dep_type(providers = [RunInfo]),
+        "default_deps": attrs.list(dep_type(), default = []),
+        "dwp": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "elf_stamp": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "gcno_files": attrs.bool(default = False),
+        "generate_gc_sections": attrs.bool(default = False),
+        "generate_linker_maps": attrs.bool(default = False),
+        "hip_compiler": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "incremental_linking": attrs.enum(IncrementalLinkingMode.values(), default = "disabled"),
+        "internal_tools": dep_type(providers = [CxxInternalTools], default = "prelude//cxx/tools:internal_tools"),
+        "libclang": attrs.option(dep_type(providers = [SharedLibraryInfo]), default = None),
+        "link_ordering": attrs.enum(LinkOrdering.values(), default = "preorder"),
+        "link_weight": attrs.int(default = 1),
+        "linker": dep_type(providers = [RunInfo]),
+        "lipo": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "llvm_cgdata": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "llvm_link": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "lto_mode": attrs.enum(LtoMode.values(), default = "none"),
+        "materialize_external_debug_info": attrs.bool(default = True),
+        # Darwin only: the deployment target to use for this build
+        "minimum_os_version": attrs.option(attrs.string(), default = None),
+        "nm": dep_type(providers = [RunInfo]),
+        "objcopy_for_shared_library_interface": dep_type(providers = [RunInfo]),
+        "objdump": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "object_format": attrs.enum(CxxObjectFormat.values(), default = "native"),
+        "pass_plugin": attrs.option(dep_type(providers = [DefaultInfo]), default = None),
+        "pic_behavior": attrs.enum(PicBehavior.values(), default = "supported"),
+        # A placeholder tool that can be used to set up toolchain constraints.
+        # Useful when fat and thin toolchahins share the same underlying tools via `command_alias()`,
+        # which requires setting up separate platform-specific aliases with the correct constraints.
+        "placeholder_tool": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        # Used for regex matching any 'platform_*' attributes.
+        "platform_deps_aliases": attrs.option(attrs.list(attrs.string()), default = None),
+        # Used for regex matching any 'platform_*' attributes.
+        "platform_name": attrs.option(attrs.string(), default = None),
+        "private_headers_symlinks_enabled": attrs.bool(default = True),
+        "public_headers_symlinks_enabled": attrs.bool(default = True),
+        "ranlib": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "rc_compiler": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "remap_cwd": attrs.bool(default = False),
+        "requires_objects": attrs.bool(default = False),
+        "runtime_library_files": attrs.set(attrs.dep(), sorted = True, default = []),  # Use `attrs.dep()` as it's not a tool, always propagate target platform
+        "sanitizer_runtime_enabled": attrs.bool(default = False),
+        "sanitizer_runtime_files": attrs.set(attrs.dep(), sorted = True, default = []),  # Use `attrs.dep()` as it's not a tool, always propagate target platform
+        "shared_library_interface_mode": attrs.enum(ShlibInterfacesMode.values(), default = "disabled"),
+        "shared_library_interface_producer": attrs.option(dep_type(providers = [RunInfo]), default = None),
+        "split_debug_mode": attrs.enum(SplitDebugMode.values(), default = "none"),
+        "strip": dep_type(providers = [RunInfo]),
+        "supports_content_based_paths": attrs.bool(default = False),
+        "supports_content_based_paths_for_archiving": attrs.bool(default = False),
+        "supports_distributed_thinlto": attrs.bool(default = False),
+        "supports_shared_libraries": attrs.bool(default = True),
+        "supports_two_phase_compilation": attrs.bool(default = False),
+        "target_stats_tools": attrs.option(dep_type(providers = [TargetStatsToolsInfo]), default = None),
+        "thin_lto_double_codegen_enabled": attrs.bool(default = False),
+        "thin_lto_premerger_enabled": attrs.bool(default = False),
+        "use_archiver_flags": attrs.bool(default = True),
+        "use_dep_files": attrs.option(attrs.bool(), default = None),
+        # TODO(scottcao): Figure out a slightly better way to integrate this. In theory, this is only needed for clang toolchain.
+        # If we were using msvc, we should be able to use dumpbin directly.
+        "_dumpbin_toolchain_path": attrs.default_only(
+            attrs.option(
+                dep_type(providers = [DefaultInfo]),
+                default = select({
+                    "DEFAULT": None,
+                    "ovr_config//os:windows": select({
+                        # Unfortunately, it seems like an unresolved select when resolve exec platforms causes the whole resolution
+                        # to fail, so I need a DEFAULT here when some target without cpu constraint tries to configure against the
+                        # windows exec platform.
+                        "DEFAULT": None,
+                        # FIXME: prelude// should be standalone (not refer to fbsource//)
+                        "ovr_config//cpu:x86_32": "fbsource//third-party/toolchains/visual_studio:cl_x86_and_tools",
+                        "ovr_config//cpu:x86_64": "fbsource//third-party/toolchains/visual_studio:cl_x64_and_tools",
+                    }),
+                })
+                if is_full_meta_repo()
+                else None,
+            )
+        ),
+        "_msvc_hermetic_exec": attrs.default_only(dep_type(providers = [RunInfo], default = "prelude//windows/tools:msvc_hermetic_exec")),
+    } | cxx_toolchain_allow_cache_upload_args()
+
+def _cxx_toolchain_inheriting_target_platform_attrs():
+    attrs = dict(cxx_rules.cxx_toolchain.attrs)
+    attrs.update(cxx_toolchain_extra_attributes(is_toolchain_rule = True))
+    return attrs
+
+cxx_toolchain_inheriting_target_platform = rule(
+    impl = cxx_toolchain_impl,
+    attrs = _cxx_toolchain_inheriting_target_platform_attrs(),
+    is_toolchain_rule = True,
+)
+
+_APPLE_PLATFORM_NAME_PREFIXES = [
+    "iphonesimulator",
+    "iphoneos",
+    "maccatalyst",
+    "macosx",
+    "watchos",
+    "watchsimulator",
+    "appletvos",
+    "appletvsimulator",
+]
+
+def _get_default_use_dep_files(platform_name: str) -> bool:
+    # All Apple platforms use Clang which supports the standard dep files format
+    for apple_platform_name_prefix in _APPLE_PLATFORM_NAME_PREFIXES:
+        if apple_platform_name_prefix in platform_name:
+            return True
+    return False
+
+def _get_header_mode(ctx: AnalysisContext) -> HeaderMode:
+    if ctx.attrs.use_header_map:
+        if ctx.attrs.private_headers_symlinks_enabled or ctx.attrs.public_headers_symlinks_enabled:
+            return HeaderMode("symlink_tree_with_header_map")
+        else:
+            return HeaderMode("header_map_only")
+    else:
+        return HeaderMode("symlink_tree_only")
+
+def _get_shared_library_name_default_prefix(ctx: AnalysisContext) -> str:
+    extension = ctx.attrs.shared_library_extension
+    return "" if extension == "dll" else "lib"
+
+def _get_shared_library_name_format(ctx: AnalysisContext) -> str:
+    linker_type = LinkerType(ctx.attrs.linker_type)
+    extension = ctx.attrs.shared_library_extension
+    if extension == "":
+        extension = LINKERS[linker_type].default_shared_library_extension
+    return "{}." + extension
+
+def _get_shared_library_versioned_name_format(ctx: AnalysisContext) -> str:
+    linker_type = LinkerType(ctx.attrs.linker_type)
+    extension_format = ctx.attrs.shared_library_versioned_extension_format.replace("%s", "{}")
+    if extension_format == "":
+        extension_format = LINKERS[linker_type].default_shared_library_versioned_extension_format
+    return "{}." + extension_format
+
+def _get_maybe_wrapped_msvc(compiler: RunInfo, compiler_type: str, msvc_hermetic_exec: RunInfo) -> RunInfo:
+    if compiler_type == "windows":
+        return RunInfo(args = cmd_args(msvc_hermetic_exec, compiler))
+    return compiler
diff --git a/buck2/prelude/cxx/cxx_toolchain_macro_layer.bzl b/buck2/prelude/cxx/cxx_toolchain_macro_layer.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_toolchain_macro_layer.bzl
@@ -0,0 +1,33 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def cxx_toolchain_macro_impl(cxx_toolchain_rule = None, **kwargs):
+    # `generate_linker_maps` set in order of priority:
+    # - Explicit attribute on the cxx_toolchain() target
+    # - Constraint on the target platform
+    # - `cxx.linker_map_enabled` buckconfig
+    if "generate_linker_maps" not in kwargs:
+        linker_map_enabled = read_root_config("cxx", "linker_map_enabled", "").lower() == "true"
+        kwargs["generate_linker_maps"] = select({
+            "DEFAULT": linker_map_enabled,
+            "config//linker/constraints:generate_linker_maps_disabled": False,
+            "config//linker/constraints:generate_linker_maps_enabled": True,
+        })
+
+    bitcode = read_root_config("cxx", "bitcode")
+    if bitcode != None:
+        if bitcode.lower() == "false":
+            kwargs["object_format"] = "native"
+        elif bitcode.lower() == "true":
+            kwargs["object_format"] = "bitcode"
+        elif bitcode.lower() == "embed":
+            kwargs["object_format"] = "embedded-bitcode"
+        else:
+            kwargs["object_format"] = "native"
+
+    cxx_toolchain_rule(**kwargs)
diff --git a/buck2/prelude/cxx/cxx_toolchain_types.bzl b/buck2/prelude/cxx/cxx_toolchain_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_toolchain_types.bzl
@@ -0,0 +1,531 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_apple_linker_flags.bzl", "apple_extra_darwin_linker_flags", "apple_format_target_triple", "is_valid_apple_platform_name")
+load("@prelude//cxx:debug.bzl", "SplitDebugMode")
+load("@prelude//target_stats:target_stats_tools.bzl", "TargetStatsToolsInfo")
+
+CXX_COMPILER_TYPES = ["clang", "clang_cl", "clang_windows", "gcc", "windows", "windows_ml64"]
+
+LinkerType = enum("gnu", "darwin", "windows", "wasm")
+
+IncrementalLinkingMode = enum("disabled", "supported", "enabled")
+
+ShlibInterfacesMode = enum(
+    "disabled",
+    "defined_only",  # Generate a "stub" shared library by only linking object files passed to the link, ignoring static libraries or dynamic libraries linked against.
+    # This known to be incorrect in the presence of static libraries, as they won't be represented in the interface.
+    "stub_from_library",  # Generate an interface from the completed shared library via some external tool.
+    "stub_from_linker_invocation",  # For linkers that support it, generate an interface from the linker invocation that would ordinarily produce the shared library, adding some extra flags
+)
+
+# TODO(T110378149): Consider whether it makes sense to move these things to
+# configurations/constraints rather than part of the toolchain.
+LinkerInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "archiver": provider_field(typing.Any, default = None),
+        "archiver_flags": provider_field(typing.Any, default = None),
+        "archiver_reads_inputs": provider_field(bool, default = True),
+        "archiver_supports_argfiles": provider_field(typing.Any, default = None),
+        "archiver_type": provider_field(typing.Any, default = None),
+        "archive_contents": provider_field(typing.Any, default = "normal"),
+        "archive_objects_locally": provider_field(typing.Any, default = None),
+        "archive_symbol_table": provider_field(bool, default = True),
+        # "archiver_platform",
+        # "" on Unix, "exe" on Windows
+        "binary_extension": provider_field(typing.Any, default = None),  # str
+        "dist_thin_lto_codegen_flags": provider_field([cmd_args, None], default = None),
+        "extra_outputs": provider_field(list[str], default = []),
+        "generate_linker_maps": provider_field(typing.Any, default = None),  # bool
+        "generate_gc_sections": provider_field(typing.Any, default = None),  # bool
+        # Whether to run native links locally.  We support this for fbcode platforms
+        # to avoid issues with C++ static links (see comment in
+        # `platform/cxx_toolchains.bzl` for details).
+        "link_binaries_locally": provider_field(typing.Any, default = None),
+        # Whether to run native shared library links locally. For certain use cases
+        # (e.g., large Apple frameworks), it's more efficient to link locally due
+        # GiBs of object files (which can also lead to RE errors/timesouts etc).
+        "link_libraries_locally": provider_field(typing.Any, default = None),
+        "link_style": provider_field(typing.Any, default = None),  # LinkStyle
+        "link_weight": provider_field(int, default = 1),  # int
+        "link_ordering": provider_field(typing.Any, default = None),  # LinkOrdering
+        "linker": provider_field(typing.Any, default = None),
+        "linker_flags": provider_field(typing.Any, default = None),
+        "executable_linker_flags": provider_field(typing.Any, default = []),
+        "binary_linker_flags": provider_field(typing.Any, default = []),
+        "link_metadata_flag": provider_field(str | None, default = None),
+        "lto_mode": provider_field(typing.Any, default = None),
+        "mk_shlib_intf": provider_field(typing.Any, default = None),
+        # "o" on Unix, "obj" on Windows
+        "object_file_extension": provider_field(typing.Any, default = None),  # str
+        "post_linker_flags": provider_field(typing.Any, default = None),
+        # `LinkInfo`s (list[LinkInfo]) of the runtime libraries the toolchain provides.
+        "runtime_library_files": provider_field(list[typing.Any], default = []),
+        "sanitizer_runtime_enabled": provider_field(bool, default = False),
+        "sanitizer_runtime_files": provider_field(list[Artifact], default = []),
+        "shlib_interfaces": provider_field(ShlibInterfacesMode),
+        "shared_dep_runtime_ld_flags": provider_field(typing.Any, default = None),
+        # "lib" on Linux/Mac/Android, "" on Windows.
+        "shared_library_name_default_prefix": provider_field(typing.Any, default = None),  # str
+        # "{}.so" on Linux, "{}.dylib" on Mac, "{}.dll" on Windows
+        "shared_library_name_format": provider_field(typing.Any, default = None),  # str
+        "shared_library_versioned_name_format": provider_field(typing.Any, default = None),  # str
+        "static_dep_runtime_ld_flags": provider_field(typing.Any, default = None),
+        # "a" on Unix, "lib" on Windows
+        "static_library_extension": provider_field(typing.Any, default = None),  # str
+        "static_pic_dep_runtime_ld_flags": provider_field(typing.Any, default = None),
+        "requires_archives": provider_field(typing.Any, default = None),
+        "requires_objects": provider_field(typing.Any, default = None),
+        "supports_distributed_thinlto": provider_field(typing.Any, default = None),
+        "independent_shlib_interface_linker_flags": provider_field(typing.Any, default = None),
+        "thin_lto_premerger_enabled": provider_field(bool, default = False),
+        "thin_lto_double_codegen_enabled": provider_field(bool, default = False),
+        "type": LinkerType,
+        "use_archiver_flags": provider_field(typing.Any, default = None),
+        "force_full_hybrid_if_capable": provider_field(typing.Any, default = None),
+        "is_pdb_generated": provider_field(typing.Any, default = None),  # bool
+        # Flags to use to "sandbox" exported library linker flags.
+        "push_pop_state_flags": provider_field(typing.Any, default = None),
+        "supports_content_based_paths_for_archiving": provider_field(bool, default = False),
+        "incremental_linking": provider_field(str, default = "disabled"),
+        "supports_shared_libraries": provider_field(bool, default = True),
+    },
+)
+
+BinaryUtilitiesInfo = provider(
+    fields = {
+        "bolt": provider_field(typing.Any, default = None),
+        "custom_tools": provider_field(dict[str, RunInfo], default = {}),
+        "dwp": provider_field(typing.Any, default = None),
+        "elf_stamp": provider_field([RunInfo, None], default = None),
+        "nm": provider_field(typing.Any, default = None),
+        "objcopy": provider_field(typing.Any, default = None),
+        "objdump": provider_field(typing.Any, default = None),
+        "ranlib": provider_field(typing.Any, default = None),
+        "strip": provider_field(typing.Any, default = None),
+    }
+)
+
+StripFlagsInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "strip_debug_flags": provider_field(typing.Any, default = None),  # [["str"], None]
+        "strip_non_global_flags": provider_field(typing.Any, default = None),  # [["str"], None]
+        "strip_all_flags": provider_field(typing.Any, default = None),  # [["str"], None]
+    },
+)
+
+DepTrackingMode = enum(
+    # MAKEFILE corresponds to `gcc -MD -MF depfile ...` on *nix
+    "makefile",
+    # SHOW_INCLUDES corresponds to `cl.exe /showIncludes ...` on windows
+    "show_includes",
+    # SHOW_HEADERS corresponds to `clang/gcc -H ...` on *nix
+    "show_headers",
+    # Some compilers - like ml64 - do not produce information about included files
+    "none",
+)
+
+# TODO(T110378147): There's a bunch of info encoded in random places in buck
+# derived from information in these toolchains but hardcoded (for example,
+# which file extensions are preprocessable/compilable). We should figure out
+# how to move most of that into these toolchain infos.
+# TODO(T110378146): The inclusion of compiler and preprocessor in here is really
+# just a legacy thing that was never cleaned up. Historically, buck supported a
+# mode where compilation was done in two, explicitly separate phases
+# (preprocess and then compile). We don't support that today, and including
+# both of these mostly just ends up with added complexity and with us
+# duplicating flags in command lines.
+
+# In cxx_library, we support a bunch of different types of files (ex. cuda),
+# the toolchain for these follow this common pattern.
+_compiler_fields = [
+    "compiler",
+    "compiler_type",
+    "compiler_flags",
+    # An optional argsfile that contains the preprocessor flags and the compiler flags.
+    "argsfile",  # `cmd_args | None`
+    # An optional argsfile that contains the preprocessor flags and the compiler flags,
+    # formatted for xcode.
+    "argsfile_xcode",  # `cmd_args | None`
+    # An optional copy of `argsfile` filtered for C++20 module precompilation,
+    # as an `argsfile_with_artifacts()` value.
+    "argsfile_precompile",  # `cmd_args | None`
+    "preprocessor",
+    "preprocessor_type",
+    "preprocessor_flags",
+    # Controls cache upload for object files
+    "allow_cache_upload",
+    "supports_two_phase_compilation",
+    "compiler_with_wrapper",
+    "supports_content_based_paths",
+]
+
+AsCompilerInfo = provider(fields = _compiler_fields)
+AsmCompilerInfo = provider(fields = _compiler_fields)
+CCompilerInfo = provider(fields = _compiler_fields)
+CudaCompilerInfo = provider(fields = _compiler_fields + ["compiler_for_dryrun"])
+CvtresCompilerInfo = provider(fields = _compiler_fields)
+CxxCompilerInfo = provider(fields = _compiler_fields)
+HipCompilerInfo = provider(fields = _compiler_fields)
+ObjcCompilerInfo = provider(fields = _compiler_fields)
+ObjcxxCompilerInfo = provider(fields = _compiler_fields)
+RcCompilerInfo = provider(fields = _compiler_fields)
+
+def compiler_info_with_argsfiles(
+    compiler_info: typing.Any, ctor: typing.Callable, argsfile: cmd_args, argsfile_xcode: cmd_args, argsfile_precompile: cmd_args | None = None
+) -> typing.Any:
+    fields = {k: getattr(compiler_info, k) for k in _compiler_fields}
+    fields["argsfile"] = argsfile
+    fields["argsfile_xcode"] = argsfile_xcode
+    fields["argsfile_precompile"] = argsfile_precompile
+
+    # CudaCompilerInfo carries fields beyond the shared set.
+    compiler_for_dryrun = getattr(compiler_info, "compiler_for_dryrun", None)
+    if compiler_for_dryrun != None:
+        fields["compiler_for_dryrun"] = compiler_for_dryrun
+    return ctor(**fields)
+
+DistLtoToolsInfo = provider(
+    fields = dict(
+        planner = dict[LinkerType, RunInfo],
+        opt = dict[LinkerType, RunInfo],
+        prepare = dict[LinkerType, RunInfo],
+        copy = RunInfo,
+        archive_mapper = RunInfo,
+        compiler_stats_merger = RunInfo,
+    )
+)
+
+CxxInternalTools = provider(
+    fields = dict(
+        check_nonempty_output = RunInfo,
+        clang_tidy_wrapper = RunInfo,
+        concatenate_diagnostics = RunInfo,
+        dep_file_processor = RunInfo,
+        dist_lto = DistLtoToolsInfo,
+        filter_argsfile = RunInfo,
+        hmap_wrapper = RunInfo,
+        make_comp_db = RunInfo,
+        remap_cwd = RunInfo,
+        serialized_diagnostics_to_json_wrapper = RunInfo,
+        stderr_to_file = RunInfo,
+        stub_header_unit = RunInfo,
+    )
+)
+
+CxxObjectFormat = enum(
+    "native",
+    "bitcode",
+    "embedded-bitcode",
+    "swift",
+)
+
+# - For targets being built for x86_64, arm64, the fPIC flag isn't respected. Everything is fPIC.
+# - For targets being built for Windows, nothing is fPIC. The flag is ignored.
+# - There are many platforms (linux, etc.) where the fPIC flag is supported.
+#
+# As a result, we can end-up in a place where you pic + non-pic artifacts are requested
+# but the platform will produce the exact same output (despite the different files).
+#
+# The PicBehavior is applied to avoid using link or output styles that are unsupported by a toolchain.
+PicBehavior = enum(
+    # Regardless of whether -fPIC is specified explicitly
+    # every compiled artifact will have a position-independent representation.
+    # This should be the default when targeting x86_64 + arm64.
+    "always_enabled",
+    # The -fPIC flag is known and changes the compiled artifact.
+    "supported",
+    # The -fPIC flag is unknown to this platform.
+    "not_supported",
+)
+
+# Additional behavior for how to handle runtime dependencies
+RuntimeDependencyHandling = enum(
+    # Do no additional handling
+    "no_symlink",
+    # Always include runtime dependencies in a symlink tree, regardless
+    # of whether shared linkage is used or not. Only include first level deps.
+    "symlink_single_level_only",
+    # Always include runtime dependencies in a symlink tree, regardless
+    # of whether shared linkage is used or not. Include transitive deps.
+    "symlink",
+)
+
+# TODO(T110378094): We should consider if we can change this from a hardcoded
+# list of compiler_info to something more general. We could maybe do a list of
+# compiler_info where each one also declares what extensions it supports.
+# TODO(T110378145): Could we split up this Info so that each of the compilers
+# could be provided by different dependencies? That would allow a target to
+# only depend on the compilers it actually needs.
+CxxToolchainInfo = provider(
+    fields = {
+        "as_compiler_info": provider_field(typing.Any, default = None),
+        "asm_compiler_info": provider_field(typing.Any, default = None),
+        "binary_utilities_info": provider_field(typing.Any, default = None),
+        "bolt_enabled": provider_field(typing.Any, default = None),
+        "c_compiler_info": provider_field(typing.Any, default = None),
+        # Maps cell names to their repo-relative path prefix. Used by coverage
+        # prefix maps to translate cell-relative paths to repo-relative paths.
+        # e.g. {"fbcode": "fbcode"} means cell "fbcode" maps to the "fbcode/"
+        # subdirectory. Cells not in the map are assumed to be the repo root.
+        "cell_to_path_prefix_map": provider_field(dict[str, str], default = {}),
+        "clang_llvm_statistics": provider_field(typing.Any, default = None),
+        "clang_remarks": provider_field(typing.Any, default = None),
+        # Produce a time profiler JSON report by calling clang with `-ftime-trace`.
+        "clang_trace": provider_field(bool, default = False),
+        "compiler_flavor_flags": provider_field(typing.Any, default = {}),
+        "cpp_dep_tracking_mode": provider_field(typing.Any, default = None),
+        "cuda_compiler_info": provider_field(typing.Any, default = None),
+        "cuda_dep_tracking_mode": provider_field(typing.Any, default = None),
+        "cvtres_compiler_info": provider_field(typing.Any, default = None),
+        "cxx_compiler_info": provider_field(typing.Any, default = None),
+        "cxx_error_handler": provider_field(typing.Any, default = None),
+        "default_deps": provider_field(list[Dependency], default = []),
+        "dumpbin_toolchain_path": provider_field(typing.Any, default = None),
+        "gcno_files": provider_field(typing.Any, default = None),
+        "header_mode": provider_field(typing.Any, default = None),
+        "headers_as_raw_headers_mode": provider_field(typing.Any, default = None),
+        "hip_compiler_info": provider_field(typing.Any, default = None),
+        # See prelude/cxx/hip_debug_extract.bzl. `hip_debug_extract` is the
+        # wrapper RunInfo (None on unsupported ROCm).
+        "hip_debug_extract": provider_field([RunInfo, None], default = None),
+        "hip_device_debug_extract": provider_field(bool, default = False),
+        "hip_gpu_archs": provider_field(list[str], default = []),
+        "internal_tools": provider_field(CxxInternalTools),
+        "libclang": provider_field(typing.Any, default = None),
+        "linker_info": provider_field(typing.Any, default = None),
+        "lipo": provider_field([RunInfo, None], default = None),
+        "llvm_cgdata": provider_field([RunInfo, None], default = None),
+        "llvm_link": provider_field(typing.Any, default = None),
+        # Whether a top-level binary's unpacked external debug info (e.g.
+        # split-dwarf .dwo files) is materialized as part of building it, via
+        # DefaultInfo.other_outputs. When False, it can still be materialized
+        # explicitly via the `[debuginfo]` sub-target.
+        "materialize_external_debug_info": provider_field(bool, default = True),
+        "minimum_os_version": provider_field([str, None], default = None),
+        "objc_compiler_info": provider_field([ObjcCompilerInfo, None], default = None),
+        "objcxx_compiler_info": provider_field([ObjcxxCompilerInfo, None], default = None),
+        "object_format": provider_field(typing.Any, default = None),
+        "pass_plugin": provider_field([Artifact, None], default = None),
+        "pic_behavior": provider_field(typing.Any, default = None),
+        "raw_headers_as_headers_mode": provider_field(typing.Any, default = None),
+        "rc_compiler_info": provider_field(typing.Any, default = None),
+        "remap_cwd": provider_field(bool, default = False),
+        "runtime_dependency_handling": provider_field(RuntimeDependencyHandling),
+        "split_debug_mode": provider_field(typing.Any, default = None),
+        "strip_flags_info": provider_field(typing.Any, default = None),
+        "supported_compile_flavors": provider_field(typing.Any, default = []),
+        "target_stats_tools": provider_field([TargetStatsToolsInfo, None], default = None),
+        "use_dep_files": provider_field(typing.Any, default = None),
+        "use_distributed_thinlto": provider_field(typing.Any, default = None),
+    },
+)
+
+# Stores "platform"/flavor name used to resolve *platform_* arguments
+CxxPlatformInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "name": provider_field(typing.Any, default = None),
+        # List of aliases used to resolve platform_deps
+        "deps_aliases": provider_field(typing.Any, default = None),
+    },
+)
+
+def _validate_linker_info(info: LinkerInfo):
+    if info.requires_archives and info.requires_objects:
+        fail("only one of `requires_archives` and `requires_objects` can be enabled")
+
+def is_bitcode_format(format: CxxObjectFormat) -> bool:
+    return format in [CxxObjectFormat("bitcode"), CxxObjectFormat("embedded-bitcode")]
+
+def cxx_toolchain_infos(
+    platform_name,
+    c_compiler_info,
+    cxx_compiler_info,
+    linker_info,
+    binary_utilities_info,
+    header_mode,
+    internal_tools: CxxInternalTools,
+    headers_as_raw_headers_mode = None,
+    raw_headers_as_headers_mode = None,
+    asm_compiler_info = None,
+    as_compiler_info = None,
+    hip_compiler_info = None,
+    hip_debug_extract = None,
+    hip_device_debug_extract = False,
+    hip_gpu_archs = [],
+    cuda_compiler_info = None,
+    cvtres_compiler_info = None,
+    rc_compiler_info = None,
+    object_format = CxxObjectFormat("native"),
+    use_distributed_thinlto = False,
+    use_dep_files = False,
+    clang_remarks = None,
+    clang_llvm_statistics = False,
+    gcno_files = None,
+    clang_trace = False,
+    cpp_dep_tracking_mode = DepTrackingMode("none"),
+    cuda_dep_tracking_mode = DepTrackingMode("none"),
+    strip_flags_info = None,
+    split_debug_mode = SplitDebugMode("none"),
+    materialize_external_debug_info = True,
+    bolt_enabled = False,
+    cell_to_path_prefix_map = {},
+    llvm_cgdata = None,
+    llvm_link = None,
+    platform_deps_aliases = [],
+    pic_behavior = PicBehavior("supported"),
+    dumpbin_toolchain_path = None,
+    minimum_os_version = None,
+    libclang = None,
+    lipo = None,
+    remap_cwd = False,
+    compiler_flavor_flags = {},
+    supported_compile_flavors = ["pic"],
+    objc_compiler_info = None,
+    objcxx_compiler_info = None,
+    cxx_error_handler = None,
+    pass_plugin = None,
+    default_deps = [],
+    runtime_dependency_handling = RuntimeDependencyHandling("no_symlink"),
+    target_stats_tools = None,
+):
+    """
+    Creates the collection of cxx-toolchain Infos for a cxx toolchain.
+
+    c and c++ compiler infos are required, as is a linker info. The rest are
+    optional, and it will be an error if any cxx_library or other rules have srcs
+    of those other types.
+    """
+
+    # TODO(T110378099): verify types of the inner info objects.
+    _validate_linker_info(linker_info)
+
+    # Maintain backwards compatibility with ObjC compilation using the C compiler.
+    if objc_compiler_info == None:
+        objc_compiler_info = ObjcCompilerInfo(**{k: getattr(c_compiler_info, k, None) for k in _compiler_fields})
+    if objcxx_compiler_info == None:
+        objcxx_compiler_info = ObjcxxCompilerInfo(**{k: getattr(cxx_compiler_info, k, None) for k in _compiler_fields})
+
+    toolchain_info = CxxToolchainInfo(
+        as_compiler_info = as_compiler_info,
+        asm_compiler_info = asm_compiler_info,
+        binary_utilities_info = binary_utilities_info,
+        bolt_enabled = bolt_enabled,
+        cell_to_path_prefix_map = cell_to_path_prefix_map,
+        c_compiler_info = c_compiler_info,
+        clang_remarks = clang_remarks,
+        clang_llvm_statistics = clang_llvm_statistics,
+        clang_trace = clang_trace,
+        cpp_dep_tracking_mode = cpp_dep_tracking_mode,
+        cuda_compiler_info = cuda_compiler_info,
+        cuda_dep_tracking_mode = cuda_dep_tracking_mode,
+        cvtres_compiler_info = cvtres_compiler_info,
+        cxx_compiler_info = cxx_compiler_info,
+        dumpbin_toolchain_path = dumpbin_toolchain_path,
+        gcno_files = gcno_files,
+        header_mode = header_mode,
+        headers_as_raw_headers_mode = headers_as_raw_headers_mode,
+        hip_compiler_info = hip_compiler_info,
+        hip_debug_extract = hip_debug_extract,
+        hip_device_debug_extract = hip_device_debug_extract,
+        hip_gpu_archs = hip_gpu_archs,
+        internal_tools = internal_tools,
+        libclang = libclang,
+        linker_info = linker_info,
+        lipo = lipo,
+        llvm_cgdata = llvm_cgdata,
+        llvm_link = llvm_link,
+        materialize_external_debug_info = materialize_external_debug_info,
+        objc_compiler_info = objc_compiler_info,
+        objcxx_compiler_info = objcxx_compiler_info,
+        object_format = object_format,
+        pass_plugin = pass_plugin,
+        compiler_flavor_flags = compiler_flavor_flags,
+        pic_behavior = pic_behavior,
+        raw_headers_as_headers_mode = raw_headers_as_headers_mode,
+        rc_compiler_info = rc_compiler_info,
+        remap_cwd = remap_cwd,
+        runtime_dependency_handling = runtime_dependency_handling,
+        split_debug_mode = split_debug_mode,
+        strip_flags_info = strip_flags_info,
+        minimum_os_version = minimum_os_version,
+        use_dep_files = use_dep_files,
+        use_distributed_thinlto = use_distributed_thinlto,
+        cxx_error_handler = cxx_error_handler,
+        supported_compile_flavors = supported_compile_flavors,
+        default_deps = default_deps,
+        target_stats_tools = target_stats_tools,
+    )
+
+    ldflags_shared_extra = None
+    if linker_info.type == LinkerType("darwin") and is_valid_apple_platform_name(platform_name):
+        # These flags are used in `cxx_genrule()`, using the toolchain's target sdk version is
+        # the best we can do, as there's no target sdk on the rule itself.
+        #
+        # Without target triple, the linker will use the host OS as the target
+        # which is almost always incorrect.
+        apple_target_triple = apple_format_target_triple(platform_name, minimum_os_version or "")
+        ldflags_shared_extra = apple_extra_darwin_linker_flags(apple_target_triple)
+
+    # Provide placeholder mappings, used primarily by cxx_genrule.
+    # We don't support these buck1 placeholders since we can't take an argument.
+    # $(ldflags-pic-filter <pattern>)
+    # $(ldflags-shared-filter <pattern>)
+    # $(ldflags-static-filter <pattern>)
+    unkeyed_variables = {
+        "ar": linker_info.archiver,
+        "cc": c_compiler_info.compiler,
+        "cflags": _shell_quote(c_compiler_info.compiler_flags),
+        "cppflags": _shell_quote(c_compiler_info.preprocessor_flags),
+        "cxx": cxx_compiler_info.compiler,
+        "cxxflags": _shell_quote(cxx_compiler_info.compiler_flags),
+        "cxxppflags": _shell_quote(cxx_compiler_info.preprocessor_flags),
+        "ld": linker_info.linker,
+        # NOTE(agallagher): The arg-less variants of the ldflags macro are
+        # identical, and are just separate to match v1's behavior (ideally,
+        # we just have a single `ldflags` macro for this case).
+        "ldflags-shared": _shell_quote(linker_info.linker_flags or [], ldflags_shared_extra),
+        "ldflags-static": _shell_quote(linker_info.linker_flags or []),
+        "ldflags-static-pic": _shell_quote(linker_info.linker_flags or []),
+        "objcopy": binary_utilities_info.objcopy,
+    }
+
+    if as_compiler_info != None:
+        unkeyed_variables["as"] = as_compiler_info.compiler
+        unkeyed_variables["asflags"] = _shell_quote(as_compiler_info.compiler_flags)
+        unkeyed_variables["asppflags"] = _shell_quote(as_compiler_info.preprocessor_flags)
+
+    if cuda_compiler_info != None:
+        unkeyed_variables["cuda"] = cuda_compiler_info.compiler
+        unkeyed_variables["cudaflags"] = _shell_quote(cuda_compiler_info.compiler_flags)
+    placeholders_info = TemplatePlaceholderInfo(unkeyed_variables = unkeyed_variables)
+    return [toolchain_info, placeholders_info, CxxPlatformInfo(name = platform_name, deps_aliases = platform_deps_aliases)]
+
+def _shell_quote(xs, extra = None):
+    return cmd_args(xs, extra or [], quote = "shell")
+
+# export these things under a single "cxx" struct
+cxx = struct(
+    LinkerType = LinkerType,
+    LinkerInfo = LinkerInfo,
+    BinaryUtilitiesInfo = BinaryUtilitiesInfo,
+    HipCompilerInfo = HipCompilerInfo,
+    CudaCompilerInfo = CudaCompilerInfo,
+    CCompilerInfo = CCompilerInfo,
+    CxxCompilerInfo = CxxCompilerInfo,
+    AsmCompilerInfo = AsmCompilerInfo,
+    AsCompilerInfo = AsCompilerInfo,
+    CxxToolchainInfo = CxxToolchainInfo,
+    CxxPlatformInfo = CxxPlatformInfo,
+    StripFlagsInfo = StripFlagsInfo,
+    DistLtoToolsInfo = DistLtoToolsInfo,
+    cxx_toolchain_infos = cxx_toolchain_infos,
+)
diff --git a/buck2/prelude/cxx/cxx_transitive_diagnostics.bzl b/buck2/prelude/cxx/cxx_transitive_diagnostics.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_transitive_diagnostics.bzl
@@ -0,0 +1,37 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",  # @unused Used as a type
+    "make_artifact_tset",
+)
+
+CxxTransitiveDiagnosticsInfo = provider(
+    fields = {
+        "transitive_diagnostics": provider_field(ArtifactTSet),
+    },
+)
+
+def cxx_transitive_diagnostics_combine(ctx: AnalysisContext, diagnostics: list[Artifact], deps: list[Dependency]) -> CxxTransitiveDiagnosticsInfo:
+    children = []
+    for dep in deps:
+        dep_diagnostics_info = dep.get(CxxTransitiveDiagnosticsInfo)
+        if dep_diagnostics_info:
+            children.append(dep_diagnostics_info.transitive_diagnostics)
+
+    transitive_diagnostics = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        artifacts = diagnostics,
+        children = children,
+    )
+
+    return CxxTransitiveDiagnosticsInfo(
+        transitive_diagnostics = transitive_diagnostics,
+    )
diff --git a/buck2/prelude/cxx/cxx_types.bzl b/buck2/prelude/cxx/cxx_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_types.bzl
@@ -0,0 +1,315 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifact_tset.bzl", "ArtifactInfoTag", "ArtifactTSet")
+load(
+    "@prelude//cxx:cuda.bzl",
+    "CudaCompileStyle",
+)
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "RuntimeDependencyHandling",  # @unused Used as a type
+)
+load(
+    "@prelude//cxx:link_groups_types.bzl",
+    "LinkGroupInfo",  # @unused Used as a type
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkArgs",
+    "SwiftmoduleLinkable",
+)
+load(
+    "@prelude//linking:linkables.bzl",
+    "LinkableProviders",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",  # @unused Used as a type
+)
+load(":argsfiles.bzl", "CompileArgsfiles")
+load(
+    ":compile_types.bzl",
+    "IndexStoreFactory",
+    "UseHeaderUnitsMode",
+)
+load(
+    ":cxx_sources.bzl",
+    "CxxSrcWithFlags",  # @unused Used as a type
+)
+load(
+    ":headers.bzl",
+    "CxxHeadersLayout",
+)
+load(
+    ":link_groups.bzl",
+    "LinkGroupLibSpec",  # @unused Used as a type
+)
+load(
+    ":linker.bzl",
+    "SharedLibraryFlagOverrides",
+)
+load(
+    ":preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorInfo",
+)
+load(
+    ":xcode.bzl",
+    "cxx_populate_xcode_attributes",
+)
+
+LinkPreference = enum("default", "full", "incremental")
+
+CxxLibraryInfo = provider(
+    fields = dict(
+        target = provider_field(Label),
+        labels = provider_field(list[str]),
+    ),
+)
+
+# Parameters to control which sub targets to define when processing Cxx rules.
+# By default, generates all subtargets.
+CxxRuleSubTargetParams = record(
+    argsfiles = field(bool, True),
+    compilation_database = field(bool, True),
+    clang_remarks = field(bool, True),
+    clang_llvm_statistics = field(bool, True),
+    clang_traces = field(bool, True),
+    headers = field(bool, True),
+    link_group_map = field(bool, True),
+    link_style_outputs = field(bool, True),
+    xcode_data = field(bool, False),
+    objects = field(bool, True),
+    bitcode_bundle = field(bool, True),
+    header_unit = field(bool, True),
+)
+
+def xcode_data_enabled() -> bool:
+    # Project generators must manually enable xcode data because it measurably increases memory usage.
+    return read_root_config("cxx", "enable_xcode_data", "false").lower() == "true"
+
+# Parameters to control which providers to define when processing Cxx rules.
+# By default, generates all providers.
+CxxRuleProviderParams = record(
+    compilation_database = field(bool, True),
+    default = field(bool, True),
+    java_packaging_info = field(bool, True),
+    android_packageable_info = field(bool, True),
+    java_global_code_info = field(bool, True),
+    linkable_graph = field(bool, True),
+    link_style_outputs = field(bool, True),
+    merged_native_link_info = field(bool, True),
+    omnibus_root = field(bool, True),
+    preprocessors = field(bool, True),
+    # Whether or not to generate a resource groups provider for raw cxx resources.
+    cxx_resources_as_apple_resources = field(bool, True),
+    resources = field(bool, True),
+    shared_libraries = field(bool, True),
+    template_placeholders = field(bool, True),
+    preprocessor_for_tests = field(bool, True),
+    third_party_build = field(bool, False),
+    transitive_diagnostics = field(bool, False),
+)
+
+# Parameters to handle non-Clang sources, e.g Swift on Apple's platforms.
+CxxRuleAdditionalParams = record(
+    srcs = field(list[CxxSrcWithFlags], []),
+    # Additional argsfiles to include for this rule.
+    argsfiles = field(CompileArgsfiles, CompileArgsfiles()),
+    # External debug info to be used when generated static output
+    static_external_debug_info = field(list[ArtifactTSet], []),
+    # External debug info to be used when generating shared objects
+    shared_external_debug_info = field(list[ArtifactTSet], []),
+    subtargets = field(dict, {}),  # [str: ["provider"]]
+    # Might be used to expose additional providers to cxx layer (e.g to support #headers subtarget for Swift)
+    additional_providers_factory = field([typing.Callable, None], None),  # ([CPreprocessorInfo, None]) -> ["provider"]:
+    # The list of tags that should be applied to generated ArtifactTSet of debug information.
+    external_debug_info_tags = field(list[ArtifactInfoTag], []),
+)
+
+# Parameters that allows to configure/extend generic implementation of C++ rules.
+# Apple-specific rules (such as `apple_binary` and `apple_library`) and regular C++
+# rules (such as `cxx_binary` and `cxx_library`) have too much in common, though
+# some aspects of behavior (like layout of headers affecting inclusion of those
+# or additional linking flags to support usage of platform frameworks) of are
+# different and need to be specified. The following record holds the data which
+# is needed to specialize user-facing rule from generic implementation.
+CxxRuleConstructorParams = record(
+    # Required
+    # Name of the top level rule utilizing the cxx rule.
+    rule_type = str,
+    # Header layout to use importing headers.
+    headers_layout = CxxHeadersLayout,
+    # Optional
+    # Whether to build an empty shared library. This is utilized for rust_python_extensions
+    # so that they can link against the rust shared object.
+    build_empty_so = field(bool, False),
+    # If the rule is a test.
+    is_test = field(bool, False),
+    # Additional information used to preprocess every unit of translation in the rule.
+    extra_preprocessors = field(list[CPreprocessor], []),
+    extra_preprocessors_info = field(list[CPreprocessorInfo], []),
+    # Additional preprocessor info to export to other rules.
+    extra_exported_preprocessors = field(list[CPreprocessor], []),
+    # Additional information used to link every object produced by the rule,
+    # flags are _both_ exported and used to link the target itself.
+    extra_exported_link_flags = field(list[typing.Any], []),
+    # Additional hidden inputs for link or archive actions.
+    extra_hidden = field(list[Artifact], []),
+    extra_dwp_flags = field(list[typing.Any], []),
+    # Additional flags used _only_ when linking the target itself.
+    # These flags are _not_ propagated up the dep tree.
+    extra_link_flags = field(list[typing.Any], []),
+    extra_binary_link_flags = field(list[typing.Any], []),
+    # Inputs that invalidate generated build info without becoming inputs to the executable link.
+    generated_build_info_invalidation_inputs = field(list[typing.Any], []),
+    # Additional artifacts to be linked together with the cxx compilation output.
+    extra_link_input = field(list[Artifact], []),
+    # If True the extra_link_input should be considered as external debug info.
+    extra_link_input_has_external_debug_info = field(bool, False),
+    # Additional args to be used to link the target.
+    extra_link_args = field(list[LinkArgs], []),
+    # The swift module linkable that should be included for linking,
+    # used for link_groups and regular linking.
+    swiftmodule_linkable = field([SwiftmoduleLinkable, None], None),
+    # The source files to compile as part of this rule. This list can be generated
+    # from ctx.attrs with the `get_srcs_with_flags` function.
+    srcs = field(list[CxxSrcWithFlags]),
+    additional = field(CxxRuleAdditionalParams, CxxRuleAdditionalParams()),
+    # A function which enables the caller to inject subtargets into the link_style provider
+    # as well as create custom providers based on the link styles.
+    output_style_sub_targets_and_providers_factory = field(typing.Callable, lambda _link_style, _context, _output: ({}, [])),
+    # Linker flags that tell the linker to create shared libraries, overriding the default shared library flags.
+    # e.g. when building Apple tests, we want to link with `-bundle` instead of `-shared` to allow
+    # linking against the bundle loader.
+    shared_library_flags = field([SharedLibraryFlagOverrides, None], None),
+    # Optional argument to override the default name of the shared object being produced.
+    soname = field([str, None], None),
+    # Optional argument to override the default name of the executable being produced.
+    executable_name = field([str, None], None),
+    # Optional argument to set the deffile for the windows linker on a dll
+    deffile = field([Artifact, None], None),
+    # If passed to cxx_executable, this field will be used to determine
+    # a shared subtarget's default output should be stripped.
+    strip_executable = field(bool, False),
+    strip_args_factory = field(typing.Callable, lambda _: cmd_args()),
+    # Whether to embed the library name as the SONAME.
+    use_soname = field(bool, True),
+    # Use link group's linking logic regardless whether a link group map's present.
+    force_link_group_linking = field(bool, False),
+    # Function to use for setting Xcode attributes for the Xcode data sub target.
+    cxx_populate_xcode_attributes_func = field(typing.Callable, cxx_populate_xcode_attributes),
+    # Define which sub targets to generate.
+    generate_sub_targets = field(CxxRuleSubTargetParams, CxxRuleSubTargetParams()),
+    # Define which providers to generate.
+    generate_providers = field(CxxRuleProviderParams, CxxRuleProviderParams()),
+    force_full_hybrid_if_capable = field(bool, False),
+    # Whether shared libs for executables should generate a shared lib link tree.
+    exe_shared_libs_link_tree = field(bool, True),
+    extra_link_deps = field(list[LinkableProviders], []),
+    # Additional link roots (e.g. dlopen-able libs in a native python link),
+    # other than the main executable, which can influence the C++ executable
+    # result (e.g. added to link group linking or needs to be searched for
+    # shared libs to include in the symlink tree).
+    extra_link_roots = field(list[LinkableProviders], []),
+    # Additional shared libs to "package".
+    extra_shared_libs = field(list[SharedLibrary], []),
+    auto_link_group_specs = field([list[LinkGroupLibSpec], None], None),
+    link_group_info = field([LinkGroupInfo, None], None),
+    # Whether to use pre-stripped objects when linking.
+    prefer_stripped_objects = field(bool, False),
+    # The category suffix to use for executables actions (e.g. linking).
+    exe_category_suffix = field(str, "executable"),
+    # Whether link groups liking should make `preferred_linkage = "static"` libs
+    # "follow" their dependents across link group boundaries.
+    link_groups_force_static_follows_dependents = field(bool, True),
+    # A factory function to produce extra artifacts and output providers for a rule
+    # with signature: f(ctx, ExtraLinkerOutputsCategory) -> ExtraLinkerOutputs
+    extra_linker_outputs_factory = field(typing.Callable | None, None),
+    # A factory function to produce linker flags for the extra linker outputs
+    # returned from the extra_linker_outputs_factory. It should have the signature
+    # f(ctx, ExtraLinkerOutputCategory, dict[str, Artifact]) -> list[ArgLike]
+    extra_linker_outputs_flags_factory = field(typing.Callable | None, None),
+    # A function to consume extra outputs produced by distributed thin-lto opt actions
+    # and merge them together, as if they were produced by a local thin-lto link.
+    # The signature should be:
+    # f(ctx, dict[str, Artifact], list[dict[str, Artifact]])
+    # The second parameter should be the artifacts field of a call to
+    # extra_linker_outputs_factory(ctx, ExtraLinkerOutputsCategory("produced-during-distributed-thin-lto-opt")),
+    # and the last parameter a list of matching dictionaries representing all the opt outputs
+    # to be merged to bind the final outputs.
+    extra_distributed_thin_lto_opt_outputs_merger = field(typing.Callable | None, None),
+    # Whether to allow cache uploads for locally-executed actions (except for linking, see "exe_allow_cache_upload").
+    allow_cache_upload = field(bool, False),
+    # Whether to allow cache uploads for locally-linked executables.
+    exe_allow_cache_upload = field(bool, False),
+    # Extra shared library interfaces to propagate, eg from mixed Swift libraries.
+    extra_shared_library_interfaces = field([list[Artifact], None], None),
+    # Compiler flags
+    compiler_flags = field(list[typing.Any], []),
+    cxx_flags = field(list[Dependency], []),
+    lang_compiler_flags = field(dict[typing.Any, typing.Any], {}),
+    # Preprocessor flags
+    preprocessor_flags = field(list[typing.Any], []),
+    lang_preprocessor_flags = field(dict[typing.Any, typing.Any], {}),
+    # modulename-Swift.h header for building objc targets that rely on this swift dep
+    swift_objc_header = field([Artifact, None], None),
+    error_handler = field([typing.Callable, None], None),
+    index_store_factory = field(IndexStoreFactory | None, None),
+    # Swift index stores to propagate
+    index_stores = field(list[Artifact] | None, None),
+    # Modularization dependency graph artifact (from Swift compilation)
+    modularization_dependency_graph = field(Artifact | None, None),
+    # Whether to add header units from dependencies to the command line.
+    use_header_units = field(UseHeaderUnitsMode, UseHeaderUnitsMode("none")),
+    # Whether to export a header unit to all dependents.
+    export_header_unit = field([str, None], None),
+    # Filter what headers to include in header units.
+    export_header_unit_filter = field(list[str], []),
+    # Additional behavior for how to handle runtime dependencies
+    runtime_dependency_handling = field([RuntimeDependencyHandling, None], None),
+    # Should this library only be used for build time linkage
+    stub = field(bool, False),
+    # The calling context is allowed to use `AnalysisActions#anon_target` API.
+    # This is not allowed in the context of the `dynamic_outputs` callback.
+    anon_targets_allowed = field(bool, True),
+    # Any extra diagnostics to include in transitive diagnostics provider
+    extra_transitive_diagnostics = field(list[Artifact], []),
+    # Any extra diagnostics to include in [check] subtarget, maps from
+    # identifier (usually filename) to diagnostic output.
+    extra_diagnostics = field(dict[str, Artifact] | None, None),
+    # Whether to use fbcc Rust wrapper
+    use_fbcc_rust_wrapper = field(bool, False),
+    # Precompiled header
+    precompiled_header = field(Dependency | None, None),
+    # Prefix header
+    prefix_header = field(Artifact | None, None),
+    # Store "_cxx_toolchain" as "Dependency" for use in "anon_target"
+    _cxx_toolchain = field(Dependency | None, None),
+    # Use content-based filepaths for artifacts
+    use_content_based_paths = field(bool, False),
+    # Coverage instrumentation compiler flags
+    coverage_instrumentation_compiler_flags = field(list[str], []),
+    # Optional profile list artifact for selective coverage via -fprofile-list
+    coverage_profile_list = field(Artifact | None, None),
+    # Separate debug info
+    separate_debug_info = field(bool, False),
+    # Cuda compile stype
+    cuda_compile_style = field(CudaCompileStyle | None, None),
+    link_preference = field(LinkPreference, LinkPreference("default")),
+    supports_stripping = field(bool, True),
+    # Whether to set expect_eligible_for_dedupe on compile actions.
+    expect_eligible_for_dedupe = field(bool, False),
+    target_stats_cycle_mode = field(str, "none"),
+    target_stats_extra_srcs = field(dict[str, Artifact], {}),
+    target_stats_swift_dot = field(Artifact | None, None),
+    # The module the cycle tools resolve imports against. Not how the target is
+    # reported -- that stays the target's label.
+    target_stats_module_name = field(str | None, None),
+)
diff --git a/buck2/prelude/cxx/cxx_utility.bzl b/buck2/prelude/cxx/cxx_utility.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/cxx_utility.bzl
@@ -0,0 +1,41 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def cxx_attrs_use_fbcc_rust_wrapper(attrs: struct) -> bool:
+    return attrs.use_fbcc_rust_wrapper if hasattr(attrs, "use_fbcc_rust_wrapper") else False
+
+def cxx_attrs_get_allow_cache_upload(attrs: struct, default: [None, bool] = None) -> bool:
+    default_value = default if default != None else False
+    if not hasattr(attrs, "allow_cache_upload"):
+        return default_value
+    value = attrs.allow_cache_upload
+    return value if value != None else default_value
+
+def cxx_toolchain_allow_cache_upload_args():
+    doc = """
+        Whether to allow uploading of object files to cache when the compile
+        action is executed locally and the configuration allows uploads (i.e.,
+        there is a cache configured and the client has permission to write to it).
+        """
+    return {
+        "c_compiler_allow_cache_upload": attrs.option(
+            attrs.bool(),
+            default = None,
+            doc = doc,
+        ),
+        "cuda_compiler_allow_cache_upload": attrs.option(
+            attrs.bool(),
+            default = None,
+            doc = doc,
+        ),
+        "cxx_compiler_allow_cache_upload": attrs.option(
+            attrs.bool(),
+            default = None,
+            doc = doc,
+        ),
+    }
diff --git a/buck2/prelude/cxx/debug.bzl b/buck2/prelude/cxx/debug.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/debug.bzl
@@ -0,0 +1,24 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Model the various "split" debug scenarios (e.g. `-gsplit-dwarf`).
+SplitDebugMode = enum(
+    # Debug info, if present, is inline in the object file, and will be linked
+    # into executables and shared libraries (e.g. traditional behavior when
+    # using `-g`).
+    "none",
+    # Debug info. if present is included in the object file, but will *not* be
+    # linked into executables and shared libraries.  This style usually requires
+    # an additional step, separate from the link, to combine and package debug
+    # info (e.g. `dSYM`, `dwp`).
+    "single",
+    # Debug info, is present, is separated to .dwo file. This style requires
+    # additional step, separate from the link, to combine and package debug
+    # info (e.g. `dSYM`, `dwp`).
+    "split",
+)
diff --git a/buck2/prelude/cxx/diagnostics.bzl b/buck2/prelude/cxx/diagnostics.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/diagnostics.bzl
@@ -0,0 +1,47 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:expect.bzl", "expect")
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+
+def check_sub_target(
+    ctx: AnalysisContext,
+    diagnostics: dict[str, Artifact],
+    error_handler: [typing.Callable, None] = None,
+    output_name: str = "diagnostics.txt",
+    extra_sub_targets: dict[str, Artifact] = {},
+) -> (list[Provider], Artifact):
+    expect(len(diagnostics) > 0)
+
+    if len(diagnostics) == 1:
+        all_diagnostics = diagnostics.values()[0]
+    else:
+        toolchain = get_cxx_toolchain_info(ctx)
+        concatenate_diagnostics_tool = toolchain.internal_tools.concatenate_diagnostics
+        all_diagnostics = ctx.actions.declare_output(output_name, has_content_based_path = False)
+        ctx.actions.run(
+            [
+                concatenate_diagnostics_tool,
+                cmd_args(all_diagnostics.as_output(), format = "--out={}"),
+                diagnostics.values(),
+            ],
+            category = "diagnostics",
+            identifier = output_name,
+            error_handler = error_handler,
+        )
+
+    all_sub_targets = {short_path: [DefaultInfo(default_output = diag)] for short_path, diag in diagnostics.items()}
+    for short_path, diag in extra_sub_targets.items():
+        all_sub_targets[short_path] = [DefaultInfo(default_output = diag)]
+
+    return [
+        DefaultInfo(
+            default_output = all_diagnostics,
+            sub_targets = all_sub_targets,
+        )
+    ], all_diagnostics
diff --git a/buck2/prelude/cxx/dist_lto/README.md b/buck2/prelude/cxx/dist_lto/README.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/README.md
@@ -0,0 +1,323 @@
+# Distributed ThinLTO in Buck2
+
+Sean Gillespie, April 2022
+
+This document is a technical overview into Buck2's implementation of a
+distributed ThinLTO. Like all rules in Buck2, this implementation is written
+entirely in Starlark, contained in `dist_lto.bzl` (in this same directory).
+
+## Motivation
+
+First, I highly recommend watching
+[Teresa Johnson's CppCon2017 talk about ThinLTO](https://www.youtube.com/watch?v=p9nH2vZ2mNo),
+which covers the topics in this section in much greater detail than I can.
+
+C and C++ have long enjoyed significant optimizations at the hands of compilers.
+However, they have also long suffered a fundamental limitation; a C or C++
+compiler can only optimize code that it sees in a single translation unit. For a
+language like C or C++, this means in practice that only code that is included
+via the preprocessor or specified in the translation unit can be optimized as a
+single unit. C and C++ compilers are unable to inline functions that are defined
+in different translation units. However, a crucial advantage of this compilation
+model is that all C and C++ compiler invocations are _completely
+parallelizable_; despite sacrificing some code quality, C and C++ compilation
+turns into a massively parallel problem with a serial link step at the very end.
+
+```
+flowchart LR;
+    header.h;
+
+    header.h --> a.cpp;
+    header.h -->|#include| b.cpp;
+    header.h --> c.cpp;
+
+    a.cpp --> a.o;
+    b.cpp -->|clang++ -O2| b.o;
+    c.cpp --> c.o;
+
+    a.o --> main;
+    b.o -->|ld| main;
+    c.o --> main;
+```
+
+([Rendered](https://fburl.com/mermaid/rzup8o32). Compilation and optimization of
+a, b, and c can proceed in parallel.)
+
+In cases where absolute performance is required, though, the inability to
+perform cross-translation-unit (or "cross-module", in LLVM parlance)
+optimizations becomes more of a problem. To solve this, a new compilation
+paradigm was designed, dubbed "Link-Time Optimization" (LTO). In this scheme, a
+compiler will not produce machine code when processing a translation unit;
+rather, it will output the compiler's intermediate representation (e.g. LLVM
+bitcode). Later on, when it is time for the linker to run, it will load all of
+the compiler IR into one giant module, run optimization passes on the
+mega-module, and produce a final binary from that.
+
+This works quite well, if all that you're looking for is run-time performance. A
+major drawback of the LTO approach is that all of the parallelism gained from
+optimizing translation units individually is now completely lost; instead, the
+linker (using a plugin) will do a single-threaded pass of _all code_ produced by
+compilation steps. This is extremely slow, memory-intensive, and unable to be
+run incrementally. There are targets at Meta that simply can't be LTO-compiled
+because of their size.
+
+```
+flowchart LR;
+    header.h;
+
+    header.h --> a.cpp;
+    header.h -->|#include| b.cpp;
+    header.h --> c.cpp;
+
+    a.cpp --> a.bc;
+    b.cpp -->|clang++ -O2 -flto -x ir| b.bc;
+    c.cpp --> c.bc;
+
+    a.bc --> a_b_c.bc;
+    b.bc -->|linker driver| a_b_c.bc;
+    c.bc --> a_b_c.bc;
+
+    a_b_c.bc -->|opt| a_b_c_optimized.bc
+
+    a_b_c_optimized.bc -->|codegen| main.o
+
+    main.o --> |ld| main
+```
+
+([Rendered](https://fburl.com/mermaid/kid35io9). `a.bc`, `b.bc`, and `c.bc` are
+LLVM bitcode; they are all merged together into a single module,
+`a_b_c_optimized.bc`, which is then optimized and codegen'd into a final
+binary.)
+
+The idea of ThinLTO comes from a desire to maintain the ability to optimize
+modules in parallel while still allowing for profitable cross-module
+optimizations. The idea is this:
+
+1. Just like regular LTO, the compiler emits bitcode instead of machine code.
+   However, it also contains some light metadata such as a call graph of symbols
+   within the module.
+2. The monolithic LTO link is split into three steps: `index`, `opt`, and
+   `link`.
+
+```
+flowchart LR;
+    header.h;
+
+    header.h --> a.cpp;
+    header.h -->|#include| b.cpp;
+    header.h --> c.cpp;
+
+    a.cpp --> a.bc;
+    b.cpp -->|clang++ -O2 -flto -x ir| b.bc;
+    c.cpp --> c.bc;
+
+    a.bc --> index;
+    b.bc --> index;
+    c.bc --> index;
+
+    index --> a.thinlto.bc;
+    index --> b.thinlto.bc;
+    index --> c.thinlto.bc;
+
+    a.thinlto.bc --> a.o;
+    b.thinlto.bc --> b.o;
+    b.bc --> a.o;
+    b.bc --> c.o;
+    c.thinlto.bc --> c.o;
+
+    a.o --> main;
+    b.o -->|ld| main;
+    c.o --> main;
+```
+
+([Rendered](https://fburl.com/mermaid/56oc99t5))
+
+The `index` step looks like a link step. However, it does not produce a final
+binary; instead, it looks at every compiler IR input file that it receives and
+heuristically determines which other IR modules it should be optimized with in
+order to achieve profitable optimizations. These modules might include functions
+that the index step thinks probably will get inlined, or globals that are read
+in the target IR input file. The output of the index step is a series of files
+on disk that indicate which sibling object files should be present when
+optimizing a particular object file, for each object file in the linker
+command-line.
+
+The `opt` step runs in parallel for every object file. Each object file will be
+optimized using the compiler's optimizer (e.g. `opt`, for LLVM). The optimizer
+will combine the objects that were referenced as part of the index step as
+potentially profitable to include and optimize them all together.
+
+The `link` step takes the outputs of `opt` and links them together, like a
+normal linker.
+
+In practice, ThinLTO manages to recapture the inherent parallelism of C/C++
+compilation by pushing the majority of work to the parallel `opt` phase of
+execution. When LLVM performs ThinLTO by default, it will launch a thread pool
+and process independent modules in parallel. ThinLTO does not produce as
+performant a binary as a monolithic LTO; however, in practice, ThinLTO binaries
+[paired with AutoFDO](https://fburl.com/wiki/q480euco) perform comparably to
+monolithic LTO. Furthermore, ThinLTO's greater efficiency allows for more
+expensive optimization passes to be run, which can further improve code quality
+near that of a monolithic LTO.
+
+This is all great, and ThinLTO has been in use at Meta for some time. However,
+Buck2 has the ability to take a step further than Buck1 could ever have - Buck2
+can distribute parallel `opt` actions across many machines via Remote Execution
+to achieve drastic speedups in ThinLTO wall clock time, memory usage, and
+incrementality.
+
+## Buck2's Implementation
+
+Buck2's role in a distributed ThinLTO compilation is to construct a graph of
+actions that directly mirrors the graph that the `index` step outputs. The graph
+that the `index` step outputs is entirely dynamic and, as such, the build system
+is only aware of what the graph could be after the `index` step is complete.
+Unlike Buck1 (or even Blaze/Bazel), Buck2 has explicit support for this paradigm
+[("dynamic dependencies")](https://fburl.com/gdoc/zklwhkll). Therefore, for
+Buck2, the basic strategy looks like:
+
+1. Invoke `clang` to act as `index`. `index` will output a file for every object
+   file that indicates what other modules need to be present when running `opt`
+   on the object file (an "imports file").
+2. Read imports files and construct a graph of dynamic `opt` actions whose
+   dependencies mirror the contents of the imports files.
+3. Collect the outputs from the `opt` actions and invoke the linker to produce a
+   final binary.
+
+Action `2` is inherently dynamic, since it must read the contents of files
+produced as part of action `1`. Furthermore, Buck2's support of `1` is
+complicated by the fact that certain Buck2 rules can produce an archive of
+object files as an output (namely, the Rust compiler). As a result, Buck2's
+implementation of Distributed ThinLTO is highly dynamic.
+
+Buck2's implementation contains four phases of actions:
+
+1. `thin_lto_prepare`, which specifically handles archives containing LLVM IR
+   and prepares them to be inputs to `thin_lto_index`,
+2. `thin_lto_index`, which invokes LLVM's ThinLTO indexer to produce a imports
+   list for every object file to be optimized,
+3. `thin_lto_opt`, which optimizes each object file in parallel with its imports
+   present,
+4. `thin_lto_link`, which links together the optimized code into a final binary.
+
+### thin_lto_prepare
+
+It is a reality of Buck2 today that some rules don't produce a statically-known
+list of object files. The list of object files is known _a priori_ during C/C++
+compilation, since they have a one-to-one correspondence to source files;
+however, the Rust compiler emits an archive of object files; without inspecting
+the archive, Buck2 has no way of knowing what the contents of the archive are,
+or even if they contain bitcode at all.
+
+Future steps (particularly `thin_lto_index`) are defined to only operate on a
+list of object files - a limitation
+[inherited from LLVM](https://lists.llvm.org/pipermail/llvm-dev/2019-June/133145.html).
+Therefore, it is the job of `thin_lto_prepare` to turn an archive into a list of
+objects - namely, by extracting the archive into a directory.
+
+Buck2 dispatches a `thin_lto_prepare` action for every archive. Each prepare
+action has two outputs:
+
+1. An **output directory** (called `objects` in the code), a directory that
+   contains the unextracted contents of the archive.
+2. A **archive manifest**, a JSON document containing a list of object files
+   that are contained in the output directory.
+
+The core logic of this action is implemented in the Python script
+`dist_lto_prepare.py`, contained in the `tools` directory. In addition to
+unpacking each archive, Buck2 keeps track of the list of archives as a Starlark
+array that will be referenced by index in later steps.
+
+### thin_lto_index
+
+With all archives prepared, the next step is to invoke LLVM's ThinLTO indexer.
+For the purposes of Buck2, the indexer looks like a linker; because of this,
+Buck2 must construct a reasonable link line. Buck2 does this by iterating over
+the list of linkables that it has been given and constructing a link line from
+them. Uniquely for distributed ThinLTO, Buck2 must wrap all objects that were
+derived from `thin_lto_prepare` (i.e. were extracted from archives) with
+`-Wl,--start-lib` and `-Wl,--end-lib` to ensure that they are still treated as
+if they were archives by the indexer.
+
+Invoking the indexer is relatively straightforward in that Buck2 invokes it like
+it would any other linker. However, once the indexer returns, Buck2 must
+post-process its output into a format that Buck2's Starlark can understand and
+translate into a graph of dynamic `opt` actions. The first thing that Buck2 is
+write a "meta file" to disk, which communicates inputs and outputs of
+`thin_lto_index` to a Python script, `dist_lto_planner.py`. The meta file
+contains a list of 7-tuples, whose members are:
+
+1. The path to the source bitcode file. This is used as an index into a
+   dictionary that records much of the metadata coming from these lines.
+2. The path to an output file. `dist_lto_planner.py` is expected to place a
+   ThinLTO index file at this location (suffixed `.thinlto.bc`).
+3. The path to an output plan. This script is expected to place a link plan here
+   (a JSON document indicating which other object files this) object file
+   depends on, among other things.
+4. If this object file came from an archive, the index of the archive in the
+   Starlark archives array.
+5. If this object file came from an archive, the name of the archive.
+6. If this object file came from an archive, the path to an output plan. This
+   script is expected to produce an archive link plan here (a JSON) document
+   similar to the object link plan, except containing link information for every
+   file in the archive from which this object came.
+7. If this object file came from an archive, the indexes directory of that
+   archive. This script is expected to place all ThinLTO indexes derived from
+   object files originating from this archive in that directory.
+
+There are two indices that are derived from this meta file: the object index
+(`mapping["index"]`) and the archive index (`mapping["archive_index"]`). These
+indices are indices into Starlark arrays for all objects and archive linkables,
+respectively. `dist_lto_planner.py` script does not inspect them; rather, it is
+expected to communicate these indices back to Starlark by writing them to the
+link plan.
+
+`dist_lto_planner.py` reads the index and imports file produced by LLVM and
+derives a number of artifacts:
+
+1. For each object file, a `thinlto.bc` file (`bitcode_file`). This file is the
+   same as the input bitcode file, except that LLVM has inserted a number of
+   module imports to refer to the other modules that will be present when the
+   object file is optimized.
+2. For each object file, an optimization plan (`plan`). The optimization plan is
+   a JSON document indicating how to construct an `opt` action for this object
+   file. This plan includes this object file's module imports, whether or not
+   this file contains bitcode at all, a location to place the optimized object
+   file, and a list of archives that this object file imported.
+3. For each archive, an optimization plan (`archive_plan`), which contains
+   optimization plans for all of the object files contained within the archive.
+
+This action is a dynamic action because, in the case that there are archives
+that needed to be preprocessed by `thin_lto_prepare`, this action must read the
+archive manifest.
+
+### thin_lto_opt
+
+After `thin_lto_index` completes, Buck2 launches `thin_lto_opt` actions for
+every object file and for every archive. For each object file, Buck2 reads that
+object file's optimization plan. At this phase, it is Buck2's responsibility to
+declare dependencies on every object file referenced by that object's
+compilation plan; it does so here by adding `hidden` dependencies on every
+object file and archive that the archive plan says that this object depends on.
+
+`thin_lto_opt` uses a Python wrapper around LLVM because of a bug (T116695431)
+where LTO fatal errors don't prevent `clang` from returning an exit code of
+zero. The Python script wraps `clang` and exits with a non-zero exit code if
+`clang` produced an empty object file.
+
+For each archive, Buck2 reads the archive's optimization plan and constructs
+additional `thin_lto_opt` actions for each object file contained in the archive.
+Buck2 creates a directory of symlinks (`opt_objects`) that either contains
+symlinks to optimized object files (if the object file contained bitcode) or the
+original object file (if it didn't). The purpose of this symlink directory is to
+allow the final link to consume object files directly from this directory
+without having to know whether they were optimized or not. Paths to these files
+are passed to the link step via the optimization manifest (`opt_manifest`).
+
+### thin_lto_link
+
+The final link step. Similar to `thin_lto_index`, this involves creating a link
+line to feed to the linker that uses the optimized artifacts that we just
+calculated. In cases where Buck2 would put an archive on the link line, it
+instead inserts `-Wl,--start-lib`, `-Wl,--end-lib`, and references to the
+objects in `opt_objects`.
diff --git a/buck2/prelude/cxx/dist_lto/darwin/common_types.bzl b/buck2/prelude/cxx/dist_lto/darwin/common_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/darwin/common_types.bzl
@@ -0,0 +1,53 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//linking:link_info.bzl",
+    "SharedLibLinkable",  # @unused Used as a type
+)
+
+EagerBitcodeLinkData = record(
+    name = str,
+    input_object_file = Artifact,  # This may be a native object file or a bitcode file, we can't tell at this point
+    output_index_shard_file = Artifact,
+    plan = Artifact,
+    output_first_codegen_round_native_object_file = field([Artifact, None]),
+    output_precodegen_ir = field([Artifact, None]),
+    output_final_native_object_file = Artifact,
+    merged_bc = field([Artifact, None]),
+    extra_outputs = field(dict[str, Artifact]),
+)
+
+LazyBitcodeLinkData = record(
+    name = str,
+    input_object_file = Artifact,  # This may be a native object file or a bitcode file, we can't tell at this point
+    output_index_shard_file = Artifact,
+    plan = Artifact,
+    output_final_native_object_file = Artifact,
+    output_first_codegen_round_native_object_file = field([Artifact, None]),
+    output_precodegen_ir = field([Artifact, None]),
+    merged_bc = field([Artifact, None]),
+    archive_start = bool,
+    archive_end = bool,
+    extra_outputs = field(dict[str, Artifact]),
+)
+
+DynamicLibraryLinkData = record(
+    linkable = SharedLibLinkable,
+)
+
+LinkDataType = enum(
+    "eager_bitcode",
+    "lazy_bitcode",
+    "dynamic_library",
+)
+
+DThinLTOLinkData = record(
+    data_type = LinkDataType,
+    link_data = field([LazyBitcodeLinkData, EagerBitcodeLinkData, DynamicLibraryLinkData]),
+)
diff --git a/buck2/prelude/cxx/dist_lto/darwin/dist_lto.bzl b/buck2/prelude/cxx/dist_lto/darwin/dist_lto.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/darwin/dist_lto.bzl
@@ -0,0 +1,926 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "make_artifact_tset",
+)
+load("@prelude//apple:apple_utility.bzl", "get_apple_architecture")
+# @oss-disable[end= ]: load("@prelude//apple/meta_only:shared_library_interfaces.bzl", "get_shared_library_interface_generation_linker_flags")
+load(
+    "@prelude//apple/swift:swift_incremental_support.bzl",
+    "get_uses_content_based_paths",
+)
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_link_utility.bzl",
+    "CxxSanitizerRuntimeArguments",
+    "cxx_link_cmd_parts",
+    "get_extra_darwin_linker_flags",
+    "linker_map_args",
+)
+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerType")
+load("@prelude//cxx:link_types.bzl", "ExtraLinkerOutputCategory", "LinkOptions")
+load("@prelude//cxx:target_sdk_version.bzl", "get_target_sdk_version_flags")
+load(
+    "@prelude//linking:link_info.bzl",
+    "ArchiveLinkable",
+    "ExtraLinkerOutputs",
+    "FrameworksLinkable",  # @unused Used as a type
+    "LinkInfo",
+    "LinkedObject",
+    "ObjectsLinkable",
+    "SharedLibLinkable",  # @unused Used as a type
+    "SwiftmoduleLinkable",  # @unused Used as a type
+    "append_linkable_args",
+    "map_to_link_infos",
+    "unpack_external_debug_info",
+)
+load("@prelude//linking:strip.bzl", "strip_object")
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load(":common_types.bzl", "DThinLTOLinkData", "DynamicLibraryLinkData", "EagerBitcodeLinkData", "LazyBitcodeLinkData", "LinkDataType")
+load(":thin_link.bzl", "thin_link")
+load(":thin_link_record_defs.bzl", "BitcodeMergeState", "ObjectFileOptimizationPlan")
+
+def identity_projection(value: cmd_args):
+    return value
+
+# This tset exists for the sole purpose of saving memory. When action inputs
+# are hashed, the memory cost for hashing tset projection generated input
+# tree nodes is paid once per unique node. Without a tset projection every
+# input is hashed once per action it is included in. The opt actions created
+# here share a tremendous number of inputs, so we might end up hashing a
+# given input 1000s of times, and paying dearly for it in memory consumption.
+# This is not ideal either, the memory allocated to hash these tset projection
+# generated inputs will not be freed for the duration of the build, but in
+# testing that is a worth while tradeoff.
+IdentityTSet = transitive_set(args_projections = {"identity": identity_projection})
+
+def _sort_index_link_data(input_list: list[DThinLTOLinkData]) -> list[DThinLTOLinkData]:
+    # Sort link datas to reduce binary size. The idea is to encourage the linker to load the minimal number of object files possible. We load force loaded archives first (since they will be loaded no matter what), then non lazy object files (which will also be loaded no matter what), then shared libraries (to share as many symbols as possible), then finally regular archives
+    force_loaded_archives = []
+    regular_archives = []
+    object_files = []
+    dynamic_libraries = []
+    for link_data in input_list:
+        if link_data.data_type == LinkDataType("eager_bitcode"):
+            object_files.append(link_data)
+        elif link_data.data_type == LinkDataType("lazy_bitcode"):
+            regular_archives.append(link_data)
+        elif link_data.data_type == LinkDataType("dynamic_library"):
+            dynamic_libraries.append(link_data)
+
+    return force_loaded_archives + object_files + dynamic_libraries + regular_archives
+
+# Generate linker flags that are common to thin-link, native-link, and the link invocation used
+# to generate a shared library interface
+def _get_common_linker_flags(ctx: AnalysisContext, link_infos: list[LinkInfo], executable_link: bool, sanitizer_runtime_args: list[ArgLike]):
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    result = cmd_args(cxx_link_cmd_parts(cxx_toolchain, executable_link).linker_flags)
+    result.add(get_extra_darwin_linker_flags(ctx))
+    result.add(sanitizer_runtime_args)
+
+    for link in link_infos:
+        result.add(link.pre_flags)
+        result.add(link.post_flags)
+
+    return result
+
+DoubleCodegenState = enum(
+    "disabled",
+    "first_round",
+    "second_round",
+)
+
+def create_output_first_codegen_round_native_object_file(ctx, name, double_codegen_enabled, uses_content_based_paths):
+    if double_codegen_enabled:
+        return ctx.actions.declare_output(name + ".opt.first_codegen_round.o", has_content_based_path = uses_content_based_paths)
+    return None
+
+def create_output_precodegen_ir(ctx, name, double_codegen_enabled, uses_content_based_paths):
+    if double_codegen_enabled:
+        return ctx.actions.declare_output(name + ".opt.precodegen.bc", has_content_based_path = uses_content_based_paths)
+    return None
+
+def complete_distributed_link_with_expanded_archive_link_data(
+    ctx: AnalysisContext,
+    artifacts,
+    outputs,
+    common_opt_cmd: cmd_args,
+    double_codegen_enabled: bool,
+    executable_link: bool,
+    external_debug_info_container_directory: Artifact,
+    extra_lto_outputs: dict[str, Artifact],
+    extra_native_link_outputs: dict[str, Artifact],
+    final_binary_out: Artifact,
+    index_argsfile_out: Artifact,
+    link_infos: list[LinkInfo],
+    link_options: LinkOptions,
+    linker_argsfile_out: Artifact,
+    linker_map_out: Artifact | None,
+    make_cat,
+    premerger_enabled: bool,
+    prepared_archive_artifacts,
+    sanitizer_runtime_args: CxxSanitizerRuntimeArguments,
+    uses_content_based_paths: bool,
+):
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    lto_planner = cxx_toolchain.internal_tools.dist_lto.planner[LinkerType("darwin")]
+    lto_opt = cxx_toolchain.internal_tools.dist_lto.opt[LinkerType("darwin")]
+    lto_archive_mapper = cxx_toolchain.internal_tools.dist_lto.archive_mapper
+
+    normalized_identifier = link_options.identifier.replace("[", "_").replace("]", "_").replace(" ", "_") if link_options.identifier != None else None
+
+    def make_id(i: str) -> str:
+        """Used to make sure identifiers for our actions include the provided identifier"""
+        if normalized_identifier != None:
+            return normalized_identifier + "_" + i
+        return i
+
+    recorded_outputs = {}
+
+    def name_for_obj(link_name: str, object_artifact: Artifact) -> str:
+        """Creates a unique name/path we can use for a particular object file input"""
+        prefix = "{}/{}".format(link_name, object_artifact.short_path)
+        case_insensitive_prefix = prefix.lower()
+        # it's possible (though unlikely) that we can get duplicate name/short_path, so just uniquify them.
+        # Make sure we case normalize before to avoid collisions on case in-sensitive file systems.
+        if case_insensitive_prefix in recorded_outputs:
+            recorded_outputs[case_insensitive_prefix] += 1
+            extra = recorded_outputs[case_insensitive_prefix]
+            prefix = "{}-{}".format(prefix, extra)
+        else:
+            recorded_outputs[case_insensitive_prefix] = 1
+        return prefix
+
+    names = {}
+
+    def name_for_link(info: LinkInfo) -> str:
+        """Creates a unique name for a LinkInfo that we are consuming"""
+        name = info.name or "unknown"
+        if name not in names:
+            names[name] = 1
+        else:
+            names[name] += 1
+            name += "-{}".format(names[name])
+        return make_id(name)
+
+    # The process to optimize and codegen a given bitcode file may depend on other bitcode
+    # files (ie. to inline function calls between bitcode files). Which bitcode files depend
+    # on one another is not known until thin link (sometimes called the dynamic plan) is run.
+    # For each input bitcode file, thin link will produce a plan JSON document that will identify
+    # which other bitcode files (or archive of bitcode files) it should be optimized along side.
+    # Thin link idenitifies these depended upon bitcode files by their index in the sorted version of this array.
+    raw_link_data = []
+    debug_info_symlink_map = {}
+    deps_linker_flags = cmd_args()
+
+    def declare_extra_opt_outputs(name: str) -> dict[str, Artifact]:
+        result = {}
+        for output_type_str in extra_lto_outputs.keys():
+            result[output_type_str] = ctx.actions.declare_output(name + "." + output_type_str, has_content_based_path = uses_content_based_paths)
+        return result
+
+    for link in link_infos:
+        link_name = name_for_link(link)
+
+        deps_linker_flags.add(link.pre_flags)
+        deps_linker_flags.add(link.post_flags)
+
+        for linkable in link.linkables:
+            if isinstance(linkable, ObjectsLinkable):
+                for obj in linkable.objects:
+                    name = name_for_obj(link_name, obj)
+                    index_shard_output = ctx.actions.declare_output(name + ".thinlto.bc", has_content_based_path = uses_content_based_paths)
+                    plan_output = ctx.actions.declare_output(name + ".opt.plan", has_content_based_path = uses_content_based_paths)
+                    final_native_object_file_output = ctx.actions.declare_output(name + ".opt.o", has_content_based_path = uses_content_based_paths)
+                    merged_bc_output = None
+                    if premerger_enabled:
+                        # Bitcode files are referenced by index shards by output path, and these merged bitcode files are produced during the
+                        # same thin-link action that produces the index shards. For this reason, we cannot enable content based path hashing
+                        # for these outputs because we need to know the final path before running the action.
+                        merged_bc_output = ctx.actions.declare_output(name + ".merged.bc", has_content_based_path = False)
+
+                    output_first_codegen_round_native_object_file = create_output_first_codegen_round_native_object_file(
+                        ctx, name, double_codegen_enabled, uses_content_based_paths
+                    )
+                    output_precodegen_ir = create_output_precodegen_ir(ctx, name, double_codegen_enabled, uses_content_based_paths)
+
+                    data = DThinLTOLinkData(
+                        data_type = LinkDataType("eager_bitcode"),
+                        link_data = EagerBitcodeLinkData(
+                            name = name,
+                            input_object_file = obj,
+                            output_index_shard_file = index_shard_output,
+                            plan = plan_output,
+                            output_final_native_object_file = final_native_object_file_output,
+                            output_first_codegen_round_native_object_file = output_first_codegen_round_native_object_file,
+                            output_precodegen_ir = output_precodegen_ir,
+                            merged_bc = merged_bc_output,
+                            extra_outputs = declare_extra_opt_outputs(name),
+                        ),
+                    )
+                    raw_link_data.append(data)
+                    debug_info_symlink_map["debug_info_file_{}".format(len(debug_info_symlink_map))] = final_native_object_file_output
+            elif isinstance(linkable, ArchiveLinkable) and linkable.archive.external_objects:
+                for virtual_archive_index, obj in enumerate(linkable.archive.external_objects):
+                    name = name_for_obj(link_name, obj)
+                    index_shard_output = ctx.actions.declare_output(name + ".thinlto.bc", has_content_based_path = uses_content_based_paths)
+                    plan_output = ctx.actions.declare_output(name + ".opt.plan", has_content_based_path = uses_content_based_paths)
+                    final_native_object_file_output = ctx.actions.declare_output(name + ".opt.o", has_content_based_path = uses_content_based_paths)
+                    merged_bc_output = None
+                    if premerger_enabled:
+                        # Bitcode files are referenced by index shards by output path, and these merged bitcode files are produced during the
+                        # same thin-link action that produces the index shards. For this reason, we cannot enable content based path hashing
+                        # for these outputs because we need to know the final path before running the action.
+                        merged_bc_output = ctx.actions.declare_output(name + ".merged.bc", has_content_based_path = False)
+
+                    output_first_codegen_round_native_object_file = create_output_first_codegen_round_native_object_file(
+                        ctx, name, double_codegen_enabled, uses_content_based_paths
+                    )
+                    output_precodegen_ir = create_output_precodegen_ir(ctx, name, double_codegen_enabled, uses_content_based_paths)
+
+                    # The first member in a non force loaded virtual archive gets --start-lib prended on the command line
+                    archive_start = (not linkable.link_whole) and virtual_archive_index == 0
+                    archive_end = (not linkable.link_whole) and virtual_archive_index == len(linkable.archive.external_objects) - 1
+                    data = DThinLTOLinkData(
+                        data_type = LinkDataType("lazy_bitcode"),
+                        link_data = LazyBitcodeLinkData(
+                            name = name,
+                            input_object_file = obj,
+                            output_index_shard_file = index_shard_output,
+                            plan = plan_output,
+                            output_final_native_object_file = final_native_object_file_output,
+                            output_first_codegen_round_native_object_file = output_first_codegen_round_native_object_file,
+                            output_precodegen_ir = output_precodegen_ir,
+                            merged_bc = merged_bc_output,
+                            archive_start = archive_start,
+                            archive_end = archive_end,
+                            extra_outputs = declare_extra_opt_outputs(name),
+                        ),
+                    )
+                    raw_link_data.append(data)
+                    debug_info_symlink_map["debug_info_file_{}".format(len(debug_info_symlink_map))] = final_native_object_file_output
+            elif isinstance(linkable, ArchiveLinkable):
+                manifest = artifacts[prepared_archive_artifacts[linkable.archive.artifact].manifest].read_json()
+                if not len(manifest["objects"]):
+                    continue
+
+                archive_name = name_for_obj(link_name, linkable.archive.artifact)
+                archive_contents_mapper_cmd = cmd_args(lto_archive_mapper)
+                archive_contents_mapper_cmd.add("--objects_dir", prepared_archive_artifacts[linkable.archive.artifact].extracted_object_files_dir)
+                for archive_index, object_basename in enumerate(manifest["objects"]):
+                    archive_start = (not linkable.link_whole) and archive_index == 0
+                    archive_end = (not linkable.link_whole) and archive_index == len(manifest["objects"]) - 1
+                    name = "{}/{}".format(archive_name, object_basename)
+                    input_object_file = ctx.actions.declare_output(name, has_content_based_path = uses_content_based_paths)
+                    index_shard_output = ctx.actions.declare_output(name + ".thinlto.bc", has_content_based_path = uses_content_based_paths)
+                    plan_output = ctx.actions.declare_output(name + ".opt.plan", has_content_based_path = uses_content_based_paths)
+                    final_native_object_file_output = ctx.actions.declare_output(name + ".opt.o", has_content_based_path = uses_content_based_paths)
+                    merged_bc_output = None
+                    if premerger_enabled:
+                        # Bitcode files are referenced by index shards by output path, and these merged bitcode files are produced during the
+                        # same thin-link action that produces the index shards. For this reason, we cannot enable content based path hashing
+                        # for these outputs because we need to know the final path before running the action.
+                        merged_bc_output = ctx.actions.declare_output(name + ".merged.bc", has_content_based_path = False)
+                    output_first_codegen_round_native_object_file = create_output_first_codegen_round_native_object_file(
+                        ctx, name, double_codegen_enabled, uses_content_based_paths
+                    )
+                    output_precodegen_ir = create_output_precodegen_ir(ctx, name, double_codegen_enabled, uses_content_based_paths)
+
+                    raw_link_data.append(
+                        DThinLTOLinkData(
+                            data_type = LinkDataType("lazy_bitcode"),
+                            link_data = LazyBitcodeLinkData(
+                                name = name,
+                                input_object_file = input_object_file,
+                                output_index_shard_file = index_shard_output,
+                                plan = plan_output,
+                                output_final_native_object_file = final_native_object_file_output,
+                                output_first_codegen_round_native_object_file = output_first_codegen_round_native_object_file,
+                                output_precodegen_ir = output_precodegen_ir,
+                                merged_bc = merged_bc_output,
+                                archive_start = archive_start,
+                                archive_end = archive_end,
+                                extra_outputs = declare_extra_opt_outputs(name),
+                            ),
+                        )
+                    )
+                    archive_contents_mapper_cmd.add("--object_to_map", object_basename, input_object_file.as_output())
+                    debug_info_symlink_map["debug_info_file_{}".format(len(debug_info_symlink_map))] = final_native_object_file_output
+                ctx.actions.run(archive_contents_mapper_cmd, category = make_cat("thin_lto_map_archive"), identifier = archive_name)
+
+            elif isinstance(linkable, SharedLibLinkable):
+                data = DThinLTOLinkData(
+                    data_type = LinkDataType("dynamic_library"),
+                    link_data = DynamicLibraryLinkData(linkable = linkable),
+                )
+                raw_link_data.append(data)
+            elif isinstance(linkable, FrameworksLinkable) or isinstance(linkable, SwiftmoduleLinkable):
+                # These linkables are handled separately for flag deduplication purposes, as in append_linkable_args:
+                # https://www.internalfb.com/code/fbsource/[c6d2c820b394]/fbcode/buck2/prelude/linking/link_info.bzl?lines=271-278
+                pass
+            else:
+                fail("Unhandled linkable type: {}".format(str(linkable)))
+
+    common_link_flags = _get_common_linker_flags(ctx, link_infos, executable_link, sanitizer_runtime_args.extra_link_args)
+
+    sorted_index_link_data = _sort_index_link_data(raw_link_data)
+
+    link_plan_out = ctx.actions.declare_output(final_binary_out.basename + ".link-plan.json", has_content_based_path = uses_content_based_paths)
+
+    thin_link(
+        ctx = ctx,
+        final_binary_out = final_binary_out,
+        sorted_index_link_data = sorted_index_link_data,
+        common_link_flags = common_link_flags,
+        linker = cxx_link_cmd_parts(cxx_toolchain, executable_link).linker,
+        lto_planner = lto_planner,
+        post_linker_flags = cxx_link_cmd_parts(cxx_toolchain, executable_link).post_linker_flags,
+        index_argsfile_out = outputs[index_argsfile_out],
+        link_plan_out = link_plan_out,
+        identifier = link_options.identifier,
+        premerger_enabled = premerger_enabled,
+        use_content_based_output_paths = uses_content_based_paths,
+        make_cat = make_cat,
+        make_id = make_id,
+    )
+
+    # Create an argsfile and dump all the flags to be processed later by lto_opt.
+    # These flags are common to all opt actions, we don't need an argfile for each action, one
+    # for the entire link unit will do.
+    opt_argsfile = ctx.actions.declare_output(final_binary_out.basename + ".lto_opt_argsfile", has_content_based_path = uses_content_based_paths)
+    ctx.actions.write(opt_argsfile.as_output(), common_opt_cmd, allow_args = True)
+
+    def optimize_object(ctx: AnalysisContext, artifacts, outputs, bitcode_link_data, double_codegen_state: DoubleCodegenState, merged_cgdata: Artifact | None):
+        output_index_shard_file = bitcode_link_data.output_index_shard_file
+        input_object_file = bitcode_link_data.input_object_file
+        merged_bc = bitcode_link_data.merged_bc
+        name = bitcode_link_data.name
+        if double_codegen_state == DoubleCodegenState("first_round"):
+            output_native_object_file = bitcode_link_data.output_first_codegen_round_native_object_file
+        else:
+            output_native_object_file = bitcode_link_data.output_final_native_object_file
+
+        plan = bitcode_link_data.plan
+
+        optimization_plan = ObjectFileOptimizationPlan(**artifacts[plan].read_json())
+
+        # If the object was not compiled with thinlto flags, then there
+        # won't be valid outputs for it from the indexing, but we still
+        # need to bind the artifact. Similarily, if a bitcode file is not
+        # loaded by the indexing phase, or is absorbed by another module,
+        # there is no point optimizing it.
+        if not optimization_plan.loaded_by_linker or not optimization_plan.is_bitcode or optimization_plan.merge_state == BitcodeMergeState("ABSORBED").value:
+            ctx.actions.write(outputs[output_native_object_file].as_output(), "")
+            if double_codegen_state == DoubleCodegenState("first_round"):
+                ctx.actions.write(outputs[bitcode_link_data.output_precodegen_ir].as_output(), "")
+            if double_codegen_state == DoubleCodegenState("disabled") or double_codegen_state == DoubleCodegenState("first_round"):
+                mapped_extra_outputs = {output_type: outputs[artifact] for output_type, artifact in bitcode_link_data.extra_outputs.items()}
+                for extra_output_artifact in mapped_extra_outputs.values():
+                    ctx.actions.write(extra_output_artifact.as_output(), "")
+            return
+
+        opt_cmd = cmd_args(lto_opt)
+        if double_codegen_state == DoubleCodegenState("second_round"):
+            # For the second round, resume from the precodegen IR produced in the first round
+            opt_cmd.add("--input", bitcode_link_data.output_precodegen_ir)
+            opt_cmd.add("--codegen-only")
+        else:
+            # First round or disabled, there is nothing to resume from
+            if premerger_enabled:
+                if optimization_plan.merge_state == BitcodeMergeState("STANDALONE").value:
+                    opt_cmd.add("--input", input_object_file)
+                elif optimization_plan.merge_state == BitcodeMergeState("ROOT").value:
+                    opt_cmd.add("--input", merged_bc)
+                else:
+                    fail("Invalid merge state {} for bitcode file: {}".format(optimization_plan.merge_state, output_index_shard_file))
+            else:
+                opt_cmd.add("--input", input_object_file)
+
+        # Always provide the index regardless of round because codegen depends on information in the index
+        opt_cmd.add("--index", output_index_shard_file)
+
+        opt_cmd.add(cmd_args(hidden = common_opt_cmd))
+        opt_cmd.add("--shared-args", opt_argsfile)
+        opt_cmd.add("--compiler", cxx_toolchain.cxx_compiler_info.compiler)
+        if double_codegen_state == DoubleCodegenState("first_round"):
+            opt_cmd.add("--generate-cgdata")
+        elif double_codegen_state == DoubleCodegenState("second_round"):
+            opt_cmd.add("--read-cgdata", merged_cgdata)
+
+        # Second round has already completed importing, so the only bitcode file necessary is the one being optimized,
+        # inlined functions have already been embedded into the saved module in round 1
+        if double_codegen_state != DoubleCodegenState("second_round"):
+            imported_input_bitcode_files = [sorted_index_link_data[idx].link_data.input_object_file for idx in optimization_plan.imports]
+
+            if premerger_enabled:
+                imported_merged_input_bitcode_files = [sorted_index_link_data[idx].link_data.merged_bc for idx in optimization_plan.imports]
+                opt_cmd.add(cmd_args(hidden = imported_merged_input_bitcode_files))
+
+            opt_cmd.add(cmd_args(hidden = imported_input_bitcode_files))
+
+        projected_opt_cmd = cmd_args(ctx.actions.tset(IdentityTSet, value = opt_cmd).project_as_args("identity"))
+
+        if double_codegen_state == DoubleCodegenState("first_round"):
+            category_string = "thin_lto_opt_object_first_round"
+        elif double_codegen_state == DoubleCodegenState("second_round"):
+            category_string = "thin_lto_opt_object_second_round"
+        else:
+            category_string = "thin_lto_opt_object"
+
+        # We have to add outputs after wrapping the cmd_args in a projection
+        projected_opt_cmd.add("--out", outputs[output_native_object_file].as_output())
+
+        if double_codegen_state == DoubleCodegenState("first_round"):
+            projected_opt_cmd.add("--save-precodegen-ir", outputs[bitcode_link_data.output_precodegen_ir].as_output())
+
+        if link_options.extra_linker_outputs_flags_factory and (
+            double_codegen_state == DoubleCodegenState("disabled") or double_codegen_state == DoubleCodegenState("first_round")
+        ):
+            # Extra linker outputs are all produced during the first round (or only round if double codegen is disabled)
+            mapped_extra_outputs = {output_type: outputs[artifact] for output_type, artifact in bitcode_link_data.extra_outputs.items()}
+            extra_outputs_args = cmd_args(
+                link_options.extra_linker_outputs_flags_factory(
+                    ctx,
+                    mapped_extra_outputs,
+                    ExtraLinkerOutputCategory("produced-during-distributed-thin-lto-opt"),
+                ),
+            )
+            projected_opt_cmd.add("--", extra_outputs_args)
+
+        ctx.actions.run(projected_opt_cmd, category = make_cat(category_string), identifier = name)
+
+    def dynamic_optimize(bitcode_link_data, double_codegen_state: DoubleCodegenState, merged_cgdata: Artifact | None = None):
+        if double_codegen_state == DoubleCodegenState("first_round"):
+            optimize_object_outputs = [
+                bitcode_link_data.output_first_codegen_round_native_object_file.as_output(),
+                bitcode_link_data.output_precodegen_ir.as_output(),
+            ]
+
+            # Produce extra linker outputs in first round
+            optimize_object_outputs += [artifact.as_output() for artifact in bitcode_link_data.extra_outputs.values()]
+        elif double_codegen_state == DoubleCodegenState("second_round"):
+            # Only produce the final native object file in the second round
+            optimize_object_outputs = [bitcode_link_data.output_final_native_object_file.as_output()]
+        else:
+            # If there is only one around, produce everything in that round
+            optimize_object_outputs = [bitcode_link_data.output_final_native_object_file.as_output()]
+            optimize_object_outputs += [artifact.as_output() for artifact in bitcode_link_data.extra_outputs.values()]
+
+        ctx.actions.dynamic_output(
+            dynamic = [bitcode_link_data.plan],
+            inputs = [],
+            outputs = optimize_object_outputs,
+            f = lambda ctx, artifacts, outputs: optimize_object(
+                ctx,
+                artifacts,
+                outputs,
+                bitcode_link_data,
+                double_codegen_state = double_codegen_state,
+                merged_cgdata = merged_cgdata,
+            ),
+        )
+
+    for artifact in sorted_index_link_data:
+        if artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):
+            double_codegen_state = DoubleCodegenState("first_round") if double_codegen_enabled else DoubleCodegenState("disabled")
+            dynamic_optimize(artifact.link_data, double_codegen_state = double_codegen_state, merged_cgdata = None)
+
+    def merge_cgdata(ctx: AnalysisContext, artifacts, outputs, output_merged_cgdata_file):
+        merge_cmd = cmd_args(cxx_toolchain.llvm_cgdata)
+        merge_args = cmd_args("--merge")
+        for artifact in sorted_index_link_data:
+            if artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):
+                optimization_plan = ObjectFileOptimizationPlan(**artifacts[artifact.link_data.plan].read_json())
+                if (
+                    not optimization_plan.loaded_by_linker
+                    or not optimization_plan.is_bitcode
+                    or optimization_plan.merge_state == BitcodeMergeState("ABSORBED").value
+                ):
+                    continue
+
+                # Some targets have spaces in them, we wrap in single quotes to make sure they are treated as single files
+                merge_args.add(cmd_args(artifact.link_data.output_first_codegen_round_native_object_file, quote = "shell"))
+        merge_args.add("--output", outputs[output_merged_cgdata_file].as_output())
+        merge_cmd.add(
+            at_argfile(
+                actions = ctx.actions,
+                name = final_binary_out.basename + ".llvm-cgdata-argsfile",
+                args = merge_args,
+            )
+        )
+        ctx.actions.run(merge_cmd, category = make_cat("thin_lto_merge_cgdata"), identifier = link_options.identifier)
+
+    if double_codegen_enabled:
+        merged_cgdata_file = ctx.actions.declare_output(final_binary_out.basename + ".cgdata", has_content_based_path = uses_content_based_paths)
+        ctx.actions.dynamic_output(
+            dynamic = [
+                artifact.link_data.plan
+                for artifact in sorted_index_link_data
+                if artifact.data_type == LinkDataType("lazy_bitcode") or artifact.data_type == LinkDataType("eager_bitcode")
+            ],
+            inputs = [],
+            outputs = [merged_cgdata_file.as_output()],
+            f = lambda ctx, artifacts, outputs: merge_cgdata(
+                ctx,
+                artifacts,
+                outputs,
+                merged_cgdata_file,
+            ),
+        )
+
+        for artifact in sorted_index_link_data:
+            link_data = artifact.link_data
+            if artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):
+                dynamic_optimize(link_data, merged_cgdata = merged_cgdata_file, double_codegen_state = DoubleCodegenState("second_round"))
+
+    ctx.actions.symlinked_dir(outputs[external_debug_info_container_directory], debug_info_symlink_map)
+
+    # merge extra outputs produced by opt actions
+    def merge_extra_opt_outputs(ctx: AnalysisContext, artifacts, outputs, lto_outputs):
+        opt_outputs_to_merge = []
+        for artifact in sorted_index_link_data:
+            if artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):
+                optimization_plan = ObjectFileOptimizationPlan(**artifacts[artifact.link_data.plan].read_json())
+                if (
+                    not optimization_plan.loaded_by_linker
+                    or not optimization_plan.is_bitcode
+                    or optimization_plan.merge_state == BitcodeMergeState("ABSORBED").value
+                ):
+                    continue
+
+                opt_outputs_to_merge.append(artifact.link_data.extra_outputs)
+
+        mapped_lto_outputs = {output_type: outputs[artifact] for output_type, artifact in lto_outputs.items()}
+        link_options.extra_distributed_thin_lto_opt_outputs_merger(ctx, mapped_lto_outputs, opt_outputs_to_merge)
+
+    if link_options.extra_distributed_thin_lto_opt_outputs_merger:
+        if extra_lto_outputs:
+            mapped_lto_outputs = {output_type: outputs[artifact] for output_type, artifact in extra_lto_outputs.items()}
+            ctx.actions.dynamic_output(
+                dynamic = [
+                    artifact.link_data.plan
+                    for artifact in sorted_index_link_data
+                    if artifact.data_type == LinkDataType("lazy_bitcode") or artifact.data_type == LinkDataType("eager_bitcode")
+                ],
+                inputs = [],
+                outputs = [outputs[artifact].as_output() for artifact in extra_lto_outputs.values()],
+                f = lambda ctx, artifacts, outputs: merge_extra_opt_outputs(ctx, artifacts, outputs, mapped_lto_outputs),
+            )
+
+    def thin_lto_final_link(ctx: AnalysisContext, artifacts, outputs):
+        plan = artifacts[link_plan_out].read_json()
+        link_args = cmd_args()
+
+        # non_lto_objects are the ones that weren't compiled with thinlto
+        # flags. In that case, we need to link against the original object.
+        non_lto_objects = {int(k): 1 for k in plan["non_lto_objects"]}
+
+        object_file_linker_inputs = []
+
+        for idx, artifact in enumerate(sorted_index_link_data):
+            if artifact.data_type == LinkDataType("dynamic_library"):
+                append_linkable_args(link_args, artifact.link_data.linkable)
+            elif artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):
+                optimization_plan = ObjectFileOptimizationPlan(**artifacts[artifact.link_data.plan].read_json())
+
+                # Input bitcode files that were loaded in thin-link, but merged into another bitcode file
+                # will not have a native object file output, so we skip them here.
+                if optimization_plan.merge_state == BitcodeMergeState("ABSORBED").value:
+                    continue
+
+                # Same for object files that are not loaded, do not include them in native link.
+                if not optimization_plan.loaded_by_linker:
+                    continue
+
+                link_line_position = optimization_plan.final_link_line_position
+
+                if idx in non_lto_objects:
+                    object_file_linker_inputs.append((link_line_position, artifact.link_data.input_object_file))
+                else:
+                    object_file_linker_inputs.append((link_line_position, artifact.link_data.output_final_native_object_file))
+
+        link_cmd_parts = cxx_link_cmd_parts(cxx_toolchain, executable_link)
+        link_cmd = cmd_args(link_cmd_parts.linker)
+        link_args.add(common_link_flags)
+
+        if link_options.extra_linker_outputs_flags_factory != None:
+            # We need the inner artifacts here
+            mapped_outputs = {output_type: outputs[artifact] for output_type, artifact in extra_native_link_outputs.items()}
+            link_args.add(
+                link_options.extra_linker_outputs_flags_factory(
+                    ctx, mapped_outputs, ExtraLinkerOutputCategory("produced-during-distributed-thin-lto-native-link")
+                )
+            )
+
+        link_args.add("-o", outputs[final_binary_out].as_output())
+        if linker_map_out:
+            link_args.add(linker_map_args(cxx_toolchain, outputs[linker_map_out].as_output()).flags)
+        ordered_object_file_linker_inputs = sorted(object_file_linker_inputs, key = lambda x: x[0])
+        for _, artifact in ordered_object_file_linker_inputs:
+            link_args.add(artifact)
+        link_cmd.add(
+            at_argfile(
+                actions = ctx.actions,
+                name = outputs[linker_argsfile_out],
+                args = link_args,
+                allow_args = True,
+                has_content_based_path = uses_content_based_paths,
+            )
+        )
+        link_cmd.add(link_cmd_parts.post_linker_flags)
+
+        ctx.actions.run(link_cmd, category = make_cat("thin_lto_link"), identifier = link_options.identifier)
+
+    final_link_outputs = [outputs[final_binary_out].as_output(), outputs[linker_argsfile_out].as_output()]
+    if linker_map_out:
+        final_link_outputs.append(outputs[linker_map_out].as_output())
+
+    # Add outputs produced by native link only
+    final_link_outputs += [outputs[output_artifact].as_output() for output_artifact in extra_native_link_outputs.values()]
+
+    ctx.actions.dynamic_output(
+        dynamic = [link_plan_out]
+        + [
+            artifact.link_data.plan
+            for artifact in sorted_index_link_data
+            if artifact.data_type == LinkDataType("lazy_bitcode") or artifact.data_type == LinkDataType("eager_bitcode")
+        ],
+        inputs = [],
+        outputs = final_link_outputs,
+        f = thin_lto_final_link,
+    )
+
+PreparedArchiveArtitfacts = record(
+    manifest = field(Artifact),
+    extracted_object_files_dir = field(Artifact),
+)
+
+def generate_shared_library_interface(
+    ctx: AnalysisContext,
+    identifier: str,
+    executable_link: bool,
+    link_infos: list[LinkInfo],
+    output: Artifact,
+    sanitizer_runtime_args: list[ArgLike],
+    shared_library_interface_out: Artifact,
+):
+    # This flag generation logic must be at least semmantically equivalent to the logic used to create a thin-link invocation.
+    # Do not for example change the input order in one place, they must be kept in sync to generate an accurate interface.
+
+    common_linker_flags = _get_common_linker_flags(ctx, link_infos, executable_link, sanitizer_runtime_args)
+
+    eager_objects = cmd_args()
+    lazy_objects = cmd_args()
+    dynamic_libraries = cmd_args()
+
+    for link in link_infos:
+        for linkable in link.linkables:
+            if isinstance(linkable, ObjectsLinkable):
+                for obj in linkable.objects:
+                    eager_objects.add(obj)
+            elif isinstance(linkable, ArchiveLinkable) and linkable.archive.external_objects:
+                lazy_objects.add("-Wl,--start-lib")
+                for obj in linkable.archive.external_objects:
+                    lazy_objects.add(obj)
+                lazy_objects.add("-Wl,--end-lib")
+            elif isinstance(linkable, ArchiveLinkable):
+                # Thin link requires that we extract all archives beforehand via dynamic output so that we can declare various
+                # artifacts for each member. These artifacts are the link plan, the summary shard, the merged bitcode file etc.
+                # However, this linking invocation does not produce any of those, it only produces the shared library interface.
+                # Passing the archive directly instead of extracting it, then passing the members between --start-lib --end-lib
+                # flags should be semantically equivalent. Note however, that we only do this in this branch where we are dealing
+                # with some kind of pre-build static archive where Buck is not aware of the contents. If we built this static archive,
+                # just pass the members directly above, don't bother creating an archive for no reason.
+                lazy_objects.add(linkable.archive.artifact)
+            elif isinstance(linkable, SharedLibLinkable):
+                append_linkable_args(dynamic_libraries, linkable)
+            elif isinstance(linkable, FrameworksLinkable) or isinstance(linkable, SwiftmoduleLinkable):
+                # These linkables are handled separately for flag deduplication purposes, as in append_linkable_args:
+                # https://www.internalfb.com/code/fbsource/[c6d2c820b394]/fbcode/buck2/prelude/linking/link_info.bzl?lines=271-278
+                pass
+            else:
+                fail("Unhandled linkable type: {}".format(str(linkable)))
+
+    interface_generation_linker_args = cmd_args()
+    interface_generation_linker_args.add(common_linker_flags)
+    interface_generation_linker_args.add(eager_objects)
+    interface_generation_linker_args.add(lazy_objects)
+    interface_generation_linker_args.add(dynamic_libraries)
+    output_as_string = cmd_args(output, ignore_artifacts = True)
+    interface_generation_linker_args.add("-o", output_as_string)
+    interface_generation_linker_argsfile = ctx.actions.declare_output(
+        output.basename + ".shared_library_interface_generation_argsfile", has_content_based_path = False
+    )
+    interface_generation_linker_argsfile, _ = ctx.actions.write(
+        interface_generation_linker_argsfile,
+        interface_generation_linker_args,
+        with_inputs = True,
+        allow_args = True,
+    )
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    linker = cxx_link_cmd_parts(cxx_toolchain, executable_link).linker
+    interface_generation_linker_invocation = cmd_args(linker)
+    interface_generation_linker_invocation.add(cmd_args(interface_generation_linker_argsfile, format = "@{}"))
+
+    interface_generation_linker_invocation.add(
+        # @oss-disable[end= ]: get_shared_library_interface_generation_linker_flags(shared_library_interface_out),
+        cmd_args(),
+    )
+    ctx.actions.run(interface_generation_linker_invocation, category = "generate_shared_library_interface", identifier = identifier)
+
+def cxx_darwin_dist_link(
+    ctx: AnalysisContext,
+    # The destination for the link output.
+    output: Artifact,
+    opts: LinkOptions,
+    premerger_enabled: bool,
+    double_codegen_enabled: bool,
+    executable_link: bool,
+    sanitizer_runtime_args: CxxSanitizerRuntimeArguments,
+    shared_library_interface: Artifact | None,
+    linker_map: Artifact | None = None,
+) -> (LinkedObject, dict[str, list[DefaultInfo]]):
+    """
+    Perform a distributed thin-lto link into the supplied output
+
+    Distributed thinlto splits the link into three stages:
+    1. global "indexing" step
+    2. many individual compilation unit optimization steps
+    3. final global link step
+
+    The 2nd and 3rd of those are done just by constructing compiler/linker commands (in dynamic_output
+    sections) using the output of the first.
+
+    For the first, we need to post-process the linker index output to get it into a form
+    that is easy for us to consume from within bzl.
+    """
+
+    def make_cat(c: str) -> str:
+        """Used to make sure categories for our actions include the provided suffix"""
+        if opts.category_suffix != None:
+            return c + "_" + opts.category_suffix
+        return c
+
+    links = opts.links + opts.binary_links
+
+    link_infos = map_to_link_infos(links)
+
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    lto_prepare = cxx_toolchain.internal_tools.dist_lto.prepare[LinkerType("darwin")]
+
+    archive_manifests = []
+
+    prepare_cat = make_cat("thin_lto_prepare")
+
+    prepared_archive_artifacts = {}
+
+    uses_content_based_paths = get_uses_content_based_paths(ctx)
+
+    recorded_artifact_names = {}
+    for link in link_infos:
+        for linkable in link.linkables:
+            if isinstance(linkable, ArchiveLinkable) and not linkable.archive.external_objects:
+                link_name = link.name or "unknown"
+                archive_name_candidate = "{}-{}".format(link_name, linkable.archive.artifact.short_path)
+                # On case in-sensitive file systems, we need to make sure that, we normalize case before checking for duplicates
+                case_insensitive_archive_name_candidate = archive_name_candidate.lower()
+                if case_insensitive_archive_name_candidate in recorded_artifact_names:
+                    recorded_artifact_names[case_insensitive_archive_name_candidate] += 1
+                    archive_name = "{}-{}".format(archive_name_candidate, recorded_artifact_names[case_insensitive_archive_name_candidate])
+                else:
+                    recorded_artifact_names[case_insensitive_archive_name_candidate] = 1
+                    archive_name = archive_name_candidate
+
+                archive_manifest = ctx.actions.declare_output(
+                    "%s/%s/manifest.json" % (prepare_cat, archive_name), has_content_based_path = uses_content_based_paths
+                )
+                archive_objects = ctx.actions.declare_output(
+                    "%s/%s/objects" % (prepare_cat, archive_name), has_content_based_path = uses_content_based_paths, dir = True
+                )
+
+                prepare_args = cmd_args([
+                    lto_prepare,
+                    "--manifest-out",
+                    archive_manifest.as_output(),
+                    "--objects-out",
+                    archive_objects.as_output(),
+                    "--ar",
+                    cxx_toolchain.linker_info.archiver,
+                    "--archive",
+                    linkable.archive.artifact,
+                    "--name",
+                    archive_name,
+                    "--target-architecture",
+                    get_apple_architecture(ctx),
+                    "--lipo",
+                    cxx_toolchain.lipo,
+                ])
+                ctx.actions.run(prepare_args, category = make_cat("thin_lto_prepare"), identifier = archive_name)
+                prepared_archive_artifacts[linkable.archive.artifact] = PreparedArchiveArtitfacts(
+                    manifest = archive_manifest, extracted_object_files_dir = archive_objects
+                )
+                archive_manifests.append(archive_manifest)
+
+    linker_argsfile_out = ctx.actions.declare_output(output.basename + ".thinlto_link_argsfile", has_content_based_path = uses_content_based_paths)
+    index_argsfile_out = ctx.actions.declare_output(output.basename + ".thinlto_index_argsfile", has_content_based_path = uses_content_based_paths)
+
+    def prepare_opt_flags(link_infos: list[LinkInfo]) -> cmd_args:
+        opt_flags = cmd_args(cxx_toolchain.linker_info.dist_thin_lto_codegen_flags)
+        if cxx_toolchain.pass_plugin:
+            opt_flags.add(cmd_args(cxx_toolchain.pass_plugin, format = "-fpass-plugin={}"))
+        opt_flags.add(get_target_sdk_version_flags(ctx))
+        for link in link_infos:
+            opt_flags.add(link.dist_thin_lto_codegen_flags)
+        return opt_flags
+
+    common_opt_cmd = prepare_opt_flags(link_infos)
+
+    external_debug_info_container_directory = ctx.actions.declare_output(
+        output.basename + ".debug_info_dir", dir = True, has_content_based_path = uses_content_based_paths
+    )
+
+    extra_linker_outputs_factory = opts.extra_linker_outputs_factory
+    link_outputs = [output.as_output(), index_argsfile_out.as_output(), linker_argsfile_out.as_output(), external_debug_info_container_directory.as_output()]
+
+    lto_outputs = ExtraLinkerOutputs()
+    native_link_outputs = ExtraLinkerOutputs()
+    if extra_linker_outputs_factory:
+        lto_outputs = extra_linker_outputs_factory(ctx, ExtraLinkerOutputCategory("produced-during-distributed-thin-lto-opt"))
+        native_link_outputs = extra_linker_outputs_factory(ctx, ExtraLinkerOutputCategory("produced-during-distributed-thin-lto-native-link"))
+
+    link_outputs.extend([lto_output.as_output() for lto_output in lto_outputs.artifacts.values()])
+    link_outputs.extend([native_link_output.as_output() for native_link_output in native_link_outputs.artifacts.values()])
+
+    if linker_map:
+        link_outputs.append(linker_map.as_output())
+
+    if opts.produce_shared_library_interface:
+        generate_shared_library_interface(
+            ctx = ctx,
+            identifier = opts.identifier,
+            executable_link = executable_link,
+            link_infos = link_infos,
+            output = output,
+            sanitizer_runtime_args = sanitizer_runtime_args.extra_link_args,
+            shared_library_interface_out = shared_library_interface,
+        )
+
+    ctx.actions.dynamic_output(
+        dynamic = archive_manifests,
+        inputs = [],
+        outputs = link_outputs,
+        f = lambda ctx, artifacts, outputs: complete_distributed_link_with_expanded_archive_link_data(
+            ctx,
+            artifacts,
+            outputs,
+            common_opt_cmd = common_opt_cmd,
+            executable_link = executable_link,
+            external_debug_info_container_directory = external_debug_info_container_directory,
+            extra_lto_outputs = lto_outputs.artifacts,
+            extra_native_link_outputs = native_link_outputs.artifacts,
+            final_binary_out = output,
+            index_argsfile_out = index_argsfile_out,
+            link_infos = link_infos,
+            link_options = opts,
+            linker_argsfile_out = linker_argsfile_out,
+            linker_map_out = linker_map,
+            make_cat = make_cat,
+            premerger_enabled = premerger_enabled,
+            double_codegen_enabled = double_codegen_enabled,
+            prepared_archive_artifacts = prepared_archive_artifacts,
+            sanitizer_runtime_args = sanitizer_runtime_args,
+            uses_content_based_paths = uses_content_based_paths,
+        ),
+    )
+
+    final_output = output
+    unstripped_output = output
+    if opts.strip:
+        strip_args = opts.strip_args_factory(ctx) if opts.strip_args_factory else cmd_args()
+        final_output = strip_object(ctx, cxx_toolchain, final_output, strip_args, opts.category_suffix)
+
+    external_debug_info = make_artifact_tset(
+        actions = ctx.actions,
+        artifacts = [external_debug_info_container_directory],
+        label = ctx.label,
+        children = [unpack_external_debug_info(ctx.actions, link_args) for link_args in links],
+    )
+
+    return LinkedObject(
+        output = final_output,
+        unstripped_output = unstripped_output,
+        prebolt_output = output,
+        dwp = None,
+        external_debug_info = external_debug_info,
+        linker_argsfile = linker_argsfile_out,
+        linker_command = None,  # There is no notion of a single linker command for DistLTO
+        index_argsfile = index_argsfile_out,
+    ), (lto_outputs.providers | native_link_outputs.providers)
diff --git a/buck2/prelude/cxx/dist_lto/darwin/thin_link.bzl b/buck2/prelude/cxx/dist_lto/darwin/thin_link.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/darwin/thin_link.bzl
@@ -0,0 +1,108 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//linking:link_info.bzl",
+    "append_linkable_args",
+)
+load(":common_types.bzl", "DThinLTOLinkData", "LinkDataType")
+
+def thin_link(
+    ctx: AnalysisContext,
+    final_binary_out: Artifact,
+    sorted_index_link_data: list[DThinLTOLinkData],
+    common_link_flags: cmd_args,
+    linker: RunInfo,
+    lto_planner: RunInfo,
+    post_linker_flags: cmd_args,
+    index_argsfile_out: Artifact,
+    link_plan_out: Artifact,
+    identifier: str | None,
+    premerger_enabled: bool,
+    use_content_based_output_paths: bool,
+    make_cat,
+    make_id,
+):
+    # See comments in dist_lto_planner.py for semantics on the values that are pushed into index_meta.
+    index_meta_records = []
+
+    index_cat = make_cat("thin_lto_index")
+    index_file_out = ctx.actions.declare_output(make_id(index_cat) + "/index", has_content_based_path = use_content_based_output_paths)
+    index_out_dir = cmd_args(index_file_out.as_output(), parent = 1)
+
+    index_args = cmd_args(common_link_flags)
+    index_args.add(cmd_args(index_file_out.as_output(), format = "-Wl,--thinlto-index-only={}"))
+    index_args.add("-Wl,--thinlto-emit-imports-files")
+    index_args.add("-Wl,--thinlto-full-index")
+
+    # By default the linker will write artifacts (import files and sharded indices) next to input bitcode files with
+    # a different suffix. This can be problematic if you are running two distributed links on the same machine at the # same time consuming the same input bitcode files. That is the links would overwrite each other's artifacts. This
+    # flag allows you to write all these artifacts into a unique directory per link to avoid this problem.
+    index_args.add(cmd_args(index_out_dir, format = "-Wl,--thinlto-prefix-replace=;{}/"))
+
+    # buildifier: disable=uninitialized
+    for idx, artifact in enumerate(sorted_index_link_data):
+        link_data = artifact.link_data
+
+        if artifact.data_type == LinkDataType("eager_bitcode") or artifact.data_type == LinkDataType("lazy_bitcode"):
+            if artifact.data_type == LinkDataType("lazy_bitcode") and link_data.archive_start:
+                index_args.add("-Wl,--start-lib")
+
+            index_args.add(link_data.input_object_file)
+
+            if artifact.data_type == LinkDataType("lazy_bitcode") and link_data.archive_end:
+                index_args.add("-Wl,--end-lib")
+
+            object_file_record = {
+                "input_object_file_path": link_data.input_object_file,
+                "output_index_shard_file_path": link_data.output_index_shard_file.as_output(),
+                "output_plan_file_path": link_data.plan.as_output(),
+                "starlark_array_index": idx,
+            }
+            if premerger_enabled:
+                object_file_record["output_premerged_bitcode_file_path"] = link_data.merged_bc.as_output()
+
+            index_meta_records.append(object_file_record)
+
+        elif artifact.data_type == LinkDataType("dynamic_library"):
+            append_linkable_args(index_args, link_data.linkable)
+
+        else:
+            fail("Unhandled data type: {}".format(str(artifact.data_type)))
+
+    output_as_string = cmd_args(final_binary_out, ignore_artifacts = True)
+    index_args.add("-o", output_as_string)
+    index_args.add(post_linker_flags)
+    index_cmd = cmd_args(linker)
+    index_argfile, _ = ctx.actions.write(
+        index_argsfile_out.as_output(),
+        index_args,
+        allow_args = True,
+    )
+    index_cmd.add(cmd_args(index_argfile, format = "@{}"))
+
+    index_meta_file = ctx.actions.write_json(
+        final_binary_out.basename + ".thinlto.meta.json",
+        index_meta_records,
+        with_inputs = True,
+        has_content_based_path = use_content_based_output_paths,
+    )
+
+    plan_cmd = cmd_args([lto_planner, "--meta", index_meta_file, "--index", index_out_dir, "--link-plan", link_plan_out.as_output()])
+    if premerger_enabled:
+        plan_cmd.add("--enable-premerger")
+    plan_cmd.add("--", index_cmd)
+
+    plan_cmd.add(
+        cmd_args(
+            hidden = [
+                index_args,
+            ]
+        )
+    )
+    ctx.actions.run(plan_cmd, category = index_cat, identifier = identifier)
diff --git a/buck2/prelude/cxx/dist_lto/darwin/thin_link_record_defs.bzl b/buck2/prelude/cxx/dist_lto/darwin/thin_link_record_defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/darwin/thin_link_record_defs.bzl
@@ -0,0 +1,24 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# These records are documented in the dist_lto_planner_darwin.py script and must be kept in sync with those definitions
+
+BitcodeMergeState = enum(
+    "STANDALONE",
+    "ABSORBED",
+    "ROOT",
+    "NOT_LOADED",
+)
+
+ObjectFileOptimizationPlan = record(
+    imports = field(list[int]),
+    is_bitcode = field(bool),
+    merge_state = field(str | None, None),  # BitcodeMergeState
+    loaded_by_linker = field(bool),
+    final_link_line_position = field(int),
+)
diff --git a/buck2/prelude/cxx/dist_lto/dist_lto.bzl b/buck2/prelude/cxx/dist_lto/dist_lto.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/dist_lto.bzl
@@ -0,0 +1,909 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "make_artifact_tset",
+    "project_artifacts",
+)
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//cxx:cxx_bolt.bzl",
+    "PRE_BOLT_SUFFIX",
+    "bolt",
+    "cxx_use_bolt",
+)
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_link_utility.bzl",
+    "cxx_link_cmd_parts",
+    "gc_sections_args",
+    "linker_map_args",
+)
+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerType")
+load("@prelude//cxx:debug.bzl", "SplitDebugMode")
+load(
+    "@prelude//cxx:dwp.bzl",
+    "run_dwp_action",
+)
+load("@prelude//cxx:link_types.bzl", "LinkOptions", "get_dwp_execution_preference")
+load("@prelude//linking:execution_preference.bzl", "get_action_execution_attributes")
+load(
+    "@prelude//linking:link_info.bzl",
+    "ArchiveLinkable",
+    "FrameworksLinkable",
+    "LinkInfo",
+    "LinkedObject",
+    "ObjectsLinkable",
+    "SharedLibLinkable",  # @unused Used as a type
+    "SwiftmoduleLinkable",
+    "append_linkable_args",
+    "map_to_link_infos",
+    "serialize_linkable_for_thinlto",
+    "unpack_external_debug_info",
+    "unpack_link_args",
+)
+load("@prelude//linking:stamp_build_info.bzl", "cxx_stamp_build_info", "stamp_build_info")
+load("@prelude//linking:strip.bzl", "strip_object")
+load("@prelude//utils:lazy.bzl", "lazy")
+
+# `_BitcodeLinkData` holds data
+# that needs to be tracked across ThinLTO phases for Bitcode (LLVM IR) files.
+# Bitcode is produced from Phase 1 (compile).
+# Tracking data is held to orchestrate between
+# Phase 2 (Thin Link) and Phase 3 (ThinLTO Backends).
+# Phase 2 (Thin Link) writes a plan for Phase 3 (ThinLTO Backends).
+# The plan contains which other bitcode files are needed to perform
+# Phase 3.
+_BitcodeLinkData = record(
+    # `id` is the number that will be used to refer back to this record across the ThinLTO phases.
+    id = int,
+    name = str,
+    initial_object = Artifact,
+    bc_file = Artifact,
+    plan = Artifact,
+    opt_object = Artifact,
+    external_debug_info = Artifact | None,
+)
+
+# `_ArchiveLinkData` holds data
+# that needs to be tracked across ThinLTO phases for Archive (.a) files that contain Bitcode/LLVM IR files.
+# See `_BitcodeLinkData` for how this data is used across the Phases.
+# `_ArchiveLinkData` is unarchived and tracking for that is held here.
+_ArchiveLinkData = record(
+    # `id` is the number that will be used to refer back to this record across the ThinLTO phases.
+    id = int,
+    name = str,
+    manifest = Artifact,
+    # A file containing paths to artifacts that are known to reside in opt_objects_dir.
+    opt_manifest = Artifact,
+    objects_dir = Artifact,
+    opt_objects_dir = Artifact,
+    indexes_dir = Artifact,
+    plan = Artifact,
+    link_whole = bool,
+    prepend = bool,
+    # Directory for .dwo files when split_debug_mode is "split".
+    dwo_dir = Artifact | None,
+)
+
+_DataType = enum(
+    "bitcode",
+    "archive",
+    "cmd_args",
+)
+
+# `_LinkDataVariant` is a discriminated union
+# that holds the arguments that is feed into the linker and
+# tracked throughout the ThinLTO phases.
+_LinkDataVariant = record(
+    # discriminant/tag field to determine what type of LinkData this is.
+    data_type = _DataType,
+    # The link_data field has the following invariant:
+    # - `list[_BitcodeLinkData]` when data_type is `_DataType("bitcode")`
+    # - `_ArchiveLinkData` when data_type is `_DataType("archive")`
+    # - `None` when data_type is `_DataType("cmd_args")`
+    link_data = list[_BitcodeLinkData] | _ArchiveLinkData | None,
+    # The linkable that this is derived from.
+    # This field is used to get the `cmd_args` form.
+    # FrameworksLinkable / SwiftmoduleLinkable are skipped before a variant is
+    # built, so they never appear here.
+    origin = ArchiveLinkable | SharedLibLinkable | ObjectsLinkable,
+)
+
+# `_ThinLinkInfo` groups together pre/post flags and a list of LinkData.
+_ThinLinkInfo = record(
+    pre_flags = list,
+    post_flags = list,
+    link_data_variants = list[_LinkDataVariant],
+)
+
+def cxx_gnu_dist_link(
+    ctx: AnalysisContext,
+    # The destination for the link output.
+    output: Artifact,
+    opts: LinkOptions,
+    linker_map: Artifact | None = None,
+    gc_sections_output: Artifact | None = None,
+    # This action will only happen if split_dwarf is enabled via the toolchain.
+    dwp_tool_available: bool = True,
+    executable_link: bool = True,
+    build_info_json: Artifact | None = None,
+) -> LinkedObject:
+    """
+    Perform a distributed thin-lto link into the supplied output
+
+    Distributed thinlto splits the link into three stages:
+    1. global "indexing" step
+    2. many individual compilation unit optimization steps
+    3. final global link step
+
+    The 2nd and 3rd of those are done just by constructing compiler/linker commands (in dynamic_output
+    sections) using the output of the first.
+
+    For the first, we need to post-process the linker index output to get it into a form
+    that is easy for us to consume from within bzl.
+    """
+
+    links = opts.links
+    binary_links = opts.binary_links
+
+    # A category suffix that will be added to the category of the link action that is generated.
+    category_suffix = opts.category_suffix
+
+    # An identifier that will uniquely name this link action in the context of a category. Useful for
+    # differentiating multiple link actions in the same rule.
+    identifier = opts.identifier
+
+    # Names derived from the identifier below become artifact paths, and callers
+    # pass identifiers containing spaces and brackets.
+    normalized_identifier = identifier.replace("[", "_").replace("]", "_").replace(" ", "_") if identifier != None else None
+
+    enable_late_build_info_stamping = executable_link and cxx_stamp_build_info(ctx)
+
+    # Unlike the plain link, a `None` (no preference) narrows to `False` here,
+    # because this also feeds `bolt` and `strip_object`, which take a plain bool.
+    enable_cache_upload = opts.allow_cache_upload or enable_late_build_info_stamping
+
+    link_action_execution_properties = get_action_execution_attributes(opts.link_execution_preference)
+    dwp_action_execution_properties = get_action_execution_attributes(get_dwp_execution_preference(opts))
+    enable_bolt = executable_link and cxx_use_bolt(ctx)
+
+    def make_cat(c: str) -> str:
+        """Used to make sure categories for our actions include the provided suffix"""
+        if category_suffix != None:
+            return c + "_" + category_suffix
+        return c
+
+    def make_id(i: str) -> str:
+        """Used to make sure identifiers for our actions include the provided identifier"""
+        if normalized_identifier != None:
+            return normalized_identifier + "_" + i
+        return i
+
+    recorded_outputs = {}
+
+    def name_for_obj(link_name: str, object_artifact: Artifact) -> str:
+        """Creates a unique name/path we can use for a particular object file input"""
+        prefix = "{}/{}".format(link_name, object_artifact.short_path)
+
+        # it's possible (though unlikely) that we can get duplicate name/short_path, so just uniquify them
+        if prefix in recorded_outputs:
+            recorded_outputs[prefix] += 1
+            extra = recorded_outputs[prefix]
+            prefix = "{}-{}".format(prefix, extra)
+        else:
+            recorded_outputs[prefix] = 1
+        return prefix
+
+    names = {}
+
+    def name_for_link(info: LinkInfo) -> str:
+        """Creates a unique name for a LinkInfo that we are consuming"""
+        name = info.name or "unknown"
+        if name not in names:
+            names[name] = 1
+        else:
+            names[name] += 1
+            name += "-{}".format(names[name])
+        return make_id(name)
+
+    link_infos = map_to_link_infos(links)
+
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    lto_planner = cxx_toolchain.internal_tools.dist_lto.planner[LinkerType("gnu")]
+    lto_opt = cxx_toolchain.internal_tools.dist_lto.opt[LinkerType("gnu")]
+    lto_prepare = cxx_toolchain.internal_tools.dist_lto.prepare[LinkerType("gnu")]
+    lto_copy = cxx_toolchain.internal_tools.dist_lto.copy
+    split_debug_mode = cxx_toolchain.split_debug_mode
+
+    PREPEND_ARCHIVE_NAMES = [
+        # T130644072: If linked with `--whole-archive`, Clang builtins must be at the
+        # front of the argument list to avoid conflicts with identically-named Rust
+        # symbols from the `compiler_builtins` crate.
+        #
+        # Once linking of C++ binaries starts to use `rlib`s, this may no longer be
+        # necessary, because our Rust `rlib`s won't need to contain copies of
+        # `compiler_builtins` to begin with, unlike our Rust `.a`s which presently do
+        # (T130789782).
+        "clang_rt.builtins",
+    ]
+
+    # `link_data_repository` is a bridge between the outputs of `dynamic_plan` (Phase 2 Thin Link)
+    # and the inputs into `dynamic_optimize` and `dynamic_optimize_archive` (Phase 3 ThinLTO Backends).
+    # Note: The index into `link_data_repository` is important as it's how things will appear in
+    # the plans produced by indexing. That allows us to map those indexes back to
+    # the actual artifacts.
+    link_data_repository = []  # type: list[_BitcodeLinkData | _ArchiveLinkData]
+
+    # thin_link_infos contains __ALL__ the arguments used in the Phase 2 Thin link step.
+    # It contains LLVM IR bitcode files, machine object files, shared objects, linker flags, etc.
+    thin_link_infos = []  # type: list[_ThinLinkInfo]
+
+    # Information used to construct the dynamic plan:
+    plan_inputs = []  # type: list[Artifact]
+    plan_outputs = []  # type: list[OutputArtifact]
+
+    # Information used to construct the opt dynamic outputs:
+    archive_opt_manifests = []  # type: list[Artifact]
+
+    prepare_cat = make_cat("thin_lto_prepare")
+
+    # The `for` loop below reads each `LinkInfo` and transforms it into a `_ThinLinkInfo`.
+    # `_ThinLinkInfo` will carry the additional structures used through out the multiple phases of ThinLTO.
+    for link in link_infos:
+        link_name = name_for_link(link)
+
+        link_data_variants = []  # type: list[_LinkDataVariant]
+        for linkable in link.linkables:
+            if isinstance(linkable, ObjectsLinkable):
+                data_type = _DataType("bitcode")
+                link_data = []  # type: list[_BitcodeLinkData]
+
+                for obj in linkable.objects:
+                    name = name_for_obj(link_name, obj)
+                    bc_output = ctx.actions.declare_output(name + ".thinlto.bc", has_content_based_path = False)
+                    plan_output = ctx.actions.declare_output(name + ".opt.plan", has_content_based_path = False)
+                    opt_output = ctx.actions.declare_output(name + ".opt.o", has_content_based_path = False)
+                    external_debug_info = None
+                    if split_debug_mode == SplitDebugMode("split"):
+                        external_debug_info = ctx.actions.declare_output(name + ".opt.dwo", has_content_based_path = False)
+                    elif split_debug_mode == SplitDebugMode("single"):
+                        external_debug_info = opt_output
+
+                    bitcode_link_data = _BitcodeLinkData(
+                        id = len(link_data_repository),
+                        name = name,
+                        initial_object = obj,
+                        bc_file = bc_output,
+                        plan = plan_output,
+                        opt_object = opt_output,
+                        external_debug_info = external_debug_info,
+                    )
+                    link_data_repository.append(bitcode_link_data)
+                    link_data.append(bitcode_link_data)
+                    plan_outputs.extend([bc_output.as_output(), plan_output.as_output()])
+            elif isinstance(linkable, ArchiveLinkable) and linkable.supports_lto:
+                data_type = _DataType("archive")
+                # Our implementation of Distributed ThinLTO operates on individual objects, not archives. Since these
+                # archives might still contain LTO-able bitcode, we first extract the objects within the archive into
+                # another directory and write a "manifest" containing the list of objects that the archive contained.
+                #
+                # Later actions in the LTO compilation pipeline will read this manifest and dynamically dispatch
+                # actions on the objects that the manifest reports.
+
+                name = name_for_obj(link_name, linkable.archive.artifact)
+                archive_manifest = ctx.actions.declare_output("%s/%s/manifest.json" % (prepare_cat, name), has_content_based_path = False)
+                archive_objects = ctx.actions.declare_output("%s/%s/objects" % (prepare_cat, name), dir = True, has_content_based_path = False)
+                archive_opt_objects = ctx.actions.declare_output("%s/%s/opt_objects" % (prepare_cat, name), dir = True, has_content_based_path = False)
+                archive_indexes = ctx.actions.declare_output("%s/%s/indexes" % (prepare_cat, name), dir = True, has_content_based_path = False)
+                archive_plan = ctx.actions.declare_output("%s/%s/plan.json" % (prepare_cat, name), has_content_based_path = False)
+                archive_opt_manifest = ctx.actions.declare_output("%s/%s/opt_objects.manifest" % (prepare_cat, name), has_content_based_path = False)
+                archive_dwo_dir = None
+                if split_debug_mode == SplitDebugMode("split"):
+                    archive_dwo_dir = ctx.actions.declare_output("%s/%s/dwo" % (prepare_cat, name), dir = True, has_content_based_path = False)
+                prepare_args = cmd_args([
+                    lto_prepare,
+                    "--manifest-out",
+                    archive_manifest.as_output(),
+                    "--objects-out",
+                    archive_objects.as_output(),
+                    "--ar",
+                    cxx_toolchain.linker_info.archiver,
+                    "--archive",
+                    linkable.archive.artifact,
+                    "--name",
+                    name,
+                ])
+                ctx.actions.run(prepare_args, category = make_cat("thin_lto_prepare"), identifier = name)
+
+                link_data = _ArchiveLinkData(
+                    id = len(link_data_repository),
+                    name = name,
+                    manifest = archive_manifest,
+                    opt_manifest = archive_opt_manifest,
+                    objects_dir = archive_objects,
+                    opt_objects_dir = archive_opt_objects,
+                    indexes_dir = archive_indexes,
+                    plan = archive_plan,
+                    link_whole = linkable.link_whole,
+                    prepend = link_name in PREPEND_ARCHIVE_NAMES,
+                    dwo_dir = archive_dwo_dir,
+                )
+                link_data_repository.append(link_data)
+                archive_opt_manifests.append(archive_opt_manifest)
+                plan_inputs.extend([archive_manifest, archive_objects])
+                plan_outputs.extend([archive_indexes.as_output(), archive_plan.as_output()])
+            elif isinstance(linkable, FrameworksLinkable) or isinstance(linkable, SwiftmoduleLinkable):
+                # These add no linker inputs on GNU: append_linkable_args no-ops them
+                # and serialize_linkable_for_thinlto rejects them, so there is nothing
+                # to emit here (the Darwin planner skips them likewise). Use `continue`,
+                # not `pass`: link_data_variants is appended below the if/elif/else, so
+                # falling through would emit a variant from the previous linkable.
+                continue
+            else:
+                data_type = _DataType("cmd_args")
+                link_data = None
+
+            link_data_variants.append(
+                _LinkDataVariant(
+                    data_type = data_type,
+                    link_data = link_data,
+                    origin = linkable,
+                )
+            )
+
+        thin_link_infos.append(
+            _ThinLinkInfo(
+                pre_flags = link.pre_flags,
+                post_flags = link.post_flags,
+                link_data_variants = link_data_variants,
+            )
+        )
+
+    index_argsfile_out = ctx.actions.declare_output(output.short_path + ".thinlto_index_argsfile", has_content_based_path = False)
+    final_link_index = ctx.actions.declare_output(output.short_path + ".final_link_index", has_content_based_path = False)
+
+    def dynamic_plan(
+        link_plan: Artifact,
+        index_argsfile_out: Artifact,
+        final_link_index: Artifact,
+    ) -> None:
+        def plan(ctx: AnalysisContext, artifacts, outputs):
+            # index link command args
+            prepend_index_args = cmd_args()
+            index_args = cmd_args()
+
+            # index_meta is the comprehensive source-of-truth for Phase 2 Thin Link.
+            # It holds the record of all the flags, linkable files, and their associated data.
+            # See comments in dist_lto_planner.py for semantics on the values that are pushed into index_meta.
+            index_meta = []
+
+            # buildifier: disable=uninitialized
+            for thin_link_info in thin_link_infos:
+                metadata_entry = {
+                    "linkables": [],
+                    "post_flags": thin_link_info.post_flags,
+                    "pre_flags": thin_link_info.pre_flags,
+                }
+                index_meta.append(metadata_entry)
+
+                if thin_link_info.pre_flags:
+                    index_args.add(thin_link_info.pre_flags)
+
+                for link_data_variant in thin_link_info.link_data_variants:
+                    if link_data_variant.data_type == _DataType("bitcode"):
+                        append_linkable_args(index_args, link_data_variant.origin)
+
+                        for link_data in link_data_variant.link_data:
+                            metadata_linkable = {
+                                "idx": link_data.id,
+                                "output": outputs[link_data.bc_file].as_output(),
+                                "path": link_data.initial_object,
+                                "plan_output": outputs[link_data.plan].as_output(),
+                                "type": "bitcode",
+                            }
+                            metadata_entry["linkables"].append(metadata_linkable)
+
+                    elif link_data_variant.data_type == _DataType("archive"):
+                        link_data = link_data_variant.link_data
+                        manifest = artifacts[link_data.manifest].read_json()
+
+                        metadata_linkable = {
+                            "archive_idx": link_data.id,
+                            "archive_index_dir": outputs[link_data.indexes_dir].as_output(),
+                            "archive_name": link_data.name,
+                            # `opt_objects_dir` is produced downstream of this plan, so it
+                            # can only be passed as a path: `ignore_artifacts` keeps it out
+                            # of the meta file's inputs, and `delimiter` makes it serialize
+                            # as a string rather than a single-element list.
+                            "archive_opt_objects_dir": cmd_args(link_data.opt_objects_dir, delimiter = "", ignore_artifacts = True),
+                            "archive_plan": outputs[link_data.plan].as_output(),
+                            "objects": [] if manifest["objects"] else None,
+                            "prepend": link_data.prepend,
+                            "type": "archive",
+                        }
+                        metadata_entry["linkables"].append(metadata_linkable)
+
+                        if not manifest["objects"]:
+                            # Despite not having any objects (and thus not needing a plan), we still need to bind the plan output.
+                            ctx.actions.write(outputs[link_data.plan].as_output(), "{}")
+                            cmd = cmd_args(["/bin/sh", "-c", "mkdir", "-p", outputs[link_data.indexes_dir].as_output()])
+                            ctx.actions.run(cmd, category = make_cat("thin_lto_mkdir"), identifier = link_data.name)
+                            continue
+
+                        archive_args = prepend_index_args if link_data.prepend else index_args
+
+                        archive_args.add(cmd_args(hidden = link_data.objects_dir))
+
+                        if not link_data.link_whole:
+                            archive_args.add("-Wl,--start-lib")
+
+                        for obj in manifest["objects"]:
+                            metadata_linkable["objects"].append({
+                                "idx": link_data.id,
+                                "output": "",
+                                "path": obj,
+                                "plan_output": "",
+                            })
+                            archive_args.add(obj)
+
+                        if not link_data.link_whole:
+                            archive_args.add("-Wl,--end-lib")
+                    elif link_data_variant.data_type == _DataType("cmd_args"):
+                        linkable_args = cmd_args()
+                        append_linkable_args(linkable_args, link_data_variant.origin)
+                        index_args.add(linkable_args)
+
+                        metadata_linkable = {
+                            "cmd_args": linkable_args,
+                            "object": serialize_linkable_for_thinlto(link_data_variant.origin),
+                            "type": "cmd_args",
+                        }
+                        metadata_entry["linkables"].append(metadata_linkable)
+                    else:
+                        fail("Unknown data type:", link_data_variant)
+
+                if thin_link_info.post_flags:
+                    index_args.add(thin_link_info.post_flags)
+
+            prepend_index_args.add(index_args)
+            index_argfile, _ = ctx.actions.write(
+                outputs[index_argsfile_out].as_output(),
+                prepend_index_args,
+                allow_args = True,
+            )
+
+            index_cat = make_cat("thin_lto_index")
+            index_file_out = ctx.actions.declare_output(make_id(index_cat) + "/index", has_content_based_path = False)
+            index_out_dir = cmd_args(index_file_out.as_output(), parent = 1)
+
+            index_cmd_parts = cxx_link_cmd_parts(cxx_toolchain, executable_link)
+
+            index_cmd = index_cmd_parts.link_cmd
+            index_cmd.add(cmd_args(index_argfile, format = "@{}", hidden = prepend_index_args))
+
+            # Binary-only link flags (e.g. --wrap) must be present at the index
+            # step so symbol resolution matches the final link. They are
+            # intentionally omitted from the per-object opt actions so those
+            # actions stay identical across links and can be deduplicated.
+            for link in binary_links:
+                index_cmd.add(unpack_link_args(link))
+
+            output_as_string = cmd_args(output, ignore_artifacts = True)
+            index_cmd.add("-o", output_as_string)
+            index_cmd.add(cmd_args(index_file_out.as_output(), format = "-Wl,--thinlto-index-only={}"))
+            index_cmd.add("-Wl,--thinlto-emit-imports-files")
+            index_cmd.add("-Wl,--thinlto-full-index")
+            index_cmd.add(cmd_args(index_out_dir, format = "-Wl,--thinlto-prefix-replace=;{}/"))
+            index_cmd.add(index_cmd_parts.post_linker_flags)
+
+            index_meta_file = ctx.actions.write_json(
+                output.short_path + ".thinlto.meta.json",
+                index_meta,
+                with_inputs = True,
+                has_content_based_path = False,
+            )
+
+            plan_cmd = cmd_args(
+                [
+                    lto_planner,
+                    "--meta",
+                    index_meta_file,
+                    "--index",
+                    index_out_dir,
+                    "--link-plan",
+                    outputs[link_plan].as_output(),
+                    "--final-link-index",
+                    outputs[final_link_index].as_output(),
+                    "--",
+                ],
+            )
+            plan_cmd.add(index_cmd)
+
+            ctx.actions.run(
+                plan_cmd,
+                category = index_cat,
+                identifier = identifier,
+                prefer_local = link_action_execution_properties.prefer_local,
+                prefer_remote = link_action_execution_properties.prefer_remote,
+                local_only = link_action_execution_properties.local_only,
+                weight = opts.link_weight,
+                force_full_hybrid_if_capable = link_action_execution_properties.full_hybrid,
+            )
+
+        # TODO(T117513091) - dynamic_output does not allow for an empty list of dynamic inputs. If we have no archives
+        # to process, we will have no dynamic inputs, and the plan action can be non-dynamic.
+        #
+        # However, buck2 disallows `dynamic_output` with a empty input list. We also can't call our `plan` function
+        # directly, since it uses `ctx.outputs` to bind its outputs. Instead of doing Starlark hacks to work around
+        # the lack of `ctx.outputs`, we declare an empty file as a dynamic input.
+        plan_inputs.append(ctx.actions.write(output.short_path + ".plan_hack.txt", "", has_content_based_path = False))
+        plan_outputs.extend([
+            link_plan.as_output(),
+            index_argsfile_out.as_output(),
+            final_link_index.as_output(),
+        ])
+        ctx.actions.dynamic_output(dynamic = plan_inputs, inputs = [], outputs = plan_outputs, f = plan)
+
+    link_plan_out = ctx.actions.declare_output(output.short_path + ".link-plan.json", has_content_based_path = False)
+    dynamic_plan(
+        link_plan = link_plan_out,
+        index_argsfile_out = index_argsfile_out,
+        final_link_index = final_link_index,
+    )
+
+    def prepare_opt_flags(link_infos: list[LinkInfo]) -> cmd_args:
+        opt_cmd_parts = cxx_link_cmd_parts(cxx_toolchain, executable_link)
+        opt_args = opt_cmd_parts.link_cmd
+
+        if cxx_toolchain.linker_info.dist_thin_lto_codegen_flags != None:
+            opt_args.add(cxx_toolchain.linker_info.dist_thin_lto_codegen_flags)
+
+        # buildifier: disable=uninitialized
+        for link in link_infos:
+            for raw_flag in link.pre_flags + link.post_flags:
+                opt_args.add(raw_flag)
+            opt_args.add(link.dist_thin_lto_codegen_flags)
+
+        opt_args.add(opt_cmd_parts.post_linker_flags)
+        return opt_args
+
+    opt_common_flags = prepare_opt_flags(link_infos)
+
+    # Create an argsfile and dump all the flags to be processed later by lto_opt.
+    # These flags are common to all opt actions, we don't need an argfile for each action, one
+    # for the entire link unit will do.
+    opt_argsfile = ctx.actions.declare_output(output.short_path + ".lto_opt_argsfile", has_content_based_path = False)
+    ctx.actions.write(opt_argsfile.as_output(), opt_common_flags, allow_args = True)
+
+    # We declare a separate dynamic_output for every object file. It would
+    # maybe be simpler to have a single dynamic_output that produced all the
+    # opt actions, but an action needs to re-run whenever the analysis that
+    # produced it re-runs. And so, with a single dynamic_output, we'd need to
+    # re-run all actions when any of the plans changed.
+    def dynamic_optimize(name: str, initial_object: Artifact, bc_file: Artifact, plan: Artifact, opt_object: Artifact, external_debug_info: Artifact | None):
+        def optimize_object(ctx: AnalysisContext, artifacts, outputs):
+            plan_json = artifacts[plan].read_json()
+
+            # If the object was not compiled with thinlto flags, then there
+            # won't be valid outputs for it from the indexing, but we still
+            # need to bind the artifact.
+            if not plan_json["is_bc"]:
+                ctx.actions.write(outputs[opt_object], "")
+                if external_debug_info != None and external_debug_info != opt_object:
+                    ctx.actions.write(outputs[external_debug_info], "")
+                return
+
+            opt_cmd = cmd_args(lto_opt)
+            opt_cmd.add("--out", outputs[opt_object].as_output())
+            opt_cmd.add("--input", initial_object)
+            opt_cmd.add("--index", bc_file)
+
+            # When invoking opt and llc via clang, clang will not respect IR metadata to generate
+            # dwo files unless -gsplit-dwarf is explicitly passed in. In other words, even if
+            # 'splitDebugFilename' set in IR 'DICompileUnit', we still need to force clang to tell
+            # llc to generate dwo sections.
+            #
+            # Local thinlto generates .dwo files by default. For distributed thinlto, however, we
+            # want to keep all dwo debug info in the object file to reduce the number of files to
+            # materialize.
+            if split_debug_mode == SplitDebugMode("none"):
+                opt_cmd.add("--split-dwarf=none")
+            elif split_debug_mode == SplitDebugMode("single"):
+                opt_cmd.add("--split-dwarf=single")
+            elif split_debug_mode == SplitDebugMode("split"):
+                opt_cmd.add("--split-dwarf=split")
+                opt_cmd.add("--dwo", outputs[external_debug_info].as_output())
+
+            opt_cmd.add(cmd_args(hidden = opt_common_flags))
+            opt_cmd.add("--args", opt_argsfile)
+
+            opt_cmd.add("--")
+            opt_cmd.add(cxx_toolchain.cxx_compiler_info.compiler)
+
+            imports = [link_data_repository[idx].initial_object for idx in plan_json["imports"]]
+            archives = [link_data_repository[idx].objects_dir for idx in plan_json["archive_imports"]]
+            opt_cmd.add(cmd_args(hidden = imports + archives))
+            ctx.actions.run(opt_cmd, category = make_cat("thin_lto_opt_object"), identifier = name)
+
+        outputs = [opt_object.as_output()]
+        if external_debug_info != None:
+            outputs.append(external_debug_info.as_output())
+        ctx.actions.dynamic_output(dynamic = [plan], inputs = [], outputs = outputs, f = optimize_object)
+
+    def dynamic_optimize_archive(archive: _ArchiveLinkData):
+        def optimize_archive(ctx: AnalysisContext, artifacts, outputs):
+            plan_json = artifacts[archive.plan].read_json()
+            if "objects" not in plan_json or not plan_json["objects"] or lazy.is_all(lambda e: not e["is_bc"], plan_json["objects"]):
+                # Nothing in this directory was lto-able; let's just copy the archive.
+                # `opt_objects_dir` is the only dir of an lto-able archive that the final
+                # link materializes, and it must hold every member at the member's path
+                # relative to the archive's base dir -- the layout the per-member branch
+                # below builds, and the one the planner derives final-link paths from.
+                ctx.actions.copied_dir(outputs[archive.opt_objects_dir], {"objects": archive.objects_dir})
+                ctx.actions.write(outputs[archive.opt_manifest], "")
+                if archive.dwo_dir != None:
+                    ctx.actions.symlinked_dir(outputs[archive.dwo_dir], {})
+                return
+
+            output_dir = {}
+            output_manifest = cmd_args()
+            dwo_dir = {}
+            for entry in plan_json["objects"]:
+                base_dir = plan_json["base_dir"]
+                source_path = paths.relativize(entry["path"], base_dir)
+                if not entry["is_bc"]:
+                    opt_object = ctx.actions.declare_output("%s/%s" % (make_cat("thin_lto_opt_copy"), source_path), has_content_based_path = False)
+                    output_manifest.add(opt_object)
+                    copy_cmd = cmd_args(
+                        [
+                            lto_copy,
+                            "--to",
+                            opt_object.as_output(),
+                            "--from",
+                            entry["path"],
+                        ],
+                        hidden = archive.objects_dir,
+                    )
+                    ctx.actions.run(copy_cmd, category = make_cat("thin_lto_opt_copy"), identifier = source_path)
+                    output_dir[source_path] = opt_object
+                    continue
+
+                opt_object = ctx.actions.declare_output("%s/%s" % (make_cat("thin_lto_opt_archive"), source_path), has_content_based_path = False)
+                output_manifest.add(opt_object)
+                output_dir[source_path] = opt_object
+
+                opt_cmd = cmd_args(lto_opt)
+                opt_cmd.add("--out", opt_object.as_output())
+                opt_cmd.add("--input", entry["path"])
+                opt_cmd.add("--index", entry["bitcode_file"])
+
+                if split_debug_mode == SplitDebugMode("none"):
+                    opt_cmd.add("--split-dwarf=none")
+                elif split_debug_mode == SplitDebugMode("single"):
+                    opt_cmd.add("--split-dwarf=single")
+                elif split_debug_mode == SplitDebugMode("split"):
+                    opt_cmd.add("--split-dwarf=split")
+                    dwo_path = source_path.removesuffix(".o") + ".dwo"
+                    dwo_output = ctx.actions.declare_output("%s/%s" % (make_cat("thin_lto_opt_archive"), dwo_path), has_content_based_path = False)
+                    dwo_dir[dwo_path] = dwo_output
+                    opt_cmd.add("--dwo", dwo_output.as_output())
+
+                opt_cmd.add(cmd_args(hidden = opt_common_flags))
+                opt_cmd.add("--args", opt_argsfile)
+
+                opt_cmd.add("--")
+                opt_cmd.add(cxx_toolchain.cxx_compiler_info.compiler)
+
+                imports = [link_data_repository[idx].initial_object for idx in entry["imports"]]
+                archives = [link_data_repository[idx].objects_dir for idx in entry["archive_imports"]]
+                opt_cmd.add(
+                    cmd_args(
+                        hidden = imports + archives + [archive.indexes_dir, archive.objects_dir],
+                    )
+                )
+                ctx.actions.run(opt_cmd, category = make_cat("thin_lto_opt_archive"), identifier = source_path)
+
+            ctx.actions.symlinked_dir(outputs[archive.opt_objects_dir], output_dir)
+            ctx.actions.write(outputs[archive.opt_manifest], output_manifest, allow_args = True)
+            if archive.dwo_dir != None:
+                ctx.actions.symlinked_dir(outputs[archive.dwo_dir], dwo_dir)
+
+        archive_opt_inputs = [archive.plan]
+        archive_opt_outputs = [archive.opt_objects_dir.as_output(), archive.opt_manifest.as_output()]
+        if archive.dwo_dir != None:
+            archive_opt_outputs.append(archive.dwo_dir.as_output())
+        ctx.actions.dynamic_output(dynamic = archive_opt_inputs, inputs = [], outputs = archive_opt_outputs, f = optimize_archive)
+
+    objects_external_debug_info = []
+    for link_data in link_data_repository:
+        if isinstance(link_data, _BitcodeLinkData):
+            external_debug_info = link_data.external_debug_info
+            dynamic_optimize(
+                name = link_data.name,
+                initial_object = link_data.initial_object,
+                bc_file = link_data.bc_file,
+                plan = link_data.plan,
+                opt_object = link_data.opt_object,
+                external_debug_info = link_data.external_debug_info,
+            )
+
+            if external_debug_info != None:
+                objects_external_debug_info.append(external_debug_info)
+        elif isinstance(link_data, _ArchiveLinkData):
+            dynamic_optimize_archive(link_data)
+
+            # For split mode, add the dwo directory to external_debug_info.
+            # For single mode, the debug info is embedded in the opt_objects.
+            if split_debug_mode == SplitDebugMode("split") and link_data.dwo_dir != None:
+                objects_external_debug_info.append(link_data.dwo_dir)
+            elif split_debug_mode == SplitDebugMode("single"):
+                objects_external_debug_info.append(link_data.opt_objects_dir)
+
+    def thin_lto_final_link(ctx: AnalysisContext, artifacts, outputs):
+        plan = artifacts[link_plan_out].read_json()
+        plan_index = {int(k): v for k, v in plan["index"].items()}
+
+        # non_lto_objects are the ones that weren't compiled with thinlto
+        # flags. In that case, we need to link against the original object.
+        non_lto_objects = {int(k): 1 for k in plan["non_lto_objects"]}
+        current_index = 0
+        link_cmd_hidden = cmd_args()
+        for link in link_infos:
+            for linkable in link.linkables:
+                if isinstance(linkable, ObjectsLinkable):
+                    for obj in linkable.objects:
+                        if current_index in plan_index:
+                            link_cmd_hidden.add(link_data_repository[current_index].opt_object)
+                        elif current_index in non_lto_objects:
+                            link_cmd_hidden.add(obj)
+                        current_index += 1
+                elif isinstance(linkable, ArchiveLinkable) and linkable.supports_lto:
+                    current_index += 1
+                else:
+                    append_linkable_args(link_cmd_hidden, linkable)
+
+            # pre/post flags may reference artifacts (e.g. linker scripts via
+            # `-Wl,--script=path`).
+            link_cmd_hidden.add(link.pre_flags)
+            link_cmd_hidden.add(link.post_flags)
+
+        link_cmd_parts = cxx_link_cmd_parts(cxx_toolchain, executable_link)
+        link_cmd = link_cmd_parts.link_cmd
+
+        # buildifier: disable=uninitialized
+        for link_data in link_data_repository:
+            if isinstance(link_data, _ArchiveLinkData):
+                link_cmd_hidden.add(link_data.opt_objects_dir)
+
+        link_cmd.add(cmd_args(final_link_index, format = "@{}", hidden = link_cmd_hidden))
+        for link in binary_links:
+            link_cmd.add(unpack_link_args(link))
+        link_cmd.add("-o", outputs[output].as_output())
+        if linker_map:
+            link_cmd.add(linker_map_args(cxx_toolchain, outputs[linker_map].as_output()).flags)
+        if gc_sections_output:
+            link_cmd.add(gc_sections_args(cxx_toolchain, outputs[gc_sections_output].as_output()).flags)
+        link_cmd.add(link_cmd_parts.post_linker_flags)
+
+        ctx.actions.run(
+            link_cmd,
+            category = make_cat("thin_lto_link"),
+            identifier = identifier,
+            prefer_local = link_action_execution_properties.prefer_local,
+            prefer_remote = link_action_execution_properties.prefer_remote,
+            local_only = link_action_execution_properties.local_only,
+            weight = opts.link_weight,
+            force_full_hybrid_if_capable = link_action_execution_properties.full_hybrid,
+            allow_cache_upload = enable_cache_upload,
+        )
+
+    final_link_inputs = [link_plan_out, final_link_index] + archive_opt_manifests
+    ctx.actions.dynamic_output(
+        dynamic = final_link_inputs,
+        inputs = [],
+        outputs = [output.as_output()] + ([linker_map.as_output()] if linker_map else []) + ([gc_sections_output.as_output()] if gc_sections_output else []),
+        f = thin_lto_final_link,
+    )
+
+    external_debug_info = make_artifact_tset(
+        label = ctx.label,
+        actions = ctx.actions,
+        artifacts = objects_external_debug_info,
+        children = [unpack_external_debug_info(ctx.actions, link_args) for link_args in links],
+    )
+
+    if enable_bolt:
+        bolt_output = bolt(ctx, output, external_debug_info, identifier, dwp_tool_available, allow_cache_upload = enable_cache_upload)
+        final_output = bolt_output.output
+        split_debug_output = bolt_output.dwo_output
+    else:
+        final_output = output
+        split_debug_output = None
+
+    if dwp_tool_available:
+        dwp_output = ctx.actions.declare_output(output.short_path.removesuffix(PRE_BOLT_SUFFIX) + ".dwp", has_content_based_path = False)
+
+        def dynamic_run_dwp_action(ctx: AnalysisContext, artifacts, outputs):
+            plan = artifacts[link_plan_out].read_json()
+            plan_index = {int(k): v for k, v in plan["index"].items()}
+            non_lto_objects = {int(k): 1 for k in plan["non_lto_objects"]}
+
+            referenced_objects = list(final_link_inputs)
+
+            # Include hidden dependencies for the final link.
+            for idx, link_data in enumerate(link_data_repository):
+                if isinstance(link_data, _BitcodeLinkData):
+                    if idx in plan_index:
+                        referenced_objects.append(link_data.opt_object)
+                    elif idx in non_lto_objects:
+                        referenced_objects.append(link_data.initial_object)
+                elif isinstance(link_data, _ArchiveLinkData):
+                    referenced_objects.append(link_data.opt_objects_dir)
+                    if link_data.dwo_dir != None:
+                        referenced_objects.append(link_data.dwo_dir)
+                else:
+                    fail("Unexpected link_data type", link_data)
+
+            if split_debug_output:
+                referenced_objects += [split_debug_output]
+            else:
+                referenced_objects += project_artifacts(ctx.actions, external_debug_info)
+
+            run_dwp_action(
+                ctx = ctx,
+                toolchain = cxx_toolchain,
+                obj = final_output,
+                identifier = identifier,
+                category_suffix = category_suffix,
+                referenced_objects = referenced_objects,
+                dwp_output = outputs[dwp_output],
+                # Mirror the link action's execution preference so dwp runs
+                # alongside the link (avoids round-tripping dwo files when link
+                # is local) -- unless the caller asked for dwp to be scheduled
+                # separately, e.g. because the link is only local for
+                # build-info stamping.
+                action_execution_properties = dwp_action_execution_properties,
+            )
+
+        ctx.actions.dynamic_output(
+            dynamic = [link_plan_out],
+            inputs = [],
+            outputs = [dwp_output.as_output()],
+            f = dynamic_run_dwp_action,
+        )
+    else:
+        dwp_output = None
+
+    unstripped_output = final_output
+    if opts.strip:
+        strip_args = opts.strip_args_factory(ctx) if opts.strip_args_factory else cmd_args()
+        final_output = strip_object(ctx, cxx_toolchain, final_output, strip_args, category_suffix, allow_cache_upload = enable_cache_upload)
+
+    final_output = (
+        stamp_build_info(
+            ctx,
+            final_output,
+            links = opts.links,
+            build_info_json = build_info_json,
+        )
+        if executable_link
+        else final_output
+    )
+
+    return LinkedObject(
+        output = final_output,
+        unstripped_output = unstripped_output,
+        prebolt_output = output,
+        dwp = dwp_output,
+        external_debug_info = external_debug_info,
+        linker_argsfile = final_link_index,
+        linker_command = None,  # There is no notion of a single linker command for DistLTO
+        index_argsfile = index_argsfile_out,
+    )
diff --git a/buck2/prelude/cxx/dist_lto/tools.bzl b/buck2/prelude/cxx/dist_lto/tools.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools.bzl
@@ -0,0 +1,55 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "DistLtoToolsInfo", "LinkerType")
+
+def _impl(ctx):
+    return [
+        DefaultInfo(),
+        DistLtoToolsInfo(
+            compiler_stats_merger = ctx.attrs.compiler_stats_merger[RunInfo],
+            planner = {LinkerType(linker_type): planner[RunInfo] for linker_type, planner in ctx.attrs.planner.items()},
+            opt = {LinkerType(linker_type): opt[RunInfo] for linker_type, opt in ctx.attrs.opt.items()},
+            prepare = {LinkerType(linker_type): prepare[RunInfo] for linker_type, prepare in ctx.attrs.prepare.items()},
+            copy = ctx.attrs.copy[RunInfo],
+            archive_mapper = ctx.attrs.archive_mapper[RunInfo],
+        ),
+    ]
+
+dist_lto_tools = rule(
+    impl = _impl,
+    attrs = {
+        "archive_mapper": attrs.dep(providers = [RunInfo], default = "prelude//cxx/dist_lto/tools:dist_lto_archive_mapper"),
+        "compiler_stats_merger": attrs.dep(providers = [RunInfo], default = "prelude//cxx/dist_lto/tools:dist_lto_compiler_stats_merger"),
+        "copy": attrs.dep(providers = [RunInfo], default = "prelude//cxx/dist_lto/tools:dist_lto_copy"),
+        "opt": attrs.dict(
+            key = attrs.enum(LinkerType.values()),
+            value = attrs.dep(providers = [RunInfo]),
+            default = {
+                "darwin": "prelude//cxx/dist_lto/tools:dist_lto_opt_darwin",
+                "gnu": "prelude//cxx/dist_lto/tools:dist_lto_opt_gnu",
+            },
+        ),
+        "planner": attrs.dict(
+            key = attrs.enum(LinkerType.values()),
+            value = attrs.dep(providers = [RunInfo]),
+            default = {
+                "darwin": "prelude//cxx/dist_lto/tools:dist_lto_planner_darwin",
+                "gnu": "prelude//cxx/dist_lto/tools:dist_lto_planner_gnu",
+            },
+        ),
+        "prepare": attrs.dict(
+            key = attrs.enum(LinkerType.values()),
+            value = attrs.dep(providers = [RunInfo]),
+            default = {
+                "darwin": "prelude//cxx/dist_lto/tools:dist_lto_prepare_darwin",
+                "gnu": "prelude//cxx/dist_lto/tools:dist_lto_prepare_gnu",
+            },
+        ),
+    },
+)
diff --git a/buck2/prelude/cxx/dist_lto/tools/BUCK b/buck2/prelude/cxx/dist_lto/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/BUCK
@@ -0,0 +1,75 @@
+load("@prelude//cxx/dist_lto:tools.bzl", "dist_lto_tools")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "dist_lto_planner_gnu",
+    main = "dist_lto_planner_gnu.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "dist_lto_planner_darwin",
+    main = "dist_lto_planner_darwin.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "dist_lto_opt_gnu",
+    main = "dist_lto_opt_gnu.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "dist_lto_opt_darwin",
+    main = "dist_lto_opt_darwin.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "dist_lto_prepare_gnu",
+    main = "dist_lto_prepare_gnu.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "dist_lto_prepare_darwin",
+    main = "dist_lto_prepare_darwin.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "dist_lto_copy",
+    main = "dist_lto_copy.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "dist_lto_archive_mapper",
+    main = "dist_lto_archive_mapper.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "dist_lto_compiler_stats_merger",
+    main = "dist_lto_compiler_stats_merger.py",
+    visibility = ["PUBLIC"],
+)
+
+dist_lto_tools(
+    name = "dist_lto_tools",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_test(
+    name = "test_dist_lto_opt",
+    srcs = [
+        "dist_lto_opt_gnu.py",
+        "tests/test_dist_lto_opt.py",
+    ],
+)
diff --git a/buck2/prelude/cxx/dist_lto/tools/__init__.py b/buck2/prelude/cxx/dist_lto/tools/__init__.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/__init__.py
diff --git a/buck2/prelude/cxx/dist_lto/tools/dist_lto_archive_mapper.py b/buck2/prelude/cxx/dist_lto/tools/dist_lto_archive_mapper.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/dist_lto_archive_mapper.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+This script is used to transform an opaque directory Buck artifact filled with
+files into a number of Buck artifacts that can each be operated on individually.
+
+This script is used to take a directory filled with object files created
+through dynamic_output and a list of name, output destination path pairs.
+For each such pair, we look for a file in the directory matching the name,
+and copy it to the destination path.
+
+This allows buck to declare and operate on each file individually, rather than
+the entire opaque directory.
+"""
+
+import argparse
+import pathlib
+import shutil
+import sys
+
+EXIT_SUCCESS = 0
+
+
+def main(argv: list[str]) -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--objects_dir")
+    parser.add_argument("--object_to_map", nargs=2, action="append")
+    args = parser.parse_args(argv[1:])
+
+    copy_map = {}
+    for object_mapping in args.object_to_map:
+        directory_member_name = object_mapping[0]
+        dest = object_mapping[1]
+        copy_map[directory_member_name] = pathlib.Path(dest)
+
+    directory_to_map = pathlib.Path(args.objects_dir)
+    for file in directory_to_map.iterdir():
+        if file.name in copy_map:
+            shutil.copy(file, copy_map[file.name])
+        else:
+            raise Exception("Object mapping is missing a file.")
+
+    return EXIT_SUCCESS
+
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv))
diff --git a/buck2/prelude/cxx/dist_lto/tools/dist_lto_compiler_stats_merger.py b/buck2/prelude/cxx/dist_lto/tools/dist_lto_compiler_stats_merger.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/dist_lto_compiler_stats_merger.py
@@ -0,0 +1,47 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import json
+import sys
+
+"""
+A helper script designed to merge multiple JSON files storing LLVM stats produced by -stats -stats-json -info-out-file=. All stats are summed together, to form a new JSON file.
+"""
+
+
+def main(argv: list[str]) -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--input-stats-filelist",
+        help="A filelist of JSON static files produced by LLVM's -stats -stats-json",
+    )
+    parser.add_argument(
+        "--output-stats-file", help="A path to write the merged JSON static file to."
+    )
+    args = parser.parse_args(argv[1:])
+    merged_stats: dict[int, str] = {}
+    with open(args.input_stats_filelist) as stats_filelist:
+        for stats_file in stats_filelist:
+            with open(stats_file.strip()) as f:
+                stats = json.load(f)
+                for key, value in stats.items():
+                    if key in merged_stats:
+                        merged_stats[key] += value
+                    else:
+                        merged_stats[key] = value
+
+    with open(args.output_stats_file, "w") as f:
+        json.dump(merged_stats, f, sort_keys=True, indent=4)
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv))
diff --git a/buck2/prelude/cxx/dist_lto/tools/dist_lto_copy.py b/buck2/prelude/cxx/dist_lto/tools/dist_lto_copy.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/dist_lto_copy.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import shutil
+import sys
+from typing import List
+
+
+def main(argv: List[str]) -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--to")
+    parser.add_argument("--from", dest="from_")
+    args = parser.parse_args(argv[1:])
+    shutil.copy(args.from_, args.to)
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv))
diff --git a/buck2/prelude/cxx/dist_lto/tools/dist_lto_opt_darwin.py b/buck2/prelude/cxx/dist_lto/tools/dist_lto_opt_darwin.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/dist_lto_opt_darwin.py
@@ -0,0 +1,124 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Python wrapper around Clang intended to optimize and codegen bitcode files
+to native object files for distributed thin lto targeting darwin. This script
+exists to work around Clang bugs where Clang will fail silently.
+"""
+
+import argparse
+import os
+import subprocess
+import sys
+import traceback
+from typing import List
+
+EXIT_SUCCESS, EXIT_FAILURE = 0, 1
+
+
+def main(argv: List[str]) -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--out", help="The output native object file.", required=True)
+    parser.add_argument("--input", help="The input bitcode object file.", required=True)
+    parser.add_argument("--index", help="The thinlto index file.", required=True)
+    parser.add_argument(
+        "--compiler", help="The path to the Clang compiler binary.", required=True
+    )
+    parser.add_argument(
+        "--shared-args",
+        help="The argsfile containing unfiltered and unprocessed flags, common to all opt actions in this link.",
+        required=True,
+    )
+    parser.add_argument(
+        "--extra-outputs-args",
+        help="The argsfile containing unfiltered and unprocessed flags, specifying extra outputs produced by this opt action.",
+    )
+    parser.add_argument(
+        "--print-command",
+        action="store_true",
+        help="Print the clang invocation and exit.",
+    )
+    parser.add_argument(
+        "--generate-cgdata",
+        help="Save cgdata to special section in produced object file",
+        action="store_true",
+    )
+    parser.add_argument("--read-cgdata", help="Read cgdata from the provided file")
+    parser.add_argument(
+        "--save-precodegen-ir",
+        help="Save optimized pre-codegen IR to the specified path",
+    )
+    parser.add_argument(
+        "--codegen-only",
+        action="store_true",
+        help="Skip IR optimization passes (input is already optimized pre-codegen IR)",
+    )
+    parser.add_argument("additional_opt_args", nargs=argparse.REMAINDER)
+    args = parser.parse_args(argv[1:])
+
+    clang_invocation = [
+        args.compiler,
+        f"@{args.shared_args}",
+        "-o",
+        args.out,
+        "-x",
+        "ir",  # Without this the input file type is incorrectly inferred.
+        "-c",
+        args.input,
+        # When lto_mode=thin/full all compile actions are passed `-flto=thin/full`. We
+        # want to generate a native object file here.
+        "-fno-lto",
+        "-Werror=unused-command-line-argument",
+        f"-fthinlto-index={args.index}",
+    ]
+
+    if args.codegen_only:
+        clang_invocation.append("-fthinlto-codegen-only")
+
+    if args.save_precodegen_ir:
+        clang_invocation.append(f"-save-precodegen-ir={args.save_precodegen_ir}")
+
+    clang_invocation += args.additional_opt_args[1:]
+
+    if args.generate_cgdata:
+        clang_invocation.extend(["-mllvm", "-codegen-data-generate"])
+
+    if args.read_cgdata:
+        clang_invocation.append(f"-fcodegen-data-use={args.read_cgdata}")
+
+    if args.print_command:
+        print(" ".join(clang_invocation))
+        return EXIT_SUCCESS
+
+    result = subprocess.run(
+        clang_invocation,
+        capture_output=True,
+        text=True,
+    )
+    if result.returncode:
+        print(result.stderr, file=sys.stderr)
+        return result.returncode
+
+    # Work around Clang bug where it fails silently: T187767815
+    if os.stat(args.out).st_size == 0:
+        print("error: clang produced empty file", file=sys.stderr)
+        return EXIT_FAILURE
+    if args.save_precodegen_ir and os.stat(args.save_precodegen_ir).st_size == 0:
+        print("error: clang produced empty precodegen IR file", file=sys.stderr)
+        return EXIT_FAILURE
+    return EXIT_SUCCESS
+
+
+if __name__ == "__main__":
+    try:
+        sys.exit(main(sys.argv))
+    except subprocess.CalledProcessError as e:
+        traceback.print_exc()
+        sys.exit(e.returncode)
diff --git a/buck2/prelude/cxx/dist_lto/tools/dist_lto_opt_gnu.py b/buck2/prelude/cxx/dist_lto/tools/dist_lto_opt_gnu.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/dist_lto_opt_gnu.py
@@ -0,0 +1,323 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Python wrapper around `clang` intended for use by the parallel opt phase of
+a Distributed ThinLTO compilation. This script works around a LLVM bug where
+LLVM will return a zero exit code in the case where ThinLTO fails with a
+fatal error.
+
+Instead of trusting the exit code of the compiler, this script checks the
+output file and returns 1 if the file has zero size.
+"""
+
+import argparse
+import os
+import subprocess
+import sys
+import traceback
+from typing import List
+
+EXIT_SUCCESS, EXIT_FAILURE = 0, 1
+
+
+# Filter opt related flags
+def _filter_flags(clang_flags: List[str]) -> List[str]:  # noqa: C901
+    # List of llvm flags to be ignored.
+    # They either don't have an valid mapping or unused during opt.
+    IGNORE_OPT_FLAGS = [
+        "-Wl,-plugin-opt,-function-sections",
+        "-Wl,--lto-whole-program-visibility",
+        "-Wl,--no-lto-whole-program-visibility",
+        "-flto=thin",
+    ]
+    # Conservatively, we only translate llvms flags in our known list
+    KNOWN_LLVM_SHARED_LIBRARY_FLAGS = ["-pie", "-shared"]
+
+    # Start with default flags for opt.
+    # The default values may change across compiler versions.
+    # Make sure they are always synced with the current values.
+    opt_flags = [
+        # TODO(T139459294):
+        # -O2 is the default optimization flag for the link-time optimizer
+        # this setting matches current llvm implementation:
+        # https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/LTO/Config.h#L57
+        "-O2",
+        "-ffunction-sections",
+        "-fdata-sections",
+    ]
+
+    # Clang driver passes through lld flags with "-Wl," prefix. There are 4 type of flags with unique
+    # prefixes:
+    # 1. "--lto-...": these are native lld flags.
+    # 2. "-plugin-opt,..." or "-plugin-opt=...": these are the aliases of the native lld flags (1).
+    # 3. "-mllvm,...": these are llvm flags.
+    # 4. "-plugin-opt,-..." or "-plugin-opt=-...": these are the aliases of llvm flags (3). Note that they differ from (2) and always start with "-".
+    #
+    # For (1) and (2), we need to convert them case by case.
+    # For (3) and (4), we should be able to pass them through into the optimizer directly by prefixing "-mllvm".
+    # TODO(T139448744): Cover all the flags. Check available flags using "ld.lld --help | grep -A 1 '\-\-plugin-opt='"
+    PLUGIN_OPT_PREFIXES = ["-Wl,-plugin-opt,", "-Wl,-plugin-opt="]
+
+    def _find_plugin_opt_prefix(flag: str) -> str:
+        matched_prefix = [
+            prefix for prefix in PLUGIN_OPT_PREFIXES if flag.startswith(prefix)
+        ]
+        if matched_prefix:
+            return matched_prefix[0]
+        return ""
+
+    plugin_opt_to_llvm_flag_map = {
+        "sample-profile=": "-fprofile-sample-use=",
+        "O": "-O",
+    }
+
+    def _plugin_opt_to_clang_flag(flag: str) -> str:
+        for k, v in plugin_opt_to_llvm_flag_map.items():
+            if flag.startswith(k):
+                return flag.replace(k, v)
+        return None
+
+    index = 0
+    while index < len(clang_flags):
+        raw_flag = clang_flags[index]
+        flag = raw_flag.replace('"', "")
+        if flag in IGNORE_OPT_FLAGS:
+            index += 1
+            continue
+        if _find_plugin_opt_prefix(flag):
+            # Convert "-Wl,-plugin-opt,...".
+            flag = flag.replace(_find_plugin_opt_prefix(flag), "", 1)
+            if flag.startswith("-"):
+                # If flag starts with "-", it is an llvm flag. Pass it through directly.
+                opt_flags.extend(["-mllvm", flag])
+            else:
+                flag = _plugin_opt_to_clang_flag(flag)
+                if flag is None:
+                    # Bail on any unknown flag.
+                    print(f"error: unrecognized flag {raw_flag}")
+                    return None
+                opt_flags.append(flag)
+        elif flag.startswith("-Wl,-mllvm,"):
+            # Convert "-Wl,-mllvm,...". It is an llvm flag. Pass it through directly.
+            flag = flag.replace("-Wl,-mllvm,", "", 1)
+            opt_flags.extend(["-mllvm", flag])
+        elif flag in KNOWN_LLVM_SHARED_LIBRARY_FLAGS:
+            # The target is a shared library, `-fPIC` is needed in opt phase to correctly generate PIC ELF.
+            opt_flags.append("-fPIC")
+        elif flag.startswith("-f"):
+            # Always pass in -f flags which are presumed to be Clang flags.
+            opt_flags.append(flag)
+        elif flag == "-Xlinker":
+            # Handle -Xlinker -xxxx flags. -Xlinker flags are passed in two
+            # lines, the first line being just "-Xlinker" and the second line
+            # being the actual arg.
+            if index + 1 >= len(clang_flags):
+                print(
+                    f"error: cannot handle -Xlinker flags {clang_flags}, "
+                    "-Xlinker should be followed by an option"
+                )
+                return EXIT_FAILURE
+            if clang_flags[index + 1] == "-mllvm":
+                # Validate -Xlinker
+                #          -mllvm
+                #          -Xlinker
+                #          -xxxx    structure
+                # This assumes -mllvm and its arg are provided consecutively,
+                # mostly to handle the case where they come from Buck's
+                # linker_flags.
+                # TODO(T159109840): Generalize this logic to handle -Xlinker
+                #       -mllvm -unrelated-flag -Xlinker -actual-mllvm-arg
+                if (
+                    index + 2 >= len(clang_flags)
+                    or index + 3 >= len(clang_flags)
+                    or clang_flags[index + 2] != "-Xlinker"
+                ):
+                    print(
+                        f"error: cannot handle -Xlinker flags {clang_flags}, "
+                        "-mllvm should be followed by an llvm option"
+                    )
+                    return EXIT_FAILURE
+                opt_flags.extend(["-mllvm", clang_flags[index + 3]])
+                index += 3
+            else:
+                # Otherwise skip this -Xlinker flag and its arg
+                index += 1
+        index += 1
+    return opt_flags
+
+
+# Clean up clang flags by obtaining the cc1 flags and filtering out those unwanted.
+# clang_opt_flags is mutated after calling this function.
+def _cleanup_flags(clang_opt_flags: List[str]) -> List[str]:
+    for i, arg in enumerate(clang_opt_flags):
+        if arg.startswith("--cc="):
+            # Find the clang binary path.
+            clang_opt_flags[i] = arg.replace("--cc=", "")
+        if arg.startswith("--log-fbcc"):
+            # Remove the log-fbcc flag since the compiler is called directly below.
+            clang_opt_flags.pop(i)
+
+    # Get the cc1 flag dump with '-###'
+    try:
+        output = (
+            subprocess.check_output(
+                clang_opt_flags + ["-###"], stderr=subprocess.STDOUT
+            )
+            .decode()
+            .splitlines()
+        )
+    except subprocess.CalledProcessError as e:
+        print(e.output.decode())
+        return None
+
+    # Flags that may conflict with the existing bitcode attributes.
+    # The value indicates if the flag is followed with a value.
+    flags_to_delete = {
+        "-mframe-pointer=none": False,
+        "-fmath-errno": False,
+        "-fno-rounding-math": False,
+        "-mconstructor-aliases": False,
+        "-munwind-tables": False,
+        "-target-cpu": True,
+        "-tune-cpu": True,
+    }
+
+    clean_output = []
+    skip_next = False
+    for f in output[-1].split()[1:]:
+        if skip_next:
+            skip_next = False
+        else:
+            f = f.strip('"')
+            if f in flags_to_delete:
+                skip_next = flags_to_delete[f]
+            else:
+                clean_output.append(f)
+    return clean_output
+
+
+# Flags that fbcc consumes and does NOT pass through to the compiler.
+# See fbcode/tools/build/buck/wrappers/fbcc.py for the full list.
+_FBCC_CONSUMED_PREFIXES = (
+    "--log-fbcc",
+    "--fbcc-create-external-debug-info=",
+    "--show-flags",
+)
+
+
+def _fbcc_prefix_end(opt_args: List[str]) -> int:
+    """Return the slice end for the fbcc prefix within opt_args.
+
+    opt_args layout:
+        ['--', <fbcc>, '--cc=<compiler>', <optional fbcc-consumed args>, ...]
+
+    Only args that fbcc *consumes* (strips before invoking the compiler)
+    belong in the prefix.  Pass-through args like ``--target=`` must be
+    excluded: they are already folded into cc1 flags by ``_cleanup_flags``
+    and including them in ``fbcc_cmd`` would place them before ``-cc1``,
+    which prevents clang from entering cc1 mode.
+    """
+    end = 3  # ['--', fbcc, '--cc=...']
+    while end < len(opt_args) and any(
+        opt_args[end].startswith(p) for p in _FBCC_CONSUMED_PREFIXES
+    ):
+        end += 1
+    return end
+
+
+def main(argv: List[str]) -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--out", help="The output native object file.")
+    parser.add_argument("--input", help="The input bitcode object file.")
+    parser.add_argument("--index", help="The thinlto index file.")
+    parser.add_argument("--split-dwarf", help="Split dwarf option.", default="none")
+    parser.add_argument("--dwo", help="Split-dwarf .dwo file to be created.")
+    parser.add_argument(
+        "--args", help="The argsfile containing unfiltered and unprocessed flags."
+    )
+    parser.add_argument("--debug", action="store_true", help="Dump clang -cc1 flags.")
+    parser.add_argument("opt_args", nargs=argparse.REMAINDER)
+    args = parser.parse_args(argv[1:])
+    split_dwarf: str = args.split_dwarf
+    dwo: str | None = args.dwo
+
+    with open(args.args, "r") as argsfile:
+        clang_opt_flags = _filter_flags(argsfile.read().splitlines())
+    if clang_opt_flags is None:
+        return EXIT_FAILURE
+
+    clang_opt_flags.extend(
+        [
+            "-o",
+            args.out,
+            "-x",
+            "ir",
+            "-c",
+            args.input,
+            f"-fthinlto-index={args.index}",
+        ]
+    )
+    if split_dwarf == "none":
+        assert dwo is None
+        clang_opt_flags.append("-gno-split-dwarf")
+    else:
+        # Note that -gsplit-dwarf=single does not create a .dwo file.
+        assert (dwo is not None) == (split_dwarf == "split")
+        clang_opt_flags.append(f"-gsplit-dwarf={args.split_dwarf}")
+
+    # The following args slices manipulating may be confusing. The opt_args are:
+    #   1. a spliter "--", it's not used anywhere;
+    #   2. the fbcc wrapper script path
+    #   3. the "--cc" arg pointing to the compiler we use
+    #   4. (optional) fbcc-consumed args like "--log-fbcc"
+    #   5. (optional) pass-through args like "--target=" (from buckified toolchains)
+    # EXAMPLE: ['--', 'buck-out/v2/gen/fbcode/8e3db19fe005003a/tools/build/buck/wrappers/__fbcc__/fbcc', '--cc=fbcode/third-party-buck/platform010/build/llvm-fb/<ver>/bin/clang++', '--log-fbcc=False', '--target=x86_64-redhat-linux-gnu', ...]
+    clang_cc1_flags = _cleanup_flags(args.opt_args[2:] + clang_opt_flags)
+    if clang_cc1_flags is None:
+        return EXIT_FAILURE
+
+    # Determine the end of fbcc-specific prefix args (fbcc path, --cc=, and
+    # optionally args that fbcc consumes like --log-fbcc).
+    # Only fbcc-consumed args belong in the prefix; pass-through args like
+    # --target= are already folded into clang_cc1_flags by _cleanup_flags
+    # and must NOT appear in fbcc_cmd where they would precede -cc1 and
+    # prevent clang from entering cc1 mode.
+    fbcc_prefix_end = _fbcc_prefix_end(args.opt_args)
+    fbcc_cmd = args.opt_args[1:fbcc_prefix_end] + clang_cc1_flags
+
+    if args.debug:
+        # Print fbcc commandline and exit.
+        print(" ".join(fbcc_cmd))
+        return EXIT_SUCCESS
+
+    subprocess.check_call(fbcc_cmd)
+    if os.stat(args.out).st_size == 0:
+        print("error: opt produced empty file")
+        return EXIT_FAILURE
+
+    if dwo is not None:
+        # Unfortunately some users manually add `-gno-split-dwarf` to the
+        # compiler flags contradicting the --split-dwarf setting. Create an
+        # empty file so buck rules are not missing the file...
+        try:
+            with open(dwo, "x") as _:
+                pass
+        except IOError:
+            pass
+
+    return EXIT_SUCCESS
+
+
+if __name__ == "__main__":
+    try:
+        sys.exit(main(sys.argv))
+    except subprocess.CalledProcessError as e:
+        traceback.print_exc()
+        sys.exit(e.returncode)
diff --git a/buck2/prelude/cxx/dist_lto/tools/dist_lto_planner_darwin.py b/buck2/prelude/cxx/dist_lto/tools/dist_lto_planner_darwin.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/dist_lto_planner_darwin.py
@@ -0,0 +1,331 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+A wrapper script around the linker invocation that completes distributed thin-lto thin-link.
+
+This script:
+
+(1) Parses the meta file, which specifies various file paths for each input object file.
+(2) Writes "plan" json files for each input object file or archive describing to Buck starlark logic how to create opt + codegen actions for each
+(3) Writes a "link plan" and a "final index". The link plan is used to identify which input object files are already native object files, and the final index constitutes a filelist used in the final native link. This filelist is a transformed version of the "index.full" file the linker produces.
+
+Starlark code holds a representation of each input object file or archive in memory in an array. When code here needs to communicate characteristics about a particular element of this array, it encodes this using the index into this array. These indices are referred to as "starlark array index"
+"""
+
+import argparse
+import dataclasses
+import json
+import os
+import os.path
+import subprocess
+import sys
+import tempfile
+import traceback
+from dataclasses import dataclass
+from enum import Enum
+from typing import Optional
+
+
+class BitcodeMergeState(str, Enum):
+    STANDALONE = "STANDALONE"
+    ABSORBED = "ABSORBED"
+    ROOT = "ROOT"
+    NOT_LOADED = "NOT_LOADED"
+
+
+def is_file_llvm_bitcode_wrapper_file(filepath: str) -> bool:
+    LLVM_BITCODE_WRAPPER_FILE_MAGIC = 0xDEC0170B
+    with open(filepath, "rb") as f:
+        file_magic = int.from_bytes(f.read(4), "big")
+        return file_magic == LLVM_BITCODE_WRAPPER_FILE_MAGIC
+
+
+def read_merged_bitcode_file(merged_bitcode_path) -> BitcodeMergeState:
+    if os.path.getsize(merged_bitcode_path) == 0:
+        return BitcodeMergeState.NOT_LOADED
+
+    if is_file_llvm_bitcode_wrapper_file(merged_bitcode_path):
+        return BitcodeMergeState.ROOT
+
+    with open(merged_bitcode_path) as merged_bitcode_file:
+        for line in merged_bitcode_file:
+            if "standalone" in line:
+                return BitcodeMergeState.STANDALONE
+            if "absorbed" in line:
+                return BitcodeMergeState.ABSORBED
+
+    raise Exception(f"unexpected merged bitcode file contents: {merged_bitcode_path}")
+
+
+@dataclass
+class ObjectFile:
+    """An object files passed directly to the distributed link. The object file may or may not be lazy."""
+
+    input_object_file_path: str
+    output_index_shard_file_path: str
+    output_premerged_bitcode_file_path: Optional[str]
+    output_plan_file_path: str
+    starlark_array_index: int
+
+    def __init__(
+        self,
+        input_object_file_path: str,
+        output_index_shard_file_path: str,
+        output_plan_file_path: str,
+        starlark_array_index: int,
+        output_premerged_bitcode_file_path: Optional[str] = None,
+    ):
+        self.input_object_file_path = input_object_file_path
+        self.output_index_shard_file_path = output_index_shard_file_path
+        self.output_premerged_bitcode_file_path = output_premerged_bitcode_file_path
+        self.output_plan_file_path = output_plan_file_path
+        self.starlark_array_index = int(starlark_array_index)
+
+
+@dataclass
+class ObjectFileOptimizationPlan:
+    """A structure holding the information required to optimize and codegen a single bitcode object file passed
+    directly to the link"""
+
+    # A list of indices into the sorted_index_link_data starlark array
+    # that identify other bitcode files this bitcode file imports from,
+    # and thus should be optimized along side
+    imports: list[int]
+    is_bitcode: bool
+    merge_state: Optional[BitcodeMergeState]
+    loaded_by_linker: bool
+
+
+BITCODE_SUFFIX = ".thinlto.bc"
+IMPORTS_SUFFIX = ".imports"
+OPT_OBJECTS_SUFFIX = ".opt.o"  # please note the files are not exist yet, this is to generate the index file use in final link
+MERGED_BITCODE_SUFFIX = ".merged.bc"
+
+
+def _parse_meta_file_records(
+    meta_file_path: str,
+) -> tuple[dict[str, ObjectFile]]:
+    object_file_records_map: dict[str, ObjectFile] = {}
+
+    with open(meta_file_path) as meta:
+        object_file_records_json = json.load(meta)
+        for record in object_file_records_json:
+            object_file_record = ObjectFile(**record)
+            object_file_records_map[object_file_record.input_object_file_path] = (
+                object_file_record
+            )
+
+    return object_file_records_map
+
+
+def _populate_premerger_path_conversion_maps(
+    object_file_records_map: dict[str, ObjectFile],
+) -> tuple[dict[str, str], dict[str, str]]:
+    original_bitcode_to_merged_bitcode_path_mapping = {}
+    merged_bitcode_to_original_bitcode_path_mapping = {}
+    for (
+        input_object_file_path,
+        object_file_record,
+    ) in object_file_records_map.items():
+        output_merged_bitcode_file_path = None
+        assert object_file_record.output_premerged_bitcode_file_path is not None
+        output_merged_bitcode_file_path = (
+            object_file_record.output_premerged_bitcode_file_path
+        )
+
+        original_bitcode_to_merged_bitcode_path_mapping[input_object_file_path] = (
+            output_merged_bitcode_file_path
+        )
+        merged_bitcode_to_original_bitcode_path_mapping[
+            output_merged_bitcode_file_path
+        ] = input_object_file_path
+
+    return (
+        original_bitcode_to_merged_bitcode_path_mapping,
+        merged_bitcode_to_original_bitcode_path_mapping,
+    )
+
+
+def _run_thin_link(
+    premerger_enabled: bool,
+    original_bitcode_to_merged_bitcode_path_mapping: dict[str, str],
+    thin_link_args: list[str],
+):
+    if premerger_enabled:
+        # Buck requires actions write output files to a location set by the build system.  When toolchain
+        # binaries cannot for whatever reason easily produce output files at known locations configurable
+        # locations, the usual approach is to use a wrapper Python script such as this one to place the
+        # files at the locations buck expects.  In this case, this will not work as sharded summaries embed
+        # paths to other bitcode files within the bitcode.  That means the toolchain must write the merged
+        # bitcode files to locations buck expects in the first place. This json document is parsed by the
+        # linker and communicates the locations at which the toolchain must write the merged bitcode files.
+        with tempfile.NamedTemporaryFile(mode="w+t") as premerger_output_mapping:
+            json.dump(
+                original_bitcode_to_merged_bitcode_path_mapping,
+                premerger_output_mapping,
+            )
+            premerger_output_mapping.flush()
+            thin_link_args.append(
+                f"-Wl,-mllvm,-premerger-output-map={premerger_output_mapping.name}"
+            )
+            subprocess.check_call(thin_link_args)
+    else:
+        subprocess.check_call(thin_link_args)
+
+
+def main(argv):
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--meta")
+    parser.add_argument("--index")
+    parser.add_argument("--link-plan")
+    parser.add_argument("--enable-premerger", action="store_true")
+    parser.add_argument("index_args", nargs=argparse.REMAINDER)
+    args = parser.parse_args(argv[1:])
+
+    premerger_enabled = args.enable_premerger
+
+    def read_imports(imports_path):
+        with open(imports_path) as infile:
+            if not premerger_enabled:
+                return [line.strip() for line in infile.readlines()]
+
+            result = []
+            for line in infile.readlines():
+                if line.strip().endswith(".merged.bc"):
+                    result.append(
+                        merged_bitcode_to_original_bitcode_path_mapping[line.strip()]
+                    )
+                else:
+                    result.append(line.strip())
+            return result
+
+    def index_path(path):
+        return os.path.join(args.index, path)
+
+    object_file_records_map = _parse_meta_file_records(args.meta)
+
+    original_bitcode_to_merged_bitcode_path_mapping = {}
+    if premerger_enabled:
+        (
+            original_bitcode_to_merged_bitcode_path_mapping,
+            merged_bitcode_to_original_bitcode_path_mapping,
+        ) = _populate_premerger_path_conversion_maps(object_file_records_map)
+
+    _run_thin_link(
+        premerger_enabled,
+        original_bitcode_to_merged_bitcode_path_mapping,
+        args.index_args[1:],
+    )
+
+    loaded_input_files_positions = {}
+    with open(index_path("index.full")) as indexfile:
+        for position, line in enumerate(indexfile):
+            if line.startswith(args.index):
+                # Bitcode files that appear in the index are prefixed with the argument to --thinlto-prefix-replace
+                # which in our case is the directory index is placed in. Remove this prefix to get the original path.
+                input_bitcode_file_path = os.path.relpath(
+                    line.strip(), start=args.index
+                )
+                loaded_input_files_positions[input_bitcode_file_path] = position
+            else:
+                loaded_input_files_positions[line.strip()] = position
+
+    def _input_file_path_is_loaded_by_linker(path):
+        return path in loaded_input_files_positions
+
+    absorbed_source_files = set()
+    non_lto_objects = {}
+
+    # Generate plans for object files
+    for path, data in sorted(object_file_records_map.items(), key=lambda v: v[0]):
+        # The linker will not write the sharded index to the location buck expects it to be by default, we need
+        # to move it there.
+        final_sharded_index_output_path = data.output_index_shard_file_path
+        os.makedirs(os.path.dirname(final_sharded_index_output_path), exist_ok=True)
+
+        temporary_sharded_index_location = index_path(path) + BITCODE_SUFFIX
+        imports_file_path = index_path(path) + IMPORTS_SUFFIX
+        merged_bitcode_path = (
+            original_bitcode_to_merged_bitcode_path_mapping[path]
+            if premerger_enabled
+            else None
+        )
+
+        final_link_line_position = -1
+        if path in loaded_input_files_positions:
+            final_link_line_position = loaded_input_files_positions[path]
+
+        # import files are only written for bitcode files
+        if os.path.exists(imports_file_path):
+            assert os.path.exists(temporary_sharded_index_location), (
+                "missing sharded index file for %s" % path
+            )
+            os.rename(temporary_sharded_index_location, final_sharded_index_output_path)
+
+            imports = read_imports(imports_file_path)
+            imports_list = []
+            for import_path in imports:
+                imported_object_file_record = object_file_records_map[import_path]
+                imports_list.append(imported_object_file_record.starlark_array_index)
+
+            merge_state = None
+            if premerger_enabled:
+                assert os.path.exists(merged_bitcode_path), (
+                    f"missing merged bitcode file at {merged_bitcode_path}"
+                )
+                merge_state = read_merged_bitcode_file(merged_bitcode_path)
+                if merge_state == BitcodeMergeState.ABSORBED:
+                    absorbed_source_files.add(path)
+
+            plan = ObjectFileOptimizationPlan(
+                imports=imports_list,
+                merge_state=merge_state,
+                is_bitcode=True,
+                loaded_by_linker=_input_file_path_is_loaded_by_linker(path),
+                final_link_line_position=final_link_line_position,
+            )
+        else:
+            # The linker will not generate an index shard, or a merged bitcode file if the input is not bitcode.
+            # Buck still expect the output, so write an empty file.
+            non_lto_objects[data.starlark_array_index] = 1
+            with open(final_sharded_index_output_path, "w"):
+                pass
+
+            if premerger_enabled:
+                with open(merged_bitcode_path, "w"):
+                    pass
+            plan = ObjectFileOptimizationPlan(
+                imports=[],
+                merge_state=None,
+                is_bitcode=False,
+                loaded_by_linker=_input_file_path_is_loaded_by_linker(path),
+                final_link_line_position=final_link_line_position,
+            )
+
+        with open(data.output_plan_file_path, "w") as planout:
+            json.dump(dataclasses.asdict(plan), planout, sort_keys=True)
+
+    # Dump the set of input object files that were already native object files instead of bitcode
+    with open(args.link_plan, "w") as outfile:
+        json.dump(
+            {
+                "non_lto_objects": non_lto_objects,
+            },
+            outfile,
+            sort_keys=True,
+        )
+
+
+if __name__ == "__main__":
+    try:
+        sys.exit(main(sys.argv))
+    except subprocess.CalledProcessError as e:
+        traceback.print_exc()
+        sys.exit(e.returncode)
diff --git a/buck2/prelude/cxx/dist_lto/tools/dist_lto_planner_gnu.py b/buck2/prelude/cxx/dist_lto/tools/dist_lto_planner_gnu.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/dist_lto_planner_gnu.py
@@ -0,0 +1,600 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+A simple wrapper around a distributed thinlto index command to fit into buck2's
+distributed thinlto build.
+
+This reads in a couple of things:
+    1. The "meta" JSON file. This is a list of all the linkable information.
+       It contains the object file, index output, plan output.
+       As well as associated pre/post flags for linkables.
+    2. The index and link plan output paths
+    3. The commands for the actual index command.
+
+It will invoke the index command and then copy the index outputs to the
+requested locations and write a plan for each of those objects. This "plan" is
+a simple json file with the most important thing being a list of the indices
+of the imports needed for that file.
+
+It will then additionally write a link plan, which is just a translation of
+the thinlto index (which lists the objects actually needed for the final link).
+
+
+Both opt and link plans use indices to refer to other files because it allows the bzl
+code to easily map back to other objects held in buck memory.
+"""
+
+import argparse
+import json
+import os
+import os.path
+import resource
+import subprocess
+import sys
+import traceback
+from typing import List, TextIO
+
+
+def _flatten_deep(items):
+    """Flatten recursive list of lists to a single list.
+
+    Example:
+    >>> _flatten_deep([1, [2, 3], 4, [5, [6]]]) == [1, 2, 3, 4, 5, 6]
+    """
+
+    def flatten_deep_helper(items, result):
+        for item in items:
+            if isinstance(item, (list, tuple)):
+                flatten_deep_helper(item, result)
+            else:
+                result.append(item)
+
+    result = []
+    flatten_deep_helper(items, result)
+
+    return result
+
+
+def _get_argsfile(args) -> str:
+    # go through the flags passed to linker and find the index argsfile
+    argsfiles = list(
+        filter(lambda arg: arg.endswith("thinlto_index_argsfile"), args.index_args)
+    )
+    assert len(argsfiles) == 1, (
+        f"expect only 1 argsfile but seeing multiple ones: {argsfiles}"
+    )
+    argsfile = argsfiles[0]
+    if argsfile.startswith("@"):
+        argsfile = argsfile[1:]
+    return argsfile
+
+
+def _extract_lib_search_path(argsfile_path: str) -> List[str]:
+    lib_search_path = []
+    with open(argsfile_path) as argsfile:
+        for line in argsfile:
+            if line.startswith("-L"):
+                lib_search_path.append(line.strip())
+    return lib_search_path
+
+
+def _write_args(argsfile: TextIO, args: List[str]) -> None:
+    for arg in args:
+        argsfile.write(arg.strip())
+        argsfile.write("\n")
+
+
+def _enable_core_dumps() -> None:
+    # The index step runs the system linker, which -- unlike Meta binaries --
+    # installs no userspace crash handler, so a crash only leaves a core dump if
+    # the kernel writes one, and the kernel writes nothing while the RLIMIT_CORE
+    # soft limit is 0. buck2 sets no per-action rlimits, so raise the soft limit
+    # to the inherited hard limit here (best effort: a no-op when the hard limit
+    # is itself 0, which needs a host/container-level change instead).
+    try:
+        _, hard = resource.getrlimit(resource.RLIMIT_CORE)
+        resource.setrlimit(resource.RLIMIT_CORE, (hard, hard))
+    except (OSError, ValueError) as e:
+        print(f"warning: failed to enable core dumps: {e}", file=sys.stderr)
+
+
+def main(argv):
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--meta")
+    parser.add_argument("--index")
+    parser.add_argument("--link-plan")
+    parser.add_argument("--final-link-index")
+    parser.add_argument("index_args", nargs=argparse.REMAINDER)
+    args = parser.parse_args(argv[1:])
+
+    _enable_core_dumps()
+    subprocess.check_call(args.index_args[1:])
+
+    bitcode_suffix = ".thinlto.bc"
+    imports_suffix = ".imports"
+    opt_objects_suffix = ".opt.o"  # please note the files are not exist yet, this is to generate the index file use in final link
+
+    # `linkables_index` contains the linkables that are NOT LLVM IR bitcode files (e.g., machine code archives, shared libraries).
+    # `linkables_index`'s key is the path to the linkable and the value is a dictionary containing the cmd_args and the meta_index.
+    # `linkables_index` is used to re-attach associated flags (pre/post flags and flags in the cmd_args form like `-Wl,--whole-archive`/`-Wl,--no-whole-archive`)
+    # for the final_link_index @argsfile used in the the Phase 4 final link.
+    # The associated flags are otherwise dropped because `ld.lld` produces an `index.full` file in the Phase 2 Thin Link step
+    # only contains the path to the linkable and no flags.
+    linkables_index = {}
+
+    with open(args.meta) as f:
+        meta = json.load(f)
+
+    for meta_entry_index1, meta_entry1 in enumerate(meta):
+        for linkable in meta_entry1["linkables"]:
+            if linkable["type"] == "cmd_args":
+                obj = linkable["object"]
+
+                if obj["type"] == "archive":
+                    linkable_path = obj["archive"]
+                    linkables_index[linkable_path] = {
+                        "cmd_args": linkable["cmd_args"],
+                        "meta_index": meta_entry_index1,
+                    }
+                elif obj["type"] == "shared_lib":
+                    linkable_path = obj["name"]
+                    linkables_index[linkable_path] = {
+                        "cmd_args": linkable["cmd_args"],
+                        "meta_index": meta_entry_index1,
+                    }
+                else:
+                    raise Exception(f"unknown linkable type: {obj}")
+
+    def read_imports(path, imports_path):
+        with open(imports_path) as infile:
+            return [line.strip() for line in infile.readlines()]
+
+    def index_path(path):
+        return os.path.join(args.index, path)
+
+    # The meta file comes directly from dist_lto.bzl and consists of a list of JSON objects.
+    #
+    # Example:
+    # ```
+    # [
+    #    {
+    #       "linkables": [
+    #          {
+    #             "type": "bitcode",
+    #             "path": "buck-out/v2/art/spongebob/Gary.cpp.o",
+    #             "output": "buck-out/v2/art/spongebob/Gary.cpp.o.thinlto.bc",
+    #             "plan_output": "buck-out/v2/art/spongebob/Gary.cpp.o.opt.plan",
+    #             "idx": 0
+    #          },
+    #          ...
+    #        ],
+    #        "pre_flags": [],
+    #        "post_flags": [],
+    #    },
+    #    {
+    #       "linkables": [
+    #         {
+    #            "type": "cmd_args",
+    #            "cmd_args": [ "build/glog/lib/libglog.a" ],
+    #            "linkable_type": "archive_linkable",
+    #            "object": {
+    #              "type": "archive",
+    #              "archive": "build/glog/lib/libglog.a",
+    #            }
+    #         }
+    #       ]
+    #     },
+    #    ...
+    # ]
+    # ```
+    #
+    # Inside objects with type "bitcode" and "archive", there are several attributes:
+    #  - path: The path to the source bitcode file from Phase 1 Compile.
+    #        This is used as an index into a dictionary (`mapping`) that records much of the metadata coming
+    #        from these lines.
+    #  - output: The path to output location of Phase 2 Thin Link's analysis result for this individual module.
+    #        This script is expected to place a ThinLTO index file at this location (suffixed `.thinlto.bc`).
+    #  - plan_output: The path to an output plan. This script is expected to place a link
+    #        plan here (a JSON document indicating which other object files this)
+    #        object file depends on, among other things.
+    #  - idx: The link data's index in the Starlark array.
+    #  - archive_name: If this object file came from an archive, the name of the archive.
+    #        Otherwise, this line is empty.
+    #  - archive_plan: If this object file came from an archive, the path to an output plan.
+    #        This script is expected to produce an archive link plan here (a JSON)
+    #        document similar to the object link plan, except containing link
+    #        information for every file in the archive from which this object
+    #        came. Otherwise, this line is empty.
+    #  - archive_index_dir: If this object file came from an archive, the indexes directory of that
+    #        archive. This script is expected to place all ThinLTO indexes derived
+    #        from object files originating from this archive in that directory.
+    #        Otherwise, this line is empty.
+    #  - archive_opt_objects_dir: If this object file came from an archive, the directory where
+    #        Phase 3 stages every member of that archive, each at its path relative
+    #        to the archive's base dir (the dir holding `archive_plan`). It is the
+    #        only dir of the archive that Phase 4 Final Link materializes, so the
+    #        final-link index must refer to members through it.
+    #
+    # There are two indices that are derived from this meta file: the object
+    # index (mapping["index"]) and the archive index (mapping["archive_index"]).
+    # These indices are indices into Starlark arrays for all objects and archive
+    # linkables, respectively. This script does not inspect them.
+    mapping = {}
+    archives = {}
+    for meta_entry_index2, meta_entry2 in enumerate(meta):
+        for linkable in meta_entry2["linkables"]:
+            if linkable["type"] == "bitcode":
+                path = linkable["path"]
+                output = linkable["output"]
+                plan_output = linkable["plan_output"]
+                idx = linkable["idx"]
+                mapping[path] = {
+                    "output": output,
+                    "plan_output": plan_output,
+                    "index": idx,
+                    "meta_index": meta_entry_index2,
+                    "archive_index": None,
+                    "archive_name": "",
+                    "opt_object_path": "",
+                }
+            elif linkable["type"] == "archive":
+                archive_idx = linkable["archive_idx"]
+                archive_name = linkable["archive_name"]
+                archive_plan = linkable["archive_plan"]
+                archive_index_dir = linkable["archive_index_dir"]
+                archive_opt_objects_dir = linkable["archive_opt_objects_dir"]
+                archive_base_dir = os.path.dirname(archive_plan)
+
+                obj_mapping_entry = {
+                    "output": "",
+                    "plan_output": "",
+                    "index": archive_idx,
+                    "meta_index": meta_entry_index2,
+                    "archive_index": archive_idx,
+                    "archive_name": archive_name,
+                }
+                for obj in linkable["objects"] or ():
+                    path = obj["path"]
+                    mapping[path] = dict(
+                        obj_mapping_entry,
+                        # Where Phase 3 stages this member, and thus the path Phase 4
+                        # Final Link must use for it.
+                        opt_object_path=os.path.join(
+                            archive_opt_objects_dir,
+                            os.path.relpath(path, archive_base_dir),
+                        ),
+                    )
+
+                archives[archive_idx] = {
+                    "name": archive_name,
+                    "objects": [],
+                    "plan": archive_plan,
+                    "index_dir": archive_index_dir,
+                }
+
+    non_lto_objects = {}
+    for path, data in sorted(mapping.items(), key=lambda v: v[0]):
+        output_loc = data["output"]
+        if os.path.exists(output_loc):
+            continue
+
+        if data["archive_index"] is not None:
+            archives[data["archive_index"]]["objects"].append(path)
+            continue
+
+        bc_file = index_path(path) + bitcode_suffix
+        imports_path = index_path(path) + imports_suffix
+        os.makedirs(os.path.dirname(output_loc), exist_ok=True)
+
+        if os.path.exists(imports_path):
+            assert os.path.exists(bc_file), "missing bc file for %s" % path
+            os.rename(bc_file, output_loc)
+            imports = read_imports(path, imports_path)
+            imports_list = []
+            archives_list = []
+            for import_path in imports:
+                if import_path not in mapping:
+                    continue
+                entry = mapping[import_path]
+                if entry["archive_index"] is not None:
+                    archives_list.append(int(entry["archive_index"]))
+                else:
+                    imports_list.append(entry["index"])
+            plan = {
+                "imports": imports_list,
+                "archive_imports": archives_list,
+                "index": data["index"],
+                "bitcode_file": bc_file,
+                "path": path,
+                "is_bc": True,
+            }
+        else:
+            non_lto_objects[data["index"]] = 1
+            with open(output_loc, "w"):
+                pass
+            plan = {
+                "is_bc": False,
+            }
+
+        with open(data["plan_output"], "w") as planout:
+            json.dump(plan, planout, sort_keys=True)
+
+    for archive in archives.values():
+        # For archives, we must produce a plan that provides Starlark enough
+        # information about how to launch a dynamic opt for each object file
+        # in the archive.
+        archive_plan = {}
+
+        # This is convenient to store, since it's difficult for Starlark to
+        # calculate it.
+        archive_plan["base_dir"] = os.path.dirname(archive["plan"])
+        object_plans = []
+        for obj in archive["objects"]:
+            imports_path = index_path(obj) + imports_suffix
+            output_path = archive["index_dir"]
+            os.makedirs(output_path, exist_ok=True)
+            if os.path.exists(imports_path):
+                bc_file = index_path(obj) + bitcode_suffix
+                os.rename(bc_file, os.path.join(output_path, os.path.basename(bc_file)))
+                imports = read_imports(path, imports_path)
+
+                imports_list = []
+                archives_list = []
+                for path in imports:
+                    if path not in mapping:
+                        continue
+                    entry = mapping[path]
+                    if entry["archive_index"] is not None:
+                        archives_list.append(int(entry["archive_index"]))
+                    else:
+                        imports_list.append(entry["index"])
+                object_plans.append(
+                    {
+                        "is_bc": True,
+                        "path": obj,
+                        "imports": imports_list,
+                        "archive_imports": archives_list,
+                        "bitcode_file": os.path.join(
+                            output_path, os.path.basename(bc_file)
+                        ),
+                    }
+                )
+            else:
+                object_plans.append(
+                    {
+                        "is_bc": False,
+                        "path": obj,
+                    }
+                )
+
+        archive_plan["objects"] = object_plans
+        with open(archive["plan"], "w") as planout:
+            json.dump(archive_plan, planout, sort_keys=True)
+
+    # We read the `index` and `index.full` files produced by linker in index stage
+    # and translate them to 2 outputs:
+    # 1. A link plan build final_link args. (This one may be able to be removed if we refactor the workflow)
+    # 2. A files list (*.final_link_index) used for final link stage which includes all the
+    #    files needed. it's based on index.full with some modification, like path updates
+    #    and redundant(added by toolchain) dependencies removing.
+    # The `index` file is a list of the LLVM IR bitcode files that were analyzed in the Phase 2 Thin Link Step.
+    # The `index.full` file is of ALL linkables used in the linking process, ordered by their symbol resolution.
+    # For a full discussion on `index.full` see https://reviews.llvm.org/D130229
+    # The file paths in `index` and the LLVM IR Bitcode files in `index.full` are listed as a child of the `args.index` directory.
+    # HOWEVER, the LLVM IR Bitcode files do NOT exist there and instead exist in the location with the `args.index` directory stripped off (i.e., with `os.path.relpath(start=args.index)`).
+    # The files suffixed with `.imports` and `.thinlto.bc` DO exist in the directory under `args.index`.
+    index = {}
+    index_files_set = set()
+    # TODO(T130322878): since we call linker wrapper twice (in index and in final_link), to avoid these libs get
+    # added twice we remove them from the index file for now.
+    KNOWN_REMOVABLE_DEPS_SUFFIX = [
+        "glibc/lib/crt1.o",
+        "glibc/lib/crti.o",
+        "glibc/lib/Scrt1.o",
+        "crtbegin.o",
+        "crtbeginS.o",
+        ".build_info.o",
+        "crtend.o",
+        "crtendS.o",
+        "glibc/lib/crtn.o",
+    ]
+    GENERATED_BUILD_INFO_OBJECT_BASENAME_PREFIX = "__buck2_generated_build_info.c"
+    with open(index_path("index")) as indexfile:
+        for line in indexfile:
+            line = line.strip()
+            index_files_set.add(line)
+            path = os.path.relpath(line, start=args.index)
+            if path in mapping:
+                index[mapping[path]["index"]] = 1
+
+    with open(args.link_plan, "w") as outfile:
+        json.dump(
+            {
+                "non_lto_objects": non_lto_objects,
+                "index": index,
+            },
+            outfile,
+            indent=2,
+            sort_keys=True,
+        )
+
+    # Append all search path flags (e.g -Lfbcode/third-party-buck/platform010/build/glibc/lib) from argsfile to final_index
+    # this workaround is to make dist_lto compatible with link_group. see T136415235 for more info
+    argsfile = _get_argsfile(args)
+    lib_search_path = _extract_lib_search_path(argsfile)
+
+    # build index file for final link use
+    with (
+        open(index_path("index.full")) as full_index_input,
+        open(args.final_link_index, "w") as final_link_index_output,
+    ):
+        final_link_index_output.write("\n".join(lib_search_path) + "\n")
+
+        # Keep track of the flags that were written because the ones that weren't are written at the end.
+        # The index into `flags_written_tracker` corresponds to the `index` into `meta`.
+        flags_written_tracker = bytearray(len(meta))
+
+        # Write out first flags without an associated linkable in the meta.
+        # Stop once we see the first linkable because
+        # flags with an associated linkables are written in the order they are seen in `full_index_input`.
+        for meta_entry_index3, meta_entry3 in enumerate(meta):
+            if meta_entry3["linkables"]:
+                # Break once we see the first linkable entry.
+                break
+            else:
+                pre_flags = _flatten_deep(meta_entry3["pre_flags"])
+                _write_args(final_link_index_output, pre_flags)
+
+                post_flags = _flatten_deep(meta_entry3["post_flags"])
+                _write_args(final_link_index_output, post_flags)
+                flags_written_tracker[meta_entry_index3] = 1
+
+        # Keep track of the previous meta_index so when the meta_index changes between loop iterations
+        # the post flags are written for the previous meta_index and pre_flags are written for the new meta_index.
+        prev_meta_index = None
+
+        for line in full_index_input:
+            line = line.strip()
+            if any(
+                filter(line.endswith, KNOWN_REMOVABLE_DEPS_SUFFIX)
+            ) or os.path.basename(line).startswith(
+                GENERATED_BUILD_INFO_OBJECT_BASENAME_PREFIX
+            ):
+                continue
+            # LLVM IR files that are indexed in Phase 2 Thin Link are reported by `ld.lld` to exist under the directory `args.index`,
+            # but they actually exist at the path with the prefix `args.index` removed.
+            # Remove the prefix `args.index` with `os.path.relpath`.
+            path = os.path.relpath(line, start=args.index)
+
+            if path in mapping:
+                mapping_entry = mapping[path]
+                meta_index = mapping_entry["meta_index"]
+            elif line in mapping:
+                # This case happens when a library is marked with `enable_distributed_thinlto = True`, but
+                # has `compiler_flags = ["-fno-lto"]`.
+                # In this case the .o file is a machine code file and thus it is NOT indexed by Phase 2 Thin Link,
+                # and `line` is NOT prefixed with `args.index`.
+                mapping_entry = mapping[line]
+                meta_index = mapping_entry["meta_index"]
+            elif line in linkables_index:
+                mapping_entry = None
+                meta_index = linkables_index[line]["meta_index"]
+            else:
+                mapping_entry = None
+                meta_index = None
+
+            has_meta_entry = meta_index is not None
+
+            if has_meta_entry:
+                # For simplicity, mark now that we have written the flags for this entry.
+                flags_written_tracker[meta_index] = 1
+
+            write_post_flags = (
+                prev_meta_index is not None and prev_meta_index != meta_index
+            )
+            if write_post_flags:
+                if post_flags := meta[prev_meta_index]["post_flags"]:
+                    _write_args(final_link_index_output, _flatten_deep(post_flags))
+
+            write_pre_flags = has_meta_entry and (
+                prev_meta_index is None or prev_meta_index != meta_index
+            )
+            if write_pre_flags:
+                # Before writing the pre_flags for THIS entry,
+                # write the preceding pre_flags/post_flags without linkables.
+                # Since this iterates backwards, we'll store the flags in a stack,
+                # and do a 2nd pass that writes them in the correct order into `final_index_args`.
+                preceding_flags_stack = []
+                for preceding_meta_index in range(meta_index - 1, -1, -1):
+                    if flags_written_tracker[preceding_meta_index]:
+                        break
+
+                    preceding_meta_entry = meta[preceding_meta_index]
+                    if preceding_meta_entry["linkables"]:
+                        # Only write up-to the next linkable
+                        break
+
+                    if preceding_post_flags := preceding_meta_entry["post_flags"]:
+                        preceding_flags_stack.append(preceding_post_flags)
+
+                    if preceding_pre_flags := preceding_meta_entry["pre_flags"]:
+                        preceding_flags_stack.append(preceding_pre_flags)
+
+                    flags_written_tracker[preceding_meta_index] = 1
+
+                for preceding_flags in reversed(preceding_flags_stack):
+                    _write_args(final_link_index_output, _flatten_deep(preceding_flags))
+
+                if pre_flags := meta[meta_index]["pre_flags"]:
+                    _write_args(final_link_index_output, _flatten_deep(pre_flags))
+
+            prev_meta_index = meta_index
+
+            if line in index_files_set and path in mapping and mapping[path]["output"]:
+                # This case is for a known and true LLVM IR Bitcode file that was
+                # NOT extracted from an archive.
+
+                # Get the output path to the actual file that is linked in Phase 4 Final Link,
+                # which is resulting file from Phase 3 ThinLTO Backends.
+                # These files are suffixed with ".opt.o" and are siblings to the ".thinlto.bc" files,
+                # so the path is obtained by replacing the suffix.
+                output = mapping[path]["output"].replace(
+                    bitcode_suffix, opt_objects_suffix
+                )
+                final_link_index_output.write(output + "\n")
+            elif (
+                mapping_entry is not None and mapping_entry["archive_index"] is not None
+            ):
+                # A member extracted from an LTO-able archive. Phase 3 stages every
+                # member -- bitcode and machine code alike -- in the archive's
+                # `opt_objects` dir, so both kinds are redirected there. Machine-code
+                # members occur for e.g. Rust `compiler_builtins`, which rustc emits as
+                # native objects even under `-Clinker-plugin-lto` (the crate is
+                # `#![no_builtins]`), so `ld.lld` produces no ThinLTO index for them.
+                final_link_index_output.write(mapping_entry["opt_object_path"] + "\n")
+            elif line in linkables_index:
+                # If this is a known linkable, then use the original cmd_args from the linkable entry,
+                # which could contain for example, "-Wl,--whole-archive" and "-Wl,--no-whole-archive" flags.
+                linkable_entry = linkables_index[line]
+                cmd_args = linkable_entry["cmd_args"]
+                if isinstance(cmd_args, list):
+                    _write_args(final_link_index_output, _flatten_deep(cmd_args))
+                else:
+                    final_link_index_output.write(cmd_args + "\n")
+            else:
+                # handle:
+                # - objects from genrule archives (not tracked by dist_lto)
+                # - pre-built archives
+                # - input files that did not come from linker input, e.g. linkerscirpts
+                final_link_index_output.write(line + "\n")
+
+        # Write post flags for the last iteration of the loop
+        if prev_meta_index is not None:
+            if post_flags := meta[prev_meta_index]["post_flags"]:
+                _write_args(final_link_index_output, _flatten_deep(post_flags))
+
+        # Write out the remaining unwritten flags
+        for flags_written_tracker_index, flags_written_tracker_entry in enumerate(
+            flags_written_tracker
+        ):
+            if not flags_written_tracker_entry:
+                meta_entry5 = meta[flags_written_tracker_index]
+                pre_flags = _flatten_deep(meta_entry5["pre_flags"])
+                _write_args(final_link_index_output, pre_flags)
+                post_flags = _flatten_deep(meta_entry5["post_flags"])
+                _write_args(final_link_index_output, post_flags)
+
+
+if __name__ == "__main__":
+    try:
+        sys.exit(main(sys.argv))
+    except subprocess.CalledProcessError as e:
+        traceback.print_exc()
+        sys.exit(e.returncode)
diff --git a/buck2/prelude/cxx/dist_lto/tools/dist_lto_prepare_darwin.py b/buck2/prelude/cxx/dist_lto/tools/dist_lto_prepare_darwin.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/dist_lto_prepare_darwin.py
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Prepares for an object-only ThinLTO link by extracting a given archive and
+producing a manifest of the objects contained within.
+"""
+
+import argparse
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import traceback
+from typing import List
+
+
+def _gen_path(parent_path: str, filename: str) -> str:
+    # concat file path and check the file exist before return
+    obj_path = os.path.join(parent_path, filename)
+    assert os.path.exists(obj_path)
+    return obj_path
+
+
+def _gen_filename(filename: str, num_of_instance: int) -> str:
+    # generate the filename based on the instance,
+    # for 1st instance, it's file.o
+    # for 2nd instance, it's file_1.o
+    if num_of_instance > 1:
+        basename, extension = os.path.splitext(filename)
+        return f"{basename}_{num_of_instance - 1}{extension}"
+    else:
+        return filename
+
+
+def is_universal_archive(archive_path: str) -> bool:
+    output = subprocess.check_output(["file", archive_path]).decode()
+    return "Mach-O universal binary" in output
+
+
+def extract_slice_from_universal_archive(
+    lipo_path: str, target_architecture: str, archive_path: str
+) -> str:
+    temp_file_name = os.path.join(tempfile.mkdtemp(), "extracted_archive.a")
+    subprocess.check_call(
+        [
+            lipo_path,
+            "-thin",
+            target_architecture,
+            "-output",
+            temp_file_name,
+            archive_path,
+        ]
+    )
+    return temp_file_name
+
+
+def main(argv: List[str]) -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--manifest-out")
+    parser.add_argument("--objects-out")
+    parser.add_argument("--ar")
+    parser.add_argument("--name")
+    parser.add_argument("--archive")
+    parser.add_argument("--target-architecture")
+    parser.add_argument("--lipo")
+    args = parser.parse_args(argv[1:])
+
+    objects_path = args.objects_out
+    os.makedirs(objects_path, exist_ok=True)
+
+    known_objects = []
+
+    archive_path = os.path.abspath(args.archive)
+    if is_universal_archive(archive_path):
+        archive_path = extract_slice_from_universal_archive(
+            args.lipo, args.target_architecture, archive_path
+        )
+
+    # Unfortunately, we use llvm-ar and, while binutils ar has had --output for
+    # a long time, llvm-ar does not support --output and the change in llvm-ar
+    # looks like it has stalled for years (https://reviews.llvm.org/D69418)
+    # So, we need to invoke ar in the directory that we want it to extract into, and so
+    # need absolute paths.
+    ar_path = os.path.abspath(args.ar)
+    output = subprocess.check_output(
+        [ar_path, "t", archive_path], cwd=objects_path
+    ).decode()
+    member_list = [member for member in output.split("\n") if member]
+
+    # This will extract all the members of the archive, including duplicates
+    # replacing existing duplicates. That is if first/foo.txt and second/foo.txt
+    # are placed in an archive in that order, this will leave second/foo.txt
+    # in the objects_path.
+    output = subprocess.check_output(
+        [ar_path, "xv", archive_path], cwd=objects_path
+    ).decode()
+
+    # Count all members of the same name.
+    counter = {}
+    for member in member_list:
+        counter.setdefault(member, 0)
+        counter[member] += 1
+        # Insert all objects at most once into the list of known objects
+        if counter[member] == 1:
+            known_objects.append(member)
+
+    with tempfile.TemporaryDirectory() as temp_dir:
+        # For each duplicate member, rename and extract duplicates 1 through N
+        # inclusive. While N was already extracted above, we don't want to rely
+        # upon this implementation detail of llvm-ar.
+        for member, count in counter.items():
+            if count <= 1:
+                continue
+            for current in range(1, count + 1):
+                # extract the file from archive
+                output = subprocess.check_output(
+                    [
+                        ar_path,
+                        "xN",
+                        str(current),
+                        archive_path,
+                        member,
+                    ],
+                    cwd=temp_dir,
+                ).decode()
+                unique_name = _gen_filename(member, current)
+                # rename and move the newly extracted file to objects_path
+                shutil.move(
+                    os.path.join(temp_dir, member),
+                    os.path.join(os.path.abspath(objects_path), unique_name),
+                )
+                if current > 1:
+                    known_objects.append(unique_name)
+
+    manifest = {
+        "objects": known_objects,
+    }
+    with open(os.path.join(args.manifest_out), "w") as outfile:
+        json.dump(manifest, outfile, indent=2, sort_keys=True)
+
+    return 0
+
+
+if __name__ == "__main__":
+    try:
+        sys.exit(main(sys.argv))
+    except subprocess.CalledProcessError as e:
+        traceback.print_exc()
+        sys.exit(e.returncode)
diff --git a/buck2/prelude/cxx/dist_lto/tools/dist_lto_prepare_gnu.py b/buck2/prelude/cxx/dist_lto/tools/dist_lto_prepare_gnu.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/dist_lto_prepare_gnu.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Prepares for an object-only ThinLTO link by extracting a given archive and
+producing a manifest of the objects contained within.
+"""
+
+import argparse
+import enum
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import traceback
+from typing import List, Tuple
+
+
+class ArchiveKind(enum.IntEnum):
+    UNKNOWN = 0
+    ARCHIVE = 1
+    THIN_ARCHIVE = 2
+
+
+def _gen_path(parent_path: str, filename: str) -> str:
+    # concat file path and check the file exist before return
+    obj_path = os.path.join(parent_path, filename)
+    assert os.path.exists(obj_path)
+    return obj_path
+
+
+def _gen_filename(filename: str, num_of_instance: int) -> str:
+    # generate the filename based on the instance,
+    # for 1st instance, it's file.o
+    # for 2nd instance, it's file_1.o
+    if num_of_instance > 1:
+        basename, extension = os.path.splitext(filename)
+        return f"{basename}_{num_of_instance - 1}{extension}"
+    else:
+        return filename
+
+
+def identify_file(path: str) -> Tuple[ArchiveKind, str]:
+    path = os.path.realpath(path)
+
+    if path.endswith(".rlib"):
+        # `file -b` sometimes misfires and reports a Rust rlib
+        # as "DOS/MBR boot sector"
+        output = "current ar archive\n"
+        return (ArchiveKind.ARCHIVE, output)
+
+    output = subprocess.check_output(["file", "-b", path]).decode()
+    if "ar archive" in output:
+        return (ArchiveKind.ARCHIVE, output)
+    elif "thin archive" in output:
+        return (ArchiveKind.THIN_ARCHIVE, output)
+    else:
+        with open(path, "rb") as infile:
+            head = infile.read(7)
+
+            if head == "!<thin>".encode():
+                return (ArchiveKind.THIN_ARCHIVE, output)
+
+    return (ArchiveKind.UNKNOWN, output)
+
+
+def main(argv: List[str]) -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--manifest-out")
+    parser.add_argument("--objects-out")
+    parser.add_argument("--ar")
+    parser.add_argument("--name")
+    parser.add_argument("--archive")
+    args = parser.parse_args(argv[1:])
+
+    objects_path = args.objects_out
+    os.makedirs(objects_path, exist_ok=True)
+
+    known_objects = []
+    file_type, debug_output = identify_file(args.archive)
+    if file_type == ArchiveKind.ARCHIVE:
+        # Unfortunately, we use llvm-ar and, while binutils ar has had --output for
+        # a long time, llvm-ar does not support --output and the change in llvm-ar
+        # looks like it has stalled for years (https://reviews.llvm.org/D69418)
+        # So, we need to invoke ar in the directory that we want it to extract into, and so
+        # need absolute paths.
+        ar_path = os.path.abspath(args.ar)
+        archive_path = os.path.abspath(args.archive)
+        output = subprocess.check_output(
+            [ar_path, "t", archive_path], cwd=objects_path
+        ).decode()
+        member_list = [member for member in output.split("\n") if member]
+
+        # This will extract all the members of the archive, including duplicates
+        # replacing existing duplicates. That is if first/foo.txt and second/foo.txt
+        # are placed in an archive in that order, this will leave second/foo.txt
+        # in the objects_path.
+        output = subprocess.check_output(
+            [ar_path, "xv", archive_path], cwd=objects_path
+        ).decode()
+
+        # Count all members of the same name.
+        counter = {}
+        for member in member_list:
+            counter.setdefault(member, 0)
+            counter[member] += 1
+            # Insert all objects at most once into the list of known objects
+            if counter[member] == 1:
+                known_objects.append(_gen_path(objects_path, member))
+
+        with tempfile.TemporaryDirectory() as temp_dir:
+            # For each duplicate member, rename and extract duplicates 1 through N
+            # inclusive. While N was already extracted above, we don't want to rely
+            # upon this implementation detail of llvm-ar.
+            for member, count in counter.items():
+                if count <= 1:
+                    continue
+                for current in range(1, count + 1):
+                    # extract the file from archive
+                    output = subprocess.check_output(
+                        [
+                            ar_path,
+                            "xN",
+                            str(current),
+                            archive_path,
+                            member,
+                        ],
+                        cwd=temp_dir,
+                    ).decode()
+                    unique_name = _gen_filename(member, current)
+                    # rename and move the newly extracted file to objects_path
+                    shutil.move(
+                        os.path.join(temp_dir, member),
+                        os.path.join(os.path.abspath(objects_path), unique_name),
+                    )
+                    if current > 1:
+                        known_objects.append(_gen_path(objects_path, unique_name))
+
+    elif file_type == ArchiveKind.THIN_ARCHIVE:
+        output = subprocess.check_output([args.ar, "t", args.archive]).decode()
+        for line in output.splitlines():
+            assert os.path.exists(line)
+            known_objects.append(line)
+    elif file_type == ArchiveKind.UNKNOWN:
+        raise AssertionError(
+            f"unknown archive kind for file {args.archive}: {debug_output}"
+        )
+
+    manifest = {
+        "debug": debug_output,
+        "objects": known_objects,
+    }
+    with open(os.path.join(args.manifest_out), "w") as outfile:
+        json.dump(manifest, outfile, indent=2, sort_keys=True)
+
+    return 0
+
+
+if __name__ == "__main__":
+    try:
+        sys.exit(main(sys.argv))
+    except subprocess.CalledProcessError as e:
+        traceback.print_exc()
+        sys.exit(e.returncode)
diff --git a/buck2/prelude/cxx/dist_lto/tools/tests/test_dist_lto_opt.py b/buck2/prelude/cxx/dist_lto/tools/tests/test_dist_lto_opt.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dist_lto/tools/tests/test_dist_lto_opt.py
@@ -0,0 +1,325 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import unittest
+
+from cxx.dist_lto.tools.dist_lto_opt_gnu import _fbcc_prefix_end, _filter_flags
+
+
+class TestDistLtoOpt(unittest.TestCase):
+    def test_filter_flags(self):
+        inputs = [
+            "-not-opt-flag",
+            "-Wl,-plugin-opt,-llvm_flag1",
+            "-Wl,-plugin-opt=-llvm_flag1_different_format",
+            "-Wl,-plugin-opt,sample-profile=/fbcode/abc/autofdo.profile",
+            "-Wl,--lto-whole-program-visibility",
+            "-Wl,-mllvm,-llvm-flag2",
+            "-Wl,-plugin-opt,O3",
+            "-Wl,-plugin-opt,-function-sections",
+            "-Wl,-mllvm,-hot-callsite-threshold=12000",
+            "-shared",
+        ]
+        flags = _filter_flags(inputs)
+        self.assertListEqual(
+            flags,
+            [
+                "-O2",
+                "-ffunction-sections",
+                "-fdata-sections",
+                "-mllvm",
+                "-llvm_flag1",
+                "-mllvm",
+                "-llvm_flag1_different_format",
+                "-fprofile-sample-use=/fbcode/abc/autofdo.profile",
+                "-mllvm",
+                "-llvm-flag2",
+                "-O3",
+                "-mllvm",
+                "-hot-callsite-threshold=12000",
+                "-fPIC",
+            ],
+        )
+
+    def test_fbcc_prefix_end_tp2_with_log_fbcc(self):
+        """TP2 toolchain: --log-fbcc is consumed by fbcc and included in prefix."""
+        opt_args = [
+            "--",
+            "buck-out/fbcc",
+            "--cc=fbcode/third-party-buck/platform010/build/llvm-fb/19/bin/clang++",
+            "--log-fbcc=False",
+            "--target=x86_64-redhat-linux-gnu",
+            "-nostdinc",
+        ]
+        self.assertEqual(_fbcc_prefix_end(opt_args), 4)
+
+    def test_fbcc_prefix_end_buckified_no_log_fbcc(self):
+        """Buckified toolchain: --target is NOT consumed by fbcc and must be
+        excluded from prefix to avoid breaking -cc1 mode."""
+        opt_args = [
+            "--",
+            "buck-out/fbcc",
+            "--cc=buck-out/v2/art/fbsource/third-party/llvm-fb/19/__build/bin/clang++__/out/clang++",
+            "--target=x86_64-redhat-linux-gnu",
+            "-nostdinc",
+            "-nostdinc++",
+        ]
+        self.assertEqual(_fbcc_prefix_end(opt_args), 3)
+
+    def test_fbcc_prefix_end_minimal(self):
+        """Minimal case: only --cc= present."""
+        opt_args = [
+            "--",
+            "buck-out/fbcc",
+            "--cc=some/clang++",
+        ]
+        self.assertEqual(_fbcc_prefix_end(opt_args), 3)
+
+    def test_fbcc_prefix_end_with_fbcc_debug_info(self):
+        """--fbcc-create-external-debug-info is consumed by fbcc."""
+        opt_args = [
+            "--",
+            "buck-out/fbcc",
+            "--cc=some/clang++",
+            "--fbcc-create-external-debug-info=/tmp/foo.dwo",
+            "--target=x86_64-redhat-linux-gnu",
+        ]
+        self.assertEqual(_fbcc_prefix_end(opt_args), 4)
+
+    def test_fbcc_prefix_end_multiple_consumed_flags(self):
+        """Multiple fbcc-consumed flags in a row."""
+        opt_args = [
+            "--",
+            "buck-out/fbcc",
+            "--cc=some/clang++",
+            "--log-fbcc=True",
+            "--fbcc-create-external-debug-info=/tmp/foo.dwo",
+            "--target=x86_64-redhat-linux-gnu",
+        ]
+        self.assertEqual(_fbcc_prefix_end(opt_args), 5)
+
+    def test_filter_flags_hhvm_case_rev_0f8618f31(self):
+        inputs = [
+            "--target=x86_64-redhat-linux-gnu",
+            "-nostdinc",
+            "-resource-dir",
+            "-idirafter",
+            "-idirafter",
+            "fbcode/third-party-buck/platform010/build/glibc/include",
+            "-idirafter",
+            "fbcode/third-party-buck/platform010/build/kernel-headers/include",
+            "-Bfbcode/third-party-buck/platform010/build/binutils/x86_64-facebook-linux/bin",
+            "--cflag=--target=x86_64-redhat-linux-gnu",
+            "-Bfbcode/third-party-buck/platform010/build/glibc/lib",
+            "-Bfbcode/third-party-buck/platform010/tools/gcc/lib/gcc/x86_64-redhat-linux-gnu/trunk",
+            "-Lfbcode/third-party-buck/platform010/build/libgcc/lib/gcc/x86_64-facebook-linux/trunk",
+            "-Wl,-nostdlib",
+            "-Wl,--dynamic-linker,/usr/local/fbcode/platform010/lib/ld.so",
+            "-Wl,--disable-new-dtags",
+            "-Bfbcode/third-party-buck/platform010/build/binutils/x86_64-facebook-linux/bin",
+            "-Wl,--no-mmap-output-file",
+            "-nodefaultlibs",
+            "--target=x86_64-redhat-linux-gnu",
+            "-Lfbcode/third-party-buck/platform010/build/glibc/lib",
+            "-Lfbcode/third-party-buck/platform010/build/libgcc/lib",
+            "-Wl,-z,notext",
+            "-Wl,-z,relro",
+            "-Wl,--gc-sections",
+            "-fuse-ld=lld",
+            "-Wl,--discard-section=.nv_fatbin",
+            "-Wl,--discard-section=.nvFatBinSegment",
+            "-Wl,--discard-section=.rela.debug_info",
+            "-Wl,--discard-section=.rela.debug_ranges",
+            "-Wl,--discard-section=.rela.debug_loc",
+            "-Wl,--discard-section=.rela.debug_line",
+            "-Wl,--discard-section=.rela.debug_aranges",
+            "-Wl,--discard-section=.rela.debug_types",
+            "-Wl,-O1",
+            "-Wl,--build-id=sha1",
+            "-Wl,-mllvm,-hot-callsite-threshold=12000",
+            "-Wl,--lto-whole-program-visibility",
+            "-fwhole-program-vtables",
+            "-Wl,--no-discard-section=.nv_fatbin",
+            "-Wl,--no-discard-section=.nvFatBinSegment",
+            "fbcode/tools/build/lib/move_gpu_sections_implicit_linker_script.txt",
+            "-fuse-ld=lld",
+            "--build-info=full",
+            "--build-info-build-mode=opt-hhvm-lto",
+            "--build-info-build-tool=buck2",
+            "--build-info-compiler=clang",
+            "--build-info-fdo-profile=",
+            "--build-info-platform=platform010",
+            "--build-info-rule=fbcode:scripts/fnz/minimal:minimal",
+            "--build-info-rule-type=cpp_binary",
+            "-flto=thin",
+            "-Wl,-plugin-opt,-function-sections",
+            "-Wl,-plugin-opt,-profile-guided-section-prefix=false",
+            "-Wl,-plugin-opt,-generate-type-units",
+            "-Wl,-plugin-opt,-enable-lto-ir-verification=false",
+            "-Xlinker",
+            "--export-dynamic-symbol=mallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=rallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=xallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=sallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=dallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=sdallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=nallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=mallctl",
+            "-Xlinker",
+            "--export-dynamic-symbol=mallctlnametomib",
+            "-Xlinker",
+            "--export-dynamic-symbol=mallctlbymib",
+            "-Xlinker",
+            "--export-dynamic-symbol=malloc_stats_print",
+            "-Xlinker",
+            "--export-dynamic-symbol=malloc_usable_size",
+            "-Xlinker",
+            "--export-dynamic-symbol=malloc_message",
+        ]
+        flags = _filter_flags(inputs)
+        self.assertIsNotNone(flags)
+        self.assertListEqual(
+            flags,
+            [
+                "-O2",
+                "-ffunction-sections",
+                "-fdata-sections",
+                "-fuse-ld=lld",
+                "-mllvm",
+                "-hot-callsite-threshold=12000",
+                "-fwhole-program-vtables",
+                "-fuse-ld=lld",
+                "-mllvm",
+                "-profile-guided-section-prefix=false",
+                "-mllvm",
+                "-generate-type-units",
+                "-mllvm",
+                "-enable-lto-ir-verification=false",
+            ],
+        )
+
+    def test_filter_flags_unicorn_case_rev_0f8618f31(self):
+        inputs = [
+            "--cflag=--target=x86_64-redhat-linux-gnu",
+            "-Bfbcode/third-party-buck/platform010/build/glibc/lib",
+            "-Bfbcode/third-party-buck/platform010/tools/gcc/lib/gcc/x86_64-redhat-linux-gnu/trunk",
+            "-Lfbcode/third-party-buck/platform010/build/libgcc/lib/gcc/x86_64-facebook-linux/trunk",
+            "-Wl,-nostdlib",
+            "-Wl,--dynamic-linker,/usr/local/fbcode/platform010/lib/ld.so",
+            "-Wl,--disable-new-dtags",
+            "-Bfbcode/third-party-buck/platform010/build/binutils/x86_64-facebook-linux/bin",
+            "-Wl,--no-mmap-output-file",
+            "-nodefaultlibs",
+            "--target=x86_64-redhat-linux-gnu",
+            "-Lfbcode/third-party-buck/platform010/build/glibc/lib",
+            "-Lfbcode/third-party-buck/platform010/build/libgcc/lib",
+            "-Wl,-z,notext",
+            "-Wl,-z,relro",
+            "-Wl,--gc-sections",
+            "-fuse-ld=lld",
+            "-Wl,--discard-section=.nv_fatbin",
+            "-Wl,--discard-section=.nvFatBinSegment",
+            "-Wl,--discard-section=.rela.debug_info",
+            "-Wl,--discard-section=.rela.debug_ranges",
+            "-Wl,--discard-section=.rela.debug_loc",
+            "-Wl,--discard-section=.rela.debug_line",
+            "-Wl,--discard-section=.rela.debug_aranges",
+            "-Wl,--discard-section=.rela.debug_types",
+            "-Wl,-O1",
+            "-Wl,--build-id=sha1",
+            "-Xlinker",
+            "-znow",
+            "-Xlinker",
+            "--emit-relocs",
+            "--build-info=full",
+            "--build-info-build-mode=opt-clang-thinlto",
+            "--build-info-build-tool=buck2",
+            "--build-info-compiler=clang",
+            "--build-info-fdo-profile=fbcode//fdo/autofdo/default_profile:autofdo",
+            "--build-info-platform=platform010",
+            "--build-info-rule=fbcode:unicorn:index_server",
+            "--build-info-rule-type=cpp_binary",
+            "-flto=thin",
+            "-Wl,-plugin-opt,sample-profile=buck-out/v2/gen/fbcode/40fc99293b37c503/fdo/autofdo/default_profile/__autofdo__/out/profile",
+            "-Wl,-plugin-opt,-function-sections",
+            "-Wl,-plugin-opt,-profile-guided-section-prefix=false",
+            "-Wl,-plugin-opt,-generate-type-units",
+            "-Wl,-plugin-opt,-enable-lto-ir-verification=false",
+            "-Xlinker",
+            "--push-state",
+            "-Xlinker",
+            "--no-as-needed",
+            "-Xlinker",
+            "--pop-state",
+            "-Wl,--undefined,Global",
+            "-Wl,--undefined,Local",
+            "-Wl,--undefined,MockConnection",
+            "-Wl,--undefined,Global",
+            "-Wl,--undefined,Local",
+            "-Wl,--undefined,MockConnection",
+            "-Xlinker",
+            "--start-group",
+            "fbcode/third-party-buck/platform010/build/IntelComposerXE/mkl/lib/intel64/libmkl_intel_lp64.a",
+            "fbcode/third-party-buck/platform010/build/IntelComposerXE/mkl/lib/intel64/libmkl_core.a",
+            "fbcode/third-party-buck/platform010/build/IntelComposerXE/mkl/lib/intel64/libmkl_intel_thread.a",
+            "-Xlinker",
+            "--end-group",
+            "-lpthread",
+            "-Xlinker",
+            "--export-dynamic-symbol=mallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=rallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=xallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=sallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=dallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=sdallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=nallocx",
+            "-Xlinker",
+            "--export-dynamic-symbol=mallctl",
+            "-Xlinker",
+            "--export-dynamic-symbol=mallctlnametomib",
+            "-Xlinker",
+            "--export-dynamic-symbol=mallctlbymib",
+            "-Xlinker",
+            "--export-dynamic-symbol=malloc_stats_print",
+            "-Xlinker",
+            "--export-dynamic-symbol=malloc_usable_size",
+            "-Xlinker",
+            "--export-dynamic-symbol=malloc_message",
+        ]
+        flags = _filter_flags(inputs)
+        self.assertIsNotNone(flags)
+        self.assertListEqual(
+            flags,
+            [
+                "-O2",
+                "-ffunction-sections",
+                "-fdata-sections",
+                "-fuse-ld=lld",
+                "-fprofile-sample-use=buck-out/v2/gen/fbcode/40fc99293b37c503/fdo/autofdo/default_profile/__autofdo__/out/profile",
+                "-mllvm",
+                "-profile-guided-section-prefix=false",
+                "-mllvm",
+                "-generate-type-units",
+                "-mllvm",
+                "-enable-lto-ir-verification=false",
+            ],
+        )
diff --git a/buck2/prelude/cxx/dwp.bzl b/buck2/prelude/cxx/dwp.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/dwp.bzl
@@ -0,0 +1,104 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("@prelude//utils:actions.bzl", "ActionExecutionAttributes")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+load(":debug.bzl", "SplitDebugMode")
+
+def dwp_available(toolchain: CxxToolchainInfo):
+    dwp = toolchain.binary_utilities_info.dwp
+    split_debug_mode = toolchain.split_debug_mode
+    return dwp != None and split_debug_mode != SplitDebugMode("none")
+
+def run_dwp_action(
+    ctx: AnalysisContext,
+    toolchain: CxxToolchainInfo,
+    obj: Artifact,
+    identifier: [str, None],
+    category_suffix: [str, None],
+    referenced_objects: [ArgLike, list[Artifact]],
+    dwp_output: Artifact,
+    action_execution_properties: ActionExecutionAttributes = ActionExecutionAttributes(),
+    from_exe = True,
+):
+    dwp = toolchain.binary_utilities_info.dwp
+
+    if from_exe:
+        args = cmd_args(
+            [dwp, "-o", dwp_output.as_output(), "-e", obj] + getattr(ctx.attrs, "extra_dwp_flags", []),
+            # All object/dwo files referenced in the library/executable are implicitly
+            # processed by dwp.
+            hidden = referenced_objects,
+        )
+    else:
+        args = cmd_args(
+            [dwp, "-o", dwp_output.as_output()] + getattr(ctx.attrs, "extra_dwp_flags", []),
+        )
+        argsfile, _ = ctx.actions.write(
+            "dwp{}{}.argsfile".format(
+                "_" + category_suffix if category_suffix else "",
+                "_" + identifier if identifier else "",
+            ),
+            referenced_objects,
+            allow_args = True,
+            has_content_based_path = False,
+        )
+        args.add(cmd_args(argsfile, format = "@{}", hidden = referenced_objects))
+
+    category = "dwp"
+    if category_suffix != None:
+        category += "_" + category_suffix
+
+    ctx.actions.run(
+        args,
+        category = category,
+        identifier = identifier,
+        prefer_local = action_execution_properties.prefer_local,
+        prefer_remote = action_execution_properties.prefer_remote,
+        local_only = action_execution_properties.local_only,
+        force_full_hybrid_if_capable = action_execution_properties.full_hybrid,
+        # dwp merges the debug info of the corpus the link consumed and its
+        # memory scales the same way, so share the link's local-slot weight.
+        weight = toolchain.linker_info.link_weight,
+    )
+
+def dwp(
+    ctx: AnalysisContext,
+    toolchain: CxxToolchainInfo,
+    # Executable/library to extra dwo paths from.
+    obj: Artifact,
+    # An identifier that will uniquely name this link action in the context of a category. Useful for
+    # differentiating multiple link actions in the same rule.
+    identifier: [str, None],
+    # A category suffix that will be added to the category of the link action that is generated.
+    category_suffix: [str, None],
+    # All `.o`/`.dwo` paths referenced in `obj`.
+    # TODO(T110378122): Ideally, referenced objects are a list of artifacts,
+    # but currently we don't track them properly.  So, we just pass in the full
+    # link line and extract all inputs from that, which is a bit of an
+    # overspecification.
+    referenced_objects: [ArgLike, list[Artifact]],
+    name_suffix: str = "",
+    action_execution_properties: ActionExecutionAttributes = ActionExecutionAttributes(),
+    from_exe = True,
+) -> Artifact:
+    # gdb/lldb expect to find a file named $file.dwp next to $file.
+    output = ctx.actions.declare_output(obj.short_path + name_suffix + ".dwp", has_content_based_path = False)
+    run_dwp_action(
+        ctx,
+        toolchain,
+        obj,
+        identifier,
+        category_suffix,
+        referenced_objects,
+        output,
+        action_execution_properties = action_execution_properties,
+        from_exe = from_exe,
+    )
+    return output
diff --git a/buck2/prelude/cxx/gcno.bzl b/buck2/prelude/cxx/gcno.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/gcno.bzl
@@ -0,0 +1,14 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Provider that exposes the .gcno files produced during compilation
+GcnoFilesInfo = provider(
+    fields = {
+        "gcno_files": provider_field(list[Artifact]),
+    }
+)
diff --git a/buck2/prelude/cxx/groups.bzl b/buck2/prelude/cxx/groups.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/groups.bzl
@@ -0,0 +1,497 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:groups_types.bzl", "Traversal")
+load("@prelude//linking:types.bzl", "Linkage")
+load(
+    "@prelude//utils:build_target_pattern.bzl",
+    "BuildTargetPattern",
+    "parse_build_target_pattern",
+)
+load(
+    "@prelude//utils:graph_utils.bzl",
+    "depth_first_traversal_by",
+)
+load(
+    "@prelude//utils:strings.bzl",
+    "strip_prefix",
+)
+load(
+    "@prelude//utils:utils.bzl",
+    "value_or",
+)
+load(
+    ":groups_types.bzl",
+    "Group",
+    "GroupAttrs",
+    "GroupDefinition",
+    "GroupFilterInfo",
+    "GroupMapping",
+)
+
+_VALID_ATTRS = [
+    "enable_distributed_thinlto",
+    "enable_if_node_count_exceeds",
+    "discard_group",
+    "linker_flags",
+    "linker_script",
+    "version_script",
+    "exported_linker_flags",
+    "link_execution_preference",
+    "no_as_needed",
+    "requires_root_node_exists",
+    "prohibit_file_duplicates",
+    "prefer_optimized_experimental",
+]
+
+# Traversal types in this list will only assign the node
+# to a target (as opposed to the transitive deps of the node's tree).
+_TRAVERSALS_TO_ASSIGN_NODE = [
+    Traversal("node"),
+    Traversal("subfolders"),
+    # TODO (dust): Possible perf optimization:
+    # When intersecting configured targets, it's not possible to intersect
+    # a parent without also intersecting it's children.
+    #
+    # As a result, there's a possible perf optimization to assign 'tree'
+    # to intersected targets instead, and leverage that to avoid traversing
+    # the entire tree of every root.
+    #
+    # For example:
+    # If iterating the tree of 'root2' we find a node which
+    # was also present in 'root1', we can skip traversing the subtree
+    # because it's evitable that everything is going to match there too.
+    Traversal("intersect_any_roots"),
+]
+
+# Creates a group from an existing group, overwriting any properties provided
+def create_group(
+    group: Group,
+    name: [None, str] = None,
+    mappings: [None, list[GroupMapping]] = None,
+    attrs: [None, GroupAttrs] = None,
+    definition_type: [None, GroupDefinition] = None,
+):
+    return Group(
+        name = value_or(name, group.name),
+        mappings = value_or(mappings, group.mappings),
+        attrs = value_or(attrs, group.attrs),
+        definition_type = value_or(definition_type, group.definition_type),
+    )
+
+def get_roots_from_mapping(mapping):
+    deps = mapping[0] if type(mapping[0]) == "list" else [mapping[0]]
+    return filter(None, deps)
+
+def parse_groups_definitions(
+    map: list,
+    # Function to parse a root label from the input type, allowing different
+    # callers to have different top-level types for the `root`s.
+    parse_root: typing.Callable = lambda d: d,
+) -> list[Group]:
+    groups = []
+    group_names = set()
+    for map_entry in map:
+        name = map_entry[0]
+
+        # Dedup the link group specs, take the deinition from the first definition
+        if name in group_names:
+            continue
+        group_names.add(name)
+        mappings = map_entry[1]
+        attrs = (map_entry[2] or {}) if len(map_entry) > 2 else {}
+
+        for attr in attrs:
+            if attr not in _VALID_ATTRS:
+                fail("invalid attr '{}' for link group '{}' found. Valid attributes are {}.".format(attr, name, _VALID_ATTRS))
+        group_attrs = GroupAttrs(
+            enable_distributed_thinlto = attrs.get("enable_distributed_thinlto", False),
+            enable_if_node_count_exceeds = attrs.get("enable_if_node_count_exceeds", None),
+            discard_group = attrs.get("discard_group", False),
+            linker_flags = attrs.get("linker_flags", []),
+            linker_script = attrs.get("linker_script", None),
+            version_script = attrs.get("version_script", None),
+            exported_linker_flags = attrs.get("exported_linker_flags", []),
+            link_execution_preference = attrs.get("link_execution_preference", None),
+            no_as_needed = attrs.get("no_as_needed", False),
+            requires_root_node_exists = attrs.get("requires_root_node_exists", True),
+            prohibit_file_duplicates = attrs.get("prohibit_file_duplicates", False),
+            prefer_optimized_experimental = attrs.get("prefer_optimized_experimental", False),
+        )
+
+        parsed_mappings = []
+        for entry in mappings:
+            traversal = _parse_traversal_from_mapping(entry[1])
+            mapping = GroupMapping(
+                roots = filter(None, [parse_root(root) for root in get_roots_from_mapping(entry)]),
+                traversal = traversal,
+                filters = _parse_filter_from_mapping(entry[2]),
+                preferred_linkage = Linkage(entry[3]) if len(entry) > 3 and entry[3] else None,
+            )
+            num_roots = len(mapping.roots) if mapping.roots else 0
+            if num_roots > 1 and mapping.traversal != Traversal("intersect_any_roots"):
+                fail("Invariant. A link_group mapping with traversal type: {} can only have 1 root node. {} found.".format(mapping.traversal, mapping.roots))
+            elif mapping.traversal == Traversal("intersect_any_roots") and num_roots < 2:
+                fail("Invariant. A link_group mapping with traversal type 'intersect' must have at least 2 root nodes. {} found.".format(mapping.roots))
+
+            parsed_mappings.append(mapping)
+
+        group = Group(
+            name = name,
+            mappings = parsed_mappings,
+            attrs = group_attrs,
+            definition_type = GroupDefinition("explicit"),
+        )
+        groups.append(group)
+
+    return groups
+
+def _parse_traversal_from_mapping(entry: str) -> Traversal:
+    if entry == "tree":
+        return Traversal("tree")
+    elif entry == "node":
+        return Traversal("node")
+    elif entry == "subfolders":
+        return Traversal("subfolders")
+    elif entry == "intersect_any_roots":
+        return Traversal("intersect_any_roots")
+    else:
+        fail("Unrecognized group traversal type: " + entry)
+
+def _parse_filter(entry: str) -> GroupFilterInfo:
+    for prefix in ("label:", "tag:"):
+        label_regex = strip_prefix(prefix, entry)
+        if label_regex != None:
+            # We need the anchors "^"" and "$" because experimental_regex match
+            # anywhere in the text, while we want full text match for group label
+            # text.
+            regex_expr = regex("^{}$".format(label_regex), fancy = False)
+
+            def matches_regex(_r, _t, labels):
+                return regex_expr.any_match(labels)
+
+            return GroupFilterInfo(
+                matches = matches_regex,
+                info = {"regex": str(regex_expr)},
+            )
+
+        target_regex = strip_prefix("target_regex:", entry)
+        if target_regex != None:
+            regex_expr = regex("^{}$".format(target_regex), fancy = True)
+
+            def matches_regex(_r, t, _labels):
+                return regex_expr.match(str(t.raw_target()))
+
+            return GroupFilterInfo(
+                matches = matches_regex,
+                info = {"target_regex": str(regex_expr)},
+            )
+
+    pattern = strip_prefix("pattern:", entry)
+    if pattern != None:
+        build_target_pattern = parse_build_target_pattern(pattern)
+
+        def matches_target_pattern(_r, t, _labels):
+            return build_target_pattern.matches(t)
+
+        return GroupFilterInfo(
+            matches = matches_target_pattern,
+            info = _make_json_info_for_build_target_pattern(build_target_pattern),
+        )
+
+    fail("Invalid group mapping filter: {}\nFilter must begin with `label:`, `tag:`, `target_regex` or `pattern:`.".format(entry))
+
+def _parse_filter_from_mapping(entry: [list[str | Dependency], str, Dependency, None]) -> list[GroupFilterInfo]:
+    if type(entry) == type([]):
+        return [_parse_filter(e) if isinstance(e, str) else e[GroupFilterInfo] for e in entry]
+    elif isinstance(entry, Dependency):
+        return [entry[GroupFilterInfo]]
+    elif type(entry) == type(""):
+        return [_parse_filter(entry)]
+    return []
+
+def compute_mappings(groups_map: dict[str, Group], graph_map: dict[Label, typing.Any]) -> dict[Label, str]:
+    """
+    Returns the group mappings {target label -> group name} based on the provided groups_map and graph.
+    """
+    if not groups_map:
+        return {}
+
+    target_to_group_map = {}
+    node_traversed_targets = {}
+
+    group_mappings_with_roots = []
+    group_mappings_without_roots = []
+    group_to_targets = {}
+
+    groups = groups_map.values()
+    for group in groups:
+        for mapping in group.mappings:
+            if mapping and not mapping.roots:
+                group_mappings_without_roots.append((group, mapping))
+            else:
+                group_mappings_with_roots.append((group, mapping))
+
+    # We assume there's more targets in the build graph then there are groups
+    for target in graph_map:
+        graph_node_labels = graph_map[target].labels
+        for group, mapping in group_mappings_without_roots:
+            all_match = True
+            for filter in mapping.filters:
+                if not filter.matches(None, target, graph_node_labels):
+                    all_match = False
+                    break
+            if all_match:
+                group_to_targets.setdefault(group.name, []).append((target, mapping))
+
+    for group, mapping in group_mappings_with_roots:
+        targets_in_mapping = _find_targets_in_mapping(graph_map, mapping)
+        for target in targets_in_mapping:
+            # If the target doesn't exist in our graph, skip the mapping.
+            if target not in graph_map:
+                continue
+            group_to_targets.setdefault(group.name, []).append((target, mapping))
+
+    for group in groups_map.values():
+        for target, mapping in group_to_targets.get(group.name, []):
+            _update_target_to_group_mapping(graph_map, target_to_group_map, node_traversed_targets, group, groups_map, mapping, target)
+
+    return target_to_group_map
+
+def get_dedupped_roots_from_groups(groups: list[Group]) -> list[Label]:
+    roots = {}
+    for group in groups:
+        for mapping in group.mappings:
+            if not mapping.roots:
+                continue
+
+            for root in mapping.roots:
+                roots[root] = True
+
+    return list(roots.keys())
+
+def _find_targets_in_mapping(graph_map: dict[Label, typing.Any], mapping: GroupMapping) -> list[Label]:
+    # If we have no filtering, we don't need to do any traversal to find targets to include.
+    if not mapping.filters:
+        if not mapping.roots:
+            # Some link groups may want to partially define their mapping roots based on constraint
+            # that potentially can be resolved to `None`.
+            #
+            # E.g:
+            # ```
+            # ("evict-mkl", [
+            #   (":mkl_ilp64_omp", "node", None, "shared"),
+            #   (select(
+            #     {"DEFAULT": None, "ovr_config//runtime:platform010": "//IntelComposerXE:mkl_ilp64_omp" }),
+            #     "node", None, "shared"
+            #   ),
+            # ])
+            # ```
+            # Second mapping will be resolved to `(None, "node", None, "shared")` and will not handle anything.
+            # There is no convenient way to gracefully handle that in user-facing link groups API.
+            return []
+
+        elif mapping.traversal != Traversal("intersect_any_roots"):
+            return mapping.roots
+
+    # Else find all dependencies that match the filter.
+    matching_targets = {}
+
+    def populate_matching_targets(node, root = None):  # Label -> bool:
+        graph_node = graph_map[node]
+
+        # This callsite was migrated away from `lazy.is_any()`
+        # because we saw a non-trivial increase in retained bytes
+        # associated with the lambda required by the function.
+        if mapping.filters:
+            for filter in mapping.filters:
+                if not filter.matches(root, node, graph_node.labels):
+                    # Filters can specify if they should stop once the first
+                    # non-match occurs.
+                    if filter.stop_at_first_non_match:
+                        return False
+                    return True
+
+        matching_targets[node] = None
+        if mapping.traversal == Traversal("tree"):
+            # We can stop traversing the tree at this point because we've added the
+            # build target to the list of all targets that will be traversed by the
+            # algorithm that applies the groups.
+            return False
+        return True
+
+    def populate_matching_targets_bfs_wrapper(node):  # (Label) -> list
+        if populate_matching_targets(node):
+            graph_node = graph_map[node]
+            return graph_node.deps + graph_node.exported_deps
+        return []
+
+    def populate_matching_targets_with_root(root, node):  # (Label, Label) -> list
+        if populate_matching_targets(node, root = root):
+            graph_node = graph_map[node]
+            return graph_node.deps + graph_node.exported_deps
+        return []
+
+    if not mapping.roots:
+        for node in graph_map:
+            populate_matching_targets(node)
+    elif mapping.traversal == Traversal("intersect_any_roots"):
+        targets_to_counter = {}
+        for root in mapping.roots:
+            # This is a captured variable inside `populate_matching_targets`.
+            # We reset it for each root we visit so that we don't have results
+            # from other roots.
+            matching_targets = {}
+            depth_first_traversal_by(graph_map, [root], partial(populate_matching_targets_with_root, root))
+            for t in matching_targets:
+                targets_to_counter[t] = targets_to_counter.get(t, 0) + 1
+
+        return [t for t, count in targets_to_counter.items() if count > 1]
+    else:
+        if len(mapping.roots) == 1:
+            matching_fn = partial(populate_matching_targets_with_root, mapping.roots[0])
+        else:
+            # When we have multiple roots there is no way to determine which
+            # root is being traversed, so just set it to None.
+            matching_fn = populate_matching_targets_bfs_wrapper
+
+        depth_first_traversal_by(graph_map, mapping.roots, matching_fn)
+
+    return matching_targets.keys()
+
+# Extracted from `_update_target_to_group_mapping` to avoid function allocations inside the loop
+def _assign_target_to_group(
+    target_to_group_map,  #: {"label": str}
+    node_traversed_targets,  #: {"label": None}
+    group,  #  Group,
+    groups_map,  # {str: Group}
+    mapping,  # GroupMapping
+    target,  # Label
+    node_traversal,
+):  # bool
+    # If the target hasn't already been assigned to a group, assign it to the
+    # first group claiming the target. Return whether the target was already assigned.
+    if target not in target_to_group_map:
+        if mapping.traversal == Traversal("subfolders"):
+            generated_group_name = _generate_group_subfolder_name(group.name, target.package)
+            _add_to_implicit_link_group(generated_group_name, group, groups_map, target_to_group_map, target)
+        else:
+            target_to_group_map[target] = group.name
+
+        if node_traversal:
+            node_traversed_targets[target] = None
+        return False
+    else:
+        return True
+
+# Extracted from `_update_target_to_group_mapping` to avoid function allocations inside the loop
+def _transitively_add_targets_to_group_mapping(
+    assign_target_to_group,  # (Label, bool) -> bool
+    node_traversed_targets,  #: {"label": None}
+    graph_map,  # {"label": "_b"}
+    node,
+):  # ([Label]) -> None
+    previously_processed = assign_target_to_group(node, False)
+
+    # If the node has been previously processed, and it was via tree (not node), all child nodes have been assigned
+    if previously_processed and node not in node_traversed_targets:
+        return None
+    graph_node = graph_map[node]
+    return graph_node.deps + graph_node.exported_deps
+
+# Types removed to avoid unnecessary type checking which degrades performance.
+def _update_target_to_group_mapping(
+    graph_map,  # {"label": "_b"}
+    target_to_group_map,  #: {"label": str}
+    node_traversed_targets,  #: {"label": None}
+    group,  #  Group,
+    groups_map,  # {str: Group}
+    mapping,  # GroupMapping
+    target,
+):  # Label
+    assign_target_to_group = partial(_assign_target_to_group, target_to_group_map, node_traversed_targets, group, groups_map, mapping)  # (Label, bool) -> bool
+    transitively_add_targets_to_group_mapping = partial(
+        _transitively_add_targets_to_group_mapping, assign_target_to_group, node_traversed_targets, graph_map
+    )  # (Label) -> list[Label]
+
+    if mapping.traversal in _TRAVERSALS_TO_ASSIGN_NODE:
+        assign_target_to_group(target, True)
+    else:  # tree
+        depth_first_traversal_by(graph_map, [target], transitively_add_targets_to_group_mapping)
+
+def _add_to_implicit_link_group(
+    generated_group_name,  # str
+    group,  # Group
+    groups_map,  # {str: Group}
+    target_to_group_map,  # {Label: str}
+    target,
+):  # Label
+    target_to_group_map[target] = generated_group_name
+    if generated_group_name not in groups_map:
+        groups_map[generated_group_name] = create_group(
+            group = group,
+            name = generated_group_name,
+            definition_type = GroupDefinition("implicit"),
+        )
+    elif groups_map[generated_group_name].definition_type == GroupDefinition("explicit"):
+        hashed_group_name = _hash_group_name(group.name, generated_group_name)
+        _add_to_implicit_link_group(hashed_group_name, group, groups_map, target_to_group_map, target)
+
+def _generate_group_subfolder_name(
+    group,  # str,
+    package,
+):  # str
+    """Dynamically generating link group name for "subfolders" traversal."""
+    name = group + "_" + package.replace("/", "_")
+
+    if len(name) > 246:
+        # Maximum filename size in unix is 255.
+        # We prefix all libraries with "lib" (3 symbols) and suffix with ".dylib" (6 symbols) or ".so" (3 symbols).
+        # Assuming ".dylib" suffix cause it's the longest, we can allow (255 - 3 - 6) = 246 symbols for the rest of the name.
+        name = _hash_group_name(group, name)
+    return name
+
+def _hash_group_name(prefix: str, name: str) -> str:
+    """
+    Creates new name via simple hashing.
+    Hash algorithm is stable in starlark: https://fburl.com/code/ptegkov6
+    """
+    return "{}_{}".format(prefix, str(hash(name)))
+
+def _make_json_info_for_build_target_pattern(build_target_pattern: BuildTargetPattern) -> dict[str, typing.Any]:
+    # `BuildTargetPattern` contains lambdas which are not serializable, so
+    # have to generate the JSON representation
+    return {
+        "cell": build_target_pattern.cell,
+        "kind": build_target_pattern.kind,
+        "name": build_target_pattern.name,
+        "path": build_target_pattern.path,
+    }
+
+def _make_json_info_for_group_mapping(group_mapping: GroupMapping) -> dict[str, typing.Any]:
+    return {
+        "filters": [filter.info for filter in group_mapping.filters],
+        "preferred_linkage": group_mapping.preferred_linkage,
+        "roots": group_mapping.roots,
+        "traversal": group_mapping.traversal,
+    }
+
+def _make_json_info_for_group(group: Group) -> dict[str, typing.Any]:
+    return {
+        "attrs": group.attrs,
+        "mappings": [_make_json_info_for_group_mapping(mapping) for mapping in group.mappings],
+        "name": group.name,
+    }
+
+def make_info_subtarget_providers(ctx: AnalysisContext, groups: list[Group], mappings: dict[Label, str]) -> list[Provider]:
+    info_json = {
+        "groups": {group.name: _make_json_info_for_group(group) for group in groups},
+        "mappings": mappings,
+    }
+    json_output = ctx.actions.write_json("link_group_map_info.json", info_json, pretty = True, has_content_based_path = False)
+    return [DefaultInfo(default_output = json_output)]
diff --git a/buck2/prelude/cxx/groups_types.bzl b/buck2/prelude/cxx/groups_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/groups_types.bzl
@@ -0,0 +1,121 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//linking:types.bzl", "Linkage")
+
+# Label for special group mapping which makes every target associated with it to be included in all groups
+MATCH_ALL_LABEL = "MATCH_ALL"
+
+# Label for special group mapping which makes every target associated with it to be linked directly
+# against the final binary
+NO_MATCH_LABEL = "NO_MATCH"
+
+# Label for special group mapping which causes every target associated with it to be included
+# in any groups that contain any targets with direct dependencies on it.
+# Sample use case: Vendor-supplied shared libraries that are used from multiple link-groups.
+MATCH_DIRECT_DEPS_LABEL = "MATCH_DIRECT_DEPS"
+
+Traversal = enum(
+    # Includes the target and all of it's transitive dependencies in the group.
+    "tree",
+    # Includes only the target in the group.
+    "node",
+    # Uses pattern and separates all targets by full folder path.
+    "subfolders",
+    # Includes targets found in the transitive deps of *any* roots.
+    # Filters for these mappings will be applied to the intersected deps.
+    "intersect_any_roots",
+)
+
+GroupFilterInfo = provider(
+    fields = {
+        # What should be dumped in the link-groups-info subtarget.
+        "info": provider_field(dict[str, typing.Any]),
+        # A function which is given an optional root label, a target label and
+        # a list of its labels returns if the target label matches.
+        "matches": provider_field(typing.Callable[[[Label, None], Label, list[str]], bool]),
+        # If the matching should stop once the filter no longer matches.
+        "stop_at_first_non_match": provider_field(bool, default = False),
+    },
+)
+
+# Representation of a parsed group mapping
+GroupMapping = record(
+    # The root to apply this mapping to.
+    roots = field(list[Label], []),
+    # The type of traversal to use.
+    traversal = field(Traversal, Traversal("tree")),
+    # Optional filter type to apply to the traversal.
+    filters = field(list[GroupFilterInfo], []),
+    # Preferred linkage for this target when added to a link group.
+    preferred_linkage = field([Linkage, None], None),
+)
+
+# Representation of group attributes
+GroupAttrs = record(
+    # Use distributed thinlto to build the link group shared library.
+    enable_distributed_thinlto = field(bool, False),
+    # Enable this link group if the binary's node count exceeds the given threshold
+    enable_if_node_count_exceeds = field([int, None], None),
+    # Discard all dependencies in the link group, useful for dropping unused dependencies
+    # from the build graph.
+    discard_group = field(bool, False),
+    # Adds additional linker flags used to link the link group shared object.
+    linker_flags = field(list[typing.Any], []),
+    # Passes a linker script to the link group shared library's link command.
+    linker_script = field([Artifact, None], None),
+    # Passes a version script to the link group shared library's link command.
+    # Tagging a group's symbols with a version keeps them from satisfying an
+    # identically-named *versioned* reference in another copy of the same library
+    # loaded into the process, which is otherwise allowed: glibc lets an
+    # unversioned definition satisfy a versioned reference, so whichever copy
+    # reaches the global scope first captures the other.
+    version_script = field([Artifact, None], None),
+    # Adds additional linker flags to apply to dependents that link against the
+    # link group's shared object.
+    exported_linker_flags = field(list[typing.Any], []),
+    # Controls link execution location: "any" (default), "full_hybrid", "local",
+    # "local_only", or "remote".
+    link_execution_preference = field([str, None, typing.Any], None),
+    # Wraps the link group shared library with `--no-as-needed/--as-needed`,
+    # used for link groups that are required at runtime but not statically referenced.
+    # Only applicable to gnu.
+    no_as_needed = field(bool, False),
+    # Requires root nodes in specs to always exist in dependency graph.
+    # Otherwise fails.
+    requires_root_node_exists = field(bool, True),
+    # For certain wide-scale generic link groups we want to enable
+    # initial duplicate analysis. This is useful for detecting dduplicated symbols problem early
+    # for automatoc link groups that we not aware about (e.g. evicting whole root package folder into link group)
+    prohibit_file_duplicates = field(bool, False),
+    # Uses optimized compilation outputs if available.
+    prefer_optimized_experimental = field(bool, False),
+)
+
+# Types of group traversal
+GroupDefinition = enum(
+    # Group is explicitly defined in mapping provided by user.
+    # That is the default behavior.
+    "explicit",
+    # Group is implicitly created during mapping computations.
+    # For example, group can be created for "subfolders" traversal.
+    "implicit",
+)
+
+# Representation of a parsed group
+Group = record(
+    # The name for this group.
+    name = str,
+    # The mappings that are part of this group.
+    mappings = list[GroupMapping],
+    attrs = GroupAttrs,
+    definition_type = field(GroupDefinition, GroupDefinition("explicit")),
+)
+
+def should_discard_group(group: [Group, None]) -> bool:
+    return group != None and group.attrs.discard_group
diff --git a/buck2/prelude/cxx/headers.bzl b/buck2/prelude/cxx/headers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/headers.bzl
@@ -0,0 +1,540 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:compile_types.bzl", "HeadersDepFiles")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo", "LinkerType")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:lazy.bzl", "lazy")
+load("@prelude//utils:utils.bzl", "value_or")
+
+# Defines the varying bits of implementation affecting on how the end user
+# should include the headers.
+# Given there are 2 headers which are defined:
+# a) one header in a list, as ["foo/bar/foobar.h"]
+# b) one header in a dict (aka named header), as {"wfh/baz.h": "path/header.h"}
+#
+# `apple`:
+# 1) header from the list should be included as NAMESPACE/PATH_BASENAME:
+# #include "namespace/foobar.h"
+# 2) header from the dict should be included as DICT_KEY (aka header name):
+# #include "wfh/baz.h"
+# 3) it should be possible to include list header from the same target via basename:
+# #include "foobar.h"
+#
+# `regular`:
+# 1) header from the list should be included as NAMESPACE/PATH:
+# #include "namespace/foo/bar/foobar.h"
+# 2) header from the dict should be included as NAMESPACE/DICT_KEY:
+# #include "namespace/wfh/baz.h"
+CxxHeadersNaming = enum("apple", "regular")
+
+# Modes supporting implementing the `raw_headers` parameter of C++ rules using
+# symlink trees and/or header maps through `headers`.
+RawHeadersAsHeadersMode = enum(
+    "enabled",
+    "disabled",
+)
+
+# Modes supporting implementing the `headers` parameter of C++ rules using raw
+# headers instead of e.g. symlink trees.
+HeadersAsRawHeadersMode = enum(
+    # Require that all headers be implemented as raw headers, failing if this
+    # is not possible.
+    "required",
+    # Attempt to implement headers via raw headers, falling to header maps or
+    # symlink tress when raw headers cannot be used (e.g. rule contains a
+    # generated header or remaps a header to an incompatible location in the
+    # header namespace).
+    "preferred",
+    "disabled",
+)
+
+HeaderMode = enum(
+    # Creates the header map that references the headers directly in the source
+    # tree.
+    "header_map_only",
+    # Creates the tree of symbolic links of headers.
+    "symlink_tree_only",
+    # Creates the tree of symbolic links of headers and creates the header map
+    # that references the symbolic links to the headers.
+    "symlink_tree_with_header_map",
+)
+
+HeaderStyle = enum(
+    "local",
+    "system",
+)
+
+Headers = record(
+    include_path = field(cmd_args),
+    # The header map on the include path, when the header mode uses one.
+    header_map = field(Artifact | None, None),
+    # NOTE(agallagher): Used for module hack replacement.
+    symlink_tree = field(Artifact | None, None),
+    # -fdebug-prefix-map args that map symlinked headers to source path
+    file_prefix_args = field([cmd_args, None], None),
+    # -fcoverage-prefix-map args (clang-only, separated so non-clang compilers can skip them)
+    coverage_prefix_args = field([cmd_args, None], None),
+)
+
+CHeader = record(
+    # `"artifact"` pointing to the actual header file
+    artifact = Artifact,
+    # Basename as it should appear in include directive
+    name = str,
+    # Prefix before the basename as it should appear in include directive
+    namespace = str,
+    # Whether or not this header is provided via dict, where the corresponding key is a new name
+    named = bool,
+)
+
+# Parameters controlling the varying aspects of headers-related behavior.
+# The contract on how headers could be used (i.e. end user inclusion rules)
+# is different for `apple_library` and `cxx_library`. Those parameters
+# allows generalizing the C++ rules implementation and are provided
+# by top-level user-facing wrappers around those generalized methods.
+CxxHeadersLayout = record(
+    # Prefix part of the header path in the include statement. Header name might
+    # not always be prepended by the namespace, `naming` parameter is controlling
+    # that behavior. The value is ready to be used and abstracts different naming
+    # for such prefix in user-facing attributes (e.g. `apple_binary.header_path_prefix`
+    # vs `cxx_binary.header_namespace`) and different default values when those
+    # attributes are omitted (package path for regular C++ rules vs target name for
+    # Apple-specific rules).
+    namespace = str,
+    # Selects the behavior in the implementation to support the specific way of how
+    # headers are allowed to be included (e.g. if header namespace is applied for
+    # headers from dicts). For more information see comment for `CxxHeadersNaming`
+    naming = CxxHeadersNaming,
+)
+
+CxxPrecompiledHeader = record(
+    header = field(Artifact),
+    basename = field(str),
+    basename_src = field(str),
+    path = field(str),
+    namespace = field(str),
+    clanguage = field(str),
+)
+
+CPrecompiledHeaderInfo = provider(
+    fields = {
+        "basename": provider_field(typing.Any, default = None),
+        "clanguage": provider_field(str | None, default = None),
+        "compiled": provider_field(bool, default = False),
+        # Actual precompiled header ready to be used during compilation.
+        "header": Artifact,
+        "path": provider_field(typing.Any, default = None),
+    }
+)
+
+def cxx_attr_header_namespace(ctx: AnalysisContext) -> str:
+    return value_or(ctx.attrs.header_namespace, ctx.label.package)
+
+def cxx_attr_headers_list(_ctx: AnalysisContext, headers: typing.Any, headers_layout: CxxHeadersLayout) -> list[CHeader]:
+    return _get_attr_headers(headers, headers_layout.namespace, headers_layout.naming)
+
+def cxx_attr_exported_headers(ctx: AnalysisContext, headers_layout: CxxHeadersLayout) -> list[CHeader]:
+    return cxx_attr_headers_list(ctx, ctx.attrs.exported_headers, headers_layout)
+
+def cxx_attr_headers(ctx: AnalysisContext, headers_layout: CxxHeadersLayout) -> list[CHeader]:
+    return cxx_attr_headers_list(ctx, ctx.attrs.headers, headers_layout)
+
+def cxx_get_regular_cxx_headers_layout(ctx: AnalysisContext) -> CxxHeadersLayout:
+    namespace = cxx_attr_header_namespace(ctx)
+    return CxxHeadersLayout(namespace = namespace, naming = CxxHeadersNaming("regular"))
+
+def cxx_attr_exported_header_style(ctx: AnalysisContext) -> HeaderStyle:
+    return HeaderStyle(ctx.attrs.exported_header_style)
+
+def _concat_inc_dir_with_raw_header(namespace, inc_dir, header) -> list[str] | None:
+    namespace_parts = namespace.split("/")
+    inc_dir_parts = inc_dir.split("/")
+    header_parts = header.short_path.split("/")
+
+    for part in inc_dir_parts:
+        if part == ".":
+            continue
+        if part == "..":
+            if not namespace_parts:
+                # Too many .., would set include root out of cell
+                return None
+            header_parts = [namespace_parts.pop()] + header_parts
+        elif part == header_parts[0]:
+            header_parts = header_parts[1:]
+        else:
+            # Header not accessible under this folder
+            return None
+    return header_parts
+
+def as_headers(ctx: AnalysisContext, raw_headers: list[Artifact], include_directories: list[str]) -> list[CHeader]:
+    headers = []
+    base_namespace = ctx.label.package
+    for header in raw_headers:
+        for inc_dir in include_directories:
+            inc_dir = paths.normalize(inc_dir)
+            mapped_header = _concat_inc_dir_with_raw_header(base_namespace, inc_dir, header)
+            if mapped_header:
+                headers.append(CHeader(artifact = header, name = "/".join(mapped_header), namespace = "", named = True))
+
+    return headers
+
+def cxx_attr_precompiled_headers(ctx: AnalysisContext, headers_layout: CxxHeadersLayout) -> CHeader | None:
+    header = ctx.attrs.srcs[0]
+    return _get_attr_headers([header], headers_layout.namespace, headers_layout.naming)[0]
+
+def _get_attr_headers(xs: typing.Any, namespace: str, naming: CxxHeadersNaming) -> list[CHeader]:
+    if type(xs) == type([]):
+        return [CHeader(artifact = x, name = _get_list_header_name(x, naming), namespace = namespace, named = False) for x in xs]
+    else:
+        return [CHeader(artifact = xs[x], name = x, namespace = _get_dict_header_namespace(namespace, naming), named = True) for x in xs]
+
+def as_raw_headers(ctx: AnalysisContext, headers: dict[str, Artifact], mode: HeadersAsRawHeadersMode) -> [list[CellPath], None]:
+    """
+    Return the include directories needed to treat the given headers as raw
+    headers, depending on the given `HeadersAsRawHeadersMode` mode.
+
+    Args:
+      mode:
+        disabled - always return `None`
+        preferred - return `None` if conversion isn't possible
+        required - fail if conversion isn't possible
+    """
+
+    # If we're not supporting raw header conversion, return `None`.
+    if mode == HeadersAsRawHeadersMode("disabled"):
+        return None
+
+    return _as_raw_headers(
+        ctx,
+        headers,
+        # Don't fail if conversion isn't required.
+        no_fail = mode != HeadersAsRawHeadersMode("required"),
+    )
+
+def _header_mode(cxx_toolchain_info: CxxToolchainInfo, header_mode: HeaderMode | None) -> HeaderMode:
+    toolchain_header_mode = cxx_toolchain_info.header_mode
+
+    # If the toolchain disabled header maps, respect that since the compiler
+    # simply cannot accept anything else.
+    if toolchain_header_mode == HeaderMode("symlink_tree_only"):
+        return toolchain_header_mode
+
+    # If the target specifies a header mode, use that in case it needs
+    # a symlink tree (even with header maps)
+    if header_mode != None:
+        return header_mode
+
+    return toolchain_header_mode
+
+def prepare_headers(
+    actions: AnalysisActions,
+    cxx_toolchain_info: CxxToolchainInfo,
+    srcs: dict[str, Artifact],
+    name: str,
+    header_mode: [HeaderMode, None] = None,
+    allow_cache_upload: bool = False,
+    uses_content_based_paths: bool = False,
+    header_namespace: [str, None] = None,
+) -> [Headers, None]:
+    """
+    Prepare all the headers we want to use, depending on the header_mode
+    set on the target's toolchain.
+        - In the case of a header map, we create a `name`.hmap file and
+          return it as part of the include path.
+        - In the case of a symlink tree, we create a directory of `name`
+          containing the headers and return it as part of the include path.
+    """
+    if len(srcs) == 0:
+        return None
+
+    header_mode = _header_mode(cxx_toolchain_info, header_mode)
+
+    # TODO(T110378135): There's a bug in clang where using header maps w/o
+    # explicit `-I` anchors breaks module map lookups.  This will be fixed
+    # by https://reviews.llvm.org/D103930 so, until it lands, disable header
+    # maps when we see a module map.
+    if header_mode == HeaderMode("symlink_tree_with_header_map") and lazy.is_any(lambda n: paths.basename(n) == "module.modulemap", srcs.keys()):
+        header_mode = HeaderMode("symlink_tree_only")
+
+    output_name = name
+
+    if header_mode == HeaderMode("header_map_only"):
+        headers = {h: (a, "{}") for h, a in srcs.items()}
+        hmap = _mk_hmap(actions, cxx_toolchain_info, output_name, headers, allow_cache_upload, uses_content_based_paths)
+        return Headers(
+            include_path = cmd_args(hmap, hidden = srcs.values()),
+            header_map = hmap,
+        )
+    symlink_dir = actions.symlinked_dir(
+        output_name,
+        _normalize_header_srcs(srcs),
+        has_content_based_path = uses_content_based_paths,
+    )
+    prefix_map_flag = "-ffile-prefix-map"
+    if header_mode == HeaderMode("symlink_tree_only"):
+        include_prefix = _infer_include_prefix(srcs, header_namespace, package = symlink_dir.owner.package)
+        replacement = _get_prefix_map_replacement(cxx_toolchain_info, symlink_dir, header_namespace, include_prefix)
+        file_prefix_args = None
+        if replacement != None:
+            file_prefix_args = cmd_args(cmd_args(symlink_dir, format = prefix_map_flag + "={}=" + replacement))
+        return Headers(
+            include_path = cmd_args(symlink_dir),
+            symlink_tree = symlink_dir,
+            file_prefix_args = file_prefix_args,
+        )
+    if header_mode == HeaderMode("symlink_tree_with_header_map"):
+        headers = {h: (symlink_dir, "{}/" + h) for h in srcs}
+        hmap = _mk_hmap(actions, cxx_toolchain_info, output_name, headers, allow_cache_upload, uses_content_based_paths)
+        include_prefix = _infer_include_prefix(srcs, header_namespace, package = symlink_dir.owner.package)
+        replacement = _get_prefix_map_replacement(cxx_toolchain_info, symlink_dir, header_namespace, include_prefix)
+        file_prefix_args = None
+        coverage_prefix_args = None
+        if replacement != None:
+            file_prefix_args = cmd_args(cmd_args(symlink_dir, format = prefix_map_flag + "={}=" + replacement))
+            coverage_prefix_args = cmd_args(cmd_args(symlink_dir, format = "-fcoverage-prefix-map={}=" + replacement))
+        return Headers(
+            include_path = cmd_args(hmap, hidden = symlink_dir),
+            header_map = hmap,
+            symlink_tree = symlink_dir,
+            file_prefix_args = file_prefix_args,
+            coverage_prefix_args = coverage_prefix_args,
+        )
+    fail("Unsupported header mode: {}".format(header_mode))
+
+def _normalize_header_srcs(srcs: dict) -> dict:
+    normalized_srcs = {}
+    for key, val in srcs.items():
+        normalized_key = paths.normalize(key)
+        stored_val = normalized_srcs.get(normalized_key, None)
+        expect(
+            stored_val == None or stored_val == val,
+            "Got different values {} and {} for the same normalized header {}".format(
+                val,
+                stored_val,
+                normalized_key,
+            ),
+        )
+        normalized_srcs[normalized_key] = val
+
+    return normalized_srcs
+
+def _as_raw_headers(
+    ctx: AnalysisContext,
+    headers: dict[str, Artifact],
+    # Return `None` instead of failing.
+    no_fail: bool = False,
+) -> [list[CellPath], None]:
+    """
+    Return the include directories needed to treat the given headers as raw
+    headers.
+    """
+
+    # Find the all the include dirs needed to treat the given headers as raw
+    # headers.
+    inc_dirs = {}
+    for name, header in headers.items():
+        inc_dir = _as_raw_header(
+            ctx,
+            name,
+            header,
+            no_fail = no_fail,
+        )
+
+        # If the conversion wasn't possible, `inc_dir` will be `None` and we
+        # should bail now.
+        if inc_dir == None:
+            return None
+        inc_dirs[inc_dir] = None
+
+    return [ctx.label.path.add(p) for p in inc_dirs]
+
+def _as_raw_header(
+    ctx: AnalysisContext,
+    # The full name used to include the header.
+    name: str,
+    header: Artifact,
+    # Return `None` instead of failing.
+    no_fail: bool = False,
+) -> [str, None]:
+    """
+    Return path to pass to `include_directories` to treat the given header as
+    a raw header.
+    """
+    name = paths.normalize(name)
+
+    # We can't handle generated headers.
+    if not header.is_source:
+        if no_fail:
+            return None
+        fail("generated headers cannot be used as raw headers ({})".format(header))
+
+    # To include the header via its name using raw headers and include dirs,
+    # it needs to be a suffix of its original path, and we'll strip the include
+    # name to get the include dir used to include it.
+    path = paths.join(ctx.label.package, header.short_path)
+    path = paths.normalize(path)
+    base = paths.strip_suffix(path, name)
+    if base == None:
+        if no_fail:
+            return None
+        fail("header name must be a path suffix of the header path to be " + "used as a raw header ({} => {})".format(name, header))
+
+    # If the include dir is underneath our package, then just relativize to find
+    # out package-relative path.
+    if len(base) >= len(ctx.label.package):
+        return paths.relativize(base, ctx.label.package)
+
+    # Otherwise, this include dir needs to reference a parent dir.
+    expect(ctx.label.package.startswith(base))
+    num_parents = len(ctx.label.package.split("/")) - (0 if not base else len(base.split("/")))
+    return "/".join([".."] * num_parents)
+
+def _get_list_header_name(header: Artifact, naming: CxxHeadersNaming) -> str:
+    if naming.value == "regular":
+        return header.short_path
+    elif naming.value == "apple":
+        return header.basename
+    else:
+        fail("Unsupported header naming: {}".format(naming))
+
+def _get_dict_header_namespace(namespace: str, naming: CxxHeadersNaming) -> str:
+    if naming.value == "regular":
+        return namespace
+    elif naming.value == "apple":
+        return ""
+    else:
+        fail("Unsupported header naming: {}".format(naming))
+
+def _infer_include_prefix(srcs: dict[str, Artifact], header_namespace: [str, None], package: [str, None] = None) -> [str, None]:
+    """
+    Compute the cell-relative path prefix that, when prepended to a symlink
+    tree key, reconstructs the correct source path within the cell.
+    Returns a cell-relative prefix string, or None when no match could be
+    determined (caller should fall back to the package path).
+    """
+    return _infer_include_prefix_from_paths(
+        {k: v.short_path for k, v in srcs.items()},
+        header_namespace,
+        package,
+    )
+
+def _infer_include_prefix_from_paths(srcs_paths: dict[str, str], header_namespace: [str, None], package: [str, None] = None) -> [str, None]:
+    if header_namespace != "":
+        return None
+    for key, short in srcs_paths.items():
+        if short.endswith(key):
+            if len(short) > len(key):
+                prefix = paths.normalize(short[: len(short) - len(key)])
+                return paths.join(package, prefix) if package else prefix
+            # Exact match (short == key) is uninformative — this entry
+            # sits directly in the package dir. Skip it and check more
+            # entries, since others may reveal a subdirectory prefix
+            # (e.g. "include/") that applies to the majority of headers.
+            continue
+        if package:
+            full_path = paths.join(package, short)
+            if full_path.endswith(key):
+                if len(full_path) > len(key):
+                    return paths.normalize(full_path[: len(full_path) - len(key)])
+                # full_path == key means the key already encodes the
+                # package-relative path (e.g. via subdir_glob prefix).
+                # Return "" so the caller uses just the cell prefix.
+                return ""
+        break
+    return None
+
+def _get_prefix_map_replacement(
+    cxx_toolchain_info: CxxToolchainInfo, header_dir: Artifact, header_namespace: [str, None] = None, include_prefix: [str, None] = None
+) -> [str, None]:
+    """Compute the replacement path for prefix-map flags."""
+
+    # NOTE(@christylee): Do we need to enable debug-prefix-map for darwin and windows?
+    if cxx_toolchain_info.linker_info.type != LinkerType("gnu"):
+        return None
+
+    cell = value_or(header_dir.owner.cell, ".")
+
+    cell_prefix = cxx_toolchain_info.cell_to_path_prefix_map.get(cell, "")
+    prefix_target = cell_prefix
+    if header_namespace == "":
+        if include_prefix != None:
+            # include_prefix captures the path from cell root to above the
+            # symlink tree key structure. Use it directly instead of the
+            # package path to avoid duplication when keys already encode
+            # the package path (e.g. via subdir_glob prefix).
+            if include_prefix:
+                prefix_target = paths.join(prefix_target, include_prefix) if prefix_target else include_prefix
+        else:
+            package = header_dir.owner.package
+            if package:
+                prefix_target = paths.join(prefix_target, package) if prefix_target else package
+    return prefix_target if prefix_target else cell
+
+def _mk_hmap(
+    actions: AnalysisActions,
+    cxx_toolchain_info: CxxToolchainInfo,
+    name: str,
+    headers: dict[str, (Artifact, str)],
+    allow_cache_upload: bool,
+    uses_content_based_paths: bool = False,
+) -> Artifact:
+    output = actions.declare_output(
+        name + ".hmap",
+        has_content_based_path = uses_content_based_paths,
+    )
+
+    header_args = cmd_args()
+    for n, (path, fmt) in headers.items():
+        header_args.add(n)
+        header_args.add(cmd_args(path, format = fmt))
+
+    hmap_args_file = actions.write(
+        output.basename + ".cxx_hmap_argsfile",
+        cmd_args(header_args, quote = "shell"),
+        has_content_based_path = uses_content_based_paths,
+    )
+
+    cmd = cmd_args(
+        [cxx_toolchain_info.internal_tools.hmap_wrapper] + ["--output", output.as_output()] + ["--mappings-file", hmap_args_file],
+    )
+    actions.run(cmd, category = "generate_hmap", identifier = name, allow_cache_upload = allow_cache_upload)
+    return output
+
+def add_headers_dep_files(
+    actions: AnalysisActions, cmd: cmd_args, headers_dep_files: HeadersDepFiles, src: Artifact, filename_base: str, action_dep_files: dict[str, ArtifactTag]
+) -> cmd_args:
+    dep_file = actions.declare_output(
+        paths.join("__dep_files__", filename_base),
+        has_content_based_path = True,
+    ).as_output()
+    processor_flags, compiler_flags = headers_dep_files.mk_flags(
+        actions,
+        filename_base,
+        src,
+    )
+    cmd.add(compiler_flags)
+
+    # API: First argument is the dep file source path, second is the
+    # dep file destination path, other arguments are the actual compile
+    # command.
+    cmd = cmd_args([
+        headers_dep_files.processor,
+        headers_dep_files.dep_tracking_mode.value,
+        processor_flags,
+        headers_dep_files.tag.tag_artifacts(dep_file),
+        cmd,
+    ])
+
+    action_dep_files["headers"] = headers_dep_files.tag
+    return cmd
+
+headers_for_tests = struct(
+    infer_include_prefix = _infer_include_prefix_from_paths,
+)
diff --git a/buck2/prelude/cxx/hip_debug_extract.bzl b/buck2/prelude/cxx/hip_debug_extract.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/hip_debug_extract.bzl
@@ -0,0 +1,60 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+
+# BOLT-pattern suffix. Wrapper writes the canonical-named patched binary
+# in the same directory to keep `$ORIGIN`-relative RPATH valid.
+PRE_EXTRACT_SUFFIX = "-pre_extract"
+
+HipDebugExtractOutputs = record(
+    patched_output = field(Artifact),
+    # arch label (e.g. "gfx942") -> sidecar .debug
+    arch_debug_files = field(dict[str, Artifact]),
+)
+
+def hip_debug_extract_available(toolchain: CxxToolchainInfo) -> bool:
+    return toolchain.hip_device_debug_extract and bool(toolchain.hip_gpu_archs) and toolchain.hip_debug_extract != None
+
+# Per-TU compile-time strip: runs the wrapper on a single `.o`'s one
+# bundle, emitting per-arch sidecars. The host linker concatenates
+# stripped bundles into the final `.hip_fatbin`; per-TU
+# `.hipFatBinSegment` pointers are resolved by linker relocation.
+def hip_debug_extract_compile_object(
+    actions: AnalysisActions, toolchain: CxxToolchainInfo, obj: Artifact, identifier: [str, None] = None
+) -> HipDebugExtractOutputs:
+    archs = toolchain.hip_gpu_archs
+
+    stripped_name = obj.short_path + ".stripped.o"
+    stripped_output = actions.declare_output(stripped_name, has_content_based_path = True)
+    canonical = obj.short_path
+    arch_debug_files = {arch: actions.declare_output("{}.{}.debug".format(canonical, arch)) for arch in archs}
+
+    cmd = cmd_args([
+        toolchain.hip_debug_extract,
+        cmd_args(obj, format = "--input-binary={}"),
+        cmd_args(stripped_output.as_output(), format = "--output-binary={}"),
+    ])
+    for arch, debug_out in arch_debug_files.items():
+        cmd.add(
+            cmd_args(
+                debug_out.as_output(),
+                format = "--arch-debug-output=" + arch + "={}",
+            )
+        )
+
+    actions.run(
+        cmd,
+        category = "hip_debug_extract_tu",
+        identifier = identifier,
+    )
+
+    return HipDebugExtractOutputs(
+        patched_output = stripped_output,
+        arch_debug_files = arch_debug_files,
+    )
diff --git a/buck2/prelude/cxx/index_store.bzl b/buck2/prelude/cxx/index_store.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/index_store.bzl
@@ -0,0 +1,225 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_toolchain_types.bzl", "AppleToolchainInfo")
+
+def _index_store_args(artifact: Artifact) -> Artifact:
+    return artifact
+
+# A transitive set (tset) where we don't need to format the items to use them
+# as CLI arguments.
+#
+# https://www.internalfb.com/intern/staticdocs/buck2/docs/rule_authors/transitive_sets/#projections-using-transitive-sets-in-command-lines
+IndexStoreTSet = transitive_set(
+    args_projections = {
+        "args": _index_store_args,
+    },
+)
+
+# A struct representing information about the index store.
+#
+# https://www.internalfb.com/intern/staticdocs/buck2/docs/rule_authors/writing_rules/#providers
+IndexStoreInfo = provider(
+    fields = {
+        # The name of the target.
+        "name": provider_field(str),
+        # All the swift index stores as a tset.
+        "swift_tset": provider_field(IndexStoreTSet),
+        # A tset (transitive set) with this target's index store and the index store
+        # of all the dependencies as children.
+        "tset": provider_field(IndexStoreTSet),
+    },
+)
+
+def _get_merge_index_store_tool(ctx: AnalysisContext) -> RunInfo | None:
+    apple_toolchain = getattr(ctx.attrs, "_apple_toolchain", None)
+    if apple_toolchain == None:
+        return None
+    return apple_toolchain[AppleToolchainInfo].merge_index_store
+
+def merge_index_store(
+    actions: AnalysisActions, merge_index_store_tool: RunInfo, index_stores: list[Artifact] | TransitiveSet, merge_output_dir_name: str
+) -> Artifact:
+    if isinstance(index_stores, list):
+        if len(index_stores) == 1:
+            return index_stores[0]
+
+    merged_index_store = actions.declare_output(merge_output_dir_name, has_content_based_path = False)
+
+    cmd = cmd_args([merge_index_store_tool])
+    cmd.add(["--dest", merged_index_store.as_output()])
+
+    txt_args = cmd_args()
+    if isinstance(index_stores, list):
+        txt_args.add(index_stores)
+    else:
+        txt_args.add(index_stores.project_as_args("args"))
+
+    argsfile_path = merge_output_dir_name + ".files.txt"
+    argsfile = actions.write(argsfile_path, txt_args, has_content_based_path = False)
+    argsfile = cmd_args(argsfile, format = "@{}", hidden = txt_args)
+
+    cmd.add(["--sources"])
+    cmd.add(argsfile)
+
+    # Merge all the individual index store directories into a single
+    # directory containing all the unit and record files.
+    #
+    # We use `prefer_remote` to maximize the work done on RE, because
+    # we assume that RE hosts have the fastest network connections,
+    # especially if the buck command is running on a local
+    # laptop. There can also be some duplication between index stores,
+    # so we expect the final output to be smaller and less to
+    # download.
+    #
+    # We use `allow_cache_upload` because the output should be
+    # deterministic, so we can reuse results from previous runs.
+    actions.run(
+        cmd,
+        category = "merge_index_store",
+        identifier = merge_output_dir_name,
+        allow_cache_upload = True,
+        prefer_remote = True,
+    )
+    return merged_index_store
+
+def _gather_deps_index_store_tsets(deps: list[Dependency]) -> list[IndexStoreTSet]:
+    deps_indexstore_infos = filter(None, [dep.get(IndexStoreInfo) for dep in deps])
+    return [info.tset for info in deps_indexstore_infos]
+
+def _gather_deps_swift_index_store_tsets(deps: list[Dependency]) -> list[IndexStoreTSet]:
+    deps_indexstore_infos = filter(None, [dep.get(IndexStoreInfo) for dep in deps])
+    return [info.swift_tset for info in deps_indexstore_infos]
+
+def create_index_store_subtargets_and_provider(
+    ctx: AnalysisContext, current_target_index_stores: list[Artifact], swift_index_stores: list[Artifact], deps: list[Dependency]
+) -> (dict[str, list[Provider]], IndexStoreInfo):
+    merge_index_store_tool = _get_merge_index_store_tool(ctx)
+
+    if merge_index_store_tool:
+        # To create the index store for this target, we merge all the individual file target stores.
+        target_index_store = merge_index_store(
+            actions = ctx.actions,
+            merge_index_store_tool = merge_index_store_tool,
+            index_stores = current_target_index_stores,
+            merge_output_dir_name = paths.join(
+                "__indexstore__",
+                ctx.attrs.name,
+                "index_store",
+            ),
+        )
+
+        # To create the full index store, we need to merge the index store for this target with the
+        # index store from all our transitive dependencies.
+        index_store_tset = ctx.actions.tset(
+            IndexStoreTSet,
+            value = target_index_store,
+            children = _gather_deps_index_store_tsets(deps),
+        )
+        full_index_store = merge_index_store(
+            actions = ctx.actions,
+            merge_index_store_tool = merge_index_store_tool,
+            index_stores = index_store_tset,
+            merge_output_dir_name = paths.join(
+                "__indexstore__",
+                ctx.attrs.name,
+                "full_index_stores",
+            ),
+        )
+
+        # The index store for all the Swift files in this target.
+        target_swift_index_store = merge_index_store(
+            actions = ctx.actions,
+            merge_index_store_tool = merge_index_store_tool,
+            index_stores = swift_index_stores,
+            merge_output_dir_name = paths.join(
+                "__swiftindexstore__",
+                ctx.attrs.name,
+                "swift_index_stores",
+            ),
+        )
+
+        # The Swift index store for this target plus its immediate dependencies (not transitive).
+        # Collect only the immediate dependencies' swift index stores (just their values, not transitive).
+        immediate_deps_swift_index_stores = [target_swift_index_store]
+        deps_swift_tsets = _gather_deps_swift_index_store_tsets(deps)
+        for deps_tset in deps_swift_tsets:
+            if deps_tset.value:
+                immediate_deps_swift_index_stores.append(deps_tset.value)
+        swift_index_store_with_1deps = merge_index_store(
+            actions = ctx.actions,
+            merge_index_store_tool = merge_index_store_tool,
+            index_stores = immediate_deps_swift_index_stores,
+            merge_output_dir_name = paths.join(
+                "__swiftindexstore1deps__",
+                ctx.attrs.name,
+                "swift_index_store_1deps",
+            ),
+        )
+
+        # The full Swift index index store is created by merging the Swift index store for this target,
+        # plus the Swift index store from all our transitive dependencies.
+        swift_index_store_tset = ctx.actions.tset(
+            IndexStoreTSet,
+            value = target_swift_index_store,
+            children = _gather_deps_swift_index_store_tsets(deps),
+        )
+        full_swift_index_store = merge_index_store(
+            actions = ctx.actions,
+            merge_index_store_tool = merge_index_store_tool,
+            index_stores = swift_index_store_tset,
+            merge_output_dir_name = paths.join(
+                "__swiftfullindexstore__",
+                ctx.attrs.name,
+                "full_index_stores",
+            ),
+        )
+
+        sub_targets = {
+            # Create a subtarget foo//bar:baz[full-index-store] that builds and merges
+            # the index stores from foo//bar:baz plus all its transitive dependencies.
+            "full-index-store": [DefaultInfo(default_output = full_index_store)],
+            # Merged index store for all files compiled by swiftc.
+            "full-swift-index-store": [
+                DefaultInfo(default_output = full_swift_index_store),
+            ],
+            # Create a subtarget foo//bar:baz[index-store] that builds the
+            # index store for foo//bar:baz.
+            "index-store": [DefaultInfo(default_output = target_index_store)],
+            # Create a subtarget foo//bar:baz[swift-index-store] that builds the
+            # Swift index store for foo//bar:baz.
+            "swift-index-store": [DefaultInfo(default_output = target_swift_index_store)],
+            # Create a subtarget foo//bar:baz[swift-index-store-1deps] that builds the
+            # Swift index store for foo//bar:baz plus its immediate dependencies.
+            "swift-index-store-1deps": [
+                DefaultInfo(default_output = swift_index_store_with_1deps),
+            ],
+        }
+
+        index_store_info = IndexStoreInfo(
+            name = ctx.attrs.name,
+            tset = index_store_tset,
+            swift_tset = swift_index_store_tset,
+        )
+    else:
+        sub_targets = {
+            "full-index-store": [DefaultInfo(default_output = None)],
+            "full-swift-index-store": [DefaultInfo(default_output = None)],
+            "index-store": [DefaultInfo(default_output = None)],
+            "swift-index-store": [DefaultInfo(default_output = None)],
+            "swift-index-store-1deps": [DefaultInfo(default_output = None)],
+        }
+
+        index_store_info = IndexStoreInfo(
+            name = ctx.attrs.name,
+            tset = ctx.actions.tset(IndexStoreTSet),
+            swift_tset = ctx.actions.tset(IndexStoreTSet),
+        )
+
+    return (sub_targets, index_store_info)
diff --git a/buck2/prelude/cxx/link.bzl b/buck2/prelude/cxx/link.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/link.bzl
@@ -0,0 +1,767 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+    "make_artifact_tset",
+    "project_artifacts",
+)
+load("@prelude//:paths.bzl", "paths")
+# @oss-disable[end= ]: load("@prelude//apple/meta_only:shared_library_interfaces.bzl", "get_shared_library_interface_generation_linker_flags")
+load(
+    "@prelude//cxx:cxx_bolt.bzl",
+    "bolt",
+    "cxx_use_bolt",
+)
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",
+    "LinkerType",
+)
+load(
+    "@prelude//cxx/dist_lto:dist_lto.bzl",
+    "cxx_gnu_dist_link",
+)
+load(
+    "@prelude//cxx/dist_lto/darwin:dist_lto.bzl",
+    "cxx_darwin_dist_link",
+)
+load("@prelude//linking:add_elf_sections.bzl", "add_elf_sections_to_executable")
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference", "LinkExecutionPreferenceInfo", "get_action_execution_attributes")
+load(
+    "@prelude//linking:link_info.bzl",
+    "ArchiveLinkable",
+    "ExtraLinkerOutputs",
+    "LinkArgs",
+    "LinkedObject",
+    "ObjectsLinkable",
+    "unpack_external_debug_info",
+    "unpack_link_args",
+)
+load(
+    "@prelude//linking:lto.bzl",
+    "LtoMode",
+    "get_split_debug_lto_info",
+)
+load("@prelude//linking:stamp_build_info.bzl", "cxx_stamp_build_info", "stamp_build_info")
+load("@prelude//linking:strip.bzl", "strip_object")
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    ":anon_link.bzl",
+    "ANON_ATTRS",
+    "deserialize_anon_attrs",
+    "serialize_anon_attrs",
+)
+load(":bitcode.bzl", "make_bitcode_bundle")
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+load(":cxx_library_utility.bzl", "EMPTY_DEFAULT_INFO")
+load(
+    ":cxx_link_utility.bzl",
+    "LinkArgsOutput",
+    "cxx_link_cmd_parts",
+    "cxx_runtime_library_arguments",
+    "cxx_sanitizer_runtime_arguments",
+    "gc_sections_args",
+    "generates_split_debug",
+    "linker_map_args",
+    "linker_supports_linker_maps",
+    "make_link_args",
+)
+load(":debug.bzl", "SplitDebugMode")
+load(":dwp.bzl", "dwp", "dwp_available")
+load(":hip_debug_extract.bzl", "PRE_EXTRACT_SUFFIX", "hip_debug_extract_available")
+load(":link_types.bzl", "CxxLinkResultType", "LinkOptions", "get_dwp_execution_preference", "merge_link_options")
+load(
+    ":linker.bzl",
+    "SharedLibraryFlagOverrides",  # @unused Used as a type
+    "get_deffile_flags",
+    "get_import_library",
+    "get_output_flags",
+    "get_shared_library_flags",
+    "get_shared_library_name_linker_flags",
+)
+
+CxxLinkerMapData = record(
+    map = field(Artifact),
+    binary = field(Artifact),
+)
+
+CxxGcSectionsData = record(
+    gc_sections = field(Artifact),
+    binary = field(Artifact),
+)
+
+CxxLinkResult = record(
+    # The resulting artifact from the link
+    linked_object = LinkedObject,
+    linker_map_data = [CxxLinkerMapData, None],
+    gc_sections_data = [CxxGcSectionsData, None],
+    link_execution_preference_info = LinkExecutionPreferenceInfo,
+    # A list of runtime shared libraries
+    sanitizer_runtime_files = field(list[Artifact]),
+    # A dictionary of extra linker outputs generated from
+    # the extra_linker_outputs_factory
+    extra_outputs = field(dict[str, list[DefaultInfo]], default = {}),
+    # A representation of a shared library to link against, rather than the shared library
+    # itself. This can be advantageous because the interface is faster to generate,
+    # or because it hides implementation changes to the shared library that would cause
+    # unnecessary build invalidation.
+    shared_library_interface = [Artifact, None],
+)
+
+def link_external_debug_info(
+    ctx: AnalysisContext, links: list[LinkArgs], split_debug_output: Artifact | None = None, pdb: Artifact | None = None
+) -> ArtifactTSet:
+    external_debug_artifacts = []
+
+    # When using LTO+split-dwarf, the link step will generate externally
+    # referenced debug info.
+    if split_debug_output != None:
+        external_debug_artifacts.append(split_debug_output)
+
+    if pdb != None:
+        external_debug_artifacts.append(pdb)
+
+    external_debug_infos = []
+
+    # Add-in an externally referenced debug info that the linked object may
+    # reference (and which may need to be available for debugging).
+    for link in links:
+        external_debug_infos.append(unpack_external_debug_info(ctx.actions, link))
+
+    return make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        artifacts = external_debug_artifacts,
+        children = external_debug_infos,
+    )
+
+def link_args_have_hip_device_debug(links: list[LinkArgs]) -> bool:
+    for link in links:
+        if link.infos != None:
+            for info in link.infos:
+                if info.has_hip_device_debug:
+                    return True
+        if link.tset != None:
+            for infos in link.tset.infos.traverse():
+                if infos.default.has_hip_device_debug:
+                    return True
+                if infos.stripped != None and infos.stripped.has_hip_device_debug:
+                    return True
+    return False
+
+def collect_hip_debug_from_links(links: list[LinkArgs]) -> dict[str, list[Artifact]]:
+    result = {}
+    for link in links:
+        if link.infos != None:
+            for info in link.infos:
+                for arch, files in info.hip_arch_debug_files.items():
+                    result.setdefault(arch, [])
+                    result[arch].extend(files)
+        if link.tset != None:
+            for infos in link.tset.infos.traverse():
+                for info in [infos.default] + ([infos.stripped] if infos.stripped != None else []):
+                    for arch, files in info.hip_arch_debug_files.items():
+                        result.setdefault(arch, [])
+                        result[arch].extend(files)
+    return result
+
+# Actually perform a link into the supplied output.
+def cxx_link_into(
+    ctx: AnalysisContext,
+    # The destination for the link output.
+    output: Artifact,
+    result_type: CxxLinkResultType,
+    opts: LinkOptions,
+    output_has_content_based_path: bool = False,
+    build_info_json: Artifact | None = None,
+) -> CxxLinkResult:
+    cxx_toolchain_info = opts.cxx_toolchain or get_cxx_toolchain_info(ctx)
+    linker_info = cxx_toolchain_info.linker_info
+    is_incremental_link = opts.incremental_link
+
+    dwp_tool_available = dwp_available(cxx_toolchain_info)
+    is_result_executable = result_type.value == "executable"
+
+    if linker_info.generate_linker_maps and linker_supports_linker_maps(linker_info.type):
+        linker_map = ctx.actions.declare_output(output.short_path + "-LinkMap.txt", has_content_based_path = False)
+        linker_map_data = CxxLinkerMapData(
+            map = linker_map,
+            binary = output,
+        )
+    else:
+        linker_map = None
+        linker_map_data = None
+
+    if linker_info.generate_gc_sections and linker_info.type == LinkerType("gnu"):
+        gc_sections_output = ctx.actions.declare_output(output.short_path + "-gc-sections.json", has_content_based_path = False)
+        gc_sections_data = CxxGcSectionsData(
+            gc_sections = gc_sections_output,
+            binary = output,
+        )
+    else:
+        gc_sections_output = None
+        gc_sections_data = None
+
+    shared_library_interface = (
+        ctx.actions.declare_output(output.short_path + ".tbd", has_content_based_path = False) if opts.produce_shared_library_interface else None
+    )
+
+    if is_incremental_link:
+        ilk_filename = paths.replace_extension(output.short_path, ".ilk")
+        ilk_artifact = ctx.actions.declare_output(ilk_filename, has_content_based_path = False)
+    else:
+        ilk_artifact = None
+
+    if linker_info.supports_distributed_thinlto and opts.enable_distributed_thinlto:
+        if not linker_info.lto_mode == LtoMode("thin"):
+            fail("Cannot use distributed thinlto if the cxx toolchain doesn't use thin-lto lto_mode")
+        if linker_info.runtime_library_files:
+            fail("runtime_library_files is not supported with distributed thin-lto")
+        sanitizer_runtime_args = cxx_sanitizer_runtime_arguments(ctx, cxx_toolchain_info, output)
+
+        linker_type = linker_info.type
+        if linker_type == LinkerType("darwin"):
+            exe, extra_outputs = cxx_darwin_dist_link(
+                ctx,
+                output,
+                opts,
+                linker_info.thin_lto_premerger_enabled,
+                linker_info.thin_lto_double_codegen_enabled,
+                is_result_executable,
+                sanitizer_runtime_args,
+                shared_library_interface,
+                linker_map,
+            )
+        elif linker_type == LinkerType("gnu"):
+            if sanitizer_runtime_args.extra_link_args or sanitizer_runtime_args.sanitizer_runtime_files:
+                fail("Cannot use GNU distributed thinlto with sanitizer runtime")
+            exe = cxx_gnu_dist_link(
+                ctx,
+                output,
+                opts,
+                linker_map,
+                gc_sections_output,
+                dwp_tool_available,
+                is_result_executable,
+                build_info_json,
+            )
+            extra_outputs = {}
+        else:
+            fail("Linker type {} not supported for distributed thin-lto".format(linker_type))
+
+        return CxxLinkResult(
+            linked_object = exe,
+            linker_map_data = linker_map_data,
+            gc_sections_data = gc_sections_data,
+            link_execution_preference_info = LinkExecutionPreferenceInfo(
+                preference = opts.link_execution_preference,
+            ),
+            sanitizer_runtime_files = sanitizer_runtime_args.sanitizer_runtime_files,
+            extra_outputs = extra_outputs,
+            shared_library_interface = shared_library_interface,
+        )
+
+    link_cmd_parts = cxx_link_cmd_parts(cxx_toolchain_info, is_result_executable)
+    extra_linker_outputs = opts.extra_linker_outputs_factory(ctx) if opts.extra_linker_outputs_factory != None else ExtraLinkerOutputs()
+    split_debug_output = None
+    split_debug_lto_info = get_split_debug_lto_info(ctx.actions, cxx_toolchain_info, output.short_path)
+    if split_debug_lto_info != None:
+        split_debug_output = split_debug_lto_info.output
+    expect(not generates_split_debug(cxx_toolchain_info) or split_debug_output != None)
+    sanitizer_runtime_args = cxx_sanitizer_runtime_arguments(ctx, cxx_toolchain_info, output)
+    runtime_library_args = cxx_runtime_library_arguments(cxx_toolchain_info)
+
+    def create_local_linker_invocation(add_linker_outputs: bool) -> LinkArgsOutput:
+        if linker_map != None and add_linker_outputs:
+            links_with_linker_map = opts.links + opts.binary_links + [linker_map_args(cxx_toolchain_info, linker_map.as_output())]
+        else:
+            links_with_linker_map = opts.links + opts.binary_links
+
+        # Add gc-sections output args if enabled
+        if gc_sections_output != None and add_linker_outputs:
+            links_with_extra_args = links_with_linker_map + [gc_sections_args(cxx_toolchain_info, gc_sections_output.as_output())]
+        else:
+            links_with_extra_args = links_with_linker_map
+
+        all_link_args = cmd_args(link_cmd_parts.linker_flags)
+        if add_linker_outputs:
+            all_link_args.add(get_output_flags(linker_info.type, output))
+            if is_incremental_link:
+                all_link_args.add("/INCREMENTAL")
+            elif linker_info.type == LinkerType("windows"):
+                all_link_args.add("/INCREMENTAL:NO")
+
+        if add_linker_outputs:
+            # Add the linker args required for any extra linker outputs requested
+            if len(extra_linker_outputs.artifacts) > 0:
+                if opts.extra_linker_outputs_flags_factory == None:
+                    fail("Extra outputs requested but missing flag factory")
+
+                all_link_args.add(opts.extra_linker_outputs_flags_factory(ctx, extra_linker_outputs.artifacts))
+
+            # Darwin LTO requires extra link outputs to preserve debug info
+            if split_debug_lto_info != None:
+                all_link_args.add(split_debug_lto_info.linker_flags)
+
+        link_args_output = make_link_args(
+            ctx,
+            ctx.actions,
+            cxx_toolchain_info,
+            links_with_extra_args,
+            output_short_path = output.short_path,
+            link_ordering = opts.link_ordering,
+        )
+        all_link_args.add(link_args_output.link_args)
+
+        # Sanitizer runtime args must appear at the end because it can affect
+        # behavior of Swift runtime loading when the app also has an embedded
+        # Swift runtime.
+        all_link_args.add(sanitizer_runtime_args.extra_link_args)
+
+        # Runtime libraries the toolchain provides (e.g. compiler-rt builtins) go at
+        # the end, to match the Clang driver's placement of compiler-rt.
+        all_link_args.add(runtime_library_args)
+
+        if linker_info.thin_lto_double_codegen_enabled:
+            # This flag should only be passed to the toolchain when using local thin-lto,
+            # for distributed thin-lto the double codegen is handled differently.
+            all_link_args.add("-Wl,-mllvm,-codegen-data-thinlto-two-rounds")
+
+        all_link_args.add(link_cmd_parts.post_linker_flags)
+
+        if linker_info.type == LinkerType("windows"):
+            shell_quoted_args = cmd_args(all_link_args)
+        else:
+            shell_quoted_args = cmd_args(all_link_args, quote = "shell")
+
+        return LinkArgsOutput(link_args = shell_quoted_args, hidden = link_args_output.hidden, pdb_artifact = link_args_output.pdb_artifact)
+
+    link_unit_generation_link_args = create_local_linker_invocation(add_linker_outputs = True)
+    argfile, _ = ctx.actions.write(
+        output.short_path + ".cxx_link_argsfile",
+        link_unit_generation_link_args.link_args,
+        allow_args = True,
+        with_inputs = True,
+        has_content_based_path = cxx_toolchain_info.cxx_compiler_info.supports_content_based_paths,
+    )
+
+    if opts.produce_shared_library_interface:
+        # If we ask the linker to produce a shared library interface, it won't produce any other outputs
+        # so we shouldn't declare any extra outputs.
+        shared_library_interface_generation_linker_args = create_local_linker_invocation(add_linker_outputs = False).link_args
+        output_as_string = cmd_args(get_output_flags(linker_info.type, output), ignore_artifacts = True)
+        shared_library_interface_generation_argfile, _ = ctx.actions.write(
+            output.short_path + ".cxx_shared_library_interface_generation_argsfile",
+            cmd_args(shared_library_interface_generation_linker_args, output_as_string),
+            allow_args = True,
+            with_inputs = True,
+            has_content_based_path = cxx_toolchain_info.cxx_compiler_info.supports_content_based_paths,
+        )
+        link_cmd_parts = cxx_link_cmd_parts(cxx_toolchain_info, is_result_executable)
+        shared_library_interface_generation_command = cmd_args(
+            link_cmd_parts.linker,
+            cmd_args(shared_library_interface_generation_argfile, format = "@{}"),
+        )
+
+        shared_library_interface_generation_command.add(
+            # @oss-disable[end= ]: get_shared_library_interface_generation_linker_flags(shared_library_interface),
+            cmd_args(),
+        )
+        ctx.actions.run(
+            shared_library_interface_generation_command,
+            category = "generate_shared_library_interface",
+            identifier = opts.identifier,
+        )
+
+    bitcode_linkables = []
+    for link_item in opts.links + opts.binary_links:
+        if link_item.infos == None:
+            continue
+        for link_info in link_item.infos:
+            for linkable in link_info.linkables:
+                if isinstance(linkable, ArchiveLinkable) or isinstance(linkable, ObjectsLinkable):
+                    if linkable.bitcode_bundle != None:
+                        bitcode_linkables.append(linkable.bitcode_bundle)
+
+    if len(bitcode_linkables) > 0:
+        bitcode_artifact = make_bitcode_bundle(ctx, output.short_path + ".bc", bitcode_linkables)
+    else:
+        bitcode_artifact = None
+
+    # Pass to the link wrapper the paths to the .dwo/.o files to rewrite, if we are
+    # using split debug with content-based paths.
+    if (
+        cxx_toolchain_info.split_debug_mode != SplitDebugMode("none")
+        and cxx_toolchain_info.cxx_compiler_info.supports_content_based_paths
+        and
+        # Darwin does not embed paths in object files themselves, but rather
+        # the linker writes those paths based on the location of object files passed
+        # to the link.
+        linker_info.type != LinkerType("darwin")
+    ):
+        links_to_rewrite = make_artifact_tset(
+            ctx.actions,
+            ctx.label,
+            children = [unpack_external_debug_info(ctx.actions, link) for link in opts.links],
+        )
+        separate_debug_info_path_file, _ = ctx.actions.write(
+            output.short_path + ".split_debug_paths",
+            project_artifacts(ctx.actions, links_to_rewrite),
+            allow_args = True,
+            has_content_based_path = False,
+        )
+        separate_debug_info_args = cmd_args(
+            "--rewrite-content-based-dwo-paths",
+            separate_debug_info_path_file,
+            "--content-based-dwo-suffix",
+            ".dwo" if cxx_toolchain_info.split_debug_mode == SplitDebugMode("split") else ".o",
+        )
+    else:
+        separate_debug_info_args = []
+
+    command = cmd_args(
+        link_cmd_parts.linker,
+        separate_debug_info_args,
+        cmd_args(argfile, format = "@{}"),
+        hidden = [
+            link_unit_generation_link_args.link_args,
+            link_unit_generation_link_args.hidden,
+        ]
+        + ([ilk_artifact.as_output()] if ilk_artifact else []),
+    )
+
+    category = "cxx_link"
+    if opts.category_suffix != None:
+        category += "_" + opts.category_suffix
+
+    # If the linked object files don't contain debug info, clang may not
+    # generate a DWO directory, so make sure we at least `mkdir` and empty
+    # one to make v2/RE happy.
+    if split_debug_output != None:
+        command = cmd_args(
+            "/bin/sh",
+            "-c",
+            cmd_args(split_debug_output.as_output(), format = 'mkdir -p {}; "$@"'),
+            '""',
+            command,
+        )
+
+    link_execution_preference_info = LinkExecutionPreferenceInfo(
+        preference = opts.link_execution_preference,
+    )
+    action_execution_properties = get_action_execution_attributes(
+        opts.link_execution_preference,
+    )
+
+    enable_late_build_info_stamping = is_result_executable and cxx_stamp_build_info(ctx)
+
+    if is_incremental_link:
+        allow_cache_upload = False
+    elif enable_late_build_info_stamping:
+        allow_cache_upload = True
+    else:
+        # Preserves `None`: no preference, as opposed to a decision not to upload.
+        allow_cache_upload = opts.allow_cache_upload
+
+    ctx.actions.run(
+        command,
+        prefer_local = action_execution_properties.prefer_local and not is_incremental_link,
+        prefer_remote = action_execution_properties.prefer_remote and not is_incremental_link,
+        local_only = action_execution_properties.local_only or is_incremental_link,
+        weight = opts.link_weight,
+        category = category,
+        identifier = opts.identifier,
+        force_full_hybrid_if_capable = action_execution_properties.full_hybrid,
+        allow_cache_upload = allow_cache_upload,
+        error_handler = opts.error_handler,
+        no_outputs_cleanup = is_incremental_link,
+    )
+
+    external_debug_info = link_external_debug_info(
+        ctx = ctx,
+        links = opts.links + opts.binary_links,
+        split_debug_output = split_debug_output,
+        pdb = link_unit_generation_link_args.pdb_artifact,
+    )
+
+    unstripped_output = output
+    if opts.strip:
+        strip_args = opts.strip_args_factory(ctx) if opts.strip_args_factory else cmd_args()
+        output = strip_object(ctx, cxx_toolchain_info, output, strip_args, opts.category_suffix, allow_cache_upload = enable_late_build_info_stamping)
+
+    prebolt_output = output
+    use_bolt = is_result_executable and cxx_use_bolt(ctx)
+    if use_bolt:
+        bolt_output = bolt(ctx, output, external_debug_info, opts.identifier, dwp_tool_available, allow_cache_upload = enable_late_build_info_stamping)
+        output = bolt_output.output
+        split_debug_output = bolt_output.dwo_output
+
+    dwp_artifact = None
+    if dwp_tool_available:
+        dwp_inputs = cmd_args()
+        if use_bolt:
+            dwp_inputs.add([split_debug_output])
+        else:
+            for link in opts.links + opts.binary_links:
+                dwp_inputs.add(unpack_link_args(link))
+            dwp_inputs.add(project_artifacts(ctx.actions, external_debug_info))
+
+        dwp_artifact = dwp(
+            ctx,
+            cxx_toolchain_info,
+            output,
+            identifier = opts.identifier,
+            category_suffix = opts.category_suffix,
+            # TODO(T110378142): Ideally, referenced objects are a list of
+            # artifacts, but currently we don't track them properly.  So, we
+            # just pass in the full link line and extract all inputs from that,
+            # which is a bit of an overspecification.
+            referenced_objects = [dwp_inputs],
+            action_execution_properties = get_action_execution_attributes(
+                get_dwp_execution_preference(opts),
+            ),
+        )
+
+    # Per-TU device-debug stripping runs at compile time (compile.bzl).
+    # Rename the linker's -pre_extract output back to the canonical name.
+    if hip_debug_extract_available(cxx_toolchain_info) and output.short_path.endswith(PRE_EXTRACT_SUFFIX):
+        renamed = ctx.actions.declare_output(
+            output.short_path.removesuffix(PRE_EXTRACT_SUFFIX),
+            has_content_based_path = False,
+        )
+        ctx.actions.copy_file(renamed.as_output(), output)
+        output = renamed
+
+    if is_result_executable:
+        output = add_elf_sections_to_executable(ctx, output, has_content_based_path = output_has_content_based_path)
+        output = stamp_build_info(
+            ctx,
+            output,
+            links = opts.links,
+            build_info_json = build_info_json,
+        )
+
+    linked_object = LinkedObject(
+        output = output,
+        link_args = opts.links + opts.binary_links,
+        bitcode_bundle = bitcode_artifact.artifact if bitcode_artifact else None,
+        prebolt_output = prebolt_output,
+        unstripped_output = unstripped_output,
+        dwp = dwp_artifact,
+        external_debug_info = external_debug_info,
+        linker_argsfile = argfile,
+        linker_command = command,
+        import_library = opts.import_library,
+        pdb = link_unit_generation_link_args.pdb_artifact,
+        ilk = ilk_artifact,
+        split_debug_output = split_debug_output,
+    )
+
+    return CxxLinkResult(
+        linked_object = linked_object,
+        linker_map_data = linker_map_data,
+        gc_sections_data = gc_sections_data,
+        link_execution_preference_info = link_execution_preference_info,
+        sanitizer_runtime_files = sanitizer_runtime_args.sanitizer_runtime_files,
+        extra_outputs = extra_linker_outputs.providers,
+        shared_library_interface = shared_library_interface,
+    )
+
+_AnonLinkInfo = provider(
+    fields = {
+        "result": provider_field(typing.Any, default = None),  # CxxLinkResult
+    }
+)
+
+# dwp and split_debug_output are optional outputs, but promise artifacts require an actual artifact
+# when being resolved. Let's add some placeholders here so that we always generate an artifact when
+# applying the map functions.
+_AnonLinkInfoPlaceholder = provider(
+    fields = {
+        "dwp": provider_field(typing.Any),
+        "split_debug_output": provider_field(typing.Any),
+    }
+)
+
+def _anon_link_impl(ctx):
+    (output, result_type, opts) = deserialize_anon_attrs(ctx.actions, ctx.label, ctx.attrs)
+
+    link_result = _cxx_link(
+        ctx = ctx,
+        output = output,
+        result_type = result_type,
+        opts = opts,
+    )
+
+    dwp_placeholder = ctx.actions.write("placeholder_dwp", "", has_content_based_path = False)
+    split_debug_output_placeholder = ctx.actions.write("placeholder_split_debug_output", "", has_content_based_path = False)
+
+    return [
+        EMPTY_DEFAULT_INFO,
+        _AnonLinkInfo(result = link_result),
+        _AnonLinkInfoPlaceholder(dwp = dwp_placeholder, split_debug_output = split_debug_output_placeholder),
+    ]
+
+_anon_link_rule = anon_rule(
+    impl = _anon_link_impl,
+    attrs = ANON_ATTRS,
+    artifact_promise_mappings = {
+        "dwp": lambda p: _get_link_artifact(p, "dwp"),
+        "output": lambda p: p[_AnonLinkInfo].result.linked_object.output,
+        "split_debug_output": lambda p: _get_link_artifact(p, "split_debug_output"),
+    },
+)
+
+def _get_link_artifact(p: ProviderCollection, name: str) -> Artifact:
+    linked_object = p[_AnonLinkInfo].result.linked_object
+    if getattr(linked_object, name) != None:
+        return getattr(linked_object, name)
+    else:
+        return getattr(p[_AnonLinkInfoPlaceholder], name)
+
+def _anon_cxx_link(ctx: AnalysisContext, output: str, result_type: CxxLinkResultType, opts: LinkOptions) -> CxxLinkResult:
+    if opts.cxx_toolchain:
+        fail("anon link requires getting toolchain from ctx.attrs._cxx_toolchain")
+    cxx_toolchain = ctx.attrs._cxx_toolchain[CxxToolchainInfo]
+    anon_link_target = ctx.actions.anon_target(
+        _anon_link_rule,
+        dict(
+            _cxx_toolchain = ctx.attrs._cxx_toolchain,
+            **serialize_anon_attrs(
+                output = output,
+                result_type = result_type,
+                opts = opts,
+            ),
+        ),
+    )
+
+    dwp = None
+    if dwp_available(cxx_toolchain):
+        dwp = anon_link_target.artifact("dwp")
+
+    split_debug_output = None
+    if generates_split_debug(cxx_toolchain):
+        split_debug_output = anon_link_target.artifact("split_debug_output")
+
+    output = ctx.actions.assert_short_path(anon_link_target.artifact("output"), short_path = output)
+
+    external_debug_info = link_external_debug_info(
+        ctx = ctx,
+        links = opts.links,
+        split_debug_output = split_debug_output,
+    )
+
+    # The anon target API doesn't allow us to return the list of artifacts for
+    # sanitizer runtime, so it has be computed here
+    sanitizer_runtime_args = cxx_sanitizer_runtime_arguments(ctx, cxx_toolchain, output)
+
+    return CxxLinkResult(
+        linked_object = LinkedObject(
+            output = output,
+            unstripped_output = output,
+            dwp = dwp,
+            external_debug_info = external_debug_info,
+        ),
+        linker_map_data = None,
+        gc_sections_data = None,
+        link_execution_preference_info = LinkExecutionPreferenceInfo(
+            preference = LinkExecutionPreference("any"),
+        ),
+        sanitizer_runtime_files = sanitizer_runtime_args.sanitizer_runtime_files,
+        shared_library_interface = None,
+    )
+
+def _cxx_link(ctx: AnalysisContext, output: str, result_type: CxxLinkResultType, opts: LinkOptions, anonymous: bool = False):
+    if anonymous:
+        return _anon_cxx_link(
+            ctx = ctx,
+            output = output,
+            result_type = result_type,
+            opts = opts,
+        )
+    return cxx_link_into(
+        ctx = ctx,
+        output = ctx.actions.declare_output(output, has_content_based_path = False),
+        result_type = result_type,
+        opts = opts,
+    )
+
+def cxx_link_shared_library(
+    ctx: AnalysisContext,
+    # The destination for the link output.
+    output: str,
+    opts: LinkOptions,
+    # Optional soname to link into shared library.
+    name: [str, None] = None,
+    # Overrides the default flags used to specify building shared libraries
+    shared_library_flags: [SharedLibraryFlagOverrides, None] = None,
+    anonymous: bool = False,
+) -> CxxLinkResult:
+    # links: list[LinkArgs] = [],
+    # link_execution_preference: LinkExecutionPreference = LinkExecutionPreference("any"),
+
+    """
+    Link a shared library into the supplied output.
+    """
+    merged_opts = _build_cxx_link_shared_library_options(
+        ctx = ctx,
+        output = output,
+        opts = opts,
+        name = name,
+        shared_library_flags = shared_library_flags,
+    )
+
+    return _cxx_link(
+        ctx = ctx,
+        output = output,
+        result_type = CxxLinkResultType("shared_library"),
+        opts = merged_opts,
+        anonymous = anonymous,
+    )
+
+def _build_cxx_link_shared_library_options(
+    ctx: AnalysisContext,
+    # The destination for the link output.
+    output: str,
+    opts: LinkOptions,
+    # Optional soname to link into shared library.
+    name: [str, None] = None,
+    # Overrides the default flags used to specify building shared libraries
+    shared_library_flags: [SharedLibraryFlagOverrides, None] = None,
+) -> LinkOptions:
+    cxx_toolchain = opts.cxx_toolchain or get_cxx_toolchain_info(ctx)
+    linker_info = cxx_toolchain.linker_info
+    linker_type = linker_info.type
+    extra_args = []
+
+    extra_args.extend(get_shared_library_flags(linker_type, shared_library_flags))  # e.g. "-shared"
+    if name != None:
+        extra_args.extend(get_shared_library_name_linker_flags(linker_type, name, shared_library_flags))
+
+    link_execution_preference = opts.link_execution_preference
+    if linker_info.link_libraries_locally and link_execution_preference == LinkExecutionPreference("any"):
+        link_execution_preference = LinkExecutionPreference("local")
+
+    (import_library, import_library_args) = get_import_library(
+        ctx,
+        linker_type,
+        output,
+    )
+
+    deffile_args = get_deffile_flags(ctx, linker_type)
+
+    links_with_extra_args = [LinkArgs(flags = extra_args)] + opts.links + [LinkArgs(flags = import_library_args + deffile_args)]
+
+    return merge_link_options(
+        opts,
+        links = links_with_extra_args,
+        link_execution_preference = link_execution_preference,
+        import_library = import_library,
+    )
diff --git a/buck2/prelude/cxx/link_groups.bzl b/buck2/prelude/cxx/link_groups.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/link_groups.bzl
@@ -0,0 +1,1396 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//cxx:groups_types.bzl",
+    "Group",  # @unused Used as a type
+)
+load(
+    "@prelude//cxx:link_groups_types.bzl",
+    "LinkGroupDefinitions",
+    "LinkGroupInfo",
+    "LinkGroupsDebugLinkableEntry",
+    "LinkGroupsDebugLinkableItem",
+)
+load(
+    "@prelude//cxx:transformation_spec.bzl",
+    "TransformationSpecContext",  # @unused Used as a type
+)
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference")
+load(
+    "@prelude//linking:link_groups.bzl",
+    "LinkGroupLib",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkArgs",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkStrategy",
+    "LinkedObject",  # @unused Used as a type
+    "SharedLibLinkable",
+    "get_lib_output_style",
+    "get_link_info_for_transformation",
+    "set_link_info_link_whole",
+    "wrap_link_info",
+    "wrap_with_no_as_needed_shared_libs_flags",
+    get_link_info_from_link_infos = "get_link_info",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",  # @unused Used as a type
+    "LinkableNode",  # @unused Used as a type
+    "LinkableRootInfo",  # @unused Used as a type
+    "ReducedLinkableGraph",
+    "create_linkable_graph",
+    "get_deps_for_link",
+    "get_linkable_graph_node_map_func",
+    "get_transitive_deps",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraries",
+    "SharedLibrary",
+    "Soname",
+    "create_shlib",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    "@prelude//utils:graph_utils.bzl",
+    "depth_first_traversal_by",
+)
+load(
+    "@prelude//utils:utils.bzl",
+    "value_or",
+)
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    ":cxx_library_utility.bzl",
+    "cxx_is_gnu",
+)
+load(":cxx_toolchain_types.bzl", "LinkerType", "PicBehavior")
+load(
+    ":groups.bzl",
+    "compute_mappings",
+    "parse_groups_definitions",
+)
+load(
+    ":groups_types.bzl",
+    "MATCH_ALL_LABEL",
+    "MATCH_DIRECT_DEPS_LABEL",
+    "NO_MATCH_LABEL",
+    "should_discard_group",
+)
+load(":hip_debug_extract.bzl", "PRE_EXTRACT_SUFFIX", "hip_debug_extract_available")
+load(
+    ":link.bzl",
+    "CxxLinkerMapData",  # @unused Used as a type
+    "collect_hip_debug_from_links",
+    "cxx_link_shared_library",
+    "link_args_have_hip_device_debug",
+)
+load(
+    ":link_types.bzl",
+    "link_options",
+)
+load(
+    ":linker.bzl",
+    "get_ignore_undefined_symbols_flags",
+)
+load(
+    ":shared_library_interface.bzl",
+    "shared_library_interface",
+)
+load(
+    ":symbols.bzl",
+    "create_dynamic_list_version_script",
+    "extract_global_syms",
+    "extract_undefined_syms",
+    "get_undefined_symbols_args",
+)
+
+# TODO(cjhopman): This deserves some high-level docs about the link group linking strategy.
+
+# TODO(cjhopman): I think it would be good to document/explain why link group linking
+# strategy also uses one of the default LinkStrategy.
+
+# Returns a list of targets that belong in the current link group. If using
+# auto_link_groups, this sub_target will only be available to use with the
+# main binary, and it will return a list of all targets that map to a link
+# group.
+LINK_GROUP_MAP_DATABASE_SUB_TARGET = "link-group-map-database"
+LINK_GROUP_MAP_DATABASE_FILENAME = "link_group_map_database.json"
+
+# Returns a mapping from link group names to its constituent targets.
+LINK_GROUP_MAPPINGS_SUB_TARGET = "link-group-mappings"
+LINK_GROUP_MAPPINGS_FILENAME_SUFFIX = ".link_group_map.json"
+
+LinkGroupLinkInfo = record(
+    link_info = field(LinkInfo),
+    output_style = field(LibOutputStyle),
+    # Where this link info is originated from.
+    # Either target label or link group name
+    link_name = field(Label | str),
+)
+
+LinkGroupLibSpec = record(
+    # The output name given to the linked shared object.
+    name = field(str),
+    # Used to differentiate normal native shared libs from e.g. Python native
+    # extensions (which are technically shared libs, but don't set a SONAME
+    # and aren't managed by `SharedLibraryInfo`s).
+    is_shared_lib = field(bool, True),
+    # Optional linkable root info that should be used to "guide" the link of
+    # this link group.  This is useful for linking e.g. standalone shared libs
+    # which may require special private linker flags (like version scripts) to
+    # link.
+    root = field([LinkableRootInfo, None], None),
+    # The link group to link.
+    group = field(Group),
+    label = field(Label | None, None),
+)
+
+_LinkedLinkGroup = record(
+    artifact = field(LinkedObject),
+    library = field([LinkGroupLib, None], None),
+    linker_map_data = field([CxxLinkerMapData, None], None),
+)
+
+_LinkedLinkGroups = record(
+    libs = field(dict[str, _LinkedLinkGroup]),
+    symbol_ldflags = field(list[typing.Any], []),
+    libs_debug_info = field(dict[typing.Any, typing.Any]),
+    # Mapping from a target to a link group name it was linked into.
+    targets_consumed_by_link_groups = field(dict[Label, str]),
+)
+
+def get_link_group(ctx: AnalysisContext) -> [str, None]:
+    return ctx.attrs.link_group
+
+def build_link_group_info(graph: LinkableGraph, groups: list[Group], min_node_count: [int, None] = None) -> LinkGroupInfo:
+    linkable_graph_node_map = get_linkable_graph_node_map_func(graph)()
+
+    # Filter out groups which don't meet the node count requirement.
+    filtered_groups = {}
+    node_count = max(value_or(min_node_count, 0), len(linkable_graph_node_map))
+    for group in groups:
+        if group.attrs.enable_if_node_count_exceeds != None and node_count < group.attrs.enable_if_node_count_exceeds:
+            continue
+        filtered_groups[group.name] = group
+
+    mappings = compute_mappings(
+        groups_map = filtered_groups,
+        graph_map = linkable_graph_node_map,
+    )
+
+    return LinkGroupInfo(
+        groups = filtered_groups,
+        groups_hash = hash(str(filtered_groups)),
+        mappings = mappings,
+        # The consumer of this info may not have deps that cover that labels
+        # referenced in our roots, so propagate graphs for them.
+        # NOTE(agallagher): We do this to maintain existing behavior here
+        # but it's not clear if it's actually desirable behavior.
+        graph = graph,
+    )
+
+# `executable_deps` and `link_strategy` must be provided unless the
+# `link_group_map` is a dependency that outputs the `LinkGroupInfo` provider
+def get_link_group_info(
+    ctx: AnalysisContext, executable_deps: [list[LinkableGraph], None] = None, link_strategy: LinkStrategy | None = None
+) -> [LinkGroupInfo, None]:
+    """
+    Parses the currently analyzed context for any link group definitions
+    and returns a list of all link groups with their mappings.
+    """
+    link_group_map = ctx.attrs.link_group_map
+
+    if not link_group_map:
+        return None
+
+    # If specified as a dep that provides the `LinkGroupInfo`, use that.
+    if isinstance(link_group_map, Dependency):
+        if LinkGroupDefinitions in link_group_map:
+            definitions = link_group_map[LinkGroupDefinitions].definitions(ctx.label, link_strategy)
+            if definitions == None:
+                return None
+            return _get_link_group_info_from_definitions(ctx, executable_deps, definitions)
+        return link_group_map[LinkGroupInfo]
+
+    # Otherwise build one from our graph.
+    return _get_link_group_info_from_linkable_graph(ctx, executable_deps, ctx.attrs.link_group_map)
+
+def _get_link_group_info_from_linkable_graph(ctx: AnalysisContext, executable_deps: list[LinkableGraph], link_group_map: list) -> LinkGroupInfo:
+    link_groups = parse_groups_definitions(link_group_map)
+    return _get_link_group_info_from_definitions(ctx, executable_deps, link_groups)
+
+def _get_link_group_info_from_definitions(ctx: AnalysisContext, executable_deps: list[LinkableGraph], link_groups: list[Group]) -> LinkGroupInfo:
+    linkable_graph = create_linkable_graph(
+        ctx,
+        deps = (executable_deps + [d[LinkableGraph] for d in getattr(ctx.attrs, "link_group_deps", [])]),
+    )
+    return build_link_group_info(
+        graph = linkable_graph,
+        groups = link_groups,
+        min_node_count = getattr(ctx.attrs, "link_group_min_binary_node_count", 0),
+    )
+
+def get_link_group_preferred_linkage(link_groups: list[Group]) -> dict[Label, Linkage]:
+    root_to_linkage = {}
+    for group in link_groups:
+        for mapping in group.mappings:
+            if not mapping.roots:
+                continue
+
+            if not mapping.preferred_linkage:
+                continue
+
+            for root in mapping.roots:
+                # TODO: There might be a bug here - if the same root is listed in
+                # two different link_group_map entries, we'll only use the preferred_linkage
+                # of the last style passed.
+                root_to_linkage[root] = mapping.preferred_linkage
+
+    return root_to_linkage
+
+LinkGroupContext = record(
+    link_group_mappings = field([dict[Label, str], None]),
+    # TODO(nga): before, `Any` was `_LinkedLinkGroup`,
+    #   which was treated as `Any`, because name starts with underscore.
+    #   Put proper type here.
+    link_group_libs = field(dict[str, typing.Any]),
+    link_group_preferred_linkage = field(dict[Label, Linkage]),
+    labels_to_links_map = field(dict[Label, LinkGroupLinkInfo]),
+    # Mapping from a target to a link group name it was linked into.
+    targets_consumed_by_link_groups = field(dict[Label, str]),
+)
+
+def is_link_group_shlib(label: Label, ctx: LinkGroupContext):
+    # If this maps to a link group which we have a `LinkGroupLibInfo` for,
+    # then we'll handle this outside of this function
+    if label in ctx.link_group_mappings and ctx.link_group_mappings[label] in ctx.link_group_libs:
+        return False
+
+    # buildifier: disable=uninitialized
+    if ctx.link_group_preferred_linkage.get(label, Linkage("any")) == Linkage("shared"):
+        return True
+
+    # if using link_groups, only materialize the link_group shlibs
+    # buildifier: disable=uninitialized
+    node_link = ctx.labels_to_links_map.get(label)
+    if node_link != None and node_link.output_style == LibOutputStyle("shared_lib"):
+        return True
+
+    return False
+
+def _transitively_update_shared_linkage(
+    linkable_graph_node_map: dict[Label, LinkableNode],
+    link_group: [str, None],
+    link_strategy: LinkStrategy,
+    link_group_preferred_linkage: dict[Label, Linkage],
+    link_group_roots: dict[Label, str],
+    pic_behavior: PicBehavior,
+    link_group_mappings: [dict[Label, str], None],
+):
+    # Identify targets whose shared linkage style may be propagated to
+    # dependencies. Implicitly created root libraries are skipped.
+    shared_lib_roots = []
+
+    for target in link_group_preferred_linkage:
+        # This preferred-linkage mapping may not actually be in the link graph.
+        node = linkable_graph_node_map.get(target)
+        if node == None:
+            continue
+        prefered_linkage = link_group_preferred_linkage.get(target, node.preferred_linkage)
+        if prefered_linkage != Linkage("static"):
+            target_link_group = link_group_roots.get(target)
+            if target_link_group == None or target_link_group == link_group:
+                shared_lib_roots.append(target)
+
+    # buildifier: disable=uninitialized
+    def process_dependency(node: Label) -> list[Label] | None:
+        if link_group_mappings and link_group_mappings.get(node) == NO_MATCH_LABEL:
+            # Do not propagate shared linkage via nodes that are excluded from link groups.
+            return None
+        linkable_node = linkable_graph_node_map[node]
+        if linkable_node.preferred_linkage == Linkage("any"):
+            link_group_preferred_linkage[node] = Linkage("shared")
+        return get_deps_for_link(linkable_node, link_strategy, pic_behavior)
+
+    depth_first_traversal_by(
+        linkable_graph_node_map,
+        shared_lib_roots,
+        process_dependency,
+    )
+
+def create_debug_linkable_entries(labels_to_links_map: dict[Label, LinkGroupLinkInfo], root: Label | None) -> list[LinkGroupsDebugLinkableEntry]:
+    entries = []
+    if root:
+        root_entry = LinkGroupsDebugLinkableEntry(
+            name = root,
+            output_style = LibOutputStyle("pic_archive"),
+        )
+        entries.append(root_entry)
+
+    for link_info in labels_to_links_map.values():
+        link_groups_linkable_info = LinkGroupsDebugLinkableEntry(
+            name = link_info.link_name if type(link_info.link_name) == "string" else link_info.link_name.raw_target(),
+            output_style = link_info.output_style,
+        )
+        entries.append(link_groups_linkable_info)
+
+    return entries
+
+# This stores final information about link arguments
+# that maps to linker.argsfile for link group or final binary.
+FinalLabelsToLinks = record(
+    # Static archives and shared libraries inputs.
+    map = field(dict[Label, LinkGroupLinkInfo]),
+)
+
+def _collect_all_linkables(
+    linkable_graph: ReducedLinkableGraph,
+    is_executable_link: bool,
+    link_strategy: LinkStrategy,
+    link_group_preferred_linkage: dict[Label, Linkage],
+    pic_behavior: PicBehavior,
+    link_group_roots: dict[str, set[Label]],
+) -> dict[str, list[Label]]:
+    """
+    Given a dict of direct roots (that should be linked as archive) for each link group collects
+    all linkables for link groups that should be linked as archive and dynamically
+    """
+    linkables = {}
+
+    for link_group, roots in link_group_roots.items():
+        linkables[link_group] = collect_linkables(
+            linkable_graph,
+            is_executable_link,
+            link_strategy,
+            link_group_preferred_linkage,
+            pic_behavior,
+            roots,
+        )
+
+    return linkables
+
+def collect_linkables(
+    linkable_graph: ReducedLinkableGraph,
+    is_executable_link: bool,
+    link_strategy: LinkStrategy,
+    link_group_preferred_linkage: dict[Label, Linkage],
+    pic_behavior: PicBehavior,
+    roots: set[Label],
+) -> list[Label]:
+    def get_potential_linkables(node: Label) -> list[Label]:
+        linkable_node = linkable_graph.nodes[node]
+        if not is_executable_link and node in roots:
+            return linkable_node.all_deps
+        return get_deps_for_link(
+            linkable_node,
+            link_strategy,
+            pic_behavior,
+            link_group_preferred_linkage.get(node, linkable_node.preferred_linkage),
+        )
+
+    # Get all potential linkable targets
+    potential_linkables = depth_first_traversal_by(
+        linkable_graph.nodes,
+        roots,
+        get_potential_linkables,
+    )
+
+    if _should_fixup_link_order(link_strategy):
+        # Link groups machinery may be used by something that does not
+        # store all information in dependency graph. E.g. python native dlopen
+        # So gathering link ordering starting from executable label may not collect all
+        # dependencies correctly. To account for that we add remaining pieces to
+        # final result. There is no particular reasoning behing putting remaining linkables first,
+        # but it is just more convenient to implement.
+        # To make it work we start with `1` instead of `0` when we collect link order dict and return default `0` for linkables
+        # that we did not put into linkable graph nodes.
+        # To my best knowledge at the moment, that is only related to python that does not currently fixes up link ordering
+        # and this is more implemented for future-proofing
+        potential_linkables = sorted(potential_linkables, key = lambda node: linkable_graph.link_order.get(node, 0))
+
+    return potential_linkables
+
+# TODO(patskovn): We should have proper DFS link order everywhere.
+#                 But now certain places fail in `opt` with fixed up link order
+#                 so enabling it more gradually with future follow ups.
+def _should_fixup_link_order(link_strategy: LinkStrategy) -> bool:
+    return link_strategy == LinkStrategy("shared")
+
+BuildLinkGroupsContext = record(
+    public_nodes = field(set[Label] | None),
+    linkable_graph = field(ReducedLinkableGraph),
+    link_groups = field(dict[str, Group]),
+    link_group_mappings = field(dict[Label, str] | None),
+    link_group_preferred_linkage = field(dict[Label, Linkage]),
+    link_strategy = field(LinkStrategy),
+    pic_behavior = field(PicBehavior),
+    link_group_libs = field(dict[str, ([Label, None], LinkInfos)]),
+    link_group_roots = field(dict[str, Label] | None, None),  # If none, derived from link_group_libs
+    prefer_stripped = field(bool, False),
+    prefer_optimized = field(bool, False),
+    transformation_spec_context = field(TransformationSpecContext | None, None),
+)
+
+def get_filtered_labels_to_links_map(
+    link_group: str | None,
+    linkables: list[Label],
+    is_executable_link: bool,
+    build_context: BuildLinkGroupsContext,
+    force_static_follows_dependents: bool = True,
+    prefer_optimized = False,
+) -> FinalLabelsToLinks:
+    """
+    Given a linkable graph, link style and link group mappings, finds all links
+    to consider for linking traversing the graph as necessary and then
+    identifies which link infos and targets belong the in the provided link group.
+    If no link group is provided, all unmatched link infos are returned.
+    """
+
+    # An index of target to link group names, for all link group library nodes.
+    # Provides fast lookup of a link group root lib via it's label.
+    link_group_roots = build_context.link_group_roots
+    if link_group_roots == None:
+        link_group_roots = {label: name for name, (label, _) in build_context.link_group_libs.items() if label != None}
+
+    # Transitively update preferred linkage to avoid runtime issues from
+    # missing dependencies (e.g. for prebuilt shared libs).
+    _transitively_update_shared_linkage(
+        build_context.linkable_graph.nodes,
+        link_group,
+        build_context.link_strategy,
+        build_context.link_group_preferred_linkage,
+        link_group_roots,
+        build_context.pic_behavior,
+        build_context.link_group_mappings,
+    )
+
+    linkable_map = {}
+
+    # Keep track of whether we've already added a link group to the link line
+    # already.  This avoids use adding the same link group lib multiple times,
+    # for each of the possible multiple nodes that maps to it.
+    link_group_added = set()
+    group_srcs = {}
+
+    def add_link(target: Label, output_style: LibOutputStyle):
+        infos = build_context.linkable_graph.nodes[target].link_infos[output_style]
+
+        if build_context.transformation_spec_context:
+            link_info = get_link_info_for_transformation(
+                build_context.transformation_spec_context,
+                infos,
+                target,
+                build_context.prefer_stripped,
+            )
+        else:
+            link_info = get_link_info_from_link_infos(
+                infos,
+                build_context.prefer_stripped,
+                prefer_optimized and output_style != LibOutputStyle("shared_lib"),  # prefer_optimized is only relevant for static libs
+            )
+
+        linkable_map[target] = LinkGroupLinkInfo(
+            link_info = link_info,
+            output_style = output_style,
+            link_name = target,
+        )
+
+    def add_link_group(target: Label, target_group: str):
+        link_group_spec = build_context.link_groups.get(target_group, None)
+        if link_group_spec and link_group_spec.attrs.prohibit_file_duplicates and build_context.public_nodes and target in build_context.public_nodes:
+            if target_group not in group_srcs:
+                group_srcs[target_group] = {}
+            target_group_srcs = group_srcs[target_group]
+            for src in build_context.linkable_graph.nodes[target].srcs:
+                if not isinstance(src, Artifact):
+                    # "src" is either source file or source file with list of compilation flags.
+                    # We do not handle the case where we have compilation flags attached to source files
+                    # because it we don't know is link gonna fail or not. So we let user deal with linker errors if there are any.
+                    continue
+
+                previous_target = target_group_srcs.get(src, None)
+                if previous_target and previous_target != target:
+                    fail(
+                        "'{}' artifact included multiple times into '{}' link group. From '{}:{}' and '{}:{}'".format(
+                            src, target_group, target.package, target.name, previous_target.package, previous_target.name
+                        )
+                    )
+                else:
+                    target_group_srcs[src] = target
+
+        # If we've already added this link group to the link line, we're done.
+        if target_group in link_group_added:
+            return
+
+        # In some flows, we may not have access to the actual link group lib
+        # in our dep tree (e.g. https://fburl.com/code/pddmkptb), so just bail
+        # in this case.
+        # NOTE(agallagher): This case seems broken, as we're not going to set
+        # DT_NEEDED tag correctly, or detect missing syms at link time.
+        link_group_lib = build_context.link_group_libs.get(target_group)
+        if link_group_lib == None:
+            return
+        _, shared_link_infos = link_group_lib
+
+        expect(target_group != link_group)
+        link_group_added.add(target_group)
+        linkable_map[target] = LinkGroupLinkInfo(
+            link_info = get_link_info_from_link_infos(shared_link_infos),
+            output_style = LibOutputStyle("shared_lib"),
+            link_name = target_group,
+        )
+
+    filtered_groups = [None, NO_MATCH_LABEL, MATCH_ALL_LABEL, MATCH_DIRECT_DEPS_LABEL]
+
+    # Pre-compute which MATCH_DIRECT_DEPS targets should be included in this link group.
+    # A MATCH_DIRECT_DEPS target is included only if there's a target in the current
+    # link group which has a direct dependency on that MATCH_DIRECT_DEPS target.
+    match_direct_deps_for_current_group = set()
+    for target in linkables:
+        target_link_group = build_context.link_group_mappings.get(target)
+        if target_link_group == link_group or target_link_group == MATCH_ALL_LABEL:
+            node = build_context.linkable_graph.nodes[target]
+            for dep in node.deps + node.exported_deps:
+                dep_link_group = build_context.link_group_mappings.get(dep)
+                if dep_link_group == MATCH_DIRECT_DEPS_LABEL:
+                    match_direct_deps_for_current_group.add(dep)
+
+    output_style = (
+        get_lib_output_style(build_context.link_strategy, Linkage("any"), build_context.pic_behavior)
+        if build_context.link_strategy != LinkStrategy("shared")
+        else LibOutputStyle("shared_lib")
+    )
+
+    for target in linkables:
+        node = build_context.linkable_graph.nodes[target]
+        target_link_group = build_context.link_group_mappings.get(target)
+
+        link_group_preferred_linkage = build_context.link_group_preferred_linkage.get(target, node.preferred_linkage)
+
+        # We should always add force-static libs to the link.
+        is_force_static_lib = (
+            force_static_follows_dependents and node.preferred_linkage == Linkage("static") and not node.ignore_force_static_follows_dependents
+        )
+
+        # If this belongs to the match all link group, the group currently being
+        # evaluated, or is a MATCH_DIRECT_DEPS target that has a direct rdep in this group
+        matches_current_link_group = target_link_group == link_group or target_link_group == MATCH_ALL_LABEL or target in match_direct_deps_for_current_group
+
+        if link_group_preferred_linkage == Linkage("shared"):
+            # filter out any dependencies to be discarded
+            if should_discard_group(build_context.link_groups.get(target_link_group)):
+                continue
+
+            # If this target is a link group root library, we
+            # 1) don't propagate shared linkage down the tree, and
+            # 2) use the provided link info in lieu of what's in the grph.
+            root_link_group = link_group_roots.get(target)
+            if root_link_group != None and root_link_group != link_group:
+                add_link_group(target, root_link_group)
+            else:
+                add_link(target, LibOutputStyle("shared_lib"))
+
+        else:
+            # Shared vs static linkage branches are similar, but separated for
+            # clarity and ease of debugging.
+            if build_context.link_strategy == LinkStrategy("shared"):
+                if (target_link_group and matches_current_link_group) or is_force_static_lib:
+                    # Target linked statically if:
+                    # 1. It belongs to current link group (unique symbols across graph)
+                    # 2. It matches all link groups (can duplicate symbols across graph)
+                    # 3. It forces static linkage (can duplicate symbols across graph)
+                    if not should_discard_group(build_context.link_groups.get(target_link_group)):
+                        add_link(target, LibOutputStyle("pic_archive"))
+
+                elif not target_link_group or target_link_group == NO_MATCH_LABEL:
+                    # Target directly linked dynamically if:
+                    # 1. It doesn't belong to any link group
+                    # 2. It belongs to NO_MATCH group
+                    add_link(target, output_style)
+
+                elif target_link_group not in filtered_groups:
+                    # Targets linked through other link group dynamically if:
+                    # 1. It matches other link group
+                    add_link_group(target, target_link_group)
+
+            else:  # static or static_pic
+                # Always add force-static libs to the link.
+                if is_force_static_lib:
+                    if not should_discard_group(build_context.link_groups.get(target_link_group)):
+                        add_link(target, output_style)
+                elif not target_link_group and not link_group:
+                    # Ungrouped linkable targets belong to the unlabeled executable
+                    add_link(target, output_style)
+                elif is_executable_link and target_link_group == NO_MATCH_LABEL:
+                    # Targets labeled NO_MATCH belong to the unlabeled executable
+                    add_link(target, output_style)
+                elif matches_current_link_group:
+                    # If this belongs to the match all link group or the group currently being evaluated
+                    add_link(target, output_style)
+                elif target_link_group not in filtered_groups:
+                    add_link_group(target, target_link_group)
+
+    return FinalLabelsToLinks(
+        map = linkable_map,
+    )
+
+# Find all link group libraries that are first order deps or exported deps of
+# the exectuble or another link group's libs
+def get_public_link_group_nodes(
+    linkable_graph_node_map: dict[Label, LinkableNode],
+    link_group_mappings: [dict[Label, str], None],
+    executable_deps: list[Label],
+    root_link_group: [str, None],
+) -> set[Label]:
+    external_link_group_nodes = set()
+
+    # TODO(@christylee): do we need to traverse root link group and NO_MATCH_LABEL exported deps?
+    # buildifier: disable=uninitialized
+    def crosses_link_group_boundary(current_group: [str, None], new_group: [str, None]):
+        # belongs to root binary
+        if new_group == root_link_group:
+            return False
+
+        if new_group == NO_MATCH_LABEL:
+            # Using NO_MATCH with an explicitly defined root_link_group is undefined behavior
+            expect(root_link_group == None or root_link_group == NO_MATCH_LABEL)
+            return False
+
+        # private node in link group
+        if new_group == current_group:
+            return False
+        return True
+
+    # Check the direct deps of the executable since the executable is not in linkable_graph_node_map
+    for label in executable_deps:
+        group = link_group_mappings.get(label)
+        if crosses_link_group_boundary(root_link_group, group):
+            external_link_group_nodes.add(label)
+
+    # identify all nodes with a dependent across group boundaries
+    for label, node in linkable_graph_node_map.items():
+        current_group = link_group_mappings.get(label)
+
+        for dep in node.deps + node.exported_deps:
+            new_group = link_group_mappings.get(dep)
+            if crosses_link_group_boundary(current_group, new_group):
+                external_link_group_nodes.add(dep)
+
+    SPECIAL_LINK_GROUPS = [MATCH_ALL_LABEL, MATCH_DIRECT_DEPS_LABEL, NO_MATCH_LABEL]
+
+    # Additionally identify exported_deps of those marked nodes (except those included in all groups or included in the main executable).
+
+    # TODO(@christylee): dlopen-able libs that depend on the main executable does not have a
+    # linkable internal edge to the main executable. Symbols that are not referenced during the
+    # executable link might be dropped unless the dlopen-able libs are linked against the main
+    # executable. We need to force export those symbols to avoid undefined symbls.
+
+    # buildifier: disable=uninitialized
+    def discover_link_group_linkables(node: Label) -> list[Label]:
+        exported_deps = []
+        for exported_dep in linkable_graph_node_map[node].exported_deps:
+            group = link_group_mappings.get(exported_dep)
+            if group != root_link_group and group not in SPECIAL_LINK_GROUPS:
+                exported_deps.append(exported_dep)
+        return exported_deps
+
+    external_link_group_nodes.update(
+        # get transitive exported deps
+        depth_first_traversal_by(
+            linkable_graph_node_map,
+            external_link_group_nodes,
+            discover_link_group_linkables,
+        ),
+    )
+
+    return external_link_group_nodes
+
+def get_filtered_links(labels_to_links_map: dict[Label, LinkGroupLinkInfo], public_link_group_nodes: [set[Label], None] = None) -> list[LinkInfo]:
+    if public_link_group_nodes == None:
+        return [link_group_info.link_info for link_group_info in labels_to_links_map.values()]
+    infos = []
+    for label, link_group_info in labels_to_links_map.items():
+        info = link_group_info.link_info
+        if label in public_link_group_nodes:
+            infos.append(set_link_info_link_whole(info))
+        else:
+            infos.append(info)
+    return infos
+
+def get_filtered_targets(labels_to_links_map: dict[Label, LinkGroupLinkInfo]):
+    # labels_to_links_map will include entries for shared link group libraries
+    # as well as libraries being statically linked into this link unit.
+    statically_linked_targets = []
+    for label, info in labels_to_links_map.items():
+        if info.output_style != LibOutputStyle("shared_lib"):
+            statically_linked_targets.append(label.raw_target())
+
+    return statically_linked_targets
+
+def get_link_group_map_json(ctx: AnalysisContext, targets: list[TargetLabel]) -> DefaultInfo:
+    json_map = ctx.actions.write_json(LINK_GROUP_MAP_DATABASE_FILENAME, sorted(targets), pretty = True, has_content_based_path = False)
+    return DefaultInfo(default_output = json_map)
+
+def _find_all_relevant_roots(
+    specs: list[LinkGroupLibSpec],
+    link_group_mappings: dict[Label, str],  # target label to link group name
+    roots: list[Label],
+    link_strategy: LinkStrategy,
+    linkable_graph_node_map: dict[Label, LinkableNode],
+) -> dict[str, set[Label]]:
+    relevant_roots = {}
+    link_groups_for_full_traversal = set()  # list[str]
+
+    # For shared linkage we need to always traverse whole graph to discover
+    # roots because `_collect_linkables` (next step in algorithm) stops linkables discovery
+    # early due to shared link strategy semantics
+    always_traverse_all_roots = link_strategy == LinkStrategy("shared")
+
+    for spec in specs:
+        if spec.root != None:
+            relevant_roots[spec.group.name] = set(spec.root.deps)
+        else:
+            roots_from_mappings, has_empty_root = _get_roots_from_mappings(spec, linkable_graph_node_map)
+            relevant_roots[spec.group.name] = set(roots_from_mappings)
+            if has_empty_root or always_traverse_all_roots:
+                link_groups_for_full_traversal.add(spec.group.name)
+
+    def collect_and_traverse_roots(node_target: Label) -> list[Label]:
+        node = linkable_graph_node_map.get(node_target)
+        if node.preferred_linkage == Linkage("static") and not node.ignore_force_static_follows_dependents:
+            return node.all_deps
+
+        node_link_group = link_group_mappings.get(node_target)
+
+        if node_link_group == MATCH_ALL_LABEL:
+            # Add node into the list of roots for all link groups
+            for link_group in relevant_roots.keys():
+                relevant_roots[link_group].add(node_target)
+        elif node_link_group in link_groups_for_full_traversal and node_link_group != NO_MATCH_LABEL:
+            relevant_roots[node_link_group].add(node_target)
+
+        # For MATCH_DIRECT_DEPS support: if this node belongs to a real link group and has
+        # a direct dep on a MATCH_DIRECT_DEPS target, add that target to this link group
+        if node_link_group and node_link_group in relevant_roots:
+            for dep in node.deps + node.exported_deps:
+                dep_link_group = link_group_mappings.get(dep)
+                if dep_link_group == MATCH_DIRECT_DEPS_LABEL:
+                    relevant_roots[node_link_group].add(dep)
+
+        return node.all_deps
+
+    depth_first_traversal_by(
+        linkable_graph_node_map,
+        roots,
+        collect_and_traverse_roots,
+    )
+
+    return relevant_roots
+
+def find_relevant_roots(
+    link_group: [str, None] = None, linkable_graph_node_map: dict[Label, LinkableNode] = {}, link_group_mappings: dict[Label, str] = {}, roots: list[Label] = []
+):
+    # Walk through roots looking for the first node which maps to the current
+    # link group.
+
+    def collect_and_traverse_roots(roots, node_target: Label) -> list[Label] | None:
+        node = linkable_graph_node_map.get(node_target)
+        if node.preferred_linkage == Linkage("static") and not node.ignore_force_static_follows_dependents:
+            return node.all_deps
+
+        node_link_group = link_group_mappings.get(node_target)
+
+        if node_link_group == MATCH_ALL_LABEL:
+            roots.append(node_target)
+        elif node_link_group == link_group:
+            roots.append(node_target)
+
+            # For MATCH_DIRECT_DEPS support: if this node has a direct dep on a MATCH_DIRECT_DEPS target,
+            # add that target to the roots for this link group
+            for dep in node.deps + node.exported_deps:
+                dep_link_group = link_group_mappings.get(dep)
+                if dep_link_group == MATCH_DIRECT_DEPS_LABEL:
+                    roots.append(dep)
+        else:
+            return node.all_deps
+
+        return None
+
+    relevant_roots = []
+
+    depth_first_traversal_by(
+        linkable_graph_node_map,
+        roots,
+        partial(collect_and_traverse_roots, relevant_roots),
+    )
+
+    return relevant_roots
+
+def _get_roots_from_mappings(spec: LinkGroupLibSpec, linkable_graph_node_map: dict[Label, LinkableNode]) -> (list[Label], bool):
+    roots = []
+    has_empty_root = False
+    for mapping in spec.group.mappings:
+        # If there's no explicit root, this means we need to search the entire
+        # graph to find candidate nodes.
+        if not mapping.roots:
+            has_empty_root = True
+        elif spec.group.attrs.requires_root_node_exists:
+            # If spec requires root to always exist (default True), always include to traversal to fail hard if it is not in deps.
+            # Otherwise add to traversal only if we sure it is in deps graph.
+            roots.extend(mapping.roots)
+        else:
+            roots.extend([root for root in mapping.roots if root in linkable_graph_node_map])
+    return (roots, has_empty_root)
+
+_CreatedLinkGroup = record(
+    linked_object = field(LinkedObject),
+    labels_to_links = field(FinalLabelsToLinks),
+    linker_map_data = field([CxxLinkerMapData, None], None),
+)
+
+_CreateLinkGroupParams = record(
+    category_suffix = field(str),
+    anonymous = field(bool),
+    allow_cache_upload = field(bool),
+    error_handler = field([typing.Callable, None]),
+    build_groups_context = field(BuildLinkGroupsContext),
+)
+
+def _create_link_group(
+    ctx: AnalysisContext, spec: LinkGroupLibSpec, linkables: list[Label], linker_flags: list[typing.Any], params: _CreateLinkGroupParams
+) -> _CreatedLinkGroup | None:
+    """
+    Link a link group library, described by a `LinkGroupLibSpec`.  This is
+    intended to handle regular shared libs and e.g. Python extensions.
+    """
+
+    inputs = []
+
+    # Add extra linker flags.
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    linker_type = linker_info.type
+    inputs.append(
+        LinkInfo(
+            pre_flags = linker_flags
+            +
+            # There's scenarios where we no required syms won't be on the root
+            # link lines (e.g. syms from executable), so we need to ignore
+            # undefined symbols.
+            get_ignore_undefined_symbols_flags(linker_type),
+        )
+    )
+
+    if spec.root != None:
+        # If there's a linkable root attached to the spec, use that to guide
+        # linking, as that will contain things like private linker flags that
+        # might be required to link the given link group.
+        inputs.append(
+            get_link_info_from_link_infos(
+                spec.root.link_infos,
+                prefer_stripped = params.build_groups_context.prefer_stripped,
+            )
+        )
+
+    # Add roots...
+    filtered_labels_to_links = get_filtered_labels_to_links_map(
+        link_group = spec.group.name,
+        linkables = linkables,
+        is_executable_link = False,
+        build_context = params.build_groups_context,
+        prefer_optimized = spec.group.attrs.prefer_optimized_experimental,
+    )
+    inputs.extend(get_filtered_links(filtered_labels_to_links.map, params.build_groups_context.public_nodes))
+
+    if not filtered_labels_to_links.map and not spec.root:
+        # don't create empty shared libraries
+        return None
+
+    # Determine link execution preference for this link group
+    # Default to "any" if not specified on the link group
+    link_exec_pref = spec.group.attrs.link_execution_preference
+    if link_exec_pref:
+        # If link_exec_pref is an Artifact (source file), extract the basename
+        # This happens when strings are specified in BUCK file attribute dictionaries
+        link_exec_pref = getattr(link_exec_pref, "basename", link_exec_pref)
+        link_execution_preference = LinkExecutionPreference(link_exec_pref)
+    else:
+        link_execution_preference = LinkExecutionPreference("any")
+
+    link_args = [LinkArgs(infos = inputs)]
+    needs_extract = hip_debug_extract_available(get_cxx_toolchain_info(ctx)) and link_args_have_hip_device_debug(link_args)
+    output_name = spec.name + PRE_EXTRACT_SUFFIX if needs_extract else spec.name
+
+    # link the rule
+    link_result = cxx_link_shared_library(
+        ctx = ctx,
+        output = paths.join("__link_groups__", output_name),
+        name = spec.name if spec.is_shared_lib else None,
+        opts = link_options(
+            links = link_args,
+            category_suffix = params.category_suffix,
+            identifier = spec.name,
+            # TODO: anonymous targets cannot be used with dynamic output yet
+            enable_distributed_thinlto = False if params.anonymous else spec.group.attrs.enable_distributed_thinlto,
+            link_execution_preference = link_execution_preference,
+            allow_cache_upload = params.allow_cache_upload,
+            error_handler = params.error_handler,
+        ),
+        anonymous = params.anonymous,
+    )
+    linked_obj = link_result.linked_object
+    hip_debug = collect_hip_debug_from_links(link_args)
+    if hip_debug:
+        linked_obj = LinkedObject(
+            output = linked_obj.output,
+            bitcode_bundle = linked_obj.bitcode_bundle,
+            unstripped_output = linked_obj.unstripped_output,
+            prebolt_output = linked_obj.prebolt_output,
+            link_args = linked_obj.link_args,
+            dwp = linked_obj.dwp,
+            hip_arch_debug_files = hip_debug,
+            external_debug_info = linked_obj.external_debug_info,
+            linker_argsfile = linked_obj.linker_argsfile,
+            linker_command = linked_obj.linker_command,
+            index_argsfile = linked_obj.index_argsfile,
+            import_library = linked_obj.import_library,
+            pdb = linked_obj.pdb,
+            split_debug_output = linked_obj.split_debug_output,
+        )
+
+    return _CreatedLinkGroup(
+        linked_object = linked_obj,
+        labels_to_links = filtered_labels_to_links,
+        linker_map_data = link_result.linker_map_data,
+    )
+
+def _stub_library(
+    ctx: AnalysisContext, name: str, extra_ldflags: list[typing.Any] = [], anonymous: bool = False, link_libraries_locally: bool = False
+) -> LinkInfos:
+    # When link_libraries_locally is active, explicitly request remote execution
+    # for stub libraries to avoid I/O contention from hundreds of trivial local
+    # links. Otherwise, use "any" to let Buck2 choose (default behavior).
+    stub_execution_preference = LinkExecutionPreference("remote") if link_libraries_locally else LinkExecutionPreference("any")
+    link_result = cxx_link_shared_library(
+        ctx = ctx,
+        output = name + ".stub",
+        name = name,
+        opts = link_options(
+            links = [LinkArgs(flags = extra_ldflags)],
+            identifier = name,
+            category_suffix = "stub_library",
+            link_execution_preference = stub_execution_preference,
+            # Anonymous stubs are canonical (owner-independent) and tiny, so
+            # sharing them through the action cache is cheap and lets other
+            # owners/builds skip the link entirely.
+            allow_cache_upload = anonymous,
+        ),
+        anonymous = anonymous,
+    )
+    toolchain_info = get_cxx_toolchain_info(ctx)
+    linker_info = toolchain_info.linker_info
+    return LinkInfos(
+        # Since we link against empty stub libraries, `--as-needed` will end up
+        # removing `DT_NEEDED` tags that we actually need at runtime, so pass in
+        # `--no-as-needed` last to make sure this is overridden.
+        # TODO(agallagher): It'd be nice to at least support a mode where we
+        # don't need to use empty stub libs.
+        default = wrap_with_no_as_needed_shared_libs_flags(
+            linker_type = linker_info.type,
+            link_info = LinkInfo(
+                linkables = [SharedLibLinkable(lib = link_result.linked_object.output)],
+            ),
+        ),
+    )
+
+def _symbol_files_for_link_group(
+    ctx: AnalysisContext, lib: LinkedObject, prefer_local: bool = False, anonymous: bool = False, hash_counter = 0
+) -> (Artifact, Artifact):
+    """
+    Find and return all undefined and global symbols form the given library.
+    """
+
+    # Extract undefined symbols.
+    undefined_symfile = extract_undefined_syms(
+        ctx = ctx,
+        cxx_toolchain = get_cxx_toolchain_info(ctx),
+        output = lib.output,
+        category_prefix = "link_groups",
+        prefer_local = prefer_local,
+        anonymous = anonymous,
+        hash_counter = hash_counter,
+    )
+
+    # Extract global symbols.
+    global_symfile = extract_global_syms(
+        ctx = ctx,
+        cxx_toolchain = get_cxx_toolchain_info(ctx),
+        output = lib.output,
+        category_prefix = "link_groups",
+        prefer_local = prefer_local,
+        anonymous = anonymous,
+    )
+
+    return undefined_symfile, global_symfile
+
+def _symbol_flags_for_link_groups(
+    ctx: AnalysisContext, linker_type: LinkerType, undefined_symfiles: list[Artifact] = [], global_symfiles: list[Artifact] = []
+) -> list[ArgLike]:
+    """
+    Generate linker flags which, when applied to the main executable, make sure
+    required symbols are included in the link *and* exported to the dynamic
+    symbol table.
+    """
+
+    sym_linker_flags = []
+
+    # Format undefined symbols into an argsfile with `-u`s, and add to linker
+    # flags.
+    sym_linker_flags.append(
+        get_undefined_symbols_args(
+            ctx = ctx,
+            name = "undefined_symbols_args",
+            symbol_files = undefined_symfiles,
+            category = "link_groups_undefined_syms_args",
+        ),
+    )
+
+    # Format global symfiles into a dynamic list version file, and add to
+    # linker flags.
+    dynamic_list_vers = create_dynamic_list_version_script(
+        actions = ctx.actions,
+        name = "dynamic_list.vers",
+        symbol_files = global_symfiles,
+        category = "link_groups_dynamic_list",
+    )
+
+    if linker_type == LinkerType("gnu"):
+        sym_linker_flags.extend([
+            "-Wl,--dynamic-list",
+            dynamic_list_vers,
+        ])
+
+    return sym_linker_flags
+
+def create_link_groups(
+    ctx: AnalysisContext,
+    public_nodes: set[Label],
+    link_strategy: LinkStrategy,
+    linkable_graph: ReducedLinkableGraph,
+    link_groups: dict[str, Group] = {},
+    link_group_specs: list[LinkGroupLibSpec] = [],
+    executable_deps: list[Label] = [],
+    other_roots: list[Label] = [],
+    linker_flags: list[typing.Any] = [],
+    prefer_stripped_objects: bool = False,
+    link_group_preferred_linkage: dict[Label, Linkage] = {},
+    link_group_mappings: [dict[Label, str], None] = None,
+    anonymous: bool = False,
+    allow_cache_upload = False,
+    transformation_spec_context: TransformationSpecContext | None = None,
+    error_handler: [typing.Callable, None] = None,
+) -> _LinkedLinkGroups:
+    # We linking libraries here so we need pic
+    if link_strategy == LinkStrategy("static"):
+        link_strategy = LinkStrategy("static_pic")
+
+    # Generate stubs first, so that subsequent links can link against them.
+    link_group_shared_links = {}
+    specs = []
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    for link_group_spec in link_group_specs:
+        if should_discard_group(link_group_spec.group):
+            # Don't create a link group for deps that we want to drop
+            continue
+        specs.append(link_group_spec)
+
+        # always add libraries that are not constructed from link groups
+        if link_group_spec.is_shared_lib:
+            link_group_shared_links[link_group_spec.group.name] = _stub_library(
+                ctx = ctx,
+                name = link_group_spec.name,
+                extra_ldflags = linker_flags,
+                anonymous = anonymous,
+                link_libraries_locally = linker_info.link_libraries_locally or False,
+            )
+
+    targets_consumed_by_link_groups = {}
+    linked_link_groups = {}
+    link_groups_debug_info = {}
+    undefined_symfiles = []
+    global_symfiles = []
+    roots = _find_all_relevant_roots(
+        specs,
+        link_group_mappings,
+        executable_deps + other_roots,
+        link_strategy,
+        linkable_graph.nodes,
+    )
+
+    pic_behavior = get_cxx_toolchain_info(ctx).pic_behavior
+    if pic_behavior == PicBehavior("supported"):
+        pic_behavior = PicBehavior("always_enabled")
+    linkables = _collect_all_linkables(
+        linkable_graph = linkable_graph,
+        is_executable_link = False,
+        link_strategy = link_strategy,
+        link_group_preferred_linkage = link_group_preferred_linkage,
+        pic_behavior = pic_behavior,
+        link_group_roots = roots,
+    )
+
+    link_group_libs = {name: (None, lib) for name, lib in link_group_shared_links.items()}
+
+    build_groups_context = BuildLinkGroupsContext(
+        public_nodes = public_nodes,
+        linkable_graph = linkable_graph,
+        link_groups = link_groups,
+        link_group_mappings = link_group_mappings,
+        link_strategy = link_strategy,
+        link_group_preferred_linkage = link_group_preferred_linkage,
+        pic_behavior = get_cxx_toolchain_info(ctx).pic_behavior,
+        link_group_libs = link_group_libs,
+        # TODO(agallagher): Should we support alternate link strategies
+        # (e.g. bottom-up with symbol errors)?
+        link_group_roots = {},
+        prefer_stripped = prefer_stripped_objects,
+        transformation_spec_context = transformation_spec_context,
+    )
+
+    create_link_group_params = _CreateLinkGroupParams(
+        category_suffix = "link_group",
+        anonymous = anonymous,
+        allow_cache_upload = allow_cache_upload,
+        error_handler = error_handler,
+        build_groups_context = build_groups_context,
+    )
+
+    toolchain_info = get_cxx_toolchain_info(ctx)
+    linker_info = toolchain_info.linker_info
+
+    for counter, link_group_spec in enumerate(specs):
+        # NOTE(agallagher): It might make sense to move this down to be
+        # done when we generated the links for the executable, so we can
+        # handle the case when a link group can depend on the executable.
+        created_link_group = _create_link_group(
+            ctx = ctx,
+            spec = link_group_spec,
+            linkables = linkables[link_group_spec.group.name],
+            linker_flags = (
+                linker_flags
+                + link_group_spec.group.attrs.linker_flags
+                + link_group_spec.group.attrs.exported_linker_flags
+                + ([cmd_args(link_group_spec.group.attrs.linker_script, format = "-Wl,--script={}")] if link_group_spec.group.attrs.linker_script else [])
+                + (
+                    [cmd_args(link_group_spec.group.attrs.version_script, format = "-Wl,--version-script={}")]
+                    if link_group_spec.group.attrs.version_script
+                    else []
+                )
+            ),
+            params = create_link_group_params,
+        )
+
+        if created_link_group == None:
+            # the link group did not match anything, don't create shlib interface
+            continue
+
+        link_group_lib = created_link_group.linked_object
+
+        root_label = link_group_spec.root.label if link_group_spec.root else None
+        link_groups_debug_info[link_group_spec.name] = LinkGroupsDebugLinkableItem(
+            ordered_linkables = create_debug_linkable_entries(created_link_group.labels_to_links.map, root_label),
+        )
+
+        for linked_target, link_info in created_link_group.labels_to_links.map.items():
+            if link_info.output_style != LibOutputStyle("shared_lib"):
+                # Remember all targets that were statically linked into link group
+                targets_consumed_by_link_groups[linked_target] = link_group_spec.group.name
+
+        if link_group_spec.root:
+            # If link group has root it always being linked statically
+            targets_consumed_by_link_groups[link_group_spec.root.label] = link_group_spec.group.name
+
+        # On GNU, use shlib interfaces when the tool is available.
+        if cxx_is_gnu(ctx) and get_cxx_toolchain_info(ctx).linker_info.mk_shlib_intf != None:
+            shlib_for_link = shared_library_interface(
+                ctx = ctx,
+                shared_lib = link_group_lib.output,
+                anonymous = anonymous,
+            )
+        else:
+            shlib_for_link = link_group_lib.output
+
+        link_info = wrap_link_info(
+            LinkInfo(
+                linkables = [SharedLibLinkable(lib = shlib_for_link)],
+            ),
+            pre_flags = link_group_spec.group.attrs.exported_linker_flags,
+        )
+
+        if link_group_spec.group.attrs.no_as_needed:
+            link_info = wrap_with_no_as_needed_shared_libs_flags(
+                linker_type = linker_info.type,
+                link_info = link_info,
+            )
+
+        linked_link_groups[link_group_spec.group.name] = _LinkedLinkGroup(
+            artifact = link_group_lib,
+            library = None
+            if not link_group_spec.is_shared_lib
+            else LinkGroupLib(
+                shared_libs = SharedLibraries(
+                    libraries = [
+                        create_shlib(
+                            label = link_group_spec.label or ctx.label,
+                            soname = link_group_spec.name,
+                            lib = link_group_lib,
+                        ),
+                    ],
+                ),
+                shared_link_infos = LinkInfos(
+                    default = link_info,
+                ),
+            ),
+            linker_map_data = created_link_group.linker_map_data,
+        )
+
+        # Merge and format all symbol files into flags that we can pass into
+        # the binary link.
+        undefined_symfile, global_symfile = _symbol_files_for_link_group(
+            ctx = ctx,
+            lib = link_group_lib,
+            anonymous = anonymous,
+            hash_counter = counter,
+        )
+        undefined_symfiles.append(undefined_symfile)
+        global_symfiles.append(global_symfile)
+
+    # Add linker flags to make sure any symbols from the main executable
+    # needed by these link groups are pulled in and exported to the dynamic
+    # symbol table.
+    symbol_ldflags = []
+    if linked_link_groups:
+        symbol_ldflags.extend(
+            _symbol_flags_for_link_groups(
+                ctx = ctx,
+                linker_type = linker_info.type,
+                undefined_symfiles = undefined_symfiles,
+                global_symfiles = global_symfiles,
+            ),
+        )
+
+    return _LinkedLinkGroups(
+        libs = linked_link_groups,
+        symbol_ldflags = symbol_ldflags,
+        libs_debug_info = link_groups_debug_info,
+        targets_consumed_by_link_groups = targets_consumed_by_link_groups,
+    )
+
+def get_transitive_deps_matching_labels(linkable_graph_node_map: dict[Label, LinkableNode], roots: list[Label], label: str) -> list[Label]:
+    # NOTE: Our Haskell DLL support impl currently links transitive haskell
+    # deps needed by DLLs which get linked into the main executable as link-
+    # whole.  To emulate this, we mark Haskell rules with a special label
+    # and traverse this to find all the nodes we need to link whole.
+    nodes = []
+    for dep in get_transitive_deps(linkable_graph_node_map, roots):
+        linkable = linkable_graph_node_map[dep]
+        if label not in linkable.labels:
+            continue
+        nodes.append(dep)
+    return nodes
+
+def build_shared_libs_for_symlink_tree(
+    use_link_groups: bool,
+    link_group_ctx: LinkGroupContext,
+    link_strategy: LinkStrategy,
+    shared_libraries: list[SharedLibrary],
+    extra_shared_libraries: list[SharedLibrary],
+) -> list[SharedLibrary]:
+    # Which targets we actually materialized as symlinks to link group
+    added_link_group_symlinks_libs = set()
+    symlink_tree_shared_libraries = []
+
+    def is_shlib_added(soname: Soname) -> bool:
+        return soname.is_str and soname.ensure_str() in added_link_group_symlinks_libs
+
+    def add_shib(shlib: SharedLibrary):
+        if shlib.soname.is_str:
+            added_link_group_symlinks_libs.add(shlib.soname.ensure_str())
+        symlink_tree_shared_libraries.append(shlib)
+
+    if use_link_groups:
+        # When there are no matches for a pattern based link group,
+        # `link_group_mappings` will not have an entry associated with the lib.
+        for _name, link_group_lib in link_group_ctx.link_group_libs.items():
+            for link_group_shlib in link_group_lib.shared_libs.libraries:
+                add_shib(link_group_shlib)
+
+    for shlib in shared_libraries:
+        if is_shlib_added(shlib.soname):
+            # Shlib was already materialised as link group.
+            # This may happen if link group spec had this target
+            # as root. That will produce link group with exact
+            # .so file and dynamic linker will be satisfied.
+            continue
+
+        if link_strategy == LinkStrategy("shared") and shlib.label in link_group_ctx.targets_consumed_by_link_groups:
+            link_group_link = create_link_group_link(
+                link_group_ctx.link_group_libs[link_group_ctx.targets_consumed_by_link_groups[shlib.label]],
+                shlib,
+            )
+            add_shib(link_group_link)
+
+        elif not use_link_groups or is_link_group_shlib(shlib.label, link_group_ctx) or link_strategy == LinkStrategy("shared"):
+            add_shib(shlib)
+
+    # Add in extra, rule-specific shared libs.
+    for extra_shlib in extra_shared_libraries:
+        if not is_shlib_added(extra_shlib.soname):
+            add_shib(extra_shlib)
+
+    return symlink_tree_shared_libraries
+
+def create_link_group_link(link_group_lib: LinkGroupLib, consumed_library: SharedLibrary) -> SharedLibrary:
+    """
+    This method implements symlinking from original .so to link group .so
+    for link groups in **dynamic linking**.
+    Current problem is: with following setup
+    ```
+        :bin
+       |    |
+      :A   :C
+       |    │
+       └ :B ┘
+    ```
+
+    If we put `:A` and `:B` to link group, `lib_c.so` will still add `lib_b.so` to `NEEDS` section.
+    But `lib_b.so` is gonna be grouped to `lib_a_b_lg.so` and there is no way to propagate this information to `lib_c.so`.
+    But we actually can have "stubs" for `lib_a.so` and `lib_b.so` that all point to actual `lib_a_b_lg.so`.
+    This approach satisfies dynamic linker.
+    """
+
+    if len(link_group_lib.shared_libs.libraries) != 1:
+        fail("This method should only be used with auto link groups that produce exactly one shared libray")
+    link_group_shlib = link_group_lib.shared_libs.libraries[0]
+
+    return create_shlib(
+        lib = link_group_shlib.lib,
+        link_args = link_group_shlib.link_args,
+        shlib_deps = link_group_shlib.shlib_deps,
+        can_be_asset = link_group_shlib.can_be_asset,
+        soname = consumed_library.soname,  # <=== we match original target soname that will symlink to link group
+        label = consumed_library.label,
+    )
diff --git a/buck2/prelude/cxx/link_groups_types.bzl b/buck2/prelude/cxx/link_groups_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/link_groups_types.bzl
@@ -0,0 +1,98 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkStrategy",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load(":groups_types.bzl", "Group", "GroupFilterInfo", "Traversal")
+
+# These are targets or link groups that will be added to .linker.argsfile
+# Targets will be expanded to .o files, link groups will be added to NEEDS
+LinkGroupsDebugLinkableEntry = record(
+    name = field(TargetLabel | Label | str),
+    output_style = field(LibOutputStyle),
+)
+
+# This is info about single output unit. It is either a final binary or
+# one of link groups.
+LinkGroupsDebugLinkableItem = record(
+    ordered_linkables = field(list[LinkGroupsDebugLinkableEntry]),
+)
+
+LinkGroupsDebugLinkInfo = record(
+    binary = field(LinkGroupsDebugLinkableItem),
+    libs = field(dict[str, LinkGroupsDebugLinkableItem]),
+)
+
+LinkGroupInfo = provider(
+    fields = {
+        # Additional graphs needed to cover labels referenced by the groups above.
+        # This is useful in cases where the consumer of this provider won't already
+        # have deps covering these.
+        # NOTE(agallagher): We do this to maintain existing behavior w/ the
+        # standalone `link_group_map()` rule, but it's not clear if it's actually
+        # desirable behavior.
+        "graph": provider_field(typing.Any, default = None),  # LinkableGraph
+        "groups": provider_field(dict[str, Group]),
+        "groups_hash": provider_field(int),
+        "mappings": provider_field(dict[Label, str]),
+    },
+)
+
+LinkGroupDefinitions = provider(
+    fields = {
+        # The label is the top-level target
+        "definitions": provider_field(typing.Callable[[Label, LinkStrategy], list[Group] | None]),
+    },
+)
+
+_FILTER_ATTR = attrs.one_of(attrs.dep(providers = [GroupFilterInfo]), attrs.string())
+
+def link_group_inlined_map_attr(root_attr):
+    return attrs.list(
+        attrs.tuple(
+            # name
+            attrs.string(),
+            # list of mappings
+            attrs.list(
+                # a single mapping
+                attrs.tuple(
+                    # root node
+                    attrs.one_of(root_attr, attrs.list(root_attr)),
+                    # traversal
+                    attrs.enum(Traversal.values()),
+                    # filters, either `None`, a single filter, or a list of filters
+                    # (which must all match).
+                    attrs.option(attrs.one_of(attrs.list(_FILTER_ATTR), _FILTER_ATTR)),
+                    # linkage
+                    attrs.option(attrs.enum(Linkage.values())),
+                ),
+            ),
+            # attributes
+            attrs.option(
+                attrs.dict(key = attrs.string(), value = attrs.one_of(attrs.source(), attrs.any()), sorted = False),
+            ),
+        ),
+    )
+
+LINK_GROUP_MAP_ATTR = attrs.option(
+    attrs.one_of(
+        attrs.dep(),  # LinkGroupInfo or LinkGroupInfoGenerator
+        link_group_inlined_map_attr(
+            # Inlined `link_group_map` will parse roots as `label`s, to avoid
+            # bloating deps w/ unrelated mappings (e.g. it's common to use
+            # a default mapping for all rules, which would otherwise add
+            # unrelated deps to them).
+            root_attr = attrs.option(attrs.label()),
+        ),
+    ),
+    default = None,
+)
diff --git a/buck2/prelude/cxx/link_types.bzl b/buck2/prelude/cxx/link_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/link_types.bzl
@@ -0,0 +1,185 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkArgs",
+    "LinkOrdering",
+)
+
+CxxLinkResultType = enum(
+    "executable",
+    "shared_library",
+)
+
+ExtraLinkerOutputCategory = enum(
+    "produced-during-local-link",
+    "produced-during-distributed-thin-lto-native-link",
+    "produced-during-distributed-thin-lto-opt",
+)
+
+LinkOptions = record(
+    # link args for binary link step
+    binary_links = field(list[LinkArgs]),
+    # common link args
+    links = list[LinkArgs],
+    link_execution_preference = LinkExecutionPreference,
+    # Execution preference for the `dwp` action that packages the split debug
+    # info of the linked output, if the toolchain produces one.
+    #
+    # `None` (the default) means "whatever the link itself uses", which is the
+    # historical behavior: dwp ran alongside the link to avoid round-tripping
+    # dwo files. Set this explicitly when the link has to be local for reasons
+    # that do not apply to dwp (e.g. build-info stamping), so that dwp is not
+    # dragged onto the local host with it.
+    dwp_execution_preference = field([LinkExecutionPreference, None], None),
+    link_weight = int,
+    link_ordering = [LinkOrdering, None],
+    enable_distributed_thinlto = bool,
+    # A category suffix that will be added to the category of the link action that is generated.
+    category_suffix = [str, None],
+    # An identifier that will uniquely name this link action in the context of a category. Useful for
+    # differentiating multiple link actions in the same rule.
+    identifier = [str, None],
+    strip = bool,
+    # A function/lambda which will generate the strip args using the ctx.
+    strip_args_factory = [typing.Callable, None],
+    import_library = Artifact | None,
+    # `None` expresses no preference, leaving the choice to buck2
+    allow_cache_upload = [bool, None],
+    cxx_toolchain = [CxxToolchainInfo, None],
+    # Force callers to use link_options() or merge_link_options() to create.
+    __private_use_link_options_function_to_construct = None,
+    error_handler = [typing.Callable, None],
+    # Factory methods used to provide extra linker outputs and flags, to
+    # both local and distributed links.
+    extra_linker_outputs_factory = field(typing.Callable | None, None),
+    extra_linker_outputs_flags_factory = field(typing.Callable | None, None),
+    extra_distributed_thin_lto_opt_outputs_merger = field(typing.Callable | None, None),
+    produce_shared_library_interface = field(bool, False),
+    incremental_link = field(bool, False),
+    has_hip_device_debug = field(bool, False),
+)
+
+def link_options(
+    links: list[LinkArgs],
+    link_execution_preference: LinkExecutionPreference,
+    dwp_execution_preference: [LinkExecutionPreference, None] = None,
+    link_weight: int = 1,
+    binary_links: list[LinkArgs] = [],
+    link_ordering: [LinkOrdering, None] = None,
+    enable_distributed_thinlto: bool = False,
+    category_suffix: [str, None] = None,
+    identifier: [str, None] = None,
+    strip: bool = False,
+    strip_args_factory = None,
+    import_library: Artifact | None = None,
+    allow_cache_upload: [bool, None] = False,
+    cxx_toolchain: [CxxToolchainInfo, None] = None,
+    error_handler: [typing.Callable, None] = None,
+    extra_linker_outputs_factory: typing.Callable | None = None,
+    extra_linker_outputs_flags_factory: typing.Callable | None = None,
+    extra_distributed_thin_lto_opt_outputs_merger: typing.Callable | None = None,
+    produce_shared_library_interface: bool = False,
+    incremental_link: bool = False,
+    has_hip_device_debug: bool = False,
+) -> LinkOptions:
+    """
+    A type-checked constructor for LinkOptions because by default record
+    constructors aren't typed.
+    """
+    return LinkOptions(
+        binary_links = binary_links,
+        links = links,
+        link_execution_preference = link_execution_preference,
+        dwp_execution_preference = dwp_execution_preference,
+        link_weight = link_weight,
+        link_ordering = link_ordering,
+        enable_distributed_thinlto = enable_distributed_thinlto,
+        category_suffix = category_suffix,
+        identifier = identifier,
+        strip = strip,
+        strip_args_factory = strip_args_factory,
+        import_library = import_library,
+        allow_cache_upload = allow_cache_upload,
+        cxx_toolchain = cxx_toolchain,
+        __private_use_link_options_function_to_construct = None,
+        error_handler = error_handler,
+        extra_linker_outputs_factory = extra_linker_outputs_factory,
+        extra_linker_outputs_flags_factory = extra_linker_outputs_flags_factory,
+        extra_distributed_thin_lto_opt_outputs_merger = extra_distributed_thin_lto_opt_outputs_merger,
+        produce_shared_library_interface = produce_shared_library_interface,
+        incremental_link = incremental_link,
+        has_hip_device_debug = has_hip_device_debug,
+    )
+
+# A marker instance to differentiate explicitly-passed None and a field that
+# isn't provided in merge_link_options.
+_NotProvided = record()
+_NOT_PROVIDED = _NotProvided()
+
+def merge_link_options(
+    base: LinkOptions,
+    binary_links: [list[LinkArgs], _NotProvided] = _NOT_PROVIDED,
+    links: [list[LinkArgs], _NotProvided] = _NOT_PROVIDED,
+    link_execution_preference: [LinkExecutionPreference, _NotProvided] = _NOT_PROVIDED,
+    dwp_execution_preference: [LinkExecutionPreference, None, _NotProvided] = _NOT_PROVIDED,
+    link_weight: [int, _NotProvided] = _NOT_PROVIDED,
+    link_ordering: [LinkOrdering, None, _NotProvided] = _NOT_PROVIDED,
+    enable_distributed_thinlto: [bool, _NotProvided] = _NOT_PROVIDED,
+    category_suffix: [str, None, _NotProvided] = _NOT_PROVIDED,
+    identifier: [str, None, _NotProvided] = _NOT_PROVIDED,
+    strip: [bool, _NotProvided] = _NOT_PROVIDED,
+    strip_args_factory = _NOT_PROVIDED,
+    import_library: [Artifact, None, _NotProvided] = _NOT_PROVIDED,
+    allow_cache_upload: [bool, None, _NotProvided] = _NOT_PROVIDED,
+    cxx_toolchain: [CxxToolchainInfo, _NotProvided] = _NOT_PROVIDED,
+    incremental_link: [bool, _NotProvided] = _NOT_PROVIDED,
+) -> LinkOptions:
+    """
+    Also something we would ideally auto-generate as LinkOptions.merge in
+    Starlark.
+    """
+
+    return LinkOptions(
+        binary_links = base.binary_links if binary_links == _NOT_PROVIDED else binary_links,
+        links = base.links if links == _NOT_PROVIDED else links,
+        link_execution_preference = base.link_execution_preference if link_execution_preference == _NOT_PROVIDED else link_execution_preference,
+        dwp_execution_preference = base.dwp_execution_preference if dwp_execution_preference == _NOT_PROVIDED else dwp_execution_preference,
+        link_weight = base.link_weight if link_weight == _NOT_PROVIDED else link_weight,
+        link_ordering = base.link_ordering if link_ordering == _NOT_PROVIDED else link_ordering,
+        enable_distributed_thinlto = base.enable_distributed_thinlto if enable_distributed_thinlto == _NOT_PROVIDED else enable_distributed_thinlto,
+        category_suffix = base.category_suffix if category_suffix == _NOT_PROVIDED else category_suffix,
+        identifier = base.identifier if identifier == _NOT_PROVIDED else identifier,
+        strip = base.strip if strip == _NOT_PROVIDED else strip,
+        strip_args_factory = base.strip_args_factory if strip_args_factory == _NOT_PROVIDED else strip_args_factory,
+        import_library = base.import_library if import_library == _NOT_PROVIDED else import_library,
+        allow_cache_upload = base.allow_cache_upload if allow_cache_upload == _NOT_PROVIDED else allow_cache_upload,
+        cxx_toolchain = base.cxx_toolchain if cxx_toolchain == _NOT_PROVIDED else cxx_toolchain,
+        __private_use_link_options_function_to_construct = None,
+        error_handler = base.error_handler,
+        extra_linker_outputs_factory = base.extra_linker_outputs_factory,
+        extra_linker_outputs_flags_factory = base.extra_linker_outputs_flags_factory,
+        extra_distributed_thin_lto_opt_outputs_merger = base.extra_distributed_thin_lto_opt_outputs_merger,
+        produce_shared_library_interface = base.produce_shared_library_interface,
+        incremental_link = base.incremental_link if incremental_link == _NOT_PROVIDED else incremental_link,
+        has_hip_device_debug = base.has_hip_device_debug,
+    )
+
+def get_dwp_execution_preference(opts: LinkOptions) -> LinkExecutionPreference:
+    """
+    The execution preference the `dwp` action for this link should run with.
+
+    Defaults to the link's own preference, so callers that do not care keep
+    dwp next to the link.
+    """
+    if opts.dwp_execution_preference != None:
+        return opts.dwp_execution_preference
+    return opts.link_execution_preference
diff --git a/buck2/prelude/cxx/linker.bzl b/buck2/prelude/cxx/linker.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/linker.bzl
@@ -0,0 +1,336 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerInfo", "LinkerType")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load("@prelude//utils:expect.bzl", "expect")
+
+# Platform-specific linker flags handling.  Modeled after the `Linker` abstraction
+# in v1 (https://fburl.com/diffusion/kqd2ylcy).
+# TODO(T110378136): It might make more sense to pass these in via the toolchain.
+Linker = record(
+    # Given the soname for the shared library, how to format the install name argument
+    shared_library_install_name_format = str,
+    # The extension to use for the shared library if not set in the toolchain.
+    default_shared_library_extension = str,
+    # The format to use for the versioned shared library extension if not set in the toolchain.
+    default_shared_library_versioned_extension_format = str,
+    # How to format arguments to the linker to set a shared lib name.
+    shared_library_name_linker_flags_format = list[str],
+    # Flags to pass to the linker to make it generate a shared library.
+    shared_library_flags = list[str],
+)
+
+# Allows overriding the default shared library flags.
+# e.g. when building Apple tests, we want to link with `-bundle` instead of `-shared` to allow
+# linking against the bundle loader.
+SharedLibraryFlagOverrides = record(
+    # How to format arguments to the linker to set a shared lib name.
+    shared_library_name_linker_flags_format = list[str],
+    # Flags to pass to the linker to make it generate a shared library.
+    shared_library_flags = list[ArgLike],
+)
+
+DARWIN_SHARED_LIBRARY_INSTALL_NAME_FORMAT_STRING = "@rpath/{}"
+
+LINKERS = {
+    LinkerType("darwin"): Linker(
+        shared_library_install_name_format = DARWIN_SHARED_LIBRARY_INSTALL_NAME_FORMAT_STRING,
+        default_shared_library_extension = "dylib",
+        default_shared_library_versioned_extension_format = "{}.dylib",
+        shared_library_name_linker_flags_format = ["-install_name", DARWIN_SHARED_LIBRARY_INSTALL_NAME_FORMAT_STRING],
+        shared_library_flags = ["-shared"],
+    ),
+    LinkerType("gnu"): Linker(
+        shared_library_install_name_format = "{}",
+        default_shared_library_extension = "so",
+        default_shared_library_versioned_extension_format = "so.{}",
+        shared_library_name_linker_flags_format = ["-Wl,-soname,{}"],
+        shared_library_flags = ["-shared"],
+    ),
+    LinkerType("wasm"): Linker(
+        shared_library_install_name_format = "{}",
+        default_shared_library_extension = "wasm",
+        default_shared_library_versioned_extension_format = "{}.wasm",
+        shared_library_name_linker_flags_format = [],
+        # lld supports this, at least.
+        # See https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md#llvm-implementation
+        shared_library_flags = ["-shared"],
+    ),
+    LinkerType("windows"): Linker(
+        shared_library_install_name_format = "{}",
+        default_shared_library_extension = "dll",
+        default_shared_library_versioned_extension_format = "dll",
+        # NOTE(agallagher): I *think* windows doesn't support a flag to set the
+        # library name, and relies on the basename.
+        shared_library_name_linker_flags_format = [],
+        shared_library_flags = ["/DLL"],
+    ),
+}
+
+IMPORT_LIBRARY_SUB_TARGET = "implib"
+PDB_SUB_TARGET = "pdb"
+
+def _sanitize(s: str) -> str:
+    return s.replace("/", "_")
+
+# NOTE(agallagher): Does this belong in the native/shared_libraries.bzl?
+def get_shared_library_name(linker_info: LinkerInfo, short_name: str, apply_default_prefix: bool, version: [str, None] = None):
+    """
+    Generate a platform-specific shared library name based for the given rule.
+    """
+    if version == None:
+        full_name = linker_info.shared_library_name_format.format(short_name)
+    else:
+        full_name = linker_info.shared_library_versioned_name_format.format(short_name, version)
+
+    if apply_default_prefix:
+        full_name = linker_info.shared_library_name_default_prefix + full_name
+
+    return full_name
+
+def _parse_ext_macro(name: str) -> [(str, [str, None]), None]:
+    """
+    Parse the `$(ext[ <version>])` macro from a user-specific library name,
+    which expands to a platform-specific suffix (e.g. `.so`, `.dylib`).  If an
+    optional version argument is given (e.g. `$(ext 3.4)`) it expands to a
+    platform-specific versioned suffix (e.g. `.so.3.4`, `.3.4.dylib`).
+    """
+
+    # If there's no macro, then there's nothing to do.
+    if ".$(ext" not in name:
+        return None
+    expect(name.endswith(")"))
+
+    # Otherwise, attempt to parse out the macro.
+    base, rest = name.split(".$(ext")
+
+    # If the macro is arg-less, then return w/o a version.
+    if rest == ")":
+        return (base, None)
+
+    # Otherwise, extract the version from the arg.
+    expect(rest.startswith(" "))
+    return (base, rest[1:-1])
+
+def get_shared_library_name_for_param(linker_info: LinkerInfo, name: str):
+    """
+    Format a user-provided shared library name, supporting v1's `$(ext)` suffix.
+    """
+    parsed = _parse_ext_macro(name)
+    if parsed != None:
+        base, version = parsed
+        name = get_shared_library_name(
+            linker_info,
+            base,
+            apply_default_prefix = False,
+            version = version,
+        )
+    return name
+
+# NOTE(agallagher): Does this belong in the native/shared_libraries.bzl?
+def get_default_shared_library_name(linker_info: LinkerInfo, label: Label):
+    """
+    Generate a platform-specific shared library name based for the given rule.
+    """
+
+    # TODO(T110378119): v1 doesn't use the cell/repo name, so we don't here for
+    # initial compatibility, but maybe we should?
+    short_name = "{}_{}".format(_sanitize(label.package), _sanitize(label.name))
+    return get_shared_library_name(linker_info, short_name, apply_default_prefix = True)
+
+def get_shared_library_name_linker_flags(linker_type: LinkerType, soname: str, flag_overrides: [SharedLibraryFlagOverrides, None] = None) -> list[str]:
+    """
+    Arguments to pass to the linker to set the given soname.
+    """
+    if flag_overrides:
+        shared_library_name_linker_flags_format = flag_overrides.shared_library_name_linker_flags_format
+    else:
+        shared_library_name_linker_flags_format = LINKERS[linker_type].shared_library_name_linker_flags_format
+
+    return [f.format(soname) for f in shared_library_name_linker_flags_format]
+
+def get_shared_library_flags(linker_type: LinkerType, flag_overrides: [SharedLibraryFlagOverrides, None] = None) -> list[ArgLike]:
+    """
+    Arguments to pass to the linker to link a shared library.
+    """
+    if flag_overrides:
+        return flag_overrides.shared_library_flags
+
+    return LINKERS[linker_type].shared_library_flags
+
+def get_link_whole_args(linker_type: LinkerType, inputs: list[Artifact]) -> list[typing.Any]:
+    """
+    Return linker args used to always link all the given inputs.
+    """
+
+    args = []
+
+    if linker_type == LinkerType("gnu"):
+        args.append("-Wl,--whole-archive")
+        args.extend(inputs)
+        args.append("-Wl,--no-whole-archive")
+    elif linker_type == LinkerType("darwin"):
+        for inp in inputs:
+            args.append("-Xlinker")
+            args.append("-force_load")
+            args.append("-Xlinker")
+            args.append(inp)
+    elif linker_type == LinkerType("windows"):
+        for inp in inputs:
+            args.append(cmd_args(inp, format = "/WHOLEARCHIVE:{}"))
+    elif linker_type == LinkerType("wasm"):
+        args.append("--whole-archive")
+        args.extend(inputs)
+        args.append("--no-whole-archive")
+    else:
+        fail("Linker type {} not supported".format(linker_type))
+
+    return args
+
+def get_objects_as_library_args(linker_type: LinkerType, objects: list[Artifact]) -> list[typing.Any]:
+    """
+    Return linker args used to link the given objects as a library.
+    """
+
+    args = []
+
+    if linker_type == LinkerType("gnu"):
+        args.append("-Wl,--start-lib")
+        args.extend(objects)
+        args.append("-Wl,--end-lib")
+    elif linker_type == LinkerType("darwin") or linker_type == LinkerType("windows") or linker_type == LinkerType("wasm"):
+        args.extend(objects)
+    else:
+        fail("Linker type {} not supported".format(linker_type))
+
+    return args
+
+def get_ignore_undefined_symbols_flags(linker_type: LinkerType) -> list[str]:
+    """
+    Return linker args used to suppress undefined symbol errors.
+    """
+
+    args = []
+
+    if linker_type == LinkerType("gnu"):
+        args.append("-Wl,--allow-shlib-undefined")
+        args.append("-Wl,--unresolved-symbols=ignore-all")
+    elif linker_type == LinkerType("darwin"):
+        args.append("-Wl,-undefined,dynamic_lookup")
+    else:
+        fail("Linker type {} not supported".format(linker_type))
+
+    return args
+
+def get_no_as_needed_shared_libs_flags(linker_type: LinkerType) -> list[str]:
+    """
+    Return linker args used to prevent linkers from dropping unused shared
+    library dependencies from the e.g. DT_NEEDED tags of the link.
+    """
+
+    args = []
+
+    if linker_type == LinkerType("gnu"):
+        args.append("-Wl,--no-as-needed")
+    elif linker_type == LinkerType("darwin"):
+        pass
+    else:
+        fail("Linker type {} not supported".format(linker_type))
+
+    return args
+
+def get_output_flags(linker_type: LinkerType, output: Artifact) -> list[ArgLike]:
+    if linker_type == LinkerType("windows"):
+        return ["/Brepro", cmd_args(output.as_output(), format = "/OUT:{}")]
+    else:
+        return ["-o", output.as_output()]
+
+def get_import_library(ctx: AnalysisContext, linker_type: LinkerType, output_short_path: str) -> (Artifact | None, list[ArgLike]):
+    if linker_type == LinkerType("windows"):
+        import_library = ctx.actions.declare_output(output_short_path + ".imp.lib", has_content_based_path = False)
+        return import_library, [cmd_args(import_library.as_output(), format = "/IMPLIB:{}")]
+    else:
+        return None, []
+
+def get_deffile_flags(ctx: AnalysisContext, linker_type: LinkerType) -> list[ArgLike]:
+    if linker_type == LinkerType("windows") and ctx.attrs.deffile != None:
+        return [
+            cmd_args(ctx.attrs.deffile, format = "/DEF:{}"),
+        ]
+    else:
+        return []
+
+def get_rpath_origin(linker_type: LinkerType) -> str:
+    """
+    Return the macro that runtime loaders resolve to the main executable at
+    runtime.
+    """
+
+    if linker_type in (LinkerType("gnu"), LinkerType("wasm")):
+        return "$ORIGIN"
+    if linker_type == LinkerType("darwin"):
+        return "@loader_path"
+
+    fail("Linker type {} not supported".format(linker_type))
+
+def is_pdb_generated(linker_type: LinkerType, linker_flags: list[[str, ResolvedStringWithMacros]]) -> bool:
+    if linker_type != LinkerType("windows"):
+        return False
+    for flag in reversed(linker_flags):
+        flag = str(flag).upper()
+        if flag.startswith('"/DEBUG') or flag.startswith('"-DEBUG'):
+            # The last one should be not /DEBUG:NONE
+            return not flag.endswith('DEBUG:NONE"')
+    return False
+
+def get_pdb_providers(pdb: Artifact, binary: Artifact):
+    return [DefaultInfo(default_output = pdb, other_outputs = [binary])]
+
+DUMPBIN_SUB_TARGET = "dumpbin"
+
+def get_dumpbin_providers(ctx: AnalysisContext, binary: Artifact, dumpbin_toolchain_path: Artifact) -> list[Provider]:
+    dumpbin_headers_out = ctx.actions.declare_output(binary.short_path + ".dumpbin_headers", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(
+            cmd_args(dumpbin_toolchain_path, format = "{}/dumpbin.exe"),
+            # We could use /ALL to display all information in one action, but that's too
+            # expensive in practice
+            "/HEADERS",
+            binary,
+            cmd_args(dumpbin_headers_out.as_output(), format = "/OUT:{}"),
+        ),
+        category = "dumpbin_headers",
+        identifier = binary.short_path,
+    )
+    return [
+        DefaultInfo(
+            sub_targets = {
+                "headers": [
+                    DefaultInfo(
+                        default_output = dumpbin_headers_out,
+                    )
+                ],
+            }
+        )
+    ]
+
+def sandbox_exported_linker_flags(linker_info: LinkerInfo, flags: list[typing.Any], post_flags: list[typing.Any]) -> (list[typing.Any], list[typing.Any]):
+    """
+    Helper to wrap exported pre/post linker flags with sandboxing flags (e.g.
+    `--push-state`/`--pop-state`) only if flags are actually non-empty.
+    """
+
+    # If we're exporting flags, wrap in push/pop state flags to provide some
+    # level of sandboxing.
+    if linker_info.push_pop_state_flags != None and (flags or post_flags):
+        push_state_flags, pop_state_flags = linker_info.push_pop_state_flags
+        flags = push_state_flags + flags
+        post_flags = post_flags + pop_state_flags
+
+    return (flags, post_flags)
diff --git a/buck2/prelude/cxx/omnibus.bzl b/buck2/prelude/cxx/omnibus.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/omnibus.bzl
@@ -0,0 +1,785 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:local_only.bzl", "get_resolved_cxx_binary_link_execution_preference")
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "LinkerType",
+    "PicBehavior",
+)
+load(
+    "@prelude//cxx:link.bzl",
+    "CxxLinkResult",  # @unused Used as a type
+    "cxx_link_shared_library",
+)
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkArgs",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkStrategy",
+    "LinkedObject",
+    "SharedLibLinkable",
+    "get_lib_output_style",
+    "link_info_to_args",
+    get_link_info_from_link_infos = "get_link_info",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",  # @unused Used as a type
+    "LinkableNode",
+    "LinkableRootInfo",
+    "get_deps_for_link",
+    "get_link_info",
+    "get_transitive_deps",
+    "linkable_deps",
+    "linkable_graph",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",  # @unused Used as a type
+    "create_shlib",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    "@prelude//utils:graph_utils.bzl",
+    "depth_first_traversal_by",
+    "post_order_traversal",
+)
+load("@prelude//utils:utils.bzl", "flatten", "value_or")
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    ":link_types.bzl",
+    "link_options",
+)
+load(
+    ":linker.bzl",
+    "get_default_shared_library_name",
+    "get_ignore_undefined_symbols_flags",
+    "get_no_as_needed_shared_libs_flags",
+    "get_shared_library_name",
+    "sandbox_exported_linker_flags",
+)
+load(
+    ":symbols.bzl",
+    "create_global_symbols_version_script",
+    "extract_global_syms",
+    "extract_symbol_names",
+    "extract_undefined_syms",
+    "get_undefined_symbols_args",
+)
+
+OmnibusEnvironment = provider(
+    # @unsorted-dict-items
+    fields = {
+        "dummy_omnibus": provider_field(typing.Any, default = None),
+        "exclusions": provider_field(typing.Any, default = None),
+        "roots": provider_field(typing.Any, default = None),
+        "enable_explicit_roots": provider_field(typing.Any, default = None),
+        "prefer_stripped_objects": provider_field(typing.Any, default = None),
+        "shared_root_ld_flags": provider_field(typing.Any, default = None),
+        "force_hybrid_links": provider_field(typing.Any, default = None),
+    },
+)
+
+Disposition = enum("root", "excluded", "body", "omitted")
+
+OmnibusGraph = record(
+    nodes = field(dict[Label, LinkableNode]),
+    # All potential root notes for an omnibus link (e.g. C++ libraries,
+    # C++ Python extensions).
+    roots = field(dict[Label, LinkableRootInfo]),
+    # All nodes that should be excluded from libomnibus.
+    excluded = field(dict[Label, None]),
+)
+
+# Bookkeeping information used to setup omnibus link rules.
+OmnibusSpec = record(
+    body = field(dict[Label, None], {}),
+    excluded = field(dict[Label, None], {}),
+    roots = field(dict[Label, LinkableRootInfo], {}),
+    exclusion_roots = field(list[Label]),
+    # All link infos.
+    link_infos = field(dict[Label, LinkableNode], {}),
+    dispositions = field(dict[Label, Disposition]),
+)
+
+OmnibusPrivateRootProductCause = record(
+    category = field(str),
+    # Miss-assigned label
+    label = field([Label, None], default = None),
+    # Its actual disposiiton
+    disposition = field([Disposition, None], default = None),
+)
+
+OmnibusRootProduct = record(
+    shared_library = field(LinkedObject),
+    undefined_syms = field(Artifact),
+    global_syms = field(Artifact),
+)
+
+# The result of the omnibus link.
+OmnibusSharedLibraries = record(
+    omnibus = field([CxxLinkResult, None], None),
+    libraries = field(list[SharedLibrary], []),
+    roots = field(dict[Label, OmnibusRootProduct], {}),
+    exclusion_roots = field(list[Label]),
+    excluded = field(list[Label]),
+    dispositions = field(dict[Label, Disposition]),
+)
+
+def get_omnibus_graph(graph: LinkableGraph, roots: dict[Label, LinkableRootInfo], excluded: dict[Label, None]) -> OmnibusGraph:
+    graph_nodes = graph.nodes.traverse()
+    nodes = {}
+    for node in filter(None, graph_nodes):
+        if node.linkable:
+            nodes[node.label] = node.linkable
+        roots.update(node.roots)
+        excluded.update(node.excluded)
+    return OmnibusGraph(nodes = nodes, roots = roots, excluded = excluded)
+
+def get_roots(deps: list[Dependency]) -> dict[Label, LinkableRootInfo]:
+    roots = {}
+    for dep in deps:
+        if LinkableRootInfo in dep:
+            root = dep[LinkableRootInfo]
+            roots[root.label] = root
+    return roots
+
+def get_excluded(deps: list[Dependency] = []) -> dict[Label, None]:
+    excluded_nodes = {}
+    for dep in deps:
+        dep_info = linkable_graph(dep)
+        if dep_info != None:
+            excluded_nodes[dep_info.label] = None
+    return excluded_nodes
+
+def create_linkable_root(label: Label, link_infos: LinkInfos, name: [str, None] = None, deps: list[LinkableGraph | Dependency] = []) -> LinkableRootInfo:
+    # Only include dependencies that are linkable.
+    return LinkableRootInfo(
+        label = label,
+        name = name,
+        link_infos = link_infos,
+        deps = linkable_deps(deps),
+    )
+
+def _omnibus_soname(ctx, name: str):
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    return get_shared_library_name(linker_info, name, apply_default_prefix = True)
+
+def create_dummy_omnibus(ctx: AnalysisContext, omnibus_lib_name: str, extra_ldflags: list[typing.Any] = [], anonymous: bool = False) -> Artifact:
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    link_result = cxx_link_shared_library(
+        ctx = ctx,
+        output = get_shared_library_name(linker_info, "omnibus-dummy", apply_default_prefix = True),
+        name = _omnibus_soname(ctx, omnibus_lib_name),
+        opts = link_options(
+            links = [LinkArgs(flags = extra_ldflags)],
+            category_suffix = "dummy_omnibus",
+            link_execution_preference = LinkExecutionPreference("any"),
+            produce_shared_library_interface = False,
+        ),
+        anonymous = anonymous,
+    )
+    return link_result.linked_object.output
+
+def _link_deps(link_infos: dict[Label, LinkableNode], deps: list[Label], pic_behavior: PicBehavior) -> list[Label]:
+    """
+    Return transitive deps required to link dynamically against the given deps.
+    This will following through deps of statically linked inputs and exported
+    deps of everything else (see https://fburl.com/diffusion/rartsbkw from v1).
+    """
+
+    def find_deps(node: Label):
+        return get_deps_for_link(link_infos[node], LinkStrategy("shared"), pic_behavior)
+
+    return depth_first_traversal_by(link_infos, deps, find_deps)
+
+def _create_root(
+    ctx: AnalysisContext,
+    spec: OmnibusSpec,
+    root_products: dict[Label, OmnibusRootProduct],
+    root: LinkableRootInfo,
+    label: Label,
+    link_deps: list[Label],
+    omnibus: Artifact,
+    pic_behavior: PicBehavior,
+    extra_ldflags: list[typing.Any] = [],
+    prefer_stripped_objects: bool = False,
+    allow_cache_upload: bool = False,
+    anonymous: bool = False,
+    hash_counter = 0,
+) -> OmnibusRootProduct:
+    """
+    Link a root omnibus node.
+    """
+
+    toolchain_info = get_cxx_toolchain_info(ctx)
+    linker_info = toolchain_info.linker_info
+    linker_type = linker_info.type
+
+    inputs = []
+
+    # Since we're linking against a dummy omnibus which has no symbols, we need
+    # to make sure the linker won't drop it from the link or complain about
+    # missing symbols.
+    inputs.append(
+        LinkInfo(
+            pre_flags = get_ignore_undefined_symbols_flags(linker_type),
+        )
+    )
+
+    # add native target link input
+    inputs.append(
+        get_link_info_from_link_infos(
+            root.link_infos,
+            prefer_stripped = prefer_stripped_objects,
+        ),
+    )
+
+    # Link to Omnibus
+    if spec.body:
+        pre_flags, post_flags = sandbox_exported_linker_flags(
+            linker_info = linker_info,
+            flags = get_no_as_needed_shared_libs_flags(linker_type),
+            post_flags = [],
+        )
+        inputs.append(
+            LinkInfo(
+                pre_flags = pre_flags,
+                linkables = [SharedLibLinkable(lib = omnibus)],
+                post_flags = post_flags,
+            )
+        )
+
+    # Add deps of the root to the link line.
+    for dep in link_deps:
+        node = spec.link_infos[dep]
+        output_style = get_lib_output_style(
+            LinkStrategy("shared"),
+            node.preferred_linkage,
+            pic_behavior,
+        )
+
+        # If this dep needs to be linked statically, then link it directly.
+        if output_style != LibOutputStyle("shared_lib"):
+            inputs.append(
+                get_link_info(
+                    node,
+                    output_style,
+                    prefer_stripped = prefer_stripped_objects,
+                )
+            )
+            continue
+
+        # If this is another root.
+        if dep in spec.roots:
+            other_root = root_products[dep]
+
+            # TODO(cjhopman): This should be passing structured linkables
+            inputs.append(LinkInfo(linkables = [SharedLibLinkable(lib = other_root.shared_library.output)]))
+            continue
+
+        # If this node is in omnibus, just add that to the link line.
+        if dep in spec.body:
+            continue
+
+        # At this point, this should definitely be an excluded node.
+        expect(dep in spec.excluded, str(dep))
+
+        # We should have already handled statically linked nodes above.
+        expect(output_style == LibOutputStyle("shared_lib"))
+        inputs.append(get_link_info(node, output_style))
+
+    output = value_or(
+        root.name,
+        get_default_shared_library_name(
+            linker_info,
+            label,
+        ),
+    )
+
+    # link the rule
+    link_result = cxx_link_shared_library(
+        ctx = ctx,
+        output = output,
+        name = root.name,
+        opts = link_options(
+            links = [LinkArgs(flags = extra_ldflags), LinkArgs(infos = inputs)],
+            category_suffix = "omnibus_root",
+            identifier = root.name or output,
+            link_execution_preference = LinkExecutionPreference("any"),
+            allow_cache_upload = allow_cache_upload,
+            produce_shared_library_interface = False,
+        ),
+        anonymous = anonymous,
+    )
+    shared_library = link_result.linked_object
+
+    return OmnibusRootProduct(
+        shared_library = shared_library,
+        global_syms = extract_global_syms(
+            ctx,
+            cxx_toolchain = toolchain_info,
+            output = shared_library.output,
+            category_prefix = "omnibus",
+            # Same as above.
+            prefer_local = not anonymous,
+            allow_cache_upload = allow_cache_upload,
+            anonymous = anonymous,
+        ),
+        undefined_syms = extract_undefined_syms(
+            ctx,
+            cxx_toolchain = toolchain_info,
+            output = shared_library.output,
+            # Don't extract weak-undefined symbols, as passing these back into
+            # the omnibus link via `-u` causes undefined sym link failures.
+            weak = False,
+            category_prefix = "omnibus",
+            # Same as above.
+            prefer_local = not anonymous,
+            allow_cache_upload = allow_cache_upload,
+            hash_counter = hash_counter,
+            anonymous = anonymous,
+        ),
+    )
+
+def _extract_global_symbols_from_link_args(
+    ctx: AnalysisContext, name: str, link_args: list[[Artifact, ResolvedStringWithMacros, cmd_args, str]], prefer_local: bool = False
+) -> Artifact:
+    """
+    Extract global symbols explicitly set in the given linker args (e.g.
+    `-Wl,--export-dynamic-symbol=<sym>`).
+    """
+
+    # TODO(T110378137): This is ported from D24065414, but it might make sense
+    # to explicitly tell Buck about the global symbols, rather than us trying to
+    # extract it from linker flags (which is brittle).
+    output = ctx.actions.declare_output(name, has_content_based_path = False)
+
+    # We intentionally drop the artifacts referenced in the args when generating
+    # the argsfile -- we just want to parse out symbol name flags and don't need
+    # to materialize artifacts to do this.
+    argsfile, _ = ctx.actions.write(name + ".args", link_args, allow_args = True, has_content_based_path = False)
+
+    # TODO(T110378133): Make this work with other platforms.
+    param = "--export-dynamic-symbol"
+    pattern = "\\(-Wl,\\)\\?{}[,=]\\([^,]*\\)".format(param)
+
+    # Used sed/grep to filter the symbol name from the relevant flags.
+    # TODO(T110378130): As is the case in v1, we don't properly extract flags
+    # from argsfiles embedded in existing args.
+    script = "set -euo pipefail; " + "cat \"$@\" | (grep -- '{0}' || [[ $? == 1 ]]) | sed 's|{0}|\\2|' | LC_ALL=C sort -S 10% -u > {{}}".format(pattern)
+    ctx.actions.run(
+        [
+            "/usr/bin/env",
+            "bash",
+            "-c",
+            cmd_args(output.as_output(), format = script),
+            "",
+            argsfile,
+        ],
+        category = "omnibus_global_symbol_flags",
+        prefer_local = prefer_local,
+        weight_percentage = 15,  # 10% + a little padding
+    )
+    return output
+
+def _create_global_symbols_version_script(
+    ctx: AnalysisContext, roots: list[OmnibusRootProduct], excluded: list[Artifact], link_args: list[[Artifact, ResolvedStringWithMacros, cmd_args, str]]
+) -> Artifact:
+    """
+    Generate a version script exporting symbols from from the given objects and
+    link args.
+    """
+
+    # Get global symbols from roots.  We set a rule to do this per-rule, as
+    # using a single rule to process all roots adds overhead to the critical
+    # path of incremental flows (e.g. that only update a single root).
+    global_symbols_files = [root.global_syms for root in roots]
+
+    # TODO(T110378126): Processing all excluded libs together may get expensive.
+    # We should probably split this up and operate on individual libs.
+    if excluded:
+        global_symbols_files.append(
+            extract_symbol_names(
+                ctx = ctx,
+                cxx_toolchain = get_cxx_toolchain_info(ctx),
+                name = "__excluded_libs__.global_syms.txt",
+                objects = excluded,
+                dynamic = True,
+                global_only = True,
+                category = "omnibus_global_syms_excluded_libs",
+            )
+        )
+
+    # Extract explicitly globalized symbols from linker args.
+    global_symbols_files.append(
+        _extract_global_symbols_from_link_args(
+            ctx,
+            "__global_symbols_from_args__.txt",
+            link_args,
+        )
+    )
+
+    return create_global_symbols_version_script(
+        actions = ctx.actions,
+        name = "__global_symbols__.vers",
+        category = "omnibus_version_script",
+        symbol_files = global_symbols_files,
+    )
+
+def _is_static_only(info: LinkableNode) -> bool:
+    """
+    Return whether this can only be linked statically.
+    """
+    return info.preferred_linkage == Linkage("static")
+
+def _is_shared_only(info: LinkableNode) -> bool:
+    """
+    Return whether this can only use shared linking
+    """
+    return info.preferred_linkage == Linkage("shared")
+
+def _is_static_deps(info: LinkableNode) -> bool:
+    """
+    Return whether avoid excluding this nodes deps, even if this node is shared
+    -only.
+    """
+    return "omnibus_static_deps" in info.labels
+
+def _create_omnibus(
+    ctx: AnalysisContext,
+    spec: OmnibusSpec,
+    omnibus_lib_name: str,
+    root_products: dict[Label, OmnibusRootProduct],
+    pic_behavior: PicBehavior,
+    extra_ldflags: list[typing.Any] = [],
+    prefer_stripped_objects: bool = False,
+    allow_cache_upload: bool = False,
+    enable_distributed_thinlto = False,
+) -> CxxLinkResult:
+    inputs = []
+
+    # Undefined symbols roots...
+    non_body_root_undefined_syms = [root.undefined_syms for label, root in root_products.items() if label not in spec.body]
+    if non_body_root_undefined_syms:
+        inputs.append(
+            LinkInfo(
+                pre_flags = [
+                    get_undefined_symbols_args(
+                        ctx = ctx,
+                        name = "__undefined_symbols__.argsfile",
+                        symbol_files = non_body_root_undefined_syms,
+                        category = "omnibus_undefined_symbols",
+                    ),
+                ]
+            )
+        )
+
+    # Process all body nodes.
+    deps = {}
+    global_symbols_link_args = []
+    for label in spec.body:
+        # If this body node is a root, add the it's output to the link.
+        if label in spec.roots:
+            root = root_products[label]
+
+            # TODO(cjhopman): This should be passing structured linkables
+            inputs.append(LinkInfo(pre_flags = [cmd_args(root.shared_library.output)]))
+            continue
+
+        node = spec.link_infos[label]
+
+        # Otherwise add in the static input for this node.
+        output_style = get_lib_output_style(
+            LinkStrategy("static_pic"),
+            node.preferred_linkage,
+            pic_behavior,
+        )
+        expect(output_style == LibOutputStyle("pic_archive"))
+        body_input = get_link_info(
+            node,
+            output_style,
+            prefer_stripped = prefer_stripped_objects,
+        )
+        inputs.append(body_input)
+        global_symbols_link_args.append(link_info_to_args(body_input))
+
+        # Keep track of all first order deps of the omnibus monolith.
+        for dep in node.deps + node.exported_deps:
+            if dep not in spec.body:
+                expect(dep in spec.excluded)
+                deps[dep] = None
+
+    toolchain_info = get_cxx_toolchain_info(ctx)
+
+    # Now add deps of omnibus to the link
+    for label in _link_deps(spec.link_infos, deps.keys(), toolchain_info.pic_behavior):
+        node = spec.link_infos[label]
+        output_style = get_lib_output_style(
+            LinkStrategy("shared"),
+            node.preferred_linkage,
+            toolchain_info.pic_behavior,
+        )
+        inputs.append(
+            get_link_info(
+                node,
+                output_style,
+                prefer_stripped = prefer_stripped_objects,
+            )
+        )
+
+    linker_info = toolchain_info.linker_info
+
+    # Add global symbols version script.
+    # FIXME(agallagher): Support global symbols for darwin.
+    if linker_info.type != LinkerType("darwin"):
+        global_sym_vers = _create_global_symbols_version_script(
+            ctx,
+            # Extract symbols from roots...
+            root_products.values(),
+            # ... and the shared libs from excluded nodes.
+            [shared_lib.lib.output for label in spec.excluded for shared_lib in spec.link_infos[label].shared_libs.libraries],
+            # Extract explicit global symbol names from flags in all body link args.
+            global_symbols_link_args,
+        )
+        inputs.append(
+            LinkInfo(
+                pre_flags = [
+                    "-Wl,--version-script",
+                    global_sym_vers,
+                    # The version script contains symbols that are not defined. Up to
+                    # LLVM 15 this behavior was ignored but LLVM 16 turns it into
+                    # warning by default.
+                    "-Wl,--undefined-version",
+                ]
+            )
+        )
+
+    soname = _omnibus_soname(ctx, omnibus_lib_name)
+
+    return cxx_link_shared_library(
+        ctx = ctx,
+        output = soname,
+        name = soname,
+        opts = link_options(
+            links = [LinkArgs(flags = extra_ldflags), LinkArgs(infos = inputs)],
+            category_suffix = "omnibus",
+            # TODO(T110378138): As with static C++ links, omnibus links are
+            # currently too large for RE, so run them locally for now (e.g.
+            # https://fb.prod.workplace.com/groups/buck2dev/posts/2953023738319012/).
+            # NB: We explicitly pass a value here to override
+            # the linker_info.link_libraries_locally that's used by `cxx_link_shared_library`.
+            # That's because we do not want to apply the linking behavior universally,
+            # just use it for omnibus.
+            link_execution_preference = get_resolved_cxx_binary_link_execution_preference(ctx, [], False, toolchain_info),
+            link_weight = linker_info.link_weight,
+            enable_distributed_thinlto = enable_distributed_thinlto,
+            identifier = soname,
+            allow_cache_upload = allow_cache_upload,
+            produce_shared_library_interface = False,
+        ),
+    )
+
+def _build_omnibus_spec(ctx: AnalysisContext, graph: OmnibusGraph) -> OmnibusSpec:
+    """
+    Divide transitive deps into excluded, root, and body nodes, which we'll
+    use to link the various parts of omnibus.
+    """
+
+    # Build up the set of all nodes that we have to exclude from omnibus linking
+    excluded = {}
+
+    # Track excluded nodes that need to transitively exclude their children.
+    exclusion_roots = []
+    exclusion_roots.extend(graph.excluded.keys())
+
+    # Walk graph nodes, looking for ones to exclude.
+    for label, info in graph.nodes.items():
+        # Exclude any body nodes which can't be linked statically.
+        if (label not in graph.roots) and _is_shared_only(info):
+            # By default, we'll also exclude this nodes transitive children,
+            # but nodes can opt-out.
+            if _is_static_deps(info):
+                excluded[label] = None
+            else:
+                exclusion_roots.append(label)
+
+    # Recursively expand exluded roots and add them to the excluded list.
+    for label in get_transitive_deps(
+        graph.nodes,
+        exclusion_roots,
+    ):
+        excluded[label] = None
+
+    # Finalized root nodes, after removing any excluded roots.
+    roots = {label: root for label, root in graph.roots.items() if label not in excluded}
+
+    # Find the deps of the root nodes that should be linked into
+    # 'libomnibus.so'.
+    #
+    # If a dep indicates preferred linkage static, it is linked directly into
+    # this omnimbus root and therefore not added to `first_order_root_deps` and
+    # thereby will not be linked into 'libomnibus.so'. If the dep does not
+    # indicate preferred linkage static, then it is added to
+    # `first_order_root_deps` and thereby will be linked into 'libomnibus.so'.
+    first_order_root_deps = []
+    for label in _link_deps(graph.nodes, flatten([r.deps for r in roots.values()]), get_cxx_toolchain_info(ctx).pic_behavior):
+        # Per the comment above, only consider deps which aren't *only*
+        # statically linked.
+        if _is_static_only(graph.nodes[label]):
+            continue
+
+        # Don't include a root's dep onto another root.
+        if label in roots:
+            continue
+        first_order_root_deps.append(label)
+
+    # All body nodes.  These included all non-excluded body nodes and any non-
+    # excluded roots which are reachable by these body nodes (since they will
+    # need to be put on the link line).
+    body = {label: None for label in get_transitive_deps(graph.nodes, first_order_root_deps) if label not in excluded}
+
+    dispositions = {}
+
+    for node, info in graph.nodes.items():
+        if _is_static_only(info):
+            continue
+
+        if node in roots:
+            dispositions[node] = Disposition("root")
+            continue
+
+        if node in excluded:
+            dispositions[node] = Disposition("excluded")
+            continue
+
+        if node in body:
+            dispositions[node] = Disposition("body")
+            continue
+
+        # Why does that happen? Who knows with Omnibus :(
+        dispositions[node] = Disposition("omitted")
+
+    return OmnibusSpec(
+        excluded = excluded,
+        roots = roots,
+        body = body,
+        link_infos = graph.nodes,
+        exclusion_roots = exclusion_roots,
+        dispositions = dispositions,
+    )
+
+def _ordered_roots(spec: OmnibusSpec, pic_behavior: PicBehavior) -> list[(Label, LinkableRootInfo, list[Label])]:
+    """
+    Return information needed to link the roots nodes.
+    """
+
+    # Calculate all deps each root node needs to link against.
+    link_deps = {label: _link_deps(spec.link_infos, root.deps, pic_behavior) for label, root in spec.roots.items()}
+
+    # Used the link deps to create the graph of root nodes.
+    root_graph = {node: [dep for dep in deps if dep in spec.roots] for node, deps in link_deps.items()}
+
+    # Emit the root link info in post-order, so that we generate root link rules
+    # for dependencies before their dependents.
+    ordered_roots = [(label, spec.roots[label], link_deps[label]) for label in post_order_traversal(root_graph)]
+
+    return ordered_roots
+
+def create_omnibus_libraries(
+    ctx: AnalysisContext,
+    graph: OmnibusGraph,
+    extra_ldflags: list[typing.Any] = [],
+    extra_root_ldflags: dict[Label, list[typing.Any]] = {},
+    prefer_stripped_objects: bool = False,
+    enable_distributed_thinlto = False,
+    omnibus_lib_name: str = "omnibus",
+    anonymous: bool = False,
+) -> OmnibusSharedLibraries:
+    spec = _build_omnibus_spec(ctx, graph)
+    pic_behavior = get_cxx_toolchain_info(ctx).pic_behavior
+
+    # Create dummy omnibus
+    dummy_omnibus = create_dummy_omnibus(
+        ctx = ctx,
+        extra_ldflags = extra_ldflags,
+        omnibus_lib_name = omnibus_lib_name,
+        anonymous = anonymous,
+    )
+
+    libraries = []
+    root_products = {}
+    counter = 0  # counter to avoid hash collisions
+
+    # Link all root nodes against the dummy libomnibus lib.
+    for label, root, link_deps in _ordered_roots(spec, pic_behavior):
+        counter += 1
+        product = _create_root(
+            ctx,
+            spec,
+            root_products,
+            root,
+            label,
+            link_deps,
+            dummy_omnibus,
+            pic_behavior,
+            extra_ldflags + extra_root_ldflags.get(label, []),
+            prefer_stripped_objects,
+            allow_cache_upload = True,
+            hash_counter = counter,
+            anonymous = anonymous,
+        )
+        if root.name != None:
+            libraries.append(
+                create_shlib(
+                    soname = root.name,
+                    lib = product.shared_library,
+                    label = label,
+                ),
+            )
+        root_products[label] = product
+
+    # If we have body nodes, then link them into the monolithic libomnibus.so.
+    omnibus = None
+    if spec.body:
+        omnibus = _create_omnibus(
+            ctx = ctx,
+            spec = spec,
+            omnibus_lib_name = omnibus_lib_name,
+            root_products = root_products,
+            pic_behavior = pic_behavior,
+            extra_ldflags = extra_ldflags,
+            prefer_stripped_objects = prefer_stripped_objects,
+            enable_distributed_thinlto = enable_distributed_thinlto,
+            allow_cache_upload = True,
+        )
+        libraries.append(
+            create_shlib(
+                soname = _omnibus_soname(ctx, omnibus_lib_name),
+                lib = omnibus.linked_object,
+                label = ctx.label,
+            ),
+        )
+
+    # For all excluded nodes, just add their regular shared libs.
+    for label in spec.excluded:
+        libraries.extend(spec.link_infos[label].shared_libs.libraries)
+
+    return OmnibusSharedLibraries(
+        omnibus = omnibus,
+        libraries = libraries,
+        roots = root_products,
+        exclusion_roots = spec.exclusion_roots,
+        excluded = spec.excluded.keys(),
+        dispositions = spec.dispositions,
+    )
diff --git a/buck2/prelude/cxx/prebuilt_cxx_library_group.bzl b/buck2/prelude/cxx/prebuilt_cxx_library_group.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/prebuilt_cxx_library_group.bzl
@@ -0,0 +1,428 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "LinkerType",
+    "PicBehavior",
+)
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorArgs",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+)
+load(
+    "@prelude//linking:link_groups.bzl",
+    "merge_link_group_lib_info",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "Archive",
+    "ArchiveLinkable",
+    "LibOutputStyle",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkStrategy",
+    "LinkedObject",
+    "SharedLibLinkable",
+    "create_merged_link_info",
+    "get_lib_output_style",
+    "get_output_styles_for_linkage",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+    "create_linkable_node",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "create_shared_libraries",
+    "merge_shared_libraries",
+)
+load("@prelude//linking:strip.bzl", "strip_debug_info")
+load("@prelude//linking:types.bzl", "Linkage")
+load(
+    "@prelude//third-party:build.bzl",
+    "create_third_party_build_info",
+)
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "filter_and_map_idx", "flatten_dict")
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    ":cxx_library_utility.bzl",
+    "cxx_attr_dep_metadata",
+    "cxx_attr_use_content_based_paths",
+    "cxx_inherited_link_info",
+    "cxx_use_shlib_intfs_mode",
+)
+load(
+    ":cxx_toolchain_types.bzl",
+    "ShlibInterfacesMode",
+)
+load(
+    ":shared_library_interface.bzl",
+    "shared_library_interface",
+)
+
+def _linkage(ctx: AnalysisContext) -> Linkage:
+    """
+    Construct the preferred linkage to use for the given prebuilt library.
+    """
+
+    # If we have both shared and static libs, we support any linkage.
+    if ctx.attrs.shared_link and (ctx.attrs.static_link or ctx.attrs.static_pic_link):
+        return Linkage("any")
+
+    # Otherwise, if we have a shared library, we only support shared linkage.
+    if ctx.attrs.shared_link:
+        return Linkage("shared")
+
+    # Otherwise, if we have a static library, we only support static linkage.
+    if ctx.attrs.static_link or ctx.attrs.static_pic_link:
+        return Linkage("static")
+
+    # Otherwise, header only libs use any linkage.
+    return Linkage("any")
+
+def _parse_macro(arg: str) -> [(str, str), None]:
+    """
+    Parse a lib reference macro (e.g. `$(lib 0)`, `$(rel-lib libfoo.so)`) into
+    the format string used to format the arg, the name of the macro parsed, and
+    the argument passed to the macro.
+    """
+
+    # TODO(T110378124): This is obviously not ideal and longer-term we should
+    # probably come up with a better UI for this rule or properly support these
+    # macros.
+
+    # If there's not macro, then there's nothing to do.
+    if "$(" not in arg:
+        return None
+
+    # Extract the macro name and it's arg out of the string.  Also, create a
+    # format string with the remaining parts which can be used to format to an
+    # actual arg.  This is pretty ugly, but we don't have too complex a case to
+    # support (e.g. a single macro with a single arg).
+    start, rest = arg.split("$(")
+    expect(start == "")
+    pos = rest.find(" ")
+    macro = rest[:pos]
+    rest = rest[pos + 1 :]
+    pos = rest.find(")")
+    param = rest[:pos]
+    end = rest[pos + 1 :]
+    expect(end == "")
+
+    return macro, param
+
+def _get_static_link_infos(ctx: AnalysisContext, linker_type: LinkerType, libs: list[Artifact], args: list[str]) -> LinkInfos:
+    """
+    Format a pair of static link string args and static libs into args to be
+    passed to the link, by resolving macro references to libraries.
+    """
+
+    def archive_linkable(artifact):
+        return ArchiveLinkable(
+            archive = Archive(artifact = artifact),
+            linker_type = linker_type,
+            # We assume prebuilt C/C++ libs don't contain LTO code and
+            # avoid potentially expensive processing of the to support
+            # dist LTO.  In additional, some prebuilt library groups
+            # use `--start-group`/`--end-group` which breaks with our
+            # dist LTO impl wrapping w/ `--start-lib`.
+            supports_lto = False,
+        )
+
+    pre_flags = []
+    post_flags = []
+    linkables = []
+    linkables_stripped = []
+
+    for arg in args:
+        res = _parse_macro(arg)
+        if res != None:
+            # We require that link lines are written such that link flags wrap
+            # linkables.  So verify that we haven't already seen post linker
+            # flags.
+            expect(not post_flags)
+
+            # Macros in the static link line are indexes to the list of static
+            # archives.
+            macro, param = res
+            expect(macro == "lib")
+            lib = libs[int(param)]
+            linkables.append(archive_linkable(lib))
+            linkables_stripped.append(
+                archive_linkable(
+                    strip_debug_info(
+                        ctx.actions,
+                        lib.short_path,
+                        lib,
+                        anonymous = True,
+                        cxx_toolchain = ctx.attrs._cxx_toolchain,
+                        has_content_based_path = cxx_attr_use_content_based_paths(ctx),
+                    )
+                )
+            )
+        elif linkables:
+            # If we've already seen linkables, put remaining flags/args into
+            # post-linker flags.
+            post_flags.append(arg)
+        else:
+            pre_flags.append(arg)
+
+    return LinkInfos(
+        default = LinkInfo(
+            pre_flags = pre_flags,
+            post_flags = post_flags,
+            linkables = linkables,
+            metadata = cxx_attr_dep_metadata(ctx),
+        ),
+        stripped = LinkInfo(
+            pre_flags = pre_flags,
+            post_flags = post_flags,
+            linkables = linkables_stripped,
+            metadata = cxx_attr_dep_metadata(ctx),
+        ),
+    )
+
+def _get_shared_link_infos(ctx: AnalysisContext, shared_libs: dict[str, Artifact], args: list[str], shlib_intfs: bool = True) -> LinkInfos:
+    """
+    Format a pair of shared link string args and shared libs into args to be
+    passed to the link, by resolving macro references to libraries.
+    """
+
+    pre_flags = []
+    post_flags = []
+    linkables = []
+
+    for arg in args:
+        res = _parse_macro(arg)
+        if res != None:
+            # We require that link lines are written such that link flags wrap
+            # linkables.  So verify that we haven't already seen post linker
+            # flags.
+            expect(not post_flags)
+
+            # Macros in the shared link line are named references to the map
+            # of all shared libs.
+            macro, lib_name = res
+            expect(macro in ("lib", "rel-lib"))
+            shared_lib = shared_libs[lib_name]
+            if shlib_intfs:
+                shared_lib = shared_library_interface(
+                    ctx = ctx,
+                    shared_lib = shared_lib,
+                    anonymous = True,
+                )
+            if macro == "lib":
+                linkables.append(SharedLibLinkable(lib = shared_lib))
+            elif macro == "rel-lib":
+                # rel-lib means link-without-soname.
+                linkables.append(SharedLibLinkable(lib = shared_lib, link_without_soname = True))
+        elif linkables:
+            # If we've already seen linkables, put remaining flags/args into
+            # post-linker flags.
+            post_flags.append(arg)
+        else:
+            pre_flags.append(arg)
+
+    return LinkInfos(
+        default = LinkInfo(
+            pre_flags = pre_flags,
+            post_flags = post_flags,
+            linkables = linkables,
+            metadata = cxx_attr_dep_metadata(ctx),
+        ),
+    )
+
+# The `prebuilt_cxx_library_group` rule is meant to provide fine user control for
+# how a group libraries of libraries are added to the link line and was added for
+# `fbcode//third-party-buck/platform009/build/IntelComposerXE:mkl_lp64_iomp`, which
+# includes libraries with dep cycles, and so must be linked together with flags
+# like `--start-group`/`--end-group`.
+#
+# The link arguments for the various link styles are specified by pair of string
+# arguments with macros referencing a collection of libraries:
+#
+# - For static link styles, the string link args (e.g. specific in `static_link`)
+#   contain macros of the form `$(lib <number>)`, where the number is an index
+#   into the corresponding list of static libraries artifacts (e.g. specified in
+#   `static_libs`).  For example:
+#
+#     static_link = ["-Wl,--start-group", "$(lib 0)", "$(lib 1)", "-Wl,--end-group"],
+#     static_libs = ["libfoo1.a", "libfoo2.a"],
+#
+# - For shared linking, the string link args contain macros of the form
+#   `$(lib <name>)` or `$(rel-lib <name>)`, where the name is key for shared
+#   libraries specified in `shared_libs` or `provided_shared_libs`.  The
+#   `lib` macro examples to the full path of the shared library, whereas the
+#   `rel-lib` macro expands to `-L<dirname> -l<name>` of the library and is
+#   meant to be used in situations where shared library does not contain an
+#   embedded soname.  For example:
+#
+#     shared_link = ["$(lib libfoo1.so)", "$(rel-lib libfoo2.so)"],
+#     shared_libs = {
+#         "libfoo1.so": "lib/libfoo1.so",
+#         "libfoo2.so": "lib/libfoo2.so",
+#     },
+#
+def prebuilt_cxx_library_group_impl(ctx: AnalysisContext) -> list[Provider]:
+    providers = []
+    sub_targets = {}
+
+    deps = ctx.attrs.deps
+    exported_deps = ctx.attrs.exported_deps
+
+    # Figure out preprocessor stuff
+    args = []
+    args.extend(ctx.attrs.exported_preprocessor_flags)
+    for inc_dir in ctx.attrs.include_dirs:
+        args += ["-isystem", inc_dir]
+    preprocessor = CPreprocessor(args = CPreprocessorArgs(args = args, precompile_args = args))
+    inherited_pp_info = cxx_inherited_preprocessor_infos(exported_deps)
+    providers.append(cxx_merge_cpreprocessors(ctx.actions, [preprocessor], inherited_pp_info))
+
+    # Figure out all the link styles we'll be building archives/shlibs for.
+    preferred_linkage = _linkage(ctx)
+
+    inherited_non_exported_link = cxx_inherited_link_info(deps)
+    inherited_exported_link = cxx_inherited_link_info(exported_deps)
+
+    linker_type = get_cxx_toolchain_info(ctx).linker_info.type
+
+    # Gather link infos, outputs, and shared libs for effective link style.
+    outputs = {}
+    libraries = {}
+    solibs = {}
+    for output_style in get_output_styles_for_linkage(preferred_linkage):
+        outs = []
+        if output_style == LibOutputStyle("archive"):
+            outs.extend(ctx.attrs.static_libs)
+            infos = _get_static_link_infos(
+                ctx,
+                linker_type,
+                ctx.attrs.static_libs,
+                ctx.attrs.static_link,
+            )
+        elif output_style == LibOutputStyle("pic_archive"):
+            outs.extend(ctx.attrs.static_pic_libs)
+            infos = _get_static_link_infos(
+                ctx,
+                linker_type,
+                ctx.attrs.static_pic_libs,
+                ctx.attrs.static_pic_link,
+            )
+        else:  # shared
+            outs.extend(ctx.attrs.shared_libs.values())
+            infos = _get_shared_link_infos(
+                ctx = ctx,
+                shared_libs = flatten_dict([ctx.attrs.shared_libs, ctx.attrs.provided_shared_libs]),
+                args = ctx.attrs.shared_link,
+                # TODO: We should not permit both modes, but to keep builds green we have to for now.
+                shlib_intfs = ctx.attrs.supports_shared_library_interface
+                and (
+                    cxx_use_shlib_intfs_mode(ctx, ShlibInterfacesMode("defined_only"))
+                    or cxx_use_shlib_intfs_mode(ctx, ShlibInterfacesMode("stub_from_library"))
+                ),
+            )
+            solibs.update({n: LinkedObject(output = lib, unstripped_output = lib) for n, lib in ctx.attrs.shared_libs.items()})
+        outputs[output_style] = outs
+
+        libraries[output_style] = infos
+
+    # This code is already compiled, so, the argument (probably) has little/no value.
+    pic_behavior = PicBehavior("supported")
+
+    # Provider for native link.
+    providers.append(
+        create_merged_link_info(
+            ctx,
+            pic_behavior,
+            libraries,
+            preferred_linkage = preferred_linkage,
+            # Export link info from our (non-exported) deps (e.g. when we're linking
+            # statically).
+            deps = inherited_non_exported_link,
+            # Export link info from our (exported) deps.
+            exported_deps = inherited_exported_link,
+        )
+    )
+
+    # Propagate shared libraries up the tree.
+    shared_libs = create_shared_libraries(ctx, solibs)
+    providers.append(
+        merge_shared_libraries(
+            ctx.actions,
+            shared_libs,
+            filter_and_map_idx(SharedLibraryInfo, deps + exported_deps),
+        )
+    )
+
+    # Create, augment and provide the linkable graph.
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            linkable_node = create_linkable_node(
+                ctx = ctx,
+                deps = deps,
+                exported_deps = exported_deps,
+                preferred_linkage = preferred_linkage,
+                link_infos = libraries,
+                shared_libs = shared_libs,
+                can_be_asset = getattr(ctx.attrs, "can_be_asset", False) or False,
+                # TODO(cjhopman): this should be set to non-None
+                default_soname = None,
+            ),
+        ),
+        deps = deps + exported_deps,
+    )
+    providers.append(linkable_graph)
+
+    providers.append(merge_link_group_lib_info(deps = deps + exported_deps))
+
+    providers.append(
+        create_unix_env_info(
+            actions = ctx.actions,
+            env = UnixEnv(
+                label = ctx.label,
+                native_libs = [shared_libs],
+            ),
+            deps = deps + exported_deps,
+        ),
+    )
+
+    # Third-party provider.
+    third_party_build_info = create_third_party_build_info(
+        ctx = ctx,
+        # cxx_headers = [propagated_preprocessor],
+        shared_libs = shared_libs.libraries,
+        cxx_header_dirs = [inc_dir.short_path for inc_dir in ctx.attrs.include_dirs],
+        deps = deps + exported_deps,
+    )
+    providers.append(third_party_build_info)
+    sub_targets["third-party-build"] = [
+        DefaultInfo(
+            default_output = third_party_build_info.build.root.artifact,
+            sub_targets = dict(
+                manifest = [DefaultInfo(default_output = third_party_build_info.build.manifest)],
+            ),
+        ),
+    ]
+
+    # prebuilt_cxx_library_group default output is always the output used for the "static" link strategy.
+    static_output_style = get_lib_output_style(LinkStrategy("static"), preferred_linkage, pic_behavior)
+    providers.append(DefaultInfo(default_outputs = outputs[static_output_style], sub_targets = sub_targets))
+
+    return providers
diff --git a/buck2/prelude/cxx/preprocessor.bzl b/buck2/prelude/cxx/preprocessor.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/preprocessor.bzl
@@ -0,0 +1,636 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load("@prelude//cxx:target_sdk_version.bzl", "get_target_sdk_version_flags")
+load(
+    "@prelude//utils:utils.bzl",
+    "filter_and_map_idx",
+    "map_val",
+    "value_or",
+)
+load(":attr_selection.bzl", "cxx_by_language_ext")
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+load(":cxx_toolchain_types.bzl", "CXX_COMPILER_TYPES")
+load(
+    ":headers.bzl",
+    "CHeader",  # @unused Used as a type
+    "CxxHeadersLayout",  # @unused Used as a type
+    "CxxHeadersNaming",
+    "HeaderMode",
+    "HeaderStyle",
+    "HeadersAsRawHeadersMode",
+    "RawHeadersAsHeadersMode",
+    "as_headers",
+    "as_raw_headers",
+    "cxx_attr_exported_header_style",
+    "cxx_attr_exported_headers",
+    "cxx_attr_headers",
+    "prepare_headers",
+)
+
+SystemIncludeDirs = record(
+    # Compiler type to infer correct include flags
+    compiler_type = field(str),
+    #  Directories to be included via [-isystem | /external:I] [arglike things]
+    include_dirs = field(list[CellPath]),
+)
+
+CPreprocessorArgs = record(
+    # The arguments, [arglike things]
+    args = field(list[typing.Any], []),
+    # -fdebug-prefix-map args that map symlinks to source file location
+    file_prefix_args = field(list[typing.Any], []),
+    # -fcoverage-prefix-map args (clang-only, separated so non-clang compilers can skip them)
+    coverage_prefix_args = field(list[typing.Any], []),
+    # Arguments used for module precompilation, replacing args
+    precompile_args = field(list[typing.Any], []),
+    # Header maps named by `args`, without the header trees behind them. Tools
+    # that resolve a header map by reading it need these and nothing else.
+    header_maps = field(list[Artifact], []),
+)
+
+HeaderUnit = record(
+    name = field(str),
+    module = field(Artifact),
+    stub = field(Artifact | None),
+    include_dir = field(Artifact),
+    import_include = field(str | None),
+    clang_trace = field(Artifact | None),
+    diagnostics = field(Artifact | None, None),
+)
+
+# Note: Any generic attributes are assumed to be relative.
+CPreprocessor = record(
+    # Relative path args to be used for build operations.
+    args = field(CPreprocessorArgs, CPreprocessorArgs()),
+    # Header specs
+    headers = field(list[CHeader], []),
+    # Those should be mutually exclusive with normal headers as per documentation
+    raw_headers = field(list[Artifact], []),
+    # Directories to be included via -I, [arglike things]
+    include_dirs = field(list[CellPath], []),
+    # Directories to be included via -isystem, [arglike things]
+    system_include_dirs = field([SystemIncludeDirs, None], None),
+    # Whether to compile with modules support
+    uses_modules = field(bool, False),
+    # Modular args to set when modules are in use, [arglike things]
+    modular_args = field(list[typing.Any], []),
+    # Modulemap artifact
+    modulemap_artifact = field([Artifact, None], None),
+    # Header units to load transitively and supporting args.
+    header_units = field(list[HeaderUnit], []),
+    # Raw include directory strings from public_include_directories attr.
+    raw_include_dirs = field(list[str], []),
+    # Raw include directory strings from public_system_include_directories attr.
+    raw_system_include_dirs = field(list[str], []),
+)
+
+_EMPTY_CPREPROCESSOR_ARGS = CPreprocessorArgs()
+EMPTY_CPREPROCESSOR = CPreprocessor()
+
+_EMPTY_SYSTEM_INCLUDE_DIRS_BY_COMPILER_TYPE = {
+    compiler_type: SystemIncludeDirs(compiler_type = compiler_type, include_dirs = []) for compiler_type in CXX_COMPILER_TYPES
+}
+
+def _system_include_dirs(compiler_type: str, include_dirs: list[CellPath]) -> SystemIncludeDirs:
+    if not include_dirs:
+        shared = _EMPTY_SYSTEM_INCLUDE_DIRS_BY_COMPILER_TYPE.get(compiler_type)
+        if shared != None:
+            return shared
+    return SystemIncludeDirs(compiler_type = compiler_type, include_dirs = include_dirs)
+
+# Methods for transitive_sets must be declared prior to their use.
+
+def _cpreprocessor_args(pres: list[CPreprocessor]):
+    args = cmd_args()
+    for pre in pres:
+        args.add(pre.args.args)
+    return args
+
+def _cpreprocessor_modular_args(pres: list[CPreprocessor]):
+    args = cmd_args()
+    for pre in pres:
+        args.add(pre.modular_args)
+    return args
+
+def _cpreprocessor_precompile_args(pres: list[CPreprocessor]):
+    args = cmd_args()
+    for pre in pres:
+        args.add(pre.args.precompile_args)
+    return args
+
+def _cpreprocessor_header_maps(pres: list[CPreprocessor]):
+    return cmd_args(hidden = [pre.args.header_maps for pre in pres])
+
+def _cpreprocessor_header_units_args_impl(pres: list[CPreprocessor], stub: bool):
+    args = cmd_args()
+    for pre in pres:
+        for h in pre.header_units:
+            artifact = h.stub if stub else h.module
+            if artifact:
+                args.add(cmd_args("-fmodule-file=", h.name, "=", artifact, delimiter = ""))
+                args.add(cmd_args(h.include_dir, format = "-I{}"))
+                args.add(cmd_args(h.include_dir, format = "-fmodule-map-file={}/module.modulemap"))
+                if h.import_include:
+                    args.add(["-include", h.import_include])
+    return args
+
+def _cpreprocessor_header_units_args(pres: list[CPreprocessor]):
+    return _cpreprocessor_header_units_args_impl(pres, stub = False)
+
+def _cpreprocessor_header_unit_stubs_args(pres: list[CPreprocessor]):
+    return _cpreprocessor_header_units_args_impl(pres, stub = True)
+
+def _cpreprocessor_has_header_units_args(children: list[bool], pres: [list[CPreprocessor], None]):
+    if pres:
+        for pre in pres:
+            if pre and pre.header_units and len(pre.header_units) > 0:
+                return True
+    return any(children)
+
+def _cpreprocessor_file_prefix_args(pres: list[CPreprocessor]):
+    args = cmd_args()
+    for pre in pres:
+        args.add(pre.args.file_prefix_args)
+    return args
+
+def _cpreprocessor_coverage_prefix_args(pres: list[CPreprocessor]):
+    args = cmd_args()
+    for pre in pres:
+        args.add(pre.args.coverage_prefix_args)
+    return args
+
+def _cpreprocessor_has_file_prefix_args(children: list[bool], pres: [list[CPreprocessor], None]):
+    if pres:
+        for pre in pres:
+            if pre.args.file_prefix_args or pre.args.coverage_prefix_args:
+                return True
+    return any(children)
+
+def _cpreprocessor_include_dirs(pres: list[CPreprocessor]):
+    args = cmd_args()
+    for pre in pres:
+        for d in pre.include_dirs:
+            args.add(cmd_args(d, format = "-I{}"))
+        if pre.system_include_dirs != None:
+            for d in pre.system_include_dirs.include_dirs:
+                system_include_args = format_system_include_arg(cmd_args(d), pre.system_include_dirs.compiler_type)
+                args.add(system_include_args)
+    return args
+
+def _cpreprocessor_uses_modules(children: list[bool], pres: [list[CPreprocessor], None]):
+    if pres:
+        for pre in pres:
+            if pre.uses_modules:
+                return True
+    return any(children)
+
+# Set of [CPreprocessor]. Most nodes have just a single value, but we
+# allow > 1 for cxx compilation commands where it we do want > 1 (one for
+# exported pp info and one for not-exported).
+CPreprocessorTSet = transitive_set(
+    args_projections = {
+        "args": _cpreprocessor_args,
+        "coverage_prefix_args": _cpreprocessor_coverage_prefix_args,
+        "file_prefix_args": _cpreprocessor_file_prefix_args,
+        "header_maps": _cpreprocessor_header_maps,
+        "header_unit_stubs_args": _cpreprocessor_header_unit_stubs_args,
+        "header_units_args": _cpreprocessor_header_units_args,
+        "include_dirs": _cpreprocessor_include_dirs,
+        "modular_args": _cpreprocessor_modular_args,
+        "precompile_args": _cpreprocessor_precompile_args,
+    },
+    reductions = {
+        "has_file_prefix_args": _cpreprocessor_has_file_prefix_args,
+        "has_header_units_args": _cpreprocessor_has_header_units_args,
+        "uses_modules": _cpreprocessor_uses_modules,
+    },
+)
+
+CPreprocessorInfo = provider(
+    fields = {
+        "set": provider_field(typing.Any, default = None),  # "CPreprocessorTSet"
+    }
+)
+
+# Defines the provider exposed by libraries to test targets,
+# so that tests can have access to the private headers of
+# the first order deps (for testing purposes).
+CPreprocessorForTestsInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        # [str] - list of targets in "tests"
+        "test_names": provider_field(typing.Any, default = None),  #
+        # CPreprocessor - the private preprocessor
+        # for the target which is _only_ exposed to any
+        # test targets defined in `test_names`
+        "own_non_exported_preprocessor": provider_field(typing.Any, default = None),
+    },
+)
+
+def cxx_attr_exported_preprocessor_flags(ctx: AnalysisContext) -> list[typing.Any]:
+    return ctx.attrs.exported_preprocessor_flags + _by_language_cxx(ctx.attrs.exported_lang_preprocessor_flags)
+
+def cxx_inherited_preprocessor_infos(first_order_deps: list[Dependency]) -> list[CPreprocessorInfo]:
+    # We filter out nones because some non-cxx rule without such providers could be a dependency, for example
+    # cxx_binary "fbcode//one_world/cli/util/process_wrapper:process_wrapper" depends on
+    # python_library "fbcode//third-party-buck/$platform/build/glibc:__project__"
+    return filter_and_map_idx(CPreprocessorInfo, first_order_deps)
+
+def cxx_merge_cpreprocessors(actions: AnalysisActions, own: list[CPreprocessor], xs: list[CPreprocessorInfo]) -> CPreprocessorInfo:
+    kwargs = {"children": [x.set for x in xs]}
+    if own:
+        kwargs["value"] = own
+    return CPreprocessorInfo(
+        set = actions.tset(CPreprocessorTSet, **kwargs),
+    )
+
+# Module globals are recursively frozen before callers can observe them.
+_INCLUDE_FLAG_ARGS = {
+    "-I": cmd_args("-I"),
+    "-isystem": cmd_args("-isystem"),
+}
+
+def _format_include_arg(flag: str, path: cmd_args, compiler_type: str) -> list[cmd_args]:
+    if compiler_type == "windows":
+        return [cmd_args(path, format = flag + "{}")]
+    else:
+        shared = _INCLUDE_FLAG_ARGS.get(flag)
+        return [shared if shared != None else cmd_args(flag), path]
+
+def format_system_include_arg(path: cmd_args, compiler_type: str) -> list[cmd_args]:
+    if compiler_type == "windows":
+        return [cmd_args(path, format = "/external:I{}")]
+    else:
+        return [_INCLUDE_FLAG_ARGS["-isystem"], path]
+
+def cxx_exported_preprocessor_info(ctx: AnalysisContext, headers_layout: CxxHeadersLayout, extra_preprocessors: list[CPreprocessor] = []) -> CPreprocessor:
+    """
+    This rule's preprocessor info which is both applied to the compilation of
+    its source and propagated to the compilation of dependent's sources.
+    """
+    exported_headers = cxx_attr_exported_headers(ctx, headers_layout)
+
+    # Add any headers passed in via constructor params
+    for pre in extra_preprocessors:
+        exported_headers += pre.headers
+
+    exported_header_map = {paths.join(h.namespace, h.name): h.artifact for h in exported_headers}
+    raw_headers = []
+    include_dirs = []
+    system_include_dirs = []
+
+    style = cxx_attr_exported_header_style(ctx)
+    compiler_type = get_cxx_toolchain_info(ctx).cxx_compiler_info.compiler_type
+
+    # If headers-as-raw-headers is enabled, convert exported headers to raw
+    # headers, with the appropriate include directories.
+    raw_headers_mode = _attr_headers_as_raw_headers_mode(ctx)
+    inferred_inc_dirs = as_raw_headers(ctx, exported_header_map, raw_headers_mode)
+    if inferred_inc_dirs != None:
+        raw_headers.extend(exported_header_map.values())
+        if style == HeaderStyle("local"):
+            include_dirs.extend(inferred_inc_dirs)
+        else:
+            system_include_dirs.extend(inferred_inc_dirs)
+        exported_header_map.clear()
+
+    # Add in raw headers and include dirs from attrs.
+    raw_headers.extend(value_or(ctx.attrs.raw_headers, []))
+
+    # if raw-headers-as-headers is enabled, convert raw headers to headers
+    if _attr_raw_headers_as_headers_mode(ctx) != RawHeadersAsHeadersMode("disabled"):
+        if raw_headers:
+            exported_headers = as_headers(ctx, raw_headers, ctx.attrs.public_include_directories + ctx.attrs.public_system_include_directories)
+            exported_header_map = {paths.join(h.namespace, h.name): h.artifact for h in exported_headers}
+            raw_headers.clear()
+
+            # Force system exported header style if any system include directories are set.
+            if ctx.attrs.public_system_include_directories:
+                style = HeaderStyle("system")
+    else:
+        include_dirs.extend([ctx.label.path.add(x) for x in ctx.attrs.public_include_directories])
+        system_include_dirs.extend([ctx.label.path.add(x) for x in ctx.attrs.public_system_include_directories])
+
+    args = get_exported_preprocessor_args(ctx, exported_header_map, style, compiler_type, raw_headers, extra_preprocessors)
+
+    modular_args = []
+    for pre in extra_preprocessors:
+        modular_args.extend(pre.modular_args)
+
+    header_units = []
+    for pre in extra_preprocessors:
+        header_units.extend(pre.header_units)
+
+    return CPreprocessor(
+        args = args,
+        headers = exported_headers,
+        raw_headers = raw_headers,
+        include_dirs = include_dirs,
+        system_include_dirs = _system_include_dirs(compiler_type, system_include_dirs),
+        modular_args = modular_args,
+        header_units = header_units,
+        raw_include_dirs = ctx.attrs.public_include_directories,
+        raw_system_include_dirs = ctx.attrs.public_system_include_directories,
+    )
+
+def get_exported_preprocessor_args(
+    ctx: AnalysisContext,
+    headers: dict[str, Artifact],
+    style: HeaderStyle,
+    compiler_type: str,
+    raw_headers: list[Artifact],
+    extra_preprocessors: list[CPreprocessor],
+) -> CPreprocessorArgs:
+    cxx_toolchain_info = get_cxx_toolchain_info(ctx)
+    allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs)
+    header_root = prepare_headers(
+        ctx.actions,
+        cxx_toolchain_info,
+        headers,
+        "buck-headers",
+        map_val(HeaderMode, getattr(ctx.attrs, "header_mode", None)),
+        allow_cache_upload = allow_cache_upload,
+        uses_content_based_paths = True,
+        header_namespace = getattr(ctx.attrs, "header_namespace", None),
+    )
+    precompile_root = prepare_headers(
+        ctx.actions,
+        cxx_toolchain_info,
+        headers,
+        "buck-pre-headers",
+        HeaderMode("header_map_only"),
+        allow_cache_upload = allow_cache_upload,
+        uses_content_based_paths = True,
+    )
+
+    # Process args to handle the `$(cxx-header-tree)` macro.
+    #
+    # Note: said macro looks like it is used for user/macro-level modulemaps, which
+    # aren't compatible with header units precompilation. The macro expansion relies on
+    # the symlink tree, which isn't compatible with the hmap-only header mode used for
+    # precompile_args anyway.
+    args = []
+    precompile_args = []
+    for arg in cxx_attr_exported_preprocessor_flags(ctx):
+        precompile_args.append(arg)
+        if _needs_cxx_header_tree_hack(arg):
+            if header_root == None or header_root.symlink_tree == None:
+                fail("No headers")
+            arg = _cxx_header_tree_hack_replacement(header_root.symlink_tree)
+        args.append(arg)
+
+    # Propagate the exported header tree.
+    file_prefix_args = []
+    coverage_prefix_args = []
+    header_maps = []
+    if header_root != None:
+        args.extend(_header_style_args(style, header_root.include_path, compiler_type))
+        precompile_args.extend(_header_style_args(style, precompile_root.include_path, compiler_type))
+        if header_root.header_map != None:
+            header_maps.append(header_root.header_map)
+        if header_root.file_prefix_args != None:
+            file_prefix_args.append(header_root.file_prefix_args)
+        if header_root.coverage_prefix_args != None:
+            coverage_prefix_args.append(header_root.coverage_prefix_args)
+
+    # Embed raw headers as hidden artifacts in our args.  This means downstream
+    # cases which use these args don't also need to know to add raw headers.
+    if raw_headers:
+        # NOTE(agallagher): It's a bit weird adding an "empty" arg, but this
+        # appears to do the job (and not e.g. expand to `""`).
+        raw_header_args = cmd_args(hidden = raw_headers)
+        args.append(raw_header_args)
+        precompile_args.append(raw_header_args)
+
+    # Append any extra preprocessor info passed in via the constructor params
+    for pre in extra_preprocessors:
+        args.extend(pre.args.args)
+        precompile_args.extend(pre.args.precompile_args)
+        header_maps.extend(pre.args.header_maps)
+
+    if not args and not file_prefix_args and not coverage_prefix_args and not precompile_args:
+        return _EMPTY_CPREPROCESSOR_ARGS
+    return CPreprocessorArgs(
+        args = args, file_prefix_args = file_prefix_args, coverage_prefix_args = coverage_prefix_args, precompile_args = precompile_args, header_maps = header_maps
+    )
+
+def cxx_private_preprocessor_info(
+    ctx: AnalysisContext,
+    headers_layout: CxxHeadersLayout,
+    raw_headers: list[Artifact] = [],
+    extra_preprocessors: list[CPreprocessor] = [],
+    non_exported_deps: list[Dependency] = [],
+    is_test: bool = False,
+) -> (CPreprocessor, list[CPreprocessor]):
+    private_preprocessor = _cxx_private_preprocessor_info(ctx, headers_layout, raw_headers, extra_preprocessors)
+
+    test_preprocessors = []
+    if is_test:
+        for non_exported_dep in non_exported_deps:
+            preprocessor_for_tests = non_exported_dep.get(CPreprocessorForTestsInfo)
+            if preprocessor_for_tests and ctx.label.name in preprocessor_for_tests.test_names:
+                test_preprocessors.append(preprocessor_for_tests.own_non_exported_preprocessor)
+
+    return (private_preprocessor, test_preprocessors)
+
+def _cxx_private_preprocessor_info(
+    ctx: AnalysisContext, headers_layout: CxxHeadersLayout, raw_headers: list[Artifact], extra_preprocessors: list[CPreprocessor]
+) -> CPreprocessor:
+    """
+    This rule's preprocessor info which is only applied to the compilation of
+    its source, and not propagated to dependents.
+    """
+    compiler_type = get_cxx_toolchain_info(ctx).cxx_compiler_info.compiler_type
+    headers = cxx_attr_headers(ctx, headers_layout)
+
+    # `apple_*` rules allow headers to be included via only a basename if those
+    # are headers (private or exported) from the same target.
+    if headers_layout.naming == CxxHeadersNaming("apple"):
+        headers.extend(
+            _remap_headers_to_basename(
+                headers + cxx_attr_exported_headers(ctx, headers_layout),
+            ),
+        )
+
+    # Include any headers provided via constructor params and determine whether
+    # to use modules.
+    uses_modules = False
+    for pp in extra_preprocessors:
+        headers += pp.headers
+        uses_modules = uses_modules or pp.uses_modules
+
+    header_map = {paths.join(h.namespace, h.name): h.artifact for h in headers}
+
+    all_raw_headers = []
+    include_dirs = []
+
+    # If headers-as-raw-headers is enabled, convert exported headers to raw
+    # headers, with the appropriate include directories.
+    raw_headers_mode = _attr_headers_as_raw_headers_mode(ctx)
+    inferred_inc_dirs = as_raw_headers(ctx, header_map, raw_headers_mode)
+    if inferred_inc_dirs != None:
+        all_raw_headers.extend(header_map.values())
+        include_dirs.extend(inferred_inc_dirs)
+        header_map.clear()
+
+    # Add in raw headers and include dirs from attrs.
+    all_raw_headers.extend(raw_headers)
+
+    # if raw-headers-as-headers is enabled, convert raw headers to headers
+    if all_raw_headers and _attr_raw_headers_as_headers_mode(ctx) != RawHeadersAsHeadersMode("disabled"):
+        # private headers are also accessible via public_include_directories
+        # same as exported_preprocessor_flags apply to the target itself.
+        headers = as_headers(
+            ctx,
+            all_raw_headers,
+            ctx.attrs.include_directories + getattr(ctx.attrs, "public_include_directories", []) + getattr(ctx.attrs, "public_system_include_directories", []),
+        )
+        header_map = {paths.join(h.namespace, h.name): h.artifact for h in headers}
+        all_raw_headers.clear()
+    else:
+        include_dirs.extend([ctx.label.path.add(x) for x in ctx.attrs.include_directories])
+
+    args = _get_private_preprocessor_args(ctx, header_map, compiler_type, all_raw_headers)
+
+    # The remaining CPreprocessor fields use their defaults below, so these
+    # checks cover every field in the record.
+    if not headers and not all_raw_headers and not include_dirs and not uses_modules and args == _EMPTY_CPREPROCESSOR_ARGS:
+        return EMPTY_CPREPROCESSOR
+
+    return CPreprocessor(
+        args = args,
+        headers = headers,
+        raw_headers = all_raw_headers,
+        include_dirs = include_dirs,
+        uses_modules = uses_modules,
+    )
+
+def _get_private_preprocessor_args(
+    ctx: AnalysisContext, headers: dict[str, Artifact], compiler_type: str, all_raw_headers: list[Artifact]
+) -> CPreprocessorArgs:
+    # Create private header tree and propagate via args.
+    args = get_target_sdk_version_flags(ctx)
+    cxx_toolchain_info = get_cxx_toolchain_info(ctx)
+    file_prefix_args = []
+    coverage_prefix_args = []
+    header_maps = []
+    header_mode = map_val(HeaderMode, getattr(ctx.attrs, "header_mode", None))
+    allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs)
+    header_root = prepare_headers(
+        ctx.actions,
+        cxx_toolchain_info,
+        headers,
+        "buck-private-headers",
+        header_mode = header_mode,
+        allow_cache_upload = allow_cache_upload,
+        uses_content_based_paths = True,
+        header_namespace = getattr(ctx.attrs, "header_namespace", None),
+    )
+    if header_root != None:
+        args.extend(_format_include_arg("-I", header_root.include_path, compiler_type))
+        if header_root.header_map != None:
+            header_maps.append(header_root.header_map)
+        if header_root.file_prefix_args != None:
+            file_prefix_args.append(header_root.file_prefix_args)
+        if header_root.coverage_prefix_args != None:
+            coverage_prefix_args.append(header_root.coverage_prefix_args)
+
+    # Embed raw headers as hidden artifacts in our args.  This means downstream
+    # cases which use these args don't also need to know to add raw headers.
+    if all_raw_headers:
+        # NOTE(agallagher): It's a bit weird adding an "empty" arg, but this
+        # appears to do the job (and not e.g. expand to `""`).
+        args.append(cmd_args(hidden = all_raw_headers))
+
+    if not args and not file_prefix_args and not coverage_prefix_args:
+        return _EMPTY_CPREPROCESSOR_ARGS
+    return CPreprocessorArgs(args = args, file_prefix_args = file_prefix_args, coverage_prefix_args = coverage_prefix_args, header_maps = header_maps)
+
+def _by_language_cxx(x: dict[typing.Any, typing.Any]) -> list[typing.Any]:
+    return cxx_by_language_ext(x, ".cpp")
+
+def _header_style_args(style: HeaderStyle, path: cmd_args, compiler_type: str) -> list[cmd_args]:
+    if style == HeaderStyle("local"):
+        return _format_include_arg("-I", path, compiler_type)
+    if style == HeaderStyle("system"):
+        return format_system_include_arg(path, compiler_type)
+    fail("unsupported header style: {}".format(style))
+
+def _attr_raw_headers_as_headers_mode(ctx: AnalysisContext) -> RawHeadersAsHeadersMode:
+    """
+    Return the `RawHeadersAsHeadersMode` setting to use for this rule.
+    """
+
+    mode = get_cxx_toolchain_info(ctx).raw_headers_as_headers_mode
+
+    # If the platform hasn't set a raw headers translation mode, we don't do anything.
+    if mode == None:
+        return RawHeadersAsHeadersMode("disabled")
+
+    # Otherwise use the rule-specific setting, if provided (not available on prebuilt_cxx_library).
+    if getattr(ctx.attrs, "raw_headers_as_headers_mode", None) != None:
+        return RawHeadersAsHeadersMode(ctx.attrs.raw_headers_as_headers_mode)
+
+    # Fallback to platform default.
+    return mode
+
+def _attr_headers_as_raw_headers_mode(ctx: AnalysisContext) -> HeadersAsRawHeadersMode:
+    """
+    Return the `HeadersAsRawHeadersMode` setting to use for this rule.
+    """
+
+    mode = get_cxx_toolchain_info(ctx).headers_as_raw_headers_mode
+
+    # If the platform hasn't set a raw headers translation mode, we don't do anything.
+    if mode == None:
+        return HeadersAsRawHeadersMode("disabled")
+
+    # Otherwise use the rule-specific setting, if provided (not available on prebuilt_cxx_library).
+    if getattr(ctx.attrs, "headers_as_raw_headers_mode", None) != None:
+        return HeadersAsRawHeadersMode(ctx.attrs.headers_as_raw_headers_mode)
+
+    # Fallback to platform default.
+    return mode
+
+def _needs_cxx_header_tree_hack(arg: typing.Any) -> bool:
+    # The macro $(cxx-header-tree) is used in exactly once place, and its a place which isn't very
+    # Buck v2 compatible. We replace $(cxx-header-tree) with HACK-CXX-HEADER-TREE at attribute time,
+    # then here we substitute in the real header tree.
+    return "HACK-CXX-HEADER-TREE" in repr(arg)
+
+def _cxx_header_tree_hack_replacement(header_tree: Artifact) -> cmd_args:
+    # Unfortunately, we can't manipulate flags very precisely (for good reasons), so we rely on
+    # knowing the form it takes.
+    # The source is: -fmodule-map-file=$(cxx-header-tree)/module.modulemap
+    return cmd_args(header_tree, format = "-fmodule-map-file={}/module.modulemap")
+
+# Remap the given headers to be includable via their basenames (for use with
+# "apple" style header naming).
+def _remap_headers_to_basename(headers: list[CHeader]) -> list[CHeader]:
+    remapped_headers = []
+    for header in headers:
+        if not header.named:
+            remapped_headers.append(
+                CHeader(
+                    artifact = header.artifact,
+                    name = paths.basename(header.name),
+                    namespace = "",
+                    named = False,
+                )
+            )
+    return remapped_headers
+
+def get_flags_for_compiler_type(compiler_type: str) -> list[str]:
+    # MSVC requires this flag to enable external headers
+    if compiler_type in ["windows"]:
+        return ["/experimental:external", "/external:W0"]
+    else:
+        return []
diff --git a/buck2/prelude/cxx/shared_library_interface.bzl b/buck2/prelude/cxx/shared_library_interface.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/shared_library_interface.bzl
@@ -0,0 +1,87 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(":cxx_context.bzl", "get_cxx_toolchain_info")
+load(":cxx_library_utility.bzl", "EMPTY_DEFAULT_INFO")
+load(":cxx_toolchain_types.bzl", "CxxToolchainInfo")
+
+def _shared_library_interface(ctx: AnalysisContext, output: str, identifier: str, shared_lib: [Artifact, Promise]) -> Artifact:
+    """
+    Convert the given shared library into an interface used for linking.
+    """
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    if linker_info.mk_shlib_intf == None:
+        fail(
+            'Shared library interface generation is enabled (shlib_interfaces != "disabled") '
+            + "but the toolchain does not define `shared_library_interface_producer`. "
+            + "Either set `shared_library_interface_producer` in the toolchain or "
+            + 'disable shared library interfaces by setting `shlib_interfaces = "disabled"`.',
+        )
+    args = cmd_args(linker_info.mk_shlib_intf[RunInfo])
+    args.add(shared_lib)
+    output = ctx.actions.declare_output(output, has_content_based_path = True)
+    args.add(output.as_output())
+    ctx.actions.run(
+        args,
+        category = "generate_shared_library_interface",
+        identifier = identifier,
+    )
+    return output
+
+_InterfaceInfo = provider(
+    fields = {
+        "artifact": provider_field(typing.Any, default = None),  # "artifact"
+    }
+)
+
+def _anon_shared_library_interface_impl(ctx):
+    output = _shared_library_interface(
+        ctx = ctx,
+        output = ctx.attrs.output,
+        shared_lib = ctx.attrs.shared_lib,
+        identifier = ctx.attrs.identifier,
+    )
+    return [EMPTY_DEFAULT_INFO, _InterfaceInfo(artifact = output)]
+
+# Anonymous wrapper for `extract_symbol_names`.
+_anon_shared_library_interface = anon_rule(
+    impl = _anon_shared_library_interface_impl,
+    attrs = {
+        "identifier": attrs.option(attrs.string(), default = None),
+        "output": attrs.string(),
+        "shared_lib": attrs.source(),
+        "_cxx_toolchain": attrs.dep(providers = [CxxToolchainInfo]),
+    },
+    artifact_promise_mappings = {
+        "shared_library_interface": lambda p: p[_InterfaceInfo].artifact,
+    },
+)
+
+def shared_library_interface(ctx: AnalysisContext, shared_lib: Artifact, anonymous: bool = False) -> Artifact:
+    output = paths.join("__shlib_intfs__", shared_lib.short_path)
+
+    if anonymous:
+        shared_lib_interface_artifact = ctx.actions.anon_target(
+            _anon_shared_library_interface,
+            dict(
+                _cxx_toolchain = ctx.attrs._cxx_toolchain,
+                output = output,
+                shared_lib = shared_lib,
+                identifier = shared_lib.short_path,
+            ),
+        ).artifact("shared_library_interface")
+        shared_lib_interface_artifact = ctx.actions.assert_has_content_based_path(shared_lib_interface_artifact)
+        return ctx.actions.assert_short_path(shared_lib_interface_artifact, short_path = output)
+    else:
+        return _shared_library_interface(
+            ctx = ctx,
+            output = output,
+            shared_lib = shared_lib,
+            identifier = shared_lib.short_path,
+        )
diff --git a/buck2/prelude/cxx/symbols.bzl b/buck2/prelude/cxx/symbols.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/symbols.bzl
@@ -0,0 +1,440 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_library_utility.bzl", "EMPTY_DEFAULT_INFO")
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",
+    "LinkerType",
+)
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+
+def _extract_symbol_names(
+    ctx: AnalysisContext,
+    cxx_toolchain: CxxToolchainInfo,
+    name: str,
+    objects: list[Artifact],
+    category: str,
+    identifier: [str, None] = None,
+    defined_only: bool = False,
+    undefined_only: bool = False,
+    # Do not include undefined-weak symbols.
+    undefined_weak: bool = True,
+    dynamic: bool = False,
+    prefer_local: bool = False,
+    local_only: bool = False,
+    global_only: bool = False,
+    allow_cache_upload: bool = False,
+) -> Artifact:
+    """
+    Generate a file with a sorted list of symbol names extracted from the given
+    native objects.
+    """
+
+    if not objects:
+        fail("no objects provided")
+
+    if defined_only and undefined_only:
+        fail("only one of defined_only and undefined_only should be True")
+
+    if not undefined_weak and not undefined_only:
+        fail("can only use undefined_weak with undefined_only")
+
+    nm = cxx_toolchain.binary_utilities_info.nm
+    output = ctx.actions.declare_output(paths.join("__symbols__", name), has_content_based_path = True)
+
+    # -A: Prepend all lines with the name of the input file to which it
+    # corresponds.  Added only to make parsing the output a bit easier.
+    # -P: Generate portable output format
+    nm_flags = "-AP"
+    if global_only:
+        nm_flags += "g"
+    if undefined_only:
+        nm_flags += "u"
+
+    # darwin objects don't have dynamic symbol tables.
+    if dynamic and cxx_toolchain.linker_info.type != LinkerType("darwin"):
+        nm_flags += "D"
+
+    # llvm-nm supports -U for this but gnu nm doesn't.
+    if defined_only:
+        nm_flags += " --defined-only"
+
+    is_windows = hasattr(ctx.attrs, "_exec_os_type") and ctx.attrs._exec_os_type[OsLookup].os == Os("windows")
+
+    if is_windows:
+        script = """& {{
+                $result = & $args[0] {} $($args[1..($args.Length-1)] -join " ")
+                $lines = $result -split '`n'
+                $lines = $lines | ForEach-Object {{ ($_ -split ' ')[1] }}
+                $lines = $lines | ForEach-Object {{ ($_ -split '@')[0] }}
+                $lines = $lines | Where-Object {{ $_ -notmatch '__odr_asan_gen_.*' }}
+                $lines = $lines | Sort-Object -Unique -CaseSensitive
+                # Avoid a trailing newline for empty symbol lists
+                if ($lines.count -eq 0) {{
+                    [IO.File]::WriteAllText('{{}}', $lines)
+                }} else {{
+                    [IO.File]::WriteAllLines('{{}}', $lines)
+                }}
+            }}""".format(nm_flags)
+        symbol_extraction_args = [
+            "powershell",
+            "-Command",
+            cmd_args(output.as_output(), format = script),
+        ]
+    else:
+        script = (
+            "set -euo pipefail; "
+            + '"$1" {} "${{@:2}}"'.format(nm_flags)
+            + (' | (grep -v "\\sw\\s*$" || true)' if undefined_only and not undefined_weak else "")
+            +
+            # Grab only the symbol name field.
+            ' | cut -d" " -f2 '
+            +
+            # Strip off ABI Version (@...) when using llvm-nm to keep compat with buck1
+            " | cut -d@ -f1 "
+            +
+            # Remove ASAN ODR generated symbols: __odr_asan_gen_*. They are
+            # handled by a separate asan_dynamic_list.txt list of asan patterns.
+            # BUT MORE IMPORTANTLY, symbols like __odr_asan_XXX[abi:cxx11] force
+            # lld into a code path that repeatedly does a linear scan of all
+            # symbols for O(num_patterns_with_bracket * num_symbols) (because of
+            # the [] being treated as a glob pattern). This totally tanks link
+            # time for builds with sanitizers! Anecdotally, a binary with 3.7M
+            # symbols and 2K __odr_asan_XXX[abi:cxx11] can spend 6 mins
+            # processing patterns and 10s actually linking. We use sed instead
+            # of grep -v here to avoid an error exit code when there's no input
+            # symbols, which is not an error for us.
+            ' | sed "/__odr_asan_gen_.*/d"'
+            +
+            # These symbols are meant to be weak locals in the binary, with
+            # definitions found on the platform. When using open source
+            # toolchain and declaring these symbols as weak, the symbols
+            # get promoted to global weak and thus failed to link due to
+            # undefined symbols.
+            ' | sed "/__gmon_start__/d"'
+            + ' | sed "/_ITM_deregisterTMCloneTable/d"'
+            + ' | sed "/_ITM_registerTMCloneTable/d"'
+            + ' | sed "/MallocExtension_Internal_GetNumericProperty/d"'
+            + ' | sed "/_ZTHN3c104impl26raw_local_dispatch_key_setE/d"'
+            +
+            # Sort and dedup symbols.  Use the `C` locale and do it in-memory to
+            # make it significantly faster. CAUTION: if ten of these processes
+            # run in parallel, they'll have cumulative allocations larger than RAM.
+            " | LC_ALL=C sort -S 10% -u > {}"
+        )
+        symbol_extraction_args = [
+            "/usr/bin/env",
+            "bash",
+            "-c",
+            cmd_args(output.as_output(), format = script),
+            "",
+        ]
+
+    ctx.actions.run(
+        symbol_extraction_args
+        + [
+            nm,
+        ]
+        + objects,
+        category = category,
+        identifier = identifier,
+        prefer_local = prefer_local,
+        local_only = local_only,
+        weight_percentage = 15,  # 10% + a little padding
+        allow_cache_upload = allow_cache_upload,
+    )
+
+    return output
+
+_SymbolsInfo = provider(
+    fields = {
+        "artifact": provider_field(typing.Any, default = None),  # "artifact"
+    }
+)
+
+def _anon_extract_symbol_names_impl(ctx):
+    output = _extract_symbol_names(
+        ctx = ctx,
+        cxx_toolchain = ctx.attrs._cxx_toolchain[CxxToolchainInfo],
+        category = ctx.attrs.category,
+        dynamic = ctx.attrs.dynamic,
+        global_only = ctx.attrs.global_only,
+        identifier = ctx.attrs.identifier,
+        local_only = ctx.attrs.local_only,
+        name = ctx.attrs.output,
+        objects = ctx.attrs.objects,
+        prefer_local = ctx.attrs.prefer_local,
+        undefined_only = ctx.attrs.undefined_only,
+        undefined_weak = ctx.attrs.undefined_weak,
+        allow_cache_upload = ctx.attrs.allow_cache_upload,
+    )
+    return [EMPTY_DEFAULT_INFO, _SymbolsInfo(artifact = output)]
+
+# Anonymous wrapper for `extract_symbol_names`.
+_anon_extract_symbol_names_impl_rule = anon_rule(
+    impl = _anon_extract_symbol_names_impl,
+    attrs = {
+        "allow_cache_upload": attrs.bool(default = False),
+        "category": attrs.string(),
+        "dynamic": attrs.bool(default = False),
+        "global_only": attrs.bool(default = False),
+        "identifier": attrs.option(attrs.string(), default = None),
+        "local_only": attrs.bool(default = False),
+        "objects": attrs.list(attrs.source()),
+        "output": attrs.string(),
+        "prefer_local": attrs.bool(default = False),
+        "undefined_only": attrs.bool(default = False),
+        "undefined_weak": attrs.bool(default = True),
+        "_cxx_toolchain": attrs.dep(providers = [CxxToolchainInfo]),
+    },
+    artifact_promise_mappings = {
+        "symbols": lambda p: p[_SymbolsInfo].artifact,
+    },
+)
+
+def extract_symbol_names(ctx: AnalysisContext, cxx_toolchain: CxxToolchainInfo, name: str, anonymous: bool = False, **kwargs) -> Artifact:
+    """
+    Generate a file with a sorted list of symbol names extracted from the given
+    native objects.
+    """
+
+    if anonymous:
+        cxx_toolchain_from_attrs = ctx.attrs._cxx_toolchain[CxxToolchainInfo]
+        if cxx_toolchain != cxx_toolchain_from_attrs:
+            fail("anon symbol extraction requires that the cxx_toolchain be from the _cxx_toolchain attr")
+        artifact = ctx.actions.anon_target(
+            _anon_extract_symbol_names_impl_rule,
+            dict(_cxx_toolchain = ctx.attrs._cxx_toolchain, output = name, **kwargs),
+        ).artifact("symbols")
+        artifact = ctx.actions.assert_has_content_based_path(artifact)
+
+        return ctx.actions.assert_short_path(artifact, short_path = paths.join("__symbols__", name))
+    else:
+        return _extract_symbol_names(ctx = ctx, cxx_toolchain = cxx_toolchain, name = name, **kwargs)
+
+def extract_defined_syms(
+    ctx: AnalysisContext,
+    cxx_toolchain: CxxToolchainInfo,
+    output: Artifact,
+    category_prefix: str,
+    prefer_local: bool = False,
+    anonymous: bool = False,
+    allow_cache_upload: bool = False,
+) -> Artifact:
+    return extract_symbol_names(
+        ctx = ctx,
+        cxx_toolchain = cxx_toolchain,
+        name = output.short_path + ".defined_syms.txt",
+        objects = [output],
+        dynamic = True,
+        global_only = True,
+        defined_only = True,
+        category = "{}_defined_syms".format(category_prefix),
+        identifier = output.short_path,
+        prefer_local = prefer_local,
+        anonymous = anonymous,
+        allow_cache_upload = allow_cache_upload,
+    )
+
+def extract_undefined_syms(
+    ctx: AnalysisContext,
+    cxx_toolchain: CxxToolchainInfo,
+    output: Artifact,
+    category_prefix: str,
+    weak: bool = True,
+    prefer_local: bool = False,
+    anonymous: bool = False,
+    allow_cache_upload: bool = False,
+    hash_counter = 0,
+) -> Artifact:
+    name = "extracted_symbol_names/{}-{}.undefined_syms.txt".format(str(hash(output.short_path)), str(hash_counter))
+    return extract_symbol_names(
+        ctx = ctx,
+        cxx_toolchain = cxx_toolchain,
+        name = name,
+        objects = [output],
+        dynamic = True,
+        global_only = True,
+        undefined_only = True,
+        undefined_weak = weak,
+        category = "{}_undefined_syms".format(category_prefix),
+        identifier = output.short_path,
+        prefer_local = prefer_local,
+        anonymous = anonymous,
+        allow_cache_upload = allow_cache_upload,
+    )
+
+def extract_global_syms(
+    ctx: AnalysisContext,
+    cxx_toolchain: CxxToolchainInfo,
+    output: Artifact,
+    category_prefix: str,
+    prefer_local: bool = False,
+    anonymous: bool = False,
+    allow_cache_upload: bool = False,
+) -> Artifact:
+    return extract_symbol_names(
+        ctx = ctx,
+        cxx_toolchain = cxx_toolchain,
+        name = output.short_path + ".global_syms.txt",
+        objects = [output],
+        dynamic = True,
+        global_only = True,
+        category = "{}_global_syms".format(category_prefix),
+        identifier = output.short_path,
+        prefer_local = prefer_local,
+        anonymous = anonymous,
+        allow_cache_upload = allow_cache_upload,
+    )
+
+def _create_symbols_file_from_script(
+    actions: AnalysisActions,
+    name: str,
+    script: str,
+    symbol_files: list[Artifact],
+    category: str,
+    prefer_local: bool,
+    weight_percentage: int,
+    identifier: [str, None] = None,
+) -> Artifact:
+    """
+    Generate a symbols file from from the given objects and
+    link args.
+    """
+
+    all_symbol_files = actions.write(name + ".symbols", symbol_files, has_content_based_path = False)
+    all_symbol_files = cmd_args(all_symbol_files, hidden = symbol_files)
+    output = actions.declare_output(name, has_content_based_path = True)
+    cmd = [
+        "/usr/bin/env",
+        "bash",
+        "-c",
+        script,
+        "",
+        all_symbol_files,
+        output.as_output(),
+    ]
+    actions.run(
+        cmd,
+        category = category,
+        prefer_local = prefer_local,
+        weight_percentage = weight_percentage,
+        identifier = identifier,
+    )
+    return output
+
+def get_undefined_symbols_args(
+    ctx: AnalysisContext, name: str, symbol_files: list[Artifact], category: [str, None] = None, identifier: [str, None] = None, prefer_local: bool = False
+) -> cmd_args:
+    argsfile = create_undefined_symbols_argsfile(
+        ctx.actions,
+        name,
+        symbol_files,
+        category,
+        identifier,
+        prefer_local,
+    )
+    return cmd_args(argsfile, format = "@{}")
+
+def create_undefined_symbols_argsfile(
+    actions: AnalysisActions, name: str, symbol_files: list[Artifact], category: [str, None] = None, identifier: [str, None] = None, prefer_local: bool = False
+) -> Artifact:
+    """
+    Combine files with sorted lists of symbols names into an argsfile to pass
+    to the linker to mark these symbols as undefined via `-u`.
+    """
+    return _create_symbols_file_from_script(
+        actions = actions,
+        name = name,
+        script = """\
+set -euo pipefail
+tr '\\n' '\\0' < "$1" > "$2.files0.txt"
+LC_ALL=C sort -S 10% -u -m --files0-from="$2.files0.txt" | sed "s/^/-u/" > "$2"
+""",
+        symbol_files = symbol_files,
+        category = category,
+        identifier = identifier,
+        prefer_local = prefer_local,
+        weight_percentage = 15,  # 10% + a little padding
+    )
+
+def create_undefined_symbols_linker_script(
+    actions: AnalysisActions, name: str, symbol_files: list[Artifact], category: [str, None] = None, identifier: [str, None] = None, prefer_local: bool = False
+) -> Artifact:
+    """
+    Combine files with sorted lists of symbols names into a linker script
+    to mark these symbols as undefined via EXTERN.
+    """
+    return _create_symbols_file_from_script(
+        actions = actions,
+        name = name,
+        script = """\
+set -euo pipefail;
+echo "EXTERN(" > "$2";
+tr '\\n' '\\0' < "$1" > "$2.files0.txt"
+LC_ALL=C sort -S 10% -u -m --files0-from="$2.files0.txt" >> "$2";
+echo ")" >> "$2";
+""",
+        symbol_files = symbol_files,
+        category = category,
+        identifier = identifier,
+        prefer_local = prefer_local,
+        weight_percentage = 15,  # 10% + a little padding
+    )
+
+def create_global_symbols_version_script(
+    actions: AnalysisActions, name: str, symbol_files: list[Artifact], identifier: [str, None] = None, category: [str, None] = None, prefer_local: bool = False
+) -> Artifact:
+    """
+    Combine files with sorted lists of symbols names into an argsfile to pass
+    to the linker to mark these symbols as undefined (e.g. `-m`).
+    """
+    return _create_symbols_file_from_script(
+        actions = actions,
+        name = name,
+        script = """\
+set -euo pipefail
+echo "{" > "$2"
+echo "  global:" >> "$2"
+tr '\\n' '\\0' < "$1" > "$2.files0.txt"
+LC_ALL=C sort -S 10% -u -m --files0-from="$2.files0.txt" | awk '{print "    \\""$1"\\";"}' >> "$2"
+echo "  local: *;" >> "$2"
+echo "};" >> "$2"
+""",
+        symbol_files = symbol_files,
+        category = category,
+        identifier = identifier,
+        prefer_local = prefer_local,
+        weight_percentage = 15,  # 10% + a little padding
+    )
+
+def create_dynamic_list_version_script(
+    actions: AnalysisActions, name: str, symbol_files: list[Artifact], identifier: [str, None] = None, category: [str, None] = None, prefer_local: bool = False
+) -> Artifact:
+    """
+    Combine files with sorted lists of symbols names into a dynamic list version
+    file that can be passed to the linked (e.g. via `--dynamic-list=<file>`).
+    """
+    return _create_symbols_file_from_script(
+        actions = actions,
+        name = name,
+        script = """\
+set -euo pipefail
+echo "{" > "$2"
+tr '\\n' '\\0' < "$1" > "$2.files0.txt"
+LC_ALL=C sort -S 10% -u -m --files0-from="$2.files0.txt" | awk '{print "    \\""$1"\\";"}' >> "$2"
+echo "};" >> "$2"
+""",
+        symbol_files = symbol_files,
+        category = category,
+        identifier = identifier,
+        prefer_local = prefer_local,
+        weight_percentage = 15,  # 10% + a little padding
+    )
diff --git a/buck2/prelude/cxx/target_sdk_version.bzl b/buck2/prelude/cxx/target_sdk_version.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/target_sdk_version.bzl
@@ -0,0 +1,77 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_apple_linker_flags.bzl", "apple_format_metal_target_triple", "apple_format_target_triple", "apple_target_triple_flags")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_platform_info", "get_cxx_toolchain_info")
+
+def version_is_greater(left: str, right: str) -> bool:
+    # Assumes version strings are in dotted format 1.2.4.
+    # After comparing components the longer remainder is
+    # considered larger.
+    left_components = left.split(".")
+    right_components = right.split(".")
+    for pair in zip(left_components, right_components):
+        x = int(pair[0])
+        y = int(pair[1])
+        if x < y:
+            return False
+        elif x > y:
+            return True
+
+    return len(left_components) > len(right_components)
+
+def get_target_sdk_version(ctx: AnalysisContext) -> [None, str]:
+    if not (hasattr(ctx.attrs, "_cxx_toolchain") or hasattr(ctx.attrs, "_apple_toolchain")):
+        return None
+
+    toolchain_target_sdk_version = get_cxx_toolchain_info(ctx).minimum_os_version
+    target_sdk_version = getattr(ctx.attrs, "target_sdk_version", None)
+    if toolchain_target_sdk_version == None:
+        if target_sdk_version == None:
+            return None
+        # There should never be cases where a target has `target_sdk_version`
+        # without the toolchain having a version as well.
+        fail(
+            "Found target which sets `target_sdk_version` for Apple platforms without the toolchain having a `minimum_os_version`, this results in undefined behavior at runtime"
+        )
+
+    if target_sdk_version and version_is_greater(target_sdk_version, toolchain_target_sdk_version):
+        # The requested target_sdk_version on the toolchain must be >=
+        # the version set on the target, which should be the minimum
+        # allowed for this version to build.
+        fail(
+            "{} has target_sdk_version {}, which is larger than the toolchain target_sdk_version of {}".format(
+                ctx.label,
+                target_sdk_version,
+                toolchain_target_sdk_version,
+            )
+        )
+
+    return toolchain_target_sdk_version
+
+def _format_target_triple(ctx: AnalysisContext, version: str) -> str:
+    platform_info = get_cxx_platform_info(ctx)
+    return apple_format_target_triple(platform_info.name, version)
+
+def get_target_triple(ctx: AnalysisContext) -> [None, str]:
+    target_sdk_version = get_target_sdk_version(ctx)
+    if target_sdk_version == None:
+        return None
+
+    return _format_target_triple(ctx, target_sdk_version)
+
+def get_versioned_metal_target_triple(ctx: AnalysisContext, version: str) -> str:
+    platform_info = get_cxx_platform_info(ctx)
+    return apple_format_metal_target_triple(platform_info.name, version)
+
+def get_unversioned_target_triple(ctx: AnalysisContext) -> str:
+    return _format_target_triple(ctx, "")
+
+def get_target_sdk_version_flags(ctx: AnalysisContext) -> list[str]:
+    target_triple = get_target_triple(ctx)
+    return apple_target_triple_flags(target_triple)
diff --git a/buck2/prelude/cxx/tools/BUCK b/buck2/prelude/cxx/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/BUCK
@@ -0,0 +1,143 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load(":defs.bzl", "cxx_hacks", "cxx_internal_tools")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+cxx_internal_tools(
+    name = "internal_tools",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "check_nonempty_output",
+    main = "check_nonempty_output.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "hmap_wrapper.py",
+    main = "hmap_wrapper.py",
+)
+
+prelude.command_alias(
+    name = "hmap_wrapper",
+    args = [
+        "--hmap-tool=$(location prelude//third-party/hmaptool:hmaptool)",
+    ],
+    exe = ":hmap_wrapper.py",
+    labels = ["buck2-only"],
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "make_comp_db",
+    main = "make_comp_db.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "dep_file_processor",
+    main = "dep_file_processor.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":dep_file_processors",
+    ],
+)
+
+prelude.python_bootstrap_library(
+    name = "dep_file_processors",
+    srcs = [
+        "dep_file_utils.py",
+        "makefile_to_dep_file.py",
+        "show_headers_to_dep_file.py",
+        "show_includes_to_dep_file.py",
+    ],
+)
+
+prelude.python_bootstrap_binary(
+    name = "linker_wrapper",
+    main = "linker_wrapper.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "remap_cwd",
+    main = "remap_cwd.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "stub_header_unit",
+    main = "stub_header_unit.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "simple_ar",
+    main = "simple_ar.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "clang_tidy_wrapper",
+    main = "clang_tidy_wrapper.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "concatenate_diagnostics",
+    main = "concatenate_diagnostics.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "stderr_to_file",
+    main = "stderr_to_file.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.sh_binary(
+    name = "serialized_diagnostics_to_json_wrapper",
+    main = "serialized_diagnostics_to_json_wrapper.sh",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "filter_argsfile",
+    main = "filter_argsfile.py",
+    visibility = ["PUBLIC"],
+)
+
+# Required to support the $(cxx-header-tree) macro
+cxx_hacks(
+    name = "cxx_hacks",
+    visibility = ["PUBLIC"],
+)
+
+# Type checking target for Python tool scripts
+prelude.python_library(
+    name = "scripts-typing",
+    srcs = [
+        "check_nonempty_output.py",
+        "clang_tidy_wrapper.py",
+        "concatenate_diagnostics.py",
+        "dep_file_processor.py",
+        "dep_file_utils.py",
+        "filter_argsfile.py",
+        "hmap_wrapper.py",
+        "linker_wrapper.py",
+        "make_comp_db.py",
+        "makefile_to_dep_file.py",
+        "remap_cwd.py",
+        "show_headers_to_dep_file.py",
+        "show_includes_to_dep_file.py",
+        "simple_ar.py",
+        "stderr_to_file.py",
+        "stub_header_unit.py",
+    ],
+    typing = True,
+)
diff --git a/buck2/prelude/cxx/tools/check_nonempty_output.py b/buck2/prelude/cxx/tools/check_nonempty_output.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/check_nonempty_output.py
@@ -0,0 +1,45 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import os
+import subprocess
+import sys
+
+
+def check_nonempty_output(command_parts):
+    # Find the output file specified after the '-o' flag
+    try:
+        output_index = command_parts.index("-o") + 1
+        output_file = command_parts[output_index]
+    except (ValueError, IndexError):
+        print("Warning: Output file not specified with '-o'.")
+
+    # Run the command with the current environment
+    try:
+        subprocess.run(command_parts, check=True, env=os.environ)
+    except subprocess.CalledProcessError as e:
+        if e.returncode == -11:
+            print(
+                f"Segmentation fault detected in subprocess:\n{' '.join(command_parts)}"
+            )
+        sys.exit(e.returncode)
+
+    # Check if the output file is not empty
+    if os.path.exists(output_file) and os.path.getsize(output_file) == 0:
+        print("Error: Output file is empty.")
+        sys.exit(1)
+
+
+if __name__ == "__main__":
+    if len(sys.argv) < 2:
+        print("Usage: python check_nonempty_output.py <command> [args...]")
+        sys.exit(1)
+
+    # Collect all command-line arguments except the script name
+    command_parts = sys.argv[1:]
+    check_nonempty_output(command_parts)
diff --git a/buck2/prelude/cxx/tools/clang_tidy_wrapper.py b/buck2/prelude/cxx/tools/clang_tidy_wrapper.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/clang_tidy_wrapper.py
@@ -0,0 +1,171 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Wrapper that generates a compile_commands.json and runs clang-tidy.
+
+Usage:
+    clang_tidy_wrapper.py \\
+        --output=path/to/diagnostics.txt \\
+        --clang-tidy=path/to/clang-tidy \\
+        --source=path/to/file.cpp \\
+        -- <compile_command> [args...]
+
+The compile command after -- is the same as what make_comp_db.py gen receives:
+the compiler binary followed by all flags and argsfiles. This wrapper expands
+argsfiles, filters out fbcc-specific flags (e.g. --cc, --log-fbcc), writes a
+single-entry compile_commands.json to a temporary directory, and invokes
+clang-tidy with -p pointing to that directory.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shlex
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+# ---------------------------------------------------------------------------
+# fbcc flag filtering (inlined from lib/FbccFilterArgs.py)
+# ---------------------------------------------------------------------------
+
+_JOINED_PREFIX_FLAGS: tuple[str, ...] = (
+    "--cc=",
+    "--fbcc-create-external-debug-info=",
+    "--log-fbcc=",
+    "-fbcc-opts=",
+)
+
+_STANDALONE_FLAGS: tuple[str, ...] = ("--show-flags",)
+
+_XFBCC_APPEND_FLAG = "-XfbccAppend"
+
+
+def _filter_fbcc_args(args: list[str]) -> list[str]:
+    """Return *args* with all fbcc-specific flags removed.
+
+    ``-XfbccAppend <value>`` consumes two tokens; the value is appended to the
+    end of the returned list (mirroring fbcc's own reordering behaviour).
+    """
+    filtered: list[str] = []
+    appended: list[str] = []
+    it = iter(args)
+    for arg in it:
+        if any(arg.startswith(p) for p in _JOINED_PREFIX_FLAGS):
+            continue
+        if arg in _STANDALONE_FLAGS:
+            continue
+        if arg == _XFBCC_APPEND_FLAG:
+            value = next(it, None)
+            if value is not None:
+                appended.append(value)
+            continue
+        filtered.append(arg)
+    filtered.extend(appended)
+    return filtered
+
+
+# ---------------------------------------------------------------------------
+# Argsfile expansion
+# ---------------------------------------------------------------------------
+
+
+def expand_argsfiles(arguments: list[str]) -> list[str]:
+    """Expand @argsfile references recursively."""
+    result = []
+    for arg in arguments:
+        if arg.startswith("@"):
+            with open(arg[1:]) as f:
+                tokens = []
+                for line in f:
+                    tokens.extend(shlex.split(line))
+                result.extend(expand_argsfiles(tokens))
+        else:
+            result.append(arg)
+    return result
+
+
+# ---------------------------------------------------------------------------
+# Main
+# ---------------------------------------------------------------------------
+
+
+def main() -> int:
+    argv = sys.argv[1:]
+    try:
+        sep_idx = argv.index("--")
+        our_args = argv[:sep_idx]
+        compile_command = argv[sep_idx + 1 :]
+    except ValueError:
+        print("error: missing -- separator", file=sys.stderr)
+        return 1
+
+    output: Path | None = None
+    clang_tidy: str | None = None
+    source: str | None = None
+
+    i = 0
+    while i < len(our_args):
+        arg = our_args[i]
+        if arg.startswith("--output="):
+            output = Path(arg.split("=", 1)[1])
+        elif arg.startswith("--clang-tidy="):
+            clang_tidy = arg.split("=", 1)[1]
+        elif arg.startswith("--source="):
+            source = arg.split("=", 1)[1]
+        i += 1
+
+    if not output or not clang_tidy or not source:
+        print(
+            "error: --output, --clang-tidy, and --source are required",
+            file=sys.stderr,
+        )
+        return 1
+
+    expanded_args = expand_argsfiles(compile_command)
+    expanded_args = _filter_fbcc_args(expanded_args)
+
+    source_abspath = os.path.abspath(source)
+    entry = [
+        {
+            "file": source_abspath,
+            "directory": os.getcwd(),
+            "arguments": expanded_args,
+        },
+    ]
+
+    with tempfile.TemporaryDirectory() as tmpdir:
+        comp_db_path = os.path.join(tmpdir, "compile_commands.json")
+        with open(comp_db_path, "w") as f:
+            json.dump(entry, f)
+
+        cmd = [
+            clang_tidy,
+            "-p",
+            tmpdir,
+            source,
+        ]
+
+        result = subprocess.run(
+            cmd,
+            capture_output=True,
+        )
+
+    diagnostics = result.stdout + result.stderr
+    output.write_bytes(diagnostics)
+    sys.stderr.buffer.write(diagnostics)
+    sys.stderr.flush()
+
+    return result.returncode
+
+
+sys.exit(main())
diff --git a/buck2/prelude/cxx/tools/compilation_database.bxl b/buck2/prelude/cxx/tools/compilation_database.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/compilation_database.bxl
@@ -0,0 +1,70 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:comp_db.bzl", "CxxCompilationDbInfo")
+load("@prelude//cxx:compile_types.bzl", "CxxSrcCompileCommand")
+load("@prelude//utils:utils.bzl", "flatten")
+
+def _make_entry(ctx: bxl.Context, target: Label, compile_command: CxxSrcCompileCommand, add_target_name: bool) -> dict:
+    args = compile_command.cxx_compile_cmd.base_compile_cmd.copy()
+    args.add(compile_command.cxx_compile_cmd.argsfile.cmd_form)
+    args.add(compile_command.args)
+    ctx.output.ensure_multiple(args)
+
+    result = {
+        "arguments": args,
+        "directory": ctx.fs.abs_path_unsafe(ctx.root()),
+        "file": compile_command.src,
+    }
+
+    if add_target_name:
+        result["target"] = target.configured_target().raw_target()
+
+    return result
+
+def _impl(ctx: bxl.Context):
+    targets = ctx.configured_targets(flatten(ctx.cli_args.targets), modifiers = ctx.modifiers)
+    if ctx.cli_args.recursive:
+        targets = ctx.cquery().deps(targets)
+
+    actions = ctx.bxl_actions().actions
+
+    db = []
+    for name, target in ctx.analysis(targets).items():
+        comp_db_info = target.providers().get(CxxCompilationDbInfo)
+        if comp_db_info:
+            for cc in comp_db_info.info.values():
+                if ctx.cli_args.include_headers or (not cc.is_header):
+                    db.append(_make_entry(ctx, name, cc, ctx.cli_args.add_target_name))
+
+    db_file = actions.declare_output("compile_commands.json", has_content_based_path = False)
+    actions.write_json(db_file.as_output(), db, with_inputs = True, pretty = True)
+    ctx.output.print(ctx.output.ensure(db_file))
+
+generate = bxl_main(
+    doc = "Generate a compilation database for a set of targets and print its path to stdout",
+    impl = _impl,
+    cli_args = {
+        "add-target-name": cli_args.bool(
+            default = False,
+            doc = "Include the name of the target in the compilation database entries (non-standard)",
+        ),
+        "include-headers": cli_args.bool(
+            default = True,
+            doc = "Include header file compilation db actions",
+        ),
+        "recursive": cli_args.bool(
+            default = False,
+            doc = "Automatically include all dependent targets in the generated compilation db",
+        ),
+        "targets": cli_args.list(
+            cli_args.configured_target_expr(),
+            doc = "Targets to generate the database for",
+        ),
+    },
+)
diff --git a/buck2/prelude/cxx/tools/concatenate_diagnostics.py b/buck2/prelude/cxx/tools/concatenate_diagnostics.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/concatenate_diagnostics.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Usage: concatenate_diagnostics.py --out path/to/output.txt [path/to/input.txt...]
+"""
+
+import argparse
+from pathlib import Path
+from typing import List, NamedTuple
+
+
+class Args(NamedTuple):
+    out: Path
+    subtarget_diagnostics: List[Path]
+
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--out", type=Path, required=True)
+    parser.add_argument("subtarget_diagnostics", nargs="*", type=Path)
+    args = Args(**vars(parser.parse_args()))
+
+    needs_blank_line = False
+    with open(args.out, "wb") as out:
+        for f in args.subtarget_diagnostics:
+            with open(f, "rb") as f:
+                content = f.read()
+            if len(content) == 0:
+                continue
+            if needs_blank_line:
+                out.write(b"\n")
+            out.write(content)
+            needs_blank_line = True
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/cxx/tools/defs.bzl b/buck2/prelude/cxx/tools/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/defs.bzl
@@ -0,0 +1,65 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxInternalTools", "DistLtoToolsInfo")
+
+def _cxx_internal_tools_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        CxxInternalTools(
+            check_nonempty_output = ctx.attrs.check_nonempty_output[RunInfo],
+            clang_tidy_wrapper = ctx.attrs.clang_tidy_wrapper[RunInfo],
+            concatenate_diagnostics = ctx.attrs.concatenate_diagnostics[RunInfo],
+            dep_file_processor = ctx.attrs.dep_file_processor[RunInfo],
+            dist_lto = ctx.attrs.dist_lto[DistLtoToolsInfo],
+            filter_argsfile = ctx.attrs.filter_argsfile[RunInfo],
+            hmap_wrapper = ctx.attrs.hmap_wrapper[RunInfo],
+            make_comp_db = ctx.attrs.make_comp_db[RunInfo],
+            remap_cwd = ctx.attrs.remap_cwd[RunInfo],
+            serialized_diagnostics_to_json_wrapper = ctx.attrs.serialized_diagnostics_to_json_wrapper[RunInfo],
+            stderr_to_file = ctx.attrs.stderr_to_file[RunInfo],
+            stub_header_unit = ctx.attrs.stub_header_unit[RunInfo],
+        ),
+    ]
+
+cxx_internal_tools = rule(
+    impl = _cxx_internal_tools_impl,
+    attrs = {
+        "check_nonempty_output": attrs.default_only(
+            attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:check_nonempty_output"),
+        ),
+        "clang_tidy_wrapper": attrs.default_only(
+            attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:clang_tidy_wrapper"),
+        ),
+        "concatenate_diagnostics": attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:concatenate_diagnostics"),
+        "dep_file_processor": attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:dep_file_processor"),
+        "dist_lto": attrs.dep(providers = [DistLtoToolsInfo], default = "prelude//cxx/dist_lto/tools:dist_lto_tools"),
+        "filter_argsfile": attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:filter_argsfile"),
+        "hmap_wrapper": attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:hmap_wrapper"),
+        "make_comp_db": attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:make_comp_db"),
+        "remap_cwd": attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:remap_cwd"),
+        "serialized_diagnostics_to_json_wrapper": attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:serialized_diagnostics_to_json_wrapper"),
+        "stderr_to_file": attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:stderr_to_file"),
+        "stub_header_unit": attrs.dep(providers = [RunInfo], default = "prelude//cxx/tools:stub_header_unit"),
+    },
+)
+
+def _cxx_hacks_impl(_ctx):
+    return [
+        DefaultInfo(),
+        TemplatePlaceholderInfo(
+            unkeyed_variables = {
+                "cxx-header-tree": "/dev/null/HACK-CXX-HEADER-TREE",
+            },
+        ),
+    ]
+
+cxx_hacks = rule(
+    impl = _cxx_hacks_impl,
+    attrs = {},
+)
diff --git a/buck2/prelude/cxx/tools/dep_file_processor.py b/buck2/prelude/cxx/tools/dep_file_processor.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/dep_file_processor.py
@@ -0,0 +1,47 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import sys
+
+from makefile_to_dep_file import process_dep_file
+from show_headers_to_dep_file import process_show_headers_dep_file
+from show_includes_to_dep_file import process_show_includes_dep_file
+
+
+def main():
+    """
+    Determines which dep file processor to use according to compiler type.
+
+    First argument is
+    dep_tracking_mode which is one of these values [ makefile | show_includes | show_headers | none].
+
+    For each mode we expect different arguments:
+
+    makefile -> intermediary_dep_file, dep_file, cmd_args
+    show_includes -> input_file, dep_file, cmd_args
+    show_headers -> input_file, dep_file, cmd_args
+
+    Where:
+
+    input_file -> Path to file we're generating the dep file for
+    intermediary_dep_file -> File where compiler output is generated to
+    dep_file -> Expected output path
+    cmd_args -> Args to be executed in order to get dependencies
+    """
+
+    dep_tracking_mode = sys.argv[1]
+    if dep_tracking_mode == "show_headers":
+        process_show_headers_dep_file(sys.argv[3], sys.argv[4:], sys.argv[2])
+    elif dep_tracking_mode == "show_includes":
+        process_show_includes_dep_file(sys.argv[3], sys.argv[4:], sys.argv[2])
+    else:
+        process_dep_file(sys.argv[2:])
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/cxx/tools/dep_file_utils.py b/buck2/prelude/cxx/tools/dep_file_utils.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/dep_file_utils.py
@@ -0,0 +1,42 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import os
+
+
+def normalize_and_write_deps(deps, dst_path):
+    cwd = os.getcwd() + os.sep
+    cwd = cwd.replace("\\", "/")
+    normalized_deps = []
+    for dep in deps:
+        # The paths we get sometimes include "../" components, so get rid
+        # of those because we want ForwardRelativePath here.
+        dep = os.path.normpath(dep).replace("\\", "/")
+
+        if os.path.isabs(dep):
+            if dep.startswith(cwd):
+                # The dep file included a path inside the build root, but
+                # expressed an absolute path. In this case, rewrite it to
+                # be a relative path.
+                dep = dep[len(cwd) :]
+            else:
+                # The dep file included a path to something outside the
+                # build root. That's bad (actions shouldn't depend on
+                # anything outside the build root), but that dependency is
+                # therefore not tracked by Buck2 (which can only see things
+                # in the build root), so it cannot be represented as a
+                # dependency and therefore we don't include it (event if we
+                # could include it, this could never cause a miss).
+                continue
+
+        normalized_deps.append(dep)
+
+    with open(dst_path, "w") as f:
+        for dep in normalized_deps:
+            f.write(dep)
+            f.write("\n")
diff --git a/buck2/prelude/cxx/tools/filter_argsfile.py b/buck2/prelude/cxx/tools/filter_argsfile.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/filter_argsfile.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import re
+import sys
+
+
+def main():
+    if len(sys.argv) != 4:
+        print(f"Usage: {sys.argv[0]} <pattern> <input_file> <output_file>")
+        sys.exit(1)
+    pattern = sys.argv[1]
+    input_file = sys.argv[2]
+    output_file = sys.argv[3]
+    regex = re.compile(pattern)
+    with open(input_file, "r") as infile, open(output_file, "w") as outfile:
+        for line in infile:
+            if not regex.search(line):
+                outfile.write(line)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/cxx/tools/hmap_wrapper.py b/buck2/prelude/cxx/tools/hmap_wrapper.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/hmap_wrapper.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import itertools
+import json
+import os
+import shlex
+import subprocess
+import sys
+import tempfile
+
+
+def main(argv):
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--hmap-tool", required=True)
+    parser.add_argument("--output", required=True)
+    parser.add_argument("--mappings-file", required=True)
+    parser.add_argument("--project-root-file", required=False)
+    args = parser.parse_args(argv[1:])
+
+    with open(args.mappings_file, "r") as argsfile:
+        mapping_args = shlex.split(argsfile.read())
+
+    if len(mapping_args) % 2 != 0:
+        parser.error("mappings must be dest-source pairs")
+
+    # Convert the hmap mappings passed on the command line to a dict.
+    mappings = {}
+    for src, dst in itertools.zip_longest(*([iter(mapping_args)] * 2)):
+        mappings[src] = dst
+
+        # NOTE(agallagher): Add a mapping from the mapped path to itself. If
+        # this is not present, clang will use the mapped path as the new key
+        # and continue searching subsequent header maps, which has a couple
+        # implications: a) it's slower, as we still search every header map and
+        # b) it means we need to use a `-I` anchor to finally terminate the
+        # search.
+        mappings[dst] = dst
+
+    # Write out the mappings to a JSON file that LLVM's hmaptool accepts.
+    with tempfile.TemporaryDirectory() as td:
+        output_filename = os.path.join(td, "output")
+        with open(output_filename, mode="w") as tf:
+            json.dump({"mappings": mappings}, tf, sort_keys=True, indent=2)
+
+        # Delegate to LLVM's hmaptool to generate the hmap.
+        subprocess.check_call(
+            [sys.executable, args.hmap_tool, "write", output_filename, args.output]
+        )
+
+
+sys.exit(main(sys.argv))
diff --git a/buck2/prelude/cxx/tools/linker_wrapper.py b/buck2/prelude/cxx/tools/linker_wrapper.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/linker_wrapper.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import codecs
+import os
+import subprocess
+import sys
+import tempfile
+
+
+def unquote(argument):
+    if len(argument) > 2 and argument[0] == '"' and argument[-1] == '"':
+        return argument[1:-1]
+    else:
+        return argument
+
+
+def is_relative_buck_out_path(argument):
+    return argument.startswith("buck-out\\")
+
+
+def is_library_path(argument):
+    return argument.endswith(".lib")
+
+
+def is_whole_archive_option(argument):
+    return argument.startswith("/WHOLEARCHIVE")
+
+
+def expand_library_path(argument, full_library_paths):
+    library_name = argument.split(":", maxsplit=1)[-1]
+    return "/WHOLEARCHIVE:" + full_library_paths[library_name]
+
+
+# NOTE: it does not check for cycles
+def expand_args(arguments):
+    expanded = []
+    for argument in arguments:
+        unquoted_argument = unquote(argument)
+        if unquoted_argument.startswith("@"):
+            filename = unquoted_argument[1:]
+            with open(filename, mode="rb") as f:
+                file_content = f.read()
+            if file_content.startswith(codecs.BOM_UTF16):
+                string = file_content.decode("utf-16")
+            else:
+                string = file_content.decode("utf-8")
+            expanded.extend(expand_args(string.splitlines()))
+        else:
+            expanded.append(argument)
+    return expanded
+
+
+def main():
+    linker_real, rest = sys.argv[1], sys.argv[2:]
+    working_dir = os.getcwd()
+
+    arguments = expand_args(rest)
+
+    full_library_paths = {}
+    new_args = []
+    for argument in arguments:
+        argument = unquote(argument)
+
+        # Save library paths to support expanding them afterwards
+        if is_library_path(argument):
+            library_name = os.path.basename(argument)
+            full_library_paths[library_name] = argument
+
+        # LLVM linker expects full path in /WHOLEARCHIVE option while MSVC
+        # expects just the filename. That's why we need to expand the path.
+        if is_whole_archive_option(argument):
+            argument = expand_library_path(argument, full_library_paths)
+
+        # Make relative paths absolute for support paths longer than 260 chars.
+        if is_relative_buck_out_path(argument):
+            argument = os.path.join(working_dir, argument)
+
+        new_args.append(argument)
+
+    # Based on rustc's @linker-arguments file construction.
+    # https://github.com/rust-lang/rust/blob/1.69.0/compiler/rustc_codegen_ssa/src/back/link.rs#L1383-L1407
+    quoted_new_args = ('"{}"\n'.format(arg) for arg in new_args)
+    new_args_content = "".join(quoted_new_args).encode("utf-16")
+
+    debug = "[\n" + "".join('    "{}"\n'.format(arg) for arg in new_args) + "]"
+    print(f"linker_args = {debug}", file=sys.stderr)
+
+    with tempfile.NamedTemporaryFile(mode="wb", delete=False) as new_args_file:
+        new_args_file.write(new_args_content)
+        new_args_file_name = new_args_file.name
+
+    command = [linker_real, "@" + new_args_file_name]
+    subprocess.run(command, check=True)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/cxx/tools/make_comp_db.py b/buck2/prelude/cxx/tools/make_comp_db.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/make_comp_db.py
@@ -0,0 +1,103 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Utility to create compilation DBs
+
+$ make_comp_db.py gen --output=entry.json foo.cpp -- g++ -c -fPIC
+$ make_comp_db.py gen --output=entry2.json foo2.cpp -- g++ -c -fPIC
+$ make_comp_db.py merge --output=comp_db.json entry.json entry2.json
+"""
+
+import argparse
+import json
+import shlex
+import sys
+from typing import List
+
+
+def process_arguments(arguments: List[str]) -> List[str]:
+    """
+    Process arguments to expand argsfiles.
+    """
+
+    combined_arguments = []
+    for arg in arguments:
+        if arg.startswith("@"):
+            with open(arg[1:]) as argsfile:
+                # The argsfile's arguments are separated by newlines; we
+                # don't want those included in the argument list.
+                lines = [" ".join(shlex.split(line)) for line in argsfile.readlines()]
+                # Support nested argsfiles.
+                combined_arguments.extend(process_arguments(lines))
+        else:
+            combined_arguments.append(arg)
+    return combined_arguments
+
+
+def gen(args: argparse.Namespace) -> None:
+    """
+    Generate a single compilation command in JSON form.
+    """
+
+    entry = {}
+    entry["file"] = args.directory + "/" + args.filename
+    entry["directory"] = "."
+    entry["arguments"] = process_arguments(args.arguments)
+
+    json.dump(entry, args.output, indent=2)
+    args.output.close()
+
+
+def merge(args: argparse.Namespace) -> None:
+    """
+    Merge multiple compilation DB commands into a single DB.
+    """
+
+    entries = []
+    for entry in args.entries:
+        if entry.startswith("@"):
+            with open(entry[1:]) as argsfile:
+                sub_entries = map(str.strip, argsfile.readlines())
+
+                for sub_entry in sub_entries:
+                    with open(sub_entry) as g:
+                        entries.append(json.load(g))
+        else:
+            with open(entry) as f:
+                entries.append(json.load(f))
+
+    json.dump(entries, args.output, indent=2)
+    args.output.close()
+
+
+def main(argv: List[str]) -> int:
+    parser = argparse.ArgumentParser()
+    subparsers = parser.add_subparsers()
+
+    parser_gen = subparsers.add_parser("gen")
+    parser_gen.add_argument("--output", type=argparse.FileType("w"), default=sys.stdout)
+    parser_gen.add_argument("filename")
+    parser_gen.add_argument("directory")
+    parser_gen.add_argument("arguments", nargs="*")
+    parser_gen.set_defaults(func=gen)
+
+    parser_merge = subparsers.add_parser("merge")
+    parser_merge.add_argument(
+        "--output", type=argparse.FileType("w"), default=sys.stdout
+    )
+    parser_merge.add_argument("entries", nargs="*")
+    parser_merge.set_defaults(func=merge)
+
+    args = parser.parse_args(argv[1:])
+    args.func(args)
+    return 0
+
+
+sys.exit(main(sys.argv))
diff --git a/buck2/prelude/cxx/tools/makefile_to_dep_file.py b/buck2/prelude/cxx/tools/makefile_to_dep_file.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/makefile_to_dep_file.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import subprocess
+import sys
+
+import dep_file_utils
+
+
+def rewrite_dep_file(src_path, dst_path):
+    """
+    Convert a makefile to a depfile suitable for use by Buck2. The files we
+    rewrite look like P488268797.
+    """
+
+    with open(src_path) as f:
+        body = f.read()
+
+    parts = body.split(": ", 1)
+    body = parts[1] if len(parts) == 2 else ""
+
+    # Escaped newlines are not meaningful so remove them.
+    body = body.replace("\\\n", "")
+
+    # Now, recover targets. They are space separated, but we need to ignore
+    # spaces that are escaped.
+    pos = 0
+
+    deps = []
+    current_parts = []
+
+    def push_slice(s):
+        if s:
+            current_parts.append(s)
+
+    def flush_current_dep():
+        if current_parts:
+            deps.append("".join(current_parts))
+            current_parts.clear()
+
+    while True:
+        next_pos = body.find(" ", pos)
+
+        # If we find the same character we started at, this means we started on
+        # a piece of whitespace. We know this cannot be escaped, because if we
+        # started here that means we stopped at the previous character, which
+        # means it must have been whitespace as well.
+        if next_pos == pos:
+            flush_current_dep()
+            pos += 1
+            continue
+
+        # No more whitespace, so this means that whatever is left from our
+        # current position to the end is the last dependency (assuming there is
+        # anything).
+        if next_pos < 0:
+            push_slice(body[pos:].rstrip("\n"))
+            break
+
+        # Check if this was escaped by looking at the previous character. If it
+        # was, then insert the part before the escape, and then push a space.
+        # If it wasn't, then we've reached the end of a dependency.
+        if next_pos > 0 and body[next_pos - 1] == "\\":
+            push_slice(body[pos : next_pos - 1])
+            push_slice(" ")
+        else:
+            push_slice(body[pos:next_pos])
+            flush_current_dep()
+
+        pos = next_pos + 1
+
+    flush_current_dep()
+
+    # Now that we've parsed deps, we need to normalize them.
+    dep_file_utils.normalize_and_write_deps(deps, dst_path)
+
+
+def process_dep_file(args):
+    """
+    Expects the src dep file to be the first argument, dst dep file to be the
+    second argument, and the command to follow.
+    """
+    ret = subprocess.call(args[2:], stdin=subprocess.DEVNULL)
+    if ret == 0:
+        rewrite_dep_file(args[0], args[1])
+    sys.exit(ret)
diff --git a/buck2/prelude/cxx/tools/remap_cwd.py b/buck2/prelude/cxx/tools/remap_cwd.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/remap_cwd.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Usage: remap_cwd.py path/to/compiler [args...]
+
+Runs `path/to/compiler [args...] -ffile-prefix-map=$PWD=. -Wa,--debug-prefix-map=$PWD=.`
+
+Flags are appended so that compiler wrappers using "$@" see the real binary as $1. Using $PWD=.
+remaps both DW_AT_comp_dir (which GCC sets to exactly $PWD without trailing slash) and source file
+paths. -Wa,--debug-prefix-map is needed because GCC does not pass -ffile-prefix-map through to the
+assembler for .s/.S/.sx files.
+"""
+
+import os
+import subprocess
+import sys
+
+
+if __name__ == "__main__":
+    cwd = os.getcwd()
+
+    ret = subprocess.call(
+        [
+            *sys.argv[1:],
+            f"-ffile-prefix-map={cwd}=.",
+            f"-Wa,--debug-prefix-map={cwd}=.",
+        ],
+    )
+    sys.exit(ret)
diff --git a/buck2/prelude/cxx/tools/serialized_diagnostics_to_json_wrapper.sh b/buck2/prelude/cxx/tools/serialized_diagnostics_to_json_wrapper.sh
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/serialized_diagnostics_to_json_wrapper.sh
@@ -0,0 +1,26 @@
+#!/bin/bash
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Wrapper script to convert serialized diagnostics output to JSON
+# for Buck error handler consumption. Usage:
+#  serialized_diagnostics_to_json_wrapper.sh <serialized_diags_to_json> <output_json> compile args
+serialized_diags_to_json="$1"
+shift
+output_json="$1"
+output_serialized="$1.dia"
+shift
+"$@" --serialize-diagnostics "$output_serialized"
+ret=$?
+if [ $ret -eq 0 ]; then
+    # We always need to output a JSON file, even if the compiler succeeded.
+    echo "[]" > "$output_json"
+else
+    $serialized_diags_to_json "$output_serialized" > "$output_json"
+fi
+exit $ret
diff --git a/buck2/prelude/cxx/tools/show_headers_to_dep_file.py b/buck2/prelude/cxx/tools/show_headers_to_dep_file.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/show_headers_to_dep_file.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import re
+import sys
+from subprocess import PIPE, run
+
+import dep_file_utils
+
+
+# output_path -> path to write the dep file to
+# cmd_args -> command to be run to get dependencies from compiler
+# input_file -> Path to the file we're generating the dep file for. We need this since
+# when generating dependencies for a file using show_headers, the output does not include
+# the file itself, so we need the path to add it manually
+def process_show_headers_dep_file(output_path, cmd_args, input_file):
+    ret = run(cmd_args, stderr=PIPE, encoding="utf-8")
+    parse_into_dep_file(ret.stderr, output_path, input_file, ret.returncode)
+    sys.exit(ret.returncode)
+
+
+def parse_into_dep_file(output, dst_path, input_file, returncode):
+    """
+    Convert stderr generated by clang to dep file. This will be a mix of output like:
+
+    warning: this is a warning!
+    .path/to/dep1.h
+    ..path/to/dep2.h
+    ...path/to/dep3.h
+
+    and we want to get:
+
+    path/to/dep1.h
+    path/to/dep2.h
+    path/to/dep3.h
+
+    """
+
+    lines = output.splitlines()
+
+    if returncode == 0:
+        deps = []
+        for line in lines:
+            if line.startswith("."):
+                path = remove_leading_dots(line.replace(" ", ""))
+                if len(path) > 0:
+                    deps.append(path.strip())
+                    continue
+            print(line, file=sys.stderr)  # This was a warning/error
+
+        deps.append(input_file)
+        dep_file_utils.normalize_and_write_deps(deps, dst_path)
+    else:
+        for line in lines:
+            if re.match(r"^\.+ ", line):
+                continue
+
+            print(line, file=sys.stderr)
+
+
+def remove_leading_dots(s):
+    while s.startswith("."):
+        s = s[1:]
+    return s
diff --git a/buck2/prelude/cxx/tools/show_includes_to_dep_file.py b/buck2/prelude/cxx/tools/show_includes_to_dep_file.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/show_includes_to_dep_file.py
@@ -0,0 +1,66 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import subprocess
+import sys
+
+import dep_file_utils
+
+DEP_PREFIX = "Note: including file:"
+
+
+# output_path -> path to write the dep field to
+# cmd_args -> command to be run to get dependencies from compiler
+# source_file -> Path to the file we're generating the dep file for. We need this since
+# when generating dependencies for a file using show_headers, the output does not include
+# the file itself, so we need the path to add it manually
+def process_show_includes_dep_file(output_path, cmd_args, input_file):
+    out = subprocess.run(cmd_args, stdout=subprocess.PIPE, encoding="utf-8")
+    if out.returncode == 0:
+        rewrite_dep_file_for_msvc(out.stdout, output_path, input_file)
+    else:
+        parse_stdout_error_output(out.stdout)
+    sys.exit(out.returncode)
+
+
+def rewrite_dep_file_for_msvc(output, dst_path, input_file):
+    """
+    Convert stdout generated by MSVC to dep file. This will be a mix of output like:
+
+    file.cpp
+    Note: including file: path/to/dep1.h
+    Note: including file:  path/to/dep2.h
+    Note: including file:   path/to/dep3.h
+    error: this is an error!
+
+    and we want to get:
+
+    path/to/dep1.h
+    path/to/dep2.h
+    path/to/dep3.h
+
+    """
+    deps = []
+    # First line is the name of the file we're generating deps for.
+    # We manually include it later so let's ignore it.
+    lines = output.splitlines()[1:]
+    for line in lines:
+        if DEP_PREFIX in line:
+            line = line.replace(DEP_PREFIX, "").strip()
+            deps.append(line)
+        else:
+            print(line, file=sys.stderr)
+    deps.append(input_file)
+    dep_file_utils.normalize_and_write_deps(deps, dst_path)
+
+
+def parse_stdout_error_output(output):
+    lines = output.splitlines()[1:]
+    for line in lines:
+        if DEP_PREFIX not in line:
+            print(line, file=sys.stderr)
diff --git a/buck2/prelude/cxx/tools/simple_ar.py b/buck2/prelude/cxx/tools/simple_ar.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/simple_ar.py
@@ -0,0 +1,142 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+For certain platform and linker versions (e.g. LLD 15+ for ELF), the
+linker ignores the archive symbol table and accesses archive members
+directly. When combined with thin archives, this produces trivial
+archive files just embedding object paths, but ar (both GNU and LLVM)
+still requires access to the object files to produce the archive,
+resulting in unnecessary downloads and RE traffic. This implementation
+instead embeds the paths directly without needing the actual files
+present. The trade-offs are:
+- Any problems in the object files will be detected at link time instead
+  of archive creation time. This should be very rare though.
+- Since we can't access the object files, we store their sizes as zero
+  instead of the actual file size in the archive member headers. LLD for
+  ELF handles this correctly but I can't speak to other linkers.
+"""
+
+import argparse
+import os.path
+import typing as t
+from pathlib import Path
+
+
+class ThinArchive:
+    MAGIC = b"!<thin>\n"
+
+    def __init__(self, inputs: t.Sequence[Path], output: Path) -> None:
+        self._output = output
+        # llvm-ar always uses the long name member, and we follow suit for simplicity.
+        self._create_name_data(inputs, output.parent)
+
+    def write(self) -> None:
+        with self._output.open("wb") as archive:
+            archive.write(self.MAGIC)
+            self._write_member_header(
+                archive,
+                name="//",
+                mtime="",
+                owner_id="",
+                group_id="",
+                mode="",
+                size=len(self._name_data),
+            )
+            archive.write(self._name_data)
+
+            for offset in self._name_offsets:
+                self._write_member_header(
+                    archive,
+                    name=f"/{offset}",
+                    mtime="0",
+                    owner_id="0",
+                    group_id="0",
+                    mode="644",
+                    size=0,  # as discussed in the file docblock
+                )
+
+    def _create_name_data(self, inputs: t.Sequence[Path], output_dir: Path) -> None:
+        self._name_data = bytearray()
+        self._name_offsets = []
+        for input_path in inputs:
+            # Paths are stored relative to the archive. We use os.path.relpath instead
+            # of Pathlib.relative_to because the latter requires a common root. We use
+            # forward slashes everywhere for consistency and to mimic llvm-ar.
+            relative_path = Path(os.path.relpath(input_path, output_dir)).as_posix()
+            encoded = (relative_path + "/\n").encode()  # add terminator
+            self._name_offsets.append(len(self._name_data))
+            self._name_data.extend(encoded)
+
+        if len(self._name_data) % 2 != 0:
+            self._name_data.extend(b"\n")  # pad to an even size
+
+    def _write_member_header(
+        self,
+        archive: t.BinaryIO,
+        *,
+        name: str,
+        mtime: str,
+        owner_id: str,
+        group_id: str,
+        mode: str,
+        size: int,
+    ) -> None:
+        # https://en.wikipedia.org/wiki/Ar_(Unix)#File_header
+        archive.write(self._encode_header_field(name, 16))
+        archive.write(self._encode_header_field(mtime, 12))
+        archive.write(self._encode_header_field(owner_id, 6))
+        archive.write(self._encode_header_field(group_id, 6))
+        archive.write(self._encode_header_field(mode, 8))
+        archive.write(self._encode_header_field(str(size), 10))
+        archive.write(b"`\n")  # ending characters
+
+    def _encode_header_field(self, value: str, length: int) -> bytes:
+        encoded = value.encode()
+        padding = length - len(encoded)
+        if padding < 0:
+            raise ValueError(f"Encoding of {str} is larger than {length} bytes")
+
+        return encoded + b" " * padding
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Simple thin archive creator", fromfile_prefix_chars="@"
+    )
+    parser.add_argument("modifiers", help="Operation and modifiers (limited support)")
+    parser.add_argument("output", type=Path, help="The output file")
+    parser.add_argument("inputs", nargs="+", help="The input files")
+    args = parser.parse_args()
+
+    if args.output.exists():
+        raise ValueError(
+            f"Appending to an existing archive ({args.output}) is unsupported"
+        )
+
+    thin = False
+    for modifier in args.modifiers:
+        if modifier == "s":
+            raise ValueError("Archive symbol tables are unsupported")
+        elif modifier == "T":
+            thin = True
+        elif modifier not in "qcSD":
+            raise ValueError(f"Unsupported operation or modifier {modifier}")
+
+    if not thin:
+        raise ValueError("Only thin archives are supported")
+
+    # Strip any leading or trailing quotes (present in Windows argsfiles)
+    inputs = [Path(p.lstrip('"').rstrip('"')) for p in args.inputs]
+    archive = ThinArchive(inputs, args.output)
+    archive.write()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/cxx/tools/stderr_to_file.py b/buck2/prelude/cxx/tools/stderr_to_file.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/stderr_to_file.py
@@ -0,0 +1,103 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Usage: stderr_to_file.py --out=path/to/output path/to/clang++ [args...]
+"""
+
+import argparse
+import asyncio
+import signal
+import subprocess
+import sys
+from pathlib import Path
+from typing import List, NamedTuple
+
+
+# Exit code of `bash -c 'sleep 100'` <CTRL+C>
+_INTERRUPTED = 128 + signal.SIGINT.value
+
+
+class Args(NamedTuple):
+    out: Path
+    command: List[str]
+
+
+class SubprocessProtocol(asyncio.SubprocessProtocol):
+    """Write subprocess stderr to both self.out and sys.stderr"""
+
+    def __init__(self, out, exit_future):
+        self.out = out
+        self.exit_future = exit_future
+        self.pipe_closed = False
+        self.exited = False
+
+    def pipe_data_received(self, fd, data):
+        if fd == sys.stderr.fileno():
+            # Blocking write to file. This is buffered in a Python
+            # io.BufferedRandom.
+            self.out.write(data)
+            # Blocking unbuffered write to stderr. Our writes will be exactly as
+            # buffered as the subprocess's writes.
+            sys.stderr.buffer.write(data)
+            sys.stderr.flush()
+
+    def pipe_connection_lost(self, fd, exc):
+        if fd == sys.stderr.fileno():
+            self.pipe_closed = True
+            # Either of pipe_connection_lost() or process_exited() can be called
+            # before the other. Wait until both methods are called.
+            self._check_for_exit()
+
+    def process_exited(self):
+        self.exited = True
+        # Either of pipe_connection_lost() or process_exited() can be called
+        # before the other. Wait until both methods are called.
+        self._check_for_exit()
+
+    def _check_for_exit(self):
+        if self.pipe_closed and self.exited:
+            try:
+                self.exit_future.set_result(True)
+            except asyncio.InvalidStateError:
+                # Event loop has shut down.
+                pass
+
+
+async def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--out", type=Path, required=True)
+    parser.add_argument("command", nargs=argparse.REMAINDER)
+    args = Args(**vars(parser.parse_args()))
+
+    loop = asyncio.get_running_loop()
+    exit_future = asyncio.Future(loop=loop)
+
+    with open(args.out, "wb+") as out:
+        transport, protocol = await loop.subprocess_exec(
+            lambda: SubprocessProtocol(out, exit_future),
+            *args.command,
+            stdin=None,  # inherit
+            stdout=None,  # inherit
+            stderr=subprocess.PIPE,
+        )
+        await exit_future
+        transport.close()
+
+    returncode = transport.get_returncode()
+    if returncode is None:
+        return _INTERRUPTED
+    else:
+        return returncode
+
+
+try:
+    sys.exit(asyncio.run(main()))
+except KeyboardInterrupt:
+    sys.exit(_INTERRUPTED)
diff --git a/buck2/prelude/cxx/tools/stub_header_unit.py b/buck2/prelude/cxx/tools/stub_header_unit.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/tools/stub_header_unit.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Usage: stub_header_unit.py [...] -o <output> [-MF <depfile>] [...]
+
+Runs the preprocessor and hashes the output to produce a stub file.
+
+Transforms compiler arguments:
+- Intercepts -o
+- Replaces --precompile with -E and redirects output to a temporary file
+  (some compiler wrappers suppress stdout)
+- Intercepts -MF to use a temporary file
+"""
+
+import hashlib
+import os
+import shlex
+import subprocess
+import sys
+import tempfile
+
+DEBUG = os.environ.get("STUB_HEADER_UNIT_DEBUG") == "1"
+
+
+def parse_and_transform_args(
+    args: list[str],
+    temp_depfile: str,
+) -> tuple[str | None, str | None, list[str]]:
+    """
+    Parse arguments to extract --cc, -o, and transform remaining args.
+
+    Args:
+        args: Command line arguments
+        temp_depfile: Path to temporary depfile to use for -MF
+
+    Returns:
+        (output_file, transformed_args)
+    """
+    output_file: str | None = None
+    transformed_args: list[str] = []
+
+    i = 0
+    while i < len(args):
+        arg = args[i]
+
+        if arg == "-o":
+            if i + 1 < len(args):
+                output_file = args[i + 1]
+                i += 2
+            else:
+                i += 1
+        elif arg.startswith("-o"):
+            # Handle -o<file> without space
+            output_file = arg[2:]
+            i += 1
+        elif arg == "--precompile":
+            # Replace --precompile with -E
+            transformed_args.append("-E")
+            i += 1
+        elif arg == "-MF":
+            # Replace -MF argument with our temporary file
+            if i + 1 < len(args):
+                transformed_args.append("-MF")
+                transformed_args.append(temp_depfile)
+                i += 2
+            else:
+                i += 1
+        elif arg.startswith("-MF"):
+            # Handle -MF<file> without space - replace with our temp file
+            transformed_args.append("-MF" + temp_depfile)
+            i += 1
+        else:
+            transformed_args.append(arg)
+            i += 1
+
+    return output_file, transformed_args
+
+
+def run_preprocessor(args: list[str]) -> bytes:
+    """
+    Run the preprocessor and return its output.
+
+    Uses -o with a temporary file since some compiler wrappers suppress stdout.
+    """
+    with tempfile.NamedTemporaryFile(
+        mode="wb", suffix=".i", delete=False
+    ) as temp_output:
+        temp_output_path = temp_output.name
+
+    try:
+        cmd = args + ["-o", temp_output_path]
+        if DEBUG:
+            print("command=" + shlex.join(cmd))
+        subprocess.run(cmd, check=True)
+        with open(temp_output_path, "rb") as f:
+            return f.read()
+    finally:
+        try:
+            os.unlink(temp_output_path)
+        except OSError:
+            pass
+
+
+def compute_hash(data: bytes) -> str:
+    """
+    Compute SHA1 hash of the given data.
+    """
+    return hashlib.sha1(data).hexdigest()
+
+
+if __name__ == "__main__":
+    # Skip argv[0]
+    args = sys.argv[1:]
+
+    # Create a temporary file for the dependency output (currently we ignore it, but in
+    # future we might want to examine the content for module deps)
+    with tempfile.NamedTemporaryFile(
+        mode="w", suffix=".d", delete=False
+    ) as temp_depfile:
+        temp_depfile_path = temp_depfile.name
+
+    try:
+        output_file, transformed_args = parse_and_transform_args(
+            args, temp_depfile_path
+        )
+
+        if output_file is None:
+            print("Error: No output file specified with -o", file=sys.stderr)
+            sys.exit(1)
+
+        try:
+            preprocessor_output = run_preprocessor(transformed_args)
+        except subprocess.CalledProcessError as e:
+            print(
+                f"Error: Preprocessor failed with exit code {e.returncode}",
+                file=sys.stderr,
+            )
+            if e.stderr:
+                sys.stderr.buffer.write(e.stderr)
+            sys.exit(e.returncode)
+
+        if DEBUG:
+            print("contents=" + str(preprocessor_output))
+        content_hash = compute_hash(preprocessor_output)
+
+        with open(output_file, "w") as f:
+            f.write(f"{content_hash}\n")
+
+    finally:
+        # Clean up temporary file
+        try:
+            os.unlink(temp_depfile_path)
+        except OSError:
+            pass
+
+    sys.exit(0)
diff --git a/buck2/prelude/cxx/transformation_spec.bzl b/buck2/prelude/cxx/transformation_spec.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/transformation_spec.bzl
@@ -0,0 +1,128 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//utils:build_graph_pattern.bzl",
+    "BuildGraphInfo",
+    "BuildGraphPattern",
+    "parse_build_graph_pattern",
+)
+load(
+    "@prelude//utils:build_target_pattern.bzl",
+    "BuildTargetPattern",
+    "parse_build_target_pattern",
+)
+load(
+    "@prelude//utils:strings.bzl",
+    "strip_prefix",
+)
+
+TransformationKind = enum(
+    "debug",
+    "optimized",
+)
+
+TransformationResultProvider = provider(
+    fields = {
+        "determine_transformation": provider_field(typing.Callable[[Label, BuildGraphInfo], TransformationKind | None]),
+        "is_empty": provider_field(bool),
+    }
+)
+
+TransformationTest = record(
+    matcher = Label | BuildTargetPattern | BuildGraphPattern,
+    result = TransformationKind,
+)
+
+TransformationSpecContext = record(
+    provider = TransformationResultProvider,
+    graph_info = BuildGraphInfo,
+)
+
+def build_transformation_spec_context(ctx: AnalysisContext, graph_info: BuildGraphInfo) -> TransformationSpecContext | None:
+    transformation_provider = (
+        ctx.attrs.transformation_spec[TransformationResultProvider] if (hasattr(ctx.attrs, "transformation_spec") and ctx.attrs.transformation_spec) else None
+    )
+    if not transformation_provider:
+        return None
+
+    return TransformationSpecContext(
+        provider = transformation_provider,
+        graph_info = graph_info,
+    )
+
+def _build_pattern_matcher(entry: str) -> BuildTargetPattern | None:
+    pattern = strip_prefix("pattern:", entry)
+    if pattern == None:
+        return None
+    return parse_build_target_pattern(pattern)
+
+def _build_graph_matcher(entry: str) -> BuildGraphPattern | None:
+    pattern = strip_prefix("graph:", entry)
+    if pattern == None:
+        return None
+    return parse_build_graph_pattern(pattern)
+
+def _build_transformations(transformations: list[(str | Dependency, str)]) -> list[TransformationTest]:
+    parsed_transformations = []
+    for entry in transformations:
+        kind = TransformationKind(entry[1])
+        if isinstance(entry[0], Dependency):
+            parsed_transformations.append(
+                TransformationTest(
+                    matcher = entry[0].label,
+                    result = kind,
+                )
+            )
+            continue
+
+        target_pattern_matcher = _build_pattern_matcher(entry[0])
+        if target_pattern_matcher:
+            parsed_transformations.append(
+                TransformationTest(
+                    matcher = target_pattern_matcher,
+                    result = kind,
+                )
+            )
+            continue
+
+        graph_matcher = _build_graph_matcher(entry[0])
+        if graph_matcher:
+            parsed_transformations.append(
+                TransformationTest(
+                    matcher = graph_matcher,
+                    result = kind,
+                )
+            )
+            continue
+
+        fail("Invalid matcher provided: " + entry[0])
+    return parsed_transformations
+
+def build_determine_transformation(transformations: list[TransformationTest]) -> typing.Callable[[Label, BuildGraphInfo], TransformationKind | None]:
+    def callable(label: Label, graph_info: BuildGraphInfo) -> TransformationKind | None:
+        for transform in transformations:
+            if isinstance(transform.matcher, BuildTargetPattern) and transform.matcher.matches(label):
+                return transform.result
+            elif isinstance(transform.matcher, Label) and transform.matcher == label:
+                return transform.result
+            elif isinstance(transform.matcher, BuildGraphPattern) and transform.matcher.matches(label, graph_info):
+                return transform.result
+
+        return None
+
+    return callable
+
+def transformation_spec_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        TransformationResultProvider(
+            is_empty = len(ctx.attrs.transformations) == 0,
+            determine_transformation = build_determine_transformation(_build_transformations(ctx.attrs.transformations)),
+        ),
+    ]
diff --git a/buck2/prelude/cxx/user/cxx_toolchain_override.bzl b/buck2/prelude/cxx/user/cxx_toolchain_override.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/user/cxx_toolchain_override.bzl
@@ -0,0 +1,356 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:compile.bzl", "compiler_info_with_toolchain_argsfiles")
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "AsCompilerInfo",
+    "AsmCompilerInfo",
+    "BinaryUtilitiesInfo",
+    "CCompilerInfo",
+    "CxxCompilerInfo",
+    "CxxInternalTools",
+    "CxxObjectFormat",
+    "CxxPlatformInfo",
+    "CxxToolchainInfo",
+    "LinkerInfo",
+    "LinkerType",
+    "ObjcCompilerInfo",
+    "ObjcxxCompilerInfo",
+    "PicBehavior",
+    "ShlibInterfacesMode",
+    "StripFlagsInfo",
+    "cxx_toolchain_infos",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_toolchain_allow_cache_upload_args")
+load("@prelude//cxx:debug.bzl", "SplitDebugMode")
+load("@prelude//cxx:headers.bzl", "HeaderMode")
+load("@prelude//cxx:linker.bzl", "is_pdb_generated")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkStyle",
+)
+load("@prelude//linking:lto.bzl", "LtoMode")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+)
+load("@prelude//user:rule_spec.bzl", "RuleRegistrationSpec")
+load("@prelude//utils:pick.bzl", _pick = "pick", _pick_and_add = "pick_and_add", _pick_bin = "pick_bin", _pick_dep = "pick_dep", _pick_raw = "pick_raw")
+load("@prelude//utils:utils.bzl", "flatten", "map_val", "value_or")
+
+def _cxx_toolchain_override(ctx):
+    base_toolchain = ctx.attrs.base[CxxToolchainInfo]
+    base_as_info = base_toolchain.as_compiler_info
+    as_info = None
+    if base_as_info != None:
+        as_info = AsCompilerInfo(
+            compiler = _pick_bin(ctx.attrs.as_compiler, base_as_info.compiler),
+            compiler_type = base_as_info.compiler_type,
+            compiler_flags = _pick(ctx.attrs.as_compiler_flags, base_as_info.compiler_flags),
+            preprocessor = _pick_bin(ctx.attrs.as_compiler, base_as_info.preprocessor),
+            preprocessor_type = base_as_info.preprocessor_type,
+            preprocessor_flags = _pick(ctx.attrs.as_preprocessor_flags, base_as_info.preprocessor_flags),
+            supports_content_based_paths = base_as_info.supports_content_based_paths,
+        )
+    asm_info = base_toolchain.asm_compiler_info
+    if asm_info != None:
+        asm_info = AsmCompilerInfo(
+            compiler = _pick_bin(ctx.attrs.asm_compiler, asm_info.compiler),
+            compiler_type = _pick_raw(ctx.attrs.asm_compiler_type, asm_info.compiler_type),
+            compiler_flags = _pick(ctx.attrs.asm_compiler_flags, asm_info.compiler_flags),
+            preprocessor = _pick_bin(ctx.attrs.asm_compiler, asm_info.preprocessor),
+            preprocessor_type = asm_info.preprocessor_type,
+            preprocessor_flags = _pick(ctx.attrs.asm_preprocessor_flags, asm_info.preprocessor_flags),
+            supports_content_based_paths = asm_info.supports_content_based_paths,
+        )
+    base_c_info = base_toolchain.c_compiler_info
+    c_info = CCompilerInfo(
+        compiler = _pick_bin(ctx.attrs.c_compiler, base_c_info.compiler),
+        compiler_type = base_c_info.compiler_type,
+        compiler_flags = _pick_and_add(ctx.attrs.c_compiler_flags, ctx.attrs.additional_c_compiler_flags, base_c_info.compiler_flags),
+        preprocessor = _pick_bin(ctx.attrs.c_compiler, base_c_info.preprocessor),
+        preprocessor_type = base_c_info.preprocessor_type,
+        preprocessor_flags = _pick(ctx.attrs.c_preprocessor_flags, base_c_info.preprocessor_flags),
+        allow_cache_upload = _pick_raw(ctx.attrs.c_compiler_allow_cache_upload, base_c_info.allow_cache_upload),
+        supports_content_based_paths = base_c_info.supports_content_based_paths,
+    )
+    base_objc_info = base_toolchain.objc_compiler_info
+    objc_info = ObjcCompilerInfo(
+        compiler = _pick_bin(ctx.attrs.c_compiler, base_c_info.compiler),
+        compiler_type = base_c_info.compiler_type,
+        compiler_flags = _pick_and_add(ctx.attrs.c_compiler_flags, ctx.attrs.additional_c_compiler_flags, base_objc_info.compiler_flags),
+        preprocessor = _pick_bin(ctx.attrs.c_compiler, base_c_info.preprocessor),
+        preprocessor_type = base_c_info.preprocessor_type,
+        preprocessor_flags = _pick(ctx.attrs.c_preprocessor_flags, base_c_info.preprocessor_flags),
+        allow_cache_upload = _pick_raw(ctx.attrs.c_compiler_allow_cache_upload, base_c_info.allow_cache_upload),
+        supports_content_based_paths = base_c_info.supports_content_based_paths,
+    )
+    base_cxx_info = base_toolchain.cxx_compiler_info
+    cxx_info = CxxCompilerInfo(
+        compiler = _pick_bin(ctx.attrs.cxx_compiler, base_cxx_info.compiler),
+        compiler_type = base_cxx_info.compiler_type,
+        compiler_flags = _pick_and_add(ctx.attrs.cxx_compiler_flags, ctx.attrs.additional_cxx_compiler_flags, base_cxx_info.compiler_flags),
+        preprocessor = _pick_bin(ctx.attrs.cxx_compiler, base_cxx_info.preprocessor),
+        preprocessor_type = base_cxx_info.preprocessor_type,
+        preprocessor_flags = _pick(ctx.attrs.cxx_preprocessor_flags, base_cxx_info.preprocessor_flags),
+        allow_cache_upload = _pick_raw(ctx.attrs.cxx_compiler_allow_cache_upload, base_cxx_info.allow_cache_upload),
+        supports_content_based_paths = base_cxx_info.supports_content_based_paths,
+    )
+    base_objcxx_info = base_toolchain.objcxx_compiler_info
+    objcxx_info = ObjcxxCompilerInfo(
+        compiler = _pick_bin(ctx.attrs.cxx_compiler, base_cxx_info.compiler),
+        compiler_type = base_cxx_info.compiler_type,
+        compiler_flags = _pick_and_add(ctx.attrs.cxx_compiler_flags, ctx.attrs.additional_cxx_compiler_flags, base_objcxx_info.compiler_flags),
+        preprocessor = _pick_bin(ctx.attrs.cxx_compiler, base_cxx_info.preprocessor),
+        preprocessor_type = base_cxx_info.preprocessor_type,
+        preprocessor_flags = _pick(ctx.attrs.cxx_preprocessor_flags, base_cxx_info.preprocessor_flags),
+        allow_cache_upload = _pick_raw(ctx.attrs.cxx_compiler_allow_cache_upload, base_cxx_info.allow_cache_upload),
+        supports_content_based_paths = base_cxx_info.supports_content_based_paths,
+    )
+
+    # The base toolchain's argsfiles don't reflect the overridden flags, so
+    # write fresh ones for every compiler info this rule reconstructs.
+    as_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "as", AsCompilerInfo, as_info)
+    asm_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "asm", AsmCompilerInfo, asm_info)
+    c_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "c", CCompilerInfo, c_info)
+    objc_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "objc", ObjcCompilerInfo, objc_info)
+    cxx_info = compiler_info_with_toolchain_argsfiles(
+        ctx.actions,
+        "cxx",
+        CxxCompilerInfo,
+        cxx_info,
+        # Only the cxx info can be precompiled for C++20 modules.
+        precompile_filter = ctx.attrs.internal_tools[CxxInternalTools].filter_argsfile,
+    )
+    objcxx_info = compiler_info_with_toolchain_argsfiles(ctx.actions, "objcxx", ObjcxxCompilerInfo, objcxx_info)
+
+    base_linker_info = base_toolchain.linker_info
+    linker_type = LinkerType(ctx.attrs.linker_type) if ctx.attrs.linker_type != None else base_linker_info.type
+    pdb_expected = is_pdb_generated(linker_type, ctx.attrs.linker_flags) if ctx.attrs.linker_flags != None else base_linker_info.is_pdb_generated
+
+    # This handles case when linker type is overridden to non-windows from
+    # windows but linker flags are inherited.
+    # When it's changed from non-windows to windows but flags are not changed,
+    # we can't inspect base linker flags and disable PDB subtargets.
+    # This shouldn't be a problem because to use windows linker after non-windows
+    # linker flags should be changed as well.
+    pdb_expected = linker_type == LinkerType("windows") and pdb_expected
+    shlib_interfaces = ShlibInterfacesMode(ctx.attrs.shared_library_interface_mode) if ctx.attrs.shared_library_interface_mode else None
+    sanitizer_runtime_files = (
+        flatten([runtime_file[DefaultInfo].default_outputs for runtime_file in ctx.attrs.sanitizer_runtime_files])
+        if ctx.attrs.sanitizer_runtime_files != None
+        else None
+    )
+    linker_flags = _pick(ctx.attrs.linker_flags, base_linker_info.linker_flags)
+    if ctx.attrs.resource_dir != None:
+        resource_dir = ctx.attrs.resource_dir[DefaultInfo].default_outputs[0]
+        linker_flags = cmd_args(
+            linker_flags,
+            cmd_args(resource_dir, format = "-resource-dir={}"),
+        )
+    linker_info = LinkerInfo(
+        archiver = _pick_bin(ctx.attrs.archiver, base_linker_info.archiver),
+        archiver_flags = value_or(ctx.attrs.archiver_flags, base_linker_info.archiver_flags),
+        archiver_type = value_or(ctx.attrs.archiver_type, base_linker_info.archiver_type),
+        archiver_reads_inputs = value_or(ctx.attrs.archiver_reads_inputs, base_linker_info.archiver_reads_inputs),
+        archiver_supports_argfiles = value_or(ctx.attrs.archiver_supports_argfiles, base_linker_info.archiver_supports_argfiles),
+        archive_contents = value_or(ctx.attrs.archive_contents, base_linker_info.archive_contents),
+        archive_objects_locally = value_or(ctx.attrs.archive_objects_locally, base_linker_info.archive_objects_locally),
+        archive_symbol_table = value_or(ctx.attrs.archive_symbol_table, base_linker_info.archive_symbol_table),
+        binary_extension = base_linker_info.binary_extension,
+        binary_linker_flags = base_linker_info.binary_linker_flags,
+        dist_thin_lto_codegen_flags = base_linker_info.dist_thin_lto_codegen_flags,
+        executable_linker_flags = base_linker_info.executable_linker_flags,
+        extra_outputs = base_linker_info.extra_outputs,
+        generate_linker_maps = value_or(ctx.attrs.generate_linker_maps, base_linker_info.generate_linker_maps),
+        generate_gc_sections = value_or(ctx.attrs.generate_gc_sections, base_linker_info.generate_gc_sections),
+        link_binaries_locally = value_or(ctx.attrs.link_binaries_locally, base_linker_info.link_binaries_locally),
+        link_libraries_locally = value_or(ctx.attrs.link_libraries_locally, base_linker_info.link_libraries_locally),
+        link_style = LinkStyle(ctx.attrs.link_style) if ctx.attrs.link_style != None else base_linker_info.link_style,
+        link_weight = value_or(ctx.attrs.link_weight, base_linker_info.link_weight),
+        link_ordering = base_linker_info.link_ordering,
+        linker = _pick_bin(ctx.attrs.linker, base_linker_info.linker),
+        linker_flags = linker_flags,
+        post_linker_flags = _pick(ctx.attrs.post_linker_flags, base_linker_info.post_linker_flags),
+        link_metadata_flag = _pick(ctx.attrs.link_metadata_flag, base_linker_info.link_metadata_flag),
+        lto_mode = value_or(map_val(LtoMode, ctx.attrs.lto_mode), base_linker_info.lto_mode),
+        object_file_extension = base_linker_info.object_file_extension,
+        shlib_interfaces = value_or(shlib_interfaces, base_linker_info.shlib_interfaces),
+        mk_shlib_intf = _pick_dep(ctx.attrs.mk_shlib_intf, base_linker_info.mk_shlib_intf),
+        requires_archives = base_linker_info.requires_archives,
+        requires_objects = base_linker_info.requires_objects,
+        runtime_library_files = base_linker_info.runtime_library_files,
+        supports_distributed_thinlto = base_linker_info.supports_distributed_thinlto,
+        independent_shlib_interface_linker_flags = base_linker_info.independent_shlib_interface_linker_flags,
+        sanitizer_runtime_enabled = value_or(ctx.attrs.sanitizer_runtime_enabled, base_linker_info.sanitizer_runtime_enabled),
+        sanitizer_runtime_files = value_or(sanitizer_runtime_files, base_linker_info.sanitizer_runtime_files),
+        shared_dep_runtime_ld_flags = base_linker_info.shared_dep_runtime_ld_flags,
+        shared_library_name_default_prefix = ctx.attrs.shared_library_name_default_prefix
+        if ctx.attrs.shared_library_name_default_prefix != None
+        else base_linker_info.shared_library_name_default_prefix,
+        shared_library_name_format = ctx.attrs.shared_library_name_format
+        if ctx.attrs.shared_library_name_format != None
+        else base_linker_info.shared_library_name_format,
+        shared_library_versioned_name_format = ctx.attrs.shared_library_versioned_name_format
+        if ctx.attrs.shared_library_versioned_name_format != None
+        else base_linker_info.shared_library_versioned_name_format,
+        static_dep_runtime_ld_flags = base_linker_info.static_dep_runtime_ld_flags,
+        static_pic_dep_runtime_ld_flags = base_linker_info.static_pic_dep_runtime_ld_flags,
+        static_library_extension = base_linker_info.static_library_extension,
+        type = linker_type,
+        use_archiver_flags = value_or(ctx.attrs.use_archiver_flags, base_linker_info.use_archiver_flags),
+        force_full_hybrid_if_capable = value_or(ctx.attrs.force_full_hybrid_if_capable, base_linker_info.force_full_hybrid_if_capable),
+        is_pdb_generated = pdb_expected,
+        push_pop_state_flags = base_linker_info.push_pop_state_flags,
+        supports_content_based_paths_for_archiving = base_linker_info.supports_content_based_paths_for_archiving,
+        supports_shared_libraries = base_linker_info.supports_shared_libraries,
+        thin_lto_premerger_enabled = base_linker_info.thin_lto_premerger_enabled,
+        thin_lto_double_codegen_enabled = base_linker_info.thin_lto_double_codegen_enabled,
+    )
+
+    base_binary_utilities_info = base_toolchain.binary_utilities_info
+    binary_utilities_info = BinaryUtilitiesInfo(
+        bolt = _pick_bin(ctx.attrs.bolt, base_binary_utilities_info.bolt),
+        elf_stamp = _pick_bin(ctx.attrs.elf_stamp, base_binary_utilities_info.elf_stamp),
+        nm = _pick_bin(ctx.attrs.nm, base_binary_utilities_info.nm),
+        objcopy = _pick_bin(ctx.attrs.objcopy, base_binary_utilities_info.objcopy),
+        objdump = _pick_bin(ctx.attrs.objdump, base_binary_utilities_info.objdump),
+        ranlib = _pick_bin(ctx.attrs.ranlib, base_binary_utilities_info.ranlib),
+        strip = _pick_bin(ctx.attrs.strip, base_binary_utilities_info.strip),
+        dwp = _pick_bin(ctx.attrs.dwp, base_binary_utilities_info.dwp),
+    )
+
+    base_strip_flags_info = base_toolchain.strip_flags_info
+    if base_strip_flags_info:
+        strip_flags_info = StripFlagsInfo(
+            strip_debug_flags = _pick(ctx.attrs.strip_debug_flags, base_strip_flags_info.strip_debug_flags),
+            strip_non_global_flags = _pick(ctx.attrs.strip_non_global_flags, base_strip_flags_info.strip_non_global_flags),
+            strip_all_flags = _pick(ctx.attrs.strip_all_flags, base_strip_flags_info.strip_all_flags),
+        )
+    else:
+        strip_flags_info = None
+
+    return [
+        DefaultInfo(),
+    ] + cxx_toolchain_infos(
+        internal_tools = ctx.attrs.internal_tools[CxxInternalTools],
+        platform_name = ctx.attrs.platform_name if ctx.attrs.platform_name != None else ctx.attrs.base[CxxPlatformInfo].name,
+        platform_deps_aliases = ctx.attrs.platform_deps_aliases if ctx.attrs.platform_deps_aliases != None else [],
+        linker_info = linker_info,
+        as_compiler_info = as_info,
+        asm_compiler_info = asm_info,
+        binary_utilities_info = binary_utilities_info,
+        bolt_enabled = value_or(ctx.attrs.bolt_enabled, base_toolchain.bolt_enabled),
+        c_compiler_info = c_info,
+        cxx_compiler_info = cxx_info,
+        objc_compiler_info = objc_info,
+        objcxx_compiler_info = objcxx_info,
+        libclang = value_or(ctx.attrs.libclang, base_toolchain.libclang),
+        llvm_link = ctx.attrs.llvm_link[RunInfo] if ctx.attrs.llvm_link != None else base_toolchain.llvm_link,
+        # the rest are used without overrides
+        target_stats_tools = base_toolchain.target_stats_tools,
+        cuda_compiler_info = base_toolchain.cuda_compiler_info,
+        hip_compiler_info = base_toolchain.hip_compiler_info,
+        hip_debug_extract = base_toolchain.hip_debug_extract,
+        hip_device_debug_extract = base_toolchain.hip_device_debug_extract,
+        hip_gpu_archs = base_toolchain.hip_gpu_archs,
+        header_mode = HeaderMode(ctx.attrs.header_mode) if ctx.attrs.header_mode != None else base_toolchain.header_mode,
+        headers_as_raw_headers_mode = base_toolchain.headers_as_raw_headers_mode,
+        use_dep_files = base_toolchain.use_dep_files,
+        clang_remarks = base_toolchain.clang_remarks,
+        clang_llvm_statistics = base_toolchain.clang_llvm_statistics,
+        gcno_files = base_toolchain.gcno_files,
+        clang_trace = base_toolchain.clang_trace,
+        object_format = CxxObjectFormat(ctx.attrs.object_format) if ctx.attrs.object_format != None else base_toolchain.object_format,
+        strip_flags_info = strip_flags_info,
+        pic_behavior = PicBehavior(ctx.attrs.pic_behavior) if ctx.attrs.pic_behavior != None else base_toolchain.pic_behavior.value,
+        materialize_external_debug_info = base_toolchain.materialize_external_debug_info,
+        split_debug_mode = SplitDebugMode(value_or(ctx.attrs.split_debug_mode, base_toolchain.split_debug_mode.value)),
+        minimum_os_version = value_or(ctx.attrs.minimum_os_version, base_toolchain.minimum_os_version),
+    )
+
+cxx_toolchain_override_registration_spec = RuleRegistrationSpec(
+    name = "cxx_toolchain_override",
+    impl = _cxx_toolchain_override,
+    attrs = {
+        "additional_c_compiler_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "additional_cxx_compiler_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "archive_contents": attrs.option(attrs.string(), default = None),
+        "archive_objects_locally": attrs.option(attrs.bool(), default = None),
+        "archive_symbol_table": attrs.option(attrs.bool(), default = None),
+        "archiver": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "archiver_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "archiver_reads_inputs": attrs.option(attrs.bool(), default = None),
+        "archiver_supports_argfiles": attrs.option(attrs.bool(), default = None),
+        "archiver_type": attrs.option(attrs.string(), default = None),
+        "as_compiler": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "as_compiler_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "as_preprocessor_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "asm_compiler": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "asm_compiler_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "asm_compiler_type": attrs.option(attrs.string(), default = None),
+        "asm_preprocessor_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "base": attrs.toolchain_dep(providers = [CxxToolchainInfo]),
+        "bolt": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "bolt_enabled": attrs.option(attrs.bool(), default = None),
+        "c_compiler": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "c_compiler_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "c_preprocessor_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "cxx_compiler": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "cxx_compiler_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "cxx_preprocessor_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "dwp": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "elf_stamp": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "force_full_hybrid_if_capable": attrs.option(attrs.bool(), default = None),
+        "generate_gc_sections": attrs.option(attrs.bool(), default = None),
+        "generate_linker_maps": attrs.option(attrs.bool(), default = None),
+        "header_mode": attrs.option(attrs.enum(HeaderMode.values()), default = None),
+        "internal_tools": attrs.exec_dep(providers = [CxxInternalTools], default = "prelude//cxx/tools:internal_tools"),
+        "libclang": attrs.option(attrs.exec_dep(providers = [SharedLibraryInfo]), default = None),
+        "link_binaries_locally": attrs.option(attrs.bool(), default = None),
+        "link_libraries_locally": attrs.option(attrs.bool(), default = None),
+        "link_metadata_flag": attrs.option(attrs.string(), default = None),
+        "link_style": attrs.option(attrs.enum(LinkStyle.values()), default = None),
+        "link_weight": attrs.option(attrs.int(), default = None),
+        "linker": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "linker_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "linker_type": attrs.option(attrs.enum(LinkerType.values()), default = None),
+        "lipo": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "llvm_link": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "lto_mode": attrs.option(attrs.enum(LtoMode.values()), default = None),
+        "minimum_os_version": attrs.option(attrs.string(), default = None),
+        "mk_shlib_intf": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "nm": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "objcopy": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "objdump": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "object_format": attrs.enum(CxxObjectFormat.values(), default = "native"),
+        "pic_behavior": attrs.enum(PicBehavior.values(), default = "supported"),
+        "platform_deps_aliases": attrs.option(attrs.list(attrs.string()), default = None),
+        "platform_name": attrs.option(attrs.string(), default = None),
+        "post_linker_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "ranlib": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "resource_dir": attrs.option(attrs.dep(), default = None),
+        "sanitizer_runtime_enabled": attrs.bool(default = False),
+        "sanitizer_runtime_files": attrs.option(
+            attrs.set(attrs.dep(), sorted = True, default = []), default = None
+        ),  # Use `attrs.dep()` as it's not a tool, always propagate target platform
+        "shared_library_interface_mode": attrs.option(attrs.enum(ShlibInterfacesMode.values()), default = None),
+        "shared_library_name_default_prefix": attrs.option(attrs.string(), default = None),
+        "shared_library_name_format": attrs.option(attrs.string(), default = None),
+        "shared_library_versioned_name_format": attrs.option(attrs.string(), default = None),
+        "split_debug_mode": attrs.option(attrs.enum(SplitDebugMode.values()), default = None),
+        "strip": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "strip_all_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "strip_debug_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "strip_non_global_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "use_archiver_flags": attrs.option(attrs.bool(), default = None),
+    }
+    | cxx_toolchain_allow_cache_upload_args(),
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/cxx/user/link_group_map.bzl b/buck2/prelude/cxx/user/link_group_map.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/user/link_group_map.bzl
@@ -0,0 +1,78 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//cxx:groups.bzl",
+    "get_roots_from_mapping",
+    "make_info_subtarget_providers",
+    "parse_groups_definitions",
+)
+load(
+    "@prelude//cxx:link_groups.bzl",
+    "build_link_group_info",
+)
+load(
+    "@prelude//cxx:link_groups_types.bzl",
+    "link_group_inlined_map_attr",
+)
+load(
+    "@prelude//linking:link_groups.bzl",
+    "LinkGroupLibInfo",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "MergedLinkInfo",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",
+    "create_linkable_graph",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+)
+load("@prelude//user:rule_spec.bzl", "RuleRegistrationSpec")
+load("@prelude//utils:utils.bzl", "flatten")
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    # Extract graphs from the roots via the raw attrs, as `parse_groups_definitions`
+    # parses them as labels.
+
+    deps = flatten([get_roots_from_mapping(mapping) for entry in ctx.attrs.map for mapping in entry[1]])
+    linkable_graph = create_linkable_graph(
+        ctx,
+        deps = [dep[LinkableGraph] for dep in deps],
+    )
+    link_groups = parse_groups_definitions(ctx.attrs.map, lambda root: root.label)
+    link_group_info = build_link_group_info(linkable_graph, link_groups)
+    return [
+        DefaultInfo(
+            sub_targets = {
+                "info": make_info_subtarget_providers(ctx, link_group_info.groups.values(), link_group_info.mappings),
+            }
+        ),
+        link_group_info,
+    ]
+
+registration_spec = RuleRegistrationSpec(
+    name = "link_group_map",
+    impl = _impl,
+    attrs = {
+        "map": link_group_inlined_map_attr(
+            root_attr = attrs.dep(
+                providers = [
+                    LinkGroupLibInfo,
+                    LinkableGraph,
+                    MergedLinkInfo,
+                    SharedLibraryInfo,
+                ],
+            ),
+        ),
+    },
+)
diff --git a/buck2/prelude/cxx/windows_resource.bzl b/buck2/prelude/cxx/windows_resource.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/windows_resource.bzl
@@ -0,0 +1,105 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//cxx:cxx_library_utility.bzl", "cxx_attr_deps")
+load("@prelude//cxx:headers.bzl", "cxx_get_regular_cxx_headers_layout")
+load("@prelude//cxx:preprocessor.bzl", "cxx_inherited_preprocessor_infos", "cxx_merge_cpreprocessors", "cxx_private_preprocessor_info")
+load("@prelude//linking:link_groups.bzl", "EMPTY_LINK_GROUP_LIB_INFO")
+load("@prelude//linking:link_info.bzl", "LibOutputStyle", "LinkInfo", "LinkInfos", "ObjectsLinkable", "create_merged_link_info")
+load("@prelude//linking:linkable_graph.bzl", "create_linkable_graph")
+load("@prelude//linking:shared_libraries.bzl", "EMPTY_SHARED_LIBRARY_INFO")
+
+def windows_resource_impl(ctx: AnalysisContext) -> list[Provider]:
+    non_exported_deps = cxx_attr_deps(ctx)
+
+    (own_non_exported_preprocessor_info, _) = cxx_private_preprocessor_info(
+        ctx = ctx,
+        headers_layout = cxx_get_regular_cxx_headers_layout(ctx),
+        raw_headers = ctx.attrs.raw_headers,
+        extra_preprocessors = [],
+        non_exported_deps = non_exported_deps,
+        is_test = False,
+    )
+
+    inherited_non_exported_preprocessor_infos = cxx_inherited_preprocessor_infos(non_exported_deps)
+
+    preprocessor = cxx_merge_cpreprocessors(
+        ctx.actions,
+        [own_non_exported_preprocessor_info],
+        inherited_non_exported_preprocessor_infos,
+    )
+
+    headers_tag = ctx.actions.artifact_tag()
+
+    objects = []
+
+    toolchain = get_cxx_toolchain_info(ctx)
+    for src in ctx.attrs.srcs:
+        rc_output = ctx.actions.declare_output(
+            "__objects__",
+            "{}.res".format(src.short_path),
+            has_content_based_path = False,
+        )
+        rc_cmd = cmd_args(
+            toolchain.rc_compiler_info.compiler,
+            toolchain.rc_compiler_info.compiler_flags,
+            cmd_args(rc_output.as_output(), format = "/fo{}"),
+            headers_tag.tag_artifacts(preprocessor.set.project_as_args("args")),
+            headers_tag.tag_artifacts(preprocessor.set.project_as_args("include_dirs")),
+            src,
+        )
+
+        ctx.actions.run(
+            rc_cmd,
+            category = "rc_compile",
+        )
+
+        cvtres_output = ctx.actions.declare_output(
+            "__objects__",
+            "{}.obj".format(src.short_path),
+            has_content_based_path = False,
+        )
+        cvtres_cmd = cmd_args(
+            toolchain.cvtres_compiler_info.compiler,
+            toolchain.cvtres_compiler_info.compiler_flags,
+            cmd_args(cvtres_output.as_output(), format = "/OUT:{}"),
+            rc_output,
+        )
+
+        ctx.actions.run(
+            cvtres_cmd,
+            category = "cvtres_compile",
+        )
+
+        objects.append(cvtres_output)
+
+    link = LinkInfo(
+        name = ctx.attrs.name,
+        linkables = [
+            ObjectsLinkable(
+                objects = objects,
+                linker_type = toolchain.linker_info.type,
+                link_whole = True,
+            )
+        ],
+    )
+
+    providers = [
+        DefaultInfo(default_output = None),
+        EMPTY_SHARED_LIBRARY_INFO,
+        EMPTY_LINK_GROUP_LIB_INFO,
+        create_linkable_graph(ctx),
+        create_merged_link_info(
+            ctx,
+            toolchain.pic_behavior,
+            {output_style: LinkInfos(default = link) for output_style in LibOutputStyle},
+        ),
+    ]
+
+    return providers
diff --git a/buck2/prelude/cxx/xcode.bzl b/buck2/prelude/cxx/xcode.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/cxx/xcode.bzl
@@ -0,0 +1,54 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//cxx:argsfiles.bzl",
+    "CompileArgsfile",  # @unused Used as a type
+)
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",  # @unused Used as a type
+)
+load("@prelude//ide_integrations/xcode:data.bzl", "XcodeDataInfoKeys")
+
+def cxx_populate_xcode_attributes(ctx, srcs: list[CxxSrcWithFlags], argsfiles: dict[str, CompileArgsfile], product_name: str) -> dict[str, typing.Any]:
+    converted_srcs = {}
+    for src in srcs:
+        file_properties = _get_artifact_owner(src.file)
+        if src.flags:
+            # List of resolved_macros will encode as:
+            # [['\"-some-flag\"'], ['\"-another-flag\"']]
+            #
+            # Convert it to a string and rip-out the quotes
+            # so it appears as ["-some-flag", "-another-flag"]
+            file_properties["flags"] = [str(flag).replace('"', "") for flag in src.flags]
+        converted_srcs[src.file] = file_properties
+
+    data = {
+        XcodeDataInfoKeys.ARGSFILES_BY_EXT: {ext: argsfile.file for ext, argsfile in argsfiles.items()},
+        XcodeDataInfoKeys.HEADERS: _get_artifacts_with_owners(ctx.attrs.headers),
+        XcodeDataInfoKeys.PRODUCT_NAME: product_name,
+        XcodeDataInfoKeys.SRCS: converted_srcs,
+    }
+
+    if hasattr(ctx.attrs, "exported_headers"):
+        data[XcodeDataInfoKeys.EXPORTED_HEADERS] = _get_artifacts_with_owners(ctx.attrs.exported_headers)
+
+    return data
+
+def _get_artifacts_with_owners(files: typing.Any) -> dict[Artifact, dict[str, Label]]:
+    if type(files) == "dict":
+        return {artifact: _get_artifact_owner(artifact) for _, artifact in files.items()}
+    else:
+        return {file: _get_artifact_owner(file) for file in files}
+
+def _get_artifact_owner(file: Artifact) -> dict[str, Label]:
+    if file.owner:
+        return {"target": file.owner}
+    else:
+        return {}
diff --git a/buck2/prelude/debugging/common.bzl b/buck2/prelude/debugging/common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/debugging/common.bzl
@@ -0,0 +1,25 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Utility functions used by "fdb.bxl"
+
+load("@prelude//debugging:types.bzl", "TargetInfo")
+
+def target_name(node: bxl.ConfiguredTargetNode | bxl.UnconfiguredTargetNode) -> str:
+    return "{}:{}".format(str(node.label.path), node.label.name)
+
+def rule_type(node: bxl.ConfiguredTargetNode) -> str:
+    return node.rule_type
+
+def create_target_info(target: bxl.ConfiguredTargetNode) -> TargetInfo:
+    attrs = target.attrs_lazy()
+    return TargetInfo(
+        target = target_name(target),
+        target_type = rule_type(target).removeprefix("prelude//rules.bzl:"),
+        labels = attrs.get("labels").value() if attrs.get("labels") != None else [],
+    )
diff --git a/buck2/prelude/debugging/configure_env.bzl b/buck2/prelude/debugging/configure_env.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/debugging/configure_env.bzl
@@ -0,0 +1,43 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//debugging:labels.bzl", "DBG_INFO_DISABLE_INCOMPATIBLE_SANITIZERS")
+load("@prelude//debugging:types.bzl", "UserMessage")
+
+ConfiguredEnv = record(
+    env = field(dict[str, str]),
+    messages = field(list[UserMessage]),
+)
+
+_DISABLE_LEAK_DETECTION = "detect_leaks=0"
+_ASAN_OPTIONS = "ASAN_OPTIONS"
+
+def configure_env(env: dict[str, str], labels: list[str]) -> ConfiguredEnv:
+    messages = []
+    altered_env = {}
+    if DBG_INFO_DISABLE_INCOMPATIBLE_SANITIZERS in labels:
+        messages.append(
+            UserMessage(
+                title = "Leak sanitizer is disabled.",
+                body = "You are trying to debug a binary with sanitizers. Certain sanitizers do not work under the debugger.\n",
+            ),
+        )
+        altered_env[_ASAN_OPTIONS] = _inject_env(env, _ASAN_OPTIONS, _DISABLE_LEAK_DETECTION, lambda x: x + "," + _DISABLE_LEAK_DETECTION)
+
+    # We should only return env fields that we altering here. The primary reason for this is unability
+    # to expand buck macroses (e.g. $(exe //some:target)) in the env field inside bxl. So we delegate that
+    # responsibility to `tpx` that gives us unwrapped and untouched env and then `fdb` merges these two,
+    # preferring results from this bxl. That keeps macro expansion working correctly.
+    return ConfiguredEnv(env = altered_env, messages = messages)
+
+def _inject_env(env: dict[str, str], key: str, value: str, merge: typing.Callable[[str], str]) -> str:
+    existing_env = env.get(key)
+    if existing_env:
+        return merge(existing_env)
+    else:
+        return value
diff --git a/buck2/prelude/debugging/ensure_dwp.bzl b/buck2/prelude/debugging/ensure_dwp.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/debugging/ensure_dwp.bzl
@@ -0,0 +1,39 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//debugging:labels.bzl", "DBG_INFO_PYTHON_REQUIRES_SECONDARY_NATIVE_DEBUGINFO")
+
+def _ensure_default_info(ctx: bxl.Context, default_info: DefaultInfo) -> None:
+    ctx.output.ensure_multiple(cmd_args(default_info.default_outputs, hidden = default_info.other_outputs))
+
+# This function ensures that certain subtargets are materialized if they exist. This is used by fdb.
+def ensure_subtargets(ctx: bxl.Context, target: bxl.ConfiguredTargetNode):
+    providers = ctx.analysis(target).providers()
+    subtargets = providers[DefaultInfo].sub_targets
+    labels = target.get_attr("labels") if target.get_attr("labels") else []
+
+    # split dwarf targets have ["dwp"] subtargets. this function ensures that all dwp files are materialized
+    if "dwp" in subtargets:
+        _ensure_default_info(ctx, subtargets["dwp"][DefaultInfo])
+
+    # Build modes whose toolchain sets `materialize_external_debug_info = False`
+    # don't materialize unpacked split-dwarf debug info (.dwo) on regular
+    # builds; materialize it here so debugging works without relying on dwp.
+    if "debuginfo" in subtargets:
+        _ensure_default_info(ctx, subtargets["debuginfo"][DefaultInfo])
+
+    if (
+        DBG_INFO_PYTHON_REQUIRES_SECONDARY_NATIVE_DEBUGINFO in labels
+        and "native-executable" in subtargets
+        and "dwp" in subtargets["native-executable"][DefaultInfo].sub_targets
+    ):
+        _ensure_default_info(ctx, subtargets["native-executable"][DefaultInfo].sub_targets["dwp"][DefaultInfo])
+
+    # ios test targets need to materialize "dwarf-and-dsym" subtarget in order for debugging to work properly.
+    if "dwarf-and-dsym" in subtargets:
+        _ensure_default_info(ctx, subtargets["dwarf-and-dsym"][DefaultInfo])
diff --git a/buck2/prelude/debugging/fdb.bxl b/buck2/prelude/debugging/fdb.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/debugging/fdb.bxl
@@ -0,0 +1,121 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Bxl script in this file is addressing the problem of retrieving additional information
+# from language rule providers in order to correctly setup debugging tools
+# Typical use case is:
+#   - a user wants to debug "buck run `//some:target`" or "buck test //some:test"
+#   - depending on the language and/or platform used //some:target could be a macros wrapping a rule provider
+#   - actual language rule might have relevant information / artifacts in order to make debugging possible.
+# So this script provides various hooks to let debugging tool
+#   1) traverse targets and rules based on  //some:target
+#   2) inspect rule providers and extract information required for seamless debugging setup
+# Example:
+# buck2 bxl prelude//debugging/fdb.bxl:inspect_target -- --target=//some:target
+# This outputs file containing JSON serialized `ExecInfo` (see types.bzl)
+
+load("@prelude//debugging:common.bzl", "rule_type")
+load("@prelude//debugging:inspect_dbg_exec.bzl", "inspect_dbg_exec")
+load("@prelude//debugging:inspect_default.bzl", "inspect_default")
+load("@prelude//debugging:inspect_java.bzl", "inspect_java_rule")
+load("@prelude//debugging:labels.bzl", "DBG_INFO_EXEC", "DBG_INFO_REF", "get_info_ref", "get_label_or_mark")
+load("@prelude//debugging:types.bzl", "ScriptSettings")
+
+def inspect_alias_rule(ctx: bxl.Context, actions: AnalysisActions, target: bxl.ConfiguredTargetNode, settings: ScriptSettings):
+    attrs = target.attrs_lazy()
+    actual = attrs.get("actual")
+    actual_target_label = ctx.configured_targets(actual.value().configured_target(), modifiers = ctx.modifiers)
+    return inspect_any_target(ctx, actions, actual_target_label, settings)
+
+INSPECT_BY_RULE = {
+    "prelude//rules.bzl:alias": inspect_alias_rule,
+    "prelude//rules.bzl:android_binary": inspect_java_rule,
+    "prelude//rules.bzl:android_instrumentation_apk": inspect_java_rule,
+    "prelude//rules.bzl:android_instrumentation_test": inspect_java_rule,
+    "prelude//rules.bzl:android_library": inspect_java_rule,
+    "prelude//rules.bzl:apk_genrule": inspect_java_rule,
+    "prelude//rules.bzl:configured_alias": inspect_alias_rule,
+    "prelude//rules.bzl:java_binary": inspect_java_rule,
+    "prelude//rules.bzl:java_library": inspect_java_rule,
+    "prelude//rules.bzl:java_test": inspect_java_rule,
+    "prelude//rules.bzl:kotlin_binary": inspect_java_rule,
+    "prelude//rules.bzl:kotlin_library": inspect_java_rule,
+    "prelude//rules.bzl:kotlin_test": inspect_java_rule,
+    "prelude//rules.bzl:robolectric_test": inspect_java_rule,
+}
+
+def inspect_info_ref_rule(ctx: bxl.Context, actions: AnalysisActions, target: bxl.ConfiguredTargetNode, settings: ScriptSettings):
+    aliased_target_label = get_info_ref(target.attrs_lazy().get("labels").value())
+    if not aliased_target_label:
+        return inspect_default(
+            ctx,
+            actions,
+            target,
+            settings,
+        )
+
+    aliases_target = ctx.configured_targets(aliased_target_label, modifiers = ctx.modifiers)
+    return inspect_any_target(
+        ctx,
+        actions,
+        aliases_target,
+        settings,
+    )
+
+INSPECT_BY_LABEL = {
+    DBG_INFO_REF: inspect_info_ref_rule,
+    DBG_INFO_EXEC: inspect_dbg_exec,
+}
+
+def inspect_any_target(ctx: bxl.Context, actions: AnalysisActions, target: bxl.ConfiguredTargetNode, settings: ScriptSettings):
+    attrs = target.attrs_lazy()
+    labels = attrs.get("labels").value() if attrs.get("labels") else []
+    inspect_func = INSPECT_BY_RULE.get(rule_type(target), inspect_default)
+    for label in labels:
+        inspect_func = INSPECT_BY_LABEL.get(get_label_or_mark(label), inspect_func)
+
+    return inspect_func(ctx, actions, target, settings)
+
+def inspect(ctx: bxl.Context, actions: AnalysisActions, target: bxl.ConfiguredTargetNode, settings: ScriptSettings):
+    result = inspect_any_target(ctx, actions, target, settings)
+
+    # when getting ExecInfo based on external action it's not possible to provide result as ExecInfo
+    # in this case we'll return the artifact which is assumed to have ExecInfo serialized in it
+    if isinstance(result, Artifact):
+        return result
+    return actions.write_json("out.json", result, has_content_based_path = False)
+
+def inspect_target_impl(ctx: bxl.Context):
+    actions = ctx.bxl_actions().actions
+    node = ctx.configured_targets(ctx.cli_args.target, modifiers = ctx.modifiers)
+
+    # Follow transitions such as opt-by-default so that we actually read the
+    # correct configuration.
+    node = node.unwrap_forward()
+
+    ctx.output.print(
+        ctx.output.ensure(
+            inspect(
+                ctx,
+                actions,
+                node,
+                ScriptSettings(
+                    target = node,
+                    args = ctx.cli_args.args if ctx.cli_args.args else [],
+                ),
+            )
+        ).abs_path()
+    )
+
+inspect_target = bxl_main(
+    impl = inspect_target_impl,
+    cli_args = {
+        "args": cli_args.option(cli_args.list(cli_args.string())),
+        "target": cli_args.target_label(),
+    },
+)
diff --git a/buck2/prelude/debugging/inspect_dbg_exec.bzl b/buck2/prelude/debugging/inspect_dbg_exec.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/debugging/inspect_dbg_exec.bzl
@@ -0,0 +1,56 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//debugging:common.bzl", "create_target_info", "target_name")
+load("@prelude//debugging:types.bzl", "JavaInfo", "ScriptSettings")
+load("@prelude//java:class_to_srcs.bzl", "JavaClassToSourceMapInfo")
+
+def inspect_dbg_exec(ctx: bxl.Context, actions: AnalysisActions, target: bxl.ConfiguredTargetNode, settings: ScriptSettings):
+    pointer_name = target_name(target)
+    if not pointer_name.endswith("_fdb"):
+        pointer_name = "{}_fdb".format(pointer_name)
+
+    fbsource_alias_target = ctx.configured_targets(pointer_name)
+    providers = ctx.analysis(fbsource_alias_target).providers()
+    fdb_helper = providers[RunInfo]
+    fdb_helper_out = actions.declare_output("fdb_helper.json", has_content_based_path = False)
+    cmd = cmd_args(fdb_helper, settings.args)
+    actions.run(cmd, category = "fdb_helper", env = {"FDB_OUTPUT_FILE": fdb_helper_out.as_output()}, local_only = True)
+    result = actions.declare_output("final_out.json", has_content_based_path = False)
+
+    original_target_providers = ctx.analysis(settings.target).providers()
+    java_debuginfo = original_target_providers[JavaClassToSourceMapInfo].debuginfo if JavaClassToSourceMapInfo in original_target_providers else None
+    if java_debuginfo:
+        ctx.output.ensure(java_debuginfo)
+
+    def build_exec_info(ctx, artifacts, outputs):
+        # TODO: make this more independent
+        # java is only supported via [JavaClassToSourceMapInfo] provider
+        exec_info = artifacts[fdb_helper_out].read_json()
+        exec_info["java"] = JavaInfo(
+            classmap_file = java_debuginfo,
+        )
+
+        # read_json can't create a record of type ExecInfo
+        # can alternativelly create ExecInfo by enumerating every single primitive nested field in there
+        ctx.bxl_actions().actions.write_json(
+            outputs[result],
+            {
+                "data": exec_info,
+                "target_info": create_target_info(settings.target),
+                "target_name": target_name(settings.target),
+            },
+        )
+
+    actions.dynamic_output(
+        dynamic = [fdb_helper_out],
+        inputs = [],
+        outputs = [result.as_output()],
+        f = build_exec_info,
+    )
+    return result
diff --git a/buck2/prelude/debugging/inspect_default.bzl b/buck2/prelude/debugging/inspect_default.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/debugging/inspect_default.bzl
@@ -0,0 +1,32 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//debugging:common.bzl", "create_target_info", "target_name")
+load("@prelude//debugging:configure_env.bzl", "configure_env")
+load("@prelude//debugging:ensure_dwp.bzl", "ensure_subtargets")
+load("@prelude//debugging:types.bzl", "ExecInfo", "ScriptSettings", "TargetExtraInfo")
+
+# "inspect_default" is reused across "fdb.bxl" to provide a fallback default information
+# in case special handling for the rule type isn't implemented yet
+def inspect_default(ctx: bxl.Context, _actions: AnalysisActions, target: bxl.ConfiguredTargetNode, settings: ScriptSettings) -> ExecInfo:
+    ensure_subtargets(ctx, target)
+    attrs = target.attrs_lazy()
+    labels = attrs.get("labels").value() if attrs.get("labels") else []
+    env = attrs.get("env").value() if attrs.get("env") else {}
+    configured_env = configure_env(env, labels)
+
+    return ExecInfo(
+        target_name = target_name(settings.target),
+        target_info = create_target_info(settings.target),
+        data = TargetExtraInfo(
+            exec_info_version = 1,
+            debugger = "fdb:debugger:default",
+            env = configured_env.env,
+        ),
+        messages = configured_env.messages,
+    )
diff --git a/buck2/prelude/debugging/inspect_java.bzl b/buck2/prelude/debugging/inspect_java.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/debugging/inspect_java.bzl
@@ -0,0 +1,39 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//debugging:common.bzl", "create_target_info", "target_name")
+load("@prelude//debugging:types.bzl", "ExecInfo", "JavaInfo", "ScriptSettings", "TargetExtraInfo")
+load("@prelude//java:class_to_srcs.bzl", "JavaClassToSourceMapInfo")
+
+def inspect_java_rule(ctx: bxl.Context, _actions: AnalysisActions, target: bxl.ConfiguredTargetNode, settings: ScriptSettings) -> ExecInfo:
+    providers = ctx.analysis(target).providers()
+    debuginfo = providers[JavaClassToSourceMapInfo].debuginfo if JavaClassToSourceMapInfo in providers else None
+    if debuginfo:
+        ctx.output.ensure(debuginfo)
+
+    program = None
+    env = {}
+    if ExternalRunnerTestInfo in providers:
+        env = providers[ExternalRunnerTestInfo].env
+        program = cmd_args(providers[ExternalRunnerTestInfo].command)
+
+        ctx.output.ensure_multiple(program)
+
+    return ExecInfo(
+        target_name = target_name(settings.target),
+        target_info = create_target_info(settings.target),
+        data = TargetExtraInfo(
+            exec_info_version = 1,
+            debugger = "fdb:debugger:jdwp",
+            java = JavaInfo(
+                classmap_file = debuginfo,
+            ),
+            env = env,
+            program = program,
+        ),
+    )
diff --git a/buck2/prelude/debugging/java/get_jdb_classmap.bxl b/buck2/prelude/debugging/java/get_jdb_classmap.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/debugging/java/get_jdb_classmap.bxl
@@ -0,0 +1,47 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# BXL script to extract the Java class-to-source map debug info from a target
+# Usage:
+# buck2 bxl @//arvr/mode/android/apk/vr_standalone/linux/dev prelude//debugging/java/get_jdb_classmap.bxl:get_jdb_classmap -- --target=<your target here>
+# This script extracts Java class-to-source mapping information from a buck target and outputs the path to a debuginfo JSON file
+# that can be used by Java debuggers (like java-dap) to map compiled classes back to their source files for debugging purposes.
+
+load("@prelude//java:class_to_srcs.bzl", "JavaClassToSourceMapInfo")
+
+def get_jdb_classmap_impl(ctx: bxl.Context):
+    # Get the target from the command line arguments
+    target = ctx.configured_targets(ctx.cli_args.target, modifiers = ctx.modifiers)
+
+    # Analyze the target to get its providers
+    providers = ctx.analysis(target).providers()
+
+    # Check if the target has the JavaClassToSourceMapInfo provider
+    if JavaClassToSourceMapInfo not in providers:
+        ctx.output.print("Error: Target does not have JavaClassToSourceMapInfo provider")
+        return
+
+    # Get the debuginfo from the provider
+    debuginfo = providers[JavaClassToSourceMapInfo].debuginfo
+
+    if not debuginfo:
+        ctx.output.print("Error: No debuginfo available for this target")
+        return
+
+    # Ensure the debuginfo file is materialized and get its path
+    debuginfo_path = ctx.output.ensure(debuginfo)
+
+    # Print the path to the debuginfo file
+    ctx.output.print(debuginfo_path)
+
+get_jdb_classmap = bxl_main(
+    impl = get_jdb_classmap_impl,
+    cli_args = {
+        "target": cli_args.target_label(),
+    },
+)
diff --git a/buck2/prelude/debugging/labels.bzl b/buck2/prelude/debugging/labels.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/debugging/labels.bzl
@@ -0,0 +1,53 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+### Lookup rules used by BXL script (See fdb.bxl) driven by the labels below:
+# 1. If target has no labels we assume a given target is a rule provider and it exposes relevant providers that BXL script depends on for a given language rule
+
+# 2. If target has a label `dbg:info:exec=//another:target` then we assume that `ExecInfo` (see types.bzl) will be obtained via [RunInfo] of another target (//another:target).
+# For example:
+#    Running "buck run //another:target" (or via using [RunInfo]) should produce `ExecInfo` as its stdout
+
+# 3. If target has a label `dbg:info:ref=//another:target` we assume a presence of //another:target which we can inspect for the presence of relevant providers (see fdb.bxl)
+
+# This label indicates where to locate "[RunInfo]" which would output `ExecInfo` -compatible output
+DBG_INFO_EXEC = "dbg:info:exec"
+
+# This label indicates where to locate "rule provider" for a given target name. Rule providers contains language/framework
+# specific information that help debugging tools to properly configure a debugger. (Support for any given language/rule needs to be implemented in fdb.bxl)
+DBG_INFO_REF = "dbg:info:ref"
+
+DBG_INFO_DISABLE_INCOMPATIBLE_SANITIZERS = "dbg:info:disable-sanitizers"
+
+# This label indicates we want to materialize debuginfo for the "native" (e.g.
+# C++) dependencies of a Python target.
+DBG_INFO_PYTHON_REQUIRES_SECONDARY_NATIVE_DEBUGINFO = "dbg:info:python-secondary-native-debuginfo-required"
+
+def dbg_info_exec(target_label) -> list[str]:
+    return ["{}={}".format(DBG_INFO_EXEC, target_label)]
+
+def dbg_info_ref(target_label) -> list[str]:
+    return ["{}={}".format(DBG_INFO_REF, target_label)]
+
+def get_info_ref(labels: list[str]) -> [str, None]:
+    for label in labels:
+        result = get_value_by_mark(DBG_INFO_REF, label)
+        if result:
+            return result
+    return None
+
+def get_label_or_mark(label: str) -> str:
+    for mark in [DBG_INFO_EXEC, DBG_INFO_REF]:
+        if label.startswith(mark):
+            return mark
+    return label
+
+def get_value_by_mark(mark: str, label: str) -> [str, None]:
+    if label.startswith(mark + "="):
+        return label.removeprefix(mark + "=")
+    return None
diff --git a/buck2/prelude/debugging/types.bzl b/buck2/prelude/debugging/types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/debugging/types.bzl
@@ -0,0 +1,106 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+
+# Types in this file represent a contract between a BXL script (see fdb.bxl) and internal debugging tool.
+# These most likely will change as the BXL integration evolves over time to be more generic
+# Right now the internal tool is making a call "buck2 bxl @mode prelude//debugging:fdb.bxl --target //some_target --arg=arg1 --arg=2"
+# And fdb.bxl is expected to output artifact with serialized ExecInfo
+# This information will be used to build debug configuration (primarily VSCode launch configuration but in some cases CLI invocations or Android Studio requests)
+
+# This type represents strongly typed contract used by "fdb.bxl" script arguments.
+# Even though arguments are available in "bxl_ctx", when using ctx.dynamic_output it's not possible to access arguments from there
+# One way to work this around is by capturing an object in a closure and this type is used to carry the contract for this object
+ScriptSettings = record(
+    target = field(bxl.ConfiguredTargetNode),
+    args = field(list[ArgLike], default = []),
+)
+
+# Basic information about requested target
+TargetInfo = record(
+    # fully qualified target name used
+    target = field(str),
+    # the rule type of the target
+    target_type = field(str),
+    # labels on the target
+    labels = field(list[str], default = []),
+)
+
+# if the target recommends a certain build configuration (e.g. build mode, buck config flags).
+# See documentation in Rust-side for more details.
+TargetPreExecInfo = record(
+    target_info = field(TargetInfo),
+    recommended_build_mode = field(str | None),
+    recommended_build_config = field(list[str]),
+)
+
+# This type mostly represent internal quirks of how python binary debugging is done.
+PythonInfo = record(
+    # TODO: probably unused keeping for safety
+    root = field(str),
+    # python script that will be used to bootstrap debugger for the "python_binary"
+    entrypoint = field(str),
+    # the module to load by bootstrap script
+    main_module = field(str),
+)
+
+# Information required to setup debug information for CLR (Common Language Runtime) targets.
+ClrInfo = record(
+    entrypoint = field(str),
+    args = field([list[ArgLike], None]),
+    cwd = field(str),
+)
+
+# This is a generic type used to customize VSCode debugging.
+# Internal VSCode debugger setup supports customizations via Jinja templates
+# This type allows to extend which template is to be used and what extra parameters are needed to render it
+Custom = record(
+    launch_mode = field([str, None]),
+    template = field(dict[str, str], default = {}),
+    template_params = field(dict[str, dict[str, [str, list[str]]]]),
+)
+
+# Java DAP server requires this file in order to correctly locate classes in the source files
+# The integration with a tool is available as a part of "JVM" rules. (java/kotlin_library/binary/test)
+JavaInfo = record(
+    classmap_file = field(Artifact | None),
+)
+
+# Customizations that are understood by debugging tool
+TargetExtraInfo = record(
+    exec_info_version = field(int),
+    debugger = field(str),
+    # program to run under debugger
+    program = field([cmd_args, None], default = None),
+    # unstripped libraries path used for debugging of specific android binaries and apks
+    library_search_path = field([str, None], default = None),
+    # explicit args to pass to the program run under debugger
+    args = field([list[ArgLike], None], default = None),
+    # extra environment variables to pass to the debugger
+    env = field(dict, default = {}),
+    source_map = field(list[list[str]] | None, default = None),
+    python = field([PythonInfo, None], default = None),
+    clr = field([ClrInfo, None], default = None),
+    vscode = field([Custom, None], default = None),
+    custom = field([Custom, None], default = None),
+    java = field([JavaInfo, None], default = None),
+)
+
+UserMessage = record(
+    title = field(str),
+    body = field(str),
+)
+
+# Full BXL response data structure understood by debugging tool
+ExecInfo = record(
+    target_name = field(str),
+    target_info = field(TargetInfo),
+    data = field([TargetExtraInfo, None], default = None),
+    messages = field(list[UserMessage], default = []),
+)
diff --git a/buck2/prelude/decls/android_common.bzl b/buck2/prelude/decls/android_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/android_common.bzl
@@ -0,0 +1,94 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+def _manifest_apk_arg():
+    return {
+        "manifest": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+    Relative path to the Android manifest for the APK. The common
+     case is that the manifest will be in the same directory as the
+     rule, in which case this will simply be
+     `'AndroidManifest.xml'`, but it can also reference
+     an `android_manifest()` rule.
+
+     Prefer using `manifest_skeleton`, which performs merging automatically.
+     Exactly one of `manifest` and `manifest_skeleton` must be set.
+""",
+        ),
+        "manifest_skeleton": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+    Relative path to the skeleton Android manifest for the APK.
+     An `android_manifest()` will be created automatically to merge
+     all manifests from libraries and resources going into the app.
+     The common case is that the manifest will be in the same directory as the
+     rule, in which case this will simply be
+     `'AndroidManifest.xml'`.
+
+     Exactly one of `manifest` and `manifest_skeleton` must be set.
+""",
+        ),
+    }
+
+def _deps_apk_arg():
+    return {
+        "deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    List of build targets whose corresponding compiled Java code,
+     Android resources, and native libraries will be included in the APK.
+     From the transitive closure of these dependencies, the outputs of rules of the following type will be included in the APK:
+     * `android_library()`* `android_resource()`* `cxx_library()`* `groovy_library()`* `java_library()`* `java_binary()`* `prebuilt_jar()`* `prebuilt_native_library()`
+""",
+        ),
+    }
+
+def _manifest_arg():
+    return {
+        "manifest": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+    An optional [Android Manifest](http://developer.android.com/guide/topics/manifest/manifest-intro.html) for the to declare any permissions or intents it may need or want to handle. May either be a file or an `android_manifest()` target.
+""",
+        ),
+    }
+
+def _patches_system_module_arg():
+    return {
+        "patches_system_module": attrs.bool(
+            default = False,
+            doc = """
+    Allow this target's sources to (re)declare packages that already exist
+     in the `--system` module image (`java.base`). Needed under the JDK 9+
+     module system when compiling stub sources for such packages (e.g.
+     Android's `dalvik.system`), which otherwise fail with "package exists
+     in another module: java.base". When set, the compiler is invoked with
+     `--patch-module java.base=.`, folding this target's sources into that
+     module. All sources in the compilation are patched in, so a target
+     using this should only contain sources whose packages belong in the
+     system module.
+""",
+        ),
+    }
+
+android_common = struct(
+    manifest_apk_arg = _manifest_apk_arg,
+    deps_apk_arg = _deps_apk_arg,
+    manifest_arg = _manifest_arg,
+    patches_system_module_arg = _patches_system_module_arg,
+)
diff --git a/buck2/prelude/decls/android_rules.bzl b/buck2/prelude/decls/android_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/android_rules.bzl
@@ -0,0 +1,1842 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//:attrs_validators.bzl", "validation_common")
+load("@prelude//:genrule.bzl", "genrule_attributes")
+load(
+    "@prelude//:validation_deps.bzl",
+    "VALIDATION_DEPS_ATTR_NAME",
+)
+load("@prelude//android:build_only_native_code.bzl", "is_build_only_native_code")
+load("@prelude//android:configuration.bzl", "CPU_TRANSITION_ATTRS", "cpu_split_transition", "cpu_transition", "is_building_android_binary_attr")
+load("@prelude//android:cpu_filters.bzl", "ALL_CPU_FILTERS")
+load("@prelude//decls:test_common.bzl", "test_common")
+load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")
+load("@prelude//utils:clear_platform.bzl", "clear_platform_transition")
+load(":android_common.bzl", "android_common")
+load(":common.bzl", "TestType", "buck", "prelude_rule")
+load(":core_rules.bzl", "TargetCpuType")
+load(":genrule_common.bzl", "genrule_common")
+load(":java_rules.bzl", "dex_min_sdk_version")
+load(":jvm_common.bzl", "jvm_common")
+load(":re_test_common.bzl", "re_test_common")
+load(":toolchains_common.bzl", "toolchains_common")
+
+DexStore = ["raw", "raw_subdir", "jar", "xzs"]
+
+DuplicateResourceBehaviour = ["allow_by_default", "ban_by_default"]
+
+ExopackageMode = ["secondary_dex", "native_library", "resources", "modules", "arch64"]
+
+JvmLanguage = ["java", "kotlin", "scala"]
+
+PackageType = ["debug", "instrumented", "release", "test"]
+
+RType = [
+    "anim",
+    "animator",
+    "array",
+    "attr",
+    "bool",
+    "color",
+    "dimen",
+    "drawable",
+    "fraction",
+    "font",
+    "id",
+    "integer",
+    "interpolator",
+    "layout",
+    "menu",
+    "navigation",
+    "mipmap",
+    "plurals",
+    "raw",
+    "string",
+    "style",
+    "styleable",
+    "transition",
+    "xml",
+]
+
+ResourceCompressionMode = ["disabled", "enabled", "enabled_strings_only", "enabled_with_strings_as_assets"]
+
+SdkProguardType = ["default", "optimized", "none"]
+
+# @oss-disable[end= ]: GatoradePhase = ["early", "middle", "late"]
+
+DISABLE_STRIPPING = read_root_config("android", "disable_stripping") in ("True", "true")
+
+# Format is {"ovveride_name": {"re_cap_key": "re_cap_value"}}; for example:
+#    {
+#        "dynamic-listing": {
+#            "platform": "riot",
+#            "pool": "EUREKA_POOL",
+#        },
+#        "test-execution": {
+#            "platform": "riot",
+#            "pool": "EUREKA_POOL",
+#        },
+#    }
+RE_CAPS = attrs.option(attrs.dict(key = attrs.string(), value = attrs.dict(key = attrs.string(), value = attrs.string())), default = None)
+
+# Format is {"ovveride_name": "re_use_case"}; for example:
+#     {
+#         "dynamic-listing": "riot",
+#         "test-execution": "riot",
+#     }
+RE_USE_CASE = attrs.option(attrs.dict(key = attrs.string(), value = attrs.string()), default = None)
+
+# Format is {"ovveride_name": {"param_name": param_value}}; for example:
+#    {
+#        "remote_execution_policy": {"setup_preference_key": "some_json_string"},
+#    }
+META_INTERNAL_EXTRA_PARAMS = attrs.option(attrs.dict(key = attrs.string(), value = attrs.any()), default = None)
+
+# Common attributes shared between android_binary and android_bundle rules
+ANDROID_BINARY_BUNDLE_COMMON_ATTRS = (
+    {
+        "aapt2_keep_raw_values": attrs.bool(default = False, doc = ""),
+        "aapt2_locale_filtering": attrs.bool(default = False, doc = ""),
+        "aapt2_preferred_density": attrs.option(attrs.string(), default = None, doc = ""),
+        "additional_aapt_params": attrs.list(attrs.string(), default = [], doc = ""),
+        "allow_r_dot_java_in_secondary_dex": attrs.bool(default = False, doc = ""),
+        "allowed_duplicate_resource_types": attrs.list(
+            attrs.enum(RType),
+            default = [],
+            doc = "Similar to banned_duplicate_resource_types, but lists the types that are allowed to have duplicates. This should only be used if duplicate_resource_behavior is 'ban_by_default'.",
+        ),
+        "android_sdk_proguard_config": attrs.option(
+            attrs.enum(SdkProguardType),
+            default = None,
+            doc = "The type of proguard configuration to use from the Android SDK. Options are 'default' to use the default config, 'optimized' to use the config with optimizations enabled, or 'none' to not use any standard configuration (you will need to supply your own version, otherwise your app will probably not work).",
+        ),
+        "application_module_blocklist": attrs.option(attrs.list(attrs.transition_dep(cfg = cpu_transition)), default = None, doc = ""),
+        "application_module_configs": attrs.dict(
+            key = attrs.string(),
+            value = attrs.list(attrs.transition_dep(cfg = cpu_transition)),
+            sorted = False,
+            default = {},
+            doc = "A map of module names to lists of targets, where the targets should seed the corresponding module. The seed targets and their exclusive dependencies are packaged into the APK in separate files to allow them to be loaded independently.",
+        ),
+        "application_module_dependencies": attrs.option(attrs.dict(key = attrs.string(), value = attrs.list(attrs.string()), sorted = False), default = None, doc = ""),
+        "banned_duplicate_resource_types": attrs.list(
+            attrs.enum(RType),
+            default = [],
+            doc = "If ['string'] is used, the build will break if multiple string resources with the same name are added in an app's Android Resources. Resource names are name-spaced by resource type, this does not enforce unique names between multiple resource types. AAPT does not enforce this, but you can prevent easy-to-introduce resource bugs by enabling this.",
+        ),
+        "build_config_values": attrs.list(attrs.string(), default = [], doc = "See the documentation on the values argument for android_build_config()."),
+        "build_config_values_file": attrs.option(
+            attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()),
+            default = None,
+            doc = "See the documentation on the values_file argument for android_build_config().",
+        ),
+        "build_string_source_map": attrs.bool(default = False, doc = ""),
+        "compiled_resource_apks": attrs.list(attrs.source(), default = [], doc = ""),
+        "cpu_filters": attrs.list(
+            attrs.enum(TargetCpuType),
+            default = [],
+            doc = """The CPU architecture filter applied to the final apk. Could be a subset of ARM, ARMV7, ARM64, X86, X86_64, MIPS. \
+Note: If you set this parameter, you must setup your NDK, otherwise Buck build will fail.""",
+        ),
+        "default_module_manifest_skeleton": attrs.option(attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()), default = None, doc = ""),
+        "defer_relink": attrs.bool(default = False),
+        "deps": attrs.list(
+            attrs.split_transition_dep(cfg = cpu_split_transition),
+            default = [],
+            doc = """List of build targets whose corresponding compiled Java code, Android resources, and native libraries will be included in the APK. \
+From the transitive closure of these dependencies, the outputs of rules of the following type will be included in the APK: \
+android_library(), android_resource(), cxx_library(), groovy_library(), java_library(), java_binary(), prebuilt_jar(), prebuilt_native_library().""",
+        ),
+        "dex_compression": attrs.option(attrs.enum(DexStore), default = None, doc = ""),
+        "disable_pre_dex": attrs.bool(default = False, doc = ""),
+        "duplicate_class_checker_enabled": attrs.bool(default = False, doc = ""),
+        "duplicate_resource_behavior": attrs.enum(
+            DuplicateResourceBehaviour,
+            default = "allow_by_default",
+            doc = "If set to 'ban_by_default', duplicate resource definitions with the same type and name will cause the build to fail, unless they are excluded by allowed_duplicate_resource_types or duplicate_resource_whitelist. If set to 'allow_by_default' (the default), no duplicate resource checks will be performed. They can still be enabled on individual types by using banned_duplicate_resource_types.",
+        ),
+        "duplicate_resource_whitelist": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = "Either a build target or a path to a file containing a whitelist of resources that should be excluded from duplicate resource detection. Format is one resource per line with the type followed by the name, separated by a space. For example, 'string app_name'.",
+        ),
+        "enable_bootstrap_dexes": attrs.bool(default = False, doc = ""),
+        "enable_relinker": attrs.bool(default = False, doc = ""),
+        "exclude_duplicate_targets_do_not_use": attrs.list(attrs.dep(), default = [], doc = ""),
+        "exopackage_modes": attrs.list(attrs.enum(ExopackageMode), default = [], doc = ""),
+        "extra_filtered_resources": attrs.list(attrs.string(), default = [], doc = ""),
+        "extra_no_compress_asset_extensions": attrs.list(attrs.string(), default = [], doc = ""),
+        "extra_no_compress_asset_regex": attrs.option(attrs.string(), default = None, doc = ""),
+        "extra_relinker_outputs": attrs.list(attrs.string(), default = [], doc = ""),
+        # @oss-disable[end= ]: "gatorade_extra_args": attrs.list(attrs.arg(), default = [], doc = "Extra Gatorade cross-library step arguments"),
+        # @oss-disable[end= ]: "gatorade_phases": attrs.set(attrs.enum(GatoradePhase), default = []),
+        "ignore_aapt_proguard_config": attrs.bool(default = False, doc = "If true, the proguard config automatically generated by aapt will be ignored."),
+        "include_build_info_file": attrs.bool(
+            # @oss-disable[end= ]: default = True,
+            default = False, # @oss-enable
+            doc = "Bake `assets/BuildInfo.json` with the buck2 `BUCK_BUILD_ID` into the APK so an installed build can be resolved back to its buck2 build and source commit. On by default for non-release builds in fbsource; set this attribute to `False` to disable. The `apk_build` action invokes a toolchain-provided generator to write the file, so the baked id refreshes when the APK content changes and a no-op rebuild reuses a prior (equally valid) id.",
+        ),
+        "includes_vector_drawables": attrs.bool(
+            default = False,
+            doc = "When calling AAPT during the packaging process, pass the --no-version-vectors flag which ensures that any vector drawables which make use of the Android support library are backwards compatible with Android 4.4 and earlier.",
+        ),
+        "is_cacheable": attrs.bool(default = False, doc = ""),
+        "is_voltron_language_pack_enabled": attrs.bool(default = False, doc = ""),
+        "keystore": attrs.dep(doc = "A build target that identifies a keystore to use to sign the APK."),
+        "locales": attrs.list(attrs.string(), default = [], doc = ""),
+        "manifest": attrs.option(
+            attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()),
+            default = None,
+            doc = """Relative path to the Android manifest for the APK. The common case is that the manifest will be in the same directory as the rule, in which case this will simply be 'AndroidManifest.xml', but it can also reference an `android_manifest()` rule. Prefer using `manifest_skeleton`, which performs merging automatically. Exactly one of `manifest` and `manifest_skeleton` must be set.""",
+        ),
+        "manifest_entries": attrs.dict(
+            key = attrs.string(),
+            value = attrs.any(),
+            default = {},
+            doc = "Insert values into the packaged AndroidManifest.xml file. Valid values are min_sdk_version, target_sdk_version, version_code, version_name, and debug_mode.",
+        ),
+        "manifest_skeleton": attrs.option(
+            attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()),
+            default = None,
+            doc = """Relative path to the skeleton Android manifest for the APK. An `android_manifest()` will be created automatically to merge all manifests from libraries and resources going into the app. The common case is that the manifest will be in the same directory as the rule, in which case this will simply be 'AndroidManifest.xml'. Exactly one of `manifest` and `manifest_skeleton` must be set.""",
+        ),
+        "min_sdk_version": attrs.option(attrs.int(), default = None),
+        "minimize_primary_dex_size": attrs.bool(default = False, doc = ""),
+        "multidex_min_api": attrs.option(attrs.string(), default = None, doc = ""),
+        "native_library_bolt_args": attrs.option(attrs.dict(key = attrs.string(), value = attrs.list(attrs.arg())), default = None, doc = ""),
+        "native_library_merge_code_generator": attrs.option(attrs.exec_dep(), default = None, doc = ""),
+        "native_library_merge_glue": attrs.option(attrs.split_transition_dep(cfg = cpu_split_transition), default = None, doc = ""),
+        "native_library_merge_linker_args": attrs.option(attrs.dict(key = attrs.string(), value = attrs.list(attrs.arg())), default = None, doc = ""),
+        "native_library_merge_linker_args_all": attrs.list(attrs.arg(), default = [], doc = "Extra linker arguments passed to all merged libraries."),
+        "native_library_merge_map": attrs.option(
+            attrs.dict(key = attrs.string(), value = attrs.list(attrs.regex()), sorted = False),
+            default = None,
+            doc = "An advanced option for apps with many native libraries.",
+        ),
+        "native_library_merge_non_asset_libs": attrs.bool(default = False, doc = ""),
+        "native_library_merge_sequence": attrs.option(
+            attrs.list(
+                attrs.one_of(
+                    attrs.tuple(attrs.string(), attrs.list(attrs.regex())),
+                    attrs.list(attrs.tuple(attrs.string(), attrs.list(attrs.regex()))),
+                ),
+            ),
+            default = None,
+            doc = """Defines a prioritized sequence of instructions for merging native libraries. Sequence entries are tuples comprised of a merged library name and a list of regular expressions for which matching native library targets and their dependencies will be added to the merged library, unless an earlier entry already matched them. Merged library names must begin with `lib` and end with `.so`. This is an advanced option for apps with many native libraries.""",
+        ),
+        "native_library_merge_sequence_blocklist": attrs.option(
+            attrs.list(attrs.regex()),
+            default = None,
+            doc = """Defines a list of regular expressions for which matching native library targets will not be merged by `native_library_merge_sequence`. Blocked targets' unblocked dependencies will still be merged.""",
+        ),
+        "native_library_pick_first": attrs.list(attrs.string(), default = [], doc = ""),
+        "no_dx": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """List of dependency targets whose Java code should be excluded from the DEX files in the final APK. \
+The classes from these targets will not be dexed, but their other resources will still be included. \
+This might be useful to resolve duplicate class errors when multiple dependencies provide the same class. \
+See [this document](https://www.internalfb.com/intern/staticdocs/confucius/docs/notes/dev/projects/android/resolving_duplicate_classes_with_no_dx/) \
+for how to resolve duplicate classes using this attribute.""",
+        ),
+        "optimization_passes": attrs.int(default = 1, doc = ""),
+        "package_asset_libraries": attrs.bool(default = False, doc = ""),
+        "package_type": attrs.enum(
+            PackageType,
+            default = "debug",
+            doc = "Determines whether ProGuard will be used when packaging the APK. Acceptable values for package_type are 'debug' and 'release'. The default value is 'debug', which indicates that ProGuard should not be used.",
+        ),
+        "package_validators": attrs.list(
+            attrs.tuple(
+                attrs.exec_dep(providers = [RunInfo]),
+                attrs.list(attrs.arg(), default = []),
+            ),
+            default = [],
+        ),
+        "package_voltron_asset_libraries": attrs.bool(
+            default = False,
+            doc = "Similar global flag as package_asset_libraries to control voltron module libs specifically.",
+        ),
+        "packaged_locales": attrs.list(attrs.string(), default = [], doc = ""),
+        "packaging_options": attrs.dict(key = attrs.string(), value = attrs.list(attrs.string()), default = {}, doc = ""),
+        "post_filter_resources_cmd": attrs.option(attrs.arg(), default = None, doc = ""),
+        "preinline_ir_sonames": attrs.list(attrs.string(), default = [], doc = "Sonames the pre-inline IR dump is restricted to (empty = all)."),
+        "preprocess_java_classes_bash": attrs.option(attrs.arg(), default = None, doc = ""),
+        "preprocess_java_classes_deps": attrs.list(attrs.dep(), default = [], doc = ""),
+        "primary_dex_patterns": attrs.list(attrs.string(), default = [], doc = ""),
+        "proguard_config": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = "Relative path to a ProGuard configuration file that will be passed via the -include flag when package_type is 'release'.",
+        ),
+        "proguard_jvm_args": attrs.list(attrs.string(), default = [], doc = ""),
+        "relinker_extra_args": attrs.dict(
+            key = attrs.string(),
+            value = attrs.list(attrs.arg()),
+            sorted = False,
+            default = {},
+            doc = "Per-library extra linker arguments passed when relinking, mapping sonames to lists of arguments.",
+        ),
+        "relinker_extra_args_all": attrs.list(attrs.arg(), default = [], doc = "Extra arguments passed when relinking all libraries."),
+        "relinker_extra_deps": attrs.list(
+            attrs.split_transition_dep(cfg = cpu_split_transition),
+            default = [],
+            doc = "Deps statically linked to every native lib by the relinker.",
+        ),
+        "relinker_whitelist": attrs.list(attrs.regex(), default = [], doc = ""),
+        "resource_compression": attrs.enum(ResourceCompressionMode, default = "disabled", doc = ""),
+        "resource_filter": attrs.list(attrs.string(), default = [], doc = ""),
+        "resource_stable_ids": attrs.option(attrs.source(), default = None, doc = ""),
+        "secondary_dex_weight_limit": attrs.option(attrs.int(), default = None, doc = ""),
+        "shared_libraries_to_exclude": attrs.list(attrs.label(), default = [], doc = ""),
+        "skip_crunch_pngs": attrs.option(attrs.bool(), default = None, doc = "If True, PNGs in the APK are not crushed by aapt."),
+        "skip_proguard": attrs.bool(
+            default = False,
+            doc = "To produce a release build without running ProGuard set the skip_proguard flag to True. This will still cause ProGuard configuration files to be generated for use by other optimizers like Redex.",
+        ),
+        "trim_resource_ids": attrs.bool(default = False, doc = ""),
+        "use_split_dex": attrs.bool(
+            default = False,
+            doc = """If this argument is True, Buck enables multidex support for the output APK. \
+Multidex support enables your app to use multiple Dalvik Executable (DEX) bytecode files and thereby \
+work around the 64K limit on the number of methods that can be referenced in a single DEX file.""",
+        ),
+        "xz_compression_level": attrs.int(default = 4, doc = ""),
+        "_android_toolchain": toolchains_common.android(),
+        "_cxx_toolchain": attrs.split_transition_dep(cfg = cpu_split_transition, default = "toolchains//:android-hack"),
+        "_dex_toolchain": toolchains_common.dex(),
+        "_exec_os_type": buck.exec_os_type_arg(),
+        "_is_building_android_binary": attrs.default_only(attrs.bool(default = True)),
+        "_java_toolchain": toolchains_common.java_for_android(),
+        VALIDATION_DEPS_ATTR_NAME: attrs.set(attrs.transition_dep(cfg = cpu_transition), sorted = True, default = []),
+    }
+    | CPU_TRANSITION_ATTRS
+    | buck.licenses_arg()
+    | buck.labels_arg()
+    | buck.contacts_arg()
+)
+
+ANDROID_BINARY_ATTRS = (
+    ANDROID_BINARY_BUNDLE_COMMON_ATTRS
+    | {
+        "strip_libraries": attrs.bool(default = not DISABLE_STRIPPING),
+    }
+    | constraint_overrides.attributes
+)
+ANDROID_BUNDLE_ATTRS = ANDROID_BINARY_BUNDLE_COMMON_ATTRS | {
+    "bundle_config_file": attrs.option(attrs.source(), default = None, doc = ""),
+    "module_manifest_skeleton": attrs.dict(
+        default = {},
+        key = attrs.string(),
+        sorted = False,
+        value = attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()),
+        doc = "",
+    ),
+    "module_manifests": attrs.option(attrs.transition_dep(cfg = cpu_transition), default = None, doc = ""),
+    "use_derived_apk": attrs.bool(default = False),
+}
+
+android_aar = prelude_rule(
+    name = "android_aar",
+    docs = """
+        An `android_aar()` rule is used to generate an Android AAR.
+
+        See the [official Android documentation](https://developer.android.com/studio/projects/android-library#aar-contents) for details about the `.aar` format.
+    """,
+    examples = """
+        ```
+        android_resource(
+          name = 'res',
+          res = 'res',
+          assets = 'assets',
+          package = 'com.example',
+        )
+
+        android_library(
+          name = 'lib',
+          srcs = glob(['**/*.java']),
+        )
+
+        android_aar(
+          name = 'app',
+          manifest_skeleton = 'AndroidManifestSkeleton.xml',
+          deps = [
+            ':res',
+            ':lib',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "manifest_skeleton": attrs.source(
+                doc = """
+                The skeleton manifest file used to generate the final `AndroidManifest.xml` . May either be a file or an `android_manifest()` target.
+            """,
+            ),
+            "build_config_values": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                See the documentation on the values argument for `android_build_config()`.
+            """,
+            ),
+            "include_build_config_class": attrs.bool(
+                default = False,
+                doc = """
+                Whether to include the `BuildConfig` class files in the final .aar file. Needs
+                 to be set to `True` if any build\\_config\\_values are specified.
+                 This is normally only needed if the build tool that is consuming the .aar file does not generate
+                 `BuildConfig` classes.
+                 Note: the AAR format does not specify a way to pass defaults that should be injected into
+                 the final `BuildConfig` class, therefore that information might need to be replicated
+                 manually in the build that's consuming the .aar file.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.split_transition_dep(cfg = cpu_split_transition),
+                default = [],
+                doc = """
+                List of build targets whose corresponding compiled Java code,
+                 Android resources, and native libraries will be included in the AAR along with their transitive
+                 dependencies. For compile time deps which should not be included in the final AAR,
+                 use `provided_deps` instead.
+                 * `android_library()` Will be included in the final `classes.jar`* `android_resource()` Will be included in the final `R.txt`,
+                 `res/` and `assets/`* `android_build_config()` Will be included in the final `classes.jar`
+                 if `include_build_config_class` is True
+                 * `groovy_library()` Will be included in the final `classes.jar`* `java_library()` Will be included in the final `classes.jar`* `prebuilt_jar()` Will be included in the final `classes.jar`* `prebuilt_native_library()` Will be included in the final `jni/` or
+                 `assets/` if `is_asset` is True
+            """,
+            ),
+            "remove_classes": attrs.list(
+                attrs.regex(),
+                default = [],
+                doc = """
+                List of classes to remove from the output aar. It removes classes from the target's own sources,
+                 and its dependencies.
+            """,
+            ),
+            "build_config_values_file": attrs.option(attrs.source(), default = None),
+            "cpu_filters": attrs.list(attrs.enum(TargetCpuType), default = ALL_CPU_FILTERS),
+            "enable_relinker": attrs.bool(default = False),
+            "excluded_java_deps": attrs.list(attrs.dep(), default = []),
+            "extra_arguments": attrs.list(attrs.string(), default = []),
+            "extra_kotlinc_arguments": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "extra_relinker_outputs": attrs.list(attrs.string(), default = []),
+            "preinline_ir_sonames": attrs.list(attrs.string(), default = []),
+            # @oss-disable[end= ]: "gatorade_extra_args": attrs.list(attrs.arg(), default = [], doc = "Extra Gatorade cross-library step arguments"),
+            # @oss-disable[end= ]: "gatorade_phases": attrs.set(attrs.enum(GatoradePhase), default = []),
+            "hardcode_permissions_for_deterministic_output": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                If set to true, Buck hardcodes the permissions in order to ensures that all files have the same
+                permissions regardless of the platform on which the zip was generated.
+            """,
+            ),
+            "java_version": attrs.option(attrs.string(), default = None),
+            "language": attrs.option(attrs.enum(JvmLanguage), default = None),
+            "manifest": attrs.option(attrs.source(), default = None),
+            "manifest_entries": attrs.dict(key = attrs.string(), value = attrs.any(), default = {}),
+            "manifest_file": attrs.option(attrs.source(), default = None),
+            "maven_coords": attrs.option(attrs.string(), default = None),
+            "min_sdk_version": attrs.option(attrs.int(), default = None),
+            "native_library_bolt_args": attrs.option(attrs.dict(key = attrs.string(), value = attrs.list(attrs.arg())), default = None),
+            "native_library_merge_code_generator": attrs.option(attrs.exec_dep(), default = None),
+            "native_library_merge_glue": attrs.option(attrs.split_transition_dep(cfg = cpu_split_transition), default = None),
+            "native_library_merge_linker_args": attrs.option(attrs.dict(key = attrs.string(), value = attrs.list(attrs.arg())), default = None),
+            "native_library_merge_linker_args_all": attrs.list(attrs.arg(), default = [], doc = "Extra linker arguments passed to all merged libraries."),
+            "native_library_merge_map": attrs.option(attrs.dict(key = attrs.string(), value = attrs.list(attrs.regex()), sorted = False), default = None),
+            "native_library_merge_non_asset_libs": attrs.bool(default = False),
+            "native_library_merge_sequence": attrs.option(
+                attrs.list(
+                    attrs.one_of(
+                        attrs.tuple(attrs.string(), attrs.list(attrs.regex())),
+                        attrs.list(attrs.tuple(attrs.string(), attrs.list(attrs.regex()))),
+                    ),
+                ),
+                default = None,
+            ),
+            "native_library_merge_sequence_blocklist": attrs.option(attrs.list(attrs.regex()), default = None),
+            "package_asset_libraries": attrs.bool(default = True),
+            "package_resources": attrs.bool(default = True),
+            "proguard_config": attrs.option(attrs.source(), default = None),
+            "relinker_extra_args": attrs.dict(
+                key = attrs.string(),
+                value = attrs.list(attrs.arg()),
+                sorted = False,
+                default = {},
+                doc = "Per-library extra linker arguments passed when relinking, mapping sonames to lists of arguments.",
+            ),
+            "relinker_extra_args_all": attrs.list(attrs.arg(), default = [], doc = "Extra arguments passed when relinking all libraries."),
+            "relinker_extra_deps": attrs.list(
+                attrs.split_transition_dep(cfg = cpu_split_transition),
+                default = [],
+                doc = "Deps statically linked to every native lib by the relinker.",
+            ),
+            "relinker_whitelist": attrs.list(attrs.regex(), default = []),
+            "required_for_source_only_abi": attrs.bool(default = False),
+            "resources": attrs.list(attrs.source(), default = []),
+            "resources_root": attrs.option(attrs.string(), default = None),
+            "runtime_deps": attrs.list(attrs.dep(), default = []),
+            "source": attrs.option(attrs.string(), default = None),
+            "source_only_abi_deps": attrs.list(attrs.dep(), default = []),
+            "srcs": attrs.list(attrs.source(), default = []),
+            "strip_libraries": attrs.default_only(attrs.bool(default = not DISABLE_STRIPPING)),
+            "target": attrs.option(attrs.string(), default = None),
+            "_android_toolchain": toolchains_common.android(),
+            "_cxx_toolchain": attrs.split_transition_dep(cfg = cpu_split_transition, default = "toolchains//:android-hack"),
+            "_is_building_android_binary": attrs.default_only(attrs.bool(default = True)),
+            "_java_toolchain": toolchains_common.java_for_android(),
+        }
+        | CPU_TRANSITION_ATTRS
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    )
+    | jvm_common.abi_generation_mode()
+    | jvm_common.annotation_processors()
+    | jvm_common.plugins(),
+)
+
+android_app_modularity = prelude_rule(
+    name = "android_app_modularity",
+    docs = """
+        An `android_app_modularity()` rule is used to determine the modular
+        structure of an Android app. It defines how application modules are
+        configured and which dependencies belong to each module, enabling
+        dynamic delivery and on-demand loading of app features.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "application_module_blocklist": attrs.option(attrs.list(attrs.dep()), default = None, doc = ""),
+            "application_module_configs": attrs.dict(key = attrs.string(), value = attrs.list(attrs.dep()), sorted = False, default = {}, doc = ""),
+            "application_module_dependencies": attrs.option(
+                attrs.dict(key = attrs.string(), value = attrs.list(attrs.string()), sorted = False),
+                default = None,
+                doc = "",
+            ),
+            "deps": attrs.list(attrs.dep(), default = [], doc = ""),
+            "no_dx": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """List of dependency targets whose Java code should be excluded from the DEX files in the final APK. \
+The classes from these targets will not be dexed, but their other resources will still be included. \
+This might be useful to resolve duplicate class errors when multiple dependencies provide the same class. \
+See [this document](https://www.internalfb.com/intern/staticdocs/confucius/docs/notes/dev/projects/android/resolving_duplicate_classes_with_no_dx/) \
+for how to resolve duplicate classes using this attribute.""",
+            ),
+            "should_include_classes": attrs.bool(default = True, doc = ""),
+            "should_include_libraries": attrs.bool(default = False, doc = ""),
+            "_android_toolchain": toolchains_common.android(),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+android_binary = prelude_rule(
+    name = "android_binary",
+    docs = """
+        An `android_binary()` rule is used to generate an Android APK.
+    """,
+    examples = None,
+    further = None,
+    attrs = ANDROID_BINARY_ATTRS,
+    cfg = constraint_overrides.transition,
+)
+
+android_build_config = prelude_rule(
+    name = "android_build_config",
+    docs = """
+        An `android_build_config()` rule is used to generate
+        a `BuildConfig` class with global configuration variables
+        that other `android_library()` rules can compile against.
+        Currently, the only variable exposed by `BuildConfig` is
+        a global `boolean` named `DEBUG`, much like
+        the `BuildConfig.java` generated by the official Android
+        build tools based on Gradle.
+
+        The fields in the generated `BuildConfig` class will
+        be non-constant-expressions (see [JLS 15.28](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28)).
+        However, if `BuildConfig` is packaged into an APK, it will
+        be replaced with a new version where:
+        * The fields will be set to literal values (i.e., constant expressions).
+         * The `boolean BuildConfig.DEBUG` field will correspond to
+        that of the `package_type` argument to the `android_binary()` rule
+        that is packaging it.
+
+        This transformation is done before ProGuard is applied (if applicable), so
+        that it can propagate constants from `BuildConfig` and eliminate
+        dead code.
+    """,
+    examples = """
+        Here is an example of an `android_build_config()` rule that
+        is transitively included by both *debug* and *release* versions
+        of an `android_binary()` rule. The value
+        of `com.example.pkg.BuildConfig.DEBUG` will be different in each APK
+        even though they both transitively depend on the same `:build_config` rule.
+
+        ```
+        android_build_config(
+          name = 'build_config',
+          package = 'com.example.pkg',
+          values = [
+            'String COMMIT_ID = "0000000000000000000000000000000000000000"',
+          ],
+        )
+
+        # The .java files in this library may contain references to the boolean
+        # com.example.pkg.BuildConfig.DEBUG because :build_config is in the deps.
+        # It could also reference BuildConfig.COMMIT_ID.
+        android_library(
+          name = 'mylib',
+          srcs = glob(['src/**/*.java']),
+          deps = [
+            ':build_config',
+          ],
+        )
+
+        android_binary(
+          name = 'debug',
+          package_type = 'DEBUG',
+          keystore =  '//keystores:debug',
+          manifest = 'AndroidManifest.xml',
+          target = 'Google Inc.:Google APIs:19',
+          deps = [
+            ':mylib',
+          ],
+        )
+
+        # The contents of the file generated by this rule might be:
+        #
+        # String COMMIT_ID = "7bf804bdf71fdbfc99cce3b155b3643f022c6fa4"
+        #
+        # Note that the output of :build_config_release_values will be cached by Buck.
+        # Assuming that generate_release_build_config.py depends on state that is not
+        # expressed by its deps (which violates a fundamental invariant in Buck!), a
+        # workaround is to ensure that the inputs to :build_config_release_values are
+        # changed in some way before :release is built to ensure that the output from
+        # :build_config_release_values is not pulled from cache. For example:
+        #
+        # $ buck build :release
+        # $ uuidgen > dummy_state_file.txt
+        # $ buck build :release
+        #
+        # This makes sure that generate_release_build_config.py is re-run before
+        # :release is rebuilt. This is much cheaper than deleting your build cache
+        # before rebuilding.
+        genrule(
+          name = 'build_config_release_values',
+          srcs = [ 'generate_release_build_config.py', 'dummy_state_file.txt' ],
+          bash = 'generate_release_build_config.py $OUT',
+          out = 'build_config_release_values.txt',
+        )
+
+        android_binary(
+          name = 'release',
+          package_type = 'RELEASE',
+          keystore =  '//keystores:release',
+          manifest = 'AndroidManifest.xml',
+          target = 'Google Inc.:Google APIs:19',
+          build_config_values_file = ':build_config_release_values',
+          deps = [
+            ':mylib',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "package": attrs.string(
+                default = "",
+                doc = """
+                Name of the Java package to use in the generated `BuildConfig.java` file.
+                 Most developers set this to the application id declared in the manifest
+                 via `<manifest package="APP_ID">`.
+                 Example: `com.facebook.orca`.
+            """,
+            ),
+            "values": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                List of strings that defines additional fields (and values) that should be declared in the
+                 generated `BuildConfig.java` file. Like `DEBUG`, the values will be
+                 non-constant-expressions that evaluate to the value specified in the file at compilation
+                 time.
+                 To override the values in an APK, specify build\\_config\\_values or build\\_config\\_values\\_file in `android_binary()`.
+            """,
+            ),
+            "values_file": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                Optional path to a file that defines additional fields (and values) that should be declared in the
+                 generated `BuildConfig.java` file. Like `DEBUG`, the values will be
+                 non-constant-expressions that evaluate to the value specified in the file at compilation
+                 time.
+                 To override the values in an APK, specify build\\_config\\_values or build\\_config\\_values\\_file in `android_binary()`.
+
+                 Note that values\\_file can be a generated file, as can build\\_config\\_values\\_file as
+                 demonstrated in the example below.
+            """,
+            ),
+            "_android_toolchain": toolchains_common.android(),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_is_building_android_binary": is_building_android_binary_attr(),
+            "_java_toolchain": toolchains_common.java_for_android(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+android_bundle = prelude_rule(
+    name = "android_bundle",
+    docs = """
+        An `android_bundle()` rule is used to generate an Android App Bundle
+        (AAB). It shares most attributes with `android_binary()`, but produces
+        an AAB file instead of an APK. App Bundles are the recommended
+        publishing format for Google Play, enabling optimized APK delivery
+        per device configuration.
+    """,
+    examples = None,
+    further = None,
+    attrs = ANDROID_BUNDLE_ATTRS,
+)
+
+android_instrumentation_apk = prelude_rule(
+    name = "android_instrumentation_apk",
+    docs = """
+        An `android_instrumentation_apk()` rule is used to generate
+        an Android Instrumentation APK.
+
+        Android's [Testing Fundamentals](http://developer.android.com/tools/testing/testing_android.html) documentation includes a diagram that shows
+        the relationship between an "application package" and a "test package"
+        when running a test. This rule corresponds to a test package. Note
+        that a test package has an interesting quirk where it is *compiled
+        against* an application package, but *must not include* the
+        resources or Java classes of the application package. Therefore, this
+        class takes responsibility for making sure the appropriate bits are
+        excluded. Failing to do so will generate mysterious runtime errors
+        when running the test.
+    """,
+    examples = """
+        Here is an example of an `android_instrumentation_apk()` rule that tests an `android_binary()`, and depends on a test
+        package.
+
+        ```
+        android_library(
+          name = 'test',
+          srcs = glob(['test/**/*.java']),
+        )
+
+        android_binary(
+          name = 'messenger',
+          manifest = 'AndroidManifest.xml',
+          keystore = '//keystores:prod',
+          package_type = 'release',
+          proguard_config = 'proguard.cfg',
+          deps = [
+            ...
+          ],
+        )
+
+        # Building this rule will produce a file named messenger_test.apk
+        android_instrumentation_apk(
+          name = 'messenger_test',
+          manifest = 'AndroidInstrumentationManifest.xml',
+          apk = ':messenger',
+          deps = [
+            ':test',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        android_common.manifest_apk_arg()
+        | {
+            "apk": attrs.dep(
+                doc = """
+                APK build target, which should be used for the instrumentation APK.
+                 Can be either an `android_binary()` or an `apk_genrule()`.
+            """,
+            ),
+        }
+        | android_common.deps_apk_arg()
+        | {
+            "cpu_filters": attrs.list(attrs.enum(TargetCpuType), default = []),
+            "deps": attrs.list(
+                attrs.split_transition_dep(cfg = cpu_split_transition),
+                default = [],
+                doc = """
+                List of build targets whose corresponding compiled Java code,
+                 Android resources, and native libraries will be included in the APK.
+                 From the transitive closure of these dependencies, the outputs of rules of the following type will be included in the APK:
+                 * `android_library()`* `android_resource()`* `cxx_library()`* `groovy_library()`* `java_library()`* `java_binary()`* `prebuilt_jar()`* `ndk_library()`* `prebuilt_native_library()`
+            """,
+            ),
+            "disable_pre_dex": attrs.bool(default = False),
+            "enable_bootstrap_dexes": attrs.bool(default = False),
+            "includes_vector_drawables": attrs.bool(default = False),
+            "is_self_instrumenting": attrs.bool(default = False),
+            "manifest": attrs.option(
+                attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()),
+                default = None,
+                doc = """
+                Relative path to the Android manifest for the APK. The common
+                 case is that the manifest will be in the same directory as the
+                 rule, in which case this will simply be
+                 `'AndroidManifest.xml'`, but it can also reference
+                 an `android_manifest()` rule.
+
+                 Prefer using `manifest_skeleton`, which performs merging automatically.
+                 Exactly one of `manifest` and `manifest_skeleton` must be set.
+            """,
+            ),
+            "manifest_skeleton": attrs.option(
+                attrs.one_of(attrs.transition_dep(cfg = cpu_transition), attrs.source()),
+                default = None,
+                doc = """
+                Relative path to the skeleton Android manifest for the APK.
+                 An `android_manifest()` will be created automatically to merge
+                 all manifests from libraries and resources going into the app.
+                 The common case is that the manifest will be in the same directory as the
+                 rule, in which case this will simply be
+                 `'AndroidManifest.xml'`.
+
+                 Exactly one of `manifest` and `manifest_skeleton` must be set.
+            """,
+            ),
+            "min_sdk_version": attrs.option(attrs.int(), default = None),
+            "multidex_min_api": attrs.option(attrs.string(), default = None),
+            "preprocess_java_classes_bash": attrs.option(attrs.arg(), default = None),
+            "preprocess_java_classes_deps": attrs.list(attrs.dep(), default = []),
+            "primary_dex_patterns": attrs.list(attrs.string(), default = []),
+            "use_split_dex": attrs.option(attrs.bool(), default = None),
+            "_android_toolchain": toolchains_common.android(),
+            "_cxx_toolchain": attrs.split_transition_dep(cfg = cpu_split_transition, default = "toolchains//:android-hack"),
+            "_dex_toolchain": toolchains_common.dex(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_is_building_android_binary": attrs.default_only(attrs.bool(default = True)),
+            "_java_toolchain": toolchains_common.java_for_android(),
+        }
+        | CPU_TRANSITION_ATTRS
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+android_instrumentation_test = prelude_rule(
+    name = "android_instrumentation_test",
+    docs = """
+        An `android_instrumentation_test()` rule is used to define
+         apks that should be used to run Android instrumentation tests.
+    """,
+    examples = """
+        Here is an example of an `android_instrumentation_test()`
+         rule that tests an `android_binary()`.
+
+        ```
+        android_binary(
+          name = 'messenger',
+          manifest = 'AndroidManifest.xml',
+          keystore = '//keystores:prod',
+          package_type = 'release',
+          proguard_config = 'proguard.cfg',
+          deps = [
+            ...
+          ],
+        )
+
+        android_instrumentation_apk(
+          name = 'messenger_test',
+          manifest = 'AndroidInstrumentationManifest.xml',
+          apk = ':messenger',
+          deps = [
+            ...
+          ],
+        )
+
+        android_instrumentation_test(
+          name = 'messenger_instrumentation_test',
+          apk = ':messenger_test',
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.inject_test_env_arg()
+        | {
+            "apk": attrs.dep(
+                doc = """
+                The APK containing the tests. Can be an `android_binary()`,
+                 an `apk_genrule()` or an `android_instrumentation_apk()`.
+            """,
+            ),
+        }
+        | buck.test_label_arg()
+        | buck.test_rule_timeout_ms()
+        | buck.licenses_arg()
+        | buck.contacts_arg()
+        | {
+            "clear_package_data": attrs.bool(
+                default = False,
+                doc = """
+                Runs `pm clear` on the app and test packages before the test run if set to True.
+            """,
+            ),
+            "collect_tombstones": attrs.bool(
+                default = False,
+                doc = """
+                Checks whether the test generated any tombstones, and downloads them from the emulator if true.
+            """,
+            ),
+            "disable_animations": attrs.bool(
+                default = False,
+                doc = """
+                Disables animations on the emulator if set to True.
+            """,
+            ),
+            "env": attrs.dict(key = attrs.string(), value = attrs.arg(), sorted = False, default = {}),
+            "extra_instrumentation_args": attrs.option(attrs.dict(key = attrs.string(), value = attrs.arg()), default = None),
+            "instrumentation_test_listener": attrs.option(attrs.exec_dep(), default = None),
+            "instrumentation_test_listener_class": attrs.option(attrs.string(), default = None),
+            "is_self_instrumenting": attrs.bool(default = False),
+            "log_extractors": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),
+            "meta_internal_extra_params": META_INTERNAL_EXTRA_PARAMS,
+            "re_caps": RE_CAPS,
+            "re_use_case": RE_USE_CASE,
+            "record_video": attrs.bool(default = False, doc = "Record video of test run and collect it as TRA"),
+            "_android_emulators": attrs.option(
+                attrs.transition_dep(cfg = clear_platform_transition, providers = [LocalResourceInfo]),
+                default = None,
+                doc = """
+                If provided, local resource of "android_emulators" type will be required to run this test locally and this target will be used to manage it. If omitted, local resource of "android_emulators" type will be ignored even if requested by the test runner.
+            """,
+            ),
+            "_android_toolchain": toolchains_common.android(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_java_test_toolchain": toolchains_common.java_for_host_test(),
+            "_java_toolchain": toolchains_common.java_for_android(),
+            "_test_srcs": attrs.list(attrs.source(allow_directory = True), default = []),
+        }
+        | test_common.attributes()
+    ),
+)
+
+android_library = prelude_rule(
+    name = "android_library",
+    docs = """
+        An `android_library()` rule is used to define a set of Java files
+        that can be compiled together against the Android SDK. The main output of an
+         `android_library()` rule is a single JAR file containing all of the
+        compiled class files and resources.
+    """,
+    examples = """
+        An `android_library` rule used in concert with an
+         `android_resource()` rule.
+        This would be a common arrangement for a standard Android Library project
+        as defined by
+         [http://developer.android.com/tools/projects/index.html](http://developer.android.com/tools/projects/index.html)
+
+        ```
+        android_resource(
+          name = 'res',
+          res = 'res',
+          package = 'com.example',
+        )
+
+        android_library(
+          name = 'my_library',
+          srcs = glob(['src/**/*.java']),
+          deps = [
+            ':res',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "srcs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                The set of `.java` files to compile for this rule.
+            """,
+            ),
+            "resources": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Static files to include among the compiled `.class`
+                 files. These files can be loaded via [Class.getResource()](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)).
+
+                **Note:** Buck uses the `src_roots` property in
+                 `.buckconfig`
+                 to help determine where resources should be placed within the generated JAR file.
+            """,
+            ),
+        }
+        | android_common.manifest_arg()
+        | {
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Rules (usually other `android_library` rules)
+                 that are used to generate the classpath required to compile this
+                 `android_library`.
+            """,
+            ),
+            "extra_arguments": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                List of additional arguments to pass into the Java compiler. These
+                 arguments follow the ones specified in `.buckconfig`.
+            """,
+            ),
+            "extra_kotlinc_arguments": attrs.list(
+                attrs.arg(anon_target_compatible = True),
+                default = [],
+                doc = """
+                List of additional arguments to pass into the Kotlin compiler.
+            """,
+            ),
+            "source": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Specifies the version of Java (as a string) to interpret source
+                 files as.
+                 Overrides the value in "source\\_level" in the "java" section
+                 of `.buckconfig`.
+            """,
+            ),
+            "target": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Specifies the version of Java (as a string) for which to
+                 generate code.
+                 Overrides the value in "target\\_level" in the "java" section
+                 of `.buckconfig`.
+            """,
+            ),
+        }
+        | jvm_common.annotation_processors()
+        | jvm_common.exported_deps()
+        | jvm_common.provided_deps()
+        | jvm_common.exported_provided_deps()
+        | buck.provided_deps_query_arg()
+        | jvm_common.abi_generation_mode()
+        | jvm_common.source_only_abi_deps()
+        | jvm_common.required_for_source_only_abi()
+        | jvm_common.k2()
+        | jvm_common.kotlin_compiler_plugins()
+        | jvm_common.incremental()
+        | jvm_common.kotlincd_content_based_paths()
+        | jvm_common.enable_used_classes()
+        | jvm_common.classic_java_content_based_paths()
+        | android_common.patches_system_module_arg()
+        | {
+            "android_optional_jars": attrs.option(attrs.list(attrs.dep()), default = None),
+            "capabilities_registrations": attrs.option(attrs.list(attrs.any()), default = None),
+            "friend_paths": jvm_common.friend_paths_attr(),
+            "jar_postprocessor": attrs.option(attrs.exec_dep(), default = None),
+            "java_version": attrs.option(attrs.string(), default = None),
+            "language": attrs.option(attrs.enum(JvmLanguage), default = None),
+            "manifest_file": attrs.option(attrs.source(), default = None),
+            "maven_coords": attrs.option(attrs.string(), default = None),
+            "proguard_config": attrs.option(attrs.source(), default = None),
+            "remove_classes": attrs.list(
+                attrs.regex(),
+                default = [],
+                doc = """
+                List of classes to remove from the output jar. It only removes classes from the target's own
+                 sources, not from any of its dependencies.
+            """,
+            ),
+            "resources_root": attrs.option(attrs.string(), default = None),
+            "runtime_deps": attrs.list(attrs.dep(), default = []),
+            VALIDATION_DEPS_ATTR_NAME: attrs.set(attrs.dep(), sorted = True, default = []),
+            "_android_toolchain": toolchains_common.android(),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_dex_min_sdk_version": attrs.default_only(attrs.option(attrs.int(), default = dex_min_sdk_version())),
+            "_dex_toolchain": toolchains_common.dex(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_is_building_android_binary": is_building_android_binary_attr(),
+            "_java_toolchain": toolchains_common.java_for_android(),
+            "_kotlin_toolchain": toolchains_common.kotlin_for_android(),
+        }
+    )
+    | jvm_common.plugins()
+    | validation_common.attrs_validators_arg()
+    | validation_common.validation_specs_arg()
+    | buck.licenses_arg()
+    | buck.labels_arg()
+    | buck.contacts_arg(),
+)
+
+android_manifest = prelude_rule(
+    name = "android_manifest",
+    docs = """
+        An `android_manifest()` rule is used to generate an
+         [Android
+        Manifest](http://developer.android.com/guide/topics/manifest/manifest-intro.html) to be used by `android_binary()` and `android_aar()` rules. This
+        rule takes a skeleton manifest, and merges it with manifests found in any deps.
+    """,
+    examples = """
+        Here's an example of an `android_manifest()` that has no deps.
+
+        ```
+        android_manifest(
+          name = 'my-manifest',
+          skeleton = 'AndroidManifestSkeleton.xml',
+        )
+        ```
+
+         This is what `AndroidManifestSkeleton.xml` looks like.
+
+        ```
+        <?xml version="1.0" encoding="utf-8"?>
+        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
+                  package="com.example"
+                  android:versionCode="1"
+                  android:versionName="1.0">
+
+            <uses-sdk targetSdkVersion="19" minSdkVersion="17"/>
+            <application
+                android:label="@string/app_name"
+                android:icon="@drawable/ic_launcher">
+                <activity
+                    android:name="MyActivity"
+                    android:label="@string/app_name">
+                    <intent-filter>
+                        <action android:name="android.intent.action.MAIN"/>
+                        <category android:name="android.intent.category.LAUNCHER"/>
+                    </intent-filter>
+                </activity>
+            </application>
+        </manifest>
+        ```
+
+         You could also use a `genrule()` to generate the manifest file and reference the
+         `build target` in the `skeleton` argument.
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "skeleton": attrs.source(
+                doc = """
+                Either a `build target` or a path to a file representing the manifest that
+                 will be merged with any manifests associated with this rule's `deps`.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                A collection of dependencies that includes android\\_library rules. The manifest files of the
+                 `android_library()` rules will be filtered out to become dependent source files for
+                 the manifest.
+            """,
+            ),
+            "_android_toolchain": toolchains_common.android(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+android_prebuilt_aar = prelude_rule(
+    name = "android_prebuilt_aar",
+    docs = """
+        An `android_prebuilt_aar()` rule takes an `.aar` file and
+        makes it available as an Android dependency. As expected,
+        an `android_binary()` that transitively depends on
+        an `android_prebuilt_aar()` will include its contents in the generated APK.
+
+        See the [official Android documentation](https://developer.android.com/studio/projects/android-library#aar-contents) for details about the `.aar` format.
+    """,
+    examples = """
+        ```
+        android_prebuilt_aar(
+          name = 'play-services',
+          aar = 'play-services-4.0.30.aar',
+          source_jar = 'play-services-4.0.30-sources.jar',
+          javadoc_url = 'file:///opt/android-sdk/extras/google/google_play_services/docs/reference',
+        )
+
+        android_library(
+          name = 'lib',
+          # This Java code can compile against Play services and reference its resources.
+          srcs = glob(['*.java']),
+          deps = [ ':play-services' ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "aar": attrs.source(
+                doc = """
+                Path to the `.aar` file. This may also be a build target to
+                 a rule (such as a `genrule()`) whose output is
+                 an `.aar` file.
+            """,
+            ),
+            "source_jar": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                Path to a JAR file that contains the `.java` files to create
+                 the `.class` in the `aar`. This is frequently
+                 provided for debugging purposes.
+            """,
+            ),
+            "javadoc_url": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                URL to the Javadoc for the `.class` files in the
+                 `aar`.
+            """,
+            ),
+            "use_system_library_loader": attrs.bool(
+                default = False,
+                doc = """
+                If this `.aar` file contains native prebuilt `.so` libraries and the
+                 Java code uses these libraries via a call to `System.loadLibrary()`, then many
+                 optimizations—such as exopackage, compression, or asset packaging—may not be compatible with these prebuilt libs.
+                 Setting this parameter to `True` causes all of these optimizations to skip the prebuilt `.so`
+                 files originating from this `.aar` file. The `.so` files will always be packaged directly into
+                 the main `.apk`.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Dependencies of this prebuilt AAR. Listed deps are automatically exported to consumers of this rule
+                 and are used to resolve the transitive classpath for desugaring. Use this to specify libraries that
+                 the `.aar` depends on at compile time or runtime but are not bundled within the `.aar` itself.
+            """,
+            ),
+            "desugar_deps": attrs.list(attrs.dep(), default = []),
+            "dex_weight_factor": attrs.int(default = 1),
+            "for_primary_apk": attrs.bool(default = False),
+            "maven_coords": attrs.option(attrs.string(), default = None),
+            "required_for_source_only_abi": attrs.bool(default = True),
+            "_android_toolchain": toolchains_common.android(),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_dex_min_sdk_version": attrs.default_only(attrs.option(attrs.int(), default = dex_min_sdk_version())),
+            "_dex_toolchain": toolchains_common.dex(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_is_building_android_binary": attrs.default_only(attrs.bool(default = False)),
+            "_java_toolchain": toolchains_common.java_for_android(),
+        }
+        | jvm_common.classic_java_content_based_paths()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+android_resource = prelude_rule(
+    name = "android_resource",
+    docs = """
+        An `android_resource()` rule is used to bundle Android resources
+        that are traditionally stored in `res` and `assets` directories.
+
+        The output of an `android_resource()` is an `R.txt` file
+        generated via `aapt --output-text-symbols`.
+    """,
+    examples = """
+        Most of the time, an `android_resource` rule defines only `name`, `res`, and `package`. By convention,
+        such simple rules are often named `res`:
+
+        ```
+        android_resource(
+          name = 'res',
+          res = subdir_glob([('res', '**')]),
+          package = 'com.example',
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "res": attrs.option(
+                attrs.one_of(attrs.source(), attrs.dict(key = attrs.string(), value = attrs.source(), sorted = True)),
+                default = None,
+                doc = """
+                A dictionary mapping relative resource paths to either
+                 the resource files or the build targets that generate them.
+                 The `subdir_glob` function
+                 can be used to generate dictionaries based on a directory structure of files checked
+                 into the repository. Alternatively, this can be a path to a directory containing
+                 Android resources, although this option is deprecated and might be removed in the future.
+            """,
+            ),
+            "unused_resource_dep_validation_has_non_xml_resources": attrs.option(attrs.bool(), default = None),
+            "package": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Java package for the `R.java` file that will be generated for these
+                 resources.
+            """,
+            ),
+            "assets": attrs.option(
+                attrs.one_of(attrs.source(), attrs.dict(key = attrs.string(), value = attrs.source(), sorted = True)),
+                default = None,
+                doc = """
+                A dictionary mapping relative asset paths to either
+                 the asset files or the build targets that generate them.
+                 The `subdir_glob` function
+                 can be used to generate dictionaries based on a directory structure of files checked
+                 into the repository. Alternatively, this can be a path to a directory containing
+                 Android assets, although this option is deprecated and might be removed in the future.
+            """,
+            ),
+            "project_res": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                A directory containing resources to be used for project generation.
+                 If not provided, defaults to whatever the build uses.
+            """,
+            ),
+            "project_assets": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                A directory containing assets to be used for project generation.
+                 If not provided, defaults to whatever the build uses.
+            """,
+            ),
+        }
+        | android_common.manifest_arg()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+        | {
+            "allowlisted_locales": attrs.option(attrs.set(attrs.string(), sorted = False), default = None),
+            "assets": attrs.option(
+                attrs.one_of(attrs.source(allow_directory = True), attrs.dict(key = attrs.string(), value = attrs.source(), sorted = True)),
+                default = None,
+                doc = """
+                A dictionary mapping relative asset paths to either
+                 the asset files or the build targets that generate them.
+                 The `subdir_glob` function
+                 can be used to generate dictionaries based on a directory structure of files checked
+                 into the repository. Alternatively, this can be a path to a directory containing
+                 Android assets, although this option is deprecated and might be removed in the future.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Other `android_resource` rules to include via `-S` when
+                 running `aapt`.
+            """,
+            ),
+            "has_whitelisted_strings": attrs.bool(default = False),
+            "project_assets": attrs.option(
+                attrs.source(allow_directory = True),
+                default = None,
+                doc = """
+                A directory containing assets to be used for project generation.
+                 If not provided, defaults to whatever the build uses.
+            """,
+            ),
+            "project_res": attrs.option(
+                attrs.source(allow_directory = True),
+                default = None,
+                doc = """
+                A directory containing resources to be used for project generation.
+                 If not provided, defaults to whatever the build uses.
+            """,
+            ),
+            "res": attrs.option(
+                attrs.one_of(attrs.source(allow_directory = True), attrs.dict(key = attrs.string(), value = attrs.source(), sorted = True)),
+                default = None,
+                doc = """
+                A dictionary mapping relative resource paths to either
+                 the resource files or the build targets that generate them.
+                 The `subdir_glob` function
+                 can be used to generate dictionaries based on a directory structure of files checked
+                 into the repository. Alternatively, this can be a path to a directory containing
+                 Android resources, although this option is deprecated and might be removed in the future.
+            """,
+            ),
+            "_android_toolchain": toolchains_common.android(),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_is_building_android_binary": attrs.default_only(attrs.bool(default = False)),
+            "_java_toolchain": toolchains_common.java_for_android(),
+        }
+    ),
+)
+
+apk_genrule = prelude_rule(
+    name = "apk_genrule",
+    docs = """
+        An `apk_genrule()` rule is used to post-process an APK. What
+        separates an apk\\_genrule from a genrule is apk\\_genrules are known by BUCK to
+        produce APKs, so commands like `buck install` or
+         `buck uninstall` still work. Additionally,
+         `apk_genrule()` rules can be inputs to other
+         `apk_genrule()` rules.
+    """,
+    examples = """
+        Here is an example of a couple `apk_genrule()` open up an APK, do
+        some super signing, and then zipalign that APK again.
+
+        ```
+        # Building this rule will produce a file named messenger.apk.
+        android_binary(
+          name = 'messenger',
+          manifest = 'AndroidManifest.xml',
+          target = 'Google Inc.:Google APIs:16',
+          keystore = '//keystores:prod',
+          package_type = 'release',
+          proguard_config = 'proguard.cfg',
+          deps = [
+            ':res',
+            ':src',
+          ],
+        )
+
+        apk_genrule(
+          name = 'messenger_super_sign_unalign',
+          apk = ':messenger',
+          bash = '$(exe //java/com/facebook/sign:super_sign) --input $APK --output $OUT',
+          cmd_exe = '$(exe //java/com/facebook/sign:super_sign) --input %APK% --output %OUT%',
+          out = 'messenger_super_sign_unalign.apk',
+        )
+
+        apk_genrule(
+          name = 'messenger_super_sign',
+          apk = ':messenger_super_sign_unalign',
+          bash = '$ANDROID_HOME/tools/zipalign -f 4 $APK $OUT',
+          cmd_exe = '%ANDROID_HOME%\\tools\\zipalign -f 4 %APK% %OUT%',
+          out = 'messenger_super_sign.apk',
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "apk": attrs.option(
+                attrs.dep(),
+                default = None,
+                doc = """
+                The input `android_binary()` rule. The path to the APK can be
+                 accessed with the `$APK` shell variable. Only one of `apk` or
+                 `aab` can be provided.
+            """,
+            ),
+            "keystore": attrs.option(attrs.dep(), default = None),
+        }
+        | genrule_common.srcs_arg()
+        | genrule_common.cmd_arg()
+        | genrule_common.bash_arg()
+        | genrule_common.cmd_exe_arg()
+        | genrule_common.type_arg()
+        | genrule_common.weight_arg()
+        | {
+            "out": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The name of the output file or directory. The complete path to this
+                 argument is provided to the shell command through
+                 the `OUT` environment variable. Only one of `out`
+                 or `outs` may be present.
+
+                For an apk_genrule the output should be a '.apk' or '.aab' file.
+            """,
+            ),
+        }
+        | genrule_common.environment_expansion_separator()
+        | {
+            "aab": attrs.option(
+                attrs.dep(),
+                default = None,
+                doc = """
+                The input `android_binary()` rule. The path to the AAB can be
+                 accessed with the `$AAB` shell variable. Only one of `apk` or
+                 `aab` can be provided.
+            """,
+            ),
+            "cacheable": attrs.option(attrs.bool(), default = None),
+            "default_outs": attrs.option(attrs.set(attrs.string(), sorted = False), default = None),
+            "enable_sandbox": attrs.option(attrs.bool(), default = None),
+            "is_cacheable": attrs.bool(default = False),
+            "outs": attrs.option(attrs.dict(key = attrs.string(), value = attrs.set(attrs.string(), sorted = False), sorted = False), default = None),
+            "remote": attrs.option(attrs.bool(), default = None),
+            "type": attrs.string(default = "apk"),
+            "use_derived_apk": attrs.bool(default = False),
+            "_android_toolchain": toolchains_common.android(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_java_toolchain": toolchains_common.java_for_android(),
+        }
+        | genrule_attributes()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+gen_aidl = prelude_rule(
+    name = "gen_aidl",
+    docs = """
+        A `gen_aidl()` rule is used to generate `.java` files
+        from `.aidl` files.
+    """,
+    examples = """
+        ```
+        android_library(
+          name = 'lib',
+          srcs = glob(['**/*.java']) + [':aidl'],
+          manifest = '//res/org/opencv:manifest',
+          deps = [
+            '//res/org/opencv:res',
+          ],
+          visibility = [ 'PUBLIC' ],
+        )
+
+        gen_aidl(
+            name = 'aidl',
+            aidl = 'engine/OpenCVEngineInterface.aidl',
+            import_path = 'java/',
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "aidl": attrs.source(
+                doc = """
+                The path to an `.aidl` file to convert to a
+                 `.java` file.
+            """,
+            ),
+            "import_path": attrs.string(
+                default = "",
+                doc = """
+                The search path for import statements for the aidl command.
+                 (This is the `-I` argument when invoking aidl
+                 from the command line. For many apps it will be the base dir where all
+                 aidl files are, with project root as its parent,
+                 e.g. `app/src/main/aidl`.). This is the same as the path to the
+                 `aidl` file relative to what would be returned from `root`.
+            """,
+            ),
+            "import_paths": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                A list of additional import statements for the aidl command.
+                 (This appends an `-I` argument for each of the provided paths when
+                 invoking aidl from the command line.
+            """,
+            ),
+            "aidl_srcs": attrs.set(
+                attrs.source(),
+                sorted = True,
+                default = [],
+                doc = """
+                Path to `.aidl` files the target `aidl` file imports.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                A list of rules that must be built before this rule.
+            """,
+            ),
+            "_aidl_toolchain": toolchains_common.android_aidl(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_java_toolchain": toolchains_common.java_for_android(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+keystore = prelude_rule(
+    name = "keystore",
+    docs = """
+        A `keystore()` contains the data for a key pair
+        created by the `keytool` executable that comes
+        with the JDK. This is a required input for an `android_binary()` rule.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "store": attrs.source(
+                doc = """
+                The path to the file that contains the key.
+                 This is the path that was passed as the `-keystore` argument
+                 when you ran `keytool`.
+            """,
+            ),
+            "properties": attrs.source(
+                doc = """
+                The path to the `.properties` file that contains the following values:
+
+                ```
+                # The value that you passed as the argument to -alias
+                # when you ran keytool.
+                key.alias=my_alias
+
+                # The value that you entered in response to
+                # the "Enter keystore password:" prompt.
+                key.store.password=store_password
+
+                # The value that you entered in response to
+                # the "Enter key password for <my_alias>" prompt.
+                key.alias.password=alias_password
+                ```
+            """,
+            ),
+            "deps": attrs.list(attrs.dep(), default = []),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+prebuilt_native_library = prelude_rule(
+    name = "prebuilt_native_library",
+    docs = """
+        A `prebuilt_native_library()` rule is used to bundle native libraries
+        (i.e., `.so` files) for Android.
+    """,
+    examples = """
+        Most of the time, a `prebuilt_native_library` is private to the `android_library()` that uses it:
+
+        ```
+        prebuilt_native_library(
+          name = 'native_libs',
+          native_libs = 'libs',
+        )
+
+        android_library(
+          name = 'my_lib',
+          srcs = glob(['*.java']),
+          deps = [
+            ':native_libs',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "native_libs": attrs.source(
+                allow_directory = True,
+                doc = """
+                Path to a directory containing native libraries.
+                 This directory has subdirectories for different architectures,
+                 such as `armeabi` and `armeabi-v7a`.
+            """,
+            ),
+            "is_asset": attrs.bool(
+                default = False,
+                doc = """
+                Normally native shared objects end up in a directory in the root of the APK
+                 named `lib/`. If this parameter is set to `True`, then
+                 these objects are placed in `assets/lib/`. Placing shared objects in
+                 a non-standard location prevents Android from extracting them to the device's
+                 internal storage.
+            """,
+            ),
+            "has_wrap_script": attrs.bool(
+                default = False,
+                doc = """
+                When using an exopackage, if this
+                 parameter is set to `True`, then the libraries for this rule are
+                 included in the primary APK even if native libraries would otherwise not be
+                 placed in it. This is intended for a native library directory that contains a
+                 [wrap.sh](https://developer.android.com/ndk/guides/wrap-script)
+                 script, which must be included in the primary APK to take effect. Only one
+                 of `is_asset` and `has_wrap_script` can be set for a rule.
+            """,
+            ),
+            "deps": attrs.list(attrs.dep(), default = []),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+robolectric_test = prelude_rule(
+    name = "robolectric_test",
+    docs = """
+        A `robolectric_test()` rule is used to define a set of
+         `.java` files that contain tests to run via JUnit
+        with Robolectric test runner. It extends from `java_test()` rule.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.inject_test_env_arg()
+        | {
+            "android_optional_jars": attrs.option(attrs.list(attrs.dep()), default = None),
+            "compiled_resource_apks": attrs.list(attrs.source(), default = []),
+            "cxx_library_allowlist": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                List of cxx_library targets to build, if use_cxx_libraries is true.
+                This can be useful if some dependencies are Android-only and won't build for the test host platform.
+            """,
+            ),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "discover_all_test_classes": attrs.bool(default = False),
+            "env": attrs.dict(key = attrs.string(), value = attrs.arg(), sorted = False, default = {}),
+            "exported_deps": attrs.list(attrs.dep(), default = []),
+            "exported_provided_deps": attrs.list(attrs.dep(), default = []),
+            "extra_arguments": attrs.list(attrs.string(), default = []),
+            "extra_kotlinc_arguments": attrs.list(
+                attrs.arg(anon_target_compatible = True),
+                default = [],
+                doc = """
+                List of additional arguments to pass into the Kotlin compiler.
+            """,
+            ),
+            "friend_paths": jvm_common.friend_paths_attr(),
+            "jar_postprocessor": attrs.option(attrs.exec_dep(), default = None),
+            "java": attrs.option(attrs.dep(), default = None),
+            "java_agents": attrs.list(attrs.source(), default = []),
+            "java_version": attrs.option(attrs.string(), default = None),
+            "language": attrs.option(attrs.enum(JvmLanguage), default = None),
+            "locales_for_binary_resources": attrs.list(attrs.string(), default = []),
+            "manifest_entries": attrs.dict(key = attrs.string(), value = attrs.any(), default = {}),
+            "manifest_file": attrs.option(attrs.source(), default = None),
+            "manifest_skeleton": attrs.option(attrs.source(), default = None),
+            "maven_coords": attrs.option(attrs.string(), default = None),
+            "preferred_density_for_binary_resources": attrs.option(attrs.string(), default = None),
+            "proguard_config": attrs.option(attrs.source(), default = None),
+            "provided_deps": attrs.list(attrs.dep(), default = []),
+            "provided_deps_query": attrs.option(attrs.query(), default = None),
+            "remove_classes": attrs.list(attrs.regex(), default = []),
+            "required_for_source_only_abi": attrs.bool(default = False),
+            "resource_stable_ids": attrs.option(attrs.source(), default = None),
+            "resources": attrs.list(attrs.source(), default = []),
+            "resources_root": attrs.option(attrs.string(), default = None),
+            "robolectric_runtime_dependencies": attrs.list(attrs.source(), default = []),
+            "robolectric_runtime_dependency": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                Robolectric only runs in offline mode with buck. Specify the relative
+                 directory containing all the jars Robolectric uses at runtime.
+            """,
+            ),
+            "run_test_separately": attrs.bool(default = False),
+            "runtime_deps": attrs.list(attrs.dep(), default = []),
+            "source": attrs.option(attrs.string(), default = None),
+            "source_only_abi_deps": attrs.list(attrs.dep(), default = []),
+            "srcs": attrs.list(attrs.source(), default = []),
+            "supports_test_execution_caching": attrs.bool(default = False),
+            "target": attrs.option(attrs.string(), default = None),
+            "test_case_timeout_ms": attrs.option(attrs.int(), default = None),
+            "test_class_names_file": attrs.option(attrs.source(), default = None),
+            "test_rule_timeout_ms": attrs.option(attrs.int(), default = None),
+            "test_type": attrs.option(attrs.enum(TestType), default = None),
+            "unbundled_resources_root": attrs.option(attrs.source(allow_directory = True), default = None),
+            "use_cxx_libraries": attrs.option(attrs.bool(), default = None),
+            "vm_args": attrs.list(attrs.arg(), default = []),
+            "_android_toolchain": toolchains_common.android(),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_is_building_android_binary": attrs.default_only(attrs.bool(default = False)),
+            "_java_test_toolchain": toolchains_common.java_test(),
+            "_java_toolchain": toolchains_common.java_for_host_test(),
+            "_kotlin_toolchain": toolchains_common.kotlin(),
+        }
+        | android_common.manifest_arg()
+        | android_common.patches_system_module_arg()
+        | jvm_common.abi_generation_mode()
+        | jvm_common.annotation_processors()
+        | jvm_common.k2()
+        | jvm_common.incremental()
+        | jvm_common.kotlincd_content_based_paths()
+        | jvm_common.plugins()
+        | jvm_common.kotlin_compiler_plugins()
+        | jvm_common.enable_used_classes()
+        | jvm_common.classic_java_content_based_paths()
+        | re_test_common.test_args()
+        | test_common.attributes()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+android_rules = struct(
+    android_aar = android_aar,
+    android_app_modularity = android_app_modularity,
+    android_binary = android_binary,
+    android_build_config = android_build_config,
+    android_bundle = android_bundle,
+    android_instrumentation_apk = android_instrumentation_apk,
+    android_instrumentation_test = android_instrumentation_test,
+    android_library = android_library,
+    android_manifest = android_manifest,
+    android_prebuilt_aar = android_prebuilt_aar,
+    android_resource = android_resource,
+    apk_genrule = apk_genrule,
+    gen_aidl = gen_aidl,
+    keystore = keystore,
+    prebuilt_native_library = prebuilt_native_library,
+    robolectric_test = robolectric_test,
+)
diff --git a/buck2/prelude/decls/common.bzl b/buck2/prelude/decls/common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/common.bzl
@@ -0,0 +1,261 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", _RuntimeDependencyHandling = "RuntimeDependencyHandling")
+
+def validate_uri(_s):
+    return True
+
+prelude_rule = record(
+    name = field(str),
+    docs = field([str, None], None),
+    examples = field([str, None], None),
+    further = field([str, None], None),
+    attrs = field(dict[str, Attr]),
+    impl = field([typing.Callable, None], None),
+    uses_plugins = field([list[plugins.PluginKind], None], None),
+    supports_incoming_transition = field([bool, None], None),
+    is_toolchain_rule = field([bool, None], None),
+    # TODO(mgd): should be `transition | None`, but `transition` does not work as type.
+    cfg = field(typing.Any | None, None),
+)
+
+AbiGenerationMode = ["class", "source", "source_only", "none"]
+
+CxxRuntimeType = ["dynamic", "static"]
+
+CxxSourceType = [
+    "c",
+    "cxx",
+    "cxx_thinlink",
+    "objc",
+    "objcxx",
+    "cuda",
+    "hip",
+    "swift",
+    "c_cpp_output",
+    "cxx_cpp_output",
+    "objc_cpp_output",
+    "objcxx_cpp_output",
+    "cuda_cpp_output",
+    "hip_cpp_output",
+    "assembler_with_cpp",
+    "assembler",
+    "asm_with_cpp",
+    "asm",
+    "pcm",
+]
+
+DefaultDepsMode = ["none", "deps", "exported_deps"]
+
+HeadersAsRawHeadersMode = ["required", "preferred", "disabled"]
+
+IncludeType = ["local", "system", "raw"]
+
+LinkableDepType = ["static", "static_pic", "shared"]
+
+OnDuplicateEntry = ["fail", "overwrite", "append"]
+
+RawHeadersAsHeadersMode = ["enabled", "disabled"]
+
+TestType = ["junit", "junit5", "testng"]
+
+UnusedDependenciesAction = ["unknown", "fail", "warn", "ignore", "unrecognized"]
+
+RuntimeDependencyHandling = _RuntimeDependencyHandling.values()
+
+def _name_arg(name_type):
+    return {
+        "name": name_type,
+    }
+
+def _deps_query_arg():
+    return {
+        "deps_query": attrs.option(
+            attrs.query(),
+            default = None,
+            doc = """
+    Status: **experimental/unstable**.
+     The deps query takes a query string that accepts the following query
+     functions, and appends the output of the query to the declared deps:
+
+    * `attrfilter`
+    * `deps`
+    * `except`
+    * `intersect`
+    * `filter`
+    * `kind`
+    * `set`
+    * `union`
+
+    Some example queries:
+
+    ```
+      "filter({name_regex}, deps('//foo:foo'))".format(name_regex='//.*')
+      "attrfilter(annotation_processors, com.foo.Processor, deps('//foo:foo'))"
+      "deps('//foo:foo', 1)"
+    ```
+""",
+        ),
+    }
+
+def _provided_deps_query_arg():
+    return {
+        "provided_deps_query": attrs.option(
+            attrs.query(),
+            default = None,
+            doc = """
+    Status: **experimental/unstable**.
+     The provided deps query functions in the same way as the deps query, but the
+     results of the query are appended to the declared provided deps.
+""",
+        ),
+    }
+
+def _labels_arg():
+    return {
+        "labels": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    Set of arbitrary strings which allow you to annotate a [build rule](https://buck2.build/docs/concepts/build_rule/) with tags
+    that can be searched for over an entire dependency tree using `buck query()`.
+""",
+        ),
+    }
+
+def _visibility_arg(visibility_type):
+    return {
+        "visibility": visibility_type,
+    }
+
+def _tests_arg(tests_type):
+    return {
+        "tests": tests_type,
+    }
+
+def _tests_apple_arg(tests_type):
+    return {
+        "tests": tests_type,
+    }
+
+def _test_label_arg():
+    return {
+        "labels": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    A list of labels to be applied to these tests. These labels are
+     arbitrary text strings and have no meaning within buck itself. They
+     can, however, have meaning for you as a test author
+     (e.g., `smoke` or `fast`). A label can be
+     used to filter or include a specific test rule
+     when executing `buck test`
+""",
+        ),
+    }
+
+def _run_test_separately_arg(run_test_separately_type):
+    return {
+        "run_test_separately": run_test_separately_type,
+    }
+
+def _test_rule_timeout_ms():
+    return {
+        "test_rule_timeout_ms": attrs.option(
+            attrs.int(),
+            default = None,
+            doc = """
+    If set specifies the maximum amount of time (in milliseconds) in which all of the tests in this
+     rule should complete. This overrides the default `rule_timeout` if any has been
+     specified in `.buckconfig`
+    .
+""",
+        ),
+    }
+
+def _target_os_type_arg() -> Attr:
+    return attrs.default_only(attrs.dep(default = "prelude//os_lookup/targets:os_lookup"))
+
+def _exec_os_type_arg() -> Attr:
+    return attrs.default_only(attrs.exec_dep(default = "prelude//os_lookup/targets:os_lookup"))
+
+def _allow_cache_upload_arg():
+    return {
+        "allow_cache_upload": attrs.option(
+            attrs.bool(),
+            default = None,
+            doc = """
+            Whether to allow uploading the output of this rule to be uploaded
+            to cache when the action is executed locally if the configuration
+            allows (i.e. there is a cache configured and the client has
+            permission to write to it).
+            """,
+        ),
+    }
+
+def _inject_test_env_arg():
+    return {
+        # NOTE: We make this a `dep` not an `exec_dep` even though we'll execute
+        # it, because it needs to execute in the same platform as the test itself
+        # (we run tests in the target platform not the exec platform, since the
+        # goal is to test the code that is being built!).
+        "_inject_test_env": attrs.default_only(attrs.dep(default = "prelude//test/tools:inject_test_env")),
+    }
+
+def _licenses_arg():
+    return {
+        "licenses": attrs.list(
+            attrs.source(),
+            default = [],
+            doc = """
+            Set of license files for this library. To get the list of license files for a given build rule and
+            all of its dependencies, you can use [buck query](https://buck2.build/docs/users/commands/query/)
+        """,
+        ),
+    }
+
+def _contacts_arg():
+    return {
+        "contacts": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+            A list of organizational contacts for this rule. These could be individuals who you would contact
+            in the event of a failure or other issue with the rule.
+
+            ```
+            contacts = [ 'Joe Sixpack', 'Erika Mustermann' ]
+            ```
+        """,
+        ),
+    }
+
+buck = struct(
+    name_arg = _name_arg,
+    deps_query_arg = _deps_query_arg,
+    exec_os_type_arg = _exec_os_type_arg,
+    provided_deps_query_arg = _provided_deps_query_arg,
+    labels_arg = _labels_arg,
+    visibility_arg = _visibility_arg,
+    tests_arg = _tests_arg,
+    tests_apple_arg = _tests_apple_arg,
+    test_label_arg = _test_label_arg,
+    run_test_separately_arg = _run_test_separately_arg,
+    test_rule_timeout_ms = _test_rule_timeout_ms,
+    target_os_type_arg = _target_os_type_arg,
+    allow_cache_upload_arg = _allow_cache_upload_arg,
+    inject_test_env_arg = _inject_test_env_arg,
+    licenses_arg = _licenses_arg,
+    contacts_arg = _contacts_arg,
+)
diff --git a/buck2/prelude/decls/core_rules.bzl b/buck2/prelude/decls/core_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/core_rules.bzl
@@ -0,0 +1,1736 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//cfg/exec_platform:marker.bzl", "get_exec_platform_marker")
+load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")
+load(":common.bzl", "OnDuplicateEntry", "buck", "prelude_rule", "validate_uri")
+load(":genrule_common.bzl", "genrule_common")
+load(":remote_common.bzl", "remote_common")
+
+ExportFileDescriptionMode = ["reference", "copy"]
+
+PlatformExePlatform = ["linux", "macos", "windows"]
+
+RemoteFileType = ["data", "executable", "exploded_zip"]
+
+TargetCpuType = ["arm", "armv7", "arm64", "arm64e", "x86", "x86_64", "mips", "riscv64"]
+
+def _has_content_based_path_attr():
+    return {
+        "has_content_based_path": attrs.bool(
+            default = select({
+                "DEFAULT": False,
+                # @oss-disable[end= ]: "config//os/constraints:android": True,
+                # @oss-disable[end= ]: "config//runtime/constraints:android-host-test": True,
+                # @oss-disable[end= ]: "config//runtime/constraints:android-unit-test": True,
+            })
+        ),
+    }
+
+def _optional_has_content_based_path_attr():
+    return {
+        "has_content_based_path": attrs.option(
+            attrs.bool(),
+            default = select({
+                "DEFAULT": None,
+                # @oss-disable[end= ]: "config//os/constraints:android": True,
+                # @oss-disable[end= ]: "config//runtime/constraints:android-host-test": True,
+                # @oss-disable[end= ]: "config//runtime/constraints:android-unit-test": True,
+            }),
+        ),
+    }
+
+alias = prelude_rule(
+    name = "alias",
+    docs = "",
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "actual": attrs.option(attrs.dep(pulls_and_pushes_plugins = plugins.All)),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+command_alias = prelude_rule(
+    name = "command_alias",
+    docs = """
+        The `command_alias` rule enables you to wrap build
+         rules that create binaries and to pre-apply command-line
+         arguments and environment variables.
+
+         Example uses include running a command written in a scripting
+         language with a specific interpreter, and transparently wrapping
+         sub-commands of a binary.
+
+         You can reference a `command_alias` target in
+         the `cmd` parameter of a `genrule()` by
+         using the `exe` macro:
+
+        ```
+        $(exe //path/to:target)
+        ```
+    """,
+    examples = """
+        ```
+        # Combining an interpreter and a script
+
+        cxx_binary(
+            name = "node-js",
+            srcs = [
+                # ...
+            ],
+            headers = [
+                # ...
+            ],
+        )
+
+        export_file(
+            name = "scripts"
+        )
+
+        command_alias(
+            name = "server",
+            exe = ":node-js",
+            args = [
+                "$(location :scripts)/start-server.js",
+            ],
+        )
+        ```
+
+        ```
+        # Exposing sub commands
+
+        export_file(
+            name = "yarn",
+            src = "yarn.sh",
+        )
+
+        command_alias(
+            name = "add",
+            exe = ":yarn",
+            args = ["add"],
+        )
+
+        command_alias(
+            name = "install",
+            exe = ":yarn",
+            args = ["install"],
+        )
+
+        command_alias(
+            name = "run",
+            exe = ":yarn",
+            args = ["run"],
+        )
+        ```
+
+        ```
+        # Platform specific commands
+
+        export_file(
+            name = "node-windows",
+            src = "windows/node.exe",
+        )
+
+        export_file(
+            name = "node-linux",
+            src = "linux/node",
+        )
+
+        export_file(
+            name = "node-macos",
+            src = "macos/node",
+        )
+
+        command_alias(
+            name = "node",
+            platform_exe = {
+                "windows": ":node-windows",
+                "linux": ":node-linux",
+                "macos": ":node-macos",
+            },
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            # Match `dep` before `source` so that we can support extracting the
+            # `RunInfo` provider of it, if one exists.
+            "exe": attrs.option(
+                attrs.one_of(attrs.dep(), attrs.source()),
+                default = None,
+                doc = """
+                A `build target` for a rule that outputs
+                 an executable, such as an `sh_binary()`,
+                 or an executable source file.
+            """,
+            ),
+            "platform_exe": attrs.dict(
+                key = attrs.enum(PlatformExePlatform),
+                value = attrs.dep(),
+                sorted = False,
+                default = {},
+                doc = """
+                A mapping from platforms to `build target`.
+                 enables you to override `exe` per host platform.
+
+                If present, `exe` will be used as a fallback on host platforms that are not
+                 specified in `platform_exe`.
+
+                It is possible to omit `exe` when providing `platform_exe`.
+                 In that case, the build will fail if the command is invoked on a platform not specified in
+                 the mapping.
+
+                Valid platforms are all values of the [`Platform` enum](https://dev.buck.build/javadoc/com/facebook/buck/util/environment/Platform.html) :
+
+                * `FREEBSD`
+                * `LINUX`
+                * `MACOS`
+                * `WINDOWS`
+            """,
+            ),
+            "args": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                A string of arguments that is passed to the executable specified by
+                 `exe` at startup. These arguments support a subset of
+                 Buck's `string parameter macros`
+                . Only the
+                 `$(location ...)` and `$(exe ...)` macros are supported currently.
+            """,
+            ),
+            "env": attrs.dict(
+                key = attrs.string(),
+                value = attrs.arg(),
+                sorted = False,
+                default = {},
+                doc = """
+                A map of environment variables that will be passed to the executable represented
+                 by `exe` on startup. Environment variables support the same macros as arguments.
+            """,
+            ),
+            "executable_name": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                If provided, use this name for the trampoline script (with an extension added if
+                 required by the platform).
+            """,
+            ),
+            "resources": attrs.list(attrs.source(), default = []),
+            "run_using_single_arg": attrs.bool(
+                default = False,
+                doc = """
+                Ensure that the command alias can be run as a single argument (instead of
+                $(exe) or RunInfo potentially expanding to multiple arguments).
+            """,
+            ),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_target_os_type": buck.target_os_type_arg(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+config_setting = prelude_rule(
+    name = "config_setting",
+    docs = """
+        `config_setting()` accepts a list of `constraint_values` and a list of values
+        (buckconfig keys + expected values) and matches if all of those match.
+
+        This is implemented as forming a single `ConfigurationInfo` from the union of the
+        referenced values and the config keys.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "constraint_values": attrs.list(attrs.configuration_label(), default = []),
+            "values": attrs.dict(
+                key = attrs.string(),
+                value = attrs.string(),
+                sorted = False,
+                default = {},
+                doc = """
+                    Buckconfig key -> expected value, evaluated from the target's cell (like `read_config`).
+                    A given `section.key` may appear in either `values` or `root_values`, but not both.
+                """,
+            ),
+            "root_values": attrs.dict(
+                key = attrs.string(),
+                value = attrs.string(),
+                sorted = False,
+                default = {},
+                doc = """
+                    Buckconfig key -> expected value, evaluated from the root cell (like `read_root_config`).
+                    A given `section.key` may appear in either `values` or `root_values`, but not both.
+                """,
+            ),
+        }
+    ),
+)
+
+configuration_alias = prelude_rule(
+    name = "configuration_alias",
+    docs = """
+        `configuration_alias()` acts like `alias()` but for configuration targets.
+
+        The `configuration_alias` itself is a configuration rule and the `actual` attribute
+        is expected to be a target defined by a configuration rule (such as `constraint`,
+        `constraint_setting`, `constraint_value`, `config_setting`, or `platform`).
+
+        Unlike regular `alias()`, `configuration_alias()` can be used wherever configuration
+        targets are expected, such as in `select()` keys or `platform.constraint_values`.
+
+        This rule is particularly useful for creating backwards-compatible aliases to constraint
+        values defined using the unified `constraint()` rule, where values are referenced via
+        subtargets (e.g., `:os[linux]`).
+    """,
+    examples = """
+        ```
+        # Define a constraint with multiple values using the unified constraint rule
+        constraint(
+            name = "os",
+            values = ["linux", "macos", "windows", "none"],
+            default = "none",
+        )
+
+        configuration_alias(
+            name = "linux",
+            actual = ":os[linux]",
+        )
+
+        configuration_alias(
+            name = "macos",
+            actual = ":os[macos]",
+        )
+
+        # The alias can be used in platform definitions
+        platform(
+            name = "linux_platform",
+            constraint_values = [
+                ":linux",  # Using the alias instead of :os[linux]
+            ],
+        )
+
+        # The alias can be used in select() expressions
+        genrule(
+            name = "my_rule",
+            cmd = select({
+                ":linux": "echo linux",
+                ":macos": "echo macos",
+                ":os[none]": "echo other",  # Can also use subtarget directly
+            }),
+            out = "out.txt",
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "actual": attrs.dep(
+                pulls_and_pushes_plugins = plugins.All,
+                doc = """
+                The target to alias. This should be a target defined by a configuration rule
+                such as `constraint`, `constraint_setting`, `constraint_value`, `config_setting`,
+                or `platform`.
+            """,
+            ),
+        }
+    ),
+)
+
+configured_alias = prelude_rule(
+    name = "configured_alias",
+    docs = "",
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            # The 'actual' attribute of configured_alias is a configured_label, which is
+            # currently unimplemented. Map it to dep so we can simply forward the providers.
+            # TODO(nga): "actual" attribute exists here only to display it in query,
+            #   actual `actual` attribute used in rule implementation is named `configured_actual`.
+            #   Logically this should be `attrs.configuration_label`, but `configuration_label`
+            #   is currently an alias for `attrs.dep`, which makes non-transitioned dependency
+            #   also a dependency along with transitioned dependency. (See D40255132).
+            "actual": attrs.label(),
+            "configured_actual": attrs.option(attrs.configured_dep(), default = None),
+            "fallback_actual": attrs.option(attrs.dep(), default = None),
+            # We use a separate field instead of re-purposing `actual`, as we want
+            # to keep output format compatibility with v1.
+            # If `configured_actual` is `None`, fallback to this unconfigured dep.
+            "platform": attrs.option(attrs.configuration_label(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+constraint_setting = prelude_rule(
+    name = "constraint_setting",
+    docs = "Declares the existence of a constraint, whose values are defined using `constraint_value()`. Consider using the newer `constraint()` instead.",
+    examples = None,
+    further = None,
+    attrs = (
+        {
+            "execution_modifier": attrs.bool(default = False),
+        }
+    ),
+)
+
+constraint_value = prelude_rule(
+    name = "constraint_value",
+    docs = "Declares a specific value of a `constraint_setting`. Consider using the newer `constraint()` instead.",
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "constraint_setting": attrs.configuration_label(
+                doc = "The constraint setting this value is attached to.",
+            ),
+            # Dependency on the exec platform marker constraint.
+            # Modifiers with execution_modifier=False will be wrapped in a conditional modifier
+            # that skips them on exec platforms.
+            "_exec_platform_marker": attrs.dep(providers = [ConfigurationInfo], default = get_exec_platform_marker()),
+        }
+    ),
+)
+
+constraint = prelude_rule(
+    name = "constraint",
+    docs = """
+        Unified constraint rule that defines both a constraint setting and its possible values.
+        Values are exposed as subtargets, e.g., `cfg//:os[linux]`.
+    """,
+    examples = """
+        ```
+        constraint(
+            name = "os",
+            values = ["linux", "macos", "windows"],
+            default = "linux",
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "values": attrs.list(
+                attrs.string(),
+                doc = "List of value names.",
+            ),
+            "default": attrs.string(
+                doc = "Default value (must be one of the `values`).",
+            ),
+            "allow_trivial_constraint": attrs.bool(
+                default = False,
+                doc = """
+                    If True, allow this constraint to declare only one value.
+                    Intended for constraints that have just a default value most of the time and may
+                    temporarily gain additional values (e.g., versioned packages that pick up an extra
+                    value during an upgrade and drop it once the upgrade lands).
+                    Default is False, which requires at least two values.
+                """,
+            ),
+            "aliases": attrs.dict(
+                attrs.string(),
+                attrs.string(),
+                default = {},
+                doc = """
+                    Optional mapping of alias name -> declared value. Each alias becomes an additional
+                    subtarget that resolves to the same providers as the underlying value, letting users
+                    refer to a constraint value by a stable shorthand (e.g. `:version[1.4]`) that maps to
+                    a brittle underlying value (e.g. `1.4.5.xxx.67890`). Alias names must not collide with
+                    declared values or reserved keywords, and alias values must appear in `values`.
+                """,
+            ),
+            "execution_modifier": attrs.bool(default = False),
+            # Dependency on the exec platform marker constraint.
+            # Modifiers with execution_modifier=False will be wrapped in a conditional modifier
+            # that skips them on exec platforms.
+            "_exec_platform_marker": attrs.dep(providers = [ConfigurationInfo], default = get_exec_platform_marker()),
+        }
+    ),
+)
+
+exec_platform_marker_constraint = prelude_rule(
+    name = "exec_platform_marker_constraint",
+    docs = """
+        Special constraint rule for defining execution platform markers.
+        This rule has the same semantics as `constraint()` but exists to avoid
+        circular dependency issues when other constraint/constraint_value rules
+        need to depend on the exec platform marker.
+        Should only be defined once in a repo.
+    """,
+    examples = """
+        exec_platform_marker_constraint(
+            name = "is_exec_platform",
+            values = ["true", "false"],
+            default = "false",
+        )
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "values": attrs.list(
+                attrs.string(),
+                doc = "List of value names.",
+            ),
+            "default": attrs.string(
+                doc = "Default value (must be one of the `values`).",
+            ),
+            "allow_trivial_constraint": attrs.bool(default = False),
+            "aliases": attrs.dict(attrs.string(), attrs.string(), default = {}),
+        }
+    ),
+)
+
+export_file = prelude_rule(
+    name = "export_file",
+    docs = """
+        An `export_file()` takes a single file or folder and exposes it so other rules can
+         use it.
+    """,
+    examples = """
+        The best way to see how the `export_file()` rule works is with some examples. The
+         common case is:
+
+        ```
+        export_file(
+          name = 'example.html',
+        )
+
+        # This is equivalent to
+
+        export_file(
+          name = 'example.html',
+          src = 'example.html',
+          out = 'example.html',
+        )
+        ```
+
+         It is sometimes useful to refer to the file not by its path, but by a more logical name:
+
+        ```
+        export_file(
+          name = 'example',
+          src = 'example.html',
+        )
+
+        # This is equivalent to
+
+        export_file(
+          name = 'example',
+          src = 'example.html',
+          out = 'example.html',
+        )
+        ```
+
+         Finally, there are occasions where you want to export a file more than once but want to copy it to
+         a different name for each output:
+
+        ```
+        export_file(
+          name = 'runner',
+          src = 'RemoteRunner.html',
+        )
+
+        export_file(
+          name = 'runner_hta',
+          src = 'RemoteRunner.html',
+          out = 'RemoteRunner.hta',
+        )
+        ```
+
+         Using the `export_file()` rule is also simple:
+
+        ```
+        export_file(
+          name = 'example',
+          src = 'example.html',
+        )
+
+        genrule(
+          name = 'demo',
+          out = 'result.html',
+          cmd = 'cp $(location :example) $OUT',
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "src": attrs.option(
+                attrs.source(allow_directory = True),
+                default = None,
+                doc = """
+                The path to the file that should be exported.
+            """,
+            ),
+            "out": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The name which the file will be called if another rule depends on it instead of the name it
+                 already has.
+            """,
+            ),
+            "executable_bit_override": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Override the executable bit of the file. If not set, the executable bit is preserved.
+            """,
+            ),
+            "mode": attrs.option(
+                attrs.enum(ExportFileDescriptionMode),
+                default = None,
+                doc = """
+                How files are referenced internally in buck.
+                 If set to 'copy', then a full copy will be made into the new location in buck-out.
+                 If set to 'reference', the original file will be used by internal build rules in-place.
+                 However, this mode does not work across repositories or if the 'out' property is set.
+                 For read-only operations, 'reference' can be more performant.
+            """,
+            ),
+        }
+        | _has_content_based_path_attr()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+    cfg = constraint_overrides.transition,
+)
+
+external_test_runner = prelude_rule(
+    name = "external_test_runner",
+    docs = "",
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "binary": attrs.dep(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+filegroup = prelude_rule(
+    name = "filegroup",
+    docs = """
+        This rule provides access to a set of files.
+
+         Files are accessible to `genrule()`s by using their relative path
+         after a `$(location)` string parameter macro.
+
+         Other rules may handle `filegroup()` rules natively for attributes
+         such as resources.
+    """,
+    examples = """
+        In this example a target exports `.xml` files from all subdirectories
+         in `resources`.
+
+        ```
+        filegroup(
+          name = 'example',
+          srcs = glob(['resources/**/*.xml']),
+        )
+
+        genrule(
+          name = 'process_xml',
+          out = 'processed.xml',
+          cmd = '$(exe //example:tool) -in $(location :example)/resources/file.xml > $OUT',
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "srcs": attrs.named_set(
+                attrs.source(allow_directory = True),
+                sorted = False,
+                default = [],
+                doc = """
+                The set of files to include in this rule.
+            """,
+            ),
+            "copy": attrs.bool(default = True),
+            "executable_bit_override": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Override the executable bit for every file in the filegroup. If not set, the executable bits are preserved.
+                Cannot be used if `copy` is set to false.
+            """,
+            ),
+            "out": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The name of the output directory. Defaults to the rule's name.
+            """,
+            ),
+        }
+        | _has_content_based_path_attr()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+    cfg = constraint_overrides.transition,
+)
+
+genrule = prelude_rule(
+    name = "genrule",
+    docs = """
+        A `genrule()` is used to generate files from a shell
+         command. It must produce a single output file or folder.
+    """,
+    examples = """
+        This genrule() uses a Python script to derive a new
+         `AndroidManifest.xml` from an
+         `AndroidManifest.xml` in the source tree.
+        Note you don't need to prepend execution commands with
+         `python`: Buck knows how to execute different
+        kinds of binaries using `$(exe)` command.
+
+        ```
+        genrule(
+          name = 'generate_manifest',
+          srcs = [
+            'AndroidManifest.xml',
+          ],
+          bash = '$(exe //python/android:basic_to_full) ' \
+              '$SRCDIR/AndroidManifest.xml > $OUT',
+          cmd_exe = '$(exe //python/android:basic_to_full) ' \
+              '%SRCDIR%\\AndroidManifest.xml > %OUT%',
+          out = 'AndroidManifest.xml',
+        )
+        ```
+
+        ```
+        genrule(
+          name = 'generate_manifest_with_named_outputs',
+          srcs = [
+            'AndroidManifest.xml',
+          ],
+          bash = '$(exe //python/android:basic_to_full) ' \
+              '$SRCDIR/AndroidManifest.xml > $OUT/AndroidManifest.xml',
+          cmd_exe = '$(exe //python/android:basic_to_full) ' \
+              '%SRCDIR%\\AndroidManifest.xml > %OUT%\\AndroidManifest.xml',
+          outs =  {
+            "manifest": [ "AndroidManifest.xml" ],
+          },
+          default_outs = [ "AndroidManifest.xml" ],
+        )
+        ```
+
+        For named outputs, build with any of the following:
+
+        ```
+          buck build //:generate_manifest_with_named_outputs
+        ```
+
+        ```
+          buck build //:generate_manifest_with_named_outputs[manifest]
+        ```
+
+        Consume in `srcs` with:
+
+        ```
+        export_file(
+            name = "magic1",
+            src = ":generate_manifest_with_named_outputs",
+            out = "some_dir_to_copy_to/AndroidManifest.xml",
+        )
+        ```
+
+        ```
+        export_file(
+            name = "magic2",
+            src = ":generate_manifest_with_named_outputs[manifest]",
+            out = "some_dir_to_copy_to/AndroidManifest.xml",
+        )
+        ```
+
+        Note that `magic1` consumes `generate_manifest_with_named_outputs`'s default
+        output. `magic2` consumes `generate_manifest_with_named_outputs`'s named
+        output "manifest," which happen to be pointing to the same output as the default output in this
+        case, but they do not have to point to the same output.
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        genrule_common.srcs_arg()
+        | genrule_common.cmd_arg()
+        | genrule_common.bash_arg()
+        | genrule_common.cmd_exe_arg()
+        | genrule_common.type_arg()
+        | genrule_common.weight_arg()
+        | {
+            "default_outs": attrs.option(
+                attrs.set(attrs.string(), sorted = False),
+                default = None,
+                doc = """
+                Default output which must be present if the `outs` arg is present. Otherwise does not apply.
+
+                 If a rule with `outs` is consumed without an output label, the default output is returned. The
+                 default output does not need to be present in any of the named outputs defined in `outs`.
+
+                 Note that a maximum of one value may be present in this list. For example:
+
+                ```
+                default_outs = [ "output_one", ]
+                ```
+                is valid, whereas
+
+                ```
+                default_outs = [ "output_one", "output_two", ]
+                ```
+                is not.
+            """,
+            ),
+            "executable_outs": attrs.option(
+                attrs.set(attrs.string(), sorted = False),
+                default = None,
+                doc = """
+                Only valid if the `outs` arg is present. Dictates which of those named outputs are marked as
+                executable.
+            """,
+            ),
+            "out": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The name of the output file or directory. The complete path to this
+                 argument is provided to the shell command through
+                 the `OUT` environment variable. Only one of `out`
+                 or `outs` may be present.
+            """,
+            ),
+            "outs": attrs.option(
+                attrs.dict(key = attrs.string(), value = attrs.set(attrs.string(), sorted = False), sorted = False),
+                default = None,
+                doc = """
+                Mapping defining `named outputs`
+                  to output paths relative to the rule's output directory. Only one of
+                  `out` or `outs` may be present.
+
+                 Example:
+
+                ```
+                genrule(
+                  name = "named_outputs",
+                  outs = {
+                    "output1": [
+                      "out1.txt",
+                    ],
+                    "output2": [
+                      "out2.txt",
+                    ],
+                  },
+                  default_outs = [ "out1.txt" ],
+                  cmd = "echo something> $OUT/out1.txt && echo another> $OUT/out2.txt",
+                )
+                ```
+
+                 Note that a maximum of one value may be present in the list in this map. For example:
+
+                ```
+                outs = {
+                  "output1": [
+                    "out1.txt",
+                  ],
+                },
+                ```
+                is valid, whereas
+
+                ```
+                outs = {
+                  "output1": [
+                    "out1.txt",
+                    "out2.txt",
+                  ],
+                },
+                ```
+                is not.
+            """,
+            ),
+        }
+        | _optional_has_content_based_path_attr()
+        | genrule_common.env_arg()
+        | genrule_common.environment_expansion_separator()
+        | {
+            "cacheable": attrs.option(attrs.bool(), default = None),
+            "enable_sandbox": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Whether this target should be executed in a sandbox or not.
+            """,
+            ),
+            "executable": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Whether the output of the genrule is itself executable. Marking an output as
+                 executable makes `buck run` and `$(exe ...)` macro
+                 expansion work with this target.
+            """,
+            ),
+            "remote": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Opts this genrule in to remote execution. Note that it is only safe to
+                 execute a genrule remotely if it is completely hermetic and completely
+                 and correctly describes its dependencies. Defaults to false. This parameter
+                 is unstable. It is subject to removal, default reversal, and other arbitrary
+                 changes in the future.
+            """,
+            ),
+            "_exec_os_type": buck.exec_os_type_arg(),
+        }
+        | genrule_common.error_handler_arg()
+        | genrule_common.allow_offline_output_cache_arg()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+    cfg = constraint_overrides.transition,
+)
+
+http_archive = prelude_rule(
+    name = "http_archive",
+    docs = """
+        An `http_archive()` rule is used to download and extract archives
+        from the Internet to be used as dependencies for other rules. These rules are
+        downloaded by running `fetch`, or can be downloaded as part of
+        `build` by setting `.buckconfig`
+    """,
+    examples = """
+        Using `http_archive()`, third party packages can be downloaded from
+         an `https` URL and used in other library types.
+
+        ```
+        http_archive(
+          name = 'thrift-archive',
+          urls = [
+            'https://internal-mirror.example.com/bin/thrift-compiler-0.1.tar.gz.badextension',
+          ],
+          sha256 = '7baa80df284117e5b945b19b98d367a85ea7b7801bd358ff657946c3bd1b6596',
+          type='tar.gz',
+          strip_prefix='thrift-compiler-0.1'
+        )
+
+        genrule(
+          name = 'thrift-compiler-bin',
+          out = 'thrift',
+          cmd = 'cp $(location :thrift-archive)/bin/thrift $OUT',
+          executable = True,
+        )
+
+        genrule(
+          name="my-thrift-lib-cpp2",
+          cmd="$(exe :thrift-compiler-bin) --gen cpp2 -o $OUT $(location //:thrift-file)",
+          out="gen-cpp2",
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        remote_common.urls_arg()
+        | remote_common.sha256_arg()
+        | remote_common.unarchive_args()
+        | {
+            "sha1": attrs.option(attrs.string(), default = None),
+            "size_bytes": attrs.option(attrs.int(), default = None),
+        }
+        | _has_content_based_path_attr()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+http_file = prelude_rule(
+    name = "http_file",
+    docs = """
+        An `http_file()` rule is used to download files from the Internet to be used as
+        dependencies for other rules. This rule only downloads single files, and can
+        optionally make them executable (see `http_file()executable`)
+        These rules are downloaded by running `fetch`, or can
+        be downloaded as part of `build` by setting `.buckconfig`
+    """,
+    examples = """
+        Using `http_file()`, third party packages can be downloaded from
+         an `https` URL and used in java libraries.
+
+        ```
+        http_file(
+          name = 'guava-23-bin',
+          urls = [
+            'http://search.maven.org/remotecontent?filepath=com/google/guava/guava/23.0/guava-23.0.jar',
+          ],
+          sha256 = '7baa80df284117e5b945b19b98d367a85ea7b7801bd358ff657946c3bd1b6596',
+        )
+        http_file(
+          name = 'guava-23-sources',
+          urls = [
+            'http://search.maven.org/remotecontent?filepath=com/google/guava/guava/23.0/guava-23.0-sources.jar',
+          ],
+          sha256 = '37fe8ba804fb3898c3c8f0cbac319cc9daa58400e5f0226a380ac94fb2c3ca14',
+        )
+
+        prebuilt_java_library(
+          name = 'guava-23',
+          binary_jar = ':guava-23-bin',
+          source_jar = ':guava-23-source',
+        )
+        ```
+
+         Tooling can also be fetched with `http_file()` and used by a `genrule()`.
+
+        ```
+        genrule(
+          name="my-thrift-lib-cpp2",
+          cmd="$(exe :thrift-compiler-bin) --gen cpp2 -o $OUT $(location //:thrift-file)",
+          out="gen-cpp2",
+        )
+
+        http_file(
+          name = 'thrift-compiler-bin',
+          url = 'https://internal-mirror.example.com/bin/thrift-compiler',
+          sha256 = 'c24932ccabb66fffb2d7122298f7f1f91e0b1f14e05168e3036333f84bdf58dc',
+          executable = True,
+        )
+        ```
+
+         Here's an example of a `http_file()` using a mvn URI which uses a Maven classifier.
+
+        ```
+        http_file(
+          name = 'guava-23-bin',
+          urls = [
+            'mvn:com.google.guava:guava:jar:23.0',
+          ],
+          sha256 = '7baa80df284117e5b945b19b98d367a85ea7b7801bd358ff657946c3bd1b6596',
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        remote_common.urls_arg()
+        | remote_common.sha256_arg()
+        | {
+            "executable": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Whether or not the file should be made executable after downloading. If true,
+                 this can also be used via `run` and the
+                 `$(exe )` `string parameter macros`
+            """,
+            ),
+            "out": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                An optional name to call the downloaded artifact. Buck will generate a default name if one is not
+                 provided that uses the `name` of the rule.
+            """,
+            ),
+            "sha1": attrs.option(attrs.string(), default = None),
+            "size_bytes": attrs.option(attrs.int(), default = None),
+        }
+        | _has_content_based_path_attr()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+platform = prelude_rule(
+    name = "platform",
+    docs = "Declares a platform, which is a build configuration composed of constraint values.",
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "constraint_values": attrs.list(
+                attrs.configuration_label(),
+                default = [],
+                doc = "List of constraint values that are set for this platform.",
+            ),
+            "deps": attrs.list(
+                attrs.configuration_label(),
+                default = [],
+                doc = "List of other platform target dependencies. The constraints from these platforms will be part of this platform (unless overridden)",
+            ),
+        }
+    ),
+)
+
+remote_file = prelude_rule(
+    name = "remote_file",
+    docs = """
+        A `remote_file()` rule is used to download files from the Internet to be used as
+        dependencies for other rules. These rules are downloaded by running `fetch`, or can
+        be downloaded as part of `build`. See the note there about the
+         `.buckconfig` setting to configure that.
+    """,
+    examples = """
+        Here's an example of a `remote_file()` using an `https` URL.
+
+        ```
+        remote_file(
+          name = 'android-ndk-r10e-darwin-x86_64',
+          url = 'https://dl.google.com/android/ndk/android-ndk-r10e-darwin-x86_64.bin',
+          sha1 = 'b57c2b9213251180dcab794352bfc9a241bf2557',
+        )
+        ```
+
+         Here's an example of a `remote_file()` using a `mvn` URL being referenced
+         by a `prebuilt_jar()`.
+
+        ```
+        prebuilt_jar(
+          name = 'jetty-all',
+          binary_jar = 'jetty-all-9.2.10.v20150310.jar',
+          source_jar = ':jetty-source',
+        )
+
+        remote_file(
+          name = 'jetty-source',
+          out = 'jetty-all-9.2.10.v20150310-sources.jar',
+          url = 'mvn:org.eclipse.jetty.aggregate:jetty-all:src:9.2.10.v20150310',
+          sha1 = '311da310416d2feb3de227081d7c3f48742d7075',
+        )
+        ```
+
+         Here's an example of a `remote_file()` using a `mvn` URI which uses a
+         non-default maven repository host.
+
+        ```
+        remote_file(
+          name = 'jetty-source',
+          out = 'jetty-all-9.2.10.v20150310-sources.jar',
+          url = 'mvn:https://maven-repo.com:org.eclipse.jetty.aggregate:jetty-all:src:9.2.10.v20150310',
+          sha1 = '311da310416d2feb3de227081d7c3f48742d7075',
+        )
+        ```
+
+         Here's an example of a `remote_file()` using a `mvn` URI which uses a
+         Maven classifier.
+
+        ```
+        remote_file(
+          name = 'groovy-groovysh-indy',
+          out = 'jetty-all-9.2.10.v20150310-sources.jar',
+          url = 'mvn:org.codehaus.groovy:groovy-groovysh:jar:indy:2.4.1',
+          sha1 = '1600fde728c885cc9506cb102deb1b494bd7c130',
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "url": attrs.string(
+                validate = validate_uri,
+                doc = """
+                You can specify an `http`, `https`, or a `mvn` URL. If you
+                 specify a `mvn` URL, it will be decoded as described in the
+                 javadocs for MavenUrlDecoder See the example section below.
+            """,
+            ),
+            "vpnless_url": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                An optional additional URL from which this resource can be downloaded when
+                  off VPN. Meta-internal only.
+            """,
+            ),
+            "sha1": attrs.string(
+                default = "",
+                doc = """
+                The [`SHA-1`](//wikipedia.org/wiki/SHA-1) hash of the downloaded artifact.
+                 Buck verifies this is correct and fails the fetch command if it doesn't match in order to
+                 guarantee repeatable builds.
+            """,
+            ),
+            "size_bytes": attrs.option(
+                attrs.int(),
+                default = None,
+                doc = """
+                Size in bytes of the downloaded artifact. Buck verifies this is correct and fails the fetch
+                 command if it doesn't match (only when a SHA-1 hash is used).
+            """,
+            ),
+            "out": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                An optional name to call the downloaded artifact. Buck will generate a default name if one is not
+                 provided that uses the `name` of the rule.
+            """,
+            ),
+            "type": attrs.option(
+                attrs.enum(RemoteFileType),
+                default = None,
+                doc = """
+                An optional type of the downloaded file.
+
+                `data`
+                Regular data file.
+                `executable`
+
+                 Executable file. Buck will ensure that output has appropriate permissions if applicable.
+
+                `exploded_zip`
+
+                 Zip archive which will be automatically unzipped into an output directory.
+            """,
+            ),
+            "sha256": attrs.option(attrs.string(), default = None),
+        }
+        | _has_content_based_path_attr()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+test_suite = prelude_rule(
+    name = "test_suite",
+    docs = """
+        A `test_suite()` is used to create a grouping of tests that should all be run by just testing this rule.
+
+        This rule can then be given to `buck test`, and all tests that it depends on will be invoked.
+         Note that the test\\_suite() target is not tested itself, it just tells buck to run other
+         tests. It will not show up in calls to the external runner nor in the normal test output.
+    """,
+    examples = """
+        This test\\_suite() sets up two different sets of tests to run, 'all' tests and 'slow' tests. Note that `all_tests` can depend on `slow_tests`, and all three tests are run.
+
+        ```
+        # instrumentation_tests/BUCK:
+        sh_test(
+            name = "instrumentation_tests",
+            test = "instrumentation_tests.sh",
+            visibility = ["PUBLIC"],
+        )
+
+        # integration_tests/BUCK:
+        sh_test(
+            name = "integration_tests",
+            test = "integration_tests.sh",
+            visibility = ["PUBLIC"],
+        )
+
+        # unit_tests/BUCK:
+        sh_test(
+            name = "unit_tests",
+            test = "unit_tests.sh",
+            visibility = ["PUBLIC"],
+        )
+
+        # BUCK:
+        test_suite(
+            name = "slow_tests",
+            tests = [
+                "//instrumentation_tests:instrumentation_tests",
+                "//integration_tests:integration_tests",
+            ],
+        )
+
+        test_suite(
+            name = "all_tests",
+            tests = [
+                ":slow_tests",
+                "//unit_tests:unit_tests",
+            ],
+        )
+        ```
+
+        Yields output like this when run:
+
+        ```
+        $ buck test //:slow_tests
+        ...
+        RESULTS FOR //instrumentation_tests:instrumentation_tests //integration_tests:integration_tests
+        PASS    <100ms  1 Passed   0 Skipped   0 Failed   //instrumentation_tests:instrumentation_tests
+        PASS    <100ms  1 Passed   0 Skipped   0 Failed   //integration_tests:integration_tests
+        TESTS PASSED
+        ...
+
+        $ buck test //:all_tests
+        RESULTS FOR //instrumentation_tests:instrumentation_tests //integration_tests:integration_tests //unit_tests:unit_tests
+        PASS    <100ms  1 Passed   0 Skipped   0 Failed   //instrumentation_tests:instrumentation_tests
+        PASS    <100ms  1 Passed   0 Skipped   0 Failed   //integration_tests:integration_tests
+        PASS    <100ms  1 Passed   0 Skipped   0 Failed   //unit_tests:unit_tests
+        TESTS PASSED
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            # On buck1 query, tests attribute on test_suite is treated as deps, while on buck2 it is not.
+            # While buck2's behavior makes more sense, we want to preserve buck1 behavior on test_suite for now to make TD behavior match between buck1 and buck2.
+            # This diff makes the behaviors match by adding a test_deps attribute to test_suite on buck2 that is used as a deps attribute. In the macro layer, we set test_deps = tests if we are using buck2.
+            # For more context: https://fb.prod.workplace.com/groups/603286664133355/posts/682567096205311/?comment_id=682623719532982&reply_comment_id=682650609530293
+            "test_deps": attrs.list(attrs.dep(), default = []),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+toolchain_alias = prelude_rule(
+    name = "toolchain_alias",
+    docs = """
+toolchain_alias acts like alias but for toolchain rules.
+
+The toolchain_alias itself is a toolchain rule and the `actual` argument is
+expected to be a toolchain_rule as well.
+    """,
+    examples = None,
+    further = None,
+    attrs = {
+        "actual": attrs.option(attrs.toolchain_dep(doc = "The actual toolchain that is being aliased. This should be a toolchain rule.")),
+    },
+)
+
+versioned_alias = prelude_rule(
+    name = "versioned_alias",
+    docs = "",
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "versions": attrs.dict(key = attrs.string(), value = attrs.dep(), sorted = False, default = {}),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+worker_tool = prelude_rule(
+    name = "worker_tool",
+    docs = """
+        Some external tools have high startup costs. To amortize those costs over the whole build
+         rather than paying them for each rule invocation, use the `worker_tool()` rule
+         in conjunction with `genrule()`.
+         Buck then starts the external tool once and reuses it by communicating with it
+         over `stdin` and `stdout` using a simple JSON protocol.
+
+         A `worker_tool` rule can be referenced in the `cmd` parameter of
+         a `genrule` by using the macro:
+
+        ```
+        $(exe //path/to:target)
+        ```
+    """,
+    examples = """
+        Consider the following `build rules`:
+
+        ```
+        #
+        # Buck
+        #
+        worker_tool(
+          name = 'ExternalToolWorker',
+          exe = ':ExternalTool',
+          args = '--arg1 --arg2'
+        )
+
+        sh_binary(
+          name = 'ExternalTool',
+          main = 'external_tool.sh',
+        )
+
+        genrule(
+          name = 'TransformA',
+          out = 'OutputA.txt',
+          cmd = '$(exe :ExternalToolWorker) argA',
+        )
+
+        genrule(
+          name = 'TransformB',
+          out = 'OutputB.txt',
+          cmd = '$(exe :ExternalToolWorker) argB',
+        )
+
+        genrule(
+          name = 'TransformC',
+          out = 'OutputC.txt',
+          cmd = '$(exe :ExternalToolWorker) argC',
+        )
+        ```
+
+         When doing a `buck build` on all three of the above `genrules`, Buck
+         first creates the worker process by invoking:
+
+        ```
+        ./external_tool.sh --arg1 --arg2
+        ```
+
+         Buck then communicates with this process using JSON over `stdin`,
+         starting with a handshake:
+
+        ```
+        [
+          {
+            "id": 0,
+            "type": "handshake",
+            "protocol_version": "0",
+            "capabilities": []
+          }
+        ```
+
+         Buck then waits for the tool to reply on `stdout`:
+
+        ```
+        [
+          {
+            "id": 0,
+            "type": "handshake",
+            "protocol_version": "0",
+            "capabilities": []
+          }
+        ```
+
+         Then, when building the first `genrule`, Buck writes to `stdin`:
+
+        ```
+          ,{
+            "id": 1,
+            "type": "command",
+            "args_path": "/tmp/1.args",
+            "stdout_path": "/tmp/1.out",
+            "stderr_path": "/tmp/1.err"
+          }
+        ```
+
+         The file `/tmp/1.args` contains `argA`. The tool should
+         perform the necessary work for this job and then write the job's output to the files
+         supplied by Buck—in this case, `/tmp/1.out` and `/tmp/1.err`.
+         Once the job is done, the tool should reply to Buck on `stdout` with:
+
+        ```
+          ,{
+            "id": 1,
+            "type": "result",
+            "exit_code": 0
+          }
+        ```
+
+         Once Buck hears back from the first genrule's job, it submits the second genrule's job in the
+         same fashion and awaits the response. When the build is all finished,
+         Buck closes the JSON by writing to `stdin`:
+
+        ```
+        ]
+        ```
+
+         which signals the tool that it should exit after replying on `stdout` with:
+
+        ```
+        ]
+        ```
+
+         In this example, Buck is guaranteed to invoke
+
+        ```
+        ./external_tool.sh --arg1 --arg2
+        ```
+
+         only once during the build. The three jobs corresponding to the three genrules are submitted
+         synchronously to the single worker process.
+
+         Note that the `id` values in the messages are not necessarily increasing or sequential,
+         but they do have to match between the request message and the response message of a given job as
+         well as in the initial handshake.
+
+         If the tool receives a message type it cannot interpret it should answer with:
+
+        ```
+        {
+          "id": &ltn>,
+          "type": "error",
+          "exit_code": 1
+        }
+        ```
+
+         If the tool receives a message type it can interpret, but the other attributes of the
+         message are in an inconsistent state, it should answer with:
+
+        ```
+        {
+          "id": &ltn>,
+          "type": "error",
+          "exit_code": 2
+        }
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "exe": attrs.option(
+                attrs.dep(),
+                default = None,
+                doc = """
+                A `build target` for a rule that outputs
+                 an executable, such as an `sh_binary()`.
+                 Buck runs this executable only once per build.
+            """,
+            ),
+            "args": attrs.one_of(
+                attrs.arg(),
+                attrs.list(attrs.arg()),
+                default = [],
+                doc = """
+                A string of args that is passed to the executable represented by `exe` on
+                 initial startup.
+            """,
+            ),
+            "max_workers": attrs.option(
+                attrs.int(),
+                default = None,
+                doc = """
+                The maximum number of workers of this type that Buck starts. Use `-1` to allow
+                 the creation of as many workers as necessary.
+            """,
+            ),
+            "max_workers_per_thread_percent": attrs.option(
+                attrs.int(),
+                default = None,
+                doc = """
+                The maximum ratio of workers of this type that Buck starts per
+                 thread, specified as a positive integer percentage (1-100). Must be
+                 greater than or equal to `1` and less than or equal to `100`.
+                 Only one of `max_workers` and `max_workers_per_thread_percent` may be specified.
+            """,
+            ),
+            "env": attrs.dict(
+                key = attrs.string(),
+                value = attrs.arg(),
+                sorted = False,
+                default = {},
+                doc = """
+                A map of environment variables that is passed to the executable represented
+                 by `exe` on initial startup.
+            """,
+            ),
+            "persistent": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                If set to true, Buck does not restart the tool unless the tool itself changes. This means the
+                 tool persists across multiple Buck commands without being shut down and may see the same
+                 rule being built more than once. Be careful not to use this setting with tools that don't expect
+                 to process the same input—with different contents—twice!
+            """,
+            ),
+            # FIXME: prelude// should be standalone (not refer to fbsource//)
+            "_worker_tool_runner": attrs.default_only(attrs.dep(default = "prelude//js/worker_runner:worker_tool_runner")),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+zip_file = prelude_rule(
+    name = "zip_file",
+    docs = """
+        A `zip_file()` allows builds to create basic zip files in
+         a platform-agnostic way.
+    """,
+    examples = """
+        This example will create a simple zip file.
+
+        ```
+        zip_file(
+          # The output will be "example.zip"
+          name = 'example',
+          srcs =
+            # These files will be found in the zip under "dir/"
+            glob(['dir/**/*']) +
+            [
+              # Imagine this generates the output
+              # "buck-out/gen/foo/hello.txt". This output will
+              # be found in the zip at "hello.txt"
+              '//some/other:target',
+
+            ],
+          zip_srcs = [
+             # The contents of this zip will be added to the generated zip.
+            'amazing-library-1.0-sources.zip',
+          ],
+          entries_to_exclude = [
+            "com/example/amazinglibrary/Source1.java",
+          ],
+        )
+        ```
+        If you were to examine the generated zip, the contents would look
+        something like (assuming the output of
+        "`//some/other:target`" was a file who's path ended with
+         `hello.txt`, the "`dir`" glob found two files,
+        and "`amazing-library-1.0-sources.zip`" contained two Java
+        source files):
+
+        ```
+        dir/file1.txt
+        dir/subdir/file2.txt
+        hello.txt
+        com/example/amazinglibrary/Source2.java
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "out": attrs.string(
+                default = "",
+                doc = """
+                The name of the zip file that should be generated. This allows
+                 builds to use a meaningful target name coupled with a meaningful zip
+                 file name. The default value takes the rule's `name` and
+                 appends `.zip`.
+            """,
+            ),
+            "srcs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                The set of files to include in the zip.
+
+                 Each `src` will be added to the zip as follows:
+                 * If the `src` is the output of another rule, the output
+                 will be included using just the output's file name.
+                 * If the `src` is a file relative to the rule's
+                 declaration, it will be included in the zip with its relative file
+                 name.
+            """,
+            ),
+            "zip_srcs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                The set of zip files whose content to include in the output zip file.
+
+                 Note that the order of files in `zip_srcs` matters because the same zip entry can be
+                 included from multiple files. See the `on_duplicate_entry` argument to learn how to
+                 control the behavior when there are multiple entries with the same name.
+
+                 The entries from `zip_srcs` are added before files from `srcs`.
+            """,
+            ),
+            "entries_to_exclude": attrs.list(
+                attrs.regex(),
+                default = [],
+                doc = """
+                List of regex expressions that describe entries that should not be included in the output zip file.
+
+                 The regexes must be defined using `java.util.regex.Pattern` syntax.
+            """,
+            ),
+            "hardcode_permissions_for_deterministic_output": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                If set to true, Buck hardcodes the permissions in order to ensures that all files have the same
+                permissions regardless of the platform on which the zip was generated.
+            """,
+            ),
+            "on_duplicate_entry": attrs.enum(
+                OnDuplicateEntry,
+                default = "overwrite",
+                doc = """
+                Action performed when Buck detects that zip\\_file input contains multiple entries with the same
+                 name.
+
+                 The valid values are:
+                 * `overwrite` (default): the last entry overwrites all previous entries with
+                 the same name.
+                * `append`: all entries are added to the output file.
+                * `fail`: fail the build when duplicate entries are present.
+            """,
+            ),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+core_args = struct(
+    has_content_based_path_attr = _has_content_based_path_attr,
+    optional_has_content_based_path_attr = _optional_has_content_based_path_attr,
+)
+
+core_rules = struct(
+    alias = alias,
+    command_alias = command_alias,
+    config_setting = config_setting,
+    configuration_alias = configuration_alias,
+    configured_alias = configured_alias,
+    constraint_setting = constraint_setting,
+    constraint = constraint,
+    constraint_value = constraint_value,
+    exec_platform_marker_constraint = exec_platform_marker_constraint,
+    export_file = export_file,
+    external_test_runner = external_test_runner,
+    filegroup = filegroup,
+    genrule = genrule,
+    http_archive = http_archive,
+    http_file = http_file,
+    platform = platform,
+    remote_file = remote_file,
+    test_suite = test_suite,
+    toolchain_alias = toolchain_alias,
+    versioned_alias = versioned_alias,
+    worker_tool = worker_tool,
+    zip_file = zip_file,
+)
diff --git a/buck2/prelude/decls/cxx_common.bzl b/buck2/prelude/decls/cxx_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/cxx_common.bzl
@@ -0,0 +1,554 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//cxx:cxx_flags.bzl", "CxxFlagsInfo")
+load(":common.bzl", "CxxSourceType", "DefaultDepsMode", "IncludeType", "RawHeadersAsHeadersMode", "RuntimeDependencyHandling")
+
+def _srcs_arg():
+    return {
+        "srcs": attrs.list(
+            attrs.one_of(attrs.source(), attrs.tuple(attrs.source(), attrs.list(attrs.arg()))),
+            default = [],
+            doc = """
+    The set of C, C++, Objective-C, Objective-C++, or assembly source files
+     to be preprocessed, compiled, and assembled by this
+     rule. We determine which stages to run on each input source based on its file extension. See the
+     [GCC documentation](https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html) for more detail on how file extensions are interpreted. Each element can be either a string
+     specifying a source file (e.g. `''`) or a tuple of
+     a string specifying a source file and a list of compilation flags
+     (e.g. `('', ['-Wall', '-Werror'])` ). In the latter case the specified flags will be used in addition to the rule's other
+     flags when preprocessing and compiling that file (if applicable).
+""",
+        ),
+    }
+
+def _deps_arg():
+    return {
+        "deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    Other rules that list `srcs` from which this rule imports.
+""",
+        ),
+    }
+
+def _default_deps_arg(default = "deps"):
+    return {
+        "default_deps": attrs.enum(
+            DefaultDepsMode,
+            default = default,
+            doc = """
+    Whether to include the default deps from the toolchain, and where to include them (deps, exported_deps, etc).
+""",
+        ),
+    }
+
+def _supported_platforms_regex_arg():
+    return {
+        "supported_platforms_regex": attrs.option(
+            attrs.regex(),
+            default = None,
+            doc = """
+    Deprecated: do not set this attribute in new code. Instead, use `target_compatible_with` to
+     restrict the platforms a target can be built for.
+
+     If present, an un-anchored regex (in java.util.regex.Pattern syntax) that matches all platforms
+     that this library supports. It will not be built for other platforms.
+""",
+        ),
+    }
+
+def _headers_arg():
+    return {
+        "headers": attrs.named_set(
+            attrs.source(),
+            sorted = True,
+            default = [],
+            doc = """
+    The set of header files that are made available for inclusion to the source files in this
+     target. These should be specified as either a list
+     of header files or a dictionary of header names to header files. The header name can contain
+     forward slashes (`/`). The headers can be included with `#include
+     "$HEADER_NAMESPACE/$HEADER_NAME"` or `#include <$HEADER_NAMESPACE/$HEADER_NAME>` , where `$HEADER_NAMESPACE` is the value of the target's `header_namespace`  attribute, and `$HEADER_NAME` is the header name if specified, and the filename
+     of the header file otherwise. See `header_namespace` for more information.
+""",
+        ),
+    }
+
+def _exported_headers_arg():
+    return {
+        "exported_headers": attrs.named_set(
+            attrs.source(),
+            sorted = True,
+            default = [],
+            doc = """
+    The set of header files that are made available for inclusion to the source files in the
+     target and all targets that transitively depend on it. These should be specified as either a list
+     of header files or a dictionary of header names to header files. The headers can be included
+     with `#include "$HEADER_NAMESPACE/$HEADER_NAME"` or `#include
+     <$HEADER_NAMESPACE/$HEADER_NAME>`, where `$HEADER_NAMESPACE` is the value
+     of the target's `header_namespace` attribute, and `$HEADER_NAME` is the
+     header name if specified, and the filename of the header file otherwise. Note that the header name
+     can contain forward slashes (`/`). See `header_namespace` for more
+     information.
+""",
+        ),
+    }
+
+def _exported_header_style_arg():
+    return {
+        "exported_header_style": attrs.enum(
+            IncludeType,
+            default = "local",
+            doc = """
+    How dependents should include exported headers from this rule. Can be either `local`
+     (e.g. `-I`) or `system` (e.g. `-isystem`).
+""",
+        ),
+    }
+
+def _header_namespace_arg():
+    return {
+        "header_namespace": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    A path prefix when including headers of this target. Defaults to the path from the root of the
+     repository to the directory where this target is defined. Can
+     contain forward slashes (`/`), but cannot start with one. See `headers` for
+     more information.
+""",
+        ),
+    }
+
+def _preprocessor_flags_arg():
+    return {
+        "preprocessor_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    Flags to use when preprocessing any of the above sources (which require preprocessing).
+""",
+        ),
+    }
+
+def _lang_preprocessor_flags_arg():
+    return {
+        "lang_preprocessor_flags": attrs.dict(
+            key = attrs.enum(CxxSourceType),
+            value = attrs.list(attrs.arg()),
+            sorted = False,
+            default = {},
+            doc = """
+    Language-specific preprocessor flags. These should be specified as a map of C-family language short
+     names to lists of flags and is used to target flags to sources files for a specific language in the
+     C-family (C, C++, assembler, etc.). The keys in the map can be:
+     * `c` for C
+    * `c++` for C++
+    * `objective-c` for Objective-C
+    * `objective-c++` for Objective-C++
+    * `cuda` for Cuda
+    * `assembler-with-cpp` for Assembly
+    * `asm-with-cpp` for ASM
+""",
+        ),
+    }
+
+def _exported_lang_preprocessor_flags_arg():
+    return {
+        "exported_lang_preprocessor_flags": attrs.dict(
+            key = attrs.enum(CxxSourceType),
+            value = attrs.list(attrs.arg()),
+            sorted = False,
+            default = {},
+            doc = """
+    Just as `lang_preprocessor_flags`, but these flags also apply to
+     rules that transitively depend on this rule.
+""",
+        ),
+    }
+
+def _exported_preprocessor_flags_arg(exported_preprocessor_flags_type):
+    return {
+        "exported_preprocessor_flags": exported_preprocessor_flags_type,
+    }
+
+def _compiler_flags_arg():
+    return {
+        "compiler_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    Flags to use when compiling any of the above sources (which require compilation).
+""",
+        ),
+    }
+
+def _lang_compiler_flags_arg():
+    return {
+        "lang_compiler_flags": attrs.dict(
+            key = attrs.enum(CxxSourceType),
+            value = attrs.list(attrs.arg()),
+            sorted = False,
+            default = {},
+            doc = """
+    Language-specific compiler flags. These should be specified as a map of C-family language short
+     names to lists of flags and is used to target flags to sources files for a specific language in the
+     C-family (C, C++, assembler, etc.). The keys in the map can be:
+     * `cpp-output` for C
+    * `c++-cpp-output` for C++
+    * `objective-c-cpp-output` for Objective-C
+    * `objective-c++-cpp-output` for Objective-C++
+    * `cuda-cpp-output` for Cuda
+    * `assembler` for Assembly
+    * `asm` for ASM
+""",
+        ),
+    }
+
+def _linker_extra_outputs_arg():
+    return {
+        "linker_extra_outputs": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    Declares extra outputs that the linker emits. These identifiers can be used in
+     `$(output ...)` macros in `linker_flags` to interpolate the output path
+     into the linker command line. Useful for custom linkers that emit extra output files.
+""",
+        ),
+    }
+
+def _linker_flags_arg():
+    return {
+        "linker_flags": attrs.list(
+            attrs.arg(anon_target_compatible = True),
+            default = [],
+            doc = """
+    Flags to add to the linker command line whenever the output from this
+     rule is used in a link operation, such as linked into an executable
+     or a shared library.
+""",
+        ),
+    }
+
+def _local_linker_flags_arg():
+    return {
+        "local_linker_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    Flags to add to the linker command line whenever the output from this
+     rule is used in a link operation *driven by this rule* (e.g. when this
+     rule links a shared library, but *not* when the output is linked into a
+     shared library by another rule's link group links).
+""",
+        ),
+    }
+
+# TODO(christylee): remove this arg once link group map migrates to its own rule
+def _local_linker_script_flags_arg():
+    return {
+        "local_linker_script_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    Linker script lags to add to the linker command line whenever the output
+     from this rule is used in a link operation *driven by this rule*. Used
+     by rules that need to treat linker script flags different from normal
+     linker flags.
+""",
+        ),
+    }
+
+def _exported_linker_flags_arg():
+    return {
+        "exported_linker_flags": attrs.list(
+            attrs.arg(anon_target_compatible = True),
+            default = [],
+            doc = """
+    Flags to add to the linker command line when the output from this
+     rule, or the output from any rule that transitively depends on this
+     rule, is used in a link operation.
+""",
+        ),
+    }
+
+def _exported_post_linker_flags_arg():
+    return {
+        "exported_post_linker_flags": attrs.list(
+            attrs.arg(anon_target_compatible = True),
+            default = [],
+            doc = """
+    Flags to add to the linker command line when the output from this
+     rule, or the output from any rule that transitively depends on this
+     rule, is used in a link operation—with the additional feature
+     that these flags are guaranteed to be placed *after* the compiled
+     object (`.o`) files on the linker command line.
+""",
+        ),
+    }
+
+def _precompiled_header_arg():
+    return {
+        "precompiled_header": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+    Path to a `cxx_precompiled_header` to use when compiling this rule's sources. The precompiled header (PCH) is built on-demand, using
+     compiler flags matching those used in this rule's compile jobs. This is to ensure
+     compatibility between this rule and the PCH. Also, this rule will inherit additional
+     `deps` from the PCH rule, and as a result, additional include paths as well
+     (e.g. `-I`, `-isystem`, `-iquote` path lists,
+     and framework paths specified with `-F`).
+""",
+        ),
+    }
+
+def _force_static(force_static_type):
+    return {
+        "force_static": force_static_type,
+    }
+
+def _reexport_all_header_dependencies_arg():
+    return {
+        "reexport_all_header_dependencies": attrs.option(
+            attrs.bool(),
+            default = None,
+            doc = """
+    Deprecated: do not set this attribute in new code. Instead, list dependencies whose
+     headers should be re-exported in `exported_deps`. Using this attribute is generally
+     bad for build speed.
+
+     Whether to automatically re-export the exported headers of all dependencies.
+
+     When this is set to false, only exported headers from
+     `exported_deps` are re-exported.
+""",
+        ),
+    }
+
+def _exported_deps_arg():
+    return {
+        "exported_deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    Dependencies that will also appear to belong to any rules that depend on this
+     one. This has two effects:
+     * Exported dependencies will also be included in the link line of
+     dependents of this rules, but normal dependencies will not.
+    * When `reexport_all_header_dependencies = False`, only exported
+     headers of the rules specified here are re-exported.
+""",
+        ),
+    }
+
+def _supports_merged_linking():
+    return {
+        "supports_merged_linking": attrs.option(
+            attrs.bool(),
+            default = None,
+            doc = """
+    Whether this rule supports building with the merged linking strategy when building for non-native
+     binaries (e.g. when using `.buckconfig`
+    s `merged` setting).
+""",
+        ),
+    }
+
+def _raw_headers_arg():
+    return {
+        "raw_headers": attrs.set(
+            attrs.source(),
+            sorted = True,
+            default = [],
+            doc = """
+    The set of header files that can be used for inclusion to the source files in the target and all
+     targets that transitively depend on it. Buck doesn't add raw headers to the search path of a
+     compiler/preprocessor automatically.
+     `include_directories` and `public_include_directories` are the recommended
+     way to add raw headers to the search path (they will be added via `-I`).
+     `compiler_flags`, `preprocessor_flags` and `exported_preprocessor_flags`
+     can also be used to add such raw headers to the search path if inclusion via `-isystem` or
+     `-iquote` is needed.
+     `raw_headers` cannot be used together with `headers` or `exported_headers` in the same target.
+""",
+        ),
+    }
+
+def _supports_stripping():
+    return {
+        "supports_stripping": attrs.bool(
+            default = True,
+            doc = """
+    Whether this rule supports stripping outputs via `strip` command for exporting.
+""",
+        ),
+    }
+
+def _raw_headers_as_headers_mode_arg():
+    return {
+        "raw_headers_as_headers_mode": attrs.option(
+            attrs.enum(RawHeadersAsHeadersMode),
+            default = None,
+            doc = """
+    Controls whether raw_headers and *include_directories attributes should be automatically
+    converted to headers and symlink trees and/or header maps via headers. Only has an effect if
+    the cxx_toolchain has explicitly opted into supporting this behavior via a non-default value,
+    even if the value is disabled.
+""",
+        ),
+    }
+
+def _include_directories_arg():
+    return {
+        "include_directories": attrs.set(
+            attrs.string(),
+            sorted = True,
+            default = [],
+            doc = """
+    A list of include directories (with `raw_headers`) to be added to the compile command for compiling this target
+     (via `-I`).
+     An include directory is relative to the current package.
+""",
+        ),
+    }
+
+def _public_include_directories_arg():
+    return {
+        "public_include_directories": attrs.set(
+            attrs.string(),
+            sorted = True,
+            default = [],
+            doc = """
+    A list of include directories (with `raw_headers`) to be added to the compile command for compiling this target
+     and every target that depends on it (via `-I`). An include directory is relative to the current package.
+""",
+        ),
+    }
+
+def _public_system_include_directories_arg():
+    return {
+        "public_system_include_directories": attrs.set(
+            attrs.string(),
+            sorted = True,
+            default = [],
+            doc = """
+    A list of include directories (with `raw_headers`) to be added to the compile command for compiling this target
+     and every target that depends on it (via `-isystem` if the compiler supports it of via `-I` otherwise).
+     An include directory is relative to the current package.
+""",
+        ),
+    }
+
+def _version_arg():
+    return {
+        "version": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    A string denoting a meaningful version of this rule that is optionally passed to the linker as extra
+     metadata.
+""",
+        ),
+    }
+
+def _runtime_dependency_handling_arg():
+    return {
+        "runtime_dependency_handling": attrs.option(
+            attrs.enum(RuntimeDependencyHandling),
+            default = None,
+            doc = """
+    Controls how shared library dependencies are handled at runtime. By default the `no_symlink` behaviour
+    is used, which opts out of symlink creation. If `symlink` is specified then shared library dependencies with
+    `preferred_linkage = "shared"` are automatically detected and included in a symlink tree
+    alongside the executable. Set to `symlink_single_level_only` to only include first-level runtime
+    dependencies in a symlink tree.
+""",
+        ),
+    }
+
+def _use_fbcc_rust_wrapper_arg():
+    return {
+        "use_fbcc_rust_wrapper": attrs.bool(
+            default = False, doc = "Opt-in for the rust version of the fbcode C++ Compiler wrapper (replacing the existing fbcc.py)"
+        ),
+    }
+
+def _use_content_based_paths_arg():
+    return {
+        # Use content-based paths by default for compile action; targets may opt out
+        # explicitly.
+        "use_content_based_paths": attrs.bool(default = True),
+    }
+
+def _expect_eligible_for_dedupe_arg():
+    return {
+        "expect_eligible_for_dedupe": attrs.bool(default = False),
+    }
+
+def _flags_arg():
+    return {
+        "flags": attrs.list(
+            attrs.dep(providers = [CxxFlagsInfo]),
+            default = [],
+            doc = """
+            `cxx_flags` targets whose flags apply before this target's own. Their transitive
+             definitions are combined into a shared argsfile, with nested flags first and
+             direct entries in list order. Repeated and diamond dependencies contribute once.
+             They cannot contribute `exported_*` or post-linker flag categories.
+        """,
+        ),
+    }
+
+cxx_common = struct(
+    srcs_arg = _srcs_arg,
+    deps_arg = _deps_arg,
+    default_deps_arg = _default_deps_arg,
+    supported_platforms_regex_arg = _supported_platforms_regex_arg,
+    headers_arg = _headers_arg,
+    exported_headers_arg = _exported_headers_arg,
+    exported_header_style_arg = _exported_header_style_arg,
+    header_namespace_arg = _header_namespace_arg,
+    preprocessor_flags_arg = _preprocessor_flags_arg,
+    lang_preprocessor_flags_arg = _lang_preprocessor_flags_arg,
+    exported_lang_preprocessor_flags_arg = _exported_lang_preprocessor_flags_arg,
+    exported_preprocessor_flags_arg = _exported_preprocessor_flags_arg,
+    compiler_flags_arg = _compiler_flags_arg,
+    lang_compiler_flags_arg = _lang_compiler_flags_arg,
+    linker_extra_outputs_arg = _linker_extra_outputs_arg,
+    linker_flags_arg = _linker_flags_arg,
+    local_linker_flags_arg = _local_linker_flags_arg,
+    local_linker_script_flags_arg = _local_linker_script_flags_arg,
+    exported_linker_flags_arg = _exported_linker_flags_arg,
+    exported_post_linker_flags_arg = _exported_post_linker_flags_arg,
+    precompiled_header_arg = _precompiled_header_arg,
+    force_static = _force_static,
+    reexport_all_header_dependencies_arg = _reexport_all_header_dependencies_arg,
+    exported_deps_arg = _exported_deps_arg,
+    supports_merged_linking = _supports_merged_linking,
+    raw_headers_arg = _raw_headers_arg,
+    raw_headers_as_headers_mode_arg = _raw_headers_as_headers_mode_arg,
+    include_directories_arg = _include_directories_arg,
+    public_include_directories_arg = _public_include_directories_arg,
+    public_system_include_directories_arg = _public_system_include_directories_arg,
+    version_arg = _version_arg,
+    runtime_dependency_handling_arg = _runtime_dependency_handling_arg,
+    use_fbcc_rust_wrapper_arg = _use_fbcc_rust_wrapper_arg,
+    use_content_based_paths_arg = _use_content_based_paths_arg,
+    expect_eligible_for_dedupe_arg = _expect_eligible_for_dedupe_arg,
+    flags_arg = _flags_arg,
+    supports_stripping = _supports_stripping,
+)
diff --git a/buck2/prelude/decls/cxx_rules.bzl b/buck2/prelude/decls/cxx_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/cxx_rules.bzl
@@ -0,0 +1,1471 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//:attrs_validators.bzl", "validation_common")
+load("@prelude//apple:apple_common.bzl", "apple_common")
+load("@prelude//cxx:cuda.bzl", "CudaCompileStyle")
+load("@prelude//cxx:cxx_flags.bzl", "CxxFlagsInfo")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CXX_COMPILER_TYPES")
+load("@prelude//cxx:cxx_types.bzl", "LinkPreference")
+load("@prelude//cxx:headers.bzl", "CPrecompiledHeaderInfo")
+load("@prelude//cxx:link_groups_types.bzl", "LINK_GROUP_MAP_ATTR")
+load("@prelude//decls:core_rules.bzl", "core_args")
+load("@prelude//decls:test_common.bzl", "test_common")
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//linking:execution_preference.bzl", "link_execution_preference_attr")
+load("@prelude//linking:link_info.bzl", "ArchiveContentsType", "LinkOrdering", "LinkStyle")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")
+load(":common.bzl", "CxxRuntimeType", "CxxSourceType", "HeadersAsRawHeadersMode", "buck", "prelude_rule")
+load(":cxx_common.bzl", "cxx_common")
+load(":genrule_common.bzl", "genrule_common")
+load(":native_common.bzl", "native_common")
+
+BUILD_INFO_ATTR = attrs.dict(
+    key = attrs.string(),
+    value = attrs.option(attrs.any()),
+    sorted = False,
+    default = {},
+    doc = "Build info that is passed along here will be late-stamped into a fb_build_info section on the output binary",
+)
+
+def _cxx_binary_and_test_attrs():
+    ret = (
+        {
+            "anonymous_link_groups": attrs.bool(default = False),
+            "auto_link_groups": attrs.bool(default = False),
+            # Linker flags that only apply to the executable link, used for link
+            # strategies (e.g. link groups) which may link shared libraries from
+            # top-level binary context.
+            "binary_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "bolt_flags": attrs.list(attrs.arg(), default = []),
+            "bolt_profile": attrs.option(attrs.source(), default = None),
+            # These flags will only be used to instrument a target
+            # when coverage for that target is enabled by a header
+            # selected for coverage either in the target or in one
+            # of the target's dependencies.
+            "coverage_instrumentation_compiler_flags": attrs.list(attrs.string(), default = []),
+            # Optional clang_profile_list target for selective coverage instrumentation via -fprofile-list.
+            "coverage_profile_list": attrs.option(attrs.dep(), default = None),
+            "cuda_compile_style": attrs.enum(CudaCompileStyle.values(), default = "mono"),
+            "enable_distributed_thinlto": attrs.bool(default = False),
+            "exported_needs_coverage_instrumentation": attrs.bool(default = False),
+            "extra_dwp_flags": attrs.list(attrs.string(), default = []),
+            "link_execution_preference": link_execution_preference_attr(),
+            "link_group_map": LINK_GROUP_MAP_ATTR,
+            "link_group_min_binary_node_count": attrs.option(attrs.int(), default = None),
+            "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),
+            "link_preference": attrs.enum(LinkPreference.values(), default = "default"),
+            "link_whole": attrs.default_only(attrs.bool(default = False)),
+            "precompiled_header": attrs.option(attrs.dep(providers = [CPrecompiledHeaderInfo]), default = None),
+            "resources": attrs.named_set(attrs.one_of(attrs.dep(), attrs.source(allow_directory = True)), sorted = True, default = []),
+            "separate_debug_info": attrs.bool(default = False),
+            "_build_info": BUILD_INFO_ATTR,
+            "_cxx_hacks": attrs.dep(default = "prelude//cxx/tools:cxx_hacks"),
+            "_cxx_toolchain": toolchains_common.cxx(),
+        }
+        | cxx_common.flags_arg()
+        | validation_common.attrs_validators_arg()
+    )
+    ret.update(constraint_overrides.attributes)
+    return ret
+
+ArchiverProviderType = ["bsd", "gnu", "llvm", "windows", "windows_clang"]
+
+CxxTestType = ["gtest", "boost"]
+
+LinkerProviderType = ["darwin", "gnu", "windows", "unknown", "wasm"]
+
+PicType = ["pic", "pdc"]
+
+cxx_binary = prelude_rule(
+    name = "cxx_binary",
+    docs = """
+        A cxx\\_binary() rule builds a native executable from the supplied set of C/C++ source files and
+        dependencies. If C/C++ library dependencies are listed, the generated native executable will request
+        and link against their static archives (which are \\*not\\* built using [PIC](http://en.wikipedia.org/wiki/Position-independent_code)).
+    """,
+    examples = """
+        ```
+        # A rule that builds a C/C++ native executable from a single .cpp file
+        # its corresponding header, and a C/C++ library dependency.
+        cxx_binary(
+          name = 'echo',
+          srcs = [
+            'echo.cpp',
+          ],
+          headers = [
+            'echo.h',
+          ],
+          deps = [
+            ':util',
+          ],
+        )
+
+        cxx_library(
+          name = 'util',
+          srcs = [
+            'util.cpp',
+          ],
+          headers = [
+            'util.h',
+          ],
+        )
+
+        # To build without stripping:
+        buck build :echo
+
+        # To build with stripping debug symbols only:
+        buck build :echo#strip-debug
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        cxx_common.srcs_arg()
+        | cxx_common.headers_arg()
+        | cxx_common.header_namespace_arg()
+        | cxx_common.preprocessor_flags_arg()
+        | cxx_common.compiler_flags_arg()
+        | cxx_common.linker_extra_outputs_arg()
+        | cxx_common.linker_flags_arg()
+        | cxx_common.precompiled_header_arg()
+        | cxx_common.default_deps_arg()
+        | native_common.link_style()
+        | native_common.link_group_deps()
+        | native_common.link_group_public_deps_label()
+        | native_common.transformation_spec_arg()
+        | buck.deps_query_arg()
+        | cxx_common.raw_headers_arg()
+        | cxx_common.include_directories_arg()
+        | cxx_common.raw_headers_as_headers_mode_arg()
+        | cxx_common.runtime_dependency_handling_arg()
+        | cxx_common.use_fbcc_rust_wrapper_arg()
+        | cxx_common.use_content_based_paths_arg()
+        | {
+            "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),
+            "default_platform": attrs.option(attrs.string(), default = None),
+            "defaults": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "devirt_enabled": attrs.bool(default = False),
+            "executable_name": attrs.option(attrs.string(), default = None),
+            "fat_lto": attrs.bool(default = False),
+            "focused_list_target": attrs.option(attrs.dep(), default = None),
+            "frameworks": attrs.list(attrs.string(), default = []),
+            "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),
+            "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "libraries": attrs.list(attrs.string(), default = []),
+            "link_deps_query_whole": attrs.bool(default = False),
+            "link_group": attrs.option(attrs.string(), default = None),
+            "link_group_map": LINK_GROUP_MAP_ATTR,
+            "post_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "prefer_stripped_objects": attrs.bool(default = False),
+            "prefix_header": attrs.option(attrs.source(), default = None),
+            "resources": attrs.named_set(attrs.source(), sorted = True, default = []),
+            "thin_lto": attrs.bool(default = False),
+            "use_header_units": attrs.one_of(attrs.bool(), attrs.enum(["stub"]), default = False),
+            "version_universe": attrs.option(attrs.string(), default = None),
+            "weak_framework_names": attrs.list(attrs.string(), default = []),
+        }
+        | buck.allow_cache_upload_arg()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+        | _cxx_binary_and_test_attrs()
+    ),
+    # @oss-disable[end= ]: cfg = constraint_overrides.transition,
+    supports_incoming_transition = True, # @oss-enable
+)
+
+cxx_genrule = prelude_rule(
+    name = "cxx_genrule",
+    docs = """
+        A `cxx_genrule()` enables you to run shell commands as part
+        of the Buck build process. A `cxx_genrule()` exposes - through
+        a set of string parameter macros and variables - information about the
+        tools and configuration options used by the
+        Buck environment, specifically those related to the C/C++ toolchain.
+
+        The information exposed through these tools and configuration options is a reflection of:
+        Buck's built-in settings,
+        the settings in `.buckconfig`
+        and `.buckconfig.local`,
+        and the result of various command-line overrides specified through
+        the `common_parameters` command-line option.
+
+        This information is available only
+        to the shell commands specified in the `cxx_genrule`.
+        The information is not available to other arguments of the rule.
+
+        A `cxx_genrule()` can be an input to
+        another `cxx_genrule()`.
+
+        Note that if you specify the `cxx_genrule` as a command-line
+        target to `buck build`, you must include a platform flavor.
+        For example:
+
+        ```
+        buck build :cxx_gr_name#iphonesimulator-x86_64
+        ```
+
+        You could also just specify the default platform flavor explicitly:
+
+        ```
+        buck build :cxx_gr_name#default
+        ```
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        genrule_common.srcs_arg()
+        | {
+            "cmd": attrs.option(
+                attrs.arg(),
+                default = None,
+                doc = """
+                The shell command to run to generate the output file. It is the fallback of `bash`
+                 and `cmd_exe`. The shell command can access information
+                 about the buck build environment through a set
+                 of *macros*, *parameterized macros*, and *variables*.
+
+                 #### Macros
+
+                 The following macros are available to the shell command and are
+                 accessed using the following syntax.
+
+                ```
+                $(<macro>)
+                ```
+
+                 Example:
+
+                ```
+                $(cc)
+                ```
+
+                `$(cc)`
+                Path to the C compiler.
+
+                `$(cxx)`
+                Path to the C++ compiler.
+
+                `$(cflags)`
+                Flags passed to the C compiler.
+
+                `$(cppflags)`
+                Flags passed to the C preprocessor.
+
+                `$(cxxflags)`
+                Flags passed to the C++ compiler.
+
+                `$(cxxppflags)`
+                Flags to pass to the C++ preprocessor.
+
+                `$(ld)`
+                Path to the linker.
+
+                `$(ldflags-pic)`
+                Flags passed to the linker for binaries that use
+                 position-independent code (PIC).
+
+                `$(ldflags-pic-filter <pattern>)`
+                Flags passed to the linker for binaries that use position-independent code (PIC).
+                 Use the *pattern* parameter to specify a regular expression that matches the build targets that use these flags.
+
+                `$(ldflags-shared)`
+                Flags passed to the linker for shared libraries, such as dynamic-link libraries (DLLs).
+
+                `$(ldflags-shared-filter <pattern>)`
+                Flags passed to the linker for shared libraries, such as dynamic-link libraries (DLLs).
+                 Use the *pattern* parameter to specify a regular expression that matches the build targets that use these flags.
+
+                `$(ldflags-static)`
+                Flags passed to the linker for statically-linked libraries.
+
+                `$(ldflags-static-filter <pattern>)`
+                Flags passed to the linker for statically-linked libraries.
+                 Use the *pattern* parameter to specify a regular expression that matches the build targets that use these flags.
+
+                #### Parameterized Macros
+
+                 It is also possible to expand references to other rules within the
+                 shell command, using the following subset of the
+                 builtin `string parameter macros`
+                .
+                 Note that all build rules expanded in the command are automatically
+                 considered to be dependencies of the `genrule()`.
+
+                 Note that the paths returned by these macros are *absolute* paths. You should convert these paths to be relative paths before
+                 embedding them in, for example, a shell script or batch file. Using
+                 relative paths ensures that your builds are *hermetic*, that
+                 is, they are reproducible across different machine environments.
+
+                 Additionally, if you embed these paths in a shell script, you should
+                 execute that script using the `sh_binary()` rule and include
+                 the targets for these paths in the `resources` argument of
+                 that `sh_binary` rule. These are the same targets that you
+                 pass to the string parameter macros.
+
+                `$(exe //path/to:target)`
+                Expands to the commands necessary to run the executable
+                 generated by the specified build rule. For a C++ executable, this
+                 will typically just be the name of the output executable itself,
+                 such as `main`. If the specified build rule does not generate an
+                 executable output, an exception will be thrown and the build will
+                 fail.
+
+                `$(location //path/to:target)`
+                Expands to the path of the output of the build rule. This
+                 means that you can refer to these without needing to be aware of
+                 how Buck is storing data on the disk mid-build.
+
+                #### Variables
+
+                 Finally, Buck adds the following variables to the environment in
+                 which the shell command runs. They are accessed using the following syntax.
+                 Note the use of braces rather than parentheses.
+
+                ```
+                ${<variable>}
+                ```
+
+                 Example:
+
+                ```
+                ${SRCS}
+                ```
+
+                `${SRCS}`
+                A string expansion of the `srcs` argument delimited by
+                 the `environment_expansion_separator` argument where each element
+                 of `srcs` will be translated into an absolute path.
+
+                `${SRCDIR}`
+                The absolute path to the to which sources are copied
+                 prior to running the command.
+
+                `${OUT}`
+                The output file for the `genrule()`. The file
+                 specified by this variable must always be written by this
+                 command. If not, the execution of this rule will be considered a
+                 failure, halting the build process.
+
+                `${TMP}`
+                A temporary directory which can be used for intermediate results and will not be
+                 bundled into the output.
+            """,
+            ),
+        }
+        | genrule_common.bash_arg()
+        | genrule_common.cmd_exe_arg()
+        | genrule_common.type_arg()
+        | genrule_common.weight_arg()
+        | genrule_common.out_arg()
+        | genrule_common.env_arg()
+        | genrule_common.environment_expansion_separator()
+        | {
+            "cacheable": attrs.option(attrs.bool(), default = None),
+            "default_outs": attrs.option(attrs.set(attrs.string(), sorted = False), default = None),
+            "enable_sandbox": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Whether this target should be executed in a sandbox or not.
+            """,
+            ),
+            "outs": attrs.option(attrs.dict(key = attrs.string(), value = attrs.set(attrs.string(), sorted = False), sorted = False), default = None),
+            "remote": attrs.option(attrs.bool(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+        | core_args.optional_has_content_based_path_attr()
+    ),
+)
+
+library_attrs = (
+    # @unsorted-dict-items
+    cxx_common.srcs_arg()
+    | cxx_common.flags_arg()
+    | cxx_common.headers_arg()
+    | cxx_common.exported_headers_arg()
+    | cxx_common.exported_header_style_arg()
+    | cxx_common.header_namespace_arg()
+    | cxx_common.preprocessor_flags_arg()
+    | cxx_common.lang_preprocessor_flags_arg()
+    | cxx_common.exported_preprocessor_flags_arg(exported_preprocessor_flags_type = attrs.list(attrs.arg(), default = []))
+    | cxx_common.exported_lang_preprocessor_flags_arg()
+    | cxx_common.compiler_flags_arg()
+    | cxx_common.lang_compiler_flags_arg()
+    | cxx_common.linker_extra_outputs_arg()
+    | cxx_common.linker_flags_arg()
+    | cxx_common.local_linker_flags_arg()
+    | cxx_common.exported_linker_flags_arg()
+    | cxx_common.exported_post_linker_flags_arg()
+    | native_common.link_style()
+    | native_common.link_whole(link_whole_type = attrs.option(attrs.bool(), default = None))
+    | native_common.soname()
+    | cxx_common.raw_headers_arg()
+    | cxx_common.supports_stripping()
+    | cxx_common.raw_headers_as_headers_mode_arg()
+    | cxx_common.include_directories_arg()
+    | cxx_common.public_include_directories_arg()
+    | cxx_common.public_system_include_directories_arg()
+    | {
+        "deffile": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+            Specifies the *.def file used on windows to modify a dll's exports in place of explicit `__declspec(dllexport)` declarations.
+              The default is to not use a defile.
+        """,
+        ),
+        "used_by_wrap_script": attrs.bool(
+            default = False,
+            doc = """
+            When using an exopackage
+              Android, if this parameter is set to `True`, then the library is
+              included in the primary APK even if native libraries would otherwise not be
+              placed in it. This is intended for native libraries that are used by a
+              [wrap.sh](https://developer.android.com/ndk/guides/wrap-script)
+              script, which must be placed in the primary APK. Only one of
+              `can_be_asset` and `used_by_wrap_script` can be set
+              for a rule.
+        """,
+        ),
+    }
+    | cxx_common.supported_platforms_regex_arg()
+    | cxx_common.force_static(force_static_type = attrs.option(attrs.bool(), default = None))
+    | native_common.preferred_linkage(preferred_linkage_type = attrs.option(attrs.enum(Linkage.values()), default = None))
+    | cxx_common.reexport_all_header_dependencies_arg()
+    | cxx_common.exported_deps_arg()
+    | cxx_common.precompiled_header_arg()
+    | apple_common.extra_xcode_sources()
+    | apple_common.extra_xcode_files()
+    | apple_common.uses_explicit_modules_arg()
+    | apple_common.meta_apple_library_validation_enabled_arg()
+    | cxx_common.version_arg()
+    | cxx_common.use_fbcc_rust_wrapper_arg()
+    | cxx_common.use_content_based_paths_arg()
+    | cxx_common.expect_eligible_for_dedupe_arg()
+    | validation_common.attrs_validators_arg()
+    | {
+        "archive_allow_cache_upload": attrs.bool(default = False),
+        "bridging_header": attrs.option(attrs.source(), default = None),
+        "can_be_asset": attrs.option(attrs.bool(), default = None),
+        "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),
+        "default_host_platform": attrs.option(attrs.configuration_label(), default = None),
+        "default_platform": attrs.option(attrs.string(), default = None),
+        "defaults": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),
+        "deps": attrs.list(attrs.dep(), default = []),
+        "devirt_enabled": attrs.bool(default = False),
+        "diagnostics": attrs.dict(key = attrs.string(), value = attrs.source(), sorted = False, default = {}),
+        "executable_name": attrs.option(attrs.string(), default = None),
+        "export_header_unit": attrs.option(
+            attrs.enum(["include", "preload"]),
+            default = None,
+            doc = """
+            If not None, export a C++20 header unit visible to dependants (including
+            recursively) with use_header_units set to True.
+
+            "include": replace includes of each file in exported_headers or
+                raw_headers with an import of the precompiled header unit; files
+                that do not include any of those headers do not load the header
+                unit.
+
+            "preload": automatically load the precompiled header unit in any
+                dependant that uses header units.
+        """,
+        ),
+        "export_header_unit_filter": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+            A list of regexes. Each regex should match a set of headers in
+            exported_headers or raw_headers to be precompiled together into one
+            C++20 header unit.
+
+            When used with export_header_unit="include", this allows different
+            subsets of headers to be loaded only by files that use them. Each group
+            should only depend on headers in previous groups.
+
+            If a header is not matched by any group, it is not precompiled and will
+            be included textually. If no filter is specified, the rule excludes
+            inline headers based on a name heuristics (e.g. "-inl.h").
+        """,
+        ),
+        "extra_dwp_flags": attrs.list(attrs.string(), default = []),
+        "fat_lto": attrs.bool(default = False),
+        "focused_list_target": attrs.option(attrs.dep(), default = None),
+        "frameworks": attrs.list(attrs.string(), default = []),
+        "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),
+        "include_in_android_merge_map_output": attrs.bool(default = True),
+        "libraries": attrs.list(attrs.string(), default = []),
+        "link_group": attrs.option(attrs.string(), default = None),
+        "link_group_map": LINK_GROUP_MAP_ATTR,
+        "module_name": attrs.option(attrs.string(), default = None),
+        "post_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+        "prefix_header": attrs.option(attrs.source(), default = None),
+        "resources": attrs.named_set(attrs.source(), sorted = True, default = []),
+        "sdk_modules": attrs.list(attrs.string(), default = []),
+        "static_library_basename": attrs.option(attrs.string(), default = None),
+        "supports_merged_linking": attrs.option(attrs.bool(), default = None),
+        "thin_lto": attrs.bool(default = False),
+        "use_archive": attrs.option(attrs.bool(), default = None),
+        "use_header_units": attrs.one_of(
+            attrs.bool(),
+            attrs.enum(["stub"]),
+            default = False,
+            doc = """
+            If True, makes any header unit exported by a dependency (including
+            recursively) through export_header_unit available to the compiler. If
+            false, the compilation ignores header units, regardless of what is
+            exported by dependencies. If "stub", uses stub header units instead
+            of full PCM files.
+        """,
+        ),
+        "uses_cxx_explicit_modules": attrs.bool(default = False),
+        "version_universe": attrs.option(attrs.string(), default = None),
+        "weak_framework_names": attrs.list(attrs.string(), default = []),
+    }
+    | buck.allow_cache_upload_arg()
+    | buck.licenses_arg()
+    | buck.labels_arg()
+    | buck.contacts_arg()
+)
+
+cxx_library = prelude_rule(
+    name = "cxx_library",
+    docs = """
+        A `cxx_library()` rule specifies a set of C/C++ source files
+        and also provides flags that specify how those files should be built.
+
+        #### Building requires a specified top-level target
+
+        Whether a Buck command builds the `cxx_library` is
+        determined by the inclusion of a top-level target, such as
+        a `cxx_binary()` or `android_binary()`, that
+        transitively depends on the `cxx_library`. The set of
+        targets specified to the Buck command (`buck build`, `buck run`, etc) must
+        include one of these top-level targets in order for Buck to build
+        the `cxx_library`. Note that you could specify the top-level target
+        implicitly using a `build target pattern` or you could also specify
+        the top-level target using a buckconfig `alias` defined in `.buckconfig`.
+
+        *How* Buck builds the library also depends on the specified top-level target.
+        For example, a C/C++ binary (`cxx_binary`) would require a static non-PIC build of the library,
+        whereas an Android APK (`android_binary`) would require a shared PIC-enabled build.
+        (PIC stands for position-independent code.)
+
+        #### Dependencies of the cxx\\_library also require a top-level target
+
+        Similarly, in order for Buck to build a target that
+        the `cxx_library` depends on, such as a `cxx_genrule()`,
+        you must specify in the Buck command a top-level target that depends on
+        the `cxx_library`. For example, you could specify
+        to `build` a `cxx_binary` that
+        depends on the `cxx_library`. If you specify as
+        your build target the `cxx_library` itself, the build targets
+        that the `cxx_library` depends on *might not be built*.
+    """,
+    examples = """
+        ```
+        # A rule that includes a single .cpp file and its corresponding header and
+        # also supplies an additional flag for compilation.
+        cxx_library(
+          name = 'fileutil',
+          srcs = [
+            'fileutil.cpp',
+          ],
+          exported_headers = [
+            'fileutil.h',
+          ],
+          compiler_flags = [
+            '-fno-omit-frame-pointer',
+          ],
+        )
+
+        # A rule that defines explicit names for its headers
+        cxx_library(
+          name = 'mathutils',
+          header_namespace = 'math',
+          srcs = [
+            'trig/src/cos.cpp',
+            'trig/src/tan.cpp',
+          ],
+          exported_headers = {
+            # These are included as <math/trig/cos.h> and <math/trig/tan.h>
+            'trig/cos.h': 'trig/include/cos.h',
+            'trig/tan.h': 'trig/include/tan.h',
+          },
+          compiler_flags = [
+            '-fno-omit-frame-pointer',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = library_attrs | cxx_common.default_deps_arg("exported_deps") | buck.allow_cache_upload_arg(),
+)
+
+cxx_precompiled_header = prelude_rule(
+    name = "cxx_precompiled_header",
+    docs = """
+        A `cxx_precompiled_header` rule specifies a single header file that can be
+         precompiled and made available for use in other build rules such as
+         a `cxx_library()` or a `cxx_binary()`.
+
+         This header file is precompiled by the preprocessor on behalf of the
+         C, C++, Objective-C, or Objective-C++ rule using it, via its `precompiled_header` parameter.
+         Afterwards the precompiled header is applied during the rule's own compilation
+         (often with an appreciable reduction in build time, the main benefit of PCH).
+
+         This PCH is built once per combination of build flags which might affect the PCH's compatibility.
+         For example, a distinct pre-compilation of the header occurs per combination of flags related to
+         optimization, debug, architecture, and so on, used by rules which employ PCH.
+         The flags used during the build of the dependent rule (that is, the "PCH-using rule")
+         are in effect while building the PCH itself. Similarly, to the same end, the include paths used
+         when building the PCH are applied to the dependent rule. For example, `deps` in the
+         PCH rule are propagated back to the dependent rule, and the PCH's header search paths
+         (e.g. `-I` or `-isystem` options) are prefixed onto the list of
+         include paths for the dependent rule.
+    """,
+    examples = """
+        The best way to see how the `cxx_precompiled_header()` rule works is with an
+        example. Let there be a header called `common.h` which has the following:
+
+        ```
+        #pragma once
+
+        /* Include common C++ files. */
+        #include <string>
+        #include <map>
+        #include <set>
+        #include <type_traits>
+        #include <vector>
+
+        /* Some frequently-used headers from the Folly project. */
+        #include <folly/Conv.h>
+        #include <folly/Executor.h>
+        #include <folly/io/async/EventBase.h>
+        ```
+
+        ```
+        cxx_precompiled_header(
+          name = 'common_pch',
+          src = 'common.h',
+          deps = [
+            # Needed for standard C++ headers:
+            '//external/libcxx:headers',
+            # Needed for the Folly includes:
+            '//folly:folly',
+            '//folly/io/async:async',
+          ],
+        )
+
+        cxx_binary(
+          name = 'main',
+          srcs = ['main.cpp'],
+          precompiled_header = ':common_pch',
+          deps = [ ... ],
+          compiler_flags = ['-g', '-O2', '-fPIC'],
+        )
+        ```
+
+        The `cxx_precompiled_header` rule declares a precompiled header "template"
+        containing the header file path, and dependencies.
+        In this example we indicate that `common.h` is to be precompiled when used by another build rule.
+
+        Note that, by itself, this `cxx_precompiled_header` rule will not result
+        in anything being built. The *usage* of this rule from another rule --
+        an "instantiation" of this precompiled header template -- is what will trigger the
+        PCH build.
+
+        In the example above, the build for the binary named `"main"` will depend on
+        the header being precompiled in a separate step, prior to compiling `main.cpp`,
+        and the resulting PCH will be used in `main`'s compilation.
+
+        The dependencies specified in this precompiled header rule's `deps` are transitive; they
+        will propagate to rules using this PCH, so that during link time, any libraries which are
+        required by the code made available in the header will be included in the final binary build.
+
+        The precompiled header dynamically created from the "template" will be built with flags
+        which would be used in the dependent rule. In this case, `main`'s use of specific
+        compiler flags `-g -O2 -fPIC` will result in the production of a precompiled header
+        with the same flags. This is so the precompiled code fully jives with rules using the PCH,
+        i.e. they will have the same debug, optimization, CPU, etc. options. (The compiler is usually
+        smart enough to reject a bad PCH, fortunately. But we want to ensure we take the appropriate
+        steps to ensure we *always have* a PCH which works with any build that uses it.)
+
+        Another effect of a rule using a precompiled header is that the rule's list of
+        build flags will change; not just to employ PCH with e.g. `-include-pch` (if using Clang), but also, to alter the sequence of header search paths.
+        The rule using the precompiled header will "inherit" the lists of paths used
+        during the PCH build, applying them *first* in its own search paths.
+        This is to ensure that an `#include` directive will resolve in exactly
+        the same way in this build as it would have in the PCH, to ensure full compatibility
+        between the PCH and other rule's builds. For example, if the PCH were to use one version
+        of `stdcxx` and another rule use a different version, the version differences
+        won't clash, thereby avoiding different versions of the `<cstring>` header
+        used between the precompiled header and the dependent rule, and preventing confused
+        structure definitions, ABI incompatibility, and so on (catastrophe, in other words).
+    """,
+    further = None,
+    attrs = (
+        cxx_common.use_fbcc_rust_wrapper_arg()
+        | {
+            "compile_pch_file": attrs.bool(
+                default = False,
+                doc = """
+                Whether to compile the precompiled header file or use legacy mode.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Dependency rules which export headers used by the header specified in `src`.
+            """,
+            ),
+            "pch_clanguage": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The c-language extension to use for the precompiled header. Eg. .c, .cpp, .m, .mm, etc.
+            """,
+            ),
+            "src": attrs.source(
+                doc = """
+                The path to the header file that should be precompiled.
+                 Only one header file can be specified. But of course this header could include
+                 any number of other headers. The included headers could belong to -- that is,
+                 be `exported_headers` from -- another rule, in which case, the rule would
+                 have to be added to `deps` as usual.
+            """
+            ),
+            "version_universe": attrs.option(attrs.string(), default = None),
+        }
+        | library_attrs
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+cxx_flags = prelude_rule(
+    name = "cxx_flags",
+    docs = """
+        A `cxx_flags()` target holds flags that C++ targets pull in through their
+        `flags` attribute. Its `deps` can reference other `cxx_flags`
+        targets; nested flags apply before the including target's flags, and all
+        shared flags apply before the consuming C++ target's own flags.
+
+        Consumers share a compiler argsfile for the transitive flag set.
+
+        Write-to-file macros (`$(@...)`) are unsupported in all flag attributes.
+    """,
+    examples = """
+        ```
+        cxx_flags(
+          name = "common_warnings",
+          compiler_flags = ["-Wall", "-Wextra"],
+        )
+
+        cxx_library(
+          name = "lib",
+          srcs = ["lib.cpp"],
+          flags = [":common_warnings"],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        {
+            "compiler_flags": attrs.list(attrs.arg(), default = []),
+            "deps": attrs.list(attrs.dep(providers = [CxxFlagsInfo]), default = []),
+            "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "preprocessor_flags": attrs.list(attrs.arg(), default = []),
+        }
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+windows_resource = prelude_rule(
+    name = "windows_resource",
+    docs = """
+        A `windows_resource()` rule specifies a set of Window's Resource File (.rc) that
+        are compiled into object files.
+
+        The files are compiled into .res files using rc.exe and then compiled into object files
+        using cvtres.exe.
+        They are not part of cxx_library because Microsoft's linker ignores the resources
+        unless they are specified as an object file, meaning including them in a possibly static
+        library is unintuitive.
+    """,
+    examples = """
+        ```
+        # A rule that includes a single .rc file and compiles it into an object file.
+        windows_resource(
+          name = "resources",
+          srcs = [
+            "resources.rc",
+          ],
+        )
+
+        # A rule that links against the above windows_resource rule.
+        cxx_binary(
+          name = "app",
+          srcs = [
+            "main.cpp",
+          ],
+          deps = [
+            ":resources"
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        cxx_common.srcs_arg()
+        | cxx_common.headers_arg()
+        | cxx_common.header_namespace_arg()
+        | cxx_common.raw_headers_arg()
+        | cxx_common.include_directories_arg()
+        | {
+            "deps": attrs.list(attrs.dep(), default = []),
+        }
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+cxx_test = prelude_rule(
+    name = "cxx_test",
+    docs = """
+        A cxx\\_test() rule builds a C/C++ binary against a C/C++ testing framework and runs
+        it as part of `test`.
+    """,
+    examples = """
+        ```
+        # A rule that builds and runs C/C++ test using gtest.
+        cxx_test(
+          name = 'echo_test',
+          srcs = [
+            'echo_test.cpp',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.inject_test_env_arg()
+        | cxx_common.srcs_arg()
+        | cxx_common.headers_arg()
+        | cxx_common.default_deps_arg()
+        | cxx_common.preprocessor_flags_arg()
+        | cxx_common.compiler_flags_arg()
+        | cxx_common.linker_flags_arg()
+        | cxx_common.precompiled_header_arg()
+        | buck.deps_query_arg()
+        | {
+            "resources": attrs.named_set(
+                attrs.source(),
+                sorted = True,
+                default = [],
+                doc = """
+                This attribute is currently not implemented, and just causes buck to rebuild
+                 the test file if any of the resources change. This will change in the future
+                 to provide a more reliable interface for resource files.
+
+                 Additional data or source files which this test uses.
+            """,
+            ),
+        }
+        | cxx_common.raw_headers_arg()
+        | cxx_common.raw_headers_as_headers_mode_arg()
+        | cxx_common.include_directories_arg()
+        | cxx_common.runtime_dependency_handling_arg()
+        | cxx_common.use_fbcc_rust_wrapper_arg()
+        | cxx_common.use_content_based_paths_arg()
+        | {
+            "args": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                A list of additional arguments to pass to the test when it's run.
+
+                 It is also possible to expand references to other rules within these
+                 arguments, using builtin `string parameter macros`
+                :
+
+                `$(location //path/to:target)`
+                Expands to the location of the output of the build rule. This
+                 means that you can refer to these without needing to be aware of how
+                 Buck is storing data on the disk mid-build.
+            """,
+            ),
+            "env": attrs.dict(
+                key = attrs.string(),
+                value = attrs.arg(),
+                sorted = False,
+                default = {},
+                doc = """
+                A map of environment names and values to set when running the test.
+
+                 It is also possible to expand references to other rules within the **values** of
+                 these environment variables, using builtin `string parameter macros`
+                :
+
+                `$(location //path/to:target)`
+                Expands to the location of the output of the build rule. This
+                 means that you can refer to these without needing to be aware of how
+                 Buck is storing data on the disk mid-build.
+            """,
+            ),
+            "framework": attrs.option(
+                attrs.enum(CxxTestType),
+                default = None,
+                doc = """
+                Unused.
+            """,
+            ),
+        }
+        | buck.run_test_separately_arg(run_test_separately_type = attrs.option(attrs.bool(), default = None))
+        | buck.test_rule_timeout_ms()
+        | native_common.link_group_deps()
+        | native_common.link_group_public_deps_label()
+        | native_common.transformation_spec_arg()
+        | native_common.link_style()
+        | {
+            "additional_coverage_targets": attrs.list(attrs.source(), default = []),
+            "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),
+            "default_platform": attrs.option(attrs.string(), default = None),
+            "defaults": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "devirt_enabled": attrs.bool(default = False),
+            "executable_name": attrs.option(attrs.string(), default = None),
+            "fat_lto": attrs.bool(default = False),
+            "focused_list_target": attrs.option(attrs.dep(), default = None),
+            "frameworks": attrs.list(attrs.string(), default = []),
+            "header_namespace": attrs.option(attrs.string(), default = None),
+            "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),
+            "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "libraries": attrs.list(attrs.string(), default = []),
+            "link_deps_query_whole": attrs.bool(default = False),
+            "link_group": attrs.option(attrs.string(), default = None),
+            "link_group_map": LINK_GROUP_MAP_ATTR,
+            "linker_extra_outputs": attrs.list(attrs.string(), default = []),
+            "post_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "prefer_stripped_objects": attrs.bool(default = False),
+            "prefix_header": attrs.option(attrs.source(), default = None),
+            "supports_test_execution_caching": attrs.bool(default = False),
+            "thin_lto": attrs.bool(default = False),
+            "use_default_test_main": attrs.option(attrs.bool(), default = None),
+            "use_header_units": attrs.one_of(
+                attrs.bool(),
+                attrs.enum(["stub"]),
+                default = False,
+                doc = """
+                If True, makes any header unit exported by a dependency (including
+                recursively) through export_header_unit available to the compiler. If
+                false, the compilation ignores header units, regardless of what is
+                exported by dependencies. If "stub", uses stub header units instead
+                of full PCM files.
+            """,
+            ),
+            "version_universe": attrs.option(attrs.string(), default = None),
+            "weak_framework_names": attrs.list(attrs.string(), default = []),
+        }
+        | buck.allow_cache_upload_arg()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+        | test_common.attributes()
+        | _cxx_binary_and_test_attrs()
+    ),
+    # @oss-disable[end= ]: cfg = constraint_overrides.transition,
+    supports_incoming_transition = True, # @oss-enable
+)
+
+cxx_toolchain = prelude_rule(
+    name = "cxx_toolchain",
+    docs = """
+        A `cxx_toolchain()` rule declares a complete C/C++ toolchain — a
+        set of compilers (C, C++, Objective-C, asm, CUDA, HIP, etc.),
+        preprocessors, linker, archiver, and binary utilities (`strip`,
+        `objcopy`, `dwp`, `nm`, etc.) — along with the flags and behavior
+        options that control how each tool is invoked.
+
+        Native rules (`cxx_binary()`, `cxx_library()`, `cxx_test()`,
+        `prebuilt_cxx_library()`, etc.) and rules in other languages that
+        ultimately link native code (e.g. `python_binary()`,
+        `rust_binary()`, `haskell_binary()`) consume a `cxx_toolchain()`
+        via a toolchain dependency to compile and link their outputs.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        cxx_common.raw_headers_as_headers_mode_arg()
+        | {
+            "archive_contents": attrs.enum(ArchiveContentsType.values(), default = "normal"),
+            "archiver": attrs.source(),
+            "archiver_flags": attrs.list(attrs.arg(), default = []),
+            "archiver_type": attrs.enum(ArchiverProviderType),
+            "asm_compiler": attrs.option(attrs.source(), default = None),
+            "asm_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "asm_compiler_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "asm_preprocessor": attrs.option(attrs.source(), default = None),
+            "asm_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+            "asm_preprocessor_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "assembler": attrs.source(),
+            "assembler_flags": attrs.list(attrs.arg(), default = []),
+            "assembler_preprocessor": attrs.option(attrs.source(), default = None),
+            "assembler_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+            "assembler_preprocessor_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "assembler_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "binary_extension": attrs.option(attrs.string(), default = None),
+            "binary_linker_flags": attrs.list(
+                attrs.arg(anon_target_compatible = True),
+                default = [],
+                doc = """
+                Linker flags that apply to all links coordinated by a binary
+                rule.  One key distinction between these and `executable_linker_flags`
+                is that these will also apply to library links coordinated by
+                binary rules (e.g. linking roots/deps when using native python or
+                omnibus link strategies).
+                """,
+            ),
+            "bolt": attrs.source(),
+            "c_compiler": attrs.source(),
+            "c_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "c_compiler_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "c_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+            "cache_links": attrs.bool(default = False),
+            "compiler_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "cuda_compiler": attrs.option(attrs.source(), default = None),
+            "cuda_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "cuda_compiler_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "cuda_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+            "custom_tools": attrs.dict(key = attrs.string(), value = attrs.source(), default = {}),
+            "cvtres_compiler": attrs.option(attrs.source(), default = None),
+            "cvtres_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "cvtres_compiler_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "cvtres_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+            "cxx_compiler": attrs.source(),
+            "cxx_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "cxx_compiler_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "cxx_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+            "debug_path_prefix_map_sanitizer_format": attrs.option(attrs.string(), default = None),
+            "dist_thin_lto_codegen_flags": attrs.list(attrs.arg(), default = []),
+            "executable_linker_flags": attrs.list(
+                attrs.arg(anon_target_compatible = True),
+                default = [],
+                doc = """
+                Linker flags that only apply when linking an executable.
+                """,
+            ),
+            "extra_linker_outputs": attrs.set(attrs.string(), default = []),
+            "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),
+            "hip_compiler": attrs.option(attrs.source(), default = None),
+            "hip_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "hip_compiler_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "hip_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+            "link_metadata_flag": attrs.option(attrs.string(), default = None),
+            "link_style": attrs.enum(
+                LinkStyle.values(),
+                default = "static",
+                doc = """
+                The default value of the `link_style` attribute for rules that use this toolchain.
+                """,
+            ),
+            "linker": attrs.source(),
+            "linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "linker_type": attrs.enum(LinkerProviderType),
+            "nm": attrs.source(),
+            "objc_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "objcopy_for_shared_library_interface": attrs.source(),
+            "objcxx_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "objdump": attrs.option(attrs.source(), default = None),
+            "object_file_extension": attrs.string(default = ""),
+            "post_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "private_headers_symlinks_enabled": attrs.bool(default = False),
+            "public_headers_symlinks_enabled": attrs.bool(default = False),
+            "ranlib": attrs.option(attrs.source(), default = None),
+            "ranlib_flags": attrs.list(attrs.arg(), default = []),
+            "rc_compiler": attrs.option(attrs.source(), default = None),
+            "rc_compiler_flags": attrs.list(attrs.arg(), default = []),
+            "rc_compiler_type": attrs.option(attrs.enum(CXX_COMPILER_TYPES), default = None),
+            "rc_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+            "requires_archives": attrs.bool(default = False),
+            "shared_dep_runtime_ld_flags": attrs.list(attrs.arg(), default = []),
+            "shared_library_extension": attrs.string(default = ""),
+            "shared_library_interface_flags": attrs.list(attrs.string(), default = []),
+            "shared_library_versioned_extension_format": attrs.string(default = ""),
+            "static_dep_runtime_ld_flags": attrs.list(attrs.arg(), default = []),
+            "static_library_extension": attrs.string(default = ""),
+            "static_pic_dep_runtime_ld_flags": attrs.list(attrs.arg(), default = []),
+            "strip": attrs.source(),
+            "strip_all_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+            "strip_debug_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+            "strip_non_global_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+            "use_header_map": attrs.bool(default = False),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+prebuilt_cxx_library = prelude_rule(
+    name = "prebuilt_cxx_library",
+    docs = """
+        A `prebuilt_cxx_library()` rule represents a set of native libraries and C/C++ header
+        files and provides various flags to control how they are linked and exported.
+    """,
+    examples = """
+        A prebuilt library containing only headers that other libraries may need.
+
+        ```
+        prebuilt_cxx_library(
+          name = 'stdutil',
+          header_only = True,
+          header_dirs = [
+            'include',
+          ],
+        )
+        ```
+
+         A prebuilt library with static and shared libs.
+
+        ```
+        prebuilt_cxx_library(
+          name = 'mylib',
+          soname = 'libmylib.so',
+          static_lib = 'libmylib.a',
+          static_pic_lib = 'libmylib_pic.a',
+          shared_lib = 'libmylib.so',
+          exported_headers = [
+            'mylib.h',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        {
+            "header_dirs": attrs.option(
+                attrs.list(attrs.source()),
+                default = None,
+                doc = """
+                A directory that headers can be included from. These directories are added
+                 to the include path using `-isystem`.
+            """,
+            ),
+            "header_only": attrs.bool(
+                default = False,
+                doc = """
+                Indicates if this library only consists of headers or not. If this is set to
+                 `True`, Buck will not link this library into any library that depends on it.
+            """,
+            ),
+            "shared_lib": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                The path to the library to use when performing shared linking.
+            """,
+            ),
+            "static_lib": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                The path to the library to use when performing static linking.
+            """,
+            ),
+            "static_pic_lib": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                The path to the library to use when performing static PIC linking.
+            """,
+            ),
+        }
+        | cxx_common.supported_platforms_regex_arg()
+        | cxx_common.exported_headers_arg()
+        | cxx_common.header_namespace_arg()
+        | cxx_common.exported_preprocessor_flags_arg(exported_preprocessor_flags_type = attrs.list(attrs.arg(), default = []))
+        | cxx_common.exported_linker_flags_arg()
+        | cxx_common.force_static(force_static_type = attrs.bool(default = False))
+        | native_common.preferred_linkage(preferred_linkage_type = attrs.option(attrs.enum(Linkage.values()), default = None))
+        | cxx_common.exported_deps_arg()
+        | cxx_common.default_deps_arg("exported_deps")
+        | cxx_common.supports_merged_linking()
+        | cxx_common.local_linker_flags_arg()
+        | cxx_common.local_linker_script_flags_arg()
+        | cxx_common.version_arg()
+        | {
+            "can_be_asset": attrs.bool(default = False),
+            "deffile": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                Specifies the *.def file used on windows to modify a dll's exports in place of explicit `__declspec(dllexport)` declarations.
+                 The default is to not use a defile.
+            """,
+            ),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "exported_lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "exported_post_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "extract_soname": attrs.bool(default = False),
+            "frameworks": attrs.list(attrs.string(), default = []),
+            "import_lib": attrs.option(attrs.source(), default = None),
+            "include_in_android_merge_map_output": attrs.bool(default = True),
+            "libraries": attrs.list(attrs.string(), default = []),
+            "link_whole": attrs.bool(default = False),
+            "link_without_soname": attrs.bool(default = False),
+            "platform_import_lib": attrs.option(attrs.list(attrs.tuple(attrs.regex(), attrs.source())), default = None),
+            "prestripped": attrs.bool(default = False, doc = "When set, skips running `strip` commands when building this library."),
+            "provided": attrs.bool(default = False),
+            "soname": attrs.option(attrs.string(), default = None),
+            "supports_shared_library_interface": attrs.bool(default = True),
+            "versioned_exported_lang_preprocessor_flags": attrs.versioned(
+                attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False)
+            ),
+            "versioned_exported_preprocessor_flags": attrs.versioned(attrs.list(attrs.arg())),
+            "versioned_header_dirs": attrs.option(attrs.versioned(attrs.list(attrs.source())), default = None),
+            "versioned_import_lib": attrs.option(attrs.versioned(attrs.source()), default = None),
+            "versioned_shared_lib": attrs.option(attrs.versioned(attrs.source()), default = None),
+            "versioned_soname": attrs.option(attrs.versioned(attrs.string()), default = None),
+            "versioned_static_lib": attrs.option(attrs.versioned(attrs.source()), default = None),
+            "versioned_static_pic_lib": attrs.option(attrs.versioned(attrs.source()), default = None),
+        }
+        | buck.allow_cache_upload_arg()
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+prebuilt_cxx_library_group = prelude_rule(
+    name = "prebuilt_cxx_library_group",
+    docs = """
+        A `prebuilt_cxx_library_group()` rule represents a group of native libraries which should
+        be handled together in a single rule, perhaps using special link-line construction.
+    """,
+    examples = """
+        A prebuilt library group wrapping two libraries that must be linked together.
+
+        ```
+        prebuilt_cxx_library_group(
+          name = 'util',
+          static_link = [
+            '-Wl,--start-group',
+            '$(lib 0)',
+            '$(lib 1)',
+            '-Wl,--end-group',
+          ],
+          static_libs = [
+            'lib/liba.a',
+            'lib/libb.a',
+          ],
+          static_pic_link = [
+            '-Wl,--start-group',
+            '$(lib 0)',
+            '$(lib 1)',
+            '-Wl,--end-group',
+          ],
+          static_libs = [
+            'lib/liba_pic.a',
+            'lib/libb_pic.a',
+          ],
+          shared_link = [
+            '$(rel-lib liba.so)',
+            '$(rel-lib libb.so)',
+          ],
+          shared_libs = {
+            'liba.so': 'lib/liba.so',
+          },
+          provided_shared_libs = {
+            'libb.so': 'lib/libb.so',
+          },
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        cxx_common.exported_preprocessor_flags_arg(exported_preprocessor_flags_type = attrs.list(attrs.string(), default = []))
+        | {
+            "provided_shared_libs": attrs.dict(
+                key = attrs.string(),
+                value = attrs.source(),
+                sorted = False,
+                default = {},
+                doc = """
+                The map of system-provided shared library names to paths used when using the shared link style.
+                 The `shared_link` parameter should refer to these libs using their library name.
+            """,
+            ),
+            "shared_libs": attrs.dict(
+                key = attrs.string(),
+                value = attrs.source(),
+                sorted = False,
+                default = {},
+                doc = """
+                The map of shared library names to paths used when using the shared link style.
+                 The `shared_link` parameter should refer to these libs using their library
+                 name.
+            """,
+            ),
+            "shared_link": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                The arguments to use when linking this library group using the shared link style.
+                 The actual paths to libraries should be listed in the `shared_libs`
+                 parameter, and referenced via the `$(lib [name])` macro (or the
+                 `$(rel-lib [name])` macro, when the shared library should be linked
+                 using the `-L[dir] -l[name]` style) in these args.
+            """,
+            ),
+            "static_libs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                The paths to the libraries used when using the static link style.
+                 The `static_link` parameter should refer to these libs using their index
+                 number.
+            """,
+            ),
+            "static_link": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                The arguments to use when linking this library group using the static link style.
+                 The actual paths to libraries should be listed in the `static_libs` parameter,
+                 and referenced via the `$(lib [index])` macro in these args.
+            """,
+            ),
+            "static_pic_libs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                The paths to the libraries used when using the static link style.
+                 The `static_pic_link` parameter should refer to these libs using their
+                 index number.
+            """,
+            ),
+            "static_pic_link": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                The arguments to use when linking this library group using the static-pic link style.
+                 The actual paths to libraries should be listed in the `static_pic_libs`
+                 parameter, and referenced via the `$(lib [index])` macro in
+                 these args.
+            """,
+            ),
+        }
+        | cxx_common.exported_deps_arg()
+        | cxx_common.version_arg()
+        | cxx_common.supported_platforms_regex_arg()
+        | {
+            "deps": attrs.list(attrs.dep(), default = []),
+            "import_libs": attrs.dict(key = attrs.string(), value = attrs.source(), sorted = False, default = {}),
+            "include_dirs": attrs.list(attrs.source(allow_directory = True), default = []),
+            "include_in_android_merge_map_output": attrs.bool(default = True),
+            "supports_shared_library_interface": attrs.bool(default = True),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+llvm_link_bitcode = prelude_rule(
+    name = "llvm_link_bitcode",
+    docs = """
+        An `llvm_link_bitcode()` rule combines a set of LLVM bitcode
+        inputs into a single bitcode object using `llvm-link`.
+
+        LLVM bitcode is the intermediate representation produced by Clang
+        when compiling with `-emit-llvm`; merging multiple bitcode files
+        into one allows downstream rules to perform whole-program
+        optimization, link-time optimization (LTO), or other
+        bitcode-level analyses on the combined module.
+
+        Inputs can be other `llvm_link_bitcode()` outputs, raw `.bc` /
+        `.o` files containing bitcode, or `cxx_library()` rules producing
+        bitcode artifacts.
+    """,
+    examples = """
+        ```
+        # A rule that builds and runs C/C++ test using gtest.
+        llvm_link_bitcode(
+          name = 'echo_test',
+          srcs = [
+            'echo_test.o',  // Where this is a LLVM bitcode object.
+            'echo_other.o', // And this is another LLVM bitcode object.
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        cxx_common.srcs_arg()
+        | buck.deps_query_arg()
+        | {
+            "deps": attrs.list(attrs.dep(), default = []),
+        }
+    ),
+)
+
+transformation_spec = prelude_rule(
+    name = "transformation_spec",
+    docs = """
+        A `transformation_spec()` rule declares a list of transformation
+        rules that map targets (by `Label`, by build target pattern, or
+        by build graph pattern) to a `TransformationKind`
+        (`debug` or `optimized`). Other rules can reference a
+        `transformation_spec()` via a `transformation_spec` attribute to
+        decide, on a per-dependency basis, which transformation should be
+        applied when building that dependency.
+        Exact `debug` and `optimized` meaning depends on
+        flags configured in toolchain for each flavor.
+    """,
+    examples = None,
+    further = None,
+    attrs = {},
+)
+
+cxx_rules = struct(
+    cxx_binary = cxx_binary,
+    cxx_genrule = cxx_genrule,
+    cxx_library = cxx_library,
+    cxx_flags = cxx_flags,
+    cxx_precompiled_header = cxx_precompiled_header,
+    windows_resource = windows_resource,
+    cxx_test = cxx_test,
+    cxx_toolchain = cxx_toolchain,
+    prebuilt_cxx_library = prebuilt_cxx_library,
+    prebuilt_cxx_library_group = prebuilt_cxx_library_group,
+    llvm_link_bitcode = llvm_link_bitcode,
+    transformation_spec = transformation_spec,
+)
diff --git a/buck2/prelude/decls/cython_rules.bzl b/buck2/prelude/decls/cython_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/cython_rules.bzl
@@ -0,0 +1,447 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:common.bzl", "buck", "prelude_rule")
+load("@prelude//decls:cxx_rules.bzl", "cxx_rules")
+load("@prelude//decls:python_common.bzl", "python_common")
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+
+cython_library = prelude_rule(
+    name = "cython_library",
+    docs = """
+        A rule that compiles Cython (.pyx) sources into Python C extensions.
+
+        This rule handles the full pipeline: Cython transpilation to C/C++,
+        compilation to shared libraries, and assembly into a Python library.
+    """,
+    attrs = (
+        # Inherit all cxx_library attrs as default_only so cxx_library_parameterized
+        # can access required attributes like supported_platforms_regex, preferred_linkage, etc.
+        # This mirrors how cxx_python_extension inherits these attrs.
+        # @unsorted-dict-items
+        {k: attrs.default_only(v) for k, v in cxx_rules.cxx_library.attrs.items()}
+        | python_common.base_module_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+        | {
+            "allow_embedding": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Whether to allow embedding this extension into the main binary.
+            """,
+            ),
+            "api": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                List of module names that should generate public API headers
+                (_api.h files) for C++ interop.
+            """,
+            ),
+            "code_comments": attrs.bool(
+                default = False,
+                doc = """
+                Whether to include source code comments in the generated output.
+            """,
+            ),
+            "cpp_compiler_flags": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                Additional flags to pass to the C++ compiler.
+            """,
+            ),
+            "cpp_deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                C++ library dependencies for linking.
+            """,
+            ),
+            "cpp_external_deps": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                External C++ dependencies specified by name.
+            """,
+            ),
+            "cpp_preprocessor_flags": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                Additional C++ preprocessor flags.
+            """,
+            ),
+            "cpp_python_extension_srcs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Additional C++ source files to compile into the Python extensions.
+            """,
+            ),
+            "cython_annotate": attrs.option(
+                attrs.enum(["off", "basic", "fullc"]),
+                default = None,
+                doc = """
+                Level of Cython annotation to generate.
+            """,
+            ),
+            "cython_binding": attrs.bool(
+                default = False,
+                doc = """
+                Whether this is a Cython binding module.
+            """,
+            ),
+            "cython_compiler": attrs.option(
+                attrs.dep(providers = [RunInfo]),
+                default = None,
+                doc = """
+                Override the default Cython compiler.
+            """,
+            ),
+            "cython_so_package": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Override the package path for the generated .so file.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Dependencies of this rule, including other cython_library
+                and python_library targets.
+            """,
+            ),
+            "flags": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                Additional flags to pass to the Cython compiler.
+            """,
+            ),
+            "generate_cpp": attrs.bool(
+                default = True,
+                doc = """
+                Whether to generate C++ (.cpp) or C (.c) output from Cython.
+            """,
+            ),
+            "header_namespace": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                A namespace for the exported headers. If set, headers will be
+                available under this namespace for dependent rules.
+            """,
+            ),
+            "headers": attrs.named_set(
+                attrs.source(),
+                sorted = True,
+                default = [],
+                doc = """
+                Cython header files (.pxd) to expose to dependent Cython rules.
+            """,
+            ),
+            "includes": attrs.named_set(
+                attrs.source(),
+                sorted = True,
+                default = [],
+                doc = """
+                Additional Cython include files (.pxd, .pxi) for this library.
+            """,
+            ),
+            "legacy_noexcept": attrs.bool(
+                default = True,
+                doc = """
+                Whether to use legacy implicit noexcept behavior.
+            """,
+            ),
+            "need_static_lib": attrs.bool(
+                default = False,
+                doc = """
+                Whether to also produce a static C++ library.
+            """,
+            ),
+            # Override inherited cxx_library attrs that need concrete defaults
+            "preferred_linkage": attrs.enum(["any", "static", "shared"], default = "any"),
+            "public_declarations": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                List of public declaration module names.
+            """,
+            ),
+            "python_deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Python-only dependencies.
+            """,
+            ),
+            "python_external_deps": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                External Python dependencies specified by name.
+            """,
+            ),
+            "srcs": attrs.named_set(
+                attrs.source(),
+                sorted = True,
+                default = [],
+                doc = """
+                The Cython source files (.pyx) and header files (.pxd, .pxi)
+                to include in this library.
+            """,
+            ),
+            "suffix_all": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Whether to suffix all symbols for static linking.
+            """,
+            ),
+            "types": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Type stub files (.pyi) for the generated modules.
+            """,
+            ),
+            "typing": attrs.bool(
+                default = False,
+                doc = """
+                Whether to enable type checking support.
+            """,
+            ),
+            # Private/toolchain attrs
+            "_cxx_toolchain": toolchains_common.cxx(),
+            "_cython_toolchain": toolchains_common.cython(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_python_toolchain": toolchains_common.python(),
+            "_target_os_type": buck.target_os_type_arg(),
+        }
+    ),
+)
+
+cython_static_extension = prelude_rule(
+    name = "cython_static_extension",
+    docs = """
+        A rule that compiles a single Cython (.pyx) source into a statically-linkable
+        Python C extension.
+
+        Similar to cython_library but simplified for single-source use and
+        produces extensions suitable for static linking into binaries.
+    """,
+    attrs = (
+        # Inherit all cxx_library attrs as default_only so cxx_library_parameterized
+        # can access required attributes like supported_platforms_regex, preferred_linkage, etc.
+        # @unsorted-dict-items
+        {k: attrs.default_only(v) for k, v in cxx_rules.cxx_library.attrs.items()}
+        | python_common.base_module_arg()
+        | {
+            "compiler_flags": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                Additional C++ compiler flags.
+            """,
+            ),
+            "cython_binding": attrs.bool(
+                default = False,
+                doc = """
+                Whether this is a Cython binding module.
+            """,
+            ),
+            "cython_code_comments": attrs.bool(
+                default = False,
+                doc = """
+                Whether to include source code comments in the generated output.
+            """,
+            ),
+            "cython_compiler": attrs.option(
+                attrs.dep(providers = [RunInfo]),
+                default = None,
+                doc = """
+                Override the default Cython compiler.
+            """,
+            ),
+            "cython_deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Cython-specific dependencies (other cython_library or
+                cython_static_extension targets).
+            """,
+            ),
+            "cython_fast_fail": attrs.bool(
+                default = True,
+                doc = """
+                Whether to enable --fast-fail for Cython compilation.
+            """,
+            ),
+            "cython_flags": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                Additional flags to pass to the Cython compiler.
+            """,
+            ),
+            "cython_generate_cpp": attrs.bool(
+                default = True,
+                doc = """
+                Whether to generate C++ (.cpp) or C (.c) output.
+            """,
+            ),
+            "cython_headers": attrs.one_of(
+                attrs.list(attrs.source()),
+                attrs.dict(attrs.string(), attrs.source()),
+                doc = """
+                    Cython header files (.pxd) for this extension.
+                    Can be a list of sources or a dict mapping names to sources.
+                """,
+            ),
+            "cython_includes": attrs.one_of(
+                attrs.list(attrs.source()),
+                attrs.dict(attrs.string(), attrs.source()),
+                doc = """
+                    Cython include files (.pxd, .pxi) for this extension.
+                    Can be a list of sources or a dict mapping names to sources.
+                """,
+            ),
+            "cython_pyx": attrs.source(
+                doc = """
+                The single Cython .pyx source file.
+            """
+            ),
+            "cython_pyx_on_disk": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                Optional on-disk override for the .pyx source.
+            """,
+            ),
+            "cython_version": attrs.enum(
+                ["2", "3", "3str"],
+                default = "3",
+                doc = """
+                The Cython language version to target.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                C++ library dependencies.
+            """,
+            ),
+            "legacy_noexcept": attrs.bool(
+                default = True,
+                doc = """
+                Whether to use legacy implicit noexcept behavior.
+            """,
+            ),
+            # Override inherited cxx_library attrs that need concrete defaults
+            "preferred_linkage": attrs.enum(["any", "static", "shared"], default = "any"),
+            "preprocessor_flags": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                Additional C++ preprocessor flags.
+            """,
+            ),
+            "public_deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Public C++ dependencies that are re-exported.
+            """,
+            ),
+            "public_include_directories": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                Public include directories for C++ consumers.
+            """,
+            ),
+            "python_deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Python dependencies.
+            """,
+            ),
+            "python_types": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Type stub files (.pyi) for the generated extension.
+            """,
+            ),
+            "raw_headers": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Raw C/C++ header files.
+            """,
+            ),
+            # cxx attrs
+            "srcs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Additional C/C++ source files to compile alongside the
+                Cython-generated source.
+            """,
+            ),
+            # Toolchain attrs
+            "_cxx_toolchain": toolchains_common.cxx(),
+            "_cython_toolchain": toolchains_common.cython(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_python_toolchain": toolchains_common.python(),
+            "_target_os_type": buck.target_os_type_arg(),
+        }
+    ),
+)
+
+cython_toolchain_rule = prelude_rule(
+    name = "cython_toolchain",
+    docs = """
+        A toolchain rule that provides the Cython compiler configuration.
+
+        Python version-based compiler selection is handled via select() +
+        py_version_select() on the "compiler" attribute in the toolchain
+        BUCK definition, mirroring the fbsource//third-party/pypi/cython:compiler
+        alias pattern.
+    """,
+    is_toolchain_rule = True,
+    attrs = {
+        "compiler": attrs.dep(
+            providers = [RunInfo],
+            doc = """
+            The Cython compiler binary target. Use select() + py_version_select()
+            to vary the compiler by Python version.
+        """,
+        ),
+        "default_flags": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+            Default flags to pass to the Cython compiler.
+        """,
+        ),
+    },
+)
+
+cython_rules = struct(
+    cython_library = cython_library,
+    cython_static_extension = cython_static_extension,
+    cython_toolchain = cython_toolchain_rule,
+)
diff --git a/buck2/prelude/decls/dotnet_rules.bzl b/buck2/prelude/decls/dotnet_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/dotnet_rules.bzl
@@ -0,0 +1,156 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load(":common.bzl", "buck", "prelude_rule")
+
+FrameworkVersion = ["net35", "net40", "net45", "net46"]
+
+csharp_library = prelude_rule(
+    name = "csharp_library",
+    docs = """
+        A csharp\\_library() rule builds a .Net library from the supplied set of C# source files
+         and dependencies by invoking csc.
+    """,
+    examples = """
+        For more examples, check out our [integration tests](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/rust/testdata/).
+
+        ```
+        csharp_library(
+          name = 'simple',
+          dll_name = 'Cake.dll',
+          framework_ver = 'net46',
+          srcs = [
+            'Hello.cs',
+          ],
+          resources = {
+            'greeting.txt': '//some:target',
+          },
+          deps=[
+            ':other',
+            'System.dll',
+          ],
+        )
+
+        prebuilt_dotnet_library(
+          name = 'other',
+          assembly = 'other-1.0.dll',
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "dll_name": attrs.string(
+                default = "",
+                doc = """
+                The output name of the dll. This allows you to specify the name of
+                 the dll exactly. When this is not set, the dll will be named after
+                 the short name of the target.
+            """,
+            ),
+            "srcs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                The collection of source files to compile.
+            """,
+            ),
+            "resources": attrs.dict(
+                key = attrs.string(),
+                value = attrs.source(),
+                sorted = False,
+                default = {},
+                doc = """
+                Resources that should be embedded within the built DLL. The format
+                 is the name of the resource once mapped into the DLL as the key, and
+                 the value being the resource that should be merged. This allows
+                 non-unique keys to be identified quickly.
+            """,
+            ),
+            "framework_ver": attrs.enum(
+                FrameworkVersion,
+                doc = """
+                The version of the .Net framework that this library targets. This is
+                 one of 'net35', 'net40', 'net45' and 'net46'.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.one_of(attrs.dep(), attrs.string()),
+                default = [],
+                doc = """
+                The set of targets or system-provided assemblies to rely on. Any
+                 values that are targets must be either csharp\\_library or `prebuilt_dotnet_library`
+                 instances.
+            """,
+            ),
+            "compiler_flags": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                The set of additional compiler flags to pass to the compiler.
+            """,
+            ),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+prebuilt_dotnet_library = prelude_rule(
+    name = "prebuilt_dotnet_library",
+    docs = """
+        A `prebuilt_dotnet_library()` rule is used to include
+        prebuilt .Net assembles into your .Net code.
+    """,
+    examples = """
+        ```
+        prebuilt_dotnet_library(
+          name = 'log4net',
+          assembly = 'log4net.dll',
+        )
+
+        csharp_library(
+          name = 'example',
+          srcs = [
+            'Hello.cs',
+          ],
+          framework_ver = 'net46',
+          deps = [
+            ':log4net',
+            'System.dll',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "assembly": attrs.source(
+                doc = """
+                The path to the DLL that this rule provides.
+            """
+            ),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+dotnet_rules = struct(
+    csharp_library = csharp_library,
+    prebuilt_dotnet_library = prebuilt_dotnet_library,
+)
diff --git a/buck2/prelude/decls/erlang_rules.bzl b/buck2/prelude/decls/erlang_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/erlang_rules.bzl
@@ -0,0 +1,838 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//erlang:erlang_application.bzl", "StartTypeValues")
+load("@prelude//erlang:erlang_info.bzl", "ErlangAppIncludeInfo", "ErlangAppInfo", "ErlangAppOrTestInfo")
+load(":common.bzl", "buck", "prelude_rule")
+load(":re_test_common.bzl", "re_test_common")
+load(":test_common.bzl", "test_common")
+
+common_attributes = (
+    buck.labels_arg()
+    | buck.contacts_arg()
+    | {
+        "os_env": attrs.option(
+            attrs.dict(key = attrs.string(), value = attrs.string()),
+            default = None,
+            doc = """
+                This attribute allows to set additional values for the operating system environment for invocations to the
+                Erlang toolchain.
+            """,
+        ),
+    }
+)
+
+common_shell_attributes = {
+    "shell_configs": attrs.set(
+        attrs.dep(),
+        default = read_root_config("erlang", "shell_configs", "").split(),
+        doc = """
+            This attribute allows to set config files for the shell. The dependencies that are typically used
+            here are `export_file` targets.
+        """,
+    ),
+    "shell_libs": attrs.set(
+        attrs.dep(providers = [ErlangAppInfo]),
+        default = ["prelude//erlang/shell:buck2_shell_utils"],
+        doc = """
+            This attribute allows to define additional dependencies for the shell. By default this is
+            set to `["prelude//erlang/shell:buck2_shell_utils"]` which includes a `user_default` module
+            that loads and compiles modules with buck2 mechanisms.
+        """,
+    ),
+}
+
+common_application_attributes = {
+    "applications": attrs.list(
+        attrs.dep(providers = [ErlangAppInfo]),
+        default = [],
+        doc = """
+        Equivalent to the corresponding `applications` and `included_applications`
+        fields you will find in `*.app.src` or `*.app` files and specify the application dependencies. Contrary to the
+        fields in the `*.app.src` or `*.app` files, **it is necessary to use target paths to the application** where a
+        dependency is desired. These fields will be used to construct equally named fields in the generated `*.app` file
+        for the application.
+
+        OTP applications are specified with the target path `prelude//erlang/applications:<application>`.
+
+        **NOTE**: _If you use the `app_src` field and the references application resource file template specifies
+        `applications` or `included_applications` buck2 checks that the target definitions and information in the template are
+        equivalent to prevent these definitions from drifting apart during migration._
+    """,
+    ),
+    "included_applications": attrs.list(
+        attrs.dep(providers = [ErlangAppInfo]),
+        default = [],
+        doc = """
+        Check the documentation for `applications`.
+    """,
+    ),
+    "version": attrs.string(
+        default = "1.0.0",
+        doc = """
+        The `version` field specifies the applications version that is materialized as `vsn` field in the generated `*.app`
+        file. If you use the the `app_src` field and specify a version in the referenced template in addition to the version
+        field, the versions need to be identical.
+
+        If no version is specified in either the `app_src` template or the `version` field, a fallback version string of
+        `"1.0.0"` is used.
+    """,
+    ),
+    "_toolchain": attrs.toolchain_dep(default = "toolchains//:erlang-default"),
+} | common_shell_attributes
+
+rules_attributes = {
+    "erlang_app": {
+        "app_name": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+                This attribute allows the user to overwrite the Erlang application name, which otherwise defaults to the target name.
+            """,
+        ),
+        "app_src": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+                The `app_src` field allows to optionally reference a `*.app.src` template file. This template file will then be used by
+                buck2 to generate the `*.app` output file in the applications `ebin/` directory. This is useful during the migration from
+                rebar3 to buck2 to avoid duplicated entries, of e.g. the `version`.
+
+                Buck2 will use or check all fields present in the template, and fill out the fields with the information provided in the
+                target, e.g. if the `version` is specified in both, buck2 will check that they are identical. Otherwise, it uses the
+                information from the template if the target doesn't specify it, and vice versa.
+
+                **NOTE**: _If you use the `app_src` field and the references application resource file template specifies `applications`
+                or `included_applications` buck2 checks that the target definitions and information in the template are equivalent to
+                prevent these definitions from drifting apart during migration._
+            """,
+        ),
+        "app_src_vsn": attrs.string(
+            default = "git",
+            doc = """
+                The version placeholder used in the `app_src` and `appup_src` templates. When the `vsn` field of `app_src` (or the
+                version element of `appup_src`) matches this placeholder, either as an atom or as a string, buck2 substitutes the
+                value from the `version` field. Defaults to `"git"`, matching rebar3's convention.
+            """,
+        ),
+        "appup_src": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+                The `appup_src` field allows to optionally reference a `*.appup.src` template file used to generate the application's
+                `*.appup` file in the `ebin/` directory. The template's first element is the application version, which buck2 substitutes
+                using the same placeholder convention as `app_src_vsn`.
+            """,
+        ),
+        "docs": attrs.list(
+            attrs.source(),
+            default = [],
+            doc = """
+                Documentation files referenced by `-moduledoc {file, "..."}` or `-doc {file, "..."}` annotations
+                in source files. These files are made available to `erlc` at compile time, preserving their path
+                relative to the application root.
+            """,
+        ),
+        "env": attrs.option(
+            attrs.dict(key = attrs.string(), value = attrs.string()),
+            default = None,
+            doc = """
+                The `env` field allows to set the application env variables. The key value pairs will materialise in the application's `.app`
+                file and can then be accessed by [`application:get_env/2`](https://www.erlang.org/doc/man/application.html#get_env-2).
+           """,
+        ),
+        "erl_opts": attrs.option(
+            attrs.list(attrs.string()),
+            default = None,
+            doc = """
+                Typically compile options are managed by global config files, however, sometimes it is
+                desirable to overwrite the pre-defined compile options. The `erl_opts` field allows developers to do so for individual
+                applications.
+            """,
+        ),
+        "extra_includes": attrs.list(
+            attrs.dep(providers = [ErlangAppIncludeInfo]),
+            default = [],
+            doc = """
+                In some cases we might have the situation, where an application `app_a` depends through the `applications` and
+                `included_applications` fields on application `app_b` and a source file in `app_b` includes a header file from `app_a`
+                (e.g. `-include_lib("app_a/include/header.hrl`). This technically creates circular dependency from `app_a` to `app_b`
+                (e.g. via `applications` field) and back from `app_b` to `app_a` (via `-include_lib`). To break the dependency
+                developers can specify targets in the `extra_includes` field, whose public include files are accessible to the
+                application target during build time.
+
+                Only the includes of the specified application are available and eventual transitive dependencies need to be managed
+                manually.
+
+                **NOTE**: _It is not possible (or even desired) to add OTP applications with this field._
+
+                **NOTE**: _This mechanism is added to circumvent unclean dependency relationships and the goal for
+                developers should be to reduce usages of this field._ **DO NOT ADD ANY MORE USAGES!!**
+            """,
+        ),
+        "extra_properties": attrs.option(
+            attrs.dict(key = attrs.string(), value = attrs.one_of(attrs.string(), attrs.list(attrs.string()))),
+            default = None,
+            doc = """
+                The extra_properties field can be used to specify extra key-value pairs which is are not defined in
+                [application_opt()](https://www.erlang.org/doc/man/application.html#load-2). The key-value pair will be stored in the
+                applications `.app` file and can be accessed by `file:consult/1`.
+            """,
+        ),
+        "include_src": attrs.bool(
+            default = True,
+            doc = """
+                This field controls if the generated application directory contains a src/ directory with the Erlang code or not.
+            """,
+        ),
+        "includes": attrs.list(
+            attrs.source(),
+            default = [],
+            doc = """
+                The public header files accessible via `-include_lib("appname/include/header.hrl")` from other erlang files.
+            """,
+        ),
+        "mod": attrs.option(
+            attrs.tuple(attrs.string(), attrs.string()),
+            default = None,
+            doc = """
+                The `mod` field specifies the equivalent field in the generated `*.app` files. The format is similar, with the
+                difference, that the module name, and the individual start arguments need to be given as the string representation
+                of the corresponding Erlang terms.
+             """,
+        ),
+        "peek_private_includes": attrs.bool(
+            default = False,
+            doc = """
+                This attribute allows you to use the private includes of the application's dependencies. This can be useful for
+                test applications, to create shared abstractions for tests. It's not advisable to use this attribute for prodution
+                code. All private includes transitively must be non-ambiguous.
+            """,
+        ),
+        "resources": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+                The `resources` field specifies targets whose default output are placed in the applications `priv/` directory. For
+                regular files this field is typically combined with `export_file`, `filegroup`, or similar targets. However, it
+                is general, and any target can be used, e.g. if you want to place a built escript in the `priv/` directory, you can use
+                an `erlang_escript` target.
+            """,
+        ),
+        "srcs": attrs.list(
+            attrs.source(),
+            default = [],
+            doc = """
+                A list of `*.erl`, `*.hrl`, `*.xrl`, or `*.yrl` source inputs that are typically located
+                in an application's `src/` folder. Header files (i.e. `*.hrl` files) specified in this field are considered application
+                private headers, and can only be accessed by the `*.erl` files of the application itself. `*.xrl` and `*.yrl` files are
+                processed into `*.erl` files before all `*.erl` files are compiled into `*.beam` files.
+            """,
+        ),
+        "use_global_parse_transforms": attrs.bool(
+            default = True,
+            doc = """
+                This field indicates if global parse_tranforms should be applied to this application as well. It often makes sense
+                for third-party dependencies to not be subjected to global parse_transforms, similar to OTP applications.
+            """,
+        ),
+        "xrl_includefile": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+                Customised prologue file to replace the default. See [`includefile` option](https://www.erlang.org/doc/apps/parsetools/leex.html#file/2) for details.
+        """,
+        ),
+        "yrl_includefile": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+                Customised prologue file to replace the default. See [`includefile` option](https://www.erlang.org/doc/apps/parsetools/yecc.html#file/2) for details.
+        """,
+        ),
+        "_includes_target": attrs.option(
+            attrs.dep(providers = [ErlangAppIncludeInfo]),
+            default = None,
+            doc = """
+                Internal, used by the `erlang_application` macro to link the proper application target and include_only targets.
+            """,
+        ),
+    }
+    | common_application_attributes,
+    "erlang_app_includes": {
+        "app_name": attrs.string(),
+        "includes": attrs.list(attrs.source(), default = []),
+        "_toolchain": attrs.toolchain_dep(default = "toolchains//:erlang-default"),
+    },
+    "erlang_escript": {
+        "configs": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+            This attribute allows to set config files for the escript. The dependencies that are typically used
+            here are `export_file` targets.""",
+        ),
+        "deps": attrs.list(
+            attrs.dep(providers = [ErlangAppInfo]),
+            doc = """
+                List of Erlang applications that are bundled in the escript. This includes all transitive dependencies as well.
+            """,
+        ),
+        "emu_args": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+                This field specifies the emulator flags that the escript uses on execution. It is often desirable to specify the number
+                of threads and schedulers the escript uses. Please refer to the
+                [OTP documentation](https://www.erlang.org/doc/man/erl.html#emu_flags) for details.
+            """,
+        ),
+        "include_priv": attrs.bool(
+            default = False,
+            doc = """
+                Setting this flag, will package the applications `priv` directory in the escript. Similar to files added through the
+                `resources` field, the `priv` folders files can then be accessed by `escript"extract/2`.
+            """,
+        ),
+        "main_module": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+                Overrides the default main module. Instead of deferring the main module from the scripts filename, the specified module
+                is used. That module needs to export a `main/1` function that is called as entry point.
+            """,
+        ),
+        "resources": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+                This adds the targets default output to the escript archive. To access these files, you need to use `escript:extract/2`,
+                which will extract the entire escript in memory. The relevant files can then be accessed through the `archive`
+                section.
+
+                Please refer to the [`escript:extract/2`](https://www.erlang.org/doc/man/escript.html) for more details.
+            """,
+        ),
+        "script_name": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+                Overrides the filename of the produced escript.
+            """,
+        ),
+        "_toolchain": attrs.toolchain_dep(default = "toolchains//:erlang-default"),
+    },
+    "erlang_otp_binaries": {
+        "erl": attrs.arg(
+            doc = """
+                Reference to `erl` binary
+            """
+        ),
+        "erlc": attrs.arg(
+            doc = """
+                Reference to `erlc` binary
+            """
+        ),
+        "escript": attrs.arg(
+            doc = """
+                Reference to `escript` binary
+            """
+        ),
+    },
+    "erlang_release": {
+        "applications": attrs.list(
+            attrs.one_of(attrs.dep(providers = [ErlangAppInfo]), attrs.tuple(attrs.dep(providers = [ErlangAppInfo]), attrs.enum(StartTypeValues))),
+            doc = """
+                This field specifies the list of applications that the release should start in the given order, and optionally the start
+                type. Top-level applications without given start type are started with type
+                [`permanent`](https://www.erlang.org/doc/man/application.html#type-restart_type).
+            """,
+        ),
+        "bootscript_builders": attrs.dict(
+            key = attrs.string(),
+            value = attrs.dep(),
+            default = {},
+            doc = """
+                The mapping listed here maps from boot script name (e.g. "start.boot") to a binary (e.g. "$(location ...)") generating the boot script.
+                The binary receives four input arguments:
+                1. path of to a json file containing the applications, i.e. `["app1", ("app2", "load"), ...]`
+                2. the location of the lib dir containing the `<app>_<version>` folders
+                3. the output location of the boot script
+                4. the output location of the script file
+                followed by the values of `extra_bootscript_builder_args`, if any.
+                """,
+        ),
+        "default_bootscript_name": attrs.string(
+            default = "start",
+            doc = """
+                The boot script a runnable release boots, named without its `.boot` extension and looked up in
+                `releases/<version>/`. The default is `start`, the release's default boot script, produced by
+                `generate_default_bootscript`. When the release also contains
+                `releases/<version>/<default_bootscript_name>.vm.args`, the launcher passes it as `-args_file`.
+            """,
+        ),
+        "extra_bootscript_builder_args": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+                Additional arguments that are appended, in order, to every `bootscript_builders` invocation
+                after the four positional arguments. This lets a custom boot script builder be parameterised
+                by the release that uses it. Macros such as `$(location //some:target)` are expanded, and the
+                targets they name are made available to the invocation.
+            """,
+        ),
+        "generate_default_bootscript": attrs.bool(
+            default = True,
+            doc = """
+                This attribute controls wether the default bootscript should be generated with OTP's systools.
+                """,
+        ),
+        "include_erts": attrs.bool(
+            default = False,
+            doc = """
+                This field controls whether OTP applications and the Erlang runtime system should be included as part of the release.
+                Please note, that at the moment the erts folder is just `erts/`.
+            """,
+        ),
+        "is_executable": attrs.bool(
+            default = False,
+            doc = """
+                This field controls whether the release is runnable. If set, a launcher is generated at
+                `bin/<release_name>` that boots the release with the bundled emulator, which is why it
+                requires `include_erts = True`. The boot script it uses is `default_bootscript_name`.
+
+                When the release contains `releases/<version>/sys.config`, the launcher passes it as `-config`.
+            """,
+        ),
+        "overlays": attrs.dict(
+            key = attrs.string(),
+            value = attrs.list(attrs.dep()),
+            default = {},
+            doc = """
+                Overlays can be used to add files to the release. They are specified as mapping from path (from the release
+                root) to list of targets. The targets files are places **flat** at the target location with their basename.
+            """,
+        ),
+        "release_name": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+                The release name can explicitly be set by this field. This overwrites the default from the target name.
+            """,
+        ),
+        "version": attrs.string(
+            default = "1.0.0",
+            doc = """
+                The `version` field specifies the release version. The release version is used in the release resource file, and
+                is part of the path for the folder containing the boot scripts.
+            """,
+        ),
+        "_toolchain": attrs.toolchain_dep(default = "toolchains//:erlang-default"),
+    },
+    "erlang_test": {
+        "common_app_env": attrs.dict(
+            key = attrs.string(),
+            value = attrs.string(),
+            default = {},
+            doc = """
+                Application environment variables for the `common` application.
+            """,
+        ),
+        "config_files": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+                Will specify what config files the erlang beam machine running test with should load, for reference look at
+                [OTP documentation](https://www.erlang.org/doc/man/config.html). These ones should consist of default_output of
+                some targets. In general, this field is filled with target coming from then `export_file` rule, as in the example below.
+            """,
+        ),
+        "deps": attrs.list(
+            attrs.dep(providers = [ErlangAppOrTestInfo]),
+            default = [],
+            doc = """
+                The set of dependencies needed for all suites included in the target
+                to compile and run. They could be either `erlang_app(lication)` or `erlang_test`
+                targets, although the latter is discouraged. If some suites need to access common methods,
+                a common helper file should be created and included in the `srcs` field of the `erlang_tests` target.
+                If some applications are included as dependencies of this target, their private include will automatically
+                be pulled and made available for the test. That allows tests to access the private header files from the
+                applications under test.
+            """,
+        ),
+        "env": attrs.dict(
+            key = attrs.string(),
+            value = attrs.string(),
+            default = {},
+            doc = """
+                Add the given values to the environment variables with which the test is executed.
+            """,
+        ),
+        "erl_opts": attrs.option(
+            attrs.list(attrs.string()),
+            default = None,
+            doc = """
+                Typically compile options are managed by global config files, however, sometimes it is
+                desirable to overwrite the pre-defined compile options. The `erl_opts` field allows developers to do so for
+                the compilation of the test suites in this target.
+            """,
+        ),
+        "extra_ct_hooks": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+                List of additional Common Test hooks. The strings are interpreted as Erlang terms.
+            """,
+        ),
+        "extra_erl_flags": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+                List of additional command line arguments given to the erl command invocation. These
+                arguments are added to the front of the argument list.
+            """,
+        ),
+        "resources": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+                The `resources` field specifies targets whose default output are placed in the test `data_dir` directory for
+                all the suites present in the macro target. Additionally, if data directory are present in the directory along
+                the suite, this one will be pulled automatically for the relevant suite.
+
+                Any target can be used, e.g. if you want to place a built escript in the `data_dir` directory, you can use
+                an `erlang_escript` target.
+            """,
+        ),
+        "suite": attrs.source(
+            doc = """
+                The source file for the test suite. If you are using the macro, you should use the `suites` attribute instead.
+
+                The suites attribute specifies which erlang_test targets should be generated. For each suite "path_to_suite/suite_SUITE.erl" an
+                implicit 'erlang_test' target suite_SUITE will be generated.
+            """
+        ),
+        "_artifact_annotation_mfa": attrs.string(default = "artifact_annotations:default_annotation/1"),
+        "_cli_lib": attrs.dep(providers = [ErlangAppInfo], default = "prelude//erlang/common_test/test_cli_lib:test_cli_lib"),
+        "_ct_opts": attrs.string(default = read_root_config("erlang", "erlang_test_ct_opts", "")),
+        "_inner_trampolines": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+            trampolines that are used for the test node
+        """,
+        ),
+        "_providers": attrs.string(default = ""),
+        "_test_binary_lib": attrs.dep(providers = [ErlangAppInfo], default = "prelude//erlang/common_test/test_binary:test_binary"),
+        "_toolchain": attrs.toolchain_dep(default = "toolchains//:erlang-default"),
+        "_trampolines": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+            trampolines that are used for the test binary
+        """,
+        ),
+    }
+    | common_shell_attributes
+    | test_common.attributes()
+    | re_test_common.test_args(),
+}
+
+attributes = {name: dict(rules_attributes[name], **common_attributes) for name in rules_attributes}
+
+erlang_app = prelude_rule(
+    name = "erlang_app",
+    docs = """
+        This rule is the main rule for Erlang applications. It gets generated by using the `erlang_application`
+        macro, that takes as attributes the same attributes as this rule. You should always use the
+        `erlang_application` macro instead of using this rule directly.
+
+        Erlang Applications are the basic building block of our buck2 integration and used by many other Erlang
+        targets, e.g. `erlang_escript`, `erlang_test`, or `erlang_release`.
+
+        The `erlang_application` targets build OTP applications and as such many attributes that are used have
+        equivalent meaning to the fields in the currently (by rebar3) used `*.app.src` files and OTP `*.app`
+        files. Please familiarize yourself with the semantics of these fields by consulting the
+        [OTP documentation](https://erlang.org/doc/man/app.html).
+
+        The target enforces uniqueness during builds, and fails to build if duplicated artifacts in the
+        global namespaces are detected:
+        - duplicated application names in the dependencies
+        - duplicated module names across any of the applications or dependencies modules
+        - ambiguity when resolving header files
+
+        The default output of this rule is the application folder of the target application and all transitive dependencies.
+    """,
+    examples = """
+        #### Minimal Erlang Application
+
+        ```
+        erlang_application(
+            name = "minimal",
+        )
+        ```
+
+        #### With `priv/` directory
+
+        ```
+        erlang_application(
+            name = "app_a",
+            srcs = [
+                "src/app_a.erl",
+            ],
+            includes = [],
+            applications = [
+                ":app_b",
+            ],
+            app_src = "src/app_a.app.src",
+            resources = [
+                ":readme",
+            ],
+        )
+
+        export_file(
+            name = "readme",
+            src = "README.md",
+        )
+        ```
+
+        #### Using OTP applications and `mod` field
+
+        ```
+        erlang_application(
+            name = "app_b",
+            srcs = [
+                "src/app_b.erl",
+                "src/app_b.hrl",
+            ],
+            includes = [],
+            applications = [
+                "kernel",
+                "stdlib",
+                ":app_c",
+            ],
+            mod = ("app_b", [
+                "some_atom",
+                "\"some string\"",
+                "{tagged_tuple, 42}",
+            ]),
+        )
+        ```
+
+        #### Using Yecc and Leex
+
+        ```
+        erlang_application(
+            name = "yecc_leex",
+            srcs = [
+                "src/leex_stub.xrl",
+                "src/yecc_stub.yrl",
+            ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = attributes["erlang_app"],
+)
+
+erlang_app_includes = prelude_rule(
+    name = "erlang_app_includes",
+    docs = """
+        This rule is a supplementary rule for Erlang applications. It gets generated by using the `erlang_application`
+        macro, that takes as attributes the same attributes as this rule. You should always use the
+        `erlang_application` macro instead of using this rule directly.
+    """,
+    further = None,
+    attrs = attributes["erlang_app_includes"],
+)
+
+erlang_escript = prelude_rule(
+    name = "erlang_escript",
+    docs = """
+        The `erlang_escript` target builds and runs bundled escripts. Please refer to the
+        [OTP documentation](https://www.erlang.org/doc/man/escript.html) for more details about escripts.
+
+        Escripts by default always try to use the module that has the same name as the escripts basename as entry point, e.g. if
+        the escript is called `script.escript` then running the escript will try to call `script:main/1`. Both name and
+        main module can be overwritten though.
+
+        The target name doubles as the default escript name. If the `main_module` attribute is not used, the escript filename will
+        be `<name>.escript`.
+    """,
+    examples = """
+        ```
+        erlang_escript(
+            name = "script",
+            main_module = "main_module",
+            script_name = "the_script",
+            deps = [
+                ":escript_app",
+            ],
+            emu_args = ["+sbtu", "+A1"],
+        )
+
+        erlang_application(
+            name = "escript_app",
+            srcs = ["src/main_module.erl"],
+            applications = [
+                "kernel",
+                "stdlib",
+            ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = attributes["erlang_escript"],
+)
+
+erlang_otp_binaries = prelude_rule(
+    name = "erlang_otp_binaries",
+    docs = """
+        This target defines the executables for the Erlang toolchains, and is required to defined a toolchain.
+    """,
+    examples = """
+        erlang_otp_binaries(
+            name = "local",
+            erl = "local/erl",
+            erlc = "local/erlc",
+            escript = "local/escript",
+        )
+    """,
+    further = None,
+    attrs = attributes["erlang_otp_binaries"],
+    is_toolchain_rule = True,
+)
+
+erlang_release = prelude_rule(
+    name = "erlang_release",
+    docs = """
+        The `erlang_release` target builds OTP releases. Please refer to the
+        [OTP documentation](https://www.erlang.org/doc/design_principles/release_structure.html) for more details about
+        releases.
+
+        The `erlang_release` target does by default (without overlays) package:
+        - applications that are required to start the release
+        - release resource file `<relname>.rel` (see [rel(4)](https://www.erlang.org/doc/man/rel.html))
+        - boot script `start.script` (see [rel(4)](https://www.erlang.org/doc/man/script.html))
+        - binary boot script `start.boot`
+        - `bin/release_variables`
+
+        The `release_variables` file contains release name, version, and erts version in shell syntax, e.g.
+        ```
+        ERTS_VSN="12.1.2"
+        REL_NAME="rel1"
+        REL_VSN="1.0.0"
+        ```
+
+        The target name doubles as the default release name. If the `release_name` attribute is used, the release name will be
+        sources from there instead.
+    """,
+    examples = """
+        ```
+        erlang_release(
+            name = "world",
+            version = "1.0.0",
+            applications = [
+                "//apps//app_a:app_a",
+                "//apps//app_b:app_b",
+            ],
+            overlays = {
+                "releases/1.0.0": [
+                    ":sys.config.src",
+                ],
+                "bin": [
+                    ":start.sh",
+                ],
+            },
+        )
+
+        export_file(
+            name = "sys.config.src",
+            src = "sys.config",
+        )
+
+        export_file(
+            name = "start.sh",
+            src = "start.sh",
+        )
+        ```
+    """,
+    further = None,
+    attrs = attributes["erlang_release"],
+)
+
+erlang_test = prelude_rule(
+    name = "erlang_test",
+    docs = """
+        The `erlang_test` ruls defines a test target for a single test suite. In most cases you
+        want to define multiple suites in one go. The `erlang_tests` macro allows users to generate
+        `erlang_test` targets for multiple test suites. Each suite `<name>_SUITE.erl` will have a
+        generated hidden `erlang_test` target whose name is `<name>_SUITE`.
+
+        Each `erlang_test` target implements tests using the Common Test library
+        [OTP documentation](https://www.erlang.org/doc/man/common_test.html). They can,
+        although **it is not recommended**, also act as dependencies of other tests. The
+        default output of this rule is a "test_folder", consisting of the compiled test suite
+        and the data directory.
+
+        For each suite  `<name>_SUITE.erl`, if a data_dir `<name>_SUITE_data` is present along the suite,
+        (as per [the data_dir naming scheme for ct](https://www.erlang.org/doc/apps/common_test/write_test_chapter.html#data-and-private-directories)),
+        it will automatically adds the corresponding resource target to the generated test target of the suite.
+        Resources will be placed in the [Data directory (data_dir)](https://www.erlang.org/doc/apps/common_test/write_test_chapter.html#data_priv_dir)
+        of each of the suite.
+
+        It allows the writer of the rule to add global configuration files and global default
+        dependencies (e.g `meck`). These ones should be specified using global
+        variables `erlang.erlang_tests_default_apps` and `erlang.erlang_tests_default_config`
+        respectively.
+
+        The `erlang_tests` macro forwards all attributes to the `erlang_test`. It defines some attributes
+        that control how the targets get generated:
+        - `srcs` ([source]): Set of files that the suites might depend on and that are not part of any specific application.
+          A "meta" application having those files as sources will automatically be created, and included in the dependencies
+          of the tests.
+
+        One can call
+        - `buck2 build //my_app:test_SUITE` to compile the test files together with its dependencies.
+        - `buck2 test //my_app:other_test_SUITE` to run the test.
+        - `buck2 run //my_app:other_test_SUITE` to open an interactive test shell, where tests can be run iteratively.
+
+        buck2 test will rely on tpx to run the suite. To get access to tpx commands, add `--` after the
+        target. For example:
+
+        - `buck2 test //my_app:other_test_SUITE -- --help` will print the list of tpx available
+        command line parameters.
+        - `buck2 test //my_app:other_test_SUITE -- group.mycase` will only run those test cases
+        that match the pattern `group.mycase`
+    """,
+    examples = """
+        erlang_test(
+            name = "unit_test_SUITE",
+            suite = "unit_test_SUTIE.erl",
+            deps = [":my_other_app"],
+            contacts = ["author@email.com"],
+        )
+
+        erlang_tests(
+            suites = ["test_SUITE.erl", "other_test_SUITE".erl],
+            deps = [":my_app"],
+            contacts = ["author@email.com"],
+        )
+    """,
+    further = None,
+    attrs = attributes["erlang_test"],
+)
+
+erlang_rules = struct(
+    erlang_app = erlang_app,
+    erlang_app_includes = erlang_app_includes,
+    erlang_escript = erlang_escript,
+    erlang_otp_binaries = erlang_otp_binaries,
+    erlang_release = erlang_release,
+    erlang_test = erlang_test,
+)
diff --git a/buck2/prelude/decls/genrule_common.bzl b/buck2/prelude/decls/genrule_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/genrule_common.bzl
@@ -0,0 +1,282 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+def _srcs_arg():
+    return {
+        "srcs": attrs.named_set(
+            attrs.source(allow_directory = True),
+            sorted = False,
+            default = [],
+            doc = """
+    Either a list or a map of the source files which Buck makes available to the shell
+     command at the path in the `SRCDIR` environment variable.
+     If you specify a list, the source files are the names in the list.
+     If you specify a map, the source files are made available as the names in
+     the keys of the map, where the values of the map are the original source
+     file names.
+""",
+        ),
+    }
+
+def _cmd_arg():
+    return {
+        "cmd": attrs.option(
+            attrs.arg(),
+            default = None,
+            doc = """
+    The shell command to run to generate the output file. It is the
+     fallback for `bash` and `cmd_exe` arguments. The following environment variables are populated by
+     Buck and available to the shell command. They are accessed using
+     the syntax:
+
+    ```
+    ${<variable>}
+    ```
+
+     Example:
+
+    ```
+    ${SRCS}
+    ```
+
+    `${SRCS}`
+
+     A string expansion of the `srcs` argument delimited
+     by the `environment_expansion_separator` argument
+     where each element of `srcs` will be translated
+     into a relative path.
+
+    `${SRCDIR}`
+
+     The relative path to a directory to which sources are copied
+     prior to running the command.
+
+    `${OUT}`
+
+     The output file or directory for the `genrule()`.
+     This variable will have whatever value is specified by
+     the `out` argument if not using named outputs. If
+     using named outputs, this variable will be the output directory.
+
+     The value should be a valid filepath. The semantics of the shell
+     command determine whether this filepath is treated as a file or a
+     directory. If the filepath is a directory, then the shell command
+     needs to create it if not using named outputs. Otherwise, it will
+     be automatically created. All outputs (directories and files) must
+     be readable, writable, and (in the case of directories) executable
+     by the current user.
+
+     The file or directory specified by this variable must always
+     be written by this command. If not, the execution of this
+     rule will be considered a failure, halting the build process.
+
+    `${TMP}`
+
+     A temporary directory which can be used for intermediate
+     results and will not be bundled into the output.
+
+""",
+        ),
+    }
+
+def _bash_arg():
+    return {
+        "bash": attrs.option(
+            attrs.arg(),
+            default = None,
+            doc = """
+    A platform-specific version of the shell command parameter `cmd`.
+     It runs on Linux and UNIX systems—including OSX—on which `bash` is installed.
+     It has a higher priority than `cmd`. The `bash` argument is run with `/usr/bin/env bash -c`.
+     It has access to the same set of macros and variables as the `cmd` argument.
+""",
+        ),
+    }
+
+def _cmd_exe_arg():
+    return {
+        "cmd_exe": attrs.option(
+            attrs.arg(),
+            default = None,
+            doc = """
+    A platform-specific version of the shell command parameter `cmd`. It runs on Windows and has a higher
+     priority than `cmd`. The `cmd_exe` argument is run with `cmd.exe /v:off /c`.
+     It has access to the same set of macros and variables as the `cmd` argument.
+""",
+        ),
+    }
+
+def _weight_arg():
+    return {
+        "weight": attrs.option(
+            attrs.int(),
+            default = None,
+            doc = """
+    How many local slots these genrule should take when executing locally.
+""",
+        ),
+    }
+
+def _out_arg():
+    return {
+        "out": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    The name of the output file or directory. The complete path to this
+     argument is provided to the shell command through
+     the `OUT` environment variable.
+""",
+        ),
+    }
+
+def _type_arg():
+    return {
+        "type": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    Specifies the *type* of this genrule. This is used for logging
+     and is particularly useful for grouping genrules that share an
+     underlying logical "type".
+
+     For example, if you have the following `cxx_genrule` defined
+     in the root directory of your Buck project
+
+    ```
+    cxx_genrule(
+      name = 'cxx_gen',
+      type = 'epilog',
+      cmd  = 'touch finish.txt; cp finish.txt $OUT',
+      out  = 'finish.txt'
+    )
+    ```
+
+     then the following `buck query` command
+
+    ```
+    buck query "attrfilter( type, 'epilog', '//...' )"
+    ```
+
+     returns
+
+    ```
+    //:cxx_gen
+    ```
+""",
+        ),
+    }
+
+def _environment_expansion_separator():
+    return {
+        "environment_expansion_separator": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    The delimiter between paths in environment variables, such as SRCS, that can contain multiple paths.
+     It can be useful to specify this parameter if the paths could contain spaces.
+""",
+        ),
+    }
+
+def _env_arg():
+    return {
+        "env": attrs.dict(
+            key = attrs.string(),
+            value = attrs.arg(),
+            sorted = False,
+            default = {},
+            doc = """
+        A map of variables to be set in the environment where the shell command is run.
+""",
+        ),
+    }
+
+def _error_handler_arg():
+    return {
+        "error_handler_category": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+                The error category name for errors produced by this genrule's error handler.
+                 Used in conjunction with `error_handler_stderr_errorformats` and `error_handler_stdout_errorformats`
+                 when calling `ActionErrorCtx.parse_with_errorformat()` to categorize parsed errors.
+
+                 See https://buck2.build/docs/api/build/ActionErrorCtx/#actionerrorctxparse_with_errorformat for more details.
+            """,
+        ),
+        "error_handler_stderr_errorformats": attrs.option(
+            attrs.list(attrs.string()),
+            default = None,
+            doc = """
+                List of Vim errorformat pattern strings used to parse error messages from
+                 stderr of failed genrule commands. These patterns extract structured error information
+                 (file paths, line numbers, error messages) from command output.
+
+                 When a genrule fails, the error handler attempts to match the stderr
+                 against these patterns.
+
+                 See https://buck2.build/docs/api/build/ActionErrorCtx/#actionerrorctxparse_with_errorformat for more details.
+            """,
+        ),
+        "error_handler_stdout_errorformats": attrs.option(
+            attrs.list(attrs.string()),
+            default = None,
+            doc = """
+                Same as `error_handler_stderr_errorformats`, but for stdout.
+
+                 See https://buck2.build/docs/api/build/ActionErrorCtx/#actionerrorctxparse_with_errorformat for more details.
+            """,
+        ),
+    }
+
+def _allow_offline_output_cache_arg():
+    return {
+        "allow_offline_output_cache": attrs.bool(
+            default = False,
+            doc = """
+                Enables caching of this genrule's outputs for offline builds.
+
+                 When set to `True`, the genrule's outputs are cached during trace builds
+                 (via `buck2 debug trace-io`) and restored during offline builds without
+                 re-executing the command.
+
+                 This is intended for genrules that read from the network (e.g., downloads,
+                 remote artifact fetches) which cannot execute in offline build environments
+                 where network access is restricted.
+
+                 During trace builds, outputs are copied to `buck-out/offline-cache/` after
+                 successful execution. During offline builds, if all outputs exist in the
+                 offline cache, they are restored without running the genrule; otherwise
+                 the genrule executes normally (graceful fallback).
+
+                 Requires `buck2.use_network_action_output_cache=true` config to take effect.
+
+                 Example use case: caching network downloads in containerized offline build environments.
+            """,
+        ),
+    }
+
+genrule_common = struct(
+    srcs_arg = _srcs_arg,
+    cmd_arg = _cmd_arg,
+    bash_arg = _bash_arg,
+    cmd_exe_arg = _cmd_exe_arg,
+    out_arg = _out_arg,
+    type_arg = _type_arg,
+    weight_arg = _weight_arg,
+    environment_expansion_separator = _environment_expansion_separator,
+    env_arg = _env_arg,
+    error_handler_arg = _error_handler_arg,
+    allow_offline_output_cache_arg = _allow_offline_output_cache_arg,
+)
diff --git a/buck2/prelude/decls/git_rules.bzl b/buck2/prelude/decls/git_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/git_rules.bzl
@@ -0,0 +1,89 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":common.bzl", "buck", "prelude_rule")
+
+git_fetch = prelude_rule(
+    name = "git_fetch",
+    docs = """
+        Checkout a commit from a git repository.
+    """,
+    examples = """
+        ```
+        git_fetch(
+            name = "serde.git",
+            repo = "https://github.com/serde-rs/serde",
+            rev = "fccb9499bccbaca0b7eef91a3a82dfcb31e0b149",
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "allow_cache_upload": attrs.bool(
+                doc = """
+                Whether the results of the fetch can be written to the action cache and CAS.
+            """,
+                default = True,
+            ),
+            "git": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Path to the git binary to use. If not specified, the system
+                git from PATH is used, with fallback to common system
+                locations (/usr/bin/git, /usr/local/bin/git).
+            """,
+            ),
+            "object_format": attrs.option(
+                attrs.enum(["sha1", "sha256"]),
+                default = None,
+                doc = """
+                The object format to use for the underlying Git repository.
+                Must be one of `sha1` or `sha256`.
+                """,
+            ),
+            "repo": attrs.string(
+                doc = """
+                Url suitable as a git remote.
+            """
+            ),
+            "rev": attrs.string(
+                doc = """
+                Commit hash. 40 hex digits for sha1, 64 hex digits for sha256.
+            """
+            ),
+            "update_submodules": attrs.bool(
+                default = False,
+                doc = """
+                Whether to initialize and update Git submodules after the worktree checkout.
+                If true, submodules are fetched recursively with depth 1.
+            """,
+            ),
+            "sub_targets": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                A list of paths within the remote repo to be made accessible as sub-targets.
+                For example if we have a git_fetch with `name = "serde.git"` and
+                `sub_targets = ["serde_derive"]`, then other targets would be able to refer
+                to the serde_derive subdirectory of the repo as `":serde.git[serde_derive]"`.
+            """,
+            ),
+            "_git_fetch_tool": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//git/tools:git_fetch")),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+git_rules = struct(
+    git_fetch = git_fetch,
+)
diff --git a/buck2/prelude/decls/go_common.bzl b/buck2/prelude/decls/go_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/go_common.bzl
@@ -0,0 +1,264 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load(":common.bzl", "LinkableDepType")
+
+LinkMode = ["internal", "external"]
+
+def _deps_arg():
+    return {
+        "deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    The set of dependencies of this rule. Currently, this only supports go\\_library rules.
+""",
+        ),
+    }
+
+def _srcs_arg():
+    return {
+        "srcs": attrs.list(
+            attrs.source(),
+            default = [],
+            doc = """
+    The set of source files to be compiled by this rule. .go files will be compiled with the Go
+     compiler, .s files will be compiled with the assembler, and everything else is assumed to be
+     files that may be `#include`d by the assembler.
+""",
+        ),
+    }
+
+def _package_root_arg():
+    return {
+        "package_root": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    Sets Go package direactory (relative to BUCK file).
+    By default (or if None passes) package_root is being detected automatically.
+    Empty string of Go package is on the same level as BUCK file otherwise the subdirectory name.
+    Example for srcs = ["foo/bar.go"], package_root = "foo"
+""",
+        ),
+    }
+
+def _link_style_arg():
+    return {
+        "link_style": attrs.option(
+            attrs.enum(LinkableDepType),
+            default = None,
+            doc = """
+    Determines whether to build and link this rule's dependencies statically or dynamically. Can be
+     one of the following values: `static`, `static_pic` or `shared`.
+     This argument is relevant only if the cgo extension is enabled. Otherwise, Buck ignores this argument.
+""",
+        ),
+    }
+
+def _link_mode_arg():
+    return {
+        "link_mode": attrs.option(
+            attrs.enum(LinkMode),
+            default = None,
+            doc = """
+    Determines the link mode (equivalent of `-mode`). Can be one of the following
+     values: `internal`, `external`.
+     If no value is provided, the mode is set automatically depending on the other args.
+""",
+        ),
+    }
+
+def _package_name_arg():
+    return {
+        "package_name": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    Sets the full name of the package being compiled. This defaults to the path from the buck root.
+     (e.g. given a ./.buckconfig, a rule in ./a/b/BUCK defaults to package "a/b")
+""",
+        ),
+    }
+
+def _compiler_flags_arg():
+    return {
+        "compiler_flags": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    The set of additional compiler flags to pass to `go tool compile`.
+""",
+        ),
+    }
+
+def _assembler_flags_arg():
+    return {
+        "assembler_flags": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    The set of additional assembler flags to pass to `go tool asm`.
+""",
+        ),
+    }
+
+def _linker_flags_arg():
+    return {
+        "linker_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    Extra linker flags passed to go link
+""",
+        ),
+    }
+
+def _external_linker_flags_arg():
+    return {
+        "external_linker_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    Extra external linker flags passed to go link via `-extld` argument.
+""",
+        ),
+    }
+
+def _embed_srcs_arg():
+    return {
+        "embed_srcs": attrs.named_set(
+            attrs.source(),
+            default = [],
+            doc = """
+    The set of files and directories to be embedded if match go:embed patterns, e.g. `//go:embed *.txt`
+
+    Can be specified as either:
+    - A list of source files (names derived from short_path)
+    - A dict mapping custom names to source files (for stable naming of generated targets)
+
+    Example (list):
+
+    ```
+    embed_srcs = ["data/config.json", "templates/index.html"]
+    ```
+
+    Example (dict):
+
+    ```
+    embed_srcs = {
+        "config.json": ":generated_config",
+        "index.html": "templates/index.html",
+    }
+    ```
+""",
+        ),
+    }
+
+def _cgo_enabled_arg():
+    return {
+        "cgo_enabled": attrs.option(
+            attrs.bool(),
+            default = None,
+            doc = """
+    Analog of CGO_ENABLED env-var, applies to this target and its dependencies.
+    If None it will depend on the availability of CXX toolchain.
+""",
+        ),
+    }
+
+def _override_cgo_enabled_arg():
+    return {
+        "override_cgo_enabled": attrs.option(
+            attrs.bool(),
+            default = None,
+            doc = """
+    Per-target analog of CGO_ENABLED env-var, overrides its value for the target, but not for its dependencies.
+""",
+        ),
+    }
+
+def _build_tags_arg():
+    return {
+        "build_tags": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    Build tags to apply to this target and its dependencies.
+""",
+        ),
+    }
+
+def _cxx_compiler_flags_arg():
+    return {
+        "cxx_compiler_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    GCC/Clang flags to use when compiling any of the above C/C++ sources (which require compilation).
+""",
+        ),
+    }
+
+def _cxx_preprocessor_flags_arg():
+    return {
+        "cxx_preprocessor_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    GCC/Clang flags to use when preprocessing any of the above C/C++ sources (which require preprocessing).
+""",
+        ),
+    }
+
+def _generate_exported_header():
+    return {
+        "generate_exported_header": attrs.bool(
+            default = False,
+            doc = """
+    Generate header file with declaration for functions exported with `//export`
+    The header name for target `cell//foo/bar:lib` will be `foo/bar/lib.h`
+""",
+        ),
+    }
+
+def _coverage_enabled():
+    return {
+        "coverage_enabled": attrs.bool(
+            default = True,
+            doc = """
+    Enable test code coverage collection for this target.
+""",
+        ),
+    }
+
+go_common = struct(
+    deps_arg = _deps_arg,
+    srcs_arg = _srcs_arg,
+    package_root_arg = _package_root_arg,
+    link_style_arg = _link_style_arg,
+    link_mode_arg = _link_mode_arg,
+    package_name_arg = _package_name_arg,
+    compiler_flags_arg = _compiler_flags_arg,
+    assembler_flags_arg = _assembler_flags_arg,
+    linker_flags_arg = _linker_flags_arg,
+    external_linker_flags_arg = _external_linker_flags_arg,
+    embed_srcs_arg = _embed_srcs_arg,
+    cgo_enabled_arg = _cgo_enabled_arg,
+    override_cgo_enabled_arg = _override_cgo_enabled_arg,
+    build_tags_arg = _build_tags_arg,
+    cxx_compiler_flags_arg = _cxx_compiler_flags_arg,
+    cxx_preprocessor_flags_arg = _cxx_preprocessor_flags_arg,
+    generate_exported_header = _generate_exported_header,
+    coverage_enabled_arg = _coverage_enabled,
+)
diff --git a/buck2/prelude/decls/go_rules.bzl b/buck2/prelude/decls/go_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/go_rules.bzl
@@ -0,0 +1,473 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//decls:test_common.bzl", "test_common")
+load(
+    "@prelude//go/transitions:defs.bzl",
+    "go_binary_transition",
+    "go_exported_library_transition",
+    "go_library_transition",
+    "go_stdlib_transition",
+    "go_test_transition",
+)
+load(":common.bzl", "buck", "prelude_rule")
+load(":cxx_common.bzl", "cxx_common")
+load(":go_common.bzl", "go_common")
+load(":re_test_common.bzl", "re_test_common")
+
+BuildMode = ["exe", "c_shared", "c_archive", "pie"]
+
+GoTestCoverStepMode = ["set", "count", "atomic", "none"]
+
+go_binary = prelude_rule(
+    name = "go_binary",
+    docs = """
+        A go\\_binary() rule builds a native executable from the supplied set of Go source files
+         and dependencies. The files supplied are expected to be in the main package, implicitly.
+    """,
+    examples = """
+        For more examples, check out our [integration tests](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/features/go/testdata).
+
+        ```
+        go_binary(
+          name='greet',
+          srcs=[
+            'main.go',
+          ],
+          deps=[
+            ':greeting',
+          ],
+        )
+
+        go_library(
+          name='greeting',
+          srcs=[
+            'greeting.go',
+          ],
+          deps=[
+            ':join',
+          ],
+        )
+
+        go_library(
+          name='join',
+          srcs=[
+            'join.go',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        go_common.package_name_arg()
+        | go_common.srcs_arg()
+        | go_common.deps_arg()
+        | go_common.link_style_arg()
+        | go_common.link_mode_arg()
+        | go_common.compiler_flags_arg()
+        | go_common.assembler_flags_arg()
+        | go_common.linker_flags_arg()
+        | go_common.external_linker_flags_arg()
+        | go_common.embed_srcs_arg()
+        | {
+            "build_mode": attrs.option(
+                attrs.enum(BuildMode),
+                doc = """
+                Determines the build mode (equivalent of `-buildmode`). Can be
+                 one of the following values: `exe`, `pie`.`
+            """,
+                default = None,
+            ),
+        }
+        | go_common.package_root_arg()
+        | go_common.cgo_enabled_arg()
+        | go_common.build_tags_arg()
+        | go_common.coverage_enabled_arg()
+        | {
+            "coverage_mode": attrs.option(
+                attrs.enum(GoTestCoverStepMode),
+                default = None,
+                doc = """
+                Coverage instrumentation mode for the binary. When set, the binary is built with
+                coverage instrumentation. Set GOCOVERDIR to a directory path when running the binary
+                to collect coverage data. Modes: set, count, atomic
+            """,
+            ),
+        }
+        | cxx_common.headers_arg()
+        | cxx_common.header_namespace_arg()
+        | go_common.cxx_preprocessor_flags_arg()
+        | go_common.cxx_compiler_flags_arg()
+        | {
+            "platform": attrs.option(attrs.string(), default = None),
+            "resources": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Static files to be symlinked into the working directory of the test. You can access these in your
+                 by opening the files as relative paths, e.g. `ioutil.ReadFile("testdata/input")`.
+            """,
+            ),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+    cfg = go_binary_transition,
+)
+
+go_exported_library = prelude_rule(
+    name = "go_exported_library",
+    docs = """
+        A go\\_exported\\_library() rule builds a C library from the supplied set of Go source files
+         and dependencies. This is done via `-buildmode` flag and "//export" annotations in the code.
+    """,
+    examples = """
+        For more examples, check out our [integration tests](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/features/go/testdata).
+
+        ```
+        go_exported_library(
+            name = "shared",
+            srcs = ["main.go"],
+            build_mode = "c_shared",
+            compiler_flags = ["-shared"],
+            deps = [":example"],
+        )
+
+        go_library(
+            name = "example",
+            package_name = "cgo",
+            srcs = [
+                "export-to-c.go",  # file with //export annotations
+            ],
+            compiler_flags = [],
+            headers = [],
+        )
+
+        cxx_genrule(
+            name = "cgo_exported_headers",
+            out = "includes",
+            cmd = (
+                "mkdir -p $OUT && " +
+                "cat `dirname $(location :shared)`/includes/*.h > $OUT/_cgo_export.h"
+            ),
+        )
+
+        prebuilt_cxx_library(
+            name = "cxx_so_with_header",
+            header_dirs = [":cgo_exported_headers"],
+            shared_lib = ":shared",
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        go_common.package_name_arg()
+        | go_common.srcs_arg()
+        | go_common.deps_arg()
+        | {
+            "build_mode": attrs.option(
+                attrs.enum(BuildMode),
+                doc = """
+                Determines the build mode (equivalent of `-buildmode`). Can be
+                 one of the following values: `c_archive`, `c_shared`.`
+            """,
+                default = None,
+            ),
+        }
+        | cxx_common.headers_arg()
+        | cxx_common.header_namespace_arg()
+        | go_common.cxx_preprocessor_flags_arg()
+        | go_common.cxx_compiler_flags_arg()
+        | go_common.link_style_arg()
+        | go_common.link_mode_arg()
+        | go_common.compiler_flags_arg()
+        | go_common.assembler_flags_arg()
+        | go_common.linker_flags_arg()
+        | go_common.external_linker_flags_arg()
+        | go_common.package_root_arg()
+        | go_common.cgo_enabled_arg()
+        | go_common.build_tags_arg()
+        | go_common.generate_exported_header()
+        | go_common.coverage_enabled_arg()
+        | go_common.embed_srcs_arg()
+        | {
+            "platform": attrs.option(attrs.string(), default = None),
+            "resources": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Static files to be symlinked into the working directory of the test. You can access these in your
+                 by opening the files as relative paths, e.g. `ioutil.ReadFile("testdata/input")`.
+            """,
+            ),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+    cfg = go_exported_library_transition,
+)
+
+go_library = prelude_rule(
+    name = "go_library",
+    docs = """
+        A go\\_library() rule builds a native library from the supplied set of Go source files
+         and dependencies.
+    """,
+    examples = """
+        For more examples, check out our [integration tests](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/features/go/testdata).
+
+        ```
+        go_library(
+          name='greeting',
+          srcs=[
+            'greeting.go',
+          ],
+          deps=[
+            ':join',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        go_common.srcs_arg()
+        | go_common.package_name_arg()
+        | go_common.deps_arg()
+        | go_common.compiler_flags_arg()
+        | go_common.assembler_flags_arg()
+        | go_common.embed_srcs_arg()
+        | go_common.package_root_arg()
+        | go_common.override_cgo_enabled_arg()
+        | cxx_common.headers_arg()
+        | cxx_common.header_namespace_arg()
+        | go_common.cxx_preprocessor_flags_arg()
+        | go_common.cxx_compiler_flags_arg()
+        | go_common.external_linker_flags_arg()
+        | go_common.link_style_arg()
+        | go_common.coverage_enabled_arg()
+        | go_common.generate_exported_header()
+        | {}
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+    cfg = go_library_transition,
+)
+
+go_test = prelude_rule(
+    name = "go_test",
+    docs = """
+        A `go_test()` rule builds a native binary from the
+         specified Go source and resource files—and a generated main file. It's
+         similar to the `go test` command.
+
+         If your test requires static files you should specify these in
+         the **resources** argument. If you do not specify these
+         files, they won't be available when your test runs.
+    """,
+    examples = """
+        For more examples, check out our [integration tests](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/features/go/testdata).
+
+        ```
+        go_library(
+          name='greeting',
+          srcs=[
+            'greeting.go',
+          ],
+          deps=[
+            ':join',
+          ],
+        )
+
+        go_test(
+          name='greeting-test',
+          srcs=[
+            'greeting_ext_test.go',
+          ],
+          deps=[
+            ':greeting'
+          ],
+        )
+
+        go_test(
+          name='greeting-internal-test',
+          package_name='greeting',
+          srcs=[
+            'greeting.go',
+            'greeting_test.go',
+          ],
+          deps=[
+            ':join',
+          ],
+        )
+
+        # Or
+
+        go_test(
+          name='greeting-better-internal-test',
+          srcs=['greeting_test.go'],
+          target_under_test=':greeting',
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.inject_test_env_arg()
+        | go_common.srcs_arg()
+        | {
+            "coverage_mode": attrs.option(
+                attrs.enum(GoTestCoverStepMode),
+                default = None,
+                doc = """
+                Test coverage functionality will be included in the executable. Modes: set, count, atomic
+            """,
+            ),
+            "package_name": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Sets the full name of the test package being compiled. This defaults to the path from the buck
+                 root with "\\_test" appended. (e.g. given a ./.buckconfig, a rule in ./a/b/BUCK defaults to package "a/b\\_test")
+
+                 Note: if you want to test packages internally (i.e. same package name), use the `target_under_test`
+                 parameter instead of setting `package_name` to include the tested source files.
+            """,
+            ),
+            "target_under_test": attrs.option(
+                attrs.dep(),
+                default = None,
+                doc = """
+                Specify the target_under_test that this internal test is testing. This will copy the `srcs`,
+                 `package_name` and `deps` from the target specified so you don't have
+                 to duplicate them.
+            """,
+            ),
+        }
+        | go_common.deps_arg()
+        | go_common.link_style_arg()
+        | go_common.coverage_enabled_arg()
+        | go_common.link_mode_arg()
+        | {
+            "build_mode": attrs.option(
+                attrs.enum(BuildMode),
+                doc = """
+                Determines the build mode (equivalent of `-buildmode`). Can be
+                 one of the following values: `exe`, `pie`.`
+            """,
+                default = None,
+            ),
+        }
+        | go_common.compiler_flags_arg()
+        | go_common.assembler_flags_arg()
+        | go_common.linker_flags_arg()
+        | go_common.external_linker_flags_arg()
+        | go_common.embed_srcs_arg()
+        | go_common.package_root_arg()
+        | go_common.cgo_enabled_arg()
+        | go_common.build_tags_arg()
+        | cxx_common.headers_arg()
+        | cxx_common.header_namespace_arg()
+        | go_common.cxx_preprocessor_flags_arg()
+        | go_common.cxx_compiler_flags_arg()
+        | {
+            "resources": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Static files that are symlinked into the working directory of the
+                 test. You can access these files in your test by opening them using
+                 relative paths, such as `ioutil.ReadFile("testdata/input")`.
+            """,
+            ),
+        }
+        | buck.test_label_arg()
+        | buck.test_rule_timeout_ms()
+        | {
+            "env": attrs.dict(
+                key = attrs.string(),
+                value = attrs.arg(),
+                sorted = False,
+                default = {},
+                doc = """
+                A map of environment variables and values to set when running the test.
+            """,
+            ),
+        }
+        | buck.run_test_separately_arg(
+            run_test_separately_type = attrs.bool(
+                default = False,
+                doc = """
+            If set to True, the test(s) in this rule are run separately from
+             all other tests. This is useful for integration tests which
+             access a physical device or other limited resource. If unset,
+             the test(s) in this rule run in parallel with all other tests.
+        """,
+            )
+        )
+        | {
+            "platform": attrs.option(attrs.string(), default = None),
+            "runner": attrs.option(attrs.dep(), default = None),
+            "specs": attrs.option(attrs.arg(json = True), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.contacts_arg()
+        | re_test_common.test_args()
+        | test_common.attributes()
+    ),
+    cfg = go_test_transition,
+)
+
+go_bootstrap_binary = prelude_rule(
+    name = "go_bootstrap_binary",
+    docs = """
+        A `go_bootstrap_binary()` rule builds a minimal Go executable used
+        during bootstrap, where the full `go_binary()` machinery is not yet
+        available. It invokes the Go toolchain directly with the given
+        sources and `build_args`.
+    """,
+    attrs = (
+        go_common.srcs_arg()
+        | {
+            "build_args": attrs.list(attrs.string(), default = [], doc = """Package name, file names and build flags"""),
+            "workdir": attrs.string(default = "", doc = """Change to subdir before running the command"""),
+        }
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+go_stdlib = prelude_rule(
+    name = "go_stdlib",
+    docs = """
+        A `go_stdlib()` rule represents the Go standard library for the
+        target configuration. It has no user-facing attributes and is
+        consumed implicitly by other Go rules.
+    """,
+    attrs = {},
+    cfg = go_stdlib_transition,
+)
+
+go_rules = struct(
+    go_binary = go_binary,
+    go_bootstrap_binary = go_bootstrap_binary,
+    go_exported_library = go_exported_library,
+    go_library = go_library,
+    go_stdlib = go_stdlib,
+    go_test = go_test,
+)
diff --git a/buck2/prelude/decls/haskell_common.bzl b/buck2/prelude/decls/haskell_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/haskell_common.bzl
@@ -0,0 +1,137 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+def _srcs_arg():
+    return {
+        "srcs": attrs.named_set(
+            attrs.source(),
+            sorted = True,
+            default = [],
+            doc = """
+    A list of Haskell sources to be built by this rule. In the list form,
+    each source file must match the module name with "." replaced by "/", e.g.
+    `[ "Main.hs", "Other/Module.hs" ]`.
+    If the source files don't match the module names 1:1, then you
+    can use the dict form, in which the keys are module names, e.g.
+    `{ "Main": "src/test.hs", "Other.Module" : "src/Other/Module.hs" }`
+""",
+        ),
+    }
+
+def _deps_arg():
+    return {
+        "deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    Either `haskell_library()` or `prebuilt_haskell_library()` rules
+     from which this rules sources import modules or native linkable rules exporting symbols
+     this rules sources call into.
+""",
+        ),
+    }
+
+def _compiler_flags_arg():
+    return {
+        # attrs.arg(), not attrs.string(): lets a flag carry a
+        # `$(location ...)`/`$(exe ...)` macro that resolves to a real
+        # dependency edge.
+        "compiler_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    Flags to pass to the Haskell compiler when compiling this rule's sources.
+""",
+        ),
+    }
+
+def _build_tool_depends_arg():
+    return {
+        "build_tool_depends": attrs.list(
+            attrs.exec_dep(),
+            default = [],
+            doc = """
+    Executables (haskell_binary(), export_exe(), or anything else with a
+    single default output) that this rule's own GHC invocation needs
+    reachable via PATH by bare name. The executables can then be used
+    with -pgmL or -pgmF flags for example, either as a command-line
+    arg or in a {-# OPTIONS_GHC ... #-} pragma.
+
+    The build_tool_depends attribute is used to implement Cabal's
+    build-tool-depends: field.
+""",
+        ),
+    }
+
+def _run_tool_depends_arg():
+    return {
+        "run_tool_depends": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    Executables that the binary needs on PATH when it runs.
+    These are on PATH whenever the binary runs through its
+    RunInfo: with `buck2 run`, as a test, or as a tool of another rule.
+
+    This is used to implement Cabal's missing run-tool-depends field.
+""",
+        ),
+    }
+
+def _exported_linker_flags_arg():
+    return {
+        "exported_linker_flags": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    Linker flags used by dependent rules when linking with this library.
+""",
+        ),
+    }
+
+def _data_dirs_arg():
+    return {
+        "data_dirs": attrs.dict(
+            attrs.string(),
+            attrs.dep(),
+            sorted = False,
+            default = {},
+            doc = """
+    Directories of data files, each keyed by the name of the environment
+    variable that should point at it (for a Cabal package, `<pkg>_datadir`,
+    which its Paths_<pkg> module reads).
+
+    When this rule's sources are compiled, the compile sets only the
+    variables that its Template Haskell splices could read. These are the
+    variables for the rule's own Paths_<pkg> modules, and the variables for
+    the Paths_<pkg> modules of any library whose code the splices can run.
+    If the compile might run one of the rule's build tools, it sets all of
+    the rule's variables instead, because a build tool might read data files
+    of its own.
+
+    For a haskell_binary, all the variables are also set whenever the binary
+    is run through its RunInfo. That happens with `buck2 run`, when the
+    binary runs as a test, and when it runs as a tool of another rule.
+""",
+        ),
+    }
+
+haskell_common = struct(
+    srcs_arg = _srcs_arg,
+    deps_arg = _deps_arg,
+    compiler_flags_arg = _compiler_flags_arg,
+    exported_linker_flags_arg = _exported_linker_flags_arg,
+    build_tool_depends_arg = _build_tool_depends_arg,
+    data_dirs_arg = _data_dirs_arg,
+    run_tool_depends_arg = _run_tool_depends_arg,
+)
diff --git a/buck2/prelude/decls/haskell_rules.bzl b/buck2/prelude/decls/haskell_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/haskell_rules.bzl
@@ -0,0 +1,362 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//linking:types.bzl", "Linkage")
+load(":common.bzl", "LinkableDepType", "buck", "prelude_rule")
+load(":haskell_common.bzl", "haskell_common")
+load(":native_common.bzl", "native_common")
+
+haskell_binary = prelude_rule(
+    name = "haskell_binary",
+    docs = """
+        A `haskell_binary()` rule represents a groups of Haskell sources
+        and deps which build an executable.
+    """,
+    examples = """
+        ```
+        haskell_binary(
+          name = 'foo',
+          srcs = [
+            'Foo.hs',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "exe_name": attrs.option(attrs.string(), default = None, doc = "The file name of the executable, if not the name of the target."),
+            "main": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The main module serving as the entry point into the binary. If not specified,
+                 the compiler default is used.
+            """,
+            ),
+        }
+        | native_common.link_group_deps()
+        | native_common.link_group_public_deps_label()
+        | native_common.link_style()
+        | haskell_common.srcs_arg()
+        | haskell_common.compiler_flags_arg()
+        | haskell_common.deps_arg()
+        | haskell_common.build_tool_depends_arg()
+        | haskell_common.data_dirs_arg()
+        | haskell_common.run_tool_depends_arg()
+        | {
+            "deps_query": attrs.option(attrs.query(), default = None),
+            "enable_profiling": attrs.bool(default = False),
+            "ghci_platform_preload_deps": attrs.list(attrs.tuple(attrs.regex(), attrs.set(attrs.dep(), sorted = True)), default = []),
+            "ghci_preload_deps": attrs.set(attrs.dep(), sorted = True, default = []),
+            "link_deps_query_whole": attrs.bool(default = False),
+            # See haskell_library's compile_granularity.
+            "compile_granularity": attrs.option(attrs.enum(["target", "module"]), default = None),
+            "_per_module_compile": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//haskell/tools:per_module_compile")),
+            "_per_module_deps": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//haskell/tools:per_module_deps")),
+            "splice_depends": attrs.list(attrs.dep(), default = []),  # see haskell_library's splice_depends
+            "linker_flags": attrs.list(attrs.arg(), default = []),
+            "platform": attrs.option(attrs.string(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+haskell_ghci = prelude_rule(
+    name = "haskell_ghci",
+    docs = """
+        A `haskell_ghci()` rule produces a deployable script that
+        launches a GHCi session with the given sources and dependencies
+        preloaded. Building the rule compiles all dependent libraries
+        (including any C++ shared libraries that GHCi needs to load);
+        running the produced script enters the session ready for
+        `:reload`-driven development.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "compiler_flags": attrs.list(attrs.string(), default = []),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "deps_query": attrs.option(attrs.query(), default = None),
+            "enable_profiling": attrs.bool(default = False),
+            "extra_script_templates": attrs.list(attrs.source(), default = []),
+            "ghci_bin_dep": attrs.option(attrs.dep(), default = None),
+            "ghci_init": attrs.option(attrs.source(), default = None),
+            "linker_flags": attrs.list(attrs.arg(), default = []),
+            "platform": attrs.option(attrs.string(), default = None),
+            "preload_deps": attrs.set(attrs.dep(), sorted = True, default = []),
+            "srcs": attrs.named_set(attrs.source(), sorted = True, default = []),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+haskell_haddock = prelude_rule(
+    name = "haskell_haddock",
+    docs = """
+        A `haskell_haddock()` rule generates Haddock documentation for
+        the given Haskell dependencies. Extra flags can be passed to the
+        `haddock` tool via `haddock_flags`.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "deps": attrs.list(attrs.dep(), default = []),
+            "deps_query": attrs.option(attrs.query(), default = None),
+            "haddock_flags": attrs.list(attrs.arg(), default = []),
+            "platform": attrs.option(attrs.string(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+haskell_ide = prelude_rule(
+    name = "haskell_ide",
+    docs = """
+        A `haskell_ide()` rule defines a project set for use with an
+        LSP-based Haskell IDE (such as `ghcide`/HLS). When built, it
+        compiles the dependencies of the listed sources and produces the
+        GHC flags needed to load them as a single multi-component IDE
+        session, which is faster than loading each project individually
+        and avoids `ghcide`'s multi-component limitations.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "compiler_flags": attrs.list(attrs.string(), default = []),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "deps_query": attrs.option(attrs.query(), default = None),
+            "extra_script_templates": attrs.list(attrs.source(), default = []),
+            "link_style": attrs.enum(LinkableDepType),
+            "linker_flags": attrs.list(attrs.arg(), default = []),
+            "platform": attrs.option(attrs.string(), default = None),
+            "srcs": attrs.named_set(attrs.source(), sorted = True, default = []),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+haskell_library = prelude_rule(
+    name = "haskell_library",
+    docs = """
+        A `haskell_library()` rule is used to identity a group of
+        Haskell sources.
+    """,
+    examples = """
+        ```
+        haskell_library(
+          name = 'fileutil',
+          srcs = [
+            'FileUtil.hs',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        haskell_common.srcs_arg()
+        | haskell_common.compiler_flags_arg()
+        | haskell_common.deps_arg()
+        | haskell_common.exported_linker_flags_arg()
+        | haskell_common.build_tool_depends_arg()
+        | haskell_common.data_dirs_arg()
+        | native_common.link_whole(link_whole_type = attrs.bool(default = False))
+        | native_common.preferred_linkage(preferred_linkage_type = attrs.enum(Linkage.values()))
+        | {
+            "enable_profiling": attrs.bool(default = False),
+            "ghci_platform_preload_deps": attrs.list(attrs.tuple(attrs.regex(), attrs.set(attrs.dep(), sorted = True)), default = []),
+            "ghci_preload_deps": attrs.set(attrs.dep(), sorted = True, default = []),
+            "haddock_flags": attrs.list(attrs.arg(), default = []),
+            # How finely the target is compiled: "target", by one `ghc
+            # --make` action for the whole target, or "module", by an action
+            # for each module (experimental). If it isn't set, the
+            # toolchain's compile_granularity decides.
+            "compile_granularity": attrs.option(attrs.enum(["target", "module"]), default = None),
+            # Tools for per-module compilation
+            "_per_module_compile": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//haskell/tools:per_module_compile")),
+            "_per_module_deps": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//haskell/tools:per_module_deps")),
+            # The local dependencies (compiled per-module or built with
+            # --make) whose code the target's Template Haskell splices and
+            # ANN pragmas run. The target's compile (a Template Haskell
+            # module's, with per_module) waits until these libraries, and
+            # the libraries they depend on, are linked. Its splices can't run
+            # code of any other local library. Splices can always run code of prebuilt packages, so
+            # listing those makes no difference. The default, an empty list,
+            # means that splices run no local library's code.
+            "splice_depends": attrs.list(attrs.dep(), default = []),
+            # Libraries that are part of this one, as the C of a Cabal package
+            # is part of its library: their objects are in its archive, and
+            # linked into its shared library, and what depends on it isn't
+            # linked with them again (nor with their own dependencies, which
+            # the library should depend on). They should have static
+            # preferred linkage, and their link info be objects
+            # (use_archive = False, for a cxx_library).
+            "internal_deps": attrs.list(attrs.dep(), default = []),
+            # The internal_deps as built for profiling (as Cabal compiles a
+            # package's C for each way): the profiled library has their
+            # objects instead.
+            "prof_internal_deps": attrs.list(attrs.dep(), default = []),
+            # Whether the library's package is exposed: for a GHC that uses
+            # its package database as an installed one (as its global one,
+            # say). The build itself hides all packages.
+            "exposed": attrs.bool(default = False),
+            # Modules of the library that are only visible to modules
+            # in the library itself (a Cabal package's other-modules).
+            "hidden_modules": attrs.list(attrs.string(), default = []),
+            # The soname of the library's shared library, when it isn't its
+            # file's name.
+            "soname": attrs.option(attrs.string(), default = None),
+            "linker_flags": attrs.list(attrs.arg(), default = []),
+            # The name the library's package has in the package db, for
+            # `import "name" Module`. Not its id, which is derived from the
+            # label and is unique.
+            "package_name": attrs.option(attrs.string(), default = None),
+            # Modules the library re-exports from the library of one of its
+            # dependencies (or from itself, when there is none): the new name to
+            # the dependency and the module's original name (the
+            # `reexported-modules` of a Cabal package).
+            "reexported_modules": attrs.dict(attrs.string(), attrs.tuple(attrs.option(attrs.dep()), attrs.string()), default = {}),
+            # The library's unit id, when it must be a particular one (that of
+            # a package GHC knows by its unit id, say: rts, ghc-internal).
+            # Otherwise it is derived from the label.
+            "unit_id": attrs.option(attrs.string(), default = None),
+            # Its version, which GHC defines `VERSION_<package>` macros with:
+            # they must agree with the ones of the package's cabal_macros.h.
+            "package_version": attrs.option(attrs.string(), default = None),
+            "platform": attrs.option(attrs.string(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+haskell_prebuilt_library = prelude_rule(
+    name = "haskell_prebuilt_library",
+    docs = """
+        A `prebuilt_haskell_library()` rule is used to identify Haskell
+        prebuilt libraries and their associated interface files.
+    """,
+    examples = """
+        ```
+        prebuilt_haskell_library(
+          name = 'file',
+          static_interfaces = [
+            'interfaces',
+          ],
+          shared_interfaces = [
+            'interfaces_dyn',
+          ],
+          static_libs = [
+            'libFileUtil.a',
+          ],
+          shared_libs = {
+            'libFileUtil.so': 'libFileUtil.so',
+          },
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Other `prebuilt_haskell_library()` rules from which this library
+                 imports modules.
+            """,
+            ),
+            "static_libs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                The libraries to use when building a statically linked top-level target.
+            """,
+            ),
+            "shared_libs": attrs.dict(
+                key = attrs.string(),
+                value = attrs.source(),
+                sorted = False,
+                default = {},
+                doc = """
+                A map of shared library names to shared library paths to use when building a
+                 dynamically linked top-level target.
+            """,
+            ),
+            "runtime_shared_libs": attrs.dict(
+                key = attrs.string(),
+                value = attrs.source(),
+                sorted = False,
+                default = {},
+                doc = """
+                A map of shared library names to shared library paths that a dynamically
+                 linked top-level target needs when it runs, but which should not be
+                 explicitly linked. This is needed to support the RTS: GHC automatically
+                 links the appropriate flavour of the RTS when linking an executable,
+                 so we have to ensure the RTS shared libraries are available when
+                 the executable runs.
+            """,
+            ),
+            "exported_compiler_flags": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                Compiler flags used by dependent rules when compiling with this library.
+            """,
+            ),
+        }
+        | haskell_common.exported_linker_flags_arg()
+        | {
+            "cxx_header_dirs": attrs.list(attrs.source(), default = []),
+            "db": attrs.source(allow_directory = True),
+            "enable_profiling": attrs.bool(default = False),
+            "exported_post_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "id": attrs.string(default = ""),
+            "import_dirs": attrs.list(attrs.source(), default = []),
+            "pic_profiled_static_libs": attrs.list(attrs.source(), default = []),
+            "pic_static_libs": attrs.list(attrs.source(), default = []),
+            "profiled_static_libs": attrs.list(attrs.source(), default = []),
+            "version": attrs.string(default = ""),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+haskell_rules = struct(
+    haskell_binary = haskell_binary,
+    haskell_ghci = haskell_ghci,
+    haskell_haddock = haskell_haddock,
+    haskell_ide = haskell_ide,
+    haskell_library = haskell_library,
+    haskell_prebuilt_library = haskell_prebuilt_library,
+)
diff --git a/buck2/prelude/decls/java_rules.bzl b/buck2/prelude/decls/java_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/java_rules.bzl
@@ -0,0 +1,680 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//:attrs_validators.bzl", "validation_common")
+load("@prelude//:genrule.bzl", "genrule_attributes")
+load("@prelude//:validation_deps.bzl", "VALIDATION_DEPS_ATTR_NAME")
+load("@prelude//android:build_only_native_code.bzl", "is_build_only_native_code")
+load("@prelude//android:configuration.bzl", "is_building_android_binary_attr")
+load("@prelude//android:min_sdk_version.bzl", "get_min_sdk_version_constraint_value_name", "get_min_sdk_version_range")
+load("@prelude//decls:test_common.bzl", "test_common")
+load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")
+load(":common.bzl", "TestType", "buck", "prelude_rule")
+load(":jvm_common.bzl", "jvm_common")
+load(":re_test_common.bzl", "re_test_common")
+load(":toolchains_common.bzl", "toolchains_common")
+
+Style = ["obf", "pretty", "detailed"]
+
+def dex_min_sdk_version():
+    min_sdk_version_dict = {"DEFAULT": None}
+    for min_sdk in get_min_sdk_version_range():
+        constraint = "prelude//android/constraints:{}".format(get_min_sdk_version_constraint_value_name(min_sdk))
+        min_sdk_version_dict[constraint] = min_sdk
+
+    return select(min_sdk_version_dict)
+
+gwt_binary = prelude_rule(
+    name = "gwt_binary",
+    docs = """
+        A `gwt_binary()` rule produces a GWT (Google Web Toolkit) application
+        by invoking the GWT compiler against the listed `modules`. The
+        resulting output can be served as part of a web app.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "deps": attrs.list(attrs.dep(), default = []),
+            "draft_compile": attrs.bool(default = False),
+            "experimental_args": attrs.list(attrs.string(), default = []),
+            "local_workers": attrs.int(default = 2),
+            "module_deps": attrs.list(attrs.dep(), default = []),
+            "modules": attrs.list(attrs.string(), default = []),
+            "optimize": attrs.int(default = 9),
+            "strict": attrs.bool(default = False),
+            "style": attrs.enum(Style, default = "obf"),
+            "vm_args": attrs.list(attrs.string(), default = []),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_java_toolchain": toolchains_common.java(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+jar_genrule = prelude_rule(
+    name = "jar_genrule",
+    docs = """
+        A `jar_genrule()` is a variant of `genrule()` whose output is
+        packaged into a JAR file. Use it to produce a JAR from arbitrary
+        commands (`bash`/`cmd`/`cmd_exe`) that operate on `srcs`.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "bash": attrs.option(attrs.arg(), default = None),
+            "cacheable": attrs.option(attrs.bool(), default = None),
+            "cmd": attrs.option(attrs.arg(), default = None),
+            "cmd_exe": attrs.option(attrs.arg(), default = None),
+            "enable_sandbox": attrs.option(attrs.bool(), default = None),
+            "environment_expansion_separator": attrs.option(attrs.string(), default = None),
+            "weight": attrs.option(attrs.int(), default = None),
+            "remote": attrs.option(attrs.bool(), default = None),
+            "srcs": attrs.named_set(attrs.source(), sorted = False, default = []),
+            "type": attrs.option(attrs.string(), default = None),
+        }
+        | genrule_attributes()
+        | {
+            "_java_toolchain": toolchains_common.java(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+java_annotation_processor = prelude_rule(
+    name = "java_annotation_processor",
+    docs = """
+        A `java_annotation_processor()` rule declares a Java annotation
+        processor (identified by `processor_class`) that can be referenced
+        from `java_library()` and `kotlin_library()` rules to run during
+        compilation.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "deps": attrs.list(attrs.dep(), default = []),
+            "does_not_affect_abi": attrs.bool(default = False),
+            "isolate_class_loader": attrs.bool(default = False),
+            "processor_class": attrs.string(default = ""),
+            "supports_abi_generation_from_source": attrs.bool(default = False),
+            "runs_on_java_only": attrs.bool(default = False),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+java_binary = prelude_rule(
+    name = "java_binary",
+    docs = """
+        A `java_binary()` rule is used to create a JAR file of the
+        compiled .class files and resources of the `java_library()`
+         rules on which it depends.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "base_dep": attrs.option(
+                attrs.dep(),
+                default = None,
+                doc = """
+                Rule (normally of type `java_library`) that should be
+                 compiled and used as a base JAR to receive all dependencies through an append operation.
+            """,
+            ),
+            "build_manifest": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                MANIFEST containing stamped build attributes, that should be merged into the main jar manifest
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Rules (normally of type `java_library`) that should be
+                 compiled and whose `.class` files and resources should be
+                 included in the generated JAR file.
+            """,
+            ),
+            "main_class": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                If provided, this will be the value specified as the
+                 `Main-Class` attribute of the `META-INF/MANIFEST.MF`
+                 file in the generated JAR file. Also, when this rule is used as
+                 an executable in a `genrule()`,
+                 `main_class` will indicate the class whose `main()` method will be invoked to process the command-line arguments. This
+                 is consistent with the expected usage of `java -jar
+                 *<name.jar>* *<args>*`.
+            """,
+            ),
+            "manifest_file": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                If provided, this manifest will be used when generating the JAR
+                 file. If combined with `main_class`, the specified manifest
+                 file will be used but the `main_class` will override the main
+                 class in the manifest.
+            """,
+            ),
+            "java_args_for_run_info": attrs.list(attrs.string(), default = []),
+            "meta_inf_directory": attrs.option(
+                attrs.source(allow_directory = True),
+                default = None,
+                doc = """
+                Note: This has beta support currently.
+                 If provided, the contents in this directory will end up in the
+                 `META-INF` directory inside the generated JAR file.
+            """,
+            ),
+            "blocklist": attrs.list(
+                attrs.regex(),
+                default = [],
+                doc = """
+                A list of patterns that identify files to exclude from the final generated JAR
+                 file. Example:
+
+                ```
+                java_binary(
+                  name = 'example',
+                  blocklist = [
+                    # Excludes com.example.A and com.example.Alligator,
+                    # as well as their inner classes and any non-class files that happen to match
+                    # the pattern
+                    'com.example.A',
+
+                    # Excludes all files from org/slf4j/**/*.
+                    'org.slf4j',
+                  ],
+                  deps = [
+                    ':example1',
+                    ':third-party-stuff',
+                  ],
+                )
+                ```
+            """,
+            ),
+            "concat_deps": attrs.bool(default = False, doc = "Use zip concatenation instead of repacking all dependency jars, which is faster"),
+            "default_cxx_platform": attrs.option(attrs.string(), default = None),
+            "generate_wrapper": attrs.bool(default = False),
+            "do_not_create_inner_jar": attrs.bool(default = False),
+            "incremental_target_prefix": attrs.option(attrs.string(), default = None),
+            "java_version": attrs.option(attrs.string(), default = None, doc = "Expected java version used at compile time"),
+            "java_runtime": attrs.option(attrs.string(), default = None, doc = "Expected java version used at runtime"),
+            "proguard_config": attrs.option(attrs.source(), default = None),
+            "proguard_jvm_args": attrs.list(attrs.string(), default = []),
+            "proguard_library_jars": attrs.list(attrs.source(), default = []),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_is_building_android_binary": is_building_android_binary_attr(),
+            "_java_toolchain": toolchains_common.java(),
+        }
+        | constraint_overrides.attributes
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+    cfg = constraint_overrides.transition,
+)
+
+java_library = prelude_rule(
+    name = "java_library",
+    docs = """
+        A `java_library()` rule defines a set of Java
+        files that can be compiled together. The main output of a
+         `java_library()` rule is a single JAR file containing all
+        of the compiled class files, as well as the static files specified in
+        the `resources` argument.
+    """,
+    examples = """
+        ```
+        # A rule that compiles a single .java file.
+        java_library(
+          name = 'JsonUtil',
+          srcs = ['JsonUtil.java'],
+          deps = [
+            '//third_party/guava:guava',
+            '//third_party/jackson:jackson',
+          ],
+        )
+
+        # A rule that compiles all of the .java files under the directory in
+        # which the rule is defined using glob(). It also excludes an
+        # individual file that may have additional dependencies, so it is
+        # compiled by a separate rule.
+        java_library(
+          name = 'messenger',
+          srcs = glob(['**/*.java'], excludes = ['MessengerModule.java']),
+          deps = [
+            '//src/com/facebook/base:base',
+            '//third_party/guava:guava',
+          ],
+        )
+
+        java_library(
+          name = 'MessengerModule',
+          srcs = ['MessengerModule.java'],
+          deps = [
+            '//src/com/facebook/base:base',
+            '//src/com/google/inject:inject',
+            '//third_party/guava:guava',
+            '//third_party/jsr-330:jsr-330',
+          ],
+        )
+
+        # A rule that builds a library with both relative and
+        # fully-qualified deps.
+        java_library(
+          name = 'testutil',
+          srcs = glob(['tests/**/*.java'], excludes = 'tests/**/*Test.java'),
+          deps = [
+            ':lib-fb4a',
+            '//java/com/facebook/base:base',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "srcs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                The set of `.java` files to compile for this rule.
+                 If any of the files in this list end in `.src.zip`,
+                 then the entries in the ZIP file that end in `.java` will be
+                 included as ordinary inputs to compilation. This is common when using
+                 a `genrule()` to auto-generate some Java source code that
+                 needs to be compiled with some hand-written Java code.
+            """,
+            ),
+        }
+        | jvm_common.resources_arg()
+        | {
+            "concat_resources": attrs.bool(
+                default = False,
+                doc = """
+                Use parallel compression and concatenation of intermediary jars to speed up jar time generation.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Rules (usually other `java_library` rules) that are used to
+                 generate the classpath required to compile this `java_library`.
+            """,
+            ),
+            "extra_arguments": attrs.list(
+                attrs.string(),
+                default = [],
+                doc = """
+                List of additional arguments to pass into the Java compiler. These
+                 arguments follow the ones specified in `.buckconfig`.
+            """,
+            ),
+            "java_version": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Equivalent to setting both `source` and `target`  to the given value. Setting this and `source` or `target` (or both!) is an error.
+            """,
+            ),
+            "source": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Specifies the version of Java (as a string) to interpret source
+                 files as.
+                 Overrides the value in "source\\_level" in the "java" section
+                 of `.buckconfig`.
+            """,
+            ),
+            "target": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Specifies the version of Java (as a string) for which to
+                 generate code.
+                 Overrides the value in "target\\_level" in the "java" section
+                 of `.buckconfig`.
+            """,
+            ),
+        }
+        | jvm_common.annotation_processors()
+        | jvm_common.remove_classes_arg()
+        | jvm_common.exported_deps()
+        | jvm_common.provided_deps()
+        | jvm_common.exported_provided_deps()
+        | jvm_common.abi_generation_mode()
+        | jvm_common.source_only_abi_deps()
+        | jvm_common.required_for_source_only_abi()
+        | jvm_common.plugins()
+        | jvm_common.multi_release_jar()
+        | jvm_common.javac()
+        | jvm_common.classic_java_content_based_paths()
+        | {
+            "class_to_src_map_deps": attrs.list(attrs.dep(), default = []),
+            "jar_postprocessor": attrs.option(attrs.exec_dep(), default = None),
+            "manifest_file": attrs.option(attrs.source(), default = None),
+            "maven_coords": attrs.option(attrs.string(), default = None),
+            "proguard_config": attrs.option(attrs.source(), default = None),
+            "resources_root": attrs.option(attrs.string(), default = None),
+            "runtime_deps": attrs.list(attrs.dep(), default = []),
+            VALIDATION_DEPS_ATTR_NAME: attrs.set(attrs.dep(), sorted = True, default = []),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_dex_min_sdk_version": attrs.option(attrs.int(), default = dex_min_sdk_version()),
+            "_dex_toolchain": toolchains_common.dex(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_is_building_android_binary": is_building_android_binary_attr(),
+            "_java_toolchain": toolchains_common.java(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+        | validation_common.attrs_validators_arg()
+    ),
+)
+
+java_plugin = prelude_rule(
+    name = "java_plugin",
+    docs = """
+        A `java_plugin()` rule declares a `javac` plugin (identified by
+        `plugin_name`) that can be referenced from `java_library()` and
+        `kotlin_library()` rules to run during compilation.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "deps": attrs.list(attrs.dep(), default = []),
+            "does_not_affect_abi": attrs.bool(default = False),
+            "isolate_class_loader": attrs.bool(default = False),
+            "plugin_name": attrs.string(default = ""),
+            "supports_abi_generation_from_source": attrs.bool(default = False),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+java_test = prelude_rule(
+    name = "java_test",
+    docs = """
+        A `java_test()` rule is used to define a set of
+         `.java` files that contain tests to run via JUnit.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.inject_test_env_arg()
+        | {
+            "resources": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Same as `java_library()`.
+            """,
+            ),
+            "srcs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Like `java_library()`,
+                 all of the `.java` files specified by the
+                 `srcs` argument will be compiled when this rule is
+                 built. In addition, all of the corresponding `.class` files that are built by this rule will be passed as arguments to
+                 JUnit when this rule is run as a test. `.class` files
+                 that are passed to JUnit that do not have any methods annotated with
+                 `@Test` are considered failed tests, so make sure that
+                 only test case classes are specified as `srcs`. This is
+                 frequently done by specifying `srcs` as
+                 `glob(['**/*Test.java'])`.
+            """,
+            ),
+        }
+        | buck.test_label_arg()
+        | {
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Same as `java_library()`.
+                 // org.junit.rules.Timeout was not introduced until 4.7.
+                 Must include JUnit (version 4.7 or later) as a dependency for JUnit tests.
+                 Must include TestNG (version 6.2 or later) and hamcrest as a dependencies for TestNG tests.
+            """,
+            ),
+            "source": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Java language level for compiling. Corresponds to the
+                 `-source` argument for `javac`.
+            """,
+            ),
+            "target": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                Bytecode target level for compiling. Corresponds to the
+                 `-target` argument for `javac`.
+            """,
+            ),
+            "test_type": attrs.option(
+                attrs.enum(TestType),
+                default = None,
+                doc = """
+                Specifies which test framework to use.
+                 The currently supported options are 'junit' and 'testng'.
+            """,
+            ),
+        }
+        | buck.run_test_separately_arg(
+            run_test_separately_type = attrs.bool(
+                default = False,
+                doc = """
+            If set to True, the test(s) in this rule are run separately from
+             all other tests. This is useful for integration tests which
+             access a physical device or other limited resource. If unset,
+             the test(s) in this rule run in parallel with all other tests.
+        """,
+            )
+        )
+        | re_test_common.test_args()
+        | buck.test_rule_timeout_ms()
+        | {
+            "cxx_library_allowlist": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                 List of cxx_library targets to build, if use_cxx_libraries is true.
+                 This can be useful if some dependencies are Android-only and won't build for the test host platform.
+            """,
+            ),
+            "use_cxx_libraries": attrs.option(
+                attrs.bool(),
+                default = None,
+                doc = """
+                Whether or not to build and link against `cxx_library()` dependencies when testing.
+            """,
+            ),
+            "vm_args": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                Runtime arguments to the JVM running the tests.
+            """,
+            ),
+        }
+        | jvm_common.test_env()
+        | jvm_common.abi_generation_mode()
+        | {
+            "deps_query": attrs.option(attrs.query(), default = None),
+            "discover_all_test_classes": attrs.bool(default = False),
+            "exported_deps": attrs.list(attrs.dep(), default = []),
+            "exported_provided_deps": attrs.list(attrs.dep(), default = []),
+            "extra_arguments": attrs.list(attrs.string(), default = []),
+            "jar_postprocessor": attrs.option(attrs.exec_dep(), default = None),
+            "java": attrs.option(attrs.dep(), default = None),
+            "java_agents": attrs.list(attrs.source(), default = []),
+            "java_version": attrs.option(attrs.string(), default = None),
+            "manifest_file": attrs.option(attrs.source(), default = None),
+            "maven_coords": attrs.option(attrs.string(), default = None),
+            "proguard_config": attrs.option(attrs.source(), default = None),
+            "provided_deps": attrs.list(attrs.dep(), default = []),
+            "remove_classes": attrs.list(attrs.regex(), default = []),
+            "required_for_source_only_abi": attrs.bool(default = False),
+            "resources_root": attrs.option(attrs.string(), default = None),
+            "runner": attrs.option(attrs.dep(), default = None),
+            "runtime_deps": attrs.list(attrs.dep(), default = []),
+            "source_only_abi_deps": attrs.list(attrs.dep(), default = []),
+            "supports_test_execution_caching": attrs.bool(default = False),
+            "test_case_timeout_ms": attrs.option(attrs.int(), default = None),
+            "test_class_names_file": attrs.option(attrs.source(), default = None),
+            "unbundled_resources_root": attrs.option(attrs.source(allow_directory = True), default = None),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_is_building_android_binary": attrs.default_only(attrs.bool(default = False)),
+            "_java_test_toolchain": toolchains_common.java_test(),
+            "_java_toolchain": toolchains_common.java(),
+        }
+        | constraint_overrides.attributes
+        | buck.licenses_arg()
+        | buck.contacts_arg()
+        | validation_common.attrs_validators_arg()
+    )
+    | jvm_common.annotation_processors()
+    | jvm_common.plugins()
+    | jvm_common.javac()
+    | test_common.attributes()
+    | jvm_common.classic_java_content_based_paths(),
+    cfg = constraint_overrides.transition,
+)
+
+prebuilt_jar = prelude_rule(
+    name = "prebuilt_jar",
+    docs = """
+        A `prebuilt_jar()` rule is used to identify a JAR file that
+        is checked into our repository as a precompiled binary rather than one
+        that is built from source by Buck. Frequently, these are used to
+        reference third-party JAR files (such as junit.jar) and
+        are used as dependencies of `java_library()` rules.
+    """,
+    examples = """
+        ```
+        prebuilt_jar(
+          name = 'junit',
+          binary_jar = 'junit-4.8.2.jar',
+          source_jar = 'junit-4.8.2-sources.jar',
+          javadoc_url = 'http://kentbeck.github.com/junit/javadoc/4.8/',
+        )
+
+        java_library(
+          name = 'tests',
+          srcs = glob(['tests/**/*Test.java']),
+          deps = [
+            ':junit',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "binary_jar": attrs.source(
+                doc = """
+                Path to the pre-built JAR file.
+            """
+            ),
+            "source_jar": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                Path to a JAR file that contains the `.java` files to create
+                 the `.class` in the `binary_jar`. This is frequently
+                 provided for debugging purposes.
+            """,
+            ),
+            "javadoc_url": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                URL to the Javadoc for the `.class` files in the
+                 `binary_jar`.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                 Rules that must be built before this rule. Because the
+                 `binary_jar` is already built, there should be nothing to
+                 build, so this should be empty.
+            """,
+            ),
+            "desugar_deps": attrs.list(attrs.dep(), default = []),
+            "generate_abi": attrs.bool(default = True),
+            "is_executable": attrs.bool(default = False),
+            "maven_coords": attrs.option(attrs.string(), default = None),
+            # Prebuilt jars are quick to build, and often contain third-party code, which in turn is
+            # often a source of annotations and constants. To ease migration to ABI generation from
+            # source without deps, we have them present during ABI gen by default.
+            "required_for_source_only_abi": attrs.bool(default = True),
+            "uses_content_based_paths": jvm_common.content_based_path_attr(),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_dex_min_sdk_version": attrs.option(attrs.int(), default = dex_min_sdk_version()),
+            "_dex_toolchain": toolchains_common.dex(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_prebuilt_jar_toolchain": toolchains_common.prebuilt_jar(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+java_rules = struct(
+    gwt_binary = gwt_binary,
+    jar_genrule = jar_genrule,
+    java_annotation_processor = java_annotation_processor,
+    java_binary = java_binary,
+    java_library = java_library,
+    java_plugin = java_plugin,
+    java_test = java_test,
+    prebuilt_jar = prebuilt_jar,
+)
diff --git a/buck2/prelude/decls/js_rules.bzl b/buck2/prelude/decls/js_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/js_rules.bzl
@@ -0,0 +1,107 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load(":common.bzl", "buck", "prelude_rule")
+
+js_bundle = prelude_rule(
+    name = "js_bundle",
+    docs = """
+        A `js_bundle()` rule builds a JavaScript bundle from one or more entry points,
+        pulling in `js_library()` dependencies and invoking a worker tool to perform
+        the bundling.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "android_package": attrs.option(attrs.string(), default = None),
+            "bundle_name": attrs.option(attrs.string(), default = None),
+            "bundle_name_for_flavor": attrs.list(attrs.tuple(attrs.string(), attrs.string()), default = []),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "entry": attrs.one_of(attrs.set(attrs.string(), sorted = False), attrs.string()),
+            "extra_json": attrs.option(attrs.arg(), default = None),
+            "fallback_transform_profile": attrs.option(attrs.string(), default = None),
+            "worker": attrs.dep(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+js_bundle_genrule = prelude_rule(
+    name = "js_bundle_genrule",
+    docs = """
+        `js_bundle_genrule` is a genrule that acts on a `js_bundle` and provides a bunch of
+        additional environment variables for the genrule to use.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "bash": attrs.option(attrs.arg(), default = None),
+            "bundle_name": attrs.option(attrs.string(), default = None),
+            "bundle_name_for_flavor": attrs.list(attrs.tuple(attrs.string(), attrs.string()), default = []),
+            "cacheable": attrs.option(attrs.bool(), default = None),
+            "cmd": attrs.option(attrs.arg(), default = None),
+            "cmd_exe": attrs.option(attrs.arg(), default = None),
+            "enable_sandbox": attrs.option(attrs.bool(), default = None),
+            "environment_expansion_separator": attrs.option(attrs.string(), default = None),
+            "js_bundle": attrs.dep(),
+            "remote": attrs.option(attrs.bool(), default = None),
+            "rewrite_deps_file": attrs.bool(default = False),
+            "rewrite_misc": attrs.bool(default = False),
+            "rewrite_sourcemap": attrs.bool(default = False),
+            "skip_resources": attrs.bool(default = False),
+            "srcs": attrs.named_set(attrs.source(), sorted = False, default = []),
+            "weight": attrs.option(attrs.int(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+js_library = prelude_rule(
+    name = "js_library",
+    docs = """
+        A `js_library()` rule groups together JavaScript source files and assets so they
+        can be consumed by a `js_bundle()`.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "asset_extensions": attrs.option(attrs.set(attrs.string(), sorted = False), default = None),
+            "asset_platforms": attrs.option(attrs.set(attrs.string(), sorted = False), default = None),
+            "base_path": attrs.option(attrs.string(), default = None),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "deps_query": attrs.option(attrs.query(), default = None),
+            "extra_json": attrs.option(attrs.arg(), default = None),
+            "srcs": attrs.list(attrs.one_of(attrs.source(), attrs.tuple(attrs.source(), attrs.string())), default = []),
+            "worker": attrs.dep(),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+js_rules = struct(
+    js_bundle = js_bundle,
+    js_bundle_genrule = js_bundle_genrule,
+    js_library = js_library,
+)
diff --git a/buck2/prelude/decls/jvm_common.bzl b/buck2/prelude/decls/jvm_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/jvm_common.bzl
@@ -0,0 +1,390 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load(":common.bzl", "AbiGenerationMode")
+
+def _test_env():
+    return {
+        "env": attrs.dict(
+            key = attrs.string(),
+            value = attrs.arg(),
+            sorted = False,
+            default = {},
+            doc = """
+    A map of environment names and values to set when running the test.
+""",
+        ),
+    }
+
+def _resources_arg():
+    return {
+        "resources": attrs.list(
+            attrs.source(),
+            default = [],
+            doc = """
+    Static files to include with the compiled `.class` files.
+     These files can be loaded
+     via [Class.getResource()](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)).
+
+    **Note:** If `resources_root` isn't set,
+     Buck uses the ``.buckconfig``
+     property in `.buckconfig` to
+     determine where resources should be placed within the generated JAR
+     file.
+""",
+        ),
+        "resources_root": attrs.option(
+            attrs.source(),
+            default = None,
+            doc = """
+    The path that resources are resolved against. For example, if `resources_root` is `"res"` and
+     `resources` contains the file `"res/com/example/foo.txt"`, that file will end up as `"com/example/foo.txt"` in the output JAR. This parameter
+     overrides the ``.buckconfig`` property in `.buckconfig`.
+""",
+        ),
+    }
+
+def _remove_classes_arg():
+    return {
+        "remove_classes": attrs.list(
+            attrs.regex(),
+            default = [],
+            doc = """
+    Specifies a list of `Patterns` that are used to exclude
+     `classes` from the `JAR`. The pattern matching is
+     based on the name of the class. This can be used to exclude a member
+     class or delete a local view of a class that will be replaced during
+     a later stage of the build.
+""",
+        ),
+    }
+
+def _provided_deps():
+    return {
+        "provided_deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    These represent dependencies that are known to be provided at run
+     time, but are required in order for the code to compile. Examples of
+     `provided_deps` include the JEE servlet APIs. When this
+     rule is included in a , the
+     `provided_deps` will not be packaged into the output.
+""",
+        ),
+    }
+
+def _exported_deps():
+    return {
+        "exported_deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    Other  rules that depend on this rule will also
+     include its `exported_deps` in their classpaths. This is useful
+     when the public API of a rule has return types or checked exceptions that are
+     defined in another rule, which would otherwise require callers to add an
+     extra dependency. It's also useful for exposing e.g. a collection of
+     `prebuilt_jar` rules as a single target for callers to depend
+     on. Targets in `exported_deps` are implicitly included in the
+     `deps` of this rule, so they don't need to be repeated there.
+""",
+        ),
+    }
+
+def _multi_release_jar():
+    return {
+        "min_release_version": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+                Minimal java version that the library should be compatible with.
+                This ensures that both the language features and the bytecode generated are
+                compatible with the specified Java version, and only APIs available in that version are accessible.
+            """,
+        ),
+        "multi_release_srcs": attrs.dict(
+            key = attrs.string(),
+            value = attrs.list(attrs.source(), default = []),
+            default = {},
+            doc = """
+                The set of `.java` files to compile for the mapped java version.
+                Each version will be packed under META-INF/versions/java_version.
+            """,
+        ),
+    }
+
+def _exported_provided_deps():
+    return {
+        "exported_provided_deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    This is a combination of `provided_deps` and `exported_deps`. Rules listed
+     in this parameter will be added to classpath of rules that depend on this rule, but they will not
+     be included in a binary if binary depends on a such target.
+""",
+        ),
+    }
+
+def _source_only_abi_deps():
+    return {
+        "source_only_abi_deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    These are dependencies that must be present during
+     `source-only ABI generation`.
+     Typically such dependencies are added when some property of the code in this rule prevents source-only ABI
+     generation from being correct without these dependencies being present.
+
+     Having `source_only_abi_deps` prevents Buck from
+     completely flattening the build graph, thus reducing the performance win from source-only
+     ABI generation. They should be avoided when possible. Often only a small code change is needed to avoid them.
+     For more information on such code changes, read about
+     `source-only ABI generation`.
+""",
+        ),
+    }
+
+def _abi_generation_mode():
+    return {
+        "abi_generation_mode": attrs.option(
+            attrs.enum(AbiGenerationMode),
+            default = None,
+            doc = """
+    Overrides `.buckconfig`
+    for this rule.
+""",
+        ),
+    }
+
+def _required_for_source_only_abi():
+    return {
+        "required_for_source_only_abi": attrs.bool(
+            default = False,
+            doc = """
+    Indicates that this rule must be present on the classpath during
+     `source-only ABI generation`
+     of any rule that depends on it. Typically this is done when a rule contains annotations,
+     enums, constants, or interfaces.
+
+     Having rules present on the classpath during source-only ABI generation prevents Buck from
+     completely flattening the build graph, thus reducing the performance win from source-only
+     ABI generation. These rules should be kept small (ideally just containing annotations,
+     constants, enums, and interfaces) and with minimal dependencies of their own.
+""",
+        ),
+    }
+
+def _k2():
+    return {
+        "k2": attrs.bool(
+            default = True,
+            doc = """
+    Enables the Kotlin K2 compiler.
+    """,
+        ),
+    }
+
+def _incremental():
+    return {
+        "incremental": attrs.bool(
+            default = False,
+            doc = """
+                Enables Kotlin incremental compilation.
+            """,
+        ),
+    }
+
+def _enable_used_classes():
+    return {
+        "enable_used_classes": attrs.bool(
+            default = True,
+            doc = """
+    Deprecated: for an experiment only, will be removed
+    """,
+        ),
+    }
+
+def _plugins():
+    return {
+        "non_exec_dep_plugins_deprecated": attrs.list(
+            attrs.one_of(
+                attrs.dep(),
+                attrs.tuple(attrs.dep(), attrs.list(attrs.string())),
+            ),
+            default = [],
+            doc = """
+                Plugins that do not use the execution platform. This exists for historical reasons,
+                and should not be used. Use `plugins` instead - plugins should be configured for
+                the execution platform since that is where they are used.
+                """,
+        ),
+        "plugins": attrs.list(
+            attrs.one_of(
+                attrs.exec_dep(),
+                attrs.tuple(attrs.exec_dep(), attrs.list(attrs.string())),
+            ),
+            default = [],
+            doc = """
+                List of plugins that should be run during compilation of the target. A list of
+                strings may additionally be provided in order to pass additional arguments to
+                the plugin.
+                """,
+        ),
+    }
+
+def _kotlin_compiler_plugins():
+    return {
+        "kotlin_compiler_plugins": attrs.list(
+            attrs.tuple(attrs.exec_dep(), attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False)),
+            default = [],
+            doc = """
+                Use this to specify [Kotlin compiler plugins](https://kotlinlang.org/docs/reference/compiler-plugins.html) to use when compiling this library.
+                 This takes a map, with each entry specify one plugin. Entry's key is plugin source path,
+                 and value is a map of plugin option key value pair. Unlike `extra_kotlinc_arguments`,
+                 these can be *source paths*, not just strings.
+
+                 A special option value is
+                 `__codegen_dir__`, in which case Buck will provide a default codegen folder's path as
+                 option value instead.
+                 E.g.
+
+                ```
+fbcode/buck2/prelude/decls/jvm_common.bzl
+                kotlin_compiler_plugins = {
+                    "somePluginSourcePath": {
+                        "plugin:somePluginId:somePluginOptionKey": "somePluginOptionValue",
+                        "plugin:somePluginId:someDirectoryRelatedOptionKey": "__codegen_dir__",
+                    },
+                },
+                ```
+                Each plugin source path will be prefixed with `-Xplugin=` and passed as extra
+                 arguments to the compiler. Plugin options will be appended after its plugin with `-P`.
+
+                 A specific example is, if you want to use [kotlinx.serialization](https://github.com/Kotlin/kotlinx.serialization)
+                 with `kotlin_library()`, you need to specify `kotlinx-serialization-compiler-plugin.jar` under `kotlin_compiler_plugins` and `kotlinx-serialization-runtime.jar` (which you may have to fetch from Maven) in your `deps`:
+
+                ```
+                kotlin_library(
+                    name = "example",
+                    srcs = glob(["*.kt"]),
+                    deps = [
+                        ":kotlinx-serialization-runtime",
+                    ],
+                    kotlin_compiler_plugins = {
+                        # Likely copied from your $KOTLIN_HOME directory.
+                        "kotlinx-serialization-compiler-plugin.jar": {},
+                    },
+                )
+
+                prebuilt_jar(
+                    name = "kotlinx-serialization-runtime",
+                    binary_jar = ":kotlinx-serialization-runtime-0.10.0",
+                )
+
+                # Note you probably want to set
+                # maven_repo=http://jcenter.bintray.com/ in your .buckconfig until
+                # https://github.com/Kotlin/kotlinx.serialization/issues/64
+                # is closed.
+                remote_file(
+                    name = "kotlinx-serialization-runtime-0.10.0",
+                    out = "kotlinx-serialization-runtime-0.10.0.jar",
+                    url = "mvn:org.jetbrains.kotlinx:kotlinx-serialization-runtime:jar:0.10.0",
+                    sha1 = "23d777a5282c1957c7ce35946374fff0adab114c"
+                )
+                ```
+            """,
+        ),
+    }
+
+def _annotation_processors():
+    return {
+        "annotation_processor_deps": attrs.list(attrs.exec_dep(), default = []),
+        "annotation_processor_params": attrs.list(attrs.string(), default = []),
+        "annotation_processors": attrs.list(attrs.string(), default = []),
+    }
+
+def _content_based_path_attr():
+    return attrs.bool(
+        default = select({
+            "DEFAULT": False,
+            # @oss-disable[end= ]: "config//build_mode/constraints:_whatsapp[whatsapp]": True,
+            # @oss-disable[end= ]: "config//build_mode:arvr_mode[enabled]": True,
+            # @oss-disable[end= ]: "config//os/constraints:android": True,
+            # @oss-disable[end= ]: "config//runtime/constraints:android-host-test": True,
+            # @oss-disable[end= ]: "config//runtime/constraints:android-unit-test": True,
+        })
+    )
+
+def _kotlincd_content_based_paths():
+    return {
+        "uses_content_based_paths_for_kotlincd": attrs.bool(default = True),
+    }
+
+def _classic_java_content_based_paths():
+    return {
+        "uses_content_based_paths_for_classic_java": _content_based_path_attr(),
+    }
+
+def _javac():
+    return {
+        "javac": attrs.option(
+            attrs.one_of(attrs.exec_dep(), attrs.source()),
+            default = None,
+            doc = """
+            Specifies the Java compiler program to use for this rule.
+                The value is a source path or an execution dep (e.g., //foo/bar:bar).
+                Overrides the value in "javac" in the "tools" section
+                of `.buckconfig`.
+            """,
+        ),
+    }
+
+def _friend_paths_attr():
+    return attrs.list(
+        attrs.one_of(attrs.dep(), attrs.string()),
+        default = [],
+        doc = """
+    Modules whose `internal` declarations this rule may access, passed to the Kotlin compiler as
+     friend-paths.
+
+    An entry is either a target (`//foo/bar:baz`) or a build target pattern covering more than one
+     target (`//foo/bar/...` recursively, or `//foo/bar:` for a single package).
+""",
+    )
+
+jvm_common = struct(
+    test_env = _test_env,
+    friend_paths_attr = _friend_paths_attr,
+    resources_arg = _resources_arg,
+    remove_classes_arg = _remove_classes_arg,
+    provided_deps = _provided_deps,
+    exported_deps = _exported_deps,
+    exported_provided_deps = _exported_provided_deps,
+    source_only_abi_deps = _source_only_abi_deps,
+    abi_generation_mode = _abi_generation_mode,
+    required_for_source_only_abi = _required_for_source_only_abi,
+    k2 = _k2,
+    incremental = _incremental,
+    plugins = _plugins,
+    kotlin_compiler_plugins = _kotlin_compiler_plugins,
+    annotation_processors = _annotation_processors,
+    javac = _javac,
+    enable_used_classes = _enable_used_classes,
+    multi_release_jar = _multi_release_jar,
+    classic_java_content_based_paths = _classic_java_content_based_paths,
+    kotlincd_content_based_paths = _kotlincd_content_based_paths,
+    content_based_path_attr = _content_based_path_attr,
+)
diff --git a/buck2/prelude/decls/kotlin_rules.bzl b/buck2/prelude/decls/kotlin_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/kotlin_rules.bzl
@@ -0,0 +1,304 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//:attrs_validators.bzl", "validation_common")
+load("@prelude//:validation_deps.bzl", "VALIDATION_DEPS_ATTR_NAME")
+load("@prelude//android:build_only_native_code.bzl", "is_build_only_native_code")
+load("@prelude//android:configuration.bzl", "is_building_android_binary_attr")
+load("@prelude//decls:test_common.bzl", "test_common")
+load(":common.bzl", "TestType", "buck", "prelude_rule")
+load(":java_rules.bzl", "dex_min_sdk_version")
+load(":jvm_common.bzl", "jvm_common")
+load(":re_test_common.bzl", "re_test_common")
+load(":toolchains_common.bzl", "toolchains_common")
+
+_no_x_jdk_release_doc = """
+        By default, classic kotlin adds -Xjdk-release=java_version to the kotlinc arguments.
+        Set this to True to not add -Xjdk-release=java_version to the kotlinc arguments.
+        This is helpful if the -Xjdk-release= brings trouble since it is not 100% guaranteed to work as expected.
+        See the [doc of kotlinc](https://kotlinlang.org/docs/compiler-reference.html#xjdk-release-version) for more detail.
+"""
+
+kotlin_library = prelude_rule(
+    name = "kotlin_library",
+    docs = """
+        A `kotlin_library()` rule is used to define a set of Kotlin
+        files that can be compiled together. The main output of a
+         `kotlin_library()` rule is a single JAR file containing all
+        of the compiled class files, as well as the static files specified in
+        the `resources` argument.
+    """,
+    examples = """
+        ```
+        # A rule that compiles a single .kt file.
+        kotlin_library(
+          name = 'JsonUtil',
+          srcs = ['JsonUtil.kt'],
+          deps = [
+            '//third_party/guava:guava',
+            '//third_party/jackson:jackson',
+          ],
+        )
+
+        # A rule that compiles all of the .kt files under the directory in
+        # which the rule is defined using glob(). It also excludes an
+        # individual file that may have additional dependencies, so it is
+        # compiled by a separate rule.
+        kotlin_library(
+          name = 'messenger',
+          srcs = glob(['**/*.kt'], excludes = ['MessengerModule.kt']),
+          deps = [
+            '//src/com/facebook/base:base',
+            '//third_party/guava:guava',
+          ],
+        )
+
+        kotlin_library(
+          name = 'MessengerModule',
+          srcs = ['MessengerModule.kt'],
+          deps = [
+            '//src/com/facebook/base:base',
+            '//src/com/google/inject:inject',
+            '//third_party/guava:guava',
+            '//third_party/jsr-330:jsr-330',
+          ],
+        )
+
+        # A rule that builds a library with both relative and
+        # fully-qualified deps.
+        kotlin_library(
+          name = 'testutil',
+          srcs = glob(['tests/**/*.kt'], excludes = 'tests/**/*Test.kt'),
+          deps = [
+            ':lib-fb4a',
+            '//java/com/facebook/base:base',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "srcs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                The set of `.kt`, `.java` or `.kts` files to compile for this rule.
+                 If any of the files in this list end in `.src.zip`,
+                 then the entries in the ZIP file that end in `.java` or `.kt` will be
+                 included as ordinary inputs to compilation.
+            """,
+            ),
+        }
+        | jvm_common.resources_arg()
+        | {
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Rules (usually other `kotlin_library` rules) that are used to
+                 generate the classpath required to compile this `kotlin_library`.
+            """,
+            ),
+            "extra_kotlinc_arguments": attrs.list(
+                attrs.arg(anon_target_compatible = True),
+                default = [],
+                doc = """
+                List of additional arguments to pass into the Kotlin compiler.
+            """,
+            ),
+            "friend_paths": jvm_common.friend_paths_attr(),
+        }
+        | jvm_common.annotation_processors()
+        | jvm_common.remove_classes_arg()
+        | jvm_common.exported_deps()
+        | jvm_common.provided_deps()
+        | jvm_common.exported_provided_deps()
+        | jvm_common.k2()
+        | jvm_common.kotlin_compiler_plugins()
+        | jvm_common.incremental()
+        | jvm_common.kotlincd_content_based_paths()
+        | jvm_common.plugins()
+        | jvm_common.javac()
+        | jvm_common.enable_used_classes()
+        | jvm_common.classic_java_content_based_paths()
+        | buck.labels_arg()
+        | jvm_common.abi_generation_mode()
+        | {
+            "extra_arguments": attrs.list(attrs.string(), default = []),
+            "jar_postprocessor": attrs.option(attrs.exec_dep(), default = None),
+            "java_version": attrs.option(attrs.string(), default = None),
+            "jdk_release": attrs.option(attrs.string(), default = None),
+            "keep_synthetics_in_class_abi": attrs.option(attrs.bool(), default = None),
+            "manifest_file": attrs.option(attrs.source(), default = None),
+            "maven_coords": attrs.option(attrs.string(), default = None),
+            "no_x_jdk_release": attrs.bool(default = False, doc = _no_x_jdk_release_doc),
+            "proguard_config": attrs.option(attrs.source(), default = None),
+            "required_for_source_only_abi": attrs.bool(default = False),
+            "resources_root": attrs.option(attrs.string(), default = None),
+            "runtime_deps": attrs.list(attrs.dep(), default = []),
+            "source": attrs.option(attrs.string(), default = None),
+            "source_only_abi_deps": attrs.list(attrs.dep(), default = []),
+            "target": attrs.option(attrs.string(), default = None),
+            VALIDATION_DEPS_ATTR_NAME: attrs.set(attrs.dep(), sorted = True, default = []),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_dex_min_sdk_version": attrs.option(attrs.int(), default = dex_min_sdk_version()),
+            "_dex_toolchain": toolchains_common.dex(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_is_building_android_binary": is_building_android_binary_attr(),
+            "_java_toolchain": toolchains_common.java(),
+            "_kotlin_toolchain": toolchains_common.kotlin(),
+        }
+        | buck.licenses_arg()
+        | buck.contacts_arg()
+        | jvm_common.plugins()
+        | validation_common.attrs_validators_arg()
+    ),
+)
+
+kotlin_test = prelude_rule(
+    name = "kotlin_test",
+    docs = """
+        A `kotlin_test()` rule is used to define a set of
+         `.kt` files that contain tests to run via JUnit.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.inject_test_env_arg()
+        | {
+            "resources": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Same as `kotlin_library()`.
+            """,
+            ),
+            "srcs": attrs.list(
+                attrs.source(),
+                default = [],
+                doc = """
+                Like ``kotlin_library()``,
+                 all of the `.kt` files specified by the
+                 `srcs` argument will be compiled when this rule is
+                 built. In addition, all of the corresponding `.class` files that are built by this rule will be passed as arguments to
+                 JUnit when this rule is run as a test. `.class` files
+                 that are passed to JUnit that do not have any methods annotated with
+                 `@Test` are considered failed tests, so make sure that
+                 only test case classes are specified as `srcs`. This is
+                 frequently done by specifying `srcs` as
+                 `glob(['**/*Test.kt'])`.
+            """,
+            ),
+        }
+        | buck.test_label_arg()
+        | {
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Same as `kotlin_library()`.
+                 // org.junit.rules.Timeout was not introduced until 4.7.
+                 Must include JUnit (version 4.7 or later) as a dependency for JUnit tests.
+                 Must include TestNG (version 6.2 or later) and hamcrest as a dependencies for TestNG tests.
+            """,
+            ),
+            "test_type": attrs.option(
+                attrs.enum(TestType),
+                default = None,
+                doc = """
+                Specifies which test framework to use.
+                 The currently supported options are 'junit' and 'testng'.
+            """,
+            ),
+        }
+        | buck.run_test_separately_arg(run_test_separately_type = attrs.bool(default = False))
+        | re_test_common.test_args()
+        | buck.test_rule_timeout_ms()
+        | {
+            "vm_args": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                Runtime arguments to the JVM running the tests.
+            """,
+            ),
+        }
+        | jvm_common.annotation_processors()
+        | jvm_common.enable_used_classes()
+        | jvm_common.incremental()
+        | jvm_common.classic_java_content_based_paths()
+        | jvm_common.kotlincd_content_based_paths()
+        | jvm_common.javac()
+        | jvm_common.k2()
+        | jvm_common.kotlin_compiler_plugins()
+        | jvm_common.plugins()
+        | jvm_common.test_env()
+        | jvm_common.abi_generation_mode()
+        | {
+            "cxx_library_allowlist": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                List of cxx_library targets to build, if use_cxx_libraries is true.
+                This can be useful if some dependencies are Android-only and won't build for the test host platform.
+            """,
+            ),
+            "deps_query": attrs.option(attrs.query(), default = None),
+            "discover_all_test_classes": attrs.bool(default = False),
+            "exported_deps": attrs.list(attrs.dep(), default = []),
+            "exported_provided_deps": attrs.list(attrs.dep(), default = []),
+            "extra_arguments": attrs.list(attrs.string(), default = []),
+            "extra_kotlinc_arguments": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "friend_paths": jvm_common.friend_paths_attr(),
+            "java": attrs.option(attrs.dep(), default = None),
+            "java_agents": attrs.list(attrs.source(), default = []),
+            "java_version": attrs.option(attrs.string(), default = None),
+            "jdk_release": attrs.option(attrs.string(), default = None),
+            "manifest_file": attrs.option(attrs.source(), default = None),
+            "maven_coords": attrs.option(attrs.string(), default = None),
+            "no_x_jdk_release": attrs.bool(default = False, doc = _no_x_jdk_release_doc),
+            "proguard_config": attrs.option(attrs.source(), default = None),
+            "provided_deps": attrs.list(attrs.dep(), default = []),
+            "remove_classes": attrs.list(attrs.regex(), default = []),
+            "required_for_source_only_abi": attrs.bool(default = False),
+            "resources_root": attrs.option(attrs.string(), default = None),
+            "runtime_deps": attrs.list(attrs.dep(), default = []),
+            "source": attrs.option(attrs.string(), default = None),
+            "source_only_abi_deps": attrs.list(attrs.dep(), default = []),
+            "supports_test_execution_caching": attrs.bool(default = False),
+            "target": attrs.option(attrs.string(), default = None),
+            "test_case_timeout_ms": attrs.option(attrs.int(), default = None),
+            "test_class_names_file": attrs.option(attrs.source(), default = None),
+            "test_info_type": attrs.option(attrs.string(), default = None),
+            "unbundled_resources_root": attrs.option(attrs.source(allow_directory = True), default = None),
+            "use_cxx_libraries": attrs.option(attrs.bool(), default = None),
+            "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_is_building_android_binary": attrs.default_only(attrs.bool(default = False)),
+            "_java_test_toolchain": toolchains_common.java_test(),
+            "_java_toolchain": toolchains_common.java(),
+            "_kotlin_toolchain": toolchains_common.kotlin(),
+        }
+        | buck.licenses_arg()
+        | buck.contacts_arg()
+        | test_common.attributes()
+    ),
+)
+
+kotlin_rules = struct(
+    kotlin_library = kotlin_library,
+    kotlin_test = kotlin_test,
+)
diff --git a/buck2/prelude/decls/lua_common.bzl b/buck2/prelude/decls/lua_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/lua_common.bzl
@@ -0,0 +1,42 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+def _srcs_arg():
+    return {
+        "srcs": attrs.named_set(
+            attrs.source(),
+            sorted = True,
+            default = [],
+            doc = """
+    The set of `.lua` files included in this library.
+""",
+        ),
+    }
+
+def _base_module_arg():
+    return {
+        "base_module": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    The package for which the given specified sources and resources should reside in their final
+     location in the top-level binary. If unset, the project relative directory that houses the
+     BUCK file is used.
+""",
+        ),
+    }
+
+lua_common = struct(
+    srcs_arg = _srcs_arg,
+    base_module_arg = _base_module_arg,
+)
diff --git a/buck2/prelude/decls/lua_rules.bzl b/buck2/prelude/decls/lua_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/lua_rules.bzl
@@ -0,0 +1,195 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load(":common.bzl", "CxxRuntimeType", "CxxSourceType", "HeadersAsRawHeadersMode", "buck", "prelude_rule")
+load(":cxx_common.bzl", "cxx_common")
+load(":lua_common.bzl", "lua_common")
+
+LuaPlatformPackageStyle = ["standalone", "inplace"]
+
+cxx_lua_extension = prelude_rule(
+    name = "cxx_lua_extension",
+    docs = """
+        A cxx\\_lua\\_extension() rule is a variant of a C/C++ library which is built as a Lua module. As such,
+        it has a module name formed by the `base_module` parameter and the rule name and implicitly
+        depends on Lua C library (configured via the `.buckconfig`
+        parameter.
+    """,
+    examples = """
+        ```
+        # A rule that builds a Lua extension from a single .cpp file.
+        cxx_lua_extension(
+          name = 'mymodule',
+          base_module = 'foo.bar',
+          srcs = [
+            'mymodule.cpp',
+          ],
+          compiler_flags = [
+            '-fno-omit-frame-pointer',
+          ],
+        )
+
+        # A library rule which has a single source importing the above extension.
+        lua_library(
+          name = 'utils',
+          srcs = [
+            'utils.lua',
+          ],
+          deps = [
+            ':mymodule',
+          ],
+        )
+        ```
+
+        ```
+        -- The `utils.lua` source, wrapped by the `utils` rule above.
+
+        -- Import the C/C++ extension build above.
+        require "foo.bar.mymodule"
+
+        ...
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        lua_common.base_module_arg()
+        | cxx_common.srcs_arg()
+        | cxx_common.headers_arg()
+        | cxx_common.header_namespace_arg()
+        | cxx_common.preprocessor_flags_arg()
+        | cxx_common.compiler_flags_arg()
+        | cxx_common.linker_flags_arg()
+        | {
+            "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),
+            "default_platform": attrs.option(attrs.string(), default = None),
+            "defaults": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "executable_name": attrs.option(attrs.string(), default = None),
+            "frameworks": attrs.list(attrs.string(), default = []),
+            "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),
+            "include_directories": attrs.set(attrs.string(), sorted = True, default = []),
+            "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "libraries": attrs.list(attrs.string(), default = []),
+            "linker_extra_outputs": attrs.list(attrs.string(), default = []),
+            "post_linker_flags": attrs.list(attrs.arg(), default = []),
+            "precompiled_header": attrs.option(attrs.source(), default = None),
+            "prefix_header": attrs.option(attrs.source(), default = None),
+            "raw_headers": attrs.set(attrs.source(), sorted = True, default = []),
+            "version_universe": attrs.option(attrs.string(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+lua_binary = prelude_rule(
+    name = "lua_binary",
+    docs = """
+        A `lua_binary()` rule is used to build an executable that uses Lua
+        sources from all transitive `lua_library()` dependencies.
+    """,
+    examples = """
+        ```
+        lua_binary(
+          name = 'tailer',
+          main_module = 'tailer',
+          deps = [
+            ':tailerutils',
+          ],
+        )
+
+        lua_library(
+          name = 'tailerutils',
+          srcs = glob(['*.lua']),
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "main_module": attrs.string(
+                default = "",
+                doc = """
+                The module which serves as the entry point for this rule.
+            """,
+            ),
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                `lua_library()` rules to this binary will access.
+            """,
+            ),
+            "native_starter_library": attrs.option(attrs.dep(), default = None),
+            "package_style": attrs.option(attrs.enum(LuaPlatformPackageStyle), default = None),
+            "platform": attrs.option(attrs.string(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+lua_library = prelude_rule(
+    name = "lua_library",
+    docs = """
+        A `lua_library()` rule is used to group together Lua sources
+        to be packaged into a top-level `lua_binary()` rule.
+    """,
+    examples = """
+        ```
+        # A rule that includes a single .py file.
+        lua_library(
+          name = 'fileutil',
+          srcs = ['fileutil.lua'],
+        )
+
+        # A rule that uses glob() to include all sources in the directory which the
+        # rule is defined.  It also lists a resource file that gets packaged with
+        # the sources in this rule.
+        lua_library(
+          name = 'testutil',
+          srcs = glob(['testutil/**/*.lua'],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        lua_common.srcs_arg()
+        | lua_common.base_module_arg()
+        | {
+            "deps": attrs.list(
+                attrs.dep(),
+                default = [],
+                doc = """
+                Other `lua_library()` rules which list `srcs` from
+                 which this rule imports modules.
+            """,
+            ),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+lua_rules = struct(
+    cxx_lua_extension = cxx_lua_extension,
+    lua_binary = lua_binary,
+    lua_library = lua_library,
+)
diff --git a/buck2/prelude/decls/native_common.bzl b/buck2/prelude/decls/native_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/native_common.bzl
@@ -0,0 +1,95 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//cxx:transformation_spec.bzl", "TransformationResultProvider")
+load(":common.bzl", "LinkableDepType")
+
+def _link_style():
+    return {
+        "link_style": attrs.option(
+            attrs.enum(LinkableDepType),
+            default = None,
+            doc = """
+    Determines whether to build and link this rule's dependencies statically or dynamically. Can be
+     either `static`, `static_pic` or `shared`.
+""",
+        ),
+    }
+
+def _link_whole(link_whole_type):
+    return {
+        "link_whole": link_whole_type,
+    }
+
+def _preferred_linkage(preferred_linkage_type):
+    return {
+        "preferred_linkage": preferred_linkage_type,
+    }
+
+def _link_group_deps():
+    return {
+        "link_group_deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    Additional targets to traverse when building link groups, but which should not
+     be direct dependencies of the main executable.
+""",
+        ),
+    }
+
+def _link_group_public_deps_label():
+    return {
+        "link_group_public_deps_label": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    Surface nodes with this label as "public" nodes in the main executable when
+     linking with with link groups.
+""",
+        ),
+    }
+
+def _soname():
+    return {
+        "soname": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    Sets the soname ("shared object name") of any shared library produced from this rule.
+     The default value is based on the full rule name.
+     The macro `$(ext)` will be replaced with a platform-appropriate extension.
+     An argument can be provided, which is a library version.
+     For example `soname = 'libfoo.$(ext 2.3)'` will be `libfoo.2.3.dylib` on Mac and `libfoo.so.2.3` on Linux.
+""",
+        ),
+    }
+
+def _transformation_spec_arg():
+    return {
+        "transformation_spec": attrs.option(
+            attrs.dep(providers = [TransformationResultProvider]),
+            default = None,
+            doc = "Dependency to a transformation spec that will selectively change parts of dependency graph",
+        ),
+    }
+
+native_common = struct(
+    link_group_deps = _link_group_deps,
+    link_group_public_deps_label = _link_group_public_deps_label,
+    link_style = _link_style,
+    link_whole = _link_whole,
+    preferred_linkage = _preferred_linkage,
+    soname = _soname,
+    transformation_spec_arg = _transformation_spec_arg,
+)
diff --git a/buck2/prelude/decls/ocaml_common.bzl b/buck2/prelude/decls/ocaml_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/ocaml_common.bzl
@@ -0,0 +1,54 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+def _deps_arg():
+    return {
+        "deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    The set of dependencies of this rule. It could include references to ocaml\\_library and cxx\\_library rules.
+""",
+        ),
+    }
+
+def _srcs_arg():
+    return {
+        "srcs": attrs.option(
+            attrs.named_set(attrs.source(), sorted = False),
+            default = None,
+            doc = """
+    The set of source files to be compiled by this rule. It supports \\*.ml, \\*.mli, \\*.mly, \\*.mll, and \\*.c files.
+     (see  [this test](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/features/ocaml/testdata/ocaml/clib/BUCK.fixture)  as C interop example and
+      [this test](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/features/ocaml/testdata/ocaml/calc/BUCK.fixture)  as parser and lexer example).
+""",
+        ),
+    }
+
+def _compiler_flags_arg():
+    return {
+        "compiler_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    The set of additional compiler flags to pass to ocaml compiler. It supports
+     specifying ppx (see [for example](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/features/ocaml/testdata/compiler_flag_macros/BUCK.fixture)).
+""",
+        ),
+    }
+
+ocaml_common = struct(
+    deps_arg = _deps_arg,
+    srcs_arg = _srcs_arg,
+    compiler_flags_arg = _compiler_flags_arg,
+)
diff --git a/buck2/prelude/decls/ocaml_rules.bzl b/buck2/prelude/decls/ocaml_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/ocaml_rules.bzl
@@ -0,0 +1,163 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load(":common.bzl", "buck", "prelude_rule")
+load(":ocaml_common.bzl", "ocaml_common")
+
+ocaml_binary = prelude_rule(
+    name = "ocaml_binary",
+    docs = """
+        A ocaml\\_binary() rule builds both native and bytecode executables from the supplied set of OCaml and C source files
+         and dependencies.
+
+         Note: Buck is currently tested with 4.X OCaml series.
+    """,
+    examples = """
+        For more examples, check out our [integration tests](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/features/ocaml/testdata/).
+
+        ```
+        ocaml_binary(
+          name='greet',
+          srcs=[
+            'main.ml',
+            'lex.mll',
+            'parser.mly',
+            'hashtable.c',
+          ],
+          deps=[
+            ':greeting',
+            ':bridge',
+          ],
+        )
+
+        ocaml_library(
+          name='greeting',
+          srcs=[
+            'greeting.ml',
+          ],
+          deps=[
+            ':join',
+          ],
+        )
+
+        ocaml_library(
+          name='join',
+          srcs=[
+            'join.ml',
+          ],
+        )
+
+        cxx_library(
+          name='bridge',
+          srcs=[
+            'bridge.c',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        ocaml_common.srcs_arg()
+        | ocaml_common.deps_arg()
+        | ocaml_common.compiler_flags_arg()
+        | {
+            "bytecode_only": attrs.option(attrs.bool(), default = None),
+            "linker_flags": attrs.list(attrs.string(), default = []),
+            "ocamldep_flags": attrs.list(attrs.arg(), default = []),
+            "platform": attrs.option(attrs.string(), default = None),
+            "warnings_flags": attrs.option(attrs.string(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+ocaml_library = prelude_rule(
+    name = "ocaml_library",
+    docs = """
+        A ocaml\\_library() rule builds a native and a bytecode libraries from the
+         supplied set of OCaml source files and dependencies.
+
+         Note: Buck is currently tested with 4.X OCaml series.
+    """,
+    examples = """
+        For more examples, check out our [integration tests](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/features/ocaml/testdata/).
+
+        ```
+        ocaml_library(
+          name='greeting',
+          srcs=[
+            'greeting.ml',
+          ],
+          deps=[
+            ':join',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        ocaml_common.srcs_arg()
+        | ocaml_common.deps_arg()
+        | ocaml_common.compiler_flags_arg()
+        | {
+            "bytecode_only": attrs.bool(default = False),
+            "linker_flags": attrs.list(attrs.arg(), default = []),
+            "native_plugin": attrs.bool(default = False),
+            "ocamldep_flags": attrs.list(attrs.arg(), default = []),
+            "warnings_flags": attrs.option(attrs.string(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+prebuilt_ocaml_library = prelude_rule(
+    name = "prebuilt_ocaml_library",
+    docs = """
+        A `prebuilt_ocaml_library()` rule wraps a precompiled OCaml library
+        (bytecode and/or native) along with any companion C libraries so it
+        can be consumed as a dependency by `ocaml_binary()` and
+        `ocaml_library()` rules.
+    """,
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "bytecode_c_libs": attrs.list(attrs.string(), default = []),
+            "bytecode_lib": attrs.option(attrs.string(), default = None),
+            "bytecode_only": attrs.bool(default = False),
+            "c_libs": attrs.list(attrs.string(), default = []),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "include_dir": attrs.string(default = ""),
+            "lib_dir": attrs.string(default = ""),
+            "lib_name": attrs.string(default = ""),
+            "native_c_libs": attrs.list(attrs.string(), default = []),
+            "native_lib": attrs.option(attrs.string(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+ocaml_rules = struct(
+    ocaml_binary = ocaml_binary,
+    ocaml_library = ocaml_library,
+    prebuilt_ocaml_library = prebuilt_ocaml_library,
+)
diff --git a/buck2/prelude/decls/python_common.bzl b/buck2/prelude/decls/python_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/python_common.bzl
@@ -0,0 +1,174 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+PythonBuckConfigPackageStyle = ["standalone", "inplace", "outplace"]
+
+def _srcs_arg():
+    return {
+        "srcs": attrs.named_set(
+            attrs.source(),
+            sorted = True,
+            default = [],
+            doc = """
+    The set of Python (`.py`) files to include in this library.
+""",
+        ),
+    }
+
+def _resources_arg():
+    return {
+        "resources": attrs.named_set(
+            attrs.source(),
+            sorted = True,
+            default = [],
+            doc = """
+    Static files to be packaged along with the Python sources.
+     These resources can be accessed at runtime using
+     the [importlib.resources](https://docs.python.org/3/library/importlib.resources.html) module
+     from the Python standard library.
+""",
+        ),
+    }
+
+def _base_module_arg():
+    return {
+        "base_module": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    The package in which the specified source files and resources should reside in their final
+     location in the top-level binary. If unset, Buck uses the project-relative directory
+     that contains the BUCK file.
+""",
+        ),
+    }
+
+def _linker_flags_arg():
+    return {
+        "linker_flags": attrs.list(
+            attrs.arg(anon_target_compatible = True),
+            default = [],
+            doc = """
+    Additional linker flags that should be applied to any linking which is specific to this rule.
+     Note that whether these flags are used is dependent on the native link strategy selected in
+     `.buckconfig` and currently applies only to the merged `.buckconfig`;
+     the `separate` link strategy pulls in shared libraries that are linked in the
+     context of the rules that own them, such as `cxx_library()`.
+""",
+        ),
+    }
+
+def _package_style_arg():
+    return {
+        "package_style": attrs.option(
+            attrs.enum(PythonBuckConfigPackageStyle),
+            default = None,
+            doc = """
+    Used to override the global packaging style that is set in `[`.buckconfig`
+    ]`.
+""",
+        ),
+    }
+
+def _preload_deps_arg():
+    return {
+        "preload_deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+    A list of C/C++ library dependencies that need to be loaded before any
+     other libraries when the PEX starts up. This requires dynamic loader support,
+     such as `LD_PRELOAD`, found on most systems. This list is order-
+     sensitive and the preload libraries listed here are passed down to the dynamic
+     linker in the same order.
+""",
+        ),
+    }
+
+def _exclude_deps_from_merged_linking_arg():
+    return {
+        "exclude_deps_from_merged_linking": attrs.bool(
+            default = False,
+            doc = """
+    When linking the top-level binary with a `merged` ``.buckconfig``,
+     do not merge or re-link any native transitive deps of this library. This is useful if
+     this library wraps prebuilt native extensions which cannot be re-linked as part of
+     library merging.
+""",
+        ),
+    }
+
+def _deduplicate_merged_link_roots():
+    return {
+        "deduplicate_merged_link_roots": attrs.bool(
+            default = True,
+            doc = """
+    When linking multiple top-level binaries with the `merged` ``.buckconfig``,
+     coalesce root link rules which are identical across independent merged links.
+""",
+        ),
+    }
+
+def _version_selections_arg():
+    return {
+        "version_selections": attrs.dict(
+            key = attrs.string(),
+            value = attrs.string(),
+            default = {},
+            doc = """A mapping from library name to desired version. Versioned dependencies from the entire dependency tree with the given name will be used at the specified version, if available.
+            Versioned libraries that are unspecified will be used at their respective default version.""",
+        ),
+    }
+
+def _executable_deps_arg():
+    return {
+        "executable_deps": attrs.list(attrs.dep(), default = []),
+    }
+
+def _deps_arg():
+    return {
+        "deps": attrs.list(
+            attrs.dep(),
+            default = [],
+            doc = """
+            A list of `python_library()` rules that specify Python
+                modules to include in the binary — including all transitive
+                dependencies of these rules.
+        """,
+        ),
+    }
+
+def _internal_tools_arg():
+    return attrs.default_only(
+        attrs.toolchain_dep(
+            default = "prelude//python/tools:python_internal_tools",
+            doc = """
+        Internal implementation details of the Python rules.
+    """,
+        )
+    )
+
+python_common = struct(
+    srcs_arg = _srcs_arg,
+    resources_arg = _resources_arg,
+    base_module_arg = _base_module_arg,
+    linker_flags_arg = _linker_flags_arg,
+    package_style_arg = _package_style_arg,
+    preload_deps_arg = _preload_deps_arg,
+    exclude_deps_from_merged_linking_arg = _exclude_deps_from_merged_linking_arg,
+    deduplicate_merged_link_roots = _deduplicate_merged_link_roots,
+    version_selections_arg = _version_selections_arg,
+    executable_deps_arg = _executable_deps_arg,
+    deps_arg = _deps_arg,
+    internal_tools_arg = _internal_tools_arg,
+)
diff --git a/buck2/prelude/decls/python_rules.bzl b/buck2/prelude/decls/python_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/python_rules.bzl
@@ -0,0 +1,792 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:attrs_validators.bzl", "validation_common")
+load("@prelude//cxx:cuda.bzl", "CudaCompileStyle")
+load("@prelude//cxx:headers.bzl", "CPrecompiledHeaderInfo")
+load("@prelude//cxx:link_groups_types.bzl", "LINK_GROUP_MAP_ATTR")
+load("@prelude//decls:cxx_rules.bzl", "BUILD_INFO_ATTR", "cxx_rules")
+load("@prelude//decls:re_test_common.bzl", "re_test_common")
+load("@prelude//decls:test_common.bzl", "test_common")
+load("@prelude//decls:third_party_common.bzl", "third_party_common")
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//linking:link_info.bzl", "LinkOrdering")
+load("@prelude//python:python.bzl", "PythonLibraryInfo")
+load("@prelude//python:python_runtime_bundle.bzl", "PythonRuntimeBundleInfo")
+load("@prelude//python:toolchain.bzl", "NativeLinkStrategy")
+load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")
+load(":common.bzl", "CxxRuntimeType", "CxxSourceType", "HeadersAsRawHeadersMode", "LinkableDepType", "buck", "prelude_rule")
+load(":cxx_common.bzl", "cxx_common")
+load(":native_common.bzl", "native_common")
+load(":python_common.bzl", "python_common")
+
+StripLibparStrategy = ["full", "extract", "none"]
+
+def _create_manifest_for_source_dir():
+    return attrs.exec_dep(default = "prelude//python/tools:create_manifest_for_source_dir")
+
+# Attrs common between python binary/test
+def _python_executable_attrs():
+    python_executable_attrs = {}
+
+    python_executable_attrs.update(constraint_overrides.attributes)
+
+    # allow non-default value for the args below
+    python_executable_attrs.update(
+        {
+            "anonymous_link_groups": attrs.bool(default = False),
+            "binary_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "bolt_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "bolt_profile": attrs.option(attrs.source(), default = None),
+            "compiler_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "cxx_main": attrs.source(default = "prelude//python/tools:embedded_main.cpp"),
+            "enable_distributed_thinlto": attrs.bool(default = False),
+            "exe_allow_cache_upload": attrs.bool(
+                default = False,
+                doc = """
+            Allow uploading native executable for caching. Only meaningful for native link strategy.
+        """,
+            ),
+            "executable_name": attrs.option(attrs.string(), default = None),
+            "inplace_build_args": attrs.list(attrs.arg(), default = []),
+            "interpreter_args": attrs.list(attrs.string(), default = []),
+            "lazy_imports_analyzer": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "link_group": attrs.option(attrs.string(), default = None),
+            "link_group_map": LINK_GROUP_MAP_ATTR,
+            "link_group_min_binary_node_count": attrs.option(attrs.int(), default = None),
+            "link_style": attrs.enum(LinkableDepType, default = "static"),
+            "main_function": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+            Name of a Python function that will serve as the main entry point of
+            the binary. The name is either a fully qualified name like
+            `foo.bar.baz` or it starts with a `.` like `.bar.baz`, in which case
+            it is relative to the package containing the target. This should
+            usually be a function defined within one of the dependencies of this
+            target. This attribute should be preferred over `main_module` or
+            `main`, and it is an error to specify more than one of these.
+        """,
+            ),
+            "make_py_package": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "manifest_module_entries": attrs.option(
+                attrs.dict(
+                    key = attrs.string(),
+                    value = attrs.one_of(
+                        attrs.dict(key = attrs.string(), value = attrs.option(attrs.any())),
+                        attrs.list(attrs.string()),
+                    ),
+                ),
+                default = None,
+                doc = """If present, it should be a `string` -> `entry` mapping that
+            gets generated into a `__manifest__` module in the executable. Top
+            level string keys will be the names of variables in this module (so
+            they must be valid Python identifiers). An `entry` can be a list of
+            `string`s, or a further `string`-keyed dictionary.""",
+            ),
+            "native_link_strategy": attrs.option(attrs.enum(NativeLinkStrategy.values()), default = None),
+            "opt_by_default_enabled": attrs.bool(default = False),
+            "optimize_for_action_throughput": attrs.bool(default = False),
+            "package_split_dwarf_dwp": attrs.bool(default = False),
+            "par_style": attrs.option(attrs.string(), default = None),
+            "resources": attrs.named_set(attrs.one_of(attrs.dep(), attrs.source(allow_directory = True)), sorted = True, default = []),
+            "run_with_inplace": attrs.bool(default = False),
+            "runtime_bundle": attrs.option(attrs.dep(providers = [PythonRuntimeBundleInfo]), default = None),
+            "runtime_bundle_full": attrs.bool(default = False),
+            "runtime_env": attrs.option(attrs.dict(key = attrs.string(), value = attrs.string()), default = None),
+            "runtime_libs": attrs.dict(
+                key = attrs.string(),
+                value = attrs.dep(),
+                default = {},
+                doc = """
+                A dictionary mapping destination filenames to dependencies whose
+                default outputs will be installed into the runtime/lib directory
+                of the PAR file. Only relevant for native python.
+            """,
+            ),
+            "standalone_build_args": attrs.list(attrs.arg(), default = []),
+            "static_extension_finder": attrs.source(default = "prelude//python/tools:static_extension_finder.py"),
+            "static_extension_utils": attrs.source(default = "prelude//python/tools:static_extension_utils.cpp"),
+            "strip_libpar": attrs.enum(StripLibparStrategy, default = "none"),
+            "strip_stapsdt": attrs.bool(default = False),
+            "use_anon_target_for_analysis": attrs.bool(
+                default = False
+            ),  # TODO(dcssiva) Delete this when we change the default analysis method to use anon targets
+            "use_lifeguard_incremental": attrs.bool(default = False),
+            "use_oss_python": attrs.bool(default = False),
+            "use_rust_make_par": attrs.bool(default = False),  # TODO(rishiarora) Delete this when we change the default build style
+            "use_rust_make_par_optimizations": attrs.bool(default = False),
+            "_build_info": BUILD_INFO_ATTR,
+            "_create_manifest_for_source_dir": _create_manifest_for_source_dir(),
+            "_cxx_hacks": attrs.default_only(attrs.dep(default = "prelude//cxx/tools:cxx_hacks")),
+            "_cxx_toolchain": toolchains_common.cxx(),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_gen_build_info": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "_generated_build_info_enabled": attrs.bool(default = False),
+            "_generated_build_info_mode": attrs.enum(["full", "stable"], default = "stable"),
+            "_generated_build_info_spec": BUILD_INFO_ATTR,
+            "_late_build_info_stamping": attrs.any(default = None),
+            "_python_internal_tools": python_common.internal_tools_arg(),
+            "_python_toolchain": toolchains_common.python(),
+            "_target_os_type": buck.target_os_type_arg(),
+        }
+    )
+
+    return python_executable_attrs
+
+def _python_test_attrs():
+    test_attrs = _python_executable_attrs()
+    test_attrs["_test_main"] = attrs.source(default = "prelude//python/tools:__test_main__.py")
+    test_attrs["implicit_test_library"] = attrs.option(attrs.dep(providers = [PythonLibraryInfo]), default = None)
+    test_attrs["safer_lazy_imports"] = attrs.bool(default = False)  # TODO(T240038931) When enabling lazy imports by default, remove this line
+    test_attrs["supports_test_execution_caching"] = attrs.bool(default = False)
+    test_attrs.update(re_test_common.test_args())
+    return test_attrs
+
+def _package_python_binary_remotely():
+    return select({
+        "DEFAULT": False,
+        "config//os/constraints:android": True,
+    })
+
+def _python_binary_attrs():
+    binary_attrs = _python_executable_attrs()
+    binary_attrs.update({
+        "link_style": attrs.enum(LinkableDepType, default = "static"),
+        "_package_remotely": attrs.bool(default = _package_python_binary_remotely()),
+        "_python_internal_tools": python_common.internal_tools_arg(),
+        "_python_toolchain": toolchains_common.python(),
+    })
+    return binary_attrs
+
+def _typing_arg():
+    return {
+        "py_version_for_type_checking": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    This option will force the type checker to perform checking under a specific version of Python interpreter.
+""",
+        ),
+        "shard_typing": attrs.option(
+            attrs.bool(),
+            default = None,
+            doc = """
+    Determines if sharding should be enabled on a given target.
+""",
+        ),
+        # NOTE(grievejia): Setting default to True here may have non-trivial impact on build memory
+        # usage (see S395002)
+        "typing": attrs.bool(
+            default = False,
+            doc = """
+    Determines whether to perform type checking on the given target. Default is False.
+""",
+        ),
+        "typing_validation": attrs.bool(
+            default = False,
+            doc = """
+    When True (and typing is also True), Pyre type checking runs as a build
+    validation during normal buck build, failing the build on type errors.
+""",
+        ),
+    }
+
+cxx_python_extension = prelude_rule(
+    name = "cxx_python_extension",
+    docs = """
+        A `cxx_python_extension()` rule is a variant of a C/C++ library which is built as a Python module. As such,
+        it has a module name formed by the `base_module` parameter and the rule name.
+    """,
+    examples = """
+        ```
+        # A rule that builds a Python extension from a single .cpp file.
+        cxx_python_extension(
+          name = 'mymodule',
+          base_module = 'foo.bar',
+          srcs = [
+            'mymodule.cpp',
+          ],
+        )
+
+        # A library rule which has a single source importing the above extension.
+        python_library(
+          name = 'utils',
+          srcs = [
+            'utils.py',
+          ],
+          deps = [
+            ':mymodule',
+          ],
+        )
+        ```
+
+        ```
+        ## The `utils.py` source, wrapped by the `utils` rule above.
+
+        ## Import the C/C++ extension build above.
+        from foo.bar import mymodule
+
+        ...
+        ```
+    """,
+    further = None,
+    attrs = (
+        # cxx_python_extension is a subset of cxx_library, plus a base_module.
+        # So we can reuse cxx_library, we augment it with the additional attributes it defines.
+        # This isn't the ideal way to reuse it (we'd rather cxx_library was split it multiple reusable parts),
+        # but it's the pragmatic way of getting it working for now.
+        # @unsorted-dict-items
+        {k: attrs.default_only(v) for k, v in cxx_rules.cxx_library.attrs.items()}
+        | buck.labels_arg()
+        | python_common.base_module_arg()
+        | cxx_common.srcs_arg()
+        | cxx_common.deps_arg()
+        | cxx_common.headers_arg()
+        | cxx_common.header_namespace_arg()
+        | cxx_common.preprocessor_flags_arg()
+        | cxx_common.compiler_flags_arg()
+        | {
+            "link_style": attrs.option(
+                attrs.enum(LinkableDepType),
+                default = None,
+                doc = """
+                Determines whether to build and link this rule's dependencies statically or dynamically.
+                 Can be either `static`, `static_pic` or `shared`.
+                 Note: since shared libraries re-export its dependencies, depending on multiple shared libraries
+                 which themselves have overlapping static dependencies may cause problems if they init using global state.
+            """,
+            ),
+        }
+        | cxx_common.linker_extra_outputs_arg()
+        | cxx_common.linker_flags_arg()
+        | cxx_common.local_linker_flags_arg()
+        | cxx_common.supports_stripping()
+        | cxx_common.default_deps_arg()
+        | native_common.transformation_spec_arg()
+        | third_party_common.create_third_party_build_root_attrs()
+        | {
+            "cxx_runtime_type": attrs.option(attrs.enum(CxxRuntimeType), default = None),
+            "default_platform": attrs.option(attrs.string(), default = None),
+            "defaults": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),
+            "executable_name": attrs.option(attrs.string(), default = None),
+            "frameworks": attrs.list(attrs.string(), default = []),
+            "headers_as_raw_headers_mode": attrs.option(attrs.enum(HeadersAsRawHeadersMode), default = None),
+            "include_directories": attrs.set(attrs.string(), sorted = True, default = []),
+            "lang_compiler_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "lang_preprocessor_flags": attrs.dict(key = attrs.enum(CxxSourceType), value = attrs.list(attrs.arg()), sorted = False, default = {}),
+            "libraries": attrs.list(attrs.string(), default = []),
+            "module_name": attrs.option(attrs.string(), default = None),
+            "post_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "precompiled_header": attrs.option(attrs.source(), default = None),
+            "prefix_header": attrs.option(attrs.source(), default = None),
+            "raw_headers": attrs.set(attrs.source(), sorted = True, default = []),
+            "type_stub": attrs.option(attrs.source(), default = None),
+        }
+        | {
+            "allow_embedding": attrs.bool(default = True),
+            "allow_suffixing": attrs.bool(default = True),
+            # Copied from cxx_library.
+            "auto_link_groups": attrs.bool(default = False),
+            # These flags will only be used to instrument a target
+            # when coverage for that target is enabled by `exported_needs_coverage_instrumentation`
+            # or by any of the target's dependencies.
+            "coverage_instrumentation_compiler_flags": attrs.list(attrs.string(), default = []),
+            # Optional clang_profile_list target for selective coverage instrumentation via -fprofile-list.
+            "coverage_profile_list": attrs.option(attrs.dep(), default = None),
+            "cuda_compile_style": attrs.enum(CudaCompileStyle.values(), default = "mono"),
+            "exported_needs_coverage_instrumentation": attrs.bool(default = False),
+            "extra_dwp_flags": attrs.list(attrs.string(), default = []),
+            "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),
+            "link_whole": attrs.default_only(attrs.bool(default = True)),
+            "precompiled_header": attrs.option(attrs.dep(providers = [CPrecompiledHeaderInfo]), default = None),
+            "preferred_linkage": attrs.default_only(attrs.string(default = "any")),
+            "separate_debug_info": attrs.bool(default = False),
+            "suffix_all": attrs.bool(default = True),
+            "suffix_exclude_rtti": attrs.bool(default = False),
+            "support_shlib_interfaces": attrs.bool(default = True),
+            "_cxx_hacks": attrs.default_only(attrs.dep(default = "prelude//cxx/tools:cxx_hacks")),
+            "_cxx_toolchain": toolchains_common.cxx(),
+            # Copied from python_library.
+            "_python_internal_tools": python_common.internal_tools_arg(),
+            "_python_toolchain": toolchains_common.python(),
+            "_target_os_type": buck.target_os_type_arg(),
+        }
+        | buck.licenses_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+prebuilt_python_library = prelude_rule(
+    name = "prebuilt_python_library",
+    docs = """
+        A `prebuilt_python_library()` rule is used to include prebuilt python packages into the output of a
+        top-level `python_binary()` or `python_test()` rule.
+
+        These prebuilt libraries can either be [whl files](https://www.python.org/dev/peps/pep-0427/) or eggs
+
+        whls for most packages are available for download from [PyPI](https://pypi.org). The whl used may be
+        downloaded with `remote_file()`. However, Buck does not attempt to infer dependency information from pip,
+        so that information will have to be imparted by the user.
+
+        To create an egg for a package, run `python setup.py bdist_egg` in the package source distribution.
+    """,
+    examples = """
+        ```
+        # A simple prebuilt_python_library with no external dependencies.
+        remote_file(
+          name = "requests-download",
+          url = "https://files.pythonhosted.org/packages/51/bd/23c926cd341ea6b7dd0b2a00aba99ae0f828be89d72b2190f27c11d4b7fb/requests-2.22.0-py2.py3-none-any.whl",
+          sha1 = "e1fc28120002395fe1f2da9aacea4e15a449d9ee",
+          out = "requests-2.22.0-py2.py3-none-any.whl",
+        )
+
+        prebuilt_python_library(
+          name = "requests",
+          binary_src = ":requests-download",
+        )
+
+        # A slightly more complex example
+        prebuilt_python_library(
+          name = "greenlet",
+          binary_src = "greenlet-0.4.7-py2.7-macosx-10.10-x86_64.egg",
+        )
+
+        prebuilt_python_library(
+          name = "gevent",
+          binary_src = "gevent-1.0.2-py2.7-macosx-10.10-x86_64.egg",
+          deps = [
+            ":greenlet",
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.labels_arg()
+        | {
+            "binary_src": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                The path to the `.whl`, `.egg`, or `.tar.gz` archive to extract.
+
+                 Exactly one of `binary_src` and `source_dir` must be set. Note:
+                 `.egg` files have a very particular naming convention that must
+                 be followed, otherwise they will not be found at runtime.
+            """,
+            ),
+            "source_dir": attrs.option(
+                attrs.source(allow_directory = True),
+                default = None,
+                doc = """
+                A directory containing an already-materialized Python package.
+
+                 The directory is manifested in place without being copied or
+                 archived. Exactly one of `binary_src` and `source_dir` must be set.
+            """,
+            ),
+        }
+        | python_common.deps_arg()
+        | python_common.exclude_deps_from_merged_linking_arg()
+        | third_party_common.create_third_party_build_root_attrs()
+        | {
+            "cxx_header_dirs": attrs.option(attrs.list(attrs.string()), default = None),
+            "infer_cxx_header_dirs": attrs.bool(default = False),
+            "lazy_imports_analyzer": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "strip_soabi_tags": attrs.bool(
+                default = False,
+                doc = """
+                    Strip the SOABI tags from extensions in the prebuilt library.
+
+                    Note that this should be considered unsafe, as it removes builtin
+                    protections that fail fast when a potententially incompatible
+                    native extension is imported.
+                """,
+            ),
+            "use_lifeguard_incremental": attrs.bool(default = False),
+            "_create_manifest_for_source_dir": _create_manifest_for_source_dir(),
+            "_extract": attrs.default_only(attrs.exec_dep(default = "prelude//python/tools:extract")),
+            "_python_internal_tools": python_common.internal_tools_arg(),
+            "_python_toolchain": toolchains_common.python(),
+        }
+        | buck.licenses_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+python_binary = prelude_rule(
+    name = "python_binary",
+    docs = """
+        A `python_binary()` rule is used to build an executable Python package
+        that includes Python sources and resources from all transitive
+        dependencies.
+    """,
+    examples = """
+        Build an executable from the Python files in the BUCK directory.
+
+        ```
+        # BUCK
+
+        python_binary(
+          name = 'tailer',
+          main_module = 'tailer',
+          deps = [
+            ':tailerutils',
+          ],
+        )
+
+        python_library(
+          name = 'tailerutils',
+          # The main module, tailer.py, is specified here.
+          # (Separated out from the glob pattern for clarity.)
+          srcs = glob(['tailer.py', '*.py']),
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {k: attrs.default_only(v) for k, v in cxx_rules.cxx_binary.attrs.items()}
+        | buck.labels_arg()
+        | {
+            "base_module": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The package in which the main module should reside in its final
+                 location in the binary. If unset, Buck uses the project-relative directory
+                 that contains the BUCK file.
+            """,
+            ),
+            "main": attrs.option(
+                attrs.source(),
+                default = None,
+                doc = """
+                The Python file which serves as the entry point for the binary.
+                 The interpreter initiates execution of the binary with the code in this file.
+            """,
+            ),
+            "main_module": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The python module that should be the entry point of the binary. This should be
+                 a module name within a `python_library` that this binary depends on. Note that
+                 module names take `base_module` of the library into account.
+                 This property is mutually exclusive with `main`, and should be preferred to `main`, which is deprecated.
+            """,
+            ),
+        }
+        | python_common.deps_arg()
+        | python_common.version_selections_arg()
+        | python_common.preload_deps_arg()
+        | python_common.package_style_arg()
+        | python_common.linker_flags_arg()
+        | python_common.deduplicate_merged_link_roots()
+        | python_common.executable_deps_arg()
+        | native_common.link_group_deps()
+        | native_common.transformation_spec_arg()
+        | native_common.link_group_public_deps_label()
+        | {
+            "build_args": attrs.list(attrs.arg(), default = []),
+            "compile": attrs.option(attrs.bool(), default = None),
+            "dummy_omnibus": attrs.option(attrs.dep(), default = None),
+            "extension": attrs.option(attrs.string(), default = None),
+            "prefer_stripped_native_objects": attrs.bool(default = False),
+            "repl_main": attrs.option(attrs.string(), default = None),
+            "repl_only_deps": attrs.list(attrs.dep(), default = []),
+            "zip_safe": attrs.option(attrs.bool(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.contacts_arg()
+        | buck.allow_cache_upload_arg()
+        | _typing_arg()
+        | _python_binary_attrs()
+        | validation_common.attrs_validators_arg()
+    ),
+    cfg = constraint_overrides.python_transition,
+)
+
+python_library = prelude_rule(
+    name = "python_library",
+    docs = """
+        A `python_library()` rule is used to group together Python
+        source files and resources to be passed together in as a `dep` of other rules.
+    """,
+    examples = """
+        Include Python source files and resource files.
+
+        ```
+        # BUCK
+
+        # A rule that includes a single Python file.
+        python_library(
+          name = 'fileutil',
+          srcs = ['fileutil.py'],
+          deps = [
+            '//third_party/python-magic:python-magic',
+          ],
+        )
+
+        # A rule that uses glob() to include all Python source files in the
+        # directory in which the rule is defined. The rule also specifies a
+        # resource file that gets packaged with the source file.
+        python_library(
+          name = 'testutil',
+          srcs = glob(['testutil/**/*.py']),
+          resources = [
+            'testdata.dat',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.labels_arg()
+        | python_common.srcs_arg()
+        | python_common.resources_arg()
+        | python_common.base_module_arg()
+        | python_common.deps_arg()
+        | python_common.exclude_deps_from_merged_linking_arg()
+        | third_party_common.create_third_party_build_root_attrs()
+        | {
+            "ignore_compile_errors": attrs.bool(default = False),
+            "lazy_imports_analyzer": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+            "resources": attrs.named_set(
+                attrs.one_of(attrs.dep(), attrs.source(allow_directory = True)),
+                sorted = True,
+                default = [],
+                doc = """
+                Static files to be packaged along with the Python sources.
+                 These resources can be accessed at runtime using
+                 the [importlib.resources](https://docs.python.org/3/library/importlib.resources.html) module
+                 from the Python standard library.
+            """,
+            ),
+            "type_stubs": attrs.named_set(attrs.source(), sorted = True, default = []),
+            "use_lifeguard_incremental": attrs.bool(default = False),
+            "versioned_resources": attrs.option(attrs.versioned(attrs.named_set(attrs.source(), sorted = True)), default = None),
+            "versioned_srcs": attrs.option(attrs.versioned(attrs.named_set(attrs.source(), sorted = True)), default = None),
+            "zip_safe": attrs.option(attrs.bool(), default = None),
+            "_create_manifest_for_source_dir": _create_manifest_for_source_dir(),
+            "_cxx_toolchain": toolchains_common.cxx(),
+            "_python_internal_tools": python_common.internal_tools_arg(),
+            "_python_toolchain": toolchains_common.python(),
+        }
+        | buck.licenses_arg()
+        | buck.contacts_arg()
+        | _typing_arg()
+        | validation_common.attrs_validators_arg()
+    ),
+)
+
+python_test = prelude_rule(
+    name = "python_test",
+    docs = """
+        A `python_test()` rule defines a set of `.py` files that contain tests to run via the [Python unit testing framework](https://docs.python.org/library/unittest.html).
+
+         If your test requires static files you should specify these in
+         the **resources** or **platform\\_resources** arguments.
+         If you do not specify these files, they won't be available when your
+         test runs.
+    """,
+    examples = """
+        ```
+        # A rule that includes a single .py file containing tests.
+        python_test(
+          name = 'fileutil_test',
+          srcs = ['fileutil_tests.py'],
+          deps = [
+            ':fileutil',
+          ],
+        )
+
+        # A rule that uses glob() to include all sources in the directory which the
+        # rule is defined.  It also lists a resource file that gets packaged with
+        # the sources in this rule.
+        python_library(
+          name = 'fileutil',
+          srcs = glob(['fileutil/**/*.py']),
+          resources = [
+            'testdata.dat',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {k: attrs.default_only(v) for k, v in cxx_rules.cxx_binary.attrs.items()}
+        | buck.inject_test_env_arg()
+        | python_common.srcs_arg()
+        | python_common.resources_arg()
+        | python_common.base_module_arg()
+        | python_common.exclude_deps_from_merged_linking_arg()
+        | {
+            "main_module": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                The main module used to run the tests.
+                 This parameter is normally not needed, as Buck will provide a default main
+                 module that runs all tests. However, you can override this with your own
+                 module to perform custom initialization or command line processing. Your
+                 custom module can import the standard Buck test main
+                 as `__test_main__`, and can invoke it's normal main function
+                 as `__test_main__.main(sys.argv)`.
+            """,
+            ),
+        }
+        | {
+            "env": attrs.dict(
+                key = attrs.string(),
+                value = attrs.arg(),
+                sorted = False,
+                default = {},
+                doc = """
+                A map of environment names and values to set when running the test.
+
+                 It is also possible to expand references to other rules within the **values** of
+                 these environment variables, using builtin `string parameter macros`
+                :
+
+                `$(location //path/to:target)`
+                Expands to the location of the output of the build rule. This
+                 means that you can refer to these without needing to be aware of how
+                 Buck is storing data on the disk mid-build.
+            """,
+            ),
+        }
+        | python_common.deps_arg()
+        | python_common.version_selections_arg()
+        | buck.test_rule_timeout_ms()
+        | python_common.package_style_arg()
+        | python_common.preload_deps_arg()
+        | python_common.linker_flags_arg()
+        | python_common.deduplicate_merged_link_roots()
+        | python_common.executable_deps_arg()
+        | native_common.link_group_deps()
+        | native_common.link_group_public_deps_label()
+        | native_common.transformation_spec_arg()
+        | {
+            "additional_coverage_targets": attrs.list(attrs.dep(), default = []),
+            "build_args": attrs.list(attrs.arg(), default = []),
+            "compile": attrs.option(attrs.bool(), default = None),
+            "dummy_omnibus": attrs.option(attrs.dep(), default = None),
+            "extension": attrs.option(attrs.string(), default = None),
+            "needed_coverage": attrs.list(attrs.tuple(attrs.int(), attrs.dep(), attrs.option(attrs.string())), default = []),
+            "prefer_stripped_native_objects": attrs.bool(default = False),
+            "repl_main": attrs.option(attrs.string(), default = None),
+            "repl_only_deps": attrs.list(attrs.dep(), default = []),
+            "runner": attrs.option(attrs.dep(), default = None),
+            "specs": attrs.option(attrs.arg(json = True), default = None),
+            "versioned_resources": attrs.option(attrs.versioned(attrs.named_set(attrs.source(), sorted = True)), default = None),
+            "versioned_srcs": attrs.option(attrs.versioned(attrs.named_set(attrs.source(), sorted = True)), default = None),
+            "zip_safe": attrs.option(attrs.bool(), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+        | _typing_arg()
+        | test_common.attributes()
+        | _python_test_attrs()
+        | validation_common.attrs_validators_arg()
+    ),
+    cfg = constraint_overrides.python_transition,
+)
+
+python_test_runner = prelude_rule(
+    name = "python_test_runner",
+    docs = "",
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.labels_arg()
+        | {
+            "main_module": attrs.string(default = ""),
+            "src": attrs.source(),
+        }
+        | buck.licenses_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+python_bootstrap_binary = prelude_rule(
+    name = "python_bootstrap_binary",
+    docs = """
+        A `python_bootstrap_binary()` rule declares a Python binary intended
+        to be used in scripts that bootstrap other aspects of the Buck2
+        prelude. Python bootstrap binaries do not use the Python toolchain
+        and, as such, are highly restricted in what they can and can't do.
+        In particular, bootstrap binaries can only depend on
+        `python_bootstrap_library()` rules and the entry point must consist
+        of a single source file.
+    """,
+    examples = None,
+    further = None,
+    attrs = {},
+)
+
+python_bootstrap_library = prelude_rule(
+    name = "python_bootstrap_library",
+    docs = """
+        A `python_bootstrap_library()` rule groups together Python sources
+        that may be consumed by `python_bootstrap_binary()` targets or by
+        other `python_bootstrap_library()` rules. Bootstrap libraries do
+        not use the Python toolchain and may only be depended on by other
+        bootstrap libraries or bootstrap binaries.
+    """,
+    examples = None,
+    further = None,
+    attrs = {},
+)
+
+python_needed_coverage_test = prelude_rule(
+    name = "python_needed_coverage_test",
+    docs = """
+        A `python_needed_coverage_test()` rule wraps an existing
+        `python_test()` target so that it runs as a coverage-collecting
+        bundle and is checked against per-module coverage thresholds. It is
+        used to enforce that specific modules covered by the wrapped test
+        meet a minimum coverage ratio at test time.
+    """,
+    examples = None,
+    further = None,
+    attrs = {},
+)
+
+python_runtime_bundle = prelude_rule(
+    name = "python_runtime_bundle",
+    docs = """
+        A `python_runtime_bundle()` rule declares a bundled Python runtime
+        — a full install of Python including the interpreter, standard
+        library, headers, and optionally `libpython.so` and additional
+        shared libraries — that can be embedded in a PAR to produce a
+        fully hermetic distribution.
+    """,
+    examples = None,
+    further = None,
+    attrs = {},
+)
+
+python_rules = struct(
+    cxx_python_extension = cxx_python_extension,
+    prebuilt_python_library = prebuilt_python_library,
+    python_binary = python_binary,
+    python_bootstrap_binary = python_bootstrap_binary,
+    python_bootstrap_library = python_bootstrap_library,
+    python_library = python_library,
+    python_needed_coverage_test = python_needed_coverage_test,
+    python_runtime_bundle = python_runtime_bundle,
+    python_test = python_test,
+    python_test_runner = python_test_runner,
+)
diff --git a/buck2/prelude/decls/re_test_common.bzl b/buck2/prelude/decls/re_test_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/re_test_common.bzl
@@ -0,0 +1,67 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":toolchains_common.bzl", "toolchains_common")
+
+def _opts_for_tests_arg() -> Attr:
+    # Attributes types do not have records.
+    # The expected shape of re_opts is:
+    # {
+    #     "capabilities": Dict<str, str> | None
+    #     "listing_capabilities": Dict<str, str> | None
+    #     "local_listing_enabled": bool | None
+    #     "local_enabled": bool |  None
+    #     "use_case": str | None
+    #     "remote_cache_enabled": bool | None
+    #     "dependencies": list<Dict<str, str>> | []
+    #     "gang_workers": list<Dict<str, str>> | []
+    #     "gang": Dict<str, str | int | Dict<str, str>> | None
+    #     "resource_units": int | None
+    #     "remote_execution_dynamic_image": dict<str, str | list<str>> | None
+    # }
+    return attrs.dict(
+        key = attrs.string(),
+        value = attrs.option(
+            attrs.one_of(
+                attrs.dict(
+                    key = attrs.string(),
+                    value = attrs.one_of(
+                        attrs.string(),
+                        attrs.list(attrs.string()),
+                        attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False),
+                        attrs.int(),
+                    ),
+                    sorted = False,
+                ),
+                attrs.string(),
+                attrs.bool(),
+                attrs.list(attrs.dict(key = attrs.string(), value = attrs.string()), default = []),
+                attrs.int(),
+            ),
+            # TODO(cjhopman): I think this default does nothing, it should be deleted
+            default = None,
+        ),
+        sorted = False,
+    )
+
+def _test_args() -> dict[str, Attr]:
+    return {
+        "remote_execution": attrs.option(
+            attrs.one_of(
+                attrs.string(),
+                _opts_for_tests_arg(),
+            ),
+            default = None,
+        ),
+        "_remote_test_execution_toolchain": toolchains_common.remote_test_execution(),
+    }
+
+re_test_common = struct(
+    test_args = _test_args,
+    opts_for_tests_arg = _opts_for_tests_arg,
+)
diff --git a/buck2/prelude/decls/remote_common.bzl b/buck2/prelude/decls/remote_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/remote_common.bzl
@@ -0,0 +1,153 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load("@prelude//http_archive:exec_deps.bzl", "HttpArchiveExecDeps")
+load(":common.bzl", "validate_uri")
+
+def _name_arg(name_type):
+    return {
+        "name": name_type,
+    }
+
+def _sha256_arg():
+    return {
+        "sha256": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    The [`SHA-256`](//wikipedia.org/wiki/SHA-2) hash of the downloaded artifact.
+     Buck verifies this is correct and fails the fetch command if it doesn't match in order to
+     guarantee repeatable builds.
+""",
+        ),
+    }
+
+def _urls_arg():
+    return {
+        "urls": attrs.list(
+            attrs.string(validate = validate_uri),
+            default = [],
+            doc = """
+    A list of urls to attempt to download from. They are tried in order, and
+     subsequent ones are only tried if the download fails. If validation fails,
+     a new URL is not used. Supported protocols are "http", "https", and "mvn".
+""",
+        ),
+        "vpnless_urls": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    Additional URLs from which this resource can be downloaded when
+     off VPN. Meta-internal only.
+""",
+        ),
+    }
+
+def _unarchive_args():
+    return {
+        "excludes": attrs.list(
+            attrs.regex(),
+            default = [],
+            doc = """
+            An optional list of regex patterns. All file paths in the extracted archive which match
+             any of the given patterns will be omitted.
+        """,
+        ),
+        "exec_deps": attrs.exec_dep(
+            providers = [HttpArchiveExecDeps],
+            default = "prelude//http_archive/tools:exec_deps",
+            doc = """
+            When using http_archive as an anon target, the rule invoking the
+            anon target needs to mirror this attribute into its own
+            attributes, and forward the provider into the anon target
+            invocation.
+
+            When using http_archive normally not as an anon target, the
+            default value is always fine.
+        """,
+        ),
+        "out": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+            An optional name to call the directory that the downloaded artifact is
+            extracted into. Buck will generate a default name if one is not
+            provided that uses the `name` of the rule.
+        """,
+        ),
+        "strip_prefix": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+            If set, files under this path will be extracted to the root of the output
+            directory. Siblings or cousins to this prefix will not be extracted at all.
+
+            For example, if a tarball has the layout:
+            * foo/bar/bar-0.1.2/data.dat
+            * foo/baz/baz-0.2.3
+            * foo\\_prime/bar-0.1.2
+
+            Only `data.dat` will be extracted, and it will be extracted into the output
+            directory specified in `out`.
+        """,
+        ),
+        "sub_targets": attrs.one_of(
+            attrs.list(attrs.string()),
+            attrs.dict(
+                attrs.string(),
+                attrs.list(attrs.string()),
+            ),
+            default = [],
+            doc = """
+            A list of filepaths within the archive to be made accessible as sub-targets.
+            For example if we have an http_archive with `name = "archive"` and
+            `sub_targets = ["src/lib.rs"]`, then other targets would be able to refer
+            to that file as `":archive[src/lib.rs]"`.
+
+            Or, a dict of sub_target name to list of files to be in that subtarget.
+            For example, with
+
+            ```
+            http_archive(
+                name = "archive",
+                ...
+                sub_targets = {
+                    "group_1": ["a.txt", "b.txt"],
+                    "a.txt": ["a.txt"]
+                },
+            )
+            ```
+
+            ... you get two sub targets: `:archive[group_1]` consisting of two files, and
+            `:archive[a.txt]` consisting of one file.
+        """,
+        ),
+        "type": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+            Normally, archive type is determined by the file's extension. If `type` is set,
+            then autodetection is overridden, and the specified type is used instead.
+
+            Supported values are: `zip`, `tar`, `tar.gz`,
+            `tar.bz2`, `tar.xz`, and `tar.zst`.
+        """,
+        ),
+    }
+
+remote_common = struct(
+    name_arg = _name_arg,
+    sha256_arg = _sha256_arg,
+    urls_arg = _urls_arg,
+    unarchive_args = _unarchive_args,
+)
diff --git a/buck2/prelude/decls/rust_common.bzl b/buck2/prelude/decls/rust_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/rust_common.bzl
@@ -0,0 +1,233 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//rust:link_info.bzl", "RustProcMacroPlugin")
+load("@prelude//rust:sources.bzl", "mapped_srcs_arg", "srcs_arg", "srcs_filegroup_arg")
+load(":toolchains_common.bzl", "toolchains_common")
+
+def rust_target_dep(is_binary: bool) -> Attr:
+    return attrs.dep(
+        pulls_and_pushes_plugins = [] if is_binary else [RustProcMacroPlugin],
+        pulls_plugins = [RustProcMacroPlugin] if is_binary else [],
+    )
+
+def _deps_arg(is_binary: bool):
+    return {
+        "deps": attrs.list(
+            rust_target_dep(is_binary),
+            default = [],
+            doc = """
+    The set of dependencies of this rule. Currently, this supports rust\\_library
+     and prebuilt\\_rust\\_library rules.
+""",
+        ),
+    }
+
+def _features_arg():
+    return {
+        "features": attrs.list(
+            attrs.string(),
+            default = [],
+            doc = """
+    The set of features to be enabled for this rule.
+
+     These are passed to `rustc` with `--cfg feature="{feature}"`, and can be used in the code with `#[cfg(feature = "{feature}")]`.
+""",
+        ),
+    }
+
+def _edition_arg():
+    return {
+        "edition": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    Set the language edition to be used for this rule. Can be set to any edition the
+     compiler supports (`2018` right now). If unset it uses the compiler's default
+     (`2015`).
+""",
+        ),
+    }
+
+def _rustc_flags_arg():
+    return {
+        "rustc_flags": attrs.list(
+            attrs.arg(),
+            default = [],
+            doc = """
+    The set of additional compiler flags to pass to `rustc`.
+""",
+        ),
+    }
+
+def _linker_flags_arg():
+    return {
+        "linker_flags": attrs.list(
+            attrs.arg(anon_target_compatible = True),
+            default = [],
+            doc = """
+    The set of additional flags to pass to the linker.
+""",
+        ),
+    }
+
+def _exported_linker_flags_arg():
+    return {
+        "exported_linker_flags": attrs.list(
+            attrs.arg(anon_target_compatible = True),
+            default = [],
+            doc = """
+    A set of additional flag to pass before this item on the link line, even if
+    this items is compiled to a DSO.
+""",
+        ),
+        "exported_post_linker_flags": attrs.list(
+            attrs.arg(anon_target_compatible = True),
+            default = [],
+            doc = """
+    A set of additional flag to pass after this item on the link line, even if
+    this items is compiled to a DSO.
+""",
+        ),
+    }
+
+def _crate(crate_type):
+    return {
+        "crate": crate_type,
+    }
+
+def _crate_root():
+    return {
+        "crate_root": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+    Set the name of the top-level source file for the crate, which can be used to override the
+     default (see `srcs`).
+""",
+        ),
+    }
+
+def _default_roots_arg():
+    return {
+        "default_roots": attrs.option(
+            attrs.list(attrs.string()),
+            default = None,
+            doc = """
+    Set the candidate source names to consider for crate root. Typically used to disambiguate between
+     lib.rs or main.rs for rust_test, which may be declare a test suite for either library or binary
+     rules. Has no effect if an explicit `crate_root` is provided.
+""",
+        ),
+    }
+
+def _env_arg():
+    return {
+        "env": attrs.dict(
+            key = attrs.string(),
+            value = attrs.arg(),
+            sorted = False,
+            default = {},
+            doc = """
+    Set environment variables for this rule's invocations of rustc. The environment variable
+     values may include macros which are expanded.
+""",
+        ),
+    }
+
+def _run_env_arg():
+    return {
+        "run_env": attrs.dict(
+            key = attrs.string(),
+            value = attrs.arg(),
+            sorted = False,
+            default = {},
+            doc = """
+    Set environment variables during test execution. The environment variable values may
+     include macros which are expanded.
+""",
+        ),
+    }
+
+def _build_and_run_env_arg():
+    # Same as env_arg(), but with different documentation.
+    return {
+        "env": attrs.dict(
+            key = attrs.string(),
+            value = attrs.arg(),
+            sorted = False,
+            default = {},
+            doc = """
+    Set environment variables for this rule's invocations of rustc *and* during execution of
+     the tests. The environment variable values may include macros which are expanded.
+""",
+        ),
+    }
+
+def _named_deps_arg(is_binary: bool):
+    return {
+        "named_deps": attrs.one_of(
+            attrs.dict(key = attrs.string(), value = rust_target_dep(is_binary), sorted = False),
+            attrs.list(attrs.tuple(attrs.arg(), rust_target_dep(is_binary))),
+            default = {},
+            doc = """
+    Add crate dependencies and define a local name by which to use that dependency by. This
+     allows a crate to have multiple dependencies with the same crate name. For example:
+     `named_deps = {"local_name", ":some_rust_crate" }`.
+     The dependencies may also be non-Rust, but the alias is ignored. It has no effect on the
+     symbols provided by a C/C++ library.
+""",
+        ),
+    }
+
+def _rust_toolchain_arg():
+    return {
+        "_rust_internal_tools_toolchain": attrs.default_only(
+            attrs.toolchain_dep(default = "prelude//rust/tools:internal_tools_toolchain"),
+        ),
+        "_rust_toolchain": toolchains_common.rust(),
+    }
+
+def _cxx_toolchain_arg():
+    return {
+        "_cxx_toolchain": toolchains_common.cxx(),
+    }
+
+def _workspaces_arg():
+    return {
+        "_workspaces": attrs.list(
+            attrs.label(),
+            default = [],
+            doc = """
+    Internal implementation detail of Rust workspaces. This should not be set manually and will be
+     replaced in favor of metadata in a future version of buck2.
+""",
+        ),
+    }
+
+rust_common = struct(
+    deps_arg = _deps_arg,
+    srcs_arg = srcs_arg,
+    srcs_filegroup_arg = srcs_filegroup_arg,
+    features_arg = _features_arg,
+    edition_arg = _edition_arg,
+    rustc_flags_arg = _rustc_flags_arg,
+    linker_flags_arg = _linker_flags_arg,
+    exported_linker_flags_arg = _exported_linker_flags_arg,
+    crate = _crate,
+    crate_root = _crate_root,
+    default_roots_arg = _default_roots_arg,
+    env_arg = _env_arg,
+    run_env_arg = _run_env_arg,
+    build_and_run_env_arg = _build_and_run_env_arg,
+    mapped_srcs_arg = mapped_srcs_arg,
+    named_deps_arg = _named_deps_arg,
+    rust_toolchain_arg = _rust_toolchain_arg,
+    cxx_toolchain_arg = _cxx_toolchain_arg,
+    workspaces_arg = _workspaces_arg,
+)
diff --git a/buck2/prelude/decls/rust_rules.bzl b/buck2/prelude/decls/rust_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/rust_rules.bzl
@@ -0,0 +1,357 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:link_groups_types.bzl", "LINK_GROUP_MAP_ATTR")
+load("@prelude//decls:cxx_rules.bzl", "BUILD_INFO_ATTR")
+load("@prelude//decls:test_common.bzl", "test_common")
+load("@prelude//decls:third_party_common.bzl", "third_party_common")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//rust:clippy_configuration.bzl", "ClippyConfiguration")
+load("@prelude//rust:link_info.bzl", "RustProcMacroPlugin")
+load("@prelude//rust:rust_binary.bzl", "rust_binary_impl", "rust_test_impl")
+load("@prelude//rust:rust_library.bzl", "rust_library_impl")
+load("@prelude//rust/rust-analyzer:provider.bzl", "RustAnalyzerTargetKind")
+load(":common.bzl", "RuntimeDependencyHandling", "buck", "prelude_rule")
+load(":cxx_common.bzl", "cxx_common")
+load(":native_common.bzl", "native_common")
+load(":re_test_common.bzl", "re_test_common")
+load(":rust_common.bzl", "rust_common", "rust_target_dep")
+
+def _rust_common_attributes(is_binary: bool):
+    return (
+        buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+        | {
+            "clippy_configuration": attrs.option(attrs.dep(providers = [ClippyConfiguration]), default = None),
+            "coverage": attrs.bool(default = False),
+            "default_platform": attrs.option(attrs.string(), default = None),
+            "flagged_deps": attrs.list(attrs.tuple(rust_target_dep(is_binary), attrs.list(attrs.string())), default = []),
+            "incremental_enabled": attrs.bool(default = False),
+            "resources": attrs.named_set(attrs.one_of(attrs.dep(), attrs.source()), sorted = True, default = []),
+            "rustdoc_flags": attrs.list(attrs.arg(), default = []),
+            "separate_debug_info": attrs.bool(default = False),
+            "use_content_based_paths": attrs.bool(default = True),
+            "uses_restricted_rustc_flags": attrs.bool(default = False),
+            "_exec_os_type": buck.exec_os_type_arg(),
+            "_target_os_type": buck.target_os_type_arg(),
+        }
+        | cxx_common.default_deps_arg()
+    )
+
+def _rust_analyzer_target_kind(kind: str) -> dict[str, Attr]:
+    return {
+        "_rust_analyzer_target_kind": attrs.default_only(
+            attrs.enum(RustAnalyzerTargetKind.values(), default = kind),
+        ),
+    }
+
+def _rust_binary_attrs_group(prefix: str) -> dict[str, Attr]:
+    attrs = rust_common.deps_arg(is_binary = True) | rust_common.named_deps_arg(is_binary = True) | rust_common.linker_flags_arg() | native_common.link_style()
+    return {prefix + name: v for name, v in attrs.items()}
+
+_RUST_EXECUTABLE_ATTRIBUTES = {
+    "anonymous_link_groups": attrs.bool(default = True),
+    # Unlike cxx which supports pre-defined link groups, we only support
+    # auto_link_groups in rust
+    "auto_link_groups": attrs.bool(default = True),
+    # BOLT post-link optimization only applies when cxx performs the link
+    # (advanced_unstable_linking toolchains; see rust_link_binary).
+    "bolt_flags": attrs.list(attrs.arg(), default = []),
+    "bolt_profile": attrs.option(attrs.source(), default = None),
+    # Contents to embed into the linked executable as named ELF sections, added
+    # after BOLT and before build info stamping. Only applies when cxx performs
+    # the link (advanced_unstable_linking toolchains; see rust_link_binary).
+    "elf_sections": attrs.dict(
+        key = attrs.string(),
+        value = attrs.source(),
+        sorted = True,
+        default = {},
+    ),
+    "enable_distributed_thinlto": attrs.bool(default = False),
+    "extra_dwp_flags": attrs.list(attrs.string(), default = []),
+    # Opt the final executable output into content-based (immutable) buck-out
+    # pathing (default off). A bare static binary becomes a content-based exe.
+    # A binary with adjacent files (`resources` and/or a shared-lib tree)
+    # ships as a content-addressed `assembled_dir` dist bundle instead (exe
+    # copied in, adjacent files symlinked; `[dist]` subtarget). Bundle
+    # immutability is per-entry: copied entries always; symlinked entries only
+    # when their target is itself content-based -- config-based resources and
+    # the (deliberately config-based) shlib tree remain rewrite-in-place.
+    "has_content_based_path": attrs.bool(default = False),
+    # Required by the rules but not supported, since Rust is auto-link groups only
+    "link_group": attrs.default_only(attrs.option(attrs.string(), default = None)),
+    "link_group_map": LINK_GROUP_MAP_ATTR,
+    "link_group_min_binary_node_count": attrs.option(attrs.int(), default = None),
+    "rpath": attrs.bool(
+        default = False,
+        doc = """
+              Set the "rpath" in the executable when using a shared link style.
+          """,
+    ),
+    "runtime_dependency_handling": attrs.option(
+        attrs.enum(RuntimeDependencyHandling),
+        default = None,
+        doc = """
+              Controls how shared library dependencies are handled at runtime. If not set,
+              falls back to the CXX toolchain default. If ``symlink`` is specified then shared
+              library dependencies with ``preferred_linkage = "shared"`` are automatically
+              detected and included in a symlink tree alongside the executable. If ``no_symlink``
+              is specified then shared library dependencies are not included in the symlink tree.
+          """,
+    ),
+    "_build_info": BUILD_INFO_ATTR,
+}
+
+rust_binary = prelude_rule(
+    name = "rust_binary",
+    impl = rust_binary_impl,
+    docs = """
+        A rust\\_binary() rule builds a native executable from the supplied set of Rust source files
+        and dependencies.
+
+        If you invoke a build with the `check` flavor, then Buck will invoke rustc
+        to check the code (typecheck, produce warnings, etc), but won't generate an executable code.
+        When applied to binaries it produces no output; for libraries it produces metadata for
+        consumers of the library.
+
+        Note: Buck is currently tested with (and therefore supports) version 1.32.0 of Rust.
+    """,
+    examples = """
+        For more examples, check out our [integration tests](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/rust/testdata/).
+
+        ```
+        rust_binary(
+          name='greet',
+          srcs=[
+            'greet.rs',
+          ],
+          deps=[
+            ':greeting',
+          ],
+        )
+
+        rust_library(
+          name='greeting',
+          srcs=[
+            'greeting.rs',
+          ],
+          deps=[
+            ':join',
+          ],
+        )
+
+        rust_library(
+          name='join',
+          srcs=[
+            'join.rs',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        rust_common.srcs_arg()
+        | rust_common.srcs_filegroup_arg()
+        | rust_common.mapped_srcs_arg()
+        | rust_common.edition_arg()
+        | rust_common.features_arg()
+        | rust_common.rustc_flags_arg()
+        | rust_common.crate(crate_type = attrs.option(attrs.string(), default = None))
+        | rust_common.crate_root()
+        | rust_common.env_arg()
+        | _rust_binary_attrs_group(prefix = "")
+        | _rust_common_attributes(is_binary = True)
+        | _rust_analyzer_target_kind("bin")
+        | _RUST_EXECUTABLE_ATTRIBUTES
+        | rust_common.cxx_toolchain_arg()
+        | rust_common.rust_toolchain_arg()
+        | rust_common.workspaces_arg()
+        | native_common.transformation_spec_arg()
+        | buck.allow_cache_upload_arg()
+    ),
+    uses_plugins = [RustProcMacroPlugin],
+    supports_incoming_transition = True,
+)
+
+rust_library = prelude_rule(
+    name = "rust_library",
+    impl = rust_library_impl,
+    docs = """
+        A rust\\_library() rule builds a native library from the supplied set of Rust source files
+        and dependencies.
+
+        If you invoke a build with the `check` flavor, then Buck will invoke rustc
+        to check the code (typecheck, produce warnings, etc), but won't generate an executable code.
+        When applied to binaries it produces no output; for libraries it produces metadata for
+        consumers of the library.
+
+        Note: Buck is currently tested with (and therefore supports) version 1.32.0 of Rust.
+    """,
+    examples = """
+        For more examples, check out our [integration tests](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/rust/testdata/).
+
+        ```
+        rust_library(
+          name='greeting',
+          srcs=[
+            'greeting.rs',
+          ],
+          deps=[
+            ':join',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        rust_common.srcs_arg()
+        | rust_common.srcs_filegroup_arg()
+        | rust_common.mapped_srcs_arg()
+        | rust_common.deps_arg(is_binary = False)
+        | rust_common.named_deps_arg(is_binary = False)
+        | rust_common.edition_arg()
+        | rust_common.features_arg()
+        | rust_common.rustc_flags_arg()
+        |
+        # linker_flags weren't supported for rust_library in Buck v1 but the
+        # fbcode macros pass them anyway. They're typically empty since the
+        # config-level flags don't get injected, but it doesn't hurt to accept
+        # them and it simplifies the implementation of Rust rules since they
+        # don't have to know whether we're building a rust_binary or a
+        # rust_library.
+        rust_common.linker_flags_arg()
+        | rust_common.exported_linker_flags_arg()
+        | rust_common.env_arg()
+        | rust_common.crate(crate_type = attrs.option(attrs.string(), default = None))
+        | rust_common.crate_root()
+        | native_common.preferred_linkage(preferred_linkage_type = attrs.enum(Linkage.values(), default = "any"))
+        | native_common.soname()
+        | native_common.link_style()
+        | native_common.link_whole(link_whole_type = attrs.option(attrs.bool(), default = None))
+        | _rust_common_attributes(is_binary = False)
+        | _rust_analyzer_target_kind("lib")
+        | {
+            "crate_dynamic": attrs.option(attrs.dep(), default = None),
+            "doc_env": rust_common.env_arg()["env"],
+            "doctests": attrs.option(attrs.bool(), default = None),
+            "include_in_android_merge_map_output": attrs.bool(default = True),
+            "proc_macro": attrs.bool(default = False),
+            "supports_python_dlopen": attrs.option(attrs.bool(), default = None),
+        }
+        | _rust_binary_attrs_group(prefix = "doc_")
+        | {
+            "doc_remote_execution": attrs.option(
+                re_test_common.opts_for_tests_arg(),
+                default = None,
+                doc = """
+                Remote execution properties for this library's rustdoc test. Only a
+                property dict is accepted, not the name of a profile on the remote test
+                execution toolchain, so that `rust_library` does not have to depend on
+                that toolchain. When unset, the rustdoc test carries no executor and
+                runs wherever the test framework would otherwise place it.
+            """,
+            ),
+        }
+        | rust_common.cxx_toolchain_arg()
+        | rust_common.rust_toolchain_arg()
+        | rust_common.workspaces_arg()
+        | third_party_common.create_third_party_build_root_attrs()
+    ),
+    uses_plugins = [RustProcMacroPlugin],
+    supports_incoming_transition = True,
+)
+
+rust_test = prelude_rule(
+    name = "rust_test",
+    impl = rust_test_impl,
+    docs = """
+        A rust\\_test() rule builds a Rust test native executable from the supplied set of Rust source
+        files and dependencies and runs this test.
+
+        Note: Buck is currently tested with (and therefore supports) version 1.32.0 of Rust.
+    """,
+    examples = """
+        For more examples, check out our [integration tests](https://github.com/facebook/buck/tree/dev/test/com/facebook/buck/rust/testdata/).
+
+        ```
+        rust_test(
+          name='greet',
+          srcs=[
+            'greet.rs',
+          ],
+          deps=[
+            ':greeting',
+          ],
+        )
+
+        rust_library(
+          name='greeting',
+          srcs=[
+            'greeting.rs',
+          ],
+          deps=[
+            ':join',
+          ],
+        )
+
+        rust_library(
+          name='join',
+          srcs=[
+            'join.rs',
+          ],
+        )
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.inject_test_env_arg()
+        | rust_common.srcs_arg()
+        | rust_common.srcs_filegroup_arg()
+        | rust_common.mapped_srcs_arg()
+        | rust_common.edition_arg()
+        | rust_common.features_arg()
+        | rust_common.rustc_flags_arg()
+        | rust_common.crate(crate_type = attrs.option(attrs.string(), default = None))
+        | rust_common.crate_root()
+        | rust_common.default_roots_arg()
+        | rust_common.run_env_arg()
+        | rust_common.build_and_run_env_arg()
+        | _rust_binary_attrs_group(prefix = "")
+        | _rust_common_attributes(is_binary = True)
+        | _rust_analyzer_target_kind("test")
+        | _RUST_EXECUTABLE_ATTRIBUTES
+        | {
+            "framework": attrs.bool(
+                default = True,
+                doc = """
+                Use the standard test framework. If this is set to false, then the result is a normal
+                executable which requires a `main()`, etc. It is still expected to accept the
+                same command-line parameters and produce the same output as the test framework.
+            """,
+            ),
+        }
+        | re_test_common.test_args()
+        | rust_common.cxx_toolchain_arg()
+        | rust_common.rust_toolchain_arg()
+        | rust_common.workspaces_arg()
+        | native_common.transformation_spec_arg()
+        | test_common.attributes()
+    ),
+    uses_plugins = [RustProcMacroPlugin],
+    supports_incoming_transition = True,
+)
+
+rust_rules = struct(
+    rust_binary = rust_binary,
+    rust_library = rust_library,
+    rust_test = rust_test,
+)
diff --git a/buck2/prelude/decls/shell_rules.bzl b/buck2/prelude/decls/shell_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/shell_rules.bzl
@@ -0,0 +1,230 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:test_common.bzl", "test_common")
+load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")
+load(":common.bzl", "buck", "prelude_rule")
+load(":re_test_common.bzl", "re_test_common")
+
+sh_binary = prelude_rule(
+    name = "sh_binary",
+    docs = """
+        An `sh_binary()` is used to execute a shell script.
+    """,
+    examples = """
+        This sh\\_binary() just cats a sample data file back at the user.
+
+        ```
+        # $REPO/BUCK
+        sh_binary(
+            name = "script",
+            main = "script.sh",
+            resources = [
+                "data.dat",
+            ],
+        )
+        ```
+
+        ```
+        # Sample data file with data we need at runtime
+        $ echo "I'm a datafile" > data.dat
+
+        # Create a simple script that prints out the resource
+        $ cat > script.sh
+        #!/bin/sh
+        cat $BUCK_DEFAULT_RUNTIME_RESOURCES/data.dat
+
+        # Make sure the script is executable
+        $ chmod u+x script.sh
+
+        # Run the script, and see that it prints out the resource we provided
+        $ buck run //:script
+        Jobs completed: 4. Time elapsed: 0.2s.
+        BUILD SUCCEEDED
+        I'm a datafile
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "main": attrs.source(
+                doc = """
+                Either the path to the script (relative to the build file), or a `build target`.
+                 This file must be executable in order to be run.
+            """
+            ),
+            "resources": attrs.list(
+                attrs.source(allow_directory = True),
+                default = [],
+                doc = """
+                A list of files or build rules that this rule requires in order to run. These could be things such as
+                 random data files.
+
+                 When the script runs, the `$BUCK_DEFAULT_RUNTIME_RESOURCES`
+                 environment variable specifies the directory that contains these resources.
+                 This directory's location is determined entirely by Buck; the script should
+                 not assume the directory's location.
+
+                 The resources are also made available in a tree structure that mirrors
+                 their locations in the source and `buck-out` trees. The
+                 environment variable `$BUCK_PROJECT_ROOT` specifies a directory
+                 that contains all the resources, laid out in their locations relative to
+                 the original buck project root.
+            """,
+            ),
+            "append_script_extension": attrs.bool(
+                default = True,
+                doc = """
+                By default, sh_binary ensures that the script has an appropriate extension (e.g. `.sh` or `.bat`),
+                  appending one itself if necessary. Setting this to False prevents that behavior and makes the caller
+                  responsible for ensuring an existing appropriate extension.
+            """,
+            ),
+            "copy_resources": attrs.bool(
+                default = False,
+                doc = """
+                By default, sh_binary attempts to use symbolic links for the resources. This can be changed so,
+                that copies are made instead.
+            """,
+            ),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "_target_os_type": buck.target_os_type_arg(),
+            "has_content_based_path": attrs.bool(default = True),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+sh_test = prelude_rule(
+    name = "sh_test",
+    docs = """
+        A `sh_test()` is a test rule that can pass results to the test runner by invoking a shell script.
+
+        **NOTE:** This rule is not currently supported on Windows.
+    """,
+    examples = """
+        This sh\\_test() fails if a string does not match a value.
+
+        ```
+        # $REPO/BUCK
+        sh_test(
+            name = "script_pass",
+            test = "script.sh",
+            args = ["--pass"],
+        )
+
+        sh_test(
+            name = "script_fail",
+            test = "script.sh",
+            args = ["--fail"],
+        )
+        ```
+
+        ```
+        # Create a simple script that prints out the resource
+        $ cat > script.sh
+        #!/bin/sh
+        for arg in $@; do
+          if [ "$arg" == "--pass" ]; then
+            echo "Passed"
+            exit 0;
+          fi
+        done
+        echo "Failed"
+        exit 1
+
+        # Make sure the script is executable
+        $ chmod u+x script.sh
+
+        # Run the script, and see that one test passes, one fails
+        $ buck test //:script_pass //:script_fail
+        FAILURE script.sh sh_test
+        Building: finished in 0.0 sec (100%) 2/2 jobs, 0 updated
+          Total time: 0.0 sec
+        Testing: finished in 0.0 sec (1 PASS/1 FAIL)
+        RESULTS FOR //:script_fail //:script_pass
+        FAIL    <100ms  0 Passed   0 Skipped   1 Failed   //:script_fail
+        FAILURE script.sh sh_test
+        ====STANDARD OUT====
+        Failed
+
+        PASS    <100ms  1 Passed   0 Skipped   0 Failed   //:script_pass
+        TESTS FAILED: 1 FAILURE
+        Failed target: //:script_fail
+        FAIL //:script_fail
+        ```
+    """,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        buck.inject_test_env_arg()
+        | {
+            "args": attrs.list(
+                attrs.arg(),
+                default = [],
+                doc = """
+                The list of arguments to invoke this script with. These are literal values, and no shell interpolation is done.
+
+                 These can contain `string parameter macros`
+                , for example, to give the location of a generated binary to the test script.
+            """,
+            ),
+            "deps": attrs.list(attrs.dep(), default = []),
+            "env": attrs.dict(
+                key = attrs.string(),
+                value = attrs.arg(),
+                sorted = False,
+                default = {},
+                doc = """
+                Environment variable overrides that should be used when running the script. The key is the variable name, and the value is its value.
+
+                 The values can contain `string parameter macros`
+                such as the location of a generated binary to be used by the test script.
+            """,
+            ),
+            "list_args": attrs.option(attrs.list(attrs.string()), default = None),
+            "list_env": attrs.option(attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False), default = None),
+            "resources": attrs.list(attrs.source(), default = []),
+            "run_args": attrs.list(attrs.string(), default = []),
+            "run_env": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),
+            "run_test_separately": attrs.bool(default = False),
+            "supports_test_execution_caching": attrs.bool(default = False),
+            "test": attrs.option(
+                attrs.one_of(attrs.dep(), attrs.source()),
+                default = None,
+                doc = """
+                Either the path to the script (relative to the build file), or a `build target`.
+                 This file must be executable in order to be run.
+            """,
+            ),
+            "test_rule_timeout_ms": attrs.option(attrs.int(), default = None),
+            "type": attrs.option(
+                attrs.string(),
+                default = None,
+                doc = """
+                If provided, this will be sent to any configured `.buckconfig`
+            """,
+            ),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+        | test_common.attributes()
+        | re_test_common.test_args()
+        | test_common.attributes()
+    ),
+    cfg = constraint_overrides.transition,
+)
+
+shell_rules = struct(
+    sh_binary = sh_binary,
+    sh_test = sh_test,
+)
diff --git a/buck2/prelude/decls/test_common.bzl b/buck2/prelude/decls/test_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/test_common.bzl
@@ -0,0 +1,19 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+
+def _attributes() -> dict[str, Attr]:
+    return {
+        "network_access": attrs.option(attrs.enum(["all", "none", "loopback", "strict", "private"]), default = None),
+        "_test_toolchain": toolchains_common.test_toolchain(),
+    }
+
+test_common = struct(
+    attributes = _attributes,
+)
diff --git a/buck2/prelude/decls/third_party_common.bzl b/buck2/prelude/decls/third_party_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/third_party_common.bzl
@@ -0,0 +1,22 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _create_third_party_build_root_attr():
+    return (
+        "_create_third_party_build_root",
+        attrs.default_only(attrs.exec_dep(default = "prelude//third-party/tools:create_build")),
+    )
+
+def _create_third_party_build_root_attrs():
+    key, val = _create_third_party_build_root_attr()
+    return {key: val}
+
+third_party_common = struct(
+    create_third_party_build_root_attr = _create_third_party_build_root_attr,
+    create_third_party_build_root_attrs = _create_third_party_build_root_attrs,
+)
diff --git a/buck2/prelude/decls/toolchains_common.bzl b/buck2/prelude/decls/toolchains_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/toolchains_common.bzl
@@ -0,0 +1,146 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_toolchain.bzl", "AidlToolchainInfo", "AndroidPlatformInfo", "AndroidToolchainInfo")
+load("@prelude//csharp:toolchain.bzl", "CSharpToolchainInfo")
+load("@prelude//go:toolchain.bzl", "GoToolchainInfo")
+load("@prelude//go_bootstrap:go_bootstrap.bzl", "GoBootstrapToolchainInfo")
+load("@prelude//haskell:toolchain.bzl", "HaskellPlatformInfo", "HaskellToolchainInfo")
+load("@prelude//java:dex_toolchain.bzl", "DexToolchainInfo")
+load(
+    "@prelude//java:java_toolchain.bzl",
+    "JavaPlatformInfo",
+    "JavaTestToolchainInfo",
+    "JavaToolchainInfo",
+    "PrebuiltJarToolchainInfo",
+)
+load(
+    "@prelude//kotlin:kotlin_toolchain.bzl",
+    "KotlinToolchainInfo",
+)
+load("@prelude//python:python_wheel_toolchain.bzl", "PythonWheelToolchainInfo")
+load("@prelude//python:toolchain.bzl", "PythonPlatformInfo", "PythonToolchainInfo")
+load("@prelude//python/cython:cython_toolchain.bzl", "CythonToolchainInfo")
+load("@prelude//python_bootstrap:python_bootstrap.bzl", "PythonBootstrapToolchainInfo")
+load("@prelude//rust:rust_toolchain.bzl", "RustToolchainInfo")
+load("@prelude//tests:remote_test_execution_toolchain.bzl", "RemoteTestExecutionToolchainInfo")
+load("@prelude//tests:test_listing.bzl", "TestListingInfo")
+load("@prelude//tests:test_toolchain.bzl", "TestToolchainInfo")
+load("@prelude//zip_file:zip_file_toolchain.bzl", "ZipFileToolchainInfo")
+
+def _toolchain(lang: str, providers: list[typing.Any], *, default: typing.Any = None) -> Attr:
+    return attrs.toolchain_dep(default = default or ("toolchains//:" + lang), providers = providers)
+
+def _android_toolchain():
+    return _toolchain("android", [AndroidToolchainInfo, AndroidPlatformInfo, TestListingInfo])
+
+def _android_aidl_toolchain():
+    return _toolchain("android_aidl", [AidlToolchainInfo])
+
+def _csharp_toolchain():
+    return _toolchain("csharp", [CSharpToolchainInfo])
+
+def _cython_toolchain():
+    return _toolchain("cython", [CythonToolchainInfo])
+
+def _cxx_toolchain():
+    # `CxxToolchainInfo, CxxPlatformInfo`, but python doesn't require it
+    lang = "cxx"
+
+    # Portions of the macro layers use the `default_deps` attribute to set this
+    # to the `:cxx_no_default_deps` option. If a targets has within_view checks
+    # that don't list `toolchains//:` they will experience an error. We can avoid
+    # this by ensuring the `within_deps` checks inside buck see either of the
+    # toolchains below as a possible default value, even though one of them is
+    # never able to be selected in this expression.
+    return _toolchain(lang, [], default = select({"DEFAULT": "toolchains//:" + lang, "config//:none": "toolchains//:cxx_no_default_deps"}))
+
+def _dex_toolchain():
+    return _toolchain("dex", [DexToolchainInfo])
+
+def _go_toolchain():
+    return _toolchain("go", [GoToolchainInfo])
+
+def _go_bootstrap_toolchain():
+    return _toolchain("go_bootstrap", [GoBootstrapToolchainInfo])
+
+def _haskell_toolchain():
+    return _toolchain("haskell", [HaskellToolchainInfo, HaskellPlatformInfo])
+
+def _java_toolchain():
+    return _toolchain("java", [JavaToolchainInfo, JavaPlatformInfo])
+
+def _java_bootstrap_toolchain():
+    return _toolchain("java_bootstrap", [JavaToolchainInfo, JavaPlatformInfo])
+
+def _java_for_android_toolchain():
+    return _toolchain("java_for_android", [JavaToolchainInfo, JavaPlatformInfo])
+
+def _java_for_host_test_toolchain():
+    return _toolchain("java_for_host_test", [JavaToolchainInfo, JavaPlatformInfo])
+
+def _java_test_toolchain():
+    return _toolchain("java_test", [JavaTestToolchainInfo, TestListingInfo])
+
+def _kotlin_toolchain():
+    return _toolchain("kotlin", [KotlinToolchainInfo])
+
+def _kotlin_for_android_toolchain():
+    return _toolchain("kotlin_for_android", [KotlinToolchainInfo])
+
+def _prebuilt_jar_toolchain():
+    # Override is allowed for bootstrapping prebuilt jar toolchains
+    return _toolchain("prebuilt_jar", [PrebuiltJarToolchainInfo])
+
+def _python_toolchain():
+    return _toolchain("python", [PythonToolchainInfo, PythonPlatformInfo])
+
+def _python_bootstrap_toolchain():
+    return _toolchain("python_bootstrap", [PythonBootstrapToolchainInfo])
+
+def _python_wheel_toolchain():
+    return _toolchain("python_wheel", [PythonWheelToolchainInfo])
+
+def _rust_toolchain():
+    return _toolchain("rust", [RustToolchainInfo])
+
+def _zip_file_toolchain():
+    return _toolchain("zip_file", [ZipFileToolchainInfo])
+
+def _remote_test_execution_toolchain():
+    return _toolchain("remote_test_execution", [RemoteTestExecutionToolchainInfo])
+
+def _test_toolchain():
+    return _toolchain("test", [TestToolchainInfo])
+
+toolchains_common = struct(
+    android = _android_toolchain,
+    android_aidl = _android_aidl_toolchain,
+    csharp = _csharp_toolchain,
+    cxx = _cxx_toolchain,
+    cython = _cython_toolchain,
+    dex = _dex_toolchain,
+    go = _go_toolchain,
+    go_bootstrap = _go_bootstrap_toolchain,
+    haskell = _haskell_toolchain,
+    java = _java_toolchain,
+    java_bootstrap = _java_bootstrap_toolchain,
+    java_for_android = _java_for_android_toolchain,
+    java_for_host_test = _java_for_host_test_toolchain,
+    java_test = _java_test_toolchain,
+    kotlin = _kotlin_toolchain,
+    kotlin_for_android = _kotlin_for_android_toolchain,
+    prebuilt_jar = _prebuilt_jar_toolchain,
+    python = _python_toolchain,
+    python_bootstrap = _python_bootstrap_toolchain,
+    python_wheel = _python_wheel_toolchain,
+    test_toolchain = _test_toolchain,
+    rust = _rust_toolchain,
+    zip_file = _zip_file_toolchain,
+    remote_test_execution = _remote_test_execution_toolchain,
+)
diff --git a/buck2/prelude/decls/uncategorized_rules.bzl b/buck2/prelude/decls/uncategorized_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/decls/uncategorized_rules.bzl
@@ -0,0 +1,57 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(cjhopman): This was generated by scripts/hacks/rules_shim_with_docs.py,
+# but should be manually edited going forward. There may be some errors in
+# the generated docs, and so those should be verified to be accurate and
+# well-formatted (and then delete this TODO)
+
+load(":common.bzl", "buck", "prelude_rule")
+
+NdkCxxRuntime = ["system", "gabixx", "stlport", "gnustl", "libcxx"]
+
+legacy_toolchain = prelude_rule(
+    name = "legacy_toolchain",
+    docs = "",
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "toolchain_name": attrs.string(default = ""),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+ndk_toolchain = prelude_rule(
+    name = "ndk_toolchain",
+    docs = "",
+    examples = None,
+    further = None,
+    attrs = (
+        # @unsorted-dict-items
+        {
+            "cxx_runtime": attrs.option(attrs.enum(NdkCxxRuntime), default = None),
+            "cxx_toolchain": attrs.dep(),
+            "objdump": attrs.source(),
+            "shared_runtime_path": attrs.option(attrs.source(), default = None),
+            "strip_apk_libs_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        }
+        | buck.licenses_arg()
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    ),
+)
+
+uncategorized_rules = struct(
+    legacy_toolchain = legacy_toolchain,
+    ndk_toolchain = ndk_toolchain,
+)
diff --git a/buck2/prelude/dist/dist_info.bzl b/buck2/prelude/dist/dist_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/dist/dist_info.bzl
@@ -0,0 +1,60 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//linking:shared_libraries.bzl", "SharedLibrariesTSet")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+
+# DistInfo is a provider that indicates what other targets/artifacts might be
+# necessary to ship alongside the current target as part of a package or other
+# distribution mechanism, such as shared libraries, default configuration,
+# graphical/media assets, etc.
+DistInfo = provider(
+    fields = {
+        # The collection of other artifacts that must be available when an
+        # executable is executed, such as resources.
+        #
+        # These files are typically a subset of `DefaultInfo.other_outputs` of the
+        # executable. `other_outputs` may contain other auxiliary helpful but
+        # nonessential runtime files, such as external debuginfo which one would
+        # need in order to run the executable in a debugger.
+        #
+        # When an executable is the end goal of a build (i.e. `buck2 build :main`)
+        # and `--materializations=none` has not been passed, then all of
+        # `other_outputs` is what gets materialized. For convenience to developers,
+        # we choose to make this include external debuginfo, rather than requiring
+        # them to build something like `buck2 build :main :main[debuginfo]` in order
+        # to have an executable that is debuggable locally.
+        #
+        # In contrast, `nondebug_runtime_files` are the things required always in
+        # any context where an executable runs. For example when this executable is
+        # the exe in a genrule -- there would be no point materializing its external
+        # debuginfo in that situation because no debugger is involved.
+        #
+        # There are yet other contexts where not even `nondebug_runtime_files` would
+        # need to be materialized. For example a rule that depends on an executable
+        # in order to compute a checksum or signature for it. As the executable does
+        # not run during that action, runtime files would not be needed. As such,
+        # bundling `nondebug_runtime_files` into an artifact group with the
+        # executable artifact itself, using `artifact.with_associated_artifacts`, is
+        # not a universally suitable alternative to nondebug runtime files.
+        #
+        # Unlike `ResourceInfo` this provider does not attempt to identify the label
+        # from which each of these artifacts originates. This is just the projected
+        # set of all the files for materialization purposes.
+        "nondebug_runtime_files": provider_field(list[ArgLike]),
+        # The artifact is a directory pointed to by the relocatable_resource_json file,
+        # which contains symlinks to the resources used by the binary.
+        "relocatable_resources_contents": provider_field(Artifact | None, default = None),
+        # A JSON file containing a mapping of resources used in the binary to their path
+        # relative to the binary in question (all paths are within
+        # `relocatable_resource_contents`).
+        "relocatable_resources_json": provider_field(Artifact | None, default = None),
+        # Transitive shared library dependencies.
+        "shared_libs": provider_field(SharedLibrariesTSet | None, default = None),
+    }
+)
diff --git a/buck2/prelude/docs/rules.bzl b/buck2/prelude/docs/rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/docs/rules.bzl
@@ -0,0 +1,20 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# We only want to document the rules in the prelude, so have a module that
+# only reexports those.
+#
+# NOTE: This file name is used to distinguish the Rules docs from API docs, if you change this file name,
+# please update the rendering code `render_function` in `starlark-rust/starlark/src/docs/markdown.rs`
+
+load("@prelude//:rules.bzl", _categorized_rules = "categorized_rules")
+
+load_symbols({
+    group_name: namespace(**{rule_name: namespace(**{rule_name: rule_obj}) for rule_name, rule_obj in group_rules.items()})
+    for group_name, group_rules in _categorized_rules.items()
+})
diff --git a/buck2/prelude/erlang/applications/BUCK b/buck2/prelude/erlang/applications/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/applications/BUCK
@@ -0,0 +1,8 @@
+load("@prelude//erlang:erlang_otp_application.bzl", "gen_otp_applications")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+gen_otp_applications()
diff --git a/buck2/prelude/erlang/common_test/common/BUCK b/buck2/prelude/erlang/common_test/common/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/BUCK
@@ -0,0 +1,35 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+erlang_application(
+    name = "common",
+    srcs = glob([
+        "src/*.erl",
+        "src/*.hrl",
+    ]),
+    applications = [
+        "kernel",
+        "stdlib",
+    ],
+    erl_opts = [
+        "+debug_info",
+        "+warnings_as_errors",
+    ],
+    includes = glob(["include/*.hrl"]),
+    shell_libs = [],
+    use_global_parse_transforms = False,
+    visibility = ["PUBLIC"],
+)
+
+erlang_tests(
+    contacts = ["build_infra"],
+    labels = ["unit"],
+    suites = ["test/ct_stdout_SUITE.erl"],
+    deps = [
+        "stdlib",
+        ":common",
+    ],
+)
diff --git a/buck2/prelude/erlang/common_test/common/include/artifact_annotations.hrl b/buck2/prelude/erlang/common_test/common/include/artifact_annotations.hrl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/include/artifact_annotations.hrl
@@ -0,0 +1,11 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+
+-define(GENERIC_BLOB, 1).
+-define(GENERIC_TEXT_LOG, 2).
diff --git a/buck2/prelude/erlang/common_test/common/include/buck_ct_records.hrl b/buck2/prelude/erlang/common_test/common/include/buck_ct_records.hrl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/include/buck_ct_records.hrl
@@ -0,0 +1,62 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+
+-record(test_info, {
+    dependencies :: [file:filename()],
+    test_suite :: binary(),
+    config_files :: [file:filename_all()],
+    providers :: [{atom(), [term()]}],
+    ct_opts :: [term()],
+    erl_cmd :: [binary()],
+    extra_flags :: [binary()],
+    common_app_env :: #{binary() => binary()},
+    artifact_annotation_mfa :: artifact_annotations:annotation_function(),
+    raw_target :: binary(),
+    trampolines :: [binary()]
+}).
+
+-record(ct_test, {
+    suite :: module(),
+    groups :: [atom()],
+    test_name :: atom(),
+    canonical_name :: string()
+}).
+
+-record(test_env, {
+    suite :: module(),
+    tests :: [#ct_test{}],
+    suite_path :: file:filename_all(),
+    output_dir :: file:filename_all(),
+    dependencies :: [file:filename_all()],
+    test_spec_file :: file:filename_all(),
+    output_format :: xml | json,
+    config_files :: [file:filename_all()],
+    providers :: [{module(), [term()]}],
+    ct_opts :: [term()],
+    common_app_env :: #{binary() => binary()},
+    erl_cmd :: [binary()],
+    extra_flags :: [binary()],
+    artifact_annotation_mfa :: artifact_annotations:annotation_function(),
+    raw_target :: binary() | undefined,
+    trampolines :: [binary()],
+    timeout :: timeout(),
+    ct_stdout_fingerprint :: ct_stdout:fingerprint(),
+    ct_stdout_streaming :: output_to_stdout | no_output_to_stdout,
+    %% Receives {run_succeed | run_failed, Result, ProgressMarkersOffsets} when the CT run ends
+    result_recipient :: pid()
+}).
+
+-record(run_specs, {
+    mfa :: {function(), [term()]} | {atom(), atom(), [term()]},
+    timeout :: integer(),
+    schedulers :: integer(),
+    code_path = [] :: [file:filename()]
+}).
+
+-record(init_provider_state, {output_dir :: file:filename(), suite :: module(), raw_target :: binary()}).
diff --git a/buck2/prelude/erlang/common_test/common/include/tpx_records.hrl b/buck2/prelude/erlang/common_test/common/include/tpx_records.hrl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/include/tpx_records.hrl
@@ -0,0 +1,37 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+
+-record(test_spec_test_info, {
+    name :: binary(),
+    filter :: binary(),
+    breakpoint :: mfa()
+}).
+
+-record(test_spec_test_case, {
+    suite :: binary(),
+    testcases :: [#test_spec_test_info{}]
+}).
+
+-type optional(Type) :: undefined | Type.
+
+-record(test, {
+    name :: string(),
+    suite :: string(),
+    type :: string(),
+    message :: optional(string()),
+    stacktrace :: optional(string()),
+    stdout :: optional(string()),
+    stderr :: optional(string()),
+    time :: optional(integer())
+}).
+
+-record(test_case, {
+    name :: string(),
+    tests :: [#test{}]
+}).
diff --git a/buck2/prelude/erlang/common_test/common/src/artifact_annotations.erl b/buck2/prelude/erlang/common_test/common/src/artifact_annotations.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/src/artifact_annotations.erl
@@ -0,0 +1,79 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(artifact_annotations).
+-moduledoc """
+This file acts as a manual erlang sync for the thrift type struct
+TestResultArtifactAnnotations defined in  https://fburl.com/code/r2t4vclb
+
+ == How To Update This File ==
+We mostly expect next iterations of thrift data structure to include
+more testArtifactTypes. Those should be manually added to the
+test_artifact_type() here.
+""".
+-compile(warn_missing_spec_all).
+
+%% Public API
+-export([serialize/1, create_artifact_annotation/2, default_annotation/1, test_metrics_artifact_annotation/2]).
+-export_type([
+    annotation_function/0,
+    test_result_artifact_annotations/0
+]).
+
+-import(common_util, [unicode_characters_to_binary/1]).
+
+-include_lib("common/include/buck_ct_records.hrl").
+
+-type generic_blob() :: #{generic_blob := #{}}.
+-type generic_text_log() :: #{generic_text_log := #{}}.
+-type test_artifact_type() :: generic_blob() | generic_text_log().
+
+-type test_result_artifact_annotations() :: #{
+    type := test_artifact_type(),
+    description := binary(),
+    % The `test_case` is matched against on the tpx side to attach artifacts related
+    % to a particular `test_case`. If the `test_case` field is missing,
+    % the artifact will be attached to all the test cases run.
+    test_case => binary()
+}.
+
+-type annotation_function() :: fun((file:filename()) -> test_result_artifact_annotations()).
+
+-spec serialize(test_result_artifact_annotations()) -> iodata().
+serialize(ArtifactAnnotation) -> json:encode(ArtifactAnnotation).
+
+-spec create_artifact_annotation(FileName, AnnotationFunction) -> test_result_artifact_annotations() when
+    FileName :: file:filename(),
+    AnnotationFunction :: annotation_function().
+create_artifact_annotation(FileName, AnnotationFunction) ->
+    AnnotationFunction(FileName).
+
+-spec default_annotation(FileName :: file:filename()) -> test_result_artifact_annotations().
+default_annotation(FileName) ->
+    Type =
+        case lists:member(filename:extension(FileName), [".json", ".html", ".log", ".spec", ".txt"]) of
+            true -> #{generic_text_log => #{}};
+            _ -> #{generic_blob => #{}}
+        end,
+    #{
+        type => Type,
+        description => unicode_characters_to_binary(FileName)
+    }.
+
+-spec test_metrics_artifact_annotation(file:filename(), nonempty_list(#ct_test{})) ->
+    test_result_artifact_annotations().
+test_metrics_artifact_annotation(FileName, Tests) ->
+    FirstTest = hd(Tests),
+    FirstTestName = unicode_characters_to_binary(
+        common_util:qualified_name(
+            lists:reverse(FirstTest#ct_test.groups),
+            FirstTest#ct_test.test_name
+        )
+    ),
+    % All tests share this artifact. Attach to first test only to prevent the Scuba uploader from uploading the same data multiple times.
+    #{type => #{generic_blob => #{}}, description => list_to_binary(FileName), test_case => FirstTestName}.
diff --git a/buck2/prelude/erlang/common_test/common/src/bounded_buffer.erl b/buck2/prelude/erlang/common_test/common/src/bounded_buffer.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/src/bounded_buffer.erl
@@ -0,0 +1,33 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(bounded_buffer).
+-moduledoc """
+A bounded FIFO queue
+""".
+-compile(warn_missing_spec_all).
+
+%% Public API
+-export([new/1, put/2, get_elements/1]).
+-export_type([buffer/1]).
+
+-opaque buffer(T) :: {{queue:queue(T), integer()}, integer(), boolean()}.
+
+-spec new(integer()) -> buffer(term()).
+new(MaxElements) -> {{queue:new(), 0}, MaxElements, false}.
+
+-spec put(buffer(T), T) -> buffer(T).
+put({{Queue, LenQueue}, MaxElements, Truncated}, Chars) when LenQueue < MaxElements ->
+    {{queue:in(Chars, Queue), LenQueue + 1}, MaxElements, Truncated};
+put({{Queue, LenQueue}, MaxElements, _Truncated} = _Buffer, Chars) when LenQueue == MaxElements ->
+    {_, NewQueue} = queue:out(Queue),
+    {{queue:in(Chars, NewQueue), LenQueue}, MaxElements, true}.
+
+-spec get_elements(buffer(T)) -> {[T], boolean()}.
+get_elements({{Queue, _LenQueue}, _MaxElements, Truncated}) ->
+    {queue:to_list(Queue), Truncated}.
diff --git a/buck2/prelude/erlang/common_test/common/src/buck_ct_parser.erl b/buck2/prelude/erlang/common_test/common/src/buck_ct_parser.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/src/buck_ct_parser.erl
@@ -0,0 +1,42 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(buck_ct_parser).
+-moduledoc """
+Utilities method to parse string args given to the test binary
+via user input.
+""".
+-compile(warn_missing_spec_all).
+
+-import(common_util, [unicode_characters_to_list/1]).
+
+%% Public API
+-export([parse_str/1]).
+
+-spec parse_str(unicode:chardata()) -> dynamic().
+parse_str(~"") ->
+    [];
+parse_str("") ->
+    [];
+parse_str(StrArgs) ->
+    try
+        {ok, Tokens, _} = erl_scan:string(unicode_characters_to_list([StrArgs, "."])),
+        erl_parse:parse_term(Tokens)
+    of
+        {ok, Term} ->
+            Term;
+        {error, Reason} ->
+            error(lists:flatten(io_lib:format("Error parsing StrArgs ~tp, Reason: ~tp", [StrArgs, Reason])))
+    catch
+        E:R:S ->
+            error(
+                lists:flatten(
+                    io_lib:format("Error parsing StrArgs ~tp, error ~ts", [StrArgs, erl_error:format_exception(E, R, S)])
+                )
+            )
+    end.
diff --git a/buck2/prelude/erlang/common_test/common/src/buck_ct_provider.erl b/buck2/prelude/erlang/common_test/common/src/buck_ct_provider.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/src/buck_ct_provider.erl
@@ -0,0 +1,175 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(buck_ct_provider).
+-moduledoc """
+behavior module defining callbacks for buck2 test providers
+""".
+-compile(warn_missing_spec_all).
+
+-export([
+    do_init/2,
+    do_pre_listing/1,
+    do_post_listing/1,
+    do_pre_running/1,
+    do_post_running/1,
+    do_terminate/1
+]).
+-optional_callbacks([
+    init/2, pre_listing/1, post_listing/1, pre_running/1, post_running/1, terminate/1
+]).
+
+-include("buck_ct_records.hrl").
+-include_lib("kernel/include/logger.hrl").
+
+-type state() :: term().
+
+-type return_type() :: {ok, state()} | {error, term()}.
+
+-type buck_ct_provider() :: {atom(), state()}.
+
+-type init_argument_type() :: any().
+
+% ------------------- Behaviors Callbacks -------------------------
+
+%%% Initialize the state of the provider
+-callback init(init_argument_type(), #init_provider_state{}) -> return_type().
+
+%%% Executed before listing and updates the state of the provider
+-callback pre_listing(state()) -> return_type().
+
+%%% Executed after listing and updatess the state of the provider
+-callback post_listing(state()) -> return_type().
+
+%%% Executed before running the tests and updates the state of the provider
+-callback pre_running(state()) -> return_type().
+
+%%% Executed after running the tests and updates the state of the provider
+-callback post_running(state()) -> return_type().
+
+%%% Executed as closing.
+-callback terminate(state()) -> return_type().
+
+% ------------------- Exported Methods -------------------------
+
+-doc """
+Handles calling the init method on providers.
+Calls the init method if this one is present and updates the state
+""".
+-spec do_init({atom(), init_argument_type()}, #init_provider_state{}) -> buck_ct_provider().
+do_init({ProviderName, Args}, InitState) ->
+    execute_method_on_provider(init, ProviderName, InitState, [Args]).
+
+-doc """
+Handles calling the pre_listing method on providers.
+Calls the pre_listing method if this one is present and updates the state.
+""".
+-spec do_pre_listing(buck_ct_provider()) -> buck_ct_provider().
+do_pre_listing({ProviderName, ProviderState}) ->
+    execute_method_on_provider(pre_listing, ProviderName, ProviderState, []).
+
+-doc """
+Handles calling the post_listing method on providers.
+Calls the post_listing method if this one is present and updates the state.
+""".
+-spec do_post_listing(buck_ct_provider()) -> buck_ct_provider().
+do_post_listing({ProviderName, ProviderState}) ->
+    execute_method_on_provider(post_listing, ProviderName, ProviderState, []).
+
+-doc """
+Handles calling the pre_running method on providers.
+Calls the pre_running method if this one is present and updates the state.
+""".
+-spec do_pre_running(buck_ct_provider()) -> buck_ct_provider().
+do_pre_running({ProviderName, ProviderState}) ->
+    execute_method_on_provider(pre_running, ProviderName, ProviderState, []).
+
+-doc """
+Handles calling the post_running method on providers.
+Calls the post_running method if this one is present and updates the state
+""".
+-spec do_post_running(buck_ct_provider()) -> buck_ct_provider().
+do_post_running({ProviderName, ProviderState}) ->
+    execute_method_on_provider(post_running, ProviderName, ProviderState, []).
+
+-doc """
+Handles calling the terminate method on providers.
+Calls the terminate method if this one is present and updates the state.
+""".
+-spec do_terminate(buck_ct_provider()) -> buck_ct_provider().
+do_terminate({ProviderName, ProviderState}) ->
+    execute_method_on_provider(terminate, ProviderName, ProviderState, []).
+
+% ------------------- Helpers Methods -------------------------
+
+-doc """
+Handles the execution of the method on a provider and dealing with the result.
+Skip if the method is undefined, updates the state or crash according to the return result
+of the method.
+""".
+-spec execute_method_on_provider(atom(), atom(), any(), [any()]) -> {atom(), term()}.
+execute_method_on_provider(Method, ProviderName, ProviderState, Args) ->
+    try safely_execute(ProviderName, Method, Args ++ [ProviderState]) of
+        undefined_method ->
+            State =
+                case Method of
+                    init -> #{};
+                    _ -> ProviderState
+                end,
+            {ProviderName, State};
+        {ok, NewState} ->
+            {ProviderName, NewState};
+        {error, Reason} ->
+            ErrorMsg = unicode:characters_to_list(
+                io_lib:format(
+                    "Method ~tp on provider ~tp with state ~tp ~n returned with error ~tp ~n", [
+                        Method, ProviderName, ProviderState, Reason
+                    ]
+                )
+            ),
+            ?LOG_ERROR(ErrorMsg),
+            throw({error_in_provider, {ProviderName, Reason}});
+        OtherReturn ->
+            case Method of
+                terminate ->
+                    {ProviderName, ProviderState};
+                _ ->
+                    ?LOG_DEBUG(
+                        "Method ~tp on provider ~tp with state ~tp ~n returned with an unexpected return ~tp ~n",
+                        [
+                            Method, ProviderName, ProviderState, OtherReturn
+                        ]
+                    ),
+                    {ProviderName, ProviderState}
+            end
+    catch
+        Class:Reason:StackTrace ->
+            ErrorMsg = unicode:characters_to_list(
+                io_lib:format("Method ~tp on provider ~tp with state ~tp ~n ~ts ~n", [
+                    Method,
+                    ProviderName,
+                    ProviderState,
+                    erl_error:format_exception(Class, Reason, StackTrace)
+                ])
+            ),
+            ?LOG_ERROR(ErrorMsg),
+            throw({crash_in_provider, {Class, Reason, StackTrace}})
+    end.
+
+-doc """
+Executes the method if this one is exported, otherwise return undefined_method.
+""".
+-spec safely_execute(atom(), atom(), [any()]) -> undefined_method | any().
+safely_execute(Module, Method, Args) ->
+    Module:module_info(),
+    case erlang:function_exported(Module, Method, length(Args)) of
+        false ->
+            undefined_method;
+        true ->
+            apply(Module, Method, Args)
+    end.
diff --git a/buck2/prelude/erlang/common_test/common/src/common_util.erl b/buck2/prelude/erlang/common_test/common/src/common_util.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/src/common_util.erl
@@ -0,0 +1,86 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% % @format
+-module(common_util).
+-compile(warn_missing_spec_all).
+
+-export([
+    unicode_characters_to_list/1,
+    unicode_characters_to_binary/1,
+
+    qualified_name/2,
+    parse_test_name/2,
+
+    filename_all_to_filename/1,
+
+    get_env/1,
+    set_env/2
+]).
+
+-include_lib("common/include/buck_ct_records.hrl").
+
+-spec unicode_characters_to_list(unicode:chardata()) -> string().
+unicode_characters_to_list(CharData) ->
+    case unicode:characters_to_list(CharData) of
+        R when not is_tuple(R) -> R
+    end.
+
+-doc """
+Gets the name for a testcase in a given group-path
+The groups order expected here is [leaf_group, ...., root_group]
+""".
+-spec qualified_name(Groups, TestCase) -> string() when
+    Groups :: [atom()],
+    TestCase :: string() | atom().
+qualified_name(Groups, TestCase) ->
+    StringGroups = [atom_to_list(Group) || Group <- Groups],
+    JoinedGroups = string:join(lists:reverse(StringGroups), ":"),
+    Raw = io_lib:format("~ts.~ts", [JoinedGroups, TestCase]),
+    unicode_characters_to_list(Raw).
+
+-doc """
+Parse the test name, and decompose it into the test, group and suite atoms
+""".
+-spec parse_test_name(string(), atom()) -> #ct_test{}.
+parse_test_name(Test, Suite) ->
+    [Groups0, TestName] = string:split(Test, ".", all),
+    Groups1 =
+        case Groups0 of
+            [] -> [];
+            _ -> string:split(Groups0, ":", all)
+        end,
+    Groups = [list_to_atom(GroupStr) || GroupStr <:- Groups1],
+    #ct_test{
+        suite = Suite,
+        groups = Groups,
+        test_name = list_to_atom(TestName),
+        canonical_name = Test
+    }.
+
+-spec unicode_characters_to_binary(unicode:chardata()) -> binary().
+unicode_characters_to_binary(Chars) ->
+    case unicode:characters_to_binary(Chars) of
+        Bin when is_binary(Bin) -> Bin
+    end.
+
+-spec filename_all_to_filename(file:filename_all()) -> file:filename().
+filename_all_to_filename(Filename) when is_binary(Filename) ->
+    unicode_characters_to_list(Filename);
+filename_all_to_filename(Filename) ->
+    Filename.
+
+%% Accessors for the `common` application's environment. Kept here so that
+%% callers in other apps (e.g. `ct_executor` in the `test_exec` app) do not read
+%% the `common` app's env directly across an app boundary (W0011).
+-spec get_env(atom()) -> undefined | {ok, dynamic()}.
+get_env(Key) ->
+    application:get_env(common, Key).
+
+-spec set_env(atom(), term()) -> ok.
+set_env(Key, Value) ->
+    application:set_env(common, Key, Value).
diff --git a/buck2/prelude/erlang/common_test/common/src/ct_error_printer.erl b/buck2/prelude/erlang/common_test/common/src/ct_error_printer.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/src/ct_error_printer.erl
@@ -0,0 +1,303 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_error_printer).
+-moduledoc """
+Helper module to format errors arising from common_test executions,
+in particular as generated by the assert.hrl module.
+""".
+-compile([warn_missing_spec_all]).
+
+%% Public API
+-export([format_error/2, format_error/3, format_reason/1]).
+
+-import(common_util, [unicode_characters_to_binary/1, unicode_characters_to_list/1]).
+
+-spec format_error(term(), boolean()) -> unicode:chardata().
+format_error(Reason, FormatStackTrace) ->
+    format_error(error, Reason, FormatStackTrace).
+
+-spec format_error(ErrorType, Reason, FormatStackTrace) -> unicode:chardata() when
+    ErrorType :: error | exit | throw,
+    Reason :: term(),
+    FormatStackTrace :: boolean().
+format_error(_ErrType, {'EXIT', Reason}, FormatStackTrace) ->
+    format_error(Reason, FormatStackTrace);
+format_error(ErrType, Err = {Reason, StackTrace}, true) when is_list(StackTrace) ->
+    case format_reason(Err) of
+        {ok, Output} ->
+            ErrReason =
+                case Reason of
+                    {Type, _} -> Type;
+                    _ -> exception
+                end,
+            ["\n", Output, erl_error:format_exception(ErrType, ErrReason, StackTrace)];
+        unrecognized_error ->
+            erl_error:format_exception(ErrType, Reason, StackTrace)
+    end;
+format_error(ErrType, Reason, true) ->
+    format_error(ErrType, Reason, false);
+format_error(ErrType, Reason, false) ->
+    case format_reason(Reason) of
+        {ok, Output} ->
+            Output;
+        unrecognized_error ->
+            erl_error:format_exception(ErrType, Reason, [])
+    end.
+
+-spec format_reason(term()) -> {ok, unicode:chardata()} | unrecognized_error.
+format_reason(Reason) ->
+    blame_reason(Reason),
+    {_, Result} = lists:foldl(
+        fun try_format_if_necessary/2,
+        {Reason, unrecognized_error},
+        [
+            fun maybe_custom_format/1,
+            fun maybe_proper_format/1,
+            fun maybe_assert_format/1
+        ]
+    ),
+    Result.
+
+-spec try_format_if_necessary(Formatter, Acc) -> Acc when
+    Formatter :: fun((Reason) -> {ok, unicode:chardata()} | unrecognized_error),
+    Acc :: {Reason, {ok, unicode:chardata()} | unrecognized_error},
+    Reason :: term().
+try_format_if_necessary(_Formatter, Acc = {_, {ok, _}}) -> Acc;
+try_format_if_necessary(Formatter, {Reason, _Err}) -> {Reason, Formatter(Reason)}.
+
+-spec blame_reason(term()) -> ok.
+blame_reason({Reason, StackTrace}) ->
+    try
+        case application:get_env(common, exception_blame) of
+            undefined ->
+                ok;
+            {ok, Blame} when is_atom(Blame) ->
+                Blame:format_blame(Reason, StackTrace)
+        end
+    catch
+        C:E:S ->
+            io:format("Error: ~ts", [erl_error:format_exception(C, E, S)])
+    end;
+blame_reason(_Reason) ->
+    ok.
+
+-spec maybe_custom_format(term()) -> unrecognized_error | {ok, unicode:chardata()}.
+maybe_custom_format({{Type, Props}, StackTrace}) when is_atom(Type), is_list(Props) ->
+    try proplists:to_map(Props) of
+        PropsMap -> maybe_custom_format({{Type, PropsMap}, StackTrace})
+    catch
+        _:_:_ -> unrecognized_error
+    end;
+maybe_custom_format({{Type, Props = #{formatter := Formatter}}, _StackTrace}) when is_atom(Formatter) ->
+    try
+        Formatter:format_assert(Type, Props)
+    catch
+        E:R:ST ->
+            {ok, [
+                io_lib:format(
+                    "unexpected error when formatting assertion: ~n"
+                    "~ts~n",
+                    [erl_error:format_exception(E, R, ST)]
+                ),
+                io_lib:format("original assertion: ~n" "~tp~n", [{Type, Props}])
+            ]}
+    end;
+maybe_custom_format(_Reason) ->
+    unrecognized_error.
+
+-spec maybe_assert_format(term()) -> unrecognized_error | {ok, unicode:chardata()}.
+maybe_assert_format({{Type, Props}, _StackTrace}) -> format_assert(Type, Props);
+maybe_assert_format(_Reason) -> unrecognized_error.
+
+-doc """
+Try to correctly format an error arising from a
+failed assertion, see
+https://github.com/erlang/otp/blob/master/bootstrap/lib/stdlib/include/assert.hrl
+for the different type of errors raised depending of which macro was used.
+""".
+-spec format_assert(term(), term()) -> unrecognized_error | {ok, unicode:chardata()}.
+format_assert(Type, Props) when is_list(Props) andalso is_atom(Type) ->
+    try proplists:to_map(Props) of
+        Map -> format_assert0(Type, Map)
+    catch
+        _:_:_ -> unrecognized_error
+    end;
+format_assert(_Type, _Props) ->
+    unrecognized_error.
+
+% For this macro to work we expect as local variable
+% Type, Module, Line and Props
+-define(FORMAT_ASSERTION(Format, Expressions, SpecificExpressions),
+    {ok, [
+        print_type_expression(Type, Format, Expressions),
+        print_location(Module, Line),
+        SpecificExpressions,
+        print_comments(
+            Props, string:chr(unicode_characters_to_list(lists:nth(1, SpecificExpressions)), $:)
+        )
+    ]}
+).
+
+-spec format_assert0(atom(), map()) -> unrecognized_error | {ok, unicode:chardata()}.
+format_assert0(
+    assert = Type,
+    #{not_boolean := Value} = Props
+) ->
+    NewProps = maps:remove(not_boolean, Props),
+    format_assert0(Type, NewProps#{value => Value});
+format_assert0(
+    assert = Type1,
+    #{
+        line := Line,
+        module := Module,
+        expression := Expression,
+        expected := Expected,
+        value := Value
+    } = Props
+) ->
+    % assertNot as formatted as assert, so we need to debug that here.
+    Type =
+        case Expected of
+            true -> Type1;
+            false -> assertNot
+        end,
+    ?FORMAT_ASSERTION(
+        "~ts",
+        [Expression],
+        [
+            io_lib:format("   expected: ~tp~n", [Expected]),
+            io_lib:format("        got: ~tp~n", [Value])
+        ]
+    );
+format_assert0(
+    assertEqual = Type,
+    #{
+        line := Line,
+        module := Module,
+        expression := Expression,
+        expected := Expected,
+        value := Value
+    } = Props
+) ->
+    ?FORMAT_ASSERTION(
+        "~0tp, ~ts",
+        [Expected, Expression],
+        [
+            io_lib:format("   expected: ~tp~n", [Expected]),
+            io_lib:format("        got: ~tp~n", [Value])
+        ]
+    );
+format_assert0(
+    Type,
+    #{line := Line, module := Module, expression := Expression, pattern := Pattern, value := Value} =
+        Props
+) when
+    Type =:= assertMatch orelse Type =:= assertNotMatch
+->
+    ?FORMAT_ASSERTION(
+        "~ts, ~ts",
+        [Pattern, Expression],
+        [
+            case Type of
+                assertMatch ->
+                    io_lib:format("     expected: ~ts~n", [Pattern]);
+                assertNotMatch ->
+                    io_lib:format(" expected not: ~ts~n", [Pattern])
+            end,
+            io_lib:format("          got: ~tp~n", [Value])
+        ]
+    );
+format_assert0(
+    assertNotEqual = Type,
+    #{line := Line, module := Module, expression := Expression, value := Value} = Props
+) ->
+    ?FORMAT_ASSERTION(
+        "~tp, ~ts",
+        [Value, Expression],
+        [
+            io_lib:format(" expected not: ~tp~n", [Value]),
+            io_lib:format("          got: ~tp~n", [Value])
+        ]
+    );
+format_assert0(
+    assertException = Type,
+    #{module := Module, line := Line, expression := Expression, pattern := Pattern} = Props
+) ->
+    ValueLine =
+        case Props of
+            #{unexpected_success := Value} ->
+                io_lib:format("          got value: ~tp~n", [Value]);
+            #{unexpected_exception := {Class, Reason, StackTrace} = _Exception} ->
+                io_lib:format(
+                    "      got exception: ~tp ~n",
+                    [{Class, Reason, StackTrace}]
+                );
+            _ ->
+                unrecognized_error
+        end,
+    case ValueLine of
+        unrecognized_error ->
+            ValueLine;
+        _ ->
+            ?FORMAT_ASSERTION(
+                "~ts, ~tp",
+                [Pattern, Expression],
+                [
+                    io_lib:format(" expected exception: ~ts~n", [Pattern]),
+                    ValueLine
+                ]
+            )
+    end;
+format_assert0(
+    assertNotException = Type,
+    #{
+        module := Module,
+        line := Line,
+        expression := Expression,
+        pattern := Pattern,
+        unexpected_exception := {Class, Reason, StackTrace}
+    } = Props
+) ->
+    ?FORMAT_ASSERTION(
+        "~tp",
+        [Expression],
+        [
+            io_lib:format(" expected no exception: ~tp~n", [Pattern]),
+            io_lib:format("         got exception: ~ts~n", [
+                erl_error:format_exception(Class, Reason, StackTrace)
+            ])
+        ]
+    );
+format_assert0(_Type, _Props) ->
+    unrecognized_error.
+
+-spec print_type_expression(atom(), string(), [term()]) -> unicode:chardata().
+print_type_expression(Type, Format, Args) ->
+    FormatStr = unicode_characters_to_binary(io_lib:format("Failure ?~tp(~ts)", [Type, Format])),
+    io_lib:format(FormatStr, Args).
+
+-spec print_location(atom(), integer()) -> unicode:chardata().
+print_location(Module, Line) ->
+    io_lib:format(" in ~tp.erl:~tp~n", [Module, Line]).
+
+-spec print_comments(map(), integer()) -> unicode:chardata().
+print_comments(#{comment := Comment}, Width) ->
+    [io_lib:format("~*.. s ~tp~n", [Width, "comment:", Comment])];
+print_comments(_Map, _Width) ->
+    [].
+
+-spec maybe_proper_format(term()) -> unrecognized_error | {ok, unicode:chardata()}.
+maybe_proper_format({{property_failed, Property, Counterexample}, _ST}) ->
+    {ok,
+        io_lib:format(
+            "Property ~ts failed with Counterexample: ~n~tp~n",
+            [Property, Counterexample]
+        )};
+maybe_proper_format(_) ->
+    unrecognized_error.
diff --git a/buck2/prelude/erlang/common_test/common/src/ct_stdout.erl b/buck2/prelude/erlang/common_test/common/src/ct_stdout.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/src/ct_stdout.erl
@@ -0,0 +1,363 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_stdout).
+-moduledoc """
+Functions to work with the stdout of a Common Test, for example
+to delimit the output of each test-case.
+""".
+-compile(warn_missing_spec_all).
+
+-export([filename/0, filename/1]).
+-export([make_fingerprint/0]).
+-export([emit_progress/4]).
+-export([process_raw_stdout_log/3, collect_method_stdout/4]).
+-export([init_process_stdout_state/3, process_stdout_line/2]).
+-export_type([progress/0, callback/0, progress_line/0, offset/0, fingerprint/0, collected_stdout/0]).
+-export_type([process_stdout_state/0]).
+
+-import(common_util, [unicode_characters_to_binary/1]).
+
+-define(UNICODE_REPLACEMENT_CHAR_UTF8, ~"�").
+
+%% ---------------------------------------------------------------------------
+%% Types
+%% ---------------------------------------------------------------------------
+
+-type progress() :: started | finished.
+-type callback() :: init_per | end_per.
+-type progress_line() :: binary().
+-type offset() :: integer().
+
+-doc """
+A marker that is included on every progress line and can be used to distinguish such
+markers among the rest of the stdout.
+""".
+-type fingerprint() :: binary().
+
+-doc """
+Mapping from a "start" marker to the stdout contents associated to that marker.
+""".
+-type collected_stdout() :: #{
+    progress_line() => binary() | {truncated, binary()}
+}.
+
+-type process_stdout_state() :: #{
+    fingerprint := fingerprint(),
+    out_handle := file:fd(),
+    write_to_stdout := boolean(),
+    progress_markers_seen := #{progress_line() => offset()},
+    has_pending_new_line := boolean(),
+    pending_progress_marker := [binary()]
+}.
+
+%% ---------------------------------------------------------------------------
+%% Public API
+%% ---------------------------------------------------------------------------
+
+-doc """
+Filename of the CT stdout log file that will be returned to the user.
+""".
+-spec filename() -> file:filename_all().
+filename() ->
+    ~"ct_stdout.txt".
+
+-doc """
+Like `m:filename/0` but will prefix the given `OutputDir`.
+""".
+-spec filename(OutputDir) -> file:filename_all() when
+    OutputDir :: file:filename_all().
+filename(OutputDir) ->
+    filename:join(OutputDir, filename()).
+
+-spec make_fingerprint() -> fingerprint().
+make_fingerprint() ->
+    base64:encode(crypto:strong_rand_bytes(24)).
+
+-doc """
+Emit a unique line to stdout to mark the start/end of a ct_suite callback.
+
+The logged line is returned so the relevant offset in the stdout file can later be found.
+
+NB. `UserProcess` is expected to be the `user` process, but we demand an
+explicit (cached) version, in case testcases mess with this process
+""".
+-spec emit_progress(UserProcess, Fingerprint, What, Progress) -> progress_line() when
+    UserProcess :: pid(),
+    Fingerprint :: fingerprint(),
+    What :: unicode:chardata(),
+    Progress :: progress().
+emit_progress(UserProcess, Fingerprint, What, Progress) ->
+    ProgressStr =
+        case Progress of
+            started -> ~"START";
+            finished -> ~"END"
+        end,
+    Uniq = erlang:unique_integer([positive]),
+    ProgressLine = unicode_characters_to_binary(
+        io_lib:format(~"~ts[~ts] ~ts ~ts [~tp]", [Fingerprint, timestamp_str(), ProgressStr, What, Uniq])
+    ),
+
+    % NB. We emit a leading newling in case the last print statement
+    % didn't finish the line. We'll manually remove it, if necessary when
+    % processing the markers
+    io:format(UserProcess, "~n~s~n", [ProgressLine]),
+
+    ProgressLine.
+
+-doc """
+The returned value contains the collected stdout for each "start" marker, capped to
+the last `MaxPerCollected` bytes.
+""".
+-spec collect_method_stdout(OutputFile, Offsets, TreeResults, MaxPerCollected) -> {ok, collected_stdout()} when
+    OutputFile :: file:filename_all(),
+    Offsets :: #{progress_line() => offset()},
+    TreeResults :: cth_tpx_test_tree:tree(),
+    MaxPerCollected :: non_neg_integer().
+collect_method_stdout(OutputFile, Offsets, TreeResults, MaxPerCollected) ->
+    MethodResults = get_method_results(TreeResults),
+    {ok, InH} = file:open(OutputFile, [raw, binary, read, read_ahead]),
+    try
+        {ok,
+            #{
+                Start => collect_stdout(InH, StartOffset, EndOffset, MaxPerCollected)
+             || #{start_progress_marker := Start, end_progress_marker := End} <- MethodResults,
+                #{Start := StartOffset, End := EndOffset} <- [Offsets]
+            }}
+    after
+        file:close(InH)
+    end.
+
+-doc """
+Writes to `OutputFile` a copy of `RawStdoutFile` where all progress markers
+have been removed.
+
+The returned value contains the offset in `OutputFile` for each progress marker seen.
+""".
+-spec process_raw_stdout_log(Fingerprint, RawStdoutFile, OutputFile) -> {ok, #{progress_line() => offset()}} when
+    Fingerprint :: fingerprint(),
+    RawStdoutFile :: file:filename_all(),
+    OutputFile :: file:filename_all().
+process_raw_stdout_log(Fingerprint, RawStdoutFile, OutputFile) ->
+    {ok, InHandle} = file:open(RawStdoutFile, [raw, binary, read, read_ahead]),
+
+    State = init_process_stdout_state(Fingerprint, OutputFile, no_output_to_stdout),
+    try
+        {ok, process_raw_stdout_log_loop(InHandle, State)}
+    after
+        file:close(InHandle)
+    end.
+
+-spec init_process_stdout_state(Fingerprint, OutputFile, StdOutput) -> process_stdout_state() when
+    Fingerprint :: fingerprint(),
+    OutputFile :: file:filename_all(),
+    StdOutput :: output_to_stdout | no_output_to_stdout.
+init_process_stdout_state(Fingerprint, OutputFile, StdOutOutput) ->
+    {ok, OutHandle} = file:open(OutputFile, [raw, write, delayed_write]),
+    WriteToStdout =
+        case StdOutOutput of
+            output_to_stdout -> true;
+            no_output_to_stdout -> false
+        end,
+    #{
+        fingerprint => Fingerprint,
+        out_handle => OutHandle,
+        write_to_stdout => WriteToStdout,
+        progress_markers_seen => #{},
+        has_pending_new_line => false,
+        pending_progress_marker => []
+    }.
+
+-spec process_stdout_line
+    (eof, State) -> {eof, #{progress_line() => offset()}} when
+        State :: process_stdout_state();
+    ({eol | noeol, Line}, State0) -> {ok, State1} when
+        Line :: binary(),
+        State0 :: process_stdout_state(),
+        State1 :: process_stdout_state().
+process_stdout_line(eof, State0) ->
+    State1 = flush_pending_newline(State0),
+    #{out_handle := OutH, progress_markers_seen := Result} = State1,
+    file:close(OutH),
+    {eof, Result};
+process_stdout_line({eol, Line}, State0) ->
+    {ok, process_stdout_line_aux(eol, Line, State0)};
+process_stdout_line({noeol, Line}, State0) ->
+    {ok, process_stdout_line_aux(noeol, Line, State0)}.
+
+%% ---------------------------------------------------------------------------
+%% Helpers
+%% ---------------------------------------------------------------------------
+
+-spec timestamp_str() -> unicode:chardata().
+timestamp_str() ->
+    T = erlang:system_time(millisecond),
+    calendar:system_time_to_rfc3339(T, [{unit, millisecond}, {time_designator, $\s}]).
+
+-spec get_method_results(TreeResults) -> [cth_tpx_test_tree:method_result()] when
+    TreeResults :: cth_tpx_test_tree:tree().
+get_method_results(TreeResults) ->
+    lists:flatten(get_method_results(TreeResults, [])).
+
+-spec get_method_results(TreeResults, Acc) -> Acc when
+    TreeResults :: cth_tpx_test_tree:tree() | [cth_tpx_test_tree:tree()],
+    Acc :: [[cth_tpx_test_tree:method_result()]].
+get_method_results([], Acc) ->
+    Acc;
+get_method_results([First | Rest], Acc0) ->
+    Acc1 = get_method_results(First, Acc0),
+    get_method_results(Rest, Acc1);
+get_method_results(Leaf = #{type := leaf}, Acc) ->
+    #{init_method := Init, main_method := Main, end_method := End} = Leaf,
+    [filter_none([Init, Main, End]) | Acc];
+get_method_results(Node = #{type := node}, Acc0) ->
+    #{init_method := Init, end_method := End, test_cases := TestCases, sub_groups := SubGroups} = Node,
+    Acc1 = [filter_none([Init, End]) | Acc0],
+    Acc2 = get_method_results(maps:values(TestCases), Acc1),
+    Acc3 = get_method_results(maps:values(SubGroups), Acc2),
+    Acc3.
+
+-spec filter_none([none | A]) -> [A].
+filter_none([]) -> [];
+filter_none([none | As]) -> filter_none(As);
+filter_none([A | As]) when A /= none -> [A | filter_none(As)].
+
+-spec process_raw_stdout_log_loop(InH, State) -> #{progress_line() => offset()} when
+    InH :: file:fd(),
+    State :: process_stdout_state().
+process_raw_stdout_log_loop(InH, State0) ->
+    case file:read_line(InH) of
+        eof ->
+            {eof, Result} = process_stdout_line(eof, State0),
+            Result;
+        {ok, Line} when is_binary(Line) ->
+            <<Line1:(byte_size(Line) - 1)/binary, "\n">> = Line,
+            {ok, State1} = process_stdout_line({eol, Line1}, State0),
+            process_raw_stdout_log_loop(InH, State1)
+    end.
+
+-spec process_stdout_line_aux(Eol, Line, State0) -> State1 when
+    Eol :: eol | noeol,
+    Line :: binary(),
+    State0 :: process_stdout_state(),
+    State1 :: process_stdout_state().
+process_stdout_line_aux(noeol, Line, State0 = #{pending_progress_marker := Chunks = [_ | _]}) ->
+    % A progress marker split on several chunks, here's a new, non-terminal chunk
+    State0#{pending_progress_marker := [Line | Chunks]};
+process_stdout_line_aux(eol, Line, State0 = #{pending_progress_marker := Chunks = [_ | _]}) ->
+    % A progress marker split on several chunks, here's the last chunk
+    ProgressLine = unicode_characters_to_binary(lists:reverse([Line | Chunks])),
+    State1 = State0#{pending_progress_marker => []},
+    process_stdout_line_aux(eol, ProgressLine, State1);
+process_stdout_line_aux(Eol, Line, State0) ->
+    #{fingerprint := Fingerprint} = State0,
+    case Line of
+        <<Fingerprint:(byte_size(Fingerprint))/binary, _/binary>> when Eol =:= noeol ->
+            % A progress marker split on several chunks, here's the first chunk
+            State0#{pending_progress_marker => [Line]};
+        <<Fingerprint:(byte_size(Fingerprint))/binary, _/binary>> ->
+            #{out_handle := OutH, progress_markers_seen := Acc} = State0,
+            {ok, Offset} = file:position(OutH, cur),
+            Acc1 = Acc#{Line => Offset},
+            State1 = State0#{progress_markers_seen => Acc1, has_pending_new_line => false},
+            State1;
+        ~"" when Eol =:= eol ->
+            % This could be the leading newline of a marker, so postpone until we are sure. However
+            State1 = flush_pending_newline(State0),
+            State2 = State1#{has_pending_new_line => true},
+            State2;
+        _ when Eol =:= eol ->
+            State1 = log_stdout([Line, ~"\n"], State0),
+            State1;
+        _ ->
+            State1 = log_stdout(Line, State0),
+            State1
+    end.
+
+-spec flush_pending_newline(State0) -> State1 when
+    State0 :: process_stdout_state(),
+    State1 :: process_stdout_state().
+flush_pending_newline(State0) ->
+    log_stdout([], State0).
+
+-spec log_stdout(Chars, State0) -> State1 when
+    Chars :: unicode:chardata(),
+    State0 :: process_stdout_state(),
+    State1 :: process_stdout_state().
+log_stdout(Chars, State0) ->
+    {Chars1, State1} =
+        case State0 of
+            #{has_pending_new_line := true} ->
+                {[~"\n", Chars], State0#{has_pending_new_line => false}};
+            _ ->
+                {Chars, State0}
+        end,
+    case Chars1 of
+        [] ->
+            ok;
+        ~"" ->
+            ok;
+        _ ->
+            #{out_handle := OutH, write_to_stdout := WriteToStdout} = State0,
+            file:write(OutH, Chars1),
+            not WriteToStdout orelse io:put_chars(Chars1)
+    end,
+    State1.
+
+-spec collect_stdout(InH, StartOffset, EndOffset, Max) -> binary() | {truncated, binary()} when
+    InH :: file:fd(),
+    StartOffset :: offset(),
+    EndOffset :: offset(),
+    Max :: non_neg_integer().
+collect_stdout(_InH, StartOffset, EndOffset, _Max) when StartOffset =:= EndOffset ->
+    ~"";
+collect_stdout(InH, StartOffset, EndOffset, Max) when StartOffset < EndOffset ->
+    Count = EndOffset - StartOffset,
+    case Count =< Max of
+        true ->
+            case file:pread(InH, StartOffset, Count) of
+                {ok, Result} when is_binary(Result) -> fix_unicode_encoding(Result)
+            end;
+        false ->
+            First1 = EndOffset - Max,
+            Count1 = Max,
+            case file:pread(InH, First1, Count1) of
+                {ok, Result} when is_binary(Result) ->
+                    % Collected stdout is rendered and serialized as UTF-8.
+                    % Sanitize before returning because truncation may start
+                    % in the middle of a codepoint and tests may also emit
+                    % arbitrary raw bytes.
+                    {truncated, fix_unicode_encoding(Result)}
+            end
+    end.
+
+-spec fix_unicode_encoding(binary()) -> binary().
+fix_unicode_encoding(Bin) ->
+    case unicode:characters_to_binary(Bin) of
+        Ok when is_binary(Ok) -> Ok;
+        {error, Prefix, Rest0} ->
+            Rest = drop_invalid_utf8_prefix(require_binary(Rest0)),
+            iolist_to_binary([Prefix, ?UNICODE_REPLACEMENT_CHAR_UTF8, fix_unicode_encoding(Rest)]);
+        {incomplete, Prefix, _Rest} ->
+            iolist_to_binary([Prefix, ?UNICODE_REPLACEMENT_CHAR_UTF8])
+    end.
+
+-spec require_binary(unicode:latin1_chardata() | unicode:chardata() | unicode:external_chardata()) -> binary().
+require_binary(Bin) when is_binary(Bin) ->
+    Bin.
+
+-spec drop_invalid_utf8_prefix(binary()) -> binary().
+drop_invalid_utf8_prefix(Bin) ->
+    case unicode:characters_to_binary(Bin) of
+        {error, ~"", <<_:8, Rest/binary>>} ->
+            drop_invalid_utf8_prefix(Rest);
+        {incomplete, ~"", _Rest} ->
+            ~"";
+        _ ->
+            Bin
+    end.
diff --git a/buck2/prelude/erlang/common_test/common/src/list_test.erl b/buck2/prelude/erlang/common_test/common/src/list_test.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/src/list_test.erl
@@ -0,0 +1,245 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(list_test).
+-compile(warn_missing_spec_all).
+
+-export([list_tests/2]).
+
+-include_lib("common/include/tpx_records.hrl").
+
+-import(common_util, [unicode_characters_to_binary/1]).
+
+-type ct_groupname() :: ct_suite:ct_groupname().
+-type ct_testname() :: ct_suite:ct_testname().
+-type suite() :: module().
+
+%% coming from the output of the group/0 method.
+%% See https://www.erlang.org/doc/man/ct_suite.html#Module:groups-0 for the upstream type.
+-type groups_output() :: [ct_group_def()].
+-type ct_group_def() ::
+    {ct_groupname(), ct_group_props(), [ct_group_content()]}
+    | {ct_groupname(), [ct_group_content()]}.
+-type ct_group_content() :: ct_testname() | ct_group_def() | {group, ct_groupname()} | ct_testcase_ref().
+
+%% coming from the output of the all/0 method.
+%% See https://www.erlang.org/doc/man/ct_suite.html#Module:all-0 for the upstream type.
+-type all_output() :: [ct_test_def()].
+-type ct_test_def() :: ct_testname() | ct_group_ref() | ct_testcase_ref().
+-type ct_testcase_ref() :: {testcase, ct_testname(), ct_testcase_repeat_prop()}.
+-type ct_testcase_repeat_prop() :: [
+    {repeat, ct_test_repeat()}
+    | {repeat_until_ok, ct_test_repeat()}
+    | {repeat_until_fail, ct_test_repeat()}
+].
+-type ct_group_ref() ::
+    {group, ct_groupname()}
+    | {group, ct_groupname(), ct_group_props_ref()}
+    | {group, ct_groupname(), ct_group_props_ref(), ct_subgroups_def()}.
+-type ct_group_props_ref() :: ct_group_props() | default.
+-type ct_group_props() ::
+    [
+        parallel
+        | sequence
+        | shuffle
+        | {shuffle, Seed :: {integer(), integer(), integer()}}
+        | {ct_group_repeat_type(), ct_test_repeat()}
+    ].
+-type ct_group_repeat_type() ::
+    repeat
+    | repeat_until_all_ok
+    | repeat_until_all_fail
+    | repeat_until_any_ok
+    | repeat_until_any_fail.
+-type ct_test_repeat() :: integer() | forever.
+-type ct_subgroups_def() ::
+    {ct_groupname(), ct_group_props_ref()}
+    | {ct_groupname(), ct_group_props_ref(), ct_subgroups_def()}.
+
+%% ------ Public Function --------
+
+-doc """
+Generates a list of tests, suitable for test runners like TPX
+""".
+-spec list_tests(Suite, Hooks) -> #test_spec_test_case{} when
+    Suite :: suite(),
+    Hooks :: [module()].
+list_tests(Suite, Hooks) ->
+    TestCases = list_test_spec(Suite, Hooks),
+    throw_if_duplicate(TestCases),
+    #test_spec_test_case{
+        suite = atom_to_binary(Suite),
+        testcases = TestCases
+    }.
+
+%% -------------- Internal functions ----------------
+%%
+%%
+-spec throw_if_duplicate([#test_spec_test_info{}]) -> ok.
+throw_if_duplicate(TestCaseInfos) ->
+    throw_if_duplicate(sets:new([{version, 2}]), TestCaseInfos).
+
+-spec throw_if_duplicate(sets:set(binary()), [#test_spec_test_info{}]) -> ok.
+throw_if_duplicate(_, []) ->
+    ok;
+throw_if_duplicate(TestNameSet, [TestCaseInfo | Tail]) ->
+    TestCaseName = TestCaseInfo#test_spec_test_info.name,
+    case sets:is_element(TestCaseName, TestNameSet) of
+        true ->
+            throw({found_duplicate_test, TestCaseInfo});
+        false ->
+            throw_if_duplicate(sets:add_element(TestCaseName, TestNameSet), Tail)
+    end.
+
+-doc """
+Test that all the tests in the list are exported.
+""".
+-spec test_exported_test(suite(), ct_testname()) -> error | ok.
+test_exported_test(Suite, Test) ->
+    case erlang:function_exported(Suite, Test, 1) of
+        false ->
+            case erlang:function_exported(Suite, '$handle_undefined_function', 2) of
+                true ->
+                    ok;
+                false ->
+                    error(
+                        {invalid_test,
+                            io_lib:format(
+                                "The test ~ts has been discovered while recursively exploring all/0, " ++
+                                    "groups/0 but is not an exported method of arity 1",
+                                [Test]
+                            )}
+                    )
+            end;
+        true ->
+            ok
+    end.
+
+-spec load_hooks([module()]) -> ok.
+load_hooks(Hooks) ->
+    ok = code:ensure_modules_loaded(Hooks).
+
+%% We extract the call to the groups() method so that we can type it.
+-spec suite_groups(suite(), [module()]) -> groups_output().
+suite_groups(Suite, Hooks) ->
+    GroupDef =
+        case erlang:function_exported(Suite, groups, 0) of
+            true -> Suite:groups();
+            false -> []
+        end,
+    lists:foldl(
+        fun(Hook, CurrGroupDef) ->
+            case erlang:function_exported(Hook, post_groups, 2) of
+                true ->
+                    Hook:post_groups(Suite, CurrGroupDef);
+                false ->
+                    CurrGroupDef
+            end
+        end,
+        GroupDef,
+        Hooks
+    ).
+
+-spec suite_all(suite(), [module()], groups_output()) -> all_output().
+suite_all(Suite, Hooks, GroupsDef) ->
+    TestsDef = Suite:all(),
+    lists:foldl(
+        fun(Hook, CurrTestsDef) ->
+            case erlang:function_exported(Hook, post_all, 3) of
+                true ->
+                    Hook:post_all(Suite, CurrTestsDef, GroupsDef);
+                false ->
+                    CurrTestsDef
+            end
+        end,
+        TestsDef,
+        Hooks
+    ).
+
+-spec list_test([ct_test_def() | ct_group_content()], [ct_groupname()], groups_output(), suite()) ->
+    [#test_spec_test_info{}].
+list_test(Node, Groups, SuiteGroups, Suite) ->
+    lists:foldl(
+        fun
+            (Test, ListTestsAcc) when is_atom(Test) ->
+                [test_case_info(Suite, Groups, Test) | ListTestsAcc];
+            ({testcase, Test}, ListTestsAcc) when is_atom(Test) ->
+                [test_case_info(Suite, Groups, Test) | ListTestsAcc];
+            ({testcase, TestName, _Properties}, ListTestsAcc) when is_atom(TestName) ->
+                [test_case_info(Suite, Groups, TestName) | ListTestsAcc];
+            (Group, ListTestsAcc) ->
+                lists:append(list_group(Group, Groups, SuiteGroups, Suite), ListTestsAcc)
+        end,
+        [],
+        Node
+    ).
+
+%% case where the format of the group is {group, GroupName}, then we need to
+%% look for the specifications of the group from the groups() method.
+-spec list_group(ct_group_ref() | ct_group_def(), [ct_groupname()], groups_output(), suite()) ->
+    [#test_spec_test_info{}].
+list_group({group, Group}, Groups, SuiteGroups, Suite) when is_atom(Group) ->
+    list_sub_group(Group, Groups, SuiteGroups, Suite);
+%% case {group, GroupName, Properties}, similar as above
+list_group({group, Group, _}, Groups, SuiteGroups, Suite) when is_atom(Group) ->
+    list_sub_group(Group, Groups, SuiteGroups, Suite);
+%% case {group, GroupName, Properties, SubGroupProperties},
+%% similar_as_above.
+list_group({group, Group, _, _}, Groups, SuiteGroups, Suite) ->
+    list_sub_group(Group, Groups, SuiteGroups, Suite);
+list_group(GroupDef, Groups, SuiteGroups, Suite) ->
+    list_group_def(GroupDef, Groups, SuiteGroups, Suite).
+
+-spec list_group_def(ct_group_def(), [ct_groupname()], groups_output(), suite()) -> [#test_spec_test_info{}].
+%% case {GroupName, SubGroupTests}, then we need to look for the specification of the group
+%% from the groups() method as above
+list_group_def({Group, SubGroupTests}, Groups, SuiteGroups, Suite) ->
+    Groups1 = lists:append(Groups, [Group]),
+    list_test(SubGroupTests, Groups1, SuiteGroups, Suite);
+%% case {GroupName, Properties, SubGroupsAndTests},
+%% then in this case we explore the SubGroupsAndTests
+list_group_def({Group, _, SubGroupTests}, Groups, SuiteGroups, Suite) ->
+    Groups1 = lists:append(Groups, [Group]),
+    list_test(SubGroupTests, Groups1, SuiteGroups, Suite).
+
+-doc """
+Makes use of the output from the groups/0 method to get the tests and subgroups
+of the group name given as input
+""".
+-spec list_sub_group(ct_groupname(), [ct_groupname()], groups_output(), suite()) -> [#test_spec_test_info{}].
+list_sub_group(Group, Groups, SuiteGroups, Suite) when is_list(SuiteGroups) ->
+    TestsAndGroups =
+        case lists:keyfind(Group, 1, SuiteGroups) of
+            {Group, TestsDef} when is_list(TestsDef) -> TestsDef;
+            {Group, _, TestsDef} when is_list(TestsDef) -> TestsDef;
+            false -> error({invalid_group, Suite, Group});
+            GroupSpec -> error({bad_group_spec, GroupSpec})
+        end,
+    Groups1 = lists:append(Groups, [Group]),
+    list_test(TestsAndGroups, Groups1, SuiteGroups, Suite).
+
+-spec test_case_info(suite(), [ct_groupname()], ct_testname()) -> #test_spec_test_info{}.
+test_case_info(Suite, Groups, Test) ->
+    ok = test_exported_test(Suite, Test),
+    ListPeriodGroups = lists:join(":", [atom_to_list(Group) || Group <:- Groups]),
+    Name = unicode_characters_to_binary(io_lib:format("~ts.~ts", [ListPeriodGroups, Test])),
+    #test_spec_test_info{
+        name = Name,
+        filter = Name,
+        breakpoint = {Suite, Test, 1}
+    }.
+
+-spec list_test_spec(Suite, Hooks) -> [#test_spec_test_info{}] when
+    Suite :: suite(),
+    Hooks :: [module()].
+list_test_spec(Suite, Hooks) ->
+    ok = load_hooks(Hooks),
+    {module, Suite} = code:ensure_loaded(Suite),
+    GroupsDef = suite_groups(Suite, Hooks),
+    AllResult = suite_all(Suite, Hooks, GroupsDef),
+    lists:reverse(list_test(AllResult, [], GroupsDef, Suite)).
diff --git a/buck2/prelude/erlang/common_test/common/src/test_artifact_directory.erl b/buck2/prelude/erlang/common_test/common/src/test_artifact_directory.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/src/test_artifact_directory.erl
@@ -0,0 +1,229 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(test_artifact_directory).
+-moduledoc """
+Artefact directory file management.
+Used by TPX to upload diagnostic reports.
+""".
+-compile(warn_missing_spec_all).
+
+%% Public API
+-export([prepare/3, link_to_artifact_dir/3, find_log_private/1]).
+
+-export_type([dir_path/0]).
+
+-include_lib("common/include/buck_ct_records.hrl").
+-include_lib("kernel/include/logger.hrl").
+
+-import(common_util, [unicode_characters_to_list/1]).
+
+-define(raw_file_access, prim_file).
+
+-type dir_path() :: file:filename() | undefined.
+
+% Gets the artifactory directory path.
+% This one might be undefined if tpx is ran in offline mode.
+-spec artifact_dir() -> dir_path().
+artifact_dir() ->
+    ArtifactDir = os:getenv("TEST_RESULT_ARTIFACTS_DIR"),
+    case ArtifactDir of
+        false ->
+            undefined;
+        Dir ->
+            filelib:ensure_path(Dir),
+            Dir
+    end.
+
+-spec with_artifact_dir(fun((file:filename()) -> X)) -> X | ok.
+with_artifact_dir(Func) ->
+    case artifact_dir() of
+        undefined -> ok;
+        Dir -> Func(Dir)
+    end.
+
+-spec artifact_annotation_dir() -> dir_path().
+artifact_annotation_dir() ->
+    ArtifactAnnotationDir = os:getenv("TEST_RESULT_ARTIFACT_ANNOTATIONS_DIR"),
+    case ArtifactAnnotationDir of
+        false ->
+            undefined;
+        Dir ->
+            filelib:ensure_path(Dir),
+            Dir
+    end.
+
+-spec with_artifact_annotation_dir(fun((file:filename()) -> X)) -> X | ok.
+with_artifact_annotation_dir(Func) ->
+    case artifact_annotation_dir() of
+        undefined -> ok;
+        Dir -> Func(Dir)
+    end.
+
+-spec coverage_tmp_dir() -> file:filename_all() | undefined.
+coverage_tmp_dir() ->
+    case os:getenv("COVERAGE_COLLECTION_TMPDIR") of
+        false ->
+            undefined;
+        Dir ->
+            filename:absname(Dir)
+    end.
+
+% Collect, create and link the logs and other relevant files in
+% the artefacts directory.
+-spec prepare(ExecutionDir, Tests, ArtifactAnnotationFunction) -> ok when
+    ExecutionDir :: file:filename_all(),
+    Tests :: [#ct_test{}],
+    ArtifactAnnotationFunction :: artifact_annotations:annotation_function().
+prepare(ExecutionDir, Tests, ArtifactAnnotationFunction) ->
+    with_artifact_dir(
+        fun(_ArtifactDir) ->
+            link_tar_ball(ExecutionDir),
+            link_to_artifact_dir(
+                join_paths(ExecutionDir, "result_exec.json"), ExecutionDir, ArtifactAnnotationFunction
+            ),
+            case coverage_tmp_dir() of
+                undefined ->
+                    ok;
+                CoverageTmpDir ->
+                    link_to_artifact_dir(
+                        join_paths(CoverageTmpDir, "feature_coverage.json"),
+                        CoverageTmpDir,
+                        ArtifactAnnotationFunction
+                    )
+            end,
+            case find_log_private(ExecutionDir) of
+                {error, log_private_not_found} ->
+                    ok;
+                LogPrivate ->
+                    LogFiles = find_log_files(LogPrivate),
+                    [
+                        link_to_artifact_dir(File, LogPrivate, ArtifactAnnotationFunction)
+                     || File <- LogFiles,
+                        filelib:is_regular(File, ?raw_file_access)
+                    ],
+                    link_to_artifact_dir(
+                        join_paths(LogPrivate, "test.pftrace"), LogPrivate, ArtifactAnnotationFunction
+                    ),
+                    link_to_artifact_dir(
+                        join_paths(LogPrivate, "test_metrics.tcompact.b64"),
+                        LogPrivate,
+                        fun(FileName) -> artifact_annotations:test_metrics_artifact_annotation(FileName, Tests) end
+                    )
+            end,
+            ok
+        end
+    ).
+
+-doc """
+Use hardlinks inside RE which doesn't follow symlinks like local execution uploads.
+""".
+-spec make_artifact_link(file:filename_all(), file:filename_all()) ->
+    ok | {error, badarg | file:posix()}.
+make_artifact_link(File, ArtifactPath) ->
+    case os:getenv("INSIDE_RE_WORKER") of
+        "1" -> file:make_link(File, ArtifactPath);
+        _ -> file:make_symlink(filename:absname(File), ArtifactPath)
+    end.
+
+-spec link_to_artifact_dir(File, Root, ArtifactAnnotationMFA) -> ok when
+    File :: file:filename_all(),
+    Root :: file:filename_all(),
+    ArtifactAnnotationMFA :: artifact_annotations:annotation_function().
+link_to_artifact_dir(File, Root, ArtifactAnnotationMFA) ->
+    with_artifact_dir(
+        fun(ArtifactDir) ->
+            RelativePath =
+                case string:prefix(File, Root) of
+                    nomatch ->
+                        ?LOG_ERROR("~ts should be a prefix of ~ts", [Root, File]),
+                        error(unexpected_path);
+                    Suffix ->
+                        string:strip(unicode_characters_to_list(Suffix), left, $/)
+                end,
+            FullFileName =
+                unicode_characters_to_list(string:replace(RelativePath, "/", ".", all)),
+            case filelib:is_file(File, ?raw_file_access) of
+                true ->
+                    make_artifact_link(File, join_paths(ArtifactDir, FullFileName)),
+                    Annotation = artifact_annotations:create_artifact_annotation(FullFileName, ArtifactAnnotationMFA),
+                    dump_annotation(Annotation, FullFileName);
+                _ ->
+                    ok
+            end
+        end
+    ).
+
+-spec link_tar_ball(file:filename_all()) -> ok.
+link_tar_ball(LogDir) ->
+    with_artifact_dir(
+        fun(ArtifactDir) ->
+            {_Pid, MonitorRef} = spawn_monitor(fun() ->
+                {ok, Items} = file:list_dir(LogDir),
+                Files = [
+                    {Item, filename:join(LogDir, Item)}
+                 || Item <- Items, not string:equal(filename:join(LogDir, Item), ArtifactDir)
+                ],
+                erl_tar:create(
+                    filename:join(ArtifactDir, "execution_dir.tar.gz"),
+                    Files,
+                    [compressed]
+                )
+            end),
+            receive
+                {'DOWN', MonitorRef, _Type, _Object, _Info} -> ok
+            after 15000 -> ok
+            end
+        end
+    ).
+
+-spec dump_annotation(artifact_annotations:test_result_artifact_annotations(), file:filename()) -> ok.
+dump_annotation(Annotation, FileName) ->
+    with_artifact_annotation_dir(
+        fun(ArtifactAnnotationDir) ->
+            AnnotationName = FileName ++ ".annotation",
+            {ok, AnnotationFile} = file:open(
+                filename:join(ArtifactAnnotationDir, AnnotationName), [write, raw]
+            ),
+            file:write(AnnotationFile, artifact_annotations:serialize(Annotation)),
+            file:close(AnnotationFile),
+            ok
+        end
+    ).
+
+-spec find_log_private(file:filename_all()) -> {error, log_private_not_found} | file:filename().
+find_log_private(LogDir) ->
+    % Use system find command for much faster directory traversal
+    % -type d: find directories only
+    % -name "log_private": match exact name
+    % -print -quit: print first match and exit immediately
+    FindCmd = lists:flatten(
+        io_lib:format("find '~s' -type d -name \"log_private\" -print -quit 2>/dev/null", [LogDir])
+    ),
+    case string:trim(os:cmd(FindCmd)) of
+        "" -> {error, log_private_not_found};
+        Result -> Result
+    end.
+
+-spec find_log_files(file:filename()) -> [file:filename()].
+find_log_files(LogPrivate) ->
+    % Use system find command for much faster directory traversal
+    % -type f: find files only
+    % -name "*.log": match files ending with .log
+    FindCmd = lists:flatten(io_lib:format("find '~s' -type f -name \"*.log\" 2>/dev/null", [LogPrivate])),
+    Output = string:trim(os:cmd(FindCmd)),
+    case Output of
+        "" -> [];
+        _ -> string:split(Output, "\n", all)
+    end.
+
+-spec join_paths(file:filename_all(), file:filename_all()) -> string().
+join_paths(Path, FileName) ->
+    case filename:join(Path, FileName) of
+        NewPath when is_list(NewPath) -> NewPath
+    end.
diff --git a/buck2/prelude/erlang/common_test/common/src/test_logger.erl b/buck2/prelude/erlang/common_test/common/src/test_logger.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/src/test_logger.erl
@@ -0,0 +1,96 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+%% % @format
+-module(test_logger).
+-compile(warn_missing_spec_all).
+
+-export([set_up_logger/3, flush/0, get_std_out/2, get_log_file/2, configure_logger/1]).
+
+-spec set_up_logger(LogDir, AppName, Type) -> ok when
+    LogDir :: file:filename(),
+    AppName :: atom(),
+    Type :: capture_stdout | no_capture_stdout.
+set_up_logger(LogDir, AppName, Type) ->
+    Log = get_log_file(LogDir, AppName),
+    filelib:ensure_dir(Log),
+    [logger:update_handler_config(Id, level, none) || Id <- logger:get_handler_ids()],
+    case Type of
+        no_capture_stdout ->
+            ok;
+        capture_stdout ->
+            StdOut = get_std_out(LogDir, AppName),
+            filelib:ensure_dir(StdOut),
+            {ok, LogFileOpened} = file:open(StdOut, [write, {encoding, utf8}]),
+            test_artifact_directory:link_to_artifact_dir(StdOut, LogDir, fun artifact_annotations:default_annotation/1),
+            group_leader(
+                LogFileOpened, self()
+            )
+    end,
+    configure_logger(Log).
+
+-spec configure_logger(file:filename_all()) -> ok.
+configure_logger(LogFile) ->
+    ok = logger:set_primary_config(#{
+        level => all,
+        filter_default => log
+    }),
+    configure_logger_handler(LogFile, 3).
+
+-spec configure_logger_handler(file:filename_all(), non_neg_integer()) -> ok.
+configure_logger_handler(LogFile, Retries) ->
+    Result = logger:add_handler(
+        file_handler, logger_std_h, #{
+            config => #{
+                file => LogFile,
+                filesync_repeat_interval => 100
+            },
+            filter_default => log,
+            formatter =>
+                {logger_formatter, #{
+                    template => [
+                        time,
+                        " ",
+                        pid,
+                        {file, [" ", file], []},
+                        {line, [":", line], []},
+                        " == ",
+                        level,
+                        ": ",
+                        msg,
+                        "\n"
+                    ]
+                }}
+        }
+    ),
+    case Result of
+        ok ->
+            ok;
+        {error, {handler_not_added, file_ctrl_process_not_started}} when Retries > 0 ->
+            %% Under host memory/IO pressure the OTP logger's hardcoded 5s
+            %% file-ctrl spawn timeout can fire before I/O completes.
+            io:format(
+                standard_error,
+                "Warning: logger file_ctrl_process not started, "
+                "retrying (~b attempts left)~n",
+                [Retries - 1]
+            ),
+            configure_logger_handler(LogFile, Retries - 1);
+        {error, _Reason} = Error ->
+            erlang:error(Error)
+    end.
+
+-spec flush() -> ok | {error, term()}.
+flush() ->
+    logger_std_h:filesync(file_handler).
+
+-spec get_std_out(file:filename_all(), atom()) -> file:filename_all().
+get_std_out(LogDir, AppName) ->
+    filename:join(LogDir, io_lib:format("~tp.stdout.txt", [AppName])).
+
+-spec get_log_file(file:filename_all(), atom()) -> file:filename_all().
+get_log_file(LogDir, AppName) ->
+    filename:join(LogDir, io_lib:format("~tp.log", [AppName])).
diff --git a/buck2/prelude/erlang/common_test/common/test/ct_stdout_SUITE.erl b/buck2/prelude/erlang/common_test/common/test/ct_stdout_SUITE.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/common/test/ct_stdout_SUITE.erl
@@ -0,0 +1,82 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%%% % @format
+-module(ct_stdout_SUITE).
+-typing([eqwalizer]).
+
+-export([all/0]).
+
+-export([
+    test_collect_method_stdout_sanitizes_invalid_utf8_in_truncated_prefix/1,
+    test_collect_method_stdout_sanitizes_invalid_utf8_in_truncated_middle/1,
+    test_collect_method_stdout_sanitizes_invalid_utf8_without_truncation/1
+]).
+
+-include_lib("stdlib/include/assert.hrl").
+
+-define(UNICODE_REPLACEMENT_CHAR_UTF8, <<239, 191, 189>>).
+
+all() ->
+    [
+        test_collect_method_stdout_sanitizes_invalid_utf8_in_truncated_prefix,
+        test_collect_method_stdout_sanitizes_invalid_utf8_in_truncated_middle,
+        test_collect_method_stdout_sanitizes_invalid_utf8_without_truncation
+    ].
+
+test_collect_method_stdout_sanitizes_invalid_utf8_in_truncated_prefix(Config) ->
+    Slice = <<16#9F, 16#98, 16#80, $A>>,
+    Content = <<"pad", Slice/binary>>,
+    Max = byte_size(Slice),
+    ?assertEqual(
+        {truncated, <<?UNICODE_REPLACEMENT_CHAR_UTF8/binary, "A">>},
+        collect_stdout(Content, Max, Config)
+    ).
+
+test_collect_method_stdout_sanitizes_invalid_utf8_in_truncated_middle(Config) ->
+    Slice = <<"prefix", 16#DD, 16#F5, $G, "tail">>,
+    Content = <<"pad", Slice/binary>>,
+    Max = byte_size(Slice),
+    ?assertEqual(
+        {truncated, <<"prefix", ?UNICODE_REPLACEMENT_CHAR_UTF8/binary, "Gtail">>},
+        collect_stdout(Content, Max, Config)
+    ).
+
+test_collect_method_stdout_sanitizes_invalid_utf8_without_truncation(Config) ->
+    Content = <<"prefix", 16#DD, 16#F5, $G, "tail">>,
+    ?assertEqual(
+        <<"prefix", ?UNICODE_REPLACEMENT_CHAR_UTF8/binary, "Gtail">>,
+        collect_stdout(Content, byte_size(Content), Config)
+    ).
+
+-spec collect_stdout(binary(), non_neg_integer(), proplists:proplist()) ->
+    binary() | {truncated, binary()}.
+collect_stdout(Content, Max, Config) ->
+    PrivDir = proplists:get_value(priv_dir, Config),
+    File = filename:join(
+        PrivDir,
+        io_lib:format("ct_stdout_~p.log", [erlang:unique_integer([positive])])
+    ),
+    ok = file:write_file(File, Content, [raw, binary]),
+    StartMarker = <<"start">>,
+    EndMarker = <<"end">>,
+    TreeResults = #{
+        name => testcase,
+        type => leaf,
+        init_method => none,
+        end_method => none,
+        main_method => #{
+            name => testcase,
+            start_progress_marker => StartMarker,
+            end_progress_marker => EndMarker,
+            outcome => passed,
+            details => ~""
+        }
+    },
+    Offsets = #{StartMarker => 0, EndMarker => byte_size(Content)},
+    {ok, CollectedStdOut} = ct_stdout:collect_method_stdout(File, Offsets, TreeResults, Max),
+    maps:get(StartMarker, CollectedStdOut).
diff --git a/buck2/prelude/erlang/common_test/cth_hooks/BUCK b/buck2/prelude/erlang/common_test/cth_hooks/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/cth_hooks/BUCK
@@ -0,0 +1,37 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+erlang_application(
+    name = "cth_hooks",
+    srcs = glob([
+        "src/*.erl",
+        "src/*.hrl",
+    ]),
+    applications = [
+        "kernel",
+        "stdlib",
+        "common_test",
+        "prelude//erlang/common_test/common:common",
+    ],
+    erl_opts = [
+        "+debug_info",
+        "+warnings_as_errors",
+    ],
+    shell_libs = [],
+    use_global_parse_transforms = False,
+    visibility = ["PUBLIC"],
+)
+
+erlang_application(
+    name = "compiled_suites",
+    srcs = glob(["tests/cth_tpx_SUITE_data/*.erl"]),
+    applications = ["stdlib"],
+    erl_opts = [
+        "+debug_info",
+        "+warnings_as_errors",
+    ],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/erlang/common_test/cth_hooks/src/cth_skip_cases.erl b/buck2/prelude/erlang/common_test/cth_hooks/src/cth_skip_cases.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/cth_hooks/src/cth_skip_cases.erl
@@ -0,0 +1,136 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(cth_skip_cases).
+-compile(warn_missing_spec_all).
+
+%% Callbacks
+-export([init/2]).
+
+-export([pre_init_per_suite/3]).
+-export([pre_init_per_group/4]).
+-export([post_init_per_group/5]).
+-export([post_end_per_group/5]).
+
+-export([pre_init_per_testcase/4]).
+
+-type ct_suite() :: module().
+-type ct_groupname() :: ct_suite:ct_groupname().
+-type ct_testname() :: ct_suite:ct_testname().
+-type ct_config() :: ct_suite:ct_config().
+-type ct_config_or_skip_or_fail() ::
+    ct_config() | {skip, term()} | {fail, term()}.
+-type ct_config_or_skip_or_fail_or_term() ::
+    ct_config_or_skip_or_fail() | ok | term().
+
+-type qualified_name() :: string().
+-type reason() :: unicode:chardata().
+-type skip_spec() :: {qualified_name(), reason()}.
+
+-type state() :: #{
+    skips := [skip_spec()],
+    groups := cth_tpx_test_tree:group_path()
+}.
+
+-doc """
+Skips suite, group, or testcase callbacks whose qualified name matches one of
+the configured regular expressions, each with its own reason.
+
+`pre_init_per_suite` matches against `""`, `pre_init_per_group` matches the
+qualified group name with an empty testcase, and `pre_init_per_testcase`
+matches the fully-qualified testcase name that
+`common_util:qualified_name/2` reports. The first matching pattern wins.
+""".
+-spec init(Id, Opts) -> {ok, state()} when
+    Id :: term(),
+    Opts :: [skip_spec()].
+init(_Id, Opts) ->
+    {ok, #{skips => Opts, groups => []}}.
+
+-spec pre_init_per_suite(_Suite, Config, State) -> {ct_config_or_skip_or_fail(), state()} when
+    _Suite :: ct_suite(),
+    Config :: ct_config(),
+    State :: state().
+pre_init_per_suite(_Suite, Config, State = #{skips := Skips}) ->
+    case find_skip("", Skips) of
+        {ok, Reason} ->
+            {{skip, Reason}, State};
+        error ->
+            {Config, State}
+    end.
+
+-spec pre_init_per_group(_Suite, Group, Config, State) -> {ct_config_or_skip_or_fail(), state()} when
+    _Suite :: ct_suite(),
+    Group :: ct_groupname(),
+    Config :: ct_config(),
+    State :: state().
+pre_init_per_group(_Suite, Group, Config, State = #{skips := Skips, groups := Groups}) ->
+    State1 = State#{groups := [Group | Groups]},
+    case find_skip(common_util:qualified_name([Group | Groups], ""), Skips) of
+        {ok, Reason} ->
+            {{skip, Reason}, State1};
+        error ->
+            {Config, State1}
+    end.
+
+-spec post_init_per_group(
+    ct_suite(), ct_groupname(), ct_config(), ct_config_or_skip_or_fail_or_term(), state()
+) ->
+    {ct_config_or_skip_or_fail_or_term(), state()}.
+post_init_per_group(_Suite, Group, _Config, Return, State) when not is_list(Return) ->
+    {Return, pop_group(Group, State)};
+post_init_per_group(_Suite, _Group, _Config, Return, State) ->
+    {Return, State}.
+
+-spec post_end_per_group(
+    ct_suite(), ct_groupname(), ct_config(), ct_config_or_skip_or_fail_or_term(), state()
+) ->
+    {ct_config_or_skip_or_fail_or_term(), state()}.
+post_end_per_group(_Suite, Group, _Config, Return, State) ->
+    {Return, pop_group(Group, State)}.
+
+-spec pre_init_per_testcase
+    (_Suite, _TestCase, SkipOrFail, State) -> {ct_config_or_skip_or_fail(), state()} when
+        _Suite :: ct_suite(),
+        _TestCase :: ct_testname(),
+        SkipOrFail :: ct_config_or_skip_or_fail(),
+        State :: state();
+    (_Suite, TestCase, Config, State) -> {ct_config_or_skip_or_fail(), state()} when
+        _Suite :: ct_suite(),
+        TestCase :: ct_testname(),
+        Config :: ct_config(),
+        State :: state().
+pre_init_per_testcase(_Suite, _TestCase, {Tag, _Reason} = SkipOrFail, State) when
+    Tag =:= skip; Tag =:= fail
+->
+    {SkipOrFail, State};
+pre_init_per_testcase(_Suite, TestCase, Config, State = #{skips := Skips, groups := Groups}) ->
+    case find_skip(common_util:qualified_name(Groups, TestCase), Skips) of
+        {ok, Reason} ->
+            {{skip, Reason}, State};
+        error ->
+            {Config, State}
+    end.
+
+-spec find_skip(Name, Skips) -> {ok, Reason} | error when
+    Name :: qualified_name(),
+    Skips :: [skip_spec()],
+    Reason :: reason().
+find_skip(_Name, []) ->
+    error;
+find_skip(Name, [{Pattern, Reason} | Rest]) ->
+    case re:run(Name, Pattern, [{capture, none}]) of
+        match -> {ok, Reason};
+        nomatch -> find_skip(Name, Rest)
+    end.
+
+-spec pop_group(ct_groupname(), state()) -> state().
+pop_group(Group, State = #{groups := [Group | Groups]}) ->
+    State#{groups := Groups};
+pop_group(_Group, State) ->
+    State.
diff --git a/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx.erl b/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx.erl
@@ -0,0 +1,793 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(cth_tpx).
+-compile(warn_missing_spec_all).
+
+-export([is_running_in_sandcastle/0]).
+
+%% Callbacks
+-export([id/1]).
+-export([init/2]).
+
+-export([pre_init_per_suite/3]).
+-export([post_init_per_suite/4]).
+-export([pre_end_per_suite/3]).
+-export([post_end_per_suite/4]).
+
+-export([pre_init_per_group/4]).
+-export([post_init_per_group/5]).
+-export([pre_end_per_group/4]).
+-export([post_end_per_group/5]).
+
+-export([pre_init_per_testcase/4]).
+-export([post_init_per_testcase/5]).
+-export([pre_end_per_testcase/4]).
+-export([post_end_per_testcase/5]).
+
+-export([on_tc_fail/4]).
+-export([on_tc_skip/4]).
+
+-export([terminate/1]).
+
+%% please dialyzer
+-export([ok_group/1, fail_group/1]).
+
+-export_type([
+    shared_state/0
+]).
+
+-import(common_util, [unicode_characters_to_list/1]).
+
+%% For tests purposes
+
+-include("method_ids.hrl").
+
+%% ----------------------- Types --------------------------
+
+%  `SUCCESS`, `FAILURE`, `ASSUMPTION_VIOLATION`, `DISABLED`, `EXCLUDED`, `DRY_RUN`
+
+%% -----------------------------------------------------------------------------
+%%            Types
+%% -----------------------------------------------------------------------------
+
+-type tree_node() :: cth_tpx_test_tree:tree_node().
+-type group_path() :: cth_tpx_test_tree:group_path().
+-type outcome() :: cth_tpx_test_tree:outcome().
+
+-record(state, {
+    cached_user_process :: pid(),
+    suite :: ct_suite(),
+    groups :: group_path(),
+    start_info :: #{method_id() => start_info()},
+    ct_stdout_fingerprint :: ct_stdout:fingerprint(),
+    tree_results :: tree_node(),
+    previous_group_failed :: boolean() | undefined,
+    output :: {file, file:filename_all()} | stdout
+}).
+
+-type hook_opts() :: #{
+    role := cth_tpx_role:role(),
+    ct_stdout_fingerprint := ct_stdout:fingerprint(),
+    result_json => file:filename_all()
+}.
+
+-type shared_state() :: #state{}.
+-type hook_state() :: #{
+    id := term(),
+    role := cth_tpx_role:role(),
+    server := cth_tpx_server:handle()
+}.
+-type start_info() :: #{
+    timestamp := float(),
+    stdout_progress_line := ct_stdout:progress_line()
+}.
+
+-type ct_suite() :: module().
+-type ct_groupname() :: ct_suite:ct_groupname().
+-type ct_testname() :: ct_suite:ct_testname().
+-type ct_config() :: ct_suite:ct_config().
+-type ct_config_or_skip_or_fail() ::
+    ct_config() | {skip, term()} | {fail, term()}.
+-type ct_config_or_skip_or_fail_or_term() ::
+    ct_config_or_skip_or_fail() | ok | term().
+
+%% -----------------------------------------------------------------------------
+
+-spec second_timestamp() -> float().
+second_timestamp() ->
+    os:system_time(millisecond) / 1000.
+
+%% -----------------------------------------------------------------------------
+%%    Registering and collecting results.
+%% -----------------------------------------------------------------------------
+
+% General workflow:
+% ct will call methods pre_ post_ method before each method init, case, end methods from
+% the test_suite.
+% Based on the state in each of these, we create a result that will be passed to the method
+% add_result/4.
+% This one will register the results into a tree, using the method cth_tpx_test_tree:register_result/4.
+% Once the whole run is finished, the method terminate/1 is called.
+% This one will, for each requested_test creates and output a method_result, using the
+% previously constructed tree_result.
+
+%%%%%%%%%%%%%%%%%% This part is similar to the one in cth_tespilot (execpt for some minor modifications
+%% in representing init / main/ end testcases as {Phase, Name})
+
+%% -----------------------------------------------------------------------------
+%% Format Functions
+%% -----------------------------------------------------------------------------
+
+-spec fmt_skip(Reason) -> unicode:chardata() when
+    Reason :: term().
+fmt_skip(Reason) ->
+    fmt_stack(Reason, "SKIPPED").
+
+-spec fmt_fail(Reason) -> unicode:chardata() when
+    Reason :: term().
+fmt_fail(Reason) ->
+    fmt_stack(Reason, "FAILED").
+
+-spec fmt_init_or_end(Suite, Callback, Reason, Label) -> unicode:chardata() when
+    Suite :: ct_suite(),
+    Callback :: init_per_suite | end_per_suite | init_per_group | end_per_group | init_per_testcase | end_per_testcase,
+    Reason :: term(),
+    Label :: unicode:chardata().
+fmt_init_or_end(Suite, Callback, {failed, {Suite, Callback, ActualReason}}, Label) ->
+    fmt_init_or_end(Suite, Callback, ActualReason, Label);
+fmt_init_or_end(_Suite, Callback, Reason, Label) ->
+    fmt_stack(Reason, io_lib:format("~ts ~ts", [Callback, Label])).
+
+-spec fmt_stack(Reason, Label) -> unicode:chardata() when
+    Reason :: term(),
+    Label :: unicode:chardata().
+fmt_stack({'EXIT', {Reason, ST}}, Label) ->
+    fmt_stack({Reason, ST}, Label);
+fmt_stack(Reason, _Label) ->
+    Output = ct_error_printer:format_error(Reason, true),
+    io_lib:format("~ts", [Output]).
+
+-doc """
+Whether a crash asks to be reported to tpx as an infra failure rather than a test
+failure.
+
+A test or callback opts in by crashing with `error(test_infra_error)` or
+`error({test_infra_error, Reason})`. tpx retries infra failures transparently and
+records them outside the failure band, so they do not break a diff.
+
+Only the wrapper shapes CT itself adds are unwrapped. The marker is deliberately not
+searched for inside arbitrary terms, so an ordinary failure that happens to carry the
+atom somewhere in its payload stays an ordinary failure.
+""".
+-spec is_infra_error(Reason) -> boolean() when Reason :: term().
+is_infra_error(test_infra_error) ->
+    true;
+is_infra_error({test_infra_error, _Reason}) ->
+    true;
+is_infra_error({failed, {_Suite, _Callback, Reason}}) ->
+    is_infra_error(Reason);
+is_infra_error({'EXIT', Reason}) ->
+    is_infra_error(Reason);
+is_infra_error({Reason, Stacktrace}) when is_list(Stacktrace) ->
+    is_infra_error(Reason);
+is_infra_error({Tag, Reason}) when Tag =:= skip; Tag =:= fail; Tag =:= error ->
+    is_infra_error(Reason);
+is_infra_error(_Reason) ->
+    false.
+
+-doc """
+The outcome to record for a failing method: `infra_failure` if it opted in via
+`test_infra_error`, otherwise the usual `failed`.
+""".
+-spec fail_outcome(Reason) -> failed | infra_failure when Reason :: term().
+fail_outcome(Reason) ->
+    case is_infra_error(Reason) of
+        true -> infra_failure;
+        false -> failed
+    end.
+
+%% -----------------------------------------------------------------------------
+%% CT hooks functions
+%% -----------------------------------------------------------------------------
+
+-doc """
+Return a unique id for this CTH.
+""".
+-spec id(hook_opts()) -> {?MODULE, cth_tpx_role:role()}.
+id(#{role := Role}) ->
+    {?MODULE, Role}.
+
+-doc """
+Always called before any other callback function. Use this to initiate
+any common state.
+""".
+-spec init(_Id :: term(), Opts :: hook_opts()) -> {ok, hook_state(), integer()}.
+init(Id, Opts = #{role := Role}) ->
+    ServerName = '$cth_tpx$server$',
+    case Role of
+        top ->
+            Output =
+                case maps:get(result_json, Opts, undefined) of
+                    undefined -> stdout;
+                    FN -> {file, FN}
+                end,
+            #{ct_stdout_fingerprint := Fingerprint} = Opts,
+            init_role_top(Id, ServerName, Fingerprint, Output);
+        bot ->
+            init_role_bot(Id, ServerName)
+    end.
+
+-spec init_role_top(Id, ServerName, Fingerprint, Output) ->
+    {ok, hook_state(), integer()}
+when
+    Id :: term(),
+    ServerName :: atom(),
+    Fingerprint :: ct_stdout:fingerprint(),
+    Output :: stdout | {file, file:filename_all()}.
+init_role_top(Id, ServerName, Fingerprint, Output) ->
+    CachedUserProcess =
+        case whereis(user) of
+            UserPid when is_pid(UserPid) -> UserPid
+        end,
+
+    SharedState = #state{
+        cached_user_process = CachedUserProcess,
+        output = Output,
+        ct_stdout_fingerprint = Fingerprint,
+        start_info = #{},
+        groups = [],
+        tree_results = cth_tpx_test_tree:new_node(unknown_suite)
+    },
+    Handle = cth_tpx_server:start_link(SharedState),
+    % Register so that init_role_bot can find it
+    register(ServerName, Handle),
+    HookState = #{
+        id => Id,
+        role => top,
+        server => Handle
+    },
+    {ok, HookState, cth_tpx_role:role_priority(top)}.
+
+-spec init_role_bot(Id, ServerName) -> {ok, hook_state(), integer()} when
+    Id :: term(), ServerName :: atom().
+init_role_bot(Id, ServerName) ->
+    % Put there by init_role_top
+    case whereis(ServerName) of
+        Handle when is_pid(Handle) ->
+            unregister(ServerName),
+            HookState = #{
+                id => Id,
+                role => bot,
+                server => Handle
+            },
+            {ok, HookState, cth_tpx_role:role_priority(bot)}
+    end.
+
+-doc """
+Called before init_per_suite is called.
+""".
+-spec pre_init_per_suite(ct_suite(), ct_config(), hook_state()) -> {ct_config_or_skip_or_fail(), hook_state()}.
+pre_init_per_suite(Suite, Config, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Config, fun(State) ->
+        State1 = collect_start_info(State, ?INIT_PER_SUITE, Suite),
+        {Config, State1#state{
+            suite = Suite,
+            groups = [],
+            tree_results = cth_tpx_test_tree:new_node(Suite),
+            previous_group_failed = false
+        }}
+    end).
+
+-spec post_init_per_suite(ct_suite(), ct_config(), ct_config_or_skip_or_fail_or_term(), hook_state()) ->
+    {ct_config_or_skip_or_fail_or_term(), hook_state()}.
+post_init_per_suite(Suite, _Config, {skip, {failed, _} = Reason} = Error, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State) ->
+        Desc = fmt_init_or_end(Suite, init_per_suite, Reason, ~"FAILED"),
+        {Error, add_result(?INIT_PER_SUITE, fail_outcome(Reason), Desc, State)}
+    end);
+post_init_per_suite(Suite, _Config, {skip, Reason} = Error, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State) ->
+        Desc = fmt_init_or_end(Suite, init_per_suite, Reason, ~"SKIPPED"),
+        {Error, add_result(?INIT_PER_SUITE, skipped, Desc, State)}
+    end);
+post_init_per_suite(Suite, _Config, {fail, Reason} = Error, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State) ->
+        Desc = fmt_init_or_end(Suite, init_per_suite, Reason, ~"FAILED"),
+        {Error, add_result(?INIT_PER_SUITE, fail_outcome(Reason), Desc, State)}
+    end);
+post_init_per_suite(Suite, _Config, Error, HookState) when not is_list(Error) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State) ->
+        Desc = fmt_init_or_end(Suite, init_per_suite, Error, ~"FAILED"),
+        {Error, add_result(?INIT_PER_SUITE, fail_outcome(Error), Desc, State)}
+    end);
+post_init_per_suite(_Suite, _Config, Return, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Return, fun(State) ->
+        {Return, add_result(?INIT_PER_SUITE, passed, ~"", State)}
+    end).
+
+-spec pre_end_per_suite(ct_suite(), ct_config(), hook_state()) -> {ct_config(), hook_state()}.
+pre_end_per_suite(Suite, Config, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Config, fun(State) ->
+        {Config, collect_start_info(State, ?END_PER_SUITE, Suite)}
+    end).
+
+-spec post_end_per_suite(ct_suite(), ct_config(), ct_config_or_skip_or_fail_or_term(), hook_state()) ->
+    {ct_config_or_skip_or_fail_or_term(), hook_state()}.
+post_end_per_suite(
+    Suite,
+    _Config,
+    {skip, Reason} = Error,
+    HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0) ->
+        Desc = fmt_init_or_end(Suite, end_per_suite, Reason, ~"SKIPPED"),
+        State1 = add_result(?END_PER_SUITE, skipped, Desc, State0),
+        {Error, clear_suite(State1)}
+    end);
+post_end_per_suite(
+    Suite,
+    _Config,
+    {fail, Reason} = Error,
+    HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0) ->
+        Desc = fmt_init_or_end(Suite, end_per_suite, Reason, ~"FAILED"),
+        State1 = add_result(?END_PER_SUITE, fail_outcome(Reason), Desc, State0),
+        {Error, clear_suite(State1)}
+    end);
+post_end_per_suite(
+    Suite,
+    _Config,
+    {error, Reason} = Error,
+    HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0) ->
+        Desc = fmt_init_or_end(Suite, end_per_suite, Reason, ~"FAILED"),
+        State1 = add_result(?END_PER_SUITE, fail_outcome(Reason), Desc, State0),
+        {Error, clear_suite(State1)}
+    end);
+post_end_per_suite(_Suite, _Config, Return, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Return, fun(State0) ->
+        %% clean TC state
+        State1 = add_result(?END_PER_SUITE, passed, ~"", State0),
+        {Return, clear_suite(State1)}
+    end).
+
+-spec clear_suite(#state{}) -> #state{}.
+clear_suite(State) ->
+    State#state{
+        suite = undefined,
+        groups = [],
+        start_info = #{}
+    }.
+
+-spec pre_init_per_group(ct_suite(), ct_groupname(), ct_config(), hook_state()) -> {ct_config(), hook_state()}.
+pre_init_per_group(_SuiteName, Group, Config, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Config, fun
+        (State = #state{groups = [_ | Groups], previous_group_failed = true}) ->
+            State1 = collect_start_info(State, ?INIT_PER_GROUP, Group),
+            {Config, State1#state{groups = Groups, previous_group_failed = false}};
+        (#state{} = State) ->
+            {Config, collect_start_info(State, ?INIT_PER_GROUP, Group)}
+    end).
+
+-spec post_init_per_group(ct_suite(), ct_groupname(), ct_config(), ct_config_or_skip_or_fail_or_term(), hook_state()) ->
+    {ct_config_or_skip_or_fail_or_term(), hook_state()}.
+post_init_per_group(
+    Suite,
+    Group,
+    _Config,
+    {skip, {failed, _} = Reason} = Error,
+    HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0 = #state{groups = Groups}) ->
+        State1 = State0#state{groups = [Group | Groups]},
+        Desc = fmt_init_or_end(Suite, init_per_group, Reason, ~"FAILED"),
+        State2 = add_result(?INIT_PER_GROUP, fail_outcome(Reason), Desc, State1),
+        {Error, fail_group(State2)}
+    end);
+post_init_per_group(
+    Suite,
+    Group,
+    _Config,
+    {skip, Reason} = Error,
+    HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0 = #state{groups = Groups}) ->
+        State1 = State0#state{groups = [Group | Groups]},
+        Desc = fmt_init_or_end(Suite, init_per_group, Reason, ~"SKIPPED"),
+        State2 = add_result(?INIT_PER_GROUP, skipped, Desc, State1),
+        {Error, fail_group(State2)}
+    end);
+post_init_per_group(
+    Suite,
+    Group,
+    _Config,
+    {fail, Reason} = Error,
+    HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0 = #state{groups = Groups}) ->
+        State1 = State0#state{groups = [Group | Groups]},
+        Desc = fmt_init_or_end(Suite, init_per_group, Reason, ~"FAILED"),
+        State2 = add_result(?INIT_PER_GROUP, fail_outcome(Reason), Desc, State1),
+        {Error, fail_group(State2)}
+    end);
+post_init_per_group(Suite, Group, _Config, Error, HookState) when not is_list(Error) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0 = #state{groups = Groups}) ->
+        State1 = State0#state{groups = [Group | Groups]},
+        Desc = fmt_init_or_end(Suite, init_per_group, Error, ~"FAILED"),
+        State2 = add_result(?INIT_PER_GROUP, fail_outcome(Error), Desc, State1),
+        {Error, fail_group(State2)}
+    end);
+post_init_per_group(_Suite, Group, _Config, Return, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Return, fun(State0 = #state{groups = Groups}) ->
+        State1 = State0#state{groups = [Group | Groups]},
+        State2 = add_result(?INIT_PER_GROUP, passed, ~"", State1),
+        {Return, ok_group(State2)}
+    end).
+
+-spec ok_group(#state{}) -> #state{}.
+ok_group(State) ->
+    State#state{previous_group_failed = false}.
+
+-spec fail_group(#state{}) -> #state{}.
+fail_group(State) ->
+    State#state{previous_group_failed = true}.
+
+-spec pre_end_per_group(ct_suite(), ct_groupname(), ct_config(), hook_state()) -> {ct_config(), hook_state()}.
+pre_end_per_group(_SuiteName, Group, Config, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Config, fun(State) ->
+        {Config, collect_start_info(State, ?END_PER_GROUP, Group)}
+    end).
+
+-spec post_end_per_group(ct_suite(), ct_groupname(), ct_config(), ct_config_or_skip_or_fail_or_term(), hook_state()) ->
+    {ct_config_or_skip_or_fail_or_term(), hook_state()}.
+post_end_per_group(
+    Suite,
+    _Group,
+    _Config,
+    {skip, Reason} = Error,
+    HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0 = #state{groups = Groups}) ->
+        Desc = fmt_init_or_end(Suite, end_per_group, Reason, ~"SKIPPED"),
+        State1 = add_result(?END_PER_GROUP, skipped, Desc, State0),
+        {Error, State1#state{groups = tl(Groups)}}
+    end);
+post_end_per_group(
+    Suite,
+    _Group,
+    _Config,
+    {fail, Reason} = Error,
+    HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0 = #state{groups = Groups}) ->
+        Desc = fmt_init_or_end(Suite, end_per_group, Reason, ~"FAILED"),
+        State1 = add_result(?END_PER_GROUP, fail_outcome(Reason), Desc, State0),
+        {Error, State1#state{groups = tl(Groups)}}
+    end);
+post_end_per_group(
+    Suite,
+    _Group,
+    _Config,
+    {error, Reason} = Error,
+    HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0 = #state{groups = Groups}) ->
+        Desc = fmt_init_or_end(Suite, end_per_group, Reason, ~"FAILED"),
+        State1 = add_result(?END_PER_GROUP, fail_outcome(Reason), Desc, State0),
+        {Error, State1#state{groups = tl(Groups)}}
+    end);
+post_end_per_group(_Suite, _Group, _Config, Return, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Return, fun(State0 = #state{groups = Groups}) ->
+        State1 = add_result(?END_PER_GROUP, passed, ~"", State0),
+        {Return, State1#state{groups = tl(Groups)}}
+    end).
+
+-spec pre_init_per_testcase(ct_suite(), ct_testname(), ct_config(), hook_state()) -> {ct_config(), hook_state()}.
+pre_init_per_testcase(_Suite, TestCase, Config, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Config, fun(State) ->
+        %% store name and start time for current test case
+        %% We capture time twice:
+        %%  1) For the init_per_testcase.
+        %%  2) For the whole testcase = init + actual_testcase + end
+        %% The reason behind is that capturing the timing for the actual_testcase
+        %% is not straightforward, as there is no pre/post method for it.
+        State1 = collect_start_info(State, {TestCase, ?INIT_PER_TESTCASE}, TestCase),
+        State2 = collect_start_info(State1, {TestCase, ?MAIN_TESTCASE}, TestCase),
+        {Config, State2}
+    end).
+
+-spec post_init_per_testcase(ct_suite(), ct_testname(), ct_config(), ct_config_or_skip_or_fail_or_term(), hook_state()) ->
+    {ct_config_or_skip_or_fail_or_term(), hook_state()}.
+post_init_per_testcase(
+    Suite,
+    TestCase,
+    _Config,
+    {skip, {failed, _} = Reason} = Error,
+    HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State) ->
+        %% ct skip because of failed init is reported as error
+        Desc = fmt_init_or_end(Suite, init_per_testcase, Reason, ~"FAILED"),
+        {Error, add_result({TestCase, ?INIT_PER_TESTCASE}, fail_outcome(Reason), Desc, State)}
+    end);
+post_init_per_testcase(
+    Suite, TestCase, _Config, {skip, Reason} = Error, HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State) ->
+        %% other skips (user skip) are reported as skips
+        Desc = fmt_init_or_end(Suite, init_per_testcase, Reason, ~"SKIPPED"),
+        {Error, add_result({TestCase, ?INIT_PER_TESTCASE}, skipped, Desc, State)}
+    end);
+post_init_per_testcase(
+    Suite, TestCase, _Config, {fail, Reason} = Error, HookState
+) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State) ->
+        %% fails are reported as errors
+        Desc = fmt_init_or_end(Suite, init_per_testcase, Reason, ~"FAILED"),
+        {Error, add_result({TestCase, ?INIT_PER_TESTCASE}, fail_outcome(Reason), Desc, State)}
+    end);
+post_init_per_testcase(Suite, TestCase, _Config, {error, Reason} = Error, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State) ->
+        %% terms are reported as errors except ok (missing in CT doc)
+        Desc = fmt_init_or_end(Suite, init_per_testcase, Reason, ~"FAILED"),
+        {Error, add_result({TestCase, ?INIT_PER_TESTCASE}, fail_outcome(Reason), Desc, State)}
+    end);
+post_init_per_testcase(Suite, TestCase, _Config, Error, HookState) when
+    not is_list(Error) andalso ok =/= Error
+->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State) ->
+        %% terms are reported as errors except ok (missing in CT doc)
+        Desc = fmt_init_or_end(Suite, init_per_testcase, Error, ~"FAILED"),
+        {Error, add_result({TestCase, ?INIT_PER_TESTCASE}, fail_outcome(Error), Desc, State)}
+    end);
+post_init_per_testcase(_Suite, TestCase, _Config, Return, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Return, fun(State) ->
+        %% everything else is ok
+        State1 = add_result({TestCase, ?INIT_PER_TESTCASE}, passed, ~"", State),
+        {Return, State1}
+    end).
+
+%% add test result to state
+-spec add_result(method_id(), outcome(), unicode:chardata(), shared_state()) -> shared_state().
+add_result(
+    Method,
+    Outcome,
+    Desc,
+    State = #state{
+        groups = Groups,
+        start_info = StartInfo0,
+        tree_results = TreeResults
+    }
+) ->
+    QualifiedName = method_name(Method, Groups),
+    TS = second_timestamp(),
+    Result0 = #{
+        name => QualifiedName,
+        outcome => Outcome,
+        details => unicode_characters_to_list(Desc)
+    },
+    Result =
+        case StartInfo0 of
+            #{Method := #{timestamp := StartTime, stdout_progress_line := StartStdOutLine}} ->
+                EndStdOutLine = ct_stdout:emit_progress(
+                    State#state.cached_user_process,
+                    State#state.ct_stdout_fingerprint,
+                    method_progress_label(Method),
+                    finished
+                ),
+
+                Result0#{
+                    start_time => StartTime,
+                    end_time => TS,
+                    start_progress_marker => StartStdOutLine,
+                    end_progress_marker => EndStdOutLine
+                };
+            _ ->
+                %% If no test data (skipped test cases/groups/suite)
+                %% then started time doesn't exist.
+                Result0
+        end,
+    ST1 = maps:remove(Method, StartInfo0),
+    NewTreeResults = cth_tpx_test_tree:register_result(TreeResults, Result, Groups, Method),
+    State#state{start_info = ST1, tree_results = NewTreeResults}.
+
+-spec method_name(method_id(), group_path()) -> string().
+method_name(Method, Groups) ->
+    MethodName =
+        case Method of
+            {TestCase, Phase} ->
+                unicode_characters_to_list(io_lib:format("~ts.~ts", [atom_to_list(TestCase), atom_to_list(Phase)]));
+            MethodName0 ->
+                atom_to_list(MethodName0)
+        end,
+    common_util:qualified_name(Groups, MethodName).
+
+-spec pre_end_per_testcase(ct_suite(), ct_testname(), ct_config(), hook_state()) -> {ct_config(), hook_state()}.
+pre_end_per_testcase(_Suite, TC, Config, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Config, fun(State) ->
+        {Config, collect_start_info(State, {TC, ?END_PER_TESTCASE}, TC)}
+    end).
+
+-spec post_end_per_testcase(ct_suite(), ct_testname(), ct_config(), ct_config_or_skip_or_fail_or_term(), hook_state()) ->
+    {ct_config_or_skip_or_fail_or_term(), hook_state()}.
+post_end_per_testcase(_Suite, TC, _Config, ok = Return, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Return, fun(State0) ->
+        State1 = add_result({TC, ?END_PER_TESTCASE}, passed, ~"", State0),
+        {ok, add_result({TC, ?MAIN_TESTCASE}, passed, ~"", State1)}
+    end);
+post_end_per_testcase(Suite, TC, Config, Error, HookState) ->
+    on_shared_state(HookState, ?FUNCTION_NAME, Error, fun(State0) ->
+        NextState =
+            case lists:keyfind(tc_status, 1, Config) of
+                {tc_status, ok} ->
+                    %% Test case passed, but we still ended in an error
+                    %% same description as ct output
+                    %% first report testcase itself
+                    State1 = add_result({TC, ?MAIN_TESTCASE}, passed, ~"", State0),
+                    %% now report end per failure
+                    Reason =
+                        case Error of
+                            {skip, Reason0} -> Reason0;
+                            {fail, Reason0} -> Reason0;
+                            _ -> Error
+                        end,
+                    Desc = fmt_init_or_end(Suite, end_per_testcase, Reason, ~"FAILED"),
+                    add_result({TC, ?END_PER_TESTCASE}, fail_outcome(Reason), Desc, State1);
+                _ ->
+                    %% Test case failed, in which case on_tc_fail already reports it
+                    add_result({TC, ?END_PER_TESTCASE}, passed, ~"", State0)
+            end,
+        {Error, NextState}
+    end).
+
+-spec on_tc_fail(Suite, Callback, Reason, HookState) -> hook_state() when
+    Suite :: ct_suite(),
+    Callback ::
+        init_per_suite
+        | end_per_suite
+        | ct_testname()
+        | {ct_testname(), ct_groupname()}
+        | {init_per_group | end_per_group, ct_groupname()},
+    Reason :: term(),
+    HookState :: hook_state().
+on_tc_fail(_SuiteName, init_per_suite, _, HookState) ->
+    HookState;
+on_tc_fail(_SuiteName, end_per_suite, _, HookState) ->
+    HookState;
+on_tc_fail(_SuiteName, {init_per_group, _GroupName}, _, HookState) ->
+    HookState;
+on_tc_fail(_SuiteName, {end_per_group, _GroupName}, _, HookState) ->
+    HookState;
+on_tc_fail(_SuiteName, {TC, _Group}, Reason, HookState) ->
+    modify_shared_state(HookState, ?FUNCTION_NAME, fun(State) ->
+        Desc = fmt_fail(Reason),
+        add_result({TC, ?MAIN_TESTCASE}, fail_outcome(Reason), Desc, State)
+    end);
+on_tc_fail(_SuiteName, TC, Reason, HookState) ->
+    modify_shared_state(HookState, ?FUNCTION_NAME, fun(State) ->
+        Desc = fmt_fail(Reason),
+        add_result({TC, ?MAIN_TESTCASE}, fail_outcome(Reason), Desc, State)
+    end).
+
+-spec on_tc_skip(Suite, Callback, Reason, HookState) -> hook_state() when
+    Suite :: ct_suite(),
+    Callback ::
+        init_per_suite
+        | end_per_suite
+        | ct_testname()
+        | {ct_testname(), ct_groupname()}
+        | {init_per_group | end_per_group, ct_groupname()},
+    Reason :: {tc_auto_skip, term()} | {tc_user_skip, term()},
+    HookState :: hook_state().
+on_tc_skip(_SuiteName, init_per_suite, _, HookState) ->
+    HookState;
+on_tc_skip(_SuiteName, end_per_suite, _, HookState) ->
+    HookState;
+on_tc_skip(_SuiteName, {init_per_group, _GroupName}, _, HookState) ->
+    HookState;
+on_tc_skip(_SuiteName, {end_per_group, _GroupName}, _, HookState) ->
+    HookState;
+on_tc_skip(_SuiteName, {TC, _Group}, Reason, HookState) ->
+    modify_shared_state(HookState, ?FUNCTION_NAME, fun(State) ->
+        handle_on_tc_skip(TC, Reason, State)
+    end);
+on_tc_skip(_SuiteName, TC, Reason, HookState) ->
+    modify_shared_state(HookState, ?FUNCTION_NAME, fun(State) ->
+        handle_on_tc_skip(TC, Reason, State)
+    end).
+
+-spec handle_on_tc_skip(TC, Reason, State) -> State when
+    TC :: ct_testname(),
+    Reason :: {tc_auto_skip, term()} | {tc_user_skip, term()},
+    State :: #state{}.
+handle_on_tc_skip(TC, {tc_auto_skip, Reason}, State = #state{suite = Suite}) ->
+    Desc = fmt_fail(Reason),
+    NewState = add_result({TC, ?MAIN_TESTCASE}, fail_outcome(Reason), Desc, State),
+    NewState#state{suite = Suite};
+handle_on_tc_skip(TC, {tc_user_skip, Reason}, State = #state{suite = Suite}) ->
+    Desc = fmt_skip(Reason),
+    NewState = add_result({TC, ?MAIN_TESTCASE}, skipped, Desc, State),
+    NewState#state{suite = Suite}.
+
+-doc """
+Called when the scope of the CTH is done
+""".
+-spec terminate(hook_state()) -> ok | {error, _Reason}.
+terminate(#{role := top, server := Handle}) ->
+    #state{output = Output, tree_results = TreeResults} = cth_tpx_server:get(Handle),
+    write_output(Output, term_to_binary(TreeResults));
+terminate(#{role := bot}) ->
+    ok.
+
+-spec write_output({file, file:filename_all()} | stdout, binary()) -> ok.
+write_output({file, FN}, JSON) ->
+    io:format("Writing result file ~tp~n", [FN]),
+    ok = filelib:ensure_dir(FN),
+    ok = file:write_file(FN, JSON, [raw, binary]);
+write_output(stdout, JSON) ->
+    io:format(user, "~tp", [JSON]).
+
+-spec collect_start_info(State, MethodId, Context) -> shared_state() when
+    State :: shared_state(),
+    MethodId :: method_id(),
+    Context :: atom().
+collect_start_info(#state{start_info = ST0} = State, MethodId, _Context) ->
+    ProgressLine = ct_stdout:emit_progress(
+        State#state.cached_user_process,
+        State#state.ct_stdout_fingerprint,
+        method_progress_label(MethodId),
+        started
+    ),
+
+    StartInfo = #{
+        timestamp => second_timestamp(),
+        stdout_progress_line => ProgressLine
+    },
+    State#state{start_info = ST0#{MethodId => StartInfo}}.
+
+-spec method_progress_label(Method) -> unicode:chardata() when
+    Method :: method_id().
+method_progress_label(Method) ->
+    io_lib:format("~tw", [Method]).
+
+-spec on_shared_state(hook_state(), Caller, Default, Action) -> {A, hook_state()} when
+    Caller :: cth_tpx_role:responsibility(),
+    Default :: A,
+    Action :: fun((shared_state()) -> {A, shared_state()}).
+on_shared_state(HookState = #{role := Role, server := Handle}, Caller, Default, Action) ->
+    case cth_tpx_role:is_responsible(Role, Caller) of
+        true ->
+            A = cth_tpx_server:modify(Handle, Action),
+            {A, HookState};
+        false ->
+            {Default, HookState}
+    end.
+
+-spec modify_shared_state(hook_state(), Caller, Action) -> hook_state() when
+    Caller :: cth_tpx_role:responsibility(),
+    Action :: fun((shared_state()) -> shared_state()).
+modify_shared_state(HookState, Caller, Action) ->
+    {ok, NewHookState} = on_shared_state(HookState, Caller, _Default = ok, fun(State) ->
+        {ok, Action(State)}
+    end),
+    NewHookState.
+
+-spec is_running_in_sandcastle() -> boolean().
+is_running_in_sandcastle() ->
+    case os:getenv("SANDCASTLE_DIFF_ID") of
+        [$D | _] ->
+            true;
+        _ ->
+            case os:getenv("SANDCASTLE") of
+                false -> false;
+                _ -> true
+            end
+    end.
diff --git a/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_role.erl b/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_role.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_role.erl
@@ -0,0 +1,131 @@
+%%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%%
+%%% This source code is licensed under both the MIT license found in the
+%%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%%% of this source tree.
+
+%% @format
+-module(cth_tpx_role).
+-moduledoc """
+## What are cth_tpx roles??
+
+### Context
+
+We first need to understand in which order CT calls hook
+callbacks when a suite has more than one hook installed.
+
+Let's assume we have two hooks cth_a and cth_b, and cth_a has
+higher priority than cth_b (so lower numerical value). Then
+CT will call the the hooks in the following order (we show
+suite stuff, group and testcase is the same):
+
+    cth_a:pre_init_per_suite
+    cth_b:pre_init_per_suite
+    cth_a:post_init_per_suite
+    cth_b:post_init_per_suite
+    ...
+    cth_b:pre_end_per_suite
+    cth_a:pre_end_per_suite
+    cth_b:post_end_per_suite
+    cth_a:post_end_per_suite
+
+In particular:
+    - cth_b sees cth_a's results for pre_init_per_suite and post_init_per_suite
+    - cth_a sees cth_b's results for pre_end_per_suite and post_end_per_suite
+
+NB. The order for the post_* functions is arguably wrong, but (historical) reasons
+https://github.com/erlang/otp/issues/7397
+
+### Problem
+
+We want cth_tpx to be able to detect when a group/suite function failed, even
+if the failure comes from a hook. But as we can see, it doesn't matter if we
+give it the highest or lower priority, it will not see the result coming from
+some other hook.
+
+Also we want to compute how long a testcase takes to run, but we will either
+fail to account for the time due to hooks on the init or the end functions.
+
+### Solutions
+
+So we need instead two versions of cth_tpx hook running at the same time, each
+with a different role, that we call "top" and "bot", and with a different
+priorities:
+
+- `top` has the maximum priority (min numerical value), `bot` has the minimum priority
+- `top` handles all the `pre_init_per_*` callbacks, since it runs first there and can
+   compute start_times accurately
+- `top`  handles all `post_end_*` callbacks, since it runs last there and can
+   see all failures from other hooks
+- `bot` is the dual, so handles `pre_end_per_*` and `post_init_per_*` for the same reason
+- `top` also handles common initializations, since it's `init/2` function is called first
+""".
+-compile(warn_missing_spec_all).
+
+-export([
+    role_priority/1,
+    is_responsible/2
+]).
+
+-export_type([
+    role/0,
+    responsibility/0
+]).
+
+-type role() :: top | bot.
+
+-doc """
+Default hook priority for the role
+- In CT, the hook with the lowest numerical value has "highest priority" and is
+  initialized first
+- In Erlang, integers are unbounded. We want top/bot to have "highest" and "lowest"
+  priority, but there is no such thing, so we do a best effort approach and
+  pick INT64_MIN and INT64_MAX. If a user really wants to bypass this, of course,
+  they will.
+""".
+-spec role_priority(role()) -> integer().
+role_priority(top) ->
+    INT64_MIN = -9223372036854775808,
+    INT64_MIN;
+role_priority(bot) ->
+    INT64_MAX = 9223372036854775807,
+    INT64_MAX.
+
+-type responsibility() ::
+    pre_init_per_suite
+    | post_init_per_suite
+    | pre_init_per_group
+    | post_init_per_group
+    | pre_init_per_testcase
+    | post_init_per_testcase
+    | on_tc_fail
+    | on_tc_skip
+    | pre_end_per_suite
+    | post_end_per_suite
+    | pre_end_per_group
+    | post_end_per_group
+    | pre_end_per_testcase
+    | post_end_per_testcase
+    | terminate.
+
+-doc """
+Partition of responsibilities among both roles
+""".
+-spec is_responsible(role(), responsibility()) -> boolean().
+is_responsible(top, pre_init_per_suite) -> true;
+is_responsible(bot, post_init_per_suite) -> true;
+is_responsible(top, pre_init_per_group) -> true;
+is_responsible(bot, post_init_per_group) -> true;
+is_responsible(top, pre_init_per_testcase) -> true;
+is_responsible(bot, post_init_per_testcase) -> true;
+is_responsible(top, on_tc_fail) -> true;
+is_responsible(top, on_tc_skip) -> true;
+is_responsible(bot, pre_end_per_suite) -> true;
+is_responsible(top, post_end_per_suite) -> true;
+is_responsible(bot, pre_end_per_group) -> true;
+is_responsible(top, post_end_per_group) -> true;
+is_responsible(bot, pre_end_per_testcase) -> true;
+is_responsible(top, post_end_per_testcase) -> true;
+is_responsible(top, terminate) -> true;
+is_responsible(_, _) -> false.
diff --git a/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_server.erl b/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_server.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_server.erl
@@ -0,0 +1,79 @@
+%%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%%
+%%% This source code is licensed under both the MIT license found in the
+%%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%%% of this source tree.
+
+%% @format
+-module(cth_tpx_server).
+-compile([warn_missing_spec_all]).
+
+-behaviour(gen_server).
+
+%% Public API
+-export([
+    start_link/1,
+    get/1,
+    modify/2
+]).
+
+%% gen_server callbacks
+-export([
+    init/1,
+    handle_call/3,
+    handle_cast/2,
+    handle_info/2
+]).
+
+-export_type([
+    handle/0
+]).
+
+-type handle() :: pid().
+
+-type state() :: cth_tpx:shared_state().
+
+-type call_reqs() ::
+    get
+    | {modify, fun((state()) -> {term(), state()})}.
+
+%% ---- PUBLIC API ---------
+-spec start_link(InitialState :: state()) -> handle().
+start_link(InitialState) ->
+    {ok, Handle} = gen_server:start_link(?MODULE, InitialState, []),
+    Handle.
+
+-spec get(Handle :: handle()) -> CurrentState :: state().
+get(Handle) ->
+    call(Handle, get).
+
+-spec modify(Handle :: handle(), Fun :: fun((state()) -> {A, state()})) -> A.
+modify(Handle, Fun) ->
+    call(Handle, {modify, Fun}).
+
+%% ---- gen_server callbacks ----------
+
+-spec call(Handle :: handle(), Req :: call_reqs()) -> dynamic().
+call(Handle, Req) ->
+    gen_server:call(Handle, Req, 6000).
+
+-spec init(InitialState :: state()) -> {ok, state()}.
+init(InitialState) ->
+    {ok, InitialState}.
+
+-spec handle_call(Req :: call_reqs(), From :: term(), State :: state()) ->
+    {reply, Reply :: term(), NewState :: state()}.
+handle_call(get, _From, State) ->
+    {reply, State, State};
+handle_call({modify, Fun}, _From, State) ->
+    {A, NewState} = Fun(State),
+    {reply, A, NewState}.
+
+-spec handle_cast(Request :: term(), State :: term()) -> {noreply, NewState :: term()}.
+handle_cast(_, State) ->
+    {noreply, State}.
+
+-spec handle_info(Info :: term(), State :: term()) -> {noreply, NewState :: term()}.
+handle_info(_, State) ->
+    {noreply, State}.
diff --git a/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_test_tree.erl b/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_test_tree.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/cth_hooks/src/cth_tpx_test_tree.erl
@@ -0,0 +1,470 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(cth_tpx_test_tree).
+-compile([warn_missing_spec_all]).
+
+%% Public API
+-export([
+    new_node/1,
+    new_leaf/1,
+
+    register_result/4,
+    collect_results/3
+]).
+
+-export_type([
+    tree/0,
+    tree_node/0,
+    test_leaf/0,
+
+    name/0,
+
+    method_result/0,
+    collected_method_result/0,
+    collected_result/0,
+    outcome/0,
+
+    group_path/0,
+    method_id/0
+]).
+
+-include("method_ids.hrl").
+
+-import(common_util, [unicode_characters_to_list/1]).
+
+-type tree() :: test_leaf() | tree_node().
+
+-type option(Type) :: Type | none.
+
+-type name() :: string() | atom().
+
+-type tree_node() :: #{
+    name := name(),
+    type := node,
+    init_method := option(method_result()),
+    end_method := option(method_result()),
+    test_cases := #{name() => test_leaf()},
+    sub_groups := #{name() => tree_node()}
+}.
+
+-type test_leaf() :: #{
+    name := name(),
+    type := leaf,
+    init_method := option(method_result()),
+    end_method := option(method_result()),
+    main_method := option(method_result())
+}.
+
+-type method_result() :: #{
+    name := name(),
+    start_time => float(),
+    end_time => float(),
+    start_progress_marker => binary(),
+    end_progress_marker => binary(),
+    outcome := outcome(),
+    details := unicode:chardata()
+}.
+
+-type collected_method_result() :: #{
+    name := name(),
+    start_time => float(),
+    end_time => float(),
+    outcome := outcome(),
+    details := unicode:chardata(),
+    std_out := unicode:chardata()
+}.
+
+-type outcome() ::
+    passed | failed | timeout | skipped | omitted | infra_failure.
+
+-type group_path() :: [atom()].
+
+-type collected_result() :: #{
+    inits := [collected_method_result()],
+    main := collected_method_result(),
+    ends := [collected_method_result()]
+}.
+
+%% Tree creation and update
+
+-doc """
+Creates a new node
+""".
+-spec new_node(Name :: name()) -> tree_node().
+new_node(Name) ->
+    #{
+        name => Name,
+        type => node,
+        init_method => none,
+        end_method => none,
+        test_cases => #{},
+        sub_groups => #{}
+    }.
+
+-doc """
+Creates a new leaf
+""".
+-spec new_leaf(Name :: name()) -> test_leaf().
+new_leaf(Name) ->
+    #{
+        name => Name,
+        type => leaf,
+        init_method => none,
+        end_method => none,
+        main_method => none
+    }.
+
+-doc """
+Puts the test result inside the tree.
+""".
+-spec register_result(tree_node(), method_result(), group_path(), method_id()) -> tree_node().
+register_result(TreeResult, Result, Groups, MethodId) ->
+    insert_result(TreeResult, Result, lists:reverse(Groups), MethodId).
+
+-doc """
+Inserts the method_result inside the tree.
+""".
+-spec insert_result(Node, Result, ReversedPath, MethodId) -> Node when
+    Node :: tree_node(),
+    Result :: method_result(),
+    ReversedPath :: group_path(),
+    MethodId :: method_id().
+insert_result(TreeNode, ResultTest, [Group | Groups], MethodId) ->
+    #{sub_groups := Children} = TreeNode,
+    GroupNode = maps:get(Group, Children, new_node(Group)),
+    NewChildren = Children#{Group => insert_result(GroupNode, ResultTest, Groups, MethodId)},
+    TreeNode#{sub_groups => NewChildren};
+insert_result(TreeNode, ResultTest, [], MethodId) ->
+    case MethodId of
+        Init when Init =:= ?INIT_PER_SUITE; Init =:= ?INIT_PER_GROUP ->
+            TreeNode#{init_method => ResultTest};
+        End when End =:= ?END_PER_SUITE; End =:= ?END_PER_GROUP ->
+            TreeNode#{end_method => ResultTest};
+        {NameCase, Phase} ->
+            #{test_cases := Cases} = TreeNode,
+            TestLeaf = maps:get(NameCase, Cases, new_leaf(NameCase)),
+            NewTestLeaf =
+                case Phase of
+                    ?INIT_PER_TESTCASE ->
+                        TestLeaf#{init_method => ResultTest};
+                    ?MAIN_TESTCASE ->
+                        TestLeaf#{main_method => ResultTest};
+                    ?END_PER_TESTCASE ->
+                        TestLeaf#{end_method => ResultTest}
+                end,
+            TreeNode#{test_cases => Cases#{NameCase => NewTestLeaf}}
+    end.
+
+%% Collecting results
+
+-doc """
+Provides a result for the RequestedResults based on the collected results.
+The format of the requested_results is a map from a list of groups to the list of test_cases that are sub-cases from the last group from the list.
+""".
+-spec collect_results(TreeResult, RequestedResults, CollectedStdOut) -> [collected_result()] when
+    TreeResult :: tree(),
+    RequestedResults :: #{group_path() => [atom()]},
+    CollectedStdOut :: ct_stdout:collected_stdout().
+collect_results(TreeResult, RequestedResults, CollectedStdOut) ->
+    [
+        collect_result(TreeResult, Groups, CaseRequest, CollectedStdOut)
+     || Groups := CasesRequests <- RequestedResults,
+        CaseRequest <- CasesRequests
+    ].
+
+-doc """
+Provides a result for a given specific requested_result.
+""".
+-spec collect_result(TreeResult, Groups, TestCase, CollectedStdOut) -> collected_result() when
+    TreeResult :: tree(),
+    Groups :: group_path(),
+    TestCase :: atom(),
+    CollectedStdOut :: ct_stdout:collected_stdout().
+collect_result(TreeResult, Groups, TestCase, CollectedStdOut) ->
+    QualifiedName = common_util:qualified_name(lists:reverse(Groups), TestCase),
+    LeafResult = collect_result(TreeResult, [], [], Groups, TestCase, QualifiedName, CollectedStdOut),
+    #{ends := EndsResults, main := MainResult} = LeafResult,
+    MainResultWithEndFailure = report_end_failure(EndsResults, MainResult),
+    LeafResult#{main => MainResultWithEndFailure}.
+
+-spec report_end_failure(MethodResults, ResultAcc) -> Result when
+    MethodResults :: [collected_method_result()],
+    ResultAcc :: collected_method_result(),
+    Result :: collected_method_result().
+report_end_failure([], ResultAcc) ->
+    ResultAcc;
+report_end_failure([#{outcome := passed} | Rest], ResultAcc) ->
+    report_end_failure(Rest, ResultAcc);
+report_end_failure([#{outcome := skipped} | Rest], ResultAcc) ->
+    report_end_failure(Rest, ResultAcc);
+report_end_failure(
+    [#{outcome := EndOutcome, details := EndDetails, name := EndName} | Rest],
+    #{name := TestName, outcome := ResultOutcome, details := ResultDetails} = ResultAcc
+) ->
+    MergedOutcome = merge_outcome(EndOutcome, ResultOutcome),
+    EndFailedDetails = io_lib:format(~"~tp ~tp because ~tp failed with~n~ts", [
+        TestName, MergedOutcome, EndName, EndDetails
+    ]),
+
+    MergedDetails =
+        case ResultOutcome of
+            passed ->
+                EndFailedDetails;
+            _ ->
+                io_lib:format("~ts~n~n~ts", [ResultDetails, EndFailedDetails])
+        end,
+    report_end_failure(Rest, ResultAcc#{outcome => MergedOutcome, details => MergedDetails}).
+
+%% A genuine failure or timeout outranks an infra failure, so that a real breakage is
+%% never masked behind an infra label (tpx applies the same precedence when it
+%% reconciles a retry against its previous attempt).
+-spec merge_outcome(outcome(), outcome()) -> outcome().
+merge_outcome(failed, _) -> failed;
+merge_outcome(_, failed) -> failed;
+merge_outcome(timeout, _) -> timeout;
+merge_outcome(_, timeout) -> timeout;
+merge_outcome(infra_failure, _) -> infra_failure;
+merge_outcome(_, infra_failure) -> infra_failure;
+merge_outcome(skipped, _) -> skipped;
+merge_outcome(_, skipped) -> skipped;
+merge_outcome(passed, Other) -> Other.
+
+-doc """
+Collects all the inits / ends methods results linked to a requested_result.
+""".
+-spec collect_result(Node, Inits, Ends, Groups, TestCase, QualifiedName, CollectedStdOut) -> collected_result() when
+    Node :: tree(),
+    Inits :: [collected_method_result()],
+    Ends :: [collected_method_result()],
+    Groups :: group_path(),
+    TestCase :: atom(),
+    QualifiedName :: string(),
+    CollectedStdOut :: ct_stdout:collected_stdout().
+collect_result(Node, Inits, Ends, Groups, TestCase, QualifiedName, CollectedStdOut) ->
+    {NewInits, OptMain, NewEnds} = collect_node(Node, Inits, Ends, QualifiedName, CollectedStdOut),
+    case OptMain of
+        none ->
+            {Child, NewGroups} = get_child(Node, Groups, TestCase),
+            collect_result(Child, NewInits, NewEnds, NewGroups, TestCase, QualifiedName, CollectedStdOut);
+        MainResult ->
+            #{inits => lists:reverse(NewInits), main => MainResult, ends => NewEnds}
+    end.
+
+-spec get_child(Node, Groups, TestCase) -> {tree(), group_path()} when
+    Node :: tree(),
+    Groups :: group_path(),
+    TestCase :: atom().
+get_child(#{sub_groups := SubGroups}, [Group | Groups], _TestCase) ->
+    {maps:get(Group, SubGroups, new_node(Group)), Groups};
+get_child(#{test_cases := TestCases}, [], TestCase) ->
+    {maps:get(TestCase, TestCases, new_leaf(TestCase)), []}.
+
+-doc """
+Collect the results from init_testcase, end_testcase and the main testcase for a given requested result.
+Proceeds with some additional logic if the result is missing or skipped.
+""".
+-spec collect_node(Tree, Inits, Ends, QualName, CollectedStdOut) ->
+    {
+        NewInits :: [collected_method_result()],
+        MainResult :: option(collected_method_result()),
+        NewEnds :: [collected_method_result()]
+    }
+when
+    Tree :: tree(),
+    Inits :: [collected_method_result()],
+    Ends :: [collected_method_result()],
+    QualName :: string(),
+    CollectedStdOut :: ct_stdout:collected_stdout().
+collect_node(
+    #{type := leaf} = TestLeaf,
+    Inits,
+    Ends,
+    QualifiedName,
+    CollectedStdOut
+) ->
+    #{init_method := OptMethodInit, end_method := OptMethodEnd, main_method := OptMethodMain} = TestLeaf,
+    {NewInits, NewEnds} = update_inits_ends(Inits, Ends, OptMethodInit, OptMethodEnd, CollectedStdOut),
+    InitsPassed = lists:all(
+        fun
+            (#{outcome := failed}) -> false;
+            (#{outcome := timeout}) -> false;
+            (#{outcome := infra_failure}) -> false;
+            (_) -> true
+        end,
+        NewInits
+    ),
+    %% Do NOT try to collect a result when one of the inits failed
+    MainResult =
+        case {InitsPassed, OptMethodMain} of
+            {false, _} ->
+                get_missing_result(NewInits, QualifiedName, CollectedStdOut);
+            {true, none} ->
+                get_missing_result(NewInits, QualifiedName, CollectedStdOut);
+            {true, Result} ->
+                case maps:get(outcome, Result) of
+                    skipped -> handle_skipped_result(NewInits, Result, CollectedStdOut);
+                    _ -> to_collected_method_result(Result, CollectedStdOut)
+                end
+        end,
+    {NewInits, MainResult, NewEnds};
+collect_node(
+    #{type := node} = TreeNode,
+    Inits,
+    Ends,
+    _QualifiedName,
+    CollectedStdOut
+) ->
+    #{init_method := OptMethodInit, end_method := OptMethodEnd} = TreeNode,
+    {NewInits, NewEnds} = update_inits_ends(Inits, Ends, OptMethodInit, OptMethodEnd, CollectedStdOut),
+    {NewInits, none, NewEnds}.
+
+-spec update_inits_ends(Inits, Ends, MethInit, MethEnd, CollectedStdOut) ->
+    {NewInits :: [collected_method_result()], NewEnds :: [collected_method_result()]}
+when
+    Inits :: [collected_method_result()],
+    Ends :: [collected_method_result()],
+    MethInit :: option(method_result()),
+    MethEnd :: option(method_result()),
+    CollectedStdOut :: ct_stdout:collected_stdout().
+update_inits_ends(Inits, Ends, OptMethodInit, OptMethodEnd, CollectedStdOut) ->
+    NewInits =
+        case OptMethodInit of
+            none -> Inits;
+            _ -> [to_collected_method_result(OptMethodInit, CollectedStdOut) | Inits]
+        end,
+    NewEnds =
+        case OptMethodEnd of
+            none -> Ends;
+            _ -> [to_collected_method_result(OptMethodEnd, CollectedStdOut) | Ends]
+        end,
+    {NewInits, NewEnds}.
+
+-doc """
+Creates a method_result for a requested method for which no result was registered.
+Attempts to locate if one of the inits is responsible for the missing result.
+""".
+-spec get_missing_result(Inits, QualifiedName, CollectedStdOut) -> collected_method_result() when
+    Inits :: [collected_method_result()],
+    QualifiedName :: string(),
+    CollectedStdOut :: ct_stdout:collected_stdout().
+get_missing_result(Inits, QualifiedName, CollectedStdOut) ->
+    MainResult =
+        #{
+            name => unicode_characters_to_list(
+                io_lib:format("~ts.[main_testcase]", [QualifiedName])
+            ),
+            outcome => failed,
+            details => ~"no results for this test were recorded"
+        },
+    handle_skipped_result(Inits, MainResult, CollectedStdOut).
+
+-doc """
+Attributes a test case that left no result of its own, or that reports itself as
+`skipped`, to the init that is responsible for it.
+
+`Inits` runs innermost first, and the first one that did not pass is the one blamed: the
+case takes that init's outcome, with a message naming the init and quoting its details.
+`failed`, `timeout`, `infra_failure`, and `skipped` therefore carry through as
+themselves; an `omitted` init is blamed as a failure. When every init passed,
+`MainResult` stands.
+""".
+-spec handle_skipped_result(Inits, MainResult, CollectedStdOut) -> collected_method_result() when
+    Inits :: [collected_method_result()],
+    MainResult :: method_result(),
+    CollectedStdOut :: ct_stdout:collected_stdout().
+handle_skipped_result([], MainResult, CollectedStdOut) ->
+    to_collected_method_result(MainResult, CollectedStdOut);
+handle_skipped_result([Init | Inits], MainResult = #{name := Name}, CollectedStdOut) ->
+    InitStdOut = io_lib:format(~"~ts stdout: ~ts", [maps:get(name, Init), maps:get(std_out, Init)]),
+    case maps:get(outcome, Init) of
+        failed ->
+            #{
+                name => Name,
+                outcome => failed,
+                details =>
+                    io_lib:format(
+                        ~"Failed because init ~ts failed, with error message:\n ~ts",
+                        [maps:get(name, Init), maps:get(details, Init)]
+                    ),
+
+                std_out => InitStdOut
+            };
+        timeout ->
+            #{
+                name => Name,
+                outcome => timeout,
+                details =>
+                    io_lib:format(
+                        ~"Timed-out because init ~ts timed-out, with error message:\n ~ts",
+                        [maps:get(name, Init), maps:get(details, Init)]
+                    ),
+
+                std_out => InitStdOut
+            };
+        infra_failure ->
+            #{
+                name => Name,
+                outcome => infra_failure,
+                details =>
+                    io_lib:format(
+                        ~"Infra failure because init ~ts hit an infra failure, with error message:\n ~ts",
+                        [maps:get(name, Init), maps:get(details, Init)]
+                    ),
+
+                std_out => InitStdOut
+            };
+        passed ->
+            handle_skipped_result(Inits, MainResult, CollectedStdOut);
+        skipped ->
+            #{
+                name => Name,
+                outcome => skipped,
+                details =>
+                    io_lib:format(
+                        ~"Skipped because init ~ts was skipped, with reason:\n ~ts",
+                        [maps:get(name, Init), maps:get(details, Init)]
+                    ),
+
+                std_out => InitStdOut
+            };
+        omitted ->
+            #{
+                name => Name,
+                outcome => failed,
+                details =>
+                    io_lib:format(
+                        ~"Failed because init ~ts was omitted, with error message:\n ~ts",
+                        [maps:get(name, Init), maps:get(details, Init)]
+                    ),
+
+                std_out => InitStdOut
+            }
+    end.
+
+-spec to_collected_method_result(MethodResult, CollectedStdOut) -> collected_method_result() when
+    MethodResult :: method_result(),
+    CollectedStdOut :: ct_stdout:collected_stdout().
+to_collected_method_result(MethodResult, CollectedStdOut) ->
+    StdOut =
+        case MethodResult of
+            #{start_progress_marker := Marker} ->
+                case maps:get(Marker, CollectedStdOut) of
+                    StdOutBin when is_binary(StdOutBin) -> StdOutBin;
+                    {truncated, StdOutBin} ->
+                        io_lib:format(
+                            "NOTICE: stdout was truncated! See ~ts for the full logs of the suite.~n~n...~ts", [
+                                ct_stdout:filename(), StdOutBin
+                            ]
+                        )
+                end;
+            _ ->
+                ~""
+        end,
+    MethodResult1 = maps:without([start_progress_marker, end_progress_marker], MethodResult),
+    MethodResult1#{std_out => StdOut}.
diff --git a/buck2/prelude/erlang/common_test/cth_hooks/src/method_ids.hrl b/buck2/prelude/erlang/common_test/cth_hooks/src/method_ids.hrl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/cth_hooks/src/method_ids.hrl
@@ -0,0 +1,30 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-ifndef(CTH_TPX_METHOD_IDS_HRL).
+-define(CTH_TPX_METHOD_IDS, true).
+
+-define(INIT_PER_SUITE, '[init_per_suite]').
+-define(INIT_PER_GROUP, '[init_per_group]').
+-define(INIT_PER_TESTCASE, '[init_per_testcase]').
+-define(END_PER_TESTCASE, '[end_per_testcase]').
+-define(END_PER_GROUP, '[end_per_group]').
+-define(END_PER_SUITE, '[end_per_suite]').
+-define(MAIN_TESTCASE, '[main_testcase]').
+
+-type method_id() ::
+    ?INIT_PER_SUITE
+    | ?INIT_PER_GROUP
+    | ?INIT_PER_TESTCASE
+    | ?END_PER_TESTCASE
+    | ?END_PER_GROUP
+    | ?END_PER_SUITE
+    | {atom(), ?INIT_PER_TESTCASE | ?END_PER_TESTCASE | ?MAIN_TESTCASE}.
+
+% CTH_TPX_METHOD_IDS_HRL
+-endif.
diff --git a/buck2/prelude/erlang/common_test/test_binary/BUCK b/buck2/prelude/erlang/common_test/test_binary/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_binary/BUCK
@@ -0,0 +1,27 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+erlang_application(
+    name = "test_binary",
+    srcs = glob([
+        "src/*.erl",
+        "src/*.hrl",
+    ]),
+    applications = [
+        "kernel",
+        "stdlib",
+        "prelude//erlang/common_test/common:common",
+        "prelude//erlang/common_test/cth_hooks:cth_hooks",
+        "prelude//erlang/common_test/test_exec:test_exec",
+    ],
+    erl_opts = [
+        "+debug_info",
+        "+warnings_as_errors",
+    ],
+    includes = glob(["include/*.hrl"]),
+    use_global_parse_transforms = False,
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/erlang/common_test/test_binary/src/json_interfacer.erl b/buck2/prelude/erlang/common_test/test_binary/src/json_interfacer.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_binary/src/json_interfacer.erl
@@ -0,0 +1,165 @@
+%% % @format
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+-module(json_interfacer).
+-moduledoc """
+Methods used for serialization to the type
+defined in tpx [here](https://www.internalfb.com/code/fbsource/[bb9e81daacad]/fbcode/testinfra/tpx/tpx-output/src/erl_parser.rs).
+""".
+-compile(warn_missing_spec_all).
+
+-export([write_json_output/4, format_json/3, status_name/1]).
+
+-import(common_util, [unicode_characters_to_binary/1]).
+
+-define(RESULT_EXEC_VERSION, 1).
+
+-define(PASSED, <<"PASSED">>).
+-define(FAILED, <<"FAILED">>).
+-define(SKIPPED, <<"SKIPPED">>).
+-define(TIMEOUT, <<"TIMEOUT">>).
+-define(OMITTED, <<"OMITTED">>).
+-define(INFRA_FAILURE, <<"INFRA_FAILURE">>).
+
+-type status() :: passed | failed | skipped | timeout | omitted | infra_failure.
+
+%% The integers are the discriminants of `TestStatusErl` in erl_parser.rs. 4 is FATAL
+%% and 6 is unused there; do not reuse them for anything else.
+-spec status(status()) -> integer().
+status(passed) -> 1;
+status(failed) -> 2;
+status(skipped) -> 3;
+status(timeout) -> 5;
+status(omitted) -> 7;
+status(infra_failure) -> 8.
+
+-spec status_name(integer()) -> status().
+status_name(1) -> passed;
+status_name(2) -> failed;
+status_name(3) -> skipped;
+status_name(5) -> timeout;
+status_name(7) -> omitted;
+status_name(8) -> infra_failure.
+
+-spec summary(status()) -> binary().
+summary(passed) -> ?PASSED;
+summary(failed) -> ?FAILED;
+summary(skipped) -> ?SKIPPED;
+summary(timeout) -> ?TIMEOUT;
+summary(omitted) -> ?OMITTED;
+summary(infra_failure) -> ?INFRA_FAILURE.
+
+-type formatted_result() ::
+    #{
+        name := binary(),
+        status := integer(),
+        summary := binary(),
+        details := binary(),
+        durationSecs := float(),
+        std_out := binary(),
+        endedTime => integer()
+    }.
+
+-type collected_result() :: cth_tpx_test_tree:collected_result().
+
+-type formatted_case_result() ::
+    #{
+        inits := [formatted_result()],
+        main := formatted_result(),
+        ends := [formatted_result()]
+    }.
+
+-type formatted_output() ::
+    #{
+        version := pos_integer(),
+        status := integer(),
+        summary := binary(),
+        details := binary(),
+        test_results := [formatted_case_result()]
+    }.
+
+-spec write_json_output(file:filename_all(), status(), unicode:chardata(), [collected_result()]) ->
+    {ok, file:filename_all()}.
+write_json_output(OutputDir, SuiteStatus, SuiteDetails, TpxResults) ->
+    OuptputFile = filename:join(OutputDir, "result_exec.json"),
+    file:write_file(
+        OuptputFile, format_json(SuiteStatus, SuiteDetails, TpxResults), [raw, binary]
+    ),
+    {ok, OuptputFile}.
+
+-spec format_json(status(), unicode:chardata(), [collected_result()]) -> iodata().
+format_json(SuiteStatus, SuiteDetails, TpxResults) ->
+    json:encode(format_output(SuiteStatus, SuiteDetails, TpxResults)).
+
+-spec format_output(status(), unicode:chardata(), [collected_result()]) -> formatted_output().
+format_output(SuiteStatus, SuiteDetails, TpxResults) ->
+    #{
+        version => ?RESULT_EXEC_VERSION,
+        status => status(SuiteStatus),
+        summary => summary(SuiteStatus),
+        details => unicode_characters_to_binary(SuiteDetails),
+        test_results => [format_case(CaseResult) || CaseResult <- TpxResults]
+    }.
+
+-spec format_case(collected_result()) -> formatted_case_result().
+format_case(
+    #{
+        inits := Inits,
+        main := Main,
+        ends := Ends
+    } = _CaseResult
+) ->
+    #{
+        inits => [format_method_result(Elem) || Elem <:- Inits],
+        main => format_method_result(Main),
+        ends => [format_method_result(Elem) || Elem <:- Ends]
+    }.
+
+-spec format_method_result(cth_tpx_test_tree:collected_method_result()) -> formatted_result().
+format_method_result(
+    #{
+        name := Name,
+        start_time := Start,
+        end_time := End,
+        outcome := Outcome,
+        details := Details,
+        std_out := StdOut
+    } = _TestResult
+) ->
+    #{
+        name => name_to_binary(Name),
+        endedTime => trunc(End),
+        durationSecs => End - Start,
+        status => status(Outcome),
+        summary => summary(Outcome),
+        details => unicode_characters_to_binary(Details),
+        std_out => unicode_characters_to_binary(StdOut)
+    };
+format_method_result(
+    #{
+        name := Name,
+        outcome := Outcome,
+        details := Details,
+        std_out := StdOut
+    } = _TestResult
+) ->
+    #{
+        name => name_to_binary(Name),
+        status => status(Outcome),
+        summary => summary(Outcome),
+        details => unicode_characters_to_binary(Details),
+        std_out => unicode_characters_to_binary(StdOut),
+        durationSecs => 0.0
+    }.
+
+-spec name_to_binary(Name) -> binary() when
+    Name :: cth_tpx_test_tree:name().
+name_to_binary(Name) when is_atom(Name) ->
+    atom_to_binary(Name);
+name_to_binary(Name) when is_list(Name) ->
+    unicode_characters_to_binary(Name).
diff --git a/buck2/prelude/erlang/common_test/test_binary/src/listing_interfacer.erl b/buck2/prelude/erlang/common_test/test_binary/src/listing_interfacer.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_binary/src/listing_interfacer.erl
@@ -0,0 +1,48 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(listing_interfacer).
+
+-compile(warn_missing_spec_all).
+
+-export([produce_json_file/2]).
+
+-include_lib("common/include/tpx_records.hrl").
+
+-import(common_util, [unicode_characters_to_binary/1]).
+
+-spec produce_json_file(OutputDir, TestCase) -> ok when
+    OutputDir :: file:filename_all(),
+    TestCase :: #test_spec_test_case{}.
+produce_json_file(OutputDir, TestCase) ->
+    Filename = filename:join(OutputDir, ~"result"),
+    {ok, Fd} = file:open(Filename, [write, raw, binary]),
+    try
+        lists:foreach(
+            fun(TestInfo) ->
+                TestInfoJson = test_info_to_json_line(TestInfo),
+                ok = file:write(Fd, [TestInfoJson, ~"\n"])
+            end,
+            TestCase#test_spec_test_case.testcases
+        )
+    after
+        file:close(Fd)
+    end.
+
+-spec test_info_to_json_line(TestInfo) -> iodata() when
+    TestInfo :: #test_spec_test_info{}.
+test_info_to_json_line(TestInfo) ->
+    {M, F, A} = TestInfo#test_spec_test_info.breakpoint,
+    BreakpointFun = unicode_characters_to_binary(io_lib:format(~"~s:~s/~p", [M, F, A])),
+
+    % NB. json:encode() guarantees the output is in one line
+    json:encode(#{
+        testcase => TestInfo#test_spec_test_info.name,
+        filter => TestInfo#test_spec_test_info.filter,
+        breakpoint => #{type => function, functionName => BreakpointFun}
+    }).
diff --git a/buck2/prelude/erlang/common_test/test_binary/src/test_binary.erl b/buck2/prelude/erlang/common_test/test_binary/src/test_binary.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_binary/src/test_binary.erl
@@ -0,0 +1,336 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(test_binary).
+-compile(warn_missing_spec_all).
+
+-export([main/0]).
+
+-import(common_util, [unicode_characters_to_binary/1, unicode_characters_to_list/1, filename_all_to_filename/1]).
+
+-include_lib("common/include/buck_ct_records.hrl").
+-include_lib("common/include/tpx_records.hrl").
+-include_lib("kernel/include/logger.hrl").
+
+-spec main() -> no_return().
+main() ->
+    Args = init:get_plain_arguments(),
+    run_action_and_halt(fun() -> argparse:run(Args, cli(), #{}) end).
+
+-spec cli() -> argparse:command().
+cli() ->
+    #{
+        handler => fun handle_list_and_run/1,
+        arguments => [
+            #{
+                name => test_info_file,
+                long => "-test-info-file",
+                type => string,
+                required => true
+            },
+            #{
+                name => edb_code,
+                long => "-edb-code",
+                type => string,
+                default => none,
+                help =>
+                    "EDB code to inject for debugging. Can be actual code or the environment variable that contains the code."
+            },
+            #{
+                name => start_epmd,
+                long => "-no-epmd",
+                action => {store, false},
+                default => true,
+                help => "Don't start epmd on a random port."
+            }
+        ],
+        commands => #{
+            "list" => #{
+                handler => fun handle_list/1,
+                arguments => [
+                    #{name => output_dir, long => "-output-dir", type => string, required => true},
+
+                    % --json flag is now a no-op, to be removed once all callers are fixed
+                    #{name => json, long => "-json", type => boolean, required => false}
+                ]
+            },
+            "run" => #{
+                handler => fun handle_run/1,
+                arguments => [
+                    #{name => output_dir, long => "-output-dir", type => string, required => true},
+                    #{name => tests, type => string, nargs => list, default => []}
+                ]
+            }
+        }
+    }.
+
+-type list_args() :: #{
+    test_info_file := file:filename(),
+    output_dir := file:filename()
+}.
+
+-type run_args() :: #{
+    test_info_file := file:filename(),
+    output_dir := file:filename(),
+    tests := [string()],
+    start_epmd := boolean(),
+    edb_code := string() | none
+}.
+
+-type list_and_run_args() :: #{
+    test_info_file := file:filename(),
+    start_epmd := boolean(),
+    edb_code := string() | none
+}.
+
+-spec handle_list(Args) -> ok when
+    Args :: list_args().
+handle_list(Args) ->
+    try
+        #{output_dir := OutputDir} = Args,
+        test_logger:set_up_logger(OutputDir, test_listing, no_capture_stdout),
+        ok = listing(Args),
+        ?LOG_DEBUG("Listing done"),
+        ok
+    catch
+        Class:Reason:StackTrace ->
+            ErrorMsg = erl_error:format_exception(Class, Reason, StackTrace),
+            io:format(standard_error, "Listing failed:~n~ts", [ErrorMsg]),
+            erlang:halt(1)
+    end.
+
+-spec handle_run(Args) -> ok when
+    Args :: run_args().
+handle_run(Args) ->
+    #{output_dir := OutputDir, edb_code := EdbCode} = Args,
+    LoggingType =
+        case EdbCode of
+            none ->
+                capture_stdout;
+            _ ->
+                os:putenv("ERLANG_BUCK_DEBUG_PRINT", "disabled"),
+                no_capture_stdout
+        end,
+    test_logger:set_up_logger(OutputDir, test_runner, LoggingType),
+    ok = running(Args),
+    ?LOG_DEBUG("Running done"),
+    ok.
+
+-spec handle_list_and_run(Args) -> ok | {exit_code, 1} when
+    Args :: list_and_run_args().
+handle_list_and_run(Args) ->
+    %% without test runner support we run all tests and need to create our own test dir
+    OutputDir = string:trim(os:cmd("mktemp -d")),
+    test_logger:set_up_logger(OutputDir, test_runner, no_capture_stdout),
+    os:putenv("ERLANG_BUCK_DEBUG_PRINT", "disabled"),
+    case list_and_run(Args, OutputDir) of
+        true ->
+            io:format("~nAt least one test didn't pass!~nYou can find the test output directory here: ~ts~n", [
+                OutputDir
+            ]),
+            {exit_code, 1};
+        false ->
+            ok
+    end.
+
+-spec run_action_and_halt(Action) -> no_return() when
+    Action :: fun(() -> ok | {exit_code, non_neg_integer()}).
+run_action_and_halt(Action) ->
+    ExitCode =
+        try Action() of
+            ok -> 0;
+            {exit_code, N} when is_integer(N) -> N
+        catch
+            Class:Reason:StackTrace ->
+                ?LOG_ERROR(erl_error:format_exception(Class, Reason, StackTrace)),
+                1
+        after
+            test_logger:flush()
+        end,
+    erlang:halt(ExitCode).
+
+-spec load_suite(binary()) -> atom().
+load_suite(SuitePath) ->
+    Path = filename:rootname(filename:absname(SuitePath)),
+    {module, Module} = code:load_abs(filename_all_to_filename(Path)),
+    Module.
+
+-spec get_hooks(#test_info{}) -> [module()].
+get_hooks(TestInfo) ->
+    Hooks = lists:append(proplists:get_all_values(ct_hooks, TestInfo#test_info.ct_opts)),
+    [
+        case HookSpec of
+            {HookModule, _InitArguments} when is_atom(HookModule) -> HookModule;
+            {HookModule, _InitArguments, Priority} when is_atom(HookModule), is_integer(Priority) -> HookModule;
+            HookModule when is_atom(HookModule) -> HookModule
+        end
+     || HookSpec <- Hooks
+    ].
+
+-spec listing(Args) -> ok when
+    Args :: list_args().
+listing(Args) ->
+    #{test_info_file := TestInfoFile, output_dir := OutputDir} = Args,
+    TestInfo = test_info:load_from_file(TestInfoFile),
+    Listing = get_listing(TestInfo, OutputDir),
+    listing_interfacer:produce_json_file(OutputDir, Listing).
+
+-spec running(Args) -> ok when
+    Args :: run_args().
+running(Args) ->
+    #{
+        test_info_file := TestInfoFile,
+        output_dir := OutputDir,
+        tests := Tests,
+        start_epmd := StartEpmd,
+        edb_code := EdbCode
+    } = Args,
+    AbsOutputDir = filename:absname(OutputDir),
+    TestInfo0 = test_info:load_from_file(TestInfoFile),
+    Listing = get_listing(TestInfo0, AbsOutputDir),
+    ExtraEmuFlags = edb_extra_emu_flags(EdbCode),
+    Timeout = max_timeout(TestInfo0, EdbCode),
+    StdoutStreaming = stdout_streaming(EdbCode),
+
+    TestInfo1 = TestInfo0#test_info{extra_flags = ExtraEmuFlags ++ TestInfo0#test_info.extra_flags},
+    case StartEpmd of
+        false -> application:set_env(test_exec, global_epmd_port, global_epmd_port());
+        true -> ok
+    end,
+    test_runner:run_tests(Tests, TestInfo1, AbsOutputDir, Listing, Timeout, StdoutStreaming).
+
+-spec get_listing(TestInfo, OutputDir) -> #test_spec_test_case{} when
+    TestInfo :: #test_info{},
+    OutputDir :: file:filename_all().
+get_listing(TestInfo, OutputDir) ->
+    code:add_paths(TestInfo#test_info.dependencies),
+    Suite = load_suite(TestInfo#test_info.test_suite),
+
+    {ok, ProjectRoot} = file:get_cwd(),
+    true = os:putenv("PROJECT_ROOT", ProjectRoot),
+
+    InitProviderState = #init_provider_state{
+        output_dir = filename_all_to_filename(OutputDir),
+        suite = Suite,
+        raw_target = TestInfo#test_info.raw_target
+    },
+    Providers0 = [
+        buck_ct_provider:do_init(Provider, InitProviderState)
+     || Provider <- TestInfo#test_info.providers
+    ],
+    HookModules = get_hooks(TestInfo),
+    Providers1 = [buck_ct_provider:do_pre_listing(Provider) || Provider <- Providers0],
+    Listing = list_test:list_tests(Suite, HookModules),
+    Providers2 = [buck_ct_provider:do_post_listing(Provider) || Provider <- Providers1],
+    [buck_ct_provider:do_terminate(Provider) || Provider <- Providers2],
+    Listing.
+
+%% rudimantary implementation for running tests with buck2 open-sourced test runner
+
+-spec list_and_run(Args, OutputDir) -> boolean() when
+    Args :: list_and_run_args(),
+    OutputDir :: file:filename().
+list_and_run(Args, OutputDir) ->
+    #{test_info_file := TestInfoFile} = Args,
+    TestInfo = test_info:load_from_file(TestInfoFile),
+    Listing = get_listing(TestInfo, OutputDir),
+    Tests = listing_to_testnames(Listing),
+    running(Args#{output_dir => OutputDir, tests => Tests}),
+    ResultsFile = filename:join(OutputDir, "result_exec.json"),
+    print_results(ResultsFile).
+
+-spec listing_to_testnames(#test_spec_test_case{}) -> [string()].
+listing_to_testnames(Listing) ->
+    [
+        unicode_characters_to_list(TestCase#test_spec_test_info.name)
+     || TestCase <- Listing#test_spec_test_case.testcases
+    ].
+
+-spec global_epmd_port() -> inet:port_number().
+global_epmd_port() ->
+    case os:getenv("ERL_EPMD_PORT") of
+        false -> 4369;
+        Port -> list_to_integer(Port)
+    end.
+
+-spec edb_extra_emu_flags(EdbCode) -> [binary()] when
+    EdbCode :: string() | none.
+edb_extra_emu_flags(none) ->
+    [];
+edb_extra_emu_flags(EdbCode) ->
+    CodeToInject =
+        case os:getenv(EdbCode) of
+            false -> unicode_characters_to_binary(EdbCode);
+            Value -> unicode_characters_to_binary(Value)
+        end,
+    [~"-eval", CodeToInject].
+
+-spec max_timeout(TestInfo, EdbCode) -> timeout() when
+    TestInfo :: #test_info{},
+    EdbCode :: string() | none.
+max_timeout(_TestInfo, EdbCode) when EdbCode /= none ->
+    % We are in a debugging session, so we don't want to ever timeout the suite
+    infinity;
+max_timeout(TestInfo, _EdbCode = none) ->
+    case os:getenv("TPX_TIMEOUT_SEC") of
+        false ->
+            CtOpts = TestInfo#test_info.ct_opts,
+            Multiplier = proplists:get_value(multiply_timetraps, CtOpts, 1),
+            %% 9 minutes 30 seconds, giving us 30 seconds to crash multiplied by multiply_timetraps
+            round(Multiplier * (9 * 60 + 30) * 1000);
+        StrTimeout ->
+            InputTimeout = list_to_integer(StrTimeout),
+            case InputTimeout of
+                _ when InputTimeout > 30 -> (InputTimeout - 30) * 1000;
+                _ -> error("Please allow at least 30s for the binary to execute")
+            end
+    end.
+
+-spec stdout_streaming(EdbCode) -> output_to_stdout | no_output_to_stdout when
+    EdbCode :: string() | none.
+stdout_streaming(none) -> no_output_to_stdout;
+stdout_streaming(_) -> output_to_stdout.
+
+-spec print_results(file:filename()) -> boolean().
+print_results(ResultsFile) ->
+    {ok, Data} = file:read_file(ResultsFile, [raw]),
+    #{<<"status">> := SuiteStatus, <<"test_results">> := Results} = json:decode(Data),
+    {Summary, AnyTestFailure} = lists:foldl(fun print_individual_results/2, {#{}, false}, Results),
+    io:format("~n~10s: ~b~n~n", ["TOTAL", lists:sum(maps:values(Summary))]),
+    [
+        io:format("~10ts: ~b~n", [json_interfacer:status_name(Result), Amount])
+     || Result := Amount <- Summary
+    ],
+    AnyTestFailure orelse json_interfacer:status_name(SuiteStatus) =/= passed.
+
+-spec print_individual_results(map(), Acc) -> Acc when Acc :: {#{non_neg_integer() => non_neg_integer()}, boolean()}.
+print_individual_results(Result, {Summary, AnyFailure}) ->
+    #{<<"main">> := #{<<"details">> := Details, <<"status">> := Status, <<"std_out">> := StdOut}} = Result,
+    NewAnyFailure =
+        case json_interfacer:status_name(Status) of
+            passed ->
+                AnyFailure;
+            skipped ->
+                print_details(StdOut, Details),
+                AnyFailure;
+            omitted ->
+                AnyFailure;
+            _NotPassed ->
+                print_details(StdOut, Details),
+                true
+        end,
+    {Summary#{Status => maps:get(Status, Summary, 0) + 1}, NewAnyFailure}.
+
+-spec print_details(StdOut, Details) -> ok when
+    StdOut :: unicode:chardata(),
+    Details :: unicode:chardata().
+print_details(StdOut, Details) ->
+    io:format("~ts~n", [StdOut]),
+    io:format("~ts~n", [Details]),
+    io:format("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -~n"),
+    io:format("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -~n").
diff --git a/buck2/prelude/erlang/common_test/test_binary/src/test_info.erl b/buck2/prelude/erlang/common_test/test_binary/src/test_info.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_binary/src/test_info.erl
@@ -0,0 +1,163 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(test_info).
+-compile(warn_missing_spec_all).
+
+-export([load_from_file/1, write_to_file/2, try_make_path_relative/1]).
+-export_type([test_info/0]).
+
+-include_lib("common/include/buck_ct_records.hrl").
+
+-type test_info() :: #test_info{}.
+
+-import(common_util, [unicode_characters_to_list/1, unicode_characters_to_binary/1]).
+
+-spec load_from_file(file:filename_all()) -> test_info().
+load_from_file(TestInfoFile) ->
+    {ok, Content} = file:read_file(TestInfoFile, [raw]),
+    #{
+        <<"dependencies">> := Dependencies,
+        <<"test_suite">> := SuiteName,
+        <<"test_dir">> := TestDir,
+        <<"config_files">> := ConfigFiles,
+        <<"providers">> := Providers,
+        <<"ct_opts">> := CtOpts,
+        <<"extra_ct_hooks">> := ExtraCtHooks,
+        <<"erl_cmd">> := [ErlExec | ErlFlags],
+        <<"extra_flags">> := ExtraFlags,
+        <<"artifact_annotation_mfa">> := ArtifactAnnotationMFA,
+        <<"common_app_env">> := CommonAppEnv,
+        <<"raw_target">> := RawTarget,
+        <<"trampolines">> := Trampolines
+    } = json:decode(Content),
+    Providers1 = buck_ct_parser:parse_str(Providers),
+    CtOpts1 = make_ct_opts(
+        buck_ct_parser:parse_str(CtOpts),
+        [buck_ct_parser:parse_str(CTH) || CTH <- ExtraCtHooks]
+    ),
+    {ok, ParsedArtifactAnnotationMFA} = parse_mfa(ArtifactAnnotationMFA),
+    #test_info{
+        dependencies = [unicode_characters_to_list(make_path_absolute(Dep)) || Dep <- Dependencies],
+        test_suite = filename:join((TestDir), [SuiteName, ".beam"]),
+        config_files = [make_path_absolute(ConfigFile) || ConfigFile <- ConfigFiles],
+        providers = Providers1,
+        artifact_annotation_mfa = ParsedArtifactAnnotationMFA,
+        ct_opts = CtOpts1,
+        erl_cmd = [unicode_characters_to_binary(normalize_erl_cmd(ErlExec)) | ErlFlags],
+        extra_flags = ExtraFlags,
+        common_app_env = CommonAppEnv,
+        raw_target = RawTarget,
+        trampolines = [unicode_characters_to_binary(make_path_absolute(Trampoline)) || [Trampoline] <- Trampolines]
+    }.
+
+-spec write_to_file(file:filename_all(), test_info()) -> ok | {error, Reason :: term()}.
+write_to_file(FileName, TestInfo) ->
+    #test_info{
+        dependencies = Dependencies,
+        test_suite = SuiteBeamPath,
+        config_files = ConfigFiles,
+        providers = Providers,
+        artifact_annotation_mfa = ArtifactAnnotationMFA,
+        ct_opts = CtOpts,
+        erl_cmd = [ErlCmd | ErlFlags],
+        extra_flags = ExtraFlags,
+        common_app_env = CommonAppEnv,
+        raw_target = RawTarget,
+        trampolines = Trampolines
+    } = TestInfo,
+    ErlTermToStr = fun(Term) -> unicode_characters_to_binary(io_lib:format("~tp", [Term])) end,
+    Json = #{
+        <<"dependencies">> => [try_make_path_relative(Dep) || Dep <- Dependencies],
+        <<"test_suite">> => filename:basename(SuiteBeamPath, ".beam"),
+        <<"test_dir">> => filename:dirname(SuiteBeamPath),
+        <<"config_files">> => [try_make_path_relative(ConfigFile) || ConfigFile <- ConfigFiles],
+        <<"providers">> => ErlTermToStr(Providers),
+        <<"ct_opts">> => ErlTermToStr(CtOpts),
+        <<"extra_ct_hooks">> => [],
+        <<"erl_cmd">> => [try_make_path_relative(ErlCmd) | ErlFlags],
+        <<"extra_flags">> => ExtraFlags,
+        <<"artifact_annotation_mfa">> => ErlTermToStr(ArtifactAnnotationMFA),
+        <<"common_app_env">> => CommonAppEnv,
+        <<"raw_target">> => RawTarget,
+        <<"trampolines">> => Trampolines
+    },
+    file:write_file(FileName, json:encode(Json), [raw, binary]).
+
+-spec normalize_erl_cmd(file:filename_all()) -> file:filename_all().
+normalize_erl_cmd(ErlCmd) when is_binary(ErlCmd) ->
+    case os:find_executable(binary_to_list(ErlCmd)) of
+        false -> make_path_absolute(ErlCmd);
+        AbsolutePath -> AbsolutePath
+    end.
+
+-spec make_path_absolute(file:filename_all()) -> file:filename_all().
+make_path_absolute(Path) ->
+    case os:getenv("REPO_ROOT") of
+        false -> filename:absname(Path);
+        RepoRoot -> filename:join(RepoRoot, Path)
+    end.
+
+%% Length guard: lists:split/2 throws badarg (not a non-matching tuple)
+%% when Path has fewer components than BaseDir.
+-spec try_make_path_relative(file:filename_all()) -> file:filename_all().
+try_make_path_relative(Path) ->
+    case filename:pathtype(Path) of
+        relative ->
+            Path;
+        _ ->
+            BaseDir =
+                case os:getenv("REPO_ROOT") of
+                    false ->
+                        {ok, CWD} = file:get_cwd(),
+                        CWD;
+                    RepoRoot ->
+                        RepoRoot
+                end,
+            BaseDirParts = filename:split(BaseDir),
+            PathParts = filename:split(Path),
+            case length(PathParts) >= length(BaseDirParts) andalso lists:split(length(BaseDirParts), PathParts) of
+                {BaseDirParts, RelativeParts} -> filename:join(RelativeParts);
+                _ -> Path
+            end
+    end.
+
+-spec parse_mfa(binary()) -> {ok, artifact_annotations:annotation_function()} | {error, term()}.
+parse_mfa(MFA) ->
+    case erl_scan:string(unicode_characters_to_list(MFA)) of
+        {ok,
+            [
+                {'fun', _},
+                {atom, _, Module},
+                {':', _},
+                {atom, _, Function},
+                {'/', _},
+                {integer, _, 1}
+            ],
+            _} when is_atom(Module), is_atom(Function) ->
+            {ok, fun Module:Function/1};
+        {ok,
+            [
+                {atom, _, Module},
+                {':', _},
+                {atom, _, Function},
+                {'/', _},
+                {integer, _, 1}
+            ],
+            _} when is_atom(Module), is_atom(Function) ->
+            {ok, fun Module:Function/1};
+        Reason ->
+            {error, Reason}
+    end.
+
+-type ctopt() :: term().
+-type cth() :: module() | {module(), term()}.
+
+-spec make_ct_opts([ctopt()], [cth()]) -> [ctopt()].
+make_ct_opts(CtOpts, []) -> CtOpts;
+make_ct_opts(CtOpts, ExtraCtHooks) -> [{ct_hooks, ExtraCtHooks} | CtOpts].
diff --git a/buck2/prelude/erlang/common_test/test_binary/src/test_runner.erl b/buck2/prelude/erlang/common_test/test_binary/src/test_runner.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_binary/src/test_runner.erl
@@ -0,0 +1,527 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(test_runner).
+-compile(warn_missing_spec_all).
+
+-export([run_tests/6]).
+
+-include_lib("common/include/tpx_records.hrl").
+-include_lib("common/include/buck_ct_records.hrl").
+-include_lib("kernel/include/logger.hrl").
+
+-import(common_util, [unicode_characters_to_list/1, unicode_characters_to_binary/1]).
+
+-define(DEFAULT_OUTPUT_FORMAT, json).
+-define(MAX_STDOUT_BYTES_PER_TESTCASE, (16 * 1024)).
+
+-spec run_tests(Tests, TestInfo, OutputDir, Listing, Timeout, StdoutStreaming) -> ok when
+    Tests :: [string()],
+    TestInfo :: #test_info{},
+    OutputDir :: file:filename_all(),
+    Listing :: #test_spec_test_case{},
+    Timeout :: timeout(),
+    StdoutStreaming :: output_to_stdout | no_output_to_stdout.
+run_tests(Tests, #test_info{} = TestInfo, OutputDir, Listing, Timeout, StdoutStreaming) ->
+    check_ct_opts(TestInfo#test_info.ct_opts),
+    Suite =
+        case filename:basename(TestInfo#test_info.test_suite, ".beam") of
+            SuiteBin when is_binary(SuiteBin) -> binary_to_atom(SuiteBin);
+            SuiteStr when is_list(SuiteStr) -> list_to_atom(SuiteStr)
+        end,
+    StructuredTests = [common_util:parse_test_name(Test, Suite) || Test <- Tests],
+    case StructuredTests of
+        [] ->
+            throw(no_tests_to_run);
+        [_ | _] ->
+            TestSpecFile = filename:join(OutputDir, "test_spec.spec"),
+            OrderedTests = reorder_tests(StructuredTests, Listing),
+
+            execute_test_suite(
+                #test_env{
+                    output_format = ?DEFAULT_OUTPUT_FORMAT,
+                    suite = Suite,
+                    tests = OrderedTests,
+                    suite_path = TestInfo#test_info.test_suite,
+                    output_dir = OutputDir,
+                    dependencies = TestInfo#test_info.dependencies,
+                    test_spec_file = TestSpecFile,
+                    config_files = TestInfo#test_info.config_files,
+                    providers = TestInfo#test_info.providers,
+                    ct_opts = TestInfo#test_info.ct_opts,
+                    common_app_env = TestInfo#test_info.common_app_env,
+                    erl_cmd = TestInfo#test_info.erl_cmd,
+                    extra_flags = TestInfo#test_info.extra_flags,
+                    artifact_annotation_mfa = TestInfo#test_info.artifact_annotation_mfa,
+                    raw_target = TestInfo#test_info.raw_target,
+                    trampolines = TestInfo#test_info.trampolines,
+                    timeout = Timeout,
+                    ct_stdout_fingerprint = ct_stdout:make_fingerprint(),
+                    ct_stdout_streaming = StdoutStreaming,
+                    result_recipient = self()
+                }
+            )
+    end.
+
+-doc """
+Prepare the test spec and run the test.
+""".
+-spec execute_test_suite(TestEnv) -> ok when
+    TestEnv :: #test_env{}.
+execute_test_suite(TestEnv) ->
+    #test_env{
+        suite = Suite,
+        tests = Tests,
+        suite_path = SuitePath,
+        output_dir = OutputDir,
+        test_spec_file = TestSpecFile,
+        ct_opts = CtOpts,
+        timeout = Timeout
+    } = TestEnv,
+    TestSpec = build_test_spec(
+        Suite,
+        Tests,
+        filename:absname(filename:dirname(SuitePath)),
+        OutputDir,
+        CtOpts,
+        TestEnv#test_env.ct_stdout_fingerprint
+    ),
+    FormattedSpec = [io_lib:format("~tp.~n", [Entry]) || Entry <- TestSpec],
+    file:write_file(TestSpecFile, FormattedSpec, [raw, binary]),
+    NewTestEnv = TestEnv#test_env{test_spec_file = TestSpecFile, ct_opts = CtOpts},
+    try run_test(NewTestEnv, Timeout) of
+        ok -> ok
+    catch
+        Class:Reason:StackTrace ->
+            ErrorMsg = io_lib:format("run_test failed due to ~ts\n", [
+                erl_error:format_exception(Class, Reason, StackTrace)
+            ]),
+            ?LOG_ERROR(ErrorMsg),
+            test_run_fail(NewTestEnv, ErrorMsg, #{})
+    end.
+
+-spec run_test(TestEnv, Timeout) -> ok when
+    TestEnv :: #test_env{},
+    Timeout :: timeout().
+run_test(TestEnv, Timeout) ->
+    application:set_env(test_exec, test_env, TestEnv, [{persistent, true}]),
+    case application:ensure_all_started(test_exec, temporary) of
+        {ok, _Apps} ->
+            Ref = erlang:monitor(process, test_exec_sup, []),
+            receive
+                {'DOWN', Ref, _Type, Object, Info} ->
+                    test_run_fail(
+                        TestEnv,
+                        io_lib:format(
+                            "unexpected exception in the buck2 Common Test runner:\n"
+                            "                        application test_exec crashed (~tp ~tp) ~n",
+                            [Object, Info]
+                        ),
+                        #{}
+                    );
+                {run_succeed, Result, ProgressMarkersOffsets} ->
+                    ensure_test_exec_stopped(),
+                    test_run_succeed(TestEnv, Result, ProgressMarkersOffsets);
+                {run_failed, Result, ProgressMarkersOffsets} ->
+                    ensure_test_exec_stopped(),
+                    test_run_fail(TestEnv, Result, ProgressMarkersOffsets)
+            after Timeout ->
+                ensure_test_exec_stopped(),
+                ErrorMsg =
+                    "\n************************\n"
+                    "* the suite timed out. *\n"
+                    "************************\n",
+                test_run_timeout(TestEnv, ErrorMsg)
+            end;
+        {error, Reason} ->
+            ErrorMsg = io_lib:format("TextExec failed to start due to ~tp", [Reason]),
+
+            ?LOG_ERROR(ErrorMsg),
+            test_run_fail(TestEnv, ErrorMsg, #{})
+    end.
+
+-spec ensure_test_exec_stopped() -> ok.
+ensure_test_exec_stopped() ->
+    {Pid, Monitor} = erlang:spawn_monitor(fun() -> application:stop(test_exec) end),
+    receive
+        {'DOWN', Monitor, process, Pid, _} -> ok
+    after 5000 -> ok
+    end.
+
+-doc """
+Provides result as specified by the tpx protocol when test failed to ran.
+""".
+-spec test_run_fail(TestEnv, Reason, ProgressMarkersOffsets) -> ok when
+    TestEnv :: #test_env{},
+    Reason :: unicode:chardata(),
+    ProgressMarkersOffsets :: #{ct_stdout:progress_line() => ct_stdout:offset()}.
+test_run_fail(TestEnv, Reason, ProgressMarkersOffsets) ->
+    provide_output_file(
+        TestEnv,
+        io_lib:format("Test failed to ran due to ~ts", [Reason]),
+        failed,
+        ProgressMarkersOffsets
+    ).
+
+-spec test_run_timeout(#test_env{}, string()) -> ok.
+test_run_timeout(TestEnv, Reason) ->
+    provide_output_file(TestEnv, Reason, timeout, #{}).
+
+-doc """
+Provides result as specified by the tpx protocol when test succeed to ran.
+""".
+-spec test_run_succeed(TestEnv, Reason, ProgressMarkersOffsets) -> ok when
+    TestEnv :: #test_env{},
+    Reason :: unicode:chardata(),
+    ProgressMarkersOffsets :: #{ct_stdout:progress_line() => ct_stdout:offset()}.
+test_run_succeed(TestEnv, Reason, ProgressMarkersOffsets) ->
+    provide_output_file(TestEnv, Reason, passed, ProgressMarkersOffsets).
+
+-doc """
+Provides result as specified by the tpx protocol.
+""".
+-spec provide_output_file(TestEnv, ResultExec, Status, ProgressMarkersOffsets) -> ok when
+    TestEnv :: #test_env{},
+    ResultExec :: unicode:chardata(),
+    Status :: failed | passed | timeout,
+    ProgressMarkersOffsets :: #{ct_stdout:progress_line() => ct_stdout:offset()}.
+provide_output_file(
+    #test_env{
+        output_dir = OutputDir,
+        tests = Tests,
+        suite = Suite,
+        artifact_annotation_mfa = ArtifactAnnotationFunction
+    },
+    ResultExec,
+    Status,
+    ProgressMarkersOffsets
+) ->
+    LogFile = test_logger:get_log_file(OutputDir, ct_executor),
+    StdOutFile = ct_stdout:filename(OutputDir),
+    LogFilesForCrashes = #{
+        ct_executor_log => LogFile,
+        ct_executor_stdout => StdOutFile
+    },
+
+    ResultsFile = filename:join(OutputDir, "result.json"),
+    Results =
+        case Status of
+            failed ->
+                collect_results_broken_run(
+                    Tests, Suite, ~"internal crash", ResultExec, LogFilesForCrashes
+                );
+            timeout ->
+                % Once the suite watchdog fires, group/suite teardown may not
+                % have completed, so no testcase has an independent verdict.
+                [];
+            passed ->
+                case file:read_file(ResultsFile, [raw]) of
+                    {ok, JsonFile} ->
+                        TreeResults = decode_erlang_term(JsonFile),
+                        case TreeResults of
+                            undefined ->
+                                ErrorMsg =
+                                    io_lib:format(
+                                        ~"ct failed to produced results valid file ~tp", [
+                                            ResultsFile
+                                        ]
+                                    ),
+                                collect_results_broken_run(
+                                    Tests, Suite, ErrorMsg, ResultExec, LogFilesForCrashes
+                                );
+                            _ ->
+                                {ok, CollectedStdOut} = ct_stdout:collect_method_stdout(
+                                    StdOutFile,
+                                    ProgressMarkersOffsets,
+                                    TreeResults,
+                                    ?MAX_STDOUT_BYTES_PER_TESTCASE
+                                ),
+                                collect_results_fine_run(TreeResults, Tests, CollectedStdOut)
+                        end;
+                    {error, _Reason} ->
+                        ErrorMsg = io_lib:format(~"ct failed to produced results file ~tp", [
+                            ResultsFile
+                        ]),
+                        collect_results_broken_run(
+                            Tests, Suite, ErrorMsg, ResultExec, LogFilesForCrashes
+                        )
+                end
+        end,
+
+    {ok, _ResultOuptuFile} =
+        json_interfacer:write_json_output(OutputDir, Status, ResultExec, Results),
+    test_artifact_directory:link_to_artifact_dir(
+        StdOutFile, OutputDir, ArtifactAnnotationFunction
+    ),
+    test_artifact_directory:link_to_artifact_dir(
+        test_logger:get_std_out(OutputDir, test_runner), OutputDir, ArtifactAnnotationFunction
+    ),
+    test_artifact_directory:prepare(OutputDir, Tests, ArtifactAnnotationFunction).
+
+-spec decode_erlang_term(Bin :: binary()) -> dynamic().
+decode_erlang_term(Bin) ->
+    binary_to_term(Bin).
+
+-spec trimmed_content_file(File) -> unicode:chardata() when
+    File :: file:filename_all().
+trimmed_content_file(File) ->
+    case file:open(File, [read, raw, binary]) of
+        {error, Reason} ->
+            io_lib:format(~"No ~tp file found, reason ~tp ", [filename:basename(File), Reason]);
+        {ok, FD} ->
+            try
+                case file:position(FD, {eof, -5000}) of
+                    {error, _} ->
+                        {ok, _} = file:position(FD, bof),
+                        case file:read(FD, 5000) of
+                            {ok, Data} -> Data;
+                            eof -> io_lib:format(~"nothing to read from ~ts", [File])
+                        end;
+                    {ok, _} ->
+                        {ok, EndOfFile} = file:read(FD, 5000),
+                        io_lib:format(~"~ts~nFile truncated, see ~tp for full output", [
+                            EndOfFile,
+                            filename:basename(File)
+                        ])
+                end
+            of
+                Content -> Content
+            after
+                file:close(FD)
+            end
+    end.
+
+-doc """
+Provide tpx with a result when CT failed to provide results for tests.
+""".
+-spec collect_results_broken_run(Tests, Suite, ErrorMsg, ResultExec, RelevantLogFiles) ->
+    [cth_tpx_test_tree:collected_result()]
+when
+    Tests :: [#ct_test{}],
+    Suite :: module(),
+    ErrorMsg :: unicode:chardata(),
+    ResultExec :: unicode:chardata(),
+    RelevantLogFiles :: #{
+        ct_executor_log => file:filename_all(),
+        ct_executor_stdout := file:filename_all()
+    }.
+collect_results_broken_run(Tests, _Suite, ErrorMsg, ResultExec, RelevantLogFiles) ->
+    #{ct_executor_stdout := StdOutFile} = RelevantLogFiles,
+    TrimmedStdOut = trimmed_content_file(StdOutFile),
+    StdOut =
+        case RelevantLogFiles of
+            #{ct_executor_log := ExecutorLogFile} ->
+                TrimmedExecutorLog = trimmed_content_file(ExecutorLogFile),
+                io_lib:format("ct_executor_log: ~ts ~nct_executor_stdout: ~ts", [TrimmedExecutorLog, TrimmedStdOut]);
+            _ ->
+                TrimmedStdOut
+        end,
+
+    FormattedErrorMsg = io_lib:format("~ts~n", [ErrorMsg]),
+    [
+        #{
+            ends => [],
+            inits => [],
+            main => #{
+                name => lists:flatten(
+                    io_lib:format("~ts.[main_testcase]", [
+                        % We need to reverse the list of groups as the method common_util:qualified_name expects them
+                        % in the reverse order (as it is designed to be called when exploring the tree of results
+                        % where we push at each time the group we are in, leading to them being in reverse order).
+                        common_util:qualified_name(
+                            lists:reverse(Test#ct_test.groups),
+                            Test#ct_test.test_name
+                        )
+                    ])
+                ),
+                details =>
+                    unicode_characters_to_list(
+                        io_lib:format(
+                            "~ts~ts ~n",
+                            [FormattedErrorMsg, ResultExec]
+                        )
+                    ),
+                outcome => failed,
+                std_out => unicode_characters_to_list(StdOut)
+            }
+        }
+     || Test <- Tests
+    ].
+
+-doc """
+Provide the results from the tests as specified by tpx protocol, from the json file
+provided by ct displaying results of all the tests ran.
+""".
+-spec collect_results_fine_run(TestResults, Tests, CollectedStdOut) -> [cth_tpx_test_tree:collected_result()] when
+    TestResults :: cth_tpx_test_tree:tree_node(),
+    Tests :: [#ct_test{}],
+    CollectedStdOut :: ct_stdout:collected_stdout().
+collect_results_fine_run(TreeResults, Tests, CollectedStdOut) ->
+    cth_tpx_test_tree:collect_results(
+        TreeResults, get_requested_tests_by_group_path(Tests), CollectedStdOut
+    ).
+
+-doc """
+Splits the requested tests into consecutive runs of tests sharing a (sequence) of groups.
+The list is [{[sequence of groups], [list of tests belonging to this sequence]}], in the order the
+tests were requested, so a sequence returned to later gets a further entry. That is, if the sequence
+is g1.t1, g2.t1, g1.t2, g1.t3, g2.t2, we produce:
+[{g1,[t1]}, {g2,[t1]}, {g1,[t2,t3]}, {g2,[t2]}]
+The tests are expected in listing order, the depth first traversal of all/0 with groups/0 expanded
+that reorder_tests/2 puts them in. The runs only follow the order the suite declares under that
+precondition.
+""".
+-spec get_requested_tests(Tests) -> [{GroupPath, TestCases}] when
+    Tests :: [#ct_test{}],
+    GroupPath :: cth_tpx_test_tree:group_path(),
+    TestCases :: [ct_suite:ct_testname()].
+get_requested_tests(Tests) ->
+    lists:foldr(
+        fun(#ct_test{groups = Groups, test_name = TestName}, Runs) ->
+            case Runs of
+                [{Groups, TestNames} | Rest] -> [{Groups, [TestName | TestNames]} | Rest];
+                _ -> [{Groups, [TestName]} | Runs]
+            end
+        end,
+        [],
+        Tests
+    ).
+
+-spec get_requested_tests_by_group_path(Tests) -> #{GroupPath => TestCases} when
+    Tests :: [#ct_test{}],
+    GroupPath :: cth_tpx_test_tree:group_path(),
+    TestCases :: [ct_suite:ct_testname()].
+get_requested_tests_by_group_path(Tests) ->
+    lists:foldr(
+        fun(#ct_test{groups = Groups, test_name = TestName}, Acc) ->
+            maps:update_with(Groups, fun(TestNames) -> [TestName | TestNames] end, [TestName], Acc)
+        end,
+        #{},
+        Tests
+    ).
+
+-doc """
+Built the test_spec selecting the requested tests and
+specifying the result output.
+""".
+-spec build_test_spec(Suite, Tests, TestDir, OutputDir, CtOpts, ProgressLineFingerprint) -> [term()] when
+    Suite :: module(),
+    Tests :: [#ct_test{}],
+    TestDir :: file:filename_all(),
+    OutputDir :: file:filename_all(),
+    CtOpts :: [term()],
+    ProgressLineFingerprint :: ct_stdout:fingerprint().
+build_test_spec(Suite, Tests, TestDir0, OutputDir, CtOpts, ProgressLineFingerprint) ->
+    TestDir = unicode_characters_to_list(TestDir0),
+    ListGroupTest = get_requested_tests(Tests),
+    SpecTests = lists:map(
+        fun
+            ({[], TopTests}) ->
+                {cases, TestDir, Suite, TopTests};
+            ({Groups, GroupTests}) ->
+                GroupPath = [[{Group, []} || Group <- Groups]],
+                {groups, TestDir, Suite, GroupPath, {cases, GroupTests}}
+        end,
+        ListGroupTest
+    ),
+    ResultOutput = filename:join(OutputDir, ~"result.json"),
+    {TpxCtHook, CtOpts1} = getCtHook(CtOpts, ResultOutput, ProgressLineFingerprint),
+    LogDir = set_up_log_dir(OutputDir),
+    CtOpts2 = add_spec_if_absent(
+        {auto_compile, false}, add_spec_if_absent({logdir, LogDir}, CtOpts1)
+    ),
+    SpecTests ++ [TpxCtHook] ++ CtOpts2.
+
+-doc """
+Collect all the ct_hooks entries provided by the user, and add the cth_tpx hook config.
+""".
+-spec getCtHook(CtOpts0, ResultOutput, ProgressLineFingerprint) -> {CtHooks, CtOpts1} when
+    CtOpts0 :: [term()],
+    ResultOutput :: file:filename_all(),
+    ProgressLineFingerprint :: ct_stdout:fingerprint(),
+    CtHooks :: {ct_hooks, [term()]},
+    CtOpts1 :: [term()].
+getCtHook(CtOpts0, ResultOutput, ProgressLineFingerprint) ->
+    {CtHooksOpts, CtOpts1} = lists:partition(
+        fun
+            ({ct_hooks, _}) -> true;
+            (_) -> false
+        end,
+        CtOpts0
+    ),
+    CtHooks0 = [CtHook || {ct_hooks, CtHooks = [_ | _]} <- CtHooksOpts, CtHook <- CtHooks],
+    CtHooks1 = [
+        {cth_tpx, #{role => top, ct_stdout_fingerprint => ProgressLineFingerprint, result_json => ResultOutput}},
+        {cth_tpx, #{role => bot}}
+        | CtHooks0
+    ],
+    CtHookHandle = {ct_hooks, CtHooks1},
+    {CtHookHandle, CtOpts1}.
+
+-doc """
+Add a spec tuple to the list of ct_options if a tuple defining the property isn't present yet.
+""".
+-spec add_spec_if_absent({atom(), term()}, [term()]) -> [term()].
+add_spec_if_absent({Key, Value}, CtOpts) ->
+    case lists:keyfind(Key, 1, CtOpts) of
+        false -> [{Key, Value} | CtOpts];
+        _ -> CtOpts
+    end.
+
+-spec reorder_tests(list(#ct_test{}), #test_spec_test_case{}) -> list(#ct_test{}).
+reorder_tests(Tests, #test_spec_test_case{testcases = TestCases}) ->
+    % This is the ordered lists of test from the suite as
+    % binary strings.
+    MapNameToTests = lists:foldl(
+        fun(#ct_test{canonical_name = Name} = Test, Map) -> Map#{unicode_characters_to_binary(Name) => Test} end,
+        maps:new(),
+        Tests
+    ),
+    lists:foldr(
+        fun(#test_spec_test_info{name = TestName}, ListOrdered) ->
+            case MapNameToTests of
+                #{TestName := Test} -> [Test | ListOrdered];
+                _ -> ListOrdered
+            end
+        end,
+        [],
+        TestCases
+    ).
+
+-doc """
+LogDir is the directory where ct will log to.
+Make sure it exists and returns it.
+""".
+-spec set_up_log_dir(file:filename_all()) -> file:filename_all().
+set_up_log_dir(OutputDir) ->
+    LogDir = filename:join(OutputDir, "log_dir"),
+    ok = filelib:ensure_path(LogDir),
+    LogDir.
+
+-doc """
+CtOpts must be tuple as defined here:
+https://www.erlang.org/doc/apps/common_test/run_test_chapter.html#test-specification-syntax
+that will be inserted to the test specification.
+We do not check here that those are valid, but that they do not conflict with those
+created here by the runner.
+""".
+-spec check_ct_opts([term()]) -> ok.
+check_ct_opts(CtOpts) ->
+    ProblematicsOpts = [suites, groups, cases, skip_suites, skip_groups, skip_cases],
+    lists:foreach(
+        fun(Opt) ->
+            case lists:keyfind(Opt, 1, CtOpts) of
+                false ->
+                    ok;
+                _ ->
+                    ?LOG_ERROR("Option ~tp is not supported by test runner", [Opt]),
+                    throw({non_valid_ct_opt, Opt})
+            end
+        end,
+        ProblematicsOpts
+    ).
diff --git a/buck2/prelude/erlang/common_test/test_cli_lib/BUCK b/buck2/prelude/erlang/common_test/test_cli_lib/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_cli_lib/BUCK
@@ -0,0 +1,36 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+erlang_application(
+    name = "test_cli_lib",
+    srcs = glob(["src/*.erl"]),
+    applications = ["//erlang/common_test/test_binary:test_binary"],
+    erl_opts = [
+        "+debug_info",
+        "+warnings_as_errors",
+    ],
+    labels = ["test_application"],
+    resources = [],
+    visibility = ["PUBLIC"],
+)
+
+erlang_tests(
+    contacts = ["whatsapp_testing_infra"],
+    labels = ["e2e"],
+    suites = ["test/test_cli_e2e_SUITE.erl"],
+    deps = [
+        "stdlib",
+        ":test_cli_e2e_SUITE_fixtures",
+        ":test_cli_lib",
+    ],
+)
+
+erlang_application(
+    name = "test_cli_e2e_SUITE_fixtures",
+    srcs = glob(["test/test_cli_e2e_SUITE_data/*.erl"]),
+    applications = [],
+    labels = ["test_application"],
+)
diff --git a/buck2/prelude/erlang/common_test/test_cli_lib/src/test.erl b/buck2/prelude/erlang/common_test/test_cli_lib/src/test.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_cli_lib/src/test.erl
@@ -0,0 +1,539 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(test).
+-moduledoc """
+User-Facing library for quick-iteration testing of Common Test
+
+  use test:help() for more information
+""".
+-typing([eqwalizer]).
+-compile(warn_missing_spec_all).
+
+%% Public API
+-export([
+    start/0,
+    help/0,
+    list/0, list/1,
+    rerun/1,
+    run/0, run/1,
+    reset/0,
+    logs/0
+]).
+
+%% init
+-export([
+    info/0,
+    ensure_initialized/0,
+    start_shell/0
+]).
+
+%% Test functions
+-export([
+    list_impl/1
+]).
+
+-include_lib("common/include/buck_ct_records.hrl").
+
+-define(raw_file_access, prim_file).
+
+-type test_id() :: string() | non_neg_integer() | atom().
+-type test_info() :: #{name := string(), suite := module()}.
+-type run_spec() :: test_id() | [test_info()].
+-type run_result() :: {non_neg_integer(), non_neg_integer()}.
+
+-type provided_test_info() :: test_info:test_info().
+
+-spec start() -> ok.
+start() ->
+    info(),
+    ensure_initialized().
+
+-spec info() -> ok.
+info() ->
+    io:format("~n"),
+    io:format(
+        "------------------------------------ Test Shell ------------------------------------~n"
+    ),
+    io:format(
+        "Test Shell for interactive testing. Within this shell you can run tests, and update ~n"
+    ),
+    io:format(
+        "the code by recompiling and hot-code loading it with c(module). You can also load ~n"
+    ),
+    io:format("additional modules with l(module). ~n"),
+    io:format(
+        "The `test` module provides functionality to list, run tests. Check the available  ~n"
+    ),
+    io:format("functions (test:help()): ~n~n"),
+    help(),
+    io:format("~n").
+
+-doc """
+Print a description of all available commands.
+""".
+-spec help() -> ok.
+help() ->
+    io:format("Buck2 Common Test Runner Shell Interface~n~n"),
+    [
+        print_help(F, A)
+     || {F, A} <- ?MODULE:module_info(exports),
+        not lists:member(F, [module_info, ensure_initialized, start, start_shell, list_impl])
+    ],
+    io:format("~n"),
+    io:format("For more information, use the built in help, e.g. h(test, help)~n"),
+    ok.
+
+-spec print_help(Fun :: atom(), arity()) -> ok.
+print_help(Fun, Arity) ->
+    #{args := Args, desc := [DescFirst | DescRest]} = command_description(Fun, Arity),
+    FunSig = string:pad(
+        io_lib:format("~ts:~ts(~ts)", [?MODULE, Fun, lists:join(", ", Args)]), 30, trailing
+    ),
+    io:format("~ts -- ~ts~n", [FunSig, DescFirst]),
+    Padding = string:pad("", 34),
+    [io:format("~ts~ts~n", [Padding, DescLine]) || DescLine <- DescRest],
+    ok.
+
+-spec command_description(Fun :: atom(), arity()) -> #{args := [string()], desc := [string()]}.
+command_description(help, 0) ->
+    #{args => [], desc => ["print help"]};
+command_description(info, 0) ->
+    #{args => [], desc => ["print info text"]};
+command_description(list, 0) ->
+    #{args => [], desc => ["list all available tests"]};
+command_description(list, 1) ->
+    #{
+        args => ["RegExOrModule"],
+        desc => ["same as list(), but filter tests with RegEx, or a test suite"]
+    };
+command_description(list, 2) ->
+    #{
+        args => ["Module", "RegEx"],
+        desc => ["same as list(), but filter tests with RegEx, and a test suite"]
+    };
+command_description(rerun, 1) ->
+    #{
+        args => ["IdOrRegex"],
+        desc =>
+            [
+                "runs a test with the shortest possible setup path, the test can ",
+                "be given as RegEx matching a single test, or the id from listing. ",
+                "This command does *not* recompile the test suite or its dependencies"
+            ]
+    };
+command_description(run, 0) ->
+    #{args => [], desc => ["run all tests"]};
+command_description(run, 1) ->
+    #{
+        args => ["IdOrRegex"],
+        desc =>
+            [
+                "same as rerun/1 but does compile the targeted suite, and loads",
+                "changed modules in the remote node."
+            ]
+    };
+command_description(reset, 0) ->
+    #{args => [], desc => ["restarts the test node, enabling a clean test state"]};
+command_description(logs, 0) ->
+    #{args => [], desc => ["print log files of the currently running test suites"]};
+command_description(F, A) ->
+    error({help_is_missing, {F, A}}).
+
+-doc """
+List all available tests
+""".
+-doc #{equiv => test:list("")}.
+-spec list() -> ok | {error, term()}.
+list() ->
+    list("").
+
+-doc """
+List all available tests, filters by the given RegEx. Please check
+[https://www.erlang.org/doc/man/re.html#regexp_syntax] for the supported
+regular expression syntax. If a module is given as argument, list all
+tests from that module instead
+""".
+-spec list(RegExOrModule :: module() | string()) -> ok | {error, term()}.
+list(RegEx) when is_list(RegEx) ->
+    case list_impl(RegEx) of
+        {ok, TestsString} -> io:format("~ts", [TestsString]);
+        Error -> Error
+    end.
+
+-doc """
+Run a test given by either the test id from the last list() command, or
+a regex that matches exactly one test. Tests are run with the shortest possible
+setup. This call does not recompile the test suite and its dependencies, but
+runs them as is. You can manually recompile code with c(Module).
+To reset the test state use reset().
+""".
+-spec rerun(run_spec()) -> run_result().
+rerun(Spec) ->
+    ensure_initialized(),
+    do_plain_test_run(Spec).
+
+-doc """
+update code and run all tests
+""".
+-doc #{equiv => run("")}.
+-spec run() -> run_result() | error.
+run() ->
+    run("").
+
+-doc """
+Run a test given by either the test id from the last list() command, or
+a regex that matches exactly one test. Tests are run with the shortest possible
+setup. This call does recompile the test suite and its dependencies. You can
+manually recompile code with c(Module). To reset the test state use reset().
+""".
+-spec run(string() | non_neg_integer()) -> run_result() | error.
+run(RegExOrId) ->
+    ensure_initialized(),
+    case discover(RegExOrId) of
+        [] ->
+            {0, 0};
+        ToRun ->
+            Suites = [maps:get(suite, TestMap) || TestMap <- ToRun],
+            case shell_buck2_utils:rebuild_modules(Suites) of
+                ok ->
+                    io:format("Reloading all changed modules... "),
+                    case ct_daemon:load_changed() of
+                        Loaded when is_list(Loaded) ->
+                            case erlang:length(Loaded) of
+                                0 ->
+                                    do_plain_test_run(ToRun);
+                                ChangedCount ->
+                                    io:format("reloaded ~tp modules ~tP~n", [ChangedCount, Loaded, 10]),
+                                    % There were some changes, so list the tests again, then run but without recompiling changes
+                                    % Note that if called with the RegEx instead of ToRun test list like above, do_plain_test_run/1 will list the tests again
+                                    do_plain_test_run(RegExOrId)
+                            end;
+                        node_down ->
+                            io:format("Node down!~n"),
+                            error
+                    end;
+                Error ->
+                    Error
+            end
+    end.
+
+-doc """
+restarts the test node, enabling a clean test state
+""".
+-spec reset() -> ok | {error, term()}.
+reset() ->
+    case is_debug_session() of
+        true ->
+            io:format(standard_error, "Cannot reset the test node during a debug session!", []);
+        false ->
+            Type = ct_daemon_node:get_domain_type(),
+            NodeName = ct_daemon_node:stop(),
+            #test_info{erl_cmd = ErlCmd} = get_provided_test_info(),
+            ct_daemon:start(ErlCmd, #{
+                type => Type, name => NodeName, cookie => erlang:get_cookie(), options => []
+            })
+    end.
+
+-doc """
+Print all the logs of the currently running test suites
+""".
+-spec logs() -> ok.
+logs() ->
+    ensure_initialized(),
+    case logs_impl() of
+        {ok, Logs} ->
+            lists:foreach(fun(LogPath) -> io:format("~ts~n", [LogPath]) end, Logs),
+            io:format("~n");
+        {error, not_found} ->
+            io:format("no logs found~n")
+    end.
+
+%% internal
+-spec list_impl(RegEx :: string()) -> {ok, string()} | {error, Error} when
+    Error :: node_down | {invalid_regex, {string(), non_neg_integer()}}.
+list_impl(RegEx) ->
+    ensure_initialized(),
+    case ct_daemon:list(RegEx) of
+        Tests when is_list(Tests) -> {ok, print_tests(Tests)};
+        {invalid_regex, _} = Err -> {error, Err};
+        node_down -> {error, node_down}
+    end.
+
+-spec ensure_initialized() -> ok.
+ensure_initialized() ->
+    PrintInit = lists:foldl(
+        fun(Fun, Acc) -> Fun() orelse Acc end,
+        false,
+        [
+            fun init_utility_apps/0,
+            fun init_node/0
+        ]
+    ),
+    case PrintInit of
+        true ->
+            io:format(">> initialization done << ~n", []);
+        false ->
+            ok
+    end.
+
+-spec init_utility_apps() -> boolean().
+init_utility_apps() ->
+    UtilityApps = application:get_env(test_cli_lib, utility_applications, []),
+    StartedApps = #{App => true || {App, _} <- proplists:get_value(started, application:info())},
+    StartResults = [init_utility_app(StartedApps, UtilityApp) || UtilityApp <- UtilityApps],
+    lists:any(fun(B) when is_boolean(B) -> B end, StartResults).
+
+-spec init_utility_app(StartedApps :: #{atom() => term()}, UtilityApp :: atom()) -> boolean().
+init_utility_app(StartedApps, UtilityApp) ->
+    case StartedApps of
+        #{UtilityApp := _} ->
+            false;
+        _ ->
+            io:format("starting utility application ~ts...~n", [UtilityApp]),
+            {Mod, Fun} = application:get_env(test_cli_lib, application_starter, {application, ensure_all_started}),
+            case Mod:Fun(UtilityApp) of
+                {ok, _} ->
+                    true;
+                Error ->
+                    abort("could not start utility applications:~n~tp", [Error])
+            end
+    end.
+
+-spec init_common_app_env(#{binary() => binary()}) -> ok.
+init_common_app_env(CommonAppEnv) ->
+    case map_size(CommonAppEnv) of
+        0 ->
+            ok;
+        _ ->
+            case application:load(common) of
+                ok -> ok;
+                {error, {already_loaded, common}} -> ok
+            end,
+            maps:foreach(
+                fun(Key, Value) ->
+                    KeyAtom = binary_to_atom(Key, utf8),
+                    % Only set the env if it's not already set to allow cli overrides
+                    case application:get_env(common, KeyAtom) of
+                        undefined ->
+                            ValueTerm = buck_ct_parser:parse_str(Value),
+                            application:set_env(common, KeyAtom, ValueTerm);
+                        _ ->
+                            ok
+                    end
+                end,
+                CommonAppEnv
+            ),
+            ok
+    end.
+
+-define(TYPE_IS_OK(Type), (Type =:= shortnames orelse Type =:= longnames)).
+
+-spec init_node() -> boolean().
+init_node() ->
+    case ct_daemon:alive() of
+        true ->
+            false;
+        false ->
+            io:format("starting test node...~n", []),
+            #test_info{erl_cmd = ErlCmd, common_app_env = CommonAppEnv} = get_provided_test_info(),
+            init_common_app_env(CommonAppEnv),
+            case application:get_env(test_cli_lib, node_config) of
+                undefined ->
+                    ct_daemon:start(ErlCmd);
+                {ok, {Type, NodeName, Cookie}} when ?TYPE_IS_OK(Type), is_atom(NodeName), is_atom(Cookie) ->
+                    ct_daemon:start(
+                        ErlCmd,
+                        #{
+                            name => NodeName,
+                            type => Type,
+                            cookie => Cookie,
+                            options => [{multiply_timetraps, infinity} || is_debug_session()]
+                        }
+                    )
+            end,
+            case is_debug_session() of
+                true ->
+                    spawn(fun watchdog/0);
+                false ->
+                    ok
+            end,
+            true
+    end.
+
+-spec get_provided_test_info() -> provided_test_info().
+get_provided_test_info() ->
+    case application:get_env(test_cli_lib, test_info_file, undefined) of
+        undefined ->
+            abort("test_info_file not provided.");
+        TestInfoFile when is_binary(TestInfoFile) ->
+            test_info:load_from_file(TestInfoFile)
+    end.
+
+-spec abort(Message :: string()) -> no_return().
+abort(Message) ->
+    abort(Message, []).
+
+-spec abort(Format :: string(), Args :: [term()]) -> no_return().
+abort(Format, Args) ->
+    io:format(standard_error, "ERROR: " ++ Format ++ "~n", Args),
+    io:format(standard_error, "exiting...~n", []),
+    erlang:halt(1).
+
+-spec watchdog() -> no_return().
+watchdog() ->
+    Node = ct_daemon_node:get_node(),
+    true = erlang:monitor_node(Node, true),
+    receive
+        {nodedown, Node} ->
+            io:format(
+                standard_error,
+                "The debugging session ended, terminating the test shell...~n",
+                []
+            ),
+            erlang:halt()
+    end.
+
+-spec print_tests([{module(), [{non_neg_integer(), string()}]}]) -> string().
+print_tests([]) ->
+    "no tests found\n";
+print_tests(Tests) ->
+    lists:flatten(print_tests_impl(lists:reverse(Tests))).
+
+-spec print_tests_impl([{module(), [{non_neg_integer(), string()}]}]) -> io_lib:chars().
+print_tests_impl([]) ->
+    "";
+print_tests_impl([{Suite, SuiteTests} | Rest]) ->
+    SuiteString = io_lib:format("~ts:~n", [Suite]),
+    TestsString = [io_lib:format("\t~b - ~ts~n", [Id, Test]) || {Id, Test} <- SuiteTests],
+    RestString = print_tests_impl(Rest),
+    SuiteString ++ TestsString ++ RestString.
+
+-spec is_debug_session() -> boolean().
+is_debug_session() ->
+    case application:get_env(test_cli_lib, debugger_mode, false) of
+        Value when is_boolean(Value) ->
+            Value
+    end.
+
+-spec collect_results(#{module() => [string()]}) -> #{string() => ct_daemon_core:run_result()}.
+collect_results(PerSuite) ->
+    maps:fold(
+        fun(Suite, Tests, Acc) ->
+            %% check if we need to reset the test node
+            ensure_per_suite_encapsulation(Suite),
+            io:format("running ~b test(s) for ~ts with output dir ~ts~n", [
+                erlang:length(Tests), Suite, ct_daemon:output_dir()
+            ]),
+            %% run all tests for the current SUITE
+            case ct_daemon:run({discovered, [#{suite => Suite, name => Test} || Test <- Tests]}) of
+                node_down ->
+                    io:format("test node shut down during test execution, aborting~n", []),
+                    Acc;
+                {error, Reason} ->
+                    io:format("Error selecting tests to run: ~p~n", [Reason]),
+                    Acc;
+                RunResult ->
+                    maps:merge(
+                        Acc,
+                        RunResult
+                    )
+            end
+        end,
+        #{},
+        PerSuite
+    ).
+
+-spec ensure_per_suite_encapsulation(module()) -> ok.
+ensure_per_suite_encapsulation(Suite) ->
+    case ct_daemon:setup_state() of
+        undefined ->
+            ok;
+        Setup ->
+            case lists:reverse(Setup) of
+                [Suite | _] ->
+                    ok;
+                _ ->
+                    %% restart node and preserver listing
+                    reset(),
+                    ok
+            end
+    end.
+
+-spec discover(string() | non_neg_integer() | atom()) -> [test_info()].
+discover(RegExOrId) ->
+    StringOrId =
+        case is_atom(RegExOrId) of
+            true ->
+                atom_to_list(RegExOrId);
+            false ->
+                RegExOrId
+        end,
+    case ct_daemon:discover(StringOrId) of
+        {error, not_listed_yet} ->
+            ct_daemon:list(""),
+            discover(RegExOrId);
+        {error, Reason} ->
+            io:format("cannot run tests ~0p: ~0p~n", [RegExOrId, Reason]),
+            [];
+        node_down ->
+            io:format("test node unexpectedly down~n"),
+            [];
+        [] ->
+            io:format("no tests found for ~0p~n", [RegExOrId]),
+            [];
+        Tests ->
+            Tests
+    end.
+
+-spec do_plain_test_run(run_spec()) -> run_result().
+do_plain_test_run([#{} | _] = ToRun) ->
+    PerSuite = maps:groups_from_list(
+        fun(#{suite := Suite}) -> Suite end,
+        fun(#{name := Name}) -> Name end,
+        ToRun
+    ),
+    Results = collect_results(PerSuite),
+    io:format("~n", []),
+    Result =
+        {Passed, Total} = maps:fold(
+            fun(Name, Result, {Passed, Total}) ->
+                ct_daemon_printer:print_result(Name, Result),
+                case Result of
+                    pass_result -> {Passed + 1, Total + 1};
+                    _ -> {Passed, Total + 1}
+                end
+            end,
+            {0, 0},
+            Results
+        ),
+    ct_daemon_printer:print_summary(Total, Passed, Total - Passed),
+    Result;
+do_plain_test_run(RegExOrId) ->
+    case discover(RegExOrId) of
+        [] -> {0, 0};
+        ToRun -> do_plain_test_run(ToRun)
+    end.
+
+-spec start_shell() -> ok | {error, already_started}.
+start_shell() ->
+    shell:start_interactive().
+
+-spec logs_impl() -> {ok, [file:filename_all()]} | {error, not_found}.
+logs_impl() ->
+    case ct_daemon:priv_dir() of
+        undefined ->
+            {error, not_found};
+        PrivDir ->
+            PatternLog = filename:join(PrivDir, "*.log"),
+            LogPaths = filelib:wildcard(PatternLog, ".", ?raw_file_access),
+            PatternLogJson = filename:join(PrivDir, "*.log.json"),
+            LogJsonPaths = filelib:wildcard(PatternLogJson, ".", ?raw_file_access),
+            AllLogs = lists:sort(LogPaths ++ LogJsonPaths),
+            {ok, AllLogs}
+    end.
diff --git a/buck2/prelude/erlang/common_test/test_cli_lib/src/test_cli_lib.erl b/buck2/prelude/erlang/common_test/test_cli_lib/src/test_cli_lib.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_cli_lib/src/test_cli_lib.erl
@@ -0,0 +1,68 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(test_cli_lib).
+-moduledoc """
+Entrypoint for the interactive Common Test shell.
+""".
+-typing([eqwalizer]).
+-compile(warn_missing_spec_all).
+
+%% Public API
+-export([start/0]).
+
+-spec start() -> ok.
+start() ->
+    case application:load(test_cli_lib) of
+        ok -> ok;
+        {error, {already_loaded, test_cli_lib}} -> ok
+    end,
+
+    case application:get_env(test_cli_lib, preamble) of
+        undefined ->
+            standard_preamble();
+        {ok, Preamble} when is_binary(Preamble) ->
+            case try_execute_preamble(Preamble) of
+                ok ->
+                    ok;
+                error ->
+                    erlang:halt(1)
+            end
+    end.
+
+-spec standard_preamble() -> ok.
+standard_preamble() ->
+    test:info(),
+    test:ensure_initialized(),
+    test:start_shell(),
+    ok.
+
+-spec try_execute_preamble(binary()) -> ok | error.
+try_execute_preamble(Preamble) ->
+    try
+        Tokens =
+            case erl_scan:string(binary_to_list(Preamble)) of
+                {ok, Toks, _} ->
+                    Toks;
+                {error, {Line1, Module1, Reason1}, _} ->
+                    throw({bad_preamble, "Lexical error at line ~p: ~s~n", [Line1, Module1:format_error(Reason1)]})
+            end,
+        Exprs =
+            case erl_parse:parse_exprs(Tokens) of
+                {ok, Es} ->
+                    Es;
+                {error, {Line2, Module2, Reason2}} ->
+                    throw({bad_preamble, "Parse error at line ~p: ~s~n", [Line2, Module2:format_error(Reason2)]})
+            end,
+        {value, _Result, _Bindings} = erl_eval:exprs(Exprs, []),
+        ok
+    catch
+        throw:{bad_preamble, ErrorFmt, Args} ->
+            io:format(ErrorFmt, Args),
+            error
+    end.
diff --git a/buck2/prelude/erlang/common_test/test_cli_lib/test/test_cli_e2e_SUITE.erl b/buck2/prelude/erlang/common_test/test_cli_lib/test/test_cli_e2e_SUITE.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_cli_lib/test/test_cli_e2e_SUITE.erl
@@ -0,0 +1,94 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+%%% % @format
+-module(test_cli_e2e_SUITE).
+-typing([eqwalizer]).
+
+-export([suite/0, all/0, init_per_suite/1, end_per_suite/1]).
+
+-export([
+    test_list/1,
+    test_try_make_path_relative/1
+]).
+
+% elp:ignore WA003 (better_assertions) - Open Source
+-include_lib("stdlib/include/assert.hrl").
+-include_lib("common_test/include/ct.hrl").
+-include_lib("common/include/buck_ct_records.hrl").
+
+suite() ->
+    [{appatic, #{enable_autoclean => true}}].
+
+all() ->
+    [test_list, test_try_make_path_relative].
+
+init_per_suite(Config) ->
+    PrivDir = proplists:get_value(priv_dir, Config),
+    TestInfoFile = filename:join(PrivDir, <<"test_info">>),
+
+    {ok, [ErlCmd]} = init:get_argument(progname),
+
+    TestSuitePath = [_ | _] = code:which(test_list_SUITE),
+    test_info:write_to_file(TestInfoFile, #test_info{
+        common_app_env = #{},
+        raw_target = ~"raw_target",
+        dependencies = [],
+        test_suite = list_to_binary(TestSuitePath),
+        config_files = [],
+        providers = [],
+        ct_opts = [],
+        erl_cmd = lists:map(fun list_to_binary/1, ErlCmd),
+        extra_flags = [],
+        artifact_annotation_mfa = fun artifact_annotations:default_annotation/1,
+        trampolines = []
+    }),
+
+    application:set_env(test_cli_lib, test_info_file, TestInfoFile),
+
+    Config.
+
+end_per_suite(_Config) ->
+    ok.
+
+test_list(_Config) ->
+    Expected =
+        "test_cli_e2e_SUITE:\n"
+        "test_list_SUITE:\n"
+        "\t2 - test_list_SUITE - .test_pass\n"
+        "\t3 - test_list_SUITE - default.test_fail\n"
+        "\t4 - test_list_SUITE - .test_extended_ascii_£\n"
+        "\t5 - test_list_SUITE - .test_unicode_🫠\n",
+    ?assertEqual({ok, Expected}, test:list_impl("test_list_SUITE")),
+
+    EmojiExpected =
+        "test_cli_e2e_SUITE:\n"
+        "test_list_SUITE:\n"
+        "\t5 - test_list_SUITE - .test_unicode_🫠\n",
+    ?assertEqual({ok, EmojiExpected}, test:list_impl("_🫠")),
+
+    ?assertMatch({error, {invalid_regex, _}}, test:list_impl("^[a")),
+
+    EmptyExpected =
+        "test_cli_e2e_SUITE:\n"
+        "test_list_SUITE:\n",
+    ?assertEqual({ok, EmptyExpected}, test:list_impl("does_not_exist_SUITE")).
+
+%% Regression: lists:split/2 crashed with badarg when Path had fewer
+%% components than CWD (e.g. sandcastle deep buck-out CWD vs short
+%% dotslash cache ErlCmd path).
+test_try_make_path_relative(_Config) ->
+    ?assertEqual("relative/path", test_info:try_make_path_relative("relative/path")),
+
+    {ok, CWD} = file:get_cwd(),
+    ChildPath = filename:join(CWD, "some/child"),
+    ?assertEqual("some/child", test_info:try_make_path_relative(ChildPath)),
+
+    %% The crash case: absolute path shorter than CWD
+    ShortAbsPath = "/short/path",
+    ?assertEqual(ShortAbsPath, test_info:try_make_path_relative(ShortAbsPath)),
+
+    DisjointPath = "/completely/different/tree/structure/file",
+    ?assertEqual(DisjointPath, test_info:try_make_path_relative(DisjointPath)).
diff --git a/buck2/prelude/erlang/common_test/test_cli_lib/test/test_cli_e2e_SUITE_data/test_list_SUITE.erl b/buck2/prelude/erlang/common_test/test_cli_lib/test/test_cli_e2e_SUITE_data/test_list_SUITE.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_cli_lib/test/test_cli_e2e_SUITE_data/test_list_SUITE.erl
@@ -0,0 +1,36 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+%%% % @format
+-module(test_list_SUITE).
+
+-include_lib("stdlib/include/assert.hrl").
+
+-export([all/0, groups/0]).
+
+-export([
+    test_pass/1,
+    test_fail/1,
+    'test_extended_ascii_£'/1,
+    'test_unicode_🫠'/1
+]).
+
+all() ->
+    [test_pass, {group, default}, 'test_extended_ascii_£', 'test_unicode_🫠'].
+
+groups() ->
+    [{default, [], [test_fail]}].
+
+test_pass(_Config) ->
+    ?assert(true).
+
+test_fail(_Config) ->
+    ?assert(false).
+
+'test_extended_ascii_£'(_Config) ->
+    ?assert('£').
+
+'test_unicode_🫠'(_Config) ->
+    ?assert('🫠').
diff --git a/buck2/prelude/erlang/common_test/test_exec/BUCK b/buck2/prelude/erlang/common_test/test_exec/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/BUCK
@@ -0,0 +1,50 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+erlang_application(
+    name = "test_exec",
+    srcs = glob([
+        "src/*.erl",
+        "src/*.hrl",
+    ]),
+    app_src = "src/test_exec.app.src",
+    applications = [
+        "kernel",
+        "stdlib",
+        "prelude//erlang/common_test/common:common",
+        "prelude//erlang/common_test/cth_hooks:cth_hooks",
+    ],
+    erl_opts = [
+        "+debug_info",
+        "+warnings_as_errors",
+    ],
+    includes = glob(["include/*.hrl"]),
+    mod = ("test_exec", "[]"),
+    resources = read_root_config("erlang", "erlang_tests_default_config", "").split(),
+    shell_libs = [],
+    use_global_parse_transforms = False,
+    visibility = ["PUBLIC"],
+)
+
+erlang_tests(
+    contacts = ["whatsapp_testing_infra"],
+    labels = ["unit"],
+    suites = ["test/ct_executor_SUITE.erl"],
+    deps = [
+        "stdlib",
+        ":test_exec",
+    ],
+)
+
+erlang_tests(
+    contacts = ["whatsapp_testing_infra"],
+    labels = ["unit"],
+    suites = ["test/ct_daemon_capture_SUITE.erl"],
+    deps = [
+        "stdlib",
+        ":test_exec",
+    ],
+)
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon.erl
@@ -0,0 +1,170 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_daemon).
+-moduledoc """
+Daemon for running Common Test in an iterative way from an Erlang Shell
+""".
+-compile(warn_missing_spec_all).
+
+-export([
+    start/1, start/2,
+    stop/0,
+    alive/0,
+    run/1,
+    list/0, list/1,
+    ping/0,
+    push_module/1,
+    push_paths/1,
+    discover/1,
+    load_changed/0,
+    setup_state/0,
+    output_dir/0,
+    priv_dir/0,
+    test_node/0
+]).
+
+-doc """
+start a test-node with random name and shortname
+""".
+-spec start(ErlCommand) -> ok | {error, {crash_on_startup, integer()}} when
+    ErlCommand :: [binary()].
+start(ErlCommand) ->
+    ct_daemon_node:start(ErlCommand).
+
+-doc """
+starts the test node with the given distribution mode and node name
+""".
+-spec start(ErlCommand, Config) -> ok | {error, {crash_on_startup, integer()}} when
+    ErlCommand :: [binary()],
+    Config :: ct_daemon_node:config().
+start(ErlCommand, NodeInfo) ->
+    ct_daemon_node:start(ErlCommand, NodeInfo).
+
+-doc """
+stops the test node
+""".
+-spec stop() -> node().
+stop() ->
+    ct_daemon_node:stop().
+
+-doc """
+returns if the test-node is alive
+""".
+-spec alive() -> boolean().
+alive() ->
+    ct_daemon_node:alive().
+
+-doc """
+run test from scratch
+""".
+-spec run(
+    Test ::
+        string()
+        | non_neg_integer()
+        | {discovered, [#{suite => module(), name => string()}]}
+) ->
+    #{string() => ct_daemon_core:run_result()} | {error, ct_daemon_runner:discover_error()} | node_down.
+run(Test) ->
+    do_call({run, Test}).
+
+-spec ping() -> {pong, term()} | node_down.
+ping() ->
+    do_call(ping).
+
+-spec load_changed() -> [module()] | node_down.
+load_changed() ->
+    do_call(load_changed).
+
+-spec list() -> [{module(), [{non_neg_integer(), string()}]}] | node_down.
+list() ->
+    do_call(list).
+
+-spec list(RegEx :: string()) ->
+    [{module(), [{non_neg_integer(), string()}]}] | {invalid_regex, {string(), non_neg_integer()}} | node_down.
+list(RegEx) ->
+    case re:compile(RegEx, [unicode]) of
+        {ok, Pattern} ->
+            case list() of
+                node_down ->
+                    node_down;
+                Listing ->
+                    [
+                        {Suite, [Test || Test = {_Id, Name} <- Tests, re:run(Name, Pattern) =/= nomatch]}
+                     || {Suite, Tests} <- Listing
+                    ]
+            end;
+        {error, ErrSpec} ->
+            {invalid_regex, ErrSpec}
+    end.
+
+-spec discover(pos_integer() | string()) ->
+    [#{suite := module(), name := string()}]
+    | {error, ct_daemon_runner:discover_error()}
+    | node_down.
+discover(RegExOrId) ->
+    do_call({discover, RegExOrId}).
+
+-spec setup_state() -> [atom()] | undefined.
+setup_state() ->
+    case alive() of
+        true ->
+            case do_call(setup) of
+                node_down -> undefined;
+                Result -> Result
+            end;
+        _ ->
+            undefined
+    end.
+
+-spec output_dir() -> file:filename_all() | node_down.
+output_dir() ->
+    do_call(output_dir).
+
+-spec priv_dir() -> file:filename_all() | undefined | node_down.
+priv_dir() ->
+    do_call(priv_dir).
+
+-spec push_paths(Paths :: [file:filename_all()]) -> ok.
+push_paths(Paths) ->
+    case alive() of
+        true ->
+            do_cast({code_paths, Paths});
+        false ->
+            ok
+    end.
+
+-spec push_module(module()) -> ok.
+push_module(Module) ->
+    case alive() of
+        true ->
+            do_cast({load_module, Module});
+        false ->
+            ok
+    end.
+
+-spec test_node() -> node() | undefined.
+test_node() ->
+    case global:whereis_name(ct_daemon_runner:name(node())) of
+        undefined -> undefined;
+        Pid -> erlang:node(Pid)
+    end.
+
+%% call abstraction:
+-spec do_call(term()) -> dynamic() | node_down.
+do_call(Request) ->
+    try
+        gen_server:call({global, ct_daemon_runner:name(node())}, Request, infinity)
+    catch
+        exit:{noproc, {gen_server, call, _}} ->
+            node_down
+    end.
+
+-spec do_cast(term()) -> ok.
+do_cast(Request) ->
+    gen_server:cast({global, ct_daemon_runner:name(node())}, Request).
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_capture.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_capture.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_capture.erl
@@ -0,0 +1,222 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_daemon_capture).
+-moduledoc """
+Group leader implementation that supports ct:capture_* API for the test shell.
+
+This module provides a group leader process that can intercept I/O output
+when capture mode is enabled. It implements the Erlang I/O protocol and
+forwards messages to the original group leader while optionally capturing
+them.
+
+The OTP ct:capture_start() sends {capture, Pid} to the group leader.
+This module handles that message to enable/disable capture mode.
+""".
+-compile(warn_missing_spec_all).
+
+-behaviour(gen_server).
+
+%% Public API
+-export([start_link/1, stop/1]).
+
+%% gen_server callbacks
+-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]).
+
+-record(state, {
+    original_gl :: pid(),
+    capture_pid :: pid() | false
+}).
+
+-type state() :: #state{}.
+
+%%--------------------------------------------------------------------
+%% Public API
+%%--------------------------------------------------------------------
+
+-doc """
+Start a capture-aware group leader that forwards to the original group leader.
+Returns {ok, Pid} where Pid is the new group leader that can be set with
+erlang:group_leader/2.
+""".
+-spec start_link(pid()) -> gen_server:start_ret().
+start_link(OriginalGL) ->
+    gen_server:start_link(?MODULE, OriginalGL, []).
+
+-doc """
+Stop the capture group leader.
+""".
+-spec stop(pid()) -> ok.
+stop(Pid) ->
+    gen_server:stop(Pid, normal, 5000).
+
+%%--------------------------------------------------------------------
+%% gen_server callbacks
+%%--------------------------------------------------------------------
+
+-spec init(pid()) -> {ok, state()}.
+init(OriginalGL) ->
+    {ok, #state{original_gl = OriginalGL, capture_pid = false}}.
+
+-spec handle_call(term(), gen_server:from(), state()) -> {reply, term(), state()}.
+%% Handle capture via gen_server:call (for compatibility with callers using call instead of message)
+handle_call({capture, Pid}, _From, State) when is_pid(Pid) ->
+    {reply, ok, State#state{capture_pid = Pid}};
+handle_call({capture, false}, _From, State) ->
+    {reply, ok, State#state{capture_pid = false}};
+%% Handle I/O requests via gen_server:call (some io operations use this)
+handle_call({io_request, _From, _ReplyAs, Request}, _GenFrom, State) ->
+    {Reply, NewState} = handle_io_request(Request, State),
+    {reply, Reply, NewState};
+handle_call(_Request, _From, State) ->
+    {reply, {error, unknown_request}, State}.
+
+-spec handle_cast(term(), state()) -> {noreply, state()}.
+handle_cast(_Msg, State) ->
+    {noreply, State}.
+
+-spec handle_info(term(), state()) -> {noreply, state()}.
+%% Handle capture start message from OTP ct:capture_start() / test_server:capture_start()
+handle_info({capture, Pid}, State) when is_pid(Pid) ->
+    {noreply, State#state{capture_pid = Pid}};
+%% Handle capture stop message from OTP ct:capture_stop() / test_server:capture_stop()
+handle_info({capture, false}, State) ->
+    {noreply, State#state{capture_pid = false}};
+%% Handle I/O requests - the core I/O protocol
+handle_info({io_request, From, ReplyAs, Request}, State) when is_pid(From) ->
+    {Reply, NewState} = handle_io_request(Request, State),
+    From ! {io_reply, ReplyAs, Reply},
+    {noreply, NewState};
+%% Ignore io_reply messages - these are responses from the original group leader
+%% to requests we forwarded, and we don't need to do anything with them
+handle_info({io_reply, _ReplyAs, _Result}, State) ->
+    {noreply, State};
+%% Forward unknown messages to original group leader
+handle_info(Msg, State = #state{original_gl = GL}) ->
+    GL ! Msg,
+    {noreply, State}.
+
+-spec terminate(term(), state()) -> ok.
+terminate(_Reason, _State) ->
+    ok.
+
+%%--------------------------------------------------------------------
+%% I/O Protocol Handling
+%%--------------------------------------------------------------------
+
+-spec handle_io_request(term(), state()) -> {term(), state()}.
+handle_io_request({put_chars, Encoding, Chars}, State) when is_atom(Encoding), is_binary(Chars) ->
+    handle_put_chars(Chars, State);
+handle_io_request({put_chars, Encoding, Chars}, State) when is_atom(Encoding), is_list(Chars) ->
+    handle_put_chars_list(Chars, State);
+handle_io_request({put_chars, Encoding, M, F, A}, State) when
+    is_atom(Encoding), is_atom(M), is_atom(F), is_list(A)
+->
+    try erlang:apply(M, F, A) of
+        Chars when is_binary(Chars) -> handle_put_chars(Chars, State);
+        Chars when is_list(Chars) -> handle_put_chars_unsafe(Chars, State);
+        _ -> {{error, {M, F, A}}, State}
+    catch
+        _:_ -> {{error, {M, F, A}}, State}
+    end;
+handle_io_request({put_chars, Chars}, State) when is_binary(Chars) ->
+    handle_put_chars(Chars, State);
+handle_io_request({put_chars, Chars}, State) when is_list(Chars) ->
+    handle_put_chars_list(Chars, State);
+handle_io_request({put_chars, M, F, A}, State) when is_atom(M), is_atom(F), is_list(A) ->
+    handle_io_request({put_chars, latin1, M, F, A}, State);
+handle_io_request({get_chars, _, _, _}, State) ->
+    {eof, State};
+handle_io_request({get_line, _, _}, State) ->
+    {eof, State};
+handle_io_request({get_until, _, _, _, _, _}, State) ->
+    {eof, State};
+handle_io_request({get_geometry, _}, State) ->
+    {{error, enotsup}, State};
+handle_io_request(getopts, State) ->
+    {[{encoding, unicode}], State};
+handle_io_request({setopts, _}, State) ->
+    {ok, State};
+handle_io_request({requests, Reqs}, State) when is_list(Reqs) -> handle_requests(Reqs, State, ok);
+handle_io_request(_, State) ->
+    {{error, request}, State}.
+
+-spec handle_put_chars(iodata(), state()) -> {ok, state()}.
+handle_put_chars(Chars, State = #state{original_gl = GL, capture_pid = Cap}) when
+    is_binary(Chars); is_list(Chars)
+->
+    %% Always forward to the original group leader
+    GL ! {io_request, self(), make_ref(), {put_chars, unicode, Chars}},
+    %% If capturing, send captured output to capture_pid's mailbox
+    %% This is how OTP's test_server_sup:capture_get/1 expects to receive it
+    case Cap of
+        false -> ok;
+        Pid when is_pid(Pid) -> Pid ! {captured, chars_to_string(Chars)}
+    end,
+    {ok, State}.
+
+%% Handle list from guards - eqWAlizer sees [term()] not iodata()
+-spec handle_put_chars_list([term()], state()) -> {ok, state()}.
+handle_put_chars_list(Chars, State = #state{original_gl = GL, capture_pid = Cap}) ->
+    %% Always forward to the original group leader
+    GL ! {io_request, self(), make_ref(), {put_chars, unicode, Chars}},
+    %% If capturing, send captured output to capture_pid's mailbox
+    case Cap of
+        false -> ok;
+        Pid when is_pid(Pid) -> Pid ! {captured, chars_to_list_unsafe(Chars)}
+    end,
+    {ok, State}.
+
+%% Handle list returned from apply - may not be strict iodata
+-spec handle_put_chars_unsafe([term()], state()) -> {ok, state()}.
+handle_put_chars_unsafe(Chars, State = #state{original_gl = GL, capture_pid = Cap}) ->
+    %% Always forward to the original group leader
+    GL ! {io_request, self(), make_ref(), {put_chars, unicode, Chars}},
+    %% If capturing, send captured output to capture_pid's mailbox
+    case Cap of
+        false -> ok;
+        Pid when is_pid(Pid) -> Pid ! {captured, chars_to_list_unsafe(Chars)}
+    end,
+    {ok, State}.
+
+-spec chars_to_string(iodata()) -> string().
+chars_to_string(Chars) ->
+    case unicode:characters_to_list(Chars) of
+        Result when is_list(Result) -> Result;
+        _ ->
+            try
+                binary_to_list(iolist_to_binary(Chars))
+            catch
+                _:_ -> lists:flatten(io_lib:format("~tp", [Chars]))
+            end
+    end.
+
+%% Handle potentially non-strict iodata from apply results or guarded lists
+%% eqWAlizer sees [term()] from guards/apply, but at runtime it's iodata()
+-spec chars_to_list_unsafe([term()]) -> string().
+chars_to_list_unsafe(Chars) ->
+    try
+        %% Use iolist_to_binary to validate and convert iodata to binary
+        % eqwalizer:ignore - Chars is iodata() at runtime, guard just provides [term()]
+        Bin = iolist_to_binary(Chars),
+        unicode:characters_to_list(Bin)
+    of
+        Result when is_list(Result) -> Result;
+        _ -> lists:flatten(io_lib:format("~tp", [Chars]))
+    catch
+        _:_ -> lists:flatten(io_lib:format("~tp", [Chars]))
+    end.
+
+-spec handle_requests([term()], state(), term()) -> {term(), state()}.
+handle_requests([], State, LastReply) ->
+    {LastReply, State};
+handle_requests([Req | Rest], State, _LastReply) ->
+    case handle_io_request(Req, State) of
+        {{error, _} = Err, NewState} -> {Err, NewState};
+        {Reply, NewState} -> handle_requests(Rest, NewState, Reply)
+    end.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_core.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_core.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_core.erl
@@ -0,0 +1,569 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_daemon_core).
+-moduledoc """
+Stateless Core functionality for ct_daemon
+""".
+-compile(warn_missing_spec_all).
+
+%% Public API
+-export([
+    test_suites/0,
+    list/0, list/1,
+    run_test/3,
+    from_qualified/1,
+    to_qualified/1, to_qualified/2
+]).
+
+-export([
+    path_timetrap/1
+]).
+
+-export_type([reason/0, run_result/0, setup/0]).
+
+-include_lib("common/include/tpx_records.hrl").
+-include_lib("common/include/buck_ct_records.hrl").
+-include_lib("kernel/include/logger.hrl").
+
+-type reason() :: term().
+-type run_result() :: term().
+
+-type suite() :: module().
+-type groupname() :: atom().
+-type testname() :: atom().
+
+-type callback(A) :: fun((ct_suite:ct_config()) -> callback_result(A)).
+-type callback_result(A) :: {skip, reason()} | {fail, reason()} | {skip_and_save, reason(), ct_suite:ct_config()} | A.
+
+-type wrapped_init_callback() :: callback(ct_suite:ct_config()).
+-type wrapped_end_callback() :: callback(test_status()).
+
+-type setup_state() :: {[atom()], [{wrapped_end_callback(), ct_suite:ct_config()}]}.
+-type setup() :: #{config => ct_suite:ct_config(), setup_state => setup_state()}.
+
+-type init_and_ends() :: [
+    {
+        Id :: suite() | groupname(),
+        Init :: wrapped_init_callback(),
+        End :: wrapped_end_callback()
+    }
+].
+-type callback_error() ::
+    {error, {Where :: atom(), Reason :: term()}}
+    | {error, {term(), term(), term()}}
+    | {skip, Where :: atom(), Reason :: term()}
+    | {fail, Where :: atom(), Reason :: term()}.
+
+-define(DEFAULT_TIMETRAP, 30 * 60 * 1000).
+
+-type ct_test_result() ::
+    none()
+    | {skip, reason()}
+    | {comment, Comment :: string()}
+    | {save_config, SaveConfig :: ct_suite:ct_config()}
+    | {skip_and_save, reason(), SaveConfig :: ct_suite:ct_config()}
+    | {fail, reason()}
+    | {error, {init_per_testcase, reason()}}
+    | {error, reason()}.
+
+-type test_status() ::
+    {error, {testname(), reason()}}
+    | {error, {testname(), {skip, reason()}}}
+    | {error, {testname(), {skip_and_save, reason()}}}
+    | {fail, {testname(), reason()}}
+    | {skip, init_per_testcase, reason()}
+    | {skip, {testname(), reason()}}
+    | pass_result.
+
+%% listing and discovery
+-spec test_suites() -> [module()].
+test_suites() ->
+    {ok, Pattern} = re:compile("_SUITE$", [unicode]),
+    [
+        erlang:list_to_atom(Module)
+     || {Module, _Filename, _Loaded} <- code:all_available(), re:run(Module, Pattern) =/= nomatch
+    ].
+
+-spec list() -> #{module() => [string()]} | {error, Reason} when
+    Reason :: {could_not_find_module, module()} | {too_many_suites, Max :: pos_integer(), Actual :: pos_integer()}.
+list() ->
+    Suites = test_suites(),
+    case erlang:length(Suites) =< 10 of
+        true ->
+            lists:foldl(
+                fun
+                    (_, Error = {error, _}) ->
+                        Error;
+                    (Suite, Tests) ->
+                        case list(Suite) of
+                            Error = {error, _} -> Error;
+                            [] -> Tests;
+                            Discovered -> Tests#{Suite => Discovered}
+                        end
+                end,
+                #{},
+                Suites
+            );
+        false ->
+            {error, {too_many_suites, 10, erlang:length(Suites)}}
+    end.
+
+-spec to_qualified(#{suite := module(), name := string()}) -> string().
+to_qualified(#{suite := Suite, name := Name}) ->
+    to_qualified(atom_to_binary(Suite), Name).
+
+-spec to_qualified(Suite, Name) -> string() when
+    Suite :: unicode:chardata(),
+    Name :: unicode:chardata().
+to_qualified(Suite, Name) ->
+    lists:flatten(io_lib:format("~ts - ~ts", [Suite, Name])).
+
+-spec from_qualified(string()) -> #{suite := module(), name := string()}.
+from_qualified(FullName) ->
+    {match, [_, {ModS, ModL}, {NameS, NameL}]} = re:run(FullName, "(.*) - (.*)", [unicode]),
+    #{
+        suite => erlang:list_to_atom(string:slice(FullName, ModS, ModL)),
+        name => string:slice(FullName, NameS, NameL)
+    }.
+
+-spec list(module()) -> [string()] | {error, Reason} when
+    Reason :: {could_not_find_module, module()}.
+list(Suite) ->
+    case code:which(Suite) of
+        non_existing ->
+            {error, {could_not_find_module, Suite}};
+        _ ->
+            #test_spec_test_case{suite = SuiteName, testcases = TestCases} = list_test:list_tests(
+                Suite, ct_daemon_hooks:get_hooks()
+            ),
+            [to_qualified(SuiteName, TestName) || #test_spec_test_info{name = TestName} <- TestCases]
+    end.
+
+%% running tests
+-spec run_test(#ct_test{}, setup(), file:filename_all()) -> {run_result(), setup()}.
+run_test(Spec, PreviousSetup, OutputDir) ->
+    case do_incremental_setup(PreviousSetup, Spec, OutputDir) of
+        {ok, SetupConfig, SetupState} ->
+            {RunResult, AfterRunConfig} = do_run_test(SetupConfig, Spec),
+            {RunResult, #{setup_state => SetupState, config => AfterRunConfig}};
+        {Skip = {skip, _, _}, SetupConfig, SetupState} ->
+            {Skip, #{setup_state => SetupState, config => SetupConfig}};
+        {{fail, Where, ST}, SetupConfig, SetupState} ->
+            %% we map fail to error
+            {{error, {Where, ST}}, #{setup_state => SetupState, config => SetupConfig}};
+        {{error, R}, SetupConfig, SetupState} ->
+            {{error, R}, #{setup_state => SetupState, config => SetupConfig}}
+    end.
+
+-spec do_incremental_setup(Setup, Spec, OutputDir) -> {Result, Config, SetupState} when
+    Setup :: undefined | setup(),
+    Spec :: #ct_test{},
+    OutputDir :: file:filename_all(),
+    Result :: ok | callback_error(),
+    Config :: ct_suite:ct_config(),
+    SetupState :: setup_state().
+do_incremental_setup(undefined, Spec, OutputDir) ->
+    do_fresh_setup(Spec, OutputDir);
+do_incremental_setup(
+    #{config := Config0, setup_state := {SetupPath0, EndStack0}},
+    _Spec = #ct_test{suite = Suite, groups = Groups},
+    _OutputDir
+) ->
+    WantPath = [Suite | Groups],
+    {CommonPrefix, RemainingSetup} = get_common_prefix(WantPath, lists:reverse(SetupPath0), []),
+    {Config1, CommonPrefix, EndStack1} = do_teardown_until(
+        CommonPrefix, SetupPath0, EndStack0, Config0
+    ),
+    do_setup_from(Suite, Config1, CommonPrefix, EndStack1, RemainingSetup).
+
+-spec do_fresh_setup(#ct_test{}, OutputDir) -> {Result, Config, SetupState} when
+    OutputDir :: file:filename_all(),
+    Config :: ct_suite:ct_config(),
+    SetupState :: setup_state(),
+    Result :: ok | callback_error().
+do_fresh_setup(#ct_test{suite = Suite, groups = Groups}, OutputDir) ->
+    InitialConfig = get_fresh_config(Suite, OutputDir),
+    RemainingSetup = [Suite | Groups],
+    InitAndEnds = build_inits_and_ends(Suite, RemainingSetup, []),
+    do_init(InitAndEnds, InitialConfig, {[], []}).
+
+-spec do_setup_from(Suite, Config, SetupPath, EndStack, RemainingSetup) -> {Result, Config, SetupState} when
+    Suite :: module(),
+    Config :: ct_suite:ct_config(),
+    SetupPath :: [suite() | groupname()],
+    EndStack :: [{wrapped_end_callback(), ct_suite:ct_config()}],
+    RemainingSetup :: [atom()],
+    Result :: ok | callback_error(),
+    SetupState :: setup_state().
+do_setup_from(Suite, Config, SetupPath, EndStack, RemainingSetup) ->
+    InitAndEnds = build_inits_and_ends(Suite, RemainingSetup, []),
+    %% return from the last config on the init path if applicable
+    ConfigIn =
+        case EndStack of
+            [{_, LastConfig} | _] -> LastConfig;
+            _ -> Config
+        end,
+    do_init(InitAndEnds, ConfigIn, {SetupPath, EndStack}).
+
+-spec do_init(InitAndEnds, Config, SetupState) -> {Result, Config, SetupState} when
+    InitAndEnds :: init_and_ends(),
+    Config :: ct_suite:ct_config(),
+    SetupState :: setup_state(),
+    Result :: ok | callback_error().
+do_init([], Config, SetupState) ->
+    {ok, Config, SetupState};
+do_init([{Id, Init, End} | Rest], ConfigIn, SetupState = {PathStack, EndsStack}) ->
+    Timetrap = path_timetrap(lists:reverse([Id | PathStack])),
+    case do_part_safe(Id, Init, ConfigIn, Timetrap) of
+        Error = {error, _} -> {Error, ConfigIn, SetupState};
+        Skip = {skip, _, _} -> {Skip, ConfigIn, SetupState};
+        Fail = {fail, _, _} -> {Fail, ConfigIn, SetupState};
+        {ok, ConfigOut} -> do_init(Rest, ConfigOut, {[Id | PathStack], [{End, ConfigOut} | EndsStack]})
+    end.
+
+-spec get_common_prefix(Ls, Rs, Acc) -> {Prefix, Remaining} when
+    Ls :: [X],
+    Rs :: [X],
+    Acc :: [X],
+    Prefix :: [X],
+    Remaining :: [X].
+get_common_prefix([L | RestL], [R | RestR], Acc) when L =:= R ->
+    get_common_prefix(RestL, RestR, [L | Acc]);
+get_common_prefix(RemainingSetup, _, Acc) ->
+    {Acc, RemainingSetup}.
+
+-spec do_teardown_until(Target, Setup, EndsStack, Config) -> {Config, Target, EndsStack} when
+    Target :: [atom()],
+    Setup :: [atom()],
+    EndsStack :: [{wrapped_end_callback(), ct_suite:ct_config()}],
+    Config :: ct_suite:ct_config().
+do_teardown_until(Target, Setup, EndsStack, Config) when Target =:= Setup ->
+    {Config, Target, EndsStack};
+do_teardown_until(Target, Path = [Id | RemainingSetup], [{End, Config} | RemainingEndsStack], _) ->
+    Timetrap = path_timetrap(lists:reverse(Path)),
+    NextConfig =
+        case do_part_safe(Id, End, Config, Timetrap) of
+            GroupResult = {ok, {return_group_result, _Status}} ->
+                [GroupResult | lists:keydelete(return_group_result, 1, Config)];
+            _ ->
+                lists:keydelete(return_group_result, 1, Config)
+        end,
+    do_teardown_until(Target, RemainingSetup, RemainingEndsStack, NextConfig).
+
+-spec build_inits_and_ends(Suite, Path, Acc) -> init_and_ends() when
+    Suite :: module(),
+    Path :: [suite() | groupname()],
+    Acc :: init_and_ends().
+build_inits_and_ends(_Suite, [], Acc) ->
+    lists:reverse(Acc);
+build_inits_and_ends(Suite, [Suite | RemainingInit], []) ->
+    build_inits_and_ends(
+        Suite,
+        RemainingInit,
+        [
+            {Suite, wrap_ct_hook(init_per_suite, [Suite], fun Suite:init_per_suite/1),
+                wrap_ct_hook(end_per_suite, [Suite], fun Suite:end_per_suite/1)}
+        ]
+    );
+build_inits_and_ends(Suite, [Group | RemainingInit], Acc) ->
+    build_inits_and_ends(
+        Suite,
+        RemainingInit,
+        [
+            {Group, wrap_ct_hook(init_per_group, [Suite, Group], fun Suite:init_per_group/2),
+                wrap_ct_hook(end_per_group, [Suite, Group], fun Suite:end_per_group/2)}
+            | Acc
+        ]
+    ).
+
+-spec do_run_test(SetupConfig, Spec) -> {test_status() | {error, Reason}, ct_suite:ct_config()} when
+    SetupConfig :: ct_suite:ct_config(),
+    Spec :: #ct_test{},
+    Reason :: term().
+do_run_test(SetupConfig, #ct_test{suite = Suite, groups = Groups, test_name = Test}) ->
+    Timetrap = path_timetrap([Suite | Groups], Test),
+    Path = [Suite | Groups] ++ [Test],
+    PartFun =
+        fun(Config) ->
+            test_part(Config, Suite, Test, Path)
+        end,
+    case do_part_safe(Test, PartFun, SetupConfig, Timetrap) of
+        Error = {error, _} -> {Error, SetupConfig};
+        {ok, Result} -> Result
+    end.
+
+-spec test_part(Config, Suite, Test, Path) -> {test_status(), ct_suite:ct_config()} when
+    Config :: ct_suite:ct_config(),
+    Suite :: module(),
+    Test :: atom(),
+    Path :: [atom()].
+test_part(Config, Suite, Test, Path) ->
+    InitResult =
+        case safe_call(wrap_ct_hook(init_per_testcase, Path, fun Suite:init_per_testcase/2), [Config]) of
+            {error, not_exported} -> Config;
+            {skip, Reason} -> {error, {skip, init_per_testcase, Reason}};
+            {fail, InitErrReason} -> {error, {skip, init_per_testcase, InitErrReason}};
+            {error, InitErrReason} -> {error, {skip, init_per_testcase, InitErrReason}};
+            InitOutConfig -> InitOutConfig
+        end,
+    {TestResult, FinalConfig} =
+        case InitResult of
+            Error = {error, _} ->
+                {Error, Config};
+            InitConfig ->
+                Result = safe_call(fun Suite:Test/1, [InitConfig]),
+                AfterRunConfig = config_from_test_result(Result, InitConfig),
+                case
+                    safe_call(wrap_ct_hook(end_per_testcase, Path, fun Suite:end_per_testcase/2), [
+                        AfterRunConfig
+                    ])
+                of
+                    {save_config, AfterEndConfig} ->
+                        {Result, AfterEndConfig};
+                    {Failed, E} when Failed =:= fail orelse Failed =:= failed ->
+                        FinalResult =
+                            case status_from_test_result(Result, Test) of
+                                pass_result -> {fail, {end_per_testcase, E}};
+                                _ -> Result
+                            end,
+                        {FinalResult, AfterRunConfig};
+                    _ ->
+                        {Result, AfterRunConfig}
+                end
+        end,
+    {status_from_test_result(TestResult, Test), FinalConfig}.
+
+-spec wrap_ct_hook(Part, Path, Fun) -> callback(Res) when
+    Part :: ct_daemon_hooks:part(),
+    Path :: [atom()],
+    Fun :: fun((Config) -> callback_result(Res)) | fun((GroupOrTest :: atom(), Config) -> callback_result(Res)),
+    Config :: ct_suite:ct_config().
+wrap_ct_hook(Part, Path, Fun) ->
+    ct_daemon_hooks:wrap(Part, Path, Fun).
+
+-doc """
+Transform exceptions into error tuples
+""".
+-spec safe_call(F, Args) -> Res | {fail, Failure} when
+    F :: fun(),
+    Args :: [term()],
+    Res :: dynamic(),
+    Failure :: {thrown, Reason, Stacktrace} | {Reason, Stacktrace} | Reason,
+    Reason :: term(),
+    Stacktrace :: erlang:stacktrace().
+safe_call(F, Args) ->
+    try erlang:apply(F, Args) of
+        Res -> Res
+    catch
+        E:R:ST ->
+            ct_daemon_hooks:format_ct_error(E, R, ST)
+    end.
+
+-spec config_from_test_result(ct_test_result(), ct_suite:ct_config()) -> ct_suite:ct_config().
+config_from_test_result({skip_and_save, _Reason, Config}, _) -> Config;
+config_from_test_result({save_config, Config}, _) -> Config;
+config_from_test_result({fail, FailReason}, Config) -> [{tc_status, {failed, FailReason}} | Config];
+config_from_test_result({skip, FailReason}, Config) -> [{tc_status, {skipped, FailReason}} | Config];
+config_from_test_result({error, Error}, Config) -> [{tc_status, {failed, Error}} | Config];
+config_from_test_result(_, Config) -> Config.
+
+-spec status_from_test_result(ct_test_result(), atom()) -> test_status().
+status_from_test_result(InitError = {error, {init_per_testcase, _}}, _) ->
+    InitError;
+status_from_test_result({error, SkipResult = {skip, init_per_testcase, _}}, _) ->
+    SkipResult;
+status_from_test_result({skip_and_save, Reason, _SaveConfig}, Test) ->
+    {error, {Test, {skip_and_save, Reason}}};
+status_from_test_result({error, {Error, Reason, Stacktrace}}, Test) ->
+    {error, {Test, {Error, {Reason, Stacktrace}}}};
+status_from_test_result({error, R}, Test) ->
+    {error, {Test, R}};
+status_from_test_result({fail, R}, Test) ->
+    {fail, {Test, R}};
+status_from_test_result({skip, R}, Test) ->
+    {skip, {Test, R}};
+status_from_test_result(_R, _) ->
+    pass_result.
+
+-spec get_fresh_config(Suite, OutputDir) -> ct_suite:ct_config() when
+    Suite :: module(),
+    OutputDir :: file:filename_all().
+get_fresh_config(Suite, OutputDir) ->
+    {module, Suite} = code:ensure_loaded(Suite),
+    SuitePath =
+        case code:which(Suite) of
+            Which when Which /= non_existing -> Which
+        end,
+    DataDir = filename:join(filename:dirname(SuitePath), io_lib:format("~ts_data", [Suite])) ++ "/",
+    PrivDir =
+        filename:join([
+            OutputDir,
+            io_lib:format("~ts.~ts", [Suite, calendar:system_time_to_rfc3339(erlang:system_time(second))]),
+            "private_log"
+        ]) ++ "/",
+    ok = filelib:ensure_path(PrivDir),
+    [{priv_dir, PrivDir}, {data_dir, DataDir}].
+
+-doc """
+run an init or end or test in an isolated process like CT
+""".
+-spec do_part_safe(Id, Fun, Config, TimeTrap) -> {ok, Res} | callback_error() when
+    Id :: atom(),
+    Fun :: callback(Res),
+    Config :: ct_suite:ct_config(),
+    TimeTrap :: timeout().
+do_part_safe(Id, Fun, Config, TimeTrap) ->
+    {Pid, ProcRef} = erlang:spawn_monitor(
+        fun() ->
+            {ParentPid, RspRef} =
+                receive
+                    M -> M
+                end,
+            {name, FunName} = erlang:fun_info(Fun, name),
+            try Fun(Config) of
+                {skip, Reason} ->
+                    ?LOG_DEBUG("got skip for ~tp because of: ~tp", [Id, Reason]),
+                    ParentPid ! {RspRef, {skip, {FunName, Id}, Reason}};
+                {fail, Reason} ->
+                    ?LOG_DEBUG("got fail for ~tp because of: ~tp", [Id, Reason]),
+                    ParentPid ! {RspRef, {fail, {FunName, Id}, Reason}};
+                {skip_and_save, Reason, _} ->
+                    ?LOG_DEBUG("got skip for ~tp because of: ~tp", [Id, Reason]),
+                    ParentPid ! {RspRef, {skip, {FunName, Id}, Reason}};
+                Res ->
+                    ?LOG_DEBUG("got new result: ~tp", [Res]),
+                    ParentPid ! {RspRef, Res}
+            catch
+                error:undef ->
+                    ParentPid ! {RspRef, Config};
+                E:R:ST ->
+                    ?LOG_DEBUG("crashed executing part: ~tp", [{E, R, ST}]),
+                    ParentPid ! {RspRef, {E, R, ST}}
+            end
+        end
+    ),
+    ReqRef = erlang:make_ref(),
+    Pid ! {self(), ReqRef},
+    receive
+        {'DOWN', ProcRef, process, _Pid, Info} ->
+            {error, {Id, {'ct_daemon_core$sentinel_crash', Info}}};
+        {ReqRef, Skip = {skip, _Where, _Reason}} ->
+            Skip;
+        {ReqRef, Fail = {fail, _Where, _Reason}} ->
+            Fail;
+        {ReqRef, {_, _, _} = ErrorTuple} ->
+            flush_monitor_msg(ProcRef),
+            {error, ErrorTuple};
+        {ReqRef, Res} ->
+            flush_monitor_msg(ProcRef),
+            {ok, Res}
+    after TimeTrap -> {error, {Id, {timetrap, TimeTrap}}}
+    end.
+
+-spec flush_monitor_msg(Ref) -> ok when
+    Ref :: erlang:reference().
+flush_monitor_msg(Ref) ->
+    true = erlang:demonitor(Ref),
+    receive
+        {'DOWN', Ref, _, _} -> ok
+    after 0 -> ok
+    end.
+
+%% timetraps
+
+-spec path_timetrap(Path) -> timeout() when
+    Path :: nonempty_list(suite() | groupname()).
+path_timetrap([Suite | Groups]) ->
+    do_path_timetrap(#{suite => Suite, groups => Groups}, ?DEFAULT_TIMETRAP).
+
+-spec path_timetrap(Path, Test) -> timeout() when
+    Path :: nonempty_list(suite() | groupname()),
+    Test :: atom().
+path_timetrap([Suite | Groups], Test) ->
+    do_path_timetrap(#{suite => Suite, groups => Groups, test => Test}, ?DEFAULT_TIMETRAP).
+
+-spec do_path_timetrap(Spec, Current) -> timeout() when
+    Spec :: #{suite := module(), groups := [groupname()], test => testname()},
+    Current :: timeout().
+do_path_timetrap(#{suite := Suite, groups := Groups} = Spec, Current) ->
+    TimeTrap0 = suite_timetrap(Suite, Current),
+    Timetrap1 =
+        lists:foldl(
+            fun(Group, Curr) ->
+                group_timetrap(Suite, Group, Curr)
+            end,
+            TimeTrap0,
+            Groups
+        ),
+    UnscaledTimetrap =
+        case Spec of
+            #{test := Test} -> test_timetrap(Suite, Test, Timetrap1);
+            _ -> TimeTrap0
+        end,
+    scale_timetrap(UnscaledTimetrap).
+
+-spec suite_timetrap(Suite, Default) -> timeout() when
+    Suite :: module(),
+    Default :: timeout().
+suite_timetrap(Suite, Default) ->
+    case erlang:function_exported(Suite, suite, 0) of
+        false ->
+            Default;
+        true ->
+            Timetrap = proplists:get_value(timetrap, Suite:suite(), Default),
+            timetrap_to_ms(Timetrap)
+    end.
+
+-spec group_timetrap(Suite, Group, Default) -> timeout() when
+    Suite :: module(),
+    Group :: groupname(),
+    Default :: timeout().
+group_timetrap(Suite, Group, Default) ->
+    case erlang:function_exported(Suite, group, 1) of
+        false ->
+            Default;
+        true ->
+            Timetrap = proplists:get_value(timetrap, Suite:group(Group), Default),
+            timetrap_to_ms(Timetrap)
+    end.
+
+-spec test_timetrap(Suite, Test, Default) -> timeout() when
+    Suite :: module(),
+    Test :: testname(),
+    Default :: timeout().
+test_timetrap(Suite, Test, Default) ->
+    case erlang:function_exported(Suite, Test, 0) of
+        false ->
+            Default;
+        true ->
+            Timetrap = proplists:get_value(timetrap, Suite:Test(), Default),
+            timetrap_to_ms(Timetrap)
+    end.
+
+-spec timetrap_to_ms(Timetrap) -> timeout() when
+    Timetrap :: timeout() | {seconds, integer()} | {minutes, integer()} | {hours, integer()}.
+timetrap_to_ms(MS) when is_integer(MS) -> MS;
+timetrap_to_ms({seconds, S}) -> S * 1000;
+timetrap_to_ms({minutes, S}) -> S * 1000 * 60;
+timetrap_to_ms({hours, S}) -> S * 1000 * 60 * 60;
+timetrap_to_ms(_) -> ?DEFAULT_TIMETRAP.
+
+-spec scale_timetrap(timeout()) -> timeout().
+scale_timetrap(infinity) ->
+    infinity;
+scale_timetrap(MS) ->
+    case application:get_env(test_exec, daemon_options, []) of
+        Options when is_list(Options) ->
+            case proplists:get_value(multiply_timetraps, Options, 1) of
+                infinity -> infinity;
+                X when is_number(X) -> MS * X
+            end;
+        BadOptions ->
+            error({bad_options, BadOptions})
+    end.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_hooks.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_hooks.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_hooks.erl
@@ -0,0 +1,545 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_daemon_hooks).
+-moduledoc """
+Implementation of hooks functionality. We mimic the behaviour of
+common test hooks so that they can run in test shell
+""".
+-compile(warn_missing_spec_all).
+
+-behaviour(gen_server).
+
+%% API
+-export([
+    start_monitor/0,
+    set_state/2,
+    get_state/1,
+    wrap/3,
+    format_ct_error/3,
+    get_hooks/0
+]).
+
+%% gen_server callbacks
+-export([
+    init/1,
+    handle_call/3,
+    handle_cast/2
+]).
+
+-export_type([part/0]).
+
+-type id() :: term().
+-type opts() :: term().
+-type hook_state() :: term().
+-type group_name() :: atom().
+-type func_name() :: atom().
+-type test_name() ::
+    init_per_suite
+    | end_per_suite
+    | {init_per_group, group_name()}
+    | {end_per_group, group_name()}
+    | {func_name(), group_name()}
+    | func_name().
+-type config() :: ct_suite:ct_config().
+
+-type hook() :: {atom(), id()}.
+-type state() :: #{
+    hooks := [hook()],
+    states := #{id() => hook_state()}
+}.
+
+-type part() ::
+    init_per_suite
+    | init_per_group
+    | init_per_testcase
+    | end_per_suite
+    | end_per_group
+    | end_per_testcase
+    | on_tc_fail
+    | on_tc_skip.
+
+-type post_hook_call() ::
+    post_init_per_suite
+    | post_init_per_group
+    | post_init_per_testcase
+    | post_end_per_suite
+    | post_end_per_group
+    | post_end_per_testcase.
+
+-type pre_hook_call() ::
+    pre_init_per_suite
+    | pre_init_per_group
+    | pre_init_per_testcase
+    | pre_end_per_suite
+    | pre_end_per_group
+    | pre_end_per_testcase.
+
+-type hook_level() ::
+    suite
+    | group
+    | testcase.
+
+-type hook_response() ::
+    [config()]
+    | {skip, term()}
+    | {fail, term()}.
+
+-type hook_config() ::
+    module()
+    | {module(), Options :: [term()]}
+    | {module(), Options :: [term()], Priority :: integer()}.
+
+%%--------------------------------------------------------------------
+%%% API
+
+-spec set_state(id(), hook_state()) -> ok.
+set_state(Id, State) ->
+    ok = gen_server:call(?MODULE, {set_state, Id, State}).
+
+-spec get_state(id()) -> {ok, hook_state()} | {error, {not_found, list()}}.
+get_state(Id) ->
+    case gen_server:call(?MODULE, {get_state, Id}) of
+        {ok, State} -> {ok, State};
+        Error = {error, {not_found, Details}} when is_list(Details) -> Error
+    end.
+
+-spec wrap(part(), [atom()], Fun) -> fun((Config) -> Res) when
+    Fun :: fun((Config) -> Res) | fun((GroupOrTest :: atom(), Config) -> Res),
+    Config :: config().
+wrap(Part, Path, Fun) ->
+    WrappedFun = gen_server:call(?MODULE, {wrap, Part, Fun}),
+    %% apply path as closure
+    fun(Config) -> WrappedFun(Path, Config) end.
+
+-spec get_hooks() -> [module()].
+get_hooks() ->
+    [get_hook_module(Hook) || Hook <- get_hooks_config()].
+
+-doc """
+Starts the server within supervision tree
+""".
+-spec start_monitor() -> gen_server:start_mon_ret().
+start_monitor() ->
+    gen_server:start_monitor({local, ?MODULE}, ?MODULE, [], []).
+
+%%--------------------------------------------------------------------
+%%% gen_server callbacks
+
+-spec init([]) -> {ok, state()}.
+init([]) ->
+    {ok, initialize_hooks()}.
+
+-spec handle_call
+    ({get_state, id()}, gen_server:from(), state()) ->
+        {reply, {ok, hook_state()}, state()} | {error, {not_found, list()}};
+    ({set_state, id(), hook_state()}, gen_server:from(), state()) -> {reply, ok, state()};
+    ({wrap, part(), fun()}, gen_server:from(), state()) -> {reply, fun(([atom()], [config()]) -> term()), state()}.
+handle_call({get_state, Id}, _From, State = #{states := HookStates}) ->
+    case HookStates of
+        #{Id := HookState} -> {reply, {ok, HookState}, State};
+        _ -> {error, {not_found, [{state, State}, {id, Id}]}}
+    end;
+handle_call({set_state, Id, HookState}, _From, State = #{states := HookStates}) ->
+    {reply, ok, State#{states => HookStates#{Id => HookState}}};
+handle_call({wrap, Part, Fun}, _From, State) ->
+    {reply, wrap_part(Part, Fun, State), State}.
+
+-spec handle_cast(Request :: term(), State :: state()) -> no_return().
+handle_cast(_Request, _State) ->
+    error(badarg).
+
+%%--------------------------------------------------------------------
+%%% Internal functions
+
+-spec initialize_hooks() -> state().
+initialize_hooks() ->
+    ConfiguredHooks = get_hooks_config(),
+    NormalizedConfiguredHooks = [
+        {get_hook_module(Hook), get_hook_opts(Hook), get_hook_priority(Hook)}
+     || Hook <- ConfiguredHooks
+    ],
+    %% first we need the Id
+    HooksWithId = [
+        case Prio of
+            undefined -> {0, wrapped_id(Mod, Opts), Mod, Opts, Prio};
+            _ -> {Prio, wrapped_id(Mod, Opts), Mod, Opts, Prio}
+        end
+     || {Mod, Opts, Prio} <- NormalizedConfiguredHooks
+    ],
+    %% according to documentation, if two hooks have the same ID, the latter one gets dropped
+    PreInitHooks0 = lists:ukeysort(2, HooksWithId),
+    %% now sort with configured prio the inits (default prio being 0)
+    PreInitHooks1 = lists:keysort(1, PreInitHooks0),
+
+    %% now let's run the inits in order and build the state
+    {States, HooksWithPriority} = lists:foldl(
+        fun({_InitPrio, Id, Mod, Opts, ConfiguredPrio}, {StatesAcc, HooksAcc}) ->
+            {Priority, HookState} = wrapped_init({Mod, Id}, Opts, ConfiguredPrio),
+            {StatesAcc#{Id => HookState}, [{Priority, {Mod, Id}} | HooksAcc]}
+        end,
+        {#{}, []},
+        PreInitHooks1
+    ),
+
+    %% sort hooks according to priority
+    %% Note: This is reverse order for the priorities, but since we wrap, we want to wrap the
+    %%       lowest priority hook first.
+    SortedHooks = lists:keysort(1, HooksWithPriority),
+
+    #{
+        states => States,
+        hooks => [Hook || {_Priority, Hook} <- SortedHooks]
+    }.
+
+-spec get_hooks_config() -> [hook_config()].
+get_hooks_config() ->
+    application:get_env(test_exec, ct_daemon_hooks, []) ++
+        proplists:get_value(ct_hooks, application:get_env(test_exec, daemon_options, []), []).
+
+-spec wrap_part(part(), fun(), state()) -> fun(([atom()], [config()]) -> term()).
+wrap_part(Part, Fun, State) ->
+    wrap_init_end(Part, Fun, State).
+
+-spec wrap_init_end(part(), fun(), state()) -> fun(([atom()], [config()]) -> term()).
+wrap_init_end(Part, Fun, #{hooks := HooksInInstallationOrder}) ->
+    %% NOTE ON EXECUTION ORDER:
+    %%
+    %% As of OTP/26 CT's behaviour according to [https://www.erlang.org/doc/apps/common_test/ct_hooks_chapter#cth-execution-order]:
+    %% > By default, each CTH installed is executed in the order that they are installed for init calls,
+    %% > and then reversed for end calls. This is not always desired, so Common Test allows the user to specify
+    %% > a priority for each hook.
+    %%
+    %% Implicit here is:
+    %% - pre_init and post_init functions are executed in the same order
+    %% - the hook with the "highest numerical priority" will be the first to run pre_init_per xxxx
+    %%
+    %% Starting from OTP/27, CT adds a new option ct_hooks_order option. The behaviour above is called `test`, and a
+    %% new behaviour called `config` will be added, in which the order of the post_xxxx functions is reversed wrt pre_xxxx
+    %% (see [https://github.com/erlang/otp/issues/7397] for discussion, and [https://github.com/erlang/otp/pull/7496]
+    %% for the upcoming ct_hooks_order option).
+    %%
+    %% Here we implement only the behaviour that corresponds to the new `config` option.
+
+    %% NB. we use a foldr to ensure that the first hook in HookInInstallationOrder is the innermost, so the first one to
+    %% be executed
+    WrappedWithPreAndPost = lists:foldr(
+        fun(Hook, FunToWrap) ->
+            fun(FullPathArg, ConfigArg0) ->
+                PathArg =
+                    case level(Part) of
+                        testcase ->
+                            [Suite | _] = FullPathArg,
+                            [Suite, lists:last(FullPathArg)];
+                        _ ->
+                            FullPathArg
+                    end,
+                case call_if_exists_with_fallback_store_state(Hook, pre(Part), PathArg ++ [ConfigArg0], ok) of
+                    {skip, SkipReason} ->
+                        {skip, SkipReason};
+                    {fail, FailReason} ->
+                        {fail, FailReason};
+                    HookCallbackResult ->
+                        ConfigArg1 =
+                            case is_list(HookCallbackResult) of
+                                true ->
+                                    HookCallbackResult;
+                                false ->
+                                    %% NB. If pre(Part) is not defined in the hook we get 'ok'
+                                    ConfigArg0
+                            end,
+                        %% first step of error handling for the post functions where we set tc_status
+                        {PostConfig, Return} =
+                            try FunToWrap(PathArg, ConfigArg1) of
+                                {skip, SkipReason} ->
+                                    {
+                                        [
+                                            {tc_status, {skipped, SkipReason}}
+                                            | lists:keydelete(tc_status, 1, ConfigArg1)
+                                        ],
+                                        {skip, SkipReason}
+                                    };
+                                {fail, FailReason} ->
+                                    {
+                                        [{tc_status, {failed, FailReason}} | lists:keydelete(tc_status, 1, ConfigArg1)],
+                                        {fail, FailReason}
+                                    };
+                                OkResult ->
+                                    ConfigArg2 =
+                                        case init_or_end(Part) of
+                                            init when is_list(OkResult) ->
+                                                OkResult;
+                                            _ ->
+                                                ConfigArg1
+                                        end,
+                                    case proplists:is_defined(tc_status, ConfigArg2) of
+                                        true -> {ConfigArg2, OkResult};
+                                        false -> {[{tc_status, ok} | ConfigArg2], OkResult}
+                                    end
+                            catch
+                                Class:Reason:Stacktrace ->
+                                    Error = format_ct_error(Class, Reason, Stacktrace),
+                                    {[{tc_status, {failed, Error}} | ConfigArg1], Error}
+                            end,
+                        Args = PathArg ++ [PostConfig, Return],
+                        call_if_exists_with_fallback_store_state(Hook, post(Part), Args, Return)
+                end
+            end
+        end,
+        normalize_part(Part, Fun),
+        HooksInInstallationOrder
+    ),
+    %% after the post_per functions we need to handle now failures, and call either on_tc_fail or on_tc_skip
+    fun(PathArg, ConfigArg) ->
+        [Suite | _] = PathArg,
+        Result =
+            try WrappedWithPreAndPost(PathArg, ConfigArg) of
+                {skip, SkipReason} ->
+                    {skip, SkipReason};
+                {fail, FailReason} ->
+                    {fail, FailReason};
+                MaybeConfig ->
+                    case init_or_end(Part) of
+                        'end' ->
+                            %% ends may return any kind of value
+                            {ok, ConfigArg};
+                        init ->
+                            case proplists:get_value(tc_status, MaybeConfig, ok) of
+                                ok ->
+                                    {ok, lists:keydelete(tc_status, 1, MaybeConfig)};
+                                FailOrSkip ->
+                                    FailOrSkip
+                            end
+                    end
+            catch
+                Class:Reason:Stacktrace -> {fail, {'EXIT', {{Class, Reason}, Stacktrace}}}
+            end,
+        handle_post_result(HooksInInstallationOrder, build_test_name(Part, PathArg), Suite, Result)
+    end.
+
+-spec handle_post_result(Hooks, TestName, Suite, Result) ->
+    hook_response()
+when
+    Hooks :: [hook()],
+    TestName :: test_name(),
+    Suite :: module(),
+    Result :: {ok, [config()]} | {skip, term()} | {fail, term()}.
+handle_post_result(Hooks, TestName, Suite, Result) ->
+    ReverseHooks = lists:reverse(Hooks),
+    case Result of
+        {skip, SkipReason} ->
+            [
+                call_if_exists_with_fallback_store_state(
+                    Hook, on_tc_skip, [Suite, TestName, {tc_user_skip, SkipReason}], ok
+                )
+             || Hook <- ReverseHooks
+            ],
+            {skip, SkipReason};
+        {fail, FailReason} ->
+            [
+                call_if_exists_with_fallback_store_state(
+                    Hook, on_tc_fail, [Suite, TestName, FailReason], ok
+                )
+             || Hook <- ReverseHooks
+            ],
+            {fail, FailReason};
+        {ok, Config} ->
+            case lists:keyfind(tc_status, 1, Config) of
+                false ->
+                    Config;
+                {tc_status, {skipped, SkipReason}} ->
+                    [
+                        call_if_exists_with_fallback_store_state(
+                            Hook, on_tc_skip, [Suite, TestName, {tc_user_skip, SkipReason}], ok
+                        )
+                     || Hook <- ReverseHooks
+                    ],
+                    {skip, SkipReason};
+                {tc_status, {failed, FailReason}} ->
+                    [
+                        call_if_exists_with_fallback_store_state(
+                            Hook, on_tc_fail, [Suite, TestName, FailReason], ok
+                        )
+                     || Hook <- ReverseHooks
+                    ],
+                    {fail, FailReason}
+            end
+    end.
+
+-spec format_ct_error(throw | error | exit, Reason, Stacktrace) ->
+    {fail, {thrown, Reason, Stacktrace}}
+    | {fail, {Reason, Stacktrace}}
+    | {fail, Reason}
+when
+    Reason :: term(), Stacktrace :: erlang:stacktrace().
+format_ct_error(throw, Reason, Stacktrace) ->
+    {fail, {thrown, Reason, Stacktrace}};
+format_ct_error(error, Reason, Stacktrace) ->
+    {fail, {Reason, Stacktrace}};
+format_ct_error(exit, Reason, Stacktrace) when is_list(Stacktrace) ->
+    {fail, {exit, Reason, Stacktrace}}.
+
+-spec build_test_name(part(), [atom()]) -> test_name().
+build_test_name(init_per_suite, _Path) ->
+    init_per_suite;
+build_test_name(end_per_suite, _Path) ->
+    end_per_suite;
+build_test_name(init_per_group, [_, Group]) ->
+    {init_per_group, Group};
+build_test_name(end_per_group, [_, Group]) ->
+    {end_per_group, Group};
+build_test_name(init_per_testcase, [_, Test]) ->
+    Test;
+build_test_name(init_per_testcase, Path) ->
+    [Test, Group | _] = lists:reverse(Path),
+    {Group, Test};
+build_test_name(end_per_testcase, [_, Test]) ->
+    Test;
+build_test_name(end_per_testcase, Path) ->
+    [Test, Group | _] = lists:reverse(Path),
+    {Group, Test}.
+
+-spec get_hook_module(hook_config()) -> module().
+get_hook_module({Mod, _, _}) -> Mod;
+get_hook_module({Mod, _}) -> Mod;
+get_hook_module(Mod) -> Mod.
+
+-spec get_hook_opts(hook_config()) -> [term()].
+get_hook_opts({_, Opts, _}) -> Opts;
+get_hook_opts({_, Opts}) -> Opts;
+get_hook_opts(_) -> [].
+
+-spec get_hook_priority(hook_config()) -> integer() | undefined.
+get_hook_priority({_, _, Prio}) -> Prio;
+get_hook_priority(_) -> undefined.
+
+-spec normalize_part(part(), fun()) -> fun().
+normalize_part(Part, Fun) ->
+    SafeFun = get_safe_part(Part, Fun),
+    case level(Part) of
+        suite -> fun([_Suite], Config) -> SafeFun(Config) end;
+        group -> fun([_Suite, Group], Config) -> SafeFun(Group, Config) end;
+        testcase -> fun(Path, Config) -> SafeFun(lists:last(Path), Config) end
+    end.
+
+%% wrappers because most calls are optional
+-spec call_if_exists(module(), atom(), [term()], Default :: {'$lazy', LazyFun :: fun(() -> term())} | term()) -> term().
+call_if_exists(Mod, Fun, Args, Default) ->
+    case erlang:function_exported(Mod, Fun, erlang:length(Args)) of
+        true ->
+            erlang:apply(Mod, Fun, Args);
+        false ->
+            case Default of
+                {'$lazy', LazyFun} when is_function(LazyFun, 0) -> LazyFun();
+                _ -> Default
+            end
+    end.
+
+-spec call_if_exists_with_fallback(module(), atom(), [term()], term()) -> term().
+call_if_exists_with_fallback(Mod, Fun, Args, ReturnDefault) ->
+    [_ | FallbackArgs] = Args,
+    call_if_exists(Mod, Fun, Args, {'$lazy', fun() -> call_if_exists(Mod, Fun, FallbackArgs, ReturnDefault) end}).
+
+-spec call_if_exists_with_fallback_store_state({module(), term()}, atom(), [term()], term()) -> term().
+call_if_exists_with_fallback_store_state({Mod, Id}, Fun, Args, ReturnDefault) ->
+    {ok, State} = get_state(Id),
+    Default =
+        case Fun of
+            _ when Fun =:= on_tc_fail orelse Fun =:= on_tc_skip -> State;
+            _ -> {ReturnDefault, State}
+        end,
+    CallReturn = call_if_exists_with_fallback(Mod, Fun, Args ++ [State], Default),
+    {NewReturn, NewState} =
+        case Fun of
+            _ when Fun =:= on_tc_fail orelse Fun =:= on_tc_skip -> {ok, CallReturn};
+            _ -> CallReturn
+        end,
+    ok = set_state(Id, NewState),
+    NewReturn.
+
+-spec wrapped_id(module(), opts()) -> term().
+wrapped_id(Mod, Opts) ->
+    case code:ensure_loaded(Mod) of
+        {module, Mod} -> ok;
+        Error -> error({load_hooks_module, Mod, Error})
+    end,
+    call_if_exists(Mod, id, [Opts], make_ref()).
+
+-spec wrapped_init(hook(), opts(), integer() | undefined) -> {integer(), hook_state()}.
+wrapped_init({Mod, Id}, Opts, ConfiguredPriority) ->
+    {InitPriority, InitState} =
+        case Mod:init(Id, Opts) of
+            {ok, State} -> {0, State};
+            {ok, State, Priority} -> {Priority, State};
+            Error -> error({hooks_init_error, Error})
+        end,
+    case ConfiguredPriority of
+        undefined -> {InitPriority, InitState};
+        _ -> {ConfiguredPriority, InitState}
+    end.
+
+-spec pre(part()) -> pre_hook_call().
+pre(init_per_suite) -> pre_init_per_suite;
+pre(init_per_group) -> pre_init_per_group;
+pre(init_per_testcase) -> pre_init_per_testcase;
+pre(end_per_suite) -> pre_end_per_suite;
+pre(end_per_group) -> pre_end_per_group;
+pre(end_per_testcase) -> pre_end_per_testcase.
+
+-spec post(part()) -> post_hook_call().
+post(init_per_suite) -> post_init_per_suite;
+post(init_per_group) -> post_init_per_group;
+post(init_per_testcase) -> post_init_per_testcase;
+post(end_per_suite) -> post_end_per_suite;
+post(end_per_group) -> post_end_per_group;
+post(end_per_testcase) -> post_end_per_testcase.
+
+-spec level(part()) -> hook_level().
+level(init_per_suite) -> suite;
+level(init_per_group) -> group;
+level(init_per_testcase) -> testcase;
+level(end_per_suite) -> suite;
+level(end_per_group) -> group;
+level(end_per_testcase) -> testcase.
+
+-spec init_or_end(part()) -> init | 'end'.
+init_or_end(init_per_suite) -> init;
+init_or_end(init_per_group) -> init;
+init_or_end(init_per_testcase) -> init;
+init_or_end(end_per_suite) -> 'end';
+init_or_end(end_per_group) -> 'end';
+init_or_end(end_per_testcase) -> 'end'.
+
+-spec get_safe_part(part(), fun()) -> fun().
+get_safe_part(Part, Fun) ->
+    case is_exported(Fun) of
+        true -> Fun;
+        false -> dummy(Part)
+    end.
+
+-spec dummy(part()) -> fun().
+dummy(init_per_suite) -> fun(Config) -> Config end;
+dummy(init_per_group) -> fun(_, Config) -> Config end;
+dummy(init_per_testcase) -> fun(_, Config) -> Config end;
+dummy(end_per_suite) -> fun(_) -> ok end;
+dummy(end_per_group) -> fun(_, _) -> ok end;
+dummy(end_per_testcase) -> fun(_, _) -> ok end.
+
+-spec is_exported(fun()) -> boolean().
+is_exported(Fun) ->
+    case maps:from_list(erlang:fun_info(Fun)) of
+        #{
+            type := external,
+            module := Module,
+            name := Function,
+            arity := Arity
+        } when is_atom(Module), is_atom(Function), is_integer(Arity) ->
+            erlang:function_exported(Module, Function, Arity);
+        _ ->
+            false
+    end.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_logger.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_logger.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_logger.erl
@@ -0,0 +1,90 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_daemon_logger).
+-moduledoc """
+CT handles logging and printing by sending a message to the ct_logs
+ process. We intercept those messages for test shell by starting a
+ gen_server that intercepts the messages and prints them to the test
+ shell. We do this instead of using the ct_logs process to have more
+ control over the output and to avoid starting ct processes that
+ might interfere with test shell's functionality.
+""".
+-compile(warn_missing_spec_all).
+
+-behaviour(gen_server).
+
+%% Public API
+-export([start/1]).
+
+%% gen_server callbacks
+-export([init/1, handle_info/2, handle_call/3, handle_cast/2]).
+
+-type state() :: #{}.
+
+-spec init(Args) -> Result when
+    Args :: term(),
+    Result :: {ok, state()}.
+init(_) -> {ok, #{}}.
+
+-spec handle_info
+    (LogMsg, State) -> {noreply, State} when
+        LogMsg :: {
+            log,
+            sync | async,
+            FromPid :: pid(),
+            GL :: pid(),
+            Category :: atom(),
+            Importance :: non_neg_integer(),
+            Content :: [{io:format(), [term()]}],
+            EscChars :: boolean()
+        };
+    (Info, State) -> {noreply, State} when
+        Info :: none(),
+        State :: state().
+handle_info({log, _SyncOrAsync, _FromPid, _GL, _Category, _Importance, Content, _EscChars} = _Info, State) when
+    is_list(Content)
+->
+    % Mimics behaviour from the logger_loop function in ct_logs.erl
+    IoList = lists:foldl(
+        fun
+            ({Format, Args}, IoList) when is_list(Format), is_list(Args) ->
+                [io_lib:format(Format, Args), "\n", IoList];
+            (_, IoList) ->
+                IoList
+        end,
+        [],
+        Content
+    ),
+    io:format("~ts~n", [IoList]),
+    {noreply, State};
+handle_info(_Info, State) ->
+    % ignore
+    {noreply, State}.
+
+-spec handle_call(Request, From, State) -> {noreply, State} when
+    Request :: term(),
+    From :: gen_server:from(),
+    State :: state().
+handle_call(_Info, _From, State) -> {noreply, State}.
+
+-spec handle_cast(Request, State) -> {noreply, State} when
+    Request :: term(),
+    State :: state().
+handle_cast(_Info, State) -> {noreply, State}.
+
+-doc """
+mocks for ct_logs functions
+""".
+-spec start(file:filename_all()) -> ok.
+start(OutputDir) ->
+    LogFile = test_logger:get_log_file(OutputDir, ct_daemon),
+    ok = test_logger:configure_logger(LogFile),
+
+    {ok, _} = gen_server:start_link({local, ct_logs}, ?MODULE, #{}, []),
+    ok.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_node.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_node.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_node.erl
@@ -0,0 +1,318 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_daemon_node).
+-compile(warn_missing_spec_all).
+
+%% Public API
+-export([start/1, start/2, stop/0, alive/0, get_node/0]).
+
+-export([node_main/1, get_domain_type/0]).
+
+-export_type([config/0]).
+
+-include_lib("kernel/include/logger.hrl").
+
+-import(common_util, [unicode_characters_to_binary/1, filename_all_to_filename/1]).
+
+-define(LOG_BASE, "/tmp/ct_daemon").
+
+-type config() :: #{
+    type := shortnames | longnames,
+    name := node(),
+    cookie := atom(),
+    options := [opt()]
+}.
+
+-type opt() ::
+    {multiply_timetraps, number() | infinity}
+    | {ct_hooks, [atom() | {atom(), [term()]}]}
+    | {output_dir, file:filename_all()}.
+
+-doc """
+start node for running tests in isolated way and keep state
+""".
+-spec start(ErlCommand) -> ok | {error, {crash_on_startup, integer()}} when
+    ErlCommand :: nonempty_list(binary()).
+start(ErlCommand) ->
+    NodeName = list_to_atom(
+        lists:flatten(io_lib:format("test~ts-atn@localhost", [random_name()]))
+    ),
+    StartConfig = #{
+        type => shortnames,
+        name => NodeName,
+        cookie => ct_runner:cookie(),
+        options => []
+    },
+    start(ErlCommand, StartConfig).
+
+-doc """
+start node for running tests in isolated way and keep state
+""".
+-spec start(ErlCommand, Config) -> ok | {error, {crash_on_startup, integer()}} when
+    ErlCommand :: nonempty_list(binary()),
+    Config :: config().
+start(
+    ErlCommand,
+    _Config = #{
+        type := Type,
+        name := Node,
+        cookie := Cookie,
+        options := Options
+    }
+) ->
+    RandomName = random_name(),
+    ok = ensure_distribution(Type, RandomName, Cookie),
+    %% get code paths from current node
+    CodePaths = code:get_path(),
+    ConfigFiles = get_config_files(),
+    OutputDir = gen_output_dir(RandomName),
+    FullOptions = [{output_dir, OutputDir} | Options],
+    Args = build_daemon_args(Type, Node, Cookie, FullOptions, OutputDir),
+
+    MainProc = self(),
+    Pid = erlang:spawn(fun() ->
+        true = erlang:register(?MODULE, self()),
+        Port = ct_runner:start_test_node(
+            ErlCommand,
+            [],
+            [],
+            CodePaths,
+            ConfigFiles,
+            OutputDir,
+            [{args, Args}, {cd, OutputDir}]
+        ),
+        port_loop_1(Port, MainProc)
+    end),
+
+    %% wait for the ct_daemon gen_server to be started
+    receive
+        {Pid, ready} ->
+            ok;
+        {Pid, Error = {crash_on_startup, N}} when is_integer(N) ->
+            ?LOG_DEBUG("Test Node Crashed on Startup"),
+            {error, Error}
+    end.
+
+-spec port_loop_1(port(), pid()) -> ok.
+port_loop_1(Port, MainProc) ->
+    receive
+        ready ->
+            true = erlang:unregister(?MODULE),
+            ok = global:sync(),
+            MainProc ! {self(), ready},
+            port_loop_2(Port);
+        {Port, {exit_status, N}} ->
+            MainProc ! {self(), {crash_on_startup, N}},
+            ok;
+        {Port, {data, {noeol, Line}}} ->
+            io:put_chars(Line),
+            port_loop_1(Port, MainProc);
+        {Port, {data, {eol, Line}}} ->
+            io:put_chars([Line, ~"\n"]),
+            port_loop_1(Port, MainProc)
+    end.
+
+-spec port_loop_2(port()) -> ok.
+port_loop_2(Port) ->
+    receive
+        {Port, {exit_status, _}} ->
+            ok;
+        {Port, {data, {noeol, Line}}} ->
+            io:put_chars(Line),
+            port_loop_2(Port);
+        {Port, {data, {eol, Line}}} ->
+            io:put_chars([Line, ~"\n"]),
+            port_loop_2(Port)
+    end.
+
+-spec stop() -> node().
+stop() ->
+    %% the gen_server might be blocked, we spawn a process on the
+    %% remote note that exectues `erlang:halt()' to bypass
+
+    Node = get_node(),
+
+    %% monitore node
+    true = erlang:monitor_node(Node, true),
+    %% kill node
+    %% elp:ignore W0014
+    _Pid = erlang:spawn(Node, fun erlang:halt/0),
+    %% wait for node to come down
+    receive
+        {nodedown, Node} -> ok
+    end,
+    Node.
+
+-spec get_node() -> node().
+get_node() ->
+    case alive() of
+        true ->
+            case get_runner_pid() of
+                undefined -> error(not_running);
+                Pid -> erlang:node(Pid)
+            end;
+        false ->
+            error(not_running)
+    end.
+
+-spec alive() -> boolean().
+alive() ->
+    erlang:is_pid(get_runner_pid()).
+
+-doc """
+node main entry point
+""".
+-spec node_main([node()]) -> no_return().
+node_main([Parent, OutputDirAtom]) ->
+    ok = application:load(test_exec),
+    OutputDir = erlang:atom_to_list(OutputDirAtom),
+
+    %% set stack trace to 20
+    erlang:system_flag(backtrace_depth, 20),
+
+    %% setup logger and prepare IO
+    ok = ct_daemon_logger:start(OutputDir),
+
+    %% setup capture-aware group leader to support ct:capture_* API
+    ok = setup_capture_group_leader(),
+
+    true = net_kernel:connect_node(Parent),
+
+    {ok, {RunnerPid, RunnerMonRef}} = ct_daemon_runner:start_monitor(Parent, OutputDir),
+    {ok, {HooksPid, HooksMonRef}} = ct_daemon_hooks:start_monitor(),
+
+    true = erlang:monitor_node(Parent, true),
+    {?MODULE, Parent} ! ready,
+
+    %% block unless parent node dies or ct_daemon_runner
+    receive
+        {nodedown, _} ->
+            ?LOG_INFO("parent node went down, terminating test node", []),
+            ok;
+        {'DOWN', RunnerMonRef, process, RunnerPid, _} ->
+            ?LOG_INFO("ct_daemon_runner went down, terminating test node", []),
+            ok;
+        {'DOWN', HooksMonRef, process, HooksPid, _} ->
+            ?LOG_INFO("ct_daemon_hooks went down, terminating test node", []),
+            ok
+    end,
+    test_logger:flush(),
+    erlang:halt(0).
+
+%% internal
+-spec ensure_distribution(Type, RandomName, Cookie) -> ok when
+    Type :: shortnames | longnames,
+    RandomName :: binary(),
+    Cookie :: atom().
+ensure_distribution(Type, RandomName, Cookie) ->
+    case erlang:node() of
+        'nonode@nohost' ->
+            % distribution is not started, ensure epmd is
+            (erl_epmd:names("localhost") =:= {error, address}) andalso
+                ([] = os:cmd("epmd -daemon")),
+            Name = list_to_atom(
+                lists:flatten(
+                    io_lib:format("ct_daemon~ts@localhost", [RandomName])
+                )
+            ),
+            {ok, _Pid} = net_kernel:start(Name, #{name_domain => Type}),
+            ok;
+        _ ->
+            %% check that the domain is correct
+            Type = get_domain_type(),
+            ok
+    end,
+    true = erlang:set_cookie(Cookie),
+    ok.
+
+-spec build_daemon_args(Type, Node, Cookie, Options, OutputDir) ->
+    [string()]
+when
+    Type :: shortnames | longnames,
+    Node :: node(),
+    Cookie :: atom(),
+    Options :: [opt()],
+    OutputDir :: file:filename_all().
+build_daemon_args(Type, Node, Cookie, Options, OutputDir) ->
+    DistArg =
+        case Type of
+            longnames -> "-name";
+            shortnames -> "-sname"
+        end,
+    [
+        DistArg,
+        convert_atom_arg(Node),
+        "-setcookie",
+        convert_atom_arg(Cookie),
+        "-test_exec",
+        "daemon_options",
+        lists:flatten(io_lib:format("~w", [Options])),
+        "-s",
+        convert_atom_arg(?MODULE),
+        "node_main",
+        convert_atom_arg(erlang:node()),
+        filename_all_to_filename(OutputDir)
+    ].
+
+-spec convert_atom_arg(atom()) -> string().
+convert_atom_arg(Arg) ->
+    lists:flatten(io_lib:format("~ts", [Arg])).
+
+-spec get_config_files() -> [file:filename_all()].
+get_config_files() ->
+    %% get config files from command line
+    case init:get_argument(config) of
+        error -> [];
+        {ok, Configs} -> [F || ConfigFiles <- Configs, F <- ConfigFiles]
+    end.
+
+-spec gen_output_dir(RandomName :: file:filename_all()) -> file:filename_all().
+gen_output_dir(RandomName) ->
+    BaseDir =
+        case application:get_env(test_exec, ct_daemon_log_dir, undefined) of
+            undefined ->
+                ?LOG_BASE;
+            LogDir ->
+                LogDir
+        end,
+    filename:join([
+        BaseDir,
+        "tests",
+        RandomName
+    ]).
+
+-spec random_name() -> binary().
+random_name() ->
+    N = io_lib:format("~b-~b~ts", [rand:uniform(100000), erlang:unique_integer([positive, monotonic]), os:getpid()]),
+    unicode_characters_to_binary(N).
+
+-spec get_domain_type() -> longnames | shortnames.
+get_domain_type() ->
+    case net_kernel:get_state() of
+        #{name_domain := shortnames} -> shortnames;
+        #{name_domain := longnames} -> longnames
+    end.
+
+-spec get_runner_pid() -> pid() | undefined.
+get_runner_pid() ->
+    global:whereis_name(ct_daemon_runner:name(node())).
+
+-spec setup_capture_group_leader() -> ok.
+setup_capture_group_leader() ->
+    %% Create a capture-aware group leader that handles {capture, Pid} messages
+    %% from ct:capture_start()/test_server:capture_start()
+    OriginalGL = erlang:group_leader(),
+    case ct_daemon_capture:start_link(OriginalGL) of
+        {ok, CaptureGL} ->
+            true = erlang:group_leader(CaptureGL, self()),
+            ok;
+        _ ->
+            %% If capture setup fails, continue without it
+            ok
+    end.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_printer.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_printer.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_printer.erl
@@ -0,0 +1,113 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_daemon_printer).
+-moduledoc """
+Abstractions for pretty printing test results
+""".
+-compile(warn_missing_spec_all).
+
+%% Public API
+-export([print_result/2, print_summary/3]).
+
+-define(CHECK_MARK, "✓").
+-define(CROSS_MARK, "✗").
+-define(SKIP_MARK, "∅").
+-define(SUM_MARK, "∑").
+
+-spec print_summary(Count, Count, Count) -> ok when Count :: non_neg_integer().
+print_summary(Total, Passed, FailedOrSkipped) ->
+    io:format("------------------------------~n"),
+    io:format("~ts   Total: ~b~n", [?SUM_MARK, Total]),
+    io:format("~ts   Passed: ~b~n", [?CHECK_MARK, Passed]),
+    io:format("~ts/~ts Failed or Skipped: ~b~n", [?CROSS_MARK, ?SKIP_MARK, FailedOrSkipped]).
+
+-spec print_result(string(), ct_daemon_core:run_result() | {error, ct_daemon_runner:discover_error()}) ->
+    ok | fail | skip.
+print_result(Name, pass_result) ->
+    io:format("~ts ~ts~n", [?CHECK_MARK, Name]);
+print_result(Name, {fail, {TestId, {end_per_testcase, E}}}) ->
+    print_result(Name ++ " [end_per_testcase]", {fail, {TestId, E}});
+print_result(Name, {fail, {_TestId, {thrown, {Reason, Stacktrace}}}}) ->
+    print_error(Name, throw, Reason, Stacktrace);
+print_result(Name, {fail, {_TestId, {Reason, Stacktrace}}}) ->
+    print_error(Name, error, Reason, Stacktrace);
+print_result(Name, {skip, Where, {error, {Reason, Stacktrace}}}) ->
+    print_skip_error(Name, Where, error, Reason, Stacktrace);
+print_result(Name, {skip, Where, {error, {thrown, Reason, Stacktrace}}}) ->
+    print_skip_error(Name, Where, throw, Reason, Stacktrace);
+print_result(Name, {skip, Where, Reason}) ->
+    io:format("~ts ~ts~n", [?SKIP_MARK, Name]),
+    io:format("skipped at ~ts because of ~tp~n", [print_skip_location(Where), Reason]),
+    skip;
+print_result(Name, {fail, {TestId, Reason}}) ->
+    io:format("~ts ~ts~n", [?CROSS_MARK, Name]),
+    io:format("~ts failed:~n", [TestId]),
+    io:format("~tp~n", [Reason]),
+    fail;
+print_result(Name, {error, {_TestId, {'ct_daemon_core$sentinel_crash', Info}}}) ->
+    io:format("~ts ~ts~n", [?CROSS_MARK, Name]),
+    io:format("Test process received EXIT signal with reason: ~tp~n", [Info]),
+    fail;
+print_result(Name, {error, {_TestId, {timetrap, TimeoutValue}}}) ->
+    io:format("~ts ~ts~n", [?CROSS_MARK, Name]),
+    io:format("Test timed out after ~tp ms~n", [TimeoutValue]),
+    fail;
+print_result(Name, {error, {_TestId, {Reason, Stacktrace}}}) ->
+    io:format("~ts ~ts~n", [?CROSS_MARK, Name]),
+    print_error(Name, error, Reason, Stacktrace);
+print_result(Name, Unstructured) ->
+    io:format("~ts ~ts~n", [?CROSS_MARK, Name]),
+    io:format("unable to format failure reason, please report.~n"),
+    io:format("~tp~n", [Unstructured]),
+    fail.
+
+-spec print_error(Name, Type, Reason, Stacktrace) -> fail when
+    Name :: unicode:chardata(),
+    Type :: error | exit | throw,
+    Reason :: term(),
+    Stacktrace :: erlang:stacktrace() | term().
+print_error(Name, Type, Reason, Stacktrace) ->
+    io:format("~ts ~ts~n", [?CROSS_MARK, Name]),
+    io:format("failed with ~tp:~n", [Type]),
+    Output = ct_error_printer:format_error(Type, {Reason, chop_stack(Stacktrace)}, true),
+    io:format("~ts~n", [Output]),
+    fail.
+
+-spec print_skip_error(Name, Where, Type, Reason, Stacktrace) -> skip when
+    Name :: unicode:chardata(),
+    Where :: term(),
+    Type :: error | exit | throw,
+    Reason :: term(),
+    Stacktrace :: erlang:stacktrace() | term().
+print_skip_error(Name, Where, Type, Reason, Stacktrace) ->
+    io:format("~ts ~ts~n", [?SKIP_MARK, Name]),
+    io:format("skipped at ~ts because of~n", [print_skip_location(Where)]),
+    Output = ct_error_printer:format_error(Type, {Reason, chop_stack(Stacktrace)}, true),
+    io:format("~ts~n", [Output]),
+    skip.
+
+-spec print_skip_location(Location) -> unicode:chardata() when
+    Location :: {_, atom()} | term().
+print_skip_location({_, GroupOrSuite}) when is_atom(GroupOrSuite) ->
+    case re:run(atom_to_list(GroupOrSuite), "SUITE$", [unicode]) of
+        nomatch -> io_lib:format("init_per_group of ~ts", [GroupOrSuite]);
+        _ -> "init_per_suite"
+    end;
+print_skip_location(Other) ->
+    io_lib:format("~ts", [Other]).
+
+-spec chop_stack(term()) -> term().
+chop_stack(E = {failed, _}) ->
+    E;
+chop_stack(Stacktrace) when is_list(Stacktrace) ->
+    lists:takewhile(
+        fun({Module, _, _, _}) -> not lists:member(Module, [ct_daemon_core, ct_daemon_hooks]) end, Stacktrace
+    );
+chop_stack(Other) ->
+    Other.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_runner.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_runner.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_daemon_runner.erl
@@ -0,0 +1,271 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_daemon_runner).
+-moduledoc """
+gen_server holding state between test runs
+""".
+-compile(warn_missing_spec_all).
+
+-behavior(gen_server).
+
+%% gen_server API
+-export([init/1, handle_call/3, handle_cast/2, handle_info/2]).
+
+%% Public API
+-export([start_monitor/2, name/1]).
+
+-export_type([discover_error/0]).
+
+-include_lib("kernel/include/logger.hrl").
+
+-type state() :: #{
+    enumerated_tests => #{test_id() => string()},
+    output_dir => file:filename_all(),
+    setup => ct_daemon_core:setup()
+}.
+
+-type regex() :: string().
+-type test_id() :: non_neg_integer().
+-type discovered() :: {discovered, [#{suite := module(), name := string()}]}.
+
+-type discover_error() ::
+    {ambiguous_test_regex, [{module(), [{non_neg_integer(), string()}]}]}
+    | {id_not_found, non_neg_integer()}
+    | not_listed_yet
+    | invalid_regex
+    | {invalid_regex, {string(), non_neg_integer()}}.
+
+-spec start_monitor(Node, OutputDir) -> gen_server:start_mon_ret() when
+    Node :: node(),
+    OutputDir :: file:filename_all().
+start_monitor(Node, OutputDir) ->
+    gen_server:start_monitor(
+        {global, name(Node)},
+        ?MODULE,
+        [#{output_dir => OutputDir, setup => undefined}],
+        []
+    ).
+
+-doc """
+global name based on calling node
+""".
+-spec name(node()) -> atom().
+name(Node) ->
+    erlang:list_to_atom(lists:flatten(io_lib:format("~ts-~ts", [Node, ?MODULE]))).
+
+%% gen_server for keeping state
+-spec init([state()]) -> {ok, state()}.
+init([InitState]) ->
+    {ok, InitState}.
+
+-spec handle_call
+    (ping, gen_server:from(), state()) -> {reply, {pong, state()}, state()};
+    (list, gen_server:from(), state()) -> {reply, [{module(), [{non_neg_integer(), string()}]}], state()};
+    ({run, RegExOrTestIdOrDiscovered}, gen_server:from(), state()) ->
+        {reply, CollectedResults | {error, Reason}, state()}
+    when
+        RegExOrTestIdOrDiscovered :: regex() | test_id() | discovered(),
+        CollectedResults :: ct_daemon_core:run_result(),
+        Reason :: discover_error();
+    ({discover, RegExOrTestId}, gen_server:from(), state()) -> {reply, Tests | {error, Reason}, state()} when
+        RegExOrTestId :: regex() | test_id(),
+        Tests :: [#{suite := module(), name := string()}],
+        Reason :: discover_error();
+    (load_changed, gen_server:from(), state()) -> {reply, [module()], state()};
+    (setup, gen_server:from(), state()) -> {reply, undefined | [atom()], state()};
+    (output_dir, gen_server:from(), state()) -> {reply, file:filename_all(), state()};
+    (priv_dir, gen_server:from(), state()) -> {reply, undefined | file:filename_all(), state()}.
+
+handle_call(ping, _From, State) ->
+    {reply, {pong, State}, State};
+handle_call(list, _From, State) ->
+    case ct_daemon_core:list() of
+        Tests when is_map(Tests) -> list_result(Tests, State)
+    end;
+handle_call({run, RegExOrTestIdOrDiscovered}, _From, State) ->
+    try
+        case get_tests(RegExOrTestIdOrDiscovered, State) of
+            E = {error, _} ->
+                {reply, E, State};
+            Tests ->
+                {CollectedResults, EndState} = lists:foldl(
+                    fun(Test, {Results, InState}) ->
+                        {TestResult, OutState} = run_test(Test, InState),
+                        {Results#{Test => TestResult}, OutState}
+                    end,
+                    {#{}, State},
+                    Tests
+                ),
+                {reply, CollectedResults, EndState}
+        end
+    catch
+        Err:R:ST ->
+            {reply, {error, {Err, R, ST}}, State}
+    end;
+handle_call({discover, RegExOrTestId}, _From, State) ->
+    case discover_test(RegExOrTestId, State) of
+        E = {error, _} ->
+            {reply, E, State};
+        Tests ->
+            {reply,
+                [
+                    ct_daemon_core:from_qualified(Test)
+                 || Test <- Tests
+                ],
+                State}
+    end;
+handle_call(load_changed, _From, State) ->
+    {reply, load_changed_modules(), State};
+handle_call(setup, _From, #{setup := #{setup_state := {Names, _}}} = State) ->
+    {reply, Names, State};
+handle_call(setup, _From, State) ->
+    {reply, undefined, State};
+handle_call(output_dir, _From, State) ->
+    DaemonOptions = application:get_env(test_exec, daemon_options, []),
+    {reply, proplists:get_value(output_dir, DaemonOptions), State};
+handle_call(priv_dir, _From, State) ->
+    Response =
+        case State of
+            #{setup := #{config := Config}} ->
+                proplists:get_value(priv_dir, Config);
+            _ ->
+                undefined
+        end,
+    {reply, Response, State};
+handle_call(Request, _From, _State) ->
+    error({unexpected_request, Request}).
+
+-spec handle_cast
+    ({code_paths, Paths}, state()) -> {noreply, state()} when
+        Paths :: [file:filename()];
+    ({load_module, Module}, state()) -> {noreply, state()} when
+        Module :: module().
+handle_cast({code_paths, Paths}, State) ->
+    ?LOG_DEBUG("adding code paths ~tp", [Paths]),
+    ok = code:add_paths(Paths),
+    {noreply, State};
+handle_cast({load_module, Module}, State) ->
+    reload_module(Module),
+    {noreply, State};
+handle_cast(Request, State) ->
+    ?LOG_INFO("unrecognized cast: ~tp state: ~tp", [Request, State]),
+    erlang:error(not_implemented).
+
+-spec handle_info(term(), state()) -> {noreply, state()}.
+handle_info(_Info, State) ->
+    {noreply, State}.
+
+%% internal
+-spec get_tests(RegexOrTestIdOrDiscovered, state()) -> {error, discover_error()} | [string()] when
+    RegexOrTestIdOrDiscovered :: regex() | test_id() | discovered().
+get_tests({discovered, Discovered}, _State) ->
+    [ct_daemon_core:to_qualified(Test) || Test <- Discovered];
+get_tests(RegExOrTestId, State) ->
+    discover_test(RegExOrTestId, State).
+
+-spec discover_test(regex() | test_id(), state()) -> {error, discover_error()} | [string()].
+discover_test(TestId, State) when erlang:is_integer(TestId) ->
+    case State of
+        #{enumerated_tests := #{TestId := Test}} ->
+            [Test];
+        #{enumerate_tests := _} ->
+            {error, {id_not_found, TestId}};
+        _ ->
+            {error, not_listed_yet}
+    end;
+discover_test(RegEx, _State) when erlang:is_list(RegEx) ->
+    case ct_daemon_core:list() of
+        Listing when is_map(Listing) ->
+            case re:compile(RegEx, [unicode]) of
+                {ok, Pattern} ->
+                    [Test || _Suite := Tests <- Listing, Test <- Tests, re:run(Test, Pattern) =/= nomatch];
+                {error, ErrSpec} ->
+                    {error, {invalid_regex, ErrSpec}}
+            end
+    end;
+discover_test(_, _) ->
+    {error, invalid_regex}.
+
+-spec list_result(#{module() => [string()]}, state()) ->
+    {reply, [{module(), [{non_neg_integer(), string()}]}], state()}.
+list_result(Tests, State) ->
+    {_, EnumeratedTests} = enumerate_tests(Tests),
+    NewState = State#{enumerated_tests => flatten_enumerated_tests(EnumeratedTests)},
+    {reply, EnumeratedTests, NewState}.
+
+-spec enumerate_tests(#{module() => [string()]}) -> {number(), [{module(), [{non_neg_integer(), string()}]}]}.
+enumerate_tests(Tests) ->
+    maps:fold(
+        fun(Suite, SuiteTests, {InCounter, Acc}) ->
+            {InCounter + erlang:length(SuiteTests), [
+                {Suite, lists:enumerate(InCounter, SuiteTests)} | Acc
+            ]}
+        end,
+        {0, []},
+        Tests
+    ).
+
+-spec flatten_enumerated_tests([{module(), [{non_neg_integer(), string()}]}]) ->
+    #{non_neg_integer() => string()}.
+flatten_enumerated_tests(Tests) ->
+    maps:from_list(lists:flatten([SuiteTests || {_, SuiteTests} <- Tests])).
+
+-spec run_test(string(), state()) -> {ct_daemon_core:run_result(), state()}.
+run_test(Test, State = #{output_dir := OutputDir, setup := InSetupState}) ->
+    #{suite := Suite, name := Name} = ct_daemon_core:from_qualified(Test),
+    Spec = common_util:parse_test_name(Name, Suite),
+
+    ?LOG_INFO("discovered test ~tp with spec ~tp", [Name, Spec]),
+
+    {Result, OutSetupState} = ct_daemon_core:run_test(Spec, InSetupState, OutputDir),
+
+    {Result, State#{setup => OutSetupState}}.
+
+-spec load_changed_modules() -> [module()].
+load_changed_modules() ->
+    ChangedModules = lists:usort([
+        M
+     || {M, _} <- code:all_loaded(), module_modified(M)
+    ]),
+    [reload_module(Module) || Module <- ChangedModules],
+    ChangedModules.
+
+-spec module_modified(Mod) -> boolean() when
+    Mod :: module().
+module_modified(Mod) ->
+    case code:is_loaded(Mod) of
+        {file, preloaded} ->
+            false;
+        {file, BeamPath} ->
+            case code:is_sticky(Mod) of
+                false -> module_modified(Mod, BeamPath);
+                true -> false
+            end;
+        _ ->
+            false
+    end.
+
+-spec module_modified(Module, BeamPath) -> boolean() when
+    Module :: module(),
+    BeamPath :: file:filename().
+module_modified(Mod, BeamPath) ->
+    LoadedMD5 = Mod:module_info(md5),
+    case beam_lib:md5(BeamPath) of
+        {ok, {Mod, DiskMD5}} ->
+            LoadedMD5 =/= DiskMD5;
+        _ ->
+            false
+    end.
+
+-spec reload_module(Module) -> ok when
+    Module :: module().
+reload_module(Module) ->
+    code:purge(Module),
+    {module, Module} = code:load_file(Module),
+    ok.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_executor.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_executor.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_executor.erl
@@ -0,0 +1,244 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_executor).
+-moduledoc """
+Simple trampoline for ct_run.
+Notably allows us to call post/pre method on the node if needed, e.g for coverage.
+""".
+-compile(warn_missing_spec_all).
+
+-export([run/1]).
+
+% For testing
+-export([preload_app_file_atoms/1, split_args/1]).
+
+-include_lib("kernel/include/logger.hrl").
+-include_lib("common/include/buck_ct_records.hrl").
+
+%% `ct_run_arg()` represents an option accepted by ct:run_test/1, such as
+%% `multiply_timetraps` or `ct_hooks`.
+%% For all the options, see https://www.erlang.org/doc/man/ct#run_test-1
+-type ct_run_arg() ::
+    {dir, dynamic()}
+    | {suite, dynamic()}
+    | {group, dynamic()}
+    | {testcase, dynamic()}
+    | {spec, dynamic()}
+    | {join_specs, dynamic()}
+    | {label, dynamic()}
+    | {config, dynamic()}
+    | {userconfig, dynamic()}
+    | {allow_user_terms, dynamic()}
+    | {logdir, dynamic()}
+    | {silent_connections, dynamic()}
+    | {stylesheet, dynamic()}
+    | {cover, dynamic()}
+    | {cover_stop, dynamic()}
+    | {step, dynamic()}
+    | {event_handler, dynamic()}
+    | {include, dynamic()}
+    | {auto_compile, dynamic()}
+    | {abort_if_missing_suites, dynamic()}
+    | {create_priv_dir, dynamic()}
+    | {multiply_timetraps, dynamic()}
+    | {scale_timetraps, dynamic()}
+    | {repeat, dynamic()}
+    | {duration, dynamic()}
+    | {until, dynamic()}
+    | {force_stop, dynamic()}
+    | {decrypt, dynamic()}
+    | {refresh_logs, dynamic()}
+    | {logopts, dynamic()}
+    | {verbosity, dynamic()}
+    | {basic_html, dynamic()}
+    | {esc_chars, dynamic()}
+    | {keep_logs, dynamic()}
+    | {ct_hooks, dynamic()}
+    | {ct_hooks_order, dynamic()}
+    | {enable_builtin_hooks, dynamic()}
+    | {release_shell, dynamic()}.
+
+-type ct_exec_arg() ::
+    {output_dir, file:filename()}
+    | {server_port, inet:port_number()}
+    | {suite, module()}
+    | {providers, [{Name :: atom(), Args :: term()}]}
+    | {common_app_env, #{binary() => binary()}}.
+
+-define(raw_file_access, prim_file).
+
+-spec run([string()]) -> no_return().
+run(Args) when is_list(Args) ->
+    {ok, CWDDir} = prim_file:get_cwd(),
+    os:putenv("HOME", CWDDir),
+    ExitCode =
+        try
+            {CtExecutorArgs, CtRunArgs} = parse_arguments(Args),
+            debug_print("~tp", [#{ct_exec_args => CtExecutorArgs, ct_run_args => CtRunArgs}]),
+            [OutputDir | _] = [OutputDir || {output_dir, OutputDir} <- CtExecutorArgs],
+            ok = test_logger:set_up_logger(OutputDir, ?MODULE, no_capture_stdout),
+            % Until this point the logger is not set up so we cannot log.
+            % Therefore we used io:format to forward information to the
+            % process calling it (ct_runner).
+
+            %% log arguments into ct_executor.log
+            ?LOG_INFO("raw args: ~tp", [Args]),
+            ?LOG_INFO("executor args: ~tp", [CtExecutorArgs]),
+            ?LOG_INFO("CtRunArgs: ~tp", [CtRunArgs]),
+
+            try
+                %% setup watchdog
+                [ServerPort | _] = [ServerPort || {server_port, ServerPort} <- CtExecutorArgs],
+                ct_executor_watchdog:start_link_client(ServerPort),
+
+                ok = init_common_app_env(proplists:get_value(common_app_env, CtExecutorArgs, #{})),
+                ok = preload_application_atoms(),
+                [Suite | _] = [Suite || {suite, Suite} <- CtExecutorArgs],
+
+                {ok, RawTarget} = common_util:get_env(raw_target),
+
+                ProviderInitState = #init_provider_state{output_dir = OutputDir, suite = Suite, raw_target = RawTarget},
+                Providers0 = [
+                    buck_ct_provider:do_init(Provider, ProviderInitState)
+                 || {providers, Providers} <- CtExecutorArgs,
+                    Provider <- Providers
+                ],
+
+                %% get longer stack traces
+                erlang:system_flag(backtrace_depth, 20),
+                ?LOG_DEBUG("ct_run called with arguments ~tp ~n", [CtRunArgs]),
+                Providers1 = [buck_ct_provider:do_pre_running(Provider) || Provider <- Providers0],
+
+                %% set global timeout
+                Result = ct:run_test(CtRunArgs),
+                ?LOG_DEBUG("ct_run finished with result ~tp ~n", [Result]),
+                Providers2 = [buck_ct_provider:do_post_running(Provider) || Provider <- Providers1],
+                [buck_ct_provider:do_terminate(Provider) || Provider <- Providers2],
+                0
+            catch
+                Class:Reason:Stack ->
+                    ?LOG_ERROR("ct executor failed due to ~ts\n", [
+                        erl_error:format_exception(Class, Reason, Stack)
+                    ]),
+                    2
+            after
+                test_logger:flush()
+            end
+        catch
+            % Catch an exception that happens before logging is set up.
+            % Will forward the exception to the process that opened the port (ct_runner).
+            Class1:Reason1:Stack1 ->
+                io:format("~ts\n", [erl_error:format_exception(Class1, Reason1, Stack1)]),
+                1
+        end,
+    erlang:halt(ExitCode).
+
+-spec parse_arguments([string()]) -> {[ct_exec_arg()], [ct_run_arg()]}.
+parse_arguments(Args) ->
+    % The logger is not set up yet.
+    % This will be sent to the program executing it (ct_runner),
+    % that will log it in its own log.
+    debug_print("CT executor called with ~tp~n", [Args]),
+    ParsedArgs = [buck_ct_parser:parse_str(Elem) || Elem <:- Args],
+    debug_print("Parsed arguments ~tp~n", [ParsedArgs]),
+    % We split the arguments between those that go to ct_run and those that are for
+    % ct_executor
+    % the args passed to ct are to be found after the --ct-args
+    split_args(ParsedArgs).
+
+-doc """
+Splits the argument before those that happens
+before ct_args (the executor args) and those after
+(the args for ct_run). ct_args will always be
+present in the list
+""".
+-spec split_args([term()]) -> {[ct_exec_arg()], [ct_run_arg()]}.
+split_args(Args) ->
+    {CtExecutorArgs, [ct_args | CtRunArgs]} = lists:splitwith(fun(Arg) -> Arg =/= ct_args end, Args),
+    {parse_ct_exec_args(CtExecutorArgs), parse_ct_run_args(CtRunArgs)}.
+
+-spec parse_ct_run_args([dynamic()]) -> [ct_run_arg()].
+parse_ct_run_args([]) ->
+    [];
+parse_ct_run_args([{Key, _Value} = Arg | Args]) when is_atom(Key) ->
+    [Arg | parse_ct_run_args(Args)].
+
+-spec parse_ct_exec_args([dynamic()]) -> [ct_exec_arg()].
+parse_ct_exec_args([]) ->
+    [];
+parse_ct_exec_args([{Key, _Value} = Arg | Args]) when
+    Key =:= output_dir; Key =:= server_port; Key =:= suite; Key =:= providers; Key =:= common_app_env
+->
+    [Arg | parse_ct_exec_args(Args)].
+
+-spec init_common_app_env(#{binary() => binary()}) -> ok.
+init_common_app_env(CommonAppEnv) ->
+    ok = load_common_app(),
+    maps:foreach(fun init_common_app_env_var/2, CommonAppEnv).
+
+-spec load_common_app() -> ok.
+load_common_app() ->
+    case application:load(common) of
+        ok -> ok;
+        {error, {already_loaded, common}} -> ok;
+        Error -> error({load_common_app, Error})
+    end.
+
+-spec init_common_app_env_var(binary(), binary()) -> ok.
+init_common_app_env_var(Key, Value) ->
+    KeyAtom = binary_to_atom(Key, utf8),
+    case common_util:get_env(KeyAtom) of
+        undefined ->
+            ValueTerm = buck_ct_parser:parse_str(Value),
+            common_util:set_env(KeyAtom, ValueTerm);
+        _ ->
+            ok
+    end.
+
+-spec preload_application_atoms() -> ok.
+preload_application_atoms() ->
+    PotentialDotApp = [
+        filename:join(Dep, filename:basename(filename:dirname(Dep)) ++ ".app")
+     || Dep <- code:get_path()
+    ],
+    lists:foreach(fun preload_app_file_atoms/1, PotentialDotApp),
+    ok.
+
+-doc """
+Loads atoms referenced by an application resource file into the atom table.
+""".
+-spec preload_app_file_atoms(file:filename_all()) -> ok.
+preload_app_file_atoms(DotApp) ->
+    case filelib:is_regular(DotApp, ?raw_file_access) of
+        true ->
+            case file:read_file(DotApp, [raw]) of
+                {ok, DotAppContents} ->
+                    % Some tests call *_to_existing_atom for atoms that only appear in dependency .app files.
+                    % Tokenizing preserves that side effect without constructing the full terms.
+                    case unicode:characters_to_list(DotAppContents) of
+                        DotAppString when is_list(DotAppString) ->
+                            _ = erl_scan:string(DotAppString),
+                            ok;
+                        _ ->
+                            ok
+                    end;
+                {error, _} ->
+                    ok
+            end;
+        false ->
+            ok
+    end.
+
+-spec debug_print(string(), [term()]) -> ok.
+debug_print(Fmt, Args) ->
+    case os:getenv("ERLANG_BUCK_DEBUG_PRINT") of
+        false -> io:format(Fmt, Args);
+        "disabled" -> ok;
+        _ -> io:format(Fmt, Args)
+    end.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_executor_watchdog.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_executor_watchdog.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_executor_watchdog.erl
@@ -0,0 +1,88 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+% @format
+-module(ct_executor_watchdog).
+-moduledoc """
+This module is responsible for watching the test binary and killing the beam
+if the test binary goes down. This is needed because the test binary can be
+terminated by the test runner in ways (SIGKILL) that we cannot intercept and
+we want to ensure we don't leave lingering beam instances behind.
+
+NOTE: Ideally, we would use the peer module to start the test node and have
+this shutdown handled by it.
+""".
+-compile(warn_missing_spec_all).
+
+-behaviour(gen_server).
+
+-export([start_link_client/1, start_server/0]).
+
+-export([
+    init/1,
+    handle_info/2,
+    handle_call/3,
+    handle_cast/2
+]).
+
+-include_lib("kernel/include/logger.hrl").
+
+-record(state, {
+    socket :: gen_tcp:socket() | undefined
+}).
+
+-spec start_server() -> {ok, number()}.
+start_server() ->
+    ServerPid = spawn(fun server/0),
+    Ref = make_ref(),
+    ServerPid ! {self(), Ref, get_port},
+    receive
+        {Ref, Port} -> {ok, Port}
+    end.
+
+-spec server() -> ok.
+server() ->
+    {ok, LSock} = gen_tcp:listen(0, [binary, {active, false}, inet6]),
+    {ok, Port} = inet:port(LSock),
+    receive
+        {From, Ref, get_port} -> From ! {Ref, Port}
+    end,
+    {ok, _Sock} = gen_tcp:accept(LSock),
+    %% wait forever
+    receive
+        _ -> ok
+    end.
+
+-spec start_link_client(Port :: integer()) -> gen_server:start_ret().
+start_link_client(Port) ->
+    gen_server:start_link({local, ?MODULE}, ?MODULE, [Port], []).
+
+-spec init([Port :: integer()]) -> {ok, #state{}} | {error, failed_to_connect_watchdog}.
+init([Port]) ->
+    try
+        {ok, Sock} = gen_tcp:connect("localhost", Port, [inet6, {active, true}]),
+        {ok, #state{socket = Sock}}
+    catch
+        Class:Reason:Stack ->
+            ?LOG_ERROR("Failed to connect to watchdog server: ~ts", [erl_error:format_exception(Class, Reason, Stack)]),
+            {error, failed_to_connect_watchdog}
+    end.
+
+-spec handle_call(any(), gen_server:from(), #state{}) -> no_return().
+handle_call(_Request, _From, _State) ->
+    error(not_implemented).
+
+-spec handle_cast(any(), #state{}) -> no_return().
+handle_cast(_Request, _State) ->
+    error(not_implemented).
+
+-spec handle_info(any(), #state{}) -> no_return().
+handle_info({tcp_closed, Socket}, #state{socket = Socket}) ->
+    %% when the test binary goes down, we kill the beam
+    ?LOG_CRITICAL("Test binary went down, killing beam"),
+    test_logger:flush(),
+    erlang:halt(1).
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/ct_runner.erl b/buck2/prelude/erlang/common_test/test_exec/src/ct_runner.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/ct_runner.erl
@@ -0,0 +1,457 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(ct_runner).
+-moduledoc """
+Simple gen_server that will run the the test and
+communicates the result to the test runner.
+""".
+-compile(warn_missing_spec_all).
+
+-behavior(gen_server).
+
+-export([start_link/1]).
+
+-export([
+    init/1,
+    handle_continue/2,
+    handle_call/3,
+    handle_cast/2,
+    handle_info/2,
+    terminate/2
+]).
+
+-export([
+    start_test_node/6,
+    start_test_node/7,
+    cookie/0,
+    generate_arg_tuple/2,
+    project_root/0
+]).
+
+-export_type([port_settings/0]).
+
+-include_lib("common/include/buck_ct_records.hrl").
+-include_lib("kernel/include/logger.hrl").
+
+-define(raw_file_access, prim_file).
+
+-import(common_util, [unicode_characters_to_binary/1, filename_all_to_filename/1]).
+
+-type opt() ::
+    {packet, N :: 1 | 2 | 4}
+    | stream
+    | {line, L :: non_neg_integer()}
+    | {cd, Dir :: string() | binary()}
+    | {env, Env :: [{Name :: os:env_var_name(), Val :: os:env_var_value() | false}]}
+    | {args, [string() | binary()]}
+    | {arg0, string() | binary()}
+    | exit_status
+    | use_stdio
+    | nouse_stdio
+    | stderr_to_stdout
+    | in
+    | out
+    | binary
+    | eof
+    | {parallelism, Boolean :: boolean()}
+    | hide
+    | {busy_limits_port, {non_neg_integer(), non_neg_integer()} | disabled}
+    | {busy_limits_msgq, {non_neg_integer(), non_neg_integer()} | disabled}.
+
+-type port_settings() :: [opt()].
+
+-type initial_state() :: #{
+    test_env := #test_env{}
+}.
+-type state() ::
+    #{
+        test_env := #test_env{},
+        ct_stdout_state := ct_stdout:process_stdout_state(),
+        port := erlang:port()
+    }.
+
+%% Starts and monitor (through an erlang port) a ct_run.
+%% Reports the result of the execution to the test runner.
+-spec start_link(#test_env{}) -> gen_server:start_ret().
+start_link(#test_env{} = TestEnv) ->
+    gen_server:start_link({local, ?MODULE}, ?MODULE, TestEnv, []).
+
+-spec init(TestEnv) -> {ok, initial_state(), {continue, {run, PortEpmd}}} when
+    TestEnv :: #test_env{},
+    PortEpmd :: inet:port_number().
+init(#test_env{} = TestEnv) ->
+    process_flag(trap_exit, true),
+    PortEpmd = epmd_manager:get_port(),
+    {ok, #{test_env => TestEnv}, {continue, {run, PortEpmd}}}.
+
+-spec handle_continue({run, PortEpmd}, State0) -> {noreply, State1} | {stop, Reason, State0} when
+    PortEpmd :: inet:port_number(),
+    State0 :: initial_state(),
+    State1 :: state(),
+    Reason :: ct_runner_failed.
+handle_continue({run, PortEpmd}, #{test_env := TestEnv} = State0) ->
+    OutputDir = TestEnv#test_env.output_dir,
+    StdOutFile = ct_stdout:filename(OutputDir),
+    CtStdOutState = ct_stdout:init_process_stdout_state(
+        TestEnv#test_env.ct_stdout_fingerprint,
+        StdOutFile,
+        TestEnv#test_env.ct_stdout_streaming
+    ),
+    try run_test(TestEnv, PortEpmd) of
+        Port ->
+            State1 = State0#{
+                port => Port,
+                ct_stdout_state => CtStdOutState
+            },
+            {noreply, State1}
+    catch
+        Class:Reason:Stack ->
+            ErrorMsg = io_lib:format("Ct Runner failed to launch test due to ~ts\n", [
+                erl_error:format_exception(Class, Reason, Stack)
+            ]),
+            ?LOG_ERROR(ErrorMsg),
+            report_result(TestEnv, run_failed, ErrorMsg, #{}),
+            {stop, ct_runner_failed, State0}
+    end.
+
+-spec handle_info
+    ({Port, {exit_status, ExitStatus}}, state()) ->
+        {stop, {ct_run_finished, ExitStatus}, state()} | {noreply, state()}
+    when
+        Port :: erlang:port(),
+        ExitStatus :: integer();
+    ({Port, {data, {eol | noeol, Data}}}, state()) -> {noreply, state()} when
+        Port :: erlang:port(),
+        Data :: binary();
+    ({Port, closed}, state()) -> {stop, ct_port_closed, state()} | {noreply, state()} when
+        Port :: erlang:port();
+    ({'EXIT', Port, Reason}, state()) -> {stop, {ct_port_exit, Reason}, state()} | {noreply, state()} when
+        Port :: erlang:port(),
+        Reason :: term().
+
+handle_info({Port, {exit_status, ExitStatus}}, #{port := Port, test_env := TestEnv} = State) ->
+    CtStdoutState = maps:get(ct_stdout_state, State),
+    {eof, ProgressMarkersOffsets} = ct_stdout:process_stdout_line(eof, CtStdoutState),
+    case ExitStatus of
+        0 ->
+            ResultMsg = "ct_runner finished successfully with exit status 0",
+            ?LOG_DEBUG(ResultMsg),
+            report_result(TestEnv, run_succeed, ResultMsg, ProgressMarkersOffsets);
+        _ ->
+            ErrorMsg =
+                case ExitStatus of
+                    N when N == 137 orelse N == 143 ->
+                        io_lib:format(
+                            ("ct runner killed by SIGKILL (exit code ~b), likely due to running out of memory."
+                            " Check https://fburl.com/wiki/01s5fnom for information about memory limits for tests"),
+                            [ExitStatus]
+                        );
+                    _ ->
+                        io_lib:format("ct run exited with status exit ~tp", [
+                            ExitStatus
+                        ])
+                end,
+            ?LOG_ERROR(ErrorMsg),
+            report_result(TestEnv, run_failed, ErrorMsg, ProgressMarkersOffsets)
+    end,
+    {stop, {ct_run_finished, ExitStatus}, State};
+handle_info({Port, {data, Data}}, State0 = #{port := Port}) ->
+    CtStdoutState0 = maps:get(ct_stdout_state, State0),
+    {ok, CtStdoutState1} = ct_stdout:process_stdout_line(Data, CtStdoutState0),
+    State1 = State0#{ct_stdout_state => CtStdoutState1},
+    {noreply, State1};
+handle_info({Port, closed}, #{port := Port} = State) ->
+    {stop, ct_port_closed, State};
+handle_info({'EXIT', Port, Reason}, #{port := Port} = State) ->
+    {stop, {ct_port_exit, Reason}, State};
+handle_info(_Info, State) ->
+    {noreply, State}.
+
+-spec handle_call(term(), gen_server:from(), state()) -> no_return().
+handle_call(_Request, _From, _State) -> error(not_implemented).
+
+-spec handle_cast(term(), state()) -> no_return().
+handle_cast(_Request, _State) -> error(not_implemented).
+
+-spec terminate(Reason, State) -> ok when
+    Reason :: normal | shutdown | {shutdown, term()} | term(),
+    State :: initial_state() | state().
+terminate(_Reason, #{port := Port}) ->
+    test_exec:kill_process(Port);
+terminate(_Reason, _State) ->
+    ok.
+
+-spec report_result(TestEnv, Outcome, Result, ProgressMarkersOffsets) -> ok when
+    TestEnv :: #test_env{},
+    Outcome :: run_succeed | run_failed,
+    Result :: unicode:chardata(),
+    ProgressMarkersOffsets :: #{ct_stdout:progress_line() => ct_stdout:offset()}.
+report_result(#test_env{result_recipient = Recipient}, Outcome, Result, ProgressMarkersOffsets) ->
+    Recipient ! {Outcome, Result, ProgressMarkersOffsets},
+    ok.
+
+-doc """
+Executes the test in a new node by launching ct_run.
+""".
+-spec run_test(#test_env{}, integer()) -> port().
+run_test(
+    #test_env{
+        test_spec_file = TestSpecFile,
+        output_dir = OutputDir,
+        config_files = ConfigFiles,
+        dependencies = Dependencies,
+        suite_path = SuitePath,
+        providers = Providers,
+        suite = Suite,
+        erl_cmd = ErlCmd,
+        extra_flags = ExtraFlags,
+        common_app_env = CommonAppEnv0,
+        raw_target = RawTarget,
+        trampolines = Trampolines
+    } = _TestEnv,
+    PortEpmd
+) ->
+    % We create the arguments for the ct_run, adding the ebin folder
+    % where the suite is as part of the dependencies.
+    SuiteFolder = filename:dirname(filename:absname(SuitePath)),
+    CodePath = [SuiteFolder | Dependencies],
+    CommonAppEnv1 = CommonAppEnv0#{~"raw_target" => unicode_characters_to_binary(io_lib:format("~0p", [RawTarget]))},
+    {ok, ServerPort} = ct_executor_watchdog:start_server(),
+
+    Args = build_run_args(OutputDir, ServerPort, Providers, Suite, TestSpecFile, CommonAppEnv1),
+
+    {ok, ProjectRoot} = prim_file:get_cwd(),
+
+    start_test_node(
+        ErlCmd,
+        Trampolines,
+        ExtraFlags,
+        CodePath,
+        ConfigFiles,
+        OutputDir,
+        [
+            {args, Args},
+            {env, [
+                {"ERL_EPMD_PORT", integer_to_list(PortEpmd)},
+                {"PROJECT_ROOT", ProjectRoot}
+            ]}
+        ]
+    ).
+
+-spec build_common_args(
+    CodePath :: [file:filename_all()],
+    ConfigFiles :: [file:filename_all()]
+) -> [binary() | string()].
+build_common_args(CodePath, ConfigFiles) ->
+    lists:append([
+        [~"-noinput"],
+        [~"-pa"],
+        CodePath,
+        config_arg(ConfigFiles)
+    ]).
+
+-spec build_run_args(
+    OutputDir :: file:filename_all(),
+    ServerPort :: number(),
+    Providers :: [{module(), [term()]}],
+    Suite :: module(),
+    TestSpecFile :: file:filename_all(),
+    CommonAppEnv :: #{binary() => binary()}
+) -> [binary()].
+build_run_args(OutputDir, ServerPort, Providers, Suite, TestSpecFile, CommonAppEnv) ->
+    lists:append(
+        [
+            [~"-run", ~"ct_executor", ~"run"],
+            generate_arg_tuple(output_dir, OutputDir),
+            generate_arg_tuple(server_port, ServerPort),
+            generate_arg_tuple(providers, Providers),
+            generate_arg_tuple(suite, Suite),
+            generate_arg_tuple(common_app_env, CommonAppEnv),
+            [~"ct_args"],
+            generate_arg_tuple(spec, TestSpecFile)
+        ]
+    ).
+
+-spec start_test_node(
+    Erl :: [binary()],
+    ExtraFlags :: [binary()],
+    CodePath :: [file:filename_all()],
+    ConfigFiles :: [file:filename_all()],
+    OutputDir :: file:filename_all(),
+    PortSettings :: port_settings()
+) -> port().
+start_test_node(
+    ErlCmd,
+    ExtraFlags,
+    CodePath,
+    ConfigFiles,
+    OutputDir,
+    PortSettings0
+) ->
+    start_test_node(
+        ErlCmd,
+        [],
+        ExtraFlags,
+        CodePath,
+        ConfigFiles,
+        OutputDir,
+        PortSettings0
+    ).
+
+-spec start_test_node(
+    Erl :: [binary()],
+    Trampolines :: [file:filename_all()],
+    ExtraFlags :: [binary()],
+    CodePath :: [file:filename_all()],
+    ConfigFiles :: [file:filename_all()],
+    OutputDir :: file:filename_all(),
+    PortSettings :: port_settings()
+) -> port().
+start_test_node(
+    ErlCmd,
+    Trampolines,
+    ExtraFlags,
+    CodePath,
+    ConfigFiles,
+    OutputDir,
+    PortSettings0
+) ->
+    % we handle ErlCmd and Trampolines as one and execute the first
+    % executale in the chain
+    [Executable | ExecutableArgs] = Trampolines ++ ErlCmd,
+
+    % HomeDir is the execution directory.
+    HomeDir = set_home_dir(OutputDir),
+
+    %% merge args, enc, cd settings
+    LaunchArgs =
+        ExecutableArgs ++ ExtraFlags ++
+            build_common_args(CodePath, ConfigFiles) ++
+            proplists:get_value(args, PortSettings0, []),
+
+    Env = proplists:get_value(env, PortSettings0, []),
+    LaunchEnv = [{"HOME", filename_all_to_filename(HomeDir)} | Env],
+
+    LaunchCD = proplists:get_value(cd, PortSettings0, HomeDir),
+
+    %% prepare launch settings
+    PortSettings1 = lists:foldl(
+        fun(Key, Settings) ->
+            lists:keydelete(Key, 1, Settings)
+        end,
+        PortSettings0,
+        [args, env, cd]
+    ),
+
+    % NB. It is important that this value is large enough to fit the
+    % ct_stdout fingerprint as we rely on that to (simplify) the
+    % detection of progress markers. The fingerprint is <40 bytes, so
+    % in practice any large number here will work
+    LineLen = 1024,
+
+    % NB using stderr_to_stdout here can make it so that we don't get the
+    % exit_status once the port exits if it opened another port with use_stdio
+    % as in blocking_process_SUITE (see https://github.com/erlang/otp/issues/10411)
+    DefaultOptions = [in, binary, use_stdio, exit_status, {line, LineLen}],
+
+    LaunchSettings = [
+        {args, LaunchArgs},
+        {env, LaunchEnv},
+        {cd, LaunchCD}
+        | PortSettings1 ++ DefaultOptions
+    ],
+
+    %% start the node
+    ?LOG_DEBUG("Launching ~tp ~tp ~n with env variables ~tp ~n", [
+        Executable,
+        LaunchArgs,
+        LaunchEnv
+    ]),
+
+    erlang:open_port({spawn_executable, Executable}, LaunchSettings).
+
+-spec generate_arg_tuple(atom(), [] | term()) -> [binary()].
+generate_arg_tuple(_Prop, []) ->
+    [];
+generate_arg_tuple(Prop, ConfigFiles) ->
+    [unicode_characters_to_binary(io_lib:format("~tp", [{Prop, ConfigFiles}]))].
+
+-spec config_arg(ConfigFiles) -> [string() | binary()] when
+    ConfigFiles :: [binary() | string()].
+config_arg([]) -> [];
+config_arg(ConfigFiles) -> [~"-config" | ConfigFiles].
+
+-doc """
+Create a set up a home dir in the output directory.
+Each test execution will have a separate home dir with a
+erlang default cookie file, setting the default cookie to
+buck2-test-runner-cookie
+""".
+-spec set_home_dir(file:filename_all()) -> file:filename_all().
+set_home_dir(OutputDir) ->
+    HomeDir = filename:join(OutputDir, "HOME"),
+    ErlangCookieFile = filename:join(HomeDir, ".erlang.cookie"),
+    ok = filelib:ensure_dir(ErlangCookieFile),
+    ok = file:write_file(ErlangCookieFile, atom_to_list(cookie()), [raw, binary]),
+    ok = file:change_mode(ErlangCookieFile, 8#00400),
+
+    % In case the system is using dotslash, we leave a symlink to
+    % the real dotslash cache, otherwise erl could be re-downloaded, etc
+    try_setup_dotslash_cache(HomeDir),
+
+    HomeDir.
+
+-spec try_setup_dotslash_cache(FakeHomeDir :: file:filename_all()) -> ok.
+try_setup_dotslash_cache(FakeHomeDir) ->
+    case init:get_argument(home) of
+        {ok, [[RealHomeDir]]} ->
+            RealDotslashCacheDir = filename:basedir(user_cache, "dotslash"),
+
+            case filelib:is_file(RealDotslashCacheDir, ?raw_file_access) of
+                false ->
+                    ok;
+                true ->
+                    RealHomeDirParts = filename:split(RealHomeDir),
+                    RealDotslashCacheDirParts = filename:split(RealDotslashCacheDir),
+
+                    case
+                        length(RealDotslashCacheDirParts) >= length(RealHomeDirParts) andalso
+                            lists:split(length(RealHomeDirParts), RealDotslashCacheDirParts)
+                    of
+                        {RealHomeDirParts, GenDotslashCacheDirParts} ->
+                            FakeHomeDotslashCacheDir = filename:join([FakeHomeDir | GenDotslashCacheDirParts]),
+                            ok = filelib:ensure_path(filename:dirname(FakeHomeDotslashCacheDir)),
+                            ok = file:make_symlink(RealDotslashCacheDir, FakeHomeDotslashCacheDir),
+                            ok;
+                        _ ->
+                            ok
+                    end
+            end;
+        _ ->
+            ok
+    end.
+
+-spec cookie() -> atom().
+cookie() ->
+    'buck2-test-runner-cookie'.
+
+-spec project_root() -> file:filename().
+project_root() ->
+    {ok, CWD} = prim_file:get_cwd(),
+    Command = "buck2 root --kind=project",
+    Dir = string:trim(os:cmd(Command)),
+    ?LOG_INFO(#{command => Command, result => Dir, cwd => CWD}),
+    case filelib:is_dir(Dir, ?raw_file_access) of
+        true ->
+            Dir;
+        false ->
+            {ok, FileInfo} = prim_file:read_file_info(Dir),
+            ?LOG_ERROR(#{directory => Dir, stat => FileInfo}),
+            error({project_root_not_found, Dir})
+    end.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/epmd_manager.erl b/buck2/prelude/erlang/common_test/test_exec/src/epmd_manager.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/epmd_manager.erl
@@ -0,0 +1,271 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(epmd_manager).
+-moduledoc """
+This module interfaces with the epmd daemon. It allows one to start/stop one for
+each suite execution.
+""".
+-compile(warn_missing_spec_all).
+
+-behaviour(gen_server).
+
+%% UI methods
+-export([start_link/1, get_epmd_out_path/1, get_port/0]).
+
+%% gen_server callbacks
+-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]).
+
+-include_lib("common/include/buck_ct_records.hrl").
+
+-define(raw_file_access, prim_file).
+
+-doc """
+Find a new port and starts this epmd daemon on this new port, ensures it is up and working,
+and set up the env variable ERL_EPMD_PORT to the port this daemon is working.
+""".
+-spec start_link(#test_env{}) -> gen_server:start_ret().
+start_link(#test_env{} = TestEnv) ->
+    gen_server:start_link({local, ?MODULE}, ?MODULE, TestEnv, []).
+
+-spec get_port() -> inet:port_number().
+get_port() ->
+    gen_server:call(?MODULE, get_port).
+
+%% ---------------- gen_server callbacks---------------
+
+-type local_epmd_state() ::
+    #{
+        global_epmd := false,
+        epmd_port := inet:port_number(),
+        epmd_erlang_port := erlang:port(),
+        log_handle := io:device()
+    }.
+-type global_epmd_state() :: #{
+    global_epmd := true,
+    epmd_port := inet:port_number()
+}.
+
+-type state() :: local_epmd_state() | global_epmd_state().
+
+-spec init(#test_env{}) -> {ok, state()} | {stop, Reason} when
+    Reason :: {epmd_start_failed, Error :: term()}.
+init(#test_env{output_dir = OutputDir}) ->
+    process_flag(trap_exit, true),
+
+    case application:get_env(test_exec, global_epmd_port) of
+        undefined ->
+            EpmdOutPath = get_epmd_out_path(OutputDir),
+            case start_epmd(EpmdOutPath) of
+                {ok, Port, PortEpmd, LogHandle} ->
+                    {ok, #{
+                        epmd_port => Port,
+                        epmd_erlang_port => PortEpmd,
+                        log_handle => LogHandle,
+                        global_epmd => false
+                    }};
+                Error ->
+                    {stop, {epmd_start_failed, Error}}
+            end;
+        {ok, Port} ->
+            {ok, #{epmd_port => Port, global_epmd => true}}
+    end.
+
+-spec handle_cast(Request, State) -> {noreply, State} when
+    Request :: term(),
+    State :: state().
+handle_cast(_Request, State) -> {noreply, State}.
+
+-spec handle_call(get_port, From, State) -> {reply, Port, State} when
+    From :: gen_server:from(),
+    State :: state(),
+    Port :: inet:port_number().
+handle_call(get_port, _From, State = #{epmd_port := Port}) -> {reply, Port, State}.
+
+-spec handle_info
+    ({PortEpmd, {exit_status, ExitStatus}}, State) -> {stop, {epmd_crashed, ExitStatus}, State} when
+        PortEpmd :: erlang:port(),
+        ExitStatus :: integer(),
+        State :: local_epmd_state();
+    ({PortEpmd, closed}, State) -> {stop, epmd_port_closed, State} when
+        PortEpmd :: erlang:port(),
+        State :: local_epmd_state();
+    ({'EXIT', PortEpmd, Reason}, State) -> {stop, {epmd_exit, Reason}, State} | {noreply, State} when
+        PortEpmd :: erlang:port(),
+        Reason :: term(),
+        State :: local_epmd_state();
+    ({PortEpmd, {data, TaggedData}}, State) -> {noreply, State} when
+        PortEpmd :: erlang:port(),
+        TaggedData :: {noeol, Data} | {eol, Data},
+        Data :: string(),
+        State :: local_epmd_state();
+    (none(), State) -> {noreply, State} when
+        State :: state().
+
+handle_info({PortEpmd, {exit_status, ExitStatus}}, State) ->
+    #{epmd_erlang_port := PortEpmd} = State,
+    {stop, {epmd_crashed, ExitStatus}, State};
+handle_info({PortEpmd, closed}, State) ->
+    #{epmd_erlang_port := PortEpmd} = State,
+    {stop, epmd_port_closed, State};
+handle_info({'EXIT', PortEpmd, Reason}, #{epmd_erlang_port := PortEpmd} = State) ->
+    {stop, {epmd_exit, Reason}, State};
+handle_info({PortEpmd, {data, TaggedData}}, State) ->
+    #{epmd_erlang_port := PortEpmd, log_handle := LogHandle} = State,
+    UntaggedData =
+        case TaggedData of
+            {noeol, Data} -> Data;
+            {eol, Data} -> Data
+        end,
+    log_input_data(UntaggedData, LogHandle),
+    {noreply, State};
+handle_info(_Info, State) ->
+    {noreply, State}.
+
+-spec terminate(Reason, State) -> ok when
+    Reason :: normal | shutdown | {shutdown, term()} | term(),
+    State :: state().
+terminate(_Reason, #{epmd_erlang_port := EpmdPort}) ->
+    test_exec:kill_process(EpmdPort);
+terminate(_Reason, _State) ->
+    ok.
+
+%% --------------  Utilities methods ------------------
+
+-doc """
+Find a new port and starts this epmd daemon on this new port, then ensures it is up and working.
+ We may have to retry in case the port becomes busy between the time
+it is discovered and the time the epmd is ran.
+""".
+-spec start_epmd(EpmdOutPath) ->
+    {ok, inet:port_number(), erlang:port(), io:device()} | {error, {epmd_starting_failed, Error}}
+when
+    EpmdOutPath :: file:filename_all(),
+    Error :: term().
+start_epmd(EpmdOutPath) ->
+    start_epmd(EpmdOutPath, 3, no_error).
+
+-spec start_epmd(EpmdOutPath, Attempts, Error) ->
+    {ok, inet:port_number(), erlang:port(), io:device()} | {error, {epmd_starting_failed, Error}}
+when
+    EpmdOutPath :: file:filename_all(),
+    Attempts :: integer(),
+    Error :: term().
+start_epmd(EpmdOutPath, Attempts, _Error) when Attempts > 0 ->
+    case find_free_port() of
+        {ok, Port} ->
+            case start_epmd_instance(Port, EpmdOutPath) of
+                {ok, PortEpmd, LogHandle} -> {ok, Port, PortEpmd, LogHandle};
+                {failed, Reason} -> start_epmd(EpmdOutPath, Attempts - 1, Reason)
+            end;
+        Error ->
+            start_epmd(EpmdOutPath, Attempts - 1, Error)
+    end;
+start_epmd(_LogDir, 0, Error) ->
+    {error, {epmd_starting_failed, Error}}.
+
+-doc """
+Finds a free TCP port.
+This methods relies on a special behavior of gen_tcp:listen/0,
+See https://www.erlang.org/doc/man/gen_tcp.html#listen-2
+""".
+-spec find_free_port() -> {ok, inet:port_number()} | {error, Reason} when
+    Reason :: system_limit | inet:posix().
+find_free_port() ->
+    case gen_tcp:listen(0, [inet]) of
+        {ok, ListenSocket} ->
+            Port = {ok, _} = inet:port(ListenSocket),
+            gen_tcp:close(ListenSocket),
+            Port;
+        {error, Reason} ->
+            {error, Reason}
+    end.
+
+-doc """
+Starts the epmd daemon on the given port,
+and writes stdout, stderr to files in the LogDir.
+""".
+-spec start_epmd_instance(inet:port_number(), file:filename_all()) -> {ok, port(), io:device()} | {failed, term()}.
+start_epmd_instance(Port, EpmdOutPath) ->
+    %% Note on the -d flag from `man 1 epmd`:
+    %% Enables debug output. The more -d flags specified, the more
+    %% debug output you will get (to a certain limit). This option is
+    %% most useful when the epmd daemon is not started as a daemon.
+    LogHandle = get_log_handle(EpmdOutPath),
+    ProcessPort = erlang:open_port(
+        {
+            spawn,
+            string:join(
+                [
+                    "epmd",
+                    "-d",
+                    "-d",
+                    "-port",
+                    integer_to_list(Port)
+                ],
+                " "
+            )
+        },
+        [stderr_to_stdout, exit_status, use_stdio, {line, 4096}]
+    ),
+    case listen_loop(ProcessPort, LogHandle, []) of
+        ok ->
+            {ok, ProcessPort, LogHandle};
+        {failed, _} = Error when is_pid(LogHandle) ->
+            file:close(LogHandle),
+            Error;
+        {failed, _} = Error ->
+            Error
+    end.
+
+-spec listen_loop(ProcessPort, LogHandle, Acc) -> {failed, term()} | ok when
+    ProcessPort :: erlang:port(),
+    LogHandle :: io:device(),
+    Acc :: [string()].
+listen_loop(ProcessPort, LogHandle, Acc) ->
+    receive
+        {ProcessPort, {exit_status, Exit}} ->
+            {failed, {epmd_exit, Exit}};
+        {ProcessPort, {data, {noeol, Data}}} ->
+            log_input_data(Data, LogHandle),
+            listen_loop(ProcessPort, LogHandle, [Data | Acc]);
+        {ProcessPort, {data, {eol, Data}}} ->
+            log_input_data(Data, LogHandle),
+
+            FullLine = string:join([Data | lists:reverse(Acc)], ""),
+            case string:find(FullLine, "entering the main select() loop") of
+                nomatch ->
+                    listen_loop(ProcessPort, LogHandle, []);
+                _ ->
+                    ok
+            end
+    after 1000 ->
+        test_exec:kill_process(ProcessPort),
+        {failed, timeout}
+    end.
+
+-spec get_log_handle(file:name_all()) -> io:device().
+get_log_handle(EpmdOutPath) ->
+    case filelib:is_file(EpmdOutPath, ?raw_file_access) of
+        true -> ok = file:delete(EpmdOutPath, [raw]);
+        false -> ok
+    end,
+    % Can't open in raw mode, since we want this handle to be consumable elsewhere
+    {ok, LogHandle} = file:open(EpmdOutPath, [write]),
+    LogHandle.
+
+-spec log_input_data(Data, LogHandle) -> ok when
+    Data :: unicode:chardata(),
+    LogHandle :: io:device().
+log_input_data(Data, LogHandle) ->
+    io:format(LogHandle, "~ts", [Data]).
+
+-spec get_epmd_out_path(OutDir) -> file:filename_all() when
+    OutDir :: file:filename_all().
+get_epmd_out_path(OutputDir) ->
+    filename:join(OutputDir, "epmd_out.log").
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/test_exec.app.src b/buck2/prelude/erlang/common_test/test_exec/src/test_exec.app.src
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/test_exec.app.src
@@ -0,0 +1,16 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+{application, test_exec, [
+    {vsn, "1.0.0"},
+    {env, [
+        {test_env, "override_me"},
+        {test_runner, "override_me"},
+        {ct_daemon_hooks, []}
+    ]}
+]}.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/test_exec.erl b/buck2/prelude/erlang/common_test/test_exec/src/test_exec.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/test_exec.erl
@@ -0,0 +1,50 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(test_exec).
+-moduledoc """
+The test_exec application deals with running
+the test as part of a separate sub-process along
+with the epmd daemon.
+""".
+-compile(warn_missing_spec_all).
+
+-behavior(application).
+
+-export([start/2, stop/1, kill_process/1]).
+
+-include_lib("kernel/include/logger.hrl").
+-include_lib("common/include/buck_ct_records.hrl").
+
+-spec start(Type, Args) -> {'ok', pid()} | {'error', supervisor:startlink_err()} when
+    Type :: application:start_type(),
+    Args :: term().
+start(_Type, _Args) ->
+    case application:get_env(test_exec, test_env) of
+        {ok, #test_env{} = TestEnv} ->
+            test_exec_sup:start_link(TestEnv);
+        _ ->
+            %% hack to make startup not fail if no config is set
+            {ok, spawn_link(timer, sleep, [infinity])}
+    end.
+
+-spec stop(State) -> ok when
+    State :: term().
+stop(_State) -> ok.
+
+-spec kill_process(port()) -> ok.
+kill_process(Port) ->
+    case erlang:port_info(Port, os_pid) of
+        undefined ->
+            ok;
+        {os_pid, OsPid} ->
+            X = os:cmd(io_lib:format("kill -9 -~tp", [OsPid])),
+            ?LOG_DEBUG("Sending kill signal to process group from ~p resulted in ~p", [OsPid, X]),
+            spawn(fun() -> port_close(Port) end),
+            ok
+    end.
diff --git a/buck2/prelude/erlang/common_test/test_exec/src/test_exec_sup.erl b/buck2/prelude/erlang/common_test/test_exec/src/test_exec_sup.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/src/test_exec_sup.erl
@@ -0,0 +1,58 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(test_exec_sup).
+-moduledoc """
+Supervisor that starts two genserver sequentially: the epmd_manager, that will
+starts the epmd daemon, and the ct_runner, that will launch the test.
+If one of them stops it entails termination of the whole tree.
+""".
+-compile([warn_missing_spec_all]).
+
+-behavior(supervisor).
+
+-export([init/1, start_link/1]).
+
+-include_lib("common/include/buck_ct_records.hrl").
+
+-spec start_link(#test_env{}) -> {'ok', pid()} | {'error', supervisor:startlink_err()}.
+start_link(#test_env{} = TestEnv) ->
+    case supervisor:start_link({local, ?MODULE}, ?MODULE, [TestEnv]) of
+        Ok = {ok, _} -> Ok;
+        Error = {error, _} -> Error
+    end.
+
+-spec init(Args :: term()) ->
+    {ok, {SupFlags :: supervisor:sup_flags(), [ChildSpec :: supervisor:child_spec()]}} | ignore.
+init([#test_env{} = TestEnv]) ->
+    {ok,
+        {
+            #{
+                % strategy doesn't matter as
+                % none of the children are to be restarted
+                strategy => one_for_all,
+                intensity => 0,
+                period => 1
+            },
+            [
+                #{
+                    id => epmd_manager,
+                    start => {epmd_manager, start_link, [TestEnv]},
+                    restart => temporary,
+                    shutdown => 1000,
+                    type => worker
+                },
+                #{
+                    id => ct_runner,
+                    start => {ct_runner, start_link, [TestEnv]},
+                    restart => temporary,
+                    shutdown => 1000,
+                    type => worker
+                }
+            ]
+        }}.
diff --git a/buck2/prelude/erlang/common_test/test_exec/test/ct_daemon_capture_SUITE.erl b/buck2/prelude/erlang/common_test/test_exec/test/ct_daemon_capture_SUITE.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/test/ct_daemon_capture_SUITE.erl
@@ -0,0 +1,113 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+%%% % @format
+-module(ct_daemon_capture_SUITE).
+-typing([eqwalizer]).
+
+-export([all/0, init_per_testcase/2, end_per_testcase/2]).
+-export([
+    test_start_stop/1,
+    test_capture_via_call/1,
+    test_capture_via_message/1,
+    test_put_chars_without_capture/1,
+    test_put_chars_with_capture/1,
+    test_io_request_forwarding/1,
+    test_unknown_request/1
+]).
+
+% elp:ignore WA003 (better_assertions) - Open Source
+-include_lib("stdlib/include/assert.hrl").
+
+all() ->
+    [
+        test_start_stop,
+        test_capture_via_call,
+        test_capture_via_message,
+        test_put_chars_without_capture,
+        test_put_chars_with_capture,
+        test_io_request_forwarding,
+        test_unknown_request
+    ].
+
+init_per_testcase(_TestCase, Config) ->
+    {ok, CaptureGL} = ct_daemon_capture:start_link(erlang:group_leader()),
+    [{capture_gl, CaptureGL} | Config].
+
+end_per_testcase(_TestCase, Config) ->
+    ct_daemon_capture:stop(proplists:get_value(capture_gl, Config)),
+    ok.
+
+%% Test that start_link and stop work correctly
+test_start_stop(Config) ->
+    CaptureGL = proplists:get_value(capture_gl, Config),
+    ?assert(is_pid(CaptureGL)),
+    ?assert(is_process_alive(CaptureGL)).
+
+%% Test capture enable/disable via gen_server:call (testshell's approach)
+test_capture_via_call(Config) ->
+    CaptureGL = proplists:get_value(capture_gl, Config),
+    ?assertEqual(ok, gen_server:call(CaptureGL, {capture, self()})),
+    ?assertEqual(ok, gen_server:call(CaptureGL, {capture, false})).
+
+%% Test capture enable/disable via message (OTP's approach)
+test_capture_via_message(Config) ->
+    CaptureGL = proplists:get_value(capture_gl, Config),
+    CaptureGL ! {capture, self()},
+    %% Synchronize by making a call to ensure the message was processed
+    _ = sys:get_state(CaptureGL),
+    CaptureGL ! {capture, false},
+    _ = sys:get_state(CaptureGL),
+    ?assert(is_process_alive(CaptureGL)).
+
+%% Test put_chars without capture enabled
+test_put_chars_without_capture(Config) ->
+    CaptureGL = proplists:get_value(capture_gl, Config),
+    Ref = make_ref(),
+    CaptureGL ! {io_request, self(), Ref, {put_chars, unicode, ~"test output"}},
+    receive
+        {io_reply, Ref, ok} -> ok
+    after 1000 -> ?assert(false)
+    end,
+    %% No captured message should be received
+    receive
+        {captured, _} -> ?assert(false)
+    after 100 -> ok
+    end.
+
+%% Test put_chars with capture enabled
+test_put_chars_with_capture(Config) ->
+    CaptureGL = proplists:get_value(capture_gl, Config),
+    ok = gen_server:call(CaptureGL, {capture, self()}),
+    Ref = make_ref(),
+    CaptureGL ! {io_request, self(), Ref, {put_chars, unicode, ~"captured output"}},
+    %% Should receive both io_reply and captured message
+    receive
+        {io_reply, Ref, ok} -> ok
+    after 1000 -> ?assert(false)
+    end,
+    receive
+        {captured, "captured output"} -> ok;
+        {captured, Other} -> ?assertEqual("captured output", Other)
+    after 1000 ->
+        ?assert(false)
+    end.
+
+%% Test that IO requests are forwarded to original group leader
+test_io_request_forwarding(Config) ->
+    CaptureGL = proplists:get_value(capture_gl, Config),
+    OldGL = erlang:group_leader(),
+    true = erlang:group_leader(CaptureGL, self()),
+    try
+        io:format("test~n"),
+        ok
+    after
+        erlang:group_leader(OldGL, self())
+    end.
+
+%% Test unknown request returns error
+test_unknown_request(Config) ->
+    CaptureGL = proplists:get_value(capture_gl, Config),
+    ?assertEqual({error, unknown_request}, gen_server:call(CaptureGL, {unknown, request})).
diff --git a/buck2/prelude/erlang/common_test/test_exec/test/ct_executor_SUITE.erl b/buck2/prelude/erlang/common_test/test_exec/test/ct_executor_SUITE.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/common_test/test_exec/test/ct_executor_SUITE.erl
@@ -0,0 +1,78 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+%%% % @format
+-module(ct_executor_SUITE).
+-typing([eqwalizer]).
+
+-export([all/0]).
+
+-export([
+    test_preload_app_file_atoms/1,
+    test_split_args/1
+]).
+
+% elp:ignore WA003 (better_assertions) - Open Source
+-include_lib("stdlib/include/assert.hrl").
+
+all() ->
+    [
+        test_split_args,
+        test_preload_app_file_atoms
+    ].
+
+test_split_args(_Config) ->
+    ?assertEqual(
+        {
+            [
+                {output_dir, ""},
+                {providers, [something]},
+                {suite, a_suite},
+                {common_app_env, #{<<"raw_target">> => <<"target">>}}
+            ],
+            [{dir, ""}, {suite, a_suite}, {group, a_group}]
+        },
+        ct_executor:split_args([
+            {output_dir, ""},
+            {providers, [something]},
+            {suite, a_suite},
+            {common_app_env, #{<<"raw_target">> => <<"target">>}},
+            ct_args,
+            {dir, ""},
+            {suite, a_suite},
+            {group, a_group}
+        ])
+    ),
+    ?assertEqual(
+        {[{output_dir, ""}, {providers, [something]}, {suite, a_suite}], []},
+        ct_executor:split_args([{output_dir, ""}, {providers, [something]}, {suite, a_suite}, ct_args])
+    ),
+    ?assertEqual(
+        {[], [{dir, ""}, {suite, a_suite}, {group, a_group}]},
+        ct_executor:split_args([ct_args, {dir, ""}, {suite, a_suite}, {group, a_group}])
+    ),
+    ?assertEqual({[], []}, ct_executor:split_args([ct_args])).
+
+test_preload_app_file_atoms(Config) ->
+    PrivDir = proplists:get_value(priv_dir, Config),
+    Suffix = integer_to_binary(erlang:unique_integer([positive])),
+    AppName = <<"ct_executor_preload_app_", Suffix/binary>>,
+    EnvName = <<"ct_executor_preload_env_", Suffix/binary>>,
+    EnvValue = <<"ct_executor_preload_value_", Suffix/binary>>,
+    AppFile = filename:join(PrivDir, binary_to_list(<<AppName/binary, ".app">>)),
+    ok = file:write_file(AppFile, [
+        "{application,",
+        AppName,
+        ",[{env,[{",
+        EnvName,
+        ",",
+        EnvValue,
+        "}]}]}.\n"
+    ]),
+    ?assertError(badarg, binary_to_existing_atom(EnvValue, utf8)),
+
+    ok = ct_executor:preload_app_file_atoms(AppFile),
+
+    ?assertEqual(EnvValue, atom_to_binary(binary_to_existing_atom(EnvValue, utf8), utf8)).
diff --git a/buck2/prelude/erlang/elp.bxl b/buck2/prelude/erlang/elp.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/elp.bxl
@@ -0,0 +1,309 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+BuildResults = record(
+    result = field(dict[Label, bxl.BuildResult]),
+    artifacts = field(dict[Label, list[bxl.EnsuredArtifact]]),
+)
+
+# ------------------ IMPL ------------------
+
+def _add_includes_to_map(includes_map, includes):
+    for inc in includes:
+        includes_map[inc["value"]] = inc["type"]
+    return includes_map
+
+def _clean_up_includes(includes):
+    # - Remove duplicates
+    # - extract paths and build results
+    include_paths = [p["value"] for p in includes if p["type"] == "path"]
+    include_paths = [_as_path(p) for p in _uniq(include_paths)]
+    builds = [b for b in includes if b["type"] == "build"]
+
+    return include_paths + builds
+
+def _get_includes(ctx, includes_target, build_results):
+    includes = []
+    for inc in includes_target.value():
+        includes += _get_absolute_path(ctx, inc, build_results)
+    return _clean_up_includes(includes)
+
+def _get_absolute_path(ctx, src, build_results, allow_multiple = True) -> list[dict[str, str | bxl.EnsuredArtifact]]:
+    """
+    Get the absolute path of the thing passed in, which is either an artifact or a target label.
+    """
+    if isinstance(src, ConfiguredProvidersLabel) and build_results and src in build_results.result:
+        target = src.configured_target()
+        build_result = build_results.result[src]
+        failed_targets = []
+        for _ in build_result.failures():
+            failed_targets.append(str(target))
+        if failed_targets != []:
+            return [_as_error("target {} failed to build due to failures on the following targets [{}]".format(target, ", ".join(failed_targets)))]
+        paths = build_results.artifacts[src]
+        if not allow_multiple and len(paths) != 1:
+            return [_as_error("target {} has multiple outputs: {}".format(target, ", ".join([str(p) for p in paths])))]
+        return [_as_build(path.abs_path()) for path in paths]
+    elif isinstance(src, ConfiguredProvidersLabel):
+        return [_as_target(str(src.raw_target()))]
+    else:
+        return [_as_path(get_path_without_materialization(src, ctx, abs = True))]
+
+def _generate_sources(ctx, src, build_results) -> list:
+    """
+    Get the full set of sources used to generate a given target.
+    """
+    if isinstance(src, ConfiguredProvidersLabel) and build_results and src in build_results.result:
+        target = src.configured_target()
+        deps = ctx.cquery().deps(target)
+        inputs = ctx.cquery().inputs(deps)
+        return [f.cell + "//" + f.path for f in inputs]
+
+    else:
+        return []
+
+def _strip_includes_only(inc):
+    str_inc = str(inc)
+    suffix = "_includes_only"
+    if str_inc.endswith(suffix):
+        str_inc = str_inc[: -len(suffix)]
+    return str_inc
+
+def _build_alias_map(ctx, targets):
+    """Build a map from alias target labels to their fully-resolved actual targets.
+
+    Follows alias chains: if alias A points to alias B which points to
+    target C, both A and B map to C.
+    """
+    alias_targets = ctx.cquery().kind("^alias$", targets)
+    raw_map = {}
+    for alias_tgt in alias_targets:
+        actual_attr = alias_tgt.attrs_lazy().get("actual")
+        if actual_attr:
+            actual_value = actual_attr.value()
+            if isinstance(actual_value, ConfiguredProvidersLabel):
+                raw_map[alias_tgt.label.raw_target()] = actual_value.raw_target()
+
+    # Collapse chains: follow each entry until it lands on a non-alias.
+    # Depth is capped at 10 to guard against alias cycles.
+    alias_map = {}
+    for src, dst in raw_map.items():
+        visited = [src]
+        cur = dst
+        for _ in range(10):
+            if cur not in raw_map:
+                break
+            visited.append(cur)
+            cur = raw_map[cur]
+        if cur in raw_map:
+            warning("alias chain starting at {} exceeds 10 hops — possible cycle, truncating".format(src))
+        for v in visited:
+            alias_map[v] = cur
+    return alias_map
+
+def _resolve_target_label(label, alias_map):
+    """If label is an alias, return the fully-resolved actual target label."""
+    return alias_map.get(label, label)
+
+def _elp_config(ctx):
+    included_targets = ctx.cli_args.included_targets
+
+    # Load the prelude targets first, so if we are working in the prelude they will be overwritten
+    # by included or deps targets, and processed in ELP
+
+    included_targets = ctx.unconfigured_targets(included_targets)
+
+    # Keep alias targets alongside erlang targets for configuration.
+    # Aliases have kind "alias" (not "erlang_app"), so a kind-only filter
+    # would drop them.  Configuring them lets deps() follow alias→actual
+    # edges, placing actual targets into the dep graph where the single
+    # alias map built below can resolve them — including multi-hop chains.
+    included_candidates = ctx.uquery().kind("^(erlang_app|erlang_test|alias)$", included_targets)
+    included_configured = ctx.configured_targets(included_candidates, None)
+    all_targets = ctx.cquery().deps(included_configured)
+
+    # Build a single alias map from the full configured dep graph.
+    # deps() already follows alias→actual edges transitively, so alias
+    # actuals are always in all_targets.  The alias map is still needed to
+    # translate alias labels (e.g. //third-party/erlang:foo in a deps
+    # attribute) to actual target labels that match result dict keys.
+    alias_map = _build_alias_map(ctx, all_targets)
+
+    # Determine which targets are directly included (apps), resolving any
+    # aliases in the user-specified set through the alias map.
+    included_labels = {}
+    for tgt in included_configured:
+        raw = tgt.label.raw_target()
+        included_labels[_resolve_target_label(raw, alias_map)] = True
+
+    all = {}
+    for tgt in ctx.cquery().kind("^(erlang_app|erlang_test)$", all_targets):
+        raw = tgt.label.raw_target()
+        if raw in included_labels:
+            all[raw] = ("app", tgt.attrs_lazy())
+    for tgt in ctx.cquery().kind("^erlang_app$", all_targets):
+        raw = tgt.label.raw_target()
+        if raw not in all:
+            all[raw] = ("dep", tgt.attrs_lazy())
+
+    build_results = None
+    if ctx.cli_args.build_generated_code:
+        build_results = prebuild(ctx, all)
+
+    result = {}
+    for label_name, (typ, attrs) in all.items():
+        includes_map = {}
+        includes = attrs.get("includes")
+        if not includes:
+            includes = []
+        else:
+            includes = _get_includes(ctx, includes, build_results)
+        includes_map = _add_includes_to_map(includes_map, includes)
+
+        extra_includes = attrs.get("extra_includes")
+        if not extra_includes:
+            extra_includes_list = []
+        else:
+            extra_includes_list = [_strip_includes_only(_resolve_target_label(tgt.raw_target(), alias_map)) for tgt in extra_includes.value()]
+
+        deps_list = []
+        apps_list = []
+        included_apps_list = []
+        deps = attrs.get("deps")
+        if deps:
+            deps_list = [_resolve_target_label(tgt.raw_target(), alias_map) for tgt in deps.value()]
+
+        test_binary_lib = attrs.get("_test_binary_lib")
+        if test_binary_lib:
+            deps_list.append(_resolve_target_label(test_binary_lib.value().raw_target(), alias_map))
+
+        apps = attrs.get("applications")
+        if apps:
+            apps_list = [_resolve_target_label(tgt.raw_target(), alias_map) for tgt in apps.value()]
+
+        included_apps = attrs.get("included_applications")
+        if included_apps:
+            included_apps_list = [_resolve_target_label(tgt.raw_target(), alias_map) for tgt in included_apps.value()]
+
+        # These end up verbatim in the generated `.app` file, so unlike the
+        # attributes above they hold application names, not target labels.
+        extra_properties_map = {}
+        extra_properties = attrs.get("extra_properties")
+        if extra_properties:
+            # Absent on target types that do not declare the attribute at all,
+            # and `None` on those that declare it and leave it unset.
+            extra_properties_map = extra_properties.value() or {}
+
+        is_generated = "generated" in attrs.get("labels").value()
+        gen_srcs = []
+        srcs_attr = attrs.get("srcs")
+        srcs = []
+        if srcs_attr:
+            for src in srcs_attr.value():
+                srcs += _get_absolute_path(ctx, src, build_results)
+                if is_generated:
+                    gen_srcs += _generate_sources(ctx, src, build_results)
+
+        suite = attrs.get("suite")
+        if not suite:
+            suite = None
+        elif suite.value() == None:
+            suite = None
+        else:
+            [suite_info] = _get_absolute_path(ctx, suite.value(), build_results, allow_multiple = False)
+            if suite_info["type"] == "path" or suite_info["type"] == "build":
+                suite = suite_info["value"]
+            else:
+                suite = None
+
+        includes = [t for t in includes_map.keys() if includes_map[t] == "path" or includes_map[t] == "build"]
+        srcs = _construct_output(srcs)
+        gen_srcs = _uniq(gen_srcs)
+        result[label_name] = dict(
+            name = attrs.get("name"),
+            app_name = attrs.get("app_name"),
+            suite = suite,
+            srcs = srcs,
+            gen_srcs = gen_srcs,
+            includes = includes,
+            labels = attrs.get("labels"),
+            deps = deps_list,
+            apps = apps_list,
+            included_apps = included_apps_list,
+            extra_includes = extra_includes_list,
+            extra_properties = extra_properties_map,
+            origin = typ,
+        )
+
+    ctx.output.print_json(result)
+
+def prebuild(ctx, all):
+    labels = []
+    for _label_name, (_typ, attrs) in all.items():
+        target_labels = attrs.get("labels")
+        if target_labels:
+            if "elp_skip_generation" in target_labels.value():
+                continue
+
+        includes = attrs.get("includes")
+        if includes:
+            for includes in includes.value():
+                if isinstance(includes, ConfiguredProvidersLabel):
+                    labels.append(includes)
+        srcs = attrs.get("srcs")
+        if srcs:
+            for src in srcs.value():
+                if isinstance(src, ConfiguredProvidersLabel):
+                    labels.append(src)
+        suite = attrs.get("suite")
+        if suite:
+            suite = suite.value()
+            if isinstance(suite, ConfiguredProvidersLabel):
+                labels.append(suite)
+
+    build_results = ctx.build(labels)
+    artifacts = ctx.output.ensure_multiple(build_results)
+    return BuildResults(result = build_results, artifacts = artifacts)
+
+def _construct_output(items: list[dict[str, str | bxl.EnsuredArtifact]]) -> list[str | bxl.EnsuredArtifact]:
+    # we completely ignore targets, since we don't have support for generated files in ELP
+    paths = _uniq([p.get("value") for p in items if p.get("type") in ["path", "build"]])
+    return paths
+
+def _uniq(xs):
+    return list(set(xs))
+
+def _as_path(src):
+    return {"type": "path", "value": src}
+
+def _as_target(src):
+    return {"type": "target", "value": src}
+
+def _as_build(artifact):
+    return {"type": "build", "value": artifact}
+
+def _as_error(error):
+    warning("ERROR: {}".format(error))
+    return {"type": "error", "value": error}
+
+# ------------------ INTERFACE ------------------
+
+elp_config = bxl_main(
+    impl = _elp_config,
+    cli_args = {
+        "build_generated_code": cli_args.option(cli_args.bool(), default = False, doc = "Enable builds for generated sources"),
+        "deps_targets": cli_args.option(
+            cli_args.list(cli_args.string()), doc = "Target to include deps from, if specified. See corresponding field in .elp.toml"
+        ),
+        "included_targets": cli_args.list(cli_args.string(), doc = "Targets to include in the query. See corresponding field in .elp.toml"),
+    },
+)
+
+# Run with `buck2 bxl prelude//erlang/elp.bxl:elp_config`
+# e.g.
+# buck2 bxl prelude//erlang/elp.bxl:elp_config -- --included_targets cell//...
diff --git a/buck2/prelude/erlang/erlang.bzl b/buck2/prelude/erlang/erlang.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang.bzl
@@ -0,0 +1,111 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":erlang_application.bzl", "erlang_application_impl")
+load(":erlang_application_includes.bzl", "erlang_application_includes_impl")
+load(":erlang_escript.bzl", "erlang_escript_impl")
+load(":erlang_otp_application.bzl", "normalize_application")
+load(":erlang_release.bzl", "erlang_release_impl")
+load(":erlang_tests.bzl", "erlang_test_impl", "erlang_tests_macro")
+load(":erlang_toolchain.bzl", "erlang_otp_binaries_impl")
+
+# all attributes are now defined in prelude//decls:erlang_rules.bzl
+
+# target rules
+
+implemented_rules = {
+    "erlang_app": erlang_application_impl,
+    "erlang_app_includes": erlang_application_includes_impl,
+    "erlang_escript": erlang_escript_impl,
+    "erlang_otp_binaries": erlang_otp_binaries_impl,
+    "erlang_release": erlang_release_impl,
+    "erlang_test": erlang_test_impl,
+}
+
+# Macros
+
+# Wrapper to generate the erlang_app and erlang_app_include target from a single
+# specification. It also redirects the target from the regular application target
+# to the include-only target for extra_include deps
+def erlang_application(
+    erlang_app_rule,
+    erlang_app_includes_rule,
+    name,
+    app_name = None,
+    applications = [],
+    included_applications = [],
+    extra_includes = [],
+    labels = [],
+    includes = [],
+    **kwargs,
+):
+    normalized_applications = select_map(applications, lambda apps: map(normalize_application, apps))
+    normalized_included_applications = select_map(included_applications, lambda apps: map(normalize_application, apps))
+
+    if not includes:
+        return erlang_app_rule(
+            name = name,
+            app_name = app_name,
+            applications = normalized_applications,
+            included_applications = normalized_included_applications,
+            extra_includes = select_map(extra_includes, lambda deps: map(_extra_include_name, deps)),
+            labels = labels,
+            **kwargs,
+        )
+    else:
+        return [
+            erlang_app_includes_rule(
+                name = _extra_include_name(name),
+                app_name = name if app_name == None else app_name,
+                includes = includes,
+                visibility = kwargs.get("visibility", None),
+                labels = ["generated", "app_includes"],
+            ),
+            erlang_app_rule(
+                name = name,
+                app_name = app_name,
+                applications = normalized_applications,
+                included_applications = normalized_included_applications,
+                extra_includes = [_extra_include_name(dep) for dep in extra_includes],
+                includes = includes,
+                _includes_target = ":" + _extra_include_name(name),
+                labels = labels,
+                **kwargs,
+            ),
+        ]
+
+# convenience macro to specify the includes-only target based on the base-application
+# target name
+def _extra_include_name(name: str) -> str:
+    return "{}_includes_only".format(name)
+
+def erlang_tests(
+    erlang_app_rule,
+    erlang_test_rule,
+    suites: list[str] = [],
+    deps: list[str] = [],
+    resources: list[str] = [],
+    srcs: list[str] = [],
+    config_files: list[str] = [],
+    common_app_env: dict[str, str] = {},
+    **common_attributes,
+):
+    """
+    Generate multiple erlang_test targets based on the `suites` field.
+    """
+    erlang_tests_macro(
+        erlang_app_rule = erlang_app_rule,
+        erlang_test_rule = erlang_test_rule,
+        suites = suites,
+        deps = deps,
+        resources = resources,
+        srcs = srcs,
+        config_files = config_files,
+        common_app_env = common_app_env,
+        **common_attributes,
+    )
diff --git a/buck2/prelude/erlang/erlang_application.bzl b/buck2/prelude/erlang/erlang_application.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_application.bzl
@@ -0,0 +1,444 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    ":erlang_build.bzl",
+    "BuildEnvironment",  # @unused Used as type
+    "erlang_build",
+)
+load(
+    ":erlang_dependencies.bzl",
+    "erlang_deps_rule",
+)
+load(
+    ":erlang_info.bzl",
+    "CodePathEntry",
+    "CodePathTSet",
+    "ErlangAppIncludeInfo",
+    "ErlangAppInfo",
+    "ErlangAppOrTestInfo",
+    "ErlangDependencyInfo",
+    "code_path_args",
+)
+load(":erlang_shell.bzl", "erlang_shell")
+load(
+    ":erlang_toolchain.bzl",
+    "Toolchain",  # @unused Used as type
+    "get_toolchain",
+)
+load(
+    ":erlang_utils.bzl",
+    "app_name",
+)
+
+StartDependencySet = transitive_set()
+
+StartTypeValues = ["permanent", "transient", "temporary", "load", "none"]
+
+StartType = enum(*StartTypeValues)
+
+StartSpec = record(
+    name = field(str),
+    version = field(str),
+    resolved = field(bool),
+    start_type = field(StartType),
+)
+
+BuiltApplication = record(
+    build_environment = field(BuildEnvironment),
+    app_file = field(Artifact),
+    appup_file = field(Artifact | None),
+    src_dir = field(Artifact),
+    priv_dir = field(Artifact),
+)
+
+def erlang_application_impl(ctx: AnalysisContext) -> Promise:
+    # select the correct tools from the toolchain
+    toolchain = get_toolchain(ctx)
+
+    # collect all dependencies
+    dep_info = ctx.actions.anon_target(
+        erlang_deps_rule,
+        {
+            "applications": ctx.attrs.applications,
+            "extra_includes": ctx.attrs.extra_includes,
+            "included_applications": ctx.attrs.included_applications,
+        },
+    )
+
+    name = app_name(ctx)
+
+    return dep_info.promise.map(lambda dep_info: build_application(ctx, name, toolchain, dep_info[ErlangDependencyInfo]))
+
+def build_application(ctx: AnalysisContext, name: str, toolchain: Toolchain, dep_info: ErlangDependencyInfo) -> Promise:
+    if name in dep_info.dependencies and ErlangAppInfo in dep_info.dependencies[name]:
+        fail("cannot depend on an application with the same name: %s" % (dep_info.dependencies[name].label,))
+
+    result = _build_erlang_application(ctx, name, toolchain, dep_info)
+    build_environment = result.build_environment
+
+    # link final output
+    app_folder = link_output(
+        ctx,
+        name,
+        result,
+    )
+
+    # build start dependencies in reverse order
+    start_dependencies = _build_start_dependencies(ctx)
+
+    app_info = build_app_info(
+        ctx,
+        dep_info,
+        build_environment,
+        app_folder,
+        start_dependencies,
+    )
+
+    # generate DefaultInfo and RunInfo providers
+    default_info = _build_default_info(dep_info, app_folder)
+    run_info = erlang_shell.build_run_info(
+        ctx,
+        dep_info = dep_info,
+        additional_code_path = cmd_args(app_folder, format = "{}/ebin"),
+    )
+    return run_info.map(lambda run_info: [default_info, run_info, app_info, ErlangAppOrTestInfo()])
+
+def _build_erlang_application(ctx: AnalysisContext, name: str, toolchain: Toolchain, dep_info: ErlangDependencyInfo) -> BuiltApplication:
+    include_info = None
+    if ctx.attrs._includes_target:
+        include_info = ctx.attrs._includes_target[ErlangAppIncludeInfo]
+        if include_info._original_includes != ctx.attrs.includes:
+            fail(
+                "includes of the includes_target and direct includes must be the same, got {} and {}".format(
+                    include_info._original_includes, ctx.attrs.includes
+                )
+            )
+        if include_info.name != name:
+            fail("includes_target must have the same name as the application, got {} and {}".format(include_info.name, name))
+    build_environment = erlang_build.prepare_build_environment(dep_info, include_info, ctx.attrs.peek_private_includes)
+
+    # build generated inputs
+    generated_source_artifacts = erlang_build.build_steps.generated_source_artifacts(ctx, toolchain)
+
+    # Put all sources in a src folder, both for hermeticity (erlc will try to load .hrl files next to the .erl file)
+    # and to ultimately put it in the app folder
+    src_dir = _link_src_dir(ctx, extra_srcs = generated_source_artifacts)
+
+    # collect all inputs
+    src_artifacts = [src for src in ctx.attrs.srcs if erlang_build.utils.is_erl(src)] + generated_source_artifacts
+
+    private_header_artifacts = [header for header in ctx.attrs.srcs if erlang_build.utils.is_hrl(header)]
+
+    # build output artifacts
+
+    # public includes only triggered if this won't called from erlang_application macro
+    # and includes weren't redirected to the includes_target dependency
+    if not include_info:
+        erlang_build.build_steps.generate_include_artifacts(
+            ctx,
+            toolchain,
+            build_environment,
+            name,
+            ctx.attrs.includes,
+        )
+
+    # private includes
+    erlang_build.build_steps.generate_include_artifacts(
+        ctx,
+        toolchain,
+        build_environment,
+        name,
+        private_header_artifacts,
+        is_private = True,
+    )
+
+    # doc files
+    _build_doc_artifacts(ctx, build_environment)
+
+    # beams
+    erlang_build.build_steps.generate_beam_artifacts(
+        ctx,
+        toolchain,
+        build_environment,
+        name,
+        src_artifacts,
+        src_dir,
+    )
+
+    # create <appname>.app file
+    app_file = _generate_app_file(
+        ctx,
+        toolchain,
+        name,
+        src_artifacts,
+    )
+
+    # create <appname>.appup file
+    appup_file = _generate_appup_file(ctx, toolchain, name)
+
+    # priv
+    priv_dir = _generate_priv_dir(ctx)
+
+    return BuiltApplication(
+        build_environment = build_environment,
+        app_file = app_file,
+        appup_file = appup_file,
+        src_dir = src_dir,
+        priv_dir = priv_dir,
+    )
+
+def _generate_priv_dir(ctx: AnalysisContext) -> Artifact:
+    """Generate the application's priv dir."""
+    name = app_name(ctx)
+
+    resources = ctx.attrs.resources
+    priv_symlinks = {}
+    for resource in resources:
+        for file in resource[DefaultInfo].default_outputs:
+            priv_symlinks[file.short_path] = file
+        for file in resource[DefaultInfo].other_outputs:
+            if isinstance(file, Artifact):
+                priv_symlinks[file.short_path] = file
+
+    return ctx.actions.symlinked_dir(
+        paths.join(
+            erlang_build.utils.BUILD_DIR,
+            name,
+            "priv",
+        ),
+        priv_symlinks,
+        has_content_based_path = False,
+    )
+
+def _generate_app_file(ctx: AnalysisContext, toolchain: Toolchain, name: str, srcs: list[Artifact]) -> Artifact:
+    """rule for generating the .app files
+
+    NOTE: We are using the .erl files as input to avoid dependencies on
+          beams.
+    """
+    _check_application_dependencies(ctx)
+
+    app_file_name = name + ".app"
+    output = ctx.actions.declare_output(erlang_build.utils.BUILD_DIR, app_file_name, has_content_based_path = False)
+    app_info_file = _app_info_content(ctx, name, srcs)
+
+    erlang_build.utils.run_with_env(
+        ctx,
+        toolchain,
+        cmd_args(toolchain.app_src_script, app_info_file, output.as_output()),
+        category = "app_resource",
+        identifier = name,
+    )
+
+    return output
+
+def _check_application_dependencies(ctx: AnalysisContext):
+    """there must not be duplicated applications within applications and included_applications"""
+    discovered = _check_applications_field(ctx.attrs.applications, "applications", {})
+    _check_applications_field(ctx.attrs.included_applications, "included_applications", discovered)
+
+def _check_applications_field(field: list[Dependency], tag: str, discovered: dict[str, str]) -> dict[str, str]:
+    for application in field:
+        name = application[ErlangAppInfo].name
+        if name in discovered:
+            fail(
+                "discovered {} in `{}`, but the application was already specified in `{}`. The `applications` and `included_applications` field must be unique.".format(
+                    name, tag, discovered[name]
+                )
+            )
+        else:
+            discovered[name] = tag
+    return discovered
+
+def _app_info_content(ctx: AnalysisContext, name: str, srcs: list[Artifact]) -> Artifact:
+    """build an app_info.json file that contains the meta information for building the .app file"""
+    app_info = ctx.actions.declare_output(erlang_build.utils.BUILD_DIR, "app_info.json", has_content_based_path = False)
+
+    data = {
+        "app_src_vsn": ctx.attrs.app_src_vsn,
+        "applications": [app[ErlangAppInfo].name for app in ctx.attrs.applications],
+        "included_applications": [app[ErlangAppInfo].name for app in ctx.attrs.included_applications],
+        "name": name,
+        "sources": srcs,
+    }
+    if ctx.attrs.version:
+        data["version"] = ctx.attrs.version
+    if ctx.attrs.app_src:
+        data["template"] = ctx.attrs.app_src
+        app_info = app_info.with_associated_artifacts([ctx.attrs.app_src])
+    if ctx.attrs.mod:
+        data["mod"] = ctx.attrs.mod
+    if ctx.attrs.env:
+        data["env"] = ctx.attrs.env
+    if ctx.attrs.extra_properties:
+        data["metadata"] = ctx.attrs.extra_properties
+
+    ctx.actions.write_json(app_info.as_output(), data)
+    return app_info
+
+def _generate_appup_file(ctx: AnalysisContext, toolchain: Toolchain, name: str) -> Artifact | None:
+    if not ctx.attrs.appup_src:
+        return None
+    if not ctx.attrs.version:
+        fail("appup_src requires `version` to be set on the target: %s" % (ctx.label,))
+
+    appup_file_name = name + ".appup"
+    output = ctx.actions.declare_output(erlang_build.utils.BUILD_DIR, appup_file_name, has_content_based_path = False)
+    appup_info_file = _appup_info_content(ctx, name)
+
+    erlang_build.utils.run_with_env(
+        ctx,
+        toolchain,
+        cmd_args(toolchain.appup_src_script, appup_info_file, output.as_output()),
+        category = "appup_resource",
+        identifier = name,
+    )
+
+    return output
+
+def _appup_info_content(ctx: AnalysisContext, name: str) -> Artifact:
+    appup_info = ctx.actions.declare_output(erlang_build.utils.BUILD_DIR, "appup_info.json", has_content_based_path = False)
+    data = {
+        "app_src_vsn": ctx.attrs.app_src_vsn,
+        "name": name,
+        "template": ctx.attrs.appup_src,
+        "version": ctx.attrs.version,
+    }
+    appup_info = appup_info.with_associated_artifacts([ctx.attrs.appup_src])
+    ctx.actions.write_json(appup_info.as_output(), data)
+    return appup_info
+
+def link_output(ctx: AnalysisContext, link_path: str, built: BuiltApplication) -> Artifact:
+    """Link application output folder in working dir root folder."""
+    name = app_name(ctx)
+
+    build_environment = built.build_environment
+    ebin = build_environment.beams.get(name, {}).values() + [built.app_file]
+    if built.appup_file:
+        ebin = ebin + [built.appup_file]
+    ebin = {paths.join("ebin", ebin_file.basename): ebin_file for ebin_file in ebin}
+
+    link_spec = {}
+    link_spec.update(ebin)
+    if ctx.attrs.include_src:
+        link_spec["src"] = built.src_dir
+    link_spec["priv"] = built.priv_dir
+    include_dir = erlang_build.own_or_dep(build_environment.include_dirs, build_environment.dep_include_dirs, name)
+    if include_dir != None:
+        link_spec["include"] = include_dir
+
+    return ctx.actions.symlinked_dir(link_path, link_spec, has_content_based_path = False)
+
+# mutates build_environment in place
+def _build_doc_artifacts(ctx: AnalysisContext, build_environment: BuildEnvironment):
+    """Build doc file artifacts at __build/<rel_path> so erlc can resolve file-based -moduledoc/-doc annotations."""
+    doc_files = ctx.attrs.docs
+    if not doc_files:
+        return
+
+    pkg_prefix = ctx.label.package
+    if pkg_prefix:
+        pkg_prefix = pkg_prefix + "/"
+    for doc in doc_files:
+        rel_path = doc.short_path
+        if pkg_prefix and rel_path.startswith(pkg_prefix):
+            rel_path = rel_path[len(pkg_prefix) :]
+        out = ctx.actions.declare_output(paths.join(erlang_build.utils.BUILD_DIR, rel_path), has_content_based_path = False)
+        ctx.actions.symlink_file(out.as_output(), doc)
+        build_environment.docs[rel_path] = out
+
+def _link_src_dir(ctx: AnalysisContext, *, extra_srcs: list[Artifact]) -> Artifact:
+    """Link all sources in a src folder"""
+    srcs = {src_file.basename: src_file for src_file in ctx.attrs.srcs}
+    if ctx.attrs.app_src:
+        srcs[ctx.attrs.app_src.basename] = ctx.attrs.app_src
+    if ctx.attrs.appup_src:
+        srcs[ctx.attrs.appup_src.basename] = ctx.attrs.appup_src
+
+    for extra_srcs in extra_srcs:
+        srcs[extra_srcs.basename] = extra_srcs
+
+    return ctx.actions.symlinked_dir(paths.join(erlang_build.utils.BUILD_DIR, "src"), srcs, has_content_based_path = False)
+
+def _build_start_dependencies(ctx: AnalysisContext) -> list[StartDependencySet]:
+    return build_apps_start_dependencies(
+        ctx.actions,
+        [(app, StartType("permanent")) for app in ctx.attrs.applications],
+    ) + build_apps_start_dependencies(
+        ctx.actions,
+        [(app, StartType("load")) for app in ctx.attrs.included_applications],
+    )
+
+def build_apps_start_dependencies(actions: AnalysisActions, apps: list[(Dependency, StartType)]) -> list[StartDependencySet]:
+    start_dependencies = []
+    for app, start_type in apps[::-1]:
+        app_spec = _build_start_spec(app[ErlangAppInfo], start_type)
+
+        if app[ErlangAppInfo].virtual:
+            children = []
+        else:
+            children = app[ErlangAppInfo].start_dependencies
+
+        app_set = actions.tset(
+            StartDependencySet,
+            value = app_spec,
+            children = children,
+        )
+
+        start_dependencies.append(app_set)
+
+    return start_dependencies
+
+def _build_start_spec(app_info: Provider, start_type: StartType) -> StartSpec:
+    return StartSpec(
+        name = app_info.name,
+        version = app_info.version,
+        resolved = not app_info.virtual,
+        start_type = start_type,
+    )
+
+def _build_default_info(dep_info: ErlangDependencyInfo, app_dir: Artifact) -> Provider:
+    """generate default_outputs and DefaultInfo provider"""
+
+    # We depend on the code path of all dependencies to force them to be compiled
+    # and emit errors when users compile just this one application
+    return DefaultInfo(default_output = app_dir, other_outputs = [code_path_args(dep_info.code_path_tset)])
+
+def build_app_info(
+    ctx: AnalysisContext,
+    dep_info: ErlangDependencyInfo,
+    build_environment: BuildEnvironment,
+    app_folder: Artifact,
+    start_dependencies: list[StartDependencySet],
+) -> Provider:
+    name = app_name(ctx)
+
+    code_path_tset = ctx.actions.tset(
+        CodePathTSet,
+        value = CodePathEntry(dir = app_folder, ebin = True),
+        children = [dep_info.code_path_tset],
+    )
+
+    # build application info
+    return ErlangAppInfo(
+        name = name,
+        version = ctx.attrs.version,
+        beams = build_environment.beams.get(name),
+        dependencies = dep_info.dependencies,
+        code_path_tset = code_path_tset,
+        start_dependencies = start_dependencies,
+        includes = erlang_build.own_or_dep(build_environment.includes, build_environment.dep_includes, name),
+        include_dir = erlang_build.own_or_dep(build_environment.include_dirs, build_environment.dep_include_dirs, name),
+        private_includes = build_environment.private_includes.get(name),
+        private_include_dir = build_environment.private_include_dirs.get(name),
+        header_deps_file = erlang_build.own_or_dep(build_environment.header_deps_files, build_environment.dep_header_deps_files, name),
+        virtual = False,
+        app_folder = app_folder,
+    )
diff --git a/buck2/prelude/erlang/erlang_application_includes.bzl b/buck2/prelude/erlang/erlang_application_includes.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_application_includes.bzl
@@ -0,0 +1,45 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":erlang_build.bzl", "BuildEnvironment", "erlang_build")
+load(":erlang_info.bzl", "ErlangAppIncludeInfo")
+load(":erlang_toolchain.bzl", "get_toolchain")
+
+def erlang_application_includes_impl(ctx: AnalysisContext) -> list[Provider]:
+    """rule for application includes target"""
+
+    # prepare include directory for current app
+    name = ctx.attrs.app_name
+
+    toolchain = get_toolchain(ctx)
+    build_environment = BuildEnvironment(
+        includes = {},
+        include_dirs = {},
+        header_deps_files = {},
+    )
+    erlang_build.build_steps.generate_include_artifacts(
+        ctx,
+        toolchain,
+        build_environment,
+        name,
+        ctx.attrs.includes,
+    )
+
+    # build application info
+    app_include_info = ErlangAppIncludeInfo(
+        name = name,
+        includes = build_environment.includes[name],
+        include_dir = build_environment.include_dirs[name],
+        header_deps_file = build_environment.header_deps_files[name],
+        _original_includes = ctx.attrs.includes,
+    )
+
+    return [
+        DefaultInfo(),
+        app_include_info,
+    ]
diff --git a/buck2/prelude/erlang/erlang_build.bzl b/buck2/prelude/erlang/erlang_build.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_build.bzl
@@ -0,0 +1,567 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(":erlang_dependencies.bzl", "fail_dep_conflict")
+load(
+    ":erlang_info.bzl",
+    "DepsMapping",
+    "EbinMapping",
+    "ErlangAppIncludeInfo",  # @unused Used as type
+    "ErlangDependencyInfo",
+    "IncludesMapping",
+    "PathArtifactMapping",
+)
+load(":erlang_paths.bzl", "strip_extension")
+load(
+    ":erlang_toolchain.bzl",
+    "Toolchain",  # @unused Used as type
+)
+
+_BUILD_DIR = "__build"
+_DEP_FILES_DIR = paths.join(_BUILD_DIR, "__dep_files")
+_DEP_INFO_FILE = paths.join(_DEP_FILES_DIR, "app.info.dep")
+_GENERATED_DIR = paths.join(_BUILD_DIR, "__generated")
+
+BuildEnvironment = record(
+    # Entries the target contributes itself. The `dep_` counterparts hold the
+    # entries inherited from the dependencies and are shared by reference with
+    # the `erlang_deps_rule` that built them, so a target never copies a map
+    # sized by its transitive closure.
+    includes = field(IncludesMapping, {}),
+    include_dirs = field(PathArtifactMapping, {}),
+    private_includes = field(IncludesMapping, {}),
+    private_include_dirs = field(PathArtifactMapping, {}),
+    beams = field(EbinMapping, {}),
+    header_deps_files = field(DepsMapping, {}),
+    docs = field(dict[str, Artifact], {}),
+    dep_includes = field(IncludesMapping, {}),
+    dep_include_dirs = field(PathArtifactMapping, {}),
+    dep_private_includes = field(IncludesMapping, {}),
+    dep_private_include_dirs = field(PathArtifactMapping, {}),
+    dep_beams = field(EbinMapping, {}),
+    dep_header_deps_files = field(DepsMapping, {}),
+    # whether the dependencies' private includes participate in include resolution
+    peeked_private_includes = field(bool, False),
+)
+
+# The layers a module's dependencies resolve against, built once per application
+# rather than per compiled file. Each include layer pairs a mapping with the
+# directory mapping it is keyed alongside.
+SmallBuildEnvironment = record(
+    include_layers = field(list[(IncludesMapping, PathArtifactMapping)]),
+    private_layers = field(list[(IncludesMapping, PathArtifactMapping)]),
+    beam_layers = field(list[EbinMapping]),
+    docs = field(dict[str, Artifact], {}),
+)
+
+def _layers(own: dict, dep: dict) -> list[dict]:
+    """The maps to consult for a lookup, the target's own entries first."""
+    return [own, dep]
+
+def _paired_layers(own: dict, dep: dict, own_dirs: dict, dep_dirs: dict) -> list[(dict, dict)]:
+    """`_layers`, pairing each include map with the directory map it is keyed alongside."""
+    return [(own, own_dirs), (dep, dep_dirs)]
+
+def _own_or_dep(own: dict, dep: dict, key: str):
+    """An application's own entry, which it inherits when a cyclic `_includes_target` contributed it."""
+    value = own.get(key, None)
+    return value if value != None else dep.get(key, None)
+
+DepInfo = record(
+    dep_file = field(Artifact),
+    path = field(str),
+)
+
+def _prepare_build_environment(
+    dep_info: ErlangDependencyInfo, includes_target: [ErlangAppIncludeInfo, None] = None, peek_private_includes: bool = False
+) -> BuildEnvironment:
+    """Prepare build environment and collect the context from all dependencies."""
+    includes = {}
+    include_dirs = {}
+    header_deps_files = {}
+
+    # it's possible we already depend on our includes target through cyclic
+    # extra_includes deps, in which case we don't need to add it again
+    if includes_target and not includes_target.name in dep_info.dependencies:
+        for file in includes_target.includes:
+            for app in dep_info.includes:
+                if file in dep_info.includes[app]:
+                    fail_dep_conflict("header", file, includes_target.name, app)
+            for app in dep_info.private_includes:
+                if file in dep_info.private_includes[app]:
+                    fail_dep_conflict("header", file, includes_target.name, app)
+        include_dirs[includes_target.name] = includes_target.include_dir
+        includes[includes_target.name] = includes_target.includes
+        header_deps_files[includes_target.name] = includes_target.header_deps_file
+
+    return BuildEnvironment(
+        includes = includes,
+        include_dirs = include_dirs,
+        private_includes = {},
+        private_include_dirs = {},
+        header_deps_files = header_deps_files,
+        beams = {},
+        docs = {},
+        dep_includes = dep_info.includes,
+        dep_include_dirs = dep_info.include_dirs,
+        dep_private_includes = dep_info.private_includes,
+        dep_private_include_dirs = dep_info.private_include_dirs,
+        dep_beams = dep_info.beams,
+        dep_header_deps_files = dep_info.header_deps_files,
+        peeked_private_includes = peek_private_includes,
+    )
+
+def _generated_source_artifacts(ctx: AnalysisContext, toolchain: Toolchain) -> list[Artifact]:
+    """Generate source output artifacts and build actions for generated erl files."""
+
+    results = []
+    for src in ctx.attrs.srcs:
+        if _is_yrl(src):
+            results.append(_build_xyrl(ctx, toolchain, src, "yrl_includefile"))
+        elif _is_xrl(src):
+            results.append(_build_xyrl(ctx, toolchain, src, "xrl_includefile"))
+    return results
+
+# mutates build_environment in place
+def _generate_include_artifacts(
+    ctx: AnalysisContext, toolchain: Toolchain, build_environment: BuildEnvironment, name: str, header_artifacts: list[Artifact], is_private: bool = False
+):
+    if not header_artifacts:
+        return
+
+    include_files = {hrl.basename: hrl for hrl in header_artifacts}
+    dir_name = "{}_private".format(name) if is_private else name
+    include_dir = ctx.actions.symlinked_dir(paths.join(_BUILD_DIR, dir_name, "include"), include_files, has_content_based_path = False)
+
+    # dep files
+    deps_files = _get_deps_files(ctx, toolchain, header_artifacts)
+
+    # detect conflicts
+    conflict_layers = _layers(build_environment.includes, build_environment.dep_includes) + _layers(
+        build_environment.private_includes, build_environment.dep_private_includes
+    )
+    for file in deps_files:
+        for layer in conflict_layers:
+            for app in layer:
+                if file in layer[app]:
+                    fail_dep_conflict("header", file, name, app)
+
+    previous_merged_file = build_environment.header_deps_files.get(name, None) or build_environment.dep_header_deps_files.get(name, None)
+    if previous_merged_file != None:
+        build_environment.header_deps_files[name] = _merged_deps_file(ctx, toolchain, name, deps_files, is_private, previous_merged_file)
+    else:
+        file = _merged_deps_file(ctx, toolchain, name, deps_files, is_private, None)
+        if file:
+            build_environment.header_deps_files[name] = file
+
+    # construct updates build environment
+    if not is_private:
+        # fields for public include directory
+        build_environment.includes[name] = include_files
+        build_environment.include_dirs[name] = include_dir
+    else:
+        # fields for private include directory
+        build_environment.private_includes[name] = include_files
+        build_environment.private_include_dirs[name] = include_dir
+
+def _merged_deps_file(
+    ctx: AnalysisContext, toolchain: Toolchain, name: str, deps_files: PathArtifactMapping, is_private: bool, previous_merged_file: [Artifact, None]
+) -> [Artifact, None]:
+    """Merge the deps files of the headers into a single deps file."""
+
+    if not deps_files:
+        return previous_merged_file
+
+    name = "{}-private".format(name) if is_private else name
+
+    merged_file = ctx.actions.declare_output(_DEP_FILES_DIR, "{}.merged.dep".format(name), has_content_based_path = False)
+    deps_files_json = ctx.actions.write_json(merged_file.short_path + ".json", deps_files, with_inputs = True, has_content_based_path = False)
+
+    cmd = cmd_args(toolchain.dependency_merger, merged_file.as_output(), deps_files_json)
+    if previous_merged_file:
+        cmd.add(previous_merged_file)
+
+    _run_with_env(
+        ctx,
+        toolchain,
+        cmd,
+        category = "dependency_merger",
+        identifier = name,
+    )
+
+    return merged_file
+
+# mutates build_environment in place
+def _generate_beam_artifacts(
+    ctx: AnalysisContext, toolchain: Toolchain, build_environment: BuildEnvironment, name: str, src_artifacts: list[Artifact], hermetic_src_dir: Artifact
+):
+    if not src_artifacts:
+        return
+
+    ebin = paths.join(_BUILD_DIR, "ebin")
+
+    beam_mapping = {}
+    for erl in src_artifacts:
+        module = module_name(erl)
+        beam_mapping[module] = ctx.actions.declare_output(ebin, "{}.beam".format(module), has_content_based_path = False)
+
+    # detect conflicts
+    for key in beam_mapping:
+        for layer in _layers(build_environment.beams, build_environment.dep_beams):
+            for app in layer:
+                if key in layer[app]:
+                    fail_dep_conflict("module", key, name, app)
+
+    build_environment.beams[name] = beam_mapping
+
+    # dep files
+    deps_files = _get_deps_files(ctx, toolchain, src_artifacts)
+    # the target's own entries first: `dependency_finalizer` keeps the first value it
+    # sees for a header, and an application's own merged dep file supersedes the one
+    # its `_includes_target` contributed
+    dep_info_file = ctx.actions.write_json(
+        _DEP_INFO_FILE,
+        [build_environment.header_deps_files, build_environment.dep_header_deps_files],
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+
+    peeked = build_environment.peeked_private_includes
+    small_build_environment = SmallBuildEnvironment(
+        include_layers = _paired_layers(
+            build_environment.includes,
+            build_environment.dep_includes,
+            build_environment.include_dirs,
+            build_environment.dep_include_dirs,
+        ),
+        private_layers = _paired_layers(
+            build_environment.private_includes,
+            build_environment.dep_private_includes if peeked else {},
+            build_environment.private_include_dirs,
+            build_environment.dep_private_include_dirs if peeked else {},
+        ),
+        beam_layers = _layers(build_environment.beams, build_environment.dep_beams),
+        docs = build_environment.docs,
+    )
+
+    for erl in src_artifacts:
+        _build_erl(ctx, toolchain, small_build_environment, deps_files, dep_info_file, hermetic_src_dir, erl, beam_mapping[module_name(erl)])
+
+def _get_deps_files(ctx: AnalysisContext, toolchain: Toolchain, srcs: list[Artifact]):
+    """Mapping from the output path to the deps file artifact for each srcs artifact and dependencies."""
+
+    return {src.basename: _get_deps_file(ctx, toolchain, src) for src in srcs}
+
+def _get_deps_file(ctx: AnalysisContext, toolchain: Toolchain, src: Artifact) -> Artifact:
+    dependency_json = ctx.actions.declare_output(_DEP_FILES_DIR, "{}.dep".format(src.short_path), has_content_based_path = False)
+
+    _run_with_env(
+        ctx,
+        toolchain,
+        cmd_args(toolchain.dependency_analyzer, src, dependency_json.as_output()),
+        category = "dependency_analyzer",
+        identifier = src.short_path,
+    )
+    return dependency_json
+
+def _build_xyrl(ctx: AnalysisContext, toolchain: Toolchain, xyrl: Artifact, custom_include_opt: str) -> Artifact:
+    """Generate an erl file out of an xrl or yrl input file."""
+    output = ctx.actions.declare_output(_GENERATED_DIR, "{}.erl".format(module_name(xyrl)), has_content_based_path = False)
+    erlc = toolchain.otp_binaries.erlc
+    custom_include = getattr(ctx.attrs, custom_include_opt, None)
+    cmd = cmd_args(erlc)
+    if custom_include:
+        cmd.add("-I", custom_include)
+    cmd.add("-o", cmd_args(output.as_output(), parent = 1), xyrl)
+    _run_with_env(
+        ctx,
+        toolchain,
+        cmd,
+        error_handler = toolchain.error_handler.erlc,
+        category = "erlc",
+        identifier = xyrl.basename,
+    )
+    return output
+
+def _build_erl(
+    ctx: AnalysisContext,
+    toolchain: Toolchain,
+    build_environment: SmallBuildEnvironment,
+    beam_deps_files: PathArtifactMapping,
+    dep_info_file: WriteJsonCliArgs,
+    hermetic_src_dir: Artifact,
+    src: Artifact,
+    output: Artifact,
+) -> None:
+    """Compile erl files into beams."""
+
+    final_dep_file = ctx.actions.declare_output(_DEP_FILES_DIR, "{}.final.dep".format(src.short_path), has_content_based_path = False)
+    initial_dep_file = beam_deps_files[src.basename]
+    _run_with_env(
+        ctx,
+        toolchain,
+        cmd_args(toolchain.dependency_finalizer, initial_dep_file, dep_info_file, final_dep_file.as_output()),
+        category = "dependency_finalizer",
+        identifier = src.basename,
+    )
+
+    # src points to the original file, but erlc will try to find .hrl files on that directory,
+    # so we build the version in hermetic_src_dir, that contains symlinks to declared src (we
+    # use the `+{source, _}` option to ensure paths still point to the actual src)
+    hermetic_src = hermetic_src_dir.project(src.basename)
+
+    def dynamic_lambda(ctx: AnalysisContext, artifacts, outputs):
+        erlc = toolchain.otp_binaries.erlc
+        erl_opts = _get_erl_opts(ctx, toolchain, src)
+        deps_args, mapping = _dependencies_to_args(artifacts, final_dep_file, build_environment)
+        erlc_cmd = cmd_args(
+            erlc,
+            erl_opts,
+            deps_args,
+            cmd_args(outputs[output].as_output(), parent = 1, format = "-o{}"),
+            hermetic_src,
+        )
+        mapping_file = ctx.actions.write_json(_dep_mapping_name(src), mapping, has_content_based_path = False)
+        _run_with_env(
+            ctx,
+            toolchain,
+            erlc_cmd,
+            error_handler = toolchain.error_handler.erlc,
+            category = "erlc",
+            identifier = src.basename,
+            env = {"BUCK2_FILE_MAPPING": mapping_file},
+            always_print_stderr = True,
+        )
+
+    dynamic_inputs = [hermetic_src] + build_environment.docs.values()
+    ctx.actions.dynamic_output(dynamic = [final_dep_file], inputs = dynamic_inputs, outputs = [output.as_output()], f = dynamic_lambda)
+    return None
+
+def _dependencies_to_args(artifacts, final_dep_file: Artifact, build_environment: SmallBuildEnvironment) -> (cmd_args, dict[str, (bool, [str, Artifact])]):
+    """Add the transitive closure of all per-file Erlang dependencies as specified in the deps files to the `args` with .hidden."""
+    includes = set()
+    include_libs = set()
+    beams = set()
+    precise_includes = []
+    doc_inputs = []
+
+    input_mapping = {}
+    deps = artifacts[final_dep_file].read_json()
+
+    include_layers = build_environment.include_layers
+    private_layers = build_environment.private_layers
+
+    # silently ignore not found dependencies and let erlc report the not found stuff
+    for dep in deps:
+        file = dep["file"]
+        if dep["type"] == "include_lib":
+            app = dep["app"]
+            found_app = False
+            for app_includes, app_dirs in include_layers:
+                if app in app_includes:
+                    found_app = True
+
+                    # if file doesn't exist in app, let the compiler fail
+                    if file in app_includes[app]:
+                        include_dir = app_dirs[app]
+                        include_libs.add(include_dir)
+                        precise_includes.append(include_dir.project(file))
+                        input_mapping[file] = (True, app_includes[app][file])
+                    break
+            if not found_app:
+                # the file might come from OTP
+                input_mapping[file] = (False, paths.join(app, "include", file))
+
+        elif dep["type"] == "include":
+            # these includes can either reside in the private includes or the public ones
+            found_private = False
+
+            # we've checked for duplicates earlier, we'll find at most one
+            for app_includes, app_dirs in private_layers:
+                for app in app_includes:
+                    if file in app_includes[app]:
+                        include_dir = app_dirs[app]
+                        includes.add(include_dir)
+                        precise_includes.append(include_dir.project(file))
+                        input_mapping[file] = (True, app_includes[app][file])
+                        found_private = True
+                        break
+                if found_private:
+                    break
+
+            if not found_private:
+                # we've checked for duplicates earlier, we'll find at most one
+                found_public = False
+                for app_includes, app_dirs in include_layers:
+                    for app in app_includes:
+                        if file in app_includes[app]:
+                            include_dir = app_dirs[app]
+                            includes.add(include_dir)
+                            precise_includes.append(include_dir.project(file))
+                            input_mapping[file] = (True, app_includes[app][file])
+                            found_public = True
+                            break
+                    if found_public:
+                        break
+
+        elif dep["type"] == "behaviour" or dep["type"] == "parse_transform" or dep["type"] == "manual_dependency":
+            module = strip_extension(file)
+
+            # we made sure earlier there are no conflicts, we'll find at most one
+            found_beam = False
+            for layer in build_environment.beam_layers:
+                for app in layer:
+                    beam = layer[app].get(module, None)
+                    if beam != None:
+                        beams.add(beam)
+                        found_beam = True
+                        break
+                if found_beam:
+                    break
+
+        elif dep["type"] == "doc_file":
+            # resolve the annotation path (relative to src/) to a package-relative path
+            resolved = paths.normalize(paths.join("src", file))
+            if resolved in build_environment.docs:
+                doc_inputs.append(build_environment.docs[resolved])
+
+        else:
+            fail("unrecognized dependency type %s", (dep["type"]))
+
+    args = cmd_args(
+        cmd_args(list(includes), format = "-I{}", ignore_artifacts = True),
+        cmd_args(list(include_libs), format = "-I{}", parent = 2, ignore_artifacts = True),
+        cmd_args(list(beams), format = "-pa{}", parent = 1),
+        hidden = precise_includes + doc_inputs,
+    )
+
+    return args, input_mapping
+
+def _get_erl_opts(ctx: AnalysisContext, toolchain: Toolchain, src: Artifact) -> cmd_args:
+    always = ["+deterministic"]
+
+    # use erl_opts defined in taret if present
+    if getattr(ctx.attrs, "erl_opts", None) == None:
+        opts = toolchain.erl_opts
+    else:
+        opts = ctx.attrs.erl_opts
+
+    # dedupe options
+    opts = dedupe(opts + always)
+
+    # build args
+    args = cmd_args(opts)
+
+    # add parse_transforms
+    parse_transforms = dict(toolchain.core_parse_transforms)
+    if getattr(ctx.attrs, "use_global_parse_transforms", True):
+        for parse_transform in toolchain.parse_transforms:
+            if (
+                # add parse_transform if there is no filter set
+                not parse_transform in toolchain.parse_transforms_filters
+                or
+                # or if module is listed in the filter and add conditionally
+                module_name(src) in toolchain.parse_transforms_filters[parse_transform]
+            ):
+                parse_transforms[parse_transform] = toolchain.parse_transforms[parse_transform]
+    args.add(parse_transforms.values())
+
+    source = cmd_args(src, format = '{source, "{}"}')
+    path_type = "{path_type, relative}"
+    preserved_opts = _preserved_opts(opts)
+
+    compile_info = cmd_args(source, path_type, preserved_opts, delimiter = ", ")
+
+    # add relevant compile_info manually
+    args.add(cmd_args(compile_info, format = "+{compile_info, [{}]}"))
+
+    return args
+
+def is_preservable_opt(opt: str) -> bool:
+    return opt in ["+beam_debug_info", "+debug_info", "+inline", "+line_coverage"]
+
+def _preserved_opts(opts: list[str]) -> cmd_args:
+    """Options that should be preserved in the beam file despite +determinstic"""
+    preserved = [opt.lstrip("+") for opt in opts if is_preservable_opt(opt)]
+
+    joined = cmd_args(preserved, delimiter = ", ")
+    return cmd_args(joined, format = "{options, [{}]}")
+
+def module_name(in_file: Artifact) -> str:
+    """Returns the basename of the artifact without extension"""
+    end = in_file.basename.rfind(".")
+    return in_file.basename[:end]
+
+def _is_hrl(in_file: Artifact) -> bool:
+    """Returns True if the artifact is a hrl file"""
+    return _is_ext(in_file, ".hrl")
+
+def _is_erl(in_file: Artifact) -> bool:
+    """Returns True if the artifact is an erl file"""
+    return _is_ext(in_file, ".erl")
+
+def _is_yrl(in_file: Artifact) -> bool:
+    """Returns True if the artifact is a yrl file"""
+    return _is_ext(in_file, ".yrl")
+
+def _is_xrl(in_file: Artifact) -> bool:
+    """Returns True if the artifact is a xrl file"""
+    return _is_ext(in_file, ".xrl")
+
+def _is_config(in_file: Artifact) -> bool:
+    """Returns True if the artifact is a config file"""
+    return _is_ext(in_file, ".config")
+
+def _is_ext(in_file: Artifact, extension: str) -> bool:
+    """Returns True if the artifact has an extension listed in extensions"""
+    return in_file.basename.endswith(extension)
+
+def _dep_mapping_name(src: Artifact) -> str:
+    return paths.join(
+        _DEP_FILES_DIR,
+        "{}.mapping".format(src.short_path),
+    )
+
+def _run_with_env(ctx: AnalysisContext, toolchain: Toolchain, args: cmd_args, **kwargs):
+    """run interfact that injects env"""
+
+    # use os_env defined in target if present
+    if getattr(ctx.attrs, "os_env", None) == None:
+        env = toolchain.env
+    else:
+        env = ctx.attrs.os_env
+
+    if "env" in kwargs:
+        kwargs["env"].update(env)
+    else:
+        kwargs["env"] = env
+
+    ctx.actions.run(args, **kwargs)
+
+# export
+
+erlang_build = struct(
+    prepare_build_environment = _prepare_build_environment,
+    own_or_dep = _own_or_dep,
+    build_steps = struct(
+        generated_source_artifacts = _generated_source_artifacts,
+        generate_include_artifacts = _generate_include_artifacts,
+        generate_beam_artifacts = _generate_beam_artifacts,
+    ),
+    utils = struct(
+        BUILD_DIR = _BUILD_DIR,
+        is_hrl = _is_hrl,
+        is_erl = _is_erl,
+        is_yrl = _is_yrl,
+        is_xrl = _is_xrl,
+        is_config = _is_config,
+        module_name = module_name,
+        run_with_env = _run_with_env,
+    ),
+)
diff --git a/buck2/prelude/erlang/erlang_dependencies.bzl b/buck2/prelude/erlang/erlang_dependencies.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_dependencies.bzl
@@ -0,0 +1,187 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    ":erlang_info.bzl",
+    "CodePathTSet",
+    "ErlangAppIncludeInfo",
+    "ErlangAppInfo",
+    "ErlangDependencyInfo",
+    "ErlangTestInfo",
+)
+
+def _erlang_deps_impl(ctx: AnalysisContext) -> list[Provider]:
+    dependencies = {}
+    _flatten_dependencies(ctx.attrs.deps, dependencies)
+    _flatten_dependencies(ctx.attrs.applications, dependencies)
+    _flatten_dependencies(ctx.attrs.included_applications, dependencies)
+    _flatten_dependencies(ctx.attrs.extra_includes, dependencies)
+
+    all_includes = {}
+    includes = {}
+    include_dirs = {}
+    header_deps_files = {}
+    private_includes = {}
+    private_include_dirs = {}
+    beams = {}
+    all_beams = {}
+
+    for name in dependencies:
+        dep = dependencies[name]
+
+        if ErlangAppInfo in dep:
+            dep_info = dep[ErlangAppInfo]
+
+            if dep_info.virtual:
+                # virtual applications don't directories we need to include
+                # we skip this entire step
+                continue
+
+            # collect beams
+            if dep_info.beams:
+                new_beams = dep_info.beams
+                for mod in new_beams:
+                    if mod in all_beams:
+                        fail_dep_conflict("module", mod, all_beams[mod], name)
+                    all_beams[mod] = name
+                beams[name] = new_beams
+
+            # collect private includes
+            if dep_info.private_include_dir:
+                private_include_dirs[name] = dep_info.private_include_dir
+                new_includes = dep_info.private_includes
+                for hrl in new_includes:
+                    if hrl in all_includes:
+                        fail_dep_conflict("header", hrl, all_includes[hrl], name)
+                    all_includes[hrl] = name
+                private_includes[name] = new_includes
+
+        elif ErlangAppIncludeInfo in dep:
+            dep_info = dep[ErlangAppIncludeInfo]
+
+        elif ErlangTestInfo in dep:
+            # for test deps we only care about code path
+            continue
+        else:
+            fail("invalid dep {}", dep)
+
+        # collect includes
+        if dep_info.include_dir:
+            include_dirs[name] = dep_info.include_dir
+            new_includes = dep_info.includes
+            for hrl in new_includes:
+                if hrl in all_includes:
+                    fail_dep_conflict("header", hrl, all_includes[hrl], name)
+                all_includes[hrl] = name
+            includes[name] = new_includes
+
+        # collect header_deps_files
+        if dep_info.header_deps_file:
+            header_deps_files[name] = dep_info.header_deps_file
+
+    code_path_tset = ctx.actions.tset(
+        CodePathTSet,
+        children = _direct_code_path_tsets(
+            ctx.attrs.deps + ctx.attrs.applications + ctx.attrs.included_applications,
+        ),
+    )
+
+    dependency_info = ErlangDependencyInfo(
+        dependencies = dependencies,
+        includes = includes,
+        include_dirs = include_dirs,
+        private_includes = private_includes,
+        private_include_dirs = private_include_dirs,
+        header_deps_files = header_deps_files,
+        beams = beams,
+        code_path_tset = code_path_tset,
+    )
+
+    return [DefaultInfo(), dependency_info]
+
+def _direct_code_path_tsets(deps: list[Dependency]) -> list[CodePathTSet]:
+    """Code path sets of the given dependencies, skipping the ones that contribute nothing.
+
+    Virtual applications carry no directory and no dependencies of their own, and
+    include-only targets are headers, so neither has a set.
+    """
+    tsets = []
+    for dep in deps:
+        if ErlangAppInfo in dep:
+            tset = dep[ErlangAppInfo].code_path_tset
+        elif ErlangTestInfo in dep:
+            tset = dep[ErlangTestInfo].code_path_tset
+        else:
+            tset = None
+        if tset != None:
+            tsets.append(tset)
+    return tsets
+
+def fail_dep_conflict(kind: str, name: str, app1: str, app2: str) -> None:
+    fail("conflicting {} `{}` found, defined in applications '{}' and '{}'".format(kind, name, app1, app2))
+
+erlang_deps_rule = anon_rule(
+    impl = _erlang_deps_impl,
+    attrs = {
+        "applications": attrs.set(attrs.dep(), default = []),
+        "deps": attrs.set(attrs.dep(), default = []),
+        "extra_includes": attrs.set(attrs.dep(), default = []),
+        "included_applications": attrs.set(attrs.dep(), default = []),
+    },
+    artifact_promise_mappings = {},
+)
+
+ErlAppDependencies = dict[str, Dependency]
+
+def flatten_dependencies(deps: list[Dependency]) -> ErlAppDependencies:
+    dependencies = {}
+    _flatten_dependencies(deps, dependencies)
+    return dependencies
+
+# mutates dependencies in place
+def _flatten_dependencies(deps: list[Dependency], dependencies: ErlAppDependencies):
+    """collect transitive dependencies
+
+    Flatten all transitive dependencies and merge together with the direct
+    ones. This is done at every step (with each `erlang_application_impl ` call),
+    so we only need to look one hop away.
+    """
+    for dep in deps:
+        if ErlangAppInfo in dep:
+            # handle transitive deps
+            for trans_dep_val in dep[ErlangAppInfo].dependencies.values():
+                dependencies = _safe_add_dependency(dependencies, trans_dep_val)
+        elif ErlangTestInfo in dep:
+            for trans_dep_val in dep[ErlangTestInfo].dependencies.values():
+                dependencies = _safe_add_dependency(dependencies, trans_dep_val)
+        dependencies = _safe_add_dependency(dependencies, dep)
+
+    return dependencies
+
+# mutates dependencies in place
+def _safe_add_dependency(dependencies: ErlAppDependencies, dep: Dependency):
+    """Adds ErlangAppInfo and ErlangAppIncludeInfo dependencies
+
+    ErlangAppInfo (full) application dependencies overwrite include_only dependencies,
+    while include_only dependencies are only added if no other dependency is already
+    present.
+
+    ErlangAppInfo applications fail, if there is already another full application with the
+    same name added.
+    """
+    if ErlangAppInfo in dep:
+        name = dep[ErlangAppInfo].name
+        if name in dependencies and ErlangAppInfo in dependencies[name] and dep.label != dependencies[name].label:
+            fail(("duplicated application `%s` in dependency tree:\n" + "    %s\n" + "    %s") % (name, str(dep.label), str(dependencies[name].label)))
+        else:
+            dependencies[name] = dep
+    elif ErlangTestInfo in dep:
+        dependencies[dep[ErlangTestInfo].name] = dep
+    elif dep[ErlangAppIncludeInfo].name not in dependencies:
+        dependencies[dep[ErlangAppIncludeInfo].name] = dep
+    return dependencies
diff --git a/buck2/prelude/erlang/erlang_error_handler.bzl b/buck2/prelude/erlang/erlang_error_handler.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_error_handler.bzl
@@ -0,0 +1,116 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    ":erlang_info.bzl",
+    "ErlangErrorHandlers",
+)
+
+# erlc error format:
+#   The erlc compiler error format is as following:
+#     <file>:<line>:<column>: <message>
+
+def erlang_erlc_action_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:
+    structured_errors = ctx.parse_with_errorformat(
+        category = "erlang_compile_error",
+        error = ctx.stderr,
+        errorformats = [
+            "%f:%l:%c:\\ %m",
+        ],
+    )
+
+    return structured_errors
+
+# extract_otp_app error format:
+#     <file>:<line>:<error_number>: <message>
+#
+# NOTE: <message> is JSON encoded
+
+def erlang_extract_otp_app_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:
+    parsed_errors = ctx.parse_with_errorformat(
+        category = "extract_from_otp_error",
+        error = ctx.stderr,
+        errorformats = [
+            "%f:%l:%n:\\ %m",
+        ],
+    )
+
+    structured_errors = []
+
+    if parsed_errors:
+        structured_errors.extend(parsed_errors)
+        for parsed_error in parsed_errors:
+            if parsed_error.error_number == 1 and parsed_error.message != None:
+                # otp_application_not_found
+                error_json = json.decode(parsed_error.message)
+                app_name = error_json["name"]
+
+                # Build available applications list if present
+                available_apps_section = ""
+                if "available_applications" in error_json and error_json["available_applications"]:
+                    available_apps = error_json["available_applications"]
+                    apps_list = "\n".join(["   - {}".format(app) for app in available_apps])
+                    available_apps_section = "\n\n Available OTP applications ({count}):\n{apps_list}".format(count = len(available_apps), apps_list = apps_list)
+
+                remediation = """To fix, verify '{app_name}' exists in your OTP installation:
+
+    $ ls -Al "{root_dir}/lib/{app_name}-*"
+
+ Common causes:
+   - The application is not part of your OTP version (e.g., jinterface was removed in OTP 27)
+   - You're using a toolchain configured for a different OTP version{available_apps_section}""".format(
+                    app_name = app_name,
+                    root_dir = error_json["root_dir"],
+                    available_apps_section = available_apps_section,
+                )
+                structured_errors.append(
+                    ctx.new_sub_error(
+                        category = parsed_error.category,
+                        subcategory = "otp_application_not_found",
+                        message = error_json["message"],
+                        remediation = remediation,
+                        file = parsed_error.file,
+                        lnum = parsed_error.lnum,
+                        error_number = parsed_error.error_number,
+                        show_in_stderr = True,
+                    )
+                )
+            elif parsed_error.error_number == 2 and parsed_error.message != None:
+                # no_matches_for_wildcard
+                error_json = json.decode(parsed_error.message)
+                structured_errors.append(
+                    ctx.new_sub_error(
+                        category = parsed_error.category,
+                        subcategory = "no_matches_for_wildcard",
+                        message = error_json["message"],
+                        file = parsed_error.file,
+                        lnum = parsed_error.lnum,
+                        error_number = parsed_error.error_number,
+                        show_in_stderr = True,
+                    )
+                )
+            elif parsed_error.error_number == 3 and parsed_error.message != None:
+                # multiple_matches_for_wildcard
+                error_json = json.decode(parsed_error.message)
+                structured_errors.append(
+                    ctx.new_sub_error(
+                        category = parsed_error.category,
+                        subcategory = "multiple_matches_for_wildcard",
+                        message = error_json["message"],
+                        file = parsed_error.file,
+                        lnum = parsed_error.lnum,
+                        error_number = parsed_error.error_number,
+                        show_in_stderr = True,
+                    )
+                )
+
+    return structured_errors
+
+erlang_action_error_handler = ErlangErrorHandlers(
+    erlc = erlang_erlc_action_error_handler,
+)
diff --git a/buck2/prelude/erlang/erlang_erts.bzl b/buck2/prelude/erlang/erlang_erts.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_erts.bzl
@@ -0,0 +1,140 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    ":erlang_error_handler.bzl",
+    "erlang_extract_otp_app_error_handler",
+)
+load(
+    ":erlang_info.bzl",
+    "ErlangOTPBinariesInfo",
+    "ErtsToolchainInfo",
+    "Tool",
+)
+load(
+    ":erlang_otp_application.bzl",
+    "otp_applications",
+)
+load(
+    ":erlang_paths.bzl",
+    "strip_extension",
+)
+load(
+    ":erlang_toolchain.bzl",
+    "default_toolchain_script_args_post",
+    "default_toolchain_script_args_pre",
+)
+
+# The extraction runs `erl`, so its exec platform has to match the target platform or the
+# artifacts come out for the wrong one. There is no DEFAULT: a target platform that is not
+# listed here fails to configure rather than silently producing a foreign-architecture release.
+_DEFAULT_EXEC_COMPATIBLE_WITH = select({
+    "config//os/constraints:os[unspecified]": [],
+    "config//os:linux": select({
+        "config//cpu:arm64": [
+            "config//cpu/constraints:arm64",
+            "config//os/constraints:linux",
+        ],
+        "config//cpu:x86_64": [
+            "config//cpu/constraints:x86_64",
+            "config//os/constraints:linux",
+        ],
+    }),
+    "config//os:macos": select({
+        "config//cpu:arm64": [
+            "config//cpu/constraints:arm64",
+            "config//os/constraints:macos",
+        ],
+        "config//cpu:x86_64": [
+            "config//cpu/constraints:x86_64",
+            "config//os/constraints:macos",
+        ],
+    }),
+    "config//os:windows": select({
+        "config//cpu:arm64": [
+            "config//cpu/constraints:arm64",
+            "config//os/constraints:windows",
+        ],
+        "config//cpu:x86_64": [
+            "config//cpu/constraints:x86_64",
+            "config//os/constraints:windows",
+        ],
+    }),
+})
+
+def _extractor(ctx: AnalysisContext, binaries: ErlangOTPBinariesInfo, env: dict[str, str]) -> Tool:
+    src = ctx.attrs._extract_from_otp
+    name = strip_extension(src.basename)
+    beam = ctx.actions.declare_output(name, name + ".beam", has_content_based_path = False)
+    erlc = cmd_args(binaries.erlc, hidden = binaries.erl)
+    ctx.actions.run(
+        cmd_args(erlc, "+deterministic", "-o", cmd_args(beam.as_output(), parent = 1), src),
+        category = "erlc",
+        identifier = src.short_path,
+        env = env,
+    )
+    return cmd_args(
+        binaries.erl,
+        cmd_args(beam, parent = 1, prepend = "-pa"),
+        default_toolchain_script_args_pre,
+        cmd_args(name, ":main(init:get_plain_arguments())", delimiter = ""),
+        default_toolchain_script_args_post,
+    )
+
+def _erlang_erts_impl(ctx: AnalysisContext) -> list[Provider]:
+    binaries = ctx.attrs.otp_binaries[ErlangOTPBinariesInfo]
+    env = ctx.attrs.env
+    extractor = _extractor(ctx, binaries, env)
+
+    def extract(name: str, args: list[str], category: str, dir: bool = True) -> Artifact:
+        out = ctx.actions.declare_output(name, dir = dir, has_content_based_path = False)
+        ctx.actions.run(
+            cmd_args(extractor, args, out.as_output()),
+            category = category,
+            identifier = ctx.attrs.name,
+            env = env,
+        )
+        return out
+
+    # one action per application, so a release only ever extracts what its own closure names
+    applications = {}
+    for application in otp_applications:
+        out = ctx.actions.declare_output(paths.join("lib", application), dir = True, has_content_based_path = False)
+        ctx.actions.run(
+            cmd_args(extractor, paths.join("lib", application + "-*"), out.as_output()),
+            category = "extract_otp_app",
+            identifier = application,
+            env = env,
+            error_handler = erlang_extract_otp_app_error_handler,
+        )
+        applications[application] = out
+
+    return [
+        DefaultInfo(),
+        ErtsToolchainInfo(
+            applications = applications,
+            erts = extract("erts", ["extract_into", "erts-*"], "extract_erts"),
+            headers = extract("erts_headers", ["erts-*/include"], "extract_erts_headers"),
+            otp_no_dot_erlang_boot = extract("otp_no_dot_erlang_boot", ["bin/no_dot_erlang.boot"], "extract_otp_boot", False),
+            otp_start_boot = extract("otp_start_boot", ["bin/start.boot"], "extract_otp_start_boot", False),
+            versions = extract("versions.json", ["versions"], "introspect_otp_versions", False),
+        ),
+    ]
+
+_erlang_erts_rule = rule(
+    impl = _erlang_erts_impl,
+    attrs = {
+        "env": attrs.dict(key = attrs.string(), value = attrs.string(), default = {}),
+        "otp_binaries": attrs.toolchain_dep(),
+        "_extract_from_otp": attrs.default_only(attrs.source(default = "prelude//erlang/erts:extract_from_otp.erl")),
+    },
+)
+
+def erlang_erts(exec_compatible_with = _DEFAULT_EXEC_COMPATIBLE_WITH, **kwargs):
+    _erlang_erts_rule(exec_compatible_with = exec_compatible_with, **kwargs)
diff --git a/buck2/prelude/erlang/erlang_escript.bzl b/buck2/prelude/erlang/erlang_escript.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_escript.bzl
@@ -0,0 +1,215 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(":erlang_build.bzl", "erlang_build")
+load(":erlang_dependencies.bzl", "flatten_dependencies")
+load(":erlang_info.bzl", "ErlangAppInfo")
+load(":erlang_paths.bzl", "has_extension")
+load(
+    ":erlang_toolchain.bzl",
+    "Toolchain",  # @unused Used as type
+    "get_toolchain",
+)
+
+def erlang_escript_impl(ctx: AnalysisContext) -> list[Provider]:
+    toolchain = get_toolchain(ctx)
+
+    # collect all dependencies
+    dependencies = flatten_dependencies(ctx.attrs.deps)
+    artifacts = {}
+
+    for dep in dependencies.values():
+        if ErlangAppInfo not in dep:
+            # skip extra includes
+            continue
+        dep_info = dep[ErlangAppInfo]
+        if dep_info.virtual:
+            # skip virtual apps
+            continue
+        app_folder = dep_info.app_folder
+
+        artifacts[_ebin_path(dep_info.name)] = app_folder.project("ebin")
+        if ctx.attrs.include_priv:
+            artifacts[_priv_path(dep_info.name)] = app_folder.project("priv")
+
+    # additional resources
+    for res in ctx.attrs.resources:
+        for artifact in res[DefaultInfo].default_outputs:
+            if artifact.short_path in artifacts:
+                fail("multiple artifacts defined for path %s", (artifact.short_path))
+            artifacts[artifact.short_path] = artifact
+        for artifact in res[DefaultInfo].other_outputs:
+            if artifact.short_path in artifacts:
+                fail("multiple artifacts defined for path %s", (artifact.short_path))
+            artifacts[artifact.short_path] = artifact
+
+    escript_name = _escript_name(ctx)
+    output = ctx.actions.declare_output(escript_name, has_content_based_path = False)
+
+    args = ctx.attrs.emu_args
+
+    config_files = _escript_config_files(ctx)
+    for config_file in config_files:
+        artifacts[config_file.short_path] = config_file
+
+    escript_trampoline = build_escript_bundled_trampoline(ctx, toolchain, config_files)
+    artifacts[escript_trampoline.basename] = escript_trampoline
+
+    args += ["-escript", "main", "erlang_escript_trampoline"]
+
+    escript_build_spec = {
+        "artifacts": artifacts,
+        "emu_args": args,
+        "output": output.as_output(),
+    }
+
+    spec_file = ctx.actions.write_json(
+        "escript_build_spec.json",
+        escript_build_spec,
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+
+    create_escript(ctx, spec_file, toolchain, escript_name)
+
+    escript_cmd = cmd_args(
+        [
+            toolchain.otp_binaries.escript,
+            output,
+        ],
+    )
+
+    return [
+        DefaultInfo(default_output = output),
+        RunInfo(escript_cmd),
+    ]
+
+def create_escript(ctx: AnalysisContext, spec_file: WriteJsonCliArgs, toolchain: Toolchain, escript_name: str) -> None:
+    """build the escript with the escript builder tool"""
+
+    erlang_build.utils.run_with_env(
+        ctx,
+        toolchain,
+        cmd_args(toolchain.escript_builder, spec_file),
+        category = "escript",
+        identifier = escript_name,
+    )
+    return None
+
+def _escript_name(ctx: AnalysisContext) -> str:
+    if ctx.attrs.script_name:
+        return ctx.attrs.script_name
+    else:
+        return ctx.attrs.name + ".escript"
+
+def _main_module(ctx: AnalysisContext) -> str:
+    if ctx.attrs.main_module:
+        return ctx.attrs.main_module
+    else:
+        return ctx.attrs.name
+
+def build_escript_unbundled_trampoline(ctx: AnalysisContext, config_files: list[Artifact]) -> Artifact:
+    data = cmd_args()
+
+    data.add("#!/usr/bin/env escript")
+    data.add("%% -*- erlang -*-")
+    data.add("%%! {}".format(" ".join(ctx.attrs.emu_args)))
+
+    data.add("-module('{}').".format(_escript_name(ctx)))
+    data.add("-export([main/1]).")
+    data.add("main(Args) ->")
+    data.add("EscriptDir = filename:dirname(escript:script_name()),")
+    data.add(_config_files_code_to_erl(config_files))
+    data.add('    EBinDirs = filelib:wildcard(filename:join([EscriptDir, "lib", "*", "ebin"])),')
+    data.add("    code:add_paths(EBinDirs),")
+    data.add("    {}:main(Args).".format(_main_module(ctx)))
+    data.add(_parse_bin())
+
+    return ctx.actions.write(
+        paths.join(erlang_build.utils.BUILD_DIR, "run.escript"),
+        data,
+        is_executable = True,
+        has_content_based_path = False,
+    )
+
+def build_escript_bundled_trampoline(ctx: AnalysisContext, toolchain, config_files: list[Artifact]) -> Artifact:
+    data = cmd_args()
+
+    data.add(
+        """-module('erlang_escript_trampoline').
+-export([main/1]).
+main(Args) ->
+EscriptDir = escript:script_name(),""",
+    )
+    data.add(_config_files_code_to_erl(config_files))
+    data.add("    {}:main(Args).".format(_main_module(ctx)))
+    data.add(_parse_bin())
+    escript_trampoline_erl = ctx.actions.write(
+        paths.join(erlang_build.utils.BUILD_DIR, "erlang_escript_trampoline.erl"),
+        data,
+        has_content_based_path = False,
+    )
+    my_output = ctx.actions.declare_output("erlang_escript_trampoline.beam", has_content_based_path = False)
+
+    erlang_build.utils.run_with_env(
+        ctx,
+        toolchain,
+        cmd_args(
+            toolchain.otp_binaries.erlc,
+            "-o",
+            cmd_args(my_output.as_output(), parent = 1),
+            escript_trampoline_erl,
+        ),
+        category = "erlc_escript_trampoline",
+    )
+
+    return my_output
+
+def _ebin_path(app_name: str) -> str:
+    return paths.join(app_name, "ebin")
+
+def _priv_path(app_name: str) -> str:
+    return paths.join(app_name, "priv")
+
+def _escript_config_files(ctx: AnalysisContext) -> list[Artifact]:
+    config_files = []
+    for config_dep in ctx.attrs.configs:
+        for artifact in config_dep[DefaultInfo].default_outputs:
+            if has_extension(artifact.short_path, ".config"):
+                config_files.append(artifact)
+        for artifact in config_dep[DefaultInfo].other_outputs:
+            if has_extension(artifact.short_path, ".config"):
+                config_files.append(artifact)
+    return config_files
+
+def _config_files_code_to_erl(config_files: list[Artifact]) -> list[str]:
+    cmd = []
+    cmd.append("ConfigFiles = [")
+    for i in range(0, len(config_files)):
+        cmd.append('"{}"'.format(config_files[i].short_path))
+        if i < len(config_files) - 1:
+            cmd.append(",")
+    cmd.append(
+        """],
+[begin
+{ok, AppConfigBin, _FullName} = erl_prim_loader:get_file(filename:join(EscriptDir, ConfigFile)),
+{ok, AppConfig} = parse_bin(AppConfigBin),
+ok = application:set_env(AppConfig, [{persistent, true}])
+end || ConfigFile <- ConfigFiles],""",
+    )
+    return cmd
+
+def _parse_bin() -> str:
+    return """
+parse_bin(<<"">>) ->
+    [];
+parse_bin(Bin) ->
+        {ok, Tokens, _} = erl_scan:string(binary_to_list(Bin)),
+        erl_parse:parse_term(Tokens).
+        """
diff --git a/buck2/prelude/erlang/erlang_headers.bzl b/buck2/prelude/erlang/erlang_headers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_headers.bzl
@@ -0,0 +1,26 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":erlang_toolchain.bzl", "get_toolchain")
+
+def _erlang_headers(ctx: AnalysisContext) -> list[Provider]:
+    erts_toolchain_info = get_toolchain(ctx).erts_toolchain_info
+    if erts_toolchain_info == None:
+        fail("%s exposes the ERTS headers, but its toolchain has no `erts_toolchain_info` to take them from" % (str(ctx.label),))
+    return [
+        DefaultInfo(
+            default_outputs = [erts_toolchain_info.headers],
+        ),
+    ]
+
+erlang_headers = rule(
+    impl = _erlang_headers,
+    attrs = {
+        "_toolchain": attrs.toolchain_dep(default = "toolchains//:erlang-default"),
+    },
+)
diff --git a/buck2/prelude/erlang/erlang_info.bzl b/buck2/prelude/erlang/erlang_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_info.bzl
@@ -0,0 +1,234 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# This file contains the specification for all the providers the Erlang
+# integration uses.
+
+CodePathEntry = record(
+    dir = field(Artifact),
+    # application directories contribute `<dir>/ebin`, test output directories contribute `<dir>`
+    ebin = field(bool),
+)
+
+def _code_path_projection(entry: CodePathEntry) -> cmd_args:
+    if entry.ebin:
+        return cmd_args(entry.dir, format = "{}/ebin")
+    return cmd_args(entry.dir)
+
+CodePathTSet = transitive_set(args_projections = {"code_path": _code_path_projection})
+
+def code_path_args(code_path_tset: CodePathTSet) -> TransitiveSetArgsProjection:
+    """The directories of a `CodePathTSet`, as they are passed to `erl -pa`."""
+    return code_path_tset.project_as_args("code_path")
+
+# Information about an Erlang application and its dependencies.
+
+ErlangAppCommonFields = [
+    # application name
+    "name",
+    # mapping from ("application", "basename") -> to header artifact
+    "includes",
+    # path to include directory
+    "include_dir",
+    # deps files short_path -> artifact
+    "header_deps_file",
+]
+
+# target type to break circular dependencies
+ErlangAppIncludeInfo = provider(
+    fields = ErlangAppCommonFields
+    + [
+        # original inclues, used for validating _include_only app against the original
+        "_original_includes",
+    ],
+)
+
+ErlangAppInfo = provider(
+    fields = ErlangAppCommonFields
+    + [
+        # version
+        "version",
+        # mapping from module name to beam artifact
+        "beams",
+        # for tests we need to preserve the private includes
+        "private_includes",
+        "private_include_dir",
+        # mapping from name to dependency for all Erlang dependencies
+        "dependencies",
+        # CodePathTSet rooted at this application, None for virtual applications
+        "code_path_tset",
+        # Transitive Set for calculating the start order
+        "start_dependencies",
+        # additional targets that the application depends on, the
+        # default output will end up in priv/
+        "resources",
+        # applications that are in path but not build by buck2 are virtual
+        # the use-case for virtual apps are OTP applications that are shipeped
+        # with the Erlang distribution
+        "virtual",
+        # app_folder
+        "app_folder",
+    ],
+)
+
+# mapping
+#   from include base name (e.g. "header.hrl")
+#   to artifact
+PathArtifactMapping = dict[str, Artifact]
+
+# mapping
+#   from application to includes in that application
+#   the artifacts are source .hrl files
+IncludesMapping = dict[str, PathArtifactMapping]
+
+# mapping
+#   from module name to beam file location
+ModuleArtifactMapping = dict[str, Artifact]
+
+# mapping
+#   from application to beam files it defines
+EbinMapping = dict[str, ModuleArtifactMapping]
+
+# mapping
+#   from application to merged deps files
+DepsMapping = dict[str, Artifact]
+
+ErlangDependencyInfo = provider(
+    fields = {
+        "beams": provider_field(EbinMapping, default = {}),
+        # code path of the transitive closure of the dependencies
+        "code_path_tset": provider_field(CodePathTSet),
+        "dependencies": provider_field(dict[str, Dependency], default = {}),
+        "header_deps_files": provider_field(DepsMapping, default = {}),
+        "include_dirs": provider_field(PathArtifactMapping, default = {}),
+        "includes": provider_field(IncludesMapping, default = {}),
+        "private_include_dirs": provider_field(PathArtifactMapping, default = {}),
+        "private_includes": provider_field(IncludesMapping, default = {}),
+    },
+)
+
+ErlangReleaseInfo = provider(
+    fields = {
+        "name": provider_field(typing.Any, default = None),
+    },
+)
+
+# Marker provider to enforce what erlang tests can depend on
+ErlangAppOrTestInfo = provider(fields = {})
+
+Tool = cmd_args
+
+ErlangOTPBinariesInfo = provider(
+    fields = {
+        "erl": provider_field(Tool),
+        "erlc": provider_field(Tool),
+        "escript": provider_field(Tool),
+    },
+)
+
+Tools = record(
+    erl = field(Tool),
+    erlc = field(Tool),
+    escript = field(Tool),
+)
+
+ErtsToolchainInfo = provider(
+    fields = {
+        # the directory each OTP application ships as, by application name
+        "applications": provider_field(dict[str, Artifact]),
+        # directory holding `erts-<version>`
+        "erts": provider_field(Artifact),
+        "headers": provider_field(Artifact),
+        "otp_no_dot_erlang_boot": provider_field(Artifact),
+        "otp_start_boot": provider_field(Artifact),
+        # json, `{"erts_version": ..., "applications": {<application>: <version>}}`
+        "versions": provider_field(Artifact),
+    },
+)
+
+ErlangErrorHandlers = record(
+    erlc = field(typing.Callable[[ActionErrorCtx], list[ActionSubError]]),
+)
+
+# toolchain provider
+ErlangToolchainInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "name": provider_field(str),
+        # command line erlc options used when compiling
+        "erl_opts": provider_field(list[str]),
+        # emulator flags used when calling erl
+        "emu_flags": provider_field(list[str]),
+        # struct containing the binaries erlc, escript, and erl
+        # this is further split into local and RE
+        "otp_binaries": provider_field(Tools),
+        # utility scripts
+        # building .app file
+        "app_src_script": provider_field(Tool),
+        # building .appup file
+        "appup_src_script": provider_field(Tool),
+        # building escripts
+        "escript_builder": provider_field(Tool),
+        # analyzing .(h|e)rl dependencies
+        "dependency_analyzer": provider_field(Tool),
+        "dependency_finalizer": provider_field(Tool),
+        "dependency_merger": provider_field(Tool),
+        "escript_trampoline": provider_field(Artifact),
+        # name to parse_transform artifacts mapping for core parse_transforms (that are always used) and
+        # user defines ones
+        "core_parse_transforms": provider_field(dict[str, cmd_args]),
+        "parse_transforms": provider_field(dict[str, cmd_args]),
+        # filter spec for parse transforms
+        "parse_transforms_filters": provider_field(dict[str, list[str]]),
+        # release boot script builder
+        "boot_script_builder": provider_field(Tool),
+        # build release_variables
+        "release_variables_builder": provider_field(Tool),
+        # beams we need for various reasons
+        "utility_modules": provider_field(Artifact),
+        # env to be set for toolchain invocations
+        "env": provider_field(dict[str, str]),
+        # Erlang Runtime System (ERTS) toolchain metadata
+        "erts_toolchain_info": provider_field(ErtsToolchainInfo | None, default = None),
+        # error handler
+        "error_handler": provider_field(ErlangErrorHandlers),
+    },
+)
+
+# multi-version toolchain
+ErlangMultiVersionToolchainInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "toolchain": provider_field(ErlangToolchainInfo),
+    },
+)
+
+# parse_transform
+ErlangParseTransformInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        # module implementing the parse_transform
+        "source": provider_field(Artifact),
+        # potential extra files placed in a resource folder
+        "extra_files": provider_field(list[Artifact]),
+    },
+)
+
+ErlangTestInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        # mapping from name to dependency for all Erlang dependencies
+        "dependencies": provider_field(dict[str, Dependency]),
+        # CodePathTSet rooted at this test
+        "code_path_tset": provider_field(CodePathTSet),
+        # The name of the suite
+        "name": provider_field(str),
+        # anchor to the output_dir
+        "output_dir": provider_field(Artifact),
+    },
+)
diff --git a/buck2/prelude/erlang/erlang_ls.config b/buck2/prelude/erlang/erlang_ls.config
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_ls.config
@@ -0,0 +1,39 @@
+{
+    "include_dirs": [
+        "./common_test",
+        "./common_test/*/include",
+        "./common_test/*/src"
+    ],
+    "apps_dirs": [
+        "./common_test/*"
+    ],
+    "compiler_telemetry_enabled": true,
+    "deps_dirs": [
+        "../../third-party/vendor/*"
+    ],
+    "diagnostics": {
+        "disabled": [
+            "crossref",
+            "dialyzer",
+            "elvis"
+        ],
+        "enabled": [
+            "edoc"
+        ]
+    },
+    "incremental_sync": true,
+    "lenses": {
+        "disabled": [
+            "suggest-spec",
+            "function-references"
+        ],
+        "enabled": [
+            "server-info"
+        ]
+    },
+    "macros": [
+        {
+            "name": "TEST"
+        }
+    ]
+}
diff --git a/buck2/prelude/erlang/erlang_otp_application.bzl b/buck2/prelude/erlang/erlang_otp_application.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_otp_application.bzl
@@ -0,0 +1,102 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":erlang_info.bzl", "ErlangAppInfo", "ErlangAppOrTestInfo")
+load(
+    ":erlang_toolchain.bzl",
+    "get_toolchain",
+)
+
+# This is a superset of all available OTP applications and needs to be manually updated
+# if new applications make it into OTP. New applications will not be available until
+# they are listed here.
+otp_applications = [
+    "asn1",
+    "common_test",
+    "compiler",
+    "crypto",
+    "debugger",
+    "dialyzer",
+    "diameter",
+    "edoc",
+    "eldap",
+    "erl_docgen",
+    "erl_interface",
+    "erts",
+    "et",
+    "eunit",
+    "ftp",
+    "inets",
+    "jinterface",
+    "kernel",
+    "megaco",
+    "mnesia",
+    "observer",
+    "os_mon",
+    "parsetools",
+    "public_key",
+    "reltool",
+    "runtime_tools",
+    "sasl",
+    "snmp",
+    "ssh",
+    "ssl",
+    "stdlib",
+    "syntax_tools",
+    "tftp",
+    "tools",
+    "wx",
+    "xmerl",
+]
+
+def gen_otp_applications() -> None:
+    for name in otp_applications:
+        _erlang_otp_application_rule(name = name, visibility = ["PUBLIC"])
+    return None
+
+def normalize_application(name: str) -> str:
+    """Try to translate OTP application names to internal targets so users can write
+    `kernel` instead of `prelude//erlang/applications:kernel`
+    """
+    if ":" not in name:
+        if name in otp_applications:
+            # Known OTP application - convert to prelude target
+            return "prelude//erlang/applications:{}".format(name)
+        else:
+            # Not a known OTP app - might be a typo or user forgot the ":"
+            fail('Unknown OTP application "{app}". If this is not supposed to be an OTP application, did you mean ":{app}"?'.format(app = name))
+    return name
+
+def _erlang_otp_application_impl(ctx: AnalysisContext) -> list[Provider]:
+    """virtual OTP application for referencing only"""
+
+    toolchain = get_toolchain(ctx)
+
+    return [
+        DefaultInfo(),
+        ErlangAppOrTestInfo(),
+        ErlangAppInfo(
+            name = ctx.attrs.name,
+            version = "dynamic",
+            beams = [],
+            includes = [],
+            dependencies = {},
+            code_path_tset = None,
+            start_dependencies = None,
+            include_dir = None,
+            virtual = True,
+            app_folder = toolchain.erts_toolchain_info.applications.get(ctx.attrs.name) if toolchain.erts_toolchain_info else None,
+        ),
+    ]
+
+_erlang_otp_application_rule = rule(
+    impl = _erlang_otp_application_impl,
+    attrs = {
+        "_toolchain": attrs.toolchain_dep(default = "toolchains//:erlang-default"),
+    },
+)
diff --git a/buck2/prelude/erlang/erlang_paths.bzl b/buck2/prelude/erlang/erlang_paths.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_paths.bzl
@@ -0,0 +1,103 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _basename_start_index(p: str) -> int:
+    last_sep = p.rfind("/")
+
+    # If there is no slash, then the basename starts at the beginning of the string,
+    # which doesn't require special handling, since we get an index of -1, add one, and
+    # get 0, i.e. the beginning of the string.
+    return last_sep + 1
+
+def strip_extension(p: str) -> str:
+    """Removes the extension of the file at the end of a path.
+
+    Args:
+      p: The path whose extension should be removed.
+    Returns:
+      The path without the extension
+    """
+    basename_start_index = _basename_start_index(p)
+    last_dot_in_basename = p.rfind(".", basename_start_index, None)
+
+    # If there is no dot or the only dot in the basename is at the front, then
+    # there is no extension.
+    if last_dot_in_basename <= 0:
+        return p
+
+    dot_distance_from_end = len(p) - last_dot_in_basename
+    return p[:-dot_distance_from_end]
+
+def basename_without_extension(p: str) -> str:
+    """
+    Args:
+      p: The path whose basename should be extracted.
+    Returns:
+      The path's basename without the extension
+    """
+    basename_start_index = _basename_start_index(p)
+    last_dot_in_basename = p.rfind(".", basename_start_index, None)
+
+    # If there is no dot or the only dot in the basename is at the front, then
+    # there is no extension.
+    if last_dot_in_basename <= 0:
+        return p
+
+    dot_distance_from_end = len(p) - last_dot_in_basename
+    return p[basename_start_index:-dot_distance_from_end]
+
+def split_basename(p: str) -> (str, str):
+    """Extracts the basename of a path, and returns the extension and the basename without the extension.
+    Args:
+      p: The path whose basename should be extracted.
+    Returns:
+      The path's basename without the extension, and the extension itself (including the leading dot)
+    """
+    basename_start_index = _basename_start_index(p)
+    last_dot_in_basename = p.rfind(".", basename_start_index, None)
+
+    # If there is no dot or the only dot in the basename is at the front, then
+    # there is no extension.
+    if last_dot_in_basename <= 0:
+        return (p, "")
+
+    dot_distance_from_end = len(p) - last_dot_in_basename
+    return (p[basename_start_index:-dot_distance_from_end], p[-dot_distance_from_end:])
+
+def get_extension(p: str) -> str:
+    """Gets the extension of the file at the end of a path.
+
+    Args:
+      p: The path whose extension should be found.
+    Returns:
+      Just the extension of file at the end of the path.
+    """
+    basename_start_index = _basename_start_index(p)
+    last_dot_in_basename = p.rfind(".", basename_start_index, None)
+
+    # If there is no dot or the only dot in the basename is at the front, then
+    # there is no extension.
+    if last_dot_in_basename <= 0:
+        return p
+
+    dot_distance_from_end = len(p) - last_dot_in_basename
+    return p[-dot_distance_from_end:]
+
+def has_extension(p: str, ext: str) -> bool:
+    """Determines whether the given path's file has the given extension.
+
+    Args:
+      p: The path whose extension should be checked.
+      ext: The extension to check for (including the leading '.').
+    Returns:
+      True, if the file at the end of a path has the given extension.
+    """
+    if ext.startswith(".") and (ext.find("/") == -1):
+        return p.endswith(ext)
+    else:
+        fail("Extension must start with a dot and not contain a slash: '{}'".format(ext))
diff --git a/buck2/prelude/erlang/erlang_release.bzl b/buck2/prelude/erlang/erlang_release.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_release.bzl
@@ -0,0 +1,570 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as type
+load(
+    ":erlang_application.bzl",
+    "StartDependencySet",
+    "StartSpec",
+    "StartType",
+    "build_apps_start_dependencies",
+)
+load(":erlang_build.bzl", "erlang_build")
+load(":erlang_dependencies.bzl", "ErlAppDependencies", "flatten_dependencies")
+load(
+    ":erlang_info.bzl",
+    "ErlangAppInfo",
+    "ErlangReleaseInfo",
+)
+load(
+    ":erlang_toolchain.bzl",
+    "Toolchain",  # @unused Used as type
+    "get_toolchain",
+)
+
+# Erlang Releases according to https://www.erlang.org/doc/design_principles/release_structure.html
+
+Release = record(
+    dir = Artifact,
+    # `bin/<name>` on its own, so a release that installs another's launcher does not take its tree
+    launcher = field(Artifact | None, None),
+    # what the release is assembled from that analysis already knows, by path from the release root
+    entries = dict[str, Artifact],
+)
+
+LauncherLines = record(
+    name = str,
+    head = list[str],
+    tail = list[str],
+)
+
+ReleaseConfig = record(
+    # the target the release is built for, only used to point failures at it
+    label = Label,
+    name = str,
+    version = str,
+    # the applications the release starts, in order, with the type each is started with, and
+    # together with their transitive dependencies what `lib/` is drawn from
+    applications = list[(Dependency, StartType)],
+    toolchain = Toolchain,
+    # the environment every toolchain invocation runs with, `None` for the toolchain's own
+    os_env = field(dict[str, str] | None, None),
+    include_erts = bool,
+    is_executable = bool,
+    generate_default_bootscript = bool,
+    default_bootscript_name = str,
+    bootscript_builders = dict[str, cmd_args],
+    extra_bootscript_builder_args = list[ArgLike],
+    # the config files the launcher hands the emulator, in the order they are applied, so a later
+    # one overrides an earlier one. Each is a path from the release root without the `.config`
+    # extension, the form `-config` names a file with, and has to be part of the release.
+    config_paths = list[str],
+    # artifacts to install, mapping the directory they go into, from the release root, to their contents
+    overlays = dict[str, list[Artifact]],
+    # artifacts to install, by their path from the release root, that the release does not build itself
+    extra_entries = field(dict[str, Artifact], {}),
+)
+
+def erlang_release_impl(ctx: AnalysisContext) -> list[Provider]:
+    config = _release_config(ctx)
+
+    release = build_release(ctx.actions, config)
+    providers = [DefaultInfo(default_output = release.dir), ErlangReleaseInfo(name = config.name)]
+
+    if config.is_executable:
+        # the launcher reaches the rest of the release through relative symlinks, so running it
+        # needs the whole tree materialised, not just `bin/<name>`
+        launcher = release.dir.project(_launcher_path(config)).with_associated_artifacts([release.dir])
+        providers.append(RunInfo(cmd_args(launcher)))
+
+    return providers
+
+def _release_config(ctx: AnalysisContext) -> ReleaseConfig:
+    applications = _applications(ctx)
+    toolchain = get_toolchain(ctx)
+    overlays = {
+        target: [artifact for dep in deps for artifact in dep[DefaultInfo].default_outputs + dep[DefaultInfo].other_outputs]
+        for target, deps in ctx.attrs.overlays.items()
+    }
+
+    # an `erlang_release` is configured with the one `sys.config` the OTP layout gives it
+    sys_config = paths.join("releases", ctx.attrs.version, "sys")
+    config_paths = [sys_config] if sys_config + ".config" in _overlay_paths(overlays) else []
+
+    return ReleaseConfig(
+        label = ctx.label,
+        name = ctx.attrs.release_name if ctx.attrs.release_name else ctx.attrs.name,
+        version = ctx.attrs.version,
+        applications = applications,
+        toolchain = toolchain,
+        os_env = getattr(ctx.attrs, "os_env", None),
+        include_erts = ctx.attrs.include_erts,
+        is_executable = ctx.attrs.is_executable,
+        generate_default_bootscript = ctx.attrs.generate_default_bootscript,
+        default_bootscript_name = ctx.attrs.default_bootscript_name,
+        bootscript_builders = {script_name: builder[RunInfo].args for script_name, builder in ctx.attrs.bootscript_builders.items()},
+        extra_bootscript_builder_args = ctx.attrs.extra_bootscript_builder_args,
+        config_paths = config_paths,
+        overlays = overlays,
+    )
+
+def _applications(ctx: AnalysisContext) -> list[(Dependency, StartType)]:
+    """Extract the applications, with their start type, from the `applications` field, order preserving"""
+    applications = []
+    for dep in ctx.attrs.applications:
+        if type(dep) == "tuple":
+            applications.append((dep[0], StartType(dep[1])))
+        else:
+            applications.append((dep, StartType("permanent")))
+    return applications
+
+def build_release(actions: AnalysisActions, config: ReleaseConfig) -> Release:
+    """Build an OTP release, returning the release root.
+
+    The versioned parts of the layout, `erts-<version>` and `lib/<application>-<version>`, are laid
+    out by a dynamic action: the versions come from the toolchain's OTP rather than from analysis.
+    """
+    _validate_include_erts(config)
+    _validate_is_executable(config)
+
+    all_apps = flatten_dependencies([app for app, _ in config.applications])
+    own_apps = _own_applications(all_apps)
+    otp_apps = _otp_applications(config, all_apps) if config.include_erts else {}
+    erts_toolchain_info = config.toolchain.erts_toolchain_info
+
+    if erts_toolchain_info == None:
+        lib_dir = actions.symlinked_dir(paths.join(erlang_build.utils.BUILD_DIR, "lib"), own_apps, has_content_based_path = False)
+    else:
+        lib_dir = actions.declare_output(paths.join(erlang_build.utils.BUILD_DIR, "lib"), dir = True, has_content_based_path = False)
+        actions.dynamic_output_new(
+            _assemble_lib_dir(
+                otp_apps = otp_apps,
+                out = lib_dir.as_output(),
+                own_apps = own_apps,
+                versions = erts_toolchain_info.versions,
+            )
+        )
+
+    entries = {"lib": lib_dir}
+    entries.update(_build_boot_scripts(actions, config, lib_dir))
+    entries.update(_build_overlays(config.overlays))
+    entries.update(_build_release_variables(actions, config))
+
+    for entry, artifact in config.extra_entries.items():
+        if entry in entries:
+            fail("%s is given `%s` to install, which its own release builds" % (str(config.label), entry))
+        entries[entry] = artifact
+
+    launcher = _build_launcher(config, entries)
+    if launcher != None and _launcher_path(config) in entries:
+        fail("the launcher of %s is installed at %s, which the release already contains" % (str(config.label), _launcher_path(config)))
+
+    launcher_file = None
+    if launcher != None:
+        launcher_file = actions.declare_output(paths.join(erlang_build.utils.BUILD_DIR, "launcher", launcher.name), has_content_based_path = False)
+
+    if erts_toolchain_info == None:
+        release_dir = actions.symlinked_dir(config.name, entries, has_content_based_path = False)
+    else:
+        release_dir = actions.declare_output(config.name, dir = True, has_content_based_path = False)
+        actions.dynamic_output_new(
+            _assemble_release(
+                entries = entries,
+                include_erts = config.include_erts,
+                launcher = launcher,
+                launcher_out = launcher_file.as_output() if launcher_file != None else None,
+                otp_erts = erts_toolchain_info.erts,
+                out = release_dir.as_output(),
+                version = config.version,
+                versions = erts_toolchain_info.versions,
+            ),
+        )
+    return Release(dir = release_dir, entries = entries, launcher = launcher_file)
+
+def _assemble_lib_dir_impl(
+    actions: AnalysisActions, otp_apps: dict[str, Artifact], own_apps: dict[str, Artifact], versions: ArtifactValue, out: OutputArtifact
+) -> list[Provider]:
+    srcs = dict(own_apps)
+    if otp_apps:
+        app_versions = versions.read_json()["applications"]
+        for app, app_folder in otp_apps.items():
+            if app not in app_versions:
+                fail("the toolchain's OTP does not contain the application `%s`" % (app,))
+            srcs["{}-{}".format(app, app_versions[app])] = app_folder
+    actions.symlinked_dir(out, srcs)
+    return []
+
+_assemble_lib_dir = dynamic_actions(
+    impl = _assemble_lib_dir_impl,
+    attrs = {
+        "otp_apps": dynattrs.value(dict[str, Artifact]),
+        "out": dynattrs.output(),
+        "own_apps": dynattrs.value(dict[str, Artifact]),
+        "versions": dynattrs.artifact_value(),
+    },
+)
+
+def _assemble_release_impl(
+    actions: AnalysisActions,
+    entries: dict[str, Artifact],
+    include_erts: bool,
+    launcher: LauncherLines | None,
+    launcher_out: OutputArtifact | None,
+    otp_erts: Artifact,
+    version: str,
+    versions: ArtifactValue,
+    out: OutputArtifact,
+) -> list[Provider]:
+    otp = versions.read_json()
+    erts_dir = "erts-{}".format(otp["erts_version"])
+
+    srcs = dict(entries)
+    if include_erts:
+        srcs[erts_dir] = otp_erts.project(erts_dir)
+
+        start_erl_data = actions.declare_output("start_erl.data", has_content_based_path = False)
+        actions.write(start_erl_data, "{} {}\n".format(otp["erts_version"], version))
+        srcs[paths.join("releases", "start_erl.data")] = start_erl_data
+
+    if launcher != None:
+        lines = launcher.head + ['BINDIR="$ROOTDIR/{}/bin"'.format(erts_dir)] + launcher.tail
+        srcs[paths.join("bin", launcher.name)] = actions.write(launcher_out, lines, is_executable = True)
+
+    actions.symlinked_dir(out, srcs)
+    return []
+
+_assemble_release = dynamic_actions(
+    impl = _assemble_release_impl,
+    attrs = {
+        "entries": dynattrs.value(dict[str, Artifact]),
+        "include_erts": dynattrs.value(bool),
+        "launcher": dynattrs.value(LauncherLines | None),
+        "launcher_out": dynattrs.option(dynattrs.output()),
+        "otp_erts": dynattrs.value(Artifact),
+        "out": dynattrs.output(),
+        "version": dynattrs.value(str),
+        "versions": dynattrs.artifact_value(),
+    },
+)
+
+def build_lib_dir(ctx: AnalysisContext, all_apps: ErlAppDependencies) -> dict[str, Artifact]:
+    """Build lib dir according to OTP specifications.
+
+    .. seealso:: `OTP Design Principles Release Structure <https://www.erlang.org/doc/design_principles/release_structure.html>`_
+    """
+    lib_dir = ctx.actions.symlinked_dir(
+        paths.join(erlang_build.utils.BUILD_DIR, "lib"),
+        _own_applications(all_apps),
+        has_content_based_path = False,
+    )
+    return {"lib": lib_dir}
+
+def _otp_applications(config: ReleaseConfig, all_apps: ErlAppDependencies) -> dict[str, Artifact]:
+    applications = {
+        "erts": config.toolchain.erts_toolchain_info.applications["erts"],
+    }
+    for dep in all_apps.values():
+        if ErlangAppInfo not in dep or not dep[ErlangAppInfo].virtual:
+            continue
+        app_info = dep[ErlangAppInfo]
+        if app_info.app_folder == None:
+            fail("%s needs the OTP application `%s`, which the toolchain's OTP does not ship" % (str(config.label), app_info.name))
+        applications[app_info.name] = app_info.app_folder
+    return applications
+
+def _own_applications(all_apps: ErlAppDependencies) -> dict[str, Artifact]:
+    return {
+        (dep[ErlangAppInfo].name + "-" + dep[ErlangAppInfo].version): dep[ErlangAppInfo].app_folder
+        for dep in all_apps.values()
+        if ErlangAppInfo in dep and not dep[ErlangAppInfo].virtual
+    }
+
+def _build_boot_scripts(actions: AnalysisActions, config: ReleaseConfig, lib_dir: Artifact) -> dict[str, Artifact]:
+    link_spec = {}
+
+    if config.generate_default_bootscript:
+        maybe_default_boot_script = _build_default_boot_scripts(actions, config, lib_dir)
+        link_spec.update(maybe_default_boot_script)
+
+    # write applications spec to file
+    data = [(app[ErlangAppInfo].name, start_type.value) for app, start_type in config.applications]
+    spec_file = actions.write_json(
+        paths.join(erlang_build.utils.BUILD_DIR, "bootscripts", "applications_json"),
+        data,
+        has_content_based_path = False,
+    )
+
+    for script_name, builder in config.bootscript_builders.items():
+        custom_boot_script_spec = _build_custom_boot_scripts(actions, config, spec_file, script_name, builder, lib_dir)
+        link_spec.update(custom_boot_script_spec)
+
+    return link_spec
+
+def _build_default_boot_scripts(actions: AnalysisActions, config: ReleaseConfig, lib_dir: Artifact) -> dict[str, Artifact]:
+    """Build Name.rel, start.script, and start.boot in the release folder.
+
+    Boot scripts are always generated regardless of include_erts setting.
+    When include_erts=False (default), OTP applications use runtime version discovery.
+    When include_erts=True, explicit versions from the toolchain are used and additional
+    no_dot_erlang boot scripts are generated for the self-contained release.
+    """
+    release_name = config.name
+
+    root_apps_names = [app[ErlangAppInfo].name for app, _ in config.applications]
+    start_dependencies = build_apps_start_dependencies(actions, config.applications)
+
+    root_set = actions.tset(
+        StartDependencySet,
+        value = StartSpec(
+            name = "__ignored__",
+            version = config.version,
+            start_type = StartType("permanent"),
+            resolved = False,
+        ),
+        children = start_dependencies,
+    )
+
+    reverse_start_order = list(root_set.traverse())
+    reverse_start_order.pop(0)
+
+    seen = set()
+    release_applications = []
+    root_apps_spec = {}
+    for spec in reverse_start_order[::-1]:
+        if spec.name in seen:
+            continue
+        seen.add(spec.name)
+
+        app_spec = {
+            "name": spec.name,
+            "resolved": spec.resolved,
+            "type": spec.start_type.value,
+            "version": spec.version,
+        }
+
+        if spec.name in root_apps_names:
+            root_apps_spec[spec.name] = app_spec
+        else:
+            release_applications.append(app_spec)
+    for app_name in root_apps_names[::-1]:
+        release_applications.append(root_apps_spec[app_name])
+
+    data = {
+        "apps": release_applications[::-1],
+        "lib_dir": lib_dir,
+        "name": release_name,
+        "version": config.version,
+    }
+
+    spec_file = actions.write_json(paths.join(erlang_build.utils.BUILD_DIR, "boot_script_spec.json"), data, with_inputs = True, has_content_based_path = False)
+
+    scripts_dir = actions.declare_output(erlang_build.utils.BUILD_DIR, "scripts", dir = True, has_content_based_path = False)
+
+    _run_with_env(
+        actions,
+        config,
+        cmd_args(config.toolchain.boot_script_builder, spec_file, scripts_dir.as_output()),
+        category = "build_boot_script",
+        identifier = release_name,
+    )
+
+    # Always include the standard boot scripts
+    boot_files = [
+        "{}.rel".format(release_name),
+        "start.script",
+        "start.boot",
+    ]
+
+    # Only include no_dot_erlang boot scripts for self-contained releases with bundled ERTS
+    if config.include_erts:
+        boot_files.extend([
+            "no_dot_erlang.script",
+            "no_dot_erlang.boot",
+        ])
+
+    result = {paths.join("releases", config.version, file): scripts_dir.project(file) for file in boot_files}
+
+    # Place OTP's boot files in bin/ so erl can find them at ROOTDIR/bin/.
+    # When erl runs from bundled ERTS (erts-VSN/bin/erl), it resolves ROOTDIR
+    # to the release root and looks for bin/<name>.boot for boot files.
+    # These are extracted once per toolchain (not per release) and contain only
+    # kernel+stdlib, so that:
+    #   - `erl` bare gives a clean shell (uses bin/start.boot)
+    #   - `erl -boot no_dot_erlang` works for ectl and other tools
+    # mini_start explicitly uses releases/VERSION/start.boot for service startup.
+    if config.include_erts:
+        result[paths.join("bin", "start.boot")] = config.toolchain.erts_toolchain_info.otp_start_boot
+        result[paths.join("bin", "no_dot_erlang.boot")] = config.toolchain.erts_toolchain_info.otp_no_dot_erlang_boot
+
+    return result
+
+def _build_custom_boot_scripts(
+    actions: AnalysisActions, config: ReleaseConfig, spec_file: Artifact, script_name: str, builder: cmd_args, lib_dir: Artifact
+) -> dict[str, Artifact]:
+    boot_script = actions.declare_output(paths.join(erlang_build.utils.BUILD_DIR, "bootscripts", script_name), has_content_based_path = False)
+    raw_script_name = paths.replace_extension(script_name, ".script")
+    raw_script = actions.declare_output(paths.join(erlang_build.utils.BUILD_DIR, "bootscripts", raw_script_name), has_content_based_path = False)
+
+    _run_with_env(
+        actions,
+        config,
+        cmd_args(
+            builder,
+            spec_file,
+            lib_dir,
+            boot_script.as_output(),
+            raw_script.as_output(),
+            config.extra_bootscript_builder_args,
+        ),
+        category = "build_custom_boot_script",
+        identifier = script_name,
+    )
+
+    return {
+        paths.join("releases", config.version, script_name): boot_script,
+        paths.join("releases", config.version, raw_script_name): raw_script,
+    }
+
+def _build_overlays(overlays: dict[str, list[Artifact]]) -> dict[str, Artifact]:
+    installed = {}
+    for target, artifacts in overlays.items():
+        for artifact in artifacts:
+            link_path = _overlay_path(target, artifact)
+            if link_path in installed:
+                fail("multiple overlays defined for the same location: %s" % (link_path,))
+            installed[link_path] = artifact
+    return installed
+
+def _overlay_paths(overlays: dict[str, list[Artifact]]) -> list[str]:
+    return [_overlay_path(target, artifact) for target, artifacts in overlays.items() for artifact in artifacts]
+
+def _overlay_path(target: str, artifact: Artifact) -> str:
+    return paths.normalize(paths.join(target, artifact.basename))
+
+def _build_release_variables(actions: AnalysisActions, config: ReleaseConfig) -> dict[str, Artifact]:
+    release_name = config.name
+
+    short_path = "bin/release_variables"
+    release_variables = actions.declare_output(
+        erlang_build.utils.BUILD_DIR,
+        "release_variables",
+        has_content_based_path = False,
+    )
+
+    spec_file = actions.write_json(
+        paths.join(erlang_build.utils.BUILD_DIR, "relvars.json"),
+        {
+            "REL_NAME": release_name,
+            "REL_VSN": config.version,
+        },
+        has_content_based_path = False,
+    )
+
+    _run_with_env(
+        actions,
+        config,
+        cmd_args(config.toolchain.release_variables_builder, spec_file, release_variables.as_output()),
+        category = "build_release_variables",
+        identifier = release_name,
+    )
+    return {short_path: release_variables}
+
+def _build_launcher(config: ReleaseConfig, release_files: dict[str, Artifact]) -> LauncherLines | None:
+    """Generate bin/<release_name>, a launcher booting the release with the bundled emulator.
+
+    Everything the emulator is told is resolved here rather than at runtime: the erts version, so
+    the launcher addresses `erts-<version>` directly, and the boot script, `vm.args` and the config
+    files, so the launcher does not depend on what it was invoked as. Every path is relative to
+    ROOTDIR, so the release stays relocatable. The tool name is still taken from the launcher's own
+    basename, so one release can serve several tools that differ only in the arguments they get.
+    """
+    if not config.is_executable:
+        return None
+
+    boot_script = paths.join("releases", config.version, config.default_bootscript_name)
+    vm_args = boot_script + ".vm.args"
+
+    for config_path in config.config_paths:
+        if config_path + ".config" not in release_files:
+            fail("%s is configured with `%s.config`, which none of its overlays installs" % (str(config.label), config_path))
+
+    if boot_script + ".boot" not in release_files:
+        fail("%s boots with `%s.boot`, which the release does not contain" % (str(config.label), boot_script))
+
+    head = [
+        "#!/usr/bin/env bash",
+        "set -euo pipefail",
+        # macOS has no `readlink -f`, so the symlink chain is followed one hop at a time
+        'SELF="${BASH_SOURCE[0]}"',
+        "HOPS=0",
+        "while :; do",
+        '    ROOTDIR="$(cd -P "$(dirname "$SELF")/.." && pwd)"',
+        '    if [ -e "$ROOTDIR/{}.boot" ]; then'.format(boot_script),
+        "        break",
+        "    fi",
+        '    if [ ! -L "$SELF" ]; then',
+        '        echo "$0: cannot find the release root above $SELF" >&2',
+        "        exit 1",
+        "    fi",
+        "    HOPS=$((HOPS + 1))",
+        "    if [ $HOPS -gt 40 ]; then",
+        '        echo "$0: too many symlink hops resolving release root" >&2',
+        "        exit 1",
+        "    fi",
+        '    SELFDIR="$(cd -P "$(dirname "$SELF")" && pwd)"',
+        '    SELF="$(readlink "$SELF")"',
+        '    case "$SELF" in',
+        "        /*) ;;",
+        '        *) SELF="$SELFDIR/$SELF" ;;',
+        "    esac",
+        "done",
+    ]
+    tail = [
+        'TOOL="$(basename "$0")"',
+        "export ROOTDIR BINDIR",
+        'exec "$BINDIR/erlexec" \\',
+        '    -boot "$ROOTDIR/{}" \\'.format(boot_script),
+    ]
+    if vm_args in release_files:
+        tail.append('    -args_file "$ROOTDIR/{}" \\'.format(vm_args))
+    for config_path in config.config_paths:
+        tail.append('    -config "$ROOTDIR/{}" \\'.format(config_path))
+    tail += [
+        '    -extra "$TOOL" ${1+"$@"}',
+        "",
+    ]
+
+    return LauncherLines(name = config.name, head = head, tail = tail)
+
+def _launcher_path(config: ReleaseConfig) -> str:
+    return paths.join("bin", config.name)
+
+def _run_with_env(actions: AnalysisActions, config: ReleaseConfig, args: cmd_args, **kwargs):
+    """run interface that injects the environment the release's toolchain invocations run with"""
+    env = config.os_env if config.os_env != None else config.toolchain.env
+
+    if "env" in kwargs:
+        kwargs["env"].update(env)
+    else:
+        kwargs["env"] = env
+
+    actions.run(args, **kwargs)
+
+def _validate_is_executable(config: ReleaseConfig) -> None:
+    """Validate that a runnable release ships the emulator its launcher runs"""
+    if config.is_executable and not config.include_erts:
+        fail("is_executable = True requires include_erts = True, the launcher runs the emulator from the release's own erts folder: %s" % (str(config.label),))
+
+def _validate_include_erts(config: ReleaseConfig) -> None:
+    """Validate that a release bundling the emulator has a toolchain to take it from"""
+    if config.include_erts and config.toolchain.erts_toolchain_info == None:
+        fail(
+            "include_erts = True requires the toolchain `%s` to set erts_toolchain_info, there is no ERTS nor OTP applications to take from it otherwise: %s"
+            % (config.toolchain.name, str(config.label))
+        )
diff --git a/buck2/prelude/erlang/erlang_shell.bzl b/buck2/prelude/erlang/erlang_shell.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_shell.bzl
@@ -0,0 +1,99 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":erlang_build.bzl", "erlang_build")
+load(":erlang_dependencies.bzl", "erlang_deps_rule")
+load(":erlang_info.bzl", "ErlangDependencyInfo", "code_path_args")
+load(":erlang_toolchain.bzl", "get_toolchain")
+
+def _build_run_info(
+    ctx: AnalysisContext,
+    *,
+    dep_info: ErlangDependencyInfo,
+    additional_code_path: cmd_args,
+    additional_shell_deps: list[Dependency] = [],
+    additional_args: [cmd_args, None] = None,
+) -> Promise:
+    """Builds an Erlang shell with the dependencies and additional code paths available."""
+    shell_dep_info = ctx.actions.anon_target(erlang_deps_rule, {"deps": additional_shell_deps + ctx.attrs.shell_libs})
+
+    return shell_dep_info.promise.map(
+        lambda shell_dep_info: _do_build_run_info(
+            ctx,
+            dep_info,
+            additional_code_path,
+            additional_args,
+            shell_dep_info[ErlangDependencyInfo],
+        )
+    )
+
+def _do_build_run_info(
+    ctx: AnalysisContext,
+    dep_info: ErlangDependencyInfo,
+    additional_code_path: cmd_args,
+    additional_args: [cmd_args, None],
+    shell_dep_info: ErlangDependencyInfo,
+) -> RunInfo:
+    tools = get_toolchain(ctx).otp_binaries
+    if len(tools.erl.inputs) != 0:
+        erl = cmd_args(cmd_args(tools.erl, delimiter = " "), format = '"${REPO_ROOT}"/{}')
+    else:
+        erl = cmd_args(cmd_args(tools.erl, delimiter = " "), format = "{}")
+    erl_args = cmd_args("exec", erl, delimiter = " \\\n")
+
+    # add paths
+    code_path = cmd_args(
+        code_path_args(dep_info.code_path_tset),
+        additional_code_path,
+        code_path_args(shell_dep_info.code_path_tset),
+        prepend = "-pa",
+        absolute_prefix = '"${REPO_ROOT}"/',
+    )
+    erl_args.add(code_path)
+
+    # add configs
+    config_files = _shell_config_files(ctx)
+    erl_args.add(cmd_args(config_files, prepend = "-config", absolute_prefix = '"${REPO_ROOT}"/'))
+
+    # add extra args
+    if additional_args:
+        erl_args.add(additional_args)
+    erl_args.add('"$@"')
+
+    start_shell_content = cmd_args(
+        "#!/usr/bin/env bash",
+        "export REPO_ROOT=$(buck2 root --kind=project)",
+        erl_args,
+        "",
+    )
+
+    shell_script, _ = ctx.actions.write(
+        "start_shell.sh",
+        start_shell_content,
+        is_executable = True,
+        with_inputs = True,
+        allow_args = True,
+        has_content_based_path = False,
+    )
+
+    return RunInfo(shell_script)
+
+def _shell_config_files(ctx: AnalysisContext) -> list[Artifact]:
+    config_files = []
+    for config_dep in ctx.attrs.shell_configs:
+        for artifact in config_dep[DefaultInfo].default_outputs:
+            if erlang_build.utils.is_config(artifact):
+                config_files.append(artifact)
+        for artifact in config_dep[DefaultInfo].other_outputs:
+            if erlang_build.utils.is_config(artifact):
+                config_files.append(artifact)
+    return config_files
+
+erlang_shell = struct(
+    build_run_info = _build_run_info,
+)
diff --git a/buck2/prelude/erlang/erlang_tests.bzl b/buck2/prelude/erlang/erlang_tests.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_tests.bzl
@@ -0,0 +1,328 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//tests:re_utils.bzl", "get_re_executors_from_props")
+load(
+    ":erlang_build.bzl",
+    "erlang_build",
+    "module_name",
+)
+load(":erlang_dependencies.bzl", "erlang_deps_rule")
+load(":erlang_info.bzl", "CodePathEntry", "CodePathTSet", "ErlangAppInfo", "ErlangAppOrTestInfo", "ErlangDependencyInfo", "ErlangTestInfo", "code_path_args")
+load(":erlang_otp_application.bzl", "normalize_application")
+load(":erlang_paths.bzl", "basename_without_extension")
+load(":erlang_shell.bzl", "erlang_shell")
+load(
+    ":erlang_toolchain.bzl",
+    "get_toolchain",
+)
+load(
+    ":erlang_utils.bzl",
+    "file_mapping",
+    "preserve_structure",
+)
+
+def erlang_tests_macro(
+    erlang_app_rule,
+    erlang_test_rule,
+    suites: list[str],
+    deps: list[str] = [],
+    resources: list[str] = [],
+    srcs: list[str] = [],
+    prefix: str | None = None,
+    generated_app_labels: list[str] = [],
+    erl_opts: list[str] | Select | None = None,
+    **common_attributes,
+) -> None:
+    """
+    Generate multiple erlang_test targets based on the `suites` field.
+    Also adds the default 'config' and 'deps' from the buck2 config.
+    The macro also produces and adds
+    resource targets for files in the suite associated <suitename>_data folder.
+    """
+    if not suites:
+        return
+
+    deps = [normalize_application(dep) for dep in deps]
+
+    if srcs:
+        # There is no "good name" for the application
+        # We create one using the first suite from the list
+        suite_name = basename_without_extension(suites[0])
+        srcs_app = "{}_app".format(suite_name)
+        app_deps = [dep for dep in deps if not dep.endswith("_SUITE")]
+        erlang_app_rule(
+            name = srcs_app,
+            srcs = srcs,
+            labels = generated_app_labels,
+            applications = app_deps,
+            erl_opts = erl_opts,
+        )
+        deps.append(":{}".format(srcs_app))
+
+    for suite in suites:
+        # forward resources and deps fields and generate erlang_test target
+        suite_name = normalize_suite_name(basename_without_extension(suite))
+        if not suite_name.endswith("_SUITE"):
+            fail("erlang_tests target only accept suite as input, found " + suite_name)
+
+        # check if there is a data folder and add it as resource if existing
+        data_dir_name = "{}_data".format(suite_name)
+        suite_resource = resources
+        data_target = generate_file_map_target(suite, prefix, data_dir_name)
+        if data_target != None:
+            suite_resource = list(suite_resource)  # copy
+            suite_resource.append(data_target)
+
+        if prefix != None:
+            suite_name = "{}_{}".format(prefix, suite_name)
+
+        # forward resources and deps fields and generate erlang_test target
+        erlang_test_rule(name = suite_name, suite = suite, deps = deps, resources = suite_resource, erl_opts = erl_opts, **common_attributes)
+
+def normalize_suite_name(suite_name: str) -> str:
+    return suite_name.split(":")[-1]
+
+default_test_args = cmd_args(
+    "-mode",
+    "minimal",
+    "-noinput",
+    "-noshell",
+    "+A0",
+    "+S1:1",
+    "+sbtu",
+    "-run",
+    "test_binary",  # provided by ctx.attr._test_binary_lib
+    "main",
+)
+
+def erlang_test_impl(ctx: AnalysisContext) -> Promise:
+    # collect all dependencies
+    dep_info_rule = (erlang_deps_rule, {"deps": ctx.attrs.deps + [ctx.attrs._test_binary_lib]})
+    binary_lib_dep_info_rule = (erlang_deps_rule, {"deps": [ctx.attrs._test_binary_lib]})
+
+    dep_infos = ctx.actions.anon_targets([dep_info_rule, binary_lib_dep_info_rule])
+
+    return dep_infos.promise.map(
+        lambda dep_infos: _build_erlang_test(
+            ctx,
+            dep_infos[0][ErlangDependencyInfo],
+            dep_infos[1][ErlangDependencyInfo],
+        )
+    )
+
+def _build_erlang_test(ctx: AnalysisContext, dep_info: ErlangDependencyInfo, binary_lib_dep_info: ErlangDependencyInfo) -> Promise:
+    toolchain = get_toolchain(ctx)
+    tools = toolchain.otp_binaries
+
+    # prepare build environment
+    build_environment = erlang_build.prepare_build_environment(dep_info, peek_private_includes = True)
+
+    # Config files for ct
+    config_files = [config_file[DefaultInfo].default_outputs[0] for config_file in ctx.attrs.config_files]
+
+    cmd = cmd_args([trampoline[RunInfo] for trampoline in ctx.attrs._trampolines])
+    cmd.add(tools.erl, default_test_args)
+
+    app_folders = [dep[ErlangAppInfo].app_folder for dep in binary_lib_dep_info.dependencies.values() if not dep[ErlangAppInfo].virtual]
+    cmd.add(cmd_args(app_folders, format = "{}/ebin", prepend = "-pa"))
+    cmd.add("--")
+
+    suite = ctx.attrs.suite
+    suite_name = module_name(suite)
+    hermetic_src_dir = ctx.actions.symlinked_dir(paths.join(erlang_build.utils.BUILD_DIR, "src"), {suite.basename: suite}, has_content_based_path = False)
+
+    erlang_build.build_steps.generate_beam_artifacts(
+        ctx,
+        toolchain,
+        build_environment,
+        "tests",
+        [suite],
+        hermetic_src_dir,
+    )
+
+    beam = build_environment.beams["tests"][suite_name]
+    ebin_dir = paths.dirname(beam.short_path)
+
+    suite_data = paths.join(ebin_dir, suite_name + "_data")
+    data_dir = _build_resource_dir(ctx, ctx.attrs.resources, suite_data)
+
+    output_dir = link_output(ctx, beam, data_dir)
+    test_info_file = _write_test_info_file(
+        ctx = ctx,
+        test_suite = suite_name,
+        dep_info = dep_info,
+        test_dir = output_dir,
+        config_files = config_files,
+        erl_cmd = toolchain.otp_binaries.erl,
+        raw_target = str(ctx.label.raw_target()) if ctx.label else "",
+        inner_trampolines = [trampoline[RunInfo].args for trampoline in ctx.attrs._inner_trampolines],
+    )
+
+    # Everything that comes after the `-extra` will be interpreted by the test_binary
+    cmd.add("-extra")
+    cmd.add(cmd_args(test_info_file, format = "--test-info-file={}"))
+
+    default_info = _build_default_info(dep_info, output_dir)
+
+    # NB. We can't use `quote="shell"` since we need $REPO_ROOT to be expanded by the shell.
+    # So we wrap everything in extra double-quotes to protect from spaces in the path
+    test_info_file_arg = cmd_args(test_info_file, format = '"<<\\"${REPO_ROOT}/{}\\">>"')
+
+    additional_shell_args = cmd_args(
+        cmd_args("-test_cli_lib", "test_info_file", test_info_file_arg, delimiter = " "),
+        cmd_args("-eval", "test_cli_lib:start()", quote = "shell"),
+        "-noshell",
+    )
+
+    run_info = erlang_shell.build_run_info(
+        ctx,
+        dep_info = dep_info,
+        additional_code_path = cmd_args(output_dir),
+        additional_shell_deps = [ctx.attrs._cli_lib],
+        additional_args = additional_shell_args,
+    )
+
+    # Setup RE executors based on the `remote_execution` param.
+    re_executors = get_re_executors_from_props(ctx)
+    external_runner_info = ExternalRunnerTestInfo(
+        type = "erlang_test",
+        command = [cmd],
+        env = ctx.attrs.env,
+        labels = ctx.attrs.labels,
+        contacts = ctx.attrs.contacts,
+        run_from_project_root = True,
+        use_project_relative_paths = True,
+        default_executor = re_executors.default_executor,
+        executor_overrides = re_executors.executor_overrides,
+    )
+    test_info = ErlangTestInfo(
+        name = suite_name,
+        dependencies = dep_info.dependencies,
+        code_path_tset = ctx.actions.tset(
+            CodePathTSet,
+            value = CodePathEntry(dir = output_dir, ebin = False),
+            children = [dep_info.code_path_tset],
+        ),
+        output_dir = output_dir,
+    )
+
+    return run_info.map(
+        lambda run_info: [
+            default_info,
+            run_info,
+            ErlangAppOrTestInfo(),
+            external_runner_info,
+            test_info,
+        ]
+    )
+
+# Copied from erlang_application.
+def _build_default_info(dep_info: ErlangDependencyInfo, output_dir: Artifact) -> Provider:
+    """generate default_outputs and DefaultInfo provider"""
+
+    # We depend on the code path of all dependencies to force them to be compiled
+    # and emit errors when users compile just this one application
+    return DefaultInfo(default_output = output_dir, other_outputs = [code_path_args(dep_info.code_path_tset)])
+
+def _write_test_info_file(
+    ctx: AnalysisContext,
+    test_suite: str,
+    dep_info: ErlangDependencyInfo,
+    test_dir: Artifact,
+    config_files: list[Artifact],
+    erl_cmd: [cmd_args, Artifact],
+    raw_target: str,
+    inner_trampolines: list[cmd_args],
+) -> WriteJsonCliArgs:
+    tests_info = {
+        "artifact_annotation_mfa": ctx.attrs._artifact_annotation_mfa,
+        "common_app_env": ctx.attrs.common_app_env,
+        "config_files": config_files,
+        "ct_opts": ctx.attrs._ct_opts,
+        "dependencies": code_path_args(dep_info.code_path_tset),
+        "erl_cmd": erl_cmd,
+        "extra_ct_hooks": ctx.attrs.extra_ct_hooks,
+        "extra_flags": ctx.attrs.extra_erl_flags,
+        "providers": ctx.attrs._providers,
+        "raw_target": raw_target,
+        "test_dir": test_dir,
+        "test_suite": test_suite,
+        "trampolines": inner_trampolines,
+    }
+    test_info_file = ctx.actions.declare_output("tests_info", has_content_based_path = False)
+    return ctx.actions.write_json(test_info_file, tests_info, with_inputs = True)
+
+def _build_resource_dir(ctx: AnalysisContext, resources: list, target_dir: str) -> [Artifact, None]:
+    """build mapping for suite data directory
+
+    generating the necessary mapping information for the suite data directory
+    the resulting mapping can be used directly to symlink
+    """
+    if not resources:
+        return None
+
+    include_symlinks = {}
+    for resource in resources:
+        files = resource[DefaultInfo].default_outputs
+        for file in files:
+            if file.short_path in include_symlinks:
+                fail("duplicate resource file: `{}`, defined in {} and {}".format(file.short_path, include_symlinks[file.short_path], file))
+            else:
+                include_symlinks[file.short_path] = file
+    return ctx.actions.symlinked_dir(
+        target_dir,
+        include_symlinks,
+        has_content_based_path = False,
+    )
+
+def link_output(ctx: AnalysisContext, beam: Artifact, data_dir: [Artifact, None]) -> Artifact:
+    """Link the data_dirs and the test_suite beam in a single output folder."""
+    link_spec = {
+        beam.basename: beam,
+        ctx.attrs.suite.basename: ctx.attrs.suite,
+    }
+    if data_dir:
+        link_spec[data_dir.basename] = data_dir
+    return ctx.actions.symlinked_dir(ctx.attrs.name, link_spec, has_content_based_path = False)
+
+def generate_file_map_target(suite: str, prefix: str | None, dir_name: str) -> str | None:
+    suite_dir = paths.dirname(suite)
+    suite_name = paths.basename(suite)
+    suite_path = paths.join(suite_dir, dir_name)
+
+    if is_target(suite):
+        files = []
+    else:
+        files = glob([paths.join(suite_path, "**")])
+
+    if len(files):
+        if prefix != None:
+            target_suffix = "{}_{}".format(prefix, suite_name)
+        else:
+            target_suffix = suite_name
+
+        # generate target for data dir
+        mapping_name = "{}-{}".format(dir_name, target_suffix)
+        file_mapping(
+            name = mapping_name,
+            mapping = preserve_structure(
+                path = suite_path,
+            ),
+        )
+        return ":" + mapping_name
+
+    return None
+
+def is_target(suite: str) -> bool:
+    if suite.startswith(":"):
+        return True
+    if suite.find("//") != -1:
+        return True
+    return False
diff --git a/buck2/prelude/erlang/erlang_toolchain.bzl b/buck2/prelude/erlang/erlang_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_toolchain.bzl
@@ -0,0 +1,324 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:paths.bzl",
+    "paths",
+)
+load(
+    ":erlang_error_handler.bzl",
+    "erlang_action_error_handler",
+)
+load(
+    ":erlang_info.bzl",
+    "ErlangOTPBinariesInfo",
+    "ErlangParseTransformInfo",
+    "ErlangToolchainInfo",
+    "ErtsToolchainInfo",
+    "Tool",
+    "Tools",
+)
+load(
+    ":erlang_paths.bzl",
+    "basename_without_extension",
+    "strip_extension",
+)
+
+Toolchain = ErlangToolchainInfo
+
+ToolchainUtillInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "app_src_script": provider_field(Artifact),
+        "appup_src_script": provider_field(Artifact),
+        "boot_script_builder": provider_field(Artifact),
+        "core_parse_transforms": provider_field(list[Dependency]),
+        "dependency_analyzer": provider_field(Artifact),
+        "dependency_finalizer": provider_field(Artifact),
+        "dependency_merger": provider_field(Artifact),
+        "escript_trampoline": provider_field(Artifact),
+        "escript_builder": provider_field(Artifact),
+        "release_variables_builder": provider_field(Artifact),
+        "utility_modules": provider_field(list[Artifact]),
+    },
+)
+
+def get_toolchain(ctx: AnalysisContext) -> Toolchain:
+    return ctx.attrs._toolchain[ErlangToolchainInfo]
+
+def _erlang_toolchain_impl(ctx: AnalysisContext) -> list[Provider]:
+    """rule for erlang toolchain"""
+
+    erl_opts = ctx.attrs.erl_opts
+    emu_flags = ctx.attrs.emu_flags
+
+    # backwards compat: options could be given as a string
+    if isinstance(erl_opts, str):
+        erl_opts = erl_opts.split()
+    if isinstance(emu_flags, str):
+        emu_flags = emu_flags.split()
+
+    # get otp binaries
+    binaries_info = ctx.attrs.otp_binaries[ErlangOTPBinariesInfo]
+    erl = cmd_args(binaries_info.erl, emu_flags)
+    erlc = cmd_args(binaries_info.erlc, hidden = binaries_info.erl)
+    escript = cmd_args(binaries_info.escript, hidden = binaries_info.erl)
+    otp_binaries = Tools(
+        erl = erl,
+        erlc = erlc,
+        escript = escript,
+    )
+
+    env = ctx.attrs.env
+    if emu_flags and "ERL_FLAGS" not in env:
+        env["ERL_FLAGS"] = " ".join(emu_flags)
+
+    # extract utility artefacts
+    utils = ctx.attrs.toolchain_utilities[ToolchainUtillInfo]
+
+    core_parse_transforms = _gen_parse_transforms(
+        ctx,
+        otp_binaries.erlc,
+        env,
+        utils.core_parse_transforms,
+    )
+
+    parse_transforms = _gen_parse_transforms(
+        ctx,
+        otp_binaries.erlc,
+        env,
+        ctx.attrs.parse_transforms,
+    )
+    intersection = [key for key in parse_transforms if key in core_parse_transforms]
+    if len(intersection):
+        fail("conflicting parse_transform with core parse_transform found: %s" % (repr(intersection),))
+
+    utility_modules = _gen_util_beams(ctx, env, utils.utility_modules, otp_binaries.erlc)
+
+    app_src_script = _gen_toolchain_script(ctx, env, utils.app_src_script, otp_binaries, utility_modules)
+    appup_src_script = _gen_toolchain_script(ctx, env, utils.appup_src_script, otp_binaries, utility_modules)
+    boot_script_builder = _gen_toolchain_script(ctx, env, utils.boot_script_builder, otp_binaries, utility_modules)
+    dependency_analyzer = _gen_toolchain_script(ctx, env, utils.dependency_analyzer, otp_binaries, utility_modules)
+    dependency_finalizer = _gen_toolchain_script(ctx, env, utils.dependency_finalizer, otp_binaries, utility_modules)
+    dependency_merger = _gen_toolchain_script(ctx, env, utils.dependency_merger, otp_binaries, utility_modules)
+    escript_builder = _gen_toolchain_script(ctx, env, utils.escript_builder, otp_binaries, utility_modules)
+    release_variables_builder = _gen_toolchain_script(ctx, env, utils.release_variables_builder, otp_binaries, utility_modules)
+
+    erts_toolchain_info = ctx.attrs.erts_toolchain_info[ErtsToolchainInfo] if ctx.attrs.erts_toolchain_info else None
+
+    return [
+        DefaultInfo(),
+        ErlangToolchainInfo(
+            name = ctx.attrs.name,
+            app_src_script = app_src_script,
+            appup_src_script = appup_src_script,
+            boot_script_builder = boot_script_builder,
+            dependency_analyzer = dependency_analyzer,
+            dependency_finalizer = dependency_finalizer,
+            dependency_merger = dependency_merger,
+            erl_opts = erl_opts,
+            env = ctx.attrs.env,
+            emu_flags = emu_flags,
+            escript_trampoline = utils.escript_trampoline,
+            escript_builder = escript_builder,
+            otp_binaries = otp_binaries,
+            release_variables_builder = release_variables_builder,
+            core_parse_transforms = core_parse_transforms,
+            parse_transforms = parse_transforms,
+            parse_transforms_filters = ctx.attrs.parse_transforms_filters,
+            utility_modules = utility_modules,
+            erts_toolchain_info = erts_toolchain_info,
+            error_handler = erlang_action_error_handler,
+        ),
+    ]
+
+def _gen_parse_transforms(ctx: AnalysisContext, erlc: Tool, env: dict[str, str], parse_transforms: list[Dependency]) -> dict[str, cmd_args]:
+    transforms = {}
+    for dep in parse_transforms:
+        src = dep[ErlangParseTransformInfo].source
+        extra = dep[ErlangParseTransformInfo].extra_files
+        module_name = basename_without_extension(src.basename)
+        if module_name in transforms:
+            fail("ambiguous global parse_transforms defined: %s", (module_name,))
+        (beam, resource_dir) = _gen_parse_transform_beam(ctx, env, src, extra, erlc)
+        transform_arg = "+{parse_transform, %s}" % (module_name,)
+        if resource_dir:
+            transforms[module_name] = cmd_args(transform_arg, cmd_args(beam, format = "-pa{}", parent = 1, hidden = resource_dir))
+        else:
+            transforms[module_name] = cmd_args(transform_arg, cmd_args(beam, format = "-pa{}", parent = 1))
+    return transforms
+
+def _gen_parse_transform_beam(ctx: AnalysisContext, env: dict[str, str], src: Artifact, extra: list[Artifact], erlc: Tool) -> (Artifact, [Artifact, None]):
+    name = strip_extension(src.basename)
+
+    # install resources
+    resource_dir = None
+    if extra:
+        resource_dir = ctx.actions.symlinked_dir(
+            paths.join(name, "resources"),
+            {infile.basename: infile for infile in extra},
+            has_content_based_path = False,
+        )
+
+    # build beam
+    output = ctx.actions.declare_output(name, name + ".beam", has_content_based_path = False)
+    _compile_toolchain_module(ctx, env, src, output.as_output(), erlc)
+
+    return output, resource_dir
+
+default_toolchain_script_args_pre = cmd_args(
+    "+A0",
+    "+S1:1",
+    "+sbtu",
+    "+SDio",
+    "1",
+    "+MMscs",
+    "8",
+    "+MMsco",
+    "false",
+    "-mode",
+    "minimal",
+    "-noinput",
+    "-noshell",
+    "-boot",
+    "no_dot_erlang",
+    "-eval",
+)
+default_toolchain_script_args_post = cmd_args("-s", "erlang", "halt", "--")
+
+def _gen_toolchain_script(ctx: AnalysisContext, env: dict[str, str], script: Artifact, tools: Tools, utility_modules: Artifact) -> Tool:
+    name = strip_extension(script.basename)
+    out = ctx.actions.declare_output(name, name + ".beam", has_content_based_path = False)
+    _compile_toolchain_module(ctx, env, script, out.as_output(), tools.erlc)
+    eval = cmd_args(name, ":main(init:get_plain_arguments())", delimiter = "")
+    return cmd_args(
+        tools.erl,
+        cmd_args(out, parent = 1, prepend = "-pa"),
+        cmd_args(utility_modules, parent = 0, prepend = "-pa"),
+        default_toolchain_script_args_pre,
+        eval,
+        default_toolchain_script_args_post,
+    )
+
+erlang_toolchain = rule(
+    impl = _erlang_toolchain_impl,
+    attrs = {
+        "core_parse_transforms": attrs.list(attrs.dep(), default = ["@prelude//erlang/toolchain:transform_project_root"]),
+        "emu_flags": attrs.one_of(
+            attrs.list(attrs.string()),
+            # deprecated: list-of-strings are preferred (e.g. they are more easily selectable)
+            attrs.string(),
+            default = [],
+        ),
+        "env": attrs.dict(key = attrs.string(), value = attrs.string(), default = {}),
+        "erl_opts": attrs.one_of(
+            attrs.list(attrs.string()),
+            # deprecated: list-of-strings are preferred (e.g. they are more easily selectable)
+            attrs.string(),
+            default = [],
+        ),
+        "erts_toolchain_info": attrs.option(attrs.dep(providers = [ErtsToolchainInfo]), default = None),
+        "otp_binaries": attrs.toolchain_dep(),
+        "parse_transforms": attrs.list(attrs.dep()),
+        "parse_transforms_filters": attrs.dict(key = attrs.string(), value = attrs.list(attrs.string())),
+        "toolchain_utilities": attrs.toolchain_dep(default = "@prelude//erlang/toolchain:toolchain_utilities"),
+    },
+    is_toolchain_rule = True,
+)
+
+def _gen_util_beams(ctx: AnalysisContext, env: dict[str, str], sources: list[Artifact], erlc: Tool) -> Artifact:
+    beams = []
+    for src in sources:
+        output = ctx.actions.declare_output(
+            paths.join(
+                "__build",
+                paths.replace_extension(src.basename, ".beam"),
+            ),
+            has_content_based_path = False,
+        )
+        _compile_toolchain_module(ctx, env, src, output.as_output(), erlc)
+        beams.append(output)
+
+    beam_dir = ctx.actions.symlinked_dir(
+        "utility_modules",
+        {beam.basename: beam for beam in beams},
+        has_content_based_path = False,
+    )
+
+    return beam_dir
+
+def _compile_toolchain_module(ctx: AnalysisContext, env: dict[str, str], src: Artifact, out: OutputArtifact, erlc: Tool):
+    # NOTE: since we do NOT define +debug_info, this is hermetic
+    ctx.actions.run(
+        [erlc, "+deterministic", "-o", cmd_args(out, parent = 1), src],
+        category = "erlc",
+        identifier = src.short_path,
+        env = env,
+    )
+
+# Parse Transform
+
+def erlang_otp_binaries_impl(ctx: AnalysisContext):
+    return [
+        DefaultInfo(),
+        ErlangOTPBinariesInfo(
+            erl = cmd_args(ctx.attrs.erl),
+            erlc = cmd_args(ctx.attrs.erlc),
+            escript = cmd_args(ctx.attrs.escript),
+        ),
+    ]
+
+erlang_parse_transform = rule(
+    impl = lambda ctx: [
+        DefaultInfo(),
+        ErlangParseTransformInfo(
+            source = ctx.attrs.src,
+            extra_files = ctx.attrs.extra_files,
+        ),
+    ],
+    attrs = {
+        "extra_files": attrs.list(attrs.source(), default = []),
+        "src": attrs.source(),
+    },
+)
+
+def _toolchain_utils(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        ToolchainUtillInfo(
+            app_src_script = ctx.attrs.app_src_script,
+            appup_src_script = ctx.attrs.appup_src_script,
+            boot_script_builder = ctx.attrs.boot_script_builder,
+            core_parse_transforms = ctx.attrs.core_parse_transforms,
+            dependency_analyzer = ctx.attrs.dependency_analyzer,
+            dependency_finalizer = ctx.attrs.dependency_finalizer,
+            dependency_merger = ctx.attrs.dependency_merger,
+            escript_trampoline = ctx.attrs.escript_trampoline,
+            escript_builder = ctx.attrs.escript_builder,
+            release_variables_builder = ctx.attrs.release_variables_builder,
+            utility_modules = ctx.attrs.utility_modules,
+        ),
+    ]
+
+toolchain_utilities = rule(
+    impl = _toolchain_utils,
+    attrs = {
+        "app_src_script": attrs.source(),
+        "appup_src_script": attrs.source(),
+        "boot_script_builder": attrs.source(),
+        "core_parse_transforms": attrs.list(attrs.dep()),
+        "dependency_analyzer": attrs.source(),
+        "dependency_finalizer": attrs.source(),
+        "dependency_merger": attrs.source(),
+        "escript_builder": attrs.source(),
+        "escript_trampoline": attrs.source(),
+        "release_variables_builder": attrs.source(),
+        "utility_modules": attrs.list(attrs.source()),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/erlang/erlang_utils.bzl b/buck2/prelude/erlang/erlang_utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erlang_utils.bzl
@@ -0,0 +1,47 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+
+def app_name(ctx: AnalysisContext) -> str:
+    if ctx.attrs.app_name == None:
+        return ctx.attrs.name
+    else:
+        return ctx.attrs.app_name
+
+def preserve_structure(path: str) -> dict[str, list[str]]:
+    """Return a mapping from a path that preserves the filestructure relative to the path."""
+    all_files = glob([paths.join(path, "**")])
+    mapping = {}
+    for filename in all_files:
+        relative_path = paths.relativize(filename, path)
+        dirname = paths.dirname(relative_path)
+        mapping[dirname] = mapping.get(dirname, []) + [filename]
+    return mapping
+
+def _file_mapping_impl(ctx: AnalysisContext) -> list[Provider]:
+    outputs = []
+    for target_path, files in ctx.attrs.mapping.items():
+        for file in files:
+            target_path = paths.normalize(target_path)
+            out_path = paths.normalize(paths.join(target_path, file.basename))
+            out = ctx.actions.symlink_file(
+                out_path,
+                file,
+                has_content_based_path = False,
+            )
+            outputs.append(out)
+
+    return [DefaultInfo(default_outputs = outputs)]
+
+file_mapping = rule(
+    impl = _file_mapping_impl,
+    attrs = {
+        "mapping": attrs.dict(key = attrs.string(), value = attrs.list(attrs.source()), default = {}),
+    },
+)
diff --git a/buck2/prelude/erlang/erts/BUCK b/buck2/prelude/erlang/erts/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erts/BUCK
@@ -0,0 +1,11 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+export_file(
+    name = "extract_from_otp.erl",
+    src = "extract_from_otp.erl",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/erlang/erts/extract_from_otp.erl b/buck2/prelude/erlang/erts/extract_from_otp.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/erts/extract_from_otp.erl
@@ -0,0 +1,216 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%%% % @format
+-module(extract_from_otp).
+-compile(warn_missing_spec_all).
+-author("loscher@meta.com").
+-moduledoc """
+Take parts of the OTP a release is built from, and introspect the versions it ships
+
+usage:
+  extract_from_otp.erl versions Target
+  extract_from_otp.erl extract_into Wildcard Target
+  extract_from_otp.erl Wildcard Target
+""".
+
+%% escript API
+-export([
+    main/1
+]).
+
+%% Macros
+-define(otp_application_not_found, 1).
+-define(no_matches_for_wildcard, 2).
+-define(multiple_matches_for_wildcard, 3).
+-define(extract_from_otp_error(ErrorNumber, Report),
+    io:format(standard_error, "~ts:~w:~w: ~ts\n", [?FILE, ?LINE, ErrorNumber, json:encode(Report)])
+).
+-define(FMT(Str, Args), bin(io_lib:format(Str, Args))).
+
+%%%=============================================================================
+%%% escript API functions
+%%%=============================================================================
+
+-spec main([string()]) -> ok.
+main(["versions", Target]) ->
+    ok = file:write_file(Target, json:encode(versions()));
+main(["extract_into", Wildcard, Target]) ->
+    ok = extract_into(Wildcard, Target);
+main([Wildcard, Target]) ->
+    ok = extract(Wildcard, Target);
+main(_) ->
+    usage().
+
+%%%-----------------------------------------------------------------------------
+%%% Internal functions
+%%%-----------------------------------------------------------------------------
+
+-compile({inline, [bin/1]}).
+-spec bin(IoListOrBinary :: iolist() | binary()) -> binary().
+bin(X) -> erlang:iolist_to_binary(X).
+
+-spec copy_dir(From, To) -> ok when From :: file:filename(), To :: file:filename().
+copy_dir(From, To) ->
+    Cmd = lists:flatten(
+        io_lib:format("cp -r ~ts ~ts", [From, To])
+    ),
+    io:format(standard_error, "cmd: ~ts~n~ts~n~n", [Cmd, os:cmd(Cmd)]),
+    case filelib:is_dir(To, prim_file) orelse filelib:is_file(To, prim_file) of
+        true -> ok;
+        false -> erlang:halt(1)
+    end.
+
+-spec extract(string(), string()) -> ok.
+extract(Wildcard, Target) ->
+    FullWildcard = filename:join(code:root_dir(), Wildcard),
+    case filelib:wildcard(FullWildcard, ".", prim_file) of
+        [OneResult] ->
+            ok = copy_dir(OneResult, Target);
+        [] ->
+            % Extract app name from wildcard for structured error reporting
+            case extract_app_name_from_wildcard(Wildcard) of
+                {ok, AppName} ->
+                    AvailableApps = get_available_otp_applications(),
+                    ?extract_from_otp_error(?otp_application_not_found, #{
+                        message => ?FMT("OTP application not found: ~ts", [AppName]),
+                        name => bin(AppName),
+                        available_applications => AvailableApps,
+                        root_dir => bin(code:root_dir())
+                    });
+                error ->
+                    ?extract_from_otp_error(?no_matches_for_wildcard, #{
+                        message => ?FMT("No matches found for wildcard: ~ts", [FullWildcard]),
+                        wildcard => bin(FullWildcard),
+                        root_dir => bin(code:root_dir())
+                    })
+            end,
+            erlang:halt(1);
+        Paths ->
+            ?extract_from_otp_error(?multiple_matches_for_wildcard, #{
+                message => ?FMT("Expected exactly one result but found ~p matches for: ~ts", [
+                    length(Paths), FullWildcard
+                ]),
+                paths => [bin(Path) || Path <- Paths],
+                wildcard => bin(FullWildcard),
+                root_dir => bin(code:root_dir())
+            }),
+            erlang:halt(1)
+    end.
+
+-spec extract_into(Wildcard, Target) -> ok when Wildcard :: string(), Target :: string().
+extract_into(Wildcard, Target) ->
+    FullWildcard = filename:join(code:root_dir(), Wildcard),
+    case filelib:wildcard(FullWildcard, ".", prim_file) of
+        [] ->
+            ?extract_from_otp_error(?no_matches_for_wildcard, #{
+                message => ?FMT("No matches found for wildcard: ~ts", [FullWildcard]),
+                wildcard => bin(FullWildcard),
+                root_dir => bin(code:root_dir())
+            }),
+            erlang:halt(1);
+        Paths ->
+            ok = filelib:ensure_path(Target),
+            lists:foreach(
+                fun(Path) ->
+                    ok = copy_dir(Path, filename:join(Target, filename:basename(Path)))
+                end,
+                Paths
+            )
+    end.
+
+-spec versions() -> #{binary() => binary() | #{binary() => binary()}}.
+versions() ->
+    LibDir = filename:join(code:root_dir(), "lib"),
+    Applications = lists:foldl(
+        fun(Entry, Acc) ->
+            case string:split(Entry, "-", trailing) of
+                [Name, Version] -> Acc#{bin(Name) => bin(Version)};
+                _ -> Acc
+            end
+        end,
+        #{},
+        filelib:wildcard("*-*", LibDir, prim_file)
+    ),
+    #{
+        <<"erts_version">> => bin(erlang:system_info(version)),
+        <<"applications">> => Applications
+    }.
+
+-spec extract_app_name_from_wildcard(string()) -> {ok, string()} | error.
+extract_app_name_from_wildcard(Wildcard) ->
+    % Expected format: "lib/appname-*"
+    case string:split(Wildcard, "/") of
+        ["lib", Pattern] ->
+            case string:split(Pattern, "-") of
+                [AppName, "*"] -> {ok, AppName};
+                _ -> error
+            end;
+        _ ->
+            error
+    end.
+
+-spec get_available_otp_applications() -> [binary()].
+get_available_otp_applications() ->
+    RootDir = code:root_dir(),
+    % Read OTP version from releases/start_erl.data (format: "ERTS_VERSION OTP_VERSION")
+    StartErlDataFile = filename:join([RootDir, "releases", "start_erl.data"]),
+    maybe
+        {ok, StartErlDataContent} ?= file:read_file(StartErlDataFile),
+        % Parse "15.1 27\n" to get OTP version "27"
+        [_ErtsVersion, OtpVersion] ?= string:split(string:trim(StartErlDataContent), " "),
+        % Read installed_application_versions file
+        InstalledAppsFile = filename:join([RootDir, "releases", OtpVersion, "installed_application_versions"]),
+        {ok, InstalledAppsContent} ?= file:read_file(InstalledAppsFile),
+        % Parse lines like "stdlib-6.1" to extract app names
+        InstalledAppsLines = [_ | _] ?= string:split(string:trim(InstalledAppsContent), "\n", all),
+        parse_installed_application_versions(InstalledAppsLines)
+    else
+        _ ->
+            % Fallback to lib directory wildcard if:
+            %   start_erl.data doesn't exist,
+            %   start_erl.data format is unexpected,
+            %   installed_application_versions doesn't exist,
+            %   or installed_application_versions format is unexpected.
+            get_available_otp_applications_from_lib()
+    end.
+
+-spec get_available_otp_applications_from_lib() -> [binary()].
+get_available_otp_applications_from_lib() ->
+    % Fallback method: scan lib directory
+    LibDir = filename:join(code:root_dir(), "lib"),
+    case filelib:wildcard("*", LibDir, prim_file) of
+        [] -> [];
+        Dirs -> parse_installed_application_versions(Dirs)
+    end.
+
+-spec parse_installed_application_versions(Dirs) -> AppNameList when Dirs :: [string()], AppNameList :: [binary()].
+parse_installed_application_versions(Dirs) ->
+    % Extract app names from directory names (format: appname-version)
+    % Sort alphabetically for consistent output
+    lists:sort(
+        lists:filtermap(
+            fun(Dir) ->
+                case string:split(Dir, "-") of
+                    [AppName | _] -> {true, bin(AppName)};
+                    _ -> false
+                end
+            end,
+            Dirs
+        )
+    ).
+
+-spec usage() -> ok.
+usage() ->
+    io:format(
+        standard_error,
+        "usage:~n"
+        "  extract_from_otp.erl versions Target~n"
+        "  extract_from_otp.erl extract_into Wildcard Target~n"
+        "  extract_from_otp.erl Wildcard Target~n",
+        []
+    ).
diff --git a/buck2/prelude/erlang/shell/BUCK b/buck2/prelude/erlang/shell/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/shell/BUCK
@@ -0,0 +1,23 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+erlang_application(
+    name = "buck2_shell_utils",
+    srcs = glob(["src/*.erl"]),
+    applications = [
+        "kernel",
+        "stdlib",
+    ],
+    erl_opts = [
+        "+debug_info",
+        "+warnings_as_errors",
+    ],
+    included_applications = [
+        "prelude//erlang/common_test/test_exec:test_exec",
+    ],
+    shell_libs = [],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/erlang/shell/shell.bxl b/buck2/prelude/erlang/shell/shell.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/shell/shell.bxl
@@ -0,0 +1,37 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _deduped_paths(paths):
+    return list({str(path): path.abs_path() for path in paths}.values())
+
+def _ebin_paths(ctx):
+    target_universe = ctx.uquery().owner(ctx.cli_args.source)
+    test_target = ctx.cquery().kind("erlang_test", ctx.cquery().owner(ctx.cli_args.source, target_universe))
+    app_target = ctx.cquery().kind("erlang_app$", ctx.cquery().owner(ctx.cli_args.source, target_universe))
+
+    target = test_target + app_target
+
+    paths = []
+    failed_targets = []
+    for k, value in ctx.build(target).items():
+        for _ in value.failures():
+            failed_targets.append(str(k.raw_target()))
+            break
+        paths.extend(ctx.output.ensure_multiple(value.artifacts()))
+
+    if failed_targets:
+        fail("failed to build {} targets: {}".format(len(failed_targets), failed_targets))
+
+    ctx.output.print(sep = "\n", *_deduped_paths(paths))
+
+ebin_paths = bxl_main(
+    impl = _ebin_paths,
+    cli_args = {
+        "source": cli_args.string(),
+    },
+)
diff --git a/buck2/prelude/erlang/shell/src/shell_buck2_module_search.erl b/buck2/prelude/erlang/shell/src/shell_buck2_module_search.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/shell/src/shell_buck2_module_search.erl
@@ -0,0 +1,109 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(shell_buck2_module_search).
+-moduledoc """
+Configurable hook for module discovery
+""".
+-compile(warn_missing_spec_all).
+
+-export([find_module/1, find_module_source/1]).
+
+-import(common_util, [unicode_characters_to_binary/1]).
+
+-callback find_module_source(module()) ->
+    {source, file:filename_all()}
+    | {error, not_found | {ambiguous, [file:filename_all()]}}.
+
+-spec find_module(atom()) ->
+    available
+    | {source, file:filename_all()}
+    | {error, not_found | {ambiguous, [file:filename_all()]}}.
+find_module(Module) ->
+    WantedModuleName = atom_to_list(Module),
+    case
+        [
+            found
+         || {ModuleName, _, _} <- code:all_available(),
+            string:equal(WantedModuleName, ModuleName)
+        ]
+    of
+        [found] ->
+            available;
+        _ ->
+            case shell_buck2_utils:get_app_env(search_module) of
+                {ok, Mod} ->
+                    Mod:find_module_source(Module);
+                _ ->
+                    find_module_source(Module)
+            end
+    end.
+
+-spec find_module_source(module()) ->
+    {source, file:filename_all()}
+    | {error, not_found | {ambiguous, [file:filename_all()]}}.
+find_module_source(Module) ->
+    Root = shell_buck2_utils:cell_root(),
+    io:format("use ~ts as root", [Root]),
+    {ok, Output} = shell_buck2_utils:run_command([
+        "find",
+        Root,
+        "-type",
+        "d",
+        "(",
+        "-path",
+        io_lib:format("~ts/_build*", [Root]),
+        "-o",
+        "-path",
+        io_lib:format("~ts/erl/_build*", [Root]),
+        "-o",
+        "-path",
+        io_lib:format("~ts/buck-out", [Root]),
+        ")",
+        "-prune",
+        "-o",
+        "-name",
+        io_lib:format("~ts.erl", [Module]),
+        "-print"
+    ]),
+    case
+        [
+            RelPath
+         || Path <- string:split(Output, ~"\n", all),
+            RelPath <- [unicode_characters_to_binary(P) || P <- [string:prefix(Path, [Root, ~"/"])], P =/= nomatch],
+            string:prefix(RelPath, ~"buck-out") == nomatch,
+            binary:match(RelPath, ~"_build") == nomatch
+        ]
+    of
+        [ModulePath] ->
+            {source, ModulePath};
+        [] ->
+            {error, not_found};
+        Candidates ->
+            %% check if there are actually targets associated
+            {ok, RawOutput} = shell_buck2_utils:buck2_query(
+                ~|owner(\\"%s\\")|,
+                [~"--json"],
+                Candidates
+            ),
+            SourceTargetMapping = json:decode(RawOutput),
+            case
+                maps:fold(
+                    fun
+                        (_Source, [], Acc) -> Acc;
+                        (Source, _, Acc) -> [Source | Acc]
+                    end,
+                    [],
+                    SourceTargetMapping
+                )
+            of
+                [] -> {error, not_found};
+                [Source] -> {source, Source};
+                More -> {error, {ambiguous, More}}
+            end
+    end.
diff --git a/buck2/prelude/erlang/shell/src/shell_buck2_utils.erl b/buck2/prelude/erlang/shell/src/shell_buck2_utils.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/shell/src/shell_buck2_utils.erl
@@ -0,0 +1,235 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(shell_buck2_utils).
+-moduledoc """
+Documentation for shell_buck2_utils, ways to use
+  it, ways to break it, etc. etc
+""".
+
+-compile(warn_missing_spec_all).
+
+%% Public API
+-export([
+    project_root/0,
+    cell_root/0,
+    rebuild_modules/1,
+    buck2_build_targets/1,
+    buck2_query/1, buck2_query/2, buck2_query/3,
+    run_command/1, run_command/2,
+    no_stderr/1,
+    get_additional_paths/1,
+    get_app_env/1
+]).
+
+-import(common_util, [unicode_characters_to_binary/1]).
+
+-type opt() :: {at_root, boolean()}.
+
+-spec project_root() -> file:filename_all().
+project_root() ->
+    root(project).
+
+-spec cell_root() -> file:filename_all().
+cell_root() ->
+    root(cell).
+
+-spec root(Type :: cell | project) -> file:filename_all().
+root(Type) ->
+    case run_command(no_stderr([~"buck2", ~"root", ~"--kind", atom_to_binary(Type)]), [{at_root, false}]) of
+        {ok, Output} ->
+            Dir = unicode_characters_to_binary(string:trim(Output)),
+            case filelib:is_dir(Dir, prim_file) of
+                true -> Dir;
+                false -> error({project_root_not_found, Dir})
+            end;
+        error ->
+            error(failed_to_query_project_root)
+    end.
+
+-spec rebuild_modules([module()]) -> ok | error.
+rebuild_modules([]) ->
+    ok;
+rebuild_modules(Modules) ->
+    case lists:filter(fun(Module) -> code:which(Module) == non_existing end, Modules) of
+        [] -> ok;
+        Missing -> error({non_existing, Missing})
+    end,
+    RelSources = [proplists:get_value(source, Module:module_info(compile)) || Module <- Modules],
+    {ok, RawQueryResult} = buck2_query(~"owner(\%s)", RelSources),
+    Targets = string:split(string:trim(RawQueryResult), "\n", all),
+    case Targets of
+        [[]] ->
+            io:format(~"ERROR: couldn't find targets for ~w~n", [Modules]),
+            error;
+        _ ->
+            buck2_build_targets(Targets)
+    end.
+
+-spec buck2_build_targets(Targets) -> ok | error when
+    Targets :: [string() | binary()].
+buck2_build_targets(Targets) ->
+    case
+        run_command([
+            ~"buck2",
+            ~"build",
+            ~"--reuse-current-config",
+            ~"--console=super",
+            get_buck2_args_from_env()
+            | Targets
+        ])
+    of
+        {ok, _Output} -> ok;
+        error -> error
+    end.
+
+-spec buck2_query(Query) -> {ok, binary()} | error when
+    Query :: string() | binary().
+buck2_query(Query) ->
+    buck2_query(Query, []).
+
+-spec buck2_query(Query, Args) -> {ok, binary()} | error when
+    Query :: string() | binary(),
+    Args :: [string() | binary()].
+buck2_query(Query, Args) ->
+    buck2_query(Query, [], Args).
+
+-spec buck2_query(Query, BuckArgs, Args) -> {ok, binary()} | error when
+    Query :: string() | binary(),
+    BuckArgs :: [string() | binary()],
+    Args :: [string() | binary()].
+buck2_query(Query, BuckArgs, Args) ->
+    run_command(
+        no_stderr([
+            ~"buck2",
+            ~"uquery",
+            ~"--reuse-current-config",
+            get_buck2_args_from_env(),
+            BuckArgs,
+            Query,
+            Args
+        ])
+    ).
+
+-spec no_stderr(CommandArgs) -> CommandArgs when
+    CommandArgs :: [unicode:chardata()].
+no_stderr(CommandArgs) ->
+    [~"sh", ~"-c", ~"exec 2>/dev/null $0 \"$@\"" | CommandArgs].
+
+-spec run_command(CommandArgs) -> {ok, binary()} | error when
+    CommandArgs :: [unicode:chardata()].
+run_command(Command) ->
+    run_command(Command, []).
+
+-spec run_command(CommandArgs, Options) -> {ok, binary()} | error when
+    CommandArgs :: unicode:chardata(),
+    Options :: [opt()].
+run_command(Command, Options) when is_binary(Command) ->
+    run_command([Command], Options);
+run_command(CmdArgs, Options) when is_list(CmdArgs) ->
+    [Cmd | Args] = flatten_command_args(CmdArgs, []),
+    CmdPath =
+        case os:find_executable(binary_to_list(Cmd)) of
+            false -> error({command_not_found, Cmd});
+            Path -> Path
+        end,
+    PortOpts0 = [{args, Args}, exit_status],
+    PortOpts1 =
+        case proplists:get_value(at_root, Options, true) of
+            true ->
+                Root = project_root(),
+                [{cd, Root} | PortOpts0];
+            false ->
+                PortOpts0
+        end,
+
+    Port = erlang:open_port({spawn_executable, CmdPath}, PortOpts1),
+    port_loop(Port, []).
+
+-spec flatten_command_args(CommandArgs, Acc) -> Acc when
+    CommandArgs :: iodata(),
+    Acc :: [binary()].
+flatten_command_args([], Acc) ->
+    lists:reverse(Acc);
+flatten_command_args([H | T], Acc) when is_binary(H) ->
+    flatten_command_args(T, [H | Acc]);
+flatten_command_args([H = [I | _] | T], Acc) when is_integer(I) ->
+    flatten_command_args(T, [unicode_characters_to_binary(H) | Acc]);
+flatten_command_args([[] | T], Acc) ->
+    flatten_command_args(T, Acc);
+flatten_command_args([[H | T1] | T2], Acc) ->
+    flatten_command_args([H, T1 | T2], Acc).
+
+-spec port_loop(port(), [binary()]) -> {ok, binary()} | error.
+port_loop(Port, StdOut) ->
+    receive
+        {Port, {exit_status, 0}} ->
+            {ok, unicode_characters_to_binary(lists:reverse(StdOut))};
+        {Port, {exit_status, _}} ->
+            error;
+        {Port, {data, Data}} ->
+            port_loop(Port, [Data | StdOut])
+    end.
+
+-spec get_additional_paths(file:filename_all()) -> [file:filename_all()].
+get_additional_paths(Path) ->
+    case
+        run_command([
+            ~"buck2",
+            ~"bxl",
+            ~"--reuse-current-config",
+            ~"--console=super",
+            get_buck2_args_from_env(),
+            ~"prelude//erlang/shell/shell.bxl:ebin_paths",
+            ~"--",
+            ~"--source",
+            Path
+        ])
+    of
+        {ok, Output} ->
+            MaybeOutputPaths = [
+                filter_escape_chars(OutputPath)
+             || OutputPath <- string:split(Output, "\n", all)
+            ],
+            MaybeAllPaths = [
+                RelevantPath
+             || OutputPath <- MaybeOutputPaths,
+                filelib:is_dir(OutputPath, prim_file),
+                RelevantPath <- [OutputPath, filename:join(OutputPath, "ebin")]
+            ],
+            Result =
+                [MaybePath || MaybePath <- MaybeAllPaths, filelib:is_dir(MaybePath, prim_file)],
+            Result;
+        error ->
+            []
+    end.
+
+%% copied from stackoverflow: https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
+-define(ANSI_ESCAPE_REGEX,
+    ~"(\x9B|\x1B\\[)[0-?]*[ -/]*[@-~]"
+).
+
+-spec filter_escape_chars(String) -> binary() when
+    String :: binary().
+filter_escape_chars(String) ->
+    unicode_characters_to_binary(re:replace(String, ?ANSI_ESCAPE_REGEX, "", [global])).
+
+-spec get_buck2_args_from_env() -> [binary()].
+get_buck2_args_from_env() ->
+    case get_app_env(buck2_args) of
+        undefined -> [];
+        {ok, Buck2Args} when is_list(Buck2Args) -> Buck2Args
+    end.
+
+-spec get_app_env(Key) -> {ok, Value} | undefined when
+    Key :: atom(),
+    Value :: dynamic().
+get_app_env(Key) ->
+    _ = application:load(buck2_shell_utils),
+    % elp:ignore W0011 (application_get_env)
+    application:get_env(buck2_shell_utils, Key).
diff --git a/buck2/prelude/erlang/shell/src/user_default.erl b/buck2/prelude/erlang/shell/src/user_default.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/shell/src/user_default.erl
@@ -0,0 +1,64 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% % @format
+-module(user_default).
+-wacov(ignore).
+
+-compile(warn_missing_spec_all).
+
+-export([
+    c/1, c/2, c/3,
+    l/1
+]).
+
+-import(common_util, [filename_all_to_filename/1]).
+
+-type c_ret() :: {ok, module()} | error.
+-type c_options() :: [compile:option()] | compile:option().
+
+-spec c(module()) -> c_ret() | {error, non_existing}.
+c(Module) ->
+    c(Module, []).
+
+-spec c(module(), c_options()) -> c_ret() | {error, non_existing}.
+c(Module, Options) ->
+    c(Module, Options, fun(_) -> true end).
+
+-spec c(module(), c_options(), fun((compile:option()) -> boolean())) -> c_ret() | {error, non_existing}.
+c(Module, _Options, _Filter) ->
+    case code:which(Module) of
+        non_existing ->
+            {error, non_existing};
+        _ ->
+            case shell_buck2_utils:rebuild_modules([Module]) of
+                ok ->
+                    ok = ct_daemon:push_module(Module),
+                    code:purge(Module),
+                    code:load_file(Module),
+                    {ok, Module};
+                error ->
+                    error
+            end
+    end.
+
+-spec l(module()) ->
+    code:load_ret()
+    | {error, not_found | {ambiguous, [file:filename_all()]}}.
+l(Module) ->
+    case shell_buck2_module_search:find_module(Module) of
+        available ->
+            c:l(Module);
+        {source, RelSource} ->
+            AbsSource = filename:absname(RelSource),
+            Paths = [filename_all_to_filename(Path) || Path <- shell_buck2_utils:get_additional_paths(AbsSource)],
+            ok = code:add_paths(Paths),
+            ok = ct_daemon:push_paths(Paths),
+            c:l(Module);
+        Error ->
+            Error
+    end.
diff --git a/buck2/prelude/erlang/toolchain/BUCK b/buck2/prelude/erlang/toolchain/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/BUCK
@@ -0,0 +1,45 @@
+load("@prelude//erlang:erlang_headers.bzl", "erlang_headers")
+load("@prelude//erlang:erlang_toolchain.bzl", "erlang_parse_transform", "toolchain_utilities")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+erlang_parse_transform(
+    name = "transform_project_root",
+    src = "transform_project_root.erl",
+    visibility = ["PUBLIC"],
+)
+
+# export escripts for testing
+filegroup(
+    name = "util_scripts",
+    srcs = glob([
+        "*.escript",
+        "*.sh",
+        "*.erl",
+    ]),
+    visibility = ["PUBLIC"],
+)
+
+toolchain_utilities(
+    name = "toolchain_utilities",
+    app_src_script = "app_src_builder.erl",
+    appup_src_script = "appup_src_builder.erl",
+    boot_script_builder = "boot_script_builder.erl",
+    core_parse_transforms = [":transform_project_root"],
+    dependency_analyzer = "dependency_analyzer.erl",
+    dependency_finalizer = "dependency_finalizer.erl",
+    dependency_merger = "dependency_merger.erl",
+    escript_builder = "escript_builder.erl",
+    escript_trampoline = "escript_trampoline.sh",
+    release_variables_builder = "release_variables_builder.erl",
+    utility_modules = ["dependency_utils.erl"],
+    visibility = ["PUBLIC"],
+)
+
+erlang_headers(
+    name = "erlang_headers",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/erlang/toolchain/app_src_builder.erl b/buck2/prelude/erlang/toolchain/app_src_builder.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/app_src_builder.erl
@@ -0,0 +1,621 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(app_src_builder).
+-moduledoc """
+Build an .app file from a given list of modules and a template
+.app.src file.
+
+usage:
+  app_src_builder.escript app_info.json
+
+app_info.json format:
+
+  The file must contain only a single JSON map with the following spec:
+
+ #{
+     <<"name">>                   := <application_name>,
+     <<"sources">>                := [<path to .erl source file>],
+     <<"applications">>           := [<entry to applications field>],
+     <<"included_applications">>  := I[<entry to included_applications field>],
+     <<"app_src_vsn">>            := <placeholder string used in the .app.src vsn field>,
+     <<"template">>               => <path to an .app.src file>,
+     <<"version">>                => <version string>,
+     <<"env">>                    => [application env variable],
+     <<"metadata">>               => map of metadata
+ }
+""".
+
+-type application_resource() :: {application, atom(), proplists:proplist()}.
+-type mod() :: {atom(), [term()]} | undefined.
+-type filename() :: binary().
+-type metadata() :: #{atom() => atom() | [atom()]}.
+-type app_info() :: #{
+    name := binary(),
+    sources := [filename()],
+    vsn := binary() | undefined,
+    app_src_vsn := binary(),
+    template := application_resource(),
+    applications := [atom()],
+    included_applications := [atom()],
+    mod := mod(),
+    env := [{atom(), term()}] | undefined,
+    metadata := metadata()
+}.
+
+-export([main/1]).
+
+-spec main(Args) -> ok when Args :: [string()].
+main([AppInfoFile, Output]) ->
+    try
+        do(dependency_utils:chars_to_binary(AppInfoFile), dependency_utils:chars_to_binary(Output))
+    catch
+        Type:{abort, Reason} ->
+            io:format(standard_error, "~ts:~ts~n", [Type, Reason]),
+            erlang:halt(1)
+    end;
+main(_) ->
+    usage().
+
+-spec usage() -> ok.
+usage() ->
+    io:format("app_src_builder.escript app_info.json~n").
+
+-spec do(AppInfoFile, Output) -> ok when
+    AppInfoFile :: filename(),
+    Output :: filename().
+do(AppInfoFile, Output) ->
+    AppInfo = do_parse_app_info_file(AppInfoFile),
+    #{name := Name, sources := Srcs} = AppInfo,
+    VerifiedTerms = check_and_normalize_template(AppInfo),
+    render_app_file(Name, VerifiedTerms, Output, Srcs).
+
+-spec do_parse_app_info_file(AppInfoFile) -> app_info() when AppInfoFile :: filename().
+do_parse_app_info_file(AppInfoFile) ->
+    case prim_file:read_file(AppInfoFile) of
+        {ok, Content} ->
+            case json:decode(Content) of
+                #{
+                    <<"name">> := Name,
+                    <<"sources">> := Sources,
+                    <<"applications">> := Applications,
+                    <<"included_applications">> := IncludedApplications
+                } = Terms ->
+                    Template = get_template(maps:get(<<"template">>, Terms, undefined)),
+                    Mod = get_mod(Name, maps:get(<<"mod">>, Terms, undefined)),
+                    Env = get_env(Name, maps:get(<<"env">>, Terms, undefined)),
+                    Metadata = get_metadata(Name, maps:get(<<"metadata">>, Terms, undefined)),
+                    #{
+                        name => Name,
+                        sources => Sources,
+                        vsn => maps:get(<<"version">>, Terms, undefined),
+                        app_src_vsn => maps:get(<<"app_src_vsn">>, Terms),
+                        template => Template,
+                        applications =>
+                            normalize_application(Name, [binary_to_atom(App) || App <- Applications]),
+                        included_applications =>
+                            [binary_to_atom(App) || App <- IncludedApplications],
+                        mod => Mod,
+                        env => Env,
+                        metadata => Metadata
+                    };
+                Terms ->
+                    file_corrupt_error(AppInfoFile, Terms)
+            end;
+        Error ->
+            open_file_error(AppInfoFile, Error)
+    end.
+
+-spec get_template(TemplateFile) -> application_resource() when
+    TemplateFile :: filename() | undefined.
+get_template(undefined) ->
+    {application, '_', []};
+get_template(TemplateFile) ->
+    case file:consult(TemplateFile) of
+        {ok, [Template]} -> Template;
+        {ok, Terms} -> file_corrupt_error(TemplateFile, Terms);
+        Error -> open_file_error(TemplateFile, Error)
+    end.
+
+-spec get_mod(AppName, RawMod) -> mod() when
+    AppName :: binary(),
+    RawMod :: [binary() | [binary()]] | undefined.
+get_mod(_, undefined) ->
+    undefined;
+get_mod(AppName, [ModuleName, StringArgs]) ->
+    parse_term(
+        AppName,
+        ["{", ModuleName, ", ", StringArgs, "}"],
+        "mod field"
+    ).
+
+-spec parse_term(AppName, RawString, Description) -> term() when
+    AppName :: binary(),
+    RawString :: iolist(),
+    Description :: iolist().
+parse_term(AppName, RawString, Description) ->
+    String = unicode:characters_to_list([RawString | "."]),
+    try
+        {ok, Tokens, _EndLine} = erl_scan:string(String),
+        {ok, Term} = erl_parse:parse_term(Tokens),
+        Term
+    catch
+        _:_ -> parse_error(AppName, String, Description)
+    end.
+
+-spec get_env(AppName, RawEnv) -> [{atom(), term()}] | undefined when
+    AppName :: binary(),
+    RawEnv :: #{binary() => binary()} | undefined.
+get_env(_AppName, undefined) ->
+    undefined;
+get_env(AppName, RawEnv) ->
+    [
+        {binary_to_atom(K), parse_term(AppName, V, io_lib:format("env value for ~ts", [K]))}
+     || K := V <- maps:iterator(RawEnv, ordered)
+    ].
+
+-spec get_metadata(AppName, RawMetadata) -> metadata() when
+    AppName :: binary(),
+    RawMetadata :: #{binary() => binary() | [binary()]} | undefined.
+get_metadata(_AppName, undefined) ->
+    #{};
+get_metadata(AppName, RawMetadata) ->
+    #{binary_to_atom(K) => normalize_metadata_value(AppName, K, V) || K := V <- RawMetadata}.
+
+-spec normalize_metadata_value(AppName, Key, Value) -> atom() | [atom()] when
+    AppName :: binary(),
+    Key :: binary(),
+    Value :: binary() | [binary()].
+normalize_metadata_value(AppName, Key, Value) when is_binary(Value) ->
+    parse_term(AppName, Value, io_lib:format("metadata value for ~ts", [Key]));
+normalize_metadata_value(AppName, Key, Values) when is_list(Values) ->
+    Value = ["[", lists:join(",", Values), "]"],
+    parse_term(AppName, Value, io_lib:format("metadata value for ~ts", [Key])).
+
+-spec check_and_normalize_template(AppInfo) -> application_resource() when AppInfo :: app_info().
+check_and_normalize_template(#{
+    name := AppName,
+    vsn := TargetVersion,
+    app_src_vsn := AppSrcVsn,
+    template := Terms,
+    applications := Applications,
+    included_applications := IncludedApplications,
+    mod := Mod,
+    env := Env,
+    metadata := Metadata
+}) ->
+    App = binary_to_atom(AppName),
+    Props =
+        case Terms of
+            {application, App, P} when erlang:is_list(P) ->
+                P;
+            {application, '_', P} when erlang:is_list(P) ->
+                P;
+            _ ->
+                Msg = io_lib:format(
+                    "expect the top-level format of the template to be {application, '~ts'/'_', [ ... ]}.~nBut got instead: ~tp",
+                    [
+                        AppName,
+                        Terms
+                    ]
+                ),
+                erlang:error(
+                    {abort, Msg}
+                )
+        end,
+    VerifiedProps = verify_app_props(
+        AppName, TargetVersion, AppSrcVsn, Applications, IncludedApplications, Props
+    ),
+    Props0 = add_optional_fields(VerifiedProps, [{mod, Mod}, {env, Env}]),
+    Props1 = add_metadata(Props0, Metadata),
+    {application, App, Props1}.
+
+-spec add_optional_fields(Props, Fields) -> proplists:proplist() when
+    Props :: proplists:proplist(),
+    Fields :: [{atom(), term() | undefined}].
+add_optional_fields(Props, []) ->
+    Props;
+add_optional_fields(Props, [{_, undefined} | Fields]) ->
+    add_optional_fields(Props, Fields);
+add_optional_fields(Props, [{K, V0} | Fields]) ->
+    V1 = proplists:get_value(K, Props, undefined),
+    case V1 of
+        undefined ->
+            add_optional_fields([{K, V0} | Props], Fields);
+        % overwrite the value of empty list in .app.src, for example: {env, []}
+        [] ->
+            add_optional_fields([{K, V0} | Props], Fields);
+        _ ->
+            case V0 =:= V1 of
+                true -> add_optional_fields(Props, Fields);
+                false -> erlang:error(app_props_not_compatible, [{K, V0}, {K, V1}])
+            end
+    end;
+add_optional_fields(Props, [Field | Fields]) ->
+    add_optional_fields([Field | Props], Fields).
+
+-spec verify_app_props(AppName, Version, AppSrcVsn, Applications, IncludedApplications, Props) ->
+    proplists:proplist()
+when
+    AppName :: binary(),
+    Version :: binary() | undefined,
+    AppSrcVsn :: binary(),
+    Applications :: [atom()],
+    IncludedApplications :: [atom()],
+    Props :: proplists:proplist().
+verify_app_props(AppName, Version, AppSrcVsn, Applications, IncludedApplications, Props0) ->
+    Props1 = verify_applications(AppName, Props0),
+    %% ensure defaults
+    ensure_fields(AppName, Version, AppSrcVsn, Applications, IncludedApplications, Props1).
+
+-spec verify_applications(AppName, Props) -> proplists:proplist() when
+    AppName :: binary(),
+    Props :: proplists:proplist().
+verify_applications(AppName, AppDetail) ->
+    case proplists:get_value(applications, AppDetail) of
+        AppList when is_list(AppList) ->
+            FinalApps = normalize_application(AppName, AppList),
+            lists:keystore(applications, 1, AppDetail, {applications, FinalApps});
+        undefined ->
+            AppDetail;
+        BadApplicationsValue ->
+            applications_type_error(AppName, BadApplicationsValue)
+    end.
+
+-spec normalize_application(binary(), [atom()]) -> [atom()].
+normalize_application(<<"kernel">>, AppList) ->
+    AppList;
+normalize_application(<<"stdlib">>, AppList) ->
+    AppList;
+normalize_application(_AppName, AppList) ->
+    normalize_application(AppList).
+
+-spec normalize_application(Applications) -> [atom()] when Applications :: [atom()].
+normalize_application(Applications) ->
+    NormalizedApplications0 =
+        case lists:member(stdlib, Applications) of
+            false ->
+                [stdlib | Applications];
+            true ->
+                Applications
+        end,
+    NormalizedApplications =
+        case lists:member(kernel, Applications) of
+            false ->
+                [kernel | NormalizedApplications0];
+            true ->
+                NormalizedApplications0
+        end,
+    NormalizedApplications.
+
+-spec ensure_fields(AppName, Version, AppSrcVsn, Applications, IncludedApplications, Props) ->
+    proplists:proplist()
+when
+    AppName :: binary(),
+    Version :: binary() | undefined,
+    AppSrcVsn :: binary(),
+    Applications :: [atom()],
+    IncludedApplications :: [atom()],
+    Props :: proplists:proplist().
+ensure_fields(AppName, Version, AppSrcVsn, Applications, IncludedApplications, Props) ->
+    %% default means to add the value if not existing
+    %% match meand to overwrite if not existing and check otherwise for
+    Defaults = [
+        {{registered, []}, default},
+        {{vsn, binary_to_list(Version)}, match},
+        {{description, "missing description"}, default},
+        {{applications, Applications}, match},
+        {{included_applications, IncludedApplications}, match}
+    ],
+    lists:foldl(
+        fun
+            ({{Key, _} = Default, default}, Acc) ->
+                case lists:keyfind(Key, 1, Acc) of
+                    false -> [Default | Acc];
+                    _ -> Acc
+                end;
+            ({{Key, Value} = Default, match}, Acc) ->
+                case lists:keyfind(Key, 1, Acc) of
+                    false ->
+                        [Default | Acc];
+                    {Key, Value} ->
+                        Acc;
+                    %% When the configured placeholder is specified as the version in the .app.src file,
+                    %% it means that the version will be calculated dynamically based on the VCS version.
+                    %% We consider the version from the Buck target to be authoritative.
+                    {vsn, Vsn} ->
+                        case is_app_src_vsn(Vsn, AppSrcVsn) of
+                            true -> [Default | lists:keydelete(vsn, 1, Acc)];
+                            false -> value_match_error(AppName, {vsn, Vsn}, Default)
+                        end;
+                    Wrong ->
+                        value_match_error(AppName, Wrong, Default)
+                end
+        end,
+        Props,
+        Defaults
+    ).
+
+-spec is_app_src_vsn(Vsn, AppSrcVsn) -> boolean() when
+    Vsn :: term(),
+    AppSrcVsn :: binary().
+is_app_src_vsn(Vsn, AppSrcVsn) when is_atom(Vsn) ->
+    atom_to_binary(Vsn) =:= AppSrcVsn;
+is_app_src_vsn(Vsn, AppSrcVsn) when is_list(Vsn) ->
+    Vsn =:= binary_to_list(AppSrcVsn);
+is_app_src_vsn(_, _) ->
+    false.
+
+-spec render_app_file(AppName, Terms, Output, Srcs) -> ok when
+    AppName :: binary(),
+    Terms :: application_resource(),
+    Output :: filename(),
+    Srcs :: [filename()].
+render_app_file(AppName, Terms, Output, Srcs) ->
+    App = binary_to_atom(AppName),
+    Modules = generate_modules(Srcs),
+    {application, App, Props0} = Terms,
+    %% remove modules key
+    Props1 = lists:keydelete(modules, 1, Props0),
+    %% construct new terms
+    Spec =
+        {application, App, [{modules, Modules} | Props1]},
+    ToWrite = io_lib:format("~kp.\n", [Spec]),
+    ok = prim_file:write_file(Output, ToWrite).
+
+-spec generate_modules(Sources) -> [atom()] when Sources :: [filename()].
+generate_modules(Sources) ->
+    Modules = lists:foldl(
+        fun(Source, Acc) ->
+            case filename:extension(Source) of
+                <<".hrl">> ->
+                    Acc;
+                Ext when Ext =:= <<".erl">> orelse Ext =:= <<".xrl">> orelse Ext =:= <<".yrl">> ->
+                    ModuleName = filename:basename(Source, Ext),
+                    Module = erlang:binary_to_atom(ModuleName),
+                    [Module | Acc];
+                _ ->
+                    unknown_extension_error(Source)
+            end
+        end,
+        [],
+        Sources
+    ),
+    lists:usort(Modules).
+
+-spec unknown_extension_error(File) -> no_return() when File :: filename().
+unknown_extension_error(File) ->
+    Msg = io_lib:format("unsupported extension for source ~ts", [File]),
+    erlang:error(
+        {abort, Msg}
+    ).
+
+-spec open_file_error(File, Error) -> no_return() when
+    File :: filename(),
+    Error :: term().
+open_file_error(File, Error) ->
+    Msg = io_lib:format("cannot open file ~ts: ~tp", [File, Error]),
+    erlang:error(
+        {abort, Msg}
+    ).
+
+-spec file_corrupt_error(File, Contents) -> no_return() when
+    File :: filename(),
+    Contents :: term().
+file_corrupt_error(File, Contents) ->
+    Msg = io_lib:format("corrupt information in ~ts: ~tp", [File, Contents]),
+    erlang:error(
+        {abort, Msg}
+    ).
+
+-spec value_match_error(AppName, Wrong, Default) -> no_return() when
+    AppName :: binary(),
+    Wrong :: {atom(), term()},
+    Default :: {atom(), term()}.
+value_match_error(AppName, Wrong = {_, Value1}, Default = {_, Value2}) when
+    is_list(Value1) andalso is_list(Value2)
+->
+    case io_lib:printable_list(Value1) andalso io_lib:printable_list(Value2) of
+        true -> value_match_error_scalar(AppName, Wrong, Default);
+        false -> value_match_error_diff(AppName, Wrong, Default)
+    end;
+value_match_error(AppName, Wrong, Default) ->
+    value_match_error_scalar(AppName, Wrong, Default).
+
+value_match_error_diff(AppName, {FieldName, Value1}, {FieldName, Value2}) ->
+    Diff = diff_list(Value1, Value2),
+    Msg = io_lib:format(
+        ("error when building ~ts.app for application ~ts: the field ~ts in "
+        "the app.src template does not match with the target definition"),
+        [
+            AppName, AppName, FieldName
+        ]
+    ),
+    erlang:error(
+        {abort, [Msg, "\n", Diff]}
+    ).
+
+value_match_error_scalar(AppName, {FieldName, Value1}, {FieldName, Value2}) ->
+    Msg = io_lib:format(
+        ("error when building ~ts.app for application ~ts: the field ~ts in the "
+        "app.src template (~tp) does not match with the target definition (~tp)"),
+        [
+            AppName, AppName, FieldName, Value1, Value2
+        ]
+    ),
+    erlang:error(
+        {abort, Msg}
+    ).
+
+-spec applications_type_error(AppName, Applications) -> no_return() when
+    AppName :: binary(),
+    Applications :: term().
+applications_type_error(AppName, Applications) ->
+    Msg = io_lib:format(
+        "error when building ~ts.app for application ~ts: require a list for applications value but got ~tw instead",
+        [
+            AppName, AppName, Applications
+        ]
+    ),
+    erlang:error(
+        {abort, Msg}
+    ).
+
+-spec parse_error(AppName, String, Description) -> no_return() when
+    AppName :: binary(),
+    String :: string(),
+    Description :: iolist().
+parse_error(AppName, String, Description) ->
+    Msg = io_lib:format(
+        "error when building ~ts.app for application ~ts: could not parse value for ~ts: `~tp`",
+        [
+            AppName, AppName, Description, String
+        ]
+    ),
+    erlang:error(
+        {abort, Msg}
+    ).
+
+diff_list(AppSrcValue, TargetValue) ->
+    LCS = lcs(AppSrcValue, TargetValue),
+    DiffSpec = construct_diff_spec(LCS, AppSrcValue, TargetValue, []),
+    construct_diff(DiffSpec).
+
+construct_diff_spec([], [], [], Acc) ->
+    lists:reverse(Acc);
+construct_diff_spec([], [RemoveItem | AppSrcValue], TargetValue, Acc) ->
+    construct_diff_spec([], AppSrcValue, TargetValue, [{remove, RemoveItem} | Acc]);
+construct_diff_spec([], [], [AddItem | TargetValue], Acc) ->
+    construct_diff_spec([], [], TargetValue, [{add, AddItem} | Acc]);
+construct_diff_spec(
+    [CommonItem | LCS], [CommonItem | AppSrcValue], [CommonItem | TargetValue], Acc
+) ->
+    NewAcc =
+        case Acc of
+            [{common, N, CommonItems} | Rest] ->
+                [{common, N + 1, [CommonItem | CommonItems]} | Rest];
+            _ ->
+                [{common, 1, [CommonItem]} | Acc]
+        end,
+    construct_diff_spec(LCS, AppSrcValue, TargetValue, NewAcc);
+construct_diff_spec([CommonItem | _] = LCS, [RemoveItem | AppSrcValue], TargetValue, Acc) when
+    CommonItem =/= RemoveItem
+->
+    construct_diff_spec(LCS, AppSrcValue, TargetValue, [{remove, RemoveItem} | Acc]);
+construct_diff_spec([CommonItem | _] = LCS, AppSrcValue, [AddItem | TargetValue], Acc) when
+    CommonItem =/= AddItem
+->
+    construct_diff_spec(LCS, AppSrcValue, TargetValue, [{add, AddItem} | Acc]).
+
+% 10 spaces
+-define(LPAD, "          ").
+% 28 spaces
+-define(MPAD, "                            ").
+% 45 spaces
+-define(RPAD, "                                             ").
+
+construct_diff(Spec) ->
+    Header = [
+        io_lib:format("           .app.src                           buck2 target~n", []),
+        io_lib:format("           ========                           ============~n", [])
+    ],
+    construct_diff(Spec, Header).
+
+construct_diff(L, Header) ->
+    Diff =
+        [
+            case E of
+                {common, N, Items} when N < 5 ->
+                    [io_lib:format(" ~ts~ts~n", [?MPAD, format_item(Item)]) || Item <- Items];
+                {common, N, Items} ->
+                    [Last | _] = Items,
+                    First = lists:last(Items),
+                    [
+                        io_lib:format(" ~ts~ts~n", [?MPAD, format_item(First)]),
+                        io_lib:format(" ~ts~ts~n", [?MPAD, io_lib:format("... ~b more ...", [N - 2])]),
+                        io_lib:format(" ~ts~ts~n", [?MPAD, format_item(Last)])
+                    ];
+                {remove, Item} ->
+                    io_lib:format("<~ts~ts~n", [?LPAD, format_item(Item)]);
+                {add, Item} ->
+                    io_lib:format(">~ts~ts~n", [?RPAD, format_item(Item)])
+            end
+         || E <- L
+        ],
+    [Header | Diff].
+
+format_item(Item) ->
+    S = io_lib:format("~tw", [Item]),
+    case string:length(S) > 30 of
+        true ->
+            io_lib:format("~.27ts...", [S]);
+        false ->
+            io_lib:format("~.30ts", [S])
+    end.
+
+%% longest common subsequence from http://rosettacode.org/wiki/Longest_common_subsequence#Erlang
+lcs_length([] = S, T, Cache) ->
+    {0, maps:put({S, T}, 0, Cache)};
+lcs_length(S, [] = T, Cache) ->
+    {0, maps:put({S, T}, 0, Cache)};
+lcs_length([H | ST] = S, [H | TT] = T, Cache) ->
+    {L, C} = lcs_length(ST, TT, Cache),
+    {L + 1, maps:put({S, T}, L + 1, C)};
+lcs_length([_SH | ST] = S, [_TH | TT] = T, Cache) ->
+    case maps:is_key({S, T}, Cache) of
+        true ->
+            {maps:get({S, T}, Cache), Cache};
+        false ->
+            {L1, C1} = lcs_length(S, TT, Cache),
+            {L2, C2} = lcs_length(ST, T, C1),
+            L = max(L1, L2),
+            {L, maps:put({S, T}, L, C2)}
+    end.
+
+lcs(S, T) ->
+    {_, C} = lcs_length(S, T, #{}),
+    lcs(S, T, C, []).
+
+lcs([], _, _, Acc) ->
+    lists:reverse(Acc);
+lcs(_, [], _, Acc) ->
+    lists:reverse(Acc);
+lcs([H | ST], [H | TT], Cache, Acc) ->
+    lcs(ST, TT, Cache, [H | Acc]);
+lcs([_SH | ST] = S, [_TH | TT] = T, Cache, Acc) ->
+    case maps:get({S, TT}, Cache) > maps:get({ST, T}, Cache) of
+        true ->
+            lcs(S, TT, Cache, Acc);
+        false ->
+            lcs(ST, T, Cache, Acc)
+    end.
+
+-spec add_metadata(Props, Metadata) -> proplists:proplist() when
+    Props :: proplists:proplist(),
+    Metadata :: metadata().
+add_metadata(Props, Metadata) ->
+    ok = verify_metadata(Props, Metadata),
+    Props ++ maps:to_list(maps:iterator(Metadata, ordered)).
+
+-spec verify_metadata(Props, Metadata) -> ok when
+    Props :: proplists:proplist(),
+    Metadata :: metadata().
+verify_metadata([], _) ->
+    ok;
+verify_metadata([{K, V0} | T], Metadata) ->
+    case maps:get(K, Metadata, undefined) of
+        undefined ->
+            verify_metadata(T, Metadata);
+        V1 ->
+            case V0 =:= V1 of
+                true ->
+                    verify_metadata(T, Metadata);
+                false ->
+                    erlang:error(metadata_not_compatible, [{K, V0}, {K, V1}])
+            end
+    end.
diff --git a/buck2/prelude/erlang/toolchain/appup_src_builder.erl b/buck2/prelude/erlang/toolchain/appup_src_builder.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/appup_src_builder.erl
@@ -0,0 +1,175 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(appup_src_builder).
+-moduledoc """
+Build an .appup file from a given .appup.src template.
+
+usage:
+  appup_src_builder.escript appup_info.json output.appup
+
+appup_info.json format:
+
+ #{
+     <<"name">>         := <application_name>,
+     <<"template">>     := <path to an .appup.src file>,
+     <<"version">>      := <version string>,
+     <<"app_src_vsn">>  := <placeholder string used in the template's vsn field>
+ }
+
+The .appup.src template is expected to contain a single Erlang term of the form
+`{Vsn, UpInstructions, DownInstructions}`. When `Vsn` matches the configured
+placeholder (either as an atom or as a string), it is substituted with the
+buck-supplied `version`. Otherwise it must already equal `version`.
+""".
+
+-export([main/1]).
+
+-type filename() :: binary().
+-type appup_info() :: #{
+    name := binary(),
+    template := filename(),
+    version := binary(),
+    app_src_vsn := binary()
+}.
+
+-spec main(Args) -> ok when Args :: [string()].
+main([AppupInfoFile, Output]) ->
+    try
+        do(dependency_utils:chars_to_binary(AppupInfoFile), dependency_utils:chars_to_binary(Output))
+    catch
+        Type:{abort, Reason} ->
+            io:format(standard_error, "~ts:~ts~n", [Type, Reason]),
+            erlang:halt(1)
+    end;
+main(_) ->
+    usage().
+
+-spec usage() -> ok.
+usage() ->
+    io:format("appup_src_builder.escript appup_info.json output.appup~n").
+
+-spec do(AppupInfoFile, Output) -> ok when
+    AppupInfoFile :: filename(),
+    Output :: filename().
+do(AppupInfoFile, Output) ->
+    #{
+        name := Name,
+        template := Template,
+        version := Version,
+        app_src_vsn := AppSrcVsn
+    } = parse_appup_info(AppupInfoFile),
+    Term = consult_template(Name, Template),
+    Substituted = substitute_vsn(Name, Term, Version, AppSrcVsn),
+    ToWrite = io_lib:format("~tp.~n", [Substituted]),
+    ok = prim_file:write_file(Output, ToWrite).
+
+-spec parse_appup_info(AppupInfoFile) -> appup_info() when AppupInfoFile :: filename().
+parse_appup_info(AppupInfoFile) ->
+    case prim_file:read_file(AppupInfoFile) of
+        {ok, Content} ->
+            case json:decode(Content) of
+                #{
+                    <<"name">> := Name,
+                    <<"template">> := Template,
+                    <<"version">> := Version,
+                    <<"app_src_vsn">> := AppSrcVsn
+                } ->
+                    #{
+                        name => Name,
+                        template => Template,
+                        version => Version,
+                        app_src_vsn => AppSrcVsn
+                    };
+                Terms ->
+                    file_corrupt_error(AppupInfoFile, Terms)
+            end;
+        Error ->
+            open_file_error(AppupInfoFile, Error)
+    end.
+
+-spec consult_template(Name, TemplateFile) -> term() when
+    Name :: binary(),
+    TemplateFile :: filename().
+consult_template(Name, TemplateFile) ->
+    case file:consult(TemplateFile) of
+        {ok, [Term]} -> Term;
+        {ok, Terms} -> file_corrupt_error(TemplateFile, Terms);
+        {error, Reason} -> consult_error(Name, TemplateFile, Reason)
+    end.
+
+-spec substitute_vsn(Name, Term, Version, AppSrcVsn) -> term() when
+    Name :: binary(),
+    Term :: term(),
+    Version :: binary(),
+    AppSrcVsn :: binary().
+substitute_vsn(Name, {Vsn, UpInstructions, DownInstructions}, Version, AppSrcVsn) ->
+    VersionStr = binary_to_list(Version),
+    case is_app_src_vsn(Vsn, AppSrcVsn) orelse Vsn =:= VersionStr of
+        true -> {VersionStr, UpInstructions, DownInstructions};
+        false -> vsn_mismatch_error(Name, Vsn, Version, AppSrcVsn)
+    end;
+substitute_vsn(Name, Term, _Version, _AppSrcVsn) ->
+    template_shape_error(Name, Term).
+
+-spec is_app_src_vsn(Vsn, AppSrcVsn) -> boolean() when
+    Vsn :: term(),
+    AppSrcVsn :: binary().
+is_app_src_vsn(Vsn, AppSrcVsn) when is_atom(Vsn) ->
+    atom_to_binary(Vsn) =:= AppSrcVsn;
+is_app_src_vsn(Vsn, AppSrcVsn) when is_list(Vsn) ->
+    Vsn =:= binary_to_list(AppSrcVsn);
+is_app_src_vsn(_, _) ->
+    false.
+
+-spec open_file_error(File, Error) -> no_return() when
+    File :: filename(),
+    Error :: term().
+open_file_error(File, Error) ->
+    Msg = io_lib:format("cannot open file ~ts: ~tp", [File, Error]),
+    erlang:error({abort, Msg}).
+
+-spec file_corrupt_error(File, Contents) -> no_return() when
+    File :: filename(),
+    Contents :: term().
+file_corrupt_error(File, Contents) ->
+    Msg = io_lib:format("corrupt information in ~ts: ~tp", [File, Contents]),
+    erlang:error({abort, Msg}).
+
+-spec consult_error(Name, File, Reason) -> no_return() when
+    Name :: binary(),
+    File :: filename(),
+    Reason :: term().
+consult_error(Name, File, Reason) ->
+    Msg = io_lib:format(
+        "error when building ~ts.appup for application ~ts: cannot read template ~ts: ~tp",
+        [Name, Name, File, Reason]
+    ),
+    erlang:error({abort, Msg}).
+
+-spec template_shape_error(Name, Term) -> no_return() when
+    Name :: binary(),
+    Term :: term().
+template_shape_error(Name, Term) ->
+    Msg = io_lib:format(
+        "error when building ~ts.appup for application ~ts: expected template to be {Vsn, UpInstructions, DownInstructions}, got: ~tp",
+        [Name, Name, Term]
+    ),
+    erlang:error({abort, Msg}).
+
+-spec vsn_mismatch_error(Name, Vsn, Version, AppSrcVsn) -> no_return() when
+    Name :: binary(),
+    Vsn :: term(),
+    Version :: binary(),
+    AppSrcVsn :: binary().
+vsn_mismatch_error(Name, Vsn, Version, AppSrcVsn) ->
+    Msg = io_lib:format(
+        "error when building ~ts.appup for application ~ts: template vsn (~tp) is neither the placeholder (~ts) nor the target version (~ts)",
+        [Name, Name, Vsn, AppSrcVsn, Version]
+    ),
+    erlang:error({abort, Msg}).
diff --git a/buck2/prelude/erlang/toolchain/boot_script_builder.erl b/buck2/prelude/erlang/toolchain/boot_script_builder.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/boot_script_builder.erl
@@ -0,0 +1,282 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(boot_script_builder).
+-author("loscher@fb.com").
+-moduledoc """
+Build the release resource file, and boot scripts from a given spec file. The spec file format
+is defined in erlang_release.bzl
+
+usage:
+  boot_script_builder.escript release_spec.term output_dir
+""".
+
+-export([main/1]).
+
+-define(EXITSUCCESS, 0).
+-define(EXITERROR, 1).
+
+-spec main([string()]) -> ok.
+main([ReleaseSpec, OutDir]) ->
+    try
+        do(ReleaseSpec, OutDir),
+        erlang:halt(?EXITSUCCESS)
+    catch
+        Type:{abort, Reason} ->
+            io:format(standard_error, "~ts:~ts~n", [Type, Reason]),
+            erlang:halt(?EXITERROR)
+    end;
+main(_) ->
+    usage().
+
+-spec usage() -> ok.
+usage() ->
+    io:format("boot_script_builder.escript release_spec.term output_dir~n").
+
+do(SpecFile, OutDir) ->
+    {ok, SpecFileContents} = file:read_file(SpecFile, [raw]),
+    #{
+        <<"apps">> := Apps,
+        <<"lib_dir">> := LibDir,
+        <<"name">> := RelNameBin,
+        <<"version">> := RelVersionBin
+    } = json:decode(SpecFileContents),
+    OTPAppMapping = get_otp_apps_mapping(),
+    LibDirWildcard = binary_to_list(filename:absname(filename:join([LibDir, "*", "ebin"]))),
+
+    %% systools requires us to be in the same directory as the .rel file
+    %% it also magically discovers the release root and makes all paths
+    %% relative to it if the structure is OTP compliant
+    ok = filelib:ensure_path(OutDir),
+    ok = file:set_cwd(OutDir),
+
+    RelName = binary_to_list(RelNameBin),
+    RelVersion = binary_to_list(RelVersionBin),
+    build_no_dot_erlang_boot(Apps, [LibDirWildcard], RelName, RelVersion, OTPAppMapping),
+    build_start_boot(Apps, [LibDirWildcard], RelName, RelVersion, OTPAppMapping).
+
+build_no_dot_erlang_boot(
+    Apps,
+    PathOption,
+    RelName,
+    RelVersion,
+    OTPAppMapping
+) ->
+    {OTPApps, _Others} = lists:partition(
+        fun(#{<<"resolved">> := Resolved}) -> not Resolved end,
+        Apps
+    ),
+
+    % Extract kernel version from OTPApps
+    Kernel =
+        case
+            lists:search(
+                fun(#{<<"name">> := Name}) -> Name =:= <<"kernel">> end,
+                OTPApps
+            )
+        of
+            {value, _} ->
+                #{<<"kernel">> := #{version := KernelVersion}} = OTPAppMapping,
+                {kernel, binary_to_list(KernelVersion)};
+            false ->
+                error({abort, "kernel version not found in OTPApps"})
+        end,
+
+    % Extract stdlib version from OTPApps
+    StdLib =
+        case
+            lists:search(
+                fun(#{<<"name">> := Name}) -> Name =:= <<"stdlib">> end,
+                OTPApps
+            )
+        of
+            {value, _} ->
+                #{<<"stdlib">> := #{version := StdLibVersion}} = OTPAppMapping,
+                {stdlib, binary_to_list(StdLibVersion)};
+            false ->
+                error({abort, "stdlib version not found in OTPApps"})
+        end,
+
+    RelFileContent = {
+        release,
+        {RelName, RelVersion},
+        {erts, erlang:system_info(version)},
+        [Kernel, StdLib]
+    },
+
+    make_boot_script(RelName, RelFileContent, [
+        no_warn_sasl,
+        no_dot_erlang,
+        {script_name, "no_dot_erlang"},
+        {path, PathOption}
+    ]).
+
+build_start_boot(
+    Apps,
+    PathOption,
+    RelName,
+    RelVersion,
+    OTPAppMapping
+) ->
+    %% OTP apps dependencies are not captures and we need to calculate
+    %% them first
+    {OTPApps, Others} = lists:partition(
+        fun(#{<<"resolved">> := Resolved}) -> not Resolved end,
+        Apps
+    ),
+    OTPAppDeps = get_otp_app_deps(OTPApps, OTPAppMapping),
+
+    %% rel file content
+    RelFileContent = {
+        release,
+        {RelName, RelVersion},
+        {erts, erlang:system_info(version)},
+        [
+            case StartType of
+                <<"permanent">> -> {binary_to_atom(AppName), binary_to_list(AppVersion)};
+                <<"load">> -> {binary_to_atom(AppName), binary_to_list(AppVersion), load}
+            end
+         || #{
+                <<"name">> := AppName,
+                <<"version">> := AppVersion,
+                <<"type">> := StartType
+            } <- OTPAppDeps ++ Others
+        ]
+    },
+    make_boot_script(RelName, RelFileContent, [
+        no_warn_sasl,
+        no_dot_erlang,
+        {script_name, "start"},
+        {path, PathOption}
+    ]).
+
+make_boot_script(RelName, RelFileContent, Options) ->
+    ok = write_file(
+        io_lib:format("~ts.rel", [RelName]),
+        io_lib:format("~tp.", [RelFileContent])
+    ),
+    case systools:make_script(RelName, Options) of
+        ok ->
+            ok;
+        Error ->
+            error({abort, Error})
+    end.
+
+get_otp_apps_mapping() ->
+    lists:foldl(
+        fun(Path, Acc) ->
+            case parse_app_path(Path) of
+                skip ->
+                    Acc;
+                [AppName, AppVersion] ->
+                    Acc#{
+                        list_to_binary(AppName) => #{
+                            version => list_to_binary(AppVersion),
+                            app_file => app_file_path(Path, AppName)
+                        }
+                    }
+            end
+        end,
+        #{},
+        code:get_path()
+    ).
+
+get_otp_app_deps(OTPApps, OTPAppMapping) ->
+    InitialDeps = [
+        Dependency
+     || #{<<"name">> := AppName} <- OTPApps,
+        Dependency <- begin
+            #{AppName := #{app_file := AppFile, version := AppVersion}} = OTPAppMapping,
+            #{name := AppName, version := AppVersion, deps := Dependencies} = parse_app_file(
+                AppFile
+            ),
+            Dependencies
+        end
+    ],
+
+    InitialAcc = lists:foldl(
+        fun(UnVersionedSpec = #{<<"name">> := AppName}, Acc) ->
+            % get specific version from toolchain
+            #{AppName := #{version := AppVersion}} = OTPAppMapping,
+            % replace dynamic version with specific one
+            VersionedSpec = UnVersionedSpec#{<<"version">> => AppVersion},
+            Acc#{binary_to_atom(AppName) => VersionedSpec}
+        end,
+        #{},
+        OTPApps
+    ),
+
+    get_otp_app_deps(InitialDeps, OTPAppMapping, InitialAcc).
+
+get_otp_app_deps([], _, Acc) ->
+    maps:values(Acc);
+get_otp_app_deps([App | Rest], OTPAppMapping, Acc) ->
+    AppName = atom_to_binary(App),
+    #{AppName := #{app_file := AppFile, version := AppVersion}} = OTPAppMapping,
+    #{name := AppName, version := AppVersion, deps := Dependencies} = parse_app_file(AppFile),
+    Spec = #{
+        <<"name">> => AppName,
+        <<"version">> => AppVersion,
+        <<"type">> => <<"permanent">>
+    },
+    FilteredDependencies = [Dep || Dep <- Dependencies, not is_map_key(Dep, Acc)],
+    get_otp_app_deps(Rest ++ FilteredDependencies, OTPAppMapping, Acc#{App => Spec}).
+
+app_file_path(Path, Name) ->
+    AppFile = unicode:characters_to_list(io_lib:format("~ts.app", [Name])),
+    filename:join(Path, AppFile).
+
+parse_app_path(Path) ->
+    case string:prefix(Path, [code:lib_dir(), "/"]) of
+        nomatch ->
+            skip;
+        RelPath ->
+            case filename:split(RelPath) of
+                [AppFolder, "ebin"] ->
+                    string:split(AppFolder, "-");
+                _ ->
+                    skip
+            end
+    end.
+
+parse_app_file(File) ->
+    io:format("~ts~n", [File]),
+    {ok, [{application, App, Props}]} =
+        file:consult(File),
+    AppName = atom_to_binary(App),
+    Version = list_to_binary(proplists:get_value(vsn, Props)),
+    Dependencies =
+        proplists:get_value(applications, Props, []) ++
+            proplists:get_value(included_applications, Props, []),
+    #{
+        name => AppName,
+        version => Version,
+        deps => Dependencies
+    }.
+
+-spec write_file(file:name_all() | iodata(), iolist()) -> string().
+write_file(File, Data) ->
+    case
+        % We write in raw mode because this is a standalone escript, so we don't
+        % need advanced file server features, and we gain performance by avoiding
+        % calling through the file server
+        file:open(File, [write, binary, raw])
+    of
+        {ok, Handle} ->
+            try
+                % We use file:pwrite instead of file:write_file to work around
+                % the latter needlessly flattening iolists (as returned by
+                % json:encode/1, etc.) to a binary
+                file:pwrite(Handle, 0, Data)
+            after
+                file:close(Handle)
+            end,
+            ok;
+        {error, _} = Error ->
+            Error
+    end.
diff --git a/buck2/prelude/erlang/toolchain/dependency_analyzer.erl b/buck2/prelude/erlang/toolchain/dependency_analyzer.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/dependency_analyzer.erl
@@ -0,0 +1,188 @@
+%% @format
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(dependency_analyzer).
+-author("loscher@fb.com").
+-moduledoc """
+ Extract direct dependencies from a given erl or hrl file
+
+ usage:
+   dependency_analyzer.escript some_file.(h|e)rl [out.term]
+
+ The output of the tool is written either to stdout,
+ or a given output file. The format is as follows and intended to
+ be consumed by other binary_to_term/1:
+```
+ [#{type := include
+            | include_lib
+            | behaviour
+            | parse_transform
+            | manual_dependency
+            | doc_file,
+  file  := <<"header_or_source_file.(h|e)rl">>,
+  app   => application %% only for include_lib
+  },
+  ...
+ ].
+```
+""".
+
+-export([main/1]).
+
+-type entry() ::
+    #{type := include, file := binary()}
+    | #{type := include_lib, file := binary(), app := binary()}
+    | #{type := behaviour, file := binary()}
+    | #{type := parse_transform, file := binary()}
+    | #{type := manual_dependency, file := binary()}
+    | #{type := doc_file, file := binary()}.
+
+-spec main([string()]) -> ok.
+main([InFile]) ->
+    do(InFile, stdout);
+main([InFile, OutFile]) ->
+    do(InFile, {file, OutFile});
+main(_) ->
+    usage(),
+    erlang:halt(1).
+
+-spec usage() -> ok.
+usage() ->
+    io:format("dependency_analyzer.escript some_file.(h|e)rl [out.term]").
+
+-spec do(InFile, OutSpec) -> ok when
+    InFile :: file:filename(),
+    OutSpec :: {file, file:filename()} | stdout.
+do(InFile0, OutSpec) ->
+    InFile = dependency_utils:chars_to_binary(InFile0),
+    {ok, File} = file:open(InFile, [read, raw, binary, read_ahead]),
+    try
+        Dependencies = lists:sort(scan_file(File, [], [], 1, [])),
+        case OutSpec of
+            {file, OutFile0} ->
+                OutData = erlang:term_to_binary(Dependencies, [deterministic]),
+                OutFile = dependency_utils:chars_to_binary(OutFile0),
+                ok = prim_file:write_file(OutFile, OutData);
+            stdout ->
+                io:format("~tp~n", [Dependencies])
+        end
+    after
+        ok = file:close(File)
+    end.
+
+-spec scan_file(File, Cont, Chars, Loc, Acc) -> [entry()] when
+    File :: file:io_device(),
+    Cont :: erl_scan:return_cont(),
+    Chars :: string(),
+    Loc :: erl_anno:location(),
+    Acc :: [entry()].
+scan_file(File, Cont, Chars, Loc, Acc) ->
+    case erl_scan:tokens(Cont, Chars, Loc) of
+        {done, {ok, Tokens, NextLoc}, Rest} ->
+            scan_file(File, [], Rest, NextLoc, extract_dependencies(Tokens) ++ Acc);
+        {done, {error, _ErrInfo, NextLoc}, Rest} ->
+            scan_file(File, [], Rest, NextLoc, Acc);
+        {done, {eof, _NextLoc}, _Rest} ->
+            Acc;
+        {more, NewCont} ->
+            case file:read_line(File) of
+                {ok, Bin} ->
+                    scan_file(File, NewCont, to_charlist(Bin), Loc, Acc);
+                eof ->
+                    case erl_scan:tokens(NewCont, eof, Loc) of
+                        {done, {ok, Tokens, _}, _} -> extract_dependencies(Tokens) ++ Acc;
+                        _ -> Acc
+                    end
+            end
+    end.
+
+-spec extract_dependencies(Tokens) -> [entry()] when
+    Tokens :: [erl_scan:token()].
+extract_dependencies([{'-', _}, {atom, _, Name} | Rest]) when
+    Name =:= include orelse
+        Name =:= include_lib orelse
+        Name =:= behaviour orelse
+        Name =:= behavior orelse
+        Name =:= doc orelse
+        Name =:= moduledoc orelse
+        Name =:= compile orelse
+        Name =:= build_dependencies
+->
+    case parse_attribute_value(Name, Rest) of
+        {include, MaybePath} when is_list(MaybePath) ->
+            [#{type => include, file => filename:basename(F)} || {ok, F} <- [try_characters_to_binary(MaybePath)]];
+        {include_lib, MaybePath} when is_list(MaybePath) ->
+            case try_characters_to_binary(MaybePath) of
+                {ok, Path} ->
+                    case filename:split(Path) of
+                        [App, <<"include">>, Include] -> [#{type => include_lib, app => App, file => Include}];
+                        _ -> error(malformed_header_include_lib)
+                    end;
+                error ->
+                    []
+            end;
+        {behaviour, M} when is_atom(M) ->
+            [#{type => behaviour, file => module_to_erl(M)}];
+        {behavior, M} when is_atom(M) ->
+            [#{type => behaviour, file => module_to_erl(M)}];
+        {doc, {file, MaybePath}} when is_list(MaybePath) ->
+            [#{type => doc_file, file => F} || {ok, F} <- [try_characters_to_binary(MaybePath)]];
+        {moduledoc, {file, MaybePath}} when is_list(MaybePath) ->
+            [#{type => doc_file, file => F} || {ok, F} <- [try_characters_to_binary(MaybePath)]];
+        {compile, Term} ->
+            [#{type => parse_transform, file => module_to_erl(M)} || M <- collect_parse_transforms(Term)];
+        {build_dependencies, Modules} when is_list(Modules) ->
+            [#{type => manual_dependency, file => module_to_erl(M)} || M <- Modules, is_atom(M)];
+        _ ->
+            []
+    end;
+extract_dependencies(_) ->
+    [].
+
+-spec parse_attribute_value(Name, Tokens) -> {Name, Value} | error when
+    Name :: atom(),
+    Tokens :: [erl_scan:token()],
+    Value :: term().
+parse_attribute_value(Name, Tokens) ->
+    case erl_parse:parse_term(Tokens) of
+        {ok, Term} -> {Name, Term};
+        {error, _} -> error
+    end.
+
+-spec module_to_erl(Module) -> binary() when
+    Module :: module().
+module_to_erl(Module) ->
+    <<(atom_to_binary(Module))/binary, ".erl"/utf8>>.
+
+-spec to_charlist(Bin) -> string() when
+    Bin :: binary().
+to_charlist(Bin) ->
+    case unicode:characters_to_list(Bin) of
+        L when is_list(L) -> L;
+        _ -> binary_to_list(Bin)
+    end.
+
+-spec try_characters_to_binary(Value) -> {ok, binary()} | error when
+    Value :: term().
+try_characters_to_binary(Value) ->
+    try unicode:characters_to_binary(Value) of
+        B when is_binary(B) -> {ok, B};
+        _ -> error
+    catch
+        _:_ -> error
+    end.
+
+-spec collect_parse_transforms(Term) -> [module()] when
+    Term :: term().
+collect_parse_transforms({parse_transform, M}) when is_atom(M) ->
+    [M];
+collect_parse_transforms(L) when is_list(L) ->
+    [M || {parse_transform, M} <- L, is_atom(M)];
+collect_parse_transforms(_) ->
+    [].
diff --git a/buck2/prelude/erlang/toolchain/dependency_finalizer.erl b/buck2/prelude/erlang/toolchain/dependency_finalizer.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/dependency_finalizer.erl
@@ -0,0 +1,139 @@
+%%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%%
+%%% This source code is licensed under both the MIT license found in the
+%%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%%% of this source tree.
+
+%% @format
+-module(dependency_finalizer).
+-author("loscher@meta.com").
+
+-export([main/1]).
+
+%% Layers of application -> merged dep file, outermost first. The keys are unused;
+%% the layering exists so the caller can pass its own entries alongside the ones it
+%% inherits without merging maps sized by its transitive closure.
+-type dep_files_data() :: [#{filename() => filename()}].
+
+-type filename() :: binary().
+
+-spec main([string()]) -> ok | no_return().
+main([Source, InFile]) ->
+    do(Source, InFile, stdout);
+main([Source, InFile, OutFile]) ->
+    do(Source, InFile, {file, OutFile});
+main(_) ->
+    usage(),
+    erlang:halt(1).
+
+-spec usage() -> ok.
+usage() ->
+    io:format("~ts.escript source_dep_file.dep dependency_spec.term [out.json]", [?MODULE]).
+
+-spec do(file:filename(), file:filename(), {file, file:filename()} | stdout) -> ok.
+do(Source0, InFile0, OutSpec) ->
+    Source = dependency_utils:chars_to_binary(Source0),
+    InFile = dependency_utils:chars_to_binary(InFile0),
+    try
+        case read_file(InFile) of
+            {ok, DepFileLayers} ->
+                FlatDepFiles = lists:foldl(
+                    fun(Layer, Acc) -> maps:fold(fun merge_deps/3, Acc, Layer) end, #{}, DepFileLayers
+                ),
+                Dependencies = build_dep_info(Source, FlatDepFiles),
+                OutData = json:encode(Dependencies),
+                case OutSpec of
+                    {file, File0} ->
+                        ok = prim_file:write_file(dependency_utils:chars_to_binary(File0), OutData);
+                    stdout ->
+                        io:format("~ts~n", [OutData])
+                end;
+            Err ->
+                io:format(standard_error, "error, could no parse file correctly: ~tp~n", [Err]),
+                erlang:halt(1)
+        end
+    catch
+        Class:Reason:Stack ->
+            io:format(standard_error, "~ts", [erl_error:format_exception(Class, Reason, Stack)]),
+            erlang:halt(1)
+    end.
+
+merge_deps(_File, DepFile, Acc) ->
+    case read_file_term(DepFile) of
+        {ok, Dependencies} ->
+            maps:merge(Dependencies, Acc);
+        Err ->
+            io:format(standard_error, "error, could no parse file correctly: ~tp~n", [Err]),
+            erlang:halt(1)
+    end.
+
+-spec read_file(filename()) -> {ok, dep_files_data()} | {error, term()}.
+read_file(File) ->
+    case prim_file:read_file(File) of
+        {ok, Data} ->
+            {ok, json:decode(Data)};
+        Err ->
+            Err
+    end.
+
+-spec read_file_term(filename()) -> {ok, dep_files_data()} | {error, term()}.
+read_file_term(File) ->
+    case prim_file:read_file(File) of
+        {ok, Data} ->
+            {ok, erlang:binary_to_term(Data)};
+        Err ->
+            Err
+    end.
+
+-spec build_dep_info(filename(), dep_files_data()) -> list(map()).
+build_dep_info(Source, DepFiles) ->
+    case read_file_term(Source) of
+        {ok, Dependencies} ->
+            Basename = filename:basename(Source, ~".dep"),
+            Key = <<Basename/binary, ".erl"/utf8>>,
+            {NextKeys, NextVisited, NextAcc} = collect_dependencies_for_key(
+                Dependencies, Key, [], sets:new([{version, 2}]), []
+            ),
+            collect_dependencies(NextKeys, DepFiles, NextVisited, NextAcc);
+        Err ->
+            io:format(standard_error, "error, could no parse file correctly: ~tp~n", [Err]),
+            erlang:halt(1)
+    end.
+
+collect_dependencies([], _, _, Acc) ->
+    Acc;
+collect_dependencies([Key | Rest], DepFiles, Visited, Acc) ->
+    case DepFiles of
+        #{Key := DepBin} ->
+            Dependencies = erlang:binary_to_term(DepBin),
+            {NextKeys, NextVisited, NextAcc} =
+                collect_dependencies_for_key(Dependencies, Key, Rest, Visited, Acc),
+            collect_dependencies(
+                NextKeys,
+                DepFiles,
+                NextVisited,
+                NextAcc
+            );
+        _ ->
+            %% We cannot find key in DepFiles, which means it's from OTP or missing
+            %% We don't add anything to the dependencies and let the compiler fail for a proper error message.
+            collect_dependencies(Rest, DepFiles, Visited, Acc)
+    end.
+
+collect_dependencies_for_key([], _CurrentKey, KeysAcc, VisitedAcc, DepAcc) ->
+    {KeysAcc, VisitedAcc, DepAcc};
+collect_dependencies_for_key([#{file := File, type := Type} = Dep | Deps], CurrentKey, KeysAcc, VisitedAcc, DepAcc) ->
+    NextKey = File,
+    case sets:is_element(NextKey, VisitedAcc) of
+        true ->
+            collect_dependencies_for_key(Deps, CurrentKey, KeysAcc, VisitedAcc, DepAcc);
+        false when Type =:= include; Type =:= include_lib ->
+            collect_dependencies_for_key(
+                Deps, CurrentKey, [NextKey | KeysAcc], sets:add_element(CurrentKey, VisitedAcc), [Dep | DepAcc]
+            );
+        false ->
+            collect_dependencies_for_key(Deps, CurrentKey, KeysAcc, sets:add_element(CurrentKey, VisitedAcc), [
+                Dep | DepAcc
+            ])
+    end.
diff --git a/buck2/prelude/erlang/toolchain/dependency_merger.erl b/buck2/prelude/erlang/toolchain/dependency_merger.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/dependency_merger.erl
@@ -0,0 +1,84 @@
+%%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%%
+%%% This source code is licensed under both the MIT license found in the
+%%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%%% of this source tree.
+
+%% @format
+-module(dependency_merger).
+
+-export([main/1]).
+
+-type filename() :: binary().
+
+-spec main([string()]) -> ok | no_return().
+main([OutFile, DepsFile, ExistingFile]) ->
+    do(OutFile, DepsFile, ExistingFile);
+main([OutFile, DepsFile]) ->
+    do(OutFile, DepsFile);
+main(_) ->
+    usage(),
+    erlang:halt(1).
+
+-spec usage() -> ok.
+usage() ->
+    io:format("escript ~ts.erl out.json deps.json already_unionized.dep", [?MODULE]).
+
+-spec do(file:filename(), file:filename(), file:filename()) -> ok.
+do(OutFile0, DepsFile0, ExistingFile0) ->
+    OutFile = dependency_utils:chars_to_binary(OutFile0),
+    DepsFile = dependency_utils:chars_to_binary(DepsFile0),
+    ExistingFile = dependency_utils:chars_to_binary(ExistingFile0),
+    case read_file_term(ExistingFile) of
+        {ok, Existing} ->
+            do_collect(OutFile, DepsFile, Existing);
+        Err ->
+            io:format(standard_error, "error, could no parse file correctly: ~tp~n", [Err]),
+            erlang:halt(1)
+    end.
+
+-spec do(file:filename(), file:filename()) -> ok.
+do(OutFile0, DepsFile0) ->
+    OutFile = dependency_utils:chars_to_binary(OutFile0),
+    DepsFile = dependency_utils:chars_to_binary(DepsFile0),
+    do_collect(OutFile, DepsFile, #{}).
+
+-spec do_collect(filename(), filename(), map()) -> ok.
+do_collect(OutFile, DepsFile, Existing) ->
+    case read_file(DepsFile) of
+        {ok, Deps} ->
+            AllCollected = maps:fold(fun collect_files/3, Existing, Deps),
+            Encoded = erlang:term_to_iovec(AllCollected, [deterministic]),
+            ok = prim_file:write_file(OutFile, Encoded);
+        Err ->
+            io:format(standard_error, "error, could no parse file correctly: ~tp~n", [Err]),
+            erlang:halt(1)
+    end.
+
+collect_files(File, DepFile, Acc) ->
+    case prim_file:read_file(DepFile) of
+        {ok, Bin} ->
+            Acc#{File => Bin};
+        Err ->
+            io:format(standard_error, "error, could not read file: ~tp~n", [Err]),
+            erlang:halt(1)
+    end.
+
+-spec read_file(filename()) -> {ok, map()} | {error, term()}.
+read_file(File) ->
+    case prim_file:read_file(File) of
+        {ok, Data} ->
+            {ok, json:decode(Data)};
+        Err ->
+            Err
+    end.
+
+-spec read_file_term(filename()) -> {ok, map()} | {error, term()}.
+read_file_term(File) ->
+    case prim_file:read_file(File) of
+        {ok, Data} ->
+            {ok, erlang:binary_to_term(Data)};
+        Err ->
+            Err
+    end.
diff --git a/buck2/prelude/erlang/toolchain/dependency_utils.erl b/buck2/prelude/erlang/toolchain/dependency_utils.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/dependency_utils.erl
@@ -0,0 +1,17 @@
+%%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%%
+%%% This source code is licensed under both the MIT license found in the
+%%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%%% of this source tree.
+
+%% @format
+-module(dependency_utils).
+
+-export([chars_to_binary/1]).
+
+-spec chars_to_binary(StringLike :: iodata()) -> binary().
+chars_to_binary(StringLike) ->
+    case unicode:characters_to_binary(StringLike) of
+        Bin when is_binary(Bin) -> Bin
+    end.
diff --git a/buck2/prelude/erlang/toolchain/escript_builder.erl b/buck2/prelude/erlang/toolchain/escript_builder.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/escript_builder.erl
@@ -0,0 +1,171 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(escript_builder).
+-author("loscher@fb.com").
+-moduledoc """
+Build an escript from a given spec file. The spec file format
+is defined in erlang_escript.bzl
+
+usage:
+  escript_builder.escript escript_build_spec.term
+""".
+
+-export([main/1]).
+
+-include_lib("kernel/include/file.hrl").
+
+-type escript_artifact_spec() :: #{
+    ArchivePath :: file:filename_all() => FileSystemPath :: file:filename_all()
+}.
+-type escript_load_spec() :: [{ArchivePath :: file:filename(), FileSystemPath :: file:filename()}].
+-type escript_archive_spec() :: [{ArchivePath :: file:filename(), binary()}].
+
+-spec main([string()]) -> ok.
+main([Spec]) ->
+    try
+        {ok, Contents} = file:read_file(Spec, [raw]),
+        Decoded = json:decode(Contents),
+        do(Decoded)
+    catch
+        Type:{abort, Reason} ->
+            io:format(standard_error, "~ts: ~ts~n", [Type, Reason]),
+            erlang:halt(1)
+    end;
+main(_) ->
+    usage().
+
+-spec usage() -> ok.
+usage() ->
+    io:format("escript_builder.escript build_spec.term ~n").
+
+-spec do(map()) -> ok.
+do(#{
+    <<"artifacts">> := Artifacts,
+    <<"emu_args">> := EmuArgs0,
+    <<"output">> := EscriptPath
+}) ->
+    ArchiveSpec = prepare_files(Artifacts),
+    Shebang = "/usr/bin/env escript",
+    Comment = "",
+    EmuArgs1 = [string:trim(Arg) || Arg <- EmuArgs0],
+    FinalEmuArgs = unicode:characters_to_list(
+        [" ", lists:join(" ", EmuArgs1)]
+    ),
+    EscriptSections =
+        [
+            {shebang, Shebang},
+            {comment, Comment},
+            {emu_args, FinalEmuArgs},
+            {archive, ArchiveSpec, []}
+        ],
+
+    case escript:create(EscriptPath, EscriptSections) of
+        ok ->
+            ok;
+        {error, EscriptError} ->
+            error(unicode:characters_to_binary(io_lib:format("could not create escript: ~tp", [EscriptError])))
+    end,
+
+    %% set executable bits (unix only)
+    {ok, #file_info{mode = Mode}} = file:read_file_info(EscriptPath),
+    ok = file:change_mode(EscriptPath, Mode bor 8#00111).
+
+-spec prepare_files(escript_artifact_spec()) -> escript_archive_spec().
+prepare_files(Artifacts) ->
+    Files = expand_to_files_list(Artifacts),
+    load_parallel(Files).
+
+-spec expand_to_files_list(escript_artifact_spec()) -> escript_load_spec().
+expand_to_files_list(Artifacts) ->
+    maps:fold(
+        fun(ArchivePathBin, FSPath, AccOuter) ->
+            ArchivePath = binary_to_list(ArchivePathBin),
+            case filelib:is_dir(FSPath, prim_file) of
+                true ->
+                    Files = filelib:wildcard("**", binary_to_list(FSPath), prim_file),
+                    lists:foldl(
+                        fun(FileShortPath, AccInner) ->
+                            FileOrDirPath = filename:join(FSPath, FileShortPath),
+                            case filelib:is_dir(FileOrDirPath, prim_file) of
+                                true ->
+                                    AccInner;
+                                false ->
+                                    [
+                                        {filename:join(ArchivePath, FileShortPath), FileOrDirPath}
+                                        | AccInner
+                                    ]
+                            end
+                        end,
+                        AccOuter,
+                        Files
+                    );
+                false ->
+                    [{ArchivePath, FSPath} | AccOuter]
+            end
+        end,
+        [],
+        Artifacts
+    ).
+
+-spec load_parallel(escript_load_spec()) -> escript_archive_spec().
+load_parallel([]) ->
+    [];
+load_parallel(Files) ->
+    Self = self(),
+    F = fun() -> worker(Self) end,
+    Jobs = min(length(Files), erlang:system_info(schedulers)),
+    Refs = #{element(2, spawn_monitor(F)) => [] || _I <- lists:seq(1, Jobs)},
+    queue(Files, Refs, maps:size(Refs), []).
+
+-spec worker(pid()) -> ok.
+worker(QueuePid) ->
+    QueuePid ! self(),
+    receive
+        {load, {ArchivePath, FSPath}} ->
+            QueuePid ! {done, FSPath, {ArchivePath, file_contents(FSPath)}},
+            worker(QueuePid);
+        empty ->
+            ok
+    end.
+
+-spec file_contents(file:filename()) -> binary().
+file_contents(Filename) ->
+    case file:read_file(Filename, [raw]) of
+        {ok, Bin} -> Bin;
+        Error -> error({read_file, Filename, Error})
+    end.
+
+-spec queue(escript_load_spec(), #{reference() => []}, non_neg_integer(), escript_archive_spec()) ->
+    escript_archive_spec().
+queue([], _JobRefs, 0, Acc) ->
+    Acc;
+queue(Files, JobRefs, NumLeft, Acc) ->
+    receive
+        {done, File, Res} ->
+            io:format("Loaded ~ts~n", [File]),
+            queue(Files, JobRefs, NumLeft, [Res | Acc]);
+        {'DOWN', Mref, _, _Pid, Info} ->
+            case Info of
+                normal when is_map_key(Mref, JobRefs) ->
+                    queue(Files, JobRefs, NumLeft - 1, Acc);
+                _ ->
+                    io:format("ERROR: Compilation failed: ~tp", [Info]),
+                    erlang:halt(1)
+            end;
+        Worker when is_pid(Worker) ->
+            case Files of
+                [] ->
+                    Worker ! empty,
+                    queue(Files, JobRefs, NumLeft, Acc);
+                [_ | _] ->
+                    [NextFile | MoreFiles] = Files,
+                    Worker ! {load, NextFile},
+                    queue(MoreFiles, JobRefs, NumLeft, Acc)
+            end
+    end.
diff --git a/buck2/prelude/erlang/toolchain/escript_trampoline.sh b/buck2/prelude/erlang/toolchain/escript_trampoline.sh
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/escript_trampoline.sh
@@ -0,0 +1,12 @@
+#! /usr/bin/env bash
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+cmd=("$2" "$1/run.escript" "${@:3}")
+
+"${cmd[@]}"
diff --git a/buck2/prelude/erlang/toolchain/release_variables_builder.erl b/buck2/prelude/erlang/toolchain/release_variables_builder.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/release_variables_builder.erl
@@ -0,0 +1,55 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(release_variables_builder).
+-author("loscher@fb.com").
+-moduledoc """
+Reads a file containing a mapping from ENV variable to string value
+and outputs a shell file that can be included in other scripts. It
+always adds ERTS_VSN.
+
+The purpose is to forward information about the release, e.g. release
+name or version, to a release startup shell script.
+
+usage:
+  release_variables_builder.escript release_variables
+""".
+
+-export([main/1]).
+
+-define(EXITSUCCESS, 0).
+-define(EXITERROR, 1).
+
+-spec main([string()]) -> ok.
+main([Spec, ReleaseVariablesFile]) ->
+    try
+        do(Spec, ReleaseVariablesFile),
+        erlang:halt(?EXITSUCCESS)
+    catch
+        Type:{abort, Reason} ->
+            io:format(standard_error, "~ts:~ts~n", [Type, Reason]),
+            erlang:halt(?EXITERROR)
+    end;
+main(_) ->
+    usage().
+
+-spec usage() -> ok.
+usage() ->
+    io:format("release_variables_builder.escript release_variables").
+
+-spec do(file:filename(), file:filename()) -> ok.
+do(Spec, ReleaseVariablesFile) ->
+    {ok, Contents} = file:read_file(Spec, [raw]),
+    Variables = json:decode(Contents),
+    {ok, F} = file:open(ReleaseVariablesFile, [write, raw]),
+    [
+        ok = file:write(F, io_lib:format("~ts=\"~ts\"~n", [Key, Value]))
+     || Key := Value <- Variables#{"ERTS_VSN" => erlang:system_info(version)}
+    ],
+    ok = file:close(F),
+    ok.
diff --git a/buck2/prelude/erlang/toolchain/transform_project_root.erl b/buck2/prelude/erlang/toolchain/transform_project_root.erl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/erlang/toolchain/transform_project_root.erl
@@ -0,0 +1,101 @@
+%% Copyright (c) Meta Platforms, Inc. and affiliates.
+%%
+%% This source code is licensed under both the MIT license found in the
+%% LICENSE-MIT file in the root directory of this source tree and the Apache
+%% License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+%% of this source tree.
+
+%% @format
+-module(transform_project_root).
+-eqwalizer(ignore).
+
+-export([parse_transform/2]).
+
+-type mapping() :: #{file:filename_all() => {true | false, file:filename_all()}}.
+
+-spec parse_transform(Forms, Options) -> Forms when
+    Forms :: [erl_parse:abstract_form() | erl_parse:form_info()], Options :: [compile:option()].
+parse_transform(Forms, Options) ->
+    Mapping = get_mapping(Options),
+    rewrite_file_attributes(Forms, Mapping).
+
+-spec rewrite_file_attributes([erl_parse:abstract_form() | erl_parse:form_info()], mapping()) ->
+    [erl_parse:abstract_form() | erl_parse:form_info()].
+rewrite_file_attributes(Forms, Mapping) ->
+    OTPRoot = code:root_dir(),
+    [
+        case Form of
+            {attribute, Anno, file, {File, Line}} ->
+                {attribute, Anno, file, {path_relativize(File, OTPRoot, Mapping), Line}};
+            _ ->
+                Form
+        end
+     || Form <- Forms
+    ].
+
+-spec path_relativize(file:filename(), file:filename(), mapping()) -> file:filename().
+path_relativize(
+    File,
+    OTPRoot,
+    Mapping
+) ->
+    case Mapping of
+        #{File := {true, RelativePath}} ->
+            RelativePath;
+        #{File := {false, MaybeOTPPath}} ->
+            case find_in_otp(MaybeOTPPath, OTPRoot) of
+                {true, FoundPath} ->
+                    FoundPath;
+                false ->
+                    %% We failed to find the file in OTP, at this point the build should
+                    %% have already failed and we let the compiler report the error.
+                    MaybeOTPPath
+            end;
+        _ ->
+            %% We don't know where the file comes from, and fall back to the information
+            %% in the beam, this happens usually with transitve header includes from OTP.
+            File
+    end.
+
+-spec find_in_otp(file:filename_all(), file:filename_all()) ->
+    {true, file:filename_all()}
+    | false.
+find_in_otp(Path, OTPRoot) ->
+    [App, "include", Header] = filename:split(Path),
+    Pattern = filename:join(["lib", [App, "-*"], "include", Header]),
+    case filelib:wildcard(Pattern, OTPRoot, prim_file) of
+        [FoundPath] -> {true, filename:join("/otp", FoundPath)};
+        _ -> false
+    end.
+
+-spec get_source([compile:option()]) -> file:filename_all().
+get_source(Options) ->
+    case proplists:get_value(compile_info, Options) of
+        undefined ->
+            error(missing_compile_info);
+        CompileInfo ->
+            case proplists:get_value(source, CompileInfo) of
+                undefined ->
+                    error(corrupt_compile_info);
+                Source ->
+                    Source
+            end
+    end.
+
+-spec get_mapping([compile:option()]) -> mapping().
+get_mapping(Options) ->
+    Source = get_source(Options),
+    BaseMapping = #{filename:basename(Source) => {true, Source}},
+    case os:getenv("BUCK2_FILE_MAPPING") of
+        false ->
+            BaseMapping;
+        MappingFile ->
+            {ok, Contents} = file:read_file(MappingFile, [raw]),
+            {Mapping, ok, <<>>} = json:decode(Contents, ok, #{object_push => fun json_mapping_push/3}),
+            maps:merge(BaseMapping, Mapping)
+    end.
+
+json_mapping_push(Key, [Bool, Path], Acc) when is_binary(Key), is_boolean(Bool), is_binary(Path) ->
+    [{binary_to_list(Key), {Bool, binary_to_list(Path)}} | Acc];
+json_mapping_push(Key, Value, Acc) ->
+    [{Key, Value} | Acc].
diff --git a/buck2/prelude/error_handler/error_enricher.bzl b/buck2/prelude/error_handler/error_enricher.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/error_handler/error_enricher.bzl
@@ -0,0 +1,82 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Unified error enrichment framework for Buck2 structured build errors.
+
+This module provides a shared abstraction for matching and enriching build errors
+across different languages.
+"""
+
+load("@prelude//error_handler:error_enricher_types.bzl", "ErrorEnricher")
+
+def match_error(matcher: str | BuckRegex, text: str) -> bool:
+    if isinstance(matcher, str):
+        return matcher in text
+    elif isinstance(matcher, BuckRegex):
+        return matcher.match(text)
+    else:
+        fail("Unknown matcher type: {}".format(type(matcher)))
+
+def _apply_subcategory_remediation(error: ActionSubError, enricher: ErrorEnricher, text: str):
+    """
+    Extracts an error subcategory (if configured) and applies the remediation
+    specific to that subcategory. Subcategories let you target tailored fixes
+    for specific error objects within a broader category.
+    """
+    if enricher.subcategory_extractor:
+        subcategory = enricher.subcategory_extractor(text)
+        if subcategory:
+            error.subcategory = subcategory
+            if enricher.subcategory_remediations and subcategory in enricher.subcategory_remediations:
+                error.remediation = enricher.subcategory_remediations[subcategory]
+
+def enrich_errors(errors: list[ActionSubError], enrichers: list[ErrorEnricher], category_prefix: str = "") -> list[ActionSubError]:
+    for error in errors:
+        message = error.message if error.message else ""
+        path = error.file if error.file else ""
+
+        for enricher in enrichers:
+            if enricher.file_matcher and enricher.file_matcher not in path:
+                continue
+            if not match_error(enricher.matcher, message):
+                continue
+
+            error.category = category_prefix + enricher.category
+            _apply_subcategory_remediation(error, enricher, message)
+            if not error.remediation and enricher.message:
+                error.remediation = enricher.message
+            break
+
+    return errors
+
+def create_and_enrich_errors(ctx: ActionErrorCtx, text: str, enrichers: list[ErrorEnricher], category_prefix: str = "") -> list[ActionSubError]:
+    """
+    Create an ActionSubError for EACH matching enricher.
+
+    Unlike enrich_errors() which enriches existing errors with the first match,
+    this function creates new errors for every matching enricher pattern.
+
+    Use this for stderr-based error handlers where multiple categories
+    may match the same output.
+    """
+    errors = []
+    for enricher in enrichers:
+        if not match_error(enricher.matcher, text):
+            continue
+
+        # Create new error for this match
+        error = ctx.new_sub_error(
+            category = category_prefix + enricher.category,
+            message = enricher.message,
+        )
+
+        _apply_subcategory_remediation(error, enricher, text)
+        errors.append(error)
+
+    return errors
diff --git a/buck2/prelude/error_handler/error_enricher_types.bzl b/buck2/prelude/error_handler/error_enricher_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/error_handler/error_enricher_types.bzl
@@ -0,0 +1,30 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Type definitions for the unified error enrichment framework.
+"""
+
+ErrorEnricher = record(
+    # Pattern to match against the error message.
+    # str performs a case-sensitive substring match.
+    matcher = str | BuckRegex,
+    # If specified, matcher will only run if the filepath contains this string.
+    file_matcher = field([str, None], default = None),
+    # Category to set on the error when matched.
+    category = str,
+    # Optional remediation message to help users fix the error.
+    # This is a general hint that applies to all matches of this pattern.
+    message = field([str, None], default = None),
+    # Optional function to extract a subcategory from the error text.
+    # This enables more granular categorization within a category.
+    subcategory_extractor = field([typing.Callable[[str], str | None], None], default = None),
+    # Map from subcategory to specific remediation message.
+    # When a subcategory is extracted, this map provides targeted remediation.
+    subcategory_remediations = field([dict[str, str], None], default = None),
+)
diff --git a/buck2/prelude/export_exe.bzl b/buck2/prelude/export_exe.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/export_exe.bzl
@@ -0,0 +1,145 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//python:manifest.bzl", "create_manifest_for_entries")
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+
+def _export_exe_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs.src and ctx.attrs.exe:
+        fail("Must supply one of src or exe to export_exe")
+
+    src = ctx.attrs.src if ctx.attrs.src else ctx.attrs.exe
+
+    providers = []
+    providers.append(DefaultInfo(other_outputs = ctx.attrs.resources))
+    providers.append(RunInfo(args = cmd_args(src, hidden = ctx.attrs.resources)))
+
+    if ctx.attrs.src != None:
+        providers.append(
+            create_unix_env_info(
+                actions = ctx.actions,
+                env = UnixEnv(
+                    label = ctx.label,
+                    binaries = [
+                        create_manifest_for_entries(
+                            ctx = ctx,
+                            name = "unix_env",
+                            entries = [
+                                (ctx.attrs.src.basename, ctx.attrs.src, ""),
+                            ],
+                        ),
+                    ],
+                ),
+            ),
+        )
+
+    return providers
+
+_export_exe = rule(
+    doc = """Exports a file as an executable, for use in $(exe) macros or as a valid target for an exec_dep().
+    Accepts either a string `src`, which is a relative path to a file that will be directly referenced,
+    or an arg `exe` which should be a path to an executable relative to a $(location) macro.
+
+    The first form is a more ergonomic replacement for export_file + command_alias. Eg. Instead of
+
+    export_file(
+        name = "script_sh",
+        src = "bin/script.sh",
+    )
+
+    command_alias(
+        name = "script.sh"
+        exe = ":script_sh",
+    )
+
+    You can write
+
+    export_exe(
+        name = "script.sh",
+        src = "bin/script.sh",
+    )
+
+    The latter form allows executing checked in binaries with required resources (eg. runtime shared libraries)
+    without unnecessary indirection via another rule which allows args, like command_alias. Eg. instead of
+
+    export_file(
+        name = "bin"
+        src = "bin",
+        mode = "reference",
+    )
+
+    export_file(
+        name = "exec.sh",
+        src = "exec.sh",
+    )
+
+    command_alias(
+        name = "compiler",
+        exe = ":exec.sh", # Just calls exec $@
+        args = [
+            "$(location :bin)/compiler",
+        ],
+    )
+
+    You can write
+
+    export_file(
+        name = "bin",
+        src = "bin",
+        mode = "reference",
+    )
+
+    export_exe(
+        name = "compiler",
+        exe = "$(location :bin)/compiler",
+    )
+
+    To ensure additional resources are materialized in Remote Execution (e.g., internal
+    compiler components that the executable invokes), use the `resources` parameter:
+
+    export_file(
+        name = "bin",
+        src = "bin",
+        mode = "reference",
+    )
+
+    export_file(
+        name = "libexec",
+        src = "libexec",
+        mode = "reference",
+    )
+
+    export_exe(
+        name = "compiler",
+        exe = "$(location :bin)/compiler",
+        resources = [":bin", ":libexec"],
+    )
+    """,
+    impl = _export_exe_impl,
+    attrs = {
+        "exe": attrs.option(attrs.arg(), default = None, doc = "arg which should evaluate to a path to an executable binary"),
+        "resources": attrs.list(attrs.source(), default = [], doc = "Additional artifacts to materialize alongside the executable (for Remote Execution)"),
+        "src": attrs.option(attrs.source(), default = None, doc = "path to an executable binary relative to this package"),
+    },
+)
+
+def export_exe(name, exe = None, src = None, **kwargs):
+    # If neither `exe` nor `src` is passed, treat the target's name as the src.
+    #
+    #     export_exe(
+    #         name = "script.sh",
+    #     )
+    #
+    # is equivalent to:
+    #
+    #     export_exe(
+    #         name = "script.sh",
+    #         src = "script.sh",
+    #     )
+    #
+    _export_exe(name = name, exe = exe, src = src if (exe or src) else name, **kwargs)
diff --git a/buck2/prelude/export_file.bzl b/buck2/prelude/export_file.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/export_file.bzl
@@ -0,0 +1,29 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Implementation of the `export_file` build rule.
+
+def export_file_impl(ctx: AnalysisContext) -> list[DefaultInfo]:
+    # mode is "copy" or "reference", defaulting to copy
+    copy = ctx.attrs.mode != "reference"
+
+    if copy:
+        dest = ctx.label.name if ctx.attrs.out == None else ctx.attrs.out
+        output = ctx.actions.copy_file(
+            dest,
+            ctx.attrs.src,
+            executable_bit_override = ctx.attrs.executable_bit_override,
+            has_content_based_path = ctx.attrs.has_content_based_path,
+        )
+    elif ctx.attrs.out != None:
+        fail("export_file does not allow specifying `out` without also specifying `mode = 'copy'`")
+    elif ctx.attrs.executable_bit_override != None:
+        fail("export_file does not allow specifying `executable_bit_override` without also specifying `mode = 'copy'`")
+    else:
+        output = ctx.attrs.src
+    return [DefaultInfo(default_output = output)]
diff --git a/buck2/prelude/filegroup.bzl b/buck2/prelude/filegroup.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/filegroup.bzl
@@ -0,0 +1,56 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifacts.bzl", "ArtifactGroupInfo")
+
+def filegroup_impl(ctx):
+    """
+    Creates a directory that contains links to the list of srcs
+
+    The output is a directory that uses `out` for its name, if provided, or the rule name if not.
+    Each symlink is based on the `short_path` for the provided `src`.
+    """
+    output_name = ctx.attrs.out if ctx.attrs.out else ctx.label.name
+    has_content_based_path = ctx.attrs.has_content_based_path
+
+    if type(ctx.attrs.srcs) == type({}):
+        srcs = ctx.attrs.srcs
+    else:
+        srcs = {}
+        for src in ctx.attrs.srcs:
+            existing = srcs.get(src.short_path)
+            if existing != None and existing != src:
+                fail("filegroup {} has srcs with duplicate names: {} and {}".format(ctx.label, src, srcs[src.short_path]))
+            srcs[src.short_path] = src
+
+    # It seems that buck1 always copies, and that's important for Python rules
+    if ctx.attrs.copy:
+        output = ctx.actions.copied_dir(
+            output_name,
+            srcs,
+            executable_bit_override = ctx.attrs.executable_bit_override,
+            has_content_based_path = has_content_based_path,
+        )
+    elif ctx.attrs.executable_bit_override != None:
+        fail("filegroup does not allow specifying `executable_bit_override` with `copy = False`")
+    else:
+        output = ctx.actions.symlinked_dir(
+            output_name,
+            srcs,
+            has_content_based_path = has_content_based_path,
+        )
+
+    if type(ctx.attrs.srcs) == type([]):
+        artifacts = ctx.attrs.srcs
+    else:
+        artifacts = [output.project(name, hide_prefix = True) for name in srcs]
+
+    return [
+        DefaultInfo(default_output = output),
+        ArtifactGroupInfo(artifacts = artifacts),
+    ]
diff --git a/buck2/prelude/genrule.bzl b/buck2/prelude/genrule.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/genrule.bzl
@@ -0,0 +1,494 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Implementation of the `genrule` build rule.
+
+load("@prelude//:cache_mode.bzl", "CacheModeInfo")
+load("@prelude//:genrule_local_labels.bzl", "resolved_genrule_labels_require_local")
+load("@prelude//:genrule_prefer_local_labels.bzl", "resolved_genrule_labels_prefer_local")
+load("@prelude//:genrule_toolchain.bzl", "GenruleToolchainInfo")
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load("@prelude//android:build_only_native_code.bzl", "is_build_only_native_code")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "flatten", "value_or")
+
+GENRULE_OUT_DIR = "out"
+
+# Currently, some rules require running from the project root, so provide an
+# opt-in list for those here.  Longer-term, these should be ported to actual
+# rule implementations in v2, rather then using `genrule`s.
+# TODO: Roll out root based genrules everywhere and flip the default to get rid of this logic.
+_BUILD_ROOT_LABELS = set([
+    # The buck2 test suite
+    "buck2_test_build_root",
+    "antlir_macros",
+    "rust_bindgen",
+    "haskell_hsc",
+    "cql_cxx_genrule",
+    "clang-module",
+    "cuda_build_root",
+    "bundle_pch_genrule",  # Compiles C++, and so need to run from build root
+    "lpm_package",
+    "haskell_dll",
+    "fnlc_build",
+    "udf_sql",
+    "redex_genrule",  # T148016945
+    "pxl",  # T151533831
+    "app_modules_genrule",  # produces JSON containing file paths that are read from the root dir.
+    "android_langpack_strings",  # produces JSON containing file paths that are read from the root dir.
+    "windows_long_path_issue",  # Windows: relative path length exceeds PATH_MAX, program cannot access file
+    "flowtype_ota_safety_target",  # produces JSON containing file paths that are project-relative
+    "ctrlr_setting_paths",
+    "llvm_buck_genrule",
+])
+
+# In Buck1 the SRCS environment variable is only set if the substring SRCS is on the command line.
+# That's a horrible heuristic, and doesn't account for users accessing $SRCS from a shell script.
+# But in some cases, $SRCS is so large it breaks the process limit, so have a label to opt in to
+# that behavior.
+_NO_SRCS_ENVIRONMENT_LABEL = "no_srcs_environment"
+
+_WINDOWS_ENV_SUBSTITUTIONS = [
+    # Replace $OUT and ${OUT}
+    (regex("\\$(OUT\\b|\\{OUT\\})"), "%OUT%"),
+    (regex("\\$(SRCDIR\\b|\\{SRCDIR\\})"), "%SRCDIR%"),
+    (regex("\\$(SRCS\\b|\\{SRCS\\})"), "%SRCS%"),
+    (regex("\\$(TMP\\b|\\{TMP\\})"), "%TMP%"),
+]
+
+def _requires_build_root(ctx: AnalysisContext) -> bool:
+    for label in ctx.attrs.labels:
+        if label in _BUILD_ROOT_LABELS:
+            return True
+    if ctx.attrs.repo_relative_root:
+        return True
+    return False
+
+def _requires_local(ctx: AnalysisContext) -> bool:
+    return resolved_genrule_labels_require_local(ctx.attrs.labels)
+
+def _prefers_local(ctx: AnalysisContext) -> bool:
+    return resolved_genrule_labels_prefer_local(ctx.attrs.labels)
+
+def _ignore_artifacts(ctx: AnalysisContext) -> bool:
+    return "buck2_ignore_artifacts" in ctx.attrs.labels
+
+def _requires_no_srcs_environment(ctx: AnalysisContext) -> bool:
+    return _NO_SRCS_ENVIRONMENT_LABEL in ctx.attrs.labels
+
+# We don't want to use cache mode in open source because the config keys that drive it aren't wired up
+_USE_CACHE_MODE = is_full_meta_repo()
+
+# Extra attributes required by every genrule based on genrule_impl
+def genrule_attributes() -> dict[str, Attr]:
+    attributes = {
+        "allow_offline_output_cache": attrs.bool(default = False),
+        "always_print_stderr": attrs.bool(default = False),
+        "metadata_env_var": attrs.option(attrs.string(), default = None),
+        "metadata_path": attrs.option(attrs.string(), default = None),
+        "no_outputs_cleanup": attrs.bool(default = False),
+        "remote_execution_dependencies": attrs.list(attrs.dict(key = attrs.string(), value = attrs.string()), default = []),
+        "repo_relative_root": attrs.bool(
+            default = False,
+            doc = """
+            If true, the genrule will be executed from the project root, instead of in the genrule location in buck-out.
+            Helps with long paths issues on windows with deeply nested directories, which will usually have long relative paths as inputs.
+            Should eventually default to true.
+        """,
+        ),
+        "_build_only_native_code": attrs.default_only(attrs.bool(default = is_build_only_native_code())),
+        "_genrule_toolchain": attrs.default_only(attrs.toolchain_dep(default = "toolchains//:genrule", providers = [GenruleToolchainInfo])),
+    }
+
+    if _USE_CACHE_MODE and not read_root_config("fb", "cache_mode") == None:
+        attributes["_cache_mode"] = attrs.dep(default = read_root_config("fb", "cache_mode"))
+
+    return attributes
+
+def _get_cache_mode(ctx: AnalysisContext) -> CacheModeInfo:
+    if _USE_CACHE_MODE:
+        return ctx.attrs._cache_mode[CacheModeInfo]
+    else:
+        return CacheModeInfo(allow_cache_uploads = False, cache_bust_genrules = False)
+
+def genrule_impl(ctx: AnalysisContext) -> list[Provider]:
+    # Directories:
+    #   sh - sh file
+    #   src - sources files
+    #   out - where outputs go
+    # `src` is the current directory
+    # Buck1 uses `.` as output, but that won't work since
+    # Buck2 clears the output directory before execution, and thus src/sh too.
+    return process_genrule(ctx, ctx.attrs.out, ctx.attrs.outs)
+
+def _project_output(out: Artifact, path: str) -> Artifact:
+    if path == ".":
+        return out
+    elif path.endswith("/"):
+        return out.project(path[:-1], hide_prefix = True)
+    else:
+        return out.project(path, hide_prefix = True)
+
+def _generate_error_handler(
+    category: str, stderr_errorformats: list[str] | None, stdout_errorformats: list[str] | None
+) -> typing.Callable[[ActionErrorCtx], list[ActionSubError]]:
+    def handler(ctx: ActionErrorCtx) -> list[ActionSubError]:
+        structured_errors = []
+        if stderr_errorformats != None:
+            structured_errors = ctx.parse_with_errorformat(
+                category = category,
+                error = ctx.stderr,
+                errorformats = stderr_errorformats,
+            )
+
+        if stdout_errorformats != None:
+            errors = ctx.parse_with_errorformat(
+                category = category,
+                error = ctx.stdout,
+                errorformats = stdout_errorformats,
+            )
+            structured_errors += errors
+        return structured_errors
+
+    return handler
+
+_HEADER_EXTENSIONS = [
+    ".h",
+    ".hpp",
+    ".hh",
+    ".h++",
+    ".hxx",
+    ".cuh",
+    ".inc",
+    ".tcc",
+]
+
+def _is_header(path: str) -> bool:
+    for ext in _HEADER_EXTENSIONS:
+        if path.endswith(ext):
+            return True
+    return False
+
+# Resolves whether a genrule's outputs should use content-based paths. When
+# `has_content_based_path` is left unset, outputs consisting solely of headers
+# default to content-based paths.
+def _is_content_based(content_based: [bool, None], out_attr: [str, None], outs_attr: [dict, None]) -> bool:
+    # An explicit setting always wins; avoid scanning outputs.
+    if content_based != None:
+        return content_based
+
+    if out_attr != None:
+        return _is_header(out_attr)
+
+    if outs_attr == None:
+        return False
+
+    for paths in outs_attr.values():
+        for path in paths:
+            if not _is_header(path):
+                return False
+    return True
+
+def process_genrule(
+    ctx: AnalysisContext,
+    out_attr: [str, None],
+    outs_attr: [dict, None],
+    extra_env_vars: dict = {},
+    identifier: [str, None] = None,
+    other_outputs: list[Artifact] = [],
+    genrule_error_handler: [typing.Callable[[ActionErrorCtx], list[ActionSubError]], None] = None,
+) -> list[Provider]:
+    if (out_attr != None) and (outs_attr != None):
+        fail("Only one of `out` and `outs` should be set. Got out=`%s`, outs=`%s`" % (repr(out_attr), repr(outs_attr)))
+
+    local_only = _requires_local(ctx)
+    prefer_local = _prefers_local(ctx)
+
+    # NOTE: Eventually we shouldn't require local_only here, since we should be
+    # fine with caching local fallbacks if necessary (or maybe that should be
+    # disallowed as a matter of policy), but for now let's be safe.
+    cacheable = value_or(ctx.attrs.cacheable, True) and (local_only or prefer_local)
+
+    executable_outs = getattr(ctx.attrs, "executable_outs", None)
+
+    content_based = _is_content_based(
+        getattr(ctx.attrs, "has_content_based_path", None),
+        out_attr,
+        outs_attr,
+    )
+
+    # `out_dir_artifact`: The base artifact into which all the outputs go
+    # `out_env`: The path we put into `$OUT`
+    # `out_prepare`: The directory to `mkdir` before calling the user's code
+    #
+    # There is no justification for the particular choice of semantics today other than that's how
+    # it always worked and changing it is very hard
+    out_dir_artifact = ctx.actions.declare_output(GENRULE_OUT_DIR, dir = True, has_content_based_path = content_based)
+    if out_attr != None:
+        out_env = _project_output(out_dir_artifact, out_attr)
+        if out_attr == ".":
+            out_prepare = out_env.as_output()
+        else:
+            out_prepare = cmd_args(out_env.as_output(), parent = 1)
+        named_outputs = {}
+        default_outputs = [out_env]
+        expect(executable_outs == None, "`executable_outs` should not be set when `out` is set")
+    elif outs_attr != None:
+        out_env = out_dir_artifact
+        out_prepare = out_dir_artifact.as_output()
+        named_outputs = {name: [_project_output(out_dir_artifact, path) for path in outputs] for (name, outputs) in outs_attr.items()}
+
+        outs_names = outs_attr.keys()
+        if executable_outs != None:
+            for executable_out in executable_outs:
+                expect(executable_out in outs_names, "Value in `executable_outs` {} is not in `outs`".format(executable_out))
+
+        default_outputs = [_project_output(out_dir_artifact, path) for path in (ctx.attrs.default_outs or [])]
+        if len(default_outputs) == 0:
+            # We want building to force something to be built, so make sure it contains at least one artifact
+            default_outputs = [out_dir_artifact]
+    else:
+        fail("One of `out` or `outs` should be set. Got `%s`" % repr(ctx.attrs))
+
+    # Some custom rules use `process_genrule` but doesn't set this attribute.
+    is_windows = hasattr(ctx.attrs, "_exec_os_type") and ctx.attrs._exec_os_type[OsLookup].os == Os("windows")
+    if is_windows:
+        path_sep = "\\"
+        cmd = ctx.attrs.cmd_exe if ctx.attrs.cmd_exe != None else ctx.attrs.cmd
+        if cmd == None:
+            fail("One of `cmd` or `cmd_exe` should be set.")
+    else:
+        path_sep = "/"
+        cmd = ctx.attrs.bash if ctx.attrs.bash != None else ctx.attrs.cmd
+        if cmd == None:
+            fail("One of `cmd` or `bash` should be set.")
+
+    replace_regex = []
+
+    # For backwards compatibility with Buck1.
+    if is_windows:
+        for re, sub in _WINDOWS_ENV_SUBSTITUTIONS:
+            replace_regex.append((re, sub))
+
+        for extra_env_var in extra_env_vars:
+            replace_regex.append(
+                (regex("\\$(%s\\b|\\{%s\\})" % (extra_env_var, extra_env_var)), "%%%s%%" % extra_env_var),
+            )
+
+    cmd = cmd_args(cmd, ignore_artifacts = _ignore_artifacts(ctx), replace_regex = replace_regex)
+
+    if type(ctx.attrs.srcs) == type([]):
+        # FIXME: We should always use the short_path, but currently that is sometimes blank.
+        # See fbcode//buck2/tests/targets/rules/genrule:genrule-dot-input for a test that exposes it.
+        symlinks = {src.short_path: src for src in ctx.attrs.srcs}
+
+        if len(symlinks) != len(ctx.attrs.srcs):
+            for src in ctx.attrs.srcs:
+                name = src.short_path
+                if symlinks[name] != src:
+                    msg = "genrule srcs include duplicative name: `{}`. ".format(name)
+                    msg += "`{}` conflicts with `{}`".format(symlinks[name].owner, src.owner)
+                    fail(msg)
+    else:
+        symlinks = ctx.attrs.srcs
+    srcs_artifact = ctx.actions.symlinked_dir(
+        "srcs" if not identifier else "{}-srcs".format(identifier),
+        symlinks,
+        has_content_based_path = content_based,
+    )
+
+    if ctx.attrs.environment_expansion_separator:
+        delimiter = ctx.attrs.environment_expansion_separator
+    else:
+        delimiter = " "
+
+    # Setup environment variables.
+    no_srcs_environment = _requires_no_srcs_environment(ctx)
+    env_vars = {
+        "GEN_DIR": "GEN_DIR_DEPRECATED",
+        "OUT": out_env.as_output(),
+        "SRCDIR": cmd_args(srcs_artifact, format = path_sep.join([".", "{}"])),
+    }
+    if not no_srcs_environment:
+        srcs = cmd_args(delimiter = delimiter)
+        for symlink in symlinks:
+            srcs.add(cmd_args(srcs_artifact, format = path_sep.join([".", "{}", symlink.replace("/", path_sep)])))
+        env_vars["SRCS"] = srcs
+    env_vars |= {k: cmd_args(v) for k, v in getattr(ctx.attrs, "env", {}).items()}
+
+    # RE will cache successful actions that don't produce the desired outptuts,
+    # so if that happens and _then_ we add a local-only label, we'll get a
+    # cache hit on the action that didn't produce the outputs and get the error
+    # again (thus making the label useless). So, when a local-only label is
+    # set, we make the action *different*.
+    if local_only:
+        env_vars["__BUCK2_LOCAL_ONLY_CACHE_BUSTER"] = ""
+
+    # see comment above
+    if prefer_local:
+        env_vars["__BUCK2_PREFER_LOCAL_CACHE_BUSTER"] = ""
+
+    # For now, when uploads are enabled, be safe and avoid sharing cache hits.
+    cache_bust = _get_cache_mode(ctx).cache_bust_genrules
+
+    if cacheable and cache_bust:
+        env_vars["__BUCK2_ALLOW_CACHE_UPLOADS_CACHE_BUSTER"] = ""
+
+    for key, value in extra_env_vars.items():
+        env_vars[key] = value
+
+    # Create required directories.
+    if is_windows:
+        script = [
+            cmd_args(
+                out_prepare,
+                format = "if not exist {} mkdir {}",
+            ),
+            cmd_args('if NOT "%TEMP%" == "" set "TMP=%TEMP%"'),
+        ]
+        script_extension = "bat"
+    else:
+        script = [
+            # Use a somewhat unique exit code so this can get retried on RE (T99656531).
+            cmd_args(out_prepare, format = "mkdir -p {} || exit 99"),
+            cmd_args("export TMP=${TMPDIR:-/tmp}"),
+        ]
+        script_extension = "sh"
+
+    # Actually define the operation, relative to where we changed to
+    script.append(cmd)
+
+    hidden = []
+    genrule_toolchain = ctx.attrs._genrule_toolchain[GenruleToolchainInfo]
+    zip_scrubber = genrule_toolchain.zip_scrubber
+    if not is_windows and zip_scrubber != None:
+        zip_outputs = [output for output in default_outputs + flatten(named_outputs.values()) if output.extension == ".zip"]
+
+        if zip_outputs:
+            hidden.append(zip_scrubber)
+
+            # Any outputs that are .zip files need to be "scrubbed" to ensure that they are deterministic.
+            script = (
+                [
+                    cmd_args("ORIGINAL_DIR_FOR_ZIP_SCRUBBING=$(pwd)"),
+                ]
+                + script
+                + [
+                    cmd_args('cd "$ORIGINAL_DIR_FOR_ZIP_SCRUBBING"'),
+                ]
+                + [cmd_args(zip_scrubber, output.as_output(), delimiter = " ", quote = "shell") for output in zip_outputs]
+            )
+
+    # Some rules need to run from the build root, but for everything else, `cd`
+    # into the sandboxed source dir and relative all paths to that.
+    if not _requires_build_root(ctx):
+        srcs_dir = srcs_artifact
+
+        if is_windows:
+            rewrite_scratch_path = cmd_args(
+                cmd_args(ctx.label.project_root, relative_to = srcs_artifact),
+                format = 'set "BUCK_SCRATCH_PATH={}\\%BUCK_SCRATCH_PATH%"',
+            )
+        else:
+            srcs_dir = cmd_args(srcs_dir, quote = "shell")
+            rewrite_scratch_path = cmd_args(
+                cmd_args(ctx.label.project_root, quote = "shell", relative_to = srcs_artifact),
+                format = "export BUCK_SCRATCH_PATH={}/$BUCK_SCRATCH_PATH",
+            )
+
+        # Relativize all paths in the command to the sandbox dir.
+        for script_cmd in script:
+            script_cmd.relative_to(srcs_artifact)
+
+        script = [
+            # Rewrite BUCK_SCRATCH_PATH
+            rewrite_scratch_path,
+            # Change to the directory that genrules expect.
+            cmd_args(srcs_dir, format = "cd {}"),
+        ] + script
+
+        # Relative all paths in the env to the sandbox dir.
+        env_vars = {key: cmd_args(value, relative_to = srcs_artifact) for key, value in env_vars.items()}
+
+    if is_windows:
+        # Should be in the beginning.
+        # Odd, why is this a single string. How does it not end up getting quoted and being weird?
+        script = [cmd_args("@echo off")] + script
+
+    sh_script, _ = ctx.actions.write(
+        "sh/genrule.{}".format(script_extension) if not identifier else "sh/{}-genrule.{}".format(identifier, script_extension),
+        script,
+        is_executable = True,
+        allow_args = True,
+        has_content_based_path = content_based,
+    )
+    if is_windows:
+        script_args = ["cmd.exe", "/v:off", "/c", sh_script]
+    else:
+        script_args = ["/usr/bin/env", "bash", "-e", sh_script]
+
+    # Only set metadata arguments when they are non-null
+    metadata_args = {}
+    if ctx.attrs.metadata_env_var:
+        metadata_args["metadata_env_var"] = ctx.attrs.metadata_env_var
+    if ctx.attrs.metadata_path:
+        metadata_args["metadata_path"] = ctx.attrs.metadata_path
+    if ctx.attrs.remote_execution_dependencies:
+        metadata_args["remote_execution_dependencies"] = ctx.attrs.remote_execution_dependencies
+
+    if genrule_error_handler == None:
+        error_handler_category = getattr(ctx.attrs, "error_handler_category", None)
+        error_handler_stderr_errorformats = getattr(ctx.attrs, "error_handler_stderr_errorformats", None)
+        error_handler_stdout_errorformats = getattr(ctx.attrs, "error_handler_stdout_errorformats", None)
+        if error_handler_category != None and (error_handler_stderr_errorformats != None or error_handler_stdout_errorformats != None):
+            genrule_error_handler = _generate_error_handler(
+                error_handler_category,
+                error_handler_stderr_errorformats,
+                error_handler_stdout_errorformats,
+            )
+
+    category = "genrule"
+    if ctx.attrs.type != None:
+        # As of 09/2021, all genrule types were legal snake case if their dashes and periods were replaced with underscores.
+        category += "_" + ctx.attrs.type.replace("-", "_").replace(".", "_")
+    ctx.actions.run(
+        cmd_args(script_args, hidden = [cmd, srcs_artifact, out_dir_artifact.as_output()] + hidden),
+        env = env_vars,
+        local_only = local_only,
+        prefer_local = prefer_local,
+        weight = value_or(ctx.attrs.weight, 1),
+        allow_cache_upload = cacheable,
+        allow_offline_output_cache = ctx.attrs.allow_offline_output_cache,
+        category = category,
+        identifier = identifier,
+        no_outputs_cleanup = ctx.attrs.no_outputs_cleanup,
+        always_print_stderr = ctx.attrs.always_print_stderr,
+        error_handler = genrule_error_handler,
+        **metadata_args,
+    )
+
+    sub_targets = {}
+    for k, v in named_outputs.items():
+        sub_target_providers = [DefaultInfo(default_outputs = v)]
+        if executable_outs != None and k in executable_outs:
+            sub_target_providers.append(RunInfo(args = cmd_args(v)))
+        sub_targets[k] = sub_target_providers
+
+    providers = [
+        DefaultInfo(
+            default_outputs = default_outputs,
+            sub_targets = sub_targets,
+            other_outputs = other_outputs,
+        )
+    ]
+
+    # The cxx_genrule also forwards here, and that doesn't have .executable, so use getattr
+    if getattr(ctx.attrs, "executable", False):
+        providers.append(RunInfo(args = cmd_args(default_outputs)))
+    return providers
diff --git a/buck2/prelude/genrule_local_labels.bzl b/buck2/prelude/genrule_local_labels.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/genrule_local_labels.bzl
@@ -0,0 +1,196 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:selects.bzl", "selects")
+
+"""
+Handle labels used to opt-out genrules from running remotely.
+"""
+
+# Some rules have to be run locally for various reasons listed next to the label.
+_GENRULE_LOCAL_LABELS = set([
+    # Used for buck2 tests that want to run locally
+    "buck2_test_local_exec",
+    # Split dwarf merge rules currently don't properly list their inputs.
+    "dwp",
+    # Bolt and hottext post-processing rules operate on a large statically
+    # linked binary which contains non-deterministic build info, meaning its
+    # a) currently too large for RE to handle and b) caching it would only
+    # waste cache space.
+    "postprocess_bolt",
+    "postprocess_hottext",
+    # The iOS build needs to run a genrule locally to gather non-deterministic
+    # build info from `hg`.
+    "non_deterministic_build_info",
+    # Some call "buck run" & "buck root" recursively.
+    "uses_buck_run",
+    # Some antlir and telephoto genrules use clowder for downloading from everstore
+    "uses_clowder",
+    # Some antlir genrules use cpio for unpacking rpms
+    "uses_cpio",
+    # Creates secondary Eden repos outside of `buck-out/`
+    "uses_eden_mounts",
+    # The Antlir core compiler uses sudo
+    "uses_sudo",
+    # Some rules utilize hg for some reason as part of code generation
+    "uses_hg",
+    # Dotslash is not yet supported on RE.
+    "uses_dotslash",
+    # Some rules apply a patch which is not on RE.
+    "uses_patch",
+    # Directly uses the smcc binary which is not on RE.
+    "uses_smcc",
+    # Uses shasum which is not on RE.
+    "uses_shasum",
+    # Uses xz which is not on RE.
+    "uses_xz",
+    # Uses tw tool which is not on RE.
+    "uses_tw",
+    # Uses thrift tool which is not on RE.
+    "uses_thrift",
+    # Uses protoc tool which is not on RE.
+    "uses_protoc",
+    # Yarn installs use a large in-repo yarn repo that's ~6.1GB at the time of
+    # writing, and so v1 uses workarounds (D17359502) to avoid the overhead this
+    # would causes.  So, run these rules locally to maintain compatibility and
+    # until we have a better yarn solution.
+    "yarn_install",
+    # Non-deterministic builds that depend on data from configerator.
+    "reads_configerator",
+    # Third party java artifacts are stored in manifold and therefore can't be accessed from RE worker.
+    "third_party_java",
+    # The antlir package-at-build-time rules current rely on tools like hg/git,
+    # which don't work on RE.
+    "antlir_macros",
+    # UPM codegen does lots of network I/O (e.g. scuba, JK, configerator), which
+    # makes it fail on RE.
+    "upm_binary_gen",
+    # Uses the `libX11-devel` package which is not available on RE.
+    "uses_x11",
+    # Unity license client needs to be set up on RE workers for this to work, and maybe further debugging.
+    "uses_unity",
+    # mksquashfs isn't available in RE, so run these locally
+    # (https://fb.workplace.com/groups/buck2users/permalink/3023630007893360/)
+    "uses_mksquashfs",
+    # PXL rules can't yet run on RE.
+    "pxl",
+    # Accesses dewey
+    "uses_dewey",
+    # Accesses justknobs configuration
+    "justknobs",
+    # Side effecting writes directly into buck-out on the local
+    # filesystem
+    "writes_to_buck_out",
+    # Side effecting writes directly to local filesystem outside of buck-out
+    # Do not add or use in new rules, just for tagging existing rules for
+    # better categorization.
+    "writes_outside_buck_out",
+    # Calculates and writes absolute paths in the local filesystem
+    "uses_local_filesystem_abspaths",
+    # Use local GPUs with latest Nvidia libs which are not available in RE yet
+    "uses_lower_locally",
+    # Uses fbpkg outside of the repo
+    "uses_fbpkg",
+    # Makes recursive calls to buck
+    "uses_buck",
+    # Uses files in the repo that it doesn't declare as dependencies
+    "uses_undeclared_inputs",
+    # Connects to service router which won't work on RE
+    "uses_service_router",
+    # Downloads direct from manifold
+    "uses_manifold",
+    # When run on RE produces "Cache is out of space" (excessive disk/memory)
+    "re_cache_out_of_space",
+    # HHVM Post-link rules need to be local since the binary is huge.
+    "hhvm_postlink",
+    # Uses network access (unspecified what as of yet)
+    "network_access",
+    # Uses clang format which is not in RE
+    "uses_clang_format",
+    # Perform makes compilation in situ.
+    "uses_make",
+    # Like uses_make but for windows
+    "uses_msbuild",
+    # Like it says in the label
+    "uses_mkscratch",
+    # Locally built toolchains which do not exist on RE
+    "toolchain_testing",
+    # sphinx_wiki always needs to run locally
+    "sphinx_wiki",
+    # Uses R (which is feature gated) pending RE support
+    "uses_rlang",
+    # Uses watchman which is not in RE
+    "uses_watchman",
+    # Uses yumdownloader which is not in RE
+    "yumdownloader",
+    # Uses locally installed mvn.
+    "uses_maven",
+    # Some Qt genrules don't support RE yet
+    "qt_moc",
+    "qt_qmlcachegen",
+    "qt_qrc_compile",
+    "qt_qrc_gen",
+    "qt_qsb_gen",
+    "qt_rcc",
+    "qt_uic",
+    # use local jar
+    "uses_jar",
+    # uses local java
+    "uses_java",
+    # use locally installed svnyum
+    "uses_svnyum",
+    # uses ruby
+    "uses_ruby",
+    # Produces an output symlink, and since Meta RE doesn't support returning
+    # output symlinks (yet?), and sometimes the output symlink also cannot be
+    # dereferenced anyway (e.g. because it violates security policies or simply
+    # points to something that does not exist).
+    "dangling_output_symlink",
+    # speech translation uses genrule to get models from manifold, high priority project
+    "speech_translation_high_priority",
+    # Uses Apple's codesign command which might not be in RE
+    "uses_codesign",
+    # Uses jf which is not on RE
+    "uses_jf",
+    # On Messenger Desktop few targets are massive and take much longer on RE than
+    # locally to build on Windows. This is a mitigation until we can break down these
+    # targets
+    "zeratul_windows_capacity_hog",
+    # The compilation databases produced by Buck have paths relative to the root of
+    # fbsource. This isn't compatible with RE.
+    "uses_compilation_database",
+    # Uses checkpolicy which is not on RE
+    "uses_checkpolicy",
+    # Need to build sgw containers on devserver and not on RE
+    # We pull base image from internet
+    "sgw_build_containers",
+    # Needs to pull docker image from a docker
+    # registry hosted on our internal network
+    "uses_docker_registry",
+])
+
+def genrule_labels_require_local(labels):
+    def check_labels(labels_list):
+        if labels_list == None:
+            return False
+
+        for label in labels_list:
+            if selects.is_select(label):
+                return selects.apply(label, lambda val: val in _GENRULE_LOCAL_LABELS if val else False)
+
+            elif label in _GENRULE_LOCAL_LABELS:
+                return True
+        return False
+
+    return selects.apply(labels, check_labels)
+
+def resolved_genrule_labels_require_local(labels: list[str]) -> bool:
+    for label in labels:
+        if label in _GENRULE_LOCAL_LABELS:
+            return True
+    return False
diff --git a/buck2/prelude/genrule_prefer_local_labels.bzl b/buck2/prelude/genrule_prefer_local_labels.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/genrule_prefer_local_labels.bzl
@@ -0,0 +1,23 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Handle labels used to make genrules prefer local execution
+"""
+
+# Some rules prefer to be run locally for various reasons listed next to the label.
+_GENRULE_PREFER_LOCAL_LABELS = set([
+    # Used for rules that just copy large files and will be faster to do locally
+    "large_copy",
+])
+
+def resolved_genrule_labels_prefer_local(labels: list[str]) -> bool:
+    for label in labels:
+        if label in _GENRULE_PREFER_LOCAL_LABELS:
+            return True
+    return False
diff --git a/buck2/prelude/genrule_toolchain.bzl b/buck2/prelude/genrule_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/genrule_toolchain.bzl
@@ -0,0 +1,14 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+GenruleToolchainInfo = provider(
+    doc = "Genrule toolchain info",
+    fields = {
+        "zip_scrubber": provider_field(typing.Any, default = None),
+    },
+)
diff --git a/buck2/prelude/git/git_fetch.bzl b/buck2/prelude/git/git_fetch.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/git/git_fetch.bzl
@@ -0,0 +1,78 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+_HEX_DIGITS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
+
+def _is_hex(rev: str, *, length: int) -> bool:
+    if len(rev) != length:
+        return False
+    for digit in rev.elems():
+        if digit not in _HEX_DIGITS:
+            return False
+    return True
+
+def git_fetch_impl(ctx: AnalysisContext) -> list[Provider]:
+    object_format = ctx.attrs.object_format
+    rev = ctx.attrs.rev
+    if object_format == None:
+        if not _is_hex(rev, length = 40):
+            fail("git_fetch's `rev` must be a 40-hex-digit commit hash: {}".format(rev))
+    elif object_format == "sha1":
+        if not _is_hex(rev, length = 40):
+            fail("git_fetch's `rev` must be a 40-hex-digit commit hash when the chosen object format is sha1: {}".format(rev))
+    elif object_format == "sha256":
+        if not _is_hex(rev, length = 64):
+            fail("git_fetch's `rev` must be a 64-hex-digit commit hash when the chosen object format is sha256: {}".format(rev))
+    else:
+        fail("Invalid git_fetch `object_format`: Must be one of sha1 or sha256: {}".format(object_format))
+
+    git_dir = ctx.actions.declare_output(".git", dir = True, has_content_based_path = False)
+
+    short_path = ctx.attrs.name.removesuffix(".git")
+    if not short_path:
+        short_path = "work-tree"
+    work_tree = ctx.actions.declare_output(short_path, dir = True, has_content_based_path = False)
+
+    if ctx.attrs.update_submodules:
+        update_submodules = cmd_args("--update-submodules")
+    else:
+        update_submodules = cmd_args()
+
+    cmd = [
+        ctx.attrs._git_fetch_tool[RunInfo],
+        cmd_args("--git-dir=", git_dir.as_output(), delimiter = ""),
+        cmd_args("--work-tree=", work_tree.as_output(), delimiter = ""),
+        cmd_args("--repo=", ctx.attrs.repo, delimiter = ""),
+        cmd_args("--rev=", rev, delimiter = ""),
+        update_submodules,
+    ]
+    if ctx.attrs.git != None:
+        cmd.append(cmd_args("--git=", ctx.attrs.git, delimiter = ""))
+    if object_format != None:
+        cmd.append(cmd_args("--object-format=", object_format, delimiter = ""))
+
+    ctx.actions.run(
+        cmd,
+        category = "git_fetch",
+        local_only = True,
+        allow_cache_upload = ctx.attrs.allow_cache_upload,
+    )
+
+    sub_targets = {path: [DefaultInfo(default_output = work_tree.project(path))] for path in ctx.attrs.sub_targets}
+
+    # The repository itself, for consumers that need to serve the fetch as a local git remote
+    # rather than read the checked-out files. git refuses to track a path named ".git", so no
+    # requested work-tree projection can ever claim this key.
+    sub_targets[".git"] = [DefaultInfo(default_output = git_dir)]
+
+    return [
+        DefaultInfo(
+            default_output = work_tree,
+            sub_targets = sub_targets,
+        )
+    ]
diff --git a/buck2/prelude/git/tools/BUCK b/buck2/prelude/git/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/git/tools/BUCK
@@ -0,0 +1,22 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "git_fetch",
+    main = "git_fetch.py",
+    visibility = ["PUBLIC"],
+)
+
+# Type checking target for Python tool scripts
+prelude.python_library(
+    name = "scripts-typing",
+    srcs = [
+        "git_fetch.py",
+    ],
+    typing = True,
+)
diff --git a/buck2/prelude/git/tools/git_fetch.py b/buck2/prelude/git/tools/git_fetch.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/git/tools/git_fetch.py
@@ -0,0 +1,146 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import os
+import shutil
+import subprocess
+import sys
+import time
+from enum import Enum
+from pathlib import Path
+from typing import List, NamedTuple, Optional
+
+
+MAX_RETRIES = 5
+
+_FALLBACK_GIT_PATHS = [
+    "/usr/bin/git",
+    "/usr/local/bin/git",
+]
+
+
+def _find_git(explicit: Optional[str] = None) -> str:
+    if explicit:
+        return explicit
+    found = shutil.which("git")
+    if found:
+        return found
+    for path in _FALLBACK_GIT_PATHS:
+        if Path(path).is_file():
+            return path
+    return "git"
+
+
+def run(cmd: List[str], check: bool, retries: int = MAX_RETRIES) -> str:
+    print(f"Running {cmd}", file=sys.stderr)
+    try:
+        proc = subprocess.run(
+            cmd,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            encoding="utf-8",
+            check=check,
+        )
+    except OSError as ex:
+        print(ex, file=sys.stderr)
+        sys.exit(1)
+    except subprocess.CalledProcessError as ex:
+        print(ex.stderr, file=sys.stderr)
+        if "The requested URL returned error: 429" in ex.stderr and retries > 0:
+            time.sleep(2 ** (MAX_RETRIES - retries))
+            return run(cmd, check, retries - 1)
+        sys.exit(ex.returncode)
+    return proc.stdout
+
+
+class ObjectFormat(str, Enum):
+    Sha1 = "sha1"
+    Sha256 = "sha256"
+
+
+class Args(NamedTuple):
+    git: Optional[str]
+    git_dir: Path
+    work_tree: Path
+    object_format: ObjectFormat
+    repo: str
+    rev: str
+    update_submodules: bool
+
+
+def arg_parse() -> Args:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--git", type=str, required=False, default=None)
+    parser.add_argument("--git-dir", type=Path, required=True)
+    parser.add_argument("--work-tree", type=Path, required=True)
+    parser.add_argument("--object-format", type=ObjectFormat, required=False)
+    parser.add_argument("--update-submodules", action="store_true", required=False)
+    parser.add_argument("--repo", type=str, required=True)
+    parser.add_argument("--rev", type=str, required=True)
+    return Args(**vars(parser.parse_args()))
+
+
+def git_configure(git: List[str]):
+    # Override if someone has `[core] autocrlf = true` in their global gitconfig
+    # on a Windows machine. That causes LF to be converted into CRLF when
+    # checking out text files, which is not desired here. Unix and Windows
+    # should produce identical directory as output.
+    run([*git, "config", "core.autocrlf", "false"], check=False)
+
+
+def main() -> None:
+    args = arg_parse()
+
+    args.work_tree.mkdir(exist_ok=True)
+
+    git_bin = _find_git(args.git)
+    git = [git_bin, f"--git-dir={args.git_dir}", f"--work-tree={args.work_tree}"]
+    if args.object_format is None:
+        object_format_args = []
+    else:
+        object_format_args = ["--object-format", args.object_format]
+
+    run([*git, "init"] + object_format_args, check=True)
+    git_configure(git)
+    run([*git, "remote", "remove", "origin"], check=False)
+    run([*git, "remote", "add", "origin", args.repo], check=True)
+    run([*git, "fetch", "--depth=1", "origin", args.rev], check=True)
+
+    fetch_head = run([*git, "rev-parse", "FETCH_HEAD"], check=True)
+    fetch_head = fetch_head.strip()
+    if fetch_head != args.rev:
+        raise RuntimeError(
+            f"fetched the wrong commit: expected {args.rev}, fetched {fetch_head}"
+        )
+
+    run([*git, "checkout", "FETCH_HEAD"], check=True)
+
+    if args.update_submodules:
+        git_in_worktree = [
+            git_bin,
+            f"--git-dir={os.path.abspath(args.git_dir)}",
+            # `git submodule` does not accept `--work-tree`, so run it from the worktree.
+            "-C",
+            str(args.work_tree),
+        ]
+        run(
+            [
+                *git_in_worktree,
+                "submodule",
+                "update",
+                "--init",
+                "--recursive",
+                "--depth=1",
+            ],
+            check=True,
+        )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/go/cgo_builder.bzl b/buck2/prelude/go/cgo_builder.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/cgo_builder.bzl
@@ -0,0 +1,258 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info", "get_opt_cxx_toolchain_info")
+load("@prelude//cxx:cxx_library.bzl", "cxx_compile_srcs")
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",
+)
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load(
+    "@prelude//cxx:cxx_types.bzl",
+    "CxxRuleConstructorParams",  # @unused Used as a type
+)
+load("@prelude//cxx:headers.bzl", "CxxHeadersLayout", "cxx_attr_header_namespace", "cxx_get_regular_cxx_headers_layout", "prepare_headers")
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorArgs",
+    "CPreprocessorInfo",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+)
+load("@prelude//cxx:target_sdk_version.bzl", "get_target_sdk_version_flags")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//os_lookup:defs.bzl", "OsLookup")
+load("@prelude//utils:cmd_script.bzl", "cmd_script")
+load(":toolchain.bzl", "GoToolchainInfo", "get_toolchain_env_vars")
+
+CGoToolOut = record(
+    cgo_gotypes = field(Artifact),  # _cgo_gotypes.go
+    cgo_export_h = field(Artifact),  # _cgo_export.h
+    cgo_export_c = field(Artifact),  # _cgo_export.c
+    cgo1_go_files = field(list[Artifact]),  # *.cgo1.go
+    cgo2_c_files = field(list[Artifact]),  # *.cgo2.c
+)
+
+# Parameters extracted from ctx.attrs
+CGoBuildContext = record(
+    # Values from implicit attrs
+    cxx_toolchain_info = field(CxxToolchainInfo),
+    target_sdk_version_flags = field(list[str]),
+    exec_os_type = field(OsLookup),
+    # Values from explicit attrs
+    header_namespace = field(str),
+    headers_layout = field(CxxHeadersLayout),
+    cxx_compiler_flags = field(list[typing.Any]),
+    cxx_preprocessor_flags = field(list[typing.Any]),
+    # Deps info
+    inherited_preprocessor_infos = field(list[CPreprocessorInfo]),
+    # Store "_cxx_toolchain" as "Dependency" for use in "anon_target"
+    _cxx_toolchain = field(Dependency | None, None),
+)
+
+def get_cgo_build_context(ctx: AnalysisContext) -> CGoBuildContext | None:
+    cxx_toolchain_info = get_opt_cxx_toolchain_info(ctx)
+    if cxx_toolchain_info == None:
+        return None
+
+    return CGoBuildContext(
+        cxx_toolchain_info = get_cxx_toolchain_info(ctx),
+        target_sdk_version_flags = get_target_sdk_version_flags(ctx),
+        exec_os_type = ctx.attrs._exec_os_type[OsLookup],
+        header_namespace = cxx_attr_header_namespace(ctx),
+        headers_layout = cxx_get_regular_cxx_headers_layout(ctx),
+        cxx_compiler_flags = ctx.attrs.cxx_compiler_flags,
+        cxx_preprocessor_flags = ctx.attrs.cxx_preprocessor_flags,
+        inherited_preprocessor_infos = cxx_inherited_preprocessor_infos(ctx.attrs.deps),
+        _cxx_toolchain = ctx.attrs._cxx_toolchain,
+    )
+
+_syscall_import_exclude_list = set([
+    "runtime/asan",
+    "runtime/cgo",
+    "runtime/race",
+    "runtime/msan",
+])
+
+def _cgo(
+    actions: AnalysisActions,
+    go_toolchain: GoToolchainInfo,
+    cgo_build_context: CGoBuildContext,
+    pkg_import_path: str,
+    standard: bool,
+    srcs: list[Artifact],
+    own_pre: list[CPreprocessor],
+    cgo_c_flags: list[str],
+    cgo_cpp_flags: list[str],
+) -> (CGoToolOut, Artifact):
+    """
+    Run `cgo` on `.go` sources to generate Go, C, and C-Header sources.
+    """
+    gen_dir = actions.declare_output("cgo_gen_tmp", dir = True, has_content_based_path = True)
+
+    # Return a `cmd_args` to use as the generated sources.
+
+    unimport_runtime_cgo = standard and pkg_import_path == "runtime/cgo"
+    unimport_syscall = standard and pkg_import_path in _syscall_import_exclude_list
+
+    # //line paths are resolved by the Go compiler against gen_dir.
+    trimpath_replaces = cmd_args(
+        [cmd_args(cmd_args(src, format = "%cwd%/{}"), cmd_args(src, relative_to = gen_dir), delimiter = "=>") for src in srcs],
+        delimiter = ";",
+    )
+
+    cmd = cmd_args(
+        go_toolchain.go_wrapper,
+        ["--go", go_toolchain.cgo],
+        "--",
+        cmd_args(gen_dir.as_output(), format = "-objdir={}"),
+        # todo: safe to remove once go1.28 is released
+        ["-trimpath", trimpath_replaces if go_toolchain.version and go_toolchain.version.minor >= 27 else "%cwd%"],
+        ["-import_runtime_cgo=false"] if unimport_runtime_cgo else [],
+        ["-import_syscall=false"] if unimport_syscall else [],
+        "--",
+        cgo_c_flags + cgo_cpp_flags,
+        cgo_build_context.cxx_compiler_flags,
+        srcs,
+    )
+
+    env = get_toolchain_env_vars(go_toolchain)
+    env["CC"] = _cxx_wrapper(actions, go_toolchain, cgo_build_context, own_pre)
+
+    actions.run(cmd, env = env, category = "go_cgo", identifier = pkg_import_path, allow_cache_upload = go_toolchain.allow_cache_upload)
+
+    return project_go_and_c_files(srcs, gen_dir), gen_dir
+
+def project_go_and_c_files(cgo_srcs: list[Artifact], gen_dir: Artifact) -> CGoToolOut:
+    return CGoToolOut(
+        cgo_gotypes = gen_dir.project("_cgo_gotypes.go"),
+        cgo_export_h = gen_dir.project("_cgo_export.h"),
+        cgo_export_c = gen_dir.project("_cgo_export.c"),
+        cgo1_go_files = [gen_dir.project(paths.replace_extension(src.basename, ".cgo1.go")) for src in cgo_srcs],
+        cgo2_c_files = [gen_dir.project(paths.replace_extension(src.basename, ".cgo2.c")) for src in cgo_srcs],
+    )
+
+def _cxx_wrapper(actions: AnalysisActions, go_toolchain: GoToolchainInfo, cgo_build_context: CGoBuildContext, own_pre: list[CPreprocessor]) -> cmd_args:
+    pre = cxx_merge_cpreprocessors(actions, own_pre, cgo_build_context.inherited_preprocessor_infos)
+    pre_args = pre.set.project_as_args("args")
+    pre_include_dirs = pre.set.project_as_args("include_dirs")
+
+    c_compiler = cgo_build_context.cxx_toolchain_info.c_compiler_info
+
+    # Construct the full C/C++ command needed to preprocess/compile sources.
+    cxx_cmd = cmd_args(
+        c_compiler.compiler,
+        c_compiler.preprocessor_flags,
+        cgo_build_context.target_sdk_version_flags,
+        c_compiler.compiler_flags,
+        pre_args,
+        pre_include_dirs,
+        go_toolchain.cxx_compiler_flags,
+    )
+
+    # Wrap the C/C++ command in a wrapper script to avoid arg length limits.
+    return cmd_script(
+        actions = actions,
+        name = "cxx_wrapper",
+        cmd = cxx_cmd,
+        language = cgo_build_context.exec_os_type.script,
+        has_content_based_path = True,
+    )
+
+# build CPreprocessor similar as cxx_private_preprocessor_info does, but with our filtered headers
+def _own_pre(actions: AnalysisActions, cgo_build_context: CGoBuildContext, package_root: str, h_files: list[Artifact]) -> CPreprocessor:
+    header_map = {paths.join(cgo_build_context.header_namespace, paths.relativize(h.short_path, package_root)): h for h in h_files}
+    header_root = prepare_headers(actions, cgo_build_context.cxx_toolchain_info, header_map, "h_files-private-headers", uses_content_based_paths = True)
+
+    return CPreprocessor(
+        args = CPreprocessorArgs(args = ["-I", header_root.include_path] if header_root != None else []),
+    )
+
+def build_cgo(
+    actions: AnalysisActions,
+    target_label: Label,
+    go_toolchain_info: GoToolchainInfo,
+    cgo_build_context: CGoBuildContext | None,
+    pkg_import_path: str,
+    package_root: str,
+    standard: bool,
+    cgo_files: list[Artifact],
+    h_files: list[Artifact],
+    c_files: list[Artifact],
+    c_flags: list[str],
+    cpp_flags: list[str],
+    anon_targets_allowed: bool = True,
+) -> (list[Artifact], list[Artifact], Artifact):
+    """
+    Arguments:
+        anon_targets_allowed: Set to `True` if the execution context allows calls to the `AnalysisActions#anon_target` API.
+                              For example, this API is NOT allowed in the context of the `AnalaysisActions#dynamic_outputs` callback.
+    """
+    if len(cgo_files) == 0:
+        return [], [], actions.copied_dir("cgo_gen_tmp", {}, has_content_based_path = True)
+
+    if cgo_build_context == None:
+        fail("cgo_build_context is None. This is likely because C++ toolchain is not available for the current target platform, but CGo files provided.")
+
+    # Gather preprocessor inputs.
+    own_pre = _own_pre(actions, cgo_build_context, package_root, h_files)
+
+    # Separate sources into C++ and GO sources.
+    cgo_tool_out, gen_dir = _cgo(actions, go_toolchain_info, cgo_build_context, pkg_import_path, standard, cgo_files, [own_pre], c_flags, cpp_flags)
+    go_gen_srcs = [cgo_tool_out.cgo_gotypes] + cgo_tool_out.cgo1_go_files
+    c_gen_headers = [cgo_tool_out.cgo_export_h]
+    c_gen_srcs = [cgo_tool_out.cgo_export_c] + cgo_tool_out.cgo2_c_files
+
+    # Wrap the generated CGO C headers in a CPreprocessor object for compiling.
+    cgo_headers_pre = CPreprocessor(
+        args = CPreprocessorArgs(
+            args = [
+                "-I",
+                prepare_headers(
+                    actions,
+                    cgo_build_context.cxx_toolchain_info,
+                    {h.basename: h for h in c_gen_headers},
+                    "cgo-private-headers",
+                    uses_content_based_paths = True,
+                ).include_path,
+            ]
+        )
+    )
+
+    # Compile C++ sources into object files.
+    c_compile_cmds = cxx_compile_srcs(
+        actions,
+        target_label,
+        cgo_build_context.cxx_toolchain_info,
+        CxxRuleConstructorParams(
+            rule_type = "cgo_sources",
+            headers_layout = cgo_build_context.headers_layout,
+            srcs = [CxxSrcWithFlags(file = src) for src in c_files + c_gen_srcs],
+            compiler_flags = go_toolchain_info.cxx_compiler_flags + c_flags + cgo_build_context.cxx_compiler_flags + cgo_build_context.target_sdk_version_flags,
+            preprocessor_flags = cpp_flags + cgo_build_context.cxx_preprocessor_flags,
+            anon_targets_allowed = anon_targets_allowed,
+            _cxx_toolchain = cgo_build_context._cxx_toolchain,
+            use_content_based_paths = True,
+        ),
+        # Create private header tree and propagate via args.
+        [own_pre, cgo_headers_pre],
+        cgo_build_context.inherited_preprocessor_infos,
+        [],
+        Linkage("any"),
+        False,  # add_coverage_instrumentation_compiler_flags
+    )
+
+    compiled_objects = c_compile_cmds.pic.objects
+
+    # Mark objects as requiring external linking since we're not currently supporting internal linking for CGo packages.
+    dynimportfail = actions.write("dynimportfail", "", has_content_based_path = True)
+
+    return go_gen_srcs, [dynimportfail] + compiled_objects, gen_dir
diff --git a/buck2/prelude/go/compile.bzl b/buck2/prelude/go/compile.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/compile.bzl
@@ -0,0 +1,51 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    ":packages.bzl",
+    "GoPkg",  # @Unused used as type
+    "merge_pkgs",
+)
+
+# Provider wrapping packages used for compiling.
+GoPkgCompileInfo = provider(
+    fields = {
+        "pkgs": provider_field(typing.Any, default = None),  # dict[str, GoPkg]
+    }
+)
+
+# Provider for test targets that test a library. Contains information for
+# compiling the test and library code together as expected by go.
+GoTestInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "deps": provider_field(typing.Any, default = None),  # [Dependency]
+        "srcs": provider_field(typing.Any, default = None),  # ["source"]
+        "pkg_import_path": provider_field(typing.Any, default = None),  # str
+        "coverage_enabled": provider_field(bool),
+    },
+)
+
+def get_inherited_compile_pkgs(deps: list[Dependency]) -> dict[str, GoPkg]:
+    return merge_pkgs([d[GoPkgCompileInfo].pkgs for d in deps if GoPkgCompileInfo in d])
+
+def infer_package_root(srcs: list[Artifact]) -> str:
+    go_sources = [s for s in srcs if s.extension == ".go"]
+    if len(go_sources) == 0:
+        return ""
+    dir_set = set([paths.dirname(s.short_path) for s in go_sources])
+    if len(dir_set) > 1:
+        fail(
+            "Provide `package_root` target attribute. Can't infer it when there are multiple directories containing .go files: {}. Sources: {}".format(
+                dir_set,
+                [s.short_path for s in go_sources],
+            )
+        )
+
+    return list(dir_set)[0]
diff --git a/buck2/prelude/go/constraints/BUCK b/buck2/prelude/go/constraints/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/constraints/BUCK
@@ -0,0 +1,27 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+constraint(
+    name = "cgo_enabled",
+    default = "true",
+    values = [
+        "true",
+        "false",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+constraint(
+    name = "coverage_mode",
+    default = "none",
+    values = [
+        "none",
+        "set",
+        "count",
+        "atomic",
+    ],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/go/coverage.bzl b/buck2/prelude/go/coverage.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/coverage.bzl
@@ -0,0 +1,72 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":toolchain.bzl", "GoToolchainInfo", "get_toolchain_env_vars")
+
+GoCoverageMode = enum(
+    "set",
+    "count",
+    "atomic",
+)
+
+def cover_srcs(
+    actions: AnalysisActions,
+    go_toolchain: GoToolchainInfo,
+    pkg_name: str,
+    pkg_import_path: str,
+    go_files: list[Artifact],
+    cgo_files: list[Artifact],
+    coverage_enabled: bool,
+    coverage_mode: GoCoverageMode | None,
+) -> (list[Artifact], list[Artifact], Artifact | None):
+    if not coverage_enabled or coverage_mode == None:
+        return go_files, cgo_files, None
+
+    if len(go_files) + len(cgo_files) == 0:
+        return go_files, cgo_files, None
+
+    env = get_toolchain_env_vars(go_toolchain)
+
+    cover_meta_file = actions.declare_output("cover_meta.bin", has_content_based_path = True)
+    out_config_file = actions.declare_output("out_config.json", has_content_based_path = True)
+
+    # Based on https://pkg.go.dev/cmd/internal/cov/covcmd#CoverPkgConfig
+    pkgcfg = {
+        "EmitMetaFile": cover_meta_file.as_output(),
+        "Granularity": "perblock",
+        "Local": True,
+        "ModulePath": "",
+        "OutConfig": out_config_file.as_output(),
+        "PkgName": pkg_name,
+        "PkgPath": pkg_import_path,
+    }
+    pkgcfg_file = actions.write_json("pkg.cfg", pkgcfg, has_content_based_path = True)
+
+    # Grab the first 16 characters of sha256.
+    # This is sufficient to make the coverage variable unique enough
+    # while keeping the instrumented file a bit more readable.
+    var = "GoCover_" + sha256(pkg_import_path)[:16]
+    instrum_vars_file = actions.declare_output("with_instrumentation", "instrum_vars.go", has_content_based_path = True)
+    instrum_go_files = [actions.declare_output("with_instrumentation", go_file.short_path, has_content_based_path = True) for go_file in go_files]
+    instrum_cgo_files = [actions.declare_output("with_instrumentation", cgo_file.short_path, has_content_based_path = True) for cgo_file in cgo_files]
+    instrum_all_files = [instrum_vars_file] + instrum_go_files + instrum_cgo_files
+    outfilelist = actions.write("outfilelist.txt", cmd_args([f.as_output() for f in instrum_all_files], ""), has_content_based_path = True)
+
+    cover_cmd = [
+        go_toolchain.cover,
+        ["-mode", coverage_mode.value],
+        ["-var", var],
+        cmd_args(["-outfilelist", outfilelist], hidden = [f.as_output() for f in instrum_all_files]),
+        cmd_args(["-pkgcfg", pkgcfg_file], hidden = [cover_meta_file.as_output(), out_config_file.as_output()]),
+        go_files,
+        cgo_files,
+    ]
+
+    actions.run(cover_cmd, env = env, category = "go_cover", identifier = pkg_import_path, allow_cache_upload = go_toolchain.allow_cache_upload)
+
+    return [instrum_vars_file] + instrum_go_files, instrum_cgo_files, out_config_file
diff --git a/buck2/prelude/go/go_binary.bzl b/buck2/prelude/go/go_binary.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/go_binary.bzl
@@ -0,0 +1,99 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifacts.bzl", "single_artifact")
+load("@prelude//dist:dist_info.bzl", "DistInfo")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkStyle",
+)
+load(
+    "@prelude//utils:utils.bzl",
+    "from_named_set",
+    "map_val",
+    "value_or",
+)
+load(":cgo_builder.bzl", "get_cgo_build_context")
+load(":compile.bzl", "GoTestInfo")
+load(":coverage.bzl", "GoCoverageMode")
+load(":link.bzl", "GoBuildMode", "link")
+load(":package_builder.bzl", "GoBuildConfig", "GoSourceInputs", "declare_package_build")
+load(":packages.bzl", "go_attr_pkg_name")
+load(":toolchain.bzl", "evaluate_cgo_enabled")
+
+def go_binary_impl(ctx: AnalysisContext) -> list[Provider]:
+    pkg_import_path = go_attr_pkg_name(ctx)
+    cgo_enabled = evaluate_cgo_enabled(ctx.attrs._cgo_enabled)
+    coverage_mode = GoCoverageMode(ctx.attrs._coverage_mode) if ctx.attrs._coverage_mode else None
+    cgo_build_context = get_cgo_build_context(ctx)
+
+    lib, pkg_info, _ = declare_package_build(
+        ctx = ctx,
+        pkg_import_path = pkg_import_path,
+        main = True,
+        sources = GoSourceInputs(
+            srcs = ctx.attrs.srcs + ctx.attrs.headers,
+            embed_srcs = from_named_set(ctx.attrs.embed_srcs),
+            package_root = ctx.attrs.package_root,
+        ),
+        cgo_build_context = cgo_build_context,
+        config = GoBuildConfig(
+            compiler_flags = ctx.attrs.compiler_flags,
+            build_tags = ctx.attrs._build_tags,
+            cgo_enabled = cgo_enabled,
+            coverage_enabled = ctx.attrs.coverage_enabled,
+            coverage_mode = coverage_mode,
+        ),
+        deps = ctx.attrs.deps,
+    )
+    (bin, runtime_files, external_debug_info) = link(
+        ctx,
+        lib,
+        cgo_enabled = cgo_enabled,
+        deps = ctx.attrs.deps,
+        link_style = value_or(map_val(LinkStyle, ctx.attrs.link_style), LinkStyle("static")),
+        build_mode = GoBuildMode(value_or(ctx.attrs.build_mode, "exe")),
+        linker_flags = ctx.attrs.linker_flags,
+        link_mode = ctx.attrs.link_mode,
+        external_linker_flags = ctx.attrs.external_linker_flags,
+    )
+
+    # runtime_files are all the artifacts that must be present in order for this
+    # binary to be runnable. Notably, all of its shared library dependencies.
+    # This is materialized when a Go binary is executed as a genrule.
+    #
+    # other_outputs is a superset of runtime_files, adding external debuginfo
+    # which is necessary for a user to run this binary in a debugger. This is
+    # materialized when a Go binary is the end result of a build.
+    runtime_files = list(runtime_files)
+    other_outputs = runtime_files + external_debug_info
+
+    for resource in ctx.attrs.resources:
+        resource = single_artifact(resource)
+
+        runtime_files.append(resource.default_output)
+        runtime_files.extend(resource.nondebug_runtime_files)
+
+        other_outputs.append(resource.default_output)
+        other_outputs.extend(resource.other_outputs)
+
+    return [
+        DefaultInfo(
+            default_output = bin,
+            other_outputs = other_outputs,
+        ),
+        RunInfo(args = cmd_args(bin, hidden = other_outputs)),
+        DistInfo(nondebug_runtime_files = runtime_files),
+        GoTestInfo(
+            deps = ctx.attrs.deps,
+            srcs = ctx.attrs.srcs,
+            pkg_import_path = pkg_import_path,
+            coverage_enabled = ctx.attrs.coverage_enabled,
+        ),
+        pkg_info,
+    ]
diff --git a/buck2/prelude/go/go_error_handler.bzl b/buck2/prelude/go/go_error_handler.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/go_error_handler.bzl
@@ -0,0 +1,24 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def go_build_error_handler(ctx: ActionErrorCtx) -> list[ActionSubError]:
+    structured_errors = ctx.parse_with_errorformat(
+        category = "go_compile_error",
+        error = ctx.stdout,
+        # reference: https://github.com/fatih/vim-go/blob/06ac99359b0b1a7de1e213447d92fd0a46cb4cd0/compiler/go.vim#L34-L40
+        errorformats = [
+            "%-G#\\ %.%#",  # Ignore lines beginning with '#' ('# command-line-arguments' line sometimes appears?)
+            "%-G%.%#panic:\\ %m",  # Ignore lines containing 'panic: message'
+            "%Ecan't\\ load\\ package:\\ %m",  # Start of multiline error string is 'can\'t load package'
+            "%A\\(\\[\\^:]\\+:\\ \\)\\?%f:%l:%c:\\ %m",  # Start of multiline unspecified string is 'filename:linenumber:columnnumber:'
+            "%A\\(\\[\\^:]\\+:\\ \\)\\?%f:%l:\\ %m",  # Start of multiline unspecified string is 'filename:linenumber:'
+            "%C%*\\s%m",  # Continuation of multiline error message is indented
+            "%-G%.%#",  # All lines not matching any of the above patterns are ignored
+        ],
+    )
+    return structured_errors
diff --git a/buck2/prelude/go/go_exported_library.bzl b/buck2/prelude/go/go_exported_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/go_exported_library.bzl
@@ -0,0 +1,188 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("@prelude//cxx:linker.bzl", "get_default_shared_library_name")
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+)
+load(
+    "@prelude//linking:link_groups.bzl",
+    "merge_link_group_lib_info",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "Archive",
+    "ArchiveLinkable",
+    "LibOutputStyle",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkStyle",
+    "LinkedObject",
+    "MergedLinkInfo",  # @unused Used as a type
+    "SharedLibLinkable",
+    "create_merged_link_info",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+    "create_linkable_node",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraries",
+    "SharedLibraryInfo",
+    "create_shlib",
+    "merge_shared_libraries",
+)
+load(
+    "@prelude//utils:utils.bzl",
+    "from_named_set",
+    "map_idx",
+    "map_val",
+    "value_or",
+)
+load(":cgo_builder.bzl", "get_cgo_build_context")
+load(":compile.bzl", "GoTestInfo")
+load(":link.bzl", "GoBuildMode", "link")
+load(":package_builder.bzl", "GoBuildConfig", "GoSourceInputs", "declare_package_build")
+load(":packages.bzl", "cgo_exported_preprocessor", "go_attr_pkg_name")
+load(":toolchain.bzl", "evaluate_cgo_enabled")
+
+def go_exported_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    pkg_import_path = go_attr_pkg_name(ctx)
+    cgo_enabled = evaluate_cgo_enabled(ctx.attrs._cgo_enabled)
+    cgo_build_context = get_cgo_build_context(ctx)
+
+    lib, pkg_info, _ = declare_package_build(
+        ctx = ctx,
+        pkg_import_path = pkg_import_path,
+        main = True,
+        sources = GoSourceInputs(
+            srcs = ctx.attrs.srcs,
+            embed_srcs = from_named_set(ctx.attrs.embed_srcs),
+            package_root = ctx.attrs.package_root,
+        ),
+        cgo_build_context = cgo_build_context,
+        config = GoBuildConfig(
+            compiler_flags = ctx.attrs.compiler_flags,
+            build_tags = ctx.attrs._build_tags,
+            cgo_enabled = cgo_enabled,
+        ),
+        deps = ctx.attrs.deps,
+    )
+
+    def link_variant(build_mode: GoBuildMode):
+        (exp_lib, _, _) = link(
+            ctx,
+            lib,
+            cgo_enabled = cgo_enabled,
+            deps = ctx.attrs.deps,
+            build_mode = build_mode,
+            link_style = value_or(map_val(LinkStyle, ctx.attrs.link_style), LinkStyle("static_pic")),
+            linker_flags = ctx.attrs.linker_flags,
+            external_linker_flags = ctx.attrs.external_linker_flags,
+        )
+        return exp_lib
+
+    c_archive = link_variant(GoBuildMode("c_archive"))  # .a - PIC-arcive
+    c_shared = link_variant(GoBuildMode("c_shared"))  # .so - PIC-shared_lib
+
+    cxx_toolchain = ctx.attrs._cxx_toolchain[CxxToolchainInfo]
+
+    soname = get_default_shared_library_name(cxx_toolchain.linker_info, ctx.label)
+
+    link_infos = {
+        LibOutputStyle("archive"): LinkInfos(
+            default = LinkInfo(
+                linkables = [
+                    ArchiveLinkable(
+                        archive = Archive(artifact = c_archive),
+                        linker_type = cxx_toolchain.linker_info.type,
+                    )
+                ]
+            ),
+        ),
+        LibOutputStyle("pic_archive"): LinkInfos(
+            default = LinkInfo(
+                linkables = [
+                    ArchiveLinkable(
+                        archive = Archive(artifact = c_archive),
+                        linker_type = cxx_toolchain.linker_info.type,
+                    )
+                ]
+            ),
+        ),
+        LibOutputStyle("shared_lib"): LinkInfos(
+            default = LinkInfo(
+                linkables = [
+                    SharedLibLinkable(
+                        lib = c_shared,
+                    )
+                ]
+            ),
+        ),
+    }
+
+    shared_libs = SharedLibraries(
+        libraries = [
+            create_shlib(
+                soname = soname,
+                label = ctx.label,
+                lib = LinkedObject(
+                    output = c_shared,
+                    unstripped_output = c_shared,
+                ),
+            ),
+        ]
+    )
+
+    own_exported_preprocessors = [cgo_exported_preprocessor(ctx, pkg_info)] if ctx.attrs.generate_exported_header else []
+
+    return [
+        DefaultInfo(
+            default_output = c_archive if ctx.attrs.build_mode == "c_archive" else c_shared,
+        ),
+        GoTestInfo(
+            deps = ctx.attrs.deps,
+            srcs = ctx.attrs.srcs,
+            pkg_import_path = pkg_import_path,
+            coverage_enabled = ctx.attrs.coverage_enabled,
+        ),
+        create_merged_link_info(
+            ctx,
+            cxx_toolchain.pic_behavior,
+            link_infos = link_infos,
+            deps = filter(None, map_idx(MergedLinkInfo, ctx.attrs.deps)),
+        ),
+        merge_shared_libraries(
+            ctx.actions,
+            node = shared_libs,
+            deps = filter(None, map_idx(SharedLibraryInfo, ctx.attrs.deps)),
+        ),
+        merge_link_group_lib_info(deps = ctx.attrs.deps),
+        create_linkable_graph(
+            ctx,
+            node = create_linkable_graph_node(
+                ctx,
+                linkable_node = create_linkable_node(
+                    ctx,
+                    default_soname = soname,
+                    deps = ctx.attrs.deps,
+                    link_infos = link_infos,
+                    shared_libs = shared_libs,
+                ),
+            ),
+            deps = ctx.attrs.deps,
+        ),
+        cxx_merge_cpreprocessors(ctx.actions, own_exported_preprocessors, cxx_inherited_preprocessor_infos(ctx.attrs.deps)),
+        pkg_info,
+    ]
diff --git a/buck2/prelude/go/go_library.bzl b/buck2/prelude/go/go_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/go_library.bzl
@@ -0,0 +1,150 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+)
+load(
+    "@prelude//linking:link_groups.bzl",
+    "merge_link_group_lib_info",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkInfo",
+    "LinkInfos",
+    "MergedLinkInfo",
+    "create_merged_link_info_for_propagation",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+    "create_linkable_node",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "merge_shared_libraries",
+)
+load(
+    "@prelude//utils:utils.bzl",
+    "from_named_set",
+    "map_idx",
+)
+load(":cgo_builder.bzl", "get_cgo_build_context")
+load(":compile.bzl", "GoPkgCompileInfo", "GoTestInfo")
+load(":coverage.bzl", "GoCoverageMode")
+load(":link.bzl", "GoPkgLinkInfo", "get_inherited_link_pkgs")
+load(":package_builder.bzl", "GoBuildConfig", "GoSourceInputs", "declare_package_build")
+load(":packages.bzl", "cgo_exported_preprocessor", "go_attr_pkg_name", "merge_pkgs")
+load(":toolchain.bzl", "GoToolchainInfo", "evaluate_cgo_enabled", "get_toolchain_env_vars")
+
+def go_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    pkg_import_path = go_attr_pkg_name(ctx)
+
+    coverage_mode = GoCoverageMode(ctx.attrs._coverage_mode) if ctx.attrs._coverage_mode else None
+    cgo_build_context = get_cgo_build_context(ctx)
+
+    pkg, pkg_info, _ = declare_package_build(
+        ctx = ctx,
+        pkg_import_path = pkg_import_path,
+        main = False,
+        sources = GoSourceInputs(
+            srcs = ctx.attrs.srcs + ctx.attrs.headers,
+            embed_srcs = from_named_set(ctx.attrs.embed_srcs),
+            package_root = ctx.attrs.package_root,
+        ),
+        cgo_build_context = cgo_build_context,
+        config = GoBuildConfig(
+            compiler_flags = ctx.attrs.compiler_flags,
+            assembler_flags = ctx.attrs.assembler_flags,
+            build_tags = ctx.attrs._build_tags,
+            coverage_enabled = ctx.attrs.coverage_enabled,
+            coverage_mode = coverage_mode,
+            cgo_enabled = evaluate_cgo_enabled(ctx.attrs._cgo_enabled, ctx.attrs.override_cgo_enabled),
+        ),
+        deps = ctx.attrs.deps,
+    )
+
+    default_output = _combine_package(ctx, pkg_import_path, pkg.archive_file, pkg.export_file)
+    pkgs = {
+        pkg_import_path: pkg,
+    }
+
+    own_exported_preprocessors = [cgo_exported_preprocessor(ctx, pkg_info)] if ctx.attrs.generate_exported_header else []
+
+    return [
+        DefaultInfo(default_output = default_output),
+        GoPkgCompileInfo(pkgs = pkgs),
+        GoPkgLinkInfo(
+            pkgs = merge_pkgs([
+                pkgs,
+                get_inherited_link_pkgs(ctx.attrs.deps),
+            ])
+        ),
+        GoTestInfo(
+            deps = ctx.attrs.deps,
+            srcs = ctx.attrs.srcs,
+            pkg_import_path = pkg_import_path,
+            coverage_enabled = ctx.attrs.coverage_enabled,
+        ),
+        create_merged_link_info_for_propagation(ctx, filter(None, [d.get(MergedLinkInfo) for d in ctx.attrs.deps])),
+        merge_shared_libraries(
+            ctx.actions,
+            deps = filter(None, map_idx(SharedLibraryInfo, ctx.attrs.deps)),
+        ),
+        merge_link_group_lib_info(deps = ctx.attrs.deps),
+        create_linkable_graph(
+            ctx,
+            # Linkable graph nodes must be present for link_groups operation (even if there are nothing to provide).
+            # Borrowing the this approach from Ocaml.
+            # Though his doesn't look entirely right.
+            node = create_linkable_graph_node(
+                ctx,
+                linkable_node = create_linkable_node(
+                    ctx,
+                    default_soname = None,
+                    exported_deps = ctx.attrs.deps,
+                    link_infos = _get_empty_link_infos(),
+                ),
+            ),
+            deps = ctx.attrs.deps,
+        ),
+        cxx_merge_cpreprocessors(ctx.actions, own_exported_preprocessors, cxx_inherited_preprocessor_infos(ctx.attrs.deps)),
+        pkg_info,
+    ]
+
+def _get_empty_link_infos() -> dict[LibOutputStyle, LinkInfos]:
+    infos = {}
+    for output_style in LibOutputStyle:
+        infos[output_style] = LinkInfos(default = LinkInfo())
+    return infos
+
+# The combined package is convinient for debugging purposes, but for actual builds we use separate objects.
+def _combine_package(ctx: AnalysisContext, pkg_import_path: str, a_file: Artifact, x_file: Artifact) -> Artifact:
+    go_toolchain = ctx.attrs._go_toolchain[GoToolchainInfo]
+    env = get_toolchain_env_vars(go_toolchain)
+
+    pkg_file = ctx.actions.declare_output(paths.basename(pkg_import_path) + "-combined.a", has_content_based_path = True)
+
+    pack_cmd = [
+        go_toolchain.packer,
+        "c",
+        pkg_file.as_output(),
+        a_file,
+        x_file,
+    ]
+
+    identifier = paths.basename(pkg_import_path) + "-combined"
+    ctx.actions.run(pack_cmd, env = env, category = "go_pack", identifier = identifier, allow_cache_upload = go_toolchain.allow_cache_upload)
+
+    return pkg_file
diff --git a/buck2/prelude/go/go_list.bzl b/buck2/prelude/go/go_list.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/go_list.bzl
@@ -0,0 +1,159 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(":toolchain.bzl", "GoToolchainInfo", "get_toolchain_env_vars")
+
+GoListError = record(
+    err = field(str),
+)
+
+# Modeled after: https://pkg.go.dev/cmd/go/internal/list#pkg-variables
+GoListOut = record(
+    name = field(str),
+    imports = field(list[str], default = []),
+    test_imports = field(list[str], default = []),
+    go_files = field(list[Artifact], default = []),
+    h_files = field(list[Artifact], default = []),
+    c_files = field(list[Artifact], default = []),
+    cxx_files = field(list[Artifact], default = []),
+    cgo_files = field(list[Artifact], default = []),
+    s_files = field(list[Artifact], default = []),
+    syso_files = field(list[Artifact], default = []),
+    test_go_files = field(list[Artifact], default = []),
+    x_test_go_files = field(list[Artifact], default = []),
+    ignored_go_files = field(list[Artifact], default = []),
+    ignored_other_files = field(list[Artifact], default = []),
+    cgo_cflags = field(list[str], default = []),
+    cgo_cppflags = field(list[str], default = []),
+    embed_patterns = field(list[str], default = []),
+    test_embed_patterns = field(list[str], default = []),
+    error = field(GoListError | None, default = None),
+)
+
+def go_list(
+    actions: AnalysisActions,
+    go_toolchain: GoToolchainInfo,
+    pkg_import_path: str,
+    srcs: list[Artifact],
+    package_root: str,
+    build_tags: list[str],
+    cgo_enabled: bool,
+    with_tests: bool,
+) -> Artifact:
+    env = get_toolchain_env_vars(go_toolchain)
+
+    go_list_out = actions.declare_output(paths.basename(pkg_import_path) + "_go_list.json", has_content_based_path = True)
+
+    srcs_dir = actions.symlinked_dir(
+        "__{}_srcs_dir__".format(paths.basename(pkg_import_path)),
+        {src.short_path.removeprefix(package_root).lstrip("/"): src for src in srcs},
+        has_content_based_path = True,
+    )
+    all_tags = [] + go_toolchain.build_tags + build_tags
+
+    go_list_args = [
+        go_toolchain.pkg_analyzer,
+        ["-o", go_list_out.as_output()],
+        ["-goos", go_toolchain.env_go_os],
+        ["-goarch", go_toolchain.env_go_arch],
+        [["-tags", ",".join(all_tags)] if all_tags else []],
+        ["-race"] if go_toolchain.race and cgo_enabled else [],
+        ["-asan"] if go_toolchain.asan and cgo_enabled else [],
+        ["-cgo"] if cgo_enabled else [],
+        ["-tests"] if with_tests else [],
+        srcs_dir,
+    ]
+
+    identifier = paths.basename(pkg_import_path)
+    actions.run(go_list_args, env = env, category = "go_list", identifier = identifier, allow_cache_upload = go_toolchain.allow_cache_upload)
+
+    return go_list_out
+
+def parse_go_list_out(srcs: list[Artifact], package_root: str, go_list_out: ArtifactValue) -> GoListOut:
+    go_list = go_list_out.read_json()
+    go_files, cgo_files, h_files, c_files, cxx_files, s_files, syso_files, test_go_files, x_test_go_files, ignored_go_files, ignored_other_files = (
+        [],
+        [],
+        [],
+        [],
+        [],
+        [],
+        [],
+        [],
+        [],
+        [],
+        [],
+    )
+
+    for src in srcs:
+        # remove package_root prefix from src artifact path to match `go list` output format
+        src_path = src.short_path.removeprefix(package_root).lstrip("/")
+        if src_path in go_list.get("GoFiles", []):
+            go_files.append(src)
+        if src_path in go_list.get("CgoFiles", []):
+            cgo_files.append(src)
+        if src_path in go_list.get("HFiles", []):
+            h_files.append(src)
+        if src_path in go_list.get("CFiles", []):
+            c_files.append(src)
+        if src_path in go_list.get("CXXFiles", []):
+            cxx_files.append(src)
+        if src_path in go_list.get("SFiles", []):
+            s_files.append(src)
+        if src_path in go_list.get("SysoFiles", []):
+            syso_files.append(src)
+        if src_path in go_list.get("TestGoFiles", []):
+            test_go_files.append(src)
+        if src_path in go_list.get("XTestGoFiles", []):
+            x_test_go_files.append(src)
+        if src_path in go_list.get("IgnoredGoFiles", []):
+            ignored_go_files.append(src)
+        if src_path in go_list.get("IgnoredOtherFiles", []):
+            ignored_other_files.append(src)
+
+    name = go_list.get("Name", "")
+    imports = go_list.get("Imports", [])
+    test_imports = go_list.get("TestImports", [])
+    cgo_cflags = go_list.get("CgoCFLAGS", [])
+    cgo_cppflags = go_list.get("CgoCPPFLAGS", [])
+    embed_patterns = go_list.get("EmbedPatterns", [])
+    test_embed_patterns = go_list.get("TestEmbedPatterns", [])
+    error = _parse_error(go_list.get("Error", None))
+
+    return GoListOut(
+        name = name,
+        imports = imports,
+        test_imports = test_imports,
+        go_files = go_files,
+        h_files = h_files,
+        c_files = c_files,
+        cxx_files = cxx_files,
+        cgo_files = cgo_files,
+        s_files = s_files,
+        syso_files = syso_files,
+        test_go_files = test_go_files,
+        x_test_go_files = x_test_go_files,
+        cgo_cflags = cgo_cflags,
+        cgo_cppflags = cgo_cppflags,
+        ignored_go_files = ignored_go_files,
+        ignored_other_files = ignored_other_files,
+        embed_patterns = embed_patterns,
+        test_embed_patterns = test_embed_patterns,
+        error = error,
+    )
+
+def _parse_error(error: dict | None) -> GoListError | None:
+    if error == None:
+        return None
+
+    if "Err" not in error:
+        # Should never happen, but if it does, fail the build.
+        fail("Invalid go_analyzer error: {}".format(error))
+
+    return GoListError(err = error.get("Err"))
diff --git a/buck2/prelude/go/go_list_stdlib.bzl b/buck2/prelude/go/go_list_stdlib.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/go_list_stdlib.bzl
@@ -0,0 +1,85 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":go_list.bzl", "GoListOut")
+load(":toolchain.bzl", "GoToolchainInfo", "get_toolchain_env_vars")
+
+def go_list_stdlib(actions: AnalysisActions, go_toolchain: GoToolchainInfo, cgo_enabled: bool) -> Artifact:
+    env = get_toolchain_env_vars(go_toolchain)
+
+    if go_toolchain.env_go_root == None:
+        fail("GOROOT has to be set ahead of time for native stdlib build")
+
+    # Hack: cut out redundant dependencies as we only care about "src" dir
+    env["GOROOT"] = cmd_args(go_toolchain.env_go_root.project("src"), parent = 1)
+
+    env["CGO_ENABLED"] = "1" if cgo_enabled else "0"
+
+    go_list_stdlib_out = actions.declare_output("go_list_stdlib.txt", has_content_based_path = True)
+    go_list_args = [
+        go_toolchain.go_wrapper,
+        ["--go", go_toolchain.go],
+        ["--output", go_list_stdlib_out.as_output()],
+        "--convert-json-stream",
+        "list",
+        "-json=ImportPath,ImportMap,EmbedFiles,Name,Imports,GoFiles,HFiles,CFiles,CXXFiles,CgoFiles,SFiles,SysoFiles,CgoCFLAGS,CgoCPPFLAGS,IgnoredGoFiles,IgnoredOtherFiles,EmbedPatterns",
+        ["-tags", ",".join(go_toolchain.build_tags)] if go_toolchain.build_tags else [],
+        ["-race"] if go_toolchain.race and cgo_enabled else [],
+        ["-asan"] if go_toolchain.asan and cgo_enabled else [],
+        "std",
+    ]
+    actions.run(go_list_args, env = env, category = "go_list_stdlib", allow_cache_upload = go_toolchain.allow_cache_upload)
+
+    return go_list_stdlib_out
+
+StdGoListOut = record(
+    import_path = field(str),
+    import_map = field(dict[str, str]),
+    embed_files = field(list[Artifact]),
+    go_list = field(GoListOut),
+)
+
+def parse_go_list_stdlib_out(goroot: Artifact, go_list: dict) -> StdGoListOut:
+    import_path = go_list.get("ImportPath", "")
+
+    def project_files(files: list[str]) -> list[Artifact]:
+        return [goroot.project("src/" + import_path + "/" + f) for f in files]
+
+    h_files = go_list.get("HFiles", [])
+    if import_path == "runtime":
+        # Hack: `go list` doesn't provide information about this dependency
+        # but we have to declare it to generate -I flag correctly,
+        # this wouldn't work if these files were not in a sub-directory.
+        h_files.extend([
+            "cgo/abi_amd64.h",
+            "cgo/abi_loong64.h",
+            "cgo/abi_arm64.h",
+            "cgo/abi_ppc64x.h",
+        ])
+
+    return StdGoListOut(
+        import_path = import_path,
+        import_map = go_list.get("ImportMap", {}),
+        embed_files = project_files(go_list.get("EmbedFiles", [])),
+        go_list = GoListOut(
+            name = go_list.get("Name", ""),
+            imports = go_list.get("Imports", []),
+            go_files = project_files(go_list.get("GoFiles", [])),
+            h_files = project_files(h_files),
+            c_files = project_files(go_list.get("CFiles", [])),
+            cxx_files = project_files(go_list.get("CXXFiles", [])),
+            cgo_files = project_files(go_list.get("CgoFiles", [])),
+            s_files = project_files(go_list.get("SFiles", [])),
+            syso_files = project_files(go_list.get("SysoFiles", [])),
+            cgo_cflags = go_list.get("CgoCFLAGS", []),
+            cgo_cppflags = go_list.get("CgoCPPFLAGS", []),
+            ignored_go_files = project_files(go_list.get("IgnoredGoFiles", [])),
+            ignored_other_files = project_files(go_list.get("IgnoredOtherFiles", [])),
+            embed_patterns = go_list.get("EmbedPatterns", []),
+        ),
+    )
diff --git a/buck2/prelude/go/go_stdlib.bzl b/buck2/prelude/go/go_stdlib.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/go_stdlib.bzl
@@ -0,0 +1,233 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_context.bzl", "get_opt_cxx_toolchain_info")
+load("@prelude//cxx:headers.bzl", "CxxHeadersLayout", "CxxHeadersNaming")
+load("@prelude//cxx:target_sdk_version.bzl", "get_target_sdk_version_flags")
+load("@prelude//os_lookup:defs.bzl", "OsLookup")
+load("@prelude//utils:graph_utils.bzl", "post_order_traversal")
+load(
+    ":cgo_builder.bzl",
+    "CGoBuildContext",  # @Unused used as type
+)
+load(":go_list_stdlib.bzl", "go_list_stdlib", "parse_go_list_stdlib_out")
+load(":package_builder.bzl", "BuildPackageGoList", "BuildPackageParams", "build_package", "go_list_for_build")
+load(":packages.bzl", "GoPkg", "GoStdlib", "GoStdlibDynamicValue", "implicit_imports")
+load(":toolchain.bzl", "GoToolchainInfo", "evaluate_cgo_enabled")
+
+def go_stdlib_impl(ctx: AnalysisContext) -> list[Provider]:
+    go_toolchain = ctx.attrs._go_toolchain[GoToolchainInfo]
+
+    cgo_enabled = evaluate_cgo_enabled(ctx.attrs._cgo_enabled)
+
+    go_list_stdlib_out = go_list_stdlib(ctx.actions, go_toolchain, cgo_enabled)
+
+    pkgdir = ctx.actions.declare_output("pkgdir", dir = True, has_content_based_path = True)
+
+    go_stdlib_value = ctx.actions.dynamic_output_new(
+        _build_stdlib(
+            goroot = go_toolchain.env_go_root,
+            go_list_stdlib_out = go_list_stdlib_out,
+            target_label = ctx.label,
+            go_toolchain = go_toolchain,
+            cgo_build_context = get_cgo_build_context(ctx),
+            pkgdir = pkgdir.as_output(),
+        )
+    )
+
+    return [
+        DefaultInfo(default_output = pkgdir),
+        GoStdlib(dynamic_value = go_stdlib_value),
+    ]
+
+def _build_stdlib_impl(
+    actions: AnalysisActions,
+    target_label: Label,
+    go_toolchain: GoToolchainInfo,
+    cgo_build_context: None | CGoBuildContext,
+    go_list_stdlib_out: ArtifactValue,
+    goroot: Artifact,
+    pkgdir: OutputArtifact,
+) -> list[Provider]:
+    # First pass: parse all packages and collect their imports
+    parsed_libs = {}  # import_path -> StdGoListOut
+    for lib in go_list_stdlib_out.read_json():
+        lib = parse_go_list_stdlib_out(goroot, lib)
+        if len(lib.go_list.go_files) == 0 and len(lib.go_list.cgo_files) == 0:
+            continue  # skip test only packages
+
+        if lib.import_path in ["unsafe", "builtin"]:
+            continue  # skip fake packages
+
+        parsed_libs[lib.import_path] = lib
+
+    # Build dependency graph: import_path -> [imports that are also in stdlib]
+    dep_graph = {}
+    for import_path, lib in parsed_libs.items():
+        dep_graph[import_path] = []
+
+        all_imports = set(lib.go_list.imports) | implicit_imports(
+            pkg_name = lib.go_list.name,
+            pkg_import_path = import_path,
+            standard = True,
+            has_cgo_files = len(lib.go_list.cgo_files) > 0,
+            coverage_enabled = False,
+            coverage_mode = None,
+        )
+        for imp in all_imports:
+            if imp in parsed_libs:
+                dep_graph[import_path].append(imp)
+
+    # Topological sort: post_order_traversal returns leaves (no deps) first,
+    # giving us the correct build order (dependencies before dependents)
+    build_order = post_order_traversal(dep_graph)
+
+    # Second pass: build packages in dependency order
+    pkgs = {}
+    for import_path in build_order:
+        lib = parsed_libs[import_path]
+
+        pkgs[lib.import_path] = _declare_stdlib_package_build(
+            actions = actions,
+            target_label = target_label,
+            go_toolchain = go_toolchain,
+            cgo_build_context = cgo_build_context,
+            go_list = go_list_for_build(lib.go_list, False),
+            params = BuildPackageParams(
+                main = False,
+                standard = True,
+                pkg_import_path = lib.import_path,
+                package_root = goroot.short_path + "/src/" + lib.import_path,
+                embed_srcs = {src.short_path: src for src in lib.embed_files},
+                compiler_flags = [],
+                assembler_flags = [],
+                coverage_enabled = False,
+                coverage_mode = None,  # we can switch-on stdlib coverage later if needed
+                deps = pkgs,
+                import_map = lib.import_map,
+            ),
+        )
+
+    # We use pkgdir artifact testing (and currently for mockgen), but not for compilation/linking
+    actions.copied_dir(
+        pkgdir,
+        {path + ".a": pkg.archive_file for path, pkg in pkgs.items()} | {path + ".x": pkg.export_file for path, pkg in pkgs.items()},
+    )
+
+    return [
+        GoStdlibDynamicValue(pkgs = pkgs),
+    ]
+
+_build_stdlib = dynamic_actions(
+    impl = _build_stdlib_impl,
+    attrs = {
+        "cgo_build_context": dynattrs.value(None | CGoBuildContext),
+        "go_list_stdlib_out": dynattrs.artifact_value(),
+        "go_toolchain": dynattrs.value(GoToolchainInfo),
+        "goroot": dynattrs.value(Artifact),
+        "pkgdir": dynattrs.output(),
+        "target_label": dynattrs.value(Label),
+    },
+)
+
+def _declare_stdlib_package_build(
+    actions: AnalysisActions,
+    target_label: Label,
+    go_toolchain: GoToolchainInfo,
+    cgo_build_context: None | CGoBuildContext,
+    go_list: BuildPackageGoList,
+    params: BuildPackageParams,
+) -> GoPkg:
+    out_a = actions.declare_output(params.pkg_import_path + "_non-shared.a", has_content_based_path = True)
+    out_x = actions.declare_output(params.pkg_import_path + "_non-shared.x", has_content_based_path = True)
+
+    out_a_shared = actions.declare_output(params.pkg_import_path + "_shared.a", has_content_based_path = True)
+    out_x_shared = actions.declare_output(params.pkg_import_path + "_shared.x", has_content_based_path = True)
+
+    actions.dynamic_output_new(
+        _build_stdlib_package(
+            target_label = target_label,
+            go_toolchain = go_toolchain,
+            cgo_build_context = cgo_build_context,
+            go_list = go_list,
+            params = params,
+            out_a = out_a.as_output(),
+            out_x = out_x.as_output(),
+            out_a_shared = out_a_shared.as_output(),
+            out_x_shared = out_x_shared.as_output(),
+        )
+    )
+
+    return GoPkg(
+        archive_file = out_a,
+        archive_file_shared = out_a_shared,
+        export_file = out_x,
+        export_file_shared = out_x_shared,
+        coverage_instrumented = params.coverage_enabled and params.coverage_mode != None,
+    )
+
+def _build_stdlib_package_impl(
+    actions: AnalysisActions,
+    target_label: Label,
+    go_toolchain: GoToolchainInfo,
+    cgo_build_context: None | CGoBuildContext,
+    go_list: BuildPackageGoList,
+    params: BuildPackageParams,
+    out_a: OutputArtifact,
+    out_x: OutputArtifact,
+    out_a_shared: OutputArtifact,
+    out_x_shared: OutputArtifact,
+) -> list[Provider]:
+    result = build_package(
+        actions = actions,
+        target_label = target_label,
+        go_toolchain = go_toolchain,
+        cgo_build_context = cgo_build_context,
+        go_list = go_list,
+        params = params,
+    )
+    actions.copy_file(out_a, result.a_file)
+    actions.copy_file(out_x, result.x_file)
+    actions.copy_file(out_a_shared, result.a_file_shared)
+    actions.copy_file(out_x_shared, result.x_file_shared)
+    return []
+
+_build_stdlib_package = dynamic_actions(
+    impl = _build_stdlib_package_impl,
+    # @unsorted-dict-items
+    attrs = {
+        # Inputs
+        "target_label": dynattrs.value(Label),
+        "go_toolchain": dynattrs.value(GoToolchainInfo),
+        "cgo_build_context": dynattrs.value(None | CGoBuildContext),
+        "go_list": dynattrs.value(BuildPackageGoList),
+        "params": dynattrs.value(BuildPackageParams),
+        # Outputs
+        "out_a": dynattrs.output(),
+        "out_x": dynattrs.output(),
+        "out_a_shared": dynattrs.output(),
+        "out_x_shared": dynattrs.output(),
+    },
+)
+
+def get_cgo_build_context(ctx: AnalysisContext) -> CGoBuildContext | None:
+    cxx_toolchain_info = get_opt_cxx_toolchain_info(ctx)
+    if cxx_toolchain_info == None:
+        return None
+
+    return CGoBuildContext(
+        cxx_toolchain_info = cxx_toolchain_info,
+        target_sdk_version_flags = get_target_sdk_version_flags(ctx),
+        exec_os_type = ctx.attrs._exec_os_type[OsLookup],
+        header_namespace = "",
+        headers_layout = CxxHeadersLayout(namespace = "", naming = CxxHeadersNaming("regular")),
+        cxx_compiler_flags = [],
+        cxx_preprocessor_flags = [],
+        inherited_preprocessor_infos = [],
+        _cxx_toolchain = ctx.attrs._cxx_toolchain,
+    )
diff --git a/buck2/prelude/go/go_test.bzl b/buck2/prelude/go/go_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/go_test.bzl
@@ -0,0 +1,196 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkStyle",
+)
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+load(
+    "@prelude//tests:re_utils.bzl",
+    "get_re_executors_from_props",
+)
+load(
+    "@prelude//utils:utils.bzl",
+    "from_named_set",
+    "map_val",
+    "value_or",
+)
+load(":cgo_builder.bzl", "get_cgo_build_context")
+load(":compile.bzl", "GoTestInfo")
+load(":coverage.bzl", "GoCoverageMode")
+load(":link.bzl", "GoBuildMode", "get_inherited_link_pkgs", "link")
+load(":package_builder.bzl", "GoBuildConfig", "GoSourceInputs", "declare_package_build")
+load(":packages.bzl", "go_attr_pkg_name")
+load(":toolchain.bzl", "GoToolchainInfo", "evaluate_cgo_enabled")
+
+def _gen_test_main(
+    ctx: AnalysisContext,
+    pkg_import_path: str,
+    coverage_mode: [GoCoverageMode, None],
+    cover_packages: list[str],  # packages those are included for coverage
+    test_go_files_argsfile: Artifact,
+) -> Artifact:
+    """
+    Generate a `main.go` which calls tests from the given sources.
+    """
+    output = ctx.actions.declare_output("main.go", has_content_based_path = True)
+    cmd = []
+    cmd.append(ctx.attrs._testmaingen[RunInfo])
+
+    # if ctx.attrs.coverage_mode:
+    cmd.append(cmd_args(output.as_output(), format = "--output={}"))
+    cmd.append(cmd_args(pkg_import_path, format = "--import-path={}"))
+    if coverage_mode != None:
+        cmd.extend(["--cover-mode", coverage_mode.value])
+    if cover_packages:
+        cover_pkgs_argsfile = ctx.actions.declare_output("cover_pkgs_argsfile", has_content_based_path = True)
+        ctx.actions.write(cover_pkgs_argsfile, [["--cover-pkgs", pkg] for pkg in cover_packages])
+        cmd.append(cmd_args(cover_pkgs_argsfile, format = "@{}"))
+    cmd.append(cmd_args(test_go_files_argsfile, format = "@{}"))
+    ctx.actions.run(cmd_args(cmd), category = "go_test_main_gen", allow_cache_upload = ctx.attrs._go_toolchain[GoToolchainInfo].allow_cache_upload)
+    return output
+
+def is_subpackage_of(other_pkg_import_path: str, pkg_import_path: str) -> bool:
+    return pkg_import_path == other_pkg_import_path or other_pkg_import_path.startswith(pkg_import_path + "/")
+
+def go_test_impl(ctx: AnalysisContext) -> list[Provider]:
+    pkg_import_path = go_attr_pkg_name(ctx)
+    cgo_enabled = evaluate_cgo_enabled(ctx.attrs._cgo_enabled)
+
+    deps = ctx.attrs.deps
+    srcs = ctx.attrs.srcs
+    coverage_enabled = ctx.attrs.coverage_enabled
+
+    # Copy the srcs, deps and pkg_import_path from the target library when set. The
+    # library code gets compiled together with the tests.
+    if ctx.attrs.target_under_test:
+        lib = ctx.attrs.target_under_test[GoTestInfo]
+        srcs += lib.srcs
+        deps += lib.deps
+
+        # TODO: should we assert that pkg_import_path != None here?
+        pkg_import_path = lib.pkg_import_path
+        coverage_enabled = coverage_enabled or lib.coverage_enabled
+
+    # If coverage is enabled for this test, we need to preprocess the sources
+    # with the Go cover tool.
+    coverage_mode = GoCoverageMode(ctx.attrs._coverage_mode) if ctx.attrs._coverage_mode else None
+    cgo_build_context = get_cgo_build_context(ctx)
+    pkgs = {}
+
+    # Compile all tests into a package.
+    tests, tests_pkg_info, test_go_files_argsfile = declare_package_build(
+        ctx = ctx,
+        pkg_import_path = pkg_import_path,
+        main = False,
+        sources = GoSourceInputs(
+            srcs = srcs,
+            embed_srcs = from_named_set(ctx.attrs.embed_srcs),
+            package_root = ctx.attrs.package_root,
+        ),
+        cgo_build_context = cgo_build_context,
+        config = GoBuildConfig(
+            compiler_flags = ctx.attrs.compiler_flags,
+            build_tags = ctx.attrs._build_tags,
+            coverage_enabled = coverage_enabled,
+            coverage_mode = coverage_mode,
+            with_tests = True,
+            cgo_enabled = cgo_enabled,
+        ),
+        pkgs = pkgs,
+        deps = deps,
+    )
+
+    cover_packages = []
+
+    # Cover the test package itself
+    if tests.coverage_instrumented:
+        cover_packages.append(pkg_import_path)
+
+    # Get all packages that are linked to the test (i.e. the entire dependency tree)
+    for import_path, pkg in get_inherited_link_pkgs(deps).items():
+        if pkg.coverage_instrumented:
+            # Cover dependencies with coverage instrumented
+            cover_packages.append(import_path)
+
+    pkgs[pkg_import_path] = tests
+
+    # Generate a 'main.go' file (test runner) which runs the actual tests from the package above.
+    # Build the it as a separate package (<foo>.test) - which imports and invokes the test package.
+    gen_main = _gen_test_main(ctx, pkg_import_path, coverage_mode, cover_packages, test_go_files_argsfile)
+    main, _, _ = declare_package_build(
+        ctx = ctx,
+        pkg_import_path = pkg_import_path + ".test",
+        main = True,
+        sources = GoSourceInputs(
+            srcs = [gen_main],
+            package_root = "",
+        ),
+        cgo_build_context = None,
+        config = GoBuildConfig(
+            cgo_enabled = cgo_enabled,
+        ),
+        pkgs = pkgs,
+        cgo_gen_dir_name = "cgo_gen_test_main",
+    )
+
+    # Link the above into a Go binary.
+    (bin, runtime_files, external_debug_info) = link(
+        ctx = ctx,
+        main = main,
+        cgo_enabled = cgo_enabled,
+        pkgs = pkgs,
+        deps = deps,
+        link_style = value_or(map_val(LinkStyle, ctx.attrs.link_style), LinkStyle("static")),
+        build_mode = GoBuildMode(value_or(ctx.attrs.build_mode, "exe")),
+        linker_flags = ctx.attrs.linker_flags,
+        external_linker_flags = ctx.attrs.external_linker_flags,
+    )
+
+    # As per v1, copy in resources next to binary.
+    copied_resources = []
+    for resource in ctx.attrs.resources:
+        copied_resources.append(ctx.actions.copy_file(resource.short_path, resource, has_content_based_path = False))
+
+    run_cmd = cmd_args(bin, hidden = [runtime_files, external_debug_info] + copied_resources)
+
+    # Setup RE executors based on the `remote_execution` param.
+    re_executors = get_re_executors_from_props(ctx)
+
+    # Emit TPX_LIST_TESTS_COMMAND so TPX can enumerate tests via AST parsing
+    # of the *_test.go sources instead of running the compiled binary with
+    # -test.list. Eliminates cgo and TestMain startup costs from listing.
+    # The lister mirrors `go test -list <regex>`
+    env = dict(ctx.attrs.env)
+    env["TPX_LIST_TESTS_COMMAND"] = cmd_args(
+        [ctx.attrs._list_tests[RunInfo]],
+        "-match=^Test.*",
+        cmd_args(test_go_files_argsfile, format = "@{}"),
+    )
+
+    return inject_test_run_info(
+        ctx,
+        ExternalRunnerTestInfo(
+            type = "go",
+            command = [run_cmd],
+            env = env,
+            labels = ctx.attrs.labels,
+            contacts = ctx.attrs.contacts,
+            default_executor = re_executors.default_executor,
+            executor_overrides = re_executors.executor_overrides,
+            run_from_project_root = True,
+            use_project_relative_paths = re_executors.use_project_relative_paths,
+        ),
+    ) + [
+        DefaultInfo(
+            default_output = bin,
+            other_outputs = [gen_main] + runtime_files + external_debug_info + copied_resources,
+        ),
+        tests_pkg_info,
+    ]
diff --git a/buck2/prelude/go/link.bzl b/buck2/prelude/go/link.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/link.bzl
@@ -0,0 +1,336 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_library_utility.bzl", "cxx_inherited_link_info")
+load(
+    "@prelude//cxx:cxx_link_utility.bzl",
+    "ExecutableSharedLibArguments",
+    "executable_shared_lib_arguments",
+    "make_link_args",
+)
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("@prelude//cxx:linker.bzl", "get_default_shared_library_name", "get_shared_library_name_linker_flags")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkStyle",
+    "get_link_args_for_strategy",
+    "to_link_strategy",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+)
+load("@prelude//linking:stamp_build_info.bzl", "stamp_build_info")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load(
+    "@prelude//utils:utils.bzl",
+    "filter_and_map_idx",
+)
+load(
+    ":packages.bzl",
+    "GoPkg",  # @Unused used as type
+    "GoStdlib",
+    "GoStdlibDynamicValue",
+    "make_link_importcfg",
+    "merge_pkgs",
+)
+load(":toolchain.bzl", "GoToolchainInfo", "get_toolchain_env_vars")
+
+# Provider wrapping packages used for linking.
+GoPkgLinkInfo = provider(
+    fields = {
+        "pkgs": provider_field(typing.Any, default = None),  # {str: "artifact"}
+    }
+)
+
+GoBuildMode = enum(
+    "exe",  # non-pic executable
+    "pie",  # pic executable
+    "c_shared",  # pic C-shared library
+    "c_archive",  # pic C-static library
+)
+
+def _build_mode_param(mode: GoBuildMode) -> str:
+    if mode == GoBuildMode("exe"):
+        return "exe"
+    if mode == GoBuildMode("pie"):
+        return "pie"
+    if mode == GoBuildMode("c_shared"):
+        return "c-shared"
+    if mode == GoBuildMode("c_archive"):
+        return "c-archive"
+    fail("unexpected: {}", mode)
+
+def get_inherited_link_pkgs(deps: list[Dependency]) -> dict[str, GoPkg]:
+    return merge_pkgs([d[GoPkgLinkInfo].pkgs for d in deps if GoPkgLinkInfo in d])
+
+# TODO(cjhopman): Is link_style a LibOutputStyle or a LinkStrategy here? Based
+# on returning an empty thing for link_style != shared, it seems likely its
+# intended to be LibOutputStyle, but it's called in places that are passing what
+# appears to be a LinkStrategy.
+def _process_shared_dependencies(ctx: AnalysisContext, artifact: Artifact, deps: list[Dependency], link_style: LinkStyle) -> ExecutableSharedLibArguments:
+    """
+    Provides files and linker args needed to for binaries with shared library linkage.
+    - the runtime files needed to run binary linked with shared libraries
+    - linker arguments for shared libraries
+    """
+    if link_style != LinkStyle("shared"):
+        return ExecutableSharedLibArguments()
+
+    shlib_info = merge_shared_libraries(
+        ctx.actions,
+        deps = filter_and_map_idx(SharedLibraryInfo, deps),
+    )
+    shared_libs = traverse_shared_library_info(shlib_info, transformation_provider = None)
+
+    return executable_shared_lib_arguments(
+        ctx,
+        ctx.attrs._cxx_toolchain[CxxToolchainInfo],
+        artifact,
+        shared_libs,
+    )
+
+def link(
+    ctx: AnalysisContext,
+    main: GoPkg,
+    cgo_enabled: bool,
+    pkgs: dict[str, GoPkg] = {},
+    deps: list[Dependency] = [],
+    build_mode: GoBuildMode = GoBuildMode("exe"),
+    link_mode: [str, None] = None,
+    link_style: LinkStyle = LinkStyle("static"),
+    linker_flags: list[typing.Any] = [],
+    external_linker_flags: list[typing.Any] = [],
+):
+    go_toolchain = ctx.attrs._go_toolchain[GoToolchainInfo]
+
+    if not cgo_enabled and (go_toolchain.asan or go_toolchain.race):
+        fail("`race=True` and `asan=True` are only supported when `cgo_enabled=True`")
+
+    if go_toolchain.env_go_os == "windows":
+        executable_extension = ".exe"
+        shared_extension = ".dll"
+        archive_extension = ".lib"
+    else:
+        executable_extension = ""
+        shared_extension = ".so"
+        archive_extension = ".a"
+
+    if build_mode == GoBuildMode("c_shared"):
+        file_extension = shared_extension
+        use_shared_code = True  # PIC
+        link_style = LinkStyle("shared")
+    elif build_mode == GoBuildMode("c_archive"):
+        file_extension = archive_extension
+        use_shared_code = True  # PIC
+        link_style = LinkStyle("static_pic")
+    elif build_mode == GoBuildMode("pie"):
+        file_extension = executable_extension
+        use_shared_code = True  # PIC
+        link_style = LinkStyle("static_pic")
+    else:  # GoBuildMode("exe")
+        file_extension = executable_extension
+        use_shared_code = False  # non-PIC
+    final_output_name = ctx.label.name + file_extension
+    output = ctx.actions.declare_output(ctx.label.name + "-tmp" + file_extension, has_content_based_path = True)
+
+    cmd = cmd_args()
+
+    cmd.add(go_toolchain.go_wrapper)
+    cmd.add(["--go", go_toolchain.linker])
+
+    # Give internally-linked Go binaries a content-hash NT_GNU_BUILD_ID note.
+    # Buck has no artifact content at analysis time, so reserve a zeroed note here
+    # (-B 0x00..00) that the wrapper fills with sha256 post-link -- rewriting only a
+    # still-all-zero descriptor, so an external link keeps its C++-set build-id.
+    elf_go_os = ["linux", "android", "freebsd", "netbsd", "openbsd", "dragonfly", "illumos", "solaris"]
+    emit_build_id = build_mode in [GoBuildMode("exe"), GoBuildMode("pie")] and link_mode in [None, "internal"] and go_toolchain.env_go_os in elf_go_os
+    if emit_build_id:
+        cmd.add("--gnu-build-id")  # wrapper flag, must precede "--"
+
+    cmd.add("--")
+    cmd.add(go_toolchain.linker_flags)
+
+    cmd.add("-buildmode=" + _build_mode_param(build_mode))
+    cmd.add("-buildid=")  # Setting to a static buildid helps make the binary reproducible.
+    if emit_build_id:
+        cmd.add("-B", "0x" + "00" * 20)  # reserve a 20-byte NT_GNU_BUILD_ID slot in PT_NOTE
+
+    if go_toolchain.race:
+        cmd.add("-race")
+
+    if go_toolchain.asan:
+        cmd.add("-asan")
+
+    # Add inherited Go pkgs to library search path.
+    all_pkgs = merge_pkgs([
+        pkgs,
+        get_inherited_link_pkgs(deps),
+    ])
+
+    identifier_prefix = ctx.label.name + "_" + _build_mode_param(build_mode)
+
+    go_stdlib = ctx.attrs._go_stdlib[GoStdlib]
+
+    executable_args = _process_shared_dependencies(ctx, output, deps, link_style)
+
+    if link_mode == None:
+        if build_mode == GoBuildMode("c_shared"):
+            link_mode = "external"
+        if build_mode == GoBuildMode("c_archive"):
+            link_mode = "external"
+
+    if link_mode != None:
+        cmd.add("-linkmode", link_mode)
+
+    cxx_toolchain_available = CxxToolchainInfo in ctx.attrs._cxx_toolchain
+    if cxx_toolchain_available:
+        cxx_toolchain = ctx.attrs._cxx_toolchain[CxxToolchainInfo]
+        is_win = ctx.attrs._exec_os_type[OsLookup].os == Os("windows")
+
+        # Gather external link args from deps.
+        ext_links = get_link_args_for_strategy(
+            ctx.actions,
+            ctx.label,
+            cxx_toolchain.linker_info,
+            cxx_inherited_link_info(deps),
+            to_link_strategy(link_style),
+            prefer_stripped = False,
+            transformation_spec_context = None,
+        )
+        ext_link_args_output = make_link_args(
+            ctx,
+            ctx.actions,
+            cxx_toolchain,
+            [ext_links],
+        )
+        ext_link_args = cmd_args(hidden = ext_link_args_output.hidden, quote = "shell")
+
+        # Toolchain linker_flags must precede the objects, not go via cmd/link's -extldflags (which
+        # it emits last): otherwise -Wl,-Bsymbolic-functions overrides cmd/link's own -Wl,-Bsymbolic
+        # for c-shared, leaving runtime cgo data symbols preemptible and breaking the link.
+        ext_link_args.add(cxx_toolchain.linker_info.linker_flags)
+        ext_link_args.add(executable_args.extra_link_args)
+        ext_link_args.add(external_linker_flags)
+        ext_link_args.add(ext_link_args_output.link_args)
+
+        if build_mode == GoBuildMode("c_shared") and go_toolchain.env_go_os != "windows":
+            soname = get_default_shared_library_name(cxx_toolchain.linker_info, ctx.label)
+            soname_flags = get_shared_library_name_linker_flags(cxx_toolchain.linker_info.type, soname)
+            ext_link_args.add(soname_flags)
+
+        # Delegate to C++ linker...
+        # TODO: It feels a bit inefficient to generate a wrapper file for every
+        # link.  Is there some way to etract the first arg of `RunInfo`?  Or maybe
+        # we can generate the platform-specific stuff once and re-use?
+        ext_link_argfile, _ = ctx.actions.write(
+            output.short_path + ".go_ext_link_argsfile",
+            ext_link_args,
+            allow_args = True,
+            has_content_based_path = True,
+        )
+        cxx_link_cmd = cmd_args(
+            [
+                cxx_toolchain.linker_info.linker,
+                cmd_args(ext_link_argfile, format = "@{}"),
+                "%*" if is_win else '"$@"',
+            ],
+            delimiter = " ",
+        )
+        linker_wrapper, _ = ctx.actions.write(
+            "__{}_cxx_link_wrapper__.{}".format(identifier_prefix, "bat" if is_win else "sh"),
+            ([] if is_win else ["#!/bin/sh"]) + [cxx_link_cmd],
+            allow_args = True,
+            is_executable = True,
+            has_content_based_path = True,
+        )
+        cmd.add("-extld", linker_wrapper, cmd_args(hidden = [cxx_link_cmd, ext_link_args, ext_link_args_output.hidden]))
+        # Kept here (not in the argfile) because these carry libraries (-lc, -ldl, ...) that must
+        # follow the objects, and cmd/link emits -extldflags last.
+        cmd.add(
+            "-extldflags",
+            cmd_args(
+                go_toolchain.external_linker_flags,
+                delimiter = " ",
+                quote = "shell",
+            ),
+        )
+
+    cmd.add(linker_flags)
+
+    env = get_toolchain_env_vars(go_toolchain)
+
+    ctx.actions.dynamic_output_new(
+        _link(
+            go_stdlib_value = go_stdlib.dynamic_value,
+            env_vars = env,
+            link_args = cmd,
+            main_pkg = main,
+            deps_pkgs = all_pkgs,
+            shared = use_shared_code,
+            identifier = identifier_prefix,
+            out = output.as_output(),
+            allow_cache_upload = go_toolchain.allow_cache_upload,
+        )
+    )
+
+    # Stamp only executable targets. An internal link never runs the ld
+    # wrapper, so there is no fb_build_info placeholder and the stamper adds
+    # the section; an external link runs the wrapper, which reserves the
+    # placeholder when the rule stamps.
+    if build_mode in [GoBuildMode("exe"), GoBuildMode("pie")]:
+        output = stamp_build_info(ctx, output, has_content_based_path = True)
+
+    final_output = ctx.actions.copy_file(final_output_name, output, has_content_based_path = False)
+
+    return (final_output, executable_args.runtime_files, executable_args.external_debug_info)
+
+def _link_impl(
+    actions: AnalysisActions,
+    go_stdlib_value: ResolvedDynamicValue,
+    env_vars: dict[str, str | cmd_args | Artifact],
+    link_args: cmd_args,
+    main_pkg: GoPkg,
+    deps_pkgs: dict[str, GoPkg],
+    shared: bool,
+    identifier: str,
+    out: OutputArtifact,
+    allow_cache_upload: bool | None,
+) -> list[Provider]:
+    go_stdlib_value = go_stdlib_value.providers[GoStdlibDynamicValue]
+
+    deps = merge_pkgs([go_stdlib_value.pkgs, deps_pkgs])
+    importcfg = make_link_importcfg(actions, deps, shared)
+    main_pkg_o = main_pkg.archive_file_shared if shared else main_pkg.archive_file
+
+    cmd = [
+        link_args,
+        ["-importcfg", importcfg],
+        ["-o", out],
+        main_pkg_o,
+    ]
+    actions.run(cmd, env = env_vars, category = "go_link", identifier = identifier, allow_cache_upload = allow_cache_upload)
+    return []
+
+_link = dynamic_actions(
+    impl = _link_impl,
+    # @unsorted-dict-items
+    attrs = {
+        "go_stdlib_value": dynattrs.dynamic_value(),  # GoStdlibDynamicValue
+        "env_vars": dynattrs.value(dict[str, str | cmd_args | Artifact]),
+        "link_args": dynattrs.value(cmd_args),
+        "main_pkg": dynattrs.value(GoPkg),
+        "deps_pkgs": dynattrs.value(dict[str, GoPkg]),
+        "shared": dynattrs.value(bool),
+        "identifier": dynattrs.value(str),
+        "out": dynattrs.output(),
+        "allow_cache_upload": dynattrs.value(bool | None),
+    },
+)
diff --git a/buck2/prelude/go/package_builder.bzl b/buck2/prelude/go/package_builder.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/package_builder.bzl
@@ -0,0 +1,658 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//utils:utils.bzl", "dedupe_by_value")
+load(
+    ":cgo_builder.bzl",
+    "CGoBuildContext",  # @Unused used as type
+    "build_cgo",
+)
+load(":compile.bzl", "get_inherited_compile_pkgs", "infer_package_root")
+load(
+    ":coverage.bzl",
+    "GoCoverageMode",  # @Unused used as type
+    "cover_srcs",
+)
+load(":go_error_handler.bzl", "go_build_error_handler")
+load(":go_list.bzl", "GoListOut", "go_list", "parse_go_list_out")
+load(":packages.bzl", "GoPackageInfo", "GoPkg", "GoStdlib", "GoStdlibDynamicValue", "implicit_imports", "make_compile_importcfg", "merge_pkgs")
+load(":toolchain.bzl", "GoToolchainInfo", "get_toolchain_env_vars")
+
+GoBuildConfig = record(
+    compiler_flags = field(list[str], []),
+    assembler_flags = field(list[str], []),
+    build_tags = field(list[str], []),
+    coverage_enabled = field(bool, False),
+    coverage_mode = field(GoCoverageMode | None, None),
+    cgo_enabled = field(bool, False),
+    with_tests = field(bool, False),
+)
+
+GoSourceInputs = record(
+    srcs = field(list[Artifact]),
+    embed_srcs = field(dict[str, Artifact], {}),
+    package_root = field(str | None, None),
+)
+
+def declare_package_build(
+    ctx: AnalysisContext,
+    pkg_import_path: str,
+    main: bool,
+    sources: GoSourceInputs,
+    cgo_build_context: CGoBuildContext | None,
+    config: GoBuildConfig,
+    pkgs: dict[str, GoPkg] = {},
+    deps: list[Dependency] = [],
+    cgo_gen_dir_name: str = "cgo_gen",
+) -> (GoPkg, GoPackageInfo, Artifact):
+    actions = ctx.actions
+    target_label = ctx.label
+    go_toolchain = ctx.attrs._go_toolchain[GoToolchainInfo]
+    go_stdlib = ctx.attrs._go_stdlib[GoStdlib]
+
+    asan = go_toolchain.asan
+    race = go_toolchain.race
+    if race and asan:
+        fail("`race=True` and `asan=True` are mutually exclusive")
+
+    if race and config.coverage_mode not in [None, GoCoverageMode("atomic")]:
+        fail("`coverage_mode` must be `atomic` when `race=True`")
+
+    out_x = actions.declare_output(paths.basename(pkg_import_path) + "_non-shared.x", has_content_based_path = True)
+    out_a = actions.declare_output(paths.basename(pkg_import_path) + "_non-shared.a", has_content_based_path = True)
+
+    out_shared_x = actions.declare_output(paths.basename(pkg_import_path) + "_shared.x", has_content_based_path = True)
+    out_shared_a = actions.declare_output(paths.basename(pkg_import_path) + "_shared.a", has_content_based_path = True)
+
+    cgo_gen_dir = actions.declare_output(cgo_gen_dir_name, dir = True, has_content_based_path = True)
+
+    srcs = dedupe_by_value(sources.srcs)
+
+    package_root = sources.package_root if sources.package_root != None else infer_package_root(srcs)
+
+    go_list_out = go_list(actions, go_toolchain, pkg_import_path, srcs, package_root, config.build_tags, config.cgo_enabled, with_tests = config.with_tests)
+
+    test_go_files_argsfile = actions.declare_output(paths.basename(pkg_import_path) + "_test_go_files.go_package_argsfile", has_content_based_path = True)
+
+    all_pkgs = merge_pkgs([
+        pkgs,
+        get_inherited_compile_pkgs(deps),
+    ])
+
+    actions.dynamic_output_new(
+        _build_package_action(
+            target_label = target_label,
+            pkg_import_path = pkg_import_path,
+            main = main,
+            sources = GoSourceInputs(
+                srcs = srcs,
+                embed_srcs = sources.embed_srcs,
+                package_root = package_root,
+            ),
+            cgo_build_context = cgo_build_context,
+            config = config,
+            deps_pkgs = all_pkgs,
+            go_toolchain = go_toolchain,
+            go_stdlib_value = go_stdlib.dynamic_value,
+            go_list_out = go_list_out,
+            cgo_gen_dir = cgo_gen_dir.as_output(),
+            out_a = out_a.as_output(),
+            out_shared_a = out_shared_a.as_output(),
+            out_shared_x = out_shared_x.as_output(),
+            out_x = out_x.as_output(),
+            test_go_files_argsfile = test_go_files_argsfile.as_output(),
+        )
+    )
+    return (
+        GoPkg(
+            archive_file = out_a,
+            archive_file_shared = out_shared_a,
+            export_file = out_x,
+            export_file_shared = out_shared_x,
+            coverage_instrumented = config.coverage_enabled and config.coverage_mode != None,
+        ),
+        GoPackageInfo(
+            build_out = out_x,
+            cgo_gen_dir = cgo_gen_dir,
+            pkg_import_path = pkg_import_path,
+            package_root = package_root,
+            go_list_out = go_list_out,
+            srcs = srcs,
+        ),
+        test_go_files_argsfile.with_associated_artifacts(srcs),
+    )
+
+def _build_package_action_impl(
+    actions: AnalysisActions,
+    target_label: Label,
+    pkg_import_path: str,
+    main: bool,
+    sources: GoSourceInputs,
+    cgo_build_context: None | CGoBuildContext,
+    config: GoBuildConfig,
+    deps_pkgs: dict[str, GoPkg],
+    go_toolchain: GoToolchainInfo,
+    go_list_out: ArtifactValue,
+    go_stdlib_value: ResolvedDynamicValue,
+    cgo_gen_dir: OutputArtifact,
+    out_a: OutputArtifact,
+    out_shared_a: OutputArtifact,
+    out_shared_x: OutputArtifact,
+    out_x: OutputArtifact,
+    test_go_files_argsfile: OutputArtifact,
+):
+    go_list = parse_go_list_out(sources.srcs, sources.package_root, go_list_out)
+
+    if go_list.error != None:
+        fail("Invalid go package: {}", go_list.error.err)
+
+    if len(go_list.x_test_go_files) > 0:
+        fail("External tests are not supported, remove suffix '_test' from package declaration '{}': {}", go_list.name, target_label)
+
+    go_stdlib_value = go_stdlib_value.providers[GoStdlibDynamicValue]
+
+    result = build_package(
+        actions = actions,
+        target_label = target_label,
+        go_toolchain = go_toolchain,
+        cgo_build_context = cgo_build_context,
+        go_list = go_list_for_build(go_list, config.with_tests),
+        params = BuildPackageParams(
+            main = main,
+            standard = False,
+            pkg_import_path = pkg_import_path,
+            package_root = sources.package_root,
+            embed_srcs = sources.embed_srcs,
+            compiler_flags = config.compiler_flags,
+            assembler_flags = config.assembler_flags,
+            coverage_enabled = config.coverage_enabled,
+            coverage_mode = config.coverage_mode,
+            deps = merge_pkgs([go_stdlib_value.pkgs, deps_pkgs]),
+            import_map = None,
+        ),
+    )
+
+    actions.write(test_go_files_argsfile, cmd_args((go_list.test_go_files if config.with_tests else []), ""))
+    actions.copy_dir(cgo_gen_dir, result.cgo_gen_dir)
+
+    actions.copy_file(out_x, result.x_file)
+    actions.copy_file(out_a, result.a_file)
+
+    actions.copy_file(out_shared_x, result.x_file_shared)
+    actions.copy_file(out_shared_a, result.a_file_shared)
+
+    return []
+
+_build_package_action = dynamic_actions(
+    impl = _build_package_action_impl,
+    # @unsorted-dict-items
+    attrs = {
+        # Input Parameters
+        "target_label": dynattrs.value(Label),
+        "pkg_import_path": dynattrs.value(str),
+        "main": dynattrs.value(bool),
+        "sources": dynattrs.value(GoSourceInputs),
+        "cgo_build_context": dynattrs.value(CGoBuildContext | None),
+        "config": dynattrs.value(GoBuildConfig),
+        "deps_pkgs": dynattrs.value(dict[str, GoPkg]),
+        "go_toolchain": dynattrs.value(GoToolchainInfo),
+        # Readable Artifacts
+        "go_list_out": dynattrs.artifact_value(),
+        # Dynamic Values
+        "go_stdlib_value": dynattrs.dynamic_value(),  # GoStdlibDynamicValue
+        # Outputs
+        "cgo_gen_dir": dynattrs.output(),
+        "out_a": dynattrs.output(),
+        "out_shared_a": dynattrs.output(),
+        "out_shared_x": dynattrs.output(),
+        "out_x": dynattrs.output(),
+        "test_go_files_argsfile": dynattrs.output(),
+    },
+)
+
+BuildPackageGoList = record(
+    pkg_name = field(str),
+    go_files = field(list[Artifact]),
+    cgo_files = field(list[Artifact]),
+    s_files = field(list[Artifact]),
+    h_files = field(list[Artifact]),
+    c_cxx_files = field(list[Artifact]),
+    syso_files = field(list[Artifact]),
+    imports = field(set[str]),
+    embed_patterns = field(list[str]),
+    cgo_cflags = field(list[str]),
+    cgo_cppflags = field(list[str]),
+)
+
+def go_list_for_build(go_list_out: GoListOut, with_tests: bool) -> BuildPackageGoList:
+    imports = set(go_list_out.imports + (go_list_out.test_imports if with_tests else []))
+    embed_patterns = go_list_out.embed_patterns + (go_list_out.test_embed_patterns if with_tests else [])
+    go_files = go_list_out.go_files + (go_list_out.test_go_files if with_tests else [])
+    c_cxx_files = go_list_out.c_files + go_list_out.cxx_files
+    return BuildPackageGoList(
+        pkg_name = go_list_out.name,
+        go_files = go_files,
+        cgo_files = go_list_out.cgo_files,
+        s_files = go_list_out.s_files,
+        h_files = go_list_out.h_files,
+        c_cxx_files = c_cxx_files,
+        syso_files = go_list_out.syso_files,
+        imports = imports,
+        embed_patterns = embed_patterns,
+        cgo_cflags = go_list_out.cgo_cflags,
+        cgo_cppflags = go_list_out.cgo_cppflags,
+    )
+
+BuildPackageParams = record(
+    main = field(bool),
+    standard = field(bool),
+    pkg_import_path = field(str),
+    package_root = field(str),
+    embed_srcs = field(dict[str, Artifact]),
+    compiler_flags = field(list[str]),
+    assembler_flags = field(list[str]),
+    coverage_enabled = field(bool),
+    coverage_mode = field(GoCoverageMode | None),
+    deps = field(dict[str, GoPkg]),
+    # Importmap is used when the import path we use in the code different
+    # from the actual import path our dependency has.
+    # For now, it's only used for stdlib's deps.
+    # - key: import path in current package's source code
+    # - value: actual import path of a dependency
+    import_map = field(dict[str, str] | None),
+)
+BuildPackageResult = record(
+    a_file = field(Artifact),
+    x_file = field(Artifact),
+    a_file_shared = field(Artifact),
+    x_file_shared = field(Artifact),
+    cgo_gen_dir = field(Artifact),
+)
+
+# Packages with forward declarations resolved at runtime.
+# Keep in sync with https://github.com/golang/go/blob/go1.26.0/src/cmd/go/internal/work/gc.go#L90
+_incomplete_pkgs_allow_list = set([
+    "bytes",
+    "internal/poll",
+    "net",
+    "os",
+    "runtime/metrics",
+    "runtime/pprof",
+    "runtime/trace",
+    "sync",
+    "syscall",
+    "time",
+])
+
+def build_package(
+    actions: AnalysisActions,
+    target_label: Label,
+    go_toolchain: GoToolchainInfo,
+    cgo_build_context: CGoBuildContext | None,
+    go_list: BuildPackageGoList,
+    params: BuildPackageParams,
+) -> BuildPackageResult:
+    covered_go_files, covered_cgo_files, coveragecfg = cover_srcs(
+        actions = actions,
+        go_toolchain = go_toolchain,
+        pkg_name = go_list.pkg_name,
+        pkg_import_path = params.pkg_import_path,
+        go_files = go_list.go_files,
+        cgo_files = go_list.cgo_files,
+        coverage_enabled = params.coverage_enabled,
+        coverage_mode = params.coverage_mode,
+    )
+
+    # A go package can can contain CGo or Go ASM files, but not both.
+    # If CGo and ASM files are present, we process ASM files together with C files with CxxToolchain.
+    # The `go build` command does additional check here and throws an error if both CGo and Go-ASM files are present.
+    c_cxx_files = [] + go_list.c_cxx_files
+    s_files = go_list.s_files
+    if len(go_list.cgo_files) > 0:
+        # the only exception when we have both types of ASM files is "runtime/cgo"
+        if params.standard and params.pkg_import_path == "runtime/cgo":
+            go_s_files = []
+            for s_file in s_files:
+                if paths.basename(s_file.short_path).startswith("gcc_"):
+                    c_cxx_files.append(s_file)
+                else:
+                    go_s_files.append(s_file)
+
+            s_files = go_s_files
+        else:
+            c_cxx_files += s_files
+            s_files = []
+
+    # Generate CGO and C sources.
+    transformed_cgo_files, cgo_o_files, cgo_gen_dir = build_cgo(
+        actions = actions,
+        target_label = target_label,
+        go_toolchain_info = go_toolchain,
+        cgo_build_context = cgo_build_context,
+        pkg_import_path = params.pkg_import_path,
+        package_root = params.package_root,
+        standard = params.standard,
+        cgo_files = covered_cgo_files,
+        h_files = go_list.h_files,
+        c_files = c_cxx_files,
+        c_flags = go_list.cgo_cflags,
+        cpp_flags = go_list.cgo_cppflags,
+        anon_targets_allowed = False,
+    )
+
+    symabis = _symabis(actions, go_toolchain, params.pkg_import_path, params.main, s_files, go_list.h_files, params.assembler_flags)
+
+    embedcfg = _embedcfg(actions, go_toolchain, params.pkg_import_path, params.package_root, params.embed_srcs, go_list.embed_patterns)
+
+    # Use -complete flag when compiling Go code only
+    complete_flag = len(go_list.cgo_files) + len(s_files) + len(c_cxx_files) + len(go_list.syso_files) == 0
+    if params.standard and params.pkg_import_path in _incomplete_pkgs_allow_list:
+        complete_flag = False
+
+    go_files_to_compile = covered_go_files + transformed_cgo_files
+
+    # Use argsfile to avoid command length limit on Windows. The source list
+    # is identical for the shared and non-shared variants, so they share it.
+    srcs_argsfile = actions.write("srcs.go_package_argsfile", go_files_to_compile, has_content_based_path = True) if go_files_to_compile else None
+
+    def build_variant(shared: bool) -> (Artifact, Artifact):
+        build_variant_id = "shared" if shared else "non-shared"  # use  tomake artifacts and actions unique
+
+        required_imports = go_list.imports | implicit_imports(
+            pkg_name = go_list.pkg_name,
+            pkg_import_path = params.pkg_import_path,
+            standard = params.standard,
+            has_cgo_files = len(go_list.cgo_files) > 0,
+            coverage_enabled = params.coverage_enabled,
+            coverage_mode = params.coverage_mode,
+        )
+
+        importcfg = make_compile_importcfg(
+            actions = actions,
+            pkg_import_path = params.pkg_import_path,
+            deps = params.deps,
+            imports = required_imports,
+            import_map = params.import_map,
+            shared = shared,
+        )
+        go_x_file, go_a_file, asmhdr = _compile(
+            actions = actions,
+            go_toolchain = go_toolchain,
+            pkg_import_path = params.pkg_import_path,
+            main = params.main,
+            go_srcs = go_files_to_compile,
+            srcs_argsfile = srcs_argsfile,
+            importcfg = importcfg,
+            compiler_flags = params.compiler_flags,
+            shared = shared,
+            race = go_toolchain.race,
+            asan = go_toolchain.asan,
+            build_variant_id = build_variant_id,
+            complete = complete_flag,
+            standard = params.standard,
+            coveragecfg = coveragecfg,
+            embedcfg = embedcfg,
+            symabis = symabis,
+            gen_asmhdr = len(s_files) > 0,
+        )
+
+        asm_o_files = _asssembly(
+            actions, go_toolchain, params.pkg_import_path, params.main, s_files, go_list.h_files, asmhdr, params.assembler_flags, shared, build_variant_id
+        )
+
+        return go_x_file, _pack(actions, go_toolchain, params.pkg_import_path, go_a_file, cgo_o_files + asm_o_files + go_list.syso_files, build_variant_id)
+
+    non_shared_x, non_shared_a = build_variant(shared = False)
+
+    shared_x, shared_a = build_variant(shared = True)
+
+    return BuildPackageResult(
+        a_file = non_shared_a,
+        x_file = non_shared_x,
+        a_file_shared = shared_a,
+        x_file_shared = shared_x,
+        cgo_gen_dir = cgo_gen_dir,
+    )
+
+# Keep in sync with https://github.com/golang/go/blob/go1.26.0/src/cmd/go/internal/test/test.go#L941
+_libfuzzer_exclude_list = set([
+    "context",
+    "internal/fuzz",
+    "internal/godebug",
+    "internal/runtime/maps",
+    "internal/sync",
+    "reflect",
+    "runtime",
+    "sync",
+    "sync/atomic",
+    "syscall",
+    "testing",
+    "time",
+])
+
+def _compile(
+    actions: AnalysisActions,
+    go_toolchain: GoToolchainInfo,
+    pkg_import_path: str,
+    main: bool,
+    go_srcs: list[Artifact],
+    srcs_argsfile: Artifact | None,
+    importcfg: Artifact,
+    compiler_flags: list[str],
+    shared: bool,
+    race: bool,
+    asan: bool,
+    build_variant_id: str,
+    complete: bool,
+    standard: bool,
+    coveragecfg: Artifact | None = None,
+    embedcfg: Artifact | None = None,
+    symabis: Artifact | None = None,
+    gen_asmhdr: bool = False,
+) -> (Artifact, Artifact, Artifact | None):
+    env = get_toolchain_env_vars(go_toolchain)
+    out_a = actions.declare_output("go_compile_out_{}.a".format(build_variant_id), has_content_based_path = True)
+    out_x = actions.declare_output("go_compile_out_{}.x".format(build_variant_id), has_content_based_path = True)
+
+    if len(go_srcs) == 0:
+        actions.write(out_a.as_output(), "")
+        actions.write(out_x.as_output(), "")
+        return out_x, out_a, None
+
+    asmhdr = actions.declare_output("__asmhdr__{}/go_asm.h".format(build_variant_id), has_content_based_path = True) if gen_asmhdr else None
+
+    compile_cmd = cmd_args(
+        [
+            go_toolchain.go_wrapper,
+            ["--go", go_toolchain.compiler],
+            "--",
+            go_toolchain.compiler_flags,
+            compiler_flags,
+            "-buildid=",
+            "-nolocalimports",
+            "-pack",
+            ["-trimpath", "%cwd%"],
+            ["-p", "main" if main else pkg_import_path],
+            ["-importcfg", importcfg],
+            ["-o", out_x.as_output()],
+            ["-linkobj", out_a.as_output()],
+            ["-race"] if race else [],
+            ["-asan"] if asan else [],
+            ["-d=libfuzzer"] if go_toolchain.fuzz and (not standard or pkg_import_path not in _libfuzzer_exclude_list) else [],
+            ["-shared"] if shared else [],
+            ["-coveragecfg", coveragecfg] if coveragecfg else [],
+            ["-embedcfg", embedcfg] if embedcfg else [],
+            ["-symabis", symabis] if symabis else [],
+            ["-asmhdr", asmhdr.as_output()] if asmhdr else [],
+            ["-complete"] if complete else [],
+            ["-std"] if standard else [],
+            cmd_args(srcs_argsfile, format = "@{}", hidden = go_srcs),
+        ],
+    )
+
+    actions.run(
+        compile_cmd,
+        env = env,
+        category = "go_compile",
+        identifier = "{} [{}]".format(pkg_import_path, build_variant_id),
+        error_handler = go_build_error_handler,
+        allow_cache_upload = go_toolchain.allow_cache_upload,
+    )
+
+    return (out_x, out_a, asmhdr)
+
+def _symabis(
+    actions: AnalysisActions,
+    go_toolchain: GoToolchainInfo,
+    pkg_import_path: str,
+    main: bool,
+    s_files: list[Artifact],
+    h_files: list[Artifact],
+    assembler_flags: list[str],
+) -> Artifact | None:
+    if len(s_files) == 0:
+        return None
+
+    env = get_toolchain_env_vars(go_toolchain)
+
+    # we have to supply "go_asm.h" with any content to make asm tool happy
+    # its content doesn't matter if -gensymabis provided
+    # https://github.com/golang/go/blob/3f8f929d60a90c4e4e2b07c8d1972166c1a783b1/src/cmd/go/internal/work/gc.go#L441-L443
+    fake_asmhdr = actions.write("__fake_asmhdr__/go_asm.h", "", has_content_based_path = True)
+    symabis = actions.declare_output("symabis", has_content_based_path = True)
+    asm_cmd = [
+        go_toolchain.go_wrapper,
+        ["--go", go_toolchain.assembler],
+        "--",
+        go_toolchain.assembler_flags,
+        assembler_flags,
+        _asm_args(go_toolchain, pkg_import_path, main, False),  # flag -shared doesn't matter for symabis
+        "-gensymabis",
+        ["-o", symabis.as_output()],
+        ["-I", cmd_args(fake_asmhdr, parent = 1)],
+        [cmd_args(h_files, parent = 1, prepend = "-I")] if h_files else [],
+        [cmd_args(s_files, parent = 1, prepend = "-I")],  # some .s files can include other .s files
+        ["-trimpath", "%cwd%"],
+        s_files,
+    ]
+
+    actions.run(asm_cmd, env = env, category = "go_symabis", identifier = pkg_import_path, allow_cache_upload = go_toolchain.allow_cache_upload)
+
+    return symabis
+
+def _asssembly(
+    actions: AnalysisActions,
+    go_toolchain: GoToolchainInfo,
+    pkg_import_path: str,
+    main: bool,
+    s_files: list[Artifact],
+    h_files: list[Artifact],
+    asmhdr: Artifact | None,
+    assembler_flags: list[str],
+    shared: bool,
+    build_variant_id: str,
+) -> list[Artifact]:
+    if len(s_files) == 0:
+        return []
+
+    env = get_toolchain_env_vars(go_toolchain)
+
+    o_files = []
+    for s_file in s_files:
+        o_file = actions.declare_output("{}_{}.o".format(s_file.short_path, build_variant_id), has_content_based_path = True)
+        o_files.append(o_file)
+
+        asm_cmd = [
+            go_toolchain.go_wrapper,
+            ["--go", go_toolchain.assembler],
+            "--",
+            go_toolchain.assembler_flags,
+            assembler_flags,
+            _asm_args(go_toolchain, pkg_import_path, main, shared),
+            ["-o", o_file.as_output()],
+            ["-I", cmd_args(asmhdr, parent = 1)] if asmhdr else [],  # can it actually be None?
+            [cmd_args(h_files, parent = 1, prepend = "-I")] if h_files else [],
+            [cmd_args(s_files, parent = 1, prepend = "-I")],  # some .s files can include other .s files
+            ["-trimpath", "%cwd%"],
+            s_file,
+        ]
+
+        actions.run(
+            asm_cmd,
+            env = env,
+            category = "go_assembly",
+            identifier = "{}/{} [{}]".format(pkg_import_path, s_file.short_path, build_variant_id),
+            allow_cache_upload = go_toolchain.allow_cache_upload,
+        )
+
+    return o_files
+
+def _pack(
+    actions: AnalysisActions, go_toolchain: GoToolchainInfo, pkg_import_path: str, a_file: Artifact, o_files: list[Artifact], build_variant_id: str
+) -> Artifact:
+    if len(o_files) == 0:
+        # no need to repack .a file, if there are no .o files
+        return a_file
+
+    env = get_toolchain_env_vars(go_toolchain)
+
+    pkg_file = actions.declare_output("pkg{}.a".format(build_variant_id), has_content_based_path = True)
+
+    pack_cmd = [
+        go_toolchain.packer,
+        "c",
+        pkg_file.as_output(),
+        a_file,
+        o_files,
+    ]
+
+    actions.run(
+        pack_cmd,
+        env = env,
+        category = "go_pack",
+        identifier = "{} [{}]".format(pkg_import_path, build_variant_id),
+        allow_cache_upload = go_toolchain.allow_cache_upload,
+    )
+
+    return pkg_file
+
+def _embedcfg(
+    actions: AnalysisActions, go_toolchain: GoToolchainInfo, pkg_import_path: str, package_root: str, embed_srcs: dict[str, Artifact], embed_patterns: list[str]
+) -> Artifact | None:
+    if len(embed_patterns) == 0:
+        return None
+
+    embedcfg = actions.declare_output("embedcfg", has_content_based_path = True)
+
+    srcs_dir = actions.copied_dir(
+        "__embed_srcs_dir__",
+        {name.removeprefix(package_root).lstrip("/"): src for name, src in embed_srcs.items()},
+        has_content_based_path = True,
+    )
+
+    embed_cmd = [
+        go_toolchain.gen_embedcfg,
+        ["-o", embedcfg.as_output()],
+        ["-pkgdir", srcs_dir],
+        embed_patterns,
+    ]
+
+    actions.run(embed_cmd, category = "go_embedcfg", identifier = pkg_import_path, allow_cache_upload = go_toolchain.allow_cache_upload)
+
+    return embedcfg.with_associated_artifacts([srcs_dir])
+
+def _asm_args(go_toolchain: GoToolchainInfo, pkg_import_path: str, main: bool, shared: bool):
+    return [
+        ["-p", "main" if main else pkg_import_path],
+        ["-I", go_toolchain.env_go_root.project("pkg/include")] if go_toolchain.env_go_root else [],
+        ["-D", "GOOS_" + go_toolchain.env_go_os] if go_toolchain.env_go_os else [],
+        ["-D", "GOARCH_" + go_toolchain.env_go_arch] if go_toolchain.env_go_arch else [],
+        ["-shared"] if shared else [],
+        ["-std"] if go_toolchain.version and go_toolchain.version.minor >= 27 else [],  # todo: safe to remove once go1.28 is released
+    ]
diff --git a/buck2/prelude/go/packages.bzl b/buck2/prelude/go/packages.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/packages.bzl
@@ -0,0 +1,193 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("@prelude//cxx:headers.bzl", "prepare_headers")
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorArgs",
+)
+load("@prelude//utils:utils.bzl", "value_or")
+load(
+    ":coverage.bzl",
+    "GoCoverageMode",  # @Unused used as type
+)
+
+# Information about a package for GOPACKAGESDRIVER
+GoPackageInfo = provider(
+    fields = {
+        "build_out": provider_field(Artifact),
+        "cgo_gen_dir": provider_field(Artifact),
+        "go_list_out": provider_field(Artifact),
+        "package_root": provider_field(str),
+        "pkg_import_path": provider_field(str),
+        # Full list of package source files
+        # including generated and files of the package under test
+        "srcs": provider_field(list[Artifact]),
+    },
+)
+
+GoPkg = record(
+    # We have to produce allways shared (PIC) and non-shared (non-PIC) archives
+    archive_file = field(Artifact),
+    archive_file_shared = field(Artifact),
+    # The content of export_file and export_file_shared is likely to be the same
+    # but we need to produce both to avoid running compilation twice.
+    export_file = field(Artifact),
+    export_file_shared = field(Artifact),
+    coverage_instrumented = field(bool),
+)
+
+GoStdlibDynamicValue = provider(
+    fields = {
+        "pkgs": provider_field(dict[str, GoPkg]),
+    },
+)
+
+GoStdlib = provider(
+    fields = {
+        "dynamic_value": provider_field(DynamicValue),  # GoStdlibDynamicValue inside
+    },
+)
+
+def go_attr_pkg_name(ctx: AnalysisContext) -> str:
+    """
+    Return the Go package name for the given context corresponding to a rule.
+    """
+    return value_or(ctx.attrs.package_name, ctx.label.package)
+
+def merge_pkgs(pkgss: list[dict[str, GoPkg]]) -> dict[str, GoPkg]:
+    """
+    Merge mappings of packages into a single mapping, throwing an error on
+    conflicts.
+    """
+
+    all_pkgs = {}
+
+    for pkgs in pkgss:
+        for name, pkg in pkgs.items():
+            if name in all_pkgs and all_pkgs[name] != pkg:
+                fail("conflict for package {!r}: {} and {}".format(name, pkg, all_pkgs[name]))
+            all_pkgs[name] = pkg
+
+    return all_pkgs
+
+def pkg_artifacts(pkgs: dict[str, GoPkg], shared: bool) -> dict[str, Artifact]:
+    """
+    Return a map package name to a `shared` or `static` package artifact.
+    """
+    return {name: pkg.archive_file_shared if shared else pkg.archive_file for name, pkg in pkgs.items()}
+
+def export_files(pkgs: dict[str, GoPkg], shared: bool) -> dict[str, Artifact]:
+    """
+    Return a map package name to a `shared` or `static` package artifact.
+    """
+    return {name: pkg.export_file_shared if shared else pkg.export_file for name, pkg in pkgs.items()}
+
+# Keep in sync with: https://github.com/golang/go/blob/go1.26.0/src/cmd/go/internal/load/pkg.go#L1718C5
+_cgo_syscall_exclude = set([
+    "runtime/cgo",
+    "runtime/race",
+    "runtime/msan",
+    "runtime/asan",
+])
+
+def implicit_imports(
+    pkg_name: str, pkg_import_path: str, standard: bool, has_cgo_files: bool, coverage_enabled: bool, coverage_mode: GoCoverageMode | None
+) -> set[str]:
+    imports = set([])
+    if has_cgo_files:
+        if not standard or pkg_import_path != "runtime/cgo":
+            imports.add("runtime/cgo")
+
+        if not standard or pkg_import_path not in _cgo_syscall_exclude:
+            imports.add("syscall")
+
+    if pkg_name == "main":
+        if coverage_enabled and coverage_mode != None:
+            imports.add("runtime/coverage")
+
+    if coverage_enabled and coverage_mode == GoCoverageMode("atomic"):
+        imports.add("sync/atomic")
+
+    return imports
+
+def make_compile_importcfg(
+    actions: AnalysisActions, pkg_import_path: str, deps: dict[str, GoPkg], imports: set[str], import_map: dict[str, str] | None, shared: bool
+) -> Artifact:
+    required_pkgs = set(imports)  # copy set to avoid modifying it
+
+    # remove fake packages, build system should never try to provide them
+    required_pkgs -= set(["unsafe", "builtin", "C"])
+
+    provided_pkgs = set()
+    content, a_files = [], []
+    for name_, pkg_ in export_files(deps, shared).items():
+        # skip packages not used by the current package
+        if name_ not in required_pkgs:
+            continue
+
+        # Hack: we use cmd_args get "artifact" valid path and write it to a file.
+        content.append(cmd_args("packagefile ", name_, "=", pkg_, delimiter = "", hidden = [pkg_]))
+        a_files.append(pkg_)
+        provided_pkgs.add(name_)
+
+    if len(provided_pkgs) != len(required_pkgs):
+        message = "cannot find package(s) when building '{}' (is your BUCK target missing deps?)\n".format(pkg_import_path)
+        for imp in required_pkgs.difference(provided_pkgs):
+            message += "  - " + imp + "\n"
+
+        fail(message)
+
+    if import_map:
+        # add import map entries
+        for import_as, import_path in import_map.items():
+            content.append(cmd_args("importmap ", import_as, "=", import_path, delimiter = ""))
+
+        unused_importmap_entries = set(import_map.values()).difference(provided_pkgs)
+        if len(unused_importmap_entries) > 0:
+            message = "found importmap entries for non-existent dependencies:\n"
+            for imp in unused_importmap_entries:
+                message += "  - " + imp + "\n"
+
+            fail(message)
+
+    importcfg = actions.declare_output("{}.importcfg".format("shared" if shared else "non_shared"), has_content_based_path = True)
+    actions.write(importcfg, content)
+
+    return importcfg.with_associated_artifacts(a_files)
+
+def make_link_importcfg(actions: AnalysisActions, deps: dict[str, GoPkg], shared: bool) -> Artifact:
+    content, a_files = [], []
+    for name_, pkg_ in pkg_artifacts(deps, shared).items():
+        content.append(cmd_args("packagefile ", name_, "=", pkg_, delimiter = "", hidden = [pkg_]))
+        a_files.append(pkg_)
+
+    importcfg = actions.declare_output("{}.importcfg".format("shared" if shared else "non_shared"), has_content_based_path = True)
+    actions.write(importcfg, content)
+
+    return importcfg.with_associated_artifacts(a_files)
+
+# Return "_cgo_export.h" to expose exported C declarations to non-Go rules
+def cgo_exported_preprocessor(ctx: AnalysisContext, pkg_info: GoPackageInfo) -> CPreprocessor:
+    cxx_toolchain_info = ctx.attrs._cxx_toolchain[CxxToolchainInfo]
+    return CPreprocessor(
+        args = CPreprocessorArgs(
+            args = [
+                "-I",
+                prepare_headers(
+                    ctx.actions,
+                    cxx_toolchain_info,
+                    {"{}/{}.h".format(ctx.label.package, ctx.label.name): pkg_info.cgo_gen_dir.project("_cgo_export.h")},
+                    "cgo-exported-headers",
+                    uses_content_based_paths = True,
+                ).include_path,
+            ]
+        )
+    )
diff --git a/buck2/prelude/go/tags/constraints/BUCK b/buck2/prelude/go/tags/constraints/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tags/constraints/BUCK
@@ -0,0 +1,8 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load(":defs.bzl", "generate_tag_constraints")
+
+oncall("build_infra")
+
+source_listing()
+
+generate_tag_constraints()
diff --git a/buck2/prelude/go/tags/constraints/defs.bzl b/buck2/prelude/go/tags/constraints/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tags/constraints/defs.bzl
@@ -0,0 +1,19 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:native.bzl", "native")
+load("@prelude//go/transitions:tags_helper.bzl", "allowed_build_tags")
+
+def generate_tag_constraints():
+    for tag in allowed_build_tags:
+        native.constraint(
+            name = tag,
+            default = "unset",
+            values = ["set", "unset"],
+            visibility = ["PUBLIC"],
+        )
diff --git a/buck2/prelude/go/toolchain.bzl b/buck2/prelude/go/toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/toolchain.bzl
@@ -0,0 +1,113 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+GoVersion = record(minor = field(int), patch = field(int))
+
+GoDistrInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "bin_go": provider_field(RunInfo),
+        "go_root": provider_field(Artifact | None),
+        "tool_asm": provider_field(RunInfo),
+        "tool_compile": provider_field(RunInfo),
+        "tool_cover": provider_field(RunInfo),
+        "tool_cgo": provider_field(RunInfo),
+        "tool_link": provider_field(RunInfo),
+        "version": provider_field(GoVersion | None),
+    },
+)
+
+GoToolchainInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "allow_cache_upload": provider_field(bool | None, default = None),
+        "assembler": provider_field(RunInfo),
+        "assembler_flags": provider_field(typing.Any, default = []),
+        "cxx_compiler_flags": provider_field(typing.Any, default = []),
+        "cgo": provider_field(RunInfo),
+        "gen_embedcfg": provider_field(RunInfo),
+        "go_wrapper": provider_field(RunInfo),
+        "compiler": provider_field(RunInfo),
+        "compiler_flags": provider_field(typing.Any, default = []),
+        "pkg_analyzer": provider_field(RunInfo),
+        "cover": provider_field(RunInfo),
+        "env_go_arch": provider_field(str),
+        "env_go_os": provider_field(str),
+        "env_go_arm": provider_field(str | None, default = None),
+        "env_go_root": provider_field(Artifact | None, default = None),
+        "env_go_debug": provider_field(dict[str, str], default = {}),
+        "env_go_experiment": provider_field(list[str], default = []),
+        "external_linker_flags": provider_field(typing.Any, default = []),
+        "go": provider_field(RunInfo),
+        "linker": provider_field(RunInfo),
+        "linker_flags": provider_field(typing.Any, default = []),
+        "packer": provider_field(RunInfo),
+        "build_tags": provider_field(list[str], default = []),
+        "asan": provider_field(bool, default = False),
+        "race": provider_field(bool, default = False),
+        "fuzz": provider_field(bool, default = False),
+        "version": provider_field(GoVersion | None),
+    },
+)
+
+def get_toolchain_env_vars(toolchain: GoToolchainInfo) -> dict[str, str | cmd_args | Artifact]:
+    env = {
+        "GOARCH": toolchain.env_go_arch,
+        "GOEXPERIMENT": ",".join(toolchain.env_go_experiment),
+        "GOOS": toolchain.env_go_os,
+    }
+
+    if toolchain.env_go_arm != None:
+        env["GOARM"] = toolchain.env_go_arm
+    if toolchain.env_go_debug:
+        godebug = ",".join(["{}={}".format(k, v) for k, v in toolchain.env_go_debug.items()])
+        env["GODEBUG"] = godebug
+
+    return env
+
+def evaluate_cgo_enabled(cgo_enabled: bool, override_cgo_enabled: bool | None = None) -> bool:
+    if override_cgo_enabled != None:
+        return override_cgo_enabled
+
+    return cgo_enabled
+
+# Parse Go version from string, accepted format:
+# - "1.20"
+# - "1.22rc1" (for pre-release versions)
+# - "1.22.1" (for patch versions)
+# - "unknown" or "devel" (for development purposes)
+def parse_go_version(version: str) -> GoVersion | None:
+    if version == "unknown" or version == "devel":
+        return None
+
+    version_parts = version.split(".")
+
+    if len(version_parts) < 2 or len(version_parts) > 3:
+        fail("Invalid Go version: '{}'. Expected format '1.20', '1.22rc1', '1.22.1', 'devel' or 'unknown'.".format(version))
+
+    if version_parts[0] != "1":
+        fail("Invalid Go version: '{}'. Expected major version to be '1'.".format(version))
+
+    if version_parts[1].isdigit():
+        minor = int(version_parts[1])
+    elif "rc" in version_parts[1]:
+        rc_parts = version_parts[1].split("rc")
+        if not (rc_parts[0].isdigit() and rc_parts[1].isdigit()):
+            fail("Invalid Go version: '{}'. Expected minor version to be a number with an optional RC suffix like 'rc1'.".format(version))
+        minor = int(rc_parts[0])
+    else:
+        fail("Invalid Go version: '{}'. Expected minor version to be a number with an optional RC suffix like 'rc1'.".format(version))
+
+    patch = 0
+    if len(version_parts) > 2:
+        if not version_parts[2].isdigit():
+            fail("Invalid Go version: '{}'. Expected patch version to be a number.".format(version))
+
+        patch = int(version_parts[2])
+
+    return GoVersion(minor = minor, patch = patch)
diff --git a/buck2/prelude/go/tools/BUCK b/buck2/prelude/go/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/BUCK
@@ -0,0 +1,93 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.go_stdlib(
+    name = "stdlib",
+    visibility = ["PUBLIC"],
+)
+
+prelude.go_bootstrap_binary(
+    name = "tool_pack",
+    build_args = [
+        "cmd/pack",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+prelude.go_bootstrap_binary(
+    name = "go_wrapper",
+    srcs = [
+        "buildid.go",
+        "go_wrapper.go",
+    ],
+    build_args = [
+        "buildid.go",
+        "go_wrapper.go",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+prelude.go_bootstrap_binary(
+    name = "testmaingen",
+    srcs = ["testmaingen.go"],
+    build_args = [
+        "testmaingen.go",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+)
+
+prelude.go_bootstrap_binary(
+    name = "list_tests",
+    srcs = ["list_tests.go"],
+    build_args = [
+        "list_tests.go",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+)
+
+prelude.go_bootstrap_binary(
+    name = "pkg_analyzer",
+    srcs = ["pkg_analyzer.go"],
+    build_args = [
+        "pkg_analyzer.go",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+)
+
+prelude.go_bootstrap_binary(
+    name = "gen_embedcfg",
+    srcs = ["gen_embedcfg.go"],
+    build_args = [
+        "gen_embedcfg.go",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+)
+
+prelude.go_bootstrap_binary(
+    name = "copy_goroot",
+    srcs = ["copy_goroot.go"],
+    build_args = [
+        "copy_goroot.go",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+)
+
+prelude.go_test(
+    name = "buildid_test",
+    srcs = ["buildid.go", "buildid_test.go"],
+)
diff --git a/buck2/prelude/go/tools/buildid.go b/buck2/prelude/go/tools/buildid.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/buildid.go
@@ -0,0 +1,183 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package main
+
+import (
+	"crypto/sha256"
+	"debug/elf"
+	"fmt"
+	"io"
+	"os"
+)
+
+// ntGNUBuildID is the NT_GNU_BUILD_ID note type. debug/elf does not export it.
+const ntGNUBuildID = 3
+
+// outputPath returns the linker's -o value. _link_impl (link.bzl) appends the
+// authoritative "-o <out>" after any user linker_flags, so return the LAST "-o"
+// to avoid picking up a stray one from user-supplied flags.
+func outputPath(args []string) string {
+	out := ""
+	for i := 0; i+1 < len(args); i++ {
+		if args[i] == "-o" {
+			out = args[i+1]
+		}
+	}
+	return out
+}
+
+// setGNUBuildID fills the zeroed .note.gnu.build-id placeholder ("-B 0x00..00")
+// of an internally linked Go binary with sha256 of the output. The write is in
+// place and same-size, so the note stays in its runtime-visible PT_NOTE segment.
+//
+// Only a still-all-zero descriptor is rewritten: a non-zero one means an external
+// linker owns the build-id and must not be clobbered. A non-ELF output, a missing
+// note, or an externally-owned descriptor is a no-op; unreadable/corrupt output
+// or a short write aborts the link, so a half-written descriptor never ships.
+func setGNUBuildID(path string) error {
+	descOff, descLen, err := findBuildIDNote(path)
+	if err != nil || descOff == 0 {
+		return err
+	}
+
+	rf, err := os.Open(path)
+	if err != nil {
+		return fmt.Errorf("reading linked output %q: %w", path, err)
+	}
+	defer rf.Close()
+	fi, err := rf.Stat()
+	if err != nil {
+		return fmt.Errorf("stat %q for build-id: %w", path, err)
+	}
+
+	newDesc, patch, err := computeBuildID(rf, fi.Size(), descOff, descLen)
+	if err != nil {
+		return err
+	}
+	if !patch {
+		return nil
+	}
+
+	f, err := os.OpenFile(path, os.O_RDWR, 0)
+	if err != nil {
+		return fmt.Errorf("opening %q for build-id write: %w", path, err)
+	}
+	if n, err := f.WriteAt(newDesc, descOff); err != nil {
+		f.Close()
+		return fmt.Errorf("writing build-id to %q: %w", path, err)
+	} else if n != len(newDesc) {
+		f.Close()
+		return fmt.Errorf("writing build-id to %q: short write %d of %d bytes", path, n, len(newDesc))
+	}
+	if err := f.Close(); err != nil {
+		return fmt.Errorf("closing %q after build-id write: %w", path, err)
+	}
+	return nil
+}
+
+// computeBuildID returns the descriptor bytes to write, or patch=false when the
+// descriptor is not the all-zero placeholder (i.e. an external linker set it).
+// It streams the output through sha256 so it never holds the whole (possibly
+// multi-GB) binary in memory. The on-disk descriptor is still zero here, so
+// hashing the file as-is is self-consistent and reproducible across hosts --
+// the same self-reference break ld/lld use.
+func computeBuildID(r io.ReaderAt, size, descOff int64, descLen int) (newDesc []byte, patch bool, err error) {
+	// Bounds required to read the descriptor at all.
+	if descLen <= 0 || descOff < 0 || descOff+int64(descLen) > size {
+		return nil, false, fmt.Errorf("build-id descriptor out of range: off=%d len=%d file=%d", descOff, descLen, size)
+	}
+	// A non-zero descriptor is owned by an external linker (or a user -B): never
+	// touch it, whatever its size.
+	desc := make([]byte, descLen)
+	if _, err := r.ReadAt(desc, descOff); err != nil {
+		return nil, false, fmt.Errorf("reading build-id descriptor: %w", err)
+	}
+	if !allZero(desc) {
+		return nil, false, nil
+	}
+	// We only fill our own placeholder, so it must fit the hash we write.
+	if descLen > sha256.Size {
+		return nil, false, fmt.Errorf("build-id placeholder too large: %d > %d bytes", descLen, sha256.Size)
+	}
+	h := sha256.New()
+	if _, err := io.Copy(h, io.NewSectionReader(r, 0, size)); err != nil {
+		return nil, false, fmt.Errorf("hashing linked output: %w", err)
+	}
+	return h.Sum(nil)[:descLen], true, nil
+}
+
+// findBuildIDNote returns the file offset and length of the .note.gnu.build-id
+// descriptor, or (0, 0, nil) to signal "skip" (not ELF, or no build-id note).
+// An I/O failure opening the output is a real error, returned not swallowed.
+func findBuildIDNote(path string) (descOff int64, descLen int, err error) {
+	osf, err := os.Open(path)
+	if err != nil {
+		return 0, 0, fmt.Errorf("opening linked output %q: %w", path, err)
+	}
+	defer osf.Close()
+
+	// Skip a genuinely non-ELF output (no ELF magic) -- the Go linker silently
+	// ignores the reserved -B note on non-ELF formats, so there is nothing to
+	// patch. But an output that claims to be ELF yet fails to parse is a corrupt
+	// or truncated linker output, which is a real error, not a skip.
+	var magic [len(elf.ELFMAG)]byte
+	if _, err := osf.ReadAt(magic[:], 0); err != nil {
+		return 0, 0, fmt.Errorf("reading linked output %q: %w", path, err)
+	}
+	if string(magic[:]) != elf.ELFMAG {
+		return 0, 0, nil
+	}
+	f, err := elf.NewFile(osf)
+	if err != nil {
+		return 0, 0, fmt.Errorf("parsing %q as ELF: %w", path, err)
+	}
+
+	sec := f.Section(".note.gnu.build-id")
+	if sec == nil {
+		return 0, 0, nil // no build-id note (e.g. an external link that emitted none)
+	}
+	data, err := sec.Data()
+	if err != nil {
+		return 0, 0, fmt.Errorf("reading .note.gnu.build-id in %q: %w", path, err)
+	}
+
+	// The section is located by name, so its contents must be a well-formed
+	// NT_GNU_BUILD_ID note (name "GNU", type 3) whose descriptor lies within the
+	// section. Any deviation is a corrupt linker output -- a real error, never a
+	// silent skip or an out-of-section write. The || short-circuits so the name
+	// slice is reached only once its bounds are known valid.
+	if len(data) < 12 {
+		return 0, 0, fmt.Errorf("malformed .note.gnu.build-id in %q: %d bytes", path, len(data))
+	}
+	namesz := f.ByteOrder.Uint32(data[0:4])
+	descsz := f.ByteOrder.Uint32(data[4:8])
+	typ := f.ByteOrder.Uint32(data[8:12])
+	descStart := 12 + align4(int64(namesz))
+	if typ != ntGNUBuildID || namesz != 4 ||
+		12+int64(namesz) > int64(len(data)) || string(data[12:12+namesz]) != "GNU\x00" ||
+		descStart+int64(descsz) > int64(len(data)) {
+		return 0, 0, fmt.Errorf("malformed .note.gnu.build-id in %q: namesz=%d descsz=%d type=%d len=%d", path, namesz, descsz, typ, len(data))
+	}
+	return int64(sec.Offset) + descStart, int(descsz), nil
+}
+
+func align4(n int64) int64 {
+	return (n + 3) &^ 3
+}
+
+func allZero(b []byte) bool {
+	for _, x := range b {
+		if x != 0 {
+			return false
+		}
+	}
+	return true
+}
diff --git a/buck2/prelude/go/tools/buildid_test.go b/buck2/prelude/go/tools/buildid_test.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/buildid_test.go
@@ -0,0 +1,292 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package main
+
+import (
+	"bytes"
+	"crypto/sha256"
+	"debug/elf"
+	"encoding/binary"
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+// newFile returns a synthetic "binary" with a descLen-byte descriptor at descOff.
+func newFile(size int, descOff int64, descLen int, descFill byte) []byte {
+	buf := make([]byte, size)
+	for i := range buf {
+		buf[i] = byte(i)
+	}
+	for i := 0; i < descLen; i++ {
+		buf[descOff+int64(i)] = descFill
+	}
+	return buf
+}
+
+func TestComputeBuildIDPatchesZeroPlaceholder(t *testing.T) {
+	const size, descOff, descLen = 256, 64, 20
+	buf := newFile(size, descOff, descLen, 0)
+
+	desc, patch, err := computeBuildID(bytes.NewReader(buf), int64(len(buf)), descOff, descLen)
+	if err != nil || !patch {
+		t.Fatalf("computeBuildID: patch=%v err=%v, want patch=true nil", patch, err)
+	}
+	if len(desc) != descLen {
+		t.Fatalf("descriptor len = %d, want %d", len(desc), descLen)
+	}
+	// Self-consistency: the hash must be over the file with the descriptor zeroed.
+	want := sha256.Sum256(buf)
+	if !bytes.Equal(desc, want[:descLen]) {
+		t.Fatalf("descriptor = %x, want %x", desc, want[:descLen])
+	}
+}
+
+func TestComputeBuildIDSensitiveToContent(t *testing.T) {
+	base := newFile(256, 64, 20, 0)
+	a, _, _ := computeBuildID(bytes.NewReader(base), int64(len(base)), 64, 20)
+	// Flip a byte outside the descriptor region.
+	other := newFile(256, 64, 20, 0)
+	other[10] ^= 0xff
+	b, _, _ := computeBuildID(bytes.NewReader(other), int64(len(other)), 64, 20)
+	if bytes.Equal(a, b) {
+		t.Fatalf("build-id unchanged after content change: %x", a)
+	}
+}
+
+func TestComputeBuildIDSkipsNonZeroDescriptor(t *testing.T) {
+	buf := newFile(256, 64, 20, 0xaa) // external linker already set it
+	desc, patch, err := computeBuildID(bytes.NewReader(buf), int64(len(buf)), 64, 20)
+	if err != nil {
+		t.Fatalf("unexpected err: %v", err)
+	}
+	if patch || desc != nil {
+		t.Fatalf("expected skip, got patch=%v desc=%x", patch, desc)
+	}
+}
+
+func TestComputeBuildIDRejectsOutOfRange(t *testing.T) {
+	zeros := make([]byte, 64)
+	for _, tc := range []struct {
+		name    string
+		buf     []byte
+		descOff int64
+		descLen int
+	}{
+		{"len non-positive", zeros, 0, 0},
+		{"off negative", zeros, -1, 20},
+		{"past end", zeros, 60, 20},
+		// An all-zero placeholder we would fill must fit the hash we write.
+		{"placeholder too large", zeros, 0, sha256.Size + 1},
+	} {
+		if _, _, err := computeBuildID(bytes.NewReader(tc.buf), int64(len(tc.buf)), tc.descOff, tc.descLen); err == nil {
+			t.Errorf("%s: expected error, got nil", tc.name)
+		}
+	}
+}
+
+// A non-zero descriptor is externally owned and must be skipped, not rejected,
+// even when it is larger than our hash (guards the check-ordering fix).
+func TestComputeBuildIDSkipsLargeNonZeroDescriptor(t *testing.T) {
+	buf := newFile(64, 0, sha256.Size+1, 0xaa)
+	desc, patch, err := computeBuildID(bytes.NewReader(buf), int64(len(buf)), 0, sha256.Size+1)
+	if err != nil || patch || desc != nil {
+		t.Fatalf("large non-zero descriptor: desc=%x patch=%v err=%v, want skip", desc, patch, err)
+	}
+}
+
+func TestOutputPath(t *testing.T) {
+	for _, tc := range []struct {
+		args []string
+		want string
+	}{
+		{[]string{"-buildmode=exe", "-o", "out/bin", "main.o"}, "out/bin"},
+		{[]string{"-buildmode=exe", "main.o"}, ""},
+		{[]string{"main.o", "-o"}, ""}, // dangling -o must not panic
+		// A stray -o in user linker_flags must not win over _link_impl's trailing -o.
+		{[]string{"-o", "stray", "-buildmode=exe", "-o", "out/bin", "main.o"}, "out/bin"},
+	} {
+		if got := outputPath(tc.args); got != tc.want {
+			t.Errorf("outputPath(%v) = %q, want %q", tc.args, got, tc.want)
+		}
+	}
+}
+
+func TestAlign4(t *testing.T) {
+	for in, want := range map[int64]int64{0: 0, 1: 4, 4: 4, 5: 8} {
+		if got := align4(in); got != want {
+			t.Errorf("align4(%d) = %d, want %d", in, got, want)
+		}
+	}
+}
+
+// craftELFWithZeroNote builds a minimal little-endian ELF64 with a
+// .note.gnu.build-id section whose descLen-byte descriptor is all zero (the
+// placeholder Go's `-B 0x00..00` writes). The note contents sit at file offset
+// 64, so the descriptor lands at 64 + 12 (note header) + 4 (aligned "GNU\0") = 80.
+func craftELFWithZeroNote(descLen int) []byte {
+	const ehdrSize, shdrSize, noteOff = 64, 64, 64
+
+	note := make([]byte, 12+4+descLen)
+	binary.LittleEndian.PutUint32(note[0:], 4)               // namesz
+	binary.LittleEndian.PutUint32(note[4:], uint32(descLen)) // descsz
+	binary.LittleEndian.PutUint32(note[8:], ntGNUBuildID)    // type
+	copy(note[12:], "GNU\x00")                               // name; descriptor left zero
+
+	shstr := []byte("\x00.note.gnu.build-id\x00.shstrtab\x00")
+	shstrOff := noteOff + len(note)
+	shoff := shstrOff + len(shstr)
+	buf := make([]byte, shoff+3*shdrSize)
+
+	copy(buf, []byte{0x7f, 'E', 'L', 'F', 2, 1, 1, 0}) // ident: ELF64, LE
+	binary.LittleEndian.PutUint16(buf[16:], 2)         // ET_EXEC
+	binary.LittleEndian.PutUint16(buf[18:], 62)        // EM_X86_64
+	binary.LittleEndian.PutUint32(buf[20:], 1)         // version
+	binary.LittleEndian.PutUint64(buf[40:], uint64(shoff))
+	binary.LittleEndian.PutUint16(buf[52:], ehdrSize)
+	binary.LittleEndian.PutUint16(buf[58:], shdrSize)
+	binary.LittleEndian.PutUint16(buf[60:], 3) // shnum
+	binary.LittleEndian.PutUint16(buf[62:], 2) // shstrndx
+	copy(buf[noteOff:], note)
+	copy(buf[shstrOff:], shstr)
+
+	sh1 := shoff + shdrSize                                        // .note.gnu.build-id
+	binary.LittleEndian.PutUint32(buf[sh1:], 1)                    // name offset
+	binary.LittleEndian.PutUint32(buf[sh1+4:], 7)                  // SHT_NOTE
+	binary.LittleEndian.PutUint64(buf[sh1+8:], 2)                  // SHF_ALLOC
+	binary.LittleEndian.PutUint64(buf[sh1+24:], uint64(noteOff))   // offset
+	binary.LittleEndian.PutUint64(buf[sh1+32:], uint64(len(note))) // size
+	binary.LittleEndian.PutUint64(buf[sh1+48:], 4)                 // addralign
+
+	sh2 := shoff + 2*shdrSize                                       // .shstrtab
+	binary.LittleEndian.PutUint32(buf[sh2:], 20)                    // name offset
+	binary.LittleEndian.PutUint32(buf[sh2+4:], 3)                   // SHT_STRTAB
+	binary.LittleEndian.PutUint64(buf[sh2+24:], uint64(shstrOff))   // offset
+	binary.LittleEndian.PutUint64(buf[sh2+32:], uint64(len(shstr))) // size
+	binary.LittleEndian.PutUint64(buf[sh2+48:], 1)                  // addralign
+	return buf
+}
+
+func TestFindAndSetBuildIDNote(t *testing.T) {
+	const descLen = 20
+	path := filepath.Join(t.TempDir(), "bin")
+	orig := craftELFWithZeroNote(descLen)
+	if err := os.WriteFile(path, orig, 0o644); err != nil {
+		t.Fatal(err)
+	}
+
+	descOff, gotLen, err := findBuildIDNote(path)
+	if err != nil {
+		t.Fatalf("findBuildIDNote: %v", err)
+	}
+	if descOff != 80 || gotLen != descLen {
+		t.Fatalf("findBuildIDNote = (%d,%d), want (80,%d)", descOff, gotLen, descLen)
+	}
+
+	if err := setGNUBuildID(path); err != nil {
+		t.Fatalf("setGNUBuildID: %v", err)
+	}
+	patched, err := os.ReadFile(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(patched) != len(orig) {
+		t.Fatalf("file size changed: %d -> %d (write not in place)", len(orig), len(patched))
+	}
+	got := patched[descOff : descOff+int64(descLen)]
+	if allZero(got) {
+		t.Fatal("descriptor still all-zero after patch")
+	}
+	zeroed := append([]byte(nil), patched...)
+	for i := 0; i < descLen; i++ {
+		zeroed[descOff+int64(i)] = 0
+	}
+	want := sha256.Sum256(zeroed)
+	if !bytes.Equal(got, want[:descLen]) {
+		t.Fatalf("build-id = %x, want sha256(output,desc zeroed)[:20] = %x", got, want[:descLen])
+	}
+
+	// Idempotent: the now non-zero descriptor is treated as externally owned -> skip.
+	if err := setGNUBuildID(path); err != nil {
+		t.Fatalf("second setGNUBuildID: %v", err)
+	}
+	again, err := os.ReadFile(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !bytes.Equal(patched, again) {
+		t.Fatal("second setGNUBuildID modified an already-set (non-zero) descriptor")
+	}
+}
+
+// TestFindBuildIDNoteNonELF confirms a non-ELF output (e.g. a wasm target that
+// passed the gate) is a clean skip, not an error.
+func TestFindBuildIDNoteNonELF(t *testing.T) {
+	path := filepath.Join(t.TempDir(), "not-elf")
+	if err := os.WriteFile(path, []byte("#!/bin/sh\necho hi\n"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	descOff, descLen, err := findBuildIDNote(path)
+	if err != nil || descOff != 0 || descLen != 0 {
+		t.Fatalf("findBuildIDNote(non-ELF) = (%d,%d,%v), want (0,0,nil)", descOff, descLen, err)
+	}
+}
+
+// TestFindBuildIDNoteMissingFile confirms a missing/unreadable output is a real
+// error, not swallowed.
+func TestFindBuildIDNoteMissingFile(t *testing.T) {
+	if _, _, err := findBuildIDNote(filepath.Join(t.TempDir(), "does-not-exist")); err == nil {
+		t.Fatal("findBuildIDNote(missing) = nil error, want non-nil (must not swallow I/O errors)")
+	}
+}
+
+// TestFindBuildIDNoteCorruptELF confirms an output with ELF magic that fails to
+// parse is a real error, not silently skipped like a genuine non-ELF file.
+func TestFindBuildIDNoteCorruptELF(t *testing.T) {
+	path := filepath.Join(t.TempDir(), "corrupt")
+	if err := os.WriteFile(path, append([]byte(elf.ELFMAG), 0, 0, 0, 0), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	if _, _, err := findBuildIDNote(path); err == nil {
+		t.Fatal("findBuildIDNote(corrupt ELF) = nil error, want non-nil (must not swallow corrupt output)")
+	}
+}
+
+// TestFindBuildIDNoteDescriptorOverrun confirms a note whose descsz claims more
+// than the section holds is a real error, not an out-of-section read/write.
+func TestFindBuildIDNoteDescriptorOverrun(t *testing.T) {
+	buf := craftELFWithZeroNote(20)
+	// Corrupt descsz (2nd u32 of the note header, at file offset 64+4) to overrun.
+	binary.LittleEndian.PutUint32(buf[64+4:], 1<<20)
+	path := filepath.Join(t.TempDir(), "overrun")
+	if err := os.WriteFile(path, buf, 0o644); err != nil {
+		t.Fatal(err)
+	}
+	if _, _, err := findBuildIDNote(path); err == nil {
+		t.Fatal("findBuildIDNote(oversized descsz) = nil error, want non-nil (descriptor overruns section)")
+	}
+}
+
+// TestFindBuildIDNoteTruncatedNote confirms a note section too short to even hold
+// its declared name is a real error, not a silent skip. craftELFWithZeroNote(20)
+// layout: ehdr[0:64], note[64:100], shstrtab[100:130], shoff=130; shdr[1] starts
+// at 194 and its sh_size field is at +32 = 226.
+func TestFindBuildIDNoteTruncatedNote(t *testing.T) {
+	buf := craftELFWithZeroNote(20)
+	binary.LittleEndian.PutUint64(buf[226:], 14) // shrink note section below the 16-byte name end
+	path := filepath.Join(t.TempDir(), "trunc")
+	if err := os.WriteFile(path, buf, 0o644); err != nil {
+		t.Fatal(err)
+	}
+	if _, _, err := findBuildIDNote(path); err == nil {
+		t.Fatal("findBuildIDNote(truncated note) = nil error, want non-nil (corrupt note, not skip)")
+	}
+}
diff --git a/buck2/prelude/go/tools/copy_goroot.go b/buck2/prelude/go/tools/copy_goroot.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/copy_goroot.go
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package main
+
+import (
+	"flag"
+	"log"
+	"os"
+	"os/exec"
+	"strings"
+)
+
+func main() {
+	output := flag.String("o", "", "Output file")
+	flag.Parse()
+
+	if *output == "" {
+		flag.Usage()
+		os.Exit(1)
+	}
+
+	cmd := exec.Command("go", "env", "GOROOT")
+	out, err := cmd.Output()
+	if err != nil {
+		log.Fatalf("failed to execute `go env GOROOT`: %v", err)
+	}
+	goroot := strings.TrimSpace(string(out))
+	if goroot == "" {
+		log.Fatal("GOROOT is empty")
+	}
+
+	if err := os.CopyFS(*output, os.DirFS(goroot)); err != nil {
+		log.Fatalf("copy directory %q -> %q: %v", goroot, *output, err)
+	}
+}
diff --git a/buck2/prelude/go/tools/gen_embedcfg.go b/buck2/prelude/go/tools/gen_embedcfg.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gen_embedcfg.go
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package main
+
+import (
+	"encoding/json"
+	"flag"
+	"fmt"
+	"io/fs"
+	"os"
+	"path"
+	"path/filepath"
+	"sort"
+	"strings"
+)
+
+// EmbedCfg is the structure expected by the Go compiler's -embedcfg flag
+type EmbedCfg struct {
+	Patterns map[string][]string `json:"Patterns"`
+	Files    map[string]string   `json:"Files"`
+}
+
+func main() {
+	pkgdir := flag.String("pkgdir", "", "Package directory containing files to embed (required)")
+	output := flag.String("o", "", "Output file for embedcfg JSON (required)")
+	flag.Parse()
+
+	if *pkgdir == "" {
+		fatal("-pkgdir is required")
+	}
+	if *output == "" {
+		fatal("-o is required")
+	}
+
+	patterns := flag.Args()
+
+	files, pmap, err := resolveEmbed(*pkgdir, patterns)
+	if err != nil {
+		fatal("%v", err)
+	}
+
+	cfg := EmbedCfg{
+		Patterns: pmap,
+		Files:    make(map[string]string),
+	}
+
+	for _, file := range files {
+		cfg.Files[file] = filepath.Join(*pkgdir, file)
+	}
+
+	data, err := json.MarshalIndent(&cfg, "", "\t")
+	if err != nil {
+		fatal("failed to marshal embedcfg: %v", err)
+	}
+
+	if err := os.WriteFile(*output, data, 0644); err != nil {
+		fatal("failed to write output file: %v", err)
+	}
+}
+
+func fatal(format string, args ...interface{}) {
+	fmt.Fprintf(os.Stderr, format+"\n", args...)
+	os.Exit(1)
+}
+
+// resolveEmbed resolves embed patterns and returns:
+// - files: deduplicated list of matched files (relative to pkgdir)
+// - pmap: mapping from original pattern to matched files
+func resolveEmbed(pkgdir string, patterns []string) (files []string, pmap map[string][]string, err error) {
+	pmap = make(map[string][]string)
+	have := make(map[string]bool)
+	var list []string
+
+	for _, pattern := range patterns {
+		origPattern := pattern
+
+		// Handle all: prefix which includes hidden files
+		all := strings.HasPrefix(pattern, "all:")
+		if all {
+			pattern = pattern[len("all:"):]
+		}
+
+		// Validate the pattern
+		if !validEmbedPattern(pattern) {
+			return nil, nil, fmt.Errorf("invalid embed pattern %q", origPattern)
+		}
+
+		// Match files for this pattern
+		match, err := matchPattern(pkgdir, pattern, all)
+		if err != nil {
+			return nil, nil, fmt.Errorf("pattern %q: %v", origPattern, err)
+		}
+
+		if len(match) == 0 {
+			return nil, nil, fmt.Errorf("pattern %s: no matching files found", origPattern)
+		}
+
+		// Sort matches for deterministic output
+		sort.Strings(match)
+		pmap[origPattern] = match
+
+		// Add to deduplicated list
+		for _, m := range match {
+			if !have[m] {
+				have[m] = true
+				list = append(list, m)
+			}
+		}
+	}
+
+	sort.Strings(list)
+	return list, pmap, nil
+}
+
+// validEmbedPattern checks if the pattern is valid for embedding
+func validEmbedPattern(pattern string) bool {
+	if !fs.ValidPath(pattern) {
+		return false
+	}
+	// "." is not allowed as a pattern
+	if pattern == "." {
+		return false
+	}
+	return true
+}
+
+// isBadEmbedName checks if the name is invalid for embedding (VCS dirs, empty)
+func isBadEmbedName(name string) bool {
+	if name == "" {
+		return true
+	}
+	switch name {
+	case ".git", ".svn", ".hg", ".bzr":
+		return true
+	}
+	return false
+}
+
+// isHidden returns true if the name starts with . or _
+func isHidden(name string) bool {
+	return strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_")
+}
+
+// matchPattern matches files against a pattern
+func matchPattern(pkgdir, pattern string, all bool) ([]string, error) {
+	// Quote special glob characters in pkgdir
+	quotedPkgdir := quoteGlobMeta(pkgdir)
+
+	// Build the full glob pattern
+	// Convert pattern separators from / to OS-specific
+	osPattern := filepath.FromSlash(pattern)
+	fullPattern := filepath.Join(quotedPkgdir, osPattern)
+
+	// Get initial matches using filepath.Glob
+	matches, err := filepath.Glob(fullPattern)
+	if err != nil {
+		return nil, err
+	}
+
+	var result []string
+
+	for _, match := range matches {
+		// Get the relative path from pkgdir
+		rel, err := filepath.Rel(pkgdir, match)
+		if err != nil {
+			continue
+		}
+		// Convert to forward slashes for consistency
+		rel = filepath.ToSlash(rel)
+
+		info, err := os.Lstat(match)
+		if err != nil {
+			continue
+		}
+
+		if info.IsDir() {
+			// For directories, walk and collect all files
+			dirFiles, err := walkDir(pkgdir, rel, all)
+			if err != nil {
+				return nil, err
+			}
+			result = append(result, dirFiles...)
+		} else {
+			// For files, check if they should be included
+			base := path.Base(rel)
+			if isBadEmbedName(base) {
+				continue
+			}
+			result = append(result, rel)
+		}
+	}
+
+	return result, nil
+}
+
+// walkDir recursively walks a directory and collects files for embedding
+func walkDir(pkgdir, dir string, all bool) ([]string, error) {
+	var result []string
+	fullDir := filepath.Join(pkgdir, filepath.FromSlash(dir))
+
+	entries, err := os.ReadDir(fullDir)
+	if err != nil {
+		return nil, err
+	}
+
+	for _, entry := range entries {
+		name := entry.Name()
+
+		// Skip bad embed names (VCS directories)
+		if isBadEmbedName(name) {
+			continue
+		}
+
+		// Skip hidden files/dirs unless all: prefix was used
+		if !all && isHidden(name) {
+			continue
+		}
+
+		relPath := path.Join(dir, name)
+
+		if entry.IsDir() {
+			// Recursively walk subdirectory
+			subFiles, err := walkDir(pkgdir, relPath, all)
+			if err != nil {
+				return nil, err
+			}
+			result = append(result, subFiles...)
+		} else {
+			result = append(result, relPath)
+		}
+	}
+
+	return result, nil
+}
+
+// quoteGlobMeta quotes glob metacharacters in a path
+func quoteGlobMeta(s string) string {
+	special := `*?[\`
+	var b strings.Builder
+	for _, c := range s {
+		if strings.ContainsRune(special, c) {
+			b.WriteRune('\\')
+		}
+		b.WriteRune(c)
+	}
+	return b.String()
+}
diff --git a/buck2/prelude/go/tools/go_wrapper.go b/buck2/prelude/go/tools/go_wrapper.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/go_wrapper.go
@@ -0,0 +1,183 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package main
+
+import (
+	"bufio"
+	"encoding/json"
+	"flag"
+	"fmt"
+	"io"
+	"log"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strings"
+)
+
+func loadArgs(args []string) []string {
+	newArgs := make([]string, 0, 0)
+	for _, arg := range args {
+		if !strings.HasPrefix(arg, "@") {
+			newArgs = append(newArgs, arg)
+		} else {
+			file, _ := os.Open(arg[1:])
+			defer file.Close()
+			scanner := bufio.NewScanner(file)
+			for scanner.Scan() {
+				newArgs = append(newArgs, scanner.Text())
+			}
+		}
+	}
+	return newArgs
+}
+
+func jsonStreamToArray(r io.Reader, w io.Writer) error {
+	var objs []any
+	for dec := json.NewDecoder(r); dec.More(); {
+		var obj any
+		if err := dec.Decode(&obj); err != nil {
+			return fmt.Errorf("failed to decode json: %w", err)
+		}
+		objs = append(objs, obj)
+	}
+	if err := json.NewEncoder(w).Encode(objs); err != nil {
+		return fmt.Errorf("failed to encode json: %w", err)
+	}
+	return nil
+}
+
+func main() {
+	os.Args = loadArgs(os.Args)
+	var wrappedBinary = flag.String("go", "", "wrapped go binary")
+	var goRoot = flag.String("goroot", "", "go root")
+	var defaultGoOS = flag.String("default-goos", "", "default GOOS (if not set by env)")
+	var defaultGoArch = flag.String("default-goarch", "", "default GOARCH (if not set by env)")
+	var outputFile = flag.String("output", "", "file to redirect stdout to")
+	var convertJsonStream = flag.Bool("convert-json-stream", false, "convert json stream to array")
+	var gnuBuildID = flag.Bool("gnu-build-id", false, "rewrite .note.gnu.build-id with sha256 of the linked output (internal Go links only)")
+	flag.Parse()
+	unknownArgs := flag.Args()
+
+	if *wrappedBinary == "" {
+		log.Fatal("No wrapped binary specified")
+	}
+
+	absWrappedBinary, err := filepath.Abs(*wrappedBinary)
+	if err != nil {
+		log.Fatal("Failed to resolve wrapped binary: %s", err)
+	}
+
+	envs := make(map[string]string)
+	for _, e := range os.Environ() {
+		pair := strings.SplitN(e, "=", 2)
+		envs[pair[0]] = pair[1]
+	}
+
+	goroot := *goRoot
+	if goroot == "" {
+		goroot = envs["GOROOT"]
+	}
+
+	if os.Getenv("GOOS") == "" && *defaultGoOS != "" {
+		envs["GOOS"] = *defaultGoOS
+	}
+	if os.Getenv("GOARCH") == "" && *defaultGoArch != "" {
+		envs["GOARCH"] = *defaultGoArch
+	}
+
+	if goroot != "" {
+		absGoroot, err := filepath.Abs(goroot)
+		if err != nil {
+			log.Fatal("Failed to resolve GOROOT: %s", err)
+		}
+		envs["GOROOT"] = absGoroot
+	}
+
+	if buckScratchPath, ok := envs["BUCK_SCRATCH_PATH"]; ok {
+		absBuckScratchPath, err := filepath.Abs(buckScratchPath)
+		if err != nil {
+			log.Fatal("Failed to resolve BUCK_SCRATCH_PATH: %s", err)
+		}
+		envs["GOCACHE"] = absBuckScratchPath
+		envs["TMPDIR"] = absBuckScratchPath
+	}
+
+	cwd, err := os.Getwd()
+	if err != nil {
+		log.Fatal("Failed to get current working directory: %s", err)
+	}
+
+	for i, arg := range unknownArgs {
+		unknownArgs[i] = strings.ReplaceAll(arg, "%cwd%", cwd)
+	}
+
+	var output *os.File
+	if *outputFile == "" {
+		output = os.Stdout
+	} else {
+		output, err = os.Create(*outputFile)
+		if err != nil {
+			log.Fatalf("Error creating output file: %s", err)
+			os.Exit(1)
+		}
+		defer output.Close()
+	}
+
+	cmd := exec.Command(absWrappedBinary, unknownArgs...)
+
+	cmd.Env = make([]string, 0, len(envs)/2)
+	for k, v := range envs {
+		cmd.Env = append(cmd.Env, k+"="+v)
+	}
+
+	stdout, err := cmd.StdoutPipe()
+	if err != nil {
+		log.Fatalf("Error creating stdout pipe: %s", err)
+	}
+	defer stdout.Close()
+
+	cmd.Stderr = os.Stderr
+
+	if err := cmd.Start(); err != nil {
+		log.Fatalf("Error starting command: %s", err)
+	}
+
+	if *convertJsonStream {
+		if err := jsonStreamToArray(stdout, output); err != nil {
+			log.Fatalf("Error converting json stream: %s", err)
+		}
+	} else {
+		if _, err := io.Copy(output, stdout); err != nil {
+			log.Fatalf("Error copying stdout: %s", err)
+		}
+	}
+
+	err = cmd.Wait()
+	if err != nil {
+		exitCode := 1
+		if exitErr, ok := err.(*exec.ExitError); ok {
+			exitCode = exitErr.ExitCode()
+		}
+		fmt.Fprintln(os.Stderr, "Error running command:", err)
+		os.Exit(exitCode)
+	}
+
+	if *gnuBuildID {
+		out := outputPath(unknownArgs)
+		if out == "" {
+			log.Fatalf("--gnu-build-id set but no -o output found in linker args: %v", unknownArgs)
+		}
+		if err := setGNUBuildID(out); err != nil {
+			log.Fatalf("Error setting GNU build id: %s", err)
+		}
+	}
+}
diff --git a/buck2/prelude/go/tools/gobuckify/BUCK b/buck2/prelude/go/tools/gobuckify/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/BUCK
@@ -0,0 +1,18 @@
+# @oss-disable[end= ]: load("@fbcode_macros//build_defs:go_binary.bzl", "go_binary")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("golang")
+
+source_listing()
+
+prelude = native # @oss-enable
+go_binary = prelude.go_binary # @oss-enable
+
+go_binary(
+    name = "gobuckify",
+    srcs = ["main.go"],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//go/tools/gobuckify/lib:gobuckifylib",
+    ],
+)
diff --git a/buck2/prelude/go/tools/gobuckify/lib/BUCK b/buck2/prelude/go/tools/gobuckify/lib/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/lib/BUCK
@@ -0,0 +1,26 @@
+# @oss-disable[end= ]: load("@fbcode_macros//build_defs:go_library.bzl", "go_library")
+# @oss-disable[end= ]: load("@fbcode_macros//build_defs:go_unittest.bzl", "go_unittest")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("golang")
+
+source_listing()
+
+prelude = native # @oss-enable
+go_library = prelude.go_library # @oss-enable
+go_unittest = prelude.go_test # @oss-enable
+
+go_library(
+    name = "gobuckifylib",
+    srcs = glob(
+        ["*.go"],
+        exclude = ["*_test.go"],
+    ),
+    visibility = ["PUBLIC"],
+)
+
+go_unittest(
+    name = "gobuckifylib_test",
+    srcs = glob(["*_test.go"]),
+    target_under_test = ":gobuckifylib",
+)
diff --git a/buck2/prelude/go/tools/gobuckify/lib/buck.go b/buck2/prelude/go/tools/gobuckify/lib/buck.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/lib/buck.go
@@ -0,0 +1,182 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package gobuckifylib
+
+import (
+	"fmt"
+	"maps"
+	"slices"
+	"strings"
+)
+
+// OSDeps is a map of Buck-OS to ArchDeps
+type OSDeps struct {
+	OS       string
+	ArchDeps map[string]*ArchDeps
+}
+
+// ArchDeps is a map of Buck-Arch to CGO-specific dependency sets
+type ArchDeps struct {
+	Arch       string
+	CommonDeps *StringSet
+	CgoDeps    map[string]*StringSet
+}
+
+// BuckTarget is a buck-friendly representation of a go package
+type BuckTarget struct {
+	Name                 string
+	ImportPath           string
+	IsBinary             bool
+	EmbedFiles           StringSet
+	CommonDeps           []string
+	PlatformDeps         map[string]*OSDeps
+	TargetCompatibleWith map[string]map[string]*StringSet // os => arch => cgo constraints
+}
+
+// Normalise prepares BuckTarget to be written to a file:
+// - Moves common dependencies to CommonDeps out of PlatformDeps
+// - Removes empty PlatformDeps
+// - Removes TargetCompatibleWith if all configurations are compatible
+func (b *BuckTarget) Normalise(totalConfigurationNumber int) {
+	freqmap := make(map[string]int)
+	for _, osDeps := range b.PlatformDeps {
+		for _, archDeps := range osDeps.ArchDeps {
+			for _, deps := range archDeps.CgoDeps {
+				for dep := range *deps {
+					freqmap[dep]++
+				}
+			}
+		}
+	}
+
+	// If a dependency is used in all configurations, it can be moved to CommonDeps
+	for dep, freq := range freqmap {
+		if freq == totalConfigurationNumber {
+			b.CommonDeps = append(b.CommonDeps, dep)
+			for _, osDeps := range b.PlatformDeps {
+				for _, archDeps := range osDeps.ArchDeps {
+					for _, deps := range archDeps.CgoDeps {
+						deps.Remove(dep)
+					}
+				}
+			}
+		}
+	}
+
+	// Identical dependencies with and without cgo do not need a cgo select.
+	for _, osDeps := range b.PlatformDeps {
+		for _, archDeps := range osDeps.ArchDeps {
+			disabled, hasDisabled := archDeps.CgoDeps["prelude//go/constraints:cgo_enabled[false]"]
+			enabled, hasEnabled := archDeps.CgoDeps["prelude//go/constraints:cgo_enabled[true]"]
+			if hasDisabled && hasEnabled && disabled.Len() > 0 && maps.Equal(*disabled, *enabled) {
+				archDeps.CommonDeps = disabled
+				archDeps.CgoDeps = nil
+			}
+		}
+	}
+
+	// Remove empty PlatformDeps
+	for os, osDeps := range b.PlatformDeps {
+		for arch, archDeps := range osDeps.ArchDeps {
+			for cgo, deps := range archDeps.CgoDeps {
+				if deps.Len() == 0 {
+					delete(archDeps.CgoDeps, cgo)
+				}
+			}
+			if archDeps.CommonDeps == nil && len(archDeps.CgoDeps) == 0 {
+				delete(osDeps.ArchDeps, arch)
+			}
+		}
+		if len(osDeps.ArchDeps) == 0 {
+			delete(b.PlatformDeps, os)
+		}
+	}
+	slices.Sort(b.CommonDeps)
+
+	compatibleWithNumber := 0
+	for _, archMap := range b.TargetCompatibleWith {
+		for _, cgoConstraints := range archMap {
+			compatibleWithNumber += cgoConstraints.Len()
+		}
+	}
+
+	if compatibleWithNumber == totalConfigurationNumber {
+		b.TargetCompatibleWith = nil // all configurations are compatible
+	}
+}
+
+// BuckTargets is a map of buck targets keyed by import path
+type BuckTargets map[string]*BuckTarget
+
+// AddPackage adds a package to the buck targets map
+func (b *BuckTargets) AddPackage(pkg *Package, buckOS, buckArch string, cgoEnabled bool) {
+	// If a package with the same import path and configuration is added again, replace its data.
+	var target *BuckTarget
+	var ok bool
+	if target, ok = (*b)[pkg.ImportPath]; !ok {
+		target = &BuckTarget{
+			Name:                 TargetNameFromImportPath(pkg.ImportPath),
+			ImportPath:           pkg.ImportPath,
+			PlatformDeps:         make(map[string]*OSDeps),
+			EmbedFiles:           *NewSet(),
+			IsBinary:             pkg.Name == "main",
+			TargetCompatibleWith: make(map[string]map[string]*StringSet),
+		}
+		(*b)[pkg.ImportPath] = target
+	}
+
+	cgoConstraint := fmt.Sprintf("prelude//go/constraints:cgo_enabled[%t]", cgoEnabled)
+	target.EmbedFiles.AddList(pkg.EmbedFiles)
+	if target.TargetCompatibleWith[buckOS] == nil {
+		target.TargetCompatibleWith[buckOS] = make(map[string]*StringSet)
+	}
+	if target.TargetCompatibleWith[buckOS][buckArch] == nil {
+		target.TargetCompatibleWith[buckOS][buckArch] = NewSet()
+	}
+	target.TargetCompatibleWith[buckOS][buckArch].Add(cgoConstraint)
+
+	if target.PlatformDeps[buckOS] == nil {
+		target.PlatformDeps[buckOS] = &OSDeps{
+			OS:       buckOS,
+			ArchDeps: make(map[string]*ArchDeps),
+		}
+	}
+
+	if target.PlatformDeps[buckOS].ArchDeps[buckArch] == nil {
+		target.PlatformDeps[buckOS].ArchDeps[buckArch] = &ArchDeps{
+			Arch:    buckArch,
+			CgoDeps: make(map[string]*StringSet),
+		}
+	}
+	target.PlatformDeps[buckOS].ArchDeps[buckArch].CgoDeps[cgoConstraint] = NewSet()
+
+	for _, dep := range pkg.Imports {
+		if !strings.ContainsRune(dep, '.') {
+			continue // skip stdlib deps
+		}
+		target.PlatformDeps[buckOS].ArchDeps[buckArch].CgoDeps[cgoConstraint].Add(dep)
+	}
+}
+
+func TargetNameFromImportPath(importPath string) string {
+	lastSlash := strings.LastIndex(importPath, "/")
+	var targetName string
+	if lastSlash == -1 {
+		targetName = importPath
+	} else {
+		targetName = importPath[lastSlash+1:]
+	}
+	return targetName
+}
+
+func TargetLabelFromImportPath(targetLabelPrefix, importPath string) string {
+	return fmt.Sprintf("%s%s:%s", targetLabelPrefix, importPath, TargetNameFromImportPath(importPath))
+}
diff --git a/buck2/prelude/go/tools/gobuckify/lib/buck_test.go b/buck2/prelude/go/tools/gobuckify/lib/buck_test.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/lib/buck_test.go
@@ -0,0 +1,324 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package gobuckifylib
+
+import (
+	"reflect"
+	"testing"
+)
+
+func TestTargetNameFromImportPath(t *testing.T) {
+	tests := []struct {
+		name       string
+		importPath string
+		want       string
+	}{
+		{
+			name:       "simple path",
+			importPath: "github.com/example/pkg",
+			want:       "pkg",
+		},
+		{
+			name:       "no slashes",
+			importPath: "my-lib.com",
+			want:       "my-lib.com",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got := TargetNameFromImportPath(tt.importPath)
+			if got != tt.want {
+				t.Errorf("TargetNameFromImportPath(%q) = %q, want %q", tt.importPath, got, tt.want)
+			}
+		})
+	}
+}
+
+func TestTargetLabelFromImportPath(t *testing.T) {
+	want := "//prefix/github.com/example/pkg:pkg"
+	got := TargetLabelFromImportPath("//prefix/", "github.com/example/pkg")
+	if got != want {
+		t.Errorf("TargetLabelFromImportPath(%q, %q) = %q, want %q",
+			"//prefix/", "github.com/example/pkg", got, want)
+	}
+}
+
+func TestBuckTargetNormalise(t *testing.T) {
+	targets := make(BuckTargets)
+	for _, platform := range []struct {
+		os      string
+		imports []string
+	}{
+		{"linux", []string{"example.com/common/dep1", "example.com/common/dep2", "example.com/linux/dep"}},
+		{"darwin", []string{"example.com/common/dep1", "example.com/common/dep2", "example.com/darwin/dep"}},
+	} {
+		for _, cgoEnabled := range []bool{false, true} {
+			targets.AddPackage(&Package{
+				ImportPath: "github.com/example/test",
+				Imports:    platform.imports,
+			}, platform.os, "x86_64", cgoEnabled)
+		}
+	}
+
+	target := targets["github.com/example/test"]
+	target.Normalise(4)
+
+	if !reflect.DeepEqual(target.CommonDeps, []string{"example.com/common/dep1", "example.com/common/dep2"}) {
+		t.Errorf("CommonDeps = %v", target.CommonDeps)
+	}
+	if len(target.PlatformDeps) != 2 {
+		t.Errorf("PlatformDeps length = %d, want 2", len(target.PlatformDeps))
+	}
+	for os, want := range map[string]string{
+		"linux":  "example.com/linux/dep",
+		"darwin": "example.com/darwin/dep",
+	} {
+		archDeps := target.PlatformDeps[os].ArchDeps["x86_64"]
+		if archDeps.CommonDeps == nil {
+			t.Errorf("%s common architecture deps = nil", os)
+			continue
+		}
+		if got := archDeps.CommonDeps.SortedList(); !reflect.DeepEqual(got, []string{want}) {
+			t.Errorf("%s common architecture deps = %v, want %v", os, got, []string{want})
+		}
+		if len(archDeps.CgoDeps) != 0 {
+			t.Errorf("%s CGO deps = %v, want none", os, archDeps.CgoDeps)
+		}
+	}
+	if target.TargetCompatibleWith != nil {
+		t.Errorf("TargetCompatibleWith = %v, want nil", target.TargetCompatibleWith)
+	}
+
+	for _, cgoEnabled := range []bool{false, true} {
+		targets.AddPackage(&Package{
+			ImportPath: "github.com/example/empty",
+		}, "linux", "x86_64", cgoEnabled)
+	}
+	emptyTarget := targets["github.com/example/empty"]
+	emptyTarget.Normalise(2)
+	if len(emptyTarget.PlatformDeps) != 0 {
+		t.Errorf("PlatformDeps = %v, want none", emptyTarget.PlatformDeps)
+	}
+}
+
+func TestBuckTargetsAddPackage(t *testing.T) {
+	tests := []struct {
+		name          string
+		pkg           *Package
+		buckOS        string
+		buckArch      string
+		wantName      string
+		wantIsBinary  bool
+		wantDepsCount int
+	}{
+		{
+			name: "add library package",
+			pkg: &Package{
+				Name:       "testpkg",
+				ImportPath: "github.com/example/testpkg",
+				Imports:    []string{"github.com/example/dep1", "github.com/example/dep2", "fmt"},
+				EmbedFiles: []string{"embed1.txt", "embed2.txt"},
+			},
+			buckOS:        "linux",
+			buckArch:      "x86_64",
+			wantName:      "testpkg",
+			wantIsBinary:  false,
+			wantDepsCount: 2, // Only non-stdlib deps
+		},
+		{
+			name: "add binary package",
+			pkg: &Package{
+				Name:       "main",
+				ImportPath: "github.com/example/cmd",
+				Imports:    []string{"github.com/example/dep1", "fmt"},
+				EmbedFiles: []string{},
+			},
+			buckOS:        "darwin",
+			buckArch:      "arm64",
+			wantName:      "cmd",
+			wantIsBinary:  true,
+			wantDepsCount: 1, // Only non-stdlib deps
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			targets := make(BuckTargets)
+			targets.AddPackage(tt.pkg, tt.buckOS, tt.buckArch, true)
+
+			// Check if the package was added
+			target, exists := targets[tt.pkg.ImportPath]
+			if !exists {
+				t.Fatalf("Package not added to targets")
+			}
+
+			// Check basic properties
+			if target.Name != tt.wantName {
+				t.Errorf("Target name = %q, want %q", target.Name, tt.wantName)
+			}
+
+			if target.ImportPath != tt.pkg.ImportPath {
+				t.Errorf("Target import path = %q, want %q", target.ImportPath, tt.pkg.ImportPath)
+			}
+
+			if target.IsBinary != tt.wantIsBinary {
+				t.Errorf("Target IsBinary = %v, want %v", target.IsBinary, tt.wantIsBinary)
+			}
+
+			if !reflect.DeepEqual(target.EmbedFiles.SortedList(), tt.pkg.EmbedFiles) {
+				t.Errorf("Target EmbedFiles = %v, want %v", target.EmbedFiles.SortedList(), tt.pkg.EmbedFiles)
+			}
+
+			// Check platform deps
+			osDeps, exists := target.PlatformDeps[tt.buckOS]
+			if !exists {
+				t.Fatalf("OS deps not found for %s", tt.buckOS)
+			}
+
+			archDeps, exists := osDeps.ArchDeps[tt.buckArch]
+			if !exists {
+				t.Fatalf("Arch deps not found for %s", tt.buckArch)
+			}
+
+			deps, exists := archDeps.CgoDeps["prelude//go/constraints:cgo_enabled[true]"]
+			if !exists {
+				t.Fatal("CGO-enabled deps not found")
+			}
+
+			if deps.Len() != tt.wantDepsCount {
+				t.Errorf("Deps count = %d, want %d", deps.Len(), tt.wantDepsCount)
+			}
+
+			// Check TargetCompatibleWith
+			archMap, exists := target.TargetCompatibleWith[tt.buckOS]
+			if !exists {
+				t.Fatalf("TargetCompatibleWith not found for %s", tt.buckOS)
+			}
+
+			cgoConstraints, exists := archMap[tt.buckArch]
+			if !exists {
+				t.Fatalf("Arch %s not found in TargetCompatibleWith for OS %s", tt.buckArch, tt.buckOS)
+			}
+			if _, exists := (*cgoConstraints)["prelude//go/constraints:cgo_enabled[true]"]; !exists {
+				t.Error("CGO-enabled constraint not found in TargetCompatibleWith")
+			}
+		})
+	}
+}
+
+func TestAddPackageMultiplePlatforms(t *testing.T) {
+	targets := make(BuckTargets)
+	pkg := &Package{
+		ImportPath: "github.com/example/testpkg",
+		Imports:    []string{"github.com/example/dep1", "github.com/example/dep2"},
+	}
+
+	// Add the same package for multiple platforms
+	targets.AddPackage(pkg, "linux", "x86_64", true)
+	targets.AddPackage(pkg, "linux", "arm64", true)
+	targets.AddPackage(pkg, "darwin", "x86_64", true)
+
+	target, exists := targets[pkg.ImportPath]
+	if !exists {
+		t.Fatalf("Package not added to targets")
+	}
+
+	// Check that all platforms were added
+	if len(target.TargetCompatibleWith) != 2 {
+		t.Errorf("Expected 2 OS entries in TargetCompatibleWith, got %d", len(target.TargetCompatibleWith))
+	}
+
+	// Check linux architectures
+	linuxArchs, exists := target.TargetCompatibleWith["linux"]
+	if !exists {
+		t.Fatalf("Linux not found in TargetCompatibleWith")
+	}
+	if len(linuxArchs) != 2 {
+		t.Errorf("Expected 2 architectures for Linux, got %d", len(linuxArchs))
+	}
+
+	// Check darwin architectures
+	darwinArchs, exists := target.TargetCompatibleWith["darwin"]
+	if !exists {
+		t.Fatalf("Darwin not found in TargetCompatibleWith")
+	}
+	if len(darwinArchs) != 1 {
+		t.Errorf("Expected 1 architecture for Darwin, got %d", len(darwinArchs))
+	}
+
+	// Check platform deps
+	if len(target.PlatformDeps) != 2 {
+		t.Errorf("Expected 2 OS entries in PlatformDeps, got %d", len(target.PlatformDeps))
+	}
+
+	linuxDeps, exists := target.PlatformDeps["linux"]
+	if !exists {
+		t.Fatalf("Linux not found in PlatformDeps")
+	}
+	if len(linuxDeps.ArchDeps) != 2 {
+		t.Errorf("Expected 2 architectures for Linux in PlatformDeps, got %d", len(linuxDeps.ArchDeps))
+	}
+}
+
+func TestAddPackageMultipleCgoConfigurations(t *testing.T) {
+	const importPath = "github.com/example/testpkg"
+	targets := make(BuckTargets)
+	targets.AddPackage(&Package{
+		ImportPath: importPath,
+		Imports:    []string{"github.com/example/common", "github.com/example/nocgo"},
+	}, "linux", "x86_64", false)
+	targets.AddPackage(&Package{
+		ImportPath: importPath,
+		Imports:    []string{"github.com/example/common", "github.com/example/cgo"},
+	}, "linux", "x86_64", true)
+
+	target := targets[importPath]
+	target.Normalise(2)
+
+	if !reflect.DeepEqual(target.CommonDeps, []string{"github.com/example/common"}) {
+		t.Errorf("CommonDeps = %v", target.CommonDeps)
+	}
+	archDeps := target.PlatformDeps["linux"].ArchDeps["x86_64"]
+	got := archDeps.CgoDeps["prelude//go/constraints:cgo_enabled[false]"].SortedList()
+	if !reflect.DeepEqual(got, []string{"github.com/example/nocgo"}) {
+		t.Errorf("CGO-disabled deps = %v", got)
+	}
+	got = archDeps.CgoDeps["prelude//go/constraints:cgo_enabled[true]"].SortedList()
+	if !reflect.DeepEqual(got, []string{"github.com/example/cgo"}) {
+		t.Errorf("CGO-enabled deps = %v", got)
+	}
+	if target.TargetCompatibleWith != nil {
+		t.Errorf("TargetCompatibleWith = %v, want nil", target.TargetCompatibleWith)
+	}
+}
+
+func TestAddCgoOnlyPackage(t *testing.T) {
+	targets := make(BuckTargets)
+	targets.AddPackage(&Package{
+		ImportPath: "github.com/example/testpkg",
+		Imports:    []string{"github.com/example/cgo"},
+	}, "linux", "x86_64", true)
+
+	target := targets["github.com/example/testpkg"]
+	target.Normalise(2)
+
+	if len(target.CommonDeps) != 0 {
+		t.Errorf("CommonDeps = %v, want none", target.CommonDeps)
+	}
+	if target.TargetCompatibleWith == nil {
+		t.Fatal("TargetCompatibleWith = nil, want CGO-enabled compatibility")
+	}
+	cgoConstraints := target.TargetCompatibleWith["linux"]["x86_64"]
+	if got := cgoConstraints.SortedList(); !reflect.DeepEqual(got, []string{"prelude//go/constraints:cgo_enabled[true]"}) {
+		t.Errorf("CGO constraints = %v", got)
+	}
+}
diff --git a/buck2/prelude/go/tools/gobuckify/lib/config.go b/buck2/prelude/go/tools/gobuckify/lib/config.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/lib/config.go
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package gobuckifylib
+
+import (
+	"encoding/json"
+	"log/slog"
+	"os"
+)
+
+// BuckConfig option to generate BUCK files
+type BuckConfig struct {
+	Preambule             string `json:"preambule"`                // added to the top of each BUCK file, e.g. "# Generated by gobuckify"
+	LoadGoBinaryRule      string `json:"load_go_binary_rule"`      // load statement for alternative go_binary rule
+	LoadGoLibraryRule     string `json:"load_go_library_rule"`     // load statement for alternative go_library rule
+	GoBinaryRule          string `json:"go_binary_rule"`           // alternaive name for go_binary rule. Default: "go_binary"
+	GoLibraryRule         string `json:"go_library_rule"`          // alternaive name for go_library rule. Default: "go_library"
+	DepsTargetLabelPrefix string `json:"deps_target_label_prefix"` // prefix for dependencies, if provided deps formatted as "{prefix}{import}:{import_suffix}"
+	GenerateEmbedSrcs     bool   `json:"generate_embed_srcs"`      // generate srcs for go:embed directives (sadly not open-sourced yet)
+	DepsAttr              string `json:"deps_attr"`                // custom attribute for dependencies e.g. "go_external_deps". Default: "deps"
+}
+
+// PlatformConfig mapping between goos/goarch and buck os/arch
+type PlatformConfig struct {
+	GoOS     string `json:"go_os"`
+	GoArch   string `json:"go_arch"`
+	BuckOS   string `json:"buck_os"`
+	BuckArch string `json:"buck_arch"`
+}
+
+// Config is the configuration for buckify
+type Config struct {
+	Buck        BuckConfig       `json:"buck"`         // options for BUCK files
+	Platforms   []PlatformConfig `json:"platforms"`    // list of platforms we query `go list`
+	DefaultTags []string         `json:"default_tags"` // list of tags we allways pass to `go list`
+}
+
+// FromJSON reads a config from a JSON file
+func FromJSON(filename string) (*Config, error) {
+	var c Config
+	data, err := os.ReadFile(filename)
+	if err != nil {
+		return nil, err
+	}
+	err = json.Unmarshal(data, &c)
+	if err != nil {
+		return nil, err
+	}
+	ensureDefaultValues(&c)
+	return &c, nil
+}
+
+func ensureDefaultValues(c *Config) {
+	if c.Buck.GoBinaryRule == "" {
+		c.Buck.GoBinaryRule = "go_binary"
+	}
+	if c.Buck.GoLibraryRule == "" {
+		c.Buck.GoLibraryRule = "go_library"
+	}
+	if c.Buck.DepsAttr == "" {
+		c.Buck.DepsAttr = "deps"
+	}
+	if c.Buck.DepsTargetLabelPrefix == "" {
+		slog.Info("buck.deps_target_label_prefix is not set, dependencies will be formatted as raw import paths")
+	}
+}
diff --git a/buck2/prelude/go/tools/gobuckify/lib/golist.go b/buck2/prelude/go/tools/gobuckify/lib/golist.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/lib/golist.go
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package gobuckifylib
+
+import (
+	"bufio"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"log/slog"
+	"os"
+	"os/exec"
+	"slices"
+	"strings"
+	"sync"
+)
+
+// Module represents a Go module from go list output
+type Module struct {
+	Path    string `json:"Path"`
+	Version string `json:"Version"`
+}
+
+// Package is a subset of the fields of the golist output
+type Package struct {
+	Name       string
+	ImportPath string
+	Imports    []string
+	EmbedFiles []string
+	Standard   bool
+	Module     *Module
+}
+
+func QueryGoList(
+	workDir, rootModuleName, goOS, goArch string,
+	cgoEnabled bool,
+	extraArgs ...string,
+) (chan *Package, chan error) {
+	pkgChan := make(chan *Package, 1000) // 1000 is a guess, but should be enough
+	errChan := make(chan error, 1)
+	go func() {
+		defer close(pkgChan)
+		defer close(errChan)
+		cmdArgs := slices.Concat(
+			[]string{"buck2", "run", "toolchains//:go[go]", "--", "list", "-C", workDir, "-e", "-json=Name,ImportPath,Imports,EmbedFiles,Standard,Module"},
+			extraArgs,
+			[]string{"all"},
+		)
+		cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
+		// Set GOOS/GOARCH so `go list` applies each target platform's build constraints:
+		// filename suffixes (e.g. `*_darwin.go`) and `//go:build` expressions (e.g.
+		// `!linux`). Passing the platform only via `-tags` is insufficient -- the host's
+		// own GOOS/GOARCH tags stay set, so negative and file-suffix constraints are
+		// mis-evaluated and platform-specific deps get silently dropped.
+		cgoEnabledValue := "0"
+		if cgoEnabled {
+			cgoEnabledValue = "1"
+		}
+		cmd.Env = append(os.Environ(), "CGO_ENABLED="+cgoEnabledValue, "GOOS="+goOS, "GOARCH="+goArch)
+
+		stdout, err := cmd.StdoutPipe()
+		if err != nil {
+			errChan <- fmt.Errorf("failed to get stdout pipe: %w", err)
+			return
+		}
+
+		stderr, err := cmd.StderrPipe()
+		if err != nil {
+			errChan <- fmt.Errorf("failed to get stderr pipe: %w", err)
+			return
+		}
+
+		if err := cmd.Start(); err != nil {
+			errChan <- fmt.Errorf("failed to start go list: %w", err)
+			return
+		}
+
+		for dec := json.NewDecoder(stdout); dec.More(); {
+			var pkg Package
+			if err := dec.Decode(&pkg); err != nil {
+				errChan <- fmt.Errorf("failed to decode json: %w", err)
+				return
+			}
+			if pkg.Standard {
+				continue // skip standard library packages
+			}
+			if pkg.Module == nil {
+				continue // that's not a ligit third-party package
+			}
+			if strings.HasPrefix(pkg.ImportPath, rootModuleName) {
+				continue // skip the root module packages
+			}
+			pkgChan <- &pkg
+		}
+
+		stderrBytes, err := io.ReadAll(stderr)
+		if err != nil {
+			errChan <- fmt.Errorf("failed to read stderr: %w", err)
+			return
+		}
+
+		if err := cmd.Wait(); err != nil {
+			fmt.Fprintln(os.Stderr, string(stderrBytes))
+			errChan <- fmt.Errorf("failed to wait for go list: %w", err)
+		}
+	}()
+
+	return pkgChan, errChan
+}
+
+func ReadModuleName(path string) (string, error) {
+	f, err := os.Open(path)
+	if err != nil {
+		return "", fmt.Errorf("failed to open %s: %w", path, err)
+	}
+	defer f.Close()
+
+	reader := bufio.NewReader(f)
+	line, err := reader.ReadString('\n')
+	if err != nil && !errors.Is(err, io.EOF) {
+		return "", fmt.Errorf("failed to read first line: %w", err)
+	}
+	parts := strings.SplitN(strings.TrimSpace(line), " ", 2)
+	if len(parts) != 2 {
+		return "", fmt.Errorf("failed to parse first line: %s", line)
+	}
+	return parts[1], nil
+}
+
+// CollectPackagesResult contains the results of collecting packages from go list
+type CollectPackagesResult struct {
+	BuckTargets BuckTargets
+	Modules     map[string]*Module
+}
+
+// CollectPackages queries go list for all platform and CGO configurations and
+// collects packages into BuckTargets and unique Modules.
+func CollectPackages(cfg *Config, thirdPartyDir, rootModuleName string) (*CollectPackagesResult, error) {
+	type result struct {
+		pkg        *Package
+		buckOS     string
+		buckArch   string
+		cgoEnabled bool
+	}
+
+	results := make(chan *result, 2*1000*len(cfg.Platforms))
+	mainErrChan := make(chan error)
+
+	// Limit concurrency to avoid OOMs as `go list` can use a lot of memory
+	semaphore := make(chan struct{}, 10)
+
+	var wg sync.WaitGroup
+	for _, p := range cfg.Platforms {
+		for _, cgoEnabled := range []bool{false, true} {
+			wg.Go(func() {
+				semaphore <- struct{}{}
+				defer func() { <-semaphore }()
+
+				// GOOS/GOARCH and CGO_ENABLED are passed via the environment (see
+				// QueryGoList), so `go list` evaluates each configuration correctly.
+				pkgChan, errChan := QueryGoList(
+					thirdPartyDir, rootModuleName, p.GoOS, p.GoArch, cgoEnabled,
+					fmt.Sprintf("-tags=%s", strings.Join(cfg.DefaultTags, ",")),
+				)
+				pkgCount := 0
+				for pkg := range pkgChan {
+					pkgCount++
+					results <- &result{pkg: pkg, buckOS: p.BuckOS, buckArch: p.BuckArch, cgoEnabled: cgoEnabled}
+				}
+				slog.Info("Found packages", "count", pkgCount, "os", p.GoOS, "arch", p.GoArch, "cgo_enabled", cgoEnabled)
+				for err := range errChan {
+					mainErrChan <- fmt.Errorf("error querying golist for %v with cgo_enabled=%t: %w", p, cgoEnabled, err)
+				}
+			})
+		}
+	}
+
+	go func() {
+		wg.Wait()
+		close(results)
+		close(mainErrChan)
+	}()
+
+	buckTargets := make(BuckTargets)
+	modules := make(map[string]*Module)
+
+	resultsClosed, mainErrChanClosed, hadErrors := false, false, false
+	for {
+		if resultsClosed && mainErrChanClosed {
+			break
+		}
+		select {
+		case res, ok := <-results:
+			if !ok {
+				resultsClosed = true
+				continue
+			}
+			buckTargets.AddPackage(res.pkg, res.buckOS, res.buckArch, res.cgoEnabled)
+			if res.pkg.Module != nil {
+				modules[res.pkg.Module.Path] = res.pkg.Module
+			}
+		case err, ok := <-mainErrChan:
+			if !ok {
+				mainErrChanClosed = true
+				continue
+			}
+			slog.Error("Error querying golist", "err", err)
+			hadErrors = true
+		}
+	}
+
+	if hadErrors {
+		return nil, fmt.Errorf("errors occurred while collecting packages")
+	}
+
+	slog.Info("Packages collected", "count", len(buckTargets))
+	slog.Info("Modules collected", "count", len(modules))
+
+	return &CollectPackagesResult{
+		BuckTargets: buckTargets,
+		Modules:     modules,
+	}, nil
+}
diff --git a/buck2/prelude/go/tools/gobuckify/lib/render.go b/buck2/prelude/go/tools/gobuckify/lib/render.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/lib/render.go
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package gobuckifylib
+
+import (
+	"fmt"
+	"log/slog"
+	"os"
+	"path/filepath"
+	"sync"
+	"text/template"
+)
+
+var TargetTemplate = `
+{{- .Config.Preambule }}
+{{- if .Target.IsBinary }}
+{{- .Config.LoadGoBinaryRule}}
+{{- else }}
+{{- .Config.LoadGoLibraryRule}}
+{{- end }}
+{{- if .Target.IsBinary }}{{ .Config.GoBinaryRule}}{{ else }}{{ .Config.GoLibraryRule}}{{ end }}(
+    name = "{{.Target.Name}}",
+    package_name = "{{.Target.ImportPath}}",
+    srcs = native.glob(["*.go", "*.s", "*.h", "*.c", "*.cc", "*.cpp", "*.S"]),
+    header_namespace = "",
+    {{- if or .Target.CommonDeps .Target.PlatformDeps }}
+    {{.Config.DepsAttr}} = [
+        {{- range .Target.CommonDeps }}
+        {{- if $.Config.DepsTargetLabelPrefix }}
+        "{{TargetLabelFromImportPath $.Config.DepsTargetLabelPrefix .}}",
+        {{- else }}
+        "{{.}}",
+        {{- end }}
+        {{- end }}
+    ]{{ if .Target.PlatformDeps }} + select({
+        "DEFAULT": [],
+        {{- range $os, $osDeps := .Target.PlatformDeps }}
+        "{{ $os }}": select({
+            "DEFAULT": [],
+            {{- range $arch, $archDeps := $osDeps.ArchDeps }}
+            "{{ $arch }}": {{ if $archDeps.CommonDeps }}[
+                {{- range $archDeps.CommonDeps.SortedList }}
+                {{- if $.Config.DepsTargetLabelPrefix }}
+                "{{TargetLabelFromImportPath $.Config.DepsTargetLabelPrefix .}}",
+                {{- else }}
+                "{{.}}",
+                {{- end }}
+                {{- end }}
+            ]{{ else }}select({
+                "DEFAULT": [],
+                {{- range $cgo, $deps := $archDeps.CgoDeps }}
+                "{{ $cgo }}": [
+                    {{- range $deps.SortedList }}
+                    {{- if $.Config.DepsTargetLabelPrefix }}
+                    "{{TargetLabelFromImportPath $.Config.DepsTargetLabelPrefix .}}",
+                    {{- else }}
+                    "{{.}}",
+                    {{- end }}
+                    {{- end }}
+                ],
+                {{- end }}
+            }){{ end }},
+            {{- end }}
+        }),
+        {{- end }}
+    }){{ end }},
+    {{- end }}
+    {{- if and .Target.EmbedFiles .Config.GenerateEmbedSrcs }}
+    embed_srcs = [
+        {{- range .Target.EmbedFiles.SortedList }}
+        "{{.}}",
+        {{- end }}
+    ],
+    {{- end }}
+    {{- if .Target.TargetCompatibleWith }}
+    target_compatible_with = select({
+        "DEFAULT": ["config//:none"],
+        {{- range $os, $archMap := .Target.TargetCompatibleWith }}
+        "{{ $os }}": select({
+            "DEFAULT": ["config//:none"],
+            {{- range $arch, $cgoConstraints := $archMap }}
+            "{{ $arch }}": select({
+                "DEFAULT": ["config//:none"],
+                {{- range $cgoConstraints.SortedList }}
+                "{{.}}": [],
+                {{- end }}
+            }),
+            {{- end }}
+        }),
+        {{- end }}
+    }),
+    {{- end }}
+    visibility = ["PUBLIC"],
+)
+`
+
+type TemplateData struct {
+	Config BuckConfig
+	Target *BuckTarget
+}
+
+func RenderBuckFiles(cfg *Config, thirdPartyDir string, buckTargets BuckTargets) error {
+	tmpl1 := template.New("buck")
+	tmpl1.Funcs(template.FuncMap{
+		"TargetLabelFromImportPath": TargetLabelFromImportPath,
+	})
+	tmpl1 = template.Must(tmpl1.Parse(TargetTemplate))
+
+	errors := make(chan error)
+	var wg sync.WaitGroup
+	sem := make(chan struct{}, 50) // limit IO concurrency to some reasonable number
+	for _, target := range buckTargets {
+		wg.Go(func() {
+			target.Normalise(2 * len(cfg.Platforms))
+
+			// Acquire semaphore before doing IO
+			sem <- struct{}{}
+			defer func() { <-sem }()
+
+			buckFile := filepath.Join(thirdPartyDir, "vendor", target.ImportPath, "BUCK")
+			f, err := os.Create(buckFile)
+			if err != nil {
+				errors <- fmt.Errorf("can't create BUCK file: %w", err)
+				return
+			}
+			defer f.Close()
+
+			if err := tmpl1.Execute(f, TemplateData{Config: cfg.Buck, Target: target}); err != nil {
+				errors <- fmt.Errorf("can't execute template: %w", err)
+			}
+		})
+	}
+
+	go func() {
+		wg.Wait()
+		close(errors)
+	}()
+
+	var lastErr error
+	for err := range errors {
+		slog.Error("RenderBuckFiles", "err", err)
+		lastErr = err
+	}
+
+	return lastErr
+}
diff --git a/buck2/prelude/go/tools/gobuckify/lib/render_test.go b/buck2/prelude/go/tools/gobuckify/lib/render_test.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/lib/render_test.go
@@ -0,0 +1,276 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package gobuckifylib
+
+import (
+	"strings"
+	"testing"
+	"text/template"
+)
+
+func TestTargetTemplate(t *testing.T) {
+	tests := []struct {
+		name           string
+		config         BuckConfig
+		target         *BuckTarget
+		expectedOutput string
+	}{
+		{
+			name: "binary target with common deps and no target label prefix",
+			config: BuckConfig{
+				Preambule:         "# Generated by gobuckify\n",
+				LoadGoBinaryRule:  "load(\":defs.bzl\", \"go_binary\")\n",
+				GoBinaryRule:      "go_binary",
+				DepsAttr:          "go_external_deps",
+				GenerateEmbedSrcs: true,
+			},
+			target: &BuckTarget{
+				Name:       "test_binary",
+				ImportPath: "github.com/example/test_binary",
+				IsBinary:   true,
+				EmbedFiles: *NewFromList([]string{"embed1.txt", "embed2.txt"}),
+				CommonDeps: []string{"github.com/example/dep1", "github.com/example/dep2"},
+			},
+			expectedOutput: `
+# Generated by gobuckify
+load(":defs.bzl", "go_binary")
+go_binary(
+    name = "test_binary",
+    package_name = "github.com/example/test_binary",
+    srcs = native.glob(["*.go", "*.s", "*.h", "*.c", "*.cc", "*.cpp", "*.S"]),
+    header_namespace = "",
+    go_external_deps = [
+        "github.com/example/dep1",
+        "github.com/example/dep2",
+    ],
+    embed_srcs = [
+        "embed1.txt",
+        "embed2.txt",
+    ],
+    visibility = ["PUBLIC"],
+)`,
+		},
+		{
+			name: "library target with platform and cgo deps",
+			config: BuckConfig{
+				Preambule:             "# Generated by gobuckify\n",
+				LoadGoLibraryRule:     "load(\":defs.bzl\", \"go_library\")\n",
+				GoLibraryRule:         "go_library",
+				DepsAttr:              "deps",
+				DepsTargetLabelPrefix: "//third-party/go/",
+			},
+			target: &BuckTarget{
+				Name:       "test_lib",
+				ImportPath: "github.com/example/test_lib",
+				CommonDeps: []string{"github.com/example/common_dep"},
+				PlatformDeps: map[string]*OSDeps{
+					"linux": {
+						OS: "linux",
+						ArchDeps: map[string]*ArchDeps{
+							"x86_64": {
+								Arch: "x86_64",
+								CgoDeps: map[string]*StringSet{
+									"prelude//go/constraints:cgo_enabled[false]": NewFromList([]string{
+										"github.com/example/nocgo_dep",
+									}),
+									"prelude//go/constraints:cgo_enabled[true]": NewFromList([]string{
+										"github.com/example/cgo_dep",
+									}),
+								},
+							},
+						},
+					},
+				},
+			},
+			expectedOutput: `
+# Generated by gobuckify
+load(":defs.bzl", "go_library")
+go_library(
+    name = "test_lib",
+    package_name = "github.com/example/test_lib",
+    srcs = native.glob(["*.go", "*.s", "*.h", "*.c", "*.cc", "*.cpp", "*.S"]),
+    header_namespace = "",
+    deps = [
+        "//third-party/go/github.com/example/common_dep:common_dep",
+    ] + select({
+        "DEFAULT": [],
+        "linux": select({
+            "DEFAULT": [],
+            "x86_64": select({
+                "DEFAULT": [],
+                "prelude//go/constraints:cgo_enabled[false]": [
+                    "//third-party/go/github.com/example/nocgo_dep:nocgo_dep",
+                ],
+                "prelude//go/constraints:cgo_enabled[true]": [
+                    "//third-party/go/github.com/example/cgo_dep:cgo_dep",
+                ],
+            }),
+        }),
+    }),
+    visibility = ["PUBLIC"],
+)`,
+		},
+		{
+			name: "library target with no deps",
+			config: BuckConfig{
+				Preambule:         "# Generated by gobuckify\n",
+				LoadGoLibraryRule: "load(\":defs.bzl\", \"go_library\")\n",
+				GoLibraryRule:     "go_library",
+			},
+			target: &BuckTarget{
+				Name:       "simple_lib",
+				ImportPath: "github.com/example/simple_lib",
+			},
+			expectedOutput: `
+# Generated by gobuckify
+load(":defs.bzl", "go_library")
+go_library(
+    name = "simple_lib",
+    package_name = "github.com/example/simple_lib",
+    srcs = native.glob(["*.go", "*.s", "*.h", "*.c", "*.cc", "*.cpp", "*.S"]),
+    header_namespace = "",
+    visibility = ["PUBLIC"],
+)`,
+		},
+		{
+			name: "library target with multiple platforms and cgo compatibility",
+			config: BuckConfig{
+				Preambule:             "# Generated by gobuckify\n",
+				LoadGoLibraryRule:     "load(\":defs.bzl\", \"go_library\")\n",
+				GoLibraryRule:         "go_library",
+				DepsAttr:              "deps",
+				DepsTargetLabelPrefix: "//third-party/go/",
+			},
+			target: &BuckTarget{
+				Name:       "platform_lib",
+				ImportPath: "github.com/example/platform_lib",
+				PlatformDeps: map[string]*OSDeps{
+					"linux": {
+						OS: "linux",
+						ArchDeps: map[string]*ArchDeps{
+							"x86_64": {
+								Arch:       "x86_64",
+								CommonDeps: NewFromList([]string{"github.com/example/linux_x86_dep"}),
+							},
+							"arm64": {
+								Arch: "arm64",
+								CgoDeps: map[string]*StringSet{
+									"prelude//go/constraints:cgo_enabled[true]": NewFromList([]string{
+										"github.com/example/linux_arm_dep",
+									}),
+								},
+							},
+						},
+					},
+					"darwin": {
+						OS: "darwin",
+						ArchDeps: map[string]*ArchDeps{
+							"x86_64": {
+								Arch: "x86_64",
+								CgoDeps: map[string]*StringSet{
+									"prelude//go/constraints:cgo_enabled[true]": NewFromList([]string{
+										"github.com/example/darwin_dep",
+									}),
+								},
+							},
+						},
+					},
+				},
+				TargetCompatibleWith: map[string]map[string]*StringSet{
+					"linux": {
+						"x86_64": NewFromList([]string{"prelude//go/constraints:cgo_enabled[true]"}),
+						"arm64":  NewFromList([]string{"prelude//go/constraints:cgo_enabled[true]"}),
+					},
+					"darwin": {
+						"x86_64": NewFromList([]string{"prelude//go/constraints:cgo_enabled[true]"}),
+					},
+				},
+			},
+			expectedOutput: `
+# Generated by gobuckify
+load(":defs.bzl", "go_library")
+go_library(
+    name = "platform_lib",
+    package_name = "github.com/example/platform_lib",
+    srcs = native.glob(["*.go", "*.s", "*.h", "*.c", "*.cc", "*.cpp", "*.S"]),
+    header_namespace = "",
+    deps = [
+    ] + select({
+        "DEFAULT": [],
+        "darwin": select({
+            "DEFAULT": [],
+            "x86_64": select({
+                "DEFAULT": [],
+                "prelude//go/constraints:cgo_enabled[true]": [
+                    "//third-party/go/github.com/example/darwin_dep:darwin_dep",
+                ],
+            }),
+        }),
+        "linux": select({
+            "DEFAULT": [],
+            "arm64": select({
+                "DEFAULT": [],
+                "prelude//go/constraints:cgo_enabled[true]": [
+                    "//third-party/go/github.com/example/linux_arm_dep:linux_arm_dep",
+                ],
+            }),
+            "x86_64": [
+                "//third-party/go/github.com/example/linux_x86_dep:linux_x86_dep",
+            ],
+        }),
+    }),
+    target_compatible_with = select({
+        "DEFAULT": ["config//:none"],
+        "darwin": select({
+            "DEFAULT": ["config//:none"],
+            "x86_64": select({
+                "DEFAULT": ["config//:none"],
+                "prelude//go/constraints:cgo_enabled[true]": [],
+            }),
+        }),
+        "linux": select({
+            "DEFAULT": ["config//:none"],
+            "arm64": select({
+                "DEFAULT": ["config//:none"],
+                "prelude//go/constraints:cgo_enabled[true]": [],
+            }),
+            "x86_64": select({
+                "DEFAULT": ["config//:none"],
+                "prelude//go/constraints:cgo_enabled[true]": [],
+            }),
+        }),
+    }),
+    visibility = ["PUBLIC"],
+)`,
+		},
+	}
+
+	tmpl := template.Must(template.New("test").Funcs(template.FuncMap{
+		"TargetLabelFromImportPath": TargetLabelFromImportPath,
+	}).Parse(TargetTemplate))
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			var buf strings.Builder
+			err := tmpl.Execute(&buf, TemplateData{
+				Config: tt.config,
+				Target: tt.target,
+			})
+			if err != nil {
+				t.Fatalf("Template execution failed: %v", err)
+			}
+
+			if got, want := strings.TrimSpace(buf.String()), strings.TrimSpace(tt.expectedOutput); got != want {
+				t.Errorf("Template output mismatch.\nExpected:\n%s\n\nGot:\n%s", want, got)
+			}
+		})
+	}
+}
diff --git a/buck2/prelude/go/tools/gobuckify/lib/set.go b/buck2/prelude/go/tools/gobuckify/lib/set.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/lib/set.go
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package gobuckifylib
+
+import "slices"
+
+type StringSet map[string]struct{}
+
+func NewSet() *StringSet {
+	newSet := make(StringSet)
+	return &newSet
+}
+
+func NewFromList(vs []string) *StringSet {
+	newSet := NewSet()
+	newSet.AddList(vs)
+	return newSet
+}
+
+func (s *StringSet) Add(v string) {
+	(*s)[v] = struct{}{}
+}
+
+func (s *StringSet) AddList(vs []string) {
+	for _, v := range vs {
+		(*s)[v] = struct{}{}
+	}
+}
+
+func (s *StringSet) Remove(v string) {
+	delete((*s), v)
+}
+
+func (s *StringSet) Len() int {
+	return len((*s))
+}
+
+func (s *StringSet) SortedList() []string {
+	result := make([]string, 0, len((*s)))
+	for k := range *s {
+		result = append(result, k)
+	}
+	slices.Sort(result)
+	return result
+}
diff --git a/buck2/prelude/go/tools/gobuckify/lib/set_test.go b/buck2/prelude/go/tools/gobuckify/lib/set_test.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/lib/set_test.go
@@ -0,0 +1,185 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package gobuckifylib
+
+import (
+	"reflect"
+	"testing"
+)
+
+func TestNewSet(t *testing.T) {
+	s := NewSet()
+	if s == nil {
+		t.Fatal("NewSet() returned nil")
+	}
+	if len(*s) != 0 {
+		t.Errorf("Expected empty set, got set with %d elements", len(*s))
+	}
+}
+
+func TestAdd(t *testing.T) {
+	s := NewSet()
+
+	// Add a single element
+	s.Add("test1")
+	if len(*s) != 1 {
+		t.Errorf("Expected set with 1 element, got %d", len(*s))
+	}
+	if _, exists := (*s)["test1"]; !exists {
+		t.Errorf("Element 'test1' not found in set after Add")
+	}
+
+	// Add the same element again (should not increase size)
+	s.Add("test1")
+	if len(*s) != 1 {
+		t.Errorf("Expected set with 1 element after adding duplicate, got %d", len(*s))
+	}
+
+	// Add a different element
+	s.Add("test2")
+	if len(*s) != 2 {
+		t.Errorf("Expected set with 2 elements, got %d", len(*s))
+	}
+	if _, exists := (*s)["test2"]; !exists {
+		t.Errorf("Element 'test2' not found in set after Add")
+	}
+}
+
+func TestRemove(t *testing.T) {
+	s := NewSet()
+
+	// Add and then remove an element
+	s.Add("test1")
+	s.Remove("test1")
+	if len(*s) != 0 {
+		t.Errorf("Expected empty set after removing element, got %d elements", len(*s))
+	}
+	if _, exists := (*s)["test1"]; exists {
+		t.Errorf("Element 'test1' still found in set after Remove")
+	}
+
+	// Remove an element that doesn't exist (should not error)
+	s.Remove("nonexistent")
+	if len(*s) != 0 {
+		t.Errorf("Expected empty set after removing nonexistent element, got %d elements", len(*s))
+	}
+
+	// Add multiple elements and remove one
+	s.Add("test1")
+	s.Add("test2")
+	s.Remove("test1")
+	if len(*s) != 1 {
+		t.Errorf("Expected set with 1 element after removing one of two elements, got %d", len(*s))
+	}
+	if _, exists := (*s)["test1"]; exists {
+		t.Errorf("Element 'test1' still found in set after Remove")
+	}
+	if _, exists := (*s)["test2"]; !exists {
+		t.Errorf("Element 'test2' not found in set after removing different element")
+	}
+}
+
+func TestLen(t *testing.T) {
+	s := NewSet()
+
+	// Empty set
+	if s.Len() != 0 {
+		t.Errorf("Expected length 0 for empty set, got %d", s.Len())
+	}
+
+	// Set with one element
+	s.Add("test1")
+	if s.Len() != 1 {
+		t.Errorf("Expected length 1 after adding element, got %d", s.Len())
+	}
+
+	// Set with multiple elements
+	s.Add("test2")
+	s.Add("test3")
+	if s.Len() != 3 {
+		t.Errorf("Expected length 3 after adding three elements, got %d", s.Len())
+	}
+
+	// After removing an element
+	s.Remove("test2")
+	if s.Len() != 2 {
+		t.Errorf("Expected length 2 after removing element, got %d", s.Len())
+	}
+}
+
+func TestSortedList(t *testing.T) {
+	s := NewSet()
+
+	// Empty set
+	list := s.SortedList()
+	if len(list) != 0 {
+		t.Errorf("Expected empty list for empty set, got list with %d elements", len(list))
+	}
+
+	// Set with one element
+	s.Add("test1")
+	list = s.SortedList()
+	expected := []string{"test1"}
+	if !reflect.DeepEqual(list, expected) {
+		t.Errorf("Expected %v, got %v", expected, list)
+	}
+
+	// Set with multiple elements (added in non-alphabetical order)
+	s.Add("test3")
+	s.Add("test2")
+	list = s.SortedList()
+	expected = []string{"test1", "test2", "test3"}
+	if !reflect.DeepEqual(list, expected) {
+		t.Errorf("Expected %v, got %v", expected, list)
+	}
+
+	// Verify the original set is not modified
+	if s.Len() != 3 {
+		t.Errorf("Expected set to still have 3 elements, got %d", s.Len())
+	}
+}
+
+func TestSetOperations(t *testing.T) {
+	// Test multiple operations together
+	s := NewSet()
+
+	// Add elements
+	s.Add("apple")
+	s.Add("banana")
+	s.Add("cherry")
+
+	// Verify length
+	if s.Len() != 3 {
+		t.Errorf("Expected length 3, got %d", s.Len())
+	}
+
+	// Verify sorted list
+	expected := []string{"apple", "banana", "cherry"}
+	list := s.SortedList()
+	if !reflect.DeepEqual(list, expected) {
+		t.Errorf("Expected %v, got %v", expected, list)
+	}
+
+	// Remove an element
+	s.Remove("banana")
+
+	// Verify length after removal
+	if s.Len() != 2 {
+		t.Errorf("Expected length 2 after removal, got %d", s.Len())
+	}
+
+	// Verify sorted list after removal
+	expected = []string{"apple", "cherry"}
+	list = s.SortedList()
+	if !reflect.DeepEqual(list, expected) {
+		t.Errorf("Expected %v, got %v", expected, list)
+	}
+}
diff --git a/buck2/prelude/go/tools/gobuckify/main.go b/buck2/prelude/go/tools/gobuckify/main.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gobuckify/main.go
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package main
+
+import (
+	"fmt"
+	"log/slog"
+	"os"
+	"path/filepath"
+
+	lib "go/tools/gobuckify/lib"
+)
+
+func main() {
+	if len(os.Args[1:]) != 1 {
+		fmt.Println("Usage: gobuckify <path-third-party-dir>")
+		os.Exit(1)
+	}
+
+	thirdPartyDir := os.Args[1]
+
+	goMod := filepath.Join(thirdPartyDir, "go.mod")
+	rootModuleName, err := lib.ReadModuleName(goMod)
+	if err != nil {
+		slog.Error("Error reading go.mod", "err", err)
+		os.Exit(1)
+	}
+
+	cfg, err := lib.FromJSON(filepath.Join(thirdPartyDir, "gobuckify.json"))
+	if err != nil {
+		slog.Error("Error reading config gobuckify.json", "err", err)
+		os.Exit(1)
+	}
+
+	result, err := lib.CollectPackages(cfg, thirdPartyDir, rootModuleName)
+	if err != nil {
+		slog.Error("Error collecting packages", "err", err)
+		os.Exit(1)
+	}
+
+	slog.Info("Rendering BUCK files")
+	if err := lib.RenderBuckFiles(cfg, thirdPartyDir, result.BuckTargets); err != nil {
+		slog.Error("Error rendering BUCK files", "err", err)
+		os.Exit(1)
+	}
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/BUCK b/buck2/prelude/go/tools/gopackagesdriver/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/BUCK
@@ -0,0 +1,16 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("golang")
+
+source_listing()
+
+prelude = native
+
+prelude.go_binary(
+    name = "gopackagesdriver",
+    srcs = ["main.go"],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//go/tools/gopackagesdriver/driver:driver",
+    ],
+)
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver.bxl b/buck2/prelude/go/tools/gopackagesdriver/driver.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver.bxl
@@ -0,0 +1,360 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//go:cgo_builder.bzl", "project_go_and_c_files")
+load("@prelude//go:go_list.bzl", "GoListOut", "parse_go_list_out")
+load("@prelude//go:packages.bzl", "GoPackageInfo")
+load(
+    "@prelude//go:toolchain.bzl",
+    "GoToolchainInfo",
+    "GoVersion",  # @unused used as a type
+)
+load("@prelude//utils:utils.bzl", "flatten")
+
+importable_go_rules = {
+    "prelude//rules.bzl:go_library": None,
+}
+
+def _go_kind(need_tests: bool) -> str:
+    go_rules = "go_binary|go_library|go_exported_library"
+    if need_tests:
+        return go_rules + "|go_test"
+    return go_rules
+
+TargetData = record(
+    target = field(bxl.ConfiguredTargetNode),
+    go_package_info = field(GoPackageInfo | None),
+)
+
+LoadMode = record(
+    need_name = field(bool, False),
+    need_files = field(bool, False),
+    need_compiled_go_files = field(bool, False),
+    need_imports = field(bool, False),
+    need_deps = field(bool, False),
+    need_export_file = field(bool, False),
+    typecheck_cgo = field(bool, False),
+)
+
+PackageError = record(
+    Msg = field(str),
+)
+
+# BXL implementation of [Go Packages Driver Protocol](https://pkg.go.dev/golang.org/x/tools@v0.23.0/go/packages#hdr-The_driver_protocol)
+#
+# It can't be used on it's own, it need a thin go-wrapper that
+# - parses input args
+# - invokes `buck2 bxl prelude//go/tools/gopackagesdriver:driver.bxl:driver`
+# - fixes output, i.e RE paths in cgo files
+# - handles standard library packages
+#
+def _driver(ctx):
+    # get flat list of resolved target labels
+    requested_targets = ctx.unconfigured_targets(flatten(ctx.cli_args.target_exprs or []))
+    # print("Matched targets:", len(target_exprs))
+
+    if ctx.cli_args.files:
+        requested_targets += ctx.uquery().owner(ctx.cli_args.files)
+
+    if ctx.cli_args.need_tests:
+        requested_targets += ctx.uquery().testsof(requested_targets)
+
+    load_mode = _parse_load_mode(ctx)
+
+    go_kind = _go_kind(ctx.cli_args.need_tests)
+    go_root_targets = ctx.uquery().kind(go_kind, requested_targets)
+    # print("Matched Go targets:", len(go_targets))
+
+    cquery_errors = []
+    all_go_targets = bxl.ctarget_set()
+    for utarget, cquery_result in _cquery(ctx, "kind('{}', deps(%s, 2147483647, target_deps()))".format(go_kind), go_root_targets):
+        if cquery_result.is_ok():
+            all_go_targets += cquery_result.unwrap()
+        else:
+            cquery_errors.append((utarget, cquery_result.unwrap_err()))
+
+    # using dict to get rid of duplicated targets with different configurations
+    unique_go_targets = {_target_id(t): t.unwrap_forward() for t in all_go_targets}
+
+    analysis_results = _analysis(ctx, unique_go_targets.values())
+
+    artifacts_to_build = []
+    artifacts_to_ensure = []
+
+    targets_data = {}
+    import_table = {}
+    for id, target in unique_go_targets.items():
+        analysis_result = analysis_results[id]
+        if not analysis_result.is_ok():
+            targets_data[id] = TargetData(
+                target = target,
+                go_package_info = None,
+            )
+            continue
+
+        need_inputs = load_mode.need_files or load_mode.need_compiled_go_files
+        go_package_info = analysis_result.unwrap().providers()[GoPackageInfo]
+
+        targets_data[id] = TargetData(
+            target = target,
+            go_package_info = go_package_info,
+        )
+
+        if target.rule_type in importable_go_rules:
+            import_table[go_package_info.pkg_import_path] = _target_id(target)
+
+        artifacts_to_build.append(go_package_info.go_list_out)
+
+        if need_inputs:
+            artifacts_to_build.extend(go_package_info.srcs)
+            artifacts_to_ensure.extend(go_package_info.srcs)
+
+        if load_mode.need_export_file:
+            artifacts_to_build.append(go_package_info.build_out)
+            artifacts_to_ensure.append(go_package_info.build_out)
+
+        if load_mode.need_compiled_go_files:
+            artifacts_to_build.append(go_package_info.cgo_gen_dir)
+            artifacts_to_ensure.append(go_package_info.cgo_gen_dir)
+
+    build_results = _build_artifacts(ctx, artifacts_to_build)
+
+    # Materialize the only artifacts we were able to build to avoid script execution failure
+    ctx.output.ensure_multiple([a for a in artifacts_to_ensure if build_results[a].is_ok()])
+
+    actions = ctx.bxl_actions().actions
+    dynamic_out = actions.declare_output("dynamic_out.json", has_content_based_path = False)
+
+    # We have to create a closure to use `dynamic_output` to read `go list` output
+    def produce_result_json(ctx, artifacts, outputs):
+        packages = []
+        for id, td in targets_data.items():
+            if not analysis_results[id].is_ok():
+                analysis_error = analysis_results[id].unwrap_err()
+
+                # @unsorted-dict-items
+                package = {
+                    "ID": _target_id(td.target),
+                    "Errors": [PackageError(Msg = analysis_error.message)],
+                }
+            elif not build_results[td.go_package_info.go_list_out].is_ok():
+                # If building go_list_out failed report an error and recover as much data as we can
+                go_list_error = build_results[td.go_package_info.go_list_out].unwrap_err()
+                go_files = [i for i in td.go_package_info.srcs if i.extension == ".go"]
+
+                # @unsorted-dict-items
+                package = {
+                    "ID": _target_id(td.target),
+                    "PkgPath": td.go_package_info.pkg_import_path,
+                    "GoFiles": go_files,
+                    "CompiledGoFiles": go_files,
+                    "Errors": [PackageError(Msg = go_list_error.message)],
+                }
+
+            else:
+                go_list_out = parse_go_list_out(td.go_package_info.srcs, td.go_package_info.package_root, artifacts[td.go_package_info.go_list_out])
+                package = _make_protocol_package(load_mode, go_list_out, td, import_table, build_results)
+
+            packages.append(package)
+
+        packages += [{"Errors": [PackageError(Msg = error.message)], "ID": str(utarget.label)} for (utarget, error) in cquery_errors]
+
+        go_version = _go_version(ctx)
+
+        ctx.bxl_actions().actions.write_json(
+            outputs[dynamic_out],
+            {
+                "GoVersion": go_version.minor if go_version else 0,
+                "Packages": packages,
+                "Roots": [str(t.label) for t in go_root_targets],
+            },
+            pretty = True,
+            absolute = True,
+        )
+
+    actions.dynamic_output(
+        dynamic = [
+            td.go_package_info.go_list_out for td in targets_data.values() if td.go_package_info and build_results[td.go_package_info.go_list_out].is_ok()
+        ],
+        inputs = [],
+        outputs = [dynamic_out.as_output()],
+        f = produce_result_json,
+    )
+
+    ctx.output.print(ctx.output.ensure(dynamic_out).abs_path())
+
+def _make_protocol_package(
+    load_mode: LoadMode, go_list_out: GoListOut, td: TargetData, import_table: dict[str, str], build_results: dict[Artifact, bxl.Result]
+) -> dict[str, typing.Any]:
+    errors = set()
+    package = {"ID": _target_id(td.target)}
+    if load_mode.need_name:
+        package["Name"] = go_list_out.name
+        package["PkgPath"] = td.go_package_info.pkg_import_path
+
+    if load_mode.need_files:
+        # todo: handle invalid Go files
+        # We don't need to use "if" statements for _test.go files, because they are always empty for non-test targets
+        package["GoFiles"] = [] + go_list_out.go_files + go_list_out.cgo_files + go_list_out.test_go_files + go_list_out.x_test_go_files
+        package["OtherFiles"] = [] + go_list_out.h_files + go_list_out.c_files + go_list_out.cxx_files + go_list_out.s_files
+        package["IgnoredFiles"] = [] + go_list_out.ignored_go_files + go_list_out.ignored_other_files
+
+    if load_mode.need_compiled_go_files:
+        compiled_go_files, compiled_go_files_errors = _compiled_go_files(load_mode, go_list_out, td, build_results)
+        package["CompiledGoFiles"] = compiled_go_files
+        errors |= compiled_go_files_errors
+
+    if load_mode.need_export_file:
+        export_file_result = build_results[td.go_package_info.build_out]
+        if export_file_result.is_ok():
+            package["ExportFile"] = td.go_package_info.build_out
+        else:
+            errors.add(_to_protocol_error(export_file_result.unwrap_err(), td.target))
+
+    if load_mode.need_imports:
+        package["Imports"] = _imports(go_list_out, import_table)
+
+    if go_list_out.error != None:
+        errors.add(PackageError(Msg = go_list_out.error.err))
+
+    if len(errors) > 0:
+        package["Errors"] = list(errors)
+
+    return package
+
+def _compiled_go_files(
+    load_mode: LoadMode, go_list_out: GoListOut, td: TargetData, build_results: dict[Artifact, bxl.Result]
+) -> (list[Artifact], set[PackageError]):
+    compiled_go_files = [] + go_list_out.go_files + go_list_out.test_go_files + go_list_out.x_test_go_files
+    if len(go_list_out.cgo_files) > 0:
+        cgo_gen_dir_result = build_results[td.go_package_info.cgo_gen_dir]
+        if not cgo_gen_dir_result.is_ok():
+            return compiled_go_files, set([_to_protocol_error(cgo_gen_dir_result.unwrap_err(), td.target)])
+
+        cgo_tool_out = project_go_and_c_files(go_list_out.cgo_files, td.go_package_info.cgo_gen_dir)
+        if load_mode.typecheck_cgo:
+            # Replace generated `.cgo1.go` files with raw CGo files
+            # That's a bit hacky, but gopls relies on it
+            # Source: https://github.com/golang/tools/blob/v0.23.0/go/packages/golist.go#L509-L516
+            compiled_go_files += [cgo_tool_out.cgo_gotypes] + go_list_out.cgo_files
+        else:
+            compiled_go_files += [cgo_tool_out.cgo_gotypes] + cgo_tool_out.cgo1_go_files
+
+    return compiled_go_files, set()
+
+# map import names to packages ID, for non-buck packages like stdlib leave names as is
+# Example {"foo/bar": "fbcode//foo/bar:bar"}
+def _imports(go_list_out: GoListOut, import_table: dict[str, str]) -> dict[str, str]:
+    # todo: make it work when deps are not requested
+
+    # We don't need to use "if" statements for test imports, because they are always empty for non-test targets
+    all_imports = [] + go_list_out.imports + go_list_out.test_imports
+
+    # resolve imports, consider an import as stdlib import if not found in buck deps
+    imports = {imp: import_table.get(imp, imp) for imp in all_imports if imp != "C"}
+
+    has_cgo_files = len(go_list_out.cgo_files) > 0
+    if has_cgo_files:
+        # we don't pass -compiled flag to `go list` to make it faster
+        # so we have to manually add there imports from generated code
+        imports |= {
+            "runtime/cgo": "runtime/cgo",
+            "syscall": "syscall",
+            "unsafe": "unsafe",
+        }
+
+    return imports
+
+def _target_id(target: bxl.ConfiguredTargetNode) -> str:
+    return str(target.label.raw_target())
+
+def _build_artifacts(ctx: bxl.Context, artifacts: list[Artifact]) -> dict[Artifact, bxl.Result]:
+    results = ctx.lazy.join_all([ctx.lazy.build_artifact(a).catch() for a in artifacts]).resolve()
+    return {k: v for k, v in zip(artifacts, results)}
+
+def _analysis(ctx: bxl.Context, targets: list[bxl.ConfiguredTargetNode]) -> dict[str, bxl.Result]:
+    results = ctx.lazy.join_all([ctx.lazy.analysis(t).catch() for t in targets]).resolve()
+    return {_target_id(k): v for k, v in zip(targets, results)}
+
+def _cquery(ctx: bxl.Context, query: str, targets: bxl.UnconfiguredTargetSet) -> list[(bxl.UnconfiguredTargetNode, bxl.Result)]:
+    results = ctx.lazy.join_all([ctx.lazy.cquery().eval(query % str(t.label)).catch() for t in targets]).resolve()
+    return zip(targets, results)
+
+def _to_protocol_error(error: bxl.Error, expected_target: bxl.ConfiguredTargetNode) -> PackageError:
+    msg = error.message
+
+    # HACK: Parse errors manually until the structured API provided T208804014
+
+    # Extract valuable part of an action failure message
+    if msg.startswith("Action failed:"):
+        if msg.startswith("Action failed: {} ".format(_target_id(expected_target))):
+            # Throw away all the information besides stdin and stdout
+            if "\nStdout:" in msg:
+                _, _, actual_error = msg.partition("\nStdout:")
+                msg = actual_error
+        else:
+            # Note: The `go list` driver doesn't return any information if a dependency failed.
+            # It might be a good idea to follow this pattern, despite it looks entirely wrong.
+            first_line, _, _ = msg.partition("\n")
+            msg = "A dependency has an error:\n" + first_line
+
+    elif msg.startswith("Error running dynamic analysis for "):
+        if "\nCaused by:\n" in msg:
+            _, _, actual_error = msg.partition("\nCaused by:\n")
+            msg = "Analysis error root-cause:\n" + actual_error
+
+    # Todo: if an error is a compilation error parse line info?
+    # Question: Shall we do it in the Go part of the driver?
+
+    return PackageError(Msg = msg)
+
+def _go_version(ctx: bxl.Context) -> GoVersion | None:
+    toolchain = ctx.analysis(ctx.configured_targets("toolchains//:go")).providers()[GoToolchainInfo]
+    return toolchain.version
+
+# https://github.com/golang/tools/blob/v0.23.0/go/packages/packages.go#L41-L42
+# The zero value is a special case, equivalent to combining
+# the NeedName, NeedFiles, and NeedCompiledGoFiles bits.
+def _parse_load_mode(ctx: bxl.Context) -> LoadMode:
+    args = ctx.cli_args
+    is_default_load_mode = (
+        any([args.need_name, args.need_files, args.need_compiled_go_files, args.need_imports, args.need_deps, args.need_export_file]) == False
+    )
+    if is_default_load_mode:
+        return LoadMode(need_name = True, need_files = True, need_compiled_go_files = True)
+
+    return LoadMode(
+        need_name = args.need_name,
+        need_files = args.need_files,
+        need_compiled_go_files = args.need_compiled_go_files,
+        need_imports = args.need_imports,
+        need_deps = args.need_deps,
+        need_export_file = args.need_export_file,
+        typecheck_cgo = args.typecheck_cgo,
+    )
+
+driver = bxl_main(
+    impl = _driver,
+    # @unsorted-dict-items
+    cli_args = {
+        # packages.Load queries
+        # Note: relative paths have similar syntax to buck targets, e.q. fbcode//foo/bar.go
+        "files": cli_args.option(cli_args.list(cli_args.string())),
+        "target_exprs": cli_args.option(cli_args.list(cli_args.target_expr())),
+        # packages.DriverRequest values
+        "need_tests": cli_args.bool(),
+        # packages.LoadMode values
+        "need_name": cli_args.bool(),
+        "need_files": cli_args.bool(),
+        "need_compiled_go_files": cli_args.bool(),
+        "need_imports": cli_args.bool(),
+        "need_deps": cli_args.bool(),  # Note: has no effect at the moment
+        "need_export_file": cli_args.bool(),
+        "typecheck_cgo": cli_args.bool(),
+    },
+)
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver/BUCK b/buck2/prelude/go/tools/gopackagesdriver/driver/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver/BUCK
@@ -0,0 +1,28 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("golang")
+
+source_listing()
+
+prelude = native
+
+prelude.go_library(
+    name = "driver",
+    srcs = glob(
+        ["*.go"],
+        exclude = ["*_test.go"],
+    ),
+    visibility = ["PUBLIC"],
+    deps = [
+        # @oss-disable[end= ]: "fbcode//third-party-go/vendor/golang.org/x/tools/go/packages:packages",
+        "prelude//go/tools/gopackagesdriver/third-party:golang.org/x/tools/go/packages", # @oss-enable
+    ],
+)
+
+prelude.go_test(
+    name = "driver_test",
+    srcs = glob(["*_test.go"]),
+    # @oss-disable[end= ]: env = {"GO_TEST2JSON_TOOL": "$(exe_target fbsource//third-party/go:test2json)"},
+    target_under_test = ":driver",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver/buck.go b/buck2/prelude/go/tools/gopackagesdriver/driver/buck.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver/buck.go
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package driver
+
+import (
+	"bufio"
+	"bytes"
+	"context"
+	"errors"
+	"fmt"
+	"io"
+	"log/slog"
+	"os"
+	"os/exec"
+	"regexp"
+	"slices"
+	"strings"
+)
+
+// Commander is an interface for execing commands and getting stdout results
+type Commander interface {
+	Exec(ctx context.Context, name string, args ...string) ([]byte, error)
+}
+
+type shellCommander struct{}
+
+// Bucker is a mockable interface of the buck functionality this package uses
+type Bucker interface {
+	Root(ctx context.Context) (string, error)
+	BXL(ctx context.Context, label string, args []string) ([]byte, error)
+}
+
+type buckShell struct {
+	cmder       Commander
+	buckOptions []string // common flags for run/build/test/bxl commands
+}
+
+func (s shellCommander) Exec(ctx context.Context, name string, args ...string) ([]byte, error) {
+	cmd := exec.CommandContext(ctx, name, args...)
+	data, err := cmd.Output()
+	if err != nil {
+		var ee *exec.ExitError
+		if errors.As(err, &ee) {
+			return nil, fmt.Errorf("failed to execute command '%v' (%w): %s", cmd.Args, ee, string(ee.Stderr))
+		}
+		return nil, fmt.Errorf("failed to execute command '%v', %w", cmd.Args, err)
+	}
+	return data, nil
+}
+
+var lineRe = regexp.MustCompile(`//line\s+(.+):1:1`)
+
+// fixRePath replaces CGo line directives with the absolute source path reported
+// by go/packages.
+func fixRePath(file, absSrcPath string) error {
+	content, err := os.ReadFile(file)
+	if err != nil {
+		return err
+	}
+
+	buf := new(bytes.Buffer)
+
+	scanner := bufio.NewScanner(bytes.NewReader(content))
+	for scanner.Scan() {
+		origLine := scanner.Text()
+		matches := lineRe.FindStringSubmatch(origLine)
+		if len(matches) == 2 {
+			srcPath := matches[1]
+			slog.Debug("fixing CGo source path", "file", file, "old", srcPath, "new", absSrcPath)
+			fmt.Fprintf(buf, "//line %s:1:1\n", absSrcPath)
+		} else {
+			buf.WriteString(origLine)
+			buf.WriteString("\n")
+		}
+	}
+	if err = scanner.Err(); err != nil {
+		return err
+	}
+	dst, err := os.OpenFile(file, os.O_WRONLY|os.O_TRUNC, 0644)
+	if err != nil {
+		return err
+	}
+	defer dst.Close()
+	_, err = io.Copy(dst, buf)
+	return err
+}
+
+func (b *buckShell) run(ctx context.Context, args []string) ([]byte, error) {
+	args = append([]string{"--client-metadata=id=gopackagesdriver"}, args...)
+	slog.Debug("running 'buck2'", "args", args)
+	out, err := b.cmder.Exec(ctx, "buck2", args...)
+	if err != nil {
+		return nil, err
+	}
+	return out, nil
+}
+
+func (b *buckShell) Root(ctx context.Context) (string, error) {
+	data, err := b.run(ctx, []string{"root", "-k", "project"})
+	if err != nil {
+		return "", err
+	}
+
+	return strings.TrimSpace(string(data)), nil
+}
+
+func (b *buckShell) BXL(ctx context.Context, label string, args []string) ([]byte, error) {
+	data, err := b.run(ctx, slices.Concat([]string{"bxl"}, b.buckOptions, []string{label, "--"}, args))
+	slog.Debug("running BXL", "label", label, "args", args)
+	if err != nil {
+		return nil, err
+	}
+	return data, nil
+}
+
+// Use this hacky way to get errors until https://fburl.com/workplace/q79a59rn implemented
+func retriveActionErrors(buckStderr []byte) string {
+	logPrefix := regexp.MustCompile(`^\[\S+\]\s*`)
+	scanner := bufio.NewScanner(bytes.NewReader(buckStderr))
+	sb := strings.Builder{}
+	writtingStarted := false
+	for scanner.Scan() {
+		line := scanner.Text()
+
+		if strings.Contains(line, "] BUILD ERRORS ") || strings.HasPrefix(line, "Traceback (most recent call last):") {
+			writtingStarted = true
+		}
+
+		if line == "BXL FAILED" {
+			break
+		}
+
+		if !writtingStarted {
+			continue
+		}
+
+		if strings.Contains(line, "] The following actions failed") ||
+			strings.Contains(line, "] Remote action, reproduce with:") ||
+			strings.Contains(line, "] Local command") {
+			continue
+		}
+
+		fmt.Fprintln(&sb, logPrefix.ReplaceAllString(line, ""))
+	}
+
+	if err := scanner.Err(); err != nil {
+		return ""
+	}
+
+	return sb.String()
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver/buck_test.go b/buck2/prelude/go/tools/gopackagesdriver/driver/buck_test.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver/buck_test.go
@@ -0,0 +1,243 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package driver
+
+import (
+	"context"
+	"maps"
+	"os"
+	"path/filepath"
+	"slices"
+	"strings"
+	"testing"
+
+	"golang.org/x/tools/go/packages"
+)
+
+// requireNoError fails the test if err is not nil
+func requireNoError(t *testing.T, err error) {
+	t.Helper()
+	if err != nil {
+		t.Fatalf("Expected no error, got %v", err)
+	}
+}
+
+// requireEqual fails the test if expected != actual
+func requireEqual(t *testing.T, expected, actual any) {
+	t.Helper()
+	if expected != actual {
+		t.Fatalf("Expected %v, got %v", expected, actual)
+	}
+}
+
+type mockCommander struct {
+	output []byte
+	err    error
+	cmd    string
+	args   []string
+}
+
+func (m *mockCommander) Exec(ctx context.Context, name string, args ...string) ([]byte, error) {
+	m.cmd = name
+	m.args = args
+	return m.output, m.err
+}
+
+type mockCommanderChain struct {
+	commands []*mockCommander
+	pos      int
+}
+
+func (m *mockCommanderChain) Exec(ctx context.Context, name string, args ...string) ([]byte, error) {
+	res, err := m.commands[m.pos].Exec(ctx, name, args...)
+	m.pos++
+	return res, err
+}
+
+func TestBuckRoot(t *testing.T) {
+	ctx := context.Background()
+	cmder := &mockCommander{output: []byte("\n/data/users/user1/fbcode\n"), err: nil}
+	bucker := buckShell{cmder: cmder}
+
+	root, err := bucker.Root(ctx)
+	requireNoError(t, err)
+	requireEqual(t, "/data/users/user1/fbcode", root)
+}
+
+func TestFixRePathTruncatesFile(t *testing.T) {
+	path := filepath.Join(t.TempDir(), "generated.go")
+	original := "//line ../../../../long/path/to/source.go:1:1\npackage example\n"
+	requireNoError(t, os.WriteFile(path, []byte(original), 0644))
+
+	requireNoError(t, fixRePath(path, "/src/source.go"))
+
+	got, err := os.ReadFile(path)
+	requireNoError(t, err)
+	want := "//line /src/source.go:1:1\npackage example\n"
+	requireEqual(t, want, string(got))
+}
+
+func TestCgoPathRewrites(t *testing.T) {
+	testCases := []struct {
+		name    string
+		pkg     *packages.Package
+		want    map[string]string
+		wantErr string
+	}{
+		{
+			name: "checked-in CGo source",
+			pkg: &packages.Package{
+				ID:              "cgo",
+				GoFiles:         []string{"/repo/plain.go", "/repo/cgo_file.go"},
+				CompiledGoFiles: []string{"/buck-out/cgo_gen/cgo_file.cgo1.go"},
+			},
+			want: map[string]string{
+				"/buck-out/cgo_gen/cgo_file.cgo1.go": "/repo/cgo_file.go",
+			},
+		},
+		{
+			name: "generated SWIG source",
+			pkg: &packages.Package{
+				ID:              "swig",
+				GoFiles:         []string{"/buck-out/swig/out/swig_lib.go"},
+				CompiledGoFiles: []string{"/buck-out/cgo_gen/swig_lib.cgo1.go"},
+			},
+			want: map[string]string{
+				"/buck-out/cgo_gen/swig_lib.cgo1.go": "/buck-out/swig/out/swig_lib.go",
+			},
+		},
+		{
+			name: "ignore CGo types file",
+			pkg: &packages.Package{
+				ID:              "cgo",
+				CompiledGoFiles: []string{"/buck-out/cgo_gen/_cgo_gotypes.go"},
+			},
+		},
+		{
+			name: "missing source",
+			pkg: &packages.Package{
+				ID:              "cgo",
+				GoFiles:         []string{"/repo/other.go"},
+				CompiledGoFiles: []string{"/buck-out/cgo_gen/cgo_file.cgo1.go"},
+			},
+			wantErr: "found 0",
+		},
+		{
+			name: "ambiguous source",
+			pkg: &packages.Package{
+				ID:              "cgo",
+				GoFiles:         []string{"/repo/one/cgo_file.go", "/repo/two/cgo_file.go"},
+				CompiledGoFiles: []string{"/buck-out/cgo_gen/cgo_file.cgo1.go"},
+			},
+			wantErr: "found 2",
+		},
+		{
+			name: "relative source",
+			pkg: &packages.Package{
+				ID:              "cgo",
+				GoFiles:         []string{"cgo_file.go"},
+				CompiledGoFiles: []string{"/buck-out/cgo_gen/cgo_file.cgo1.go"},
+			},
+			wantErr: "is not absolute",
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			got, err := cgoPathRewrites(tc.pkg)
+			if tc.wantErr != "" {
+				if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
+					t.Fatalf("Expected error containing %q, got %v", tc.wantErr, err)
+				}
+				return
+			}
+			requireNoError(t, err)
+			requireEqual(t, true, maps.Equal(tc.want, got))
+		})
+	}
+}
+
+func TestBuildBXLArgsRequestsGoFilesForCompiledGoFiles(t *testing.T) {
+	req := &packages.DriverRequest{Mode: packages.NeedCompiledGoFiles}
+	args := buildBXLArgs(req, nil, nil)
+	requireEqual(t, true, slices.Contains(args, "--need_files"))
+	requireEqual(t, true, slices.Contains(args, "--need_compiled_go_files"))
+}
+
+func TestFixQuery(t *testing.T) {
+	testCases := []struct {
+		name   string
+		target string
+		want   string
+	}{
+		{
+			name:   "empty",
+			target: "",
+			want:   "",
+		},
+		{
+			name:   "basic",
+			target: "./fbcode//dns/lib/dnsgen/...",
+			want:   "fbcode//dns/lib/dnsgen/...",
+		},
+	}
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			got := fixPattern(tc.target)
+			requireEqual(t, tc.want, got)
+		})
+	}
+}
+
+func TestRetriveActionErrors(t *testing.T) {
+	buckStderr := []byte(`[2024-09-12T07:57:42.799-07:00] Buck UI: https://www.internalfb.com/buck2/86f93efa-c28e-4a34-94a8-129da2fc5336
+[2024-09-12T07:57:42.799-07:00] RE Session: reSessionID-21f215ea-c9f9-47db-a8d5-93787b9c3c7b
+[2024-09-12T07:57:42.880-07:00] Action failed: fbcode//scripts/user1/helloworld/greeting:greeting (cfg:linux-x86_64-fbcode-platform010-clang17-asan-ubsan-dev#0b9c1ba57ab15e90) (go_compile greeting)
+[2024-09-12T07:57:42.880-07:00] Local command returned non-zero exit code 2
+[2024-09-12T07:57:42.880-07:00] Local command: env -- 'BUCK_SCRATCH_PATH=buck-out/v2/tmp/fbcode/638f78105dd4e4ee/go_compile/greeting' 'CGO_ENABLED=1' 'GOARCH=amd64' 'GOEXPERIMENT=nocoverageredesign' 'GOOS=linux' 'GOROOT=third-party/go/1.23.1/linux_amd64' buck-out/v2/gen/prelude/a32dc125c1d570bc/go_bootstrap/tools/__go_go_wrapper__/go_go_wrapper --go buck-out/v2/gen/fbsource/a32dc125c1d570bc/third-party/go/1.23.1/linux_amd64/__compile.exe__/compile.exe -- '-buildid=' -nolocalimports -trimpath '%cwd%' -p scripts/peters95/helloworld/greeting -importcfg buck-out/v2/gen/fbcode/0b9c1ba57ab15e90/scripts/peters95/helloworld/greeting/__greeting__/__action___0__/scripts/peters95/helloworld/greeting.final.importcfg -o buck-out/v2/gen/fbcode/0b9c1ba57ab15e90/scripts/peters95/helloworld/greeting/__greeting__/__action___0__/go_compile_out.a @buck-out/v2/gen/fbcode/0b9c1ba57ab15e90/scripts/peters95/helloworld/greeting/__greeting__/__action___0__/greeting_srcs.go_package_argsfile
+[2024-09-12T07:57:42.880-07:00] Stdout:
+fbcode/scripts/user1/helloworld/greeting/greeting.go:8:18: syntax error: unexpected name get, expected (
+fbcode/scripts/user1/helloworld/greeting/greeting.go:10:1: syntax error: unexpected } after top level declaration
+[2024-09-12T07:57:42.880-07:00] Stderr:
+Error running command: exit status 2
+
+/data/users/user1/fbsource/buck-out/v2/gen-bxl/fbcode/6788fe67763f3975/tools/go/driver/driver.bxl/__driver__e0355e856f017750__/dynamic_out.json
+[2024-09-12T07:57:42.882-07:00] Cache hits: 0%
+[2024-09-12T07:57:42.882-07:00] Commands: 1 (cached: 0, remote: 0, local: 1)
+[2024-09-12T07:57:42.882-07:00] Network: Up: 0B  Down: 0B  (reSessionID-21f215ea-c9f9-47db-a8d5-93787b9c3c7b)
+[2024-09-12T07:57:42.886-07:00]
+[2024-09-12T07:57:42.886-07:00] BUILD ERRORS (1)
+[2024-09-12T07:57:42.886-07:00] The following actions failed during the execution of this command:
+[2024-09-12T07:57:42.886-07:00] Action failed: fbcode//scripts/user1/helloworld/greeting:greeting (cfg:linux-x86_64-fbcode-platform010-clang17-asan-ubsan-dev#0b9c1ba57ab15e90) (go_compile greeting)
+[2024-09-12T07:57:42.886-07:00] Local command returned non-zero exit code 2
+[2024-09-12T07:57:42.886-07:00] Local command: env -- 'BUCK_SCRATCH_PATH=buck-out/v2/tmp/fbcode/638f78105dd4e4ee/go_compile/greeting' 'CGO_ENABLED=1' 'GOARCH=amd64' 'GOEXPERIMENT=nocoverageredesign' 'GOOS=linux' 'GOROOT=third-party/go/1.23.1/linux_amd64' buck-out/v2/gen/prelude/a32dc125c1d570bc/go_bootstrap/tools/__go_go_wrapper__/go_go_wrapper --go buck-out/v2/gen/fbsource/a32dc125c1d570bc/third-party/go/1.23.1/linux_amd64/__compile.exe__/compile.exe -- '-buildid=' -nolocalimports -trimpath '%cwd%' -p scripts/peters95/helloworld/greeting -importcfg buck-out/v2/gen/fbcode/0b9c1ba57ab15e90/scripts/peters95/helloworld/greeting/__greeting__/__action___0__/scripts/peters95/helloworld/greeting.final.importcfg -o buck-out/v2/gen/fbcode/0b9c1ba57ab15e90/scripts/peters95/helloworld/greeting/__greeting__/__action___0__/go_compile_out.a @buck-out/v2/gen/fbcode/0b9c1ba57ab15e90/scripts/peters95/helloworld/greeting/__greeting__/__action___0__/greeting_srcs.go_package_argsfile
+[2024-09-12T07:57:42.886-07:00] Stdout:
+fbcode/scripts/user1/helloworld/greeting/greeting.go:8:18: syntax error: unexpected name get, expected (
+fbcode/scripts/user1/helloworld/greeting/greeting.go:10:1: syntax error: unexpected } after top level declaration
+[2024-09-12T07:57:42.886-07:00] Stderr:
+Error running command: exit status 2
+
+[2024-09-12T07:57:42.886-07:00]
+BXL FAILED
+Failed to build 'fbcode//scripts/user1/helloworld/greeting:greeting (cfg:linux-x86_64-fbcode-platform010-clang17-asan-ubsan-dev#0b9c1ba57ab15e90)'`)
+
+	expected := `BUILD ERRORS (1)
+Action failed: fbcode//scripts/user1/helloworld/greeting:greeting (cfg:linux-x86_64-fbcode-platform010-clang17-asan-ubsan-dev#0b9c1ba57ab15e90) (go_compile greeting)
+Stdout:
+fbcode/scripts/user1/helloworld/greeting/greeting.go:8:18: syntax error: unexpected name get, expected (
+fbcode/scripts/user1/helloworld/greeting/greeting.go:10:1: syntax error: unexpected } after top level declaration
+Stderr:
+Error running command: exit status 2
+
+
+`
+	requireEqual(t, expected, retriveActionErrors(buckStderr))
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver/driver.go b/buck2/prelude/go/tools/gopackagesdriver/driver/driver.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver/driver.go
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package driver
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"io"
+	"log/slog"
+	"os"
+	"runtime/debug"
+	"strings"
+	"time"
+
+	"golang.org/x/tools/go/packages"
+)
+
+const envVarPkgDriver = "GOPACKAGESDRIVER"
+
+const (
+	// Special case targets for meta-packages
+	metaAllPackages = "./..."
+	metaAll         = "all"
+	metaCmd         = "cmd"
+	metaStdLib      = "std"
+)
+
+var allPackagesTargetExprs = strings.Fields(os.Getenv("GOPACKAGESDRIVER_BUCK_ALL_PACKAGES_TARGET_EXPRS"))
+
+func query(ctx context.Context, req *packages.DriverRequest, bucker Bucker, platform Platform, targets []string) (*packages.DriverResponse, error) {
+	var resp *packages.DriverResponse
+	var err error
+
+	// The LSP tries to do this on start, which is all packages
+	// This will get stuck for a while so ignore it
+	safeTargets := make([]string, 0, len(targets))
+	for _, target := range targets {
+		if target == metaAllPackages || target == metaAll {
+			safeTargets = append(safeTargets, allPackagesTargetExprs...)
+			continue
+		}
+		safeTargets = append(safeTargets, target)
+	}
+
+	goBinary, cleanup, err := getGoBinary()
+	if err != nil {
+		slog.Error("failed to get go binary", "err", err)
+		return nil, err
+	}
+	defer cleanup()
+
+	goRootDir, err := getGoRoot(goBinary)
+	if err != nil {
+		slog.Error("failed to get go root", "err", err)
+	}
+
+	targetsByType, err := parsePatterns(platform, safeTargets, goRootDir)
+	if err != nil {
+		return nil, err
+	}
+
+	resp, err = queryBXL(ctx, req, bucker, targetsByType.buckPatterns, targetsByType.buckFiles)
+	if err != nil {
+		slog.Error("error when query BXL", "args", os.Args, "err", err)
+		return nil, err
+	}
+
+	if len(resp.Roots) > 0 {
+		stdDeps, err := getImportedStdPackages(ctx, resp, req, goBinary)
+		if err != nil {
+			return nil, err
+		}
+		resp.Packages = append(resp.Packages, stdDeps...)
+	}
+
+	if len(targetsByType.stdFiles) > 0 || len(targetsByType.stdPatterns) > 0 {
+		query := buildStdQuery(targetsByType.stdFiles, targetsByType.stdPatterns)
+		stdPackages, err := queryStd(ctx, req, goBinary, query)
+		if err != nil {
+			return nil, err
+		}
+
+		roots := extractRoots(stdPackages)
+
+		if req.Mode&packages.NeedDeps != 0 {
+			stdPackages = flattenDeps(stdPackages)
+		}
+
+		resp.Roots = append(resp.Roots, roots...)
+		resp.Packages = append(resp.Packages, stdPackages...)
+	}
+
+	// fallback to `go list` if we don't have any roots
+	// this will allow us to resolve non-buck targets
+	if len(resp.Roots) == 0 {
+		resp.NotHandled = true
+	}
+
+	return resp, nil
+}
+
+func readDriverRequest() (*packages.DriverRequest, error) {
+	stat, err := os.Stdin.Stat()
+	if err != nil {
+		return nil, fmt.Errorf("could not stat stdin: %w", err)
+	}
+
+	// No data being piped in
+	if (stat.Mode() & os.ModeCharDevice) != 0 {
+		slog.Info("no request data in stdin")
+		return &packages.DriverRequest{}, nil
+	}
+
+	slog.Info("reading request data from stdin")
+	reqData, err := io.ReadAll(os.Stdin)
+
+	if err != nil {
+		return nil, err
+	}
+	var req packages.DriverRequest
+	if err := json.Unmarshal(reqData, &req); err != nil {
+		return nil, fmt.Errorf("could not unmarshal driver request: %w", err)
+	}
+
+	if req.Overlay == nil {
+		req.Overlay = map[string][]byte{}
+	}
+
+	return &req, nil
+}
+
+// RunOptions holds configuration options for the driver
+type RunOptions struct {
+	telemetry Telemetry
+}
+
+// Option is a functional option for configuring RunOptions
+type Option func(*RunOptions)
+
+// WithTelemetry sets the telemetry implementation
+func WithTelemetry(t Telemetry) Option {
+	return func(opts *RunOptions) {
+		opts.telemetry = t
+	}
+}
+
+// Run parses the command line arguments and stdin, then runs buck2 and `go list` and writes results to stdout
+func Run(ctx context.Context, opts ...Option) error {
+	options := &RunOptions{
+		telemetry: &NoopTelemetry{},
+	}
+	for _, opt := range opts {
+		opt(options)
+	}
+
+	telemetry := options.telemetry
+	defer func() {
+		if r := recover(); r != nil {
+			telemetry.LogEvent(ctx, &PanicEvent{
+				PanicValue: r,
+				Stack:      debug.Stack(),
+			})
+			panic(r)
+		}
+	}()
+
+	start := time.Now()
+
+	// This must be cleared or we could forkbomb ourselves
+	// because we will call GoListDriver inside.
+	os.Setenv(envVarPkgDriver, "off")
+
+	switch os.Getenv("GOPACKAGESDRIVER_LOG_LEVEL") {
+	case "debug":
+		slog.SetLogLoggerLevel(slog.LevelDebug)
+	case "info":
+		slog.SetLogLoggerLevel(slog.LevelInfo)
+	case "warn":
+		slog.SetLogLoggerLevel(slog.LevelWarn)
+	case "error":
+		slog.SetLogLoggerLevel(slog.LevelError)
+	}
+
+	cwd := CWD()
+	targets := os.Args[1:]
+	cmder := &shellCommander{}
+	bucker := &buckShell{
+		cmder:       cmder,
+		buckOptions: strings.Fields(os.Getenv("GOPACKAGESDRIVER_BUCK_OPTIONS")),
+	}
+
+	req, err := readDriverRequest()
+	if err != nil {
+		return fmt.Errorf("failed to read driver request: %w", err)
+	}
+
+	platform, err := newPlatform(ctx, bucker, req)
+	if err != nil {
+		slog.Error("error creating platform", "err", err)
+		return err
+	}
+
+	slog.Info("running with args", "cwd", cwd, "project", platform.ProjectDir(), "args", os.Args)
+	slog.Debug("running with env", "env", os.Environ())
+
+	var resp *packages.DriverResponse
+
+	defer func() {
+		telemetry.LogEvent(ctx, &RequestFinishedEvent{
+			Duration: time.Since(start),
+			BuckRoot: platform.ProjectDir(),
+			Request:  req,
+			Patterns: targets,
+			Response: resp,
+			Error:    err,
+		})
+	}()
+
+	resp, err = query(ctx, req, bucker, platform, targets)
+	if err != nil {
+		return err
+	}
+
+	enc := json.NewEncoder(os.Stdout)
+	enc.SetIndent(" ", "    ")
+	return enc.Encode(resp)
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver/gobinary.go b/buck2/prelude/go/tools/gopackagesdriver/driver/gobinary.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver/gobinary.go
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package driver
+
+import (
+	"fmt"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strings"
+)
+
+// getGoBinary creates a temporary Go binary wrapper that uses Buck2
+// Won't work on Windows
+func getGoBinary() (string, func(), error) {
+	tmpDir, err := os.MkdirTemp("", "go-bin-*")
+	if err != nil {
+		return "", func() {}, fmt.Errorf("failed to create temp dir: %w", err)
+	}
+
+	buckOpts := strings.Fields(os.Getenv("GOPACKAGESDRIVER_BUCK_OPTIONS"))
+	scriptContent := fmt.Sprintf(`#!/usr/bin/env bash
+# remove the current directory from the path to avoid infinite recursion on system_go_toolchain
+export PATH=${PATH//$(dirname "$0"):/}
+exec buck2 run %s 'toolchains//:go[go]' -- "$@"
+`, strings.Join(buckOpts, " "))
+
+	goBinaryPath := filepath.Join(tmpDir, "go")
+	err = os.WriteFile(goBinaryPath, []byte(scriptContent), 0755)
+	if err != nil {
+		return "", func() {}, fmt.Errorf("failed to write to temp file: %w", err)
+	}
+
+	cleanup := func() {
+		_ = os.RemoveAll(tmpDir)
+	}
+
+	return goBinaryPath, cleanup, nil
+}
+
+func getGoRoot(goBinary string) (string, error) {
+	out, err := exec.Command(goBinary, "env", "GOROOT").Output()
+	if err != nil {
+		return "", err
+	}
+	return strings.TrimSpace(string(out)), nil
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver/platform.go b/buck2/prelude/go/tools/gopackagesdriver/driver/platform.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver/platform.go
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package driver
+
+import (
+	"bytes"
+	"context"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+
+	"golang.org/x/tools/go/packages"
+)
+
+// Platform is an interface to any system level operation we need
+// for example opening files or finding unique file paths
+type Platform interface {
+	ProjectDir() string
+	// Returns true if the file exists on the filesystem
+	FileExists(path string) bool
+}
+
+type realPlatform struct {
+	// absolute goroot path
+	projectDir string
+	overlay    map[string][]byte
+}
+
+func (p *realPlatform) ProjectDir() string {
+	return p.projectDir
+}
+
+// OverlayOpener creates a closure over an FS overlay that allows for overrides of FS reads
+func OverlayOpener(overlay map[string][]byte) func(path string) (io.ReadCloser, error) {
+	return func(path string) (io.ReadCloser, error) {
+		ol := overlay
+		if data, ok := ol[path]; ok {
+			return io.NopCloser(bytes.NewReader(data)), nil
+		}
+		return os.Open(path)
+	}
+}
+
+func (p *realPlatform) FileExists(path string) bool {
+	if _, ok := p.overlay[path]; ok {
+		return true
+	}
+	info, err := os.Stat(path)
+	if os.IsNotExist(err) {
+		return false
+	}
+	return !info.IsDir()
+}
+
+// CWD returns the current WD with symlinks resolved
+func CWD() string {
+	cwd, _ := os.Getwd()
+	cwd, _ = filepath.EvalSymlinks(cwd)
+	return cwd
+}
+
+// findProjectDirectory finds the absolute buck project directory
+func findProjectDirectory(ctx context.Context, bucker Bucker) (string, error) {
+	return bucker.Root(ctx)
+}
+
+// newPlatform creates a new actual platform using system libraries and buck
+func newPlatform(ctx context.Context, bucker Bucker, req *packages.DriverRequest) (*realPlatform, error) {
+	rp := &realPlatform{
+		overlay: req.Overlay,
+	}
+
+	pd, err := findProjectDirectory(ctx, bucker)
+	if err != nil || pd == "" {
+		return nil, fmt.Errorf("failed to find buck project directory: %w", err)
+	}
+	rp.projectDir = pd
+
+	return rp, nil
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver/query_bxl.go b/buck2/prelude/go/tools/gopackagesdriver/driver/query_bxl.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver/query_bxl.go
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package driver
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"log/slog"
+	"maps"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"slices"
+	"strings"
+
+	"golang.org/x/tools/go/packages"
+)
+
+// LoadModeTypecheckCgo is a hack to support cgo in gopls
+// We declare a copy of private value that for some reason is used in gopls
+// Ideally we should not do this, but it's the only way to support cgo in gopls
+const LoadModeTypecheckCgo = packages.LoadMode(4096)
+
+const cgoGenFileNameExt = ".cgo1.go"
+
+// queryBXL is a wrapper around query that will use BXL to resolve the targets
+func queryBXL(
+	ctx context.Context,
+	req *packages.DriverRequest,
+	bucker Bucker,
+	patterns []string,
+	files []string,
+) (*packages.DriverResponse, error) {
+	if len(patterns) == 0 && len(files) == 0 {
+		return &packages.DriverResponse{}, nil
+	}
+
+	bxlArgs := buildBXLArgs(req, patterns, files)
+
+	bxlOut, err := bucker.BXL(ctx, "prelude//go/tools/gopackagesdriver:driver.bxl:driver", bxlArgs)
+	if err != nil {
+		var ee *exec.ExitError
+		if errors.As(err, &ee) {
+			// Create ad-hoc package with information about the error
+			// This is likely will be done inside BXL
+			// once  https://fburl.com/workplace/q79a59rn implemented
+			actionErrors := retriveActionErrors(ee.Stderr)
+			if len(actionErrors) > 0 {
+				slog.Warn("failed to query BXL, but we have action errors", "err", err)
+				return &packages.DriverResponse{
+					Roots: []string{"ad-hoc-error-recovery"},
+					Packages: []*packages.Package{{
+						ID:              "ad-hoc-error-recovery",
+						GoFiles:         files,
+						CompiledGoFiles: files,
+						Errors: []packages.Error{{
+							Msg:  actionErrors,
+							Kind: packages.ListError,
+						}},
+					}},
+				}, nil
+			}
+		}
+
+		return nil, err
+	}
+
+	filePath := strings.TrimSuffix(string(bxlOut), "\n")
+
+	file, err := os.ReadFile(filePath)
+	if err != nil {
+		return nil, err
+	}
+	slog.Debug("Response from query BXL", "file", file)
+
+	var response packages.DriverResponse
+	err = json.Unmarshal(file, &response)
+	if err != nil {
+		return nil, err
+	}
+
+	rewrites := make(map[string]string)
+	for _, pkg := range response.Packages {
+		pkgRewrites, err := cgoPathRewrites(pkg)
+		if err != nil {
+			return nil, err
+		}
+		for generatedFile, sourceFile := range pkgRewrites {
+			if _, ok := rewrites[generatedFile]; ok {
+				return nil, fmt.Errorf("duplicate CGo path rewrite for %q", generatedFile)
+			}
+			rewrites[generatedFile] = sourceFile
+		}
+	}
+	for generatedFile, sourceFile := range rewrites {
+		if err := fixRePath(generatedFile, sourceFile); err != nil {
+			return nil, fmt.Errorf("rewrite CGo source path for %q: %w", generatedFile, err)
+		}
+	}
+
+	return &response, nil
+}
+
+func cgoPathRewrites(pkg *packages.Package) (map[string]string, error) {
+	sourcesByBase := make(map[string]map[string]struct{})
+	for _, sourceFile := range pkg.GoFiles {
+		sourceBase := filepath.Base(sourceFile)
+		if sourcesByBase[sourceBase] == nil {
+			sourcesByBase[sourceBase] = make(map[string]struct{})
+		}
+		sourcesByBase[sourceBase][sourceFile] = struct{}{}
+	}
+
+	rewrites := make(map[string]string)
+	for _, generatedFile := range pkg.CompiledGoFiles {
+		generatedBase := filepath.Base(generatedFile)
+		if !strings.HasSuffix(generatedBase, cgoGenFileNameExt) {
+			continue
+		}
+
+		sourceBase := strings.TrimSuffix(generatedBase, cgoGenFileNameExt) + ".go"
+		matches := sourcesByBase[sourceBase]
+		if len(matches) != 1 {
+			return nil, fmt.Errorf("package %q: expected exactly one GoFiles source named %q for %q, found %d", pkg.ID, sourceBase, generatedFile, len(matches))
+		}
+		sourceFile := slices.Collect(maps.Keys(matches))[0]
+		if !filepath.IsAbs(sourceFile) {
+			return nil, fmt.Errorf("package %q: GoFiles source %q for %q is not absolute", pkg.ID, sourceFile, generatedFile)
+		}
+		rewrites[generatedFile] = sourceFile
+	}
+	return rewrites, nil
+}
+
+func buildBXLArgs(req *packages.DriverRequest, patterns []string, files []string) []string {
+	bxlArgs := []string{}
+	if len(patterns) > 0 {
+		bxlArgs = append(bxlArgs, "--target_exprs")
+		bxlArgs = append(bxlArgs, patterns...)
+	}
+	if len(files) > 0 {
+		bxlArgs = append(bxlArgs, "--files")
+		bxlArgs = append(bxlArgs, files...)
+	}
+	if req.Tests {
+		bxlArgs = append(bxlArgs, "--need_tests", "true")
+	}
+	if req.Mode&packages.NeedName != 0 {
+		bxlArgs = append(bxlArgs, "--need_name", "true")
+	}
+	// we have to implicitly add some flags if syntax/types requested
+	// same as `go list` driver does
+	// todo: add packages.NeedTypesSizes to the query as well, when we fix slow builds
+	// as gopls requires it, but it can't wait very long
+	needTypes := packages.NeedTypes | packages.NeedTypesInfo
+	needCompiledGoFiles := packages.NeedCompiledGoFiles | packages.NeedSyntax | needTypes
+	if req.Mode&(packages.NeedFiles|needCompiledGoFiles) != 0 {
+		bxlArgs = append(bxlArgs, "--need_files", "true")
+	}
+	if req.Mode&needCompiledGoFiles != 0 {
+		bxlArgs = append(bxlArgs, "--need_compiled_go_files", "true")
+	}
+	if req.Mode&(packages.NeedImports|needTypes) != 0 {
+		bxlArgs = append(bxlArgs, "--need_imports", "true")
+	}
+	if req.Mode&(packages.NeedDeps|needTypes) != 0 {
+		bxlArgs = append(bxlArgs, "--need_deps", "true")
+	}
+	if req.Mode&(packages.NeedExportFile|needTypes) != 0 {
+		bxlArgs = append(bxlArgs, "--need_export_file", "true")
+	}
+	if req.Mode&LoadModeTypecheckCgo != 0 {
+		bxlArgs = append(bxlArgs, "--typecheck_cgo", "true")
+	}
+	return bxlArgs
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver/stdlib.go b/buck2/prelude/go/tools/gopackagesdriver/driver/stdlib.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver/stdlib.go
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package driver
+
+import (
+	"bytes"
+	"context"
+	"fmt"
+	"go/parser"
+	"go/token"
+	"log/slog"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"sort"
+	"strconv"
+	"strings"
+
+	"golang.org/x/tools/go/packages"
+)
+
+// queryStd resolves packages the "normal" way
+// This is mostly used to resolve builtins and stdlib which buck doesn't know about
+// - stdlibDeps is a special argument, we never add it to roots, as it's always a dependency of buck's package
+func queryStd(ctx context.Context, req *packages.DriverRequest, goBinPath string, queryArgs []string) ([]*packages.Package, error) {
+	// If we exist within a buck environment, then use the buck go tool instead
+	// of the one in the system PATH
+	origPath := os.Getenv("PATH")
+	goBinDir := filepath.Dir(goBinPath)
+	os.Setenv("PATH", fmt.Sprintf("%s:%s", goBinDir, origPath))
+	slog.Info("overriding PATH to use Go from Buck", "dir", goBinDir)
+	defer os.Setenv("PATH", origPath)
+
+	mode := req.Mode
+
+	// HACK: patch request to fix Syntax and Types for stdlib
+	needTypes := packages.NeedTypes | packages.NeedTypesInfo
+	if req.Mode&(packages.NeedSyntax|needTypes) != 0 {
+		mode |= packages.NeedFiles | packages.NeedCompiledGoFiles
+	}
+	if req.Mode&(needTypes) != 0 {
+		mode |= packages.NeedExportFile | packages.NeedDeps
+	}
+
+	// HACK: if go distribution has been built with CGO_ENABLED=0, this changes default behaviour on "always disabled"
+	// Unfortunately we're relying on the original behaviour "lookup GCC" until we enable buck2 to build stdlib atonomously
+	// Let's emulate this behaviour it for now
+	cgoEnabled := "CGO_ENABLED=1"
+	if _, err := exec.LookPath("gcc"); err != nil {
+		cgoEnabled = "CGO_ENABLED=0"
+	}
+
+	loadcfg := &packages.Config{
+		Context:    ctx,
+		BuildFlags: req.BuildFlags,
+		Overlay:    req.Overlay,
+		Tests:      req.Tests,
+		Mode:       mode,
+		Logf: func(format string, args ...any) {
+			slog.Info(fmt.Sprintf(format, args...))
+		},
+		Env: append(os.Environ(), cgoEnabled),
+	}
+
+	slog.Info("running stdlib load", "mode", loadcfg.Mode, "tests", loadcfg.Tests, "buildFlags", loadcfg.BuildFlags)
+	loaded, err := packages.Load(loadcfg, queryArgs...)
+	if err != nil {
+		return nil, err
+	}
+
+	return loaded, nil
+}
+
+func parseImports(path string, content []byte) []string {
+	ast, err := parser.ParseFile(token.NewFileSet(), path, bytes.NewReader(content), parser.ImportsOnly)
+	if err != nil {
+		return []string{}
+	}
+
+	imports := make([]string, 0, len(ast.Imports))
+	for _, imp := range ast.Imports {
+		impPath, err := strconv.Unquote(imp.Path.Value)
+		if err != nil {
+			continue
+		}
+		imports = append(imports, impPath)
+	}
+
+	return imports
+}
+
+// flattenDeps traverses response of packages.Load
+// to transform it into a format of gopackages driver response
+// Borrowed from: https://github.com/golang/tools/blob/15c16a55ca665ba6c72a3159c7dca3b0455e37d2/go/packages/gopackages/main.go#L129
+func flattenDeps(pkgs []*packages.Package) []*packages.Package {
+	var all []*packages.Package // postorder
+	seen := make(map[*packages.Package]bool)
+	var visit func(*packages.Package)
+	visit = func(lpkg *packages.Package) {
+		if !seen[lpkg] {
+			seen[lpkg] = true
+
+			// visit imports
+			var importPaths []string
+			for path := range lpkg.Imports {
+				importPaths = append(importPaths, path)
+			}
+			sort.Strings(importPaths) // for determinism
+			for _, path := range importPaths {
+				visit(lpkg.Imports[path])
+			}
+
+			all = append(all, lpkg)
+		}
+	}
+	for _, lpkg := range pkgs {
+		visit(lpkg)
+	}
+	return all
+}
+
+// getImportedStdPackages analyzes the response and request to find imported standard library packages
+func getImportedStdPackages(ctx context.Context, resp *packages.DriverResponse, req *packages.DriverRequest, goBinary string) ([]*packages.Package, error) {
+	if len(resp.Roots) == 0 {
+		return nil, nil
+	}
+
+	stdPackages, err := queryStd(ctx, req, goBinary, []string{metaStdLib})
+	if err != nil {
+		return nil, err
+	}
+
+	stdPackageByImportName := make(map[string]*packages.Package)
+	for _, pkg := range stdPackages {
+		// skip test packages, we don't import them
+		if strings.HasSuffix(pkg.ID, ".test") || strings.HasSuffix(pkg.ID, ".test]") {
+			continue
+		}
+
+		stdPackageByImportName[pkg.PkgPath] = pkg
+	}
+
+	importedPkgs := make(map[string]bool)
+	for _, pkg := range resp.Packages {
+		for _, imp := range pkg.Imports {
+			importedPkgs[imp.ID] = true
+		}
+
+		// If a user has unsaved changes and imported a new stdlib package, we need to add it to the response
+		for _, file := range pkg.GoFiles {
+			if content, ok := req.Overlay[file]; ok {
+				for _, impPath := range parseImports(file, content) {
+					// If we never saw this import before, adding it to pkg.Imports
+					if stdPkg, ok := stdPackageByImportName[impPath]; ok {
+						pkg.Imports[impPath] = stdPkg
+					}
+
+					// Also, adding it to the list of imported packages to add dependencies to the response
+					importedPkgs[impPath] = true
+				}
+			}
+		}
+	}
+
+	directDeps := []*packages.Package{}
+	for imported := range importedPkgs {
+		if pkg, ok := stdPackageByImportName[imported]; ok {
+			directDeps = append(directDeps, pkg)
+		}
+	}
+
+	return flattenDeps(directDeps), nil
+}
+
+// buildStdQuery constructs query arguments for standard library targets
+func buildStdQuery(stdFiles, stdPatterns []string) []string {
+	query := make([]string, 0, len(stdFiles)+len(stdPatterns))
+	for _, pattern := range stdPatterns {
+		query = append(query, "pattern="+pattern)
+	}
+	for _, file := range stdFiles {
+		query = append(query, "file="+file)
+	}
+	return query
+}
+
+// extractRoots extracts package IDs as roots from a list of packages
+func extractRoots(packages []*packages.Package) []string {
+	roots := make([]string, 0, len(packages))
+	for _, pkg := range packages {
+		roots = append(roots, pkg.ID)
+	}
+	return roots
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver/targets.go b/buck2/prelude/go/tools/gopackagesdriver/driver/targets.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver/targets.go
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package driver
+
+import (
+	"fmt"
+	"path/filepath"
+	"strings"
+)
+
+type targetsByType struct {
+	buckPatterns []string
+	buckFiles    []string
+	stdPatterns  []string
+	stdFiles     []string
+}
+
+func parsePatterns(platform Platform, targets []string, goRoot string) (*targetsByType, error) {
+	var fileTargets, pkgTargets []string
+	for _, targ := range targets {
+		targ = fixPattern(targ)
+
+		// Hack for golangci-lint, it doesn't add the file= prefix, let's detect it ourselves
+		// https://github.com/golangci/golangci-lint/blob/726b8153cac6c04238264b189f5b05ec059f9330/pkg/lint/package.go#L234-L250
+		targetIsFile := filepath.Ext(targ) == ".go" && platform.FileExists(targ)
+		if strings.HasPrefix(targ, "file=") || targetIsFile {
+			fname := strings.TrimPrefix(targ, "file=")
+			if !platform.FileExists(fname) {
+				return nil, fmt.Errorf("cannot find input file '%s'", fname)
+			}
+			fname = absRealPath(fname)
+
+			fileTargets = append(fileTargets, fname)
+			continue
+		}
+		if strings.HasPrefix(targ, "pattern=") {
+			pkgTargets = append(pkgTargets, strings.TrimPrefix(targ, "pattern="))
+			continue
+		}
+		pkgTargets = append(pkgTargets, targ)
+	}
+
+	result := &targetsByType{}
+	for _, pkg := range pkgTargets {
+		if strings.Contains(pkg, "//") || strings.Contains(pkg, ":") {
+			result.buckPatterns = append(result.buckPatterns, pkg)
+		} else {
+			result.stdPatterns = append(result.stdPatterns, pkg)
+		}
+	}
+
+	for _, file := range fileTargets {
+		if strings.Contains(file, goRoot) {
+			result.stdFiles = append(result.stdFiles, file)
+		} else {
+			result.buckFiles = append(result.buckFiles, file)
+		}
+	}
+
+	return result, nil
+}
+
+// fixPattern fixes target name
+func fixPattern(target string) string {
+	// Remove leading ./ added by golangci-lint
+	// https://github.com/golangci/golangci-lint/blob/726b8153cac6c04238264b189f5b05ec059f9330/pkg/lint/package.go#L245
+	return strings.TrimPrefix(target, fmt.Sprintf(".%c", filepath.Separator))
+}
+
+func absRealPath(f string) string {
+	path, _ := filepath.Abs(f)
+	path, _ = filepath.EvalSymlinks(path)
+	return path
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/driver/telemetry.go b/buck2/prelude/go/tools/gopackagesdriver/driver/telemetry.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/driver/telemetry.go
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package driver
+
+import (
+	"context"
+	"time"
+
+	"golang.org/x/tools/go/packages"
+)
+
+type RequestFinishedEvent struct {
+	Duration time.Duration
+	BuckRoot string
+	Request  *packages.DriverRequest
+	Patterns []string
+	// Note: Response or Error can be nil
+	Response *packages.DriverResponse
+	Error    error
+}
+
+type PanicEvent struct {
+	PanicValue interface{} // from recover
+	Stack      []byte      // from debug.Stack
+}
+
+// Telemetry abstracts loging of the driver events. It is recemmended to be:
+// - qucik to avoid slowing down the tool
+// - thread safe as we can run multiple gorutines
+// - flexible to skip unknown events
+type Telemetry interface {
+	LogEvent(ctx context.Context, event any)
+}
+
+// NoopTelemetry is a noop implementation of Telemetry
+type NoopTelemetry struct{}
+
+func (*NoopTelemetry) LogEvent(ctx context.Context, event any) {
+	// noop
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/main.go b/buck2/prelude/go/tools/gopackagesdriver/main.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/main.go
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package main
+
+import (
+	"context"
+	"log/slog"
+	"os"
+
+	"go/tools/gopackagesdriver/driver"
+)
+
+func main() {
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+
+	err := driver.Run(ctx, driver.WithTelemetry(&driver.NoopTelemetry{}))
+	if err != nil {
+		slog.Error("error with input", "args", os.Args[1:], "err", err)
+		os.Exit(1)
+	}
+}
diff --git a/buck2/prelude/go/tools/gopackagesdriver/third-party/BUCK b/buck2/prelude/go/tools/gopackagesdriver/third-party/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/gopackagesdriver/third-party/BUCK
@@ -0,0 +1,354 @@
+# @oss-disable[end= ]: load("@fbsource//tools/target_determinator/macros:ci.bzl", "ci")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("golang")
+
+source_listing()
+
+prelude = native
+
+prelude.http_archive(
+    name = "golang.org/x/tools__srcs",
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    sha1 = "e11c0f5a96ff80c5dcf09bcaf35bf04c286ebf15",
+    strip_prefix = "golang.org/x/tools@v0.34.0",
+    sub_targets = {
+        "go/gcexportdata": [
+            "go/gcexportdata/gcexportdata.go",
+            "go/gcexportdata/importer.go",
+            "go/gcexportdata/main.go",
+        ],
+        "go/packages": [
+            "go/packages/doc.go",
+            "go/packages/external.go",
+            "go/packages/golist_overlay.go",
+            "go/packages/golist.go",
+            "go/packages/loadmode_string.go",
+            "go/packages/packages.go",
+            "go/packages/visit.go",
+        ],
+        "go/types/objectpath": [
+            "go/types/objectpath/objectpath.go",
+        ],
+        "go/types/typeutil": [
+            "go/types/typeutil/callee.go",
+            "go/types/typeutil/imports.go",
+            "go/types/typeutil/map.go",
+            "go/types/typeutil/methodsetcache.go",
+            "go/types/typeutil/ui.go",
+        ],
+        "internal/aliases": [
+            "internal/aliases/aliases.go",
+            "internal/aliases/aliases_go122.go",
+        ],
+        "internal/event": [
+            "internal/event/doc.go",
+            "internal/event/event.go",
+        ],
+        "internal/event/core": [
+            "internal/event/core/event.go",
+            "internal/event/core/export.go",
+            "internal/event/core/fast.go",
+        ],
+        "internal/event/keys": [
+            "internal/event/keys/keys.go",
+            "internal/event/keys/standard.go",
+            "internal/event/keys/util.go",
+        ],
+        "internal/event/label": [
+            "internal/event/label/label.go",
+        ],
+        "internal/gcimporter": [
+            "internal/gcimporter/bimport.go",
+            "internal/gcimporter/exportdata.go",
+            "internal/gcimporter/gcimporter.go",
+            "internal/gcimporter/iexport.go",
+            "internal/gcimporter/iimport_go122.go",
+            "internal/gcimporter/iimport.go",
+            "internal/gcimporter/main.go",
+            "internal/gcimporter/predeclared.go",
+            "internal/gcimporter/support.go",
+            "internal/gcimporter/ureader_yes.go",
+        ],
+        "internal/gocommand": [
+            "internal/gocommand/invoke_notunix.go",
+            "internal/gocommand/invoke_unix.go",
+            "internal/gocommand/invoke.go",
+            "internal/gocommand/vendor.go",
+            "internal/gocommand/version.go",
+        ],
+        "internal/packagesinternal": [
+            "internal/packagesinternal/packages.go",
+        ],
+        "internal/pkgbits": [
+            "internal/pkgbits/codes.go",
+            "internal/pkgbits/decoder.go",
+            "internal/pkgbits/doc.go",
+            "internal/pkgbits/encoder.go",
+            "internal/pkgbits/flags.go",
+            "internal/pkgbits/reloc.go",
+            "internal/pkgbits/support.go",
+            "internal/pkgbits/sync.go",
+            "internal/pkgbits/syncmarker_string.go",
+            "internal/pkgbits/version.go",
+        ],
+        "internal/stdlib": [
+            "internal/stdlib/deps.go",
+            "internal/stdlib/generate.go",
+            "internal/stdlib/import.go",
+            "internal/stdlib/manifest.go",
+            "internal/stdlib/stdlib.go",
+        ],
+        "internal/typeparams": [
+            "internal/typeparams/common.go",
+            "internal/typeparams/copytermlist.go",
+            "internal/typeparams/coretype.go",
+            "internal/typeparams/free.go",
+            "internal/typeparams/normalize.go",
+            "internal/typeparams/termlist.go",
+            "internal/typeparams/typeterm.go",
+        ],
+        "internal/typesinternal": [
+            "internal/typesinternal/classify_call.go",
+            "internal/typesinternal/element.go",
+            "internal/typesinternal/errorcode_string.go",
+            "internal/typesinternal/errorcode.go",
+            "internal/typesinternal/qualifier.go",
+            "internal/typesinternal/recv.go",
+            "internal/typesinternal/toonew.go",
+            "internal/typesinternal/typeindex",
+            "internal/typesinternal/types.go",
+            "internal/typesinternal/varkind.go",
+            "internal/typesinternal/zerovalue.go",
+        ],
+        "internal/versions": [
+            "internal/versions/features.go",
+            "internal/versions/gover.go",
+            "internal/versions/types.go",
+            "internal/versions/versions.go",
+        ],
+    },
+    urls = ["https://proxy.golang.org/golang.org/x/tools/@v/v0.34.0.zip"],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/go/packages",
+    package_name = "golang.org/x/tools/go/packages",
+    srcs = [":golang.org/x/tools__srcs[go/packages]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [
+        ":golang.org/x/sync/errgroup",
+        ":golang.org/x/tools/go/gcexportdata",
+        ":golang.org/x/tools/internal/gocommand",
+        ":golang.org/x/tools/internal/packagesinternal",
+        ":golang.org/x/tools/internal/typesinternal",
+    ],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/gocommand",
+    package_name = "golang.org/x/tools/internal/gocommand",
+    srcs = [":golang.org/x/tools__srcs[internal/gocommand]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [
+        ":golang.org/x/mod/semver",
+        ":golang.org/x/tools/internal/event",
+        ":golang.org/x/tools/internal/event/keys",
+        ":golang.org/x/tools/internal/event/label",
+    ],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/event",
+    package_name = "golang.org/x/tools/internal/event",
+    srcs = [":golang.org/x/tools__srcs[internal/event]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [
+        ":golang.org/x/tools/internal/event/core",
+        ":golang.org/x/tools/internal/event/keys",
+        ":golang.org/x/tools/internal/event/label",
+    ],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/event/core",
+    package_name = "golang.org/x/tools/internal/event/core",
+    srcs = [":golang.org/x/tools__srcs[internal/event/core]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [
+        ":golang.org/x/tools/internal/event/keys",
+        ":golang.org/x/tools/internal/event/label",
+    ],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/event/keys",
+    package_name = "golang.org/x/tools/internal/event/keys",
+    srcs = [":golang.org/x/tools__srcs[internal/event/keys]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [":golang.org/x/tools/internal/event/label"],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/event/label",
+    package_name = "golang.org/x/tools/internal/event/label",
+    srcs = [":golang.org/x/tools__srcs[internal/event/label]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/packagesinternal",
+    package_name = "golang.org/x/tools/internal/packagesinternal",
+    srcs = [":golang.org/x/tools__srcs[internal/packagesinternal]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/go/gcexportdata",
+    package_name = "golang.org/x/tools/go/gcexportdata",
+    srcs = [":golang.org/x/tools__srcs[go/gcexportdata]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [
+        ":golang.org/x/tools/internal/gcimporter",
+    ],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/gcimporter",
+    package_name = "golang.org/x/tools/internal/gcimporter",
+    srcs = [":golang.org/x/tools__srcs[internal/gcimporter]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [
+        ":golang.org/x/tools/go/types/objectpath",
+        ":golang.org/x/tools/internal/aliases",
+        ":golang.org/x/tools/internal/pkgbits",
+        ":golang.org/x/tools/internal/typesinternal",
+    ],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/go/types/objectpath",
+    package_name = "golang.org/x/tools/go/types/objectpath",
+    srcs = [":golang.org/x/tools__srcs[go/types/objectpath]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [
+        ":golang.org/x/tools/internal/aliases",
+        ":golang.org/x/tools/internal/typesinternal",
+    ],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/aliases",
+    package_name = "golang.org/x/tools/internal/aliases",
+    srcs = [":golang.org/x/tools__srcs[internal/aliases]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/typesinternal",
+    package_name = "golang.org/x/tools/internal/typesinternal",
+    srcs = [":golang.org/x/tools__srcs[internal/typesinternal]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [
+        ":golang.org/x/tools/go/types/typeutil",
+        ":golang.org/x/tools/internal/aliases",
+        ":golang.org/x/tools/internal/stdlib",
+        ":golang.org/x/tools/internal/versions",
+    ],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/go/types/typeutil",
+    package_name = "golang.org/x/tools/go/types/typeutil",
+    srcs = [":golang.org/x/tools__srcs[go/types/typeutil]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [":golang.org/x/tools/internal/typeparams"],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/typeparams",
+    package_name = "golang.org/x/tools/internal/typeparams",
+    srcs = [":golang.org/x/tools__srcs[internal/typeparams]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+    deps = [":golang.org/x/tools/internal/aliases"],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/stdlib",
+    package_name = "golang.org/x/tools/internal/stdlib",
+    srcs = [":golang.org/x/tools__srcs[internal/stdlib]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/versions",
+    package_name = "golang.org/x/tools/internal/versions",
+    srcs = [":golang.org/x/tools__srcs[internal/versions]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+)
+
+prelude.go_library(
+    name = "golang.org/x/tools/internal/pkgbits",
+    package_name = "golang.org/x/tools/internal/pkgbits",
+    srcs = [":golang.org/x/tools__srcs[internal/pkgbits]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+)
+
+prelude.http_archive(
+    name = "golang.org/x/mod__srcs",
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    sha1 = "d51ef52b9d2d7c76b23c12ab0839aa86b170fd67",
+    strip_prefix = "golang.org/x/mod@v0.25.0",
+    sub_targets = {
+        "semver": [
+            "semver/semver.go",
+        ],
+    },
+    urls = ["https://proxy.golang.org/golang.org/x/mod/@v/v0.25.0.zip"],
+)
+
+prelude.go_library(
+    name = "golang.org/x/mod/semver",
+    package_name = "golang.org/x/mod/semver",
+    srcs = [":golang.org/x/mod__srcs[semver]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+)
+
+prelude.http_archive(
+    name = "golang.org/x/sync__srcs",
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    sha1 = "ee6b73cda3ce9a52bcc8d54088fc5d0773356dd1",
+    strip_prefix = "golang.org/x/sync@v0.15.0",
+    sub_targets = {
+        "errgroup": [
+            "errgroup/errgroup.go",
+        ],
+    },
+    urls = ["https://proxy.golang.org/golang.org/x/sync/@v/v0.15.0.zip"],
+)
+
+prelude.go_library(
+    name = "golang.org/x/sync/errgroup",
+    package_name = "golang.org/x/sync/errgroup",
+    srcs = [":golang.org/x/sync__srcs[errgroup]"],
+    # @oss-disable[end= ]: labels = [ci.skip_target()],
+    visibility = ["prelude//go/tools/gopackagesdriver/..."],
+)
diff --git a/buck2/prelude/go/tools/list_tests.go b/buck2/prelude/go/tools/list_tests.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/list_tests.go
@@ -0,0 +1,196 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+// Lists Go test, benchmark, fuzz target and example names from `*_test.go`
+// source files without compiling or running the test binary. Output is one
+// name per line on stdout. Mirrors `go test -list <regex>` semantics:
+// detection rules and ordering match `cmd/go/internal/load.isTest` and the
+// `testing.MainStart` slice population done by testmaingen.go in this same
+// directory.
+//
+// Used by TPX for static test listing. For the same source set and the same
+// `-match` regex, the output is identical to what
+// `<test_binary> -test.list=<regex>` would print.
+
+package main
+
+import (
+	"bufio"
+	"flag"
+	"fmt"
+	"go/ast"
+	"go/doc"
+	"go/parser"
+	"go/token"
+	"log"
+	"os"
+	"regexp"
+	"strings"
+	"unicode"
+	"unicode/utf8"
+)
+
+var matchRegex = flag.String("match", "",
+	"Regex to filter names. Empty matches all. Mirrors `go test -list`.")
+
+// Resolve argsfiles in args (e.g. `@file.txt`). Matches testmaingen's helper.
+func loadArgs(args []string) []string {
+	newArgs := make([]string, 0, len(args))
+	for _, arg := range args {
+		if !strings.HasPrefix(arg, "@") {
+			newArgs = append(newArgs, arg)
+			continue
+		}
+		file, err := os.Open(arg[1:])
+		if err != nil {
+			log.Fatalln("Could not open argsfile:", err)
+		}
+		scanner := bufio.NewScanner(file)
+		for scanner.Scan() {
+			newArgs = append(newArgs, scanner.Text())
+		}
+		if err := scanner.Err(); err != nil {
+			log.Fatalln("Could not read argsfile:", err)
+		}
+		file.Close()
+	}
+	return newArgs
+}
+
+// isTest reports whether name has the given test-kind prefix (Test, Benchmark,
+// Fuzz) and isn't followed by a lowercase letter. Matches Go's
+// `cmd/go/internal/load.isTest`: "Testing" is excluded, "Test" / "TestX" /
+// "Test_X" / "Test123" are accepted.
+func isTest(name, prefix string) bool {
+	if !strings.HasPrefix(name, prefix) {
+		return false
+	}
+	if len(name) == len(prefix) {
+		return true
+	}
+	r, _ := utf8.DecodeRuneInString(name[len(prefix):])
+	return !unicode.IsLower(r)
+}
+
+// isTestFunc reports whether fn has the signature `func F(_ *<pkg>.<arg>)`
+// where <arg> is T, B or F. Matches testmaingen's `isTestFunc`.
+func isTestFunc(fn *ast.FuncDecl, arg string) bool {
+	if fn.Recv != nil {
+		return false
+	}
+	if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 {
+		return false
+	}
+	if fn.Type.Params == nil || len(fn.Type.Params.List) != 1 {
+		return false
+	}
+	if len(fn.Type.Params.List[0].Names) > 1 {
+		return false
+	}
+	ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr)
+	if !ok {
+		return false
+	}
+	if name, ok := ptr.X.(*ast.Ident); ok && name.Name == arg {
+		return true
+	}
+	if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == arg {
+		return true
+	}
+	return false
+}
+
+// collectNames walks one parsed file and returns test/benchmark/fuzz/example
+// names in the order `testing.MainStart` registers them: tests first (source
+// order), then benchmarks, then fuzz targets, then examples.
+func collectNames(f *ast.File) []string {
+	var tests, benches, fuzzes, examples []string
+	for _, d := range f.Decls {
+		fn, ok := d.(*ast.FuncDecl)
+		if !ok {
+			continue
+		}
+		if fn.Recv != nil {
+			continue
+		}
+		name := fn.Name.Name
+		switch {
+		case name == "TestMain":
+			// TestMain(t *testing.T) is a regular test; TestMain(m *testing.M)
+			// is the binary entrypoint and is not listed. Mirrors testmaingen.
+			if isTestFunc(fn, "T") {
+				tests = append(tests, name)
+			}
+		case isTest(name, "Test"):
+			if isTestFunc(fn, "T") {
+				tests = append(tests, name)
+			}
+		case isTest(name, "Benchmark"):
+			if isTestFunc(fn, "B") {
+				benches = append(benches, name)
+			}
+		case isTest(name, "Fuzz"):
+			if isTestFunc(fn, "F") {
+				fuzzes = append(fuzzes, name)
+			}
+		}
+	}
+	// Examples via go/doc — same filter testmaingen applies: skip examples
+	// without expected output unless they were declared with empty output.
+	for _, e := range doc.Examples(f) {
+		if e.Output == "" && !e.EmptyOutput {
+			continue
+		}
+		examples = append(examples, "Example"+e.Name)
+	}
+	out := make([]string, 0, len(tests)+len(benches)+len(fuzzes)+len(examples))
+	out = append(out, tests...)
+	out = append(out, benches...)
+	out = append(out, fuzzes...)
+	out = append(out, examples...)
+	return out
+}
+
+func main() {
+	os.Args = loadArgs(os.Args)
+	flag.Parse()
+
+	var matcher *regexp.Regexp
+	if *matchRegex != "" {
+		var err error
+		matcher, err = regexp.Compile(*matchRegex)
+		if err != nil {
+			log.Fatalln("Invalid -match regex:", err)
+		}
+	}
+
+	fset := token.NewFileSet()
+	bw := bufio.NewWriter(os.Stdout)
+
+	for _, filename := range flag.Args() {
+		f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments|parser.SkipObjectResolution)
+		if err != nil {
+			log.Fatalln("Could not parse:", err)
+		}
+		names := collectNames(f)
+		for _, n := range names {
+			if matcher != nil && !matcher.MatchString(n) {
+				continue
+			}
+			if _, err := fmt.Fprintln(bw, n); err != nil {
+				log.Fatalln("Could not write name:", err)
+			}
+		}
+	}
+
+	if err := bw.Flush(); err != nil {
+		log.Fatalln("Could not flush stdout:", err)
+	}
+}
diff --git a/buck2/prelude/go/tools/pkg_analyzer.go b/buck2/prelude/go/tools/pkg_analyzer.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/pkg_analyzer.go
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+// pkg_analyzer is a tool that provides package analysis generation
+// for Go packages. It serves as a replacement for "go list" in Buck2 builds,
+// providing the exact output format expected by go_list.bzl.
+//
+// Usage:
+//
+//	pkg_analyzer [flags] <directory>
+package main
+
+import (
+	"encoding/json"
+	"errors"
+	"flag"
+	"fmt"
+	"go/build"
+	"os"
+	"path/filepath"
+	"strings"
+)
+
+// AnalyzerOutput represents the unified JSON output containing both
+// go list results and embedcfg for the Go compiler.
+type AnalyzerOutput struct {
+	// Package information (matches go list -json output expected by go_list.bzl)
+	Name              string   `json:"Name"`
+	Imports           []string `json:"Imports,omitempty"`
+	TestImports       []string `json:"TestImports,omitempty"`
+	XTestImports      []string `json:"XTestImports,omitempty"`
+	GoFiles           []string `json:"GoFiles,omitempty"`
+	HFiles            []string `json:"HFiles,omitempty"`
+	CFiles            []string `json:"CFiles,omitempty"`
+	CXXFiles          []string `json:"CXXFiles,omitempty"`
+	CgoFiles          []string `json:"CgoFiles,omitempty"`
+	SFiles            []string `json:"SFiles,omitempty"`
+	TestGoFiles       []string `json:"TestGoFiles,omitempty"`
+	XTestGoFiles      []string `json:"XTestGoFiles,omitempty"`
+	IgnoredGoFiles    []string `json:"IgnoredGoFiles,omitempty"`
+	IgnoredOtherFiles []string `json:"IgnoredOtherFiles,omitempty"`
+	CgoCFLAGS         []string `json:"CgoCFLAGS,omitempty"`
+	CgoCPPFLAGS       []string `json:"CgoCPPFLAGS,omitempty"`
+	EmbedPatterns     []string `json:"EmbedPatterns,omitempty"`
+	TestEmbedPatterns []string `json:"TestEmbedPatterns,omitempty"`
+
+	// Error information (matches go list -e output)
+	Error *PackageError `json:"Error,omitempty"`
+}
+
+// PackageError describes an error loading information about a package.
+type PackageError struct {
+	Err string `json:"Err"`
+}
+
+func main() {
+	tags := flag.String("tags", "", "Build tags (comma-separated)")
+	cgoEnabled := flag.Bool("cgo", false, "Enable CGO")
+	withTests := flag.Bool("tests", false, "Include test files")
+	race := flag.Bool("race", false, "Enable race detection")
+	asan := flag.Bool("asan", false, "Enable address sanitizer")
+	goos := flag.String("goos", "", "Target GOOS (default: current OS)")
+	goarch := flag.String("goarch", "", "Target GOARCH (default: current arch)")
+	output := flag.String("o", "", "Output file (default: stdout)")
+	flag.Usage = func() {
+		fmt.Fprintf(os.Stderr, `Usage: pkg_analyzer [flags] <directory>
+
+Analyze a Go package and output JSON containing package information
+(matching go list -json format). Optionally outputs embedcfg for the
+Go compiler to a separate file via -embedcfg flag.
+
+Flags:
+`)
+		flag.PrintDefaults()
+	}
+
+	flag.Parse()
+
+	if flag.NArg() != 1 {
+		flag.Usage()
+		os.Exit(1)
+	}
+
+	dir := flag.Arg(0)
+	absDir, err := filepath.Abs(dir)
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "pkg_analyzer: failed to resolve directory: %v\n", err)
+		os.Exit(1)
+	}
+
+	// Build the context with the specified settings
+	ctx := build.Default
+	if *goos != "" {
+		ctx.GOOS = *goos
+	}
+	if *goarch != "" {
+		ctx.GOARCH = *goarch
+	}
+	ctx.CgoEnabled = *cgoEnabled
+
+	// Parse build tags
+	var buildTags []string
+	if *tags != "" {
+		buildTags = strings.Split(*tags, ",")
+	}
+	if *race {
+		buildTags = append(buildTags, "race")
+	}
+	if *asan {
+		buildTags = append(buildTags, "asan")
+	}
+	ctx.BuildTags = buildTags
+
+	// Import the package
+	pkg, err := ctx.ImportDir(absDir, build.ImportComment|build.IgnoreVendor)
+	var pkgErr *PackageError
+	if err != nil {
+		var noGoErr *build.NoGoError
+		if errors.As(err, &noGoErr) {
+			// TODO(michaelpo): Skip unil we are ready to handle no-go errors.
+			// We likely be skippling this in the future as well and return an error directly in the build-rules.
+		} else {
+			pkgErr = &PackageError{
+				Err: err.Error(),
+			}
+		}
+	}
+
+	// Build the output
+	out := AnalyzerOutput{
+		Name:              pkg.Name,
+		Imports:           pkg.Imports,
+		GoFiles:           pkg.GoFiles,
+		CgoFiles:          pkg.CgoFiles,
+		HFiles:            pkg.HFiles,
+		CFiles:            pkg.CFiles,
+		CXXFiles:          pkg.CXXFiles,
+		SFiles:            pkg.SFiles,
+		IgnoredGoFiles:    pkg.IgnoredGoFiles,
+		IgnoredOtherFiles: pkg.IgnoredOtherFiles,
+		CgoCFLAGS:         pkg.CgoCFLAGS,
+		CgoCPPFLAGS:       pkg.CgoCPPFLAGS,
+		EmbedPatterns:     pkg.EmbedPatterns,
+		Error:             pkgErr,
+	}
+
+	// Include test files if requested
+	if *withTests {
+		out.TestGoFiles = pkg.TestGoFiles
+		out.XTestGoFiles = pkg.XTestGoFiles
+		out.TestImports = pkg.TestImports
+		out.TestEmbedPatterns = pkg.TestEmbedPatterns
+	}
+
+	jsonData, err := json.MarshalIndent(out, "", "\t")
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "pkg_analyzer: failed to marshal JSON: %v\n", err)
+		os.Exit(1)
+	}
+
+	if *output != "" {
+		if err := os.WriteFile(*output, jsonData, 0644); err != nil {
+			fmt.Fprintf(os.Stderr, "pkg_analyzer: failed to write output file: %v\n", err)
+			os.Exit(1)
+		}
+	} else {
+		fmt.Println(string(jsonData))
+	}
+}
diff --git a/buck2/prelude/go/tools/testmaingen.go b/buck2/prelude/go/tools/testmaingen.go
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/tools/testmaingen.go
@@ -0,0 +1,453 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+// Generates testmain.go files from a group of test files.
+//
+// Regular go tests (ones run with `go test`) don't actually define a main
+// package. Moreover, Go's reflection does not have the ability to inspect
+// packages (e.g. list functions). This script generates a main.go that
+// runs some set of tests passed in on the CLI. The code liberally borrows from
+// the `go test` implementation at https://github.com/golang/go/blob/master/src/cmd/go/test.go
+
+package main
+
+import (
+	"bufio"
+	"errors"
+	"flag"
+	"fmt"
+	"go/ast"
+	"go/doc"
+	"go/parser"
+	"go/token"
+	"log"
+	"maps"
+	"os"
+	"slices"
+	"sort"
+	"strings"
+	"text/template"
+	"unicode"
+	"unicode/utf8"
+)
+
+// A helper flag that takes a comma-separated list of strings and
+// converts it to a "set" (map). The boolean value is meaningless.
+// Example: --foo=bar,baz,bar
+// Result: map[string]bool{"foo": true, "baz": true, "bar": true}
+type stringSetFlag map[string]bool
+
+// Set implements the flag.Value interface for stringSetFlag
+func (s stringSetFlag) Set(value string) error {
+	for _, item := range strings.Split(value, ",") {
+		s[item] = true
+	}
+	return nil
+}
+
+// String implements the flag.Value interface for stringSetFlag
+func (s stringSetFlag) String() string {
+	return strings.Join(slices.Collect(maps.Keys(s)), ",")
+}
+
+// Flags
+var (
+	pkgImportPath string
+	outputFile    string
+	testCoverMode string
+	coverPkgs     = make(stringSetFlag)
+)
+
+func init() {
+	flag.StringVar(&pkgImportPath, "import-path", "test", "The import path in the test file")
+	flag.StringVar(&outputFile, "output", "", "The path to the output file. Default to stdout.")
+	flag.Var(&coverPkgs, "cover-pkgs", "A comma-separated list of packages to gather coverage info on")
+	flag.StringVar(&testCoverMode, "cover-mode", "", "Cover mode (see `go tool cover`)")
+}
+
+// Resolve argsfiles in args (e.g. `@file.txt`).
+func loadArgs(args []string) []string {
+	newArgs := make([]string, 0, 0)
+	for _, arg := range args {
+		if !strings.HasPrefix(arg, "@") {
+			newArgs = append(newArgs, arg)
+		} else {
+			file, _ := os.Open(arg[1:])
+			defer file.Close()
+			scanner := bufio.NewScanner(file)
+			for scanner.Scan() {
+				newArgs = append(newArgs, scanner.Text())
+			}
+		}
+	}
+	return newArgs
+}
+
+func main() {
+	os.Args = loadArgs(os.Args)
+	flag.Parse()
+
+	pkgs := make([]*Package, 0, len(coverPkgs))
+	testCoverPaths := make([]string, 0, len(coverPkgs))
+	for importPath := range coverPkgs {
+		pkg := &Package{ImportPath: importPath}
+		pkgs = append(pkgs, pkg)
+		testCoverPaths = append(testCoverPaths, importPath)
+	}
+
+	testFuncs, err := loadTestFuncsFromFiles(pkgImportPath, flag.Args())
+	if err != nil {
+		log.Fatalln("Could not read test files:", err)
+	}
+	// Coverage enabled
+	if testCoverMode != "" {
+		testFuncs.Cover = &TestCover{
+			Pkgs:  pkgs,
+			Paths: testCoverPaths,
+			Mode:  testCoverMode,
+		}
+	}
+
+	out := os.Stdout
+	if outputFile != "" {
+		out, err = os.Create(outputFile)
+		if err != nil {
+			log.Fatalln("Could not write test main:", err)
+		}
+	}
+
+	if err := testmainTmplNewCoverage.Execute(out, testFuncs); err != nil {
+		log.Fatalln("Failed to generate main file:", err)
+	}
+}
+
+func loadTestFuncsFromFiles(packageImportPath string, files []string) (*testFuncs, error) {
+	t := &testFuncs{
+		Package: &Package{
+			ImportPath: packageImportPath,
+		},
+	}
+	for _, filename := range files {
+		if err := t.load(filename, "_test", &t.ImportTest, &t.NeedTest); err != nil {
+			return nil, err
+		}
+	}
+	return t, nil
+}
+
+//
+//
+//
+// Most of the code below is a direct copy from the 'go test' command:
+//   https://github.com/golang/go/blob/release-branch.go1.24/src/cmd/go/internal/load/test.go
+//
+//
+//
+
+// This is a fake version of the actual Package type, since we don't really need all
+// ~300 fields of it.
+type Package struct {
+	ImportPath string `json:",omitempty"` // import path of package in dir
+}
+
+// isTestFunc tells whether fn has the type of a testing function. arg
+// specifies the parameter type we look for: B, F, M or T.
+func isTestFunc(fn *ast.FuncDecl, arg string) bool {
+	if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 ||
+		fn.Type.Params.List == nil ||
+		len(fn.Type.Params.List) != 1 ||
+		len(fn.Type.Params.List[0].Names) > 1 {
+		return false
+	}
+	ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr)
+	if !ok {
+		return false
+	}
+	// We can't easily check that the type is *testing.M
+	// because we don't know how testing has been imported,
+	// but at least check that it's *M or *something.M.
+	// Same applies for B, F and T.
+	if name, ok := ptr.X.(*ast.Ident); ok && name.Name == arg {
+		return true
+	}
+	if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == arg {
+		return true
+	}
+	return false
+}
+
+// isTest tells whether name looks like a test (or benchmark, according to prefix).
+// It is a Test (say) if there is a character after Test that is not a lower-case letter.
+// We don't want TesticularCancer.
+func isTest(name, prefix string) bool {
+	if !strings.HasPrefix(name, prefix) {
+		return false
+	}
+	if len(name) == len(prefix) { // "Test" is ok
+		return true
+	}
+	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
+	return !unicode.IsLower(rune)
+}
+
+type TestCover struct {
+	Mode  string
+	Local bool
+	Pkgs  []*Package
+	Paths []string
+}
+
+// CoverVar holds the name of the generated coverage variables targeting the named file.
+type CoverVar struct {
+	File string // local file name
+	Var  string // name of count struct
+}
+
+type testFuncs struct {
+	Tests       []testFunc
+	Benchmarks  []testFunc
+	FuzzTargets []testFunc
+	Examples    []testFunc
+	TestMain    *testFunc
+	Package     *Package
+	ImportTest  bool
+	NeedTest    bool
+	ImportXtest bool
+	NeedXtest   bool
+	Cover       *TestCover
+}
+
+// ImportPath returns the import path of the package being tested, if it is within GOPATH.
+// This is printed by the testing package when running benchmarks.
+func (t *testFuncs) ImportPath() string {
+	pkg := t.Package.ImportPath
+	if strings.HasPrefix(pkg, "_/") {
+		return ""
+	}
+	if pkg == "command-line-arguments" {
+		return ""
+	}
+	return pkg
+}
+
+// Covered returns a string describing which packages are being tested for coverage.
+// If the covered package is the same as the tested package, it returns the empty string.
+// Otherwise it is a comma-separated human-readable list of packages beginning with
+// " in", ready for use in the coverage message.
+func (t *testFuncs) Covered() string {
+	if t.Cover == nil || t.Cover.Paths == nil {
+		return ""
+	}
+	return " in " + strings.Join(t.Cover.Paths, ", ")
+}
+
+func (t *testFuncs) CoverSelectedPackages() string {
+	if t.Cover == nil || t.Cover.Paths == nil {
+		return `[]string{"` + t.Package.ImportPath + `"}`
+	}
+	var sb strings.Builder
+	fmt.Fprintf(&sb, "[]string{")
+	for k, p := range t.Cover.Pkgs {
+		if k != 0 {
+			sb.WriteString(", ")
+		}
+		fmt.Fprintf(&sb, `"%s"`, p.ImportPath)
+	}
+	sb.WriteString("}")
+	return sb.String()
+}
+
+type testFunc struct {
+	Package   string // imported package name (_test or _xtest)
+	Name      string // function name
+	Output    string // output, for examples
+	Unordered bool   // output is allowed to be unordered.
+}
+
+var testFileSet = token.NewFileSet()
+
+func (t *testFuncs) load(filename, pkg string, doImport, seen *bool) error {
+	// Pass in the overlaid source if we have an overlay for this file.
+	src, err := os.Open(filename)
+	if err != nil {
+		return err
+	}
+	defer src.Close()
+	f, err := parser.ParseFile(testFileSet, filename, src, parser.ParseComments|parser.SkipObjectResolution)
+	if err != nil {
+		return err
+	}
+	for _, d := range f.Decls {
+		n, ok := d.(*ast.FuncDecl)
+		if !ok {
+			continue
+		}
+		if n.Recv != nil {
+			continue
+		}
+		name := n.Name.String()
+		switch {
+		case name == "TestMain":
+			if isTestFunc(n, "T") {
+				t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
+				*doImport, *seen = true, true
+				continue
+			}
+			err := checkTestFunc(n, "M")
+			if err != nil {
+				return err
+			}
+			if t.TestMain != nil {
+				return errors.New("multiple definitions of TestMain")
+			}
+			t.TestMain = &testFunc{pkg, name, "", false}
+			*doImport, *seen = true, true
+		case isTest(name, "Test"):
+			err := checkTestFunc(n, "T")
+			if err != nil {
+				return err
+			}
+			t.Tests = append(t.Tests, testFunc{pkg, name, "", false})
+			*doImport, *seen = true, true
+		case isTest(name, "Benchmark"):
+			err := checkTestFunc(n, "B")
+			if err != nil {
+				return err
+			}
+			t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, "", false})
+			*doImport, *seen = true, true
+		case isTest(name, "Fuzz"):
+			err := checkTestFunc(n, "F")
+			if err != nil {
+				return err
+			}
+			t.FuzzTargets = append(t.FuzzTargets, testFunc{pkg, name, "", false})
+			*doImport, *seen = true, true
+		}
+	}
+	ex := doc.Examples(f)
+	sort.Slice(ex, func(i, j int) bool { return ex[i].Order < ex[j].Order })
+	for _, e := range ex {
+		*doImport = true // import test file whether executed or not
+		if e.Output == "" && !e.EmptyOutput {
+			// Don't run examples with no output.
+			continue
+		}
+		t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output, e.Unordered})
+		*seen = true
+	}
+	return nil
+}
+
+func checkTestFunc(fn *ast.FuncDecl, arg string) error {
+	var why string
+	if !isTestFunc(fn, arg) {
+		why = fmt.Sprintf("must be: func %s(%s *testing.%s)", fn.Name.String(), strings.ToLower(arg), arg)
+	}
+	if fn.Type.TypeParams.NumFields() > 0 {
+		why = "test functions cannot have type parameters"
+	}
+	if why != "" {
+		pos := testFileSet.Position(fn.Pos())
+		return fmt.Errorf("%s: wrong signature for %s, %s", pos, fn.Name.String(), why)
+	}
+	return nil
+}
+
+var testmainTmplNewCoverage = template.Must(template.New("main").Parse(`
+// Code generated by 'go test'. DO NOT EDIT.
+
+package main
+
+import (
+	"fmt"
+	"os"
+	"path/filepath"
+{{if .TestMain}}
+	"reflect"
+{{end}}
+	"testing"
+	"testing/internal/testdeps"
+{{if .Cover}}
+	"internal/coverage/cfile"
+{{end}}
+
+{{if .ImportTest}}
+	{{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "%q"}}
+{{end}}
+{{if .ImportXtest}}
+	{{if .NeedXtest}}_xtest{{else}}_{{end}} {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
+{{end}}
+)
+
+var tests = []testing.InternalTest{
+{{range .Tests}}
+	{"{{.Name}}", {{.Package}}.{{.Name}}},
+{{end}}
+}
+
+var benchmarks = []testing.InternalBenchmark{
+{{range .Benchmarks}}
+	{"{{.Name}}", {{.Package}}.{{.Name}}},
+{{end}}
+}
+
+var fuzzTargets = []testing.InternalFuzzTarget{
+{{range .FuzzTargets}}
+	{"{{.Name}}", {{.Package}}.{{.Name}}},
+{{end}}
+}
+
+var examples = []testing.InternalExample{
+{{range .Examples}}
+	{"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}, {{.Unordered}}},
+{{end}}
+}
+
+func init() {
+{{if .Cover}}
+	testdeps.CoverMode = {{printf "%q" .Cover.Mode}}
+	testdeps.Covered = {{printf "%q" .Covered}}
+	testdeps.CoverSelectedPackages = {{printf "%s" .CoverSelectedPackages}}
+	testdeps.CoverSnapshotFunc = cfile.Snapshot
+	testdeps.CoverProcessTestDirFunc = cfile.ProcessCoverTestDir
+	testdeps.CoverMarkProfileEmittedFunc = cfile.MarkProfileEmitted
+
+{{end}}
+	testdeps.ImportPath = {{.ImportPath | printf "%q"}}
+}
+
+func main() {
+	// Buck ensures that resources defined on the test targets live in the same
+	// directory as the binary. We change the working directory to this
+	// directory to make sure that tests can read test fixtures relative to the
+	// current working directory. This matches behavior with "go test" from the
+	// test author perspective.
+	execPath, err := os.Executable()
+	if err != nil {
+		os.Stderr.WriteString("Unable to get path to test binary executable.")
+		os.Exit(1)
+	}
+	execDir := filepath.Dir(execPath)
+	err = os.Chdir(execDir)
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Failed to change directory to %s.", execDir)
+		os.Exit(1)
+	}
+	m := testing.MainStart(testdeps.TestDeps{}, tests, benchmarks, fuzzTargets, examples)
+{{with .TestMain}}
+	{{.Package}}.{{.Name}}(m)
+	os.Exit(int(reflect.ValueOf(m).Elem().FieldByName("exitCode").Int()))
+{{else}}
+	os.Exit(m.Run())
+{{end}}
+}
+
+`))
diff --git a/buck2/prelude/go/transitions/defs.bzl b/buck2/prelude/go/transitions/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/transitions/defs.bzl
@@ -0,0 +1,183 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//go:coverage.bzl", "GoCoverageMode")
+load(":tags_helper.bzl", "selects_for_tags", "tag_to_constraint_value")
+
+def _cgo_enabled_transition(platform, refs, attrs):
+    # If attribute is None, do nothing
+    if attrs.cgo_enabled == None:
+        return platform
+
+    # Override configuration with attribute value
+    configuration = platform.configuration
+    if attrs.cgo_enabled == True:
+        cgo_enabled_value = refs.cgo_enabled_true[ConstraintValueInfo]
+    else:
+        cgo_enabled_value = refs.cgo_enabled_false[ConstraintValueInfo]
+
+    configuration.insert(cgo_enabled_value)
+
+    return PlatformInfo(
+        label = platform.label,
+        configuration = configuration,
+    )
+
+def _coverage_mode_transition(platform, refs, attrs):
+    # If attribute is None, do nothing
+    if attrs.coverage_mode == None:
+        return platform
+
+    # Override configuration with attribute value
+    configuration = platform.configuration
+    if attrs.coverage_mode == "set":
+        coverage_mode_value = refs.coverage_mode_set[ConstraintValueInfo]
+    elif attrs.coverage_mode == "count":
+        coverage_mode_value = refs.coverage_mode_count[ConstraintValueInfo]
+    elif attrs.coverage_mode == "atomic":
+        coverage_mode_value = refs.coverage_mode_atomic[ConstraintValueInfo]
+    else:
+        fail("`coverage_mode` can be either: 'set', 'count', 'atomic' or None, got: {}".format(attrs.coverage_mode))
+
+    configuration.insert(coverage_mode_value)
+
+    return PlatformInfo(
+        label = platform.label,
+        configuration = configuration,
+    )
+
+def _tags_transition(platform, refs, attrs):
+    # If no build tags, do nothing
+    if not attrs.build_tags:
+        return platform
+
+    # Override configuration with attribute values
+    configuration = platform.configuration
+    for build_tag in attrs.build_tags:
+        ref_name = "tag_{}__set".format(build_tag)
+        if not hasattr(refs, ref_name):
+            fail("Add build_tag '{}' to .buckconfig attribute `go.allowed_build_tags` to allow using it".format(build_tag))
+
+        tag_value = getattr(refs, ref_name)[ConstraintValueInfo]
+        configuration.insert(tag_value)
+
+    return PlatformInfo(
+        label = platform.label,
+        configuration = configuration,
+    )
+
+def _force_mingw_on_windows(platform, refs, _):
+    constraints = platform.configuration.constraints
+
+    abi_gnu_value = refs.abi_gnu[ConstraintValueInfo]
+    if abi_gnu_value.setting.label in constraints and constraints[abi_gnu_value.setting.label] == abi_gnu_value:
+        # Already MinGW/GNU, do nothing
+        return platform
+
+    os_windows_value = refs.os_windows[ConstraintValueInfo]
+    if os_windows_value.setting.label in constraints and constraints[os_windows_value.setting.label] != os_windows_value:
+        # Non-Windows, do nothing
+        return platform
+
+    constraints[abi_gnu_value.setting.label] = abi_gnu_value
+
+    new_cfg = ConfigurationInfo(
+        constraints = constraints,
+        values = platform.configuration.values,
+    )
+
+    return PlatformInfo(
+        label = platform.label,
+        configuration = new_cfg,
+    )
+
+def _chain_transitions(transitions):
+    def tr(platform, refs, attrs):
+        for t in transitions:
+            platform = t(platform, refs, attrs)
+        return platform
+
+    return tr
+
+_all_level_transitions = [_force_mingw_on_windows]
+_top_level_transitions = [_cgo_enabled_transition, _tags_transition] + _all_level_transitions
+
+_all_level_refs = {
+    "abi_gnu": "prelude//abi/constraints:gnu",
+    "os_windows": "config//os/constraints:windows",
+}
+
+_top_level_refs = (
+    {
+        "cgo_enabled_false": "prelude//go/constraints:cgo_enabled[false]",
+        "cgo_enabled_true": "prelude//go/constraints:cgo_enabled[true]",
+    }
+    | {"tag_{}__set".format(tag): constraint_value for tag, constraint_value in tag_to_constraint_value().items()}
+    | _all_level_refs
+)
+
+_attrs = ["cgo_enabled", "build_tags"]
+
+_coverage_mode_refs = {
+    "coverage_mode_atomic": "prelude//go/constraints:coverage_mode[atomic]",
+    "coverage_mode_count": "prelude//go/constraints:coverage_mode[count]",
+    "coverage_mode_set": "prelude//go/constraints:coverage_mode[set]",
+}
+
+go_binary_transition = transition(
+    impl = _chain_transitions(_top_level_transitions + [_coverage_mode_transition]),
+    refs = _top_level_refs | _coverage_mode_refs,
+    attrs = _attrs + ["coverage_mode"],
+)
+
+go_test_transition = transition(
+    impl = _chain_transitions(_top_level_transitions + [_coverage_mode_transition]),
+    refs = _top_level_refs | _coverage_mode_refs,
+    attrs = _attrs + ["coverage_mode"],
+)
+
+go_exported_library_transition = transition(
+    impl = _chain_transitions(_top_level_transitions),
+    refs = _top_level_refs,
+    attrs = _attrs,
+)
+
+go_library_transition = transition(
+    impl = _chain_transitions(_all_level_transitions),
+    refs = _all_level_refs,
+    attrs = [],
+)
+
+go_stdlib_transition = transition(
+    impl = _chain_transitions(_all_level_transitions),
+    refs = _all_level_refs,
+    attrs = [],
+)
+
+cgo_enabled_attr = attrs.default_only(
+    attrs.bool(
+        default = select({
+            "prelude//go/constraints:cgo_enabled[false]": False,
+            "prelude//go/constraints:cgo_enabled[true]": True,
+        })
+    ),
+)
+
+coverage_mode_attr = attrs.default_only(
+    attrs.option(
+        attrs.enum(GoCoverageMode.values()),
+        default = select({
+            "prelude//go/constraints:coverage_mode[atomic]": "atomic",
+            "prelude//go/constraints:coverage_mode[count]": "count",
+            "prelude//go/constraints:coverage_mode[none]": None,
+            "prelude//go/constraints:coverage_mode[set]": "set",
+        }),
+    )
+)
+
+build_tags_attr = attrs.default_only(attrs.list(attrs.string(), default = selects_for_tags()))
diff --git a/buck2/prelude/go/transitions/tags_helper.bzl b/buck2/prelude/go/transitions/tags_helper.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go/transitions/tags_helper.bzl
@@ -0,0 +1,24 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:buckconfig.bzl", "read_list")
+
+allowed_build_tags = read_list("go", "allowed_build_tags", default = [], root_cell = True)
+
+def tag_to_constraint_value():
+    return {tag: "prelude//go/tags/constraints:{}[set]".format(tag) for tag in allowed_build_tags}
+
+def selects_for_tags():
+    selects = []
+    for tag in allowed_build_tags:
+        selects += select({
+            "prelude//go/tags/constraints:{}[set]".format(tag): [tag],
+            "prelude//go/tags/constraints:{}[unset]".format(tag): [],
+        })
+
+    return selects
diff --git a/buck2/prelude/go_bootstrap/go_bootstrap.bzl b/buck2/prelude/go_bootstrap/go_bootstrap.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go_bootstrap/go_bootstrap.bzl
@@ -0,0 +1,73 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+
+GoBootstrapDistrInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "bin_go": provider_field(RunInfo),
+        "go_root": provider_field(Artifact | None),
+    },
+)
+GoBootstrapToolchainInfo = provider(
+    fields = {
+        "env_go_arch": provider_field(str),
+        "env_go_os": provider_field(str),
+        "env_go_root": provider_field(Artifact | None, default = None),
+        "go": provider_field(RunInfo),
+        "go_wrapper": provider_field(RunInfo),
+    },
+)
+
+def go_bootstrap_binary_impl(ctx: AnalysisContext) -> list[Provider]:
+    """
+    Produces a Go binary for use in prelude. Similar to `python_bootstrap_binary`
+    It doesn't depend on other Go rules and uses `go build` under the hood.
+    CGo is disabled minimise dependencies.
+    """
+    go_toolchain = ctx.attrs._go_bootstrap_toolchain[GoBootstrapToolchainInfo]
+
+    target_is_win = go_toolchain.env_go_os == "windows"
+    exe_suffix = ".exe" if target_is_win else ""
+    output = ctx.actions.declare_output(ctx.label.name + exe_suffix, has_content_based_path = True)
+
+    # Copy files, because go:embed doesn't work with symlinks
+    srcs_dir = ctx.actions.copied_dir(
+        "__srcs_dir__",
+        {paths.relativize(src.short_path, ctx.attrs.workdir): src for src in ctx.attrs.srcs},
+        has_content_based_path = True,
+    )
+
+    cmd = cmd_args([
+        go_toolchain.go_wrapper,
+        go_toolchain.go,
+        ["--workdir", srcs_dir],
+        "build",
+        "-trimpath",
+        ["-o", cmd_args(output.as_output(), relative_to = srcs_dir)],
+        ctx.attrs.build_args,
+    ])
+
+    env = {
+        "CGO_ENABLED": "0",
+        "GO111MODULE": "",
+        "GOARCH": go_toolchain.env_go_arch,
+        "GOOS": go_toolchain.env_go_os,
+        "GOTOOLCHAIN": "local",
+    }
+
+    if go_toolchain.env_go_root != None:
+        env["GOROOT"] = go_toolchain.env_go_root
+
+    ctx.actions.run(cmd, env = env, category = "go_bootstrap_binary")
+
+    return [
+        DefaultInfo(default_output = output),
+        RunInfo(args = [output]),
+    ]
diff --git a/buck2/prelude/go_bootstrap/tools/BUCK b/buck2/prelude/go_bootstrap/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go_bootstrap/tools/BUCK
@@ -0,0 +1,22 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "go_wrapper_py",
+    main = "go_wrapper.py",
+    visibility = ["PUBLIC"],
+)
+
+# Type checking target for Python tool scripts
+prelude.python_library(
+    name = "scripts-typing",
+    srcs = [
+        "go_wrapper.py",
+    ],
+    typing = True,
+)
diff --git a/buck2/prelude/go_bootstrap/tools/go_wrapper.py b/buck2/prelude/go_bootstrap/tools/go_wrapper.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/go_bootstrap/tools/go_wrapper.py
@@ -0,0 +1,93 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import os
+import shlex
+import subprocess
+import sys
+from pathlib import Path
+
+
+# A copy of "cmd/internal/quoted" translated into Python with GPT-4
+# Source: https://github.com/golang/go/blob/7e9894449e8a12157a28a4a14fc9341353a6469c/src/cmd/internal/quoted/quoted.go#L65
+def go_join(args):
+    buf = []
+    for i, arg in enumerate(args):
+        if i > 0:
+            buf.append(" ")
+        saw_space, saw_single_quote, saw_double_quote = False, False, False
+        for c in arg:
+            if ord(c) > 127:
+                continue
+            elif c.isspace():
+                saw_space = True
+            elif c == "'":
+                saw_single_quote = True
+            elif c == '"':
+                saw_double_quote = True
+        if not saw_space and not saw_single_quote and not saw_double_quote:
+            buf.append(arg)
+        elif not saw_single_quote:
+            buf.append("'")
+            buf.append(arg)
+            buf.append("'")
+        elif not saw_double_quote:
+            buf.append('"')
+            buf.append(arg)
+            buf.append('"')
+        else:
+            raise ValueError(
+                f"Argument {arg} contains both single and double quotes and cannot be quoted"
+            )
+    return "".join(buf)
+
+
+def main(argv):
+    """
+    This is a wrapper script around the `go` binary.
+    - It fixes GOROOT and GOCACHE
+    """
+    if len(argv) < 2:
+        print("usage: go_wrapper.py <wrapped binary> <args>", file=sys.stderr)
+        return 1
+
+    wrapped_binary = Path(argv[1]).resolve()
+
+    parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
+    parser.add_argument("--workdir", type=Path, default=None)
+    parser.add_argument("--output", type=argparse.FileType("w"), default=sys.stdout)
+    parsed, unknown = parser.parse_known_args(argv[2:])
+
+    env = os.environ.copy()
+    # Make paths absolute, otherwise go build will fail.
+    if "GOROOT" in env:
+        env["GOROOT"] = os.path.realpath(env["GOROOT"])
+
+    env["GOCACHE"] = os.path.realpath(env["BUCK_SCRATCH_PATH"])
+
+    cwd = os.getcwd()
+    for env_var in ["CC", "CGO_CFLAGS", "CGO_CPPFLAGS", "CGO_LDFLAGS"]:
+        if env_var in env:
+            # HACK: Split the value into a list of arguments then join them back.
+            # This is because buck encodes quoted args in a way `go` doesn't like,
+            # but `go_join` does it in a way that `go` expects.
+            var_value = go_join(shlex.split(env[env_var]))
+            # HACK: Replace %cwd% with the current working directory to make it work when `go` does `cd` to a tmp-dir.
+            env[env_var] = var_value.replace("%cwd%", cwd)
+
+    unknown = [arg.replace("%cwd%", cwd) for arg in unknown]
+
+    retcode = subprocess.call(
+        [wrapped_binary] + unknown, env=env, cwd=parsed.workdir, stdout=parsed.output
+    )
+    parsed.output.close()
+    return retcode
+
+
+sys.exit(main(sys.argv))
diff --git a/buck2/prelude/graphql/graphql.bzl b/buck2/prelude/graphql/graphql.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/graphql/graphql.bzl
@@ -0,0 +1,95 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+    "make_artifact_tset",
+)
+load(
+    "@prelude//cxx:cxx_library_utility.bzl",
+    "cxx_attr_deps",
+    "cxx_attr_exported_deps",
+)
+
+GraphQLiOSInfo = record(
+    header_path_prefix = str | None,
+    force_export_fragment_headers = bool,
+    fragment_models_use_classes = bool,
+    use_implicit_codegen = bool,
+)
+
+GraphQLAndroidInfo = record(
+    allow_legacy_fragments = bool,
+    allow_type_models = bool,
+    composition_mode = str | None,
+    enable_associated_library = bool,
+    use_implicit_codegen = bool,
+)
+
+GraphQLCxxInfo = record(
+    use_implicit_codegen = bool,
+)
+
+GraphQLInfo = provider(
+    fields = {
+        "config_name": provider_field(str),
+        "enforce_colocation": provider_field(bool),
+        "is_subconfig": provider_field(bool),
+        "is_test_target": provider_field(bool),
+        "platform_config": provider_field(GraphQLAndroidInfo | GraphQLCxxInfo | GraphQLiOSInfo),
+        "srcs": provider_field(list[Artifact]),
+        "target": provider_field(Label),
+    },
+)
+
+GraphQLCodegenInput = provider(
+    fields = {
+        "artifacts": provider_field(ArtifactTSet),
+    },
+)
+
+GraphQLMobileConfigInput = provider(
+    fields = {
+        "artifacts": provider_field(ArtifactTSet),
+    },
+)
+
+def _graphql_info_provider(label: Label, deps: list[Dependency]) -> list[Provider]:
+    return [dep[GraphQLInfo] for dep in deps if GraphQLInfo in dep and dep[GraphQLInfo].target == label]
+
+def graphql_codegen_sets(deps: list[Dependency]) -> list[ArtifactTSet]:
+    return [dep[GraphQLCodegenInput].artifacts for dep in deps if GraphQLCodegenInput in dep]
+
+def graphql_mobileconfig_sets(deps: list[Dependency]) -> list[ArtifactTSet]:
+    return [dep[GraphQLMobileConfigInput].artifacts for dep in deps if GraphQLMobileConfigInput in dep]
+
+def graphql_providers(ctx: AnalysisContext) -> list[Provider]:
+    deps = cxx_attr_deps(ctx)
+    providers = _graphql_info_provider(ctx.label, deps)
+    if len(providers) > 1:
+        fail("Multiple GraphQLInfo providers found in deps of {}".format(ctx.label.raw_target()))
+
+    all_deps = deps + cxx_attr_exported_deps(ctx) + getattr(ctx.attrs, "runtime_deps", [])
+    output_sets = graphql_codegen_sets(all_deps)
+    if output_sets:
+        providers.append(
+            GraphQLCodegenInput(
+                artifacts = make_artifact_tset(actions = ctx.actions, children = output_sets),
+            ),
+        )
+
+    mobileconfig_sets = graphql_mobileconfig_sets(all_deps)
+    if mobileconfig_sets:
+        providers.append(
+            GraphQLMobileConfigInput(
+                artifacts = make_artifact_tset(actions = ctx.actions, children = mobileconfig_sets),
+            ),
+        )
+
+    return providers
diff --git a/buck2/prelude/haskell/advice.bxl b/buck2/prelude/haskell/advice.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/advice.bxl
@@ -0,0 +1,64 @@
+# A report of the advice in a set of targets' validation results (see Note
+# [Advice] in compile_per_module.bzl): for each validation that found
+# something, its explanation, then the message of each target it found
+# something in. Validations and targets with nothing to report are left out.
+#
+#     cat $(buck2 bxl prelude//haskell/advice.bxl:main -- --targets //...)
+#
+# It prints the path of the report. The targets must have been built, or are
+# built by this.
+
+def _report_impl(bxl_ctx: bxl.Context, results: dict[Label, dict[str, ArtifactValue]], output: OutputArtifact):
+    by_name = {}
+    for target, validations in results.items():
+        for name, value in validations.items():
+            data = value.read_json()["data"]
+            if data.get("findings"):
+                by_name.setdefault(name, struct(explanation = data.get("explanation"), lines = []))
+                by_name[name].lines.append((str(target.raw_target()), data["message"]))
+    lines = []
+    for name, advice in sorted(by_name.items()):
+        if lines:
+            lines.append("")
+        lines.append("{} ({} {})".format(name, len(advice.lines), "target" if len(advice.lines) == 1 else "targets"))
+        if advice.explanation:
+            lines.append("  " + advice.explanation)
+        lines += ["  {}: {}".format(target, message) for target, message in sorted(advice.lines)]
+    if not lines:
+        lines = ["No advice for the {} {} checked.".format(len(results), "target" if len(results) == 1 else "targets")]
+    bxl_ctx.bxl_actions().actions.write(output, lines)
+    return [DefaultInfo()]
+
+_report = bxl.dynamic_actions(
+    impl = _report_impl,
+    attrs = {
+        "output": dynattrs.output(),
+        "results": dynattrs.dict(Label, dynattrs.dict(str, dynattrs.artifact_value())),
+    },
+)
+
+def _impl(ctx: bxl.Context):
+    lazy = ctx.lazy
+    nodes = lazy.join_all([lazy.configured_target_node(t, modifiers = ctx.modifiers).catch() for t in ctx.cli_args.targets]).resolve()
+    analyses = lazy.join_all([lazy.analysis(n.unwrap()).catch() for n in nodes if n.is_ok()]).resolve()
+
+    results = {}
+    for analysis in analyses:
+        if not analysis.is_ok():
+            continue
+        validation_info = analysis.unwrap().providers().get(ValidationInfo)
+        if not validation_info:
+            continue
+        results[analysis.unwrap().as_dependency().label] = {spec.name: spec.validation_result for spec in validation_info.validations}
+
+    actions = ctx.bxl_actions().actions
+    out = actions.declare_output("haskell-advice.txt", has_content_based_path = False)
+    actions.dynamic_output_new(_report(results = results, output = out.as_output()))
+    ctx.output.print(ctx.output.ensure(out).abs_path())
+
+main = bxl_main(
+    impl = _impl,
+    cli_args = {
+        "targets": cli_args.target_expr(),
+    },
+)
diff --git a/buck2/prelude/haskell/compile.bzl b/buck2/prelude/haskell/compile.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/compile.bzl
@@ -0,0 +1,600 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+)
+load(
+    "@prelude//haskell:library_info.bzl",
+    "HaskellLibraryInfoTSet",
+    "HaskellLibraryProvider",
+    "HaskellModuleFiles",
+)
+load("@prelude//haskell:link_info.bzl", "HaskellLinkInfo")
+load(
+    "@prelude//haskell:toolchain.bzl",
+    "HaskellToolchainInfo",
+    "compile_env_script",
+    "in_compile_env",
+)
+load(
+    "@prelude//haskell:util.bzl",
+    "attr_deps",
+    "attr_deps_haskell_lib_infos",
+    "attr_deps_haskell_link_infos",
+    "variant_name",
+    "is_haskell_src",
+    "output_extensions",
+    "srcs_to_pairs",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkStyle",
+)
+load("@prelude//utils:argfile.bzl", "at_argfile")
+
+# The type of the return value of the `_compile()` function.
+CompileResultInfo = record(
+    objects = field(Artifact),
+    hi = field(Artifact),
+    stubs = field(Artifact),
+    producing_indices = field(bool),
+    import_dir = field(str),
+    # These are only set when the target is compiled per-module:
+    modules = field(dict[str, HaskellModuleFiles] | None, None),
+    # GHC's messages, such as warnings: a file for each module.
+    diagnostics = field(list[Artifact], []),
+    closures = field(typing.Any, None),
+    # For each module and node name, the dynamic object that GHC's internal
+    # interpreter loads when a splice runs that module's code. This is the
+    # module's object in a shared compile, or its .dyn_o with -dynamic-too.
+    # These objects are also in `objects`, but separating them out lets a
+    # compile action that only needs some of them depend on just those.
+    #
+    # Only per_module produces this field. A --make compile is one action that
+    # may need any of the objects, so it depends on the whole `objects`
+    # directory instead.
+    dynamic_objects = field(dict[str, Artifact] | None, None),
+    # The results of the advice checks, by the names of their validations
+    # (see Note [Advice] in compile_per_module.bzl).
+    advice = field(dict[str, Artifact] | None, None),
+)
+
+CompileArgsInfo = record(
+    srcs = field(cmd_args),
+    args_for_cmd = field(cmd_args),
+    args_for_file = field(cmd_args),
+    # The compile's variant (see variant_name).
+    variant = field(str),
+)
+
+PackagesInfo = record(
+    exposed_package_args = cmd_args,
+    packagedb_args = cmd_args,
+    transitive_deps = field(HaskellLibraryInfoTSet),
+)
+
+def _package_flag(toolchain: HaskellToolchainInfo) -> str:
+    if toolchain.support_expose_package:
+        return "-expose-package"
+    else:
+        return "-package"
+
+# The names of the libraries whose code the target's Template Haskell
+# splices may run. These are the dependencies that splice_depends lists,
+# the dependencies that are neither local nor prebuilt Haskell libraries,
+# and the closures of both.
+#
+# A compile action gets the final dbs and the linked libraries of these
+# dependencies. For its other dependencies it only gets the interfaces. So
+# the compile has to wait until these dependencies are linked.
+#
+# The closures are included because a
+# library's code needs the libraries it was linked against.
+def target_splice_libraries(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool) -> set[str]:
+    return splice_libraries(ctx.actions, splice_dep_infos(ctx, link_style, enable_profiling))
+
+# The names of the libraries that a splice may load. `infos` are the
+# target's splice dependencies (see splice_dep_infos). A splice may load the
+# base dependencies, and the listed ones, or only those of them named in
+# `names` if it isn't None. It may also load any library that these depend
+# on, directly or indirectly.
+def splice_libraries(actions: AnalysisActions, infos, names: [list[str], None] = None) -> set[str]:
+    listed = infos.listed.values() if names == None else [infos.listed[n] for n in names]
+    return set([l.name for l in actions.tset(HaskellLibraryInfoTSet, children = infos.base + listed).traverse()])
+
+# The libraries which may be used by the target's Template Haskell splices
+# (see target_splice_libraries), in two groups:
+#
+# - base: the dependencies that are neither local nor prebuilt Haskell
+#   libraries, which splices can always run.
+# - listed: the dependencies that splice_depends lists, by name.
+def splice_dep_infos(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool):
+    deps = attr_deps(ctx) + ctx.attrs.template_deps
+    known = set([d.label.raw_target() for d in deps])
+    listed = set()
+    for d in ctx.attrs.splice_depends:
+        t = d.label.raw_target()
+        if t not in known:
+            fail("{}: splice_depends names {}, which is not a dependency".format(ctx.label.raw_target(), t))
+        listed.add(t)
+
+    base = []
+    named = {}
+    for d in deps:
+        link = d.get(HaskellLinkInfo)
+        if link == None:
+            continue
+        info = link.prof_info[link_style] if enable_profiling else link.info[link_style]
+        provider = d.get(HaskellLibraryProvider)
+        lib = (provider.prof_lib if enable_profiling else provider.lib)[link_style] if provider != None else None
+        if lib == None or (lib.early_db == None and not lib.is_prebuilt):
+            base.append(info)
+        elif d.label.raw_target() in listed:
+            named[lib.name] = info
+    return struct(base = base, listed = named)
+
+# Whether a compile action can use `lib`'s library-less db, rather than its
+# full db. The action's splices may load the libraries in `finalDbs` (see
+# target_splice_libraries). If `finalDbs` is None, the splices may load
+# every library, so every library needs its full db.
+def uses_library_less_db(lib, finalDbs: [set[str], None]) -> bool:
+    return finalDbs != None and lib.early_db != None and lib.name not in finalDbs
+
+# The `final` argument names the libraries whose final dbs and linked
+# libraries the compile uses (see target_splice_libraries).
+def get_packages_info(ctx: AnalysisContext, link_style: LinkStyle, specify_pkg_version: bool, enable_profiling: bool, final: [set[str], None] = None) -> PackagesInfo:
+    # Collect library dependencies. Note that these don't need to be in a
+    # particular order.
+    libs = dependency_libs(ctx, link_style, enable_profiling)
+
+    exposed_package_args = cmd_args()
+
+    packagedb_args = cmd_args()
+    packagedb_set = set()
+
+    for lib in libs.traverse():
+        if uses_library_less_db(lib, final):
+            # A library compiled per-module has no library-less db of its
+            # own. Its early db names the directory of its modules'
+            # interfaces, which are inputs one by one.
+            packagedb_set.add(lib.early_db)
+            if lib.modules != None:
+                interfaces = [f for m in lib.modules.values() for f in [m.hi, m.dyn_hi] if f != None]
+            else:
+                interfaces = lib.import_dirs
+            hidden_args = cmd_args(hidden = [interfaces, lib.stub_dirs])
+        else:
+            packagedb_set.add(lib.db)
+            hidden_args = cmd_args(
+                hidden = [
+                    lib.import_dirs,
+                    lib.stub_dirs,
+                    # libs of dependencies might be needed at compile time if
+                    # we're using Template Haskell:
+                    lib.libs,
+                ]
+            )
+
+        exposed_package_args.add(hidden_args)
+
+        packagedb_args.add(hidden_args)
+
+    # These we need to add for all the packages/dependencies, i.e.
+    # direct and transitive (e.g. `fbcode-common-hs-util-hs-array`)
+    packagedb_args.add([cmd_args("-package-db", x) for x in packagedb_set])
+
+    exposed_package_args.add(get_exposed_package_args(ctx, link_style, specify_pkg_version, enable_profiling))
+
+    return PackagesInfo(
+        exposed_package_args = exposed_package_args,
+        packagedb_args = packagedb_args,
+        transitive_deps = libs,
+    )
+
+def dependency_libs(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool) -> HaskellLibraryInfoTSet:
+    direct_deps_link_info = attr_deps_haskell_link_infos(ctx)
+    return ctx.actions.tset(
+        HaskellLibraryInfoTSet,
+        children = [lib.prof_info[link_style] if enable_profiling else lib.info[link_style] for lib in direct_deps_link_info],
+    )
+
+def get_exposed_package_args(ctx: AnalysisContext, link_style: LinkStyle, specify_pkg_version: bool, enable_profiling: bool) -> cmd_args:
+    package_flag = _package_flag(ctx.attrs._haskell_toolchain[HaskellToolchainInfo])
+    exposed_package_args = cmd_args()
+    haskell_direct_deps_lib_infos = attr_deps_haskell_lib_infos(
+        ctx,
+        link_style,
+        enable_profiling,
+    )
+
+    # Expose only the packages we depend on directly
+    for lib in haskell_direct_deps_lib_infos:
+        # The rts has no modules to import, and is a dependency to be linked
+        # with. GHC warns about exposing a package that is not used
+        # (-Wunused-packages), which is an error in some projects.
+        if lib.name == "rts":
+            continue
+        if lib.id:
+            # Resolve by unit id rather than by name: unambiguous even when
+            # another version of the same package is visible in another
+            # package db (e.g. GHC's global db vs. a cabal-store rebuild of a
+            # boot package such as time or directory, or a global Cabal
+            # vs. one built from source here).
+            exposed_package_args.add("-package-id", lib.id)
+            continue
+
+        pkg_name = lib.name
+        if specify_pkg_version:
+            pkg_name += "-{}".format(lib.version)
+
+        exposed_package_args.add(package_flag, pkg_name)
+
+    return exposed_package_args
+
+# Whether the target's compiles get `flag`, from the toolchain's or the
+# target's compiler_flags. A flag in a module's OPTIONS_GHC isn't seen.
+def has_compiler_flag(ctx: AnalysisContext, flag: str) -> bool:
+    toolchain_flags = ctx.attrs._haskell_toolchain[HaskellToolchainInfo].compiler_flags or []
+    return flag in toolchain_flags + ctx.attrs.compiler_flags
+
+# Whether haddock documents the target from the interfaces of its compile,
+# rather than compiling its modules again. It does if the compiles keep the
+# docs in their interfaces (-haddock).
+def haddock_from_interfaces(ctx: AnalysisContext) -> bool:
+    # Haddock can read them from GHC 9.12 (--no-compilation).
+    return has_compiler_flag(ctx, "-haddock") and _ghc_at_least(ctx.attrs._haskell_toolchain[HaskellToolchainInfo], (9, 12))
+
+# Whether the toolchain's GHC is at least the given version.
+def _ghc_at_least(haskell_toolchain: HaskellToolchainInfo, version: (int, int)) -> bool:
+    major_minor = [int(x) for x in haskell_toolchain.ghc_version.split(".")[:2]]
+    return (major_minor[0], major_minor[1]) >= version
+
+def ghc_flags(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool, pkgname = None, dynamic_too: bool = False) -> (cmd_args, cmd_args):
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+
+    compile_cmd = cmd_args()
+    compile_cmd.add(haskell_toolchain.compiler_flags)
+
+    # Some rules pass in RTS (e.g. `+RTS ... -RTS`) options for GHC, which can't
+    # be parsed when inside an argsfile.
+    compile_cmd.add(ctx.attrs.compiler_flags)
+
+    compile_args = cmd_args()
+    compile_args.add("-no-link", "-i")
+    compile_args.add("-package-env=-")
+
+    # Without this, GHC's own implicit global package db (always loaded,
+    # independent of anything passed via -package-db below) leaks in
+    # alongside the deps get_packages_info() computes - normally harmless
+    # (nothing there collides with an ordinary project's own package
+    # names), but GHC ships boot libraries under names a project can
+    # itself build from source under the same name (e.g. `Cabal`,
+    # `Cabal-syntax`) - then both the boot copy (auto-exposed globally)
+    # and this target's own explicitly `-package-id`-exposed one export
+    # the same module name, and GHC fails with "Ambiguous module name"
+    # for any of that module's importers, even though the -package-id
+    # given to *this* compile is perfectly unambiguous on its own.
+    # get_packages_info() already computes exactly the exposure set this
+    # compile needs (direct deps + base, see its own comment) - with
+    # `-hide-all-packages` GHC uses only that, ignoring the global db's
+    # own default exposure entirely.
+    compile_args.add("-hide-all-packages")
+
+    if enable_profiling:
+        compile_args.add("-prof")
+
+    if link_style == LinkStyle("shared"):
+        compile_args.add("-dynamic", "-fPIC")
+    elif link_style == LinkStyle("static_pic"):
+        compile_args.add("-fPIC", "-fexternal-dynamic-refs")
+
+    if dynamic_too:
+        # Produces .dyn_o/.dyn_hi alongside this compile's ordinary .o/.hi,
+        # in the same -odir/-hidir (the only way to get both from GHC in
+        # --make mode - there's no flag to write them to different
+        # directories). GHC guarantees these are consistent with the
+        # primary .o/.hi, since they come from the same compile pass and
+        # share its frontend work - unlike reusing an *independently*
+        # compiled "shared" variant's interfaces would be, which carries no
+        # such guarantee. See haskell.bzl's use of this (building a
+        # library's static archive and shared library from a single
+        # -dynamic-too compile instead of two independent ones) for why
+        # this matters enough to ask for explicitly rather than just
+        # tolerating two compiles.
+        compile_args.add("-dynamic-too")
+
+    # We want maximum determinism, so we turn this on when it's available.
+    if _ghc_at_least(haskell_toolchain, (9, 12)):
+        compile_args.add("-fobject-determinism")
+
+    osuf, hisuf = output_extensions(link_style, enable_profiling)
+    compile_args.add("-osuf", osuf, "-hisuf", hisuf)
+
+    if getattr(ctx.attrs, "main", None) != None:
+        compile_args.add(["-main-is", ctx.attrs.main])
+
+    # Add args from preprocess-able inputs: for the C preprocessor of Haskell
+    # code, and for the C that GHC compiles itself. For example:
+    #   foreign import capi "Header.h ..." ...
+    # generates a C file that includes Header.h, so we need to pass the
+    # preprocessor options via -optc too.
+    inherited_pre = cxx_inherited_preprocessor_infos(attr_deps(ctx))
+    pre = cxx_merge_cpreprocessors(ctx.actions, [], inherited_pre)
+    pre_args = pre.set.project_as_args("args")
+    compile_args.add(cmd_args(pre_args, format = "-optP={}"))
+    compile_args.add(cmd_args(pre_args, format = "-optc={}"))
+
+    if pkgname:
+        compile_args.add(["-this-unit-id", pkgname])
+
+    return compile_cmd, compile_args
+
+def get_producing_indices(ctx: AnalysisContext) -> bool:
+    return has_compiler_flag(ctx, "-fwrite-ide-info")
+
+def compile_args(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool, pkgname = None, dynamic_too: bool = False, final: [set[str], None] = None) -> CompileArgsInfo:
+    compile_cmd, compile_args = ghc_flags(ctx, link_style, enable_profiling, pkgname, dynamic_too)
+
+    # Add -package-db and -package/-expose-package flags for each Haskell
+    # library dependency.
+    packages_info = get_packages_info(
+        ctx,
+        link_style,
+        specify_pkg_version = False,
+        enable_profiling = enable_profiling,
+        final = final,
+    )
+
+    compile_args.add(packages_info.exposed_package_args)
+    compile_args.add(packages_info.packagedb_args)
+
+    arg_srcs = []
+    hidden_srcs = []
+    for _, src in srcs_to_pairs(ctx.attrs.srcs):
+        # hs-boot files aren't expected to be an argument to compiler but does need
+        # to be included in the directory of the associated src file
+        if is_haskell_src(src):
+            arg_srcs.append(src)
+        else:
+            hidden_srcs.append(src)
+    srcs = cmd_args(
+        arg_srcs,
+        hidden = hidden_srcs,
+    )
+
+    return CompileArgsInfo(
+        srcs = srcs,
+        args_for_cmd = compile_cmd,
+        args_for_file = compile_args,
+        variant = variant_name(link_style, enable_profiling),
+    )
+
+# Shell steps that run before `ghc --make`, in the same shell as the
+# toolchain's environment (see in_env). Each step takes its arguments from
+# the front of the positional parameters and shifts them off, so that what
+# is left at the end is the command to run.
+
+# GHC creates the -stubdir only when it compiles a module. The action keeps
+# the outputs of its previous run (see no_outputs_cleanup in compile), so if
+# GHC finds every module up to date, it compiles nothing. If the stub
+# directory is missing in that case, for example because Buck removed it,
+# the action would fail to produce one of its outputs. This step makes the
+# directory that its argument names.
+_MAKE_STUBDIR = 'mkdir -p "$1"; shift; '
+
+# Copies the .dyn_o objects of another compile of the same sources into this
+# compile's -odir. The arguments are the -odir and the other compile's
+# objects directory.
+_COPY_DYN_OBJECTS = """\
+odir=$1; src=$2; shift 2
+(cd "$src" && find . -name '*.dyn_o') | while read -r f; do
+  mkdir -p "$odir/${f%/*}"
+  cp -f "$src/$f" "$odir/$f"
+done
+"""
+
+# The environment for the rule's `data_dirs`: each variable name mapped to the
+# directory it should point at. A package's generated Paths_<pkg> module reads
+# its `<pkg>_datadir` variable to find the package's data-files, so setting
+# these lets `getDataFileName` work both at compile time (in a Template Haskell
+# splice, or a build tool run by the compile) and when a binary runs.
+def data_dirs_env(ctx: AnalysisContext) -> dict[str, Artifact]:
+    return {name: dep[DefaultInfo].default_outputs[0] for name, dep in ctx.attrs.data_dirs.items()}
+
+# The data dirs that the Paths_<pkg> modules among `modules` read, keyed by
+# environment variable. For example, if `modules` includes Paths_foo, the
+# result has data_dirs["foo_datadir"], if there is one.
+def paths_data_dirs(modules, data_dirs: dict[str, Artifact]) -> dict[str, Artifact]:
+    vars = [m.removeprefix("Paths_") + "_datadir" for m in modules if m.startswith("Paths_")]
+    return {var: data_dirs[var] for var in vars if var in data_dirs}
+
+# The data dirs that the rule's own Paths_<pkg> modules read.
+def own_data_dirs(ctx: AnalysisContext) -> dict[str, Artifact]:
+    return paths_data_dirs([m for m, _ in srcs_to_pairs(ctx.attrs.srcs)], data_dirs_env(ctx))
+
+# The data dirs that a compile action sets, for splices that run code from
+# the libraries whose data dirs are `lib_dirs` and from the target's modules
+# `own_modules`. The compile needs the data dirs that the Paths_<pkg>
+# modules among those read. If the compile might run one of the target's
+# build tools (`runs_tools`), it gets all the target's data dirs
+# (`data_dirs`) instead, because a build tool might read data files of its
+# own. See Note [Data files of splices] in compile_per_module.bzl.
+def compile_data_dirs(data_dirs: dict[str, Artifact], lib_dirs: dict[str, Artifact], own_modules: list[str], runs_tools: bool) -> dict[str, Artifact]:
+    if runs_tools:
+        return data_dirs
+    return lib_dirs | paths_data_dirs(own_modules, data_dirs)
+
+# The data dirs that a --make compile of the target sets. Its splices can
+# run code from any of the target's own modules, and from the libraries in
+# `final` (see target_splice_libraries).
+def splice_data_dirs(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool, final: set[str]) -> dict[str, Artifact]:
+    libs = [lib for lib in dependency_libs(ctx, link_style, enable_profiling).traverse() if lib.name in final]
+    return compile_data_dirs(
+        data_dirs_env(ctx),
+        {var: d for lib in libs for var, d in lib.data_dirs.items()},
+        [m for m, _ in srcs_to_pairs(ctx.attrs.srcs)],
+        len(build_tools(ctx)) > 0,
+    )
+
+# The target's build tools (build_tool_depends), by the name of each tool's
+# executable, which is the name that a program looks it up by on PATH.
+def build_tools(ctx: AnalysisContext) -> dict[str, Artifact]:
+    return {
+        dep[DefaultInfo].default_outputs[0].basename: dep[DefaultInfo].default_outputs[0]
+        for dep in ctx.attrs.build_tool_depends
+    }
+
+# The environment to run GHC in: the toolchain's compile_env variables, and
+# the target's build tools added to PATH.
+def ghc_env(ctx: AnalysisContext, build_tool_dir: str):
+    return tools_env(ctx.actions, ctx.attrs._haskell_toolchain[HaskellToolchainInfo].compile_env, build_tools(ctx), build_tool_dir)
+
+# The environment to run GHC in: the `compile_env` variables, and the build
+# tools in `tools` (as build_tools gives them) added to PATH. The tools are
+# linked into a directory at `build_tool_dir`.
+def tools_env(actions: AnalysisActions, compile_env: dict[str, str], tools: dict[str, Artifact], build_tool_dir: str):
+    script = compile_env_script(compile_env) if compile_env else ""
+    args = []
+
+    # We smuggle the build tools in via an extra argument and make the shell
+    # command add them to the PATH.
+    if tools:
+        script += 'export PATH="$PATH:$1"; shift; '
+        args.append(actions.symlinked_dir(build_tool_dir, tools, has_content_based_path = False))
+    return struct(script = script, args = args)
+
+def in_env(env, cmd: cmd_args) -> cmd_args:
+    return in_compile_env(env.script, env.args, cmd)
+
+# Whether the target has modules for GHC to compile (e.g. not a target whose
+# code is all C).
+def has_modules(ctx: AnalysisContext) -> bool:
+    return any([is_haskell_src(src) for _, src in srcs_to_pairs(ctx.attrs.srcs)])
+
+# Which objects GHC loads when a splice runs code from the target's own
+# modules. GHC decides this, and the compile has to put those objects where
+# GHC will look for them:
+#
+# - "own": the objects the compile makes itself. An external interpreter
+#   loads these, because it runs in the same way as the compile, and so
+#   does a GHC that isn't dynamically linked.
+# - "dynamic": a dynamically linked GHC's internal interpreter loads
+#   dynamic objects. A shared compile makes these anyway, and a static one
+#   makes them with -dynamic-too.
+# - "from_non_profiled": like "dynamic", but a profiled compile doesn't
+#   make dynamic objects, so it uses the ones from the non-profiled compile.
+def splice_objects_kind(ctx: AnalysisContext, enable_profiling: bool) -> str:
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+    if has_compiler_flag(ctx, "-fexternal-interpreter") or not haskell_toolchain.dynamic_ghc:
+        return "own"
+    return "from_non_profiled" if enable_profiling else "dynamic"
+
+# Compile all the context's sources with `ghc --make`.
+#
+# For a profiled compile, `dynamic_from` is the non-profiled compile of the
+# same sources. When a splice runs code from this library's own modules,
+# GHC's internal interpreter may want a module's .dyn_o (see
+# splice_objects_kind), and it looks for it next to the profiled object, in
+# this compile's -odir. With Cabal both compiles share a build directory, so
+# it's there. Here each compile has its own -odir, so we copy the .dyn_o
+# files in first.
+def compile(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool, pkgname: str | None = None, dynamic_too: bool = False, dynamic_from: [CompileResultInfo, None] = None) -> CompileResultInfo:
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+    compile_cmd = cmd_args(haskell_toolchain.compiler)
+
+    splices = target_splice_env(ctx, link_style, enable_profiling)
+    args = compile_args(ctx, link_style, enable_profiling, pkgname, dynamic_too = dynamic_too, final = splices.final)
+    import_dir = "hi-" + args.variant
+    result = CompileResultInfo(
+        objects = ctx.actions.declare_output("objects-" + args.variant, dir = True, has_content_based_path = False),
+        hi = ctx.actions.declare_output(import_dir, dir = True, has_content_based_path = False),
+        import_dir = import_dir,
+        stubs = ctx.actions.declare_output("stubs-" + args.variant, dir = True, has_content_based_path = False),
+        producing_indices = get_producing_indices(ctx),
+    )
+
+    if not has_modules(ctx):
+        ctx.actions.run(
+            cmd_args("mkdir", "-p", result.objects.as_output(), result.hi.as_output(), result.stubs.as_output()),
+            category = "haskell_compile",
+            identifier = args.variant,
+        )
+        return result
+
+    compile_cmd.add(args.args_for_cmd)
+    outputs = cmd_args(
+        "-odir",
+        result.objects.as_output(),
+        "-hidir",
+        result.hi.as_output(),
+        "-hiedir",
+        result.hi.as_output(),
+        "-stubdir",
+        result.stubs.as_output(),
+    )
+    compile_cmd.add(ghc_file_args(ctx, "args-" + args.variant + ".haskell_compile_argsfile", cmd_args(args.args_for_file, outputs), args.srcs))
+
+    steps = _MAKE_STUBDIR
+    step_args = [result.stubs.as_output()]
+    if dynamic_from != None and splice_objects_kind(ctx, enable_profiling) == "from_non_profiled":
+        steps += _COPY_DYN_OBJECTS
+        step_args += [result.objects.as_output(), dynamic_from.objects]
+
+    # This keeps the previous run's -odir/-hidir (see run_ghc), so that `ghc
+    # --make` can do its own recompilation checking and only rebuild the
+    # modules whose sources or imported interfaces changed.
+    #
+    # GHC >= 9.4 tracks file changes with hashes rather than
+    # timestamps, so this is safe even though Buck doesn't preserve
+    # timestamps on artifacts.
+    run_ghc(ctx, compile_cmd, splices, args.variant, args.variant, steps, step_args, "haskell_compile")
+
+    return result
+
+# What the splices need in an action that runs GHC on all the target's
+# modules at once, such as the --make compile or haddock. This is the set of
+# libraries that the splices may run (`final`, see target_splice_libraries),
+# and the data dirs that the splices may read (see splice_data_dirs).
+def target_splice_env(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool):
+    final = target_splice_libraries(ctx, link_style, enable_profiling)
+    return struct(
+        final = final,
+        data_dirs = splice_data_dirs(ctx, link_style, enable_profiling, final),
+    )
+
+# Run `cmd`, a GHC program, with what its splices need (`splices`, from
+# target_splice_env) and with the target's build tools (see ghc_env).
+#
+# Before `cmd`, the shell runs `steps`, which are shell commands. They take
+# `step_args` from the front of the positional parameters and shift them
+# off. `variant` is the action's identifier (see variant_name). `name` names
+# the directories that the action makes, and has to be unique among the
+# target's run_ghc actions.
+#
+# The action doesn't clean up its outputs before it runs, because GHC can
+# sometimes reuse them. Pass -fforce-recomp in `cmd` to stop GHC from doing
+# that.
+def run_ghc(ctx: AnalysisContext, cmd: cmd_args, splices, variant: str, name: str, steps: str, step_args: list, category: str):
+    env = ghc_env(ctx, "build-tool-depends-" + name)
+    ctx.actions.run(
+        in_env(struct(script = env.script + "set -eu; " + steps, args = env.args + step_args), cmd),
+        category = category,
+        identifier = variant,
+        no_outputs_cleanup = True,
+        env = splices.data_dirs,
+    )
+
+# GHC's arguments `args` and the sources `srcs`, in a file named `name` if
+# the toolchain uses one (use_argsfile).
+def ghc_file_args(ctx: AnalysisContext, name: str, args: cmd_args, srcs: cmd_args) -> cmd_args:
+    if ctx.attrs._haskell_toolchain[HaskellToolchainInfo].use_argsfile:
+        return at_argfile(actions = ctx.actions, name = name, args = [args, srcs], allow_args = True)
+    return cmd_args(args, srcs)
diff --git a/buck2/prelude/haskell/compile_per_module.bzl b/buck2/prelude/haskell/compile_per_module.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/compile_per_module.bzl
@@ -0,0 +1,1522 @@
+# Per-module compilation (`compile_granularity = "module"`): one `ghc -c`
+# action per module instead of one `ghc --make` action per target. See the
+# Notes at the end of this file, starting with Note [Per-module compilation].
+
+load(
+    "@prelude//haskell:compile.bzl",
+    "CompileResultInfo",
+    "data_dirs_env",
+    "dependency_libs",
+    "get_exposed_package_args",
+    "get_producing_indices",
+    "build_tools",
+    "compile_data_dirs",
+    "ghc_env",
+    "ghc_flags",
+    "has_modules",
+    "in_env",
+    "splice_dep_infos",
+    "splice_libraries",
+    "splice_objects_kind",
+    "tools_env",
+    "uses_library_less_db",
+)
+load(
+    "@prelude//haskell:library_info.bzl",
+    "HaskellLibraryInfoTSet",
+    "HaskellModuleFiles",
+)
+load(
+    "@prelude//haskell:toolchain.bzl",
+    "HaskellToolchainInfo",
+)
+load(
+    "@prelude//haskell:util.bzl",
+    "attr_deps",
+    "variant_name",
+    "haskell_library_unit_id",
+    "is_haskell_src",
+    "module_name_to_file",
+    "output_extensions",
+    "srcs_to_pairs",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkStyle",
+)
+
+# A module's closure set holds the interface files of the module's closure:
+# the module itself, and everything it imports, directly or indirectly, from
+# targets compiled per-module (see Note [Per-module compilation]). It is a
+# transitive set whose value is the module's own files, and whose children
+# are the closure sets of the modules it imports. Each target passes its
+# modules' closure sets on to its dependents (in PerModuleClosures), so no
+# target ever has to list a whole closure itself.
+def _interfaces(files: HaskellModuleFiles):
+    return [files.hi, files.abi] + ([files.dyn_hi] if files.dyn_hi != None else [])
+
+_ModuleClosureTSet = transitive_set(args_projections = {"interfaces": _interfaces})
+
+# The provider that a per-module target's dynamic output returns: the
+# closure set of each of the target's modules, keyed by node name (see
+# _nodes).
+PerModuleClosures = provider(fields = {"by_module": provider_field(dict)})
+
+# The package db flags for a per-module compile, and the inputs that go
+# with them. `libs` are all of the target's dependencies, direct and
+# transitive. See Note [Libraries of the early package dbs].
+#
+# A prebuilt dependency, or a local one named in `final`, is on its final
+# db, with its interface directories as inputs. Every other local
+# dependency is on a db that names no library, so that the compile doesn't
+# wait for its library to be built:
+#
+# - A dependency compiled per-module: its early db. This adds no inputs,
+#   because each module's compile adds the particular interfaces it imports
+#   itself.
+# - A dependency built with --make: its library-less db, with the library's
+#   interface directories as inputs.
+#
+# A module that runs Template Haskell (`runs_th`) also has the libraries of
+# its final dbs as inputs, because GHC's interpreter loads them.
+# `below_make` names the dependencies compiled per-module that some
+# dependency built with --make depends on. Their whole interface
+# directories are inputs as well: see Note [Compiling against dependencies
+# module by module]. `import_dirs_tag` tags all the interface inputs, so
+# that a compile's dep file can list the ones it read.
+#
+# As well as the flags, the result has `local_import_dirs`, the interface
+# directories of the --make dependencies with their library names, and
+# `early_names`, the names of the dependencies on their early dbs. The
+# compile tool needs both to find the interfaces that its dep file lists.
+def _package_dbs(libs: list, final: set[str], below_make: set[str], import_dirs_tag, runs_th: bool):
+    packagedb_args = cmd_args()
+    packagedb_set = set()
+    local_import_dirs = []
+    early_names = set()
+    for lib in libs:
+        library_less = uses_library_less_db(lib, final)
+        if library_less and lib.modules != None:
+            packagedb_set.add(lib.early_db)
+            early_names.add(lib.name)
+            if lib.name in below_make:
+                # A library built with --make depends on this one, and its
+                # interfaces refer to this one's: see Note [Compiling against
+                # dependencies module by module].
+                packagedb_args.add(import_dirs_tag.tag_artifacts(cmd_args(hidden = lib.import_dirs)))
+            continue
+        packagedb_set.add(lib.early_db if library_less else lib.db)
+        import_dirs = lib.import_dirs
+        local_import_dirs += [(lib.name, d) for d in import_dirs if not d.is_source]
+        # The interfaces are tagged, so that a compile's dep file can list
+        # the ones it read. The libraries that a Template Haskell module
+        # loads never appear in the dep file (see Note [Template Haskell
+        # modules]), so they are plain inputs, and any change to one
+        # compiles the module again. A module that runs no Template Haskell
+        # loads none, so it doesn't wait for them to be linked.
+        loads = runs_th and not library_less
+        packagedb_args.add(cmd_args(hidden = [
+            lib.stub_dirs,
+            import_dirs_tag.tag_artifacts(cmd_args(hidden = import_dirs)),
+            lib.libs if loads else [],
+        ]))
+
+    # These we need to add for all the packages/dependencies, i.e.
+    # direct and transitive (e.g. `fbcode-common-hs-util-hs-array`)
+    packagedb_args.add([cmd_args("-package-db", x) for x in packagedb_set])
+    return struct(packagedb_args = packagedb_args, local_import_dirs = local_import_dirs, early_names = early_names)
+
+# The suffix that marks a boot source or interface (.hs-boot or
+# .hi-boot). A boot file's node name (its key in srcs) is
+# "<module>-boot".
+_BOOT = "-boot"
+
+def _is_boot(node: str) -> bool:
+    return node.endswith(_BOOT)
+
+def _module_of(node: str) -> str:
+    return node[:-len(_BOOT)] if _is_boot(node) else node
+
+# The path of a node's output file with the given extension, relative to
+# the output directory. For example, with ext = "dyn_hi", it is
+# Foo/Bar.dyn_hi for the module Foo.Bar, and Foo/Bar.dyn_hi-boot for its
+# boot file.
+def _node_file(node: str, ext: str) -> str:
+    return module_name_to_file(_module_of(node), ext + (_BOOT if _is_boot(node) else ""))
+
+# The directory, relative to the target's outputs, that holds everything a
+# per-module compile of the target writes for one combination of link style
+# and profiling (static, shared, profiled and so on). The modules' own
+# outputs are in a subdirectory of it (see per_module_out_dir).
+def per_module_dir(link_style: LinkStyle, enable_profiling: bool) -> str:
+    return "per-module-" + variant_name(link_style, enable_profiling) + "/"
+
+# The directory, relative to the target's outputs, where the target's
+# modules write their objects and interfaces, for one combination of link
+# style and profiling. Every module's compile has it on its import path, and
+# it is the import directory of the target's early package db, which is how
+# dependents find the interfaces there too.
+#
+# It is named after the target's set of modules. buck2 doesn't delete the
+# outputs of an action that no longer exists, so if a module moved to another
+# target, GHC would still find its old interface here. A new set of modules
+# gets a fresh directory instead. The cost is that adding, removing or
+# renaming a module compiles the whole target again.
+def per_module_out_dir(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool) -> str:
+    names = " ".join(sorted([n for n, _ in _nodes(ctx)]))
+    return per_module_dir(link_style, enable_profiling) + "out-" + str(hash(names) & 0xffffffff)
+
+# The directory to give GHC as an import or output directory, worked out
+# from one node's output file in it. `artifact` is the node's file with
+# extension `ext`, and the result is the directory above the module's own
+# path: for the module Foo.Bar, whose interface is <dir>/Foo/Bar.hi, the
+# result is <dir>.
+def _dir_of(artifact, node: str, ext: str) -> cmd_args:
+    return cmd_args(artifact, parent = _node_file(node, ext).count("/") + 1)
+
+# Read the module graph that the deps tool wrote (see
+# tools/ghc-api/PerModuleDeps.hs). It returns:
+#
+# - imports: for each node, the nodes of this target that it imports.
+# - upstream: for each node, the modules it imports from dependencies
+#   compiled per-module, as (package id, module name) pairs. Imports from
+#   other dependencies are left out, since those aren't tracked module by
+#   module.
+# - th: the nodes that may run Template Haskell, with why (the deps tool's
+#   "th_reason").
+# - programs: for each node, the programs that GHC runs for it and finds on
+#   PATH, by name, such as a preprocessor that -F -pgmF names.
+# - splice_imports: for each node with explicit level imports, the modules
+#   it imports at the splice level, as (library name, module) pairs. The
+#   library is that of a dependency that the import comes through, which for
+#   a re-exported module is the dependency that re-exports it.
+#
+# `prebuilt_names` maps the unit id of each prebuilt dependency to its name.
+def _read_deps(label, deps: dict, nodes: list, module_libs: dict, prebuilt_names: dict[str, str]):
+    imports = {n: [] for n, _ in nodes}
+    upstream = {n: [] for n, _ in nodes}
+    th = {}
+    programs = {n: [] for n, _ in nodes}
+    splice_imports = {}
+    for n, d in deps.items():
+        if n not in imports:
+            fail("{}: GHC's dependency analysis found {}, but srcs has no such module (or boot file)".format(label, n))
+        imports[n] = d["imports"]
+        for pkg, mod in d["external"]:
+            lib = module_libs.get(pkg)
+            if lib != None and mod in lib.modules and (pkg, mod) not in upstream[n]:
+                upstream[n].append((pkg, mod))
+        if d["th"]:
+            th[n] = d.get("th_reason", "module")
+        programs[n] = d["programs"]
+        if "splice" in d:
+            splice_imports[n] = [(prebuilt_names.get(pkg, pkg), mod) for pkg, mod in d["splice"]]
+    return imports, upstream, th, splice_imports, programs
+
+# For each node, all the nodes of this target that it imports directly or
+# indirectly, with its direct imports first. `order` must be a dependency
+# order (each node after the nodes it imports), so that an import's closure
+# has already been computed when its importers need it.
+def _transitive_closure(order: list[str], imports: dict) -> dict:
+    closure = {}
+    for n in order:
+        c = set(imports[n])
+        for d in imports[n]:
+            for x in closure[d]:
+                c.add(x)
+        closure[n] = list(c)
+    return closure
+
+# Sort the nodes into dependency order, so that each node comes after the
+# nodes it imports. It returns the sorted nodes, and the nodes that couldn't
+# be sorted because they are in an import cycle or import something that
+# is.
+#
+# This is Kahn's algorithm. Starlark has no while loop, so instead of a work
+# queue we iterate over `order` while appending to it, so it's linear in the
+# size of the graph.
+def _dependency_order(nodes: list, imports: dict) -> (list[str], list[str]):
+    importers = {n: [] for n, _ in nodes}
+    waiting = {}
+    for n, _ in nodes:
+        waiting[n] = len(imports[n])
+        for d in imports[n]:
+            importers[d].append(n)
+    order = [n for n, _ in nodes if waiting[n] == 0]
+    for i in range(len(nodes)):
+        if i >= len(order):
+            break
+        for m in importers[order[i]]:
+            waiting[m] -= 1
+            if waiting[m] == 0:
+                order.append(m)
+    done = set(order)
+    return order, [n for n, _ in nodes if n not in done]
+
+# The nodes of the target's module graph, as (node name, source) pairs. A
+# module's node name is the module's name, and a boot file's is
+# "<module>-boot". When srcs is a dict, a boot file's key is already
+# "<module>-boot". When it is a list, srcs_to_pairs names a boot file after
+# its module, so "-boot" is added here.
+def _nodes(ctx: AnalysisContext) -> list:
+    nodes = []
+    for name, src in srcs_to_pairs(ctx.attrs.srcs):
+        if is_haskell_src(src):
+            nodes.append((name, src))
+        elif src.short_path.endswith(_BOOT):
+            nodes.append((name if _is_boot(name) else name + _BOOT, src))
+    return nodes
+
+# Declare each node's output files, all in the target's output directory
+# (see per_module_out_dir). They are at fixed paths rather than
+# content-based ones, so that GHC can find a module's interface from the
+# module's name.
+#
+# They are declared here, before the module graph is known, rather than in
+# the dynamic output that registers the compiles. That way the target can
+# give them to its dependents directly (in HaskellModuleFiles), and not only
+# through the objects and hi directories that the dynamic output builds.
+def _declare_module_outputs(ctx: AnalysisContext, out_dir: str, nodes: list, osuf: str, hisuf: str, dynamic_too: bool):
+    def declare(n, ext):
+        return ctx.actions.declare_output(out_dir + "/" + _node_file(n, ext), has_content_based_path = False)
+
+    return struct(
+        o = {n: declare(n, osuf) for n, _ in nodes},
+        hi = {n: declare(n, hisuf) for n, _ in nodes},
+        abi = {n: declare(n, "abi") for n, _ in nodes},
+        diagnostics = {n: declare(n, "diag") for n, _ in nodes},
+        dyn_o = {n: declare(n, "dyn_o") for n, _ in nodes} if dynamic_too else {},
+        dyn_hi = {n: declare(n, "dyn_hi") for n, _ in nodes} if dynamic_too else {},
+    )
+
+# For each node, the object that a splice loads to run that module's code
+# (see Note [Template Haskell modules], section 6).
+#
+# GHC looks for a module's dynamic object as <module>.dyn_o in the output
+# directory. A profiled compile makes no dynamic objects, so it puts links
+# there to the dynamic objects of the non-profiled compile, `dynamic_from`.
+# compile() copies the same objects in for --make.
+def _splice_objects(ctx: AnalysisContext, out_dir: str, nodes: list, o_of: dict, dynamic_objects: dict, enable_profiling: bool, dynamic_from: [CompileResultInfo, None]) -> dict:
+    kind = splice_objects_kind(ctx, enable_profiling)
+    if kind == "own":
+        return o_of
+    if kind == "dynamic":
+        return dynamic_objects
+    if dynamic_from == None or dynamic_from.dynamic_objects == None:
+        fail("a profiled per_module compile needs a non-profiled per_module compile to take its splices' dynamic objects from")
+    links = {}
+    for n, _ in nodes:
+        if n in dynamic_from.dynamic_objects:
+            link = ctx.actions.declare_output(out_dir + "/" + _node_file(n, "dyn_o"), has_content_based_path = False)
+            ctx.actions.symlink_file(link, dynamic_from.dynamic_objects[n])
+            links[n] = link
+    return links
+
+# The version of the request that each compile action sends, and of the
+# files that the worker writes back. The worker and the compile tool refuse a
+# request of any other version, so that a worker built from another version
+# of the rules reports the mismatch rather than misreading the request. When
+# either the request or the worker's outputs change, bump this and the
+# version in tools/ghc-api/Contract.hs.
+_WORKER_CONTRACT = "7"
+
+# The dynamic output of a per-module compile. It runs once the deps tool has
+# written the module graph. It registers a compile action for each node,
+# builds the target's objects and hi directories from their outputs, and
+# returns each module's closure set for the target's dependents (see
+# _ModuleClosureTSet). `s` carries the values that compile_per_module worked
+# out during analysis.
+def _register_modules_impl(actions: AnalysisActions, s: typing.Any, deps: ArtifactValue, libdir: ArtifactValue, dep_closures: dict, artifacts: list[Artifact], outputs: list[OutputArtifact]) -> list[Provider]:
+    out = {a: o for a, o in zip(artifacts, outputs)}
+    nodes = s.nodes
+    src_of = s.src_of
+    modules = s.modules
+    module_libs = s.module_libs
+    module_lib_dirs = s.module_lib_dirs
+    splice_infos = s.splice_infos
+    packages = s.packages
+    early_packages = s.early_packages
+    target_splice_packages = s.target_splice_packages
+    dynamic_too = s.dynamic_too
+    o_of = s.o_of
+    hi_of = s.hi_of
+    abi_of = s.abi_of
+    dyn_o_of = s.dyn_o_of
+    splice_objects = s.splice_objects
+    dyn_hi_of = s.dyn_hi_of
+    diag_of = s.diag_of
+    objects = s.objects
+    hi = s.hi
+    stubs = s.stubs
+    prefix = s.prefix
+    variant = s.variant
+    osuf = s.osuf
+    hisuf = s.hisuf
+    tag = s.tag
+    producing_indices = s.producing_indices
+    src_tree = s.src_tree
+    base_cmd = s.base_cmd
+    data_dirs = s.data_dirs
+    worker_info = s.worker_info
+    tools = s.tools
+    compile_script = s.compile_script
+
+    imports, upstream, th_nodes, splice_imports, program_nodes = _read_deps(s.label, deps.read_json(), nodes, module_libs, s.prebuilt_names)
+    order, left = _dependency_order(nodes, imports)
+    if left:
+        fail("{}: import cycle among {}".format(s.label, ", ".join(left)))
+    closure = _transitive_closure(order, imports)
+
+    # Make two transitive sets for each node, in dependency order:
+    #
+    # - closure_sets[n] is the node's closure set, for the target's
+    #   dependents. It includes the node's own files.
+    # - upstream_closure_sets[n] holds the interfaces from dependencies
+    #   compiled per-module that the node's compile may read: the closure
+    #   sets of the modules that the node imports from those dependencies,
+    #   or that anything it imports from this target does. It doesn't
+    #   include this target's own interfaces, which are added separately
+    #   below.
+    dep_closure_sets = {name: dv.providers[PerModuleClosures].by_module for name, dv in dep_closures.items()}
+    closure_sets = {}
+    upstream_closure_sets = {}
+    for n in order:
+        ups = [dep_closure_sets[pkg][mod] for pkg, mod in upstream[n] if mod in dep_closure_sets.get(pkg, {})]
+        upstream_closure_sets[n] = actions.tset(_ModuleClosureTSet, children = [upstream_closure_sets[i] for i in imports[n]] + ups)
+        closure_sets[n] = actions.tset(_ModuleClosureTSet, value = modules[n], children = [closure_sets[i] for i in imports[n]] + ups)
+
+    runs_th = {n: n in th_nodes for n, _ in nodes}
+
+    # The environment of each set of build tools that some module may run,
+    # made once for each set (see module_tools below).
+    tools_envs = {}
+
+    def env_with(names):
+        key = ",".join(sorted(names))
+        if key not in tools_envs:
+            tools_envs[key] = tools_env(actions, s.compile_env, {t: tools[t] for t in names}, prefix + "build-tools/" + str(len(tools_envs)))
+        return tools_envs[key]
+
+    # The package flags of each module that has explicit level imports (see
+    # Note [Explicit level imports]). Of the target's splice dependencies,
+    # the module gets the final dbs of the ones whose modules it imports at
+    # the splice level, and of their closures. For its other local
+    # dependencies, it gets library-less dbs.
+    narrowed_splice_packages = {}
+
+    # A splice can run code of any prebuilt package, since all their
+    # libraries are there from the start (see Note [Libraries of the early
+    # package dbs]). So only local packages are checked here.
+    prebuilt = set(s.prebuilt_names.values())
+
+    # The package flags of a Template Haskell module. That is the target's
+    # set, unless the module has explicit level imports, which may narrow it.
+    def splice_packages(n):
+        if n not in splice_imports:
+            return target_splice_packages
+        libs = {lib: m for lib, m in splice_imports[n] if lib != s.this_pkg}
+        imports_own = len([lib for lib, _ in splice_imports[n] if lib == s.this_pkg]) > 0
+        # An import of a module that several dependencies re-export, or that
+        # its own package exposes as well, comes through each of them, and
+        # any one would do. But each of them has to be covered here. That is
+        # stricter than it needs to be, in a case that should be rare.
+        for lib, m in libs.items():
+            if lib not in target_splice_packages.final and lib not in prebuilt:
+                fail("{}: {}'s splice import of {} runs code from {}, but splice_depends doesn't list it".format(s.label, _module_of(n), m, lib))
+        # A dependency that isn't listed, but that a listed one's closure
+        # brings in, has no closure of its own here. A module that imports
+        # from one gets the target's whole set, as does a module that imports
+        # one of the target's own modules.
+        if [l for l in libs if l not in splice_infos.listed and l not in prebuilt] or imports_own:
+            return target_splice_packages
+        names = sorted([l for l in libs if l in splice_infos.listed])
+        key = " ".join(names)
+        if key not in narrowed_splice_packages:
+            narrowed_splice_packages[key] = packages(splice_libraries(actions, splice_infos, names))
+        return narrowed_splice_packages[key]
+
+    # Register the compiles in dependency order. An action's inputs, and the
+    # artifacts that a symlinked_dir links to, must be outputs of actions
+    # that have already been registered.
+    hie_of = {}
+
+    # The modules compiled without the worker, with the build tools they may
+    # run, for the haskell_modules_outside_worker check.
+    outside_worker = {}
+    for n in order:
+        # The module finds the interfaces it imports from this target in
+        # the target's output directory, which all the target's modules
+        # share, and which is on the module's import path. The interface
+        # files of the module's closure are tagged inputs, so the module
+        # waits for exactly those, and its dep file can list them. (Giving
+        # each module a symlink tree of just its own closure was tried, but
+        # the trees took longer to materialise than the compiles
+        # themselves.)
+        closure_files = []
+        for d in closure[n]:
+            closure_files += [hi_of[d], abi_of[d]]
+            if dynamic_too:
+                closure_files.append(dyn_hi_of[d])
+            if runs_th[n] and d in splice_objects:
+                # The objects a splice may load (see _splice_objects).
+                closure_files.append(splice_objects[d])
+        mod_packages = splice_packages(n) if runs_th[n] else early_packages
+        # These are the build tools that the module's compile may run. Only
+        # these tools are on the compile's PATH, so the compile depends only
+        # on them. GHC itself may run a build tool, such as a preprocessor
+        # that -F -pgmF names. A splice may run any of the target's build
+        # tools, so a module that runs Template Haskell gets all of them. A
+        # module compiles in the worker only if it has no tools, because the
+        # worker can't put a compile's tools on PATH (see Note [The
+        # persistent worker]).
+        module_tools = list(tools) if runs_th[n] else [p for p in program_nodes[n] if p in tools]
+        # A module without Template Haskell needs no data dirs. A Template
+        # Haskell module that may run build tools gets all the target's data
+        # dirs. Any other Template Haskell module gets only the data dirs that
+        # its splices could read. Those are the data dirs of its splices'
+        # libraries, and the data dirs of any of the target's own Paths_<pkg>
+        # modules that it imports. See Note [Data files of splices].
+        own_modules = [_module_of(d) for d in closure[n] if not _is_boot(d)]
+        module_data_dirs = compile_data_dirs(data_dirs, mod_packages.data_dirs, own_modules, len(module_tools) > 0) if runs_th[n] else {}
+        hidirs = mod_packages.local_import_dirs + [(name, d) for name, d in module_lib_dirs.items() if name in mod_packages.early_names]
+
+        # The flags specific to this module: its source and output files.
+        # They go after the flags that all the target's modules share.
+        stubdir = actions.declare_output(prefix + "stubs/" + n, dir = True, has_content_based_path = False)
+        module_flags = cmd_args("-c", src_of[n], "-o", out[o_of[n]], "-ohi", out[hi_of[n]], "-stubdir", stubdir.as_output())
+        mkdirs = [stubdir.as_output()]
+        if closure[n]:
+            module_flags.add(tag.tag_artifacts(cmd_args(_dir_of(hi_of[closure[n][0]], closure[n][0], hisuf), hidden = closure_files, format = "-i{}")))
+        # The interfaces that the module may read from dependencies compiled
+        # per-module. A Template Haskell module also gets the interfaces of the
+        # dependencies whose final dbs it compiles against, through those dbs.
+        module_flags.add(tag.tag_artifacts(cmd_args(hidden = upstream_closure_sets[n].project_as_args("interfaces"))))
+        if dynamic_too:
+            module_flags.add("-dyno", out[dyn_o_of[n]], "-dynohi", out[dyn_hi_of[n]])
+        if producing_indices:
+            # The module's .hie file. GHC writes it under -hiedir, at a path
+            # made from the module's name. It goes in the target's hi
+            # directory, which is also the target's index, as with --make.
+            hie_of[n] = actions.declare_output(prefix + "hie/" + n + "/" + _node_file(n, "hie"), has_content_based_path = False)
+            module_flags.add("-hiedir", _dir_of(hie_of[n].as_output(), n, "hie"))
+
+        # The request that the action sends to the worker, or to the compile
+        # tool if there is no worker (see Note [The persistent worker]).
+        # Request.hs in tools/ghc-api describes each argument.
+        depfile = actions.declare_output(prefix + "dep/" + n + ".dep", has_content_based_path = False)
+        request = cmd_args(
+            "--request",
+            "--contract",
+            _WORKER_CONTRACT,
+            "--libdir",
+            libdir.read_string().strip(),
+            "--depfile",
+            tag.tag_artifacts(depfile.as_output()),
+            "--abi",
+            out[abi_of[n]],
+            "--diagnostics",
+            out[diag_of[n]],
+            "--module",
+            _module_of(n).replace(".", "/"),
+            "--source",
+            src_of[n],
+            "--outdir",
+            _dir_of(out[hi_of[n]], n, hisuf),
+            "--hisuf",
+            hisuf,
+            "--boot" if _is_boot(n) else [],
+            # The modules in the closure (not just boot files), whose objects
+            # a splice may load (see Note [Template Haskell modules]).
+            ["--loadable=" + d for d in closure[n] if not _is_boot(d)] if runs_th[n] else [],
+            # Where each dependency's interfaces are, so that the tool can
+            # turn the usages GHC records into dep file entries. These are
+            # paths only, not inputs. The interfaces themselves are inputs
+            # already: through upstream_closure_sets, and, for --make
+            # libraries, through the package db flags. For a dependency
+            # compiled per-module, the path is worked out from one of its
+            # interface files, so as an input it would make the module wait
+            # for that particular interface for no reason.
+            [cmd_args(d, format = "--hidir=" + unit + "={}", ignore_artifacts = True) for unit, d in hidirs],
+            tag.tag_artifacts(cmd_args(src_tree, format = "--srcroot={}")) if src_tree != None else [],
+            cmd_args(mkdirs, format = "--mkdir={}"),
+            # See Note [Data files of splices].
+            [cmd_args(d, format = "--data-dir=" + var + "={}") for var, d in module_data_dirs.items()],
+            # See Note [Template Haskell modules], section 4.
+            "--",
+            base_cmd,
+            mod_packages.args,
+            "--",
+            module_flags,
+        )
+        # The compile tool runs the request as one `ghc -c`. With a worker,
+        # buck2 sends the request to the worker instead, and runs the compile
+        # tool only when it runs the action somewhere the worker isn't, such
+        # as on a remote executor.
+        # The worker cannot give a compile environment variables of its
+        # own, since it is a single process. So a module whose splices need
+        # the environment variables for the target's data dirs (see Note
+        # [Data files of splices]) must also compile outside the worker.
+        needs_data = len(module_data_dirs) > 0
+        script = in_env(env_with(module_tools), cmd_args(compile_script))
+        category = "haskell_compile"
+        identifier = variant + "/" + n
+        in_worker = worker_info != None and not module_tools and not needs_data
+        if worker_info != None and not in_worker:
+            outside_worker[n] = struct(tools = module_tools, data_dirs = needs_data)
+        # For allow_dep_file_cache_upload, see Note [Early cut-off by dep files], section 5.
+        if in_worker:
+            actions.run(request, exe = WorkerRunInfo(worker = worker_info, exe = script), category = category, identifier = identifier, dep_files = {"hs": tag}, allow_dep_file_cache_upload = True)
+        else:
+            actions.run(cmd_args(script, request), category = category, identifier = identifier, dep_files = {"hs": tag}, allow_dep_file_cache_upload = True)
+
+    obj_map = {}
+    hi_map = {}
+    for n, _ in nodes:
+        obj_map[_node_file(n, osuf)] = o_of[n]
+        hi_map[_node_file(n, hisuf)] = hi_of[n]
+        hi_map[_node_file(n, "abi")] = abi_of[n]
+        if n in hie_of:
+            hi_map[_node_file(n, "hie")] = hie_of[n]
+        if dynamic_too:
+            obj_map[_node_file(n, "dyn_o")] = dyn_o_of[n]
+            hi_map[_node_file(n, "dyn_hi")] = dyn_hi_of[n]
+    actions.symlinked_dir(out[objects], obj_map, has_content_based_path = False)
+    actions.symlinked_dir(out[hi], hi_map, has_content_based_path = False)
+    # The target's stubs directory is left empty. Each module writes its
+    # stub headers (the _stub.h files of its foreign exports) to a directory
+    # of its own instead. Nothing looks inside a target's stubs directory:
+    # with --make too, it is only ever an input of other actions, so an
+    # empty one is enough.
+    actions.symlinked_dir(out[stubs], {}, has_content_based_path = False)
+
+    actions.write(out[s.advice["haskell_unused_build_tools"]], json.encode(_unused_build_tools(tools, runs_th, program_nodes)))
+    actions.write(out[s.advice["haskell_template_haskell_from_flags"]], json.encode(_template_haskell_from_flags(th_nodes)))
+    actions.write(out[s.advice["haskell_ann_pragmas"]], json.encode(_ann_pragmas(th_nodes)))
+    actions.write(out[s.advice["haskell_modules_outside_worker"]], json.encode(_modules_outside_worker(outside_worker, runs_th)))
+    return [PerModuleClosures(by_module = closure_sets)]
+
+_register_modules = dynamic_actions(
+    impl = _register_modules_impl,
+    attrs = {
+        "artifacts": dynattrs.value(list[Artifact]),
+        "dep_closures": dynattrs.dict(str, dynattrs.dynamic_value()),
+        "deps": dynattrs.artifact_value(),
+        "libdir": dynattrs.artifact_value(),
+        "outputs": dynattrs.list(dynattrs.output()),
+        "s": dynattrs.value(typing.Any),
+    },
+)
+
+# The advice checks of a target compiled per-module, indexed by the names of their
+# validations (see Note [Advice]).
+ADVICE_CHECKS = ["haskell_unused_build_tools", "haskell_template_haskell_from_flags", "haskell_ann_pragmas", "haskell_modules_outside_worker"]
+
+def advice_validations(compiled: CompileResultInfo) -> list[Provider]:
+    if not compiled.advice:
+        return []
+    return [ValidationInfo(validations = [
+        ValidationSpec(name = name, validation_result = result)
+        for name, result in compiled.advice.items()
+    ])]
+
+# Identify modules that compile as Template Haskell modules because their
+# target's flags turn on TemplateHaskell or QuasiQuotes.
+def _template_haskell_from_flags(th: dict) -> dict:
+    modules = sorted([_module_of(n) for n, why in th.items() if why == "flags"])
+    return _advice(
+        [{"module": m} for m in modules],
+        "{} modules".format(len(modules)),
+        "Modules that compile as if they used Template Haskell, which is slower, because their target's flags turn on TemplateHaskell or QuasiQuotes. Turn the extensions on only in the modules that need them.",
+    )
+
+# Identify modules that use ANN pragmas (which implies TH).
+def _ann_pragmas(th: dict) -> dict:
+    modules = sorted([_module_of(n) for n, why in th.items() if why == "ann"])
+    return _advice(
+        [{"module": m} for m in modules],
+        ", ".join(modules),
+        "Modules that compile as if they used Template Haskell only because of ANN pragmas, which is slower. For HLint's, write {- HLINT ignore ... -} comments instead.",
+    )
+
+# Identify modules that are forced to compile outside the worker.
+def _modules_outside_worker(outside: dict, runs_th: dict) -> dict:
+    findings = [
+        {
+            "module": _module_of(n),
+            "tools": sorted(why.tools),
+            "template_haskell": runs_th[n],
+            "data_dirs": why.data_dirs,
+        }
+        for n, why in sorted(outside.items())
+    ]
+    def describe(f):
+        why = []
+        if f["tools"]:
+            why.append(("may run " if f["template_haskell"] else "runs ") + ", ".join(f["tools"]))
+        if f["data_dirs"]:
+            why.append("its splices may read data files")
+        return "{} ({})".format(f["module"], "; ".join(why))
+    return _advice(
+        findings,
+        "; ".join([describe(f) for f in findings]),
+        "Modules that compile without the persistent worker, which is slower. A module compiles outside it if it may run build tools (tools), or if its splices may read data files (data_dirs). A module that runs Template Haskell (template_haskell) is assumed to run any of its target's build tools.",
+    )
+
+# We special-case the build tools that we run in actions of their own, so they're never run as part of a module's
+# actual compilation action.
+_PREPROCESSORS = ["alex", "happy", "hsc2hs"]
+
+# Identify build tools which aren't used in compiling any module, as far as we can tell.
+def _unused_build_tools(tools: dict, runs_th: dict, program_nodes: dict) -> dict:
+    run = set([p for programs in program_nodes.values() for p in programs])
+    splices = any(runs_th.values())
+    findings = [
+        {"tool": t, "splices": splices}
+        for t in sorted(tools)
+        if t not in run and t not in _PREPROCESSORS
+    ]
+    return _advice(
+        findings,
+        ", ".join([f["tool"] for f in findings]) + (" (unless a splice runs them)" if splices else ""),
+        "Build tools that no module's compile runs, though where the target has Template Haskell splices (splices), a splice might. Remove them from build_tool_depends, or, for a program that runs them, move them to run_tool_depends.",
+    )
+
+# The result of an advice check. Advice checks always succeed, and the findings go in
+# the result's data. `message` says what the check found in this target, and
+# `explanation`, which is the same for every target, says what the check
+# looks for and what to do about it.
+def _advice(findings: list, message: str, explanation: str) -> dict:
+    return {"version": 1, "data": {"status": "success", "message": message if findings else "nothing to report", "explanation": explanation, "findings": findings}}
+
+# Whether the target is compiled per-module: its compile granularity is
+# "module", and it has at least one Haskell module. A target without any
+# modules always goes through compile(), which produces the empty outputs that
+# such a target needs.
+def compiles_per_module(ctx: AnalysisContext) -> bool:
+    return _compile_granularity(ctx) == "module" and has_modules(ctx)
+
+# The target's compile_granularity, or the toolchain's if the target doesn't
+# set it. A rule that has no compile_granularity attribute always compiles
+# the whole target with --make.
+def _compile_granularity(ctx: AnalysisContext) -> str:
+    if not hasattr(ctx.attrs, "compile_granularity"):
+        return "target"
+    return ctx.attrs.compile_granularity or ctx.attrs._haskell_toolchain[HaskellToolchainInfo].compile_granularity
+
+# Compile the target's sources with one action per module (see Note
+# [Per-module compilation]). It takes the same arguments as compile(), so
+# that the two are interchangeable. A splice can't call the target's own
+# native libraries, as with --make. A profiled compile gets the dynamic
+# objects its splices load from dynamic_from (see _splice_objects).
+def compile_per_module(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool, pkgname: str | None = None, dynamic_too: bool = False, dynamic_from: [CompileResultInfo, None] = None) -> CompileResultInfo:
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+    variant = variant_name(link_style, enable_profiling)
+    osuf, hisuf = output_extensions(link_style, enable_profiling)
+    prefix = per_module_dir(link_style, enable_profiling)
+
+    # When GHC's internal interpreter loads dynamic objects, a static compile
+    # makes them too, in case a splice runs one of the target's own modules
+    # (see Note [Template Haskell modules], section 6).
+    if link_style != LinkStyle("shared") and not enable_profiling and splice_objects_kind(ctx, False) == "dynamic":
+        dynamic_too = True
+
+    # The tag of every input a module's dep file may list: see Note [Early
+    # cut-off by dep files].
+    tag = ctx.actions.artifact_tag()
+
+    # A module's package flags (see _package_dbs). They have the final dbs
+    # of the prebuilt dependencies and of the local ones in `final`, and dbs
+    # that name no library for the other local ones. A module that runs no
+    # Template Haskell compiles against no local library.
+    dep_libs = list(dependency_libs(ctx, link_style, enable_profiling).traverse())
+    exposed_package_args = get_exposed_package_args(ctx, link_style, False, enable_profiling)
+
+    # The dependencies compiled per-module that some dependency built with
+    # --make depends on, found through the --make libraries' `below` sets
+    # (see Note [Compiling against dependencies module by module]).
+    below = ctx.actions.tset(HaskellLibraryInfoTSet, children = [lib.below for lib in dep_libs if lib.below != None])
+    below_make = set([lib.name for lib in below.traverse() if lib.modules != None])
+
+    # A module with explicit level imports calls this from the dynamic
+    # output, with the packages that its splice imports need.
+    def packages(final, runs_th = True):
+        dbs = _package_dbs(dep_libs, final, below_make, tag, runs_th)
+        return struct(
+            args = cmd_args(exposed_package_args, dbs.packagedb_args),
+            local_import_dirs = dbs.local_import_dirs,
+            early_names = dbs.early_names,
+            final = final,
+            # The data dirs that the Paths_<pkg> modules of the libraries in
+            # `final` read (see Note [Data files of splices]).
+            data_dirs = {var: d for lib in dep_libs if lib.name in final for var, d in lib.data_dirs.items()},
+        )
+
+    early_packages = packages(set(), runs_th = False)
+
+    # Only the actions of Template Haskell modules depend on the
+    # dependencies' libraries, because only those modules load them, and so
+    # only they have to wait for the libraries to be linked. Most Template
+    # Haskell modules use the target's set of final dbs. A module with
+    # explicit level imports narrows it to what its splices import (see Note
+    # [Explicit level imports]).
+    splice_infos = splice_dep_infos(ctx, link_style, enable_profiling)
+    target_splice_packages = packages(splice_libraries(ctx.actions, splice_infos))
+    module_libs = {lib.name: lib for lib in dep_libs if lib.modules != None}
+    this_pkg = pkgname or haskell_library_unit_id(ctx.label)
+
+    # Every module is compiled with -this-unit-id. A library's unit is the
+    # `pkgname` it is registered under. A binary's is made from the target's
+    # label, rather than GHC's default of `main`. Otherwise all binaries
+    # would share the unit `main`. A persistent worker runs the splices of
+    # many targets in one process, and its runtime would then confuse two
+    # binaries' modules that have the same name.
+    cmd_flags, file_flags = ghc_flags(ctx, link_style, enable_profiling, this_pkg, dynamic_too)
+    # The target's other sources, such as headers that a module #includes.
+    # GHC doesn't record which of these a module used, so they can't go in
+    # the dep file. Instead, every module's compile has all of them as plain
+    # inputs, as the --make compile does.
+    other_srcs = [src for _, src in srcs_to_pairs(ctx.attrs.srcs) if not is_haskell_src(src) and not src.short_path.endswith(_BOOT)]
+    # With per_module, buck2 decides when a module compiles, so GHC must
+    # never reuse an earlier result. -fforce-recomp stops it from doing that
+    # (see Note [Early cut-off by dep files]).
+    ghc_args = cmd_args(cmd_flags, file_flags, "-fforce-recomp", hidden = other_srcs)
+    base_cmd = cmd_args(haskell_toolchain.compiler, ghc_args)
+    env = ghc_env(ctx, prefix + "build-tool-depends")
+
+    # The toolchain's shared worker (see Note [The persistent worker]), or
+    # None if it has none.
+    worker_info = haskell_toolchain.per_module_shared_worker
+
+    nodes = _nodes(ctx)
+    src_of = {n: src for n, src in nodes}
+
+    # With a worker, each module's session finds the target's modules in a
+    # tree that holds just the target's sources (see Note [The persistent
+    # worker]). The tree changes whenever any of the target's sources
+    # changes, and that alone is no reason to compile every module again. So
+    # the tree is a tagged input, which only matters to a compile if its dep
+    # file lists it. A module's own source is an ordinary input as well.
+    src_tree = None
+    if worker_info != None:
+        src_tree = ctx.actions.symlinked_dir(
+            prefix + "srcs",
+            # Each source keeps its own extension, because GHC reads a file
+            # according to its extension: a .lhs file is literate Haskell,
+            # for example.
+            {_module_of(n).replace(".", "/") + src.extension: src for n, src in nodes},
+            has_content_based_path = False,
+        )
+
+    out_dir = per_module_out_dir(ctx, link_style, enable_profiling)
+    module_outputs = _declare_module_outputs(ctx, out_dir, nodes, osuf, hisuf, dynamic_too)
+    o_of = module_outputs.o
+    hi_of = module_outputs.hi
+    abi_of = module_outputs.abi
+    dyn_o_of = module_outputs.dyn_o
+    dyn_hi_of = module_outputs.dyn_hi
+    diag_of = module_outputs.diagnostics
+    dynamic_objects = o_of if link_style == LinkStyle("shared") else dyn_o_of
+    splice_objects = _splice_objects(ctx, out_dir, nodes, o_of, dynamic_objects, enable_profiling, dynamic_from)
+    objects = ctx.actions.declare_output("objects-" + variant, dir = True, has_content_based_path = False)
+    hi = ctx.actions.declare_output("hi-" + variant, dir = True, has_content_based_path = False)
+    stubs = ctx.actions.declare_output("stubs-" + variant, dir = True, has_content_based_path = False)
+    producing_indices = get_producing_indices(ctx)
+
+    # The libdir of the GHC that compiles the target. The tools need it to
+    # run GHC's code (see Libdir and Request in tools/ghc-api).
+    libdir = haskell_toolchain.libdir
+    if libdir == None:
+        fail("{}: per_module needs the Haskell toolchain's `libdir`, which print_libdir() in prelude/haskell/toolchain.bzl makes".format(ctx.label))
+
+    # Work out the module graph with GHC's own dependency analysis, which the
+    # deps tool runs (see tools/ghc-api/PerModuleDeps.hs). For each node, it
+    # finds the imports, both from this target and from dependencies,
+    # whether the node may run Template Haskell, and what it imports at the
+    # splice level. It runs against the early dbs, so it doesn't wait for
+    # any dependency compiled per-module. (It does wait for dependencies
+    # built with --make, whose interfaces are inputs of their package dbs.)
+    # The tool is given each node with its source, and the GHC flags without
+    # the compiler itself, because it runs GHC's analysis in-process.
+    deps = ctx.actions.declare_output(prefix + "deps.json")
+    ctx.actions.run(
+        # The tool takes the libdir as a flag, so the shell reads it from
+        # the file and puts the flag after the tool.
+        in_env(struct(
+            script = env.script + 'tool="$1"; libdir=$(cat "$2"); shift 2; set -- "$tool" "--libdir=$libdir" "$@"; ',
+            args = env.args,
+        ), cmd_args(
+            haskell_toolchain.per_module_deps or ctx.attrs._per_module_deps[RunInfo],
+            libdir,
+            deps.as_output(),
+            [cmd_args(n, src, delimiter = "=") for n, src in nodes],
+            "--",
+            ghc_args,
+            early_packages.args,
+            # The compiler command may carry files that the libdir is made
+            # of, so we add a dependency on it
+            hidden = haskell_toolchain.compiler,
+        )),
+        category = "haskell_deps",
+        identifier = variant,
+    )
+
+    # The output directory of each dependency compiled per-module, where the
+    # compile tool looks up its interfaces. It is worked out from the
+    # interface of the dependency's first module. Every such dependency has
+    # at least one module, since a target without any goes through compile()
+    # instead (see compiles_per_module).
+    def out_dir_of(lib):
+        m, files = list(lib.modules.items())[0]
+        return _dir_of(files.hi, m, hisuf)
+
+    module_lib_dirs = {name: out_dir_of(lib) for name, lib in module_libs.items()}
+
+    # The prebuilt dependencies' names, by unit id. The deps tool names the
+    # packages that splice imports come through by unit id.
+    prebuilt_names = {lib.id: lib.name for lib in dep_libs if lib.is_prebuilt}
+
+    modules = {
+        n: HaskellModuleFiles(hi = hi_of[n], abi = abi_of[n], dyn_hi = dyn_hi_of[n] if dynamic_too else None)
+        for n, _ in nodes
+    }
+    # The results of the advice checks (see Note [Advice]).
+    advice = {name: ctx.actions.declare_output(prefix + "advice/" + name + ".json") for name in ADVICE_CHECKS}
+    all_outputs = [objects, hi, stubs] + advice.values()
+    for files in [o_of, hi_of, abi_of, dyn_o_of, dyn_hi_of, diag_of]:
+        all_outputs += files.values()
+    closures = ctx.actions.dynamic_output_new(_register_modules(
+        s = struct(
+            label = ctx.label,
+            this_pkg = this_pkg,
+            compile_script = haskell_toolchain.per_module_compile or ctx.attrs._per_module_compile[RunInfo],
+            nodes = nodes,
+            src_of = src_of,
+            modules = modules,
+            module_libs = module_libs,
+            module_lib_dirs = module_lib_dirs,
+            prebuilt_names = prebuilt_names,
+            splice_infos = splice_infos,
+            packages = packages,
+            early_packages = early_packages,
+            target_splice_packages = target_splice_packages,
+            dynamic_too = dynamic_too,
+            o_of = o_of,
+            hi_of = hi_of,
+            abi_of = abi_of,
+            dyn_o_of = dyn_o_of,
+            splice_objects = splice_objects,
+            dyn_hi_of = dyn_hi_of,
+            diag_of = diag_of,
+            objects = objects,
+            hi = hi,
+            stubs = stubs,
+            prefix = prefix,
+            variant = variant,
+            osuf = osuf,
+            hisuf = hisuf,
+            tag = tag,
+            producing_indices = producing_indices,
+            src_tree = src_tree,
+            base_cmd = base_cmd,
+            worker_info = worker_info,
+            data_dirs = data_dirs_env(ctx),
+            tools = build_tools(ctx),
+            compile_env = haskell_toolchain.compile_env,
+            advice = advice,
+        ),
+        deps = deps,
+        libdir = libdir,
+        dep_closures = {lib.name: lib.closures for lib in module_libs.values()},
+        artifacts = all_outputs,
+        outputs = [a.as_output() for a in all_outputs],
+    ))
+    return CompileResultInfo(objects = objects, hi = hi, stubs = stubs, producing_indices = producing_indices, diagnostics = diag_of.values(), modules = modules, closures = closures, import_dir = out_dir, advice = advice, dynamic_objects = dynamic_objects)
+
+# Note [Advice]
+#
+# Some ways of declaring a target build correctly but slowly. A build tool
+# that no module's compilation action runs, for example, is still built
+# before the target's modules compile, and in a second configuration if the
+# program also runs it. The rules can spot some of these from what they
+# learn while compiling, and report them as advice.
+#
+# Each kind of advice is a check with a buck2 validation of its own (see
+# ADVICE_CHECKS), which the target returns in its ValidationInfo. A check
+# always succeeds, even when it has findings, so the advice never stops a
+# build. The findings are in the result's data, as a list under "findings",
+# with a "message" that sums them up and an "explanation" of what the check
+# looks for and what to do about it. prelude//haskell/advice.bxl turns the
+# results into one report of what there is to act on, using only these
+# fields. The prelude's
+# validation/audit_results.bxl gives the paths of the results themselves,
+# and can pick checks out by name:
+#
+#     buck2 bxl prelude//validation/audit_results.bxl:main -- --take haskell_unused_build_tools --trim true --targets //...
+#
+# A check's result is written by the dynamic output that registers the
+# target's compiles, which has the deps tool's results already, so a check
+# costs no action of its own.
+
+# Note [Per-module compilation]
+#
+# Normally a target is compiled by one `ghc --make` action. With
+# compile_granularity = "module", it is compiled by one `ghc -c` action per
+# module instead. buck2 can then:
+#
+# - run the target's modules in parallel with everything else in the build;
+# - start each module as soon as the modules it imports are compiled, even
+#   those of other targets, rather than waiting for whole targets;
+# - after an edit, run again only the modules affected.
+#
+# The price is CPU. Each `ghc -c` reads the interfaces of everything its
+# module imports (and, for Template Haskell, loads the dependencies' shared
+# libraries), which `ghc --make` does only once per target. A persistent
+# worker takes most of that cost away (see Note [The persistent worker]).
+#
+# Terms
+#
+# - Node: a module, or a module's boot file (.hs-boot). Each node has an
+#   action of its own; a boot file's comes from the "<module>-boot" entry of
+#   srcs (see _nodes). The modules that import a boot file with
+#   {-# SOURCE #-} depend on it, and so does the module itself, since GHC
+#   checks that the two agree.
+# - Module graph: the target's nodes and their imports, from GHC's own
+#   dependency analysis of all of its sources, in one action (the deps tool,
+#   tools/ghc-api/PerModuleDeps.hs). This action needs only the
+#   sources and the package dbs, not any compiled dependency, and runs again
+#   whenever a source changes. A dynamic_output reads the graph and
+#   registers the nodes' actions.
+# - Closure: everything a module imports, directly or indirectly, from the
+#   targets compiled per-module. A compile needs the interfaces of its whole
+#   closure, since GHC reads them for instances and type families. A
+#   Template Haskell module also needs the objects of its closure.
+#   Dependencies that are prebuilt or built with `ghc --make` aren't part of
+#   closures: a compile gets their modules whole, through their normal
+#   package dbs.
+# - Output directory: where all of a target's modules write their objects
+#   and interfaces. It is on the import path of every compile of the
+#   target. Its files are at fixed paths rather than content-based ones, so
+#   that GHC can find them by module name. A target has one output
+#   directory for each way it is compiled in (static, shared, profiled),
+#   named after its set of modules (see per_module_out_dir). The objects
+#   and hi directories that the rest of the rules use are built from the
+#   output directories with symlinked_dir.
+# - Early and final package db: a dependency compiled per-module is
+#   registered twice. Its "early" db names no library, and its interfaces
+#   appear one by one as its modules compile. Its "final" db is the normal
+#   one, registered once its library is linked. See Note [Compiling against
+#   dependencies module by module]. A dependency built with --make also has
+#   a "library-less" db, the final db without the library (see Note
+#   [Libraries of the early package dbs]).
+# - Template Haskell module: one that runs a splice, or evaluates an ANN
+#   pragma (GHC uses its interpreter for those too). It runs its
+#   dependencies' code at compile time, so it needs their libraries, not
+#   just their interfaces. See Note [Template Haskell modules].
+# - Dep file: the list of the inputs an action actually read, which buck2
+#   uses to decide whether to run the action again. See Note [Early cut-off
+#   by dep files].
+#
+# The other Notes, in reading order
+#
+# - Note [Compiling against dependencies module by module]: how a module
+#   can compile before its dependencies are finished.
+# - Note [Early cut-off by dep files]: which modules compile again after an
+#   edit.
+# - Note [Template Haskell modules]: what the modules that run code at
+#   compile time wait for. Note [Libraries of the early package dbs] has
+#   the package dbs each compile gets, and Note [Explicit level imports]
+#   how a module can say what its splices run.
+# - Note [The persistent worker]: compiling the modules in long-running
+#   GHC sessions rather than one `ghc -c` per module.
+
+# Note [Compiling against dependencies module by module]
+#
+# 1. The problem
+#
+# Say module X of target T imports module Y of dependency D, and X runs no
+# Template Haskell (for those, see Note [Template Haskell modules]). X needs
+# the interfaces of Y and of Y's closure. It doesn't need the rest of D: not
+# D's other interfaces, and not D's library. So X should be able to start as
+# soon as Y and its closure are compiled, however much of D is left.
+#
+# But GHC finds D's interfaces through D's package db, and a normal package
+# db is only registered once D's library is built.
+#
+# 2. The solution
+#
+# A dependency compiled per-module also has an "early" package db (see the
+# `early_db` field of HaskellLibraryInfo). It is registered before
+# anything is compiled, names no library, and has D's output directory as
+# its import directory, which fills up as D's modules compile. X compiles
+# against D's early db, and depends on just the interface files it needs.
+# (D's final db, registered once its library is linked, is the normal one
+# that `ghc --make` would use.)
+#
+# Two things tell us which interface files X needs:
+#
+# - X's own imports from dependencies come from GHC's dependency analysis,
+#   which finds each imported module in the package dbs, before its
+#   interface exists, and says which dependency (unit) it belongs to.
+# - Their closures come from the dependencies themselves. Each per-module
+#   target's dynamic output makes a closure set for each of its modules (a
+#   transitive set of the interfaces of its closure), and passes them on to
+#   its dependents (_ModuleClosureTSet). A compile's inputs are a projection
+#   of its imports' closure sets, so no target lists a whole closure.
+#
+# A dependency built with --make breaks that chain. Say library M is built
+# with --make, and imports module Y of D, which is compiled per-module. When
+# GHC reads one of M's interfaces, it may need Y's too, because M's
+# interfaces refer to things defined in Y. But M has no closure sets, so
+# nothing tells a module that imports M that it needs Y's interface.
+#
+# To cover this, each library built with --make records the libraries it
+# depends on, in the `below` field of HaskellLibraryInfo. A per-module
+# compile collects these, picks out the libraries compiled per-module
+# (below_make), and gives every one of its modules their whole interface
+# directories as tagged inputs. That doesn't make anything wait longer than
+# it already does. Every module of the target already waits for M's
+# interfaces, and M, being built with --make, can't be compiled until all of
+# D has been.
+
+# Note [Early cut-off by dep files]
+#
+# 1. The problem
+#
+# After an edit, a module should compile again only if one of the modules
+# it imports changed its ABI. (GHC's own recompilation check goes further:
+# it also looks at which of the imported module's entities the module
+# uses.) Comparing the imported modules' interface files isn't enough: an
+# interface includes a hash of its source, so even a comment-only edit
+# changes it.
+#
+# 2. The solution
+#
+# buck2 decides this for each action, from a dep file. Every file a module's
+# compile might read from other compiles is a tagged input: the interfaces,
+# and for a Template Haskell module the objects of the target's own modules.
+# (Its own source is an ordinary input, so editing it always compiles it
+# again.) After the compile, the action lists the tagged inputs it actually
+# read. On the next build, buck2 runs the action again only if one of those
+# has changed.
+#
+# The list comes from the usages GHC records in the new interface, which are
+# also what GHC's own recompilation check reads:
+#
+# - For each imported module, its .abi file, which holds just the
+#   interface's ABI hash. Each action writes one next to its interface, from
+#   the interface itself (DepFile in tools/ghc-api, which the compile tool
+#   and the persistent worker share).
+# - The objects of the target's own modules that a splice loaded, which GHC
+#   records as dependent files. (The dependencies' libraries are plain
+#   inputs instead, as Note [Template Haskell modules] explains.)
+#
+# 3. buck2 decides, not GHC
+#
+# buck2 removes an action's previous outputs before running it, so GHC's
+# recompilation check never has anything to compare against, and the module
+# compiles whenever the action runs. GHC's check would also notice a change
+# to the code a splice ran, since it records the hash of each object and
+# Haskell library the splice loaded. But it doesn't record extra-libraries,
+# which is how the package dbs here name a library, so the libraries are
+# inputs of the compile instead (see Note [Template Haskell modules]).
+#
+# 4. Coarser than GHC's check
+#
+# The dep file names a whole imported module's ABI. So a module that imports
+# `A (f)` compiles again when A gains an export, or when A's g changes,
+# though GHC's check would know that neither matters to it. The cascade
+# usually stops there: the module's _own_ ABI comes out the same, so its
+# importers don't compile again.
+#
+# GHC's interface has what we'd need for a finer cut-off: the hash of the
+# export list, and of each entity the module used. A module's compile could
+# write those as separate files (a directory per module), and its importers'
+# dep files would list only the ones they used.
+#
+# 5. With a remote cache
+#
+# buck2 keeps dep files in the daemon's memory, so a new daemon, or a new
+# checkout, has none, and a module whose tagged inputs changed compiles
+# again even if it read none of them. A remote cache can keep the dep files
+# too. buck2 then also stores each compile's result under a key that leaves
+# out the tagged inputs, together with its dep file, and reuses the result
+# if the inputs that the dep file lists are unchanged. The compiles allow
+# that with allow_dep_file_cache_upload, which only uploads where results
+# are uploaded at all, and the execution platform that uses the cache turns
+# it on with remote_dep_file_cache_enabled.
+
+# Note [Template Haskell modules]
+#
+# 1. The problem
+#
+# A Template Haskell module runs its dependencies' code at compile time, so
+# it needs their libraries, not just their interfaces. That means waiting
+# for its dependencies to be linked, which loses much of the parallelism
+# that compiling per-module gains.
+#
+# 2. What it waits for
+#
+# A Template Haskell module compiles against the final package dbs of the
+# local dependencies that the target's splice_depends lists (see
+# target_splice_libraries in compile.bzl), with their libraries and the native
+# libraries they depend on as inputs. So it waits only for those libraries
+# (and those of their own dependencies), and compiles against library-less
+# dbs for the other local dependencies, like any other module. The prebuilt packages'
+# libraries are there from the start, so a Template Haskell module gets
+# them all.
+#
+# A module with explicit level imports narrows the target's list further,
+# to the libraries that its splices import. See Note [Explicit level
+# imports].
+#
+# Note [Libraries of the early package dbs] has a table of which package db
+# a compile gets for each dependency. If a splice runs code from a
+# dependency that was left out, the compile fails, and GHC names the symbol
+# it couldn't load. In the persistent worker the compile may succeed
+# instead (see section 5).
+#
+# 3. Why the libraries aren't in the dep file
+#
+# The libraries are plain inputs of the compile, rather than tagged inputs
+# that its dep file lists. So the module compiles again whenever one of them
+# is linked again, even if its splices didn't use it. The dep file can't
+# list just the libraries that the splices used, because nothing records
+# them. GHC records in a module's interface each Haskell library (from
+# hs-libraries) that its splices loaded. But the package dbs here name a
+# package's library as one of its extra-libraries, which GHC doesn't record.
+# So a splice that ran a dependency's code leaves no trace of the
+# dependency's library in the interface, and yet a change to that code must
+# compile the module again.
+#
+# 4. Native libraries
+#
+# A library that buck2 links refers to the native libraries it was linked
+# against by soname, but it has no RUNPATH to find them. So a splice that
+# loads such a library relies on its package db naming them, for GHC's
+# interpreter to load first (see Note [Native libraries in package dbs] in
+# haskell.bzl). A Template Haskell module needs nothing from its
+# environment for them, so it can compile in the persistent worker.
+#
+# 5. Splices in the persistent worker
+#
+# GHC's internal interpreter runs splices in GHC's own process. For a
+# `ghc -c`, that process compiles one module, so any state is limited in
+# scope. The persistent worker is one process which is shared by every
+# session for the length of a build. (buck2 starts a worker for each
+# WorkerInfo, and the toolchain makes one WorkerInfo for each
+# configuration. buck2 starts the worker again in each build.) This means
+# we don't get proper isolation between splices. So in the worker:
+#
+# - A splice can run code from a library that another target's splice has
+#   loaded, without having that library as an input. This means that in
+#   principle a dependency left out of splice_depends can go
+#   unnoticed, depending on the order the modules compile in.
+# - The splices of different targets share the global state of a library
+#   they both run.
+# - A splice that crashes the process fails every compile action that the
+#   worker is running, not just its own module's.
+#
+# The rules' tests have some expected-failure tests for these cases.
+#
+# Some modules really need a different environment (e.g. they need data
+# files). So these have to be compiled outside the worker currently.
+#
+# A target compiled with -fexternal-interpreter (in its compiler_flags, or
+# the toolchain's) runs its splices in external interpreters instead. In the
+# worker, each session has an interpreter of its own, a process which loads
+# the libraries that the session's splices run. (GHC chooses the interpreter
+# when a session starts, so the flag has no effect in a module's
+# OPTIONS_GHC pragma.) A session belongs to one target, so the splices of
+# different targets don't share libraries or their state, and a splice that
+# crashes its interpreter fails only the compiles of its own session. The
+# splices of one session still share a library's global state, as those of
+# one target do with --make. The cost is a process for each session that
+# runs splices, and the time to send code and values to it. Before GHC
+# 9.12, GHC doesn't stop two compiles from using one interpreter at once,
+# so the compiles of a session that run splices take turns (see
+# interpreterLock in the worker).
+#
+# In a static or profiled build (the opt and prof modes), the interpreter
+# is static or profiled too. It loads a local library's archive with GHC's
+# own linker, and the shared libraries of the library's native dependencies
+# because its package db names them (see Note [Native libraries in package
+# dbs] in haskell.bzl).
+#
+# 6. Splices that run the target's own modules
+#
+# A splice can run code of the target's own modules, as it can with --make.
+# GHC loads the objects of those modules from the output directory. So the
+# compile action of a Template Haskell module has the objects of all the
+# modules in its closure as tagged inputs. Its dep file lists only the
+# objects that a splice actually loaded (see Note [Early cut-off by dep
+# files]).
+#
+# When GHC loads one of the target's modules, it also loads the libraries
+# that the module uses. It does this even when the splice only reads a
+# value from one of those libraries, because GHC links whole modules along
+# with their imports. So splice_depends has to list those libraries too,
+# as it does with --make.
+#
+# Which objects GHC loads depends on the interpreter that runs the splice,
+# as it does with --make (see _splice_objects):
+#
+# - The internal interpreter of a dynamically linked GHC loads dynamic
+#   objects. A shared compile's own objects are dynamic. A static compile
+#   makes dynamic objects, its .dyn_o files, only with -dynamic-too.
+# - A profiled compile makes no dynamic objects. So the internal
+#   interpreter loads the dynamic objects of the non-profiled compile
+#   instead, which compile() also arranges for --make.
+# - With -fexternal-interpreter, the interpreter is built in the same way
+#   as the compile, so it loads the objects that the compile makes itself.
+#
+# --make gets GHC to add -dynamic-too for just the modules that splices
+# need. A per-module compile can't do that, because it learns which modules
+# those are only after the deps tool has run. So when GHC's internal
+# interpreter loads dynamic objects, every non-profiled static compile uses
+# -dynamic-too, even in a target with no splices. That makes such a compile
+# cost about as much as two. A profiled compile takes its dynamic objects
+# from the non-profiled compile that its caller passes as `dynamic_from`.
+#
+# A splice can't call the target's own native libraries. That isn't
+# supported with --make either.
+#
+# 7. Modules behind boot files
+#
+# Say that the Template Haskell module T imports A, and that A imports B
+# with {-# SOURCE #-}. T's closure has A and B's boot file, but not B
+# itself, because B may not be compiled yet. If a splice in T runs A's
+# code, that code may call B's, and then GHC has to link B. But B's object
+# isn't an input of T's compile. So with per_module, a splice can't run
+# code of a module that T reaches only through boot files. GHC might still
+# find B's object in the output directory, left there by an earlier build,
+# but then T's compile would depend on a file that buck2 doesn't know
+# about. So the compile fails if a splice loaded such an object (see
+# DepFile in tools/ghc-api).
+#
+# In the persistent worker, a splice like this can fail even when T also
+# imports B normally. T's session sees B in the way that T's imports record
+# it, and if one of those imports records only B's boot interface, GHC's
+# linker won't load B.
+#
+# 8. Finding the Template Haskell modules
+#
+# Which modules run Template Haskell has to be decided before anything is
+# compiled. The deps tool asks GHC which extensions each module has, from its
+# pragmas and the target's flags, and looks for ANN pragmas in its
+# (preprocessed) source. That can find too much (an ANN pragma in a comment,
+# say), but it's better to be conservative. It doesn't catch GHC plugins.
+
+# Note [Libraries of the early package dbs]
+#
+# 1. The problem
+#
+# A Template Haskell module runs code in GHC's interpreter, which first
+# loads the library of every package on the command line, and of their
+# dependencies (GHC's "preload" units), whether or not the splice uses it.
+# A dynamically linked GHC tolerates a missing library file. It warns, or
+# says nothing, and carries on. But a library that is there, and was linked
+# against one that isn't, fails to load in the system's dynamic linker, and
+# then the compile fails. buck2 doesn't sandbox local actions, so a library
+# that a compile doesn't declare as an input may or may not be on disk. It
+# may not have been linked yet, or not materialised, even if a library next
+# to it has been.
+#
+# 2. The solution
+#
+# Every package db that a compile gets either names no library, or names
+# one that the compile depends on. For each local dependency, a compile
+# gets either a db that names no library (the early db of one compiled
+# per-module, or the library-less db of one built with --make), or its
+# final db, which names the library and brings it as an input of the
+# compile. The prebuilt packages share one db, whose libraries exist before
+# the build starts:
+#
+#                                 local dependency         prebuilt
+#                                 (per-module, --make)     dependency
+#   module that runs no TH        no library               final
+#   TH module                     final if listed,         final
+#                                 else no library
+#   TH module, explicit level     final if listed and      final
+#   imports                       its splice imports
+#                                 need it,
+#                                 else no library
+#
+# A final db comes with the final dbs of the dependency's closure. A module
+# that runs no Template Haskell never starts the interpreter, so it doesn't
+# depend on the libraries of the final dbs it gets.
+
+# Note [Explicit level imports]
+#
+# 1. The idea
+#
+# With ExplicitLevelImports (GHC 9.14 and later), or
+# NoImplicitStagePersistence, a splice or ANN pragma can only use what the
+# module imports with `import splice`. Using a name imported otherwise, even
+# from the Prelude, is a level error. So those imports tell us exactly what
+# code the module's splices may run, and so which libraries its compile
+# needs:
+#
+# - A module of a dependency needs that dependency's library, and the
+#   libraries of its own dependencies (see Note [Libraries of the early
+#   package dbs]).
+# - A module of the target itself might use any of the target's splice
+#   dependencies, so the module gets the target's whole set (see Note
+#   [Template Haskell modules], section 6).
+#
+# The splice imports refine the target's splice_depends, as a module's
+# imports refine its target's dependencies. The module compiles against the
+# final dbs of the listed dependencies, local or prebuilt, that its splice
+# imports come through, and against dbs that name no library for the
+# others. So it waits only for those libraries, even if its target lists
+# more. A module that a dependency re-exports comes through that
+# dependency, whose closure has the package that defines it.
+#
+# A splice import from a dependency outside the closures of the listed ones
+# is an error, as an import from a package that isn't a dependency is. A
+# dependency inside one of those closures that isn't listed itself has no
+# closure of its own here, so a module that imports from it gets the
+# target's whole set. This works for dependencies built with --make too,
+# since GHC's dependency analysis says which dependency any imported module
+# comes from.
+#
+# 2. Finding the splice imports
+#
+# The deps tool reads each import's level from GHC's summary of the module,
+# whose imports carry a level from GHC 9.14. It decides whether the module
+# has explicit level imports from the module's extensions, which come from
+# its pragmas and the target's flags.
+
+# Note [The persistent worker]
+#
+# 1. The problem
+#
+# Compiling per-module uses more CPU than --make, and most of the extra cost
+# comes from starting a new GHC for every module. Each of those GHCs reads
+# the interfaces of everything its module imports, so an interface that 100
+# modules import is read 100 times, where --make reads it once.
+#
+# 2. The solution
+#
+# A buck2 persistent worker is a long-running process that buck2 sends
+# actions to. Ours (prelude/haskell/tools/worker) compiles each module as it arrives,
+# concurrently with the others, in a GHC session that keeps the interfaces
+# it has read. It is configured by `[haskell] per_module_worker` (see
+# prelude/haskell/per_module_worker.bzl).
+#
+# 3. The request
+#
+# A module's action sends the same request whether or not there is a
+# worker. The request goes either to the worker, or to the compile tool,
+# which runs it as one `ghc -c`. It holds the module's source, the libdir
+# of the GHC that compiles it, and the compile's flags. The flags come in
+# two parts:
+#
+# - The session flags are the same for all of the target's modules that run
+#   no Template Haskell. Its Template Haskell modules have session flags of
+#   their own, because their package dbs differ (see Note [Libraries of the
+#   early package dbs]). The worker keeps a session for each distinct set of
+#   session flags.
+# - The module flags are the module's own. The worker uses only the output
+#   flags among them: -o, -ohi, -dyno, -dynohi, -hiedir and -stubdir.
+#
+# The request names its version (_WORKER_CONTRACT), so that a worker built
+# for another version of the rules refuses it.
+#
+# 4. Which worker takes a module
+#
+# buck2 starts a process for each worker (WorkerInfo) that an action names,
+# and keeps it until the end of the build. A worker per target would be
+# hundreds of processes in a large project, each with its own runtime and
+# sessions, which would take far too much memory. So the targets share one
+# worker, made once by the toolchain.
+#
+# The worker is a single process, so it can't give each request its own
+# environment variables or PATH. That means the shared worker can only
+# compile modules that need nothing from their target's environment.
+#
+# What a module may need from that environment is its target's build tools,
+# which a compile without the worker finds on PATH. Most modules never run
+# one. For example, a target that uses alex has a module generated from a
+# .x file, but alex runs in an action of its own, before the compile. A
+# module runs a build tool in one of two ways:
+#
+# - GHC runs a program for it that GHC finds on PATH. An example is a
+#   preprocessor that the module's OPTIONS_GHC pragma names with -F -pgmF,
+#   such as hspec-discover. The target's flags can name one too, for all of
+#   its modules. The deps tool reports these programs by name, and the
+#   module's tools are the target's build tools of those names.
+# - A splice of the module runs a program. Nothing can tell which programs
+#   a splice runs, so a module that runs Template Haskell is taken to need
+#   all its target's build tools.
+#
+# A module's compile has only its own tools on PATH, and so a change to a
+# build tool recompiles only the modules that may run it. A Template Haskell
+# module may also need environment variables for the libraries its splices
+# run: their data dirs (see Note [Data files of splices]).
+#
+# A module with any tools is compiled without a worker, by its own `ghc -c`.
+# Giving each such target a worker of its own, running in the target's
+# environment, would compile them faster. But each of those
+# workers would keep its memory until the end of the build, and there may be
+# dozens of them.
+#
+# 5. The import path
+#
+# A session finds the modules that a compile imports by looking up their
+# names on an import path. The import path is a tree that holds just the
+# target's sources. The project's source directories won't do, because they
+# can hold modules of other targets too, such as a sublibrary's, and the
+# session could find one of those instead of the target's own module of the
+# same name.
+#
+# 6. Memory and concurrency
+#
+# A worker lives for one build. It drops a target's sessions once all the
+# target's modules are compiled. It also keeps a bounded number of sessions,
+# dropping the least recently used idle ones (see Note [Dropping the idle
+# sessions] in prelude/haskell/tools/worker/src/Worker.hs). It has no concurrency
+# limit of its own. buck2's -j already limits the actions that run in workers,
+# along with all the others, and a lower limit for each worker would only hold
+# back a target's modules.
+
+# Note [Data files of splices]
+#
+# A package's Paths_<pkg> module finds the package's data files by reading
+# the environment variable <pkg>_datadir. The variable's value comes from
+# the target's data_dirs attribute (see data_dirs_env). If a splice runs
+# code that reads data files, the compile that runs the splice has to set
+# these variables.
+#
+# A module whose compile needs any of these variables can't compile in the
+# worker (see the last paragraph). In a large project nearly every target
+# has some data dirs, so setting all of them for every Template Haskell
+# module would keep most of those modules out of the worker. Instead, each
+# Template Haskell module gets only the variables that its splices could
+# read.
+#
+# Working those out relies on two facts. First, a splice can only run code
+# from the libraries in its splice set, and from the target's own modules
+# that the module imports, directly or indirectly (see Note [Template
+# Haskell modules], section 6). Second, code can only read the data files
+# of its own package, and it does that through the package's Paths_<pkg>
+# module. So a module needs <pkg>_datadir only if one of the libraries in
+# its splice set has a Paths_<pkg> module, or if it imports a Paths_<pkg>
+# module of its own target. Each library records the data dirs that its
+# own Paths_<pkg> modules read (see own_data_dirs in compile.bzl), and most
+# Template Haskell modules need none of them. A --make compile works out
+# its variables in the same way, but for the whole target. Its splices can
+# run code of any of the target's modules, so it includes all the target's
+# own Paths_<pkg> modules. compile_data_dirs in compile.bzl does this for
+# both kinds of compile.
+#
+# Build tools are an exception. A build tool might read data files of its
+# own, and we can't tell which. So a module that might run one of the
+# target's build tools gets all the target's data dirs. A --make compile
+# of a target that has any build tools does too.
+#
+# A module that needs data dirs gets them in its request, as
+# --data-dir=VAR=DIR, and they are inputs of its compile. The compile tool
+# sets the variables for `ghc -c`, which runs the splices in its own
+# process. The worker can't do that, because all its sessions share one
+# environment. So a module that needs data dirs compiles outside the
+# worker.
diff --git a/buck2/prelude/haskell/ghc_api_tool.bzl b/buck2/prelude/haskell/ghc_api_tool.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/ghc_api_tool.bzl
@@ -0,0 +1,125 @@
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//haskell:toolchain.bzl", "HaskellToolchainInfo", "compile_env_script", "in_compile_env")
+
+# Rule to build a local tool that uses the GHC API. It has to be able
+# to read .hi files generated by the toolchain's GHC, so it must be
+# built by the same GHC. It can only depend on GHC and GHC's built-in
+# packages. We can't use haskell rules to build it because that would
+# be a cyclic dependency, hence this rather horrible hand-crafted
+# rule.
+#
+# The rules pass the program GHC's libdir when they run it (see Libdir in
+# tools/ghc-api).
+
+def _haskell_ghc_api_tool_impl(ctx: AnalysisContext) -> list[Provider]:
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+    srcs = ctx.actions.symlinked_dir("srcs", {src.basename: src for src in ctx.attrs.srcs}, has_content_based_path = False)
+    exe = build_ghc_api_tool(
+        ctx.actions,
+        ctx.attrs.name,
+        haskell_toolchain.compiler,
+        haskell_toolchain.compile_env,
+        [cmd_args(srcs, format = "-i{}")],
+        cmd_args(srcs, ctx.attrs.main, delimiter = "/"),
+        GHC_API_TOOL_PACKAGES,
+        [],
+    )
+    return [DefaultInfo(default_output = exe), RunInfo(args = cmd_args(exe))]
+
+# Build a program that uses the GHC API, with `compiler`, from the Main
+# module `main` and the modules that the -i flags `includes` find, using only
+# GHC's own `packages`.
+#
+# This is a function rather than just a rule, so that a toolchain can build
+# such a program with its own compiler. It can't do that through a
+# rule without depending on itself.
+def build_ghc_api_tool(actions: AnalysisActions, name: str, compiler, compile_env: dict[str, str], includes: list, main, packages: list[str], flags: list[str]) -> Artifact:
+    # Run GHC with the toolchain's compile_env set, as every GHC command is.
+    env_script = compile_env_script(compile_env)
+    exe = actions.declare_output(name)
+    actions.run(
+        in_compile_env(env_script, [], cmd_args(
+            "sh",
+            "-c",
+            'exec "$@" -outputdir "$BUCK_SCRATCH_PATH"',
+            "sh",
+            compiler,
+            "-v0",
+            "-O",
+            # Use only GHC's own packages, ignoring any package environment
+            # file (one in the project, for example).
+            "-package-env=-",
+            "-hide-all-packages",
+            [["-package", p] for p in packages],
+            # Leave out the debug information that the GHC library may have:
+            # with it, each tool can be a gigabyte.
+            "-optl-Wl,-S",
+            flags,
+            includes,
+            main,
+            "-o",
+            exe.as_output(),
+        )),
+        category = "haskell_ghc_api_tool",
+        identifier = name,
+    )
+    return exe
+
+# The packages the tools use, all of which come with GHC.
+GHC_API_TOOL_PACKAGES = ["base", "bytestring", "containers", "directory", "filepath", "ghc", "ghc-boot", "process"]
+
+# The tools of the per-module compiles, by the name of their Main module. The
+# tools' sources are in prelude//haskell/tools/ghc-api, and each source is
+# also a target of prelude//haskell/tools, named after its path there.
+GHC_API_TOOLS = {
+    "per_module_compile": "PerModuleCompile",
+    "per_module_deps": "PerModuleDeps",
+}
+
+# The modules that the tools share.
+_SHARED_MODULES = ["Contract", "DepFile", "Imports", "Interface", "Libdir", "Pragmas", "Request"]
+
+def ghc_api_tool_srcs(tool: str) -> dict[str, str]:
+    """The `srcs` of a haskell_binary() that builds one of GHC_API_TOOLS,
+    keyed by module name.
+
+    A toolchain whose GHC is built from source can't use the tools that
+    haskell_ghc_api_tool() builds, because they are linked with the GHC
+    library of the GHC that builds them. It can build its own instead, as
+    haskell_binary() targets that depend on the GHC library of the GHC that
+    the toolchain runs, and pass them in the toolchain's `per_module_deps`
+    and `per_module_compile`.
+    """
+    def src(module):
+        return "prelude//haskell/tools:ghc-api/{}.hs".format(module)
+    srcs = {module: src(module) for module in _SHARED_MODULES}
+    srcs["Main"] = src(GHC_API_TOOLS[tool])
+    return srcs
+
+def ghc_api_tool_sources() -> list[str]:
+    """The tools' source files, relative to prelude//haskell/tools."""
+    return ["ghc-api/{}.hs".format(module) for module in _SHARED_MODULES + GHC_API_TOOLS.values()]
+
+def check_ghc_api_tool_sources(found: list[str]):
+    """Fails if a source in `found` isn't one of ghc_api_tool_sources().
+
+    The modules are listed here, rather than found with a glob, because a
+    toolchain in another cell can't glob the tools' directory. So the
+    directory's BUCK file passes its own glob here, to make sure that a new
+    module doesn't go unlisted.
+    """
+    missing = [src for src in found if src not in ghc_api_tool_sources()]
+    if missing:
+        fail("add these modules to GHC_API_TOOLS or _SHARED_MODULES in ghc_api_tool.bzl: " + ", ".join(missing))
+
+haskell_ghc_api_tool = rule(
+    impl = _haskell_ghc_api_tool_impl,
+    attrs = {
+        # The program's modules. They must all be in the same directory,
+        # which is the program's only source directory.
+        "srcs": attrs.list(attrs.source()),
+        # The file name of the Main module, which must be one of `srcs`.
+        "main": attrs.string(),
+        "_haskell_toolchain": toolchains_common.haskell(),
+    },
+)
diff --git a/buck2/prelude/haskell/haskell.bzl b/buck2/prelude/haskell/haskell.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/haskell.bzl
@@ -0,0 +1,1904 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Implementation of the Haskell build rules.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:archive.bzl", "make_archive")
+load(
+    "@prelude//cxx:cxx.bzl",
+    "get_auto_link_group_specs",
+)
+load(
+    "@prelude//cxx:cxx_context.bzl",
+    "get_cxx_toolchain_info",
+)
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",
+    "LinkerType",
+    "PicBehavior",
+)
+load("@prelude//cxx:groups.bzl", "get_dedupped_roots_from_groups")
+load(
+    "@prelude//cxx:link_groups.bzl",
+    "BuildLinkGroupsContext",
+    "LinkGroupContext",
+    "collect_linkables",
+    "create_link_groups",
+    "find_relevant_roots",
+    "get_filtered_labels_to_links_map",
+    "get_filtered_links",
+    "get_link_group_info",
+    "get_link_group_preferred_linkage",
+    "get_public_link_group_nodes",
+    "get_transitive_deps_matching_labels",
+    "is_link_group_shlib",
+)
+load(
+    "@prelude//cxx:linker.bzl",
+    "LINKERS",
+    "get_rpath_origin",
+    "get_shared_library_flags",
+)
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorArgs",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+)
+load(
+    "@prelude//haskell:compile.bzl",
+    "CompileResultInfo",
+    "compile",
+    "data_dirs_env",
+    "own_data_dirs",
+    "dependency_libs",
+)
+load(
+    "@prelude//haskell:compile_per_module.bzl",
+    "advice_validations",
+    "compile_per_module",
+    "compiles_per_module",
+)
+load(
+    "@prelude//haskell:haskell_haddock.bzl",
+    "haskell_haddock_lib",
+)
+load(
+    "@prelude//haskell:library_info.bzl",
+    "HaskellLibraryInfo",
+    "HaskellLibraryInfoTSet",
+    "HaskellLibraryProvider",
+    "HaskellModuleFiles",
+)
+load(
+    "@prelude//haskell:link_info.bzl",
+    "HaskellLinkInfo",
+    "HaskellProfLinkInfo",
+    "attr_link_style",
+    "cxx_toolchain_link_style",
+)
+load(
+    "@prelude//haskell:toolchain.bzl",
+    "HaskellToolchainInfo",
+)
+load(
+    "@prelude//haskell:util.bzl",
+    "attr_deps",
+    "attr_deps_haskell_link_infos_sans_template_deps",
+    "attr_deps_merged_link_infos",
+    "attr_deps_shared_library_infos",
+    "variant_name",
+    "haskell_library_name",
+    "haskell_library_unit_id",
+    "is_haskell_src",
+    "output_extensions",
+    "src_to_module_name",
+    "module_name_to_file",
+    "srcs_to_pairs",
+)
+load(
+    "@prelude//linking:link_groups.bzl",
+    "gather_link_group_libs",
+    "merge_link_group_lib_info",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "Archive",
+    "ArchiveContentsType",
+    "ArchiveLinkable",
+    "LibOutputStyle",
+    "LinkArgs",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkOrdering",
+    "LinkStyle",
+    "LinkedObject",
+    "MergedLinkInfo",
+    "SharedLibLinkable",
+    "create_merged_link_info",
+    "default_output_style_for_link_strategy",
+    "get_lib_output_style",
+    "get_link_args_for_strategy",
+    "get_output_styles_for_linkage",
+    "get_own_link_infos",
+    "legacy_output_style_to_link_style",
+    "process_link_strategy_for_pic_behavior",
+    "process_output_style_for_pic_behavior",
+    "to_link_strategy",
+    "unpack_link_args",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+    "create_linkable_node",
+    "reduce_linkable_graph",
+)
+load(
+    "@prelude//linking:linkables.bzl",
+    "linkables",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "create_shared_libraries",
+    "create_shlib_symlink_tree",
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load(
+    "@prelude//python:python.bzl",
+    "PythonLibraryInfo",
+)
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load("@prelude//utils:utils.bzl", "filter_and_map_idx", "flatten")
+
+HaskellIndexingTSet = transitive_set()
+
+# A list of hie dirs
+HaskellIndexInfo = provider(
+    fields = {
+        "info": provider_field(typing.Any, default = None),  # dict[LinkStyle, HaskellIndexingTset]
+    },
+)
+
+# This conversion is non-standard, see TODO about link style below
+def _to_lib_output_style(link_style: LinkStyle) -> LibOutputStyle:
+    return default_output_style_for_link_strategy(to_link_strategy(link_style))
+
+def _attr_preferred_linkage(ctx: AnalysisContext) -> Linkage:
+    preferred_linkage = ctx.attrs.preferred_linkage
+
+    # force_static is deprecated, but it has precedence over preferred_linkage
+    if getattr(ctx.attrs, "force_static", False):
+        preferred_linkage = "static"
+
+    return Linkage(preferred_linkage)
+
+# --
+
+def _get_haskell_prebuilt_libs(ctx, link_style: LinkStyle, enable_profiling: bool) -> list[Artifact]:
+    if link_style == LinkStyle("shared"):
+        if enable_profiling:
+            # Profiling doesn't support shared libraries
+            return []
+
+        return ctx.attrs.shared_libs.values()
+    elif link_style == LinkStyle("static"):
+        if enable_profiling:
+            return ctx.attrs.profiled_static_libs
+        return ctx.attrs.static_libs
+    elif link_style == LinkStyle("static_pic"):
+        if enable_profiling:
+            return ctx.attrs.pic_profiled_static_libs
+        return ctx.attrs.pic_static_libs
+    else:
+        fail("Unexpected LinkStyle: " + link_style.value)
+
+def haskell_prebuilt_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    # MergedLinkInfo for both with and without profiling
+    native_infos = []
+    prof_native_infos = []
+
+    haskell_infos = []
+    shared_library_infos = []
+    for dep in ctx.attrs.deps:
+        used = False
+        if HaskellLinkInfo in dep:
+            used = True
+            haskell_infos.append(dep[HaskellLinkInfo])
+        li = dep.get(MergedLinkInfo)
+        if li != None:
+            used = True
+            native_infos.append(li)
+            if HaskellLinkInfo not in dep:
+                prof_native_infos.append(li)
+        if HaskellProfLinkInfo in dep:
+            prof_native_infos.append(dep[HaskellProfLinkInfo].prof_infos)
+        if SharedLibraryInfo in dep:
+            used = True
+            shared_library_infos.append(dep[SharedLibraryInfo])
+        if PythonLibraryInfo in dep:
+            used = True
+        if not used:
+            fail("Unexpected link info encountered")
+
+    hlibinfos = {}
+    prof_hlibinfos = {}
+    hlinkinfos = {}
+    prof_hlinkinfos = {}
+    link_infos = {}
+    prof_link_infos = {}
+    for link_style in LinkStyle:
+        libs = _get_haskell_prebuilt_libs(ctx, link_style, False)
+        prof_libs = _get_haskell_prebuilt_libs(ctx, link_style, True)
+
+        hlibinfo = HaskellLibraryInfo(
+            name = ctx.attrs.name,
+            db = ctx.attrs.db,
+            import_dirs = [],
+            stub_dirs = [],
+            id = ctx.attrs.id,
+            libs = libs,
+            version = ctx.attrs.version,
+            is_prebuilt = True,
+            profiling_enabled = False,
+        )
+        prof_hlibinfo = HaskellLibraryInfo(
+            name = ctx.attrs.name,
+            db = ctx.attrs.db,
+            import_dirs = [],
+            stub_dirs = [],
+            id = ctx.attrs.id,
+            libs = prof_libs,
+            version = ctx.attrs.version,
+            is_prebuilt = True,
+            profiling_enabled = True,
+        )
+
+        def archive_linkable(lib):
+            return ArchiveLinkable(
+                archive = Archive(artifact = lib),
+                linker_type = LinkerType("gnu"),
+            )
+
+        def shared_linkable(lib):
+            return SharedLibLinkable(
+                lib = lib,
+            )
+
+        linkables = [(shared_linkable if link_style == LinkStyle("shared") else archive_linkable)(lib) for lib in libs]
+        prof_linkables = [(shared_linkable if link_style == LinkStyle("shared") else archive_linkable)(lib) for lib in prof_libs]
+
+        hlibinfos[link_style] = hlibinfo
+        hlinkinfos[link_style] = ctx.actions.tset(
+            HaskellLibraryInfoTSet,
+            value = hlibinfo,
+            children = [lib.info[link_style] for lib in haskell_infos],
+        )
+        prof_hlibinfos[link_style] = prof_hlibinfo
+        prof_hlinkinfos[link_style] = ctx.actions.tset(
+            HaskellLibraryInfoTSet,
+            value = prof_hlibinfo,
+            children = [lib.prof_info[link_style] for lib in haskell_infos],
+        )
+        link_infos[link_style] = LinkInfos(
+            default = LinkInfo(
+                pre_flags = ctx.attrs.exported_linker_flags,
+                post_flags = ctx.attrs.exported_post_linker_flags,
+                linkables = linkables,
+            ),
+        )
+        prof_link_infos[link_style] = LinkInfos(
+            default = LinkInfo(
+                pre_flags = ctx.attrs.exported_linker_flags,
+                post_flags = ctx.attrs.exported_post_linker_flags,
+                linkables = prof_linkables,
+            ),
+        )
+
+    haskell_link_infos = HaskellLinkInfo(
+        info = hlinkinfos,
+        prof_info = prof_hlinkinfos,
+    )
+    haskell_lib_provider = HaskellLibraryProvider(
+        lib = hlibinfos,
+        prof_lib = prof_hlibinfos,
+    )
+
+    # The link info that will be used when this library is a dependency of a non-Haskell
+    # target (e.g. a cxx_library()). We need to pick the profiling libs if we're in
+    # profiling mode.
+    default_link_infos = prof_link_infos if ctx.attrs.enable_profiling else link_infos
+    default_native_infos = prof_native_infos if ctx.attrs.enable_profiling else native_infos
+    merged_link_info = create_merged_link_info(
+        ctx,
+        # We don't have access to a CxxToolchain here (yet).
+        # Give that it's already built, this doesn't mean much, use a sane default.
+        pic_behavior = PicBehavior("supported"),
+        link_infos = {_to_lib_output_style(s): v for s, v in default_link_infos.items()},
+        exported_deps = default_native_infos,
+    )
+
+    prof_merged_link_info = create_merged_link_info(
+        ctx,
+        # We don't have access to a CxxToolchain here (yet).
+        # Give that it's already built, this doesn't mean much, use a sane default.
+        pic_behavior = PicBehavior("supported"),
+        link_infos = {_to_lib_output_style(s): v for s, v in prof_link_infos.items()},
+        exported_deps = prof_native_infos,
+    )
+
+    solibs = {}
+    for soname, lib in ctx.attrs.shared_libs.items():
+        solibs[soname] = LinkedObject(output = lib, unstripped_output = lib)
+    shared_libs = create_shared_libraries(ctx, solibs)
+
+    # The executables that depend on this library have its runtime_shared_libs
+    # in their symlink trees of shared libraries, along with its shared_libs.
+    # The linkable graph only has the shared_libs, so nothing is linked
+    # against the runtime_shared_libs.
+    for soname, lib in ctx.attrs.runtime_shared_libs.items():
+        solibs[soname] = LinkedObject(output = lib, unstripped_output = lib)
+    runtime_shared_libs = create_shared_libraries(ctx, solibs)
+
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            linkable_node = create_linkable_node(
+                ctx = ctx,
+                exported_deps = ctx.attrs.deps,
+                link_infos = {_to_lib_output_style(s): v for s, v in link_infos.items()},
+                shared_libs = shared_libs,
+                default_soname = None,
+            ),
+        ),
+        deps = ctx.attrs.deps,
+    )
+
+    inherited_pp_info = cxx_inherited_preprocessor_infos(ctx.attrs.deps)
+    own_pp_info = CPreprocessor(
+        args = CPreprocessorArgs(args = flatten([["-isystem", d] for d in ctx.attrs.cxx_header_dirs])),
+    )
+
+    return [
+        DefaultInfo(),
+        haskell_lib_provider,
+        cxx_merge_cpreprocessors(ctx.actions, [own_pp_info], inherited_pp_info),
+        merge_shared_libraries(
+            ctx.actions,
+            runtime_shared_libs,
+            shared_library_infos,
+        ),
+        merge_link_group_lib_info(deps = ctx.attrs.deps),
+        haskell_link_infos,
+        merged_link_info,
+        HaskellProfLinkInfo(
+            prof_infos = prof_merged_link_info,
+        ),
+        linkable_graph,
+    ]
+
+def _srcs_to_objfiles(ctx: AnalysisContext, odir: Artifact, osuf: str) -> list[Artifact]:
+    objfiles = []
+    for modl, src in srcs_to_pairs(ctx.attrs.srcs):
+        # Don't link boot sources, as they're only meant to be used for compiling.
+        if is_haskell_src(src):
+            objfiles.append(odir.project(module_name_to_file(modl, osuf)))
+    return objfiles
+
+# The packager is the rest of the arguments: it may be a command with
+# arguments of its own.
+_REGISTER_PACKAGE = """\
+set -eu
+DB=$1
+PKGCONF=$2
+ALWAYS_USE_CACHE=$3
+FORCE=$4
+shift 4
+"$@" init "$DB"
+"$@" register --package-conf "$DB" --no-expand-pkgroot $ALWAYS_USE_CACHE $FORCE "$PKGCONF"
+"""
+
+# Shared libraries that GHC can load: a directory of them, and their names,
+# for `-lNAME` or a package's extra-libraries, in dependency order, each
+# after the ones it depends on.
+_NamedNativeLibs = record(
+    dir = Artifact,
+    names = list[str],
+)
+
+# Create a package
+#
+# The way we use packages is a bit strange. We're not using them
+# at link time at all: all the linking info is in the
+# HaskellLibraryInfo and we construct linker command lines
+# manually. Packages are used for:
+#
+#  - finding .hi files at compile time
+#
+#  - symbol namespacing (so that modules with the same name in
+#    different libraries don't clash).
+#
+#  - controlling module visibility: only dependencies that are
+#    directly declared as dependencies may be used
+#
+#  - Template Haskell: the compiler needs to load libraries itself
+#    at compile time, so it uses the package specs to find out
+#    which libraries and where.
+def _make_package(
+    ctx: AnalysisContext,
+    link_style: LinkStyle,
+    pkgname: str,
+    libname: str,
+    hlis: list[HaskellLibraryInfo],
+    hi: list[Artifact],
+    lib: list[Artifact],
+    # Libraries whose directories go in dynamic-library-dirs, where a
+    # dynamically linked GHC looks for the package's library. Like `lib`, it
+    # is ignored for an early or library-less package.
+    dynamic_lib: list[Artifact],
+    enable_profiling: bool,
+    # The directory, relative to the target's outputs, that the interfaces are
+    # written to (see import_dir on CompileResultInfo). 
+    import_dir: str,
+    # Every library this one depends on, when it re-exports modules: the
+    # package the module is defined in may be one that the dependency re-exports it
+    # from, and ghc-pkg has to find it.
+    all_hlis: list[HaskellLibraryInfo] = [],
+    # See HaskellLibraryInfo.early_db
+    early: bool = False,
+    library_less: bool = False,
+    # The library's native libraries, which GHC's interpreter loads before
+    # the library (see Note [Native libraries in package dbs]). Like `lib`,
+    # they are ignored for an early or library-less package.
+    native_libs: [_NamedNativeLibs, None] = None,
+) -> Artifact:
+    variant = variant_name(link_style, enable_profiling)
+    db_variant = ("early-" if early else "nolib-" if library_less else "") + variant
+
+    # Don't expose boot sources, as they're only meant to be used for compiling.
+    modules = [x for x, src in srcs_to_pairs(ctx.attrs.srcs) if is_haskell_src(src)]
+
+    db = ctx.actions.declare_output("db-" + db_variant, has_content_based_path = False)
+
+    # The package names the directories of the interfaces and libraries it
+    # was given, wherever they are, by their paths relative to ${pkgroot}: the
+    # directory that the package db is in.
+    def pkgroot_path(artifact: Artifact, parent: int = 0) -> cmd_args:
+        return cmd_args(artifact, parent = parent, relative_to = (db, 1), format = '"${pkgroot}/{}"')
+
+    # An early db mustn't depend on the target's interfaces. It is registered
+    # before any of the target's modules compile, so that a dependent's module
+    # can compile as soon as the interfaces it imports exist. So it refers to 
+    # the directory that the interfaces are written to by its path (`import_dir`),
+    # rather than by an artifact.
+    #
+    # It also has to use only that one directory, because GHC's dependency
+    # analysis accepts interfaces that don't exist yet _only_ when a package has
+    # a single import directory.
+    #
+    # Every other db names its interfaces using the `hi` artifacts, which is
+    # a lot simpler. 
+    if early:
+        import_dirs = cmd_args('"${pkgroot}/' + import_dir + '"')
+    else:
+        import_dirs = cmd_args([pkgroot_path(d) for d in hi], delimiter = ", ")
+    native_dirs = [pkgroot_path(native_libs.dir)] if native_libs != None else []
+    library_dirs = cmd_args([pkgroot_path(l, parent = 1) for l in lib] + native_dirs, delimiter = ", ")
+
+    # Reexports are identified by the unit ID they come from, and are sorted
+    # by module name to match Cabal's behaviour.
+    reexports = []
+    for new_name, (origin, original_name) in sorted(ctx.attrs.reexported_modules.items()):
+        if origin == None:
+            origin_id = pkgname
+        else:
+            provider = origin.get(HaskellLibraryProvider)
+            origin_id = (provider.prof_lib if enable_profiling else provider.lib)[link_style].id
+        reexports.append("{} from {}:{}".format(new_name, origin_id, original_name))
+
+    conf = [
+        "name: " + (ctx.attrs.package_name or pkgname),
+        "version: " + (ctx.attrs.package_version or "1.0.0"),
+        "id: " + pkgname,
+        "key: " + pkgname,
+        "exposed: " + ("True" if ctx.attrs.exposed else "False"),
+        "exposed-modules: " + ", ".join([m for m in modules if m not in ctx.attrs.hidden_modules] + reexports),
+        "hidden-modules: " + ", ".join(ctx.attrs.hidden_modules),
+        cmd_args("import-dirs: ", import_dirs, delimiter = ""),
+        "depends: " + ", ".join([lib.id for lib in hlis]),
+    ]
+    if not early and not library_less:
+        conf += [
+            cmd_args("library-dirs: ", library_dirs, delimiter = ""),
+            "extra-libraries: " + ", ".join((native_libs.names if native_libs != None else []) + [libname]),
+            cmd_args("dynamic-library-dirs: ", cmd_args([pkgroot_path(l, parent = 1) for l in dynamic_lib] + native_dirs, delimiter = ", "), delimiter = ""),
+        ]
+    pkg_conf = ctx.actions.write("pkg-" + db_variant + ".conf", conf, has_content_based_path = False)
+
+    # While the list of hlis is unique, there may be multiple packages in the same db.
+    # Cutting down the GHC_PACKAGE_PATH significantly speeds up GHC.
+    db_deps = list(set([x.early_db if (early or library_less) and x.early_db != None else x.db for x in hlis + all_hlis]))
+
+    # So that ghc-pkg can find the DBs for the dependencies. We might
+    # be able to use flags for this instead, but this works.
+    ghc_package_path = cmd_args(
+        db_deps,
+        delimiter = ":",
+    )
+
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+
+    # --always-use-cache is a custom option to ghc-pkg that tells it to ignore the
+    # modification time on the package cache and use it anyway. This is useful in
+    # RE where file modification times can't be relied upon; without this option
+    # ghc-pkg will fall back to reading all the package configs which is much
+    # slower.
+    if haskell_toolchain.support_always_use_cache:
+        use_cache_arg = "--always-use-cache"
+    else:
+        use_cache_arg = ""
+
+    ctx.actions.run(
+        cmd_args(
+            [
+                "sh",
+                "-c",
+                _REGISTER_PACKAGE,
+                "",
+                db.as_output(),
+                pkg_conf,
+                use_cache_arg,
+                "--force" if early else "",
+                haskell_toolchain.packager,
+            ],
+            # needs hi, because ghc-pkg checks that the .hi files exist
+            hidden = [] if early else hi if library_less else hi + lib + dynamic_lib + ([native_libs.dir] if native_libs != None else []),
+        ),
+        category = "haskell_package",
+        identifier = db_variant,
+        env = {"GHC_PACKAGE_PATH": ghc_package_path} if db_deps else {},
+    )
+
+    return db
+
+# The library built in one variant: its compile, and what was linked from it.
+Library = record(
+    link_style = LinkStyle,
+    compiled = CompileResultInfo,
+    libs = list[Artifact],
+    solibs = dict[str, LinkedObject],
+    link_infos = LinkInfos,
+)
+
+HaskellLibBuildOutput = record(
+    library = Library,
+    hlib = HaskellLibraryInfo,
+)
+
+def _get_haskell_shared_library_name_linker_flags(linker_type: LinkerType, soname: str) -> list[str]:
+    if linker_type == LinkerType("gnu"):
+        return ["-Wl,-soname,{}".format(soname)]
+    elif linker_type == LinkerType("darwin"):
+        # Passing `-install_name @rpath/...` or
+        # `-Xlinker -install_name -Xlinker @rpath/...` instead causes
+        # ghc-9.6.3: panic! (the 'impossible' happened)
+        return ["-Wl,-install_name,@rpath/{}".format(soname)]
+    else:
+        fail("Unknown linker type '{}'.".format(linker_type))
+
+# The shared libraries of a target's native dependencies, and of their
+# dependencies in turn. A library's package db names them (see Note [Native
+# libraries in package dbs]).
+#
+# It leaves out the shared libraries of the target's Haskell dependencies,
+# whose own package dbs name theirs.
+def _native_libs(ctx: AnalysisContext) -> SharedLibraryInfo:
+    return merge_shared_libraries(ctx.actions, deps = [d[SharedLibraryInfo] for d in ctx.attrs.deps if SharedLibraryInfo in d and HaskellLinkInfo not in d])
+
+# _link_library() and _register_library() are invoked once for each variant
+# that the library builds (see Note [Link styles and profiling]).
+def _link_library(
+    ctx,
+    libname: str,
+    nlis: list[MergedLinkInfo],  # native link infos from all deps
+    link_style: LinkStyle,
+    enable_profiling: bool,
+    # The variant's compile. For "shared", this may be the dynamic view of
+    # a static compile (see _dynamic_view).
+    compiled: CompileResultInfo,
+) -> Library:
+    linker_info = ctx.attrs._cxx_toolchain[CxxToolchainInfo].linker_info
+
+    # Link the objects into a library
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+
+    osuf, _hisuf = output_extensions(link_style, enable_profiling)
+
+    solibs = {}
+    variant = variant_name(link_style, enable_profiling)
+
+    if link_style == LinkStyle("shared"):
+        libfile = "lib" + libname + "." + LINKERS[linker_info.type].default_shared_library_extension
+    else:
+        libfile = "lib" + libname + ".a"
+
+    lib_short_path = paths.join("lib-{}".format(variant), libfile)
+
+    objfiles = _srcs_to_objfiles(ctx, compiled.objects, osuf)
+
+    if link_style == LinkStyle("shared"):
+        lib = ctx.actions.declare_output(lib_short_path, has_content_based_path = False)
+        link = cmd_args(
+            [haskell_toolchain.linker]
+            + [haskell_toolchain.linker_flags]
+            + [ctx.attrs.linker_flags]
+            + ["-o", lib.as_output()]
+            + [
+                "-package-env=-",
+                get_shared_library_flags(linker_info.type),
+                "-dynamic",
+                cmd_args(
+                    _get_haskell_shared_library_name_linker_flags(linker_info.type, _soname(ctx, libfile)),
+                    prepend = "-optl",
+                ),
+            ]
+            # The objects of its internal_deps are part of it, as in its archive.
+            + [objfiles, _internal_objects(ctx, LinkStyle("shared"))],
+            hidden = compiled.stubs,
+        )
+
+        infos = get_link_args_for_strategy(
+            ctx.actions,
+            ctx.label,
+            linker_info,
+            nlis,
+            to_link_strategy(LinkStyle("shared")),
+            prefer_stripped = False,
+            transformation_spec_context = None,
+        )
+        # Wrap linker args that we pass to GHC as `-optl=X`, not `-optl X`:
+        # if X is an argsfile (@file) we want it passed literally to
+        # the C compiler rather than GHC expanding it which wouldn't wrap
+        # each argument in `-optl`. We do the same thing for `-optP` and
+        # `-optc` in compile_args().
+        link.add(cmd_args(unpack_link_args(infos), format = "-optl={}"))
+        ctx.actions.run(
+            link,
+            category = "haskell_link",
+            identifier = variant,
+            env = haskell_toolchain.link_env,
+        )
+
+        solibs[_soname(ctx, libfile)] = LinkedObject(output = lib, unstripped_output = lib)
+        link_infos = LinkInfos(default = LinkInfo(
+            pre_flags = ctx.attrs.exported_linker_flags,
+            linkables = [SharedLibLinkable(lib = lib)],
+        ))
+        libs = [lib]
+
+    else:  # static flavours
+        # TODO: avoid making an archive for a single object, like cxx does
+        # (but would that work with Template Haskell?)
+        # TODO: Opt haskell actions into content based paths.
+        archive = make_archive(ctx, lib_short_path, objfiles + _internal_objects(ctx, link_style, enable_profiling), force_disable_content_based_path = True)
+        lib = archive.artifact
+        libs = [lib] + (archive.external_objects if archive.archive_contents_type == ArchiveContentsType("thin") else [])
+        link_infos = LinkInfos(
+            default = LinkInfo(
+                pre_flags = ctx.attrs.exported_linker_flags,
+                linkables = [
+                    ArchiveLinkable(
+                        archive = archive,
+                        linker_type = linker_info.type,
+                        link_whole = ctx.attrs.link_whole,
+                    ),
+                ],
+            ),
+        )
+
+    return Library(
+        link_style = link_style,
+        compiled = compiled,
+        libs = libs,
+        solibs = solibs,
+        link_infos = link_infos,
+    )
+
+def _register_library(
+    ctx,
+    libname: str,
+    pkgname: str,
+    hlis: list[HaskellLinkInfo],  # haskell link infos from all deps
+    enable_profiling: bool,
+    # The library's native libraries (see _native_libs), named for its
+    # package db (see Note [Native libraries in package dbs]).
+    native_libs: [_NamedNativeLibs, None],
+    library: Library,
+    # The splice variant of `library`: the variant whose code GHC loads when
+    # a splice in a module compiled against `library` runs this library's
+    # code. It may be `library` itself (see Note [Link styles and
+    # profiling]).
+    splice_variant: Library,
+) -> HaskellLibBuildOutput:
+    link_style = library.link_style
+    compiled = library.compiled
+    linfos = [x.prof_info if enable_profiling else x.info for x in hlis]
+
+    # only gather direct dependencies
+    uniq_infos = [x[link_style].value for x in linfos]
+    all_hlis = [lib for x in linfos for lib in x[link_style].traverse()] if ctx.attrs.reexported_modules else []
+    below = ctx.actions.tset(HaskellLibraryInfoTSet, children = [x[link_style] for x in linfos])
+
+    # The package names the variant's own interfaces, stubs and libraries,
+    # and those of its splice variant. Its library-dirs names only the
+    # variant's own library, because listing both can confuse a profiled
+    # external interpreter. GHC's internal interpreter finds a shared splice
+    # variant's library through dynamic-library-dirs instead. When the
+    # variant is its own splice variant, or both come from one -dynamic-too
+    # compile, they share some files, so each file is named only once.
+    def unique(xs: list) -> list:
+        return list(set(xs))
+
+    import_artifacts = unique([compiled.hi, splice_variant.compiled.hi])
+    stub_dirs = unique([compiled.stubs, splice_variant.compiled.stubs])
+    all_libs = unique(library.libs + splice_variant.libs)
+
+    # The library's native libraries are among its `libs`, so that whatever
+    # may load the library has them too.
+    if native_libs != None:
+        all_libs.append(native_libs.dir)
+
+    db = _make_package(
+        ctx,
+        link_style,
+        pkgname,
+        libname,
+        uniq_infos,
+        import_artifacts,
+        [library.libs[0]],
+        [splice_variant.libs[0]],
+        enable_profiling = enable_profiling,
+        import_dir = compiled.import_dir,
+        all_hlis = all_hlis,
+        native_libs = native_libs,
+    )
+
+    hlib = HaskellLibraryInfo(
+        name = pkgname,
+        db = db,
+        id = pkgname,
+        import_dirs = import_artifacts,
+        stub_dirs = stub_dirs,
+        libs = all_libs,
+        data_dirs = own_data_dirs(ctx),
+        version = ctx.attrs.package_version or "1.0.0",
+        is_prebuilt = False,
+        profiling_enabled = enable_profiling,
+        **_per_module_fields(ctx, link_style, pkgname, libname, uniq_infos, compiled, enable_profiling = enable_profiling, all_hlis = all_hlis, hi = import_artifacts, below = below)
+    )
+
+    return HaskellLibBuildOutput(library = library, hlib = hlib)
+
+# The shared libraries in `info`, each after the ones that it depends on.
+def _dependencies_first(info: SharedLibraryInfo) -> list:
+    if not info.set:
+        return []
+    seen = set()
+    libs = []
+    # A topological traversal visits each node before its children.
+    for node in reversed(list(info.set.traverse(ordering = "topological"))):
+        for lib in node.libraries:
+            soname = lib.soname.ensure_str()
+            if soname not in seen:
+                seen.add(soname)
+                libs.append(lib)
+    return libs
+
+# The shared libraries in `info`, named for GHC, or None if there are none.
+# GHC only finds a library as libNAME.so (on Linux), so each library is
+# linked into the directory under that form of its soname: libver.so.1, say,
+# as liblibver.so.1.so, named libver.so.1. The dynamic loader still knows a
+# loaded library by its soname, so it finds it loaded when another library
+# needs it.
+def _named_native_libs(ctx: AnalysisContext, info: SharedLibraryInfo) -> [_NamedNativeLibs, None]:
+    libs = _dependencies_first(info)
+    if not libs:
+        return None
+    ext = LINKERS[ctx.attrs._cxx_toolchain[CxxToolchainInfo].linker_info.type].default_shared_library_extension
+    names = []
+    links = {}
+    for lib in libs:
+        name = lib.soname.ensure_str().replace("/", "_")
+        names.append(name)
+        links["lib" + name + "." + ext] = lib.lib.output
+    return _NamedNativeLibs(dir = ctx.actions.symlinked_dir("native-libs", links, has_content_based_path = False), names = names)
+
+# The link style of the splice variant of a variant with this link style,
+# whether profiled or not (see Note [Link styles and profiling]). Where this
+# returns the style unchanged, a non-profiled variant is its own splice
+# variant.
+def _splice_variant_style(ctx: AnalysisContext, link_style: LinkStyle) -> LinkStyle:
+    dynamic_ghc = ctx.attrs._haskell_toolchain[HaskellToolchainInfo].dynamic_ghc
+    return LinkStyle("shared") if dynamic_ghc else link_style
+
+# Given a compilation built with -dynamic-too, produce a `CompileResultInfo`
+# that sees the "extra" dynamic interface files as the primary ones. The
+# objects need no change, because the shared variant's link takes the .dyn_o
+# files from the same directory.
+def _dynamic_view(compiled: CompileResultInfo) -> CompileResultInfo:
+    modules = None
+    if compiled.modules != None:
+        modules = {m: HaskellModuleFiles(hi = f.dyn_hi, abi = f.abi) for m, f in compiled.modules.items()}
+    return CompileResultInfo(
+        objects = compiled.objects,
+        hi = compiled.hi,
+        stubs = compiled.stubs,
+        producing_indices = compiled.producing_indices,
+        import_dir = compiled.import_dir,
+        modules = modules,
+        closures = compiled.closures,
+        dynamic_objects = compiled.dynamic_objects,
+        advice = compiled.advice,
+        diagnostics = compiled.diagnostics,
+    )
+
+# The HaskellLibraryInfo fields that per-module compiles of a library's
+# dependents use (see library_info.bzl). They are filled in for every
+# library, whether or not it is itself compiled per-module, because any of
+# its dependents might be:
+#
+# - For a library built with --make: its library-less db, and `below`.
+# - For a library compiled per-module: its early db, the files of each of
+#   its modules, and their closure sets.
+def _per_module_fields(
+        ctx: AnalysisContext,
+        link_style: LinkStyle,
+        pkgname: str,
+        libname: str,
+        hlis: list[HaskellLibraryInfo],
+        compiled: CompileResultInfo,
+        enable_profiling: bool = False,
+        all_hlis: list[HaskellLibraryInfo] = [],
+        hi: list[Artifact] = [],
+        below: [TransitiveSet, None] = None) -> dict:
+    if compiled.modules == None:
+        # Built with --make: the library-less db its per-module dependents
+        # compile against, and its dependencies.
+        return {
+            "below": below,
+            "early_db": _make_package(ctx, link_style, pkgname, libname, hlis, hi, [], [], enable_profiling = enable_profiling, import_dir = compiled.import_dir, all_hlis = all_hlis, library_less = True),
+        }
+    return {
+        "early_db": _make_package(ctx, link_style, pkgname, libname, hlis, [], [], [], enable_profiling = enable_profiling, import_dir = compiled.import_dir, all_hlis = all_hlis, early = True),
+        "modules": compiled.modules,
+        "closures": compiled.closures,
+    }
+
+def _soname(ctx: AnalysisContext, libfile: str) -> str:
+    # The soname of the library's shared library, whose file is `libfile`.
+    return ctx.attrs.soname or libfile
+
+def _internal_objects(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool = False) -> list[Artifact]:
+    # The objects of the library's internal_deps (its prof_internal_deps, if
+    # it has them, when profiled), which its archive has in it as well as its
+    # own.
+    objects = []
+    deps = ctx.attrs.prof_internal_deps if enable_profiling and ctx.attrs.prof_internal_deps else ctx.attrs.internal_deps
+    for dep in deps:
+        infos = get_own_link_infos(dep[MergedLinkInfo], to_link_strategy(link_style))
+        if infos == None:
+            fail("{}: internal dependency {} has nothing to link for {} linking".format(ctx.label, dep.label, link_style.value))
+        for linkable in infos.default.linkables:
+            if not hasattr(linkable, "objects"):
+                fail("{}: internal dependency {} isn't objects, which the library's archive can include (use_archive = False, for a cxx_library)".format(ctx.label, dep.label))
+            objects.extend(linkable.objects)
+    return objects
+
+def _exported_link_infos(ctx: AnalysisContext, enable_profiling: bool) -> list[MergedLinkInfo]:
+    # The link infos of the library's dependencies, but not of its
+    # internal_deps.
+    return filter(None, [
+        (d.get(HaskellProfLinkInfo).prof_infos if enable_profiling and d.get(HaskellProfLinkInfo) else d.get(MergedLinkInfo))
+        for d in ctx.attrs.deps
+    ])
+
+# A file of all the messages, such as warnings, that GHC gave when compiling
+# the target's modules per-module. They are kept with each module's outputs,
+# so a module that buck2 didn't compile again, or found in a cache, still has
+# its messages here.
+#
+# A target compiled with --make has no such file. Its compile keeps its
+# previous outputs and compiles only the modules that changed, so the file
+# would have only those modules' messages, in no fixed order, and a cache
+# would keep whichever ones it happened to have.
+def _diagnostics(ctx: AnalysisContext, compiled: CompileResultInfo) -> Artifact:
+    out = ctx.actions.declare_output("diagnostics.txt", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args("sh", "-c", 'out="$1"; shift; cat "$@" > "$out"', "sh", out.as_output(), compiled.diagnostics),
+        category = "haskell_diagnostics",
+    )
+    return out
+
+def haskell_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    preferred_linkage = _attr_preferred_linkage(ctx)
+    if ctx.attrs.enable_profiling and preferred_linkage == Linkage("any"):
+        preferred_linkage = Linkage("static")
+
+    # Get haskell and native link infos from all deps (but not internal_deps,
+    # whose objects are the library's own)
+    hlis = attr_deps_haskell_link_infos_sans_template_deps(ctx)
+    nlis = attr_deps_merged_link_infos(ctx, ctx.attrs.deps)
+    shared_library_infos = attr_deps_shared_library_infos(ctx)
+
+    solibs = {}
+    link_infos = {}
+    prof_link_infos = {}
+    hlib_infos = {}
+    hlib_compiled = {}
+    hlink_infos = {}
+    prof_hlib_infos = {}
+    prof_hlink_infos = {}
+    indexing_tsets = {}
+    sub_targets = {}
+
+    libname = haskell_library_name(ctx.label)
+    pkgname = ctx.attrs.unit_id or haskell_library_unit_id(ctx.label)
+
+    native_libs = _named_native_libs(ctx, _native_libs(ctx))
+
+    link_styles = [legacy_output_style_to_link_style(o) for o in get_output_styles_for_linkage(preferred_linkage)]
+
+    # The static link style that a statically-linked consumer actually
+    # uses: "static", unless the toolchain's code is always
+    # position-independent (macOS), when it's "static_pic".
+    pic_behavior = ctx.attrs._cxx_toolchain[CxxToolchainInfo].pic_behavior
+    consumed_static_link_style = legacy_output_style_to_link_style(
+        process_output_style_for_pic_behavior(LibOutputStyle("archive"), pic_behavior),
+    )
+
+    # Records one variant's outputs in the dicts above. A variant that the
+    # library builds only to be a splice variant has a package, for its
+    # dependents' splice variants to compile against, but nothing links it,
+    # so it has no link infos, shared libraries or sub-target.
+    def record(link_style: LinkStyle, enable_profiling: bool, hlib_build_out: HaskellLibBuildOutput):
+        hlib = hlib_build_out.hlib
+        splice_only = not enable_profiling and link_style not in link_styles
+        if not splice_only:
+            solibs.update(hlib_build_out.library.solibs)
+        compiled = hlib_build_out.library.compiled
+        libs = hlib_build_out.library.libs
+
+        if enable_profiling:
+            prof_hlib_infos[link_style] = hlib
+            prof_hlink_infos[link_style] = ctx.actions.tset(
+                HaskellLibraryInfoTSet,
+                value = hlib,
+                children = [li.prof_info[link_style] for li in hlis],
+            )
+            prof_link_infos[link_style] = hlib_build_out.library.link_infos
+        else:
+            hlib_infos[link_style] = hlib
+            hlib_compiled[link_style] = compiled
+            hlink_infos[link_style] = ctx.actions.tset(
+                HaskellLibraryInfoTSet,
+                value = hlib,
+                children = [li.info[link_style] for li in hlis],
+            )
+            if not splice_only:
+                link_infos[link_style] = hlib_build_out.library.link_infos
+
+        # Build the indices and create subtargets only once, with profiling
+        # enabled or disabled based on what was set in the library's
+        # target.
+        if ctx.attrs.enable_profiling == enable_profiling and not splice_only:
+            if compiled.producing_indices:
+                tset = derive_indexing_tset(
+                    ctx.actions,
+                    link_style,
+                    compiled.hi,
+                    attr_deps(ctx),
+                )
+                indexing_tsets[link_style] = tset
+
+            sub_targets[link_style.value.replace("_", "-")] = [
+                DefaultInfo(
+                    default_outputs = libs,
+                )
+            ]
+
+    # Profiled code can only be linked statically, so whatever the library's
+    # preferred_linkage, a profiled link wants a profiled archive of it: a
+    # library that is otherwise only shared (preferred_linkage "shared") is a
+    # profiled archive to a profiled executable. These are only built when a
+    # profiled link asks for them. See Note [Link styles and profiling].
+    prof_link_styles = [legacy_output_style_to_link_style(o) for o in get_output_styles_for_linkage(Linkage("static"))]
+
+    unprof_link_styles = list(link_styles)
+    for style in link_styles + prof_link_styles:
+        splice_style = _splice_variant_style(ctx, style)
+        if splice_style not in unprof_link_styles:
+            unprof_link_styles.append(splice_style)
+
+    # When the shared variant and the static style that executables use are
+    # both built, they come from one -dynamic-too compile instead of two
+    # independent ones (see _dynamic_view).
+    build_shared_too = (
+        consumed_static_link_style in unprof_link_styles and
+        LinkStyle("shared") in unprof_link_styles
+    )
+
+    compiles = {}
+
+    def compile_variant(link_style: LinkStyle, enable_profiling: bool, dynamic_from: [CompileResultInfo, None]) -> CompileResultInfo:
+        key = (link_style, enable_profiling)
+        if key not in compiles:
+            compiles[key] = (compile_per_module if compiles_per_module(ctx) else compile)(
+                ctx,
+                link_style,
+                enable_profiling = enable_profiling,
+                pkgname = pkgname,
+                dynamic_too = build_shared_too and link_style == consumed_static_link_style and not enable_profiling,
+                dynamic_from = dynamic_from,
+            )
+        return compiles[key]
+
+    # Each variant is built after its splice variant, so the shared variant
+    # first.
+    variants = (
+        [(False, s) for s in unprof_link_styles if s == LinkStyle("shared")] +
+        [(False, s) for s in unprof_link_styles if s != LinkStyle("shared")] +
+        [(True, s) for s in prof_link_styles]
+    )
+    # The libraries of the non-profiled variants, by style.
+    libraries = {}
+    for enable_profiling, link_style in variants:
+        splice_style = _splice_variant_style(ctx, link_style)
+        if build_shared_too and link_style == LinkStyle("shared"):
+            compiled = _dynamic_view(compile_variant(consumed_static_link_style, False, None))
+        else:
+            # A profiled compile can't make the dynamic objects that its
+            # splices load, so it takes them from its splice variant's compile
+            # (see `dynamic_from` on compile).
+            compiled = compile_variant(link_style, enable_profiling, libraries[splice_style].compiled if enable_profiling else None)
+
+        library = _link_library(ctx, libname, nlis, link_style, enable_profiling, compiled)
+        if not enable_profiling:
+            libraries[link_style] = library
+        record(link_style, enable_profiling, _register_library(
+            ctx,
+            libname,
+            pkgname,
+            hlis = hlis,
+            enable_profiling = enable_profiling,
+            native_libs = native_libs,
+            library = library,
+            splice_variant = libraries[splice_style],
+        ))
+
+    link_style = cxx_toolchain_link_style(ctx)
+    output_style = get_lib_output_style(
+        to_link_strategy(link_style),
+        preferred_linkage,
+        pic_behavior,
+    )
+    shared_libs = create_shared_libraries(ctx, solibs)
+
+    # TODO(cjhopman): this haskell implementation does not consistently handle LibOutputStyle
+    # and LinkStrategy as expected and it's hard to tell what the intent of the existing code is
+    # and so we currently just preserve its existing use of the legacy LinkStyle type and just
+    # naively convert it at the boundaries of other code. This needs to be cleaned up by someone
+    # who understands the intent of the code here.
+    actual_link_style = legacy_output_style_to_link_style(output_style)
+
+    # The link info for this library as a dependency of a non-Haskell target
+    # (a cxx_binary(), say). When the library is profiled and that target
+    # links it shared, there is no profiled shared library (GHC doesn't
+    # support profiling with dynamic linking), so it gets the non-profiled
+    # one. A profiled Haskell link uses prof_merged_link_info, which never
+    # does.
+    default_link_infos = link_infos
+    if ctx.attrs.enable_profiling:
+        default_link_infos = dict(prof_link_infos)
+        if LinkStyle("shared") in link_infos:
+            default_link_infos[LinkStyle("shared")] = link_infos[LinkStyle("shared")]
+    merged_link_info = create_merged_link_info(
+        ctx,
+        pic_behavior = pic_behavior,
+        link_infos = {_to_lib_output_style(s): v for s, v in default_link_infos.items()},
+        preferred_linkage = preferred_linkage,
+        # Haskell code may refer to the code of any library below it (through
+        # inlining), so the libraries it depends on are linked with it, but
+        # not those that are part of it (its internal_deps, in its archive or
+        # linked into its shared library).
+        exported_deps = _exported_link_infos(ctx, enable_profiling = ctx.attrs.enable_profiling),
+    )
+
+    prof_merged_link_info = create_merged_link_info(
+        ctx,
+        pic_behavior = pic_behavior,
+        link_infos = {_to_lib_output_style(s): v for s, v in prof_link_infos.items()},
+        # A profiled archive, for any link strategy (see prof_link_styles).
+        preferred_linkage = Linkage("static"),
+        exported_deps = _exported_link_infos(ctx, enable_profiling = True),
+    )
+
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            linkable_node = create_linkable_node(
+                ctx = ctx,
+                preferred_linkage = preferred_linkage,
+                exported_deps = ctx.attrs.deps,
+                link_infos = {_to_lib_output_style(s): v for s, v in link_infos.items()},
+                shared_libs = shared_libs,
+                # TODO(cjhopman): this should be set to non-None
+                default_soname = None,
+            ),
+        ),
+        deps = ctx.attrs.deps,
+    )
+
+    default_output = libraries[actual_link_style].libs
+
+    inherited_pp_info = cxx_inherited_preprocessor_infos(attr_deps(ctx))
+
+    # We would like to expose the generated _stub.h headers to C++
+    # compilations, but it's hard to do that without overbuilding. Which
+    # link_style should we pick below? If we pick a different link_style from
+    # the one being used by the root rule, we'll end up building all the
+    # Haskell libraries multiple times.
+    #
+    #    pp = [CPreprocessor(
+    #        args =
+    #            flatten([["-isystem", dir] for dir in hlib_infos[actual_link_style].stub_dirs]),
+    #    )]
+    pp = []
+
+    # The interfaces of the default output's compile, and its messages when
+    # it is compiled per-module.
+    sub_targets["interfaces"] = [DefaultInfo(default_output = hlib_compiled[actual_link_style].hi)]
+    if hlib_compiled[actual_link_style].modules != None:
+        sub_targets["diagnostics.txt"] = [DefaultInfo(default_output = _diagnostics(ctx, hlib_compiled[actual_link_style]))]
+
+    providers = [
+        DefaultInfo(
+            default_outputs = default_output,
+            sub_targets = sub_targets,
+        ),
+        HaskellLibraryProvider(
+            lib = hlib_infos,
+            prof_lib = prof_hlib_infos,
+        ),
+        HaskellLinkInfo(
+            info = hlink_infos,
+            prof_info = prof_hlink_infos,
+        ),
+        merged_link_info,
+        HaskellProfLinkInfo(
+            prof_infos = prof_merged_link_info,
+        ),
+        linkable_graph,
+        cxx_merge_cpreprocessors(ctx.actions, pp, inherited_pp_info),
+        merge_shared_libraries(
+            ctx.actions,
+            shared_libs,
+            shared_library_infos,
+        ),
+        haskell_haddock_lib(ctx, pkgname, actual_link_style, hlib_compiled[actual_link_style]),
+    ]
+
+    if indexing_tsets:
+        providers.append(HaskellIndexInfo(info = indexing_tsets))
+
+    # TODO(cjhopman): This code is for templ_vars is duplicated from cxx_library
+    templ_vars = {}
+
+    # Add in ldflag macros.
+    for link_style in (LinkStyle("static"), LinkStyle("static_pic")):
+        name = "ldflags-" + link_style.value.replace("_", "-")
+        args = cmd_args()
+        linker_info = ctx.attrs._cxx_toolchain[CxxToolchainInfo].linker_info
+        args.add(linker_info.linker_flags)
+        args.add(
+            unpack_link_args(
+                get_link_args_for_strategy(
+                    ctx.actions,
+                    ctx.label,
+                    linker_info,
+                    [merged_link_info],
+                    to_link_strategy(link_style),
+                    prefer_stripped = False,
+                    transformation_spec_context = None,
+                ),
+            )
+        )
+        templ_vars[name] = args
+
+    # TODO(T110378127): To implement `$(ldflags-shared ...)` properly, we'd need
+    # to setup a symink tree rule for all transitive shared libs.  Since this
+    # currently would be pretty costly (O(N^2)?), and since it's not that
+    # commonly used anyway, just use `static-pic` instead.  Longer-term, once
+    # v1 is gone, macros that use `$(ldflags-shared ...)` (e.g. Haskell's
+    # hsc2hs) can move to a v2 rules-based API to avoid needing this macro.
+    templ_vars["ldflags-shared"] = templ_vars["ldflags-static-pic"]
+
+    providers.append(TemplatePlaceholderInfo(keyed_variables = templ_vars))
+
+    providers.append(merge_link_group_lib_info(deps = attr_deps(ctx)))
+    providers += advice_validations(hlib_compiled[actual_link_style])
+
+    return providers
+
+# TODO(cjhopman): should this be LibOutputType or LinkStrategy?
+def derive_indexing_tset(actions: AnalysisActions, link_style: LinkStyle, value: Artifact | None, children: list[Dependency]) -> HaskellIndexingTSet:
+    index_children = []
+    for dep in children:
+        li = dep.get(HaskellIndexInfo)
+        if li:
+            if link_style in li.info:
+                index_children.append(li.info[link_style])
+
+    return actions.tset(
+        HaskellIndexingTSet,
+        value = value,
+        children = index_children,
+    )
+
+def _run_tools(ctx: AnalysisContext) -> list[Artifact]:
+    return [t[DefaultInfo].default_outputs[0] for t in ctx.attrs.run_tool_depends]
+
+# Write a wrapper script that sets up the binary's environment and then runs
+# it, as `cabal run` does. The script sets the environment variables for the
+# rule's data_dirs, and puts the directories of its run_tool_depends at the
+# front of PATH.
+#
+# The script refers to the data directories, the tools and the binary by
+# paths relative to its own location, and turns them into absolute paths when
+# it runs. That way they don't depend on where buck-out is, and they keep
+# working if the binary is started from another directory (a test run by
+# run_in_cwd, say) or changes directory itself.
+def _run_wrapper(ctx: AnalysisContext, binary: Artifact) -> Artifact:
+    script = ctx.actions.declare_output(binary.basename + "-run", has_content_based_path = False)
+    tools = _run_tools(ctx)
+    ctx.actions.write(
+        script,
+        cmd_args(
+            "#!/bin/sh",
+            'here=$(cd "$(dirname "$0")" && pwd)',
+            [
+                cmd_args("export ", name, '="$here/', dir, '"', delimiter = "")
+                for name, dir in data_dirs_env(ctx).items()
+            ],
+            cmd_args(
+                'export PATH="',
+                [cmd_args("$here/", cmd_args(t, parent = 1), ":", delimiter = "") for t in tools],
+                '$PATH"',
+                delimiter = "",
+            ) if tools else [],
+            cmd_args('exec "$here/', binary, '" "$@"', delimiter = ""),
+            relative_to = (script, 1),
+        ),
+        is_executable = True,
+    )
+    return script
+
+def haskell_binary_impl(ctx: AnalysisContext) -> list[Provider]:
+    enable_profiling = ctx.attrs.enable_profiling
+
+    # Decide what kind of linking we're doing
+
+    link_style = attr_link_style(ctx)
+
+    # Link Groups
+    link_group_info = get_link_group_info(
+        ctx,
+        filter_and_map_idx(LinkableGraph, attr_deps(ctx)),
+        to_link_strategy(link_style),
+    )
+
+    # Profiling doesn't support shared libraries
+    if enable_profiling and link_style == LinkStyle("shared"):
+        link_style = LinkStyle("static")
+
+    link_style = LinkStyle(
+        process_link_strategy_for_pic_behavior(to_link_strategy(link_style), get_cxx_toolchain_info(ctx).pic_behavior).value
+    )
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+
+    # A profiled compile of a binary takes the dynamic objects that its
+    # splices load from its splice variant's compile, as a library's does
+    # (see `dynamic_from` on `compile`). A binary has no such compile
+    # otherwise, so we make one.
+    dynamic_from = None
+    if enable_profiling and compiles_per_module(ctx):
+        dynamic_from = compile_per_module(ctx, _splice_variant_style(ctx, link_style), enable_profiling = False)
+
+    compiled = (compile_per_module if compiles_per_module(ctx) else compile)(
+        ctx,
+        link_style,
+        enable_profiling = enable_profiling,
+        dynamic_from = dynamic_from,
+    )
+
+    output = ctx.actions.declare_output(ctx.attrs.exe_name or ctx.attrs.name, has_content_based_path = False)
+    link = cmd_args(
+        [haskell_toolchain.compiler] + ["-o", output.as_output()] + [haskell_toolchain.linker_flags] + [ctx.attrs.linker_flags],
+        hidden = compiled.stubs,
+    )
+
+    # Without this, GHC will link the non-profiled RTS which leads to
+    # duplicate symbols. We already do this at compile-time in
+    # compile.bzl:compile_args.
+    if enable_profiling:
+        link.add("-prof")
+
+    # Without this, GHC links its static RTS into a binary whose
+    # Haskell libraries are shared, and the linker discards whatever
+    # parts of it the binary itself doesn't use - but the shared
+    # libraries need them too, since they aren't linked against an RTS
+    # themselfs (which RTS - threaded or not - is only decided here).
+    # With it, GHC links the correct shared RTS instead.
+    if link_style == LinkStyle("shared"):
+        link.add("-dynamic")
+
+    link_args = cmd_args("-package-env=-")
+
+    # By default GHC links the rts, ghc-internal and base packages of its
+    # own package database. When a dependency provides the RTS (is_rts), the
+    # link passes -no-auto-link-packages, and the RTS's package database and
+    # -package-id, so that GHC links that RTS in place of its own. The
+    # RTS's files are inputs of the link, because GHC reads them. Other
+    # packages, including ghc-internal and base, are linked as the
+    # dependencies' link infos say, so the link doesn't need their package
+    # databases.
+    rts = {
+        lib.id: lib
+        for lib in dependency_libs(ctx, link_style, enable_profiling).traverse()
+        if lib.is_rts
+    }.values()
+    if len(rts) > 1:
+        fail("{}: more than one RTS among the dependencies: {}".format(ctx.label, ", ".join([lib.id for lib in rts])))
+    if rts:
+        link_args.add(
+            "-no-auto-link-packages",
+            cmd_args("-package-db", rts[0].db),
+            cmd_args("-package-id", rts[0].id, hidden = rts[0].libs),
+        )
+
+    osuf, _hisuf = output_extensions(link_style, enable_profiling)
+
+    objfiles = _srcs_to_objfiles(ctx, compiled.objects, osuf)
+    link_args.add(objfiles)
+
+    indexing_tsets = {}
+    if compiled.producing_indices:
+        tset = derive_indexing_tset(ctx.actions, link_style, compiled.hi, attr_deps(ctx))
+        indexing_tsets[link_style] = tset
+
+    slis = []
+    for lib in attr_deps(ctx):
+        li = lib.get(SharedLibraryInfo)
+        if li != None:
+            slis.append(li)
+    shlib_info = merge_shared_libraries(
+        ctx.actions,
+        deps = slis,
+    )
+
+    sos = []
+
+    link_strategy = to_link_strategy(link_style)
+    if link_group_info != None:
+        own_binary_link_flags = []
+        auto_link_groups = {}
+        link_group_libs = {}
+        link_deps = linkables(attr_deps(ctx))
+        reduced_linkable_graph = reduce_linkable_graph(link_group_info.graph)
+        linkable_graph_node_map = reduced_linkable_graph.nodes
+        link_group_preferred_linkage = get_link_group_preferred_linkage(link_group_info.groups.values())
+
+        # If we're using auto-link-groups, where we generate the link group links
+        # in the prelude, the link group map will give us the link group libs.
+        # Otherwise, pull them from the `LinkGroupLibInfo` provider from out deps.
+        auto_link_group_specs = get_auto_link_group_specs(ctx, link_group_info)
+        executable_deps = [d.linkable_graph.nodes.value.label for d in link_deps if d.linkable_graph != None]
+        public_nodes = get_public_link_group_nodes(
+            linkable_graph_node_map,
+            link_group_info.mappings,
+            executable_deps,
+            None,
+        )
+        if auto_link_group_specs != None:
+            linked_link_groups = create_link_groups(
+                ctx = ctx,
+                link_strategy = link_strategy,
+                linkable_graph = reduced_linkable_graph,
+                link_group_mappings = link_group_info.mappings,
+                link_group_preferred_linkage = link_group_preferred_linkage,
+                executable_deps = executable_deps,
+                link_group_specs = auto_link_group_specs,
+                public_nodes = public_nodes,
+            )
+            for name, linked_link_group in linked_link_groups.libs.items():
+                auto_link_groups[name] = linked_link_group.artifact
+                if linked_link_group.library != None:
+                    link_group_libs[name] = linked_link_group.library
+            own_binary_link_flags += linked_link_groups.symbol_ldflags
+
+        else:
+            # NOTE(agallagher): We don't use version scripts and linker scripts
+            # for non-auto-link-group flow, as it's note clear it's useful (e.g.
+            # it's mainly for supporting dlopen-enabled libs and extensions).
+            link_group_libs = gather_link_group_libs(
+                children = [d.link_group_lib_info for d in link_deps],
+            )
+
+        link_group_relevant_roots = find_relevant_roots(
+            linkable_graph_node_map = linkable_graph_node_map,
+            link_group_mappings = link_group_info.mappings,
+            roots = get_dedupped_roots_from_groups(link_group_info.groups.values()),
+        )
+
+        roots = set(
+            [d.linkable_graph.nodes.value.label for d in link_deps if d.linkable_graph != None] + link_group_relevant_roots,
+        )
+        is_executable_link = True
+        pic_behavior = PicBehavior("supported")
+        exec_linkables = collect_linkables(
+            reduced_linkable_graph,
+            is_executable_link,
+            link_strategy,
+            link_group_preferred_linkage,
+            pic_behavior,
+            roots,
+        )
+        build_context = BuildLinkGroupsContext(
+            public_nodes = public_nodes,
+            linkable_graph = reduced_linkable_graph,
+            link_groups = link_group_info.groups,
+            link_group_mappings = link_group_info.mappings,
+            link_group_preferred_linkage = link_group_preferred_linkage,
+            link_strategy = link_strategy,
+            pic_behavior = pic_behavior,
+            link_group_libs = {name: (lib.label, lib.shared_link_infos) for name, lib in link_group_libs.items()},
+            prefer_stripped = False,
+            prefer_optimized = False,
+        )
+        labels_to_links = get_filtered_labels_to_links_map(
+            link_group = None,
+            linkables = exec_linkables,
+            is_executable_link = True,
+            build_context = build_context,
+            force_static_follows_dependents = True,
+        )
+
+        # NOTE: Our Haskell DLL support impl currently links transitive haskell
+        # deps needed by DLLs which get linked into the main executable as link-
+        # whole.  To emulate this, we mark Haskell rules with a special label
+        # and traverse this to find all the nodes we need to link whole.
+        public_nodes = []
+        if ctx.attrs.link_group_public_deps_label != None:
+            public_nodes = get_transitive_deps_matching_labels(
+                linkable_graph_node_map = linkable_graph_node_map,
+                label = ctx.attrs.link_group_public_deps_label,
+                roots = link_group_relevant_roots,
+            )
+
+        link_infos = []
+        link_infos.append(
+            LinkInfo(
+                pre_flags = own_binary_link_flags,
+            ),
+        )
+        link_infos.extend(get_filtered_links(labels_to_links.map, set(public_nodes)))
+        infos = LinkArgs(infos = link_infos)
+
+        link_group_ctx = LinkGroupContext(
+            link_group_mappings = link_group_info.mappings,
+            link_group_libs = link_group_libs,
+            link_group_preferred_linkage = link_group_preferred_linkage,
+            labels_to_links_map = labels_to_links.map,
+            targets_consumed_by_link_groups = {},
+        )
+
+        for shared_lib in traverse_shared_library_info(shlib_info, transformation_provider = None):
+            label = shared_lib.label
+            if is_link_group_shlib(label, link_group_ctx):
+                sos.append(shared_lib)
+
+        # When there are no matches for a pattern based link group,
+        # `link_group_mappings` will not have an entry associated with the lib.
+        for _name, link_group_lib in link_group_libs.items():
+            sos.extend(link_group_lib.shared_libs.libraries)
+
+    else:
+        nlis = []
+        for lib in attr_deps(ctx):
+            if enable_profiling:
+                hli = lib.get(HaskellProfLinkInfo)
+                if hli != None:
+                    nlis.append(hli.prof_infos)
+                    continue
+            li = lib.get(MergedLinkInfo)
+            if li != None:
+                nlis.append(li)
+        sos.extend(traverse_shared_library_info(shlib_info, transformation_provider = None))
+        cxx_toolchain = ctx.attrs._cxx_toolchain[CxxToolchainInfo]
+        infos = get_link_args_for_strategy(
+            ctx.actions,
+            ctx.label,
+            cxx_toolchain.linker_info,
+            nlis,
+            to_link_strategy(link_style),
+            prefer_stripped = False,
+            transformation_spec_context = None,
+        )
+
+    # `link_ordering = "topological"`, not the default `"preorder"`: this
+    # migration hands raw static-archive paths straight to the linker
+    # (unlike a plain Cabal/GHC `-package`-based link, which computes
+    # correct archive order itself from the package DB). buck2's own
+    # LinkOrdering docs (prelude/linking/link_info.bzl) describe exactly
+    # what a single left-to-right `ld` pass needs here: "topological sort,
+    # such that nodes are listed after all nodes that have them as
+    # descendants" - i.e. a shared descendant (e.g. `primitive`, needed by
+    # both `fb-util` and `vector`, two independent direct deps of the same
+    # binary) is positioned after *every* consumer that needs it, not just
+    # whichever one's subtree the default preorder-with-first-occurrence-
+    # wins traversal happens to reach first (which, for two *independent*
+    # siblings that share a transitive dependency, has no way to know the
+    # *other* sibling needs it too - producing "undefined reference" even
+    # though the defining archive is genuinely present on the command
+    # line, just too early for the second consumer). This is a real,
+    # first-class ordering mode already implemented in buck2's own tset
+    # machinery - not a workaround - haskell_binary_impl here just never
+    # requested it, always taking the `unpack_link_args` default.
+    link_args.add(cmd_args(unpack_link_args(infos, link_ordering = LinkOrdering("topological")), format = "-optl={}"))
+
+    link.add(
+        at_argfile(
+            actions = ctx.actions,
+            name = "args.haskell_link_argsfile",
+            args = link_args,
+            allow_args = True,
+        )
+    )
+
+    symlink_dir = None
+    if link_style == LinkStyle("shared") or link_group_info != None:
+        # Built *before* the link action below (not after, as this used to
+        # be) so its real, build-time-valid path can be passed to the linker
+        # as `-rpath-link` right now - see the comment on that flag below for
+        # why this reordering is load-bearing, not cosmetic.
+        sos_dir = "__{}__shared_libs_symlink_tree".format(ctx.attrs.name)
+        symlink_dir = create_shlib_symlink_tree(
+            actions = ctx.actions,
+            out = sos_dir,
+            shared_libs = sos,
+        )
+        linker_type = get_cxx_toolchain_info(ctx).linker_info.type
+        rpath_ref = get_rpath_origin(linker_type)
+        rpath_ldflag = "-Wl,{}/{}".format(rpath_ref, sos_dir)
+        is_gnu_linker = linker_type == LinkerType("gnu")
+
+        # `--disable-new-dtags`: without it, GNU ld's default emits the
+        # modern DT_RUNPATH tag for `-rpath`, which the dynamic loader only
+        # consults when resolving *this object's own* direct NEEDED entries
+        # - it is deliberately not inherited by anything loaded as a result
+        # of it. That's invisible for a single-hop native shared dependency
+        # (executable -> core.so -> rts.so: core.so's own link already
+        # embeds a direct reference to rts.so, so the executable's runpath
+        # is never even needed for that hop) but breaks a multi-hop chain
+        # like executable -> db.so -> rocksdb.so -> storage.so: none of
+        # db.so/rocksdb.so carry any rpath of their own (nothing in this
+        # migration's cxx_library()/haskell_library() link steps sets one),
+        # so once the executable's own DT_RUNPATH resolves db.so, nothing
+        # is left to tell the loader where storage.so lives when resolving
+        # *rocksdb.so's* NEEDED entries - "cannot open shared object file"
+        # at process startup despite the .so genuinely being right there in
+        # the symlink tree that got built. The legacy DT_RPATH tag doesn't
+        # have this limitation: the loader folds every RPATH it encounters
+        # into one global search list used for the *whole* transitive
+        # resolution, not just the object that carries it - exactly what a
+        # dependency chain of arbitrary depth needs, without requiring every
+        # library along the way to separately carry its own rpath.
+        # (GNU ld only: Mach-O has no such distinction.)
+        if is_gnu_linker:
+            link.add("-optl", "-Wl,--disable-new-dtags")
+        link.add("-optl", "-Wl,-rpath", "-optl", rpath_ldflag)
+
+        # `-rpath` (above) only takes effect once the *finished binary* runs
+        # - it's a token ($ORIGIN/...) baked into the ELF's DT_RUNPATH,
+        # meaningless to the linker invoked *right now* to produce that
+        # binary, since there's no running process yet for $ORIGIN to refer
+        # to. That's invisible for a single-hop shared dependency (e.g. this
+        # binary -> rts.so directly): buck2's normal cxx linking machinery
+        # already emits a direct, real `-L<dir> -l<name>` for anything in
+        # `nlis` above, which the build-time linker can resolve on its own.
+        # It breaks down for a *multi-hop* native shared-library chain (e.g.
+        # this binary -> db.so -> rocksdb.so -> storage.so, where storage
+        # is only ever a dependency-of-a-dependency, never listed directly
+        # in any Haskell target's own `deps`): the linker, while resolving
+        # rocksdb.so's own DT_NEEDED entry on storage.so to check whether it
+        # actually provides the symbols db.so's own code references, has no
+        # real, existing-right-now path to look in, and conservatively
+        # reports those symbols undefined rather than assuming they'd
+        # resolve at runtime. `-rpath-link` is the link-time-only counterpart
+        # to `-rpath`: same directory, but as a real path valid *now*, purely
+        # a search hint for the linker's own transitive-NEEDED resolution -
+        # it doesn't get embedded in the output at all. Passing both this and
+        # the $ORIGIN-relative `-rpath` fixes multi-hop native shared
+        # dependencies generally, without needing to know in advance whether
+        # any given target's dependency graph actually has one.
+        #
+        # (GNU ld only: Apple's ld doesn't resolve a dependency's own
+        # dependencies at link time.)
+        if is_gnu_linker:
+            link.add("-optl", cmd_args("-Wl,-rpath-link,", symlink_dir, delimiter = ""))
+
+    ctx.actions.run(link, category = "haskell_link", env = haskell_toolchain.link_env)
+
+    if symlink_dir != None:
+        run = cmd_args(output, hidden = symlink_dir)
+    else:
+        run = cmd_args(output)
+
+    # With data_dirs or run_tool_depends, `buck2 run` and tests go through
+    # the wrapper script. The original command, the data directories and the
+    # tools are hidden inputs, so that they (and the symlink_dir of shared
+    # libraries) are materialized too.
+    if ctx.attrs.data_dirs or ctx.attrs.run_tool_depends:
+        run = cmd_args(
+            _run_wrapper(ctx, output),
+            hidden = [run, data_dirs_env(ctx).values(), [t.get(RunInfo) or t[DefaultInfo].default_outputs for t in ctx.attrs.run_tool_depends]],
+        )
+
+    providers = [
+        DefaultInfo(
+            default_output = output,
+            sub_targets = {"interfaces": [DefaultInfo(default_output = compiled.hi)]} | (
+                {"diagnostics.txt": [DefaultInfo(default_output = _diagnostics(ctx, compiled))]} if compiled.modules != None else {}
+            ),
+        ),
+        RunInfo(args = run),
+    ] + advice_validations(compiled)
+
+    if indexing_tsets:
+        providers.append(HaskellIndexInfo(info = indexing_tsets))
+
+    return providers
+
+# Note [Link styles and profiling]
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# The big picture
+# ---------------
+#
+# Haskell code can be linked in three styles:
+#
+#   static      archives (.a) of ordinary code
+#   static_pic  archives of position-independent code
+#   shared      shared libraries (.so, .dylib)
+#
+# and, independently, profiled or not. Profiled code can only be linked
+# statically: GHC doesn't support profiling with dynamic linking. So there are
+# five variants of a library: static, static_pic and shared unprofiled, and
+# static and static_pic profiled.
+#
+# Two parties decide how a library is linked, separately:
+#
+#  * The library, by its preferred_linkage, decides which variants it offers.
+#    It can't know how the executables that use it will be linked: a target
+#    is analysed apart from the targets that depend on it, and all it sees of
+#    them is its configuration.
+#
+#  * The executable, by its link_style, decides which variant it asks for.
+#
+# Where the two disagree, buck2 lets the library win: for each library, the
+# variant an executable gets is get_lib_output_style(link strategy,
+# preferred_linkage), in prelude/linking/link_info.bzl. In particular, a
+# library whose preferred_linkage is "shared" is linked shared whatever the
+# executable asks for.
+#
+# Profiling breaks that rule, because a profiled executable can't link a
+# shared library: to it, every library is linked statically. The rest of this
+# Note is about how each side does its part, and how profiling and Template
+# Haskell fit in.
+#
+# What a library offers
+# ---------------------
+#
+# haskell_library_impl declares the actions for each variant it offers. For
+# each, it compiles the library's modules, registers the package in a package
+# database of its own (for compiling against it), and makes the library
+# itself (an archive, or a shared library). buck2 only runs the actions whose
+# outputs are demanded, so it costs nothing extra to offer all the variants.
+#
+#  * The unprofiled variants are those of its preferred_linkage
+#    (get_output_styles_for_linkage):
+#
+#      "any"     static, static_pic, shared
+#      "static"  static, static_pic
+#      "shared"  static_pic, shared
+#
+#  * The profiled variants are always static and static_pic, whatever its
+#    preferred_linkage (prof_link_styles).
+#
+# What it offers is described by these providers:
+#
+#  * HaskellLinkInfo: the package of each variant, with those of its
+#    dependencies, by link style: `info` for the unprofiled variants and
+#    `prof_info` for the profiled ones. This is what a compile against the
+#    library uses.
+#
+#  * MergedLinkInfo: how to link the library and its dependencies, for each
+#    link strategy, by the get_lib_output_style table. This is what an
+#    unprofiled link uses, and what any non-Haskell target that depends on the
+#    library uses (a cxx_binary, say).
+#
+#  * HaskellProfLinkInfo: the same for a profiled link, made as if the
+#    library's preferred_linkage were "static", so that it gives the profiled
+#    archive of the same style for every link strategy (prof_merged_link_info).
+#    It never gives a shared library: there is no profiled one, and an
+#    unprofiled one linked into a profiled executable fails at runtime.
+#
+# A library can itself have enable_profiling = True. Then its "any" linkage
+# becomes "static", and its MergedLinkInfo is that of its profiled variants,
+# for a non-Haskell target to link. Such a target may still link it shared, so
+# its MergedLinkInfo also offers the unprofiled shared library, where there is
+# one (default_link_infos).
+#
+# What an executable asks for
+# ---------------------------
+#
+# haskell_binary_impl takes its link_style from the attribute, or else from the
+# C++ toolchain's default, and then adjusts it:
+#
+#  * A profiled executable asking for "shared" is linked "static".
+#
+#  * Where all code is position-independent (macOS: the toolchain's
+#    pic_behavior is "always_enabled"), "static" is "static_pic".
+#
+# It then uses that link style twice, with the libraries it depends on:
+#
+#  1. To compile its own modules against them. It asks each for the package of
+#     that link style (info[link_style], or prof_info[link_style] when
+#     profiled), so each library must offer a variant of that style.
+#
+#  2. To link them. An unprofiled executable takes each library's
+#     MergedLinkInfo for its link strategy, and so gets whatever variant the
+#     get_lib_output_style table picks; a profiled one takes each library's
+#     HaskellProfLinkInfo, and so gets the profiled archive of its style.
+#
+# Template Haskell
+# ----------------
+#
+# GHC runs a Template Haskell splice in its own process, by loading the code
+# the splice uses: the modules it uses of the libraries the module depends on,
+# and of the module's own library. GHC loads code the way that it was itself
+# linked (GHC calls this its "host way"). A GHC linked statically loads
+# archives, and the ordinary .hi interfaces that go with them: any
+# non-profiled static variant will do. A GHC linked dynamically
+# (haskell_toolchain.dynamic_ghc, which is how GHC is normally installed)
+# loads shared libraries, and the .dyn_hi interfaces that go with them. It
+# can also load a non-profiled archive, with GHC's own runtime linker, but we
+# don't rely on that. No GHC can load profiled code.
+#
+# For each variant of a library, its splice variant is the variant whose code
+# GHC loads when a splice in a module compiled against that variant runs the
+# library's code. With a dynamic GHC, every variant's splice variant is the
+# shared variant. With a static GHC, it is the non-profiled variant of the
+# same style, so a non-profiled variant is its own. The library builds a
+# splice variant even if it doesn't otherwise offer it, and then nothing links
+# it.
+#
+# A variant's package names its splice variant's interfaces in import-dirs,
+# beside its own. With a dynamic GHC, the package's dynamic-library-dirs
+# names the shared library's directory (see _register_library). GHC finds
+# the shared library there because it has the same name as the variant's own
+# library. A static GHC looks in library-dirs, which names only the variant's
+# own library, so it doesn't find a profiled variant's splice variant (see
+# Known gaps below).
+#
+# When the shared variant and the static style that executables use
+# (consumed_static_link_style: "static", or "static_pic" on macOS) are both
+# built, we compile the static variant with -dynamic-too (build_shared_too),
+# and make the shared variant from the same compile: the shared library is
+# linked from the .dyn_o files, and the .dyn_hi files are beside the .hi
+# files, in the static variant's own directory.
+#
+# A splice can also use a module of the same library. GHC then loads that
+# module's .dyn_o from the compile's own output directory, where it would be
+# if, as with Cabal, both ways were compiled in one place. A profiled compile
+# writes only profiled objects, so the .dyn_o of the unprofiled compile that
+# made the shared library are copied in before it runs (`dynamic_from` on
+# compile).
+#
+# Examples
+# --------
+#
+# With a dynamic GHC:
+#
+#  * Libraries "shared", executables "shared": each module is compiled once,
+#    the dynamic way. (Offering a static variant as well would make that one
+#    compile with -dynamic-too, which costs about as much as two.)
+#
+#  * Libraries "any" or "static", executables "static": each module is
+#    compiled once with -dynamic-too, for both the static and the shared
+#    variant. A "static" library's shared variant is only for splices. An
+#    executable that compiles per module also compiles each of its own
+#    modules with -dynamic-too, because a per-module compile can't tell which
+#    modules splices need (see Note [Template Haskell modules] in
+#    compile_per_module.bzl). With --make, GHC uses -dynamic-too only for
+#    those modules.
+#
+#  * Either of those, with executables that have enable_profiling = True: the
+#    executables compile against their libraries' profiled packages and link
+#    their profiled archives, whatever their link_style. The libraries'
+#    profiled variants are compiled as well, and registered with their shared
+#    variants, which are built already.
+#
+# Known gaps
+# ----------
+#
+#  * An unprofiled executable whose link_style is "static" fails analysis when
+#    a library it depends on doesn't offer static (its preferred_linkage is
+#    "shared"): there is no package of that style to compile against. One
+#    whose link_style is "static_pic" compiles against the libraries'
+#    static_pic packages, but still links their shared libraries.
+#
+#  * With a static GHC, a profiled module can't use a library's code in a
+#    splice, unless it is compiled with -fexternal-interpreter. GHC's
+#    internal interpreter looks for the library in the profiled package's
+#    library-dirs, which names only the profiled archive, and it can't load
+#    profiled code. Cabal puts both archives in one directory. Here a
+#    library's package is shared by targets that may or may not use an
+#    external interpreter, and the two want different archives under the
+#    same name. This is from reading GHC's loader: the tests use a dynamic
+#    GHC.
+
+# Note [Native libraries in package dbs]
+#
+# A library's shared object needs the shared libraries of its native (C)
+# dependencies. They are `DT_NEEDED` entries with no rpath that finds them
+# in buck-out. So when GHC's interpreter loads the library, for a splice,
+# something must load them first.
+#
+# So a library's final db names them, as a Cabal-built package names its C
+# libraries: in `extra-libraries`, each after the ones it depends on and
+# all before the library itself, with their directory in `library-dirs` and
+# `dynamic-library-dirs`. The library's own Haskell library is the last
+# entry of `extra-libraries` too. GHC's interpreter loads a package's
+# `extra-libraries` by path, in that order, and the dynamic loader then
+# finds each one already loaded when a later one needs it.
+# (`extra-ghci-libraries` would be the wrong field: the interpreter loads it
+# instead of `extra-libraries`, not as well.)
+#
+# No link reads these fields: no link is given the package dbs or -package
+# flags of local libraries, which it links from their link infos.
+#
+# That needs nothing from the environment of the process that loads the
+# library, so a module whose splices load native libraries can compile in
+# the persistent worker.
+#
+# GHC only finds a library named in extra-libraries as libNAME.so, which a
+# library's soname needn't be (libver.so.1, say). So the db's directory has
+# a link of that form for each library (see _named_native_libs).
+#
+# In the persistent worker, loaded native libraries are shared by the
+# compiles of every target. Two different native libraries with the same
+# soname would clash there.
diff --git a/buck2/prelude/haskell/haskell_ghci.bzl b/buck2/prelude/haskell/haskell_ghci.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/haskell_ghci.bzl
@@ -0,0 +1,740 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "PicBehavior")
+load(
+    "@prelude//cxx:link.bzl",
+    "cxx_link_shared_library",
+)
+load(
+    "@prelude//cxx:link_types.bzl",
+    "link_options",
+)
+load(
+    "@prelude//haskell:compile.bzl",
+    "PackagesInfo",
+    "get_packages_info",
+)
+load(
+    "@prelude//haskell:library_info.bzl",
+    "HaskellLibraryInfo",
+    "HaskellLibraryProvider",
+)
+load(
+    "@prelude//haskell:toolchain.bzl",
+    "HaskellToolchainInfo",
+)
+load("@prelude//haskell:util.bzl", "attr_deps")
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkArgs",
+    "LinkInfo",
+    "LinkStyle",
+    "get_lib_output_style",
+    "set_linkable_link_whole",
+    "to_link_strategy",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",
+    "LinkableRootInfo",
+    "create_linkable_graph",
+    "get_deps_for_link",
+    "get_link_info",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "create_shlib_symlink_tree",
+    "traverse_shared_library_info",
+    "with_unique_str_sonames",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load(
+    "@prelude//utils:graph_utils.bzl",
+    "depth_first_traversal",
+    "depth_first_traversal_by",
+)
+load("@prelude//utils:utils.bzl", "flatten")
+
+GHCiPreloadDepsInfo = record(
+    preload_symlinks = dict[str, Artifact],
+    preload_deps_root = Artifact,
+)
+
+USER_GHCI_PATH = "user_ghci_path"
+BINUTILS_PATH = "binutils_path"
+GHCI_LIB_PATH = "ghci_lib_path"
+CC_PATH = "cc_path"
+CPP_PATH = "cpp_path"
+CXX_PATH = "cxx_path"
+GHCI_PACKAGER = "ghc_pkg_path"
+GHCI_GHC_PATH = "ghc_path"
+
+HaskellOmnibusData = record(
+    omnibus = Artifact,
+    so_symlinks_root = Artifact,
+)
+
+def _write_final_ghci_script(
+    ctx: AnalysisContext,
+    omnibus_data: HaskellOmnibusData,
+    packages_info: PackagesInfo,
+    packagedb_args: cmd_args,
+    prebuilt_packagedb_args: cmd_args,
+    iserv_script: Artifact,
+    start_ghci_file: Artifact,
+    ghci_bin: Artifact,
+    haskell_toolchain: HaskellToolchainInfo,
+    ghci_script_template: Artifact,
+    enable_profiling: bool,
+) -> Artifact:
+    srcs = " ".join(
+        [
+            paths.normalize(
+                paths.join(
+                    paths.relativize(str(ctx.label.path), "fbcode"),
+                    s,
+                ),
+            )
+            for s in ctx.attrs.srcs
+        ],
+    )
+
+    # Collect compiler flags
+    compiler_flags = cmd_args(
+        # TODO(gustavoavena): do I need to filter these flags?
+        filter(lambda x: x == "-O", haskell_toolchain.compiler_flags),
+        delimiter = " ",
+    )
+
+    compiler_flags.add([
+        "-fPIC",
+        "-fexternal-dynamic-refs",
+    ])
+
+    if enable_profiling:
+        compiler_flags.add([
+            "-prof",
+            "-osuf p_o",
+            "-hisuf p_hi",
+        ])
+
+    compiler_flags.add(ctx.attrs.compiler_flags)
+    omnibus_so = omnibus_data.omnibus
+
+    final_ghci_script = _replace_macros_in_script_template(
+        ctx,
+        script_template = ghci_script_template,
+        haskell_toolchain = haskell_toolchain,
+        ghci_bin = ghci_bin,
+        exposed_package_args = packages_info.exposed_package_args,
+        packagedb_args = packagedb_args,
+        prebuilt_packagedb_args = prebuilt_packagedb_args,
+        start_ghci = start_ghci_file,
+        iserv_script = iserv_script,
+        squashed_so = omnibus_so,
+        compiler_flags = compiler_flags,
+        srcs = srcs,
+        output_name = ctx.label.name,
+    )
+
+    return final_ghci_script
+
+def _build_haskell_omnibus_so(ctx: AnalysisContext) -> HaskellOmnibusData:
+    link_style = LinkStyle("static_pic")
+    if False:
+        # TODO(nga): typechecker raises issue here.
+        def unknown():
+            pass
+
+        link_style = unknown()
+
+    # pic_behavior = PicBehavior("always_enabled")
+    pic_behavior = PicBehavior("supported")
+    preload_deps = ctx.attrs.preload_deps
+
+    all_deps = attr_deps(ctx) + preload_deps + ctx.attrs.template_deps
+
+    linkable_graph_ = create_linkable_graph(
+        ctx,
+        deps = all_deps,
+    )
+
+    # Keep only linkable nodes
+    graph_nodes = {n.label: n.linkable for n in linkable_graph_.nodes.traverse() if n.linkable}
+
+    # Map node label to its dependencies' labels
+    dep_graph = {nlabel: get_deps_for_link(n, to_link_strategy(link_style), pic_behavior) for nlabel, n in graph_nodes.items()}
+
+    all_direct_deps = []
+    for dep in all_deps:
+        graph = dep.get(LinkableGraph)
+        if graph:
+            all_direct_deps.append(graph.label)
+    dep_graph[ctx.label] = all_direct_deps
+
+    # Need to exclude all transitive deps of excluded deps
+    all_nodes_to_exclude = depth_first_traversal(
+        dep_graph,
+        [dep[LinkableGraph].label for dep in preload_deps if LinkableGraph in dep],
+    )
+
+    # Body nodes should support haskell omnibus (e.g. cxx_library)
+    # and can't be prebuilt tp dependencies
+    body_nodes = set()
+
+    # Prebuilt (i.e. third-party) nodes shouldn't be statically linked on
+    # the omnibus, but we need to keep track of them because they're a
+    # dependency of it and are linked dynamically.
+    prebuilt_so_deps = set()
+
+    # Helper to get body nodes and prebuilt dependencies of the
+    # omnibus SO (which should dynamically linked) during BFS traversal
+    def find_deps_for_body(node_label: Label):
+        deps = dep_graph[node_label]
+
+        final_deps = []
+        for node_label in deps:
+            node = graph_nodes[node_label]
+
+            # We process these libs even if they're excluded, as they need to
+            # be added to the link line.
+            if "prebuilt_so_for_haskell_omnibus" in node.labels:
+                # If the library is marked as force-static, then it won't provide
+                # shared libs and we'll have to link is statically.
+                if node.preferred_linkage == Linkage("static"):
+                    body_nodes.add(node_label)
+                else:
+                    prebuilt_so_deps.add(node_label)
+
+            if node_label in all_nodes_to_exclude:
+                continue
+
+            if "supports_haskell_omnibus" in node.labels and "prebuilt_so_for_haskell_omnibus" not in node.labels:
+                body_nodes.add(node_label)
+
+            final_deps.append(node_label)
+
+        return final_deps
+
+    # This is not the final set of body nodes, because it still includes
+    # nodes that don't support omnibus (e.g. haskell_library nodes)
+    depth_first_traversal_by(
+        dep_graph,
+        [ctx.label],
+        find_deps_for_body,
+    )
+
+    # After collecting all the body nodes, get all their linkables (e.g. `.a`
+    # files) that will be part of the omnibus SO.
+    body_link_infos = {}
+
+    for node_label in body_nodes:
+        node = graph_nodes[node_label]
+
+        node_target = node_label.raw_target()
+        if node_target in body_link_infos:
+            # Not skipping these leads to duplicate symbol errors
+            continue
+
+        output_style = get_lib_output_style(
+            to_link_strategy(link_style),
+            node.preferred_linkage,
+            pic_behavior = pic_behavior,
+        )
+
+        li = get_link_info(node, output_style)
+        linkables = [
+            # All symbols need to be included in the omnibus so, even if
+            # they're not being referenced yet, so we should enable
+            # link_whole which passes the `--whole-archive` linker flag.
+            set_linkable_link_whole(linkable)
+            for linkable in li.linkables
+        ]
+        new_li = LinkInfo(
+            name = li.name,
+            pre_flags = li.pre_flags,
+            post_flags = li.post_flags,
+            linkables = linkables,
+            external_debug_info = li.external_debug_info,
+        )
+        body_link_infos[node_target] = new_li
+
+    # Handle third-party dependencies of the omnibus SO
+    tp_deps_shared_link_infos = {}
+    prebuilt_shlibs = []
+
+    for node_label in prebuilt_so_deps:
+        node = graph_nodes[node_label]
+
+        output_style = get_lib_output_style(
+            to_link_strategy(LinkStyle("shared")),
+            node.preferred_linkage,
+            pic_behavior = pic_behavior,
+        )
+
+        shared_li = node.link_infos.get(output_style, None)
+        if shared_li != None:
+            tp_deps_shared_link_infos[node_label] = shared_li.default
+        prebuilt_shlibs.extend(node.shared_libs.libraries)
+
+    # Create symlinks to the TP dependencies' SOs
+    so_symlinks_root_path = ctx.label.name + ".so-symlinks"
+    so_symlinks_root = create_shlib_symlink_tree(
+        actions = ctx.actions,
+        out = so_symlinks_root_path,
+        shared_libs = prebuilt_shlibs,
+    )
+
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    soname = "libghci_dependencies.so"
+    extra_ldflags = [
+        "-rpath",
+        "$ORIGIN/{}".format(so_symlinks_root_path),
+    ]
+    link_result = cxx_link_shared_library(
+        ctx,
+        soname,
+        opts = link_options(
+            links = [
+                LinkArgs(flags = extra_ldflags),
+                LinkArgs(infos = body_link_infos.values()),
+                LinkArgs(infos = tp_deps_shared_link_infos.values()),
+            ],
+            category_suffix = "omnibus",
+            link_weight = linker_info.link_weight,
+            identifier = soname,
+            link_execution_preference = LinkExecutionPreference("any"),
+            produce_shared_library_interface = False,
+        ),
+    )
+    omnibus = link_result.linked_object.output
+
+    return HaskellOmnibusData(
+        omnibus = omnibus,
+        so_symlinks_root = so_symlinks_root,
+    )
+
+# Use the script_template_processor.py script to generate a script from a
+# script template.
+def _replace_macros_in_script_template(
+    ctx: AnalysisContext,
+    script_template: Artifact,
+    haskell_toolchain: HaskellToolchainInfo,
+    # Optional artifacts
+    ghci_bin: Artifact | None = None,
+    start_ghci: Artifact | None = None,
+    iserv_script: Artifact | None = None,
+    squashed_so: Artifact | None = None,
+    # Optional cmd_args
+    exposed_package_args: [cmd_args, None] = None,
+    packagedb_args: [cmd_args, None] = None,
+    prebuilt_packagedb_args: [cmd_args, None] = None,
+    compiler_flags: [cmd_args, None] = None,
+    # Optional string args
+    srcs: [str, None] = None,
+    output_name: [str, None] = None,
+    ghci_iserv_path: [Artifact, None] = None,
+    preload_libs: [str, None] = None,
+) -> Artifact:
+    toolchain_paths = {
+        BINUTILS_PATH: haskell_toolchain.ghci_binutils_path,
+        GHCI_LIB_PATH: haskell_toolchain.ghci_lib_path.get(DefaultInfo).default_outputs[0],
+        CC_PATH: haskell_toolchain.ghci_cc_path,
+        CPP_PATH: haskell_toolchain.ghci_cpp_path,
+        CXX_PATH: haskell_toolchain.ghci_cxx_path,
+        GHCI_PACKAGER: haskell_toolchain.ghci_packager.get(DefaultInfo).default_outputs[0],
+        GHCI_GHC_PATH: haskell_toolchain.ghci_ghc_path.get(DefaultInfo).default_outputs[0],
+    }
+
+    if ghci_bin != None:
+        toolchain_paths[USER_GHCI_PATH] = ghci_bin.short_path
+
+    final_script = ctx.actions.declare_output(
+        script_template.basename if not output_name else output_name,
+        has_content_based_path = False,
+    )
+    script_template_processor = haskell_toolchain.script_template_processor[RunInfo]
+
+    replace_cmd = cmd_args(script_template_processor)
+    replace_cmd.add(cmd_args(script_template, format = "--script_template={}"))
+    for name, path in toolchain_paths.items():
+        if path:
+            replace_cmd.add(cmd_args(path, format = "--{}={{}}".format(name)))
+
+    replace_cmd.add(
+        cmd_args(
+            final_script.as_output(),
+            format = "--output={}",
+        )
+    )
+
+    replace_cmd.add(
+        cmd_args(
+            ctx.label.name,
+            format = "--target_name={}",
+        )
+    )
+
+    exposed_package_args = exposed_package_args if exposed_package_args != None else ""
+    replace_cmd.add(
+        cmd_args(
+            cmd_args(exposed_package_args, delimiter = " "),
+            format = "--exposed_packages={}",
+        )
+    )
+
+    if packagedb_args != None:
+        replace_cmd.add(
+            cmd_args(
+                packagedb_args,
+                format = "--package_dbs={}",
+            )
+        )
+    if prebuilt_packagedb_args != None:
+        replace_cmd.add(
+            cmd_args(
+                prebuilt_packagedb_args,
+                format = "--prebuilt_package_dbs={}",
+            )
+        )
+
+    # Tuple containing orig value (for null check), macro value and flag name
+    optional_flags = [
+        (
+            start_ghci,
+            start_ghci.short_path if start_ghci != None else "",
+            "--start_ghci",
+        ),
+        (iserv_script, "iserv", "--iserv_path"),
+        (
+            squashed_so,
+            squashed_so.short_path if squashed_so != None else "",
+            "--squashed_so",
+        ),
+        (compiler_flags, compiler_flags, "--compiler_flags"),
+        (srcs, srcs, "--srcs"),
+        (ghci_iserv_path, ghci_iserv_path, "--ghci_iserv_path"),
+        (preload_libs, preload_libs, "--preload_libs"),
+    ]
+
+    for orig_val, macro_value, flag in optional_flags:
+        if orig_val != None:
+            replace_cmd.add(
+                cmd_args(
+                    macro_value,
+                    format = flag + "={}",
+                )
+            )
+
+    ctx.actions.run(
+        replace_cmd,
+        category = "replace_template_{}".format(
+            script_template.basename.replace("-", "_"),
+        ),
+        local_only = True,
+    )
+
+    return final_script
+
+def _write_iserv_script(
+    ctx: AnalysisContext, preload_deps_info: GHCiPreloadDepsInfo, haskell_toolchain: HaskellToolchainInfo, enable_profiling: bool
+) -> Artifact:
+    ghci_iserv_template = haskell_toolchain.ghci_iserv_template
+
+    if not ghci_iserv_template:
+        fail("ghci_iserv_template missing in haskell_toolchain")
+
+    preload_libs = ":".join(
+        [
+            paths.join(
+                "${DIR}",
+                preload_deps_info.preload_deps_root.short_path,
+                so,
+            )
+            for so in sorted(preload_deps_info.preload_symlinks)
+        ],
+    )
+
+    if enable_profiling:
+        ghci_iserv_path = haskell_toolchain.ghci_iserv_prof_path
+    else:
+        ghci_iserv_path = haskell_toolchain.ghci_iserv_path
+
+    iserv_script_name = "iserv"
+    if enable_profiling:
+        iserv_script_name += "-prof"
+
+    iserv_script = _replace_macros_in_script_template(
+        ctx,
+        script_template = ghci_iserv_template,
+        output_name = iserv_script_name,
+        haskell_toolchain = haskell_toolchain,
+        ghci_iserv_path = ghci_iserv_path.get(DefaultInfo).default_outputs[0],
+        preload_libs = preload_libs,
+    )
+    return iserv_script
+
+def _build_preload_deps_root(ctx: AnalysisContext, haskell_toolchain: HaskellToolchainInfo) -> GHCiPreloadDepsInfo:
+    preload_deps = ctx.attrs.preload_deps
+
+    preload_symlinks = {}
+    preload_libs_root = ctx.label.name + ".preload-symlinks"
+
+    for preload_dep in preload_deps:
+        if SharedLibraryInfo in preload_dep:
+            slib_info = preload_dep[SharedLibraryInfo]
+
+            shlib = traverse_shared_library_info(slib_info, transformation_provider = None)
+
+            for soname, shared_lib in with_unique_str_sonames(shlib).items():
+                preload_symlinks[soname] = shared_lib.lib.output
+
+        # TODO(T150785851): build or get SO for direct preload_deps
+        # TODO(T150785851): find out why the only SOs missing are the ones from
+        # the preload_deps themselves, even though the ones from their deps are
+        # already there.
+        if LinkableRootInfo in preload_dep:
+            linkable_root_info = preload_dep[LinkableRootInfo]
+            preload_so_name = linkable_root_info.name
+
+            linkables = map(lambda x: x.objects, linkable_root_info.link_infos.default.linkables)
+
+            object_file = flatten(linkables)[0]
+
+            preload_so = ctx.actions.declare_output(preload_so_name, has_content_based_path = False)
+            link = cmd_args(haskell_toolchain.linker)
+            link.add(haskell_toolchain.linker_flags)
+            link.add(ctx.attrs.linker_flags)
+            link.add("-o", preload_so.as_output())
+
+            link.add(
+                "-shared",
+                "-dynamic",
+                "-optl",
+                "-Wl,-soname",
+                "-optl",
+                "-Wl," + preload_so_name,
+            )
+            link.add(object_file)
+
+            ctx.actions.run(
+                link,
+                category = "haskell_ghci_link",
+                identifier = preload_so_name,
+            )
+
+            preload_symlinks[preload_so_name] = preload_so
+
+    preload_deps_root = ctx.actions.symlinked_dir(preload_libs_root, preload_symlinks, has_content_based_path = False)
+    return GHCiPreloadDepsInfo(
+        preload_deps_root = preload_deps_root,
+        preload_symlinks = preload_symlinks,
+    )
+
+# Symlink the ghci binary that will be used, e.g. the internal fork in Haxlsh
+def _symlink_ghci_binary(ctx, haskell_toolchain: HaskellToolchainInfo, ghci_bin: Artifact):
+    ghci_bin_dep = ctx.attrs.ghci_bin_dep
+    if not ghci_bin_dep:
+        ghci_bin_dep = haskell_toolchain.ghci_ghc_path
+
+    # NOTE: In the buck1 version we'd symlink the binary only if a custom one
+    # was provided, but in buck2 we're always setting `ghci_bin_dep` (i.e.
+    # to default one if custom wasn't provided).
+    src = ghci_bin_dep[DefaultInfo].default_outputs[0]
+    ctx.actions.symlink_file(ghci_bin.as_output(), src)
+
+def _first_order_haskell_deps(ctx: AnalysisContext, enable_profiling: bool) -> list[HaskellLibraryInfo]:
+    libs = []
+    for dep in ctx.attrs.deps:
+        if HaskellLibraryProvider in dep:
+            if enable_profiling:
+                libs.append(dep[HaskellLibraryProvider].prof_lib.values())
+            else:
+                libs.append(dep[HaskellLibraryProvider].lib.values())
+
+    return dedupe(flatten(libs))
+
+# Creates the start.ghci script used to load the packages during startup
+def _write_start_ghci(ctx: AnalysisContext, script_file: Artifact, enable_profiling: bool):
+    start_cmd = cmd_args()
+
+    # Reason for unsetting `LD_PRELOAD` env var obtained from D6255224:
+    # "Certain libraries (like allocators) cannot be loaded after the process
+    # has started. When needing to use these libraries, send them to a
+    # user-supplied script for handling them appropriately. Running the real
+    # iserv with these libraries under LD_PRELOAD accomplishes this.
+    # To ensure the LD_PRELOAD env doesn't make it to subsequently forked
+    # processes, the very first action of start.ghci is to unset the variable."
+    start_cmd.add('System.Environment.unsetEnv "LD_PRELOAD"')
+
+    set_cmd = cmd_args(":set", delimiter = " ")
+    first_order_deps = list(
+        map(
+            lambda dep: dep.name + "-" + dep.version,
+            _first_order_haskell_deps(ctx, enable_profiling),
+        )
+    )
+    deduped_deps = {pkg: 1 for pkg in first_order_deps}.keys()
+    package_list = cmd_args(
+        deduped_deps,
+        format = "-package {}",
+        delimiter = " ",
+    )
+    set_cmd.add(package_list)
+    set_cmd.add("\n")
+    start_cmd.add(set_cmd)
+
+    header_ghci = ctx.actions.declare_output("header.ghci", has_content_based_path = False)
+
+    ctx.actions.write(header_ghci.as_output(), start_cmd)
+
+    if ctx.attrs.ghci_init:
+        append_ghci_init = cmd_args()
+        append_ghci_init.add(
+            ["sh", "-c", 'cat "$1" "$2" > "$3"', "--", header_ghci, ctx.attrs.ghci_init, script_file.as_output()],
+        )
+        ctx.actions.run(append_ghci_init, category = "append_ghci_init")
+    else:
+        ctx.actions.copy_file(script_file, header_ghci)
+
+def haskell_ghci_impl(ctx: AnalysisContext) -> list[Provider]:
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+    enable_profiling = ctx.attrs.enable_profiling
+
+    start_ghci_file = ctx.actions.declare_output("start.ghci", has_content_based_path = False)
+    _write_start_ghci(ctx, start_ghci_file, enable_profiling)
+
+    ghci_bin = ctx.actions.declare_output(ctx.attrs.name + ".bin/ghci", has_content_based_path = False)
+    _symlink_ghci_binary(ctx, haskell_toolchain, ghci_bin)
+
+    preload_deps_info = _build_preload_deps_root(ctx, haskell_toolchain)
+
+    ghci_script_template = haskell_toolchain.ghci_script_template
+
+    if not ghci_script_template:
+        fail("ghci_script_template missing in haskell_toolchain")
+
+    iserv_script = _write_iserv_script(
+        ctx,
+        preload_deps_info,
+        haskell_toolchain,
+        enable_profiling,
+    )
+
+    link_style = LinkStyle("static_pic")
+
+    packages_info = get_packages_info(
+        ctx,
+        link_style,
+        specify_pkg_version = True,
+        enable_profiling = enable_profiling,
+    )
+
+    # Create package db symlinks
+    package_symlinks = []
+
+    package_symlinks_root = ctx.label.name + ".packages"
+
+    packagedb_args = cmd_args(delimiter = " ")
+    prebuilt_packagedb_args_set = set()
+
+    for lib in packages_info.transitive_deps.traverse():
+        if lib.is_prebuilt:
+            prebuilt_packagedb_args_set.add(lib.db)
+        else:
+            lib_symlinks_root = paths.join(
+                package_symlinks_root,
+                lib.name,
+            )
+            lib_symlinks = {
+                "packagedb": lib.db,
+            }
+
+            for import_dir in lib.import_dirs:
+                lib_symlinks[import_dir.short_path] = import_dir
+
+            for o in lib.libs:
+                lib_symlinks[o.short_path] = o
+
+            symlinked_things = ctx.actions.symlinked_dir(
+                lib_symlinks_root,
+                lib_symlinks,
+                has_content_based_path = False,
+            )
+
+            package_symlinks.append(symlinked_things)
+
+            packagedb_args.add(
+                paths.join(
+                    lib_symlinks_root,
+                    "packagedb",
+                ),
+            )
+    prebuilt_packagedb_args = cmd_args(list(prebuilt_packagedb_args_set), delimiter = " ")
+
+    script_templates = []
+    for script_template in ctx.attrs.extra_script_templates:
+        final_script = _replace_macros_in_script_template(
+            ctx,
+            script_template = script_template,
+            haskell_toolchain = haskell_toolchain,
+            ghci_bin = ghci_bin,
+            exposed_package_args = packages_info.exposed_package_args,
+            packagedb_args = packagedb_args,
+            prebuilt_packagedb_args = prebuilt_packagedb_args,
+        )
+        script_templates.append(final_script)
+
+    omnibus_data = _build_haskell_omnibus_so(ctx)
+
+    final_ghci_script = _write_final_ghci_script(
+        ctx,
+        omnibus_data,
+        packages_info,
+        packagedb_args,
+        prebuilt_packagedb_args,
+        iserv_script,
+        start_ghci_file,
+        ghci_bin,
+        haskell_toolchain,
+        ghci_script_template,
+        enable_profiling,
+    )
+
+    outputs = [
+        start_ghci_file,
+        ghci_bin,
+        preload_deps_info.preload_deps_root,
+        iserv_script,
+        omnibus_data.omnibus,
+        omnibus_data.so_symlinks_root,
+        final_ghci_script,
+    ]
+    outputs.extend(package_symlinks)
+    outputs.extend(script_templates)
+
+    # As default output (e.g. used in `$(location )` buck macros), the rule
+    # should output a directory containing symlinks to all scripts and resources
+    # (e.g. shared objects, package configs)
+    output_artifacts = {o.short_path: o for o in outputs}
+    root_output_dir = ctx.actions.symlinked_dir(
+        "__{}__".format(ctx.label.name),
+        output_artifacts,
+        has_content_based_path = False,
+    )
+    run = cmd_args(final_ghci_script, hidden = outputs)
+
+    return [
+        DefaultInfo(default_outputs = [root_output_dir]),
+        RunInfo(args = run),
+    ]
diff --git a/buck2/prelude/haskell/haskell_haddock.bzl b/buck2/prelude/haskell/haskell_haddock.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/haskell_haddock.bzl
@@ -0,0 +1,141 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//haskell:compile.bzl", "CompileResultInfo", "compile_args", "ghc_file_args", "haddock_from_interfaces", "run_ghc", "target_splice_env")
+load("@prelude//linking:link_info.bzl", "LinkStyle")
+load(
+    "@prelude//haskell:toolchain.bzl",
+    "HaskellToolchainInfo",
+)
+load(
+    "@prelude//haskell:util.bzl",
+    "attr_deps",
+)
+
+HaskellHaddockInfo = provider(
+    fields = {
+        "html": provider_field(typing.Any, default = None),
+        "interface": provider_field(typing.Any, default = None),
+    },
+)
+
+# The documentation of a library. `compiled` is the library's compile in
+# `link_style`.
+def haskell_haddock_lib(ctx: AnalysisContext, pkgname: str, link_style: LinkStyle, compiled: CompileResultInfo) -> Provider:
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+
+    iface = ctx.actions.declare_output("haddock-interface", has_content_based_path = False)
+    odir = ctx.actions.declare_output("haddock-html", dir = True, has_content_based_path = False)
+
+    # From the compile's interfaces, where haddock can, it runs no splices,
+    # so it needs no dependency's library. Otherwise it compiles the
+    # library's modules as `ghc --make` would, so its splices see what the
+    # compile's do.
+    from_interfaces = haddock_from_interfaces(ctx)
+    if from_interfaces:
+        splices = struct(final = set(), data_dirs = {})
+    else:
+        splices = target_splice_env(ctx, link_style, False)
+    args = compile_args(
+        ctx,
+        link_style,
+        enable_profiling = False,
+        pkgname = pkgname,
+        final = splices.final,
+    )
+
+    cmd = cmd_args(haskell_toolchain.haddock)
+    cmd.add(cmd_args(args.args_for_cmd, format = "--optghc={}"))
+    cmd.add(
+        "--use-index",
+        "doc-index.html",
+        "--use-contents",
+        "index.html",
+        "--html",
+        "--hoogle",
+        "--no-warnings",
+        "--dump-interface",
+        iface.as_output(),
+        "--odir",
+        odir.as_output(),
+        "--package-name",
+        pkgname,
+    )
+
+    for lib in attr_deps(ctx):
+        hi = lib.get(HaskellHaddockInfo)
+        if hi != None:
+            cmd.add("--read-interface", hi.interface)
+
+    cmd.add(ctx.attrs.haddock_flags)
+
+    source_entity = read_root_config("haskell", "haddock_source_entity", None)
+    if source_entity:
+        cmd.add("--source-entity", source_entity)
+
+    if args.args_for_file:
+        cmd.add(ghc_file_args(ctx, "args-" + args.variant + ".haskell_haddock_argsfile", cmd_args(args.args_for_file, format = "--optghc={}"), args.srcs))
+
+    if from_interfaces:
+        cmd.add("--no-compilation", "--optghc=-hidir", cmd_args(compiled.hi, format = "--optghc={}"))
+
+    # Otherwise haddock compiles in a temporary directory of its own.
+    run_ghc(ctx, cmd, splices, args.variant, "haddock-" + args.variant, "", [], "haskell_haddock")
+
+    return HaskellHaddockInfo(interface = iface, html = odir)
+
+def haskell_haddock_impl(ctx: AnalysisContext) -> list[Provider]:
+    haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
+
+    out = ctx.actions.declare_output("haddock-html", dir = True, has_content_based_path = False)
+
+    cmd = cmd_args(haskell_toolchain.haddock)
+
+    cmd.add(
+        "--gen-index",
+        "--gen-contents",
+        "-o",
+        out.as_output(),
+    )
+
+    dep_htmls = []
+    for lib in attr_deps(ctx):
+        hi = lib.get(HaskellHaddockInfo)
+        if hi != None:
+            cmd.add("--read-interface", hi.interface)
+            dep_htmls.append(hi.html)
+
+    cmd.add(ctx.attrs.haddock_flags)
+
+    script = ctx.actions.declare_output("haddock-script", has_content_based_path = False)
+    script_args = cmd_args([
+        "#!/usr/bin/env bash",
+        "set -ueo pipefail",
+        cmd_args(cmd, delimiter = " ", quote = "shell"),
+    ])
+    for dir in dep_htmls:
+        script_args.add(
+            cmd_args(
+                ["cp", "-Rf", cmd_args(dir, format = "{}/*"), out.as_output()],
+                delimiter = " ",
+            ),
+        )
+    ctx.actions.write(
+        script,
+        script_args,
+        is_executable = True,
+        allow_args = True,
+    )
+
+    ctx.actions.run(
+        cmd_args(script, hidden = script_args),
+        category = "haskell_haddock",
+        no_outputs_cleanup = True,
+    )
+
+    return [DefaultInfo(default_outputs = [out])]
diff --git a/buck2/prelude/haskell/haskell_ide.bzl b/buck2/prelude/haskell/haskell_ide.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/haskell_ide.bzl
@@ -0,0 +1,10 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def haskell_ide_impl(_ctx: AnalysisContext) -> list[Provider]:
+    return [DefaultInfo()]
diff --git a/buck2/prelude/haskell/ide/README.md b/buck2/prelude/haskell/ide/README.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/ide/README.md
@@ -0,0 +1,14 @@
+# Haskell Language Server integration
+
+This integration allows loading `haskell_binary` and `haskell_library` targets
+on Haskell Language Server. This is accomplished via a BXL script that is used
+to drive a hie-bios "bios" cradle.
+
+# Usage
+
+To print the list of GHC flags and targets for a Haskell source file:
+
+buck2 bxl prelude//haskell/ide/ide.bxl -- --bios true --file
+<repo_relative_path_to_source_file>
+
+To integrate with hie_bios, copy `hie.yaml` to your repo root
diff --git a/buck2/prelude/haskell/ide/hie.yaml b/buck2/prelude/haskell/ide/hie.yaml
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/ide/hie.yaml
@@ -0,0 +1,3 @@
+cradle:
+  bios:
+    shell: buck2 bxl prelude//haskell/ide/ide.bxl --bios true --file $HIE_BIOS_ARG > $HIE_BIOS_OUTPUT
diff --git a/buck2/prelude/haskell/ide/ide.bxl b/buck2/prelude/haskell/ide/ide.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/ide/ide.bxl
@@ -0,0 +1,344 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//haskell:library_info.bzl", "HaskellLibraryProvider")
+load("@prelude//haskell:link_info.bzl", "HaskellLinkInfo")
+load("@prelude//haskell:toolchain.bzl", "HaskellToolchainInfo")
+load("@prelude//linking:link_info.bzl", "LinkStyle")
+
+# This script computes a solution for loading a Haskell project in VSCode
+# The solution includes:
+# - flags (and materializing any artifacts used by the flags)
+# - source files
+# - external dependencies whose changes will cause a reload (e.g. TARGETS files)
+
+# There are only 3 rule types that we need to support
+# - haskell_binary
+# - haskell_library
+# - haskell_ide (aka "projects")
+
+# The input to the script is usually a source file, although it can also be a target
+# Solving an input involves:
+# 1. Finding its owner target, if the input is a file
+# 2. Finding the target's "project", which involves a rdeps search
+# 3. Computing the project solution (flags, sources and dependencies)
+# 4. Outputting the solution as JSON
+
+_HASKELL_BIN = "prelude//rules.bzl:haskell_binary"
+_HASKELL_IDE = "prelude//rules.bzl:haskell_ide"
+_HASKELL_LIB = "prelude//rules.bzl:haskell_library"
+
+linkStyle = LinkStyle("static")
+
+configuration_modifiers = ["ovr_config//third-party/ghc/constraints:9.2.4"]
+
+def _impl_target(ctx):
+    target = ctx.cli_args.target
+    project_universe = ctx.cli_args.project_universe
+    res = _find_project_and_solve(ctx, target, project_universe)
+    solution = _assembleSolution(ctx, linkStyle, res)
+    _print_solution(ctx, solution)
+
+def _print_solution(ctx, solution):
+    if not ctx.cli_args.bios:
+        ctx.output.print_json(solution)
+    else:
+        for flag in solution["flags"]:
+            ctx.output.print(flag)
+        for src in solution["sources"]:
+            ctx.output.print(src)
+
+def _impl_file(ctx):
+    project_universe = ctx.cli_args.project_universe
+    res = _solution_for_file(ctx, ctx.cli_args.file, project_universe)
+    solution = _assembleSolution(ctx, linkStyle, res)
+    _print_solution(ctx, solution)
+
+def _solution_for_file(ctx, file, project_universe):
+    unconfigured_owners = ctx.uquery().owner(file)
+    target_universe = ctx.target_universe(unconfigured_owners).target_set()
+    owners = ctx.cquery().owner(file, target_universe)
+    if not owners or len(owners) == 0:
+        return {
+            "external_dependencies": [],
+            "flags": [],
+            "generated_dependencies": [],
+            "haskell_deps": {},
+            "import_dirs": [],
+            "owner": "No owner found for " + file,
+            "project": "",
+            "project_type": "",
+            "sources": [],
+            "targets": [],
+        }
+
+    owner = owners[0]
+
+    result = _find_project_and_solve(ctx, owner, project_universe)
+    result["owner"] = owner.label.raw_target()
+    return result
+
+def _find_project_and_solve(ctx, target, project_universe = []):
+    if target.label.package.startswith("users/"):
+        prefix = "/".join(target.label.package.split("/")[:3])
+    else:
+        prefix = target.label.package.split("/", 1)[0]
+    local_universe = _find_project_universe(ctx, target.label.cell, prefix)
+    if local_universe:
+        project_universe.extend(local_universe)
+    project = _find_target_in_universe(ctx, target, dedupe(project_universe))
+
+    result = _solution_for_target(ctx, project)
+    result["project"] = project.label.raw_target()
+    result["project_type"] = project.rule_type
+    return result
+
+def _find_target_in_universe(ctx, target, project_universe):
+    for p in project_universe:
+        cfg_p = (
+            ctx.lazy.configured_target_node(
+                p,
+                modifiers = configuration_modifiers,
+            )
+            .catch()
+            .resolve()
+        )
+        if not (cfg_p.is_ok()) or cfg_p.unwrap() == None:
+            continue
+        cfg_p = cfg_p.unwrap()
+        members = cfg_p.resolved_attrs_eager(ctx).include_projects
+        for member in members:
+            if target.label.raw_target() == member.label.raw_target():
+                return cfg_p
+
+    return target
+
+def _find_project_universe(ctx, cell, prefix):
+    return ctx.uquery().eval("kind(haskell_ide, %s//%s/...)" % (cell, prefix))
+
+def _solution_for_target(ctx, target, exclude = {}):
+    result = None
+    if target.rule_type == _HASKELL_LIB:
+        result = _solution_for_haskell_lib(ctx, target, exclude)
+    elif target.rule_type == _HASKELL_BIN:
+        result = _solution_for_haskell_bin(ctx, target, exclude)
+    elif target.rule_type == _HASKELL_IDE:
+        result = _solution_for_haskell_ide(ctx, target)
+
+    if result == None:
+        return {"error": "Cannot handle rule type " + target.rule_type}
+    return result
+
+def _solution_for_haskell_ide(ctx, target):
+    resolved_attrs = target.resolved_attrs_eager(ctx)
+    results = []
+    deps = {}
+    for dep in resolved_attrs.deps_query:
+        t = ctx.configured_targets(
+            dep.label.raw_target(),
+            modifiers = configuration_modifiers,
+        )
+        if t.rule_type == _HASKELL_LIB or t.rule_type == _HASKELL_BIN:
+            deps[dep.label] = t
+    for lib in deps.values():
+        results.append(_solution_for_target(ctx, lib, deps))
+
+    final = merge(results)
+    final["targets"].extend(targetsForTarget(ctx, target))
+    return final
+
+def _solution_for_haskell_bin(ctx, target, exclude):
+    return _solution_for_haskell_lib(ctx, target, exclude)
+
+def _solution_for_haskell_lib(ctx, target, exclude):
+    resolved_attrs = target.resolved_attrs_eager(ctx)
+    hli = ctx.analysis(target).providers().get(HaskellLibraryProvider)
+
+    haskellLibs = {}
+    for dep in resolved_attrs.deps + resolved_attrs.template_deps:
+        if exclude.get(dep.label) == None:
+            providers = ctx.analysis(dep.label).providers()
+            lb = providers.get(HaskellLinkInfo)
+            if lb != None:
+                haskellLibs[dep.label] = lb
+
+    sources = []
+    for item in ctx.output.ensure_multiple(resolved_attrs.srcs.values()):
+        sources.append(item.abs_path())
+
+    import_dirs = {}
+    root = ctx.root()
+    for key, item in resolved_attrs.srcs.items():
+        # because BXL won't give you the path of an ensured artifact
+        sp = get_path_without_materialization(item, ctx)
+        (_, ext) = paths.split_extension(sp)
+        diff = sp.removesuffix(paths.replace_extension(key, ext))
+        import_dirs["%s/%s" % (root, diff)] = ()
+
+    haskell_toolchain = ctx.analysis(resolved_attrs._haskell_toolchain.label)
+    toolchain = haskell_toolchain.providers().get(HaskellToolchainInfo)
+
+    if "platform010/build/ghc/8.8.3/" in str(toolchain.packager):
+        msg = """ 
+        Haskell IDE cannot process this file. We only supports GHC 9.2.4,
+            but this file seems to have 8.8.3 dependecies. Please migrate your project to GHC 9.2.4.
+        """
+        fail(msg)
+
+    binutils_path = paths.join(root, toolchain.ghci_binutils_path)
+    cc_path = paths.join(root, toolchain.ghci_cc_path)
+    cxx_path = paths.join(root, toolchain.ghci_cxx_path)
+    cpp_path = paths.join(root, toolchain.ghci_cpp_path)
+
+    flags = [
+        "-this-unit-id",
+        "fbcode_fake_unit_id",
+        "-optP-undef",
+        "-optP-traditional-cpp",
+        "-I.",
+        "-no-global-package-db",
+        "-no-user-package-db",
+        "-hide-all-packages",
+        "-pgma%s" % cc_path,
+        "-pgml%s" % cxx_path,
+        "-pgmc%s" % cc_path,
+        "-pgmP%s" % cpp_path,
+        "-opta-B%s" % binutils_path,
+        "-optc-B%s" % binutils_path,
+    ]
+    flags.extend(resolved_attrs.compiler_flags)
+
+    return {
+        "exclude_packages": {hli.lib.get(linkStyle).name: ()} if hli else {},
+        "flags": flags,
+        "generated_dependencies": externalSourcesForTarget(ctx, target),
+        "haskell_deps": haskellLibs,
+        "import_dirs": import_dirs.keys(),
+        "sources": sources,
+        "targets": targetsForTarget(ctx, target),
+    }
+
+def targetsForTarget(ctx, target):
+    buildfile = ctx.cquery().buildfile(target)
+    root = ctx.root()
+    paths = []
+    for b in buildfile:
+        paths.append("%s/%s" % (root, str(b).replace("//", "/")))
+    return paths
+
+def externalSourcesForTarget(ctx, target):
+    deps3 = ctx.cquery().deps(target, 3)
+    thrifts = ctx.cquery().attrfilter("labels", "thrift_library=hs2/compile", deps3)
+    paths = []
+    for thrift in thrifts:
+        paths.extend(thrift.resolved_attrs_lazy(ctx).get("srcs"))
+    return paths
+
+def merge(results):
+    seen_flags = set()
+    flags = []
+    sources = {}
+    haskellDeps = {}
+    import_dirs = {}
+    generated_dependencies = {}
+    targets = {}
+    exclude_packages = {}
+
+    for result in results:
+        for flag in result["flags"]:
+            if not (flag in seen_flags):
+                flags.append(flag)
+                seen_flags.add(flag)
+        for source in result["sources"]:
+            sources[source] = ()
+        for p, v in result["haskell_deps"].items():
+            haskellDeps[p] = v
+        for i in result["import_dirs"]:
+            import_dirs[i] = ()
+        for dep in result["generated_dependencies"]:
+            generated_dependencies[dep] = ()
+        for t in result["targets"]:
+            targets[t] = ()
+        for t in result["exclude_packages"]:
+            exclude_packages[t] = ()
+
+    return {
+        "exclude_packages": exclude_packages,
+        "flags": flags,
+        "generated_dependencies": generated_dependencies.keys(),
+        "haskell_deps": haskellDeps,
+        "import_dirs": import_dirs.keys(),
+        "sources": sources.keys(),
+        "targets": targets.keys(),
+    }
+
+def _assembleSolution(ctx, linkStyle, result):
+    flags = result["flags"]
+    package_dbs = {}
+    for i in result["import_dirs"]:
+        flags.append("-i%s" % i)
+    hlis = {}
+    for provider in result["haskell_deps"].values():
+        info = provider.info.get(linkStyle)
+        if info != None:
+            for item in info.traverse():
+                if result["exclude_packages"].get(item.name) == None:
+                    hlis[item.name] = item
+    for hli in hlis.values():
+        if not (hli.name.startswith("z-")):
+            flags.append("-package")
+            flags.append(hli.name)
+
+        ctx.output.ensure_multiple(hli.stub_dirs)
+        ctx.output.ensure_multiple(hli.libs)
+        ctx.output.ensure_multiple(hli.import_dirs)
+        package_dbs[hli.db] = ()
+    for pkgdb in ctx.output.ensure_multiple(package_dbs.keys()):
+        flags.append("-package-db")
+        flags.append(pkgdb.abs_path())
+
+    external_deps = result["targets"]
+    for s in ctx.output.ensure_multiple(result["generated_dependencies"]):
+        external_deps.append(s.abs_path())
+
+    return {
+        "externalDependencies": external_deps,
+        "flags": result["flags"],
+        "owner": result.get("owner"),
+        "owner_type": result.get("owner_type"),
+        "project": result.get("project"),
+        "project_type": result.get("project_type"),
+        # TODO check for duplicate module names in sources
+        "sources": result["sources"],
+    }
+
+_common_flags = {
+    "bios": cli_args.bool(False, "Output GHC flags and targets separated by newlines"),
+    "project_universe": cli_args.list(cli_args.target_label("list of haskell_ide targets"), []),
+}
+
+ide_for_target = bxl_main(
+    impl = _impl_target,
+    cli_args = dict(
+        _common_flags.items()
+        + {
+            "target": cli_args.target_label(),
+        }.items()
+    ),
+)
+
+ide_for_file = bxl_main(
+    impl = _impl_file,
+    cli_args = dict(
+        _common_flags.items()
+        + {
+            "file": cli_args.string("File to load in IDE"),
+        }.items()
+    ),
+)
diff --git a/buck2/prelude/haskell/library_info.bzl b/buck2/prelude/haskell/library_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/library_info.bzl
@@ -0,0 +1,110 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+# If the target is a haskell library, the HaskellLibraryProvider
+# contains its HaskellLibraryInfo. (in contrast to a HaskellLinkInfo,
+# which contains the HaskellLibraryInfo for all the transitive
+# dependencies). Direct dependencies are treated differently from
+# indirect dependencies for the purposes of module visibility.
+HaskellLibraryProvider = provider(
+    fields = {
+        "lib": provider_field(typing.Any, default = None),  # dict[LinkStyle, HaskellLibraryInfo]
+        "prof_lib": provider_field(typing.Any, default = None),  # dict[LinkStyle, HaskellLibraryInfo]
+    },
+)
+
+# The files of one module of a library compiled per-module that modules of
+# other targets need when they import it:
+#
+# - hi: the module's interface.
+# - abi: a file containing just the interface's ABI hash, which is what the
+#   importers' dep files refer to (see Note [Early cut-off by dep files] in
+#   compile_per_module.bzl).
+# - dyn_hi: the module's dynamic interface, if it was compiled with
+#   -dynamic-too, and None otherwise.
+HaskellModuleFiles = record(
+    hi = field(Artifact),
+    abi = field(Artifact),
+    dyn_hi = field(Artifact | None, None),
+)
+
+# A record of a Haskell library.
+HaskellLibraryInfo = record(
+    # The library target name: e.g. "rts"
+    name = str,
+    # package config database: e.g. platform009/build/ghc/lib/package.conf.d
+    db = Artifact,
+    # e.g. "base-4.13.0.0"
+    id = str,
+    # The directories that hold the library's interfaces, and those of its
+    # splice variant (see Note [Link styles and profiling] in haskell.bzl).
+    import_dirs = list[Artifact],
+    stub_dirs = list[Artifact],
+    # This field is only used as hidden inputs to compilation, to
+    # support Template Haskell which may need access to the libraries
+    # at compile time.  The real library flags are propagated up the
+    # dependency graph via MergedLinkInfo.
+    libs = field(list[Artifact], []),
+    # Package version, used to specify the full package when exposing it,
+    # e.g. filepath-1.4.2.1, deepseq-1.4.4.0.
+    # Internal packages default to 1.0.0, e.g. `fbcode-dsi-logger-hs-types-1.0.0`.
+    version = str,
+    is_prebuilt = bool,
+    profiling_enabled = bool,
+    # A package db for this library that doesn't name its library file.
+    # Per-module compiles of the library's dependents use this db instead of
+    # `db`. It is None for a prebuilt library, whose normal db is used.
+    #
+    # - For a library compiled per-module, this is its "early" db. It is
+    #   registered before any of the library's modules are compiled, so that
+    #   a dependent's module can start compiling as soon as the particular
+    #   modules it imports are done (see Note [Compiling against dependencies
+    #   module by module] in compile_per_module.bzl).
+    # - For a library built with --make, it is its "library-less" db: the
+    #   normal package, but without the library file. A dependent's compile
+    #   then waits for the library's interfaces but not for the library to be
+    #   linked, and a Template Haskell splice in it can't load the library's
+    #   code (see Note [Template Haskell modules] in compile_per_module.bzl).
+    early_db = field(Artifact | None, None),
+    # see Note [Compiling against dependencies module by module]
+    # in compile_per_module.bzl.
+    below = field(TransitiveSet | None, None),
+    # The data dirs that the library's own Paths_<pkg> modules read, keyed by
+    # environment variable. A splice that runs the library's code can only
+    # read these (see Note [Data files of splices] in compile_per_module.bzl).
+    data_dirs = field(dict[str, Artifact], {}),
+    # The remaining fields are only set for a library compiled per-module.
+    #
+    # The files of each of the library's modules and boot files, keyed by
+    # node name: the module's name, or "<module>-boot" for a boot file.
+    modules = field(dict[str, HaskellModuleFiles] | None, None),
+    # For each module, the interface files of the module itself and of
+    # everything it imports, directly or indirectly, from libraries compiled
+    # per-module. A dependent's module uses these to depend on exactly the
+    # interfaces it needs. This is a DynamicValue, because a library's
+    # imports are only known once its dependency analysis has run. Its
+    # PerModuleClosures provider (see compile_per_module.bzl) maps each
+    # module to its closure set.
+    closures = field(typing.Any, None),
+    # True for the package of an RTS that the project provides, in place of
+    # the RTS of the compiler's own package database. GHC links the RTS
+    # itself, because it chooses the RTS's library from the way that it
+    # links (threaded or debug, say). So an executable that depends on this
+    # package passes -package-id for it, and the package's link info must
+    # not give the RTS's libraries to the link. GHC adds those way tags only
+    # to the RTS's libraries, which is why this is only for the RTS.
+    #
+    # The link reads only this package's `db`, so that database must also
+    # have the packages that the RTS depends on (libffi-clib, say).
+    # Otherwise GHC would ignore the RTS because its dependencies are
+    # missing.
+    is_rts = field(bool, False),
+)
+
+HaskellLibraryInfoTSet = transitive_set()
diff --git a/buck2/prelude/haskell/link_info.bzl b/buck2/prelude/haskell/link_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/link_info.bzl
@@ -0,0 +1,47 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",
+)
+load(
+    "@prelude//haskell:library_info.bzl",
+    "HaskellLibraryInfoTSet",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkStyle",
+)
+
+# A list of `HaskellLibraryInfo`s.
+HaskellLinkInfo = provider(
+    # Contains a list of HaskellLibraryInfo records.
+    fields = {
+        "info": provider_field(dict[LinkStyle, HaskellLibraryInfoTSet]),
+        "prof_info": provider_field(dict[LinkStyle, HaskellLibraryInfoTSet]),
+    },
+)
+
+# HaskellProfLinkInfo exposes the MergedLinkInfo of a target and all of its
+# dependencies built for profiling. This allows top-level targets (e.g.
+# `haskell_binary`) to be defined with profiling enabled by default.
+HaskellProfLinkInfo = provider(
+    fields = {
+        "prof_infos": provider_field(typing.Any, default = None),  # MergedLinkInfo
+    },
+)
+
+def cxx_toolchain_link_style(ctx: AnalysisContext) -> LinkStyle:
+    return ctx.attrs._cxx_toolchain[CxxToolchainInfo].linker_info.link_style
+
+def attr_link_style(ctx: AnalysisContext) -> LinkStyle:
+    if ctx.attrs.link_style != None:
+        return LinkStyle(ctx.attrs.link_style)
+    else:
+        return cxx_toolchain_link_style(ctx)
diff --git a/buck2/prelude/haskell/per_module_worker.bzl b/buck2/prelude/haskell/per_module_worker.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/per_module_worker.bzl
@@ -0,0 +1,164 @@
+# The Haskell toolchain's `per_module_worker` says whether the modules of
+# per-module targets are compiled in the persistent worker, and the
+# buckconfig setting `[haskell] per_module_worker` sets it for the standard
+# toolchain (toolchains/defaults.bzl). It can be:
+#
+# - "builtin", the default. The toolchain builds the worker from its
+#   sources in prelude/haskell/tools/worker, with the toolchain's own GHC, so
+#   it always matches that GHC. A toolchain can give its own build of the
+#   worker instead, in its `per_module_worker_program` (see below).
+# - "none". There is no worker, and each module is compiled by its own
+#   `ghc -c`.
+#
+# The worker runs GHC's code in-process, so it must be linked with the GHC
+# library of the GHC that compiles the modules. The builtin worker is linked
+# with the `ghc` package installed with the toolchain's GHC. A GHC built from
+# source has no such package: its GHC library is a target of the build. So a
+# toolchain for such a GHC builds the worker itself, as a haskell_binary()
+# with the srcs that per_module_worker_srcs() gives, which depends on that
+# target, and passes it in `per_module_worker_program`. The worker must be
+# linked dynamically if the GHC is, for the reason given at
+# build_per_module_worker below.
+#
+# A toolchain of a project's own can also set HaskellToolchainInfo's
+# per_module_shared_worker itself (see per_module_worker_info in
+# prelude/haskell/toolchain.bzl).
+
+load("@prelude//haskell:ghc_api_tool.bzl", "GHC_API_TOOL_PACKAGES", "build_ghc_api_tool")
+
+# The value of the standard toolchain's `per_module_worker`: "builtin" or
+# "none".
+def toolchain_per_module_worker() -> str:
+    return read_root_config("haskell", "per_module_worker", "") or "builtin"
+
+# Whether the per-module compiles use a worker at all.
+def has_per_module_worker() -> bool:
+    return toolchain_per_module_worker() != "none"
+
+# Build the persistent worker with `compiler`, from `srcs`, the directory
+# that prelude//haskell/tools:worker-srcs makes. It uses only packages that
+# come with GHC.
+#
+# The worker is linked dynamically when the GHC is. A worker compiles
+# modules as that GHC would, so it has to load the code of Template Haskell
+# splices the same way, which depends on how it is itself linked (see the
+# notes on Template Haskell in prelude/haskell/haskell.bzl).
+#
+# The RTS options are the worker's defaults. The toolchain overrides -A and
+# -qn with per_module_worker_rts_options. --disable-delayed-os-memory-return
+# makes the RTS give the memory of dropped sessions back to the OS at once.
+# By default the RTS uses MADV_FREE, and the memory stays counted against
+# the process until the kernel needs it. The worker's cabal package
+# (prelude/haskell/tools/worker), which builds it for its tests and
+# benchmark, has the same options: keep the two in step.
+def build_per_module_worker(actions: AnalysisActions, compiler, compile_env: dict[str, str], srcs: Artifact, dynamic: bool) -> Artifact:
+    return build_ghc_api_tool(
+        actions,
+        "buck2-ghc-worker",
+        compiler,
+        compile_env,
+        [cmd_args("-i", srcs, "/worker/src", delimiter = "")],
+        cmd_args(srcs, "/worker/app/Main.hs", delimiter = ""),
+        PER_MODULE_WORKER_PACKAGES,
+        per_module_worker_link_flags() + (["-dynamic"] if dynamic else []),
+    )
+
+# The packages that the worker uses, all of which come with GHC.
+PER_MODULE_WORKER_PACKAGES = GHC_API_TOOL_PACKAGES + ["stm", "unix"]
+
+# The flags that the worker is linked with, and its default RTS options (see
+# build_per_module_worker).
+def per_module_worker_link_flags() -> list[str]:
+    return ["-threaded", "-rtsopts", "-with-rtsopts=-N -A16m -qn4 --disable-delayed-os-memory-return"]
+
+# The worker's own modules, in prelude//haskell/tools/worker/src.
+_WORKER_MODULES = ["Compat", "Grpc", "Proto", "Session", "Worker"]
+
+# The modules that the worker shares with the tools of the per-module
+# compiles. worker/src has symlinks to them in prelude//haskell/tools/ghc-api.
+_WORKER_SHARED_MODULES = ["Contract", "DepFile", "Imports", "Interface", "Pragmas", "Request"]
+
+def per_module_worker_srcs() -> dict[str, str]:
+    """The `srcs` of a haskell_binary() that builds the worker, keyed by
+    module name. Build it with PER_MODULE_WORKER_PACKAGES and
+    per_module_worker_link_flags()."""
+    srcs = {m: "prelude//haskell/tools:worker/src/{}.hs".format(m) for m in _WORKER_MODULES}
+    srcs.update({m: "prelude//haskell/tools:ghc-api/{}.hs".format(m) for m in _WORKER_SHARED_MODULES})
+    srcs["Main"] = "prelude//haskell/tools:worker/app/Main.hs"
+    return srcs
+
+def per_module_worker_sources() -> list[str]:
+    """The worker's own source files, relative to prelude//haskell/tools."""
+    return ["worker/src/{}.hs".format(m) for m in _WORKER_MODULES] + ["worker/app/Main.hs"]
+
+def check_per_module_worker_sources(found: list[str]):
+    """Fails if a module in `found`, the sources in worker/src, isn't listed
+    in _WORKER_MODULES or _WORKER_SHARED_MODULES. See
+    check_ghc_api_tool_sources in ghc_api_tool.bzl for why the modules are
+    listed."""
+    listed = ["worker/src/{}.hs".format(m) for m in _WORKER_MODULES + _WORKER_SHARED_MODULES]
+    missing = [src for src in found if src not in listed]
+    if missing:
+        fail("add these modules to _WORKER_MODULES or _WORKER_SHARED_MODULES in per_module_worker.bzl: " + ", ".join(missing))
+
+# The RTS options of the shared worker, from `[haskell]
+# per_module_worker_rts_options` in the buckconfig.
+#
+# All the worker's compiles share one heap, and each garbage collection
+# stops all of them. So the default options aim to make collections rare
+# and quick:
+#
+# - -A64m gives a large allocation area, because the process runs many
+#   compiles at once. -n4m splits the area into chunks, so that a
+#   capability that runs out can take a chunk from the others.
+# - -qn8 collects with 8 threads, rather than 4, or the RTS's default of one
+#   for each capability.
+# - -I5 makes the RTS wait for 5 seconds of idleness before a full
+#   collection, rather than 0.3 seconds. A worker is idle for a moment
+#   between requests all the time, and with the RTS's default, each of
+#   those moments cost it a full collection of its heap. On the build of a
+#   test-suite of CircuitHub's monorepo, the default took 5 times the
+#   collection time of -I5, and the build took longer.
+#
+# We measured these with the worker's benchmark (its `project` benchmark at
+# -j8, three runs each; see prelude/haskell/tools/worker/DESIGN.md). With 8
+# collection threads the build took 20.5-22.1s, of which 2.4-2.5s was
+# collection. With 4 threads it took 22.0-23.7s (3.7-3.9s of collection), and
+# with one thread per capability 21.0-21.4s (3.5-3.6s). A larger allocation
+# area means fewer collections, but costs memory: -A128m and -A256m used
+# 1.6-3.8 GB more at peak, with no clear gain in time. Each capability has its
+# own allocation area, kept for the whole build. So with -N, on a machine with
+# many cores, a smaller -A or a -maxN keeps the memory in check.
+def per_module_worker_rts_options() -> list[str]:
+    return (read_root_config("haskell", "per_module_worker_rts_options", "") or "-A64m -n4m -qn8 -I5").split()
+
+# The most sessions that the shared worker keeps at once, counting both the
+# sessions in use and the idle ones, from `[haskell]
+# per_module_worker_sessions` in the buckconfig. If it is unset, the limit
+# is the worker's number of capabilities.
+#
+# If the worker drops a session while the session's target is only partly
+# built, it makes the session again for the target's next module. That is
+# cheap for a one-shot session, because the worker shares the interfaces it
+# has read between all its one-shot sessions. But a --make session (see
+# per_module_worker_session_mode) holds the interfaces that its own target
+# has read, which can be a few hundred MB for a large target, and a new
+# session has to read them all again. So the limit makes little difference
+# to one-shot sessions, and for --make sessions it trades memory for speed.
+# Note [Dropping the idle sessions] in prelude/haskell/tools/worker/src/Worker.hs has
+# the benchmark's figures.
+def per_module_worker_sessions() -> str:
+    return read_root_config("haskell", "per_module_worker_sessions", "")
+
+# The kind of session that the shared worker compiles each target in, from
+# `[haskell] per_module_worker_session_mode` in the buckconfig. It can be:
+#
+# - auto, which is the worker's default when this is unset. Targets without
+#   hs-boot files get one-shot sessions, which share the interfaces they
+#   read. The other targets get sessions in GHC's --make mode.
+# - make. Every target gets a --make session, which reads its interfaces
+#   for itself.
+#
+# See Note [One-shot sessions] in prelude/haskell/tools/worker/src/Session.hs.
+def per_module_worker_session_mode() -> str:
+    return read_root_config("haskell", "per_module_worker_session_mode", "")
diff --git a/buck2/prelude/haskell/toolchain.bzl b/buck2/prelude/haskell/toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/toolchain.bzl
@@ -0,0 +1,138 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+HaskellPlatformInfo = provider(
+    fields = {
+        "name": provider_field(typing.Any, default = None),
+    }
+)
+
+# The shell commands that export the variables of compile_env. The shell
+# evaluates each value when the action runs, rather than buck2 passing it
+# through literally. That way a value such as
+# "$(clang -print-file-name=libclang_rt.asan-x86_64.so)" is worked out on
+# the machine that runs the action. This follows the project's convention
+# of finding tools on $PATH when an action runs, rather than writing
+# absolute paths of the host into .bzl or BUCK files (see `compiler` and
+# `packager` in toolchains/BUCK).
+def compile_env_script(compile_env: dict[str, str]) -> str:
+    return "".join([
+        'export {}="{}"; '.format(name, value)
+        for name, value in compile_env.items()
+    ])
+
+# Run `cmd` after the shell script `script`, such as one made by
+# compile_env_script. The script's positional parameters are `args`
+# followed by `cmd`. The script must shift `args` off, so that what is left
+# is the command to run.
+def in_compile_env(script: str, args: list, cmd: cmd_args) -> cmd_args:
+    if not script:
+        return cmd
+    return cmd_args(["sh", "-c", script + 'exec "$@"', "sh"] + args, cmd)
+
+# Write the libdir of `compiler` to a new file called `name`. The libdir is
+# what `ghc --print-libdir` prints. The per-module tools run GHC's code
+# in-process, and that code reads GHC's settings and package database from
+# the libdir. A toolchain rule calls this and puts the file in the
+# toolchain's `libdir`. That way the compiler runs once per configuration,
+# rather than once for each target.
+def print_libdir(actions: AnalysisActions, name: str, compiler, compile_env: dict[str, str]) -> Artifact:
+    out = actions.declare_output(name)
+    actions.run(
+        # The shell sends its output, and so the compiler's, to the file.
+        in_compile_env(
+            compile_env_script(compile_env) + 'exec > "$1"; shift; ',
+            [out.as_output()],
+            cmd_args(compiler, "--print-libdir"),
+        ),
+        category = "haskell_libdir",
+        identifier = name,
+    )
+    return out
+
+# Make the WorkerInfo for a per-module worker program, `worker`. The worker
+# runs with the toolchain's compile_env set. The other arguments are the
+# worker's settings, which per_module_worker_rts_options,
+# per_module_worker_sessions and per_module_worker_session_mode in
+# prelude/haskell/per_module_worker.bzl describe.
+def per_module_worker_info(worker, compile_env: dict[str, str], rts_options: list[str], sessions: int | None, session_mode: str | None) -> WorkerInfo:
+    cmd = cmd_args(worker, ["+RTS"] + rts_options + ["-RTS"] if rts_options else [])
+    env = {}
+    if sessions != None:
+        env["BUCK2_GHC_WORKER_SESSIONS"] = str(sessions)
+    if session_mode != None:
+        env["BUCK2_GHC_WORKER_SESSION_MODE"] = session_mode
+    return WorkerInfo(
+        exe = in_compile_env(compile_env_script(compile_env), [], cmd),
+        env = env,
+    )
+
+HaskellToolchainInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "compiler": provider_field(typing.Any, default = None),
+        "compiler_flags": provider_field(typing.Any, default = None),
+        "compile_env": provider_field(typing.Any, default = {}),
+        # Environment for the link actions, unlike `compile_env` literally
+        # (not shell-evaluated).
+        "link_env": provider_field(typing.Any, default = {}),
+        "dynamic_ghc": provider_field(bool, default = True),
+        # The version of `compiler`, such as "9.12.2", so that the rules can
+        # use the flags that it supports.
+        "ghc_version": provider_field(str),
+        # A file that holds the libdir of `compiler`, as print_libdir writes
+        # it. Targets that compile per-module need it.
+        "libdir": provider_field(Artifact | None, default = None),
+        # The persistent worker (prelude/haskell/tools/worker) that compiles the
+        # modules of per-module targets, as a WorkerInfo made by
+        # per_module_worker_info. It is None if the toolchain has no worker.
+        # See Note [The persistent worker] in compile_per_module.bzl.
+        "per_module_shared_worker": provider_field(typing.Any, default = None),
+        # How a target is compiled when it doesn't set compile_granularity:
+        # "target" or "module" (see compiles_per_module in
+        # compile_per_module.bzl).
+        "compile_granularity": provider_field(str, default = "target"),
+        # The worker's settings: its RTS options, the most sessions it keeps,
+        # and its session mode.
+        "per_module_worker_rts_options": provider_field(list[str], default = []),
+        "per_module_worker_sessions": provider_field(int | None, default = None),
+        "per_module_worker_session_mode": provider_field(str | None, default = None),
+        "linker": provider_field(typing.Any, default = None),
+        "linker_flags": provider_field(typing.Any, default = None),
+        "haddock": provider_field(typing.Any, default = None),
+        "hsc2hs": provider_field(typing.Any, default = None),
+        "compiler_major_version": provider_field(typing.Any, default = None),
+        "package_name_prefix": provider_field(typing.Any, default = None),
+        "packager": provider_field(typing.Any, default = None),
+        "support_always_use_cache": provider_field(bool, default = False),
+        "use_argsfile": provider_field(typing.Any, default = None),
+        "support_expose_package": provider_field(bool, default = False),
+        "archive_contents": provider_field(typing.Any, default = None),
+        "ghci_script_template": provider_field(typing.Any, default = None),
+        "ghci_iserv_template": provider_field(typing.Any, default = None),
+        "ide_script_template": provider_field(typing.Any, default = None),
+        "ghci_binutils_path": provider_field(typing.Any, default = None),
+        "ghci_lib_path": provider_field(typing.Any, default = None),
+        "ghci_ghc_path": provider_field(typing.Any, default = None),
+        "ghci_iserv_path": provider_field(typing.Any, default = None),
+        "ghci_iserv_prof_path": provider_field(typing.Any, default = None),
+        "ghci_cxx_path": provider_field(typing.Any, default = None),
+        "ghci_cc_path": provider_field(typing.Any, default = None),
+        "ghci_cpp_path": provider_field(typing.Any, default = None),
+        "ghci_packager": provider_field(typing.Any, default = None),
+        "cache_links": provider_field(typing.Any, default = None),
+        "script_template_processor": provider_field(typing.Any, default = None),
+        # The tools of the per-module compiles (see compile_per_module in
+        # compile_per_module.bzl), as RunInfo. They must be linked with the
+        # GHC library of the same version as `compiler`. When they are None,
+        # the rules use the tools of prelude//haskell/tools, which are built
+        # with the toolchain's GHC (see haskell_ghc_api_tool()).
+        "per_module_deps": provider_field(typing.Any, default = None),
+        "per_module_compile": provider_field(typing.Any, default = None),
+    },
+)
diff --git a/buck2/prelude/haskell/tools/BUCK b/buck2/prelude/haskell/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/BUCK
@@ -0,0 +1,69 @@
+load("@prelude//haskell:ghc_api_tool.bzl", "GHC_API_TOOLS", "check_ghc_api_tool_sources", "ghc_api_tool_sources", "haskell_ghc_api_tool")
+load("@prelude//haskell:per_module_worker.bzl", "check_per_module_worker_sources", "per_module_worker_sources")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "script_template_processor",
+    main = "script_template_processor.py",
+    visibility = ["PUBLIC"],
+)
+
+# The tools of the per-module compiles (see compile_per_module in
+# prelude/haskell/compile_per_module.bzl), built with the toolchain's GHC.
+[
+    haskell_ghc_api_tool(
+        name = name,
+        srcs = ghc_api_tool_sources(),
+        main = main + ".hs",
+        visibility = ["PUBLIC"],
+    )
+    for name, main in GHC_API_TOOLS.items()
+]
+
+check_ghc_api_tool_sources(glob(["ghc-api/*.hs"]))
+
+# The tools' sources, for a toolchain that builds the tools itself (see
+# ghc_api_tool_srcs()).
+[
+    prelude.export_file(
+        name = src,
+        visibility = ["PUBLIC"],
+    )
+    for src in ghc_api_tool_sources()
+]
+
+# The sources of the persistent worker, which a toolchain builds with its own
+# compiler.
+prelude.filegroup(
+    name = "worker-srcs",
+    srcs = glob(["worker/src/*.hs", "worker/app/Main.hs"]),
+    visibility = ["PUBLIC"],
+)
+
+check_per_module_worker_sources(glob(["worker/src/*.hs"]))
+
+# The worker's own sources, for a toolchain that builds the worker itself
+# (see per_module_worker_srcs()). The sources it shares with the tools are
+# exported above.
+[
+    prelude.export_file(
+        name = src,
+        visibility = ["PUBLIC"],
+    )
+    for src in per_module_worker_sources()
+]
+
+# Type checking target for Python tool scripts
+prelude.python_library(
+    name = "scripts-typing",
+    srcs = [
+        "script_template_processor.py",
+    ],
+    typing = True,
+)
diff --git a/buck2/prelude/haskell/tools/ghc-api/Contract.hs b/buck2/prelude/haskell/tools/ghc-api/Contract.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/ghc-api/Contract.hs
@@ -0,0 +1,9 @@
+-- | The version of the request that the rules send, and of the files that
+-- the worker writes back. Each request names the version that the rules use
+-- (_WORKER_CONTRACT in compile_per_module.bzl). A worker or compile tool
+-- that was built from another version of the rules then reports the
+-- mismatch, rather than misreading the request.
+module Contract (contract) where
+
+contract :: String
+contract = "7"
diff --git a/buck2/prelude/haskell/tools/ghc-api/DepFile.hs b/buck2/prelude/haskell/tools/ghc-api/DepFile.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/ghc-api/DepFile.hs
@@ -0,0 +1,77 @@
+-- | Writing the files that the compile tool and the worker produce besides
+-- GHC's own outputs: a module's .abi file, and its buck2 dep file.
+module DepFile (writeDepFiles) where
+
+import Control.Monad (filterM, forM, unless)
+import Data.List (isPrefixOf)
+import qualified Data.Set as Set
+import System.Directory (canonicalizePath, doesFileExist, getCurrentDirectory)
+import System.FilePath (dropExtension, makeRelative, takeDirectory, takeFileName, (<.>), (</>))
+
+import GHC (moduleName, moduleNameString, moduleUnit)
+import GHC.Unit.Module.Deps (Usage (..), dep_direct_mods)
+import GHC.Unit.Module.ModIface (ModIface, mi_deps)
+import GHC.Unit.Types (GenWithIsBoot (..), IsBootInterface (..), unitString)
+import GHC.Utils.Fingerprint (Fingerprint)
+import GHC.Utils.Panic (GhcException (ProgramError), throwGhcExceptionIO)
+
+import Interface (abiHash, directDep, usageFile, usageLoadedModule, usages)
+import Request
+
+-- | Write a compiled module's ABI file and dep file, from its interface. The
+-- ABI file has the interface's ABI hash. The dep file lists the usages GHC
+-- recorded for its own recompilation check: the imported modules, as their
+-- .abi files, and the files a splice loaded. See Note [Early cut-off by dep
+-- files] in compile_per_module.bzl.
+writeDepFiles :: Request -> ModIface -> IO ()
+writeDepFiles r iface = do
+  writeFile (reqAbi r) (show (abiHash iface :: Fingerprint) ++ "\n")
+  cwd <- getCurrentDirectory
+  -- A module that is only imported {-# SOURCE #-} is listed as its boot
+  -- file's .abi-boot.
+  let direct = [(gwib_mod d, gwib_isBoot d) | (_, d) <- map directDep (Set.toList (dep_direct_mods (mi_deps iface)))]
+      ext m = if (m, IsBoot) `elem` direct && (m, NotBoot) `notElem` direct then "abi-boot" else "abi"
+  -- Without usages, the dep file would say the module read nothing, and it
+  -- would never compile again.
+  us <- maybe (throwGhcExceptionIO (ProgramError (modName ++ ": its interface records no usages, so its dep file can't say what it read: don't compile it with -fno-write-if-self-recomp"))) pure (usages iface)
+  -- Only the objects of the modules in this module's closure are inputs of
+  -- the compile, so a splice can't use a module that it reaches only
+  -- through a boot file (see Note [Template Haskell modules] in
+  -- compile_per_module.bzl). GHC might still find such a module's object in
+  -- the output directory, left by an earlier build, or the worker's session
+  -- might already hold the module's code. So we fail the compile if a
+  -- splice loaded such a module either way.
+  outDir <- canonicalizePath (reqOutDir r)
+  loaded <- fmap concat . forM us $ \u -> case usageFile u of
+    Just path -> do
+      ok <- doesFileExist path
+      -- Only the directory is canonicalized. A profiled compile's .dyn_o
+      -- files are links to the non-profiled compile's objects, so following
+      -- the link would take the path out of the output directory.
+      c <- if ok then (</> takeFileName path) <$> canonicalizePath (takeDirectory path) else pure path
+      pure [map (\ch -> if ch == '/' then '.' else ch) (dropExtension (makeRelative outDir c)) | (outDir ++ "/") `isPrefixOf` c]
+    Nothing -> pure [moduleNameString m | Just m <- [usageLoadedModule u]]
+  let reached = [m | m <- loaded, m `notElem` reqLoadable r]
+  unless (null reached) $
+    throwGhcExceptionIO (ProgramError (modName ++ ": a splice ran code of " ++ unwords reached ++ ", which " ++ modName ++ " reaches only through hs-boot files, and per_module doesn't support that: build the target with compile_granularity = \"target\""))
+  entries <- fmap concat . forM us $ \u -> case u of
+    UsageHomeModule{usg_mod_name = m} -> existing [reqOutDir r </> modFile m <.> ext m]
+    _ | Just m <- usageLoadedModule u -> existing [reqOutDir r </> modFile m <.> "abi"]
+    -- Looked up by its unit as well as its name, since a module of another
+    -- unit may have the same name.
+    UsagePackageModule{usg_mod = m} -> firstExisting (concat [[d </> modFile (moduleName m) <.> "abi", d </> modFile (moduleName m) <.> reqHisuf r] | (unit, d) <- reqHidirs r, unit == unitString (moduleUnit m)])
+    _ | Just path <- usageFile u -> do
+      -- Files outside the project (the libraries of GHC's own package db)
+      -- aren't inputs of the action.
+      ok <- doesFileExist path
+      if ok then (\c -> [c | isUnder cwd c]) <$> canonicalizePath path else pure []
+    _ -> pure []
+  self <- if reqBoot r then pure [] else existing [reqOutDir r </> reqModPath r <.> "abi-boot"]
+  rel <- mapM (fmap (makeRelative cwd) . canonicalizePath) (entries ++ self)
+  writeFile (reqDepfile r) (unlines rel)
+  where
+    modName = map (\c -> if c == '/' then '.' else c) (reqModPath r)
+    modFile = map (\c -> if c == '.' then '/' else c) . moduleNameString
+    existing = filterM doesFileExist
+    firstExisting = fmap (take 1) . existing
+    isUnder cwd p = (cwd ++ "/") `isPrefixOf` p
diff --git a/buck2/prelude/haskell/tools/ghc-api/Imports.hs b/buck2/prelude/haskell/tools/ghc-api/Imports.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/ghc-api/Imports.hs
@@ -0,0 +1,90 @@
+{-# LANGUAGE CPP #-}
+-- | A module summary's imports, wherever each GHC version (9.6 to 10.1)
+-- keeps them.
+module Imports (Import, ordinaryImports, textualImports, sourceImports, importName, importLocated, spliceImport, findImport, findModuleByName) where
+
+import GHC (GenLocated (..), Located, ModSummary, ModuleName, PkgQual (..))
+import GHC.Driver.Env (HscEnv)
+import GHC.Unit.Finder (FindResult, findImportedModule)
+import GHC.Unit.Module.ModSummary (ModSummary (ms_textual_imps), ms_imps, ms_srcimps)
+#if MIN_VERSION_ghc(9,14,0)
+import GHC.Types.Basic (ImportLevel (..))
+#endif
+#if MIN_VERSION_ghc(10,1,0)
+import GHC.Unit.Finder (resolveImport)
+import GHC.Types.UnresolvedImport (UnresolvedImport (..))
+import GHC.Unit.Types (IsBootInterface (..), ModuleLookupScope (..))
+#endif
+
+-- | An import of a module summary. GHC 9.14 added an import level to each
+-- import, which only spliceImport reads.
+#if MIN_VERSION_ghc(10,1,0)
+type Import = UnresolvedImport PkgQual
+#elif MIN_VERSION_ghc(9,14,0)
+type Import = (ImportLevel, PkgQual, Located ModuleName)
+#else
+type Import = (PkgQual, Located ModuleName)
+#endif
+
+-- | The module's imports that aren't {-# SOURCE #-} imports, including
+-- those of its plugins.
+ordinaryImports :: ModSummary -> [Import]
+
+-- | The module's own imports that aren't {-# SOURCE #-} imports, without
+-- those of its plugins.
+textualImports :: ModSummary -> [Import]
+
+-- | The module names of the module's {-# SOURCE #-} imports.
+sourceImports :: ModSummary -> [ModuleName]
+
+-- | An import's module name, and the package that it names (with
+-- PackageImports), if any.
+importName :: Import -> (ModuleName, PkgQual)
+
+-- | An import's module name, with its source location.
+importLocated :: Import -> Located ModuleName
+
+-- | Whether an import is at the splice level (`import splice`). An import
+-- before GHC 9.14, which added levels, never is.
+spliceImport :: Import -> Bool
+
+-- | Find the module that an import names, as GHC does when it compiles the
+-- module. Since GHC 10.1, the lookup depends on where the import comes
+-- from: GHC's implicit import of GHC.Essentials may name a hidden module,
+-- for example.
+findImport :: HscEnv -> Import -> IO FindResult
+
+-- | Find a module by its name alone, as a user's import that names no
+-- package would.
+findModuleByName :: HscEnv -> ModuleName -> IO FindResult
+
+#if MIN_VERSION_ghc(10,1,0)
+-- Since GHC 10.1, ms_imps has the {-# SOURCE #-} imports too.
+ordinaryImports = filter ((== NotBoot) . ui_boot) . ms_imps
+textualImports = filter ((== NotBoot) . ui_boot) . ms_textual_imps
+sourceImports ms = [mn | UnresolvedImport{ui_mod_name = L _ mn} <- ms_srcimps ms]
+importName i = let L _ mn = ui_mod_name i in (mn, ui_pkg_qual i)
+importLocated = ui_mod_name
+spliceImport = (== SpliceLevel) . ui_level
+findImport = resolveImport
+findModuleByName hsc mn = findImportedModule hsc LookupUser mn NoPkgQual
+#elif MIN_VERSION_ghc(9,14,0)
+ordinaryImports = ms_imps
+textualImports = ms_textual_imps
+sourceImports ms = [mn | L _ mn <- ms_srcimps ms]
+importName (_, pkg, L _ mn) = (mn, pkg)
+importLocated (_, _, lmn) = lmn
+spliceImport (level, _, _) = level == SpliceLevel
+#else
+ordinaryImports = ms_imps
+textualImports = ms_textual_imps
+sourceImports ms = [mn | (_, L _ mn) <- ms_srcimps ms]
+importName (pkg, L _ mn) = (mn, pkg)
+importLocated (_, lmn) = lmn
+spliceImport _ = False
+#endif
+
+#if !MIN_VERSION_ghc(10,1,0)
+findImport hsc i = let (mn, pkg) = importName i in findImportedModule hsc mn pkg
+findModuleByName hsc mn = findImportedModule hsc mn NoPkgQual
+#endif
diff --git a/buck2/prelude/haskell/tools/ghc-api/Interface.hs b/buck2/prelude/haskell/tools/ghc-api/Interface.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/ghc-api/Interface.hs
@@ -0,0 +1,84 @@
+{-# LANGUAGE CPP #-}
+-- | Reading a module's interface, and what the rules take from it, wherever
+-- each GHC version (9.6 to 10.1) keeps it.
+module Interface
+  ( readInterface
+  , readInterfaceIn
+  , abiHash
+  , usages
+  , usageFile
+  , usageLoadedModule
+  , directDep
+  ) where
+
+import Control.Monad.IO.Class (liftIO)
+
+import GHC (getSession, runGhc)
+import GHC.Driver.Env (HscEnv, hsc_NC, hsc_dflags)
+import GHC.Driver.Session (targetProfile)
+import GHC.Iface.Binary (CheckHiWay (..), TraceBinIFace (..), readBinIface)
+import GHC.Unit.Module.Deps (Usage (..))
+import GHC.Unit.Module.ModIface (ModIface, mi_usages)
+#if MIN_VERSION_ghc(9,8,0)
+import GHC.Data.FastString (unpackFS)
+#endif
+#if MIN_VERSION_ghc(9,14,0)
+import GHC.Unit.Module.ModIface (mi_mod_hash)
+#else
+import GHC.Unit.Module.ModIface (mi_final_exts, mi_mod_hash)
+#endif
+import GHC.Unit.Module (ModuleName)
+import GHC.Utils.Fingerprint (Fingerprint)
+
+-- | Read the interface file, with GHC's libdir.
+readInterface :: FilePath -> FilePath -> IO ModIface
+readInterface libdir path = runGhc (Just libdir) $ do
+  hsc <- getSession
+  liftIO (readInterfaceIn hsc path)
+
+-- | Read the interface file, with the session's flags and name cache.
+readInterfaceIn :: HscEnv -> FilePath -> IO ModIface
+readInterfaceIn hsc = readBinIface (targetProfile (hsc_dflags hsc)) (hsc_NC hsc) IgnoreHiWay QuietBinIFace
+
+-- | The interface's ABI hash and usages. From GHC 9.14 an interface may
+-- record no usages (-fno-write-if-self-recomp).
+abiHash :: ModIface -> Fingerprint
+usages :: ModIface -> Maybe [Usage]
+#if MIN_VERSION_ghc(9,14,0)
+abiHash = mi_mod_hash
+usages = mi_usages
+#else
+abiHash = mi_mod_hash . mi_final_exts
+usages = Just . mi_usages
+#endif
+
+-- | The file of a usage of a file (from addDependentFile, or a library that a
+-- splice loaded).
+usageFile :: Usage -> Maybe FilePath
+#if MIN_VERSION_ghc(9,8,0)
+usageFile UsageFile{usg_file_path = p} = Just (unpackFS p)
+#else
+usageFile UsageFile{usg_file_path = p} = Just p
+#endif
+usageFile _ = Nothing
+
+-- | The module of a usage that records a home module whose code a splice
+-- loaded into the interpreter. GHC 10.0 renamed the constructor of these
+-- usages from UsageHomeModuleInterface to UsageHomeModuleBytecode.
+usageLoadedModule :: Usage -> Maybe ModuleName
+#if MIN_VERSION_ghc(10,0,0)
+usageLoadedModule UsageHomeModuleBytecode{usg_mod_name = m} = Just m
+#else
+usageLoadedModule UsageHomeModuleInterface{usg_mod_name = m} = Just m
+#endif
+usageLoadedModule _ = Nothing
+
+-- | An interface's direct dependency, without the import level it carries
+-- since GHC 9.14.
+#if MIN_VERSION_ghc(9,14,0)
+directDep :: (a, b, c) -> (b, c)
+directDep (_, uid, m) = (uid, m)
+#else
+directDep :: (b, c) -> (b, c)
+directDep = id
+#endif
diff --git a/buck2/prelude/haskell/tools/ghc-api/Libdir.hs b/buck2/prelude/haskell/tools/ghc-api/Libdir.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/ghc-api/Libdir.hs
@@ -0,0 +1,17 @@
+-- | The libdir of the GHC that compiles the target, which the rules pass to
+-- the tools. The tools run GHC's code in-process, which needs the libdir to
+-- find GHC's settings and package database, and to read the interfaces that
+-- the GHC writes.
+module Libdir (takeLibdir) where
+
+import Data.List (stripPrefix)
+import System.Exit (ExitCode (..), exitWith)
+import System.IO (hPutStrLn, stderr)
+
+-- | Split the first argument, --libdir=DIR, off the arguments, or exit with
+-- an error, naming the tool, if it isn't there.
+takeLibdir :: String -> [String] -> IO (FilePath, [String])
+takeLibdir _ (arg : rest) | Just dir <- stripPrefix "--libdir=" arg = pure (dir, rest)
+takeLibdir tool _ = do
+  hPutStrLn stderr (tool ++ ": the first argument must be --libdir=DIR, the libdir of the GHC that compiles the target")
+  exitWith (ExitFailure 2)
diff --git a/buck2/prelude/haskell/tools/ghc-api/PerModuleCompile.hs b/buck2/prelude/haskell/tools/ghc-api/PerModuleCompile.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/ghc-api/PerModuleCompile.hs
@@ -0,0 +1,70 @@
+-- | Compiles one module of a target compiled per-module with `ghc -c`, then
+-- writes the module's .abi file and buck2 dep file from the interface GHC
+-- wrote. It takes the same request as the persistent worker, and writes the
+-- same files (see Request and DepFile, and compile_per_module in
+-- prelude/haskell/compile_per_module.bzl).
+--
+-- It reads the interface with GHC's code, using the libdir that the request
+-- names. This program must be built with the same version of GHC as the
+-- GHC that compiles the module, because only that version can read the
+-- module's interface.
+module Main (main) where
+
+import Control.Exception (SomeException, displayException, fromException, handle, throwIO)
+import Control.Monad (unless, when)
+import qualified Data.ByteString as B
+import System.Directory (createDirectoryIfMissing)
+import System.Environment (getArgs, getEnvironment)
+import System.Exit (ExitCode (..), exitWith)
+import System.FilePath (takeDirectory)
+import System.IO (Handle, IOMode (WriteMode), hPutStrLn, hSetBinaryMode, stderr, withBinaryFile)
+import System.Process (CreateProcess (..), StdStream (..), createProcess, proc, waitForProcess)
+
+import GHC.Utils.Panic (GhcException (..))
+
+import DepFile (writeDepFiles)
+import Interface (readInterface)
+import Request
+
+main :: IO ()
+main = handle failed $ do
+  r <- either (\err -> hPutStrLn stderr ("per_module_compile: " ++ err) >> exitWith (ExitFailure 2)) pure . parseRequest =<< getArgs
+  mapM_ (createDirectoryIfMissing True) (reqMkdirs r)
+  -- GHC's interpreter runs the module's splices in GHC's own process, with
+  -- GHC's environment. So GHC gets the variables of the request's data dirs
+  -- (see Note [Data files of splices] in compile_per_module.bzl).
+  env <- withRequestEnv r <$> getEnvironment
+  (_, _, Just err, p) <- createProcess (proc (reqCompiler r) (reqSessionArgs r ++ reqModuleArgs r)){std_err = CreatePipe, env = Just env}
+  createDirectoryIfMissing True (takeDirectory (reqDiagnostics r))
+  withBinaryFile (reqDiagnostics r) WriteMode (relay err)
+  code <- exitCode <$> waitForProcess p
+  when (code /= 0) $ exitWith (ExitFailure code)
+  case moduleArg "-ohi" r of
+    Just hi -> readInterface (reqLibdir r) hi >>= writeDepFiles r
+    Nothing -> hPutStrLn stderr "per_module_compile: the request names no interface file (-ohi)" >> exitWith (ExitFailure 2)
+
+-- | Copy GHC's diagnostics to stderr as they come, and to the request's
+-- diagnostics file, bytes unchanged.
+relay :: Handle -> Handle -> IO ()
+relay h file = hSetBinaryMode h True >> hSetBinaryMode stderr True >> go
+  where
+    go = do
+      chunk <- B.hGetSome h 65536
+      unless (B.null chunk) (B.hPut stderr chunk >> B.hPut file chunk >> go)
+
+-- | Fail with what went wrong, such as an interface that recorded no usages
+-- (see DepFile), rather than with an uncaught exception.
+failed :: SomeException -> IO ()
+failed e = case fromException e of
+  Just exit -> throwIO (exit :: ExitCode)
+  Nothing -> do
+    hPutStrLn stderr ("per_module_compile: " ++ case fromException e of
+      Just (ProgramError m) -> m
+      _ -> displayException e)
+    exitWith (ExitFailure 1)
+
+-- | A process's exit code, as a shell gives it: 128 plus the signal's number
+-- for a process killed by a signal.
+exitCode :: ExitCode -> Int
+exitCode ExitSuccess = 0
+exitCode (ExitFailure n) = if n < 0 then 128 - n else n
diff --git a/buck2/prelude/haskell/tools/ghc-api/PerModuleDeps.hs b/buck2/prelude/haskell/tools/ghc-api/PerModuleDeps.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/ghc-api/PerModuleDeps.hs
@@ -0,0 +1,261 @@
+{-# LANGUAGE CPP #-}
+-- | The module graph of a target compiled per-module, from GHC's own
+-- dependency analysis of its sources (see compile_per_module in
+-- prelude/haskell/compile_per_module.bzl).
+--
+-- > per_module_deps --libdir=DIR OUT NODE=SOURCE... -- GHC_FLAGS...
+--
+-- Each NODE=SOURCE is one of the target's nodes, as the rules name it, and
+-- its source: a module, or a boot file as "Mod-boot". The GHC flags are the
+-- target's, without the compiler: the analysis is this program's own, with
+-- the GHC code that it is linked with, which is the same version as the GHC
+-- that compiles the target. DIR is that GHC's libdir (see Libdir).
+--
+-- OUT is a JSON object with a member for each node. Each has:
+--
+-- - "imports": the target's nodes that it depends on: its imports, and a
+--   module's own boot file, which GHC checks the module against;
+-- - "external": the modules it imports from other units, as [unit id,
+--   module];
+-- - "th": whether it may run code at compile time: a splice, or an ANN
+--   pragma, which GHC also evaluates with its interpreter;
+-- - "th_reason", if "th" is true: why. "flags" if the target's flags turn
+--   on TemplateHaskell or QuasiQuotes, "module" if the module's own pragmas
+--   do, and "ann" if it has an ANN pragma (or something like one in a
+--   comment);
+-- - "programs": the programs that GHC runs for it and finds on PATH, by
+--   name, such as a preprocessor that -F -pgmF names. A program may come
+--   from the module's OPTIONS_GHC pragma or from the target's flags;
+-- - "splice": the modules it imports at the splice level, if it has explicit
+--   level imports (from GHC 9.14), as [unit id, module], with each unit that
+--   the import comes through (see throughUnits). The member is absent if it
+--   doesn't.
+module Main (main) where
+
+import Control.Monad (forM, unless)
+import Control.Monad.IO.Class (liftIO)
+import Data.Char (isSpace, ord, toLower)
+import Data.List (intercalate, isPrefixOf, isSuffixOf, nub, tails)
+import qualified Data.Map as M
+import Data.Maybe (isJust, mapMaybe)
+import System.Environment (getArgs)
+import System.Exit (ExitCode (..), exitWith)
+import System.FilePath (normalise)
+import System.IO (hPutStrLn, stderr)
+import Text.Printf (printf)
+
+import GHC
+import GHC.Data.StringBuffer (StringBuffer (..), hGetStringBuffer, lexemeToString)
+import GHC.Driver.Env (hsc_dflags, hsc_home_unit, hsc_units)
+import GHC.Driver.Ppr (showSDoc)
+import GHC.Driver.Session (defaultFatalMessager, defaultFlushOut, parseDynamicFilePragma, pgm_F, pgm_L, pgm_P, pgm_a, pgm_c, pgm_i, pgm_lc, pgm_lo, xopt)
+import GHC.Iface.Errors (cannotFindModule)
+import qualified GHC.LanguageExtensions as LangExt
+import GHC.Unit.Finder (FindResult (..))
+import GHC.Unit.Home (homeUnitId)
+import GHC.Unit.Info (unitId)
+import GHC.Unit.State (LookupResult (..), ModuleOrigin (..), lookupModuleWithSuggestions)
+import GHC.Unit.Module.ModSummary (isBootSummary)
+import GHC.Unit.Types (unitIdString, unitString)
+#if MIN_VERSION_ghc(10,1,0)
+import GHC.Unit.Types (ModuleLookupScope (LookupUser))
+#endif
+import GHC.Utils.Outputable (ppr)
+#if MIN_VERSION_ghc(9,8,0)
+import GHC.Driver.Config.Diagnostic (initIfaceMessageOpts)
+import GHC.Iface.Errors.Ppr (missingInterfaceErrorDiagnostic)
+#endif
+
+import Pragmas (optionsPragmas)
+import Imports (findImport, importLocated, importName, ordinaryImports, sourceImports, spliceImport, textualImports)
+import Libdir (takeLibdir)
+import Request (withoutRts)
+
+main :: IO ()
+main = do
+  (libdir, args) <- takeLibdir "per_module_deps" =<< getArgs
+  case break (== "--") args of
+    (out : nodes, _ : flags) | Just sources <- mapM node nodes -> writeFile out =<< analyse libdir sources (withoutRts flags)
+    _ -> hPutStrLn stderr "usage: per_module_deps --libdir=DIR OUT NODE=SOURCE... -- GHC_FLAGS..." >> exitWith (ExitFailure 2)
+  where
+    node arg = case break (== '=') arg of
+      (n, '=' : src) -> Just (n, src)
+      _ -> Nothing
+
+analyse :: FilePath -> [(String, FilePath)] -> [String] -> IO String
+analyse libdir sources flags = defaultErrorHandler defaultFatalMessager defaultFlushOut $ runGhc (Just libdir) $
+  handleSourceError (\e -> printException e >> liftIO (exitWith (ExitFailure 1))) $ do
+    dflags0 <- getSessionDynFlags
+    logger <- getLogger
+    (dflags, leftover, _) <- parseDynamicFlags logger dflags0 (map noLoc flags)
+    unless (null leftover) . liftIO $ do
+      hPutStrLn stderr ("per_module_deps: not GHC flags: " ++ unwords (map unLoc leftover))
+      exitWith (ExitFailure 2)
+    -- In GHC's mode for `ghc -M`, the finder takes a dependency's module to
+    -- be in its package's only import directory without looking: in an
+    -- early package db, the interface isn't there yet.
+    _ <- setSessionDynFlags dflags{ghcMode = MkDepend}
+    unit <- homeUnitId . hsc_home_unit <$> getSession
+    -- The boot files aren't targets: GHC finds them next to their modules,
+    -- from the {-# SOURCE #-} imports.
+    setTargets =<< mapM (\(_, src) -> guessTarget src (Just unit) Nothing) [s | s@(_, src) <- sources, not ("-boot" `isSuffixOf` src)]
+    summaries <- mgModSummaries <$> depanal [] False
+    hsc <- getSession
+    let byPath = M.fromList [(normalise src, n) | (n, src) <- sources]
+    named <- liftIO . forM summaries $ \ms -> case ml_hs_file (ms_location ms) >>= \src -> M.lookup (normalise src) byPath of
+      Just n -> pure (n, ms)
+      Nothing -> do
+        hPutStrLn stderr ("per_module_deps: GHC's dependency analysis found " ++ moduleNameString (ms_mod_name ms) ++ " in " ++ maybe "no file" id (ml_hs_file (ms_location ms)) ++ ", which isn't one of the target's sources")
+        exitWith (ExitFailure 1)
+    let isBoot ms = isBootSummary ms == IsBoot
+        -- The node of each home module, and of its boot file.
+        nodeOf = M.fromList [(ms_mod_name ms, n) | (n, ms) <- named, not (isBoot ms)]
+        bootOf = M.fromList [(ms_mod_name ms, n) | (n, ms) <- named, isBoot ms]
+        -- An import that names another package (PackageImports) isn't of a
+        -- home module, even if a home module has the same name.
+        home mn pkg = case pkg of
+          OtherPkg _ -> Nothing
+          _ -> M.lookup mn nodeOf
+    nodes <- liftIO . forM named $ \(n, ms) -> do
+      let imports = ordinaryImports ms
+          opts = ms_hspp_opts ms
+          own = [b | not (isBoot ms), Just b <- [M.lookup (ms_mod_name ms) bootOf]]
+      external <- forM [i | i <- imports, let (mn, pkg) = importName i, home mn pkg == Nothing] $ \i -> do
+        found <- findImport hsc i
+        case found of
+          Found _ m -> pure (unitString (moduleUnit m), moduleNameString (moduleName m))
+          _ -> notFound hsc (importLocated i) found
+      text <- maybe (readFile (ms_hspp_file ms)) (\b -> pure (lexemeToString b (len b))) (ms_hspp_buf ms)
+      let splices f = xopt LangExt.TemplateHaskell f || xopt LangExt.QuasiQuotes f
+          thReason
+            | isBoot ms = Nothing
+            | splices dflags = Just "flags"
+            | splices opts = Just "module"
+            | hasAnn text = Just "ann"
+            | otherwise = Nothing
+      -- The module's flags are read again from its original source, because
+      -- the module's own flags (ms_hspp_opts) come from the preprocessed
+      -- source. A preprocessor that -F -pgmF names usually writes a module
+      -- without the pragma that named it, so those flags would leave it out.
+      -- GHC reports any error in the pragmas when it compiles the module.
+      sourceFlags <- maybe (pure dflags) (withSourcePragmas logger dflags) (ml_hs_file (ms_location ms))
+      splice <-
+        if not (isBoot ms) && explicitLevelImports opts
+          then fmap (Just . concat) . forM [i | i <- textualImports ms, spliceImport i] $ \i -> do
+            let (mn, pkg) = importName i
+            case home mn pkg of
+              Just _ -> pure [(unitIdString (homeUnitId (hsc_home_unit hsc)), moduleNameString mn)]
+              Nothing -> do
+                found <- findImport hsc i
+                case found of
+                  Found _ m -> pure [(u, moduleNameString mn) | u <- throughUnits hsc mn pkg m]
+                  _ -> notFound hsc (importLocated i) found
+          else pure Nothing
+      pure
+        ( n
+        , nub (mapMaybe (uncurry home . importName) imports ++ mapMaybe (`M.lookup` bootOf) (sourceImports ms) ++ own)
+        , external
+        , thReason
+        , pathPrograms dflags0 sourceFlags
+        , splice
+        )
+    pure (render nodes)
+
+-- | Fail as GHC does when it can't find an imported module, at the import.
+notFound :: HscEnv -> Located ModuleName -> FindResult -> IO a
+notFound hsc (L loc mn) found = do
+  let dflags = hsc_dflags hsc
+#if MIN_VERSION_ghc(9,8,0)
+      doc = missingInterfaceErrorDiagnostic (initIfaceMessageOpts dflags) (cannotFindModule hsc mn found)
+#else
+      doc = cannotFindModule hsc mn found
+#endif
+  hPutStrLn stderr (showSDoc dflags (ppr loc) ++ ": error:\n" ++ unlines (map ("    " ++) (lines (showSDoc dflags doc))))
+  exitWith (ExitFailure 1)
+
+-- | The programs that GHC, compiling a module with the flags @opts@, finds
+-- on PATH. Those are the programs which the flags name without a directory,
+-- and which aren't the ones that GHC runs by default (@base@ has GHC's
+-- defaults). For example, @-F -pgmF hspec-discover@ makes GHC run
+-- hspec-discover from PATH. A toolchain names its programs with their
+-- directories, so they don't count.
+pathPrograms :: DynFlags -> DynFlags -> [String]
+pathPrograms base opts = nub [p opts | p <- programs, p opts /= p base, '/' `notElem` p opts]
+  where
+    programs = [pgm_F, pgm_L, fst . pgm_P, pgm_c, fst . pgm_a, fst . pgm_lo, fst . pgm_lc, pgm_i]
+
+-- | The flags, with those of the OPTIONS_GHC pragmas of the source file
+-- added.
+withSourcePragmas :: Logger -> DynFlags -> FilePath -> IO DynFlags
+#if MIN_VERSION_ghc(9,14,0)
+withSourcePragmas logger dflags src = do
+  buf <- hGetStringBuffer src
+  (flags, _, _) <- parseDynamicFilePragma logger dflags (optionsPragmas dflags buf src)
+  pure flags
+#else
+withSourcePragmas _ dflags src = do
+  buf <- hGetStringBuffer src
+  (flags, _, _) <- parseDynamicFilePragma dflags (optionsPragmas dflags buf src)
+  pure flags
+#endif
+
+-- | The units that an import of the module `m`, found in another unit, comes
+-- through. Those are the units that re-export it (as a Cabal package's
+-- reexported-modules does), and its own unit if that exposes it too. For a
+-- module that nothing re-exports, that is just its own unit.
+throughUnits :: HscEnv -> ModuleName -> PkgQual -> Module -> [String]
+throughUnits hsc mn pkg m = case lookupImport (hsc_units hsc) mn pkg of
+  LookupFound _ (_, origin)
+    | not (null (fromExposedReexport origin)) ->
+        map (unitIdString . unitId) (fromExposedReexport origin) ++ [own | fromOrigUnit origin == Just True]
+  _ -> [own]
+  where
+    own = unitString (moduleUnit m)
+#if MIN_VERSION_ghc(10,1,0)
+    -- The import is one that the module's source has, so it may only name
+    -- a module that the user can import.
+    lookupImport units = lookupModuleWithSuggestions units LookupUser
+#else
+    lookupImport = lookupModuleWithSuggestions
+#endif
+
+-- | Whether a module has explicit level imports, so that the levels of its
+-- imports say what its splices may run (see Note [Explicit level imports]
+-- in compile_per_module.bzl). The test is whether implicit stage
+-- persistence is off, rather than whether ExplicitLevelImports is on.
+-- ExplicitLevelImports turns implicit stage persistence off, but a module
+-- may turn it back on, and then its splices can still run code from its
+-- ordinary imports.
+explicitLevelImports :: DynFlags -> Bool
+#if MIN_VERSION_ghc(9,14,0)
+explicitLevelImports opts = not (xopt LangExt.ImplicitStagePersistence opts)
+#else
+explicitLevelImports _ = False
+#endif
+
+-- | Whether the (preprocessed) source has an ANN pragma, whose name, like
+-- any pragma's, may be in any case.
+hasAnn :: String -> Bool
+hasAnn text = or [isAnn (dropWhile isSpace (drop 3 t)) | t <- tails text, "{-#" `isPrefixOf` t]
+  where
+    isAnn s = map toLower (take 3 s) == "ann" && all isSpace (take 1 (drop 3 s))
+
+render :: [(String, [String], [(String, String)], Maybe String, [String], Maybe [(String, String)])] -> String
+render nodes = "{" ++ intercalate ",\n" (map node nodes) ++ "}\n"
+  where
+    node (n, imports, external, thReason, programs, splice) =
+      str n ++ ": {"
+        ++ intercalate ", "
+          ( ["\"imports\": " ++ list (map str imports), "\"external\": " ++ list [list [str u, str m] | (u, m) <- external], "\"th\": " ++ bool (isJust thReason)]
+              ++ ["\"th_reason\": " ++ str r | Just r <- [thReason]]
+              ++ ["\"programs\": " ++ list (map str programs)]
+              ++ ["\"splice\": " ++ list [list [str u, str m] | (u, m) <- sp] | Just sp <- [splice]]
+          )
+        ++ "}"
+    bool b = if b then "true" else "false"
+    list xs = "[" ++ intercalate ", " xs ++ "]"
+    str s = "\"" ++ concatMap char s ++ "\""
+    char c
+      | c == '"' || c == '\\' = ['\\', c]
+      | ord c < 0x20 = printf "\\u%04x" (ord c)
+      | otherwise = [c]
diff --git a/buck2/prelude/haskell/tools/ghc-api/Pragmas.hs b/buck2/prelude/haskell/tools/ghc-api/Pragmas.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/ghc-api/Pragmas.hs
@@ -0,0 +1,28 @@
+{-# LANGUAGE CPP #-}
+-- | The flags that a module's OPTIONS_GHC and LANGUAGE pragmas give.
+module Pragmas (optionsPragmas) where
+
+import GHC (DynFlags, Located)
+import GHC.Data.StringBuffer (StringBuffer)
+import GHC.Driver.Config.Parser (initParserOpts)
+import GHC.Parser.Header (getOptions)
+#if MIN_VERSION_ghc(9,14,0)
+import GHC.Driver.Config.Parser (supportedLanguagePragmas)
+#endif
+#if MIN_VERSION_ghc(10,0,0)
+import GHC.Types.SourceError (initSourceErrorContext)
+#endif
+
+-- | Read the flags that the OPTIONS_GHC and LANGUAGE pragmas at the head of
+-- a module's source give, parsing the source with the given flags. The file
+-- name is only used in GHC's messages. (From GHC 9.14, the parser also needs
+-- the list of supported extensions, and from GHC 10.0 the context in which
+-- to report errors.)
+optionsPragmas :: DynFlags -> StringBuffer -> FilePath -> [Located String]
+#if MIN_VERSION_ghc(10,0,0)
+optionsPragmas dflags buf file = snd (getOptions (initParserOpts dflags) (initSourceErrorContext dflags) (supportedLanguagePragmas dflags) buf file)
+#elif MIN_VERSION_ghc(9,14,0)
+optionsPragmas dflags buf file = snd (getOptions (initParserOpts dflags) (supportedLanguagePragmas dflags) buf file)
+#else
+optionsPragmas dflags buf file = snd (getOptions (initParserOpts dflags) buf file)
+#endif
diff --git a/buck2/prelude/haskell/tools/ghc-api/Request.hs b/buck2/prelude/haskell/tools/ghc-api/Request.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/ghc-api/Request.hs
@@ -0,0 +1,126 @@
+-- | The request that the rules send to compile each module, and the flags
+-- of the GHC session that compiles it.
+module Request (Request (..), parseRequest, moduleArg, sessionFlags, withRequestEnv, withoutRts) where
+
+import Data.List (isPrefixOf, stripPrefix)
+
+import Contract (contract)
+
+-- | The request to compile one module, which the rules send as the
+-- action's arguments (see Note [The persistent worker] in
+-- compile_per_module.bzl):
+--
+-- > --request --contract V --libdir LIBDIR --depfile DEP --abi ABI
+-- >   --module Foo/Bar --source Foo/Bar.hs --outdir OUT --hisuf SUF [--boot]
+-- >   [--hidir=UNIT=DIR]... [--srcroot=SRCS]... [--mkdir=DIR]...
+-- >   [--data-dir=VAR=DIR]... [--loadable=MODULE]...
+-- >   -- ghc SESSION_FLAGS... -- -c Foo/Bar.hs -o ... -ohi ...
+--
+-- The flags come in two parts: the session flags, which are the same for
+-- every module of the target, and the module's own. The worker compiles the
+-- module in the session, and takes only the outputs from the module's flags:
+-- @-o@, @-ohi@, @-dyno@, @-dynohi@, @-hiedir@ and @-stubdir@. When buck2
+-- doesn't use the worker, the compile tool (PerModuleCompile) takes the same
+-- request.
+--
+-- LIBDIR is the libdir of the GHC that compiles the module. The worker and
+-- the compile tool run GHC's code in-process, and that code reads GHC's
+-- settings and package database from the libdir.
+data Request = Request
+  { reqLibdir :: FilePath
+  , reqDepfile :: FilePath
+  , reqAbi :: FilePath
+  , reqDiagnostics :: FilePath -- where to write the compile's messages, such as warnings
+  , reqModPath :: String -- Foo/Bar
+  , reqSource :: FilePath
+  , reqOutDir :: FilePath -- where every module's outputs are
+  , reqHisuf :: String
+  , reqHidirs :: [(String, FilePath)] -- the dependencies' interface (and .abi) dirs, by unit id
+  , reqSrcRoots :: [FilePath] -- trees of the target's sources, which go on the session's import path
+  , reqMkdirs :: [FilePath] -- output directories to create first
+  , reqDataDirs :: [(String, FilePath)] -- the variables for the module's splices, with the data dirs they name (see Note [Data files of splices] in compile_per_module.bzl)
+  , reqBoot :: Bool -- whether the module is a boot file
+  , reqLoadable :: [String] -- for a module that runs Template Haskell, the target's modules whose objects the compile has, so that its splices may load them (see Note [Template Haskell modules] in compile_per_module.bzl)
+  , reqCompiler :: String
+  , reqSessionArgs :: [String] -- the session flags, which are the same for every module of the target
+  , reqModuleArgs :: [String] -- the module flags: `ghc -c`'s source and output files, -hiedir and -stubdir
+  }
+
+-- | The value that the request's module flags give `flag`, such as the
+-- interface file that @-ohi@ names.
+moduleArg :: String -> Request -> Maybe FilePath
+moduleArg flag r = case dropWhile (/= flag) (reqModuleArgs r) of
+  _ : v : _ -> Just v
+  _ -> Nothing
+
+-- | Parse the request from an action's command line. buck2 sends the whole
+-- command line, so it starts with the program and the program's own
+-- arguments. Those end at the "--request" marker, and are ignored.
+parseRequest :: [String] -> Either String Request
+parseRequest args = case drop 1 (dropWhile (/= "--request") args) of
+  "--contract" : v : rest
+    | v == contract -> go (Request "" "" "" "" "" "" "" "" [] [] [] [] False [] "" [] []) rest
+    | otherwise -> Left ("this program takes version " ++ contract ++ " of the rules' requests, but the rules sent version " ++ v ++ ": build it from the same version of the rules")
+  _ -> Left "the request names no version: build this program from the same version of the rules"
+  where
+    go r ("--libdir" : v : rest) = go r{reqLibdir = v} rest
+    go r ("--depfile" : v : rest) = go r{reqDepfile = v} rest
+    go r ("--abi" : v : rest) = go r{reqAbi = v} rest
+    go r ("--diagnostics" : v : rest) = go r{reqDiagnostics = v} rest
+    go r ("--module" : v : rest) = go r{reqModPath = v} rest
+    go r ("--source" : v : rest) = go r{reqSource = v} rest
+    go r ("--outdir" : v : rest) = go r{reqOutDir = v} rest
+    go r ("--hisuf" : v : rest) = go r{reqHisuf = v} rest
+    go r ("--boot" : rest) = go r{reqBoot = True} rest
+    go r ("--" : compiler : rest)
+      | null (reqLibdir r) = Left "the request names no libdir (--libdir)"
+      | null (reqDiagnostics r) = Left "the request names no diagnostics file (--diagnostics)"
+      | otherwise =
+          let (session, moduleArgs) = break (== "--") rest
+           in Right r{reqCompiler = compiler, reqSessionArgs = session, reqModuleArgs = drop 1 moduleArgs}
+    go r (x : rest)
+      | Just v <- stripPrefix "--hidir=" x, (unit, '=' : d) <- break (== '=') v = go r{reqHidirs = reqHidirs r ++ [(unit, d)]} rest
+      | Just v <- stripPrefix "--srcroot=" x = go r{reqSrcRoots = reqSrcRoots r ++ [v]} rest
+      | Just v <- stripPrefix "--mkdir=" x = go r{reqMkdirs = reqMkdirs r ++ [v]} rest
+      | Just v <- stripPrefix "--loadable=" x = go r{reqLoadable = reqLoadable r ++ [v]} rest
+      | Just v <- stripPrefix "--data-dir=" x, (var, '=' : d) <- break (== '=') v = go r{reqDataDirs = reqDataDirs r ++ [(var, d)]} rest
+      | otherwise = Left ("unexpected request argument " ++ show x)
+    go _ [] = Left "the request has no compiler command"
+
+-- | The flags of the session that compiles the request's module. They are
+-- the request's session flags, without two kinds of flag that only the ghc
+-- program takes:
+--
+-- - options for the ghc program's runtime (@+RTS ... -RTS@), because the
+--   worker has its own runtime;
+-- - @-B@, which tells the ghc program its libdir. A toolchain whose GHC is
+--   built from source passes it as part of the compiler command. The worker
+--   takes the libdir from the request instead (@--libdir@).
+--
+-- To those, this adds:
+--
+-- - @-odir@ and @-hidir@, so that GHC writes each output into the output
+--   directory, at a path made from the module's name. That is where the
+--   rules expect the outputs.
+-- - The trees of the target's sources, on the import path.
+--
+-- Every other flag comes from the rules, so that the worker compiles with
+-- the same flags as the compile tool's @ghc -c@.
+sessionFlags :: Request -> [String]
+sessionFlags r =
+  filter (not . ("-B" `isPrefixOf`)) (withoutRts (reqSessionArgs r))
+    ++ ["-odir", reqOutDir r, "-hidir", reqOutDir r]
+    ++ ["-i" ++ d | d <- reqSrcRoots r]
+
+-- | Add the variables of the request's data dirs to an environment, in place
+-- of any variables with the same names. The request's splices need them.
+withRequestEnv :: Request -> [(String, String)] -> [(String, String)]
+withRequestEnv r env = vars ++ [(k, v) | (k, v) <- env, k `notElem` map fst vars]
+  where
+    vars = reqDataDirs r
+
+-- | GHC's flags without options for its runtime (@+RTS ... -RTS@).
+withoutRts :: [String] -> [String]
+withoutRts args = case break (== "+RTS") args of
+  (ghc, _ : rest) -> ghc ++ withoutRts (drop 1 (dropWhile (/= "-RTS") rest))
+  (ghc, []) -> ghc
diff --git a/buck2/prelude/haskell/tools/script_template_processor.py b/buck2/prelude/haskell/tools/script_template_processor.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/script_template_processor.py
@@ -0,0 +1,218 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+"""
+Helper script to generate scripts required by haskell tools from script
+template files.
+
+These script templates require GHC and/or toolchain values, e.g. GHC flags used,
+paths to cxx tools.
+
+The macros in the script should be in the format `<MACRO_NAME>`.
+For example, `echo <binutils_path>` is an expression that would be replaced.
+"""
+
+import argparse
+import os
+import re
+import sys
+from typing import Dict, List, Optional
+
+# Paths in the toolchain that are passed relative to the project's cell and
+# need to be canonicalized before being replaced in the script.
+TOOLCHAIN_PATHS = [
+    "binutils_path",
+    "ghci_lib_path",
+    "cc_path",
+    "cpp_path",
+    "cxx_path",
+    "ghci_iserv_path",
+    "ghc_pkg_path",
+    "ghc_path",
+]
+
+
+def _replace_template_values(
+    template_file,
+    output_fpath: str,
+    user_ghci_path: Optional[str],
+    rel_toolchain_paths: Dict[str, str],
+    exposed_packages: List[str],
+    package_dbs: Optional[str],
+    prebuilt_package_dbs: Optional[str],
+    string_macros: Dict[str, Optional[str]],
+):
+    script_template = template_file.read()
+
+    for macro_name, rel_path in rel_toolchain_paths.items():
+        # Skip macro if its path wasn't provided for a specific template
+        if not rel_path:
+            continue
+
+        # Follow symlink to get canonical path
+        canonical_path = os.path.realpath(rel_path)
+
+        script_template = re.sub(
+            pattern=f"<{macro_name}>",
+            repl=canonical_path,
+            string=script_template,
+        )
+
+    if user_ghci_path is not None:
+        # user_ghci_path has to be handled separately because it needs to be passed
+        # with the ghci_lib_path as the `-B` argument.
+        ghci_lib_path = rel_toolchain_paths["ghci_lib_path"]
+
+        if ghci_lib_path:
+            ghci_lib_canonical_path = os.path.realpath(ghci_lib_path)
+
+            replacement = "${{DIR}}/{user_ghci_path} -B{ghci_lib_path}".format(
+                user_ghci_path=user_ghci_path,
+                ghci_lib_path=ghci_lib_canonical_path,
+            )
+        else:
+            replacement = "${{DIR}}/{user_ghci_path}".format(
+                user_ghci_path=user_ghci_path,
+            )
+
+        script_template = re.sub(
+            pattern="<user_ghci_path>",
+            repl=replacement,
+            string=script_template,
+        )
+
+    if len(exposed_packages) > 0:
+        script_template = re.sub(
+            pattern="<exposed_packages>",
+            repl=" ".join(exposed_packages),
+            string=script_template,
+        )
+
+    prebuilt_package_dbs_args = None
+    package_dbs_args = None
+
+    if prebuilt_package_dbs is not None:
+        prebuilt_pkgs_canonical_paths = [
+            os.path.realpath(
+                rel_path,
+            )
+            for rel_path in prebuilt_package_dbs.split(" ")
+        ]
+
+        prebuilt_package_dbs_args = " ".join(
+            ["-package-db {}".format(pkg) for pkg in prebuilt_pkgs_canonical_paths]
+        )
+
+    if package_dbs is not None:
+        package_dbs_args = " ".join(
+            ["-package-db ${{DIR}}/{}".format(pkg) for pkg in package_dbs.split(" ")]
+        )
+
+    script_template = re.sub(
+        pattern="<package_dbs>",
+        repl=" ".join(filter(None, [prebuilt_package_dbs_args, package_dbs_args])),
+        string=script_template,
+    )
+
+    # Replace all other macros
+    for macro_name, macro_value in string_macros.items():
+        if macro_value is not None:
+            script_template = re.sub(
+                pattern=f"<{macro_name}>",
+                repl=macro_value,
+                string=script_template,
+            )
+
+    with open(output_fpath, "w") as output_file:
+        output_file.write(script_template)
+
+    os.chmod(output_fpath, 0o777)  # Script should be executable
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser()
+
+    parser.add_argument(
+        "--script_template",
+        type=argparse.FileType("r"),
+    )
+
+    for tpath in TOOLCHAIN_PATHS:
+        parser.add_argument(
+            "--{}".format(tpath),
+        )
+
+    parser.add_argument(
+        "--user_ghci_path",
+    )
+
+    parser.add_argument(
+        "--exposed_packages",
+        type=str,
+        nargs="+",
+    )
+    parser.add_argument(
+        "--output",
+        help="The final script with all macros replaced.",
+    )
+
+    STRING_ARGS = [
+        "package_dbs",
+        "prebuilt_package_dbs",
+        # Name of the buck target being built, e.g. haxlsh
+        "target_name",
+        "start_ghci",
+        # Path to the final iserv script. Used by the final ghci script.
+        "iserv_path",
+        "compiler_flags",
+        "srcs",
+        "preload_libs",
+        "squashed_so",
+    ]
+
+    for str_arg in STRING_ARGS:
+        parser.add_argument(
+            "--{}".format(str_arg),
+            type=str,
+        )
+
+    args = parser.parse_args()
+
+    rel_toolchain_paths = {}
+    for tpath in TOOLCHAIN_PATHS:
+        rel_toolchain_paths[tpath] = getattr(args, tpath)
+
+    # Macros that don't require special handling and are not paths that need
+    # to be canonicalized.
+    string_macros = {
+        "name": args.target_name,
+        "start_ghci": args.start_ghci,
+        "iserv_path": args.iserv_path,
+        "compiler_flags": args.compiler_flags,
+        "srcs": args.srcs,
+        "squashed_so": args.squashed_so,
+        "preload_libs": args.preload_libs,
+    }
+
+    _replace_template_values(
+        args.script_template,
+        args.output,
+        args.user_ghci_path,
+        rel_toolchain_paths,
+        args.exposed_packages,
+        args.package_dbs,
+        args.prebuilt_package_dbs,
+        string_macros,
+    )
+
+    return 0
+
+
+sys.exit(main())
diff --git a/buck2/prelude/haskell/tools/worker/DESIGN.md b/buck2/prelude/haskell/tools/worker/DESIGN.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/DESIGN.md
@@ -0,0 +1,529 @@
+# The design of buck2-ghc-worker
+
+This document explains why the worker is built the way it is, and which
+alternatives we tried or considered. The code explains how it works: start
+with Note [The persistent worker] in `prelude/haskell/compile_per_module.bzl`,
+then Note [How the worker works] in `src/Worker.hs`.
+
+The figures come from the bench (`bench/Main.hs`; see the README), and each
+one gives the options that reproduce it. They were measured on one laptop
+with 8 cores and 16 threads, with GHC 9.12, and with 8 compiles running at
+once unless stated otherwise. Each measurement was run three times, and
+the ranges cover the three runs.
+
+Some choices were based on measurements of a large private codebase. For
+those we give the reason, but no figures, since nobody else can check
+them.
+
+## Goals
+
+We want the worker:
+
+- to be as fast as the machine's memory allows, and to slow down gracefully
+  rather than fail when memory is short;
+- to work with stock GHC, from 9.6 to 9.14, so that it doesn't rely on a
+  patched GHC;
+- to produce exactly what `ghc -c` produces, so that a module's action
+  gives the same result with or without the worker.
+
+## 1. Why a worker
+
+With `compile_granularity = "module"`, the rules compile each module of a target in a
+buck2 action of its own, which runs `ghc -c` on that one module. This gives
+buck2 a finer-grained build graph, but it is slow. Each `ghc -c` repeats
+work that a `ghc --make` for the whole target does only once:
+
+- it starts GHC;
+- it reads the interfaces of everything its module imports;
+- for Template Haskell, it loads the libraries of the target's
+  dependencies.
+
+None of this work leaves anything on disk that a later process could load
+more cheaply. The only way to avoid repeating it is to keep a process
+alive that has already done it. On the bench
+(`cabal bench --benchmark-options='8 3'`), `ghc -c` compares with the
+persistent worker like this:
+
+| workload | `ghc -c` | worker | CPU time of `ghc -c`, as a multiple of the worker's |
+|---|---|---|---|
+| `wide` | 9.5-9.8s | 3.6s | 2.9 |
+| `deep` | 8.8-8.9s | 3.2-3.3s | 3.2 |
+| `th` | 6.4-6.5s | 2.1-2.2s | 3.5-3.7 |
+| `th-heavy` | 7.4-7.5s | 2.2-2.3s | 4.1 |
+| `project` | 98.9-130.2s | 22.2-24.7s | 5.4-6.4 |
+
+The worker comes close to building the whole target with one
+`ghc --make`. On `wide` and `deep`, which are single targets, we ran
+`ghc --make -j8` and the worker alternately, three times each
+(`BENCH_WAYS=make` and `BENCH_WAYS=worker` with
+`--benchmark-options='8 1 wide'`, and likewise for `deep`). Given the
+worker's allocation area (`+RTS -A64m -n4m`, by setting `GHC` to a script
+that adds those options), `ghc --make -j8` took 2.5-3.1s, against the
+worker's 2.7-3.4s. With GHC's default RTS options it took 4.1-5.5s, and
+nearly all of the difference was time spent collecting garbage.
+
+So the worker wins back most of what compiling per-module costs.
+
+### What compiling per-module buys
+
+Compiling per-module gives two things: smaller rebuilds, and more
+parallelism.
+
+#### Rebuilds
+
+After an edit, buck2 runs again every action whose inputs changed. When
+each target is compiled by one `ghc --make`, buck2 runs again:
+
+- the edited module's target, from scratch, since buck2 doesn't keep the
+  target's old outputs for GHC to compare against;
+- each target that depends on a rebuilt target whose interfaces changed,
+  again from scratch. The interfaces change on almost any edit, even to a
+  comment, because an interface records the hash of its source.
+
+When each module is compiled on its own, buck2 compiles again:
+
+- the edited module;
+- each module with an import whose ABI changed. A module's dep file names
+  the ABI hashes of its imports, not their interfaces (see Note [Early
+  cut-off by dep files] in compile_per_module.bzl).
+
+So an edit to a comment compiles one module again, and a new definition
+compiles the edited module and the modules that import it.
+
+How much that saves depends on the module structure. It saves the most for
+an edit low in the module graph, in a large target, or in a target that
+many others depend on. It saves the least for an edit to a small target
+that nothing depends on.
+
+The bench rebuilds after three edits, each made on top of the one before
+(see `edits` in bench/Main.hs). On `project`, with 8 compiles at once, in
+one run on a busy machine (`BENCH_WAYS='make per-target ghc-c worker' cabal
+bench --benchmark-options='8 1 project chain many'`):
+
+| `project`, after | a `ghc --make` per target | one multi-unit `ghc --make -j8` | a `ghc -c` per module | worker |
+|---|---|---|---|---|
+| a comment at the bottom | 3 targets, 5.2s | 1 module, 2.3s | 1 module, 0.8s | 1 module, 0.7s |
+| a new definition at the bottom | 6 targets, 9.1s | 7 modules, 2.4s | 7 modules, 2.5s | 7 modules, 1.1s |
+| a new definition at the top | 1 target, 2.8s | 1 module, 2.2s | 1 module, 1.0s | 1 module, 0.8s |
+
+The results for `chain` and `many` are similar. After each edit, the
+worker took 0.8-1.2s, and a `ghc --make` per target took 2.0-7.6s.
+
+- One multi-unit `ghc --make` compiles the same modules as the per-module
+  builds, but first checks every module to see whether it is up to date,
+  which took about 2s here.
+- On a rebuild, the worker gains little over `ghc -c`. buck2 starts a fresh
+  worker for each build, so on a rebuild that compiles only a few modules,
+  there are few interfaces for the sessions to share. The worker gains
+  more when a rebuild compiles many modules.
+- None of the bench's edits changes the ABI of most of the modules above
+  it. After such an edit, compiling per-module would also compile most of
+  the build again, and gain little.
+
+#### Parallelism
+
+When each module is compiled on its own, it can start as soon as its
+imports are compiled, even those in another target. That only helps when a
+`ghc --make` per target can't keep every core busy. That happens when
+targets depend on each other in a chain, or when the machine has more
+cores than there are targets ready to build.
+
+The bench's `chain` workload is ten targets, each depending on the one
+before (`cabal bench --benchmark-options='8 3 chain'`):
+
+| `chain` | wall | CPU |
+|---|---|---|
+| a `ghc --make` per target | 20.1-21.8s | 20-21s |
+| worker | 5.5-5.9s | 24-26s |
+| one multi-unit `ghc --make -j8`, with `-A64m -n4m` | 3.7-3.9s | 21s |
+
+A `ghc --make` per target can only build one target at a time here, using
+one core.
+
+In `project`, each layer has ten targets, so a `ghc --make` per target
+already keeps 8 cores busy, and the worker is 5-15% slower (see section
+7). More cores would change that. The critical path of a build is the
+least time it could take with unlimited cores. The bench measures it most
+accurately with one compile at a time
+(`BENCH_WAYS='per-target worker' cabal bench --benchmark-options='1 2
+project'`):
+
+| `project`, one compile at a time | wall | critical path |
+|---|---|---|
+| a `ghc --make` per target | 64.6-68.0s | 6.6-7.3s |
+| worker | 50.2-51.4s | 1.4-1.5s |
+
+Dividing the total time by the critical path, a `ghc --make` per target
+could use about ten cores, and a per-module build about 35, if a single
+worker could keep that many busy (see section 7).
+
+## 2. One compile per request
+
+The worker compiles each request in the thread that received it, with
+GHC's `compileOne`, which is the step that `ghc --make -j` runs to compile
+one module. buck2 decides when each module compiles, and the worker just
+runs the compiles it is sent.
+
+We rejected:
+
+- Batching, that is, collecting the requests that arrive close together
+  and compiling each batch with one `--make -j`. This would lose too much
+  of the per-module granularity that we are trying to get, and would add a
+  lot of waiting.
+- A limit on how many compiles the worker runs at once. buck2 already
+  limits how many actions run at once, so there is no point in the worker
+  limiting them too.
+
+## 3. One worker for all targets
+
+We want as few worker processes as possible. Each process has overheads of
+its own, and processes can't share what they have read. So as far as
+possible, all targets share a single worker.
+
+However, a process can't change its environment between requests, so the
+shared worker can't compile a module that needs an environment specific to
+its target. In practice, that means a module that may run one of its
+target's build tools from `PATH`: one that GHC runs a preprocessor for
+(`-F -pgmF`, say), or one that runs Template Haskell, whose splices could
+run anything. The target's other modules don't need its build tools.
+
+Those modules are compiled by a plain `ghc -c` instead. In practice they
+are few: mostly the one module of a test suite that runs a test-discovery
+preprocessor.
+
+We rejected:
+
+- A worker per target. Each process has its own runtime, including an
+  allocation area for each capability, and its own sessions, and buck2
+  keeps it alive until the end of the build. A large project has hundreds
+  of targets.
+- A worker per target, used only for the modules that need the target's
+  environment. A target's modules would then be split between the shared
+  worker and the target's own, so neither worker would see every module of
+  the target. That makes it harder to tell when a target is finished and
+  its sessions can be dropped (see section 4).
+- Sharding: several shared workers, each taking a fixed share of the
+  targets. Each worker's major collections would be cheaper, but in our
+  experiments the total memory grew too fast.
+
+Still open:
+
+- A supervisor, which buck2 would see as one worker, running several
+  workers behind it. Unlike sharding in the rules, the supervisor would see
+  the requests as they arrive. So it could:
+  - place each target on the worker with the fewest active sessions when
+    the target's first request comes, and keep it there;
+  - prefer the worker that already has a target's dependencies, so that
+    fewer interfaces are read twice;
+  - stop sending new targets to a worker whose memory has grown, and
+    restart it once its targets have finished, which frees the interfaces
+    that a worker otherwise never frees (see section 5);
+  - run more workers when memory allows, and only one when it doesn't;
+  - give each worker its own environment.
+
+  On a machine with many cores, this is probably the way to use them. One
+  process keeps only about 6 of 8 cores busy (see section 7), while the
+  module graph has room for far more (see section 1).
+
+## 4. Sessions, and when to drop them
+
+A session is a GHC session that the worker keeps for compiling requests,
+along with the interfaces it has read. The worker keeps one session for
+each set of session flags, that is, the flags that all the modules of a
+target share. A target has one set of session flags for each way it is
+built: static, shared, profiled and so on.
+
+Sessions use most of the worker's memory, so we drop them when we no
+longer need them:
+
+- we drop a target's sessions once the worker has compiled every module of
+  the target;
+- when there are more sessions than a limit (`per_module_worker_sessions`),
+  we drop the idle session that was least recently used.
+
+If a target needs a session after it has been dropped, the worker has to
+make it again. Note [Dropping the idle sessions] in `src/Worker.hs` has
+the details.
+
+With a lower session limit, the worker has to make sessions again more
+often. How much that costs depends on the kind of session (see sections 5
+and 6). A one-shot session is cheap to make again. The interfaces that the
+one-shot sessions share use most of the worker's memory, so the limit
+changes little. A `--make` session has to read its interfaces again, so the
+limit trades memory for speed. On the bench's `project`
+(`BUCK2_GHC_WORKER_SESSIONS=4 cabal bench --benchmark-options='8 3 project'`,
+and likewise for the other limits), where all 30 targets are part-built at
+once:
+
+| limit | one-shot sessions: made, wall, peak | `--make` sessions: made, wall, peak |
+|---|---|---|
+| 4 | 120-124, 21.8-24.7s, 5.1-5.2 GB | 120-122, 38.0-44.6s, 2.4-2.5 GB |
+| 16 (the default on this machine) | 93-95, 22.2-24.7s, 5.2 GB | 91-93, 32.9-40.3s, 5.1-5.5 GB |
+| 32 | 30, 23.1-25.2s, 5.2 GB | 30, 22.5-23.1s, 5.2 GB |
+
+We rejected:
+
+- A timeout. A short timeout drops the session of a target that is waiting
+  for a slow module upstream. A long one keeps nearly every target's
+  sessions.
+- A memory threshold. The runtime only knows the size of the live heap
+  after a major collection, and a dropped session's memory only comes back
+  at the next one. So the worker would overshoot the threshold.
+- No limit, dropping only the sessions of finished targets. buck2 starts
+  any module whose imports are compiled. So a clean build of a large
+  project has well over a hundred targets part-built at once, far more
+  than buck2's `-j`. A session for each of them takes more memory than a
+  laptop has.
+- Keeping the sessions of targets that have requests to come. The worker
+  can't see buck2's queue, so it could only guess which those are.
+- A heap limit (`-M`). That would turn using too much memory into failing
+  partway through the build.
+
+## 5. What the sessions share
+
+All the sessions share:
+
+- one name cache, so that an entity has the same `Name` in every session
+  (Note [One name cache for all the sessions]);
+- one cache of the hashes of the libraries that Template Haskell loads.
+  GHC computes these for every module with splices, and without a shared
+  cache, compiles running at the same time would all miss the cache
+  together (Note [Hashing the libraries]);
+- one copy of each package database, read only once (Note [One copy of
+  each package database]).
+
+These Notes are in `src/Session.hs`.
+
+### Interfaces
+
+Most of what a session reads is interfaces: those of the libraries, and
+those of the target's dependencies. Sharing them saves the most.
+
+GHC has two modes of compiling. `ghc -c` uses one-shot mode, and
+`ghc --make` uses `--make` mode. A session in one-shot mode reads every
+interface it needs into its external package state, GHC's cache of the
+interfaces it has read, including the interfaces of its own target's
+modules. It keeps no home package table, which is where `--make` mode
+keeps the target's own modules. So one-shot sessions can share one
+external package state, as long as their compiles read each interface in
+the same way.
+
+GHC reads an interface using the flags of the compile that reads it,
+including those in the module's OPTIONS_GHC pragmas. So two compiles can
+only share a state if they have the same build configuration and the same
+flags, apart from flags that GHC doesn't consult when it reads an
+interface. Notes [One-shot sessions] and [The flags an interface is read
+with] in `src/Session.hs` have the details.
+
+Sharing makes the difference when the worker drops sessions and makes them
+again. On the bench (`cabal bench --benchmark-options='8 3 project
+many'`; section 4 has `project` with other limits), with the default limit:
+
+| workload | one-shot sessions | `--make` sessions |
+|---|---|---|
+| `project` (93-95 sessions) | 22.2-24.7s | 32.9-40.3s |
+| `many` (323-335 sessions) | 17.7-21.5s | 59.2-78.1s |
+
+With a limit high enough that no session is dropped, the two kinds of
+session take the same time.
+
+This sharing has a cost. GHC typechecks an interface's declarations
+lazily, the first time they are needed. Until a declaration has been
+typechecked, it keeps alive the environment of the compile that read it,
+and with it that session's unit state, which is what GHC knows about the
+packages. So:
+
+- all the sessions made for a target with the same flags share one unit
+  state, so that what the shared state keeps alive grows with the number
+  of targets, not the number of sessions;
+- the shared state itself is never freed, so the worker's memory grows
+  through the build.
+
+We rejected:
+
+- Replacing the shared state with a fresh one from time to time. That made
+  things worse. An old state lives as long as any session that uses it,
+  and the fresh one reads the same interfaces again.
+- Sharing one external package state between `--make` sessions. A target's
+  modules are home modules in the target's own sessions, but external
+  modules in its dependents' sessions. So a shared state would hold them
+  twice, and their instances would overlap. Multi-unit `ghc --make` can
+  share its state only because there, each unit is either home or external
+  for the whole session.
+- Sharing only the libraries' interfaces, in a pool separate from each
+  session's own state. When GHC typechecks a declaration from the pool, it
+  loads the interfaces that the declaration needs into the pool, not into
+  the session. So a session could miss instances.
+- Sharing only the reading of interface files. GHC 9.12 has no hook for
+  it, and decoding interfaces is a small part of a compile.
+
+Still open, as the fallback if one-shot sharing runs into trouble:
+
+- One session with a home unit for each target in the build, as
+  multi-unit `ghc --make` has. That would share interfaces without lazy
+  declarations keeping sessions alive. But a module's interface would then
+  record other targets' modules as home modules, so it would differ from
+  what `ghc -c` produces. And each compile would need the module graphs of
+  its dependencies, which GHC makes from their sources (GHC 9.14 can do
+  without them).
+
+## 6. Boot files
+
+One-shot mode can't compile a target with `.hs-boot` files, because its
+cache has no notion of a boot interface being replaced by the full module.
+Say module A imports B with `{-# SOURCE #-}`, which puts B's boot
+interface in the cache. Then:
+
+- B's own compile sees B's instances twice, once from the boot interface
+  and once from B itself;
+- a later import of B may be given the boot interface instead of the full
+  module.
+
+So a target with boot files gets `--make` sessions. These keep their
+target's interfaces to themselves, and give each compile a home package
+table of its own (Note [The session's state] in `src/Session.hs`).
+
+`per_module_worker_session_mode` chooses between the two kinds of session:
+
+- `auto`, the default, uses one-shot sessions for the targets that can
+  have them, and `--make` sessions for the others;
+- `make` uses `--make` sessions for every target.
+
+The tests run every target in both modes, so that each kind of session is
+tested on every target it can compile.
+
+## 7. Concurrency and garbage collection
+
+All the compiles share one heap, so every collection stops all of them.
+Separate `ghc -c` or `ghc --make` processes each collect their own heap,
+without stopping the others. So the worker's GC settings matter a lot.
+
+The rules' default RTS options for the worker are `-A64m -n4m -qn8 -I5`:
+
+- a large allocation area for each capability, since the process runs many
+  compiles at once;
+- the area split into 4 MB chunks, which a capability that runs out can
+  take from the others;
+- 8 threads for each collection;
+- a full collection only after 5 seconds of idleness (see below).
+
+On the bench's `project`
+(`BUCK2_GHC_WORKER_RTS='-A64m -n4m -qn8' BENCH_WAYS=worker cabal bench
+--benchmark-options='8 3 project'`, and likewise for the other options):
+
+| RTS options | wall | GC | peak |
+|---|---|---|---|
+| `-A64m -n4m -qn4` | 22.0-23.7s | 3.7-3.9s | 5.2-5.3 GB |
+| `-A64m -n4m -qn8`, the default | 20.5-22.1s | 2.4-2.5s | 5.2 GB |
+| `-A32m -n4m -qn8` | 21.3-25.0s | 3.1-3.5s | 5.1-5.5 GB |
+| `-A128m -n4m -qn8` | 20.3-23.4s | 2.3-2.6s | 6.8 GB |
+| `-A256m -n4m -qn8` | 19.6-22.5s | 1.5-2.2s | 7.4-9.0 GB |
+
+Without `-qn`, the RTS uses a GC thread for each of the worker's 16
+capabilities. That took 21.0-21.4s, with 3.5-3.6s of GC, against
+20.0-20.8s, with 2.4s of GC, for `-qn8` in the same runs.
+
+More GC threads make each collection shorter, up to a point. A larger
+allocation area means fewer collections, but costs memory for each
+capability, and its effect on the wall time is within the noise here.
+
+The bench's builds keep the worker busy, so they don't show the cost of the
+RTS's idle collection. By default, the RTS makes a full collection whenever
+the process has been idle for 0.3 seconds (`-I0.3`). That suits an
+interactive program, which waits for its user. A worker waits for buck2's
+next request many times in a build, so each of those waits cost a full
+collection of its heap. On a clean build of a test-suite of CircuitHub's
+monorepo, whose two configurations each had a worker (one run each, so the
+times are rough):
+
+| RTS options, besides `-A64m -n4m -qn8` | wall | GC CPU of the two workers |
+|---|---|---|
+| none (`-I0.3`) | 252s | 259s and 265s |
+| `-I5` | 179s | 41s and 48s |
+| `-I0` (no idle collection) | 166-207s | 39-52s and 46-48s |
+
+Waiting 5 seconds saves as much as turning idle collection off, and still
+collects after a long wait, when the worker may have memory to give back.
+
+`-qi1` with `-qb1`, which would leave capabilities that have been idle out
+of young-generation collections, crashed both workers within a minute, with
+the RTS reporting a corrupted heap. We don't know whether that is a bug of
+the RTS or one that its different timing exposes in the worker.
+
+We rejected the following, because in our measurements each was slower,
+used more memory, or both:
+
+- the non-moving collector;
+- a smaller growth factor (`-F`);
+- compaction;
+- fewer capabilities (`-N` set to the number of physical cores).
+
+### Where the worker falls behind
+
+The worker does less work than separate processes, but keeps fewer cores
+busy. So its lead over a `ghc --make` per target shrinks as more compiles
+run at once. On the bench's `project`
+(`BENCH_WAYS='per-target worker' cabal bench --benchmark-options='N 1
+project'`, one run each):
+
+| compiles at once | `ghc --make` per target | worker |
+|---|---|---|
+| 1 | 67.1s | 53.2s |
+| 2 | 39.0s | 34.3s |
+| 4 | 25.9s | 28.4s |
+| 8 | 19.6s | 20.5s, with 11% less CPU |
+
+With 8 compiles at once, the worker keeps about 6.2-6.4 cores busy, and a
+`ghc --make` per target about 7.4. On a quieter machine, in alternating
+runs with 8 at once, the worker took 14.3-15.2s on `project`, against
+12.6-13.5s for a `ghc --make` per target.
+
+One multi-unit `ghc --make -j8`, with the worker's allocation area, shows
+the best that a single process can do. In the same alternating runs, it
+took 3.7-3.9s on `chain`, against the worker's 5.5-5.8s, and 10.4-11.6s on
+`project`, against 14.3-15.2s. It shares interfaces between targets without needing sessions,
+but its outputs differ from those of `ghc -c` (see section 5).
+
+Besides waiting for collections, the compiles wait for each other inside
+GHC: on thunks that another compile is evaluating, and on locks.
+Multi-unit `ghc --make -j8` has the same limit, so the limit comes from
+running many compiles in one GHC process, not from the worker. It isn't
+caused by the shared name cache: a worker patched to give each session a
+cache of its own was no faster. Several processes (see section 3) would get
+past the limit, at the cost of memory.
+
+## 8. Correctness
+
+Some of the worker's structure is there because a simpler version gave
+wrong results:
+
+- Each compile has a home package table of its own. One shared table,
+  patched for each compile, caused several bugs with boot interfaces (Note
+  [Each compile's home modules]).
+- The worker passes `-fforce-recomp`. Under buck2 it makes no difference,
+  since buck2 removes a module's outputs before compiling it. But without
+  it, outside buck2, GHC could decide that a module is up to date when the
+  inputs of one of its splices have changed (Note [Compiling whenever buck2
+  asks]).
+- The worker refuses flags that affect the whole process. Otherwise, a
+  later session would silently ignore them (Note [Flags of the whole
+  process]).
+- The worker starts the object linker once, itself. Two sessions starting
+  it at the same time could hang (Note [Starting the object linker once]).
+- Each session has a temporary directory of its own. Otherwise, a new
+  library at a path that an old session had used could be mistaken for the
+  old one (Note [A temporary directory per session]).
+
+These Notes are in `src/Session.hs` and `src/Worker.hs`.
+
+## 9. Open questions
+
+- The default session limit is the worker's number of capabilities. A
+  higher limit is faster where memory allows (see section 4), but we
+  haven't settled what the default should be.
+- A memory budget could adapt to the machine better than a fixed limit.
+  The worker would drop sessions, and collect garbage, before its memory
+  reached a set size.
+- buck2 spreads its jobs across every target that can start. It has no way
+  to prefer the targets that are already part-built, which would need
+  fewer sessions.
diff --git a/buck2/prelude/haskell/tools/worker/README.md b/buck2/prelude/haskell/tools/worker/README.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/README.md
@@ -0,0 +1,167 @@
+# buck2-ghc-worker
+
+A [buck2 persistent worker](https://buck2.build/docs/users/advanced/persistent_workers/)
+for the per-module compiles of targets with `compile_granularity = "module"` (see the
+repository README). Without the worker, each module is compiled by a
+`ghc -c` process of its own, which has to start GHC and read the interfaces
+of all the module's imports again. With the worker, buck2 sends the
+compiles to one long-running process that serves many targets. The worker
+compiles each module as its request arrives, concurrently with the others,
+in a GHC session for the module's set of flags. The sessions share the
+interfaces they read, so the worker reads each interface once, however
+many targets import it. buck2 still schedules each module's compile as a
+separate action, and still skips a module whose imports' ABIs haven't
+changed, as it does without the worker.
+
+DESIGN.md explains why the worker is built this way, and which
+alternatives we tried.
+
+## Building
+
+The worker links against the `ghc` library of the GHC that builds it, so it
+has to be built with the same GHC as the project. It uses GHC's API, which
+changes with each major release, so the code has some CPP and quirks for
+particular versions.
+
+The toolchain builds the worker itself, with the project's GHC, from the
+modules in `src` and `app` (some of which are links to modules of the rules'
+GHC-API tools, in `prelude/haskell/tools/ghc-api`). It uses only the packages
+that come with GHC, so building it is a single `ghc` command, which takes a
+few seconds, and an edit to its sources takes effect in the next build. To
+compile without the worker, with a `ghc -c` for each module, set
+`per_module_worker` in the `[haskell]` section of the project's buckconfig
+(`.buckconfig.local`, for example):
+
+```
+[haskell]
+  per_module_worker = none
+```
+
+A project's own toolchain can use a worker built some other way, such as a
+profiled build (see `prelude/haskell/per_module_worker.bzl`). It must be
+built with the project's GHC. Nothing checks that, and a worker built with
+another GHC fails in obscure ways.
+
+This directory's cabal package is for the worker's tests and benchmark,
+which `cabal test` and `cabal bench` run. Only those use packages beyond
+GHC's own: `http2`, `http-types` and `network` for their gRPC client, and
+the test frameworks.
+
+A worker built from a different version of the rules refuses their
+requests, with an error that says so.
+
+## Sessions and memory
+
+buck2 sends the worker as many compiles at once as its `-j` allows,
+counting the other actions it runs, and keeps the worker running until the
+end of the build. The worker keeps a session for each set of flags it has
+seen, and drops sessions so that its memory doesn't grow without bound:
+
+- Once it has compiled all of a target's modules, it drops that target's
+  sessions.
+- While it has more sessions than its limit, it drops the idle session
+  that was least recently used.
+
+If a request comes for a session that was dropped, the worker makes the
+session again. A target with hs-boot files has sessions that don't share
+the interfaces they read, so a new session for it reads them all again.
+
+The worker that the targets share runs with the RTS options in
+`per_module_worker_rts_options`, in the `[haskell]` section of the
+buckconfig. The default is `-A64m -n4m -qn8 -I5`, and
+`prelude/haskell/per_module_worker.bzl` explains why, and what to change on a
+machine with many cores. The worker keeps at most
+`per_module_worker_sessions` sessions, by default as many as it has
+capabilities.
+
+Most of the worker's memory holds the interfaces that its one-shot sessions
+share. That grows with the build rather than with the session limit, so the
+limit makes little difference to memory by default. On a machine that is
+short of memory, `per_module_worker_session_mode = make` with a low limit
+uses less, at the cost of reading interfaces again. On the bench's
+`project`, `make` sessions with a limit of 4 used 2.4-2.5 GB at peak and
+took 38.0-44.6s, against 5.2 GB and 22.2-24.7s with the defaults. Section 4
+of DESIGN.md has the figures.
+
+To see what the worker does, set `BUCK2_GHC_WORKER_VERBOSE=1` in the environment
+of the buck2 daemon. Each worker then logs the time of each compile, and
+the sessions it makes and drops, to its stderr file under
+`/tmp/buck2_worker/`. If its RTS options also include `-T`, it logs its
+peak memory, largest live heap, time spent collecting garbage, and the CPU
+time of its mutator and of its collections when it ends.
+
+## Known issues
+
+Splices run in the worker's own process, in GHC's internal interpreter. So
+the splices of every target in a configuration share the libraries they
+load, and the libraries' global state, and a splice that crashes the
+process fails every compile the worker is running. Note [Template Haskell
+modules] in `compile_per_module.bzl` says what follows from that. A target
+compiled with `-fexternal-interpreter` (in its `compiler_flags`, or the
+toolchain's) runs each session's splices in an external interpreter of its
+own instead.
+
+The worker keeps what it reads for as long as it runs. That is only safe
+because buck2 starts a new worker for each command. The rules' tests check
+that it does.
+
+A few of GHC's flags set state for the whole process, not just for one
+compile. Note [Flags of the whole process] in `src/Session.hs` lists them.
+The worker refuses a target whose flags include one of them, so such a
+target has to be compiled without the worker.
+
+## Testing
+
+`cabal test`, or the `nix flake` checks, run two test suites against the
+built worker:
+
+- `spec` compiles a small package through the worker, sending one request
+  per module as the rules do. It checks the files the worker writes, and
+  the sessions it keeps and drops.
+- `props` generates histories of a small package, with boot files, splices,
+  and a dependency package imported through an early package db. It builds
+  each history again and again through the worker, as buck2 would, using
+  the worker's own dep files to decide what to compile again. After each
+  build it compares every module with a clean build by `ghc -c`. The
+  module must compile in both or fail in both, and have the same ABI hash.
+  From GHC 9.12, whose objects are deterministic, the objects must be the
+  same too. Before 9.12, the hashes of imports that the interfaces record
+  must be the same instead.
+
+## Benchmarking
+
+`cabal bench` builds a few generated workloads (`wide`, `deep`, `th`,
+`th-heavy`, `many`, `project` and `chain`) in several ways:
+
+- through a worker, sending the modules as buck2 would with `-j 8`, once in
+  the worker's default session mode and once with `--make` sessions only;
+- with a `ghc -c` per module, as the rules compile per-module without the
+  worker;
+- with a `ghc --make` per target, as the rules compile with
+  `compile_granularity = "target"`;
+- with one multi-unit `ghc --make -j8` for all the targets.
+
+For each build it prints the wall time, CPU time, peak memory, largest
+live heap and GC time, and the number of sessions the worker made. It also
+prints the critical path, which is the least time the build could take
+with unlimited cores, and, where one process does the whole build, the CPU
+time of its mutator and of its collections.
+
+`many` and `project` have many targets that depend on each other, so that
+many targets are part-built at once, as in a clean build of a large
+project. That is what fills a worker's memory. `chain` is a line of
+targets, each depending on the one before, which a `ghc --make` per target
+has to build one at a time. `bench/Main.hs` describes each workload.
+
+`cabal bench --benchmark-options='N REPETITIONS [WORKLOAD...]'` sets how
+many compiles run at once, how many times each build is repeated, and which
+workloads to run. `GHC_FLAGS` sets the compiles' flags (`-O` by default),
+and the worker's own environment variables, such as
+`BUCK2_GHC_WORKER_SESSIONS`, are passed on to it.
+
+## How the worker works
+
+The code describes how the worker works. Start with Note [The persistent
+worker] in the rules' `prelude/haskell/compile_per_module.bzl`, then Note
+[The session's state] and Note [Each compile's home modules] in
+`src/Session.hs`, and Note [Dropping the idle sessions] in `src/Worker.hs`.
diff --git a/buck2/prelude/haskell/tools/worker/app/Main.hs b/buck2/prelude/haskell/tools/worker/app/Main.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/app/Main.hs
@@ -0,0 +1,92 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+-- | A buck2 persistent worker that compiles the modules of Haskell targets
+-- that are compiled per-module. See Note [How the worker works] in Worker.
+module Main (main) where
+
+import Control.Concurrent (forkIO, threadDelay)
+import Control.Concurrent.MVar
+import Control.Exception (SomeException, catch, displayException, throwIO, try)
+import System.Timeout (timeout)
+import Control.Monad (forever, void, when)
+import qualified Data.ByteString.Char8 as B8
+import System.Environment (lookupEnv)
+import System.Exit (ExitCode (..), exitWith)
+import System.IO (BufferMode (..), hPutStrLn, hSetBuffering, stderr)
+import System.Posix.Process (exitImmediately, getParentProcessID)
+
+import GHC.Utils.Panic (GhcException (..))
+import Grpc (serve)
+import Request (parseRequest)
+import Worker
+
+main :: IO ()
+main = do
+  -- Write each line of stderr whole. stderr is unbuffered by default, which
+  -- writes a line a character at a time, so the lines that concurrent
+  -- compiles log would be interleaved.
+  hSetBuffering stderr LineBuffering
+  socket <- lookupEnv "WORKER_SOCKET"
+  case socket of
+    Nothing -> do
+      hPutStrLn stderr "buck2-ghc-worker: runs as a buck2 persistent worker, with WORKER_SOCKET set; without one, the rules compile with their compile tool (prelude/haskell/tools/ghc-api)"
+      exitWith (ExitFailure 2)
+    Just path -> persistent path
+
+-- Serve requests on the socket at the given path. The worker (see Worker) is
+-- only started when the first request arrives, because it needs to know
+-- which GHC the request names. After that, each request is compiled by the
+-- thread that received it. If the worker can't be started, every request
+-- fails with the reason.
+persistent :: FilePath -> IO ()
+persistent path = do
+  -- buck2 sends its workers SIGTERM when the build is done. But if the
+  -- buck2 daemon is killed during the build, the worker would live on,
+  -- holding its sessions' memory, with nothing left to send it requests. So
+  -- the worker also exits when the process that started it (buck2's
+  -- forkserver) exits, which it notices because its parent process ID
+  -- changes.
+  --
+  -- Either way, `end` shuts the sessions down first, which removes their
+  -- temporary files, and then exits. It exits even if the shutdown throws
+  -- an exception or hangs, hence the `try` and the `timeout`. It exits with
+  -- exitImmediately rather than exitWith, because it may run in the thread
+  -- that watches the parent, where exitWith's exception would only end that
+  -- thread, not the process.
+  worker <- newEmptyMVar
+  let end = do
+        _ <- timeout 5000000 (try (tryReadMVar worker >>= mapM_ (either (const (pure ())) shutdown)) :: IO (Either SomeException ()))
+        exitImmediately ExitSuccess
+  parent <- getParentProcessID
+  void . forkIO . forever $ do
+    threadDelay 1000000
+    p <- getParentProcessID
+    when (p /= parent) end
+  first <- newEmptyMVar
+  let handle argv = case parseRequest (map B8.unpack argv) of
+        Left err -> pure (2, B8.pack ("buck2-ghc-worker: " ++ err ++ "\n"))
+        Right req -> do
+          _ <- tryPutMVar first req
+          w <- readMVar worker
+          case w of
+            Left err -> pure (2, B8.pack (err ++ "\n"))
+            Right wk -> (\(code, err) -> (code, B8.pack err)) <$> compileRequest wk req
+  void . forkIO $ serve path handle `catch` \(e :: SomeException) -> do
+    hPutStrLn stderr ("buck2-ghc-worker: " ++ displayException e)
+    exitImmediately (ExitFailure 1)
+  req <- takeMVar first
+  -- GHC's signal handlers, which withWorker installs, turn buck2's SIGTERM
+  -- (see above) into a 'Signal' exception in this thread.
+  started <- try $ withWorker req (\w -> putMVar worker (Right w) >> forever (threadDelay maxBound)) `catch` \e -> case e of
+    Signal _ -> end
+    _ -> throwIO e
+  case started of
+    Right () -> pure ()
+    Left (e :: SomeException) -> do
+      let err = displayException e
+      hPutStrLn stderr err
+      -- If the worker never started, `worker` is still empty. Filling it
+      -- with the error makes every request fail with that error, and the
+      -- process stays up until buck2 ends it. If the worker had started,
+      -- the exception (an interrupt, for example) ends the process.
+      failed <- tryPutMVar worker (Left err)
+      if failed then forever (threadDelay maxBound) else end
diff --git a/buck2/prelude/haskell/tools/worker/bench/Main.hs b/buck2/prelude/haskell/tools/worker/bench/Main.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/bench/Main.hs
@@ -0,0 +1,567 @@
+-- | A benchmark that builds generated packages in several ways, and reports
+-- the time and memory that each way takes. The ways, as BENCH_WAYS names
+-- them, are:
+--
+-- - make: one `ghc --make -jN` for the whole workload. For a workload of
+--   several targets, this is one multi-unit build, which neither buck2 nor
+--   cabal does. So it shows the best that one GHC process can do, rather
+--   than being a practical alternative.
+-- - per-target: one `ghc --make` per target, as the rules compile a target
+--   without per_module. This is only run for workloads of several targets.
+--   Each target is compiled once the targets it depends on are, at most N
+--   at a time, and without -j, since the rules don't pass one.
+-- - ghc-c: one `ghc -c` per module, as the rules compile per-module without
+--   the worker.
+-- - worker: through the worker, in its default session mode.
+-- - worker-make: through the worker, with --make sessions only.
+--
+-- With ghc-c and the workers, each module is compiled as soon as the
+-- modules it imports have been, whether they are in its own target or
+-- another (early package dbs let the rules do this too). At most N modules
+-- compile at a time, as when buck2 runs the modules' actions with -j N. A
+-- fresh worker gets one request per module, with the arguments the rules
+-- send.
+--
+-- Each way builds the workload from scratch, then again after each of a few
+-- edits (see edits). On each rebuild, it compiles what it would compile in
+-- practice:
+--
+-- - make: whatever GHC's own recompilation check finds out of date.
+-- - per-target: the edited module's target, and each target with a
+--   dependency whose interfaces changed, each from scratch, as buck2 runs
+--   them.
+-- - ghc-c and the workers: the edited module, and each module with an
+--   import whose ABI changed, as buck2 decides from the dep files.
+--
+-- For each build, the bench reports:
+--
+-- - the wall time;
+-- - the CPU time of the worker or GHC processes, and their children;
+-- - where a single process does the build, its peak memory, its largest
+--   live heap and the wall time it spent collecting garbage, from its RTS
+--   statistics. The live heap is only measured at major collections, so it
+--   varies from run to run;
+-- - for the worker, the number of sessions it made;
+-- - for the builds that the bench schedules itself (all but make), the
+--   critical path: the least time the build could take with unlimited
+--   cores (see schedule);
+-- - for make and the workers, the CPU time of the process's mutator and of
+--   its collections.
+--
+-- usage: bench [N] [REPETITIONS] [WORKLOAD...]
+--
+-- N defaults to 8 and REPETITIONS to 1. The worker and GHC are found as in the
+-- test suite (BUCK2_GHC_WORKER, GHC). GHC_FLAGS gives the compiles' flags, -O
+-- by default. BUCK2_GHC_WORKER_RTS gives the worker's RTS options, by default
+-- those that the rules give the shared worker. The worker inherits the bench's
+-- environment, so its own settings, such as BUCK2_GHC_WORKER_SESSIONS, can be
+-- set there. BENCH_WAYS lists the ways to build, by default all of them, in
+-- the order above. The workloads are:
+--
+-- - wide: many modules, none of which imports another.
+-- - deep: layers of modules, each importing every module of the layer
+--   below.
+-- - th: modules with splices that run only template-haskell's code. They
+--   are compiled with -dynamic, because GHC is dynamically linked and so
+--   loads dynamic objects to run a splice.
+-- - th-heavy: th, with a large set of packages exposed, whose libraries
+--   GHC's interpreter loads before it runs any splice.
+-- - many: many targets, in layers, each depending on two targets of the
+--   layer below. Each target is a chain of modules, which import large
+--   interfaces of the ghc package as well as modules of the targets it
+--   depends on. So many targets are part-built at once, as in a clean build
+--   of a large project. This is the workload that tests the worker's
+--   memory.
+-- - project: the same targets as many, but each with a few layers of
+--   several modules rather than a chain, which is more like a project's
+--   libraries.
+-- - chain: ten targets, each depending on the one before, as in a stack of
+--   libraries, and each with layers of a few modules. A `ghc --make` per
+--   target must build them one at a time. But from the target below, a
+--   module only imports the module in the same place there, so per-module
+--   builds of the targets can overlap.
+module Main (main) where
+
+import Control.Concurrent (forkIO)
+import Control.Concurrent.MVar
+import Control.Concurrent.QSem
+import Control.Exception (SomeException, bracket_, finally, try)
+import Control.Monad (forM, forM_, unless, when)
+import qualified Data.ByteString as B
+import Data.IORef
+import Data.List (isInfixOf)
+import qualified Data.Map as M
+import qualified Data.Set as Set
+import Data.Maybe (fromMaybe)
+import GHC.Clock (getMonotonicTime)
+import System.Directory
+import System.Environment (getArgs, lookupEnv)
+import System.Exit (ExitCode (..), exitFailure)
+import System.FilePath ((<.>), (</>))
+import System.IO (BufferMode (..), IOMode (..), hPutStrLn, hSetBuffering, stderr, stdout, withFile)
+import System.Posix.Process (ProcessTimes (..), getProcessID, getProcessTimes)
+import System.Posix.Unistd (SysVar (..), getSysVar)
+import System.Process
+import Text.Printf (printf)
+import Text.Read (readMaybe)
+
+import Client
+import Contract (contract)
+import Interface (abiHash, readInterface)
+
+-- | A generated workload: its targets, and the flags its compiles need
+-- beyond the common ones.
+data Workload = Workload {wName :: String, wTargets :: [Target], wFlags :: [String]}
+
+-- | A target of a workload. tDir is the target's subdirectory of the
+-- workload's directory, which is also its unit id. It is empty for a
+-- workload of one target. tDeps are the targets it depends on. tModules are
+-- its modules, each with its name, the names of the modules it imports
+-- (from any target), and its source.
+data Target = Target {tDir :: FilePath, tDeps :: [FilePath], tModules :: [(String, [String], String)]}
+
+workloads :: [Workload]
+workloads =
+  [ one "wide" [(m i, [], body m i []) | i <- [1 .. 200 :: Int]] []
+  , one "deep" [(l k i, below k, body (l k) i (below k)) | k <- [1 .. 20 :: Int], i <- [1 .. 8]] []
+  , one "th" splicers th
+    -- The same modules, but with the ghc and Cabal packages exposed. The
+    -- interpreter loads the libraries of these and all the packages they
+    -- depend on before it runs any splice.
+  , one "th-heavy" splicers (th ++ ["-package", "ghc", "-package", "Cabal"])
+  , layered "many" "Many" 12 1 tiers
+  , layered "project" "Project" 4 4 tiers
+  , layered "chain" "Chain" 8 2 ([(k, 1) | k <- [1 .. 10]], \k i -> [(k - 1, i) | k > 1])
+  ]
+  where
+    one name modules = Workload name [Target "" [] modules]
+    m i = "W" ++ show i
+    l k i = "L" ++ show k ++ "_" ++ show i
+    s i = "S" ++ show i
+    splicers = [(s i, [], splicing i) | i <- [1 .. 100 :: Int]]
+    th = ["-dynamic", "-package", "template-haskell"]
+    below k = [l (k - 1) j | k > 1, j <- [1 .. 8 :: Int]]
+    -- The splices run only template-haskell's code, because per-module
+    -- compiles can't run code of the build's own modules (see Note
+    -- [Template Haskell modules] in compile_per_module.bzl).
+    splicing i = case lines (body s i []) of
+      header : rest -> unlines (["{-# LANGUAGE TemplateHaskell #-}", header, "import Language.Haskell.TH"] ++ rest ++ ["$(sequence [funD (mkName (\"g\" ++ show k)) [clause [] (normalB (litE (integerL (k * " ++ show i ++ ")))) []] | k <- [1 .. 20 :: Integer]])"])
+      [] -> ""
+    -- Three layers of ten targets. Target i of layer k depends on targets i
+    -- and i + 1 (wrapping around) of the layer below.
+    tiers = ([(k, i) | k <- [1 .. 3], i <- [1 .. 10]], \k i -> [(k - 1, i') | k > 1, i' <- [i, i `mod` 10 + 1 :: Int]])
+    -- A workload of the targets (k, i) in `targets`, where `lower k i` gives
+    -- the targets that (k, i) depends on. Each target has `depth` layers of
+    -- `width` modules. A module imports every module of the layer below it
+    -- in its own target, and the module in the same place in each target
+    -- that its target depends on. So a target's modules can start
+    -- compiling while the targets it depends on are still being compiled.
+    layered name prefix depth width (targets, lower) =
+      Workload name [Target (t k i) (deps k i) [(c k i a b, imports k i a b, heavy (c k i a) b (imports k i a b)) | a <- [1 .. depth], b <- [1 .. width]] | (k, i) <- targets] ["-package", "ghc"]
+      where
+        t :: Int -> Int -> FilePath
+        t k i = name ++ show k ++ "t" ++ show i
+        c :: Int -> Int -> Int -> Int -> String
+        c k i a b = prefix ++ show k ++ "T" ++ show i ++ "L" ++ show a ++ "M" ++ show b
+        deps k i = [t k' i' | (k', i') <- lower k i]
+        imports k i a b = [c k i (a - 1) b' | a > 1, b' <- [1 .. width]] ++ [c k' i' a b | (k', i') <- lower k i]
+    -- A module that uses GHC's API. GHC's interfaces are many and large,
+    -- and every session has to read them, as the sessions of a real project
+    -- read the interfaces of its libraries.
+    heavy name i imports = case lines (body name i imports) of
+      header : rest ->
+        unlines $
+          [header, "import qualified GHC"]
+            ++ rest
+            ++ [ "flags :: GHC.Ghc GHC.DynFlags"
+               , "flags = GHC.getSessionDynFlags"
+               , "modName :: GHC.ModuleName"
+               , "modName = GHC.mkModuleName " ++ show (name i)
+               , "graph :: GHC.Ghc [GHC.ModSummary]"
+               , "graph = GHC.mgModSummaries <$> GHC.getModuleGraph"
+               ]
+      [] -> ""
+
+-- | A module of a realistic size: a data type with derived instances, and
+-- functions over it. Its `total` also uses the `total` of each import.
+body :: (Int -> String) -> Int -> [String] -> String
+body name i imports =
+  unlines $
+    ["module " ++ name i ++ " where", "import qualified Data.Map.Strict as Map"]
+      ++ ["import qualified " ++ d | d <- imports]
+      ++ [ "data T = A Int | B String | C [T] | D (Map.Map Int T) deriving (Show, Eq, Ord)"
+         , "size :: T -> Int"
+         , "size (A n) = n"
+         , "size (B s) = length s"
+         , "size (C ts) = sum (map size ts)"
+         , "size (D m) = Map.foldr (\\t n -> n + size t) 0 m"
+         , "build :: Int -> T"
+         , "build 0 = A " ++ show i
+         , "build n = C [D (Map.fromList [(k, build (n - 1)) | k <- [1 .. 3]]), B (show n)]"
+         , "total :: Int"
+         , "total = size (build 4)" ++ concat [" + " ++ d ++ ".total" | d <- imports]
+         ]
+
+-- | An edit before a rebuild: a label that describes it, the target and
+-- name of the module it changes, and the module's source after the edit and
+-- as generated.
+data Edit = Edit {eLabel :: String, eTarget :: Target, eModule :: String, eSource :: String, eOriginal :: String}
+
+-- | The edits made before the rebuilds. They are made in turn, each on top
+-- of those before:
+--
+-- - A comment in the first module of the first target, which the rest of
+--   the workload builds on. The module's ABI stays the same.
+-- - A new definition in the same module. This changes its ABI, so the
+--   modules that import it compile again, but their own ABIs don't change.
+-- - A new definition in the last module of the last target, which nothing
+--   imports, as with most edits to a project's own code.
+--
+-- The Template Haskell workloads get no edits. Their modules import none of
+-- the others, so an edit would only compile the module it changes.
+edits :: Workload -> [Edit]
+edits w
+  | "template-haskell" `elem` wFlags w = []
+  | otherwise = case (wTargets w, reverse (wTargets w)) of
+      (first : _, final : _)
+        | (bottom, _, bsrc) : _ <- tModules first
+        , (top, _, tsrc) : _ <- reverse (tModules final) ->
+            [ Edit "a comment at the bottom" first bottom (bsrc ++ comment) bsrc
+            , Edit "a new definition at the bottom" first bottom (bsrc ++ comment ++ definition) bsrc
+            , Edit "a new definition at the top" final top (tsrc ++ definition) tsrc
+            ]
+      _ -> []
+  where
+    comment = "-- an edit\n"
+    definition = "edited :: Int\nedited = 1\n"
+
+sourceOf :: Target -> String -> FilePath
+sourceOf t name = tDir t </> "src" </> name <.> "hs"
+
+-- | What a build took.
+data Measure = Measure
+  { mWall :: Double
+  , mCpu :: Double
+  , mPeakMB :: Maybe Double -- the process's peak memory, as its RTS reports it
+  , mLiveMB :: Maybe Double -- its largest live heap at a major collection
+  , mGcS :: Maybe Double -- the wall time it spent collecting garbage
+  , mSessions :: Maybe Int -- the sessions the worker made
+  , mPathS :: Maybe Double -- the critical path (see schedule)
+  , mSplit :: Maybe (Double, Double) -- the CPU time of the process's mutator and GC
+  }
+
+main :: IO ()
+main = do
+  -- Flush each line, so that a run's progress shows up when the output
+  -- goes to a file.
+  hSetBuffering stdout LineBuffering
+  args <- getArgs
+  let (n, reps, names) = case args of
+        a : b : rest | Just x <- readMaybe a, Just y <- readMaybe b -> (x, y, rest)
+        a : rest | Just x <- readMaybe a -> (x, 1, rest)
+        rest -> (8, 1, rest)
+      chosen = [w | w <- workloads, null names || wName w `elem` names]
+  when (null chosen) $ hPutStrLn stderr ("no such workload: " ++ unwords names) >> exitFailure
+  worker <- fromMaybe "buck2-ghc-worker" <$> lookupEnv "BUCK2_GHC_WORKER"
+  ghc <- fromMaybe "ghc" <$> lookupEnv "GHC"
+  flags <- maybe ["-O"] words <$> lookupEnv "GHC_FLAGS"
+  -- The default is the RTS options that the rules give the shared worker (see
+  -- per_module_worker_rts_options in prelude/haskell/per_module_worker.bzl).
+  rts <- maybe ["-A64m", "-n4m", "-qn8", "-I5"] words <$> lookupEnv "BUCK2_GHC_WORKER_RTS"
+  ways <- maybe ["make", "per-target", "ghc-c", "worker", "worker-make"] words <$> lookupEnv "BENCH_WAYS"
+  printf "%-6s %-52s %8s %8s %9s %9s %8s %9s %8s  %s\n" "" "" "wall" "cpu" "peak MB" "live MB" "GC" "sessions" "path" "mut/GC cpu"
+  forM_ chosen $ \w -> forM_ [1 .. reps :: Int] $ \_ -> withWorkload ghc w $ \dir -> do
+    let common = ["-hide-all-packages", "-package", "base", "-package", "containers"] ++ wFlags w ++ flags
+        -- Build from scratch, then rebuild after each edit, the edits
+        -- accumulating. Afterwards, restore the original sources for the
+        -- next way.
+        run way how build what = when (way `elem` ways) $ do
+          clean dir w
+          fst <$> build Nothing >>= report w how
+          forM_ (edits w) $ \e -> do
+            writeFile (dir </> sourceOf (eTarget e) (eModule e)) (eSource e)
+            (m, k) <- build (Just (eModule e))
+            report w ("  after " ++ eLabel e ++ ": " ++ show k ++ " " ++ what) m
+          forM_ (edits w) $ \e -> writeFile (dir </> sourceOf (eTarget e) (eModule e)) (eOriginal e)
+    run "make" ("ghc --make -j" ++ show n) (make dir ghc n common w) "modules"
+    when (length (wTargets w) > 1) $ run "per-target" ("ghc --make per target, " ++ show n ++ " at once") (perTarget dir ghc n common w) "targets"
+    run "ghc-c" ("ghc -c, " ++ show n ++ " at once") (perModule dir ghc n common w) "modules"
+    run "worker" ("worker, " ++ show n ++ " at once") (viaWorker dir worker rts ghc n common [] w) "modules"
+    run "worker-make" ("worker --make, " ++ show n ++ " at once") (viaWorker dir worker rts ghc n common [("BUCK2_GHC_WORKER_SESSION_MODE", "make")] w) "modules"
+  where
+    report w how m =
+      printf "%-6s %-52s %7.1fs %7.1fs %9s %9s %8s %9s %8s  %s\n" (wName w) how (mWall m) (mCpu m) (shown (mPeakMB m)) (shown (mLiveMB m)) (seconds (mGcS m)) (maybe "" show (mSessions m)) (seconds (mPathS m)) (maybe "" (\(a, b) -> printf "%.1fs/%.1fs" a b) (mSplit m) :: String)
+    shown = maybe "" (\x -> show (round x :: Int))
+    seconds = maybe "" (printf "%.1fs") :: Maybe Double -> String
+
+-- | Write the workload's sources to a new temporary directory, and run the
+-- action in it. If the workload has several targets, each one is
+-- registered in the package database db before anything is compiled, with
+-- its output directory as its import directory, as the rules register a
+-- dependency's early package db.
+withWorkload :: String -> Workload -> (FilePath -> IO a) -> IO a
+withWorkload ghc w k = do
+  tmp <- getTemporaryDirectory
+  pid <- getProcessID
+  let dir = tmp </> ("buck2-ghc-worker-bench-" ++ show pid)
+  (setup dir >> k dir) `finally` removePathForcibly dir
+  where
+    setup dir = do
+      removePathForcibly dir
+      createDirectoryIfMissing True (dir </> "tmp")
+      forM_ (wTargets w) $ \t -> do
+        mapM_ (createDirectoryIfMissing True . (dir </>)) [tDir t </> "src", outDir t, tDir t </> "dep"]
+        forM_ (tModules t) $ \(name, _, src) -> writeFile (dir </> tDir t </> "src" </> name <.> "hs") src
+      _ <- readProcess (ghcPkgOf ghc) ["init", dir </> "db"] ""
+      forM_ [t | t <- wTargets w, not (null (tDir t))] $ \t -> do
+        let conf = dir </> tDir t <.> "conf"
+        writeFile conf $
+          unlines
+            [ "name: " ++ tDir t, "version: 0", "id: " ++ tDir t, "key: " ++ tDir t, "exposed: True"
+            , "exposed-modules: " ++ unwords [name | (name, _, _) <- tModules t]
+            , "import-dirs: " ++ dir </> outDir t
+            ]
+        -- --force, because ghc-pkg refuses a package whose interfaces don't
+        -- exist yet.
+        (code, _, err) <- readProcessWithExitCode (ghcPkgOf ghc) ["register", "--force", "--package-db", dir </> "db", conf] ""
+        unless (code == ExitSuccess) $ hPutStrLn stderr err >> exitFailure
+
+-- | Remove every target's outputs and dep files.
+clean :: FilePath -> Workload -> IO ()
+clean dir w = forM_ (wTargets w) $ \t -> forM_ [outDir t, tDir t </> "dep"] $ \d -> do
+  removePathForcibly (dir </> d)
+  createDirectoryIfMissing True (dir </> d)
+
+-- | Run the action, and return its wall time and CPU time with its result.
+-- The CPU time only counts the child processes that the action waits for.
+timed :: IO a -> IO (Double, Double, a)
+timed act = do
+  tick <- fromIntegral <$> getSysVar ClockTick
+  let cpu = (\t -> fromIntegral (fromEnum (childUserTime t) + fromEnum (childSystemTime t)) / tick) <$> getProcessTimes
+  c0 <- cpu
+  t0 <- getMonotonicTime
+  a <- act
+  t1 <- getMonotonicTime
+  c1 <- cpu
+  pure (t1 - t0, c1 - c0, a)
+
+-- | The RTS options that make GHC write its statistics to the given file.
+rtsStats :: FilePath -> [String]
+rtsStats file = ["+RTS", "-t" ++ file, "--machine-readable", "-RTS"]
+
+readRtsSplit :: FilePath -> IO (Maybe (Double, Double))
+readRtsSplit file = do
+  text <- readFile file
+  let stats = fromMaybe [] (readMaybe (unlines (drop 1 (lines text))) :: Maybe [(String, String)])
+      value k = readMaybe =<< lookup k stats :: Maybe Double
+  pure ((,) <$> value "mut_cpu_seconds" <*> value "GC_cpu_seconds")
+
+readWorkerSplit :: FilePath -> IO (Maybe (Double, Double))
+readWorkerSplit file = do
+  ls <- lines <$> readFile file
+  -- Force the whole file, so that it is closed before the next build
+  -- overwrites it.
+  length ls `seq` pure $ case [(m, g) | l <- ls, ["buck2-ghc-worker:", "CPU", "mutator", m, "ms,", "GC", g, "ms"] <- [words l]] of
+    (m, g) : _ -> (,) <$> ms m <*> ms g
+    [] -> Nothing
+  where
+    ms = fmap ((/ 1000) . fromIntegral) . (readMaybe :: String -> Maybe Int)
+
+-- | Read the peak memory and largest live heap, in MB, and the seconds spent
+-- collecting garbage, from the file that 'rtsStats' makes GHC write.
+readRtsStats :: FilePath -> IO (Maybe Double, Maybe Double, Maybe Double)
+readRtsStats file = do
+  text <- readFile file
+  -- The file has GHC's command line on its first line, and then a list of
+  -- named values.
+  let stats = fromMaybe [] (readMaybe (unlines (drop 1 (lines text))) :: Maybe [(String, String)])
+      value k = readMaybe =<< lookup k stats :: Maybe Double
+      mb k = (/ 2 ^ (20 :: Int)) <$> value k
+  pure (mb "max_mem_in_use_bytes", mb "max_live_bytes", value "GC_wall_seconds")
+
+-- | Read from a verbose worker's log the peak memory and largest live heap,
+-- in MB, and the seconds spent collecting garbage, which the worker logs as
+-- it ends if it runs with +RTS -T (see shutdown in Worker). Also count the
+-- sessions it made, from the line it logs for each.
+readWorkerLog :: FilePath -> IO (Maybe Double, Maybe Double, Maybe Double, Int)
+readWorkerLog file = do
+  ls <- lines <$> readFile file
+  let memory = [(peak, live, gc) | l <- ls, ["buck2-ghc-worker:", "peak", "memory", peak, "MB,", "max", "live", live, "MB,", "GC", gc, "ms"] <- [words l]]
+      number = fmap fromIntegral . (readMaybe :: String -> Maybe Int)
+  pure $ case memory of
+    (peak, live, gc) : _ -> (number peak, number live, (/ 1000) <$> number gc, sessions ls)
+    [] -> (Nothing, Nothing, Nothing, sessions ls)
+  where
+    sessions = length . filter ("session for the flags" `isInfixOf`)
+
+-- | Build the workload with one `ghc --make`. After an edit, GHC's own
+-- recompilation check decides what to compile again. Also returns the
+-- number of modules that GHC compiled.
+make :: FilePath -> String -> Int -> [String] -> Workload -> Maybe String -> IO (Measure, Int)
+make dir ghc n common w _ = do
+  let stats = dir </> "make.stats"
+      unit t = ["-no-link", "-i" ++ tDir t </> "src", "-odir", outDir t, "-hidir", outDir t] ++ common ++ concat [["-package-id", d] | d <- tDeps t] ++ [tDir t </> "src" </> name <.> "hs" | (name, _, _) <- tModules t]
+  targets <- case wTargets w of
+    [t] -> pure (unit t)
+    ts -> forM ts $ \t -> do
+      let file = dir </> tDir t <.> "unit"
+      writeFile file (unwords (["-this-unit-id", tDir t] ++ unit t))
+      pure ("-unit @" ++ file)
+  (wall, cpu, (code, out, err)) <- timed $ readCreateProcessWithExitCode (proc ghc (["--make", "-j" ++ show n, "-no-link"] ++ concatMap words targets ++ rtsStats stats)){cwd = Just dir} ""
+  unless (code == ExitSuccess) $ hPutStrLn stderr err >> exitFailure
+  (peak, live, gc) <- readRtsStats stats
+  split <- readRtsSplit stats
+  pure (Measure wall cpu peak live gc Nothing Nothing split, length (filter ("Compiling " `isInfixOf`) (lines out)))
+
+-- | Build each target with a `ghc --make` of its own. After an edit, build
+-- the targets that buck2 would: the edited module's target, and each target
+-- with a dependency whose interfaces changed, each from scratch. Also
+-- returns the number of targets built.
+perTarget :: FilePath -> String -> Int -> [String] -> Workload -> Maybe String -> IO (Measure, Int)
+perTarget dir ghc n common w edit = do
+  changed <- newMVar Set.empty
+  count <- newIORef (0 :: Int)
+  let job t = do
+        dirty <- (\ch -> any (`Set.member` ch) (tDeps t)) <$> readMVar changed
+        if maybe True (`elem` [name | (name, _, _) <- tModules t]) edit || dirty
+          then do
+            before <- interfaces t
+            removePathForcibly (dir </> outDir t)
+            createDirectoryIfMissing True (dir </> outDir t)
+            r <- compile t
+            after <- interfaces t
+            when (after /= before) $ modifyMVar_ changed (pure . Set.insert (tDir t))
+            atomicModifyIORef' count (\k -> (k + 1, ()))
+            pure r
+          else pure (True, "")
+  (wall, cpu, path) <- timed $ schedule n [(tDir t, tDeps t, job t) | t <- wTargets w]
+  k <- readIORef count
+  pure (Measure wall cpu Nothing Nothing Nothing Nothing (Just path) Nothing, k)
+  where
+    compile t = do
+      let out = outDir t
+      (code, _, err) <- readCreateProcessWithExitCode (proc ghc (["--make", "-no-link", "-i" ++ tDir t </> "src", "-odir", out, "-hidir", out] ++ compileFlags common t ++ [tDir t </> "src" </> name <.> "hs" | (name, _, _) <- tModules t])){cwd = Just dir} ""
+      pure (code == ExitSuccess, err)
+    -- The target's interfaces, which are the outputs that its dependents'
+    -- actions read. If they change, buck2 runs the dependents again.
+    interfaces t = forM [name | (name, _, _) <- tModules t] $ \name -> do
+      let f = dir </> outDir t </> name <.> "hi"
+      exists <- doesFileExist f
+      if exists then Just <$> B.readFile f else pure Nothing
+
+-- | Build each module with a `ghc -c` of its own. After each compile, write
+-- the module's ABI file from its interface, as the compile tool does. The
+-- bench reads the interface in its own process, so this costs less here
+-- than with the compile tool.
+perModule :: FilePath -> String -> Int -> [String] -> Workload -> Maybe String -> IO (Measure, Int)
+perModule dir ghc n common w edit = do
+  libdir <- takeWhile (/= '\n') <$> readProcess ghc ["--print-libdir"] ""
+  (wall, cpu, (path, k)) <- timed $ dispatch dir n w edit $ \t name -> do
+    (code, _, err) <- readCreateProcessWithExitCode (proc ghc (compileFlags common t ++ ["-fforce-recomp"] ++ compileArgs t name)){cwd = Just dir} ""
+    when (code == ExitSuccess) $ do
+      iface <- readInterface libdir (dir </> outDir t </> name <.> "hi")
+      writeFile (dir </> outDir t </> name <.> "abi") (show (abiHash iface))
+    pure (code == ExitSuccess, err)
+  pure (Measure wall cpu Nothing Nothing Nothing Nothing (Just path) Nothing, k)
+
+-- | Build the workload through a fresh worker, started in the workload's
+-- directory with the given environment variables. Each module is sent to it
+-- as a request, and the worker is ended as buck2 ends it.
+viaWorker :: FilePath -> FilePath -> [String] -> String -> Int -> [String] -> [(String, String)] -> Workload -> Maybe String -> IO (Measure, Int)
+viaWorker dir worker rts ghc n common settings w edit = do
+  libdir <- takeWhile (/= '\n') <$> readProcess ghc ["--print-libdir"] ""
+  let logFile = dir </> "worker.log"
+  (wall, cpu, (path, k)) <- timed $ withFile logFile WriteMode $ \logH ->
+    withWorkerProcess worker (["+RTS", "-T"] ++ rts ++ ["-RTS"]) dir ([("TMPDIR", dir </> "tmp"), ("BUCK2_GHC_WORKER_VERBOSE", "1")] ++ settings) (UseHandle logH) $ \sock ->
+      dispatch dir n w edit (\t name -> (\(code, err) -> (code == 0, err)) <$> grpc sock (workerRequest ghc libdir common t name))
+  (peak, live, gc, sessions) <- readWorkerLog logFile
+  split <- readWorkerSplit logFile
+  pure (Measure wall cpu peak live gc (Just sessions) (Just path) split, k)
+
+-- | The arguments of a module's request, as the rules send them.
+workerRequest :: String -> FilePath -> [String] -> Target -> String -> [String]
+workerRequest ghc libdir common t name =
+  [ "--request", "--contract", contract, "--libdir", libdir
+  , "--depfile", tDir t </> "dep" </> name <.> "dep", "--abi", outDir t </> name <.> "abi", "--diagnostics", outDir t </> name <.> "diag", "--module", name, "--source", tDir t </> "src" </> name <.> "hs"
+  , "--outdir", outDir t, "--hisuf", "hi", "--srcroot=" ++ tDir t </> "src"]
+  ++ ["--", ghc] ++ compileFlags common t ++ ["-fforce-recomp", "--"] ++ compileArgs t name
+
+-- | The directory that a target's compiles write to. It follows the layout
+-- of buck2's output directories, which the worker uses to tell which
+-- targets' one-shot sessions can share the interfaces they read (see
+-- 'interfaceKey' in Session).
+outDir :: Target -> FilePath
+outDir t = "buck-out" </> "v2" </> "art" </> "bench" </> "0" </> tDir t </> "out"
+
+-- | compileFlags are the flags that all of a target's compiles share, as the
+-- rules give them. compileArgs are the arguments for one module's compile:
+-- its source and output files.
+compileFlags :: [String] -> Target -> [String]
+compileFlags common t =
+  common ++ ["-i" ++ outDir t] ++ concat [["-this-unit-id", tDir t] | not (null (tDir t))]
+    ++ concat [["-package-db", "db", "-package-id", d] | d <- tDeps t]
+
+compileArgs :: Target -> String -> [String]
+compileArgs t name = ["-c", src, "-o", out "o", "-ohi", out "hi"]
+  where
+    src = tDir t </> "src" </> name <.> "hs"
+    out ext = outDir t </> name <.> ext
+
+-- | Run each module's compile once the modules it imports are compiled, at
+-- most n at a time. After an edit to a module, run only the compiles that
+-- buck2 would: the edited module's, and each one with an import whose ABI
+-- file changed (see Note [Early cut-off by dep files] in
+-- compile_per_module.bzl). Returns the critical path and the number of
+-- modules compiled.
+dispatch :: FilePath -> Int -> Workload -> Maybe String -> (Target -> String -> IO (Bool, String)) -> IO (Double, Int)
+dispatch root n w edit compile = do
+  changed <- newMVar Set.empty
+  count <- newIORef (0 :: Int)
+  let job t name imports = do
+        dirty <- (\ch -> any (`Set.member` ch) imports) <$> readMVar changed
+        if maybe True (== name) edit || dirty
+          then do
+            let abi = root </> outDir t </> name <.> "abi"
+            before <- readAbi abi
+            r <- compile t name
+            after <- readAbi abi
+            when (after /= before) $ modifyMVar_ changed (pure . Set.insert name)
+            atomicModifyIORef' count (\k -> (k + 1, ()))
+            pure r
+          else pure (True, "")
+  path <- schedule n [(name, imports, job t name imports) | t <- wTargets w, (name, imports, _) <- tModules t]
+  (,) path <$> readIORef count
+  where
+    readAbi f = do
+      exists <- doesFileExist f
+      if exists then Just <$> B.readFile f else pure Nothing
+
+-- | Run each job once the jobs it waits for are done, at most n at a time.
+-- A job is a key, the keys of the jobs it waits for, and an action, which
+-- returns whether it succeeded and, if not, the error. An action that
+-- throws counts as failed, so that the jobs waiting for it still run. If
+-- any job failed, the bench prints the first few errors and exits once all
+-- the jobs have run.
+--
+-- Returns the critical path: the longest total time of a chain of jobs,
+-- each waiting for the one before, using the time each job actually took.
+-- However many slots there were, the jobs couldn't finish sooner. Jobs that
+-- share a machine or a worker run slower when more run at once, so the
+-- critical path measured with one job at a time is the more accurate
+-- bound.
+schedule :: (Ord k, Show k) => Int -> [(k, [k], IO (Bool, String))] -> IO Double
+schedule n jobs = do
+  slots <- newQSem n
+  done <- M.fromList <$> forM jobs (\(k, _, _) -> (,) k <$> newEmptyMVar)
+  forM_ jobs $ \(k, after, job) -> forkIO $ do
+    before <- maximum . (0 :) . map snd <$> mapM (readMVar . (done M.!)) after
+    (result, took) <- bracket_ (waitQSem slots) (signalQSem slots) $ do
+      start <- getMonotonicTime
+      result <- either (\e -> (False, show (e :: SomeException))) id <$> try job
+      end <- getMonotonicTime
+      pure (result, end - start)
+    putMVar (done M.! k) (result, before + took)
+  results <- forM jobs $ \(k, _, _) -> (,) k <$> readMVar (done M.! k)
+  let failed = [(k, err) | (k, ((False, err), _)) <- results]
+  unless (null failed) $ mapM_ (\(k, err) -> hPutStrLn stderr (show k ++ ": " ++ err)) (take 3 failed) >> exitFailure
+  pure (maximum (0 : map (snd . snd) results))
diff --git a/buck2/prelude/haskell/tools/worker/props/Main.hs b/buck2/prelude/haskell/tools/worker/props/Main.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/props/Main.hs
@@ -0,0 +1,886 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+-- | Property tests that check that building through the worker gives the
+-- same results as a plain `ghc -c`. We generate histories of a small
+-- package, and build each history step by step through the worker, as
+-- buck2 would build it. After each build, we compare the results with a
+-- clean build of the same sources, with one `ghc -c` per module.
+--
+-- A history is a package, sometimes a second package p that it depends on,
+-- and a sequence of builds, with edits to the sources before each one.
+--
+-- - The main package has modules M0..Mn, each importing some of the
+--   modules before it. Some modules have a boot file, which modules before
+--   them import {-# SOURCE #-}. Some have a Template Haskell splice, which
+--   runs a module that it imports.
+-- - p has modules P0..Pk, which the main package imports through p's early
+--   package db, as the rules arrange for a dependency compiled per-module.
+--   The db names no library, and its import directory is the one that p's
+--   interfaces are written to as each module compiles. Sometimes p's
+--   modules are named M0..Mk instead, so that a module of p can have the
+--   same name as one of the main package. Only the unit id then tells them
+--   apart, for example in the usages that the dep files are made from.
+-- - On Linux, a splice may run p's code instead. The module's compile then
+--   gets p's final package db, which names p's library, and GHC's
+--   interpreter loads p's code from that library. The test links p's
+--   library as the rules link a library. p has no native libraries.
+--
+-- Each build gets a fresh worker, as each buck2 build does. The test sends
+-- it the modules and boot files that buck2 would compile: those never
+-- compiled before, and those whose source has changed since they were last
+-- compiled, or a file that their dep file lists has (the early cut-off of
+-- Note [Early cut-off by dep files] in compile_per_module.bzl). Each one is
+-- sent once everything it imports is done, with independent ones sent at
+-- the same time. A module with a failed import isn't sent. After each
+-- build, every module and boot file must agree with the clean build on
+-- whether it compiles, on its ABI hash, and on its object (from GHC 9.12,
+-- whose objects are deterministic).
+--
+-- The worker and GHC are found as in the test suite (BUCK2_GHC_WORKER, GHC).
+-- The command-line options are tasty's: --hedgehog-tests N runs N histories
+-- (30 by default), and a failure prints how to run it again
+-- (--hedgehog-replay).
+module Main (main) where
+
+import Control.Applicative ((<|>))
+import Control.Concurrent (forkIO)
+import Control.Concurrent.MVar
+import Control.Exception (SomeException, catch, throwIO, try)
+import Control.Monad (forM, forM_, replicateM, unless, when)
+import Control.Monad.IO.Class (liftIO)
+import qualified Data.ByteString as B
+import Data.IORef
+import Data.List (intercalate, sort)
+import qualified Data.Map as M
+import Data.Maybe (fromMaybe, isJust)
+import Data.Version (showVersion, versionBranch)
+import System.Directory
+import System.Environment (lookupEnv)
+import System.Exit (ExitCode (..), exitFailure)
+import System.FilePath ((<.>), (</>))
+import System.Info (fullCompilerVersion, os)
+import System.IO (IOMode (..), hPutStrLn, openFile, stderr)
+import System.Timeout (timeout)
+import System.Posix.Process (getProcessID)
+import System.Process
+
+import Hedgehog
+import qualified Hedgehog.Gen as Gen
+import qualified Hedgehog.Range as Range
+import Test.Tasty (TestTree, adjustOption, askOption, defaultMain, localOption, testGroup)
+import Test.Tasty.Hedgehog (HedgehogTestLimit (..), testPropertyNamed)
+
+import Client
+import Contract (contract)
+
+-- * Histories
+
+data Ty = TInt | TInteger
+  deriving (Eq, Show)
+
+-- | A generated module. Modules are identified by keys: the main package's
+-- from 0, and p's from 100 (see pkgP). The fields are:
+--
+-- - mImports: the modules it imports, all qualified. A module may import
+--   modules of its own package with lower keys, and a module of the main
+--   package may also import any module of p.
+-- - mSourceImports: the modules it imports {-# SOURCE #-}. Each has a
+--   higher key and a boot file.
+-- - mValues: its exported values, each with a number for its name, a type,
+--   and the constant in its definition. Value 0 also adds up value 0 of
+--   each import, and value t of each import that has one. A module with
+--   SOURCE imports also exports an INLINE value t, the sum of the SOURCE
+--   imports' values 0, and for each SOURCE import a function that shows the
+--   import's type T.
+-- - mBoot: whether it has a boot file, which declares its value 0 and a
+--   type T with a Show instance.
+-- - mSplice: the key of an imported module whose value 0 the module's
+--   splice uses, or Nothing if it has no splice. If the imported module is
+--   in p, the splice evaluates the value. If it's in the main package, the
+--   splice only refers to the value, since the main package's values may
+--   form a cycle through SOURCE imports. GHC still has to link that
+--   module's code.
+-- - mComments and mBootComments: how many comment-only edits have been made
+--   to it and to its boot file.
+-- - mBroken: whether it has a type error.
+-- - mOwnFlags: whether its requests have an extra flag, so that it compiles
+--   in a session of its own, as a Template Haskell module does in the rules
+--   because its package flags differ.
+-- - mReexports: the imports whose value 0 it re-exports. Its importers'
+--   value 0 adds those too. GHC then records a usage of the module that
+--   defines the value in the importers' interfaces, though they don't
+--   import that module.
+-- - mOptions: the flags of its OPTIONS_GHC pragma, if any (see
+--   optionFlags). They change how its compile reads and writes interfaces,
+--   or give the same setting in another way, so that compiles whose flags
+--   differ share the worker's interfaces only when they should (see
+--   'interfaceKey' in the worker's Session).
+data Mod = Mod
+  { mImports :: [Int]
+  , mSourceImports :: [Int]
+  , mValues :: [(Int, Ty, Int)]
+  , mBoot :: Bool
+  , mSplice :: Maybe Int
+  , mComments :: Int
+  , mBootComments :: Int
+  , mBroken :: Bool
+  , mOwnFlags :: Bool
+  , mReexports :: [Int]
+  , mOptions :: [String]
+  }
+  deriving (Eq, Show)
+
+data Edit
+  = Comment Int
+  | BootComment Int
+  | Body Int Int Int -- the module, the value, and the value's new constant
+  | AddValue Int
+  | RemoveValue Int
+  | Retype Int -- change the type of value 0, which the boot file declares too
+  | AddImport Int Int
+  | RemoveImport Int Int
+  | AddSourceImport Int Int
+  | RemoveSourceImport Int Int
+  | Break Int -- add a type error, or remove it if there is one
+  | AddReexport Int Int
+  | RemoveReexport Int Int
+  | SetOptions Int [String] -- replace the flags of its OPTIONS_GHC pragma
+  deriving (Show)
+
+-- | A build: the edits made before it, and whether its worker drops
+-- sessions as soon as they are idle (a session limit of 0).
+data Build = Build {bEdits :: [Edit], bEagerDrop :: Bool}
+  deriving (Show)
+
+-- | A history: whether its compiles optimise (-O), its modules keyed as
+-- described at Mod, and its builds.
+data History = History {hOptimise :: Bool, hModules :: [(Int, Mod)], hBuilds :: [Build]}
+  deriving (Show)
+
+-- | Generate a history. Its modules have boot files only if the argument is
+-- True.
+genHistory :: Bool -> Gen History
+genHistory bootsAllowed = do
+  -- Each count has a constant part and a part that grows with Hedgehog's
+  -- size parameter. The size grows by one with each test, so it stays
+  -- small over the default 30 histories, and a history needs several
+  -- builds and edits to be worth running whatever its size. A long run
+  -- (--hedgehog-tests 500, say) reaches the larger sizes, and with them
+  -- longer chains of imports and more edits between builds.
+  n <- grow 2 6 6
+  pn <- Gen.frequency [(1, pure 0), (2, Gen.int (Range.constant 1 3))]
+  -- p's modules. Their keys start from pkgClash when they should have the
+  -- same names as the main package's (see modName).
+  pbase <- Gen.element [pkgP, pkgClash]
+  let pkeys = [pbase + j | j <- [0 .. pn - 1]]
+  pmods <- forM [0 .. pn - 1] $ \i -> do
+    imports <- Gen.subsequence (take i pkeys)
+    k <- Gen.int (Range.constant 1 3)
+    values <- forM [0 .. k - 1] $ \v -> (,,) v <$> Gen.element [TInt, TInteger] <*> Gen.int (Range.linear 0 9)
+    reexports <- Gen.subsequence imports
+    pure (Mod imports [] values False Nothing 0 0 False False reexports [])
+  boots <- forM [0 .. n - 1] $ \i -> if i == 0 || not bootsAllowed then pure False else Gen.frequency [(2, pure False), (1, pure True)]
+  mods <- forM [0 .. n - 1] $ \i -> do
+    own' <- if i == 0 then pure [] else Gen.subsequence [0 .. i - 1]
+    fromP <- Gen.subsequence pkeys
+    let imports = own' ++ fromP
+    k <- Gen.int (Range.constant 1 3)
+    values <- forM [0 .. k - 1] $ \v -> (,,) v <$> Gen.element [TInt, TInteger] <*> Gen.int (Range.linear 0 9)
+    -- The splice uses one of this module's imports, from p twice as often
+    -- as from the main package.
+    splice <- Gen.frequency ([(3, pure Nothing)] ++ [(1, Just <$> Gen.element own') | not (null own')] ++ [(2, Just <$> Gen.element fromP) | pSplices, not (null fromP)])
+    -- A module with a splice gets no SOURCE imports, because compiledAs
+    -- would drop its splice. (An edit may still add one later.)
+    sourceImports <- if isJust splice then pure [] else Gen.subsequence [j | j <- [i + 1 .. n - 1], boots !! j]
+    own <- Gen.frequency [(2, pure False), (1, pure True)]
+    reexports <- Gen.subsequence imports
+    options <- Gen.frequency [(3, pure []), (1, genOptions)]
+    pure (Mod imports sourceImports values (boots !! i) splice 0 0 False own reexports options)
+  buildCount <- grow 2 6 4
+  builds <- replicateM buildCount (Build <$> (grow 1 4 3 >>= \k -> replicateM k (genEdit ([0 .. n - 1] ++ pkeys))) <*> Gen.bool)
+  History <$> Gen.bool <*> pure (zip [0 ..] mods ++ zip pkeys pmods) <*> pure builds
+  where
+    grow lo hi extra = (+) <$> Gen.int (Range.constant lo hi) <*> Gen.int (Range.linear 0 extra)
+
+-- | The flags that a module's OPTIONS_GHC pragma may have. Some change how
+-- its compile reads interfaces (-O0 and -fignore-interface-pragmas ignore
+-- the unfoldings in them) or writes its own (-fomit-interface-pragmas
+-- leaves them out). Others give the same setting as GHC's default, or as
+-- another flag here, or don't matter to interfaces at all. A pragma may
+-- also give a flag twice, or the same flags in another order than another
+-- module's.
+optionFlags :: [String]
+optionFlags =
+  [ "-O0"
+  , "-O"
+  , "-fignore-interface-pragmas"
+  , "-fno-ignore-interface-pragmas"
+  , "-fomit-interface-pragmas"
+  , "-fno-omit-interface-pragmas"
+  , "-w"
+  , "-fno-warn-orphans"
+  ]
+
+genOptions :: Gen [String]
+genOptions = Gen.list (Range.constant 1 3) (Gen.element optionFlags)
+
+-- | pkgP is the lowest key of p's modules, and the main package's modules
+-- have lower keys. p's modules with keys from pkgClash up are named
+-- M0, M1 and so on, like the main package's (see modName).
+pkgP, pkgClash :: Int
+pkgP = 100
+pkgClash = 200
+
+inP :: Int -> Bool
+inP i = i >= pkgP
+
+-- | Generate an edit to one or two of the modules with the given keys.
+genEdit :: [Int] -> Gen Edit
+genEdit keys =
+  Gen.frequency $
+    map ((,) 1)
+    [ Comment <$> m
+    , BootComment <$> m
+    -- The edit changes value 0 most often, because the importers' values 0
+    -- and the splices that run p's code use it.
+    , Body <$> m <*> Gen.frequency [(3, pure 0), (1, Gen.int (Range.linear 1 3))] <*> Gen.int (Range.linear 0 9)
+    , AddValue <$> m
+    , RemoveValue <$> m
+    , Retype <$> m
+    , AddImport <$> m <*> m
+    , RemoveImport <$> m <*> m
+    , AddSourceImport <$> m <*> m
+    , RemoveSourceImport <$> m <*> m
+    , Break <$> m
+    , AddReexport <$> m <*> m
+    , RemoveReexport <$> m <*> m
+    , SetOptions <$> m <*> Gen.frequency [(1, pure []), (2, genOptions)]
+    ]
+      -- Also change value 0 of a module of p. That changes p's library under
+      -- the splices that run p's code, whose modules must then compile
+      -- again. This edit has a high weight, because it only tests anything
+      -- when the history also has a splice that runs p's code, and a later
+      -- build compiles the splice's module.
+      ++ [(4, Body <$> Gen.element ps <*> pure 0 <*> Gen.int (Range.linear 0 9)) | let ps = filter inP keys, not (null ps)]
+  where
+    m = Gen.element keys
+
+-- | Apply an edit to the modules. An edit that doesn't make sense, such as
+-- one that removes a value or import that the module doesn't have, changes
+-- nothing. Then any edit applies to any package, so a history that
+-- Hedgehog has shrunk, removing some modules, is still valid.
+applyEdit :: M.Map Int Mod -> Edit -> M.Map Int Mod
+applyEdit mods e = case e of
+  Comment i -> at i $ \m -> m{mComments = mComments m + 1}
+  BootComment i -> at i $ \m -> if mBoot m then m{mBootComments = mBootComments m + 1} else m
+  Body i v c -> at i $ \m -> m{mValues = [if k == v then (k, t, c) else (k, t, x) | (k, t, x) <- mValues m]}
+  AddValue i -> at i $ \m -> m{mValues = mValues m ++ [(1 + maximum [k | (k, _, _) <- mValues m], TInt, 0)]}
+  RemoveValue i -> at i $ \m -> if length (mValues m) > 1 then m{mValues = init (mValues m)} else m
+  Retype i -> at i $ \m -> m{mValues = [if k == 0 then (k, flip' t, x) else (k, t, x) | (k, t, x) <- mValues m]}
+  AddImport i j -> if j < i && inP i == inP j || inP j && not (inP i) then at i (\m -> m{mImports = add j (mImports m)}) else mods
+  RemoveImport i j -> at i $ \m -> m{mImports = filter (/= j) (mImports m)}
+  AddSourceImport i j -> if j > i && not (inP i) && maybe False mBoot (M.lookup j mods) then at i (\m -> m{mSourceImports = add j (mSourceImports m)}) else mods
+  RemoveSourceImport i j -> at i $ \m -> m{mSourceImports = filter (/= j) (mSourceImports m)}
+  Break i -> at i $ \m -> m{mBroken = not (mBroken m)}
+  AddReexport i j -> at i $ \m -> if j `elem` mImports m then m{mReexports = add j (mReexports m)} else m
+  RemoveReexport i j -> at i $ \m -> m{mReexports = filter (/= j) (mReexports m)}
+  SetOptions i fs -> at i $ \m -> m{mOptions = fs}
+  where
+    at i f = M.adjust f i mods
+    add j js = if j `elem` js then js else sort (j : js)
+    flip' TInt = TInteger
+    flip' TInteger = TInt
+
+-- * Sources
+
+-- | A node of the build: a module, or its boot file.
+type Node = (Int, Bool)
+
+nodes :: M.Map Int Mod -> [Node]
+nodes mods = concat [[(i, True) | mBoot m] ++ [(i, False)] | (i, m) <- M.toList mods]
+
+-- | The nodes whose outputs a node's compile reads, and so has to wait for.
+-- A boot file reads none. A module reads its imports, the boot files of its
+-- SOURCE imports, and its own boot file.
+--
+-- A module of the main package also waits for every module of p that its
+-- imports from p depend on, directly or indirectly, since GHC may read
+-- their interfaces too. The rules make it wait for these in the same way
+-- (see Note [Compiling against dependencies module by module] in
+-- compile_per_module.bzl).
+--
+-- A module whose splice runs p's code also waits for every module of p,
+-- because its splice loads p's library, which is linked from all of p's
+-- modules (see linkP).
+nodeDeps :: M.Map Int Mod -> Node -> [Node]
+nodeDeps _ (_, True) = []
+nodeDeps mods (i, False) =
+  [(j, False) | j <- mImports m] ++ [(j, True) | j <- mSourceImports m] ++ [(i, True) | mBoot m]
+    ++ (if inP i then [] else [(j, False) | j <- belowInP mods [x | x <- mImports m, inP x]])
+    ++ (if splicesP m then [(j, False) | j <- M.keys mods, inP j] else [])
+  where
+    m = mods M.! i
+
+-- | Whether splices may run p's code, which is only on Linux, where linkP
+-- links p's library as an ELF shared library.
+pSplices :: Bool
+pSplices = os == "linux"
+
+-- | Whether a module's splice runs p's code. If it does, the module's
+-- compile gets p's final package db, and its splice loads p's library (see
+-- linkP).
+splicesP :: Mod -> Bool
+splicesP m = maybe False inP (mSplice m)
+
+-- | The given modules of p, and every module of p that they import,
+-- directly or indirectly.
+belowInP :: M.Map Int Mod -> [Int] -> [Int]
+belowInP mods = go []
+  where
+    go visited [] = visited
+    go visited (x : xs)
+      | x `elem` visited = go visited xs
+      | otherwise = go (x : visited) (mImports (mods M.! x) ++ xs)
+
+-- | The modules of its own package that a module imports, directly or
+-- indirectly, leaving out SOURCE imports. The rules pass these to a module
+-- that runs a splice, since the splice may load their objects (see Note
+-- [Template Haskell modules] in compile_per_module.bzl).
+closureOf :: M.Map Int Mod -> Int -> [Int]
+closureOf mods i = go [] [x | x <- mImports (mods M.! i), inP x == inP i]
+  where
+    go visited [] = visited
+    go visited (x : xs)
+      | x `elem` visited = go visited xs
+      | otherwise = go (x : visited) ([y | y <- mImports (mods M.! x), inP y == inP i] ++ xs)
+
+-- | The modules behind the boot files below the given modules.
+linkedPastBoots :: M.Map Int Mod -> [Int] -> [Int]
+linkedPastBoots mods = go [] []
+  where
+    go _ found [] = found
+    go visited found (x : xs)
+      | x `elem` visited = go visited found xs
+      | otherwise = let mx = mods M.! x in go (x : visited) (mSourceImports mx ++ found) (mImports mx ++ mSourceImports mx ++ xs)
+
+-- | The package as the build compiles it, without the splices that
+-- per_module doesn't support. Those are the splices that might run code
+-- behind a boot file (see Note [Template Haskell modules] in
+-- compile_per_module.bzl), in a module with a boot file below its imports
+-- or a SOURCE import of its own.
+compiledAs :: M.Map Int Mod -> M.Map Int Mod
+compiledAs mods = M.map (\m -> if linksPast m || not (null (mSourceImports m)) then m{mSplice = Nothing} else m) mods
+  where
+    linksPast m = not (null (linkedPastBoots mods (mImports m)))
+
+nodeName :: Node -> String
+nodeName (i, boot) = modName i ++ (if boot then "-boot" else "")
+
+modName :: Int -> String
+modName i
+  | i >= pkgClash = "M" ++ show (i - pkgClash)
+  | inP i = "P" ++ show (i - pkgP)
+  | otherwise = "M" ++ show i
+
+-- | The alias that a module imports another module as. Modules use aliases,
+-- not module names, to refer to their imports' values, because a module of
+-- p may have the same name as one of the main package's.
+alias :: Int -> String
+alias j = "X" ++ show j
+
+-- | The directories of the sources and outputs of a node's package. The
+-- outputs of both packages are under one configuration's directory, laid
+-- out as buck2 lays them out, so that the worker's one-shot sessions for the
+-- two packages share their external state (see 'interfaceKey' in the
+-- worker's Session).
+srcDir, outDir :: Int -> FilePath
+srcDir i = if inP i then "psrc" else "src"
+outDir i = "art" </> "root" </> "cfg" </> if inP i then "pout" else "out"
+
+suffix :: Node -> String
+suffix (_, boot) = if boot then "-boot" else ""
+
+source :: Node -> FilePath
+source n@(i, _) = srcDir i </> modName i <.> ("hs" ++ suffix n)
+
+value :: Int -> Int -> String
+value j k = "v" ++ show j ++ "_" ++ show k
+
+tyName :: Ty -> String
+tyName TInt = "Int"
+tyName TInteger = "Integer"
+
+render :: M.Map Int Mod -> Node -> String
+render mods (i, True) =
+  let m = mods M.! i
+      t = case [vt | (0, vt, _) <- mValues m] of
+        vt : _ -> vt
+        [] -> TInt
+   in unlines ["module " ++ modName i ++ " where", "-- edit " ++ show (mBootComments m), value i 0 ++ " :: " ++ tyName t, "data " ++ ty i, "instance Show " ++ ty i]
+render mods (i, False) =
+  unlines $
+    ["{-# OPTIONS_GHC " ++ unwords (mOptions m) ++ " #-}" | not (null (mOptions m))]
+      ++ ["{-# LANGUAGE TemplateHaskell #-}" | isJust (mSplice m)]
+      ++ ["{-# LANGUAGE PackageImports #-}" | fromP]
+      ++ ["module " ++ modName i ++ " (" ++ intercalate ", " exports ++ ") where"]
+      ++ ["import qualified " ++ (if fromP && inP j then "\"p\" " else "") ++ modName j ++ " as " ++ alias j | j <- mImports m]
+      ++ ["import {-# SOURCE #-} qualified " ++ modName j ++ " as " ++ alias j | j <- mSourceImports m]
+      ++ ["import Language.Haskell.TH.Syntax (lift)" | isJust (mSplice m)]
+      ++ ["-- edit " ++ show (mComments m)]
+      ++ concat
+        [ [ value i k ++ " :: " ++ tyName t
+          , value i k ++ " = " ++ show c ++ concat [" + fromIntegral " ++ alias j ++ "." ++ v | k == 0, j <- mImports m, v <- value j 0 : ["t" ++ show j | hasT j] ++ [value r 0 | r <- reexported j]]
+          ]
+        | (k, t, c) <- mValues m
+        ]
+      ++ concat [["t" ++ show i ++ " :: Integer", "t" ++ show i ++ " = 0" ++ concat [" + fromIntegral " ++ alias j ++ "." ++ value j 0 | j <- mSourceImports m], "{-# INLINE t" ++ show i ++ " #-}"] | hasT i]
+      ++ concat [[shows' j ++ " :: " ++ alias j ++ "." ++ ty j ++ " -> String", shows' j ++ " = show"] | j <- mSourceImports m]
+      ++ concat [["data " ++ ty i ++ " = " ++ ty i, "instance Show " ++ ty i ++ " where show _ = " ++ show (ty i)] | mBoot m]
+      -- A splice of p's code puts the value it computes into the module's
+      -- object, and p's values can't form a cycle, because p has no boot
+      -- files. So if the worker's splice ran a stale copy of p's library,
+      -- the object would differ from the clean build's.
+      ++ concat [["s" ++ show i ++ " :: Integer", "s" ++ show i ++ " = $(lift (" ++ (if inP j then "fromIntegral " ++ alias j ++ "." ++ value j 0 else "fromIntegral (length [" ++ alias j ++ "." ++ value j 0 ++ "])") ++ " :: Integer))"] | Just j <- [mSplice m]]
+      ++ (if mBroken m then ["broken :: Int", "broken = \"not an Int\""] else [])
+  where
+    m = mods M.! i
+    exports = [value i k | (k, _, _) <- mValues m] ++ ["t" ++ show i | hasT i] ++ map shows' (mSourceImports m) ++ [ty i | mBoot m] ++ ["s" ++ show i | isJust (mSplice m)] ++ [alias r ++ "." ++ value r 0 | r <- reexported i]
+    hasT j = not (null (mSourceImports (mods M.! j)))
+    -- A re-export of an import that an edit removed is dropped.
+    reexported j = let mj = mods M.! j in [r | r <- mReexports mj, r `elem` mImports mj]
+    fromP = not (inP i) && any inP (mImports m)
+    shows' j = "show" ++ show i ++ "_" ++ show j
+
+-- | The type a module with a boot file declares in both.
+ty :: Int -> String
+ty i = "T" ++ show i
+
+-- | commonFlags are the flags of every compile in the history, and
+-- nodeFlags are the flags specific to a node's package and module.
+commonFlags :: History -> [String]
+commonFlags h =
+  ["-hide-all-packages", "-package", "base"]
+    ++ (if hOptimise h then ["-O"] else ["-O0"])
+    -- GHC is dynamically linked, so to run a splice it loads dynamic
+    -- objects, which -dynamic makes.
+    ++ ["-dynamic" | any (isJust . mSplice . snd) (hModules h)]
+
+nodeFlags :: M.Map Int Mod -> Node -> [String]
+nodeFlags mods (i, _)
+  | inP i = ["-this-unit-id", "p", "-i" ++ outDir pkgP]
+  | otherwise =
+      ["-DOWN_SESSION" | mOwnFlags m]
+        ++ (if isJust (mSplice m) then ["-package", "template-haskell"] else [])
+        ++ (if any (inP . fst) (M.toList mods) then ["-package-db", if splicesP m then "pfinal" else "pdb", "-package", "p"] else [])
+        ++ ["-iout"]
+  where
+    m = mods M.! i
+
+-- * Running a history
+
+-- | The result of a build for one node. Compiled holds the node's ABI hash,
+-- its object, and the usages of imports that its interface records. Failed
+-- holds the compile's errors. Blocked means the node wasn't compiled because
+-- something it imports failed.
+data Outcome = Compiled String B.ByteString [String] | Failed String | Blocked
+  deriving (Eq)
+
+describe :: Outcome -> String
+describe (Compiled abi _ us) = "compiled, ABI " ++ abi ++ (if null us then "" else ", usages " ++ intercalate "; " us)
+describe (Failed err) = "failed: " ++ take 400 err
+describe Blocked = "not compiled (an import failed)"
+
+isCompiled :: Outcome -> Bool
+isCompiled (Compiled _ _ _) = True
+isCompiled _ = False
+
+-- | How to run the histories: the worker, GHC, and working directory;
+-- whether to compare objects (which are deterministic from GHC 9.12) or
+-- else the usages that interfaces record; and whether the worker uses
+-- one-shot sessions rather than --make ones.
+data Config = Config {cWorker :: FilePath, cGhc :: String, cLibdir :: FilePath, cDir :: FilePath, cObjects :: Bool, cOneShot :: Bool}
+
+-- | Counts of what a history's builds did. The coverage checks in
+-- historyProp use them to make sure the generated histories exercise the
+-- cases they are meant to.
+data Stats = Stats {sSkipped :: Int, sRecompiled :: Int, sFailed :: Int, sBlocked :: Int, sLibChanged :: Int}
+
+-- | For each node, the source the worker last compiled it from, and the
+-- contents at that time of each file its dep file lists. For a module whose
+-- splice runs p's code, the files also include p's library, which the dep
+-- file doesn't list. This is how the test decides, as buck2 would, whether
+-- a node is up to date.
+type LastOk = M.Map Node (String, [(FilePath, Maybe B.ByteString)])
+
+-- | Run each build of the history through the worker, and as a clean
+-- build, and compare them. Returns a description of the first build where
+-- they disagree, if there is one.
+runHistory :: Config -> History -> IO (Either String (), Stats)
+runHistory cfg h = do
+  stats <- newIORef (Stats 0 0 0 0 0)
+  let dir = cDir cfg
+  removePathForcibly dir
+  mapM_ (createDirectoryIfMissing True . (dir </>)) ["w/src", "w" </> outDir 0, "w/psrc", "w" </> outDir pkgP, "w/dep", "w/tmp", "ref"]
+  -- Register p's package dbs for the worker's builds. Each clean build
+  -- registers package dbs of its own.
+  let ps = [i | (i, _) <- hModules h, inP i]
+  registerP cfg (dir </> "w") ps
+  lastOk <- newIORef M.empty
+  libSeen <- newIORef M.empty
+  let go _ _ [] = pure (Right ())
+      go mods n (b : rest) = do
+        let mods' = foldl applyEdit mods (bEdits b)
+            built = compiledAs mods'
+        forM_ (nodes built) $ \node -> writeFileIfChanged (dir </> "w" </> source node) (render built node)
+        (worker, skipped) <- workerBuild cfg h b built lastOk libSeen stats
+        ref <- refBuild cfg h built
+        case [(node, w, r) | (node, w) <- M.toList worker, let r = ref M.! node, not (agree w r)] of
+          [] -> go mods' (n + 1) rest
+          diffs ->
+            pure . Left $
+              unlines $
+                ("after build " ++ show (n :: Int) ++ ":")
+                  : [nodeName node ++ ": through the worker " ++ describe w ++ (if node `elem` skipped then " (skipped as up to date)" else "") ++ "; with ghc -c " ++ describe r | (node, w, r) <- diffs]
+  result <- go (M.fromList (hModules h)) 1 (hBuilds h)
+  (,) result <$> readIORef stats
+  where
+    agree (Compiled a o u) (Compiled a' o' u') = a == a' && (if cObjects cfg then o == o' else u == u')
+    agree (Failed _) (Failed _) = True
+    agree Blocked Blocked = True
+    agree _ _ = False
+
+-- | If p has modules, register p's two package dbs in the given directory,
+-- in the way that the rules make them (see haskell.bzl):
+--
+-- - The early db, pdb, names no library. Its import directory is the one
+--   that p's interfaces are written to.
+-- - The final db, pfinal, names p's library (see linkP) as one of its
+--   extra-libraries, and gives the directory it is in.
+registerP :: Config -> FilePath -> [Int] -> IO ()
+registerP _ _ [] = pure ()
+registerP cfg dir ps = do
+  let common = "name: p\nversion: 0\nid: p\nkey: p\nexposed: True\nexposed-modules: " ++ unwords (map modName ps) ++ "\nimport-dirs: " ++ dir </> outDir pkgP ++ "\n"
+  forM_ [("pdb", common), ("pfinal", common ++ "library-dirs: " ++ dir </> "plib" ++ "\nextra-libraries: p\ndynamic-library-dirs: " ++ dir </> "plib" ++ "\n")] $ \(db, conf) -> do
+    removePathForcibly (dir </> db)
+    writeFile (dir </> db <.> "conf") conf
+    _ <- readProcess (ghcPkgOf (cGhc cfg)) ["init", dir </> db] ""
+    -- --force, because ghc-pkg refuses a package whose interfaces and
+    -- library don't exist yet. It still warns about them, so we ignore its
+    -- output.
+    _ <- readProcessWithExitCode (ghcPkgOf (cGhc cfg)) ["register", "--force", "--package-db", dir </> db, dir </> db <.> "conf"] ""
+    pure ()
+
+-- | Link p's library, libp.so, from p's objects in the given directory, as
+-- the rules link a library, with a soname. It returns the library's
+-- contents. As in the rules, a module whose splice loads the library has it
+-- as a plain input, so the test needs the contents to decide whether the
+-- module is up to date.
+linkP :: Config -> FilePath -> [Int] -> IO B.ByteString
+linkP cfg dir ps = do
+  createDirectoryIfMissing True (dir </> "plib")
+  let lib = dir </> "plib" </> "libp.so"
+  callProcess (cGhc cfg) (["-shared", "-dynamic", "-hide-all-packages", "-package", "base", "-o", lib, "-optl-Wl,-soname,libp.so"] ++ [dir </> outDir pkgP </> modName i <.> "o" | i <- ps])
+  B.readFile lib
+
+writeFileIfChanged :: FilePath -> String -> IO ()
+writeFileIfChanged path s = do
+  old <- (Just <$> readFile' path) `catchAny` pure Nothing
+  unless (old == Just s) (writeFile path s)
+  where
+    readFile' p = do t <- readFile p; length t `seq` pure t
+
+-- | Sort the nodes into layers, so that each node's dependencies are all in
+-- earlier layers. Also returns the nodes that couldn't be placed, because
+-- they are in a cycle or depend on one.
+layers :: (Node -> [Node]) -> [Node] -> ([[Node]], [Node])
+layers deps = go M.empty
+  where
+    go _ [] = ([], [])
+    go done pending =
+      let ready = [n | n <- pending, all (`M.member` done) (deps n)]
+       in if null ready then ([], pending) else let (rest, left) = go (M.union done (M.fromList [(n, ()) | n <- ready])) (filter (`notElem` ready) pending) in (ready : rest, left)
+
+-- | Run one build through a fresh worker. Each node is sent as soon as the
+-- nodes it waits for are done, as buck2 sends them. Returns each node's
+-- outcome, and the nodes that were skipped because they were up to date.
+-- For a module whose splice runs p's code, p's library is an input too, so
+-- the module is out of date if the library has changed since the worker
+-- last compiled it.
+workerBuild :: Config -> History -> Build -> M.Map Int Mod -> IORef LastOk -> IORef (M.Map Node B.ByteString) -> IORef Stats -> IO (M.Map Node Outcome, [Node])
+workerBuild cfg h b mods lastOk libSeen stats = do
+  let wdir = cDir cfg </> "w"
+  -- Each build overwrites the worker's log, so after a failure the log of
+  -- the failing build is left to look at.
+  logH <- openFile (wdir </> "worker.log") WriteMode
+  -- A one-shot history has no boot files, so auto gives every target a
+  -- one-shot session.
+  let mode = if cOneShot cfg then "auto" else "make"
+  withWorkerProcess (cWorker cfg) [] wdir ([("TMPDIR", wdir </> "tmp"), ("BUCK2_GHC_WORKER_VERBOSE", "1"), ("BUCK2_GHC_WORKER_SESSION_MODE", mode)] ++ [("BUCK2_GHC_WORKER_SESSIONS", "0") | bEagerDrop b]) (UseHandle logH) $ \sock -> do
+      skippedRef <- newIORef []
+      -- p's library is linked at most once in each build, by the first
+      -- module whose splice needs it. All of p's modules are compiled by
+      -- then, because such a module waits for them (see nodeDeps).
+      libVar <- newMVar Nothing
+      let pLib = modifyMVar libVar $ \l -> case l of
+            Just c -> pure (l, c)
+            Nothing -> (\c -> (Just c, c)) <$> linkP cfg wdir [k | k <- M.keys mods, inP k]
+      vars <- M.fromList <$> forM (nodes mods) (\node -> (,) node <$> newEmptyMVar)
+      let result node = readMVar (vars M.! node) >>= either (\(e :: SomeException) -> throwIO e) pure
+      forM_ (nodes mods) $ \node -> forkIO $ do
+        r <- try $ do
+          deps <- mapM result (nodeDeps mods node)
+          decide wdir sock skippedRef pLib (all isCompiled deps) node
+        putMVar (vars M.! node) r
+      (,) . M.fromList <$> forM (nodes mods) (\node -> (,) node <$> result node) <*> readIORef skippedRef
+  where
+    count = update stats
+    -- Each node's compile runs in a thread of its own, so the shared
+    -- records must be updated atomically.
+    update r f = atomicModifyIORef' r (\x -> (f x, ()))
+    decide wdir sock skippedRef pLib depsOk node@(i, boot)
+      | not depsOk = do
+          update lastOk (M.delete node)
+          count (\st -> st{sBlocked = sBlocked st + 1})
+          pure Blocked
+      | otherwise = do
+          let src = render mods node
+          -- If the module's splice loads p's library, the library is a plain
+          -- input of the compile, which the dep file doesn't list. So it is
+          -- recorded in lastOk alongside the files that the dep file lists.
+          -- libSeen only counts the library's changes for the coverage
+          -- checks.
+          lib <- if not boot && splicesP (mods M.! i) then (\c -> [("plib/libp.so", Just c)]) <$> pLib else pure []
+          forM_ [c | (_, Just c) <- lib] $ \c -> do
+            seen <- atomicModifyIORef' libSeen (\s -> (M.insert node c s, M.lookup node s))
+            when (maybe False (/= c) seen) $ count (\st -> st{sLibChanged = sLibChanged st + 1})
+          previous <- M.lookup node <$> readIORef lastOk
+          upToDate <- case previous of
+            Just (s, deps) | s == src -> and <$> mapM (\(f, c) -> (== c) <$> contents (wdir </> f)) deps
+            _ -> pure False
+          if upToDate
+            then count (\st -> st{sSkipped = sSkipped st + 1}) >> update skippedRef (node :) >> current wdir node
+            else do
+              -- Compiling one of these modules takes a second or two, so a
+              -- request that takes minutes means the worker has hung.
+              answer <- timeout 120000000 (grpc sock (request node))
+              (code, err) <- maybe (fail ("the worker didn't answer " ++ nodeName node ++ " in two minutes (see " ++ (wdir </> "worker.log") ++ ")")) pure answer
+              when (isJust previous) $ count (\st -> st{sRecompiled = sRecompiled st + 1})
+              if code /= 0
+                then do
+                  update lastOk (M.delete node)
+                  count (\st -> st{sFailed = sFailed st + 1})
+                  pure (Failed err)
+                else do
+                  deps <- lines <$> readFile (wdir </> depFile node)
+                  cs <- mapM (contents . (wdir </>)) deps
+                  update lastOk (M.insert node (src, zip deps cs ++ lib))
+                  current wdir node
+    contents f = (Just <$> B.readFile f) `catchAny` pure Nothing
+    current wdir node@(i, _) = do
+      let out ext = wdir </> outDir i </> modName i <.> (ext ++ suffix node)
+      us <- if cObjects cfg then pure [] else usagesOf <$> readProcess (cGhc cfg) ["--show-iface", out "hi"] ""
+      Compiled . trim <$> readFile (out "abi") <*> B.readFile (out "o") <*> pure us
+    -- Named after the package as well as the module, since a module of
+    -- each package may have the same name.
+    depFile node@(i, _) = "dep" </> (if inP i then "p-" else "") ++ nodeName node <.> "dep"
+    request node@(i, boot) =
+      [ "--request", "--contract", contract, "--libdir", cLibdir cfg
+      , "--depfile", depFile node, "--abi", outDir i </> modName i <.> ("abi" ++ suffix node), "--diagnostics", outDir i </> modName i <.> ("diag" ++ suffix node), "--module", modName i
+      , "--source", source node, "--outdir", outDir i, "--hisuf", "hi", "--srcroot=" ++ srcDir i
+      ] ++ ["--boot" | boot] ++ ["--loadable=" ++ modName k | not boot, isJust (mSplice (mods M.! i)), k <- closureOf mods i]
+      ++ ["--hidir=p=" ++ outDir pkgP | not (inP i)]
+      ++ ["--", cGhc cfg] ++ commonFlags h ++ nodeFlags mods node ++ ["-fforce-recomp"] ++ ["-fobject-determinism" | cObjects cfg]
+      ++ ["--", "-c", source node, "-o", outDir i </> modName i <.> ("o" ++ suffix node), "-ohi", outDir i </> modName i <.> ("hi" ++ suffix node)]
+
+-- | A clean build of the same sources, with one `ghc -c` per node.
+refBuild :: Config -> History -> M.Map Int Mod -> IO (M.Map Node Outcome)
+refBuild cfg h mods = do
+  let rdir = cDir cfg </> "ref"
+  removePathForcibly rdir
+  mapM_ (createDirectoryIfMissing True . (rdir </>)) ["src", outDir 0, "psrc", outDir pkgP]
+  registerP cfg rdir [i | i <- M.keys mods, inP i]
+  forM_ (nodes mods) $ \node -> writeFile (rdir </> source node) (render mods node)
+  outcomes <- newIORef M.empty
+  linked <- newIORef False
+  forM_ (concat (fst (layers (nodeDeps mods) (nodes mods)))) $ \node@(i, boot) -> do
+    done <- readIORef outcomes
+    outcome <-
+      if any (\d -> not (maybe False isCompiled (M.lookup d done))) (nodeDeps mods node)
+        then pure Blocked
+        else do
+          already <- readIORef linked
+          when (not boot && splicesP (mods M.! i) && not already) $ do
+            _ <- linkP cfg rdir [k | k <- M.keys mods, inP k]
+            writeIORef linked True
+          let flags = commonFlags h ++ nodeFlags mods node ++ ["-fobject-determinism" | cObjects cfg]
+          (code, _, err) <- readCreateProcessWithExitCode (proc (cGhc cfg) (["-c", source node, "-odir", outDir i, "-hidir", outDir i] ++ flags)){cwd = Just rdir} ""
+          case code of
+            ExitSuccess -> do
+              iface <- readProcess (cGhc cfg) ["--show-iface", rdir </> outDir i </> modName i <.> ("hi" ++ suffix node)] ""
+              Compiled (abiOf iface) <$> B.readFile (rdir </> outDir i </> modName i <.> ("o" ++ suffix node)) <*> pure (if cObjects cfg then [] else usagesOf iface)
+            _ -> pure (Failed err)
+    modifyIORef' outcomes (M.insert node outcome)
+  readIORef outcomes
+  where
+    abiOf iface = case [w | l <- lines iface, "ABI" : "hash:" : w : _ <- [words l]] of
+      a : _ -> a
+      [] -> "?"
+
+-- | The usages of imported modules in the text that `ghc --show-iface`
+-- prints, which are lines of the form "import -/ M hash". Since GHC 9.14 the
+-- first of them is on the "usages:" line itself. Before GHC 9.12, whose
+-- objects aren't deterministic and so aren't compared, the usages show what
+-- a module was compiled against, which its ABI hash doesn't.
+usagesOf :: String -> [String]
+usagesOf iface = [unwords u | l <- lines iface, u@("import" : "-/" : _) <- [dropWhile (/= "import") (words l)]]
+
+catchAny :: forall a. IO a -> IO a -> IO a
+catchAny a b = (try a :: IO (Either SomeException a)) >>= either (const b) pure
+
+trim :: String -> String
+trim = reverse . dropWhile (`elem` ("\r\n " :: String)) . reverse
+
+main :: IO ()
+main = do
+  worker <- fromMaybe "buck2-ghc-worker" <$> lookupEnv "BUCK2_GHC_WORKER"
+  ghc <- fromMaybe "ghc" <$> lookupEnv "GHC"
+  version <- trim <$> readProcess ghc ["--numeric-version"] ""
+  when (version /= showVersion fullCompilerVersion) $ do
+    hPutStrLn stderr ("the props were built with GHC " ++ showVersion fullCompilerVersion ++ " but `" ++ ghc ++ "` is " ++ version ++ ": set GHC")
+    exitFailure
+  libdir <- trim <$> readProcess ghc ["--print-libdir"] ""
+  tmp <- getTemporaryDirectory
+  pid <- getProcessID
+  let v = versionBranch fullCompilerVersion
+      cfg = Config worker ghc libdir (tmp </> ("buck2-ghc-worker-props-" ++ show pid)) (v >= [9, 12]) False
+      -- Each property has a directory of its own, because tasty runs them
+      -- at the same time.
+      oneShotCfg = cfg{cOneShot = True, cDir = cDir cfg ++ "-one-shot"}
+      bootCycleCfg = cfg{cDir = cDir cfg ++ "-boot-cycle"}
+      bootCycle2Cfg = cfg{cDir = cDir cfg ++ "-boot-cycle-2"}
+  -- If a property fails, its directory is kept, so that we can look at
+  -- what the failing history built.
+  let tree = adjustOption (\(HedgehogTestLimit n) -> HedgehogTestLimit (n <|> Just 30)) . askOption $ \(HedgehogTestLimit n) ->
+        -- Test both of the worker's explicit session modes (see Note
+        -- [One-shot sessions] in the worker's Session), rather than the
+        -- default, auto, which mixes them. With --make sessions the
+        -- histories may have boot files. With one-shot sessions they have
+        -- none, since the worker refuses targets with boot files in that
+        -- mode.
+        testGroup
+          "a history built through the worker agrees with clean ghc -c builds"
+          [ testPropertyNamed "with --make sessions" "historyMake" (historyProp cfg (maybe 30 fromIntegral n))
+          , testPropertyNamed "with one-shot sessions" "historyOneShot" (historyProp oneShotCfg (maybe 30 fromIntegral n))
+          , fixed (testPropertyNamed "a boot file cycle rebuilt with -O" "bootCycle" (fixedHistory bootCycleCfg bootCycle))
+          , fixed (testPropertyNamed "a second boot file cycle rebuilt with -O" "bootCycle2" (fixedHistory bootCycle2Cfg bootCycle2))
+          ]
+  defaultMain tree `catch` \code -> do
+    when (code == ExitSuccess) (mapM_ (removePathForcibly . cDir) [cfg, oneShotCfg, bootCycleCfg, bootCycle2Cfg])
+    throwIO code
+
+-- | Run a property that doesn't generate anything only once. main sets
+-- tasty-hedgehog's test limit for all the properties, and that limit
+-- overrides a property's own withTests, so we set it back to 1 here.
+fixed :: TestTree -> TestTree
+fixed = localOption (HedgehogTestLimit (Just 1))
+
+-- | A property that the given history, built through a worker of the given
+-- configuration, agrees with clean builds. Nothing is generated, so it
+-- only needs to run once (see 'fixed').
+fixedHistory :: Config -> History -> Property
+fixedHistory cfg h = withTests 1 . property $ do
+  (result, _) <- liftIO (runHistory cfg h)
+  either (\err -> annotate err >> failure) (const success) result
+
+-- | A fixed history with import cycles through boot files. M1 imports M4
+-- through M4's boot file, and M4 imports M1. M0 imports M1 through M1's
+-- boot file. M5 imports M0, and M2, which imports M1. With -O, after another
+-- edit to a comment in M0, M5 must compile in the second build as it did in
+-- the first.
+bootCycle :: History
+bootCycle =
+  History
+    { hOptimise = True
+    , hModules =
+        [ (0, plain{mSourceImports = [1]})
+        , (1, plain{mSourceImports = [4], mBoot = True})
+        , (2, plain{mImports = [1]})
+        , (3, plain)
+        , (4, plain{mImports = [1], mBoot = True})
+        , (5, plain{mImports = [0, 2]})
+        ]
+    , hBuilds = [Build [Comment 0] False, Build [Comment 0] False]
+    }
+  where
+    plain = Mod [] [] [(0, TInt, 0)] False Nothing 0 0 False False [] []
+
+-- | A second fixed history with a boot file cycle. M1 imports M2 through
+-- M2's boot file, and M1's INLINE value t1 uses M2. M2 imports M0, which
+-- imports M1 through M1's boot file. M3 imports M1. M5 imports M2, and also
+-- M3, through an edit before the first build. With -O, M3's interface has an
+-- unfolding that mentions M2 through t1, though M3 doesn't import M2. After
+-- an edit to a comment in M0, M5 must compile in the second build as it did
+-- in the first.
+bootCycle2 :: History
+bootCycle2 =
+  History
+    { hOptimise = True
+    , hModules =
+        [ (0, plain{mSourceImports = [1]})
+        , (1, plain{mSourceImports = [2], mBoot = True, mSplice = Just 1})
+        , (2, plain{mImports = [0], mBoot = True})
+        , (3, plain{mImports = [1], mSplice = Just 6})
+        , (4, plain)
+        , (5, plain{mImports = [2]})
+        ]
+    , hBuilds = [Build [AddImport 5 3] False, Build [Comment 0] False]
+    }
+  where
+    plain = Mod [] [] [(0, TInt, 0)] False Nothing 0 0 False False [] []
+
+-- | The property that generated histories built through the worker agree
+-- with clean builds. The argument is the number of histories to run, which
+-- decides whether the coverage minimums are checked.
+historyProp :: Config -> Int -> Property
+historyProp cfg tests =
+  -- Allow only a few shrinks, since each one runs a whole history, which
+  -- takes a minute or more.
+  withShrinks 30 . property $ do
+    h <- forAll (genHistory (not (cOneShot cfg)))
+    (result, st) <- liftIO (runHistory cfg h)
+    -- Check how often the histories include the cases they are meant to
+    -- test, judged from the package as first generated. A minimum catches a
+    -- generator that has stopped producing a case. Each minimum is far
+    -- enough below the case's usual share that 30 histories fall short of
+    -- one only about once in 3,000 runs. With fewer than 30 histories, the
+    -- cases are only counted, not checked.
+    let mods = compiledAs (M.fromList (hModules h))
+        ms = M.elems mods
+        sourced j = not (null (mSourceImports (mods M.! j)))
+        cover' p l b = if tests >= 30 then cover p l b else classify l b
+    cover' 50 "a module skipped as up to date" (sSkipped st > 0)
+    cover' 40 "a module compiled again" (sRecompiled st > 0)
+    cover' 25 "a module failed" (sFailed st > 0)
+    cover' 15 "a module blocked by a failed import" (sBlocked st > 0)
+    cover' 25 "a module with a session of its own" (any mOwnFlags ms)
+    unless (cOneShot cfg) $ do
+      cover' 25 "a boot file" (any mBoot ms)
+      cover' 10 "a SOURCE import" (any (not . null . mSourceImports) ms)
+      cover' 10 "an import of a module with SOURCE imports" (any (any sourced . filter (not . inP) . mImports) ms)
+    cover' 10 "a splice" (any (isJust . mSplice . snd) (hModules h))
+    -- (Fewer: see compiledAs.)
+    classify "a splice compiled" (any (isJust . mSplice) ms)
+    unless (cOneShot cfg) $ classify "a splice in a module with a boot file" (any (\m -> mBoot m && isJust (mSplice m)) ms)
+    cover' 10 "an import from p" (any (any inP . mImports) ms)
+    (if pSplices then cover' 10 else classify) "a splice that runs p's code, from p's library" (any splicesP ms)
+    -- This case is only classified, not given a minimum coverage, because
+    -- it happens in only about one history in eight. That is too rare for
+    -- any minimum that 30 histories reliably meet.
+    classify "p's library changed under a module whose splice loads it" (sLibChanged st > 0)
+    cover' 10 "a module of p with the name of one of the main package" (any (\i -> i >= pkgClash && i - pkgClash < M.size (M.filterWithKey (\k _ -> not (inP k)) mods)) (M.keys mods))
+    cover' 10 "a value used through a re-export" (any (any (\j -> any (`elem` mImports (mods M.! j)) (mReexports (mods M.! j))) . mImports) ms)
+    cover' 45 "sessions dropped as soon as idle" (any bEagerDrop (hBuilds h))
+    cover' 25 "a module with OPTIONS_GHC flags" (any (not . null . mOptions) ms)
+    case result of
+      Right () -> success
+      Left err -> annotate err >> failure
diff --git a/buck2/prelude/haskell/tools/worker/src/Compat.hs b/buck2/prelude/haskell/tools/worker/src/Compat.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/Compat.hs
@@ -0,0 +1,287 @@
+{-# LANGUAGE CPP #-}
+-- GHC 9.14 deprecates replacing an environment's home package table, and
+-- emptyHome has to do that to give an environment an empty table.
+{-# OPTIONS_GHC -Wno-deprecations #-}
+-- | Wrappers for the parts of the GHC API that differ between the GHC
+-- versions that the worker can be built with (9.6 to 10.1). Keeping the CPP
+-- in this module lets the rest of the worker do without it.
+module Compat
+  ( analyseTargets
+  , sharedFileHashes
+  , withFileHashes
+  , emptyHome
+  , withModuleGraph
+  , withOneShotModuleGraph
+  , insertHome
+  , addHomes
+  , interpreterLock
+  , useUnitDbs
+  , unitDbsRead
+  , LocationFile (..)
+  , setLocationFile
+  , summariseSource
+  , throwDriverErrors
+  , pkgDbRefPath
+  ) where
+
+#if MIN_VERSION_ghc(9,12,0)
+import Control.Concurrent.MVar (newMVar, withMVar)
+#else
+import Control.Concurrent.MVar (MVar, newMVar)
+#endif
+
+import GHC
+import GHC.Unit.Finder (initFinderCache)
+import GHC.Unit.Finder.Types (FinderCache (..))
+import GHC.Driver.Main (initModDetails)
+import GHC.Unit.Home.ModInfo (HomeModInfo (..), HomeModLinkable)
+import GHC.Unit.Env (UnitEnv (..))
+import GHC.Unit.State (UnitDatabase (..))
+import GHC.Unit.Types (UnitId)
+import GHC.Driver.Errors.Types (DriverMessages, GhcMessage (..))
+import GHC.Driver.Make (summariseFile)
+import GHC.Driver.Env (hsc_home_unit)
+import GHC.Driver.Session (PkgDbRef (..))
+import GHC.Types.SourceError (throwErrors)
+#if MIN_VERSION_ghc(10,0,0)
+import GHC.Data.OsPath (unsafeDecodeUtf)
+import GHC.Driver.Env (hsc_dflags)
+#endif
+import qualified Data.Map as M
+#if MIN_VERSION_ghc(10,1,0)
+import Data.IORef (newIORef)
+#endif
+#if MIN_VERSION_ghc(9,12,0)
+import GHC.Data.OsPath (unsafeEncodeUtf)
+#endif
+#if MIN_VERSION_ghc(10,1,0)
+import GHC.Unit.External.Database (lookupExternalUnitDatabases)
+import GHC.Unit.External.Index (cacheExternalUnitDatabase, readExternalUnitDatabases)
+#else
+import GHC.Unit.Env (HomeUnitEnv (..), ue_currentUnit, ue_unit_dbs, ue_updateHomeUnitEnv)
+#endif
+import GHC.Types.Error (isEmptyMessages)
+#if MIN_VERSION_ghc(9,14,0)
+import GHC.Types.Error (mkUnknownDiagnostic)
+import GHC.Driver.Downsweep (downsweepThunk)
+import GHC.Driver.Env (hscUpdateHPT, hsc_HPT, setModuleGraph)
+import GHC.Unit.Home.PackageTable (addHomeModInfoToHpt, emptyHomePackageTable)
+import Control.Monad (forM)
+#if MIN_VERSION_ghc(10,0,0)
+import GHC.Types.SourceError (initSourceErrorContext)
+#endif
+#else
+import GHC.Driver.Env (hscUpdateHPT, hsc_mod_graph)
+import GHC.Unit.Home.ModInfo (addListToHpt, addToHpt, emptyHomePackageTable)
+import System.IO (fixIO)
+#endif
+
+-- | Run GHC's dependency analysis of the session's targets, and return
+-- whether it found no errors. If it found any, GHC leaves the session's
+-- module graph empty.
+analyseTargets :: Ghc Bool
+#if MIN_VERSION_ghc(9,14,0)
+analyseTargets = isEmptyMessages . fst <$> depanalE mkUnknownDiagnostic Nothing [] True
+#else
+analyseTargets = isEmptyMessages . fst <$> depanalE [] True
+#endif
+
+-- | Make a finder cache to hold the file hashes that all the sessions share
+-- (see Note [Hashing the libraries] in Session). From GHC 9.12, it looks up
+-- each hash under a lock, so that when two compiles need the same hash at
+-- the same time, only one of them computes it. Before GHC 9.12, the finder
+-- cache's `lookupFileCache` can't be replaced, so there is no lock.
+sharedFileHashes :: IO FinderCache
+sharedFileHashes = do
+  fc <- initFinderCache
+#if MIN_VERSION_ghc(9,12,0)
+  lock <- newMVar ()
+  pure fc{lookupFileCache = \f -> withMVar lock (\_ -> lookupFileCache fc f)}
+#else
+  pure fc
+#endif
+
+-- | Make a session's finder cache (the second argument) use the shared file
+-- hashes of the first, which 'sharedFileHashes' made, instead of its own.
+withFileHashes :: FinderCache -> FinderCache -> FinderCache
+#if MIN_VERSION_ghc(9,12,0)
+withFileHashes shared fc = fc{lookupFileCache = lookupFileCache shared}
+#else
+withFileHashes shared fc = fc{fcFileCache = fcFileCache shared}
+#endif
+
+-- | Give the environment an empty home package table of its own. Before
+-- GHC 9.14 the table is an immutable value. From 9.14 it is mutable, so a
+-- new table has to be created.
+emptyHome :: HscEnv -> IO HscEnv
+#if MIN_VERSION_ghc(9,14,0)
+emptyHome hsc = (\hpt -> hscUpdateHPT (const hpt) hsc) <$> emptyHomePackageTable
+#else
+emptyHome = pure . hscUpdateHPT (const emptyHomePackageTable)
+#endif
+
+-- | Replace the environment's module graph.
+withModuleGraph :: ModuleGraph -> HscEnv -> HscEnv
+#if MIN_VERSION_ghc(9,14,0)
+withModuleGraph = setModuleGraph
+#else
+withModuleGraph mg hsc = hsc{hsc_mod_graph = mg}
+#endif
+
+-- | Give the environment the module graph that `ghc -c` would have when it
+-- compiles the given module in one-shot mode. From GHC 9.14, that is the
+-- graph of the modules below the module, which GHC only builds if the
+-- compile needs it. For example, a module with explicit level imports needs
+-- it to find out at which levels it sees an instance. Before GHC 9.14,
+-- `ghc -c` has no module graph, so the environment is left as it is.
+withOneShotModuleGraph :: HscEnv -> ModSummary -> IO HscEnv
+#if MIN_VERSION_ghc(9,14,0)
+withOneShotModuleGraph hsc ms = (`setModuleGraph` hsc) <$> downsweepThunk hsc ms
+#else
+withOneShotModuleGraph hsc _ = pure hsc
+#endif
+
+-- | Add a module's entry to the environment's home package table. Before
+-- GHC 9.14 this returns an environment with a new table. From 9.14 the table
+-- is mutable, and this changes it in place.
+insertHome :: HscEnv -> ModuleName -> HomeModInfo -> IO HscEnv
+#if MIN_VERSION_ghc(9,14,0)
+insertHome hsc _ hmi = addHomeModInfoToHpt hmi (hsc_HPT hsc) >> pure hsc
+#else
+insertHome hsc mn hmi = pure (hscUpdateHPT (\hpt -> addToHpt hpt mn hmi) hsc)
+#endif
+
+-- | Add home modules to the environment's home package table, making their
+-- entries from their interfaces. The modules are either a single module, or
+-- a group of modules that import one another through boot files. Each
+-- module's entry is typechecked lazily, against the table with the whole
+-- group in it, so that the modules can refer to one another. GHC's --make
+-- does the same for a cycle of modules once it has compiled them (see
+-- typecheckLoop in GHC). It returns the new environment and the entries.
+addHomes :: HscEnv -> [(ModIface, HomeModLinkable)] -> IO (HscEnv, [HomeModInfo])
+#if MIN_VERSION_ghc(9,14,0)
+-- The table is mutable, so when a module's entry is typechecked, which
+-- happens lazily, it finds the entries of the whole group in the table.
+addHomes hsc mods = do
+  hmis <- forM mods $ \(iface, linkable) -> do
+    details <- initModDetails hsc iface
+    let hmi = HomeModInfo iface details linkable
+    addHomeModInfoToHpt hmi (hsc_HPT hsc)
+    pure hmi
+  pure (hsc, hmis)
+#else
+addHomes hsc mods = do
+  -- Each module's details are typechecked against the table that holds all
+  -- the modules' entries, so the table and the details are made together
+  -- with fixIO. That works because a table entry is strict in everything
+  -- except its details, and nothing forces the details while the table is
+  -- being made.
+  (env, details) <- fixIO $ \ ~(_, details) -> do
+    let env = hscUpdateHPT (\hpt -> addListToHpt hpt [(moduleName (mi_module iface), HomeModInfo iface (details !! k) linkable) | (k, (iface, linkable)) <- zip [0 ..] mods]) hsc
+    (,) env <$> mapM (initModDetails env . fst) mods
+  pure (env, [HomeModInfo iface d linkable | ((iface, linkable), d) <- zip mods details])
+#endif
+
+-- | Make the lock that a session's compiles take in turn, or return Nothing
+-- if they need none. The compiles of a session run concurrently and share
+-- the session's external interpreter, if the flags ask for one. Before GHC
+-- 9.12, GHC sends the interpreter a message and then reads its reply
+-- without taking a lock, so two compiles could read each other's replies.
+-- One way this shows up is as a panic in mallocStrings. From GHC 9.12, GHC
+-- locks the interpreter itself, so the compiles need no lock of their own.
+#if MIN_VERSION_ghc(9,12,0)
+interpreterLock :: DynFlags -> IO (Maybe a)
+interpreterLock _ = pure Nothing
+#else
+interpreterLock :: DynFlags -> IO (Maybe (MVar ()))
+interpreterLock dflags = if gopt Opt_ExternalInterpreter dflags then Just <$> newMVar () else pure Nothing
+#endif
+
+-- | Give a new session's unit environment the package databases that the
+-- worker has read already. When the session's flags are set, GHC then uses
+-- these instead of reading the databases from disk (see Note [One copy of
+-- each package database] in Session).
+useUnitDbs :: [UnitDatabase UnitId] -> UnitEnv -> IO UnitEnv
+
+-- | The package databases at the given paths that GHC read when the
+-- session's flags were set, if it read all of them.
+unitDbsRead :: [FilePath] -> UnitEnv -> IO (Maybe [UnitDatabase UnitId])
+
+#if MIN_VERSION_ghc(10,1,0)
+-- From GHC 10.1, a unit environment has a cache of the databases that GHC
+-- has read, keyed by path (ue_uic). GHC looks there before it reads a
+-- database. Each session has a cache of its own, so the worker adds the
+-- databases to the session's cache, and looks there for the ones GHC read.
+-- If GHC also read the user's database, it is in the cache too, but the
+-- worker doesn't keep it, because it isn't one of the paths.
+useUnitDbs dbs ue = ue <$ mapM_ (cacheExternalUnitDatabase (ue_uic ue)) dbs
+unitDbsRead paths ue = do
+  cached <- readExternalUnitDatabases (ue_uic ue)
+  pure (mapM (\p -> lookupExternalUnitDatabases (unsafeEncodeUtf p) cached) paths)
+#else
+-- Before GHC 10.1, the current unit's databases are kept in its home unit
+-- environment, and GHC reads them only if there are none there yet. If GHC
+-- also read the user's database, the databases it read don't match the
+-- paths, and none of them are returned.
+useUnitDbs dbs ue = pure (ue_updateHomeUnitEnv (\hue -> hue{homeUnitEnv_unit_dbs = Just dbs}) (ue_currentUnit ue) ue)
+unitDbsRead paths ue = pure $ case ue_unit_dbs ue of
+  Just dbs | map unitDatabasePath dbs == paths -> Just dbs
+  _ -> Nothing
+#endif
+
+-- | The output files of a module's location.
+data LocationFile = HiFile | DynHiFile | ObjFile | DynObjFile | HieFile
+
+-- | Set one of the output files of a module's location. From GHC 9.12, the
+-- location's fields are OsPaths. GHC 10.0 removed the pattern synonym that
+-- let them be set as FilePaths.
+setLocationFile :: LocationFile -> FilePath -> ModLocation -> ModLocation
+#if MIN_VERSION_ghc(9,12,0)
+setLocationFile file path loc = case file of
+  HiFile -> loc{ml_hi_file_ospath = p}
+  DynHiFile -> loc{ml_dyn_hi_file_ospath = p}
+  ObjFile -> loc{ml_obj_file_ospath = p}
+  DynObjFile -> loc{ml_dyn_obj_file_ospath = p}
+  HieFile -> loc{ml_hie_file_ospath = p}
+  where
+    p = unsafeEncodeUtf path
+#else
+setLocationFile file path loc = case file of
+  HiFile -> loc{ml_hi_file = path}
+  DynHiFile -> loc{ml_dyn_hi_file = path}
+  ObjFile -> loc{ml_obj_file = path}
+  DynObjFile -> loc{ml_dyn_obj_file = path}
+  HieFile -> loc{ml_hie_file = path}
+#endif
+
+-- | Summarise a module's source file, as GHC's dependency analysis does,
+-- without any summaries from before. From GHC 10.1, summariseFile keeps its
+-- cache of summaries in an IORef.
+summariseSource :: HscEnv -> FilePath -> IO (Either DriverMessages ModSummary)
+#if MIN_VERSION_ghc(10,1,0)
+summariseSource hsc src = do
+  cache <- newIORef M.empty
+  summariseFile hsc (hsc_home_unit hsc) cache src Nothing Nothing
+#else
+summariseSource hsc src = summariseFile hsc (hsc_home_unit hsc) M.empty src Nothing Nothing
+#endif
+
+-- | Throw the driver's errors as a SourceError. From GHC 10.0, a
+-- SourceError carries the context in which to report its messages.
+throwDriverErrors :: HscEnv -> DriverMessages -> IO a
+#if MIN_VERSION_ghc(10,0,0)
+throwDriverErrors hsc = throwErrors (initSourceErrorContext (hsc_dflags hsc)) . fmap GhcDriverMessage
+#else
+throwDriverErrors _ = throwErrors . fmap GhcDriverMessage
+#endif
+
+-- | The path of the package database that a -package-db flag names, or
+-- Nothing for the global and the user's databases. From GHC 10.0, the path
+-- is an OsPath.
+pkgDbRefPath :: PkgDbRef -> Maybe FilePath
+#if MIN_VERSION_ghc(10,0,0)
+pkgDbRefPath (PkgDbPath p) = Just (unsafeDecodeUtf p)
+#else
+pkgDbRefPath (PkgDbPath p) = Just p
+#endif
+pkgDbRefPath _ = Nothing
diff --git a/buck2/prelude/haskell/tools/worker/src/Contract.hs b/buck2/prelude/haskell/tools/worker/src/Contract.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/Contract.hs
@@ -0,0 +1,9 @@
+-- | The version of the request that the rules send, and of the files that
+-- the worker writes back. Each request names the version that the rules use
+-- (_WORKER_CONTRACT in compile_per_module.bzl). A worker or compile tool
+-- that was built from another version of the rules then reports the
+-- mismatch, rather than misreading the request.
+module Contract (contract) where
+
+contract :: String
+contract = "7"
diff --git a/buck2/prelude/haskell/tools/worker/src/DepFile.hs b/buck2/prelude/haskell/tools/worker/src/DepFile.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/DepFile.hs
@@ -0,0 +1,77 @@
+-- | Writing the files that the compile tool and the worker produce besides
+-- GHC's own outputs: a module's .abi file, and its buck2 dep file.
+module DepFile (writeDepFiles) where
+
+import Control.Monad (filterM, forM, unless)
+import Data.List (isPrefixOf)
+import qualified Data.Set as Set
+import System.Directory (canonicalizePath, doesFileExist, getCurrentDirectory)
+import System.FilePath (dropExtension, makeRelative, takeDirectory, takeFileName, (<.>), (</>))
+
+import GHC (moduleName, moduleNameString, moduleUnit)
+import GHC.Unit.Module.Deps (Usage (..), dep_direct_mods)
+import GHC.Unit.Module.ModIface (ModIface, mi_deps)
+import GHC.Unit.Types (GenWithIsBoot (..), IsBootInterface (..), unitString)
+import GHC.Utils.Fingerprint (Fingerprint)
+import GHC.Utils.Panic (GhcException (ProgramError), throwGhcExceptionIO)
+
+import Interface (abiHash, directDep, usageFile, usageLoadedModule, usages)
+import Request
+
+-- | Write a compiled module's ABI file and dep file, from its interface. The
+-- ABI file has the interface's ABI hash. The dep file lists the usages GHC
+-- recorded for its own recompilation check: the imported modules, as their
+-- .abi files, and the files a splice loaded. See Note [Early cut-off by dep
+-- files] in compile_per_module.bzl.
+writeDepFiles :: Request -> ModIface -> IO ()
+writeDepFiles r iface = do
+  writeFile (reqAbi r) (show (abiHash iface :: Fingerprint) ++ "\n")
+  cwd <- getCurrentDirectory
+  -- A module that is only imported {-# SOURCE #-} is listed as its boot
+  -- file's .abi-boot.
+  let direct = [(gwib_mod d, gwib_isBoot d) | (_, d) <- map directDep (Set.toList (dep_direct_mods (mi_deps iface)))]
+      ext m = if (m, IsBoot) `elem` direct && (m, NotBoot) `notElem` direct then "abi-boot" else "abi"
+  -- Without usages, the dep file would say the module read nothing, and it
+  -- would never compile again.
+  us <- maybe (throwGhcExceptionIO (ProgramError (modName ++ ": its interface records no usages, so its dep file can't say what it read: don't compile it with -fno-write-if-self-recomp"))) pure (usages iface)
+  -- Only the objects of the modules in this module's closure are inputs of
+  -- the compile, so a splice can't use a module that it reaches only
+  -- through a boot file (see Note [Template Haskell modules] in
+  -- compile_per_module.bzl). GHC might still find such a module's object in
+  -- the output directory, left by an earlier build, or the worker's session
+  -- might already hold the module's code. So we fail the compile if a
+  -- splice loaded such a module either way.
+  outDir <- canonicalizePath (reqOutDir r)
+  loaded <- fmap concat . forM us $ \u -> case usageFile u of
+    Just path -> do
+      ok <- doesFileExist path
+      -- Only the directory is canonicalized. A profiled compile's .dyn_o
+      -- files are links to the non-profiled compile's objects, so following
+      -- the link would take the path out of the output directory.
+      c <- if ok then (</> takeFileName path) <$> canonicalizePath (takeDirectory path) else pure path
+      pure [map (\ch -> if ch == '/' then '.' else ch) (dropExtension (makeRelative outDir c)) | (outDir ++ "/") `isPrefixOf` c]
+    Nothing -> pure [moduleNameString m | Just m <- [usageLoadedModule u]]
+  let reached = [m | m <- loaded, m `notElem` reqLoadable r]
+  unless (null reached) $
+    throwGhcExceptionIO (ProgramError (modName ++ ": a splice ran code of " ++ unwords reached ++ ", which " ++ modName ++ " reaches only through hs-boot files, and per_module doesn't support that: build the target with compile_granularity = \"target\""))
+  entries <- fmap concat . forM us $ \u -> case u of
+    UsageHomeModule{usg_mod_name = m} -> existing [reqOutDir r </> modFile m <.> ext m]
+    _ | Just m <- usageLoadedModule u -> existing [reqOutDir r </> modFile m <.> "abi"]
+    -- Looked up by its unit as well as its name, since a module of another
+    -- unit may have the same name.
+    UsagePackageModule{usg_mod = m} -> firstExisting (concat [[d </> modFile (moduleName m) <.> "abi", d </> modFile (moduleName m) <.> reqHisuf r] | (unit, d) <- reqHidirs r, unit == unitString (moduleUnit m)])
+    _ | Just path <- usageFile u -> do
+      -- Files outside the project (the libraries of GHC's own package db)
+      -- aren't inputs of the action.
+      ok <- doesFileExist path
+      if ok then (\c -> [c | isUnder cwd c]) <$> canonicalizePath path else pure []
+    _ -> pure []
+  self <- if reqBoot r then pure [] else existing [reqOutDir r </> reqModPath r <.> "abi-boot"]
+  rel <- mapM (fmap (makeRelative cwd) . canonicalizePath) (entries ++ self)
+  writeFile (reqDepfile r) (unlines rel)
+  where
+    modName = map (\c -> if c == '/' then '.' else c) (reqModPath r)
+    modFile = map (\c -> if c == '.' then '/' else c) . moduleNameString
+    existing = filterM doesFileExist
+    firstExisting = fmap (take 1) . existing
+    isUnder cwd p = (cwd ++ "/") `isPrefixOf` p
diff --git a/buck2/prelude/haskell/tools/worker/src/Grpc.hs b/buck2/prelude/haskell/tools/worker/src/Grpc.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/Grpc.hs
@@ -0,0 +1,335 @@
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+-- | A gRPC server for buck2's local worker protocol, using only the packages
+-- that come with GHC. It serves the unary call `/worker.Worker/Execute`
+-- over HTTP/2, on the Unix socket that buck2 names in WORKER_SOCKET. See
+-- Note [Just enough HTTP/2].
+module Grpc (serve) where
+
+import Control.Concurrent (ThreadId, forkIO, killThread)
+import Control.Concurrent.MVar
+import Control.Concurrent.STM
+import Control.Exception (SomeAsyncException, SomeException, bracket, evaluate, finally, fromException, throwIO, try)
+import Control.Monad (forM_, unless, void, when)
+import Data.Bits (shiftL, shiftR, testBit, (.&.), (.|.))
+import Data.ByteString (ByteString)
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Builder as BB
+import qualified Data.ByteString.Lazy as BL
+import qualified Data.Map.Strict as M
+import Data.Word (Word32, Word8)
+#if !defined(darwin_HOST_OS)
+import Data.Word (Word16)
+#endif
+import Foreign.C.Error (throwErrnoIfMinus1, throwErrnoIfMinus1Retry, throwErrnoIfMinus1_)
+import Foreign.C.Types (CInt (..), CUInt (..))
+import Foreign.Marshal.Alloc (allocaBytes)
+import Foreign.Marshal.Array (pokeArray)
+import Foreign.Marshal.Utils (copyBytes)
+import Foreign.Ptr (Ptr, castPtr, nullPtr, plusPtr)
+import Foreign.Storable (pokeByteOff)
+import qualified GHC.Foreign as GHC
+import GHC.IO.Encoding (getFileSystemEncoding)
+import GHC.IO.Handle.FD (fdToHandle)
+import System.IO (BufferMode (..), Handle, hClose, hFlush, hPutStrLn, hSetBinaryMode, hSetBuffering, stderr)
+import System.IO.Error (isEOFError, isResourceVanishedError)
+import System.Posix.IO (FdOption (CloseOnExec), setFdOption)
+import System.Posix.Types (Fd (..))
+
+import Proto
+
+-- | Serve requests on the Unix socket at the given path. For each request,
+-- the handler is given the argv of the command that buck2 asks the worker to
+-- run, and returns the command's exit code and stderr. This never returns.
+serve :: FilePath -> ([ByteString] -> IO (Int, ByteString)) -> IO ()
+serve path handler = bracket (listenUnix path) (throwErrnoIfMinus1_ "close" . c_close) $ \sock -> do
+  let loop = do
+        conn <- closeOnExec =<< throwErrnoIfMinus1Retry "accept" (c_accept sock nullPtr nullPtr)
+        void (forkIO (connection conn handler))
+        loop
+  loop
+
+-- * The socket
+
+foreign import ccall unsafe "socket" c_socket :: CInt -> CInt -> CInt -> IO CInt
+foreign import ccall unsafe "bind" c_bind :: CInt -> Ptr () -> CUInt -> IO CInt
+foreign import ccall unsafe "listen" c_listen :: CInt -> CInt -> IO CInt
+-- accept blocks until a client connects, so it is a safe call, which runs
+-- in an OS thread of its own.
+foreign import ccall safe "accept" c_accept :: CInt -> Ptr () -> Ptr CUInt -> IO CInt
+foreign import ccall unsafe "dup" c_dup :: CInt -> IO CInt
+foreign import ccall unsafe "close" c_close :: CInt -> IO CInt
+
+-- | Mark a file descriptor close-on-exec. The worker starts other programs,
+-- such as the external interpreter of each session, and they shouldn't hold
+-- the worker's sockets open.
+closeOnExec :: CInt -> IO CInt
+closeOnExec fd = setFdOption (Fd fd) CloseOnExec True >> pure fd
+
+-- | A socket listening on the Unix socket at the given path. A Unix socket's
+-- address (struct sockaddr_un) is its family and then its path, a C string
+-- in the file system's encoding. On Linux the family takes 2 bytes. On
+-- macOS a byte holding the address's length comes first, and then a byte of
+-- family.
+listenUnix :: FilePath -> IO CInt
+listenUnix path = do
+  sock <- closeOnExec =<< throwErrnoIfMinus1 "socket" (c_socket afUnix sockStream 0)
+  enc <- getFileSystemEncoding
+  allocaBytes addrSize $ \addr -> GHC.withCStringLen enc path $ \(cpath, len) -> do
+    when (len >= addrSize - pathOffset) $ ioError (userError ("buck2-ghc-worker: socket path too long: " ++ path))
+    pokeArray (addr `plusPtr` pathOffset) (replicate (addrSize - pathOffset) 0 :: [Word8])
+#if defined(darwin_HOST_OS)
+    pokeByteOff addr 0 (fromIntegral addrSize :: Word8)
+    pokeByteOff addr 1 (fromIntegral afUnix :: Word8)
+#else
+    pokeByteOff addr 0 (fromIntegral afUnix :: Word16)
+#endif
+    copyBytes (addr `plusPtr` pathOffset) (castPtr cpath) len
+    throwErrnoIfMinus1_ "bind" (c_bind sock addr (fromIntegral addrSize))
+  throwErrnoIfMinus1_ "listen" (c_listen sock 64)
+  pure sock
+  where
+    afUnix = 1
+    sockStream = 1
+    pathOffset = 2
+#if defined(darwin_HOST_OS)
+    addrSize = 106
+#else
+    addrSize = 110
+#endif
+
+-- * HTTP/2
+
+-- | The state of one HTTP/2 connection.
+data Conn = Conn
+  { cOut :: Handle -- written only with cLock held
+  , cLock :: MVar ()
+  , cSendWindow :: TVar Int -- how much the client lets us send on the connection
+  , cStreamWindows :: TVar (M.Map Word32 Int) -- how much the client lets us send on each open stream
+  , cInitialWindow :: TVar Int -- a new stream's window, from the client's SETTINGS
+  , cMaxFrame :: TVar Int -- the largest frame the client takes
+  , cRequests :: TVar (M.Map Word32 ThreadId) -- the thread of each request that is still running
+  }
+
+-- | Serve one connection until the client closes it. Reads go through one
+-- Handle and writes through another, on a duplicate of the socket, because
+-- a Handle's lock is held for the whole of a blocking read. When the
+-- connection ends, the requests still running on it are cancelled.
+connection :: CInt -> ([ByteString] -> IO (Int, ByteString)) -> IO ()
+connection fd handler = do
+  inH <- fdToHandle fd
+  outH <- fdToHandle =<< closeOnExec =<< throwErrnoIfMinus1 "dup" (c_dup fd)
+  forM_ [inH, outH] $ \h -> hSetBinaryMode h True >> hSetBuffering h (BlockBuffering Nothing)
+  conn <- Conn outH <$> newMVar () <*> newTVarIO 65535 <*> newTVarIO M.empty <*> newTVarIO 65535 <*> newTVarIO 16384 <*> newTVarIO M.empty
+  r <- try $ do
+    preface <- B.hGet inH 24
+    unless (preface == "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") $ ioError (userError "not an HTTP/2 connection")
+    -- We send a SETTINGS frame that gives each new stream a large window,
+    -- and raise the connection's window too, so that the client can send a
+    -- request's body without waiting for us to return the window.
+    send conn (frame 4 0 0 (BL.toStrict (BB.toLazyByteString (BB.word16BE 4 <> BB.word32BE bigWindow))) <> frame 8 0 0 (word32 (fromIntegral bigWindow - 65535)))
+    readFrames inH conn handler M.empty
+  -- The connection normally ends when buck2 closes it, which the reads see
+  -- as the end of the input, or as an error if buck2 resets the socket.
+  -- Anything else is a bug, or a client that doesn't speak HTTP/2.
+  case r of
+    Left (e :: SomeException)
+      | Just io <- fromException e, isEOFError io || isResourceVanishedError io -> pure ()
+      | otherwise -> hPutStrLn stderr ("buck2-ghc-worker: connection: " ++ show e)
+    Right () -> pure ()
+  readTVarIO (cRequests conn) >>= mapM_ (forkIO . killThread)
+  hClose inH `finally` hClose outH
+  where
+    bigWindow = 2 ^ (30 :: Int) :: Word32
+
+-- | Read frames until the connection ends. `bodies` holds the body read so
+-- far of each stream whose request hasn't ended yet.
+readFrames :: Handle -> Conn -> ([ByteString] -> IO (Int, ByteString)) -> M.Map Word32 ByteString -> IO ()
+readFrames h conn handler bodies = do
+  header <- B.hGet h 9
+  unless (B.length header < 9) $ do
+    let len = fromIntegral (be (B.take 3 header))
+        typ = B.index header 3
+        flags = B.index header 4
+        sid = fromIntegral (be (B.drop 5 header)) .&. 0x7fffffff
+        endStream = testBit flags 0
+    payload <- B.hGet h len
+    case typ of
+      -- DATA: a piece of a request's body. Give the client back the window
+      -- it used at once, and run the request when its body is complete.
+      0 -> do
+        when (len > 0) $ send conn (frame 8 0 0 (word32 len) <> frame 8 0 sid (word32 len))
+        let body = M.findWithDefault B.empty sid bodies <> unpad flags payload
+        if endStream
+          then request conn handler sid body >> readFrames h conn handler (M.delete sid bodies)
+          else readFrames h conn handler (M.insert sid body bodies)
+      -- HEADERS: a new request. The worker only serves one method, so the
+      -- headers aren't decoded (see Note [Just enough HTTP/2]).
+      1 -> do
+        atomically $ readTVar (cInitialWindow conn) >>= \w -> modifyTVar' (cStreamWindows conn) (M.insert sid w)
+        readFrames h conn handler (M.insert sid B.empty bodies)
+      -- RST_STREAM: the client gave up on a request, so cancel it. The
+      -- request's thread is killed from a thread of its own, since
+      -- killThread waits until the exception is delivered.
+      3 -> do
+        running <- atomically $ do
+          modifyTVar' (cStreamWindows conn) (M.delete sid)
+          M.lookup sid <$> readTVar (cRequests conn)
+        mapM_ (forkIO . killThread) running
+        readFrames h conn handler (M.delete sid bodies)
+      -- SETTINGS: acknowledge them, and note the ones that limit what we send.
+      4 | not (testBit flags 0) -> do
+            forM_ (chunks 6 payload) $ \s -> case be (B.take 2 s) of
+              4 -> atomically $ do
+                let new = fromIntegral (be (B.drop 2 s))
+                old <- readTVar (cInitialWindow conn)
+                writeTVar (cInitialWindow conn) new
+                modifyTVar' (cStreamWindows conn) (M.map (+ (new - old)))
+              5 -> atomically $ writeTVar (cMaxFrame conn) (fromIntegral (be (B.drop 2 s)))
+              _ -> pure ()
+            send conn (frame 4 1 0 B.empty)
+            readFrames h conn handler bodies
+      -- PING: answer it.
+      6 | not (testBit flags 0) -> send conn (frame 6 1 0 payload) >> readFrames h conn handler bodies
+      -- GOAWAY: the client is done.
+      7 -> pure ()
+      -- WINDOW_UPDATE: the client lets us send more.
+      8 -> do
+        let inc = fromIntegral (be payload .&. 0x7fffffff)
+        atomically $
+          if sid == 0
+            then modifyTVar' (cSendWindow conn) (+ inc)
+            else modifyTVar' (cStreamWindows conn) (M.adjust (+ inc) sid)
+        readFrames h conn handler bodies
+      -- Anything else needs nothing from us: PRIORITY, the CONTINUATION of
+      -- headers that we don't read, and acknowledgements.
+      _ -> readFrames h conn handler bodies
+  where
+    unpad flags p
+      | testBit flags 3, Just (n, rest) <- B.uncons p = B.take (B.length rest - fromIntegral n) rest
+      | otherwise = p
+
+-- | Run a request in a thread of its own, and send its response: headers,
+-- the gRPC message, and trailers with the call's status. The status is
+-- always OK, since a failed compile is reported by the exit code in the
+-- response, not as a gRPC error.
+--
+-- If the handler throws an exception, which is a bug in the worker, the
+-- exception goes to stderr and the stream is reset, so that buck2 reports
+-- the action as failed. The response is evaluated fully before any of it is
+-- sent, so that an exception hidden in it is caught here too. If the
+-- request is cancelled, or the connection closes before the response is
+-- ready, nothing is sent.
+request :: Conn -> ([ByteString] -> IO (Int, ByteString)) -> Word32 -> ByteString -> IO ()
+request conn handler sid body = do
+  -- The thread waits until it is in cRequests, so that it can't finish
+  -- before it is added, and a later RST_STREAM always finds it.
+  registered <- newEmptyMVar
+  tid <- forkIO $ (readMVar registered >> respond) `finally` atomically (do
+    modifyTVar' (cStreamWindows conn) (M.delete sid)
+    modifyTVar' (cRequests conn) (M.delete sid))
+  atomically (modifyTVar' (cRequests conn) (M.insert sid tid))
+  putMVar registered ()
+  where
+    respond = do
+      r <- trySync $ do
+        (code, err) <- handler (ecArgv (decodeExecuteCommand (message body)))
+        let msg = encodeExecuteResponse code err
+        evaluate (BL.toStrict (BB.toLazyByteString (BB.word8 0 <> BB.word32BE (fromIntegral (B.length msg)) <> BB.byteString msg)))
+      void . trySync $ case r of
+        Left e -> do
+          hPutStrLn stderr ("buck2-ghc-worker: " ++ show e)
+          send conn (frame 3 0 sid (word32 2))
+        Right grpcMessage -> do
+          send conn (frame 1 4 sid responseHeaders)
+          open <- sendData conn sid grpcMessage
+          when open $ send conn (frame 1 5 sid trailers)
+    -- The body of a unary call holds one message, after gRPC's prefix: a
+    -- byte saying whether it's compressed, and its length in 4 bytes.
+    message bs = B.take (fromIntegral (be (B.take 4 (B.drop 1 bs)))) (B.drop 5 bs)
+    -- Catch the exceptions that the request's own code throws, but not the
+    -- one that cancels the request.
+    trySync :: IO a -> IO (Either SomeException a)
+    trySync act = try act >>= \case
+      Left e | Just (_ :: SomeAsyncException) <- fromException e -> throwIO e
+      other -> pure other
+
+-- | Send a response's message as DATA frames, each no larger than the
+-- client allows or than its windows have room for. It returns False if the
+-- client reset the stream before the message was all sent.
+sendData :: Conn -> Word32 -> ByteString -> IO Bool
+sendData conn sid bs
+  | B.null bs = pure True
+  | otherwise = do
+      n <- atomically $ do
+        stream <- M.lookup sid <$> readTVar (cStreamWindows conn)
+        case stream of
+          Nothing -> pure 0
+          Just sw -> do
+            conw <- readTVar (cSendWindow conn)
+            maxFrame <- readTVar (cMaxFrame conn)
+            let n = minimum [conw, sw, maxFrame, B.length bs]
+            check (n > 0)
+            writeTVar (cSendWindow conn) (conw - n)
+            modifyTVar' (cStreamWindows conn) (M.adjust (subtract n) sid)
+            pure n
+      if n == 0
+        then pure False
+        else send conn (frame 0 0 sid (B.take n bs)) >> sendData conn sid (B.drop n bs)
+
+-- | The response's headers, ":status: 200" and "content-type:
+-- application/grpc", and its trailers, "grpc-status: 0", in HPACK.
+-- ":status: 200" is an entry of HPACK's static table. The others are
+-- literals that the client isn't asked to add to its table (see Note [Just
+-- enough HTTP/2]).
+responseHeaders, trailers :: ByteString
+responseHeaders = B.pack [0x88, 0x0f, 0x10, 16] <> "application/grpc"
+trailers = B.pack [0x00, 11] <> "grpc-status" <> B.pack [1] <> "0"
+
+-- | Write some frames, whole, and flush them.
+send :: Conn -> BB.Builder -> IO ()
+send conn b = withMVar (cLock conn) $ \_ -> BB.hPutBuilder (cOut conn) b >> hFlush (cOut conn)
+
+-- | A frame: its 9-byte header (length, type, flags and stream), then its
+-- payload.
+frame :: Word8 -> Word8 -> Word32 -> ByteString -> BB.Builder
+frame typ flags sid payload =
+  BB.word8 (fromIntegral (len `shiftR` 16)) <> BB.word16BE (fromIntegral len) <> BB.word8 typ <> BB.word8 flags <> BB.word32BE sid <> BB.byteString payload
+  where
+    len = B.length payload
+
+word32 :: Int -> ByteString
+word32 = BL.toStrict . BB.toLazyByteString . BB.word32BE . fromIntegral
+
+-- | A big-endian number.
+be :: ByteString -> Word32
+be = B.foldl' (\a b -> (a `shiftL` 8) .|. fromIntegral b) 0
+
+chunks :: Int -> ByteString -> [ByteString]
+chunks n bs = if B.length bs < n then [] else B.take n bs : chunks n (B.drop n bs)
+
+{- Note [Just enough HTTP/2]
+
+buck2 talks to its local workers with gRPC, over HTTP/2 on a Unix socket.
+This module implements only as much of HTTP/2 (RFC 9113) as a server of one
+unary method needs, so that the worker depends on no package beyond those
+that come with GHC.
+
+- Headers aren't read. A request's HEADERS frame, and any CONTINUATION
+  frames, only say which method is called. The worker serves only Execute,
+  so it takes every request to be one. HPACK, the headers' compression,
+  keeps a table on each side that each header block may change. Since this
+  server never decodes a block, it needn't keep the client's table. Its own
+  blocks use HPACK's static table and literals that it doesn't ask the
+  client to add to the client's table, so neither side's table changes.
+- Flow control: the server gives each new stream and the connection a large
+  window, and gives the client back the window that a request's body used
+  as soon as it arrives, so the client doesn't wait to send. When the server
+  sends a response, it waits for the client's windows (sendData).
+- The server handles only the frames that a unary call needs: one HEADERS
+  and some DATA in, then HEADERS, DATA and trailers out. It cancels a
+  request when the client resets its stream or closes the connection.
+  PRIORITY is ignored, and the server never pushes.
+-}
diff --git a/buck2/prelude/haskell/tools/worker/src/Imports.hs b/buck2/prelude/haskell/tools/worker/src/Imports.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/Imports.hs
@@ -0,0 +1,90 @@
+{-# LANGUAGE CPP #-}
+-- | A module summary's imports, wherever each GHC version (9.6 to 10.1)
+-- keeps them.
+module Imports (Import, ordinaryImports, textualImports, sourceImports, importName, importLocated, spliceImport, findImport, findModuleByName) where
+
+import GHC (GenLocated (..), Located, ModSummary, ModuleName, PkgQual (..))
+import GHC.Driver.Env (HscEnv)
+import GHC.Unit.Finder (FindResult, findImportedModule)
+import GHC.Unit.Module.ModSummary (ModSummary (ms_textual_imps), ms_imps, ms_srcimps)
+#if MIN_VERSION_ghc(9,14,0)
+import GHC.Types.Basic (ImportLevel (..))
+#endif
+#if MIN_VERSION_ghc(10,1,0)
+import GHC.Unit.Finder (resolveImport)
+import GHC.Types.UnresolvedImport (UnresolvedImport (..))
+import GHC.Unit.Types (IsBootInterface (..), ModuleLookupScope (..))
+#endif
+
+-- | An import of a module summary. GHC 9.14 added an import level to each
+-- import, which only spliceImport reads.
+#if MIN_VERSION_ghc(10,1,0)
+type Import = UnresolvedImport PkgQual
+#elif MIN_VERSION_ghc(9,14,0)
+type Import = (ImportLevel, PkgQual, Located ModuleName)
+#else
+type Import = (PkgQual, Located ModuleName)
+#endif
+
+-- | The module's imports that aren't {-# SOURCE #-} imports, including
+-- those of its plugins.
+ordinaryImports :: ModSummary -> [Import]
+
+-- | The module's own imports that aren't {-# SOURCE #-} imports, without
+-- those of its plugins.
+textualImports :: ModSummary -> [Import]
+
+-- | The module names of the module's {-# SOURCE #-} imports.
+sourceImports :: ModSummary -> [ModuleName]
+
+-- | An import's module name, and the package that it names (with
+-- PackageImports), if any.
+importName :: Import -> (ModuleName, PkgQual)
+
+-- | An import's module name, with its source location.
+importLocated :: Import -> Located ModuleName
+
+-- | Whether an import is at the splice level (`import splice`). An import
+-- before GHC 9.14, which added levels, never is.
+spliceImport :: Import -> Bool
+
+-- | Find the module that an import names, as GHC does when it compiles the
+-- module. Since GHC 10.1, the lookup depends on where the import comes
+-- from: GHC's implicit import of GHC.Essentials may name a hidden module,
+-- for example.
+findImport :: HscEnv -> Import -> IO FindResult
+
+-- | Find a module by its name alone, as a user's import that names no
+-- package would.
+findModuleByName :: HscEnv -> ModuleName -> IO FindResult
+
+#if MIN_VERSION_ghc(10,1,0)
+-- Since GHC 10.1, ms_imps has the {-# SOURCE #-} imports too.
+ordinaryImports = filter ((== NotBoot) . ui_boot) . ms_imps
+textualImports = filter ((== NotBoot) . ui_boot) . ms_textual_imps
+sourceImports ms = [mn | UnresolvedImport{ui_mod_name = L _ mn} <- ms_srcimps ms]
+importName i = let L _ mn = ui_mod_name i in (mn, ui_pkg_qual i)
+importLocated = ui_mod_name
+spliceImport = (== SpliceLevel) . ui_level
+findImport = resolveImport
+findModuleByName hsc mn = findImportedModule hsc LookupUser mn NoPkgQual
+#elif MIN_VERSION_ghc(9,14,0)
+ordinaryImports = ms_imps
+textualImports = ms_textual_imps
+sourceImports ms = [mn | L _ mn <- ms_srcimps ms]
+importName (_, pkg, L _ mn) = (mn, pkg)
+importLocated (_, _, lmn) = lmn
+spliceImport (level, _, _) = level == SpliceLevel
+#else
+ordinaryImports = ms_imps
+textualImports = ms_textual_imps
+sourceImports ms = [mn | (_, L _ mn) <- ms_srcimps ms]
+importName (pkg, L _ mn) = (mn, pkg)
+importLocated (_, lmn) = lmn
+spliceImport _ = False
+#endif
+
+#if !MIN_VERSION_ghc(10,1,0)
+findImport hsc i = let (mn, pkg) = importName i in findImportedModule hsc mn pkg
+findModuleByName hsc mn = findImportedModule hsc mn NoPkgQual
+#endif
diff --git a/buck2/prelude/haskell/tools/worker/src/Interface.hs b/buck2/prelude/haskell/tools/worker/src/Interface.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/Interface.hs
@@ -0,0 +1,84 @@
+{-# LANGUAGE CPP #-}
+-- | Reading a module's interface, and what the rules take from it, wherever
+-- each GHC version (9.6 to 10.1) keeps it.
+module Interface
+  ( readInterface
+  , readInterfaceIn
+  , abiHash
+  , usages
+  , usageFile
+  , usageLoadedModule
+  , directDep
+  ) where
+
+import Control.Monad.IO.Class (liftIO)
+
+import GHC (getSession, runGhc)
+import GHC.Driver.Env (HscEnv, hsc_NC, hsc_dflags)
+import GHC.Driver.Session (targetProfile)
+import GHC.Iface.Binary (CheckHiWay (..), TraceBinIFace (..), readBinIface)
+import GHC.Unit.Module.Deps (Usage (..))
+import GHC.Unit.Module.ModIface (ModIface, mi_usages)
+#if MIN_VERSION_ghc(9,8,0)
+import GHC.Data.FastString (unpackFS)
+#endif
+#if MIN_VERSION_ghc(9,14,0)
+import GHC.Unit.Module.ModIface (mi_mod_hash)
+#else
+import GHC.Unit.Module.ModIface (mi_final_exts, mi_mod_hash)
+#endif
+import GHC.Unit.Module (ModuleName)
+import GHC.Utils.Fingerprint (Fingerprint)
+
+-- | Read the interface file, with GHC's libdir.
+readInterface :: FilePath -> FilePath -> IO ModIface
+readInterface libdir path = runGhc (Just libdir) $ do
+  hsc <- getSession
+  liftIO (readInterfaceIn hsc path)
+
+-- | Read the interface file, with the session's flags and name cache.
+readInterfaceIn :: HscEnv -> FilePath -> IO ModIface
+readInterfaceIn hsc = readBinIface (targetProfile (hsc_dflags hsc)) (hsc_NC hsc) IgnoreHiWay QuietBinIFace
+
+-- | The interface's ABI hash and usages. From GHC 9.14 an interface may
+-- record no usages (-fno-write-if-self-recomp).
+abiHash :: ModIface -> Fingerprint
+usages :: ModIface -> Maybe [Usage]
+#if MIN_VERSION_ghc(9,14,0)
+abiHash = mi_mod_hash
+usages = mi_usages
+#else
+abiHash = mi_mod_hash . mi_final_exts
+usages = Just . mi_usages
+#endif
+
+-- | The file of a usage of a file (from addDependentFile, or a library that a
+-- splice loaded).
+usageFile :: Usage -> Maybe FilePath
+#if MIN_VERSION_ghc(9,8,0)
+usageFile UsageFile{usg_file_path = p} = Just (unpackFS p)
+#else
+usageFile UsageFile{usg_file_path = p} = Just p
+#endif
+usageFile _ = Nothing
+
+-- | The module of a usage that records a home module whose code a splice
+-- loaded into the interpreter. GHC 10.0 renamed the constructor of these
+-- usages from UsageHomeModuleInterface to UsageHomeModuleBytecode.
+usageLoadedModule :: Usage -> Maybe ModuleName
+#if MIN_VERSION_ghc(10,0,0)
+usageLoadedModule UsageHomeModuleBytecode{usg_mod_name = m} = Just m
+#else
+usageLoadedModule UsageHomeModuleInterface{usg_mod_name = m} = Just m
+#endif
+usageLoadedModule _ = Nothing
+
+-- | An interface's direct dependency, without the import level it carries
+-- since GHC 9.14.
+#if MIN_VERSION_ghc(9,14,0)
+directDep :: (a, b, c) -> (b, c)
+directDep (_, uid, m) = (uid, m)
+#else
+directDep :: (b, c) -> (b, c)
+directDep = id
+#endif
diff --git a/buck2/prelude/haskell/tools/worker/src/Pragmas.hs b/buck2/prelude/haskell/tools/worker/src/Pragmas.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/Pragmas.hs
@@ -0,0 +1,28 @@
+{-# LANGUAGE CPP #-}
+-- | The flags that a module's OPTIONS_GHC and LANGUAGE pragmas give.
+module Pragmas (optionsPragmas) where
+
+import GHC (DynFlags, Located)
+import GHC.Data.StringBuffer (StringBuffer)
+import GHC.Driver.Config.Parser (initParserOpts)
+import GHC.Parser.Header (getOptions)
+#if MIN_VERSION_ghc(9,14,0)
+import GHC.Driver.Config.Parser (supportedLanguagePragmas)
+#endif
+#if MIN_VERSION_ghc(10,0,0)
+import GHC.Types.SourceError (initSourceErrorContext)
+#endif
+
+-- | Read the flags that the OPTIONS_GHC and LANGUAGE pragmas at the head of
+-- a module's source give, parsing the source with the given flags. The file
+-- name is only used in GHC's messages. (From GHC 9.14, the parser also needs
+-- the list of supported extensions, and from GHC 10.0 the context in which
+-- to report errors.)
+optionsPragmas :: DynFlags -> StringBuffer -> FilePath -> [Located String]
+#if MIN_VERSION_ghc(10,0,0)
+optionsPragmas dflags buf file = snd (getOptions (initParserOpts dflags) (initSourceErrorContext dflags) (supportedLanguagePragmas dflags) buf file)
+#elif MIN_VERSION_ghc(9,14,0)
+optionsPragmas dflags buf file = snd (getOptions (initParserOpts dflags) (supportedLanguagePragmas dflags) buf file)
+#else
+optionsPragmas dflags buf file = snd (getOptions (initParserOpts dflags) buf file)
+#endif
diff --git a/buck2/prelude/haskell/tools/worker/src/Proto.hs b/buck2/prelude/haskell/tools/worker/src/Proto.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/Proto.hs
@@ -0,0 +1,87 @@
+-- | Encoding and decoding of the protobuf messages of buck2's worker
+-- protocol (worker.proto), written by hand. The worker only uses two small
+-- messages, ExecuteCommand and ExecuteResponse, which aren't worth a
+-- dependency on a protobuf library.
+--
+-- In protobuf's wire format, each field starts with a varint key, which is
+-- the field number shifted left by 3 bits, with the wire type in the low 3
+-- bits. The field's value follows. For wire type 0 the value is a varint,
+-- and for wire type 2 it is a varint length followed by that many bytes.
+module Proto (ExecuteCommand (..), decodeExecuteCommand, encodeExecuteResponse, encodeExecuteCommand, decodeExecuteResponse) where
+
+import Data.Bits (shiftL, shiftR, (.&.), (.|.))
+import Data.ByteString (ByteString)
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Builder as BB
+import qualified Data.ByteString.Lazy as BL
+import Data.Word (Word64, Word8)
+
+-- | The part of an ExecuteCommand message that the worker uses: the
+-- command's arguments (field 1). The command's environment (field 2) is
+-- ignored, since the rules don't give these actions an environment of their
+-- own.
+newtype ExecuteCommand = ExecuteCommand {ecArgv :: [ByteString]}
+
+-- Split a message into its fields, each with its field number and value. A
+-- varint value is in 'Left', and a length-delimited value in 'Right'.
+-- Fixed-size values (wire types 1 and 5) are skipped, and decoding stops at
+-- any other wire type.
+fields :: ByteString -> [(Word64, Either Word64 ByteString)]
+fields bs
+  | B.null bs = []
+  | otherwise =
+      let (key, rest) = varint bs
+          num = key `shiftR` 3
+       in case key .&. 7 of
+            0 -> let (v, rest') = varint rest in (num, Left v) : fields rest'
+            2 ->
+              let (len, rest') = varint rest
+                  (payload, rest'') = B.splitAt (fromIntegral len) rest'
+               in (num, Right payload) : fields rest''
+            1 -> fields (B.drop 8 rest)
+            5 -> fields (B.drop 4 rest)
+            _ -> []
+
+varint :: ByteString -> (Word64, ByteString)
+varint = go 0 0
+  where
+    go acc shift bs = case B.uncons bs of
+      Nothing -> (acc, B.empty)
+      Just (b, rest) ->
+        let acc' = acc .|. (fromIntegral (b .&. 0x7f) `shiftL` shift)
+         in if b .&. 0x80 == 0 then (acc', rest) else go acc' (shift + 7) rest
+
+decodeExecuteCommand :: ByteString -> ExecuteCommand
+decodeExecuteCommand bs = ExecuteCommand [a | (1, Right a) <- fields bs]
+
+-- Encode an ExecuteResponse with the given exit code (field 1, a varint) and
+-- stderr (field 2, a byte string). The keys 8 and 18 are those two field
+-- numbers combined with their wire types.
+encodeExecuteResponse :: Int -> ByteString -> ByteString
+encodeExecuteResponse code err =
+  BL.toStrict . BB.toLazyByteString $
+    putVarint 8 <> putVarint (fromIntegral code)
+      <> putVarint 18 <> putVarint (fromIntegral (B.length err)) <> BB.byteString err
+
+putVarint :: Word64 -> BB.Builder
+putVarint n
+  | n < 0x80 = BB.word8 (fromIntegral n)
+  | otherwise = BB.word8 (fromIntegral (n .&. 0x7f) .|. 0x80 :: Word8) <> putVarint (n `shiftR` 7)
+
+-- | Encode an ExecuteCommand with the given argv. This and
+-- 'decodeExecuteResponse' are the client's side of the protocol, for
+-- programs that talk to the worker, such as its test suites.
+encodeExecuteCommand :: [ByteString] -> ByteString
+encodeExecuteCommand argv =
+  BL.toStrict . BB.toLazyByteString . mconcat $
+    [putVarint 10 <> putVarint (fromIntegral (B.length a)) <> BB.byteString a | a <- argv]
+
+-- | Decode the exit code and stderr of an ExecuteResponse. A missing field
+-- reads as protobuf's default, which is 0 or empty.
+decodeExecuteResponse :: ByteString -> (Int, ByteString)
+decodeExecuteResponse bs = (fromIntegral code, B.concat (take 1 [e | (2, Right e) <- fs]))
+  where
+    fs = fields bs
+    code = case [c | (1, Left c) <- fs] of
+      c : _ -> c
+      [] -> 0
diff --git a/buck2/prelude/haskell/tools/worker/src/Request.hs b/buck2/prelude/haskell/tools/worker/src/Request.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/Request.hs
@@ -0,0 +1,126 @@
+-- | The request that the rules send to compile each module, and the flags
+-- of the GHC session that compiles it.
+module Request (Request (..), parseRequest, moduleArg, sessionFlags, withRequestEnv, withoutRts) where
+
+import Data.List (isPrefixOf, stripPrefix)
+
+import Contract (contract)
+
+-- | The request to compile one module, which the rules send as the
+-- action's arguments (see Note [The persistent worker] in
+-- compile_per_module.bzl):
+--
+-- > --request --contract V --libdir LIBDIR --depfile DEP --abi ABI
+-- >   --module Foo/Bar --source Foo/Bar.hs --outdir OUT --hisuf SUF [--boot]
+-- >   [--hidir=UNIT=DIR]... [--srcroot=SRCS]... [--mkdir=DIR]...
+-- >   [--data-dir=VAR=DIR]... [--loadable=MODULE]...
+-- >   -- ghc SESSION_FLAGS... -- -c Foo/Bar.hs -o ... -ohi ...
+--
+-- The flags come in two parts: the session flags, which are the same for
+-- every module of the target, and the module's own. The worker compiles the
+-- module in the session, and takes only the outputs from the module's flags:
+-- @-o@, @-ohi@, @-dyno@, @-dynohi@, @-hiedir@ and @-stubdir@. When buck2
+-- doesn't use the worker, the compile tool (PerModuleCompile) takes the same
+-- request.
+--
+-- LIBDIR is the libdir of the GHC that compiles the module. The worker and
+-- the compile tool run GHC's code in-process, and that code reads GHC's
+-- settings and package database from the libdir.
+data Request = Request
+  { reqLibdir :: FilePath
+  , reqDepfile :: FilePath
+  , reqAbi :: FilePath
+  , reqDiagnostics :: FilePath -- where to write the compile's messages, such as warnings
+  , reqModPath :: String -- Foo/Bar
+  , reqSource :: FilePath
+  , reqOutDir :: FilePath -- where every module's outputs are
+  , reqHisuf :: String
+  , reqHidirs :: [(String, FilePath)] -- the dependencies' interface (and .abi) dirs, by unit id
+  , reqSrcRoots :: [FilePath] -- trees of the target's sources, which go on the session's import path
+  , reqMkdirs :: [FilePath] -- output directories to create first
+  , reqDataDirs :: [(String, FilePath)] -- the variables for the module's splices, with the data dirs they name (see Note [Data files of splices] in compile_per_module.bzl)
+  , reqBoot :: Bool -- whether the module is a boot file
+  , reqLoadable :: [String] -- for a module that runs Template Haskell, the target's modules whose objects the compile has, so that its splices may load them (see Note [Template Haskell modules] in compile_per_module.bzl)
+  , reqCompiler :: String
+  , reqSessionArgs :: [String] -- the session flags, which are the same for every module of the target
+  , reqModuleArgs :: [String] -- the module flags: `ghc -c`'s source and output files, -hiedir and -stubdir
+  }
+
+-- | The value that the request's module flags give `flag`, such as the
+-- interface file that @-ohi@ names.
+moduleArg :: String -> Request -> Maybe FilePath
+moduleArg flag r = case dropWhile (/= flag) (reqModuleArgs r) of
+  _ : v : _ -> Just v
+  _ -> Nothing
+
+-- | Parse the request from an action's command line. buck2 sends the whole
+-- command line, so it starts with the program and the program's own
+-- arguments. Those end at the "--request" marker, and are ignored.
+parseRequest :: [String] -> Either String Request
+parseRequest args = case drop 1 (dropWhile (/= "--request") args) of
+  "--contract" : v : rest
+    | v == contract -> go (Request "" "" "" "" "" "" "" "" [] [] [] [] False [] "" [] []) rest
+    | otherwise -> Left ("this program takes version " ++ contract ++ " of the rules' requests, but the rules sent version " ++ v ++ ": build it from the same version of the rules")
+  _ -> Left "the request names no version: build this program from the same version of the rules"
+  where
+    go r ("--libdir" : v : rest) = go r{reqLibdir = v} rest
+    go r ("--depfile" : v : rest) = go r{reqDepfile = v} rest
+    go r ("--abi" : v : rest) = go r{reqAbi = v} rest
+    go r ("--diagnostics" : v : rest) = go r{reqDiagnostics = v} rest
+    go r ("--module" : v : rest) = go r{reqModPath = v} rest
+    go r ("--source" : v : rest) = go r{reqSource = v} rest
+    go r ("--outdir" : v : rest) = go r{reqOutDir = v} rest
+    go r ("--hisuf" : v : rest) = go r{reqHisuf = v} rest
+    go r ("--boot" : rest) = go r{reqBoot = True} rest
+    go r ("--" : compiler : rest)
+      | null (reqLibdir r) = Left "the request names no libdir (--libdir)"
+      | null (reqDiagnostics r) = Left "the request names no diagnostics file (--diagnostics)"
+      | otherwise =
+          let (session, moduleArgs) = break (== "--") rest
+           in Right r{reqCompiler = compiler, reqSessionArgs = session, reqModuleArgs = drop 1 moduleArgs}
+    go r (x : rest)
+      | Just v <- stripPrefix "--hidir=" x, (unit, '=' : d) <- break (== '=') v = go r{reqHidirs = reqHidirs r ++ [(unit, d)]} rest
+      | Just v <- stripPrefix "--srcroot=" x = go r{reqSrcRoots = reqSrcRoots r ++ [v]} rest
+      | Just v <- stripPrefix "--mkdir=" x = go r{reqMkdirs = reqMkdirs r ++ [v]} rest
+      | Just v <- stripPrefix "--loadable=" x = go r{reqLoadable = reqLoadable r ++ [v]} rest
+      | Just v <- stripPrefix "--data-dir=" x, (var, '=' : d) <- break (== '=') v = go r{reqDataDirs = reqDataDirs r ++ [(var, d)]} rest
+      | otherwise = Left ("unexpected request argument " ++ show x)
+    go _ [] = Left "the request has no compiler command"
+
+-- | The flags of the session that compiles the request's module. They are
+-- the request's session flags, without two kinds of flag that only the ghc
+-- program takes:
+--
+-- - options for the ghc program's runtime (@+RTS ... -RTS@), because the
+--   worker has its own runtime;
+-- - @-B@, which tells the ghc program its libdir. A toolchain whose GHC is
+--   built from source passes it as part of the compiler command. The worker
+--   takes the libdir from the request instead (@--libdir@).
+--
+-- To those, this adds:
+--
+-- - @-odir@ and @-hidir@, so that GHC writes each output into the output
+--   directory, at a path made from the module's name. That is where the
+--   rules expect the outputs.
+-- - The trees of the target's sources, on the import path.
+--
+-- Every other flag comes from the rules, so that the worker compiles with
+-- the same flags as the compile tool's @ghc -c@.
+sessionFlags :: Request -> [String]
+sessionFlags r =
+  filter (not . ("-B" `isPrefixOf`)) (withoutRts (reqSessionArgs r))
+    ++ ["-odir", reqOutDir r, "-hidir", reqOutDir r]
+    ++ ["-i" ++ d | d <- reqSrcRoots r]
+
+-- | Add the variables of the request's data dirs to an environment, in place
+-- of any variables with the same names. The request's splices need them.
+withRequestEnv :: Request -> [(String, String)] -> [(String, String)]
+withRequestEnv r env = vars ++ [(k, v) | (k, v) <- env, k `notElem` map fst vars]
+  where
+    vars = reqDataDirs r
+
+-- | GHC's flags without options for its runtime (@+RTS ... -RTS@).
+withoutRts :: [String] -> [String]
+withoutRts args = case break (== "+RTS") args of
+  (ghc, _ : rest) -> ghc ++ withoutRts (drop 1 (dropWhile (/= "-RTS") rest))
+  (ghc, []) -> ghc
diff --git a/buck2/prelude/haskell/tools/worker/src/Session.hs b/buck2/prelude/haskell/tools/worker/src/Session.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/Session.hs
@@ -0,0 +1,988 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+-- | A GHC session for one set of session flags, in which requests compile
+-- their modules concurrently. Each compile uses compileOne, the function
+-- that `ghc --make -j` runs for each module. See Note [The session's state].
+module Session (GhcSession, gsModules, gsOutDir, gsOneShot, SessionMode (..), Shared, newShared, newSession, endSession, compile, Node, Diagnostic (..), tryNonAsync) where
+
+import Control.Exception (SomeAsyncException, SomeException, finally, fromException, onException, throwIO, try)
+import Control.Monad (foldM, forM, forM_, unless)
+import Control.Concurrent.MVar
+import Data.Graph (SCC, flattenSCC, stronglyConnComp)
+import Data.IORef
+import Control.Applicative ((<|>))
+import Data.Char (isDigit)
+import Data.List (isPrefixOf, isSuffixOf, stripPrefix)
+import qualified Data.Map as M
+import Data.Maybe (isJust, maybeToList)
+import qualified Data.Set as Set
+import Data.Unique (hashUnique, newUnique)
+import System.Directory (createDirectory, createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getTemporaryDirectory, listDirectory, removePathForcibly)
+import System.Posix.Process (getProcessID)
+import System.Environment (lookupEnv)
+import System.FilePath (dropTrailingPathSeparator, joinPath, splitDirectories, takeDirectory, (<.>), (</>))
+import System.IO (hPutStrLn, stderr)
+
+import GHC
+import GHC.Data.StringBuffer (hGetStringBuffer)
+import GHC.Driver.Env (hscSetFlags, hsc_FC, hsc_NC, hsc_dflags, hsc_home_unit, hsc_interp, hsc_logger, hsc_mod_graph, hsc_tmpfs, hsc_type_env_vars, hsc_unit_env)
+import GHC.Driver.Env.KnotVars (knotVarsFromModuleEnv)
+import GHC.Types.TypeEnv (emptyTypeEnv)
+import GHC.Unit.Module.Env (mkModuleEnv)
+import GHC.Driver.Monad (Ghc (..), Session (..))
+import GHC.Driver.Pipeline (compileOne)
+import qualified GHC.Data.EnumSet as EnumSet
+import GHC.Driver.Session (PackageDBFlag (..), PkgDbRef (..), fFlags, flagSpecName, globalPackageDatabasePath, hasNoDebugOutput, hasPprDebug, setUnsafeGlobalDynFlags, ways)
+import GHC.Platform.Ways (Way (..))
+import GHC.Runtime.Interpreter (stopInterp)
+import GHC.Types.Error (MessageClass (..), getCaretDiagnostic, mkLocMessageWarningGroups)
+import GHC.Types.SourceFile (HscSource (..))
+import GHC.Unit.Finder (FindResult (..), findObjectLinkableMaybe, initFinderCache)
+import GHC.Types.Name.Cache (NameCache)
+import GHC.Unit.Finder.Types (FinderCache)
+import GHC.Unit.Home (HomeUnit, homeUnitId, isHomeModule)
+import GHC.Unit.Module.ModSummary (isBootSummary, msHsFilePath)
+import GHC.Unit.Home.ModInfo (HomeModInfo (..), HomeModLinkable (..), emptyHomeModInfoLinkable)
+import GHC.Unit.Module.Deps (dep_boot_mods, dep_direct_mods)
+import GHC.Unit.Module.Location (addBootSuffixLocn, addBootSuffixLocnOut)
+import GHC.Unit.Env (HomeUnitEnv (..), UnitEnv (..), ue_currentUnit, ue_findHomeUnitEnv, ue_updateHomeUnitEnv)
+import GHC.Unit.External (ExternalUnitCache, initExternalUnitCache)
+import GHC.Unit.State (UnitDatabase, UnitState)
+import GHC.Unit.Types (GenWithIsBoot (..), UnitId)
+import GHC.Utils.Logger (LogFlags (..))
+import GHC.Utils.Outputable (empty, renderWithContext, ($+$))
+import GHC.Utils.Panic (throwGhcExceptionIO)
+import GHC.Utils.TmpFs (cleanCurrentModuleTempFiles, cleanTempDirs, cleanTempFiles, forkTmpFsFrom, mergeTmpFsInto)
+
+import Compat
+import DepFile (writeDepFiles)
+import Pragmas (optionsPragmas)
+import Imports (findImport, findModuleByName, importName, sourceImports, textualImports)
+import Interface (directDep, readInterfaceIn, usages)
+import Request
+
+-- | A GHC session, and what the worker keeps with it.
+data GhcSession = GhcSession
+  { gsEnv :: HscEnv -- the session's GHC environment, which each compile gives a home package table of its own
+  , gsHomes :: MVar Homes -- what a --make session keeps of its home modules, locked while a compile's home package table is made
+  , gsTmpDir :: FilePath -- the session's own temporary directory (see Note [A temporary directory per session])
+  , gsModules :: Maybe (Set.Set Node) -- the modules and boot interfaces of the session's target, or Nothing if GHC's analysis of the target failed
+  , gsOutDir :: FilePath -- the output directory of the target's modules, for the way the session builds them, which identifies the target in Worker
+  , gsOneShot :: Bool -- whether the session compiles in one-shot mode (see Note [One-shot sessions])
+  , gsExternal :: MVar (M.Map [String] ExternalUnitCache) -- the external package states that the compiles read interfaces into, keyed by 'interfaceKey'; all the one-shot sessions share one map
+  , gsInterpLock :: Maybe (MVar ()) -- the lock that each of the session's compiles holds while it runs, or Nothing if the session's interpreter needs no lock (see 'interpreterLock')
+  }
+
+-- | Which mode the sessions compile in (see Note [One-shot sessions]).
+data SessionMode
+  = AutoSessions -- one-shot for a target without boot files, and --make for a target with them
+  | MakeSessions -- --make for every target
+
+-- | What the sessions share, for the whole life of the worker.
+data Shared = Shared
+  { shDbs :: MVar (M.Map FilePath (UnitDatabase UnitId)) -- the package databases read so far, keyed by path (see Note [One copy of each package database])
+  , shExternal :: MVar (M.Map [String] ExternalUnitCache) -- the external package states of the one-shot sessions, keyed by 'interfaceKey'
+  , shUnits :: MVar (M.Map [String] (UnitState, Maybe HomeUnit)) -- the unit state of the one-shot sessions, keyed by session flags (see Note [One-shot sessions])
+  }
+
+newShared :: IO Shared
+newShared = Shared <$> newMVar M.empty <*> newMVar M.empty <*> newMVar M.empty
+
+-- | A diagnostic that a compile reported: whether it is an error, and its
+-- rendered text.
+data Diagnostic = Diagnostic {diagIsError :: Bool, diagText :: String}
+
+-- | Make a session for the request's session flags, in the given mode. It
+-- runs GHC's dependency analysis over the target's sources, to find the
+-- target's modules (see Note [The session's state]). The session shares
+-- with the others the file hashes in the given finder cache (see Note
+-- [Hashing the libraries]), the given name cache (see Note [One name cache
+-- for all the sessions]), and everything in 'Shared'. Anything that GHC
+-- logs outside a compile, which is rare, goes to the worker's stderr.
+newSession :: FilePath -> FinderCache -> NameCache -> Shared -> SessionMode -> Request -> IO GhcSession
+newSession libdir files names shared mode r = do
+  ref <- newIORef (error "buck2-ghc-worker: the session isn't made yet")
+  let session = Session ref
+  unGhc (initGhcMonad (Just libdir)) session
+  modifyIORef' ref (\hsc -> hsc{hsc_NC = names})
+  dflags0 <- unGhc getSessionDynFlags session
+  unGhc (modifyLogger (pushLogHook (\_ lf _ _ doc -> hPutStrLn stderr (renderWithContext (log_default_user_context lf) doc)))) session
+  logger <- hsc_logger <$> readIORef ref
+  tmp <- newTmpDir
+  -- If the session can't be made, remove its temporary directory.
+  (`onException` removePathForcibly tmp) $ do
+    (dflags, leftover, _) <- parseDynamicFlags logger dflags0 (map noLoc (sessionFlags r ++ ["-tmpdir", tmp]))
+    -- Refuse arguments that aren't flags GHC knows, as `ghc` itself would.
+    unless (null leftover) $
+      throwGhcExceptionIO (CmdLineError ("unrecognised flags: " ++ unwords (map unLoc leftover)))
+    -- See Note [Flags of the whole process].
+    let wholeProcess =
+          ["-fno-state-hack" | gopt Opt_G_NoStateHack dflags]
+            ++ ["-dppr-debug" | hasPprDebug dflags]
+            ++ ["-dno-debug-output" | hasNoDebugOutput dflags]
+            ++ ["-dinitial-unique" | initialUnique dflags /= 0]
+            ++ ["-dunique-increment" | uniqueIncrement dflags /= 1]
+            ++ ["-H" | isJust (ghcHeapSize dflags)]
+            ++ ["-Rghc-timing" | enableTimeStats dflags]
+    unless (null wholeProcess) $ do
+      setUnsafeGlobalDynFlags dflags0
+      throwGhcExceptionIO (CmdLineError (unwords wholeProcess ++ ": these set GHC's state for the whole worker process, not one session's; compile this target without the worker"))
+    setFlags shared session dflags
+    found <- concat <$> mapM sources (reqSrcRoots r)
+    -- Only the modules' sources are given to GHC as targets, not the boot
+    -- files. GHC finds the boot files itself, from the {-# SOURCE #-}
+    -- imports. Before GHC 9.12, giving a boot file as a target leaves the
+    -- module graph without the boot interfaces, and a compile needs them
+    -- in the graph to find the instances of the boot interfaces it imports.
+    let srcs = filter (\f -> any (`isSuffixOf` f) [".hs", ".lhs"]) found
+    let oneShot = isOneShot mode (any (\f -> any (`isSuffixOf` f) [".hs-boot", ".lhs-boot"]) found)
+    -- Make the target's module graph with GHC's own dependency analysis of
+    -- the source tree. If the analysis fails, the graph is left empty, and
+    -- the compiles of the modules at fault report the errors.
+    --
+    -- The analysis can also fail with an exception rather than errors.
+    -- GHC throws one when it can't run a module's preprocessor because the
+    -- preprocessor isn't on the worker's PATH. The worker is never asked to
+    -- compile such a module, but its target's other modules can still be
+    -- compiled here.
+    analysed <- either (const False) id <$> tryNonAsync (unGhc (do
+      hsc <- getSession
+      targets <- mapM (\f -> guessTarget f (Just (homeUnitId (hsc_home_unit hsc))) Nothing) srcs
+      setTargets targets
+      analyseTargets) session)
+    -- The analysis looked up the modules imported from dependencies, and
+    -- most of their interfaces don't exist yet, since the interfaces in a
+    -- dependency's early package db are written one by one as its modules
+    -- compile. GHC's finder caches failed lookups as well as successful
+    -- ones, so the compiles start with an empty finder cache, sharing only
+    -- the file hashes.
+    fc <- initFinderCache
+    hsc0 <- readIORef ref
+    let modules = Set.fromList [(ms_mod_name ms, isBootSummary ms) | ms <- mgModSummaries (hsc_mod_graph hsc0)]
+    hsc <- if oneShot then oneShotEnv shared r hsc0 else pure hsc0
+    external <- if oneShot then pure (shExternal shared) else newMVar M.empty
+    GhcSession hsc{hsc_FC = withFileHashes files fc} <$> newMVar (Homes M.empty M.empty) <*> pure tmp <*> pure (if analysed then Just modules else Nothing) <*> pure (reqOutDir r) <*> pure oneShot <*> pure external <*> interpreterLock (hsc_dflags hsc)
+  where
+    sources dir = do
+      entries <- listDirectory dir
+      fmap concat . forM entries $ \e -> do
+        let path = dir </> e
+        isDir <- doesDirectoryExist path
+        if isDir then sources path else pure [path]
+
+-- | Whether a session compiles in one-shot mode, from the session mode and
+-- whether the session's target has boot files.
+isOneShot :: SessionMode -> Bool -> Bool
+isOneShot AutoSessions boots = not boots
+isOneShot MakeSessions _ = False
+
+-- | Set the session's flags. If every package database that the flags name
+-- has been read already, the session is given the shared copies, so that
+-- GHC doesn't read them again. Otherwise GHC reads them, and the worker
+-- keeps the copies for later sessions. See Note [One copy of each package
+-- database].
+setFlags :: Shared -> Session -> DynFlags -> IO ()
+setFlags shared session@(Session ref) dflags = do
+  -- GHC only reads the package databases if the session has none yet, so
+  -- giving it the shared copies first makes GHC use those.
+  pathEnv <- lookupEnv "GHC_PACKAGE_PATH"
+  let paths = dbPaths dflags
+  known <- readMVar (shDbs shared)
+  let cached = if isJust pathEnv then Nothing else mapM (`M.lookup` known) paths
+  forM_ cached $ \c -> do
+    hsc <- readIORef ref
+    ue <- useUnitDbs c (hsc_unit_env hsc)
+    writeIORef ref hsc{hsc_unit_env = ue}
+  unGhc (setSessionDynFlags dflags >> pure ()) session
+  unless (isJust cached || isJust pathEnv) $ do
+    new <- unitDbsRead paths . hsc_unit_env =<< readIORef ref
+    forM_ new $ \dbs ->
+      modifyMVar_ (shDbs shared) (\m -> pure (M.union m (M.fromList (zip paths dbs))))
+
+-- | Turn the session's environment into one for one-shot compiles (see Note
+-- [One-shot sessions]). It uses the unit state of the first one-shot session
+-- made with the same session flags, and has no module graph.
+oneShotEnv :: Shared -> Request -> HscEnv -> IO HscEnv
+oneShotEnv shared r hsc = do
+  let dflags = hsc_dflags hsc
+      ue = hsc_unit_env hsc
+      unit = ue_currentUnit ue
+      hue = ue_findHomeUnitEnv unit ue
+  (units, home) <- sharedAt (shUnits shared) (sessionFlags r) (pure (homeUnitEnv_units hue, homeUnitEnv_home_unit hue))
+  let ue' = ue_updateHomeUnitEnv (\h -> h{homeUnitEnv_units = units, homeUnitEnv_home_unit = home}) unit ue
+  pure (withModuleGraph emptyMG (hscSetFlags dflags{ghcMode = OneShot} hsc{hsc_unit_env = ue'}))
+
+-- | Look up the key in a shared map. If it isn't there, make its value with
+-- the given action, and add it to the map.
+sharedAt :: Ord k => MVar (M.Map k v) -> k -> IO v -> IO v
+sharedAt var k make = modifyMVar var $ \m -> case M.lookup k m of
+  Just v -> pure (m, v)
+  Nothing -> make >>= \v -> pure (M.insert k v m, v)
+
+-- | The key under which a compile reads interfaces into an external package
+-- state. Only compiles with the same key share a state. Besides the modules
+-- themselves, the interfaces that GHC reads depend on two things:
+--
+-- - The build configuration. Two configurations can build a module with the
+--   same unit id but different interfaces.
+-- - The compile's flags, which are its session's flags followed by those of
+--   its module's pragmas (see Note [The flags an interface is read with]).
+--   The key holds them as GHC has applied them, where it can: the set of
+--   general flags (the -f flags) that are on, and the ways that change what
+--   GHC reads (profiled or dynamic). Two compiles whose flags differ only in
+--   order, or repeat a flag, then share a state. The flags whose effect
+--   those don't record stay in the key as given.
+--
+-- buck2 puts each configuration's outputs under
+-- buck-out/v2/art/<cell>/<configuration hash>, so that part of the output
+-- directory identifies the configuration. If the output directory isn't in
+-- that layout (in the worker's own tests, for example), the whole output
+-- directory is used instead, so each target reads interfaces of its own.
+interfaceKey :: Request -> DynFlags -> [String] -> [String]
+interfaceKey r dflags pragmas =
+  configuration
+    : unwords ("general" : [show f | f <- EnumSet.toList (generalFlags dflags), f /= Opt_ExternalInterpreter])
+    : unwords ("ways" : [show w | w <- Set.toList (ways dflags), w `elem` [WayProf, WayDyn]])
+    : filter (not . recorded) (readingFlags (sessionFlags r ++ pragmas))
+  where
+    configuration = case break (== "art") (splitDirectories (reqOutDir r)) of
+      (before, art : cell : hash : _) -> joinPath (before ++ [art, cell, hash])
+      _ -> reqOutDir r
+    -- Whether the flag's whole effect is among the general flags or the ways
+    -- above. An -O flag sets the general flags of its level. GHC parses
+    -- -fPIC apart from its other general flags, so fFlags doesn't name it.
+    -- (-fexternal-interpreter is a general flag too, so this drops it, and
+    -- the key's set of general flags leaves it out.)
+    recorded f =
+      f `elem` ["-dynamic", "-prof", "-debug", "-eventlog", "-fPIC", "-fno-PIC"]
+        || (f == "-O" || ("-O" `isPrefixOf` f && all isDigit (drop 2 f)))
+        || maybe False (`Set.member` generalNames) (stripPrefix "-fno-" f <|> stripPrefix "-f" f)
+    generalNames = Set.fromList (map flagSpecName fFlags)
+
+-- | Remove the flags that are known not to change how GHC reads an
+-- interface. Every other flag is kept, so that compiles that differ in such
+-- a flag read interfaces of their own.
+readingFlags :: [String] -> [String]
+readingFlags flags = case flags of
+  f : _ : rest | f `elem` withArgument -> readingFlags rest
+  f : rest | f `elem` alone || any (`isPrefixOf` f) prefixes -> readingFlags rest
+  f : rest -> f : readingFlags rest
+  [] -> []
+  where
+    -- Flags with an argument that say which unit is compiled, which
+    -- packages it may import, where the outputs go, how to link, and what
+    -- to tell Haddock.
+    withArgument = ["-this-unit-id", "-package", "-package-id", "-package-db", "-odir", "-hidir", "-dumpdir", "-pgml", "-haddock-opts"]
+    -- Flags that turn warnings off, or choose the runtime system that a
+    -- binary is linked with.
+    alone = ["-w", "-threaded"]
+    -- Flags with these prefixes say where sources and headers are, give
+    -- options to the preprocessor, the C compiler and the linker, control
+    -- warnings, language extensions and what GHC dumps, or set a binary's
+    -- runtime options.
+    prefixes = ["-i", "-I", "-D", "-U", "-optP", "-optc", "-optl", "-W", "-fwarn-", "-fno-warn-", "-X", "-ddump-", "-dsuppress-", "-rtsopts", "-with-rtsopts"]
+
+-- | The flags that the module's OPTIONS_GHC and LANGUAGE pragmas give. As in
+-- GHC, they are read from the source after preprocessing, which the module's
+-- summary usually holds. If it doesn't, the source file is read.
+pragmaFlags :: DynFlags -> ModSummary -> IO [String]
+pragmaFlags dflags ms = do
+  buf <- maybe (hGetStringBuffer file) pure (ms_hspp_buf ms)
+  pure (map unLoc (optionsPragmas dflags buf file))
+  where
+    file = msHsFilePath ms
+
+-- | The paths of the package databases that GHC reads for the given flags,
+-- in the order GHC reads them (worked out as in GHC's getUnitDbRefs). The
+-- user's database is left out, because GHC only reads it if it exists.
+dbPaths :: DynFlags -> [FilePath]
+dbPaths dflags = concatMap path (reverse (foldr flag [UserPkgDb, GlobalPkgDb] (packageDBFlags dflags)))
+  where
+    flag (PackageDB p) refs = p : refs
+    flag NoUserPackageDB refs = filter (/= UserPkgDb) refs
+    flag NoGlobalPackageDB refs = filter (/= GlobalPkgDb) refs
+    flag ClearPackageDBs _ = []
+    path GlobalPkgDb = [dropTrailingPathSeparator (globalPackageDatabasePath dflags)]
+    path ref = map dropTrailingPathSeparator (maybeToList (pkgDbRefPath ref))
+
+-- | Remove the session's temporary files and directories, and stop its
+-- external interpreter if it started one, as GHC does when a session ends.
+endSession :: GhcSession -> IO ()
+endSession s = do
+  let hsc = gsEnv s
+  cleanTempFiles (hsc_logger hsc) (hsc_tmpfs hsc)
+  cleanTempDirs (hsc_logger hsc) (hsc_tmpfs hsc)
+  mapM_ stopInterp (hsc_interp hsc)
+  removePathForcibly (gsTmpDir s)
+
+-- | Create a new directory for a session's temporary files, inside the
+-- system's temporary directory. Its name has the worker's process ID and a
+-- number unique within the process, so it is never reused (see Note [A
+-- temporary directory per session]).
+newTmpDir :: IO FilePath
+newTmpDir = do
+  base <- getTemporaryDirectory
+  pid <- getProcessID
+  n <- hashUnique <$> newUnique
+  let dir = base </> ("buck2-ghc-worker-" ++ show pid ++ "-" ++ show n)
+  createDirectory dir
+  pure dir
+
+-- | Compile the request's module, passing each diagnostic to the given
+-- action, and then write the module's .abi file and dep file. It returns the
+-- node that it compiled. If the session's interpreter needs a lock (see
+-- 'gsInterpLock'), it holds the lock for the whole compile.
+compile :: GhcSession -> (Diagnostic -> IO ()) -> Request -> IO Node
+compile s report r = maybe id (\l -> withMVar l . const) (gsInterpLock s) (compileHeld s report r)
+
+compileHeld :: GhcSession -> (Diagnostic -> IO ()) -> Request -> IO Node
+compileHeld s report r = do
+  mapM_ (createDirectoryIfMissing True) (reqMkdirs r)
+  let hsc0 = gsEnv s
+  ems <- summariseSource hsc0 (reqSource r)
+  ms1 <- either (throwDriverErrors hsc0) pure ems
+  -- Before GHC 9.12, summariseFile treats a boot file as an ordinary
+  -- module, so we mark the summary as a boot file ourselves.
+  let ms0
+        | reqBoot r && ms_hsc_src ms1 /= HsBootFile = ms1{ms_hsc_src = HsBootFile, ms_location = addBootSuffixLocnOut (ms_location ms1)}
+        | otherwise = ms1
+  -- Write the .hie file and the stub header of foreign exports to the
+  -- directories that the request's module flags give. The session's flags
+  -- don't set these directories, so GHC would otherwise put the files next
+  -- to the source.
+  withHie <- case moduleArg "-hiedir" r of
+    Just dir -> do
+      let file = dir </> reqModPath r <.> (if reqBoot r then "hie-boot" else "hie")
+      createDirectoryIfMissing True (takeDirectory file)
+      pure ms0{ms_location = setLocationFile HieFile file (ms_location ms0)}
+    Nothing -> pure ms0
+  -- Likewise, use the object and interface files that the request names.
+  -- They are where GHC would put them anyway, given the module's name and
+  -- the session's -odir and -hidir, except for a Main module whose file has
+  -- another name.
+  let outputs = [(ObjFile, "-o"), (HiFile, "-ohi"), (DynObjFile, "-dyno"), (DynHiFile, "-dynohi")]
+      withOutputs =
+        withHie
+          { ms_location = foldr (\(file, flag) loc -> maybe loc (\v -> setLocationFile file v loc) (moduleArg flag r)) (ms_location withHie) outputs
+          }
+  let ms = case moduleArg "-stubdir" r of
+        Just dir -> withOutputs{ms_hspp_opts = (ms_hspp_opts withOutputs){stubDir = Just dir}}
+        Nothing -> withOutputs
+  -- The compile reads interfaces into the external package state for its
+  -- flags, including those of its module's pragmas. The entries of a
+  -- --make compile's home package table are cached by the same key (see
+  -- Note [The flags an interface is read with]).
+  key <- interfaceKey r (ms_hspp_opts ms) <$> pragmaFlags (hsc_dflags hsc0) ms
+  external <- sharedAt (gsExternal s) key initExternalUnitCache
+  let keyed = hsc0{hsc_unit_env = (hsc_unit_env hsc0){ue_eps = external}}
+  -- A one-shot compile reads its home modules into the external state, so
+  -- its home package table is empty. It must be a new empty table for each
+  -- compile, because from GHC 9.14 compileOne adds the module it has
+  -- compiled to the table. Its module graph is the one `ghc -c` would have.
+  (hsc, boots) <-
+    if gsOneShot s
+      then (\e -> (e, Set.empty)) <$> (emptyHome keyed >>= (`withOneShotModuleGraph` ms))
+      else homeView s r key (hscSetFlags (ms_hspp_opts ms) keyed) ms
+  -- The compile's own temporary files (its assembly code, for example) are
+  -- removed when it finishes. The temporary files that must last as long as
+  -- the session are merged into the session's, as `--make -j` does for each
+  -- module. The compile's diagnostics go to the request, through `report`,
+  -- as `ghc -c` would print them: with their location, and the source line
+  -- they are about.
+  tmpfs <- forkTmpFsFrom (hsc_tmpfs hsc)
+  let logger = pushLogHook (\_ lf cls srcSpan doc -> do
+        text <- case cls of
+          MCDiagnostic {} -> do
+            caret <- if log_show_caret lf then getCaretDiagnostic cls srcSpan else pure empty
+            pure (mkLocMessageWarningGroups (log_show_warn_groups lf) cls srcSpan doc $+$ caret)
+          _ -> pure doc
+        report (Diagnostic (isError cls) (renderWithContext (log_default_user_context lf) text))) (hsc_logger hsc)
+  hmi <- compileOne hsc{hsc_tmpfs = tmpfs, hsc_logger = logger} ms 1 1 Nothing emptyHomeModInfoLinkable
+    `finally` (cleanCurrentModuleTempFiles (hsc_logger hsc) tmpfs >> mergeTmpFsInto tmpfs (hsc_tmpfs hsc))
+  let n = (ms_mod_name ms, if reqBoot r then IsBoot else NotBoot)
+  unless (gsOneShot s) $ modifyMVar_ (gsHomes s) (pure . compiled key n boots hmi)
+  -- The dep file comes from the usages that the interface records. When
+  -- GHC compiles its primitive module, GHC.Internal.Prim, it writes the
+  -- module's interface to disk, but returns its built-in interface for the
+  -- module, which records no usages. In that case, the worker reads the
+  -- interface that GHC wrote, as the compile tool does for every module.
+  iface <- if isJust (usages (hm_iface hmi)) then pure (hm_iface hmi) else readInterfaceIn hsc (ml_hi_file (ms_location ms))
+  writeDepFiles r iface
+  pure n
+  where
+    isError cls = case cls of
+      MCDiagnostic SevError _ _ -> True
+      MCFatal -> True
+      _ -> False
+
+-- | A node of the module graph: a home module, or a home module's boot
+-- interface.
+type Node = (ModuleName, IsBootInterface)
+
+-- | What a --make session keeps of its home modules (see Note [Each
+-- compile's home modules]):
+--
+-- - hIfaces: each node's interface and object, read from disk once, or kept
+--   from the session's own compile of the node.
+-- - hEntries: the home package table entries made from those interfaces.
+--   An entry is keyed by the 'interfaceKey' of the compiles it was made for,
+--   its node, and the set of boot interfaces below it.
+--
+-- Nothing here goes stale: the worker lives for one build, in which each
+-- module is compiled once, so no interface is replaced after entries have
+-- been made from it.
+data Homes = Homes
+  { hIfaces :: M.Map Node (ModIface, HomeModLinkable)
+  , hEntries :: M.Map ([String], Node, Set.Set ModuleName) HomeModInfo
+  }
+
+-- | Record a module that the session has just compiled, with the
+-- 'interfaceKey' of the compile and the boot interfaces below the module in
+-- the compile's view.
+compiled :: [String] -> Node -> Set.Set ModuleName -> HomeModInfo -> Homes -> Homes
+compiled key n boots hmi h =
+  Homes
+    { hIfaces = M.insert n (hm_iface hmi, hm_linkable hmi) (hIfaces h)
+    , hEntries = M.insert (key, n, boots) hmi (hEntries h)
+    }
+
+-- | Give the environment the home package table that the compile of the
+-- given module should see (see Note [Each compile's home modules]). The
+-- environment is the session's, with the compile's flags, and the key is
+-- the 'interfaceKey' of those flags. The table holds the home modules below
+-- the module's imports, each in the form that `ghc -c` would see (the whole
+-- module, or its boot interface), and the module's own boot interface if it
+-- has one. It also returns the boot interfaces below the module's imports,
+-- for 'compiled'.
+homeView :: GhcSession -> Request -> [String] -> HscEnv -> ModSummary -> IO (HscEnv, Set.Set ModuleName)
+homeView s r key hsc ms = modifyMVar (gsHomes s) $ \homes0 -> do
+  let unit = homeUnitId (hsc_home_unit hsc)
+      own = ms_mod_name ms
+  -- An import that names another package (with PackageImports) isn't an
+  -- import of a home module, even if a home module has the same name.
+  imports <- fmap concat . forM (textualImports ms) $ \imp -> do
+    found <- findImport hsc imp
+    pure [fst (importName imp) | Found _ m <- [found], isHomeModule (hsc_home_unit hsc) m]
+  let sources = sourceImports ms
+  ownBoot <- if reqBoot r then pure False else doesFileExist (ml_hi_file (addBootSuffixLocn (ms_location ms)))
+  homes1 <- foldM (\h mn -> ifaceOf hsc h (mn, NotBoot)) homes0 imports
+  -- Work out which modules the compile sees as boot interfaces, as GHC
+  -- does in rnImports. Each import's interface records the boot files
+  -- below it (dep_boot_mods), and whether each is reached only through
+  -- {-# SOURCE #-} imports. A module is seen whole if it is imported
+  -- directly, or if anything below an import imports it whole. Otherwise
+  -- it is seen as its boot interface. The module being compiled always
+  -- sees its own boot interface.
+  let recordedBelow mn = M.fromList [(gwib_mod b, gwib_isBoot b) | (u, b) <- Set.toList (dep_boot_mods (mi_deps (fst (hIfaces homes1 M.! (mn, NotBoot))))), u == unit]
+      recorded = M.unionsWith min (map recordedBelow imports ++ [M.fromList [(mn, IsBoot) | mn <- sources]])
+      bootness = M.fromList [(mn, NotBoot) | mn <- imports] `M.union` M.insert own IsBoot recorded
+      node mn b = (mn, M.findWithDefault b mn bootness)
+      roots = [node mn NotBoot | mn <- imports] ++ [node mn IsBoot | mn <- sources]
+  -- Find the nodes below the compile, reading their interfaces as needed.
+  -- Each node's edges go to the modules it imports, and to the modules
+  -- whose boot files are recorded below it. The latter are needed because
+  -- an unfolding in the node's interface may mention one of those modules
+  -- even though the node doesn't import it (for example, through an INLINE
+  -- function of a module it imports). Before GHC 9.14, an entry is
+  -- typechecked against the table as it is when the entry is added, so
+  -- those modules must already be in the table by then.
+  let walk (h, graph) [] = pure (h, graph)
+      walk (h, graph) (n : todo)
+        | n `M.member` graph = walk (h, graph) todo
+        | otherwise = do
+            h' <- ifaceOf hsc h n
+            let iface = fst (hIfaces h' M.! n)
+            let deps =
+                  [node (gwib_mod d) (gwib_isBoot d) | (u, d) <- map directDep (Set.toList (dep_direct_mods (mi_deps iface))), u == unit]
+                    ++ [node (gwib_mod b) IsBoot | (u, b) <- Set.toList (dep_boot_mods (mi_deps iface)), u == unit]
+            walk (h', M.insert n deps graph) (deps ++ todo)
+  (homes2, graph) <- walk (homes1, M.empty) (roots ++ [(own, IsBoot) | ownBoot])
+  -- Build the table in dependency order, reusing the entries made for
+  -- earlier compiles that had the same boot interfaces below them. The
+  -- exception is the modules above the compile's own boot interface. Their
+  -- interfaces refer to the module being compiled, and the compile ties
+  -- those references to itself through its knot, as `ghc -c` does. So
+  -- their entries are typechecked again for this compile, as --make does.
+  -- See Note [Modules above the compile's boot interface].
+  knot <- newIORef emptyTypeEnv
+  let withKnot e = e{hsc_type_env_vars = knotVarsFromModuleEnv (mkModuleEnv [(ms_mod ms, knot)])}
+      ownBootNode = [(own, IsBoot) | ownBoot]
+  env0 <- emptyHome hsc
+  (homes3, env, below) <- foldM (addScc key graph ownBootNode withKnot) (homes2, env0, M.empty) (stronglyConnComp [(n, n, deps) | (n, deps) <- M.toList graph])
+  pure (homes3, (withKnot env, Set.unions [bootsBelow (below M.! n) | n <- roots]))
+
+-- | What is below a node in a compile's view of the home modules, including
+-- the node itself: the modules seen as boot interfaces, and all the nodes.
+data Below = Below {bootsBelow :: Set.Set ModuleName, nodesBelow :: Set.Set Node}
+
+-- | Add a strongly connected component of the compile's module graph to the
+-- compile's home package table, reusing or caching entries under the given
+-- 'interfaceKey'. The components below this one must have been added
+-- already. A component is a single node, or several whole modules that
+-- import one another through boot files. If the component is above the
+-- compile's own boot interface (the third argument, which is empty if there
+-- is none), its entries are typechecked with the compile's knot, for this
+-- compile alone (see Note [Modules above the compile's boot interface]).
+addScc :: [String] -> M.Map Node [Node] -> [Node] -> (HscEnv -> HscEnv) -> (Homes, HscEnv, M.Map Node Below) -> SCC Node -> IO (Homes, HscEnv, M.Map Node Below)
+addScc key graph ownBoot withKnot (h, env, below) scc = do
+  let members = flattenSCC scc
+      outside = [below M.! d | m <- members, d <- graph M.! m, d `notElem` members]
+      -- What is below the members, other than the members themselves. Its
+      -- set of boot interfaces is part of the key of each member's entry.
+      under = Below (Set.fromList [fst d | m <- members, d <- graph M.! m, snd d == IsBoot] <> Set.unions (map bootsBelow outside)) (Set.unions (map nodesBelow outside))
+      selfBelow m = Below (Set.fromList [fst m | snd m == IsBoot] <> bootsBelow under) (Set.fromList members <> nodesBelow under)
+      below' = foldr (\m -> M.insert m (selfBelow m)) below members
+      aboveOwnBoot = any (`Set.member` nodesBelow under) ownBoot
+      -- Entries above the compile's own boot interface are typechecked with
+      -- the compile's knot, and the entry for the boot interface itself is
+      -- made in the compile's table (see Note [The compile's own boot
+      -- interface]). Neither is cached for other compiles.
+      cacheable = not aboveOwnBoot && members /= ownBoot
+      cachedEntries = if cacheable then mapM (\m -> M.lookup (key, m, bootsBelow under) (hEntries h)) members else Nothing
+  case cachedEntries of
+    Just hmis -> do
+      env' <- foldM (\e (m, hmi) -> insertHome e (fst m) hmi) env (zip members hmis)
+      pure (h, env', below')
+    Nothing -> do
+      (env', hmis) <- addHomes (if aboveOwnBoot then withKnot env else env) [hIfaces h M.! m | m <- members]
+      let entries = if cacheable then foldr (\(m, hmi) -> M.insert (key, m, bootsBelow under) hmi) (hEntries h) (zip members hmis) else hEntries h
+      pure (h{hEntries = entries}, env'{hsc_type_env_vars = hsc_type_env_vars env}, below')
+
+-- | Read the node's interface and object from disk into 'hIfaces', unless
+-- they are there already.
+ifaceOf :: HscEnv -> Homes -> Node -> IO Homes
+ifaceOf hsc h n
+  | n `M.member` hIfaces h = pure h
+  | otherwise = do
+      found <- findModuleByName hsc (fst n)
+      case found of
+        Found loc0 m -> do
+          let loc = if snd n == IsBoot then addBootSuffixLocn loc0 else loc0
+          iface <- readInterfaceIn hsc (ml_hi_file loc)
+          obj <- if snd n == IsBoot then pure Nothing else findObjectLinkableMaybe m loc
+          pure h{hIfaces = M.insert n (iface, emptyHomeModInfoLinkable{homeMod_object = obj}) (hIfaces h)}
+        _ -> throwGhcExceptionIO (ProgramError ("buck2-ghc-worker: no interface for home module " ++ moduleNameString (fst n)))
+
+-- | Like `try`, except that asynchronous exceptions (a cancelled request,
+-- or the worker ending) are rethrown rather than caught.
+tryNonAsync :: IO a -> IO (Either SomeException a)
+tryNonAsync act = do
+  result <- try act
+  case result of
+    Left e | Just (_ :: SomeAsyncException) <- fromException e -> throwIO e
+    _ -> pure result
+
+{- Note [The session's state]
+
+1. The problem
+
+To compile a module, GHC needs the interfaces of the home modules (the
+modules of the same package) that the module imports. GHC has two ways to
+get them:
+
+  - One-shot mode (`ghc -c`) reads them from disk into its cache of
+    external interfaces, the same cache it uses for other packages' modules.
+  - --make mode expects them in the compile's home package table (HPT), and
+    finds their instances (and, for Template Haskell, their objects) through
+    the session's module graph.
+
+One-shot mode is simpler for the worker, but its cache can't cope with
+boot files. The cache has no notion of a module's boot interface being
+replaced by the full module. Once a {-# SOURCE #-} import of B has put B's
+boot interface in the cache, B's own compile sees the boot interface's
+instances as another module's. And a later import of B may be given the
+boot interface instead of the module.
+
+2. The solution
+
+So by default a session uses one-shot mode if its target has no boot files
+(see Note [One-shot sessions]), and --make mode if it has. In --make mode:
+
+  - The module graph is the result of GHC's dependency analysis of the
+    whole target, which runs over the target's source tree when the
+    session is made. The worker only uses the graph to tell which modules
+    depend on which.
+  - Each compile has an HPT of its own (see Note [Each compile's home
+    modules]). It is made from what the session keeps: the home modules'
+    interfaces, each read from disk once or kept from the session's own
+    compile of the module, and the HPT entries made from those interfaces.
+
+3. The road not taken
+
+For targets with boot files, an obvious alternative is one-shot mode with a
+separate cache for each compile, as each `ghc -c` process has. We tried it,
+and modules with boot files then failed in ways that they don't with
+`ghc -c`. A module's own boot interface's instances were reported as
+duplicates, or GHC read the module's interface before it had been written.
+We didn't find out why. The likely cause is the session's name cache,
+which the compiles still shared.
+-}
+
+{- Note [One-shot sessions]
+
+1. The problem
+
+Each session reads the interfaces that its compiles need (those of the
+prebuilt libraries, and those of the target's dependencies in the build)
+into an external package state of its own. A large build makes thousands
+of sessions, because the worker drops idle sessions and makes them again
+when their target needs them (see Note [Dropping the idle sessions] in
+Worker). Each of those sessions reads much the same interfaces again. For
+example, every session reads base's interfaces.
+
+2. The solution
+
+A session whose target has no boot files compiles in one-shot mode, as
+`ghc -c` does (see Note [The session's state]). Its compiles share their
+external package state with the compiles of every other one-shot session
+that read interfaces with the same flags (see Note [The flags an interface
+is read with]). So an interface is read only once in the worker's life,
+however many sessions use it. In one-shot mode, GHC reads the interfaces of
+the target's own modules into the external state too. So the session keeps
+no home package table, and its compiles write exactly what `ghc -c` writes.
+
+This is the worker's default session mode, `auto`. The session mode is set
+by BUCK2_GHC_WORKER_SESSION_MODE. Mode `make` uses --make sessions for every
+target, which turns the sharing off. The tests use both modes, so that each
+kind of session is tested on every target it can compile.
+
+3. What the shared state keeps alive
+
+GHC typechecks an interface's declarations lazily. A declaration that
+hasn't been typechecked yet keeps alive the environment of the compile
+that read it, and with it the session's unit state, which is what GHC
+knows about the packages and takes a few MB. So the shared state keeps
+alive the unit state of every session that has read anything into it.
+
+To bound that, the one-shot sessions with the same session flags (the
+successive sessions of one target, in practice) share the unit state of
+the first of them. Then the memory that the shared state keeps alive grows
+with the number of targets, rather than with the number of sessions. For
+the same reason, a one-shot session has no module graph, since the graph
+holds the target's sources.
+
+The shared state is never emptied, and for a large build it holds several
+GB of interfaces. Replacing it with a fresh one now and then doesn't help.
+An old state lives until its last session is dropped, and the fresh ones
+read the same interfaces again.
+
+4. The alternatives
+
+One session with a home unit for each target in the build, as `ghc --make`
+has with several -unit flags, would also share the interfaces, without
+lazy declarations keeping sessions alive. But a module's interface would
+then record the modules of other targets as home modules rather than as
+modules of packages, so it would differ from what `ghc -c` writes. And each
+compile would need the module graphs of its dependencies, which GHC makes
+from their sources.
+
+5. Measurements
+
+These are the results on the bench (bench/Main.hs) at -j8, on workloads
+where the worker drops sessions and makes them again, with the default
+limit of 16 sessions. The command was
+`cabal bench --benchmark-options='8 3 project many'`.
+
+  workload                one-shot sessions   --make sessions
+  project (94 sessions)   22.2-24.7s          32.9-40.3s
+  many (330 sessions)     17.7-21.5s          59.2-78.1s
+
+With a limit high enough that no session is dropped, the two take the same
+time. The worker's peak memory was about the same either way: 5.1-5.5 GB
+on project, 5.0-6.2 GB on many.
+-}
+
+{- Note [Each compile's home modules]
+
+1. The problem
+
+In --make mode, GHC looks up the home modules a compile needs in the
+compile's home package table (HPT). The obvious design for the worker is
+one HPT per session, shared by all its compiles. That doesn't work, because
+of boot files.
+
+Say module B has a boot file, B.hs-boot, and module C imports B with
+{-# SOURCE #-}. When `ghc -c` compiles a module X that imports C, it can
+see B in one of two forms:
+
+  - the boot interface (from B.hs-boot), if X only reaches B through
+    {-# SOURCE #-} imports;
+  - the full module, if X, or anything X imports, imports B normally.
+
+GHC decides which form to use from what the interfaces of X's imports
+record (dep_boot_mods). The choice affects what X's compile sees, and so
+X's interface and object.
+
+With one shared HPT, the form X sees would depend on whether the session
+happened to have compiled B already, which comes down to scheduling. X's
+output would vary from build to build, and differ from `ghc -c`'s. (Since
+GHC 9.14 the HPT is also mutable, so a compile could even see a module that
+a concurrent compile added part-way through.)
+
+2. The solution
+
+Each compile gets its own HPT. It holds exactly the home modules X depends
+on, each in the form `ghc -c` would use, plus X's own boot interface if it
+has one (GHC checks X against it).
+
+Making an HPT entry from an interface is cheap, because GHC typechecks the
+entry's contents lazily. So the session caches the entries. It reuses an
+entry for any later compile that has the same boot interfaces below the
+entry's module, and that reads interfaces with the same flags as the
+compile the entry was made for (see Note [The flags an interface is read
+with]). When the session compiles a module, it discards that module's
+entries and those of everything that depends on it. Modules in an import
+cycle (through boot files) are added together, as GHC's --make does (see
+addHomes).
+
+-}
+
+{- Note [The flags an interface is read with]
+
+1. The problem
+
+GHC typechecks an interface with the flags of the compile that reads it,
+and the external state then keeps the result for every later compile. For
+instance, at -O0 GHC ignores interface pragmas. A compile at -O0 that reads
+base's Data.Bits doesn't learn the arity of toIntegralSized, so it calls
+the function as an unknown one. A module with {-# OPTIONS_GHC -O2 #-} does
+read the pragmas. If the -O2 module reads Data.Bits first, an -O0 compile
+that shares its external state sees the arity, and calls toIntegralSized
+directly.
+
+So a module's object would depend on what the worker had compiled before
+it, and would differ from `ghc -c`'s. Worse, it would differ from build to
+build. After a clean build, an edit to one of a library's modules that
+leaves its code the same, such as an edit to a comment, could still change
+the module's object, because the worker compiles the module after different
+modules this time. buck2 would then link the library again, and compile
+again the Template Haskell modules that depend on it.
+
+The flags that matter are the compile's own. They are the flags of its
+session, followed by those of its module's OPTIONS_GHC pragmas, which GHC
+reads as it compiles the module.
+
+2. The solution
+
+Each compile reads interfaces into an external package state that is kept
+for its flags, including those of its module's pragmas (see
+'interfaceKey'). The entries of a --make compile's home package table are
+cached by the same key. The key leaves out the flags that GHC doesn't
+consult when it reads an interface, so that targets and modules that
+differ only in those flags share what they read. The flags left out say
+where sources, headers and outputs are and which packages a module may
+import, give options to the preprocessor, the C compiler and the linker,
+control warnings, language extensions and what GHC dumps, choose a
+binary's runtime system and its options, or run splices in an external
+interpreter. Every other flag is kept. A flag that GHC doesn't consult either, but that isn't left out,
+only splits the state, which costs time but doesn't affect correctness.
+-}
+
+{- Note [Modules above the compile's boot interface]
+
+1. The problem
+
+Say module M has a boot file, M.hs-boot, and module A imports M with
+{-# SOURCE #-}, while M imports A. That is an import cycle, which the boot
+file breaks. A's interface then mentions M's definitions, and so may the
+unfoldings in it (the code of A's functions that GHC may inline
+elsewhere).
+
+When `ghc -c` compiles M, it reads A's interface while it typechecks M, and
+ties those mentions to the M it is compiling, through the compile's "knot"
+(hsc_type_env_vars). So if M inlines a function of A's that calls M.x, the
+inlined code calls M's own x, and GHC correctly sees a recursion. GHC's
+--make gets the same result by typechecking A again, with the knot, before
+it compiles M. (GHC calls this "rehydrating"; see GHC's Note [Hydrating
+Modules].)
+
+If the worker made A's HPT entry from M's boot interface instead, the
+inlined code would call the boot file's M.x, which to GHC is a different
+thing, and M's interface would differ from `ghc -c`'s.
+
+2. The solution
+
+The worker does what --make does. When it makes the HPT for M's compile,
+the entries of the modules that depend on M's boot interface (A here) are
+made for that compile alone, with its knot, and aren't cached.
+-}
+
+{- Note [The compile's own boot interface]
+
+1. The problem
+
+GHC typechecks an HPT entry's contents lazily, against the HPT the entry
+was made in, when something first needs them. Since GHC 9.14 the HPT is
+mutable, and compileOne ends by adding the module it has just compiled to
+the compile's own HPT (initModDetails).
+
+So when the worker compiles M, the HPT has M's boot interface in it,
+because GHC checks M against it. If the entry for that boot interface is
+only typechecked after the compile, it finds the full M in the HPT, and
+takes M's definitions for its own. The boot interface's instances then
+become M's, unfoldings and all. A module that later imports M with
+{-# SOURCE #-} and inlines one of those instances then refers to something
+that the boot interface doesn't have, and GHC panics ("lookupVers1").
+
+2. The solution
+
+The entry for M's boot interface made for M's own compile is used by that
+compile alone, and never cached. An entry for M's boot interface made for
+any other compile is safe to cache, since no other compile adds M to its
+HPT.
+-}
+
+{- Note [Flags of the whole process]
+
+1. The problem
+
+A few of GHC's flags set state for the whole process, not just for the
+session they are given to. In the worker, one session's setting would then
+apply to every session, or to none:
+
+  - -fno-state-hack: the simplifier reads it from a global, which
+    parseDynamicFlags sets and the first optimised compile then fixes for
+    good (unsafeHasNoStateHack);
+  - -dppr-debug and -dno-debug-output: the pretty-printer and GHC's tracing
+    read them from globals set the same way (unsafeHasPprDebug,
+    unsafeHasNoDebugOutput);
+  - -dinitial-unique and -dunique-increment: only ghc's Main applies them;
+  - -H and -Rghc-timing: these set the runtime's options.
+
+2. The solution
+
+The worker refuses to make a session with any of these flags, and
+restores the globals that parsing the session's flags has just set. A
+target that needs these flags must be compiled without the worker. (The
+same flags in an OPTIONS_GHC pragma don't reach the globals, in `ghc -c` or
+in the worker, so they are fine there.)
+-}
+
+{- Note [Compiling whenever buck2 asks]
+
+buck2 decides when a module needs compiling again, from the module's dep
+file (see Note [Early cut-off by dep files] in compile_per_module.bzl). So
+the worker should compile every request it gets, and never let GHC decide
+that the module is up to date.
+
+buck2 already removes an action's previous outputs before running it, so
+GHC normally finds no old interface to compare with. The rules also pass
+-fforce-recomp, so that GHC compiles the module whatever is on disk, in the
+worker as in the compile tool.
+
+This matters for Template Haskell. A splice can read a file without
+recording it (with runIO, and without addDependentFile), so the module's
+interface doesn't list the file. After the file changed, GHC's check would
+find the module up to date, and keep its old object. With -fforce-recomp,
+the worker compiles such a module whenever buck2 asks for it.
+-}
+
+{- Note [A temporary directory per session]
+
+1. The problem
+
+To run a splice, GHC links the objects it needs into a temporary shared
+library, and loads it with dlopen. The library's file name comes from a
+counter in the session's temporary-file state, and each new session starts
+counting again. But the dynamic linker caches libraries by path. If it has
+loaded a library from a path before, dlopen returns that library again,
+even if the file at that path is new.
+
+So after the worker dropped a session (and removed its files), a new
+session could create a library at a path that the old session had already
+loaded. The new session's splice would get the old library, and fail to
+find the new library's symbols ("During interactive linking, GHCi couldn't
+find the following symbol").
+
+2. The solution
+
+Each session puts its temporary files in a directory of its own, which is
+never reused.
+-}
+
+{- Note [Hashing the libraries]
+
+1. The problem
+
+For each module that runs Template Haskell, GHC records a hash of every
+Haskell library (hs-libraries) and object file that the interpreter loaded
+(`mkObjectUsage`), and caches the hashes in the session's finder cache.
+Each library is a few megabytes, so hashing is slow, and in the worker it
+would happen far too often:
+
+  - Each session has its own cache, and a target may have several sessions
+    in a build, since a dropped session is made again when it is needed
+    (see Note [Dropping the idle sessions] in Worker).
+  - Modules compiled at the same time in one session all miss the cache
+    together, and each of them hashes every library.
+
+2. The solution
+
+All the sessions share one cache of hashes for the life of the worker, and
+look up a hash under a lock. Then one compile hashes each library while
+the others wait for it (see sharedFileHashes). Before GHC 9.12 the cache's
+lookup function can't be replaced, so the sessions share the cache without
+the lock, and compiles that miss it at the same time each hash the library.
+
+Caching the hashes for the worker's whole life is safe, because the
+libraries don't change while the worker lives. buck2 writes each output
+only once in a build, and a worker lives for one build. (buck2 starts a
+worker for each command, which the rules' tests check.)
+-}
+
+{- Note [One copy of each package database]
+
+1. The problem
+
+A session reads its package databases from disk when it is made. They are
+the database of each library in the build, and the database of the
+third-party packages, which describes hundreds of packages. A whole build
+makes thousands of sessions, and each session would keep its own copy of
+the databases while it lives, though most of the copies are the same.
+
+2. The solution
+
+The worker keeps every database it has read, keyed by path, for its whole
+life. It gives a new session the copies of the session's databases, and
+GHC then uses them instead of reading the databases (as it does when a
+session's flags are set again). If some of a session's databases haven't
+been read yet, GHC reads all of them, and the worker keeps what GHC read.
+
+Keeping the databases for the worker's life is safe for the same reason as
+in Note [Hashing the libraries]: buck2 writes each database only once in a
+build. If a session would read the user's database, or the databases in
+GHC_PACKAGE_PATH, which the rules don't make, the worker leaves the
+session's databases to GHC.
+-}
+
+{- Note [One name cache for all the sessions]
+
+1. The problem
+
+GHC gives each entity that it reads from an interface a Name, made of the
+entity's module, its name, and a unique number. The name cache maps each
+module and name to its Name, so that every interface that mentions an
+entity gives it the same Name. A session made with GHC's API has a name
+cache of its own. So when many sessions read the same libraries'
+interfaces, as they do in a clean build of a large project, each session
+holds its own Names for all of those entities, and its own cache of them.
+
+2. The solution
+
+All the sessions share the name cache of the worker's own session (see
+withWorker), as all the home units of a multi-unit `ghc --make` do. An
+entity has the same module and name in every session, so it can have the
+same Name in every session. That holds for the modules of the build's
+targets too. A target's module is a home module in the target's own
+sessions, and comes from a package db in its dependents' sessions, but it
+is the same module, with the same unit id. GHC takes a lock to change the
+cache, as it must for the threads of `--make -j`. The Names that a dropped
+session read stay in the cache, but a later session would read most of
+them again anyway.
+
+One-shot sessions need the shared cache, since they share interfaces (see
+Note [One-shot sessions]), and the Names in those interfaces must be the
+ones that every session would make. For --make sessions, sharing the cache
+saves a little. On the bench's `project` workload, a worker patched to give
+each --make session a cache of its own took the same time, with 5-7% more
+peak memory and 2-4% more CPU.
+-}
diff --git a/buck2/prelude/haskell/tools/worker/src/Worker.hs b/buck2/prelude/haskell/tools/worker/src/Worker.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/src/Worker.hs
@@ -0,0 +1,440 @@
+-- | The worker's sessions. The worker keeps a GHC session for each set of
+-- session flags, compiles each request in the session for its flags, and
+-- decides when to drop sessions. See Note [How the worker works].
+module Worker (Worker, withWorker, compileRequest, shutdown) where
+
+import Control.Concurrent (forkIO, getNumCapabilities)
+import Control.Concurrent.MVar
+import Control.Exception (SomeAsyncException, SomeException, finally, fromException, mask, mask_, throwIO, try, uninterruptibleMask_)
+import Control.Monad (when)
+import Data.IORef
+import Data.List (partition, sortOn)
+import qualified Data.Map as M
+import Data.Maybe (isJust)
+import qualified Data.Set as Set
+import Foreign.C.Types (CInt (..))
+import System.Directory (createDirectoryIfMissing)
+import System.Environment (lookupEnv)
+import System.FilePath (takeDirectory)
+import System.IO (hPutStrLn, stderr)
+import Text.Read (readMaybe)
+
+import GHC (getSession, mkModuleName, runGhc)
+import GHC.Driver.Env (hsc_NC)
+import GHC.Types.Name.Cache (NameCache)
+import GHC.Clock (getMonotonicTime)
+import GHC.Stats (RTSStats (..), getRTSStats, getRTSStatsEnabled)
+import GHC.Types.SourceError (SourceError)
+import GHC.Unit.Finder.Types (FinderCache)
+import GHC.Unit.Types (IsBootInterface (..))
+import Control.Monad.IO.Class (liftIO)
+
+import Compat (sharedFileHashes)
+import Request
+import Session
+
+-- | The state of the worker. It holds the worker's sessions, one for each
+-- set of session flags (see Note [How the worker works]). A session is made
+-- when the first request with its flags arrives. It keeps the interfaces it
+-- has read until the worker drops it (see Note [Dropping the idle
+-- sessions]).
+data Worker = Worker
+  { wCompiler :: String -- the GHC that the requests name
+  , wLibdir :: FilePath -- the libdir that the requests name
+  , wSessions :: MVar (M.Map [String] Entry) -- the sessions, keyed by their session flags
+  , wMaxSessions :: Int -- how many sessions to keep, counting those in use and those idle (BUCK2_GHC_WORKER_SESSIONS)
+  , wCompiled :: MVar (M.Map FilePath (Set.Set Node)) -- for each target, keyed by its output directory, the modules compiled so far
+  , wVerbose :: Bool -- whether to log each compile and each session made or dropped (BUCK2_GHC_WORKER_VERBOSE)
+  , wFiles :: FinderCache -- holds the file hashes that the sessions share (see Note [Hashing the libraries] in Session)
+  , wNames :: NameCache -- the name cache that the sessions share (see Note [One name cache for all the sessions] in Session)
+  , wShared :: Shared -- everything else that the sessions share
+  , wMode :: SessionMode -- how the sessions compile (BUCK2_GHC_WORKER_SESSION_MODE)
+  }
+
+-- | A session in the worker's map, and how it is being used. The session
+-- may have been made, may still be being made, or may have failed.
+data Entry = Entry
+  { eSession :: MVar (Either SomeException GhcSession) -- empty while the session is being made
+  , eInFlight :: Int -- the number of requests using the session
+  , eLastDone :: Double -- when the session's last compile finished
+  , eFinished :: Bool -- whether all the modules of the session's target have been compiled
+  }
+
+-- | Start the worker for the GHC and libdir that the first request names,
+-- and run the given action with it. While the action runs, GHC's signal
+-- handlers are installed, so buck2's SIGTERM arrives as a 'Signal'
+-- exception.
+withWorker :: Request -> (Worker -> IO a) -> IO a
+withWorker first k = do
+  sessions <- newMVar M.empty
+  verbose <- isJust <$> lookupEnv "BUCK2_GHC_WORKER_VERBOSE"
+  maxSessions <- maybe getNumCapabilities pure . (>>= readMaybe) =<< lookupEnv "BUCK2_GHC_WORKER_SESSIONS"
+  compiled <- newMVar M.empty
+  files <- sharedFileHashes
+  shared <- newShared
+  mode <- lookupEnv "BUCK2_GHC_WORKER_SESSION_MODE" >>= \m -> case m of
+    Nothing -> pure AutoSessions
+    Just "auto" -> pure AutoSessions
+    Just "make" -> pure MakeSessions
+    Just other -> fail ("buck2-ghc-worker: BUCK2_GHC_WORKER_SESSION_MODE is " ++ other ++ ", not auto or make")
+  -- See Note [Starting the object linker once].
+  initLinker 1
+  -- The session that `runGhc` makes is never used to compile anything. It
+  -- is there for two things: GHC's signal handlers, which turn SIGTERM into
+  -- a 'Signal' exception, and its name cache, which all the sessions share
+  -- (see Note [One name cache for all the sessions] in Session). The
+  -- sessions that compile are made on demand, by withSession.
+  runGhc (Just (reqLibdir first)) $ do
+    names <- hsc_NC <$> getSession
+    liftIO (k (Worker (reqCompiler first) (reqLibdir first) sessions maxSessions compiled verbose files names shared mode))
+
+-- | Start the runtime's object linker (see Note [Starting the object linker
+-- once]). A non-zero argument makes the linker keep the CAFs of the code it
+-- loads, which is what GHC's interpreter asks for.
+foreign import ccall unsafe "initLinker_" initLinker :: CInt -> IO ()
+
+-- | Remove sessions from the map. Every idle session of a finished target is
+-- removed. Then, while there are still more sessions than 'wMaxSessions',
+-- the least recently used of the other idle sessions is removed. It returns
+-- the map that is left, and the removed sessions, which the caller must end.
+-- See Note [Dropping the idle sessions].
+dropIdle :: Worker -> M.Map [String] Entry -> (M.Map [String] Entry, [Entry])
+dropIdle w m = (foldr M.delete m (map fst gone), map snd gone)
+  where
+    (finished, idle) = partition (eFinished . snd) (sortOn (eLastDone . snd) (M.toList (M.filter ((== 0) . eInFlight) m)))
+    gone = finished ++ take (M.size m - length finished - wMaxSessions w) idle
+
+-- | Record that the session has compiled a module of its target. Once every
+-- module of the target has been compiled, mark all the target's sessions
+-- finished, so that they are dropped when idle. A target whose dependency
+-- analysis failed is never finished, since there is no list of its modules
+-- to count against.
+compiledIn :: Worker -> GhcSession -> Node -> IO ()
+compiledIn w s n = mask_ $ do
+  let target = gsOutDir s
+  finished <- modifyMVar (wCompiled w) $ \m -> do
+    let done = Set.insert n (M.findWithDefault Set.empty target m)
+    pure (M.insert target done m, maybe False (`Set.isSubsetOf` done) (gsModules s))
+  when finished $ do
+    uninterruptibleMask_ $ modifyMVar_ (wSessions w) $ traverse $ \e -> do
+      made <- tryReadMVar (eSession e)
+      pure $ case made of
+        Just (Right s') | gsOutDir s' == target -> e{eFinished = True}
+        _ -> e
+    when (wVerbose w) $ hPutStrLn stderr ("buck2-ghc-worker: " ++ target ++ " finished")
+
+-- | End the dropped sessions in a thread of their own, so that the request
+-- that dropped them can be answered without waiting for the sessions'
+-- external interpreters to stop. If a session can't be ended, the error is
+-- logged and the session's temporary files are left behind. The second
+-- argument is the number of sessions left, for the log.
+endDropped :: Worker -> Int -> [Entry] -> IO ()
+endDropped _ _ [] = pure ()
+endDropped w left gone = do
+  _ <- forkIO $ mapM_ (\e -> tryNonAsync (endEntry e) >>= either (\err -> hPutStrLn stderr ("buck2-ghc-worker: ending a session: " ++ show err)) pure) gone
+  -- Don't run a major GC to reclaim the dropped sessions' memory now. Once
+  -- the worker has loaded libraries for Template Haskell, every major GC
+  -- checks each static closure against those libraries, which is slow, and
+  -- a shared worker drops sessions all the time.
+  when (wVerbose w) $ hPutStrLn stderr ("buck2-ghc-worker: " ++ show (length gone) ++ " idle sessions dropped, " ++ show left ++ " left")
+
+-- | End the entry's session, if it was made successfully.
+endEntry :: Entry -> IO ()
+endEntry e = tryReadMVar (eSession e) >>= mapM_ (either (const (pure ())) endSession)
+
+-- | End every session, before the worker exits. In verbose mode, also log
+-- the worker's peak memory, its largest live heap, the time it spent
+-- collecting garbage, and the CPU time of its mutator and of its
+-- collections, if the RTS collects these statistics (+RTS -T).
+shutdown :: Worker -> IO ()
+shutdown w = do
+  readMVar (wSessions w) >>= mapM_ endEntry . M.elems
+  enabled <- getRTSStatsEnabled
+  when (wVerbose w && enabled) $ do
+    stats <- getRTSStats
+    hPutStrLn stderr ("buck2-ghc-worker: peak memory " ++ show (max_mem_in_use_bytes stats `div` 2 ^ (20 :: Int)) ++ " MB, max live " ++ show (max_live_bytes stats `div` 2 ^ (20 :: Int)) ++ " MB, GC " ++ show (gc_elapsed_ns stats `div` 10 ^ (6 :: Int)) ++ " ms")
+    hPutStrLn stderr ("buck2-ghc-worker: CPU mutator " ++ show (mutator_cpu_ns stats `div` 10 ^ (6 :: Int)) ++ " ms, GC " ++ show (gc_cpu_ns stats `div` 10 ^ (6 :: Int)) ++ " ms")
+
+-- | Run an action in the session for the request's session flags, making
+-- the session first if there is none yet. If the session can't be made,
+-- this request fails with the reason, and so do the requests that were
+-- waiting for the session. The next request with the same flags tries to
+-- make it again. If the request that is making the session is cancelled
+-- instead, one of the waiting requests makes it again, and the others wait
+-- for that one.
+withSession :: Worker -> Request -> (GhcSession -> IO a) -> IO a
+withSession w r k = mask $ \restore -> do
+  let flags = sessionFlags r
+  -- Asynchronous exceptions are masked here, except while the session is
+  -- being made and while it is used. If a request were cancelled anywhere
+  -- else, it could leave its entry's session never filled in, so that the
+  -- requests waiting for the session would block for ever. Or it could
+  -- leave the entry's count of requests in flight too high, so that the
+  -- session would never be dropped.
+  (var, fresh) <- modifyMVar (wSessions w) $ \m -> case M.lookup flags m of
+    Just e -> pure (M.insert flags e{eInFlight = eInFlight e + 1} m, (eSession e, False))
+    Nothing -> do
+      v <- newEmptyMVar
+      pure (M.insert flags (Entry v 1 0 False) m, (v, True))
+  -- `ours f` applies f to the entry that this request counted itself in, if
+  -- that entry is still in the map. It may not be. If making the session
+  -- failed, the request that was making it removed the entry, and another
+  -- request may since have added a new entry for the same flags. (The waits
+  -- for the lock below are uninterruptible, since the lock is only held
+  -- briefly.)
+  let ours f = M.update (\e -> Just (if eSession e == var then f e else e)) flags
+      -- `done` counts the request out of its session, and drops idle
+      -- sessions. It does both while holding the lock on the sessions. A
+      -- request also holds that lock while it counts itself in, so no
+      -- request can be using a session that is dropped here.
+      done = do
+        t <- getMonotonicTime
+        (left, gone) <- uninterruptibleMask_ $ modifyMVar (wSessions w) $ \m -> do
+          let (m', gone) = dropIdle w (ours (\e -> e{eInFlight = eInFlight e - 1, eLastDone = t}) m)
+          pure (m', (M.size m', gone))
+        endDropped w left gone
+  (`finally` done) $ do
+    when fresh $ do
+      t0 <- getMonotonicTime
+      made <- try (restore (newSession (wLibdir w) (wFiles w) (wNames w) (wShared w) (wMode w) r))
+      t1 <- getMonotonicTime
+      -- If making the session failed, remove its entry before the waiting
+      -- requests see the failure. Then a waiting request that makes the
+      -- session again, or the next request with these flags, makes a new
+      -- entry rather than finding the failed one.
+      case made of
+        Left _ -> uninterruptibleMask_ (modifyMVar_ (wSessions w) (pure . M.filter ((/= var) . eSession)))
+        Right _ -> pure ()
+      putMVar var made
+      when (wVerbose w) $ hPutStrLn stderr ("buck2-ghc-worker: a " ++ either (const "") (\s -> if gsOneShot s then "one-shot " else "--make ") made ++ "session for the flags of " ++ reqModPath r ++ " in " ++ show (round ((t1 - t0) * 1000) :: Int) ++ "ms")
+      either (\e -> when (isAsync e) (throwIO e)) (const (pure ())) made
+    made <- readMVar var
+    case made of
+      -- The request that was making the session was cancelled. That isn't
+      -- a failure of this request, so start again, which makes the session
+      -- unless another waiting request has already started to.
+      Left e | isAsync e, not fresh -> restore (withSession w r k)
+      _ -> either throwIO (restore . k) made
+  where
+    isAsync e = isJust (fromException e :: Maybe SomeAsyncException)
+
+-- | Compile the request's module in the session for its session flags. It
+-- returns the exit code for buck2, and the compile's diagnostics as text.
+--
+-- A request that names a different GHC or libdir from the worker's fails
+-- with exit code 2. The worker makes all of its sessions with its own
+-- libdir, so it can't compile a request for another.
+compileRequest :: Worker -> Request -> IO (Int, String)
+compileRequest w r
+  | reqCompiler r /= wCompiler w =
+      pure (2, "buck2-ghc-worker: this worker runs " ++ wCompiler w ++ ", the request names " ++ reqCompiler r ++ "\n")
+  | reqLibdir r /= wLibdir w =
+      pure (2, "buck2-ghc-worker: this worker uses the libdir " ++ wLibdir w ++ ", the request names " ++ reqLibdir r ++ "\n")
+  | otherwise = do
+      -- The worker lives for one build, in which buck2 compiles each module
+      -- once. Its sessions rely on that: what they keep of a module is
+      -- never replaced (see 'Homes' in Session).
+      done <- M.findWithDefault Set.empty (reqOutDir r) <$> readMVar (wCompiled w)
+      if requestNode r `Set.member` done
+        then pure (2, "buck2-ghc-worker: this worker has already compiled " ++ reqModPath r ++ " in " ++ reqOutDir r ++ ", and a worker lives for one build\n")
+        else do
+          diagnostics <- newIORef []
+          t0 <- getMonotonicTime
+          result <- tryNonAsync (withSession w r (\s -> compile s (\d -> modifyIORef' diagnostics (d :)) r >>= compiledIn w s))
+          t1 <- getMonotonicTime
+          ds <- reverse <$> readIORef diagnostics
+          when (wVerbose w) $ hPutStrLn stderr ("buck2-ghc-worker: " ++ reqModPath r ++ " " ++ show (round ((t1 - t0) * 1000) :: Int) ++ "ms")
+          let text = map diagText ds
+          -- The messages are the action's diagnostics output as well as its
+          -- answer.
+          answered (reqDiagnostics r) $ case result of
+            Right () | not (any diagIsError ds) -> (0, unlines text)
+            Right () -> (1, unlines text)
+            -- compileOne throws a compile's errors as a SourceError rather than
+            -- logging them. (In --make mode, GHC's driver catches and logs them
+            -- after the compile.) The errors from summarising the source arrive
+            -- the same way.
+            Left e -> case fromException e :: Maybe SourceError of
+              Just se -> (1, unlines (text ++ [show se]))
+              -- Other failures, such as a splice that couldn't load the code
+              -- it runs, come with no location, so they get the source's, as
+              -- GHC's errors have.
+              Nothing -> (1, unlines (text ++ [reqSource r ++ ": error:"] ++ map ("    " ++) (lines (dropWhile (== '\n') (show e)))))
+
+-- | Write an answer's messages to the given file, and give the answer.
+answered :: FilePath -> (Int, String) -> IO (Int, String)
+answered file answer = do
+  createDirectoryIfMissing True (takeDirectory file)
+  writeFile file (snd answer)
+  pure answer
+
+-- | The node that the request compiles: its module, or its module's boot
+-- interface.
+requestNode :: Request -> Node
+requestNode r = (mkModuleName [if c == '/' then '.' else c | c <- reqModPath r], if reqBoot r then IsBoot else NotBoot)
+
+{- Note [How the worker works]
+
+buck2 starts the worker as a persistent worker (see Note [The persistent
+worker] in compile_per_module.bzl). It sends the worker each module's
+compile action as a request, which holds the action's arguments, over gRPC
+on a Unix socket. The worker compiles the requests concurrently, each in
+the thread that received it, and answers each one with the compile's exit
+code and diagnostics. One worker serves many targets.
+
+Terms
+
+- Request: one module to compile (see Request). When buck2 runs the action
+  without the worker, the compile tool
+  (prelude/haskell/tools/ghc-api/PerModuleCompile.hs) takes the same
+  request.
+- Session flags: the flags of a request that are the same for all the
+  modules of its target. A target that is built in several ways (static,
+  shared, profiled) has a different set of session flags for each way.
+- Session: a GHC session for one set of session flags. It keeps the
+  interfaces it has read. The worker makes a session when the first
+  request with its flags arrives, and drops it when it is no longer needed.
+- Home modules: the modules of the session's target. In a --make session,
+  each compile gets a home package table of its own (see Note [Each
+  compile's home modules] in Session).
+- Boot interface: the interface of a module's .hs-boot file. A
+  {-# SOURCE #-} import of the module sees the boot interface instead of
+  the module itself.
+
+The modules
+
+- Main: the process. It starts the worker when the first request arrives,
+  and exits on buck2's SIGTERM, or when buck2 has gone away.
+- Grpc and Proto: buck2's worker protocol.
+- Request: a request's arguments, and the flags of its session.
+- Worker: the sessions, and when to drop them (see Note [Dropping the idle
+  sessions]).
+- Session: compiling a request in a session (see Note [The session's
+  state], and the Notes after it).
+- DepFile: writing the .abi file and the dep file that the rules need as
+  well as GHC's own outputs.
+- Compat: the parts of the GHC API that differ between the GHC versions
+  that the worker can be built with.
+-}
+
+{- Note [Starting the object linker once]
+
+1. The problem
+
+The runtime has one object linker per process. Each session's interpreter
+starts the linker the first time it runs code, by calling initLinker_.
+That function is meant to be safe to call more than once. But it records
+whether it has already run in a flag that it neither locks nor sets
+atomically. So if two sessions ran their first splices at the same time,
+both would fill the linker's symbol table, the chains in the table's hash
+buckets would form loops, and both compiles would hang. (GHC's --make never
+hits this, because it has only one interpreter, which starts the linker
+once.)
+
+2. The solution
+
+The worker starts the linker itself when the worker starts, before any
+session can. When a session's interpreter calls initLinker_ later, the
+flag is already set, and the call does nothing.
+-}
+
+{- Note [Dropping the idle sessions]
+
+1. The problem
+
+A --make session keeps every interface it has read, which can be a few
+hundred MB for a large package. (A one-shot session keeps little of its
+own, since the interfaces it reads go into state that all the one-shot
+sessions share; see Note [One-shot sessions] in Session.) buck2 keeps the
+worker until the end of the build, and one worker serves many targets (see
+Note [The persistent worker] in compile_per_module.bzl). If the worker kept
+every session, a clean build of a large project would use more memory than
+the machine has.
+
+So the worker has to drop sessions. But dropping a session that is still
+needed costs time. The next request with its flags makes the session again,
+which means analysing the target's sources and reading its imports from
+disk again. And a session is often idle while it is still needed. buck2
+starts each module as soon as its imports are compiled, so many targets are
+part-built at once. Each of them is waiting for a slow module, either one
+of its own or one of a dependency's, and there are more such targets than
+compiles running at once (-j).
+
+2. The solution
+
+After each compile, the worker:
+
+  - drops the idle sessions of every finished target (see 3); and
+  - while it has more sessions, in use or idle, than its limit, drops the
+    least recently used idle session. The limit is BUCK2_GHC_WORKER_SESSIONS,
+    which the rules set from the buckconfig. If that isn't set, the limit
+    is the number of capabilities.
+
+The limit bounds the memory, as cabal's -j does by bounding the number of
+ghc --make processes. Defaulting to the number of capabilities scales the
+limit with the machine, as buck2's default -j does. buck2's -j bounds the
+number of sessions in use, so a limit of at least -j leaves room for some
+idle sessions too. A limit below -j never stops a compile from running,
+since the worker only drops idle sessions, but it can make the worker drop
+a session as soon as its compile is done.
+
+3. Finished targets
+
+Each way that a target is built in (static, shared, profiled) is compiled
+separately, into an output directory of its own, though with the same unit
+id. So here a target means a target built in one way, and the worker
+recognises a target's sessions by their output directory. A target is
+finished once the worker has compiled every module and boot interface that
+GHC's analysis of the target found. The compiles count whichever of the
+target's sessions they ran in, since the worker may have dropped the
+target's session and made it again.
+
+A target that is only partly built never finishes, and its sessions are
+only dropped because of the limit. That happens when a single module is
+requested on its own, when a build needs only some of a target's modules,
+in an incremental build, and when a module fails to compile. It also
+happens when GHC's analysis of the target fails (because a module's imports
+don't parse, for example), since that leaves no list of modules to count
+against. If a target is requested again after it has finished, its session
+is simply made again. That costs time, but never compiles anything wrongly.
+
+4. Measurements
+
+These are the results on the bench's `project` workload (bench/Main.hs),
+where all 30 targets are part-built at once, at -j8, with limits
+(BUCK2_GHC_WORKER_SESSIONS) of 4, 16 and 32. The command was
+`cabal bench --benchmark-options='8 3 project'`.
+
+  limit   one-shot sessions                    --make sessions
+          made     wall         peak         made     wall         peak
+  4       120-124  21.8-24.7s   5.1-5.2 GB   120-122  38.0-44.6s   2.4-2.5 GB
+  16      93-95    22.2-24.7s   5.2 GB       91-93    32.9-40.3s   5.1-5.5 GB
+  32      30       23.1-25.2s   5.2 GB       30       22.5-23.1s   5.2 GB
+
+So with one-shot sessions the limit matters little, and with --make
+sessions it trades memory for speed.
+
+5. The alternatives
+
+  - Dropping sessions after a timeout doesn't bound the memory. With a
+    timeout of thirty seconds, for example, the worker holds on to the
+    sessions of every target finished in the last half minute, however
+    many there are.
+  - Dropping sessions above a memory threshold would overshoot. The RTS
+    only knows the size of the live heap after a major GC, and a dropped
+    session's memory only comes back at the next major GC.
+  - Exiting the worker doesn't work. buck2 keeps the worker it started
+    until the build is done. Once the worker has exited, buck2 fails each
+    action it sends to it, rather than starting another worker.
+  - Keeping just the sessions that have requests still to come isn't
+    possible, because the worker can't see those requests. buck2 only sends
+    an action when it runs it. The worker could guess, from the targets
+    that have a module whose imports are all compiled. But when many
+    targets advance in turn, all of them have such a module, and some
+    sessions must be dropped all the same.
+
+After the worker drops sessions, the memory that the process still holds
+is the RTS's own. It is the allocation area, which the RTS never gives back
+(hence the small default -A in the cabal file), and the part of the heap's
+peak that the RTS keeps.
+-}
diff --git a/buck2/prelude/haskell/tools/worker/test/Client.hs b/buck2/prelude/haskell/tools/worker/test/Client.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/test/Client.hs
@@ -0,0 +1,104 @@
+{-# LANGUAGE OverloadedStrings #-}
+-- | A client that talks to the worker the way buck2 does, for the test suite
+-- and the benchmarks.
+module Client (ghcPkgOf, grpc, poll, startWorkerProcess, withWorkerProcess) where
+
+import Control.Concurrent (threadDelay)
+import Control.Exception (IOException, bracket, finally, try)
+import Control.Monad (unless)
+import Data.ByteString (ByteString)
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Builder as BB
+import qualified Data.ByteString.Char8 as B8
+import qualified Network.HTTP.Types as H
+import qualified Network.HTTP2.Client as H2
+import Network.Socket
+import Data.List (isPrefixOf)
+import System.Directory (removePathForcibly)
+import System.Environment (getEnvironment)
+import System.FilePath (takeDirectory, takeFileName, (</>))
+import System.Process (CreateProcess (..), ProcessHandle, StdStream, createProcess, proc, terminateProcess, waitForProcess)
+
+import Proto
+
+-- | Send a request with the given arguments to the worker listening on the
+-- socket, as a gRPC call of /worker.Worker/Execute, and return the exit code
+-- and stderr that the worker answers with. Unlike buck2, which sends many
+-- requests over one connection, this opens a new connection for each
+-- request. The worker handles both the same way.
+grpc :: FilePath -> [String] -> IO (Int, String)
+grpc path args = do
+  sock <- socket AF_UNIX Stream defaultProtocol
+  connect sock (SockAddrUnix path)
+  -- Allow the connection to stay quiet for far longer than any compile
+  -- takes, instead of http2's default of 30 seconds. The callers put their
+  -- own time limits on compiles.
+  conf <- H2.allocSimpleConfig' sock 4096 600000000
+  (code, err) <- H2.run H2.defaultClientConfig conf client `finally` (H2.freeSimpleConfig conf >> close sock)
+  pure (code, B8.unpack err)
+  where
+    payload = encodeExecuteCommand (map B8.pack args)
+    frame = BB.word8 0 <> BB.word32BE (fromIntegral (B.length payload)) <> BB.byteString payload
+    client :: H2.Client (Int, ByteString)
+    client sendRequest _ = sendRequest (H2.requestBuilder H.methodPost "/worker.Worker/Execute" [("content-type", "application/grpc"), ("te", "trailers")] frame) $ \rsp -> do
+      body <- readAll rsp []
+      pure (decodeExecuteResponse (B.drop 5 body))
+    readAll rsp acc = do
+      chunk <- H2.getResponseBodyChunk rsp
+      if B.null chunk then pure (B.concat (reverse acc)) else readAll rsp (chunk : acc)
+
+-- | Start a worker the way buck2 starts it. The worker runs in the given
+-- directory, with the given arguments (RTS options, for example), the given
+-- environment variables added to this process's environment, and the given
+-- stderr. Its socket is w.sock in that directory. Once the worker accepts
+-- connections on the socket, this returns the worker's process and the
+-- socket's path.
+startWorkerProcess :: FilePath -> [String] -> FilePath -> [(String, String)] -> StdStream -> IO (ProcessHandle, FilePath)
+startWorkerProcess worker args dir settings0 err = do
+  let sock = dir </> "w.sock"
+      settings = ("WORKER_SOCKET", sock) : settings0
+  removePathForcibly sock
+  environment <- getEnvironment
+  (_, _, _, ph) <- createProcess (proc worker args){cwd = Just dir, env = Just (settings ++ filter ((`notElem` map fst settings) . fst) environment), std_err = err}
+  -- The socket's file appears when the worker binds it, a moment before the
+  -- worker starts listening, so the first connections may be refused. So we
+  -- retry until one succeeds, as buck2 does.
+  ok <- poll 100 (accepts sock)
+  unless ok $ terminateProcess ph >> fail "the worker opened no socket"
+  pure (ph, sock)
+
+-- | Whether a connection to the socket succeeds.
+accepts :: FilePath -> IO Bool
+accepts path = bracket (socket AF_UNIX Stream defaultProtocol) close $ \sock ->
+  either (\(_ :: IOException) -> False) (const True) <$> try (connect sock (SockAddrUnix path))
+
+-- | Start a worker with startWorkerProcess, and run the body with the
+-- worker's socket. Afterwards, whether or not the body succeeded, end the
+-- worker with SIGTERM, as buck2 does.
+withWorkerProcess :: FilePath -> [String] -> FilePath -> [(String, String)] -> StdStream -> (FilePath -> IO a) -> IO a
+withWorkerProcess worker args dir settings err k =
+  bracket
+    (startWorkerProcess worker args dir settings err)
+    (\(ph, _) -> terminateProcess ph >> waitForProcess ph)
+    (k . snd)
+
+-- | Check the condition every tenth of a second, up to the given number of
+-- times, and return whether it ever held. This is for waiting on another
+-- process, whose progress the caller can only observe from outside.
+poll :: Int -> IO Bool -> IO Bool
+poll n cond = do
+  ok <- cond
+  if ok then pure True else if n <= 0 then pure False else threadDelay 100000 >> poll (n - 1) cond
+
+-- | The ghc-pkg that comes with the given GHC, in the same directory. For
+-- example, the ghc-pkg of /opt/bin/ghc-9.12.4 is /opt/bin/ghc-pkg-9.12.4. If
+-- the GHC is a bare name with no directory, so is the result, to be looked
+-- up on $PATH.
+ghcPkgOf :: String -> String
+ghcPkgOf ghc = if '/' `elem` ghc then takeDirectory ghc </> name else name
+  where
+    name = rename (takeFileName ghc)
+    rename s
+      | "ghc" `isPrefixOf` s = "ghc-pkg" ++ drop 3 s
+      | c : rest <- s = c : rename rest
+      | otherwise = "ghc-pkg"
diff --git a/buck2/prelude/haskell/tools/worker/test/Main.hs b/buck2/prelude/haskell/tools/worker/test/Main.hs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/tools/worker/test/Main.hs
@@ -0,0 +1,913 @@
+{-# LANGUAGE CPP #-}
+{-# LANGUAGE OverloadedStrings #-}
+-- | Tests of the worker that drive it as buck2 does. Each test group starts
+-- a worker in the directory of a small generated package, and sends it one
+-- request per module over its socket, with the arguments that the rules
+-- send (see compile_per_module.bzl). As under buck2, the requests name files
+-- relative to the worker's directory.
+--
+-- The tests check the files the worker writes for the rules (interfaces,
+-- objects, ABI files and dep files) and how it manages its sessions: that it
+-- compiles independent modules at the same time, compiles a module again
+-- after an edit, compiles several targets side by side, and drops sessions
+-- it no longer needs. A last group checks that a worker ends when the
+-- process that started it goes away.
+module Main (main) where
+
+import Control.Concurrent (forkIO)
+import Control.Concurrent.MVar
+import Control.Exception (IOException, SomeException, catch, finally)
+import Control.Monad (forM, forM_, unless, void, when)
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Char8 as B8
+import Data.IORef (IORef, newIORef, readIORef, writeIORef)
+import Data.List (isInfixOf, isPrefixOf, isSuffixOf)
+import Data.Maybe (fromMaybe)
+import System.Directory
+import System.Environment (getEnvironment, lookupEnv)
+import Data.Version (showVersion)
+import System.Exit (ExitCode (..), exitFailure)
+import System.Info (fullCompilerVersion)
+import System.FilePath ((<.>), (</>))
+import System.IO (IOMode (..), hGetLine, hPutStrLn, openFile, stderr)
+import System.Posix.Process (getProcessID)
+import System.Posix.Signals (nullSignal, sigKILL, signalProcess)
+import System.Process
+import System.Timeout (timeout)
+
+import Test.Tasty
+import Test.Tasty.HUnit
+
+import Client
+import Contract (contract)
+
+main :: IO ()
+main = do
+  -- cabal puts the worker on $PATH (it is in build-tool-depends). The GHC
+  -- that the requests name must be the one the worker and this test were
+  -- built with. By default that is the `ghc` on $PATH; GHC overrides it.
+  worker <- fromMaybe "buck2-ghc-worker" <$> lookupEnv "BUCK2_GHC_WORKER"
+  ghc <- fromMaybe "ghc" <$> lookupEnv "GHC"
+  version <- trim <$> readProcess ghc ["--numeric-version"] ""
+  let built = showVersion fullCompilerVersion
+  unless (version == built) $
+    die' ("the test was built with GHC " ++ built ++ " but `" ++ ghc ++ "` is " ++ version ++ ": set GHC")
+  libdir <- trim <$> readProcess ghc ["--print-libdir"] ""
+  -- The tests in a group run in order, because each builds on what the
+  -- earlier ones compiled. The first group is run twice, once in session
+  -- mode make and once in auto, the default, which compiles the targets
+  -- without boot files one-shot (see Note [One-shot sessions] in Session).
+  -- The groups after it use auto.
+  defaultMain . dependentTestGroup "buck2-ghc-worker" AllFinish $
+    [ withTestWorker ("one worker, over its socket, in session mode " ++ mode) mode worker ghc libdir $ \getW ->
+        [testCase "compiles a package, and again after edits" $ getW >>= \w -> scenarios (sendOwn w) (twRestart w) (twDir w) ghc]
+          ++ bootTests ghc getW
+          ++ [ testCase "each compile removes its temporary files" $ do
+                 w <- getW
+                 asm <- filter (".s" `isSuffixOf`) <$> filesUnder (twDir w </> "tmp")
+                 assertBool ("assembly files left: " ++ show asm) (null asm)
+             , testCase "compiles another target's modules beside the first's" $ getW >>= \w -> twRestart w >> otherTarget (twSendIn w) (twDir w) ghc
+             , testCase "fails each request for a session that can't be made" $ getW >>= \w -> twRestart w >> failedSessions (sendOwn w)
+             , testCase "refuses a request for another GHC" $ getW >>= otherCompiler . sendOwn
+             , testCase "refuses a request for another libdir" $ getW >>= otherLibdir . sendOwn
+             , testCase "ignores the ghc program's -B flag" $ getW >>= \w -> twRestart w >> libdirFlag (sendOwn w) libdir
+             , testCase "runs a splice in an external interpreter" $ getW >>= \w -> externalInterpreter w ghc
+             , testCase "drops the least recently used idle session, and compiles in new ones" $ getW >>= \w -> idleDrop w ghc
+             , testCase "drops a target's session once its modules are all compiled" $ getW >>= \w -> finishedDrop w ghc
+             , testCase "never finishes a target whose analysis failed" $ getW >>= \w -> unanalysed w ghc
+             , testCase "reads the interfaces a module imports as ghc -c does with its OPTIONS_GHC" $ getW >>= \w -> pragmaFlags w ghc
+             , testCase "refuses to compile a module twice" $ getW >>= compilesOnce
+             , testCase "makes the same object as the compile tool's ghc -c" $ getW >>= \w -> sameAsTool w ghc libdir
+             ]
+    | mode <- ["make", "auto"]
+    ]
+      ++ [ withTestWorker "one worker in session mode auto" "auto" worker ghc libdir $ \getW ->
+             [testCase "compiles a target one-shot, and one with boot files with --make" $ getW >>= \w -> autoModes w ghc]
+         , withTestWorker "a new worker's first splices, two at once" "auto" worker ghc libdir $ \getW ->
+             [testCase "both compile" $ getW >>= \w -> firstSplices (sendOwn w) (twDir w)]
+         , withResource (newPackage ghc "orphan") removePathForcibly $ \getDir ->
+             dependentTestGroup "a worker whose parent has gone ends" AllFinish
+               [testCase (show when') $ getDir >>= \dir -> orphan when' dir worker ghc libdir | when' <- [Idle, AfterASplice, DuringASplice]]
+         ]
+  where
+    trim = reverse . dropWhile (`elem` ("\r\n" :: String)) . reverse
+    -- The tests of a target with boot files (see cyclePackage), which
+    -- gets a --make session in either mode.
+    bootTests ghc getW =
+      [ testCase "compiles a cycle through a boot file, and again after edits" $ getW >>= \w -> cycles w ghc
+      , testCase "sees the home modules around boot files as ghc -c does" $ getW >>= \w -> bootViews (sendCycle w) (twRestart w) (twDir w </> "cycle") ghc
+      ]
+
+-- | A splice runs in an external interpreter (-fexternal-interpreter), and
+-- the interpreter's process keeps running as long as its session does.
+-- idleDrop, which runs next, checks that the process stops once the
+-- session is dropped. The target has a second module that is never
+-- compiled, so that the worker doesn't drop the session because the target
+-- is finished. Where there is no /proc, we can't see the interpreter, so
+-- we only check that the splice compiles.
+externalInterpreter :: TestWorker -> String -> IO ()
+externalInterpreter w ghc = do
+  pkg <- targetOf w ghc "ext" [("A", splicing), ("B", plain)]
+  (code, err) <- twSendIn w pkg (req "F.A" "F/A"){extraFlags = externalFlags pkg}
+  assertBool ("a splice runs in an external interpreter: " ++ err) (code == 0)
+  haveProc <- doesDirectoryExist "/proc/self"
+  running <- interpreters (twDir w)
+  when haveProc $ assertBool "the external interpreter runs while its session does" (not (null running))
+
+-- | The worker drops the least recently used idle session when it has more
+-- than its limit, and new sessions still work after older ones were
+-- dropped. The test worker's limit is one session (see withTestWorker).
+-- After externalInterpreter, a compile in a new target that also isn't
+-- finished pushes the worker over that limit. The worker should then drop
+-- externalInterpreter's session, which also stops its interpreter process.
+--
+-- Earlier tests ran splices in sessions that have since been dropped. A
+-- splice in a new session must still work, which it wouldn't if, say, the
+-- new session reused a dropped one's temporary paths (see Note [A temporary
+-- directory per session] in Session).
+idleDrop :: TestWorker -> String -> IO ()
+idleDrop w ghc = do
+  let dir = twDir w
+  pkg <- targetOf w ghc "lru" [("A", plain'), ("B", plain)]
+  (code, err) <- twSendIn w pkg (req "F.A" "F/A"){extraFlags = ["-this-unit-id", pkg]}
+  assertBool ("a module compiles: " ++ err) (code == 0)
+  finished <- or <$> mapM (finishedIn w) ["ext/out", "lru/out"]
+  assertBool "neither target is finished" (not finished)
+  -- The worker tells the interpreter to stop, but the process stops in its
+  -- own time, so we wait for it.
+  stopped <- poll 300 (null <$> interpreters dir)
+  assertBool "a dropped session's external interpreter has stopped" stopped
+  -- -DAFTER_THE_DROP gives this request flags of its own, so it gets a new
+  -- session. Its splice loads an object that none of the dropped sessions
+  -- loaded (T.H's), which the worker must not mistake for one of theirs.
+  writeFile (dir </> "src/T/Q.hs") "{-# LANGUAGE TemplateHaskell #-}\nmodule T.Q where\nimport T.H (h)\nimport Language.Haskell.TH.Syntax (lift)\nq :: Int\nq = $(lift h)\n"
+  (qCode, qErr) <- sendOwn w (req "T.Q" "T/Q"){extraFlags = ["-dynamic", "-package", "template-haskell", "-DAFTER_THE_DROP"], loadable = ["T.H", "T.G"]}
+  assertBool ("a splice compiles in a session made after others that ran splices were dropped: " ++ qErr) (qCode == 0)
+
+-- | The worker drops a target's session as soon as the target is finished,
+-- that is, once it has compiled all of the target's modules, even when the
+-- session limit doesn't require it. The target has two modules, and the
+-- first runs a splice in an external interpreter. After the first module,
+-- the target's session is the most recently used, so the limit doesn't
+-- drop it and the target isn't finished. After the second, the worker
+-- should log that the target is finished, and stop its interpreter.
+finishedDrop :: TestWorker -> String -> IO ()
+finishedDrop w ghc = do
+  pkg <- targetOf w ghc "two" [("A", splicing), ("B", plain)]
+  (aCode, aErr) <- twSendIn w pkg (req "F.A" "F/A"){extraFlags = externalFlags pkg}
+  assertBool ("a target's first module compiles: " ++ aErr) (aCode == 0)
+  early <- finishedIn w (pkg </> "out")
+  assertBool "a target with a module left isn't finished" (not early)
+  (bCode, bErr) <- twSendIn w pkg (req "F.B" "F/B"){extraFlags = externalFlags pkg}
+  assertBool ("a target's last module compiles: " ++ bErr) (bCode == 0)
+  finished <- finishedIn w (pkg </> "out")
+  assertBool "a target whose modules are all compiled is finished" finished
+  stopped <- poll 300 (null <$> interpreters (twDir w))
+  assertBool "a finished target's external interpreter has stopped" stopped
+
+-- | The worker can only tell that a target is finished from GHC's analysis
+-- of the target's modules. If that analysis fails, here because one module's
+-- imports don't parse, the worker must never consider the target finished,
+-- even though every module it was asked for has compiled.
+unanalysed :: TestWorker -> String -> IO ()
+unanalysed w ghc = do
+  pkg <- targetOf w ghc "bad" [("A", splicing), ("Bad", "module F.Bad where\nimport\n")]
+  (code, err) <- twSendIn w pkg (req "F.A" "F/A"){extraFlags = externalFlags pkg}
+  assertBool ("a module beside one that doesn't parse compiles: " ++ err) (code == 0)
+  finished <- finishedIn w (pkg </> "out")
+  assertBool "a target whose analysis failed isn't finished" (not finished)
+
+-- | Sources for targetOf's modules. `splicing` is an F.A with a splice,
+-- which runs in an external interpreter when it is compiled with
+-- externalFlags. plain' is an F.A without a splice, and plain is an F.B.
+splicing, plain', plain :: String
+splicing = "{-# LANGUAGE TemplateHaskell #-}\nmodule F.A where\nimport Language.Haskell.TH.Syntax (lift)\na :: Int\na = $(lift (1 :: Int))\n"
+plain' = "module F.A where\na :: Int\na = 1\n"
+plain = "module F.B where\nb :: Int\nb = 2\n"
+
+-- | A module's OPTIONS_GHC must not change how other modules see the
+-- interfaces they import (see Note [The flags an interface is read with]
+-- in Session). F.P and F.Q share a session, and both import base's
+-- toIntegralSized. F.P's OPTIONS_GHC turns interface pragmas on, so its
+-- compile learns the function's arity. F.Q is compiled after it, at -O0,
+-- where `ghc -c` ignores interface pragmas and so calls toIntegralSized as
+-- an unknown function. We check that F.Q's code, in its Cmm dump, calls
+-- toIntegralSized the same way as `ghc -c`'s does.
+pragmaFlags :: TestWorker -> String -> IO ()
+pragmaFlags w ghc = do
+  let p = "{-# OPTIONS_GHC -fno-ignore-interface-pragmas #-}\nmodule F.P where\nimport Data.Bits (toIntegralSized)\np :: Int -> Maybe Word\np n = toIntegralSized n\n"
+      q = "{-# OPTIONS_GHC -ddump-cmm -ddump-to-file #-}\nmodule F.Q where\nimport Data.Bits (toIntegralSized)\nq :: Integer -> Maybe Int\nq n = toIntegralSized n\n"
+  pkg <- targetOf w ghc "prags" [("P", p), ("Q", q)]
+  let dir = twDir w </> pkg
+      flags = ["-this-unit-id", pkg, "-dumpdir", pkg </> "dump"]
+  forM_ ["P", "Q"] $ \m -> do
+    (code, err) <- twSendIn w pkg (req ("F." ++ m) ("F/" ++ m)){extraFlags = flags}
+    assertBool ("F." ++ m ++ " compiles: " ++ err) (code == 0)
+  createDirectoryIfMissing True (dir </> "ref")
+  _ <- readCreateProcess (proc ghc ["-c", "src/F/Q.hs", "-o", "ref/Q.o", "-ohi", "ref/Q.hi", "-hide-all-packages", "-package", "base", "-dumpdir", "ref"]){cwd = Just dir} ""
+  let directCall d = do
+        cmm <- filter ("Q.dump-cmm" `isSuffixOf`) <$> filesUnder d
+        case cmm of
+          [f] -> ("toIntegralSized_info(" `isInfixOf`) <$> readFile f
+          _ -> assertFailure ("one Cmm dump of F.Q under " ++ d ++ ": " ++ show cmm) >> pure False
+  worker <- directCall (dir </> "dump")
+  ref <- directCall (dir </> "ref")
+  assertBool ("F.Q calls toIntegralSized " ++ (if ref then "directly" else "as an unknown function") ++ ", as ghc -c does") (worker == ref)
+
+-- | The session flags for a target made by targetOf, with splices run in an
+-- external interpreter.
+externalFlags :: String -> [String]
+externalFlags pkg = ["-this-unit-id", pkg, "-fexternal-interpreter", "-package", "template-haskell"]
+
+-- | Make a package in a subdirectory, of the given name, of the worker's
+-- directory. Its modules are F.<name> with the given sources, in place of
+-- the T modules that makePackage writes. Returns the subdirectory, relative
+-- to the worker's directory.
+targetOf :: TestWorker -> String -> String -> [(String, String)] -> IO FilePath
+targetOf w ghc name modules = do
+  let dir = twDir w </> name
+  makePackage ghc dir
+  removePathForcibly (dir </> "src/T")
+  createDirectoryIfMissing True (dir </> "src/F")
+  forM_ modules $ \(m, src) -> writeFile (dir </> "src/F" </> m <.> "hs") src
+  pure name
+
+-- | Whether the worker's log says that the target with the given output
+-- directory is finished. The directory is relative to the worker's
+-- directory, as the requests name it.
+finishedIn :: TestWorker -> FilePath -> IO Bool
+finishedIn w out = elem (B8.pack ("buck2-ghc-worker: " ++ out ++ " finished")) . B8.lines <$> B.readFile (twDir w </> "worker.log")
+
+die' :: String -> IO a
+die' msg = hPutStrLn stderr msg >> exitFailure
+
+-- | Send a request as the rules would, and return the exit code and stderr
+-- that the worker answers with.
+type Send = Req -> IO (Int, String)
+
+data Req = Req
+  { node :: String
+  , modPath :: String
+  , boot :: Bool
+  , reqContract :: String
+  , extraFlags :: [String]
+  , compiler :: Maybe String -- a GHC to name instead of the test's
+  , libdirOf :: Maybe String -- a libdir to name instead of the test's GHC's
+  , loadable :: [String] -- the modules in its closure whose objects its splices may load, as the rules pass them with --loadable
+  }
+
+-- | The arguments of a request for a module of the package in the given
+-- subdirectory of the worker's directory. Paths are relative to the
+-- worker's directory. For the worker's own package the subdirectory is "",
+-- so that the paths have no leading "./", as buck2 gives them.
+argv :: FilePath -> String -> FilePath -> Req -> [String]
+argv pkg ghc libdir r =
+  [ "--request", "--contract", reqContract r, "--libdir", fromMaybe libdir (libdirOf r)
+  , "--depfile", pkg </> "dep" </> node r <.> "dep", "--abi", abi, "--diagnostics", pkg </> "diag" </> node r <.> "diag", "--module", modPath r, "--source", src
+  , "--outdir", out, "--hisuf", "hi"
+  ] ++ ["--boot" | boot r] ++ ["--loadable=" ++ m | m <- loadable r]
+  ++ ["--srcroot=" ++ pkg </> "src", "--mkdir=" ++ pkg </> "stubs" </> node r]
+  ++ ["--", fromMaybe ghc (compiler r), "-hide-all-packages", "-package", "base", "-package-db", pkg </> "db", "-package", "p", "-fforce-recomp"] ++ determinism ++ extraFlags r
+  ++ ["--", "-c", src, "-o", o, "-ohi", hi, "-stubdir", pkg </> "stubs" </> node r, "-i" ++ out]
+  where
+    out = pkg </> "out"
+    suffix = if boot r then "-boot" else ""
+    src = pkg </> "src" </> modPath r <.> ("hs" ++ suffix)
+    hi = out </> modPath r <.> ("hi" ++ suffix)
+    o = out </> modPath r <.> ("o" ++ suffix)
+    abi = out </> modPath r <.> ("abi" ++ suffix)
+
+req :: String -> String -> Req
+req n m = Req n m False contract [] Nothing Nothing []
+
+-- | Make a package (see makePackage) in a new temporary directory, named
+-- after the given string, and return the directory.
+newPackage :: String -> String -> IO FilePath
+newPackage ghc name = do
+  tmp <- getTemporaryDirectory
+  pid <- getProcessID
+  let dir = tmp </> ("buck2-ghc-worker-test-" ++ show pid ++ "-" ++ name)
+  removePathForcibly dir
+  makePackage ghc dir
+  pure dir
+
+-- | Write the test package into the directory. T.C imports T.D, T.B imports
+-- both, T.E imports nothing, and T.P imports P.Q from package p. No module
+-- has a boot file (writeCycle adds one).
+--
+-- p is registered the way the rules register the early package db of a
+-- dependency that is compiled per-module: it names no library, and its
+-- import directory stays empty until a test compiles P.Q into it.
+makePackage :: String -> FilePath -> IO ()
+makePackage ghc dir = do
+  mapM_ (createDirectoryIfMissing True) [dir </> "src/T", dir </> "out", dir </> "dep", dir </> "stubs", dir </> "p", dir </> "psrc/P", dir </> "tmp"]
+  writeFile (dir </> "src/T/D.hs") "module T.D where\nnewtype D = D [Int]\ndSize :: D -> Int\ndSize (D ns) = sum ns\n"
+  writeFile (dir </> "src/T/C.hs") "module T.C where\nimport T.D (D (..), dSize)\ndata C = Leaf | Node D\nsize :: C -> Int\nsize Leaf = 1\nsize (Node d) = 1 + dSize d\n"
+  writeFile (dir </> "src/T/B.hs") "module T.B (total) where\nimport T.C (C (..), size)\nimport T.D (D (..))\ntotal :: Int\ntotal = size (Node (D [1, 2]))\n"
+  writeFile (dir </> "src/T/E.hs") "module T.E where\ne :: Int\ne = 5\n"
+  writeFile (dir </> "src/T/P.hs") "module T.P where\nimport P.Q (q)\np :: Int\np = q\n"
+  writeFile (dir </> "psrc/P/Q.hs") "module P.Q where\nq :: Int\nq = 1\n"
+  writeFile (dir </> "p.conf") ("name: p\nversion: 0\nid: p-0\nkey: p-0\nexposed: True\nexposed-modules: P.Q\nimport-dirs: " ++ dir </> "p" ++ "\n")
+  _ <- readProcess (ghcPkgOf ghc) ["init", dir </> "db"] ""
+  -- --force, because ghc-pkg refuses a package whose interfaces don't
+  -- exist yet. It still warns about them, so we ignore its output.
+  void $ readProcessWithExitCode (ghcPkgOf ghc) ["register", "--force", "--package-db", dir </> "db", dir </> "p.conf"] ""
+
+-- | Rewrite the package in the directory so that T.C and T.D form an import
+-- cycle, broken by a boot file. T.C gets a boot file, T.D imports T.C
+-- {-# SOURCE #-}, and T.C still imports T.D.
+writeCycle :: FilePath -> IO ()
+writeCycle dir = do
+  writeFile (dir </> "src/T/C.hs-boot") "module T.C where\ndata C\nsize :: C -> Int\n"
+  writeFile (dir </> "src/T/D.hs") "module T.D where\nimport {-# SOURCE #-} T.C (C, size)\nnewtype D = D [C]\ndSize :: D -> Int\ndSize (D cs) = sum (map size cs)\n"
+  writeFile (dir </> "src/T/B.hs") "module T.B (total) where\nimport T.C (C (..), size)\nimport T.D (D (..))\ntotal :: Int\ntotal = size (Node (D [Leaf, Leaf]))\n"
+
+-- | The package in the subdirectory "cycle" of the worker's directory, whose
+-- T.C and T.D form a cycle (see writeCycle). It is made the first time it is
+-- needed. Returns its subdirectory, as twSendIn takes it.
+--
+-- Its modules are compiled with the unit id "cycle" (see sendCycle). They
+-- have the same names as the worker's own package's modules, whose unit id
+-- is GHC's default of "main". All the sessions share one name cache (see
+-- Note [One name cache for all the sessions] in Session), so with the same
+-- unit id the two packages' modules would be taken for each other.
+cyclePackage :: TestWorker -> String -> IO FilePath
+cyclePackage w ghc = do
+  let dir = twDir w </> "cycle"
+  made <- doesDirectoryExist dir
+  unless made (makePackage ghc dir >> writeCycle dir)
+  pure "cycle"
+
+-- | Send a request for a module of the cycle package (see cyclePackage).
+sendCycle :: TestWorker -> Send
+sendCycle w r = twSendIn w "cycle" r{extraFlags = cycleUnit ++ extraFlags r}
+
+cycleUnit :: [String]
+cycleUnit = ["-this-unit-id", "cycle"]
+
+-- | Send the request, and check that it succeeds and writes the module's
+-- interface, object and ABI file to the package's out directory.
+compiledIn :: Send -> FilePath -> Req -> IO ()
+compiledIn send dir r = do
+  (code, err) <- send r
+  assertBool (node r ++ " compiles: " ++ err) (code == 0)
+  let out = dir </> "out"
+      suffix = if boot r then "-boot" else ""
+  ok <- and <$> mapM doesFileExist [out </> modPath r <.> ("hi" ++ suffix), out </> modPath r <.> ("o" ++ suffix)]
+  assertBool (node r ++ " writes its interface and object") ok
+  abi <- readFile (out </> modPath r <.> ("abi" ++ suffix))
+  assertBool (node r ++ " writes an ABI hash") (length (filter (/= '\n') abi) == 32)
+
+-- | The files listed in the dep file of the request's module.
+depsIn :: FilePath -> Req -> IO [String]
+depsIn dir r = lines <$> readFile (dir </> "dep" </> node r <.> "dep")
+
+-- | Check that the dep file of the request's module lists each of the given
+-- files, and lists no file outside the package's own outputs.
+listsIn :: FilePath -> Req -> [String] -> IO ()
+listsIn dir r files = do
+  deps <- depsIn dir r
+  forM_ files $ \f -> assertBool (node r ++ ".dep lists " ++ f ++ ": " ++ show deps) (any (f `isInfixOf`) deps)
+  assertBool (node r ++ ".dep lists only the package's own files: " ++ show deps) (all ("out/T/" `isInfixOf`) deps)
+
+scenarios :: Send -> IO () -> FilePath -> String -> IO ()
+scenarios send restart dir ghc = do
+  let out = dir </> "out"
+      compiled = compiledIn send dir
+      lists = listsIn dir
+
+  -- Compile the modules in an order buck2 could send them. T.D and T.E
+  -- import nothing, so they are sent at the same time. The dep files must
+  -- list the ABI files of exactly the modules each one imports.
+  done <- newEmptyMVar
+  _ <- forkIO (compiled (req "T.E" "T/E") `finally` putMVar done ())
+  compiled (req "T.D" "T/D")
+  takeMVar done
+  compiled (req "T.C" "T/C")
+  compiled (req "T.B" "T/B")
+  lists (req "T.C" "T/C") ["out/T/D.abi"]
+  lists (req "T.B" "T/B") ["out/T/C.abi", "out/T/D.abi"]
+  eDeps <- depsIn dir (req "T.E" "T/E")
+  assertBool "T.E.dep is empty" (null eDeps)
+
+  -- T.P imports P.Q from package p, whose interface didn't exist yet when
+  -- the session was made. The session must still find it once P.Q has been
+  -- compiled, as with an early package db.
+  _ <- readProcess ghc ["-c", dir </> "psrc/P/Q.hs", "-this-unit-id", "p-0", "-hidir", dir </> "p", "-odir", dir </> "pobj", "-hide-all-packages", "-package", "base"] ""
+  compiled (req "T.P" "T/P")
+
+  -- A comment-only edit must leave the module's ABI hash unchanged, so that
+  -- buck2 doesn't compile its importers again. From GHC 9.12, whose objects
+  -- are deterministic, the object must be unchanged too.
+  -- Each compile of a module after the first is in a build of its own, so
+  -- in a new worker.
+  abi <- readFile (out </> "T/C.abi")
+#if MIN_VERSION_GLASGOW_HASKELL(9,12,0,0)
+  obj <- B.readFile (out </> "T/C.o")
+#endif
+  restart
+  appendFile (dir </> "src/T/C.hs") "\n-- an edit\n"
+  compiled (req "T.C" "T/C")
+  abi' <- readFile (out </> "T/C.abi")
+  assertBool "a comment-only edit leaves the ABI" (abi == abi')
+#if MIN_VERSION_GLASGOW_HASKELL(9,12,0,0)
+  obj' <- B.readFile (out </> "T/C.o")
+  assertBool "a comment-only edit leaves the object" (obj == obj')
+#endif
+
+  -- A new exported definition must change the ABI hash.
+  restart
+  appendFile (dir </> "src/T/C.hs") "\nanother :: Int\nanother = 2\n"
+  compiled (req "T.C" "T/C")
+  abi'' <- readFile (out </> "T/C.abi")
+  assertBool "an exported binding changes the ABI" (abi /= abi'')
+  compiled (req "T.B" "T/B")
+
+  -- A request with different flags is compiled in a new session. That
+  -- session has to read T.C's and T.D's interfaces from disk, since another
+  -- session compiled them.
+  restart
+  compiled (req "T.B" "T/B"){extraFlags = ["-DOTHER_FLAGS"]}
+  lists (req "T.B" "T/B") ["out/T/C.abi", "out/T/D.abi"]
+
+  -- T.H's splice runs T.G, a module of the same target. T.H compiles in a
+  -- session of its own, so GHC loads T.G's object, which the session read
+  -- from disk, and T.H's dep file lists that object. (GHC is dynamically
+  -- linked, so it loads dynamic objects.)
+  let th = ["-dynamic", "-package", "template-haskell"]
+  writeFile (dir </> "src/T/G.hs") "{-# LANGUAGE TemplateHaskellQuotes #-}\nmodule T.G (g) where\nimport Language.Haskell.TH (Exp, Q)\ng :: Q Exp\ng = [| 3 :: Int |]\n"
+  writeFile (dir </> "src/T/H.hs") "{-# LANGUAGE TemplateHaskell #-}\nmodule T.H (h) where\nimport T.G (g)\nh :: Int\nh = $(g)\n"
+  compiled (req "T.G" "T/G"){extraFlags = th}
+  compiled (req "T.H" "T/H"){extraFlags = th ++ ["-DOTHER_FLAGS"], loadable = ["T.G"]}
+  lists (req "T.H" "T/H") ["out/T/G.abi", "out/T/G.o"]
+  -- The target has its own module named Data.Bool, which is never
+  -- compiled. T.I imports Data.Bool qualified with "base", and must get
+  -- base's module, not the target's.
+  createDirectoryIfMissing True (dir </> "src/Data")
+  writeFile (dir </> "src/Data/Bool.hs") "module Data.Bool where\n"
+  writeFile (dir </> "src/T/I.hs") "{-# LANGUAGE PackageImports #-}\nmodule T.I where\nimport \"base\" Data.Bool (bool)\ni :: Int\ni = bool 1 2 True\n"
+  compiled (req "T.I" "T/I")
+
+  -- The worker must compile every request, even when GHC's own check would
+  -- find the module up to date (see Note [Compiling whenever buck2 asks] in
+  -- Session). T.RF's splice reads a file without recording it, so GHC's
+  -- check misses a change to the file. After we change it and send T.RF
+  -- again, its object must change.
+  writeFile (dir </> "rf-input") "one"
+  writeFile (dir </> "src/T/RF.hs") "{-# LANGUAGE TemplateHaskell #-}\nmodule T.RF where\nimport Language.Haskell.TH.Syntax (lift, runIO)\nrf :: Int\nrf = $(runIO (readFile \"rf-input\") >>= lift . length)\n"
+  let rfReq = (req "T.RF" "T/RF"){extraFlags = ["-dynamic", "-package", "template-haskell"]}
+  compiled rfReq
+  rfBefore <- B.readFile (out </> "T/RF.o")
+  writeFile (dir </> "rf-input") "three"
+  restart
+  compiled rfReq
+  rfAfter <- B.readFile (out </> "T/RF.o")
+  assertBool "a module is compiled whenever it is asked to be, whatever GHC's own check" (rfBefore /= rfAfter)
+
+  -- The stub header of a module with a foreign export must go to the
+  -- request's -stubdir, as `ghc -c` puts it, and not next to the source.
+  writeFile (dir </> "src/T/FE.hs") "module T.FE where\nforeign export ccall fe :: Int -> Int\nfe :: Int -> Int\nfe = (+ 1)\n"
+  compiled (req "T.FE" "T/FE")
+  inStubs <- doesFileExist (dir </> "stubs/T.FE/T/FE_stub.h")
+  inSrc <- doesFileExist (dir </> "src/T/FE_stub.h")
+  assertBool ("T.FE's stub header is in its -stubdir, not by its source: " ++ show (inStubs, inSrc)) (inStubs && not inSrc)
+
+  -- A module with a type error fails, and the request's stderr has GHC's
+  -- error, with the source location.
+  writeFile (dir </> "src/T/F.hs") "module T.F where\nf :: Int\nf = \"no\"\n"
+  (code, err) <- send (req "T.F" "T/F")
+  assertBool ("T.F fails: " ++ show code) (code /= 0)
+  assertBool ("T.F's error names its source and the problem: " ++ err) ("T/F.hs:3:5" `isInfixOf` err && "String" `isInfixOf` err)
+
+  -- The toolchain's compiler_flags may contain RTS options for the ghc
+  -- program, such as +RTS -A64m -RTS. They mean nothing to a session, and
+  -- the worker must accept them.
+  restart
+  compiled (req "T.E" "T/E"){extraFlags = ["+RTS", "-A64m", "-RTS"]}
+
+  -- A flag that sets state for the whole GHC process can't apply to one
+  -- session alone, so the worker must refuse it and name the flag (see
+  -- Note [Flags of the whole process] in Session).
+  restart
+  forM_ ["-fno-state-hack", "-dppr-debug"] $ \flag -> do
+    (gCode, gErr) <- send (req "T.E" "T/E"){extraFlags = [flag]}
+    assertBool ("a flag of the whole process is refused: " ++ show gCode ++ " " ++ gErr) (gCode /= 0 && flag `isInfixOf` gErr)
+
+  -- A request from another version of the rules must be refused, with a
+  -- message about the version.
+  (code', err') <- send (req "T.E" "T/E"){reqContract = "0"}
+  assertBool ("a contract mismatch is refused: " ++ show code' ++ " " ++ err') (code' /= 0 && "version" `isInfixOf` err')
+
+-- | A target with an import cycle through a boot file (see cyclePackage)
+-- compiles in the order buck2 would send it. The dep files of the modules
+-- that read the boot file list its ABI file (T/C.abi-boot). The target
+-- compiles again after an edit to the boot file.
+cycles :: TestWorker -> String -> IO ()
+cycles w ghc = do
+  pkg <- cyclePackage w ghc
+  let dir = twDir w </> pkg
+      compiled = compiledIn (sendCycle w) dir
+      lists = listsIn dir
+  compiled (req "T.C-boot" "T/C"){boot = True}
+  compiled (req "T.D" "T/D")
+  compiled (req "T.C" "T/C")
+  compiled (req "T.B" "T/B")
+  lists (req "T.D" "T/D") ["out/T/C.abi-boot"]
+  lists (req "T.C" "T/C") ["out/T/D.abi", "out/T/C.abi-boot"]
+  lists (req "T.B" "T/B") ["out/T/C.abi", "out/T/D.abi"]
+
+  -- Edit the boot file, then compile it and every module that reads it,
+  -- in order.
+  twRestart w
+  appendFile (dir </> "src/T/C.hs-boot") "\n-- an edit\n"
+  compiled (req "T.C-boot" "T/C"){boot = True}
+  compiled (req "T.D" "T/D")
+  compiled (req "T.C" "T/C")
+  compiled (req "T.B" "T/B")
+
+-- | In session mode auto, the worker makes a one-shot session for a target
+-- without boot files, and a --make session for a target with them (see
+-- cyclePackage). We check this in the worker's log.
+autoModes :: TestWorker -> String -> IO ()
+autoModes w ghc = do
+  _ <- cyclePackage w ghc
+  compiledIn (sendOwn w) (twDir w) (req "T.E" "T/E")
+  compiledIn (sendCycle w) (twDir w </> "cycle") (req "T.C-boot" "T/C"){boot = True}
+  logged <- lines <$> readFile (twDir w </> "worker.log")
+  let said l = assertBool ("the worker's log says " ++ show l ++ ": " ++ show logged) (any (l `isPrefixOf`) logged)
+  said "buck2-ghc-worker: a one-shot session for the flags of T/E"
+  said "buck2-ghc-worker: a --make session for the flags of T/C"
+
+-- | A new worker can run its first two splices at the same time, in two
+-- sessions. The process has a single object linker, and starting it from
+-- two sessions at once could hang both compiles (see Note [Starting the
+-- object linker once] in Worker). Each splice waits until the other has
+-- started, so both run at the same time, and their compiles then hash the
+-- libraries they loaded at the same time too (see Note [Hashing the
+-- libraries] in Session). A compile that never answers fails the test
+-- after two minutes.
+firstSplices :: Send -> FilePath -> IO ()
+firstSplices send dir = do
+  let th = ["-dynamic", "-package", "template-haskell"]
+  writeFile (dir </> "src/T/G.hs") "{-# LANGUAGE TemplateHaskellQuotes #-}\nmodule T.G (g) where\nimport Language.Haskell.TH (Exp, Q)\ng :: Q Exp\ng = [| 3 :: Int |]\n"
+  (gCode, gErr) <- send (req "T.G" "T/G"){extraFlags = th}
+  assertBool ("T.G compiles: " ++ gErr) (gCode == 0)
+  results <- forM [("T.K", "T.L", "-DSPLICE_ONE"), ("T.L", "T.K", "-DSPLICE_TWO")] $ \(m, other, flag) -> do
+    let path = map (\c -> if c == '.' then '/' else c) m
+    writeFile (dir </> "src" </> path <.> "hs") ("{-# LANGUAGE TemplateHaskell #-}\nmodule " ++ m ++ " where\nimport Control.Concurrent (threadDelay)\nimport Language.Haskell.TH.Syntax (runIO)\nimport System.Directory (doesFileExist)\nimport T.G (g)\nk :: Int\nk = $(runIO (writeFile " ++ show (m ++ "-started") ++ " \"\" >> let go = doesFileExist " ++ show (other ++ "-started") ++ " >>= \\ok -> if ok then pure () else threadDelay 10000 >> go in go) >> g)\n")
+    v <- newEmptyMVar
+    _ <- forkIO ((send (req m path){extraFlags = th ++ ["-package", "directory", flag], loadable = ["T.G"]} >>= putMVar v) `finally` tryPutMVar v (1, "the compile failed"))
+    pure (m, v)
+  forM_ results $ \(m, v) -> do
+    r <- timeout 120000000 (takeMVar v)
+    case r of
+      Nothing -> assertBool (m ++ " compiles, in one of two sessions at once: its splice still waits for the other's") False
+      Just (code, err) -> assertBool (m ++ " compiles, in one of two sessions at once: " ++ err) (code == 0)
+
+
+-- | Where modules have boot files, a compile must see each home module in
+-- the form that `ghc -c` would see it (the boot interface or the full
+-- module), whatever the session compiled before (see Note [Each compile's
+-- home modules] in Session). The modules are written into the cycle package
+-- (see cyclePackage), and the given Send sends their requests.
+bootViews :: Send -> IO () -> FilePath -> String -> IO ()
+bootViews send restart dir ghc = do
+  let out = dir </> "out"
+      compiled r = do
+        (code, err) <- send r
+        assertBool (node r ++ " compiles: " ++ err) (code == 0)
+      showIface f = readProcess ghc ["--show-iface", f] ""
+      -- These flags give the modules below a session of their own. A
+      -- session analyses its target's sources when it is made, so it has to
+      -- be made after the modules have been written.
+      th = ["-dynamic", "-package", "template-haskell", "-DBOOT_VIEWS"]
+
+  -- T.SB has a boot file and runs a splice. When it is compiled again
+  -- after an edit, with its previous interface still on disk, GHC must still
+  -- check it against its boot file. That check gives the module's Show
+  -- instance an extra binding with the name that importers of the boot file
+  -- use for it (the boot file's dfun, $fxShowT), so that name must be in
+  -- the new interface.
+  writeFile (dir </> "src/T/SB.hs-boot") "module T.SB where\ndata T\ninstance Show T\n"
+  writeFile (dir </> "src/T/SA.hs") "module T.SA where\nimport {-# SOURCE #-} T.SB (T)\nshowT :: T -> String\nshowT = show\n"
+  let sb :: Int -> IO ()
+      sb n = writeFile (dir </> "src/T/SB.hs") ("{-# LANGUAGE TemplateHaskell #-}\nmodule T.SB where\nimport T.SA (showT)\nimport Language.Haskell.TH.Syntax (lift)\ndata T = T\ninstance Show T where show _ = showT T\nn :: Int\nn = $(lift (" ++ show n ++ " :: Int))\n")
+  sb 1
+  compiled (req "T.SB-boot" "T/SB"){boot = True, extraFlags = th}
+  compiled (req "T.SA" "T/SA"){extraFlags = th}
+  compiled (req "T.SB" "T/SB"){extraFlags = th}
+  sb 2
+  restart
+  compiled (req "T.SB" "T/SB"){extraFlags = th}
+  sbIface <- showIface (out </> "T/SB.hi")
+  assertBool "a module compiled again is checked against its boot file" ("$fxShowT" `isInfixOf` sbIface)
+
+  -- T.YZ imports T.YA, which imports T.Y {-# SOURCE #-}. The session has
+  -- already compiled the full T.Y, but T.YZ must still see T.Y's boot
+  -- interface, because that is what `ghc -c` uses (T.YA's interface
+  -- records that it depends on the boot file). So T.YZ's ABI hash must
+  -- match that of a `ghc -c` compile.
+  writeFile (dir </> "src/T/Y.hs-boot") "module T.Y where\ny :: Int\n"
+  writeFile (dir </> "src/T/Y.hs") "module T.Y where\ny :: Int\ny = 42\n"
+  writeFile (dir </> "src/T/YA.hs") "module T.YA where\nimport {-# SOURCE #-} T.Y (y)\na :: Int\na = y + 1\n{-# INLINE a #-}\n"
+  writeFile (dir </> "src/T/YZ.hs") "module T.YZ where\nimport T.YA (a)\nz :: Int\nz = a + 1\n"
+  let opt = ["-O", "-DBOOT_VIEWS"]
+  compiled (req "T.Y-boot" "T/Y"){boot = True, extraFlags = opt}
+  compiled (req "T.Y" "T/Y"){extraFlags = opt}
+  compiled (req "T.YA" "T/YA"){extraFlags = opt}
+  compiled (req "T.YZ" "T/YZ"){extraFlags = opt}
+  createDirectoryIfMissing True (dir </> "ref")
+  _ <- readProcess ghc (["-c", dir </> "src/T/YZ.hs", "-o", dir </> "ref/YZ.o", "-ohi", dir </> "ref/YZ.hi", "-i" ++ out, "-hide-all-packages", "-package", "base"] ++ cycleUnit ++ opt ++ determinism) ""
+  let abiOf = filter ("ABI hash" `isInfixOf`) . lines
+  worker <- abiOf <$> showIface (out </> "T/YZ.hi")
+  reference <- abiOf <$> showIface (dir </> "ref/YZ.hi")
+  assertBool ("a module below a boot file has ghc -c's ABI: " ++ show (worker, reference)) (worker == reference && not (null worker))
+
+  -- T.RB has a boot file, and imports T.RA, whose unfolding refers back to
+  -- T.RB's rb through the boot file. When T.RB is compiled, that reference
+  -- must be to the T.RB being compiled, as with `ghc -c`, so that GHC sees
+  -- the recursion and gives rb no unfolding (see Note [Modules above the
+  -- compile's boot interface] in Session). T.RB's ABI hash must match that
+  -- of a `ghc -c` compile.
+  writeFile (dir </> "src/T/RB.hs-boot") "module T.RB where\nrb :: Int\n"
+  writeFile (dir </> "src/T/RA.hs") "module T.RA where\nimport {-# SOURCE #-} T.RB (rb)\nra :: Int\nra = rb + 1\n{-# INLINE ra #-}\n"
+  writeFile (dir </> "src/T/RB.hs") "module T.RB where\nimport T.RA (ra)\nrb :: Int\nrb = ra + 1\n"
+  compiled (req "T.RB-boot" "T/RB"){boot = True, extraFlags = opt}
+  compiled (req "T.RA" "T/RA"){extraFlags = opt}
+  compiled (req "T.RB" "T/RB"){extraFlags = opt}
+  _ <- readProcess ghc (["-c", dir </> "src/T/RB.hs", "-o", dir </> "ref/RB.o", "-ohi", dir </> "ref/RB.hi", "-i" ++ out, "-hide-all-packages", "-package", "base"] ++ cycleUnit ++ opt ++ determinism) ""
+  rbWorker <- abiOf <$> showIface (out </> "T/RB.hi")
+  rbReference <- abiOf <$> showIface (dir </> "ref/RB.hi")
+  assertBool ("a module whose import names it back through its boot file has ghc -c's ABI: " ++ show (rbWorker, rbReference)) (rbWorker == rbReference && not (null rbWorker))
+
+  -- T.SJ imports T.SI {-# SOURCE #-}. The session has compiled T.SI, and
+  -- for that compile read T.SI's boot interface from disk, because another
+  -- session compiled the boot file. T.SJ must see the boot file's Show
+  -- instance, not T.SI's. Otherwise T.SJ could inline T.SI's method and
+  -- refer to something the boot interface doesn't have, which makes
+  -- GHC 9.14 panic (see Note [The compile's own boot interface] in
+  -- Session). The test passes if T.SJ compiles.
+  writeFile (dir </> "src/T/SI.hs-boot") "module T.SI where\ndata T\ninstance Show T\n"
+  writeFile (dir </> "src/T/SI.hs") "module T.SI where\ndata T = T\ninstance Show T where show _ = \"T\"\n"
+  writeFile (dir </> "src/T/SJ.hs") "module T.SJ where\nimport {-# SOURCE #-} T.SI (T)\nshowT :: T -> String\nshowT = show\n"
+  let optSI = ["-O", "-DBOOT_INSTANCE"]
+  compiled (req "T.SI-boot" "T/SI"){boot = True, extraFlags = optSI ++ ["-DBOOT_INSTANCE_BOOT"]}
+  compiled (req "T.SI" "T/SI"){extraFlags = optSI}
+  compiled (req "T.SJ" "T/SJ"){extraFlags = optSI}
+
+-- | The flags that the rules give every module's compile for object code
+-- that doesn't depend on what the process compiled before (see ghc_flags in
+-- compile.bzl).
+determinism :: [String]
+#if MIN_VERSION_GLASGOW_HASKELL(9,12,0,0)
+determinism = ["-fobject-determinism"]
+#else
+determinism = []
+#endif
+
+-- | One worker compiles two targets side by side, as the targets of a build
+-- share a worker, and keeps them apart even where their modules have the
+-- same names.
+--
+-- Each target has a T.E, with different exports, and the two are compiled
+-- at the same time. Then each target compiles a module that uses something
+-- only its own T.E exports.
+--
+-- Then each target compiles a T.W. The first target's T.W runs a splice
+-- that creates the file w-started and then waits for the file w-go. While
+-- it waits, the other target's T.W compiles, with a warning, and only then
+-- does the test create w-go. Each request's stderr must have its own
+-- module's diagnostics and not the other's.
+otherTarget :: (FilePath -> Send) -> FilePath -> String -> IO ()
+otherTarget sendIn dir ghc = do
+  makePackage ghc (dir </> "other")
+  writeFile (dir </> "other/src/T/E.hs") "module T.E where\nother :: Bool\nother = True\n"
+  writeFile (dir </> "other/src/T/G.hs") "module T.G where\nimport T.E (other)\ng :: Bool\ng = not other\n"
+  let unit = ["-this-unit-id", "other"]
+  appendFile (dir </> "src/T/E.hs") "\n-- an edit\n"
+  first <- newEmptyMVar
+  _ <- forkIO ((sendIn "" (req "T.E" "T/E") >>= putMVar first) `finally` tryPutMVar first (1, "the compile failed"))
+  (otherCode, otherErr) <- sendIn "other" (req "T.E" "T/E"){extraFlags = unit}
+  assertBool ("another target's T.E compiles: " ++ otherErr) (otherCode == 0)
+  (firstCode, firstErr) <- takeMVar first
+  assertBool ("T.E compiles beside another target's: " ++ firstErr) (firstCode == 0)
+  (gCode, gErr) <- sendIn "other" (req "T.G" "T/G"){extraFlags = unit}
+  assertBool ("another target's module imports its own T.E: " ++ gErr) (gCode == 0)
+  writeFile (dir </> "src/T/J.hs") "module T.J where\nimport T.E (e)\nj :: Int\nj = e + 1\n"
+  (jCode, jErr) <- sendIn "" (req "T.J" "T/J")
+  assertBool ("a module imports its own target's T.E: " ++ jErr) (jCode == 0)
+  writeFile (dir </> "src/T/W.hs") "{-# LANGUAGE TemplateHaskell #-}\nmodule T.W where\nimport Control.Concurrent (threadDelay)\nimport Language.Haskell.TH.Syntax (lift, runIO)\nimport System.Directory (doesFileExist)\nw :: Int\nw = $(runIO (writeFile \"w-started\" \"\" >> let go = doesFileExist \"w-go\" >>= \\ok -> if ok then pure () else threadDelay 10000 >> go in go) >> lift (1 :: Int))\n"
+  writeFile (dir </> "other/src/T/W.hs") "module T.W where\nw :: Int\nw = let othersUnused = 1 :: Int in 2\n"
+  mine <- newEmptyMVar
+  _ <- forkIO ((sendIn "" (req "T.W" "T/W"){extraFlags = ["-dynamic", "-package", "template-haskell", "-package", "directory"]} >>= putMVar mine) `finally` tryPutMVar mine (1, "the compile threw"))
+  started <- poll 300 (doesFileExist (dir </> "w-started"))
+  assertBool "T.W's compile starts" started
+  -- A worker that compiled one module at a time would never answer this
+  -- request, since T.W waits for it. So we give up after two minutes.
+  (otherWCode, otherWErr) <- fromMaybe (1, "no answer in two minutes, with T.W's compile waiting") <$> timeout 120000000 (sendIn "other" (req "T.W" "T/W"){extraFlags = unit ++ ["-Wunused-local-binds"]})
+  writeFile (dir </> "w-go") ""
+  (wCode, wErr) <- takeMVar mine
+  assertBool ("the other target's T.W compiles, with its warning: " ++ otherWErr) (otherWCode == 0 && "othersUnused" `isInfixOf` otherWErr)
+  assertBool ("the warning names its file and line, as ghc -c's does: " ++ otherWErr) ("T/W.hs:3:" `isInfixOf` otherWErr)
+  assertBool ("T.W compiles, without the other target's warning: " ++ wErr) (wCode == 0 && not ("othersUnused" `isInfixOf` wErr))
+
+-- | When a session can't be made, here because of a flag GHC doesn't know,
+-- every request waiting for it must fail with the reason, rather than wait
+-- for a session that never comes. Two requests for the same session are
+-- sent at the same time.
+failedSessions :: Send -> IO ()
+failedSessions send = do
+  vs <- forM [("T.E", "T/E"), ("T.P", "T/P")] $ \(n, m) -> do
+    v <- newEmptyMVar
+    _ <- forkIO ((send (req n m){extraFlags = ["-fno-such-flag"]} >>= putMVar v) `finally` tryPutMVar v (0, "the request threw"))
+    pure v
+  forM_ vs $ \v -> do
+    r <- timeout 60000000 (takeMVar v)
+    case r of
+      Nothing -> assertBool "a request whose session can't be made returns" False
+      Just (code, err) -> assertBool ("a request whose session can't be made fails, saying why: " ++ err) (code /= 0 && "no-such-flag" `isInfixOf` err)
+
+-- | The worker refuses a request that names a different GHC from the one
+-- it runs.
+otherCompiler :: Send -> IO ()
+otherCompiler send = do
+  (code, err) <- send (req "T.E" "T/E"){compiler = Just "/no/such/ghc"}
+  assertBool ("a request for another GHC is refused: " ++ err) (code /= 0 && "/no/such/ghc" `isInfixOf` err)
+
+-- | The worker refuses a request that names a different libdir from the one
+-- it was started with.
+otherLibdir :: Send -> IO ()
+otherLibdir send = do
+  (code, err) <- send (req "T.E" "T/E"){libdirOf = Just "/no/such/libdir"}
+  assertBool ("a request for another libdir is refused: " ++ err) (code /= 0 && "/no/such/libdir" `isInfixOf` err)
+
+-- | A toolchain whose GHC is built from source gives its compiler command
+-- the GHC's libdir with -B. The worker isn't the ghc program, and takes the
+-- libdir from the request, so it must accept the flag and ignore it.
+-- | A worker lives for one build, in which buck2 compiles each module once,
+-- so it refuses to compile a module of a target a second time.
+compilesOnce :: TestWorker -> IO ()
+compilesOnce w = do
+  twRestart w
+  compiledIn (sendOwn w) (twDir w) (req "T.E" "T/E")
+  (code, err) <- sendOwn w (req "T.E" "T/E")
+  assertBool ("a second compile of a module is refused: " ++ show code ++ " " ++ err) (code /= 0 && "already compiled" `isInfixOf` err)
+
+-- | The worker makes the same object as the compile tool, which runs `ghc`
+-- with the request's session and module flags (see PerModuleCompile), so
+-- that it doesn't matter which of them compiled a module. The worker has
+-- compiled other modules first. That only gives the same object with
+-- 'determinism', so before GHC 9.12 there is nothing to check.
+sameAsTool :: TestWorker -> String -> FilePath -> IO ()
+sameAsTool w ghc libdir = when (not (null determinism)) $ do
+  let dir = twDir w
+      r = req "T.DT" "T/DT"
+      o = dir </> "out" </> "T/DT.o"
+  writeFile (dir </> "src/T/DT.hs") "module T.DT where\ndata D = A Int | B String deriving (Eq, Show)\nclass C a where c :: a -> Int\ninstance C D where\n  c (A n) = n\n  c (B s) = length s\nds :: [D]\nds = [A 1, B \"two\"]\n"
+  compiledIn (sendOwn w) dir r
+  fromWorker <- B.readFile o
+  removeFile o
+  case break (== "--") (drop 1 (dropWhile (/= "--") (argv "" ghc libdir r))) of
+    (program : session, _ : moduleArgs) -> do
+      (code, _, err) <- readCreateProcessWithExitCode (proc program (session ++ moduleArgs)){cwd = Just dir} ""
+      assertBool ("ghc -c compiles T.DT: " ++ err) (code == ExitSuccess)
+    _ -> assertFailure "the request has no session and module flags"
+  fromTool <- B.readFile o
+  assertBool "the worker's object is byte for byte the same as ghc -c's" (fromWorker == fromTool)
+
+libdirFlag :: Send -> FilePath -> IO ()
+libdirFlag send libdir = do
+  (code, err) <- send (req "T.E" "T/E"){extraFlags = ["-B" ++ libdir]}
+  assertBool ("a request whose compiler command has -B compiles: " ++ err) (code == 0)
+
+-- | The process ids of the external interpreters (iserv) that the worker
+-- in the given directory started. We recognise them by their TMPDIR, which
+-- is the worker's. This needs /proc, and finds nothing without it.
+interpreters :: FilePath -> IO [String]
+interpreters dir = do
+  pids <- filter (all (`elem` ['0' .. '9'])) <$> (listDirectory "/proc" `catch` \(_ :: IOException) -> pure [])
+  concat <$> forM pids (\pid -> do
+    let file f = B8.unpack <$> B.readFile ("/proc" </> pid </> f)
+    found <- ((\cmd env -> "iserv" `isInfixOf` cmd && ("TMPDIR=" ++ dir </> "tmp") `isInfixOf` env) <$> file "cmdline" <*> file "environ")
+      `catch` \(_ :: IOException) -> pure False
+    pure [pid | found])
+
+-- | The files in a directory and below it.
+filesUnder :: FilePath -> IO [FilePath]
+filesUnder d = do
+  entries <- map (d </>) <$> listDirectory d
+  concat <$> mapM (\e -> doesDirectoryExist e >>= \isDir -> if isDir then filesUnder e else pure [e]) entries
+
+-- | A worker running in the directory of a new package, as the tests of a
+-- group see it.
+data TestWorker = TestWorker
+  { twDir :: FilePath
+  , twProcess :: IORef ProcessHandle
+  , twSendIn :: FilePath -> Send -- for the package in the given subdirectory
+  , twRestart :: IO () -- end the worker and start a new one, as buck2 does for each build
+  }
+
+-- | Send a request for the package in the worker's own directory.
+sendOwn :: TestWorker -> Send
+sendOwn w = twSendIn w ""
+
+-- | A group of tests, run in order, against one worker. The worker is
+-- started as buck2 starts it, in the directory of a new package, and the
+-- tests send it requests over its socket (see 'grpc'). Since targets share
+-- a worker, a request may be for the package in any subdirectory.
+--
+-- The worker's session limit is one, so that the tests can check when it
+-- drops sessions. It runs verbosely, logging to worker.log in its
+-- directory, which some tests read.
+--
+-- A worker lives for one build, in which it compiles each module once, so
+-- a test that compiles a module again after an edit restarts it first.
+--
+-- The last test ends the worker with SIGTERM, as buck2 does. The worker must
+-- exit successfully and leave no temporary files behind.
+withTestWorker :: String -> String -> FilePath -> String -> FilePath -> (IO TestWorker -> [TestTree]) -> TestTree
+withTestWorker name mode worker ghc libdir tests =
+  withResource start stop $ \getW ->
+    dependentTestGroup name AllFinish (tests getW ++ [testCase "ends on SIGTERM, leaving no temporary files" (getW >>= end)])
+  where
+    start = do
+      -- The directory is named after the initials of the group's name, to
+      -- keep it short. The worker's socket is in this directory, and macOS
+      -- limits a socket's path to 104 bytes, of which $TMPDIR takes about
+      -- 50.
+      dir <- newPackage ghc [c | c : _ <- words name]
+      let launch logMode = do
+            logH <- openFile (dir </> "worker.log") logMode
+            startWorkerProcess worker [] dir [("BUCK2_GHC_WORKER_SESSIONS", "1"), ("BUCK2_GHC_WORKER_VERBOSE", "1"), ("BUCK2_GHC_WORKER_SESSION_MODE", mode), ("TMPDIR", dir </> "tmp")] (UseHandle logH)
+      (ph, sock) <- launch WriteMode
+      ref <- newIORef ph
+      let restart = do
+            old <- readIORef ref
+            terminateProcess old
+            _ <- waitForProcess old
+            launch AppendMode >>= writeIORef ref . fst
+      pure (TestWorker dir ref (\pkg -> grpc sock . argv pkg ghc libdir) restart)
+    end w = do
+      ph <- readIORef (twProcess w)
+      terminateProcess ph
+      code <- waitForProcess ph
+      code @?= ExitSuccess
+      left <- listDirectory (twDir w </> "tmp")
+      assertBool ("temporary files left: " ++ show left) (null left)
+    -- Clean up, whether or not the tests ended the worker.
+    stop w = do
+      ph <- readIORef (twProcess w)
+      terminateProcess ph
+      _ <- waitForProcess ph
+      removePathForcibly (twDir w)
+
+-- | What the worker is doing when its parent goes away.
+data Orphaned = Idle | AfterASplice | DuringASplice
+  deriving (Eq, Show)
+
+-- | A worker must end when its parent process exits without ending it. This
+-- happens when the buck2 daemon is killed: the forkserver that started the
+-- worker exits too. We check three cases:
+--
+-- - Idle: the worker hasn't compiled anything.
+-- - AfterASplice: the worker has compiled a module that ran a splice, so it
+--   has a session and the libraries that the splice loaded.
+-- - DuringASplice: the worker is in the middle of a compile whose splice
+--   never finishes. The worker's stderr is closed in this case, to check
+--   that failing to write to stderr doesn't stop the worker from ending.
+--
+-- The worker's parent here is a shell script. It waits for the worker's
+-- socket to appear, so that the worker has recorded its parent before the
+-- parent exits. Then it waits until the test creates the file "go", or
+-- until the test process itself has gone, so that a test killed part-way
+-- doesn't leave a worker behind.
+orphan :: Orphaned -> FilePath -> FilePath -> String -> FilePath -> IO ()
+orphan when' dir worker ghc libdir = do
+  environment <- getEnvironment
+  let sock = dir </> "w.sock"
+      go = dir </> "go"
+  removePathForcibly sock
+  removePathForcibly go
+  let stderr' = if when' == DuringASplice then "2>&-" else "2>/dev/null"
+  (_, Just out, _, ph) <- createProcess (proc "sh" ["-c", "\"$0\" >/dev/null " ++ stderr' ++ " & echo $!; until [ -S \"$1\" ]; do sleep 0.1; done; until [ -e \"$2\" ] || ! kill -0 $PPID 2>/dev/null; do sleep 0.1; done", worker, sock, go]){cwd = Just dir, env = Just (("WORKER_SOCKET", sock) : filter ((/= "WORKER_SOCKET") . fst) environment), std_out = CreatePipe}
+  pid <- read <$> hGetLine out
+  opened <- poll 50 (doesFileExist sock)
+  assertBool "the worker opened a socket" opened
+  let th = ["-dynamic", "-package", "template-haskell"]
+  when (when' /= Idle) $ do
+    writeFile (dir </> "src/T/G.hs") "{-# LANGUAGE TemplateHaskellQuotes #-}\nmodule T.G (g) where\nimport Language.Haskell.TH (Exp, Q)\ng :: Q Exp\ng = [| 3 :: Int |]\n"
+    writeFile (dir </> "src/T/H.hs") "{-# LANGUAGE TemplateHaskell #-}\nmodule T.H (h) where\nimport T.G (g)\nh :: Int\nh = $(g)\n"
+    forM_ [(req "T.G" "T/G"){extraFlags = th}, (req "T.H" "T/H"){extraFlags = th ++ ["-DSPLICING"], loadable = ["T.G"]}] $ \r -> do
+      (code, err) <- grpc sock (argv "" ghc libdir r)
+      assertBool ("before its parent goes, " ++ node r ++ " compiles: " ++ err) (code == 0)
+  when (when' == DuringASplice) $ do
+    writeFile (dir </> "src/T/Z.hs") "{-# LANGUAGE TemplateHaskell #-}\nmodule T.Z where\nimport Control.Concurrent (threadDelay)\nimport Control.Monad (forever)\nimport Language.Haskell.TH.Syntax (lift, runIO)\nimport T.H (h)\nz :: Int\nz = $(runIO (writeFile \"z-started\" \"\" >> forever (threadDelay 100000)) >> lift h)\n"
+    void . forkIO . void $ grpc sock (argv "" ghc libdir (req "T.Z" "T/Z"){extraFlags = th ++ ["-DNEVER_DONE"], loadable = ["T.H", "T.G"]}) `catch` \(_ :: SomeException) -> pure (0, "")
+    started <- poll 300 (doesFileExist (dir </> "z-started"))
+    assertBool "the compile that never ends starts" started
+  writeFile go ""
+  _ <- waitForProcess ph
+  let alive = (signalProcess nullSignal pid >> pure True) `catch` \(_ :: IOException) -> pure False
+  ok <- poll 50 (not <$> alive)
+  unless ok $ signalProcess sigKILL pid
+  assertBool ("a worker whose parent has gone ends, " ++ show when') ok
diff --git a/buck2/prelude/haskell/util.bzl b/buck2/prelude/haskell/util.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/haskell/util.bzl
@@ -0,0 +1,164 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//haskell:library_info.bzl",
+    "HaskellLibraryInfo",
+    "HaskellLibraryProvider",
+)
+load(
+    "@prelude//haskell:link_info.bzl",
+    "HaskellLinkInfo",
+    "HaskellProfLinkInfo",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkStyle",
+    "MergedLinkInfo",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+)
+
+HASKELL_EXTENSIONS = [
+    ".hs",
+    ".lhs",
+    ".hsc",
+    ".chs",
+    ".x",
+    ".y",
+]
+
+# We take a named_set for srcs, which is sometimes a list, sometimes a dict.
+# In future we should only accept a list, but for now, cope with both.
+def srcs_to_pairs(srcs) -> list[(str, Artifact)]:
+    if type(srcs) == type({}):
+        return srcs.items()
+    else:
+        return [(src_to_module_name(src.short_path), src) for src in srcs]
+
+# The name of the files of a haskell_library() (lib<name>.a, say), from its
+# label.
+#
+# A package path containing a literal "." (e.g. a directory unpacked
+# from a versioned tarball, like "hackage-security-0.6.4.0") isn't
+# just cosmetic here: ghc-pkg's own .conf parser rejects a "name:"/
+# "id:"/"key:" token containing *any* hyphen-delimited component
+# that's purely numeric unless it's the token's very last component
+# (it's parsing for a trailing name-version split, same as any
+# ordinary "foo-1.2.3" package identifier) - confirmed empirically:
+# both a literal "." and a plain "_"-for-"." substitution (still
+# hyphenated into an all-digits component by the final "_" -> "-"
+# below) fail the same way ("unexpected Empty component, after ..."),
+# while splicing in a letter so the component is never purely numeric
+# (e.g. "0.6.4.0" -> "0d6d4d0") is accepted regardless of position.
+def haskell_library_name(label: Label | TargetLabel) -> str:
+    return repr(label.path).replace("//", "_").replace("/", "_").replace(".", "d").removesuffix("_") + "_" + label.name
+
+# The unit id of a haskell_library(), from its label.
+def haskell_library_unit_id(label: Label | TargetLabel) -> str:
+    return haskell_library_name(label).replace("_", "-")
+
+def is_haskell_src(x: Artifact) -> bool:
+    _, ext = paths.split_extension(x.short_path)
+    return ext in HASKELL_EXTENSIONS
+
+def src_to_module_name(x: str) -> str:
+    base, _ext = paths.split_extension(x)
+    return base.replace("/", ".")
+
+def module_name_to_file(x: str, ext: str) -> str:
+    return x.replace(".", "/") + "." + ext
+
+def attr_deps(ctx: AnalysisContext) -> list[Dependency]:
+    # A library's internal_deps are dependencies like the others, except in
+    # what it passes on to be linked with it.
+    return ctx.attrs.deps + (getattr(ctx.attrs, "internal_deps", None) or [])
+
+def attr_deps_haskell_link_infos(ctx: AnalysisContext) -> list[HaskellLinkInfo]:
+    return dedupe(
+        filter(
+            None,
+            [d.get(HaskellLinkInfo) for d in attr_deps(ctx) + ctx.attrs.template_deps],
+        )
+    )
+
+# DONT CALL THIS FUNCTION, you want attr_deps_haskell_link_infos instead
+def attr_deps_haskell_link_infos_sans_template_deps(ctx: AnalysisContext) -> list[HaskellLinkInfo]:
+    return dedupe(
+        filter(
+            None,
+            [d.get(HaskellLinkInfo) for d in attr_deps(ctx)],
+        )
+    )
+
+def attr_deps_haskell_lib_infos(ctx: AnalysisContext, link_style: LinkStyle, enable_profiling: bool) -> list[HaskellLibraryInfo]:
+    if enable_profiling and link_style == LinkStyle("shared"):
+        fail("Profiling isn't supported when using dynamic linking")
+    return [
+        x.prof_lib[link_style] if enable_profiling else x.lib[link_style]
+        for x in filter(None, [d.get(HaskellLibraryProvider) for d in attr_deps(ctx) + ctx.attrs.template_deps])
+    ]
+
+# The *_link_infos and *_library_infos functions are of `deps`, if given,
+# instead of all the deps.
+
+def attr_deps_merged_link_infos(ctx: AnalysisContext, deps: [list[Dependency], None] = None) -> list[MergedLinkInfo]:
+    return dedupe(
+        filter(
+            None,
+            [d.get(MergedLinkInfo) for d in (attr_deps(ctx) if deps == None else deps)],
+        )
+    )
+
+def attr_deps_profiling_link_infos(ctx: AnalysisContext, deps: [list[Dependency], None] = None) -> list[MergedLinkInfo]:
+    return filter(
+        None,
+        [d.get(HaskellProfLinkInfo).prof_infos if d.get(HaskellProfLinkInfo) else d.get(MergedLinkInfo) for d in (attr_deps(ctx) if deps == None else deps)],
+    )
+
+def attr_deps_shared_library_infos(ctx: AnalysisContext, deps: [list[Dependency], None] = None) -> list[SharedLibraryInfo]:
+    return filter(
+        None,
+        [d.get(SharedLibraryInfo) for d in (attr_deps(ctx) if deps == None else deps)],
+    )
+
+def _link_style_extensions(link_style: LinkStyle) -> (str, str):
+    if link_style == LinkStyle("shared"):
+        return ("dyn_o", "dyn_hi")
+    elif link_style == LinkStyle("static_pic"):
+        return ("o", "hi")  # is this right?
+    elif link_style == LinkStyle("static"):
+        return ("o", "hi")
+    fail("unknown LinkStyle")
+
+def output_extensions(link_style: LinkStyle, profiled: bool) -> (str, str):
+    osuf, hisuf = _link_style_extensions(link_style)
+    if profiled:
+        return ("p_" + osuf, "p_" + hisuf)
+    else:
+        return (osuf, hisuf)
+
+# The name of a 'variant', one way of building a target's code, such as "static-prof".
+#
+# A target often builds the same thing in several variants, so the rules
+# use the variant to tell the actions and outputs apart.
+#
+# - An action's category says what kind of action it is, such as
+#   'haskell_compile', which is useful to match on. The variant goes in the
+#   action's identifier, along with any other context, such as the module
+#   of a per-module compile.
+# - An output only has a path, so its path is made from what the output is
+#   and the variant.
+def variant_name(link_style: LinkStyle, enable_profiling: bool) -> str:
+    variant = link_style.value
+    if enable_profiling:
+        variant += "-prof"
+    return variant
diff --git a/buck2/prelude/http_archive/exec_deps.bzl b/buck2/prelude/http_archive/exec_deps.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/http_archive/exec_deps.bzl
@@ -0,0 +1,28 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+HttpArchiveExecDeps = provider(
+    fields = {
+        "exec_os_type": provider_field(typing.Any, default = None),
+    }
+)
+
+def _http_archive_exec_deps_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        HttpArchiveExecDeps(
+            exec_os_type = ctx.attrs.exec_os_type,
+        ),
+    ]
+
+http_archive_exec_deps = rule(
+    impl = _http_archive_exec_deps_impl,
+    attrs = {
+        "exec_os_type": attrs.default_only(attrs.dep(default = "prelude//os_lookup/targets:os_lookup")),
+    },
+)
diff --git a/buck2/prelude/http_archive/extract_archive.bzl b/buck2/prelude/http_archive/extract_archive.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/http_archive/extract_archive.bzl
@@ -0,0 +1,62 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:remote_common.bzl", "remote_common")
+load("@prelude//user:rule_spec.bzl", "RuleRegistrationSpec")
+load("@prelude//utils:utils.bzl", "value_or")
+load(":exec_deps.bzl", "HttpArchiveExecDeps")
+load(":unarchive.bzl", "archive_type", "unarchive")
+
+# Buck v2 doesn't support directories as source inputs, while v1 allows that.
+# This rule fills that gap and allows to produce a directory from archive,
+# which then can be used as an input for other rules.
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    output, sub_targets = unarchive(
+        ctx,
+        archive = ctx.attrs.src,
+        output_name = value_or(
+            value_or(ctx.attrs.out, ctx.attrs.directory_name),
+            ctx.label.name,
+        ),
+        ext_type = archive_type(ctx.attrs.src.short_path, ctx.attrs.type),
+        excludes = ctx.attrs.excludes,
+        strip_prefix = ctx.attrs.strip_prefix,
+        sub_targets = ctx.attrs.sub_targets,
+        exec_deps = ctx.attrs.exec_deps[HttpArchiveExecDeps],
+        # no need -- no http involved
+        prefer_local = False,
+    )
+
+    return [
+        DefaultInfo(
+            default_output = output,
+            sub_targets = sub_targets,
+        )
+    ]
+
+registration_spec = RuleRegistrationSpec(
+    name = "extract_archive",
+    impl = _impl,
+    attrs = remote_common.unarchive_args()
+    | {
+        "directory_name": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = """
+            Name of the result directory, if omitted, `name` attribute will be used instead.
+            Deprecated in favour of `out`.
+        """,
+        ),
+        "src": attrs.source(
+            doc = """
+            .tar.gz or zip archive with the contents of the result directory
+        """
+        ),
+    },
+)
diff --git a/buck2/prelude/http_archive/http_archive.bzl b/buck2/prelude/http_archive/http_archive.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/http_archive/http_archive.bzl
@@ -0,0 +1,64 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:materialization_test.bzl", "materialization_test")
+load("@prelude//utils:utils.bzl", "value_or")
+load(":exec_deps.bzl", "HttpArchiveExecDeps")
+load(":unarchive.bzl", "archive_type", "unarchive")
+
+def http_archive_impl(ctx: AnalysisContext) -> list[Provider]:
+    expect(len(ctx.attrs.urls) == 1, "multiple `urls` not supported: {}".format(ctx.attrs.urls))
+    expect(len(ctx.attrs.vpnless_urls) < 2, "multiple `vpnless_urls` not supported: {}".format(ctx.attrs.vpnless_urls))
+
+    # The HTTP download is local so it makes little sense to run actions
+    # remotely, unless we can defer them. We'll be able to defer if we provide
+    # a digest that the daemon's digest config natively supports.
+    digest_config = ctx.actions.digest_config()
+    prefer_local = True
+    if ctx.attrs.sha1 != None and digest_config.allows_sha1():
+        prefer_local = False
+    elif ctx.attrs.sha256 != None and digest_config.allows_sha256():
+        prefer_local = False
+
+    ext_type = archive_type(ctx.attrs.urls[0], ctx.attrs.type)
+
+    # Download archive.
+    archive = ctx.actions.declare_output("archive." + ext_type, has_content_based_path = ctx.attrs.has_content_based_path)
+    url = ctx.attrs.urls[0]
+    vpnless_url = None if len(ctx.attrs.vpnless_urls) == 0 else ctx.attrs.vpnless_urls[0]
+    ctx.actions.download_file(
+        archive.as_output(),
+        url,
+        vpnless_url = vpnless_url,
+        sha1 = ctx.attrs.sha1,
+        sha256 = ctx.attrs.sha256,
+        size_bytes = ctx.attrs.size_bytes,
+        has_content_based_path = ctx.attrs.has_content_based_path,
+    )
+
+    output, sub_targets = unarchive(
+        ctx,
+        archive = archive,
+        output_name = value_or(ctx.attrs.out, ctx.label.name),
+        ext_type = ext_type,
+        excludes = ctx.attrs.excludes,
+        strip_prefix = ctx.attrs.strip_prefix,
+        sub_targets = ctx.attrs.sub_targets,
+        exec_deps = ctx.attrs.exec_deps[HttpArchiveExecDeps],
+        prefer_local = prefer_local,
+        has_content_based_path = ctx.attrs.has_content_based_path,
+    )
+
+    return [
+        DefaultInfo(
+            default_output = output,
+            sub_targets = sub_targets,
+        ),
+        materialization_test([archive, output]),
+    ]
diff --git a/buck2/prelude/http_archive/tools/BUCK b/buck2/prelude/http_archive/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/http_archive/tools/BUCK
@@ -0,0 +1,11 @@
+load("@prelude//http_archive:exec_deps.bzl", "http_archive_exec_deps")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+http_archive_exec_deps(
+    name = "exec_deps",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/http_archive/unarchive.bzl b/buck2/prelude/http_archive/unarchive.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/http_archive/unarchive.bzl
@@ -0,0 +1,240 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "value_or")
+load(":exec_deps.bzl", "HttpArchiveExecDeps")
+
+# Flags to apply to decompress the various types of archives.
+_TAR_FLAGS = {
+    "tar": [],
+    "tar.bz2": ["-j"],
+    "tar.gz": ["-z"],
+    "tar.xz": ["-J"],
+    "tar.zst": ["--use-compress-program=unzstd"],
+}
+
+_ARCHIVE_EXTS = _TAR_FLAGS.keys() + [
+    "zip",
+]
+
+def _url_path(url: str) -> str:
+    if "?" in url:
+        return url.split("?")[0]
+    else:
+        return url
+
+def _type_from_url(url: str) -> [str, None]:
+    url_path = _url_path(url)
+    for filename_ext in _ARCHIVE_EXTS:
+        if url_path.endswith("." + filename_ext):
+            return filename_ext
+    return None
+
+def archive_type(url_or_path: str, typ: str | None) -> str:
+    if typ == None:
+        typ = value_or(_type_from_url(url_or_path), "tar.gz")
+    if typ not in _ARCHIVE_EXTS:
+        fail("unsupported archive type: {}".format(typ))
+    return typ
+
+# Returns a two-element tuple:
+#
+# 1. The cmd_args with the unarchive command
+# 2. A bool indicating whether the prefix still needs to be stripped (in cases where the tool used to uncompress does not support this feature).
+def _unarchive_cmd(ext_type: str, archive: Artifact, strip_prefix: [str, None]) -> (cmd_args, bool):
+    if ext_type in _TAR_FLAGS:
+        return cmd_args(
+            "tar",
+            _TAR_FLAGS[ext_type],
+            "-x",
+            "-f",
+            archive,
+            _tar_strip_prefix_flags(strip_prefix),
+        ), False
+    elif ext_type == "zip":
+        # gnutar does not intrinsically support zip
+        return cmd_args(archive, format = "unzip {}"), bool(strip_prefix)
+    else:
+        fail()
+
+def _tar_strip_prefix_flags(strip_prefix: [str, None]) -> list[str]:
+    if strip_prefix:
+        # count nonempty path components in the prefix
+        count = len(filter(lambda c: c != "", strip_prefix.split("/")))
+        return ["--strip-components=" + str(count), strip_prefix]
+    return []
+
+# buck-out on Windows on eden is a symlink. bsdtar which ships with Windows will
+# not extract files when the cwd contains a path segment that is a symlink (as
+# a side effect of or excessively cautious against wild writes to the system).
+# Powershell lets us 'dereference' that symlink to get the physical path to the
+# output folder we tell tar to unpack into while preserving security, instead of
+# passing -P.
+def _windows_unpack_ps1(out: OutputArtifact, archive: Artifact, ext_type: str, strip_prefix: [str, None], exclude_flags: list) -> list:
+    tar = '"$env:SystemRoot\\System32\\tar.exe"'
+    quoted_archive = cmd_args(archive, format = "'{}'")
+    strip = _tar_strip_prefix_flags(strip_prefix)
+
+    lines = [
+        "$ErrorActionPreference = 'Stop'",
+        cmd_args(out, format = "$out = '{}'"),
+        "New-Item -ItemType Directory -Force -Path $out | Out-Null",
+        "$link = (Get-Item -LiteralPath 'buck-out').Target",
+        "if ($link) { $real = Join-Path @($link)[0] $out.Substring('buck-out'.Length).TrimStart('\\', '/') } else { $real = $out }",
+    ]
+
+    if ext_type == "tar.zst":
+        # bsdtar cannot invoke zstd itself, and a PowerShell native pipe would
+        # corrupt the binary stream, so decompress to a scratch file first.
+        return lines + [
+            "$scratch = $env:BUCK_SCRATCH_PATH",
+            "if (-not $scratch) { $scratch = [System.IO.Path]::GetTempPath() }",
+            "$tmp = Join-Path $scratch 'http_archive_unpack.tar'",
+            cmd_args("zstd", "-d", "-f", quoted_archive, "-o", '"$tmp"', delimiter = " "),
+            cmd_args("&", tar, "-x", "-C", '"$real"', "-f", '"$tmp"', strip, exclude_flags, delimiter = " "),
+            "Remove-Item -LiteralPath $tmp -Force",
+        ]
+    elif ext_type == "zip":
+        return lines + [
+            cmd_args("&", tar, "-x", "-C", '"$real"', "-f", quoted_archive, strip, delimiter = " "),
+        ]
+    elif ext_type in _TAR_FLAGS:
+        return lines + [
+            cmd_args("&", tar, _TAR_FLAGS[ext_type], "-x", "-C", '"$real"', "-f", quoted_archive, strip, exclude_flags, delimiter = " "),
+        ]
+    else:
+        fail("unsupported archive type on Windows: {}".format(ext_type))
+
+def unarchive(
+    ctx: AnalysisContext,
+    archive: Artifact,
+    output_name: str,
+    ext_type,
+    excludes,
+    strip_prefix,
+    exec_deps: HttpArchiveExecDeps,
+    prefer_local: bool,
+    sub_targets: list[str] | dict[str, list[str]],
+    has_content_based_path: bool = False,
+):
+    exec_is_windows = exec_deps.exec_os_type[OsLookup].os == Os("windows")
+
+    # The excludes listing runs `tar --list` and redirects it to a file; keep it
+    # in the shell whose redirect writes raw bytes (cmd on Windows, sh else).
+    if exec_is_windows:
+        listing_ext = "bat"
+        listing_interpreter = []
+        first_param = "%1"
+    else:
+        listing_ext = "sh"
+        listing_interpreter = ["/bin/sh"]
+        first_param = '"$1"'
+
+    # Unpack archive to output directory.
+    exclude_flags = []
+    exclude_hidden = []
+    if excludes:
+        tar_flags = _TAR_FLAGS.get(ext_type)
+        expect(tar_flags != None, "excludes not supported for non-tar archives")
+
+        # Tar excludes files using globs, but we take regexes, so we need to
+        # apply our regexes onto the file listing and produce an exclusion list
+        # that just has strings.
+        exclusions = ctx.actions.declare_output(output_name + "_exclusions", has_content_based_path = False)
+        contents = ctx.actions.declare_output(output_name + "_contents", has_content_based_path = False)
+        tar_script, _ = ctx.actions.write(
+            "{}_listing.{}".format(output_name, listing_ext),
+            [
+                cmd_args(
+                    archive,
+                    format = "tar --list " + " ".join(tar_flags) + " -f {} > " + first_param,
+                )
+            ],
+            is_executable = True,
+            allow_args = True,
+            has_content_based_path = False,
+        )
+        ctx.actions.run(
+            cmd_args(listing_interpreter + [tar_script, contents.as_output()], hidden = [archive]),
+            category = "process_exclusions",
+        )
+
+        def create_exclusion_list(ctx: AnalysisContext, artifacts, outputs):
+            files = artifacts[contents].read_string().splitlines()
+            exclusion_list = []
+            exclude_regexen = [regex(e) for e in excludes]
+            for f in files:
+                for exclusion in exclude_regexen:
+                    if exclusion.match(f):
+                        exclusion_list.append(f)
+                        break
+            ctx.actions.write(outputs[exclusions], "\n".join(exclusion_list))
+
+        ctx.actions.dynamic_output(
+            dynamic = [contents],
+            inputs = [],
+            outputs = [exclusions.as_output()],
+            f = create_exclusion_list,
+        )
+
+        exclude_flags.append(cmd_args(exclusions, format = "--exclude-from={}"))
+        exclude_hidden.append(exclusions)
+
+    unarchive_cmd = None  # unused on Windows (see _windows_unpack_ps1)
+    if exec_is_windows:
+        needs_strip_prefix = False
+        unpack_ext = "ps1"
+        unpack_interpreter = ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]
+    else:
+        unarchive_cmd, needs_strip_prefix = _unarchive_cmd(ext_type, archive, strip_prefix)
+        unpack_ext = "sh"
+        unpack_interpreter = ["/bin/sh"]
+
+    output = ctx.actions.declare_output(output_name, dir = True, has_content_based_path = has_content_based_path)
+    script_output = ctx.actions.declare_output(output_name + "_tmp", dir = True, has_content_based_path = False) if needs_strip_prefix else output
+
+    if exec_is_windows:
+        script_lines = _windows_unpack_ps1(script_output.as_output(), archive, ext_type, strip_prefix, exclude_flags)
+    else:
+        script_lines = [
+            cmd_args(script_output.as_output(), format = "mkdir -p {}"),
+            cmd_args(script_output.as_output(), format = "cd {}"),
+            cmd_args([unarchive_cmd] + exclude_flags, delimiter = " ", relative_to = script_output.as_output()),
+        ]
+
+    script, _ = ctx.actions.write(
+        "{}_unpack.{}".format(output_name, unpack_ext),
+        script_lines,
+        is_executable = True,
+        allow_args = True,
+        has_content_based_path = False,
+    )
+
+    ctx.actions.run(
+        cmd_args(
+            unpack_interpreter + [script],
+            hidden = exclude_hidden + [archive, script_output.as_output()],
+        ),
+        category = "http_archive",
+        identifier = output_name,
+        prefer_local = prefer_local,
+    )
+
+    if needs_strip_prefix:
+        ctx.actions.copy_dir(output.as_output(), script_output.project(strip_prefix), has_content_based_path = has_content_based_path)
+
+    if type(sub_targets) == type([]):
+        sub_targets = {path: [DefaultInfo(default_output = output.project(path))] for path in sub_targets}
+    elif type(sub_targets) == type({}):
+        sub_targets = {name: [DefaultInfo(default_outputs = [output.project(path) for path in paths])] for name, paths in sub_targets.items()}
+    else:
+        fail("sub_targets must be a list or dict")
+
+    return output, sub_targets
diff --git a/buck2/prelude/http_file.bzl b/buck2/prelude/http_file.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/http_file.bzl
@@ -0,0 +1,78 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:materialization_test.bzl", "materialization_test")
+load("@prelude//utils:utils.bzl", "value_or")
+
+def http_file_shared(
+    actions: AnalysisActions,
+    name: str,
+    url: str,
+    vpnless_url: [None, str],
+    is_executable: bool,
+    is_exploded_zip: bool,
+    unzip_tool: [RunInfo, None],
+    sha1: [None, str],
+    sha256: [None, str],
+    size_bytes: [None, int],
+    has_content_based_path: bool,
+) -> list[Provider]:
+    output = actions.declare_output(name, has_content_based_path = has_content_based_path)
+    downloaded_output = actions.declare_output("exploded_zip", has_content_based_path = has_content_based_path) if is_exploded_zip else output
+    actions.download_file(
+        downloaded_output,
+        url,
+        vpnless_url = vpnless_url,
+        is_executable = is_executable,
+        sha1 = sha1,
+        sha256 = sha256,
+        size_bytes = size_bytes,
+    )
+
+    if is_exploded_zip:
+        actions.run(
+            cmd_args([
+                unzip_tool,
+                "--src",
+                downloaded_output,
+                "--dst",
+                output.as_output(),
+            ]),
+            category = "exploded_zip_unzip",
+            local_only = sha1 == None,
+        )
+
+    providers = [
+        DefaultInfo(default_output = output),
+        materialization_test([downloaded_output, output]),
+    ]
+    if is_executable:
+        providers.append(RunInfo(args = [output]))
+    return providers
+
+def http_file_impl(ctx: AnalysisContext) -> list[Provider]:
+    expect(len(ctx.attrs.urls) == 1, "multiple `urls` not supported: {}", ctx.attrs.urls)
+    expect(len(ctx.attrs.vpnless_urls) < 2, "multiple `vpnless_urls` not supported: {}", ctx.attrs.vpnless_urls)
+    if len(ctx.attrs.vpnless_urls) > 0:
+        vpnless_url = ctx.attrs.vpnless_urls[0]
+    else:
+        vpnless_url = None
+    return http_file_shared(
+        ctx.actions,
+        name = value_or(ctx.attrs.out, ctx.label.name),
+        url = ctx.attrs.urls[0],
+        vpnless_url = vpnless_url,
+        sha1 = ctx.attrs.sha1,
+        sha256 = ctx.attrs.sha256,
+        is_executable = ctx.attrs.executable or False,
+        is_exploded_zip = False,
+        unzip_tool = None,
+        size_bytes = ctx.attrs.size_bytes,
+        has_content_based_path = ctx.attrs.has_content_based_path,
+    )
diff --git a/buck2/prelude/ide_integrations/apple/build_index/BUCK b/buck2/prelude/ide_integrations/apple/build_index/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/apple/build_index/BUCK
@@ -0,0 +1,19 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("apple_build_infra")
+
+source_listing()
+
+python_bootstrap_binary(
+    name = "build_index_store",
+    main = "main.py",
+    visibility = [
+        "fbcode//glean/glass/test/regression:swift-binary",
+        "fbcode//glean/glass/test/regression:swift-objc-xlang-binary",
+        "fbcode//glean/lang/swift/tests:tests",
+        "fbcode//glean/lang/swift/tests:tests-rust-indexer",
+    ],
+    deps = [
+        "prelude//apple/tools/index:merge_index_store_lib",
+    ],
+)
diff --git a/buck2/prelude/ide_integrations/apple/build_index/main.py b/buck2/prelude/ide_integrations/apple/build_index/main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/apple/build_index/main.py
@@ -0,0 +1,113 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import multiprocessing
+import subprocess
+from argparse import Namespace
+from pathlib import Path
+
+from merge_index_store import merge_directory
+
+BXL = "prelude//ide_integrations/apple/build_index/swift_index_store.bxl:main"
+
+
+def parse_arguments() -> Namespace:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("-d", "--dest", type=str, required=True)
+    parser.add_argument("-t", "--target", type=str, required=True, nargs="+")
+    parser.add_argument(
+        "-c", "--config", action="append", help="Buck configuration flags"
+    )
+    parser.add_argument(
+        "-s",
+        "--subtarget",
+        type=str,
+        help="Subtarget to build (e.g., swift-index-store)",
+    )
+    parser.add_argument(
+        "--isolation-dir",
+        type=str,
+        help="Isolation directory for buck2",
+    )
+    return parser.parse_args()
+
+
+def parse_targets(target_args: list[str]) -> list[str]:
+    """Parse target arguments, handling multiple targets separated by newlines or spaces."""
+    targets = []
+    for target_arg in target_args:
+        split_targets = []
+        for line in target_arg.split("\n"):
+            split_targets.extend(line.split())
+        targets.extend([t.strip() for t in split_targets if t.strip()])
+    return targets
+
+
+def run_bxl_and_merge_index(
+    targets: list[str],
+    dest: str,
+    configs: list[str] = None,
+    subtarget: str = None,
+    isolation_dir: str = None,
+) -> None:
+    targets_str = " ".join(targets)
+    config_flags = ""
+    subtarget_arg = f" --subtarget {subtarget}" if subtarget else ""
+    isolation_dir_flag = f" --isolation-dir {isolation_dir}" if isolation_dir else ""
+    if configs:
+        config_flags = " ".join([f"-c {config}" for config in configs])
+        command = f"buck2{isolation_dir_flag} bxl {config_flags} {BXL} -- --target {targets_str}{subtarget_arg}"
+    else:
+        command = f"buck2{isolation_dir_flag} bxl {BXL} -- --target {targets_str}{subtarget_arg}"
+    process = subprocess.Popen(
+        command,
+        shell=True,
+        stdout=subprocess.PIPE,
+        text=True,
+        bufsize=1,  # Line buffering to ensure real-time output capture
+    )
+
+    # Process pool for running merge_directory in separate processes
+    # Default number of pool processes is the number of CPUs
+    with multiprocessing.Pool() as pool:
+        processes = []
+        for line in iter(process.stdout.readline, ""):
+            index_store_path = line.strip()
+            if index_store_path:
+                # Run merge_directory in a separate process
+                result = pool.apply_async(merge_directory, (index_store_path, dest))
+                processes.append(result)
+
+        # Wait for all processes to complete
+        for p in processes:
+            p.get()
+
+    process.stdout.close()
+    return_code = process.wait()
+
+    if return_code != 0:
+        error_output = process.stderr.read() if process.stderr else ""
+        print(f"\033[91mError: {error_output}\033[0m")
+        if process.stderr:
+            process.stderr.close()
+        raise SystemExit(1)
+
+
+def main() -> None:
+    args = parse_arguments()
+    Path(args.dest).mkdir(parents=True, exist_ok=True)
+    targets = parse_targets(args.target)
+    run_bxl_and_merge_index(
+        targets, args.dest, args.config, args.subtarget, args.isolation_dir
+    )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/ide_integrations/apple/build_index/swift_index_store.bxl b/buck2/prelude/ide_integrations/apple/build_index/swift_index_store.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/apple/build_index/swift_index_store.bxl
@@ -0,0 +1,75 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//bxl:lazy.bxl", "batch_apply_lazy")
+load("@prelude//cxx:index_store.bzl", "IndexStoreInfo", "merge_index_store")
+
+MERGE_TOOL_TARGET = "prelude//apple/tools/index:merge_index_store"
+
+# Magic number here. There is a trade off here:
+# more buckets -> fewer index stores in each bucket -> more duplication -> more materializion time but less time to wait from RE to merge bucket
+# less buckets -> more index stores in each bucket -> less duplication -> less materialization time but more time to wait from RE to merge bucket
+BUCKET_COUNT = 20
+
+def _hash_bucket_index_stores(index_stores: list[Artifact]) -> dict[int, list[Artifact]]:
+    buckets_to_artifacts = {}
+    for index_store in index_stores:
+        hash_value = hash(index_store.short_path)
+        bucket = hash_value % BUCKET_COUNT
+        if bucket not in buckets_to_artifacts:
+            buckets_to_artifacts[bucket] = []
+        buckets_to_artifacts[bucket].append(index_store)
+    return buckets_to_artifacts
+
+def _main(ctx: bxl.Context):
+    targets = ctx.cli_args.target
+    subtarget = getattr(ctx.cli_args, "subtarget", "full-swift-index-store")
+    configured_nodes = batch_apply_lazy(ctx, ctx.lazy.configured_target_node, targets)
+    analysis_results = batch_apply_lazy(ctx, ctx.lazy.analysis, configured_nodes)
+
+    index_stores = []
+    for analysis_res in analysis_results:
+        if IndexStoreInfo not in analysis_res.providers():
+            continue
+        index_store_info = analysis_res.providers()[IndexStoreInfo]
+        if subtarget == "swift-index-store":
+            # Only get the Swift index store for this target (not transitive dependencies)
+            index_stores.append(index_store_info.swift_tset.value)
+        elif subtarget == "swift-index-store-1deps":
+            # Get the Swift index store for this target and its immediate dependencies
+            index_stores.append(index_store_info.swift_tset.value)
+            for child in index_store_info.swift_tset.children:
+                index_stores.append(child.value)
+        else:
+            # Default behavior: get all Swift index stores including transitive dependencies
+            index_stores.extend(list(index_store_info.swift_tset.traverse()))
+
+    merge_tool_target = ctx.unconfigured_sub_targets(MERGE_TOOL_TARGET)
+    bxl_actions = ctx.bxl_actions(
+        exec_deps = [merge_tool_target],
+    )
+
+    merge_tool = bxl_actions.exec_deps[merge_tool_target][RunInfo]
+
+    buckets_to_artifacts = _hash_bucket_index_stores(index_stores)
+
+    for bucket, index_stores in buckets_to_artifacts.items():
+        if not index_stores:
+            continue
+        merged_buck_index_store = merge_index_store(bxl_actions.actions, merge_tool, index_stores, "merge_bucket/{}/index_store".format(bucket))
+
+        merged = ctx.output.ensure(merged_buck_index_store).abs_path()
+        ctx.output.stream(merged, wait_on = [merged])
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "subtarget": cli_args.option(cli_args.string()),
+        "target": cli_args.list(cli_args.string()),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/BUCK b/buck2/prelude/ide_integrations/visual_studio/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/BUCK
@@ -0,0 +1,41 @@
+# @no-autodeps
+
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("windows_ide_support")
+
+source_listing()
+
+filegroup(
+    name = "vsgo_bxl",
+    srcs = glob(["**/*.bxl"]),
+    visibility = ["PUBLIC"],
+)
+
+export_file(
+    name = "absolutize_path_exe",
+    src = "msvs/absolutize_path.exe",
+    mode = "reference",
+    visibility = ["PUBLIC"],
+)
+
+export_file(
+    name = "vs_buck_build_props",
+    src = "msvs/vs_buck_build.props",
+    mode = "reference",
+    visibility = ["PUBLIC"],
+)
+
+python_library(
+    name = "vsgo_lib",
+    srcs = ["vsgo.py"],
+    visibility = ["PUBLIC"],
+)
+
+python_binary(
+    name = "vsgo",
+    main_module = ".vsgo",
+    deps = [
+        ":vsgo_lib",
+    ],
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/README.md b/buck2/prelude/ide_integrations/visual_studio/README.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/README.md
@@ -0,0 +1,34 @@
+# VSGO: Visual Studio project generation for buck targets
+
+VSGO is a project generator that generates Visual Studio project and solution
+files given buck target labels or patterns, with full functional IntelliSense
+and build/run/debug setup.
+
+The majority of heavy lifting is implemented in
+[BXL](https://buck2.build/docs/developers/bxl/), Buck Extension Language, which
+offers superb performance and handles incremental changes extremely well.
+
+![demo](assets/demo.png)
+
+## Quick Start
+
+Use project "buck2/examples/vscode" as an example,
+
+```
+mkdir modes && echo "" > modes/debug  # One-time setup. Skip if there is one already exists.
+python prelude/ide_integrations/visual_studio/vsgo.py root//:main --mode_files modes/debug
+```
+
+This will generate project and solution files for the specific target and output
+file paths at the end. From there, you can continue with Visual Studio to
+browse, edit, and run/debug your buck target.
+
+To list all options and their help docs, run
+
+```
+python prelude/ide_integrations/visual_studio/vsgo.py --help
+```
+
+## How It Works
+
+![how-it-works.png](assets/how-it-works.png)
diff --git a/buck2/prelude/ide_integrations/visual_studio/constants.bxl b/buck2/prelude/ide_integrations/visual_studio/constants.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/constants.bxl
@@ -0,0 +1,26 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+DEBUG_CMD = "BuckDebuggerCommand"
+DEBUG_ARGS = "BuckDebuggerCommandArguments"
+DEBUG_PWD = "BuckDebuggerCommandWorkingDirectory"
+DEBUG_ENV = "BuckDebuggerEnvironment"
+
+ADDITIONAL_TARGETS = "AdditionalTargets"
+EXTRA_BUCK_OPTIONS = "ExtraBuckOptions"
+IMMEDIATE_BUCK_OPTIONS = "ImmediateBuckOptions"
+
+BY_MODES = "ByModes"
+
+TOOLSET = "toolset"
+LANGUAGE_STANDARD = "language_standard"
+
+CLANG = "clang"
+CLANG_WINDOWS = "clang_windows"
+VS2019 = "vs2019"
+VS2022 = "vs2022"
diff --git a/buck2/prelude/ide_integrations/visual_studio/flags_parser_utils.bxl b/buck2/prelude/ide_integrations/visual_studio/flags_parser_utils.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/flags_parser_utils.bxl
@@ -0,0 +1,178 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("ppflags.bxl", "COMPILER_FLAGS_MAP", "COMPILER_IGNORE_OPTIONS", "LANGUAGE_STANDARD_MAP", "LINKER_FLAGS_MAP")
+load("utils.bxl", "dedupe_by_value")
+
+def flatten_flag_lists(flag_lists):
+    # Flags are in form of list of list like [["/WX"],["/W4"],["/w15038"]] in attrs and list of strings in mode config
+    flatten_list = []
+    for flag in flag_lists:
+        if isinstance(flag, list):
+            flatten_list.extend(flag)
+        elif isinstance(flag, str):
+            flatten_list.append(flag)
+    return flatten_list
+
+def unquote_flag(flag):
+    if flag.startswith('"') and flag.endswith('"'):
+        return flag[1:-1]
+    elif flag.startswith('\\"') and flag.endswith('\\"'):
+        return flag[2:-2]
+    return flag
+
+def parse_include_dirs_from_flags(flags):
+    include_dirs = []
+    filtered_flags = []
+    skip_next = False
+    for i in range(len(flags)):
+        if skip_next:
+            skip_next = False
+            continue
+        include_path = None
+        flag = unquote_flag(flags[i])
+        if flag in ["/I", "-I", "/isystem", "-isystem"]:
+            include_path = unquote_flag(flags[i + 1])
+            skip_next = True
+        elif flag.startswith("/I") or flag.startswith("-I"):
+            include_path = flag[2:]
+        elif flag.startswith("/isystem") or flag.startswith("-isystem"):
+            include_path = flag[len("-isystem") :]
+
+        if include_path:
+            include_dirs.append("$(RepoRoot)\\" + include_path)
+        else:
+            filtered_flags.append(flag)
+
+    return include_dirs, filtered_flags
+
+def parse_defines_from_flags(flags):
+    defines = []
+    undefines = []
+    filtered_flags = []
+    skip_next = False
+    for i in range(len(flags)):
+        if skip_next:
+            skip_next = False
+            continue
+        define = None
+        undefine = None
+        flag = unquote_flag(flags[i])
+        if flag == "/D" or flag == "-D":
+            define = unquote_flag(flags[i + 1])
+            skip_next = True
+        elif flag.startswith("/D") or flag.startswith("-D"):
+            define = flag[2:]
+            splits = define.split("=")
+            if len(splits) == 2:
+                define = splits[0] + "=" + unquote_flag(splits[1])
+        elif flag == "/U" or flag == "-U":
+            undefine = unquote_flag(flags[i + 1])
+            skip_next = True
+        elif flag.startswith("/U") or flag.startswith("-U"):
+            undefine = flag[2:]
+            splits = undefine.split("=")
+            if len(splits) == 2:
+                undefine = splits[0] + "=" + unquote_flag(splits[1])
+
+        if define:
+            defines.append(define)
+        elif undefine:
+            undefines.append(undefine)
+        else:
+            filtered_flags.append(flag)
+
+    return dedupe_by_value(defines), dedupe_by_value(undefines), filtered_flags
+
+def get_linker_settings_from_flags(flags, buck_root):
+    linker_settings = {}
+
+    additional_library_directories = []
+    additional_dependencies = []
+    additional_options = []
+    no_default_libs = []
+
+    for flag in flags:
+        original_flag = flag
+
+        # Unify leading character to "/" for easier matching
+        if flag.startswith("-"):
+            flag = "/" + flag[1:]
+
+        if not flag.startswith("/"):
+            additional_dependencies.append(flag)
+        elif flag.startswith("/LIBPATH:"):
+            additional_library_directories.append(flag[len("/LIBPATH:") :])
+        elif flag.startswith("/NODEFAULTLIB:"):
+            no_default_libs.append(flag[len("/NODEFAULTLIB:") :])
+        elif flag in LINKER_FLAGS_MAP:
+            linker_settings.update(LINKER_FLAGS_MAP[flag])
+        elif flag.startswith("/TLBID:"):
+            linker_settings["TypeLibraryResourceID"] = flag[len("/TLBID:") :]
+        elif flag.startswith("/PDBALTPATH"):
+            pass
+        elif flag.startswith("/PDBSOURCEPATH"):
+            # Overwrite the /PDBSOURCEPATH to the buck root instead of using the default
+            additional_options.append("/PDBSOURCEPATH:" + buck_root)
+        elif flag.startswith("/INCLUDE:"):
+            if "ForceSymbolReferences" not in linker_settings:
+                linker_settings["ForceSymbolReferences"] = []
+            linker_settings["ForceSymbolReferences"].append(
+                flag[len("/INCLUDE:") :],
+            )
+        else:
+            additional_options.append(original_flag)
+
+    linker_settings["AdditionalLibraryDirectories"] = dedupe_by_value(
+        additional_library_directories,
+    )
+    linker_settings["AdditionalDependencies"] = dedupe_by_value(additional_dependencies)
+    linker_settings["AdditionalOptions"] = dedupe_by_value(additional_options)
+    linker_settings["IgnoreDefaultLibraryNames"] = dedupe_by_value(no_default_libs)
+
+    return linker_settings
+
+def get_compiler_settings_from_flags(flags):
+    compiler_settings = {}
+    disable_specific_warnings = []
+    forced_include_files = []
+    additional_options = []
+
+    include_directories, flags = parse_include_dirs_from_flags(flags)
+    defines, undefines, flags = parse_defines_from_flags(flags)
+
+    for flag in flags:
+        original_flag = flag
+
+        # Unify leading character to "/" for easier matching
+        if flag.startswith("-"):
+            flag = "/" + flag[1:]
+
+        if flag in COMPILER_FLAGS_MAP:
+            compiler_settings.update(COMPILER_FLAGS_MAP[flag])
+        elif flag in LANGUAGE_STANDARD_MAP:
+            compiler_settings["LanguageStandard"] = LANGUAGE_STANDARD_MAP[flag]
+        elif flag in COMPILER_IGNORE_OPTIONS:
+            pass
+        elif flag.startswith("/FI"):
+            forced_include_files.append(flag[3:])
+        elif flag.startswith("/wd"):
+            disable_specific_warnings.append(flag[3:])
+        elif flag.startswith("/W"):
+            pass  # Incompatible gcc style warnings
+        else:
+            additional_options.append(original_flag)
+
+    compiler_settings["AdditionalIncludeDirectories"] = include_directories
+    compiler_settings["AdditionalOptions"] = additional_options
+    compiler_settings["PreprocessorDefinitions"] = defines
+    compiler_settings["UndefinePreprocessorDefinitions"] = undefines
+    compiler_settings["DisableSpecificWarnings"] = disable_specific_warnings
+    compiler_settings["ForcedIncludeFiles"] = forced_include_files
+
+    return compiler_settings
diff --git a/buck2/prelude/ide_integrations/visual_studio/gen_filters.bxl b/buck2/prelude/ide_integrations/visual_studio/gen_filters.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/gen_filters.bxl
@@ -0,0 +1,164 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("get_attrs.bxl", "get_attrs", "get_cxx_toolchain")
+load("get_vs_settings.bxl", "get_vs_settings")
+load("utils.bxl", "dedupe_by_value", "dirname", "get_project_file_path", "h")
+
+def _get_common_directory(paths) -> str:
+    # handle single file case separately, otherwise it will return the full path
+    if len(paths) == 1:
+        return paths[0].rsplit("\\", 2)[0] + "\\"
+
+    components = [path.split("\\") for path in paths]
+    common_prefix = []
+    for component_list in zip(*components):
+        if len(set(component_list)) == 1:
+            common_prefix.append(component_list[0])
+        else:
+            break
+
+    # Remove the last level of common directory so that there's always something in the filters file
+    if len(common_prefix) != 0:
+        common_prefix.pop()
+    return "\\".join(common_prefix) + ("\\" if len(common_prefix) != 0 else "")
+
+def _get_file_filter_map(vs_settings: dict) -> dict:
+    filters = {}
+    files = vs_settings["Headers"] + vs_settings["Sources"].keys()
+
+    # Handle paths that start with "buck-out"(exported files) separately since these file
+    # don't have any common dir with the others and would make the hierarchy really nested
+    # if processed together
+    buck_out_paths = [path for path in files if path.startswith("buck-out")]
+    buck_out_common_dir = _get_common_directory(buck_out_paths)
+    for file in buck_out_paths:
+        # Add a "generated_files" folder so that the files don't get mixed up with the others
+        filters[file] = "\\".join(["generated_files", dirname(file[len(buck_out_common_dir) :], "\\")])
+
+    non_buck_out_paths = [path for path in files if not path.startswith("buck-out")]
+    non_buck_out_common_dir = _get_common_directory(non_buck_out_paths)
+    for file in non_buck_out_paths:
+        filters[file] = dirname(file[len(non_buck_out_common_dir) :], "\\")
+    return filters
+
+def _get_filter_list(file_filter_map: dict) -> list:
+    """
+    All levels of directory need to defined as filters
+    e.g. To define a filter "include\\npc\\AI\\Attention", we need to define
+    ["include", "include\\npc", "include\\npc\\AI", "include\\npc\\AI\\Attention"]
+    """
+    filters = []
+    for filter in file_filter_map.values():
+        components = filter.split("\\")
+        current_path = ""
+        for component in components:
+            if current_path:
+                current_path += "\\" + component
+            else:
+                current_path = component
+            filters.append(current_path)
+    return dedupe_by_value(filters)
+
+def gen_filters(vs_settings: dict):
+    filters_map = _get_file_filter_map(vs_settings)
+    filters_list = _get_filter_list(filters_map)
+    content = cmd_args(
+        """<?xml version="1.0" encoding="utf-8"?>""",
+        """<Project ToolsVersion="17.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">""",
+        h(
+            "ItemGroup",
+            [h("Filter", None, {"Include": filter}, indent_level = 2) for filter in filters_list],
+            {
+                "Label": "Filters",
+            },
+            indent_level = 1,
+        ),
+        h(
+            "ItemGroup",
+            [
+                h(
+                    "ClCompile",
+                    [h("Filter", filters_map[file], indent_level = 3)],
+                    {"Include": "$(RepoRoot)\\" + file},
+                    indent_level = 2,
+                )
+                for file in vs_settings["Sources"]
+            ],
+            {
+                "Label": "Sources",
+            },
+            indent_level = 1,
+        ),
+        h(
+            "ItemGroup",
+            [
+                h(
+                    "ClInclude",
+                    [h("Filter", filters_map[file], indent_level = 3)],
+                    {"Include": "$(RepoRoot)\\" + file},
+                    indent_level = 2,
+                )
+                for file in vs_settings["Headers"]
+            ],
+            {
+                "Label": "Headers",
+            },
+            indent_level = 1,
+        ),
+        """</Project>""",
+        delimiter = "\n",
+    )
+    return content
+
+def _main(bxl_ctx):
+    target_label = bxl_ctx.cli_args.target
+    target_node = bxl_ctx.configured_targets(target_label, modifiers = bxl_ctx.modifiers)
+    actions = bxl_ctx.bxl_actions().actions
+    attrs = get_attrs(target_node, bxl_ctx)
+    toolchain = get_cxx_toolchain(target_node, bxl_ctx)
+    attrs_outfile = actions.write_json(get_project_file_path(target_node.label, ".json"), attrs, has_content_based_path = False)
+    filters_artifact = actions.declare_output(get_project_file_path(target_node.label, ".vcxproj.filters"), has_content_based_path = False)
+
+    def f(
+        ctx,
+        artifacts,
+        outputs,
+        attrs_outfile = attrs_outfile,
+        filters_artifact = filters_artifact,
+        target = target_node,
+        cli_args = bxl_ctx.cli_args,
+        buck_root = bxl_ctx.root(),
+    ):
+        attrs_input = artifacts[attrs_outfile].read_json()
+        vs_settings = get_vs_settings(target, toolchain, attrs_input, {}, cli_args, buck_root, ctx)
+        content = gen_filters(vs_settings)
+        ctx.bxl_actions().actions.write(outputs[filters_artifact].as_output(), content, allow_args = True)
+
+    actions.dynamic_output(
+        dynamic = [attrs_outfile],
+        inputs = [],
+        outputs = [
+            filters_artifact.as_output(),
+        ],
+        f = f,
+    )
+    bxl_ctx.output.print(bxl_ctx.output.ensure(filters_artifact))
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "debug_settings": cli_args.option(cli_args.json()),  # target label => debug_settings.
+        "extra_buck_options": cli_args.list(cli_args.string(), default = []),
+        "immediate_buck_options": cli_args.list(cli_args.string(), default = []),
+        "log_level": cli_args.int(default = 30),
+        "mode_files": cli_args.list(cli_args.string(), default = ["fbsource//arvr/mode/win/dev"]),
+        "mode_hashes": cli_args.option(cli_args.json()),  # mode => configuration hash.
+        "target": cli_args.target_label(),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/gen_mode_configs.bxl b/buck2/prelude/ide_integrations/visual_studio/gen_mode_configs.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/gen_mode_configs.bxl
@@ -0,0 +1,228 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("constants.bxl", "CLANG", "CLANG_WINDOWS", "LANGUAGE_STANDARD", "TOOLSET", "VS2019", "VS2022")
+load("flags_parser_utils.bxl", "get_compiler_settings_from_flags", "get_linker_settings_from_flags")
+load("get_compiler_settings.bxl", "gen_compiler_settings")
+load("get_linker_settings.bxl", "gen_linker_settings")
+load("utils.bxl", "dedupe_by_value", "get_mode_config_path", "h")
+
+# @unsorted-dict-items
+LANGUAGE_STANDARD_AND_TOOLSET_MAP = {
+    CLANG: {
+        LANGUAGE_STANDARD: None,
+        TOOLSET: "Clang_5_0",
+    },
+    CLANG_WINDOWS: {
+        LANGUAGE_STANDARD: "stdcpp20",
+        TOOLSET: "ClangCL",
+    },
+    VS2019: {
+        LANGUAGE_STANDARD: "stdcpp17",
+        TOOLSET: "v142",
+    },
+    VS2022: {
+        LANGUAGE_STANDARD: "stdcpp20",
+        TOOLSET: "v143",
+    },
+}
+
+ABSOLUTIZE_PATH_EXE = "prelude//ide_integrations/visual_studio:absolutize_path_exe"
+VS_BUCK_BUILD_PROPS = "prelude//ide_integrations/visual_studio:vs_buck_build_props"
+
+def _remove_flags_with_macros(flags: list) -> list:
+    # Hacky way to find macros since regex sub is not available in bxl
+    flags = [item for item in flags if "$(" not in item and ")" not in item]
+    return dedupe_by_value(flags)
+
+# Simple record type that holds flags read from the `cxx_toolchain`.
+_CxxToolchainFlags = record(
+    cxxflags = list[str],
+    cxxppflags = list[str],
+    ldflags = list[str],
+)
+
+def _get_compiler_settings(cxx_toolchain_flags: _CxxToolchainFlags) -> dict:
+    compiler_flags = cxx_toolchain_flags.cxxppflags + cxx_toolchain_flags.cxxflags
+    compiler_flags = _remove_flags_with_macros(compiler_flags)
+    return get_compiler_settings_from_flags(compiler_flags)
+
+def _get_linker_settings(cxx_toolchain_flags: _CxxToolchainFlags, buck_root: str) -> dict:
+    linker_flags = _remove_flags_with_macros(cxx_toolchain_flags.ldflags)
+    return get_linker_settings_from_flags(linker_flags, buck_root)
+
+def _get_provider_output_path(provider, bxl_ctx):
+    default_outputs = provider.default_outputs
+    if default_outputs:
+        return get_path_without_materialization(default_outputs[0], bxl_ctx, abs = True)
+    else:
+        return None
+
+def _get_path(target: str, bxl_ctx):
+    target_node = bxl_ctx.configured_targets(target)
+    providers = bxl_ctx.analysis(target_node).providers()
+    absolute_path = _get_provider_output_path(providers[DefaultInfo], bxl_ctx)
+    return absolute_path
+
+def _produce_proj_artifact_with_async_cxx_toolchain(bxl_ctx, actions, fbsource: bool, output_artifact: Artifact, root: str) -> None:
+    """Reads the cxx_toolchain's flags with `actions.dynamic_output` before continuing to produce the final output project artifact.
+
+    The cxx_toolchain's flags cannot be directly read because they are type `cmd_args`.
+    The flags are indirectly read after dynamically materializing them to an output artifact
+    (i.e., write them to an artifact, and read them inside of `dynamic_output`'s callback).
+    """
+
+    # Get the configured toolchain target with modifiers applied to ensure correct toolchain selection
+    cxx_toolchain_target_node = bxl_ctx.configured_targets("toolchains//:cxx", modifiers = bxl_ctx.modifiers)
+    cxx_toolchain_analysis_result = bxl_ctx.analysis(cxx_toolchain_target_node)
+    cxx_toolchain = cxx_toolchain_analysis_result.providers().get(CxxToolchainInfo)
+    compiler_type = cxx_toolchain.cxx_compiler_info.compiler_type
+    if compiler_type == "windows":
+        platform = "vs" + bxl_ctx.cli_args.vs_version_year
+    else:
+        platform = compiler_type
+
+    cxxflags_artifact, cxxflags_macro_artifacts = actions.write(
+        "cxxflags", cxx_toolchain.cxx_compiler_info.compiler_flags, allow_args = True, has_content_based_path = False
+    )
+
+    cxxppflags_artifact, cxxppflags_macro_artifacts = actions.write(
+        "cxxppflags", cxx_toolchain.cxx_compiler_info.preprocessor_flags, allow_args = True, has_content_based_path = False
+    )
+
+    ldflags_artifact, ldflags_macro_artifacts = actions.write("ldflags", cxx_toolchain.linker_info.linker_flags, allow_args = True, has_content_based_path = False)
+
+    def dyn_output_continuation(ctx, dynamic: dict[Artifact, ArtifactValue], outputs: dict[Artifact, typing.Any], platform = platform) -> None:
+        """async continuation/callback for the `dynamic_output` call that reads the cxx_toolchain flags from materialized artifacts and continues to produce the final project file artifact.
+
+        The cxx_toolchain flags are stored in `dynamic` and are now readable becuase their artifacts were materialized by the `dynamic_output`.
+        """
+        cxxflags = dynamic[cxxflags_artifact].read_string().splitlines()
+        cxxppflags = dynamic[cxxppflags_artifact].read_string().splitlines()
+        ldflags = dynamic[ldflags_artifact].read_string().splitlines()
+        cxx_toolchain_flags = _CxxToolchainFlags(
+            cxxflags = cxxflags,
+            cxxppflags = cxxppflags,
+            ldflags = ldflags,
+        )
+
+        # the actions are grabbed again because the outer ones cannot be frozen
+        actions = ctx.bxl_actions().actions
+        hidden_artifacts = cxxflags_macro_artifacts + cxxppflags_macro_artifacts + ldflags_macro_artifacts
+        _produce_proj_artifact(
+            ctx, actions, fbsource, cxx_toolchain_flags, outputs[output_artifact], root = root, platform = platform, hidden_artifacts = hidden_artifacts
+        )
+
+    dyn_artifacts = [
+        cxxflags_artifact,
+        cxxppflags_artifact,
+        ldflags_artifact,
+    ]
+    actions.dynamic_output(dynamic = dyn_artifacts, inputs = [], outputs = [output_artifact.as_output()], f = dyn_output_continuation)
+
+    bxl_ctx.output.ensure_multiple(dyn_artifacts)
+
+def _main(bxl_ctx):
+    actions = bxl_ctx.bxl_actions().actions
+
+    # Capture `fbsource` and `root` because those attributes on `bxl_ctx` are not avaliable on the dynamic_output's ctx and `bxl_ctx` cannot be captured.
+    fbsource = bxl_ctx.cli_args.fbsource
+    root = bxl_ctx.root()
+
+    output_artifact = actions.declare_output(get_mode_config_path(bxl_ctx.cli_args.mode_name), has_content_based_path = False)
+
+    _produce_proj_artifact_with_async_cxx_toolchain(bxl_ctx, actions, fbsource, output_artifact, root = root)
+
+    bxl_ctx.output.print(bxl_ctx.output.ensure(output_artifact).abs_path())
+
+def _produce_proj_artifact(
+    bxl_ctx,
+    actions,
+    fbsource: bool,
+    cxx_toolchain_flags: _CxxToolchainFlags,
+    output_artifact: Artifact,
+    root: str,
+    platform: str,
+    hidden_artifacts: None | list[Artifact] = None,
+):
+    """Produce the <Project> file output artifact"""
+    compiler_settings = _get_compiler_settings(cxx_toolchain_flags)
+    linker_settings = _get_linker_settings(cxx_toolchain_flags, root)
+    platform_toolset = LANGUAGE_STANDARD_AND_TOOLSET_MAP[platform][TOOLSET]
+
+    # Set default language standard if not specified
+    if "LanguageStandard" not in compiler_settings:
+        compiler_settings["LanguageStandard"] = LANGUAGE_STANDARD_AND_TOOLSET_MAP[platform][LANGUAGE_STANDARD]
+
+    # Overwrite configs for clang(android) projects
+    if platform == CLANG:
+        compiler_settings.pop("LanguageStandard")
+
+    compiler_settings_content = gen_compiler_settings(compiler_settings)
+    linker_settings_content = gen_linker_settings(linker_settings)
+
+    toolchains_props = ""
+    if fbsource and platform != CLANG:
+        toolchains_props = '        <Import Project="$(RepoRoot)\\third-party\\toolchains\\visual_studio\\toolchain.props"/>'
+
+    absolutize_path_exe = _get_path(ABSOLUTIZE_PATH_EXE, bxl_ctx)
+    vs_buck_build_props_path = _get_path(VS_BUCK_BUILD_PROPS, bxl_ctx)
+    vs_buck_build_props = """        <Import Project="{}"/>""".format(vs_buck_build_props_path)
+
+    content = cmd_args(
+        """<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+""",
+        """    <ImportGroup Label="PropertySheets">""",
+        """        <Import Project="$(VCTargetsPath)\\Microsoft.Cpp.default.props" />""",
+        """    </ImportGroup>""",
+        h(
+            "PropertyGroup",
+            [
+                h("PlatformToolset", platform_toolset, indent_level = 2),
+                h("AbsolutizePathExe", absolutize_path_exe, indent_level = 2),
+            ],
+            indent_level = 1,
+        ),
+        """    <ImportGroup Label="PropertySheets">""",
+        """        <Import Project="$(VCTargetsPath)\\Microsoft.Cpp.props" />""",
+        """        <Import Condition="exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"/>""",
+        toolchains_props,
+        """    </ImportGroup>""",
+        """    <ItemDefinitionGroup>""",
+        compiler_settings_content,
+        linker_settings_content,
+        """    </ItemDefinitionGroup>""",
+        """    <Import Project="$(VCTargetsPath)\\Microsoft.Cpp.Targets" />""",
+        """    <ImportGroup Label="PropertySheets">""",
+        vs_buck_build_props,
+        """    </ImportGroup>""",
+        """</Project>""",
+        delimiter = "\n",
+        hidden = hidden_artifacts or [],
+    )
+
+    actions.write(output_artifact.as_output(), content, allow_args = True)
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "fbsource": cli_args.bool(
+            default = False,
+            doc = "Whether to turn on fbsource specific behaviors.",
+        ),
+        "mode_name": cli_args.string(
+            doc = "Single mode file to generate projects for.",
+        ),
+        "vs_version_year": cli_args.string(
+            default = "2022",
+            doc = "Generate mode configs for Visual Studio <vs_version_year> projects",
+        ),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/gen_sln.bxl b/buck2/prelude/ide_integrations/visual_studio/gen_sln.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/gen_sln.bxl
@@ -0,0 +1,203 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("get_vs_settings.bxl", "get_basic_vs_settings")
+load("utils.bxl", "basename", "gen_guid", "get_project_file_path", "log_debug", "sanitize")
+
+def _gen_entry(project_type_guid, project_name, project_filepath, project_guid):
+    return """Project("{project_type_guid}") = "{project_name}", "{project_filepath}", "{project_guid}"
+EndProject""".format(
+        project_type_guid = project_type_guid,
+        project_name = project_name,
+        project_filepath = project_filepath,
+        project_guid = project_guid,
+    )
+
+def _gen_folder(folder_path, guid):
+    project_name = basename(folder_path)
+
+    # Imagine you have `foo//bar:bar` and `foo//:bar`.  This means that underneath `foo`, you will have
+    # both a Solution Folder called `bar`, as well as a project called `bar`.  Visual Studio doesn't
+    # allow this, so we disambiguate folders from projects by surrounding folder names with parens.
+    # While we could try to be smart and only do this when we detect a collision, what happens then is
+    # that we would end up with solution folders, some with parens and some without parens, and it would
+    # break the sorting of child items when there is a long list of solution folders.  For example, you
+    # might end up with:
+    #    (bar)
+    #    (xyz)
+    #    bar
+    project_name = "(" + project_name + ")"
+
+    # List of project type GUIDs https://github.com/JamesW75/visual-studio-project-type-guid
+    project_type_guid_folder = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"
+
+    return _gen_entry(
+        project_type_guid_folder,
+        project_name,
+        project_name,
+        guid,
+    )
+
+def _gen_project(target, vs_settings):
+    project_name = sanitize(target.label.name)
+
+    # List of project type GUIDs https://github.com/JamesW75/visual-studio-project-type-guid
+    project_type_guid_cpp = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}"
+
+    return _gen_entry(
+        project_type_guid_cpp,
+        project_name,
+        get_project_file_path(target.label, ".vcxproj").replace("/", "\\"),
+        vs_settings["Globals"]["ProjectGuid"],
+    )
+
+# For each target/project, generate intermediate folder entries if they haven't and the target/project itself,
+# as well as mappings of item => folder for solution nested projects structure.
+def _gen_target(target, vs_settings, existing_folders, nested_projects):
+    entries = []
+
+    # It's possible to have `foo//:target` and `bar//:target`.  It's not sufficient to simply use the package
+    # name, because if you do that then you will get a name collision in the above scenario.
+    folders = [target.label.cell]
+    if target.label.package:
+        folders += target.label.package.split("/")
+
+    folder_prev = None
+    for i in range(len(folders)):
+        folder = "/".join(folders[0 : i + 1])
+        folder_guid = gen_guid(folder)
+        if folder_prev:
+            nested_projects[folder_guid] = existing_folders[folder_prev]
+        if folder not in existing_folders:
+            entries.append(_gen_folder(folder, folder_guid))
+            existing_folders[folder] = folder_guid
+        folder_prev = folder
+    nested_projects[vs_settings["Globals"]["ProjectGuid"]] = existing_folders[folder_prev]
+
+    entries.append(_gen_project(target, vs_settings))
+    return "\n".join(entries)
+
+def _gen_nested_projects(nested_projects):
+    return "\n".join(["\t\t{} = {}".format(child, parent) for (child, parent) in nested_projects.items()])
+
+def _gen_solution_configuration_platform(project_configuration):
+    return "\t\t{configuration}|{platform} = {configuration}|{platform}".format(
+        configuration = project_configuration["Configuration"],
+        platform = project_configuration["Platform"],
+    )
+
+def _gen_project_configuration_platforms(target_node, vs_settings, explicit_targets):
+    configs = []
+    guid = vs_settings["Globals"]["ProjectGuid"]
+    for config in vs_settings["ProjectConfigurations"]:
+        config_name = config["Configuration"] + "|" + config["Platform"]
+        configs.append(
+            "\t\t{guid}.{config_name}.ActiveCfg = {config_name}".format(
+                guid = guid,
+                config_name = config_name,
+            )
+        )
+        if target_node.label.raw_target() in explicit_targets:
+            configs.append(
+                "\t\t{guid}.{config_name}.Build.0 = {config_name}".format(
+                    guid = guid,
+                    config_name = config_name,
+                )
+            )
+    return "\n".join(configs)
+
+def _set_startup_target(targets, vs_settings_list, startup_target_label: TargetLabel):
+    targets_labels = [target.label.raw_target() for target in targets]
+    if startup_target_label in targets_labels:
+        startup_target_index = targets_labels.index(startup_target_label)
+        targets[0], targets[startup_target_index] = targets[startup_target_index], targets[0]
+        vs_settings_list[0], vs_settings_list[startup_target_index] = vs_settings_list[startup_target_index], vs_settings_list[0]
+    else:
+        warning(
+            "Startup target couldn't be located: {}. Please check passed in targets list, `--recursive_target_types`, `--target_exclude_pattern` and `--target_exclude_pattern`.".format(
+                startup_target_label
+            )
+        )
+
+# In buck dependency tree, duplicate targets can exist with exact same label but different
+# configurations. While VS doesn't like duplicate project names (prompting with message: The
+# solution already contains an item named 'xxx'). Besides, there is not much value in showing
+# multiple projects for the same target but with slightly different configuration. Ideally, this
+# could be more efficient trimming those duplicates while building dependency trees, but it's more
+# risky of getting missing target nodes while traversaling the dependency tree after trimming.
+def _dedup_targets(targets, vs_settings_list):
+    deduped_targets = []
+    deduped_vs_settings_list = []
+    seen_raw_targets = set()
+    for i in range(len(targets)):
+        raw_target = targets[i].label.raw_target()
+        if raw_target not in seen_raw_targets:
+            seen_raw_targets.add(raw_target)
+            deduped_targets.append(targets[i])
+            deduped_vs_settings_list.append(vs_settings_list[i])
+    return deduped_targets, deduped_vs_settings_list
+
+def gen_sln(targets, vs_settings_list, explicit_targets, startup_target_label: TargetLabel, bxl_ctx):
+    log_debug("# Generating sln for {}", startup_target_label, bxl_ctx = bxl_ctx)
+    if len(targets) != len(vs_settings_list):
+        fail("targets and vs_settings_list are expected to be length.")
+
+    _set_startup_target(targets, vs_settings_list, startup_target_label)
+    targets, vs_settings_list = _dedup_targets(targets, vs_settings_list)
+    existing_folders = {}  # folder path => folder guid
+    nested_projects = {}  # project guid => parent guid
+
+    # Ideally this should have some amount of uniqueness built in, but it isn't clear what a good algorithm for doing this would be
+    solution_guid = gen_guid("Buck2 vsgo solution file")
+    sln_content = """Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17
+MinimumVisualStudioVersion = 10.0.40219.1
+{projects}
+Global
+\tGlobalSection(SolutionConfigurationPlatforms) = preSolution
+{solution_configuration_platforms}
+\tEndGlobalSection
+\tGlobalSection(ProjectConfigurationPlatforms) = postSolution
+{project_configuration_platforms}
+\tEndGlobalSection
+\tGlobalSection(SolutionProperties) = preSolution
+\t\tHideSolutionNode = FALSE
+\tEndGlobalSection
+\tGlobalSection(NestedProjects) = preSolution
+{nested_projects}
+\tEndGlobalSection
+\tGlobalSection(ExtensibilityGlobals) = postSolution
+\t\tSolutionGuid = {solution_guid}
+\tEndGlobalSection
+EndGlobal""".format(
+        projects = "\n".join([_gen_target(t, s, existing_folders, nested_projects) for (t, s) in zip(targets, vs_settings_list)]),
+        solution_configuration_platforms = "\n".join([_gen_solution_configuration_platform(config) for config in vs_settings_list[-1]["ProjectConfigurations"]]),
+        project_configuration_platforms = "\n".join([_gen_project_configuration_platforms(t, s, explicit_targets) for (t, s) in zip(targets, vs_settings_list)]),
+        nested_projects = _gen_nested_projects(nested_projects),
+        solution_guid = solution_guid,
+    )
+
+    return sln_content
+
+def _main(bxl_ctx):
+    target_label = bxl_ctx.cli_args.target
+    target_node = bxl_ctx.configured_targets(target_label, modifiers = bxl_ctx.modifiers)
+
+    basic_vs_settings = get_basic_vs_settings(target_node, bxl_ctx.cli_args)
+    sln_content = gen_sln([target_node], [basic_vs_settings], [target_label], target_node.label, bxl_ctx)
+    bxl_ctx.output.print(sln_content)
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "log_level": cli_args.int(default = 30),
+        "mode_files": cli_args.list(cli_args.string(), default = ["fbsource//arvr/mode/win/dev"]),
+        "target": cli_args.target_label(),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/gen_user_macros.bxl b/buck2/prelude/ide_integrations/visual_studio/gen_user_macros.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/gen_user_macros.bxl
@@ -0,0 +1,52 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("constants.bxl", "ADDITIONAL_TARGETS", "BY_MODES", "DEBUG_ARGS", "DEBUG_CMD", "DEBUG_ENV", "DEBUG_PWD", "EXTRA_BUCK_OPTIONS", "IMMEDIATE_BUCK_OPTIONS")
+load("utils.bxl", "get_vs_configuration", "h")
+
+def gen_user_macros(target: bxl.ConfiguredTargetNode, vs_settings: dict, _cli_args, buck_root):
+    user_macros = []
+
+    user_macros.append(
+        h(
+            "PropertyGroup",
+            [
+                h("RepoRoot", buck_root, indent_level = 2),
+                h("ovrsource_root", buck_root, indent_level = 2),  # Keep for backward compatibility
+            ],
+            {
+                "Label": "UserMacros",
+            },
+            indent_level = 1,
+        )
+    )
+
+    for mode_file, settings in vs_settings[BY_MODES].items():
+        buck_targets_list = [target.label.raw_target()] + settings[ADDITIONAL_TARGETS]
+        user_macros.append(
+            h(
+                "PropertyGroup",
+                [
+                    h("BuckModeFile", mode_file, indent_level = 2),
+                    h("BuckTarget", " ".join([str(t) for t in buck_targets_list]), indent_level = 2),
+                    h(EXTRA_BUCK_OPTIONS, " ".join(settings[EXTRA_BUCK_OPTIONS]), indent_level = 2),
+                    h(IMMEDIATE_BUCK_OPTIONS, " ".join(settings[IMMEDIATE_BUCK_OPTIONS]), indent_level = 2),
+                    h(DEBUG_CMD, settings[DEBUG_CMD], indent_level = 2),
+                    h(DEBUG_ARGS, " ".join(settings[DEBUG_ARGS]), indent_level = 2),
+                    h(DEBUG_PWD, settings[DEBUG_PWD], indent_level = 2),
+                    h(DEBUG_ENV, ["{}={}".format(k, v) for (k, v) in settings[DEBUG_ENV].items()], indent_level = 2),
+                ],
+                {
+                    "Condition": "'$(Configuration)'=='{}'".format(get_vs_configuration(mode_file)),
+                    "Label": "UserMacrosByModes",
+                },
+                indent_level = 1,
+            ),
+        )
+
+    return user_macros
diff --git a/buck2/prelude/ide_integrations/visual_studio/gen_vcxproj.bxl b/buck2/prelude/ide_integrations/visual_studio/gen_vcxproj.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/gen_vcxproj.bxl
@@ -0,0 +1,239 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("constants.bxl", "BY_MODES")
+load("gen_user_macros.bxl", "gen_user_macros")
+load("get_attrs.bxl", "get_attrs", "get_cxx_toolchain")
+load("get_compiler_settings.bxl", "gen_compiler_settings", "materialize_compiler_settings_file")
+load("get_linker_settings.bxl", "gen_linker_settings")
+load("get_vs_settings.bxl", "get_vs_settings")
+load("utils.bxl", "get_mode_config_path", "get_project_file_path", "get_root_path_relative_to", "get_vs_configuration", "h", "log_debug", "merge")
+
+def _gen_project_configurations(project_configurations):
+    return h(
+        "ItemGroup",
+        [
+            h(
+                "ProjectConfiguration",
+                [
+                    h("Configuration", config["Configuration"], indent_level = 3),
+                    h("Platform", config["Platform"], indent_level = 3),
+                ],
+                {
+                    "Include": config["Configuration"] + "|" + config["Platform"],
+                },
+                indent_level = 2,
+            )
+            for config in project_configurations
+        ],
+        {
+            "Label": "ProjectConfigurations",
+        },
+        indent_level = 1,
+    )
+
+def _gen_configuration_type(project_configurations):
+    return h(
+        "PropertyGroup",
+        [
+            h("ConfigurationType", project_configurations[0]["ConfigurationType"], indent_level = 2),
+        ],
+        indent_level = 1,
+    )
+
+def _gen_headers(headers):
+    return h(
+        "ItemGroup",
+        [
+            h(
+                "ClInclude",
+                None,
+                {
+                    "Include": cmd_args("$(RepoRoot)\\", header, delimiter = ""),
+                },
+                indent_level = 2,
+            )
+            for header in headers
+        ],
+        indent_level = 1,
+    )
+
+def _gen_sources(sources):
+    source_entries = [
+        h(
+            "ClCompile",
+            [h("BuckObjSubTarget", object, indent_level = 3)],
+            {
+                "Include": cmd_args("$(RepoRoot)\\", source, delimiter = ""),
+            },
+            indent_level = 2,
+        )
+        for source, object in sources.items()
+    ]
+    return h("ItemGroup", source_entries, indent_level = 1)
+
+def _gen_import_mode_configs(vs_settings: dict, target):
+    imports = []
+    for mode_file, _ in vs_settings[BY_MODES].items():
+        import_config = "        <Import Condition=\"'$(Configuration)'=='{}'\" Project=\"{}mode_configs\\{}\" />\n".format(
+            get_vs_configuration(mode_file),
+            get_root_path_relative_to(target.label),
+            get_mode_config_path(mode_file),
+        )
+        imports.append(import_config)
+    return h(
+        "ImportGroup",
+        imports,
+        {
+            "Label": "PropertySheets",
+        },
+        indent_level = 1,
+    )
+
+def gen_vcxproj(target: bxl.ConfiguredTargetNode, vs_settings: dict, cli_args, buck_root):
+    log_debug("# Generating vcxproj for {}", target.label.raw_target(), log_level = cli_args.log_level)
+
+    project_configurations = _gen_project_configurations(vs_settings["ProjectConfigurations"])
+    configuration_type = _gen_configuration_type(vs_settings["ProjectConfigurations"])
+    user_macros = gen_user_macros(target, vs_settings, cli_args, buck_root)
+    headers = _gen_headers(vs_settings["Headers"])
+    sources = _gen_sources(vs_settings["Sources"])
+    compiler_settings = gen_compiler_settings(vs_settings["CompilerSettings"])
+    linker_settings = gen_linker_settings(vs_settings["LinkerSettings"])
+    import_mode_configs = _gen_import_mode_configs(vs_settings, target)
+
+    # Why are we using cmd_args instead of strings? Because bxl resolved_attrs does not support string manipulation (as of July 2024)
+    # See https://fb.workplace.com/groups/buck2users/permalink/3703593843230303/ for more context
+    vcxproj_content = cmd_args(
+        """<?xml version="1.0" encoding="utf-8"?>""",
+        """<Project DefaultTargets="Build" ToolsVersion="17.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">""",
+        project_configurations,
+        "",
+        h(
+            "PropertyGroup",
+            [h(key, value, indent_level = 2) for (key, value) in vs_settings["Globals"].items()],
+            {
+                "Label": "Globals",
+            },
+            indent_level = 1,
+        ),
+        "",
+        configuration_type,
+        "",
+        """    <ImportGroup Label="ExtensionSettings" />""",
+        "",
+        user_macros,
+        "",
+        import_mode_configs,  # mode configs must be imported early but after user_macros so that it can be overwrite
+        "",
+        """    <ItemDefinitionGroup>""",
+        compiler_settings,
+        linker_settings,
+        """    </ItemDefinitionGroup>""",
+        "",
+        headers,
+        "",
+        sources,
+        "",
+        h(
+            "Target",
+            [
+                h(
+                    "Exec",
+                    None,
+                    {
+                        "Command": "$(vs_buck_build_command)[objects][%(ClCompile.BuckObjSubTarget)] $(ExtraBuckOptions)",
+                        "WorkingDirectory": "$(RepoRoot)",
+                    },
+                    indent_level = 2,
+                ),
+            ],
+            {
+                "Condition": "'@(ClCompile)' != ''",
+                "DependsOnTargets": "SelectClCompile",
+                "Name": "ClCompile",
+            },
+            indent_level = 1,
+        ),
+        """
+    <ImportGroup Label="ExtensionTargets" />
+</Project>""",
+        delimiter = "\n",
+    )
+    return vcxproj_content
+
+def _main(bxl_ctx):
+    target_label = bxl_ctx.cli_args.target
+    target_node = bxl_ctx.configured_targets(target_label, modifiers = bxl_ctx.modifiers)
+    actions = bxl_ctx.bxl_actions().actions
+    attrs = get_attrs(target_node, bxl_ctx)
+    attrs_outfile = actions.write_json(get_project_file_path(target_node.label, ".json"), attrs, has_content_based_path = False)
+    vcxproj_artifact = actions.declare_output(get_project_file_path(target_node.label, ".vcxproj"), has_content_based_path = False)
+
+    dynamic = [attrs_outfile]
+
+    cxx_toolchain_target = get_cxx_toolchain(target_node, bxl_ctx)
+    toolchain_settings_file_out = None
+
+    if cxx_toolchain_target:
+        label = cxx_toolchain_target.label.configured_target()
+        cxx_toolchain_target_node = bxl_ctx.configured_targets(label)
+        cxx_toolchain_analysis_result = bxl_ctx.analysis(cxx_toolchain_target_node)
+        cxx_toolchain_info = cxx_toolchain_analysis_result.providers().get(CxxToolchainInfo)
+
+        toolchain_settings_file_out = materialize_compiler_settings_file(cxx_toolchain_target_node, actions, cxx_toolchain_info, bxl_ctx)
+        dynamic.append(toolchain_settings_file_out)
+
+    def f(
+        ctx,
+        artifacts,
+        outputs,
+        attrs_outfile = attrs_outfile,
+        cxx = toolchain_settings_file_out,
+        vcxproj_artifact = vcxproj_artifact,
+        target = target_node,
+        cli_args = bxl_ctx.cli_args,
+        buck_root = bxl_ctx.root(),
+    ):
+        attrs_input = artifacts[attrs_outfile].read_json()
+
+        vs_settings = get_vs_settings(target, cxx_toolchain_target, attrs_input, {}, cli_args, buck_root, ctx)
+        if cxx:
+            cxx_input = artifacts[cxx].read_json()
+            aggregated_compiler_settings = merge(
+                vs_settings["CompilerSettings"],
+                cxx_input["exported_compiler_settings"],
+            )
+            vs_settings["CompilerSettings"] = aggregated_compiler_settings
+
+        vcxproj_content = gen_vcxproj(target, vs_settings, cli_args, buck_root)
+        ctx.bxl_actions().actions.write(outputs[vcxproj_artifact].as_output(), vcxproj_content, allow_args = True)
+
+    actions.dynamic_output(
+        dynamic = dynamic,
+        inputs = [],
+        outputs = [
+            vcxproj_artifact.as_output(),
+        ],
+        f = f,
+    )
+    bxl_ctx.output.print(bxl_ctx.output.ensure(vcxproj_artifact))
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "debug_settings": cli_args.option(cli_args.json()),  # target label => debug_settings.
+        "extra_buck_options": cli_args.list(cli_args.string(), default = []),
+        "immediate_buck_options": cli_args.list(cli_args.string(), default = []),
+        "log_level": cli_args.int(default = 30),
+        "mode_files": cli_args.list(cli_args.string(), default = ["fbsource//arvr/mode/win/dev"]),
+        "mode_hashes": cli_args.option(cli_args.json()),  # mode => configuration hash.
+        "target": cli_args.target_label(),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/get_attrs.bxl b/buck2/prelude/ide_integrations/visual_studio/get_attrs.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/get_attrs.bxl
@@ -0,0 +1,233 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("utils.bxl", "log_debug")
+
+def get_attrs(target: bxl.ConfiguredTargetNode, bxl_ctx) -> dict:
+    """
+    Parse the target's resolved_attrs and return the needed entries in form of a dictionary
+
+    This should be the only api to get anything from target's attrs
+    (With one exception of querying dependencies in get_vs_settings)
+    The rest of the functions in this file are all intended to be private helper functions
+    """
+
+    log_debug("# Getting attributes for {}", target.label.raw_target(), bxl_ctx = bxl_ctx)
+
+    # TODO: Compare between resolved_attrs_lazy and resolved_attrs_eager after everything is done
+    attrs = target.resolved_attrs_lazy(bxl_ctx)
+    output = {}
+    output["buck_type"] = _get_buck_type(attrs)
+    output["srcs"] = _get_srcs(attrs)
+    output["headers"] = _get_headers(attrs)
+    output["exported_headers"] = _get_exported_headers(attrs)
+    output["header_namespace"] = _get_header_namespace(attrs)
+    output["raw_headers"] = _get_raw_headers(attrs)
+    output["header_dirs"] = _get_header_dirs(attrs)
+    output["compiler_flags"] = _get_compiler_flags(attrs)
+    output["linker_flags"] = _get_linker_flags(attrs)
+    output["exported_linker_flags"] = _get_exported_linker_flags(attrs)
+    output["preprocessor_flags"] = _get_preprocessor_flags(attrs)
+    output["exported_preprocessor_flags"] = _get_exported_preprocessor_flags(attrs)
+    output["include_directories"] = _get_include_directories(attrs)
+    output["public_include_directories"] = _get_public_include_directories(attrs)
+    output["public_system_include_directories"] = _get_public_system_include_directories(attrs)
+
+    output["args"] = _get_args(attrs)
+    output["env"] = _get_env(attrs)
+    output["exe"] = _get_exe(attrs)
+    return output
+
+def get_unified_value(attrs, common_key: str, take_values = False) -> list:
+    """
+    Return unified list of common and platform value for given keys.
+    If the attr resolve to a dictionary, the keys are taken, except if take_values is set to True, in which case
+    values are taken.
+    """
+    all_flags = []
+
+    if attrs.get(common_key):
+        common_flags = attrs.get(common_key)
+        if isinstance(common_flags, dict):
+            common_flags = common_flags.values() if take_values else common_flags
+        all_flags.extend(common_flags)
+    return all_flags
+
+def get_cxx_toolchain(target: bxl.ConfiguredTargetNode, bxl_ctx, preferred_arch: str | None = None) -> Dependency | None:
+    attrs = target.resolved_attrs_lazy(bxl_ctx)
+    cxx_toolchain = attrs.get("_cxx_toolchain")
+
+    # Handle multi-platform toolchains (e.g., Android targets) where _cxx_toolchain is a dict
+    if isinstance(cxx_toolchain, dict):
+        if not cxx_toolchain:
+            return None
+
+        # If a preferred architecture was specified, try that first
+        if preferred_arch and preferred_arch in cxx_toolchain:
+            return cxx_toolchain[preferred_arch]
+
+        # Try common fallback keys that might be present
+        common_keys = ["default", "host", "target"]
+        for key in common_keys:
+            if key in cxx_toolchain:
+                return cxx_toolchain[key]
+
+        # Final fallback: pick the first available toolchain
+        # Note: This gives a stable, deterministic result since dict iteration order
+        # is guaranteed in Python 3.7+ (which Buck2 uses)
+        return list(cxx_toolchain.values())[0]
+
+    return cxx_toolchain
+
+# TODO: Implement actual toolchain names
+def _platform_regex_match(plat, toolchain = "windows") -> bool:
+    """Return if given platform entry matches specified toolchain"""
+    if not plat:
+        return True
+    if "(?=" in plat or "(?<=" in plat:
+        # Hacky workaround that look-around isn't supported: https://github.com/rust-lang/regex/discussions/910
+        return toolchain in plat
+    if "(?!" in plat or "(?<!" in plat:
+        # Hacky workaround that look-around isn't supported: https://github.com/rust-lang/regex/discussions/910
+        return toolchain not in plat
+    return regex_match(plat, toolchain)
+
+############## headers ##############
+
+def _get_headers(attrs) -> list:
+    return get_unified_value(attrs, "headers", take_values = True)
+
+def _get_exported_headers(attrs) -> dict:
+    # TODO: support get dict without taking keys or values in get_unified_value.
+    return dict(
+        zip(
+            get_unified_value(attrs, "exported_headers", take_values = False),
+            get_unified_value(attrs, "exported_headers", take_values = True),
+        )
+    )
+
+def _get_raw_headers(attrs) -> list:
+    return attrs.get("raw_headers") or []
+
+def _get_header_dirs(attrs) -> list:
+    return attrs.get("header_dirs") or []
+
+############## include directories ##############
+
+def _get_include_directories(attrs) -> list:
+    return get_unified_value(attrs, "include_directories")
+
+def _get_public_include_directories(attrs) -> list:
+    return get_unified_value(attrs, "public_include_directories")
+
+def _get_public_system_include_directories(attrs) -> list:
+    return get_unified_value(attrs, "public_system_include_directories")
+
+############## flags ##############
+
+def _get_compiler_flags(attrs) -> list:
+    """Return list of compiler flags"""
+    return get_unified_value(attrs, "compiler_flags")
+
+def _get_linker_flags(attrs) -> list:
+    """Return list of linker flags"""
+    return get_unified_value(attrs, "linker_flags")
+
+def _get_exported_linker_flags(attrs) -> list:
+    """Return list of exported linker flags"""
+    return get_unified_value(attrs, "exported_linker_flags")
+
+def _get_preprocessor_flags(attrs) -> list:
+    """Return list of preprocessor flags"""
+    return get_unified_value(attrs, "preprocessor_flags")
+
+def _get_exported_preprocessor_flags(attrs) -> list:
+    """Return list of exported preprocessor flags"""
+    return get_unified_value(attrs, "exported_preprocessor_flags")
+
+############## others ##############
+
+def _get_srcs(attrs) -> dict:
+    """Returns list of source associated with its src property"""
+
+    # take_values as genrule target src properties can be a map of target location to source
+    # location, and this function is defined to always return the source location.
+    raw_srcs = get_unified_value(attrs, "srcs", take_values = True)
+
+    srcs = {}
+
+    for src in raw_srcs:
+        obj = None
+        if isinstance(src, Artifact):
+            obj = src.short_path + ".o"
+
+        # Flatten the list to remove any per-file compile flags, these won't
+        # get carried thru to the vcxproj file.
+        if isinstance(src, tuple):
+            src = src[0]
+
+        srcs[src] = obj
+
+    return srcs
+
+def _get_buck_type(attrs) -> str:
+    return attrs.get("buck.type")
+
+def _get_args(attrs) -> list:
+    args = attrs.get("args")
+    if args == None:
+        return []
+    elif isinstance(args, list):
+        return args
+    else:
+        # args can be non-list, e.g., ci_skycastle has dict type args. We're not generating vcxproj for them, but still need to get attrs.
+        return []
+
+def _get_env(attrs) -> dict:
+    env_raw = attrs.get("env") or {}
+    env = {}
+    for key, value in env_raw.items():
+        # Environmental variables such as PATH have to use absolute path as PWD of Visual Studio can be arbitrary.
+        env[key] = cmd_args(value, absolute_prefix = "$(RepoRoot)\\")
+    return env
+
+def _get_exe(attrs):
+    exe = None
+    platform_exe = attrs.get("platform_exe")
+    if platform_exe:
+        for p, e in platform_exe.items():
+            if _platform_regex_match(p):
+                exe = e
+                break
+
+    if not exe:
+        exe = attrs.get("exe")
+
+    if not exe:
+        return None
+    return exe.label.raw_target()
+
+def _get_header_namespace(attrs):
+    return attrs.get("header_namespace")
+
+def _main(bxl_ctx):
+    target_label = bxl_ctx.cli_args.target
+    target_node = bxl_ctx.configured_targets(target_label, modifiers = bxl_ctx.modifiers)
+    output = get_attrs(target_node, bxl_ctx)
+    action_factory = bxl_ctx.bxl_actions().actions
+    outfile = action_factory.declare_output("attrs.json", has_content_based_path = False)
+    action_factory.write_json(outfile, output, pretty = True)
+    bxl_ctx.output.print(bxl_ctx.output.ensure(outfile))
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "log_level": cli_args.int(default = 30),
+        "target": cli_args.target_label(),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/get_compiler_settings.bxl b/buck2/prelude/ide_integrations/visual_studio/get_compiler_settings.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/get_compiler_settings.bxl
@@ -0,0 +1,175 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("flags_parser_utils.bxl", "flatten_flag_lists", "get_compiler_settings_from_flags")
+load("get_attrs.bxl", "get_attrs")
+load("utils.bxl", "basename", "dedupe_by_value", "dirname", "escape_xml", "get_argsfiles_output_path", "get_project_file_path", "h", "normcase", "normpath")
+
+def _get_additional_include_directories(target: bxl.ConfiguredTargetNode, attrs: dict) -> list:
+    dirs = attrs["include_directories"]
+    dirs = [target.label.package + "/" + d for d in dirs]
+
+    # Headers shall not be directly added to additional include directories.
+
+    dirs = ["$(RepoRoot)\\" + d for d in dirs]
+    return dedupe_by_value(dirs)
+
+def _get_exported_additional_include_directories(target: bxl.ConfiguredTargetNode, attrs: dict, bxl_ctx) -> list:
+    dirs = attrs["public_include_directories"] + attrs["public_system_include_directories"]
+    dirs = [target.label.package + "/" + d for d in dirs]
+
+    # header_dirs is used in prebuilt_cxx_library (legacy Buck rule, still widely used for third-party code)
+    # e.g., //third-party/gsl:gsl
+    dirs += attrs["header_dirs"]
+
+    # TODO: handle header files with header_path_prefix
+    for name, path in attrs["exported_headers"].items():
+        header_namespace = attrs["header_namespace"]
+        if header_namespace != None:
+            if name == path:
+                # Assuming exported_header is a list and no customized export name specified.
+                # e.g.,
+                # header: arvr/projects/xrtech/resources/FaceTracker/models:FaceWaveBinaryResources  https://fburl.com/code/ee9ewpv7
+                # usage: arvr/projects/facetracking/FaceWave:OVRLipSyncCommon  https://fburl.com/code/76zx2fmw
+                name = header_namespace + "/" + basename(name)
+            else:
+                # e.g.,
+                # header: xplat/ocean/impl/ocean/base:base  https://fburl.com/code/uiyr5ay9
+                # usage: xplat/ocean/impl/ocean/math:math  https://fburl.com/code/ebtcvn44
+                name = header_namespace + "/" + name
+        name = normcase(name)
+
+        # If file path is in generated buck-out, the file will be either not available or more correct form buck-headers exists.
+        if "buck-out" not in path and path.endswith(name):
+            # e.g.,
+            # header: xplat/ocean/impl/ocean/base:base  https://fburl.com/code/uiyr5ay9
+            # usage: xplat/ocean/impl/ocean/math:math  https://fburl.com/code/ebtcvn44
+            include_dir = path.removesuffix(name)
+            if include_dir:
+                dirs.append(include_dir)
+        else:
+            # Header tree created by buck. This is the most correct form but depends on previous local build to materialize.
+            # e.g.,
+            # header: xplat/third-party/yajl:yajl  https://fburl.com/code/xqzlvuot
+            # usage: xplat/mobileconfig/FBMobileConfigCore:FBMobileConfigCore  https://fburl.com/code/p4qw1cx3
+            argsfiles_output_path = get_argsfiles_output_path(target, bxl_ctx)
+            if argsfiles_output_path:
+                dirs.append(dirname(argsfiles_output_path) + "/buck-headers")
+
+    dirs = [normpath(d) for d in dirs]
+    dirs = dedupe_by_value(dirs)
+    dirs = ["$(RepoRoot)\\" + d for d in dirs]
+
+    return dirs
+
+def _format_compiler_settings(compiler_settings: dict) -> dict:
+    # Starlark passed in reference of dict. We don't want to accidentally override values, thus creating hard copy.
+    concat_compiler_settings = dict(compiler_settings)
+
+    concat_compiler_settings["AdditionalIncludeDirectories"] = ";".join(compiler_settings["AdditionalIncludeDirectories"] + ["%(AdditionalIncludeDirectories)"])
+    concat_compiler_settings["AdditionalOptions"] = " ".join(compiler_settings["AdditionalOptions"] + ["%(AdditionalOptions)"])
+    concat_compiler_settings["PreprocessorDefinitions"] = ";".join(
+        [escape_xml(s) for s in compiler_settings["PreprocessorDefinitions"]] + ["%(PreprocessorDefinitions)"]
+    )
+    concat_compiler_settings["UndefinePreprocessorDefinitions"] = ";".join(
+        compiler_settings["UndefinePreprocessorDefinitions"] + ["%(UndefinePreprocessorDefinitions)"]
+    )
+    concat_compiler_settings["DisableSpecificWarnings"] = ";".join(compiler_settings["DisableSpecificWarnings"] + ["%(DisableSpecificWarnings)"])
+    concat_compiler_settings["ForcedIncludeFiles"] = ";".join(compiler_settings["ForcedIncludeFiles"] + ["%(ForcedIncludeFiles)"])
+    return concat_compiler_settings
+
+def get_compiler_settings(target: bxl.ConfiguredTargetNode, attrs: dict) -> dict:
+    """return private compiler settings to be written to .vcxproj for given buck target"""
+    compiler_flags = flatten_flag_lists(attrs["preprocessor_flags"] + attrs["compiler_flags"])
+    compiler_settings = get_compiler_settings_from_flags(compiler_flags)
+    compiler_settings["AdditionalIncludeDirectories"].extend(_get_additional_include_directories(target, attrs))
+
+    return compiler_settings
+
+def get_exported_compiler_settings(target: bxl.ConfiguredTargetNode, attrs: dict, bxl_ctx) -> dict:
+    """return exported compiler settings that propogate to transitive dependants"""
+    exported_compiler_flags = flatten_flag_lists(attrs["exported_preprocessor_flags"])
+    exported_compiler_settings = get_compiler_settings_from_flags(exported_compiler_flags)
+    exported_compiler_settings["AdditionalIncludeDirectories"].extend(_get_exported_additional_include_directories(target, attrs, bxl_ctx))
+
+    return exported_compiler_settings
+
+def gen_compiler_settings(compiler_settings: dict):
+    concat_compiler_settings = _format_compiler_settings(compiler_settings)
+    return h(
+        "ClCompile",
+        [h(key, value, indent_level = 3) for key, value in concat_compiler_settings.items()],
+        {
+            "Label": "CompilerSettings",
+        },
+        indent_level = 2,
+    )
+
+def materialize_compiler_settings_file(target_node, actions, cxx_toolchain_info, bxl_ctx):
+    attrs = get_attrs(target_node, bxl_ctx)
+
+    cxxflags_artifact = None
+    if cxx_toolchain_info:
+        cxxflags_artifact, _ = actions.write(
+            get_project_file_path(target_node.label, ".toolchain.cxxflags"),
+            cxx_toolchain_info.cxx_compiler_info.compiler_flags,
+            allow_args = True,
+            has_content_based_path = False,
+        )
+
+    # Use a different filename suffix for toolchain attrs to avoid conflicts with regular target attrs
+    attrs_outfile = actions.write_json(get_project_file_path(target_node.label, ".toolchain.attrs.json"), attrs, pretty = True, has_content_based_path = False)
+    out = actions.declare_output(get_project_file_path(target_node.label, ".compiler_settings.json"), has_content_based_path = False)
+
+    def f(ctx, artifacts, outputs, attrs_outfile = attrs_outfile, out = out, target = target_node):
+        attrs_input = artifacts[attrs_outfile].read_json()
+        settings = {}
+
+        if cxx_toolchain_info:
+            cxxflags = artifacts[cxxflags_artifact].read_string().splitlines()
+            exported_compiler_settings = get_compiler_settings_from_flags(cxxflags)
+        else:
+            exported_compiler_settings = get_exported_compiler_settings(target, attrs_input, ctx)
+
+        settings["compiler_settings"] = get_compiler_settings(target_node, attrs_input)
+        settings["exported_compiler_settings"] = exported_compiler_settings
+
+        ctx.bxl_actions().actions.write_json(outputs[out].as_output(), settings, pretty = True)
+
+    dynamic = [attrs_outfile]
+    if cxxflags_artifact:
+        dynamic.append(cxxflags_artifact)
+
+    actions.dynamic_output(
+        dynamic = dynamic,
+        inputs = [],
+        outputs = [out.as_output()],
+        f = f,
+    )
+
+    return out
+
+def _main(bxl_ctx):
+    target = bxl_ctx.cli_args.target
+    target_node = bxl_ctx.configured_targets(target)
+    actions = bxl_ctx.bxl_actions().actions
+
+    cxx_toolchain_analysis_result = bxl_ctx.analysis(target_node)
+    cxx_toolchain_info = cxx_toolchain_analysis_result.providers().get(CxxToolchainInfo)
+
+    out = materialize_compiler_settings_file(target_node, actions, cxx_toolchain_info, bxl_ctx)
+    bxl_ctx.output.print(bxl_ctx.output.ensure(out))
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "log_level": cli_args.int(default = 30),
+        "target": cli_args.target_label(),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/get_deps.bxl b/buck2/prelude/ide_integrations/visual_studio/get_deps.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/get_deps.bxl
@@ -0,0 +1,37 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("utils.bxl", "flatten_lists", "log_debug")
+
+def get_deps(bxl_ctx, targets: bxl.ConfiguredTargetSet) -> typing.Iterable:
+    log_debug("# Getting dependencies for {}", targets, bxl_ctx = bxl_ctx)
+
+    # -1 or large value for unbounded traversal https://fburl.com/code/7vtwh6bu
+    # Return dependencies in DFS post-order.
+    deps = bxl_ctx.cquery().deps(targets, -1, "target_deps()")
+
+    # Skip special targets that are going to cause trouble in generation and not useful in final solution.
+    block_list = {
+        "toolchains//:android-hack": True,
+    }
+
+    return [dep for dep in deps if dep.label.raw_target() not in block_list]
+
+def _main(bxl_ctx):
+    targets = flatten_lists(bxl_ctx.cli_args.target)
+    deps = get_deps(bxl_ctx, targets)
+    for t in deps:
+        bxl_ctx.output.print(t.label)
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "log_level": cli_args.int(default = 30),
+        "target": cli_args.list(cli_args.target_expr()),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/get_linker_settings.bxl b/buck2/prelude/ide_integrations/visual_studio/get_linker_settings.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/get_linker_settings.bxl
@@ -0,0 +1,77 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("flags_parser_utils.bxl", "flatten_flag_lists", "get_linker_settings_from_flags")
+load("get_attrs.bxl", "get_attrs")
+load("utils.bxl", "get_project_file_path", "h")
+
+def get_linker_settings(attrs: dict, buck_root: str) -> dict:
+    linker_flags = flatten_flag_lists(attrs["linker_flags"])
+    linker_settings = get_linker_settings_from_flags(linker_flags, buck_root)
+    if "SubSystem" not in linker_settings:
+        linker_settings["SubSystem"] = "CONSOLE"
+    return linker_settings
+
+def get_exported_linker_settings(attrs: dict, buck_root: str) -> dict:
+    exported_linker_flags = flatten_flag_lists(attrs["exported_linker_flags"])
+    exported_linker_settings = get_linker_settings_from_flags(exported_linker_flags, buck_root)
+    return exported_linker_settings
+
+def _format_linker_settings(linker_settings: dict) -> dict:
+    # Starlark passed in reference of dict. We don't want to accidentally override values, thus creating hard copy.
+    concat_linker_settings = dict(linker_settings)
+    concat_linker_settings["AdditionalLibraryDirectories"] = ";".join(linker_settings["AdditionalLibraryDirectories"] + ["%(AdditionalLibraryDirectories)"])
+    concat_linker_settings["AdditionalOptions"] = " ".join(linker_settings["AdditionalOptions"] + ["%(AdditionalOptions)"])
+    concat_linker_settings["AdditionalDependencies"] = ";".join(linker_settings["AdditionalDependencies"] + ["%(AdditionalDependencies)"])
+    concat_linker_settings["IgnoreDefaultLibraryNames"] = ";".join(linker_settings["IgnoreDefaultLibraryNames"] + ["%(IgnoreDefaultLibraryNames)"])
+    if "ForceSymbolReferences" in linker_settings:
+        concat_linker_settings["ForceSymbolReferences"] = ";".join(linker_settings["ForceSymbolReferences"] + ["%(ForceSymbolReferences)"])
+    return concat_linker_settings
+
+def gen_linker_settings(linker_settings: dict):
+    concat_linker_settings = _format_linker_settings(linker_settings)
+    return h(
+        "Link",
+        [h(key, value, indent_level = 3) for key, value in concat_linker_settings.items()],
+        {
+            "Label": "LinkerSettings",
+        },
+        indent_level = 2,
+    )
+
+def _main(bxl_ctx):
+    target = bxl_ctx.cli_args.target
+    target_node = bxl_ctx.configured_targets(target)
+    actions = bxl_ctx.bxl_actions().actions
+    attrs = get_attrs(target_node, bxl_ctx)
+    attrs_outfile = actions.write_json(get_project_file_path(target_node.label, ".json"), attrs, has_content_based_path = False)
+    out = actions.declare_output(get_project_file_path(target_node.label, ".out"), has_content_based_path = False)
+
+    def f(ctx, artifacts, outputs, attrs_outfile = attrs_outfile, out = out, buck_root = bxl_ctx.root()):
+        attrs_input = artifacts[attrs_outfile].read_json()
+        settings = {}
+        settings["linker_settings"] = get_linker_settings(attrs_input, buck_root)
+        settings["exported_linker_settings"] = get_exported_linker_settings(attrs_input, buck_root)
+
+        ctx.bxl_actions().actions.write_json(outputs[out].as_output(), settings)
+
+    actions.dynamic_output(
+        dynamic = [attrs_outfile],
+        inputs = [],
+        outputs = [out.as_output()],
+        f = f,
+    )
+    bxl_ctx.output.print(bxl_ctx.output.ensure(out).abs_path())
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "log_level": cli_args.int(default = 30),
+        "target": cli_args.target_label(),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/get_mode_hashes.bxl b/buck2/prelude/ide_integrations/visual_studio/get_mode_hashes.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/get_mode_hashes.bxl
@@ -0,0 +1,28 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _main(bxl_ctx):
+    configured_targets = bxl_ctx.configured_targets(bxl_ctx.cli_args.target, modifiers = bxl_ctx.modifiers)
+    output_json = {}
+    for target in configured_targets:
+        config = str(target.label.config()).split("#")
+        if len(config) == 2:
+            config_hash = config[1]
+            output_json[str(target.label.raw_target())] = config_hash
+
+    bxl_ctx.output.print(output_json)
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "target": cli_args.list(
+            cli_args.target_label(),
+            doc = "Buck target(s) to look up the mode hash for the current mode",
+        ),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/get_vs_settings.bxl b/buck2/prelude/ide_integrations/visual_studio/get_vs_settings.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/get_vs_settings.bxl
@@ -0,0 +1,314 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("constants.bxl", "ADDITIONAL_TARGETS", "BY_MODES", "DEBUG_ARGS", "DEBUG_CMD", "DEBUG_ENV", "DEBUG_PWD", "EXTRA_BUCK_OPTIONS", "IMMEDIATE_BUCK_OPTIONS")
+load("get_attrs.bxl", "get_attrs", "get_cxx_toolchain", "get_unified_value")
+load("get_compiler_settings.bxl", "get_compiler_settings", "get_exported_compiler_settings")
+load("get_linker_settings.bxl", "get_exported_linker_settings", "get_linker_settings")
+load(
+    "utils.bxl",
+    "dedupe_by_value",
+    "dirname",
+    "flatten_lists",
+    "gen_guid",
+    "get_output_path",
+    "get_project_file_path",
+    "get_vs_configuration",
+    "infer_settings_by_modes",
+    "log_debug",
+    "log_warn",
+    "merge",
+    "suffix",
+    "translate_content_based_path",
+)
+
+def _get_application_type_and_platform(mode_file):
+    if "android" in mode_file:
+        return "Android", "ARM64"
+
+    # Windows Desktop application doesn't set ApplicationType https://learn.microsoft.com/en-us/visualstudio/extensibility/visual-cpp-project-extensibility?view=vs-2022
+    return None, "x64"
+
+# List of options: https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.vcproject.configurationtypes?view=visualstudiosdk-2022
+def _get_vs_configuration_type(buck_type):
+    if buck_type.endswith("_library"):
+        return "DynamicLibrary"
+    elif buck_type.endswith("_binary"):
+        return "Application"
+
+    return "DynamicLibrary"
+
+def _get_all_header_files(attrs: dict):
+    header_list = attrs["headers"] + attrs["exported_headers"].values() + attrs["raw_headers"]
+    return dedupe_by_value(header_list)
+
+# Buck target can have same file declared in both headers and srcs and buck will work without any problem,
+# while VS will error out: The item "xxx" already exists under the filter "".
+# e.g., fbsource//xplat/QNNPACK:operators
+def _get_headers_and_sources(attrs):
+    headers_dict = {h: True for h in _get_all_header_files(attrs)}
+    sources_dict = attrs["srcs"]
+
+    def is_header(filename):
+        return suffix(filename) in ["h", "hh", "hpp", "hxx", "hm", "inl", "inc", "ipp", "xsd"]
+
+    headers_list = [h for h in headers_dict if h not in sources_dict or is_header(h)]
+    sources_dict = {s: o for s, o in sources_dict.items() if s not in headers_dict or not is_header(s)}
+    return headers_list, sources_dict
+
+def _unescape_arg(arg):
+    if arg.startswith("\\-\\-"):
+        return "--" + arg[4:]
+    if arg.startswith("\\-"):
+        return "-" + arg[2:]
+    return arg
+
+def _get_debug_settings(target: bxl.ConfiguredTargetNode, attrs: dict, attrs_lazy, vs_settings_dict: dict, cli_args, bxl_ctx):
+    default_mode_file = cli_args.mode_files[0]
+    debug_settings = {
+        DEBUG_CMD: get_output_path(target, bxl_ctx),
+        DEBUG_ARGS: flatten_lists(attrs["args"]),
+        DEBUG_PWD: "",
+        DEBUG_ENV: {key: ";".join(value_list) for (key, value_list) in attrs["env"].items()},
+        # When dependency is referenced in [exe] subtarget form, PDB is not automatically materialized and debugging will not be able to load symbols nor stop at breakpoints.
+        # See T197712426 and D56372580. Add additional full buck targets to force buck to build/materialize PDBs to make debugging work.
+        ADDITIONAL_TARGETS: [],
+        # Unescape option prefix.
+        EXTRA_BUCK_OPTIONS: [_unescape_arg(o) for o in cli_args.extra_buck_options],
+        IMMEDIATE_BUCK_OPTIONS: [_unescape_arg(o) for o in cli_args.immediate_buck_options],
+    }
+
+    # TODO(zhaopuwang): I think target.label is messed up because of the hash change. Might want to use raw target label instead
+    # to avoid the "Failed to infer debug settings for command_alias target" errors.
+    if attrs["buck_type"] == "alias":
+        actual_target_label = attrs_lazy.get("actual").label.configured_target()
+        actual_target_debug_settings = vs_settings_dict[actual_target_label][BY_MODES][default_mode_file]
+        debug_settings = {key: actual_target_debug_settings[key] for key in debug_settings}
+    elif attrs["buck_type"] == "command_alias" and target.label.name.endswith("_oxx_runner"):
+        # Replicate oxx_runner as it invokes base binary via child process which Visual Studio cannot debug into. https://fburl.com/code/i1pkehjo
+        base_binary_target = bxl_ctx.configured_targets(
+            target.label.cell + "//" + target.label.package + ":" + target.label.name.removesuffix("_oxx_runner"),
+            modifiers = bxl_ctx.modifiers,
+        )
+        if base_binary_target.label in vs_settings_dict:
+            debug_settings[DEBUG_CMD] = vs_settings_dict[base_binary_target.label][BY_MODES][default_mode_file][DEBUG_CMD]
+            debug_settings[ADDITIONAL_TARGETS] += [base_binary_target.label.raw_target()]
+        else:
+            log_warn("Failed to infer debug settings for command_alias target ({}).", target.label)
+        oxx_runner_path = []
+        for key, value in debug_settings[DEBUG_ENV].items():
+            if key == "BUCK_EXTRA_LIB_SEARCH_PATH_COUNT" or not key.startswith("BUCK_EXTRA_LIB_SEARCH_PATH_"):
+                continue
+            for path in value.split(";"):
+                if suffix(path) in ["dll", "pdb"]:
+                    path = dirname(path, separator = "\\")
+                if path:
+                    oxx_runner_path.append(path)
+        if oxx_runner_path:
+            debug_settings[DEBUG_ENV].setdefault("PATH", "%PATH%")
+            debug_settings[DEBUG_ENV]["PATH"] = ";".join(oxx_runner_path) + ";" + debug_settings[DEBUG_ENV]["PATH"]
+    elif attrs["buck_type"] == "command_alias" and attrs["exe"] == "fbsource//arvr/tools/buck:launcher":
+        # Replicate launcher behavior as it launches binary via child process which Visual Studio cannot debug into. https://fburl.com/code/sb7e6zi7
+        exe_path = debug_settings[DEBUG_ARGS][0]
+
+        # Infer config based path as content based path varies after local changes.
+        exe_path = translate_content_based_path(exe_path, target.label, cli_args)
+        debug_settings[DEBUG_CMD] = "$(RepoRoot)\\" + exe_path
+        debug_settings[DEBUG_PWD] = "$(RepoRoot)\\" + dirname(exe_path, separator = "\\")
+        debug_settings[DEBUG_ARGS].pop(0)
+    elif attrs["buck_type"] == "command_alias" and attrs["exe"]:
+        # Replicate generic command_alias as buck launches exe binary via child process which Visual Studio cannot debug into.
+        exe_target = bxl_ctx.configured_targets(attrs["exe"], modifiers = bxl_ctx.modifiers)
+        if exe_target.label in vs_settings_dict:
+            debug_settings[DEBUG_CMD] = vs_settings_dict[exe_target.label][BY_MODES][default_mode_file][DEBUG_CMD]
+            debug_settings[DEBUG_ENV].update(vs_settings_dict[exe_target.label][BY_MODES][default_mode_file][DEBUG_ENV])
+            debug_settings[ADDITIONAL_TARGETS] += vs_settings_dict[exe_target.label][BY_MODES][default_mode_file][ADDITIONAL_TARGETS]
+        else:
+            log_warn("Failed to infer debug settings for command_alias target ({}).", target.label)
+    elif attrs["buck_type"] == "cxx_test" and "BUCK_BASE_BINARY" in attrs["env"]:
+        test_binary_path = attrs["env"]["BUCK_BASE_BINARY"][0]
+        debug_settings[DEBUG_CMD] = test_binary_path
+    elif attrs["buck_type"] == "cxx_test" and "AVATAR_LAUNCHER_TARGET" in attrs["env"]:
+        # Replicate Avatar launcher script https://fburl.com/code/wylf2zjx
+        test_binary_path = attrs["env"]["AVATAR_LAUNCHER_TARGET"][0]
+        debug_settings[DEBUG_CMD] = test_binary_path
+        debug_settings[DEBUG_PWD] = dirname(test_binary_path, separator = "\\")
+
+    return debug_settings
+
+def get_basic_vs_settings(target: bxl.ConfiguredTargetNode, cli_args):
+    mode_files = cli_args.mode_files
+
+    application_type, platform = _get_application_type_and_platform(mode_files[0])
+
+    basic_vs_settings = {}
+
+    basic_vs_settings["Globals"] = {
+        "ProjectGuid": gen_guid(str(target.label)),
+    }
+    if application_type == "Android":
+        basic_vs_settings["Globals"].update({
+            "ApplicationType": "Android",
+            # Find latest ApplicationTypeRevision at $(VCTargetsPath)/Application Type/Android/.
+            "ApplicationTypeRevision": "3.0",
+        })
+
+    basic_vs_settings["ProjectConfigurations"] = [
+        {
+            "Configuration": get_vs_configuration(m),
+            "Platform": platform,
+        }
+        for m in mode_files
+    ]
+
+    return basic_vs_settings
+
+def get_vs_settings_for_toolchain(target: bxl.ConfiguredTargetNode, compiler_settings: dict, cli_args):
+    log_debug("# Getting VS settings for toolchain {}", target.label.raw_target(), log_level = cli_args.log_level)
+
+    vs_settings = get_basic_vs_settings(target, cli_args)
+
+    vs_settings["Headers"] = []
+    vs_settings["Sources"] = {}
+
+    vs_settings["ProjectConfigurations"] = []
+
+    vs_settings["CompilerSettings"] = {}
+    vs_settings["ExportedCompilerSettings"] = compiler_settings["exported_compiler_settings"]
+
+    vs_settings["LinkerSettings"] = {}
+    vs_settings["ExportedLinkerSettings"] = {}
+
+    return vs_settings
+
+def get_vs_settings(target: bxl.ConfiguredTargetNode, toolchain, attrs: dict, vs_settings_dict: dict, cli_args, buck_root, bxl_ctx):
+    log_debug("# Getting VS settings for {}", target.label.raw_target(), log_level = cli_args.log_level)
+    mode_files = cli_args.mode_files
+
+    vs_settings = get_basic_vs_settings(target, cli_args)
+
+    vs_settings["Headers"], vs_settings["Sources"] = _get_headers_and_sources(attrs)
+
+    configuration_type = _get_vs_configuration_type(attrs["buck_type"])
+    for i in range(len(mode_files)):
+        vs_settings["ProjectConfigurations"][i].update({
+            "ConfigurationType": configuration_type,
+        })
+
+    attrs_lazy = target.resolved_attrs_lazy(bxl_ctx)
+
+    # NB: We want to keep dep label as a label type to find rel path, instead of using strings like the rest of attrs
+    deps = get_unified_value(attrs_lazy, "deps")
+    deps = flatten_lists([d.values() if isinstance(d, dict) else d for d in deps])
+    exported_deps = get_unified_value(attrs_lazy, "exported_deps")
+    exported_deps = flatten_lists([d.values() if isinstance(d, dict) else d for d in exported_deps])
+    if attrs["buck_type"] == "alias":
+        exported_deps.append(attrs_lazy.get("actual"))
+    if attrs_lazy.get("reexport_all_header_dependencies"):
+        # Turn all normal dependencies to exported dependencies so that dependents on this target can find headers of transitive dependencies.
+        # Might bring in additional exported dependencies, but does the job.
+        # e.g., fbsource//arvr/projects/hsr/libraries/common/tooling/code_gen:idl_serializer
+        exported_deps.extend(deps)
+        deps = []
+
+    # NB: Some rules (e.g., xplugins_binary_direct_deps in
+    # tools/build_defs/xplugins/rules/binary_direct_deps.bzl) define `deps` as
+    # `attrs.list(attrs.label())` rather than `attrs.list(attrs.dep())`. In that
+    # case, items in `deps`/`exported_deps` are already `Label`s instead of
+    # `Dependency` objects (which have `.label`). Normalize both shapes here.
+    deps = [(d.label if isinstance(d, Dependency) else d).configured_target() for d in deps]  # list[configured_target_label]
+    exported_deps = [(d.label if isinstance(d, Dependency) else d).configured_target() for d in exported_deps]  # list[configured_target_label]
+
+    # NB: We can safely assume that dependencies have been processed before this loop as cquery_ctx.deps return dependencies tree in post-order.
+    aggregated_exported_compiler_settings = {}
+    aggregated_exported_linker_settings = {}
+    for dep in exported_deps:
+        aggregated_exported_compiler_settings = merge(
+            aggregated_exported_compiler_settings,
+            vs_settings_dict.get(dep, {}).get("ExportedCompilerSettings", {}),
+        )
+        aggregated_exported_linker_settings = merge(
+            aggregated_exported_linker_settings,
+            vs_settings_dict.get(dep, {}).get("ExportedLinkerSettings", {}),
+        )
+    aggregated_exported_compiler_settings = merge(aggregated_exported_compiler_settings, get_exported_compiler_settings(target, attrs, bxl_ctx))
+    vs_settings["ExportedCompilerSettings"] = aggregated_exported_compiler_settings
+    aggregated_exported_linker_settings = merge(aggregated_exported_linker_settings, get_exported_linker_settings(attrs, buck_root))
+    vs_settings["ExportedLinkerSettings"] = aggregated_exported_linker_settings
+
+    # Exported settings are also applicable to current target.
+    aggregated_private_compiler_settings = merge({}, aggregated_exported_compiler_settings)
+    aggregated_private_linker_settings = merge({}, aggregated_exported_linker_settings)
+    for dep in deps:
+        aggregated_private_compiler_settings = merge(
+            aggregated_private_compiler_settings,
+            vs_settings_dict.get(dep, {}).get("ExportedCompilerSettings", {}),
+        )
+        aggregated_private_linker_settings = merge(
+            aggregated_private_linker_settings,
+            vs_settings_dict.get(dep, {}).get("ExportedLinkerSettings", {}),
+        )
+
+    if toolchain:
+        toolchain_compiler_settings = vs_settings_dict.get(toolchain.label, {}).get("ExportedCompilerSettings", {})
+        aggregated_private_compiler_settings = merge(aggregated_private_compiler_settings, toolchain_compiler_settings)
+
+    vs_settings["CompilerSettings"] = merge(
+        aggregated_private_compiler_settings,
+        get_compiler_settings(target, attrs),
+    )
+    vs_settings["LinkerSettings"] = merge(
+        aggregated_private_linker_settings,
+        get_linker_settings(attrs, buck_root),
+    )
+
+    debug_settings = _get_debug_settings(target, attrs, attrs_lazy, vs_settings_dict, cli_args, bxl_ctx)
+    debug_settings_by_modes = infer_settings_by_modes(str(target.label.raw_target()), debug_settings, cli_args.mode_files, cli_args.mode_hashes)
+    debug_settings_overrides = (cli_args.debug_settings or {}).get(str(target.label.raw_target()), {})
+    debug_settings_by_modes_with_overrides = merge(debug_settings_by_modes, debug_settings_overrides)
+    vs_settings[BY_MODES] = debug_settings_by_modes_with_overrides
+
+    return vs_settings
+
+def _main(bxl_ctx):
+    target_label = bxl_ctx.cli_args.target
+
+    # Get the configured target with modifiers applied to ensure correct toolchain selection
+    target_node = bxl_ctx.configured_targets(target_label, modifiers = bxl_ctx.modifiers)
+    actions = bxl_ctx.bxl_actions().actions
+
+    attrs = get_attrs(target_node, bxl_ctx)
+    toolchain = get_cxx_toolchain(target_node, bxl_ctx)
+    attrs_artifact = actions.write_json(get_project_file_path(target_node.label, ".attrs.json"), attrs, pretty = True, has_content_based_path = False)
+    vs_settings_artifact = actions.declare_output(get_project_file_path(target_node.label, ".vs_settings.json"), has_content_based_path = False)
+
+    def f(ctx, artifacts, outputs, cli_args = bxl_ctx.cli_args, root = bxl_ctx.root()):
+        attrs = artifacts[attrs_artifact].read_json()
+        vs_settings = get_vs_settings(target_node, toolchain, attrs, {}, cli_args, root, ctx)
+        ctx.bxl_actions().actions.write_json(outputs[vs_settings_artifact].as_output(), vs_settings, pretty = True)
+
+    actions.dynamic_output(
+        dynamic = [attrs_artifact],
+        inputs = [],
+        outputs = [vs_settings_artifact.as_output()],
+        f = f,
+    )
+    bxl_ctx.output.print(bxl_ctx.output.ensure(vs_settings_artifact))
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "debug_settings": cli_args.option(cli_args.json()),  # target label => debug_settings.
+        "extra_buck_options": cli_args.list(cli_args.string(), default = []),
+        "immediate_buck_options": cli_args.list(cli_args.string(), default = []),
+        "log_level": cli_args.int(default = 30),
+        "mode_files": cli_args.list(cli_args.string(), default = ["fbsource//arvr/mode/win/dev"]),
+        "mode_hashes": cli_args.option(cli_args.json()),  # mode => configuration hash.
+        "target": cli_args.target_label(),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/main.bxl b/buck2/prelude/ide_integrations/visual_studio/main.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/main.bxl
@@ -0,0 +1,335 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//bxl:lazy.bxl", "batch_apply_lazy_catch_each")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("gen_filters.bxl", "gen_filters")
+load("gen_sln.bxl", "gen_sln")
+load("gen_vcxproj.bxl", "gen_vcxproj")
+load("get_attrs.bxl", "get_attrs", "get_cxx_toolchain")
+load("get_compiler_settings.bxl", "materialize_compiler_settings_file")
+load("get_deps.bxl", "get_deps")
+load("get_vs_settings.bxl", "get_basic_vs_settings", "get_vs_settings", "get_vs_settings_for_toolchain")
+load("utils.bxl", "basename", "get_project_file_path", "log_debug")
+
+def _match_recursive_target_types(target: bxl.ConfiguredTargetNode, recursive_target_types: list[str], bxl_ctx) -> bool:
+    for type_regex in recursive_target_types:
+        if regex_match(type_regex, target.rule_type):
+            return True
+    log_debug("Target filtered out for not matching recursive_target_types: target={}, type={}", target.label.raw_target(), target.rule_type, bxl_ctx = bxl_ctx)
+    return False
+
+def _normalize_include_exclude_pattern(pattern):
+    if pattern.startswith("//"):
+        pattern = "fbsource" + pattern
+    elif "//" not in pattern:
+        pattern = "fbsource//" + pattern
+    return pattern.removesuffix("...")
+
+def _match_include_exclude_patterns(target: bxl.ConfiguredTargetNode, exclude_patterns, include_patterns, bxl_ctx):
+    raw_target_str = str(target.label.raw_target())
+    for pattern in exclude_patterns:
+        if raw_target_str.startswith(pattern):
+            log_debug("Target filtered out for matching target_exclude_pattern: target={}, pattern={}", target.label.raw_target(), pattern, bxl_ctx = bxl_ctx)
+            return False
+    if include_patterns:
+        for pattern in include_patterns:
+            if raw_target_str.startswith(pattern):
+                return True
+        log_debug("Target filtered out for not matching target_include_pattern: target={}", target.label.raw_target(), bxl_ctx = bxl_ctx)
+        return False
+    return True
+
+def _main(bxl_ctx):
+    """
+    Q: Why are we using dynamic output and making it more complicated?
+    A:
+    There is this function bxl.ConfiguredTargetNode.resolved_attrs_lazy that will
+    return the attributes of a target node nice and clean with all the macros resolved,
+    which is exactly what we need fo VSGO.
+    However, the macros only get resolved at *write* time, which means that we can not
+    convert the attrs to string and parse them in the middle of the bxl process.
+
+    One example blocker we're seeing is that for a compiler flag like `-I$(location <target>)`
+    we want to add the resolved `$(location <target>)` to additional include directories but we
+    can't isolate the macro part from `-I`
+
+    The recommended workaround is to use dynamic output to *write* all the attributes
+    to a intermediate json file first to get all the macros resolve.
+    Then we can use a dynamic function to continue the generation progress.
+
+    References:
+    https://buck2.build/docs/api/bxl/bxl.ConfiguredTargetNode/#bxlconfiguredtargetnoderesolved_attrs_eager
+    https://fb.workplace.com/groups/buck2dev/permalink/3745100652444646/
+    https://buck2.build/docs/developers/dynamic_output/#dynamic-output
+    """
+    actions = bxl_ctx.bxl_actions().actions
+    targets = []  # list[ConfiguredTargetNode]. Configured target list from command line after target pattern expansion.
+    explicit_targets = {}  # dict[TargetLabel, True]. Explicit target list from command line, i.e., not from target pattern expansion.
+    for ulabel in bxl_ctx.cli_args.target:
+        # Add explicit cell name when it's omitted as otherwise BXL will use cell name of BXL script, i.e., prelude.
+        if bxl_ctx.cli_args.fbsource and (":" in ulabel or "..." in ulabel):
+            if "//" not in ulabel:
+                ulabel = "fbsource//" + ulabel
+            elif ulabel.startswith("//"):
+                ulabel = "fbsource" + ulabel
+
+        # Target label or alias.
+        is_explicit_target = ((":" in ulabel) and (not ulabel.endswith(":"))) or ((":" not in ulabel) and ("/" not in ulabel))
+
+        # Using bxl_ctx.configured_targets on a wildcard target label will cause all targets to fail
+        # if one of the targets is incompatible. We are using unconfigured_target_nodes_keep_going
+        # to filter out the incompatible targets first.
+        success_targets, error_map = bxl_ctx.lazy.unconfigured_target_nodes_keep_going(ulabel).resolve()
+
+        # Handle errors
+        for package_path, _ in error_map.items():
+            log_debug("Failed to configure target {}, skipping", package_path, bxl_ctx = bxl_ctx)
+
+        # Pass along modifiers as required by API to get same configuration as buck2 build.
+        # bxl_ctx.modifiers includes modifiers from both command line and mode file.
+        def configured_target_with_modifiers(target: bxl.UnconfiguredTargetNode) -> bxl.Lazy:
+            return bxl_ctx.lazy.configured_target_node(target, modifiers = bxl_ctx.modifiers)
+
+        utargets = list(success_targets)
+
+        results = batch_apply_lazy_catch_each(bxl_ctx, configured_target_with_modifiers, utargets)
+        for unode, res in zip(utargets, results):
+            if res.is_ok():
+                cnode = res.unwrap()
+                targets.append(cnode)
+                if is_explicit_target:
+                    explicit_targets[cnode.label.raw_target()] = True
+            else:
+                log_debug("Failed to configure target {}, skipping", unode, bxl_ctx = bxl_ctx)
+
+    target_set = bxl.ctarget_set(targets)
+    missing_mode_hashes = [m for m in bxl_ctx.cli_args.mode_files if m not in (bxl_ctx.cli_args.mode_hashes or {})]
+    if len(bxl_ctx.cli_args.mode_files) > 1 and missing_mode_hashes:
+        warning("Missing mode hashes for following mode files: " + str(missing_mode_hashes))
+
+    deps = get_deps(bxl_ctx, target_set)  # list[bxl.ConfiguredTargetNode]
+    # print(deps)
+
+    target_exclude_patterns = [_normalize_include_exclude_pattern(p) for p in bxl_ctx.cli_args.target_exclude_pattern]
+    target_include_patterns = [_normalize_include_exclude_pattern(p) for p in bxl_ctx.cli_args.target_include_pattern]
+
+    # Generate vcxproj only for matched targets based on rule_type/target_type, target_include_pattern, target_exclude_pattern etc
+    # to reduce number of projects in final solution and thus speedup solution loading.
+    deps_with_vcxproj = {}  # list[TargetLabel]. Targets (including dependencies) that will have vcxproj generated and show up in final solution.
+    for dep in deps:
+        if dep.label.raw_target() not in explicit_targets:
+            if not _match_recursive_target_types(dep, bxl_ctx.cli_args.recursive_target_types, bxl_ctx):
+                continue
+            if not _match_include_exclude_patterns(dep, target_exclude_patterns, target_include_patterns, bxl_ctx):
+                continue
+        deps_with_vcxproj[dep.label.raw_target()] = True
+    log_debug("Number of targets to generate vcxproj for: {}", len(deps_with_vcxproj), bxl_ctx = bxl_ctx)
+    if not deps_with_vcxproj:
+        fail(
+            "No targets selected for generation. Please check provided targets list and/or --recursive_target_types, --target_include_pattern, --target_exclude_pattern."
+        )
+
+    basic_vs_settings_list = []
+    attrs_artifact_dict = {}  # target label => attrs artifact
+    vcxproj_artifact_dict = {}  # target label => vcxproj artifact
+    filters_artifact_dict = {}  # target label => filters artifact
+    toolchain_dep_dict = {}
+    for dep in deps:
+        # Write the attrs to a json file so that all macros get resolved
+        attrs = get_attrs(dep, bxl_ctx)
+
+        # Populate the compiler settings file for this target's cxx toolchain attribute.  Normally this is just toolchains//:cxx, and we need its settings file
+        # in order to parse the flags that were specified directly to its CxxCompilerInfo provider and get include directories and defines at the toolchain
+        # level.  However, it's not enough to simply parse `toolchains//:cxx`, because this can be overridden via a number of different methods (for example,
+        # via `cxx_toolchain_override` or by passing the `_cxx_toolchain` attribute to the cxx_library rule invocation).
+        cxx_toolchain = get_cxx_toolchain(dep, bxl_ctx)
+
+        # The target may not be a cxx library or related rule, in which case there will be no cxx toolchain.
+        if cxx_toolchain:
+            cxx_toolchain_label = cxx_toolchain.label
+            cxx_toolchain_artifact = attrs_artifact_dict.get(cxx_toolchain_label, None)
+
+            # Do this lazily.  Many targets can reference the same toolchain, but don't bother trying to run analysis or create the entry for the toolchain
+            # more than once.
+            if not cxx_toolchain_artifact:
+                cxx_toolchain_target_label = cxx_toolchain.label.configured_target()
+                cxx_toolchain_target_node = bxl_ctx.configured_targets(cxx_toolchain_target_label)
+                cxx_toolchain_info = bxl_ctx.analysis(cxx_toolchain_target_node).providers().get(CxxToolchainInfo)
+                settings_file_artifact = materialize_compiler_settings_file(cxx_toolchain_target_node, actions, cxx_toolchain_info, bxl_ctx)
+                attrs_artifact_dict[cxx_toolchain_label] = settings_file_artifact
+
+                toolchain_dep_dict[cxx_toolchain_label] = (cxx_toolchain, cxx_toolchain_target_node)
+
+        attrs_outfile = actions.write_json(get_project_file_path(dep.label, ".attrs.json"), attrs, pretty = True, has_content_based_path = False)
+        attrs_artifact_dict[dep.label] = attrs_outfile
+
+        # Create the output artifacts. Contents will be written into these in the lambda function
+        if dep.label.raw_target() in deps_with_vcxproj:
+            vcxproj_artifact = actions.declare_output(get_project_file_path(dep.label, ".vcxproj"), has_content_based_path = False)
+            vcxproj_artifact_dict[dep.label] = vcxproj_artifact
+            filters_artifact = actions.declare_output(get_project_file_path(dep.label, ".vcxproj.filters"), has_content_based_path = False)
+            filters_artifact_dict[dep.label] = filters_artifact
+
+        # This vs_settings is generated OUTSIDE of dynamic output and has unresolved macros
+        # This is just for generating sln file since vs_settings_list is not available inside the lambda function
+        # Sln file doesn't need any attr that involves macro so we're good here
+        basic_vs_settings_list.append(get_basic_vs_settings(dep, bxl_ctx.cli_args))
+
+    toolchain_deps = toolchain_dep_dict.values()
+
+    # This lambda function gets executed after attrs are written into the json files and then loads them back to get resolved macro values.
+    # Params:
+    # ctx, artifacts, outputs: required params by a dynamic output lambda function(see https://buck2.build/docs/rule_authors/dynamic_dependencies/)
+    # cli_args: bxl_ctx.cli_args, this is not available inside the lambda function so we have to pass them in as param
+    # buck_root: bxl_ctx.buck_root(), same as above
+    def gen_vcxproj_files(
+        ctx,
+        artifacts,
+        outputs,
+        # additional arguments that needs binding.
+        cli_args = bxl_ctx.cli_args,
+        buck_root = bxl_ctx.root(),
+    ):
+        # Read in the attrs json file contents. target label => attrs.
+        attrs_content_dict = {dep.label: artifacts[attrs_artifact_dict[dep.label]].read_json() for dep in deps}
+
+        for dep, _ in toolchain_deps:
+            content = artifacts[attrs_artifact_dict[dep.label]].read_json()
+            attrs_content_dict[dep.label] = content
+
+        vs_settings_dict = {}  # target label => vs_settings.
+        for dep, node in toolchain_deps:
+            attrs = attrs_content_dict[dep.label]
+            vs_settings = get_vs_settings_for_toolchain(node, attrs, cli_args)
+            vs_settings_dict[dep.label] = vs_settings
+
+        for dep in deps:
+            attrs = attrs_content_dict[dep.label]
+            toolchain = get_cxx_toolchain(dep, ctx)
+            vs_settings = get_vs_settings(dep, toolchain, attrs, vs_settings_dict, cli_args, buck_root, ctx)
+            vs_settings_dict[dep.label] = vs_settings
+
+            if dep.label.raw_target() in deps_with_vcxproj:
+                vcxproj_content = gen_vcxproj(dep, vs_settings, cli_args, buck_root)
+                ctx.bxl_actions().actions.write(outputs[vcxproj_artifact_dict[dep.label]].as_output(), vcxproj_content, allow_args = True)
+                filters_content = gen_filters(vs_settings)
+                ctx.bxl_actions().actions.write(outputs[filters_artifact_dict[dep.label]].as_output(), filters_content, allow_args = True)
+
+    actions.dynamic_output(
+        dynamic = attrs_artifact_dict.values(),
+        inputs = [],
+        outputs = [artifact.as_output() for artifact in (vcxproj_artifact_dict.values() + filters_artifact_dict.values())],
+        f = gen_vcxproj_files,
+    )
+
+    if bxl_ctx.cli_args.solution_name or len(targets) > 1:
+        sln_path = (bxl_ctx.cli_args.solution_name or basename(bxl_ctx.root(), separator = "\\")) + ".sln"
+    else:
+        main_target_node = bxl_ctx.configured_targets(targets[0], modifiers = bxl_ctx.modifiers)
+        sln_path = get_project_file_path(main_target_node.label, ".sln")
+
+    # Find out indices of final targets and vs_settings pair to pass on to generate sln file.
+    deps_with_vcxproj_indices = {}
+    for idx, dep in enumerate(deps):
+        if dep.label.raw_target() in deps_with_vcxproj:
+            deps_with_vcxproj_indices[idx] = True
+    if explicit_targets:
+        startup_target_fallback = explicit_targets.keys()[0]
+    else:
+        startup_target_fallback = targets[0].label.raw_target()
+    sln_content = gen_sln(
+        [dep for (idx, dep) in enumerate(deps) if idx in deps_with_vcxproj_indices],
+        [s for (idx, s) in enumerate(basic_vs_settings_list) if idx in deps_with_vcxproj_indices],
+        explicit_targets,
+        bxl_ctx.cli_args.startup_target or startup_target_fallback,
+        bxl_ctx,
+    )
+    sln_artifact = actions.declare_output(sln_path, has_content_based_path = False)
+    actions.write(sln_artifact, sln_content)
+
+    ensured_outputs = bxl_ctx.output.ensure_multiple(vcxproj_artifact_dict.values() + filters_artifact_dict.values() + [sln_artifact])
+    if bxl_ctx.cli_args.output == "json":
+        bxl_ctx.output.print_json({
+            "projects_count": len(ensured_outputs) - 1,
+            "sln_path": ensured_outputs[-1].abs_path(),
+        })
+    else:
+        for output in ensured_outputs:
+            bxl_ctx.output.print(output)
+
+main = bxl_main(
+    impl = _main,
+    cli_args = {
+        "debug_settings": cli_args.option(
+            cli_args.json(),
+            doc = "Override target debug settings. Takes in JSON string of shape target_label => debug_settings.",
+        ),
+        "extra_buck_options": cli_args.list(
+            cli_args.string(),
+            default = [],
+            doc = "Extra options passed to buck build command of generated project(s) build settings. Escape `-` with `\\-`.",
+        ),
+        "fbsource": cli_args.bool(
+            default = False,
+            doc = "Whether to turn on fbsource specific behaviors.",
+        ),
+        "immediate_buck_options": cli_args.list(
+            cli_args.string(),
+            default = [],
+            doc = "Immediate options passed to buck build command of generated project(s) build settings. Escape `-` with `\\-`.",
+        ),
+        "log_level": cli_args.int(
+            default = 30,
+            doc = "Log level in output.",
+        ),
+        "mode_files": cli_args.list(
+            cli_args.string(),
+            default = ["fbsource//arvr/mode/win/dev"],
+            doc = "List of mode files to generate projects for.",
+        ),
+        "mode_hashes": cli_args.option(
+            cli_args.json(),
+            doc = "Hash values of mode file configurations. Takes in JSON string of shape mode_file => configuration_hash.",
+        ),
+        "output": cli_args.option(
+            cli_args.enum(["text", "json"], "text"),
+            doc = "Final result output format.",
+        ),
+        "recursive_target_types": cli_args.list(
+            cli_args.string(),
+            default = ["cxx_binary", "cxx_library", "cxx_test", "alias", "command_alias"],
+            doc = "The types of targets that will be recovered when buck expands target pattern (`...`) and transitive dependencies.",
+        ),
+        "solution_name": cli_args.option(
+            cli_args.string(),
+            doc = "Name of generated solution. Default to target name.",
+        ),
+        "startup_target": cli_args.option(
+            cli_args.target_label(),
+            doc = "Default startup target/project. Takes in buck target label. Default to first target.",
+        ),
+        # Not using target_expr() here as we need to differentiate between explicit target and target pattern.
+        "target": cli_args.list(
+            cli_args.string(),
+            doc = "Buck target(s) to generate project files for. Takes in buck target label and/or pattern.",
+        ),
+        # Not using target_expr() here as it can get extremely slow when expanding massive pattern like xplat/...
+        "target_exclude_pattern": cli_args.list(
+            cli_args.string(),
+            default = [],
+            doc = "Buck target label, pattern or path to exclude in generation.",
+        ),
+        # Not using target_expr() here as it can get extremely slow when expanding massive pattern like xplat/...
+        "target_include_pattern": cli_args.list(
+            cli_args.string(),
+            default = [],
+            doc = "Buck target label, pattern or path to include in generation only.",
+        ),
+    },
+)
diff --git a/buck2/prelude/ide_integrations/visual_studio/msvs/absolutize_path.exe b/buck2/prelude/ide_integrations/visual_studio/msvs/absolutize_path.exe
new file mode 100644
# file too large to diff: buck2/prelude/ide_integrations/visual_studio/msvs/absolutize_path.exe
diff --git a/buck2/prelude/ide_integrations/visual_studio/msvs/vs_buck_build.props b/buck2/prelude/ide_integrations/visual_studio/msvs/vs_buck_build.props
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/msvs/vs_buck_build.props
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <!--
+      Overrides for default VS targets which allow building a project with buck instead of MSBuild.
+  -->
+  <PropertyGroup>
+      <vs_buck_path>buck2</vs_buck_path>
+      <vs_buck_build_command>$(AbsolutizePathExe) --local_root $(RepoRoot) -- $(vs_buck_path) $(ImmediateBuckOptions) build @$(BuckModeFile) $(BuckConfig) $(BuckTarget)</vs_buck_build_command>
+  </PropertyGroup>
+  <Target Name="Build">
+      <Exec WorkingDirectory="$(RepoRoot)" Command="$(vs_buck_build_command) $(ExtraBuckOptions)"/>
+  </Target>
+  <Target Name="Clean">
+    <Exec WorkingDirectory="$(RepoRoot)" Command="buck2 clean @$(BuckModeFile)"/>
+  </Target>
+  <Target Name="Rebuild" DependsOnTargets="Clean;Build"/>
+  <PropertyGroup>
+    <LocalDebuggerCommand Condition="'$(LocalDebuggerCommand)'=='$(TargetPath)'">$(BuckDebuggerCommand)</LocalDebuggerCommand>
+    <LocalDebuggerWorkingDirectory Condition="'$(BuckDebuggerCommandWorkingDirectory)' != ''">$(BuckDebuggerCommandWorkingDirectory)</LocalDebuggerWorkingDirectory>
+    <LocalDebuggerCommandArguments>$(BuckDebuggerCommandArguments) $(LocalDebuggerCommandArguments)</LocalDebuggerCommandArguments>
+    <LocalDebuggerEnvironment>$(BuckDebuggerEnvironment)
+$(LocalDebuggerEnvironment)</LocalDebuggerEnvironment>
+    <!-- Allows test discovery and probably other things to work too -->
+    <TargetPath Condition="'$(BuckDebuggerCommand)'!=''">$(BuckDebuggerCommand)</TargetPath>
+  </PropertyGroup>
+</Project>
diff --git a/buck2/prelude/ide_integrations/visual_studio/ppflags.bxl b/buck2/prelude/ide_integrations/visual_studio/ppflags.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/ppflags.bxl
@@ -0,0 +1,156 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Source: https://learn.microsoft.com/en-us/visualstudio/msbuild/cl-task?view=vs-2022
+COMPILER_FLAGS_MAP = {
+    "/EHa": [("ExceptionHandling", "Async")],
+    "/EHs": [("ExceptionHandling", "SyncCThrow")],
+    "/EHsc": [("ExceptionHandling", "Sync")],
+    "/FC": [("UseFullPaths", "true")],
+    "/GF": [("StringPooling", "true")],
+    "/GF-": [("StringPooling", "false")],
+    "/GR": [("RuntimeTypeInfo", "true")],
+    "/GS": [("BufferSecurityCheck", "true")],
+    "/GS-": [("BufferSecurityCheck", "false")],
+    "/Gd": [("CallingConvention", "Cdecl")],
+    "/Gm": [("MinimalRebuild", "true")],
+    "/Gm-": [("MinimalRebuild", "false")],
+    "/Gr": [("CallingConvention", "FastCall")],
+    "/Gy": [("FunctionLevelLinking", "true")],
+    "/Gy-": [("FunctionLevelLinking", "false")],
+    "/Gz": [("CallingConvention", "StdCall")],
+    "/MD": [("RuntimeLibrary", "MultiThreadedDLL")],
+    "/MDd": [("RuntimeLibrary", "MultiThreadedDebugDLL")],
+    "/MP": [("MultiProcessorCompilation", "true")],
+    "/MT": [("RuntimeLibrary", "MultiThreaded")],
+    "/MTd": [("RuntimeLibrary", "MultiThreadedDebug")],
+    "/O0": [("Optimization", "Disabled")],
+    "/O1": [("Optimization", "MinSpace")],
+    "/O2": [("Optimization", "MaxSpeed")],
+    "/O3": [("Optimization", "Full")],
+    "/Ob0": [("InlineFunctionExpansion", "Disabled")],
+    "/Ob1": [("InlineFunctionExpansion", "OnlyExplicitInline")],
+    "/Ob2": [("InlineFunctionExpansion", "AnySuitable")],
+    "/Od": [("Optimization", "Disabled")],
+    "/Oi": [("IntrinsicFunctions", "true")],
+    "/Oi-": [("IntrinsicFunctions", "false")],
+    "/Ox": [("Optimization", "Full")],
+    "/Oy": [("OmitFramePointers", "true")],
+    "/Oy-": [("OmitFramePointers", "false")],
+    "/RTC1": [("BasicRuntimeChecks", "EnableFastChecks")],
+    "/RTCs": [("BasicRuntimeChecks", "StackFrameRuntimeCheck")],
+    "/RTCu": [("BasicRuntimeChecks", "UninitializedLocalUsageCheck")],
+    "/TP": [("CompileAs", "CompileAsCpp")],
+    "/W0": [("WarningLevel", "TurnOffAllWarnings")],
+    "/W1": [("WarningLevel", "Level1")],
+    "/W2": [("WarningLevel", "Level2")],
+    "/W3": [("WarningLevel", "Level3")],
+    "/W4": [("WarningLevel", "Level4")],
+    "/WX": [("TreatLinkerWarningAsErrors", "true")],
+    "/WX-": [("TreatLinkerWarningAsErrors", "false")],
+    "/Wall": [("WarningLevel", "EnableAllWarnings")],
+    "/Werror": [("TreatLinkerWarningAsErrors", "true")],
+    "/Z7": [("DebugInformationFormat", "OldStyle")],
+    "/ZI": [("DebugInformationFormat", "EditAndContinue")],
+    "/Zc:forScope": [("ForceConformanceInForLoopScope", "true")],
+    "/Zc:forScope-": [("ForceConformanceInForLoopScope", "false")],
+    "/Zc:wchar_t": [("TreatWChar_tAsBuiltInType", "true")],
+    "/Zc:wchar_t-": [("TreatWChar_tAsBuiltInType", "false")],
+    "/Zi": [("DebugInformationFormat", "ProgramDatabase")],
+    "/Zp4": [("StructMemberAlignment", "4Bytes")],
+    "/arch:AVX": [("EnableEnhancedInstructionSet", "AdvancedVectorExtensions")],
+    "/arch:AVX2": [("EnableEnhancedInstructionSet", "AdvancedVectorExtensions2")],
+    "/arch:AVX512": [("EnableEnhancedInstructionSet", "AdvancedVectorExtensions512")],
+    "/arch:IA32": [("EnableEnhancedInstructionSet", "NoExtensions")],
+    "/arch:SSE": [("EnableEnhancedInstructionSet", "StreamingSIMDExtensions")],
+    "/arch:SSE2": [("EnableEnhancedInstructionSet", "StreamingSIMDExtensions2")],
+    "/errorReport:none": [("ErrorReporting", "None")],
+    "/errorReport:prompt": [("ErrorReporting", "Prompt")],
+    "/errorReport:queue": [("ErrorReporting", "Queue")],
+    "/errorReport:send": [("ErrorReporting", "Send")],
+    "/fcxx-exceptions": [("ExceptionHandling", "Sync")],
+    "/fexceptions": [("ExceptionHandling", "Sync")],
+    "/ffast-math": [("FloatingPointModel", "Fast")],
+    "/fno-exceptions": [("ExceptionHandling", "false")],
+    "/fno-omit-frame-pointer": [("OmitFramePointers", "false")],
+    "/fomit-frame-pointer": [("OmitFramePointers", "true")],
+    "/fp:fast": [("FloatingPointModel", "Fast")],
+    "/fp:precise": [("FloatingPointModel", "Precise")],
+    "/fp:strict": [("FloatingPointModel", "Strict")],
+    "/frtti": [("RuntimeTypeInfo", "true")],
+    "/fstack-protector": [("BufferSecurityCheck", "true")],
+    "/fstack-protector-all": [("BufferSecurityCheck", "true")],
+    "/fstack-protector-explicit": [("BufferSecurityCheck", "true")],
+    "/fstack-protector-strong": [("BufferSecurityCheck", "true")],
+    "/mno-omit-leaf-frame-pointer": [("OmitFramePointers", "false")],
+    "/nologo": [("SuppressStartupBanner", "true")],
+    "/openmp": [("OpenMPSupport", "true")],
+}
+
+COMPILER_IGNORE_OPTIONS = [
+    "/g",
+    "/nostdinc",
+    "/nostdlib",
+    "/fdiagnostics-format=msvc",
+    "/gcodeview",
+    "/flto-visibility-public-std",
+    "/Xclang",
+    "/mfma",
+    "/mrtm",
+]
+
+# Source: https://learn.microsoft.com/en-us/visualstudio/msbuild/link-task?view=vs-2022
+LINKER_FLAGS_MAP = {
+    "/DEBUG": [("GenerateDebugInformation", "true")],
+    "/DEBUG:FASTLINK": [("GenerateDebugInformation", "true")],
+    "/DEBUG:FULL": [("GenerateDebugInformation", "true")],
+    "/DEBUG:NONE": [("GenerateDebugInformation", "false")],
+    "/DYNAMICBASE": [("RandomizedBaseAddress", "true")],
+    "/DYNAMICBASE:NO": [("RandomizedBaseAddress", "false")],
+    "/ENTRY:MAINCRTSTARTUP": [("EntryPointSymbol", "mainCRTStartup")],
+    "/G": [("GenerateDebugInformation", "true")],
+    "/INCREMENTAL": [("LinkIncremental", "true")],
+    "/INCREMENTAL:NO": [("LinkIncremental", "false")],
+    "/LTCG": [("LinkTimeCodeGeneration", "UseLinkTimeCodeGeneration")],
+    "/LTCG:PGInstrument": [("LinkTimeCodeGeneration", "PGInstrument")],
+    "/LTCG:PGOptimize": [("LinkTimeCodeGeneration", "PGOptimization")],
+    "/LTCG:PGUpdate": [("LinkTimeCodeGeneration", "PGUpdate")],
+    "/MACHINE:X64": [("TargetMachine", "MachineX64")],
+    "/MANIFEST": [("GenerateManifest", "true")],
+    "/MANIFEST:NO": [("GenerateManifest", "false")],
+    "/NXCOMPAT": [("DataExecutionPrevention", "true")],
+    "/NXCOMPAT:NO": [("DataExecutionPrevention", "false")],
+    "/OPT:ICF": [("EnableCOMDATFolding", "true")],
+    "/OPT:NOICF": [("EnableCOMDATFolding", "false")],
+    "/OPT:NOREF": [("OptimizeReferences", "false")],
+    "/OPT:REF": [("OptimizeReferences", "true")],
+    "/SAFESEH": [("ImageHasSafeExceptionHandlers", "true")],
+    "/SAFESEH:NO": [("ImageHasSafeExceptionHandlers", "false")],
+    "/SUBSYSTEM:CONSOLE": [("SubSystem", "Console")],
+    "/SUBSYSTEM:NATIVE": [("SubSystem", "Windows")],
+    "/SUBSYSTEM:WINDOWS": [("SubSystem", "Native")],
+    "/fPIE": [("RandomizedBaseAddress", "true")],
+    "/fpie": [("RandomizedBaseAddress", "true")],
+    "/pie": [("RandomizedBaseAddress", "true")],
+}
+
+# @unsorted-dict-items
+LANGUAGE_STANDARD_MAP = {
+    # stdcpp17
+    "/std:c++17": "stdcpp17",
+    "/std=gnu++17": "stdcpp17",
+    "/std=c++17": "stdcpp17",
+    # stdcpp20
+    "/std:c++20": "stdcpp20",
+    "/std=gnu++20": "stdcpp20",
+    "/std=c++20": "stdcpp20",
+    # stdcpplatest
+    "/std:c++latest": "stdcpplatest",
+    "/std=gnu++latest": "stdcpplatest",
+    "/std=c++latest": "stdcpplatest",
+}
diff --git a/buck2/prelude/ide_integrations/visual_studio/utils.bxl b/buck2/prelude/ide_integrations/visual_studio/utils.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/utils.bxl
@@ -0,0 +1,329 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# hyperscript inspired helper function to simplify creation of XML.
+# https://github.com/hyperhype/hyperscript
+def h(tag, children, attrs = {}, indent_level = 0) -> cmd_args:
+    indent = "    " * indent_level
+    if attrs:
+        attrs_list = [
+            cmd_args(
+                key,
+                '="',
+                value,
+                '"',
+                delimiter = "",
+            )
+            for key, value in attrs.items()
+        ]
+        attrs = cmd_args("", attrs_list, delimiter = " ")
+    else:
+        attrs = ""
+
+    if isinstance(children, list):
+        if len(children) == 0:
+            children = "\n"
+        else:
+            children = cmd_args(
+                "\n",
+                cmd_args(
+                    children,
+                    delimiter = "\n",
+                ),
+                "\n",
+                delimiter = "",
+            )
+        return cmd_args(
+            indent,
+            cmd_args(
+                "<",
+                tag,
+                attrs,
+                ">",
+            ),
+            children,
+            indent,
+            cmd_args(
+                "</",
+                tag,
+                ">",
+            ),
+            delimiter = "",
+        )
+    elif children == None:
+        return cmd_args(
+            indent,
+            cmd_args(
+                "<",
+                tag,
+                attrs,
+                "/>",
+            ),
+            delimiter = "",
+        )
+    else:
+        return cmd_args(
+            indent,
+            cmd_args(
+                "<",
+                tag,
+                attrs,
+                ">",
+            ),
+            children,
+            cmd_args(
+                "</",
+                tag,
+                ">",
+            ),
+            delimiter = "",
+        )
+
+# Pseudo GUID generator purely based on target label.
+# i.e., the same target label will generate the same GUID.
+def gen_guid(input):
+    sha = sha256(input).upper()
+    guid = "{{{}-{}-{}-{}-{}}}".format(sha[:8], sha[8:12], sha[12:16], sha[16:20], sha[20:32])
+    return guid
+
+def is_header(path):
+    exts = [".h", ".hpp"]
+    for e in exts:
+        if path.endswith(e):
+            return True
+    return False
+
+def partition(predicate, iterable):
+    trues = []
+    falses = []
+    for i in iterable:
+        if predicate(i):
+            trues.append(i)
+        else:
+            falses.append(i)
+    return falses, trues
+
+def get_vs_configuration(mode_file):
+    return mode_file.split("/")[-1].capitalize()
+
+def basename(path, separator = "/"):
+    chunks = path.rsplit(separator, 1)
+    return chunks[1] if len(chunks) > 1 else chunks[0]
+
+def dirname(path, separator = "/"):
+    return path.rsplit(separator, 1)[0]
+
+def normcase(path):
+    return path.replace("/", "\\")
+
+def normcase_backwards(path):
+    return path.replace("\\", "/")
+
+def normpath(path):
+    chunks = normcase(path).split("\\")
+    result = []
+    for chunk in chunks:
+        if not chunk:
+            pass
+        elif chunk == ".":
+            pass
+        elif chunk == "..":
+            result.pop()
+        else:
+            result.append(chunk)
+    return "\\".join(result)
+
+def suffix(path):
+    chunks = path.rsplit(".", 1)
+    return chunks[1] if len(chunks) > 1 else ""
+
+def get_project_file_path(target_label, extension):
+    path = target_label.cell + "/"
+    if target_label.package:
+        path = path + target_label.package + "/"
+
+    # The same target may exists under two configuration
+    config_hash = str(target_label.config()).split("#")
+    if len(config_hash) == 2:
+        config_hash = config_hash[1]
+    else:
+        # config can be unbound (https://buck2.build/docs/rule_authors/configurations/#configurationinfo-platform-analysis-and-more)
+        config_hash = "unbound_config"
+    return config_hash + "/" + path + sanitize(target_label.name) + extension
+
+def get_mode_config_path(mode_name):
+    if mode_name.startswith("//"):
+        mode_name = mode_name[2:]
+    elif mode_name.startswith("fbsource//"):
+        mode_name = mode_name[len("fbsource//") :]
+    return mode_name.replace("/", "_") + ".props"
+
+def get_root_path_relative_to(target_label):
+    # Workaround: "".split("/") returns [""], which is not expected.
+    if not target_label.package:
+        return "../../"
+
+    # + 1 for the hash layer of directory and + 1 more for cell
+    return "../" * (len(target_label.package.split("/")) + 2)
+
+def get_output_path(target_node: bxl.ConfiguredTargetNode, bxl_ctx) -> str:
+    providers = bxl_ctx.analysis(target_node).providers()
+    default_outputs = providers[DefaultInfo].default_outputs
+    if not default_outputs:
+        return ""
+
+    return get_path_without_materialization(default_outputs[0], bxl_ctx, abs = True)
+
+# Check if the input is possibly a hash string in content-based path (hacky!).
+def _is_possibly_hash(input):
+    return len(input) == 16 and all(map(lambda c: c.islower() or c.isdigit(), input.elems()))
+
+# Translate content based path to configuration based path as VS relies on stable paths to launch and debug binaries.
+def translate_content_based_path(content_based_path: str, target_label, cli_args) -> str:
+    default_mode_file = cli_args.mode_files[0]
+    default_mode_hash = cli_args.mode_hashes.get(default_mode_file) or {}
+    if target_label in default_mode_hash:
+        default_mode_hash = default_mode_hash[target_label]
+    else:
+        default_mode_hash = default_mode_hash["default"]
+
+    found_cell = False
+    found_target = False
+    skip_next = False
+    config_based_path = []
+    for component in content_based_path.split("\\"):
+        if skip_next:
+            if not _is_possibly_hash(component):
+                # Not a content-based path.
+                return content_based_path
+            skip_next = False
+
+            # Skip SHA component in content-based path.
+            continue
+
+        config_based_path += [component]
+        if (not found_cell) and component == target_label.cell:
+            found_cell = True
+            config_based_path += [default_mode_hash]
+        if (not found_target) and component.startswith("__") and component.endswith("__"):
+            found_target = True
+            skip_next = True
+
+    return "\\".join(config_based_path)
+
+def infer_settings_by_modes(target_label, settings, mode_files, mode_hashes) -> dict[str, typing.Any]:
+    if len(mode_files) == 1:
+        settings_by_modes = {mode_files[0]: settings}
+        return settings_by_modes
+
+    mode_hashes = mode_hashes or {}
+    default_mode_file = mode_files[0]
+    default_mode_hash = mode_hashes.get(default_mode_file) or {}
+    if target_label in default_mode_hash:
+        default_mode_hash = default_mode_hash[target_label]
+    else:
+        default_mode_hash = default_mode_hash["default"]
+    settings_json = json.encode(settings)
+
+    settings_by_modes = {default_mode_file: settings}
+    for mode_file in mode_files[1:]:
+        mode_hash = mode_hashes.get(mode_file) or {}
+        if target_label in mode_hash:
+            mode_hash = mode_hash[target_label]
+        else:
+            mode_hash = mode_hash["default"]
+
+        # We're ignoring the suggestion that don't rely on buck-out implementation detail here,
+        # as we have no way to get the buck-out under a different mode than current one using to run the BXL script.
+        settings_by_modes[mode_file] = json.decode(settings_json.replace(default_mode_hash, mode_hash))
+    return settings_by_modes
+
+def get_argsfiles_output_path(target_node: bxl.ConfiguredTargetNode, bxl_ctx):
+    providers = bxl_ctx.analysis(target_node).providers()
+    argsfiles_subtarget = providers[DefaultInfo].sub_targets.get("argsfiles", None)
+    if not argsfiles_subtarget:
+        return None
+    default_outputs = argsfiles_subtarget[DefaultInfo].default_outputs
+    if default_outputs:
+        return get_path_without_materialization(default_outputs[0], bxl_ctx)
+    else:
+        return None
+
+def dedupe_by_value(list):
+    # Not convert list to dict and take out keys as we want to preserve orders in list, but also deterministic.
+    uniques = []
+    map = {}
+    for item in list:
+        if item not in map:
+            uniques.append(item)
+            map[item] = True
+    return uniques
+
+# Replace problematic characters when used as filename. https://en.wikipedia.org/wiki/Filename#Problematic_characters
+def sanitize(input):
+    return input.replace("/", "_").replace(".", "_")
+
+# https://en.wikipedia.org/wiki/XML#Escaping
+# TODO: apply escape in more places.
+def escape_xml(input):
+    return input.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("'", "&apos;").replace('"', "&quot;")
+
+def flatten_lists(list_list):
+    final_list = []
+    for item in list_list:
+        if isinstance(item, list):
+            final_list += flatten_lists(item)
+        else:
+            final_list.append(item)
+    return final_list
+
+# Recursively merge list or dict.
+# - scalar value such as strings/numbers will be replaced.
+# - lists will be concatenated and deduped.
+# - dicts will be recursively merged.
+def merge(input1, input2):
+    if input1 == None:
+        return input2
+
+    if isinstance(input1, str) and isinstance(input2, str):
+        return input2
+
+    if isinstance(input1, list):
+        return {item: True for item in input1 + input2}.keys()
+
+    result = {}
+    for key, value in input1.items() + input2.items():
+        result[key] = merge(result.get(key), value)
+    return result
+
+def _log(level, msg, *args, **kwargs):
+    # There are cases when bxl_ctx or cli_args is not available such as dynamic output lambda.
+    if "log_level" in kwargs:
+        log_level = kwargs["log_level"]
+    elif "bxl_ctx" in kwargs:
+        log_level = kwargs["bxl_ctx"].cli_args.log_level
+    else:
+        log_level = 30
+
+    if level >= log_level:
+        print(msg.format(*args, **kwargs))  # buildifier: disable=print
+
+def log_debug(msg, *args, **kwargs):
+    _log(10, msg, *args, **kwargs)
+
+def log_info(msg, *args, **kwargs):
+    _log(20, msg, *args, **kwargs)
+
+def log_warn(msg, *args, **kwargs):
+    _log(30, msg, *args, **kwargs)
+
+def log_error(msg, *args, **kwargs):
+    _log(40, msg, *args, **kwargs)
+
+def log_critical(msg, *args, **kwargs):
+    _log(50, msg, *args, **kwargs)
diff --git a/buck2/prelude/ide_integrations/visual_studio/vsgo.py b/buck2/prelude/ide_integrations/visual_studio/vsgo.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/visual_studio/vsgo.py
@@ -0,0 +1,391 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import json
+import logging
+import os
+import shutil
+import subprocess
+import sys
+
+
+MODE_CONFIGS_DIR = "mode_configs"
+
+
+def is_explicit_target(target):
+    return "..." not in target and not target.endswith(":")
+
+
+def is_target_alias(target):
+    return all(symbol not in target for symbol in [":", "/", "..."])
+
+
+def get_mode_hashes(
+    sample_target,
+    explicit_targets,
+    mode_files,
+    extra_buck_options,
+    debug,
+    subprocess_cwd=None,
+):
+    # Resolve sample_target to full target label to match the BXL script output.
+    sample_target = subprocess.check_output(
+        ["buck2", "targets", sample_target], text=True, cwd=subprocess_cwd
+    ).strip()
+
+    mode_hashes = {}
+    default_mode_file = mode_files[0]
+    for mode_file in mode_files:
+        bxl_cmds = [
+            "buck2",
+        ]
+        if mode_file != default_mode_file:
+            bxl_cmds += ["--isolation-dir", "vsgo-" + mode_file.split("/")[-1]]
+        bxl_cmds += (
+            [
+                "bxl",
+                "@" + mode_file,
+                "prelude//ide_integrations/visual_studio/get_mode_hashes.bxl:main",
+            ]
+            + extra_buck_options
+            + ["--", "--target", sample_target]
+            + explicit_targets
+        )
+
+        if debug:
+            print("Running bxl command:", " ".join(bxl_cmds))
+        try:
+            output = json.loads(
+                subprocess.check_output(
+                    bxl_cmds, text=True, stderr=subprocess.PIPE, cwd=subprocess_cwd
+                )
+            )
+            # Change the key 'sample_target' to 'default' in the output JSON
+            if sample_target not in output:
+                raise Exception(
+                    "BXL script did not return sample_target in the output JSON"
+                )
+            output["default"] = output.pop(sample_target)
+
+        except subprocess.CalledProcessError as e:
+            print("\nstdout:\n" + e.stdout, file=sys.stderr)
+            print("\nstderr:\n" + e.stderr, file=sys.stderr)
+            raise
+
+        mode_hashes[mode_file] = output
+
+    return mode_hashes
+
+
+# Replace option prefix "--" with "\-\-" to avoid BXL mistakes them as arguments to BXL.
+def _escape_arg(arg):
+    if arg.startswith("--"):
+        return r"\-\-" + arg[2:]
+    if arg.startswith("-"):
+        return r"\-" + arg[1:]
+    return arg
+
+
+def gen_mode_configs(bxl_path, mode_files, fbsource, debug, subprocess_cwd=None):
+    mode_config_paths = []
+    default_mode_file = mode_files[0]
+    for mode_file in mode_files:
+        bxl_cmds = [
+            "buck2",
+        ]
+        if mode_file != default_mode_file:
+            bxl_cmds += ["--isolation-dir", "vsgo-" + mode_file.split("/")[-1]]
+        bxl_cmds += [
+            "bxl",
+            "@" + mode_file,
+            os.path.dirname(bxl_path) + "/gen_mode_configs.bxl:main",
+            "--",
+            "--mode_name",
+            mode_file,
+            "--fbsource",
+            str(fbsource).lower(),
+        ]
+        if debug:
+            print("Running BXL command:", " ".join(bxl_cmds))
+        try:
+            bxl_process = subprocess.run(
+                bxl_cmds,
+                text=True,
+                capture_output=True,
+                check=True,
+                cwd=subprocess_cwd,
+            )
+        except subprocess.CalledProcessError as e:
+            print("\nstdout:\n" + e.stdout, file=sys.stderr)
+            print("\nstderr:\n" + e.stderr, file=sys.stderr)
+            raise
+        mode_config_paths.append(bxl_process.stdout.strip())
+    return mode_config_paths
+
+
+def main(
+    targets,
+    mode_files,
+    extra_bxl_options,
+    extra_buck_options,
+    generated_folder,
+    recursive_target_types,
+    target_exclude_patterns,
+    target_include_patterns,
+    solution_name,
+    startup_target,
+    fbsource,
+    bxl_path,
+    sample_target,
+    debug,
+    subprocess_cwd=None,
+):
+    mode_configs = gen_mode_configs(
+        bxl_path, mode_files, fbsource, debug, subprocess_cwd
+    )
+
+    explicit_targets = [target for target in targets if is_explicit_target(target)]
+    mode_hashes = get_mode_hashes(
+        sample_target,
+        explicit_targets,
+        mode_files,
+        extra_bxl_options,
+        debug,
+        subprocess_cwd,
+    )
+
+    if debug:
+        print("mode_hashes:", mode_hashes)
+
+    default_mode_file = mode_files[0]
+    bxl_cmds = (
+        [
+            "buck2",
+            "bxl",
+            "@" + default_mode_file,
+        ]
+        + extra_bxl_options
+        + [
+            bxl_path + ":main",
+            "--",
+        ]
+        + ["--target"]
+        + targets
+        + ["--mode_files"]
+        + mode_files
+    )
+    if extra_buck_options:
+        # Pass extra buck options verbatim so that run/debug invokes buck using the same options beside target and mode file.
+        bxl_cmds += ["--extra_buck_options"] + [
+            _escape_arg(o) for o in extra_buck_options
+        ]
+    bxl_cmds += ["--mode_hashes", json.dumps(mode_hashes, separators=(",", ":"))]
+    if recursive_target_types:
+        bxl_cmds += ["--recursive_target_types"] + recursive_target_types
+    if target_exclude_patterns:
+        bxl_cmds += ["--target_exclude_pattern"] + target_exclude_patterns
+    if target_include_patterns:
+        bxl_cmds += ["--target_include_pattern"] + target_include_patterns
+    if solution_name:
+        bxl_cmds += ["--solution_name", solution_name]
+    if startup_target:
+        bxl_cmds += ["--startup_target", startup_target]
+    bxl_cmds += ["--output", "json"]
+    bxl_cmds += ["--fbsource", str(fbsource).lower()]
+    if debug:
+        bxl_cmds += ["--log_level", "0"]
+        print("Running BXL command:", " ".join(bxl_cmds))
+
+    # Capture both stdout and stderr to "tee" to both console and remote error logs.
+    try:
+        bxl_process = subprocess.run(
+            bxl_cmds, text=True, capture_output=True, check=True, cwd=subprocess_cwd
+        )
+    except subprocess.CalledProcessError as e:
+        print("\nstdout:\n" + e.stdout, file=sys.stderr)
+        print("\nstderr:\n" + e.stderr, file=sys.stderr)
+        raise
+    # Show potential warnings to user.
+    print(bxl_process.stderr, file=sys.stderr)
+    bxl_output = json.loads(bxl_process.stdout)
+    sln_path = bxl_output["sln_path"]
+
+    parts = sln_path.split(os.sep)
+    gen_root_index = parts.index("main.bxl")
+    # Skip the entry point (e.g. __main__)
+    gen_root_index += 1
+    # bxl now generates an extra layer of hash in the path
+    gen_root_index += 1
+    gen_root = os.sep.join(parts[: gen_root_index + 1])
+
+    os.makedirs(os.path.join(gen_root, MODE_CONFIGS_DIR), exist_ok=True)
+    for file_path in mode_configs:
+        file_name = os.path.basename(file_path)
+        destination_file_path = os.path.join(gen_root, MODE_CONFIGS_DIR, file_name)
+        shutil.copy(file_path, destination_file_path)
+
+    logging.warning(
+        "Copying generated project and solution files to final destination ..."
+    )
+    shutil.copytree(gen_root, generated_folder, dirs_exist_ok=True)
+    sln_relative_to_gen_root = os.sep.join(parts[gen_root_index + 1 :])
+    sln_path = os.path.normcase(
+        os.path.join(generated_folder, sln_relative_to_gen_root)
+    )
+    dest_sln_path = os.path.join(generated_folder, os.path.basename(sln_path))
+    shutil.move(sln_path, dest_sln_path)
+
+    return bxl_output | {"sln_path": dest_sln_path}
+
+
+DEFAULT_RECURSIVE_TARGET_TYPES = [
+    "cxx_binary",
+    "cxx_library",
+    "cxx_test",
+    "alias",
+    "command_alias",
+]
+
+if __name__ == "__main__":
+    import argparse
+
+    parser = argparse.ArgumentParser(
+        prog="vsgo",
+        description="Visual Studio project generator for buck targets",
+    )
+    parser.add_argument(
+        "targets",
+        help="""List of buck targets, aliases and/or patterns. Dependencies and transitive dependencies are automatically pulled in.
+Individual specified targets are preferred over target patterns as the latter will usually pull in unused targets which
+could potentially slow down project generation and project loading significantly. Examples:
+    1. Single fully-specified target:
+        //arvr/projects/pcsdk:OVRServer
+        (Only fully-specified targets are guaranteed to be able to link to the debugger)
+    2. target alias:
+        ovrserver
+    3. '...' target pattern (CAUTION: Using '...' in targets is not properly supported and may lead to incorrect behavior. Please consider
+using explicit targets instead. It also might bring in massive targets with recursive dependencies and result in very slow solution
+generating and loading):
+        //arvr/projects/mixedreality/...
+    4. Combinations of above:
+        ovrserver //arvr/projects/pcsdk:OVRServer
+    """,
+        nargs="*",
+        type=str,
+        default=[],
+    )
+    parser.add_argument(
+        "--target",
+        nargs="+",
+        help="alias for positional argument targets. Preferred over positional arguments",
+        default=[],
+    )
+    parser.add_argument(
+        "--mode_files",
+        nargs="+",
+        help="list of mode files (without leading `@`), which will be generated as different configurations",
+        default=[],
+    )
+    parser.add_argument(
+        "--extra_bxl_options",
+        nargs="+",
+        help="extra options when running BXL scripts during project generation",
+        default=[],
+    )
+    parser.add_argument(
+        "--extra_buck_options",
+        nargs="+",
+        help="extra options when running buck from generated project settings. Note '-' within option value needs to be escaped, e.g., `vsgo //third-party/semver:basic_example --extra_buck_options '\\-\\-out' 'C:\\open\\temp-out' '\\-\\-local-only'`",
+        default=[],
+    )
+    parser.add_argument(
+        "--generated_folder",
+        action="store",
+        help="output directory of generated projects and solutions",
+        default="generated_projects",
+    )
+    parser.add_argument(
+        "--recursive_target_types",
+        nargs="+",
+        help="the types of targets that will be recovered when target patterns ('...') are expanded and transitive dependencies are queried. Default to "
+        + str(DEFAULT_RECURSIVE_TARGET_TYPES),
+        default=DEFAULT_RECURSIVE_TARGET_TYPES,
+    )
+    parser.add_argument(
+        "--target_include_patterns",
+        nargs="+",
+        help="include target(s) only if it matches buck target pattern",
+        default=[],
+    )
+    parser.add_argument(
+        "--target_exclude_patterns",
+        nargs="+",
+        help="exclude target(s) if it matches buck target pattern",
+        default=[],
+    )
+    parser.add_argument(
+        "--solution_name",
+        action="store",
+        help="name of the generated solution",
+    )
+    parser.add_argument(
+        "--startup_target",
+        action="store",
+        help="buck target to be set as the default startup project",
+    )
+    parser.add_argument(
+        "--fbsource",
+        action="store_true",
+        help="whether to turn on fbsource specific behaviors",
+        default=False,
+    )
+    parser.add_argument(
+        "--bxl_path",
+        action="store",
+        help="path of BXL script",
+        default="prelude//ide_integrations/visual_studio/main.bxl",
+    )
+    parser.add_argument(
+        "--sample_target",
+        action="store",
+        help="sample target to build in order to get configuration hash values",
+    )
+    parser.add_argument(
+        "--debug",
+        action="store_true",
+        help="verbose output",
+        default=False,
+    )
+
+    args = parser.parse_args()
+    args.targets.extend(args.target)
+    if not args.targets:
+        parser.error(
+            "Required argument targets not found! Specify targets using either preferred `--target` option or as positional arguments."
+        )
+    if not args.mode_files:
+        parser.error("Required argument mode_files not found!")
+
+    bxl_output = main(
+        targets=args.targets,
+        mode_files=args.mode_files,
+        extra_bxl_options=args.extra_bxl_options,
+        extra_buck_options=args.extra_buck_options,
+        generated_folder=args.generated_folder,
+        recursive_target_types=args.recursive_target_types,
+        target_exclude_patterns=args.target_exclude_patterns,
+        target_include_patterns=args.target_include_patterns,
+        solution_name=args.solution_name,
+        startup_target=args.startup_target,
+        fbsource=args.fbsource,
+        bxl_path=args.bxl_path,
+        sample_target=args.sample_target,
+        debug=args.debug,
+    )
+    print("Solution generated at " + bxl_output["sln_path"])
diff --git a/buck2/prelude/ide_integrations/xcode/argsfiles.bzl b/buck2/prelude/ide_integrations/xcode/argsfiles.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/xcode/argsfiles.bzl
@@ -0,0 +1,21 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# @oss-disable[end= ]: load("@prelude//apple/meta_only:xcode_argsfiles.bzl", "get_meta_specific_xcode_arg_substitutions")
+
+def _get_meta_specific_xcode_arg_substitutions():
+    # @oss-disable[end= ]: return get_meta_specific_xcode_arg_substitutions()
+    return [] # @oss-enable
+
+XCODE_ARGSFILES_SUB_TARGET = "xcode-argsfiles"
+
+XCODE_ARG_SUBSTITUTIONS = [
+    (regex("-filter-error=.+"), "-fcolor-diagnostics"),
+    (regex("-filter-ignore=.+"), "-fcolor-diagnostics"),
+    (regex("-filter-warning=.+"), "-fcolor-diagnostics"),
+] + _get_meta_specific_xcode_arg_substitutions()
diff --git a/buck2/prelude/ide_integrations/xcode/data.bzl b/buck2/prelude/ide_integrations/xcode/data.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/xcode/data.bzl
@@ -0,0 +1,68 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+XCODE_DATA_SUB_TARGET = "xcode-data"
+_XCODE_DATA_FILE_NAME = "xcode_data.json"
+
+XcodeDataInfo = provider(
+    fields = {
+        "data": provider_field(typing.Any, default = None),  # {str: _a}
+    }
+)
+
+XcodeDataInfoKeys = struct(
+    APP_EXTENSION_DEPENDENCIES = "app_extension_dependencies",
+    ARCH = "arch",
+    ARGSFILES_BY_EXT = "argsfiles_by_ext",
+    BUNDLE_TYPE = "bundle_type",
+    CONTAINS_SWIFT_SOURCES = "contains_swift_sources",
+    DEFAULT_TARGET_PLATFORM = "default_target_platform",
+    DEPLOYMENT_VERSION = "deployment_version",
+    EXPORTED_HEADERS = "exported_headers",
+    EXTRA_XCODE_FILES = "extra_xcode_files",
+    HEADERS = "headers",
+    INFO_PLIST = "info_plist",
+    OUTPUT = "output",
+    PROCESSED_INFO_PLIST = "processed_info_plist",
+    INFO_PLIST_RELATIVE_PATH = "info_plist_relative_path",
+    PRODUCT_NAME = "product_name",
+    RULE_TYPE = "rule_type",
+    SDK = "sdk",
+    SRCS = "srcs",
+    SWIFT_VERSION = "swift_version",
+    TARGET = "target",
+    TEST_HOST_APP_BINARY = "test_host_app_binary",
+    TEST_HOST_APP_BUNDLE = "test_host_app_bundle",
+    TEST_HOST_APP_TARGET = "test_host_app_target",
+    TEST_TARGET = "test_target",
+    TEST_TYPE = "test_type",
+    XCTOOLCHAIN_BUNDLE_ID_TARGET = "xctoolchain_bundle_id_target",
+    XCTOOLCHAIN_BUNDLE_ID = "xctoolchain_bundle_id",
+    XCTOOLCHAIN_BUNDLE_TARGET = "xctoolchain_bundle_target",
+    TEST_TARGET_REFS_IN_CURRENT_TARGET = "test_target_refs_in_current_target",
+)
+
+def generate_xcode_data(
+    ctx: AnalysisContext, rule_type: str, output: Artifact | None, populate_rule_specific_attributes_func: [typing.Callable, None] = None, **kwargs
+) -> (list[DefaultInfo], XcodeDataInfo):
+    data = {
+        XcodeDataInfoKeys.RULE_TYPE: rule_type,
+        XcodeDataInfoKeys.TARGET: ctx.label,
+    }
+    if output:
+        data[XcodeDataInfoKeys.OUTPUT] = output
+
+    data[XcodeDataInfoKeys.EXTRA_XCODE_FILES] = []
+    if hasattr(ctx.attrs, "extra_xcode_files"):
+        data[XcodeDataInfoKeys.EXTRA_XCODE_FILES] = ctx.attrs.extra_xcode_files
+
+    if populate_rule_specific_attributes_func:
+        data.update(populate_rule_specific_attributes_func(ctx, **kwargs))
+
+    json_file = ctx.actions.write_json(_XCODE_DATA_FILE_NAME, data, has_content_based_path = False)
+    return [DefaultInfo(default_output = json_file)], XcodeDataInfo(data = data)
diff --git a/buck2/prelude/ide_integrations/xcode/scheme_settings.bzl b/buck2/prelude/ide_integrations/xcode/scheme_settings.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/xcode/scheme_settings.bzl
@@ -0,0 +1,12 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+XCODE_SCHEME_SETTINGS_ATTR_NAME = "xcode_scheme_settings"
+XCODE_SCHEME_SETTINGS_ATTR_TYPE = attrs.option(
+    attrs.source(), default = None, doc = "Optional settings to set on schemes when this target is represented in Xcode."
+)
diff --git a/buck2/prelude/ide_integrations/xcode/xcode_files.bzl b/buck2/prelude/ide_integrations/xcode/xcode_files.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ide_integrations/xcode/xcode_files.bzl
@@ -0,0 +1,47 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_platforms.bzl", "APPLE_PLATFORMS_KEY")
+load(
+    "@prelude//ide_integrations/xcode:data.bzl",
+    "XCODE_DATA_SUB_TARGET",
+    "XcodeDataInfoKeys",
+    "generate_xcode_data",
+)
+load("@prelude//user:rule_spec.bzl", "RuleRegistrationSpec")
+
+# A rule that exposes files to Xcode (in project generation).
+
+def _xcode_files_impl(ctx: AnalysisContext) -> list[Provider]:
+    xcode_data_default_info, xcode_data_info = generate_xcode_data(ctx, "xcode_files", None, _xcode_populate_attributes)
+
+    return [
+        DefaultInfo(
+            default_output = None,
+            sub_targets = {
+                XCODE_DATA_SUB_TARGET: xcode_data_default_info,
+            },
+        ),
+        xcode_data_info,
+    ]
+
+def _xcode_populate_attributes(ctx) -> dict[str, typing.Any]:
+    data = {XcodeDataInfoKeys.EXTRA_XCODE_FILES: ctx.attrs.files}
+    return data
+
+registration_spec = RuleRegistrationSpec(
+    name = "xcode_files",
+    impl = _xcode_files_impl,
+    attrs = {
+        "files": attrs.list(
+            attrs.option(attrs.source(allow_directory = True)), default = [], doc = """List of paths to the file or folders that should be included in Xcode."""
+        ),
+        "labels": attrs.list(attrs.string(), default = []),
+        APPLE_PLATFORMS_KEY: attrs.dict(key = attrs.string(), value = attrs.dep(), sorted = False, default = {}),
+    },
+)
diff --git a/buck2/prelude/is_buck2.bzl b/buck2/prelude/is_buck2.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/is_buck2.bzl
@@ -0,0 +1,12 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:is_buck2_internal.bzl", "yes")
+
+def is_buck2():
+    return yes == True
diff --git a/buck2/prelude/is_buck2_internal.bzl b/buck2/prelude/is_buck2_internal.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/is_buck2_internal.bzl
@@ -0,0 +1,9 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+yes = True
diff --git a/buck2/prelude/is_full_meta_repo.bzl b/buck2/prelude/is_full_meta_repo.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/is_full_meta_repo.bzl
@@ -0,0 +1,10 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def is_full_meta_repo() -> bool:
+    return read_root_config("buck2", "is_full_meta_repo", None) == "true"
diff --git a/buck2/prelude/java/class_to_srcs.bzl b/buck2/prelude/java/class_to_srcs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/class_to_srcs.bzl
@@ -0,0 +1,148 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//java:java_toolchain.bzl",
+    "JavaToolchainInfo",  # @unused Used as a type
+)
+load("@prelude//utils:argfile.bzl", "at_argfile")
+
+def _class_to_src_map_args(mapping: Artifact | None):
+    if mapping != None:
+        return cmd_args(mapping)
+    return cmd_args()
+
+JavaClassToSourceMapTset = transitive_set(
+    args_projections = {
+        "class_to_src_map": _class_to_src_map_args,
+    },
+)
+
+JavaClassToSourceMapInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "tset": provider_field(typing.Any, default = None),
+        "debuginfo": provider_field(typing.Any, default = None),
+        # Used internally in this module to aid generation of `debuginfo`.
+        "_tset_debuginfo": provider_field(typing.Any, default = None),
+    },
+)
+
+def create_class_to_source_map_info(
+    ctx: AnalysisContext, mapping: Artifact | None = None, mapping_debuginfo: Artifact | None = None, deps = [Dependency]
+) -> JavaClassToSourceMapInfo:
+    # Only generate debuginfo if the debug info tool is available.
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    tset_debuginfo = None
+    debuginfo = None
+    if java_toolchain.gen_class_to_source_map_debuginfo != None:
+        tset_debuginfo = ctx.actions.tset(
+            JavaClassToSourceMapTset,
+            value = mapping_debuginfo,
+            children = [
+                d[JavaClassToSourceMapInfo]._tset_debuginfo
+                for d in deps
+                if JavaClassToSourceMapInfo in d and d[JavaClassToSourceMapInfo]._tset_debuginfo != None
+            ],
+        )
+        debuginfo = _create_merged_debug_info(
+            actions = ctx.actions,
+            java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo],
+            tset_debuginfo = tset_debuginfo,
+            name = ctx.label.name + ".debuginfo_merged.json",
+        )
+
+    return JavaClassToSourceMapInfo(
+        _tset_debuginfo = tset_debuginfo,
+        tset = ctx.actions.tset(
+            JavaClassToSourceMapTset,
+            value = mapping,
+            children = [d[JavaClassToSourceMapInfo].tset for d in deps if JavaClassToSourceMapInfo in d],
+        ),
+        debuginfo = debuginfo,
+    )
+
+def create_class_to_source_map_from_jar(
+    actions: AnalysisActions,
+    name: str,
+    java_toolchain: JavaToolchainInfo,
+    jar: Artifact,
+    srcs: list[Artifact],
+    owner_target: str,
+    sources_jar_name: [str, None] = None,
+    debuginfo: Artifact | None = None,
+) -> (Artifact, Artifact | None):
+    output = actions.declare_output(name, has_content_based_path = True)
+    cmd = cmd_args(java_toolchain.gen_class_to_source_map[RunInfo])
+    if java_toolchain.gen_class_to_source_map_include_sourceless_compiled_packages != None:
+        for item in java_toolchain.gen_class_to_source_map_include_sourceless_compiled_packages:
+            cmd.add("-i", item)
+    cmd.add("-o", output.as_output())
+    if debuginfo != None:
+        cmd.add("--debuginfo", debuginfo)
+    cmd.add("--owner-target", owner_target)
+    cmd.add(jar)
+    cmd.add(at_argfile(actions = actions, name = "class_to_srcs_map_argsfile.txt", args = srcs, has_content_based_path = True))
+    sources_jar = None
+    if sources_jar_name:
+        sources_jar = actions.declare_output(sources_jar_name, has_content_based_path = True)
+        cmd.add("--sources_jar", sources_jar.as_output())
+    actions.run(cmd, category = "class_to_srcs_map")
+    return (output, sources_jar)
+
+def maybe_create_class_to_source_map_debuginfo(actions: AnalysisActions, name: str, java_toolchain: JavaToolchainInfo, srcs: list[Artifact]) -> Artifact | None:
+    # Only generate debuginfo if the debug info tool is available.
+    if java_toolchain.gen_class_to_source_map_debuginfo == None:
+        return None
+
+    output = actions.declare_output(name, has_content_based_path = True)
+    cmd = cmd_args(java_toolchain.gen_class_to_source_map_debuginfo[RunInfo])
+    cmd.add("gen")
+    cmd.add("-o", output.as_output())
+    cmd.add(at_argfile(actions = actions, name = "sourcefiles.txt", args = srcs))
+    actions.run(cmd, category = "class_to_srcs_map_debuginfo")
+    return output
+
+def merge_class_to_source_map_from_jar(
+    actions: AnalysisActions, name: str, java_toolchain: JavaToolchainInfo, relative_to: [CellRoot, None], deps: list[JavaClassToSourceMapInfo]
+) -> Artifact:
+    output = actions.declare_output(name, has_content_based_path = True)
+
+    tset = actions.tset(
+        JavaClassToSourceMapTset,
+        value = None,
+        children = [d.tset for d in deps],
+    )
+    class_to_source_files = tset.project_as_args("class_to_src_map")
+    mappings_file = actions.write("class_to_src_map.txt", class_to_source_files, has_content_based_path = True)
+
+    cmd = cmd_args(
+        java_toolchain.merge_class_to_source_maps[RunInfo],
+        cmd_args(output.as_output(), format = "--output={}"),
+        cmd_args(str(relative_to), format = "--relative-to={}") if relative_to != None else [],
+        ["--mappings", mappings_file],
+        hidden = class_to_source_files,
+    )
+    actions.run(cmd, category = "merge_class_to_srcs_map")
+    return output
+
+def _create_merged_debug_info(actions: AnalysisActions, java_toolchain: JavaToolchainInfo, tset_debuginfo: TransitiveSet, name: str):
+    output = actions.declare_output(name, has_content_based_path = True)
+    cmd = cmd_args(java_toolchain.gen_class_to_source_map_debuginfo[RunInfo])
+    cmd.add("merge")
+    cmd.add(cmd_args(output.as_output(), format = "-o={}"))
+
+    tset = actions.tset(
+        JavaClassToSourceMapTset,
+        children = [tset_debuginfo],
+    )
+    input_files = tset.project_as_args("class_to_src_map")
+    cmd.add(at_argfile(actions = actions, name = "debuginfo_list.txt", args = input_files, has_content_based_path = True))
+
+    actions.run(cmd, category = "merged_debuginfo")
+    return output
diff --git a/buck2/prelude/java/dex.bzl b/buck2/prelude/java/dex.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/dex.bzl
@@ -0,0 +1,103 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:dex_toolchain.bzl", "DexToolchainInfo")
+
+DexLibraryInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        # the .dex.jar file. May be None if there were not any Java classes to dex. If None, the
+        # remaining fields should be ignored.
+        "dex": provider_field(typing.Any, default = None),  # ["artifact", None]
+        # a unique string identifier for this DEX file
+        "identifier": provider_field(typing.Any, default = None),  # [str, None]
+        # the names of the .class files that went into the DEX file
+        "class_names": provider_field(typing.Any, default = None),  # ["artifact", None]
+        # resources that are referenced by the classes in this DEX file
+        "referenced_resources": provider_field(typing.Any, default = None),  # ["artifact", None]
+        # a value that estimates how much space the code represented by this object will take up in
+        # a DEX file. The units for this estimate are not important, as long as they are consistent
+        # with those used when determining how secondary DEX files should be packed.
+        "weight_estimate": provider_field(typing.Any, default = None),  # ["artifact", None]
+        # a file containing the exact method_ids_size, field_ids_size, and type_ids_size
+        # from the DEX header. Format: "<method_ref_count> <field_ref_count> <type_ref_count>"
+        # (single line). These are the actual counts that the 64K DEX limits apply to,
+        # unlike weight_estimate which is a byte-size proxy.
+        "ref_count": provider_field(typing.Any, default = None),  # ["artifact", None]
+        # a file mapping each synthetic class D8 created to the class it was synthesized from,
+        # one "<synthetic> <context>" pair per line. A synthetic must be placed in the same dex
+        # as its context class, and D8 reports the pairing because the synthetic's name is
+        # mangled in a format it does not treat as stable.
+        "synthetic_contexts": provider_field(typing.Any, default = None),  # ["artifact", None]
+    },
+)
+
+def get_dex_produced_from_java_library(
+    ctx: AnalysisContext,
+    dex_toolchain: DexToolchainInfo,
+    jar_to_dex: Artifact,
+    needs_desugar: bool = False,
+    desugar_deps: [TransitiveSetArgsProjection, None] = None,
+    weight_factor: int = 1,
+) -> DexLibraryInfo:
+    d8_cmd = cmd_args(dex_toolchain.d8_command[RunInfo])
+
+    library_path = jar_to_dex.short_path
+    prefix = "dex/{}".format(library_path)
+    output_dex_file = ctx.actions.declare_output(prefix + ".dex.jar", has_content_based_path = True)
+    d8_cmd.add(["--output-dex-file", output_dex_file.as_output()])
+
+    d8_cmd.add(["--file-to-dex", jar_to_dex])
+    d8_cmd.add(["--android-jar", dex_toolchain.android_jar])
+
+    d8_cmd.add(["--intermediate", "--no-optimize", "--force-jumbo"])
+    if not needs_desugar:
+        d8_cmd.add("--no-desugar")
+    else:
+        desugar_deps_file = ctx.actions.write(prefix + "_desugar_deps_file.txt", desugar_deps or [], has_content_based_path = True)
+        d8_cmd.add(["--classpath-files", desugar_deps_file])
+        d8_cmd.add(cmd_args(hidden = desugar_deps or []))
+
+    referenced_resources_file = ctx.actions.declare_output(prefix + "_referenced_resources.txt", has_content_based_path = True)
+    d8_cmd.add(["--referenced-resources-path", referenced_resources_file.as_output()])
+
+    weight_estimate_file = ctx.actions.declare_output(prefix + "_weight_estimate.txt", has_content_based_path = True)
+    d8_cmd.add(["--weight-estimate-path", weight_estimate_file.as_output()])
+
+    d8_cmd.add(["--weight-factor", str(weight_factor)])
+
+    class_names_file = ctx.actions.declare_output(prefix + "_class_names.txt", has_content_based_path = True)
+    d8_cmd.add(["--class-names-path", class_names_file.as_output()])
+
+    ref_count_file = ctx.actions.declare_output(prefix + "_ref_count.txt", has_content_based_path = True)
+    d8_cmd.add(["--ref-count-path", ref_count_file.as_output()])
+
+    synthetic_contexts_file = ctx.actions.declare_output(prefix + "_synthetic_contexts.txt", has_content_based_path = True)
+    d8_cmd.add(["--synthetic-contexts-path", synthetic_contexts_file.as_output()])
+
+    min_sdk_version = getattr(ctx.attrs, "_dex_min_sdk_version", None) or getattr(ctx.attrs, "min_sdk_version", None)
+    if min_sdk_version:
+        d8_cmd.add(["--min-sdk-version", str(min_sdk_version)])
+
+    identifier = "{}:{} {}".format(ctx.label.package, ctx.label.name, output_dex_file.short_path)
+    ctx.actions.run(
+        d8_cmd,
+        category = "pre_dex",
+        identifier = identifier,
+        allow_cache_upload = True,
+    )
+
+    return DexLibraryInfo(
+        dex = output_dex_file,
+        identifier = identifier,
+        class_names = class_names_file,
+        referenced_resources = referenced_resources_file,
+        weight_estimate = weight_estimate_file,
+        ref_count = ref_count_file,
+        synthetic_contexts = synthetic_contexts_file,
+    )
diff --git a/buck2/prelude/java/dex_toolchain.bzl b/buck2/prelude/java/dex_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/dex_toolchain.bzl
@@ -0,0 +1,17 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# TODO(T107163344) These should be part of the Android toolchain!
+# Move out once we have overlays.
+DexToolchainInfo = provider(
+    doc = "Dex toolchain info",
+    fields = {
+        "android_jar": provider_field(typing.Any, default = None),
+        "d8_command": provider_field(typing.Any, default = None),
+    },
+)
diff --git a/buck2/prelude/java/gwt_binary.bzl b/buck2/prelude/java/gwt_binary.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/gwt_binary.bzl
@@ -0,0 +1,65 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    ":java_providers.bzl",
+    "get_all_java_packaging_deps",
+    "get_compiling_deps_tset",
+)
+
+_GWT_COMPILER_CLASS = "com.google.gwt.dev.Compiler"
+
+def gwt_binary_impl(ctx: AnalysisContext) -> list[Provider]:
+    expect(ctx.attrs.local_workers > 0, "local workers must be greater than zero")
+
+    output = ctx.actions.declare_output("{}.zip".format(ctx.label.name), has_content_based_path = False)
+
+    # Write deploy files to separate directory so that the generated .zip is smaller
+    deploy_output = ctx.actions.declare_output("deploy", has_content_based_path = False)
+
+    module_deps_classpath = [dep.gwt_module for dep in get_all_java_packaging_deps(ctx, ctx.attrs.module_deps) if dep.gwt_module]
+    compiling_deps_tset = get_compiling_deps_tset(ctx.actions, ctx.attrs.deps)
+    deps_classpath = [dep.full_library for dep in (list(compiling_deps_tset.traverse()) if compiling_deps_tset else [])]
+
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    gwt_args = cmd_args([
+        java_toolchain.java[RunInfo],
+        "-Dgwt.normalizeTimestamps=true",
+        ctx.attrs.vm_args,
+        "-classpath",
+        cmd_args(module_deps_classpath + deps_classpath, delimiter = get_path_separator_for_exec_os(ctx)),
+        _GWT_COMPILER_CLASS,
+        "-war",
+        output.as_output(),
+        "-style",
+        ctx.attrs.style,
+        "-optimize",
+        str(ctx.attrs.optimize),
+        "-localWorkers",
+        str(ctx.attrs.local_workers),
+        "-deploy",
+        deploy_output.as_output(),
+    ])
+
+    if ctx.attrs.draft_compile:
+        gwt_args.add("-draftCompile")
+    if ctx.attrs.strict:
+        gwt_args.add("-strict")
+    gwt_args.add(ctx.attrs.experimental_args)
+    gwt_args.add(ctx.attrs.modules)
+
+    ctx.actions.run(gwt_args, category = "gwt_binary")
+
+    sub_targets = {"deploy": [DefaultInfo(default_output = deploy_output)]}
+
+    return [
+        DefaultInfo(default_output = output, sub_targets = sub_targets),
+    ]
diff --git a/buck2/prelude/java/jar_genrule.bzl b/buck2/prelude/java/jar_genrule.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/jar_genrule.bzl
@@ -0,0 +1,34 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:genrule.bzl", "process_genrule")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//utils:expect.bzl", "expect")
+
+def jar_genrule_impl(ctx: AnalysisContext) -> list[Provider]:
+    output_name = "{}.jar".format(ctx.label.name)
+    providers = process_genrule(ctx, output_name, None)
+    expect(
+        len(providers) == 1,
+        "expected exactly one provider of type DefaultInfo from {} ({})".format(ctx.label.name, providers),
+    )
+
+    default_info = providers[0]  # DefaultInfo type
+    outputs = default_info.default_outputs
+    expect(
+        len(outputs) == 1,
+        "expected exactly one output from {} ({})".format(ctx.label.name, outputs),
+    )
+    output_jar = outputs[0]
+
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    java_cmd = cmd_args(java_toolchain.java[RunInfo])
+    java_cmd.add("-jar", output_jar)
+
+    providers.append(RunInfo(args = java_cmd))
+    return providers
diff --git a/buck2/prelude/java/java.bzl b/buck2/prelude/java/java.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/java.bzl
@@ -0,0 +1,27 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java/plugins:java_annotation_processor.bzl", "java_annotation_processor_impl")
+load("@prelude//java/plugins:java_plugin.bzl", "java_plugin_impl")
+load(":gwt_binary.bzl", "gwt_binary_impl")
+load(":jar_genrule.bzl", "jar_genrule_impl")
+load(":java_binary.bzl", "java_binary_impl")
+load(":java_library.bzl", "java_library_impl")
+load(":java_test.bzl", "java_test_impl")
+load(":prebuilt_jar.bzl", "prebuilt_jar_impl")
+
+implemented_rules = {
+    "gwt_binary": gwt_binary_impl,
+    "jar_genrule": jar_genrule_impl,
+    "java_annotation_processor": java_annotation_processor_impl,
+    "java_binary": java_binary_impl,
+    "java_library": java_library_impl,
+    "java_plugin": java_plugin_impl,
+    "java_test": java_test_impl,
+    "prebuilt_jar": prebuilt_jar_impl,
+}
diff --git a/buck2/prelude/java/java_binary.bzl b/buck2/prelude/java/java_binary.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/java_binary.bzl
@@ -0,0 +1,303 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//java:proguard.bzl", "get_proguard_output")
+load("@prelude//java/utils:java_utils.bzl", "get_class_to_source_map_info", "get_classpath_subtargets")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",  # @unused used as type
+    "SharedLibraryInfo",
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+)
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    ":java_providers.bzl",
+    "create_template_info",
+    "get_compiling_deps_tset",
+    "get_java_packaging_info",
+)
+
+def _generate_script(generate_wrapper: bool, native_libs: list[SharedLibrary]) -> bool:
+    # if `generate_wrapper` is set and no native libs then it should be a wrapper script as result,
+    # otherwise fat jar will be generated (inner jar or script will be included inside a final fat jar)
+    return generate_wrapper and len(native_libs) == 0
+
+def _create_fat_jar(
+    ctx: AnalysisContext,
+    jars: cmd_args,
+    native_libs: list[SharedLibrary] = [],
+    name_prefix: str = "",
+    concat_jars: bool = False,
+    do_not_create_inner_jar: bool = True,
+    generate_wrapper: bool = False,
+    main_class: [str, None] = None,
+    append_jar: [Artifact, None] = None,
+) -> list[Artifact]:
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    extension = "sh" if _generate_script(generate_wrapper, native_libs) else "jar"
+    output = ctx.actions.declare_output("{}{}.{}".format(name_prefix, ctx.label.name, extension), has_content_based_path = False)
+
+    args = [
+        java_toolchain.fat_jar[RunInfo],
+        "--jar_builder_tool",
+        cmd_args(java_toolchain.jar_builder, delimiter = " "),
+        "--zip_scrubber_tool",
+        cmd_args(java_toolchain.zip_scrubber, delimiter = " "),
+        "--output",
+        output.as_output(),
+        "--jars_file",
+        ctx.actions.write("{}jars_file".format(name_prefix), jars, has_content_based_path = False),
+    ]
+
+    if concat_jars:
+        args += ["--concat_jars"]
+    if append_jar:
+        args += ["--append_jar", append_jar]
+
+    if native_libs:
+        expect(
+            java_toolchain.is_bootstrap_toolchain == False,
+            "Bootstrap java toolchain could not be used for java_binary() with native code.",
+        )
+        args += [
+            "--native_libs_file",
+            ctx.actions.write(
+                "{}native_libs".format(name_prefix),
+                [cmd_args([native_lib.soname.ensure_str(), native_lib.lib.output], delimiter = " ") for native_lib in native_libs],
+                has_content_based_path = False,
+            ),
+        ]
+        if do_not_create_inner_jar:
+            args += [
+                "--do_not_create_inner_jar",
+            ]
+        else:
+            args += [
+                "--fat_jar_lib",
+                java_toolchain.fat_jar_main_class_lib,
+                # fat jar's main class
+                "--fat_jar_main_class",
+                "com.facebook.buck.jvm.java.fatjar.FatJarMain",
+                # native libraries directory name. Main class expects to find libraries packed inside this directory.
+                "--fat_jar_native_libs_directory_name",
+                "nativelibs",
+            ]
+
+    if main_class:
+        args += ["--main_class", main_class]
+
+    if ctx.attrs.manifest_file:
+        args += ["--manifest", ctx.attrs.manifest_file]
+
+    build_manifest = ctx.attrs.build_manifest
+    if build_manifest:
+        args += ["--build_manifest", build_manifest]
+
+    blocklist = ctx.attrs.blocklist
+    if blocklist:
+        args += ["--blocklist", ctx.actions.write("{}blocklist_args".format(name_prefix), blocklist, has_content_based_path = False)]
+
+    if ctx.attrs.meta_inf_directory:
+        args += ["--meta_inf_directory", ctx.attrs.meta_inf_directory]
+
+    outputs = [output]
+    if generate_wrapper:
+        classpath_args_output = ctx.actions.declare_output("classpath_args", has_content_based_path = False)
+        args += [
+            "--generate_wrapper",
+            "--classpath_args_output",
+            classpath_args_output.as_output(),
+            "--java_tool",
+            java_toolchain.java[RunInfo],
+            "--script_marker_file_name",
+            "wrapper_script",
+        ]
+        outputs.append(classpath_args_output)
+
+    fat_jar_cmd = cmd_args(
+        args,
+        hidden = [jars] + [native_lib.lib.output for native_lib in native_libs],
+    )
+
+    ctx.actions.run(
+        fat_jar_cmd,
+        local_only = False,
+        category = "{}fat_jar".format(name_prefix),
+        allow_cache_upload = True,
+    )
+
+    if generate_wrapper == False:
+        expect(
+            len(outputs) == 1,
+            "expected exactly one output when creating a fat jar",
+        )
+
+    # If `generate_wrapper` is not set then the result will contain only 1 item that represent fat jar artifact.
+    # Else if `generate_wrapper` is set then the first item in the result list will be script or far jar, and the second one is for @classpath_args file
+    return outputs
+
+def _get_run_cmd(attrs: struct, script_mode: bool, main_artifact: Artifact, java_toolchain: JavaToolchainInfo) -> cmd_args:
+    if script_mode:
+        return cmd_args(["/usr/bin/env", "bash", main_artifact])
+    else:
+        return cmd_args([java_toolchain.java[RunInfo]] + attrs.java_args_for_run_info + ["-jar", main_artifact])
+
+def _get_java_tool_artifacts(java_toolchain: JavaToolchainInfo) -> list:
+    default_info = java_toolchain.java[DefaultInfo]
+    return default_info.default_outputs + default_info.other_outputs
+
+def java_binary_impl(ctx: AnalysisContext) -> list[Provider]:
+    """
+     java_binary() rule implementation
+
+    Args:
+        ctx: rule analysis context
+    Returns:
+        list of created providers (DefaultInfo and RunInfo)
+    """
+
+    if ctx.attrs._build_only_native_code:
+        return [
+            DefaultInfo(default_output = ctx.actions.write("{}/unused.jar".format(ctx.label.name), [], has_content_based_path = False)),
+            RunInfo(),
+        ]
+
+    packaging_info = get_java_packaging_info(ctx, ctx.attrs.deps, None)
+
+    first_order_deps = get_compiling_deps_tset(ctx.actions, ctx.attrs.deps)
+    first_order_libs = [dep.full_library for dep in (list(first_order_deps.traverse()) if first_order_deps else [])]
+
+    shared_library_info = merge_shared_libraries(
+        ctx.actions,
+        deps = filter(None, [x.get(SharedLibraryInfo) for x in ctx.attrs.deps]),
+    )
+    native_deps = traverse_shared_library_info(shared_library_info, transformation_provider = None)
+
+    base_dep = ctx.attrs.base_dep
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    concat_deps = ctx.attrs.concat_deps
+    need_to_generate_wrapper = ctx.attrs.generate_wrapper == True
+    do_not_create_inner_jar = ctx.attrs.do_not_create_inner_jar == True
+    packaging_deps = list(packaging_info.packaging_deps.traverse())
+    incremental_target_prefix = ctx.attrs.incremental_target_prefix
+    main_class = ctx.attrs.main_class
+    packaging_dep_infos = {dep.jar: dep.label.raw_target() for dep in packaging_deps if dep and dep.jar}
+
+    other_outputs = []
+
+    if ctx.attrs.proguard_config:
+        java_base = [java_toolchain.java_base_jar] if java_toolchain.java_base_jar else []
+        library_jars = ctx.attrs.proguard_library_jars + java_base
+        proguard_output = get_proguard_output(
+            ctx = ctx,
+            input_jars = packaging_dep_infos,
+            java_packaging_deps = packaging_deps,
+            additional_proguard_configs = [],
+            additional_jars = library_jars,
+            sdk_proguard_config_mode = None,
+            sdk_proguard_config = None,
+            sdk_optimized_proguard_config = None,
+            proguard_jar = java_toolchain.proguard_jar,
+            skip_proguard = False,
+        )
+        packaging_dep_infos = proguard_output.jars_to_owners
+    packaging_jar_args = cmd_args(packaging_dep_infos.keys())
+
+    if incremental_target_prefix:
+        base_jar = None
+        incremental_jars = []
+        dependency_jars = []
+
+        # separate jars in groups
+        for dep_jar, owner in packaging_dep_infos.items():
+            # lookup for the base jar that can be used to append all other dependencies
+            if base_dep and owner == base_dep.label.raw_target():
+                expect(
+                    base_jar == None,
+                    "JAR can only have one base JAR file.",
+                )
+                base_jar = dep_jar
+            elif str(owner).startswith(incremental_target_prefix):
+                # if it's not a base jar, it can be an incremental jar or dependency only
+                incremental_jars.append(dep_jar)
+            else:
+                dependency_jars.append(dep_jar)
+
+        # collect incremental targets
+        expect(
+            len(incremental_jars) > 0,
+            "No incremental dependencies found that starts with {}.".format(incremental_target_prefix),
+        )
+
+        # generate intermediary jar only with dependencies
+        deps_outputs = _create_fat_jar(
+            ctx,
+            cmd_args(dependency_jars),
+            concat_jars = concat_deps,
+            name_prefix = "deps_",
+            append_jar = base_jar,
+        )
+        other_outputs = [deps_outputs[0]]
+
+        # generate final jar appending modules to the dependencies jar
+        outputs = _create_fat_jar(
+            ctx,
+            cmd_args(incremental_jars),
+            native_libs = native_deps,
+            do_not_create_inner_jar = do_not_create_inner_jar,
+            generate_wrapper = need_to_generate_wrapper,
+            main_class = main_class,
+            append_jar = deps_outputs[0],
+        )
+    else:
+        outputs = _create_fat_jar(
+            ctx,
+            packaging_jar_args,
+            concat_jars = concat_deps,
+            native_libs = native_deps,
+            do_not_create_inner_jar = do_not_create_inner_jar,
+            generate_wrapper = need_to_generate_wrapper,
+            main_class = main_class,
+        )
+
+    run_cmd = _get_run_cmd(
+        attrs = ctx.attrs,
+        script_mode = _generate_script(need_to_generate_wrapper, native_deps),
+        main_artifact = outputs[0],
+        java_toolchain = java_toolchain,
+    )
+
+    if need_to_generate_wrapper:
+        classpath_file = outputs[1]
+        run_cmd.add(
+            cmd_args(
+                hidden = [
+                    java_toolchain.java[RunInfo],
+                    classpath_file,
+                    packaging_jar_args,
+                ]
+            )
+        )
+        other_outputs = [classpath_file] + [packaging_jar_args] + _get_java_tool_artifacts(java_toolchain)
+
+    sub_targets = get_classpath_subtargets(ctx.actions, packaging_info)
+
+    class_to_src_map, _, _ = get_class_to_source_map_info(
+        ctx,
+        outputs = None,
+        deps = ctx.attrs.deps,
+    )
+
+    return [
+        DefaultInfo(default_output = outputs[0], other_outputs = other_outputs, sub_targets = sub_targets),
+        RunInfo(args = run_cmd),
+        create_template_info(ctx, packaging_info, first_order_libs),
+        class_to_src_map,
+    ]
diff --git a/buck2/prelude/java/java_library.bzl b/buck2/prelude/java/java_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/java_library.bzl
@@ -0,0 +1,899 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:attrs_validators.bzl", "get_attrs_validation_specs")
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")
+load("@prelude//android:android_providers.bzl", "merge_android_packageable_info")
+load("@prelude//graphql:graphql.bzl", "graphql_providers")
+load(
+    "@prelude//java:java_providers.bzl",
+    "ClasspathSnapshotGranularity",
+    "JavaCompileOutputs",  # @unused Used as type
+    "JavaCompilingDepsTSet",  # @unused Used as type
+    "JavaLibraryInfo",
+    "JavaPackagingDepTSet",
+    "JavaProviders",
+    "create_abi",
+    "create_java_library_providers",
+    "create_native_providers",
+    "generate_java_classpath_snapshot",
+    "get_compiling_deps_tset",
+    "make_compile_outputs",
+    "to_list",
+)
+load("@prelude//java:java_resources.bzl", "get_resources_map")
+load("@prelude//java:java_toolchain.bzl", "AbiGenerationMode", "JavaToolchainInfo")
+load("@prelude//java:javacd_jar_creator.bzl", "create_jar_artifact_javacd")
+load("@prelude//java/plugins:java_annotation_processor.bzl", "AnnotationProcessorProperties", "create_annotation_processor_properties")
+load(
+    "@prelude//java/plugins:java_plugin.bzl",
+    "PluginParams",  # @unused Used as type
+    "create_plugin_params",
+)
+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")
+load(
+    "@prelude//java/utils:java_utils.bzl",
+    "CustomJdkInfo",  # @unused Used as a type,
+    "build_bootclasspath",
+    "declare_prefixed_name",
+    "derive_javac",
+    "get_abi_generation_mode",
+    "get_class_to_source_map_info",
+    "get_default_info",
+    "get_java_version_attributes",
+    "to_java_version",
+)
+load("@prelude//jvm:cd_jar_creator_util.bzl", "postprocess_jar")
+load("@prelude//jvm:nullsafe.bzl", "get_nullsafe_info")
+load("@prelude//linking:shared_libraries.bzl", "SharedLibraryInfo")
+load("@prelude//target_stats:target_stats.bzl", "CycleMode", "target_stats_providers_and_subtargets")
+load("@prelude//target_stats:target_stats_config.bzl", "TARGET_STATS_ENABLED")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:label_provider.bzl", "LabelInfo")
+
+_JAVA_FILE_EXTENSION = [".java"]
+_SUPPORTED_ARCHIVE_SUFFIXES = [".src.zip", "-sources.jar"]
+
+_JAVAC_PLUGIN_JVM_ARGS = [
+    "-J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
+    "-J--add-exports=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED",
+    "-J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED",
+    "-J--add-exports=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED",
+    "-J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED",
+    "-J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED",
+    "-J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED",
+    "-J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED",
+    "-J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED",
+    "-J--add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",
+    "-J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
+    "-J--add-opens=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED",
+    "-J--add-opens=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED",
+    "-J--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
+]
+
+def _process_classpath(actions: AnalysisActions, classpath_args: cmd_args, args_file_name: str, option_name: str, has_content_based_path: bool) -> cmd_args:
+    # write joined classpath string into args file
+    classpath_args_file, _ = actions.write(
+        args_file_name,
+        classpath_args,
+        allow_args = True,
+        has_content_based_path = has_content_based_path,
+    )
+
+    return cmd_args(
+        option_name,
+        # add classpath args file to cmd
+        classpath_args_file,
+        # mark classpath artifacts as input
+        hidden = classpath_args,
+    )
+
+def _classpath_args(ctx: AnalysisContext, args):
+    return cmd_args(args, delimiter = get_path_separator_for_exec_os(ctx))
+
+def _process_plugins(
+    ctx: AnalysisContext,
+    actions_identifier: [str, None],
+    annotation_processor_properties: AnnotationProcessorProperties,
+    plugin_params: [PluginParams, None],
+    javac_args: cmd_args,
+    use_content_based_paths: bool,
+) -> cmd_args:
+    cmd = cmd_args()
+    processors_classpath_tsets = []
+
+    # Process Annotation processors
+    if annotation_processor_properties.annotation_processors:
+        # For external javac, we can't preserve separate classpaths for separate processors. So we just concat everything.
+        javac_args.add("-processor")
+        joined_processors_string = ",".join([p for ap in annotation_processor_properties.annotation_processors for p in ap.processors])
+
+        javac_args.add(joined_processors_string)
+        for param in annotation_processor_properties.annotation_processor_params:
+            javac_args.add("-A{}".format(param))
+
+        for ap in annotation_processor_properties.annotation_processors:
+            if ap.deps:
+                processors_classpath_tsets.append(ap.deps)
+
+    else:
+        javac_args.add("-proc:none")
+
+    # Process Javac Plugins
+    if plugin_params:
+        plugin, args = plugin_params.processors[0]
+
+        # Produces "-Xplugin:PluginName arg1 arg2 arg3", as a single argument
+        plugin_and_args = cmd_args(plugin)
+        plugin_and_args.add(args)
+        plugin_arg = cmd_args(format = "-Xplugin:{}", quote = "shell")
+        plugin_arg.add(cmd_args(plugin_and_args, delimiter = " "))
+
+        javac_args.add(plugin_arg)
+        if plugin_params.deps:
+            processors_classpath_tsets.append(plugin_params.deps)
+
+    if len(processors_classpath_tsets) > 1:
+        processors_classpath_tset = ctx.actions.tset(JavaPackagingDepTSet, children = processors_classpath_tsets)
+    elif len(processors_classpath_tsets) == 1:
+        processors_classpath_tset = processors_classpath_tsets[0]
+    else:
+        processors_classpath_tset = None
+
+    if processors_classpath_tset:
+        processors_classpath = _classpath_args(ctx, processors_classpath_tset.project_as_args("full_jar_args"))
+        cmd.add(
+            _process_classpath(
+                ctx.actions,
+                processors_classpath,
+                declare_prefixed_name("plugin_cp_args", actions_identifier),
+                "--javac_processors_classpath_file",
+                use_content_based_paths,
+            )
+        )
+
+    return cmd
+
+def _build_classpath(
+    actions: AnalysisActions,
+    deps: list[Dependency],
+    additional_classpath_entries: JavaCompilingDepsTSet | None,
+    classpath_args_projection: str,
+    additional_classpath_entries_list: list[Artifact],
+) -> [cmd_args, None]:
+    compiling_deps_tset = get_compiling_deps_tset(actions, deps)
+
+    if additional_classpath_entries or compiling_deps_tset or additional_classpath_entries_list:
+        args = cmd_args()
+        if compiling_deps_tset:
+            args.add(compiling_deps_tset.project_as_args(classpath_args_projection))
+        if additional_classpath_entries:
+            args.add(additional_classpath_entries.project_as_args(classpath_args_projection))
+        if additional_classpath_entries_list:
+            args.add(additional_classpath_entries_list)
+        return args
+
+    return None
+
+def _append_javac_params(
+    ctx: AnalysisContext,
+    actions_identifier: [str, None],
+    java_toolchain: JavaToolchainInfo,
+    srcs: list[Artifact],
+    remove_classes: list[str],
+    annotation_processor_properties: AnnotationProcessorProperties,
+    javac_plugin_params: [PluginParams, None],
+    source_level: int,
+    target_level: int,
+    deps: list[Dependency],
+    extra_arguments: cmd_args,
+    additional_classpath_entries: JavaCompilingDepsTSet | None,
+    custom_jdk_info: CustomJdkInfo | None,
+    generated_sources_dir: Artifact,
+    use_content_based_paths: bool,
+) -> cmd_args:
+    cmd = cmd_args()
+    shared_javac_args = cmd_args(
+        "-encoding",
+        "utf-8",
+        # Set the sourcepath to stop us reading source files out of jars by mistake.
+        "-sourcepath",
+        '""',
+    )
+
+    min_release_version = ctx.attrs.min_release_version if hasattr(ctx.attrs, "min_release_version") else None
+    multi_release_srcs = ctx.attrs.multi_release_srcs if hasattr(ctx.attrs, "multi_release_srcs") else {}
+
+    shared_javac_args.add(extra_arguments)
+
+    additional_classpath_entries_list = []
+
+    # min_release_version will use latest JDK for compilation, so we need to add JDK8 bootclasspath
+    if target_level >= 9 or min_release_version:
+        if custom_jdk_info:
+            additional_classpath_entries_list = custom_jdk_info.bootclasspath
+            shared_javac_args.add("--system", custom_jdk_info.system_image)
+    else:
+        custom_bootclasspath = custom_jdk_info.bootclasspath if custom_jdk_info else []
+        bootclasspath_list = build_bootclasspath(custom_bootclasspath, source_level, java_toolchain)
+        if bootclasspath_list:
+            cmd.add(
+                _process_classpath(
+                    ctx.actions,
+                    _classpath_args(ctx, bootclasspath_list),
+                    declare_prefixed_name("bootclasspath_args", actions_identifier),
+                    "--javac_bootclasspath_file",
+                    use_content_based_paths,
+                )
+            )
+
+    compiling_classpath = _build_classpath(ctx.actions, deps, additional_classpath_entries, "args_for_compiling", additional_classpath_entries_list)
+    if compiling_classpath:
+        cmd.add(
+            _process_classpath(
+                ctx.actions,
+                _classpath_args(ctx, compiling_classpath),
+                declare_prefixed_name("classpath_args", actions_identifier),
+                "--javac_classpath_file",
+                use_content_based_paths,
+            )
+        )
+    else:
+        shared_javac_args.add("-classpath ''")
+
+    cmd.add(
+        _process_plugins(
+            ctx,
+            actions_identifier,
+            annotation_processor_properties,
+            javac_plugin_params,
+            shared_javac_args,
+            use_content_based_paths,
+        )
+    )
+
+    cmd.add("--generated_sources_dir", generated_sources_dir.as_output())
+
+    zipped_sources, plain_sources = split_on_archives_and_plain_files(srcs, _JAVA_FILE_EXTENSION)
+
+    # copy of javac_args to be used by multi_release_args_file before release is added and before srcs is added
+    javac_args = shared_javac_args.copy()
+    if min_release_version:
+        javac_args.add("--release", min_release_version)
+    else:
+        javac_args.add("-source", str(source_level))
+        javac_args.add("-target", str(target_level))
+    javac_args.add(*plain_sources)
+    args_file, _ = ctx.actions.write(
+        declare_prefixed_name("javac_args", actions_identifier),
+        javac_args,
+        allow_args = True,
+        has_content_based_path = use_content_based_paths,
+    )
+    cmd.add(cmd_args(hidden = javac_args))
+
+    # mark plain srcs artifacts as input
+    cmd.add(cmd_args(hidden = plain_sources))
+
+    cmd.add("--javac_args_file", args_file)
+
+    if min_release_version and multi_release_srcs:
+        for min_release_version, release_srcs in multi_release_srcs.items():
+            release_args = shared_javac_args.copy()
+            release_args.add("--release", min_release_version)
+            release_args.add(*release_srcs)
+            release_args_file, _ = ctx.actions.write(
+                declare_prefixed_name("multi_release_args.java{}".format(min_release_version), actions_identifier),
+                release_args,
+                allow_args = True,
+                has_content_based_path = use_content_based_paths,
+            )
+            cmd.add("--multi_release_args_file", release_args_file)
+            cmd.add(cmd_args(hidden = release_srcs))
+
+    if zipped_sources:
+        cmd.add(
+            "--zipped_sources_file",
+            ctx.actions.write(declare_prefixed_name("zipped_source_args", actions_identifier), zipped_sources, has_content_based_path = use_content_based_paths),
+        )
+        cmd.add(cmd_args(hidden = zipped_sources))
+
+    if remove_classes:
+        cmd.add(
+            "--remove_classes",
+            ctx.actions.write(declare_prefixed_name("remove_classes_args", actions_identifier), remove_classes, has_content_based_path = use_content_based_paths),
+        )
+
+    return cmd
+
+def split_on_archives_and_plain_files(srcs: list[Artifact], plain_file_extensions: list[str]) -> (list[Artifact], list[Artifact]):
+    archives = []
+    plain_sources = []
+
+    for src in srcs:
+        if src.extension in plain_file_extensions:
+            plain_sources.append(src)
+        elif _is_supported_archive(src):
+            archives.append(src)
+        else:
+            fail("Provided java source is not supported: {}".format(src))
+
+    return (archives, plain_sources)
+
+def _is_supported_archive(src: Artifact) -> bool:
+    basename = src.basename
+    for supported_suffix in _SUPPORTED_ARCHIVE_SUFFIXES:
+        if basename.endswith(supported_suffix):
+            return True
+    return False
+
+def _copy_resources(
+    actions: AnalysisActions,
+    actions_identifier: [str, None],
+    java_toolchain: JavaToolchainInfo,
+    package: str,
+    resources: list[Artifact],
+    resources_root: [str, None],
+    use_content_based_paths: bool,
+) -> Artifact:
+    resources_to_copy = get_resources_map(java_toolchain, package, resources, resources_root)
+    resource_output = actions.symlinked_dir(
+        declare_prefixed_name("resources", actions_identifier), resources_to_copy, has_content_based_path = use_content_based_paths
+    )
+    return resource_output
+
+def _jar_creator(javac_tool: [typing.Any, None], java_toolchain: JavaToolchainInfo) -> typing.Callable:
+    if javac_tool or java_toolchain.javac_protocol == "classic":
+        return _create_jar_artifact
+    elif java_toolchain.javac_protocol == "javacd":
+        return create_jar_artifact_javacd
+    else:
+        fail("unrecognized javac protocol `{}`".format(java_toolchain.javac_protocol))
+
+def compile_to_jar(
+    ctx: AnalysisContext,
+    srcs: list[Artifact],
+    *,
+    abi_generation_mode: [AbiGenerationMode, None] = None,
+    output: Artifact | None = None,
+    actions_identifier: [str, None] = None,
+    javac_tool: [typing.Any, None] = None,
+    resources: [list[Artifact], None] = None,
+    resources_root: [str, None] = None,
+    remove_classes: [list[str], None] = None,
+    manifest_file: Artifact | None = None,
+    annotation_processor_properties: [AnnotationProcessorProperties, None] = None,
+    plugin_params: [PluginParams, None] = None,
+    source_level: [int, None] = None,
+    target_level: [int, None] = None,
+    deps: [list[Dependency], None] = None,
+    required_for_source_only_abi: bool = False,
+    source_only_abi_deps: [list[Dependency], None] = None,
+    extra_arguments: [cmd_args, None] = None,
+    additional_classpath_entries: JavaCompilingDepsTSet | None = None,
+    additional_compiled_srcs: Artifact | None = None,
+    custom_jdk_info: CustomJdkInfo | None = None,
+    is_creating_subtarget: bool = False,
+    debug_port: [int, None] = None,
+    enable_depfiles: [bool, None] = True,
+) -> JavaCompileOutputs:
+    if not extra_arguments:
+        extra_arguments = cmd_args()
+    if not resources:
+        resources = []
+    if not deps:
+        deps = []
+    if not remove_classes:
+        remove_classes = []
+    if not annotation_processor_properties:
+        annotation_processor_properties = AnnotationProcessorProperties(annotation_processors = [], annotation_processor_params = [])
+    if not source_only_abi_deps:
+        source_only_abi_deps = []
+
+    # TODO(cjhopman): Should verify that source_only_abi_deps are contained within the normal classpath.
+
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    if not source_level:
+        source_level = to_java_version(java_toolchain.source_level)
+    if not target_level:
+        target_level = to_java_version(java_toolchain.target_level)
+
+    is_building_android_binary = ctx.attrs._is_building_android_binary
+
+    return _jar_creator(javac_tool, java_toolchain)(
+        ctx,
+        actions_identifier,
+        abi_generation_mode,
+        java_toolchain,
+        ctx.label,
+        output,
+        javac_tool,
+        srcs,
+        remove_classes,
+        resources,
+        resources_root,
+        manifest_file,
+        annotation_processor_properties,
+        plugin_params,
+        source_level,
+        target_level,
+        deps,
+        required_for_source_only_abi,
+        source_only_abi_deps,
+        extra_arguments,
+        additional_classpath_entries,
+        additional_compiled_srcs,
+        custom_jdk_info,
+        is_building_android_binary,
+        is_creating_subtarget,
+        debug_port,
+        enable_depfiles,
+    )
+
+def _create_jar_artifact(
+    ctx: AnalysisContext,
+    actions_identifier: [str, None],
+    abi_generation_mode: [AbiGenerationMode, None],
+    java_toolchain: JavaToolchainInfo,
+    label: Label,
+    output: Artifact | None,
+    javac_tool: [typing.Any, None],
+    srcs: list[Artifact],
+    remove_classes: list[str],
+    resources: list[Artifact],
+    resources_root: [str, None],
+    manifest_file: Artifact | None,
+    annotation_processor_properties: AnnotationProcessorProperties,
+    plugin_params: [PluginParams, None],
+    source_level: int,
+    target_level: int,
+    deps: list[Dependency],
+    required_for_source_only_abi: bool,
+    _source_only_abi_deps: list[Dependency],
+    extra_arguments: cmd_args,
+    additional_classpath_entries: JavaCompilingDepsTSet | None,
+    additional_compiled_srcs: Artifact | None,
+    custom_jdk_info: CustomJdkInfo | None,
+    _is_building_android_binary: bool,
+    _is_creating_subtarget: bool = False,
+    _debug_port: [int, None] = None,
+    _enable_depfiles: [bool, None] = True,
+) -> JavaCompileOutputs:
+    """
+    Creates jar artifact.
+
+    Returns a single artifacts that represents jar output file
+    """
+    use_content_based_paths = ctx.attrs.uses_content_based_paths_for_classic_java
+    javac_tool = javac_tool or derive_javac(java_toolchain.javac)
+    jar_out = output or ctx.actions.declare_output(
+        paths.join(actions_identifier or "jar", "{}.jar".format(label.name)), has_content_based_path = use_content_based_paths
+    )
+
+    # since create_jar_artifact_javacd does not support this, it will not be added to common_compile_kwargs
+    concat_resources = getattr(ctx.attrs, "concat_resources", False)
+
+    args = [
+        java_toolchain.compile_and_package[RunInfo],
+        "--jar_builder_tool",
+        cmd_args(java_toolchain.jar_builder, delimiter = " "),
+        "--output",
+        jar_out.as_output(),
+    ]
+
+    skip_javac = False if srcs or annotation_processor_properties.annotation_processors or plugin_params else True
+    if skip_javac:
+        args.append("--skip_javac_run")
+    else:
+        args += ["--javac_tool", javac_tool]
+        if plugin_params:
+            jvm_args_file = ctx.actions.write(
+                declare_prefixed_name("javac_jvm_args", actions_identifier),
+                _JAVAC_PLUGIN_JVM_ARGS,
+                has_content_based_path = use_content_based_paths,
+            )
+            args += ["--javac_jvm_args_file", jvm_args_file]
+
+    if resources:
+        resource_dir = _copy_resources(ctx.actions, actions_identifier, java_toolchain, label.package, resources, resources_root, use_content_based_paths)
+        args += ["--resources_dir", resource_dir]
+    if concat_resources:
+        args += ["--concat_resources"]
+
+    if manifest_file:
+        args += ["--manifest", manifest_file]
+
+    if additional_compiled_srcs:
+        args += ["--additional_compiled_srcs", additional_compiled_srcs]
+
+    compile_and_package_cmd = cmd_args(args)
+
+    generated_sources_dir = None
+    if not skip_javac:
+        generated_sources_dir = ctx.actions.declare_output(
+            declare_prefixed_name("generated_sources", actions_identifier), dir = True, has_content_based_path = use_content_based_paths
+        )
+        compile_and_package_cmd.add(
+            _append_javac_params(
+                ctx,
+                actions_identifier,
+                java_toolchain,
+                srcs,
+                remove_classes,
+                annotation_processor_properties,
+                plugin_params,
+                source_level,
+                target_level,
+                deps,
+                extra_arguments,
+                additional_classpath_entries,
+                custom_jdk_info,
+                generated_sources_dir,
+                use_content_based_paths,
+            )
+        )
+
+    ctx.actions.run(compile_and_package_cmd, category = "javac_and_jar", identifier = actions_identifier)
+
+    abi = (
+        None
+        if (not srcs and not additional_compiled_srcs) or abi_generation_mode == AbiGenerationMode("none") or java_toolchain.is_bootstrap_toolchain
+        else create_abi(ctx.actions, java_toolchain.class_abi_generator, jar_out, getattr(ctx.attrs, "keep_synthetics_in_class_abi", False) or False)
+    )
+
+    has_postprocessor = hasattr(ctx.attrs, "jar_postprocessor") and ctx.attrs.jar_postprocessor
+    final_jar = (
+        postprocess_jar(
+            ctx.actions,
+            java_toolchain.zip_scrubber,
+            ctx.attrs.jar_postprocessor[RunInfo],
+            java_toolchain.postprocessor_runner[RunInfo],
+            jar_out,
+            actions_identifier,
+        )
+        if has_postprocessor
+        else jar_out
+    )
+
+    jar_snapshot = generate_java_classpath_snapshot(
+        ctx.actions, java_toolchain.cp_snapshot_generator, ClasspathSnapshotGranularity("CLASS_MEMBER_LEVEL"), abi or final_jar, actions_identifier
+    )
+    return make_compile_outputs(
+        full_library = final_jar,
+        preprocessed_library = jar_out,
+        class_abi = abi,
+        required_for_source_only_abi = required_for_source_only_abi,
+        annotation_processor_output = generated_sources_dir,
+        abi_jar_snapshot = jar_snapshot,
+    )
+
+def _check_dep_types(deps: list[Dependency]):
+    for dep in deps:
+        if JavaLibraryInfo not in dep and SharedLibraryInfo not in dep:
+            fail("Received dependency {} is not supported. `java_library`, `prebuilt_jar` and native libraries are supported.".format(dep))
+
+def _check_provided_deps(provided_deps: list[Dependency], attr_name: str):
+    for provided_dep in provided_deps:
+        expect(
+            JavaLibraryInfo in provided_dep or SharedLibraryInfo not in provided_dep,
+            "Java code does not need native libs in order to compile, so not valid as {}: {}".format(attr_name, provided_dep),
+        )
+
+def _check_exported_deps(exported_deps: list[Dependency], attr_name: str):
+    for exported_dep in exported_deps:
+        expect(
+            JavaLibraryInfo in exported_dep,
+            "Exported deps are meant to be forwarded onto the classpath for dependents, so only "
+            + "make sense for a target that emits Java bytecode, {} in {} does not.".format(exported_dep, attr_name),
+        )
+        expect(
+            not exported_dep[JavaLibraryInfo].may_not_be_exported,
+            "{} has 'may_not_be_exported' label and should not be present in {}.".format(exported_dep.label.raw_target(), attr_name),
+        )
+
+# TODO(T145137403) remove need for this
+def _skip_java_library_dep_checks(ctx: AnalysisContext) -> bool:
+    return "skip_buck2_java_library_dep_checks" in ctx.attrs.labels
+
+def jvm_target_stats(ctx: AnalysisContext) -> (list[Provider], dict[str, list[Provider]]):
+    """target_stats for a JVM library rule (java_library, kotlin_library).
+
+    JVM sources get package cycles, as android_library does; the tools come from
+    the java toolchain, which is the one both rules have. A no-op unless the
+    config is enabled and that toolchain carries the tools.
+    """
+    if not TARGET_STATS_ENABLED:
+        return [], {}
+    tools = ctx.attrs._java_toolchain[JavaToolchainInfo].target_stats_tools
+    if tools == None:
+        return [], {}
+    return target_stats_providers_and_subtargets(
+        ctx,
+        tools = tools,
+        srcs = {src.short_path: src for src in ctx.attrs.srcs},
+        # Target stats cover the compile graph, including non-packaged provided deps.
+        deps = (ctx.attrs.deps + ctx.attrs.exported_deps + ctx.attrs.runtime_deps + ctx.attrs.provided_deps + ctx.attrs.exported_provided_deps),
+        cycle_mode = CycleMode("package"),
+        module_name = ctx.label.name,
+    )
+
+def java_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    """
+     java_library() rule implementation
+
+    Args:
+        ctx: rule analysis context
+    Returns:
+        list of created providers
+    """
+    packaging_deps = ctx.attrs.deps + ctx.attrs.exported_deps + ctx.attrs.runtime_deps
+
+    # TODO(T107163344) this shouldn't be in java_library itself, use overlays to remove it.
+    android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, packaging_deps)
+    if ctx.attrs._build_only_native_code:
+        shared_library_info, cxx_resource_info, linkable_graph = create_native_providers(ctx, ctx.label, packaging_deps)
+        return [
+            shared_library_info,
+            cxx_resource_info,
+            linkable_graph,
+            # Add an unused default output in case this target is used an an attr.source() anywhere.
+            DefaultInfo(default_output = ctx.actions.write("{}/unused.jar".format(ctx.label.name), [], has_content_based_path = False)),
+            TemplatePlaceholderInfo(
+                keyed_variables = {
+                    "classpath": "unused_but_needed_for_analysis",
+                }
+            ),
+            android_packageable_info,
+        ]
+
+    if not _skip_java_library_dep_checks(ctx):
+        _check_dep_types(ctx.attrs.deps)
+        _check_dep_types(ctx.attrs.provided_deps)
+        _check_dep_types(ctx.attrs.exported_deps)
+        _check_dep_types(ctx.attrs.exported_provided_deps)
+        _check_dep_types(ctx.attrs.runtime_deps)
+
+    target_stats_providers, target_stats_subtargets = jvm_target_stats(ctx)
+
+    java_providers = build_java_library(
+        ctx = ctx,
+        srcs = ctx.attrs.srcs,
+        validation_deps_outputs = get_validation_deps_outputs(ctx),
+        extra_sub_targets = target_stats_subtargets,
+    )
+
+    return to_list(java_providers) + [android_packageable_info] + [LabelInfo(labels = ctx.attrs.labels)] + graphql_providers(ctx) + target_stats_providers
+
+def build_java_library(
+    ctx: AnalysisContext,
+    srcs: list[Artifact],
+    run_annotation_processors = True,
+    additional_classpath_entries: JavaCompilingDepsTSet | None = None,
+    custom_jdk_info: CustomJdkInfo | None = None,
+    additional_compiled_srcs: Artifact | None = None,
+    generated_sources: list[Artifact] = [],
+    override_abi_generation_mode: [AbiGenerationMode, None] = None,
+    extra_sub_targets: dict = {},
+    validation_deps_outputs: [list[Artifact], None] = None,
+    extra_arguments = [],
+) -> JavaProviders:
+    expect(
+        not getattr(ctx.attrs, "_build_only_native_code", False),
+        "Shouldn't call build_java_library if we're only building native code!",
+    )
+
+    _check_provided_deps(ctx.attrs.provided_deps, "provided_deps")
+    _check_provided_deps(ctx.attrs.exported_provided_deps, "exported_provided_deps")
+    _check_exported_deps(ctx.attrs.exported_deps, "exported_deps")
+    _check_exported_deps(ctx.attrs.exported_provided_deps, "exported_provided_deps")
+
+    deps_query = getattr(ctx.attrs, "deps_query", []) or []
+    provided_deps_query = getattr(ctx.attrs, "provided_deps_query", []) or []
+    first_order_deps = ctx.attrs.deps + deps_query + ctx.attrs.exported_deps + ctx.attrs.provided_deps + provided_deps_query + ctx.attrs.exported_provided_deps
+
+    resources = ctx.attrs.resources
+    resources_root = ctx.attrs.resources_root
+    expect(resources_root != "", "Empty resources_root is not legal, try '.' instead!")
+
+    annotation_processor_properties = (
+        create_annotation_processor_properties(
+            ctx,
+            ctx.attrs.plugins + ctx.attrs.non_exec_dep_plugins_deprecated,
+            ctx.attrs.annotation_processors,
+            ctx.attrs.annotation_processor_params,
+            ctx.attrs.annotation_processor_deps,
+        )
+        if run_annotation_processors
+        else None
+    )
+    plugin_params = create_plugin_params(ctx, ctx.attrs.plugins + ctx.attrs.non_exec_dep_plugins_deprecated) if run_annotation_processors else None
+    manifest_file = ctx.attrs.manifest_file
+    source_level, target_level = get_java_version_attributes(ctx)
+
+    outputs = None
+    common_compile_kwargs = None
+    has_srcs = bool(srcs) or bool(additional_compiled_srcs)
+    if has_srcs or resources or manifest_file:
+        abi_generation_mode = override_abi_generation_mode or get_abi_generation_mode(ctx.attrs.abi_generation_mode)
+
+        common_compile_kwargs = {
+            "abi_generation_mode": abi_generation_mode,
+            "additional_classpath_entries": additional_classpath_entries,
+            "additional_compiled_srcs": additional_compiled_srcs,
+            "annotation_processor_properties": annotation_processor_properties,
+            "custom_jdk_info": custom_jdk_info,
+            "debug_port": getattr(ctx.attrs, "debug_port", None),
+            "deps": first_order_deps,
+            "enable_depfiles": getattr(ctx.attrs, "enable_depfiles", True),
+            "javac_tool": derive_javac(ctx.attrs.javac) if getattr(ctx.attrs, "javac", None) else None,
+            "manifest_file": manifest_file,
+            "remove_classes": ctx.attrs.remove_classes,
+            "required_for_source_only_abi": ctx.attrs.required_for_source_only_abi,
+            "resources": resources,
+            "resources_root": resources_root,
+            "source_level": source_level,
+            "source_only_abi_deps": ctx.attrs.source_only_abi_deps,
+            "srcs": srcs,
+            "target_level": target_level,
+        }
+
+        # The outputs of validation_deps need to be added as hidden arguments
+        # to an action for the validation_deps targets to be built and enforced.
+        extra_arguments = cmd_args(
+            ctx.attrs.extra_arguments + extra_arguments,
+            hidden = validation_deps_outputs or [],
+        )
+
+        outputs = compile_to_jar(ctx, plugin_params = plugin_params, extra_arguments = extra_arguments, **common_compile_kwargs)
+
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    if common_compile_kwargs and srcs and not ctx.attrs._is_building_android_binary:
+        extra_sub_targets = _nullsafe_subtarget(ctx, extra_sub_targets, common_compile_kwargs)
+        if not java_toolchain.is_bootstrap_toolchain:
+            extra_sub_targets = _semanticdb_subtarget(ctx, extra_sub_targets, java_toolchain, common_compile_kwargs)
+
+    gwt_output = None
+    if (srcs or resources) and not java_toolchain.is_bootstrap_toolchain and not ctx.attrs._is_building_android_binary:
+        gwt_output = ctx.actions.declare_output("gwt_module/{}.jar".format(ctx.label.name), has_content_based_path = False)
+        entries = []
+
+        if srcs or resources:
+            entries.append(_copy_resources(ctx.actions, "gwt_module", java_toolchain, ctx.label.package, srcs + resources, resources_root, False))
+        if outputs and outputs.annotation_processor_output:
+            entries.append(outputs.annotation_processor_output)
+
+        gwt_cmd_args = cmd_args(
+            java_toolchain.jar_builder,
+            "--entries-to-jar",
+            ctx.actions.write("gwt_entries.txt", entries, has_content_based_path = False),
+            "--output",
+            gwt_output.as_output(),
+            hidden = entries,
+        )
+
+        ctx.actions.run(gwt_cmd_args, category = "gwt_module")
+
+    all_generated_sources = list(generated_sources)
+    if outputs and outputs.annotation_processor_output:
+        all_generated_sources.append(outputs.annotation_processor_output)
+
+    if len(all_generated_sources) == 1:
+        extra_sub_targets = extra_sub_targets | {
+            "generated_sources": [
+                DefaultInfo(default_output = all_generated_sources[0]),
+            ]
+        }
+
+    class_to_src_map, sources_jar, class_to_src_map_sub_targets = get_class_to_source_map_info(
+        ctx,
+        outputs = outputs,
+        deps = ctx.attrs.deps + deps_query + ctx.attrs.exported_deps,
+        generate_sources_jar = True,
+        class_to_src_map_deps = getattr(ctx.attrs, "class_to_src_map_deps", []),
+    )
+    extra_sub_targets = extra_sub_targets | class_to_src_map_sub_targets
+
+    (
+        java_library_info,
+        java_packaging_info,
+        global_code_info,
+        shared_library_info,
+        cxx_resource_info,
+        linkable_graph,
+        template_placeholder_info,
+        intellij_info,
+    ) = create_java_library_providers(
+        ctx,
+        library_output = outputs.classpath_entry if outputs else None,
+        global_code_config = java_toolchain.global_code_config,
+        declared_deps = ctx.attrs.deps + deps_query,
+        exported_deps = ctx.attrs.exported_deps,
+        provided_deps = ctx.attrs.provided_deps + provided_deps_query,
+        exported_provided_deps = ctx.attrs.exported_provided_deps,
+        runtime_deps = ctx.attrs.runtime_deps,
+        generated_sources = all_generated_sources,
+        has_srcs = has_srcs,
+        sources_jar = sources_jar,
+        gwt_module = gwt_output,
+        preprocessed_library = outputs.preprocessed_library if outputs else None,
+        used_jars_json = outputs.used_jars_json if outputs else None,
+    )
+
+    validation_specs = get_attrs_validation_specs(ctx)
+    if hasattr(ctx.attrs, "validation_specs"):
+        validation_specs.extend([ValidationSpec(name = name, validation_result = result) for name, result in ctx.attrs.validation_specs.items()])
+
+    validation_info = ValidationInfo(validations = validation_specs) if validation_specs else None
+
+    default_info = get_default_info(
+        ctx.actions,
+        java_toolchain,
+        outputs,
+        java_packaging_info,
+        extra_sub_targets,
+    )
+    return JavaProviders(
+        java_library_info = java_library_info,
+        java_library_intellij_info = intellij_info,
+        java_packaging_info = java_packaging_info,
+        java_global_code_info = global_code_info,
+        shared_library_info = shared_library_info,
+        cxx_resource_info = cxx_resource_info,
+        linkable_graph = linkable_graph,
+        template_placeholder_info = template_placeholder_info,
+        default_info = default_info,
+        class_to_src_map = class_to_src_map,
+        validation_info = validation_info,
+    )
+
+def _nullsafe_subtarget(ctx: AnalysisContext, extra_sub_targets: dict, common_compile_kwargs: dict):
+    nullsafe_info = get_nullsafe_info(ctx)
+    if nullsafe_info:
+        compile_to_jar(
+            ctx,
+            actions_identifier = "nullsafe",
+            plugin_params = nullsafe_info.plugin_params,
+            extra_arguments = nullsafe_info.extra_arguments,
+            is_creating_subtarget = True,
+            **common_compile_kwargs,
+        )
+
+        extra_sub_targets = extra_sub_targets | {
+            "nullsafex-json": [
+                DefaultInfo(default_output = nullsafe_info.output),
+            ]
+        }
+    return extra_sub_targets
+
+def _semanticdb_subtarget(ctx: AnalysisContext, extra_sub_targets: dict, java_toolchain: JavaToolchainInfo, common_compile_kwargs: dict):
+    semanticdb_javac_plugin = java_toolchain.semanticdb_javac
+    sourceroot = java_toolchain.semanticdb_sourceroot
+    if not sourceroot or not semanticdb_javac_plugin:
+        return extra_sub_targets
+    sourceroot_args = cmd_args(sourceroot, format = "-sourceroot:{}")
+    semanticdb_output = ctx.actions.declare_output("semanticdb", dir = True, has_content_based_path = False)
+    targetroot_args = cmd_args(semanticdb_output.as_output(), format = "-targetroot:{}")
+    semanticdb_plugin_params = create_plugin_params(
+        ctx,
+        [(semanticdb_javac_plugin, cmd_args(sourceroot_args, targetroot_args))],
+    )
+    compile_to_jar(
+        ctx,
+        actions_identifier = "semanticdb_javac",
+        plugin_params = semanticdb_plugin_params,
+        extra_arguments = None,
+        is_creating_subtarget = True,
+        **common_compile_kwargs,
+    )
+    extra_sub_targets = extra_sub_targets | {
+        "semanticdb": [
+            DefaultInfo(default_output = semanticdb_output),
+        ]
+    }
+    return extra_sub_targets
diff --git a/buck2/prelude/java/java_providers.bzl b/buck2/prelude/java/java_providers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/java_providers.bzl
@@ -0,0 +1,809 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:resources.bzl",
+    "ResourceInfo",  # @unused Used as a type
+    "gather_resources",
+    "make_resource_info",
+)
+load("@prelude//java:class_to_srcs.bzl", "JavaClassToSourceMapInfo")
+load("@prelude//java:dex.bzl", "DexLibraryInfo", "get_dex_produced_from_java_library")
+load("@prelude//java:dex_toolchain.bzl", "DexToolchainInfo")
+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")
+load("@prelude//linking:linkable_graph.bzl", "LinkableGraph", "create_linkable_graph")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "merge_shared_libraries",
+)
+load("@prelude//utils:expect.bzl", "expect")
+
+# JAVA PROVIDER DOCS
+#
+# Our core Java provider is JavaLibraryInfo. At a basic level, this provider needs to give
+# its dependents the ability to do two things: compilation and packaging.
+#
+# Compilation
+#
+# When we compile, we need to add all of our dependencies to the classpath. That includes
+# anything in `deps`, `exported_deps`, `provided_deps` and `exported_provided_deps`, (but
+# not `runtime_deps`). Additionally, it includes anything that these dependencies export
+# (via `exported_deps` or `exported_provided_deps`). For example, if A depends upon B,
+# and B has an exported dependency on C, then we need to add both B and C to the classpath
+# when compiling A, i.e. both B and C need to be part of B's `compiling_deps`.
+#
+# Therefore, the `compiling_deps` consist of the library's own output (if it exists) plus
+# the `compiling_deps` of any `exported_deps` and `exported_provided_deps`.
+#
+# When we compile, we don't need to compile against the full library - instead, we just
+# compile against the library's public interface, or ABI.
+#
+# Packaging
+#
+# When we package our Java code into a `java_binary`, we need to include all of the Java
+# code that is need to run the application - i.e. all the transitive dependencies. That
+# includes anything in `deps`, `exported_deps` and `runtime_deps` (but not `provided_deps`
+# or `exported_provided_deps`). For example, if A depends upon B, and B has a `dep` on C
+# and a `provided_dep` on D, then if we package A we also need to include B and C, but
+# not D.
+#
+# Therefore, the `packaging_deps` consist of the library's own output (if it exists) plus
+# the `packaging_deps` of any `deps`, `exported_deps` and `runtime_deps`.
+#
+# When we package, we need to use the full library (since we are actually going to be
+# running the code contained in the library).
+#
+# We also need to package up any native code that is declared transitively. The
+# `SharedLibraryInfo` also consists of the `SharedLibraryInfo` of any `deps`,
+# `exported_deps` and `runtime_deps`.
+#
+# Android
+#
+# Because Android uses Java, and we don't currently have the ability to "overlay" our
+# providers, the core Java providers are extended to support Android's requirements.
+# This introduces some additional complexity.
+#
+# Android doesn't package Java bytecode, but instead it converts the Java bytecode
+# .dex (Dalvik Executable) files that are packaged into the Android binary (either an
+# APK or an AAB). Therefore, our `packaging_deps` contain not just a `jar` field but
+# also a `dex` field. If the `dex` field is empty, then the dep should not be
+# packaged into the APK - this is useful for things like `android_build_config` where
+# we want the output (.jar) to be present in any Java annotation processors that we
+# run, but not in the final binary (since we rewrite the build config at the binary
+# level anyway).
+#
+# Android also provides the ability to run Proguard on your binary in order to
+# remove unused classes etc. Each Java library can specify any classes that it wants
+# to always keep etc, via a `proguard_config`. This config also needs to be added to
+# the `packaging_deps`.
+#
+# Java-like rules also provide a "special" function that can be used inside queries:
+# "classpath". `classpath(A)` returns all of the packaging deps of A, while
+# `classpath(A, 1)` returns all of the first-order packaging deps of A.
+
+JavaClasspathEntry = record(
+    full_library = field(Artifact),
+    abi = field(Artifact),
+    # abi_as_dir is the abi .jar unzipped into a directory. If available, it is used to provide
+    # .class level granularity for javacd and kotlincd dep-files.
+    abi_as_dir = field(Artifact | None),
+    required_for_source_only_abi = field(bool),
+    abi_jar_snapshot = field(Artifact | None),
+)
+
+def _args_for_ast_dumper(entry: JavaClasspathEntry):
+    return [
+        "--dependency",
+        '"{}"'.format(entry.abi.owner),
+        entry.abi,
+    ]
+
+def _args_for_compiling(entry: JavaClasspathEntry):
+    return entry.abi
+
+def _javacd_json(v):
+    return v.abi
+
+def _abi_snapshot_json(entry: JavaClasspathEntry):
+    if entry.abi and entry.abi_jar_snapshot:
+        return cmd_args([entry.abi_jar_snapshot], delimiter = " ")
+
+    return None
+
+def _abi_dirs(entry: JavaClasspathEntry):
+    return entry.abi_as_dir or []
+
+def _abi_and_dir(entry: JavaClasspathEntry):
+    return [entry.abi, entry.abi_as_dir or ""]
+
+def _source_only_abi_jars(entry: JavaClasspathEntry):
+    return [entry.abi] if entry.required_for_source_only_abi else []
+
+def _source_only_abi_and_dir(entry: JavaClasspathEntry):
+    return _abi_and_dir(entry) if entry.required_for_source_only_abi else []
+
+def _full_library_args(entry: JavaClasspathEntry):
+    return entry.full_library
+
+# This doesn't have any projections on it at all. It exists only for the
+# purpose of propagating JavaCompilingDepsTSet nodes up the graph in
+# JavaGlobalCodeInfo.
+#
+# We then traverse this wrapper to get the underlying JavaCompilingDepsTSets.
+# It is much, much cheaper in memory usage to do this than it is to ensure
+# a TSet projection at every node for every different global code info spec.
+JavaCompilingDepsTSetWrapper = transitive_set()
+
+JavaCompilingDepsTSet = transitive_set(
+    args_projections = {
+        "abi_and_dir": _abi_and_dir,
+        "abi_dirs": _abi_dirs,
+        "args_for_ast_dumper": _args_for_ast_dumper,
+        "args_for_compiling": _args_for_compiling,
+        "full_library_args": _full_library_args,
+        "source_only_abi_and_dir": _source_only_abi_and_dir,
+        "source_only_abi_jars": _source_only_abi_jars,
+    },
+    json_projections = {
+        "abi_snapshot_json": _abi_snapshot_json,
+        "javacd_json": _javacd_json,
+    },
+)
+
+JavaPackagingDep = record(
+    label = Label,
+    jar = Artifact | None,
+    dex = [DexLibraryInfo, None],
+    gwt_module = Artifact | None,
+    is_prebuilt_jar = bool,
+    proguard_config = Artifact | None,
+    # An output that is used solely by the system to have an artifact bound to the target (that the core can then use to find
+    # the right target from the given artifact).
+    output_for_classpath_macro = Artifact,
+    sources_jar = Artifact | None,
+)
+
+def _full_jar_args(dep: JavaPackagingDep):
+    if dep.jar:
+        return cmd_args(dep.jar)
+    return cmd_args()
+
+def _full_jar_owner_args(dep: JavaPackagingDep):
+    if dep.jar:
+        return cmd_args(dep.label.raw_target())
+    return cmd_args()
+
+def _args_for_classpath_macro(dep: JavaPackagingDep):
+    return dep.output_for_classpath_macro
+
+def _packaging_dep_javacd_json(dep: JavaPackagingDep):
+    return dep.jar or ""
+
+JavaPackagingDepTSet = transitive_set(
+    args_projections = {
+        "args_for_classpath_macro": _args_for_classpath_macro,
+        "full_jar_args": _full_jar_args,
+        "full_jar_owner_args": _full_jar_owner_args,
+    },
+    json_projections = {
+        "javacd_json": _packaging_dep_javacd_json,
+    },
+)
+
+JavaGlobalCodeInfo = provider(
+    doc = """This dictionary maps a framework key to its corresponding GlobalCodeConfig. The GlobalCodeConfig specifies the dependency .jars required by the framework for global-level code generation (binary level).
+    The process responsible for generating the global_code_info provider for the target utilizes this mapping to:
+    * Retrieve the GlobalCodeConfig associated with each framework, identified by its key.
+    * Determine whether the .jar files for the library or any of its dependencies are necessary for global code generation for that particular framework.
+    * Create a mapping from each framework key to a list of the required .jars identified in the previous step.""",
+    fields = {
+        "global_code_map": provider_field(typing.Any, default = None),  # "{name: JavaCompilingDepsTSet}"
+    },
+)
+
+JavaLibraryInfo = provider(
+    doc = "Information about a java library and its dependencies",
+    fields = {
+        # Java dependencies exposed to dependent targets and supposed to be used during compilation.
+        # Consisting of this library's own output, and the "compiling_deps" of any exported_deps and exported_provided_deps.
+        #
+        "compiling_deps": provider_field(typing.Any, default = None),  # ["JavaCompilingDepsTSet", None]
+        # A TSet that contains the "compiling_deps" as a node. This is used to propagate "global code info" up the graph.
+        "compiling_deps_wrapper": provider_field(typing.Any, default = None),  # ["JavaCompilingDepsTSetWrapper", None]
+        # An output of the library. If present then already included into `compiling_deps` field.
+        "library_output": provider_field(typing.Any, default = None),  # ["JavaClasspathEntry", None]
+        # Shows if the library can be exported or not
+        "may_not_be_exported": provider_field(typing.Any, default = None),
+        # Shows if the library can be packaged or not
+        "may_not_be_packaged": provider_field(typing.Any, default = None),
+        # An output that is used solely by the system to have an artifact bound to the target (that the core can then use to find
+        # the right target from the given artifact).
+        "output_for_classpath_macro": provider_field(typing.Any, default = None),  # "artifact"
+    },
+)
+
+JavaLibraryIntellijInfo = provider(
+    doc = "Information about a java library that is required for Intellij project generation",
+    fields = {
+        # Directory containing external annotation jars
+        "annotation_jars_dir": provider_field(typing.Any, default = None),  # ["artifact", None]
+        # All the artifacts that were used in order to compile this library
+        "compiling_classpath": provider_field(typing.Any, default = None),  # ["artifact"]
+        "generated_sources": provider_field(typing.Any, default = None),  # ["artifact"]
+        "lint_jar": provider_field(typing.Any, default = None),  # ["artifact"]
+        # If this library has a jar_postprocessor, this is the jar prior to post-processing.
+        # Otherwise, it is the same as library_output in JavaLibraryInfo.
+        "preprocessed_library": provider_field(typing.Any, default = None),  # ["artifact", None]
+        "used_jars_json": provider_field(typing.Any, default = None),  # ["artifact"]
+    },
+)
+
+JavaPackagingInfo = provider(
+    fields = {
+        # Presents all java dependencies used to build this library and it's dependencies (all transitive deps except provided ones).
+        # These deps must be included into the final artifact.
+        "packaging_deps": provider_field(typing.Any, default = None),  # ["JavaPackagingDepTSet", None],
+    },
+)
+
+JavaCompileOutputs = record(
+    full_library = Artifact,
+    class_abi = Artifact | None,
+    source_abi = Artifact | None,
+    source_only_abi = Artifact | None,
+    classpath_entry = JavaClasspathEntry,
+    annotation_processor_output = Artifact | None,
+    preprocessed_library = Artifact,
+    incremental_state_dir = Artifact | None,
+    used_jars_json = Artifact | None,
+)
+
+JavaProviders = record(
+    java_library_info = JavaLibraryInfo,
+    java_library_intellij_info = JavaLibraryIntellijInfo,
+    java_packaging_info = JavaPackagingInfo,
+    java_global_code_info = JavaGlobalCodeInfo,
+    shared_library_info = SharedLibraryInfo,
+    cxx_resource_info = ResourceInfo,
+    linkable_graph = LinkableGraph,
+    template_placeholder_info = TemplatePlaceholderInfo,
+    default_info = DefaultInfo,
+    class_to_src_map = [JavaClassToSourceMapInfo, None],
+    validation_info = [ValidationInfo, None],
+)
+
+def to_list(java_providers: JavaProviders) -> list[Provider]:
+    providers = [
+        java_providers.java_library_info,
+        java_providers.java_library_intellij_info,
+        java_providers.java_packaging_info,
+        java_providers.java_global_code_info,
+        java_providers.shared_library_info,
+        java_providers.cxx_resource_info,
+        java_providers.linkable_graph,
+        java_providers.template_placeholder_info,
+        java_providers.default_info,
+    ]
+    if java_providers.class_to_src_map != None:
+        providers.append(java_providers.class_to_src_map)
+
+    if java_providers.validation_info != None:
+        providers.append(java_providers.validation_info)
+
+    return providers
+
+# Creates a JavaCompileOutputs. `classpath_abi` can be set to specify a
+# specific artifact to be used as the abi for the JavaClasspathEntry.
+def make_compile_outputs(
+    full_library: Artifact,
+    preprocessed_library: Artifact,
+    class_abi: Artifact | None = None,
+    source_abi: Artifact | None = None,
+    source_only_abi: Artifact | None = None,
+    classpath_abi: Artifact | None = None,
+    classpath_abi_dir: Artifact | None = None,
+    required_for_source_only_abi: bool = False,
+    annotation_processor_output: Artifact | None = None,
+    incremental_state_dir: Artifact | None = None,
+    abi_jar_snapshot: Artifact | None = None,
+    used_jars_json: Artifact | None = None,
+) -> JavaCompileOutputs:
+    expect(classpath_abi != None or classpath_abi_dir == None, "A classpath_abi_dir should only be provided if a classpath_abi is provided!")
+    return JavaCompileOutputs(
+        full_library = full_library,
+        class_abi = class_abi,
+        source_abi = source_abi,
+        source_only_abi = source_only_abi,
+        classpath_entry = JavaClasspathEntry(
+            full_library = full_library,
+            abi = classpath_abi or class_abi or full_library,
+            abi_as_dir = classpath_abi_dir,
+            required_for_source_only_abi = required_for_source_only_abi,
+            abi_jar_snapshot = abi_jar_snapshot,
+        ),
+        annotation_processor_output = annotation_processor_output,
+        preprocessed_library = preprocessed_library,
+        incremental_state_dir = incremental_state_dir,
+        used_jars_json = used_jars_json,
+    )
+
+def create_abi(actions: AnalysisActions, class_abi_generator: Dependency, library: Artifact, keepSynthetic: bool = False) -> Artifact:
+    # It's possible for the library to be created in a subdir that is
+    # itself some actions output artifact, so we replace directory
+    # separators to get a path that we can uniquely own.
+    # TODO(cjhopman): This probably should take in the output path.
+    class_abi = actions.declare_output("{}-class-abi.jar".format(library.short_path.replace("/", "_")), has_content_based_path = True)
+    cmd = [
+        class_abi_generator[RunInfo],
+        library,
+        class_abi.as_output(),
+    ]
+    if keepSynthetic:
+        cmd.append("--keep-synthetic")
+    actions.run(
+        cmd,
+        category = "class_abi_generation",
+        identifier = library.short_path,
+    )
+    return class_abi
+
+ClasspathSnapshotGranularity = enum("CLASS_LEVEL", "CLASS_MEMBER_LEVEL")
+
+def generate_java_classpath_snapshot(
+    actions: AnalysisActions, snapshot_generator: Dependency | None, granularity: ClasspathSnapshotGranularity, library: Artifact, action_identifier: str | None
+) -> Artifact | None:
+    if not snapshot_generator:
+        return None
+    identifier = ("{}_".format(action_identifier) if action_identifier else "") + library.short_path.replace("/", "_").rsplit(".", 1)[
+        0
+    ]  # remove the extension and preserve any [foo.baz].[jar] or [thing-1.2.3.4].[jar] style names
+    output = actions.declare_output(
+        "{}_jar_snapshot_{}.bin".format(
+            identifier,
+            "cl" if ClasspathSnapshotGranularity("CLASS_LEVEL") == granularity else "cml",
+        ),
+        has_content_based_path = True,
+    )
+    actions.run(
+        [
+            snapshot_generator[RunInfo],
+            "--input-jar",
+            library,
+            "--output-snapshot",
+            output.as_output(),
+            "--granularity",
+            granularity.value,
+        ],
+        category = "jar_snapshot",
+        identifier = identifier,
+    )
+    return output
+
+def single_library_compiling_deps(actions: AnalysisActions, library_output: [JavaClasspathEntry, None]) -> [JavaCompilingDepsTSet, None]:
+    return get_compiling_deps_tset(actions, value = library_output)
+
+def get_compiling_deps_tset(
+    actions: AnalysisActions,
+    deps: list[Dependency] = [],
+    additional_classpath_entries: list[JavaCompilingDepsTSet] = [],
+    value: JavaClasspathEntry | None = None,
+) -> JavaCompilingDepsTSet | None:
+    """Create a classpath root with an optional value before its children."""
+    children = [info.compiling_deps for info in filter(None, [dep.get(JavaLibraryInfo) for dep in deps]) if info.compiling_deps != None]
+    children += additional_classpath_entries
+    if value != None:
+        return actions.tset(JavaCompilingDepsTSet, value = value, children = children)
+    if not children:
+        return None
+    if len(children) == 1:
+        return children[0]
+    return actions.tset(JavaCompilingDepsTSet, children = children)
+
+def single_library_compiling_deps_wrapper(actions: AnalysisActions, compiling_deps_tset: [JavaCompilingDepsTSet, None]) -> [JavaCompilingDepsTSetWrapper, None]:
+    if compiling_deps_tset:
+        return actions.tset(JavaCompilingDepsTSetWrapper, value = compiling_deps_tset)
+    else:
+        return None
+
+# Accumulate the wrappers required for propagating JavaCompilingDepsTSets up the graph.
+def derive_compiling_deps_wrapper(
+    actions: AnalysisActions, library_output: [JavaCompilingDepsTSetWrapper, None], children: list[Dependency]
+) -> [JavaCompilingDepsTSetWrapper, None]:
+    if children:
+        filtered_children = filter(
+            None,
+            [exported_dep.compiling_deps_wrapper for exported_dep in filter(None, [x.get(JavaLibraryInfo) for x in children])],
+        )
+        children = filtered_children
+
+    if not library_output and not children:
+        return None
+
+    return actions.tset(JavaCompilingDepsTSetWrapper, children = (children or []) + ([library_output] if library_output else []))
+
+def create_java_packaging_dep(
+    ctx: AnalysisContext,
+    library_jar: Artifact | None = None,
+    output_for_classpath_macro: Artifact | None = None,
+    # Defaults off because callers outside `create_java_library_providers` dex synthetic jars that
+    # hold only part of a nest (per-type R.java jars, canary classes), which D8 rejects when nest
+    # desugaring is on. Such jars have no cross-nest private access, so skipping is safe.
+    needs_desugar: bool = False,
+    desugar_deps: [TransitiveSetArgsProjection, None] = None,
+    is_prebuilt_jar: bool = False,
+    has_srcs: bool = True,
+    sources_jar: Artifact | None = None,
+    dex_weight_factor: int = 1,
+    proguard_config: Artifact | None = None,
+    gwt_module: Artifact | None = None,
+) -> JavaPackagingDep:
+    dex_toolchain = getattr(ctx.attrs, "_dex_toolchain", None)
+    if library_jar != None and has_srcs and dex_toolchain != None and ctx.attrs._dex_toolchain[DexToolchainInfo].d8_command != None:
+        dex = get_dex_produced_from_java_library(
+            ctx,
+            ctx.attrs._dex_toolchain[DexToolchainInfo],
+            library_jar,
+            needs_desugar,
+            desugar_deps,
+            dex_weight_factor,
+        )
+    else:
+        dex = None
+
+    expect(library_jar != None or output_for_classpath_macro != None, "Must provide an output_for_classpath_macro if no library_jar is provided!")
+
+    return JavaPackagingDep(
+        label = ctx.label,
+        jar = library_jar,
+        dex = dex,
+        gwt_module = gwt_module,
+        is_prebuilt_jar = is_prebuilt_jar,
+        proguard_config = proguard_config or getattr(ctx.attrs, "proguard_config", None),
+        output_for_classpath_macro = output_for_classpath_macro or library_jar,
+        sources_jar = sources_jar,
+    )
+
+def get_all_java_packaging_deps(ctx: AnalysisContext, deps: list[Dependency]) -> list[JavaPackagingDep]:
+    return get_all_java_packaging_deps_from_packaging_infos(ctx, filter(None, [x.get(JavaPackagingInfo) for x in deps]))
+
+def get_all_java_packaging_deps_from_packaging_infos(ctx: AnalysisContext, infos: list[JavaPackagingInfo]) -> list[JavaPackagingDep]:
+    children = filter(None, [info.packaging_deps for info in infos])
+    if not children:
+        return []
+
+    tset = ctx.actions.tset(JavaPackagingDepTSet, children = children)
+
+    return list(tset.traverse())
+
+def get_all_java_packaging_deps_tset(
+    ctx: AnalysisContext, java_packaging_infos: list[JavaPackagingInfo], java_packaging_dep: [JavaPackagingDep, None] = None
+) -> [JavaPackagingDepTSet, None]:
+    packaging_deps_kwargs = {}
+    if java_packaging_dep != None:
+        packaging_deps_kwargs["value"] = java_packaging_dep
+
+    packaging_deps_children = filter(None, [info.packaging_deps for info in java_packaging_infos])
+    if packaging_deps_children:
+        packaging_deps_kwargs["children"] = packaging_deps_children
+
+    return ctx.actions.tset(JavaPackagingDepTSet, **packaging_deps_kwargs) if packaging_deps_kwargs else None
+
+_EMPTY_JAVA_PACKAGING_INFO = JavaPackagingInfo(packaging_deps = None)
+
+# Accumulate deps necessary for packaging, which consist of all transitive java deps (except provided ones)
+def get_java_packaging_info(ctx: AnalysisContext, raw_deps: list[Dependency], java_packaging_dep: [JavaPackagingDep, None] = None) -> JavaPackagingInfo:
+    java_packaging_infos = filter(None, [x.get(JavaPackagingInfo) for x in raw_deps])
+    packaging_deps = get_all_java_packaging_deps_tset(ctx, java_packaging_infos, java_packaging_dep)
+    if packaging_deps == None:
+        return _EMPTY_JAVA_PACKAGING_INFO
+    return JavaPackagingInfo(packaging_deps = packaging_deps)
+
+def _group_global_code_children_by_name(global_code_infos: list[JavaGlobalCodeInfo]) -> dict[str, list[JavaCompilingDepsTSetWrapper]]:
+    # Collect the per-framework children from all global_code_infos in a single pass over the infos.
+    # Callers build a tset for many frameworks, so grouping once here avoids re-scanning every info
+    # for every framework, which would be O(frameworks * deps).
+    children_by_name = {}
+    for info in global_code_infos:
+        for name, child in info.global_code_map.items():
+            children_by_name.setdefault(name, []).append(child)
+
+    return children_by_name
+
+def _create_global_code_tset(actions: AnalysisActions, children: list[JavaCompilingDepsTSetWrapper]) -> [JavaCompilingDepsTSetWrapper, None]:
+    if not children:
+        return None
+    elif len(children) == 1:
+        return children[0]
+    else:
+        return actions.tset(JavaCompilingDepsTSetWrapper, children = children)
+
+# This function identifies and collects necessary dependencies that meet criteria defined in `GLOBAL_CODE_CONFIG` for global code generation across frameworks.
+# It maps framework names to their corresponding Java compiling dependency sets.
+# Example: Below configuration specifies criteria for the "di" framework:
+# GLOBAL_CODE_CONFIG = {
+#     "di": (
+#         triggers = ["//fbandroid/java/com/facebook/inject:inject"],
+#         deps = [],
+#         requires_first_order_classpath = False,
+#     ),
+# }
+# With this setup, if a target depends on "//fbandroid/java/com/facebook/inject:inject", the `global_code_info` provider for that target will have an entry under "di".
+# This entry will be a JavaCompilingDepsTSet containing the .jar files associated with that target.
+# Each framework (like "di") can use a Buck rule to identify dependencies with matching values for their framework key in the `global_code_info` provider.
+# They can then compile all the .jars needed for global code generation.
+
+def get_global_code_info(
+    ctx: AnalysisContext,
+    declared_deps: list[Dependency],
+    packaging_deps: list[Dependency],
+    single_library_dep: [JavaCompilingDepsTSetWrapper, None],
+    library_compiling_deps: [JavaCompilingDepsTSetWrapper, None],
+    first_order_compiling_deps_without_library_itself: list[JavaCompilingDepsTSetWrapper],
+    global_code_config: dict,
+) -> JavaGlobalCodeInfo:
+    global_code_infos = filter(None, [x.get(JavaGlobalCodeInfo) for x in packaging_deps])
+    children_by_name = _group_global_code_children_by_name(global_code_infos)
+
+    declared_deps_raw_targets = set([declared_dep.label.raw_target() for declared_dep in declared_deps])
+    raw_target = ctx.label.raw_target()
+
+    def declared_deps_contains_trigger(deps_triggers: set[TargetLabel]) -> TargetLabel | None:
+        for trigger in deps_triggers:
+            if trigger in declared_deps_raw_targets:
+                return trigger
+
+        return None
+
+    global_code_map = {}
+    for name, (config) in global_code_config.items():
+        target_is_global_code_dep = raw_target in config.deps
+        contains_trigger = None
+        if declared_deps_raw_targets and not target_is_global_code_dep:
+            contains_trigger = declared_deps_contains_trigger(config.triggers)
+        if (contains_trigger or target_is_global_code_dep) and config.requires_first_order_classpath:
+            global_code_library_compiling_deps = []
+            if single_library_dep:
+                global_code_library_compiling_deps.append(single_library_dep)
+            if first_order_compiling_deps_without_library_itself:
+                global_code_library_compiling_deps.extend(first_order_compiling_deps_without_library_itself)
+        elif target_is_global_code_dep:
+            global_code_library_compiling_deps = [library_compiling_deps]
+        elif contains_trigger:
+            if single_library_dep == None:
+                # We have to have single_library_dep - otherwise there is no output.
+                # This /should/ be a failure - however there are WAY too many places that do not follow this pattern to effectively fail here.
+                # fail("Target {} contains dep {} which is a 'trigger' for the global code rule {}, but the target does not produce any output. ".format(
+                #         ctx.label.raw_target(),
+                #         contains_trigger,
+                #         name,
+                #     ) +
+                #     "If the target does not export anything, it can be removed completely, or otherwise just remove all of the deps.")
+                global_code_library_compiling_deps = []
+            else:
+                global_code_library_compiling_deps = [single_library_dep]
+        else:
+            global_code_library_compiling_deps = []
+
+        children = list(children_by_name.get(name, []))
+        if global_code_library_compiling_deps:
+            children.extend(global_code_library_compiling_deps)
+
+        global_code_tset = _create_global_code_tset(ctx.actions, children)
+        if global_code_tset:
+            global_code_map[name] = global_code_tset
+
+    return JavaGlobalCodeInfo(global_code_map = global_code_map)
+
+def propagate_global_code_info(ctx: AnalysisContext, packaging_deps: list[Dependency]) -> JavaGlobalCodeInfo:
+    global_code_map = {}
+    global_code_infos = filter(None, [x.get(JavaGlobalCodeInfo) for x in packaging_deps])
+    children_by_name = _group_global_code_children_by_name(global_code_infos)
+
+    for key, children in children_by_name.items():
+        global_code_tset = _create_global_code_tset(ctx.actions, children)
+        if global_code_tset:
+            global_code_map[key] = global_code_tset
+
+    return JavaGlobalCodeInfo(global_code_map = global_code_map)
+
+def create_native_providers(ctx: AnalysisContext, label: Label, packaging_deps: list[Dependency]) -> (SharedLibraryInfo, ResourceInfo, LinkableGraph):
+    shared_library_info = merge_shared_libraries(
+        ctx.actions,
+        deps = filter(None, [x.get(SharedLibraryInfo) for x in packaging_deps]),
+    )
+    cxx_resource_info = make_resource_info(
+        gather_resources(
+            label,
+            deps = packaging_deps,
+        )
+    )
+
+    linkable_graph = create_linkable_graph(ctx, deps = filter(None, [x.get(LinkableGraph) for x in packaging_deps]))
+    return shared_library_info, cxx_resource_info, linkable_graph
+
+def _create_non_template_providers(
+    ctx: AnalysisContext,
+    library_output: [JavaClasspathEntry, None],
+    global_code_config,
+    declared_deps: list[Dependency] = [],
+    provided_deps: list[Dependency] = [],
+    exported_deps: list[Dependency] = [],
+    exported_provided_deps: list[Dependency] = [],
+    runtime_deps: list[Dependency] = [],
+    needs_desugar: bool = True,
+    desugar_classpath: [TransitiveSetArgsProjection, None] = None,
+    is_prebuilt_jar: bool = False,
+    has_srcs: bool = True,
+    sources_jar: Artifact | None = None,
+    proguard_config: Artifact | None = None,
+    gwt_module: Artifact | None = None,
+    dex_weight_factor: int = 1,
+) -> (JavaLibraryInfo, JavaPackagingInfo, JavaGlobalCodeInfo, SharedLibraryInfo, ResourceInfo, LinkableGraph):
+    """Creates java library providers of type `JavaLibraryInfo` and `JavaPackagingInfo`.
+
+    Args:
+        library_output: optional JavaClasspathEntry that represents library output
+        declared_deps: declared dependencies (usually comes from `deps` field of the rule)
+        exported_deps: dependencies that are exposed to dependent rules as compiling deps
+        exported_provided_deps: dependencies that are are exposed to dependent rules and not be included into packaging
+        runtime_deps: dependencies that are used for packaging only
+    """
+    packaging_deps = declared_deps + exported_deps + runtime_deps
+    for dep in packaging_deps:
+        if JavaLibraryInfo in dep and dep[JavaLibraryInfo].may_not_be_packaged:
+            fail(
+                "{} has 'may_not_be_packaged' label but is present in {}. If you need to use it in order to build the library, move it into 'provided_deps'".format(
+                    dep.label.raw_target(),
+                    ctx.label.raw_target(),
+                )
+            )
+    shared_library_info, cxx_resource_info, linkable_graph = create_native_providers(ctx, ctx.label, packaging_deps)
+
+    output_for_classpath_macro = (
+        library_output.abi
+        if (library_output and library_output.abi.owner != None)
+        else ctx.actions.write("dummy_output_for_classpath_macro.txt", "Unused", has_content_based_path = False)
+    )
+    java_packaging_dep = create_java_packaging_dep(
+        ctx,
+        library_output.full_library if library_output else None,
+        output_for_classpath_macro,
+        needs_desugar,
+        desugar_classpath,
+        is_prebuilt_jar,
+        has_srcs,
+        sources_jar,
+        proguard_config = proguard_config,
+        gwt_module = gwt_module,
+        dex_weight_factor = dex_weight_factor,
+    )
+
+    java_packaging_info = get_java_packaging_info(
+        ctx,
+        raw_deps = packaging_deps,
+        java_packaging_dep = java_packaging_dep,
+    )
+
+    single_library = single_library_compiling_deps(ctx.actions, library_output)
+
+    single_library_wrapper = single_library_compiling_deps_wrapper(ctx.actions, single_library)
+    compiling_deps_wrapper = derive_compiling_deps_wrapper(ctx.actions, single_library_wrapper, exported_deps + exported_provided_deps)
+    first_order_compiling_deps_wrappers_without_library_itself = filter(
+        None,
+        [
+            exported_dep.compiling_deps_wrapper
+            for exported_dep in filter(None, [x.get(JavaLibraryInfo) for x in declared_deps + exported_deps + provided_deps + exported_provided_deps])
+        ],
+    )
+
+    global_code_info = get_global_code_info(
+        ctx,
+        declared_deps,
+        packaging_deps,
+        single_library_wrapper,
+        compiling_deps_wrapper,
+        first_order_compiling_deps_wrappers_without_library_itself,
+        global_code_config,
+    )
+
+    compiling_deps = get_compiling_deps_tset(
+        ctx.actions,
+        exported_deps + exported_provided_deps,
+        [single_library] if single_library else [],
+    )
+
+    return (
+        JavaLibraryInfo(
+            compiling_deps = compiling_deps,
+            compiling_deps_wrapper = compiling_deps_wrapper,
+            library_output = library_output,
+            output_for_classpath_macro = output_for_classpath_macro,
+            may_not_be_exported = "may_not_be_exported" in (ctx.attrs.labels or []),
+            may_not_be_packaged = "may_not_be_packaged" in (ctx.attrs.labels or []),
+        ),
+        java_packaging_info,
+        global_code_info,
+        shared_library_info,
+        cxx_resource_info,
+        linkable_graph,
+    )
+
+def create_template_info(ctx: AnalysisContext, packaging_info: JavaPackagingInfo, first_order_classpath_libs: list[Artifact]) -> TemplatePlaceholderInfo:
+    return TemplatePlaceholderInfo(
+        keyed_variables = {
+            "classpath": cmd_args(packaging_info.packaging_deps.project_as_args("full_jar_args"), delimiter = get_path_separator_for_exec_os(ctx))
+            if packaging_info.packaging_deps
+            else cmd_args(),
+            "classpath_including_targets_with_no_output": cmd_args(
+                packaging_info.packaging_deps.project_as_args("args_for_classpath_macro"), delimiter = get_path_separator_for_exec_os(ctx)
+            ),
+            "first_order_classpath": cmd_args(first_order_classpath_libs, delimiter = get_path_separator_for_exec_os(ctx)),
+        }
+    )
+
+def create_java_library_providers(
+    ctx: AnalysisContext,
+    library_output: [JavaClasspathEntry, None],
+    global_code_config,
+    declared_deps: list[Dependency] = [],
+    exported_deps: list[Dependency] = [],
+    provided_deps: list[Dependency] = [],
+    exported_provided_deps: list[Dependency] = [],
+    runtime_deps: list[Dependency] = [],
+    needs_desugar: bool = True,
+    is_prebuilt_jar: bool = False,
+    has_srcs: bool = True,
+    sources_jar: Artifact | None = None,
+    generated_sources: list[Artifact] = [],
+    annotation_jars_dir: Artifact | None = None,
+    proguard_config: Artifact | None = None,
+    gwt_module: Artifact | None = None,
+    lint_jar: Artifact | None = None,
+    preprocessed_library: Artifact | None = None,
+    used_jars_json: Artifact | None = None,
+    dex_weight_factor: int = 1,
+) -> (JavaLibraryInfo, JavaPackagingInfo, JavaGlobalCodeInfo, SharedLibraryInfo, ResourceInfo, LinkableGraph, TemplatePlaceholderInfo, JavaLibraryIntellijInfo):
+    first_order_classpath_deps = filter(None, [x.get(JavaLibraryInfo) for x in declared_deps + exported_deps + runtime_deps])
+    first_order_classpath_libs = [dep.output_for_classpath_macro for dep in first_order_classpath_deps]
+
+    compiling_deps = get_compiling_deps_tset(ctx.actions, declared_deps + exported_deps + provided_deps + exported_provided_deps)
+    desugar_classpath = compiling_deps.project_as_args("full_library_args") if needs_desugar and compiling_deps != None else None
+
+    library_info, packaging_info, global_code_info, shared_library_info, cxx_resource_info, linkable_graph = _create_non_template_providers(
+        ctx,
+        library_output = library_output,
+        global_code_config = global_code_config,
+        declared_deps = declared_deps,
+        provided_deps = provided_deps,
+        exported_deps = exported_deps,
+        exported_provided_deps = exported_provided_deps,
+        runtime_deps = runtime_deps,
+        needs_desugar = needs_desugar,
+        desugar_classpath = desugar_classpath,
+        is_prebuilt_jar = is_prebuilt_jar,
+        has_srcs = has_srcs,
+        sources_jar = sources_jar,
+        proguard_config = proguard_config,
+        gwt_module = gwt_module,
+        dex_weight_factor = dex_weight_factor,
+    )
+
+    first_order_libs = first_order_classpath_libs + [library_info.library_output.full_library] if library_info.library_output else first_order_classpath_libs
+    template_info = create_template_info(ctx, packaging_info, first_order_libs)
+
+    intellij_info = JavaLibraryIntellijInfo(
+        compiling_classpath = [dep.full_library for dep in (list(compiling_deps.traverse()) if compiling_deps else [])],
+        generated_sources = generated_sources,
+        annotation_jars_dir = annotation_jars_dir,
+        lint_jar = lint_jar,
+        preprocessed_library = preprocessed_library,
+        used_jars_json = used_jars_json,
+    )
+
+    return (library_info, packaging_info, global_code_info, shared_library_info, cxx_resource_info, linkable_graph, template_info, intellij_info)
diff --git a/buck2/prelude/java/java_resources.bzl b/buck2/prelude/java/java_resources.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/java_resources.bzl
@@ -0,0 +1,71 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+
+# Infer the likely package name for the given path based on conventional
+# source root components.
+def get_src_package(src_root_prefixes: list[str], src_root_elements: list[str], path: str) -> str:
+    for prefix in src_root_prefixes:
+        if path.startswith(prefix):
+            return paths.relativize(
+                path,
+                prefix,
+            )
+    parts = path.split("/")
+    for i in range(len(parts) - 2, -1, -1):
+        part = parts[i]
+        if part in src_root_elements:
+            return "/".join(parts[i + 1 :])
+
+    return path
+
+def get_resources_map(java_toolchain: JavaToolchainInfo, package: str, resources: list[Artifact], resources_root: [str, None]) -> dict[str, Artifact]:
+    # As in v1, root the resource root via the current package.
+    if resources_root != None:
+        resources_root = paths.normalize(paths.join(package, resources_root))
+
+    resources_to_copy = {}
+    for resource in resources:
+        # Create the full resource path.
+        full_resource = paths.join(
+            resource.owner.package if resource.owner else package,
+            resource.short_path,
+        )
+
+        # As in v1 (https://fburl.com/code/j2vwny56, https://fburl.com/code/9era0xpz),
+        # if this resource starts with the resource root, relativize and insert it as
+        # is.
+        if resources_root != None and paths.starts_with(full_resource, resources_root):
+            resource_name = paths.relativize(
+                full_resource,
+                resources_root,
+            )
+            if not resource_name:
+                # Match v1 behavior: https://fburl.com/code/x7zhlz5m
+                resource_name = resource.short_path
+        else:
+            resource_name = get_src_package(java_toolchain.src_root_prefixes, java_toolchain.src_root_elements, full_resource)
+        resources_to_copy[resource_name] = resource
+    return resources_to_copy
+
+def parse_src_roots(src_roots: list[str]) -> (list[str], list[str]):
+    prefixes = []
+    elements = []
+    for src_root in src_roots:
+        if src_root.startswith("/"):
+            if not src_root.endswith("/"):
+                fail("Elements in java.src_roots config that begin with a / must end in one too, but {} does not".format(src_root))
+            prefixes.append(src_root[1:])
+        elif "/" in src_root:
+            fail("No / is permitted in java.src_roots config elements, but {} has one".format(src_root))
+        else:
+            elements.append(src_root)
+
+    return elements, prefixes
diff --git a/buck2/prelude/java/java_test.bzl b/buck2/prelude/java/java_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/java_test.bzl
@@ -0,0 +1,226 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//java:class_to_srcs.bzl",
+    "JavaClassToSourceMapInfo",  # @unused Used as a type
+    "merge_class_to_source_map_from_jar",
+)
+load("@prelude//java:java_library.bzl", "build_java_library", "jvm_target_stats")
+load("@prelude//java:java_providers.bzl", "JavaLibraryInfo", "JavaPackagingInfo", "get_all_java_packaging_deps_tset")
+load("@prelude//java:java_toolchain.bzl", "JavaTestToolchainInfo", "JavaToolchainInfo")
+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "create_shlib_symlink_tree",
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+)
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+load(
+    "@prelude//tests:re_utils.bzl",
+    "get_re_executors_from_props",
+)
+load("@prelude//tests:test_listing.bzl", "TestListingInfo")
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load("@prelude//utils:expect.bzl", "expect")
+
+def java_test_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs._build_only_native_code:
+        return [DefaultInfo()]
+
+    target_stats_providers, target_stats_subtargets = jvm_target_stats(ctx)
+    java_providers = build_java_library(
+        ctx,
+        ctx.attrs.srcs,
+        extra_sub_targets = target_stats_subtargets,
+    )
+    external_runner_test_info = build_junit_test(ctx, java_providers.java_library_info, java_providers.java_packaging_info, java_providers.class_to_src_map)
+
+    providers = [
+        java_providers.java_library_intellij_info,
+        java_providers.java_library_info,
+        java_providers.java_packaging_info,
+        java_providers.template_placeholder_info,
+        java_providers.default_info,
+        java_providers.class_to_src_map,
+    ]
+    if java_providers.validation_info:
+        providers.append(java_providers.validation_info)
+    providers.extend(target_stats_providers)
+
+    return inject_test_run_info(ctx, external_runner_test_info) + providers
+
+def build_junit_test(
+    ctx: AnalysisContext,
+    tests_java_library_info: JavaLibraryInfo,
+    tests_java_packaging_info: JavaPackagingInfo,
+    tests_class_to_source_info: [JavaClassToSourceMapInfo, None] = None,
+    extra_cmds: list = [],
+    extra_classpath_entries: list[Artifact] = [],
+) -> ExternalRunnerTestInfo:
+    java_test_toolchain = ctx.attrs._java_test_toolchain[JavaTestToolchainInfo]
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+
+    java = ctx.attrs.java[RunInfo] if ctx.attrs.java else java_toolchain.java_for_tests
+
+    cmd = [java] + extra_cmds + ctx.attrs.vm_args + ["-XX:-MaxFDLimit"]
+    if java_test_toolchain.jvm_args:
+        cmd.extend(java_test_toolchain.jvm_args)
+
+    cmd.append(cmd_args(ctx.attrs.java_agents, format = "-javaagent:{}"))
+
+    classpath = (
+        [
+            java_test_toolchain.test_runner_library_jar,
+        ]
+        + [
+            get_all_java_packaging_deps_tset(ctx, java_packaging_infos = [tests_java_packaging_info]).project_as_args("full_jar_args", ordering = "bfs"),
+        ]
+        + extra_classpath_entries
+    )
+
+    if ctx.attrs.unbundled_resources_root:
+        classpath.append(ctx.attrs.unbundled_resources_root)
+
+    labels = ctx.attrs.labels or []
+
+    # Setup RE executors based on the `remote_execution` param.
+    re_executors = get_re_executors_from_props(ctx)
+
+    # We implicitly make the target run from the project root if remote
+    # execution options were specified.
+    run_from_cell_root = "buck2_run_from_cell_root" in labels
+
+    uses_java8 = "run_with_java8" in labels
+
+    relative_to = {"relative_to": ctx.label.cell_root} if run_from_cell_root else {}
+
+    if uses_java8:
+        # Java 8 does not support using argfiles, and these tests can have huge classpaths so we need another
+        # mechanism to write the classpath to a file.
+        # We add "FileClassPathRunner" to the classpath, and then write a line-separated classpath file which we pass
+        # to the "FileClassPathRunner" as a system variable. The "FileClassPathRunner" then loads all the jars
+        # from that file onto the classpath, and delegates running the test to the junit test runner.
+        cmd.extend(["-classpath", cmd_args(java_test_toolchain.test_runner_library_jar)])
+        classpath_args = cmd_args(cmd_args(classpath), **relative_to)
+        classpath_args_file = ctx.actions.write("classpath_args_file", classpath_args, has_content_based_path = False)
+        cmd.append(
+            cmd_args(
+                classpath_args_file,
+                format = "-Dbuck.classpath_file={}",
+                hidden = classpath_args,
+            )
+        )
+    else:
+        # Java 9+ supports argfiles, so just write the classpath to an argsfile. "FileClassPathRunner" will delegate
+        # immediately to the junit test runner.
+        classpath_args = cmd_args("-classpath", cmd_args(classpath, delimiter = get_path_separator_for_exec_os(ctx)), **relative_to)
+        cmd.append(at_argfile(actions = ctx.actions, name = "classpath_args_file", args = classpath_args))
+
+    if ctx.attrs.test_type == "junit5":
+        cmd.extend(java_test_toolchain.junit5_test_runner_main_class_args)
+    elif ctx.attrs.test_type == "testng":
+        cmd.extend(java_test_toolchain.testng_test_runner_main_class_args)
+    else:
+        cmd.extend(java_test_toolchain.junit_test_runner_main_class_args)
+
+    if ctx.attrs.test_case_timeout_ms:
+        cmd.extend(["--default-test-timeout", str(ctx.attrs.test_case_timeout_ms)])
+
+    if ctx.attrs.test_class_names_file and getattr(ctx.attrs, "discover_all_test_classes", False):
+        fail("Cannot set both test_class_names_file and discover_all_test_classes")
+
+    if ctx.attrs.test_class_names_file:
+        class_names = ctx.attrs.test_class_names_file
+    else:
+        expect(tests_java_library_info.library_output != None, "Built test library has no output, likely due to missing srcs")
+        class_names = ctx.actions.declare_output("class_names", has_content_based_path = False)
+        discover_all = getattr(ctx.attrs, "discover_all_test_classes", False)
+        list_class_names_args = [
+            java_test_toolchain.list_class_names[RunInfo],
+            "--jar",
+            tests_java_library_info.library_output.full_library,
+            "--sources",
+            ctx.actions.write("sources.txt", [] if discover_all else ctx.attrs.srcs, has_content_based_path = False),
+            "--output",
+            class_names.as_output(),
+        ]
+        if discover_all:
+            list_class_names_args.append("--discover-all")
+        list_class_names_cmd = cmd_args(list_class_names_args, hidden = ctx.attrs.srcs)
+        ctx.actions.run(list_class_names_cmd, category = "list_class_names")
+
+    cmd.extend(["--test-class-names-file", class_names])
+
+    native_libs_env = _get_native_libs_env(ctx)
+    env = {}
+    for d in [ctx.attrs.env, native_libs_env]:
+        for key, value in d.items():
+            if key in env:
+                fail("Duplicate key for java_test env: '{}'".format(key))
+            env[key] = value
+
+    if tests_class_to_source_info != None:
+        transitive_class_to_src_map = merge_class_to_source_map_from_jar(
+            actions = ctx.actions,
+            name = ctx.label.name + ".transitive_class_to_src.json",
+            java_toolchain = java_toolchain,
+            relative_to = ctx.label.cell_root if run_from_cell_root else None,
+            deps = [tests_class_to_source_info],
+        )
+        if run_from_cell_root:
+            transitive_class_to_src_map = cmd_args(transitive_class_to_src_map, relative_to = ctx.label.cell_root)
+        env["JACOCO_CLASSNAME_SOURCE_MAP"] = transitive_class_to_src_map
+
+    list_tests_info = ctx.attrs._java_test_toolchain[TestListingInfo]
+    list_tests = list_tests_info.list_tests
+    if list_tests != None and "tpx:supports_static_listing=true" in ctx.attrs.labels and "tpx:supports_static_listing=false" not in ctx.attrs.labels:
+        list_tests_command = cmd_args([
+            list_tests[RunInfo],
+            "list-tests",
+            "--sources-file",
+            ctx.actions.write("source_files.txt", ctx.attrs.srcs, with_inputs = True, has_content_based_path = False),
+        ])
+        env["TPX_LIST_TESTS_COMMAND"] = list_tests_command
+
+    test_info_type = getattr(ctx.attrs, "test_info_type", None) or "junit"
+    test_info = ExternalRunnerTestInfo(
+        type = test_info_type,
+        command = cmd,
+        env = env,
+        labels = ctx.attrs.labels,
+        contacts = ctx.attrs.contacts,
+        run_from_project_root = not run_from_cell_root,
+        use_project_relative_paths = not run_from_cell_root,
+        default_executor = re_executors.default_executor,
+        executor_overrides = re_executors.executor_overrides,
+        supports_test_execution_caching = ctx.attrs.supports_test_execution_caching,
+    )
+    return test_info
+
+def _get_native_libs_env(ctx: AnalysisContext) -> dict:
+    if not ctx.attrs.use_cxx_libraries:
+        return {}
+
+    deps_to_search = ctx.attrs.cxx_library_allowlist or ctx.attrs.deps
+    shared_library_infos = filter(None, [x.get(SharedLibraryInfo) for x in deps_to_search])
+
+    shared_library_info = merge_shared_libraries(
+        ctx.actions,
+        deps = shared_library_infos,
+    )
+
+    cxx_library_symlink_tree = create_shlib_symlink_tree(
+        actions = ctx.actions,
+        out = "cxx_library_symlink_tree",
+        shared_libs = traverse_shared_library_info(shared_library_info, transformation_provider = None),
+    )
+
+    return {"BUCK_LD_SYMLINK_TREE": cxx_library_symlink_tree}
diff --git a/buck2/prelude/java/java_toolchain.bzl b/buck2/prelude/java/java_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/java_toolchain.bzl
@@ -0,0 +1,122 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+AbiGenerationMode = enum("class", "none", "source", "source_only")
+
+DepFiles = enum("none", "per_class", "per_jar")
+
+JavacProtocol = enum("classic", "javacd")
+
+JavaPlatformInfo = provider(
+    doc = "Java platform info",
+    fields = {
+        "name": provider_field(typing.Any, default = None),
+    },
+)
+
+JavaToolchainInfo = provider(
+    doc = "Java toolchain info",
+    fields = {
+        "abi_generation_mode": provider_field(typing.Any, default = None),
+        "bootclasspath_7": provider_field(typing.Any, default = None),
+        "bootclasspath_8": provider_field(typing.Any, default = None),
+        "class_abi_generator": provider_field(typing.Any, default = None),
+        "class_loader_bootstrapper": provider_field(typing.Any, default = None),
+        "compile_and_package": provider_field(typing.Any, default = None),
+        "cp_snapshot_generator": provider_field(typing.Any, default = None),
+        "dep_files": provider_field(typing.Any, default = None),
+        "fat_jar": provider_field(typing.Any, default = None),
+        "fat_jar_main_class_lib": provider_field(typing.Any, default = None),
+        "gen_class_to_source_map": provider_field(typing.Any, default = None),
+        "gen_class_to_source_map_debuginfo": provider_field(typing.Any, default = None),  # optional
+        "gen_class_to_source_map_include_sourceless_compiled_packages": provider_field(typing.Any, default = None),
+        "global_code_config": provider_field(typing.Any, default = None),
+        "is_bootstrap_toolchain": provider_field(typing.Any, default = None),
+        "jar": provider_field(typing.Any, default = None),
+        "jar_builder": provider_field(typing.Any, default = None),
+        "java": provider_field(typing.Any, default = None),
+        "java_base_jar": provider_field(typing.Any, default = None),
+        "java_error_handler": provider_field(typing.Any, default = None),
+        "java_for_tests": provider_field(typing.Any, default = None),
+        # Major version of the JDK that `java` points at, or None when that is not known
+        # (for example when a toolchain supplies its own `java` binary).
+        "java_runtime_version": provider_field(typing.Any, default = None),
+        "javac": provider_field(typing.Any, default = None),
+        "javac_protocol": provider_field(typing.Any, default = None),
+        "javacd": provider_field(typing.Any, default = None),
+        "javacd_debug_port": provider_field(typing.Any, default = None),
+        "javacd_debug_target": provider_field(typing.Any, default = None),
+        "javacd_jvm_args": provider_field(typing.Any, default = None),
+        "javacd_jvm_args_target": provider_field(typing.Any, default = None),
+        "javacd_main_class": provider_field(typing.Any, default = None),
+        "javacd_remote_worker": provider_field(typing.Any, default = None),
+        "javacd_worker": provider_field(typing.Any, default = None),
+        "jlink": provider_field(typing.Any, default = None),
+        "jmod": provider_field(typing.Any, default = None),
+        "jrt_fs_jar": provider_field(typing.Any, default = None),
+        "merge_class_to_source_maps": provider_field(typing.Any, default = None),
+        "nullsafe": provider_field(typing.Any, default = None),
+        "nullsafe_extra_args": provider_field(typing.Any, default = None),
+        "nullsafe_signatures": provider_field(typing.Any, default = None),
+        "postprocessor_runner": provider_field(typing.Any, default = None),
+        "proguard_jar": provider_field(typing.Any, default = None),
+        "proguard_max_heap_size": provider_field(typing.Any, default = None),
+        "semanticdb_javac": provider_field(typing.Any, default = None),
+        "semanticdb_sourceroot": provider_field(typing.Any, default = None),
+        "source_level": provider_field(typing.Any, default = None),
+        "src_root_elements": provider_field(typing.Any, default = None),
+        "src_root_prefixes": provider_field(typing.Any, default = None),
+        "target_level": provider_field(typing.Any, default = None),
+        "target_stats_tools": provider_field(typing.Any, default = None),
+        "track_class_usage": provider_field(bool, default = True),
+        "uses_content_based_paths": provider_field(bool, default = True),
+        "zip_scrubber": provider_field(typing.Any, default = None),
+    },
+)
+
+def unsafe_memory_access_jvm_args(java_runtime_version: [int, None]) -> list[str]:
+    """
+    JVM args that keep the compiler daemon from warning about protobuf-java's use of
+    sun.misc.Unsafe.
+
+    protobuf-java, which carries the daemon's command protocol, calls
+    sun.misc.Unsafe::arrayBaseOffset from a static initializer. JDK 24 and up print a
+    terminal-deprecation warning for that call, and it lands in the stderr buck2 reports
+    for a failed compilation. No protobuf-java release has dropped the call, so the
+    warning has to be turned off at the JVM. The option does not exist before JDK 24,
+    where passing it stops the JVM from starting at all.
+    """
+    if java_runtime_version != None and java_runtime_version >= 24:
+        return ["--sun-misc-unsafe-memory-access=allow"]
+    return []
+
+JavaTestToolchainInfo = provider(
+    doc = "Java test toolchain info",
+    fields = {
+        "junit5_test_runner_main_class_args": provider_field(typing.Any, default = None),
+        "junit_test_runner_main_class_args": provider_field(typing.Any, default = None),
+        "jvm_args": provider_field(typing.Any, default = None),
+        "list_class_names": provider_field(typing.Any, default = None),
+        "test_runner_library_jar": provider_field(typing.Any, default = None),
+        "testng_test_runner_main_class_args": provider_field(typing.Any, default = None),
+    },
+)
+
+# prebuilt_jar needs so little of the Java toolchain that it's worth
+# giving it its own to reduce the occurrence of cycles as we add
+# more Java- and Kotlin-built tools to the Java and Kotlin toolchains
+PrebuiltJarToolchainInfo = provider(
+    doc = "prebuilt_jar toolchain info",
+    fields = {
+        "class_abi_generator": provider_field(typing.Any, default = None),
+        "cp_snapshot_generator": provider_field(typing.Any, default = None),
+        "global_code_config": provider_field(typing.Any, default = None),
+        "is_bootstrap_toolchain": provider_field(typing.Any, default = None),
+        "java": provider_field(typing.Any, default = None),
+    },
+)
diff --git a/buck2/prelude/java/javacd_jar_creator.bzl b/buck2/prelude/java/javacd_jar_creator.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/javacd_jar_creator.bzl
@@ -0,0 +1,386 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//java:java_providers.bzl",
+    "ClasspathSnapshotGranularity",
+    "JavaCompileOutputs",  # @unused Used as a type
+    "JavaCompilingDepsTSet",  # @unused Used as a type
+    "generate_java_classpath_snapshot",
+    "get_compiling_deps_tset",
+    "make_compile_outputs",
+)
+load("@prelude//java:java_resources.bzl", "get_resources_map")
+load(
+    "@prelude//java:java_toolchain.bzl",
+    "AbiGenerationMode",  # @unused Used as a type
+    "DepFiles",
+    "JavaToolchainInfo",  # @unused Used as a type
+)
+load(
+    "@prelude//java/plugins:java_annotation_processor.bzl",
+    "AnnotationProcessorProperties",  # @unused Used as a type
+)
+load(
+    "@prelude//java/plugins:java_plugin.bzl",
+    "PluginParams",  # @unused Used as a type
+)
+load(
+    "@prelude//java/utils:java_utils.bzl",
+    "CustomJdkInfo",  # @unused Used as a type
+    "build_bootclasspath",
+)
+load(
+    "@prelude//jvm:cd_jar_creator_util.bzl",
+    "BuildMode",
+    "OutputPaths",
+    "TargetType",
+    "base_qualified_name",
+    "declare_prefixed_output",
+    "define_output_paths",
+    "encode_command",
+    "generate_abi_jars",
+    "get_abi_generation_mode",
+    "prepare_cd_exe",
+    "prepare_final_jar",
+    "setup_dep_files",
+)
+load("@prelude//utils:expect.bzl", "expect")
+
+def create_jar_artifact_javacd(
+    ctx: AnalysisContext,
+    actions_identifier: [str, None],
+    abi_generation_mode: [AbiGenerationMode, None],
+    java_toolchain: JavaToolchainInfo,
+    label,
+    output: Artifact | None,
+    javac_tool: [typing.Any, None],
+    srcs: list[Artifact],
+    remove_classes: list[str],
+    resources: list[Artifact],
+    resources_root: [str, None],
+    manifest_file: Artifact | None,
+    annotation_processor_properties: AnnotationProcessorProperties,
+    plugin_params: [PluginParams, None],
+    source_level: int,
+    target_level: int,
+    deps: list[Dependency],
+    required_for_source_only_abi: bool,
+    source_only_abi_deps: list[Dependency],
+    extra_arguments: cmd_args,
+    additional_classpath_entries: JavaCompilingDepsTSet | None,
+    additional_compiled_srcs: Artifact | None,
+    custom_jdk_info: CustomJdkInfo | None,
+    is_building_android_binary: bool,
+    is_creating_subtarget: bool = False,
+    debug_port: [int, None] = None,
+    enable_depfiles: [bool, None] = True,
+) -> JavaCompileOutputs:
+    if javac_tool != None:
+        fail("cannot set explicit javac on library when using javacd")
+
+    actions = ctx.actions
+    resources_map = get_resources_map(java_toolchain, label.package, resources, resources_root)
+
+    custom_bootclasspath = custom_jdk_info.bootclasspath if custom_jdk_info else []
+    bootclasspath_entries = build_bootclasspath(custom_bootclasspath, source_level, java_toolchain)
+    abi_generation_mode = get_abi_generation_mode(abi_generation_mode, java_toolchain, srcs, annotation_processor_properties)
+
+    uses_content_based_paths = java_toolchain.uses_content_based_paths
+
+    should_create_class_abi = (
+        not additional_compiled_srcs and not is_creating_subtarget and (abi_generation_mode == AbiGenerationMode("class") or not is_building_android_binary)
+    )
+    if should_create_class_abi:
+        class_abi_jar = declare_prefixed_output(actions, actions_identifier, "class-abi.jar", uses_content_based_paths)
+        class_abi_output_dir = declare_prefixed_output(actions, actions_identifier, "class_abi_dir", uses_content_based_paths, dir = True)
+    else:
+        class_abi_jar = None
+        class_abi_output_dir = None
+
+    output_paths = define_output_paths(actions, actions_identifier, label, uses_content_based_paths)
+
+    compiling_deps_tset = get_compiling_deps_tset(actions, deps, [additional_classpath_entries] if additional_classpath_entries else [])
+
+    track_class_usage = java_toolchain.track_class_usage and enable_depfiles
+    define_javacd_action = partial(
+        _define_javacd_action,
+        actions,
+        java_toolchain,
+        should_create_class_abi,
+        class_abi_jar,
+        class_abi_output_dir,
+        srcs,
+        track_class_usage,
+        debug_port,
+        uses_content_based_paths,
+    )
+    library_classpath_jars_tag = actions.artifact_tag()
+    command_builder = _command_builder(
+        label = label,
+        srcs = srcs,
+        remove_classes = remove_classes,
+        annotation_processor_properties = annotation_processor_properties,
+        plugin_params = plugin_params,
+        manifest_file = manifest_file,
+        source_level = source_level,
+        target_level = target_level,
+        compiling_deps_tset = compiling_deps_tset,
+        bootclasspath_entries = bootclasspath_entries,
+        system_image = custom_jdk_info.system_image if custom_jdk_info else None,
+        abi_generation_mode = abi_generation_mode,
+        resources_map = resources_map,
+        extra_arguments = extra_arguments,
+        use_abi_dirs = bool(not is_creating_subtarget and srcs and track_class_usage and java_toolchain.dep_files == DepFiles("per_class")),
+    )
+    command = command_builder(
+        build_mode = BuildMode("LIBRARY"),
+        target_type = TargetType("library"),
+        output_paths = output_paths,
+        classpath_jars_tag = library_classpath_jars_tag,
+        source_only_abi_compiling_deps = None,
+        track_class_usage = track_class_usage,
+    )
+    used_jars_json = define_javacd_action(
+        category_prefix = "",
+        actions_identifier = actions_identifier,
+        encoded_command = command,
+        qualified_name = base_qualified_name(label),
+        output_paths = output_paths,
+        classpath_jars_tag = library_classpath_jars_tag,
+        abi_dir = class_abi_output_dir if should_create_class_abi else None,
+        target_type = TargetType("library"),
+        is_creating_subtarget = is_creating_subtarget,
+    )
+    jar_postprocessor = ctx.attrs.jar_postprocessor[RunInfo] if hasattr(ctx.attrs, "jar_postprocessor") and ctx.attrs.jar_postprocessor else None
+    final_jar_output = prepare_final_jar(
+        actions = actions,
+        actions_identifier = actions_identifier,
+        output = output,
+        output_paths = output_paths,
+        additional_compiled_srcs = additional_compiled_srcs,
+        jar_builder = java_toolchain.jar_builder,
+        jar_postprocessor = jar_postprocessor,
+        jar_postprocessor_runner = java_toolchain.postprocessor_runner[RunInfo] if java_toolchain.postprocessor_runner else None,
+        zip_scrubber = java_toolchain.zip_scrubber,
+        uses_content_based_paths = uses_content_based_paths,
+    )
+
+    if not is_creating_subtarget:
+        class_abi, source_abi, source_only_abi, classpath_abi, classpath_abi_dir = generate_abi_jars(
+            actions = actions,
+            actions_identifier = actions_identifier,
+            label = label,
+            abi_generation_mode = abi_generation_mode,
+            additional_compiled_srcs = additional_compiled_srcs,
+            is_building_android_binary = is_building_android_binary,
+            class_abi_generator = java_toolchain.class_abi_generator,
+            final_jar = final_jar_output.final_jar,
+            compiling_deps_tset = compiling_deps_tset,
+            source_only_abi_deps = source_only_abi_deps,
+            class_abi_jar = class_abi_jar,
+            class_abi_output_dir = class_abi_output_dir,
+            track_class_usage = track_class_usage,
+            encode_abi_command = command_builder,
+            define_action = define_javacd_action,
+            uses_content_based_paths = uses_content_based_paths,
+        )
+
+        abi_jar_snapshot = generate_java_classpath_snapshot(
+            ctx.actions, java_toolchain.cp_snapshot_generator, ClasspathSnapshotGranularity("CLASS_MEMBER_LEVEL"), classpath_abi, actions_identifier
+        )
+        result = make_compile_outputs(
+            full_library = final_jar_output.final_jar,
+            preprocessed_library = final_jar_output.preprocessed_jar,
+            class_abi = class_abi,
+            source_abi = source_abi,
+            source_only_abi = source_only_abi,
+            classpath_abi = classpath_abi,
+            classpath_abi_dir = classpath_abi_dir,
+            required_for_source_only_abi = required_for_source_only_abi,
+            annotation_processor_output = output_paths.annotations,
+            abi_jar_snapshot = abi_jar_snapshot,
+            used_jars_json = used_jars_json,
+        )
+    else:
+        full_jar_snapshot = generate_java_classpath_snapshot(
+            ctx.actions,
+            java_toolchain.cp_snapshot_generator,
+            ClasspathSnapshotGranularity("CLASS_MEMBER_LEVEL"),
+            final_jar_output.final_jar,
+            actions_identifier,
+        )
+        result = make_compile_outputs(
+            full_library = final_jar_output.final_jar,
+            preprocessed_library = final_jar_output.preprocessed_jar,
+            required_for_source_only_abi = required_for_source_only_abi,
+            annotation_processor_output = output_paths.annotations,
+            abi_jar_snapshot = full_jar_snapshot,
+            used_jars_json = used_jars_json,
+        )
+    return result
+
+def _command_builder(
+    label: Label,
+    srcs: list[Artifact],
+    remove_classes: list[str],
+    annotation_processor_properties: AnnotationProcessorProperties,
+    plugin_params: [PluginParams, None],
+    manifest_file: Artifact | None,
+    source_level: int,
+    target_level: int,
+    compiling_deps_tset: [JavaCompilingDepsTSet, None],
+    bootclasspath_entries: list[Artifact],
+    system_image: Artifact | None,
+    abi_generation_mode: AbiGenerationMode,
+    resources_map: dict[str, Artifact],
+    extra_arguments: cmd_args,
+    use_abi_dirs: bool,
+):
+    return partial(
+        encode_command,
+        label = label,
+        srcs = srcs,
+        remove_classes = remove_classes,
+        annotation_processor_properties = annotation_processor_properties,
+        plugin_params = plugin_params,
+        manifest_file = manifest_file,
+        source_level = source_level,
+        target_level = target_level,
+        compiling_deps_tset = compiling_deps_tset,
+        bootclasspath_entries = bootclasspath_entries,
+        system_image = system_image,
+        abi_generation_mode = abi_generation_mode,
+        resources_map = resources_map,
+        extra_arguments = extra_arguments,
+        kotlin_extra_params = None,
+        provide_classpath_snapshot = False,
+        use_abi_dirs = use_abi_dirs,
+    )
+
+# buildifier: disable=uninitialized
+def _define_javacd_action(
+    # provided by factory
+    actions: AnalysisActions,
+    java_toolchain: JavaToolchainInfo,
+    should_create_class_abi: bool,
+    class_abi_jar: [Artifact, None],
+    class_abi_output_dir: [Artifact, None],
+    srcs: list[Artifact],
+    track_class_usage: bool,
+    debug_port: [int, None],
+    uses_content_based_paths: bool,
+    # end of factory provided
+    category_prefix: str,
+    actions_identifier: [str, None],
+    encoded_command: struct,
+    qualified_name: str,
+    output_paths: OutputPaths,
+    classpath_jars_tag: ArtifactTag,
+    abi_dir: Artifact | None,
+    target_type: TargetType,
+    is_creating_subtarget: bool = False,
+):
+    expect(java_toolchain.javacd, "java_toolchain.javacd must be set for javacd protocol")
+    compiler = java_toolchain.javacd
+    exe, local_only = prepare_cd_exe(
+        qualified_name,
+        java = java_toolchain.java[RunInfo],
+        class_loader_bootstrapper = java_toolchain.class_loader_bootstrapper,
+        compiler = compiler,
+        main_class = java_toolchain.javacd_main_class,
+        worker = java_toolchain.javacd_worker[WorkerInfo] if java_toolchain.javacd_worker else None,
+        remote_worker = java_toolchain.javacd_remote_worker[WorkerInfo] if java_toolchain.javacd_remote_worker else None,
+        target_specified_debug_port = debug_port,
+        toolchain_specified_debug_port = java_toolchain.javacd_debug_port,
+        toolchain_specified_debug_target = java_toolchain.javacd_debug_target,
+        extra_jvm_args = java_toolchain.javacd_jvm_args,
+        extra_jvm_args_target = java_toolchain.javacd_jvm_args_target,
+        java_runtime_version = java_toolchain.java_runtime_version,
+    )
+
+    post_build_params = {}
+    args = cmd_args()
+    if target_type == TargetType("library") and should_create_class_abi:
+        post_build_params["shouldCreateClassAbi"] = True
+        post_build_params["libraryJar"] = output_paths.jar.as_output()
+        post_build_params["abiJar"] = class_abi_jar.as_output()
+        post_build_params["abiOutputDir"] = class_abi_output_dir.as_output()
+
+    if target_type == TargetType("source_abi") or target_type == TargetType("source_only_abi"):
+        post_build_params["abiJar"] = output_paths.jar.as_output()
+        post_build_params["abiOutputDir"] = abi_dir.as_output()
+
+    dep_files = {}
+    used_jars_json_output = None
+    if (
+        not is_creating_subtarget
+        and srcs
+        and (java_toolchain.dep_files == DepFiles("per_jar") or java_toolchain.dep_files == DepFiles("per_class"))
+        and track_class_usage
+    ):
+        used_classes_json_outputs = [cmd_args(output_paths.jar.as_output(), format = "{}/used-classes.json", parent = 1)]
+        if target_type == TargetType("library"):
+            used_jars_json_output = declare_prefixed_output(actions, actions_identifier, "jar/used-jars.json", uses_content_based_paths)
+        setup_dep_files(
+            actions,
+            actions_identifier,
+            post_build_params,
+            classpath_jars_tag,
+            used_classes_json_outputs,
+            used_jars_json_output,
+            uses_content_based_paths,
+        )
+
+        dep_files["classpath_jars"] = classpath_jars_tag
+
+    java_build_command = struct(
+        buildCommand = encoded_command,
+        postBuildParams = post_build_params,
+    )
+
+    proto = declare_prefixed_output(actions, actions_identifier, "jar_command.proto.json", uses_content_based_paths)
+    dep_file_fingerprints = []
+    if dep_files:
+        proto, fingerprint = actions.write_json(
+            proto,
+            java_build_command,
+            dep_files_fingerprint_using_canonical_paths = True,
+        )
+        proto_for_args = classpath_jars_tag.tag_artifacts(proto)
+        dep_file_fingerprints.append(fingerprint)
+    else:
+        proto_for_args = actions.write_json(proto, java_build_command, with_inputs = True)
+
+    args.add(
+        "--action-id",
+        qualified_name,
+        "--command-file",
+        proto_for_args,
+    )
+
+    actions.run(
+        args,
+        env = {
+            "BUCK_CLASSPATH": compiler,
+            "JAVACD_ABSOLUTE_PATHS_ARE_RELATIVE_TO_CWD": "1",
+        },
+        category = "{}javacd_jar".format(category_prefix),
+        identifier = actions_identifier or "",
+        dep_files = dep_files,
+        dep_file_fingerprints = dep_file_fingerprints,
+        allow_dep_file_cache_upload = True,
+        allow_cache_upload = True,
+        exe = exe,
+        local_only = local_only,
+        low_pass_filter = False,
+        weight = 2,
+        error_handler = java_toolchain.java_error_handler,
+    )
+
+    return used_jars_json_output
diff --git a/buck2/prelude/java/plugins/java_annotation_processor.bzl b/buck2/prelude/java/plugins/java_annotation_processor.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/plugins/java_annotation_processor.bzl
@@ -0,0 +1,194 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_providers.bzl", "JavaLibraryInfo", "JavaPackagingDepTSet", "JavaPackagingInfo")
+load("@prelude//utils:type_defs.bzl", "is_tuple")
+
+JavaProcessorsType = enum(
+    "java_annotation_processor",
+    "ksp_annotation_processor",
+    "plugin",
+)
+
+JavaProcessorsInfo = provider(
+    # @unsorted-dict-items
+    doc = "Information about java annotation processor/ java compiler plugins and their dependencies",
+    fields = {
+        "affects_abi": provider_field(typing.Any, default = None),
+        # Java dependencies exposed to dependent targets and supposed to be used during compilation.
+        "deps": provider_field(typing.Any, default = None),  # [JavaPackagingDepTSet, None]
+        "isolate_class_loader": provider_field(typing.Any, default = None),
+        # Names of processors
+        "processors": provider_field(typing.Any, default = None),  # ["string"]
+        # Whether processor can only run on java and shall run on javac even in KotlinCD
+        # (which means it will only apply on java files in kotlin module)
+        "runs_on_java_only": provider_field(typing.Any, default = None),
+        # Whether processor support source only abi
+        "supports_source_only_abi": provider_field(typing.Any, default = None),
+        # Type of processor
+        "type": provider_field(typing.Any, default = None),  # "JavaProcessorsType"
+    },
+)
+
+AnnotationProcessor = record(
+    affects_abi = field(bool),
+    supports_source_only_abi = field(bool),
+    runs_on_java_only = field(bool),
+    processors = field(list[str]),
+    deps = field([JavaPackagingDepTSet, None]),
+    isolate_class_loader = field(bool),
+)
+
+AnnotationProcessorProperties = record(
+    annotation_processors = field(list[AnnotationProcessor]),
+    annotation_processor_params = field(list[str]),
+)
+
+# Every transitive java annotation processors dependency has to be included into processor classpath for AP/Java Plugin run
+def derive_transitive_deps(ctx: AnalysisContext, deps: list[Dependency]) -> [JavaPackagingDepTSet, None]:
+    for dep in deps:
+        if not dep[JavaLibraryInfo]:
+            fail("Dependency must have a type of `java_library` or `prebuilt_jar`. Deps: {}".format(deps))
+
+    return (
+        ctx.actions.tset(
+            JavaPackagingDepTSet,
+            children = [dep[JavaPackagingInfo].packaging_deps for dep in deps],
+        )
+        if deps
+        else None
+    )
+
+def create_annotation_processor_properties(
+    ctx: AnalysisContext,
+    plugins: list[[Dependency, (Dependency, list[str])]],
+    annotation_processor_names: list[str],
+    annotation_processor_params: list[str],
+    annotation_processor_deps: list[Dependency],
+) -> AnnotationProcessorProperties:
+    annotation_processors = []
+
+    # Extend `ap_processor_deps` with java deps from `annotation_processor_deps`
+    if annotation_processor_names or annotation_processor_deps:
+        for ap_dep in [_get_plugin_provider(x, JavaLibraryInfo) for x in annotation_processor_deps]:
+            if not ap_dep:
+                fail("Dependency must have a type of `java_library` or `prebuilt_jar`. Deps: {}".format(annotation_processor_deps))
+
+        # "legacy" annotation processors have no mechanism for indicating if they affect abi or if they support source_only or if they run on javac for mix modules
+        annotation_processors.append(
+            AnnotationProcessor(
+                affects_abi = True,
+                supports_source_only_abi = False,
+                runs_on_java_only = False,
+                processors = annotation_processor_names,
+                # using packaging deps to have all transitive deps collected for processors classpath
+                deps = derive_transitive_deps(ctx, annotation_processor_deps),
+                isolate_class_loader = False,
+            )
+        )
+
+    # APs derived from `plugins` attribute
+    for ap_plugin in filter(None, [_get_plugin_provider(x, JavaProcessorsInfo) for x in plugins]):
+        if not ap_plugin:
+            fail("Plugin must have a type of `java_annotation_processor` or `java_plugin`. Plugins: {}".format(plugins))
+        if ap_plugin.type == JavaProcessorsType("java_annotation_processor"):
+            annotation_processors.append(
+                AnnotationProcessor(
+                    affects_abi = ap_plugin.affects_abi,
+                    supports_source_only_abi = ap_plugin.supports_source_only_abi,
+                    runs_on_java_only = ap_plugin.runs_on_java_only,
+                    processors = ap_plugin.processors,
+                    deps = ap_plugin.deps,
+                    isolate_class_loader = ap_plugin.isolate_class_loader,
+                )
+            )
+
+    annotation_processor_params = _update_first(
+        annotation_processor_params,
+        "buck.current_buck_target=<will_be_replaced>",
+        "buck.current_buck_target=" + str(ctx.label.raw_target()),
+    )
+
+    annotation_processor_params = _update_first(
+        annotation_processor_params,
+        "buck.required_for_source_only_abi=<will_be_replaced>",
+        ("buck.required_for_source_only_abi=" + str(ctx.attrs.required_for_source_only_abi)) if hasattr(ctx.attrs, "required_for_source_only_abi") else None,
+    )
+
+    return AnnotationProcessorProperties(
+        annotation_processors = annotation_processors,
+        annotation_processor_params = annotation_processor_params,
+    )
+
+def _update_first(iterable, old_value, new_value):
+    """
+    Replaces the first occurrence of old_value with new_value.
+    If new_value is None, removes the first occurrence instead.
+    Returns the original iterable unchanged if old_value is not found.
+    """
+    if old_value not in iterable:
+        return iterable
+    result = list(iterable)
+    idx = result.index(old_value)
+    if new_value == None:
+        result.pop(idx)
+    else:
+        result[idx] = new_value
+    return result
+
+def create_ksp_annotation_processor_properties(plugins: list[[Dependency, (Dependency, list[str])]]) -> AnnotationProcessorProperties:
+    annotation_processors = []
+
+    # APs derived from `plugins` attribute
+    for ap_plugin in filter(None, [_get_plugin_provider(x, JavaProcessorsInfo) for x in plugins]):
+        if not ap_plugin:
+            fail("Plugin must have a type of `java_annotation_processor` or `java_plugin`. Plugins: {}".format(plugins))
+        if ap_plugin.type == JavaProcessorsType("ksp_annotation_processor"):
+            annotation_processors.append(
+                AnnotationProcessor(
+                    affects_abi = ap_plugin.affects_abi,
+                    supports_source_only_abi = ap_plugin.supports_source_only_abi,
+                    runs_on_java_only = ap_plugin.runs_on_java_only,
+                    processors = ap_plugin.processors,
+                    deps = ap_plugin.deps,
+                    isolate_class_loader = ap_plugin.isolate_class_loader,
+                )
+            )
+
+    return AnnotationProcessorProperties(
+        annotation_processors = annotation_processors,
+        annotation_processor_params = [],
+    )
+
+def _get_processor_type(processor_class: str) -> JavaProcessorsType:
+    if processor_class.startswith("KSP:"):
+        return JavaProcessorsType("ksp_annotation_processor")
+
+    return JavaProcessorsType("java_annotation_processor")
+
+def _get_plugin_provider(plugin: [Dependency, (Dependency, list[str])], provider: typing.Callable[[], Provider]) -> [Provider, None]:
+    return (plugin[0] if is_tuple(plugin) else plugin).get(provider)
+
+def java_annotation_processor_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs._build_only_native_code:
+        return [DefaultInfo()]
+
+    transitive_deps = derive_transitive_deps(ctx, ctx.attrs.deps)
+
+    return [
+        JavaProcessorsInfo(
+            deps = transitive_deps,
+            processors = [ctx.attrs.processor_class],
+            type = _get_processor_type(ctx.attrs.processor_class),
+            affects_abi = not ctx.attrs.does_not_affect_abi,
+            supports_source_only_abi = ctx.attrs.supports_abi_generation_from_source,
+            runs_on_java_only = ctx.attrs.runs_on_java_only,
+            isolate_class_loader = ctx.attrs.isolate_class_loader,
+        ),
+        DefaultInfo(default_output = None, other_outputs = [transitive_deps.project_as_args("full_jar_args")]),
+    ]
diff --git a/buck2/prelude/java/plugins/java_plugin.bzl b/buck2/prelude/java/plugins/java_plugin.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/plugins/java_plugin.bzl
@@ -0,0 +1,66 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_providers.bzl", "JavaPackagingDepTSet")
+load(
+    "@prelude//java/plugins:java_annotation_processor.bzl",
+    "JavaProcessorsInfo",
+    "JavaProcessorsType",
+    "derive_transitive_deps",
+)
+load("@prelude//utils:type_defs.bzl", "is_list", "is_tuple")
+
+PluginParams = record(
+    processors = field(list[(str, cmd_args)]),
+    deps = field([JavaPackagingDepTSet, None]),
+)
+
+def create_plugin_params(ctx: AnalysisContext, plugins: list[[Dependency, (Dependency, list[str] | cmd_args)]]) -> [PluginParams, None]:
+    processors = []
+    plugin_deps = []
+
+    # Compiler plugin derived from `plugins` attribute
+    for item in plugins:
+        # Each plugin can be either a tuple of (target, arguments) or just the target
+        if is_tuple(item):
+            plugin = item[0]
+            arguments = cmd_args(item[1]) if is_list(item[1]) else item[1]
+        else:
+            plugin = item
+            arguments = cmd_args()
+
+        processors_info = plugin.get(JavaProcessorsInfo)
+        if processors_info != None and processors_info.type == JavaProcessorsType("plugin"):
+            if len(processors_info.processors) > 1:
+                fail("Only 1 java compiler plugin is expected. But received: {}".format(processors_info.processors))
+            processor = processors_info.processors[0]
+            if processors_info.deps:
+                plugin_deps.append(processors_info.deps)
+
+            processors.append((processor, arguments))
+
+    if not processors:
+        return None
+
+    return PluginParams(
+        processors = processors,
+        deps = ctx.actions.tset(JavaPackagingDepTSet, children = plugin_deps) if plugin_deps else None,
+    )
+
+def java_plugin_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs._build_only_native_code:
+        return [DefaultInfo()]
+
+    return [
+        JavaProcessorsInfo(
+            deps = derive_transitive_deps(ctx, ctx.attrs.deps),
+            processors = [ctx.attrs.plugin_name],
+            type = JavaProcessorsType("plugin"),
+        ),
+        DefaultInfo(default_output = None),
+    ]
diff --git a/buck2/prelude/java/prebuilt_jar.bzl b/buck2/prelude/java/prebuilt_jar.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/prebuilt_jar.bzl
@@ -0,0 +1,110 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_providers.bzl", "merge_android_packageable_info")
+load("@prelude//java/utils:java_utils.bzl", "get_classpath_subtargets")
+load(
+    ":java_providers.bzl",
+    "ClasspathSnapshotGranularity",
+    "JavaClasspathEntry",
+    "create_abi",
+    "create_java_library_providers",
+    "generate_java_classpath_snapshot",
+)
+load(":java_toolchain.bzl", "PrebuiltJarToolchainInfo")
+
+def prebuilt_jar_impl(ctx: AnalysisContext) -> list[Provider]:
+    """
+     prebuilt_jar() rule implementation
+
+    Args:
+        ctx: rule analysis context
+    Returns:
+        list of created providers
+    """
+
+    expected_extensions = [".jar", ".jmod"]
+    binary_jar = ctx.attrs.binary_jar
+    extension = binary_jar.extension
+    if extension not in expected_extensions:
+        fail(
+            "Extension of the binary_jar attribute has to be one of '{}' but '{}' has an extension '{}'".format(
+                expected_extensions,
+                binary_jar,
+                extension,
+            )
+        )
+
+    output = ctx.actions.declare_output("symlink/{}".format(binary_jar.short_path), has_content_based_path = ctx.attrs.uses_content_based_paths)
+    ctx.actions.symlink_file(output, binary_jar)
+
+    gwt_output = ctx.actions.declare_output("{}-gwt.jar".format(ctx.label.name), has_content_based_path = False)
+    ctx.actions.copy_file(gwt_output, ctx.attrs.source_jar if ctx.attrs.source_jar else ctx.attrs.binary_jar)
+
+    abi = None
+    prebuilt_jar_toolchain = ctx.attrs._prebuilt_jar_toolchain[PrebuiltJarToolchainInfo]
+    if not prebuilt_jar_toolchain.is_bootstrap_toolchain:
+        if ctx.attrs.generate_abi:
+            abi = create_abi(ctx.actions, prebuilt_jar_toolchain.class_abi_generator, output)
+    jar_snapshot = generate_java_classpath_snapshot(
+        ctx.actions,
+        ctx.attrs._prebuilt_jar_toolchain[PrebuiltJarToolchainInfo].cp_snapshot_generator,
+        ClasspathSnapshotGranularity("CLASS_LEVEL"),
+        abi or output,
+        "",
+    )
+
+    library_output_classpath_entry = JavaClasspathEntry(
+        full_library = output,
+        abi = abi or output,
+        abi_as_dir = None,
+        required_for_source_only_abi = ctx.attrs.required_for_source_only_abi,
+        abi_jar_snapshot = jar_snapshot,
+    )
+
+    java_library_info, java_packaging_info, global_code_info, shared_library_info, cxx_resource_info, linkable_graph, template_placeholder_info, _ = (
+        create_java_library_providers(
+            ctx,
+            library_output = library_output_classpath_entry,
+            global_code_config = prebuilt_jar_toolchain.global_code_config,
+            declared_deps = ctx.attrs.deps,
+            exported_deps = ctx.attrs.deps,
+            provided_deps = ctx.attrs.desugar_deps,
+            is_prebuilt_jar = True,
+            gwt_module = gwt_output,
+            sources_jar = ctx.attrs.source_jar,
+        )
+    )
+
+    # TODO(T107163344) this shouldn't be in prebuilt_jar itself, use overlays to remove it.
+    android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, ctx.attrs.deps)
+
+    sub_targets = get_classpath_subtargets(ctx.actions, java_packaging_info)
+    sub_targets["abi"] = [
+        java_library_info,
+        template_placeholder_info,
+        DefaultInfo(default_output = library_output_classpath_entry.abi),
+    ]
+
+    return [
+        java_library_info,
+        java_packaging_info,
+        global_code_info,
+        shared_library_info,
+        cxx_resource_info,
+        android_packageable_info,
+        template_placeholder_info,
+        linkable_graph,
+        DefaultInfo(default_output = output, sub_targets = sub_targets),
+    ] + (
+        [
+            RunInfo(args = cmd_args([ctx.attrs._prebuilt_jar_toolchain[PrebuiltJarToolchainInfo].java[RunInfo], "-jar", output])),
+        ]
+        if ctx.attrs.is_executable
+        else []
+    )
diff --git a/buck2/prelude/java/proguard.bzl b/buck2/prelude/java/proguard.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/proguard.bzl
@@ -0,0 +1,223 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//java:java_providers.bzl",
+    "JavaPackagingDep",  # @unused Used as type
+)
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//utils:expect.bzl", "expect")
+
+ProguardOutput = record(
+    jars_to_owners = dict[Artifact, TargetLabel],
+    proguard_configuration_output_file = Artifact | None,
+    proguard_mapping_output_file = Artifact,
+    proguard_artifacts = list[Artifact],
+    proguard_hidden_artifacts = list[Artifact],
+)
+
+def _get_proguard_command_line_args(
+    ctx: AnalysisContext,
+    input_jars_to_output_jars: dict[Artifact, Artifact],
+    proguard_configs: list[Artifact],
+    additional_jars: list[Artifact],
+    mapping: Artifact,
+    configuration: Artifact | None,
+    seeds: Artifact | None,
+    usage: Artifact | None,
+    sdk_proguard_config_mode: str | None,
+    sdk_proguard_config: Artifact | None,
+    sdk_optimized_proguard_config: Artifact | None,
+) -> (cmd_args, list[Artifact]):
+    cmd = cmd_args()
+    hidden = []
+    cmd.add("-basedirectory", "<user.dir>")
+
+    sdk_proguard_config_mode = sdk_proguard_config_mode or "none"
+    if sdk_proguard_config_mode == "optimized":
+        expect(sdk_optimized_proguard_config)
+        cmd.add("-include", sdk_optimized_proguard_config)
+        cmd.add("-optimizationpasses", str(ctx.attrs.optimization_passes))
+        hidden.append(sdk_optimized_proguard_config)
+    elif sdk_proguard_config_mode == "default":
+        expect(sdk_proguard_config)
+        cmd.add("-include", sdk_proguard_config)
+        hidden.append(sdk_proguard_config)
+    else:
+        expect(sdk_proguard_config_mode == "none")
+
+    for proguard_config in dedupe(proguard_configs):
+        cmd.add("-include")
+        cmd.add(cmd_args('"', proguard_config, '"', delimiter = ""))
+        hidden.append(proguard_config)
+
+    for jar_input, jar_output in input_jars_to_output_jars.items():
+        cmd.add("-injars", jar_input, "-outjars", jar_output if jar_output == jar_input else jar_output.as_output())
+
+    cmd.add("-libraryjars")
+    cmd.add(cmd_args(additional_jars, delimiter = get_path_separator_for_exec_os(ctx)))
+    hidden.extend(additional_jars)
+
+    cmd.add("-printmapping", mapping.as_output())
+    if configuration:
+        cmd.add("-printconfiguration", configuration.as_output())
+    if seeds:
+        cmd.add("-printseeds", seeds.as_output())
+    if usage:
+        cmd.add("-printusage", usage.as_output())
+
+    return cmd, hidden
+
+def run_proguard(
+    ctx: AnalysisContext,
+    java_toolchain: JavaToolchainInfo,
+    proguard_jar: Artifact,
+    command_line_args_file: Artifact,
+    command_line_args: cmd_args,
+    mapping_file: Artifact,
+    usage_file: Artifact,
+    output_jars: list[Artifact],
+):
+    run_proguard_cmd = cmd_args()
+    run_proguard_cmd.add(
+        java_toolchain.java[RunInfo],
+        "-XX:-MaxFDLimit",
+        ctx.attrs.proguard_jvm_args,
+        "-Xmx{}".format(java_toolchain.proguard_max_heap_size),
+        "-jar",
+        proguard_jar,
+    )
+    run_proguard_cmd.add(
+        cmd_args(command_line_args_file, format = "@{}", hidden = command_line_args),
+    )
+
+    output_jars_file = ctx.actions.write("proguard/output_jars.txt", output_jars, has_content_based_path = False)
+
+    is_windows = hasattr(ctx.attrs, "_exec_os_type") and ctx.attrs._exec_os_type[OsLookup].os == Os("windows")
+
+    # Some proguard configs can propagate the "-dontobfuscate" flag which disables
+    # obfuscation and prevents the mapping.txt and usage.txt file from being generated.
+    # Scrub all jars emitted from proguard to make them deterministic.
+    if not is_windows:
+        sh_cmd = cmd_args([
+            "sh",
+            "-c",
+            "touch $1 && touch $2 && $3 && $4 --paths-to-scrub $5 --create-if-not-present",
+            "--",
+            mapping_file.as_output(),
+            usage_file.as_output(),
+            cmd_args(run_proguard_cmd, delimiter = " "),
+            cmd_args(ctx.attrs._java_toolchain[JavaToolchainInfo].zip_scrubber, delimiter = " "),
+            output_jars_file,
+        ])
+    else:
+        sh_cmd = cmd_args([
+            "cmd.exe",
+            "/c",
+            cmd_args(
+                [
+                    cmd_args([mapping_file.as_output()], format = "echo. > {}"),
+                    cmd_args([usage_file.as_output()], format = "echo. > {}"),
+                    cmd_args(run_proguard_cmd, delimiter = " "),
+                    cmd_args(
+                        ctx.attrs._java_toolchain[JavaToolchainInfo].zip_scrubber,
+                        "--paths-to-scrub",
+                        output_jars_file,
+                        "--create-if-not-present",
+                        delimiter = " ",
+                    ),
+                ],
+                delimiter = " && ",
+            ),
+        ])
+
+    ctx.actions.run(sh_cmd, category = "run_proguard")
+
+# Note that ctx.attrs.skip_proguard means that we should create the proguard command line (since
+# e.g. Redex might want to consume it) but we don't actually run the proguard command.
+def get_proguard_output(
+    ctx: AnalysisContext,
+    input_jars: dict[Artifact, TargetLabel],
+    java_packaging_deps: list[JavaPackagingDep],
+    additional_proguard_configs: list[Artifact],
+    additional_jars: list[Artifact],
+    sdk_proguard_config_mode: str | None,
+    sdk_proguard_config: Artifact | None,
+    sdk_optimized_proguard_config: Artifact | None,
+    proguard_jar: Artifact,
+    skip_proguard: bool = False,
+) -> ProguardOutput:
+    proguard_configs = [packaging_dep.proguard_config for packaging_dep in java_packaging_deps if packaging_dep.proguard_config]
+    if ctx.attrs.proguard_config:
+        proguard_configs.append(ctx.attrs.proguard_config)
+    proguard_configs.extend(additional_proguard_configs)
+
+    if skip_proguard:
+        input_jars_to_output_jars = {input_jar: input_jar for input_jar in input_jars.keys()}
+        mapping = ctx.actions.write("proguard/mapping.txt", [], has_content_based_path = False)
+        configuration = None
+        seeds = None
+        usage = None
+    else:
+        input_jars_to_output_jars = {
+            input_jar: ctx.actions.declare_output(
+                "proguard_output_jars/{}_{}_obfuscated.jar".format(input_jar.short_path, i),
+                has_content_based_path = False,
+            )
+            for i, input_jar in enumerate(input_jars.keys())
+        }
+        mapping = ctx.actions.declare_output("proguard/mapping.txt", has_content_based_path = True)
+        configuration = ctx.actions.declare_output("proguard/configuration.txt", has_content_based_path = True)
+        seeds = ctx.actions.declare_output("proguard/seeds.txt", has_content_based_path = True)
+        usage = ctx.actions.declare_output("proguard/usage.txt", has_content_based_path = True)
+
+    command_line_args, hidden_artifacts = _get_proguard_command_line_args(
+        ctx,
+        input_jars_to_output_jars,
+        proguard_configs,
+        additional_jars,
+        mapping,
+        configuration,
+        seeds,
+        usage,
+        sdk_proguard_config_mode,
+        sdk_proguard_config,
+        sdk_optimized_proguard_config,
+    )
+
+    command_line_args_file = ctx.actions.write("proguard/command-line.txt", command_line_args, has_content_based_path = False)
+
+    if skip_proguard:
+        return ProguardOutput(
+            jars_to_owners = input_jars,
+            proguard_configuration_output_file = None,
+            proguard_mapping_output_file = mapping,
+            proguard_artifacts = [command_line_args_file, mapping],
+            proguard_hidden_artifacts = hidden_artifacts,
+        )
+    else:
+        run_proguard(
+            ctx,
+            ctx.attrs._java_toolchain[JavaToolchainInfo],
+            proguard_jar,
+            command_line_args_file,
+            command_line_args,
+            mapping,
+            usage,
+            input_jars_to_output_jars.values(),
+        )
+        output_jars = {output: input_jars[input_jar] for input_jar, output in input_jars_to_output_jars.items()}
+        return ProguardOutput(
+            jars_to_owners = output_jars,
+            proguard_configuration_output_file = configuration,
+            proguard_mapping_output_file = mapping,
+            proguard_artifacts = [command_line_args_file, mapping, configuration, seeds, usage],
+            proguard_hidden_artifacts = hidden_artifacts,
+        )
diff --git a/buck2/prelude/java/tools/BUCK b/buck2/prelude/java/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/BUCK
@@ -0,0 +1,119 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "gen_class_to_source_map",
+    main = "gen_class_to_source_map.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "merge_class_to_source_maps",
+    main = "merge_class_to_source_maps.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "compile_and_package",
+    main = "compile_and_package.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":utils_lib",
+    ],
+)
+
+prelude.python_bootstrap_binary(
+    name = "fat_jar",
+    main = "fat_jar.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":utils_lib",
+    ],
+)
+
+prelude.python_bootstrap_binary(
+    name = "list_class_names",
+    main = "list_class_names.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":utils_lib",
+    ],
+)
+
+prelude.python_bootstrap_binary(
+    name = "postprocessor_runner",
+    main = "run_postprocessor.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":utils_lib",
+    ],
+)
+
+prelude.python_bootstrap_library(
+    name = "utils_lib",
+    srcs = [
+        "utils.py",
+    ],
+    visibility = [
+        "prelude//android/tools/...",
+        "prelude//java/tools/...",
+        "prelude//kotlin/tools/...",
+    ],
+)
+
+# Type checking target for Python tool scripts
+prelude.python_library(
+    name = "scripts-typing",
+    srcs = [
+        "compile_and_package.py",
+        "fat_jar.py",
+        "gen_class_to_source_map.py",
+        "list_class_names.py",
+        "merge_class_to_source_maps.py",
+        "run_postprocessor.py",
+        "utils.py",
+    ],
+    typing = True,
+)
+
+prelude.python_test(
+    name = "test_fat_jar",
+    srcs = [
+        "fat_jar.py",
+        "tests/test_fat_jar.py",
+        "utils.py",
+    ],
+    base_module = "",
+)
+
+prelude.python_test(
+    name = "test_gen_class_to_source_map",
+    srcs = [
+        "gen_class_to_source_map.py",
+        "tests/test_gen_class_to_source_map.py",
+    ],
+    base_module = "",
+)
+
+prelude.python_test(
+    name = "test_list_class_names",
+    srcs = [
+        "list_class_names.py",
+        "tests/test_list_class_names.py",
+    ],
+    base_module = "",
+)
+
+prelude.python_test(
+    name = "test_merge_class_to_source_maps",
+    srcs = [
+        "merge_class_to_source_maps.py",
+        "tests/test_merge_class_to_source_maps.py",
+    ],
+    base_module = "",
+)
diff --git a/buck2/prelude/java/tools/compile_and_package.py b/buck2/prelude/java/tools/compile_and_package.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/compile_and_package.py
@@ -0,0 +1,440 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import pathlib
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+from tempfile import TemporaryDirectory
+from typing import List
+
+import utils
+
+_JAVA_FILE_EXTENSION = [".java"]
+
+
+def _parse_args():
+    parser = argparse.ArgumentParser(
+        description="Tool to compile and create a jar for java library."
+    )
+
+    parser.add_argument(
+        "--jar_builder_tool",
+        type=str,
+        required=True,
+        help="a path to a jar builder tool",
+    )
+    parser.add_argument(
+        "--output", type=pathlib.Path, required=True, help="a path to an output result"
+    )
+    parser.add_argument(
+        "--skip_javac_run",
+        action="store_true",
+        help="flag that if set then need to skip javac execution",
+    )
+    parser.add_argument(
+        "--javac_tool",
+        type=pathlib.Path,
+        help="a path to a java compiler tool",
+    )
+    parser.add_argument(
+        "--javac_args_file",
+        type=pathlib.Path,
+        required=False,
+        metavar="javac_args_file",
+        help="path to file with stored args that need to be passed to java compiler",
+    )
+    parser.add_argument(
+        "--multi_release_args_file",
+        action="append",
+        type=pathlib.Path,
+        required=False,
+        metavar="multi_release_args_file",
+        help="path to file with stored args that need to be passed to java compiler for multi-release build",
+    )
+    parser.add_argument(
+        "--zipped_sources_file",
+        type=pathlib.Path,
+        required=False,
+        metavar="zipped_sources_file",
+        help="path to file with stored zipped source files that need to be passed to java compiler",
+    )
+
+    parser.add_argument(
+        "--javac_classpath_file",
+        type=pathlib.Path,
+        required=False,
+        metavar="javac_classpath_file",
+        help="path to file with stored classpath for java compilation",
+    )
+    parser.add_argument(
+        "--javac_processors_classpath_file",
+        type=pathlib.Path,
+        required=False,
+        metavar="javac_processors_classpath_file",
+        help="path to file with stored classpath for java compilation processors",
+    )
+    parser.add_argument(
+        "--javac_bootclasspath_file",
+        type=pathlib.Path,
+        required=False,
+        metavar="javac_bootclasspath_file",
+        help="path to file with stored bootclasspath for java compilation",
+    )
+    parser.add_argument(
+        "--javac_jvm_args_file",
+        type=pathlib.Path,
+        required=False,
+        metavar="javac_jvm_args_file",
+        help="path to file with JVM args (-J prefixed) to pass directly to javac on the command line (not via @argfile)",
+    )
+    parser.add_argument(
+        "--resources_dir",
+        type=pathlib.Path,
+        required=False,
+        metavar="resources_dir",
+        help="path to a directory with resources",
+    )
+    parser.add_argument(
+        "--generated_sources_dir",
+        type=pathlib.Path,
+        required=False,
+        metavar="generated_sources_dir",
+        help="path to a directory where generated sources should be written",
+    )
+    parser.add_argument(
+        "--manifest",
+        type=pathlib.Path,
+        required=False,
+        metavar="manifest",
+        help="a path to a custom manifest file",
+    )
+    parser.add_argument(
+        "--remove_classes",
+        type=pathlib.Path,
+        help="paths to file with stored remove classes patterns",
+    )
+    parser.add_argument(
+        "--additional_compiled_srcs",
+        type=pathlib.Path,
+        required=False,
+        metavar="additional_compiled_srcs",
+        help=".class files that should be packaged into the final jar",
+    )
+    parser.add_argument(
+        "--concat_resources",
+        action="store_true",
+        help="if the jar tool should use parallel compression anc doncat intermediary jars",
+    )
+
+    return parser.parse_args()
+
+
+def _get_multi_release_version(args_file: pathlib.Path) -> str:
+    """
+    Extracts the Java version from a filename ending with '.java<version>'.
+    """
+    version_match = re.search(r".java(\d+)$", str(args_file))
+    return version_match.group(1) if version_match else None
+
+
+def _get_multi_release_classpath(
+    temp_build_dir: pathlib.Path,
+    javac_classpath: pathlib.Path,
+    javac_output: pathlib.Path,
+) -> pathlib.Path:
+    """
+    Creates a copy of javac classpath at temp_build_dir/multi_release_classpath containing
+    javac_classpath and javac_output, joined by the platform path separator.
+    Returns the path to the created classpath file.
+    """
+    multi_release_classpath = temp_build_dir / "multi_release_classpath"
+    if javac_classpath:
+        shutil.copyfile(javac_classpath, multi_release_classpath)
+        with multi_release_classpath.open("a", encoding="utf-8") as f:
+            f.write(f":{javac_output}")
+    else:
+        multi_release_classpath.write_text(f"{javac_output}")
+    return multi_release_classpath
+
+
+def _get_multi_release_manifest(temp_build_dir: pathlib.Path) -> pathlib.Path:
+    """
+    Creates a Multi-Release manifest file at temp_build_dir/MANIFEST.MF
+    Returns the path to the created manifest file.
+    """
+    multi_release_manifest = temp_build_dir / "MANIFEST.MF"
+    multi_release_manifest.write_text("Manifest-Version: 1.0\nMulti-Release: true\n")
+    return multi_release_manifest
+
+
+def _run_javac(
+    javac_tool: pathlib.Path,
+    javac_args_file: pathlib.Path,
+    javac_output: pathlib.Path,
+    zipped_sources_file: pathlib.Path,
+    javac_classpath_file: pathlib.Path,
+    javac_processor_classpath_file: pathlib.Path,
+    javac_bootclasspath_file: pathlib.Path,
+    generated_sources_dir: pathlib.Path,
+    temp_build_dir: pathlib.Path,
+    javac_jvm_args_file: pathlib.Path = None,
+) -> pathlib.Path:
+    # make sure output folder exists
+    javac_output.mkdir(parents=True, exist_ok=True)
+
+    javac_cmd = [javac_tool]
+
+    # JVM args must be passed directly on the command line (not via @argfile)
+    # because javac does not support -J flags inside @argfiles.
+    if javac_jvm_args_file:
+        with open(javac_jvm_args_file) as f:
+            for line in f:
+                arg = line.strip()
+                if arg:
+                    javac_cmd.append(arg)
+
+    args_file = javac_args_file
+    if zipped_sources_file:
+        args_file = utils.extract_source_files(
+            zipped_sources_file, javac_args_file, _JAVA_FILE_EXTENSION, temp_build_dir
+        )
+
+    if utils.sources_are_present(args_file, _JAVA_FILE_EXTENSION):
+        javac_cmd += ["@{}".format(args_file)]
+
+        if javac_classpath_file:
+            javac_cmd += ["-classpath", "@{}".format(javac_classpath_file)]
+
+        if javac_bootclasspath_file:
+            javac_cmd += ["-bootclasspath", "@{}".format(javac_bootclasspath_file)]
+
+        if javac_processor_classpath_file:
+            javac_cmd += [
+                "-processorpath",
+                "@{}".format(javac_processor_classpath_file),
+            ]
+
+        if generated_sources_dir:
+            javac_cmd += [
+                "-s",
+                generated_sources_dir,
+            ]
+
+        javac_cmd += ["-g"]
+
+        javac_cmd += ["-d", javac_output]
+        utils.log_message(
+            "executing command = '{}'".format(
+                " ".join([shlex.quote(str(s)) for s in javac_cmd])
+            )
+        )
+
+        p = subprocess.run(javac_cmd, stderr=subprocess.PIPE, text=True)
+        if p.returncode != 0:
+            print(
+                f"javac command failed with exit code {p.returncode}. javac_tool={javac_tool}",
+                file=sys.stderr,
+            )
+            if p.stderr:
+                print(utils.pretty_exception_j(p.stderr), file=sys.stderr)
+            sys.exit(p.returncode)
+
+        return javac_output
+
+    return javac_output
+
+
+def _run_jar(
+    jar_builder_tool: str,
+    output_path: pathlib.Path,
+    manifest_files: List[pathlib.Path],
+    javac_output: pathlib.Path,
+    resources_dir: pathlib.Path,
+    additional_compiled_srcs: pathlib.Path,
+    remove_classes_file: pathlib.Path,
+    temp_build_dir: pathlib.Path,
+    concat_resources: bool = False,
+):
+    jar_cmd = []
+    jar_cmd.extend(utils.shlex_split(jar_builder_tool))
+
+    content_to_pack_dirs = []
+    if javac_output:
+        content_to_pack_dirs.append(javac_output)
+    if resources_dir:
+        content_to_pack_dirs.append(resources_dir)
+    if additional_compiled_srcs:
+        content_to_pack_dirs.append(additional_compiled_srcs)
+
+    entries_to_jar_file = temp_build_dir / "entries_to_jar.txt"
+    entries_to_jar_file.write_text(
+        "\n".join(str(path) for path in content_to_pack_dirs)
+    )
+
+    jar_cmd.extend(["--entries-to-jar", entries_to_jar_file])
+
+    if manifest_files:
+        jar_cmd.append("--merge-manifests")
+        for manifest_file in manifest_files:
+            jar_cmd.extend(["--manifest-file", manifest_file])
+    if concat_resources:
+        jar_cmd.extend(["--concat-jars"])
+
+    if remove_classes_file:
+        jar_cmd.extend(["--blocklist-patterns", remove_classes_file])
+        jar_cmd.extend(
+            ["--blocklist-patterns-matcher", "remove_classes_patterns_matcher"]
+        )
+
+    jar_cmd.extend(["--output", output_path])
+
+    utils.log_message("jar_cmd: {}".format(" ".join([str(s) for s in jar_cmd])))
+    utils.execute_command(jar_cmd)
+
+
+def main():
+    args = _parse_args()
+
+    skip_javac_run = args.skip_javac_run
+    javac_tool = args.javac_tool
+    jar_builder_tool = args.jar_builder_tool
+    output_path = args.output
+    javac_args = args.javac_args_file
+    multi_release_args_file = args.multi_release_args_file
+    zipped_sources_file = args.zipped_sources_file
+    javac_classpath = args.javac_classpath_file
+    javac_processor_classpath = args.javac_processors_classpath_file
+    javac_bootclasspath_file = args.javac_bootclasspath_file
+    javac_jvm_args_file = args.javac_jvm_args_file
+    resources_dir = args.resources_dir
+    generated_sources_dir = args.generated_sources_dir
+    manifest = args.manifest
+    remove_classes_file = args.remove_classes
+    additional_compiled_srcs = args.additional_compiled_srcs
+    concat_resources = args.concat_resources
+    manifest_files = [manifest] if manifest else []
+
+    utils.log_message("javac_tool: {}".format(javac_tool))
+    utils.log_message("jar_builder_tool: {}".format(jar_builder_tool))
+    utils.log_message("output: {}".format(output_path))
+    if skip_javac_run:
+        utils.log_message("skip_javac_run: {}".format(skip_javac_run))
+    if javac_args:
+        utils.log_message("javac_args: {}".format(javac_args))
+    if multi_release_args_file:
+        for multi_release_args in multi_release_args_file:
+            utils.log_message("multi_release_args: {}".format(multi_release_args))
+    if zipped_sources_file:
+        utils.log_message("zipped_sources_file: {}".format(zipped_sources_file))
+    if javac_classpath:
+        utils.log_message("javac_classpath: {}".format(javac_classpath))
+    if javac_processor_classpath:
+        utils.log_message(
+            "javac_processor_classpath: {}".format(javac_processor_classpath)
+        )
+    if javac_bootclasspath_file:
+        utils.log_message(
+            "javac_bootclasspath_file: {}".format(javac_bootclasspath_file)
+        )
+    if resources_dir:
+        utils.log_message("resources_dir: {}".format(resources_dir))
+    if concat_resources:
+        utils.log_message("concat_resources: {}".format(concat_resources))
+    if generated_sources_dir:
+        utils.log_message("generated_sources_dir: {}".format(generated_sources_dir))
+        if not generated_sources_dir.exists():
+            generated_sources_dir.mkdir()
+    if manifest:
+        utils.log_message("manifest: {}".format(manifest))
+    if remove_classes_file:
+        utils.log_message("remove classes file: {}".format(remove_classes_file))
+    if additional_compiled_srcs:
+        utils.log_message(
+            "additional_compiled_srcs: {}".format(additional_compiled_srcs)
+        )
+
+    with TemporaryDirectory() as temp_dir:
+        temp_build_dir = pathlib.Path(temp_dir)
+        javac_output = temp_build_dir / "classes"
+        javac_output.mkdir(parents=True, exist_ok=True)
+
+        if not skip_javac_run:
+            _run_javac(
+                javac_tool,
+                javac_args,
+                javac_output,
+                zipped_sources_file,
+                javac_classpath,
+                javac_processor_classpath,
+                javac_bootclasspath_file,
+                generated_sources_dir,
+                temp_build_dir,
+                javac_jvm_args_file,
+            )
+            if multi_release_args_file:
+                # add javac_output as classpath for the multi-release build
+                multi_release_classpath = _get_multi_release_classpath(
+                    temp_build_dir, javac_classpath, javac_output
+                )
+                multi_release_manifest = _get_multi_release_manifest(temp_build_dir)
+                manifest_files.append(multi_release_manifest)
+
+                utils.log_message(f"multi_release_manifest: {multi_release_manifest}")
+                utils.log_message(f"multi_release_classpath: {multi_release_classpath}")
+
+                for multi_release_args in multi_release_args_file:
+                    # The release file should be named as args.java<release_version>
+                    multi_release_version = _get_multi_release_version(
+                        multi_release_args
+                    )
+                    if not multi_release_version:
+                        raise Exception(
+                            f"Invalid release args file: {multi_release_args}"
+                        )
+
+                    # Multi-release classes are located in META-INF/versions/<multi_release_version>
+                    multi_release_output = (
+                        javac_output / f"META-INF/versions/{multi_release_version}"
+                    )
+
+                    utils.log_message(
+                        f"javac multi_release {multi_release_version} at {multi_release_output}"
+                    )
+
+                    _run_javac(
+                        javac_tool,
+                        multi_release_args,
+                        multi_release_output,
+                        None,
+                        multi_release_classpath,
+                        javac_processor_classpath,
+                        javac_bootclasspath_file,
+                        generated_sources_dir,
+                        temp_build_dir,
+                    )
+
+        _run_jar(
+            jar_builder_tool,
+            output_path,
+            manifest_files,
+            javac_output,
+            resources_dir,
+            additional_compiled_srcs,
+            remove_classes_file,
+            temp_build_dir,
+            concat_resources,
+        )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/java/tools/fat_jar.py b/buck2/prelude/java/tools/fat_jar.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/fat_jar.py
@@ -0,0 +1,482 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import os
+import pathlib
+import zipfile
+from shutil import copy, copytree
+from tempfile import TemporaryDirectory
+from typing import Optional
+
+import utils
+
+
+def _prepare_meta_inf_override(
+    meta_inf_staging: pathlib.Path,
+    temp_dir: str,
+    concat_jars: bool,
+) -> pathlib.Path:
+    """Prepare the meta_inf override entries file for the jar builder.
+
+    When concat_jars is True, packages the meta_inf_staging directory into a
+    jar file first (ConcatJarBuilder requires all entries to be jar files).
+    Otherwise, passes the directory path directly.
+
+    Returns the path to a file whose content is the path to the override entry.
+    """
+    if concat_jars:
+        # ConcatJarBuilder requires all entries to be jar files,
+        # so package the meta_inf_staging directory into a jar.
+        meta_inf_jar = pathlib.Path(temp_dir) / "meta_inf_staging.jar"
+        with zipfile.ZipFile(
+            meta_inf_jar,
+            mode="w",
+            strict_timestamps=False,
+            compression=zipfile.ZIP_STORED,
+        ) as zf:
+            for content in meta_inf_staging.rglob("*"):
+                if content.is_file():
+                    zf.write(
+                        content,
+                        content.relative_to(meta_inf_staging),
+                    )
+        meta_inf_directory_file = pathlib.Path(temp_dir) / "meta_inf_directory_file"
+        meta_inf_directory_file.write_text(str(meta_inf_jar))
+    else:
+        meta_inf_directory_file = pathlib.Path(temp_dir) / "meta_inf_directory_file"
+        meta_inf_directory_file.write_text(str(meta_inf_staging))
+
+    return meta_inf_directory_file
+
+
+def _parse_args():
+    parser = argparse.ArgumentParser(
+        description="Tool to create a fat jar from passed multiple jars."
+    )
+
+    parser.add_argument(
+        "--jar_builder_tool",
+        type=str,
+        required=True,
+        help="tool for building jars",
+    )
+    parser.add_argument(
+        "--zip_scrubber_tool",
+        type=str,
+        required=True,
+        help="tool for scrubbing jars",
+    )
+    parser.add_argument(
+        "--output", type=pathlib.Path, required=True, help="a path to an output result"
+    )
+    parser.add_argument(
+        "--jars_file",
+        type=pathlib.Path,
+        required=True,
+        help="paths to file with stored jars paths for merging",
+    )
+    parser.add_argument(
+        "--main_class", type=str, help="main class to include into manifest file"
+    )
+    parser.add_argument(
+        "--manifest",
+        type=pathlib.Path,
+        help="a path to a custom manifest file",
+    )
+    parser.add_argument(
+        "--build_manifest",
+        type=pathlib.Path,
+        help="a path to a custom build manifest file",
+    )
+    parser.add_argument(
+        "--blocklist",
+        type=pathlib.Path,
+        help="paths to file with stored blocklist patterns",
+    )
+    parser.add_argument(
+        "--meta_inf_directory",
+        type=pathlib.Path,
+        help="a path to a custom META-INF directory artifacts",
+    )
+
+    # generate wrapper params
+    parser.add_argument(
+        "--generate_wrapper",
+        required=False,
+        action="store_true",
+        help="flag that if set then need to produce an executable script as a final artifact",
+    )
+    parser.add_argument(
+        "--classpath_args_output",
+        type=pathlib.Path,
+        required=False,
+        help="a path to an classpath args file",
+    )
+    parser.add_argument("--java_tool", type=pathlib.Path, help="a path to a java tool")
+    parser.add_argument(
+        "--script_marker_file_name",
+        type=str,
+        help="In case of generate script wrapper is set and native libraries are present the marker file would be stored inside the final fat jar",
+    )
+
+    # native libraries params
+    parser.add_argument(
+        "--native_libs_file",
+        type=pathlib.Path,
+        help="paths to file with stored native libs paths",
+    )
+    parser.add_argument(
+        "--fat_jar_lib",
+        type=pathlib.Path,
+        help="path to fat jar lib that contains fat jar main class",
+    )
+    parser.add_argument(
+        "--fat_jar_main_class",
+        type=str,
+        help="Fat jar's main class",
+    )
+    parser.add_argument(
+        "--fat_jar_native_libs_directory_name",
+        type=str,
+        help="Fat jar's native libraries directory name",
+    )
+    parser.add_argument(
+        "--do_not_create_inner_jar",
+        required=False,
+        action="store_true",
+        help="Whether to create an inner jar if native libraries are present.",
+    )
+    parser.add_argument(
+        "--append_jar",
+        required=False,
+        type=pathlib.Path,
+        help="path to a jar used as base of the new jar, which new files will be added",
+    )
+    parser.add_argument(
+        "--concat_jars",
+        required=False,
+        action="store_true",
+        help="If the jar aggrgation should use concat instead of merge.",
+    )
+
+    return parser.parse_args()
+
+
+def _fat_jar(
+    jar_builder_tool: str,
+    output_path: str,
+    append_jar: Optional[str] = None,
+    concat_jars: Optional[bool] = False,
+    main_class: Optional[str] = None,
+    entries_to_jar_file: Optional[str] = None,
+    override_entries_to_jar_file: Optional[str] = None,
+    manifest_file: Optional[str] = None,
+    build_manifest_file: Optional[str] = None,
+    blocklist_file: Optional[str] = None,
+) -> None:
+    cmd = []
+    cmd.extend(utils.shlex_split(jar_builder_tool))
+    if append_jar:
+        cmd.extend(["--append-jar", append_jar])
+    if main_class:
+        cmd.extend(["--main-class", main_class])
+    if entries_to_jar_file:
+        cmd.extend(["--entries-to-jar", entries_to_jar_file])
+        if concat_jars:
+            cmd.append("--concat-jars")
+    if override_entries_to_jar_file:
+        cmd.extend(["--override-entries-to-jar", override_entries_to_jar_file])
+    if manifest_file:
+        cmd.extend(["--manifest-file", manifest_file])
+    if build_manifest_file:
+        cmd.extend(["--manifest-file", build_manifest_file])
+    if blocklist_file:
+        cmd.extend(["--blocklist-patterns", blocklist_file])
+        cmd.extend(["--blocklist-patterns-matcher", "substring"])
+    cmd.append("--merge-manifests")
+    cmd.extend(["--output", output_path])
+    utils.log_message("fat_jar_cmd: {}".format(cmd))
+    utils.execute_command(cmd)
+
+
+# Reads a list of files from native_libs_file and symlinks each as files in native_libs_dir.
+# native_libs_dir's contents are used as input to create the jar.
+def build_native_libs_dir(
+    native_libs_file: str, current_working_directory: str, native_libs_dir: str
+) -> None:
+    with open(native_libs_file) as f:
+        lines = f.readlines()
+        for line in lines:
+            so_name, native_lib_name = line.rstrip().split(" ")
+            native_lib_path = os.path.join(current_working_directory, native_lib_name)
+            os.symlink(
+                native_lib_path,
+                os.path.join(native_libs_dir, so_name),
+            )
+
+
+def main():
+    args = _parse_args()
+
+    jar_builder_tool = args.jar_builder_tool
+    zip_scrubber_tool = args.zip_scrubber_tool
+    output_path = args.output
+    jars_file = args.jars_file
+    main_class = args.main_class
+    manifest = args.manifest
+    build_manifest = args.build_manifest
+    blocklist_file = args.blocklist
+    meta_inf_directory = args.meta_inf_directory
+    append_jar = args.append_jar
+
+    concat_jars = args.concat_jars
+    generate_wrapper = args.generate_wrapper
+    classpath_args_output = args.classpath_args_output
+    java_tool = args.java_tool
+    script_marker_file_name = args.script_marker_file_name
+
+    native_libs_file = args.native_libs_file
+    do_not_create_inner_jar = args.do_not_create_inner_jar
+    fat_jar_lib = args.fat_jar_lib
+    fat_jar_main_class = args.fat_jar_main_class
+    fat_jar_native_libs_directory_name = args.fat_jar_native_libs_directory_name
+
+    utils.log_message("jar_builder_tool: {}".format(jar_builder_tool))
+    utils.log_message("output: {}".format(output_path))
+    utils.log_message("jars_file: {}".format(jars_file))
+
+    if native_libs_file:
+        utils.log_message("native_libs_file: {}".format(native_libs_file))
+        utils.log_message("fat_jar_lib: {}".format(fat_jar_lib))
+        utils.log_message("fat_jar_main_class: {}".format(fat_jar_main_class))
+        utils.log_message(
+            "fat_jar_native_libs_directory_name: {}".format(
+                fat_jar_native_libs_directory_name
+            )
+        )
+        utils.log_message("do_not_create_inner_jar: {}".format(do_not_create_inner_jar))
+
+    if main_class:
+        utils.log_message("main_class = {}".format(main_class))
+    if manifest:
+        utils.log_message("manifest = {}".format(manifest))
+    if build_manifest:
+        utils.log_message("build_manifest = {}".format(build_manifest))
+    if blocklist_file:
+        utils.log_message("blocklist_file = {}".format(blocklist_file))
+    if meta_inf_directory:
+        utils.log_message("meta_inf_directory = {}".format(meta_inf_directory))
+    if generate_wrapper:
+        utils.log_message("generate_wrapper = {}".format(generate_wrapper))
+        utils.log_message("classpath_args_output: {}".format(classpath_args_output))
+        utils.log_message("java_tool: {}".format(java_tool))
+        utils.log_message("script_marker_file_name: {}".format(script_marker_file_name))
+    if append_jar:
+        utils.log_message("append_jar = {}".format(append_jar))
+    if concat_jars:
+        utils.log_message("concat_jars = {}".format(concat_jars))
+
+    need_to_process_native_libs = native_libs_file is not None
+    if need_to_process_native_libs and not do_not_create_inner_jar:
+        if (
+            fat_jar_lib is None
+            or fat_jar_main_class is None
+            or fat_jar_native_libs_directory_name is None
+        ):
+            raise AssertionError(
+                "All native libraries inner jar related params have to be present!"
+            )
+    else:
+        if (
+            fat_jar_lib is not None
+            or fat_jar_main_class is not None
+            or fat_jar_native_libs_directory_name is not None
+        ):
+            raise AssertionError(
+                "All native libraries inner jar related params should not be present!"
+            )
+
+    if generate_wrapper is True:
+        if (
+            classpath_args_output is None
+            or java_tool is None
+            or script_marker_file_name is None
+        ):
+            raise AssertionError(
+                "All generate wrapper related params have to be present!"
+            )
+    else:
+        if (
+            classpath_args_output is not None
+            or java_tool is not None
+            or script_marker_file_name is not None
+        ):
+            raise AssertionError(
+                "All generate wrapper related params have to be present!"
+            )
+
+    current_working_directory = os.getcwd()
+    with TemporaryDirectory() as temp_dir:
+        if generate_wrapper:  # generate wrapper script
+            jars = []
+            with open(jars_file) as f:
+                lines = f.readlines()
+                for line in lines:
+                    jars.append(line.rstrip())
+            utils.log_message("jars: {}".format(jars))
+            with open(classpath_args_output, "w") as f:
+                f.write(":".join(jars))
+
+            jar_output = output_path
+            with open(jar_output, "w") as f:
+                script_args = [
+                    str(java_tool),
+                    "-cp",
+                    "@" + str(classpath_args_output),
+                ]
+                if main_class:
+                    script_args.append(main_class)
+                script_args.append('"$@"')
+
+                f.write(" ".join(script_args))
+
+        else:  # generate fat jar
+            entries_to_jar_file = jars_file
+            override_entries_to_jar = None
+
+            if need_to_process_native_libs and do_not_create_inner_jar:
+                # symlink native libs to `nativelibs` directory
+                native_libs_staging = pathlib.Path(temp_dir) / "native_libs_staging"
+                native_libs_staging.mkdir()
+                native_libs_staging_subdir = (
+                    pathlib.Path(temp_dir) / "native_libs_staging" / "nativelibs"
+                )
+                native_libs_staging_subdir.mkdir()
+                build_native_libs_dir(
+                    native_libs_file=native_libs_file,
+                    current_working_directory=current_working_directory,
+                    native_libs_dir=native_libs_staging_subdir,
+                )
+                jars_and_native_libs_directory_file = (
+                    pathlib.Path(temp_dir) / "jars_and_nativelibs_directory_file"
+                )
+                # combine jars_file and native_libs_file into a single set of entries
+                with open(jars_and_native_libs_directory_file, "w") as f:
+                    with open(jars_file, "r") as f2:
+                        f.write(str(f2.read()) + "\n")
+                    f.write(str(native_libs_staging))
+
+                entries_to_jar_file = jars_and_native_libs_directory_file
+
+            if meta_inf_directory:
+                meta_inf_staging = pathlib.Path(temp_dir) / "meta_inf_staging"
+                meta_inf_staging.mkdir()
+                copytree(
+                    meta_inf_directory,
+                    meta_inf_staging / "META-INF",
+                    copy_function=copy,
+                    dirs_exist_ok=True,
+                )
+
+                override_entries_to_jar = _prepare_meta_inf_override(
+                    meta_inf_staging,
+                    temp_dir,
+                    concat_jars,
+                )
+
+            jar_output = (
+                os.path.join(temp_dir, "inner.jar")
+                if need_to_process_native_libs and not do_not_create_inner_jar
+                else output_path
+            )
+
+            utils.log_message("jar_output: {}".format(jar_output))
+
+            _fat_jar(
+                jar_builder_tool=jar_builder_tool,
+                output_path=jar_output,
+                main_class=main_class,
+                entries_to_jar_file=entries_to_jar_file,
+                override_entries_to_jar_file=override_entries_to_jar,
+                manifest_file=manifest,
+                build_manifest_file=build_manifest,
+                blocklist_file=blocklist_file,
+                append_jar=append_jar,
+                concat_jars=concat_jars,
+            )
+
+        if need_to_process_native_libs and not do_not_create_inner_jar:
+            fat_jar_content_dir = os.path.join(temp_dir, "fat_jar_content_dir")
+            os.mkdir(fat_jar_content_dir)
+
+            # copy inner.jar into an appropriate location for packaging
+            inner_jar_file = os.path.join(fat_jar_content_dir, "inner.jar")
+            if generate_wrapper:
+                copy(
+                    jar_output,
+                    inner_jar_file,
+                )
+                # marker file used in FatJarMain.java main class to correctly launch a new jvm process with native libs.
+                marker_file = os.path.join(fat_jar_content_dir, script_marker_file_name)
+                pathlib.Path(marker_file).touch()
+            else:
+                os.symlink(
+                    jar_output,
+                    inner_jar_file,
+                )
+
+            # symlink native libs to `nativelibs` directory
+            native_libs_dir = os.path.join(
+                fat_jar_content_dir, fat_jar_native_libs_directory_name
+            )
+            os.mkdir(native_libs_dir)
+
+            build_native_libs_dir(
+                native_libs_file=native_libs_file,
+                current_working_directory=current_working_directory,
+                native_libs_dir=native_libs_dir,
+            )
+
+            # Build the final fat JAR from the structure we've laid out above.  We first package the
+            # fat jar resources (e.g. native libs) using the "stored" compression level, to avoid
+            # expensive compression on builds and decompression on startup.
+            contents_zip_path = os.path.join(temp_dir, "contents.zip")
+            with zipfile.ZipFile(
+                contents_zip_path,
+                mode="w",
+                strict_timestamps=False,
+                compression=zipfile.ZIP_STORED,
+            ) as contents_zip:
+                for content in pathlib.Path(fat_jar_content_dir).rglob("*"):
+                    contents_zip.write(
+                        content,
+                        content.relative_to(fat_jar_content_dir),
+                    )
+
+            zip_scrubber_cmd = []
+            zip_scrubber_cmd.extend(utils.shlex_split(zip_scrubber_tool))
+            zip_scrubber_cmd.append(contents_zip_path)
+            utils.execute_command(zip_scrubber_cmd)
+
+            entries_to_jar_file = os.path.join(temp_dir, "entries_to_jar.txt")
+            with open(entries_to_jar_file, "w") as f:
+                f.write("\n".join([contents_zip_path, str(fat_jar_lib)]))
+
+            _fat_jar(
+                jar_builder_tool=jar_builder_tool,
+                output_path=output_path,
+                main_class=fat_jar_main_class,
+                entries_to_jar_file=entries_to_jar_file,
+                build_manifest_file=build_manifest,
+            )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/java/tools/gen_class_to_source_map.py b/buck2/prelude/java/tools/gen_class_to_source_map.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/gen_class_to_source_map.py
@@ -0,0 +1,238 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import zipfile
+from collections import defaultdict
+from collections.abc import Iterable
+from typing import TextIO
+
+
+def _base_class_name_matches_base_source_path(
+    base_class_name: str, base_source_path: str
+) -> bool:
+    return base_class_name == base_source_path or base_source_path.endswith(
+        "/" + base_class_name
+    )
+
+
+def _source_stem(source_path: str) -> str:
+    return os.path.splitext(os.path.basename(source_path))[0]
+
+
+def _normalize_kotlin_file_facade(class_name: str, source_path: str | None) -> str:
+    if source_path is None or not class_name.endswith("Kt"):
+        return class_name
+
+    # A Kotlin file facade (`Foo.kt` -> class `FooKt`) is renamed back to the file
+    # name, but a real class literally named `FooKt` (from `FooKt.kt`) is left alone.
+    simple_name = class_name.rsplit(".", 1)[-1]
+    if simple_name[:-2] == _source_stem(source_path):
+        return class_name[:-2]
+    return class_name
+
+
+def _load_debug_class_to_source_map(path: str | None) -> dict[str, str]:
+    if path is None:
+        return {}
+
+    with open(path) as debuginfo_file:
+        source_files = json.load(debuginfo_file)
+
+    class_to_sources: defaultdict[str, set[str]] = defaultdict(set)
+    for source_file in source_files:
+        for class_info in source_file["classes"]:
+            class_to_sources[class_info["name"]].add(source_file["file_path"])
+
+    unique_class_to_source: dict[str, str] = {}
+    for class_name, source_paths in class_to_sources.items():
+        # Never guess which source owns a class claimed by multiple files.
+        if len(source_paths) != 1:
+            continue
+        unique_class_to_source[class_name] = next(iter(source_paths))
+    return unique_class_to_source
+
+
+def _legacy_source_for_class(class_name: str, sources: dict[str, str]) -> str | None:
+    base_class_name = class_name.replace(".", "/")
+    for source_base, source_path in sources.items():
+        if _base_class_name_matches_base_source_path(base_class_name, source_base) or (
+            base_class_name.endswith("Kt")
+            and _base_class_name_matches_base_source_path(
+                base_class_name[:-2], source_base
+            )
+        ):
+            return source_path
+    return None
+
+
+def _resolve_source_path(
+    compiled_class: str,
+    top_level_class: str,
+    debug_class_to_source: dict[str, str],
+    legacy_sources: dict[str, str],
+) -> str | None:
+    # Debug records are authoritative. Legacy matching keeps toolchains without
+    # debug support, and classes missing from otherwise valid debug data, working.
+    return (
+        debug_class_to_source.get(compiled_class)
+        or debug_class_to_source.get(top_level_class)
+        or _legacy_source_for_class(top_level_class, legacy_sources)
+    )
+
+
+def _source_identity(class_name: str, source_path: str) -> str:
+    package, _, _ = class_name.rpartition(".")
+    source_stem = _source_stem(source_path)
+    return package + "." + source_stem if package else source_stem
+
+
+def _jar_class_names(jar: str) -> list[str]:
+    with zipfile.ZipFile(jar) as jar_file:
+        return [
+            entry[:-6].replace("/", ".")
+            for entry in jar_file.namelist()
+            if entry.endswith(".class")
+        ]
+
+
+def _add_source_identity_aliases(entries: dict[str, dict[str, str]]) -> None:
+    # Android aggregate coverage identifies a source by package and file stem.
+    # Preserve a real class mapping if it has the same name as that identity.
+    for entry in list(entries.values()):
+        source_path = entry.get("srcPath")
+        if source_path is None:
+            continue
+        identity = _source_identity(entry["className"], source_path)
+        entries.setdefault(identity, {"className": identity, "srcPath": source_path})
+
+
+def _build_class_entries(
+    jar: str,
+    source_paths: Iterable[str],
+    debuginfo: str | None,
+    include_classes_prefixes: Iterable[str],
+) -> list[dict[str, str]]:
+    legacy_sources = {os.path.splitext(source)[0]: source for source in source_paths}
+    debug_class_to_source = _load_debug_class_to_source_map(debuginfo)
+    include_prefixes = tuple(include_classes_prefixes)
+    entries: dict[str, dict[str, str]] = {}
+
+    for compiled_class in _jar_class_names(jar):
+        top_level_class = compiled_class.split("$", 1)[0]
+        source_path = _resolve_source_path(
+            compiled_class,
+            top_level_class,
+            debug_class_to_source,
+            legacy_sources,
+        )
+        class_name = _normalize_kotlin_file_facade(top_level_class, source_path)
+        existing_entry = entries.get(class_name)
+        if source_path is not None:
+            # Nested and synthetic classes collapse to their top-level class. Prefer
+            # a sourceful mapping regardless of their order in the JAR.
+            if existing_entry is None or "srcPath" not in existing_entry:
+                entries[class_name] = {
+                    "className": class_name,
+                    "srcPath": source_path,
+                }
+        elif (
+            existing_entry is None
+            and "$" not in compiled_class
+            and compiled_class.startswith(include_prefixes)
+        ):
+            entries[class_name] = {"className": class_name}
+
+    _add_source_identity_aliases(entries)
+
+    return list(entries.values())
+
+
+def _write_sources_jar(classes: Iterable[dict[str, str]], output: str) -> None:
+    # Several classes can share one source file, so entries are keyed by source path
+    # and named after the file rather than the class to avoid source duplication.
+    written_sources: set[str] = set()
+    with zipfile.ZipFile(output, "w") as sources_jar:
+        for entry in classes:
+            source_path = entry.get("srcPath")
+            if source_path is None or source_path in written_sources:
+                continue
+            written_sources.add(source_path)
+            package, _, _ = entry["className"].rpartition(".")
+            package_dir = package.replace(".", "/")
+            source_name = os.path.basename(source_path)
+            archive_path = (
+                package_dir + "/" + source_name if package_dir else source_name
+            )
+            sources_jar.write(source_path, archive_path)
+
+
+def generate_class_to_source_map(
+    jar: str,
+    source_paths: Iterable[str],
+    output: TextIO,
+    *,
+    debuginfo: str | None = None,
+    include_classes_prefixes: Iterable[str] = (),
+    owner_target: str | None = None,
+    sources_jar: str | None = None,
+) -> None:
+    classes = _build_class_entries(
+        jar,
+        source_paths,
+        debuginfo,
+        include_classes_prefixes,
+    )
+    if sources_jar is not None:
+        _write_sources_jar(classes, sources_jar)
+
+    result = {"jarPath": jar, "classes": classes}
+    if owner_target is not None:
+        result["ownerTarget"] = owner_target
+    json.dump(result, output)
+    output.write("\n")
+
+
+def main(argv: list[str]) -> int:
+    parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
+    parser.add_argument(
+        "--include_classes_prefixes",
+        "-i",
+        default=[],
+        nargs="*",
+        help="Prefixes of classes to include in the output, even if their source isn't present",
+    )
+    parser.add_argument(
+        "--output", "-o", type=argparse.FileType("w"), default=sys.stdout
+    )
+    parser.add_argument("--sources_jar", required=False)
+    parser.add_argument("--debuginfo", required=False)
+    parser.add_argument("--owner-target", required=False)
+    parser.add_argument("jar")
+    parser.add_argument("sources", nargs="*")
+    args = parser.parse_args(argv[1:])
+
+    generate_class_to_source_map(
+        args.jar,
+        args.sources,
+        args.output,
+        debuginfo=args.debuginfo,
+        include_classes_prefixes=args.include_classes_prefixes,
+        owner_target=args.owner_target,
+        sources_jar=args.sources_jar,
+    )
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv))
diff --git a/buck2/prelude/java/tools/list_class_names.py b/buck2/prelude/java/tools/list_class_names.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/list_class_names.py
@@ -0,0 +1,104 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import pathlib
+import zipfile
+
+
+def _parse_args():
+    parser = argparse.ArgumentParser(
+        description="Tool to list all the classes found in a jar."
+    )
+
+    parser.add_argument(
+        "--jar",
+        type=pathlib.Path,
+        required=True,
+        help="a path to a .jar to list classes for",
+    )
+    parser.add_argument(
+        "--sources",
+        type=pathlib.Path,
+        required=True,
+        help="A file containing a list of sources that were used to create the .jar",
+    )
+    parser.add_argument(
+        "--output",
+        type=pathlib.Path,
+        required=True,
+        help="a path to write the output to",
+    )
+    parser.add_argument(
+        "--discover-all",
+        action="store_true",
+        default=False,
+        help="Include all top-level classes from the jar, skipping stem-based "
+        "source matching. Useful for Kotlin targets where file names may not "
+        "match class names.",
+    )
+
+    return parser.parse_args()
+
+
+_SUPPORTED_ARCHIVE_SUFFIXES = [".src.zip", "-sources.jar"]
+
+
+def _is_supported_archive(src):
+    for supported_suffix in _SUPPORTED_ARCHIVE_SUFFIXES:
+        if src.name.endswith(supported_suffix):
+            return True
+    return False
+
+
+def _get_class_names(
+    sources_path: pathlib.Path, jar_path: pathlib.Path, discover_all: bool = False
+):
+    sources = set()
+    if not discover_all:
+        with open(sources_path, "r") as sources_file:
+            for line in sources_file.readlines():
+                source_file_path = pathlib.Path(line.strip())
+                if _is_supported_archive(source_file_path):
+                    with zipfile.ZipFile(source_file_path, "r") as sources_archive:
+                        for archived_source in sources_archive.namelist():
+                            sources.add(pathlib.Path(archived_source).stem)
+                else:
+                    sources.add(source_file_path.stem)
+
+    with zipfile.ZipFile(jar_path, "r") as jar:
+        class_names = []
+        for file_name in jar.namelist():
+            if not file_name.endswith(".class"):
+                continue
+
+            if "$" in file_name:
+                continue
+
+            if discover_all or pathlib.Path(file_name).stem in sources:
+                # Remove the .class suffix and convert the path of the
+                # compiled class to a fully-qualified name.
+                class_names.append(file_name[:-6].replace("/", "."))
+
+    return class_names
+
+
+def main():
+    args = _parse_args()
+    sources = args.sources
+    jar = args.jar
+    output = args.output
+
+    classes = _get_class_names(sources, jar, discover_all=args.discover_all)
+    with open(output, "a") as output_file:
+        output_file.write("\n".join(classes))
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/java/tools/merge_class_to_source_maps.py b/buck2/prelude/java/tools/merge_class_to_source_maps.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/merge_class_to_source_maps.py
@@ -0,0 +1,50 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+import os
+import pathlib
+import sys
+
+
+def merge_class_to_source_maps(mappings, output, relative_to=None):
+    for mapping in mappings:
+        with open(mapping) as f:
+            obj = json.load(f)
+
+        if relative_to is not None:
+            obj["jarPath"] = os.path.relpath(obj["jarPath"], relative_to)
+            for class_entry in obj["classes"]:
+                if "srcPath" in class_entry:
+                    class_entry["srcPath"] = os.path.relpath(
+                        class_entry["srcPath"], relative_to
+                    )
+
+        json.dump(obj, output)
+        print("", file=output)
+
+
+def main(argv):
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--output", "-o", type=argparse.FileType("w"), default=sys.stdin
+    )
+    parser.add_argument(
+        "--relative-to",
+    )
+    parser.add_argument("--mappings", "-m", type=pathlib.Path, required=True)
+    args = parser.parse_args(argv[1:])
+
+    with open(args.mappings) as f:
+        mappings = [line.replace("\n", "") for line in f.readlines()]
+    merge_class_to_source_maps(mappings, args.output, args.relative_to)
+
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv))
diff --git a/buck2/prelude/java/tools/run_postprocessor.py b/buck2/prelude/java/tools/run_postprocessor.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/run_postprocessor.py
@@ -0,0 +1,50 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import pathlib
+
+import utils
+
+
+def _parse_args():
+    parser = argparse.ArgumentParser(description="Tool to run a jar postprocessor.")
+
+    parser.add_argument(
+        "--postprocessor_cmd",
+        type=str,
+        required=True,
+    )
+    parser.add_argument(
+        "--zip_scrubber",
+        type=str,
+        required=True,
+        help="A command to run a zip scrubber",
+    )
+    parser.add_argument(
+        "--output",
+        type=pathlib.Path,
+        required=True,
+        help="the path that the postprocessor writes to, which is then scrubbed",
+    )
+
+    return parser.parse_args()
+
+
+def main():
+    args = _parse_args()
+
+    utils.execute_command(utils.shlex_split(args.postprocessor_cmd))
+
+    scrubber_cmd = utils.shlex_split(args.zip_scrubber) + [args.output]
+    utils.execute_command(scrubber_cmd)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/java/tools/tests/test_fat_jar.py b/buck2/prelude/java/tools/tests/test_fat_jar.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/tests/test_fat_jar.py
@@ -0,0 +1,120 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import pathlib
+import tempfile
+import unittest
+import zipfile
+
+from fat_jar import _prepare_meta_inf_override
+
+
+class PrepareMetaInfOverrideTest(unittest.TestCase):
+    def test_without_concat_jars_points_to_directory(self):
+        # Setup: create a meta_inf_staging directory with a META-INF/services file.
+        with tempfile.TemporaryDirectory() as temp_dir:
+            meta_inf_staging = pathlib.Path(temp_dir) / "meta_inf_staging"
+            meta_inf_staging.mkdir()
+            services_dir = meta_inf_staging / "META-INF" / "services"
+            services_dir.mkdir(parents=True)
+            service_file = services_dir / "com.example.MyService"
+            service_file.write_text("com.example.MyServiceImpl\n")
+
+            override_dir = pathlib.Path(temp_dir) / "override"
+            override_dir.mkdir()
+
+            # Execute: call with concat_jars=False.
+            result = _prepare_meta_inf_override(
+                meta_inf_staging, str(override_dir), concat_jars=False
+            )
+
+            # Assert: the returned file points to the staging directory (not a jar).
+            self.assertTrue(result.exists())
+            override_path = result.read_text()
+            self.assertEqual(override_path, str(meta_inf_staging))
+            self.assertTrue(pathlib.Path(override_path).is_dir())
+
+    def test_with_concat_jars_points_to_jar(self):
+        # Setup: create a meta_inf_staging directory with a META-INF/services file.
+        with tempfile.TemporaryDirectory() as temp_dir:
+            meta_inf_staging = pathlib.Path(temp_dir) / "meta_inf_staging"
+            meta_inf_staging.mkdir()
+            services_dir = meta_inf_staging / "META-INF" / "services"
+            services_dir.mkdir(parents=True)
+            service_file = services_dir / "com.example.MyService"
+            service_file.write_text("com.example.MyServiceImpl\n")
+
+            override_dir = pathlib.Path(temp_dir) / "override"
+            override_dir.mkdir()
+
+            # Execute: call with concat_jars=True.
+            result = _prepare_meta_inf_override(
+                meta_inf_staging, str(override_dir), concat_jars=True
+            )
+
+            # Assert: the returned file points to a valid jar file (not a directory).
+            self.assertTrue(result.exists())
+            jar_path = pathlib.Path(result.read_text())
+            self.assertTrue(jar_path.exists())
+            self.assertTrue(str(jar_path).endswith(".jar"))
+
+            # Verify the jar contains the expected META-INF entry.
+            with zipfile.ZipFile(jar_path, "r") as zf:
+                names = zf.namelist()
+                self.assertIn("META-INF/services/com.example.MyService", names)
+                content = zf.read("META-INF/services/com.example.MyService").decode()
+                self.assertEqual(content, "com.example.MyServiceImpl\n")
+
+    def test_with_concat_jars_multiple_files(self):
+        # Setup: create a meta_inf_staging directory with multiple META-INF files.
+        with tempfile.TemporaryDirectory() as temp_dir:
+            meta_inf_staging = pathlib.Path(temp_dir) / "meta_inf_staging"
+            meta_inf_staging.mkdir()
+            services_dir = meta_inf_staging / "META-INF" / "services"
+            services_dir.mkdir(parents=True)
+            (services_dir / "com.example.ServiceA").write_text("ImplA\n")
+            (services_dir / "com.example.ServiceB").write_text("ImplB\n")
+
+            override_dir = pathlib.Path(temp_dir) / "override"
+            override_dir.mkdir()
+
+            # Execute: call with concat_jars=True.
+            result = _prepare_meta_inf_override(
+                meta_inf_staging, str(override_dir), concat_jars=True
+            )
+
+            # Assert: the jar contains both service files.
+            jar_path = pathlib.Path(result.read_text())
+            with zipfile.ZipFile(jar_path, "r") as zf:
+                names = zf.namelist()
+                self.assertIn("META-INF/services/com.example.ServiceA", names)
+                self.assertIn("META-INF/services/com.example.ServiceB", names)
+
+    def test_with_concat_jars_skips_directories(self):
+        # Setup: create a meta_inf_staging directory with nested subdirectories.
+        with tempfile.TemporaryDirectory() as temp_dir:
+            meta_inf_staging = pathlib.Path(temp_dir) / "meta_inf_staging"
+            meta_inf_staging.mkdir()
+            nested_dir = meta_inf_staging / "META-INF" / "nested" / "deep"
+            nested_dir.mkdir(parents=True)
+            (nested_dir / "file.txt").write_text("content\n")
+
+            override_dir = pathlib.Path(temp_dir) / "override"
+            override_dir.mkdir()
+
+            # Execute: call with concat_jars=True.
+            result = _prepare_meta_inf_override(
+                meta_inf_staging, str(override_dir), concat_jars=True
+            )
+
+            # Assert: only the file is in the jar, not directory entries.
+            jar_path = pathlib.Path(result.read_text())
+            with zipfile.ZipFile(jar_path, "r") as zf:
+                names = zf.namelist()
+                self.assertEqual(names, ["META-INF/nested/deep/file.txt"])
diff --git a/buck2/prelude/java/tools/tests/test_gen_class_to_source_map.py b/buck2/prelude/java/tools/tests/test_gen_class_to_source_map.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/tests/test_gen_class_to_source_map.py
@@ -0,0 +1,380 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import io
+import json
+import pathlib
+import tempfile
+import unittest
+import zipfile
+from contextlib import redirect_stdout
+
+from gen_class_to_source_map import generate_class_to_source_map, main
+
+
+class GenClassToSourceMapTest(unittest.TestCase):
+    def _generate(
+        self,
+        directory: pathlib.Path,
+        *,
+        jar_classes: list[str],
+        sources: list[pathlib.Path],
+        debuginfo: list[dict] | None,
+        include_prefixes: tuple[str, ...] = (),
+        sources_jar: str | None = None,
+    ) -> list[dict[str, str]]:
+        jar_path = directory / "library.jar"
+        with zipfile.ZipFile(jar_path, "w") as jar:
+            for class_name in jar_classes:
+                jar.writestr(class_name.replace(".", "/") + ".class", b"")
+
+        debuginfo_path = None
+        if debuginfo is not None:
+            debuginfo_file = directory / "debuginfo.json"
+            debuginfo_file.write_text(json.dumps(debuginfo))
+            debuginfo_path = str(debuginfo_file)
+
+        output = io.StringIO()
+        generate_class_to_source_map(
+            str(jar_path),
+            [str(source) for source in sources],
+            output,
+            debuginfo=debuginfo_path,
+            include_classes_prefixes=include_prefixes,
+            sources_jar=sources_jar,
+        )
+        return json.loads(output.getvalue())["classes"]
+
+    def test_maps_case_mismatch_for_class_and_source_consumers(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            source = directory / "MWATestInitializer.kt"
+            classes = self._generate(
+                directory,
+                jar_classes=["com.example.MwaTestInitializer"],
+                sources=[source],
+                debuginfo=[
+                    {
+                        "file_path": str(source),
+                        "classes": [{"name": "com.example.MwaTestInitializer"}],
+                    }
+                ],
+            )
+
+        self.assertEqual(
+            classes,
+            [
+                {
+                    "className": "com.example.MwaTestInitializer",
+                    "srcPath": str(source),
+                },
+                {
+                    "className": "com.example.MWATestInitializer",
+                    "srcPath": str(source),
+                },
+            ],
+        )
+
+    def test_maps_source_root_that_does_not_match_package(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            source = directory / "unrelated" / "Feature.java"
+            classes = self._generate(
+                directory,
+                jar_classes=["com.example.Feature"],
+                sources=[source],
+                debuginfo=[
+                    {
+                        "file_path": str(source),
+                        "classes": [{"name": "com.example.Feature"}],
+                    }
+                ],
+            )
+
+        self.assertEqual(
+            classes,
+            [{"className": "com.example.Feature", "srcPath": str(source)}],
+        )
+
+    def test_maps_multiple_top_level_kotlin_classes(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            source = directory / "Shared.kt"
+            classes = self._generate(
+                directory,
+                jar_classes=["com.example.First", "com.example.Second"],
+                sources=[source],
+                debuginfo=[
+                    {
+                        "file_path": str(source),
+                        "classes": [
+                            {"name": "com.example.First"},
+                            {"name": "com.example.Second"},
+                        ],
+                    }
+                ],
+            )
+
+        self.assertEqual(
+            classes,
+            [
+                {"className": "com.example.First", "srcPath": str(source)},
+                {"className": "com.example.Second", "srcPath": str(source)},
+                {"className": "com.example.Shared", "srcPath": str(source)},
+            ],
+        )
+
+    def test_normalizes_kotlin_file_facade(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            source = directory / "Utilities.kt"
+            classes = self._generate(
+                directory,
+                jar_classes=["com.example.UtilitiesKt"],
+                sources=[source],
+                debuginfo=[
+                    {
+                        "file_path": str(source),
+                        "classes": [{"name": "com.example.UtilitiesKt"}],
+                    }
+                ],
+            )
+
+        self.assertEqual(
+            classes,
+            [{"className": "com.example.Utilities", "srcPath": str(source)}],
+        )
+
+    def test_preserves_real_class_with_kt_suffix(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            source = directory / "UtilitiesKt.kt"
+            classes = self._generate(
+                directory,
+                jar_classes=["com.example.UtilitiesKt"],
+                sources=[source],
+                debuginfo=[
+                    {
+                        "file_path": str(source),
+                        "classes": [{"name": "com.example.UtilitiesKt"}],
+                    }
+                ],
+            )
+
+        self.assertEqual(
+            classes,
+            [{"className": "com.example.UtilitiesKt", "srcPath": str(source)}],
+        )
+
+    def test_nested_and_synthetic_classes_map_to_outer_class(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            source = directory / "Outer.kt"
+            classes = self._generate(
+                directory,
+                jar_classes=["com.example.Outer$Inner", "com.example.Outer$1"],
+                sources=[source],
+                debuginfo=[
+                    {
+                        "file_path": str(source),
+                        "classes": [
+                            {"name": "com.example.Outer"},
+                            {"name": "com.example.Outer$Inner"},
+                        ],
+                    }
+                ],
+            )
+
+        self.assertEqual(
+            classes,
+            [{"className": "com.example.Outer", "srcPath": str(source)}],
+        )
+
+    def test_sourceful_mapping_wins_regardless_of_jar_order(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            source = directory / "Outer.kt"
+            classes = self._generate(
+                directory,
+                jar_classes=[
+                    "androidx.databinding.Outer",
+                    "androidx.databinding.Outer$Inner",
+                ],
+                sources=[source],
+                debuginfo=[
+                    {
+                        "file_path": str(source),
+                        "classes": [{"name": "androidx.databinding.Outer$Inner"}],
+                    }
+                ],
+                include_prefixes=("androidx.databinding",),
+            )
+
+        self.assertEqual(
+            classes,
+            [
+                {
+                    "className": "androidx.databinding.Outer",
+                    "srcPath": str(source),
+                }
+            ],
+        )
+
+    def test_preserves_sourceless_generated_classes_and_ignores_parser_only_classes(
+        self,
+    ) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            source = directory / "Phantom.java"
+            classes = self._generate(
+                directory,
+                jar_classes=[
+                    "androidx.databinding.WidgetBinding",
+                    "com.example.Unknown",
+                ],
+                sources=[source],
+                debuginfo=[
+                    {
+                        "file_path": str(source),
+                        "classes": [{"name": "com.example.Phantom"}],
+                    }
+                ],
+                include_prefixes=("androidx.databinding",),
+            )
+
+        self.assertEqual(classes, [{"className": "androidx.databinding.WidgetBinding"}])
+
+    def test_ignores_ambiguous_debuginfo_and_falls_back_to_paths(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            source = directory / "com" / "example" / "Ambiguous.java"
+            other = directory / "elsewhere" / "Ambiguous.java"
+            classes = self._generate(
+                directory,
+                jar_classes=["com.example.Ambiguous"],
+                sources=[source, other],
+                debuginfo=[
+                    {
+                        "file_path": str(source),
+                        "classes": [{"name": "com.example.Ambiguous"}],
+                    },
+                    {
+                        "file_path": str(other),
+                        "classes": [{"name": "com.example.Ambiguous"}],
+                    },
+                ],
+            )
+
+        # Two sources claim the same class, so the debug mapping is discarded and the
+        # legacy package-path match (com/example/Ambiguous) is used instead.
+        self.assertEqual(
+            classes,
+            [{"className": "com.example.Ambiguous", "srcPath": str(source)}],
+        )
+
+    def test_falls_back_to_legacy_path_matching_without_debuginfo(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            source = directory / "src" / "com" / "example" / "Legacy.java"
+            classes = self._generate(
+                directory,
+                jar_classes=["com.example.Legacy"],
+                sources=[source],
+                debuginfo=None,
+            )
+
+        self.assertEqual(
+            classes,
+            [{"className": "com.example.Legacy", "srcPath": str(source)}],
+        )
+
+    def test_sources_jar_writes_one_entry_per_source_file(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            shared = directory / "DatError.kt"
+            shared.write_text("interface DatError\ninternal class DatErrorImpl\n")
+            other = directory / "Feature.kt"
+            other.write_text("class Feature\n")
+            sources_jar = directory / "library-sources.jar"
+            self._generate(
+                directory,
+                jar_classes=[
+                    "com.example.DatError",
+                    "com.example.DatErrorImpl",
+                    "com.example.Feature",
+                ],
+                sources=[shared, other],
+                debuginfo=[
+                    {
+                        "file_path": str(shared),
+                        "classes": [
+                            {"name": "com.example.DatError"},
+                            {"name": "com.example.DatErrorImpl"},
+                        ],
+                    },
+                    {
+                        "file_path": str(other),
+                        "classes": [{"name": "com.example.Feature"}],
+                    },
+                ],
+                sources_jar=str(sources_jar),
+            )
+
+            with zipfile.ZipFile(sources_jar) as jar:
+                entries = jar.namelist()
+                shared_contents = jar.read("com/example/DatError.kt").decode()
+
+        # `DatErrorImpl` shares `DatError.kt`, so the file is written once under its
+        # own name instead of once per class.
+        self.assertCountEqual(
+            entries,
+            ["com/example/DatError.kt", "com/example/Feature.kt"],
+        )
+        self.assertEqual(
+            shared_contents, "interface DatError\ninternal class DatErrorImpl\n"
+        )
+
+    def test_defaults_output_to_stdout(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            jar_path = pathlib.Path(temp_dir) / "library.jar"
+            with zipfile.ZipFile(jar_path, "w"):
+                pass
+
+            output = io.StringIO()
+            with redirect_stdout(output):
+                exit_code = main(["gen_class_to_source_map", str(jar_path)])
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(
+            json.loads(output.getvalue()),
+            {"jarPath": str(jar_path), "classes": []},
+        )
+
+    def test_serializes_owner_target(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            jar_path = pathlib.Path(temp_dir) / "library.jar"
+            with zipfile.ZipFile(jar_path, "w"):
+                pass
+
+            output = io.StringIO()
+            generate_class_to_source_map(
+                str(jar_path),
+                [],
+                output,
+                owner_target="cell//package:library",
+            )
+
+        self.assertEqual(
+            json.loads(output.getvalue()),
+            {
+                "jarPath": str(jar_path),
+                "classes": [],
+                "ownerTarget": "cell//package:library",
+            },
+        )
diff --git a/buck2/prelude/java/tools/tests/test_list_class_names.py b/buck2/prelude/java/tools/tests/test_list_class_names.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/tests/test_list_class_names.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import pathlib
+import tempfile
+import unittest
+import zipfile
+
+from list_class_names import _get_class_names
+
+
+def _create_jar(path, class_files):
+    with zipfile.ZipFile(path, "w") as zf:
+        for cf in class_files:
+            zf.writestr(cf, b"")
+
+
+def _create_sources(path, sources):
+    path.write_text("\n".join(sources) + "\n")
+
+
+class ListClassNamesTest(unittest.TestCase):
+    def test_java_stem_matching(self):
+        with tempfile.TemporaryDirectory() as d:
+            d = pathlib.Path(d)
+            jar = d / "test.jar"
+            sources = d / "sources.txt"
+            _create_jar(jar, ["com/example/Foo.class", "com/example/Bar.class"])
+            _create_sources(sources, ["src/com/example/Foo.java"])
+            result = _get_class_names(sources, jar)
+            self.assertEqual(result, ["com.example.Foo"])
+
+    def test_java_no_match(self):
+        with tempfile.TemporaryDirectory() as d:
+            d = pathlib.Path(d)
+            jar = d / "test.jar"
+            sources = d / "sources.txt"
+            _create_jar(jar, ["com/example/Foo.class"])
+            _create_sources(sources, ["src/com/example/Bar.java"])
+            result = _get_class_names(sources, jar)
+            self.assertEqual(result, [])
+
+    def test_inner_classes_excluded(self):
+        with tempfile.TemporaryDirectory() as d:
+            d = pathlib.Path(d)
+            jar = d / "test.jar"
+            sources = d / "sources.txt"
+            _create_jar(jar, ["com/example/Foo.class", "com/example/Foo$Inner.class"])
+            _create_sources(sources, ["src/com/example/Foo.java"])
+            result = _get_class_names(sources, jar)
+            self.assertEqual(result, ["com.example.Foo"])
+
+    def test_discover_all_includes_all_top_level_classes(self):
+        with tempfile.TemporaryDirectory() as d:
+            d = pathlib.Path(d)
+            jar = d / "test.jar"
+            sources = d / "sources.txt"
+            _create_jar(
+                jar,
+                [
+                    "com/example/Foo.class",
+                    "com/example/Bar.class",
+                    "com/example/Baz.class",
+                    "com/example/Foo$Inner.class",
+                ],
+            )
+            _create_sources(sources, ["src/com/example/Main.kt"])
+            result = _get_class_names(sources, jar, discover_all=True)
+            self.assertEqual(
+                sorted(result),
+                ["com.example.Bar", "com.example.Baz", "com.example.Foo"],
+            )
+
+    def test_discover_all_still_excludes_inner_classes(self):
+        with tempfile.TemporaryDirectory() as d:
+            d = pathlib.Path(d)
+            jar = d / "test.jar"
+            sources = d / "sources.txt"
+            _create_jar(
+                jar,
+                ["com/example/Foo.class", "com/example/Foo$Inner.class"],
+            )
+            _create_sources(sources, ["src/com/example/Foo.kt"])
+            result = _get_class_names(sources, jar, discover_all=True)
+            self.assertEqual(result, ["com.example.Foo"])
+
+    def test_discover_all_ignores_non_class_files(self):
+        with tempfile.TemporaryDirectory() as d:
+            d = pathlib.Path(d)
+            jar = d / "test.jar"
+            sources = d / "sources.txt"
+            _create_jar(
+                jar,
+                [
+                    "com/example/Foo.class",
+                    "META-INF/MANIFEST.MF",
+                    "com/example/resource.txt",
+                ],
+            )
+            _create_sources(sources, ["src/com/example/Foo.kt"])
+            result = _get_class_names(sources, jar, discover_all=True)
+            self.assertEqual(result, ["com.example.Foo"])
+
+    def test_empty_sources(self):
+        with tempfile.TemporaryDirectory() as d:
+            d = pathlib.Path(d)
+            jar = d / "test.jar"
+            sources = d / "sources.txt"
+            _create_jar(jar, ["com/example/Foo.class"])
+            _create_sources(sources, [])
+            result = _get_class_names(sources, jar)
+            self.assertEqual(result, [])
+
+    def test_discover_all_with_empty_jar(self):
+        with tempfile.TemporaryDirectory() as d:
+            d = pathlib.Path(d)
+            jar = d / "test.jar"
+            sources = d / "sources.txt"
+            _create_jar(jar, [])
+            _create_sources(sources, ["src/Foo.kt"])
+            result = _get_class_names(sources, jar, discover_all=True)
+            self.assertEqual(result, [])
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/buck2/prelude/java/tools/tests/test_merge_class_to_source_maps.py b/buck2/prelude/java/tools/tests/test_merge_class_to_source_maps.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/tests/test_merge_class_to_source_maps.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import io
+import json
+import pathlib
+import tempfile
+import unittest
+
+from merge_class_to_source_maps import merge_class_to_source_maps
+
+
+class MergeClassToSourceMapsTest(unittest.TestCase):
+    def test_relativizes_paths_and_preserves_owner_and_sourceless_classes(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            directory = pathlib.Path(temp_dir)
+            mapping_path = directory / "mapping.json"
+            mapping_path.write_text(
+                json.dumps(
+                    {
+                        "jarPath": str(directory / "library.jar"),
+                        "ownerTarget": "cell//package:library",
+                        "classes": [
+                            {
+                                "className": "com.example.Sourceful",
+                                "srcPath": str(directory / "Sourceful.java"),
+                            },
+                            {"className": "com.example.Generated"},
+                        ],
+                    }
+                )
+            )
+            output = io.StringIO()
+
+            merge_class_to_source_maps([str(mapping_path)], output, str(directory))
+
+        self.assertEqual(
+            json.loads(output.getvalue()),
+            {
+                "jarPath": "library.jar",
+                "ownerTarget": "cell//package:library",
+                "classes": [
+                    {
+                        "className": "com.example.Sourceful",
+                        "srcPath": "Sourceful.java",
+                    },
+                    {"className": "com.example.Generated"},
+                ],
+            },
+        )
diff --git a/buck2/prelude/java/tools/utils.py b/buck2/prelude/java/tools/utils.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/tools/utils.py
@@ -0,0 +1,486 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import os
+import pathlib
+import platform
+import re
+import shlex
+import subprocess
+import sys
+import tempfile
+import zipfile
+from enum import Enum
+from shutil import copyfile
+from typing import Callable, List, Match, Pattern
+from urllib.parse import urlencode
+
+# ANSI color codes
+RED = "\033[91m"
+YELLOW = "\033[93m"
+GREEN = "\033[92m"
+MAGENTA = "\033[95m"
+BLUE = "\033[94m"
+BOLD = "\033[1m"
+RESET = "\033[0m"
+
+ERROR_PATTERN = re.compile(
+    r"\berror\b(:.*?\n)((?:.*?\n)+?\s*)(\^+)\n", flags=re.IGNORECASE
+)
+WARNING_PATTERN = re.compile(r"\bwarning\b(:.*?)\n", flags=re.IGNORECASE)
+
+JAVA_FILE_PATTERN = re.compile(
+    r"(?:\x1b\[[0-9;]*m)*(/?(?:[\w-]+/)*[\w-]+\.java)\b:(\d+):"
+)
+
+KOTLIN_FILE_PATTERN = re.compile(
+    r"(?:\x1b\[[0-9;]*m)*(/?(?:[\w-]+/)*[\w-]+\.kt)\b:(\d+):(\d+):"
+)
+
+# Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
+JAVA_KEYWORDS = [
+    "abstract",
+    "assert",
+    "boolean",
+    "break",
+    "byte",
+    "case",
+    "catch",
+    "char",
+    "class",
+    "const",
+    "continue",
+    "default",
+    "do",
+    "double",
+    "else",
+    "enum",
+    "extends",
+    "final",
+    "finally",
+    "float",
+    "for",
+    "goto",
+    "if",
+    "implements",
+    "import",
+    "instanceof",
+    "int",
+    "interface",
+    "long",
+    "native",
+    "new",
+    "package",
+    "private",
+    "protected",
+    "public",
+    "return",
+    "short",
+    "static",
+    "strictfp",
+    "super",
+    "switch",
+    "synchronized",
+    "this",
+    "throw",
+    "throws",
+    "transient",
+    "try",
+    "void",
+    "volatile",
+    "while",
+    "null",
+    "true",
+    "false",
+    "record",
+    "sealed",
+    "permits",
+    "non-sealed",
+    "var",
+]
+
+# Source: https://kotlinlang.org/docs/keyword-reference.html
+KOTLIN_KEYWORDS = [
+    "as",
+    "as?",
+    "break",
+    "class",
+    "continue",
+    "do",
+    "else",
+    "false",
+    "for",
+    "fun",
+    "if",
+    "in",
+    "!in",
+    "interface",
+    "is",
+    "!is",
+    "null",
+    "object",
+    "package",
+    "return",
+    "super",
+    "this",
+    "throw",
+    "true",
+    "try",
+    "typealias",
+    "val",
+    "var",
+    "when",
+    "while",
+    "by",
+    "catch",
+    "constructor",
+    "delegate",
+    "dynamic",
+    "field",
+    "file",
+    "finally",
+    "get",
+    "import",
+    "init",
+    "param",
+    "property",
+    "receiver",
+    "set",
+    "setparam",
+    "where",
+    "actual",
+    "abstract",
+    "annotation",
+    "companion",
+    "const",
+    "crossinline",
+    "data",
+    "enum",
+    "expect",
+    "external",
+    "final",
+    "infix",
+    "inline",
+    "inner",
+    "internal",
+    "lateinit",
+    "noinline",
+    "open",
+    "operator",
+    "out",
+    "override",
+    "private",
+    "protected",
+    "public",
+    "reified",
+    "sealed",
+    "suspend",
+    "tailrec",
+    "vararg",
+    "field",
+    "it",
+]
+
+
+class FileType(Enum):
+    """Enum representing supported file types with their associated patterns and keywords."""
+
+    JAVA = (
+        JAVA_KEYWORDS,
+        # File pattern for Java files
+        JAVA_FILE_PATTERN,
+        "JAVA",
+    )
+
+    KOTLIN = (
+        KOTLIN_KEYWORDS,
+        # File pattern for Kotlin files
+        KOTLIN_FILE_PATTERN,
+        "KOTLIN",
+    )
+
+    def __init__(self, keywords: List[str], file_pattern: Pattern, lang: str):
+        self.keywords = keywords
+        self.file_pattern = file_pattern
+        self.lang = lang
+
+
+def _hyperlink(file: str, line: int, text: str) -> str:
+    """
+    Creates a clickable hyperlink in the terminal using OSC 8 escape sequences.
+    Supports both VS Code and Android Studio links based on ANDROID_EDITOR environment variable.
+
+    Args:
+        file: The file path to link to
+        line: The line number to link to
+        text: The text to display as the hyperlink
+
+    Returns:
+        A string containing the hyperlinked text with terminal escape sequences
+    """
+    # Keep in sync with fbcode/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/ErrorInterceptor.java
+    isVsCode = (
+        os.environ.get("FBVSCODE_REMOTE_ENV_NAME") == "od"
+        or os.environ.get("TERM_PROGRAM") == "vscode"
+    )
+
+    isHyperlinkDisabled = os.path.exists(
+        os.path.expanduser("~/.disable_buck_jvm_path_hyperlink")
+    )
+
+    if isVsCode or isHyperlinkDisabled:
+        return text
+
+    OSC = "\033]"
+    ST = "\033\\"
+
+    is_jetbrains = (
+        "ANDROID_EDITOR" in os.environ
+        or pathlib.Path("~/.jetbrains-fb/.buck_path_hyperlink_uses_jetbrains")
+        .expanduser()
+        .is_file()
+    )
+
+    if is_jetbrains:
+        params = {
+            "ide": "intellij",
+            "filepath": f"/fbsource/{file}",
+            "line": line,
+        }
+        encoded_params = "&".join(
+            [
+                f"{key}={urlencode({key: str(value)}).split('=', 1)[1]}"
+                for key, value in params.items()
+            ]
+        )
+
+        uri = f"fb-ide-opener://open/?{encoded_params}"
+
+    else:
+        params = {
+            "project": "fbsource",
+            "paths[0]": file,
+            "lines[0]": line,
+        }
+
+        encoded_params = urlencode(params)
+
+        uri = f"https://www.internalfb.com/intern/nuclide/open/arc/?{encoded_params}"
+
+    return f"{OSC}8;;{uri}{ST}{text}{OSC}8;;{ST}"
+
+
+def _highlight_code(s: str, keywords: List[str]) -> str:
+    if not keywords:
+        return s
+    return re.sub(
+        rf"\b({'|'.join(keywords)})\b",
+        lambda match: f"{BLUE}{match.group(1)}{RESET}",
+        s,
+    )
+
+
+def _highlight_error(match: Match, keywords: List[str]) -> str:
+    return (
+        f"{RED}error{RESET}{BOLD}{match.group(1)}{RESET}"
+        f"{_highlight_code(match.group(2), keywords)}{RED}{match.group(3)}{RESET}\n"
+    )
+
+
+def _highlight_warning(match: Match) -> str:
+    return f"{YELLOW}warning{RESET}{BOLD}{match.group(1)}{RESET}\n"
+
+
+def _highlight_java_file(match: Match) -> str:
+    file = match.group(1)
+    line = int(match.group(2))
+
+    return f"{GREEN}{_hyperlink(file, line, file)}{RESET}:{MAGENTA}{match.group(2)}{RESET}:"
+
+
+def _highlight_kotlin_file(match: Match) -> str:
+    file = match.group(1)
+    line = int(match.group(2))
+
+    return (
+        f"{GREEN}{_hyperlink(file, line, file)}{RESET}:"
+        f"{MAGENTA}{match.group(2)}{RESET}:{MAGENTA}{match.group(3)}{RESET}:"
+    )
+
+
+def _colorize_pattern(
+    pattern: Pattern, message: str, colorizer: Callable[[Match], str]
+) -> str:
+    """
+    Apply a colorizer function to all matches of a pattern in a string.
+
+    Args:
+        pattern: The pattern to match
+        message: The string to search
+        colorizer: The function to apply to each match
+
+    Returns:
+        The colorized string
+    """
+    if not pattern:
+        return message
+
+    result = ""
+    last_end = 0
+    for match in pattern.finditer(message):
+        result += message[last_end : match.start()]
+        result += colorizer(match)
+        last_end = match.end()
+    result += message[last_end:]
+    return result
+
+
+def pretty_exception(e: str, file_type: FileType = None) -> str:
+    """
+    Format compiler error messages with syntax highlighting and clickable file links.
+
+    Args:
+        e: The error message to format
+        lang_type: The language type (if known, otherwise will be auto-detected)
+
+    Returns:
+        A formatted error message with ANSI color codes
+    """
+
+    if "NO_COLOR" in os.environ or (
+        file_type.name and f"NO_{file_type.name}C_COLOR" in os.environ
+    ):
+        return e
+
+    # Process error messages
+    e = _colorize_pattern(
+        ERROR_PATTERN, e, lambda match: _highlight_error(match, file_type.keywords)
+    )
+
+    # Process warning messages
+    e = _colorize_pattern(WARNING_PATTERN, e, _highlight_warning)
+
+    # Process file references
+    if file_type == FileType.JAVA:
+        e = _colorize_pattern(file_type.file_pattern, e, _highlight_java_file)
+    elif file_type == FileType.KOTLIN:
+        e = _colorize_pattern(file_type.file_pattern, e, _highlight_kotlin_file)
+
+    return e
+
+
+def pretty_exception_j(e: str) -> str:
+    return pretty_exception(e, FileType.JAVA)
+
+
+def pretty_exception_k(e: str) -> str:
+    return pretty_exception(e, FileType.KOTLIN)
+
+
+def file_name_matches(file_name: str, extensions: List[str]) -> bool:
+    for extension in extensions:
+        if file_name.endswith(extension):
+            return True
+    return False
+
+
+def extract_source_files(
+    zipped_sources_file: pathlib.Path,
+    args_file: pathlib.Path,
+    file_name_extensions: List[str],
+    temp_dir: tempfile.TemporaryDirectory,
+) -> pathlib.Path:
+    extracted_zip_dir = os.path.join(temp_dir, "extracted_srcs")
+    all_extracted_files = []
+
+    with open(zipped_sources_file) as file:
+        zip_file_paths = [line.rstrip() for line in file.readlines()]
+        for zip_file_path in zip_file_paths:
+            with zipfile.ZipFile(zip_file_path, "r") as zip_file:
+                files_to_extract = []
+                for file_name in zip_file.namelist():
+                    if file_name_matches(file_name, file_name_extensions):
+                        files_to_extract.append(file_name)
+                zip_file.extractall(path=extracted_zip_dir, members=files_to_extract)
+                all_extracted_files += files_to_extract
+
+    # append args file with new extracted sources
+    merged_args_file = os.path.join(temp_dir, "merged_args_file")
+    # copy content from args file
+    copyfile(args_file, merged_args_file)
+
+    with open(merged_args_file, "a") as merged_file:
+        # append with extracted paths
+        for path in all_extracted_files:
+            merged_file.write(
+                "{}{}".format(os.linesep, os.path.join(extracted_zip_dir, path))
+            )
+    return merged_args_file
+
+
+def _to_class_name(path: pathlib.Path) -> str:
+    return str(path).replace(os.sep, ".").replace(".class", "")
+
+
+def sources_are_present(
+    args_file: pathlib.Path, permitted_extensions: List[str]
+) -> bool:
+    with open(args_file, "r") as file:
+        for line in file.readlines():
+            for extension in permitted_extensions:
+                if line.strip().endswith(extension):
+                    return True
+    return False
+
+
+def shlex_split(cmd: str) -> List[str]:
+    if platform.system() == "Windows":
+        # Windows shlex.split removes backslashes.
+        return cmd.split()
+    else:
+        return shlex.split(cmd)
+
+
+def log_message(message: str):
+    level = "debug"
+
+    main_file = os.path.realpath(sys.argv[0]) if sys.argv[0] else None
+    if main_file:
+        program_name = os.path.basename(main_file)
+    else:
+        program_name = ""
+
+    print(
+        "{}[{}] {}".format(
+            "[{}] ".format(program_name) if program_name else "", level, message
+        ),
+        file=sys.stderr,
+    )
+
+
+def execute_command(command: List):
+    log_message(
+        "executing command = '{}'".format(
+            " ".join([shlex.quote(str(s)) for s in command])
+        )
+    )
+    exit_code = subprocess.call(command)
+    if exit_code != 0:
+        sys.exit(exit_code)
+
+
+def execute_command_ignore_exit_codes(command: List, exit_codes_to_ignore: List):
+    log_message(
+        "executing command = '{}'".format(
+            " ".join([shlex.quote(str(s)) for s in command])
+        )
+    )
+    exit_code = subprocess.call(command)
+    if exit_code != 0 and exit_code not in exit_codes_to_ignore:
+        sys.exit(exit_code)
diff --git a/buck2/prelude/java/utils/java_more_utils.bzl b/buck2/prelude/java/utils/java_more_utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/utils/java_more_utils.bzl
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//utils:expect.bzl", "expect")
+
+def get_path_separator_for_exec_os(ctx: AnalysisContext) -> str:
+    expect(hasattr(ctx.attrs, "_exec_os_type"), "Expect ctx.attrs._exec_os_type is defined.")
+    is_windows = ctx.attrs._exec_os_type[OsLookup].os == Os("windows")
+    return ";" if is_windows else ":"
diff --git a/buck2/prelude/java/utils/java_utils.bzl b/buck2/prelude/java/utils/java_utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/java/utils/java_utils.bzl
@@ -0,0 +1,220 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load(
+    "@prelude//java:class_to_srcs.bzl",
+    "JavaClassToSourceMapInfo",  # @unused Used as a type
+    "create_class_to_source_map_from_jar",
+    "create_class_to_source_map_info",
+    "maybe_create_class_to_source_map_debuginfo",
+)
+load(
+    "@prelude//java:java_providers.bzl",
+    "JavaCompileOutputs",  # @unused Used as a type
+    "JavaPackagingInfo",  # @unused Used as a type
+)
+load("@prelude//java:java_toolchain.bzl", "AbiGenerationMode", "JavaToolchainInfo")
+load("@prelude//utils:expect.bzl", "expect")
+
+CustomJdkInfo = record(
+    # Used with -bootclasspath flag for JDK 8 and older release targets
+    # This is also added to the normal classpath when used with kotlinc or javac with JDK9+ release
+    bootclasspath = list[Artifact],
+    bootclasspath_jar_snapshots = list[Artifact],
+    # Used with --system flag for JDK 9+ release targets
+    system_image = Artifact,
+)
+
+def derive_javac(javac_attribute: [str, Dependency, Artifact]) -> [str, RunInfo, Artifact]:
+    javac_attr_type = type(javac_attribute)
+    if isinstance(javac_attribute, Dependency):
+        javac_run_info = javac_attribute.get(RunInfo)
+        if javac_run_info:
+            return javac_run_info
+        outputs = javac_attribute[DefaultInfo].default_outputs
+        expect(len(outputs) == 1, "Expect one default output from build dep of attr javac!")
+        return outputs[0]
+
+    if isinstance(javac_attribute, Artifact):
+        return javac_attribute
+
+    if javac_attr_type == type(""):
+        return javac_attribute
+
+    fail(
+        'Type of attribute javac {} that equals to {} is not supported.\n Supported types are "dependency", "artifact" and "string".'.format(
+            javac_attr_type, javac_attribute
+        )
+    )
+
+def get_java_version_attributes(ctx: AnalysisContext) -> (int, int):
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+
+    # used for multi-release jars
+    # the attribute might not exist if function is being used in other macros, such as kotlin_library
+    min_release_version = ctx.attrs.min_release_version if hasattr(ctx.attrs, "min_release_version") else None
+    java_version = ctx.attrs.java_version
+    java_source = ctx.attrs.source
+    java_target = ctx.attrs.target
+
+    if java_version or min_release_version:
+        if java_source or java_target:
+            fail("No need to set 'source' and/or 'target' attributes when 'java_version' or 'min_release_version' are present")
+        java_version = to_java_version(min_release_version) if min_release_version else to_java_version(java_version)
+        return (java_version, java_version)
+
+    source = java_source or java_toolchain.source_level
+    target = java_target or java_toolchain.target_level
+
+    expect(bool(source) and bool(target), "Java source level and target level must be set!")
+
+    source = to_java_version(source)
+    target = to_java_version(target)
+
+    expect(source <= target, "java library source level {} is higher than target {} ", source, target)
+
+    return (source, target)
+
+def to_java_version(java_version: str) -> int:
+    if java_version.startswith("1."):
+        expect(len(java_version) == 3, "Supported java version number format is 1.X, where X is a single digit number, but it was set to {}", java_version)
+        java_version_number = int(java_version[2:])
+        expect(
+            java_version_number < 9,
+            "Supported java version number format is 1.X, where X is a single digit number that is less than 9, but it was set to {}",
+            java_version,
+        )
+        return java_version_number
+    else:
+        return int(java_version)
+
+def get_string_concat_inline_javac_args(source_level: int) -> list[str]:
+    # Android build tools before SDK 36 lack java.lang.invoke.StringConcatFactory, which javac
+    # targets for invokedynamic string concatenation at -source 9+ (JEP 280). Force javac to emit
+    # classic StringBuilder concatenation instead so the bytecode compiles and runs against those SDKs.
+    if source_level >= 9:
+        return ["-XDstringConcat=inline"]
+    return []
+
+def get_abi_generation_mode(abi_generation_mode):
+    return {
+        None: None,
+        "class": AbiGenerationMode("class"),
+        "migrating_to_source_only": AbiGenerationMode("source"),
+        "none": AbiGenerationMode("none"),
+        "source": AbiGenerationMode("source"),
+        "source_only": AbiGenerationMode("source_only"),
+    }[abi_generation_mode]
+
+def get_default_info(
+    actions: AnalysisActions,
+    java_toolchain: JavaToolchainInfo,
+    outputs: [JavaCompileOutputs, None],
+    packaging_info: JavaPackagingInfo,
+    extra_sub_targets: dict = {},
+) -> DefaultInfo:
+    sub_targets = get_classpath_subtargets(actions, packaging_info)
+    default_info = DefaultInfo(
+        sub_targets = extra_sub_targets | sub_targets,
+    )
+    if outputs:
+        abis = [
+            ("class-abi", outputs.class_abi),
+            ("source-abi", outputs.source_abi),
+            ("source-only-abi", outputs.source_only_abi),
+        ]
+        for name, artifact in abis:
+            if artifact != None:
+                sub_targets[name] = [DefaultInfo(default_output = artifact)]
+        other_outputs = []
+        if not java_toolchain.is_bootstrap_toolchain and outputs.annotation_processor_output:
+            other_outputs.append(outputs.annotation_processor_output)
+        default_info = DefaultInfo(
+            default_output = outputs.full_library,
+            sub_targets = extra_sub_targets | sub_targets,
+            other_outputs = other_outputs,
+        )
+    return default_info
+
+def declare_prefixed_name(name: str, prefix: [str, None]) -> str:
+    if not prefix:
+        return name
+
+    return "{}_{}".format(prefix, name)
+
+def get_class_to_source_map_info(
+    ctx: AnalysisContext,
+    outputs: [JavaCompileOutputs, None],
+    deps: list[Dependency],
+    generate_sources_jar: bool = False,
+    class_to_src_map_deps: list[Dependency] = [],
+) -> (JavaClassToSourceMapInfo, Artifact | None, dict):
+    sub_targets = {}
+    class_to_srcs = None
+    mapping_debuginfo = None
+    sources_jar = None
+    if outputs != None:
+        name = ctx.label.name
+        java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+        mapping_debuginfo = maybe_create_class_to_source_map_debuginfo(
+            actions = ctx.actions,
+            java_toolchain = java_toolchain,
+            name = name + ".debuginfo.json",
+            srcs = ctx.attrs.srcs,
+        )
+        class_to_srcs, sources_jar = create_class_to_source_map_from_jar(
+            actions = ctx.actions,
+            java_toolchain = java_toolchain,
+            name = name + ".class_to_srcs.json",
+            jar = outputs.classpath_entry.full_library,
+            srcs = ctx.attrs.srcs,
+            owner_target = str(ctx.label.raw_target()),
+            sources_jar_name = "{}-sources.jar".format(name) if generate_sources_jar else None,
+            debuginfo = mapping_debuginfo,
+        )
+        sub_targets["class-to-srcs"] = [DefaultInfo(default_output = class_to_srcs)]
+        if sources_jar:
+            sub_targets["sources.jar"] = [DefaultInfo(default_output = sources_jar)]
+
+    # Include class_to_src_map_deps for classmap collection. These are deps that
+    # only contribute to the class-to-source map (for debugging) but not to compilation.
+    all_classmap_deps = deps + class_to_src_map_deps
+    class_to_src_map_info = create_class_to_source_map_info(
+        ctx = ctx,
+        mapping = class_to_srcs,
+        mapping_debuginfo = mapping_debuginfo,
+        deps = all_classmap_deps,
+    )
+    if outputs != None:
+        sub_targets["debuginfo"] = [DefaultInfo(default_output = class_to_src_map_info.debuginfo)]
+    return (class_to_src_map_info, sources_jar, sub_targets)
+
+def get_classpath_subtargets(actions: AnalysisActions, packaging_info: JavaPackagingInfo) -> dict[str, list[Provider]]:
+    proj = packaging_info.packaging_deps.project_as_args("full_jar_args")
+    output = actions.write("classpath", proj, has_content_based_path = False)
+
+    classpath_targets_proj = packaging_info.packaging_deps.project_as_args("full_jar_owner_args")
+    classpath_targets_output = actions.write("classpath_targets", classpath_targets_proj, has_content_based_path = False)
+
+    return {
+        "classpath": [DefaultInfo(output, other_outputs = [proj])],
+        "classpath_targets": [DefaultInfo(classpath_targets_output)],
+    }
+
+def build_bootclasspath(bootclasspath_entries: list[Artifact], source_level: int, java_toolchain: JavaToolchainInfo) -> list[Artifact]:
+    bootclasspath_list = []
+
+    if bootclasspath_entries:
+        bootclasspath_list = bootclasspath_entries
+    elif source_level == 8:
+        if not is_full_meta_repo():
+            return bootclasspath_list
+        expect(java_toolchain.bootclasspath_8, "Must specify bootclasspath for source level 8")
+        bootclasspath_list = java_toolchain.bootclasspath_8
+    return bootclasspath_list
diff --git a/buck2/prelude/js/js.bzl b/buck2/prelude/js/js.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/js/js.bzl
@@ -0,0 +1,108 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:genrule.bzl", "genrule_attributes")
+load("@prelude//decls:common.bzl", "buck")
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//js:js_bundle.bzl", "js_bundle_impl")
+load("@prelude//js:js_bundle_genrule.bzl", "js_bundle_genrule_impl")
+load("@prelude//js:js_library.bzl", "js_library_impl")
+
+def _select_platform():
+    return select({
+        "DEFAULT": select({
+            "DEFAULT": "android",
+            "config//os/constraints:appletvos": "ios",
+            "config//os/constraints:iphoneos": "ios",
+            "config//os/constraints:macos": "macos",
+            "config//os/constraints:windows": "windows",
+        }),
+        "config//react-native:macos": "macos",
+        "fbsource//tools/build_defs/js/constraints/metro_js_platform_override:metro_js_platform_override[android]": "android",
+        "fbsource//tools/build_defs/js/constraints/metro_js_platform_override:metro_js_platform_override[ios]": "ios",
+        "fbsource//tools/build_defs/js/constraints/metro_js_platform_override:metro_js_platform_override[macos]": "macos",
+        "fbsource//tools/build_defs/js/constraints/metro_js_platform_override:metro_js_platform_override[vr]": "vr",
+        "fbsource//tools/build_defs/js/constraints/metro_js_platform_override:metro_js_platform_override[windows]": "windows",
+    })
+
+def _is_release():
+    return select({
+        "DEFAULT": select({
+            "DEFAULT": select({
+                "DEFAULT": False,
+                "config//build_mode:optimization[opt]": True,
+            }),
+            "config//build_mode/constraints:build_mode[release]": True,
+        }),
+        "config//runtime:fbcode": select({
+            "DEFAULT": False,
+            "config//build_mode/constraints:opt": True,
+        }),
+    })
+
+def _select_asset_dest_path_resolver():
+    return select({
+        "DEFAULT": None,
+        "fbsource//tools/build_defs/js/constraints/asset_dest_path_resolver:asset_dest_path_resolver[android]": "android",
+        "fbsource//tools/build_defs/js/constraints/asset_dest_path_resolver:asset_dest_path_resolver[generic]": "generic",
+    })
+
+implemented_rules = {
+    "js_bundle": js_bundle_impl,
+    "js_bundle_genrule": js_bundle_genrule_impl,
+    "js_library": js_library_impl,
+}
+
+extra_attributes = {
+    "js_bundle": {
+        "worker": attrs.exec_dep(),
+        "_android_toolchain": toolchains_common.android(),
+        "_is_release": attrs.bool(
+            default = _is_release(),
+        ),
+        "_platform": attrs.string(
+            default = _select_platform(),
+        ),
+    },
+    "js_bundle_genrule": genrule_attributes()
+    | {
+        "has_content_based_path": attrs.bool(
+            default = select({
+                "DEFAULT": False,
+                "config//features/apple:content_based_path_hashing_enabled": True,
+            })
+        ),
+        "type": attrs.string(
+            default = "js_bundle_genrule",
+        ),
+        "_exec_os_type": buck.exec_os_type_arg(),
+        "_is_release": attrs.bool(
+            default = _is_release(),
+        ),
+        "_platform": attrs.string(
+            default = _select_platform(),
+        ),
+    },
+    "js_library": {
+        "extra_babel_plugins": attrs.list(
+            attrs.one_of(attrs.dep(), attrs.tuple(attrs.dep(), attrs.arg(default = "{}"))),
+            default = [],
+        ),
+        "worker": attrs.exec_dep(),
+        "_asset_dest_path_resolver": attrs.option(
+            attrs.string(),
+            default = _select_asset_dest_path_resolver(),
+        ),
+        "_is_release": attrs.bool(
+            default = _is_release(),
+        ),
+        "_platform": attrs.string(
+            default = _select_platform(),
+        ),
+    },
+}
diff --git a/buck2/prelude/js/js_bundle.bzl b/buck2/prelude/js/js_bundle.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/js/js_bundle.bzl
@@ -0,0 +1,206 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_providers.bzl", "AndroidResourceInfo", "RESOURCE_PRIORITY_NORMAL", "merge_android_packageable_info")
+load("@prelude//android:android_resource.bzl", "JAVA_PACKAGE_FILENAME", "aapt2_compile", "get_text_symbols")
+load("@prelude//android:android_toolchain.bzl", "AndroidToolchainInfo")
+load("@prelude//js:js_providers.bzl", "JsBundleInfo", "JsLibraryInfo", "get_transitive_outputs")
+load("@prelude//js:js_utils.bzl", "TRANSFORM_PROFILES", "get_apple_resource_providers_for_js_bundle", "get_bundle_name", "get_flavors", "run_worker_commands")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "map_idx")
+
+def _build_dependencies_file(
+    ctx: AnalysisContext, transform_profile: str, flavors: list[str], transitive_js_library_outputs: TransitiveSetArgsProjection
+) -> Artifact:
+    dependencies_file = ctx.actions.declare_output("{}/dependencies_file", transform_profile, has_content_based_path = False)
+
+    extra_data_args = cmd_args(
+        ctx.attrs.extra_json if ctx.attrs.extra_json else "{}",
+        delimiter = "",
+    )
+    job_args = {
+        "command": "dependencies",
+        "entryPoints": [ctx.attrs.entry] if type(ctx.attrs.entry) == "string" else list(ctx.attrs.entry),
+        "extraData": extra_data_args,
+        "flavors": flavors,
+        "libraries": transitive_js_library_outputs,
+        "outputFilePath": dependencies_file.as_output(),
+        "platform": ctx.attrs._platform,
+        "release": ctx.attrs._is_release,
+    }
+    command_args_file = ctx.actions.write_json(
+        "{}_dep_command_args".format(transform_profile),
+        job_args,
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+
+    run_worker_commands(
+        ctx = ctx,
+        worker_tool = ctx.attrs.worker,
+        command_args_file = command_args_file,
+        identifier = transform_profile,
+        category = "dependencies",
+    )
+    return dependencies_file
+
+def _build_js_bundle(
+    ctx: AnalysisContext,
+    bundle_name: str,
+    transform_profile: str,
+    flavors: list[str],
+    transitive_js_library_outputs: TransitiveSetArgsProjection,
+    dependencies_file: Artifact,
+) -> JsBundleInfo:
+    base_dir = transform_profile
+    assets_dir = ctx.actions.declare_output("{}/assets_dir".format(base_dir), has_content_based_path = False)
+    bundle_dir_output = ctx.actions.declare_output("{}/js".format(base_dir), dir = True, has_content_based_path = False)
+    misc_dir_path = ctx.actions.declare_output("{}/misc_dir_path".format(base_dir), has_content_based_path = False)
+    source_map = ctx.actions.declare_output("{}/source_map".format(base_dir), has_content_based_path = False)
+
+    extra_data_args = cmd_args(
+        ctx.attrs.extra_json if ctx.attrs.extra_json else "{}",
+        delimiter = "",
+    )
+    job_args = {
+        "assetsDirPath": assets_dir.as_output(),
+        "bundlePath": cmd_args(
+            [bundle_dir_output.as_output(), bundle_name],
+            delimiter = "/",
+        ),
+        "command": "bundle",
+        "entryPoints": [ctx.attrs.entry] if type(ctx.attrs.entry) == "string" else list(ctx.attrs.entry),
+        "extraData": extra_data_args,
+        "flavors": flavors,
+        "libraries": transitive_js_library_outputs,
+        "miscDirPath": misc_dir_path.as_output(),
+        "platform": ctx.attrs._platform,
+        "release": ctx.attrs._is_release,
+        "sourceMapPath": source_map.as_output(),
+    }
+
+    # On Android, ask Metro to write the `assets/` subtree (from js_library targets using
+    # `_asset_dest_path_resolver = "generic"`) to a sibling directory, which we can keep out of assets_dir and aapt processing
+    generic_assets = None
+    if ctx.attrs._platform == "android":
+        generic_assets = ctx.actions.declare_output("{}/generic_assets".format(base_dir), dir = True, has_content_based_path = False)
+        job_args["genericAssetsDirPath"] = generic_assets.as_output()
+
+    command_args_file = ctx.actions.write_json(
+        "{}_bundle_command_args".format(base_dir),
+        job_args,
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+
+    run_worker_commands(
+        ctx = ctx,
+        worker_tool = ctx.attrs.worker,
+        command_args_file = command_args_file,
+        identifier = base_dir,
+        category = "bundle",
+    )
+
+    return JsBundleInfo(
+        bundle_name = bundle_name,
+        built_js = bundle_dir_output,
+        source_map = source_map,
+        res = assets_dir,
+        generic_assets = generic_assets,
+        misc = misc_dir_path,
+        dependencies_file = dependencies_file,
+    )
+
+def _get_fallback_transform_profile(ctx: AnalysisContext) -> str:
+    if ctx.attrs.fallback_transform_profile in TRANSFORM_PROFILES:
+        return ctx.attrs.fallback_transform_profile
+
+    if ctx.attrs.fallback_transform_profile == "default" or ctx.attrs.fallback_transform_profile == None:
+        return "hermes-legacy"
+
+    fail("Invalid fallback_transform_profile attribute {}!".format(ctx.attrs.fallback_transform_profile))
+
+def _get_default_providers(js_bundle_info: JsBundleInfo) -> list[Provider]:
+    return [DefaultInfo(default_output = js_bundle_info.built_js)]
+
+def _get_android_resource_info(ctx: AnalysisContext, js_bundle_info: JsBundleInfo, identifier: str) -> AndroidResourceInfo:
+    aapt2_compile_output = aapt2_compile(
+        ctx,
+        js_bundle_info.res,
+        ctx.attrs._android_toolchain[AndroidToolchainInfo],
+        identifier = identifier,
+    )
+    expect(ctx.attrs.android_package != None, "Must provide android_package for android builds!")
+    r_dot_java_package = ctx.actions.write("{}_{}".format(identifier, JAVA_PACKAGE_FILENAME), ctx.attrs.android_package, has_content_based_path = False)
+    expect(js_bundle_info.generic_assets != None, "generic_assets must be set for Android js_bundle")
+    return AndroidResourceInfo(
+        raw_target = ctx.label.raw_target(),
+        aapt2_compile_output = aapt2_compile_output,
+        allow_strings_as_assets_resource_filtering = True,
+        assets = [js_bundle_info.built_js, js_bundle_info.generic_assets],
+        manifest_file = None,
+        r_dot_java_package = r_dot_java_package,
+        res = js_bundle_info.res,
+        res_priority = RESOURCE_PRIORITY_NORMAL,
+        text_symbols = get_text_symbols(ctx, js_bundle_info.res, [], identifier),
+        unused_resource_dep_validation_has_non_xml_resources = True,
+    )
+
+def _get_extra_providers(ctx: AnalysisContext, js_bundle_info: JsBundleInfo, identifier: str) -> list[Provider]:
+    providers = [js_bundle_info]
+    if ctx.attrs._platform == "android":
+        resource_info = _get_android_resource_info(ctx, js_bundle_info, identifier)
+        providers.append(resource_info)
+        providers.append(merge_android_packageable_info(ctx.label, ctx.actions, ctx.attrs.deps, resource_info = resource_info))
+
+    providers += get_apple_resource_providers_for_js_bundle(ctx, js_bundle_info, ctx.attrs._platform, skip_resources = False)
+
+    return providers
+
+def js_bundle_impl(ctx: AnalysisContext) -> list[Provider]:
+    sub_targets = {}
+    default_outputs = []
+    extra_unnamed_output_providers = None
+    bundle_name = get_bundle_name(ctx, "{}.js".format(ctx.attrs.name))
+    flavors = get_flavors(ctx)
+    for transform_profile in TRANSFORM_PROFILES:
+        dep_infos = map_idx(JsLibraryInfo, [dep[DefaultInfo].sub_targets[transform_profile] for dep in ctx.attrs.deps])
+
+        transitive_js_library_tset = get_transitive_outputs(ctx.actions, deps = dep_infos)
+        transitive_js_library_outputs = transitive_js_library_tset.project_as_args("artifacts")
+        dependencies_file = _build_dependencies_file(ctx, transform_profile, flavors, transitive_js_library_outputs)
+
+        js_bundle_info = _build_js_bundle(ctx, bundle_name, transform_profile, flavors, transitive_js_library_outputs, dependencies_file)
+
+        built_js_providers = _get_default_providers(js_bundle_info)
+        extra_providers = _get_extra_providers(ctx, js_bundle_info, transform_profile)
+        misc_providers = [DefaultInfo(default_output = js_bundle_info.misc)]
+        source_map_providers = [DefaultInfo(default_output = js_bundle_info.source_map)]
+        dependencies_providers = [DefaultInfo(default_output = js_bundle_info.dependencies_file)]
+        res_providers = [DefaultInfo(default_output = js_bundle_info.res)]
+
+        sub_targets[transform_profile] = built_js_providers + extra_providers
+        sub_targets["{}-misc".format(transform_profile)] = misc_providers
+        sub_targets["{}-source_map".format(transform_profile)] = source_map_providers
+        sub_targets["{}-dependencies".format(transform_profile)] = dependencies_providers
+
+        fallback_transform_profile = _get_fallback_transform_profile(ctx)
+        if transform_profile == fallback_transform_profile:
+            default_outputs.append(js_bundle_info.built_js)
+            expect(extra_unnamed_output_providers == None, "Extra unnamed output providers should only be set once!")
+            extra_unnamed_output_providers = extra_providers
+            sub_targets["misc"] = misc_providers
+            sub_targets["source_map"] = source_map_providers
+            sub_targets["dependencies"] = dependencies_providers
+            sub_targets["res"] = res_providers
+
+    expect(len(default_outputs) == 1, "Should get exactly one default output!")
+    expect(extra_unnamed_output_providers != None, "Should set extra unnamed output providers once!")
+    return [
+        DefaultInfo(default_outputs = default_outputs, sub_targets = sub_targets),
+    ] + extra_unnamed_output_providers
diff --git a/buck2/prelude/js/js_bundle_genrule.bzl b/buck2/prelude/js/js_bundle_genrule.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/js/js_bundle_genrule.bzl
@@ -0,0 +1,317 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:cache_mode.bzl", "CacheModeInfo")
+load("@prelude//:genrule_local_labels.bzl", "resolved_genrule_labels_require_local")
+load("@prelude//:genrule_prefer_local_labels.bzl", "resolved_genrule_labels_prefer_local")
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load("@prelude//android:android_providers.bzl", "AndroidResourceInfo", "merge_android_packageable_info")
+load("@prelude//js:js_providers.bzl", "JsBundleInfo")
+load("@prelude//js:js_utils.bzl", "TRANSFORM_PROFILES", "get_apple_resource_providers_for_js_bundle", "get_bundle_name")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "value_or")
+
+_GENRULE_OUT_DIR = "out"
+
+_WINDOWS_ENV_SUBSTITUTIONS = [
+    # Replace $OUT and ${OUT}
+    (regex("\\$(OUT\\b|\\{OUT\\})"), "%OUT%"),
+    (regex("\\$(SRCDIR\\b|\\{SRCDIR\\})"), "%SRCDIR%"),
+    (regex("\\$(SRCS\\b|\\{SRCS\\})"), "%SRCS%"),
+    (regex("\\$(TMP\\b|\\{TMP\\})"), "%TMP%"),
+]
+
+# We don't want to use cache mode in open source because the config keys that drive it aren't wired up
+_USE_CACHE_MODE = is_full_meta_repo()
+
+def _get_cache_mode(ctx: AnalysisContext) -> CacheModeInfo:
+    if _USE_CACHE_MODE:
+        return ctx.attrs._cache_mode[CacheModeInfo]
+    else:
+        return CacheModeInfo(allow_cache_uploads = False, cache_bust_genrules = False)
+
+def _run_genrule(ctx: AnalysisContext, out_name: str, extra_env_vars: dict, identifier: str) -> Artifact:
+    local_only = resolved_genrule_labels_require_local(ctx.attrs.labels)
+    prefer_local = resolved_genrule_labels_prefer_local(ctx.attrs.labels)
+
+    # NOTE: Eventually we shouldn't require local_only here, since we should be
+    # fine with caching local fallbacks if necessary (or maybe that should be
+    # disallowed as a matter of policy), but for now let's be safe.
+    cacheable = value_or(ctx.attrs.cacheable, True) and (local_only or prefer_local)
+
+    content_based = ctx.attrs.has_content_based_path
+
+    out_artifact = ctx.actions.declare_output(_GENRULE_OUT_DIR, out_name, has_content_based_path = content_based)
+
+    is_windows = ctx.attrs._exec_os_type[OsLookup].os == Os("windows")
+    if is_windows:
+        path_sep = "\\"
+        cmd = ctx.attrs.cmd_exe if ctx.attrs.cmd_exe != None else ctx.attrs.cmd
+        if cmd == None:
+            fail("One of `cmd` or `cmd_exe` should be set.")
+    else:
+        path_sep = "/"
+        cmd = ctx.attrs.bash if ctx.attrs.bash != None else ctx.attrs.cmd
+        if cmd == None:
+            fail("One of `cmd` or `bash` should be set.")
+
+    replace_regex = []
+
+    # For backwards compatibility with Buck1.
+    if is_windows:
+        for re, sub in _WINDOWS_ENV_SUBSTITUTIONS:
+            replace_regex.append((re, sub))
+
+        for extra_env_var in extra_env_vars:
+            replace_regex.append(
+                (regex("\\$(%s\\b|\\{%s\\})" % (extra_env_var, extra_env_var)), "%%%s%%" % extra_env_var),
+            )
+
+    cmd = cmd_args(cmd, replace_regex = replace_regex)
+
+    if type(ctx.attrs.srcs) == type([]):
+        # FIXME: We should always use the short_path, but currently that is sometimes blank.
+        symlinks = {src.short_path: src for src in ctx.attrs.srcs}
+
+        if len(symlinks) != len(ctx.attrs.srcs):
+            for src in ctx.attrs.srcs:
+                name = src.short_path
+                if symlinks[name] != src:
+                    msg = "genrule srcs include duplicative name: `{}`. ".format(name)
+                    msg += "`{}` conflicts with `{}`".format(symlinks[name].owner, src.owner)
+                    fail(msg)
+    else:
+        symlinks = ctx.attrs.srcs
+    srcs_artifact = ctx.actions.symlinked_dir(
+        "{}-srcs".format(identifier),
+        symlinks,
+        has_content_based_path = content_based,
+    )
+
+    delimiter = ctx.attrs.environment_expansion_separator or " "
+
+    # Setup environment variables.
+    srcs = cmd_args(delimiter = delimiter)
+    for symlink in symlinks:
+        srcs.add(cmd_args(srcs_artifact, format = path_sep.join([".", "{}", symlink.replace("/", path_sep)])))
+    env_vars = {
+        "GEN_DIR": "GEN_DIR_DEPRECATED",
+        "OUT": out_artifact.as_output(),
+        "SRCDIR": cmd_args(srcs_artifact, format = path_sep.join([".", "{}"])),
+        "SRCS": srcs,
+    } | {k: cmd_args(v) for k, v in getattr(ctx.attrs, "env", {}).items()}
+
+    # RE will cache successful actions that don't produce the desired outputs,
+    # so if that happens and _then_ we add a local-only label, we'll get a
+    # cache hit on the action that didn't produce the outputs and get the error
+    # again (thus making the label useless). So, when a local-only label is
+    # set, we make the action *different*.
+    if local_only:
+        env_vars["__BUCK2_LOCAL_ONLY_CACHE_BUSTER"] = ""
+
+    # see comment above
+    if prefer_local:
+        env_vars["__BUCK2_PREFER_LOCAL_CACHE_BUSTER"] = ""
+
+    # For now, when uploads are enabled, be safe and avoid sharing cache hits.
+    if cacheable and _get_cache_mode(ctx).cache_bust_genrules:
+        env_vars["__BUCK2_ALLOW_CACHE_UPLOADS_CACHE_BUSTER"] = ""
+
+    for key, value in extra_env_vars.items():
+        env_vars[key] = value
+
+    if is_windows:
+        script_extension = "bat"
+        script = [
+            cmd_args('if NOT "%TEMP%" == "" set "TMP=%TEMP%"'),
+            cmd,
+        ]
+    else:
+        script_extension = "sh"
+        script = [
+            cmd_args("export TMP=${TMPDIR:-/tmp}"),
+            cmd,
+        ]
+
+    # `cd` into the sandboxed source dir and relativize all paths to that, unless
+    # the genrule explicitly opts in to running from the build root.
+    if not ctx.attrs.repo_relative_root:
+        srcs_dir = srcs_artifact
+
+        if is_windows:
+            rewrite_scratch_path = cmd_args(
+                cmd_args(ctx.label.project_root, relative_to = srcs_artifact),
+                format = 'set "BUCK_SCRATCH_PATH={}\\%BUCK_SCRATCH_PATH%"',
+            )
+        else:
+            srcs_dir = cmd_args(srcs_dir, quote = "shell")
+            rewrite_scratch_path = cmd_args(
+                cmd_args(ctx.label.project_root, quote = "shell", relative_to = srcs_artifact),
+                format = "export BUCK_SCRATCH_PATH={}/$BUCK_SCRATCH_PATH",
+            )
+
+        for script_cmd in script:
+            script_cmd.relative_to(srcs_artifact)
+
+        script = [
+            rewrite_scratch_path,
+            cmd_args(srcs_dir, format = "cd {}"),
+        ] + script
+
+        env_vars = {key: cmd_args(value, relative_to = srcs_artifact) for key, value in env_vars.items()}
+
+    if is_windows:
+        # Odd, why is this a single string. How does it not end up getting quoted and being weird?
+        script = [cmd_args("@echo off")] + script
+
+    sh_script, _ = ctx.actions.write(
+        "sh/{}-genrule.{}".format(identifier, script_extension),
+        script,
+        is_executable = True,
+        allow_args = True,
+        has_content_based_path = content_based,
+    )
+    if is_windows:
+        script_args = ["cmd.exe", "/v:off", "/c", sh_script]
+    else:
+        script_args = ["/usr/bin/env", "bash", "-e", sh_script]
+
+    # Only set metadata arguments when they are non-null
+    metadata_args = {}
+    if ctx.attrs.metadata_env_var:
+        metadata_args["metadata_env_var"] = ctx.attrs.metadata_env_var
+    if ctx.attrs.metadata_path:
+        metadata_args["metadata_path"] = ctx.attrs.metadata_path
+    if ctx.attrs.remote_execution_dependencies:
+        metadata_args["remote_execution_dependencies"] = ctx.attrs.remote_execution_dependencies
+
+    # As of 09/2021, all genrule types were legal snake case if their dashes and periods were replaced with underscores.
+    category = "genrule_" + ctx.attrs.type.replace("-", "_").replace(".", "_")
+
+    ctx.actions.run(
+        cmd_args(script_args, hidden = [cmd, srcs_artifact, out_artifact.as_output()]),
+        env = env_vars,
+        local_only = local_only,
+        prefer_local = prefer_local,
+        weight = value_or(ctx.attrs.weight, 1),
+        allow_cache_upload = cacheable,
+        allow_offline_output_cache = ctx.attrs.allow_offline_output_cache,
+        category = category,
+        identifier = identifier,
+        no_outputs_cleanup = ctx.attrs.no_outputs_cleanup,
+        always_print_stderr = ctx.attrs.always_print_stderr,
+        **metadata_args,
+    )
+
+    return out_artifact
+
+def _build_js_bundle(ctx: AnalysisContext, bundle_name_out: str, js_bundle_info: JsBundleInfo, named_output: str) -> JsBundleInfo:
+    env_vars = {
+        "DEPENDENCIES": cmd_args(js_bundle_info.dependencies_file),
+        "JS_BUNDLE_NAME": cmd_args(js_bundle_info.bundle_name),
+        "JS_BUNDLE_NAME_OUT": cmd_args(bundle_name_out),
+        "JS_DIR": cmd_args(js_bundle_info.built_js),
+        "MISC_DIR": cmd_args(js_bundle_info.misc),
+        "PLATFORM": cmd_args(ctx.attrs._platform),
+        "RELEASE": cmd_args("1" if ctx.attrs._is_release else ""),
+        "RES_DIR": cmd_args(js_bundle_info.res),
+        "SOURCEMAP": cmd_args(js_bundle_info.source_map),
+    }
+    has_content_based_path = ctx.attrs.has_content_based_path
+    if ctx.attrs.rewrite_sourcemap:
+        source_map_out = ctx.actions.declare_output("{}/source_map".format(named_output), has_content_based_path = has_content_based_path)
+        env_vars["SOURCEMAP_OUT"] = cmd_args(source_map_out.as_output())
+    else:
+        source_map_out = js_bundle_info.source_map
+
+    if ctx.attrs.rewrite_misc:
+        misc_out = ctx.actions.declare_output("{}/misc".format(named_output), has_content_based_path = has_content_based_path)
+        env_vars["MISC_OUT"] = cmd_args(misc_out.as_output())
+    else:
+        misc_out = js_bundle_info.misc
+
+    if ctx.attrs.rewrite_deps_file:
+        dependencies_out = ctx.actions.declare_output("{}/dependencies".format(named_output), has_content_based_path = has_content_based_path)
+        env_vars["DEPENDENCIES_OUT"] = cmd_args(dependencies_out.as_output())
+    else:
+        dependencies_out = js_bundle_info.dependencies_file
+
+    built_js = _run_genrule(ctx, "{}-js".format(named_output), env_vars, named_output)
+
+    return JsBundleInfo(
+        bundle_name = bundle_name_out,
+        built_js = built_js,
+        source_map = source_map_out,
+        res = js_bundle_info.res,
+        generic_assets = js_bundle_info.generic_assets,
+        misc = misc_out,
+        dependencies_file = dependencies_out,
+    )
+
+def _get_extra_providers(
+    ctx: AnalysisContext, skip_resources: bool, initial_target: [ProviderCollection, Dependency], js_bundle_out: JsBundleInfo
+) -> list[Provider]:
+    providers = []
+    android_resource_info = initial_target.get(AndroidResourceInfo)
+    if android_resource_info:
+        expect(js_bundle_out.generic_assets != None, "generic_assets must be set for Android js_bundle")
+        assets = [js_bundle_out.built_js]
+        if not skip_resources:
+            assets.append(js_bundle_out.generic_assets)
+        new_android_resource_info = AndroidResourceInfo(
+            raw_target = ctx.label.raw_target(),
+            aapt2_compile_output = None if skip_resources else android_resource_info.aapt2_compile_output,
+            allow_strings_as_assets_resource_filtering = True,
+            assets = assets,
+            manifest_file = None,
+            r_dot_java_package = None if skip_resources else android_resource_info.r_dot_java_package,
+            res = None if skip_resources else android_resource_info.res,
+            res_priority = android_resource_info.res_priority,
+            text_symbols = None if skip_resources else android_resource_info.text_symbols,
+            unused_resource_dep_validation_has_non_xml_resources = True,
+        )
+        providers.append(new_android_resource_info)
+        providers.append(merge_android_packageable_info(ctx.label, ctx.actions, deps = [], resource_info = new_android_resource_info))
+
+    providers += get_apple_resource_providers_for_js_bundle(ctx, js_bundle_out, ctx.attrs._platform, skip_resources)
+
+    return providers
+
+def js_bundle_genrule_impl(ctx: AnalysisContext) -> list[Provider]:
+    sub_targets = {}
+    for transform_profile in TRANSFORM_PROFILES:
+        js_bundle = ctx.attrs.js_bundle[DefaultInfo].sub_targets[transform_profile]
+        js_bundle_info = js_bundle[JsBundleInfo]
+        bundle_name_out = get_bundle_name(ctx, js_bundle_info.bundle_name)
+
+        js_bundle_out = _build_js_bundle(ctx, bundle_name_out, js_bundle_info, transform_profile)
+
+        sub_targets[transform_profile] = [
+            DefaultInfo(default_output = js_bundle_out.built_js),
+            js_bundle_out,
+        ] + _get_extra_providers(ctx, ctx.attrs.skip_resources, js_bundle, js_bundle_out)
+        sub_targets["{}-misc".format(transform_profile)] = [DefaultInfo(default_output = js_bundle_out.misc)]
+        sub_targets["{}-source_map".format(transform_profile)] = [DefaultInfo(default_output = js_bundle_out.source_map)]
+        sub_targets["{}-dependencies".format(transform_profile)] = [DefaultInfo(default_output = js_bundle_out.dependencies_file)]
+        sub_targets["{}-res".format(transform_profile)] = [DefaultInfo(default_output = js_bundle_out.res)]
+
+    js_bundle_info = ctx.attrs.js_bundle[JsBundleInfo]
+    bundle_name_out = get_bundle_name(ctx, js_bundle_info.bundle_name)
+    js_bundle_out = _build_js_bundle(ctx, bundle_name_out, js_bundle_info, "default")
+
+    sub_targets["dependencies"] = [DefaultInfo(default_output = js_bundle_out.dependencies_file)]
+    sub_targets["misc"] = [DefaultInfo(default_output = js_bundle_out.misc)]
+    sub_targets["source_map"] = [DefaultInfo(default_output = js_bundle_out.source_map)]
+    sub_targets["res"] = [DefaultInfo(default_output = js_bundle_out.res)]
+    default_info_out = DefaultInfo(
+        default_output = js_bundle_out.built_js,
+        sub_targets = sub_targets,
+    )
+
+    return [default_info_out, js_bundle_out] + _get_extra_providers(ctx, ctx.attrs.skip_resources, ctx.attrs.js_bundle, js_bundle_out)
diff --git a/buck2/prelude/js/js_library.bzl b/buck2/prelude/js/js_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/js/js_library.bzl
@@ -0,0 +1,296 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//js:js_providers.bzl", "JsLibraryInfo", "get_transitive_outputs")
+load("@prelude//js:js_utils.bzl", "TRANSFORM_PROFILES", "get_canonical_src_name", "get_flavors", "run_worker_commands")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "map_idx")
+
+# A group of sources that all have the same canonical name. The main_source is arbitrary but
+# consistent (it is just the first source encountered when processing the src files).
+GroupedSource = record(
+    canonical_name = str,
+    main_source = Artifact,
+    additional_sources = list[Artifact],
+)
+
+def _get_grouped_srcs(ctx: AnalysisContext) -> list[GroupedSource]:
+    grouped_srcs = {}
+    for src in ctx.attrs.srcs:
+        expect(
+            isinstance(src, Artifact),
+            "src {} is not an artifact, its type is: {}".format(src, type(src)),
+        )
+        canonical_src_name = get_canonical_src_name(src.short_path)
+        if grouped_srcs.get(canonical_src_name, None) == None:
+            grouped_srcs[canonical_src_name] = GroupedSource(
+                canonical_name = canonical_src_name,
+                main_source = src,
+                additional_sources = [],
+            )
+        else:
+            grouped_srcs[canonical_src_name].additional_sources.append(src)
+
+    return grouped_srcs.values()
+
+def _get_base_package(ctx: AnalysisContext) -> str:
+    # The base package is identical for every source in the target, so callers resolve it once and
+    # pass it into _get_virtual_path rather than re-deriving it on every call.
+    package = ctx.label.package
+    base_path = ctx.attrs.base_path
+    if base_path and base_path not in ["", "."]:
+        package = paths.join(package, base_path)
+
+    return package
+
+def _get_virtual_path(package: str, src: Artifact) -> str:
+    return paths.join(package, src.short_path)
+
+# A source's transform job args, minus the fields that depend on the transform profile
+# (`outputFilePath` and `transformProfile`). These are built once per source and reused across
+# all of TRANSFORM_PROFILES.
+_PrecomputedJsFile = record(
+    canonical_name = str,
+    hidden_inputs = list[ArgLike],
+    job_args = dict,
+)
+
+def _precompute_transform_job_args(ctx: AnalysisContext, flavors: list[str], grouped_srcs: list[GroupedSource]) -> list[_PrecomputedJsFile]:
+    # `js_library_impl` runs the transform pipeline once per entry in TRANSFORM_PROFILES. Every
+    # field of a source's transform job args is identical across profiles except `outputFilePath`
+    # and `transformProfile`, so build the profile-independent portion exactly once here instead
+    # of rebuilding it for every (source, profile) pair inside `_build_js_files`.
+    extra_job_args = {}
+    extra_hidden_inputs = []
+    if ctx.attrs.extra_json:
+        extra_job_args["extraData"] = cmd_args(ctx.attrs.extra_json, delimiter = "")
+        extra_hidden_inputs.append(ctx.attrs.extra_json)
+
+    if ctx.attrs.extra_babel_plugins:
+        babel_plugin_configs = []
+        for plugin_value in ctx.attrs.extra_babel_plugins:
+            if type(plugin_value) == "tuple":
+                plugin_dep, plugin_args_json = plugin_value
+            else:
+                plugin_dep = plugin_value
+                plugin_args_json = None
+            plugin_artifact = plugin_dep[DefaultInfo].default_outputs[0]
+            config = {"modulePath": plugin_artifact}
+            extra_hidden_inputs.append(plugin_artifact)
+            if plugin_args_json != None:
+                config["pluginArgs"] = cmd_args(plugin_args_json, delimiter = "")
+                extra_hidden_inputs.append(plugin_args_json)
+            babel_plugin_configs.append(config)
+        extra_job_args["extraBabelPlugins"] = babel_plugin_configs
+
+    base_package = _get_base_package(ctx)
+
+    precomputed_js_files = []
+    for grouped_src in grouped_srcs:
+        job_args = {
+            "additionalSources": [
+                {
+                    "sourcePath": additional_source,
+                    "virtualPath": _get_virtual_path(base_package, additional_source),
+                }
+                for additional_source in grouped_src.additional_sources
+            ],
+            "command": "transform",
+            "flavors": flavors,
+            "release": ctx.attrs._is_release,
+            "sourceJsFileName": _get_virtual_path(base_package, grouped_src.main_source),
+            "sourceJsFilePath": grouped_src.main_source,
+        }
+        job_args.update(extra_job_args)
+        precomputed_js_files.append(
+            _PrecomputedJsFile(
+                canonical_name = grouped_src.canonical_name,
+                hidden_inputs = [grouped_src.main_source] + grouped_src.additional_sources + extra_hidden_inputs,
+                job_args = job_args,
+            )
+        )
+
+    return precomputed_js_files
+
+def _build_js_files(ctx: AnalysisContext, transform_profile: str, precomputed_js_files: list[_PrecomputedJsFile]) -> list[Artifact]:
+    if not precomputed_js_files:
+        return []
+
+    all_output_paths = []
+    all_command_hidden_artifacts = []
+    all_job_args = []
+    for precomputed_js_file in precomputed_js_files:
+        identifier = "{}/{}".format(transform_profile, precomputed_js_file.canonical_name)
+
+        output_path = ctx.actions.declare_output(
+            "transform-out/{}.jsfile".format(identifier),
+            has_content_based_path = True,
+        )
+
+        # Copy the profile-independent base and fill in the two profile-specific fields.
+        job_args = dict(precomputed_js_file.job_args)
+        job_args["outputFilePath"] = output_path.as_output()
+        job_args["transformProfile"] = "default" if transform_profile == "hermes-legacy" else transform_profile
+
+        all_output_paths.append(output_path)
+        all_command_hidden_artifacts.append(precomputed_js_file.hidden_inputs + [output_path.as_output()])
+        all_job_args.append(job_args)
+
+    command_args_file = ctx.actions.write_json(
+        "{}.js_command_args".format(transform_profile),
+        {
+            "commands": all_job_args,
+            "version": 1,
+        },
+        with_inputs = False,
+        has_content_based_path = True,
+    )
+
+    batch_size = 25
+    command_count = len(all_output_paths)
+    for batch_number, start_index in enumerate(range(0, command_count, batch_size)):
+        end_index = min(start_index + batch_size, command_count)
+        hidden_artifacts = []
+        for command_hidden_artifacts in all_command_hidden_artifacts[start_index:end_index]:
+            hidden_artifacts.extend(command_hidden_artifacts)
+        run_worker_commands(
+            ctx = ctx,
+            worker_tool = ctx.attrs.worker,
+            command_args_file = command_args_file,
+            command_args_file_range = (start_index, end_index),
+            hidden_artifacts = hidden_artifacts,
+            identifier = "{}_{}_batch{}".format(ctx.label.name, transform_profile, batch_number),
+            category = "transform",
+            has_content_based_path = True,
+        )
+
+    return all_output_paths
+
+def _build_library_files(ctx: AnalysisContext, transform_profile: str, flavors: list[str], js_files: list[Artifact]) -> Artifact:
+    output_path = ctx.actions.declare_output(
+        "library-files-out/{}/library_files".format(transform_profile),
+        has_content_based_path = True,
+    )
+
+    job_args = {
+        "command": "library-files",
+        "flavors": flavors,
+        "outputFilePath": output_path.as_output(),
+        "platform": ctx.attrs._platform,
+        "release": ctx.attrs._is_release,
+        "sourceFilePaths": js_files,
+    }
+
+    if ctx.attrs.extra_json:
+        job_args["extraData"] = cmd_args(ctx.attrs.extra_json, delimiter = "")
+
+    if ctx.attrs._asset_dest_path_resolver:
+        job_args["assetDestPathResolver"] = ctx.attrs._asset_dest_path_resolver
+
+    command_args_file = ctx.actions.write_json(
+        "library_files_{}_command_args".format(transform_profile),
+        job_args,
+        with_inputs = True,
+        has_content_based_path = True,
+    )
+
+    run_worker_commands(
+        ctx = ctx,
+        worker_tool = ctx.attrs.worker,
+        command_args_file = command_args_file,
+        identifier = transform_profile,
+        category = "library_files",
+        has_content_based_path = True,
+    )
+    return output_path
+
+def _build_js_library(ctx: AnalysisContext, transform_profile: str, library_files: Artifact, flavors: list[str], dep_library_files: list[Artifact]) -> Artifact:
+    output_path = ctx.actions.declare_output(
+        "library-dependencies-out/{}.jslib".format(transform_profile),
+        has_content_based_path = True,
+    )
+    job_args = {
+        "aggregatedSourceFilesFilePath": library_files,
+        "command": "library-dependencies",
+        "dependencyLibraryFilePaths": dep_library_files,
+        "flavors": flavors,
+        "outputPath": output_path.as_output(),
+        "platform": ctx.attrs._platform,
+        "release": ctx.attrs._is_release,
+    }
+
+    if ctx.attrs.extra_json:
+        job_args["extraData"] = cmd_args(ctx.attrs.extra_json, delimiter = "")
+
+    command_args_file = ctx.actions.write_json(
+        "library_deps_{}_args".format(transform_profile),
+        job_args,
+        with_inputs = True,
+        has_content_based_path = True,
+    )
+
+    run_worker_commands(
+        ctx = ctx,
+        worker_tool = ctx.attrs.worker,
+        command_args_file = command_args_file,
+        identifier = transform_profile,
+        category = "library_dependencies",
+        has_content_based_path = True,
+    )
+
+    return output_path
+
+def js_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    grouped_srcs = _get_grouped_srcs(ctx)
+    flavors = get_flavors(ctx)
+    precomputed_js_files = _precompute_transform_job_args(ctx, flavors, grouped_srcs)
+    sub_targets = {}
+
+    for transform_profile in TRANSFORM_PROFILES:
+        built_js_files = _build_js_files(ctx, transform_profile, precomputed_js_files)
+        library_files = _build_library_files(ctx, transform_profile, flavors, built_js_files)
+
+        js_library_deps = dedupe(
+            map_idx(
+                JsLibraryInfo,
+                [dep[DefaultInfo].sub_targets[transform_profile] for dep in ctx.attrs.deps],
+            )
+        )
+        # Dependency resolution only needs each dep's own module map (file
+        # paths, haste IDs and package info), all of which is present in the
+        # dep's `library_files` output. Depending on that instead of the dep's
+        # resolved `.jslib` output keeps the depth of the action graph constant
+        # instead of proportional to the depth of the js_library target graph.
+        js_library = _build_js_library(
+            ctx,
+            transform_profile,
+            library_files,
+            flavors,
+            [js_library_dep.library_files for js_library_dep in js_library_deps],
+        )
+
+        transitive_outputs = get_transitive_outputs(
+            ctx.actions,
+            value = js_library,
+            deps = js_library_deps,
+        )
+
+        sub_targets[transform_profile] = [
+            DefaultInfo(default_output = js_library),
+            JsLibraryInfo(
+                library_files = library_files,
+                output = js_library,
+                transitive_outputs = transitive_outputs,
+            ),
+        ]
+
+    return [
+        DefaultInfo(default_output = None, sub_targets = sub_targets),
+    ]
diff --git a/buck2/prelude/js/js_providers.bzl b/buck2/prelude/js/js_providers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/js/js_providers.bzl
@@ -0,0 +1,52 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _artifacts(value: Artifact):
+    return value
+
+TransitiveOutputsTSet = transitive_set(args_projections = {"artifacts": _artifacts})
+
+JsLibraryInfo = provider(
+    fields = {
+        # Output of the `library_files` action: the library's own transformed
+        # files, before cross-library dependency resolution.
+        "library_files": provider_field(Artifact | None, default = None),
+        "output": provider_field(Artifact | None, default = None),
+        "transitive_outputs": provider_field(TransitiveOutputsTSet | None, default = None),
+    },
+)
+
+JsBundleInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "bundle_name": provider_field(typing.Any, default = None),  # str
+        # Directory containing the built JavaScript.
+        "built_js": provider_field(typing.Any, default = None),  # "artifact",
+        # Source map belonging to the built JavaScript.
+        "source_map": provider_field(typing.Any, default = None),  # "artifact",
+        # Directory containing the resources (or assets) used by the bundled JavaScript source code.
+        "res": provider_field(typing.Any, default = None),  # ["artifact", None]
+        # Directory of raw asset files produced by js_library targets that use
+        # `_asset_dest_path_resolver = "generic"`. Only used on Android platforms.
+        "generic_assets": provider_field(typing.Any, default = None),  # ["artifact", None]
+        # Directory containing various metadata that can be used by dependent rules but are not
+        # meant to be shipped with the application.
+        "misc": provider_field(typing.Any, default = None),  # "artifact"
+        # Dependencies graph file associated with the built JavaScript.
+        "dependencies_file": provider_field(typing.Any, default = None),  # "artifact"
+    },
+)
+
+def get_transitive_outputs(actions: AnalysisActions, value: Artifact | None = None, deps: list[JsLibraryInfo] = []) -> TransitiveOutputsTSet:
+    kwargs = {}
+    if value:
+        kwargs["value"] = value
+    if deps:
+        kwargs["children"] = [js_library_info.transitive_outputs for js_library_info in deps]
+
+    return actions.tset(TransitiveOutputsTSet, **kwargs)
diff --git a/buck2/prelude/js/js_utils.bzl b/buck2/prelude/js/js_utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/js/js_utils.bzl
@@ -0,0 +1,181 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//apple:apple_resource_types.bzl", "AppleResourceDestination", "AppleResourceSpec")
+load("@prelude//apple:resource_groups.bzl", "ResourceGraphInfo", "create_resource_graph")  # @unused `ResourceGraphInfo` used as a type
+load("@prelude//js:js_providers.bzl", "JsBundleInfo")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+load("@prelude//utils:expect.bzl", "expect")
+load(":worker_tool.bzl", "WorkerToolInfo")
+
+TRANSFORM_PROFILES = ["hermes-legacy", "hermes-stable", "hermes-canary"]
+
+# Matches the default value for resolver.assetExts in metro-config
+ASSET_EXTENSIONS = [
+    # Image formats
+    "bmp",
+    "gif",
+    "jpg",
+    "jpeg",
+    "png",
+    "psd",
+    "svg",
+    "webp",
+    # Video formats
+    "m4v",
+    "mov",
+    "mp4",
+    "mpeg",
+    "mpg",
+    "webm",
+    # Audio formats
+    "aac",
+    "aiff",
+    "caf",
+    "m4a",
+    "mp3",
+    "wav",
+    # Document formats
+    "html",
+    "pdf",
+    "yaml",
+    "yml",
+    # Font formats
+    "otf",
+    "ttf",
+    # Archives (virtual files)
+    "zip",
+    "lottie",
+    # 3D models
+    "glb",
+]
+
+# Matches the default value for resolver.platforms in metro-config
+ASSET_PLATFORMS = ["ios", "android", "windows", "macos", "web"]
+
+def get_apple_resource_providers_for_js_bundle(
+    ctx: AnalysisContext, js_bundle_info: JsBundleInfo, platform: str, skip_resources: bool
+) -> list[ResourceGraphInfo]:
+    if platform != "ios" and platform != "macos":
+        return []
+
+    # `skip_resources` controls whether the JS resources should be skipped, not whether
+    # the whole bundle should be skipped as a resource
+    resources_content_dirs = [] if skip_resources else [js_bundle_info.res]
+    resource_spec = AppleResourceSpec(
+        content_dirs = [
+            js_bundle_info.built_js,
+        ]
+        + resources_content_dirs,
+        destination = AppleResourceDestination("resources"),
+    )
+    return [
+        create_resource_graph(
+            ctx = ctx,
+            labels = ctx.attrs.labels,
+            deps = [],
+            exported_deps = [],
+            resource_spec = resource_spec,
+        )
+    ]
+
+def _strip_platform_from_asset_name(name: str) -> str:
+    name_without_extension, extension = paths.split_extension(name)
+    return name_without_extension if extension[1:] in ASSET_PLATFORMS else name
+
+def _strip_scale_from_asset_name(name: str) -> str:
+    scale_start = -1
+    for i in range(len(name)):
+        char = name[i]
+        if scale_start != -1:
+            if char == "x":
+                return name[:scale_start] + name[i + 1 :]
+            if char.isdigit() or char == ".":
+                continue
+            fail("Invalid format for scale of asset {}!".format(name))
+        if name[i] == "@":
+            scale_start = i
+
+    expect(scale_start == -1, "Found scale_start but not its end {}!".format(name))
+
+    return name
+
+def get_canonical_src_name(src: str) -> str:
+    dirname = paths.dirname(src)
+    basename = paths.basename(src)
+    filename, extension = paths.split_extension(basename)
+    if extension[1:] not in ASSET_EXTENSIONS:
+        return src
+
+    filename = _strip_platform_from_asset_name(filename)
+    filename = _strip_scale_from_asset_name(filename)
+
+    return paths.join(dirname, filename + extension)
+
+def get_flavors(ctx: AnalysisContext) -> list[str]:
+    flavors = [ctx.attrs._platform]
+    if ctx.attrs._is_release:
+        flavors.append("release")
+
+    return flavors
+
+def get_bundle_name(ctx: AnalysisContext, default_bundle_name: str) -> str:
+    bundle_name_for_flavor_map = {key: value for key, value in ctx.attrs.bundle_name_for_flavor}
+    flavors = bundle_name_for_flavor_map.keys()
+    for flavor in flavors:
+        expect(
+            flavor == "android" or flavor == "ios" or flavor == "macos" or flavor == "windows" or flavor == "vr",
+            "Currently only support picking bundle name by platform!",
+        )
+
+    platform = ctx.attrs._platform
+    if platform in flavors:
+        return bundle_name_for_flavor_map[platform]
+    else:
+        return ctx.attrs.bundle_name if ctx.attrs.bundle_name else default_bundle_name
+
+def run_worker_commands(
+    ctx: AnalysisContext,
+    worker_tool: Dependency,
+    command_args_file: ArgLike,
+    identifier: str,
+    category: str,
+    has_content_based_path: bool = False,
+    command_args_file_range = None,
+    hidden_artifacts = None,
+):
+    if hidden_artifacts == None:
+        hidden_artifacts = []
+
+    worker_args = cmd_args(
+        "--command-args-file",
+        command_args_file,
+        "--command-args-file-extra-data-fixup-hack=true",
+    )
+    if command_args_file_range != None:
+        worker_args.add(
+            "--command-args-file-range",
+            "{}:{}".format(command_args_file_range[0], command_args_file_range[1]),
+        )
+
+    worker_tool_info = worker_tool[WorkerToolInfo]
+    worker_command = cmd_args(
+        worker_tool_info.command.copy(),
+        worker_args,
+        hidden = [command_args_file] + hidden_artifacts,
+    )
+
+    ctx.actions.run(
+        worker_command,
+        category = category.replace("-", "_"),
+        identifier = identifier,
+        # Handshake seems more prone to failure when running locally, so workaround by running remotely where possible.
+        prefer_remote = True,
+        expect_eligible_for_dedupe = has_content_based_path,
+    )
diff --git a/buck2/prelude/js/worker_runner/BUCK b/buck2/prelude/js/worker_runner/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/js/worker_runner/BUCK
@@ -0,0 +1,13 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "worker_tool_runner",
+    main = "worker_tool_runner.py",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/js/worker_runner/worker_tool_runner.py b/buck2/prelude/js/worker_runner/worker_tool_runner.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/js/worker_runner/worker_tool_runner.py
@@ -0,0 +1,460 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+import os
+import pathlib
+import subprocess
+import sys
+import tempfile
+import traceback
+from typing import Any, Dict
+
+ENCODING = "utf-8"
+AGGREGATE_COMMAND_ARGS_VERSION = 1
+
+TYPE_HANDSHAKE = "handshake"
+TYPE_COMMAND = "command"
+TYPE_RESULT = "result"
+TYPE_ERROR = "error"
+PROTOCOL_VERSION = "0"
+
+START_HANDSHAKE_PREFIX = "["
+START_MESSAGE_PREFIX = ","
+EXIT_DATA = "]"
+
+
+def _parse_args():
+    parser = argparse.ArgumentParser(
+        description="Worker tool runner.",
+        fromfile_prefix_chars="@",
+    )
+
+    parser.add_argument(
+        "--worker-tool",
+        type=str,
+        required=True,
+        metavar="worker_tool",
+        help="Worker tool",
+    )
+
+    parser.add_argument(
+        "--worker-args-file",
+        type=pathlib.Path,
+        metavar="worker_args_file",
+        help="Path to the file with stored worker tool arguments",
+    )
+
+    parser.add_argument(
+        "--worker-env-file",
+        type=pathlib.Path,
+        metavar="worker_env_file",
+        help="Path to the file with stored environment variables",
+    )
+
+    parser.add_argument(
+        "--command-args-file",
+        type=str,
+        nargs="+",
+        metavar="command_args_file",
+        help="Path to the file with command arguments",
+    )
+
+    parser.add_argument(
+        "--command-args-file-range",
+        type=str,
+        metavar="command_args_file_range",
+        help="START:END range of command arguments to run from an aggregate command args file",
+    )
+
+    # TODO(T121096376) remove this hack
+    parser.add_argument(
+        "--command-args-file-extra-data-fixup-hack",
+        type=bool,
+        metavar="command_args_file_extra_data_fixup_hack",
+        help="Whether to change the 'extraData' in the command args file to be a JSON blob",
+    )
+
+    return parser.parse_known_args()
+
+
+def _write_to_stream(stream, data):
+    stream.write(data.encode(ENCODING))
+    stream.flush()
+
+
+def read_till_separator(stream, separator):
+    buffer = ""
+    while True:  # until EOF
+        chunk = stream.read(1)
+        if not chunk:  # EOF?
+            return buffer
+
+        decoded_chunk = chunk.decode(ENCODING)
+        buffer += decoded_chunk
+        if separator == decoded_chunk:
+            return buffer.strip()
+
+
+def _read_from_stream(stream, delimiter="}") -> str:
+    return read_till_separator(stream, separator=delimiter)
+
+
+def _create_handshake_data(message_id) -> Dict[str, Any]:
+    return {
+        "id": message_id,
+        "type": TYPE_HANDSHAKE,
+        "protocol_version": PROTOCOL_VERSION,
+        "capabilities": [],
+    }
+
+
+def _perform_handshake(worker, message_id):
+    handshake_data = _create_handshake_data(message_id)
+    handshake_data_string = json.dumps(handshake_data).rstrip()
+    _write_to_stream(
+        worker.stdin, "{}{}".format(START_HANDSHAKE_PREFIX, handshake_data_string)
+    )
+    handshake_reply = _read_from_stream(worker.stdout)
+    if len(handshake_reply) == 0:
+        raise RuntimeError(
+            "Handshake '"
+            + handshake_data_string
+            + "' failed for worker '"
+            + json.dumps(worker.args).rstrip()
+            + "' with stderr: '"
+            + _read_from_stream(worker.stderr)
+            + "'"
+        )
+    assert START_HANDSHAKE_PREFIX == handshake_reply[0]
+    handshake_reply_data = json.loads(handshake_reply[1:])
+    assert handshake_data == handshake_reply_data
+
+
+def _create_args_file(args, tmp_dir) -> pathlib.Path:
+    args_path = os.path.join(tmp_dir, "command.args")
+    with open(args_path, "x") as args_path_writer:
+        for arg in args:
+            args_path_writer.write(arg)
+            args_path_writer.write(os.linesep)
+    return args_path
+
+
+def _create_job_command(args_path, message_id, tmp_dir) -> Dict[str, Any]:
+    job_stdout = os.path.join(tmp_dir, "{}.out".format(message_id))
+    job_stderr = os.path.join(tmp_dir, "{}.err".format(message_id))
+
+    return {
+        "id": message_id,
+        "type": TYPE_COMMAND,
+        "args_path": args_path,
+        "stdout_path": job_stdout,
+        "stderr_path": job_stderr,
+    }
+
+
+def _send_command(command, worker):
+    _write_to_stream(
+        worker.stdin, "{}{}".format(START_MESSAGE_PREFIX, json.dumps(command).rstrip())
+    )
+
+
+def _receive_command_reply(worker, message_id) -> int:
+    reply = _read_from_stream(worker.stdout)
+    if not reply:
+        raise RuntimeError(
+            f"Failed to receive reply from worker opened with args: {worker.args}\nstderr:\n{worker.stderr.read()}"
+        )
+    assert START_MESSAGE_PREFIX == reply[0]
+    reply_data = json.loads(reply[1:])
+
+    assert reply_data["id"] == message_id
+
+    type = reply_data["type"]
+    if type == TYPE_ERROR:
+        raise AssertionError("Worker had an error: {}".format(reply_data))
+
+    assert type == TYPE_RESULT
+
+    exit_code = reply_data["exit_code"]
+    if not isinstance(exit_code, int):
+        raise AssertionError(
+            "Worker returned non-integer exit code: {}".format(reply_data)
+        )
+    return exit_code
+
+
+def _perform_termination(worker):
+    _write_to_stream(worker.stdin, EXIT_DATA)
+    exit_reply = _read_from_stream(worker.stdout, delimiter=EXIT_DATA)
+    assert exit_reply == EXIT_DATA
+
+
+def _maybe_expand_worker_arg(arg, envs) -> str:
+    expanded_arg = arg
+    if "$" in arg:
+        for k, v in os.environ.items():
+            expanded_arg = expanded_arg.replace("${}".format(k), v)
+            expanded_arg = expanded_arg.replace("${}{}{}".format("{", k, "}"), v)
+    return expanded_arg
+
+
+def _println(line):
+    if line:
+        print("{}{}".format(line.rstrip(), os.linesep))
+
+
+def _fixup_command_args_file(command_args_file, index, tmp_dir) -> str:
+    content = _load_command_args_json(command_args_file)
+    content = _fixup_command_args_content(content, command_args_file)
+    return _write_command_args_file(content, index, tmp_dir)
+
+
+def _load_command_args_json(command_args_file) -> Dict[str, Any]:
+    with open(command_args_file, "r") as input_f:
+        try:
+            content = json.load(input_f)
+        except json.JSONDecodeError as error:
+            raise RuntimeError(
+                f"Unable to decode {command_args_file}, it should be a JSON file."
+            ) from error
+
+    if not isinstance(content, dict):
+        raise RuntimeError(f"{command_args_file} should contain a JSON object.")
+
+    return content
+
+
+def _fixup_command_args_content(content, command_args_file):
+    content = dict(content)
+
+    if "extraData" in content:
+        try:
+            content["extraData"] = json.loads(content["extraData"])
+        except json.JSONDecodeError as error:
+            raise RuntimeError(
+                f"Unable to decode 'extraData' in {command_args_file}, it should be a JSON string."
+            ) from error
+
+    return content
+
+
+def _write_command_args_file(content, index, tmp_dir) -> str:
+    args_path = os.path.join(
+        tmp_dir,
+        "fixup_command_args_{}".format(index),
+    )
+    with open(args_path, "x") as args_path_writer:
+        args_path_writer.write(json.dumps(content, sort_keys=True))
+
+    return args_path
+
+
+def _parse_command_args_file_range(command_args_file_range):
+    parts = command_args_file_range.split(":")
+    if len(parts) != 2:
+        raise RuntimeError(
+            f"Invalid --command-args-file-range '{command_args_file_range}', expected START:END."
+        )
+
+    try:
+        start = int(parts[0])
+        end = int(parts[1])
+    except ValueError as error:
+        raise RuntimeError(
+            f"Invalid --command-args-file-range '{command_args_file_range}', START and END must be integers."
+        ) from error
+
+    if start < 0 or end < 0 or start > end:
+        raise RuntimeError(
+            f"Invalid --command-args-file-range '{command_args_file_range}', expected 0 <= START <= END."
+        )
+
+    return start, end
+
+
+def _prepare_aggregate_command_args_files(
+    command_args_files,
+    command_args_file_range,
+    command_args_file_extra_data_fixup_hack,
+    tmp_dir,
+):
+    if len(command_args_files) != 1:
+        raise RuntimeError(
+            "--command-args-file-range requires exactly one --command-args-file."
+        )
+
+    command_args_file = command_args_files[0]
+    start, end = _parse_command_args_file_range(command_args_file_range)
+    content = _load_command_args_json(command_args_file)
+
+    if content.get("version") != AGGREGATE_COMMAND_ARGS_VERSION:
+        raise RuntimeError(
+            f"{command_args_file} has unsupported aggregate command args version: {content.get('version')}"
+        )
+
+    commands = content.get("commands")
+    if not isinstance(commands, list):
+        raise RuntimeError(f"{command_args_file} should contain a 'commands' list.")
+
+    if end > len(commands):
+        raise RuntimeError(
+            f"--command-args-file-range '{command_args_file_range}' exceeds {command_args_file} command count {len(commands)}."
+        )
+
+    expanded_command_args_files = []
+    for command_index, command in enumerate(commands[start:end], start):
+        if not isinstance(command, dict):
+            raise RuntimeError(
+                f"{command_args_file} command at index {command_index} should be a JSON object."
+            )
+        if command_args_file_extra_data_fixup_hack:
+            command = _fixup_command_args_content(command, command_args_file)
+        expanded_command_args_files.append(
+            _write_command_args_file(command, command_index, tmp_dir)
+        )
+
+    return expanded_command_args_files
+
+
+def _prepare_command_args_files(parsed_args, unparsed_args, tmp_dir):
+    command_args_files = parsed_args.command_args_file
+    command_args_file_range = parsed_args.command_args_file_range
+    command_args_file_extra_data_fixup_hack = (
+        parsed_args.command_args_file_extra_data_fixup_hack
+    )
+    command_args = unparsed_args
+
+    if command_args_files and len(command_args) > 0:
+        raise RuntimeError("Use either command line arguments or a file, not both!")
+
+    if command_args_file_range and not command_args_files:
+        raise RuntimeError(
+            "--command-args-file-range requires --command-args-file to be specified."
+        )
+
+    if command_args_files:
+        if command_args_file_range:
+            command_args_files = _prepare_aggregate_command_args_files(
+                command_args_files,
+                command_args_file_range,
+                command_args_file_extra_data_fixup_hack,
+                tmp_dir,
+            )
+        elif command_args_file_extra_data_fixup_hack:
+            command_args_files = [
+                _fixup_command_args_file(command_args_file, i, tmp_dir)
+                for i, command_args_file in enumerate(command_args_files)
+            ]
+    elif command_args:
+        if command_args_file_extra_data_fixup_hack:
+            raise RuntimeError(
+                "Only request command args file fixup if a command args file is specified!"
+            )
+        command_args_file = _create_args_file(command_args, tmp_dir)
+        command_args_files = [command_args_file]
+    else:
+        raise RuntimeError("Must provide a command for the worker to run!")
+
+    return command_args_files
+
+
+def _prepare_environment(worker_env_file):
+    envs = dict(os.environ)
+    if worker_env_file:
+        with open(worker_env_file) as we_file:
+            lines = we_file.readlines()
+            for i in range(0, len(lines), 2):
+                key = lines[i].rstrip()
+                value = lines[i + 1].rstrip()
+                envs[key] = value
+    return envs
+
+
+def _handle_error(exit_code, job_command):
+    if exit_code:
+        _println("Worker tool command finished with exit code: {}".format(exit_code))
+
+    if job_command is None:
+        _println("Handshake failed")
+    else:
+        stdout_path = job_command["stdout_path"]
+        if os.path.exists(stdout_path):
+            _println("{}std out: ".format(os.linesep))
+            with open(job_command["stdout_path"], "r") as std_out_reader:
+                for line in std_out_reader.readlines():
+                    _println(line)
+
+        stderr_path = job_command["stderr_path"]
+        if os.path.exists(stderr_path):
+            _println("{}std err: ".format(os.linesep))
+            with open(job_command["stderr_path"], "r") as std_err_reader:
+                for line in std_err_reader.readlines():
+                    _println(line)
+
+    if exit_code is not None:
+        sys.exit(exit_code)
+
+
+def _get_worker_tool_args(worker_args_file, envs):
+    worker_tool_args = []
+    if worker_args_file:
+        with open(worker_args_file) as wa_file:
+            for line in wa_file.readlines():
+                worker_tool_args.append(_maybe_expand_worker_arg(line.rstrip(), envs))
+    return worker_tool_args
+
+
+def main():
+    parsed_args, unparsed_args = _parse_args()
+
+    envs = _prepare_environment(parsed_args.worker_env_file)
+    worker_tool_args = _get_worker_tool_args(parsed_args.worker_args_file, envs)
+
+    with tempfile.TemporaryDirectory() as tmp_dir:
+        command_args_files = _prepare_command_args_files(
+            parsed_args, unparsed_args, tmp_dir
+        )
+
+        worker_tool = parsed_args.worker_tool
+        # It's important to use os.path.normpath() instead of pathlib.Path.resolve()
+        # because we don't want to resolve symlinks.
+        worker_tool = os.path.normpath(os.path.join(os.getcwd(), worker_tool))
+        with subprocess.Popen(
+            [worker_tool] + worker_tool_args,
+            env=envs,
+            stdout=subprocess.PIPE,
+            stdin=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+        ) as worker:
+            exit_code = None
+            try:
+                job_command = None
+                message_id = 0
+                _perform_handshake(worker, message_id)
+
+                for command_args_file in command_args_files:
+                    message_id += 1
+                    job_command = _create_job_command(
+                        command_args_file, message_id, tmp_dir
+                    )
+                    _send_command(job_command, worker)
+                    exit_code = _receive_command_reply(worker, message_id)
+
+                _perform_termination(worker)
+
+            except Exception:
+                traceback.print_exc()
+                exit_code = 1
+            finally:
+                _handle_error(exit_code, job_command)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/js/worker_tool.bzl b/buck2/prelude/js/worker_tool.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/js/worker_tool.bzl
@@ -0,0 +1,74 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:expect.bzl", "expect")
+
+WorkerToolInfo = provider(
+    fields = {
+        "command": provider_field(typing.Any, default = None),  # cmd_args
+    },
+)
+
+def worker_tool(ctx: AnalysisContext) -> list[Provider]:
+    """
+     worker_tool() rule implementation
+
+    Args:
+        ctx: rule analysis context
+    Returns:
+        list of created providers (DefaultInfo with an empty output and TemplatePlaceholderInfo with $(worker) macro key)
+    """
+
+    executable = ctx.attrs.exe
+    worker_tool_run_info = executable[RunInfo]
+    expect(worker_tool_run_info != None, "Worker tool executable must have a RunInfo!")
+
+    worker_tool_runner = ctx.attrs._worker_tool_runner[RunInfo]
+    worker_tool_cmd = [worker_tool_runner]
+    worker_tool_cmd.append("--worker-tool")
+    worker_tool_cmd.append(worker_tool_run_info)
+
+    worker_args = ctx.attrs.args
+    if worker_args:
+        worker_args_file, _ = ctx.actions.write(
+            "worker_tool_args",
+            worker_args,
+            allow_args = True,
+            has_content_based_path = False,
+        )
+
+        worker_tool_cmd.append("--worker-args-file")
+        worker_tool_cmd.append(worker_args_file)
+
+    worker_env = ctx.attrs.env
+    if worker_env:
+        env_args = []
+        for key, value in worker_env.items():
+            env_args.append(key)
+            env_args.append(value)
+
+        env_args_file, _ = ctx.actions.write(
+            "worker_tool_envs",
+            env_args,
+            allow_args = True,
+            has_content_based_path = False,
+        )
+
+        worker_tool_cmd.append("--worker-env-file")
+        worker_tool_cmd.append(env_args_file)
+
+    worker_tool_cmd = cmd_args(worker_tool_cmd)
+    return [
+        DefaultInfo(),
+        RunInfo(
+            args = worker_tool_cmd,
+        ),
+        WorkerToolInfo(
+            command = worker_tool_cmd,
+        ),
+    ]
diff --git a/buck2/prelude/julia/julia.bzl b/buck2/prelude/julia/julia.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/julia/julia.bzl
@@ -0,0 +1,64 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:common.bzl", "buck")
+load("@prelude//decls:test_common.bzl", "test_common")
+load(":julia_binary.bzl", "julia_binary_impl")
+load(":julia_library.bzl", "julia_jll_library_impl", "julia_library_impl")
+load(":julia_test.bzl", "julia_test_impl")
+load(":julia_toolchain.bzl", "julia_toolchain")
+
+implemented_rules = {
+    "julia_binary": julia_binary_impl,
+    "julia_jll_library": julia_jll_library_impl,
+    "julia_library": julia_library_impl,
+    "julia_test": julia_test_impl,
+}
+
+extra_attributes = {
+    "julia_binary": {
+        "deps": attrs.list(attrs.dep(), default = []),
+        "julia_args": attrs.list(attrs.string(), default = []),
+        "julia_flags": attrs.list(attrs.string(), default = []),
+        "main": attrs.string(),
+        "srcs": attrs.list(attrs.source(), default = []),
+        "_julia_toolchain": julia_toolchain(),
+    }
+    | buck.labels_arg()
+    | buck.contacts_arg(),
+    "julia_jll_library": {
+        "jll_name": attrs.string(),
+        "lib_mapping": attrs.named_set(attrs.dep()),
+        "uuid": attrs.string(),
+        "_julia_toolchain": julia_toolchain(),
+    }
+    | buck.labels_arg()
+    | buck.contacts_arg(),
+    "julia_library": {
+        "deps": attrs.list(attrs.dep(), default = []),
+        "project_toml": attrs.source(),
+        "resources": attrs.list(attrs.source(allow_directory = True), default = []),
+        "srcs": attrs.list(attrs.source(), default = []),
+        "_julia_toolchain": julia_toolchain(),
+    }
+    | buck.labels_arg()
+    | buck.contacts_arg(),
+    "julia_test": {
+        "deps": attrs.list(attrs.dep(), default = []),
+        "julia_args": attrs.list(attrs.string(), default = []),
+        "julia_flags": attrs.list(attrs.string(), default = []),
+        "main": attrs.string(),
+        "srcs": attrs.list(attrs.source(), default = []),
+        "_julia_toolchain": julia_toolchain(),
+        # TODO: coverage
+    }
+    | buck.labels_arg()
+    | buck.contacts_arg()
+    | buck.inject_test_env_arg()
+    | test_common.attributes(),
+}
diff --git a/buck2/prelude/julia/julia_binary.bzl b/buck2/prelude/julia/julia_binary.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/julia/julia_binary.bzl
@@ -0,0 +1,151 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "create_shlib_symlink_tree",
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+)
+load("@prelude//utils:utils.bzl", "flatten")
+load(":julia_info.bzl", "JuliaLibraryInfo", "JuliaLibraryTSet", "JuliaToolchainInfo")
+
+def build_jll_shlibs_mapping(ctx: AnalysisContext, json_info_file: Artifact):
+    """
+    Builds a mapping of julia shared library names to their corresponding.so files
+
+    We need to create a JSON file that contains all the relevant jlls, all the
+    shlibs that that particular jll needs to link to, and the solib locations.
+    Julia requires an absolute path. We get around this by establishing the
+    paths of all the libraries relative to the current JSON file, and then pull
+    the absolute path of the JSON file during runtime with a python script.
+
+    We populate the JSON file with the following structure:
+
+    Generates a list with the following structure:
+    [
+       ("first_jll", "uuid",
+          [
+             ("julia_foo_solib_name", symlink_dir_location, shlib_label),
+             ("julia_bar_solib_name", symlink_dir_location, shlib_label),
+          ]
+       )
+      ... etc
+    ]
+    """
+
+    # build a tree for the jlls
+    deps = filter(None, [dep.get(JuliaLibraryInfo) for dep in ctx.attrs.deps])
+    julia_library_info = ctx.actions.tset(
+        JuliaLibraryTSet,
+        children = [j.julia_tsets for j in deps],
+    )
+
+    # build a tree for the c/c++ shlibs
+    shlibs = traverse_shared_library_info(
+        merge_shared_libraries(
+            ctx.actions,
+            None,
+            filter(None, [d.shared_library_info for d in deps]),
+        ),
+        transformation_provider = None,
+    )
+
+    shared_libs_symlink_tree = create_shlib_symlink_tree(
+        actions = ctx.actions,
+        out = "__shared_libs_symlink_tree__",
+        shared_libs = shlibs,
+    )
+
+    shlib_label_to_soname = {shlib.label: shlib.soname.ensure_str() for shlib in shlibs}
+
+    # iterate through all the jll libraries
+    json_info = []
+    for jli in julia_library_info.traverse():
+        jll = jli.jll
+        if jll == None:
+            continue
+
+        # iterate through all the shlib dependencies for the current jll
+        artifact_info = []
+        for julia_name, label in jll.libs.items():
+            symlink_dir = cmd_args(
+                shared_libs_symlink_tree,
+                delimiter = "",
+                relative_to = json_info_file,  # That cannot be produced by a tset projection
+            )
+            artifact_info.append((julia_name, symlink_dir, shlib_label_to_soname[label]))
+        json_info.append((jll.name, jli.uuid, artifact_info))
+
+    return json_info
+
+def build_load_path_symtree(ctx: AnalysisContext):
+    """Builds symtree of all julia library files."""
+    dep_julia_library_infos = filter(None, [dep.get(JuliaLibraryInfo) for dep in ctx.attrs.deps])
+
+    julia_library_info = ctx.actions.tset(
+        JuliaLibraryTSet,
+        children = [j.julia_tsets for j in dep_julia_library_infos],
+    )
+    traversed = list(julia_library_info.traverse())
+    src_labels = flatten([t.src_labels for t in traversed])
+    srcs = flatten([t.srcs for t in traversed])
+
+    dict_from_tree = {k: p for k, p in zip(src_labels, srcs)}
+    symlink_dir = ctx.actions.symlinked_dir("_modules_", dict_from_tree, has_content_based_path = False)
+
+    return symlink_dir
+
+def build_julia_command(ctx):
+    """
+    run a command of the form:
+    $ julia -flag_1 -flag_2 -- my_script.jl arg1 arg2
+
+    https://docs.julialang.org/en/v1/manual/command-line-options/
+    """
+    julia_toolchain = ctx.attrs._julia_toolchain[JuliaToolchainInfo]
+
+    # build out the symlink tree for libs
+    symlink_dir = build_load_path_symtree(ctx)
+
+    # build symdir for sources
+    srcs_by_path = {f.short_path: f for f in ctx.attrs.srcs}
+    srcs = ctx.actions.symlinked_dir("srcs_tree", srcs_by_path, has_content_based_path = False)
+    if ctx.attrs.main not in srcs_by_path:
+        fail("main should be in srcs!")
+
+    # python processor
+    cmd = cmd_args(
+        [julia_toolchain.cmd_processor],
+        hidden = [symlink_dir] + [srcs],
+    )
+
+    # prepare a json file to hold all the data the python preprocessor needs to
+    # execute the julia interpreter.
+    json_info_file = ctx.actions.declare_output("artifacts/Overrides.json", has_content_based_path = False)
+
+    json_info_dict = {
+        "env": julia_toolchain.env,
+        "jll_mapping": build_jll_shlibs_mapping(ctx, json_info_file),
+        "julia_args": ctx.attrs.julia_args,
+        "julia_binary": cmd_args(julia_toolchain.julia, delimiter = " ", relative_to = json_info_file),
+        "julia_flags": ctx.attrs.julia_flags,
+        "lib_path": cmd_args(symlink_dir, delimiter = " ", relative_to = json_info_file),
+        "main": cmd_args(srcs.project(ctx.attrs.main), delimiter = " ", relative_to = json_info_file),
+    }
+
+    json_file_loc = ctx.actions.write_json(json_info_file, json_info_dict, with_inputs = True)
+
+    # json path
+    cmd.add(["--json-path", json_file_loc])
+
+    return cmd, json_info_file
+
+def julia_binary_impl(ctx: AnalysisContext) -> list[Provider]:
+    cmd, json_info_file = build_julia_command(ctx)
+    return [DefaultInfo(default_output = json_info_file, other_outputs = [cmd]), RunInfo(cmd)]
diff --git a/buck2/prelude/julia/julia_info.bzl b/buck2/prelude/julia/julia_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/julia/julia_info.bzl
@@ -0,0 +1,86 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",  # @unused Used as a type
+    "merge_shared_libraries",
+)
+
+JuliaToolchainInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "julia": provider_field(typing.Any, default = None),
+        "env": provider_field(typing.Any, default = None),
+        "cmd_processor": provider_field(typing.Any, default = None),
+    },
+)
+
+JllInfo = record(
+    name = field(str),
+    libs = field(dict),  # Julia name to label
+)
+
+JuliaLibrary = record(
+    uuid = str,
+    src_labels = typing.Any,
+    srcs = typing.Any,
+    project_toml = typing.Any,
+    label = field(Label),
+    jll = field([JllInfo, None]),
+)
+
+def project_load_src_label(lib):
+    return lib.src_labels
+
+def project_load_srcs(lib):
+    return lib.srcs
+
+JuliaLibraryTSet = transitive_set(
+    args_projections = {
+        "load_src_label": project_load_src_label,
+        "load_srcs": project_load_srcs,
+    },
+)
+
+# Information about a julia library and its dependencies.
+JuliaLibraryInfo = provider(
+    fields = {
+        "julia_tsets": provider_field(typing.Any, default = None),  # JuliaLibraryTSet
+        "shared_library_info": provider_field(typing.Any, default = None),  # SharedLibraryInfo
+    }
+)
+
+def create_julia_library_info(
+    actions: AnalysisActions,
+    label: Label,
+    uuid: str = "",
+    src_labels: typing.Any = [],
+    project_toml: typing.Any = None,
+    srcs: typing.Any = [],
+    deps: list[JuliaLibraryInfo] = [],
+    jll: [JllInfo, None] = None,
+    shlibs: list[SharedLibraryInfo] = [],
+) -> JuliaLibraryInfo:
+    julia_tsets = JuliaLibrary(
+        uuid = uuid,
+        label = label,
+        src_labels = src_labels,
+        srcs = srcs,
+        project_toml = project_toml,
+        jll = jll,
+    )
+
+    return JuliaLibraryInfo(
+        julia_tsets = actions.tset(JuliaLibraryTSet, value = julia_tsets, children = [dep.julia_tsets for dep in deps]),
+        shared_library_info = merge_shared_libraries(
+            actions,
+            None,
+            [dep.shared_library_info for dep in deps] + shlibs,
+        ),
+    )
diff --git a/buck2/prelude/julia/julia_library.bzl b/buck2/prelude/julia/julia_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/julia/julia_library.bzl
@@ -0,0 +1,125 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//linking:shared_libraries.bzl", "SharedLibraryInfo")
+load(":julia_info.bzl", "JllInfo", "JuliaLibraryInfo", "create_julia_library_info")
+
+def gather_dep_libraries(raw_deps: list[Dependency]):
+    """
+    Takes a list of raw dependencies, and partitions them into julia_library / shared library providers.
+    Fails if a dependency is not one of these.
+    """
+    clean_libs = []
+    for dep in raw_deps:
+        if JuliaLibraryInfo in dep:
+            clean_libs.append(dep[JuliaLibraryInfo])
+        else:
+            fail("Dependency {} is not a julia_library or julia_jll_library!".format(dep.label))
+    return clean_libs
+
+def strip_srcs_path(ctx: AnalysisContext) -> list[str]:
+    """Strip the src path to include just the module folder.
+
+    By default, the short path will list the path of the src file relative to
+    cwd. If the module is far away, then all the nested folders are also
+    included. For the symlink dir we create later, we want a directory of
+    containing just the modules themselves, since the Julia package manager
+    won't recursively traverse this directory for nested modules.
+
+    To do this, we'll just look at the current project.toml file, and deduce the
+    name of the module folder. Then we can strip all the other source locs.
+    """
+    toml_main = ctx.attrs.project_toml.short_path.split("/")[0:-2]
+    necessary_prefix = ""
+    toml_main_path = ""
+    for p in toml_main:
+        toml_main_path = toml_main_path + p + "/"
+
+    # If the toml file is in the current directory, then we need to account for
+    # that. Specifically, we have to tell the parser to look in the current
+    # directory, and we need to ensure the parser places the current module in
+    # its own folder (otherwise libs will clobber each other). The name of the
+    # folder doesn't matter, so long as it's unique. Using the rule name is a
+    # safe bet here, since each library rule name should be unique...
+    if toml_main_path == "":
+        toml_main_path = "./"
+        necessary_prefix = ctx.attrs.name + "/"
+
+    src_labels = [necessary_prefix + f.short_path.split(toml_main_path)[-1] for f in ctx.attrs.srcs]
+    src_labels += [necessary_prefix + ctx.attrs.project_toml.short_path.split(toml_main_path)[-1]]
+    return src_labels
+
+def julia_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    """Creates rule for julia libraries.
+
+    The library rule needs to do a few important things:
+
+    (1) Build a tree of all the source files (like we do with the binary rule).
+    (2) Append this tree's path to a list of paths that will later go inside the
+        JULIA_LOAD_PATH env variable.
+    (3) Traverse all the dependencies and build up the JULIA_LOAD_PATH from
+        their dependencies (note that Julia packages should form a DAG... but we
+        should still have a check to make sure we don't get caught in an infinite
+        loop).
+    (4) Properly link to any jll libraries that are dependencies.
+
+    So long as we fill the JULIA_LOAD_PATH with all the package paths, then
+    Julia's internal package manager will automatically detect a project.toml
+    file with those package dependencies etc. In other words, if the path is
+    complete, then the package manager should work "out of the box".
+    """
+    providers = [DefaultInfo()]
+
+    clean_libs = gather_dep_libraries(ctx.attrs.deps)
+
+    library_info = create_julia_library_info(
+        actions = ctx.actions,
+        label = ctx.label,
+        project_toml = ctx.attrs.project_toml,
+        src_labels = strip_srcs_path(ctx),
+        srcs = ctx.attrs.srcs + [ctx.attrs.project_toml],
+        deps = clean_libs,
+    )
+
+    providers.append(library_info)
+
+    return providers
+
+def julia_jll_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    """Creates rule for julia jll libraries.
+
+    jll libraries are wrappers for c++ libraries. Normally, these libraries are
+    packaged using BinaryBuilder.jl: https://docs.binarybuilder.org/stable/jll/
+
+    By creating a separate rule for jll libraries, we can leverage Julia's
+    internal package manager. Specifically, most packages that depend on C/C++
+    libraries implicitly place a dependency on the jll wrapper _instead_ of the
+    library itself. As such, we can preserve the entire pipeline _except_ for
+    the jll itself, which we have to custom wrap _anyway_!
+
+    Consequently, this rule should *only* depend on other C/C++ rules.
+    """
+    providers = [DefaultInfo()]
+
+    shlibs = [lib[SharedLibraryInfo] for lib in ctx.attrs.lib_mapping.values()]
+    jll_libs = {name: lib.label for name, lib in ctx.attrs.lib_mapping.items()}
+
+    library_info = create_julia_library_info(
+        actions = ctx.actions,
+        label = ctx.label,
+        uuid = ctx.attrs.uuid,
+        jll = JllInfo(
+            name = ctx.attrs.jll_name,
+            libs = jll_libs,
+        ),
+        shlibs = shlibs,
+    )
+
+    providers.append(library_info)
+
+    return providers
diff --git a/buck2/prelude/julia/julia_test.bzl b/buck2/prelude/julia/julia_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/julia/julia_test.bzl
@@ -0,0 +1,22 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+load(":julia_binary.bzl", "build_julia_command")
+
+def julia_test_impl(ctx: AnalysisContext) -> list[Provider]:
+    cmd, json_info_file = build_julia_command(ctx)
+    external_runner_test_info = ExternalRunnerTestInfo(
+        type = "julia",
+        command = [cmd],
+        contacts = ctx.attrs.contacts,
+        # FIXME: Consider setting to true
+        run_from_project_root = False,
+    )
+
+    return inject_test_run_info(ctx, external_runner_test_info) + [DefaultInfo(default_output = json_info_file)]
diff --git a/buck2/prelude/julia/julia_toolchain.bzl b/buck2/prelude/julia/julia_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/julia/julia_toolchain.bzl
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":julia_info.bzl", "JuliaToolchainInfo")
+
+def _toolchain(lang: str, providers: list[typing.Any]) -> Attr:
+    return attrs.default_only(attrs.toolchain_dep(default = "toolchains//:" + lang, providers = providers))
+
+def julia_toolchain():
+    return _toolchain("julia", [JuliaToolchainInfo])
diff --git a/buck2/prelude/julia/tools/BUCK b/buck2/prelude/julia/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/julia/tools/BUCK
@@ -0,0 +1,22 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "parse_julia_cmd",
+    main = "parse_julia_cmd.py",
+    visibility = ["PUBLIC"],
+)
+
+# Type checking target for Python tool scripts
+prelude.python_library(
+    name = "scripts-typing",
+    srcs = [
+        "parse_julia_cmd.py",
+    ],
+    typing = True,
+)
diff --git a/buck2/prelude/julia/tools/parse_julia_cmd.py b/buck2/prelude/julia/tools/parse_julia_cmd.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/julia/tools/parse_julia_cmd.py
@@ -0,0 +1,144 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+import os
+import pathlib
+import subprocess
+import sys
+import tempfile
+
+
+def clean_relative_paths(parent_path: str, rel_path: str) -> pathlib.Path:
+    """Removes the extra upper dir level from a relative path and properly joins."""
+    return os.path.join(parent_path, pathlib.Path(*pathlib.Path(rel_path).parts[1:]))
+
+
+class jll_artifact:
+    """Parses artifact info from json file and stores the relevant info."""
+
+    def __init__(self, artifact_entry, json_file_dir):
+        self.artifact_name = artifact_entry[0]
+        rel_path_of_binary = artifact_entry[2]
+        self.artifacts_path = os.path.join(
+            clean_relative_paths(json_file_dir, artifact_entry[1]), rel_path_of_binary
+        )
+
+    def form_artifact_dependency(self):
+        """Creates artifact dependency line that goes inside julia source file."""
+        return '{} = "{}"'.format(self.artifact_name, self.artifacts_path)
+
+
+class jll_library:
+    """Parses the provided json file and stores the relevant info."""
+
+    def __init__(self, json_entry, json_file_dir):
+        self.package_name = json_entry[0]
+        self.uuid = json_entry[1]
+        self.jll_artifacts = [jll_artifact(a, json_file_dir) for a in json_entry[2]]
+
+    def write_library(self, root_directory):
+        """Creates and populates the library sources and directories"""
+        self.package_dir = pathlib.Path(root_directory) / self.package_name
+        self.package_dir.mkdir(parents=True, exist_ok=True)
+        self._create_jll_src()
+        self._create_project_toml()
+
+    def _create_jll_src(self):
+        """Creates the library src.jl file."""
+        src_filename = self.package_name + ".jl"
+        src_path = self.package_dir / "src"
+        src_path.mkdir(parents=True, exist_ok=True)
+
+        exports = [a.artifact_name for a in self.jll_artifacts]
+        with open(src_path / src_filename, "w") as src_file:
+            src_file.write("module " + self.package_name + "\n")
+            src_file.write("export " + ", ".join(exports) + "\n")
+            for a in self.jll_artifacts:
+                src_file.write(a.form_artifact_dependency() + "\n")
+            src_file.write("end\n")
+
+    def _create_project_toml(self):
+        """Creates the library Project.toml file."""
+        with open(self.package_dir / "Project.toml", "w") as toml_file:
+            toml_file.write('name = "{}"\n'.format(self.package_name))
+            toml_file.write('uuid = "{}"\n'.format(self.uuid))
+            toml_file.close()
+
+
+def parse_jll_libs(json_data, json_file_dir, lib_dir):
+    """Pulls jll library data from json file and writes library files."""
+
+    libs = []
+    for entry in json_data:
+        # parse the jll itself into our data structure
+        jll_lib = jll_library(entry, json_file_dir)
+        # use that structure to "create" a new library in a temp directory
+        jll_lib.write_library(lib_dir)
+        # store for later if needed.
+        libs.append(jll_lib)
+
+    return libs
+
+
+def build_command(json_data, json_file_dir, lib_dir, depot_dir):
+    """Builds the run command and env from the supplied args."""
+
+    lib_path = clean_relative_paths(json_file_dir, json_data["lib_path"])
+
+    # Compose the environment variables to pass
+    my_env = os.environ.copy()
+    my_env["JULIA_LOAD_PATH"] = "{}:{}::".format(lib_path, lib_dir)
+    my_env["JULIA_DEPOT_PATH"] = "{}:{}::".format(lib_path, depot_dir)
+
+    # For now, we hard code the path of the shlibs relative to the json file.
+    my_env["LD_LIBRARY_PATH"] = "{}:{}".format(
+        os.path.join(lib_path, "../__shared_libs_symlink_tree__"),
+        my_env.setdefault("LD_LIBRARY_PATH", ""),
+    )
+
+    binary_path = clean_relative_paths(json_file_dir, json_data["julia_binary"])
+
+    main_file = clean_relative_paths(json_file_dir, json_data["main"])
+
+    # Compose main julia command
+    my_command = (
+        [binary_path] + json_data["julia_flags"] + [main_file] + json_data["julia_args"]
+    )
+
+    return my_command, my_env
+
+
+def main() -> int:
+    """Sets up the julia environment with appropriate library aliases."""
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--json-path", default="")
+    args = parser.parse_args()
+
+    # pull everything from json file
+    json_file = args.json_path
+    json_file_dir = os.path.split(json_file)[0]
+    with open(json_file) as f:
+        json_data = json.load(f)
+
+    # create a temporary directory to store artifacts. Note that this temporary
+    # directory will be deleted when the process exits.
+    with tempfile.TemporaryDirectory() as lib_dir:
+        with tempfile.TemporaryDirectory() as depot_dir:
+            parse_jll_libs(json_data["jll_mapping"], json_file_dir, lib_dir)
+            my_command, my_env = build_command(
+                json_data, json_file_dir, lib_dir, depot_dir
+            )
+            code = subprocess.call(my_command, env=my_env)
+
+    sys.exit(code)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/jvm/cd_jar_creator_util.bzl b/buck2/prelude/jvm/cd_jar_creator_util.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/jvm/cd_jar_creator_util.bzl
@@ -0,0 +1,714 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//java:java_providers.bzl",
+    "JavaClasspathEntry",
+    "JavaCompilingDepsTSet",  # @unused Used as type
+    "JavaLibraryInfo",
+    "create_abi",
+)
+load("@prelude//java:java_toolchain.bzl", "AbiGenerationMode", "JavaToolchainInfo", "unsafe_memory_access_jvm_args")
+load("@prelude//java/plugins:java_annotation_processor.bzl", "AnnotationProcessorProperties")  # @unused Used as type
+load(
+    "@prelude//java/plugins:java_plugin.bzl",
+    "PluginParams",  # @unused Used as type
+)
+load("@prelude//java/utils:java_utils.bzl", "declare_prefixed_name")
+load("@prelude//utils:expect.bzl", "expect")
+
+def declare_prefixed_output(actions: AnalysisActions, prefix: [str, None], output: str, has_content_based_path: bool, dir: bool = False) -> Artifact:
+    return actions.declare_output(declare_prefixed_name(output, prefix), dir = dir, has_content_based_path = has_content_based_path)
+
+# The library and the toolchain can both set a specific abi generation
+# mode. The toolchain's setting is effectively the "highest" form of abi
+# that the toolchain supports and then the same for the target and we will choose
+# the "highest" that both support.
+def _resolve_abi_generation_mode(abi_generation_mode: [AbiGenerationMode, None], java_toolchain: JavaToolchainInfo) -> AbiGenerationMode:
+    if abi_generation_mode == None:
+        return java_toolchain.abi_generation_mode
+    for mode in [AbiGenerationMode("none"), AbiGenerationMode("class"), AbiGenerationMode("source"), AbiGenerationMode("source_only")]:
+        if mode in (java_toolchain.abi_generation_mode, abi_generation_mode):
+            return mode
+    fail("resolving abi generation mode failed. had `{}` and `{}`".format(java_toolchain.abi_generation_mode, abi_generation_mode))
+
+def get_abi_generation_mode(
+    abi_generation_mode: [AbiGenerationMode, None],
+    java_toolchain: JavaToolchainInfo,
+    srcs: list[Artifact],
+    annotation_processor_properties: AnnotationProcessorProperties,
+) -> AbiGenerationMode:
+    resolved_mode = AbiGenerationMode("none") if not srcs else _resolve_abi_generation_mode(abi_generation_mode, java_toolchain)
+    if resolved_mode == AbiGenerationMode("source_only"):
+
+        def plugins_support_source_only_abi():
+            for ap in annotation_processor_properties.annotation_processors:
+                if ap.affects_abi and not ap.supports_source_only_abi:
+                    return False
+            return True
+
+        if not plugins_support_source_only_abi():
+            resolved_mode = AbiGenerationMode("source")
+    return resolved_mode
+
+# We need to construct a complex protobuf message. We do it by constructing
+# a bunch of nested structs and then use write_json to get a json-encoded
+# protobuf message.
+#
+# The definition is in xplat/toolchains/android/sdk/src/com/facebook/buck/cd/resources/proto/javacd.proto
+# and xplat/toolchains/android/sdk/src/com/facebook/buck/cd/resources/proto/kotlincd.proto and is, sadly,
+# poorly documented.
+
+# Our protobuf format mostly encodes paths in RelPath/AbsPath structs with a single "path" field.
+# Note that we don't actually use abspath and instead enable JAVACD_ABSOLUTE_PATHS_ARE_RELATIVE_TO_CWD
+TargetType = enum("library", "source_abi", "source_only_abi")
+BuildMode = enum("LIBRARY", "ABI")
+
+def encode_abi_generation_mode(mode: AbiGenerationMode) -> str:
+    return {
+        AbiGenerationMode("none"): "NONE",
+        AbiGenerationMode("class"): "CLASS",
+        AbiGenerationMode("source"): "SOURCE",
+        AbiGenerationMode("source_only"): "SOURCE_ONLY",
+    }[mode]
+
+def encode_target_type(target_type: TargetType) -> str:
+    if target_type == TargetType("library"):
+        return "LIBRARY"
+    if target_type == TargetType("source_abi"):
+        return "SOURCE_ABI"
+    if target_type == TargetType("source_only_abi"):
+        return "SOURCE_ONLY_ABI"
+    fail()
+
+OutputPaths = record(
+    jar = Artifact,
+    annotations = Artifact | None,
+)
+
+def qualified_name_with_subtarget(label: Label) -> str:
+    if label.sub_target:
+        return "{}:{}[{}]".format(label.path, label.name, label.sub_target[0])
+    return "{}:{}".format(label.path, label.name)
+
+# Converted to str so that we get the right result when written as json.
+def base_qualified_name(label: Label) -> str:
+    return "{}:{}".format(label.path, label.name)
+
+def get_qualified_name(label: Label, target_type: TargetType) -> str:
+    # These should match the names for subtargets in java_library.bzl
+    return {
+        TargetType("library"): base_qualified_name(label),
+        TargetType("source_abi"): base_qualified_name(label) + "[source-abi]",
+        TargetType("source_only_abi"): base_qualified_name(label) + "[source-only-abi]",
+    }[target_type]
+
+def define_output_paths(
+    actions: AnalysisActions,
+    prefix: [str, None],
+    label: Label,
+    uses_content_based_paths: bool,
+    declare_annotations: bool = True,
+) -> OutputPaths:
+    # currently, javacd requires that at least some outputs are in the root
+    # output dir. so we put all of them there. If javacd is updated we
+    # could consolidate some of these into one subdir.
+    return OutputPaths(
+        jar = declare_prefixed_output(actions, prefix, "jar/{}.jar".format(label.name), uses_content_based_paths),
+        annotations = declare_prefixed_output(actions, prefix, "__gen__", uses_content_based_paths, dir = True) if declare_annotations else None,
+    )
+
+def encode_output_paths(label: Label, paths: OutputPaths, target_type: TargetType) -> struct:
+    paths = struct(
+        outputJarDirPath = cmd_args(paths.jar.as_output(), parent = 1),
+        annotationPath = paths.annotations.as_output() if paths.annotations else None,
+        outputJarPath = paths.jar.as_output(),
+    )
+
+    return struct(
+        libraryPaths = paths if target_type == TargetType("library") else None,
+        sourceAbiPaths = paths if target_type == TargetType("source_abi") else None,
+        sourceOnlyAbiPaths = paths if target_type == TargetType("source_only_abi") else None,
+        libraryTargetFullyQualifiedName = base_qualified_name(label),
+    )
+
+def encode_jar_params(remove_classes: list[str], output_paths: OutputPaths, manifest_file: Artifact | None) -> struct:
+    return struct(
+        jarPath = output_paths.jar.as_output(),
+        removeEntryPredicate = struct(
+            patterns = remove_classes,
+        ),
+        manifestFile = manifest_file,
+    )
+
+def command_abi_generation_mode(target_type: TargetType, abi_generation_mode: [AbiGenerationMode, None]) -> [AbiGenerationMode, None]:
+    # We want the library target to have the real generation mode, but the source one's just use their own.
+    # The generation mode will be used elsewhere to setup the target's classpath entry to use the correct abi.
+    if target_type == TargetType("source_abi"):
+        return AbiGenerationMode("source")
+    if target_type == TargetType("source_only_abi"):
+        return AbiGenerationMode("source_only")
+    return abi_generation_mode
+
+def _source_only_abi_jars(entries: list[JavaClasspathEntry]):
+    return [entry.abi for entry in entries]
+
+def _source_only_abi_and_dir(entries: list[JavaClasspathEntry]):
+    return [path for entry in entries for path in (entry.abi, entry.abi_as_dir or "")]
+
+SourceOnlyAbiCompilingDepsTSet = transitive_set(
+    args_projections = {
+        "source_only_abi_and_dir": _source_only_abi_and_dir,
+        "source_only_abi_jars": _source_only_abi_jars,
+    },
+)
+
+def get_source_only_abi_compiling_deps(
+    actions: AnalysisActions,
+    compiling_deps_tset: [JavaCompilingDepsTSet, None],
+    source_only_abi_deps: list[Dependency],
+) -> JavaCompilingDepsTSet | SourceOnlyAbiCompilingDepsTSet:
+    if not source_only_abi_deps and compiling_deps_tset != None:
+        return compiling_deps_tset
+    source_only_abi_compiling_deps = []
+    if compiling_deps_tset:
+        source_only_abi_deps_filter = {}
+        for d in source_only_abi_deps:
+            info = d.get(JavaLibraryInfo)
+            if not info:
+                fail("source_only_abi_deps must produce a JavaLibraryInfo but '{}' does not, please remove it".format(d.label))
+            if info.library_output:
+                source_only_abi_deps_filter[info.library_output.abi] = True
+
+        def filter_compiling_deps(dep):
+            return dep.abi in source_only_abi_deps_filter or dep.required_for_source_only_abi
+
+        source_only_abi_compiling_deps = [compiling_dep for compiling_dep in list(compiling_deps_tset.traverse()) if filter_compiling_deps(compiling_dep)]
+    return actions.tset(SourceOnlyAbiCompilingDepsTSet, value = source_only_abi_compiling_deps)
+
+# buildifier: disable=unused-variable
+def encode_ap_params(annotation_processor_properties: AnnotationProcessorProperties, target_type: TargetType) -> [struct, None]:
+    # buck1 oddly only inspects annotation processors, not plugins for
+    # abi/source-only abi related things, even though the plugin rules
+    # support the flags. we apply it to both.
+    encoded_ap_params = None
+    if annotation_processor_properties.annotation_processors:
+        encoded_ap_params = struct(
+            parameters = annotation_processor_properties.annotation_processor_params,
+            pluginProperties = [],
+        )
+        for ap in annotation_processor_properties.annotation_processors:
+            # We should also filter out non-abi-affecting APs for source-abi, but buck1 doesn't and so we have lots that depend on not filtering them there.
+            if target_type == TargetType("source_only_abi") and not ap.affects_abi:
+                continue
+            if ap.deps or ap.processors:
+                encoded_ap_params.pluginProperties.append(
+                    struct(
+                        canReuseClassLoader = not ap.isolate_class_loader,
+                        doesNotAffectAbi = not ap.affects_abi,
+                        supportsAbiGenerationFromSource = ap.supports_source_only_abi,
+                        runsOnJavaOnly = ap.runs_on_java_only,
+                        processorNames = ap.processors,
+                        classpath = ap.deps.project_as_json("javacd_json") if ap.deps else [],
+                    ),
+                )
+    return encoded_ap_params
+
+def encode_plugin_params(plugin_params: [PluginParams, None]) -> [struct, None]:
+    encoded_plugin_params = None
+    if plugin_params:
+        encoded_plugin_params = struct(
+            pluginProperties = [encode_plugin_properties(processor, arguments, plugin_params) for processor, arguments in plugin_params.processors],
+        )
+    return encoded_plugin_params
+
+def encode_plugin_properties(processor: str, arguments: cmd_args, plugin_params: PluginParams) -> struct:
+    return struct(
+        canReuseClassLoader = False,
+        doesNotAffectAbi = False,
+        supportsAbiGenerationFromSource = False,
+        runsOnJavaOnly = False,
+        processorNames = [processor],
+        classpath = plugin_params.deps.project_as_json("javacd_json") if plugin_params.deps else [],
+        pathParams = {},
+        arguments = arguments,
+    )
+
+def encode_base_jar_command(
+    target_type: TargetType,
+    output_paths: OutputPaths,
+    remove_classes: list[str],
+    label: Label,
+    compiling_deps_tset: [JavaCompilingDepsTSet, None],
+    classpath_jars_tag: ArtifactTag,
+    bootclasspath_entries: list[Artifact],
+    system_image: Artifact | None,
+    source_level: int,
+    target_level: int,
+    abi_generation_mode: [AbiGenerationMode, None],
+    srcs: list[Artifact],
+    resources_map: dict[str, Artifact],
+    annotation_processor_properties: AnnotationProcessorProperties,
+    plugin_params: [PluginParams, None],
+    manifest_file: Artifact | None,
+    extra_arguments: cmd_args,
+    source_only_abi_compiling_deps: JavaCompilingDepsTSet | SourceOnlyAbiCompilingDepsTSet | None,
+    track_class_usage: bool,
+    provide_classpath_snapshot: bool = False,
+    use_abi_dirs: bool = False,
+    incremental_metadata_ignored_inputs_tag: ArtifactTag | None = None,
+) -> struct:
+    jar_parameters = encode_jar_params(remove_classes, output_paths, manifest_file)
+    qualified_name = get_qualified_name(label, target_type)
+    if target_type == TargetType("source_only_abi"):
+        expect(source_only_abi_compiling_deps != None)
+        # A list-valued JSON projection would introduce an extra array level.
+        compiling_classpath = cmd_args(source_only_abi_compiling_deps.project_as_args("source_only_abi_and_dir" if use_abi_dirs else "source_only_abi_jars"))
+        compiling_classpath_snapshot = []
+    else:
+        expect(source_only_abi_compiling_deps == None)
+
+        if use_abi_dirs:
+            compiling_classpath = cmd_args(compiling_deps_tset.project_as_args("abi_and_dir", ordering = "topological")) if compiling_deps_tset else []
+        else:
+            compiling_classpath = compiling_deps_tset.project_as_json("javacd_json", ordering = "topological") if compiling_deps_tset else []
+        # The snapshot inputs are tagged for association with dep_files, but they are not marked as used,
+        # as they serve the incremental compiler's internal needs,
+        # which are utilized after the build system has determined whether a rebuild is necessary.
+        compiling_classpath_snapshot = classpath_jars_tag.tag_artifacts(
+            compiling_deps_tset.project_as_json("abi_snapshot_json", ordering = "topological") if provide_classpath_snapshot and compiling_deps_tset else []
+        )
+
+    compiling_classpath = classpath_jars_tag.tag_artifacts(compiling_classpath)
+    if use_abi_dirs and incremental_metadata_ignored_inputs_tag:
+        compiling_classpath = incremental_metadata_ignored_inputs_tag.tag_artifacts(compiling_classpath)
+
+    build_target_value = struct(
+        fullyQualifiedName = qualified_name,
+        type = encode_target_type(target_type),
+    )
+    resolved_java_options = struct(
+        bootclasspathList = bootclasspath_entries,
+        languageLevelOptions = struct(
+            sourceLevel = source_level,
+            targetLevel = target_level,
+        ),
+        javaAnnotationProcessorParams = encode_ap_params(annotation_processor_properties, target_type),
+        standardJavacPluginParams = encode_plugin_params(plugin_params),
+        extraArguments = extra_arguments,
+        systemImage = system_image,
+    )
+
+    return struct(
+        outputPathsValue = encode_output_paths(label, output_paths, target_type),
+        compileTimeClasspathPaths = [] if use_abi_dirs else compiling_classpath,
+        compileTimeClasspathAbiAndDirPaths = compiling_classpath if use_abi_dirs else [],
+        compileTimeClasspathSnapshotPaths = compiling_classpath_snapshot,
+        javaSrcs = srcs,
+        abiGenerationMode = encode_abi_generation_mode(command_abi_generation_mode(target_type, abi_generation_mode)),
+        trackClassUsage = track_class_usage,
+        buildTargetValue = build_target_value,
+        resourcesMap = [
+            {
+                "key": v,
+                "value": k,
+            }
+            for (k, v) in resources_map.items()
+        ],
+        resolvedJavacOptions = resolved_java_options,
+        jarParameters = jar_parameters,
+        annotationsPath = output_paths.annotations.as_output() if output_paths.annotations else None,
+    )
+
+def setup_dep_files(
+    actions: AnalysisActions,
+    actions_identifier: [str, None],
+    post_build_params: dict,
+    classpath_jars_tag: ArtifactTag,
+    used_classes_json_outputs: list[cmd_args],
+    used_jars_json_output: Artifact | None,
+    uses_content_based_paths: bool,
+):
+    dep_file = declare_prefixed_output(actions, actions_identifier, "jar/dep-file.txt", uses_content_based_paths)
+
+    post_build_params["usedClasses"] = used_classes_json_outputs
+    post_build_params["depFile"] = classpath_jars_tag.tag_artifacts(dep_file.as_output())
+    if used_jars_json_output != None:
+        post_build_params["usedJarsFile"] = used_jars_json_output.as_output()
+
+FORCE_PERSISTENT_WORKERS = read_root_config("build", "require_persistent_workers", "false").lower() == "true"
+
+def prepare_cd_exe(
+    qualified_name: str,
+    java: RunInfo,
+    class_loader_bootstrapper: Artifact,
+    compiler: Artifact,
+    main_class: str,
+    worker: WorkerInfo | None,
+    remote_worker: WorkerInfo | None,
+    target_specified_debug_port: [int, None],
+    toolchain_specified_debug_port: [int, None],
+    toolchain_specified_debug_target: [Label, None],
+    extra_jvm_args: list[str],
+    extra_jvm_args_target: list[Label],
+    java_runtime_version: [int, None],
+) -> tuple:
+    local_only = False
+    jvm_args = ["-XX:-MaxFDLimit"] + unsafe_memory_access_jvm_args(java_runtime_version)
+
+    # The variables 'extra_jvm_args' and 'extra_jvm_args_target' are generally used, but they are primarily designed for profiling use-cases.
+    # The following section is configured with the profiling use-case in mind.
+    if extra_jvm_args_target:
+        if len(extra_jvm_args_target) == 1:
+            # If there's only one target to profile, we want to isolate its compilation.
+            # This target should be built in its own action, allowing the worker (if available) to handle the remaining targets.
+            if qualified_name == qualified_name_with_subtarget(extra_jvm_args_target[0]):
+                jvm_args = jvm_args + extra_jvm_args
+                local_only = True  # This flag ensures the target is not run on the worker.
+        else:
+            # If there are multiple targets to profile, they should be built on the worker to generate a single profiling data set.
+            # The remaining targets should be built individually, either locally or on the Remote Execution (RE).
+            local_only = True  # By default, targets are not run on the worker.
+            for target in extra_jvm_args_target:
+                # If the current target matches the qualified name with subtarget, it is selected for profiling.
+                if qualified_name == qualified_name_with_subtarget(target):
+                    jvm_args = jvm_args + extra_jvm_args
+                    local_only = False  # This flag allows the target to run on the worker.
+                    break
+    else:
+        # If no specific target is provided, the extra JVM arguments are added to all targets that run on worker, local machine or RE.
+        jvm_args = jvm_args + extra_jvm_args
+
+    # Allow JVM compiler daemon to access internal jdk.compiler APIs
+    jvm_args += [
+        "--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
+        "--add-exports=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED",
+        "--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED",
+        "--add-exports=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED",
+        "--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED",
+        "--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED",
+        "--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED",
+        "--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED",
+        "--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED",
+        "--add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",
+        "--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
+        "--add-opens=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED",
+        "--add-opens=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED",
+        "--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
+    ]
+
+    if target_specified_debug_port:
+        debug_port = target_specified_debug_port
+    elif toolchain_specified_debug_port and qualified_name == qualified_name_with_subtarget(toolchain_specified_debug_target):
+        debug_port = toolchain_specified_debug_port
+    else:
+        debug_port = None
+
+    if debug_port:
+        # Do not use a worker when debugging is enabled
+        local_only = True
+        jvm_args.extend(["-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address={}".format(debug_port)])
+
+    non_worker_args = cmd_args([java, jvm_args, "-cp", compiler, "-jar", class_loader_bootstrapper, main_class])
+
+    if local_only or not worker:
+        # buck doesn't support the case where remote_worker is provided but worker is not.
+        if not worker:
+            expect(remote_worker == None, "When worker is not provided, remote_worker must be None.")
+        return RunInfo(args = non_worker_args), local_only
+    else:
+        worker_run_info = WorkerRunInfo(
+            # Specifies the command to compile using a non-worker process, on RE or if workers are disabled
+            # RE workers need exe to run the action, but RE persistent workers need it to be empty
+            # we should make this less confusing, but it is how things currently work.
+            exe = [] if remote_worker else non_worker_args,
+            # Specifies the command to initialize a new worker process.
+            # This is used for local execution if `build.use_persistent_workers=True`
+            worker = worker,
+            remote_worker = remote_worker,
+        )
+        return worker_run_info, FORCE_PERSISTENT_WORKERS
+
+FinalJarOutput = record(
+    final_jar = Artifact,
+    # The same as final_jar unless there is a jar_postprocessor.
+    preprocessed_jar = Artifact,
+)
+
+# If there's additional compiled srcs, we need to merge them in and if the
+# caller specified an output artifact we need to make sure the jar is in that
+# location.
+def prepare_final_jar(
+    actions: AnalysisActions,
+    actions_identifier: [str, None],
+    output: Artifact | None,
+    output_paths: OutputPaths,
+    additional_compiled_srcs: Artifact | None,
+    jar_builder: RunInfo,
+    jar_postprocessor: [RunInfo, None],
+    jar_postprocessor_runner: RunInfo | None,
+    zip_scrubber: RunInfo,
+    uses_content_based_paths: bool,
+    postprocessor_merged_into_compile_action: bool = False,
+) -> FinalJarOutput:
+    def make_output(jar: Artifact) -> FinalJarOutput:
+        if jar_postprocessor and not postprocessor_merged_into_compile_action:
+            expect(jar_postprocessor_runner != None, "Must provide a jar_postprocessor_runner if jar_postprocessor is provided!")
+            postprocessed_jar = postprocess_jar(actions, zip_scrubber, jar_postprocessor, jar_postprocessor_runner, jar, actions_identifier)
+            return FinalJarOutput(final_jar = postprocessed_jar, preprocessed_jar = jar)
+        else:
+            return FinalJarOutput(final_jar = jar, preprocessed_jar = jar)
+
+    if not additional_compiled_srcs:
+        output_jar = output_paths.jar
+        if output:
+            actions.copy_file(output.as_output(), output_paths.jar)
+            output_jar = output
+
+        return make_output(output_jar)
+
+    merged_jar = output
+    if not merged_jar:
+        merged_jar = declare_prefixed_output(actions, actions_identifier, "merged.jar", uses_content_based_paths)
+    files_to_merge = [output_paths.jar, additional_compiled_srcs]
+    files_to_merge_file = actions.write(declare_prefixed_name("files_to_merge.txt", actions_identifier), files_to_merge, has_content_based_path = False)
+    actions.run(
+        cmd_args(
+            [
+                jar_builder,
+                "--output",
+                merged_jar.as_output(),
+                "--entries-to-jar",
+                files_to_merge_file,
+            ],
+            hidden = files_to_merge,
+        ),
+        category = "merge_additional_srcs",
+        identifier = actions_identifier,
+    )
+
+    return make_output(merged_jar)
+
+def encode_command(
+    label: Label,
+    srcs: list[Artifact],
+    remove_classes: list[str],
+    annotation_processor_properties: AnnotationProcessorProperties,
+    plugin_params: [PluginParams, None],
+    manifest_file: Artifact | None,
+    source_level: int,
+    target_level: int,
+    compiling_deps_tset: [JavaCompilingDepsTSet, None],
+    bootclasspath_entries: list[Artifact],
+    system_image: Artifact | None,
+    abi_generation_mode: AbiGenerationMode,
+    resources_map: dict[str, Artifact],
+    extra_arguments: cmd_args,
+    kotlin_extra_params: [struct, None],
+    provide_classpath_snapshot: bool,
+    build_mode: BuildMode,
+    target_type: TargetType,
+    output_paths: OutputPaths,
+    classpath_jars_tag: ArtifactTag,
+    source_only_abi_compiling_deps: JavaCompilingDepsTSet | SourceOnlyAbiCompilingDepsTSet | None,
+    track_class_usage: bool,
+    use_abi_dirs: bool = False,
+    incremental_metadata_ignored_inputs_tag: ArtifactTag | None = None,
+) -> struct:
+    base_jar_command = encode_base_jar_command(
+        target_type,
+        output_paths,
+        remove_classes,
+        label,
+        compiling_deps_tset,
+        classpath_jars_tag,
+        bootclasspath_entries,
+        system_image,
+        source_level,
+        target_level,
+        abi_generation_mode,
+        srcs,
+        resources_map,
+        annotation_processor_properties = annotation_processor_properties,
+        plugin_params = plugin_params,
+        manifest_file = manifest_file,
+        extra_arguments = cmd_args(extra_arguments),
+        source_only_abi_compiling_deps = source_only_abi_compiling_deps,
+        track_class_usage = track_class_usage,
+        provide_classpath_snapshot = provide_classpath_snapshot,
+        use_abi_dirs = use_abi_dirs,
+        incremental_metadata_ignored_inputs_tag = incremental_metadata_ignored_inputs_tag,
+    )
+
+    if kotlin_extra_params:
+        return struct(
+            buildMode = build_mode,
+            baseJarCommand = base_jar_command,
+            kotlinExtraParams = kotlin_extra_params,
+        )
+    else:
+        return struct(
+            buildMode = build_mode,
+            baseJarCommand = base_jar_command,
+        )
+
+# buildifier: disable=unused-variable
+def generate_abi_jars(
+    actions: AnalysisActions,
+    actions_identifier: [str, None],
+    label: Label,
+    abi_generation_mode: [AbiGenerationMode, None],
+    additional_compiled_srcs: Artifact | None,
+    is_building_android_binary: bool,
+    class_abi_generator: Dependency,
+    final_jar: Artifact,
+    compiling_deps_tset: [JavaCompilingDepsTSet, None],
+    source_only_abi_deps: list[Dependency],
+    class_abi_jar: Artifact | None,
+    class_abi_output_dir: Artifact | None,
+    track_class_usage: bool,
+    encode_abi_command: typing.Callable,
+    define_action: typing.Callable,
+    uses_content_based_paths: bool,
+    kotlin_extra_params_builder: typing.Callable | None = None,
+    source_only_abi_compiling_deps: JavaCompilingDepsTSet | SourceOnlyAbiCompilingDepsTSet | None = None,
+) -> tuple:
+    class_abi = None
+    source_abi = None
+    source_only_abi = None
+    classpath_abi = None
+    classpath_abi_dir = None
+
+    # If we are merging additional compiled_srcs, we can't produce source/source-only abis. Otherwise we
+    # always generation the source/source-only abis and setup the classpath entry to use the appropriate
+    # abi. This allows us to build/inspect/debug source/source-only abi for rules that don't have it enabled.
+    if not additional_compiled_srcs:
+        if abi_generation_mode == AbiGenerationMode("source") or not is_building_android_binary:
+            source_abi_identifier = declare_prefixed_name("source_abi", actions_identifier)
+            source_abi_target_type = TargetType("source_abi")
+            source_abi_qualified_name = get_qualified_name(label, source_abi_target_type)
+            source_abi_output_paths = define_output_paths(actions, source_abi_identifier, label, uses_content_based_paths, declare_annotations = False)
+            source_abi_classpath_jars_tag = actions.artifact_tag()
+            source_abi_dir = declare_prefixed_output(actions, source_abi_identifier, "source-abi-dir", uses_content_based_paths, dir = True)
+
+            if kotlin_extra_params_builder:
+                source_abi_kotlin_extra_params = kotlin_extra_params_builder()
+                source_abi_encode_abi_command = encode_abi_command(kotlin_extra_params = source_abi_kotlin_extra_params, provide_classpath_snapshot = False)
+            else:
+                source_abi_encode_abi_command = encode_abi_command
+
+            source_abi_command = source_abi_encode_abi_command(
+                build_mode = BuildMode("ABI"),
+                target_type = source_abi_target_type,
+                output_paths = source_abi_output_paths,
+                classpath_jars_tag = source_abi_classpath_jars_tag,
+                source_only_abi_compiling_deps = None,
+                track_class_usage = track_class_usage,
+            )
+            define_action(
+                "source_abi_",
+                source_abi_identifier,
+                source_abi_command,
+                source_abi_qualified_name,
+                source_abi_output_paths,
+                source_abi_classpath_jars_tag,
+                source_abi_dir,
+                source_abi_target_type,
+            )
+            source_abi = source_abi_output_paths.jar
+
+            if abi_generation_mode == AbiGenerationMode("source"):
+                classpath_abi = source_abi
+                classpath_abi_dir = source_abi_dir
+
+        if abi_generation_mode == AbiGenerationMode("source_only") or not is_building_android_binary:
+            source_only_abi_identifier = declare_prefixed_name("source_only_abi", actions_identifier)
+            source_only_abi_target_type = TargetType("source_only_abi")
+            source_only_abi_qualified_name = get_qualified_name(label, source_only_abi_target_type)
+            source_only_abi_output_paths = define_output_paths(actions, source_only_abi_identifier, label, uses_content_based_paths, declare_annotations = False)
+            source_only_abi_classpath_jars_tag = actions.artifact_tag()
+            source_only_abi_dir = declare_prefixed_output(actions, source_only_abi_identifier, "dir", uses_content_based_paths, dir = True)
+            if source_only_abi_compiling_deps == None:
+                source_only_abi_compiling_deps = get_source_only_abi_compiling_deps(actions, compiling_deps_tset, source_only_abi_deps)
+
+            if kotlin_extra_params_builder:
+                source_only_abi_kotlin_extra_params = kotlin_extra_params_builder()
+                source_only_abi_encode_abi_command = encode_abi_command(
+                    kotlin_extra_params = source_only_abi_kotlin_extra_params, provide_classpath_snapshot = False
+                )
+            else:
+                source_only_abi_encode_abi_command = encode_abi_command
+
+            source_only_abi_command = source_only_abi_encode_abi_command(
+                build_mode = BuildMode("ABI"),
+                target_type = source_only_abi_target_type,
+                output_paths = source_only_abi_output_paths,
+                classpath_jars_tag = source_only_abi_classpath_jars_tag,
+                source_only_abi_compiling_deps = source_only_abi_compiling_deps,
+                track_class_usage = track_class_usage,
+            )
+            define_action(
+                "source_only_abi_",
+                source_only_abi_identifier,
+                source_only_abi_command,
+                source_only_abi_qualified_name,
+                source_only_abi_output_paths,
+                source_only_abi_classpath_jars_tag,
+                source_only_abi_dir,
+                source_only_abi_target_type,
+            )
+            source_only_abi = source_only_abi_output_paths.jar
+
+            if abi_generation_mode == AbiGenerationMode("source_only"):
+                classpath_abi = source_only_abi
+                classpath_abi_dir = source_only_abi_dir
+
+        if abi_generation_mode == AbiGenerationMode("none"):
+            classpath_abi = final_jar
+
+    if classpath_abi == None or not is_building_android_binary:
+        class_abi = class_abi_jar or create_abi(actions, class_abi_generator, final_jar)
+        if classpath_abi == None:
+            classpath_abi = class_abi
+            if class_abi_output_dir:
+                classpath_abi_dir = class_abi_output_dir
+
+    return class_abi, source_abi, source_only_abi, classpath_abi, classpath_abi_dir
+
+def postprocess_jar(
+    actions: AnalysisActions,
+    zip_scrubber: RunInfo,
+    jar_postprocessor: RunInfo,
+    jar_postprocessor_runner: RunInfo,
+    original_jar: Artifact,
+    actions_identifier: [str, None],
+) -> Artifact:
+    jar_path = original_jar.short_path
+    postprocessed_output = actions.declare_output("postprocessed_{}".format(jar_path), has_content_based_path = True)
+
+    postprocess_jar_cmd = cmd_args(
+        jar_postprocessor_runner,
+        "--postprocessor_cmd",
+        cmd_args(
+            [
+                jar_postprocessor,
+                original_jar,
+                postprocessed_output.as_output(),
+            ],
+            delimiter = " ",
+        ),
+        "--zip_scrubber",
+        cmd_args(zip_scrubber, delimiter = " "),
+        "--output",
+        postprocessed_output.as_output(),
+    )
+
+    identifier = actions_identifier if actions_identifier else ""
+    actions.run(postprocess_jar_cmd, category = "postprocessed{}".format(identifier))
+
+    return postprocessed_output
diff --git a/buck2/prelude/jvm/nullsafe.bzl b/buck2/prelude/jvm/nullsafe.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/jvm/nullsafe.bzl
@@ -0,0 +1,59 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo")
+load("@prelude//java/plugins:java_plugin.bzl", "PluginParams", "create_plugin_params")
+
+NullsafeInfo = record(
+    output = field(Artifact),
+    plugin_params = field(PluginParams),
+    extra_arguments = field(cmd_args),
+)
+
+def get_nullsafe_info(ctx: AnalysisContext) -> [NullsafeInfo, None]:
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    extra_arguments = cmd_args(ctx.attrs.extra_arguments)
+
+    nullsafe_plugin = java_toolchain.nullsafe
+    nullsafe_signatures = java_toolchain.nullsafe_signatures
+    nullsafe_extra_args = java_toolchain.nullsafe_extra_args
+
+    if nullsafe_plugin:
+        nullsafe_output = ctx.actions.declare_output("reports", dir = True, has_content_based_path = True)
+
+        plugin_args = cmd_args()
+        plugin_args.add("nullsafe.reportToJava=false")
+        plugin_args.add(
+            cmd_args(
+                nullsafe_output.as_output(),
+                format = "nullsafe.writeJsonReportToDir={}",
+            )
+        )
+        if nullsafe_signatures:
+            plugin_args.add(
+                cmd_args(
+                    nullsafe_signatures,
+                    format = "nullsafe.signatures={}",
+                )
+            )
+
+        if nullsafe_extra_args:
+            plugin_args.add(nullsafe_extra_args)
+
+        nullsafe_plugin_params = create_plugin_params(ctx, [(nullsafe_plugin, plugin_args)])
+
+        # -XDcompilePolicy=simple is a javac flag, not a plugin option
+        extra_arguments.add("-XDcompilePolicy=simple")
+
+        return NullsafeInfo(
+            output = nullsafe_output,
+            plugin_params = nullsafe_plugin_params,
+            extra_arguments = extra_arguments,
+        )
+
+    return None
diff --git a/buck2/prelude/kotlin/kotlin.bzl b/buck2/prelude/kotlin/kotlin.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/kotlin.bzl
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":kotlin_library.bzl", "kotlin_library_impl")
+load(":kotlin_test.bzl", "kotlin_test_impl")
+
+implemented_rules = {
+    "kotlin_library": kotlin_library_impl,
+    "kotlin_test": kotlin_test_impl,
+}
diff --git a/buck2/prelude/kotlin/kotlin_library.bzl b/buck2/prelude/kotlin/kotlin_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/kotlin_library.bzl
@@ -0,0 +1,759 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:attrs_validators.bzl", "get_attrs_validation_specs")
+load("@prelude//:validation_deps.bzl", "get_validation_deps_outputs")
+load("@prelude//android:android_providers.bzl", "merge_android_packageable_info")
+load(
+    "@prelude//java:java_library.bzl",
+    "build_java_library",
+    "jvm_target_stats",
+    "split_on_archives_and_plain_files",
+)
+load(
+    "@prelude//java:java_providers.bzl",
+    "JavaClasspathEntry",
+    "JavaCompilingDepsTSet",  # @unused Used as a type
+    "JavaLibraryInfo",
+    "JavaPackagingDepTSet",
+    "JavaPackagingInfo",
+    "JavaProviders",
+    "create_java_library_providers",
+    "create_native_providers",
+    "get_compiling_deps_tset",
+    "to_list",
+)
+load(
+    "@prelude//java:java_toolchain.bzl",
+    "AbiGenerationMode",
+    "JavaToolchainInfo",
+)
+load(
+    "@prelude//java/plugins:java_annotation_processor.bzl",
+    "AnnotationProcessorProperties",
+    "create_annotation_processor_properties",
+    "create_ksp_annotation_processor_properties",
+)
+load("@prelude//java/plugins:java_plugin.bzl", "create_plugin_params")
+load("@prelude//java/utils:java_more_utils.bzl", "get_path_separator_for_exec_os")
+load(
+    "@prelude//java/utils:java_utils.bzl",
+    "CustomJdkInfo",  # @unused Used as a type
+    "derive_javac",
+    "get_abi_generation_mode",
+    "get_class_to_source_map_info",
+    "get_default_info",
+    "get_java_version_attributes",
+)
+load("@prelude//jvm:nullsafe.bzl", "get_nullsafe_info")
+load(
+    "@prelude//kotlin:kotlin_toolchain.bzl",
+    "KotlinToolchainInfo",
+)
+load("@prelude//kotlin:kotlin_utils.bzl", "get_friend_paths", "get_kotlinc_compatible_target")
+load("@prelude//kotlin:kotlincd_jar_creator.bzl", "create_jar_artifact_kotlincd")
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:lazy.bzl", "lazy")
+load("@prelude//utils:utils.bzl", "map_idx")
+
+_JAVA_OR_KOTLIN_FILE_EXTENSION = [".java", ".kt"]
+
+def _create_kotlin_sources(
+    ctx: AnalysisContext,
+    srcs: list[Artifact],
+    deps: list[Dependency],
+    annotation_processor_properties: AnnotationProcessorProperties,
+    ksp_annotation_processor_properties: AnnotationProcessorProperties,
+    additional_classpath_entries: JavaCompilingDepsTSet | None,
+    bootclasspath_entries: list[Artifact],
+    plugins: list[tuple],
+    target_level: int,
+    output_artifact_prefix: str = "",
+) -> (Artifact, Artifact | None, Artifact | None):
+    """
+    Runs kotlinc on the provided kotlin sources.
+    """
+
+    kotlin_toolchain = ctx.attrs._kotlin_toolchain[KotlinToolchainInfo]
+    compile_kotlin_tool = kotlin_toolchain.compile_kotlin[RunInfo]
+    kotlinc = kotlin_toolchain.kotlinc[RunInfo]
+    kotlinc_output = ctx.actions.declare_output(
+        output_artifact_prefix,
+        "kotlinc_classes_output",
+        dir = True,
+        has_content_based_path = True,
+    )
+
+    compile_kotlin_cmd_args = [
+        compile_kotlin_tool,
+        "--kotlinc_output",
+        kotlinc_output.as_output(),
+    ]
+    compile_kotlin_cmd_hidden = cmd_args()
+
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    zip_scrubber_args = ["--zip_scrubber", cmd_args(java_toolchain.zip_scrubber, delimiter = " ")]
+    compile_kotlin_cmd_args.append(zip_scrubber_args)
+
+    kotlinc_cmd_args = cmd_args([kotlinc])
+
+    compiling_classpath = cmd_args()
+    if additional_classpath_entries:
+        compiling_classpath.add(additional_classpath_entries.project_as_args("args_for_compiling"))
+
+    # kotlic doesn't support -bootclasspath param, so adding `bootclasspath_entries` into kotlin classpath
+    compiling_classpath.add(bootclasspath_entries)
+
+    compiling_deps_tset = get_compiling_deps_tset(ctx.actions, deps + [kotlin_toolchain.kotlin_stdlib])
+    if compiling_deps_tset:
+        compiling_classpath.add(compiling_deps_tset.project_as_args("args_for_compiling"))
+
+    classpath_args = cmd_args(
+        compiling_classpath,
+        delimiter = get_path_separator_for_exec_os(ctx),
+    )
+
+    compile_kotlin_cmd_hidden.add(compiling_classpath)
+
+    kotlinc_cmd_args.add(["-classpath"])
+    kotlinc_cmd_args.add(
+        at_argfile(
+            actions = ctx.actions,
+            name = "{}kotlinc_classpath".format(output_artifact_prefix),
+            args = classpath_args,
+            allow_args = True,
+        )
+    )
+
+    # this is required for the Kotlin compiler to be able to use jspecify annotations
+    kotlinc_cmd_args.add(["-Xjspecify-annotations=strict"])
+
+    jdk_release = getattr(ctx.attrs, "jdk_release", None) or ctx.attrs.java_version
+    jvm_target = None
+    if jdk_release and not ctx.attrs.no_x_jdk_release:
+        kotlinc_cmd_args.add(["-Xjdk-release=" + jdk_release])
+    else:
+        jvm_target = get_kotlinc_compatible_target(str(target_level))
+        kotlinc_cmd_args.add([
+            "-jvm-target",
+            jvm_target,
+        ])
+
+    module_name = ctx.label.package.replace("/", ".") + "." + ctx.label.name
+    kotlinc_cmd_args.add(
+        [
+            "-module-name",
+            module_name,
+            "-no-stdlib",
+            "-no-reflect",
+        ]
+        + ctx.attrs.extra_kotlinc_arguments
+        + get_language_version_arg(ctx),
+    )
+
+    kapt_generated_sources_output = None
+    if annotation_processor_properties.annotation_processors:
+        compile_kotlin_cmd_args.extend(
+            ["--kapt_annotation_processing_jar", kotlin_toolchain.annotation_processing_jar[JavaLibraryInfo].library_output.full_library]
+        )
+        compile_kotlin_cmd_args.extend(
+            ["--kapt_annotation_processors", ",".join([p for ap in annotation_processor_properties.annotation_processors for p in ap.processors])]
+        )
+        compile_kotlin_cmd_args.extend(["--kapt_annotation_processor_params", ";".join(annotation_processor_properties.annotation_processor_params)])
+
+        annotation_processor_classpath_tsets = filter(None, ([ap.deps for ap in annotation_processor_properties.annotation_processors])) + [
+            dep[JavaPackagingInfo].packaging_deps for dep in [kotlin_toolchain.annotation_processing_jar, kotlin_toolchain.kotlin_stdlib]
+        ]
+        annotation_processor_classpath = ctx.actions.tset(
+            JavaPackagingDepTSet,
+            children = annotation_processor_classpath_tsets,
+        ).project_as_args("full_jar_args")
+        kapt_classpath_file = ctx.actions.write(
+            "{}kapt_classpath_file".format(output_artifact_prefix), annotation_processor_classpath, has_content_based_path = False
+        )
+        compile_kotlin_cmd_args.extend(["--kapt_classpath_file", kapt_classpath_file])
+        compile_kotlin_cmd_hidden.add(annotation_processor_classpath)
+
+        sources_output = ctx.actions.declare_output(output_artifact_prefix, "kapt_sources_output", has_content_based_path = True)
+        compile_kotlin_cmd_args.append(["--kapt_sources_output", sources_output.as_output()])
+        classes_output = ctx.actions.declare_output(output_artifact_prefix, "kapt_classes_output", has_content_based_path = True)
+        compile_kotlin_cmd_args.append(["--kapt_classes_output", classes_output.as_output()])
+        stubs = ctx.actions.declare_output(output_artifact_prefix, "kapt_stubs", has_content_based_path = True)
+        compile_kotlin_cmd_args.append(["--kapt_stubs", stubs.as_output()])
+
+        kapt_generated_sources_output = ctx.actions.declare_output(output_artifact_prefix, "kapt_generated_sources_output.src.zip", has_content_based_path = True)
+        compile_kotlin_cmd_args.append(["--kapt_generated_sources_output", kapt_generated_sources_output.as_output()])
+        compile_kotlin_cmd_args.append(["--kapt_base64_encoder", cmd_args(kotlin_toolchain.kapt_base64_encoder[RunInfo], delimiter = " ")])
+        generated_kotlin_output = ctx.actions.declare_output(output_artifact_prefix, "kapt_generated_kotlin_output", has_content_based_path = True)
+        compile_kotlin_cmd_args.append(["--kapt_generated_kotlin_output", generated_kotlin_output.as_output()])
+        if jvm_target:
+            compile_kotlin_cmd_args.append(["--kapt_jvm_target", jvm_target])
+
+    friend_paths = get_friend_paths(ctx)
+    if friend_paths:
+        concat_friends_paths = cmd_args(
+            [friend_path.library_output.abi for friend_path in map_idx(JavaLibraryInfo, friend_paths) if friend_path.library_output], delimiter = ","
+        )
+        kotlinc_cmd_args.add(cmd_args(["-Xfriend-paths", concat_friends_paths], delimiter = "="))
+
+    zipped_sources, plain_sources = split_on_archives_and_plain_files(srcs, _JAVA_OR_KOTLIN_FILE_EXTENSION)
+
+    kotlinc_cmd_args.add(plain_sources)
+
+    ksp_zipped_sources_output = None
+    if ksp_annotation_processor_properties.annotation_processors:
+        ksp_cmd = [compile_kotlin_tool]
+        ksp_cmd.append(zip_scrubber_args)
+
+        ksp_annotation_processor_classpath_tsets = filter(None, ([ap.deps for ap in ksp_annotation_processor_properties.annotation_processors]))
+        if ksp_annotation_processor_classpath_tsets:
+            ksp_annotation_processor_classpath = ctx.actions.tset(
+                JavaPackagingDepTSet,
+                children = ksp_annotation_processor_classpath_tsets,
+            ).project_as_args("full_jar_args")
+            ksp_cmd.append("--ksp_processor_jars")
+            ksp_cmd.append(cmd_args(ksp_annotation_processor_classpath, delimiter = ","))
+
+        ksp_cmd.extend(["--ksp_classpath", classpath_args])
+        ksp_classes_and_resources_output = ctx.actions.declare_output(
+            output_artifact_prefix, "ksp_output_dir/ksp_classes_and_resources_output", has_content_based_path = True
+        )
+        ksp_cmd.extend(["--ksp_classes_and_resources_output", ksp_classes_and_resources_output.as_output()])
+        ksp_output = cmd_args(ksp_classes_and_resources_output.as_output(), parent = 1)
+        ksp_cmd.extend(["--ksp_output", ksp_output])
+        ksp_sources_output = ctx.actions.declare_output(output_artifact_prefix, "ksp_output_dir/ksp_sources_output", has_content_based_path = True)
+        ksp_cmd.extend(["--ksp_sources_output", ksp_sources_output.as_output()])
+        ksp_zipped_sources_output = ctx.actions.declare_output(
+            output_artifact_prefix, "ksp_output_dir/ksp_zipped_sources_output.src.zip", has_content_based_path = True
+        )
+        ksp_cmd.extend(["--ksp_zipped_sources_output", ksp_zipped_sources_output.as_output()])
+        ksp_cmd.extend(["--ksp_project_base_dir", ctx.label.path])
+
+        ksp_kotlinc_cmd_args = cmd_args(kotlinc_cmd_args)
+        plugins_cmd_args = _add_plugins(ctx, plugins, is_ksp = True)
+        ksp_kotlinc_cmd_args.add(plugins_cmd_args.kotlinc_cmd_args)
+        ksp_cmd.append(plugins_cmd_args.compile_kotlin_cmd)
+
+        ksp_cmd_args_file, _ = ctx.actions.write(
+            "{}ksp_kotlinc_cmd".format(output_artifact_prefix),
+            ksp_kotlinc_cmd_args,
+            allow_args = True,
+            has_content_based_path = False,
+        )
+
+        ksp_cmd.extend(["--kotlinc_cmd_file", ksp_cmd_args_file])
+
+        ctx.actions.run(
+            cmd_args(ksp_cmd, hidden = ksp_kotlinc_cmd_args),
+            category = "ksp_kotlinc",
+            allow_cache_upload = True,
+            error_handler = kotlin_toolchain.kotlin_error_handler,
+        )
+
+        zipped_sources = (zipped_sources or []) + [ksp_zipped_sources_output]
+        compile_kotlin_cmd_args.extend(["--ksp_generated_classes_and_resources", ksp_classes_and_resources_output])
+
+    plugin_cmd_args = _add_plugins(ctx, plugins, is_ksp = False)
+    kotlinc_cmd_args.add(plugin_cmd_args.kotlinc_cmd_args)
+    compile_kotlin_cmd_args.append(plugin_cmd_args.compile_kotlin_cmd)
+
+    if zipped_sources:
+        zipped_sources_file = ctx.actions.write("{}kotlinc_zipped_source_args".format(output_artifact_prefix), zipped_sources, has_content_based_path = False)
+        compile_kotlin_cmd_args.append(["--zipped_sources_file", zipped_sources_file])
+        compile_kotlin_cmd_hidden.add(zipped_sources)
+
+    args_file, _ = ctx.actions.write(
+        "{}kotlinc_cmd".format(output_artifact_prefix),
+        kotlinc_cmd_args,
+        allow_args = True,
+        has_content_based_path = False,
+    )
+
+    compile_kotlin_cmd_hidden.add(plain_sources)
+
+    compile_kotlin_cmd_args.append("--kotlinc_cmd_file")
+    compile_kotlin_cmd_args.append(args_file)
+    compile_kotlin_cmd_hidden.add(kotlinc_cmd_args)
+
+    ctx.actions.run(
+        cmd_args(compile_kotlin_cmd_args, hidden = compile_kotlin_cmd_hidden),
+        category = "{}kotlinc".format(output_artifact_prefix),
+        allow_cache_upload = True,
+        error_handler = kotlin_toolchain.kotlin_error_handler,
+    )
+
+    return kotlinc_output, kapt_generated_sources_output, ksp_zipped_sources_output
+
+def _is_ksp_plugin(plugin: str) -> bool:
+    return "symbol-processing" in plugin
+
+_PluginCmdArgs = record(
+    kotlinc_cmd_args = cmd_args,
+    compile_kotlin_cmd = cmd_args,
+)
+
+def _add_plugins(ctx: AnalysisContext, plugins: list[tuple], is_ksp: bool) -> _PluginCmdArgs:
+    kotlinc_cmd_args = cmd_args()
+    compile_kotlin_cmd = cmd_args()
+    for plugin, plugin_options in plugins:
+        if _is_ksp_plugin(str(plugin)) != is_ksp:
+            continue
+
+        kotlinc_cmd_args.add(cmd_args(["-Xplugin", plugin[DefaultInfo].default_outputs[0]], delimiter = "="))
+        options = []
+        for option_key, option_val in plugin_options.items():
+            # "_codegen_dir_" means buck should provide a dir
+            if option_val == "__codegen_dir__":
+                option_val = ctx.actions.declare_output("kotlin_compiler_plugin_dir", has_content_based_path = True)
+                options.append(cmd_args([option_key, option_val.as_output()], delimiter = "="))
+                compile_kotlin_cmd.add(["--kotlin_compiler_plugin_dir", option_val.as_output()])
+            else:
+                options.append(cmd_args([option_key, option_val], delimiter = "="))
+
+        if options:
+            kotlinc_cmd_args.add(["-P", cmd_args(options, delimiter = ",")])
+
+    return _PluginCmdArgs(kotlinc_cmd_args = kotlinc_cmd_args, compile_kotlin_cmd = compile_kotlin_cmd)
+
+def get_language_version(ctx: AnalysisContext) -> str:
+    kotlin_toolchain = ctx.attrs._kotlin_toolchain[KotlinToolchainInfo]
+
+    # kotlin compiler expects relase version of format 1.6, 1.7, etc. Don't include patch version
+    current_kotlin_release_version = ".".join(kotlin_toolchain.kotlin_version.split(".")[:2])
+
+    current_language_version = None
+    for arg in ctx.attrs.extra_kotlinc_arguments:
+        # If `-language-version` is defined multiple times, we use the last one, just like the compiler does
+        if "-language-version" in str(arg):
+            current_language_version = str(arg).split("=")[1].strip(' "')
+
+    if ctx.attrs.k2 != False:
+        if not current_language_version or current_language_version < "2.0":
+            if current_kotlin_release_version < "2.0":
+                current_language_version = "2.0"
+            else:
+                current_language_version = current_kotlin_release_version
+    else:  # use K1
+        # K1 frontend is deprecated in Kotlin 2.3 and will be removed in future versions
+        if current_kotlin_release_version >= "2.3":
+            fail(
+                "K1 mode (k2=False) is not supported with Kotlin {}. The K1 frontend is deprecated in Kotlin 2.3 and will be removed in future releases. Please use K2 mode instead.".format(
+                    kotlin_toolchain.kotlin_version
+                )
+            )
+        if not current_language_version or current_language_version >= "2.0":
+            if current_kotlin_release_version >= "2.0":
+                current_language_version = "1.9"
+            else:
+                current_language_version = current_kotlin_release_version
+
+    return current_language_version
+
+def get_language_version_arg(ctx: AnalysisContext) -> list[str]:
+    language_version = get_language_version(ctx)
+    return ["-language-version=" + language_version]
+
+def filter_out_language_version(extra_arguments: list) -> list:
+    return [arg for arg in extra_arguments if not (isinstance(arg, str) and "-language-version" in arg)]
+
+def kotlin_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    packaging_deps = ctx.attrs.deps + ctx.attrs.exported_deps + ctx.attrs.runtime_deps
+
+    # TODO(T107163344) this shouldn't be in kotlin_library itself, use overlays to remove it.
+    android_packageable_info = merge_android_packageable_info(ctx.label, ctx.actions, packaging_deps)
+    if ctx.attrs._build_only_native_code:
+        shared_library_info, cxx_resource_info, linkable_graph = create_native_providers(ctx, ctx.label, packaging_deps)
+        return [
+            shared_library_info,
+            cxx_resource_info,
+            linkable_graph,
+            # Add an unused default output in case this target is used an an attr.source() anywhere.
+            DefaultInfo(default_output = ctx.actions.write("{}/unused.jar".format(ctx.label.name), [], has_content_based_path = False)),
+            TemplatePlaceholderInfo(
+                keyed_variables = {
+                    "classpath": "unused_but_needed_for_analysis",
+                }
+            ),
+            android_packageable_info,
+        ]
+
+    target_stats_providers, target_stats_subtargets = jvm_target_stats(ctx)
+
+    java_providers = build_kotlin_library(
+        ctx = ctx,
+        validation_deps_outputs = get_validation_deps_outputs(ctx),
+        extra_sub_targets = target_stats_subtargets,
+    )
+    return to_list(java_providers) + [android_packageable_info] + target_stats_providers
+
+def _check_exported_deps(exported_deps: list[Dependency], attr_name: str):
+    for exported_dep in exported_deps:
+        # TODO(navidq) add a check that the exported dep always have a JavaLibraryInfo provider
+        if JavaLibraryInfo in exported_dep:
+            expect(
+                not exported_dep[JavaLibraryInfo].may_not_be_exported,
+                "{} has 'may_not_be_exported' label and should not be present in {}.".format(exported_dep.label.raw_target(), attr_name),
+            )
+
+def build_kotlin_library(
+    ctx: AnalysisContext,
+    additional_classpath_entries: JavaCompilingDepsTSet | None = None,
+    custom_jdk_info: CustomJdkInfo | None = None,
+    extra_sub_targets: dict = {},
+    validation_deps_outputs: [list[Artifact], None] = None,
+    extra_arguments = [],
+) -> JavaProviders:
+    srcs = ctx.attrs.srcs
+    has_kotlin_srcs = lazy.is_any(lambda src: src.extension == ".kt" or src.basename.endswith(".src.zip") or src.basename.endswith("-sources.jar"), srcs)
+
+    if not has_kotlin_srcs:
+        return build_java_library(
+            ctx,
+            ctx.attrs.srcs,
+            custom_jdk_info = custom_jdk_info,
+            additional_classpath_entries = additional_classpath_entries,
+            # Match buck1, which always does class ABI generation for Kotlin targets unless explicitly specified.
+            override_abi_generation_mode = get_abi_generation_mode(ctx.attrs.abi_generation_mode) or AbiGenerationMode("class"),
+            extra_sub_targets = extra_sub_targets,
+            validation_deps_outputs = validation_deps_outputs,
+            extra_arguments = extra_arguments,
+        )
+
+    else:
+        deps_query = getattr(ctx.attrs, "deps_query", []) or []
+        provided_deps_query = getattr(ctx.attrs, "provided_deps_query", []) or []
+        _check_exported_deps(ctx.attrs.exported_deps, "exported_deps")
+        _check_exported_deps(ctx.attrs.exported_provided_deps, "exported_provided_deps")
+        deps = ctx.attrs.deps + deps_query + ctx.attrs.exported_deps + ctx.attrs.provided_deps + provided_deps_query + ctx.attrs.exported_provided_deps
+        annotation_processor_properties = create_annotation_processor_properties(
+            ctx,
+            ctx.attrs.plugins + ctx.attrs.non_exec_dep_plugins_deprecated,
+            ctx.attrs.annotation_processors,
+            ctx.attrs.annotation_processor_params,
+            ctx.attrs.annotation_processor_deps,
+        )
+        ksp_annotation_processor_properties = create_ksp_annotation_processor_properties(ctx.attrs.plugins + ctx.attrs.non_exec_dep_plugins_deprecated)
+
+        # -bootclasspath is a javac-only, JDK<9 release concept, but we still use this field
+        # to append additional jars to the kotlinc classpath. When we drop Java 8 language
+        # level support someday, we should rework this field and treat it like additional
+        # classpath entries.
+        bootclasspath_for_kotlinc = custom_jdk_info.bootclasspath if custom_jdk_info else []
+        bootclasspath_jar_snapshots_for_kotlinc = custom_jdk_info.bootclasspath_jar_snapshots if custom_jdk_info and ctx.attrs.incremental else []
+
+        javac_tool = derive_javac(ctx.attrs.javac) if getattr(ctx.attrs, "javac", None) else None
+        source_level, target_level = get_java_version_attributes(ctx)
+
+        kotlin_toolchain = ctx.attrs._kotlin_toolchain[KotlinToolchainInfo]
+        if javac_tool or kotlin_toolchain.kotlinc_protocol == "classic":
+            kotlinc_classes, kapt_generated_sources, ksp_generated_sources = _create_kotlin_sources(
+                ctx,
+                ctx.attrs.srcs,
+                (deps or []) + [kotlin_toolchain.kotlin_stdlib],
+                annotation_processor_properties,
+                ksp_annotation_processor_properties,
+                additional_classpath_entries,
+                bootclasspath_for_kotlinc,
+                ctx.attrs.kotlin_compiler_plugins,
+                target_level,
+            )
+            semanticdb_res = _semanticdb_plugin(ctx, kotlin_toolchain)
+            if not ctx.attrs._is_building_android_binary and semanticdb_res:
+                (semanticdb_plugin, semanticdb_output) = semanticdb_res
+                _create_kotlin_sources(
+                    ctx,
+                    ctx.attrs.srcs,
+                    (deps or []) + [kotlin_toolchain.kotlin_stdlib],
+                    annotation_processor_properties,
+                    ksp_annotation_processor_properties,
+                    additional_classpath_entries,
+                    bootclasspath_for_kotlinc,
+                    semanticdb_plugin,
+                    target_level,
+                    output_artifact_prefix = "semanticdb",
+                )
+                extra_sub_targets = extra_sub_targets | {"semanticdb": [DefaultInfo(default_output = semanticdb_output)]}
+
+            srcs = [src for src in ctx.attrs.srcs if not src.extension == ".kt"]
+            if kapt_generated_sources:
+                srcs.append(kapt_generated_sources)
+            if ksp_generated_sources:
+                srcs.append(ksp_generated_sources)
+            all_additional_classpath_entries = get_compiling_deps_tset(
+                ctx.actions,
+                value = JavaClasspathEntry(
+                    full_library = kotlinc_classes,
+                    abi = kotlinc_classes,
+                    abi_as_dir = None,
+                    required_for_source_only_abi = True,
+                    abi_jar_snapshot = None,
+                ),
+                additional_classpath_entries = ([additional_classpath_entries] if additional_classpath_entries else [])
+                + [kotlin_toolchain.kotlin_stdlib[JavaLibraryInfo].compiling_deps],
+            )
+            java_lib = build_java_library(
+                ctx,
+                srcs,
+                run_annotation_processors = False,
+                custom_jdk_info = custom_jdk_info,
+                additional_classpath_entries = all_additional_classpath_entries,
+                additional_compiled_srcs = kotlinc_classes,
+                generated_sources = filter(None, [kapt_generated_sources, ksp_generated_sources]),
+                extra_sub_targets = extra_sub_targets,
+                validation_deps_outputs = validation_deps_outputs,
+                extra_arguments = extra_arguments,
+            )
+            return java_lib
+        elif kotlin_toolchain.kotlinc_protocol == "kotlincd":
+            expect(
+                ctx.attrs._java_toolchain[JavaToolchainInfo].javac_protocol == "javacd",
+                "Kotlin compiler mode: kotlincd and java compiler mode: {} don't match.".format(ctx.attrs._java_toolchain[JavaToolchainInfo].javac_protocol)
+                + "\nHint: If you have a Java toolchain with a custom javac, you should also provide a custom kotlinc for your Kotlin toolchain.",
+            )
+            extra_arguments = cmd_args(
+                ctx.attrs.extra_arguments + extra_arguments,
+                # The outputs of validation_deps need to be added as hidden arguments
+                # to an action for the validation_deps targets to be built and enforced.
+                hidden = validation_deps_outputs or [],
+            )
+
+            common_kotlincd_kwargs = {
+                "abi_generation_mode": get_abi_generation_mode(ctx.attrs.abi_generation_mode),
+                "actions": ctx.actions,
+                "additional_classpath_entries": additional_classpath_entries,
+                "annotation_processor_properties": AnnotationProcessorProperties(
+                    annotation_processors = annotation_processor_properties.annotation_processors + ksp_annotation_processor_properties.annotation_processors,
+                    annotation_processor_params = annotation_processor_properties.annotation_processor_params
+                    + ksp_annotation_processor_properties.annotation_processor_params,
+                ),
+                "bootclasspath_entries": bootclasspath_for_kotlinc,
+                "custom_jdk_info": custom_jdk_info,
+                "debug_port": getattr(ctx.attrs, "debug_port", None),
+                "deps": deps + [kotlin_toolchain.kotlin_stdlib],
+                "enable_depfiles": getattr(ctx.attrs, "enable_depfiles", True),
+                "enable_used_classes": ctx.attrs.enable_used_classes,
+                "extra_kotlinc_arguments": filter_out_language_version(ctx.attrs.extra_kotlinc_arguments or []),
+                "friend_paths": get_friend_paths(ctx),
+                "is_building_android_binary": ctx.attrs._is_building_android_binary,
+                "jar_postprocessor": ctx.attrs.jar_postprocessor[RunInfo] if hasattr(ctx.attrs, "jar_postprocessor") and ctx.attrs.jar_postprocessor else None,
+                "java_toolchain": ctx.attrs._java_toolchain[JavaToolchainInfo],
+                "kotlin_compiler_plugins": ctx.attrs.kotlin_compiler_plugins,
+                "kotlin_toolchain": kotlin_toolchain,
+                "label": ctx.label,
+                "language_version": get_language_version(ctx),
+                "manifest_file": ctx.attrs.manifest_file,
+                "remove_classes": ctx.attrs.remove_classes,
+                "required_for_source_only_abi": ctx.attrs.required_for_source_only_abi,
+                "resources": ctx.attrs.resources,
+                "resources_root": ctx.attrs.resources_root,
+                "source_level": source_level,
+                "source_only_abi_deps": ctx.attrs.source_only_abi_deps,
+                "srcs": srcs,
+                "target_level": target_level,
+            }
+
+            outputs, proto, tracking_outputs = create_jar_artifact_kotlincd(
+                plugin_params = create_plugin_params(ctx, ctx.attrs.plugins + ctx.attrs.non_exec_dep_plugins_deprecated),
+                extra_arguments = extra_arguments,
+                actions_identifier = "",
+                incremental = ctx.attrs.incremental,
+                uses_content_based_paths = ctx.attrs.uses_content_based_paths_for_kotlincd,
+                bootclasspath_snapshot_entries = bootclasspath_jar_snapshots_for_kotlinc,
+                track_files_which_skipped_compilation = kotlin_toolchain.track_files_which_skipped_compilation,
+                **common_kotlincd_kwargs,
+            )
+
+            if proto:
+                extra_sub_targets = extra_sub_targets | {"jar_command_proto_json": [DefaultInfo(default_output = proto)]}
+            if outputs and outputs.incremental_state_dir:
+                extra_sub_targets = extra_sub_targets | {
+                    "incremental_state_dir": [
+                        DefaultInfo(default_output = outputs.incremental_state_dir),
+                    ]
+                }
+
+            for subtarget_name, tracking_artifact in tracking_outputs.items():
+                extra_sub_targets = extra_sub_targets | {
+                    subtarget_name: [
+                        DefaultInfo(default_output = tracking_artifact),
+                    ]
+                }
+
+            if outputs and outputs.annotation_processor_output:
+                generated_sources = [outputs.annotation_processor_output]
+                extra_sub_targets = extra_sub_targets | {
+                    "generated_sources": [
+                        DefaultInfo(default_output = outputs.annotation_processor_output),
+                    ]
+                }
+            else:
+                generated_sources = []
+
+            java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+            if not java_toolchain.is_bootstrap_toolchain and not ctx.attrs._is_building_android_binary:
+                # Skip Nullsafe for Kotlin-only targets (no real .java) — its javac step crashes on them.
+                if lazy.is_any(lambda src: src.extension == ".java", srcs):
+                    extra_sub_targets = _nullsafe_subtarget(ctx, extra_sub_targets, common_kotlincd_kwargs)
+                extra_sub_targets = _semanticdb_subtarget(ctx, extra_sub_targets, kotlin_toolchain, java_toolchain, common_kotlincd_kwargs)
+
+            class_to_src_map, sources_jar, class_to_src_map_sub_targets = get_class_to_source_map_info(
+                ctx,
+                outputs = outputs,
+                deps = ctx.attrs.deps + deps_query + ctx.attrs.exported_deps,
+                generate_sources_jar = True,
+            )
+            extra_sub_targets = extra_sub_targets | class_to_src_map_sub_targets
+
+            (
+                java_library_info,
+                java_packaging_info,
+                global_code_info,
+                shared_library_info,
+                cxx_resource_info,
+                linkable_graph,
+                template_placeholder_info,
+                intellij_info,
+            ) = create_java_library_providers(
+                ctx,
+                library_output = outputs.classpath_entry if outputs else None,
+                global_code_config = java_toolchain.global_code_config,
+                declared_deps = ctx.attrs.deps + deps_query,
+                exported_deps = ctx.attrs.exported_deps,
+                provided_deps = ctx.attrs.provided_deps + provided_deps_query,
+                exported_provided_deps = ctx.attrs.exported_provided_deps,
+                runtime_deps = ctx.attrs.runtime_deps,
+                generated_sources = generated_sources,
+                has_srcs = bool(srcs),
+                sources_jar = sources_jar,
+                preprocessed_library = outputs.preprocessed_library if outputs else None,
+                used_jars_json = outputs.used_jars_json if outputs else None,
+            )
+
+            default_info = get_default_info(
+                ctx.actions,
+                ctx.attrs._java_toolchain[JavaToolchainInfo],
+                outputs,
+                java_packaging_info,
+                extra_sub_targets = extra_sub_targets,
+            )
+
+            validation_specs = get_attrs_validation_specs(ctx)
+            validation_info = ValidationInfo(validations = validation_specs) if validation_specs else None
+
+            return JavaProviders(
+                java_library_info = java_library_info,
+                java_library_intellij_info = intellij_info,
+                java_packaging_info = java_packaging_info,
+                java_global_code_info = global_code_info,
+                shared_library_info = shared_library_info,
+                cxx_resource_info = cxx_resource_info,
+                linkable_graph = linkable_graph,
+                template_placeholder_info = template_placeholder_info,
+                default_info = default_info,
+                class_to_src_map = class_to_src_map,
+                validation_info = validation_info,
+            )
+        else:
+            fail("unrecognized kotlinc protocol `{}`".format(kotlin_toolchain.kotlinc_protocol))
+
+def _nullsafe_subtarget(ctx: AnalysisContext, extra_sub_targets: dict, common_kotlincd_kwargs: dict):
+    nullsafe_info = get_nullsafe_info(ctx)
+    if nullsafe_info:
+        create_jar_artifact_kotlincd(
+            actions_identifier = "nullsafe",
+            plugin_params = nullsafe_info.plugin_params,
+            extra_arguments = nullsafe_info.extra_arguments,
+            # To make sure that even for pure Kotlin targets empty output dir is always present
+            optional_dirs = [nullsafe_info.output.as_output()],
+            is_creating_subtarget = True,
+            incremental = False,
+            uses_content_based_paths = ctx.attrs.uses_content_based_paths_for_kotlincd,
+            bootclasspath_snapshot_entries = [],
+            **common_kotlincd_kwargs,
+        )
+
+        extra_sub_targets = extra_sub_targets | {
+            "nullsafex-json": [
+                DefaultInfo(default_output = nullsafe_info.output),
+            ]
+        }
+    return extra_sub_targets
+
+def _semanticdb_plugin(ctx: AnalysisContext, kotlin_toolchain: KotlinToolchainInfo) -> tuple | None:
+    sourceroot = kotlin_toolchain.semanticdb_sourceroot
+    if not sourceroot:
+        return None
+    kotlin_version = get_language_version(ctx)
+    semanticdb_kotlinc_plugins = kotlin_toolchain.semanticdb_kotlinc
+    semanticdb_kotlinc = semanticdb_kotlinc_plugins.get(kotlin_version) if semanticdb_kotlinc_plugins else None
+    if not semanticdb_kotlinc:
+        return None
+    semanticdb_kotlinc_output = ctx.actions.declare_output("semanticdb", "out", dir = True, has_content_based_path = False)
+    semanticdb_plugin = [
+        (
+            semanticdb_kotlinc,
+            {
+                "plugin:semanticdb-kotlinc:sourceroot": sourceroot,
+                "plugin:semanticdb-kotlinc:targetroot": cmd_args(semanticdb_kotlinc_output.as_output()),
+            },
+        )
+    ]
+    return (semanticdb_plugin, semanticdb_kotlinc_output)
+
+def _semanticdb_subtarget(
+    ctx: AnalysisContext, extra_sub_targets: dict, kotlin_toolchain: KotlinToolchainInfo, java_toolchain: JavaToolchainInfo, common_kotlincd_kwargs: dict
+):
+    sourceroot = kotlin_toolchain.semanticdb_sourceroot
+    if not sourceroot:
+        return extra_sub_targets
+    semanticdb_javac = java_toolchain.semanticdb_javac
+    semanticdb_kotlinc_plugins = kotlin_toolchain.semanticdb_kotlinc
+    kotlin_version = get_language_version(ctx)
+    semanticdb_kotlinc = kotlin_toolchain.semanticdb_kotlinc.get(kotlin_version) if semanticdb_kotlinc_plugins else None
+    if semanticdb_javac or semanticdb_kotlinc:
+        semanticdb_output = ctx.actions.declare_output("semanticdb", dir = True, has_content_based_path = False)
+        semanticdb_javac_plugin_params = None
+        if semanticdb_javac:
+            javac_sourceroot_args = cmd_args(sourceroot, format = "-sourceroot:{}")
+            javac_targetroot_args = cmd_args(semanticdb_output.as_output(), format = "-targetroot:{}")
+            semanticdb_javac_plugin_params = create_plugin_params(
+                ctx,
+                [(semanticdb_javac, cmd_args(javac_sourceroot_args, javac_targetroot_args))],
+            )
+        kwargs = common_kotlincd_kwargs
+        if semanticdb_kotlinc:
+            # IMPORTANT: Append semanticdb to existing plugins, don't replace them
+            # This ensures other plugins (like Ultralight DI) continue to work
+            existing_plugins = common_kotlincd_kwargs.get("kotlin_compiler_plugins", [])
+            semanticdb_plugin = (
+                semanticdb_kotlinc,
+                {
+                    "plugin:semanticdb-kotlinc:sourceroot": sourceroot,
+                    "plugin:semanticdb-kotlinc:targetroot": cmd_args(semanticdb_output.as_output()),
+                },
+            )
+            kotlin_compiler_plugins = existing_plugins + [semanticdb_plugin]
+            kwargs = common_kotlincd_kwargs | {"kotlin_compiler_plugins": kotlin_compiler_plugins}
+        create_jar_artifact_kotlincd(
+            actions_identifier = "semanticdb",
+            plugin_params = semanticdb_javac_plugin_params,
+            extra_arguments = cmd_args(),
+            optional_dirs = [],
+            is_creating_subtarget = True,
+            incremental = False,
+            uses_content_based_paths = ctx.attrs.uses_content_based_paths_for_kotlincd,
+            bootclasspath_snapshot_entries = [],
+            **kwargs,
+        )
+        extra_sub_targets = extra_sub_targets | {
+            "semanticdb": [
+                DefaultInfo(default_output = semanticdb_output),
+            ]
+        }
+    return extra_sub_targets
diff --git a/buck2/prelude/kotlin/kotlin_test.bzl b/buck2/prelude/kotlin/kotlin_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/kotlin_test.bzl
@@ -0,0 +1,36 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_library.bzl", "jvm_target_stats")
+load("@prelude//java:java_test.bzl", "build_junit_test")
+load("@prelude//kotlin:kotlin_library.bzl", "build_kotlin_library")
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+
+def kotlin_test_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.attrs._build_only_native_code:
+        return [DefaultInfo()]
+
+    target_stats_providers, target_stats_subtargets = jvm_target_stats(ctx)
+    java_providers = build_kotlin_library(
+        ctx,
+        extra_sub_targets = target_stats_subtargets,
+    )
+    external_runner_test_info = build_junit_test(ctx, java_providers.java_library_info, java_providers.java_packaging_info, java_providers.class_to_src_map)
+
+    return (
+        inject_test_run_info(ctx, external_runner_test_info)
+        + [
+            java_providers.java_library_intellij_info,
+            java_providers.java_library_info,
+            java_providers.java_packaging_info,
+            java_providers.template_placeholder_info,
+            java_providers.default_info,
+            java_providers.class_to_src_map,
+        ]
+        + target_stats_providers
+    )
diff --git a/buck2/prelude/kotlin/kotlin_toolchain.bzl b/buck2/prelude/kotlin/kotlin_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/kotlin_toolchain.bzl
@@ -0,0 +1,46 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+KotlincProtocol = enum("classic", "kotlincd")
+
+KotlinToolchainInfo = provider(
+    doc = "Kotlin toolchain info",
+    fields = {
+        "allow_experimental_content_based_path_hashing": provider_field(bool, default = False),
+        "annotation_processing_jar": provider_field(typing.Any, default = None),
+        "class_loader_bootstrapper": provider_field(typing.Any, default = None),
+        "compile_kotlin": provider_field(typing.Any, default = None),
+        "dep_files": provider_field(typing.Any, default = None),
+        "enable_incremental_compilation": provider_field(typing.Any, default = None),
+        "java_binary_for_kotlincd": provider_field(typing.Any, default = None),
+        "jvm_abi_gen_plugin": provider_field(typing.Any, default = None),
+        "kapt_base64_encoder": provider_field(typing.Any, default = None),
+        "kosabi_applicability_plugin": provider_field(typing.Any, default = None),
+        "kosabi_jvm_abi_gen_k2_plugin": provider_field(typing.Any, default = None),
+        "kosabi_stubs_gen_k2_plugin": provider_field(typing.Any, default = None),
+        "kotlin_error_handler": provider_field(typing.Any, default = None),
+        "kotlin_home_libraries": provider_field(typing.Any, default = None),
+        "kotlin_stdlib": provider_field(typing.Any, default = None),
+        "kotlin_version": provider_field(str),
+        "kotlinc": provider_field(typing.Any, default = None),
+        "kotlinc_protocol": provider_field(typing.Any, default = None),
+        "kotlincd": provider_field(typing.Any, default = None),
+        "kotlincd_debug_port": provider_field(typing.Any, default = None),
+        "kotlincd_debug_target": provider_field(typing.Any, default = None),
+        "kotlincd_jvm_args": provider_field(typing.Any, default = None),
+        "kotlincd_jvm_args_target": provider_field(typing.Any, default = None),
+        "kotlincd_main_class": provider_field(typing.Any, default = None),
+        "kotlincd_remote_worker": provider_field(typing.Any, default = None),
+        "kotlincd_worker": provider_field(typing.Any, default = None),
+        "ksp2_enable_incremental_processing": provider_field(typing.Any, default = None),
+        "semanticdb_kotlinc": provider_field(typing.Any, default = None),
+        "semanticdb_sourceroot": provider_field(typing.Any, default = None),
+        "track_class_usage_plugin": provider_field(typing.Any, default = None),
+        "track_files_which_skipped_compilation": provider_field(bool, default = False),
+    },
+)
diff --git a/buck2/prelude/kotlin/kotlin_utils.bzl b/buck2/prelude/kotlin/kotlin_utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/kotlin_utils.bzl
@@ -0,0 +1,39 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_providers.bzl", "JavaLibraryInfo")
+load(
+    "@prelude//utils:build_target_pattern.bzl",
+    "parse_build_target_pattern",
+)
+load("@prelude//utils:lazy.bzl", "lazy")
+
+# kotlinc is strict about the target that you can pass, e.g.
+# error: unknown JVM target version: 8.  Supported versions: 1.8, 9, 10, 11, 12
+def get_kotlinc_compatible_target(target: str) -> str:
+    return "1.8" if target == "8" else target
+
+def get_friend_paths(ctx: AnalysisContext) -> list[Dependency]:
+    """
+    Resolves the `friend_paths` attribute to the deps whose ABI jars kotlinc gets as `-Xfriend-paths`.
+    """
+    friend_paths = ctx.attrs.friend_paths
+    explicit_friends = [dep for dep in friend_paths if not isinstance(dep, str)]
+    patterns = [parse_build_target_pattern(f) for f in friend_paths if isinstance(f, str)]
+    if not patterns:
+        return explicit_friends
+
+    friends = {dep.label.raw_target(): dep for dep in explicit_friends}
+    for dep in ctx.attrs.deps + ctx.attrs.exported_deps + ctx.attrs.provided_deps + ctx.attrs.exported_provided_deps:
+        if JavaLibraryInfo not in dep:
+            continue
+        target = dep.label.raw_target()
+        if target not in friends and lazy.is_any(lambda pattern: pattern.matches(dep.label), patterns):
+            friends[target] = dep
+
+    return list(friends.values())
diff --git a/buck2/prelude/kotlin/kotlincd_jar_creator.bzl b/buck2/prelude/kotlin/kotlincd_jar_creator.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/kotlincd_jar_creator.bzl
@@ -0,0 +1,663 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//java:java_providers.bzl",
+    "ClasspathSnapshotGranularity",
+    "JavaCompileOutputs",  # @unused Used as a type
+    "JavaCompilingDepsTSet",  # @unused Used as a type
+    "JavaLibraryInfo",
+    "generate_java_classpath_snapshot",
+    "get_compiling_deps_tset",
+    "make_compile_outputs",
+)
+load("@prelude//java:java_resources.bzl", "get_resources_map")
+load("@prelude//java:java_toolchain.bzl", "AbiGenerationMode", "DepFiles", "JavaToolchainInfo")
+load(
+    "@prelude//java/plugins:java_annotation_processor.bzl",
+    "AnnotationProcessorProperties",  # @unused Used as type
+)
+load(
+    "@prelude//java/plugins:java_plugin.bzl",
+    "PluginParams",  # @unused Used as type
+)
+load(
+    "@prelude//java/utils:java_utils.bzl",
+    "CustomJdkInfo",  # @unused Used as type
+)
+load(
+    "@prelude//jvm:cd_jar_creator_util.bzl",
+    "BuildMode",
+    "OutputPaths",
+    "TargetType",
+    "base_qualified_name",
+    "declare_prefixed_output",
+    "define_output_paths",
+    "encode_command",
+    "generate_abi_jars",
+    "get_source_only_abi_compiling_deps",
+    "prepare_cd_exe",
+    "prepare_final_jar",
+    "setup_dep_files",
+)
+load("@prelude//kotlin:kotlin_toolchain.bzl", "KotlinToolchainInfo")
+load("@prelude//kotlin:kotlin_utils.bzl", "get_kotlinc_compatible_target")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "map_idx")
+
+def create_jar_artifact_kotlincd(
+    actions: AnalysisActions,
+    actions_identifier: [str, None],
+    abi_generation_mode: [AbiGenerationMode, None],
+    java_toolchain: JavaToolchainInfo,
+    kotlin_toolchain: KotlinToolchainInfo,
+    label: Label,
+    srcs: list[Artifact],
+    remove_classes: list[str],
+    resources: list[Artifact],
+    resources_root: [str, None],
+    annotation_processor_properties: AnnotationProcessorProperties,
+    plugin_params: [PluginParams, None],
+    manifest_file: Artifact | None,
+    source_level: int,
+    target_level: int,
+    deps: list[Dependency],
+    required_for_source_only_abi: bool,
+    source_only_abi_deps: list[Dependency],
+    extra_arguments: cmd_args,
+    additional_classpath_entries: JavaCompilingDepsTSet | None,
+    bootclasspath_entries: list[Artifact],
+    bootclasspath_snapshot_entries: list[Artifact],
+    custom_jdk_info: CustomJdkInfo | None,
+    is_building_android_binary: bool,
+    friend_paths: list[Dependency],
+    kotlin_compiler_plugins: list[(Dependency, dict[str, [str, cmd_args]])],
+    extra_kotlinc_arguments: list,
+    incremental: bool,
+    enable_used_classes: bool,
+    language_version: str,
+    uses_content_based_paths: bool,
+    is_creating_subtarget: bool = False,
+    optional_dirs: list[OutputArtifact] = [],
+    jar_postprocessor: [RunInfo, None] = None,
+    debug_port: [int, None] = None,
+    enable_depfiles: [bool, None] = True,
+    track_files_which_skipped_compilation: bool = False,
+) -> (JavaCompileOutputs, Artifact, dict[str, Artifact]):
+    resources_map = get_resources_map(
+        java_toolchain = java_toolchain,
+        package = label.package,
+        resources = resources,
+        resources_root = resources_root,
+    )
+
+    expect(abi_generation_mode != AbiGenerationMode("source"), "abi_generation_mode: source is not supported in kotlincd")
+    if abi_generation_mode == AbiGenerationMode("source_only") and language_version < "2.0":
+        fail(
+            'source_only ABI generation is not supported with K1 (language_version {}). Either upgrade to K2 (language_version >= 2.0) or use abi_generation_mode = "class".'.format(
+                language_version
+            )
+        )
+    actual_abi_generation_mode = abi_generation_mode or AbiGenerationMode("class") if srcs else AbiGenerationMode("none")
+    kosabi_applicability_cell_root = (
+        label.cell_root
+        if not is_creating_subtarget and actual_abi_generation_mode == AbiGenerationMode("source_only") and kotlin_toolchain.kosabi_applicability_plugin != None
+        else None
+    )
+    uses_content_based_paths = uses_content_based_paths or kotlin_toolchain.allow_experimental_content_based_path_hashing
+
+    output_paths = define_output_paths(actions, actions_identifier, label, uses_content_based_paths)
+
+    # Only create class-abi inline for class-mode targets. For source_only targets,
+    # the fallback in cd_jar_creator_util.bzl (create_abi) handles class-abi generation
+    # for subtargets. This keeps the kotlincd action key config-invariant. See T264990210.
+    should_create_class_abi = (
+        not is_creating_subtarget and actual_abi_generation_mode == AbiGenerationMode("class") and kotlin_toolchain.jvm_abi_gen_plugin != None
+    )
+    if should_create_class_abi:
+        class_abi_jar = declare_prefixed_output(actions, actions_identifier, "class-abi.jar", uses_content_based_paths)
+        class_abi_output_dir = declare_prefixed_output(actions, actions_identifier, "class_abi_dir", uses_content_based_paths, dir = True)
+        jvm_abi_gen = cmd_args(output_paths.jar.as_output(), format = "{}/jvm-abi-gen.jar", parent = 1)
+        should_use_jvm_abi_gen = True
+    else:
+        class_abi_jar = None
+        class_abi_output_dir = None
+        jvm_abi_gen = None
+        should_use_jvm_abi_gen = False
+
+    # Structured applicability must see every source in the target.
+    should_kotlinc_run_incrementally = kotlin_toolchain.enable_incremental_compilation and incremental and kosabi_applicability_cell_root == None
+    should_ksp2_run_incrementally = kotlin_toolchain.ksp2_enable_incremental_processing and incremental and kosabi_applicability_cell_root == None
+    incremental_state_dir = declare_prefixed_output(actions, actions_identifier, "incremental_state", uses_content_based_paths, dir = True)
+    incremental_metadata_ignored_inputs_tag = actions.artifact_tag()
+
+    compiling_deps_tset = get_compiling_deps_tset(actions, deps, [additional_classpath_entries] if additional_classpath_entries else [])
+
+    # Compute the reduced SO-ABI classpath for applicability checking during
+    # library builds. The applicability plugin needs to know which deps will be
+    # available during source-only-abi generation (only deps with
+    # required_for_source_only_abi=True or in source_only_abi_deps).
+    source_only_abi_applicability_classpath = cmd_args()
+    so_abi_deps = None
+    if actual_abi_generation_mode == AbiGenerationMode("source_only"):
+        so_abi_deps = get_source_only_abi_compiling_deps(actions, compiling_deps_tset, source_only_abi_deps)
+        source_only_abi_applicability_classpath = cmd_args(so_abi_deps.project_as_args("source_only_abi_jars"))
+
+    track_class_usage = enable_used_classes and enable_depfiles and kotlin_toolchain.track_class_usage_plugin != None
+
+    if track_files_which_skipped_compilation:
+        files_which_skipped_compilation = declare_prefixed_output(actions, actions_identifier, "files_which_skipped_compilation", uses_content_based_paths)
+        jvm_abi_files_which_skipped_compilation = (
+            declare_prefixed_output(actions, actions_identifier, "jvm_abi_files_which_skipped_compilation", uses_content_based_paths)
+            if should_use_jvm_abi_gen
+            else None
+        )
+    else:
+        files_which_skipped_compilation = None
+        jvm_abi_files_which_skipped_compilation = None
+
+    define_kotlincd_action = partial(
+        _define_kotlincd_action,
+        actions,
+        java_toolchain,
+        kotlin_toolchain,
+        srcs,
+        should_create_class_abi,
+        class_abi_jar,
+        jvm_abi_gen,
+        class_abi_output_dir,
+        optional_dirs,
+        track_class_usage,
+        compiling_deps_tset,
+        debug_port,
+        uses_content_based_paths,
+        incremental_metadata_ignored_inputs_tag,
+        jar_postprocessor,
+        files_which_skipped_compilation,
+        jvm_abi_files_which_skipped_compilation,
+    )
+
+    library_classpath_jars_tag = actions.artifact_tag()
+    command_builder = _command_builder(
+        label = label,
+        srcs = srcs,
+        remove_classes = remove_classes,
+        annotation_processor_properties = annotation_processor_properties,
+        plugin_params = plugin_params,
+        manifest_file = manifest_file,
+        source_level = source_level,
+        target_level = target_level,
+        compiling_deps_tset = compiling_deps_tset,
+        bootclasspath_entries = bootclasspath_entries,
+        system_image = custom_jdk_info.system_image if custom_jdk_info else None,
+        abi_generation_mode = actual_abi_generation_mode,
+        resources_map = resources_map,
+        extra_arguments = extra_arguments,
+        use_abi_dirs = bool(not is_creating_subtarget and srcs and track_class_usage and kotlin_toolchain.dep_files == DepFiles("per_class")),
+    )
+
+    # this is required for the Kotlin compiler to be able to use jspecify annotations
+    extra_kotlinc_arguments = ["-Xjspecify-annotations=strict"] + extra_kotlinc_arguments
+
+    kotlin_extra_params = _encode_kotlin_extra_params(
+        kotlin_toolchain = kotlin_toolchain,
+        kotlin_compiler_plugins = kotlin_compiler_plugins,
+        extra_kotlinc_arguments = extra_kotlinc_arguments,
+        bootclasspath_entries = bootclasspath_entries,
+        bootclasspath_snapshot_entries = bootclasspath_snapshot_entries,
+        friend_paths = friend_paths,
+        target_level = target_level,
+        should_use_jvm_abi_gen = should_use_jvm_abi_gen,
+        kosabi_applicability_cell_root = kosabi_applicability_cell_root,
+        should_kotlinc_run_incrementally = should_kotlinc_run_incrementally,
+        should_ksp2_run_incrementally = should_ksp2_run_incrementally,
+        incremental_state_dir = incremental_state_dir,
+        language_version = language_version,
+        source_only_abi_applicability_classpath = source_only_abi_applicability_classpath,
+    )
+
+    library_command_builder = command_builder(
+        kotlin_extra_params = kotlin_extra_params,
+        provide_classpath_snapshot = should_kotlinc_run_incrementally,
+        incremental_metadata_ignored_inputs_tag = incremental_metadata_ignored_inputs_tag
+        if should_kotlinc_run_incrementally or should_ksp2_run_incrementally
+        else None,
+    )
+    command = library_command_builder(
+        build_mode = BuildMode("LIBRARY"),
+        target_type = TargetType("library"),
+        output_paths = output_paths,
+        classpath_jars_tag = library_classpath_jars_tag,
+        source_only_abi_compiling_deps = None,
+        track_class_usage = track_class_usage,
+    )
+    proto, used_jars_json = define_kotlincd_action(
+        category_prefix = "",
+        actions_identifier = actions_identifier,
+        encoded_command = command,
+        qualified_name = base_qualified_name(label),
+        output_paths = output_paths,
+        classpath_jars_tag = library_classpath_jars_tag,
+        abi_dir = class_abi_output_dir if should_create_class_abi else None,
+        target_type = TargetType("library"),
+        is_creating_subtarget = is_creating_subtarget,
+        incremental_state_dir = incremental_state_dir,
+        should_action_run_incrementally = should_kotlinc_run_incrementally or should_ksp2_run_incrementally,
+    )
+
+    final_jar_output = prepare_final_jar(
+        actions = actions,
+        actions_identifier = actions_identifier,
+        output_paths = output_paths,
+        output = None,
+        additional_compiled_srcs = None,
+        jar_builder = java_toolchain.jar_builder,
+        jar_postprocessor = jar_postprocessor,
+        jar_postprocessor_runner = java_toolchain.postprocessor_runner[RunInfo] if java_toolchain.postprocessor_runner else None,
+        zip_scrubber = java_toolchain.zip_scrubber,
+        uses_content_based_paths = uses_content_based_paths,
+        postprocessor_merged_into_compile_action = jar_postprocessor != None,
+    )
+
+    if not is_creating_subtarget:
+        kotlin_extra_params_builder = partial(
+            _encode_kotlin_extra_params,
+            kotlin_toolchain = kotlin_toolchain,
+            kotlin_compiler_plugins = kotlin_compiler_plugins,
+            extra_kotlinc_arguments = extra_kotlinc_arguments,
+            bootclasspath_entries = bootclasspath_entries,
+            bootclasspath_snapshot_entries = bootclasspath_snapshot_entries,
+            friend_paths = friend_paths,
+            target_level = target_level,
+            should_use_jvm_abi_gen = should_use_jvm_abi_gen,
+            kosabi_applicability_cell_root = None,
+            should_kotlinc_run_incrementally = False,
+            should_ksp2_run_incrementally = False,
+            incremental_state_dir = None,
+            language_version = language_version,
+            source_only_abi_applicability_classpath = cmd_args(),
+        )
+
+        # kotlincd does not support source abi
+        class_abi, _, source_only_abi, classpath_abi, classpath_abi_dir = generate_abi_jars(
+            actions = actions,
+            actions_identifier = actions_identifier,
+            label = label,
+            abi_generation_mode = actual_abi_generation_mode,
+            additional_compiled_srcs = None,
+            is_building_android_binary = is_building_android_binary,
+            class_abi_generator = java_toolchain.class_abi_generator,
+            final_jar = final_jar_output.final_jar,
+            compiling_deps_tset = compiling_deps_tset,
+            source_only_abi_deps = source_only_abi_deps,
+            class_abi_jar = class_abi_jar,
+            class_abi_output_dir = class_abi_output_dir,
+            track_class_usage = True,
+            encode_abi_command = command_builder,
+            define_action = define_kotlincd_action,
+            uses_content_based_paths = uses_content_based_paths,
+            kotlin_extra_params_builder = kotlin_extra_params_builder,
+            source_only_abi_compiling_deps = so_abi_deps,
+        )
+        abi_jar_snapshot = generate_java_classpath_snapshot(
+            actions, java_toolchain.cp_snapshot_generator, ClasspathSnapshotGranularity("CLASS_MEMBER_LEVEL"), classpath_abi, actions_identifier
+        )
+        tracking_outputs = {}
+        if files_which_skipped_compilation:
+            tracking_outputs["files_which_skipped_compilation"] = files_which_skipped_compilation
+        if jvm_abi_files_which_skipped_compilation:
+            tracking_outputs["jvm_abi_files_which_skipped_compilation"] = jvm_abi_files_which_skipped_compilation
+        return (
+            make_compile_outputs(
+                full_library = final_jar_output.final_jar,
+                preprocessed_library = final_jar_output.preprocessed_jar,
+                class_abi = class_abi,
+                source_only_abi = source_only_abi,
+                classpath_abi = classpath_abi,
+                classpath_abi_dir = classpath_abi_dir,
+                required_for_source_only_abi = required_for_source_only_abi,
+                annotation_processor_output = output_paths.annotations,
+                incremental_state_dir = incremental_state_dir,
+                abi_jar_snapshot = abi_jar_snapshot,
+                used_jars_json = used_jars_json,
+            ),
+            proto,
+            tracking_outputs,
+        )
+    else:
+        full_jar_snapshot = generate_java_classpath_snapshot(
+            actions, java_toolchain.cp_snapshot_generator, ClasspathSnapshotGranularity("CLASS_MEMBER_LEVEL"), final_jar_output.final_jar, actions_identifier
+        )
+        return (
+            make_compile_outputs(
+                full_library = final_jar_output.final_jar,
+                preprocessed_library = final_jar_output.preprocessed_jar,
+                required_for_source_only_abi = required_for_source_only_abi,
+                annotation_processor_output = output_paths.annotations,
+                abi_jar_snapshot = full_jar_snapshot,
+                used_jars_json = used_jars_json,
+            ),
+            proto,
+            {},
+        )
+
+def _encode_kotlin_extra_params(
+    kotlin_toolchain: KotlinToolchainInfo,
+    kotlin_compiler_plugins: list[(Dependency, dict[str, [str, cmd_args]])],
+    extra_kotlinc_arguments: list,
+    bootclasspath_entries: list[Artifact],
+    bootclasspath_snapshot_entries: list[Artifact],
+    friend_paths: list[Dependency],
+    target_level: int,
+    should_use_jvm_abi_gen: bool,
+    kosabi_applicability_cell_root,
+    should_kotlinc_run_incrementally: bool,
+    should_ksp2_run_incrementally: bool,
+    incremental_state_dir: Artifact | None,
+    language_version: str,
+    source_only_abi_applicability_classpath: cmd_args = cmd_args(),
+):
+    kosabiPluginOptionsMap = {}
+
+    if kotlin_toolchain.kosabi_stubs_gen_k2_plugin != None:
+        kosabiPluginOptionsMap["kosabi_stubs_gen_k2_plugin"] = kotlin_toolchain.kosabi_stubs_gen_k2_plugin
+
+    if kotlin_toolchain.kosabi_applicability_plugin != None:
+        kosabiPluginOptionsMap["kosabi_applicability_plugin"] = kotlin_toolchain.kosabi_applicability_plugin
+
+    if kosabi_applicability_cell_root != None:
+        kosabiPluginOptionsMap["kosabi_applicability_cell_root"] = cmd_args(kosabi_applicability_cell_root, delimiter = "")
+
+    if kotlin_toolchain.kosabi_jvm_abi_gen_k2_plugin != None:
+        kosabiPluginOptionsMap["kosabi_jvm_abi_gen_k2_plugin"] = kotlin_toolchain.kosabi_jvm_abi_gen_k2_plugin
+
+    return struct(
+        extraClassPaths = bootclasspath_entries,
+        extraClassPathSnapshots = bootclasspath_snapshot_entries if should_kotlinc_run_incrementally else [],
+        standardLibraryClassPath = kotlin_toolchain.kotlin_stdlib[JavaLibraryInfo].library_output.full_library,
+        annotationProcessingClassPath = kotlin_toolchain.annotation_processing_jar[JavaLibraryInfo].library_output.full_library,
+        jvmAbiGenPlugin = kotlin_toolchain.jvm_abi_gen_plugin,
+        kotlinCompilerPlugins = {plugin[DefaultInfo].default_outputs[0]: {"params": plugin_options} for plugin, plugin_options in kotlin_compiler_plugins},
+        kosabiPluginOptions = struct(**kosabiPluginOptionsMap),
+        friendPaths = [friend_path.library_output.abi for friend_path in map_idx(JavaLibraryInfo, friend_paths) if friend_path.library_output],
+        kotlinHomeLibraries = kotlin_toolchain.kotlin_home_libraries,
+        jvmTarget = get_kotlinc_compatible_target(str(target_level)),
+        shouldUseJvmAbiGen = should_use_jvm_abi_gen,
+        shouldVerifySourceOnlyAbiConstraints = kosabi_applicability_cell_root != None,
+        extraKotlincArguments = extra_kotlinc_arguments,
+        depTrackerPlugin = kotlin_toolchain.track_class_usage_plugin,
+        shouldKotlincRunIncrementally = should_kotlinc_run_incrementally,
+        shouldKsp2RunIncrementally = should_ksp2_run_incrementally,
+        incrementalStateDir = incremental_state_dir.as_output() if incremental_state_dir else None,
+        languageVersion = language_version,
+        javaBinary = cmd_args(kotlin_toolchain.java_binary_for_kotlincd[RunInfo], delimiter = " ") if kotlin_toolchain.java_binary_for_kotlincd else "",
+        applicabilityClasspath = source_only_abi_applicability_classpath,
+    )
+
+def _command_builder(
+    label: Label,
+    srcs: list[Artifact],
+    remove_classes: list[str],
+    annotation_processor_properties: AnnotationProcessorProperties,
+    plugin_params: [PluginParams, None],
+    manifest_file: Artifact | None,
+    source_level: int,
+    target_level: int,
+    compiling_deps_tset: [JavaCompilingDepsTSet, None],
+    bootclasspath_entries: list[Artifact],
+    system_image: Artifact | None,
+    abi_generation_mode: AbiGenerationMode,
+    resources_map: dict[str, Artifact],
+    extra_arguments: cmd_args,
+    use_abi_dirs: bool,
+):
+    return partial(
+        _encode_kotlin_command,
+        label = label,
+        srcs = srcs,
+        remove_classes = remove_classes,
+        annotation_processor_properties = annotation_processor_properties,
+        plugin_params = plugin_params,
+        manifest_file = manifest_file,
+        source_level = source_level,
+        target_level = target_level,
+        compiling_deps_tset = compiling_deps_tset,
+        bootclasspath_entries = bootclasspath_entries,
+        system_image = system_image,
+        abi_generation_mode = abi_generation_mode,
+        resources_map = resources_map,
+        extra_arguments = extra_arguments,
+        use_abi_dirs = use_abi_dirs,
+    )
+
+def _encode_kotlin_command(
+    label: Label,
+    srcs: list[Artifact],
+    remove_classes: list[str],
+    annotation_processor_properties: AnnotationProcessorProperties,
+    plugin_params: [PluginParams, None],
+    manifest_file: Artifact | None,
+    source_level: int,
+    target_level: int,
+    compiling_deps_tset: [JavaCompilingDepsTSet, None],
+    bootclasspath_entries: list[Artifact],
+    system_image: Artifact | None,
+    abi_generation_mode: AbiGenerationMode,
+    resources_map: dict[str, Artifact],
+    extra_arguments: cmd_args,
+    kotlin_extra_params: [struct, None],
+    provide_classpath_snapshot: bool,
+    use_abi_dirs: bool,
+    incremental_metadata_ignored_inputs_tag: ArtifactTag | None = None,
+):
+    return partial(
+        encode_command,
+        label = label,
+        srcs = srcs,
+        remove_classes = remove_classes,
+        annotation_processor_properties = annotation_processor_properties,
+        plugin_params = plugin_params,
+        manifest_file = manifest_file,
+        source_level = source_level,
+        target_level = target_level,
+        compiling_deps_tset = compiling_deps_tset,
+        bootclasspath_entries = bootclasspath_entries,
+        system_image = system_image,
+        abi_generation_mode = abi_generation_mode,
+        resources_map = resources_map,
+        extra_arguments = extra_arguments,
+        kotlin_extra_params = kotlin_extra_params,
+        provide_classpath_snapshot = provide_classpath_snapshot,
+        use_abi_dirs = use_abi_dirs,
+        incremental_metadata_ignored_inputs_tag = incremental_metadata_ignored_inputs_tag,
+    )
+
+# buildifier: disable=uninitialized
+# buildifier: disable=unused-variable
+def _define_kotlincd_action(
+    # provided by factory
+    actions: AnalysisActions,
+    java_toolchain: JavaToolchainInfo,
+    kotlin_toolchain: KotlinToolchainInfo,
+    srcs: list[Artifact],
+    should_create_class_abi: bool,
+    class_abi_jar: [Artifact, None],
+    jvm_abi_gen: [cmd_args, None],
+    class_abi_output_dir: [Artifact, None],
+    optional_dirs: list[OutputArtifact],
+    track_class_usage: bool,
+    compiling_deps_tset: [JavaCompilingDepsTSet, None],
+    debug_port: [int, None],
+    uses_content_based_paths: bool,
+    incremental_metadata_ignored_inputs_tag: ArtifactTag,
+    jar_postprocessor: [RunInfo, None],
+    files_which_skipped_compilation: [Artifact, None],
+    jvm_abi_files_which_skipped_compilation: [Artifact, None],
+    # end of factory provided
+    category_prefix: str,
+    actions_identifier: [str, None],
+    encoded_command: struct,
+    qualified_name: str,
+    output_paths: OutputPaths,
+    classpath_jars_tag: ArtifactTag,
+    abi_dir: Artifact | None,
+    target_type: TargetType,
+    is_creating_subtarget: bool = False,
+    incremental_state_dir: Artifact | None = None,
+    should_action_run_incrementally: bool = False,
+):
+    compiler = kotlin_toolchain.kotlincd[DefaultInfo].default_outputs[0]
+    exe, local_only = prepare_cd_exe(
+        qualified_name,
+        java = java_toolchain.java[RunInfo],
+        class_loader_bootstrapper = kotlin_toolchain.class_loader_bootstrapper,
+        compiler = compiler,
+        main_class = kotlin_toolchain.kotlincd_main_class,
+        worker = kotlin_toolchain.kotlincd_worker[WorkerInfo] if kotlin_toolchain.kotlincd_worker else None,
+        remote_worker = kotlin_toolchain.kotlincd_remote_worker[WorkerInfo] if kotlin_toolchain.kotlincd_remote_worker else None,
+        target_specified_debug_port = debug_port,
+        toolchain_specified_debug_port = kotlin_toolchain.kotlincd_debug_port,
+        toolchain_specified_debug_target = kotlin_toolchain.kotlincd_debug_target,
+        extra_jvm_args = kotlin_toolchain.kotlincd_jvm_args,
+        extra_jvm_args_target = kotlin_toolchain.kotlincd_jvm_args_target,
+        java_runtime_version = java_toolchain.java_runtime_version,
+    )
+
+    args = cmd_args()
+    post_build_params = {}
+    if target_type == TargetType("library") and should_create_class_abi:
+        post_build_params["shouldCreateClassAbi"] = True
+        post_build_params["libraryJar"] = output_paths.jar.as_output()
+        post_build_params["abiJar"] = class_abi_jar.as_output()
+        post_build_params["jvmAbiGen"] = jvm_abi_gen
+        post_build_params["abiOutputDir"] = class_abi_output_dir.as_output()
+
+    if target_type == TargetType("source_abi") or target_type == TargetType("source_only_abi"):
+        post_build_params["abiJar"] = output_paths.jar.as_output()
+        post_build_params["abiOutputDir"] = abi_dir.as_output()
+
+    if optional_dirs:
+        post_build_params["optionalDirs"] = optional_dirs
+
+    if incremental_state_dir:
+        post_build_params["incrementalStateDir"] = incremental_state_dir.as_output()
+
+    if target_type == TargetType("library") and files_which_skipped_compilation:
+        post_build_params["filesWhichSkippedCompilation"] = files_which_skipped_compilation.as_output()
+    if target_type == TargetType("library") and jvm_abi_files_which_skipped_compilation:
+        post_build_params["jvmAbiFilesWhichSkippedCompilation"] = jvm_abi_files_which_skipped_compilation.as_output()
+
+    if jar_postprocessor and target_type == TargetType("library"):
+        if "libraryJar" not in post_build_params:
+            post_build_params["libraryJar"] = output_paths.jar.as_output()
+        post_build_params["postProcessorCmd"] = cmd_args(jar_postprocessor, delimiter = " ")
+
+    dep_files = {}
+    used_jars_json_output = None
+    if (
+        not is_creating_subtarget
+        and srcs
+        and (kotlin_toolchain.dep_files == DepFiles("per_jar") or kotlin_toolchain.dep_files == DepFiles("per_class"))
+        and track_class_usage
+    ):
+        used_classes_json_outputs = [
+            cmd_args(output_paths.jar.as_output(), format = "{}/used-classes.json", parent = 1),
+            cmd_args(output_paths.jar.as_output(), format = "{}/kotlin-used-classes.json", parent = 1),
+        ]
+        if target_type == TargetType("library"):
+            used_jars_json_output = declare_prefixed_output(actions, actions_identifier, "jar/used-jars.json", uses_content_based_paths)
+        if should_action_run_incrementally and kotlin_toolchain.dep_files == DepFiles("per_class") and compiling_deps_tset:
+            # The combined projection is excluded from incremental metadata to avoid
+            # enumerating ABI directories; the incremental compiler still needs the jars.
+            args.add(classpath_jars_tag.tag_artifacts(cmd_args(hidden = compiling_deps_tset.project_as_args("args_for_compiling", ordering = "topological"))))
+        setup_dep_files(
+            actions,
+            actions_identifier,
+            post_build_params,
+            classpath_jars_tag,
+            used_classes_json_outputs,
+            used_jars_json_output,
+            uses_content_based_paths,
+        )
+
+        dep_files["classpath_jars"] = classpath_jars_tag
+
+    kotlin_build_command = struct(
+        buildCommand = encoded_command,
+        postBuildParams = post_build_params,
+    )
+
+    proto = declare_prefixed_output(actions, actions_identifier, "jar_command.proto.json", uses_content_based_paths)
+    dep_file_fingerprints = []
+    if dep_files:
+        proto, fingerprint = actions.write_json(
+            proto,
+            kotlin_build_command,
+            dep_files_fingerprint_using_canonical_paths = True,
+        )
+        proto_for_args = classpath_jars_tag.tag_artifacts(proto)
+        dep_file_fingerprints.append(fingerprint)
+    else:
+        proto_for_args = actions.write_json(proto, kotlin_build_command, with_inputs = True)
+
+    args.add(
+        "--action-id",
+        qualified_name,
+        "--command-file",
+        proto_for_args,
+    )
+
+    if should_action_run_incrementally:
+        args.add(
+            "--incremental-config-file",
+            _create_incremental_config(actions, actions_identifier, kotlin_build_command, kotlin_toolchain.kotlin_version, uses_content_based_paths),
+        )
+
+    incremental_run_params = (
+        {
+            "incremental_metadata_ignore_tags": [incremental_metadata_ignored_inputs_tag],
+            "metadata_env_var": "ACTION_METADATA",
+            "metadata_path": "action_metadata.json",
+            "no_outputs_cleanup": True,
+        }
+        if should_action_run_incrementally
+        else {}
+    )
+    actions.run(
+        args,
+        env = {
+            "BUCK_CLASSPATH": compiler,
+            "JAVACD_ABSOLUTE_PATHS_ARE_RELATIVE_TO_CWD": "1",
+        },
+        category = "{}kotlincd_jar".format(category_prefix),
+        identifier = actions_identifier,
+        dep_files = dep_files,
+        dep_file_fingerprints = dep_file_fingerprints,
+        allow_dep_file_cache_upload = True,
+        allow_cache_upload = True,
+        exe = exe,
+        local_only = local_only,
+        low_pass_filter = False,
+        weight = 2,
+        error_handler = kotlin_toolchain.kotlin_error_handler,
+        **incremental_run_params,
+    )
+    return proto, used_jars_json_output
+
+def _create_incremental_config(
+    actions: AnalysisActions, actions_identifier: [str, None], kotlin_build_command: struct, kotlin_version: str, uses_content_based_paths: bool
+):
+    incremental_meta_data_output = declare_prefixed_output(actions, actions_identifier, "incremental_config.json", uses_content_based_paths)
+    incremental_meta_data = struct(
+        version = 3,
+        track_class_usage = kotlin_build_command.buildCommand.baseJarCommand.trackClassUsage,
+        should_use_jvm_abi_gen = kotlin_build_command.buildCommand.kotlinExtraParams.shouldUseJvmAbiGen,
+        extra_kotlinc_arguments = kotlin_build_command.buildCommand.kotlinExtraParams.extraKotlincArguments,
+        kotlin_version = kotlin_version,
+    )
+    return actions.write_json(incremental_meta_data_output, incremental_meta_data, with_inputs = True)
diff --git a/buck2/prelude/kotlin/tools/compile_kotlin/BUCK b/buck2/prelude/kotlin/tools/compile_kotlin/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/tools/compile_kotlin/BUCK
@@ -0,0 +1,16 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "compile_kotlin",
+    main = "compile_kotlin.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//java/tools:utils_lib",
+    ],
+)
diff --git a/buck2/prelude/kotlin/tools/compile_kotlin/compile_kotlin.py b/buck2/prelude/kotlin/tools/compile_kotlin/compile_kotlin.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/tools/compile_kotlin/compile_kotlin.py
@@ -0,0 +1,743 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+
+import argparse
+import os
+import pathlib
+import shlex
+import shutil
+import subprocess
+import sys
+import zipfile
+from tempfile import TemporaryDirectory
+from typing import List
+
+import utils
+
+_JAVA_OR_KOTLIN_FILE_EXTENSION = [".java", ".kt"]
+
+_PLUGIN = "-P"
+_X_PLUGIN_ARG = "-Xplugin"
+_KAPT3_PLUGIN = "plugin:org.jetbrains.kotlin.kapt3:"
+_APT_MODE_STUBS_AND_APT = _KAPT3_PLUGIN + "aptMode=stubsAndApt"
+_AP_CLASSPATH_ARG = _KAPT3_PLUGIN + "apclasspath"
+_AP_PROCESSORS_ARG = _KAPT3_PLUGIN + "processors"
+_SOURCES_ARG = _KAPT3_PLUGIN + "sources"
+_CLASSES_ARG = _KAPT3_PLUGIN + "classes"
+_STUBS_ARG = _KAPT3_PLUGIN + "stubs"
+_KAPT_GENERATED_ARG = "kapt.kotlin.generated"
+_LIGHT_ANALYSIS = _KAPT3_PLUGIN + "useLightAnalysis"
+_CORRECT_ERROR_TYPES = _KAPT3_PLUGIN + "correctErrorTypes"
+_AP_OPTIONS = _KAPT3_PLUGIN + "apoptions"
+_JAVAC_ARG = _KAPT3_PLUGIN + "javacArguments"
+_KAPT_USE_K2 = _KAPT3_PLUGIN + "useK2"
+_X_USE_K2_KAPT = "-Xuse-k2-kapt"
+
+_KSP_PLUGIN = "plugin:com.google.devtools.ksp.symbol-processing:"
+_KSP_AP_CLASSPATH_ARG = _KSP_PLUGIN + "apclasspath"
+_KSP_PROJECT_BASE_DIR_ARG = _KSP_PLUGIN + "projectBaseDir"
+_ksp_classes_and_resources_output_ARG = _KSP_PLUGIN + "classOutputDir"
+_KSP_KOTLIN_OUTPUT_ARG = _KSP_PLUGIN + "kotlinOutputDir"
+_KSP_JAVA_OUTPUT_ARG = _KSP_PLUGIN + "javaOutputDir"
+_KSP_RESOURCE_OUTPUT_ARG = _KSP_PLUGIN + "resourceOutputDir"
+_KSP_CACHES_DIR_ARG = _KSP_PLUGIN + "cachesDir"
+_KSP_OUTPUT_ARG = _KSP_PLUGIN + "kspOutputDir"
+_KSP_INCREMENTAL_ARG = _KSP_PLUGIN + "incremental"
+_KSP_WITH_COMPILATION_ARG = _KSP_PLUGIN + "withCompilation"
+
+
+def _parse_args():
+    parser = argparse.ArgumentParser(description="Tool to compile kotlin source files.")
+
+    parser.add_argument(
+        "--kotlinc_cmd_file",
+        type=pathlib.Path,
+        required=False,
+        metavar="kotlinc_cmd_file",
+        help="path to file with the command that should be run for compilation",
+    )
+    parser.add_argument(
+        "--kotlinc_output",
+        type=pathlib.Path,
+        required=False,
+        metavar="kotlinc_output",
+        help="path to .class files produced by running kotlinc",
+    )
+    parser.add_argument(
+        "--zipped_sources_file",
+        type=pathlib.Path,
+        required=False,
+        metavar="zipped_sources_file",
+        help="path to file with stored zipped source files that need to be passed to kotlin compiler",
+    )
+    parser.add_argument(
+        "--kapt_annotation_processing_jar",
+        type=str,
+        required=False,
+        metavar="kapt_annotation_processing_jar",
+        help="annotation processing jar used by KAPT",
+    )
+    parser.add_argument(
+        "--kapt_annotation_processors",
+        type=str,
+        required=False,
+        metavar="kapt_annotation_processors",
+        help="comma separated list of annotation processors to be run by KAPT",
+    )
+    parser.add_argument(
+        "--kapt_annotation_processor_params",
+        type=str,
+        required=False,
+        metavar="kapt_annotation_processor_params",
+        help="comma separated list of annotation processor params to be passed to KAPT",
+    )
+    parser.add_argument(
+        "--kapt_classpath_file",
+        type=pathlib.Path,
+        required=False,
+        metavar="kapt_classpath_file",
+        help="path to file with the classpath that should be used for KAPT",
+    )
+    parser.add_argument(
+        "--kapt_sources_output",
+        type=pathlib.Path,
+        required=False,
+        metavar="kapt_sources_output",
+        help="path where kapt-generated sources should be written",
+    )
+    parser.add_argument(
+        "--kapt_generated_sources_output",
+        type=pathlib.Path,
+        required=False,
+        metavar="kapt_generated_sources_output",
+        help="path generated sources should be zipped",
+    )
+    parser.add_argument(
+        "--kapt_classes_output",
+        type=pathlib.Path,
+        required=False,
+        metavar="kapt_classes_output",
+        help="path where kapt-generated classes should be written",
+    )
+    parser.add_argument(
+        "--kapt_stubs",
+        type=pathlib.Path,
+        required=False,
+        metavar="kapt_stubs",
+        help="path where kapt-generated stubs should be written",
+    )
+    parser.add_argument(
+        "--kapt_base64_encoder",
+        type=str,
+        required=False,
+        metavar="kapt_base64_encoder",
+        help="tool for doing base64 encoding for KAPT",
+    )
+    parser.add_argument(
+        "--kapt_generated_kotlin_output",
+        type=pathlib.Path,
+        required=False,
+        metavar="kapt_generated_kotlin_output",
+        help="path where kapt-generated kotlin output should be written",
+    )
+    parser.add_argument(
+        "--kapt_jvm_target",
+        type=str,
+        required=False,
+        metavar="kapt_jvm_target",
+        help="JVM target to use for KAPT call",
+    )
+    parser.add_argument(
+        "--ksp_processor_jars",
+        type=str,
+        required=False,
+        metavar="ksp_processor_jars",
+        help="comma separated list of jars containing KSP annotation processors",
+    )
+    parser.add_argument(
+        "--ksp_classpath",
+        type=str,
+        required=False,
+        metavar="ksp_classpath",
+        help="classpath to be passed to KSP (so that it can find the resources it needs)",
+    )
+    parser.add_argument(
+        "--ksp_classes_and_resources_output",
+        type=pathlib.Path,
+        required=False,
+        metavar="ksp_classes_and_resources_output",
+        help="path where ksp-generated classes and resources should be written",
+    )
+    parser.add_argument(
+        "--ksp_sources_output",
+        type=pathlib.Path,
+        required=False,
+        metavar="ksp_sources_output",
+        help="path where ksp-generated Java and Kotlin sources should be written",
+    )
+    parser.add_argument(
+        "--ksp_zipped_sources_output",
+        type=pathlib.Path,
+        required=False,
+        metavar="ksp_zipped_sources_output",
+        help="path where zipped ksp-generated Java and Kotlin sources should be written",
+    )
+    parser.add_argument(
+        "--ksp_output",
+        type=pathlib.Path,
+        required=False,
+        metavar="ksp_output",
+        help="root of KSP output dirs",
+    )
+    parser.add_argument(
+        "--ksp_project_base_dir",
+        type=pathlib.Path,
+        required=False,
+        metavar="ksp_project_base_dir",
+        help="project dir for this KSP invocation",
+    )
+    parser.add_argument(
+        "--ksp_generated_classes_and_resources",
+        type=pathlib.Path,
+        required=False,
+        metavar="ksp_generated_classes_and_resources",
+        help="classes and resources that were generated by a previous invocation of KSP",
+    )
+    parser.add_argument(
+        "--kotlin_compiler_plugin_dir",
+        type=pathlib.Path,
+        required=False,
+        metavar="kotlin_compiler_plugin_dir",
+        help="Directory for KAPT compiler plugins to use",
+    )
+    parser.add_argument(
+        "--zip_scrubber",
+        required=True,
+        help="tool for scrubbing timestamps from zip files to produce deterministic output",
+    )
+    parser.add_argument(
+        "--jdk_locator",
+        type=pathlib.Path,
+        required=False,
+        metavar="jdk_locator",
+        help="Path to Python script that extracts JAVA_HOME from javac binary",
+    )
+    parser.add_argument(
+        "--java_binary",
+        type=pathlib.Path,
+        required=False,
+        metavar="java_binary",
+        help="Path to java or javac binary for JDK home derivation",
+    )
+    return parser.parse_args()
+
+
+def _get_jdk_home(jdk_locator: pathlib.Path, java_binary: pathlib.Path) -> str:
+    """Get JDK home by invoking jdk_locator with java binary."""
+    try:
+        if (
+            jdk_locator
+            and java_binary
+            and jdk_locator.exists()
+            and java_binary.exists()
+        ):
+            result = subprocess.run(
+                [str(jdk_locator), str(java_binary)],
+                capture_output=True,
+                text=True,
+                check=True,
+            )
+            java_home = result.stdout.strip()
+            if java_home and os.path.isdir(java_home):
+                return java_home
+            utils.log_message("jdk_locator returned invalid path: {}".format(java_home))
+    except Exception as e:
+        utils.log_message("Failed to get JDK home from jdk_locator: {}".format(e))
+    return None
+
+
+def _run_kotlinc(
+    kotlinc_output: pathlib.Path,
+    kotlinc_cmd_file: pathlib.Path,
+    zipped_sources_file: pathlib.Path,
+    ksp_cmd: List[str],
+    kapt_cmd: List[str],
+    kapt_generated_kotlin_output: pathlib.Path,
+    kapt_sources_output: pathlib.Path,
+    temp_dir: TemporaryDirectory,
+    java_binary: pathlib.Path = None,
+    jdk_locator: pathlib.Path = None,
+) -> pathlib.Path:
+    cmd_file = kotlinc_cmd_file
+    if zipped_sources_file:
+        cmd_file = utils.extract_source_files(
+            zipped_sources_file,
+            kotlinc_cmd_file,
+            _JAVA_OR_KOTLIN_FILE_EXTENSION,
+            temp_dir,
+        )
+
+    if not utils.sources_are_present(cmd_file, [".kt"]):
+        os.mkdir(kotlinc_output)
+        return kotlinc_output
+
+    with open(cmd_file, "r") as file:
+        base_cmd = [line.strip() for line in file.readlines()]
+
+    # Derive JAVA_HOME using jdk_locator + java_binary
+    jdk_args = []
+    jdk_home = _get_jdk_home(jdk_locator, java_binary)
+    if jdk_home:
+        utils.log_message("Derived JAVA_HOME from jdk_locator: {}".format(jdk_home))
+        jdk_args = ["-jdk-home", jdk_home]
+
+    def _exec_kotlinc(cmd: List[str]) -> None:
+        utils.log_message(
+            "executing command = '{}'".format(
+                " ".join([shlex.quote(str(s)) for s in cmd])
+            )
+        )
+        p = subprocess.run(cmd, stderr=subprocess.PIPE, text=True)
+        if p.returncode != 0:
+            print(utils.pretty_exception_k(p.stderr), file=sys.stderr)
+            sys.exit(p.returncode)
+
+    if kapt_cmd:
+        # KAPT runs in 'stubsAndApt' mode (the only mode supported on Kotlin 2.x): it
+        # generates Java/Kotlin sources from annotation processors but, unlike the
+        # legacy 'compile' mode, does NOT emit the final Kotlin bytecode. So we invoke
+        # kotlinc twice: first to run annotation processing, then a separate final
+        # compilation that actually produces the Kotlin classes. The generated *Java*
+        # sources are compiled downstream by javac; the generated *Kotlin* sources are
+        # folded into this final compilation so they end up in the Kotlin output.
+        ap_output = os.path.join(temp_dir, "kapt_ap_output")
+        os.mkdir(ap_output)
+        if kapt_generated_kotlin_output and not os.path.exists(
+            kapt_generated_kotlin_output
+        ):
+            os.makedirs(kapt_generated_kotlin_output)
+        _exec_kotlinc(base_cmd + ksp_cmd + kapt_cmd + jdk_args + ["-d", ap_output])
+
+        final_cmd = list(base_cmd) + jdk_args
+        # The final Kotlin compilation must see the sources KAPT generated so it can
+        # resolve references to generated types (e.g. Dagger components, databinding
+        # *BindingImpl). Generated Kotlin is compiled into the Kotlin output; generated
+        # Java is passed only for symbol resolution (kotlinc does not emit bytecode for
+        # .java inputs) and is compiled downstream by javac.
+        for gen_dir in (kapt_generated_kotlin_output, kapt_sources_output):
+            if gen_dir and os.path.isdir(gen_dir):
+                final_cmd += [
+                    str(path)
+                    for ext in ("*.kt", "*.java")
+                    for path in pathlib.Path(gen_dir).rglob(ext)
+                ]
+        if kotlinc_output:
+            final_cmd += ["-d", kotlinc_output]
+        _exec_kotlinc(final_cmd)
+    else:
+        kotlinc_cmd = base_cmd + ksp_cmd + jdk_args
+        if kotlinc_output:
+            kotlinc_cmd += ["-d", kotlinc_output]
+        _exec_kotlinc(kotlinc_cmd)
+
+    return kotlinc_output
+
+
+def _encode_kapt_ap_options(
+    kapt_annotation_processor_params: str,
+    kapt_base64_encoder_cmd: List[str],
+    kapt_generated_kotlin_output: pathlib.Path,
+    temp_dir: TemporaryDirectory,
+) -> str:
+    ap_options_file = os.path.join(temp_dir, "ap_options.txt")
+    with open(ap_options_file, "w") as file:
+        file.write(
+            "{}={}".format(_KAPT_GENERATED_ARG, str(kapt_generated_kotlin_output))
+        )
+        if kapt_annotation_processor_params:
+            for param in kapt_annotation_processor_params.split(";"):
+                file.write("\n")
+                file.write(param)
+
+    encoded_ap_options_file = os.path.join(temp_dir, "encoded_ap_options.txt")
+    return _encode_options(
+        kapt_base64_encoder_cmd, ap_options_file, encoded_ap_options_file
+    )
+
+
+def _encode_javac_arguments(
+    jvm_target: str | None,
+    kapt_base64_encoder_cmd: List[str],
+    temp_dir: TemporaryDirectory,
+) -> str:
+    javac_arguments_file = os.path.join(temp_dir, "javac_arguments.txt")
+    with open(javac_arguments_file, "w") as file:
+        # An empty file encodes to an empty option map, which leaves KAPT's javac
+        # on its own defaults. Writing a blank line instead would crash the encoder.
+        if jvm_target:
+            file.write("-source={}\n-target={}".format(jvm_target, jvm_target))
+
+    encoded_javac_arguments_file = os.path.join(temp_dir, "encoded_javac_arguments.txt")
+    return _encode_options(
+        kapt_base64_encoder_cmd, javac_arguments_file, encoded_javac_arguments_file
+    )
+
+
+def _encode_options(
+    kapt_base64_encoder_cmd: List[str],
+    options_file: pathlib.Path,
+    encoded_options_file: pathlib.Path,
+) -> str:
+    cmd = kapt_base64_encoder_cmd + [options_file, encoded_options_file]
+
+    utils.execute_command(cmd)
+
+    with open(encoded_options_file, "r") as file:
+        return file.read().strip()
+
+
+def _get_language_version(kotlinc_cmd_file: pathlib.Path) -> str | None:
+    with open(kotlinc_cmd_file, "r") as file:
+        kotlinc_args = [line.strip() for line in file.readlines()]
+
+    for index, arg in enumerate(kotlinc_args):
+        if arg.startswith("-language-version="):
+            return arg.split("=", 1)[1]
+        if arg == "-language-version" and index + 1 < len(kotlinc_args):
+            return kotlinc_args[index + 1]
+
+    return None
+
+
+def _get_k2_kapt_flag(kotlinc_cmd_file: pathlib.Path) -> str | None:
+    language_version = _get_language_version(kotlinc_cmd_file)
+    if not language_version:
+        return None
+
+    version_parts = language_version.split(".")
+    try:
+        version_tuple = tuple(int(part) for part in version_parts[:2])
+    except ValueError:
+        return None
+
+    return _X_USE_K2_KAPT if version_tuple >= (2, 1) else None
+
+
+def _get_kapt_cmd(
+    kotlinc_cmd_file: pathlib.Path,
+    kapt_annotation_processing_jar: pathlib.Path,
+    kapt_annotation_processors: str,
+    kapt_annotation_processor_params: str,
+    kapt_classpath_file: pathlib.Path,
+    kapt_sources_output: pathlib.Path,
+    kapt_classes_output: pathlib.Path,
+    kapt_stubs: pathlib.Path,
+    kapt_base64_encoder: pathlib.Path,
+    kapt_generated_kotlin_output: pathlib.Path,
+    kapt_jvm_target: str | None,
+    temp_dir: TemporaryDirectory,
+) -> List[str]:
+    if not kapt_annotation_processors:
+        return []
+
+    kapt_plugin_options = [_APT_MODE_STUBS_AND_APT]
+    k2_kapt_flag = _get_k2_kapt_flag(kotlinc_cmd_file)
+    if k2_kapt_flag:
+        kapt_plugin_options.append("=".join([_KAPT_USE_K2, "true"]))
+    kapt_plugin_options += [
+        "=".join([_AP_PROCESSORS_ARG, ap])
+        for ap in kapt_annotation_processors.split(",")
+    ]
+    with open(kapt_classpath_file, "r") as file:
+        kapt_plugin_options += [
+            "=".join([_AP_CLASSPATH_ARG, line.strip()]) for line in file.readlines()
+        ]
+
+    kapt_base64_encoder_cmd = utils.shlex_split(kapt_base64_encoder)
+    kapt_plugin_options += [
+        "=".join([_SOURCES_ARG, str(kapt_sources_output)]),
+        "=".join([_CLASSES_ARG, str(kapt_classes_output)]),
+        "=".join([_STUBS_ARG, str(kapt_stubs)]),
+        "=".join([_LIGHT_ANALYSIS, "true"]),
+        "=".join([_CORRECT_ERROR_TYPES, "true"]),
+        "=".join(
+            [
+                _AP_OPTIONS,
+                _encode_kapt_ap_options(
+                    kapt_annotation_processor_params,
+                    kapt_base64_encoder_cmd,
+                    kapt_generated_kotlin_output,
+                    temp_dir,
+                ),
+            ]
+        ),
+        "=".join(
+            [
+                _JAVAC_ARG,
+                _encode_javac_arguments(
+                    kapt_jvm_target, kapt_base64_encoder_cmd, temp_dir
+                ),
+            ]
+        ),
+    ]
+
+    kapt_cmd = [
+        "=".join([_X_PLUGIN_ARG, str(kapt_annotation_processing_jar)]),
+        _PLUGIN,
+        ",".join(kapt_plugin_options),
+    ]
+    if k2_kapt_flag:
+        kapt_cmd.append(k2_kapt_flag)
+    return kapt_cmd
+
+
+def _get_ksp_cmd(
+    ksp_processors_jars: str,
+    ksp_classpath: str,
+    ksp_project_base_dir: pathlib.Path,
+    base_ksp_output_dir: pathlib.Path,
+    ksp_classes_and_resources_output: pathlib.Path,
+    ksp_sources_output: pathlib.Path,
+) -> List[str]:
+    if not ksp_processors_jars:
+        return []
+
+    ksp_plugin_options = [
+        "{}={}".format(
+            _KSP_AP_CLASSPATH_ARG, os.pathsep.join(ksp_processors_jars.split(","))
+        ),
+        "{}={}".format(_KSP_PLUGIN + "apoption=cp", ksp_classpath),
+        "{}={}".format(_KSP_PROJECT_BASE_DIR_ARG, ksp_project_base_dir.resolve()),
+        "{}={}".format(
+            _ksp_classes_and_resources_output_ARG,
+            ksp_classes_and_resources_output.resolve(),
+        ),
+        "{}={}".format(_KSP_KOTLIN_OUTPUT_ARG, ksp_sources_output.resolve()),
+        "{}={}".format(_KSP_JAVA_OUTPUT_ARG, ksp_sources_output.resolve()),
+        "{}={}".format(
+            _KSP_RESOURCE_OUTPUT_ARG, ksp_classes_and_resources_output.resolve()
+        ),
+        "{}={}".format(_KSP_OUTPUT_ARG, base_ksp_output_dir.resolve()),
+        "{}={}".format(_KSP_CACHES_DIR_ARG, base_ksp_output_dir.resolve()),
+        "{}={}".format(_KSP_INCREMENTAL_ARG, False),
+        "{}={}".format(_KSP_WITH_COMPILATION_ARG, False),
+    ]
+
+    return [
+        _PLUGIN,
+        ",".join(ksp_plugin_options),
+    ]
+
+
+def _zip_recursive(archive_path: pathlib.Path, source_path: pathlib.Path):
+    # Same as 'zip -r archive_path source_path'
+    with zipfile.ZipFile(
+        archive_path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6
+    ) as z:
+        z.write(source_path)
+        for f in source_path.glob("**/*"):
+            z.write(f)
+
+
+def main():
+    args = _parse_args()
+
+    output_path = args.kotlinc_output
+    kotlinc_cmd_file = args.kotlinc_cmd_file
+    zipped_sources_file = args.zipped_sources_file
+    kapt_annotation_processing_jar = args.kapt_annotation_processing_jar
+    kapt_annotation_processors = args.kapt_annotation_processors
+    kapt_annotation_processor_params = args.kapt_annotation_processor_params
+    kapt_classpath_file = args.kapt_classpath_file
+    kapt_sources_output = args.kapt_sources_output
+    kapt_classes_output = args.kapt_classes_output
+    kapt_generated_sources_output = args.kapt_generated_sources_output
+    kapt_stubs = args.kapt_stubs
+    kapt_base64_encoder = args.kapt_base64_encoder
+    kapt_generated_kotlin_output = args.kapt_generated_kotlin_output
+    kapt_jvm_target = args.kapt_jvm_target
+    kotlin_compiler_plugin_dir = args.kotlin_compiler_plugin_dir
+    ksp_processor_jars = args.ksp_processor_jars
+    ksp_classpath = args.ksp_classpath
+    ksp_output = args.ksp_output
+    ksp_project_base_dir = args.ksp_project_base_dir
+    ksp_classes_and_resources_output = args.ksp_classes_and_resources_output
+    ksp_sources_output = args.ksp_sources_output
+    ksp_zipped_sources_output = args.ksp_zipped_sources_output
+    ksp_generated_classes_and_resources = args.ksp_generated_classes_and_resources
+    zip_scrubber = args.zip_scrubber
+    jdk_locator = args.jdk_locator
+    java_binary = args.java_binary
+
+    utils.log_message("output: {}".format(output_path))
+    utils.log_message("kotlinc_cmd_file: {}".format(kotlinc_cmd_file))
+    if zipped_sources_file:
+        utils.log_message("zipped_sources_file: {}".format(zipped_sources_file))
+    utils.log_message(
+        "kapt_annotation_processing_jar: {}".format(kapt_annotation_processing_jar)
+    )
+    utils.log_message(
+        "kapt_annotation_processors: {}".format(kapt_annotation_processors)
+    )
+    utils.log_message(
+        "kapt_annotation_processor_params: {}".format(kapt_annotation_processor_params)
+    )
+    utils.log_message("kapt_classpath_file: {}".format(kapt_classpath_file))
+    utils.log_message("kapt_sources_output: {}".format(kapt_sources_output))
+    utils.log_message(
+        "kapt_generated_sources_output: {}".format(kapt_generated_sources_output)
+    )
+    utils.log_message("kapt_classes_output: {}".format(kapt_classes_output))
+    utils.log_message("kapt_stubs: {}".format(kapt_stubs))
+    utils.log_message("kapt_base64_encoder: {}".format(kapt_base64_encoder))
+    utils.log_message(
+        "kapt_generated_kotlin_output: {}".format(kapt_generated_kotlin_output)
+    )
+    utils.log_message("kapt_jvm_target: {}".format(kapt_jvm_target))
+    utils.log_message(
+        "kotlin_compiler_plugin_dir: {}".format(kotlin_compiler_plugin_dir)
+    )
+    utils.log_message("ksp_processor_jars: {}".format(ksp_processor_jars))
+    utils.log_message("ksp_classpath: {}".format(ksp_classpath))
+    utils.log_message("ksp_output: {}".format(ksp_output))
+    utils.log_message("ksp_project_base_dir: {}".format(ksp_project_base_dir))
+    utils.log_message(
+        "ksp_classes_and_resources_output: {}".format(ksp_classes_and_resources_output)
+    )
+    utils.log_message("ksp_sources_output: {}".format(ksp_sources_output))
+    utils.log_message("ksp_zipped_sources_output: {}".format(ksp_zipped_sources_output))
+    utils.log_message(
+        "ksp_generated_classes_and_resources: {}".format(
+            ksp_generated_classes_and_resources
+        )
+    )
+    utils.log_message("zip_scrubber: {}".format(zip_scrubber))
+    utils.log_message("jdk_locator: {}".format(jdk_locator))
+    utils.log_message("java_binary: {}".format(java_binary))
+
+    if (
+        kapt_annotation_processing_jar
+        or kapt_annotation_processors
+        or kapt_classpath_file
+        or kapt_sources_output
+        or kapt_classes_output
+        or kapt_generated_sources_output
+        or kapt_stubs
+        or kapt_base64_encoder
+        or kapt_generated_kotlin_output
+        or kapt_jvm_target
+    ):
+        assert (
+            kapt_annotation_processing_jar
+            and kapt_annotation_processors
+            and kapt_classpath_file
+            and kapt_sources_output
+            and kapt_classes_output
+            and kapt_generated_sources_output
+            and kapt_stubs
+            and kapt_base64_encoder
+            and kapt_generated_kotlin_output
+        )
+    if (
+        ksp_processor_jars
+        or ksp_classpath
+        or ksp_output
+        or ksp_project_base_dir
+        or ksp_classes_and_resources_output
+        or ksp_sources_output
+        or ksp_zipped_sources_output
+    ):
+        assert (
+            ksp_processor_jars
+            and ksp_classpath
+            and ksp_output
+            and ksp_project_base_dir
+            and ksp_classes_and_resources_output
+            and ksp_sources_output
+            and ksp_zipped_sources_output
+        )
+
+    with TemporaryDirectory() as temp_dir:
+        ksp_cmd = _get_ksp_cmd(
+            ksp_processor_jars,
+            ksp_classpath,
+            ksp_project_base_dir,
+            ksp_output,
+            ksp_classes_and_resources_output,
+            ksp_sources_output,
+        )
+        kapt_cmd = _get_kapt_cmd(
+            kotlinc_cmd_file,
+            kapt_annotation_processing_jar,
+            kapt_annotation_processors,
+            kapt_annotation_processor_params,
+            kapt_classpath_file,
+            kapt_sources_output,
+            kapt_classes_output,
+            kapt_stubs,
+            kapt_base64_encoder,
+            kapt_generated_kotlin_output,
+            kapt_jvm_target,
+            temp_dir,
+        )
+        _run_kotlinc(
+            output_path,
+            kotlinc_cmd_file,
+            zipped_sources_file,
+            ksp_cmd,
+            kapt_cmd,
+            kapt_generated_kotlin_output,
+            kapt_sources_output,
+            temp_dir,
+            java_binary,
+            jdk_locator,
+        )
+
+    if ksp_sources_output:
+        if not ksp_sources_output.exists():
+            ksp_sources_output.mkdir()
+        _zip_recursive(ksp_zipped_sources_output, ksp_sources_output)
+        utils.execute_command(
+            utils.shlex_split(zip_scrubber) + [ksp_zipped_sources_output]
+        )
+
+    if ksp_classes_and_resources_output:
+        if not ksp_classes_and_resources_output.exists():
+            ksp_classes_and_resources_output.mkdir()
+    if kapt_sources_output:
+        if not os.path.exists(kapt_sources_output):
+            os.mkdir(kapt_sources_output)
+            kapt_generated_sources_output.touch()
+        else:
+            _zip_recursive(kapt_generated_sources_output, kapt_sources_output)
+            utils.execute_command(
+                utils.shlex_split(zip_scrubber) + [kapt_generated_sources_output]
+            )
+
+    if kapt_classes_output:
+        if not os.path.exists(kapt_classes_output):
+            os.mkdir(kapt_classes_output)
+        else:
+            shutil.copytree(kapt_classes_output, output_path, dirs_exist_ok=True)
+    if kapt_stubs and not os.path.exists(kapt_stubs):
+        os.mkdir(kapt_stubs)
+    if kapt_generated_kotlin_output and not os.path.exists(
+        kapt_generated_kotlin_output
+    ):
+        os.mkdir(kapt_generated_kotlin_output)
+    if kotlin_compiler_plugin_dir and not kotlin_compiler_plugin_dir.exists():
+        kotlin_compiler_plugin_dir.mkdir()
+    if ksp_generated_classes_and_resources:
+        shutil.copytree(
+            ksp_generated_classes_and_resources, output_path, dirs_exist_ok=True
+        )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/kotlin/tools/defs.bzl b/buck2/prelude/kotlin/tools/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/tools/defs.bzl
@@ -0,0 +1,56 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Wrappers for native rules that use a minimal "bootstrap" toolchain instead of the full toolchain.
+
+Use these to break cycles when a target used in a toolchain needs that toolchain to compile. Such targets
+provide functionality that is not strictly required in order to build, and thus can be omitted from the
+bootstrap toolchain. For example, an ABI generator for Java can be written in Java and compiled with a
+bootstrap toolchain that does not include an ABI generator. While using that bootstrap toolchain, buck2
+will just use the full JARs as ABI jars, which will be slower and result in some unnecessary recompilation,
+but still produce valid results.
+"""
+
+load("@prelude//:prelude.bzl", "native")
+
+def java_bootstrap_binary(**kwargs):
+    kwargs = _set_bootstrap_java_toolchain(**kwargs)
+    native.java_binary(**kwargs)
+
+def java_bootstrap_library(**kwargs):
+    kwargs = _set_bootstrap_java_toolchain(**kwargs)
+    kwargs = _set_dex_toolchain(**kwargs)
+    native.java_library(**kwargs)
+
+def kotlin_bootstrap_library(**kwargs):
+    kwargs = _set_bootstrap_java_toolchain(**kwargs)
+    kwargs = _set_bootstrap_kotlin_toolchain(**kwargs)
+    kwargs = _set_dex_toolchain(**kwargs)
+    native.kotlin_library(**kwargs)
+
+def prebuilt_jar_bootstrap(**kwargs):
+    kwargs["_prebuilt_jar_toolchain"] = "toolchains//:prebuilt_jar_bootstrap"
+    native.prebuilt_jar(**kwargs)
+
+def _set_bootstrap_java_toolchain(**kwargs):
+    kwargs["_java_toolchain"] = "toolchains//:java_bootstrap"
+    return kwargs
+
+def _set_bootstrap_kotlin_toolchain(**kwargs):
+    kwargs["_kotlin_toolchain"] = "toolchains//:kotlin_bootstrap"
+    return kwargs
+
+def _set_dex_toolchain(**kwargs):
+    # Override dex toolchain to avoid dependency cycles in unconfigured graph
+    dex_toolchain = kwargs.pop("_dex_toolchain", None)
+    kwargs["_dex_toolchain"] = dex_toolchain or select({
+        "DEFAULT": "toolchains//:empty_dex",
+        "config//os/constraints:android": "toolchains//:dex",
+    })
+    return kwargs
diff --git a/buck2/prelude/kotlin/tools/kapt_base64_encoder/BUCK b/buck2/prelude/kotlin/tools/kapt_base64_encoder/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/tools/kapt_base64_encoder/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//kotlin/tools:defs.bzl", "java_bootstrap_binary", "java_bootstrap_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+java_bootstrap_library(
+    name = "kapt_base64_encoder_lib",
+    srcs = [
+        "com/facebook/kapt/KaptBase64Encoder.java",
+    ],
+    source = "11",
+    target = "11",
+)
+
+java_bootstrap_binary(
+    name = "kapt_base64_encoder",
+    main_class = "com.facebook.kapt.KaptBase64Encoder",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":kapt_base64_encoder_lib",
+    ],
+)
diff --git a/buck2/prelude/kotlin/tools/kapt_base64_encoder/com/facebook/kapt/KaptBase64Encoder.java b/buck2/prelude/kotlin/tools/kapt_base64_encoder/com/facebook/kapt/KaptBase64Encoder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/kotlin/tools/kapt_base64_encoder/com/facebook/kapt/KaptBase64Encoder.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kapt;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Main entry point for encoding KAPT options in base64. Usage:
+ * <param_key1=param_val1,param_key2=param_val2> <output_path>
+ */
+public class KaptBase64Encoder {
+
+  public static void main(String[] args) throws IOException {
+    String optionsFile = args[0];
+    String outputPath = args[1];
+    List<String> params = Files.readAllLines(Paths.get(optionsFile));
+
+    try (ByteArrayOutputStream os = new ByteArrayOutputStream();
+        ObjectOutputStream oos = new ObjectOutputStream(os)) {
+
+      oos.writeInt(params.size());
+      for (String param : params) {
+        String[] splitParam = param.split("=");
+        oos.writeUTF(splitParam[0]);
+        oos.writeUTF(splitParam[1]);
+      }
+
+      oos.flush();
+      Files.write(
+          Paths.get(outputPath),
+          Collections.singleton(Base64.getEncoder().encodeToString(os.toByteArray())));
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+
+    System.exit(0);
+  }
+}
diff --git a/buck2/prelude/linking/add_elf_sections.bzl b/buck2/prelude/linking/add_elf_sections.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/add_elf_sections.bzl
@@ -0,0 +1,108 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_library_utility.bzl",
+    "cxx_is_gnu",
+)
+
+# Sections are added after BOLT but before build info stamping, so a target
+# with `elf_sections` carries this suffix outside of `PRE_STAMPED_SUFFIX`.
+PRE_ADD_ELF_SECTIONS_SUFFIX = "-pre_sectioned"
+
+def _validate_section_name(name: str):
+    if not name:
+        fail("ELF section names must not be empty")
+    if "=" in name:
+        fail("ELF section names must not contain `=`: `{}`".format(name))
+
+def add_elf_sections(ctx: AnalysisContext, obj: Artifact, sections: dict[str, Artifact], output: Artifact, category: str) -> Artifact:
+    """
+    Copy `obj` to `output`, adding each entry of `sections` as an ELF section
+    named by its key holding the contents of its value.
+
+    Sections added this way are not allocated, so they cost file size but not
+    resident memory in the running binary.
+    """
+    toolchain = get_cxx_toolchain_info(ctx)
+
+    cmd = cmd_args(toolchain.binary_utilities_info.objcopy)
+    for name, content in sections.items():
+        _validate_section_name(name)
+        cmd.add("--add-section", cmd_args(content, format = "{}={{}}".format(name)))
+    cmd.add(obj, output.as_output())
+
+    # objcopy rewrites the whole file. This can be run remotely, but it's often
+    # cheaper to do it locally for large binaries, especially on CI using
+    # limited hybrid.
+    prefer_local = not getattr(ctx.attrs, "optimize_for_action_throughput", False)
+
+    ctx.actions.run(
+        cmd,
+        identifier = obj.short_path,
+        category = category,
+        prefer_local = prefer_local,
+        prefer_remote = not prefer_local,
+        allow_cache_upload = toolchain.cxx_compiler_info.allow_cache_upload,
+    )
+
+    return output
+
+def extract_elf_section(ctx: AnalysisContext, obj: Artifact, name: str) -> Artifact:
+    _validate_section_name(name)
+    toolchain = get_cxx_toolchain_info(ctx)
+    output = ctx.actions.declare_output(
+        "{}-{}.section".format(obj.short_path, name),
+        has_content_based_path = False,
+    )
+    ctx.actions.run(
+        cmd_args(
+            toolchain.binary_utilities_info.objcopy,
+            "--dump-section",
+            cmd_args(output.as_output(), format = name + "={}"),
+            obj,
+        ),
+        category = "extract_elf_section",
+        identifier = obj.short_path,
+    )
+    return output
+
+def get_elf_sections(ctx: AnalysisContext) -> dict[str, Artifact]:
+    """
+    The rule's `elf_sections`, or empty for rules that do not have the attr.
+    """
+    return getattr(ctx.attrs, "elf_sections", None) or {}
+
+def add_elf_sections_to_executable(ctx: AnalysisContext, obj: Artifact, has_content_based_path: bool = False) -> Artifact:
+    """
+    Add the rule's `elf_sections` to a linked executable, if it has any.
+
+    `obj` is expected to still carry `PRE_ADD_ELF_SECTIONS_SUFFIX`; the result
+    drops it, so the next stage of the link sees the name it would have seen had
+    the target declared no sections.
+    """
+    sections = get_elf_sections(ctx)
+    if not sections:
+        return obj
+
+    if not cxx_is_gnu(ctx):
+        fail("`elf_sections` is only supported for GNU ELF binaries")
+
+    stem, ext = paths.split_extension(obj.short_path)
+    if not stem.endswith(PRE_ADD_ELF_SECTIONS_SUFFIX):
+        fail("expected `{}` to end in `{}`".format(obj.short_path, PRE_ADD_ELF_SECTIONS_SUFFIX))
+
+    return add_elf_sections(
+        ctx,
+        obj,
+        sections,
+        ctx.actions.declare_output(stem.removesuffix(PRE_ADD_ELF_SECTIONS_SUFFIX) + ext, has_content_based_path = has_content_based_path),
+        category = "add_elf_sections",
+    )
diff --git a/buck2/prelude/linking/execution_preference.bzl b/buck2/prelude/linking/execution_preference.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/execution_preference.bzl
@@ -0,0 +1,85 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_library_utility.bzl", "cxx_attr_deps", "cxx_attr_exported_deps")
+load("@prelude//utils:actions.bzl", "ActionExecutionAttributes")
+
+LinkExecutionPreferenceTypes = [
+    "any",
+    "full_hybrid",
+    "local",
+    "local_only",
+    "remote",
+]
+
+LinkExecutionPreference = enum(*LinkExecutionPreferenceTypes)
+
+LinkExecutionPreferenceDeterminatorInfo = provider(
+    fields = {
+        # function that takes a list of target labels and the LinkExecutionPreferenceInfo of deps, and returns a LinkExecutionPreference
+        "preference_for_links": provider_field(typing.Any, default = None),
+    }
+)
+
+LinkExecutionPreferenceInfo = provider(
+    fields = {
+        "preference": provider_field(typing.Any, default = None),  # LinkExecutionPreference
+    }
+)
+
+def link_execution_preference_attr():
+    # The attribute is optional, allowing for None to represent that no preference has been set and we should fallback on the toolchain.
+    return attrs.option(
+        attrs.one_of(attrs.enum(LinkExecutionPreferenceTypes), attrs.dep(providers = [LinkExecutionPreferenceDeterminatorInfo])),
+        default = None,
+        doc = """
+    The execution preference for linking. Options are:
+
+    - any : No preference is set, and the link action will be performed based on buck2's executor configuration.
+    - full_hybrid : The link action will execute both locally and remotely, regardless of buck2's executor configuration (if
+        the executor is capable of hybrid execution). The use_limited_hybrid setting of the hybrid executor is ignored.
+    - local : The link action will execute locally if compatible on current host platform.
+    - local_only : The link action will execute locally, and error if the current platform is not compatible.
+    - remote : The link action will execute remotely if a compatible remote platform exists, otherwise locally.
+
+    The default is None, expressing that no preference has been set on the target itself.
+    """,
+    )
+
+def get_link_execution_preference(ctx, links: list[Label]) -> LinkExecutionPreference:
+    if not hasattr(ctx.attrs, "link_execution_preference"):
+        fail("`get_link_execution_preference` called on a rule that does not support link_execution_preference!")
+
+    link_execution_preference = ctx.attrs.link_execution_preference
+
+    # If no preference has been set, we default to any.
+    if not link_execution_preference:
+        return LinkExecutionPreference("any")
+
+    if not isinstance(link_execution_preference, Dependency):
+        return LinkExecutionPreference(link_execution_preference)
+
+    all_deps = cxx_attr_deps(ctx) + cxx_attr_exported_deps(ctx)
+    deps_preferences = filter(None, [dep.get(LinkExecutionPreferenceInfo) for dep in all_deps])
+
+    info = link_execution_preference[LinkExecutionPreferenceDeterminatorInfo]
+    return info.preference_for_links(links, deps_preferences)
+
+def get_action_execution_attributes(preference: LinkExecutionPreference) -> ActionExecutionAttributes:
+    if preference == LinkExecutionPreference("any"):
+        return ActionExecutionAttributes()
+    elif preference == LinkExecutionPreference("full_hybrid"):
+        return ActionExecutionAttributes(full_hybrid = True)
+    elif preference == LinkExecutionPreference("local"):
+        return ActionExecutionAttributes(prefer_local = True)
+    elif preference == LinkExecutionPreference("local_only"):
+        return ActionExecutionAttributes(local_only = True)
+    elif preference == LinkExecutionPreference("remote"):
+        return ActionExecutionAttributes(prefer_remote = True)
+    else:
+        fail("Unhandled LinkExecutionPreference: {}".format(str(preference)))
diff --git a/buck2/prelude/linking/generated_build_info.bzl b/buck2/prelude/linking/generated_build_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/generated_build_info.bzl
@@ -0,0 +1,330 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifact_tset.bzl", "make_artifact_tset")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//cxx:cxx_library.bzl", "cxx_compile_srcs")
+load("@prelude//cxx:cxx_sources.bzl", "CxxSrcWithFlags")
+load("@prelude//cxx:cxx_types.bzl", "CxxRuleConstructorParams")
+load("@prelude//cxx:headers.bzl", "CxxHeadersLayout", "CxxHeadersNaming")
+load("@prelude//cxx:link.bzl", "cxx_link_shared_library")
+load("@prelude//cxx:link_types.bzl", "link_options")
+load("@prelude//cxx:shared_library_interface.bzl", "shared_library_interface")
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkArgs",
+    "LinkInfo",
+    "ObjectsLinkable",
+    "SharedLibLinkable",
+    "unpack_link_args_metadata",
+    "wrap_with_no_as_needed_shared_libs_flags",
+)
+load("@prelude//linking:shared_libraries.bzl", "SharedLibrary", "create_shlib")
+load("@prelude//linking:types.bzl", "Linkage")
+
+GeneratedBuildInfo = record(
+    json = Artifact,
+    linker_flags = list[typing.Any],
+    manifest_entries = field(Artifact | None, None),
+    source = Artifact,
+)
+
+GeneratedBuildInfoData = record(
+    json = Artifact,
+    manifest_entries = field(Artifact | None, None),
+)
+
+GeneratedBuildInfoCompileOutput = record(
+    external_debug_info = list[Artifact],
+    objects = list[Artifact],
+)
+
+# Action-output-relative dir for generated build-info artifacts. Consumers use
+# it to locate the linked DSO next to the binaries that link it.
+GENERATED_BUILD_INFO_OUTPUT_DIR = "__generated_build_info__"
+
+_REQUIRED_GENERATED_BUILD_INFO_FIELDS = [
+    "allow_cache_upload",
+    "base_linker_flags",
+    "enabled",
+    "exported_symbols",
+    "final_linker_flags",
+    "finalize_build_info_at_link",
+    "local_only",
+]
+
+GeneratedBuildInfoInvalidationInfo = provider(
+    fields = {
+        "inputs": provider_field(typing.Any),
+    },
+)
+
+GeneratedBuildInfoSharedLibrary = record(
+    json = Artifact,
+    library = SharedLibrary,
+    link_args = LinkArgs,
+    manifest_entries = field(Artifact | None, None),
+)
+
+def compile_generated_build_info(ctx: AnalysisContext, info: GeneratedBuildInfo) -> GeneratedBuildInfoCompileOutput:
+    cxx_toolchain_info = get_cxx_toolchain_info(ctx)
+
+    # `-fno-whole-program-vtables` is a Clang-only flag; GCC errors out on it.
+    src_flags = ["-fno-lto"]
+    if cxx_toolchain_info.c_compiler_info.compiler_type in ["clang", "clang_windows", "clang_cl"]:
+        src_flags = ["-fno-whole-program-vtables"] + src_flags
+
+    compiled = cxx_compile_srcs(
+        actions = ctx.actions,
+        target_label = ctx.label,
+        cxx_toolchain_info = cxx_toolchain_info,
+        impl_params = CxxRuleConstructorParams(
+            rule_type = "generated_build_info",
+            headers_layout = CxxHeadersLayout(
+                namespace = "",
+                naming = CxxHeadersNaming("regular"),
+            ),
+            srcs = [CxxSrcWithFlags(file = info.source, flags = src_flags)],
+            _cxx_toolchain = ctx.attrs._cxx_toolchain,
+        ),
+        own_preprocessors = [],
+        inherited_non_exported_preprocessor_infos = [],
+        inherited_exported_preprocessor_infos = [],
+        preferred_linkage = Linkage("shared"),
+        add_coverage_instrumentation_compiler_flags = False,
+        filename_prefix = "generated_build_info_",
+    )
+    return GeneratedBuildInfoCompileOutput(
+        external_debug_info = (compiled.pic.external_debug_info + (compiled.pic.objects if compiled.pic.objects_have_external_debug_info else [])),
+        objects = compiled.pic.objects,
+    )
+
+# Expected `_generated_build_info_spec` shape:
+# {
+#     "<generator-owned-field>": <JSON-compatible value>,
+# }
+# Generator-owned fields remain at the top level so configured selectors are
+# resolved before the specification is serialized.
+def _generated_build_info_config(ctx: AnalysisContext):
+    spec = dict(getattr(ctx.attrs, "_generated_build_info_spec", {}))
+    configured_enabled = getattr(ctx.attrs, "_generated_build_info_enabled", None)
+    if configured_enabled != None:
+        if not configured_enabled:
+            return None
+        if not spec:
+            fail("generated build-info spec is missing")
+
+        mode = ctx.attrs._generated_build_info_mode
+        spec["allow_cache_upload"] = mode != "full"
+        spec["build_info"] = mode
+        spec["enabled"] = True
+        spec["final_linker_flags"] = ["--build-info={}".format(mode)]
+        spec["local_only"] = mode == "full"
+    elif not spec or not spec.get("enabled", False):
+        return None
+
+    missing_fields = [field for field in _REQUIRED_GENERATED_BUILD_INFO_FIELDS if field not in spec]
+    if missing_fields:
+        fail("generated build-info spec is missing required fields: {}".format(", ".join(missing_fields)))
+
+    tool = getattr(ctx.attrs, "_gen_build_info", None)
+    if tool == None:
+        fail("_gen_build_info must be set when generated build info is enabled")
+    return (spec, tool[RunInfo])
+
+def _generate_build_info_data(
+    ctx: AnalysisContext,
+    spec,
+    tool: RunInfo,
+    generator_args: list[typing.Any] = [],
+    invalidation_inputs: list[typing.Any] = [],
+) -> GeneratedBuildInfoData:
+    output_dir = GENERATED_BUILD_INFO_OUTPUT_DIR
+    json = getattr(ctx.attrs, "_generated_build_info_data", None)
+    if json != None and spec.get("emit_manifest_entries", False):
+        fail("supplied generated build-info data does not provide manifest entries")
+    manifest_entries = None
+    # A caller that supplies the JSON artifact owns its invalidation edges;
+    # `invalidation_inputs` apply only when this rule generates the JSON.
+    if json == None:
+        generator_spec = ctx.actions.write_json(
+            output_dir + "/generator_spec.json",
+            spec,
+        )
+        json = ctx.actions.declare_output(output_dir, "build_info.json")
+        manifest_entries = ctx.actions.declare_output(output_dir, "manifest_entries.json") if spec.get("emit_manifest_entries", False) else None
+        command = cmd_args(
+            tool,
+            generator_args,
+            "--spec-json",
+            generator_spec,
+            "--output-json",
+            json.as_output(),
+        )
+        if manifest_entries != None:
+            command.add("--output-manifest-entries", manifest_entries.as_output())
+        command.add(cmd_args(hidden = invalidation_inputs))
+        ctx.actions.run(
+            command,
+            category = "generate_build_info_json",
+            local_only = spec["local_only"],
+            allow_cache_upload = spec["allow_cache_upload"],
+        )
+    return GeneratedBuildInfoData(
+        json = json,
+        manifest_entries = manifest_entries,
+    )
+
+def generate_build_info_data(
+    ctx: AnalysisContext,
+    generator_args: list[typing.Any] = [],
+    invalidation_inputs: list[typing.Any] = [],
+) -> GeneratedBuildInfoData | None:
+    config = _generated_build_info_config(ctx)
+    if config == None:
+        return None
+    spec, tool = config
+    return _generate_build_info_data(
+        ctx,
+        spec,
+        tool,
+        generator_args = generator_args,
+        invalidation_inputs = invalidation_inputs,
+    )
+
+# Expected `_generated_build_info_spec` shape:
+# {
+#     "<action-owned-field>": <JSON-compatible value>,
+# }
+# Generator arguments are supplied separately so callers can reuse existing
+# configurable argument lists without expanding them into this dictionary.
+def generate_build_info(
+    ctx: AnalysisContext,
+    invalidation_inputs: list[typing.Any] = [],
+    generator_args: list[typing.Any] = [],
+) -> GeneratedBuildInfo | None:
+    config = _generated_build_info_config(ctx)
+    if config == None:
+        return None
+    spec, tool = config
+    data = _generate_build_info_data(ctx, spec, tool, generator_args, invalidation_inputs)
+
+    output_dir = GENERATED_BUILD_INFO_OUTPUT_DIR
+    source = ctx.actions.declare_output(output_dir, "__buck2_generated_build_info.c")
+
+    ctx.actions.run(
+        cmd_args(
+            tool,
+            "--input-json",
+            data.json,
+            "--output-source",
+            source.as_output(),
+        ),
+        category = "generate_build_info_source",
+    )
+
+    json_linker_flags = (
+        (spec.get("final_linker_flags", []) + [cmd_args("--build-info-json=", data.json, delimiter = "")])
+        if spec.get("finalize_build_info_at_link", True)
+        else []
+    )
+    return GeneratedBuildInfo(
+        json = data.json,
+        linker_flags = json_linker_flags + spec["base_linker_flags"],
+        manifest_entries = data.manifest_entries,
+        source = source,
+    )
+
+def generate_build_info_shared_library(
+    ctx: AnalysisContext,
+    metadata_link_args: LinkArgs,
+    generator_args: list[typing.Any] = [],
+    invalidation_inputs: list[typing.Any] = [],
+) -> GeneratedBuildInfoSharedLibrary | None:
+    config = _generated_build_info_config(ctx)
+    if config == None:
+        return None
+    spec, _tool = config
+
+    info = generate_build_info(
+        ctx,
+        generator_args = generator_args
+        + [
+            cmd_args(
+                unpack_link_args_metadata(metadata_link_args),
+                format = "--build-info-link-metadata={}",
+            ),
+        ],
+        invalidation_inputs = invalidation_inputs,
+    )
+    if info == None:
+        return None
+
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    soname = "libgenerated_build_info.so"
+    compile_output = compile_generated_build_info(ctx, info)
+    exported_symbols = spec["exported_symbols"]
+    links = [
+        LinkArgs(
+            infos = [
+                LinkInfo(
+                    external_debug_info = make_artifact_tset(
+                        actions = ctx.actions,
+                        label = ctx.label,
+                        artifacts = compile_output.external_debug_info,
+                    ),
+                    pre_flags = info.linker_flags + ["-Wl,--export-dynamic-symbol={}".format(symbol) for symbol in exported_symbols],
+                    linkables = [
+                        ObjectsLinkable(
+                            objects = compile_output.objects,
+                            linker_type = linker_info.type,
+                            link_whole = True,
+                        ),
+                    ],
+                ),
+            ],
+        ),
+        LinkArgs(
+            flags = cmd_args(
+                unpack_link_args_metadata(metadata_link_args),
+                format = "--build-info-link-metadata={}",
+            ),
+        ),
+    ]
+    link_result = cxx_link_shared_library(
+        ctx = ctx,
+        output = "{}/{}".format(GENERATED_BUILD_INFO_OUTPUT_DIR, soname),
+        name = soname,
+        opts = link_options(
+            links = links,
+            link_execution_preference = LinkExecutionPreference("any"),
+            link_weight = linker_info.link_weight,
+        ),
+    )
+    interface = shared_library_interface(ctx, link_result.linked_object.output)
+    link_info = wrap_with_no_as_needed_shared_libs_flags(
+        linker_info.type,
+        LinkInfo(linkables = [SharedLibLinkable(lib = interface)]),
+    )
+    return GeneratedBuildInfoSharedLibrary(
+        json = info.json,
+        library = create_shlib(
+            label = ctx.label,
+            lib = link_result.linked_object,
+            soname = soname,
+        ),
+        link_args = LinkArgs(infos = [link_info]),
+        manifest_entries = info.manifest_entries,
+    )
+
+def generated_build_info_is_shared_library(ctx: AnalysisContext) -> bool:
+    spec = getattr(ctx.attrs, "_generated_build_info_spec", {})
+    configured_enabled = getattr(ctx.attrs, "_generated_build_info_enabled", None)
+    enabled = configured_enabled if configured_enabled != None else spec.get("enabled", False)
+    return bool(enabled and spec.get("link_as_shared_library", False))
diff --git a/buck2/prelude/linking/link_groups.bzl b/buck2/prelude/linking/link_groups.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/link_groups.bzl
@@ -0,0 +1,81 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//utils:dicts.bzl",
+    "flatten_x",
+)
+load(
+    ":link_info.bzl",
+    "LinkInfos",
+)
+load(
+    ":shared_libraries.bzl",
+    "SharedLibraries",
+)
+
+# Information about a linkable node which explicitly sets `link_group`.
+LinkGroupLib = record(
+    # The label of the owning target (if any).
+    label = field([Label, None], None),
+    # The shared libs to package for this link group.
+    shared_libs = field(SharedLibraries),
+    # The link info to link against this link group.
+    shared_link_infos = field(LinkInfos),
+)
+
+# Provider propagating info about transitive link group libs.
+LinkGroupLibInfo = provider(
+    fields = {
+        # A map of link group names to their shared libraries.
+        "libs": provider_field(typing.Any, default = None),  # dict[str, LinkGroupLib]
+    }
+)
+
+EMPTY_LINK_GROUP_LIB_INFO = LinkGroupLibInfo(libs = {})
+
+def gather_link_group_libs(
+    libs: list[dict[str, LinkGroupLib]] = [], children: list[LinkGroupLibInfo] = [], deps: list[Dependency] = []
+) -> dict[str, LinkGroupLib]:
+    """
+    Return all link groups libs deps and top-level libs.
+    """
+    return flatten_x(
+        (libs + [c.libs for c in children] + [d[LinkGroupLibInfo].libs for d in deps if LinkGroupLibInfo in d]),
+        fmt = 'conflicting link group roots for "{0}": {1} != {2}',
+    )
+
+def merge_link_group_lib_info(
+    label: [Label, None] = None,
+    name: [str, None] = None,
+    shared_libs: [SharedLibraries, None] = None,
+    shared_link_infos: [LinkInfos, None] = None,
+    deps: list[Dependency] = [],
+    children: list[LinkGroupLibInfo] = [],
+) -> LinkGroupLibInfo:
+    """
+    Merge and return link group info libs from deps and the current rule wrapped
+    in a provider.
+    """
+    libs = {}
+    if name != None:
+        libs[name] = LinkGroupLib(
+            label = label,
+            shared_libs = shared_libs,
+            shared_link_infos = shared_link_infos,
+        )
+    merged = gather_link_group_libs(
+        libs = [libs],
+        deps = deps,
+        children = children,
+    )
+    if not merged:
+        return EMPTY_LINK_GROUP_LIB_INFO
+    return LinkGroupLibInfo(
+        libs = merged,
+    )
diff --git a/buck2/prelude/linking/link_groups_explained.md b/buck2/prelude/linking/link_groups_explained.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/link_groups_explained.md
@@ -0,0 +1,974 @@
+# Link Groups Explained
+
+This document explains in detail how Buck2's link groups system works — all the
+options, how they interact, and what the resulting binaries look like. It's meant
+to be read top-to-bottom, with each section building on the previous.
+
+## What Link Groups Do
+
+Link groups partition a binary's native dependencies into separate shared
+libraries. Without link groups, a statically-linked binary is one giant
+executable. With link groups, selected subsets of the dependency graph are evicted
+into `.so` files, reducing the main binary size.
+
+```
+Without link groups:              With link groups:
+
+┌─────────────────────┐           ┌───────────────┐
+│      binary         │           │    binary     │
+│                     │           │   (smaller)   │
+│  lib_a              │           │  lib_ungrouped│
+│  lib_b              │           └──────┬────────┘
+│  lib_c              │                  │ DT_NEEDED
+│  lib_d              │           ┌──────┴─────────────┐
+│  lib_ungrouped      │           │                    │
+│  ...                │      ┌────▼─────┐        ┌─────▼────┐
+└─────────────────────┘      │libgroup_a│        │libgroup_b│
+                             │  lib_a   │        │  lib_c   │
+                             │  lib_b   │        │  lib_d   │
+                             └──────────┘        └──────────┘
+```
+
+## The Pipeline
+
+Link groups processing happens in a fixed sequence of phases:
+
+```
+┌──────────────────────────────────────────────────────────────┐
+│ Phase 0: Parse link_group_map attribute                      │
+│          → list[Group] with mappings, attrs, traversals      │
+└───────────────────────┬──────────────────────────────────────┘
+                        ▼
+┌──────────────────────────────────────────────────────────────┐
+│ Phase 1: Compute mappings (target → group)                   │
+│          For each mapping:                                    │
+│            1a. Discovery: find matching targets               │
+│                (_find_targets_in_mapping)                     │
+│            1b. Assignment: walk subtrees, assign to group     │
+│                (_update_target_to_group_mapping)              │
+│          → dict[Label, str]  (first-assignment-wins)         │
+└───────────────────────┬──────────────────────────────────────┘
+                        ▼
+┌──────────────────────────────────────────────────────────────┐
+│ Phase 2: Generate link group specs                           │
+│          → one LinkGroupLibSpec per shared library to create │
+└───────────────────────┬──────────────────────────────────────┘
+                        ▼
+┌──────────────────────────────────────────────────────────────┐
+│ Phase 3: Identify public nodes (cross-boundary targets)      │
+│          → set[Label] needing --whole-archive                │
+└───────────────────────┬──────────────────────────────────────┘
+                        ▼
+┌──────────────────────────────────────────────────────────────┐
+│ Phase 4: Find roots per group                                │
+│          → dict[group_name, set[Label]]                      │
+└───────────────────────┬──────────────────────────────────────┘
+                        ▼
+┌──────────────────────────────────────────────────────────────┐
+│ Phase 5: Collect linkables per group (DFS from roots)        │
+│          → dict[group_name, list[Label]]                     │
+└───────────────────────┬──────────────────────────────────────┘
+                        ▼
+┌──────────────────────────────────────────────────────────────┐
+│ Phase 6: Per-target decision logic                           │
+│          For each group + binary: decide how each target     │
+│          appears on the link line (static, shared, or ref)   │
+└───────────────────────┬──────────────────────────────────────┘
+                        ▼
+┌──────────────────────────────────────────────────────────────┐
+│ Phase 7: Link shared libraries + assemble symlink tree       │
+│          → final binary + .so files + runtime symlinks       │
+└──────────────────────────────────────────────────────────────┘
+```
+
+### Phase details
+
+**Phase 0: Parse `link_group_map`** (`parse_groups_definitions` in `groups.bzl`)
+
+Parses the `link_group_map` attribute into a `list[Group]`. Each group has a
+name, list of `GroupMapping`s (root, traversal, filter, linkage), and optional
+`GroupAttrs` (discard_group, linker_flags, enable_distributed_thinlto, etc.).
+Deduplicates groups by name (first definition wins). Filters out groups that
+don't meet `enable_if_node_count_exceeds` threshold.
+
+**Phase 1: Compute mappings** (`compute_mappings` in `groups.bzl`)
+
+Builds the `dict[Label, str]` mapping from target to group name. Described in
+detail under "How Phase 1 works" below. This is the only phase that uses
+traversal types and filters.
+
+**Phase 2: Generate link group specs** (caller-side, e.g. `cxx_executable.bzl`)
+
+Creates one `LinkGroupLibSpec` per shared library to be produced. Each spec
+has: an output name (the .so filename), a `Group` reference, an optional
+`LinkableRootInfo` (providing private linker flags, version scripts, etc.),
+and whether it's a real shared lib (with SONAME) or something else like a
+Python extension. The specs come from `auto_link_group_specs` on the rule,
+which are typically generated by the fbcode macro based on the link group map.
+
+**Phase 3: Identify public nodes** (`get_public_link_group_nodes` in
+`link_groups.bzl`)
+
+Finds all targets that are depended on across a link group boundary — i.e., a
+target in group A has a dep on a target in group B. These "public" targets
+need `--whole-archive` to ensure their symbols are exported from their group's
+.so, since the linker can't see cross-.so usage at static link time.
+
+Also transitively includes `exported_deps` of public nodes (since exported
+deps form part of the public API surface).
+
+**Phase 4: Find roots per group** (`_find_all_relevant_roots` in
+`link_groups.bzl`)
+
+Determines the DFS starting points for each group in Phase 5. Sources of roots:
+- Specs with explicit `root`: use `root.deps`
+- Specs without root: extract roots from the group's mappings, plus a full
+  graph DFS to discover additional roots for groups with rootless mappings or
+  when using shared link strategy
+- `MATCH_ALL` targets are added to every group's root set
+- `MATCH_DIRECT_DEPS` targets are added to a group if any member has a direct
+  dep on them
+- Force-static targets (`preferred_linkage = "static"`) are traversed through
+  unconditionally during root discovery (they always return `all_deps`)
+
+**Phase 5: Collect linkables per group** (`_collect_all_linkables` →
+`collect_linkables` in `link_groups.bzl`)
+
+For each group, does a DFS from that group's roots to discover all reachable
+linkable targets. The DFS uses `get_deps_for_link` to decide which edges to
+follow: for statically-linked nodes, follow all deps; for shared-linked nodes,
+follow only `exported_deps` (since the shared lib satisfies its own internal
+deps).
+
+The result is a `dict[group_name, list[Label]]` — the ordered list of targets
+that are candidates for each group's link line. This is the most expensive
+phase (see Performance Analysis in `link_groups.md`), because it does a
+separate full DFS per group with heavy overlap.
+
+**Phase 6: Per-target decision logic** (`get_filtered_labels_to_links_map` in
+`link_groups.bzl`)
+
+Called once per group (inside `_create_link_group`) plus once for the binary
+itself. For each target in the group's linkable list from Phase 5, decides how
+it appears on the link line:
+
+- **Same group** (or `MATCH_ALL` / `MATCH_DIRECT_DEPS`): statically linked
+  into this group
+- **Different group**: reference that group's .so (added once via `add_link_group`)
+- **Ungrouped / `NO_MATCH`**: statically linked into the binary (when linking
+  the binary's link line)
+- **`preferred_linkage = "shared"`**: linked as a pre-existing shared lib
+- **Force-static**: always statically linked, regardless of group assignment
+- **`discard_group`**: skipped entirely
+
+Also applies `--whole-archive` to public nodes (from Phase 3) and handles
+transformation specs (link info filtering/transformation per target).
+
+**Phase 7: Link shared libraries + assemble symlink tree**
+(`_create_link_group` → `cxx_link_shared_library`, then caller assembles
+symlink tree)
+
+For each group spec: produces the actual `cxx_link_shared_library` action with
+the link inputs from Phase 6, generates stub libraries, extracts symbol files
+(global/undefined) for version scripts, and creates shared library interfaces
+(on GNU). The caller then assembles the runtime symlink tree mapping sonames
+to the built .so files.
+
+## The `link_group_map` Attribute
+
+A `link_group_map` is a list of group definitions. Each definition is a tuple:
+
+```python
+link_group_map = [
+    # (group_name, mappings, optional_attrs)
+    ("group_a", [
+        (":lib_a", "tree", None, None),     # root, traversal, filter, linkage
+        (":lib_b", "node", None, None),
+    ]),
+    ("group_b", [
+        (":lib_c", "tree", "label:vendor/.*", "shared"),
+    ], {"discard_group": False}),
+]
+```
+
+Each mapping tuple has four fields:
+
+| Field | Type | Description |
+|---|---|---|
+| root | Label, list[Label], or None | Starting point(s) for target discovery |
+| traversal | str | How to expand from the root: `tree`, `node`, `subfolders`, `intersect_any_roots` |
+| filter | str, Dependency, or None | Additional predicate on discovered targets |
+| linkage | str or None | Override preferred linkage: `"static"`, `"shared"`, `"any"`, or None |
+
+## Traversal Types
+
+The traversal type controls which targets are assigned to a group starting from
+the root. Understanding this requires understanding how Phase 1 works internally.
+
+### How Phase 1 works: discovery then assignment
+
+Phase 1 (`compute_mappings`) processes mappings in two passes:
+
+**Pass 1 — Discovery** (`_find_targets_in_mapping`): For each mapping, find
+"seed" targets. This is where traversal type and filters are evaluated.
+Discovery does NOT assign anything — it just collects candidate `(target,
+mapping)` pairs into a per-group list.
+
+**Pass 2 — Assignment** (`_update_target_to_group_mapping`): Iterate groups in
+definition order. For each group's discovered targets:
+- **tree**: DFS from the seed target, claiming every unassigned target in the
+  subtree for this group. **No filter is applied** — everything reachable gets
+  claimed.
+- **node / subfolders / intersect_any_roots**: Just assign the seed target
+  itself. No DFS, no subtree claiming.
+
+All discoveries complete before any assignment begins. Assignment processes
+groups in definition order, which is what makes first-assignment-wins
+deterministic.
+
+```
+Example: discovery finds candidates, assignment claims them
+
+link_group_map = [
+    ("a", [(":A", "tree", None, None)]),
+    ("c", [(":C", "node", None, None)]),
+]
+
+    A ──► B ──► C
+
+Discovery pass:
+  group "a": seed = [A]    (tree root, no filter → just return roots)
+  group "c": seed = [C]    (node root)
+
+Assignment pass (in group order):
+  group "a" first: tree DFS from A
+    A → assign to "a"
+    B → assign to "a"
+    C → assign to "a"     ◄── claimed by tree DFS before group "c" runs!
+  group "c" second:
+    C → already assigned to "a" → no-op
+
+Result: C is in group "a", NOT "c".
+```
+
+If the groups were listed in the opposite order, "c" would be assigned first,
+and C would go to "c". When "a"'s tree DFS later reaches C, it would find C
+already assigned but would still continue through C's children (because C was
+assigned via `node`, not `tree` — see below).
+
+### `tree` — Root + all transitive deps
+
+During assignment, a tree DFS from the seed target claims every unassigned
+target in the subtree. No filter is applied — the filter was only used during
+discovery to find the seed.
+
+```
+link_group_map = [
+    ("group_a", [(":lib_a", "tree", None, None)]),
+]
+
+Dependency graph:              Group assignment:
+
+    binary                        binary (ungrouped)
+    ├── lib_a ◄── root            ├── lib_a ──► group_a
+    │   ├── lib_x                 │   ├── lib_x ──► group_a
+    │   └── lib_y                 │   └── lib_y ──► group_a
+    │       └── lib_z             │       └── lib_z ──► group_a
+    └── lib_b                     └── lib_b (ungrouped)
+```
+
+If a target is already assigned to another group, the tree DFS does NOT
+reassign it, but its behavior at that point depends on HOW the target was
+previously assigned:
+
+- **Previously assigned via tree**: the DFS **stops** — that target's entire
+  subtree was already claimed, so there's nothing left to do.
+- **Previously assigned via node/subfolders/intersect_any_roots**: the DFS
+  **continues through** the target into its children, because node assignment
+  didn't claim the subtree.
+
+```
+link_group_map = [
+    ("group_a", [(":lib_a", "node", None, None)]),   # node: just lib_a
+    ("group_b", [(":lib_b", "tree", None, None)]),    # tree: lib_b + deps
+]
+
+    binary
+    ├── lib_a ──► group_a (node)
+    │   └── lib_shared
+    └── lib_b ──► group_b (tree root)
+        └── lib_a ──► already group_a, but tree continues through...
+            └── lib_shared ──► group_b (claimed by tree through lib_a)
+```
+
+### `node` — Root only
+
+Only the seed target itself is assigned to the group. No DFS, no subtree
+claiming. Its deps are NOT assigned (unless another mapping assigns them).
+
+```
+link_group_map = [
+    ("group_a", [(":lib_a", "node", None, None)]),
+]
+
+Dependency graph:              Group assignment:
+
+    binary                        binary (ungrouped)
+    ├── lib_a ◄── root            ├── lib_a ──► group_a
+    │   ├── lib_x                 │   ├── lib_x (ungrouped)
+    │   └── lib_y                 │   └── lib_y (ungrouped)
+    └── lib_b                     └── lib_b (ungrouped)
+```
+
+### `subfolders` — Per-directory implicit groups
+
+Like `node`, but instead of using the group name directly, generates implicit
+group names based on each target's package path.
+
+```
+link_group_map = [
+    ("evict", [(None, "subfolders", "pattern:foo//...", None)]),
+]
+
+Targets:                       Implicit group names:
+  foo//bar:lib1     ──►    evict_foo_bar
+  foo//bar:lib2     ──►    evict_foo_bar
+  foo//baz:lib3     ──►    evict_foo_baz
+```
+
+Each unique package path produces a separate shared library. Name format:
+`{group_name}_{package/path}` with `/` replaced by `_`, truncated to 246 chars.
+
+### `intersect_any_roots` — Common deps of 2+ roots
+
+Requires at least 2 roots. Finds targets reachable from **more than one** root.
+
+```
+link_group_map = [
+    ("common", [([":root_a", ":root_b"], "intersect_any_roots", None, None)]),
+]
+
+    binary
+    ├── root_a
+    │   ├── lib_only_a       ← only reachable from root_a, NOT assigned
+    │   ├── lib_common       ← reachable from BOTH roots → group "common"
+    │   └── lib_shared_dep   ← reachable from BOTH roots → group "common"
+    └── root_b
+        ├── lib_only_b       ← only reachable from root_b, NOT assigned
+        ├── lib_common       ← reachable from BOTH roots → group "common"
+        └── lib_shared_dep   ← reachable from BOTH roots → group "common"
+```
+
+## Filters
+
+Filters restrict which targets within a traversal are assigned to the group.
+Multiple filters on a mapping use AND semantics (all must match).
+
+### Filter types
+
+| Prefix                         | Matches against                | Example                      |
+|--------------------------------|--------------------------------|------------------------------|
+| `label:REGEX`                  | Target's labels/tags           | `label:vendor`               |
+| `tag:REGEX`                    | Same as `label:`               | `tag:third_party`            |
+| `target_regex:REGEX`           | Target's `raw_target()` string | `target_regex:caffe2/.*`     |
+| `pattern:BUILD_TARGET_PATTERN` | Buck target pattern            | `pattern:fbcode//caffe2/...` |
+
+### Filter interaction with tree traversal
+
+Filters only apply during discovery (pass 1). During tree assignment (pass 2),
+the DFS claims all unassigned targets unconditionally — no filter is checked.
+
+During discovery, the DFS visits nodes and checks the filter at each node:
+
+- **Filter matches**: The node is added to the group's matching targets. For
+  tree traversal, the DFS **stops descending** from that node (an optimization
+  — the subtree will be collected during assignment instead).
+- **Filter doesn't match**: The node is **not** added, but the DFS **continues
+  descending** into children by default, looking for matches deeper down. This
+  means filters can "reach through" non-matching intermediate nodes.
+
+```
+link_group_map = [
+    ("group_a", [(":root", "tree", "pattern:fbcode//vendor/...", None)]),
+]
+
+    root                           Traversal during _find_targets_in_mapping:
+    ├── lib_x (no match)           DFS continues ─►
+    │   └── vendor/lib_v (match!)  DFS STOPS (subtree handled during assignment)
+    │       └── vendor/lib_w       Not visited during discovery, but...
+    └── lib_y (no match)           DFS continues ─►
+
+Assignment (step 1b):
+  vendor/lib_v ──► group_a
+  vendor/lib_w ──► group_a  (discovered via tree assignment from lib_v)
+```
+
+### `stop_at_first_non_match`
+
+By default, when a filter doesn't match a node, the DFS **skips that node but
+continues descending into its children** — it "reaches through" non-matching
+nodes to find matches deeper in the graph. With `stop_at_first_non_match = True`,
+the DFS **halts at the non-matching node** and does not visit any of its children.
+
+The tables below describe the **discovery phase** behavior — whether the DFS
+descends into a node's children. This interacts with the traversal type because
+tree and non-tree traversals have opposite default descend behavior on match:
+
+**For tree traversal** (match stops descending, non-match continues by default):
+
+| Situation                                     | Added? | Descend? |
+|-----------------------------------------------|--------|----------|
+| Filter matches                                | Yes    | No (subtree handled in step 1b) |
+| Filter fails, `stop_at_first_non_match=False` | No     | **Yes** — skip node, keep looking deeper |
+| Filter fails, `stop_at_first_non_match=True`  | No     | **No** — halt here |
+
+With tree traversal, matches already stop descending (step 1b handles
+the subtree). So `stop_at_first_non_match=True` means *both* match and non-match
+stop — the DFS never goes past the first level. Only the roots themselves can
+match. This combination is effectively degenerate and not useful in practice.
+
+**For non-tree traversals** like `intersect_any_roots` (match **continues**
+descending):
+
+| Situation                                     | Added? | Descend? |
+|-----------------------------------------------|--------|----------|
+| Filter matches                                | Yes    | **Yes** — keep going |
+| Filter fails, `stop_at_first_non_match=False` | No     | **Yes** — skip node, keep looking deeper |
+| Filter fails, `stop_at_first_non_match=True`  | No     | **No** — halt here |
+
+This is where `stop_at_first_non_match` is meaningful. The DFS keeps descending
+as long as nodes match, and stops at the boundary where they don't — defining
+a **contiguous matching region** from the root:
+
+```
+intersect_any_roots + filter + stop_at_first_non_match=True:
+
+    root (match) ──► add, continue
+    ├── dep_a (match) ──► add, continue
+    │   ├── dep_a1 (match) ──► add, continue
+    │   └── dep_a2 (no match) ──► HALT, don't look deeper
+    └── dep_b (no match) ──► HALT, don't look deeper
+        └── dep_b1 (match) ──► never visited!
+```
+
+Note: None of the built-in filter types (`label:`, `tag:`, `pattern:`,
+`target_regex:`) set this flag. It exists for custom filter targets — rules
+that provide a `GroupFilterInfo` provider directly as a dependency in the
+`link_group_map`, rather than using a string filter.
+
+## Special Groups
+
+Three pseudo-group names have special semantics. They don't produce shared
+libraries — they control how targets are distributed.
+
+### `MATCH_ALL` — Include in every group
+
+Targets assigned to `MATCH_ALL` are **statically linked into every link group**.
+This means their symbols are duplicated across all shared libraries.
+
+```
+link_group_map = [
+    ("MATCH_ALL", [(":lib_common", "tree", None, None)]),
+    ("group_a",   [(":lib_a", "tree", None, None)]),
+    ("group_b",   [(":lib_b", "tree", None, None)]),
+]
+
+Result:
+
+┌───────────────┐
+│    binary     │
+│  (ungrouped)  │
+└──────┬────────┘
+       │
+  ┌────┴─────────────┐
+  │                  │
+┌─▼──────────┐   ┌───▼─────────┐
+│libgroup_a  │   │ libgroup_b  │
+│  lib_a     │   │  lib_b      │
+│  lib_common│   │  lib_common │  ◄── duplicated in both!
+└────────────┘   └─────────────┘
+```
+
+Note: `MATCH_ALL` duplicates symbols across groups, which increases binary
+size and can cause subtle ODR (One Definition Rule) issues. In most cases,
+it's better to place shared utilities in their own named group or leave them
+ungrouped in the main binary.
+
+### `NO_MATCH` — Force into the main binary
+
+Targets assigned to `NO_MATCH` are **never** placed in any link group. They are
+linked directly into the main binary, regardless of other mappings.
+
+```
+link_group_map = [
+    ("NO_MATCH",  [(":lib_critical", "node", None, None)]),
+    ("group_a",   [(":lib_a", "tree", None, None)]),
+]
+
+    binary
+    ├── lib_a ──► group_a (tree root)
+    │   └── lib_critical ──► NO_MATCH (stays in binary, NOT in group_a)
+    └── lib_critical ──► NO_MATCH
+
+Result:
+
+┌──────────────────┐
+│      binary      │
+│  lib_critical    │  ◄── forced into binary
+└──────┬───────────┘
+       │
+  ┌────▼────────┐
+  │ libgroup_a  │
+  │  lib_a      │    ◄── lib_critical NOT here despite being lib_a's dep
+  └─────────────┘
+```
+
+### `MATCH_DIRECT_DEPS` — Follow reverse dependencies
+
+Targets assigned to `MATCH_DIRECT_DEPS` are included in **any group that has a
+target with a direct dependency on them**. Like `MATCH_ALL`, this can cause
+duplication.
+
+```
+link_group_map = [
+    ("MATCH_DIRECT_DEPS", [(":lib_vendor", "node", None, None)]),
+    ("group_a", [(":lib_a", "node", None, None)]),
+    ("group_b", [(":lib_b", "node", None, None)]),
+]
+
+    binary
+    ├── lib_a ──► group_a
+    │   └── lib_vendor  ◄── direct dep of lib_a (group_a) → included in group_a
+    └── lib_b ──► group_b
+                            lib_b does NOT depend on lib_vendor → NOT in group_b
+
+Result:
+
+┌────────────┐
+│   binary   │
+└─────┬──────┘
+      │
+ ┌────┴───────────┐
+ │                │
+┌▼───────────┐  ┌─▼──────────┐
+│libgroup_a  │  │ libgroup_b │
+│  lib_a     │  │  lib_b     │
+│  lib_vendor│  │            │  ◄── lib_vendor NOT here
+└────────────┘  └────────────┘
+```
+
+## First-Assignment-Wins Ordering
+
+When multiple groups could claim a target, the group whose assignment runs
+**first** wins. Assignment processes groups in the order they appear in
+`link_group_map` (see "How Phase 1 works" above). This is a critical ordering
+dependency.
+
+```
+link_group_map = [
+    ("group_first",  [(":lib_a", "tree", None, None)]),   # listed first
+    ("group_second", [(":lib_b", "tree", None, None)]),   # listed second
+]
+
+    binary
+    ├── lib_a ──► group_first (root)
+    │   └── lib_shared_dep ──► group_first  (claimed by tree, first wins!)
+    └── lib_b ──► group_second (root)
+        └── lib_shared_dep ──► already group_first, stays there
+
+Result:
+
+┌─────────────────┐   ┌───────────────────┐
+│ libgroup_first  │   │ libgroup_second   │
+│  lib_a          │   │  lib_b            │
+│  lib_shared_dep │   │                   │  ◄── lib_shared_dep NOT here
+└─────────────────┘   └───────────────────┘
+```
+
+## Preferred Linkage Override
+
+Each mapping can override the preferred linkage of matched targets:
+
+```python
+("group_a", [(":lib", "tree", None, "shared")]),   # force shared linkage
+("group_b", [(":lib", "tree", None, "static")]),   # force static linkage
+("group_c", [(":lib", "tree", None, None)]),       # use target's own preference
+```
+
+When `preferred_linkage = "shared"`, the target is linked as a pre-existing
+shared library rather than being statically linked into the group. The group
+just references it.
+
+## Force-Static Libraries
+
+Targets with `preferred_linkage = "static"` (and
+`ignore_force_static_follows_dependents = False`) get special treatment:
+
+1. **They follow their dependents**: a force-static lib is statically linked
+   into **whatever group or binary depends on it**, regardless of group
+   assignment. This applies to both `deps` and `exported_deps` edges — a
+   force-static target reached through `exported_deps` is still pulled into the
+   depending group.
+
+2. **They can be duplicated**: if multiple groups depend on a force-static lib,
+   each group gets its own static copy.
+
+3. **Root discovery sees through them**: normally, root discovery stops at
+   shared-linkage boundaries. But force-static nodes always use `all_deps`
+   for traversal, so the root discovery DFS continues through them to find
+   additional roots on the other side.
+
+```
+link_group_map = [
+    ("group_a", [(":lib_a", "node", None, None)]),
+]
+
+    binary
+    └── lib_a ──► group_a (node)
+        └── lib_static (preferred_linkage = "static")
+
+Without force-static:
+  lib_static is ungrouped → linked into binary
+
+With force-static (default):
+  lib_static follows its dependent (lib_a) → linked into group_a
+```
+
+## Public Nodes and `--whole-archive`
+
+When a target crosses a link group boundary (depended on by a target in a
+different group), it's marked as a **public node**. Public nodes are linked with
+`--whole-archive` to ensure all their symbols are available.
+
+```
+    group_a contains: lib_a, lib_shared
+    group_b contains: lib_b
+
+    lib_b (group_b) ──depends on──► lib_shared (group_a)
+                                         ▲
+                                    public node!
+                                    linked with --whole-archive
+
+Why: Without --whole-archive, the linker might only pull in the object
+files from lib_shared that resolve symbols within group_a. But group_b
+also needs symbols from lib_shared, and those might not be included.
+```
+
+Public nodes are also expanded transitively through `exported_deps` (since
+exported deps are part of the public API surface), except for special groups
+(`MATCH_ALL`, `NO_MATCH`, `MATCH_DIRECT_DEPS`).
+
+## The `discard_group` Attribute
+
+A group with `discard_group = True` drops all its targets entirely — no shared
+library is created, and the targets are removed from the link line.
+
+```python
+link_group_map = [
+    ("unused", [(":lib_unused", "tree", None, None)], {"discard_group": True}),
+    ("group_a", [(":lib_a", "tree", None, None)]),
+]
+
+    binary
+    ├── lib_a ──► group_a
+    │   └── lib_unused ──► "unused" (discarded!)
+    └── lib_unused ──► "unused" (discarded!)
+
+Result: lib_unused does not appear anywhere — not in the binary,
+not in any shared library. It is completely eliminated.
+```
+
+Use case: removing known-unused dependencies from the build to reduce binary
+size.
+
+## Group Attributes Reference
+
+| Attribute                          | Default | Description |
+|------------------------------------|---------|---|
+| `discard_group`                    | `False` | Drop all group targets entirely |
+| `enable_if_node_count_exceeds`     | `None`  | Only enable group if binary has more nodes than threshold |
+| `enable_distributed_thinlto`       | `False` | Use distributed ThinLTO for the group's .so |
+| `linker_flags`                     | `[]`    | Extra flags when linking the group's .so |
+| `linker_script`                    | `None`  | Linker script for the group's .so |
+| `exported_linker_flags`            | `[]`    | Flags added to dependents linking against the group's .so |
+| `no_as_needed`                     | `False` | Wrap with `--no-as-needed` (for runtime-only deps) |
+| `requires_root_node_exists`        | `True`  | Fail if root targets don't exist in the graph |
+| `prohibit_file_duplicates`         | `False` | Error if duplicate source files appear in public nodes |
+| `link_execution_preference`        | `None`  | Control link execution location (local/remote) |
+
+## The Per-Target Decision Logic
+
+This is the core of link groups: for each target in a group's linkable set, the
+system decides how it appears on the link line. The decision depends on the
+target's group assignment, preferred linkage, and the link strategy.
+
+### Decision tree (`static`/`static_pic` link strategy)
+
+```
+For each target in linkables:
+│
+├── preferred_linkage == shared?
+│   ├── YES: target's group is discarded? → SKIP (drop entirely)
+│   ├── YES: target is a link group root in a DIFFERENT group?
+│   │        → REFERENCE that group's .so
+│   └── YES: otherwise → LINK as shared lib directly
+│
+├── is force-static? (static linkage + follows dependents)
+│   ├── YES: group is discarded? → SKIP
+│   └── YES: → STATIC LINK into current group/binary
+│
+├── no group assigned AND building the binary?
+│   └── YES: → STATIC LINK into binary (ungrouped target)
+│
+├── assigned to NO_MATCH AND building the binary?
+│   └── YES: → STATIC LINK into binary
+│
+├── matches current group? (same group, MATCH_ALL, or MATCH_DIRECT_DEPS rdep)
+│   └── YES: → STATIC LINK into this group
+│
+└── assigned to a DIFFERENT group?
+    └── YES: → REFERENCE that group's .so
+```
+
+### How groups reference each other
+
+When a target belongs to `group_b` but is encountered while building `group_a`'s
+link line, the system doesn't link the target — it adds a reference to
+`group_b`s shared library instead. This creates the `DT_NEEDED` relationship.
+
+```
+Building group_a's link line:
+
+  lib_a (group_a)  → static link (archive)
+  lib_x (group_a)  → static link (archive)
+  lib_y (group_b)  → REFERENCE libgroup_b.so  ← not the target itself!
+  lib_z (group_a)  → static link (archive)
+
+Result: libgroup_a.so has DT_NEEDED libgroup_b.so
+```
+
+## Stub Libraries
+
+Before any groups are linked, the system creates **empty stub shared libraries**
+for each group. These serve as placeholders during linking — when `group_a`
+references `group_b`, it links against the stub for `group_b`. After all groups are
+linked with real content, the stubs are replaced.
+
+```
+Step 1: Create stubs
+  libgroup_a.so (empty)
+  libgroup_b.so (empty)
+
+Step 2: Link group_a → references stub libgroup_b.so
+Step 3: Link group_b → references stub libgroup_a.so
+
+Each group uses --ignore-undefined-symbols because the stubs
+don't have real symbols yet.
+```
+
+## Symbol Handling
+
+After all link groups are created, the system generates linker flags for the
+main binary:
+
+1. **Undefined symbols** (`-u symbol`): Forces the main binary to pull in
+   symbols that link groups need but that might otherwise be dead-stripped.
+
+2. **Dynamic list** (`--dynamic-list`): Exports symbols from the main binary
+   to the dynamic symbol table so link group `.so` files can find them at
+   runtime.
+
+## Runtime Symlink Tree
+
+At runtime, the dynamic linker needs to find all shared libraries. The symlink
+tree handles the case where a target was originally a shared library but got
+merged into a link group:
+
+```
+Original shared lib:      After link groups:
+
+  lib_c.so (standalone)     lib_c.so → symlink to libgroup_a.so
+
+If binary has DT_NEEDED lib_c.so, the symlink resolves
+to the link group that now contains lib_c's code.
+```
+
+## Common Patterns
+
+### Pattern: Evict large dependencies
+
+```python
+link_group_map = [
+    ("caffe2", [(None, "tree", "pattern:fbcode//caffe2/...", None)]),
+    ("velox",  [(None, "tree", "pattern:fbcode//velox/...", None)]),
+]
+```
+
+This evicts all caffe2 and velox targets into separate shared libraries,
+reducing the main binary size. The `None` root + pattern filter means: find all
+targets matching the pattern in the full graph.
+
+### Pattern: Per-directory splitting
+
+```python
+link_group_map = [
+    ("libs", [(None, "subfolders", "pattern:fbcode//large_dep/...", None)]),
+]
+```
+
+Automatically creates one shared library per directory under `large_dep/`,
+avoiding the need to enumerate every directory.
+
+### Pattern: Common utilities shared across groups
+
+```python
+link_group_map = [
+    ("MATCH_ALL", [(":lib_common", "tree", None, None)]),
+    ("group_a",   [(":lib_a", "tree", None, None)]),
+    ("group_b",   [(":lib_b", "tree", None, None)]),
+]
+```
+
+`lib_common` (and its deps) are statically linked into both `group_a` and
+`group_b`. This avoids cross-group references at the cost of code duplication.
+
+### Pattern: Force specific targets into the binary
+
+```python
+link_group_map = [
+    ("NO_MATCH", [(":critical_lib", "node", None, None)]),
+    ("everything_else", [(None, "tree", "pattern:fbcode//...", None)]),
+]
+```
+
+`critical_lib` is kept in the main binary even though `everything_else` would
+otherwise claim it.
+
+## Interaction Matrix
+
+How the different options interact with each other:
+
+| Feature                      | `MATCH_ALL`      | `NO_MATCH`     | `MATCH_DIRECT_DEPS` | force-static         | discard |
+|------------------------------|------------------|----------------|---------------------|----------------------|---------|
+| Creates a .so?               | No               | No             | No                  | N/A                  | No      |
+| Can duplicate symbols?       | Yes (all groups) | No             | Yes (rdep groups)   | Yes                  | No      |
+| Stops shared propagation?    | No               | Yes            | No                  | No                   | N/A     |
+| Is a public node?            | Excluded         | Excluded       | Excluded            | N/A                  | N/A     |
+| Appears in link-groups-info? | In every group   | In binary only | In rdep groups      | In dependent's group | Nowhere |
+
+## `enable_if_node_count_exceeds`
+
+This attribute makes a group conditional on the binary's dependency graph size.
+It's used for groups that are only useful for large binaries:
+
+```python
+link_group_map = [
+    ("large_dep", [(":lib", "tree", None, None)],
+     {"enable_if_node_count_exceeds": 10000}),
+]
+```
+
+If the binary has fewer than 10,000 nodes in its linkable graph, this group is
+silently disabled and its targets stay in the main binary.
+
+## `no_as_needed`
+
+By default, the linker may drop `DT_NEEDED` entries for shared libraries that
+are not directly referenced by any symbol. `no_as_needed` prevents this:
+
+```python
+link_group_map = [
+    ("runtime_only", [(":lib", "tree", None, None)],
+     {"no_as_needed": True}),
+]
+```
+
+This wraps the group's .so with `--no-as-needed` / `--as-needed` flags,
+ensuring it's always loaded at runtime even if no static symbol references it
+(useful for libraries that register themselves via constructors).
+
+## Python dlopen-enabled Libraries
+
+When link groups are used by a Python binary, additional link group specs are
+auto-generated for two categories of native dependencies: **dlopen-enabled
+libraries** and **Python native extensions**. These are created by
+`_get_root_link_group_specs` in `python/linking/native.bzl` and prepended to
+any user-defined link group specs, giving them higher precedence.
+
+### How libraries opt in
+
+C++ and Rust libraries set `supports_python_dlopen = True` in their rule
+definition. This causes the rule to emit a `DlopenableLibraryInfo` marker
+provider (an empty provider with no fields). Prebuilt C++ libraries default
+to `supports_python_dlopen = True`.
+
+### What happens at Python binary analysis time
+
+When `process_native_linking` builds a Python binary, it calls
+`merge_cxx_extension_info` which scans first-order deps
+(`ctx.attrs.deps + ctx.attrs.preload_deps`) and separates them into:
+
+- **`dlopen_deps`**: deps with `DlopenableLibraryInfo` — C++/Rust libs that
+  should be their own standalone .so
+- **`shared_only_libs`**: prebuilt libs that only provide shared linkage
+  (detected by having `MergedLinkInfo` but no `LinkableRootInfo`)
+- **`unembeddable_extensions`**: Python C extensions that can't be statically
+  embedded
+
+### Auto-generated specs
+
+For each `dlopen_dep`, a `LinkGroupLibSpec` is created with:
+
+```
+LinkGroupLibSpec(
+    name = <lib name>,
+    is_shared_lib = True,        # gets SONAME, stub library, SharedLibraries packaging
+    root = <LinkableRootInfo>,   # private linker flags, version scripts
+    group = Group(
+        name = <lib name>,
+        mappings = [GroupMapping(
+            roots = [<lib label>],
+            traversal = Traversal("node"),  # only the library itself, not transitive deps
+        )],
+    ),
+)
+```
+
+For each unembeddable Python extension, a similar spec is created but with
+`is_shared_lib = False` (no SONAME, no stub library).
+
+### `is_shared_lib` controls three behaviors in Phase 7
+
+| Behavior                  | `is_shared_lib = True` (dlopen libs) | `is_shared_lib = False` (extensions) |
+|---------------------------|--------------------------------------|--------------------------------------|
+| SONAME on .so             | Yes                                  | No                                   |
+| Stub library generated    | Yes (other groups can link against)  | No                                   |
+| Packaged as SharedLibrary | Yes (in runtime symlink tree)        | No (just an artifact)                |
+
+Stub libraries are empty .so files created before the real link groups are
+linked. They allow other groups to declare `DT_NEEDED` entries against the
+dlopen lib. The real .so replaces the stub at runtime.
+
+Symbol export is also critical: after linking each dlopen group's .so, the
+system extracts its undefined and global symbols. These are fed back to the
+main executable link as `-u <symbol>` flags (forcing the linker to keep symbols
+needed by dlopen libs) and `--dynamic-list` entries (exporting symbols to the
+dynamic symbol table so dlopen'd libs can resolve them at runtime). Without
+this, the main executable's linker would discard symbols that nothing in the
+static link references, even though dlopen'd libs need them at runtime.
+
+### Shared-only libraries
+
+Prebuilt libraries that only provide shared linkage get `Group` records (not
+`LinkGroupLibSpec`s) with `preferred_linkage = Linkage("shared")`. This forces
+them to be linked dynamically rather than attempting static linkage that would
+fail. These groups don't produce their own .so — they just ensure the existing
+.so is referenced correctly.
+
+### Link ordering edge case
+
+Python dlopen deps are not part of the main dependency graph rooted at the
+executable. The normal DFS in `collect_linkables` (Phase 5) may not find them
+through the executable's deps. The `extra_link_roots` mechanism adds dlopen
+deps as additional starting points for the linkable collection, and there's a
+fixup in `collect_linkables` for ordering correctness.
diff --git a/buck2/prelude/linking/link_info.bzl b/buck2/prelude/linking/link_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/link_info.bzl
@@ -0,0 +1,1150 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+    "make_artifact_tset",
+)
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "LinkerInfo",
+    "LinkerType",
+    "PicBehavior",
+)
+load(
+    "@prelude//cxx:linker.bzl",
+    "get_link_whole_args",
+    "get_no_as_needed_shared_libs_flags",
+    "get_objects_as_library_args",
+)
+load(
+    "@prelude//cxx:transformation_spec.bzl",
+    "TransformationKind",
+    "TransformationSpecContext",  # @unused Used as a type
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+
+ExtraLinkerOutputs = record(
+    # The unbound extra outputs produced by a link action
+    # stored by key for lookup in the flag factory.
+    artifacts = field(dict[str, Artifact], {}),
+    # The output providers for the extra linker output.
+    providers = field(dict[str, list[DefaultInfo]], {}),
+)
+
+ArchiveContentsType = enum(
+    "normal",  # The static archive itself contains a symbol table and compressed object files
+    "thin",  # The static archive only has a symbol table and refers to object files elsewhere on disk
+    "virtual",  # Object files are passed directly to the linker between --start-lib --end-lib flags to indicate archive semantics, and a normal static archive is used by actions that request the archive itself
+)
+
+# Represents an archive (.a file)
+Archive = record(
+    archive_contents_type = field(ArchiveContentsType, default = ArchiveContentsType("normal")),
+    artifact = field(Artifact),
+    # For a thin archive, this contains all the referenced .o files
+    external_objects = field(list[Artifact], []),
+)
+
+# The different strategies that are used to determine sharedlib/executable
+# link constituents.
+# These default link strategies will each traverse dependenciess and collect
+# all transitive dependencies that will link as archives until it reaches ones that will
+# link as shared libs. For each dependency, this link strategy and that dependency's
+# preferred_linkage will determine which LibOutputStyle will be used.
+LinkStrategy = enum(
+    # Prefers that dependencies be included in the link line as archives of native objects
+    "static",
+    # Prefers that dependencies be included in the link line as archives of PIC native objects
+    "static_pic",
+    # Prefers that dependencies be included in the link line as shared libraries
+    "shared",
+)
+
+# A legacy type that was previously used to encode both LibOutputStyle and LinkStrategy. Uses should
+# be updated to use the appropriate new enum.
+LinkStyle = enum(
+    "static",
+    "static_pic",
+    "shared",
+)
+
+# We still read link_style (and some related) attrs to LinkStyle but then usually convert them
+# immediately to LinkStrategy.
+# TODO(cjhopman): We should migrate the attr name to `link_strategy`
+def to_link_strategy(link_style: LinkStyle) -> LinkStrategy:
+    return LinkStrategy(link_style.value)
+
+# The different types of outputs of native library. Which specific output style to use for a library
+# will depend on the link_strategy that is being computed and the library's preferred_linkage.
+LibOutputStyle = enum(
+    "archive",
+    "pic_archive",
+    "shared_lib",
+)
+
+def default_output_style_for_link_strategy(link_strategy: LinkStrategy) -> LibOutputStyle:
+    if link_strategy == LinkStrategy("static"):
+        return LibOutputStyle("archive")
+    if link_strategy == LinkStrategy("static_pic"):
+        return LibOutputStyle("pic_archive")
+    return LibOutputStyle("shared_lib")
+
+# An archive.
+ArchiveLinkable = record(
+    # Artifact in the .a format from ar
+    archive = field(Archive),
+    # If a bitcode bundle was created for this artifact it will be present here
+    bitcode_bundle = field(Artifact | None, None),
+    linker_type = field(LinkerType),
+    link_whole = field(bool, False),
+    # Indicates if this archive may contain LTO bit code.  Can be set to `False`
+    # to e.g. tell dist LTO handling that a potentially expensive archive doesn't
+    # need to be processed.
+    supports_lto = field(bool, True),
+)
+
+# A shared lib.
+SharedLibLinkable = record(
+    lib = field(Artifact),
+    link_without_soname = field(bool, False),
+)
+
+# A list of objects.
+ObjectsLinkable = record(
+    objects = field([list[Artifact], None], None),
+    # Any of the objects that are in bitcode format
+    bitcode_bundle = field(Artifact | None, None),
+    linker_type = field(LinkerType),
+    link_whole = field(bool, False),
+)
+
+# Framework + library information for Apple/Cxx targets.
+FrameworksLinkable = record(
+    # An untrimmed list of framework paths, used to construct `-framework` args.
+    frameworks = field(typing.Iterable, []),
+    # A untrimmed list of library names, used to construct `-l` args.
+    libraries = field(typing.Iterable, []),
+    #
+    ## WHY ITERABLES? ##
+    #
+    # For leaf nodes we just insert the attrs.frameworks + attrs.libraries
+    # interned strings/lists.
+    # They get dedupped into sets as they propagate.
+)
+
+_EMPTY_FRAMEWORKS_LINKABLE = FrameworksLinkable()
+
+SwiftmoduleLinkable = record(
+    swiftmodules = field(ArtifactTSet, ArtifactTSet()),
+)
+
+_EMPTY_SWIFTMODULE_LINKABLE = SwiftmoduleLinkable()
+
+_EMPTY_FRAMEWORKS_LINKABLE_BY_STRATEGY = {link_strategy: _EMPTY_FRAMEWORKS_LINKABLE for link_strategy in LinkStrategy}
+_EMPTY_SWIFTMODULE_LINKABLE_BY_STRATEGY = {link_strategy: _EMPTY_SWIFTMODULE_LINKABLE for link_strategy in LinkStrategy}
+
+LinkableTypes = [
+    ArchiveLinkable,
+    SharedLibLinkable,
+    ObjectsLinkable,
+    FrameworksLinkable,
+    SwiftmoduleLinkable,
+]
+
+LinkerFlags = record(
+    flags = field(list[typing.Any], []),
+    post_flags = field(list[typing.Any], []),
+    exported_flags = field(list[typing.Any], []),
+    exported_post_flags = field(list[typing.Any], []),
+)
+
+DepMetadata = record(
+    # The version of a particular library linked into a binary. This is reported by
+    # attributes on the library target itself.
+    version = field(str),
+)
+
+# Contains the information required to add an item (often corresponding to a single library) to a link command line.
+LinkInfo = record(
+    # An informative name for this LinkInfo. This may be used in user messages
+    # or when constructing intermediate output paths and does not need to be unique.
+    name = field([str, None], None),
+    dist_thin_lto_codegen_flags = field(list[typing.Any], []),
+    # Opaque cmd_arg-likes to be added pre/post this item on a linker command line.
+    pre_flags = field(list[typing.Any], []),
+    post_flags = field(list[typing.Any], []),
+    # Primary input to the linker, one of the Linkable types above.
+    linkables = field(list[LinkableTypes], []),
+    # Debug info which is referenced -- but not included -- by linkables in the
+    # link info.  For example, this may include `.dwo` files, or the original
+    # `.o` files if they contain debug info that doesn't follow the link.
+    external_debug_info = field(ArtifactTSet, ArtifactTSet()),
+    # Metadata attached to this LinkInfo. This metadata is propagated up the graph to
+    # root nodes (like binaries).
+    metadata = field(list[DepMetadata], []),
+    has_hip_device_debug = field(bool, False),
+    hip_arch_debug_files = field(dict[str, list[Artifact]], {}),
+)
+
+# The ordering to use when traversing linker libs transitive sets.
+LinkOrdering = enum(
+    # Preorder traversal, the default behavior which traverses depth-first returning the current
+    # node, and then its children left-to-right.
+    "preorder",
+    # Topological sort, such that nodes are listed after all nodes that have them as descendants.
+    "topological",
+)
+
+CxxSanitizerRuntimeInfo = provider(
+    fields = {
+        "runtime_files": provider_field(list[Artifact]),
+    }
+)
+
+def set_link_info_link_whole(info: LinkInfo) -> LinkInfo:
+    linkables = [set_linkable_link_whole(linkable) for linkable in info.linkables]
+    return LinkInfo(
+        name = info.name,
+        pre_flags = info.pre_flags,
+        post_flags = info.post_flags,
+        linkables = linkables,
+        external_debug_info = info.external_debug_info,
+        metadata = info.metadata,
+        has_hip_device_debug = info.has_hip_device_debug,
+        hip_arch_debug_files = info.hip_arch_debug_files,
+    )
+
+def set_linkable_link_whole(
+    linkable: [ArchiveLinkable, ObjectsLinkable, SharedLibLinkable, FrameworksLinkable],
+) -> [ArchiveLinkable, ObjectsLinkable, SharedLibLinkable, FrameworksLinkable]:
+    if isinstance(linkable, ArchiveLinkable):
+        return ArchiveLinkable(
+            archive = linkable.archive,
+            linker_type = linkable.linker_type,
+            link_whole = True,
+            supports_lto = linkable.supports_lto,
+        )
+    elif isinstance(linkable, ObjectsLinkable):
+        return ObjectsLinkable(
+            objects = linkable.objects,
+            linker_type = linkable.linker_type,
+            link_whole = True,
+        )
+    return linkable
+
+# Helper to wrap a LinkInfo with additional pre/post-flags.
+def wrap_link_info(inner: LinkInfo, pre_flags: list[typing.Any] = [], post_flags: list[typing.Any] = []) -> LinkInfo:
+    pre_flags = pre_flags + inner.pre_flags
+    post_flags = inner.post_flags + post_flags
+    return LinkInfo(
+        name = inner.name,
+        pre_flags = pre_flags,
+        post_flags = post_flags,
+        linkables = inner.linkables,
+        external_debug_info = inner.external_debug_info,
+        metadata = inner.metadata,
+        has_hip_device_debug = inner.has_hip_device_debug,
+        hip_arch_debug_files = inner.hip_arch_debug_files,
+    )
+
+def _is_linkable_comprised_of_object_files_or_a_lazy_archive(linkable: LinkableTypes) -> bool:
+    return isinstance(linkable, ObjectsLinkable) or (isinstance(linkable, ArchiveLinkable) and not linkable.link_whole)
+
+def serialize_linkable_for_thinlto(linkable: LinkableTypes) -> dict[str, typing.Any]:
+    """Serialize the `linkable` so that it can be used in the ThinLTO metadata file."""
+    object = {}
+    if isinstance(linkable, ArchiveLinkable):
+        object["type"] = "archive"
+        object["archive"] = linkable.archive.artifact
+    elif isinstance(linkable, SharedLibLinkable):
+        object["type"] = "shared_lib"
+        object["name"] = linkable.lib
+    elif isinstance(linkable, ObjectsLinkable):
+        # This path should NOT be reached.
+        # ObjectLinkables are managed as bitcode, not as generic linkables.
+        fail("ObjectsLinkable are sent as _BitcodeLinkData {}".format(str(linkable)))
+    elif isinstance(linkable, FrameworksLinkable) or isinstance(linkable, SwiftmoduleLinkable):
+        fail("Apple Frameworks linkables are not supported on GNU {}".format(str(linkable)))
+    else:
+        fail("Encountered unhandled linkable {}".format(str(linkable)))
+
+    return object
+
+# Adds appropriate args representing `linkable` to `args`
+def append_linkable_args(args: cmd_args, linkable: LinkableTypes):
+    if isinstance(linkable, ArchiveLinkable):
+        if linkable.archive.archive_contents_type == ArchiveContentsType("virtual"):
+            if not linkable.link_whole:
+                args.add("-Wl,--start-lib")
+
+            for object in linkable.archive.external_objects:
+                args.add(object)
+
+            if not linkable.link_whole:
+                args.add("-Wl,--end-lib")
+        elif linkable.link_whole:
+            args.add(get_link_whole_args(linkable.linker_type, [linkable.archive.artifact]))
+        else:
+            args.add(linkable.archive.artifact)
+
+        if linkable.archive.archive_contents_type == ArchiveContentsType("thin"):
+            # When using thin archives, object files are implicitly used as inputs
+            # to the link, so make sure track them as inputs so that they're
+            # materialized/tracked properly.
+            args.add(cmd_args(hidden = linkable.archive.external_objects))
+    elif isinstance(linkable, SharedLibLinkable):
+        if linkable.link_without_soname:
+            linkable_name = linkable.lib.basename.removeprefix("lib").split(".")[0]
+            args.add(cmd_args(linkable.lib, format = "-L{}", parent = 1))
+            args.add("-l" + linkable_name)
+        else:
+            args.add(linkable.lib)
+    elif isinstance(linkable, ObjectsLinkable):
+        # We need to export every symbol when link groups are used, but enabling
+        # --whole-archive with --start-lib is undefined behavior in gnu linkers:
+        # https://reviews.llvm.org/D120443. We need to export symbols from every
+        # linkable in the link_info
+        if not linkable.link_whole:
+            args.add(get_objects_as_library_args(linkable.linker_type, linkable.objects))
+        else:
+            args.add(linkable.objects)
+    elif isinstance(linkable, FrameworksLinkable) or isinstance(linkable, SwiftmoduleLinkable):
+        # These flags are handled separately so they can be deduped.
+        #
+        # We've seen in apps with larger dependency graphs that failing
+        # to dedupe these args results in linker.argsfile which are too big.
+        pass
+    else:
+        fail("Encountered unhandled linkable {}".format(str(linkable)))
+
+LinkInfoArgumentFilter = enum(
+    "all",
+    "object_files_and_lazy_archives_only",
+    "exclude_object_files_and_lazy_archives",
+)
+
+def link_info_to_args(value: LinkInfo, argument_type_filter: LinkInfoArgumentFilter = LinkInfoArgumentFilter("all")) -> cmd_args:
+    result = cmd_args()
+
+    do_pre_post_flags = argument_type_filter == LinkInfoArgumentFilter("all") or argument_type_filter == LinkInfoArgumentFilter(
+        "exclude_object_files_and_lazy_archives"
+    )
+    if do_pre_post_flags:
+        result.add(value.pre_flags)
+
+    for linkable in value.linkables:
+        if argument_type_filter == LinkInfoArgumentFilter("all"):
+            append_linkable_args(result, linkable)
+
+        elif argument_type_filter == LinkInfoArgumentFilter("object_files_and_lazy_archives_only") and _is_linkable_comprised_of_object_files_or_a_lazy_archive(
+            linkable
+        ):
+            append_linkable_args(result, linkable)
+
+        elif argument_type_filter == LinkInfoArgumentFilter(
+            "exclude_object_files_and_lazy_archives"
+        ) and not _is_linkable_comprised_of_object_files_or_a_lazy_archive(linkable):
+            append_linkable_args(result, linkable)
+
+    if do_pre_post_flags:
+        result.add(value.post_flags)
+
+    return result
+
+def _link_info_to_tbd_creation_args(value: LinkInfo) -> cmd_args:
+    result = cmd_args()
+    for linkable in value.linkables:
+        if isinstance(linkable, ArchiveLinkable) and linkable.archive.external_objects:
+            for object in linkable.archive.external_objects:
+                result.add(object)
+        elif isinstance(linkable, ArchiveLinkable):
+            result.add(linkable.archive.artifact)
+        if isinstance(linkable, ObjectsLinkable):
+            for object in linkable.objects:
+                result.add(object)
+
+    return result
+
+LinkableFlavor = enum(
+    # Provides compile outputs
+    "default",
+    # Provides compile outputs
+    # using optimization flags from toolchain
+    "optimized",
+    # Provides compile outputs
+    # using debug flags from toolchain
+    "debug",
+    # Provides compile outputs
+    # stripped of debug symbols
+    "stripped",
+)
+
+# Encapsulate all `LinkInfo`s provided by a given rule's link style.
+#
+# We provide both the "default" and (optionally) a pre-"stripped" LinkInfo. For a consumer that doesn't care
+# about debug info (for example, who is going to produce stripped output anyway), it can be significantly
+# cheaper to consume the pre-stripped LinkInfo.
+LinkInfos = record(
+    label = field(Label | None, None),
+    # Link info to use by default.
+    default = field(LinkInfo),
+    # Link info for objects compiler with extra optimizations (EXPERIMENTAL)
+    optimized = field([LinkInfo, None], None),
+    # Link info for objects compiler with debug optimizations (-g2 + -O0)
+    debuggable = field([LinkInfo, None], None),
+    # Link info stripped of debug symbols.
+    stripped = field([LinkInfo, None], None),
+)
+
+def _link_info_default_args(infos: LinkInfos) -> cmd_args:
+    info = infos.default
+    return link_info_to_args(info, argument_type_filter = LinkInfoArgumentFilter("all"))
+
+def _link_info_stripped_link_args(infos: LinkInfos) -> cmd_args:
+    info = infos.stripped or infos.default
+    return link_info_to_args(info, argument_type_filter = LinkInfoArgumentFilter("all"))
+
+def _link_info_object_files_and_lazy_archives_only_args(infos: LinkInfos) -> cmd_args:
+    return link_info_to_args(infos.default, argument_type_filter = LinkInfoArgumentFilter("object_files_and_lazy_archives_only"))
+
+def _link_info_excluding_object_files_and_lazy_archives_args(infos: LinkInfos) -> cmd_args:
+    return link_info_to_args(infos.default, argument_type_filter = LinkInfoArgumentFilter("exclude_object_files_and_lazy_archives"))
+
+def _link_info_tbd_creation_args(infos: LinkInfos) -> cmd_args:
+    return _link_info_to_tbd_creation_args(infos.default)
+
+def link_info_to_metadata_args(info: LinkInfo, args: cmd_args | None = None) -> ArgLike:
+    if args == None:
+        args = cmd_args()
+    for meta in info.metadata:
+        args.add("version:" + meta.version)
+    return args
+
+def _link_info_metadata_args(infos: LinkInfos):
+    info = infos.stripped or infos.default
+    return link_info_to_metadata_args(info)
+
+# TransitiveSet of LinkInfos.
+LinkInfosTSet = transitive_set(
+    args_projections = {
+        "default": _link_info_default_args,
+        "exclude_object_files_and_lazy_archives": _link_info_excluding_object_files_and_lazy_archives_args,
+        "metadata": _link_info_metadata_args,
+        "object_files_and_lazy_archives_only": _link_info_object_files_and_lazy_archives_only_args,
+        "stripped": _link_info_stripped_link_args,
+        "tbd_creation_args": _link_info_tbd_creation_args,
+    },
+)
+
+LinkArgsTSet = record(
+    infos = field(LinkInfosTSet),
+    external_debug_info = field(ArtifactTSet, ArtifactTSet()),
+    prefer_stripped = field(bool, False),
+)
+
+# An enum. Only one field should be set. The variants here represent different
+# ways in which we might obtain linker commands: through a t-set of propagated
+# dependencies (used for deps propagated unconditionally up a tree), through a
+# series of LinkInfo (used for link groups, Omnibus linking), or simply through
+# raw arguments we want to include (used for e.g. per-target link flags).
+LinkArgs = record(
+    # A LinkInfosTSet + a flag indicating if stripped is preferred.
+    tset = field([LinkArgsTSet, None], None),
+    # A list of LinkInfos
+    infos = field([list[LinkInfo], None], None),
+    # A bunch of flags.
+    flags = field([ArgLike, None], None),
+)
+
+# The output of a native link (e.g. a shared library or an executable).
+LinkedObject = record(
+    output = field([Artifact, Promise]),
+    # The combined bitcode from this linked object and any static libraries
+    bitcode_bundle = field(Artifact | None, None),
+    # the generated linked output before running stripping(and bolt).
+    unstripped_output = field(Artifact),
+    # the generated linked output before running bolt, may be None if bolt is not used.
+    prebolt_output = field(Artifact | None, None),
+    # The LinkArgs used to produce this LinkedObject. This can be useful for debugging or
+    # for downstream rules to reproduce the shared library with some modifications (for example
+    # android relinker will link again with an added version script argument).
+    link_args = field(list[LinkArgs] | None, None),
+    # A linked object (binary/shared library) may have an associated dwp file with
+    # its corresponding DWARF debug info.
+    # May be None when Split DWARF is disabled or for some types of synthetic link objects.
+    dwp = field(Artifact | None, None),
+    # Per-gfx-arch sidecar `.debug` files keyed by arch label.
+    # Not set by cxx_link_into(); populated by callers (cxx_library,
+    # link_groups) from compile outputs after linking.
+    hip_arch_debug_files = field(dict[str, list[Artifact]], {}),
+    # Additional dirs or paths that contain debug info referenced by the linked
+    # object (e.g. split dwarf files or PDB file).
+    external_debug_info = field(ArtifactTSet, ArtifactTSet()),
+    # This argsfile is generated in the `cxx_link` step and contains a list of arguments
+    # passed to the linker. It is being exposed as a sub-target for debugging purposes.
+    linker_argsfile = field(Artifact | None, None),
+    # The linker command as generated by `cxx_link`. Exposed for debugging purposes only.
+    # Not present for DistLTO scenarios.
+    linker_command = field([cmd_args, None], None),
+    # This sub-target is only available for distributed thinLTO builds.
+    index_argsfile = field(Artifact | None, None),
+    # Import library for linking with DLL on Windows.
+    # If not on Windows it's always None.
+    import_library = field(Artifact | None, None),
+    # A linked object (binary/shared library) may have an associated PDB file with
+    # its corresponding Windows debug info.
+    # If not on Windows it's always None.
+    pdb = field(Artifact | None, None),
+    # Incremental linking state file (.ilk) for MSVC on Windows.
+    ilk = field(Artifact | None, None),
+    # Split-debug info generated by the link.
+    split_debug_output = field(Artifact | None, None),
+)
+
+# A map of native linkable infos from transitive dependencies for each LinkStrategy.
+# This contains the information about how to link in a target for each link strategy.
+# This doesn't contain the information about things needed to package the linked result
+# (i.e. this doesn't contain the information needed to know what shared libs needed at runtime
+# for the final result).
+MergedLinkInfo = provider(
+    fields = {
+        # Apple framework linker args must be deduped to avoid overflow in our argsfiles.
+        #
+        # To save on repeated computation of transitive LinkInfos, we store a dedupped
+        # structure, based on the link-style.
+        "frameworks": provider_field(dict[LinkStrategy, FrameworksLinkable | None]),
+        "swiftmodules": provider_field(dict[LinkStrategy, SwiftmoduleLinkable | None]),
+        "_external_debug_info": provider_field(dict[LinkStrategy, ArtifactTSet]),
+        "_infos": provider_field(dict[LinkStrategy, LinkInfosTSet]),
+    }
+)
+
+# A map of linkages to all possible output styles it supports.
+_LIB_OUTPUT_STYLES_FOR_LINKAGE = {
+    Linkage("any"): [LibOutputStyle("archive"), LibOutputStyle("pic_archive"), LibOutputStyle("shared_lib")],
+    Linkage("static"): [LibOutputStyle("archive"), LibOutputStyle("pic_archive")],
+    Linkage("shared"): [LibOutputStyle("pic_archive"), LibOutputStyle("shared_lib")],
+}
+
+# Helper to wrap a LinkInfos with additional pre/post-flags.
+def wrap_link_infos(inner: LinkInfos, pre_flags: list[typing.Any] = [], post_flags: list[typing.Any] = []) -> LinkInfos:
+    return LinkInfos(
+        default = wrap_link_info(
+            inner.default,
+            pre_flags = pre_flags,
+            post_flags = post_flags,
+        ),
+        stripped = None
+        if inner.stripped == None
+        else wrap_link_info(
+            inner.stripped,
+            pre_flags = pre_flags,
+            post_flags = post_flags,
+        ),
+    )
+
+def create_merged_link_info(
+    # Target context for which to create the link info.
+    ctx: AnalysisContext,
+    pic_behavior: PicBehavior,
+    # The outputs available for this rule, as a map from LibOutputStyle (as
+    # used by dependents) to `LinkInfo`.
+    link_infos: dict[LibOutputStyle, LinkInfos] = {},
+    # How the rule requests to be linked.  This will be used to determine
+    # which actual link style to propagate for each "requested" link style.
+    preferred_linkage: Linkage = Linkage("any"),
+    # Link info to propagate from non-exported deps for static link styles.
+    deps: list[MergedLinkInfo] = [],
+    # Link info to always propagate from exported deps.
+    exported_deps: list[MergedLinkInfo] = [],
+    frameworks_linkable: [FrameworksLinkable, None] = None,
+    swiftmodule_linkable: [SwiftmoduleLinkable, None] = None,
+) -> MergedLinkInfo:
+    """
+    Create a `MergedLinkInfo` provider.
+    """
+
+    infos = {}
+    external_debug_info = {}
+    frameworks = None
+    swiftmodules = None
+
+    # We don't know how this target will be linked, so we generate the possible
+    # link info given the target's preferred linkage, to be consumed by the
+    # ultimate linking target.
+    for link_strategy in LinkStrategy:
+        actual_output_style = get_lib_output_style(link_strategy, preferred_linkage, pic_behavior)
+
+        children = []
+        external_debug_info_children = []
+        framework_linkables = []
+        swiftmodule_linkables = []
+
+        # When we're being linked statically, we also need to export all private
+        # linkable input (e.g. so that any unresolved symbols we have are
+        # resolved properly when we're linked).
+        if actual_output_style != LibOutputStyle("shared_lib"):
+            # We never want to propagate the linkables used to build a shared library.
+            #
+            # Doing so breaks the encapsulation of what is in linked in the library vs. the main executable.
+            framework_linkables.append(frameworks_linkable)
+            framework_linkables += [dep_info.frameworks[link_strategy] for dep_info in exported_deps]
+
+            swiftmodule_linkables.append(swiftmodule_linkable)
+            swiftmodule_linkables += [dep_info.swiftmodules[link_strategy] for dep_info in exported_deps]
+
+            for dep_info in deps:
+                # The inherited link infos no longer guarantees that a tset will be available for
+                # all link strategies. Protect against missing infos
+                value = dep_info._infos.get(link_strategy)
+                if value:
+                    children.append(value)
+                value = dep_info._external_debug_info.get(link_strategy)
+                if value:
+                    external_debug_info_children.append(value)
+
+                framework_linkables.append(dep_info.frameworks[link_strategy])
+                swiftmodule_linkables.append(dep_info.swiftmodules[link_strategy])
+
+        # We always export link info for exported deps.
+        for dep_info in exported_deps:
+            value = dep_info._infos.get(link_strategy)
+            if value:
+                children.append(value)
+            value = dep_info._external_debug_info.get(link_strategy)
+            if value:
+                external_debug_info_children.append(value)
+
+        merged_frameworks = _merge_framework_linkables(framework_linkables)
+        if merged_frameworks != _EMPTY_FRAMEWORKS_LINKABLE:
+            if frameworks == None:
+                frameworks = dict(_EMPTY_FRAMEWORKS_LINKABLE_BY_STRATEGY)
+            frameworks[link_strategy] = merged_frameworks
+
+        merged_swiftmodules = merge_swiftmodule_linkables(ctx, swiftmodule_linkables)
+        if merged_swiftmodules != _EMPTY_SWIFTMODULE_LINKABLE:
+            if swiftmodules == None:
+                swiftmodules = dict(_EMPTY_SWIFTMODULE_LINKABLE_BY_STRATEGY)
+            swiftmodules[link_strategy] = merged_swiftmodules
+
+        if actual_output_style in link_infos:
+            link_info = link_infos[actual_output_style]
+
+            # TODO(cjhopman): This seems like we won't propagate information about our children unless this target itself
+            # has an output for this strategy. Why is that correct?
+            infos[link_strategy] = ctx.actions.tset(
+                LinkInfosTSet,
+                value = link_info,
+                children = children,
+            )
+            external_debug_info[link_strategy] = make_artifact_tset(
+                actions = ctx.actions,
+                label = ctx.label,
+                children = ([link_info.default.external_debug_info] + external_debug_info_children),
+            )
+
+    return MergedLinkInfo(
+        _infos = infos,
+        _external_debug_info = external_debug_info,
+        frameworks = frameworks if frameworks != None else _EMPTY_FRAMEWORKS_LINKABLE_BY_STRATEGY,
+        swiftmodules = swiftmodules if swiftmodules != None else _EMPTY_SWIFTMODULE_LINKABLE_BY_STRATEGY,
+    )
+
+def get_own_link_infos(merged: MergedLinkInfo, link_strategy: LinkStrategy) -> [LinkInfos, None]:
+    """The LinkInfos of the target itself (not its dependencies') that
+    `merged` is the MergedLinkInfo of, for a link strategy."""
+    infos = merged._infos.get(link_strategy)
+    return infos.value if infos != None else None
+
+def create_merged_link_info_for_propagation(ctx: AnalysisContext, xs: list[MergedLinkInfo]) -> MergedLinkInfo:
+    """
+    Creates a MergedLinkInfo for a node that just propagates up its dependencies' MergedLinkInfo without contributing anything itself.
+
+    A node that contributes something itself would use create_merged_link_info.
+    """
+    merged = {}
+    merged_external_debug_info = {}
+    frameworks = None
+    swiftmodules = None
+    for link_strategy in LinkStrategy:
+        merged[link_strategy] = ctx.actions.tset(
+            LinkInfosTSet,
+            children = filter(None, [x._infos.get(link_strategy) for x in xs]),
+        )
+        merged_external_debug_info[link_strategy] = make_artifact_tset(
+            actions = ctx.actions,
+            label = ctx.label,
+            children = filter(None, [x._external_debug_info.get(link_strategy) for x in xs]),
+        )
+        merged_frameworks = _merge_framework_linkables([x.frameworks[link_strategy] for x in xs])
+        if merged_frameworks != _EMPTY_FRAMEWORKS_LINKABLE:
+            if frameworks == None:
+                frameworks = dict(_EMPTY_FRAMEWORKS_LINKABLE_BY_STRATEGY)
+            frameworks[link_strategy] = merged_frameworks
+
+        merged_swiftmodules = merge_swiftmodule_linkables(ctx, [x.swiftmodules[link_strategy] for x in xs])
+        if merged_swiftmodules != _EMPTY_SWIFTMODULE_LINKABLE:
+            if swiftmodules == None:
+                swiftmodules = dict(_EMPTY_SWIFTMODULE_LINKABLE_BY_STRATEGY)
+            swiftmodules[link_strategy] = merged_swiftmodules
+
+    return MergedLinkInfo(
+        _infos = merged,
+        _external_debug_info = merged_external_debug_info,
+        frameworks = frameworks if frameworks != None else _EMPTY_FRAMEWORKS_LINKABLE_BY_STRATEGY,
+        swiftmodules = swiftmodules if swiftmodules != None else _EMPTY_SWIFTMODULE_LINKABLE_BY_STRATEGY,
+    )
+
+def get_link_info(infos: LinkInfos, prefer_stripped: bool = False, prefer_optimized: bool = False) -> LinkInfo:
+    """
+    Helper for getting a `LinkInfo` out of a `LinkInfos`.
+    """
+
+    # When requested, prefer using pre-stripped link info.
+    if prefer_stripped and infos.stripped != None:
+        return infos.stripped
+    if prefer_optimized and infos.optimized:
+        return infos.optimized
+
+    return infos.default
+
+def unpack_link_args_metadata(args: LinkArgs) -> ArgLike:
+    if args.tset != None:
+        return args.tset.infos.project_as_args("metadata")
+    ret = cmd_args()
+    if args.infos != None:
+        for info in args.infos:
+            link_info_to_metadata_args(info, ret)
+    return ret
+
+def dedupe_dep_metadata(metadatas: list[DepMetadata]) -> list[DepMetadata]:
+    versions = set([m.version for m in metadatas])
+    return [DepMetadata(version = v) for v in versions]
+
+def truncate_dep_metadata(metadatas: list[DepMetadata]) -> list[DepMetadata]:
+    """
+    It's entirely possible we have way too much link metadata to put into buildinfo;
+    let's truncate based on the first 512 bytes (counting strings).
+    """
+    max_size = 512
+    size = 0
+    for i, metadata in enumerate(metadatas):
+        if size > max_size:
+            return metadatas[:i]
+        size += len(metadata.version)
+
+    return metadatas
+
+def link_args_metadata_with_flag(args: LinkArgs, link_metadata_flag: str | None = None) -> cmd_args:
+    cmd = cmd_args()
+    if link_metadata_flag:
+        cmd.add(cmd_args(unpack_link_args_metadata(args), prepend = link_metadata_flag))
+    return cmd
+
+def unpack_link_args(args: LinkArgs, link_ordering: [LinkOrdering, None] = None, link_metadata_flag: str | None = None) -> ArgLike:
+    cmd = link_args_metadata_with_flag(args, link_metadata_flag)
+    if args.tset != None:
+        ordering = link_ordering.value if link_ordering else "preorder"
+
+        tset = args.tset.infos
+        if args.tset.prefer_stripped:
+            cmd.add(tset.project_as_args("stripped", ordering = ordering))
+        else:
+            cmd.add(tset.project_as_args("default", ordering = ordering))
+        return cmd
+
+    if args.infos != None:
+        cmd.add([link_info_to_args(info) for info in args.infos])
+        return cmd
+
+    if args.flags != None:
+        cmd.add(args.flags)
+        return cmd
+
+    fail("Unpacked invalid empty link args")
+
+def unpack_link_args_excluding_object_files_and_lazy_archives(args: LinkArgs) -> [ArgLike, None]:
+    if args.tset != None:
+        if args.tset.prefer_stripped:
+            fail("Preferring stripped link infos is not supported by this function.")
+
+        return args.tset.infos.project_as_args("exclude_object_files_and_lazy_archives")
+
+    if args.infos != None:
+        result_args = cmd_args()
+        for info in args.infos:
+            result_args.add(link_info_to_args(info, argument_type_filter = LinkInfoArgumentFilter("exclude_object_files_and_lazy_archives")))
+        return result_args
+
+    if args.flags != None:
+        return args.flags
+
+    fail("Unpacked invalid empty link args")
+
+def unpack_link_args_object_files_and_lazy_archives_only(args: LinkArgs) -> [ArgLike, None]:
+    if args.tset != None:
+        if args.tset.prefer_stripped:
+            fail("Preferring stripped link infos is not supported by this function.")
+
+        return args.tset.infos.project_as_args("object_files_and_lazy_archives_only")
+
+    if args.infos != None:
+        result_args = cmd_args()
+        for info in args.infos:
+            result_args.add(link_info_to_args(info, argument_type_filter = LinkInfoArgumentFilter("object_files_and_lazy_archives_only")))
+        return result_args
+
+    if args.flags != None:
+        return None
+
+    fail("Unpacked invalid empty link args")
+
+def unpack_link_args_for_tbd_creation(args: LinkArgs) -> ArgLike:
+    if args.tset != None:
+        if args.tset.prefer_stripped:
+            fail("Preferring stripped link infos is not supported by this function.")
+
+        return args.tset.infos.project_as_args("tbd_creation_args")
+
+    if args.infos != None:
+        result_args = cmd_args()
+        for info in args.infos:
+            result_args.add(_link_info_to_tbd_creation_args(info))
+        return result_args
+
+    if args.flags != None:
+        return None
+
+    fail("Unpacked invalid empty link args")
+
+def unpack_external_debug_info(actions: AnalysisActions, args: LinkArgs) -> ArtifactTSet:
+    if args.tset != None:
+        if args.tset.prefer_stripped:
+            return ArtifactTSet()
+        return args.tset.external_debug_info
+
+    if args.infos != None:
+        return make_artifact_tset(
+            actions = actions,
+            children = [info.external_debug_info for info in args.infos],
+        )
+
+    if args.flags != None:
+        return ArtifactTSet()
+
+    fail("Unpacked invalid empty link args")
+
+def map_to_link_infos(links: list[LinkArgs]) -> list[LinkInfo]:
+    res = []
+
+    def append(v):
+        if v.pre_flags or v.post_flags or v.dist_thin_lto_codegen_flags or v.linkables:
+            res.append(v)
+
+    for link in links:
+        if link.tset != None:
+            for info in link.tset.infos.traverse():
+                if link.tset.prefer_stripped:
+                    append(info.stripped or info.default)
+                else:
+                    append(info.default)
+            continue
+        if link.infos != None:
+            for link in link.infos:
+                append(link)
+            continue
+        if link.flags != None:
+            append(LinkInfo(pre_flags = [link.flags]))
+            continue
+        fail("Unpacked invalid empty link args")
+    return res
+
+def get_link_args_for_strategy(
+    actions: AnalysisActions,
+    label: Label,
+    linker_info: LinkerInfo,
+    deps_merged_link_infos: list[MergedLinkInfo],
+    link_strategy: LinkStrategy,
+    prefer_stripped: bool,
+    transformation_spec_context: TransformationSpecContext | None,
+    additional_link_info: [LinkInfo, None] = None,
+) -> LinkArgs:
+    """
+    Derive the `LinkArgs` for a strategy and strip preference from a list of dependency's MergedLinkInfo.
+    """
+
+    infos_kwargs = {}
+    if additional_link_info:
+        infos_kwargs = {"value": LinkInfos(default = additional_link_info, stripped = additional_link_info)}
+    infos = actions.tset(LinkInfosTSet, children = filter(None, [x._infos.get(link_strategy) for x in deps_merged_link_infos]), **infos_kwargs)
+
+    external_debug_info = make_artifact_tset(
+        actions = actions,
+        label = label,
+        children = filter(
+            None,
+            [x._external_debug_info.get(link_strategy) for x in deps_merged_link_infos]
+            + ([additional_link_info.external_debug_info] if additional_link_info else []),
+        ),
+    )
+
+    if transformation_spec_context and not transformation_spec_context.provider.is_empty:
+        link_ordering = linker_info.link_ordering or "preorder"
+        flattened_results = []
+        for link_infos in infos.traverse(ordering = link_ordering):
+            link_info = get_link_info_for_transformation(
+                transformation_spec_context,
+                link_infos,
+                link_infos.label,
+                prefer_stripped,
+            )
+            flattened_results.append(link_info)
+        return LinkArgs(
+            infos = flattened_results,
+        )
+
+    return LinkArgs(
+        tset = LinkArgsTSet(
+            infos = infos,
+            external_debug_info = external_debug_info,
+            prefer_stripped = prefer_stripped,
+        ),
+    )
+
+def _get_non_transformed_info(link_infos: LinkInfos, prefer_stripped: bool) -> LinkInfo:
+    if prefer_stripped:
+        return link_infos.stripped or link_infos.default
+    return link_infos.default
+
+def get_link_info_for_transformation(
+    transformation_spec_context: TransformationSpecContext, link_infos: LinkInfos, label: Label | None, prefer_stripped: bool
+) -> LinkInfo:
+    info = None
+
+    if label:
+        transformation_kind = transformation_spec_context.provider.determine_transformation(label, transformation_spec_context.graph_info)
+        if transformation_kind:
+            if transformation_kind == TransformationKind("debug"):
+                info = link_infos.debuggable
+            elif transformation_kind == TransformationKind("optimized"):
+                info = link_infos.optimized
+
+    return info or _get_non_transformed_info(link_infos, prefer_stripped)
+
+def get_lib_output_style(requested_link_strategy: LinkStrategy, preferred_linkage: Linkage, pic_behavior: PicBehavior) -> LibOutputStyle:
+    """
+    Return what lib output style to use for a library for a requested link style and preferred linkage.
+    --------------------------------------------------------------
+    | preferred_linkage |              link_strategy             |
+    |                   |----------------------------------------|
+    |                   | static   | static_pic   |   shared     |
+    -------------------------------------------------------------|
+    |      static       | *archive | *pic_archive | *pic_archive |
+    |      shared       | shared   |   shared     |   shared     |
+    |       any         | *archive | *pic_archive |   shared     |
+    --------------------------------------------------------------
+
+    Either of *static or *static_pic may be changed to the other based on the pic_behavior
+    """
+    no_pic_style = _get_lib_output_style_without_pic_behavior(requested_link_strategy, preferred_linkage)
+    return process_output_style_for_pic_behavior(no_pic_style, pic_behavior)
+
+def _get_lib_output_style_without_pic_behavior(requested_link_strategy: LinkStrategy, preferred_linkage: Linkage) -> LibOutputStyle:
+    if preferred_linkage == Linkage("any"):
+        return default_output_style_for_link_strategy(requested_link_strategy)
+    elif preferred_linkage == Linkage("shared"):
+        return LibOutputStyle("shared_lib")
+    else:  # preferred_linkage = static
+        if requested_link_strategy == LinkStrategy("static"):
+            return LibOutputStyle("archive")
+        else:
+            return LibOutputStyle("pic_archive")
+
+def process_link_strategy_for_pic_behavior(link_strategy: LinkStrategy, behavior: PicBehavior) -> LinkStrategy:
+    """
+    Converts static/static_pic link styles to the appropriate static form according to the pic behavior.
+    """
+    if link_strategy == LinkStrategy("shared"):
+        return link_strategy
+    elif behavior == PicBehavior("supported"):
+        return link_strategy
+    elif behavior == PicBehavior("not_supported"):
+        return LinkStrategy("static")
+    elif behavior == PicBehavior("always_enabled"):
+        return LinkStrategy("static_pic")
+    else:
+        fail("Unknown pic_behavior: {}".format(behavior))
+
+# TODO(cjhopman): I think we should be able to make it an error to request an output style that
+# violates the PicBehavior if we consistently translate LinkStyle and other top-level requests (i.e.
+# it seems like the need to translate output styles points to us missing a translation at some higher level).
+def process_output_style_for_pic_behavior(output_style: LibOutputStyle, behavior: PicBehavior) -> LibOutputStyle:
+    """
+    Converts archive/archive_pic output styles to the appropriate output form according to the pic behavior.
+    """
+    if output_style == LibOutputStyle("shared_lib"):
+        return output_style
+    elif behavior == PicBehavior("supported"):
+        return output_style
+    elif behavior == PicBehavior("not_supported"):
+        return LibOutputStyle("archive")
+    elif behavior == PicBehavior("always_enabled"):
+        return LibOutputStyle("pic_archive")
+    else:
+        fail("Unknown pic_behavior: {}".format(behavior))
+
+def subtarget_for_output_style(output_style: LibOutputStyle) -> str:
+    # TODO(cjhopman): This preserves historical strings for these (when we used LinkStyle for both link strategies and
+    # output styles). It would be good to update that to match the LibOutputStyle.
+    return legacy_output_style_to_link_style(output_style).value.replace("_", "-")
+
+def get_output_styles_for_linkage(linkage: Linkage) -> list[LibOutputStyle]:
+    """
+    Return all possible `LibOutputStyle`s that apply for the given `Linkage`.
+    """
+    return _LIB_OUTPUT_STYLES_FOR_LINKAGE[linkage]
+
+def legacy_output_style_to_link_style(output_style: LibOutputStyle) -> LinkStyle:
+    """
+    We previously used LinkStyle to represent both the type of a library output and for the different default link strategies.
+
+    To support splitting those two concepts, some places are still using LinkStyle when they probably should be using LibOutputStyle.
+    """
+    if output_style == LibOutputStyle("shared_lib"):
+        return LinkStyle("shared")
+    elif output_style == LibOutputStyle("archive"):
+        return LinkStyle("static")
+    elif output_style == LibOutputStyle("pic_archive"):
+        return LinkStyle("static_pic")
+    fail("unrecognized output_style {}".format(output_style))
+
+def has_framework_linkable(linkables: list[[FrameworksLinkable, None]]) -> bool:
+    for linkable in linkables:
+        if linkable:
+            return True
+
+    return False
+
+def _merge_framework_linkables(linkables: list[[FrameworksLinkable, None]]) -> FrameworksLinkable:
+    if not has_framework_linkable(linkables):
+        return _EMPTY_FRAMEWORKS_LINKABLE
+
+    unique_frameworks = set()
+    unique_libraries = set()
+    for linkable in linkables:
+        if not linkable:
+            continue
+
+        unique_frameworks.update(linkable.frameworks)
+        unique_libraries.update(linkable.libraries)
+
+    # Non-None inputs can still be contentless (leaf nodes pass fresh empty
+    # records rather than None); collapse to the shared empty.
+    if not unique_frameworks and not unique_libraries:
+        return _EMPTY_FRAMEWORKS_LINKABLE
+
+    return FrameworksLinkable(
+        frameworks = unique_frameworks,
+        libraries = unique_libraries,
+    )
+
+def merge_swiftmodule_linkables(ctx: AnalysisContext, linkables: list[[SwiftmoduleLinkable, None]]) -> SwiftmoduleLinkable:
+    # Contentless linkables (empty inner tset) contribute nothing; dropping
+    # them here lets the all-empty and single-contributor cases share records
+    # instead of re-wrapping per node.
+    non_empty = [linkable for linkable in linkables if linkable != None and linkable.swiftmodules._tset != None]
+
+    if not non_empty:
+        return _EMPTY_SWIFTMODULE_LINKABLE
+
+    if len(non_empty) == 1:
+        return non_empty[0]
+
+    return SwiftmoduleLinkable(
+        swiftmodules = make_artifact_tset(
+            actions = ctx.actions,
+            label = ctx.label,
+            children = [linkable.swiftmodules for linkable in non_empty],
+        )
+    )
+
+def wrap_with_no_as_needed_shared_libs_flags(linker_type: LinkerType, link_info: LinkInfo) -> LinkInfo:
+    """
+    Wrap link info in args used to prevent linkers from dropping unused shared
+    library dependencies from the e.g. DT_NEEDED tags of the link.
+    """
+
+    if linker_type == LinkerType("gnu"):
+        return wrap_link_info(
+            inner = link_info,
+            pre_flags = (["-Wl,--push-state"] + get_no_as_needed_shared_libs_flags(linker_type)),
+            post_flags = ["-Wl,--pop-state"],
+        )
+
+    if linker_type == LinkerType("darwin"):
+        return link_info
+
+    fail("Linker type {} not supported".format(linker_type))
+
+# Represents information to debug linker commands. Used to carry information
+# about link commands.
+LinkCommandDebugOutput = record(
+    # The filename of the linkable output.
+    filename = str,
+    command = ArgLike,
+    argsfile = Artifact,
+)
+
+# NB: Debug output is _not_ transitive over deps, so tsets are not used here.
+LinkCommandDebugOutputInfo = provider(
+    fields = [
+        "debug_outputs",  # ["LinkCommandDebugOutput"]
+    ],
+)
+
+UnstrippedLinkOutputInfo = provider(
+    fields = {
+        "artifact": Artifact,
+    }
+)
+
+def make_link_command_debug_output(linked_object: LinkedObject) -> [LinkCommandDebugOutput, None]:
+    if not linked_object.output or not linked_object.linker_command or not linked_object.linker_argsfile:
+        return None
+    return LinkCommandDebugOutput(
+        filename = linked_object.output.short_path,
+        command = linked_object.linker_command,
+        argsfile = linked_object.linker_argsfile,
+    )
+
+# Given a list of `LinkCommandDebugOutput`, it will produce a JSON info file.
+# The JSON info file will contain entries for each link command. In addition,
+# it will _not_ materialize any inputs to the link command except:
+# - linker argfile
+def make_link_command_debug_output_json_info(actions: AnalysisActions, debug_outputs: list[LinkCommandDebugOutput]) -> Artifact:
+    json_info = []
+    associated_artifacts = []
+    for debug_output in debug_outputs:
+        json_info.append({
+            "argsfile": debug_output.argsfile,
+            "command": debug_output.command,
+            "filename": debug_output.filename,
+        })
+
+        # Ensure all argsfile get materialized, as those are needed for debugging
+        associated_artifacts.extend(filter(None, [debug_output.argsfile]))
+
+    # Explicitly drop all inputs by using `with_inputs = False`, we don't want
+    # to materialize all inputs to the link actions (which includes all object files
+    # and possibly other shared libraries).
+    json_output = actions.write_json("linker.command", json_info, with_inputs = False, has_content_based_path = False)
+    json_output_with_artifacts = json_output.with_associated_artifacts(associated_artifacts)
+    return json_output_with_artifacts
diff --git a/buck2/prelude/linking/linkable_graph.bzl b/buck2/prelude/linking/linkable_graph.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/linkable_graph.bzl
@@ -0,0 +1,368 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:compile_types.bzl", "CxxSrcCompileCommand")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "PicBehavior")
+load("@prelude//cxx:headers.bzl", "CPrecompiledHeaderInfo")
+# TODO(mattpayne): Add this back once the type is supported by dependency mgmt
+# load("@prelude//cxx:shared_library_interface.bzl", "SharedInterfaceInfo")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//python:python.bzl", "PythonLibraryInfo")
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    "@prelude//utils:graph_utils.bzl",
+    "depth_first_traversal_by",
+)
+load(
+    ":link_info.bzl",
+    "LibOutputStyle",
+    "LinkInfo",  # @unused Used as a type
+    "LinkInfos",
+    "LinkStrategy",
+    "LinkerFlags",
+    "MergedLinkInfo",
+    "get_lib_output_style",
+    "get_output_styles_for_linkage",
+    _get_link_info = "get_link_info",
+)
+load(
+    ":shared_libraries.bzl",
+    "SharedLibraries",
+)
+
+# A provider with information used to link a rule into a shared library.
+# Potential omnibus roots must provide this so that omnibus can link them
+# here, in the context of the top-level packaging rule.
+LinkableRootInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "label": provider_field(Label),
+        "link_infos": provider_field(typing.Any, default = None),  # LinkInfos
+        "name": provider_field(typing.Any, default = None),  # [str, None]
+        "deps": provider_field(typing.Any, default = None),  # ["label"]
+    },
+)
+
+###############################################################################
+# Linkable Graph collects information on a node in the target graph that
+# contains linkable output. This graph information may then be provided to any
+# consumers of this target.
+###############################################################################
+
+_DisallowConstruction = record()
+_TargetSourceType = Artifact | str | tuple
+
+LinkableNode = record(
+    # Attribute labels on the target.
+    labels = field(list[str], []),
+    # Preferred linkage for this target.
+    preferred_linkage = field(Linkage, Linkage("any")),
+    default_link_strategy = field(LinkStrategy),
+    # Linkable deps of this target.
+    deps = field(list[Label], []),
+    # Exported linkable deps of this target.
+    #
+    # We distinguish between deps and exported deps so that when creating shared
+    # libraries in a large graph we only need to link each library against its
+    # deps and their (transitive) exported deps. This helps keep link lines smaller
+    # and produces more efficient libs (for example, DT_NEEDED stays a manageable size).
+    exported_deps = field(list[Label], []),
+    # List of both deps and exported deps. We traverse linkable graph lots of times
+    # and preallocating this list saves RAM during analysis
+    all_deps = field(list[Label], []),
+    # Link infos for all supported lib output styles supported by this node. This should have a value
+    # for every output_style supported by the preferred linkage.
+    link_infos = field(dict[LibOutputStyle, LinkInfos], {}),
+    # Contains the linker flags for this node.
+    # Note: The values in link_infos will already be adding in the exported_linker_flags
+    # TODO(cjhopman): We should probably make all use of linker_flags explicit, but that may need to wait
+    # for all link strategies to operate on the LinkableGraph.
+    linker_flags = field(LinkerFlags),
+    # Shared libraries provided by this target.  Used if this target is
+    # excluded.
+    shared_libs = field(SharedLibraries, SharedLibraries(libraries = [])),
+    # The soname this node would use in default link strategies. May be used by non-default
+    # link strategies as a lib's soname.
+    default_soname = field(str | None),
+    # Records Android's can_be_asset value for the node. This indicates whether the node can be bundled
+    # as an asset in android apks.
+    can_be_asset = field(bool),
+    # Collected target sources from the target.
+    srcs = field(list[_TargetSourceType]),
+    # Whether the node should appear in the android mergemap (which provides information about the original
+    # soname->final merged lib mapping)
+    include_in_android_mergemap = field(bool),
+    # Don't follow dependents on this node even if has preferred linkage static
+    ignore_force_static_follows_dependents = field(bool),
+    # Should this library only be used for build time linkage
+    stub = field(bool),
+    # Per-source C/C++ compile commands for this node, used to aggregate an app-level native
+    # compile-command database (the [native_build_commands][compile] sub-target). Populated only when
+    # compile-command capture is enabled (see cxx_library); empty otherwise and for nodes with no
+    # sources (e.g. prebuilt libraries).
+    compile_cmds = field(list[CxxSrcCompileCommand], []),
+    # Only allow constructing within this file.
+    _private = _DisallowConstruction,
+)
+
+LinkableGraphNode = record(
+    # Target/label of this node
+    label = field(Label),
+    # If this node has linkable output, it's linkable data
+    linkable = field([LinkableNode, None]),
+    # All potential root notes for an omnibus link (e.g. C++ libraries,
+    # C++ Python extensions).
+    roots = field(dict[Label, LinkableRootInfo]),
+    # Exclusions this node adds to the Omnibus graph
+    excluded = field(dict[Label, None]),
+    # Only allow constructing within this file.
+    _private = _DisallowConstruction,
+)
+
+LinkableGraphTSet = transitive_set()
+
+# The LinkableGraph for a target holds all the transitive nodes, roots, and exclusions
+# from all of its dependencies.
+#
+# TODO(cjhopman): Rather than flattening this at each node, we should build up an actual
+# graph structure.
+LinkableGraph = provider(
+    fields = {
+        # Target identifier of the graph.
+        "label": provider_field(typing.Any, default = None),  # Label
+        "nodes": provider_field(typing.Any, default = None),  # "LinkableGraphTSet"
+    }
+)
+
+# Used to tag a rule as providing a shared native library that may be loaded
+# dynamically, at runtime (e.g. via `dlopen`).
+DlopenableLibraryInfo = provider(fields = {})
+
+DLOPENABLE_LIBRARY_INFO_MARKER = DlopenableLibraryInfo()
+
+def _get_required_outputs_for_linkage(linkage: Linkage) -> list[LibOutputStyle]:
+    if linkage == Linkage("shared"):
+        return [LibOutputStyle("shared_lib")]
+
+    return get_output_styles_for_linkage(linkage)
+
+def _get_target_sources(ctx: AnalysisContext) -> list[_TargetSourceType]:
+    srcs = []
+    if hasattr(ctx.attrs, "srcs"):
+        srcs.extend(ctx.attrs.srcs)
+    return srcs
+
+def create_linkable_node(
+    ctx: AnalysisContext,
+    default_soname: str | None,
+    preferred_linkage: Linkage = Linkage("any"),
+    default_link_strategy: LinkStrategy = LinkStrategy("shared"),
+    deps: list[Dependency | LinkableGraph] = [],
+    exported_deps: list[Dependency | LinkableGraph] = [],
+    link_infos: dict[LibOutputStyle, LinkInfos] = {},
+    shared_libs: SharedLibraries = SharedLibraries(libraries = []),
+    can_be_asset: bool = True,
+    include_in_android_mergemap: bool = True,
+    linker_flags: [LinkerFlags, None] = None,
+    ignore_force_static_follows_dependents: bool = False,
+    stub: bool = False,
+    compile_cmds: list[CxxSrcCompileCommand] = [],
+) -> LinkableNode:
+    for output_style in _get_required_outputs_for_linkage(preferred_linkage):
+        expect(
+            output_style in link_infos,
+            "must have {} link info".format(output_style),
+        )
+    if not linker_flags:
+        linker_flags = LinkerFlags()
+    deps = linkable_deps(deps)
+    exported_deps = linkable_deps(exported_deps)
+    return LinkableNode(
+        labels = ctx.attrs.labels,
+        preferred_linkage = preferred_linkage,
+        default_link_strategy = default_link_strategy,
+        deps = deps,
+        exported_deps = exported_deps,
+        all_deps = deps + exported_deps,
+        link_infos = link_infos,
+        shared_libs = shared_libs,
+        can_be_asset = can_be_asset,
+        srcs = _get_target_sources(ctx),
+        include_in_android_mergemap = include_in_android_mergemap,
+        default_soname = default_soname,
+        linker_flags = linker_flags,
+        ignore_force_static_follows_dependents = ignore_force_static_follows_dependents,
+        stub = stub,
+        compile_cmds = compile_cmds,
+        _private = _DisallowConstruction(),
+    )
+
+def create_linkable_graph_node(
+    ctx: AnalysisContext,
+    linkable_node: [LinkableNode, None] = None,
+    roots: dict[Label, LinkableRootInfo] = {},
+    excluded: dict[Label, None] = {},
+    label: Label | None = None,
+) -> LinkableGraphNode:
+    if not label:
+        label = ctx.label
+    return LinkableGraphNode(
+        label = label,
+        linkable = linkable_node,
+        roots = roots,
+        excluded = excluded,
+        _private = _DisallowConstruction(),
+    )
+
+def create_linkable_graph(
+    ctx: AnalysisContext,
+    node: [LinkableGraphNode, None] = None,
+    # This list of deps must include all deps referenced by the LinkableGraphNode.
+    deps: list[[LinkableGraph, Dependency]] = [],
+) -> LinkableGraph:
+    graph_deps = []
+    for d in deps:
+        if isinstance(d, LinkableGraph):
+            graph_deps.append(d)
+        else:
+            graph = d.get(LinkableGraph)
+            if graph:
+                graph_deps.append(graph)
+
+    if node and node.linkable:
+        deps_labels = set([x.label for x in graph_deps])
+        for l in [node.linkable.deps, node.linkable.exported_deps]:  # buildifier: disable=confusing-name
+            for d in l:
+                if not d in deps_labels:
+                    fail(
+                        "LinkableNode had {} in its deps, but that label is missing from the node's linkable graph children (`{}`)".format(
+                            d, ", ".join(deps_labels)
+                        )
+                    )
+
+    children = [x.nodes for x in graph_deps]
+
+    kwargs = {
+        "children": children,
+    }
+    if node:
+        kwargs["value"] = node
+        label = node.label
+    else:
+        label = ctx.label
+    return LinkableGraph(
+        label = label,
+        nodes = ctx.actions.tset(LinkableGraphTSet, **kwargs),
+    )
+
+ReducedLinkableGraph = record(
+    # Label to information map for whole graph.
+    # Does not have entry for executable
+    nodes = field(dict[Label, LinkableNode]),
+    # Order of linkable in the graph as it would go into linker argsfile
+    # when building executable in static link strategy
+    link_order = field(dict[Label, int]),
+)
+
+def reduce_linkable_graph(graph: LinkableGraph) -> ReducedLinkableGraph:
+    linkable_nodes = {}
+    link_order = {}
+
+    # Link groups machinery may be used by something that does not
+    # store all information in dependency graph. E.g. python native dlopen
+    # So gathering link ordering starting from executable label may not collect all
+    # dependencies correctly. To account for that we add remaining pieces to
+    # final result. There is no particular reasoning behing putting remaining linkables first,
+    # but it is just more convenient to implement.
+    # So to make it work properly we start with `1` instead of `0` and return default `0` for linkables
+    # that we did not put into linkable graph nodes.
+    link_order_idx = 1
+
+    for node in filter(None, graph.nodes.traverse()):
+        if node.linkable:
+            linkable_nodes[node.label] = node.linkable
+            link_order[node.label] = link_order_idx
+            link_order_idx += 1
+
+    return ReducedLinkableGraph(
+        nodes = linkable_nodes,
+        link_order = link_order,
+    )
+
+def get_linkable_graph_node_map_func(graph: LinkableGraph):
+    def get_linkable_graph_node_map() -> dict[Label, LinkableNode]:
+        nodes = graph.nodes.traverse()
+        linkable_nodes = {}
+        for node in filter(None, nodes):
+            if node.linkable:
+                linkable_nodes[node.label] = node.linkable
+        return linkable_nodes
+
+    return get_linkable_graph_node_map
+
+def linkable_deps(deps: list[Dependency | LinkableGraph]) -> list[Label]:
+    labels = []
+
+    for dep in deps:
+        if isinstance(dep, LinkableGraph):
+            labels.append(dep.label)
+        else:
+            dep_info = linkable_graph(dep)
+            if dep_info != None:
+                labels.append(dep_info.label)
+
+    return labels
+
+def linkable_graph(dep: Dependency) -> [LinkableGraph, None]:
+    """
+    Helper to extract `LinkableGraph` from a dependency which also
+    provides `MergedLinkInfo`.
+    """
+
+    # We only care about "linkable" deps.
+    if PythonLibraryInfo in dep or MergedLinkInfo not in dep or dep.label.sub_target == ["headers"]:
+        return None
+
+    if CPrecompiledHeaderInfo in dep:
+        # `cxx_precompiled_header()` does not contribute to the link, only to compile
+        return None
+
+    return dep[LinkableGraph]
+
+def get_link_info(node: LinkableNode, output_style: LibOutputStyle, prefer_stripped: bool = False, prefer_optimized: bool = False) -> LinkInfo:
+    info = _get_link_info(
+        node.link_infos[output_style],
+        prefer_stripped = prefer_stripped,
+        prefer_optimized = prefer_optimized,
+    )
+    return info
+
+def get_deps_for_link(
+    node: LinkableNode, strategy: LinkStrategy, pic_behavior: PicBehavior, overridden_preferred_linkage: Linkage | None = None
+) -> list[Label]:
+    """
+    Return deps to follow when linking against this node with the given link
+    style.
+    """
+
+    # If we're linking statically, include non-exported deps.
+    output_style = get_lib_output_style(strategy, overridden_preferred_linkage if overridden_preferred_linkage else node.preferred_linkage, pic_behavior)
+    if output_style != LibOutputStyle("shared_lib"):
+        return node.all_deps
+    else:
+        return node.exported_deps
+
+def get_transitive_deps(link_infos: dict[Label, LinkableNode], roots: list[Label]) -> list[Label]:
+    """
+    Return all transitive deps from following the given nodes.
+    """
+
+    def find_transitive_deps(node: Label):
+        return link_infos[node].all_deps
+
+    return depth_first_traversal_by(link_infos, roots, find_transitive_deps)
diff --git a/buck2/prelude/linking/linkables.bzl b/buck2/prelude/linking/linkables.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/linkables.bzl
@@ -0,0 +1,51 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    ":link_groups.bzl",
+    "LinkGroupLibInfo",
+)
+load(
+    ":link_info.bzl",
+    "MergedLinkInfo",
+)
+load(
+    ":linkable_graph.bzl",
+    "LinkableGraph",
+    "LinkableRootInfo",
+)
+load(
+    ":shared_libraries.bzl",
+    "SharedLibraryInfo",
+)
+
+# A record containing all provider types used for linking in the prelude.  This
+# is essentially the minimal subset of a "linkable" `dependency` that user rules
+# need to implement linking, and avoids needing functions to take the heavier-
+# weight `dependency` type.
+LinkableProviders = record(
+    link_group_lib_info = field(LinkGroupLibInfo),
+    linkable_graph = field([LinkableGraph, None], None),
+    merged_link_info = field(MergedLinkInfo),
+    shared_library_info = field(SharedLibraryInfo),
+    linkable_root_info = field([LinkableRootInfo, None], None),
+)
+
+def linkable(dep: Dependency) -> LinkableProviders:
+    expect(LinkGroupLibInfo in dep, str(dep.label.raw_target()))
+    return LinkableProviders(
+        shared_library_info = dep[SharedLibraryInfo],
+        linkable_graph = dep.get(LinkableGraph),
+        merged_link_info = dep[MergedLinkInfo],
+        link_group_lib_info = dep[LinkGroupLibInfo],
+        linkable_root_info = dep.get(LinkableRootInfo),
+    )
+
+def linkables(deps: list[Dependency]) -> list[LinkableProviders]:
+    return [linkable(dep) for dep in deps if MergedLinkInfo in dep]
diff --git a/buck2/prelude/linking/lto.bzl b/buck2/prelude/linking/lto.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/lto.bzl
@@ -0,0 +1,99 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",
+    "LinkerType",
+)
+load("@prelude//cxx:debug.bzl", "SplitDebugMode")
+
+# Styles of LTO.
+LtoMode = enum(
+    # No LTO
+    "none",
+    # Object files contain both LTO IR and native code to allow binaries to link
+    # either via standard or LTO.
+    "fat",
+    # Traditional, monolithic LTO.
+    "monolithic",
+    # https://clang.llvm.org/docs/ThinLTO.html
+    "thin",
+)
+
+def lto_compiler_flags(lto_mode: LtoMode) -> list[str]:
+    if lto_mode == LtoMode("none"):
+        return []
+    elif lto_mode == LtoMode("fat") or lto_mode == LtoMode("monolithic"):
+        return ["-flto=full"]
+    elif lto_mode == LtoMode("thin"):
+        return ["-flto=thin"]
+    else:
+        fail("Unhandled LTO mode: " + repr(lto_mode))
+
+SplitDebugLtoInfo = record(
+    # The output that the linker will generate split debug object(s) too.  May
+    # be a single object file (e.g. for darwin+monoLTO) or a directory.
+    output = field(Artifact),
+    # The flags to add to the link to use the above output.
+    linker_flags = field(cmd_args),
+)
+
+def get_split_debug_lto_info(actions: AnalysisActions, cxx_toolchain: CxxToolchainInfo, name: str) -> [SplitDebugLtoInfo, None]:
+    linker_info = cxx_toolchain.linker_info
+
+    # We only generate these flags for LTO+DWO.
+    if cxx_toolchain.split_debug_mode == SplitDebugMode("none"):
+        return None
+    if cxx_toolchain.linker_info.lto_mode == LtoMode("none"):
+        return None
+
+    # TODO: It might be nice to generalize a but more and move the darwin v. gnu
+    # differences into toolchain settings (e.g. `split_debug_lto_flags_fmt`).
+    if linker_info.type == LinkerType("darwin"):
+        # https://releases.llvm.org/14.0.0/tools/clang/docs/CommandGuide/clang.html#cmdoption-flto
+        # We need to pass -object_path_lto to keep the temporary LTO object files around to use
+        # for dSYM generation.
+        if linker_info.lto_mode == LtoMode("thin"):
+            # For thin LTO the path is a folder that will contain the various object files.
+            lto_object_path_artifact = actions.declare_output("lto_object_files", dir = True, has_content_based_path = False)
+        else:
+            # For monolithic LTO the path is a single object file.
+            lto_object_path_artifact = actions.declare_output("lto_object_file.o", dir = False, has_content_based_path = False)
+
+        linker_args = cmd_args([
+            # Use -Xlinker in case the path has a ,
+            "-Xlinker",
+            "-object_path_lto",
+            "-Xlinker",
+            lto_object_path_artifact.as_output(),
+        ])
+
+        return SplitDebugLtoInfo(
+            output = lto_object_path_artifact,
+            linker_flags = linker_args,
+        )
+
+    if linker_info.type == LinkerType("gnu"):
+        dwo_dir = actions.declare_output(name + ".dwo.d", dir = True, has_content_based_path = False)
+
+        linker_flags = cmd_args([
+            "-Xlinker",
+            "-plugin-opt",
+            "-Xlinker",
+            # NOTE: can't use -Wl,plugin-opt,dwo_dir=... because the $(output ...)
+            # macro might be expanded to a value with commas breaking -Wl, parsing.
+            cmd_args(dwo_dir.as_output(), format = "dwo_dir={}"),
+        ])
+
+        return SplitDebugLtoInfo(
+            output = dwo_dir,
+            linker_flags = linker_flags,
+        )
+
+    fail("can't handle split-debug+LTO for linker type: {}".format(linker_info.type))
diff --git a/buck2/prelude/linking/shared_libraries.bzl b/buck2/prelude/linking/shared_libraries.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/shared_libraries.bzl
@@ -0,0 +1,396 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load(
+    "@prelude//cxx:transformation_spec.bzl",
+    "TransformationKind",
+    "TransformationSpecContext",  # @unused Used as a type
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkArgs",
+    "LinkableFlavor",  # @unused Used as a type
+    "LinkedObject",  # @unused Used as a type
+)
+load("@prelude//linking:strip.bzl", "strip_object")
+load("@prelude//utils:expect.bzl", "expect")
+
+Soname = record(
+    # Return the SONAME if it's a string, otherwise None.
+    as_str = field(typing.Callable),
+    # Return the SONAME as a string, throwing an error if it is actually an
+    # artifact.
+    ensure_str = field(typing.Callable),
+    # Return `True` if the SONAME is respresented as a string.
+    is_str = field(bool),
+    # The actual SONAME can be represented by a static string, or the
+    # contents of a file generated at build time.
+    _soname = field(str | Artifact),
+)
+
+SharedLibrary = record(
+    lib = field(LinkedObject),
+    # The LinkArgs used to produce this SharedLibrary. This can be useful for debugging or
+    # for downstream rules to reproduce the shared library with some modifications (for example
+    # android relinker will link again with an added version script argument).
+    # TODO(cjhopman): This is currently always available.
+    link_args = field(list[LinkArgs] | None, None),
+    # The sonames of the shared libraries that this links against.
+    # TODO(cjhopman): This is currently always available.
+    shlib_deps = field(list[str] | None, None),
+    stripped_lib = field(Artifact | None, None),
+    can_be_asset = field(bool, False),
+    for_primary_apk = field(bool, False),
+    soname = field(Soname),
+    label = field(Label),
+    extra_outputs = field(dict[str, list[DefaultInfo]], default = {}),
+)
+
+def _ensure_str(soname: str | Artifact) -> str:
+    expect(type(soname) == type(""), "SONAME is not a `str`: {}", soname)
+    return soname
+
+def to_soname(soname: str | Artifact | Soname) -> Soname:
+    if isinstance(soname, Soname):
+        return soname
+    soname_is_str = isinstance(soname, str)
+    return Soname(
+        as_str = lambda: soname if soname_is_str else None,
+        ensure_str = lambda: _ensure_str(soname),
+        is_str = soname_is_str,
+        _soname = soname,
+    )
+
+def create_shlib(
+    # The soname can either be a string or an artifact with the soname in
+    # text form.
+    soname: str | Artifact | Soname,
+    **kwargs,
+) -> SharedLibrary:
+    return SharedLibrary(soname = to_soname(soname), **kwargs)
+
+SharedLibraries = record(
+    label = field(Label | None, None),
+    # A mapping of shared library SONAME (e.g. `libfoo.so.2`) to the artifact.
+    # Since the SONAME is what the dynamic loader uses to uniquely identify
+    # libraries, using this as the key allows easily detecting conflicts from
+    # dependencies.
+    libraries = field(list[SharedLibrary]),
+    flavored_libraries = field(dict[LinkableFlavor, SharedLibrary] | None, None),
+)
+
+def _project_external_debug_info(shared_libraries: SharedLibraries) -> cmd_args:
+    rv = cmd_args()
+    for shared_library in shared_libraries.libraries:
+        external_debug_info = shared_library.lib.external_debug_info._tset
+        if external_debug_info:
+            rv.add(external_debug_info.project_as_args("artifacts"))
+    return rv
+
+def _project_symlink_tree(shared_libraries: SharedLibraries) -> list[(bool, str | Artifact, Artifact, Artifact | None)]:
+    rv = []
+    for shared_library in shared_libraries.libraries:
+        soname = shared_library.soname  # type: Soname
+        linked_object = shared_library.lib  # type: LinkedObject
+
+        rv.append(
+            (
+                soname.is_str,
+                soname._soname,
+                linked_object.output,
+                linked_object.dwp,
+            )
+        )
+    return rv
+
+# T-set of SharedLibraries
+SharedLibrariesTSet = transitive_set(
+    args_projections = {
+        "external_debug_info": _project_external_debug_info,
+    },
+    json_projections = {
+        "symlink_tree": _project_symlink_tree,
+    },
+)
+
+# Shared libraries required by top-level packaging rules (e.g. shared libs
+# for Python binary, symlink trees of shared libs for C++ binaries)
+SharedLibraryInfo = provider(
+    fields = {
+        "set": provider_field(SharedLibrariesTSet | None, default = None),
+    }
+)
+
+EMPTY_SHARED_LIBRARY_INFO = SharedLibraryInfo(set = None)
+
+def get_strip_non_global_flags(cxx_toolchain: CxxToolchainInfo) -> list:
+    if cxx_toolchain.strip_flags_info and cxx_toolchain.strip_flags_info.strip_non_global_flags:
+        return cxx_toolchain.strip_flags_info.strip_non_global_flags
+
+    return ["--strip-unneeded"]
+
+def create_shlib_from_ctx(
+    ctx: AnalysisContext, soname: str | Artifact | Soname, lib: LinkedObject, extra_outputs: dict[str, list[DefaultInfo]] = {}
+) -> SharedLibrary:
+    cxx_toolchain = getattr(ctx.attrs, "_cxx_toolchain", None)
+    return create_shlib(
+        lib = lib,
+        stripped_lib = strip_object(
+            ctx,
+            cxx_toolchain[CxxToolchainInfo],
+            lib.output,
+            cmd_args(get_strip_non_global_flags(cxx_toolchain[CxxToolchainInfo])),
+        )
+        if cxx_toolchain != None
+        else None,
+        link_args = lib.link_args,
+        shlib_deps = None,  # TODO(cjhopman): we need this figured out.
+        can_be_asset = getattr(ctx.attrs, "can_be_asset", False) or False,
+        for_primary_apk = getattr(ctx.attrs, "used_by_wrap_script", False),
+        label = ctx.label,
+        soname = soname,
+        extra_outputs = extra_outputs,
+    )
+
+NamedLinkedObject = record(
+    soname = field(str),
+    linked_object = field(LinkedObject),
+    extra_outputs = field(dict[str, list[DefaultInfo]], {}),
+)
+
+def create_flavored_shared_libraries(ctx: AnalysisContext, libraries: dict[LinkableFlavor, NamedLinkedObject]) -> SharedLibraries:
+    default_libraries = []
+    flavored_libraries = {}
+    for flavor in libraries:
+        solib = libraries[flavor]
+        shlib = create_shlib_from_ctx(
+            ctx = ctx,
+            soname = solib.soname,
+            lib = solib.linked_object,
+            extra_outputs = solib.extra_outputs,
+        )
+        flavored_libraries[flavor] = shlib
+        if flavor == LinkableFlavor("default"):
+            default_libraries.append(shlib)
+
+    return SharedLibraries(
+        label = ctx.label,
+        libraries = default_libraries,
+        flavored_libraries = flavored_libraries,
+    )
+
+def create_shared_libraries(
+    ctx: AnalysisContext, libraries: dict[str, LinkedObject], extra_outputs: dict[str, dict[str, list[DefaultInfo]]] = {}
+) -> SharedLibraries:
+    """
+    Take a mapping of dest -> src and turn it into a mapping that will be
+    passed around in providers. Used for both srcs, and resources.
+    """
+    return SharedLibraries(
+        label = ctx.label,
+        libraries = [
+            create_shlib_from_ctx(
+                ctx = ctx,
+                soname = name,
+                lib = shlib,
+                extra_outputs = extra_outputs.get(name, {}),
+            )
+            for (name, shlib) in libraries.items()
+        ],
+    )
+
+# Merge multiple SharedLibraryInfo. The value in `node` represents a set of
+# SharedLibraries that is provided by the target being analyzed. It's optional
+# because that might not always exist, e.g. a Python library can pass through
+# SharedLibraryInfo but it cannot produce any. The value in `deps` represents
+# all the inherited shared libraries for this target.
+def merge_shared_libraries(actions: AnalysisActions, node: [SharedLibraries, None] = None, deps: list[SharedLibraryInfo] = []) -> SharedLibraryInfo:
+    kwargs = {}
+
+    contributing_deps = []
+    children = []
+    for dep in deps:
+        if dep.set != None:
+            contributing_deps.append(dep)
+            children.append(dep.set)
+
+    if node == None:
+        if not children:
+            return EMPTY_SHARED_LIBRARY_INFO
+        if len(children) == 1:
+            # With no local value, one contributing dep is already the complete
+            # merged result.
+            return contributing_deps[0]
+    if children:
+        kwargs["children"] = children
+    if node != None:
+        kwargs["value"] = node
+
+    set = actions.tset(SharedLibrariesTSet, **kwargs) if kwargs else None
+    return SharedLibraryInfo(set = set)
+
+def traverse_shared_library_info(info: SharedLibraryInfo, transformation_provider: TransformationSpecContext | None) -> list[SharedLibrary]:
+    libraries = []
+    if info.set:
+        for libs in info.set.traverse():
+            fallback_to_default = True
+
+            if transformation_provider and not transformation_provider.provider.is_empty and libs.label and libs.flavored_libraries:
+                transformation_kind = transformation_provider.provider.determine_transformation(libs.label, transformation_provider.graph_info)
+
+                if transformation_kind == TransformationKind("debug") and LinkableFlavor("debug") in libs.flavored_libraries:
+                    libraries.append(libs.flavored_libraries[LinkableFlavor("debug")])
+                    fallback_to_default = False
+                elif transformation_kind == TransformationKind("optimized") and LinkableFlavor("optimized") in libs.flavored_libraries:
+                    libraries.append(libs.flavored_libraries[LinkableFlavor("optimized")])
+                    fallback_to_default = False
+
+            if fallback_to_default:
+                libraries.extend(libs.libraries)
+
+    return libraries
+
+# Helper to merge shlibs, throwing an error if more than one have the same SONAME.
+def _merge_shlibs(shared_libs: list[SharedLibrary], resolve_soname: typing.Callable) -> dict[str, SharedLibrary]:
+    merged = {}
+    for shlib in shared_libs:
+        soname = resolve_soname(shlib.soname)
+        existing = merged.get(soname)
+        if existing != None and existing.lib != shlib.lib:
+            error = "Duplicate library {}! Conflicting mappings:\n" + "{} from {}\n" + "{} from {}"
+            fail(
+                error.format(
+                    shlib.soname,
+                    existing.lib,
+                    existing.label,
+                    shlib.lib,
+                    shlib.label,
+                ),
+            )
+        merged[soname] = shlib
+    return merged
+
+def with_unique_str_sonames(shared_libs: list[SharedLibrary], skip_dynamic: bool = False) -> dict[str, SharedLibrary]:
+    """
+    Convert a list of `SharedLibrary`s to a map of unique SONAMEs to the
+    corresponding `SharedLibrary`.
+
+    Will fail if the same SONAME maps to multiple `SharedLibrary`s.
+    """
+    return _merge_shlibs(
+        shared_libs = [shlib for shlib in shared_libs if shlib.soname.is_str or not skip_dynamic],
+        resolve_soname = lambda s: s.ensure_str(),
+    )
+
+def gen_shared_libs_action(actions: AnalysisActions, out: str, shared_libs: list[SharedLibrary], gen_action: typing.Callable, dir = False) -> Artifact:
+    """
+    Produce an action by first resolving all SONAME of the given shlibs and
+    enforcing that each SONAME is unique.
+
+    The provided `gen_action` callable is called with a map of unique SONAMEs
+    to the corresponding shlibs.
+    """
+
+    output = actions.declare_output(out, dir = dir, has_content_based_path = False)
+
+    def func(actions, artifacts, output):
+        def resolve_soname(soname):
+            if soname.is_str:
+                return soname._soname
+            else:
+                return artifacts[soname._soname].read_string().strip()
+
+        gen_action(
+            actions,
+            output,
+            _merge_shlibs(
+                shared_libs = shared_libs,
+                resolve_soname = resolve_soname,
+            ),
+        )
+
+    dynamic_sonames = [shlib.soname._soname for shlib in shared_libs if not shlib.soname.is_str]
+    if dynamic_sonames:
+        actions.dynamic_output(
+            dynamic = dynamic_sonames,
+            inputs = [],
+            outputs = [output.as_output()],
+            f = lambda ctx, artifacts, outputs: func(ctx.actions, artifacts, outputs[output]),
+        )
+    else:
+        func(actions, {}, output)
+
+    return output
+
+def zip_shlibs(merged: dict[str, SharedLibrary], vals: list[(SharedLibrary, typing.Any)]) -> list[(str, SharedLibrary, typing.Any)]:
+    """
+    Helper to "zip" together the soname->shlib map to a list with associated
+    shared lib values.
+
+    This is useful for callers of `gen_shared_libs_action` to combine the merged
+    shared libs, in dedup'd dict form, with some additional data.
+    """
+
+    zipped = []
+
+    # Walk through the shlib and val tuples
+    idx = 0
+    for soname, shlib in merged.items():
+        for idx in range(idx, len(vals)):
+            if vals[idx][0] == shlib:
+                break
+        zipped.append((soname, shlib, vals[idx][1]))
+
+    return zipped
+
+def create_shlib_symlink_tree(actions: AnalysisActions, out: str, shared_libs: list[SharedLibrary]) -> Artifact:
+    """
+    Merged shared libs into a symlink tree mapping the library's SONAME to
+    it's artifact.
+    """
+    return gen_shared_libs_action(
+        actions = actions,
+        out = out,
+        shared_libs = shared_libs,
+        gen_action = lambda actions, output, shared_libs: actions.symlinked_dir(
+            output,
+            {name: shlib.lib.output for name, shlib in shared_libs.items()},
+            has_content_based_path = False,
+        ),
+        dir = True,
+    )
+
+def create_shlib_dwp_tree(actions: AnalysisActions, out: str, shared_libs: list[SharedLibrary]) -> Artifact:
+    return gen_shared_libs_action(
+        actions = actions,
+        out = out,
+        shared_libs = shared_libs,
+        gen_action = lambda actions, output, shared_libs: actions.symlinked_dir(
+            output,
+            {name + ".dwp": shlib.lib.dwp for name, shlib in shared_libs.items() if shlib.lib.dwp != None},
+            has_content_based_path = False,
+        ),
+        dir = True,
+    )
+
+def extract_soname_from_shlib(actions: AnalysisActions, name: str, shared_lib: Artifact) -> Artifact:
+    """
+    Extract the SONAME from a shared library into a file.
+    """
+    soname = actions.declare_output(name, has_content_based_path = False)
+    cmd = cmd_args(
+        "sh",
+        "-c",
+        '''set -euo pipefail; objdump -p "$1" | grep SONAME | awk '{print $2}' > "$2"''',
+        "",
+        shared_lib,
+        soname.as_output(),
+    )
+    actions.run(cmd, category = "extract_soname", identifier = shared_lib.short_path)
+    return soname
diff --git a/buck2/prelude/linking/stamp_build_info.bzl b/buck2/prelude/linking/stamp_build_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/stamp_build_info.bzl
@@ -0,0 +1,117 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_library_utility.bzl",
+    "cxx_is_gnu",
+)
+load("@prelude//linking:add_elf_sections.bzl", "add_elf_sections")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkArgs",  # @unused Used as a type
+    "dedupe_dep_metadata",
+    "get_link_info",
+    "truncate_dep_metadata",
+)
+
+PRE_STAMPED_SUFFIX = "-pre_stamped"
+
+def cxx_stamp_build_info(ctx: AnalysisContext) -> bool:
+    if getattr(ctx.attrs, "_generated_build_info_enabled", False):
+        spec = ctx.attrs._generated_build_info_spec
+        return bool(spec.get("link_as_shared_library", False) and cxx_is_gnu(ctx))
+
+    generated_build_info = getattr(ctx.attrs, "_generated_build_info_spec", {})
+    if generated_build_info.get("enabled", False):
+        return bool(generated_build_info.get("link_as_shared_library", False) and cxx_is_gnu(ctx))
+
+    if not hasattr(ctx.attrs, "_build_info") or not ctx.attrs._build_info or not cxx_is_gnu(ctx):
+        return False
+
+    late_build_info_stamping = getattr(ctx.attrs, "_late_build_info_stamping", None)
+    return late_build_info_stamping == None or late_build_info_stamping
+
+def _get_library_versions(links: list[LinkArgs] | None) -> str:
+    if not links:
+        return ""
+
+    metadatas = []
+    for args in links:
+        if args.tset != None:
+            for info in args.tset.infos.traverse():
+                metadatas.extend(get_link_info(info).metadata)
+        elif args.infos != None:
+            for info in args.infos:
+                metadatas.extend(info.metadata)
+
+    versions = [metadata.version for metadata in truncate_dep_metadata(dedupe_dep_metadata(metadatas))]
+    return ";".join(versions)
+
+def stamp_build_info(
+    ctx: AnalysisContext,
+    obj: Artifact,
+    stamped_output: Artifact | None = None,
+    has_content_based_path: bool = False,
+    links: list[LinkArgs] | None = None,
+    build_info_json: Artifact | None = None,
+) -> Artifact:
+    """
+    If necessary, add fb_build_info section to binary via late-stamping
+    """
+    if cxx_stamp_build_info(ctx):
+        if build_info_json == None:
+            build_info = dict(ctx.attrs._build_info)
+            library_versions = _get_library_versions(links)
+            if library_versions:
+                build_info["library_versions"] = library_versions
+            build_info_json = ctx.actions.write_json(obj.short_path + "-build-info.json", build_info, has_content_based_path = has_content_based_path)
+        stem, ext = paths.split_extension(obj.short_path)
+        if not stamped_output:
+            name = stem.removesuffix(PRE_STAMPED_SUFFIX) if stem.endswith(PRE_STAMPED_SUFFIX) else stem + "-stamped"
+            stamped_output = ctx.actions.declare_output(name + ext, has_content_based_path = has_content_based_path)
+
+        toolchain = get_cxx_toolchain_info(ctx)
+
+        # elf_stamp adds the section itself when the link did not reserve
+        # one, so stamping has no link-side prerequisites. Exec-platform
+        # toolchains omit elf_stamp (to break the toolchain -> elf_stamp ->
+        # toolchain cycle); objcopy adds the section there instead.
+        elf_stamp = toolchain.binary_utilities_info.elf_stamp
+        if not elf_stamp:
+            return add_elf_sections(
+                ctx,
+                obj,
+                {"fb_build_info": build_info_json},
+                stamped_output,
+                category = "stamp_build_info",
+            )
+
+        cmd = cmd_args([
+            elf_stamp,
+            "--section",
+            cmd_args(build_info_json, format = "fb_build_info={}"),
+            obj,
+            stamped_output.as_output(),
+        ])
+
+        # This can be run remotely, but it's often cheaper to do this locally for large
+        # binaries, especially on CI using limited hybrid
+        prefer_local = not getattr(ctx.attrs, "optimize_for_action_throughput", False)
+
+        ctx.actions.run(
+            cmd,
+            identifier = obj.short_path,
+            category = "stamp_build_info",
+            prefer_local = prefer_local,
+            prefer_remote = not prefer_local,
+            allow_cache_upload = toolchain.cxx_compiler_info.allow_cache_upload,
+        )
+        return stamped_output
+    return obj
diff --git a/buck2/prelude/linking/strip.bzl b/buck2/prelude/linking/strip.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/strip.bzl
@@ -0,0 +1,142 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",
+    "LinkerType",
+)
+
+def _strip_debug_info(actions: AnalysisActions, cxx_toolchain: CxxToolchainInfo, out: str, obj: Artifact, has_content_based_path: bool) -> Artifact:
+    """
+    Strip debug information from an object.
+    """
+    strip = cxx_toolchain.binary_utilities_info.strip
+    output = actions.declare_output("__stripped__", out, has_content_based_path = has_content_based_path)
+    if cxx_toolchain.linker_info.type == LinkerType("gnu"):
+        cmd = cmd_args([strip, "--strip-debug", "--strip-unneeded", "-o", output.as_output(), obj])
+    else:
+        cmd = cmd_args([strip, "-S", "-o", output.as_output(), obj])
+    actions.run(cmd, category = "strip_debug", identifier = out)
+    return output
+
+_InterfaceInfo = provider(
+    fields = {
+        "artifact": provider_field(typing.Any, default = None),  # "artifact"
+    }
+)
+
+def _anon_strip_debug_info_impl(ctx):
+    output = _strip_debug_info(
+        actions = ctx.actions,
+        cxx_toolchain = ctx.attrs._cxx_toolchain[CxxToolchainInfo],
+        out = ctx.attrs.out,
+        obj = ctx.attrs.obj,
+        has_content_based_path = ctx.attrs.has_content_based_path,
+    )
+    return [DefaultInfo(), _InterfaceInfo(artifact = output)]
+
+# Anonymous wrapper for `extract_symbol_names`.
+_anon_strip_debug_info = anon_rule(
+    impl = _anon_strip_debug_info_impl,
+    attrs = {
+        "has_content_based_path": attrs.bool(),
+        "obj": attrs.source(),
+        "out": attrs.string(),
+        "_cxx_toolchain": attrs.dep(providers = [CxxToolchainInfo]),
+    },
+    artifact_promise_mappings = {
+        "strip_debug_info": lambda p: p[_InterfaceInfo].artifact,
+    },
+)
+
+def strip_debug_info(
+    actions: AnalysisActions,
+    out: str,
+    obj: Artifact,
+    cxx_toolchain_info: CxxToolchainInfo | None = None,
+    cxx_toolchain: Dependency | None = None,
+    anonymous: bool = False,
+    has_content_based_path: bool = False,
+) -> Artifact:
+    if anonymous:
+        strip_debug_info = actions.anon_target(
+            _anon_strip_debug_info,
+            dict(
+                _cxx_toolchain = cxx_toolchain,
+                out = out,
+                obj = obj,
+                has_content_based_path = has_content_based_path,
+            ),
+        ).artifact("strip_debug_info")
+
+        if has_content_based_path:
+            return actions.assert_has_content_based_path(strip_debug_info)
+
+        return actions.assert_short_path(strip_debug_info, short_path = out)
+    else:
+        return _strip_debug_info(
+            actions = actions,
+            cxx_toolchain = cxx_toolchain_info,
+            out = out,
+            obj = obj,
+            has_content_based_path = has_content_based_path,
+        )
+
+def strip_object(
+    ctx: AnalysisContext,
+    cxx_toolchain: CxxToolchainInfo,
+    unstripped: Artifact,
+    strip_flags: cmd_args,
+    category_suffix: [str, None] = None,
+    output_path: [str, None] = None,
+    allow_cache_upload: bool = False,
+) -> Artifact:
+    """
+    Strip unneeded information from binaries / shared libs.
+    """
+    strip = cxx_toolchain.binary_utilities_info.strip
+
+    output_path = output_path or unstripped.short_path
+    stripped_lib = ctx.actions.declare_output("stripped/{}".format(output_path), has_content_based_path = False)
+
+    # TODO(T109996375) support configuring the flags used for stripping
+    cmd = cmd_args(
+        strip,
+        strip_flags,
+        unstripped,
+        "-o",
+        stripped_lib.as_output(),
+    )
+
+    effective_category_suffix = category_suffix if category_suffix else "shared_lib"
+    category = "strip_{}".format(effective_category_suffix)
+
+    ctx.actions.run(cmd, category = category, identifier = output_path, allow_cache_upload = allow_cache_upload)
+
+    return stripped_lib
+
+def strip_debug_with_gnu_debuglink(ctx: AnalysisContext, name: str, obj: Artifact) -> tuple:
+    """
+    Split a binary into a separate debuginfo binary and a stripped binary with a .gnu_debuglink reference
+    """
+    objcopy = get_cxx_toolchain_info(ctx).binary_utilities_info.objcopy
+
+    # We flatten the directory structure because .gnu_debuglink doesn't understand directories and we
+    # need to avoid name conflicts between different inputs
+    debuginfo_name = name.replace("/", ".")
+    debuginfo_output = ctx.actions.declare_output("__debuginfo__", debuginfo_name + ".debuginfo", has_content_based_path = False)
+    cmd = cmd_args([objcopy, "--only-keep-debug", obj, debuginfo_output.as_output()])
+    ctx.actions.run(cmd, category = "extract_debuginfo", identifier = name, local_only = get_cxx_toolchain_info(ctx).linker_info.link_binaries_locally)
+
+    binary_output = ctx.actions.declare_output("__stripped_objects__", name, has_content_based_path = False)
+    cmd = cmd_args([objcopy, "--strip-debug", "--keep-file-symbols", "--add-gnu-debuglink", debuginfo_output, obj, binary_output.as_output()])
+    ctx.actions.run(cmd, category = "strip_debug", identifier = name, local_only = get_cxx_toolchain_info(ctx).linker_info.link_binaries_locally)
+
+    return binary_output, debuginfo_output
diff --git a/buck2/prelude/linking/types.bzl b/buck2/prelude/linking/types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/linking/types.bzl
@@ -0,0 +1,17 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Ways a library can request to be linked (e.g. usually specific via a rule
+# param like `preferred_linkage`). The actual link style used for a library is
+# usually determined by a combination of this and the link style being exported
+# via a provider.
+Linkage = enum(
+    "any",
+    "static",
+    "shared",
+)
diff --git a/buck2/prelude/local_only.bzl b/buck2/prelude/local_only.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/local_only.bzl
@@ -0,0 +1,57 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",  # @unused Used as type
+)
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference", "get_link_execution_preference")
+load("@prelude//python:toolchain.bzl", "PythonToolchainInfo")
+
+def link_cxx_binary_locally(ctx: AnalysisContext, cxx_toolchain: [CxxToolchainInfo, None] = None) -> bool:
+    # Core tools are linked on RE because they are
+    # a) small enough to do so and
+    # b) don't get build stamping so they do cache correctly.
+    if _is_core_tool(ctx):
+        return False
+
+    return _cxx_toolchain_sets_link_binaries_locally(ctx, cxx_toolchain)
+
+def get_resolved_cxx_binary_link_execution_preference(
+    ctx: AnalysisContext, links: list[Label], force_full_hybrid_if_capable: bool, cxx_toolchain: [CxxToolchainInfo, None] = None
+) -> LinkExecutionPreference:
+    if force_full_hybrid_if_capable:
+        return LinkExecutionPreference("full_hybrid")
+
+    # Core tools can be linked on RE because they are
+    # a) small enough to do so and
+    # b) don't get build stamping so they do cache correctly.
+    if _is_core_tool(ctx):
+        return LinkExecutionPreference("any")
+
+    # Check if the toolchain has a preference.
+    if _cxx_toolchain_sets_link_binaries_locally(ctx, cxx_toolchain):
+        return LinkExecutionPreference("local")
+
+    # Else use the preference on the target.
+    return get_link_execution_preference(ctx, links)
+
+def package_python_locally(ctx: AnalysisContext, python_toolchain: PythonToolchainInfo) -> bool:
+    if _is_core_tool(ctx) or getattr(ctx.attrs, "_package_remotely", False):
+        return False
+
+    return python_toolchain.build_standalone_binaries_locally
+
+def _is_core_tool(ctx: AnalysisContext) -> bool:
+    return "is_core_tool" in getattr(ctx.attrs, "labels", [])
+
+def _cxx_toolchain_sets_link_binaries_locally(ctx: AnalysisContext, cxx_toolchain: [CxxToolchainInfo, None]) -> bool:
+    if not cxx_toolchain:
+        cxx_toolchain = get_cxx_toolchain_info(ctx)
+    return cxx_toolchain.linker_info.link_binaries_locally
diff --git a/buck2/prelude/lua/cxx_lua_extension.bzl b/buck2/prelude/lua/cxx_lua_extension.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/lua/cxx_lua_extension.bzl
@@ -0,0 +1,10 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def cxx_lua_extension_impl(_ctx: AnalysisContext) -> list[Provider]:
+    return [DefaultInfo()]
diff --git a/buck2/prelude/lua/lua_binary.bzl b/buck2/prelude/lua/lua_binary.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/lua/lua_binary.bzl
@@ -0,0 +1,10 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def lua_binary_impl(_ctx: AnalysisContext) -> list[Provider]:
+    return [DefaultInfo()]
diff --git a/buck2/prelude/lua/lua_library.bzl b/buck2/prelude/lua/lua_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/lua/lua_library.bzl
@@ -0,0 +1,10 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def lua_library_impl(_ctx: AnalysisContext) -> list[Provider]:
+    return [DefaultInfo()]
diff --git a/buck2/prelude/matlab/matlab.bzl b/buck2/prelude/matlab/matlab.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/matlab/matlab.bzl
@@ -0,0 +1,21 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":matlab_program.bzl", "matlab_program_impl")
+load(":matlab_toolchain.bzl", "matlab_toolchain")
+
+implemented_rules = {
+    "matlab_program": matlab_program_impl,
+}
+
+extra_attributes = {
+    "matlab_program": {
+        "main": attrs.source(),
+        "_matlab_toolchain": matlab_toolchain(),
+    },
+}
diff --git a/buck2/prelude/matlab/matlab_info.bzl b/buck2/prelude/matlab/matlab_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/matlab/matlab_info.bzl
@@ -0,0 +1,13 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+MatlabToolchainInfo = provider(
+    fields = {
+        "matlab_exe": RunInfo,
+    }
+)
diff --git a/buck2/prelude/matlab/matlab_program.bzl b/buck2/prelude/matlab/matlab_program.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/matlab/matlab_program.bzl
@@ -0,0 +1,24 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":matlab_info.bzl", "MatlabToolchainInfo")
+
+def matlab_program_impl(ctx: AnalysisContext) -> list[Provider]:
+    toolchain = ctx.attrs._matlab_toolchain[MatlabToolchainInfo]
+
+    cmd = cmd_args(toolchain.matlab_exe)
+    cmd.add(
+        "-batch",
+        cmd_args(
+            ctx.attrs.main.basename.removesuffix(".m"),
+            quote = "shell",
+        ),
+    )
+    cmd.add("-sd", cmd_args(ctx.attrs.main, parent = 1))
+
+    return [DefaultInfo(default_output = None, other_outputs = [cmd]), RunInfo(cmd)]
diff --git a/buck2/prelude/matlab/matlab_toolchain.bzl b/buck2/prelude/matlab/matlab_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/matlab/matlab_toolchain.bzl
@@ -0,0 +1,17 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":matlab_info.bzl", "MatlabToolchainInfo")
+
+def matlab_toolchain():
+    return attrs.default_only(
+        attrs.toolchain_dep(
+            default = "toolchains//:matlab",
+            providers = [MatlabToolchainInfo],
+        ),
+    )
diff --git a/buck2/prelude/native.bzl b/buck2/prelude/native.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/native.bzl
@@ -0,0 +1,487 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# `native` is fine to use in the prelude for v2
+
+# This is buck2's shim import. Any public symbols here will be available within
+# **all** interpreted files.
+
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//:rules.bzl", __rules__ = "rules")
+load("@prelude//android:cpu_filters.bzl", "ALL_CPU_FILTERS", "CPU_FILTER_FOR_DEFAULT_PLATFORM")
+load(
+    "@prelude//apple:apple_macro_layer.bzl",
+    "apple_binary_macro_impl",
+    "apple_bundle_macro_impl",
+    "apple_library_for_distribution_macro_impl",
+    "apple_library_macro_impl",
+    "apple_metal_library_macro_impl",
+    "apple_package_macro_impl",
+    "apple_test_macro_impl",
+    "apple_universal_executable_macro_impl",
+    "apple_xcuitest_macro_impl",
+    "prebuilt_apple_framework_macro_impl",
+)
+load("@prelude//apple:prebuilt_apple_xcframework_macro_impl.bzl", "prebuilt_apple_xcframework_macro_impl")
+load("@prelude//apple/swift:swift_toolchain_macro_layer.bzl", "swift_toolchain_macro_impl")
+load("@prelude//cxx:cxx_toolchain.bzl", "cxx_toolchain_inheriting_target_platform")
+load("@prelude//cxx:cxx_toolchain_macro_layer.bzl", "cxx_toolchain_macro_impl")
+load("@prelude//cxx:cxx_toolchain_types.bzl", _cxx = "cxx")
+load("@prelude//erlang:erlang.bzl", _erlang_application = "erlang_application", _erlang_tests = "erlang_tests")
+load("@prelude//python:toolchain.bzl", _python = "python")
+load("@prelude//rust:link_info.bzl", "RustLinkInfo")
+load("@prelude//rust:rust_common.bzl", "rust_common_macro_wrapper")
+load("@prelude//rust:rust_library.bzl", "rust_library_macro_wrapper")
+load("@prelude//rust:sources.bzl", "RustSources")
+load("@prelude//rust:with_workspace.bzl", "with_rust_workspace")
+load("@prelude//user:all.bzl", _user_rules = "rules")
+load(
+    "@prelude//utils:buckconfig.bzl",
+    _read_config = "read_config_with_logging",
+    _read_root_config = "read_root_config_with_logging",
+    log_buckconfigs = "LOG_BUCKCONFIGS",
+)
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:selects.bzl", "selects")
+
+def __struct_to_dict(s):
+    vals = {}
+    for name in dir(s):
+        vals[name] = getattr(s, name)
+    return vals
+
+def _tp2_constraint(project, version):
+    """
+    Return the target configuration constraint to use for the given project
+    version
+    """
+
+    return "ovr_config//third-party/{}/constraints:{}".format(project, version)
+
+def _tp2_constraint_multi(versions):
+    """
+    Return the `select` key rule name which corresponds to the given tp2 project
+    versions.
+    """
+
+    expect(len(versions) >= 1, str(versions))
+
+    # If there's only a single project/version pair, then just return the its
+    # pre-defined constraint value rule name.
+    if len(versions) == 1:
+        (project, version) = versions.items()[0]
+        return _tp2_constraint(project, version)
+
+    # Otherwise, generate a `config_setting` to combine the constraint value
+    # rules for all the project/version pairs.
+    name = "-".join(["_tp2_constraints_"] + ["{}-{}".format(p, v) for p, v in sorted(versions.items())])
+    if not rule_exists(name):
+        __rules__["config_setting"](
+            name = name,
+            constraint_values = [_tp2_constraint(p, v) for p, v in versions.items()],
+        )
+    return ":" + name
+
+def _extract_versions(constraints):
+    """
+    Convert v1-style version constraints to a v2-compatible config settings.
+
+    The constraints are normally of the form:
+    `{"python": "3.8"}`.
+    """
+
+    versions = {}
+
+    # Since the constraints will be duplicated for each fbcode "platform", do
+    # some initial work to de-duplicate them here, by extracting just the
+    # project and version and verify we get just a single reduced result.
+    for project, version in constraints.items():
+        expect(project not in versions or version == versions[project])
+        versions[project] = version
+
+    return versions
+
+def _versioned_param_to_select(items, default = None):
+    """
+    Convert a v1-style `versioned_*` param to a `select` map.
+
+    Parameters:
+    - items: A list of 2-tuples of a list of version constraints to match and
+          the values to use in case of match.
+    """
+
+    if items == None:
+        return None
+
+    # TODO(agallagher): Remove once we move to a `uquery` based TD.
+    if read_root_config("fbcode", "cquery_td") == "true":
+        return None
+
+    # Special case a form of "empty" constraints that `buckify_tp2` may
+    # generate in tp2 TARGETS.
+    if len(items) == 1 and not items[0][0]:
+        return items[0][1]
+
+    select_map = {}
+
+    # If a default is provided add that.
+    if default != None:
+        select_map["DEFAULT"] = default
+
+    # Convert v1 tp2-style versioned_* params to their analogous v2 select
+    # constraint maps.
+    for constraints, item in items:
+        versions = _extract_versions(constraints)
+        select_map[_tp2_constraint_multi(versions)] = item
+
+    if not select_map:
+        return None
+
+    return select(select_map)
+
+def _concat(*items):
+    """
+    Concatenate non-`None` items and return result.
+    """
+    res = None
+
+    for item in items:
+        if item == None:
+            continue
+        if res == None:
+            res = item
+        elif type(res) == type({}) and type(item) == type({}):
+            new_res = {}
+            new_res.update(res)
+            new_res.update(item)
+            res = new_res
+        else:
+            res += item  # buildifier: disable=dict-concatenation
+
+    return res
+
+def _at_most_one(*items):
+    """
+    Return a non-`None` value if it exists.  Fail if more that one non-`None`
+    exists.
+    """
+
+    res = None
+
+    for item in items:
+        if item == None:
+            continue
+        expect(res == None)
+        res = item
+
+    return res
+
+def _get_valid_cpu_filters(cpu_filters: [list[str], None]) -> list[str]:
+    if read_root_config("buck2", "android_force_single_default_cpu") in ("True", "true"):
+        return [CPU_FILTER_FOR_DEFAULT_PLATFORM]
+
+    cpu_abis_config_string = read_root_config("ndk", "cpu_abis")
+    if cpu_abis_config_string:
+        cpu_abis = [v.strip() for v in cpu_abis_config_string.split(",")]
+        for cpu_abi in cpu_abis:
+            if cpu_abi not in ALL_CPU_FILTERS:
+                fail("Entries in ndk.cpu_abis must be one of {}, but {} is not".format(ALL_CPU_FILTERS, cpu_abi))
+    else:
+        cpu_abis = ALL_CPU_FILTERS
+
+    cpu_filters = cpu_filters or ALL_CPU_FILTERS
+
+    return [cpu_filter for cpu_filter in cpu_filters if cpu_filter in cpu_abis]
+
+def _android_aar_macro_stub(cpu_filters = None, **kwargs):
+    __rules__["android_aar"](cpu_filters = _get_valid_cpu_filters(cpu_filters), **kwargs)
+
+def _convert_kotlin_compiler_plugins(kotlin_compiler_plugins):
+    if type(kotlin_compiler_plugins) == type(select({})):
+        return native.select_map(kotlin_compiler_plugins, _convert_kotlin_compiler_plugins)
+    if type(kotlin_compiler_plugins) == type({}):
+        return [(key, value) for key, value in kotlin_compiler_plugins.items()]
+    else:
+        return kotlin_compiler_plugins
+
+def _kotlin_library_macro_stub(kotlin_compiler_plugins = {}, **kwargs):
+    __rules__["kotlin_library"](kotlin_compiler_plugins = _convert_kotlin_compiler_plugins(kotlin_compiler_plugins), **kwargs)
+
+def _kotlin_test_macro_stub(kotlin_compiler_plugins = {}, **kwargs):
+    __rules__["kotlin_test"](kotlin_compiler_plugins = _convert_kotlin_compiler_plugins(kotlin_compiler_plugins), **kwargs)
+
+def _android_library_macro_stub(kotlin_compiler_plugins = {}, **kwargs):
+    __rules__["android_library"](kotlin_compiler_plugins = _convert_kotlin_compiler_plugins(kotlin_compiler_plugins), **kwargs)
+
+def _robolectric_test_macro_stub(kotlin_compiler_plugins = {}, **kwargs):
+    __rules__["robolectric_test"](kotlin_compiler_plugins = _convert_kotlin_compiler_plugins(kotlin_compiler_plugins), **kwargs)
+
+def _android_binary_macro_stub(allow_r_dot_java_in_secondary_dex = False, cpu_filters = None, primary_dex_patterns = [], **kwargs):
+    if not allow_r_dot_java_in_secondary_dex:
+        primary_dex_patterns = primary_dex_patterns + [
+            "/R^",
+            "/R$",
+            # Pin this to the primary for apps with no primary dex classes.
+            "^com/facebook/buck_generated/AppWithoutResourcesStub^",
+        ]
+
+    # TODO: T218493860 Accept `select` for `cpu_filters` and apply the same logic as for non-select cases
+    __rules__["android_binary"](
+        allow_r_dot_java_in_secondary_dex = allow_r_dot_java_in_secondary_dex,
+        cpu_filters = cpu_filters if isinstance(cpu_filters, Select) else _get_valid_cpu_filters(cpu_filters),
+        primary_dex_patterns = primary_dex_patterns,
+        **kwargs,
+    )
+
+def _android_bundle_macro_stub(cpu_filters = None, **kwargs):
+    __rules__["android_bundle"](
+        # TODO: T218493860 Accept `select` for `cpu_filters` and apply the same logic as for non-select cases
+        cpu_filters = cpu_filters if isinstance(cpu_filters, Select) else _get_valid_cpu_filters(cpu_filters),
+        **kwargs,
+    )
+
+def _android_instrumentation_apk_macro_stub(cpu_filters = None, primary_dex_patterns = [], **kwargs):
+    primary_dex_patterns = primary_dex_patterns + [
+        "/R^",
+        "/R$",
+        # Pin this to the primary for apps with no primary dex classes.
+        "^com/facebook/buck_generated/AppWithoutResourcesStub^",
+    ]
+    __rules__["android_instrumentation_apk"](cpu_filters = _get_valid_cpu_filters(cpu_filters), primary_dex_patterns = primary_dex_patterns, **kwargs)
+
+# export_file src defaults to name, despite being string vs source, so adjust it in the macros
+def _export_file_macro_stub(name, src = None, **kwargs):
+    __rules__["export_file"](name = name, src = name if src == None else src, **kwargs)
+
+def _prebuilt_cxx_library_macro_stub(
+    exported_preprocessor_flags = None,
+    versioned_exported_preprocessor_flags = None,
+    exported_lang_preprocessor_flags = None,
+    versioned_exported_lang_preprocessor_flags = None,
+    static_lib = None,
+    versioned_static_lib = None,
+    static_pic_lib = None,
+    versioned_static_pic_lib = None,
+    shared_lib = None,
+    versioned_shared_lib = None,
+    header_dirs = None,
+    versioned_header_dirs = None,
+    **kwargs,
+):
+    __rules__["prebuilt_cxx_library"](
+        exported_preprocessor_flags = _concat(
+            exported_preprocessor_flags,
+            _versioned_param_to_select(versioned_exported_preprocessor_flags),
+        ),
+        exported_lang_preprocessor_flags = _concat(
+            exported_lang_preprocessor_flags,
+            _versioned_param_to_select(versioned_exported_lang_preprocessor_flags),
+        ),
+        static_lib = selects.apply_n(
+            [static_lib, selects.apply(versioned_static_lib, _versioned_param_to_select)],
+            _at_most_one,
+        ),
+        static_pic_lib = selects.apply_n(
+            [static_pic_lib, selects.apply(versioned_static_pic_lib, _versioned_param_to_select)],
+            _at_most_one,
+        ),
+        shared_lib = selects.apply_n(
+            [shared_lib, selects.apply(versioned_shared_lib, _versioned_param_to_select)],
+            _at_most_one,
+        ),
+        header_dirs = selects.apply_n(
+            [header_dirs, selects.apply(versioned_header_dirs, _versioned_param_to_select)],
+            _at_most_one,
+        ),
+        **kwargs,
+    )
+
+def _python_library_macro_stub(srcs = None, versioned_srcs = None, resources = None, versioned_resources = None, **kwargs):
+    __rules__["python_library"](
+        srcs = _concat(srcs, _versioned_param_to_select(versioned_srcs, default = None)),
+        resources = _concat(resources, _versioned_param_to_select(versioned_resources, default = None)),
+        **kwargs,
+    )
+
+def _versioned_alias_macro_stub(versions = {}, **kwargs):
+    project = paths.basename(package_name())
+    __rules__["alias"](actual = select({_tp2_constraint(project, version): actual for version, actual in versions.items()}), **kwargs)
+
+def _configured_alias_macro_stub(
+    name,
+    actual,
+    platform,
+    # Whether to fallback to a unconfigured `alias` if `platform` is `None`.
+    fallback_to_unconfigured_alias = False,
+    **kwargs,
+):
+    pred = lambda platform: platform != None or not fallback_to_unconfigured_alias
+    __rules__["configured_alias"](
+        name = name,
+        # `actual` needs to be a pair of target + platform, as that's the format
+        # expected by the `configured_dep()` field
+        # Use a select map to make this thing `None` if `platform` is `None`.
+        configured_actual = selects.apply(
+            platform,
+            lambda platform: (actual, platform) if pred(platform) else None,
+        ),
+        # Make sure that exactly one of `configured_actual` or `fallback_actual` is set
+        fallback_actual = selects.apply(
+            platform,
+            lambda platform: None if pred(platform) else actual,
+        ),
+        # Unused.
+        actual = actual,
+        platform = platform,
+        **kwargs,
+    )
+
+def _apple_bundle_macro_stub(**kwargs):
+    apple_bundle_macro_impl(apple_bundle_rule = __rules__["apple_bundle"], apple_resource_bundle_rule = __rules__["apple_resource_bundle"], **kwargs)
+
+def _apple_watchos_bundle_macro_stub(**kwargs):
+    apple_bundle_macro_impl(apple_bundle_rule = __rules__["apple_watchos_bundle"], apple_resource_bundle_rule = __rules__["apple_resource_bundle"], **kwargs)
+
+def _apple_macos_bundle_macro_stub(**kwargs):
+    apple_bundle_macro_impl(apple_bundle_rule = __rules__["apple_macos_bundle"], apple_resource_bundle_rule = __rules__["apple_resource_bundle"], **kwargs)
+
+def _apple_test_macro_stub(**kwargs):
+    apple_test_macro_impl(apple_test_rule = __rules__["apple_test"], apple_resource_bundle_rule = __rules__["apple_resource_bundle"], **kwargs)
+
+def _apple_xcuitest_macro_stub(**kwargs):
+    apple_xcuitest_macro_impl(apple_xcuitest_rule = __rules__["apple_xcuitest"], **kwargs)
+
+def _apple_binary_macro_stub(**kwargs):
+    apple_binary_macro_impl(apple_binary_rule = __rules__["apple_binary"], apple_universal_executable = __rules__["apple_universal_executable"], **kwargs)
+
+def _apple_library_macro_stub(**kwargs):
+    apple_library_macro_impl(apple_library_rule = __rules__["apple_library"], **kwargs)
+
+def _apple_metal_library_macro_stub(**kwargs):
+    apple_metal_library_macro_impl(apple_metal_library_rule = __rules__["apple_metal_library"], **kwargs)
+
+def _apple_library_for_distribution_macro_stub(**kwargs):
+    apple_library_for_distribution_macro_impl(apple_library_for_distribution_rule = __rules__["apple_library_for_distribution"], **kwargs)
+
+def _apple_package_macro_stub(**kwargs):
+    apple_package_macro_impl(apple_package_rule = __rules__["apple_package"], apple_ipa_package_rule = __rules__["apple_ipa_package"], **kwargs)
+
+def _apple_universal_executable_macro_stub(**kwargs):
+    apple_universal_executable_macro_impl(apple_universal_executable_rule = __rules__["apple_universal_executable"], **kwargs)
+
+def _swift_toolchain_macro_stub(**kwargs):
+    rule = __rules__["swift_toolchain"]
+
+    swift_toolchain_macro_impl(swift_toolchain_rule = rule, **kwargs)
+
+def _cxx_toolchain_macro_stub(**kwargs):
+    if is_full_meta_repo():
+        cache_links = kwargs.get("cache_links")
+        kwargs["cache_links"] = select({
+            "DEFAULT": cache_links,
+            "ovr_config//platform/execution/constraints:execution-platform-transitioned": True,
+        })
+    cxx_toolchain_macro_impl(cxx_toolchain_rule = cxx_toolchain_inheriting_target_platform, **kwargs)
+
+def _cxx_toolchain_override_macro_stub(**kwargs):
+    cxx_toolchain_macro_impl(cxx_toolchain_rule = _user_rules["cxx_toolchain_override"], **kwargs)
+
+def _erlang_application_macro_stub(**kwargs):
+    _erlang_application(erlang_app_rule = __rules__["erlang_app"], erlang_app_includes_rule = __rules__["erlang_app_includes"], **kwargs)
+
+def _erlang_tests_macro_stub(**kwargs):
+    _erlang_tests(erlang_app_rule = __rules__["erlang_app"], erlang_test_rule = __rules__["erlang_test"], **kwargs)
+
+def _rust_library_macro_stub(**kwargs):
+    rust_library = rust_common_macro_wrapper(__rules__["rust_library"])
+    rust_library = rust_library_macro_wrapper(rust_library)
+    rust_library(**kwargs)
+
+def _rust_binary_macro_stub(**kwargs):
+    rust_binary = rust_common_macro_wrapper(__rules__["rust_binary"])
+    rust_binary(**kwargs)
+
+def _rust_test_macro_stub(**kwargs):
+    rust_test = rust_common_macro_wrapper(__rules__["rust_test"])
+    rust_test(**kwargs)
+
+def _prebuilt_apple_framework_macro_stub(**kwargs):
+    prebuilt_apple_framework_macro_impl(prebuilt_apple_framework_rule = __rules__["prebuilt_apple_framework"], **kwargs)
+
+def _prebuilt_apple_xcframework_macro_stub(**kwargs):
+    prebuilt_apple_xcframework_macro_impl(
+        filegroup_rule = __rules__["filegroup"], genrule = __rules__["genrule"], prebuilt_apple_framework_rule = __rules__["prebuilt_apple_framework"], **kwargs
+    )
+
+# TODO(cjhopman): These macro wrappers should be handled in prelude/rules.bzl+rule_impl.bzl.
+# Probably good if they were defined to take in the base rule that
+# they are wrapping and return the wrapped one.
+__extra_rules__ = {
+    "android_aar": _android_aar_macro_stub,
+    "android_binary": _android_binary_macro_stub,
+    "android_bundle": _android_bundle_macro_stub,
+    "android_instrumentation_apk": _android_instrumentation_apk_macro_stub,
+    "android_library": _android_library_macro_stub,
+    "apple_binary": _apple_binary_macro_stub,
+    "apple_bundle": _apple_bundle_macro_stub,
+    "apple_library": _apple_library_macro_stub,
+    "apple_library_for_distribution": _apple_library_for_distribution_macro_stub,
+    "apple_macos_bundle": _apple_macos_bundle_macro_stub,
+    "apple_metal_library": _apple_metal_library_macro_stub,
+    "apple_package": _apple_package_macro_stub,
+    "apple_test": _apple_test_macro_stub,
+    "apple_universal_executable": _apple_universal_executable_macro_stub,
+    "apple_watchos_bundle": _apple_watchos_bundle_macro_stub,
+    "apple_xcuitest": _apple_xcuitest_macro_stub,
+    "configured_alias": _configured_alias_macro_stub,
+    "cxx_toolchain": _cxx_toolchain_macro_stub,
+    "cxx_toolchain_override": _cxx_toolchain_override_macro_stub,
+    "erlang_application": _erlang_application_macro_stub,
+    "erlang_tests": _erlang_tests_macro_stub,
+    "export_file": _export_file_macro_stub,
+    "kotlin_library": _kotlin_library_macro_stub,
+    "kotlin_test": _kotlin_test_macro_stub,
+    "prebuilt_apple_framework": _prebuilt_apple_framework_macro_stub,
+    "prebuilt_apple_xcframework": _prebuilt_apple_xcframework_macro_stub,
+    "prebuilt_cxx_library": _prebuilt_cxx_library_macro_stub,
+    "python_library": _python_library_macro_stub,
+    "robolectric_test": _robolectric_test_macro_stub,
+    "rust_binary": _rust_binary_macro_stub,
+    "rust_library": _rust_library_macro_stub,
+    "rust_test": _rust_test_macro_stub,
+    "rust_with_workspace": with_rust_workspace,
+    "swift_toolchain": _swift_toolchain_macro_stub,
+    "versioned_alias": _versioned_alias_macro_stub,
+}
+
+__overridden_builtins__ = (
+    {
+        "read_config": _read_config,
+        "read_root_config": _read_root_config,
+    }
+    if log_buckconfigs
+    else {}
+)
+
+__shimmed_native__ = __struct_to_dict(__buck2_builtins__)
+__shimmed_native__.update(__overridden_builtins__)
+__shimmed_native__.update(__rules__)
+__shimmed_native__.update(_user_rules)
+
+# Should come after the rules which are macro overridden
+__shimmed_native__.update(__extra_rules__)
+__shimmed_native__.update({"cxx": _cxx, "python": _python})
+__shimmed_native__.update({
+    "__internal_autodeps_hacks__": struct(
+        rust_link_info = RustLinkInfo,
+        rust_sources = RustSources,
+    ),
+})
+
+native = struct(**__shimmed_native__)
diff --git a/buck2/prelude/none.bzl b/buck2/prelude/none.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/none.bzl
@@ -0,0 +1,39 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+)
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    label = ctx.label.raw_target()
+    setting = ConstraintSettingInfo(label = label)
+    value = ConstraintValueInfo(setting = setting, label = label)
+
+    return [
+        DefaultInfo(),
+        SharedLibraryInfo(),
+        # A never-satisfied configuration. This is useful as a way to express
+        # negation in a select for a target_compatible_with attribute.
+        #     target_compatible_with = select({
+        #         "DEFAULT": [],
+        #         "config//build_mode/constraints:tsan": ["prelude//:none"],
+        #     })
+        ConfigurationInfo(
+            constraints = {label: value},
+            values = {},
+        ),
+    ]
+
+none_rule = rule(
+    attrs = {},
+    impl = _impl,
+    doc = "A rule that produces nothing. Used for no-op dep in a select.",
+    is_configuration_rule = True,
+)
diff --git a/buck2/prelude/ocaml/attrs.bzl b/buck2/prelude/ocaml/attrs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ocaml/attrs.bzl
@@ -0,0 +1,94 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Attributes for OCaml build rules.
+
+# --
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxPlatformInfo", "CxxToolchainInfo")
+load("@prelude//ocaml:ocaml_toolchain_types.bzl", "OCamlPlatformInfo", "OCamlToolchainInfo")
+
+def _toolchain(lang: str, providers: list[typing.Any]) -> Attr:
+    return attrs.default_only(attrs.toolchain_dep(default = "toolchains//:" + lang, providers = providers))
+
+def _cxx_toolchain() -> Attr:
+    return _toolchain("cxx", [CxxToolchainInfo, CxxPlatformInfo])
+
+def _ocaml_toolchain() -> Attr:
+    return _toolchain("ocaml", [OCamlToolchainInfo, OCamlPlatformInfo])
+
+# --
+
+def prebuilt_ocaml_library_attributes() -> dict:
+    return {
+        # These fields in 'attributes.bzl' are wrong.
+        #
+        # There they are defined in terms of `attrs.string()`. This
+        # block overrides/corrects them here so as to be in terms of
+        # `attrs.source()`.
+        "bytecode_c_libs": attrs.list(attrs.source(), default = []),
+        "bytecode_lib": attrs.option(attrs.source(), default = None),
+        "c_libs": attrs.list(attrs.source(), default = []),
+        "include_dir": attrs.option(attrs.source(allow_directory = True), default = None),
+        "native_c_libs": attrs.list(attrs.source(), default = []),
+        "native_lib": attrs.option(attrs.source(), default = None),
+    }
+
+def ocaml_binary_attributes() -> dict:
+    return {
+        "_cxx_toolchain": _cxx_toolchain(),
+        "_ocaml_toolchain": _ocaml_toolchain(),
+    }
+
+def ocaml_library_attributes() -> dict:
+    return {
+        "_cxx_toolchain": _cxx_toolchain(),
+        "_ocaml_toolchain": _ocaml_toolchain(),
+    }
+
+def ocaml_object_attributes() -> dict:
+    return {
+        "bytecode_only": attrs.option(attrs.bool(), default = None),
+        "compiler_flags": attrs.list(attrs.arg(), default = []),
+        "contacts": attrs.list(attrs.string(), default = []),
+        "deps": attrs.list(attrs.dep(), default = []),
+        "labels": attrs.list(attrs.string(), default = []),
+        "licenses": attrs.list(attrs.source(), default = []),
+        "linker_flags": attrs.list(attrs.string(), default = []),
+        "ocamldep_flags": attrs.list(attrs.arg(), default = []),
+        "platform": attrs.option(attrs.string(), default = None),
+        "srcs": attrs.option(attrs.named_set(attrs.source(), sorted = False), default = None),
+        "warnings_flags": attrs.option(attrs.string(), default = None),
+        "_cxx_toolchain": _cxx_toolchain(),
+        "_ocaml_toolchain": _ocaml_toolchain(),
+    }
+
+def ocaml_shared_attributes() -> dict:
+    return {
+        "bytecode_only": attrs.option(attrs.bool(), default = None),
+        "compiler_flags": attrs.list(attrs.arg(), default = []),
+        "contacts": attrs.list(attrs.string(), default = []),
+        "deps": attrs.list(attrs.dep(), default = []),
+        "labels": attrs.list(attrs.string(), default = []),
+        "licenses": attrs.list(attrs.source(), default = []),
+        "linker_flags": attrs.list(attrs.string(), default = []),
+        "ocamldep_flags": attrs.list(attrs.arg(), default = []),
+        "platform": attrs.option(attrs.string(), default = None),
+        "srcs": attrs.option(attrs.named_set(attrs.source(), sorted = False), default = None),
+        "warnings_flags": attrs.option(attrs.string(), default = None),
+        "_cxx_toolchain": _cxx_toolchain(),
+        "_ocaml_toolchain": _ocaml_toolchain(),
+    }
+
+ocaml_extra_attributes = {
+    "ocaml_binary": ocaml_binary_attributes(),
+    "ocaml_library": ocaml_library_attributes(),
+    "ocaml_object": ocaml_object_attributes(),
+    "ocaml_shared": ocaml_shared_attributes(),
+    "prebuilt_ocaml_library": prebuilt_ocaml_library_attributes(),
+}
diff --git a/buck2/prelude/ocaml/makefile.bzl b/buck2/prelude/ocaml/makefile.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ocaml/makefile.bzl
@@ -0,0 +1,161 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Parse and resolve Makefile's produce by ocamldeps.
+load("@prelude//:paths.bzl", "paths")
+
+# [Note: Dynamic dependency calculations]
+# ---------------------------------------
+# We are given the contents of a Makefile produced by ocamldep in -native mode e.g.
+# ```
+#      quux.cmi:
+#      quux.cmx:
+#        quux.cmi
+#      corge.cmx:
+#        quux.cmx
+# ```
+# and the sources we care about.
+#
+#'parse_makefile' produces a mapping of which sources depend on which. In fact,
+# it computes a pair of mappings:
+#
+# Result (1):  Replace '.cmi' with '.mli' and '.cmx' with '.ml' e.g.
+# ```
+#      quux.mli:
+#      quux.ml:
+#        quux.mli
+#      corge.ml:
+#        quux.ml
+# ```
+# If -opqaue is not in effect then this reflects the dependency requirements
+# that enable cross module inlining (see the description of the -opaque flag [in
+# the ocamlopt manual](https://v2.ocaml.org/manual/native.html)).
+
+# Result(2):
+#
+#   If '-opqaue' is not in effect, then this is a copy of result(1). If though
+#   '-opaque' is in effect, replace 'foo.cmx' with 'foo.cmi' in the RHS of rules
+#   as long as there is a rule with LHS 'foo.cmi' in the ocamldep input. Then,
+#   replace '.cmi' with .mli' and '.cmx' with '.ml' as before e.g.
+# ```
+#      quux.mli:
+#      quux.ml:
+#        quux.mli
+#      corge.ml:
+#        quux.mli
+# ```
+# This mapping reflects the dependency requirements that don't admit cross
+# module inlining (cutting down significantly on recompilations when only a
+# module implementation and not its interface is changed).
+def parse_makefile(makefile: str, srcs: list[Artifact], opaque_enabled: bool) -> (dict[Artifact, list[Artifact]], dict[Artifact, list[Artifact]]):
+    # ocamldep is always invoked with '-native' so compiled modules are always
+    # reported as '.cmx' files
+    contents = _parse(makefile)
+
+    # Collect all the files we reference.
+    files = {}
+    for aa, bb in contents:
+        for x in aa + bb:
+            files[x] = None
+
+    # Produce a mapping of the files on the LHS of rules to their source
+    # equivalents e.g. {'corge.cmx': 'corge.ml', 'quux.cmx': 'quux.ml',
+    # 'quux.mli': 'quux.mli'}.
+    resolved = _resolve(files.keys(), srcs)
+
+    # This nested loop is technically O(n^2), but since `a` is at most 2 in OCaml
+    # it's not an issue
+    result = {}
+    for aa, bb in contents:
+        for a in aa:
+            if a in resolved:
+                result[resolved[a]] = [resolved[b] for b in bb if b in resolved]
+
+    # This is not an optimization, we rely on this early return (see [Note:
+    # Dynamic dependencies] earlier in this file).
+    if not opaque_enabled:
+        return (result, result)
+
+    # Replace '.cmx' (or '.cmo') dependencies with '.cmi' on the RHS of
+    # rules everywhere we can.
+    contents = [_replace_rhs_cmx_with_cmi(contents, c) for c in contents]
+
+    # Compute a new result based on having replaced '.cmx' ('.cmo') with '.cmi'
+    # on the RHS of rules where we can.
+    result2 = {}
+    for aa, bb in contents:
+        for a in aa:
+            if a in resolved:
+                result2[resolved[a]] = [resolved[b] for b in bb if b in resolved]
+
+    return (result, result2)
+
+def _resolve(entries: list[str], srcs: list[Artifact]) -> dict[str, Artifact]:
+    # O(n^2), alas - switch to a prefix map if that turns out to be too slow.
+    result = {}
+    for x in entries:
+        prefix, ext = paths.split_extension(x)
+        if ext == ".cmx":
+            y = prefix + ".ml"
+        elif ext == ".cmi":
+            y = prefix + ".mli"
+        else:
+            fail("ocamldeps makefile, unexpected extension: " + x)
+        possible = [src for src in srcs if y.endswith("/" + src.short_path)]
+        if len(possible) == 1:
+            result[x] = possible[0]
+        elif len(possible) == 0:
+            # If we get here, then ocamldep has found a dependency on a .ml file
+            # that wasn't in `srcs`. On Remote Execution, that shouldn't happen,
+            # and would be user error. When running locally, ocamldep will look
+            # at any .ml files that are in the same directory as a `srcs` (no
+            # way to stop it), so sometimes it finds those when they are meant
+            # to be opaque or coming in through `deps`. The only solution is
+            # just to ignore such unknown entries and "pretend" the .ml file
+            # wasn't found.
+            pass
+        else:
+            fail("ocamldeps makefile, multiple sources: " + x)
+    return result
+
+# Do the low level parse, returning the strings that are in the makefile as
+# dependencies
+def _parse(makefile: str) -> list[(list[str], list[str])]:
+    # For the OCaml makefile, it's a series of lines, often with a '\' line
+    # continuation.
+    lines = []
+    line = ""
+    for x in makefile.splitlines():
+        if x.endswith("\\"):
+            line += x[:-1]
+        else:
+            lines.append(line + x)
+            line = ""
+    lines.append(line)
+
+    result = []
+    for x in lines:
+        before, _, after = (x + " ").partition(" : ")
+        result.append((before.split(), after.strip().split()))
+    return result
+
+# If 'f.cmi' appears on the LHS of a rule, change occurrences of 'f.cmx' to
+# 'f.cmi' in all RHS's in the results of a parsed makefile.
+def _replace_rhs_cmx_with_cmi(contents: list[(list[str], list[str])], p: (list[str], list[str])) -> (list[str], list[str]):
+    def replace_in(p):
+        pre, ext = paths.split_extension(p)
+
+        # Search the LHS's of contents for a for 'p.cmi'.
+        exists = len([p for p in contents if pre + ".cmi" in p[0]]) != 0
+        if exists and ext == ".cmx":
+            # Replace 'p.cmx' in this RHS with 'p.cmi'.
+            return pre + ".cmi"
+        return p
+
+    xs, ys = p
+    return (xs, [replace_in(y) for y in ys])
diff --git a/buck2/prelude/ocaml/ocaml.bzl b/buck2/prelude/ocaml/ocaml.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ocaml/ocaml.bzl
@@ -0,0 +1,1114 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Implementation of the OCaml build rules.
+
+# IMPORTANT: Don't land your change without running these tests!
+# ```
+# buck2 build --num-threads 4 $(buck2 uquery "kind('ocaml_binary', 'fbcode//hphp/...')")
+# ```
+#
+# If you are really, really keen, this command builds all hack, not just the
+# OCaml binaries.
+# ```
+# buck2 build --num-threads 4 fbcode//hphp/hack/...
+# ```
+
+# To avoid name collisions (where '/' designates the build output
+# directory root):
+#
+
+#   - Binaries (.opt) and libraries (.a, .cmxa) are written to '/'
+#   - Where <mode> is one of 'bytecode', 'native' or 'expand':
+#     - Generated sources are written to `/_<mode>_gen_`
+#     - Intermedidate files (.cmi, .cmti, .cmt, .cmx, .o, .pp.ml, ...) are
+#       written to `/_<mode>_obj_`
+#
+# For example given,
+#   ocaml_binary(
+#      name = "quux",
+#      srcs = [
+#          "quux/quux.ml",
+#          "quux/corge/corge.ml"
+#      ],
+#   )
+# the structure of the native build output will be (roughly)
+# /
+#   _native_obj_/
+#     quux/quux.cmi
+#     quux/quux.cmx
+#     quux/quux.o
+#     quux/corge/corge.cmi
+#     quux/corge/corge.cmx
+#     quux/corge/corge.o
+#   quux.opt
+
+load("@prelude//:local_only.bzl", "link_cxx_binary_locally")
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_link_utility.bzl",
+    "make_link_args",
+)
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "CPreprocessorInfo",
+    "cxx_merge_cpreprocessors",
+)
+load(
+    "@prelude//linking:link_groups.bzl",
+    "merge_link_group_lib_info",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkStrategy",
+    "LinkerFlags",
+    "MergedLinkInfo",
+    "ObjectsLinkable",
+    "create_merged_link_info",
+    "create_merged_link_info_for_propagation",
+    "get_link_args_for_strategy",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+    "create_linkable_node",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "merge_shared_libraries",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load(
+    "@prelude//python:python.bzl",
+    "PythonLibraryInfo",
+)
+load("@prelude//utils:graph_utils.bzl", "depth_first_traversal", "post_order_traversal")
+load("@prelude//utils:utils.bzl", "filter_and_map_idx")
+load(":makefile.bzl", "parse_makefile")
+load(
+    ":ocaml_toolchain_types.bzl",
+    "OCamlLibraryInfo",
+    "OCamlLinkInfo",
+    "OCamlToolchainInfo",
+    "OtherOutputsInfo",
+    "merge_ocaml_link_infos",
+    "merge_other_outputs_info",
+)
+
+BuildMode = enum("native", "bytecode", "expand")
+
+# Native vs. bytecode compiler.
+def _is_native(mode: BuildMode) -> bool:
+    return mode.value in ("native", "expand")
+
+# The type of the return value of the `_compile()` function.
+CompileResultInfo = record(
+    # The .cmx file names in topological order
+    cmxs_order = field(Artifact),
+    # .o files (of .c files)
+    stbs = field(list[Artifact], []),
+    # .o files (of .ml files)
+    objs = field(list[Artifact], []),
+    # .cmi files
+    cmis = field(list[Artifact], []),
+    # .cmo files
+    cmos = field(list[Artifact], []),
+    # .cmx files
+    cmxs = field(list[Artifact], []),
+    # .cmt files
+    cmts = field(list[Artifact], []),
+    # .cmti files
+    cmtis = field(list[Artifact], []),
+    # .pp.mli files
+    ppmlis = field(list[Artifact], []),
+    # .pp.ml files
+    ppmls = field(list[Artifact], []),
+)
+
+def _compile_result_to_tuple(r):
+    return (r.cmxs_order, r.stbs, r.objs, r.cmis, r.cmos, r.cmxs, r.cmts, r.cmtis, r.ppmlis, r.ppmls)
+
+# ---
+
+def _attr_deps(ctx: AnalysisContext) -> list[Dependency]:
+    return ctx.attrs.deps
+
+def _attr_deps_merged_link_infos(ctx: AnalysisContext) -> list[MergedLinkInfo]:
+    return filter(None, [d.get(MergedLinkInfo) for d in _attr_deps(ctx)])
+
+def _attr_deps_ocaml_link_infos(ctx: AnalysisContext) -> list[OCamlLinkInfo]:
+    return filter(None, [d.get(OCamlLinkInfo) for d in _attr_deps(ctx)])
+
+def _attr_deps_other_outputs_infos(ctx: AnalysisContext) -> list[OtherOutputsInfo]:
+    return filter(None, [d.get(OtherOutputsInfo) for d in _attr_deps(ctx)])
+
+# ---
+
+# Rules
+
+# We want to pass a series of arguments as a command, but the OCaml compiler
+# only lets us pass a single script. Therefore, produce a script that contains
+# many arguments.
+def _mk_script(ctx: AnalysisContext, file: str, args: list[typing.Any], env: dict[str, typing.Any]) -> cmd_args:
+    lines = ["#!/usr/bin/env bash"]
+    for name, val in env.items():
+        lines.append(cmd_args(val, format = "export {}={{}}".format(name)))
+    lines.append(cmd_args([cmd_args(args, quote = "shell"), '"$@"'], delimiter = " "))
+    script, _ = ctx.actions.write(
+        file,
+        lines,
+        is_executable = True,
+        allow_args = True,
+        has_content_based_path = False,
+    )
+    return cmd_args(script, hidden = args + env.values())
+
+# An environment in which a custom `bin` is at the head of `$PATH`.
+def _mk_env(ctx: AnalysisContext) -> dict[str, cmd_args]:
+    ocaml_toolchain = ctx.attrs._ocaml_toolchain[OCamlToolchainInfo]
+
+    # "Partial linking" (via `ocamlopt.opt -output-obj`) emits calls to `ld -r
+    # -o`. This is the `ld` that will be invoked. See [Note: What is
+    # `binutils_ld`?] in `providers.bzl`.
+    binutils_ld = ocaml_toolchain.binutils_ld
+    binutils_as = ocaml_toolchain.binutils_as
+
+    links = {}
+    if binutils_as != None:
+        links["as"] = binutils_as
+    if binutils_ld != None:
+        links["ld"] = binutils_ld
+
+    if links:
+        # A local `bin` dir of soft links.
+        bin = ctx.actions.symlinked_dir("bin", links, has_content_based_path = False)
+
+        # An environment in which `bin` is at the head of `$PATH`.
+        return {"PATH": cmd_args(bin, format = '{}:"$PATH"')}
+    else:
+        return {}
+
+# Pass '-cc cc.sh' to ocamlopt to use 'cc.sh' as the C compiler.
+def _mk_cc(ctx: AnalysisContext, cc_args: list[typing.Any], cc_sh_filename: typing.Any) -> cmd_args:
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    compiler = cxx_toolchain.c_compiler_info.compiler
+    return _mk_script(ctx, cc_sh_filename, [compiler] + cc_args, {})
+
+# Pass '-cc ld.sh' to ocamlopt to use 'ld.sh' as the C linker.
+# Uses @argsfile to avoid ARG_MAX limits with large LTO link commands.
+def _mk_ld(ctx: AnalysisContext, link_args: list[typing.Any], ld_sh_filename: typing.Any) -> cmd_args:
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    linker = cxx_toolchain.linker_info.linker
+    linker_flags = cxx_toolchain.linker_info.linker_flags
+
+    argsfile_name = ld_sh_filename.removesuffix(".sh") + "_args.txt"
+    all_link_args = cmd_args(linker_flags)
+    all_link_args.add(link_args)
+    argsfile, _ = ctx.actions.write(argsfile_name, all_link_args, allow_args = True, with_inputs = True, has_content_based_path = False)
+
+    argsfile_ref = cmd_args(argsfile, format = "@{}", hidden = all_link_args)
+    return _mk_script(ctx, ld_sh_filename, [linker, argsfile_ref], {})
+
+# This should get called only once for any invocation of `ocaml_library_impl`,
+# `ocaml_binary_impl` (or `prebuilt_ocaml_library_impl`) and choice of
+# `build_mode`. It produces a script that forwards arguments to the ocaml
+# compiler (one of `ocamlopt.opt` vs `ocamlc.opt` consistent with the value of
+# `build_mode`) in the environment of a local 'bin' directory.
+def _mk_ocaml_compiler(ctx: AnalysisContext, env: dict[str, typing.Any], build_mode: BuildMode) -> cmd_args:
+    ocaml_toolchain = ctx.attrs._ocaml_toolchain[OCamlToolchainInfo]
+    compiler = ocaml_toolchain.ocaml_compiler if _is_native(build_mode) else ocaml_toolchain.ocaml_bytecode_compiler
+    script_name = "ocamlopt" + build_mode.value + ".sh"
+    script_args = _mk_script(ctx, script_name, [compiler], env)
+    return script_args
+
+def _get_empty_link_infos() -> dict[LibOutputStyle, LinkInfos]:
+    infos = {}
+    for output_style in LibOutputStyle:
+        infos[output_style] = LinkInfos(default = LinkInfo())
+    return infos
+
+def _get_linkable_graph(
+    ctx: AnalysisContext,
+    preferred_linkage: Linkage,
+    deps: list[Dependency] = [],
+    link_infos: dict[LibOutputStyle, LinkInfos] = {},
+    linker_flags: [LinkerFlags, None] = None,
+) -> LinkableGraph:
+    if not deps:
+        deps = ctx.attrs.deps
+    return create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            linkable_node = create_linkable_node(
+                ctx,
+                default_soname = None,
+                preferred_linkage = preferred_linkage,
+                deps = deps,
+                link_infos = link_infos if link_infos else _get_empty_link_infos(),
+                linker_flags = linker_flags,
+            ),
+        ),
+        deps = deps,
+    )
+
+# A command initialized with flags common to all compiler commands.
+def _compiler_cmd(ctx: AnalysisContext, compiler: cmd_args, cc: cmd_args) -> cmd_args:
+    ocaml_toolchain = ctx.attrs._ocaml_toolchain[OCamlToolchainInfo]
+
+    cmd = cmd_args(compiler)
+    cmd.add("-g", "-noautolink")
+    if ocaml_toolchain.interop_includes:
+        cmd.add("-nostdlib")
+    cmd.add("-cc", cc)
+
+    # First add compiler flags. These contain 'ocaml_common.bzl' flags
+    # e.g. -w @a -safe-string followed by any target specific flags
+    # (like -ppx ... for example). Note that ALL warnings (modulo
+    # safe-string) are enabled and marked as fatal by this.
+    cmd.add(ctx.attrs.compiler_flags)
+
+    # Now, add in `COMMON_OCAML_WARNING_FLAGS` (defined by
+    # 'fbcode/tools/build/buck/gen_modes.py') e.g.
+    # -4-29-35-41-42-44-45-48-50 to selective disable warnings.
+    attr_warnings = ctx.attrs.warnings_flags if ctx.attrs.warnings_flags != None else ""
+    cmd.add("-w", ocaml_toolchain.warnings_flags + attr_warnings)
+
+    return cmd
+
+# The include paths for the immediate dependencies of the current target.
+def _include_paths_in_context(ctx: AnalysisContext, build_mode: BuildMode):
+    ocaml_libs = merge_ocaml_link_infos(_attr_deps_ocaml_link_infos(ctx)).info
+    includes = []
+    for lib in ocaml_libs:
+        includes.extend(lib.include_dirs_nat if _is_native(build_mode) else lib.include_dirs_byt)
+
+    # It's helpful if the stdlib search path comes last.
+    ocaml_toolchain = ctx.attrs._ocaml_toolchain[OCamlToolchainInfo]
+    includes.extend([cmd_args(ocaml_toolchain.interop_includes)] if ocaml_toolchain.interop_includes else [])
+
+    return includes
+
+def _compiler_flags(ctx: AnalysisContext, build_mode: BuildMode):
+    ocaml_toolchain = ctx.attrs._ocaml_toolchain[OCamlToolchainInfo]
+    mode_flags = ocaml_toolchain.ocamlopt_flags if _is_native(build_mode) else ocaml_toolchain.ocamlc_flags
+
+    return ocaml_toolchain.ocaml_compiler_flags + mode_flags
+
+# Configure a new compile command. Each source file (.mli, .ml) gets one of its
+# own.
+def _compile_cmd(ctx: AnalysisContext, compiler: cmd_args, build_mode: BuildMode, cc: cmd_args, includes: list[cmd_args]) -> cmd_args:
+    cmd = _compiler_cmd(ctx, compiler, cc)
+    cmd.add("-bin-annot")  # TODO(sf, 2023-02-21): Move this to 'gen_modes.py'?
+    cmd.add(_compiler_flags(ctx, build_mode))
+    cmd.add(cmd_args(includes, format = "-I={}"))
+
+    return cmd
+
+# Run any preprocessors, returning a list of ml/mli/c artifacts you can compile
+def _preprocess(ctx: AnalysisContext, srcs: list[Artifact], build_mode: BuildMode) -> list[Artifact]:
+    ocaml_toolchain = ctx.attrs._ocaml_toolchain[OCamlToolchainInfo]
+    ocamllex = ocaml_toolchain.lex_compiler
+    menhir = ocaml_toolchain.menhir_compiler  # We no longer use yacc_compiler, just menhir.
+
+    result = []
+    gen_dir = "_" + build_mode.value + "_gen_/"
+    for src in srcs:
+        ext = src.extension
+
+        if ext == ".mly":
+            name = gen_dir + paths.replace_extension(src.short_path, "")
+
+            # We don't actually need the file `prefix`. It's a device
+            # we use to get the `-b` flag argument.
+            prefix = ctx.actions.write(name, "", has_content_based_path = False)
+            parser = ctx.actions.declare_output(name + ".ml", has_content_based_path = False)
+            parser_sig = ctx.actions.declare_output(name + ".mli", has_content_based_path = False)
+            result.extend((parser_sig, parser))
+
+            cmd = cmd_args(
+                [menhir, "--fixed-exception", "-b", cmd_args(prefix, ignore_artifacts = True), src],
+                hidden = [parser.as_output(), parser_sig.as_output()],
+            )
+            ctx.actions.run(cmd, category = "ocaml_yacc_" + build_mode.value, identifier = src.short_path)
+
+        elif ext == ".mll":
+            name = gen_dir + paths.replace_extension(src.short_path, "")
+            lexer = ctx.actions.declare_output(name + ".ml", has_content_based_path = False)
+            result.append(lexer)
+
+            cmd = cmd_args([ocamllex, src, "-o", lexer.as_output()])
+            ctx.actions.run(cmd, category = "ocaml_lex_" + build_mode.value, identifier = src.short_path)
+
+        else:
+            result.append(src)
+
+    return result
+
+# Generate the dependencies
+def _depends(ctx: AnalysisContext, srcs: list[Artifact], build_mode: BuildMode) -> Artifact:
+    ocaml_toolchain = ctx.attrs._ocaml_toolchain[OCamlToolchainInfo]
+    ocamldep = ocaml_toolchain.dep_tool
+
+    dep_output_filename = "ocamldep_" + build_mode.value + ".mk"
+    dep_output = ctx.actions.declare_output(dep_output_filename, has_content_based_path = False)
+    dep_cmdline = cmd_args([ocamldep, "-native"])  # Yes, always native (see D36426635 for details).
+
+    # We are writing the command into a file for later execution. Each flag
+    # needs enclosing in quotes (since it's possible that some flags contain
+    # might contain whitespace e.g. `foo --as-ppx`).
+    dep_cmdline.add([cmd_args(f, format = '"{}"') for f in ctx.attrs.ocamldep_flags])
+
+    # These -I's are for ocamldep.
+    dep_cmdline.add(cmd_args([cmd_args(src, parent = 1) for src in srcs], format = "-I {}"))
+    dep_cmdline.add(srcs)
+    dep_script_name = "ocamldep_" + build_mode.value + ".sh"
+    dep_sh, _ = ctx.actions.write(
+        dep_script_name,
+        ["#!/usr/bin/env bash", cmd_args([dep_cmdline, ">", dep_output], delimiter = " ")],
+        is_executable = True,
+        allow_args = True,
+        has_content_based_path = False,
+    )
+    ctx.actions.run(cmd_args(dep_sh, hidden = [dep_output.as_output(), dep_cmdline]), category = "ocamldep_" + build_mode.value)
+    return dep_output
+
+# Compile all the context's sources. If bytecode compiling, 'cmxs' & 'objs' will
+# be empty in the returned tuple while 'cmos' will be non-empty. If compiling
+# native code, 'cmos' in the returned info will be empty while 'objs' & 'cmxs'
+# will be non-empty.
+def _compile(ctx: AnalysisContext, compiler: cmd_args, build_mode: BuildMode) -> CompileResultInfo:
+    opaque_enabled = "-opaque" in _compiler_flags(ctx, build_mode)
+    is_native = _is_native(build_mode)
+    is_bytecode = not is_native
+
+    # Preprocess: Generate modules from lexers and parsers.
+    srcs = _preprocess(ctx, ctx.attrs.srcs, build_mode)
+    headers = [s for s in srcs if s.extension == ".h"]
+    mlis = {s.short_path: s for s in srcs if s.extension == ".mli"}
+
+    # 'ocamldep' will be sorting .cmo files or it will be sorting .cmx files and
+    # so needs to know if we are byte or native compiling.
+    depends_output = _depends(ctx, srcs, build_mode)
+
+    # Compile
+    produces = {}  # A tuple of things each source file produces.
+    includes = {}  # Source file, .cmi pairs.
+    stbs, objs, cmis, cmos, cmxs, cmts, cmtis, ppmlis, ppmls = ([], [], [], [], [], [], [], [], [])
+    obj_dir = "_" + build_mode.value + "obj_/"
+    for src in srcs:
+        obj_name = obj_dir + paths.replace_extension(src.short_path, "")
+        ext = src.extension
+
+        if ext == ".mli":
+            cmi = ctx.actions.declare_output(obj_name + ".cmi", has_content_based_path = False)
+            cmti = ctx.actions.declare_output(obj_name + ".cmti", has_content_based_path = False)
+            ppmli = ctx.actions.declare_output(obj_name + ".pp.mli", has_content_based_path = False) if build_mode.value == "expand" else None
+            produces[src] = (cmi, cmti, ppmli)
+            includes[src] = cmi
+            cmis.append(cmi)
+            cmtis.append(cmti)
+            if ppmli != None:
+                ppmlis.append(ppmli)
+
+        elif ext == ".ml":
+            # Sometimes a .ml file has an explicit .mli, sometimes its implicit
+            # and we generate it. The variable below contains the artifact of
+            # the explicit mli if present.
+            mli = mlis.get(paths.replace_extension(src.short_path, ".mli"), None)
+
+            cmt = ctx.actions.declare_output(obj_name + ".cmt", has_content_based_path = False)
+            obj = ctx.actions.declare_output(obj_name + ".o", has_content_based_path = False) if is_native else None
+            cmx = ctx.actions.declare_output(obj_name + ".cmx", has_content_based_path = False) if is_native else None
+            cmo = ctx.actions.declare_output(obj_name + ".cmo", has_content_based_path = False) if is_bytecode else None
+            cmi = ctx.actions.declare_output(obj_name + ".cmi", has_content_based_path = False) if mli == None else None
+            ppml = ctx.actions.declare_output(obj_name + ".pp.ml", has_content_based_path = False) if build_mode.value == "expand" else None
+            produces[src] = (obj, cmo, cmx, cmt, cmi, ppml)
+
+            if cmo != None:
+                cmos.append(cmo)
+            if cmx != None:
+                cmxs.append(cmx)
+            if obj != None:
+                objs.append(obj)
+            if cmi != None:
+                cmis.append(cmi)
+                includes[src] = cmi
+            if ppml != None:
+                ppmls.append(ppml)
+            cmts.append(cmt)
+
+        elif ext == ".c":
+            stb = ctx.actions.declare_output(obj_name + ".o", has_content_based_path = False)
+            produces[src] = (stb,)
+            stbs.append(stb)
+
+        elif ext == ".h":
+            pass
+
+        else:
+            fail("Unexpected extension: '" + src.basename + "'")
+
+    # FIXME: Should populate these
+    todo_inputs = []
+
+    outputs = []
+    for x in produces.values():
+        outputs.extend(x)
+    outputs = filter(None, outputs)
+
+    # A file containing topologically sorted .cmx or .cmo files. We use the name
+    # 'cmxs_order' without regard for which.
+    cmxs_order = ctx.actions.declare_output("cmxs_order_" + build_mode.value + ".lst", has_content_based_path = False)
+
+    pre = cxx_merge_cpreprocessors(ctx.actions, [], filter(None, [d.get(CPreprocessorInfo) for d in _attr_deps(ctx)]))
+    pre_args = pre.set.project_as_args("args")
+    cc_sh_filename = "cc_" + build_mode.value + ".sh"
+    cc = _mk_cc(ctx, [pre_args], cc_sh_filename)
+
+    # These -I's are common to all compile commands for the given 'ctx'. This
+    # includes the compiler include path.
+    global_include_paths = _include_paths_in_context(ctx, build_mode)
+
+    def f(ctx: AnalysisContext, artifacts, outputs):
+        # A pair of mappings that detail which source files depend on which. See
+        # [Note: Dynamic dependencies] in 'makefile.bzl'.
+        makefile, makefile2 = parse_makefile(artifacts[depends_output].read_string(), srcs, opaque_enabled)
+
+        # Ensure all '.ml' files are in the makefile, with zero dependencies if
+        # necessary (so 'post_order_traversal' finds them).
+        for x in srcs:
+            if x.short_path.endswith(".ml"):
+                if x not in makefile:
+                    makefile[x] = []
+                if x not in makefile2:
+                    makefile2[x] = []
+
+        mk_out = lambda x: outputs[x].as_output()
+
+        # We want to write out all the compiled module files in transitive
+        # dependency order.
+        #
+        # If compiling bytecode we order .cmo files (index 1) otherwise .cmx
+        # files (index 2).
+        cm_kind_index = 1 if is_bytecode else 2
+        ctx.actions.write(
+            mk_out(cmxs_order),  # write the ordered list
+            [produces[x][cm_kind_index] for x in post_order_traversal(makefile) if x.short_path.endswith(".ml")],
+        )
+
+        # Compile
+        for src in srcs:
+            ext = src.extension
+
+            # Things that are produced/includable from my dependencies
+            depends_produce = []
+
+            # These -I's are for the compile command for 'src'. They result from
+            # the dependency of 'src' on other files in 'srcs'.
+            depends_include_paths = []
+            seen_dirs = {}
+            for d in depth_first_traversal(makefile2, makefile2.get(src, [])):
+                # 'src' depends on 'd' (e.g. src='quux.ml' depends on
+                # d='quux.mli').
+                #
+                # What artifacts does compiling 'd' produce? These are hidden
+                # dependencies of the command to compile 'src' (e.g.
+                # 'quux.cmi').
+                #
+                # In the event `-opaque` is enabled, 'makefile2' is a rewrite of
+                # 'makefile' such that if 'f.mli' exists, then we will never
+                # have a dependency here on 'f.cmx' ('f.cmo') only 'f.cmi'.
+                depends_produce.extend(filter(None, produces[d]))
+                i = includes.get(d, None)
+                if i != None:
+                    p = paths.dirname(i.short_path)
+                    if not p in seen_dirs:
+                        depends_include_paths.append(cmd_args(i, parent = 1))
+                        seen_dirs[p] = None
+
+            # *All* the include paths needed to compile 'src'.
+            all_include_paths = depends_include_paths + global_include_paths
+
+            if ext == ".mli":
+                (cmi, cmti, ppmli) = produces[src]
+                cmd = _compile_cmd(ctx, compiler, build_mode, cc, all_include_paths)
+                cmd.add(src, "-c", "-o", mk_out(cmi))
+                if build_mode.value == "expand":
+                    cmd.add("-dsource")
+                cmd.add(cmd_args(hidden = [mk_out(cmti), depends_produce]))
+
+                if build_mode.value == "expand":
+                    sh = cmd_args(["/bin/sh", "-c", '"$@" 2> "$preprocessed_source_file"', "--", cmd])
+                    env = {"preprocessed_source_file": mk_out(ppmli)}
+                    ctx.actions.run(sh, category = "shell_ocaml_" + build_mode.value, identifier = src.short_path, env = env)
+                else:
+                    ctx.actions.run(cmd, category = "ocaml_compile_mli_" + build_mode.value, identifier = src.short_path)
+
+            elif ext == ".ml":
+                (obj, cmo, cmx, cmt, cmi, ppml) = produces[src]
+                cmd = _compile_cmd(ctx, compiler, build_mode, cc, all_include_paths)
+                cmd.add(cmd_args(hidden = depends_produce))
+                if cmo != None:
+                    cmd.add(src, "-c", "-o", mk_out(cmo))
+                if cmx != None:
+                    cmd.add(src, "-c", "-o", mk_out(cmx))
+                cmd.add(cmd_args(hidden = mk_out(cmt)))
+                if build_mode.value == "expand":
+                    cmd.add("-dsource")
+                if obj != None:
+                    cmd.add(cmd_args(hidden = mk_out(obj)))
+                if cmi != None:
+                    cmd.add("-intf-suffix", ",nomli,")  # ignore any .mlis that aren't explicit dependencies
+                    cmd.add(cmd_args(hidden = mk_out(cmi)))
+                else:
+                    # An explicit '.mli' for this '.ml' is a dependency.
+                    cmd.add(cmd_args(hidden = mlis[paths.replace_extension(src.short_path, ".mli")]))
+
+                if build_mode.value == "expand":
+                    sh = cmd_args(["/bin/sh", "-c", '"$@" 2> "$preprocessed_source_file"', "--", cmd])
+                    env = {"preprocessed_source_file": mk_out(ppml)}
+                    ctx.actions.run(sh, category = "shell_ocaml_" + build_mode.value, identifier = src.short_path, env = env)
+                else:
+                    ctx.actions.run(cmd, category = "ocaml_compile_ml_" + build_mode.value, identifier = src.short_path)
+
+            elif ext == ".c":
+                (stb,) = produces[src]
+                cmd = _compile_cmd(ctx, compiler, build_mode, cc, all_include_paths)
+
+                # `ocaml_object` breaks for `-flto=...` so ensure `-fno-lto` prevails here.
+                cmd.add(src, "-c", "-ccopt", "-fno-lto", "-ccopt", cmd_args(mk_out(stb), format = '-o "{}"'))
+                cmd.add(cmd_args(hidden = headers))  # Any .h files given are dependencies.
+                ctx.actions.run(cmd, category = "ocaml_compile_c", identifier = src.short_path)
+
+            elif ext == ".h":
+                pass
+
+            else:
+                fail("Unexpected extension: '" + src.basename + "'")
+
+    if outputs == []:
+        ctx.actions.write(cmxs_order, "")
+    else:
+        ctx.actions.dynamic_output(
+            dynamic = [depends_output],
+            inputs = todo_inputs,
+            outputs = [o.as_output() for o in outputs + [cmxs_order]],
+            f = f,
+        )
+
+    return CompileResultInfo(cmxs_order = cmxs_order, stbs = stbs, objs = objs, cmis = cmis, cmos = cmos, cmxs = cmxs, cmts = cmts, cmtis = cmtis, ppmlis = ppmlis, ppmls = ppmls)
+
+# The include path directories a client will provide a compile command to use
+# the given artifacts.
+def _include_paths(cmis: list[Artifact], cmos: list[Artifact]) -> cmd_args:
+    include_paths = []
+    seen_dirs = {}
+    for f in cmis:
+        p = paths.dirname(f.short_path)
+        if not p in seen_dirs:
+            include_paths.append(cmd_args(f, parent = 1))
+            seen_dirs[p] = None
+    for f in cmos:
+        p = paths.dirname(f.short_path)
+        if not p in seen_dirs:
+            include_paths.append(cmd_args(f, parent = 1))
+            seen_dirs[p] = None
+    include_paths = cmd_args(
+        include_paths,
+        hidden = cmis + cmos,
+    )
+    return include_paths
+
+def ocaml_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    opaque_enabled_nat = "-opaque" in _compiler_flags(ctx, BuildMode("native"))
+    opaque_enabled_byt = "-opaque" in _compiler_flags(ctx, BuildMode("bytecode"))
+
+    env = _mk_env(ctx)
+    ocamlopt = _mk_ocaml_compiler(ctx, env, BuildMode("native"))
+    ocamlc = _mk_ocaml_compiler(ctx, env, BuildMode("bytecode"))
+
+    ld_nat = _mk_ld(ctx, [], "ld_native.sh")
+    ld_byt = _mk_ld(ctx, [], "ld_bytecode.sh")
+
+    cmd_nat = _compiler_cmd(ctx, ocamlopt, ld_nat)
+    cmd_byt = _compiler_cmd(ctx, ocamlc, ld_byt)
+
+    cmxs_order, stbs_nat, objs, cmis_nat, _cmos, cmxs, cmts_nat, cmtis_nat, _, _ = _compile_result_to_tuple(_compile(ctx, ocamlopt, BuildMode("native")))
+    _, _, _, _, _, _, _, _, ppmlis, ppmls = _compile_result_to_tuple(_compile(ctx, ocamlopt, BuildMode("expand")))
+    cmd_nat.add("-a")
+    cmxa = ctx.actions.declare_output("lib" + ctx.attrs.name + ".cmxa", has_content_based_path = False)
+    cmd_nat.add("-o", cmxa.as_output())
+    if len([s for s in ctx.attrs.srcs if s.extension == ".ml"]) != 0:
+        native_c_lib = ctx.actions.declare_output("lib" + ctx.attrs.name + ".a", has_content_based_path = False)
+        cmd_nat.add(cmd_args(hidden = native_c_lib.as_output()))
+        native_c_libs = [native_c_lib]
+    else:
+        native_c_libs = []
+    cmd_nat.add(stbs_nat, "-args", cmxs_order)
+
+    # Native clients need these compile flags to use this library.
+    include_paths_nat = _include_paths(cmis_nat, cmxs if not opaque_enabled_nat else [])
+
+    # These were produced by the compile step and so are hidden dependencies of
+    # the archive step.
+    cmd_nat.add(cmd_args(hidden = [cmxs, cmis_nat, objs, cmts_nat, cmtis_nat]))
+    ctx.actions.run(cmd_nat, category = "ocaml_archive_native")
+
+    cmxs_order, stbs_byt, _objs, cmis_byt, cmos, _cmxs, cmts_byt, cmtis_byt, _ppmlis, _ppmls = _compile_result_to_tuple(
+        _compile(ctx, ocamlc, BuildMode("bytecode"))
+    )
+    cmd_byt.add("-a")
+
+    cma = ctx.actions.declare_output("lib" + ctx.attrs.name + ".cma", has_content_based_path = False)
+    cmd_byt.add("-o", cma.as_output())
+    cmd_byt.add(stbs_byt, "-args", cmxs_order)
+
+    # Bytecode clients need these compile flags to use this library.
+    include_paths_byt = _include_paths(cmis_byt, cmos if not opaque_enabled_byt else [])
+
+    # These were produced by the compile step and so are hidden dependencies of
+    # the archive step.
+    cmd_byt.add(cmd_args(hidden = [cmos, cmis_byt, cmts_byt, cmtis_byt]))
+    ctx.actions.run(cmd_byt, category = "ocaml_archive_bytecode")
+
+    infos = _attr_deps_ocaml_link_infos(ctx)
+    infos.append(
+        OCamlLinkInfo(
+            info = [
+                OCamlLibraryInfo(
+                    name = ctx.attrs.name,
+                    target = ctx.label,
+                    c_libs = [],
+                    stbs_nat = stbs_nat,
+                    stbs_byt = stbs_byt,
+                    cmas = [cma],
+                    cmxas = [cmxa],
+                    cmis_nat = cmis_nat,
+                    cmis_byt = cmis_byt,
+                    cmos = cmos,
+                    cmxs = cmxs,
+                    cmts_nat = cmts_nat,
+                    cmts_byt = cmts_byt,
+                    cmtis_nat = cmtis_nat,
+                    cmtis_byt = cmtis_byt,
+                    include_dirs_nat = [include_paths_nat],
+                    include_dirs_byt = [include_paths_byt],
+                    native_c_libs = native_c_libs,
+                    bytecode_c_libs = [],
+                )
+            ]
+        ),
+    )
+
+    other_outputs = {
+        "bytecode": cmis_byt + cmos,
+        "expand": ppmlis + ppmls,
+        "ide": cmis_nat + cmtis_nat + cmts_nat,
+    }
+    other_outputs_info = merge_other_outputs_info(ctx, other_outputs, _attr_deps_other_outputs_infos(ctx))
+
+    info_ide = [
+        DefaultInfo(
+            default_output = cmts_nat[0] if cmts_nat else None,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("ide"))],
+        ),
+    ]
+    info_byt = [
+        DefaultInfo(
+            default_output = cma,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("bytecode"))],
+        ),
+    ]
+    info_expand = [
+        DefaultInfo(
+            default_output = cmxa,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("expand"))],
+        ),
+    ]
+    sub_targets = {"bytecode": info_byt, "expand": info_expand, "ide": info_ide}
+
+    if ctx.attrs.bytecode_only:
+        return info_byt
+
+    return [
+        DefaultInfo(default_output = cmxa, sub_targets = sub_targets),
+        merge_ocaml_link_infos(infos),
+        create_merged_link_info_for_propagation(ctx, _attr_deps_merged_link_infos(ctx)),
+        merge_shared_libraries(ctx.actions, deps = filter_and_map_idx(SharedLibraryInfo, _attr_deps(ctx))),
+        merge_link_group_lib_info(deps = _attr_deps(ctx)),
+        other_outputs_info,
+        _get_linkable_graph(ctx, Linkage("any")),
+    ]
+
+def ocaml_binary_impl(ctx: AnalysisContext) -> list[Provider]:
+    ocaml_toolchain = ctx.attrs._ocaml_toolchain[OCamlToolchainInfo]
+    ocaml_toolchain_runtime_deps = ocaml_toolchain.runtime_dep_link_extras
+
+    env = _mk_env(ctx)
+    ocamlopt = _mk_ocaml_compiler(ctx, env, BuildMode("native"))
+    ocamlc = _mk_ocaml_compiler(ctx, env, BuildMode("bytecode"))
+
+    dep_link_infos = _attr_deps_merged_link_infos(ctx) + filter(None, [ocaml_toolchain.libc]) + [d.get(MergedLinkInfo) for d in ocaml_toolchain_runtime_deps]
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    link_args_output = make_link_args(
+        ctx,
+        ctx.actions,
+        cxx_toolchain,
+        [
+            get_link_args_for_strategy(
+                ctx.actions,
+                ctx.label,
+                cxx_toolchain.linker_info,
+                dep_link_infos,
+                LinkStrategy("static_pic"),
+                prefer_stripped = False,
+                transformation_spec_context = None,
+            )
+        ],
+    )
+    ld_nat = _mk_ld(ctx, [link_args_output.link_args], "ld_native.sh")
+    ld_byt = _mk_ld(ctx, [link_args_output.link_args], "ld_bytecode.sh")
+
+    cmd_nat = _compiler_cmd(ctx, ocamlopt, ld_nat)
+    cmd_byt = _compiler_cmd(ctx, ocamlc, ld_byt)
+
+    # These -I's are to find 'stdlib.cmxa'/'stdlib.cma'.
+    if ocaml_toolchain.interop_includes:
+        cmd_nat.add(cmd_args(ocaml_toolchain.interop_includes, format = "-I={}"))
+        cmd_byt.add(cmd_args(ocaml_toolchain.interop_includes, format = "-I={}"))
+
+    for lib in merge_ocaml_link_infos(_attr_deps_ocaml_link_infos(ctx)).info:
+        cmd_nat.add(lib.cmxas, lib.c_libs, lib.native_c_libs, lib.stbs_nat)
+        cmd_byt.add(lib.cmas, lib.c_libs, lib.bytecode_c_libs, lib.stbs_byt)
+
+    cmxs_order, stbs_nat, objs, cmis_nat, _cmos, cmxs, cmts_nat, cmtis_nat, _, _ = _compile_result_to_tuple(_compile(ctx, ocamlopt, BuildMode("native")))
+    _, _, _, _, _, _, _, _, ppmlis, ppmls = _compile_result_to_tuple(_compile(ctx, ocamlopt, BuildMode("expand")))
+    cmd_nat.add(stbs_nat, "-args", cmxs_order)
+
+    # These were produced by the compile step and are therefore hidden
+    # dependencies of the link step.
+    cmd_nat.add(cmd_args(hidden = [cmxs, cmis_nat, cmts_nat, cmtis_nat, objs, link_args_output.hidden]))
+    binary_nat = ctx.actions.declare_output(ctx.attrs.name + ".opt", has_content_based_path = False)
+
+    cmd_nat.add([cmd_args(["-cclib", f]) for f in ocaml_toolchain.runtime_dep_link_flags])
+    cmd_nat.add("-cclib", "-lpthread")
+    cmd_nat.add("-o", binary_nat.as_output())
+    local_only = link_cxx_binary_locally(ctx)
+    ctx.actions.run(cmd_nat, category = "ocaml_link_native", local_only = local_only)
+
+    cmxs_order, stbs_byt, _objs, cmis_byt, cmos, _cmxs, cmts_byt, cmtis_byt, _, _ = _compile_result_to_tuple(_compile(ctx, ocamlc, BuildMode("bytecode")))
+    cmd_byt.add(stbs_byt, "-args", cmxs_order)
+
+    # These were produced by the compile step and are therefore hidden
+    # dependencies of the link step.
+    cmd_byt.add(cmd_args(hidden = [cmos, cmis_byt, cmts_byt, cmtis_byt, link_args_output.hidden]))
+    binary_byt = ctx.actions.declare_output(ctx.attrs.name, has_content_based_path = False)
+    cmd_byt.add("-custom")
+    cmd_byt.add([cmd_args(["-cclib", f]) for f in ocaml_toolchain.runtime_dep_link_flags])
+    cmd_byt.add("-cclib", "-lpthread")
+    cmd_byt.add("-o", binary_byt.as_output())
+    local_only = link_cxx_binary_locally(ctx)
+    ctx.actions.run(cmd_byt, category = "ocaml_link_bytecode", local_only = local_only)
+
+    other_outputs = {
+        "bytecode": cmis_byt + cmos,
+        "expand": ppmlis + ppmls,
+        "ide": cmis_nat + cmtis_nat + cmts_nat,
+    }
+    other_outputs_info = merge_other_outputs_info(ctx, other_outputs, _attr_deps_other_outputs_infos(ctx))
+
+    info_ide = [
+        DefaultInfo(
+            default_output = cmts_nat[0] if cmts_nat else None,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("ide"))],
+        ),
+    ]
+    info_expand = [
+        DefaultInfo(
+            default_output = binary_nat,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("expand"))],
+        ),
+    ]
+    info_byt = [
+        DefaultInfo(
+            default_output = binary_byt,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("bytecode"))],
+        ),
+        RunInfo(args = [binary_byt]),
+    ]
+    sub_targets = {"bytecode": info_byt, "expand": info_expand, "ide": info_ide}
+
+    if ctx.attrs.bytecode_only:
+        return info_byt
+
+    return [
+        DefaultInfo(default_output = binary_nat, sub_targets = sub_targets),
+        RunInfo(args = [binary_nat]),
+    ]
+
+def ocaml_object_impl(ctx: AnalysisContext) -> list[Provider]:
+    ocaml_toolchain = ctx.attrs._ocaml_toolchain[OCamlToolchainInfo]
+
+    env = _mk_env(ctx)
+    ocamlopt = _mk_ocaml_compiler(ctx, env, BuildMode("native"))
+    dep_link_infos = _attr_deps_merged_link_infos(ctx)
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    link_args_output = make_link_args(
+        ctx,
+        ctx.actions,
+        cxx_toolchain,
+        [
+            get_link_args_for_strategy(
+                ctx.actions,
+                ctx.label,
+                cxx_toolchain.linker_info,
+                dep_link_infos,
+                LinkStrategy("static_pic"),
+                prefer_stripped = False,
+                transformation_spec_context = None,
+            )
+        ],
+    )
+    ld = _mk_ld(ctx, [link_args_output.link_args], "ld.sh")
+
+    cmxs_order, stbs, objs, cmis, _cmos, cmxs, cmts, cmtis, _, _ = _compile_result_to_tuple(_compile(ctx, ocamlopt, BuildMode("native")))
+    _, _, _, _, _, _, _, _, ppmlis, ppmls = _compile_result_to_tuple(_compile(ctx, ocamlopt, BuildMode("expand")))
+
+    cmd = _compiler_cmd(ctx, ocamlopt, ld)
+
+    # These -I's are to find 'stdlib.cmxa'/'stdlib.cma'.
+    if ocaml_toolchain.interop_includes:
+        cmd.add(cmd_args(ocaml_toolchain.interop_includes, format = "-I={}"))
+
+    for lib in merge_ocaml_link_infos(_attr_deps_ocaml_link_infos(ctx)).info:
+        cmd.add(lib.cmxas, lib.c_libs, lib.native_c_libs, lib.stbs_nat)
+        cmd.add(cmd_args(hidden = [lib.cmxs, lib.cmis_nat, lib.cmts_nat]))
+
+    cmd.add(stbs, "-args", cmxs_order)
+    cmd.add(cmd_args(hidden = [cmxs, cmis, cmts, objs, cmtis, link_args_output.hidden]))
+
+    obj = ctx.actions.declare_output(ctx.attrs.name + ".o", has_content_based_path = False)
+    cmd.add("-output-complete-obj")
+    cmd.add("-o", obj.as_output())
+    local_only = link_cxx_binary_locally(ctx)
+    ctx.actions.run(cmd, category = "ocaml_complete_obj_link", local_only = local_only)
+
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    ocaml_toolchain_runtime_deps = ocaml_toolchain.runtime_dep_link_extras
+    linker_type = cxx_toolchain.linker_info.type
+    link_infos = {}
+    linker_flags = [cmd_args(f) for f in ocaml_toolchain.runtime_dep_link_flags]
+    for output_style in LibOutputStyle:
+        link_infos[output_style] = LinkInfos(
+            default = LinkInfo(
+                linkables = [
+                    ObjectsLinkable(objects = [obj], linker_type = linker_type),
+                ],
+                post_flags = linker_flags,
+            )
+        )
+
+    obj_link_info = create_merged_link_info(
+        ctx,
+        pic_behavior = cxx_toolchain.pic_behavior,
+        link_infos = link_infos,
+        exported_deps = dep_link_infos + [d.get(MergedLinkInfo) for d in ocaml_toolchain_runtime_deps],
+    )
+
+    other_outputs = {
+        "bytecode": [],
+        "expand": ppmlis + ppmls,
+        "ide": cmis + cmtis + cmts,
+    }
+    other_outputs_info = merge_other_outputs_info(ctx, other_outputs, _attr_deps_other_outputs_infos(ctx))
+
+    info_ide = [
+        DefaultInfo(
+            default_output = cmts[0] if cmts else None,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("ide"))],
+        ),
+    ]
+    info_byt = [
+        DefaultInfo(
+            default_output = obj,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("bytecode"))],
+        ),
+    ]
+    info_expand = [
+        DefaultInfo(
+            default_output = obj,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("expand"))],
+        ),
+    ]
+    sub_targets = {"bytecode": info_byt, "expand": info_expand, "ide": info_ide}
+
+    deps = _attr_deps(ctx) + ocaml_toolchain_runtime_deps
+
+    return [
+        DefaultInfo(default_output = obj, sub_targets = sub_targets),
+        obj_link_info,
+        merge_link_group_lib_info(deps = deps),
+        merge_shared_libraries(ctx.actions, deps = filter_and_map_idx(SharedLibraryInfo, deps)),
+        _get_linkable_graph(ctx, Linkage("static"), deps, link_infos, LinkerFlags(post_flags = linker_flags)),
+    ]
+
+# `ocaml_shared` enables one to produce an OCaml "plugin". Such native code
+# ('.cmxs') files can be dynamically loaded into a running-process via the
+# `Dynlink` module. Example use cases include writing compiler plugins for use
+# with the `-plugin` compiler flag & "deriver" plugins for use with the
+# `ppx_deriving` framework.
+def ocaml_shared_impl(ctx: AnalysisContext) -> list[Provider]:
+    ocaml_toolchain = ctx.attrs._ocaml_toolchain[OCamlToolchainInfo]
+
+    env = _mk_env(ctx)
+    ocamlopt = _mk_ocaml_compiler(ctx, env, BuildMode("native"))
+
+    dep_link_infos = _attr_deps_merged_link_infos(ctx) + filter(None, [ocaml_toolchain.libc])
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    link_args_output = make_link_args(
+        ctx,
+        ctx.actions,
+        cxx_toolchain,
+        [
+            get_link_args_for_strategy(
+                ctx.actions,
+                ctx.label,
+                cxx_toolchain.linker_info,
+                dep_link_infos,
+                LinkStrategy("static_pic"),
+                prefer_stripped = False,
+                transformation_spec_context = None,
+            )
+        ],
+    )
+
+    # 'ocamlopt.opt' with '-cc' fails to propagate '-shared' (and potentially
+    # other required flags - see the darwin "dylib" specific block below) to the
+    # linker. See https://www.internalfb.com/phabricator/paste/view/P596226070.
+    # This is a workaround.
+    shared_args = ["-shared"]
+    if host_info().os.is_macos:
+        shared_args.extend(["-flat_namespace", "-undefined suppress", "-Wl,-no_compact_unwind"])
+
+    ld_nat = _mk_ld(ctx, shared_args + [link_args_output.link_args], "ld_native.sh")
+
+    cmd_nat = _compiler_cmd(ctx, ocamlopt, ld_nat)
+
+    cmxs_order, stbs, objs, cmis_nat, _cmos, cmxs, cmts_nat, cmtis_nat, _, _ = _compile_result_to_tuple(_compile(ctx, ocamlopt, BuildMode("native")))
+    _, _, _, _, _, _, _, _, ppmlis, ppmls = _compile_result_to_tuple(_compile(ctx, ocamlopt, BuildMode("expand")))
+
+    cmd_nat.add(stbs, "-args", cmxs_order)
+
+    # These were produced by the compile step and are therefore hidden
+    # dependencies of the link step.
+    cmd_nat.add(cmd_args(hidden = [cmxs, cmis_nat, cmts_nat, cmtis_nat, objs, link_args_output.hidden]))
+    binary_nat = ctx.actions.declare_output(ctx.attrs.name + ".cmxs", has_content_based_path = False)
+    cmd_nat.add("-shared")
+    cmd_nat.add("-o", binary_nat.as_output())
+    local_only = link_cxx_binary_locally(ctx)
+    ctx.actions.run(cmd_nat, category = "ocaml_shared_link", local_only = local_only)
+
+    other_outputs = {
+        "bytecode": [],
+        "expand": ppmlis + ppmls,
+        "ide": cmis_nat + cmtis_nat + cmts_nat,
+    }
+    other_outputs_info = merge_other_outputs_info(ctx, other_outputs, _attr_deps_other_outputs_infos(ctx))
+
+    info_ide = [
+        DefaultInfo(
+            default_output = cmts_nat[0] if cmts_nat else None,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("ide"))],
+        ),
+    ]
+    info_expand = [
+        DefaultInfo(
+            default_output = binary_nat,
+            other_outputs = [cmd_args(other_outputs_info.info.project_as_args("expand"))],
+        ),
+    ]
+    sub_targets = {"expand": info_expand, "ide": info_ide}
+
+    return [
+        DefaultInfo(default_output = binary_nat, sub_targets = sub_targets),
+        _get_linkable_graph(ctx, Linkage("shared")),
+    ]
+
+def prebuilt_ocaml_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    # examples:
+    #   name: 'threads'
+    #   bytecode_c_libs: 'libthreads.a'
+    #   bytecode_lib: 'threads.cma'
+    #   native_lib: 'threads.cmxa'
+    #   c_libs: 'libcore_kernel_stubs.a'
+    #   include_dir:  'share/dotopam/.../threads'
+    #   lib_dir: ""
+    #   native_c_libs: 'libthreadsnat.a'
+
+    name = ctx.attrs.name
+    c_libs = ctx.attrs.c_libs
+    cmas = [ctx.attrs.bytecode_lib] if ctx.attrs.bytecode_lib != None else []
+    cmxas = [ctx.attrs.native_lib] if ctx.attrs.native_lib != None else []
+
+    # `ctx.attrs.include_dirs` has type `"artifact"`, convert it to a `cmd_args`
+    include_dirs = [cmd_args(ctx.attrs.include_dir)] if ctx.attrs.include_dir != None else []
+    native_c_libs = ctx.attrs.native_c_libs
+    bytecode_c_libs = ctx.attrs.bytecode_c_libs
+
+    info = OCamlLibraryInfo(
+        name = name,
+        target = ctx.label,
+        c_libs = c_libs,
+        cmas = cmas,
+        cmxas = cmxas,
+        include_dirs_nat = include_dirs,
+        include_dirs_byt = include_dirs,
+        stbs_nat = [],
+        stbs_byt = [],
+        cmis_nat = [],
+        cmis_byt = [],
+        cmos = [],
+        cmxs = [],
+        cmts_nat = [],
+        cmts_byt = [],
+        cmtis_nat = [],
+        cmtis_byt = [],
+        native_c_libs = native_c_libs,
+        bytecode_c_libs = bytecode_c_libs,
+    )
+
+    native_infos, ocaml_infos = ([], [])
+    for dep in ctx.attrs.deps:
+        used = False
+        if OCamlLinkInfo in dep:
+            used = True
+            ocaml_infos.append(dep[OCamlLinkInfo])
+        if MergedLinkInfo in dep:
+            used = True
+            native_infos.append(dep[MergedLinkInfo])
+        if PythonLibraryInfo in dep:
+            used = True
+        if not used:
+            fail("Unexpected link info encountered")
+
+    return [
+        DefaultInfo(),
+        merge_ocaml_link_infos(ocaml_infos + [OCamlLinkInfo(info = [info])]),
+        create_merged_link_info_for_propagation(ctx, native_infos),
+        merge_link_group_lib_info(deps = ctx.attrs.deps),
+        merge_shared_libraries(ctx.actions, deps = filter_and_map_idx(SharedLibraryInfo, ctx.attrs.deps)),
+        _get_linkable_graph(ctx, Linkage("any")),
+    ]
diff --git a/buck2/prelude/ocaml/ocaml_toolchain_types.bzl b/buck2/prelude/ocaml/ocaml_toolchain_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/ocaml/ocaml_toolchain_types.bzl
@@ -0,0 +1,133 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Providers for OCaml build rules.
+
+load("@prelude//utils:utils.bzl", "flatten")
+
+OCamlToolchainInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "ocaml_compiler": provider_field(typing.Any, default = None),
+        # [Note: What is `binutils_ld`?]
+        # ------------------------------
+        # When the compiler is invoked in partial linking mode (`ocamlopt.opt
+        # -output-obj ...`) it makes naked calls to `ld`. In such a case, if we
+        # don't arrange to execute `ocamlopt.opt` in an environment where `ld`
+        # resolves to an `ld` that is either the `ld` in scope when the compiler was
+        # built (or at least compatible with it) it then a call to the system `ld`
+        # will result and almost certainly be a mismatch.
+        #
+        # How the compiler invokes `ld` is established when it's built by its
+        # configure script
+        # (https://github.com/ocaml/ocaml/blob/f27d671b23f5246d37d91571eeccb802d5399a0b/configure.ac).
+        #
+        # So far I've found `fbcode//.../binutils:bin/ld` to be a choice that works.
+        # It's in `_mk_ocaml_opt` in `ocaml.bzl` where we make use of this.
+        "binutils_ld": provider_field(typing.Any, default = None),
+        "binutils_as": provider_field(typing.Any, default = None),
+        "dep_tool": provider_field(typing.Any, default = None),
+        "yacc_compiler": provider_field(typing.Any, default = None),
+        "menhir_compiler": provider_field(typing.Any, default = None),
+        "lex_compiler": provider_field(typing.Any, default = None),
+        "libc": provider_field(typing.Any, default = None),  # MergedLinkInfo of libc
+        "ocaml_bytecode_compiler": provider_field(typing.Any, default = None),
+        "debug": provider_field(typing.Any, default = None),
+        "interop_includes": provider_field(typing.Any, default = None),
+        "warnings_flags": provider_field(typing.Any, default = None),
+        "ocaml_compiler_flags": provider_field(typing.Any, default = None),  # passed to both ocamlc and ocamlopt, like dune's (flags)
+        "ocamlc_flags": provider_field(typing.Any, default = None),  # passed to ocamlc only, like dune's (ocamlc_flags)
+        "ocamlopt_flags": provider_field(typing.Any, default = None),  # passed to ocamlopt only, like dune's (ocamlopt_flags)
+        "runtime_dep_link_flags": provider_field(typing.Any, default = None),  # `ocaml_object` uses this to satisfy OCaml runtimes C link dependencies
+        "runtime_dep_link_extras": provider_field(typing.Any, default = None),  # `ocaml_object` uses this to satisfy OCaml runtimes C link dependencies
+    },
+)
+
+# Stores "platform"/flavor name used to resolve *platform_* arguments
+OCamlPlatformInfo = provider(
+    fields = {
+        "name": provider_field(typing.Any, default = None),
+    }
+)
+
+# A list of `OCamlLibraryInfo`s.
+OCamlLinkInfo = provider(
+    # Contains a list of OCamlLibraryInfo records
+    fields = {"info": provider_field(typing.Any, default = None)},
+)
+
+# A record of an OCaml library.
+OCamlLibraryInfo = record(
+    # The library target name: e.g. "`foo`"
+    name = str,
+    # The full library target: e.g. "`fbcode//...:foo`"
+    target = Label,
+    # .a (C archives e.g. `libfoo_stubs.a`)
+    c_libs = list[Artifact],
+    # .o (Native compiler produced stubs)
+    stbs_nat = list[Artifact],
+    # .o (Bytecode compiler produced stubs)
+    stbs_byt = list[Artifact],
+    # .cma (Bytecode compiler module archives e.g. `libfoo.cma`)
+    cmas = list[Artifact],
+    # .cmxa (Native compiler module archives e.g. `libfoo.cmxa`)
+    cmxas = list[Artifact],
+    # .cmi (Native compiled module interfaces)
+    cmis_nat = list[Artifact],
+    # .cmi (Bytecode compiled module interfaces)
+    cmis_byt = list[Artifact],
+    # .cmo (Bytecode compiled modules - bytecode)
+    cmos = list[Artifact],
+    # .cmx (Compiled modules - native)
+    cmxs = list[Artifact],
+    # .cmt (Native compiler produced typed abstract syntax trees)
+    cmts_nat = list[Artifact],
+    # .cmt (Bytecode compiler produced typed abstract syntax trees)
+    cmts_byt = list[Artifact],
+    # .cmti (Native compiler produced typed abstract syntax trees)
+    cmtis_nat = list[Artifact],
+    # .cmti (Bytecode compiler produced typed abstract syntax trees)
+    cmtis_byt = list[Artifact],
+    # Compile flags for native clients who use this library.
+    include_dirs_nat = list[cmd_args],
+    # Compile flags for bytecode clients who use this library.
+    include_dirs_byt = list[cmd_args],
+    # Native C libs (like `libthreadsnat.a` in the compiler's `threads` package)
+    native_c_libs = list[Artifact],
+    # Bytecode C libs (like `libthreads.a` in the compiler's `threads` package)
+    bytecode_c_libs = list[Artifact],
+)
+
+def merge_ocaml_link_infos(lis: list[OCamlLinkInfo]) -> OCamlLinkInfo:
+    return OCamlLinkInfo(info = dedupe(flatten([li.info for li in lis])))
+
+def project_expand(value: dict[str, list[Artifact]]):
+    return value["expand"]
+
+def project_ide(value: dict[str, list[Artifact]]):
+    return value["ide"]
+
+def project_bytecode(value: dict[str, list[Artifact]]):
+    return value["bytecode"]
+
+OtherOutputsTSet = transitive_set(
+    args_projections = {"bytecode": project_bytecode, "expand": project_expand, "ide": project_ide},
+)
+
+OtherOutputsInfo = provider(
+    fields = {"info": provider_field(typing.Any, default = None)},  # :OtherOutputsTSet
+)
+
+def merge_other_outputs_info(ctx: AnalysisContext, value: dict[str, list[Artifact]], infos: list[OtherOutputsInfo]) -> OtherOutputsInfo:
+    return OtherOutputsInfo(
+        info = ctx.actions.tset(
+            OtherOutputsTSet,
+            value = value,
+            children = [p.info for p in infos],
+        ),
+    )
diff --git a/buck2/prelude/os/BUCK b/buck2/prelude/os/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/os/BUCK
@@ -0,0 +1,149 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native  # Avoid warnings and auto-formatters
+
+# The short list of ubiquitous, mainstream operating systems:
+
+config_setting(
+    name = "linux",
+    constraint_values = [
+        "//os/constraints:os[linux]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "macos",
+    constraint_values = [
+        "//os/constraints:os[macos]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "windows",
+    constraint_values = [
+        "//os/constraints:os[windows]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+# Android
+
+config_setting(
+    name = "android",
+    constraint_values = [
+        "//os/constraints:os[android]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+prelude.constraint_setting(
+    name = "maybe_building_android_binary",
+    visibility = ["PUBLIC"],
+)
+
+prelude.constraint_value(
+    name = "building_android_binary",
+    constraint_setting = ":maybe_building_android_binary",
+    visibility = ["prelude//..."],
+)
+
+# Rest of Apple's operating systems.
+
+config_setting(
+    name = "iphoneos",
+    constraint_values = [
+        "//os/constraints:os[iphoneos]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "tvos",
+    constraint_values = [
+        "//os/constraints:os[tvos]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "watchos",
+    constraint_values = [
+        "//os/constraints:os[watchos]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+# Long tail but contemporarily relevant operating systems.
+# Whether a Tier 2 rustc target exists is approximately the right bar.
+
+config_setting(
+    name = "freebsd",
+    constraint_values = [
+        "//os/constraints:os[freebsd]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "fuchsia",
+    constraint_values = [
+        "//os/constraints:os[fuchsia]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "illumos",
+    constraint_values = [
+        "//os/constraints:os[illumos]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "netbsd",
+    constraint_values = [
+        "//os/constraints:os[netbsd]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "wasi",
+    constraint_values = [
+        "//os/constraints:os[wasi]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "linux-sgx",
+    constraint_values = [
+        "//os/constraints:os[linux]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+config_setting(
+    name = "linux-arm64",
+    constraint_values = [
+        "//cpu/constraints:cpu[arm64]",
+        "//os/constraints:os[linux]",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+# For platforms with no OS, like microcontrollers.
+config_setting(
+    name = "none",
+    constraint_values = [
+        "//os/constraints:os[none]",
+    ],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/os/constraints/BUCK b/buck2/prelude/os/constraints/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/os/constraints/BUCK
@@ -0,0 +1,41 @@
+load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+# Used by open source projects to support `prelude//`
+
+constraint_with_aliases(
+    name = "os",
+    aliases = {
+        "android": "android",
+        "freebsd": "freebsd",
+        "iphoneos": "iphoneos",
+        "linux": "linux",
+        "macos": "macos",
+        "none": "none",
+        "wasi": "wasi",
+        "watchos": "watchos",
+        "windows": "windows",
+    },
+    default = "unspecified",
+    values = [
+        "linux",
+        "macos",
+        "windows",
+        "android",
+        "iphoneos",
+        "tvos",
+        "watchos",
+        "freebsd",
+        "fuchsia",
+        "illumos",
+        "netbsd",
+        "wasi",
+        "none",
+        "unspecified",
+    ],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/os_lookup/defs.bzl b/buck2/prelude/os_lookup/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/os_lookup/defs.bzl
@@ -0,0 +1,43 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:core_rules.bzl", "PlatformExePlatform", "TargetCpuType")
+
+Os = enum("fat_mac_linux", "freebsd", "unknown", *PlatformExePlatform)
+
+ScriptLanguage = enum(
+    "sh",  # Unix shell script
+    "bat",  # Windows batch file
+)
+
+OsLookup = provider(
+    fields = {
+        "cpu": str | None,
+        "os": Os,
+        "script": ScriptLanguage,
+    }
+)
+
+def _os_lookup_impl(ctx: AnalysisContext):
+    return [
+        DefaultInfo(),
+        OsLookup(
+            cpu = ctx.attrs.cpu,
+            os = Os(ctx.attrs.os),
+            script = ScriptLanguage(ctx.attrs.script),
+        ),
+    ]
+
+os_lookup = rule(
+    impl = _os_lookup_impl,
+    attrs = {
+        "cpu": attrs.option(attrs.enum(TargetCpuType), default = None),
+        "os": attrs.enum(Os.values()),
+        "script": attrs.enum(ScriptLanguage.values()),
+    },
+)
diff --git a/buck2/prelude/os_lookup/targets/BUCK b/buck2/prelude/os_lookup/targets/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/os_lookup/targets/BUCK
@@ -0,0 +1,31 @@
+load("@prelude//os_lookup:defs.bzl", "os_lookup")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+os_lookup(
+    name = "os_lookup",
+    cpu = select({
+        "DEFAULT": None,
+        "config//cpu:arm64": "arm64",
+        "config//cpu:riscv64": "riscv64",
+        "config//cpu:x86_64": "x86_64",
+    }),
+    os = select({
+        # FIXME(JakobDegen): No default
+        "DEFAULT": "linux",
+        "config//os:linux": "linux",
+        "config//os:macos": "macos",
+        "config//os:windows": "windows",
+        # FIXME(JakobDegen): We assuem fat means fat mac linux, but that might not be true in the
+        # future.
+        "prelude//platforms:fat_platform_enabled": "fat_mac_linux",
+    }),
+    script = select({
+        "DEFAULT": "sh",
+        "config//os:windows": "bat",
+    }),
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/oss/CHANGELOG.md b/buck2/prelude/oss/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/oss/CHANGELOG.md
@@ -0,0 +1,3 @@
+# Buck2 Prelude
+
+- Initial version.
diff --git a/buck2/prelude/oss/CODE_OF_CONDUCT.md b/buck2/prelude/oss/CODE_OF_CONDUCT.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/oss/CODE_OF_CONDUCT.md
@@ -0,0 +1,45 @@
+# Open Source Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment include:
+
+Using welcoming and inclusive language
+Being respectful of differing viewpoints and experiences
+Gracefully accepting constructive criticism
+Focusing on what is best for the community
+Showing empathy towards other community members
+Examples of unacceptable behavior by participants include:
+
+The use of sexualized language or imagery and unwelcome sexual attention or advances
+Trolling, insulting/derogatory comments, and personal or political attacks
+Public or private harassment
+Publishing others’ private information, such as a physical or electronic address, without explicit permission
+Other conduct which could reasonably be considered inappropriate in a professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at opensource-conduct@fb.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
+
+[homepage]: https://www.contributor-covenant.org
diff --git a/buck2/prelude/oss/CONTRIBUTING.md b/buck2/prelude/oss/CONTRIBUTING.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/oss/CONTRIBUTING.md
@@ -0,0 +1,51 @@
+# Contributing to Buck2 Prelude
+
+This repository is a subset of <https://github.com/facebook/buck2>. You can
+contribute to either that repo, or this repo - changes will be mirrored to both.
+
+We want to make contributing to this project as easy and transparent as
+possible.
+
+## Our Development Process
+
+Buck2 Prelude is currently developed in Meta's internal repositories and
+then exported out to GitHub by a Meta team member; however, we invite you to
+submit pull requests as described below.
+
+## Pull Requests
+
+We actively welcome your pull requests.
+
+1. Fork the repo and create your branch from `main`.
+2. If you've added code that should be tested, add tests.
+3. If you've changed APIs, update the documentation.
+4. Ensure the test suite passes.
+5. Make sure your code lints.
+6. If you haven't already, complete the Contributor License Agreement ("CLA").
+
+## Contributor License Agreement ("CLA")
+
+In order to accept your pull request, we need you to submit a CLA. You only need
+to do this once to work on any of Meta's open source projects.
+
+Complete your CLA here: <https://code.facebook.com/cla>
+
+## Issues
+
+We use GitHub issues to track public bugs. Please ensure your description is
+clear and has sufficient instructions to be able to reproduce the issue.
+
+Meta has a [bounty program](https://bugbounty.meta.com/) for the safe
+disclosure of security bugs. In those cases, please go through the process
+outlined on that page and do not file a public issue.
+
+## Coding Style
+
+We use several Python formatters.
+
+## License
+
+By contributing to Buck2 Prelude, you agree that your contributions will be
+licensed under both the [LICENSE-MIT](LICENSE-MIT) and
+[LICENSE-APACHE](LICENSE-APACHE) files in the root directory of this source
+tree.
diff --git a/buck2/prelude/oss/LICENSE-APACHE b/buck2/prelude/oss/LICENSE-APACHE
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/oss/LICENSE-APACHE
@@ -0,0 +1,201 @@
+Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
diff --git a/buck2/prelude/oss/LICENSE-MIT b/buck2/prelude/oss/LICENSE-MIT
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/oss/LICENSE-MIT
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) Meta Platforms, Inc. and affiliates.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/buck2/prelude/oss/README.md b/buck2/prelude/oss/README.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/oss/README.md
@@ -0,0 +1,16 @@
+# Buck2 Prelude
+
+This repo contains a copy of the Buck2 Prelude, which is often included as a
+submodule with a Buck2 project. To obtain a copy of this repo, and set up other
+details of a Buck2, you should usually run `buck2 init --git`. Most information
+can be found on the main
+[Buck2 GitHub project](https://github.com/facebook/buck2).
+
+Pull requests and issues should be raised at
+[facebook/buck2](https://github.com/facebook/buck2) as that project is more
+closely monitored and contains CI checks.
+
+## License
+
+Buck2 Prelude is both MIT and Apache License, Version 2.0 licensed, as found in
+the [LICENSE-MIT](LICENSE-MIT) and [LICENSE-APACHE](LICENSE-APACHE) files.
diff --git a/buck2/prelude/oss/pull_request_template.md b/buck2/prelude/oss/pull_request_template.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/oss/pull_request_template.md
@@ -0,0 +1,7 @@
+IMPORTANT: Please don't raise pull requests here, but at
+[facebook/buck2](https://github.com/facebook/buck2/pulls).
+
+The [`prelude`](https://github.com/facebook/buck2/tree/main/prelude) directory
+is a mirror of this repo, but that repo also features CI tests and is more
+actively monitored. Any PR's landing there will automatically show up here at
+the same time.
diff --git a/buck2/prelude/paths.bzl b/buck2/prelude/paths.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/paths.bzl
@@ -0,0 +1,289 @@
+# Copyright 2017 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.
+
+# @lint-ignore-every LICENSELINT
+
+"""Skylib module containing file path manipulation functions.
+
+NOTE: The functions in this module currently only support paths with Unix-style
+path separators (forward slash, "/"); they do not handle Windows-style paths
+with backslash separators or drive letters.
+
+The corresponding unittest file is: fbcode/buck2/tests/targets/starlib/paths_tests.bzl
+"""
+
+def _basename(p: str) -> str:
+    """Returns the basename (i.e., the file portion) of a path.
+
+    Note that if `p` ends with a slash, this function returns an empty string.
+    This matches the behavior of Python's `os.path.basename`, but differs from
+    the Unix `basename` command (which would return the path segment preceding
+    the final slash).
+
+    Args:
+      p: The path whose basename should be returned.
+    Returns:
+      The basename of the path, which includes the extension.
+    """
+    return p.rpartition("/")[-1]
+
+def _dirname(p: str) -> str:
+    """Returns the dirname of a path.
+
+    The dirname is the portion of `p` up to but not including the file portion
+    (i.e., the basename). Any slashes immediately preceding the basename are not
+    included, unless omitting them would make the dirname empty.
+
+    Args:
+      p: The path whose dirname should be returned.
+    Returns:
+      The dirname of the path.
+    """
+    prefix, sep, _ = p.rpartition("/")
+    if not prefix:
+        return sep
+    else:
+        # If there are multiple consecutive slashes, strip them all out as Python's
+        # os.path.dirname does.
+        return prefix.rstrip("/")
+
+def _is_absolute(path: str) -> bool:
+    """Returns `True` if `path` is an absolute path.
+
+    Args:
+      path: A path (which is a string).
+    Returns:
+      `True` if `path` is an absolute path.
+    """
+    return path.startswith("/")
+
+def _join(path: str, *others) -> str:
+    """Joins one or more path components intelligently.
+
+    This function mimics the behavior of Python's `os.path.join` function on POSIX
+    platform. It returns the concatenation of `path` and any members of `others`,
+    inserting directory separators before each component except the first. The
+    separator is not inserted if the path up until that point is either empty or
+    already ends in a separator.
+
+    If any component is an absolute path, all previous components are discarded.
+
+    Args:
+      path: A path segment.
+      *others: Additional path segments.
+    Returns:
+      A string containing the joined paths.
+    """
+    result = path
+
+    for p in others:
+        if _is_absolute(p):
+            result = p
+        elif not result or result.endswith("/"):
+            result += p
+        else:
+            result += "/" + p
+
+    return result
+
+def _normalize(path: str) -> str:
+    """Normalizes a path, eliminating double slashes and other redundant segments.
+
+    This function mimics the behavior of Python's `os.path.normpath` function on
+    POSIX platforms; specifically:
+
+    - If the entire path is empty, "." is returned.
+    - All "." segments are removed, unless the path consists solely of a single
+      "." segment.
+    - Trailing slashes are removed, unless the path consists solely of slashes.
+    - ".." segments are removed as long as there are corresponding segments
+      earlier in the path to remove; otherwise, they are retained as leading ".."
+      segments.
+    - Single and double leading slashes are preserved, but three or more leading
+      slashes are collapsed into a single leading slash.
+    - Multiple adjacent internal slashes are collapsed into a single slash.
+
+    Args:
+      path: A path.
+    Returns:
+      The normalized path.
+    """
+    if not path:
+        return "."
+
+    if path.startswith("//") and not path.startswith("///"):
+        initial_slashes = 2
+    elif path.startswith("/"):
+        initial_slashes = 1
+    else:
+        initial_slashes = 0
+    is_relative = initial_slashes == 0
+
+    components = path.split("/")
+    new_components = []
+
+    for component in components:
+        if component in ("", "."):
+            continue
+        if component == "..":
+            if new_components and new_components[-1] != "..":
+                # Only pop the last segment if it isn't another "..".
+                new_components.pop()
+            elif is_relative:
+                # Preserve leading ".." segments for relative paths.
+                new_components.append(component)
+        else:
+            new_components.append(component)
+
+    path = "/".join(new_components)
+    if not is_relative:
+        path = ("/" * initial_slashes) + path
+
+    return path or "."
+
+def _relativize(path: str, start: str) -> str:
+    """Returns the portion of `path` that is relative to `start`.
+
+    Because we do not have access to the underlying file system, this
+    implementation differs slightly from Python's `os.path.relpath` in that it
+    will fail if `path` is not beneath `start` (rather than use parent segments to
+    walk up to the common file system root).
+
+    Relativizing paths that start with parent directory references is not allowed.
+
+    Args:
+      path: The path to relativize.
+      start: The ancestor path against which to relativize.
+    Returns:
+      The portion of `path` that is relative to `start` or empty string if they
+      are identical.
+    """
+    if path == start:
+        return ""
+    segments = _normalize(path).split("/")
+    start_segments = _normalize(start).split("/")
+    if start_segments == ["."]:
+        start_segments = []
+    start_length = len(start_segments)
+
+    if path.startswith("..") or start.startswith(".."):
+        fail("Cannot relativize paths above the current (unknown) directory")
+
+    if path.startswith("/") != start.startswith("/") or len(segments) < start_length:
+        fail("Path '%s' is not beneath '%s'" % (path, start))
+
+    for ancestor_segment, segment in zip(start_segments, segments):
+        if ancestor_segment != segment:
+            fail("Path '%s' is not beneath '%s'" % (path, start))
+
+    length = len(segments) - start_length
+    result_segments = segments[-length:]
+    return "/".join(result_segments)
+
+def _replace_extension(p: str, new_extension: str) -> str:
+    """Replaces the extension of the file at the end of a path.
+
+    If the path has no extension, the new extension is added to it.
+
+    Args:
+      p: The path whose extension should be replaced.
+      new_extension: The new extension for the file. The new extension should
+          begin with a dot if you want the new filename to have one.
+    Returns:
+      The path with the extension replaced (or added, if it did not have one).
+    """
+    return _split_extension(p)[0] + new_extension
+
+def _split_extension(p: str) -> (str, str):
+    """Splits the path `p` into a tuple containing the root and extension.
+
+    Leading periods on the basename are ignored, so
+    `path.split_extension(".bashrc")` returns `(".bashrc", "")`.
+
+    Args:
+      p: The path whose root and extension should be split.
+    Returns:
+      A tuple `(root, ext)` such that the root is the path without the file
+      extension, and `ext` is the file extension (which, if non-empty, contains
+      the leading dot). The returned tuple always satisfies the relationship
+      `root + ext == p`.
+    """
+    b = _basename(p)
+    last_dot_in_basename = b.rfind(".")
+
+    # If there is no dot or the only dot in the basename is at the front, then
+    # there is no extension.
+    if last_dot_in_basename <= 0:
+        return (p, "")
+
+    dot_distance_from_end = len(b) - last_dot_in_basename
+    return (p[:-dot_distance_from_end], p[-dot_distance_from_end:])
+
+def _strip_suffix(a: str, b: str) -> [str, None]:
+    """Strip suffix `b` from path `a`, returning the resulting path.
+
+    Args:
+      a: The path which will be stripped of the given suffix.
+      b: The suffix path to strip.
+    Returns:
+      If `a` ends with `b`, returning the result of stripping `b`.  Otherwise,
+      return `None`.
+    """
+
+    # If path b is longer than a by char count, then it can't be a suffix.
+    # (should we assume normalized paths?).
+    if len(b) > len(a):
+        return None
+
+    # Split paths into lists of path components.
+    pa = a.split("/")
+    pb = b.split("/")
+
+    # If path b has more components than a, then it can't be a suffix
+    # (should we assume normalized paths?).
+    if len(pb) > len(pa):
+        return None
+
+    # If any path component of the suffix isn't in the path, return `None`.
+    for idx in range(len(pb)):
+        if pb[len(pb) - 1 - idx] != pa[len(pa) - 1 - idx]:
+            return None
+
+    # Return the original path, minus the suffix.
+    return "/".join(pa[: len(pa) - len(pb)])
+
+def _starts_with(path: str, prefix: str) -> bool:
+    """Returns `True` if `prefix` is a prefix path of `path`.
+
+    Args:
+      path: A path (which is a string).
+      prefix: A prefix path (which is a string).
+    Returns:
+      `True` if `prefix` is a prefix path of `path`.
+    """
+
+    return path == prefix or path.startswith(prefix + "/")
+
+paths = struct(
+    basename = _basename,
+    dirname = _dirname,
+    is_absolute = _is_absolute,
+    join = _join,
+    normalize = _normalize,
+    relativize = _relativize,
+    replace_extension = _replace_extension,
+    split_extension = _split_extension,
+    starts_with = _starts_with,
+    strip_suffix = _strip_suffix,
+)
diff --git a/buck2/prelude/platforms/BUCK b/buck2/prelude/platforms/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/platforms/BUCK
@@ -0,0 +1,90 @@
+# Used by open source projects to provide a simple platform setting
+
+load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load(":defs.bzl", "execution_platform", "host_configuration")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+execution_platform(
+    name = "default",
+    cpu_configuration = host_configuration.cpu,
+    os_configuration = host_configuration.os,
+    use_windows_path_separators = host_info().os.is_windows,
+    visibility = ["PUBLIC"],
+)
+
+prelude.constraint_setting(
+    name = "runs_remote",
+)
+
+prelude.constraint_value(
+    name = "may_run_remote",
+    constraint_setting = ":runs_remote",
+    visibility = ["PUBLIC"],
+)
+
+constraint_with_aliases(
+    name = "runs_local",
+    aliases = {
+        "may_run_local": "may_run_local",
+    },
+    default = "unspecified",
+    values = ["may_run_local", "unspecified"],
+    visibility = ["PUBLIC"],
+)
+
+prelude.constraint_setting(
+    name = "runs_only",
+)
+
+prelude.constraint_value(
+    name = "runs_only_local",
+    constraint_setting = ":runs_only",
+    visibility = ["PUBLIC"],
+)
+
+prelude.constraint_value(
+    name = "runs_only_remote",
+    constraint_setting = ":runs_only",
+    visibility = ["PUBLIC"],
+)
+
+prelude.constraint_setting(
+    name = "fat_platform_marker",
+)
+
+prelude.constraint_value(
+    name = "fat_platform_enabled",
+    constraint_setting = ":fat_platform_marker",
+    visibility = ["PUBLIC"],
+)
+
+# This is mostly here for a rule type to add a dependency on it to mark all
+# instances of that rule type as incompatible with a fat platform. Ideally,
+# toolchains could affect the target compatibility of their users directly but
+# toolchains are currently all exec deps and so cannot do that. We'd like
+# buck2 to support a form of dep that inherited its users execution platform
+# so that toolchains could basically get visibility and affect both target and
+# execution configuration, but that's not implemented yet.
+export_file(
+    name = "fat_platform_incompatible",
+    src = "BUCK",
+    has_content_based_path = True,
+    target_compatible_with = select({
+        ":fat_platform_enabled": ["config//:none"],
+        "DEFAULT": [],
+    }),
+    visibility = ["PUBLIC"],
+)
+
+# Empty platform containing no constraint values.
+platform(
+    name = "void",
+    constraint_values = [],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/platforms/apple/base.bzl b/buck2/prelude/platforms/apple/base.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/platforms/apple/base.bzl
@@ -0,0 +1,94 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:is_buck2.bzl", "is_buck2") # @oss-enable
+load(
+    "@prelude//platforms/apple:build_mode.bzl",
+    "APPLE_BUILD_MODES",
+      "CONSTRAINT_PACKAGE", # @oss-enable
+    "get_build_mode",
+)
+load(
+    "@prelude//platforms/apple:constants.bzl",
+    "appletv_platforms",
+    "ios_platforms",
+    "mac_catalyst_platforms",
+    "mac_platforms",
+    "watch_platforms",
+)
+# @oss-disable[end= ]: load("@prelude//platforms/apple/meta_only:build_mode.bzl", _get_build_mode_constraints_map = "get_build_mode_constraints_map")
+
+def get_build_mode_constraints_map(use_whatsapp_build_modes):
+    return {build_mode: ["{}:{}".format(CONSTRAINT_PACKAGE, build_mode)] for build_mode in APPLE_BUILD_MODES} # @oss-enable
+    # @oss-disable[end= ]: return _get_build_mode_constraints_map(use_whatsapp_build_modes)
+
+_MOBILE_PLATFORMS = [
+    appletv_platforms.APPLETVOS_ARM64,
+    appletv_platforms.APPLETVSIMULATOR_ARM64,
+    ios_platforms.IPHONEOS_ARM64,
+    ios_platforms.IPHONEOS_ARM64E,
+    ios_platforms.IPHONESIMULATOR_ARM64,
+    ios_platforms.IPHONESIMULATOR_X86_64,
+    watch_platforms.WATCHOS_ARM64,
+    watch_platforms.WATCHOS_ARM64_32,
+    watch_platforms.WATCHSIMULATOR_ARM64,
+    watch_platforms.WATCHSIMULATOR_X86_64,
+]
+
+_MAC_PLATFORMS = [
+    mac_platforms.MACOS_ARM64,
+    mac_platforms.MACOS_X86_64,
+    mac_platforms.MACOS_UNIVERSAL,
+    mac_catalyst_platforms.MACCATALYST_ARM64,
+    mac_catalyst_platforms.MACCATALYST_X86_64,
+]
+
+# TODO: Drop the platform_rule when we're not longer attempting to support buck1.
+def apple_generated_platforms(
+    name, constraint_values, deps, platform_rule, platform = None, supported_build_modes = APPLE_BUILD_MODES, use_whatsapp_build_modes = False
+):
+    # By convention, the cxx.default_platform is typically the same as the platform being defined.
+    # This is not the case for all watch platforms, so provide an override.
+    platform = platform if platform else name
+    build_mode_constraints_map = get_build_mode_constraints_map(use_whatsapp_build_modes)
+    if is_mobile_platform(platform) or is_buck2_mac_platform(platform):
+        for build_mode in supported_build_modes:
+            platform_rule(
+                name = _get_generated_name(name, platform, build_mode),
+                constraint_values = constraint_values + build_mode_constraints_map[build_mode],
+                visibility = ["PUBLIC"],
+                deps = deps,
+            )
+
+    # Create a platform without the build mode to support backwards compatibility of hardcoded platforms
+    # and with buck1 cxx platform setup.
+    # TODO(chatatap): Look to remove all hardcoded references and get rid of these
+    platform_rule(
+        name = name,
+        constraint_values = constraint_values,
+        visibility = ["PUBLIC"],
+        deps = deps,
+    )
+
+def apple_build_mode_backed_platform(name, platform, build_mode = None):
+    build_mode = get_build_mode() if build_mode == None else build_mode
+    return _get_generated_name(name, platform, build_mode)
+
+def is_mobile_platform(platform):
+    # These builds modes are primarily used in mobile code. MacOS builds in fbcode/arvr use different
+    # modes to represent dev/opt variants.
+    return platform in _MOBILE_PLATFORMS
+
+def is_buck2_mac_platform(platform):
+    return platform in _MAC_PLATFORMS
+
+def _get_generated_name(name, platform, build_mode):
+    if is_mobile_platform(platform) or is_buck2_mac_platform(platform):
+        return "{}-{}".format(name, build_mode)
+    else:
+        return name
diff --git a/buck2/prelude/platforms/apple/build_mode.bzl b/buck2/prelude/platforms/apple/build_mode.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/platforms/apple/build_mode.bzl
@@ -0,0 +1,50 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//platforms/apple/meta_only:build_mode.bzl",
+    _APPLE_BUILD_MODES = "APPLE_BUILD_MODES",
+    _BUILD_MODE = "BUILD_MODE",
+    _REMAPPED_BUILD_MODES = "REMAPPED_BUILD_MODES",
+    _get_build_mode = "get_build_mode",
+    _get_build_mode_debug = "get_build_mode_debug",
+    _get_build_mode_release = "get_build_mode_release",
+# @oss-disable[end= ]: )
+
+BUILD_MODE_DEBUG = "debug" # @oss-enable
+BUILD_MODE_PROFILE = "profile" # @oss-enable
+BUILD_MODE_RELEASE = "release" # @oss-enable
+
+APPLE_BUILD_MODES = [BUILD_MODE_DEBUG, BUILD_MODE_PROFILE, BUILD_MODE_RELEASE] # @oss-enable
+# @oss-disable[end= ]: APPLE_BUILD_MODES = _APPLE_BUILD_MODES
+
+# 1:1 mapping of build mode to canonical (supported/default) apple build modes
+REMAPPED_BUILD_MODES = {} # @oss-enable
+# @oss-disable[end= ]: REMAPPED_BUILD_MODES = _REMAPPED_BUILD_MODES
+
+BUILD_MODE = struct( # @oss-enable
+    DEBUG = BUILD_MODE_DEBUG, # @oss-enable
+    PROFILE = BUILD_MODE_PROFILE, # @oss-enable
+    RELEASE = BUILD_MODE_RELEASE, # @oss-enable
+) # @oss-enable
+# @oss-disable[end= ]: BUILD_MODE = _BUILD_MODE
+
+CONSTRAINT_PACKAGE = "prelude//platforms/apple/constraints" # @oss-enable
+# @oss-disable[end= ]: CONSTRAINT_PACKAGE = "ovr_config//build_mode/apple/constraints"
+
+def get_build_mode():
+    return read_root_config("apple", "build_mode", BUILD_MODE_DEBUG) # @oss-enable
+    # @oss-disable[end= ]: return _get_build_mode()
+
+def get_build_mode_debug():
+    return BUILD_MODE.DEBUG # @oss-enable
+    # @oss-disable[end= ]: return _get_build_mode_debug()
+
+def get_build_mode_release():
+    return BUILD_MODE.RELEASE # @oss-enable
+    # @oss-disable[end= ]: return _get_build_mode_release()
diff --git a/buck2/prelude/platforms/apple/constants.bzl b/buck2/prelude/platforms/apple/constants.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/platforms/apple/constants.bzl
@@ -0,0 +1,114 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# These are identifiers used in defining Apple platforms for configuring apple_* rules.
+
+APPLE = "Apple"
+
+# Apple SDK Definitions
+APPLETVOS = "appletvos"
+
+IOS = "ios"
+
+MACOSX = "macosx"
+
+WATCHOS = "watchos"
+
+VISIONOS = "visionos"
+
+# Apple TV Platforms/Flavors
+
+APPLETVOS_ARM64 = "appletvos-arm64"
+
+APPLETVSIMULATOR_ARM64 = "appletvsimulator-arm64"
+
+# iOS Platforms/Flavors
+
+IPHONEOS_ARM64 = "iphoneos-arm64"
+
+IPHONEOS_ARM64E = "iphoneos-arm64e"
+
+IPHONESIMULATOR_ARM64 = "iphonesimulator-arm64"
+
+IPHONESIMULATOR_X86_64 = "iphonesimulator-x86_64"
+
+# Mac Catalyst Platforms/Flavors
+
+MACCATALYST_ARM64 = "maccatalyst-arm64"
+
+MACCATALYST_X86_64 = "maccatalyst-x86_64"
+
+# Mac OS X Platforms/Flavors
+
+MACOS_ARM64 = "macosx-arm64"
+
+MACOS_X86_64 = "macosx-x86_64"
+
+MACOS_UNIVERSAL = "macosx-universal"
+
+# Watch OS Platforms/Flavors
+
+WATCHOS_ARM64 = "watchos-arm64"
+
+WATCHOS_ARM64_32 = "watchos-arm64_32"
+
+WATCHSIMULATOR_ARM64 = "watchsimulator-arm64"
+
+WATCHSIMULATOR_X86_64 = "watchsimulator-x86_64"
+
+# Vision OS Platforms/Flavors
+VISIONOS_ARM64 = "visionos-arm64"
+
+VISIONSIMULATOR_ARM64 = "visionsimulator-arm64"
+
+apple_sdks = struct(
+    IOS = IOS,
+    WATCHOS = WATCHOS,
+    MACOSX = MACOSX,
+    APPLETVOS = APPLETVOS,
+    VISIONOS = VISIONOS,
+)
+
+ALL_APPLE_SDKS = tuple(
+    [getattr(apple_sdks, field) for field in dir(apple_sdks)]
+)  # convert the `apple_sdks` struct into a tuple (taking the values, not the keys)
+
+appletv_platforms = struct(
+    APPLETVOS_ARM64 = APPLETVOS_ARM64,
+    APPLETVSIMULATOR_ARM64 = APPLETVSIMULATOR_ARM64,
+)
+
+ios_platforms = struct(
+    IPHONEOS_ARM64 = IPHONEOS_ARM64,
+    IPHONEOS_ARM64E = IPHONEOS_ARM64E,
+    IPHONESIMULATOR_ARM64 = IPHONESIMULATOR_ARM64,
+    IPHONESIMULATOR_X86_64 = IPHONESIMULATOR_X86_64,
+)
+
+mac_catalyst_platforms = struct(
+    MACCATALYST_ARM64 = MACCATALYST_ARM64,
+    MACCATALYST_X86_64 = MACCATALYST_X86_64,
+)
+
+mac_platforms = struct(
+    MACOS_ARM64 = MACOS_ARM64,
+    MACOS_X86_64 = MACOS_X86_64,
+    MACOS_UNIVERSAL = MACOS_UNIVERSAL,
+)
+
+watch_platforms = struct(
+    WATCHOS_ARM64 = WATCHOS_ARM64,
+    WATCHOS_ARM64_32 = WATCHOS_ARM64_32,
+    WATCHSIMULATOR_ARM64 = WATCHSIMULATOR_ARM64,
+    WATCHSIMULATOR_X86_64 = WATCHSIMULATOR_X86_64,
+)
+
+vision_platforms = struct(
+    VISIONOS_ARM64 = VISIONOS_ARM64,
+    VISIONSIMULATOR_ARM64 = VISIONSIMULATOR_ARM64,
+)
diff --git a/buck2/prelude/platforms/apple/platforms.bzl b/buck2/prelude/platforms/apple/platforms.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/platforms/apple/platforms.bzl
@@ -0,0 +1,295 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//apple:apple_platforms.bzl", "APPLE_PLATFORMS_KEY")
+load("@prelude//platforms/apple:base.bzl", "apple_build_mode_backed_platform", "get_build_mode_constraints_map", "is_buck2_mac_platform", "is_mobile_platform")
+load(
+    "@prelude//platforms/apple:build_mode.bzl",
+    "APPLE_BUILD_MODES",
+    "REMAPPED_BUILD_MODES",
+    "get_build_mode",
+    "get_build_mode_debug",
+)
+load(
+    "@prelude//platforms/apple:constants.bzl",
+    "IOS",
+    "appletv_platforms",
+    "ios_platforms",
+    "mac_catalyst_platforms",
+    "mac_platforms",
+    "watch_platforms",
+)
+load("@prelude//platforms/apple:platforms_map.bzl", "APPLE_PLATFORMS_MAP", "APPLE_SDK_DEFAULT_PLATFORM_MAP")
+load("@prelude//utils:buckconfig.bzl", "read")
+
+_SUPPORTED_IOS_PLATFORMS = [
+    ios_platforms.IPHONEOS_ARM64,
+    ios_platforms.IPHONESIMULATOR_ARM64,
+    ios_platforms.IPHONESIMULATOR_X86_64,
+]
+
+_SUPPORTED_APPLETV_PLATFORMS = [
+    appletv_platforms.APPLETVOS_ARM64,
+    appletv_platforms.APPLETVSIMULATOR_ARM64,
+]
+
+_SUPPORTED_MACOS_PLATFORMS = [
+    mac_platforms.MACOS_ARM64,
+    mac_platforms.MACOS_X86_64,
+]
+
+_SUPPORTED_MAC_CATALYST_PLATFORMS = [
+    mac_catalyst_platforms.MACCATALYST_ARM64,
+    mac_catalyst_platforms.MACCATALYST_X86_64,
+]
+
+_SUPPORTED_WATCHOS_PLATFORMS = [
+    watch_platforms.WATCHOS_ARM64,
+    watch_platforms.WATCHOS_ARM64_32,
+    watch_platforms.WATCHSIMULATOR_ARM64,
+    watch_platforms.WATCHSIMULATOR_X86_64,
+]
+
+_ANALYSIS_CONSTRAINTS = ["ovr_config//bitcode/constraints:bitcode_mode[bitcode]"]
+_DEFAULT_ANALYSIS_IOS_PLATFORM = ios_platforms.IPHONEOS_ARM64
+_DEFAULT_ANALYSIS_MACOS_PLATFORM = mac_platforms.MACOS_ARM64
+_DEFAULT_ANALYSIS_WATCHOS_PLATFORM = watch_platforms.WATCHOS_ARM64
+_DEFAULT_ANALYSIS_APPLETVOS_PLATFORM = appletv_platforms.APPLETVOS_ARM64
+
+DEFAULT_SUPPORTED_CXX_PLATFORMS = _SUPPORTED_IOS_PLATFORMS
+
+INVERSE_REMAPPED_BUILD_MODES = {v: k for k, v in REMAPPED_BUILD_MODES.items()}
+
+def apple_target_platforms(
+    base_name: str,
+    platform_rule,
+    constraint_values = None,  # Constraint values added to all generated platforms
+    visibility = None,
+    deps = None,
+    cxx_platforms_constraint_values = None,  # Must be a map of a supported cxx platform to a list of constraint values
+    build_mode_constraint_values = None,  # Must be a map of a supported build mode to a list of constraint values
+    generate_base_platform = True,  # Whether to generate a base platform
+    add_config_based_platforms = True,  # Whether to add the configured cxx platform family when it is otherwise unsupported
+    use_whatsapp_build_modes = False,
+    supported_cxx_platforms = DEFAULT_SUPPORTED_CXX_PLATFORMS,  # Cxx platforms to generate platforms for
+    supported_build_modes = APPLE_BUILD_MODES,
+) -> None:  # Build modes to generate platforms for
+    """Define architecture and sdk specific platforms alongside the base platform."""
+
+    # HACK: Apps shouldn't be generating platforms for cxx_platforms they don't support. However, to support cases where other apps
+    # depend on shared libraries that don't generate particular platforms, and set a cxx.default_platform on the command line, we need
+    # to make the graph parseable and generate the missing target platforms. They will never be used, but need to exist in the config
+    # backed world.
+    config_based_platform = read("cxx", "default_platform")
+    if add_config_based_platforms and config_based_platform != None and config_based_platform not in supported_cxx_platforms:
+        supported_cxx_platforms = list(supported_cxx_platforms)
+        for platform_family in [
+            _SUPPORTED_MACOS_PLATFORMS,
+            _SUPPORTED_MAC_CATALYST_PLATFORMS,
+            _SUPPORTED_IOS_PLATFORMS,
+            _SUPPORTED_WATCHOS_PLATFORMS,
+            _SUPPORTED_APPLETV_PLATFORMS,
+        ]:
+            if config_based_platform in platform_family:
+                for p in platform_family:
+                    if p not in supported_cxx_platforms:
+                        supported_cxx_platforms.append(p)
+
+    # Form defaults
+    constraint_values = constraint_values or []
+    cxx_platforms_constraint_values = cxx_platforms_constraint_values or {}
+    build_mode_constraint_values = build_mode_constraint_values or {}
+    visibility = visibility or ["PUBLIC"]
+    deps = deps or []
+
+    _validate_cxx_platforms_constraint_values(base_name, cxx_platforms_constraint_values, supported_cxx_platforms)
+    _validate_build_mode_constraint_values(base_name, build_mode_constraint_values, supported_build_modes)
+
+    # Define the generated platforms
+    build_mode_constraints_map = get_build_mode_constraints_map(use_whatsapp_build_modes)
+    for platform in supported_cxx_platforms:
+        platform_dep = _get_base_target_platform_for_platform(platform)
+        cxx_platform_constraints = cxx_platforms_constraint_values.get(platform, [])
+        if is_mobile_platform(platform) or is_buck2_mac_platform(platform):
+            for build_mode in supported_build_modes:
+                build_mode_constraints = build_mode_constraint_values.get(build_mode, []) + build_mode_constraints_map[build_mode]
+                _define_platform(
+                    base_name,
+                    platform,
+                    build_mode,
+                    constraint_values + cxx_platform_constraints + build_mode_constraints,
+                    visibility,
+                    deps + [platform_dep],
+                    platform_rule,
+                )
+        else:
+            _define_platform(
+                base_name,
+                platform,
+                None,
+                constraint_values + cxx_platform_constraints,
+                visibility,
+                deps + [platform_dep],
+                platform_rule,
+            )
+
+    # Define the base platform in case it is needed (example: to be a dep of another platform)
+    if generate_base_platform:
+        platform_rule(
+            name = base_name,
+            constraint_values = constraint_values,
+            visibility = visibility,
+            deps = deps,
+        )
+
+        analysis_platform = _get_analysis_platform_for_supported_platforms(supported_cxx_platforms)
+        analysis_platform_dep = _get_base_target_platform_for_platform(analysis_platform)
+        analysis_platform_build_mode_constraints = build_mode_constraint_values.get(get_build_mode_debug(), [])
+
+        platform_rule(
+            name = base_name + "-analysis",
+            constraint_values = constraint_values + analysis_platform_build_mode_constraints + _ANALYSIS_CONSTRAINTS,
+            visibility = ["PUBLIC"],
+            deps = deps + [analysis_platform_dep],
+        )
+
+def config_backed_apple_target_platform(target_platform = None, platform = None, build_mode = None, supported_build_modes = None) -> str | None:
+    platform = _get_default_platform() if platform == None else platform
+
+    build_mode = get_build_mode() if build_mode == None else build_mode
+    supported_build_modes = APPLE_BUILD_MODES if supported_build_modes == None else supported_build_modes
+    if build_mode not in supported_build_modes:
+        # If build_mode is an unsupported build mode, attempt to map it to a supported one using the inverse map
+        build_mode = INVERSE_REMAPPED_BUILD_MODES.get(build_mode, build_mode)
+
+    if target_platform == None:
+        return get_default_target_platform_for_platform(platform)
+
+    return _get_generated_name(target_platform, platform, build_mode)
+
+def get_default_target_platform_for_platform(sdk_arch) -> str | None:
+    data = APPLE_PLATFORMS_MAP.get(sdk_arch)
+    if data != None:
+        return data.target_platform
+
+    return None
+
+def set_apple_platforms(
+    platform: str | Select, base_config_backed_target_platform: str | None, kwargs: dict[str, typing.Any], supported_build_modes = None
+) -> dict[str, typing.Any]:
+    def get_supported_platforms() -> list[str] | None:
+        if platform in _SUPPORTED_IOS_PLATFORMS:
+            return _SUPPORTED_IOS_PLATFORMS
+        elif platform in _SUPPORTED_MACOS_PLATFORMS:
+            return _SUPPORTED_MACOS_PLATFORMS
+        elif platform in _SUPPORTED_MAC_CATALYST_PLATFORMS:
+            return _SUPPORTED_MAC_CATALYST_PLATFORMS
+        elif platform in _SUPPORTED_WATCHOS_PLATFORMS:
+            return _SUPPORTED_WATCHOS_PLATFORMS
+        elif platform in _SUPPORTED_APPLETV_PLATFORMS:
+            return _SUPPORTED_APPLETV_PLATFORMS
+        else:
+            return None
+
+    supported_build_modes = APPLE_BUILD_MODES if supported_build_modes == None else supported_build_modes
+
+    supported_platforms = get_supported_platforms()
+    if not supported_platforms:
+        return kwargs
+
+    # If we've already defined the apple platforms, we can avoid having to process them again.
+    if APPLE_PLATFORMS_KEY in kwargs:
+        return kwargs
+
+    apple_platforms = {}
+    for platform in supported_platforms:
+        for build_mode in supported_build_modes:
+            identifier = "{}-{}".format(platform, build_mode)
+            if base_config_backed_target_platform:
+                apple_platforms[identifier] = config_backed_apple_target_platform(base_config_backed_target_platform, platform, build_mode)
+            else:
+                base_target_platform = _get_base_target_platform_for_platform(platform)
+                if not base_target_platform:
+                    fail("A valid base target platform is required!")
+                apple_platforms[identifier] = apple_build_mode_backed_platform(base_target_platform, platform, build_mode)
+
+    kwargs[APPLE_PLATFORMS_KEY] = apple_platforms
+
+    return kwargs
+
+def _get_generated_name(base_name, platform, build_mode) -> str:
+    platform_and_build_mode_name = apple_build_mode_backed_platform(platform, platform, build_mode)
+    return "{}-{}".format(base_name, platform_and_build_mode_name)
+
+def _get_default_platform() -> str:
+    platform = read("cxx", "default_platform")
+    return platform if platform != None else APPLE_SDK_DEFAULT_PLATFORM_MAP.get(IOS)
+
+def _define_platform(base_name, platform, build_mode, constraint_values, visibility, deps, platform_rule) -> None:
+    platform_rule(
+        name = _get_generated_name(base_name, platform, build_mode),
+        constraint_values = constraint_values,
+        visibility = visibility,
+        deps = deps,
+    )
+
+def _get_base_target_platform_for_platform(sdk_arch) -> str | None:
+    data = APPLE_PLATFORMS_MAP.get(sdk_arch)
+    if data != None:
+        return data.base_target_platform
+
+    return None
+
+def _get_analysis_platform_for_supported_platforms(supported_cxx_platforms) -> str:
+    # For determining the platform deps to use for the base platform, we inspect the supported
+    # cxx platforms, giving precedence to iOS platforms.
+    for platform in _SUPPORTED_IOS_PLATFORMS:
+        if platform in supported_cxx_platforms:
+            return _DEFAULT_ANALYSIS_IOS_PLATFORM
+
+    for platform in _SUPPORTED_MACOS_PLATFORMS:
+        if platform in supported_cxx_platforms:
+            return _DEFAULT_ANALYSIS_MACOS_PLATFORM
+
+    for platform in _SUPPORTED_WATCHOS_PLATFORMS:
+        if platform in supported_cxx_platforms:
+            return _DEFAULT_ANALYSIS_WATCHOS_PLATFORM
+
+    for platform in _SUPPORTED_APPLETV_PLATFORMS:
+        if platform in supported_cxx_platforms:
+            return _DEFAULT_ANALYSIS_APPLETVOS_PLATFORM
+
+    return _DEFAULT_ANALYSIS_IOS_PLATFORM
+
+def _validate_cxx_platforms_constraint_values(base_name, cxx_platforms_constraint_values, supported_cxx_platforms) -> None:
+    if type(cxx_platforms_constraint_values) != type({}):
+        fail("cxx_platforms_constraint_values must be a map of platform to constraint values!")
+    for platform, platform_values in cxx_platforms_constraint_values.items():
+        if platform not in supported_cxx_platforms:
+            fail(
+                "\n\nProviding platform constraints for an unsupported platform!\nBase platform: {}\nCXX Platform: {} with values {}\nSupported platforms: {}\n".format(
+                    base_name,
+                    platform,
+                    platform_values,
+                    ", ".join(supported_cxx_platforms),
+                )
+            )
+
+def _validate_build_mode_constraint_values(base_name, build_mode_constraint_values, supported_build_modes) -> None:
+    if type(build_mode_constraint_values) != type({}):
+        fail("build_mode_constraint_values must be a map of build mode to constraint values!")
+    for build_mode, build_mode_values in build_mode_constraint_values.items():
+        if build_mode not in supported_build_modes:
+            fail(
+                "\n\nProviding build mode constraints for an unsupported build mode!\nBase platform: {}\nBuild mode: {} with values {}\nSupported build modes: {}\n".format(
+                    base_name,
+                    build_mode,
+                    build_mode_values,
+                    ", ".join(supported_build_modes),
+                )
+            )
diff --git a/buck2/prelude/platforms/apple/platforms_map.bzl b/buck2/prelude/platforms/apple/platforms_map.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/platforms/apple/platforms_map.bzl
@@ -0,0 +1,19 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//platforms/apple/meta_only:platforms_map.bzl",
+    _APPLE_PLATFORMS_MAP = "APPLE_PLATFORMS_MAP",
+    _APPLE_SDK_DEFAULT_PLATFORM_MAP = "APPLE_SDK_DEFAULT_PLATFORM_MAP",
+# @oss-disable[end= ]: )
+
+APPLE_PLATFORMS_MAP = {} # TODO: Define OSS platforms map # @oss-enable
+# @oss-disable[end= ]: APPLE_PLATFORMS_MAP = _APPLE_PLATFORMS_MAP
+
+APPLE_SDK_DEFAULT_PLATFORM_MAP = {} # @oss-enable
+# @oss-disable[end= ]: APPLE_SDK_DEFAULT_PLATFORM_MAP = _APPLE_SDK_DEFAULT_PLATFORM_MAP
diff --git a/buck2/prelude/platforms/apple/sdk.bzl b/buck2/prelude/platforms/apple/sdk.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/platforms/apple/sdk.bzl
@@ -0,0 +1,25 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+_APPLE_SDKS = [
+    "iphoneos",
+    "iphonesimulator",
+    "maccatalyst",
+    "macosx",
+    "visionos",
+    "visionsimulator",
+    "watchos",
+    "watchsimulator",
+    "appletvos",
+    "appletvsimulator",
+    # Marker entry used to help toolchain selectors define a set of
+    # tools outside the apple_toolchain definition.
+    "toolchain-tool",
+]
+
+AppleSdk = enum(*_APPLE_SDKS)
diff --git a/buck2/prelude/platforms/defs.bzl b/buck2/prelude/platforms/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/platforms/defs.bzl
@@ -0,0 +1,72 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cfg/exec_platform:marker.bzl", "get_exec_platform_marker")
+
+def _execution_platform_impl(ctx: AnalysisContext) -> list[Provider]:
+    constraints = dict()
+    constraints.update(ctx.attrs.cpu_configuration[ConfigurationInfo].constraints)
+    constraints.update(ctx.attrs.os_configuration[ConfigurationInfo].constraints)
+    cfg = ConfigurationInfo(constraints = constraints, values = {})
+
+    name = ctx.label.raw_target()
+    platform = ExecutionPlatformInfo(
+        label = name,
+        configuration = cfg,
+        executor_config = CommandExecutorConfig(
+            local_enabled = True,
+            remote_enabled = False,
+            use_windows_path_separators = ctx.attrs.use_windows_path_separators,
+        ),
+    )
+
+    return [
+        DefaultInfo(),
+        platform,
+        PlatformInfo(label = str(name), configuration = cfg),
+        ExecutionPlatformRegistrationInfo(
+            platforms = [platform],
+            exec_marker_constraint = get_exec_platform_marker(),
+        ),
+    ]
+
+execution_platform = rule(
+    impl = _execution_platform_impl,
+    attrs = {
+        "cpu_configuration": attrs.dep(providers = [ConfigurationInfo]),
+        "os_configuration": attrs.dep(providers = [ConfigurationInfo]),
+        "use_windows_path_separators": attrs.bool(),
+    },
+)
+
+def _host_cpu_configuration() -> str:
+    arch = host_info().arch
+    if arch.is_aarch64:
+        return "prelude//cpu:arm64"
+    elif arch.is_arm:
+        return "prelude//cpu:arm32"
+    elif arch.is_i386:
+        return "prelude//cpu:x86_32"
+    elif arch.is_riscv64:
+        return "prelude//cpu:riscv64"
+    else:
+        return "prelude//cpu:x86_64"
+
+def _host_os_configuration() -> str:
+    os = host_info().os
+    if os.is_macos:
+        return "prelude//os:macos"
+    elif os.is_windows:
+        return "prelude//os:windows"
+    else:
+        return "prelude//os:linux"
+
+host_configuration = struct(
+    cpu = _host_cpu_configuration(),
+    os = _host_os_configuration(),
+)
diff --git a/buck2/prelude/playground/test.bxl b/buck2/prelude/playground/test.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/playground/test.bxl
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _impl(ctx):
+    ctx.output.print("123")
+
+playground = bxl_main(
+    impl = _impl,
+    cli_args = {},
+)
diff --git a/buck2/prelude/prelude.bzl b/buck2/prelude/prelude.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/prelude.bzl
@@ -0,0 +1,30 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:native.bzl", _native = "native")
+load(
+    "@prelude//utils:buckconfig.bzl",
+    _read_config = "read_config_with_logging",
+    _read_root_config = "read_root_config_with_logging",
+    log_buckconfigs = "LOG_BUCKCONFIGS",
+)
+
+__overridden_builtins__ = (
+    {
+        "read_config": _read_config,
+        "read_root_config": _read_root_config,
+    }
+    if log_buckconfigs
+    else {}
+)
+
+load_symbols(__overridden_builtins__)
+
+# Public symbols in this file become globals everywhere except `bzl` files in prelude.
+# Additionally, members of `native` struct also become globals in `BUCK` files.
+native = _native
diff --git a/buck2/prelude/python/compile.bzl b/buck2/prelude/python/compile.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/compile.bzl
@@ -0,0 +1,61 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":manifest.bzl", "ManifestInfo")
+load(":toolchain.bzl", "PythonToolchainInfo")
+
+def compile_manifests(ctx: AnalysisContext, manifests: list[ManifestInfo]) -> ManifestInfo:
+    mode = "UNCHECKED_HASH"
+    has_content_based_path = ctx.attrs._python_toolchain[PythonToolchainInfo].supports_content_based_paths == True
+    output = ctx.actions.declare_output("bytecode_{}".format(mode), dir = True, has_content_based_path = has_content_based_path)
+    bytecode_manifest = ctx.actions.declare_output("bytecode_{}.manifest".format(mode), has_content_based_path = has_content_based_path)
+    cmd = [
+        ctx.attrs._python_toolchain[PythonToolchainInfo].host_interpreter,
+        ctx.attrs._python_toolchain[PythonToolchainInfo].compile,
+        cmd_args(output.as_output(), format = "--output={}"),
+        cmd_args(bytecode_manifest.as_output(), format = "--bytecode-manifest={}"),
+        "--invalidation-mode={}".format(mode),
+    ]
+
+    env = {
+        # On some platforms (e.g. linux), python hash code randomness can cause
+        # the bytecode to be non-deterministic, so pin via the `PYTHONHASHSEED`
+        # env var.
+        "PYTHONHASHSEED": "7",
+    }
+
+    # support invalidating cached pyc compile actions by bumping the env var.
+    # the value itself is meaningless, just the fact it changes is meaningful.
+    # using the PYC magic number for *convenience* only
+    version = ctx.attrs._python_toolchain[PythonToolchainInfo].version
+    if version and "cinder" in version:
+        # for Cinder, this is a workaround...
+        # this action *should* use the bundled (in-repo) runtime for compilation
+        # (and then the change in the Cinder codebase would be sufficient to invalidate caches)
+        # currently though, the action uses the platform Cinder for PYC compilation,
+        # and these are deployed in-place (no change to toolchain paths),
+        # so we need to force cache invalidation when needed (e.g. for S411091)
+        env["CINDER_DUMMY_PYC_CACHE_BUSTER"] = "3451"
+    elif version and "3.12" in version:
+        # for CPython, the magic number *shouldn't* change during the lifetime of a feature release
+        # but internally we do make more significant changes (rarely),
+        # so for those cases we support forced invalidation using this env var
+        env["PYTHON312_DUMMY_PYC_CACHE_BUSTER"] = "3532"
+
+    hidden = []
+    for manifest in manifests:
+        cmd.append(manifest.manifest)
+        hidden.extend([a for a, _ in manifest.artifacts])
+    ctx.actions.run(
+        cmd_args(cmd, hidden = hidden),
+        env = env,
+        category = "py_compile",
+        identifier = mode,
+        error_handler = ctx.attrs._python_toolchain[PythonToolchainInfo].python_error_handler,
+    )
+    return ManifestInfo(manifest = bytecode_manifest.without_associated_artifacts(), artifacts = [(output, "bytecode")])
diff --git a/buck2/prelude/python/compute_providers.bzl b/buck2/prelude/python/compute_providers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/compute_providers.bzl
@@ -0,0 +1,61 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+load(
+    "@prelude//tests:re_utils.bzl",
+    "get_re_executors_from_props",
+)
+load(":make_py_package.bzl", "PexProviders", "make_default_info", "make_run_info")
+
+ExecutableType = enum(
+    "binary",
+    "test",
+)
+
+def compute_providers(ctx: AnalysisContext, exe: PexProviders, executable_type: ExecutableType) -> list[Provider]:
+    if executable_type == ExecutableType("binary"):
+        return compute_binary_providers(ctx, exe)
+    elif executable_type == ExecutableType("test"):
+        return compute_test_providers(ctx, exe)
+    else:
+        fail("Unknown executable type: " + executable_type)
+
+def compute_binary_providers(ctx: AnalysisContext, exe: PexProviders) -> list[Provider]:
+    return [
+        make_default_info(exe),
+        make_run_info(exe, ctx.attrs.run_with_inplace),
+    ]
+
+def compute_test_providers(ctx: AnalysisContext, exe: PexProviders) -> list[Provider]:
+    test_cmd = exe.run_cmd
+
+    # Setup RE executors based on the `remote_execution` param.
+    re_executors = get_re_executors_from_props(ctx)
+    test_env = ctx.attrs.env
+    if exe.dbg_source_db:
+        test_env["PYTHON_SOURCE_MAP"] = exe.dbg_source_db
+
+    return inject_test_run_info(
+        ctx,
+        ExternalRunnerTestInfo(
+            type = "pyunit",
+            command = [test_cmd],
+            env = test_env,
+            labels = ctx.attrs.labels,
+            contacts = ctx.attrs.contacts,
+            default_executor = re_executors.default_executor,
+            executor_overrides = re_executors.executor_overrides,
+            # We implicitly make this test via the project root, instead of
+            # the cell root (e.g. fbcode root). `network_access` is carried on
+            # the executor config (see `get_re_executors_from_props`).
+            run_from_project_root = re_executors.run_from_project_root,
+            use_project_relative_paths = re_executors.use_project_relative_paths,
+            supports_test_execution_caching = ctx.attrs.supports_test_execution_caching,
+        ),
+    ) + [make_default_info(exe)]
diff --git a/buck2/prelude/python/cxx_python_extension.bzl b/buck2/prelude/python/cxx_python_extension.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/cxx_python_extension.bzl
@@ -0,0 +1,399 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//cxx:cuda.bzl",
+    "CudaCompileStyle",
+)
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_library.bzl",
+    "cxx_library_parameterized",
+)
+load(
+    "@prelude//cxx:cxx_library_utility.bzl",
+    "cxx_attr_deps",
+)
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "get_srcs_with_flags",
+)
+load(
+    "@prelude//cxx:cxx_types.bzl",
+    "CxxRuleConstructorParams",
+    "CxxRuleProviderParams",
+    "CxxRuleSubTargetParams",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load("@prelude//cxx:headers.bzl", "cxx_get_regular_cxx_headers_layout")
+load("@prelude//cxx:linker.bzl", "DUMPBIN_SUB_TARGET", "PDB_SUB_TARGET", "get_dumpbin_providers", "get_pdb_providers")
+load(
+    "@prelude//cxx:omnibus.bzl",
+    "create_linkable_root",
+    "get_roots",
+)
+load(
+    "@prelude//linking:link_groups.bzl",
+    "merge_link_group_lib_info",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkableFlavor",
+    "create_merged_link_info",
+    "wrap_link_infos",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+    "create_linkable_node",
+)
+load(
+    "@prelude//linking:linkables.bzl",
+    "LinkableProviders",
+    "linkables",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "merge_shared_libraries",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//python:toolchain.bzl", "PythonToolchainInfo")
+load(
+    "@prelude//python/linking:native_python_util.bzl",
+    "merge_cxx_extension_info",
+    "rewrite_static_symbols",
+)
+load(
+    "@prelude//third-party:build.bzl",
+    "create_third_party_build_root",
+    "prefix_from_label",
+)
+load("@prelude//third-party:providers.bzl", "ThirdPartyBuild", "third_party_build_info")
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+load("@prelude//utils:utils.bzl", "value_or")
+load(":manifest.bzl", "create_manifest_for_source_map")
+load(":python.bzl", "NativeDepsInfo", "NativeDepsInfoTSet", "PythonLibraryInfo")
+load(":python_library.bzl", "create_python_library_info", "dest_prefix", "gather_dep_libraries", "qualify_srcs")
+load(":source_db.bzl", "create_python_source_db_info", "create_source_db_no_deps")
+load(":versions.bzl", "gather_versioned_dependencies")
+
+# This extension is basically cxx_library, plus base_module.
+# So we augment with default attributes so it has everything cxx_library has, and then call cxx_library_parameterized and work from that.
+def cxx_python_extension_impl(ctx: AnalysisContext) -> list[Provider]:
+    providers = []
+
+    if ctx.attrs._target_os_type[OsLookup].os == Os("windows"):
+        library_extension = ".pyd"
+    else:
+        library_extension = ".so"
+    module_name = value_or(ctx.attrs.module_name, ctx.label.name)
+    name = module_name + library_extension
+    base_module = dest_prefix(ctx.label, ctx.attrs.base_module)
+
+    sub_targets = CxxRuleSubTargetParams(
+        argsfiles = True,
+        compilation_database = True,
+        headers = False,
+        link_group_map = False,
+        link_style_outputs = False,
+        xcode_data = False,
+    )
+
+    cxx_providers = CxxRuleProviderParams(
+        compilation_database = True,
+        default = False,  # We need to do some postprocessing to make sure the shared library is our default output
+        java_packaging_info = False,
+        java_global_code_info = False,
+        linkable_graph = False,  # We create this here so we can correctly apply exclusions
+        link_style_outputs = False,
+        merged_native_link_info = False,
+        omnibus_root = True,
+        preprocessors = False,
+        resources = True,
+        shared_libraries = False,
+        template_placeholders = False,
+        preprocessor_for_tests = False,
+    )
+
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+
+    impl_params = CxxRuleConstructorParams(
+        build_empty_so = True,
+        rule_type = "cxx_python_extension",
+        headers_layout = cxx_get_regular_cxx_headers_layout(ctx),
+        srcs = get_srcs_with_flags(ctx),
+        soname = name,
+        use_soname = False,
+        generate_providers = cxx_providers,
+        generate_sub_targets = sub_targets,
+        compiler_flags = ctx.attrs.compiler_flags,
+        lang_compiler_flags = ctx.attrs.lang_compiler_flags,
+        extra_link_flags = python_toolchain.extension_linker_flags,
+        preprocessor_flags = ctx.attrs.preprocessor_flags,
+        lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,
+        error_handler = cxx_toolchain.cxx_error_handler,
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),
+        precompiled_header = ctx.attrs.precompiled_header,
+        prefix_header = ctx.attrs.prefix_header,
+        _cxx_toolchain = ctx.attrs._cxx_toolchain,
+        coverage_instrumentation_compiler_flags = ctx.attrs.coverage_instrumentation_compiler_flags,
+        coverage_profile_list = ctx.attrs.coverage_profile_list[DefaultInfo].default_outputs[0] if ctx.attrs.coverage_profile_list else None,
+        separate_debug_info = ctx.attrs.separate_debug_info,
+        cuda_compile_style = CudaCompileStyle(ctx.attrs.cuda_compile_style),
+        supports_stripping = ctx.attrs.supports_stripping,
+        use_content_based_paths = cxx_toolchain.cxx_compiler_info.supports_content_based_paths,
+    )
+
+    cxx_library_info = cxx_library_parameterized(ctx, impl_params)
+    libraries = cxx_library_info.all_outputs
+    shared_output = libraries.outputs[LibOutputStyle("shared_lib")][LinkableFlavor("default")]
+
+    solib_default = libraries.solibs.get(LinkableFlavor("default"), None)
+    if not solib_default:
+        fail("Expected cxx_python_extension to produce a solib: {}".format(ctx.label))
+    extension = solib_default.linked_object
+
+    sub_targets = cxx_library_info.sub_targets
+    if extension.pdb:
+        sub_targets[PDB_SUB_TARGET] = get_pdb_providers(pdb = extension.pdb, binary = extension.output)
+
+    dumpbin_toolchain_path = cxx_toolchain.dumpbin_toolchain_path
+    if dumpbin_toolchain_path:
+        sub_targets[DUMPBIN_SUB_TARGET] = get_dumpbin_providers(ctx, extension.output, dumpbin_toolchain_path)
+
+    cxx_deps = cxx_attr_deps(ctx)
+
+    extension_artifacts = {}
+    python_module_names = {}
+    unembeddable_extensions = {}
+
+    link_infos = libraries.link_infos
+
+    # For python_cxx_extensions we need to mangle the symbol names in order to avoid collisions
+    # when linking into the main binary
+    embeddable = ctx.attrs.allow_embedding and LibOutputStyle("archive") in libraries.outputs
+    if embeddable:
+        pyinit_prefix = "PyInit"
+        if ctx.attrs._target_os_type[OsLookup].os == Os("macos"):
+            pyinit_prefix = "_PyInit"
+        if not ctx.attrs.allow_suffixing:
+            pyinit_symbol = "{}_{}".format(pyinit_prefix, module_name)
+        else:
+            suffix = base_module.replace("/", "$") + module_name
+            static_output = libraries.outputs[LibOutputStyle("archive")][LinkableFlavor("default")]
+            static_pic_output = libraries.outputs[LibOutputStyle("pic_archive")][LinkableFlavor("default")]
+
+            debuggable_static_pic_objects = []
+            if LinkableFlavor("debug") in libraries.outputs[LibOutputStyle("pic_archive")]:
+                debuggable_static_pic_objects = libraries.outputs[LibOutputStyle("pic_archive")][LinkableFlavor("debug")].object_files
+
+            link_infos = rewrite_static_symbols(
+                ctx,
+                suffix,
+                pic_objects = static_pic_output.object_files,
+                non_pic_objects = static_output.object_files,
+                debuggable_pic_objects = debuggable_static_pic_objects,
+                libraries = link_infos,
+                cxx_toolchain = cxx_toolchain,
+                suffix_all = ctx.attrs.suffix_all,
+                suffix_exclude_rtti = ctx.attrs.suffix_exclude_rtti,
+            )
+            pyinit_symbol = "{}_{}_{}".format(pyinit_prefix, module_name, suffix)
+
+        if base_module != "":
+            lines = ["# auto generated stub for {}\n".format(ctx.label.raw_target())]
+            stub_name = module_name + ".empty_stub"
+            extension_artifacts.update(
+                qualify_srcs(ctx.label, ctx.attrs.base_module, {stub_name: ctx.actions.write(stub_name, lines, has_content_based_path = False)})
+            )
+
+        python_module_names[base_module.replace("/", ".") + module_name] = pyinit_symbol
+
+    # Add a dummy shared link info to avoid marking this node as preferred
+    # linkage being "static", which has a special meaning for various link
+    # strategies
+    link_infos[LibOutputStyle("shared_lib")] = LinkInfos(default = LinkInfo())
+
+    # Create linkable providers for the extension.
+    link_deps = linkables(cxx_deps)
+    linkable_providers = LinkableProviders(
+        link_group_lib_info = merge_link_group_lib_info(deps = cxx_deps),
+        linkable_graph = create_linkable_graph(
+            ctx = ctx,
+            node = create_linkable_graph_node(
+                ctx = ctx,
+                linkable_node = create_linkable_node(
+                    ctx = ctx,
+                    deps = cxx_deps,
+                    preferred_linkage = Linkage("any"),
+                    link_infos = link_infos,
+                    default_soname = name,
+                ),
+            ),
+            deps = [d.linkable_graph for d in link_deps if d.linkable_graph != None],
+        ),
+        merged_link_info = create_merged_link_info(
+            ctx = ctx,
+            pic_behavior = cxx_toolchain.pic_behavior,
+            link_infos = link_infos,
+            preferred_linkage = Linkage("static"),
+            deps = [d.merged_link_info for d in link_deps],
+        ),
+        shared_library_info = merge_shared_libraries(
+            actions = ctx.actions,
+            deps = [d.shared_library_info for d in link_deps],
+        ),
+        linkable_root_info = create_linkable_root(
+            label = ctx.label,
+            link_infos = wrap_link_infos(
+                link_infos[LibOutputStyle("pic_archive")],
+                pre_flags = ctx.attrs.linker_flags,
+                post_flags = ctx.attrs.post_linker_flags,
+            ),
+            deps = cxx_deps,
+        ),
+    )
+
+    if not embeddable:
+        unembeddable_extensions[base_module + name] = linkable_providers
+        linkable_providers = None
+
+    providers.append(
+        merge_cxx_extension_info(
+            actions = ctx.actions,
+            deps = cxx_deps,
+            linkable_providers = linkable_providers,
+            artifacts = extension_artifacts,
+            python_module_names = python_module_names,
+            unembeddable_extensions = unembeddable_extensions,
+        )
+    )
+    providers.extend(cxx_library_info.providers)
+
+    # If a type stub was specified, create a manifest for export.
+    src_types = None
+    src_type_manifest = None
+    if ctx.attrs.type_stub != None:
+        src_types = qualify_srcs(
+            ctx.label,
+            ctx.attrs.base_module,
+            {module_name + ".pyi": ctx.attrs.type_stub},
+        )
+        src_type_manifest = create_manifest_for_source_map(
+            ctx,
+            "type_stub",
+            src_types,
+        )
+
+    # Export library info.
+    raw_deps = ctx.attrs.deps
+
+    deps, shared_deps = gather_dep_libraries(raw_deps, resolve_versioned_deps = False)
+    providers.append(gather_versioned_dependencies(raw_deps))
+
+    # We dont process anything for cxx_extensions, we just add an empty set
+    native_deps = ctx.actions.tset(
+        NativeDepsInfoTSet,
+        value = NativeDepsInfo(native_deps = {}),
+        children = [],
+    )
+    library_info = create_python_library_info(
+        ctx.actions,
+        ctx.label,
+        extensions = qualify_srcs(ctx.label, ctx.attrs.base_module, {name: extension}),
+        deps = deps,
+        extension_shared_libraries = shared_deps,
+        src_types = src_type_manifest,
+        native_deps = native_deps,
+        is_native_dep = True,
+    )
+    providers.append(library_info)
+
+    # Source DBs.
+    if src_types != None:
+        sub_targets["source-db-no-deps"] = [create_source_db_no_deps(ctx, src_types), create_python_source_db_info(library_info.manifests)]
+
+    providers.append(
+        DefaultInfo(
+            default_output = shared_output.default,
+            other_outputs = shared_output.other,
+            sub_targets = sub_targets,
+        )
+    )
+
+    # Omnibus providers
+
+    # Handle the case where C++ Python extensions depend on other C++ Python
+    # extensions, which should also be treated as roots.
+    roots = get_roots([
+        dep
+        for dep in raw_deps
+        # We only want to handle C++ Python extension deps, but not other native
+        # linkable deps like C++ libraries.
+        if PythonLibraryInfo in dep
+    ])
+
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            roots = roots,
+        ),
+        deps = raw_deps,
+    )
+    providers.append(linkable_graph)
+
+    # Allow third-party-build rules to depend on Python rules.
+    tp_prefix = prefix_from_label(ctx.label)
+    providers.append(
+        third_party_build_info(
+            actions = ctx.actions,
+            build = ThirdPartyBuild(
+                prefix = tp_prefix,
+                root = create_third_party_build_root(
+                    ctx = ctx,
+                    paths = [(paths.join("lib/python", base_module + name), extension.output)],
+                ),
+                manifest = ctx.actions.write_json(
+                    "third_party_build_manifest.json",
+                    dict(
+                        bin_paths = [],
+                        c_include_paths = [],
+                        cxx_include_paths = [],
+                        lib_paths = [],
+                        libs = [],
+                        prefix = tp_prefix,
+                        py_lib_paths = ["lib/python"],
+                        runtime_lib_paths = [],
+                    ),
+                    has_content_based_path = False,
+                ),
+            ),
+            deps = raw_deps,
+        ),
+    )
+
+    providers.append(
+        create_unix_env_info(
+            actions = ctx.actions,
+            env = UnixEnv(
+                label = ctx.label,
+                python_libs = [library_info],
+            ),
+            deps = raw_deps,
+        ),
+    )
+
+    return providers
diff --git a/buck2/prelude/python/cython/cython_compile.bzl b/buck2/prelude/python/cython/cython_compile.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/cython/cython_compile.bzl
@@ -0,0 +1,184 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load(
+    ":cython_providers.bzl",
+    "CythonCompileOutput",
+)
+load(
+    ":cython_toolchain.bzl",
+    "CythonToolchainInfo",
+)
+
+def generate_cython_flags(
+    generate_cpp: bool,
+    cython_binding: bool = False,
+    code_comments: bool = False,
+    legacy_noexcept: bool = True,
+    annotate: [str, None] = None,
+    flags: list[str] = [],
+) -> list[str]:
+    """
+    Build the list of flags to pass to the Cython compiler.
+
+    Mirrors the flag construction logic from the existing cython_library macro's
+    generate_cython_flags() function.
+    """
+    result = []
+
+    # Language version (always Python 3)
+    result.append("-3")
+
+    # Fast fail on first error
+    result.append("--fast-fail")
+
+    # Annotation
+    if annotate == "basic":
+        result.append("--annotate")
+    elif annotate == "fullc":
+        result.append("--annotate-fullc")
+
+    # C++ mode
+    if generate_cpp:
+        result.append("--cplus")
+
+    # Cython binding mode
+    result.extend(["-X", "binding={}".format(cython_binding)])
+
+    # Code comments
+    result.extend(["-X", "emit_code_comments={}".format(code_comments)])
+
+    # Language level workaround (Cython v3.0 compat)
+    result.extend(["-X", "language_level=3"])
+
+    # Legacy implicit noexcept
+    result.extend(["-X", "legacy_implicit_noexcept={}".format(legacy_noexcept)])
+
+    # User-provided flags last so they can override defaults
+    result.extend(flags)
+
+    return result
+
+def _build_package_init_tree(actions: AnalysisActions, package_path: str, identifier: str) -> dict[str, Artifact]:
+    """
+    Create __init__.py markers for all intermediate directories in the package path.
+    """
+    init_files = {}
+    if not package_path:
+        return init_files
+
+    init_py = actions.write("__cython_init__/" + identifier + "/__init__.py", "", has_content_based_path = False)
+    parts = package_path.split("/")
+    for i in range(len(parts)):
+        prefix = "/".join(parts[: i + 1])
+        init_files[prefix + "/__init__.py"] = init_py
+
+    return init_files
+
+def cython_compile(
+    actions: AnalysisActions,
+    cython_toolchain: CythonToolchainInfo,
+    src: Artifact,
+    package_path: str,
+    include_tree: [Artifact, None],
+    flags: list[str],
+    generate_cpp: bool,
+    identifier: str,
+    exec_os_type = None,
+) -> CythonCompileOutput:
+    """
+    Run the Cython compiler on a single .pyx file.
+
+    Args:
+        actions: The AnalysisActions context.
+        cython_toolchain: The CythonToolchainInfo provider.
+        src: The .pyx source file artifact.
+        package_path: The package path (e.g., "thrift/python").
+        include_tree: Symlinked directory of transitive .pxd headers (or None).
+        flags: Compiler flags to pass.
+        generate_cpp: Whether to generate C++ (.cpp) or C (.c) output.
+        identifier: A unique identifier for this compile action.
+        exec_os_type: OsLookup provider for the execution platform.
+
+    Returns:
+        A CythonCompileOutput record with the generated source and header artifacts.
+    """
+    ext = ".cpp" if generate_cpp else ".c"
+    module_name = paths.split_extension(paths.basename(src.short_path))[0]
+
+    # Create a source layout directory with the .pyx under the package path
+    # and __init__.py markers for package discovery
+    src_layout = {}
+    if package_path:
+        src_layout[package_path + "/" + src.basename] = src
+    else:
+        src_layout[src.basename] = src
+
+    # Add __init__.py markers for all intermediate package directories
+    init_files = _build_package_init_tree(actions, package_path, identifier)
+    src_layout.update(init_files)
+
+    src_dir = actions.symlinked_dir(
+        "__cython_src__/" + identifier,
+        src_layout,
+        has_content_based_path = False,
+    )
+
+    out_dir = actions.declare_output("__cython__/" + identifier, dir = True, has_content_based_path = False)
+
+    cython_cmd = cmd_args()
+    cython_cmd.add(cython_toolchain.compiler)
+    cython_cmd.add(flags)
+
+    if include_tree:
+        cython_cmd.add("-I")
+        cython_cmd.add(include_tree)
+
+    # Output file path
+    out_file = module_name + ext
+    cython_cmd.add("-o")
+    cython_cmd.add(cmd_args(out_dir.as_output(), format = "{}" + "/" + out_file))
+
+    # Input file path
+    if package_path:
+        cython_cmd.add(cmd_args(src_dir, format = "{}" + "/" + package_path + "/" + src.basename))
+    else:
+        cython_cmd.add(cmd_args(src_dir, format = "{}" + "/" + src.basename))
+
+    # Wrap with OS-appropriate mkdir to ensure the output directory exists
+    # before the Cython compiler tries to write to it.
+    is_windows = exec_os_type != None and exec_os_type[OsLookup].os == Os("windows")
+    if is_windows:
+        cmd = cmd_args([
+            cmd_args(["cmd.exe", "/c", cmd_args([out_dir.as_output()], format = "if not exist {} md {}")]),
+            "&&",
+            cython_cmd,
+        ])
+    else:
+        cmd = cmd_args(
+            "/bin/sh",
+            "-c",
+            cmd_args(out_dir.as_output(), format = 'mkdir -p {} && "$@"'),
+            '""',
+            cython_cmd,
+        )
+
+    actions.run(
+        cmd,
+        category = "cython_compile",
+        identifier = identifier,
+        env = {"PYTHONHASHSEED": "0"},
+    )
+
+    return CythonCompileOutput(
+        cpp_src = out_dir.project(out_file),
+        api_header = out_dir.project(module_name + "_api.h"),
+        public_header = out_dir.project(module_name + ".h"),
+    )
diff --git a/buck2/prelude/python/cython/cython_library.bzl b/buck2/prelude/python/cython/cython_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/cython/cython_library.bzl
@@ -0,0 +1,520 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//cxx:cxx_context.bzl",
+    "get_cxx_toolchain_info",
+)
+load(
+    "@prelude//cxx:cxx_library.bzl",
+    "cxx_library_parameterized",
+)
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",
+)
+load(
+    "@prelude//cxx:cxx_types.bzl",
+    "CxxRuleConstructorParams",
+    "CxxRuleProviderParams",
+    "CxxRuleSubTargetParams",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load(
+    "@prelude//cxx:headers.bzl",
+    "cxx_get_regular_cxx_headers_layout",
+)
+load(
+    "@prelude//cxx:omnibus.bzl",
+    "get_roots",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkableFlavor",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+)
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//python:manifest.bzl", "create_manifest_for_source_map")
+load(
+    "@prelude//python:python.bzl",
+    "PythonLibraryInfo",
+)
+load(
+    "@prelude//python:python_library.bzl",
+    "create_python_library_info",
+    "dest_prefix",
+    "gather_dep_libraries",
+    "qualify_srcs",
+)
+load(
+    "@prelude//python:source_db.bzl",
+    "create_python_source_db_info",
+    "create_source_db_no_deps",
+)
+load("@prelude//python:toolchain.bzl", "PythonToolchainInfo")
+load(
+    "@prelude//python:versions.bzl",
+    "gather_versioned_dependencies",
+)
+load(
+    "@prelude//python/linking:native_python_util.bzl",
+    "merge_cxx_extension_info",
+    "merge_native_deps",
+)
+load(
+    "@prelude//third-party:build.bzl",
+    "create_third_party_build_root",
+    "prefix_from_label",
+)
+load("@prelude//third-party:providers.bzl", "ThirdPartyBuild", "third_party_build_info")
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+load(
+    ":cython_compile.bzl",
+    "cython_compile",
+    "generate_cython_flags",
+)
+load(
+    ":cython_providers.bzl",
+    "CythonIncludesInfo",
+    "CythonLibraryInfo",
+)
+load(
+    ":cython_toolchain.bzl",
+    "CythonToolchainInfo",
+)
+
+def _srcs_to_artifacts(srcs) -> list[Artifact]:
+    """Convert named_set (list or dict) to a list of artifacts."""
+    if isinstance(srcs, dict):
+        return srcs.values()
+    return srcs
+
+def _gather_cython_includes(ctx: AnalysisContext, srcs, headers, includes, deps: list[Dependency]) -> (Artifact, dict[str, Artifact]):
+    """
+    Collect all Cython include files (.pxd, .pxi) from the current rule
+    and transitive dependencies, and create a symlinked directory for includes.
+    """
+    base_module = dest_prefix(ctx.label, ctx.attrs.base_module)
+
+    # Collect raw headers for this rule
+    raw_headers = {}
+    for src in _srcs_to_artifacts(srcs):
+        _, ext = paths.split_extension(src.short_path)
+        if ext in (".pxd", ".pxi"):
+            raw_headers[base_module + src.basename] = src
+    for hdr in _srcs_to_artifacts(headers):
+        raw_headers[base_module + hdr.basename] = hdr
+    for inc in _srcs_to_artifacts(includes):
+        raw_headers[base_module + inc.basename] = inc
+
+    # Collect transitive includes from deps
+    for dep in deps:
+        if CythonIncludesInfo in dep:
+            dep_headers = dep[CythonIncludesInfo].raw_headers
+            for path, artifact in dep_headers.items():
+                if path not in raw_headers:
+                    raw_headers[path] = artifact
+
+    # Build __init__.py markers for package directories
+    all_dirs = {}
+    init_py = ctx.actions.write("__cython_init__/__init__.py", "", has_content_based_path = False)
+    for path in raw_headers.keys():
+        parts = paths.dirname(path).split("/")
+        for i in range(len(parts)):
+            if parts[i] and parts[i] != ".":
+                dir_path = "/".join(parts[: i + 1])
+                if dir_path not in all_dirs:
+                    all_dirs[dir_path] = True
+
+    # Create the symlinked dir with headers + init files
+    layout = dict(raw_headers)
+    for dir_path in all_dirs.keys():
+        init_path = dir_path + "/__init__.py"
+        if init_path not in layout:
+            layout[init_path] = init_py
+
+    include_tree = ctx.actions.symlinked_dir(
+        "__cython_includes__",
+        layout,
+        has_content_based_path = False,
+    )
+
+    return include_tree, raw_headers
+
+def _compile_cython_sources(
+    ctx: AnalysisContext, cython_toolchain: CythonToolchainInfo, srcs, include_tree: Artifact, flags: list[str], generate_cpp: bool
+) -> dict:
+    """
+    Compile all .pyx sources using the Cython compiler.
+    Returns a dict of {module_name: CythonCompileOutput}.
+    """
+    base_module = dest_prefix(ctx.label, ctx.attrs.base_module)
+
+    # Remove trailing slash for use as package_path
+    package_path = base_module.rstrip("/")
+
+    compiled = {}
+    for src in _srcs_to_artifacts(srcs):
+        _, ext = paths.split_extension(src.short_path)
+        if ext != ".pyx":
+            continue
+
+        module_name = paths.split_extension(paths.basename(src.short_path))[0]
+        identifier = module_name
+
+        compile_output = cython_compile(
+            actions = ctx.actions,
+            cython_toolchain = cython_toolchain,
+            src = src,
+            package_path = package_path,
+            include_tree = include_tree,
+            flags = flags,
+            generate_cpp = generate_cpp,
+            identifier = identifier,
+            exec_os_type = ctx.attrs._exec_os_type,
+        )
+        compiled[module_name] = compile_output
+
+    return compiled
+
+def _build_cxx_python_extension(ctx: AnalysisContext, module_name: str, generated_src: Artifact, cpp_compiler_flags: list, cpp_preprocessor_flags: list):
+    """
+    Build a single C++ Python extension from a generated .cpp/.c file.
+
+    Returns the linked extension output and associated providers.
+    """
+    if ctx.attrs._target_os_type[OsLookup].os == Os("windows"):
+        library_extension = ".pyd"
+    else:
+        library_extension = ".so"
+
+    name = module_name + library_extension
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+
+    sub_targets = CxxRuleSubTargetParams(
+        argsfiles = True,
+        compilation_database = True,
+        headers = False,
+        link_group_map = False,
+        link_style_outputs = False,
+        xcode_data = False,
+    )
+
+    cxx_providers = CxxRuleProviderParams(
+        compilation_database = True,
+        default = False,
+        java_packaging_info = False,
+        java_global_code_info = False,
+        linkable_graph = False,
+        link_style_outputs = False,
+        merged_native_link_info = False,
+        omnibus_root = True,
+        preprocessors = False,
+        resources = True,
+        shared_libraries = False,
+        template_placeholders = False,
+        preprocessor_for_tests = False,
+    )
+
+    srcs = [CxxSrcWithFlags(file = generated_src, flags = [], is_header = False)]
+
+    impl_params = CxxRuleConstructorParams(
+        build_empty_so = True,
+        rule_type = "cython_library",
+        headers_layout = cxx_get_regular_cxx_headers_layout(ctx),
+        srcs = srcs,
+        soname = name,
+        use_soname = False,
+        generate_providers = cxx_providers,
+        generate_sub_targets = sub_targets,
+        compiler_flags = cpp_compiler_flags,
+        preprocessor_flags = cpp_preprocessor_flags,
+        extra_link_flags = python_toolchain.extension_linker_flags,
+        error_handler = cxx_toolchain.cxx_error_handler,
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, cxx_toolchain.cxx_compiler_info.allow_cache_upload),
+        _cxx_toolchain = ctx.attrs._cxx_toolchain,
+    )
+
+    cxx_library_info = cxx_library_parameterized(ctx, impl_params)
+    libraries = cxx_library_info.all_outputs
+
+    solib_default = libraries.solibs.get(LinkableFlavor("default"), None)
+    if not solib_default:
+        fail("Expected cython_library extension to produce a solib for module: {}".format(module_name))
+    extension = solib_default.linked_object
+
+    return extension, cxx_library_info
+
+def cython_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    """
+    Implementation of the cython_library rule.
+
+    High-level flow:
+    1. Gather transitive Cython includes (.pxd/.pxi) from deps
+    2. Compile each .pyx source to .cpp/.c using the Cython compiler
+    3. Build each generated file as a C++ Python extension
+    4. Assemble Python library info with extensions + type stubs
+    5. Return all providers (DefaultInfo, PythonLibraryInfo, CythonIncludesInfo, etc.)
+    """
+    providers = []
+    sub_targets = {}
+
+    # Get the cython toolchain, with optional per-rule compiler override.
+    # Python version-based compiler selection is handled via select() on the
+    # toolchain's compiler attribute, so no imperative version matching needed.
+    cython_toolchain = ctx.attrs._cython_toolchain[CythonToolchainInfo]
+    if ctx.attrs.cython_compiler:
+        cython_toolchain = CythonToolchainInfo(
+            compiler = ctx.attrs.cython_compiler[RunInfo],
+            default_flags = cython_toolchain.default_flags,
+        )
+
+    # Determine source extension
+    generate_cpp = ctx.attrs.generate_cpp
+    ext = ".cpp" if generate_cpp else ".c"
+
+    # Build compiler flags
+    flags = generate_cython_flags(
+        generate_cpp = generate_cpp,
+        cython_binding = ctx.attrs.cython_binding,
+        code_comments = ctx.attrs.code_comments,
+        legacy_noexcept = ctx.attrs.legacy_noexcept,
+        annotate = ctx.attrs.cython_annotate,
+        flags = ctx.attrs.flags,
+    )
+
+    # Gather all Cython include files from current rule and deps
+    include_tree, raw_headers = _gather_cython_includes(
+        ctx = ctx,
+        srcs = ctx.attrs.srcs,
+        headers = ctx.attrs.headers,
+        includes = ctx.attrs.includes,
+        deps = ctx.attrs.deps,
+    )
+
+    # Compile all .pyx sources
+    compiled_modules = _compile_cython_sources(
+        ctx = ctx,
+        cython_toolchain = cython_toolchain,
+        srcs = ctx.attrs.srcs,
+        include_tree = include_tree,
+        flags = flags,
+        generate_cpp = generate_cpp,
+    )
+
+    # Build generated-sources and generated-headers sub-targets for debugging
+    gen_src_sub_targets = {}
+    gen_header_sub_targets = {}
+    all_gen_srcs = []
+    all_declaration_headers = []
+
+    for module_name, compile_output in compiled_modules.items():
+        all_gen_srcs.append(compile_output.cpp_src)
+        gen_src_sub_targets[module_name + ext] = [
+            DefaultInfo(
+                default_output = compile_output.cpp_src,
+            )
+        ]
+
+        gen_header_sub_targets[module_name + "_api.h"] = [
+            DefaultInfo(
+                default_output = compile_output.api_header,
+            )
+        ]
+        gen_header_sub_targets[module_name + ".h"] = [
+            DefaultInfo(
+                default_output = compile_output.public_header,
+            )
+        ]
+
+        # Collect declaration headers for api modules
+        if module_name in ctx.attrs.api:
+            all_declaration_headers.append(compile_output.api_header)
+            all_declaration_headers.append(compile_output.public_header)
+
+    sub_targets["generated-sources"] = [
+        DefaultInfo(
+            default_outputs = all_gen_srcs,
+            sub_targets = gen_src_sub_targets,
+        )
+    ]
+    sub_targets["generated-headers"] = [
+        DefaultInfo(
+            default_outputs = all_declaration_headers,
+            sub_targets = gen_header_sub_targets,
+        )
+    ]
+
+    # Build C++ Python extensions for each compiled module
+    base_module = dest_prefix(ctx.label, ctx.attrs.base_module)
+    if ctx.attrs._target_os_type[OsLookup].os == Os("windows"):
+        library_extension = ".pyd"
+    else:
+        library_extension = ".so"
+
+    all_extensions = {}
+    all_cxx_library_infos = []
+
+    for module_name, compile_output in compiled_modules.items():
+        extension, cxx_library_info = _build_cxx_python_extension(
+            ctx = ctx,
+            module_name = module_name,
+            generated_src = compile_output.cpp_src,
+            cpp_compiler_flags = ctx.attrs.cpp_compiler_flags,
+            cpp_preprocessor_flags = ctx.attrs.cpp_preprocessor_flags,
+        )
+
+        ext_name = module_name + library_extension
+        all_extensions[ext_name] = extension
+        all_cxx_library_infos.append(cxx_library_info)
+
+    # Qualify extensions with base module prefix
+    qualified_extensions = qualify_srcs(ctx.label, ctx.attrs.base_module, all_extensions)
+
+    # Add type stubs if present
+    src_types = None
+    src_type_manifest = None
+    type_stubs = {}
+    for type_stub in ctx.attrs.types:
+        type_stubs[type_stub.basename] = type_stub
+    if type_stubs:
+        qualified_types = qualify_srcs(ctx.label, ctx.attrs.base_module, type_stubs)
+        src_type_manifest = create_manifest_for_source_map(
+            ctx,
+            "type_stubs",
+            qualified_types,
+        )
+        src_types = qualified_types
+
+    # Build PythonLibraryInfo
+    raw_deps = ctx.attrs.deps + ctx.attrs.python_deps
+    deps, shared_deps = gather_dep_libraries(raw_deps, resolve_versioned_deps = False)
+    providers.append(gather_versioned_dependencies(raw_deps))
+
+    native_deps = merge_native_deps(ctx, raw_deps)
+
+    library_info = create_python_library_info(
+        ctx.actions,
+        ctx.label,
+        extensions = qualified_extensions,
+        deps = deps,
+        extension_shared_libraries = shared_deps,
+        src_types = src_type_manifest,
+        native_deps = native_deps,
+        is_native_dep = True,
+    )
+    providers.append(library_info)
+
+    # CxxExtensionInfo for omnibus linking
+    providers.append(
+        merge_cxx_extension_info(
+            actions = ctx.actions,
+            deps = raw_deps + ctx.attrs.cpp_deps,
+        )
+    )
+
+    # Linkable graph
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            roots = get_roots([dep for dep in raw_deps if PythonLibraryInfo in dep]),
+        ),
+        deps = raw_deps + ctx.attrs.cpp_deps,
+    )
+    providers.append(linkable_graph)
+
+    # UnixEnv provider
+    providers.append(
+        create_unix_env_info(
+            actions = ctx.actions,
+            env = UnixEnv(
+                label = ctx.label,
+                python_libs = [library_info],
+            ),
+            deps = raw_deps,
+        ),
+    )
+
+    # Allow third-party-build rules to depend on cython_library.
+    tp_prefix = prefix_from_label(ctx.label)
+    providers.append(
+        third_party_build_info(
+            actions = ctx.actions,
+            build = ThirdPartyBuild(
+                prefix = tp_prefix,
+                root = create_third_party_build_root(
+                    ctx = ctx,
+                    paths = [(paths.join("lib/python", base_module + ext_name), ext.output) for ext_name, ext in all_extensions.items()],
+                ),
+                manifest = ctx.actions.write_json(
+                    "third_party_build_manifest.json",
+                    dict(
+                        bin_paths = [],
+                        c_include_paths = [],
+                        cxx_include_paths = [],
+                        lib_paths = [],
+                        libs = [],
+                        prefix = tp_prefix,
+                        py_lib_paths = ["lib/python"],
+                        runtime_lib_paths = [],
+                    ),
+                    has_content_based_path = False,
+                ),
+            ),
+            deps = raw_deps,
+        ),
+    )
+
+    # CythonIncludesInfo for downstream cython_library deps
+    cython_includes_info = CythonIncludesInfo(
+        include_tree = include_tree,
+        raw_headers = raw_headers,
+    )
+    providers.append(cython_includes_info)
+
+    # CythonLibraryInfo for C++ interop
+    declaration_hdrs = {}
+    for module_name, compile_output in compiled_modules.items():
+        if module_name in ctx.attrs.api:
+            declaration_hdrs[base_module + module_name + "_api.h"] = compile_output.api_header
+            declaration_hdrs[base_module + module_name + ".h"] = compile_output.public_header
+
+    providers.append(
+        CythonLibraryInfo(
+            declaration_headers = declaration_hdrs,
+            include_info = cython_includes_info,
+        )
+    )
+
+    # Source DB sub-targets
+    if src_types:
+        sub_targets["source-db-no-deps"] = [
+            create_source_db_no_deps(ctx, src_types),
+            create_python_source_db_info(library_info.manifests),
+        ]
+
+    # Default output - if there are extensions, use the first one
+    default_output = None
+    if all_gen_srcs:
+        default_output = all_gen_srcs[0]
+
+    providers.append(
+        DefaultInfo(
+            default_output = default_output,
+            sub_targets = sub_targets,
+        )
+    )
+
+    return providers
diff --git a/buck2/prelude/python/cython/cython_providers.bzl b/buck2/prelude/python/cython/cython_providers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/cython/cython_providers.bzl
@@ -0,0 +1,34 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+CythonCompileOutput = record(
+    # The generated .c or .cpp source file
+    cpp_src = field(Artifact),
+    # The generated _api.h header (may not exist for all modules)
+    api_header = field(Artifact),
+    # The generated .h public header (may not exist for all modules)
+    public_header = field(Artifact),
+)
+
+CythonIncludesInfo = provider(
+    fields = {
+        # Symlinked directory of .pxd/.pxi files for Cython include resolution
+        "include_tree": provider_field(Artifact),
+        # {package_path/name: Artifact} for downstream merging of headers
+        "raw_headers": provider_field(dict[str, Artifact]),
+    }
+)
+
+CythonLibraryInfo = provider(
+    fields = {
+        # {path: Artifact} for _api.h/.h declaration headers for C++ interop
+        "declaration_headers": provider_field(dict[str, Artifact]),
+        # CythonIncludesInfo for downstream Cython deps
+        "include_info": provider_field(CythonIncludesInfo),
+    }
+)
diff --git a/buck2/prelude/python/cython/cython_static_extension.bzl b/buck2/prelude/python/cython/cython_static_extension.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/cython/cython_static_extension.bzl
@@ -0,0 +1,423 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//cxx:cxx_context.bzl",
+    "get_cxx_toolchain_info",
+)
+load(
+    "@prelude//cxx:cxx_library.bzl",
+    "cxx_library_parameterized",
+)
+load(
+    "@prelude//cxx:cxx_sources.bzl",
+    "CxxSrcWithFlags",
+)
+load(
+    "@prelude//cxx:cxx_types.bzl",
+    "CxxRuleConstructorParams",
+    "CxxRuleProviderParams",
+    "CxxRuleSubTargetParams",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load(
+    "@prelude//cxx:headers.bzl",
+    "cxx_get_regular_cxx_headers_layout",
+)
+load(
+    "@prelude//cxx:omnibus.bzl",
+    "get_roots",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkableFlavor",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+)
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//python:manifest.bzl", "create_manifest_for_source_map")
+load(
+    "@prelude//python:python.bzl",
+    "PythonLibraryInfo",
+)
+load(
+    "@prelude//python:python_library.bzl",
+    "create_python_library_info",
+    "dest_prefix",
+    "gather_dep_libraries",
+    "qualify_srcs",
+)
+load(
+    "@prelude//python:source_db.bzl",
+    "create_python_source_db_info",
+    "create_source_db_no_deps",
+)
+load("@prelude//python:toolchain.bzl", "PythonToolchainInfo")
+load(
+    "@prelude//python:versions.bzl",
+    "gather_versioned_dependencies",
+)
+load(
+    "@prelude//python/linking:native_python_util.bzl",
+    "merge_cxx_extension_info",
+    "merge_native_deps",
+)
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+load(
+    ":cython_compile.bzl",
+    "cython_compile",
+)
+load(
+    ":cython_providers.bzl",
+    "CythonIncludesInfo",
+    "CythonLibraryInfo",
+)
+load(
+    ":cython_toolchain.bzl",
+    "CythonToolchainInfo",
+)
+
+def _gather_cython_includes_static(ctx: AnalysisContext, cython_headers, cython_includes, cython_deps: list[Dependency]) -> (Artifact, dict[str, Artifact]):
+    """
+    Collect Cython include files from the current rule and transitive deps.
+    """
+    base_module = dest_prefix(ctx.label, ctx.attrs.base_module)
+
+    raw_headers = {}
+
+    # Handle cython_headers - can be list or dict
+    if isinstance(cython_headers, dict):
+        for name, artifact in cython_headers.items():
+            raw_headers[base_module + name] = artifact
+    else:
+        for hdr in cython_headers:
+            raw_headers[base_module + hdr.basename] = hdr
+
+    # Handle cython_includes - can be list or dict
+    if isinstance(cython_includes, dict):
+        for name, artifact in cython_includes.items():
+            raw_headers[base_module + name] = artifact
+    else:
+        for inc in cython_includes:
+            raw_headers[base_module + inc.basename] = inc
+
+    # Collect transitive includes from cython deps
+    for dep in cython_deps:
+        if CythonIncludesInfo in dep:
+            dep_headers = dep[CythonIncludesInfo].raw_headers
+            for path, artifact in dep_headers.items():
+                if path not in raw_headers:
+                    raw_headers[path] = artifact
+
+    # Build __init__.py markers for package directories
+    all_dirs = {}
+    init_py = ctx.actions.write("__cython_init__/__init__.py", "", has_content_based_path = False)
+    for path in raw_headers.keys():
+        parts = paths.dirname(path).split("/")
+        for i in range(len(parts)):
+            if parts[i] and parts[i] != ".":
+                dir_path = "/".join(parts[: i + 1])
+                if dir_path not in all_dirs:
+                    all_dirs[dir_path] = True
+
+    layout = dict(raw_headers)
+    for dir_path in all_dirs.keys():
+        init_path = dir_path + "/__init__.py"
+        if init_path not in layout:
+            layout[init_path] = init_py
+
+    include_tree = ctx.actions.symlinked_dir(
+        "__cython_includes__",
+        layout,
+        has_content_based_path = False,
+    )
+
+    return include_tree, raw_headers
+
+def cython_static_extension_impl(ctx: AnalysisContext) -> list[Provider]:
+    """
+    Implementation of the cython_static_extension rule.
+
+    Similar to cython_library but simplified for a single .pyx source,
+    producing a statically-linkable extension.
+    """
+    providers = []
+    sub_targets = {}
+
+    # Get the cython toolchain, with optional per-rule compiler override.
+    # Python version-based compiler selection is handled via select() on the
+    # toolchain's compiler attribute, so no imperative version matching needed.
+    cython_toolchain = ctx.attrs._cython_toolchain[CythonToolchainInfo]
+    if ctx.attrs.cython_compiler:
+        cython_toolchain = CythonToolchainInfo(
+            compiler = ctx.attrs.cython_compiler[RunInfo],
+            default_flags = cython_toolchain.default_flags,
+        )
+
+    generate_cpp = ctx.attrs.cython_generate_cpp
+    ext = ".cpp" if generate_cpp else ".c"
+
+    # Build compiler flags
+    cython_flags = []
+
+    # Language version
+    if ctx.attrs.cython_version in ("3", "3str"):
+        cython_flags.append("-3")
+    else:
+        cython_flags.append("-2")
+
+    # Fast fail
+    if ctx.attrs.cython_fast_fail:
+        cython_flags.append("--fast-fail")
+
+    # C++ mode
+    if generate_cpp:
+        cython_flags.append("--cplus")
+
+    # Binding
+    cython_flags.extend(["-X", "binding={}".format(ctx.attrs.cython_binding)])
+
+    # Code comments
+    cython_flags.extend(["-X", "emit_code_comments={}".format(ctx.attrs.cython_code_comments)])
+
+    # Language level workaround
+    cython_flags.extend(["-X", "language_level=3"])
+
+    # Legacy noexcept
+    cython_flags.extend(["-X", "legacy_implicit_noexcept={}".format(ctx.attrs.legacy_noexcept)])
+
+    # User-provided flags last
+    cython_flags.extend(ctx.attrs.cython_flags)
+
+    # Gather includes
+    include_tree, raw_headers = _gather_cython_includes_static(
+        ctx = ctx,
+        cython_headers = ctx.attrs.cython_headers,
+        cython_includes = ctx.attrs.cython_includes,
+        cython_deps = ctx.attrs.cython_deps,
+    )
+
+    # Compile the single .pyx source
+    src = ctx.attrs.cython_pyx
+    base_module = dest_prefix(ctx.label, ctx.attrs.base_module)
+    package_path = base_module.rstrip("/")
+    module_name = paths.split_extension(paths.basename(src.short_path))[0]
+
+    compile_output = cython_compile(
+        actions = ctx.actions,
+        cython_toolchain = cython_toolchain,
+        src = src,
+        package_path = package_path,
+        include_tree = include_tree,
+        flags = cython_flags,
+        generate_cpp = generate_cpp,
+        identifier = module_name,
+        exec_os_type = ctx.attrs._exec_os_type,
+    )
+
+    # Sub-targets for generated sources
+    gen_src_sub_targets = {
+        module_name + ext: [DefaultInfo(default_output = compile_output.cpp_src)],
+    }
+    gen_header_sub_targets = {
+        module_name + "_api.h": [DefaultInfo(default_output = compile_output.api_header)],
+        module_name + ".h": [DefaultInfo(default_output = compile_output.public_header)],
+    }
+    sub_targets["generated-sources"] = [
+        DefaultInfo(
+            default_outputs = [compile_output.cpp_src],
+            sub_targets = gen_src_sub_targets,
+        )
+    ]
+    sub_targets["generated-headers"] = [
+        DefaultInfo(
+            default_outputs = [compile_output.api_header, compile_output.public_header],
+            sub_targets = gen_header_sub_targets,
+        )
+    ]
+
+    # Build the C++ extension with static linkage preference
+    if ctx.attrs._target_os_type[OsLookup].os == Os("windows"):
+        library_extension = ".pyd"
+    else:
+        library_extension = ".so"
+
+    name = module_name + library_extension
+    cxx_toolchain = get_cxx_toolchain_info(ctx)
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+
+    cxx_sub_targets = CxxRuleSubTargetParams(
+        argsfiles = True,
+        compilation_database = True,
+        headers = False,
+        link_group_map = False,
+        link_style_outputs = False,
+        xcode_data = False,
+    )
+
+    cxx_providers_params = CxxRuleProviderParams(
+        compilation_database = True,
+        default = False,
+        java_packaging_info = False,
+        java_global_code_info = False,
+        linkable_graph = False,
+        link_style_outputs = False,
+        merged_native_link_info = False,
+        omnibus_root = True,
+        preprocessors = False,
+        resources = True,
+        shared_libraries = False,
+        template_placeholders = False,
+        preprocessor_for_tests = False,
+    )
+
+    # Combine generated source with any additional C++ sources
+    all_srcs = [CxxSrcWithFlags(file = compile_output.cpp_src, flags = [], is_header = False)]
+    for additional_src in ctx.attrs.srcs:
+        all_srcs.append(CxxSrcWithFlags(file = additional_src, flags = [], is_header = False))
+
+    impl_params = CxxRuleConstructorParams(
+        build_empty_so = True,
+        rule_type = "cython_static_extension",
+        headers_layout = cxx_get_regular_cxx_headers_layout(ctx),
+        srcs = all_srcs,
+        soname = name,
+        use_soname = False,
+        generate_providers = cxx_providers_params,
+        generate_sub_targets = cxx_sub_targets,
+        compiler_flags = ctx.attrs.compiler_flags,
+        preprocessor_flags = ctx.attrs.preprocessor_flags,
+        extra_link_flags = python_toolchain.extension_linker_flags,
+        error_handler = cxx_toolchain.cxx_error_handler,
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, cxx_toolchain.cxx_compiler_info.allow_cache_upload),
+        _cxx_toolchain = ctx.attrs._cxx_toolchain,
+    )
+
+    cxx_library_info = cxx_library_parameterized(ctx, impl_params)
+    libraries = cxx_library_info.all_outputs
+
+    solib_default = libraries.solibs.get(LinkableFlavor("default"), None)
+    if not solib_default:
+        fail("Expected cython_static_extension to produce a solib: {}".format(ctx.label))
+    extension = solib_default.linked_object
+
+    providers.extend(cxx_library_info.providers)
+
+    # Build qualified extensions map
+    ext_name = module_name + library_extension
+    qualified_extensions = qualify_srcs(ctx.label, ctx.attrs.base_module, {ext_name: extension})
+
+    # Type stubs
+    src_types = None
+    src_type_manifest = None
+    type_stubs = {}
+    for type_stub in ctx.attrs.python_types:
+        type_stubs[type_stub.basename] = type_stub
+    if type_stubs:
+        qualified_types = qualify_srcs(ctx.label, ctx.attrs.base_module, type_stubs)
+        src_type_manifest = create_manifest_for_source_map(
+            ctx,
+            "type_stubs",
+            qualified_types,
+        )
+        src_types = qualified_types
+
+    # Build PythonLibraryInfo
+    raw_deps = ctx.attrs.deps + ctx.attrs.python_deps + ctx.attrs.cython_deps
+    deps, shared_deps = gather_dep_libraries(raw_deps, resolve_versioned_deps = False)
+    providers.append(gather_versioned_dependencies(raw_deps))
+
+    native_deps = merge_native_deps(ctx, raw_deps)
+
+    library_info = create_python_library_info(
+        ctx.actions,
+        ctx.label,
+        extensions = qualified_extensions,
+        deps = deps,
+        extension_shared_libraries = shared_deps,
+        src_types = src_type_manifest,
+        native_deps = native_deps,
+        is_native_dep = True,
+    )
+    providers.append(library_info)
+
+    # CxxExtensionInfo
+    providers.append(
+        merge_cxx_extension_info(
+            actions = ctx.actions,
+            deps = raw_deps,
+        )
+    )
+
+    # Linkable graph
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            roots = get_roots([dep for dep in raw_deps if PythonLibraryInfo in dep]),
+        ),
+        deps = raw_deps,
+    )
+    providers.append(linkable_graph)
+
+    # UnixEnv
+    providers.append(
+        create_unix_env_info(
+            actions = ctx.actions,
+            env = UnixEnv(
+                label = ctx.label,
+                python_libs = [library_info],
+            ),
+            deps = raw_deps,
+        ),
+    )
+
+    # CythonIncludesInfo
+    cython_includes_info = CythonIncludesInfo(
+        include_tree = include_tree,
+        raw_headers = raw_headers,
+    )
+    providers.append(cython_includes_info)
+
+    # CythonLibraryInfo with declaration headers
+    declaration_hdrs = {
+        base_module + module_name + "_api.h": compile_output.api_header,
+        base_module + module_name + ".h": compile_output.public_header,
+    }
+    providers.append(
+        CythonLibraryInfo(
+            declaration_headers = declaration_hdrs,
+            include_info = cython_includes_info,
+        )
+    )
+
+    # Source DB
+    if src_types:
+        sub_targets["source-db-no-deps"] = [
+            create_source_db_no_deps(ctx, src_types),
+            create_python_source_db_info(library_info.manifests),
+        ]
+
+    # Default output
+    shared_output = libraries.outputs.get(LibOutputStyle("shared_lib"), {})
+    default_flavor = shared_output.get(LinkableFlavor("default"), None)
+    default_output = default_flavor.default if default_flavor else compile_output.cpp_src
+
+    providers.append(
+        DefaultInfo(
+            default_output = default_output,
+            sub_targets = sub_targets,
+        )
+    )
+
+    return providers
diff --git a/buck2/prelude/python/cython/cython_toolchain.bzl b/buck2/prelude/python/cython/cython_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/cython/cython_toolchain.bzl
@@ -0,0 +1,29 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+CythonToolchainInfo = provider(
+    fields = {
+        # The cython compiler binary (RunInfo provider).
+        # Python version-based selection should be handled via select() + py_version_select()
+        # on the compiler attribute in the toolchain BUCK definition, mirroring the
+        # fbsource//third-party/pypi/cython:compiler alias pattern.
+        "compiler": provider_field(RunInfo),
+        # Default compiler flags. Currently unused by cython_library and
+        # cython_static_extension (flags are built from rule attributes instead).
+        "default_flags": provider_field(list[str]),
+    }
+)
+
+def cython_toolchain_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        CythonToolchainInfo(
+            compiler = ctx.attrs.compiler[RunInfo],
+            default_flags = ctx.attrs.default_flags,
+        ),
+    ]
diff --git a/buck2/prelude/python/interface.bzl b/buck2/prelude/python/interface.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/interface.bzl
@@ -0,0 +1,35 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+PythonLibraryManifestsInterface = record(
+    # Returns the source manifests for this Python library.
+    # [_arglike] of source manifests
+    src_manifests = field(typing.Callable),
+    # Returns the files referenced by source manifests for this Python library.
+    # [_arglike] of source artifacts
+    src_artifacts = field(typing.Callable),
+    # Returns the bytecode manifests for this Python library.
+    # [_arglike] of bytecode manifests
+    bytecode_manifests = field(typing.Callable),
+    # Returns the files referenced by bytecode manifests for this Python library.
+    # [_arglike] of bytecode artifacts
+    bytecode_artifacts = field(typing.Callable),
+    # Returns the resources manifests for this Python library.
+    # [_arglike] of resource manifests
+    resource_manifests = field(typing.Callable),
+    # Returns the files referenced by resource manifests for this Python library.
+    # [_arglike] of resource artifacts
+    resource_artifacts = field(typing.Callable),
+    hidden_resources = field(typing.Callable),
+    has_hidden_resources = field(typing.Callable),
+)
+
+# Entry point for Python binaries. First component designates if the second
+# component is to be interpreted as a module or a function name.
+EntryPointKind = enum("module", "function")
+EntryPoint = (EntryPointKind, str)
diff --git a/buck2/prelude/python/internal_tools.bzl b/buck2/prelude/python/internal_tools.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/internal_tools.bzl
@@ -0,0 +1,68 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# This is a provider that acts much like `PythonToolchainInfo` and is used sort of similarly.
+# However, `PythonToolchainInfo` is used for things that are intended to actually be customizable
+# on a per-toolchain basis. This is for things that users are not expected to be able to
+# customize.
+PythonInternalToolsInfo = provider(
+    fields = {
+        "default_sitecustomize": Artifact,
+        # An `{}` JSON file, the type-check result for targets with typing disabled.
+        "empty_typing_result": Artifact,
+        "fail_with_message": RunInfo,
+        "generate_static_extension_info": Dependency,
+        "make_py_package_inplace": RunInfo,
+        "make_py_package_manifest_module": RunInfo,
+        "make_py_package_modules": RunInfo,
+        "make_source_db": RunInfo,
+        "make_source_db_no_deps": RunInfo,
+        "run_lpar_main": Artifact,
+        # A filegroup that gets added to all python executables
+        "runtime_library": Dependency,
+        "type_check_result_to_validation": RunInfo,
+    }
+)
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        PythonInternalToolsInfo(
+            default_sitecustomize = ctx.attrs.default_sitecustomize,
+            empty_typing_result = ctx.attrs.empty_typing_result,
+            fail_with_message = ctx.attrs.fail_with_message[RunInfo],
+            generate_static_extension_info = ctx.attrs.generate_static_extension_info,
+            make_source_db = ctx.attrs.make_source_db[RunInfo],
+            make_source_db_no_deps = ctx.attrs.make_source_db_no_deps[RunInfo],
+            make_py_package_inplace = ctx.attrs.make_py_package_inplace[RunInfo],
+            make_py_package_manifest_module = ctx.attrs.make_py_package_manifest_module[RunInfo],
+            make_py_package_modules = ctx.attrs.make_py_package_modules[RunInfo],
+            run_lpar_main = ctx.attrs.run_lpar_main,
+            runtime_library = ctx.attrs.runtime_library,
+            type_check_result_to_validation = ctx.attrs.type_check_result_to_validation[RunInfo],
+        ),
+    ]
+
+python_internal_tools = rule(
+    impl = _impl,
+    attrs = {
+        "default_sitecustomize": attrs.source(default = "prelude//python/tools/make_par:sitecustomize.py"),
+        "empty_typing_result": attrs.default_only(attrs.source(default = "prelude//python/tools:empty_typing_result.json")),
+        "fail_with_message": attrs.exec_dep(default = "prelude//python/tools:fail_with_message", providers = [RunInfo]),
+        "generate_static_extension_info": attrs.exec_dep(default = "prelude//python/tools:generate_static_extension_info"),
+        "make_py_package_inplace": attrs.exec_dep(default = "prelude//python/tools:make_py_package_inplace", providers = [RunInfo]),
+        "make_py_package_manifest_module": attrs.exec_dep(default = "prelude//python/tools:make_py_package_manifest_module", providers = [RunInfo]),
+        "make_py_package_modules": attrs.exec_dep(default = "prelude//python/tools:make_py_package_modules", providers = [RunInfo]),
+        "make_source_db": attrs.exec_dep(default = "prelude//python/tools:make_source_db", providers = [RunInfo]),
+        "make_source_db_no_deps": attrs.exec_dep(default = "prelude//python/tools:make_source_db_no_deps", providers = [RunInfo]),
+        "run_lpar_main": attrs.source(default = "prelude//python/tools/make_par:__run_lpar_main__.py"),
+        "runtime_library": attrs.dep(default = "prelude//python/runtime:bootstrap_files"),
+        "type_check_result_to_validation": attrs.exec_dep(default = "prelude//python/tools:type_check_result_to_validation", providers = [RunInfo]),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/python/lazy_imports.bzl b/buck2/prelude/python/lazy_imports.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/lazy_imports.bzl
@@ -0,0 +1,101 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:argfile.bzl", "argfile")
+load(":toolchain.bzl", "PythonToolchainInfo")
+
+def get_lazy_imports_analyzer(ctx: AnalysisContext) -> RunInfo | None:
+    """Resolve the lifeguard analyzer binary, checking the target attr first
+    then falling back to the toolchain."""
+    attr_analyzer = getattr(ctx.attrs, "lazy_imports_analyzer", None)
+    if attr_analyzer != None:
+        return attr_analyzer[RunInfo]
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    return python_toolchain.lazy_imports_analyzer
+
+def _get_main_module(ctx: AnalysisContext) -> str | None:
+    main_module = getattr(ctx.attrs, "main_module", None)
+    if main_module != None:
+        return main_module
+    main_function = getattr(ctx.attrs, "main_function", None)
+    if main_function != None:
+        return ""
+    return None
+
+def run_lazy_imports_analyzer(ctx: AnalysisContext, resources, output: Artifact, dbg_source_db_output: Artifact) -> DefaultInfo:
+    """
+    Run the lazy imports analyzer (lifeguard) against a Python binary by
+    ingesting the existing dbg-db.json.
+    """
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    cmd = cmd_args(ctx.attrs.lazy_imports_analyzer[RunInfo], hidden = resources)
+    cmd.add(dbg_source_db_output)  # First arg: <DB_PATH>
+    cmd.add(output.as_output())  # Second arg: <OUTPUT_PATH>
+    cmd.add("--buck_mode")
+    cmd.add("buck-build")
+
+    main_module = _get_main_module(ctx)
+    if main_module != None:
+        cmd.add("--main-module")
+        cmd.add(main_module)
+
+    ctx.actions.run(
+        cmd,
+        category = "py_lazy_import_analysis",
+        error_handler = python_toolchain.python_error_handler,
+    )
+
+    return DefaultInfo(default_output = output)
+
+def run_lazy_imports_library_analyzer(ctx: AnalysisContext, analyzer: RunInfo, output: Artifact, source_db: DefaultInfo) -> DefaultInfo:
+    """
+    Run analyze_library: analyze this library's own srcs and produce
+    a cache file. Cross-library resolution is deferred to analyze-binary.
+    """
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    cmd = cmd_args(analyzer, hidden = source_db.other_outputs)
+    cmd.add("analyze-library")
+    cmd.add(source_db.default_outputs[0])  # <DB_PATH>
+    cmd.add(output.as_output())  # <CACHE_OUTPUT_PATH>
+
+    ctx.actions.run(
+        cmd,
+        category = "py_lazy_import_library_analysis",
+        error_handler = python_toolchain.python_error_handler,
+    )
+
+    return DefaultInfo(default_output = output)
+
+def run_lazy_imports_cached_analysis(ctx: AnalysisContext, analyzer: RunInfo, output: Artifact, dep_caches: list[Artifact]) -> DefaultInfo:
+    """
+    Run analyze_binary: assemble the final Lifeguard .json from cached
+    library outputs. No per-file analysis happens here.
+    """
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    cmd = cmd_args(analyzer)
+    cmd.add("analyze-binary")
+    cmd.add(output.as_output())  # <OUTPUT_PATH>
+
+    cache_args = cmd_args()
+    for cache in dep_caches:
+        cache_args.add(cache)
+    cmd.add("--cache-manifest")
+    cmd.add(argfile(actions = ctx.actions, name = "safer_lazy_imports/cache-manifest.txt", args = cache_args, allow_args = True))
+
+    main_module = _get_main_module(ctx)
+    if main_module != None:
+        cmd.add("--main-module")
+        cmd.add(main_module)
+
+    ctx.actions.run(
+        cmd,
+        category = "py_lazy_import_binary_analysis",
+        error_handler = python_toolchain.python_error_handler,
+    )
+
+    return DefaultInfo(default_output = output)
diff --git a/buck2/prelude/python/linking/link_helper.bzl b/buck2/prelude/python/linking/link_helper.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/linking/link_helper.bzl
@@ -0,0 +1,130 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//cxx:link_groups_types.bzl",
+    "LINK_GROUP_MAP_ATTR",
+)
+load("@prelude//cxx:transformation_spec.bzl", "TransformationResultProvider")
+load("@prelude//decls:cxx_rules.bzl", "BUILD_INFO_ATTR")
+load("@prelude//python:internal_tools.bzl", "PythonInternalToolsInfo")
+load("@prelude//python:toolchain.bzl", "PythonToolchainInfo")
+load("@prelude//python/linking:native.bzl", "process_native_linking")
+
+LinkProviders = provider(
+    fields = {
+        "build_info_manifest_entries": provider_field(typing.Any, default = None),
+        "extensions": provider_field(typing.Any, default = None),
+        "extra": provider_field(typing.Any, default = None),
+        "extra_artifacts": provider_field(typing.Any, default = None),
+        "gc_sections_data": provider_field(typing.Any, default = None),
+        "link_args": provider_field(typing.Any, default = None),
+        "linker_map_data": provider_field(typing.Any, default = None),
+        "runtime_files": provider_field(typing.Any, default = None),
+        "shared_libraries": provider_field(typing.Any, default = None),
+    },
+)
+
+cxx_implicit_attrs = {
+    "allow_cache_upload": attrs.bool(default = False),
+    "anonymous_link_groups": attrs.bool(default = True),
+    "binary_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+    "bolt_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+    "bolt_profile": attrs.option(attrs.source(), default = None),
+    "compiler_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+    "cxx_main": attrs.source(default = "prelude//python/tools:embedded_main.cpp"),
+    "defaults": attrs.dict(key = attrs.string(), value = attrs.string(), sorted = False, default = {}),
+    "enable_distributed_thinlto": attrs.bool(default = False),
+    "executable_deps": attrs.list(attrs.dep()),
+    "executable_name": attrs.option(attrs.string(), default = None),
+    "frameworks": attrs.list(attrs.string(), default = []),
+    "header_namespace": attrs.option(attrs.string(), default = None),
+    "headers": attrs.set(attrs.source(), sorted = True, default = []),
+    "include_directories": attrs.set(attrs.string(), sorted = True, default = []),
+    "lang_compiler_flags": attrs.any(default = {}),
+    "lang_preprocessor_flags": attrs.any(default = {}),
+    "libraries": attrs.list(attrs.string(), default = []),
+    "link_group": attrs.option(attrs.string(), default = None),
+    "link_group_deps": attrs.list(attrs.dep(), default = []),
+    "link_group_map": LINK_GROUP_MAP_ATTR,
+    "link_group_min_binary_node_count": attrs.option(attrs.int(), default = None),
+    "link_group_public_deps_label": attrs.option(attrs.string(), default = None),
+    "link_ordering": attrs.option(attrs.any(), default = None),
+    "link_style": attrs.option(attrs.any(), default = None),
+    "linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+    "precompiled_header": attrs.option(attrs.dep(), default = None),
+    "prefer_stripped_native_objects": attrs.option(attrs.any(), default = None),
+    "preload_deps": attrs.list(attrs.dep(), default = []),
+    "preprocessor_flags": attrs.any(default = []),
+    "raw_headers": attrs.set(attrs.source(), sorted = True, default = []),
+    "_gen_build_info": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+    "_generated_build_info_enabled": attrs.bool(default = False),
+    "_generated_build_info_mode": attrs.enum(["full", "stable"], default = "stable"),
+    "_generated_build_info_spec": BUILD_INFO_ATTR,
+    "_late_build_info_stamping": attrs.any(default = None),
+}
+
+python_implicit_attrs = {
+    "static_extension_finder": attrs.source(default = "prelude//python/tools:static_extension_finder.py"),
+    "use_oss_python": attrs.bool(default = False),
+}
+
+def _process_native_linking_rule_impl(ctx):
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    python_internal_tools = ctx.attrs._python_internal_tools[PythonInternalToolsInfo]
+    raw_deps = ctx.attrs.deps
+    shared_libs, extensions, link_args, extra, extra_artifacts, linker_map_data, gc_sections_data, runtime_files, build_info_manifest_entries = (
+        process_native_linking(
+            ctx,
+            raw_deps,
+            python_toolchain,
+            python_internal_tools,
+            ctx.attrs.package_style,
+            ctx.attrs.allow_cache_upload,
+            generated_build_info_invalidation_deps = ctx.attrs.generated_build_info_invalidation_deps,
+            generated_build_info_invalidation_sources = ctx.attrs.generated_build_info_invalidation_sources,
+        )
+    )
+    return [
+        LinkProviders(
+            build_info_manifest_entries = build_info_manifest_entries,
+            shared_libraries = shared_libs,
+            link_args = link_args,
+            extensions = extensions,
+            extra = extra,
+            extra_artifacts = extra_artifacts,
+            gc_sections_data = gc_sections_data,
+            linker_map_data = linker_map_data,
+            runtime_files = runtime_files,
+        ),
+        DefaultInfo(),
+    ]
+
+process_native_linking_rule = rule(
+    impl = _process_native_linking_rule_impl,
+    attrs = {
+        "deps": attrs.list(attrs.dep()),  # Note: cxx-only deps here
+        "dlopen_deps": attrs.list(attrs.dep(), default = []),
+        "generated_build_info_invalidation_deps": attrs.list(attrs.dep(), default = []),
+        "generated_build_info_invalidation_sources": attrs.list(attrs.source(), default = []),
+        "package_style": attrs.any(),
+        "rpath": attrs.string(),
+        "shared_only_deps": attrs.list(attrs.dep(), default = []),
+        "static_extension_utils": attrs.source(),
+        "transformation_spec": attrs.option(
+            attrs.dep(providers = [TransformationResultProvider]),
+            default = None,
+        ),
+        "use_anon_target_for_analysis": attrs.bool(default = True),
+        "_cxx_toolchain": attrs.dep(),
+        "_python_internal_tools": attrs.dep(),
+        "_python_toolchain": attrs.dep(),
+    }
+    | cxx_implicit_attrs
+    | python_implicit_attrs,
+)
diff --git a/buck2/prelude/python/linking/native.bzl b/buck2/prelude/python/linking/native.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/linking/native.bzl
@@ -0,0 +1,550 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:resources.bzl", "gather_resources")
+load("@prelude//cxx:cxx.bzl", "create_shared_lib_link_group_specs")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_executable.bzl",
+    "CxxExecutableOutput",  # @unused Used as a type
+    "cxx_executable",
+)
+load("@prelude//cxx:cxx_sources.bzl", "CxxSrcWithFlags")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerType")
+load(
+    "@prelude//cxx:cxx_types.bzl",
+    "CxxRuleConstructorParams",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load(
+    "@prelude//cxx:groups_types.bzl",
+    "Group",
+    "GroupAttrs",
+    "GroupMapping",
+    "Traversal",
+)
+load("@prelude//cxx:headers.bzl", "cxx_get_regular_cxx_headers_layout")
+load("@prelude//cxx:link.bzl", "CxxGcSectionsData", "CxxLinkerMapData")  # @unused Used as a type
+load(
+    "@prelude//cxx:link_groups.bzl",
+    "LinkGroupLibSpec",
+    "build_link_group_info",
+    "get_link_group_info",
+)
+load(
+    "@prelude//cxx:link_groups_types.bzl",
+    "LinkGroupDefinitions",
+    "LinkGroupInfo",  # @unused Used as a type
+)
+load("@prelude//cxx:linker.bzl", "get_rpath_origin")
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "cxx_inherited_preprocessor_infos",
+)
+load("@prelude//linking:generated_build_info.bzl", "GENERATED_BUILD_INFO_OUTPUT_DIR")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkArgs",  # @unused Used as a type
+    "LinkStrategy",
+    "LinkedObject",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",
+    "LinkableGraphTSet",
+)
+load(
+    "@prelude//linking:linkables.bzl",
+    "LinkableProviders",
+    "linkables",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",  # @unused Used as a type
+    "create_shlib",
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//python:internal_tools.bzl", "PythonInternalToolsInfo")
+load(
+    "@prelude//python:python.bzl",
+    "PythonLibraryInfo",
+    "PythonLibraryManifestsTSet",
+    "python_attr_preload_deps",
+)
+load("@prelude//python:toolchain.bzl", "PackageStyle")
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load(
+    ":native_python_util.bzl", "CxxExtensionLinkInfo", "CxxExtensionLinkInfoReduced", "merge_cxx_extension_info", "reduce_cxx_extension_info"
+)  # @unused Used as a type
+
+def _get_root_link_group_specs(libs: list[LinkableProviders], extensions: dict[str, LinkableProviders]) -> list[LinkGroupLibSpec]:
+    """
+    Walk the linkable graph finding dlopen-able C++ libs.
+    """
+
+    # TODO(agallagher): We should handle `allow_embedding = False` C++ extensions
+    # here too.
+
+    specs = []
+
+    # Add link group specs for dlopen-able libs.
+    found_libs = set()
+    for dep in libs:
+        if dep.linkable_graph.label in found_libs:
+            continue
+        else:
+            found_libs.add(dep.linkable_graph.label)
+        specs.append(
+            LinkGroupLibSpec(
+                name = dep.linkable_root_info.name,
+                is_shared_lib = True,
+                root = dep.linkable_root_info,
+                label = dep.linkable_graph.nodes.value.label,
+                group = Group(
+                    name = dep.linkable_root_info.name,
+                    mappings = [
+                        GroupMapping(
+                            roots = [dep.linkable_graph.nodes.value.label],
+                            traversal = Traversal("node"),
+                        ),
+                    ],
+                    # TODO(@christylee): Add attributes to python dlopen-able libs
+                    attrs = GroupAttrs(
+                        enable_distributed_thinlto = False,
+                    ),
+                ),
+            ),
+        )
+
+    found_extensions = set()
+
+    # Add link group specs for extensions.
+    for name, extension in extensions.items():
+        if extension.linkable_graph.label in found_extensions:
+            continue
+        else:
+            found_extensions.add(extension.linkable_graph.label)
+        specs.append(
+            LinkGroupLibSpec(
+                name = name,
+                is_shared_lib = False,
+                root = extension.linkable_root_info,
+                group = Group(
+                    name = name,
+                    mappings = [
+                        GroupMapping(
+                            roots = [extension.linkable_graph.nodes.value.label],
+                            traversal = Traversal("node"),
+                        ),
+                    ],
+                    # TODO(@christylee): Add attributes to extensions
+                    attrs = GroupAttrs(
+                        enable_distributed_thinlto = False,
+                    ),
+                ),
+            ),
+        )
+
+    return specs
+
+def _get_shared_only_groups(shared_only_libs: list[LinkableProviders]) -> list[Group]:
+    """
+    Create link group mappings for shared-only libs that'll force the link to
+    link them dynamically.
+    """
+
+    groups = []
+
+    # Add link group specs for dlopen-able libs.
+    for dep in shared_only_libs:
+        if dep.linkable_graph == None:
+            continue
+        groups.append(
+            Group(
+                name = str(dep.linkable_graph.nodes.value.label.raw_target()),
+                mappings = [
+                    GroupMapping(
+                        roots = [dep.linkable_graph.nodes.value.label],
+                        traversal = Traversal("node"),
+                        preferred_linkage = Linkage("shared"),
+                    ),
+                ],
+                # TODO(@christylee): Add attributes to python dlopen-able libs
+                attrs = GroupAttrs(
+                    enable_distributed_thinlto = False,
+                ),
+            ),
+        )
+    return groups
+
+def _get_link_group_info(
+    ctx: AnalysisContext,
+    link_deps: list[LinkableProviders],
+    libs: list[LinkableProviders],
+    extensions: dict[str, LinkableProviders],
+    shared_only_libs: list[LinkableProviders],
+) -> ([LinkGroupInfo, None], list[LinkGroupLibSpec]):
+    """
+    Return the `LinkGroupInfo` and link group lib specs to use for this binary.
+    This will handle parsing the various user-specific parameters and automatic
+    link group lib spec generation for dlopen-enabled native libraries and,
+    eventually, extensions.
+    """
+
+    link_group_map = ctx.attrs.link_group_map
+    definitions = []
+
+    # Native python is only ever used with static-pic linking
+    link_strategy = LinkStrategy("static_pic")
+    if isinstance(link_group_map, Dependency):
+        if LinkGroupDefinitions in link_group_map:
+            definitions = link_group_map[LinkGroupDefinitions].definitions(ctx.label, link_strategy)
+
+    if not definitions:
+        link_group_info = get_link_group_info(ctx, [d.linkable_graph for d in link_deps], link_strategy)
+
+        # Add link group specs from user-provided link group info.
+        if link_group_info != None:
+            definitions = link_group_info.groups.values()
+
+    # Add link group specs from dlopenable C++ libraries.
+    root_specs = _get_root_link_group_specs(libs, extensions)
+
+    # We prepend the dlopen roots, so that they take precedence over
+    # user-specific ones.
+    link_group_specs = root_specs + create_shared_lib_link_group_specs(ctx, definitions)
+
+    # We add the auto-generated root specs first so it takes precedence (as
+    # we really rely on this for things to work), followed by shared-only libs
+    # to make sure we link against them dynamically. Add user-defined mappings
+    # last.
+    link_groups = [s.group for s in root_specs] + _get_shared_only_groups(shared_only_libs) + definitions
+
+    linkable_graph = LinkableGraph(
+        # label = ctx.label,
+        nodes = ctx.actions.tset(
+            LinkableGraphTSet,
+            children = (
+                [d.linkable_graph.nodes for d in link_deps]
+                + [d.linkable_graph.nodes for d in libs]
+                + [d.linkable_graph.nodes for d in extensions.values()]
+                + [d.linkable_graph.nodes for d in shared_only_libs]
+            ),
+        ),
+    )
+
+    link_group_info = build_link_group_info(
+        graph = linkable_graph,
+        groups = link_groups,
+        min_node_count = ctx.attrs.link_group_min_binary_node_count,
+    )
+
+    return (link_group_info, link_group_specs)
+
+def _compute_cxx_extension_info(ctx, deps) -> (CxxExtensionLinkInfo, CxxExtensionLinkInfoReduced):
+    executable_deps = ctx.attrs.executable_deps
+
+    if getattr(ctx.attrs, "use_anon_target_for_analysis", False):
+        shared_deps = ctx.attrs.dlopen_deps + ctx.attrs.shared_only_deps
+    else:
+        shared_deps = ctx.attrs.deps + python_attr_preload_deps(ctx)
+
+    extension_info = merge_cxx_extension_info(
+        ctx.actions,
+        deps + executable_deps,
+        # Add in dlopen-enabled libs from first-order deps.
+        shared_deps = shared_deps,
+    )
+    extension_info_reduced = reduce_cxx_extension_info(extension_info)
+    return extension_info, extension_info_reduced
+
+def _cxx_exe_allow_cache_upload(ctx) -> bool:
+    return hasattr(ctx.attrs, "exe_allow_cache_upload") and bool(ctx.attrs.exe_allow_cache_upload)
+
+def _python_source_build_info_invalidation_inputs(ctx, deps, sources):
+    """
+    Return all Python sources packaged into the binary, but only when full
+    build info is enabled. These are consumed solely as hidden inputs to the
+    build-info generator; they must not become native link inputs.
+    """
+    if not getattr(ctx.attrs, "_generated_build_info_enabled", False) or ctx.attrs._generated_build_info_mode != "full":
+        return []
+
+    manifest_sets = [dep[PythonLibraryInfo].manifests for dep in deps if PythonLibraryInfo in dep]
+    # Deliberately project sources, not extension artifacts. The latter makes
+    # native Python build-info generation eagerly build every transitive
+    # extension DSO (the behavior removed in D121806144).
+    transitive_sources = [ctx.actions.tset(PythonLibraryManifestsTSet, children = manifest_sets).project_as_args("source_artifacts")] if manifest_sets else []
+    return sources + transitive_sources
+
+def _compute_cxx_executable_info(
+    ctx,
+    extension_info_reduced,
+    static_extension_info_out,
+    inherited_preprocessor_info,
+    python_toolchain,
+    package_style,
+    allow_cache_upload,
+    generated_build_info_invalidation_inputs,
+) -> (CxxExecutableOutput, Artifact | None):
+    cxx_executable_srcs = [
+        CxxSrcWithFlags(file = ctx.attrs.cxx_main, flags = []),
+        CxxSrcWithFlags(file = ctx.attrs.static_extension_utils, flags = ["-DOSS_PYTHON=1"] if ctx.attrs.use_oss_python else []),
+        CxxSrcWithFlags(file = static_extension_info_out, flags = []),
+    ]
+
+    # All deps involved in the link.
+    link_deps = linkables(ctx.attrs.executable_deps + python_attr_preload_deps(ctx)) + extension_info_reduced.linkable_providers
+
+    link_group_info, auto_link_group_specs = _get_link_group_info(
+        ctx,
+        link_deps,
+        extension_info_reduced.dlopen_deps,
+        extension_info_reduced.unembeddable_extensions,
+        extension_info_reduced.shared_only_libs,
+    )
+
+    extra_binary_link_flags = []
+
+    extra_binary_link_flags.extend(python_toolchain.binary_linker_flags)
+
+    # Force the linker to retain all PyInit symbols for embeddable C extensions.
+    # The generated static_extension_info.cpp references these symbols via asm
+    # directives, but the linker may still drop archive members that define them
+    # if nothing else references them (e.g. when link groups or --gc-sections
+    # are in play). Adding -u flags ensures the linker treats them as undefined
+    # entry points and pulls in the necessary object files from archives.
+    pyinit_symbols = extension_info_reduced.python_module_names.values()
+    if pyinit_symbols:
+        pyinit_argsfile = ctx.actions.write(
+            "__pyinit_undefined_symbols__.argsfile",
+            cmd_args(["-u" + sym for sym in pyinit_symbols]),
+            has_content_based_path = False,
+        )
+        extra_binary_link_flags.append(cmd_args(pyinit_argsfile, format = "@{}"))
+
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+
+    # Set rpaths to find 1) the shared libs dir and the 2) runtime libs dir.
+    rpath_ref = get_rpath_origin(linker_info.type)
+    rpath_ldflag = "-Wl,-rpath,{}/".format(rpath_ref)
+    if package_style == PackageStyle("standalone"):
+        extra_binary_link_flags.append(rpath_ldflag + "../..")
+        extra_binary_link_flags.append(rpath_ldflag + "../lib")
+    else:
+        use_anon_target = getattr(ctx.attrs, "use_anon_target_for_analysis", False)
+        if use_anon_target:
+            # Under the anon target, ctx.attrs.name is "python_linking:<name>", but the
+            # link-tree dir (built by the outer python_binary rule) uses the bare name. The
+            # bare name is threaded through as the `rpath` attr; use it so the baked RPATH
+            # matches the real "<name>#link-tree" dir. (getattr(..., "name", ...) never falls
+            # back since `name` always exists, so it would emit a nonexistent RPATH.)
+            link_tree_name = ctx.attrs.rpath
+        else:
+            link_tree_name = ctx.attrs.name
+
+        rpath_ldflag_prefix = rpath_ldflag + "{}#link-tree".format(link_tree_name)
+        extra_binary_link_flags.append(rpath_ldflag_prefix + "/runtime/lib")
+        extra_binary_link_flags.append(rpath_ldflag_prefix)
+        if use_anon_target:
+            # Under the anon target the ELF is materialized at a content-addressed
+            # path, so the link-tree RPATH entries above cannot resolve the bundled
+            # runtime/lib (notably libgenerated_build_info.so) when the binary is
+            # re-exec'd via its real path. The DSO is also materialized next to the
+            # ELF under __generated_build_info__/, so fall back to it. Harmless when
+            # the DSO is not linked: the loader ignores nonexistent RPATH dirs.
+            extra_binary_link_flags.append(rpath_ldflag + GENERATED_BUILD_INFO_OUTPUT_DIR)
+
+    impl_params = CxxRuleConstructorParams(
+        rule_type = "python_binary",
+        headers_layout = cxx_get_regular_cxx_headers_layout(ctx),
+        srcs = cxx_executable_srcs,
+        extra_binary_link_flags = extra_binary_link_flags,
+        extra_link_flags = python_toolchain.linker_flags,
+        extra_preprocessors = [],
+        extra_preprocessors_info = inherited_preprocessor_info,
+        extra_link_deps = link_deps,
+        exe_shared_libs_link_tree = False,
+        force_full_hybrid_if_capable = True,
+        # Darwin requires inputs ordering for binary size and historical reasons, the ordering functions do not support stripped objects yet.
+        prefer_stripped_objects = linker_info.type != LinkerType("darwin") and ctx.attrs.prefer_stripped_native_objects,
+        link_group_info = link_group_info,
+        auto_link_group_specs = auto_link_group_specs,
+        exe_category_suffix = "python_exe",
+        extra_shared_libs = traverse_shared_library_info(
+            merge_shared_libraries(
+                actions = ctx.actions,
+                deps = [d.shared_library_info for d in extension_info_reduced.shared_only_libs],
+            ),
+            transformation_provider = None,
+        ),
+        extra_link_roots = (
+            extension_info_reduced.unembeddable_extensions.values()
+            + extension_info_reduced.dlopen_deps
+            + extension_info_reduced.shared_only_libs
+            + linkables(ctx.attrs.link_group_deps)
+        ),
+        exe_allow_cache_upload = bool(allow_cache_upload) or _cxx_exe_allow_cache_upload(ctx),
+        compiler_flags = ctx.attrs.compiler_flags,
+        lang_compiler_flags = ctx.attrs.lang_compiler_flags,
+        preprocessor_flags = ctx.attrs.preprocessor_flags,
+        lang_preprocessor_flags = ctx.attrs.lang_preprocessor_flags,
+        error_handler = python_toolchain.python_error_handler,
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, get_cxx_toolchain_info(ctx).cxx_compiler_info.allow_cache_upload),
+        precompiled_header = ctx.attrs.precompiled_header,
+        generated_build_info_invalidation_inputs = generated_build_info_invalidation_inputs,
+        _cxx_toolchain = ctx.attrs._cxx_toolchain,
+    )
+
+    executable_info = cxx_executable(ctx, impl_params)
+    return (executable_info, executable_info.build_info_manifest_entries)
+
+def process_native_linking(
+    ctx,
+    deps,
+    python_toolchain,
+    python_internal_tools: PythonInternalToolsInfo,
+    package_style,
+    allow_cache_upload,
+    generated_build_info_invalidation_deps = [],
+    generated_build_info_invalidation_sources = [],
+) -> (
+    list[(SharedLibrary, str)],
+    dict[str, (LinkedObject, Label)],
+    list[LinkArgs],
+    dict[str, typing.Any],
+    dict[str, typing.Any],
+    [CxxLinkerMapData, None],
+    [CxxGcSectionsData, None],
+    list[typing.Any],
+    Artifact | None,
+):
+    extra = {}
+    extra_artifacts = {}
+
+    extension_info, extension_info_reduced = _compute_cxx_extension_info(ctx, deps)
+    generated_build_info_invalidation_inputs = _python_source_build_info_invalidation_inputs(
+        ctx,
+        generated_build_info_invalidation_deps,
+        generated_build_info_invalidation_sources,
+    )
+
+    executable_deps = ctx.attrs.executable_deps
+
+    inherited_preprocessor_info = cxx_inherited_preprocessor_infos(executable_deps)
+
+    # Generate an additional C file as input
+    static_extension_info_out = ctx.actions.declare_output("static_extension_info.cpp", has_content_based_path = False)
+    argfile = at_argfile(
+        actions = ctx.actions,
+        name = "generate_static_extension_info.argsfile",
+        args = cmd_args(
+            extension_info.set.project_as_args("python_module_names"),
+        ),
+    )
+    cmd = cmd_args()
+    cmd.add(cmd_args(python_internal_tools.generate_static_extension_info[RunInfo]))
+    cmd.add(cmd_args(argfile))
+    cmd.add(cmd_args(static_extension_info_out.as_output(), format = "--output={}"))
+
+    ctx.actions.run(cmd, category = "generate_static_extension_info")
+
+    extra["static_extension_info"] = [DefaultInfo(default_output = static_extension_info_out)]
+
+    executable_info, build_info_manifest_entries = _compute_cxx_executable_info(
+        ctx,
+        extension_info_reduced,
+        static_extension_info_out,
+        inherited_preprocessor_info,
+        python_toolchain,
+        package_style,
+        allow_cache_upload,
+        generated_build_info_invalidation_inputs,
+    )
+    extra["native-executable"] = [DefaultInfo(default_output = executable_info.binary, sub_targets = executable_info.sub_targets)]
+    if "generated_build_info" in executable_info.sub_targets:
+        extra["generated_build_info"] = executable_info.sub_targets["generated_build_info"]
+
+    # Add sub-targets for libs.
+    for shlib in executable_info.shared_libs:
+        # TODO(agallagher) There appears to be pre-existing soname conflicts
+        # when building this (when using link groups), which prevents using
+        # `with_unique_str_sonames`.
+        if shlib.soname.is_str:
+            extra[shlib.soname.ensure_str()] = [DefaultInfo(default_output = shlib.lib.output)]
+
+    for name, group in executable_info.auto_link_groups.items():
+        extra[name] = [DefaultInfo(default_output = group.output)]
+
+    # Unembeddable extensions.
+    extensions = {
+        name: (
+            executable_info.auto_link_groups[name],
+            link.linkable_graph.nodes.value.label,
+        )
+        for name, link in extension_info_reduced.unembeddable_extensions.items()
+    }
+
+    # Put native libraries into the runtime location, as we need to unpack
+    # potentially all of them before startup.
+    shared_libs = [(s, "runtime/lib") for s in executable_info.shared_libs]
+
+    extra_artifacts.update(extension_info_reduced.artifacts)
+    shared_libs.append(
+        (
+            create_shlib(
+                soname = ctx.attrs.executable_name,
+                label = ctx.label,
+                lib = LinkedObject(
+                    output = executable_info.binary,
+                    unstripped_output = executable_info.binary,
+                    dwp = executable_info.dwp,
+                ),
+            ),
+            "runtime/bin",
+        )
+    )
+
+    link_args = executable_info.link_args
+    extra_artifacts["static_extension_finder.py"] = ctx.attrs.static_extension_finder
+
+    # The native executable runs from `runtime/bin/<binary>` inside the packaged
+    # PAR (e.g. the xar mount). build::ExternalResourceManager reads
+    # `<exe>.resources.json` next to it, but transitive C++ resources are bundled
+    # at the PAR root under `__cxx_resources__/`. Emit a manifest next to the
+    # inner binary mapping each resource to its `__cxx_resources__/` location so
+    # getResourcePath resolves at runtime in a packaged (xar/standalone) context.
+    # (The inplace case is covered separately by forwarding runtime_files.)
+    cxx_resource_names = []
+    for label_resources in gather_resources(ctx.label, deps = deps).values():
+        cxx_resource_names.extend(label_resources.keys())
+    if cxx_resource_names:
+        runtime_bin_resources_json = ctx.actions.write_json(
+            "runtime_bin_resources.json",
+            {name: "../../__cxx_resources__/" + name for name in cxx_resource_names},
+            has_content_based_path = False,
+        )
+        # Name the manifest after the in-PAR binary, which is placed at
+        # `runtime/bin/<executable_name>` (the shlib soname) — executable_name
+        # carries the runtime flavor suffix (e.g. `#native-main#...`), so this
+        # matches what getCurrentExecutablePath() resolves to at runtime.
+        extra_artifacts["runtime/bin/" + ctx.attrs.executable_name + ".resources.json"] = runtime_bin_resources_json
+
+    return (
+        shared_libs,
+        extensions,
+        link_args,
+        extra,
+        extra_artifacts,
+        executable_info.linker_map_data,
+        executable_info.gc_sections_data,
+        executable_info.runtime_files,
+        build_info_manifest_entries,
+    )
diff --git a/buck2/prelude/python/linking/native_python_util.bzl b/buck2/prelude/python/linking/native_python_util.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/linking/native_python_util.bzl
@@ -0,0 +1,424 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifacts.bzl", "ArtifactGroupInfo")
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkInfo",
+    "LinkInfos",
+    "MergedLinkInfo",
+    "ObjectsLinkable",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "DlopenableLibraryInfo",
+    "LinkableRootInfo",
+)
+load(
+    "@prelude//linking:linkables.bzl",
+    "LinkableProviders",  # @unused Used as type
+    "linkable",
+)
+load("@prelude//linking:shared_libraries.bzl", "SharedLibraryInfo")
+load("@prelude//linking:strip.bzl", "strip_debug_info")
+load("@prelude//python:python.bzl", "NativeDepsInfo", "NativeDepsInfoTSet", "PythonLibraryInfo")
+load("@prelude//python:toolchain.bzl", "NativeLinkStrategy", "PythonToolchainInfo")
+
+# Info required to link cxx_python_extensions into native python binaries
+CxxExtensionLinkInfo = provider(
+    fields = {
+        "set": provider_field(typing.Any, default = None),  # "CxxExtensionTSet"
+    },
+)
+
+CxxExtensionLinkInfoMember = record(
+    linkable_providers = field([LinkableProviders, None], None),
+    artifacts = field([dict[str, Artifact], None], None),
+    python_module_names = field([dict[str, str], None], None),
+    unembeddable_extensions = field([dict[str, LinkableProviders], None], None),
+    dlopen_deps = field([dict[Label, LinkableProviders], None], None),
+    shared_only_libs = field([dict[Label, LinkableProviders], None], None),
+)
+CxxExtensionLinkInfoReduced = record(
+    linkable_providers = field(list[LinkableProviders], []),
+    artifacts = field(dict[str, Artifact], {}),
+    python_module_names = field(dict[str, str], {}),
+    unembeddable_extensions = field(dict[str, LinkableProviders], {}),
+    dlopen_deps = field(list[LinkableProviders], []),
+    shared_only_libs = field(list[LinkableProviders], []),
+)
+
+def merge_native_deps(ctx, deps: list[Dependency], shared_deps: list[Dependency] = []) -> NativeDepsInfoTSet:
+    native_deps = {}
+    children = []
+    for dep in deps:
+        if PythonLibraryInfo in dep:
+            if dep[PythonLibraryInfo].is_native_dep:
+                native_deps[dep.label] = dep
+            else:
+                children.append(dep[PythonLibraryInfo].native_deps)
+
+        if DlopenableLibraryInfo in dep:
+            native_deps[dep.label] = dep
+        elif MergedLinkInfo in dep:
+            native_deps[dep.label] = dep
+        elif SharedLibraryInfo in dep:
+            native_deps[dep.label] = dep
+        elif ArtifactGroupInfo in dep:
+            native_deps[dep.label] = dep
+        elif PythonLibraryInfo not in dep:
+            native_deps[dep.label] = dep
+
+    dlopen_deps = {}
+    shared_only_deps = {}
+    for dep in shared_deps:
+        if DlopenableLibraryInfo in dep:
+            dlopen_deps[dep.label] = dep
+        elif MergedLinkInfo in dep and LinkableRootInfo not in dep:
+            shared_only_deps[dep.label] = dep
+
+    return ctx.actions.tset(
+        NativeDepsInfoTSet,
+        value = NativeDepsInfo(
+            native_deps = native_deps,
+            dlopen_deps = dlopen_deps,
+            shared_only_deps = shared_only_deps,
+        ),
+        children = children,
+    )
+
+def _cxx_extension_info_python_module_names(info: CxxExtensionLinkInfoMember):
+    return cmd_args(
+        ["{}:{}".format(k, v) for k, v in (info.python_module_names or {}).items()],
+        format = "--extension={}",
+    )
+
+CxxExtensionTSet = transitive_set(
+    args_projections = {
+        "python_module_names": _cxx_extension_info_python_module_names,
+    },
+)
+
+def compute_link_strategy(ctx: AnalysisContext) -> NativeLinkStrategy | None:
+    if ctx.attrs._cxx_toolchain.get(CxxToolchainInfo) == None:
+        # cxx toolchain is required
+        return None
+
+    return NativeLinkStrategy(
+        ctx.attrs.native_link_strategy or ctx.attrs._python_toolchain[PythonToolchainInfo].native_link_strategy,
+    )
+
+def merge_cxx_extension_info(
+    actions: AnalysisActions,
+    deps: list[Dependency],
+    linkable_providers: [LinkableProviders, None] = None,
+    artifacts: dict[str, typing.Any] = {},
+    python_module_names: dict[str, str] = {},
+    unembeddable_extensions: dict[str, LinkableProviders] = {},
+    shared_deps: list[Dependency] = [],
+) -> CxxExtensionLinkInfo:
+    dlopen_deps = {}
+    shared_only_libs = {}
+    for dep in shared_deps:
+        # Libs that should be linked into their own, standalone link groups
+        if DlopenableLibraryInfo in dep:
+            dlopen_deps[dep.label] = linkable(dep)
+            continue
+
+        # Try to detect prebuilt, shared-only libraries.
+        # TODO(agallagher): We need a more general way to support this, which
+        # should *just* use `preferred_linkage` (and so it supports non-prebuilt
+        # libs too), but this will require hoisting the rules first-order deps
+        # up the tree as `dlopen_deps` so that we link them properly.
+        if MergedLinkInfo in dep and LinkableRootInfo not in dep:
+            shared_only_libs[dep.label] = linkable(dep)
+
+    children = []
+    for dep in deps:
+        info = dep.get(CxxExtensionLinkInfo)
+        if info != None:
+            children.append(info.set)
+
+    return CxxExtensionLinkInfo(
+        set = actions.tset(
+            CxxExtensionTSet,
+            value = CxxExtensionLinkInfoMember(
+                linkable_providers = linkable_providers or None,
+                artifacts = artifacts or None,
+                python_module_names = python_module_names or None,
+                unembeddable_extensions = unembeddable_extensions or None,
+                dlopen_deps = dlopen_deps or None,
+                shared_only_libs = shared_only_libs or None,
+            ),
+            children = children,
+        ),
+    )
+
+def reduce_cxx_extension_info(link_info: CxxExtensionLinkInfo) -> CxxExtensionLinkInfoReduced:
+    linkable_providers = []
+    artifacts = {}
+    python_module_names = {}
+    unembeddable_extensions = {}
+    dlopen_deps = {}
+    shared_only_libs = {}
+
+    for info in link_info.set.traverse():
+        if info.linkable_providers:
+            linkable_providers.append(info.linkable_providers)
+        if info.artifacts:
+            artifacts.update(info.artifacts)
+        if info.python_module_names:
+            python_module_names.update(info.python_module_names)
+        if info.unembeddable_extensions:
+            unembeddable_extensions.update(info.unembeddable_extensions)
+        if info.dlopen_deps:
+            dlopen_deps.update(info.dlopen_deps)
+        if info.shared_only_libs:
+            shared_only_libs.update(info.shared_only_libs)
+
+    return CxxExtensionLinkInfoReduced(
+        linkable_providers = linkable_providers,
+        artifacts = artifacts,
+        python_module_names = python_module_names,
+        unembeddable_extensions = unembeddable_extensions,
+        dlopen_deps = dlopen_deps.values(),
+        shared_only_libs = shared_only_libs.values(),
+    )
+
+def rewrite_static_symbols(
+    ctx: AnalysisContext,
+    suffix: str,
+    pic_objects: list[Artifact],
+    non_pic_objects: list[Artifact],
+    # NOTE: at the moment, we only compile debuggable PIC objects.
+    debuggable_pic_objects: list[Artifact],
+    libraries: dict[LibOutputStyle, LinkInfos],
+    cxx_toolchain: CxxToolchainInfo,
+    suffix_all: bool = False,
+    suffix_exclude_rtti: bool = False,
+) -> dict[LibOutputStyle, LinkInfos]:
+    symbols_file = _write_syms_file(
+        ctx = ctx,
+        name = ctx.label.name + "_rename_syms",
+        objects = non_pic_objects,
+        suffix = suffix,
+        cxx_toolchain = cxx_toolchain,
+        suffix_all = suffix_all,
+        suffix_exclude_rtti = suffix_exclude_rtti,
+    )
+    static_objects, stripped_static_objects = suffix_symbols(ctx, suffix, non_pic_objects, symbols_file, cxx_toolchain)
+
+    symbols_file_pic = _write_syms_file(
+        ctx = ctx,
+        name = ctx.label.name + "_rename_syms_pic",
+        objects = pic_objects,
+        suffix = suffix,
+        cxx_toolchain = cxx_toolchain,
+        suffix_all = suffix_all,
+        suffix_exclude_rtti = suffix_exclude_rtti,
+    )
+    static_pic_objects, stripped_static_pic_objects = suffix_symbols(ctx, suffix, pic_objects, symbols_file_pic, cxx_toolchain)
+
+    debuggable_static_pic_objects, _ = suffix_symbols(ctx, suffix, debuggable_pic_objects, symbols_file_pic, cxx_toolchain)
+
+    static_info = libraries[LibOutputStyle("archive")].default
+    updated_static_info = LinkInfo(
+        name = static_info.name,
+        pre_flags = static_info.pre_flags,
+        post_flags = static_info.post_flags,
+        linkables = [static_objects],
+        external_debug_info = static_info.external_debug_info,
+        metadata = static_info.metadata,
+    )
+    updated_stripped_static_info = None
+    static_info = libraries[LibOutputStyle("archive")].stripped
+    if static_info != None:
+        updated_stripped_static_info = LinkInfo(
+            name = static_info.name,
+            pre_flags = static_info.pre_flags,
+            post_flags = static_info.post_flags,
+            linkables = [stripped_static_objects],
+            metadata = static_info.metadata,
+        )
+
+    static_pic_info = libraries[LibOutputStyle("pic_archive")].default
+    updated_static_pic_info = LinkInfo(
+        name = static_pic_info.name,
+        pre_flags = static_pic_info.pre_flags,
+        post_flags = static_pic_info.post_flags,
+        linkables = [static_pic_objects],
+        external_debug_info = static_pic_info.external_debug_info,
+        metadata = static_pic_info.metadata,
+    )
+    updated_stripped_static_pic_info = None
+    static_pic_info = libraries[LibOutputStyle("pic_archive")].stripped
+    if static_pic_info != None:
+        updated_stripped_static_pic_info = LinkInfo(
+            name = static_pic_info.name,
+            pre_flags = static_pic_info.pre_flags,
+            post_flags = static_pic_info.post_flags,
+            linkables = [stripped_static_pic_objects],
+            metadata = static_pic_info.metadata,
+        )
+    updated_debuggable_static_pic_info = None
+    debuggable_static_pic_info = libraries[LibOutputStyle("pic_archive")].debuggable
+    if debuggable_static_pic_info != None:
+        updated_debuggable_static_pic_info = LinkInfo(
+            name = debuggable_static_pic_info.name,
+            pre_flags = debuggable_static_pic_info.pre_flags,
+            post_flags = debuggable_static_pic_info.post_flags,
+            linkables = [debuggable_static_pic_objects],
+            external_debug_info = debuggable_static_pic_info.external_debug_info,
+            metadata = debuggable_static_pic_info.metadata,
+        )
+
+    updated_libraries = {
+        LibOutputStyle("archive"): LinkInfos(
+            default = updated_static_info,
+            stripped = updated_stripped_static_info,
+        ),
+        LibOutputStyle("pic_archive"): LinkInfos(
+            default = updated_static_pic_info,
+            stripped = updated_stripped_static_pic_info,
+            # non-pic debuggable isn't being built for now, since debuggable is
+            # used for transformation_spec which is intended only for pic
+            # builds. Also, native python uses PIC by default.
+            debuggable = updated_debuggable_static_pic_info,
+            # We duplicate `optimized` as `stripped` for now because for focused
+            # debugging purposes, native Python stripped info uses `-O3` and
+            # strips, which is close enough to C++ focused debugging.
+            optimized = updated_stripped_static_pic_info,
+        ),
+    }
+    return updated_libraries
+
+def _write_syms_file(
+    ctx: AnalysisContext,
+    name: str,
+    objects: list[Artifact],
+    suffix: str,
+    cxx_toolchain: CxxToolchainInfo,
+    suffix_all: bool = False,
+    suffix_exclude_rtti: bool = False,
+) -> Artifact:
+    """
+    Take a list of objects and append a suffix to all  defined symbols.
+    """
+    nm = cxx_toolchain.binary_utilities_info.nm
+    symbols_file = ctx.actions.declare_output(name, has_content_based_path = True)
+
+    objects_argsfile = ctx.actions.write(name + ".py_objects_argsfile", objects, has_content_based_path = True)
+    objects_args = cmd_args(objects_argsfile, hidden = objects)
+
+    script_env = {
+        "NM": nm,
+        "OBJECTS": objects_args,
+        "SYMSFILE": symbols_file.as_output(),
+    }
+
+    # Compile symbols defined by all object files into a de-duplicated list of symbols to rename
+    # --no-sort tells nm not to sort the output because we are sorting it to dedupe anyway
+    # --defined-only prints only the symbols defined by this extension this way we won't rename symbols defined externally e.g. PyList_GetItem, etc...
+    # --extern-only if suffix_all is not set, we are only interested in the externally visible PyInit symbols
+    # -j print only the symbol name
+    # sed removes filenames generated from objcopy (lines ending with ":") and empty lines
+    # sort -u sorts the combined list of symbols and removes any duplicate entries
+    # using awk we format the symbol names 'PyInit_hello' followed by the symbol name with the suffix appended to create the input file for objcopy
+    # objcopy uses a list of symbol name followed by updated name e.g. 'PyInit_hello PyInit_hello_package_module'
+    script = (
+        "set -euo pipefail; "  # fail if any command in the script fails
+        + '"$NM" --no-sort --defined-only -j {}@"$OBJECTS" | sed "/:$/d;/^$/d"'
+    ).format("--extern-only " if not suffix_all else "")
+
+    if not suffix_all:
+        script += ' | grep -E "^_?PyInit_"'
+
+    # Don't suffix asan symbols, as they shouldn't conflict, and suffixing
+    # prevents deduplicating all the module constructors, which can be really
+    # expensive to run.  We need to keep ODR guards but remove all sanitizer
+    # globals. This removes:
+    # __asan_*, ___asan_*, __tsan_*, ___tsan_*, __sanitizer_*, ___sanitizer_*,
+    # asan.module_ctor, asan.module_dtor, tsan.module_ctor, tsan.module_dtor
+    script += ' | grep -v "\\(\\(^_\\?__\\(\\(a\\|t\\)san\\|\\(sanitizer\\)\\)_\\)\\|\\(^\\(a\\|t\\)san.module_\\(c\\|d\\)tor\\)\\)"'
+    if suffix_exclude_rtti:
+        # We also should not rename _ZTI... RTTI type info symbols as whole
+        # program devirtualisation uses them to detect subclasses.
+        script += " | grep -v '^_ZTI'"
+
+    script += ' | awk \'{{print $1" "$1"_{suffix}"}}\' | sort -u > '.format(suffix = suffix) + '"$SYMSFILE";'
+
+    ctx.actions.run(
+        [
+            "/usr/bin/env",
+            "bash",
+            "-c",
+            script,
+        ],
+        env = script_env,
+        category = "write_syms_file",
+        identifier = "{}_write_syms_file".format(symbols_file.basename),
+    )
+
+    return symbols_file
+
+def suffix_symbols(
+    ctx: AnalysisContext, suffix: str, objects: list[Artifact], symbols_file: Artifact, cxx_toolchain: CxxToolchainInfo
+) -> (ObjectsLinkable, ObjectsLinkable):
+    """
+    Take a list of objects and append a suffix to all  defined symbols.
+    """
+    objcopy = cxx_toolchain.binary_utilities_info.objcopy
+
+    artifacts = []
+    stripped_artifacts = []
+    for obj in objects:
+        base, name = paths.split_extension(obj.short_path)
+        updated_name = "_".join([base, suffix, name])
+        artifact = ctx.actions.declare_output(updated_name, has_content_based_path = True)
+
+        script_env = {
+            "OBJCOPY": objcopy,
+            "ORIGINAL": obj,
+            "OUT": artifact.as_output(),
+            "SYMSFILE": symbols_file,
+        }
+
+        script = (
+            "set -euo pipefail; "  # fail if any command in the script fails
+            + '"$OBJCOPY" --redefine-syms="$SYMSFILE" "$ORIGINAL" "$OUT"'  # using objcopy we pass in the symbols file to re-write the original symbol name to the now suffixed version
+        )
+
+        # Usage: objcopy [option(s)] in-file [out-file]
+        ctx.actions.run(
+            [
+                "/usr/bin/env",
+                "bash",
+                "-c",
+                script,
+            ],
+            env = script_env,
+            category = "suffix_symbols",
+            identifier = updated_name,
+        )
+
+        artifacts.append(artifact)
+        updated_base, _ = paths.split_extension(artifact.short_path)
+        stripped_artifacts.append(strip_debug_info(ctx.actions, updated_base + ".stripped.o", artifact, cxx_toolchain, has_content_based_path = True))
+
+    default = ObjectsLinkable(
+        objects = artifacts,
+        linker_type = cxx_toolchain.linker_info.type,
+    )
+    stripped = ObjectsLinkable(
+        objects = stripped_artifacts,
+        linker_type = cxx_toolchain.linker_info.type,
+    )
+    return default, stripped
diff --git a/buck2/prelude/python/linking/omnibus.bzl b/buck2/prelude/python/linking/omnibus.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/linking/omnibus.bzl
@@ -0,0 +1,124 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load(
+    "@prelude//cxx:omnibus.bzl",
+    "create_omnibus_libraries",
+    "get_excluded",
+    "get_omnibus_graph",
+    "get_roots",
+)
+load("@prelude//linking:link_info.bzl", "LinkedObject")  # @unused Used as a type
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "create_linkable_graph",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",  # @unused Used as a type
+)
+load("@prelude//python:python.bzl", "python_attr_preload_deps")
+load(
+    "@prelude//python:toolchain.bzl",
+    "PythonToolchainInfo",  # @unused Used as a type
+)
+
+OmnibusMetadataInfo = provider(
+    # @unsorted-dict-items
+    fields = {"omnibus_libs": provider_field(typing.Any, default = None), "omnibus_graph": provider_field(typing.Any, default = None)},
+)
+
+def process_omnibus_linking(
+    ctx: AnalysisContext,
+    deps: list[Dependency],
+    extensions: dict[str, (LinkedObject, Label)],
+    python_toolchain: PythonToolchainInfo,
+    extra: dict[str, typing.Any],
+) -> (
+    list[(SharedLibrary, str)],
+    dict[str, (LinkedObject, Label)],
+):
+    # If we're using omnibus linking, re-link libraries and extensions and
+    # update the libraries we'll pull into the final binary.
+
+    # Collect omnibus info from deps.
+    linkable_graph = create_linkable_graph(
+        ctx,
+        deps = deps,
+    )
+
+    omnibus_graph = get_omnibus_graph(
+        graph = linkable_graph,
+        # Add in any potential native root targets from our first-order deps.
+        roots = get_roots(deps),
+        # Exclude preloaded deps from omnibus linking, to prevent preloading
+        # the monolithic omnibus library.
+        excluded = get_excluded(deps = python_attr_preload_deps(ctx)),
+    )
+
+    # Link omnibus libraries.
+    omnibus_libs = create_omnibus_libraries(
+        ctx,
+        omnibus_graph,
+        extra_ldflags = (
+            # TODO(agallagher): Should these "binary" linker flags comes
+            # from the Python toolchain instead?
+            get_cxx_toolchain_info(ctx).linker_info.binary_linker_flags + python_toolchain.linker_flags + ctx.attrs.linker_flags
+        ),
+        prefer_stripped_objects = ctx.attrs.prefer_stripped_native_objects,
+        enable_distributed_thinlto = ctx.attrs.enable_distributed_thinlto,
+        anonymous = ctx.attrs.deduplicate_merged_link_roots,
+    )
+
+    # Extract re-linked extensions.
+    extensions = {dest: (omnibus_libs.roots[label].shared_library, label) for dest, (_, label) in extensions.items()}
+    shared_libs = [(shlib, "") for shlib in omnibus_libs.libraries]
+
+    omnibus_providers = []
+
+    if omnibus_libs.omnibus != None:
+        omnibus_link_result = omnibus_libs.omnibus
+        omnibus_linked_obj = omnibus_link_result.linked_object
+
+        sub_targets = {}
+        sub_targets["dwp"] = [DefaultInfo(default_output = omnibus_linked_obj.dwp if omnibus_linked_obj.dwp else None)]
+        if omnibus_link_result.linker_map_data != None:
+            sub_targets["linker-map"] = [
+                DefaultInfo(default_output = omnibus_link_result.linker_map_data.map, other_outputs = [omnibus_link_result.linker_map_data.binary])
+            ]
+        omnibus_info = DefaultInfo(
+            default_output = omnibus_linked_obj.output,
+            sub_targets = sub_targets,
+        )
+    else:
+        omnibus_info = DefaultInfo()
+    omnibus_providers.append(omnibus_info)
+
+    if python_toolchain.emit_omnibus_metadata:
+        omnibus_providers.append(
+            OmnibusMetadataInfo(
+                omnibus_libs = omnibus_libs,
+                omnibus_graph = omnibus_graph,
+            ),
+        )
+
+        exclusion_roots = ctx.actions.write_json("omnibus/exclusion_roots.json", omnibus_libs.exclusion_roots, has_content_based_path = False)
+        extra["omnibus-exclusion-roots"] = [DefaultInfo(default_output = exclusion_roots)]
+
+        roots = ctx.actions.write_json("omnibus/roots.json", omnibus_libs.roots, has_content_based_path = False)
+        extra["omnibus-roots"] = [DefaultInfo(default_output = roots)]
+
+        omnibus_excluded = ctx.actions.write_json("omnibus/excluded.json", omnibus_libs.excluded, has_content_based_path = False)
+        extra["omnibus-excluded"] = [DefaultInfo(default_output = omnibus_excluded)]
+
+        omnibus_graph_json = ctx.actions.write_json("omnibus_graph.json", omnibus_graph, has_content_based_path = False)
+        extra["linkable-graph"] = [DefaultInfo(default_output = omnibus_graph_json)]
+
+    extra["omnibus"] = omnibus_providers
+    return shared_libs, extensions
diff --git a/buck2/prelude/python/make_py_package.bzl b/buck2/prelude/python/make_py_package.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/make_py_package.bzl
@@ -0,0 +1,1410 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Rule for the inplace pex builder, and some utility methods for generic pex builder
+execution
+"""
+
+load("@prelude//:artifact_tset.bzl", "project_artifacts")
+load("@prelude//:local_only.bzl", "package_python_locally")
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//cxx:cxx_library_utility.bzl",
+    "cxx_is_gnu",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "DepMetadata",
+    "LinkArgs",
+    "LinkInfosTSet",
+    "dedupe_dep_metadata",
+    "get_link_info",
+    "truncate_dep_metadata",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",  # @unused Used as a type
+    "gen_shared_libs_action",
+    "traverse_shared_library_info",
+    "zip_shlibs",
+)
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//python:manifest.bzl", "create_manifest_for_entries")
+load("@prelude//python:python.bzl", "python_attr_preload_deps")
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load(":interface.bzl", "EntryPoint", "EntryPointKind", "PythonLibraryManifestsInterface")
+load(":internal_tools.bzl", "PythonInternalToolsInfo")
+load(":manifest.bzl", "ManifestInfo")  # @unused Used as a type
+load(":python.bzl", "manifests_to_interface")
+load(":python_library.bzl", "gather_dep_libraries")
+load(":toolchain.bzl", "PackageStyle", "PythonToolchainInfo", "get_package_style")
+
+# This represents the input to the creation of a Pex. Manifests provide source
+# files, extensions are native extensions, and compile indicates whether we
+# should also include bytecode from manifests.
+PexModules = record(
+    manifests = field(PythonLibraryManifestsInterface),
+    extensions = field(ManifestInfo | None, None),
+    extra_manifests = field(ManifestInfo | None, None),
+    repl_manifests = field(PythonLibraryManifestsInterface | None, None),
+    compile = field(bool, False),
+)
+
+# The output of pex creation. It's everything needed to make the DefaultInfo and RunInfo
+# providers.
+PexProviders = record(
+    default_output = field(Artifact),
+    other_outputs = list[ArgLike],
+    other_outputs_prefix = str | None,
+    hidden_resources = list[ArgLike],
+    sub_targets = dict[str, list[Provider]],
+    run_cmd = cmd_args,
+    dbg_source_db = field(Artifact | None, None),
+)
+
+ManifestModule = record(
+    manifest = ArgLike,
+    artifacts = list[ArgLike],
+)
+
+def make_py_package_providers(ctx: AnalysisContext, manifest_identifier: str, pex: PexProviders) -> list[Provider]:
+    providers = [
+        make_default_info(pex),
+        make_run_info(pex),
+    ]
+
+    # UnixEnv is used by other rules like conda_package that
+    # copies python libraries/binaries to the output directory.
+    # Only standalone works here since inplace uses link tree.
+    if manifest_identifier == "standalone":
+        providers.append(
+            create_unix_env_info(
+                actions = ctx.actions,
+                env = UnixEnv(
+                    label = ctx.label,
+                    binaries = [
+                        create_manifest_for_entries(
+                            ctx = ctx,
+                            name = "unix_env_for_{}".format(manifest_identifier),
+                            entries = [
+                                (ctx.label.name, pex.default_output, ""),
+                            ],
+                        ),
+                    ],
+                ),
+            )
+        )
+
+    return providers
+
+def _live_par_generated_files(
+    ctx: AnalysisContext,
+    output: Artifact,
+    python_toolchain: PythonToolchainInfo,
+    python_internal_tools: PythonInternalToolsInfo,
+    build_args: list[ArgLike],
+    main: EntryPoint,
+    preload_libraries: ArgLike,
+    output_suffix: str,
+    linktree_suffix: str = "#link-tree",
+) -> list[(Artifact, str)]:
+    artifacts = []
+    artifacts.append((python_internal_tools.run_lpar_main, "__run_lpar_main__.py"))
+
+    lpar_bootstrap = ctx.actions.declare_output("_bootstrap.sh{}".format(output_suffix), has_content_based_path = False)
+    gen_bootstrap = cmd_args(python_toolchain.gen_lpar_bootstrap[RunInfo])
+
+    # Add passthrough args
+    gen_bootstrap.add(cmd_args([cmd_args(arg, replace_regex = ("--passthrough=", "")) for arg in build_args]))
+
+    # in tools/make_par/buck.py we add "os.curdir" to the ld_library_path
+    gen_bootstrap.add("--ld-library=.")
+    for lib_path in python_toolchain.native_library_runtime_paths:
+        gen_bootstrap.add("--ld-library={}".format(lib_path))
+
+    if main[0] == EntryPointKind("module"):
+        gen_bootstrap.add(["--main-module", main[1]])
+    else:
+        gen_bootstrap.add(["--main-function", main[1]])
+    if ctx.attrs.runtime_env:
+        for k, v in ctx.attrs.runtime_env.items():
+            gen_bootstrap.add(cmd_args(["--runtime_env={}={}".format(k, v)]))
+    if ctx.attrs.interpreter_args:
+        gen_bootstrap.add(cmd_args(["--interpreter-flags={}".format(json.encode(ctx.attrs.interpreter_args))]))
+
+    gen_bootstrap.add([
+        "--python",
+        python_toolchain.interpreter,
+    ])
+    gen_bootstrap.add(["--main-runner", python_toolchain.main_runner])
+
+    gen_bootstrap.add(preload_libraries)
+
+    gen_bootstrap.add(["--linktree-suffix", linktree_suffix])
+    gen_bootstrap.add(["--bootstrap-output", lpar_bootstrap.as_output()])
+    gen_bootstrap.add(["--output", output.as_output()])
+    ctx.actions.run(gen_bootstrap, category = "par", identifier = "lpar_gen_bootstrap{}".format(output_suffix))
+    artifacts.append((lpar_bootstrap, "_bootstrap.sh"))
+    return artifacts
+
+def _live_par_windows_bootstrap(
+    ctx: AnalysisContext,
+    output: Artifact,
+    python_toolchain: PythonToolchainInfo,
+    python_internal_tools: PythonInternalToolsInfo,
+    main: EntryPoint,
+    preload_libraries: ArgLike,
+    symlink_tree_path: Artifact,
+    output_suffix: str,
+):
+    # Windows can't use _bootstrap.sh, so reuse existing make_py_package_inplace tool
+    # to generate a Python bootstrap script.
+    bootstrap = cmd_args(python_internal_tools.make_py_package_inplace)
+    bootstrap.add(
+        _pex_bootstrap_args(
+            python_toolchain,
+            main,
+            output,
+            preload_libraries,
+            symlink_tree_path,
+            PackageStyle("inplace"),
+            True,
+        )
+    )
+    if ctx.attrs.runtime_env:
+        for k, v in ctx.attrs.runtime_env.items():
+            bootstrap.add(cmd_args(["--runtime_env", "{}={}".format(k, v)]))
+    for flag in ctx.attrs.interpreter_args:
+        bootstrap.add(cmd_args(["--python-interpreter-flags={}".format(flag)]))
+    ctx.actions.run(bootstrap, category = "par", identifier = "bootstrap{}".format(output_suffix))
+
+def make_default_info(pex: PexProviders) -> Provider:
+    return DefaultInfo(
+        default_output = pex.default_output,
+        other_outputs = pex.other_outputs + pex.hidden_resources,
+        sub_targets = pex.sub_targets,
+    )
+
+def make_run_info(pex: PexProviders, run_with_inplace: bool = False) -> Provider:
+    if run_with_inplace and "inplace" in pex.sub_targets:
+        # If running with inplace, we want to use the RunInfo of inplace subtarget.
+        return pex.sub_targets["inplace"][1]
+
+    return RunInfo(pex.run_cmd)
+
+def _srcs(srcs: list[typing.Any], format = "{}") -> cmd_args:
+    args = cmd_args()
+    for src in srcs:
+        args.add(cmd_args(src, format = format))
+    return args
+
+def _fail_at_build_time(ctx: AnalysisContext, python_internal_tools: PythonInternalToolsInfo, msg: str, suffix: str) -> PexProviders:
+    error_message = ctx.actions.write("__error_message{}".format(suffix), msg, has_content_based_path = False)
+    dummy_output = ctx.actions.declare_output("__dummy_output{}".format(suffix), has_content_based_path = False)
+    cmd = cmd_args([
+        python_internal_tools.fail_with_message,
+        error_message,
+        dummy_output.as_output(),
+    ])
+    ctx.actions.run(cmd, category = "par", identifier = "failure{}".format(suffix))
+    return PexProviders(
+        default_output = dummy_output,
+        other_outputs = [],
+        other_outputs_prefix = None,
+        hidden_resources = [],
+        # Stub `link-tree` so e.g. `target[outplace][link-tree]` resolves and
+        # surfaces the build-time failure message. Without this, sub-target
+        # lookup fails at analysis time with "no such sub-target" and the user
+        # never sees the underlying error.
+        sub_targets = {
+            "link-tree": [DefaultInfo(default_output = dummy_output)],
+        },
+        run_cmd = cmd_args(),
+    )
+
+def _fail(ctx: AnalysisContext, python_internal_tools: PythonInternalToolsInfo, suffix: str, msg: str) -> PexProviders:
+    if suffix:
+        return _fail_at_build_time(ctx, python_internal_tools, msg, suffix)
+
+    # suffix is empty, which means this is the default subtarget. All failures must
+    # occur at analysis time
+    fail(msg)
+
+def make_py_package(
+    ctx: AnalysisContext,
+    python_toolchain: PythonToolchainInfo,
+    python_internal_tools: PythonInternalToolsInfo,
+    # A rule-provided tool to use to build the PEX.
+    make_py_package_cmd: RunInfo | None,
+    package_style: PackageStyle,
+    build_args: list[ArgLike],
+    pex_modules: PexModules,
+    shared_libraries: list[(SharedLibrary, str)],
+    preload_labels: set[Label],
+    main: EntryPoint,
+    allow_cache_upload: bool,
+    link_args: list[LinkArgs] = [],
+    debuginfo_files: list[(str | (str, SharedLibrary, str), Artifact)] = [],
+    manifest_entries_overlay: Artifact | None = None,
+) -> PexProviders:
+    """
+    Passes a standardized set of flags to a `make_py_package` binary to create a python
+    "executable".
+
+    Arguments:
+        - python_toolchain: Used to locate the PEX binaries.
+        - package_style: How to package this binary. Might be controlled by the
+          toolchain, but also by the rule.
+        - build_args: Extra arguments to pass to the PEX binary.
+        - pex_modules: Manifests for sources to package.
+        - shared_libraries: Shared libraries to link in. Mapping of soname to
+          artifact and whether they should be preloaded.
+        - main: the name of the entry point to execute when running the
+          resulting binary.
+    """
+    srcs = []
+    srcs.extend(pex_modules.manifests.src_manifests())
+
+    if pex_modules.extensions:
+        srcs.append(pex_modules.extensions.manifest)
+
+    if ctx.attrs._exec_os_type[OsLookup].os == Os("macos"):
+        # preload_deps might include additional shared libraries which macOS will
+        # not be able to load unless they're inside the PAR.
+        _, preload_deps_shared_libraries = gather_dep_libraries(python_attr_preload_deps(ctx))
+        shared_libraries = shared_libraries + [
+            (lib, "") for info in preload_deps_shared_libraries for lib in traverse_shared_library_info(info, transformation_provider = None)
+        ]
+
+    preload_libraries = _preload_libraries_args(
+        ctx = ctx,
+        shared_libraries = [(shlib, libdir) for shlib, libdir in shared_libraries if shlib.label in preload_labels],
+    )
+
+    # Add link metadata to manifest_module_entries if requested.
+    manifest_module_entries = _add_dep_metadata_to_manifest_module(ctx, shared_libraries, link_args, python_toolchain)
+    generated_files = []
+
+    startup_functions_loader = generate_startup_function_loader(ctx, manifest_module_entries)
+    startup_function = ctx.actions.write_json(
+        "manifest/startup_function_loader.manifest",
+        [
+            ["__par__/__startup_function_loader__.py", startup_functions_loader, "prelude//python:make_py_package.bzl"],
+        ],
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+    generated_files.append((startup_functions_loader, "__par__/__startup_function_loader__.py"))
+
+    manifest_module = _generate_manifest_module(ctx, manifest_module_entries, manifest_entries_overlay, python_toolchain, python_internal_tools, srcs)
+    if manifest_module:
+        generated_files.append((manifest_module.artifacts[1], "__manifest__.py"))
+        generated_files.append((manifest_module.artifacts[0], "__manifest__.json"))
+
+    common_modules_args, dep_artifacts, debug_artifacts = _pex_modules_common_args(
+        ctx,
+        pex_modules,
+        [startup_function] if startup_function else [],
+        shared_libraries,
+        debuginfo_files = debuginfo_files,
+    )
+
+    default = _make_py_package_wrapper(
+        ctx,
+        python_toolchain,
+        python_internal_tools,
+        make_py_package_cmd,
+        package_style,
+        build_args,
+        shared_libraries,
+        generated_files,
+        preload_libraries,
+        common_modules_args,
+        dep_artifacts,
+        debug_artifacts,
+        main,
+        manifest_module,
+        pex_modules,
+        output_suffix = "",
+        allow_cache_upload = allow_cache_upload,
+    )
+
+    # lets make a shell
+    if ctx.attrs.repl_main:
+        repl_deps, _ = gather_dep_libraries(ctx.attrs.repl_only_deps)
+        repl_manifests = manifests_to_interface(repl_deps[0].manifests)
+
+        repl_pex_modules = PexModules(
+            manifests = pex_modules.manifests,
+            extra_manifests = pex_modules.extra_manifests,
+            extensions = pex_modules.extensions,
+            repl_manifests = repl_manifests,
+            compile = pex_modules.compile,
+        )
+
+        repl_common_modules_args, repl_dep_artifacts, repl_debug_artifacts = _pex_modules_common_args(
+            ctx,
+            repl_pex_modules,
+            [startup_function] if startup_function else [],
+            shared_libraries,
+            debuginfo_files = debuginfo_files,
+            suffix = "_repl",
+        )
+
+        default.sub_targets["repl"] = make_py_package_providers(
+            ctx,
+            "repl",
+            _make_py_package_wrapper(
+                ctx,
+                python_toolchain,
+                python_internal_tools,
+                make_py_package_cmd,
+                PackageStyle("inplace"),
+                build_args,
+                shared_libraries,
+                generated_files,
+                preload_libraries,
+                repl_common_modules_args,
+                repl_dep_artifacts,
+                repl_debug_artifacts,
+                (EntryPointKind("function"), ctx.attrs.repl_main),
+                manifest_module,
+                repl_pex_modules,
+                output_suffix = "-repl",
+                allow_cache_upload = allow_cache_upload,
+            ),
+        )
+
+    for style in PackageStyle.values():
+        pex_providers = (
+            default
+            if style == package_style.value
+            else _make_py_package_wrapper(
+                ctx,
+                python_toolchain,
+                python_internal_tools,
+                make_py_package_cmd,
+                PackageStyle(style),
+                build_args,
+                shared_libraries,
+                generated_files,
+                preload_libraries,
+                common_modules_args,
+                dep_artifacts,
+                debug_artifacts,
+                main,
+                manifest_module,
+                pex_modules,
+                output_suffix = "-{}".format(style),
+                allow_cache_upload = allow_cache_upload,
+            )
+        )
+        default.sub_targets[style] = make_py_package_providers(
+            ctx,
+            style,
+            pex_providers,
+        )
+
+    # cpp binaries already emit a `debuginfo` subtarget with a different format,
+    # so we opt to use a more specific subtarget
+    default.sub_targets["par-debuginfo"] = _debuginfo_subtarget(ctx, debug_artifacts)
+    return default
+
+def _make_py_package_wrapper(
+    ctx: AnalysisContext,
+    python_toolchain: PythonToolchainInfo,
+    python_internal_tools: PythonInternalToolsInfo,
+    make_py_package_cmd: RunInfo | None,
+    package_style: PackageStyle,
+    build_args: list[ArgLike],
+    shared_libraries: list[(SharedLibrary, str)],
+    generated_files: list[(Artifact, str)],
+    preload_libraries: cmd_args,
+    common_modules_args: cmd_args,
+    dep_artifacts: list[ArgLike],
+    debug_artifacts: list[(str | (str, SharedLibrary, str), ArgLike)],
+    main: EntryPoint,
+    manifest_module: ManifestModule | None,
+    pex_modules: PexModules,
+    output_suffix: str,
+    allow_cache_upload: bool,
+) -> PexProviders:
+    if package_style in [PackageStyle("inplace"), PackageStyle("outplace")] and ctx.attrs.use_rust_make_par:
+        return _make_py_package_live(
+            ctx,
+            python_toolchain.make_py_package_live[RunInfo],
+            pex_modules,
+            build_args,
+            preload_libraries,
+            main,
+            shared_libraries,
+            generated_files,
+            python_toolchain,
+            python_internal_tools,
+            output_suffix,
+            package_style,
+            allow_cache_upload,
+        )
+    return _make_py_package_impl(
+        ctx,
+        python_toolchain,
+        python_internal_tools,
+        make_py_package_cmd,
+        package_style,
+        build_args,
+        preload_libraries,
+        common_modules_args,
+        dep_artifacts,
+        debug_artifacts,
+        main,
+        manifest_module,
+        pex_modules,
+        output_suffix = output_suffix,
+        allow_cache_upload = allow_cache_upload,
+    )
+
+def _make_py_package_impl(
+    ctx: AnalysisContext,
+    python_toolchain: PythonToolchainInfo,
+    python_internal_tools: PythonInternalToolsInfo,
+    make_py_package_cmd: RunInfo | None,
+    package_style: PackageStyle,
+    build_args: list[ArgLike],
+    preload_libraries: cmd_args,
+    common_modules_args: cmd_args,
+    dep_artifacts: list[ArgLike],
+    debug_artifacts: list[(str | (str, SharedLibrary, str), ArgLike)],
+    main: EntryPoint,
+    manifest_module: ManifestModule | None,
+    pex_modules: PexModules,
+    output_suffix: str,
+    allow_cache_upload: bool,
+) -> PexProviders:
+    name = "{}{}".format(ctx.attrs.name, output_suffix)
+    standalone = package_style == PackageStyle("standalone")
+    inplace = package_style == PackageStyle("inplace")
+    include_bytecode = pex_modules.compile and not inplace
+
+    runtime_files = []
+    sub_targets = {}
+    hidden_resources = []
+    if standalone:
+        err = _check_hidden_resources(ctx, pex_modules, package_style, output_suffix)
+        if err:
+            return _fail(ctx, python_internal_tools, output_suffix, err)
+    elif pex_modules.manifests.has_hidden_resources(mode = package_style.value):
+        hidden_resources = pex_modules.manifests.hidden_resources(mode = package_style.value)
+
+    # Accumulate all of the artifacts required by the build
+    runtime_artifacts = []
+    runtime_artifacts.extend(dep_artifacts)
+    runtime_artifacts.extend(pex_modules.manifests.resource_artifacts(mode = package_style.value))
+    if include_bytecode:
+        runtime_artifacts.extend(pex_modules.manifests.bytecode_artifacts())
+    if manifest_module:
+        runtime_artifacts.extend(manifest_module.artifacts)
+
+    symlink_tree_path = None
+    if standalone:
+        if python_toolchain.make_py_package_standalone == None:
+            return _fail(
+                ctx,
+                python_internal_tools,
+                output_suffix,
+                "Python toolchain does not provide make_py_package_standalone",
+            )
+    else:
+        symlink_tree_path = ctx.actions.declare_output("{}#link-tree".format(name), dir = True, has_content_based_path = False)
+
+    modules_args = _pex_modules_args(
+        ctx,
+        common_modules_args,
+        runtime_artifacts,
+        debug_artifacts,
+        package_style,
+        include_bytecode,
+        symlink_tree_path,
+        manifest_module,
+        pex_modules,
+        output_suffix,
+    )
+
+    output = ctx.actions.declare_output("{}{}".format(name, ctx.attrs.extension or python_toolchain.pex_extension), has_content_based_path = False)
+
+    bootstrap_args = _pex_bootstrap_args(
+        python_toolchain,
+        main,
+        output,
+        preload_libraries,
+        symlink_tree_path,
+        package_style,
+        True if ctx.attrs.zip_safe == None else ctx.attrs.zip_safe,
+    )
+    bootstrap_args.add(build_args)
+    if standalone:
+        bootstrap_args.add(ctx.attrs.standalone_build_args)
+    else:
+        bootstrap_args.add(ctx.attrs.inplace_build_args)
+        runtime_files.extend(runtime_artifacts)
+        runtime_files.append(symlink_tree_path)
+
+    # For standalone builds, or builds setting make_py_package we generate args for calling make_par.py
+    if standalone or make_py_package_cmd != None:
+        # We support building _standalone_ packages locally to e.g. support fbcode's
+        # current style of build info stamping (e.g. T10696178).
+        prefer_local = (not getattr(ctx.attrs, "optimize_for_action_throughput", False)) and standalone and package_python_locally(ctx, python_toolchain)
+        prefer_remote = getattr(ctx.attrs, "optimize_for_action_throughput", False)
+
+        cmd = cmd_args(
+            make_py_package_cmd if make_py_package_cmd != None else python_toolchain.make_py_package_standalone,
+        )
+        cmd.add(modules_args)
+        cmd.add(bootstrap_args)
+        if ctx.attrs.runtime_env:
+            for k, v in ctx.attrs.runtime_env.items():
+                cmd.add(cmd_args(["--passthrough", "--runtime_env={}={}".format(k, v)]))
+        if ctx.attrs.interpreter_args:
+            cmd.add(cmd_args(["--passthrough", "--interpreter-flags={}".format(json.encode(ctx.attrs.interpreter_args))]))
+        if package_style == PackageStyle("outplace"):
+            cmd.add(cmd_args("--passthrough=--copy-files", hidden = runtime_artifacts))
+
+        identifier_prefix = "standalone{}" if standalone else "inplace{}"
+        ctx.actions.run(
+            cmd,
+            prefer_local = prefer_local,
+            prefer_remote = prefer_remote,
+            category = "par",
+            identifier = identifier_prefix.format(output_suffix),
+            allow_cache_upload = allow_cache_upload,
+            error_handler = python_toolchain.python_error_handler,
+        )
+
+    else:
+        modules = cmd_args(python_internal_tools.make_py_package_modules)
+        modules.add(modules_args)
+        if package_style == PackageStyle("outplace"):
+            modules.add(cmd_args("--copy-files", hidden = runtime_artifacts))
+        ctx.actions.run(
+            modules,
+            category = "par",
+            identifier = "modules{}".format(output_suffix),
+            allow_cache_upload = allow_cache_upload,
+        )
+
+        bootstrap = cmd_args(python_internal_tools.make_py_package_inplace)
+        bootstrap.add(bootstrap_args)
+        if python_toolchain.native_library_env_var != None:
+            bootstrap.add(cmd_args(python_toolchain.native_library_env_var, format = "--native-libs-env-var={}"))
+
+        if ctx.attrs.runtime_env:
+            for k, v in ctx.attrs.runtime_env.items():
+                bootstrap.add(cmd_args(["--runtime_env", "{}={}".format(k, v)]))
+        for flag in ctx.attrs.interpreter_args:
+            bootstrap.add(cmd_args(["--python-interpreter-flags={}".format(flag)]))
+
+        ctx.actions.run(
+            bootstrap,
+            category = "par",
+            identifier = "bootstrap{}".format(output_suffix),
+            allow_cache_upload = allow_cache_upload,
+        )
+
+    run_args = []
+
+    # Windows can't run PAR directly.
+    if ctx.attrs._exec_os_type[OsLookup].os == Os("windows"):
+        run_args.append(ctx.attrs._python_toolchain[PythonToolchainInfo].interpreter)
+    run_args.append(output)
+
+    if symlink_tree_path != None:
+        sub_targets["link-tree"] = [
+            DefaultInfo(
+                default_output = symlink_tree_path,
+                other_outputs = runtime_files + (hidden_resources if package_style == PackageStyle("outplace") else []),
+                sub_targets = {},
+            )
+        ]
+
+    return PexProviders(
+        default_output = output,
+        other_outputs = runtime_files,
+        other_outputs_prefix = symlink_tree_path.short_path if symlink_tree_path != None else None,
+        hidden_resources = hidden_resources,
+        sub_targets = sub_targets,
+        run_cmd = cmd_args(
+            run_args,
+            hidden = runtime_files + hidden_resources + [python_toolchain.interpreter],
+        ),
+    )
+
+def _make_py_package_live(
+    ctx: AnalysisContext,
+    make_py_package_live: RunInfo,
+    pex_modules: PexModules,
+    build_args: list[ArgLike],
+    preload_libraries: cmd_args,
+    main: EntryPoint,
+    shared_libraries: list[(SharedLibrary, str)],
+    common_generated_files: list[(Artifact, str)],
+    python_toolchain: PythonToolchainInfo,
+    python_internal_tools: PythonInternalToolsInfo,
+    output_suffix: str,
+    package_style: PackageStyle,
+    allow_cache_upload: bool,
+) -> PexProviders:
+    """
+    Bundle contents of par into symlink dir
+    * generated_files
+      * _bootstrap.sh
+      * __manifest__.py
+      * __manifest__.json
+      * __run_lpar_main__.py
+      * __par__/__startup_function_loader__.py
+    * source files
+    * resources
+    * bytecode
+    * extras
+      * dbg-db.json
+      * sitecustomize.py
+      * static_extension_finder.py
+      * cxx_python_extension stub files
+    * extensions
+      * cxx_python_extensions ".so" files - when using native linking these are the "unembedable" extensions
+    * native-libraries
+      * All of the required shared cxx libraries
+      * Link group libraries
+      * native-executable
+    * TODO: bundled-runtime
+    * Debug info:
+      * External debug info is included in runtime_files so that it is materialized at build time
+      since we are building an inplace par and the .so files symlink to their
+      actual build location the debug-info does not need to be included in the
+      link tree
+      * EXCLUDED: dwp files - we do not package dwp files in inplace pars
+      * EXCLUDED: debuginfo - we do not package debug-info for inplace pars
+    """
+    is_outplace = package_style == PackageStyle("outplace")
+    if is_outplace:
+        err = _check_hidden_resources(ctx, pex_modules, package_style, output_suffix)
+        if err:
+            return _fail(ctx, python_internal_tools, output_suffix, err)
+    sub_targets = {}
+    name = "{}{}".format(ctx.attrs.name, output_suffix)
+
+    symlink_tree_path = ctx.actions.declare_output("{}#link-tree".format(name), dir = True, has_content_based_path = False)
+    runtime_files = []
+
+    output = ctx.actions.declare_output("{}{}".format(name, ctx.attrs.extension or python_toolchain.pex_extension), has_content_based_path = False)
+
+    generated_files = []
+    generated_files.extend(common_generated_files)
+
+    is_windows = ctx.attrs._target_os_type[OsLookup].os == Os("windows")
+
+    if is_windows:
+        _live_par_windows_bootstrap(
+            ctx,
+            output,
+            python_toolchain,
+            python_internal_tools,
+            main,
+            preload_libraries,
+            symlink_tree_path,
+            output_suffix,
+        )
+    else:
+        generated_files.extend(
+            _live_par_generated_files(
+                ctx,
+                output,
+                python_toolchain,
+                python_internal_tools,
+                build_args + ctx.attrs.inplace_build_args,
+                main,
+                preload_libraries,
+                output_suffix,
+            )
+        )
+
+    cmd = cmd_args(make_py_package_live)
+    cmd.add(cmd_args(symlink_tree_path.as_output(), format = "--output-path={}"))
+
+    sources = pex_modules.manifests.src_manifests()
+    if pex_modules.repl_manifests:
+        sources.extend(pex_modules.repl_manifests.src_manifests())
+        runtime_files.extend(pex_modules.repl_manifests.src_artifacts())
+
+    source_manifests_path = ctx.actions.write(
+        "__source_manifests{}.txt".format(output_suffix),
+        sources,
+        has_content_based_path = False,
+    )
+    cmd.add(cmd_args(source_manifests_path, format = "--sources={}", hidden = sources))
+    runtime_files.extend(pex_modules.manifests.src_artifacts())
+
+    # Gather binary resources
+    resources = pex_modules.manifests.resource_manifests(mode = package_style.value)
+    if resources:
+        resource_artifacts = pex_modules.manifests.resource_artifacts(mode = package_style.value)
+        resource_manifests_path = ctx.actions.write(
+            "__resource_manifests{}.txt".format(output_suffix),
+            resources,
+            has_content_based_path = False,
+        )
+
+        # Since we allow including directories for resources we have to enumerate the directory at build time, so we pass the resource artifacts as a hidden arg so that it will be materialized on disk when we build the par.
+        # Note: resource_artifacts are intentionally omitted from `hidden` here to avoid a non-trivial build speed regression.
+        cmd.add(cmd_args(resource_manifests_path, format = "--resources={}", hidden = [resources]))
+        runtime_files.extend(resource_artifacts)
+
+    if pex_modules.compile and is_outplace:
+        # bytecode is compiled per library so the actual bytecode artifacts are directories
+        # the compile command outputs json manifest in the form
+        # [(src, dst, origin),]
+        bytecode_manifests = pex_modules.manifests.bytecode_manifests()
+        bytecode_manifests_path = ctx.actions.write(
+            "__bytecode_manifests{}.txt".format(output_suffix),
+            bytecode_manifests,
+            has_content_based_path = False,
+        )
+        cmd.add(cmd_args(bytecode_manifests_path, format = "--bytecode={}", hidden = bytecode_manifests))
+
+        bytecode_artifacts = pex_modules.manifests.bytecode_artifacts()
+        runtime_files.extend(bytecode_artifacts)
+
+        # Pass resolved bytecode artifact paths so the Rust builder can replace
+        # the /output_artifacts/ placeholder with actual content hashes.
+        bytecode_artifacts_path = ctx.actions.write(
+            "__bytecode_artifacts{}.txt".format(output_suffix),
+            cmd_args(bytecode_artifacts),
+            has_content_based_path = False,
+        )
+        cmd.add(cmd_args(bytecode_artifacts_path, format = "--bytecode-artifacts={}"))
+
+    if pex_modules.extra_manifests != None:
+        extras_manifest = ctx.actions.write(
+            "{}-extra.txt".format(name),
+            [cmd_args(a, p, delimiter = "::") for a, p in pex_modules.extra_manifests.artifacts],
+            with_inputs = True,
+            has_content_based_path = False,
+        )
+        cmd.add(cmd_args(extras_manifest.without_associated_artifacts(), format = "--extras={}"))
+        runtime_files.append(extras_manifest)
+
+    if pex_modules.extensions != None:
+        cmd.add(cmd_args(pex_modules.extensions.manifest, format = "--extensions={}"))
+        runtime_files.extend([a[0] for a in pex_modules.extensions.artifacts])
+
+    native_libraries_manifest = gen_shared_libs_action(
+        actions = ctx.actions,
+        out = "{}-native-libraries.txt".format(name),
+        shared_libs = [shlib for shlib, _ in shared_libraries],
+        gen_action = lambda actions, output, shared_libs: actions.write(
+            output,
+            cmd_args(
+                [cmd_args(shlib.lib.output, paths.join(libdir, soname), delimiter = "::") for soname, shlib, libdir in zip_shlibs(shared_libs, shared_libraries)],
+            ),
+        ),
+    )
+    cmd.add(cmd_args(native_libraries_manifest.without_associated_artifacts(), format = "--shared-libs={}"))
+    runtime_files.append(native_libraries_manifest)
+
+    # Due to dynamic action weirdness we need to explicitly add the shared_libs to the output
+    runtime_files.extend([shlib.lib.output for shlib, _ in shared_libraries])
+
+    # Make sure all external debug-info is materialized at runtime
+    runtime_files.extend(
+        project_artifacts(
+            ctx.actions,
+            [shlib.lib.external_debug_info for shlib, _ in shared_libraries],
+        )
+    )
+
+    generated_manifest = ctx.actions.write(
+        "{}-generated.txt".format(name), [cmd_args(a, p, delimiter = "::") for a, p in generated_files], with_inputs = True, has_content_based_path = False
+    )
+    cmd.add(cmd_args(generated_manifest.without_associated_artifacts(), format = "--generated={}"))
+    runtime_files.extend([a for a, _ in generated_files])
+
+    if ctx.attrs._exec_os_type[OsLookup].os == Os("windows"):
+        # Windows can't produce these pars in a cache-portable form.
+        allow_cache_upload = False
+
+    if is_outplace:
+        cmd.add(cmd_args("--copy", hidden = runtime_files))
+        ctx.actions.run(
+            cmd,
+            category = "par",
+            identifier = "make_outplace_par{}".format(output_suffix),
+            allow_cache_upload = allow_cache_upload,
+        )
+    else:
+        state = ctx.actions.declare_output("{}-state.json".format(name), has_content_based_path = False)
+        cmd.add(cmd_args(state.as_output(), format = "--state={}"))
+        runtime_files.append(state)
+        sub_targets["state"] = [DefaultInfo(default_output = state)]
+
+        cmd.add(["--incremental"])
+        if getattr(ctx.attrs, "use_rust_make_par_optimizations", False):
+            cmd.add(["--use-rust-make-par-optimizations"])
+        ctx.actions.run(
+            cmd,
+            metadata_env_var = "ACTION_METADATA",
+            metadata_path = "action_metadata-{}.json".format(name),
+            category = "par",
+            identifier = "make_live_par_incremental{}".format(output_suffix),
+            no_outputs_cleanup = True,
+            # Incremental action: its output is a function of the prior on-disk
+            # state, not solely of its inputs, so uploading it to the cache is
+            # never sound. Keep it off regardless of the rule/toolchain
+            # `allow_cache_upload`, mirroring how cxx excludes incremental links.
+            allow_cache_upload = False,
+        )
+
+    runtime_files.append(symlink_tree_path)
+
+    # For outplace, every runtime file is copied into the link-tree directory,
+    # so the link-tree itself is the only output that needs to be materialized
+    # by consumers. For inplace, the link-tree contains symlinks pointing into
+    # buck-out, so the runtime files (and any hidden resources) must be
+    # materialized alongside it.
+    if is_outplace:
+        hidden_resources = []
+        link_tree_other_outputs = []
+        pex_other_outputs = [symlink_tree_path]
+    else:
+        hidden_resources = pex_modules.manifests.hidden_resources(mode = package_style.value)
+        link_tree_other_outputs = runtime_files + hidden_resources
+        pex_other_outputs = runtime_files
+
+    sub_targets["link-tree"] = [
+        DefaultInfo(
+            default_output = symlink_tree_path,
+            other_outputs = link_tree_other_outputs,
+            sub_targets = {},
+        )
+    ]
+
+    run_args = []
+    if is_windows:
+        run_args.append(python_toolchain.interpreter)
+    run_args.append(output)
+
+    return PexProviders(
+        default_output = output,
+        other_outputs = pex_other_outputs,
+        other_outputs_prefix = symlink_tree_path.short_path,
+        hidden_resources = hidden_resources,
+        sub_targets = sub_targets,
+        run_cmd = cmd_args(
+            run_args,
+            hidden = runtime_files + hidden_resources + [python_toolchain.interpreter],
+        ),
+    )
+
+def _debuginfo_subtarget(ctx: AnalysisContext, debug_artifacts: list[(str | (str, SharedLibrary, str), ArgLike)]) -> list[Provider]:
+    for_shared_libs = []
+    other = []
+    for name, artifact in debug_artifacts:
+        if type(name) == type(()):
+            for_shared_libs.append((name[1], (artifact, name[0], name[2])))
+        else:
+            if len(name) == 0:
+                # This is external debug information, most likely coming from execution
+                # platform, skip packaging them because they are not important.
+                continue
+            other.append((artifact, name))
+    out = gen_shared_libs_action(
+        actions = ctx.actions,
+        out = "debuginfo.manifest.json",
+        shared_libs = [shlib for shlib, _ in for_shared_libs],
+        gen_action = lambda actions, output, shared_libs: actions.write_json(
+            output,
+            [(debug, paths.join(libdir, soname + ext)) for soname, _, (debug, libdir, ext) in zip_shlibs(shared_libs, for_shared_libs)] + other,
+        ),
+    )
+    return [DefaultInfo(default_output = out, other_outputs = [d for _, d in debug_artifacts])]
+
+def _preload_libraries_args(ctx: AnalysisContext, shared_libraries: list[(SharedLibrary, str)]) -> cmd_args:
+    preload_libraries_path = gen_shared_libs_action(
+        actions = ctx.actions,
+        out = "__preload_libraries.txt",
+        shared_libs = [shlib for shlib, _ in shared_libraries],
+        gen_action = lambda actions, output, shared_libs: actions.write(
+            output,
+            ["--preload={}".format(paths.join(libdir, soname)) for soname, _, libdir in zip_shlibs(shared_libs, shared_libraries)],
+        ),
+    )
+    return cmd_args(preload_libraries_path, format = "@{}")
+
+def _pex_bootstrap_args(
+    toolchain: PythonToolchainInfo,
+    main: EntryPoint,
+    output: Artifact,
+    preload_libraries: cmd_args,
+    symlink_tree_path: Artifact | None,
+    package_style: PackageStyle,
+    zip_safe: bool,
+) -> cmd_args:
+    cmd = cmd_args()
+    cmd.add(preload_libraries)
+    cmd.add([
+        "--python",
+        toolchain.interpreter,
+        "--host-python",
+        toolchain.host_interpreter,
+    ])
+    if main[0] == EntryPointKind("module"):
+        cmd.add(["--entry-point", main[1]])
+    else:
+        cmd.add(["--main-function", main[1]])
+    if symlink_tree_path != None:
+        cmd.add(cmd_args(["--modules-dir", symlink_tree_path], ignore_artifacts = True))
+
+    cmd.add(["--main-runner", toolchain.main_runner])
+
+    cmd.add(output.as_output())
+
+    if package_style == PackageStyle("standalone") and not zip_safe:
+        cmd.add("--no-zip-safe")
+
+    for lib_path in toolchain.native_library_runtime_paths:
+        cmd.add("--native-library-runtime-path={}".format(lib_path))
+
+    return cmd
+
+def _pex_modules_common_args(
+    ctx: AnalysisContext,
+    pex_modules: PexModules,
+    extra_manifests: list[ArgLike],
+    shared_libraries: list[(SharedLibrary, str)],
+    debuginfo_files: list[(str | (str, SharedLibrary, str), Artifact)],
+    suffix: str = "",
+) -> (cmd_args, list[ArgLike], list[(str | (str, SharedLibrary, str), ArgLike)]):
+    srcs = []
+    src_artifacts = []
+    deps = []
+    debug_artifacts = []
+
+    srcs.extend(pex_modules.manifests.src_manifests())
+    src_artifacts.extend(pex_modules.manifests.src_artifacts())
+
+    if pex_modules.extensions:
+        srcs.append(pex_modules.extensions.manifest)
+        src_artifacts.extend([a[0] for a in pex_modules.extensions.artifacts])
+
+    if pex_modules.extra_manifests:
+        srcs.append(pex_modules.extra_manifests.manifest)
+        src_artifacts.extend([a[0] for a in pex_modules.extra_manifests.artifacts])
+
+    if pex_modules.repl_manifests:
+        srcs.extend(pex_modules.repl_manifests.src_manifests())
+        src_artifacts.extend(pex_modules.repl_manifests.src_artifacts())
+
+    if extra_manifests:
+        srcs.extend(extra_manifests)
+        deps.extend(extra_manifests)
+
+    deps.extend(src_artifacts)
+
+    src_manifests_path = ctx.actions.write(
+        "__src_manifests{}.txt".format(suffix),
+        _srcs(srcs, format = "--module-manifest={}"),
+        has_content_based_path = False,
+    )
+    native_libraries = gen_shared_libs_action(
+        actions = ctx.actions,
+        out = "__native_libraries{}__.txt".format(suffix),
+        shared_libs = [shlib for shlib, _ in shared_libraries],
+        gen_action = lambda actions, output, shared_libs: actions.write(
+            output,
+            cmd_args(
+                _srcs(
+                    [shlib.lib.output for shlib in shared_libs.values()],
+                    format = "--native-library-src={}",
+                ),
+                ["--native-library-dest={}".format(paths.join(libdir, soname)) for soname, _, libdir in zip_shlibs(shared_libs, shared_libraries)],
+            ),
+        ),
+    )
+
+    src_manifest_args = cmd_args(src_manifests_path, hidden = srcs)
+
+    cmd = cmd_args()
+    cmd.add(cmd_args(src_manifest_args, format = "@{}"))
+    cmd.add(cmd_args(native_libraries, format = "@{}"))
+
+    if debuginfo_files:
+        debuginfo_srcs_path = ctx.actions.write(
+            "__debuginfo___srcs{}.txt".format(suffix),
+            _srcs([src for _, src in debuginfo_files], format = "--debuginfo-src={}"),
+            has_content_based_path = False,
+        )
+        debuginfo_srcs_args = cmd_args(debuginfo_srcs_path)
+        cmd.add(cmd_args(debuginfo_srcs_args, format = "@{}"))
+        for name, artifact in debuginfo_files:
+            if type(name) != type(""):
+                libdir, shlib, ext = name
+                name = paths.join(libdir, shlib.soname.ensure_str() + ext)
+            debug_artifacts.append((name, artifact))
+
+    if ctx.attrs.package_split_dwarf_dwp:
+        if ctx.attrs.strip_libpar == "extract" and get_package_style(ctx) in [PackageStyle("standalone"), PackageStyle("outplace")] and cxx_is_gnu(ctx):
+            dwp_ext = ".debuginfo.dwp"
+        else:
+            dwp_ext = ".dwp"
+        dwp_args = gen_shared_libs_action(
+            actions = ctx.actions,
+            out = "__dwp{}__.txt".format(suffix),
+            shared_libs = [shlib for shlib, _ in shared_libraries],
+            gen_action = lambda actions, output, shared_libs: actions.write(
+                output,
+                cmd_args(
+                    _srcs(
+                        [shlib.lib.dwp for shlib in shared_libs.values() if shlib.lib.dwp != None],
+                        format = "--dwp-src={}",
+                    ),
+                    _srcs(
+                        [paths.join(libdir, soname + dwp_ext) for soname, shlib, libdir in zip_shlibs(shared_libs, shared_libraries) if shlib.lib.dwp != None],
+                        format = "--dwp-dest={}",
+                    ),
+                ),
+            ),
+        )
+        cmd.add(cmd_args(dwp_args, format = "@{}"))
+
+        for shlib, libdir in shared_libraries:
+            if shlib.lib.dwp != None:
+                debug_artifacts.append(((libdir, shlib, dwp_ext), shlib.lib.dwp))
+
+    for shlib, _ in shared_libraries:
+        deps.append(shlib.lib.output)
+
+    external_debug_info = project_artifacts(
+        ctx.actions,
+        [shlib.lib.external_debug_info for shlib, _ in shared_libraries],
+    )
+
+    # HACK: external_debug_info has an empty path
+    debug_artifacts.extend([("", d) for d in external_debug_info])
+
+    return (cmd, deps, debug_artifacts)
+
+def _pex_modules_args(
+    ctx: AnalysisContext,
+    common_args: cmd_args,
+    dep_artifacts: list[ArgLike],
+    debug_artifacts: list[(str | (str, SharedLibrary, str), ArgLike)],
+    package_style: PackageStyle,
+    include_bytecode: bool,
+    symlink_tree_path: Artifact | None,
+    manifest_module: ManifestModule | None,
+    pex_modules: PexModules,
+    output_suffix: str,
+) -> cmd_args:
+    """
+    Produces args to deal with a PEX's modules. Returns args to pass to the
+    modules builder.
+    """
+
+    cmd = []
+    hidden = []
+
+    cmd.append(common_args)
+
+    if manifest_module != None:
+        cmd.append(cmd_args(manifest_module.manifest, format = "--module-manifest={}"))
+
+    if include_bytecode:
+        bytecode_manifests = pex_modules.manifests.bytecode_manifests()
+
+        bytecode_manifests_path = ctx.actions.write(
+            "__bytecode_manifests{}.txt".format(output_suffix),
+            _srcs(
+                bytecode_manifests,
+                format = "--module-manifest={}",
+            ),
+            has_content_based_path = False,
+        )
+        cmd.append(cmd_args(bytecode_manifests_path, format = "@{}"))
+        hidden.append(bytecode_manifests)
+
+        # To support content-based path hashing, we need to pass in the actual
+        # bytecode artifacts alongside the manifest in order to replace the
+        # placeholder "output_artifacts" portion of the path with the resolved hash.
+        bytecode_artifacts = pex_modules.manifests.bytecode_artifacts()
+
+        bytecode_artifacts_path = ctx.actions.write(
+            "__bytecode_artifacts{}.txt".format(output_suffix),
+            cmd_args(bytecode_artifacts),
+            has_content_based_path = False,
+        )
+        cmd.append(cmd_args(bytecode_artifacts_path, format = "--bytecode-artifacts={}"))
+
+    if symlink_tree_path != None:
+        cmd.extend(["--modules-dir", symlink_tree_path.as_output()])
+    else:
+        # Accumulate all the artifacts we depend on. Only add them to the command
+        # if we are not going to create symlinks.
+        hidden.append(dep_artifacts)
+
+    hidden.extend([s for _, s in debug_artifacts])
+
+    resources = pex_modules.manifests.resource_manifests(mode = package_style.value)
+    if resources:
+        resource_manifests_path = ctx.actions.write(
+            "__resource_manifests{}.txt".format(output_suffix),
+            _srcs(resources, format = "--resource-manifest={}"),
+            has_content_based_path = False,
+        )
+        resource_manifest_args = cmd_args(resource_manifests_path, hidden = resources)
+        cmd.append(cmd_args(resource_manifest_args, format = "@{}"))
+
+    return cmd_args(cmd, hidden = hidden)
+
+def _check_hidden_resources(ctx: AnalysisContext, pex_modules: PexModules, package_style: PackageStyle, output_suffix: str) -> str | None:
+    """
+    Return an error message if pex_modules has hidden resources (which standalone
+    and outplace can't package), else None. Only call for unsupported styles.
+    """
+    if not pex_modules.manifests.has_hidden_resources(mode = package_style.value):
+        return None
+
+    # constructing the full error message is expensive, only do it when we abort analysis
+    if output_suffix:
+        return "{} builds don't support hidden resources".format(package_style.value)
+    return _hidden_resources_error_message(
+        ctx.label,
+        pex_modules.manifests.hidden_resources(mode = package_style.value),
+        package_style.value,
+    )
+
+def _hidden_resources_error_message(current_target: Label, hidden_resources: list[ArgLike] | None, style_name: str) -> str:
+    """
+    Friendlier error message about putting non-python resources into standalone/outplace bins
+    """
+    owner_to_artifacts = {}
+
+    for resource_set in hidden_resources:
+        for resources in resource_set.traverse():
+            for r in resources:
+                # TODO: `r` is sometimes a tset projection, but it shouldn't be
+                if getattr(r, "is_source", True):
+                    # Source files; do a string repr so that we get the
+                    # package path in there too
+                    owner_to_artifacts.setdefault("", []).append(str(r))
+                else:
+                    owner_to_artifacts.setdefault(r.owner, []).append(r.short_path)
+
+    msg = (
+        "Cannot package hidden srcs/resources in a {} python_binary. ".format(style_name)
+        + 'Eliminate resources in non-Python dependencies of this python binary, set `package_style = "inplace"` on '
+        + str(current_target.raw_target())
+        + ", "
+        + 'use `strip_mode="full"` or turn off Split DWARF `-c fbcode.split-dwarf=false` on C++ binary resources.\n'
+    )
+
+    for rule, resources in owner_to_artifacts.items():
+        if rule != "":
+            msg += "Hidden srcs/resources for {}\n".format(rule)
+        else:
+            msg += "Debug instructions:\n"
+            msg += "Find the reason this file was included with `buck2 cquery 'allpaths({}, owner(%s))' <file paths>`\n".format(current_target.raw_target())
+        for resource in sorted(resources):
+            msg += "  {}\n".format(resource)
+    return msg
+
+def get_shared_library_dep_metadata(ctx: AnalysisContext, shared_libraries: list[(SharedLibrary, str)], link_args: list[LinkArgs]) -> list[DepMetadata]:
+    """
+    Dedupes the linker metadata for each shared library into a single string.
+
+    Note: this can be expensive because we're traversing a tset rather than
+    projecting the value. This is unfortunate but we need to be able to truncate
+    how much metadata we put into the manifest module.
+    """
+    link_infos_tsets = []
+    link_infos = []
+
+    def add_inner_infos(args: LinkArgs) -> None:
+        if args.tset != None:
+            tset = args.tset
+            link_infos_tsets.append(tset.infos)
+        elif args.infos != None:
+            link_infos.extend(args.infos)
+
+    for args in link_args:
+        add_inner_infos(args)
+
+    for lib, _ in shared_libraries:
+        # Note: refer to SharedLibrary.LinkedObject.link_args here. SharedLibrary.link_args isn't
+        # always populated.
+        for args in lib.lib.link_args or []:
+            if args:
+                add_inner_infos(args)
+
+    tset = ctx.actions.tset(LinkInfosTSet, children = link_infos_tsets)
+    metadatas = []
+    for info in tset.traverse():
+        metadatas.extend(get_link_info(info).metadata)
+    for info in link_infos:
+        metadatas.extend(info.metadata)
+
+    return dedupe_dep_metadata(metadatas)
+
+def get_truncated_shared_library_versions(metadatas: list[DepMetadata]) -> list[str]:
+    return [metadata.version for metadata in truncate_dep_metadata(metadatas)]
+
+def _add_dep_metadata_to_manifest_module(
+    ctx: AnalysisContext, shared_libraries: list[(SharedLibrary, str)], link_args: list[LinkArgs], python_toolchain: PythonToolchainInfo
+) -> dict[str, typing.Any] | None:
+    """
+    Updates manifest_module_entries with link metadata if they exist.
+    """
+
+    # FIXME(JakobDegen): Hack: Outside of the fbcode macros, we don't pass `--no-manifest` to the
+    # par builder which means that we can't generate any manifest data in the prelude
+    if python_toolchain.manifest_module_entries == None or "fbcode_macros" not in ctx.attrs.labels:
+        if ctx.attrs.manifest_module_entries == None:
+            return None
+        manifest_module_entries = dict(ctx.attrs.manifest_module_entries)
+    else:
+        manifest_module_entries = dict(python_toolchain.manifest_module_entries)
+        if ctx.attrs.manifest_module_entries != None:
+            for k, v in ctx.attrs.manifest_module_entries.items():
+                if k not in manifest_module_entries:
+                    manifest_module_entries[k] = v
+                    continue
+                if isinstance(manifest_module_entries[k], dict) and isinstance(v, dict):
+                    d = dict(manifest_module_entries[k])
+                    d.update(v)
+                    manifest_module_entries[k] = d
+                else:
+                    fail("Cannot merge manifest_module_entries entry {}: {} and {}".format(k, manifest_module_entries[k], v))
+
+    metadatas = get_shared_library_dep_metadata(ctx, shared_libraries, link_args)
+    manifest_module_entries["library_versions"] = get_truncated_shared_library_versions(metadatas)
+
+    return manifest_module_entries
+
+def generate_startup_function_loader(ctx: AnalysisContext, manifest_module_entries: dict[str, typing.Any] | None) -> Artifact:
+    """
+    Generate `__startup_function_loader__.py` used for early bootstrap of a par.
+    Things that go here are also enumerated in `__manifest__['startup_functions']`
+    Some examples include:
+     * static extension finder init
+     * eager import loader init
+     * cinderx init
+    """
+
+    if manifest_module_entries == None:
+        startup_functions_list = ""
+    else:
+        startup_functions_list = "\n".join(
+            ["'''" + startup_function + "'''," for _, startup_function in sorted(manifest_module_entries.get("startup_functions", {}).items())],
+        )
+
+    src_startup_functions_path = ctx.actions.write(
+        "manifest/__startup_function_loader__.py",
+        """
+import importlib
+import warnings
+
+VARS = {vars}
+STARTUP_FUNCTIONS=[{startup_functions_list}]
+
+VARS["_dearg"] = lambda *args, **kwargs: (args, kwargs)
+
+def load_startup_functions():
+    for name in STARTUP_FUNCTIONS:
+        mod, sep, func = name.partition(":")
+        if sep:
+            try:
+                func, _, args = func.partition("(")
+                args, kwargs = eval("_dearg(" + args, VARS) if args else ((), {{}})
+                module = importlib.import_module(mod)
+                getattr(module, func)(*args, **kwargs)
+            except Exception as e:
+                # TODO: Ignoring errors for now.
+                warnings.warn(
+                    "Startup function '%s' (%s:%s) not executed: %s"
+                    % (func, mod, func, e),
+                    stacklevel=1,
+                )
+
+        """.format(
+            startup_functions_list = startup_functions_list,
+            vars = {
+                "label": repr(ctx.label),
+                "name": ctx.attrs.name,
+            },
+        ),
+        has_content_based_path = False,
+    )
+    return src_startup_functions_path
+
+def _generate_manifest_module(
+    ctx: AnalysisContext,
+    manifest_module_entries: dict[str, typing.Any] | None,
+    manifest_entries_overlay: Artifact | None,
+    python_toolchain: PythonToolchainInfo,
+    python_internal_tools: PythonInternalToolsInfo,
+    src_manifests: list[ArgLike],
+) -> ManifestModule | None:
+    """
+    Generates a __manifest__.py module, and an extra entry to add to source manifests.
+
+    The contents of the manifest are taken from an attribute if it exists. If the
+    attribute is None, this function does nothing.
+    """
+
+    if manifest_module_entries == None:
+        return None
+    module = ctx.actions.declare_output("manifest/__manifest__.py", has_content_based_path = False)
+    json_entries_output = ctx.actions.declare_output("manifest/__manifest__.json", has_content_based_path = False)
+    entries_json = ctx.actions.write_json("manifest/entries.json", manifest_module_entries, has_content_based_path = False)
+    src_manifests_path = ctx.actions.write(
+        "__module_manifests.txt",
+        src_manifests,
+        has_content_based_path = False,
+    )
+    if ctx.attrs.use_rust_make_par and manifest_entries_overlay == None:
+        cmd = cmd_args(
+            python_toolchain.make_py_package_live[RunInfo],
+            "manifest-module",
+            ["--manifest-entries", entries_json],
+            ["--module-manifests", src_manifests_path],
+            ["--output", module.as_output()],
+            hidden = src_manifests,
+        )
+        ctx.actions.run(cmd, category = "par", identifier = "manifest-module")
+        ctx.actions.copy_file(json_entries_output.as_output(), entries_json)
+    else:
+        cmd = cmd_args(
+            python_internal_tools.make_py_package_manifest_module,
+            ["--manifest-entries", entries_json],
+            ["--manifest-entries-overlay", manifest_entries_overlay] if manifest_entries_overlay else [],
+            ["--module-manifests", src_manifests_path],
+            ["--output", module.as_output()],
+            ["--output-json", json_entries_output.as_output()],
+            hidden = src_manifests,
+        )
+        ctx.actions.run(cmd, category = "par", identifier = "manifest-module")
+
+    src_manifest = ctx.actions.write_json(
+        "manifest/module_manifest.json",
+        [
+            ["__manifest__.py", module, "prelude//python:make_py_package.bzl"],
+            ["__manifest__.json", json_entries_output, "prelude//python:make_py_package.bzl"],
+        ],
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+
+    return ManifestModule(manifest = src_manifest, artifacts = [json_entries_output, module])
diff --git a/buck2/prelude/python/manifest.bzl b/buck2/prelude/python/manifest.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/manifest.bzl
@@ -0,0 +1,112 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifact_tset.bzl", "project_artifacts")
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",
+    "gen_shared_libs_action",
+)
+load("@prelude//utils:arglike.bzl", "ArgLike")
+
+# Manifests are files containing information how to map sources into a package.
+# The files are JSON lists with an entry per source, where each source is 3-tuple
+# of relative destination path, artifact path, and a short description of the
+# origin of this source (used for error messages in tooling that uses these).
+ManifestInfo = record(
+    # The actual manifest file (in the form of a JSON file).
+    manifest = field(Artifact),
+    # All artifacts that are referenced in the manifest.
+    artifacts = field(list[[Artifact, ArgLike]]),
+)
+
+def _write_manifest(ctx: AnalysisContext, name: str, entries: list[(str, Artifact, str)]) -> Artifact:
+    """
+    Serialize the given source manifest entries to a JSON file.
+    """
+    return ctx.actions.write_json(name + ".manifest", entries, has_content_based_path = False)
+
+def create_manifest_for_entries(ctx: AnalysisContext, name: str, entries: list[(str, Artifact, str)]) -> ManifestInfo:
+    """
+    Generate a source manifest for the given list of sources.
+    """
+    return ManifestInfo(
+        manifest = _write_manifest(ctx, name, entries),
+        artifacts = [(a, dest) for dest, a, _ in entries],
+    )
+
+def create_manifest_for_source_map(ctx: AnalysisContext, param: str, srcs: dict[str, Artifact]) -> ManifestInfo:
+    """
+    Generate a source manifest for the given map of sources from the given rule.
+    """
+    origin = "{} {}".format(ctx.label.raw_target(), param)
+    return create_manifest_for_entries(
+        ctx,
+        param,
+        [(dest, artifact, origin) for dest, artifact in srcs.items()],
+    )
+
+def get_srcs_from_manifest(src_manifest: [ManifestInfo, None]) -> list[Artifact]:
+    return [a for (a, _) in src_manifest.artifacts] if src_manifest else []
+
+def create_manifest_for_shared_libs(actions: AnalysisActions, name: str, shared_libs: list[SharedLibrary], lib_dir: str = "") -> ManifestInfo:
+    """
+    Generate a source manifest for the given list of sources.
+    """
+    return ManifestInfo(
+        manifest = gen_shared_libs_action(
+            actions = actions,
+            out = name + ".manifest",
+            shared_libs = shared_libs,
+            gen_action = lambda actions, output, shared_libs: actions.write_json(
+                output,
+                [(paths.join(lib_dir, soname), shlib.lib.output, name) for soname, shlib in shared_libs.items()],
+            ),
+        ),
+        artifacts = [(shlib.lib.output, "") for shlib in shared_libs],
+    )
+
+def create_manifest_for_source_dir(ctx: AnalysisContext, param: str, extracted: Artifact, exclude: [str, None]) -> ManifestInfo:
+    """
+    Generate a source manifest for the given directory of sources from the given
+    rule.
+    """
+    manifest = ctx.actions.declare_output(param + ".manifest", has_content_based_path = False)
+    cmd = cmd_args(ctx.attrs._create_manifest_for_source_dir[RunInfo])
+    cmd.add("--origin={}".format(ctx.label.raw_target()))
+    cmd.add(cmd_args(manifest.as_output(), format = "--output={}"))
+    cmd.add(extracted)
+    if exclude != None:
+        cmd.add("--exclude={}".format(exclude))
+    ctx.actions.run(cmd, category = "py_source_manifest", identifier = param)
+
+    # TODO: enumerate directory?
+    return ManifestInfo(manifest = manifest.without_associated_artifacts(), artifacts = [(extracted, param)])
+
+def create_manifest_for_extensions(
+    ctx: AnalysisContext,
+    extensions: dict[str, (typing.Any, Label)],
+    # Whether to include DWP files.
+    dwp: bool = False,
+) -> ManifestInfo:
+    entries = []
+    for dest, (lib, label) in extensions.items():
+        entries.append((dest, lib.output, str(label.raw_target())))
+        if dwp and lib.dwp != None:
+            entries.append((dest + ".dwp", lib.dwp, str(label.raw_target()) + ".dwp"))
+    manifest = create_manifest_for_entries(ctx, "extensions", entries)
+
+    # Include external debug paths, even though they're not explicitly listed
+    # in the manifest, as python packaging may also consume debug paths which
+    # were referenced in native code.
+    for name, (lib, _) in extensions.items():
+        for dbginfo in project_artifacts(ctx.actions, lib.external_debug_info):
+            manifest.artifacts.append((dbginfo, name))
+
+    return manifest
diff --git a/buck2/prelude/python/needed_coverage.bzl b/buck2/prelude/python/needed_coverage.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/needed_coverage.bzl
@@ -0,0 +1,54 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:expect.bzl", "expect")
+
+# All modules owned by a library. This will be used by top-level tests to find
+# paths that corresponds to the library.
+PythonNeededCoverageInfo = provider(
+    fields = {
+        "modules": provider_field(typing.Any, default = None),  # {str: str}
+    }
+)
+
+PythonNeededCoverage = record(
+    # A value from 0.0 to 1.0 indicating the ratio of coveraged code in the
+    # associated modules.
+    ratio = field(float),
+    # Modules that need to be covered.
+    modules = field(list[str]),
+)
+
+def _parse_python_needed_coverage_spec(raw_spec: (int, Dependency, [str, None])) -> PythonNeededCoverage:
+    ratio_percentage, dep, specific_module = raw_spec
+
+    if ratio_percentage < 0 or ratio_percentage > 100:
+        fail("ratio_percentage must be between 0 and 100 (inclusive): {}".format(ratio_percentage))
+    ratio_percentage = ratio_percentage / 100.0
+
+    coverage = dep[PythonNeededCoverageInfo]
+    expect(coverage != None, "{} doesn't have a `PythonNeededCoverageInfo` provider", dep.label)
+
+    # Extract modules for this dep.
+    if specific_module != None:
+        module = coverage.modules.get(specific_module)
+        if module == None:
+            fail(
+                "module {} specified in needed_coverage not found in target {}".format(specific_module, dep.label),
+            )
+        modules = [module]
+    else:
+        modules = coverage.modules.values()
+
+    return PythonNeededCoverage(
+        ratio = ratio_percentage,
+        modules = modules,
+    )
+
+def parse_python_needed_coverage_specs(raw_specs: list[(int, Dependency, [str, None])]) -> list[PythonNeededCoverage]:
+    return [_parse_python_needed_coverage_spec(raw_spec) for raw_spec in raw_specs]
diff --git a/buck2/prelude/python/prebuilt_python_library.bzl b/buck2/prelude/python/prebuilt_python_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/prebuilt_python_library.bzl
@@ -0,0 +1,273 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:resources.bzl",
+    "gather_resources",
+    "make_resource_info",
+)
+load(
+    "@prelude//cxx:omnibus.bzl",
+    "get_excluded",
+    "get_roots",
+)
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "CPreprocessor",
+    "CPreprocessorArgs",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+    "format_system_include_arg",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+)
+load(
+    "@prelude//third-party:build.bzl",
+    "create_third_party_build_root",
+    "prefix_from_label",
+)
+load("@prelude//third-party:providers.bzl", "ThirdPartyBuild", "third_party_build_info")
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+load(":compile.bzl", "compile_manifests")
+load(":lazy_imports.bzl", "get_lazy_imports_analyzer", "run_lazy_imports_library_analyzer")
+load(":manifest.bzl", "ManifestInfo", "create_manifest_for_source_dir")
+load(":python.bzl", "NativeDepsInfo", "NativeDepsInfoTSet")
+load(
+    ":python_library.bzl",
+    "create_python_library_info",
+    "gather_dep_libraries",
+)
+load(":source_db.bzl", "create_python_source_db_info", "create_source_db_no_deps_from_manifest")
+load(":toolchain.bzl", "PythonToolchainInfo")
+
+def prebuilt_python_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    providers = []
+
+    binary_src = ctx.attrs.binary_src
+    source_dir = ctx.attrs.source_dir
+    if (binary_src == None) == (source_dir == None):
+        fail("exactly one of `binary_src` or `source_dir` must be set")
+    if source_dir != None and ctx.attrs.strip_soabi_tags:
+        fail("`strip_soabi_tags` is only supported with `binary_src`")
+
+    # Archives must be extracted before their contents can be manifested. A
+    # source directory can be manifested directly, while still using the
+    # preparation tool to discover entry points and optional C++ headers.
+    entry_points = ctx.actions.declare_output("entry_points.manifest", has_content_based_path = False)
+    entry_points_dir = ctx.actions.declare_output("__entry_points__", dir = True, has_content_based_path = False)
+    if binary_src != None:
+        source = binary_src
+        source_root = ctx.actions.declare_output("{}_extracted".format(ctx.label.name), dir = True, has_content_based_path = False)
+        cmd = cmd_args(
+            ctx.attrs._extract[RunInfo],
+            binary_src,
+            "--output",
+            source_root.as_output(),
+            "--entry-points-manifest",
+            entry_points.as_output(),
+            "--entry-points",
+            entry_points_dir.as_output(),
+        )
+    else:
+        source = source_dir
+        source_root = source_dir
+        cmd = cmd_args(
+            ctx.attrs._extract[RunInfo],
+            source_dir,
+            "--entry-points-manifest",
+            entry_points.as_output(),
+            "--entry-points",
+            entry_points_dir.as_output(),
+        )
+    if ctx.attrs.strip_soabi_tags:
+        cmd.add("--strip-soabi-tags")
+    inferred_cxx_header_dirs = None
+    if ctx.attrs.infer_cxx_header_dirs:
+        inferred_cxx_header_dirs = ctx.actions.declare_output("__cxx_header_dirs__.txt", has_content_based_path = False)
+        cmd.add(
+            "--cxx-header-dirs",
+            inferred_cxx_header_dirs.as_output(),
+        )
+    ctx.actions.run(cmd, category = "py_prepare_prebuilt_library")
+    deps, shared_deps = gather_dep_libraries(ctx.attrs.deps)
+    manifest_param = "binary_src" if binary_src != None else "source_dir"
+    src_manifest = create_manifest_for_source_dir(ctx, manifest_param, source_root, exclude = "\\.pyc$")
+    bytecode = None
+    if ctx.attrs._python_toolchain[PythonToolchainInfo].pyc_compilation_enabled:
+        bytecode = compile_manifests(ctx, [src_manifest])
+
+    lazy_imports_analyzer = get_lazy_imports_analyzer(ctx)
+    lazy_imports_cache_output = None
+    if lazy_imports_analyzer != None and getattr(ctx.attrs, "use_lifeguard_incremental", False):
+        lazy_imports_cache_output = ctx.actions.declare_output("safer_lazy_imports/library-cache.bin")
+
+    library_info = create_python_library_info(
+        ctx.actions,
+        ctx.label,
+        srcs = src_manifest,
+        src_types = src_manifest,
+        bytecode = bytecode,
+        deps = deps,
+        shared_libraries = shared_deps,
+        native_deps = ctx.actions.tset(
+            NativeDepsInfoTSet,
+            value = NativeDepsInfo(native_deps = {}),
+            children = [],
+        ),
+        is_native_dep = False,
+        lazy_imports_cache = lazy_imports_cache_output,
+    )
+    providers.append(library_info)
+
+    entry_points_manifest = ManifestInfo(
+        manifest = entry_points,
+        artifacts = [(entry_points_dir, "")],
+    )
+
+    # Create, augment and provide the linkable graph.
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            roots = get_roots(ctx.attrs.deps),
+            excluded = get_excluded(deps = ctx.attrs.deps if ctx.attrs.exclude_deps_from_merged_linking else []),
+        ),
+        deps = ctx.attrs.deps,
+    )
+    providers.append(linkable_graph)
+
+    source_db_no_deps = create_source_db_no_deps_from_manifest(ctx, src_manifest)
+    sub_targets = {"source-db-no-deps": [source_db_no_deps, create_python_source_db_info(library_info.manifests)]}
+
+    if lazy_imports_cache_output != None:
+        run_lazy_imports_library_analyzer(
+            ctx,
+            lazy_imports_analyzer,
+            lazy_imports_cache_output,
+            source_db_no_deps,
+        )
+        sub_targets["lazy-import-cache"] = [DefaultInfo(default_output = lazy_imports_cache_output)]
+    providers.append(DefaultInfo(default_output = source, sub_targets = sub_targets))
+
+    # C++ resources.
+    providers.append(
+        make_resource_info(
+            gather_resources(
+                label = ctx.label,
+                deps = ctx.attrs.deps,
+            ),
+        ),
+    )
+
+    # Allow third-party-build rules to depend on Python rules.
+    tp_prefix = prefix_from_label(ctx.label)
+    providers.append(
+        third_party_build_info(
+            actions = ctx.actions,
+            build = ThirdPartyBuild(
+                prefix = tp_prefix,
+                root = create_third_party_build_root(
+                    ctx = ctx,
+                    paths = [
+                        ("lib/python", source_root),
+                    ],
+                    manifests = [
+                        ("bin", entry_points_manifest),
+                    ],
+                ),
+                manifest = ctx.actions.write_json(
+                    "third_party_build_manifest.json",
+                    dict(
+                        c_include_paths = [],
+                        cxx_include_paths = [],
+                        lib_paths = [],
+                        libs = [],
+                        prefix = tp_prefix,
+                        py_lib_paths = ["lib/python"],
+                        runtime_lib_paths = [],
+                    ),
+                    has_content_based_path = False,
+                ),
+            ),
+            deps = ctx.attrs.deps,
+        ),
+    )
+
+    # Unix env provider.
+    providers.append(
+        create_unix_env_info(
+            actions = ctx.actions,
+            env = UnixEnv(
+                label = ctx.label,
+                python_libs = [library_info],
+                binaries = [entry_points_manifest],
+            ),
+            deps = ctx.attrs.deps,
+        ),
+    )
+
+    # If this prebuilt wheel contains headers, export them via a C++ provider.
+    pp_args = []
+    if ctx.attrs.cxx_header_dirs:
+        for header_dir in ctx.attrs.cxx_header_dirs:
+            pp_args.append(
+                format_system_include_arg(
+                    cmd_args(source_root.project(header_dir)),
+                    "clang",
+                ),
+            )
+    if inferred_cxx_header_dirs != None:
+        pp_argsfile = ctx.actions.declare_output("__cxx_header_dirs__.py_cxx_header_argsfile", has_content_based_path = False)
+
+        def write_argsfile(actions, header_dirs, output):
+            lines = []
+            for header_dir in header_dirs.read_string().splitlines():
+                lines.append(
+                    format_system_include_arg(
+                        cmd_args(source_root.project(header_dir)),
+                        "clang",
+                    )
+                )
+            actions.write(output, lines)
+
+        ctx.actions.dynamic_output(
+            dynamic = [inferred_cxx_header_dirs],
+            inputs = [],
+            outputs = [pp_argsfile.as_output()],
+            f = lambda ctx, artifacts, outputs: write_argsfile(
+                ctx.actions,
+                artifacts[inferred_cxx_header_dirs],
+                outputs[pp_argsfile],
+            ),
+        )
+        pp_args.append(
+            cmd_args(
+                pp_argsfile,
+                format = "@{}",
+                hidden = [source_root],
+            ),
+        )
+    if pp_args:
+        providers.append(
+            cxx_merge_cpreprocessors(
+                actions = ctx.actions,
+                own = [
+                    CPreprocessor(
+                        args = CPreprocessorArgs(
+                            args = pp_args,
+                        ),
+                    ),
+                ],
+                xs = cxx_inherited_preprocessor_infos(ctx.attrs.deps),
+            )
+        )
+
+    return providers
diff --git a/buck2/prelude/python/python.bzl b/buck2/prelude/python/python.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/python.bzl
@@ -0,0 +1,157 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//linking:link_info.bzl", "LinkedObject")
+load("@prelude//linking:shared_libraries.bzl", "SharedLibraryInfo")
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load(":interface.bzl", "PythonLibraryManifestsInterface")
+load(":manifest.bzl", "ManifestInfo")
+load(":toolchain.bzl", "PythonToolchainInfo")
+
+NativeDepsInfoTSet = transitive_set()
+
+NativeDepsInfo = record(
+    native_deps = field(dict[Label, Dependency], dict()),
+    dlopen_deps = field(dict[Label, Dependency], dict()),
+    shared_only_deps = field(dict[Label, Dependency], dict()),
+)
+
+PythonLibraryManifests = record(
+    label = field(Label),
+    srcs = field([ManifestInfo, None]),
+    src_types = field([ManifestInfo, None], None),
+    default_resources = field([(ManifestInfo, list[ArgLike]), None]),
+    standalone_resources = field([(ManifestInfo, list[ArgLike]), None]),
+    outplace_resources = field([(ManifestInfo, list[ArgLike]), None]),
+    bytecode = field([ManifestInfo, None]),
+    extensions = field([dict[str, LinkedObject], None]),
+)
+
+def _bytecode_artifacts(value: PythonLibraryManifests) -> list[ArgLike]:
+    return [] if value.bytecode == None else [a for a, _ in value.bytecode.artifacts]
+
+def _bytecode_manifests(value: PythonLibraryManifests) -> list[None] | Artifact:
+    return [] if value.bytecode == None else value.bytecode.manifest
+
+def _hidden_resources_for(field_name: str) -> typing.Callable[[PythonLibraryManifests], list[ArgLike]]:
+    return lambda value: [] if getattr(value, field_name) == None else getattr(value, field_name)[1]
+
+def _has_hidden_resources_for(field_name: str) -> typing.Callable[[list[bool], [PythonLibraryManifests, None]], bool]:
+    def impl(children: list[bool], value: [PythonLibraryManifests, None]) -> bool:
+        if value:
+            resources = getattr(value, field_name)
+            if resources and len(resources[1]) > 0:
+                return True
+        return any(children)
+
+    return impl
+
+def _resource_manifests_for(field_name: str) -> typing.Callable[[PythonLibraryManifests], list[None] | Artifact]:
+    return lambda value: [] if getattr(value, field_name) == None else getattr(value, field_name)[0].manifest
+
+def _resource_artifacts_for(field_name: str) -> typing.Callable[[PythonLibraryManifests], list[ArgLike]]:
+    return lambda value: [] if getattr(value, field_name) == None else [a for a, _ in getattr(value, field_name)[0].artifacts]
+
+def _source_manifests(value: PythonLibraryManifests) -> list[None] | Artifact:
+    if value.srcs == None:
+        return []
+    return value.srcs.manifest
+
+def _source_artifacts(value: PythonLibraryManifests) -> list[ArgLike]:
+    if value.srcs == None:
+        return []
+    return [a for a, _ in value.srcs.artifacts]
+
+def _source_type_manifests(value: PythonLibraryManifests) -> list[None] | Artifact:
+    if value.src_types == None:
+        return []
+    return value.src_types.manifest
+
+def _source_type_artifacts(value: PythonLibraryManifests) -> list[ArgLike]:
+    if value.src_types == None:
+        return []
+    return [a for a, _ in value.src_types.artifacts]
+
+def _extension_artifacts(value: PythonLibraryManifests) -> list[Artifact]:
+    if value.extensions == None:
+        return []
+    return [extension.output for extension in value.extensions.values()]
+
+# Mode strings mirror PackageStyle.value
+_RESOURCE_MODES = {
+    "inplace": ("", "default_resources"),
+    "outplace": ("outplace_", "outplace_resources"),
+    "standalone": ("standalone_", "standalone_resources"),
+}
+
+args_projections = {
+    "bytecode_artifacts": _bytecode_artifacts,
+    "bytecode_manifests": _bytecode_manifests,
+    "extension_artifacts": _extension_artifacts,
+    "source_artifacts": _source_artifacts,
+    "source_manifests": _source_manifests,
+    "source_type_artifacts": _source_type_artifacts,
+    "source_type_manifests": _source_type_manifests,
+}
+args_projections.update({"{}hidden_resources".format(prefix): _hidden_resources_for(field_name) for prefix, field_name in _RESOURCE_MODES.values()})
+args_projections.update({"{}resource_manifests".format(prefix): _resource_manifests_for(field_name) for prefix, field_name in _RESOURCE_MODES.values()})
+args_projections.update({"{}resource_artifacts".format(prefix): _resource_artifacts_for(field_name) for prefix, field_name in _RESOURCE_MODES.values()})
+
+PythonLibraryManifestsTSet = transitive_set(
+    args_projections = args_projections,
+    reductions = {"{}has_hidden_resources".format(prefix): _has_hidden_resources_for(field_name) for prefix, field_name in _RESOURCE_MODES.values()},
+)
+
+LazyImportsCacheTSet = transitive_set()
+
+PythonLibraryInfo = provider(
+    fields = {
+        # Shared libraries coming from cxx_python_extension targets
+        "extension_shared_libraries": provider_field(SharedLibraryInfo),
+        "is_native_dep": provider_field(bool),
+        # Transitive lazy imports caches for incremental analysis
+        "lazy_imports_caches": provider_field(LazyImportsCacheTSet | None, default = None),
+        # See the docs for PythonLibraryManifestsInterface
+        "manifests": provider_field(PythonLibraryManifestsTSet),
+        # Native deps
+        "native_deps": provider_field(NativeDepsInfoTSet),
+        # Package style for python binaries (None for libraries). One of
+        # "inplace", "standalone", "outplace". Mirrors PackageStyle from toolchain.bzl.
+        "package_style": provider_field(str | None, default = None),
+        # PAR style for python binaries (None for libraries)
+        "par_style": provider_field(str | None, default = None),
+        # Shared libraries coming from python_library and others
+        "shared_libraries": provider_field(SharedLibraryInfo),
+    }
+)
+
+def manifests_to_interface(manifests: PythonLibraryManifestsTSet) -> PythonLibraryManifestsInterface:
+    return PythonLibraryManifestsInterface(
+        src_manifests = lambda: [manifests.project_as_args("source_manifests")],
+        src_artifacts = lambda: [manifests.project_as_args("source_artifacts")],
+        bytecode_manifests = lambda: [manifests.project_as_args("bytecode_manifests")],
+        bytecode_artifacts = lambda: [manifests.project_as_args("bytecode_artifacts")],
+        resource_manifests = lambda mode = "inplace": [manifests.project_as_args("{}resource_manifests".format(_RESOURCE_MODES[mode][0]))],
+        resource_artifacts = lambda mode = "inplace": [manifests.project_as_args("{}resource_artifacts".format(_RESOURCE_MODES[mode][0]))],
+        has_hidden_resources = lambda mode = "inplace": manifests.reduce("{}has_hidden_resources".format(_RESOURCE_MODES[mode][0])),
+        hidden_resources = lambda mode = "inplace": [manifests.project_as_args("{}hidden_resources".format(_RESOURCE_MODES[mode][0]))],
+    )
+
+# The exported dependencies, and the default deps (if selected)
+def python_attr_preload_deps(ctx: AnalysisContext) -> list[Dependency]:
+    deps = []
+
+    from_attr = getattr(ctx.attrs, "preload_deps", None)
+    if from_attr:
+        deps.extend(from_attr)
+
+    toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    if toolchain.preload_deps:
+        deps.extend(toolchain.preload_deps)
+
+    return deps
diff --git a/buck2/prelude/python/python_binary.bzl b/buck2/prelude/python/python_binary.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/python_binary.bzl
@@ -0,0 +1,730 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifacts.bzl",
+    "ArtifactGroupInfo",
+    "ArtifactOutputs",  # @unused Used as a type
+)
+load("@prelude//:attrs_validators.bzl", "get_attrs_validation_specs")
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//:resources.bzl", "gather_resources")
+load("@prelude//cxx:cxx_context.bzl", "get_opt_cxx_toolchain_info")
+load(
+    "@prelude//cxx:cxx_library_utility.bzl",
+    "cxx_is_gnu",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkArgs",  # @unused Used as a type
+    "LinkedObject",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    _linkable_graph = "linkable_graph",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",
+    "to_soname",
+    "traverse_shared_library_info",
+)
+load("@prelude//linking:strip.bzl", "strip_debug_with_gnu_debuglink")
+load("@prelude//python:compute_providers.bzl", "ExecutableType", "compute_providers")
+load("@prelude//python:python.bzl", "python_attr_preload_deps")
+load(
+    "@prelude//python/linking:link_helper.bzl",
+    "LinkProviders",
+    "cxx_implicit_attrs",
+    "process_native_linking_rule",
+    "python_implicit_attrs",
+)
+load("@prelude//python/linking:native.bzl", "process_native_linking")
+load("@prelude//python/linking:native_python_util.bzl", "compute_link_strategy", "merge_native_deps")
+load("@prelude//python/linking:omnibus.bzl", "process_omnibus_linking")
+load("@prelude//utils:utils.bzl", "value_or")
+load(":compile.bzl", "compile_manifests")
+load(
+    ":interface.bzl",
+    "EntryPoint",
+    "EntryPointKind",
+)
+load(":internal_tools.bzl", "PythonInternalToolsInfo")
+load(":lazy_imports.bzl", "get_lazy_imports_analyzer", "run_lazy_imports_analyzer", "run_lazy_imports_cached_analysis", "run_lazy_imports_library_analyzer")
+load(":make_py_package.bzl", "PexModules", "PexProviders", "make_py_package")
+load(
+    ":manifest.bzl",
+    "ManifestInfo",  # @unused Used as a type
+    "create_manifest_for_extensions",
+    "create_manifest_for_source_map",
+)
+load(":python.bzl", "PythonLibraryInfo", "manifests_to_interface")
+load(
+    ":python_library.bzl",
+    "create_python_library_info",
+    "gather_dep_libraries",
+    "py_attr_resources",
+    "py_resources_deduped",
+    "qualify_srcs",
+)
+load(":python_runtime_bundle.bzl", "PythonRuntimeBundleInfo")
+load(":source_db.bzl", "create_dbg_source_db", "create_python_source_db_info", "create_source_db_no_deps")
+load(":toolchain.bzl", "NativeLinkStrategy", "PackageStyle", "PythonToolchainInfo", "get_package_style")
+load(":typing.bzl", "create_per_target_type_check", "create_type_check_validation")
+load(":versions.bzl", "LibraryName", "LibraryVersion", "gather_versioned_dependencies", "resolve_versions")
+
+# We do a lot of merging extensions, so don't use O(n) type annotations
+def _merge_extensions(
+    # {str: ("_a", "label")}
+    extensions,
+    # Label
+    incoming_label,
+    # {str: "_a"}
+    incoming_extensions,
+) -> None:
+    """
+    Merges a incoming_extensions into `extensions`. Fails if duplicate dests exist.
+    """
+    for extension_name, incoming_artifact in incoming_extensions.items():
+        existing = extensions.get(extension_name)
+        if existing != None and existing[0] != incoming_artifact:
+            existing_artifact, existing_label = existing
+            error = "Duplicate extension: {}! Conflicting mappings:\n" + "{} from {}\n" + "{} from {}"
+            fail(
+                error.format(
+                    extension_name,
+                    existing_artifact,
+                    existing_label,
+                    incoming_artifact,
+                    incoming_label,
+                ),
+            )
+        extensions[extension_name] = (incoming_artifact, incoming_label)
+
+def _qualify_entry_point(main: EntryPoint, base_module: str) -> EntryPoint:
+    qualname = main[1]
+    fqname = qualname
+    if qualname.startswith("."):
+        fqname = base_module + qualname
+        if fqname.startswith("."):
+            fqname = fqname[1:]
+    return (main[0], fqname)
+
+def python_executable(
+    ctx: AnalysisContext,
+    main: EntryPoint,
+    srcs: dict[str, Artifact],
+    default_resources: dict[str, ArtifactOutputs],
+    standalone_resources: dict[str, ArtifactOutputs] | None,
+    outplace_resources: dict[str, ArtifactOutputs] | None,
+    compile: bool,
+    allow_cache_upload: bool,
+    executable_type: ExecutableType,
+) -> list[Provider] | Promise:
+    # Returns a three tuple: the Python binary, all its potential runtime files,
+    # and a provider for its source DB.
+    raw_deps = ctx.attrs.deps
+
+    # `preload_deps` is used later to configure `LD_PRELOAD` environment variable,
+    # here we make the actual libraries to appear in the distribution.
+    preload_deps = python_attr_preload_deps(ctx)
+    raw_deps.extend(preload_deps)
+
+    selected_deps = resolve_versions(
+        gather_versioned_dependencies(raw_deps),
+        {LibraryName(value = key): LibraryVersion(value = ver) for key, ver in ctx.attrs.version_selections.items()},
+    )
+    raw_deps.extend(selected_deps)
+
+    python_deps, shared_deps = gather_dep_libraries(raw_deps, resolve_versioned_deps = False)
+
+    src_manifest = None
+    bytecode_manifest = None
+
+    python_internal_tools = ctx.attrs._python_internal_tools[PythonInternalToolsInfo]
+    for artifact in python_internal_tools.runtime_library[ArtifactGroupInfo].artifacts:
+        srcs[artifact.short_path] = artifact
+
+    if srcs:
+        src_manifest = create_manifest_for_source_map(ctx, "srcs", srcs)
+
+        python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+        if python_toolchain.pyc_compilation_enabled:
+            bytecode_manifest = compile_manifests(ctx, [src_manifest])
+
+    all_default_resources = {}
+    all_standalone_resources = {}
+    all_outplace_resources = {}
+    cxx_extra_resources = {}
+    for cxx_resources in gather_resources(ctx.label, deps = raw_deps).values():
+        for name, resource in cxx_resources.items():
+            cxx_extra_resources[paths.join("__cxx_resources__", name)] = resource
+    all_default_resources.update(cxx_extra_resources)
+    all_standalone_resources.update(cxx_extra_resources)
+    all_outplace_resources.update(cxx_extra_resources)
+
+    if default_resources:
+        all_default_resources.update(default_resources)
+    if standalone_resources:
+        all_standalone_resources.update(standalone_resources)
+    if outplace_resources:
+        all_outplace_resources.update(outplace_resources)
+
+    binary_default_resources, binary_standalone_resources, binary_outplace_resources = py_resources_deduped(
+        ctx,
+        [
+            ("", all_default_resources),
+            ("_standalone", all_standalone_resources),
+            ("_outplace", all_outplace_resources),
+        ],
+    )
+
+    library_info = create_python_library_info(
+        ctx.actions,
+        ctx.label,
+        srcs = src_manifest,
+        src_types = src_manifest,
+        default_resources = binary_default_resources,
+        standalone_resources = binary_standalone_resources,
+        outplace_resources = binary_outplace_resources,
+        bytecode = bytecode_manifest,
+        deps = python_deps,
+        shared_libraries = shared_deps,
+        native_deps = merge_native_deps(ctx, raw_deps, shared_deps = ctx.attrs.deps + preload_deps),
+        is_native_dep = False,
+        par_style = ctx.attrs.par_style,
+        package_style = get_package_style(ctx).value,
+    )
+
+    source_db_no_deps = create_source_db_no_deps(ctx, srcs)
+
+    return _convert_python_library_to_executable(
+        ctx,
+        _qualify_entry_point(
+            main,
+            ctx.attrs.base_module if ctx.attrs.base_module != None else ctx.label.package.replace("/", "."),
+        ),
+        library_info,
+        raw_deps,
+        compile,
+        allow_cache_upload,
+        src_manifest,
+        python_deps,
+        source_db_no_deps,
+        executable_type,
+    )
+
+def _add_executable_subtargets(
+    ctx,
+    exe: PexProviders,
+    dbg_source_db: DefaultInfo,
+    dbg_source_db_output: Artifact | None,
+    library_info: PythonLibraryInfo,
+    main: EntryPoint,
+    source_db_no_deps: DefaultInfo,
+    src_manifest: ManifestInfo | None,
+    python_deps: list[PythonLibraryInfo],
+) -> (PexProviders, Artifact | None):
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    exe = PexProviders(
+        default_output = exe.default_output,
+        other_outputs = exe.other_outputs,
+        other_outputs_prefix = exe.other_outputs_prefix,
+        hidden_resources = exe.hidden_resources,
+        sub_targets = exe.sub_targets,
+        run_cmd = cmd_args(python_toolchain.run_prefix, exe.run_cmd),
+        dbg_source_db = dbg_source_db_output,
+    )
+
+    exe.sub_targets.update({
+        "dbg-source-db": [dbg_source_db],
+        "library-info": [library_info],
+        "main": [DefaultInfo(default_output = ctx.actions.write_json("main.json", main, has_content_based_path = False))],
+        "source-db-no-deps": [source_db_no_deps, create_python_source_db_info(library_info.manifests)],
+    })
+
+    # Type check
+    type_checker = python_toolchain.type_checker
+    validation_output = None
+
+    if type_checker != None:
+        type_check_info = create_per_target_type_check(
+            ctx,
+            type_checker,
+            src_manifest,
+            python_deps,
+            typeshed = python_toolchain.typeshed_stubs,
+            py_version = ctx.attrs.py_version_for_type_checking,
+            typing_enabled = ctx.attrs.typing,
+            sharding_enabled = ctx.attrs.shard_typing,
+        )
+        exe.sub_targets.update({"typecheck": [type_check_info]})
+
+        if ctx.attrs.typing and ctx.attrs.typing_validation:
+            validation_output = create_type_check_validation(ctx, type_check_info.default_outputs[0])
+
+    return exe, validation_output
+
+def _compute_pex_providers(
+    ctx,
+    src_manifest: ManifestInfo | None,
+    python_deps: list[PythonLibraryInfo],
+    source_db_no_deps: DefaultInfo,
+    main: EntryPoint,
+    compile: bool,
+    library: PythonLibraryInfo,
+    allow_cache_upload: bool,
+    shared_libs: list[(SharedLibrary, str)],
+    extensions: dict[str, (LinkedObject, Label)],
+    link_args: list[LinkArgs],
+    extra: dict[str, typing.Any],
+    link_extra_artifacts: dict[str, typing.Any],
+    executable_type: ExecutableType,
+    linker_map_data = None,
+    gc_sections_data = None,
+    native_runtime_files = [],
+    build_info_manifest_entries = None,
+) -> list[Provider] | Promise:
+    dbg_source_db_output = ctx.actions.declare_output("dbg-db.json", has_content_based_path = True)
+    dbg_source_db = create_dbg_source_db(ctx, dbg_source_db_output, src_manifest, python_deps)
+
+    extra_artifacts = {key: value for key, value in link_extra_artifacts.items()}
+
+    link_strategy = compute_link_strategy(ctx)
+    build_args = ctx.attrs.build_args
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    python_internal_tools = ctx.attrs._python_internal_tools[PythonInternalToolsInfo]
+
+    if link_strategy == NativeLinkStrategy("native"):
+        entry_point = "runtime/bin/{}".format(ctx.attrs.executable_name)
+        build_args.append(cmd_args("--passthrough=--runtime-binary={}".format(entry_point)))
+
+    extra_artifacts["dbg-db.json"] = dbg_source_db_output
+
+    # Run lazy import analysis if the attribute is enabled.
+    # Prefer the cache-based path (analyze_binary from per-library caches) when
+    # incremental mode is on. Fall back to the monolithic path
+    # (analyze against dbg-db.json) for backward compatibility.
+    lazy_imports_analyzer = get_lazy_imports_analyzer(ctx)
+    if getattr(ctx.attrs, "use_lifeguard_incremental", False) and lazy_imports_analyzer != None:
+        lazy_import_analysis_output = ctx.actions.declare_output("safer_lazy_imports/lazy-import-analysis.json", has_content_based_path = False)
+        if library.lazy_imports_caches != None:
+            dep_caches = list(library.lazy_imports_caches.traverse())
+        else:
+            dep_caches = []
+
+        binary_lib_cache = ctx.actions.declare_output("safer_lazy_imports/binary-library-cache.bin")
+        # This first call pulls in the hidden __par__ modules
+        run_lazy_imports_library_analyzer(
+            ctx,
+            lazy_imports_analyzer,
+            binary_lib_cache,
+            source_db_no_deps,
+        )
+
+        # This call builds the Lifeguard output file
+        run_lazy_imports_cached_analysis(
+            ctx,
+            lazy_imports_analyzer,
+            lazy_import_analysis_output,
+            dep_caches + [binary_lib_cache],
+        )
+        extra_artifacts["safer_lazy_imports/lazy-import-analysis.json"] = lazy_import_analysis_output
+    elif getattr(ctx.attrs, "lazy_imports_analyzer", None):
+        lazy_import_analysis_output = ctx.actions.declare_output("safer_lazy_imports/lazy-import-analysis.json", has_content_based_path = False)
+        run_lazy_imports_analyzer(ctx, dbg_source_db.other_outputs, lazy_import_analysis_output, dbg_source_db_output)
+        extra_artifacts["safer_lazy_imports/lazy-import-analysis.json"] = lazy_import_analysis_output
+
+    extra_artifacts["sitecustomize.py"] = python_internal_tools.default_sitecustomize
+
+    # Add bundled runtime
+    if ctx.attrs.runtime_bundle:
+        bundle = ctx.attrs.runtime_bundle[PythonRuntimeBundleInfo]
+        build_args.append(cmd_args("--passthrough=--python-home=runtime"))
+        extra_artifacts["runtime/bin/{}".format(bundle.py_bin.basename)] = bundle.py_bin
+        extra_artifacts["runtime/lib/{}".format(bundle.stdlib.basename)] = bundle.stdlib
+        if bundle.libpython:
+            if link_strategy != NativeLinkStrategy("native"):
+                build_args.append(cmd_args("--passthrough=--preload=runtime/lib/{}".format(bundle.libpython.basename)))
+            extra_artifacts["runtime/lib/{}".format(bundle.libpython.basename)] = bundle.libpython
+        if link_strategy != NativeLinkStrategy("native"):
+            entry_point = "runtime/bin/{}".format(bundle.py_bin.basename)
+            build_args.append(cmd_args(["--passthrough=--runtime-binary={}".format(entry_point)]))
+            extra_artifacts[entry_point] = bundle.py_bin
+        if ctx.attrs.runtime_bundle_full:
+            extra_artifacts["runtime/include/{}".format(bundle.include.basename)] = bundle.include
+
+    # Add additional runtime libs
+    for name, dep in ctx.attrs.runtime_libs.items():
+        dep_info = dep.get(DefaultInfo)
+        if dep_info != None:
+            extra_artifacts["runtime/lib/{}".format(name)] = dep_info.default_outputs[0]
+
+    extra_manifests = create_manifest_for_source_map(ctx, "extra_manifests", extra_artifacts)
+    package_style = get_package_style(ctx)
+
+    # Collect HIP sidecars from shared libs before stripping (strip replaces LinkedObjects).
+    hip_all_debug_files = {}
+    for shlib, _libdir in shared_libs:
+        for arch, files in shlib.lib.hip_arch_debug_files.items():
+            hip_all_debug_files.setdefault(arch, [])
+            hip_all_debug_files[arch].extend(files)
+
+    # Strip native libraries and extensions and update the .gnu_debuglink references if we are extracting
+    # debug symbols from the par
+    debuginfo_files = []
+    debuginfos = {}
+    if ctx.attrs.strip_libpar == "extract" and package_style in [PackageStyle("standalone"), PackageStyle("outplace")] and cxx_is_gnu(ctx):
+        stripped_shlibs = []
+        for shlib, libdir in shared_libs:
+            name = paths.join(
+                libdir,
+                value_or(
+                    shlib.soname.as_str(),
+                    shlib.lib.unstripped_output.short_path,
+                ),
+            )
+            existing = debuginfos.get(name)
+            if existing == None:
+                stripped, debuginfo = strip_debug_with_gnu_debuglink(
+                    ctx = ctx,
+                    name = name,
+                    obj = shlib.lib.unstripped_output,
+                )
+                debuginfos[name] = (stripped, debuginfo)
+            else:
+                stripped, debuginfo = existing
+
+            shlib = SharedLibrary(
+                soname = shlib.soname,
+                label = shlib.label,
+                lib = LinkedObject(
+                    output = stripped,
+                    unstripped_output = shlib.lib.unstripped_output,
+                    dwp = shlib.lib.dwp,
+                ),
+            )
+            stripped_shlibs.append((shlib, libdir))
+            debuginfo_files.append(((libdir, shlib, ".debuginfo"), debuginfo))
+        shared_libs = stripped_shlibs
+        stripped_extensions = {}
+        for name, (extension, label) in extensions.items():
+            stripped, debuginfo = strip_debug_with_gnu_debuglink(
+                ctx = ctx,
+                name = name,
+                obj = extension.unstripped_output,
+            )
+            stripped_extensions[name] = (
+                LinkedObject(
+                    output = stripped,
+                    unstripped_output = extension.unstripped_output,
+                    dwp = extension.dwp,
+                ),
+                label,
+            )
+            debuginfo_files.append((name + ".debuginfo", debuginfo))
+        extensions = stripped_extensions
+
+    # Combine sources and extensions into a map of all modules.
+    pex_modules = PexModules(
+        manifests = manifests_to_interface(library.manifests),
+        extra_manifests = extra_manifests,
+        compile = compile,
+        extensions = create_manifest_for_extensions(
+            ctx,
+            extensions,
+            dwp = ctx.attrs.package_split_dwarf_dwp,
+        )
+        if extensions
+        else None,
+    )
+
+    # Add GPU sidecars to debuginfo regardless of strip_libpar setting.
+    for debug_artifacts in hip_all_debug_files.values():
+        for debug_artifact in debug_artifacts:
+            debuginfo_files.append(
+                (debug_artifact.basename, debug_artifact),
+            )
+
+    # Convert preloaded deps to a set of their names to be loaded by.
+    preload_labels = set([_linkable_graph(d).label for d in python_attr_preload_deps(ctx) if _linkable_graph(d)])
+
+    # Build the PEX.
+    pex = make_py_package(
+        ctx = ctx,
+        python_toolchain = python_toolchain,
+        python_internal_tools = python_internal_tools,
+        make_py_package_cmd = ctx.attrs.make_py_package[RunInfo] if ctx.attrs.make_py_package != None else None,
+        package_style = package_style,
+        build_args = build_args,
+        pex_modules = pex_modules,
+        shared_libraries = shared_libs,
+        preload_labels = preload_labels,
+        main = main,
+        allow_cache_upload = allow_cache_upload,
+        debuginfo_files = debuginfo_files,
+        link_args = link_args,
+        manifest_entries_overlay = build_info_manifest_entries,
+    )
+
+    pex.sub_targets.update(extra)
+
+    # Native PARs build their executable via cxx_executable, which already emits
+    # `<binary>.resources.json` and adds it (plus the referenced C++ resources)
+    # to its runtime_files. process_native_linking otherwise drops these, so the
+    # manifest is declared next to the binary but never materialized, and the C++
+    # build::ExternalResourceManager FATALs at startup with
+    # "Cannot find resource: ...". Re-attach them as PAR runtime files so they
+    # land next to the executable.
+    if native_runtime_files:
+        pex.other_outputs.extend(native_runtime_files)
+
+    if linker_map_data != None:
+        pex.sub_targets["linker-map"] = [
+            DefaultInfo(
+                default_output = linker_map_data.map,
+                other_outputs = [linker_map_data.binary],
+            )
+        ]
+
+    if gc_sections_data != None:
+        pex.sub_targets["gc-sections"] = [
+            DefaultInfo(
+                default_output = gc_sections_data.gc_sections,
+                other_outputs = [gc_sections_data.binary],
+            )
+        ]
+
+    if hip_all_debug_files:
+        all_files = [f for files in hip_all_debug_files.values() for f in files]
+        hip_debug_manifest = ctx.actions.write(
+            "__hip_debug_manifest_par__.txt",
+            cmd_args(all_files, delimiter = "\n"),
+        )
+        pex.sub_targets["hip_debug"] = [
+            DefaultInfo(
+                default_output = hip_debug_manifest,
+                other_outputs = all_files,
+                sub_targets = {arch: [DefaultInfo(default_outputs = files)] for arch, files in hip_all_debug_files.items()},
+            ),
+        ]
+
+    updated_pex, validation_output = _add_executable_subtargets(
+        ctx, pex, dbg_source_db, dbg_source_db_output, library, main, source_db_no_deps, src_manifest, python_deps
+    )
+
+    providers = compute_providers(ctx, updated_pex, executable_type)
+
+    # Build-time type check validation
+    validation_specs = get_attrs_validation_specs(ctx)
+    if validation_output != None:
+        validation_specs.append(ValidationSpec(name = "pyre", validation_result = validation_output))
+    if validation_specs:
+        providers.append(ValidationInfo(validations = validation_specs))
+
+    return providers
+
+def _convert_python_library_to_executable(
+    ctx: AnalysisContext,
+    main: EntryPoint,
+    library: PythonLibraryInfo,
+    deps: list[Dependency],
+    compile: bool,
+    allow_cache_upload: bool,
+    src_manifest: ManifestInfo | None,
+    python_deps: list[PythonLibraryInfo],
+    source_db_no_deps: DefaultInfo,
+    executable_type: ExecutableType,
+) -> list[Provider] | Promise:
+    extra = {}
+
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    python_internal_tools = ctx.attrs._python_internal_tools[PythonInternalToolsInfo]
+    package_style = get_package_style(ctx)
+
+    extra_artifacts = {}
+    link_args = []
+    link_strategy = compute_link_strategy(ctx)
+    native_runtime_files = []
+
+    if link_strategy == NativeLinkStrategy("native"):
+        invalidate_build_info_on_python_sources = getattr(ctx.attrs, "_generated_build_info_enabled", False) and ctx.attrs._generated_build_info_mode == "full"
+        generated_build_info_invalidation_deps = deps if invalidate_build_info_on_python_sources else []
+        generated_build_info_invalidation_sources = (
+            [artifact for artifact, _ in src_manifest.artifacts] if invalidate_build_info_on_python_sources and src_manifest != None else []
+        )
+
+        use_anon_target = getattr(ctx.attrs, "use_anon_target_for_analysis", False)
+        if use_anon_target:
+            native_deps = {}
+            dlopen_deps = {}
+            shared_only_deps = {}
+            for info in library.native_deps.traverse():
+                native_deps.update(info.native_deps)
+                dlopen_deps.update(info.dlopen_deps)
+                shared_only_deps.update(info.shared_only_deps)
+
+            explicit_attrs = {
+                "allow_cache_upload": allow_cache_upload,
+                "deps": list(native_deps.values()),
+                "dlopen_deps": list(dlopen_deps.values()),
+                "generated_build_info_invalidation_deps": generated_build_info_invalidation_deps,
+                "generated_build_info_invalidation_sources": generated_build_info_invalidation_sources,
+                "name": "python_linking:" + ctx.attrs.name,
+                "package_style": package_style,
+                "rpath": ctx.attrs.name,
+                "shared_only_deps": list(shared_only_deps.values()),
+                "static_extension_utils": ctx.attrs.static_extension_utils,
+                "transformation_spec": ctx.attrs.transformation_spec,
+                "_cxx_toolchain": ctx.attrs._cxx_toolchain,
+                "_python_internal_tools": ctx.attrs._python_internal_tools,
+                "_python_toolchain": ctx.attrs._python_toolchain,
+            }
+            implicit_attrs = {
+                a: getattr(ctx.attrs, a) for a in (set(cxx_implicit_attrs.keys()) | set(python_implicit_attrs.keys())) - set(explicit_attrs.keys())
+            }
+            return ctx.actions.anon_target(
+                process_native_linking_rule,
+                explicit_attrs | implicit_attrs,
+            ).promise.map(
+                lambda providers: _compute_pex_providers(
+                    ctx,
+                    src_manifest,
+                    python_deps,
+                    source_db_no_deps,
+                    main,
+                    compile,
+                    library,
+                    allow_cache_upload,
+                    providers[LinkProviders].shared_libraries,
+                    providers[LinkProviders].extensions,
+                    providers[LinkProviders].link_args,
+                    providers[LinkProviders].extra,
+                    providers[LinkProviders].extra_artifacts,
+                    executable_type,
+                    providers[LinkProviders].linker_map_data,
+                    providers[LinkProviders].gc_sections_data,
+                    native_runtime_files = providers[LinkProviders].runtime_files,
+                    build_info_manifest_entries = providers[LinkProviders].build_info_manifest_entries,
+                )
+            )
+        else:
+            shared_libs, extensions, link_args, extra, extra_artifacts, linker_map_data, gc_sections_data, native_runtime_files, build_info_manifest_entries = (
+                process_native_linking(
+                    ctx,
+                    deps,
+                    python_toolchain,
+                    python_internal_tools,
+                    package_style,
+                    allow_cache_upload,
+                    generated_build_info_invalidation_deps = generated_build_info_invalidation_deps,
+                    generated_build_info_invalidation_sources = generated_build_info_invalidation_sources,
+                )
+            )
+            if ctx.attrs.runtime_bundle:
+                runtime_bundle = ctx.attrs.runtime_bundle[PythonRuntimeBundleInfo]
+
+                # On some platforms libpython does not link with system libraries. Include libraries
+                # in the PAR in this case.
+                for dep in runtime_bundle.shared_libs:
+                    lib = dep.get(DefaultInfo).default_outputs[0]
+                    shared_libs.append(
+                        (
+                            # There's probably a smarter way to get the shared library object out of the
+                            # dependency, but I'm not sure what that is.
+                            SharedLibrary(
+                                soname = to_soname(lib.basename),
+                                label = dep.label,
+                                lib = LinkedObject(output = lib, unstripped_output = lib),
+                            ),
+                            "",
+                        )
+                    )
+
+    else:
+        build_info_manifest_entries = None
+        linker_map_data = None
+        gc_sections_data = None
+        extensions = {}
+        for manifest in library.manifests.traverse():
+            if manifest.extensions:
+                _merge_extensions(extensions, manifest.label, manifest.extensions)
+        if link_strategy == NativeLinkStrategy("merged"):
+            shared_libs, extensions = process_omnibus_linking(ctx, deps, extensions, python_toolchain, extra)
+        else:
+            shared_libs = [(shared_lib, "") for shared_lib in traverse_shared_library_info(library.shared_libraries, transformation_provider = None)]
+
+            # darwin and windows expect self-contained dynamically linked
+            # python extensions without additional transitive shared libraries
+            shared_libs += [
+                (extension_shared_lib, "")
+                for extension_shared_lib in traverse_shared_library_info(library.extension_shared_libraries, transformation_provider = None)
+            ]
+
+    return _compute_pex_providers(
+        ctx,
+        src_manifest,
+        python_deps,
+        source_db_no_deps,
+        main,
+        compile,
+        library,
+        allow_cache_upload,
+        shared_libs,
+        extensions,
+        link_args,
+        extra,
+        extra_artifacts,
+        executable_type,
+        linker_map_data = linker_map_data if link_strategy == NativeLinkStrategy("native") else None,
+        gc_sections_data = gc_sections_data if link_strategy == NativeLinkStrategy("native") else None,
+        native_runtime_files = native_runtime_files,
+        build_info_manifest_entries = build_info_manifest_entries,
+    )
+
+def python_binary_impl(ctx: AnalysisContext) -> list[Provider] | Promise:
+    main_module = ctx.attrs.main_module
+    main_function = ctx.attrs.main_function
+    if main_module != None and ctx.attrs.main != None:
+        fail("Only one of main_module or main may be set. Prefer main_function as main and main_module are considered deprecated")
+    elif main_module != None and main_function != None:
+        fail("Only one of main_module or main_function may be set. Prefer main_function.")
+    elif ctx.attrs.main != None and main_function == None:
+        main_module = "." + ctx.attrs.main.short_path.replace("/", ".")
+        if main_module.endswith(".py"):
+            main_module = main_module[:-3]
+
+    if main_module != None:
+        main = (EntryPointKind("module"), main_module)
+    else:
+        main = (EntryPointKind("function"), main_function)
+
+    srcs = {}
+    if ctx.attrs.main != None:
+        srcs[ctx.attrs.main.short_path] = ctx.attrs.main
+    srcs = qualify_srcs(ctx.label, ctx.attrs.base_module, srcs)
+    default_resources_map, standalone_resources_map, outplace_resources_map = py_attr_resources(ctx)
+    standalone_resources = qualify_srcs(ctx.label, ctx.attrs.base_module, standalone_resources_map)
+    outplace_resources = qualify_srcs(ctx.label, ctx.attrs.base_module, outplace_resources_map)
+    default_resources = qualify_srcs(ctx.label, ctx.attrs.base_module, default_resources_map)
+
+    cxx_toolchain_info = get_opt_cxx_toolchain_info(ctx)
+    toolchain_allow_cache_upload = cxx_toolchain_info.cxx_compiler_info.allow_cache_upload if cxx_toolchain_info else None
+
+    return python_executable(
+        ctx,
+        main,
+        srcs,
+        default_resources,
+        standalone_resources,
+        outplace_resources,
+        compile = value_or(ctx.attrs.compile, False),
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs, toolchain_allow_cache_upload),
+        executable_type = ExecutableType("binary"),
+    )
diff --git a/buck2/prelude/python/python_library.bzl b/buck2/prelude/python/python_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/python_library.bzl
@@ -0,0 +1,562 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifacts.bzl",
+    "ArtifactOutputs",  # @unused Used as a type
+    "unpack_artifact_map",
+)
+load("@prelude//:attrs_validators.bzl", "get_attrs_validation_specs")
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//:resources.bzl",
+    "gather_resources",
+    "make_resource_info",
+)
+load("@prelude//cxx:cxx_link_utility.bzl", "shared_libs_symlink_tree_name")
+load(
+    "@prelude//cxx:omnibus.bzl",
+    "get_excluded",
+    "get_roots",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkedObject",  # @unused Used as a type
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableRootInfo",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+)
+load("@prelude//linking:shared_libraries.bzl", "SharedLibraryInfo", "merge_shared_libraries")
+load("@prelude//linking:stamp_build_info.bzl", "PRE_STAMPED_SUFFIX")
+load(
+    "@prelude//python/linking:native_python_util.bzl",
+    "merge_cxx_extension_info",
+    "merge_native_deps",
+)
+load(
+    "@prelude//third-party:build.bzl",
+    "create_third_party_build_root",
+    "prefix_from_label",
+)
+load("@prelude//third-party:providers.bzl", "ThirdPartyBuild", "third_party_build_info")
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "from_named_set")
+load(":compile.bzl", "compile_manifests")
+load(":lazy_imports.bzl", "get_lazy_imports_analyzer", "run_lazy_imports_library_analyzer")
+load(
+    ":manifest.bzl",
+    "ManifestInfo",  # @unused Used as a type
+    "create_manifest_for_source_map",
+)
+load(":needed_coverage.bzl", "PythonNeededCoverageInfo")
+load(":python.bzl", "LazyImportsCacheTSet", "NativeDepsInfoTSet", "PythonLibraryInfo", "PythonLibraryManifests", "PythonLibraryManifestsTSet")
+load(":source_db.bzl", "create_python_source_db_info", "create_source_db_no_deps")
+load(":toolchain.bzl", "PythonToolchainInfo")
+load(":typing.bzl", "create_per_target_type_check", "create_type_check_validation")
+load(":versions.bzl", "VersionedDependenciesInfo", "gather_versioned_dependencies", "resolve_versions")
+
+def dest_prefix(label: Label, base_module: [None, str]) -> str:
+    """
+    Find the prefix to use for placing files inside of the python link tree
+
+    This uses the label's package path if `base_module` is `None`, or `base_module`,
+    with '.' replaced by '/', if not None. If non-empty, the returned prefix will
+    end with a '/'
+    """
+    if base_module == None:
+        prefix = label.package
+    else:
+        prefix = base_module.replace(".", "/")
+
+    # Add a leading slash if we need to, but don't do that for an empty base_module
+    if prefix != "":
+        prefix += "/"
+
+    return prefix
+
+def qualify_srcs(label: Label, base_module: [None, str], srcs: dict[str, typing.Any]) -> dict[str, typing.Any]:
+    """
+    Fully qualify package-relative sources with the rule's base module.
+
+    Arguments:
+        label: The label for the `python_library`. Used for errors, and to construct
+               the path for each source file
+        base_module: If provided, the module to prefix all files from `srcs` with in
+                     the eventual binary. If `None`, use the package path.
+                     Usage of this is discouraged, because it makes on-disk paths
+                     not match the module in execution.
+        srcs: A dictionary of {relative destination path: source file}. The derived
+              base module will be prepended to the destination.
+    """
+    prefix = dest_prefix(label, base_module)
+
+    # Use `path.normalize` here in case items in `srcs` contains relative paths.
+    return {paths.normalize(prefix + dest): src for dest, src in srcs.items()}
+
+def create_python_needed_coverage_info(label: Label, base_module: [None, str], srcs: list[str]) -> PythonNeededCoverageInfo:
+    prefix = dest_prefix(label, base_module)
+    return PythonNeededCoverageInfo(
+        modules = {src: prefix + src for src in srcs},
+    )
+
+def create_python_library_info(
+    actions: AnalysisActions,
+    label: Label,
+    native_deps: NativeDepsInfoTSet,
+    is_native_dep: bool,
+    srcs: [ManifestInfo, None] = None,
+    src_types: [ManifestInfo, None] = None,
+    bytecode: [ManifestInfo, None] = None,
+    default_resources: [(ManifestInfo, list[ArgLike]), None] = None,
+    standalone_resources: [(ManifestInfo, list[ArgLike]), None] = None,
+    outplace_resources: [(ManifestInfo, list[ArgLike]), None] = None,
+    extensions: [dict[str, LinkedObject], None] = None,
+    deps: list[PythonLibraryInfo] = [],
+    shared_libraries: list[SharedLibraryInfo] = [],
+    extension_shared_libraries: list[SharedLibraryInfo] = [],
+    par_style: str | None = None,
+    package_style: str | None = None,
+    lazy_imports_cache: [Artifact, None] = None,
+):
+    """
+    Create a `PythonLibraryInfo` for a set of sources and deps
+
+    Arguments:
+        label: The label for the `python_library`. Used for errors, and to construct
+               the path for each source file
+        srcs: A dictionary of {relative destination path: source file}.
+        resources: A dictionary of {relative destination path: source file}.
+        prebuilt_libraries: Prebuilt python libraries to include.
+        deps: A list of `PythonLibraryInfo` objects from dependencies. These are merged
+              into the resulting `PythonLibraryInfo`, as python needs all files present
+              in the end
+    Return:
+        A fully merged `PythonLibraryInfo` provider, or fails if deps and/or srcs
+        have destination paths that collide.
+    """
+
+    manifests = PythonLibraryManifests(
+        label = label,
+        srcs = srcs,
+        src_types = src_types,
+        default_resources = default_resources,
+        standalone_resources = standalone_resources,
+        outplace_resources = outplace_resources,
+        bytecode = bytecode,
+        extensions = extensions,
+    )
+
+    new_shared_libraries = merge_shared_libraries(
+        actions,
+        deps = shared_libraries + [dep.shared_libraries for dep in deps],
+    )
+
+    new_extension_shared_libraries = merge_shared_libraries(
+        actions,
+        deps = extension_shared_libraries + [dep.extension_shared_libraries for dep in deps],
+    )
+
+    dep_cache_children = [dep.lazy_imports_caches for dep in deps if dep.lazy_imports_caches != None]
+    if lazy_imports_cache != None:
+        lazy_imports_caches = actions.tset(LazyImportsCacheTSet, value = lazy_imports_cache, children = dep_cache_children)
+    elif dep_cache_children:
+        lazy_imports_caches = actions.tset(LazyImportsCacheTSet, children = dep_cache_children)
+    else:
+        lazy_imports_caches = None
+
+    return PythonLibraryInfo(
+        manifests = actions.tset(PythonLibraryManifestsTSet, value = manifests, children = [dep.manifests for dep in deps]),
+        shared_libraries = new_shared_libraries,
+        extension_shared_libraries = new_extension_shared_libraries,
+        is_native_dep = is_native_dep,
+        lazy_imports_caches = lazy_imports_caches,
+        native_deps = native_deps,
+        par_style = par_style,
+        package_style = package_style,
+    )
+
+def gather_dep_libraries(raw_deps: list[Dependency], resolve_versioned_deps: bool = True) -> (list[PythonLibraryInfo], list[SharedLibraryInfo]):
+    """
+    Takes a list of raw dependencies, and partitions them into python_library / shared library providers.
+    If resolve_versions is True, it also collects versioned_library dependencies and uses their default version. Otherwise these are skipped, and should be handled elsewhere.
+    """
+    deps = []
+    shared_libraries = []
+    for dep in raw_deps:
+        if resolve_versioned_deps and VersionedDependenciesInfo in dep:
+            vdeps, vshlibs = gather_dep_libraries(resolve_versions(dep[VersionedDependenciesInfo], {}))
+            deps.extend(vdeps)
+            shared_libraries.extend(vshlibs)
+
+        if PythonLibraryInfo in dep:
+            deps.append(dep[PythonLibraryInfo])
+        elif SharedLibraryInfo in dep:
+            shared_libraries.append(dep[SharedLibraryInfo])
+        else:
+            # Non-Python dependencies (e.g. genrule deps on third-party whls) are
+            # silently ignored here; they don't provide PythonLibraryInfo or
+            # SharedLibraryInfo but are valid transitive deps.
+            pass
+    return (deps, shared_libraries)
+
+def _exclude_deps_from_omnibus(ctx: AnalysisContext, srcs: dict[str, Artifact]) -> bool:
+    # User-specified parameter.
+    if ctx.attrs.exclude_deps_from_merged_linking:
+        return True
+
+    # In some cases, Python library rules package prebuilt native extensions,
+    # in which case, we can't support library merging (since we can't re-link
+    # these extensions against new libraries).
+    for src in srcs:
+        # TODO(agallagher): Ideally, we'd prevent sources with these suffixes
+        # and requires specifying them another way to make this easier to detect.
+        if paths.split_extension(src)[1] in (".so", ".dll", ".pyd"):
+            return True
+
+    return False
+
+def _attr_srcs(ctx: AnalysisContext) -> dict[str, Artifact]:
+    return dict(from_named_set(ctx.attrs.srcs))
+
+def _attr_resources(ctx: AnalysisContext) -> dict[str, Artifact | Dependency]:
+    return dict(from_named_set(ctx.attrs.resources))
+
+def py_attr_resources(ctx: AnalysisContext) -> (dict[str, ArtifactOutputs], dict[str, ArtifactOutputs], dict[str, ArtifactOutputs]):
+    """
+    Return the resources provided by this rule as three maps from resource name
+    to ArtifactOutputs: one for the default (inplace) build, one for standalone,
+    and one for outplace.
+
+    For python_binary resources, standalone substitutes the dep with its `.par`
+    artifact, while outplace substitutes with the `[outplace]` subtarget so the
+    full link-tree directory is materialized alongside the bash script.
+    """
+    resources = _attr_resources(ctx)
+    standalone_artifacts = {}
+    outplace_overrides = {}
+    for key, value in resources.items():
+        s_resource = value
+        if not isinstance(value, Artifact) and DefaultInfo in value:
+            sub_targets = value[DefaultInfo].sub_targets
+            if "standalone" in sub_targets:
+                s_resource = sub_targets["standalone"][DefaultInfo].default_outputs[0]
+            if "outplace" in sub_targets:
+                outplace_di = sub_targets["outplace"][DefaultInfo]
+                outplace_overrides[key] = ArtifactOutputs(
+                    default_output = outplace_di.default_outputs[0],
+                    nondebug_runtime_files = outplace_di.other_outputs,
+                    other_outputs = outplace_di.other_outputs,
+                )
+        standalone_artifacts[key] = s_resource
+
+    default_resources = unpack_artifact_map(resources)
+    standalone_resources = unpack_artifact_map(standalone_artifacts)
+    outplace_resources = dict(default_resources)
+    outplace_resources.update(outplace_overrides)
+
+    return default_resources, standalone_resources, outplace_resources
+
+def py_resources_deduped(ctx: AnalysisContext, keyed_resources: list[(str, dict[str, ArtifactOutputs])]) -> list[[(ManifestInfo, list[ArgLike]), None]]:
+    """
+    Build one resource manifest per entry, aliasing entries whose resource
+    maps are identical to a single manifest (the maps only diverge when a
+    resource dep exposes style-specific subtargets). Returns one result per
+    entry, None for empty maps.
+    """
+    built = []
+    results = []
+    for suffix, resources in keyed_resources:
+        if not resources:
+            results.append(None)
+            continue
+        result = None
+        for seen_resources, seen_result in built:
+            if resources == seen_resources:
+                result = seen_result
+                break
+        if result == None:
+            result = py_resources(ctx, resources, suffix)
+            built.append((resources, result))
+        results.append(result)
+    return results
+
+def py_resources(ctx: AnalysisContext, resources: dict[str, ArtifactOutputs], suffix: str = "") -> (ManifestInfo, list[ArgLike]):
+    """
+    Generate a manifest to wrap this rules resources.
+    """
+    d = {name: resource.default_output for name, resource in resources.items()}
+    hidden = []
+    for name, resource in resources.items():
+        for o in resource.nondebug_runtime_files:
+            # HACK: this is a heuristic to detect shared libs emitted from cpp_binary rules.
+            if isinstance(o, Artifact) and (
+                (
+                    o.basename
+                    == (
+                        shared_libs_symlink_tree_name(
+                            resource.default_output.short_path,
+                        )
+                    )
+                )
+                or (
+                    o.basename
+                    == (
+                        shared_libs_symlink_tree_name(
+                            resource.default_output.short_path + PRE_STAMPED_SUFFIX,
+                        )
+                    )
+                )
+            ):
+                # Package the binary's shared libs next to the binary
+                # (the path is stored in RPATH relative to the binary).
+                d[paths.join(paths.dirname(name), o.basename)] = o
+            elif isinstance(o, Artifact) and o.basename.endswith("#link-tree"):
+                # HACK: heuristic to detect Python runtime directories from python_binary rules.
+                # Package the runtime directory next to the startup script
+                d[paths.join(paths.dirname(name), o.basename)] = o
+            else:
+                hidden.append(o)
+    manifest = create_manifest_for_source_map(ctx, "resources{}".format(suffix), d)
+    return manifest, dedupe(hidden)
+
+def _src_types(srcs: dict[str, Artifact], type_stubs: dict[str, Artifact]) -> dict[str, Artifact]:
+    src_types = {}
+
+    # First, add all `.py` files.
+    for name, src in srcs.items():
+        _, ext = paths.split_extension(name)
+        if ext == ".py" or ext == ".pyi":
+            src_types[name] = src
+
+    # Override sources which have a corresponding type stub.
+    for name, src in type_stubs.items():
+        base, ext = paths.split_extension(name)
+        expect(ext == ".pyi", "type stubs must have `.pyi` suffix: {}", name)
+        src_types.pop(base + ".py", None)
+        src_types[name] = src
+
+    return src_types
+
+def python_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    # Versioned params should be intercepted and converted away via the stub.
+    expect(not ctx.attrs.versioned_srcs)
+    expect(not ctx.attrs.versioned_resources)
+
+    providers = []
+    sub_targets = {}
+
+    srcs = _attr_srcs(ctx)
+    qualified_srcs = qualify_srcs(ctx.label, ctx.attrs.base_module, srcs)
+    default_resources_map, standalone_resources_map, outplace_resources_map = py_attr_resources(ctx)
+    standalone_resources = qualify_srcs(ctx.label, ctx.attrs.base_module, standalone_resources_map)
+    outplace_resources = qualify_srcs(ctx.label, ctx.attrs.base_module, outplace_resources_map)
+    default_resources = qualify_srcs(ctx.label, ctx.attrs.base_module, default_resources_map)
+    type_stubs = qualify_srcs(ctx.label, ctx.attrs.base_module, from_named_set(ctx.attrs.type_stubs))
+    src_types = _src_types(qualified_srcs, type_stubs)
+
+    src_manifest = create_manifest_for_source_map(ctx, "srcs", qualified_srcs) if qualified_srcs else None
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+
+    # For the common all-`.py`, no-stub-override case the type manifest lists
+    # exactly the srcs, so reuse that manifest instead of writing a copy.
+    if src_types == qualified_srcs:
+        src_type_manifest = src_manifest
+    elif src_types:
+        src_type_manifest = create_manifest_for_source_map(ctx, "type_stubs", src_types)
+    else:
+        src_type_manifest = None
+
+    # Compile bytecode.
+    bytecode = None
+    if src_manifest != None and python_toolchain.pyc_compilation_enabled:
+        bytecode = compile_manifests(ctx, [src_manifest])
+        sub_targets["compile"] = [DefaultInfo(default_output = bytecode.artifacts[0][0])]
+        sub_targets["src-manifest"] = [DefaultInfo(default_output = src_manifest.manifest, other_outputs = [a for a, _ in src_manifest.artifacts])]
+
+    raw_deps = ctx.attrs.deps
+    default_resource_manifest, standalone_resource_manifest, outplace_resource_manifest = py_resources_deduped(
+        ctx,
+        [
+            ("", default_resources),
+            ("_standalone", standalone_resources),
+            ("_outplace", outplace_resources),
+        ],
+    )
+    deps, shared_libraries = gather_dep_libraries(raw_deps, resolve_versioned_deps = False)
+    providers.append(gather_versioned_dependencies(raw_deps))
+
+    native_deps = merge_native_deps(ctx, raw_deps, shared_deps = raw_deps)
+
+    lazy_imports_analyzer = get_lazy_imports_analyzer(ctx)
+    lazy_imports_cache_output = None
+    if lazy_imports_analyzer != None and getattr(ctx.attrs, "use_lifeguard_incremental", False):
+        lazy_imports_cache_output = ctx.actions.declare_output("safer_lazy_imports/library-cache.bin")
+
+    library_info = create_python_library_info(
+        ctx.actions,
+        ctx.label,
+        srcs = src_manifest,
+        src_types = src_type_manifest,
+        default_resources = default_resource_manifest,
+        standalone_resources = standalone_resource_manifest,
+        outplace_resources = outplace_resource_manifest,
+        bytecode = bytecode,
+        deps = deps,
+        shared_libraries = shared_libraries,
+        native_deps = native_deps,
+        is_native_dep = False,
+        lazy_imports_cache = lazy_imports_cache_output,
+    )
+    providers.append(library_info)
+    providers.append(
+        create_unix_env_info(
+            actions = ctx.actions,
+            env = UnixEnv(
+                label = ctx.label,
+                python_libs = [library_info],
+            ),
+            deps = raw_deps,
+        ),
+    )
+
+    # Allow third-party-build rules to depend on Python rules.
+    tp_prefix = prefix_from_label(ctx.label)
+    third_party_build = third_party_build_info(
+        actions = ctx.actions,
+        build = ThirdPartyBuild(
+            prefix = tp_prefix,
+            root = create_third_party_build_root(
+                ctx = ctx,
+                # TODO(agallagher): use constraints to get py version.
+                manifests = ([("lib/python", src_manifest)] if src_manifest != None else [])
+                + ([("lib/python", default_resource_manifest[0])] if default_resource_manifest != None else []),
+            ),
+            manifest = ctx.actions.write_json(
+                "third_party_build_manifest.json",
+                dict(
+                    prefix = tp_prefix,
+                    py_lib_paths = ["lib/python"],
+                    bin_paths = [],
+                    lib_paths = [],
+                    runtime_lib_paths = [],
+                    libs = [],
+                ),
+                has_content_based_path = False,
+            ),
+        ),
+        deps = raw_deps,
+    )
+    providers.append(third_party_build)
+    sub_targets["third-party-build"] = [
+        DefaultInfo(
+            default_output = third_party_build.build.root.artifact,
+            sub_targets = dict(
+                manifest = [DefaultInfo(default_output = third_party_build.build.manifest)],
+            ),
+        ),
+    ]
+
+    providers.append(create_python_needed_coverage_info(ctx.label, ctx.attrs.base_module, srcs.keys()))
+
+    # Source DBs.
+    source_db_no_deps = create_source_db_no_deps(ctx, src_types)
+    sub_targets["source-db-no-deps"] = [source_db_no_deps, create_python_source_db_info(library_info.manifests)]
+
+    # Lazy imports library cache (action scheduling — output was declared above).
+    # Use qualified_srcs (.py files) not src_types (.pyi stubs override .py),
+    # because the lifeguard analyzer needs the actual Python source, not type stubs.
+    if lazy_imports_cache_output != None:
+        lazy_srcs = qualified_srcs or {}
+        lazy_db_output = ctx.actions.write_json("safer_lazy_imports/db_no_deps.json", lazy_srcs, has_content_based_path = True)
+        lazy_imports_source_db = DefaultInfo(default_output = lazy_db_output, other_outputs = lazy_srcs.values())
+        run_lazy_imports_library_analyzer(
+            ctx,
+            lazy_imports_analyzer,
+            lazy_imports_cache_output,
+            lazy_imports_source_db,
+        )
+        sub_targets["lazy-import-cache"] = [DefaultInfo(default_output = lazy_imports_cache_output)]
+
+    # Type check
+    type_checker = python_toolchain.type_checker
+    pyre_validation_spec = None
+    if type_checker != None:
+        type_check_info = create_per_target_type_check(
+            ctx,
+            type_checker,
+            src_type_manifest,
+            deps,
+            typeshed = python_toolchain.typeshed_stubs,
+            py_version = ctx.attrs.py_version_for_type_checking,
+            typing_enabled = ctx.attrs.typing,
+            sharding_enabled = ctx.attrs.shard_typing,
+        )
+        sub_targets["typecheck"] = [type_check_info]
+
+        # Build-time type check validation (separate action for sole-output constraint)
+        if ctx.attrs.typing and ctx.attrs.typing_validation:
+            validation_output = create_type_check_validation(ctx, type_check_info.default_outputs[0])
+            pyre_validation_spec = ValidationSpec(name = "pyre", validation_result = validation_output)
+
+    providers.append(DefaultInfo(sub_targets = sub_targets))
+
+    # Create, augment and provide the linkable graph.
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            # Add in any potential native root targets from our first-order deps.
+            roots = get_roots(raw_deps),
+            # Exclude preloaded deps from omnibus linking, to prevent preloading
+            # the monolithic omnibus library.
+            excluded = get_excluded(
+                deps = (
+                    (raw_deps if _exclude_deps_from_omnibus(ctx, qualified_srcs) else [])
+                    +
+                    # We also need to exclude deps that can't be re-linked, via
+                    # the `LinkableRootInfo` provider (i.e. `prebuilt_cxx_library_group`).
+                    [d for d in raw_deps if LinkableRootInfo not in d]
+                ),
+            ),
+        ),
+        deps = raw_deps,
+    )
+    providers.append(linkable_graph)
+
+    # Link info for native python
+    providers.append(
+        merge_cxx_extension_info(
+            ctx.actions,
+            raw_deps,
+            shared_deps = raw_deps,
+        ),
+    )
+
+    # C++ resources.
+    providers.append(
+        make_resource_info(
+            gather_resources(
+                label = ctx.label,
+                deps = raw_deps,
+            ),
+        ),
+    )
+
+    # Attrs validators (combined with optional pyre type-check validation spec).
+    attr_validation_specs = get_attrs_validation_specs(ctx)
+    if pyre_validation_spec != None:
+        attr_validation_specs.append(pyre_validation_spec)
+    if attr_validation_specs:
+        providers.append(ValidationInfo(validations = attr_validation_specs))
+
+    return providers
diff --git a/buck2/prelude/python/python_needed_coverage_test.bzl b/buck2/prelude/python/python_needed_coverage_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/python_needed_coverage_test.bzl
@@ -0,0 +1,63 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+load(
+    "@prelude//tests:re_utils.bzl",
+    "get_re_executors_from_props",
+)
+load(
+    ":needed_coverage.bzl",
+    "parse_python_needed_coverage_specs",
+)
+
+def python_needed_coverage_test_impl(ctx: AnalysisContext) -> list[Provider]:
+    test_cmd = list(ctx.attrs.test[ExternalRunnerTestInfo].command)
+
+    test_env = {}
+    test_env.update(ctx.attrs.env)
+
+    # Pass in needed coverage flags to the test.
+    needed_coverages = parse_python_needed_coverage_specs(ctx.attrs.needed_coverage)
+    test_cmd.append("--collect-coverage")
+    test_cmd.append("--coverage-include")
+    test_cmd.append(",".join(["*/{}".format(module) for needed_coverage in needed_coverages for module in needed_coverage.modules]))
+    for needed_coverage in needed_coverages:
+        for module in needed_coverage.modules:
+            test_cmd.append("--coverage-verdict={}={}".format(module, needed_coverage.ratio))
+
+    # A needed coverage run just runs the entire test binary as bundle to
+    # determine coverage.  Rather than special implementation in tpx, we
+    # just use a simple test type to do this, which requires settings a few
+    # additional flags/env-vars which the Python tpx test type would
+    # otherwise handle.
+    test_type = "simple"
+    test_env["TEST_PILOT"] = "1"
+
+    # Setup RE executors based on the `remote_execution` param.
+    re_executors = get_re_executors_from_props(ctx)
+
+    return inject_test_run_info(
+        ctx,
+        ExternalRunnerTestInfo(
+            type = test_type,
+            command = test_cmd,
+            env = test_env,
+            labels = ctx.attrs.labels,
+            contacts = ctx.attrs.contacts,
+            default_executor = re_executors.default_executor,
+            executor_overrides = re_executors.executor_overrides,
+            # We implicitly make this test via the project root, instead of
+            # the cell root (e.g. fbcode root).
+            run_from_project_root = re_executors.run_from_project_root,
+            use_project_relative_paths = re_executors.use_project_relative_paths,
+            supports_test_execution_caching = ctx.attrs.supports_test_execution_caching,
+        ),
+    ) + [
+        DefaultInfo(),
+    ]
diff --git a/buck2/prelude/python/python_runtime_bundle.bzl b/buck2/prelude/python/python_runtime_bundle.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/python_runtime_bundle.bzl
@@ -0,0 +1,40 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+A bundled runtime includes the full install of python in the par, allowing a fully hermetic distribution.
+This rule defines the artifacts which may be include.
+include - the headers files required for compiling against the runtime
+libpython - the shared object `libpython.so` which has all of the required symbols for the runtime
+py_bin - the python executable
+py_version - a string denoting the version of python represented by this provider
+stdlib - the path to the python standard library
+"""
+
+PythonRuntimeBundleInfo = provider(
+    fields = {
+        "include": provider_field(Artifact),
+        "libpython": provider_field(Artifact | None),
+        "py_bin": provider_field(Artifact),
+        "py_version": provider_field(str),
+        "shared_libs": provider_field(list[Dependency]),
+        "stdlib": provider_field(Artifact),
+    }
+)
+
+def python_runtime_bundle_impl(ctx: AnalysisContext) -> list[Provider]:
+    root = ctx.attrs.install_root[DefaultInfo].default_outputs[0]
+    info = PythonRuntimeBundleInfo(
+        py_version = ctx.attrs.py_version,
+        py_bin = root.project(ctx.attrs.py_bin),
+        stdlib = root.project(ctx.attrs.stdlib),
+        libpython = root.project(ctx.attrs.libpython) if ctx.attrs.libpython else None,
+        include = root.project(ctx.attrs.include),
+        shared_libs = ctx.attrs.shared_libs,
+    )
+    return [DefaultInfo(default_output = root), info]
diff --git a/buck2/prelude/python/python_test.bzl b/buck2/prelude/python/python_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/python_test.bzl
@@ -0,0 +1,68 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//python:compute_providers.bzl", "ExecutableType")
+load("@prelude//utils:utils.bzl", "from_named_set", "value_or")
+load(":interface.bzl", "EntryPointKind")
+load(
+    ":manifest.bzl",
+    "get_srcs_from_manifest",
+)
+load(":python.bzl", "PythonLibraryInfo")
+load(":python_binary.bzl", "python_executable")
+load(":python_library.bzl", "py_attr_resources", "qualify_srcs")
+
+def _write_test_modules_list(ctx: AnalysisContext, srcs: dict[str, Artifact]) -> (str, Artifact):
+    """
+    Generate a python source file with a list of all test modules.
+    """
+    name = "__test_modules__.py"
+    contents = "TEST_MODULES = [\n"
+    for dst in srcs:
+        root, ext = paths.split_extension(dst)
+        if ext != ".py":
+            fail("test sources must end with .py")
+        module = root.replace("/", ".")
+        contents += '    "{}",\n'.format(module)
+    contents += "]\n"
+    return name, ctx.actions.write(name, contents, has_content_based_path = False)
+
+def python_test_executable(ctx: AnalysisContext) -> list[Provider] | Promise:
+    main_module = value_or(ctx.attrs.main_module, "__test_main__")
+
+    srcs = qualify_srcs(ctx.label, ctx.attrs.base_module, from_named_set(ctx.attrs.srcs))
+    if ctx.attrs.implicit_test_library != None:
+        top_level_manifest = list(ctx.attrs.implicit_test_library[PythonLibraryInfo].manifests.traverse(ordering = "preorder"))[0]
+        srcs.update(qualify_srcs(ctx.label, ctx.attrs.base_module, from_named_set(get_srcs_from_manifest(top_level_manifest.srcs))))
+
+    test_modules_name, test_modules_path = _write_test_modules_list(ctx, srcs)
+    srcs[test_modules_name] = test_modules_path
+
+    # Add in default test runner.
+    srcs["__test_main__.py"] = ctx.attrs._test_main
+
+    resources_map, standalone_resources_map, outplace_resources_map = py_attr_resources(ctx)
+    standalone_resources = qualify_srcs(ctx.label, ctx.attrs.base_module, standalone_resources_map)
+    outplace_resources = qualify_srcs(ctx.label, ctx.attrs.base_module, outplace_resources_map)
+    resources = qualify_srcs(ctx.label, ctx.attrs.base_module, resources_map)
+
+    return python_executable(
+        ctx,
+        (EntryPointKind("module"), main_module),
+        srcs,
+        resources,
+        standalone_resources,
+        outplace_resources,
+        compile = value_or(ctx.attrs.compile, False),
+        allow_cache_upload = False,
+        executable_type = ExecutableType("test"),
+    )
+
+def python_test_impl(ctx: AnalysisContext) -> list[Provider] | Promise:
+    return python_test_executable(ctx)
diff --git a/buck2/prelude/python/python_wheel.bzl b/buck2/prelude/python/python_wheel.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/python_wheel.bzl
@@ -0,0 +1,585 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "PicBehavior")
+load(
+    "@prelude//cxx:link.bzl",
+    "cxx_link_shared_library",
+)
+load(
+    "@prelude//cxx:link_types.bzl",
+    "link_options",
+)
+load(
+    "@prelude//cxx:omnibus.bzl",
+    "create_omnibus_libraries",
+    "get_omnibus_graph",
+    "get_roots",
+)
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//linking:execution_preference.bzl", "LinkExecutionPreference", "link_execution_preference_attr")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkArgs",
+    "LinkStrategy",
+    "get_lib_output_style",
+    "get_link_info",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",
+    "LinkableNode",  # @unused Used as a type
+    "LinkableRootInfo",
+    "create_linkable_graph",
+    "get_deps_for_link",
+    "get_linkable_graph_node_map_func",
+    get_link_info_for_node = "get_link_info",
+)
+load("@prelude//linking:shared_libraries.bzl", "SharedLibraryInfo")
+load(
+    "@prelude//python:manifest.bzl",
+    "ManifestInfo",
+    "create_manifest_for_entries",
+    "create_manifest_for_shared_libs",
+)
+load("@prelude//python:python.bzl", "PythonLibraryInfo")
+load("@prelude//python:python_wheel_toolchain.bzl", "PythonWheelToolchainInfo")
+load("@prelude//python:toolchain.bzl", "PythonToolchainInfo")
+load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")
+load("@prelude//utils:expect.bzl", "expect")
+load(
+    "@prelude//utils:graph_utils.bzl",
+    "depth_first_traversal_by",
+)
+load("@prelude//utils:utils.bzl", "value_or")
+
+def _link_deps(link_infos: dict[Label, LinkableNode], deps: list[Label], link_strategy: LinkStrategy, pic_behavior: PicBehavior) -> list[Label]:
+    """
+    Return transitive deps required to link dynamically against the given deps.
+    This will following through deps of statically linked inputs and exported
+    deps of everything else (see https://fburl.com/diffusion/rartsbkw from v1).
+    """
+
+    def find_deps(node: Label):
+        return get_deps_for_link(link_infos[node], link_strategy, pic_behavior)
+
+    return depth_first_traversal_by(link_infos, deps, find_deps)
+
+def _python_version_from_tag(tag):
+    """Extract Python version from a wheel tag: "py3.12" -> "3.12", "cp312" -> "3.12"."""
+    version = tag
+    for prefix in ("cp", "py"):
+        if tag.startswith(prefix):
+            version = tag[len(prefix) :]
+            break
+    if "." in version:
+        return version
+    if len(version) >= 2:
+        return version[0] + "." + version[1:]
+    return version
+
+def _cpython_tag(python_version):
+    """Convert Python version to CPython tag: "3.12" -> "cp312"."""
+    return "cp" + python_version.replace(".", "")
+
+def _whl_cmd(
+    ctx: AnalysisContext,
+    output: Artifact,
+    platform: str,
+    abi: str,
+    python: str,
+    manifests: list[ManifestInfo] = [],
+    srcs: dict[str, Artifact] = {},
+    computed_metadata: dict[str, str] = {},
+    readme: Artifact | None = None,
+) -> cmd_args:
+    cmd = []
+
+    cmd.append(ctx.attrs._wheel[RunInfo])
+
+    cmd.append("--output")
+    cmd.append(output.as_output())
+    cmd.append("--name={}".format(ctx.attrs.dist or ctx.attrs.name))
+    cmd.append("--version={}".format(ctx.attrs.version))
+    cmd.append("--python-tag={}".format(python))
+    cmd.append("--abi-tag={}".format(abi))
+    cmd.append("--platform-tag={}".format(platform))
+
+    if ctx.attrs.entry_points:
+        cmd.append("--entry-points={}".format(json.encode(ctx.attrs.entry_points)))
+
+    for key, val in ctx.attrs.extra_metadata.items():
+        cmd.extend(["--metadata", key, val])
+
+    for key, val in computed_metadata.items():
+        cmd.extend(["--metadata", key, val])
+
+    for requires in ctx.attrs.requires:
+        cmd.extend(["--metadata", "Requires-Dist", requires])
+
+    if readme != None:
+        cmd.extend(["--readme", readme])
+
+    for name, script in ctx.attrs.scripts.items():
+        cmd.extend(["--data", paths.join("scripts", name), script])
+
+    for dst, src in srcs.items():
+        cmd.extend(["--src-path", dst, src])
+
+    hidden = []
+    for manifest in manifests:
+        cmd.append("--manifest")
+        cmd.append(manifest.manifest)
+        for a, _ in manifest.artifacts:
+            hidden.append(a)
+
+    return cmd_args(cmd, hidden = hidden)
+
+def _rpath(rpath, origin):
+    """
+    Relative the given `rpath` to `dst`, via `$ORIGIN`.
+    If `rpath` is absolute, return it as-is.
+    """
+    if paths.is_absolute(rpath):
+        return rpath
+
+    expect(not paths.is_absolute(origin))
+
+    base = "$ORIGIN"
+    if origin:
+        base = paths.join(base, *[".." for _ in origin.split("/")])
+    return paths.join(base, rpath)
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    providers = []
+    sub_targets = {}
+
+    libraries = {}
+    seen_raw_targets = {}
+    for lib in ctx.attrs.libraries:
+        libraries[lib.label] = lib
+        seen_raw_targets[str(lib.label.raw_target())] = True
+    if ctx.attrs.libraries_query != None:
+        for lib in ctx.attrs.libraries_query:
+            if PythonLibraryInfo in lib:
+                raw = str(lib.label.raw_target())
+                if raw in seen_raw_targets:
+                    # Same target in a different configuration (e.g. due to
+                    # a configuration transition in the dep graph).
+                    # Keep the first instance.
+                    continue
+                seen_raw_targets[raw] = True
+                libraries[lib.label] = lib
+
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    toolchain_info = get_cxx_toolchain_info(ctx)
+    dist = ctx.attrs.dist or ctx.attrs.name
+    lib_dir = value_or(ctx.attrs.lib_dir, paths.join(dist, "lib"))
+
+    # RPATHs to embed in the binary.
+    rpaths = [lib_dir] + ctx.attrs.rpaths + python_toolchain.wheel_rpaths
+
+    def maybe_patchelf(dst, src):
+        # If there's no rpaths, there's nothing to patch.
+        if not rpaths:
+            return src
+
+        # Heuristic: if we see an extension, assume it's not an ELF file (this might miss
+        # DSOs embedded as resources).
+        _, ext = paths.split_extension(dst)
+        if ext:
+            return src
+
+        # Run the patchelf -- this will just copy if it turns out the given
+        # path isn't and ELF file.
+        out = ctx.actions.declare_output(paths.join("__patched__", dst), has_content_based_path = False)
+        cmd = cmd_args(
+            ctx.attrs._patchelf[RunInfo],
+            "--output",
+            out.as_output(),
+            cmd_args([_rpath(p, origin = paths.dirname(dst)) for p in rpaths], format = "--rpath={}"),
+            src,
+        )
+        ctx.actions.run(cmd, category = "patchelf", identifier = dst)
+        return out
+
+    srcs = []
+    native_srcs = []
+    extensions = {}
+    shared_libs = []
+    native_deps = {}
+    for dep in libraries.values():
+        manifests = dep[PythonLibraryInfo].manifests.value
+        if manifests.srcs != None:
+            srcs.append(manifests.srcs)
+        if manifests.default_resources != None:
+            # default_resources is a tuple of (manifest, hidden_runtime_files).
+            # The manifest ([0]) contains the actual resource files that should
+            # be packaged. Hidden runtime files ([1]) are auxiliary artifacts
+            # that resources depend on at execution time (e.g., symlink trees
+            # for shared libs); they are not directly packageable in a wheel.
+            # Previously this asserted [1] was empty, which broke MTIA wheel
+            # builds whose deps include native libraries with such auxiliary
+            # artifacts. Skipping [1] is safe because the wheel build path
+            # bundles shared libs via a separate mechanism.
+            srcs.append(manifests.default_resources[0])
+        if manifests.extensions != None:
+            ((extension, _),) = manifests.extensions.items()
+            if extension in extensions:
+                existing = extensions[extension]
+                if existing.label.raw_target() == dep.label.raw_target():
+                    # Same target in a different configuration (e.g. due to
+                    # a configuration transition in the dep graph).
+                    # Keep the first instance.
+                    continue
+                fail("Duplicate extension entry for {}. Did your library_query forget to filter by `target_deps()`?".format(extension))
+            extensions[extension] = dep
+
+        # These are non-extension native deps that may be dlopen'ed at
+        # runtime and should be included in the search space for omnibus roots.
+        for native_dep in dep[PythonLibraryInfo].native_deps.value.native_deps.values():
+            if SharedLibraryInfo in native_dep:
+                native_deps[native_dep.label] = native_dep
+
+    # We support two modes of linking:
+    # - omnibus: All native deps of all extensions are linked into a shared DSO
+    # - static-everything: Each extension statically links all its deps (note
+    #       this can mean each extension gets its own copy of common deps).
+    if ctx.attrs.omnibus:
+        deps = (extensions | native_deps).values()
+        linkable_graph = create_linkable_graph(
+            ctx = ctx,
+            deps = deps,
+        )
+        omnibus_graph = get_omnibus_graph(
+            graph = linkable_graph,
+            roots = get_roots(deps),
+            excluded = {},
+        )
+
+        extension_labels = {dep.label: None for dep in extensions.values()}
+
+        # Link omnibus libraries.
+        omnibus_libs = create_omnibus_libraries(
+            ctx = ctx,
+            graph = omnibus_graph,
+            omnibus_lib_name = "omnibus-{}".format(dist),
+            extra_ldflags = python_toolchain.wheel_linker_flags + ctx.attrs.linker_flags,
+            extra_root_ldflags = {
+                dep.label: (
+                    python_toolchain.extension_linker_flags
+                    + python_toolchain.wheel_extension_linker_flags
+                    + ["-Wl,-rpath,{}".format(_rpath(rpath, origin = paths.dirname(extension))) for rpath in rpaths]
+                )
+                for extension, dep in extensions.items()
+            }
+            | {
+                # For non-extension roots, set rpaths relative the lib dir.
+                root: ["-Wl,-rpath,{}".format(_rpath(rpath, origin = lib_dir)) for rpath in rpaths]
+                for root in omnibus_graph.roots.keys()
+                if root not in extension_labels
+            },
+            anonymous = ctx.attrs.anonymous_link,
+        )
+
+        # Extract re-linked extensions.
+        extensions = {dest: omnibus_libs.roots[dep.label].shared_library for dest, dep in extensions.items()}
+        shared_libs = omnibus_libs.libraries
+    else:
+        for extension, dep in extensions.items():
+            root = dep[LinkableRootInfo]
+
+            # Add link inputs for the linkable root and any deps.
+            inputs = []
+            inputs.append(
+                get_link_info(
+                    infos = root.link_infos,
+                    prefer_stripped = ctx.attrs.prefer_stripped_objects,
+                )
+            )
+            link_infos = get_linkable_graph_node_map_func(dep[LinkableGraph])()
+            for ext_dep in _link_deps(
+                link_infos,
+                root.deps,
+                LinkStrategy("static_pic"),
+                toolchain_info.pic_behavior,
+            ):
+                node = link_infos[ext_dep]
+                output_style = get_lib_output_style(
+                    LinkStrategy("static_pic"),
+                    node.preferred_linkage,
+                    toolchain_info.pic_behavior,
+                )
+                inputs.append(
+                    get_link_info_for_node(
+                        node,
+                        output_style,
+                        prefer_stripped = ctx.attrs.prefer_stripped_objects,
+                    )
+                )
+
+                # Record shared libs we need to package.
+                if output_style == LibOutputStyle("shared_lib"):
+                    shared_libs.extend(node.shared_libs.libraries)
+
+            # link the rule
+            link_result = cxx_link_shared_library(
+                ctx = ctx,
+                output = extension,
+                opts = link_options(
+                    links = [
+                        LinkArgs(flags = python_toolchain.extension_linker_flags),
+                        LinkArgs(flags = python_toolchain.wheel_linker_flags),
+                        LinkArgs(flags = ["-Wl,-rpath,{}".format(_rpath(rpath, origin = paths.dirname(extension))) for rpath in rpaths]),
+                        LinkArgs(flags = ctx.attrs.linker_flags),
+                        LinkArgs(infos = inputs),
+                    ],
+                    category_suffix = "native_extension",
+                    identifier = extension,
+                    link_execution_preference = LinkExecutionPreference("any"),
+                ),
+            )
+            extensions[extension] = link_result.linked_object
+
+    # Add sub-target for extensions.
+    sub_targets["extensions"] = [
+        DefaultInfo(
+            sub_targets = {name: [DefaultInfo(default_output = ext.output)] for name, ext in extensions.items()},
+        ),
+    ]
+    sub_targets["native-libs"] = [
+        DefaultInfo(
+            sub_targets = {shlib.soname.ensure_str(): [DefaultInfo(default_output = shlib.lib.output)] for shlib in shared_libs if shlib.soname.is_str},
+        ),
+    ]
+
+    # Add shlibs manifest.
+    if shared_libs:
+        # NOTE(agallaher): We copy shared libs/roots, rather than symlink, as
+        # some DSO loading frameworks `realpath` the DSO before opening them,
+        # causing the `$ORIGIN` in them to no longer be valid, e.g.
+        # https://github.com/pytorch/pytorch/blob/main/torch/_utils_internal.py#L62
+        native_srcs.append(
+            create_manifest_for_shared_libs(
+                actions = ctx.actions,
+                name = "shared_libs.txt",
+                shared_libs = shared_libs,
+                lib_dir = lib_dir,
+            ),
+        )
+
+    if extensions:
+        srcs.append(
+            create_manifest_for_entries(
+                ctx,
+                name = "extensions.txt",
+                entries = [(name, extension.output, "<unknown>") for name, extension in extensions.items()],
+            ),
+        )
+
+    # Add in resources for the current rule.
+    if ctx.attrs.resources:
+        srcs.append(
+            create_manifest_for_entries(
+                ctx,
+                name = "resources.txt",
+                entries = [(dest, maybe_patchelf(dest, resource), str(ctx.label.raw_target())) for dest, resource in ctx.attrs.resources.items()],
+            ),
+        )
+
+    # Resolve platform: use attr if set, otherwise fall back to toolchain default
+    wheel_toolchain = ctx.attrs._python_wheel_toolchain[PythonWheelToolchainInfo]
+    python = value_or(ctx.attrs.python, wheel_toolchain.python)
+    platform = ctx.attrs.platform or wheel_toolchain.platform
+    if not platform:
+        fail("platform must be set either on python_wheel target or in python_wheel_toolchain")
+
+    # Resolve ABI tag: explicit attr > toolchain default
+    abi = value_or(ctx.attrs.abi, wheel_toolchain.abi)
+
+    # Auto-detect CPython tags for wheels with native extensions (PEP 427).
+    # When native extensions are present and no explicit ABI override is set,
+    # switch from py*-none to cpXXX-cpXXX tags.
+    python_version = _python_version_from_tag(python)
+
+    # Normalize python tag to PEP 425 format: "py3.12" -> "py312"
+    if "." in python:
+        python = python.replace(".", "")
+
+    if extensions and abi == "none":
+        cp_tag = _cpython_tag(python_version)
+        python = cp_tag
+        abi = cp_tag
+
+    # Computed metadata for WHEEL/METADATA files
+    computed_metadata = {"Requires-Python": "==" + python_version + ".*"}
+
+    def normalize_name(name):
+        # Normalize name part of the *.whl file per:
+        #  * https://packaging.python.org/en/latest/specifications/recording-installed-packages/#the-dist-info-directory
+        #  * https://packaging.python.org/en/latest/specifications/name-normalization/
+        #
+        # Equivalent to fbcode/buck2/prelude/python/tools/wheel.py#normalize_name()
+        # but need to do it here since we need to set output path
+
+        # PEP503 name normalization
+        #   1. Convert to lowercase
+        pep503_normalized = name.lower()
+
+        #   2. Replace all dots and underscores with hyphens
+        pep503_normalized = pep503_normalized.replace(".", "-")
+        pep503_normalized = pep503_normalized.replace("_", "-")
+
+        #   3. Collapse multiple consecutive hyphens into single hyphen
+        #      Since we don't have regex, we'll do multiple passes
+        for _ in range(pep503_normalized.count("--")):
+            pep503_normalized = pep503_normalized.replace("--", "-")
+
+        # Finally replace hyphens with underscores
+        return pep503_normalized.replace("-", "_")
+
+    name_parts = [
+        # only normalize `dist` in the *.whl filename (NOT the dist name in dist-info/METADATA)
+        normalize_name(dist),
+        ctx.attrs.version,
+        python,
+        abi,
+        platform,
+    ]
+
+    # Action to create wheel.
+    wheel = ctx.actions.declare_output("{}.whl".format("-".join(name_parts)), has_content_based_path = False)
+    whl_cmd = _whl_cmd(
+        ctx = ctx,
+        output = wheel,
+        platform = platform,
+        abi = abi,
+        python = python,
+        manifests = srcs + native_srcs,
+        computed_metadata = computed_metadata,
+        readme = ctx.attrs.readme,
+    )
+    ctx.actions.run(whl_cmd, category = "wheel")
+
+    # Create symlink tree for inplace module layout.
+    manifest_args = []
+    manifest_srcs = []
+    for manifest in srcs:
+        manifest_args.append(cmd_args(manifest.manifest, format = "--link-manifest={}"))
+        for a, _ in manifest.artifacts:
+            manifest_srcs.append(a)
+    for manifest in native_srcs:
+        manifest_args.append(
+            cmd_args(
+                manifest.manifest,
+                format = "--copy-manifest={}",
+                hidden = [a for (a, _) in manifest.artifacts],
+            ),
+        )
+    link_tree = ctx.actions.declare_output("__editable__/tree.d", dir = True, has_content_based_path = False)
+    link_tree_cmd = cmd_args(
+        ctx.attrs._create_link_tree[RunInfo],
+        cmd_args(link_tree.as_output(), format = "--output={}"),
+        manifest_args,
+    )
+    ctx.actions.run(link_tree_cmd, category = "link_tree")
+
+    # Create <dist>.pth to put in the wheel and points to the symlink tree.
+    pth = ctx.actions.declare_output("__editable__/{}.pth".format(dist), has_content_based_path = False)
+    pth_cmd = cmd_args(
+        "sh",
+        "-c",
+        # We need to embed an absolute paths to the link-tree into the `.pth` file.
+        # so we'll also make sure this rule is local-only.
+        'echo "$PWD/$2" > $1',
+        "",
+        pth.as_output(),
+        # We don't care about the link tree contents, so prevent it from affecting
+        # the cache key.
+        cmd_args(link_tree, ignore_artifacts = True),
+    )
+    ctx.actions.run(pth_cmd, category = "pth", local_only = True)
+
+    # Action to create editable wheel.
+    ewheel = ctx.actions.declare_output("__editable__/{}.whl".format("-".join(name_parts)), has_content_based_path = False)
+    ewhl_cmd = _whl_cmd(
+        ctx = ctx,
+        output = ewheel,
+        platform = platform,
+        abi = abi,
+        python = python,
+        srcs = {"{}.pth".format(dist): pth},
+        computed_metadata = computed_metadata,
+        readme = ctx.attrs.readme,
+    )
+    ctx.actions.run(ewhl_cmd, category = "editable_wheel")
+    sub_targets["editable"] = [
+        DefaultInfo(
+            default_output = ewheel,
+            other_outputs = (manifest_srcs + [link_tree]),
+        ),
+    ]
+
+    providers.append(DefaultInfo(default_output = wheel, sub_targets = sub_targets))
+
+    return providers
+
+python_wheel = rule(
+    impl = _impl,
+    cfg = constraint_overrides.python_transition,
+    attrs = dict(
+        dist = attrs.option(attrs.string(), default = None),
+        version = attrs.string(default = "1.0.0"),
+        python = attrs.option(attrs.string(), default = None),
+        abi = attrs.option(attrs.string(), default = None),
+        entry_points = attrs.dict(
+            key = attrs.string(),
+            value = attrs.dict(
+                key = attrs.string(),
+                value = attrs.string(),
+            ),
+            default = {},
+        ),
+        requires = attrs.list(attrs.string(), default = []),
+        extra_metadata = attrs.dict(
+            key = attrs.string(),
+            value = attrs.string(),
+            default = {},
+        ),
+        readme = attrs.option(attrs.source(), default = None),
+        platform = attrs.option(
+            attrs.string(),
+            default = None,
+            doc = "Platform tag for the wheel. If not set, uses the toolchain default.",
+        ),
+        omnibus = attrs.bool(default = False),
+        libraries = attrs.list(attrs.dep(providers = [PythonLibraryInfo]), default = []),
+        scripts = attrs.dict(key = attrs.string(), value = attrs.source(), default = {}),
+        libraries_query = attrs.option(attrs.query(), default = None),
+        prefer_stripped_objects = attrs.default_only(attrs.bool(default = False)),
+        resources = attrs.dict(key = attrs.string(), value = attrs.source(), default = {}),
+        rpaths = attrs.list(attrs.string(), default = []),
+        lib_dir = attrs.option(attrs.string(), default = None),
+        labels = attrs.list(attrs.string(), default = []),
+        deffile = attrs.option(attrs.source(), default = None),
+        linker_flags = attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+        anonymous_link = attrs.bool(default = True),
+        link_execution_preference = link_execution_preference_attr(),
+        _wheel = attrs.default_only(attrs.exec_dep(default = "prelude//python/tools:wheel")),
+        _patchelf = attrs.default_only(attrs.exec_dep(default = "prelude//python/tools:patchelf")),
+        _python_wheel_toolchain = toolchains_common.python_wheel(),
+        _create_link_tree = attrs.default_only(attrs.exec_dep(default = "prelude//python/tools:create_link_tree")),
+        _cxx_toolchain = toolchains_common.cxx(),
+        _python_toolchain = toolchains_common.python(),
+        opt_by_default_enabled = attrs.bool(default = False),
+    )
+    | constraint_overrides.attributes,
+)
diff --git a/buck2/prelude/python/python_wheel_toolchain.bzl b/buck2/prelude/python/python_wheel_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/python_wheel_toolchain.bzl
@@ -0,0 +1,24 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Python wheel toolchain for configuring wheel building and repair tools.
+
+This toolchain provides configuration for tools used in building and repairing
+Python wheels, particularly for manylinux compliance via auditwheel.
+"""
+
+PythonWheelToolchainInfo = provider(
+    doc = "Python wheel toolchain info",
+    fields = {
+        "abi": provider_field(str, default = "none"),
+        # Default platform tag for wheels (e.g., linux_x86_64, manylinux_2_28_x86_64)
+        "platform": provider_field(str, default = "any"),
+        "python": provider_field(str, default = "py3"),
+    },
+)
diff --git a/buck2/prelude/python/runtime/BUCK b/buck2/prelude/python/runtime/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/runtime/BUCK
@@ -0,0 +1,11 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("plf_experience")
+
+source_listing()
+
+filegroup(
+    name = "bootstrap_files",
+    srcs = glob(["__par__/**/*.py"]),
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/python/runtime/__par__/bootstrap.py b/buck2/prelude/python/runtime/__par__/bootstrap.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/runtime/__par__/bootstrap.py
@@ -0,0 +1,95 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+import os
+import types
+from typing import Callable, Sequence
+
+
+def iscoroutinefunction(func: Callable[[], None]) -> bool:
+    # This is the guts of inspect.iscoroutinefunction without the cost of inspect import
+    CO_COROUTINE = 128  # This hasn't changed in 8 years most likely never will
+    return isinstance(func, types.FunctionType) and bool(
+        func.__code__.co_flags & CO_COROUTINE
+    )
+
+
+def run_as_main(
+    main_module: str,
+    main_function: str | None,
+    main_function_hooks: Sequence[Callable[[], None]] = (),
+) -> None:
+    """
+    Run the specified module or function as the main program.
+
+    `main_module` is the fully qualified import path to the module to be run as
+    main. If `main_function` is not None, it's the attribute on `main_module`
+    that should be called after importing it.
+
+    This function supports overriding the main module when the `PAR_MAIN_OVERRIDE`
+    env variable is set.
+
+    When `main_function_hooks` is set, the hooks are called in sequence after the
+    main module has been imported, just before the main function is invoked. This
+    parameter has no effect if `main_function` is `None`.
+    """
+
+    # Allow users to decorate the main module. In normal Python invocations this
+    # can be done by prefixing the arguments with `-m decoratingmodule`. It's not
+    # that easy for par files. The startup script sets up `sys.path` from
+    # within the Python interpreter. Enable decorating the main module after
+    # `sys.path` has been setup by setting the PAR_MAIN_OVERRIDE environment
+    # variable.
+    decorate_main_module = os.environ.pop("PAR_MAIN_OVERRIDE", None)
+    is_decorated_module = "PAR_MAIN_ORIGINAL" in os.environ
+    if decorate_main_module:
+        # Pass the original main module as environment variable for the process.
+        # Allowing the decorating module to pick it up.
+        os.environ["PAR_MAIN_ORIGINAL"] = main_module
+        main_module = decorate_main_module
+
+    # Also pass the main function if set:
+    decorate_main_function = os.environ.pop("PAR_MAIN_FUNCTION_OVERRIDE", None)
+    if main_function and (decorate_main_module or is_decorated_module):
+        os.environ["PAR_MAIN_FUNCTION_ORIGINAL"] = main_function
+        main_function = decorate_main_function
+
+    if not main_function:
+        import runpy
+
+        # pyre-fixme[16]: Module `runpy` has no attribute `_run_module_as_main`.
+        runpy._run_module_as_main(main_module, alter_argv=False)
+        return
+
+    from importlib import import_module
+
+    mod = import_module(main_module)
+    main = getattr(mod, main_function)
+
+    # This is normally done by `runpy._run_module_as_main`, and is
+    # important to make multiprocessing work
+    import sys
+
+    sys.modules["__main__"] = mod
+
+    # Pretend we're executing `main()` directly
+    if hasattr(main, "__globals__") and isinstance(main.__globals__, dict):
+        main.__globals__["__name__"] = "__main__"
+    for hook in main_function_hooks:
+        hook()
+
+    if iscoroutinefunction(main):
+        import asyncio
+
+        asyncio.run(main())
+    else:
+        main()
diff --git a/buck2/prelude/python/source_db.bzl b/buck2/prelude/python/source_db.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/source_db.bzl
@@ -0,0 +1,68 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//python:python.bzl", "PythonLibraryInfo")
+load(":internal_tools.bzl", "PythonInternalToolsInfo")
+load(
+    ":manifest.bzl",
+    "ManifestInfo",  # @unused Used as a type
+)
+load(":python.bzl", "PythonLibraryManifestsTSet")
+load(":toolchain.bzl", "PythonToolchainInfo")
+
+# Information about what modules a Python target contains for type checking purpose
+PythonSourceDBInfo = provider(
+    fields = {
+        "manifests": provider_field(typing.Any, default = None),  # PythonLibraryManifestsTSet
+    }
+)
+
+def create_python_source_db_info(manifests: [PythonLibraryManifestsTSet, None]) -> PythonSourceDBInfo:
+    return PythonSourceDBInfo(manifests = manifests)
+
+def create_dbg_source_db(ctx: AnalysisContext, output: Artifact, srcs: [ManifestInfo, None], python_deps: list[PythonLibraryInfo]) -> DefaultInfo:
+    artifacts = []
+
+    python_toolchain = ctx.attrs._python_toolchain[PythonToolchainInfo]
+    python_internal_tools = ctx.attrs._python_internal_tools[PythonInternalToolsInfo]
+    if ctx.attrs.use_rust_make_par:
+        cmd = cmd_args(python_toolchain.make_py_package_live[RunInfo])
+        cmd.add("source-db")
+    else:
+        cmd = cmd_args(python_internal_tools.make_source_db)
+    cmd.add(cmd_args(output.as_output(), format = "--output={}"))
+
+    # Pass manifests for rule's sources.
+    if srcs != None:
+        cmd.add(cmd_args(srcs.manifest, format = "--sources={}"))
+        artifacts.extend([a for a, _ in srcs.artifacts])
+
+    # Pass manifests for transitive deps.
+    dep_manifests = ctx.actions.tset(PythonLibraryManifestsTSet, children = [d.manifests for d in python_deps])
+
+    dependency_manifests = cmd_args(dep_manifests.project_as_args("source_manifests"))
+    deps_file = ctx.actions.write("deps_path.txt", dependency_manifests, has_content_based_path = True)
+    cmd.add(cmd_args(deps_file, format = "--dependency_manifests={}", hidden = dependency_manifests))
+
+    artifacts.append(dep_manifests.project_as_args("source_artifacts"))
+    ctx.actions.run(cmd, category = "py_dbg_source_db", error_handler = python_toolchain.python_error_handler)
+
+    return DefaultInfo(default_output = output, other_outputs = artifacts)
+
+def create_source_db_no_deps(ctx: AnalysisContext, srcs: [dict[str, Artifact], None]) -> DefaultInfo:
+    content = {} if srcs == None else srcs
+    output = ctx.actions.write_json("db_no_deps.json", content, has_content_based_path = True)
+    return DefaultInfo(default_output = output, other_outputs = content.values())
+
+def create_source_db_no_deps_from_manifest(ctx: AnalysisContext, srcs: ManifestInfo) -> DefaultInfo:
+    output = ctx.actions.declare_output("db_no_deps.json", has_content_based_path = True)
+    cmd = cmd_args(ctx.attrs._python_internal_tools[PythonInternalToolsInfo].make_source_db_no_deps)
+    cmd.add(cmd_args(output.as_output(), format = "--output={}"))
+    cmd.add(srcs.manifest)
+    ctx.actions.run(cmd, category = "py_source_db")
+    return DefaultInfo(default_output = output, other_outputs = [a for a, _ in srcs.artifacts])
diff --git a/buck2/prelude/python/sourcedb/build.bxl b/buck2/prelude/python/sourcedb/build.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/build.bxl
@@ -0,0 +1,54 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _get_artifact(result: bxl.BuildResult) -> Artifact:
+    # NOTE: the first artifact is always the source db json
+    # T124989384 will make this nicer
+    for artifact in result.artifacts():
+        return artifact
+    fail("Sourcedb rule must have at least one artifact")
+
+def _get_sourcedb(result: list[bxl.EnsuredArtifact]) -> bxl.EnsuredArtifact:
+    # NOTE: the first artifact is always the source db json
+    # T124989384 will make this nicer
+    for artifact in result:
+        return artifact
+    fail("Sourcedb rule must have at least one artifact")
+
+def _abort_on_build_failure(target_label: TargetLabel, result: bxl.BuildResult) -> None:
+    for failure in result.failures():
+        error_message = "Target `{}` cannot be built by Buck\nreason: {}".format(target_label, failure)
+        fail(error_message)
+
+def _build(ctx: bxl.Context, targets: list[ConfiguredTargetLabel]) -> dict[Label, bxl.BuildResult]:
+    # Build sourcedbs of all targets
+    configured_sub_targets = [target.with_sub_target(["source-db-no-deps"]) for target in targets]
+    return ctx.build(configured_sub_targets)
+
+# Build sourcedb for the given targets, and return a mapping from target names
+# to the corresponding sourcedb JSON file location.
+def do_build(ctx: bxl.Context, targets: list[ConfiguredTargetLabel]) -> dict[TargetLabel, Artifact]:
+    build_results = _build(ctx, targets)
+
+    # Compute result dict
+    output = {}
+    for key, result in build_results.items():
+        raw_target = key.raw_target()
+        _abort_on_build_failure(raw_target, result)
+        path = _get_artifact(result)
+        output[raw_target] = path
+    return output
+
+# Same as do_build, except calls ensure to ensure artifacts are materialized.
+def do_build_ensured(ctx: bxl.Context, targets: list[ConfiguredTargetLabel]) -> dict[TargetLabel, bxl.EnsuredArtifact]:
+    build_results = _build(ctx, targets)
+    for key, value in build_results.items():
+        _abort_on_build_failure(key.raw_target(), value)
+
+    ensured_artifacts = ctx.output.ensure_multiple(build_results)
+    return {label.raw_target(): _get_sourcedb(artifact) for label, artifact in ensured_artifacts.items()}
diff --git a/buck2/prelude/python/sourcedb/classic.bxl b/buck2/prelude/python/sourcedb/classic.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/classic.bxl
@@ -0,0 +1,50 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":build.bxl", "do_build")
+load(":merge.bxl", "do_merge")
+load(":query.bxl", "do_query")
+
+def _build_entry_point(ctx: bxl.Context) -> None:
+    bxl_actions = ctx.bxl_actions(
+        exec_deps = "prelude//python/tools/sourcedb_merger:legacy_merge",
+        target_platform = "prelude//platforms:default",
+    )
+    actions = bxl_actions.actions
+
+    query = ctx.uquery()
+    targets = do_query(ctx, query, actions, [query.eval(target) for target in ctx.cli_args.target])
+    built_sourcedbs = do_build(ctx, targets)
+
+    # Ensure all source files are materialized
+    ctx.output.ensure_multiple(built_sourcedbs.values())
+
+    # Ensure merged sourcedb is materialized
+    merged_sourcedb = do_merge(
+        ctx,
+        bxl_actions,
+        built_sourcedbs,
+        command_category = "pyre_legacy_merge_sourcedb",
+    )
+    ctx.output.print_json({"db": merged_sourcedb.abs_path()})
+
+build = bxl_main(
+    doc = """Build Python sourcedb for Pyre classic type checking server.
+
+    It takes a list of target patterns (usually obtained from Pyre local configuration
+    file), and will build source-db for those targets.
+    """,
+    impl = _build_entry_point,
+    cli_args = {
+        "target": cli_args.list(
+            cli_args.string(
+                doc = "Target pattern to build a source db for",
+            ),
+        ),
+    },
+)
diff --git a/buck2/prelude/python/sourcedb/code_navigation.bxl b/buck2/prelude/python/sourcedb/code_navigation.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/code_navigation.bxl
@@ -0,0 +1,53 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":build.bxl", "do_build")
+load(":merge.bxl", "do_merge")
+load(":query.bxl", "do_query")
+
+def _build_entry_point(ctx: bxl.Context) -> None:
+    bxl_actions = ctx.bxl_actions(
+        exec_deps = "prelude//python/tools/sourcedb_merger:merge",
+        target_platform = "prelude//platforms:default",
+    )
+    actions = bxl_actions.actions
+
+    query = ctx.uquery()
+    root = ctx.root()
+
+    sources = ["{}/{}".format(root, source) for source in ctx.cli_args.source]
+    targets = do_query(ctx, query, actions, query.owner(sources))
+    built_sourcedbs = do_build(ctx, targets)
+
+    # Ensure all source files are materialized
+    ctx.output.ensure_multiple(built_sourcedbs.values())
+
+    # Ensure merged sourcedb is materialized
+    merged_sourcedb = do_merge(
+        ctx,
+        bxl_actions,
+        built_sourcedbs,
+        command_category = "pyre_merge_sourcedb",
+    )
+    ctx.output.print_json({"db": merged_sourcedb.abs_path()})
+
+build = bxl_main(
+    doc = """Build Python sourcedb for Pyre code navigation server.
+
+    It takes a list of file paths, and will find the owner targets for all
+    those files and build source-db for those owning targets.
+    """,
+    impl = _build_entry_point,
+    cli_args = {
+        "source": cli_args.list(
+            cli_args.string(
+                doc = "File to build a source db for (relative to source root)",
+            ),
+        ),
+    },
+)
diff --git a/buck2/prelude/python/sourcedb/filter.bxl b/buck2/prelude/python/sourcedb/filter.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/filter.bxl
@@ -0,0 +1,62 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+BUCK_PYTHON_RULE_KINDS = [
+    "python_binary",
+    "python_library",
+    "python_test",
+]
+BUCK_PYTHON_RULE_KIND_QUERY = "|".join(BUCK_PYTHON_RULE_KINDS)
+
+def get_unfiltered_root_targets(query: bxl.UqueryContext, target_patterns: typing.Any) -> bxl.UnconfiguredTargetSet:
+    candidate_targets = utarget_set()
+    for pattern in target_patterns:
+        candidate_targets += query.kind(
+            BUCK_PYTHON_RULE_KIND_QUERY,
+            pattern,
+        )
+    return candidate_targets
+
+def filter_root_targets(query: bxl.UqueryContext, target_patterns: typing.Any) -> bxl.UnconfiguredTargetSet:
+    # Find all Pure-Python targets
+    candidate_targets = get_unfiltered_root_targets(query, target_patterns)
+
+    # Don't check generated rules
+    filtered_targets = candidate_targets - query.attrfilter(
+        "labels",
+        "generated",
+        candidate_targets,
+    )
+
+    # Provide an opt-out label
+    filtered_targets = filtered_targets - query.attrfilter(
+        "labels",
+        "no_pyre",
+        candidate_targets,
+    )
+    return filtered_targets
+
+def do_filter(query: bxl.UqueryContext, target_patterns: typing.Any) -> list[TargetLabel]:
+    root_targets = filter_root_targets(query, target_patterns)
+    return [root_target.label for root_target in root_targets]
+
+def _do_filter_entry_point(ctx: bxl.Context) -> None:
+    query = ctx.uquery()
+    targets = do_filter(
+        query,
+        [query.eval(target) for target in ctx.cli_args.target],
+    )
+    ctx.output.print_json(targets)
+
+filter = bxl_main(
+    doc = ("Expand target patterns and look for all targets in immediate sources " + "that will be built by Pyre."),
+    impl = _do_filter_entry_point,
+    cli_args = {
+        "target": cli_args.list(cli_args.string()),
+    },
+)
diff --git a/buck2/prelude/python/sourcedb/ide.bxl b/buck2/prelude/python/sourcedb/ide.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/ide.bxl
@@ -0,0 +1,57 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":build.bxl", "do_build_ensured")
+load(":query.bxl", "do_query")
+
+def _build_entry_point(ctx: bxl.Context) -> None:
+    bxl_actions = ctx.bxl_actions(
+        target_platform = "prelude//platforms:default",
+    )
+    actions = bxl_actions.actions
+
+    query = ctx.uquery()
+
+    output = {}
+    for source in ctx.cli_args.source:
+        owning_targets_unfiltered = query.owner(source)
+        owning_targets = owning_targets_unfiltered - query.attrfilter(
+            "labels",
+            "conda",
+            owning_targets_unfiltered,
+        )
+        targets_configured = do_query(ctx, query, actions, owning_targets)
+        targets_configured += [target.label for target in ctx.configured_targets(ctx.cli_args.extra_source_targets)]
+
+        sourcedbs = do_build_ensured(ctx, targets_configured)
+
+        output[source] = {"db": sourcedbs, "owning_targets": [target.label for target in owning_targets]}
+
+    ctx.output.print_json(output)
+
+build = bxl_main(
+    doc = """Build Python sourcedb for Python IDE support.
+
+    It takes a list of file paths, and will find the owner targets for all
+    those files and build source-db for those owning targets, returning them all.
+    """,
+    impl = _build_entry_point,
+    cli_args = {
+        "extra-source-targets": cli_args.list(
+            cli_args.string(
+                doc = "fully qualified targets to include in the sourcedb",
+            ),
+            [],  # default value
+        ),
+        "source": cli_args.list(
+            cli_args.string(
+                doc = "File to build a source db for (relative to source root)",
+            ),
+        ),
+    },
+)
diff --git a/buck2/prelude/python/sourcedb/merge.bxl b/buck2/prelude/python/sourcedb/merge.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/merge.bxl
@@ -0,0 +1,27 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def do_merge(ctx: bxl.Context, bxl_actions: bxl.Actions, built_sourcedbs: dict[TargetLabel, Artifact], command_category: str) -> bxl.EnsuredArtifact:
+    actions = bxl_actions.actions
+
+    merger_input = actions.write_json("merge_input.json", built_sourcedbs, has_content_based_path = False)
+    merger_output = actions.declare_output("merged_db.json", has_content_based_path = False)
+
+    dependency_key = bxl_actions.exec_deps.keys()[0]
+
+    command = cmd_args(
+        bxl_actions.exec_deps[dependency_key][RunInfo],
+        merger_input,
+        "--output",
+        merger_output.as_output(),
+        # Declare that the merger result depends on all sourcedbs
+        hidden = built_sourcedbs.values(),
+    )
+
+    actions.run(command, category = command_category)
+    return ctx.output.ensure(merger_output)
diff --git a/buck2/prelude/python/sourcedb/owners.bxl b/buck2/prelude/python/sourcedb/owners.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/owners.bxl
@@ -0,0 +1,42 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":filter.bxl", "get_unfiltered_root_targets")
+
+def _owners_entry_point(ctx: bxl.Context) -> None:
+    query = ctx.uquery()
+    root = ctx.root()
+
+    owning_targets = get_unfiltered_root_targets(query, query.owner(ctx.cli_args.source))
+
+    files = []
+    if len(owning_targets) > 0:
+        target = owning_targets[0]
+        files = query.inputs(target)
+        cell_root = ctx.audit().cell([target.label.cell])[target.label.cell]
+        files = ["{}/{}".format(cell_root, file.path) for file in files]
+
+    ctx.output.print_json({"files": files, "owning_targets": [target.label for target in owning_targets], "root": root})
+
+build = bxl_main(
+    doc = """Determines owning python targets and root, providing files within the first owning target.
+    Note: must be run from within fbsource.
+
+    It takes a file path, returning an object of format
+    `{'owning_targets': List<string>, 'root': string, 'files': List<string>}`
+    - Owning targets is the list of python target labels that own the file.
+    - Root is the buck project root.
+    - Files is the list of files (absolute paths) within the first owning target, if any.
+    """,
+    impl = _owners_entry_point,
+    cli_args = {
+        "source": cli_args.string(
+            doc = "Source file (absolute path)",
+        ),
+    },
+)
diff --git a/buck2/prelude/python/sourcedb/pyrefly.bxl b/buck2/prelude/python/sourcedb/pyrefly.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/pyrefly.bxl
@@ -0,0 +1,526 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Analyse some python files/targets and produce data for the Pyrefly IDE.
+# See <https://github.com/facebook/pyrefly>.
+
+# Missing features:
+#
+# * Manifests for prebuilt library (i.e. 3p python libraries). I think getting those would actually require some extracting and reading from disk (https://github.com/facebook/buck2/blob/2b6c84ef285519a86ad793800296b3cda17e85dd/prelude/python/prebuilt_python_library.bzl#L56)
+# * Anything logic that tries to inject / alter srcs or deps within the python rule need to be replicated, e.g.
+#   + https://github.com/facebook/buck2/blob/2b6c84ef285519a86ad793800296b3cda17e85dd/prelude/python/python_library.bzl#L188-L192
+#   + https://github.com/facebook/buck2/blob/2b6c84ef285519a86ad793800296b3cda17e85dd/prelude/python/python_library.bzl#L339-L341
+#   + https://github.com/facebook/buck2/blob/2b6c84ef285519a86ad793800296b3cda17e85dd/prelude/python/python_library.bzl#L290-L306
+
+load("@prelude//python:typing.bzl", "DEFAULT_PY_VERSION") # @oss-enable
+# @oss-disable[end= ]: load("@prelude//python/meta_only:config.bzl", "DEFAULT_PY_VERSION")
+
+_MODULE_SUFFIXES = set([
+    "dll",
+    "py",
+    "pyi",
+    "pyd",
+    "so",
+])
+
+_CATCH_ALL_STUB_CONTENT = "from typing import Any\n\ndef __getattr__(name: str) -> Any: ...\n"
+
+_MANIFESTLESS_RULE_TYPES = set([
+    "forward",
+    "prelude//rules.bzl:command_alias",
+    "prelude//rules.bzl:export_file",
+    "prelude//rules.bzl:filegroup",
+])
+
+def _rule_has_no_manifest(rule_type: str) -> bool:
+    """Whether a rule contributes no manifest beyond targets already in its dependency graph."""
+    return (
+        rule_type in _MANIFESTLESS_RULE_TYPES
+        or rule_type.endswith(":target_group")
+        or rule_type.endswith("_fbcode_configured_alias_transition")
+        or rule_type.endswith(":rust_proc_macro_alias")
+        or rule_type.endswith(":fbpkg_builder")
+        or rule_type.endswith(":_source_listing")
+    )
+
+def _get_suffix(path: str) -> str | None:
+    """Extract the file suffix without leading dot (e.g. 'py') from a path, or None if no suffix."""
+    last_sep = path.rfind("/")
+    dot = path.rfind(".")
+    if dot > last_sep and dot + 1 < len(path):
+        return path[dot + 1 :]
+    return None
+
+def _append_to_or_set_list(mapping: dict[str, list[str | bxl.EnsuredArtifact]], key: str, value: str | bxl.EnsuredArtifact) -> None:
+    if key in mapping:
+        mapping[key].append(value)
+    else:
+        mapping[key] = [value]
+
+def _append_or_default_if_module(
+    srcs: dict[str, list[str | bxl.EnsuredArtifact]], module: str, path: str | bxl.EnsuredArtifact, extra_filetypes: dict[str, None]
+) -> None:
+    if isinstance(path, bxl.EnsuredArtifact):
+        # we can't filter ensured artifacts, since there's no way to inspect the path
+        _append_to_or_set_list(srcs, module, path)
+        return
+    for suffix in _MODULE_SUFFIXES:
+        if path.endswith("." + suffix):
+            _append_to_or_set_list(srcs, module, path)
+            return
+
+    # File has a non-standard suffix — still include it and record the suffix
+    suffix = _get_suffix(path)
+    if suffix != None:
+        _append_to_or_set_list(srcs, module, path)
+        extra_filetypes[suffix] = None
+
+# Produce a list of all the targets that I care about.
+# This should be everything reachable from the command line arguments.
+def _list_targets(ctx: bxl.Context) -> bxl.ConfiguredTargetSet:
+    cquery = ctx.cquery()
+    uquery = ctx.uquery()
+    files = cquery.deps(ctx.target_universe(uquery.owner(ctx.cli_args.file)).target_set(), 0)
+    targets = cquery.eval("kind('python_library|alias|genrule', %s)", ctx.cli_args.target)
+    res = files
+    for target in targets.values():
+        res += target
+
+    return cquery.deps(res, filter = "kind('python_library|alias|genrule|cxx_python_extension', target_deps())")
+
+def _clean_module(base_module: str, module: str) -> str:
+    base_module = base_module.removesuffix("/").replace("/", ".")
+    module = module.replace("/", ".").removesuffix(".pyi").removesuffix(".py").removesuffix("__init__").removesuffix(".")
+    sep = ""
+    if len(base_module) != 0 and len(module) != 0:
+        sep = "."
+    return (base_module + sep + module).removeprefix("gen-py3.").removeprefix("gen-python.")
+
+# Set common fields for a target entry.
+# NOTE: This function doesn't populate `srcs`. Instead return an empty `srcs` dict for downstream logic to populate.
+def _set_entry_common_fields(
+    entry: dict, attrs: bxl.LazyAttrs, fs: bxl.Filesystem, target: bxl.ConfiguredTargetNode, known_targets: dict[TargetLabel, bxl.ConfiguredTargetNode]
+) -> dict[str, list[str | bxl.EnsuredArtifact]]:
+    srcs = {}
+    deps = []
+    entry["srcs"] = srcs
+    entry["deps"] = deps
+    entry["buildfile_path"] = fs.project_rel_path(target.buildfile_path)
+    python_version = attrs.get("py_version_for_type_checking")
+    entry["python_version"] = python_version.value() if python_version != None and python_version.value() != None else DEFAULT_PY_VERSION
+
+    # TODO(connernilsen): replace with actual platform later
+    entry["python_platform"] = "linux"
+
+    # Get buck.deps first, then fall back to deps. buck.deps might
+    # have extra targets we eventually exclude or stop processing, which is fine.
+    attr_deps = attrs.get("buck.deps") or attrs.get("deps")
+    if attr_deps == None:
+        fail(target.rule_type)
+    attr_deps = attr_deps.value()
+    for dep in attr_deps:
+        dep = dep.raw_target()
+        if dep in known_targets:
+            deps.append(str(dep))
+
+    return srcs
+
+def _handle_alias(entry: dict, attrs: bxl.LazyAttrs, target: bxl.ConfiguredTargetNode) -> None:
+    actual = attrs.get("actual")
+    if actual != None and actual.value() != None:
+        entry["alias"] = actual.value().raw_target()
+    else:
+        fail("Alias has no actual target".format(target.label))
+
+def _handle_python_extension(
+    entry: dict, attrs: bxl.LazyAttrs, fs: bxl.Filesystem, target: bxl.ConfiguredTargetNode, known_targets: dict[TargetLabel, bxl.ConfiguredTargetNode]
+) -> None:
+    _set_entry_common_fields(entry, attrs, fs, target, known_targets)
+
+def _handle_genrule(
+    entry: dict,
+    attrs: bxl.LazyAttrs,
+    fs: bxl.Filesystem,
+    target: bxl.ConfiguredTargetNode,
+    known_targets: dict[TargetLabel, bxl.ConfiguredTargetNode],
+    to_remove: dict[str, None],
+    to_build: list,
+    to_insert: list,
+    genrule_to_insert: list,
+    extra_filetypes: dict[str, None],
+) -> None:
+    labels = attrs.get("labels")
+    if "custom_rule_internal" in labels.value():
+        # skip internal targets, since they will be materialized as part
+        # of their including target
+        to_remove[str(target.label.raw_target())] = None
+        return
+
+    srcs = _set_entry_common_fields(entry, attrs, fs, target, known_targets)
+
+    # Collect suffixes from genrule source files
+    attr_srcs = attrs.get("srcs")
+    if attr_srcs != None:
+        attr_srcs_value = attr_srcs.value()
+        if attr_srcs_value != None:
+            if type(attr_srcs_value) == type({}):
+                attr_srcs_value = attr_srcs_value.values()
+            for src in attr_srcs_value:
+                path = getattr(src, "short_path", None)
+                if path != None:
+                    suffix = _get_suffix(path)
+                    if suffix != None and suffix not in _MODULE_SUFFIXES:
+                        extra_filetypes[suffix] = None
+
+    to_build.append(target)
+
+    # Only one of these will have a value, but get both of them now since
+    # it's easy.
+    out = attrs.get("out")
+    outs = attrs.get("outs")
+    if out != None and out.value() != None:
+        items = {out.value(): out.value()}
+    elif outs != None and outs.value() != None:
+        items = outs.value()
+    else:
+        fail(target)
+
+    if len(items) == 1:
+        module_path = list(items.keys())[0]
+        suffix = _get_suffix(module_path)
+        if suffix != None:
+            if suffix not in _MODULE_SUFFIXES:
+                extra_filetypes[suffix] = None
+            to_insert.append((srcs, _clean_module("", module_path), target.label.with_sub_target()))
+    else:
+        # we need to handle building the full genrule
+        genrule_to_insert.append((target, entry))
+        for module_path, src_paths in items.items():
+            if len(src_paths) < 1:
+                fail("Target src has no output path: {}".format(target.label))
+            suffix = _get_suffix(module_path)
+            if suffix != None:
+                if suffix not in _MODULE_SUFFIXES:
+                    extra_filetypes[suffix] = None
+                _append_or_default_if_module(srcs, _clean_module("", module_path), src_paths[0], extra_filetypes)
+
+def _is_triton_kernel_py_library(target: bxl.ConfiguredTargetNode, attrs: bxl.LazyAttrs) -> bool:
+    """Detect if a target is a triton_kernel _py library.
+
+    These libraries have generated sources from the Triton AOT compiler,
+    which is expensive to build. We skip them to avoid triggering
+    the AOT compile during Pyrefly's sourcedb generation.
+    """
+
+    # Check if target name ends with _py (triton_kernel convention)
+    if not target.label.name.endswith("_py"):
+        return False
+
+    label_str = str(target.label.raw_target())
+    if "triton" not in label_str.lower():
+        return False
+
+    # triton_kernel emits a `{name}_py` python_library whose cpp_dep is the
+    # generated `{name}` library. In configured attrs, that cpp_dep is exposed
+    # through normal deps rather than a separate `cpp_deps` attr.
+    deps = attrs.get("deps")
+    if deps == None or deps.value() == None:
+        return False
+    base_label = label_str.removesuffix("_py")
+    for dep in deps.value():
+        if str(dep.raw_target()) == base_label:
+            return True
+    return False
+
+def _get_python_library_base_module(attrs: bxl.LazyAttrs, target: bxl.ConfiguredTargetNode) -> str:
+    base_module = attrs.get("base_module")
+    if base_module != None and base_module.value() != None:
+        return base_module.value()
+    return target.label.package
+
+def _add_python_library_module_names(modules: dict[str, None], to_add: list | dict, to_remove: dict[str, None], base_module: str) -> None:
+    if type(to_add) == type([]):
+        for v in to_add:
+            short_path = getattr(v, "short_path", None)
+            if getattr(v, "is_source", False) or (type(v) != "Label" and short_path):
+                modules[_clean_module(base_module, short_path)] = None
+            elif type(v) == "Label" and "=" in str(v.raw_target()):
+                split_target = str(v.raw_target()).split("=")
+                if len(split_target) != 2:
+                    fail("Unexpected special type stub target: {}".format(v.raw_target()))
+                to_remove[str(v.raw_target())] = None
+                to_remove[str(split_target[0])] = None
+                modules[_clean_module("", split_target[1])] = None
+    elif type(to_add) == type({}):
+        for k in to_add:
+            modules[_clean_module(base_module, k)] = None
+
+def _catch_all_stub_output_path(target: bxl.ConfiguredTargetNode, module: str) -> str:
+    stable_id = sha256(str(target.label.raw_target()))[:16]
+    module_path = module.replace(".", "/") if len(module) != 0 else "__init__"
+    return "catch_all_sourcedb_stubs/" + stable_id + "/" + module_path + ".pyi"
+
+def _declare_catch_all_stub_source(
+    actions, target: bxl.ConfiguredTargetNode, srcs: dict[str, list[str | bxl.EnsuredArtifact]], module: str, catch_all_stubs_to_insert: list
+) -> None:
+    stub = actions.write(
+        _catch_all_stub_output_path(target, module),
+        _CATCH_ALL_STUB_CONTENT,
+        has_content_based_path = False,
+    )
+    catch_all_stubs_to_insert.append((srcs, module, stub))
+
+def _handle_python_library(
+    actions,
+    entry: dict,
+    attrs: bxl.LazyAttrs,
+    fs: bxl.Filesystem,
+    target: bxl.ConfiguredTargetNode,
+    known_targets: dict[TargetLabel, bxl.ConfiguredTargetNode],
+    to_remove: dict[str, None],
+    to_build: list,
+    to_insert: list,
+    catch_all_stubs_to_insert: list,
+    extra_filetypes: dict[str, None],
+    genrules_reexported: dict[str, None] | None = None,
+) -> None:
+    base_module = _get_python_library_base_module(attrs, target)
+
+    srcs = _set_entry_common_fields(entry, attrs, fs, target, known_targets)
+
+    # Triton kernel *_py libraries expose generated AOT outputs as Python
+    # sources. Building them here is expensive, so model their modules with a
+    # cheap generated stub instead of materializing the real sources.
+    if _is_triton_kernel_py_library(target, attrs):
+        modules = {}
+        type_stubs = attrs.get("type_stubs")
+        type_stubs = {} if type_stubs == None else type_stubs.value()
+        _add_python_library_module_names(modules, type_stubs, to_remove, base_module)
+
+        attr_srcs = attrs.get("srcs")
+        attr_srcs = {} if attr_srcs == None else attr_srcs.value()
+        _add_python_library_module_names(modules, attr_srcs, to_remove, base_module)
+
+        for module in sorted(modules.keys()):
+            _declare_catch_all_stub_source(actions, target, srcs, module, catch_all_stubs_to_insert)
+        return
+
+    # add type stubs first, so that they're preferred by Pyrefly
+    type_stubs = attrs.get("type_stubs")
+    type_stubs = {} if type_stubs == None else type_stubs.value()
+    _get_and_materialize_sources(
+        type_stubs,
+        to_remove,
+        base_module,
+        srcs,
+        to_build,
+        to_insert,
+        fs,
+        extra_filetypes,
+    )
+
+    # python_binary might be the root target, which doesn't have `srcs`.
+    attr_srcs = attrs.get("srcs")
+    attr_srcs = {} if attr_srcs == None else attr_srcs.value()
+    _get_and_materialize_sources(
+        attr_srcs,
+        to_remove,
+        base_module,
+        srcs,
+        to_build,
+        to_insert,
+        fs,
+        extra_filetypes,
+        genrules_reexported,
+    )
+
+def _build_generated_files(ctx: bxl.Context, to_build: list, to_insert: list, genrule_to_insert: list, extra_filetypes: dict[str, None]) -> None:
+    if not to_build:
+        return
+
+    built = ctx.build(to_build)
+    ensured = ctx.output.ensure_multiple(built)
+
+    # handle individual generated files
+    for srcs, module_name, target in to_insert:
+        ensured_target = ensured[target]
+
+        # skip genrule files that failed to build
+        if len(ensured_target) < 1:
+            continue
+        _append_or_default_if_module(srcs, module_name, ensured_target[0].rel_path(), extra_filetypes)
+
+    # handle genrules
+    for target, entry in genrule_to_insert:
+        label = target.label.with_sub_target()
+
+        # skip full genrules that failed to build
+        ensured_label = ensured[label]
+        if len(ensured_label) < 1:
+            entry["srcs"] = {}
+            continue
+        relative_to = ensured_label[0].rel_path()
+        entry["relative_to"] = relative_to
+
+def _ensure_catch_all_stubs(ctx: bxl.Context, catch_all_stubs_to_insert: list, extra_filetypes: dict[str, None]) -> None:
+    if not catch_all_stubs_to_insert:
+        return
+
+    stubs = []
+    for item in catch_all_stubs_to_insert:
+        stubs.append(item[2])
+    ensured_stubs = ctx.output.ensure_multiple(stubs)
+    for i in range(len(ensured_stubs)):
+        ensured_stub = ensured_stubs[i]
+        srcs, module, _ = catch_all_stubs_to_insert[i]
+        _append_or_default_if_module(srcs, module, ensured_stub.rel_path(), extra_filetypes)
+
+def _get_and_materialize_sources(
+    to_add: list | dict,
+    to_remove: dict[str, None],
+    base_module: str,
+    srcs: dict[str, list[str | bxl.EnsuredArtifact]],
+    to_build: list,
+    to_insert: list,
+    fs: bxl.Filesystem,
+    extra_filetypes: dict[str, None],
+    genrules_reexported: dict[str, None] | None = None,
+):
+    if type(to_add) == type([]):
+        for v in to_add:
+            if getattr(v, "is_source", False):
+                _append_or_default_if_module(
+                    srcs,
+                    _clean_module(base_module, v.short_path),
+                    fs.project_rel_path(v),
+                    extra_filetypes,
+                )
+            elif type(v) != "Label" and getattr(v, "short_path"):
+                to_build.append(v)
+                to_insert.append((srcs, _clean_module(base_module, v.short_path), v))
+            elif type(v) == "Label" and "=" in str(v.raw_target()):
+                # handle special type_stubs target types for Pytorch
+                # for these, we want to use the part after the `=` as the
+                # full module name, the part before as a target we don't want
+                # to materialize, and the whole label as a target to build.
+                # Don't materialize the first part of the target, since
+                # otherwise the owning target for the file will be ambiguous,
+                # and we will likely not be able to find any circular imports
+                # these genrules expect.
+                split_target = str(v.raw_target()).split("=")
+                if len(split_target) != 2:
+                    return
+                to_remove[str(v.raw_target())] = None
+                to_remove[str(split_target[0])] = None
+                relative_path = split_target[1]
+                to_build.append(v)
+                to_insert.append((srcs, _clean_module("", relative_path), v))
+    elif type(to_add) == type({}):
+        for k, v in to_add.items():
+            if getattr(v, "is_source", False):
+                _append_or_default_if_module(
+                    srcs,
+                    _clean_module(base_module, k),
+                    fs.project_rel_path(v),
+                    extra_filetypes,
+                )
+            else:
+                if genrules_reexported != None and type(v) == "Label":
+                    genrules_reexported[str(v.raw_target())] = None
+                to_build.append(v)
+                to_insert.append((srcs, _clean_module(base_module, k), v))
+
+def _main(ctx: bxl.Context) -> None:
+    fs = ctx.fs
+    actions = ctx.bxl_actions().actions
+    extra_filetypes = {}  # Set of non-Python file types discovered (dict used as mutable set)
+    to_remove = {}  # Set of targets to remove at the end
+    to_build = []  # List of targets I need to build
+    to_insert = []  # Triples of (target srcs ref, module name, artifact) to insert after building
+    catch_all_stubs_to_insert = []  # Triples of (target srcs ref, module name, stub artifact) to insert after ensuring
+    genrule_to_insert = []  # Doubles of (target, entry) to insert after building
+    entries = {}  # dict[target, {"deps": list[target], "srcs": dict[qualified_path, list[files]]}]
+    json = {"db": entries, "root": ctx.root()}
+
+    # We only want to add `deps` to targets that are in the output.
+    known_targets = {x.label.raw_target(): x for x in _list_targets(ctx) if not _rule_has_no_manifest(x.rule_type) and x.label.name != "restricted_bin"}
+
+    # Tracks genrule targets whose outputs are re-exported by a python_library
+    # via its srcs attribute (not just deps). Populated during _handle_python_library
+    # → _get_and_materialize_sources when a Label-type src references a genrule.
+    genrules_reexported = {}
+
+    for raw_target, x in known_targets.items():
+        if str(raw_target) in to_remove:
+            continue
+
+        attrs = x.attrs_lazy()
+        entry = {}
+        entries[str(x.label.raw_target())] = entry
+
+        if (
+            x.rule_type == "prelude//rules.bzl:alias"
+            or x.rule_type.endswith("_fbcode_configured_alias")
+            or x.rule_type.endswith(":build_mode_alias")
+            or x.rule_type.endswith(":_sanitizer_alias")
+        ):
+            _handle_alias(entry, attrs, x)
+        elif x.rule_type == "prelude//rules.bzl:cxx_python_extension":
+            _handle_python_extension(entry, attrs, fs, x, known_targets)
+        elif "genrule" in x.rule_type:
+            _handle_genrule(entry, attrs, fs, x, known_targets, to_remove, to_build, to_insert, genrule_to_insert, extra_filetypes)
+        elif "python_library" in x.rule_type or x.rule_type.endswith(":python_binary") or x.rule_type.endswith(":python_test"):
+            _handle_python_library(
+                actions, entry, attrs, fs, x, known_targets, to_remove, to_build, to_insert, catch_all_stubs_to_insert, extra_filetypes, genrules_reexported
+            )
+        else:
+            fail("Unknown rule type `{}` for target `{}`".format(x.rule_type, x.label.raw_target()))
+
+    _build_generated_files(ctx, to_build, to_insert, genrule_to_insert, extra_filetypes)
+    _ensure_catch_all_stubs(ctx, catch_all_stubs_to_insert, extra_filetypes)
+
+    # Clear srcs on multi-output genrule targets whose files are re-exported
+    # by a python_library under namespaced module names. Genrules have no
+    # base_module, so _clean_module("", ...) produces bare names like
+    # "unittest" that shadow stdlib modules. We only clear genrules that were
+    # detected as re-exported during _get_and_materialize_sources (via Label
+    # raw_target matching), keeping genrules that are only in deps untouched.
+    for target, _entry in genrule_to_insert:
+        target_name = str(target.label.raw_target())
+        if target_name in genrules_reexported:
+            entry = entries.get(target_name)
+            if entry != None:
+                entry["srcs"] = {}
+
+    # remove any targets we decided we shouldn't output
+    for remove in to_remove:
+        entries.pop(remove)
+    for entry in entries.values():
+        if "deps" in entry:
+            entry["deps"] = [dep for dep in entry["deps"] if dep not in to_remove]
+
+    json["extra_filetypes"] = sorted(extra_filetypes.keys())
+    ctx.output.print_json(json)
+
+main = bxl_main(
+    doc = """Produce data required for the Pyrefly IDE.
+
+    Takes a list of target patterns and build the right data to check each.
+    """,
+    impl = _main,
+    cli_args = {
+        "file": cli_args.list(
+            cli_args.string(doc = "File to analyse"),
+            default = [],
+        ),
+        "target": cli_args.list(
+            cli_args.string(doc = "Target pattern to analyse"),
+            default = [],
+        ),
+    },
+)
diff --git a/buck2/prelude/python/sourcedb/pysa_merged_source_db.bxl b/buck2/prelude/python/sourcedb/pysa_merged_source_db.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/pysa_merged_source_db.bxl
@@ -0,0 +1,137 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//python:python.bzl", "PythonLibraryManifestsTSet")
+load("@prelude//python:source_db.bzl", "PythonSourceDBInfo")
+load("@prelude//python:toolchain.bzl", "PythonToolchainInfo")
+load("@prelude//python:typing.bzl", "get_default_sys_platform")
+# @oss-disable[end= ]: load("@prelude//python/meta_only:config.bzl", "DEFAULT_PY_VERSION")
+load("@prelude//python:typing.bzl", "DEFAULT_PY_VERSION") # @oss-enable
+load("@prelude//python/sourcedb:filter.bxl", "BUCK_PYTHON_RULE_KINDS")
+load("@prelude//utils:utils.bzl", "flatten")
+
+def _is_python_target(rule_type: str) -> bool:
+    for kind in BUCK_PYTHON_RULE_KINDS:
+        if rule_type.endswith(kind):
+            return True
+    return False
+
+def _is_binary_or_test(rule_type: str) -> bool:
+    return rule_type.endswith("python_binary") or rule_type.endswith("python_test")
+
+def _get_manifests_from_analysis(analysis_result: bxl.AnalysisResult) -> [PythonLibraryManifestsTSet, None]:
+    sub_targets = analysis_result.providers()[DefaultInfo].sub_targets
+    sdb = sub_targets.get("source-db-no-deps")
+    if sdb == None:
+        return None
+    info = sdb.get(PythonSourceDBInfo)
+    if info == None:
+        return None
+    return info.manifests
+
+def _ensure_manifest_artifacts(ctx: bxl.Context, manifest_info) -> None:
+    for artifact, _dest in manifest_info.artifacts:
+        ctx.output.ensure(artifact)
+
+def _run(ctx: bxl.Context) -> None:
+    # Resolve target patterns to Python targets
+    all_targets = ctx.unconfigured_targets(flatten(ctx.cli_args.target))
+    python_targets = [t for t in all_targets if _is_python_target(t.rule_type)]
+
+    if len(python_targets) == 0:
+        fail("No Python targets found matching the given patterns")
+
+    # python_binary and python_test targets create an implicit <name>-library
+    # target that holds the actual sources. Resolve to those instead.
+    library_labels = []
+    for target in python_targets:
+        if _is_binary_or_test(target.rule_type):
+            library_labels.append(str(target.label) + "-library")
+        else:
+            library_labels.append(str(target.label))
+    library_targets = ctx.unconfigured_targets(library_labels)
+
+    configured_targets = ctx.configured_targets(library_targets, modifiers = ctx.modifiers)
+    analysis_results = ctx.analysis(configured_targets)
+
+    # Collect manifests tsets and track which targets are roots
+    root_labels = {}
+    all_tsets = []
+    first_configured = None
+    for configured_target in configured_targets:
+        label = configured_target.label.with_sub_target()
+        result = analysis_results[label]
+        manifests = _get_manifests_from_analysis(result)
+        if manifests != None:
+            all_tsets.append(manifests)
+            root_labels[str(configured_target.label)] = True
+            if first_configured == None:
+                first_configured = configured_target
+
+    if len(all_tsets) == 0:
+        fail("No PythonSourceDBInfo manifests found for the given targets")
+
+    # Get typeshed from the first target's Python toolchain
+    first_attrs = first_configured.resolved_attrs_eager(ctx)
+    typeshed = first_attrs._python_toolchain[PythonToolchainInfo].typeshed_stubs
+
+    # Create a combined tset from all root targets' manifests
+    actions = ctx.bxl_actions().actions
+    combined = actions.tset(PythonLibraryManifestsTSet, children = all_tsets)
+
+    # Traverse the combined tset to separate sources from dependencies
+    source_manifests = []
+    dep_manifests = []
+    for manifest in combined.traverse():
+        if manifest.src_types == None:
+            continue
+        if str(manifest.label.configured_target()) in root_labels:
+            source_manifests.append(manifest.src_types)
+        else:
+            dep_manifests.append(manifest.src_types)
+
+    # Ensure all manifest files and their referenced source artifacts
+    source_paths = []
+    for manifest_info in source_manifests:
+        ensured = ctx.output.ensure(manifest_info.manifest)
+        source_paths.append(ensured.rel_path())
+        _ensure_manifest_artifacts(ctx, manifest_info)
+
+    dep_paths = []
+    for manifest_info in dep_manifests:
+        ensured = ctx.output.ensure(manifest_info.manifest)
+        dep_paths.append(ensured.rel_path())
+        _ensure_manifest_artifacts(ctx, manifest_info)
+
+    # Ensure typeshed artifacts
+    typeshed_path = None
+    if typeshed != None:
+        typeshed_ensured = ctx.output.ensure(typeshed.manifest)
+        typeshed_path = typeshed_ensured.rel_path()
+        _ensure_manifest_artifacts(ctx, typeshed)
+
+    ctx.output.print_json({
+        "dependencies": dep_paths,
+        "py_version": DEFAULT_PY_VERSION,
+        "sources": source_paths,
+        "system_platform": get_default_sys_platform(),
+        "typeshed": typeshed_path,
+    })
+
+run = bxl_main(
+    doc = """Produce a merged type check config for multiple Python Buck targets.
+
+    Usage: buck2 bxl prelude//python/sourcedb/pysa_merged_source_db.bxl:run -- --target fbcode//foo/...
+    """,
+    impl = _run,
+    cli_args = {
+        "target": cli_args.list(
+            cli_args.target_expr(doc = "Target pattern to include in the merged config"),
+        ),
+    },
+)
diff --git a/buck2/prelude/python/sourcedb/query.bxl b/buck2/prelude/python/sourcedb/query.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/query.bxl
@@ -0,0 +1,72 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//python:python.bzl", "PythonLibraryManifestsTSet")
+load("@prelude//python:source_db.bzl", "PythonSourceDBInfo")
+load("@prelude//python/sourcedb:filter.bxl", "filter_root_targets")
+
+def _get_python_library_manifests_from_analysis_result(analysis_result: bxl.AnalysisResult) -> [PythonLibraryManifestsTSet, None]:
+    sub_target = analysis_result.providers()[DefaultInfo].sub_targets.get("source-db-no-deps")
+    if sub_target == None:
+        return None
+    python_source_db_info = sub_target.get(PythonSourceDBInfo)
+    if python_source_db_info == None:
+        return None
+    return python_source_db_info.manifests
+
+def _get_python_library_manifests_from_targets(ctx: bxl.Context, targets: bxl.UnconfiguredTargetSet) -> list[PythonLibraryManifestsTSet]:
+    configured_targets = ctx.configured_targets(targets, modifiers = ctx.modifiers)
+    return filter(None, [_get_python_library_manifests_from_analysis_result(analysis_result) for analysis_result in ctx.analysis(configured_targets).values()])
+
+def get_python_library_manifests_tset_from_targets(
+    ctx: bxl.Context, actions: AnalysisActions, root_targets: bxl.UnconfiguredTargetSet
+) -> PythonLibraryManifestsTSet:
+    return actions.tset(
+        PythonLibraryManifestsTSet,
+        children = _get_python_library_manifests_from_targets(ctx, root_targets),
+    )
+
+def get_python_library_manifests_tset_from_target_patterns(
+    ctx: bxl.Context, query: bxl.UqueryContext, actions: AnalysisActions, target_patterns: typing.Any
+) -> PythonLibraryManifestsTSet:
+    root_targets = filter_root_targets(query, target_patterns)
+    return get_python_library_manifests_tset_from_targets(ctx, actions, root_targets)
+
+def do_query(ctx: bxl.Context, query: bxl.UqueryContext, actions: AnalysisActions, target_patterns: typing.Any) -> list[ConfiguredTargetLabel]:
+    manifests_of_transitive_dependencies = get_python_library_manifests_tset_from_target_patterns(
+        ctx,
+        query,
+        actions,
+        target_patterns,
+    )
+
+    # Invariant: every target whose manifest has non-None src_types must also
+    # provide a "source-db-no-deps" subtarget, since build.bxl will attempt to
+    # build that subtarget for each target returned here.
+    # Rule types that currently satisfy this: python_library,
+    # prebuilt_python_library, and cxx_python_extension.
+    return [manifest.label.configured_target() for manifest in manifests_of_transitive_dependencies.traverse() if manifest.src_types != None]
+
+def _do_query_entry_point(ctx: bxl.Context) -> None:
+    query = ctx.uquery()
+    actions = ctx.bxl_actions().actions
+    targets = do_query(
+        ctx,
+        query,
+        actions,
+        [query.eval(target) for target in ctx.cli_args.target],
+    )
+    ctx.output.print_json([target.raw_target() for target in targets])
+
+query = bxl_main(
+    doc = ("Expand target patterns and look for all targets in their transitive" + "dependencies that will be built by Pyre."),
+    impl = _do_query_entry_point,
+    cli_args = {
+        "target": cli_args.list(cli_args.string()),
+    },
+)
diff --git a/buck2/prelude/python/sourcedb/tests/pyrefly_expected.json b/buck2/prelude/python/sourcedb/tests/pyrefly_expected.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/pyrefly_expected.json
@@ -0,0 +1,267 @@
+{
+  "db": {
+    "prelude//python/sourcedb/tests/test_files/triton_collision/a:b": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/triton_collision/a/BUCK",
+      "deps": [],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {}
+    },
+    "prelude//python/sourcedb/tests/test_files/triton_collision/a:b_lib": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/triton_collision/a/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files/triton_collision/a:b_py"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {}
+    },
+    "prelude//python/sourcedb/tests/test_files/triton_collision/a:b_py": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/triton_collision/a/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files/triton_collision/a:b"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12-pyrefly",
+      "relative_to": null,
+      "srcs": {
+        "python.sourcedb.tests.test_files.triton_collision.kernel": [
+          "buck-out/v2/gen/prelude/<more generated path output>/out/catch_all_sourcedb_stubs/6514d54e329e0204/python/sourcedb/tests/test_files/triton_collision/kernel.pyi"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files/triton_collision:a_b": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/triton_collision/BUCK",
+      "deps": [],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {}
+    },
+    "prelude//python/sourcedb/tests/test_files/triton_collision:a_b_lib": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/triton_collision/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files/triton_collision:a_b_py"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {}
+    },
+    "prelude//python/sourcedb/tests/test_files/triton_collision:a_b_py": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/triton_collision/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files/triton_collision:a_b"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12-pyrefly",
+      "relative_to": null,
+      "srcs": {
+        "python.sourcedb.tests.test_files.triton_collision.kernel": [
+          "buck-out/v2/gen/prelude/<more generated path output>/out/catch_all_sourcedb_stubs/fa07c7f3671b4749/python/sourcedb/tests/test_files/triton_collision/kernel.pyi"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files:alias": {
+      "alias": "prelude//python/sourcedb/tests/test_files:alias_lib"
+    },
+    "prelude//python/sourcedb/tests/test_files:alias_lib": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {
+        "alias": [
+          "prelude/python/sourcedb/tests/test_files/alias.py"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files:build_mode_alias": {
+      "alias": "prelude//python/sourcedb/tests/test_files:alias_lib"
+    },
+    "prelude//python/sourcedb/tests/test_files:generated_file": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {
+        "generated_file": [
+          "buck-out/v2/gen/prelude/<more generated path output>/out/generated_file.pyi"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files:generated_files": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": "buck-out/<some generated path>/out/",
+      "srcs": {
+        "generated1": [
+          "generated1.py"
+        ],
+        "generated2": [
+          "generated2.py"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files:lib": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files:alias",
+        "prelude//python/sourcedb/tests/test_files:generated_file",
+        "prelude//python/sourcedb/tests/test_files:subdir"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {
+        "python.sourcedb.tests.test_files.lib": [
+          "prelude/python/sourcedb/tests/test_files/lib.py"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files:main": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files/triton_collision/a:b_lib",
+        "prelude//python/sourcedb/tests/test_files/triton_collision:a_b_lib",
+        "prelude//python/sourcedb/tests/test_files:build_mode_alias",
+        "prelude//python/sourcedb/tests/test_files:lib",
+        "prelude//python/sourcedb/tests/test_files:my_extension_lib",
+        "prelude//python/sourcedb/tests/test_files:reexported_genrule_lib",
+        "prelude//python/sourcedb/tests/test_files:triton_test_lib"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {
+        "python.sourcedb.tests.test_files.main": [
+          "prelude/python/sourcedb/tests/test_files/main.py"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files:my_extension": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files:my_extension_stub"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {}
+    },
+    "prelude//python/sourcedb/tests/test_files:my_extension_lib": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files:my_extension"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {
+        "python.sourcedb.tests.test_files.my_extension": [
+          "prelude/python/sourcedb/tests/test_files/my_extension.py"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files:my_extension_stub": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {
+        "python.sourcedb.tests.test_files.my_extension": [
+          "prelude/python/sourcedb/tests/test_files/my_extension.pyi"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files:reexported_genrule": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": "buck-out/<some generated path>/out/",
+      "srcs": {}
+    },
+    "prelude//python/sourcedb/tests/test_files:reexported_genrule_lib": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files:reexported_genrule",
+        "prelude//python/sourcedb/tests/test_files:reexported_genrule",
+        "prelude//python/sourcedb/tests/test_files:reexported_genrule"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {
+        "python.sourcedb.tests.test_files.helpers": [
+          "buck-out/v2/gen/prelude/<more generated path output>/out/helpers.py"
+        ],
+        "python.sourcedb.tests.test_files.utils": [
+          "buck-out/v2/gen/prelude/<more generated path output>/out/utils.py"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files:subdir": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files:generated_files"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {
+        "python.sourcedb.tests.test_files.subdir": [
+          "prelude/python/sourcedb/tests/test_files/subdir/__init__.py",
+          "prelude/python/sourcedb/tests/test_files/subdir/__init__.pyi"
+        ],
+        "python.sourcedb.tests.test_files.subdir.util": [
+          "prelude/python/sourcedb/tests/test_files/subdir/util.py",
+          "prelude/python/sourcedb/tests/test_files/subdir/util.pyi"
+        ]
+      }
+    },
+    "prelude//python/sourcedb/tests/test_files:triton_test": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {}
+    },
+    "prelude//python/sourcedb/tests/test_files:triton_test_lib": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files:triton_test_py"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12",
+      "relative_to": null,
+      "srcs": {}
+    },
+    "prelude//python/sourcedb/tests/test_files:triton_test_py": {
+      "buildfile_path": "prelude/python/sourcedb/tests/test_files/BUCK",
+      "deps": [
+        "prelude//python/sourcedb/tests/test_files:triton_test"
+      ],
+      "python_platform": "linux",
+      "python_version": "3.12-pyrefly",
+      "relative_to": null,
+      "srcs": {
+        "python.sourcedb.tests.test_files.triton_kernel": [
+          "buck-out/v2/gen/prelude/<more generated path output>/out/catch_all_sourcedb_stubs/7d64be37df83c3cd/python/sourcedb/tests/test_files/triton_kernel.pyi"
+        ]
+      }
+    }
+  },
+  "extra_filetypes": [
+    "sh"
+  ],
+  "root": ""
+}
diff --git a/buck2/prelude/python/sourcedb/tests/pyrefly_test.py b/buck2/prelude/python/sourcedb/tests/pyrefly_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/pyrefly_test.py
@@ -0,0 +1,232 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+from __future__ import annotations
+
+import argparse
+import dataclasses
+import difflib
+import json
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+EXPECTATIONS: Path = Path(__file__).parent / "pyrefly_expected.json"
+DEFAULT_TEST_TARGET: str = "prelude//python/sourcedb/tests/test_files:main"
+PATH_PREFIX: str = "prelude/python"
+
+
+def strip_prefix(path: str) -> str:
+    if path.startswith("buck-out"):
+        catch_all_stub_marker = "/catch_all_sourcedb_stubs/"
+        if catch_all_stub_marker in path:
+            return (
+                "buck-out/v2/gen/prelude/<more generated path output>/out/"
+                + "catch_all_sourcedb_stubs/"
+                + path.split(catch_all_stub_marker, 1)[1]
+            )
+        path = Path(path)
+        return f"buck-out/v2/gen/prelude/<more generated path output>/out/{path.name}"
+    elif PATH_PREFIX in str(path):
+        return PATH_PREFIX + str(path).split(PATH_PREFIX)[1]
+    else:
+        return path
+
+
+@dataclasses.dataclass
+class Alias:
+    alias: str
+
+
+@dataclasses.dataclass
+class Manifest:
+    srcs: dict[str, list[str]]
+    deps: list[str]
+    buildfile_path: str
+    python_version: str
+    python_platform: str
+    relative_to: str | None
+
+    def strip_root(self) -> None:
+        for paths in self.srcs.values():
+            old_paths = list(paths)
+            paths.clear()
+            for path in old_paths:
+                paths.append(strip_prefix(path))
+
+        if self.relative_to is not None:
+            self.relative_to = "buck-out/<some generated path>/out/"
+
+        self.buildfile_path = strip_prefix(self.buildfile_path)
+
+    @staticmethod
+    def from_json(json: Any) -> "Manifest":
+        for key in (
+            "srcs",
+            "deps",
+            "buildfile_path",
+            "python_version",
+            "python_platform",
+        ):
+            if key not in json:
+                raise ValueError(
+                    f"Unknown type for manifest, does not have '{key}' key. Keys are: "
+                    + ", ".join(json.keys())
+                )
+        # make sure relative_to is set
+        json["relative_to"] = json.get("relative_to")
+
+        manifest = Manifest(**json)
+        for paths in manifest.srcs.values():
+            paths.sort()
+        manifest.deps.sort()
+        return manifest
+
+
+@dataclasses.dataclass
+class DB:
+    db: dict[str, Manifest | Alias]
+    root: str
+    extra_filetypes: list[str]
+
+    def strip_root(self) -> None:
+        self.root = strip_prefix(self.root)
+
+        for value in self.db.values():
+            if not isinstance(value, Manifest):
+                continue
+            value.strip_root()
+
+    @staticmethod
+    def from_json(json: Any) -> "DB":
+        expected_keys = {"db", "root", "extra_filetypes"}
+        if set(json.keys()) != expected_keys:
+            raise ValueError(
+                f"Mismatched keys from DB. Expected {expected_keys}, got {json.keys()}"
+            )
+
+        inner_db = {}
+
+        for target, info in json["db"].items():
+            if "alias" in info:
+                inner_db[target] = Alias(alias=info["alias"])
+            else:
+                inner_db[target] = Manifest.from_json(info)
+
+        db = DB(
+            # strip root, since it's not relevant to these tests
+            root="",
+            db=inner_db,
+            extra_filetypes=json["extra_filetypes"],
+        )
+
+        db.strip_root()
+        return db
+
+    def to_json(self) -> str:
+        return json.dumps(dataclasses.asdict(self), indent=2, sort_keys=True)
+
+
+def query_buck(test_target: str) -> Any:
+    result = subprocess.run(
+        [
+            "buck2",
+            "bxl",
+            "--reuse-current-config",
+            "prelude//python/sourcedb/pyrefly.bxl:main",
+            "--",
+            "--target",
+            test_target,
+        ],
+        capture_output=True,
+    )
+
+    stdout = result.stdout.decode("utf-8")
+    if result.returncode != 0:
+        stderr = result.stderr.decode("utf-8")
+        raise Exception(
+            f"Pyrefly execution with Buck2 resulted in non-zero exit: {result.returncode}\n"
+            + f"STDOUT: ```\n{stdout}```\nSTDERR: ```\n{stderr}```\nCOMMAND: `{result.args}`"
+        )
+
+    return json.loads(stdout)
+
+
+def diff_result(actual: DB, expected: DB, output: Path | None) -> None:
+    if actual == expected:
+        print("Congrats, you passed!")
+        exit(0)
+
+    actual_str = actual.to_json().split("\n")
+    expected_str = expected.to_json().split("\n")
+
+    diff = "\n".join(
+        difflib.context_diff(
+            actual_str, expected_str, fromfile="actual", tofile="expected"
+        )
+    )
+
+    if output is None:
+        print(diff)
+    else:
+        output.write_bytes(diff.encode("utf-8"))
+
+    print("\nTest results differ...")
+    sys.exit(1)
+
+
+def get_expectations(expectations: Path) -> DB:
+    text = expectations.read_bytes().decode("utf-8")
+    return DB.from_json(json.loads(text))
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Test `pyrefly.bxl` to ensure stability between changes.",
+    )
+    parser.add_argument(
+        "--test-target",
+        default=DEFAULT_TEST_TARGET,
+        help="The target to generate output for and compare against expectations",
+    )
+    parser.add_argument(
+        "--generate",
+        action="store_true",
+        help="Regenerate the expectations file and skip checking. Writes to `--expectations`",
+    )
+    parser.add_argument(
+        "--output",
+        help=(
+            "Where to write the diff on failure. If no output is provided, writes to stdout"
+        ),
+        type=Path,
+    )
+    parser.add_argument(
+        "--expectations",
+        help="The expectations file to compare results against",
+        type=Path,
+        default=EXPECTATIONS,
+    )
+    args = parser.parse_args()
+
+    actual = DB.from_json(query_buck(args.test_target))
+
+    if args.generate:
+        text = actual.to_json()
+        args.expectations.write_bytes(text.encode("utf-8"))
+        print("Generated!")
+        sys.exit(0)
+
+    expectations = get_expectations(args.expectations)
+
+    diff_result(actual, expectations, args.output)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/BUCK b/buck2/prelude/python/sourcedb/tests/test_files/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/BUCK
@@ -0,0 +1,146 @@
+load("@fbcode_macros//build_defs:python_library.bzl", fbcode_python_library = "python_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load(":test_rules.bzl", "build_mode_alias")
+
+oncall("pyre")
+
+source_listing()
+
+python_library(
+    name = "main",
+    srcs = ["main.py"],
+    deps = [
+        "prelude//python/sourcedb/tests/test_files/triton_collision:a_b_lib",
+        "prelude//python/sourcedb/tests/test_files/triton_collision/a:b_lib",
+        ":build_mode_alias",
+        ":lib",
+        ":my_extension_lib",
+        ":reexported_genrule_lib",
+        ":triton_test_lib",
+    ],
+)
+
+build_mode_alias(
+    name = "build_mode_alias",
+    actual = ":alias_lib",
+)
+
+# Test that multi-output genrule srcs are cleared when a parent python_library
+# re-exports the files under namespaced module names. The genrule produces
+# bare names (e.g. "utils") that would shadow stdlib modules; the parent
+# provides proper names (e.g. "python.sourcedb.tests.test_files.utils").
+genrule(
+    name = "reexported_genrule",
+    srcs = ["gen.sh"],
+    outs = {
+        "helpers.py": [
+            "helpers.py",
+        ],
+        "utils.py": [
+            "utils.py",
+        ],
+    },
+    cmd = "touch ${OUT}/utils.py && touch ${OUT}/helpers.py",
+)
+
+python_library(
+    name = "reexported_genrule_lib",
+    srcs = {
+        "helpers.py": ":reexported_genrule[helpers.py]",
+        "utils.py": ":reexported_genrule[utils.py]",
+    },
+    deps = [":reexported_genrule"],
+)
+
+python_library(
+    name = "lib",
+    srcs = ["lib.py"],
+    type_stubs = [":generated_file"],
+    deps = [
+        ":alias",
+        ":subdir",
+    ],
+)
+
+python_library(
+    name = "subdir",
+    srcs = [
+        "subdir/__init__.py",
+        "subdir/__init__.pyi",
+        "subdir/util.py",
+        "subdir/util.pyi",
+    ],
+    deps = [":generated_files"],
+)
+
+alias(
+    name = "alias",
+    actual = ":alias_lib",
+)
+
+python_library(
+    name = "alias_lib",
+    srcs = ["alias.py"],
+    # @lint-ignore BUCKLINT tests Python type checking sourcedb functionality with base_module
+    base_module = "",
+)
+
+genrule(
+    name = "generated_files",
+    srcs = ["gen.sh"],
+    outs = {
+        "generated1.py": [
+            "generated1.py",
+        ],
+        "generated2.py": [
+            "generated2.py",
+        ],
+    },
+    cmd = "touch ${OUT}/generated1.py && touch ${OUT}/generated2.py",
+)
+
+genrule(
+    name = "generated_file",
+    out = "generated_file.pyi",
+    cmd = "touch ${OUT}",
+)
+
+python_library(
+    name = "my_extension_stub",
+    srcs = ["my_extension.pyi"],
+)
+
+cxx_python_extension(
+    name = "my_extension",
+    srcs = ["my_extension.cpp"],
+    base_module = "my_extension",
+    deps = [":my_extension_stub"],
+)
+
+cxx_python_extension(
+    name = "triton_test",
+    srcs = ["my_extension.cpp"],
+    base_module = "triton_test",
+)
+
+python_library(
+    name = "my_extension_lib",
+    srcs = ["my_extension.py"],
+    deps = [":my_extension"],
+)
+
+# Test targets for Triton source DB filtering.
+
+fbcode_python_library(
+    name = "triton_test_py",
+    srcs = ["triton_kernel.py"],
+    # Real triton_kernel rules generate a *_py python_library with cpp_deps.
+    # The source DB should stub it to avoid materializing expensive AOT output.
+    cpp_deps = [":triton_test"],
+)
+
+python_library(
+    name = "triton_test_lib",
+    srcs = [],
+    deps = [":triton_test_py"],
+)
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/alias.py b/buck2/prelude/python/sourcedb/tests/test_files/alias.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/alias.py
@@ -0,0 +1,7 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/gen.sh b/buck2/prelude/python/sourcedb/tests/test_files/gen.sh
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/gen.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/bash
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/lib.py b/buck2/prelude/python/sourcedb/tests/test_files/lib.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/lib.py
@@ -0,0 +1,7 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/main.py b/buck2/prelude/python/sourcedb/tests/test_files/main.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/main.py
@@ -0,0 +1,7 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/my_extension.cpp b/buck2/prelude/python/sourcedb/tests/test_files/my_extension.cpp
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/my_extension.cpp
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/my_extension.py b/buck2/prelude/python/sourcedb/tests/test_files/my_extension.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/my_extension.py
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/my_extension.pyi b/buck2/prelude/python/sourcedb/tests/test_files/my_extension.pyi
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/my_extension.pyi
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/subdir/__init__.py b/buck2/prelude/python/sourcedb/tests/test_files/subdir/__init__.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/subdir/__init__.py
@@ -0,0 +1,7 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/subdir/__init__.pyi b/buck2/prelude/python/sourcedb/tests/test_files/subdir/__init__.pyi
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/subdir/__init__.pyi
@@ -0,0 +1,7 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/subdir/util.py b/buck2/prelude/python/sourcedb/tests/test_files/subdir/util.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/subdir/util.py
@@ -0,0 +1,7 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/subdir/util.pyi b/buck2/prelude/python/sourcedb/tests/test_files/subdir/util.pyi
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/subdir/util.pyi
@@ -0,0 +1,7 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/test_rules.bzl b/buck2/prelude/python/sourcedb/tests/test_files/test_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/test_rules.bzl
@@ -0,0 +1,17 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _forwarding_alias_impl(ctx: AnalysisContext) -> list[Provider]:
+    return ctx.attrs.actual.providers
+
+build_mode_alias = rule(
+    impl = _forwarding_alias_impl,
+    attrs = {
+        "actual": attrs.dep(),
+    },
+)
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/BUCK b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/BUCK
@@ -0,0 +1,25 @@
+load("@fbcode_macros//build_defs:python_library.bzl", fbcode_python_library = "python_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("pyre")
+
+source_listing()
+
+cxx_python_extension(
+    name = "a_b",
+    srcs = ["extension.cpp"],
+    base_module = "triton_collision",
+)
+
+fbcode_python_library(
+    name = "a_b_py",
+    srcs = ["kernel.py"],
+    base_module = "python.sourcedb.tests.test_files.triton_collision",
+    cpp_deps = [":a_b"],
+)
+
+python_library(
+    name = "a_b_lib",
+    srcs = [],
+    deps = [":a_b_py"],
+)
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/BUCK b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/BUCK
@@ -0,0 +1,25 @@
+load("@fbcode_macros//build_defs:python_library.bzl", fbcode_python_library = "python_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("pyre")
+
+source_listing()
+
+cxx_python_extension(
+    name = "b",
+    srcs = ["extension.cpp"],
+    base_module = "triton_collision",
+)
+
+fbcode_python_library(
+    name = "b_py",
+    srcs = ["kernel.py"],
+    base_module = "python.sourcedb.tests.test_files.triton_collision",
+    cpp_deps = [":b"],
+)
+
+python_library(
+    name = "b_lib",
+    srcs = [],
+    deps = [":b_py"],
+)
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/extension.cpp b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/extension.cpp
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/extension.cpp
@@ -0,0 +1,9 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/kernel.py b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/kernel.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/a/kernel.py
@@ -0,0 +1,7 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/extension.cpp b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/extension.cpp
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/extension.cpp
@@ -0,0 +1,9 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/kernel.py b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/kernel.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/triton_collision/kernel.py
@@ -0,0 +1,7 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
diff --git a/buck2/prelude/python/sourcedb/tests/test_files/triton_kernel.py b/buck2/prelude/python/sourcedb/tests/test_files/triton_kernel.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/tests/test_files/triton_kernel.py
@@ -0,0 +1,25 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Simulated Triton kernel for testing stub generation.
+
+This file represents code that would normally be generated by the Triton AOT
+compiler. In real usage, this would be expensive to generate during IDE analysis.
+"""
+
+
+def kernel_func(x):
+    """A simulated kernel function."""
+    return x * 2
+
+
+class KernelClass:
+    """A simulated kernel class."""
+
+    def method(self):
+        return 42
diff --git a/buck2/prelude/python/sourcedb/typing_query.bxl b/buck2/prelude/python/sourcedb/typing_query.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/sourcedb/typing_query.bxl
@@ -0,0 +1,44 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//python/sourcedb:filter.bxl", "BUCK_PYTHON_RULE_KIND_QUERY")
+
+def get_owners_for_files(query: bxl.UqueryContext, sources: list[str]) -> dict[str, bxl.UnconfiguredTargetSet]:
+    return {source: query.owner(source) for source in sources}
+
+def has_any_python_targets_with_typing(query: bxl.UqueryContext, owners: bxl.UnconfiguredTargetSet) -> bool:
+    targets_with_typing = query.attrfilter("typing", "True", owners)
+
+    python_targets_with_typing = query.kind(
+        BUCK_PYTHON_RULE_KIND_QUERY,
+        targets_with_typing,
+    )
+
+    return len(python_targets_with_typing) != 0
+
+def get_files_per_target_typed(query: bxl.UqueryContext, sources: list[str]) -> dict[str, bool]:
+    files_to_owners = get_owners_for_files(query, sources)
+
+    return {file: has_any_python_targets_with_typing(query, owners) for file, owners in files_to_owners.items()}
+
+def _do_typing_query_entry_point(ctx: bxl.Context) -> None:
+    query = ctx.uquery()
+    files_per_target_typed = get_files_per_target_typed(query, ctx.cli_args.source)
+    ctx.output.print_json(files_per_target_typed)
+
+typing_query = bxl_main(
+    doc = ("Queries Buck about a given file to determine if any owning targets have typing " + "in their attributes."),
+    impl = _do_typing_query_entry_point,
+    cli_args = {
+        "source": cli_args.list(
+            cli_args.string(
+                doc = "The absolute path to a file you are trying to get typing attributes of",
+            ),
+        ),
+    },
+)
diff --git a/buck2/prelude/python/toolchain.bzl b/buck2/prelude/python/toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/toolchain.bzl
@@ -0,0 +1,124 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:arglike.bzl", "ArgLike")
+load(":manifest.bzl", "ManifestInfo")
+
+# The ways that Python executables handle native linkable dependencies.
+NativeLinkStrategy = enum(
+    # Statically links extensions into an embedded python binary
+    "native",
+    # Pull transitive native deps in as fully linked standalone shared libraries.
+    # This is typically the fastest build-time link strategy, as it requires no
+    # top-level context and therefore can shared build artifacts with all other
+    # binaries using this strategy.
+    "separate",
+    # Statically link all transitive native deps, which don't have an explicit
+    # dep from non-C/C++ code (e.g. Python), into a monolithic shared library.
+    # Native dep roots, which have an explicit dep from non-C/C++ code, remain
+    # as fully linked standalone shared libraries so that, typically, application
+    # code doesn't need to change to work with this strategy. This strategy
+    # incurs a relatively big build-time cost, but can significantly reduce the
+    # size of native code and number of shared libraries pulled into the binary.
+    "merged",
+)
+
+PackageStyle = enum(
+    "inplace",
+    "standalone",
+    # Similar to inplace, but generate copies instead of symlinks
+    "outplace",
+)
+
+StripLibparStrategy = enum(
+    # Strip all binaries and libraries
+    "full",
+    # Extract debug symbols into separate files
+    "extract",
+    # Leave debug symbols intact
+    "none",
+)
+
+PythonToolchainInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "build_standalone_binaries_locally": provider_field(bool | None, default = None),
+        "compile": provider_field(ArgLike | None, default = None),
+        # Whether to precompile .pyc bytecode for this version. Disabled for
+        # versions whose pyc magic number isn't yet frozen + fully deployed.
+        "pyc_compilation_enabled": provider_field(bool, default = True),
+        # The interpreter to use to compile bytecode.
+        "host_interpreter": provider_field(ArgLike | None, default = None),
+        "interpreter": provider_field(ArgLike | None, default = None),
+        "version": provider_field(str | None, default = None),
+        "native_link_strategy": provider_field(str | None, default = None),  # Should be `NativeLinkStrategy`.
+        "linker_flags": provider_field(ArgLike, default = []),
+        "binary_linker_flags": provider_field(ArgLike, default = []),
+        "supports_content_based_paths": provider_field(bool | None, default = None),
+        "extension_linker_flags": provider_field(ArgLike, default = []),
+        "wheel_extension_linker_flags": provider_field(ArgLike, default = []),
+        "wheel_linker_flags": provider_field(ArgLike, default = []),
+        # site-packages-relative rpaths to embed into libs/bins in the wheel
+        "wheel_rpaths": provider_field(ArgLike, default = []),
+        "gen_lpar_bootstrap": provider_field(Dependency | None, default = None),
+        "package_style": provider_field(str | None, default = None),  # Should be `PackageStyle`.
+        "strip_libpar": provider_field(str | None, default = None),  # Should be `StripLibparStrategy`.
+        "native_library_runtime_paths": provider_field(ArgLike, default = []),
+        "native_library_env_var": provider_field(ArgLike | None, default = None),
+        "make_py_package_live": provider_field(Dependency | None, default = None),
+        "make_py_package_standalone": provider_field(ArgLike | None, default = None),
+        "pex_extension": provider_field(str, default = ".par"),
+        # An optional executable for per-target type checking. It is invoked as
+        # `<type_checker> <config.json> --output <result.json>`.
+        #
+        # The input JSON contains `sources` and `dependencies` manifest lists,
+        # a `typeshed` manifest, `py_version`, and `system_platform`. The checker
+        # must write a Pyre-compatible JSON object containing an `errors` list.
+        # Each error must include `code`; `name` and `severity` are optional.
+        # Errors that fail validation must also include `path`, `line`, `column`,
+        # and `description`. Diagnostics with code 0, name `unused-ignore` or
+        # `unused-type-ignore`, or severity `info`, `ignore`, or `warn` do not
+        # fail validation.
+        #
+        # The checker must exit successfully whenever it writes valid result
+        # JSON, including when that result contains type errors. A nonzero exit
+        # fails the type-checking action before Buck2 can convert the result to
+        # validation output.
+        "type_checker": provider_field(RunInfo | None, default = None),
+        "typeshed_stubs": provider_field(ManifestInfo | None, default = None),
+        "emit_omnibus_metadata": provider_field(bool | None, default = None),
+        # The fully qualified name of a function that handles invoking the
+        # executable's entry point
+        "main_runner": provider_field(str, default = "__par__.bootstrap.run_as_main"),
+        # Prefix to use when running a Python test/executable.
+        "run_prefix": provider_field(ArgLike, default = []),
+        "python_error_handler": provider_field(typing.Callable | None, default = None),
+        "lazy_imports_analyzer": provider_field(RunInfo | None, default = None),
+        "manifest_module_entries": provider_field(dict[str, list[str] | dict[str, typing.Any]] | None, default = None),
+        "preload_deps": provider_field(list[Dependency], default = []),
+    },
+)
+
+# Stores "platform"/flavor name used to resolve *platform_* arguments
+PythonPlatformInfo = provider(
+    fields = {
+        "name": provider_field(typing.Any, default = None),
+    }
+)
+
+def get_package_style(ctx: AnalysisContext) -> PackageStyle:
+    if ctx.attrs.package_style != None:
+        return PackageStyle(ctx.attrs.package_style.lower())
+    return PackageStyle(ctx.attrs._python_toolchain[PythonToolchainInfo].package_style)
+
+python = struct(
+    PythonToolchainInfo = PythonToolchainInfo,
+    PythonPlatformInfo = PythonPlatformInfo,
+    PackageStyle = PackageStyle,
+    NativeLinkStrategy = NativeLinkStrategy,
+)
diff --git a/buck2/prelude/python/tools/BUCK b/buck2/prelude/python/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/BUCK
@@ -0,0 +1,186 @@
+load("@prelude//python:internal_tools.bzl", "python_internal_tools")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("plf_experience")
+
+source_listing()
+
+python_internal_tools(
+    name = "python_internal_tools",
+    visibility = ["PUBLIC"],
+)
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "extract",
+    main = "extract.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "create_manifest_for_source_dir",
+    main = "create_manifest_for_source_dir.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "make_source_db",
+    main = "make_source_db.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "make_source_db_no_deps",
+    main = "make_source_db_no_deps.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.export_file(
+    name = "__test_main__.py",
+    src = "__test_main__.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "make_py_package_inplace.py",
+    main = "make_py_package_inplace.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.export_file(
+    name = "run_inplace.py.in",
+    src = "run_inplace.py.in",
+)
+
+prelude.command_alias(
+    name = "make_py_package_inplace",
+    args = [
+        "--template",
+        "$(location :run_inplace.py.in)",
+    ],
+    exe = ":make_py_package_inplace.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "make_py_package_modules",
+    main = "make_py_package_modules.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.export_file(
+    name = "compile.py",
+    src = "compile.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "generate_static_extension_info",
+    main = "generate_static_extension_info.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.export_file(
+    name = "gen_bytecode_bundle.py",
+    src = "gen_bytecode_bundle.py",
+    visibility = ["PUBLIC"],
+)
+
+# Main file used for native python binaries
+prelude.export_file(
+    name = "embedded_main.cpp",
+    src = "embedded_main.cpp",
+    visibility = ["PUBLIC"],
+)
+
+# Custom importer for native linked `cxx_python_extension' targets
+prelude.export_file(
+    name = "static_extension_utils.cpp",
+    src = "static_extension_utils.cpp",
+    visibility = ["PUBLIC"],
+)
+
+prelude.export_file(
+    name = "static_extension_finder.py",
+    src = "static_extension_finder.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "make_py_package_manifest_module",
+    main = "make_py_package_manifest_module.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "fail_with_message",
+    main = "fail_with_message.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "type_check_result_to_validation",
+    main = "type_check_result_to_validation.py",
+    visibility = ["PUBLIC"],
+)
+
+# Shared by every target whose typing is disabled, in place of writing the
+# same empty result per target.
+prelude.export_file(
+    name = "empty_typing_result.json",
+    src = "empty_typing_result.json",
+    mode = "reference",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "wheel",
+    main = "wheel.py",
+    visibility = ["PUBLIC"],
+)
+
+# Run the test suite with this command:
+# buck2 run prelude//python/tools:tool_tests --target-platforms prelude//platforms:default
+prelude.sh_binary(
+    name = "tool_tests",
+    main = "tests/main.sh",
+    resources = [
+        "gen_bytecode_bundle.py",
+        "make_py_package_inplace.py",
+        "make_py_package_manifest_module.py",
+        "run_inplace.py.in",
+        "type_check_result_to_validation.py",
+        "wheel.py",
+    ]
+    + glob(["tests/**/*.py"]),
+)
+
+prelude.export_file(
+    name = "patchelf.py",
+    src = "patchelf.py",
+    mode = "reference",
+)
+
+prelude.command_alias(
+    name = "patchelf",
+    args = [
+        "--patchelf",
+        # @oss-disable[end= ]: "$(exe_target fbsource//third-party/patchelf:patchelf)",
+        "patchelf", # @oss-enable
+    ],
+    exe = ":patchelf.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "create_link_tree",
+    main = "create_link_tree.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "gather_libpython_symbols",
+    main = "gather_libpython_symbols.py",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/python/tools/__test_main__.py b/buck2/prelude/python/tools/__test_main__.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/__test_main__.py
@@ -0,0 +1,802 @@
+#!/usr/bin/env fbpython -tt
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+This file contains the main module code for buck python test programs.
+
+By default, this is the main module for all python_test() rules.  However,
+rules can also specify their own custom main_module.  If you write your own
+main module, you can import this module as tools.test.stubs.fbpyunit, to access
+any of its code to help implement your main module.
+"""
+
+import contextlib
+import ctypes
+import fnmatch
+import json
+import logging
+import optparse
+import os
+import platform
+import re
+import sys
+import time
+import traceback
+import unittest
+from importlib.machinery import PathFinder
+from io import StringIO
+
+try:
+    import coverage  # type: ignore
+except ImportError:
+    coverage = None
+from importlib.machinery import SourceFileLoader
+
+
+EXIT_CODE_SUCCESS = 0
+EXIT_CODE_TEST_FAILURE = 70
+
+
+class TestStatus:
+    ABORTED = "FAILURE"
+    PASSED = "SUCCESS"
+    FAILED = "FAILURE"
+    EXPECTED_FAILURE = "SUCCESS"
+    UNEXPECTED_SUCCESS = "FAILURE"
+    SKIPPED = "ASSUMPTION_VIOLATION"
+    EXCLUDED = "EXCLUDED"
+
+
+class PathMatcher:
+    def __init__(self, include_patterns, omit_patterns):
+        self.include_patterns = include_patterns
+        self.omit_patterns = omit_patterns
+
+    def omit(self, path):
+        """
+        Omit iff matches any of the omit_patterns or the include patterns are
+        not empty and none is matched
+        """
+        path = os.path.realpath(path)
+        return any(fnmatch.fnmatch(path, p) for p in self.omit_patterns) or (
+            self.include_patterns
+            and not any(fnmatch.fnmatch(path, p) for p in self.include_patterns)
+        )
+
+    def include(self, path):
+        return not self.omit(path)
+
+
+class DebugWipeFinder(PathFinder):
+    """
+    PEP 302 finder that uses a DebugWipeLoader for all files which do not need
+    coverage
+    """
+
+    def __init__(self, matcher):
+        self.matcher = matcher
+
+    def find_spec(self, fullname, path=None, target=None):
+        spec = super().find_spec(fullname, path=path, target=target)
+        if spec is None or spec.origin is None:
+            return None
+        if not spec.origin.endswith(".py"):
+            return None
+        if self.matcher.include(spec.origin):
+            return None
+
+        class PyVarObject(ctypes.Structure):
+            _fields_ = [
+                ("ob_refcnt", ctypes.c_long),
+                ("ob_type", ctypes.c_void_p),
+                ("ob_size", ctypes.c_ulong),
+            ]
+
+        class DebugWipeLoader(SourceFileLoader):
+            """
+            PEP302 loader that zeros out debug information before execution
+            """
+
+            def get_code(self, fullname):
+                code = super().get_code(fullname)
+                # This can segfault in 3.12
+                if code and sys.version_info < (3, 12):
+                    # Ideally we'd do
+                    # code.co_lnotab = b''
+                    # But code objects are READONLY. Not to worry though; we'll
+                    # directly modify CPython's object
+                    code_impl = PyVarObject.from_address(id(code.co_lnotab))
+                    code_impl.ob_size = 0
+                return code
+
+        if isinstance(spec.loader, SourceFileLoader):
+            spec.loader = DebugWipeLoader(fullname, spec.origin)
+        return spec
+
+
+def optimize_for_coverage(cov, include_patterns, omit_patterns):
+    """
+    We get better performance if we zero out debug information for files which
+    we're not interested in. Only available in CPython.
+    """
+    matcher = PathMatcher(include_patterns, omit_patterns)
+    if platform.python_implementation() == "CPython":
+        sys.meta_path.insert(0, DebugWipeFinder(matcher))
+
+
+class TeeStream:
+    def __init__(self, *streams):
+        self._streams = streams
+
+    def write(self, data):
+        for stream in self._streams:
+            stream.write(data)
+
+    def flush(self):
+        for stream in self._streams:
+            stream.flush()
+
+    def isatty(self):
+        return False
+
+
+class CallbackStream:
+    def __init__(self, callback, bytes_callback=None, orig=None):
+        self._callback = callback
+        self._fileno = orig.fileno() if orig else None
+
+        # Python 3 APIs:
+        # - `encoding` is a string holding the encoding name
+        # - `errors` is a string holding the error-handling mode for encoding
+        # - `buffer` should look like an io.BufferedIOBase object
+
+        self.errors = orig.errors if orig else None
+        if bytes_callback:
+            # those members are only on the io.TextIOWrapper
+            self.encoding = orig.encoding if orig else "UTF-8"
+            self.buffer = CallbackStream(bytes_callback, orig=orig)
+
+    def write(self, data):
+        self._callback(data)
+
+    def flush(self):
+        pass
+
+    def isatty(self):
+        return False
+
+    def fileno(self):
+        return self._fileno
+
+
+class BuckTestResult(unittest.TextTestResult):
+    """
+    Our own TestResult class that outputs data in a format that can be easily
+    parsed by buck's test runner.
+    """
+
+    def __init__(
+        self, stream, descriptions, verbosity, show_output, main_program, suite
+    ):
+        super(BuckTestResult, self).__init__(stream, descriptions, verbosity)
+        self._main_program = main_program
+        self._suite = suite
+        self._results = []
+        self._current_test = None
+        self._saved_stdout = sys.stdout
+        self._saved_stderr = sys.stderr
+        self._show_output = show_output
+
+    def getResults(self):
+        return self._results
+
+    def startTest(self, test):
+        super(BuckTestResult, self).startTest(test)
+
+        # Pass in the real stdout and stderr filenos.  We can't really do much
+        # here to intercept callers who directly operate on these fileno
+        # objects.
+        sys.stdout = CallbackStream(
+            self.addStdout, self.addStdoutBytes, orig=sys.stdout
+        )
+        sys.stderr = CallbackStream(
+            self.addStderr, self.addStderrBytes, orig=sys.stderr
+        )
+        self._current_test = test
+        self._test_start_time = time.time()
+        self._current_status = TestStatus.ABORTED
+        self._messages = []
+        self._stacktrace = None
+        self._stdout = ""
+        self._stderr = ""
+
+    def _find_next_test(self, suite):
+        """
+        Find the next test that has not been run.
+        """
+
+        for test in suite:
+            # We identify test suites by test that are iterable (as is done in
+            # the builtin python test harness).  If we see one, recurse on it.
+            if hasattr(test, "__iter__"):
+                test = self._find_next_test(test)
+
+            # The builtin python test harness sets test references to `None`
+            # after they have run, so we know we've found the next test up
+            # if it's not `None`.
+            if test is not None:
+                return test
+
+    def stopTest(self, test):
+        sys.stdout = self._saved_stdout
+        sys.stderr = self._saved_stderr
+
+        super(BuckTestResult, self).stopTest(test)
+
+        # If a failure occurred during module/class setup, then this "test" may
+        # actually be a `_ErrorHolder`, which doesn't contain explicit info
+        # about the upcoming test.  Since we really only care about the test
+        # name field (i.e. `_testMethodName`), we use that to detect an actual
+        # test cases, and fall back to looking the test up from the suite
+        # otherwise.
+        if not hasattr(test, "_testMethodName"):
+            potential_test = self._find_next_test(self._suite)
+
+            if potential_test is not None:
+                test = potential_test
+            elif hasattr(test, "id"):
+                # If the next test can't be found, this could be a failure in class teardown. Fallback
+                # to using the id, which will likely be the method name as the test method.
+                test._testMethodName = test.id()
+
+        self._results.append(
+            {
+                "testCaseName": "{0}.{1}".format(
+                    test.__class__.__module__, test.__class__.__name__
+                ),
+                "testCase": test._testMethodName,
+                "type": self._current_status,
+                "time": int((time.time() - self._test_start_time) * 1000),
+                "message": os.linesep.join(self._messages),
+                "stacktrace": self._stacktrace,
+                "stdOut": self._stdout,
+                "stdErr": self._stderr,
+            }
+        )
+
+        self._current_test = None
+
+    def stopTestRun(self):
+        cov = self._main_program.get_coverage()
+        if cov is not None:
+            self._results.append({"coverage": cov})
+
+    @contextlib.contextmanager
+    def _withTest(self, test):
+        self.startTest(test)
+        yield
+        self.stopTest(test)
+
+    def _setStatus(self, test, status, message=None, stacktrace=None):
+        assert test == self._current_test
+        self._current_status = status
+        self._stacktrace = stacktrace
+        if message is not None:
+            if message.endswith(os.linesep):
+                message = message[:-1]
+            self._messages.append(message)
+
+    def setStatus(self, test, status, message=None, stacktrace=None):
+        # addError() may be called outside of a test if one of the shared
+        # fixtures (setUpClass/tearDownClass/setUpModule/tearDownModule)
+        # throws an error.
+        #
+        # In this case, create a fake test result to record the error.
+        if self._current_test is None:
+            with self._withTest(test):
+                self._setStatus(test, status, message, stacktrace)
+        else:
+            self._setStatus(test, status, message, stacktrace)
+
+    def setException(self, test, status, excinfo):
+        exctype, value, tb = excinfo
+        self.setStatus(
+            test,
+            status,
+            "{0}: {1}".format(exctype.__name__, value),
+            "".join(traceback.format_tb(tb)),
+        )
+
+    def addSuccess(self, test):
+        super(BuckTestResult, self).addSuccess(test)
+        self.setStatus(test, TestStatus.PASSED)
+
+    def addError(self, test, err):
+        super(BuckTestResult, self).addError(test, err)
+        self.setException(test, TestStatus.ABORTED, err)
+
+    def addFailure(self, test, err):
+        super(BuckTestResult, self).addFailure(test, err)
+        self.setException(test, TestStatus.FAILED, err)
+
+    def addSkip(self, test, reason):
+        super(BuckTestResult, self).addSkip(test, reason)
+        self.setStatus(test, TestStatus.SKIPPED, "Skipped: %s" % (reason,))
+
+    def addExpectedFailure(self, test, err):
+        super(BuckTestResult, self).addExpectedFailure(test, err)
+        self.setException(test, TestStatus.EXPECTED_FAILURE, err)
+
+    def addUnexpectedSuccess(self, test):
+        super(BuckTestResult, self).addUnexpectedSuccess(test)
+        self.setStatus(test, TestStatus.UNEXPECTED_SUCCESS, "Unexpected success")
+
+    def addStdout(self, val):
+        self._stdout += val
+        if self._show_output:
+            self._saved_stdout.write(val)
+            self._saved_stdout.flush()
+
+    def addStdoutBytes(self, val):
+        string = val.decode("utf-8", errors="backslashreplace")
+        self.addStdout(string)
+
+    def addStderr(self, val):
+        self._stderr += val
+        if self._show_output:
+            self._saved_stderr.write(val)
+            self._saved_stderr.flush()
+
+    def addStderrBytes(self, val):
+        string = val.decode("utf-8", errors="backslashreplace")
+        self.addStderr(string)
+
+
+class BuckTestRunner(unittest.TextTestRunner):
+    def __init__(self, main_program, suite, show_output=True, **kwargs):
+        super(BuckTestRunner, self).__init__(**kwargs)
+        self.show_output = show_output
+        self._main_program = main_program
+        self._suite = suite
+
+    def _makeResult(self):
+        return BuckTestResult(
+            self.stream,
+            self.descriptions,
+            self.verbosity,
+            self.show_output,
+            self._main_program,
+            self._suite,
+        )
+
+
+def _format_test_name(test_class, attrname):
+    """
+    Format the name of the test buck-style.
+    """
+    return "{0}.{1}#{2}".format(test_class.__module__, test_class.__name__, attrname)
+
+
+class StderrLogHandler(logging.StreamHandler):
+    """
+    This class is very similar to logging.StreamHandler, except that it
+    always uses the current sys.stderr object.
+
+    StreamHandler caches the current sys.stderr object when it is constructed.
+    This makes it behave poorly in unit tests, which may replace sys.stderr
+    with a StringIO buffer during tests.  The StreamHandler will continue using
+    the old sys.stderr object instead of the desired StringIO buffer.
+    """
+
+    def __init__(self):
+        logging.Handler.__init__(self)
+
+    @property
+    # pyrefly: ignore [bad-override]
+    def stream(self):
+        return sys.stderr
+
+
+class RegexTestLoader(unittest.TestLoader):
+    def __init__(self, regex=None):
+        self.regex = regex
+        super(RegexTestLoader, self).__init__()
+
+    def getTestCaseNames(self, testCaseClass):
+        """
+        Return a sorted sequence of method names found within testCaseClass
+        """
+
+        testFnNames = super(RegexTestLoader, self).getTestCaseNames(testCaseClass)
+        if self.regex is None:
+            return testFnNames
+        robj = re.compile(self.regex)
+        matched = []
+        for attrname in testFnNames:
+            fullname = _format_test_name(testCaseClass, attrname)
+            if robj.search(fullname):
+                matched.append(attrname)
+        return matched
+
+    def loadTestsFromName(self, name, module=None):
+        """
+        Tries to find and import the module from `name` and discover test cases inside.
+
+        NOTE: this function is used by the unittest framework and our unittest
+        adapters to integrate with buck/tpx.
+        """
+        suite = super().loadTestsFromName(name, module)
+        for test in suite:
+            if isinstance(test, unittest.loader._FailedTest):
+                # _FailedTest means that the test module couldn't be loaded
+                # (usually, because of a bad import). Instead of pretending to
+                # execute a synthetic test case
+                # `unittest.loader._FailedTest(<failed module>)` and reporting
+                # it to the downstream consumers, we should hard fail.
+                # When static listing is used this will let TPX to associate the
+                # failure to either the main test (for bundled execution) or
+                # individual test cases (regular execution) in a test target,
+                # and not to the synthetic _FailedTest case.
+                print(test._exception, file=sys.stderr)
+                sys.exit(1)
+
+        return suite
+
+
+class Loader:
+    def __init__(self, modules, regex=None):
+        self.modules = modules
+        self.regex = regex
+
+    def load_all(self):
+        loader = RegexTestLoader(self.regex)
+        test_suite = unittest.TestSuite()
+        for module_name in self.modules:
+            __import__(module_name, level=0)
+            module = sys.modules[module_name]
+            module_suite = loader.loadTestsFromModule(module)
+            test_suite.addTest(module_suite)
+        return test_suite
+
+    def load_args(self, args):
+        loader = RegexTestLoader(self.regex)
+
+        suites = []
+        for arg in args:
+            suite = loader.loadTestsFromName(arg)
+            # loadTestsFromName() can only process names that refer to
+            # individual test functions or modules.  It can't process package
+            # names.  If there were no module/function matches, check to see if
+            # this looks like a package name.
+            if suite.countTestCases() != 0:
+                suites.append(suite)
+                continue
+
+            # Load all modules whose name is <arg>.<something>
+            prefix = arg + "."
+            for module in self.modules:
+                if module.startswith(prefix):
+                    suite = loader.loadTestsFromName(module)
+                    suites.append(suite)
+
+        return loader.suiteClass(suites)
+
+
+class MainProgram:
+    """
+    This class implements the main program.  It can be subclassed by
+    users who wish to customize some parts of the main program.
+    (Adding additional command line options, customizing test loading, etc.)
+    """
+
+    DEFAULT_VERBOSITY = 2
+
+    def __init__(self, argv):
+        self.init_option_parser()
+        self.parse_options(argv)
+        self.setup_logging()
+
+    def init_option_parser(self):
+        usage = "%prog [options] [TEST] ..."
+        op = optparse.OptionParser(usage=usage, add_help_option=False)
+        self.option_parser = op
+
+        op.add_option(
+            "--hide-output",
+            dest="show_output",
+            action="store_false",
+            default=True,
+            help="Suppress data that tests print to stdout/stderr, and only "
+            "show it if the test fails.",
+        )
+        op.add_option(
+            "-o",
+            "--output",
+            help="Write results to a file in a JSON format to be read by Buck",
+        )
+        op.add_option(
+            "-f",
+            "--failfast",
+            action="store_true",
+            default=False,
+            help="Stop after the first failure",
+        )
+        op.add_option(
+            "-l",
+            "--list-tests",
+            action="store_true",
+            dest="list",
+            default=False,
+            help="List tests and exit",
+        )
+        op.add_option(
+            "-L",
+            "--list-format",
+            dest="list_format",
+            choices=["buck", "python"],
+            default="python",
+            help="List tests format",
+        )
+        op.add_option(
+            "-r",
+            "--regex",
+            default=None,
+            help="Regex to apply to tests, to only run those tests",
+        )
+        op.add_option(
+            "--collect-coverage",
+            action="store_true",
+            default=False,
+            help="Collect test coverage information",
+        )
+        op.add_option(
+            "--coverage-include",
+            default="*",
+            help='File globs to include in converage (split by ",")',
+        )
+        op.add_option(
+            "--coverage-omit",
+            default="",
+            help='File globs to omit from converage (split by ",")',
+        )
+        op.add_option(
+            "--logger",
+            action="append",
+            metavar="<category>=<level>",
+            default=[],
+            help="Configure log levels for specific logger categories",
+        )
+        op.add_option(
+            "-q",
+            "--quiet",
+            action="count",
+            default=0,
+            help="Decrease the verbosity (may be specified multiple times)",
+        )
+        op.add_option(
+            "-v",
+            "--verbosity",
+            action="count",
+            default=self.DEFAULT_VERBOSITY,
+            help="Increase the verbosity (may be specified multiple times)",
+        )
+        op.add_option(
+            "-?", "--help", action="help", help="Show this help message and exit"
+        )
+
+    def parse_options(self, argv):
+        self.options, self.test_args = self.option_parser.parse_args(argv[1:])
+        self.options.verbosity -= self.options.quiet
+
+        if self.options.collect_coverage and coverage is None:
+            self.option_parser.error("coverage module is not available")
+        self.options.coverage_include = self.options.coverage_include.split(",")
+        if self.options.coverage_omit == "":
+            self.options.coverage_omit = []
+        else:
+            self.options.coverage_omit = self.options.coverage_omit.split(",")
+
+    def setup_logging(self):
+        # Configure the root logger to log at INFO level.
+        # This is similar to logging.basicConfig(), but uses our
+        # StderrLogHandler instead of a StreamHandler.
+        fmt = logging.Formatter("%(pathname)s:%(lineno)s: %(message)s")
+        log_handler = StderrLogHandler()
+        log_handler.setFormatter(fmt)
+        root_logger = logging.getLogger()
+        root_logger.addHandler(log_handler)
+        root_logger.setLevel(logging.INFO)
+
+        level_names = {
+            "debug": logging.DEBUG,
+            "info": logging.INFO,
+            "warn": logging.WARNING,
+            "warning": logging.WARNING,
+            "error": logging.ERROR,
+            "critical": logging.CRITICAL,
+            "fatal": logging.FATAL,
+        }
+
+        for value in self.options.logger:
+            parts = value.rsplit("=", 1)
+            if len(parts) != 2:
+                self.option_parser.error(
+                    "--logger argument must be of the form <name>=<level>: %s" % value
+                )
+            name = parts[0]
+            level_name = parts[1].lower()
+            level = level_names.get(level_name)
+            if level is None:
+                self.option_parser.error(
+                    "invalid log level %r for log category %s" % (parts[1], name)
+                )
+            logging.getLogger(name).setLevel(level)
+
+    def create_loader(self):
+        import __test_modules__
+
+        return Loader(__test_modules__.TEST_MODULES, self.options.regex)
+
+    def load_tests(self):
+        loader = self.create_loader()
+        if self.options.collect_coverage:
+            self.start_coverage()
+            include = self.options.coverage_include
+            omit = self.options.coverage_omit
+            if include and "*" not in include:
+                optimize_for_coverage(self.cov, include, omit)
+
+        if self.test_args:
+            suite = loader.load_args(self.test_args)
+        else:
+            suite = loader.load_all()
+        if self.options.collect_coverage:
+            self.cov.start()
+        return suite
+
+    def get_tests(self, test_suite):
+        tests = []
+
+        for test in test_suite:
+            if isinstance(test, unittest.TestSuite):
+                tests.extend(self.get_tests(test))
+            else:
+                tests.append(test)
+
+        return tests
+
+    def run(self):
+        test_suite = self.load_tests()
+
+        if self.options.list:
+            for test in self.get_tests(test_suite):
+                # Python 3.12 changed the implementation of `TestCase.__str__`.
+                # We construct the name manually here to ensure consistency between
+                # Python versions.
+                # Example: "test_basic (tests.test_object.TestAbsent)".
+                method_name = getattr(test, "_testMethodName", "")
+                cls = test.__class__
+                if self.options.list_format == "python":
+                    if method_name:
+                        name = f"{method_name} ({cls.__module__}.{cls.__qualname__})"
+                    else:
+                        name = str(test)
+
+                elif self.options.list_format == "buck":
+                    name = _format_test_name(cls, method_name)
+                else:
+                    raise Exception(
+                        "Bad test list format: %s" % (self.options.list_format,)
+                    )
+
+                print(name)
+            return EXIT_CODE_SUCCESS
+        else:
+            result = self.run_tests(test_suite)
+            if self.options.output is not None:
+                with open(self.options.output, "w") as f:
+                    json.dump(result.getResults(), f, indent=4, sort_keys=True)
+            if not result.wasSuccessful():
+                return EXIT_CODE_TEST_FAILURE
+            return EXIT_CODE_SUCCESS
+
+    def run_tests(self, test_suite):
+        # Install a signal handler to catch Ctrl-C and display the results
+        unittest.installHandler()
+
+        # Run the tests
+        runner = BuckTestRunner(
+            self,
+            test_suite,
+            verbosity=self.options.verbosity,
+            show_output=self.options.show_output,
+        )
+        result = runner.run(test_suite)
+
+        if self.options.collect_coverage and self.options.show_output:
+            self.cov.stop()
+            if self.cov.html_report:
+                self.cov.html_report()
+            else:
+                self.cov.report(file=sys.stdout)
+
+        return result
+
+    def start_coverage(self):
+        if not self.options.collect_coverage:
+            return
+
+        # Keep the original working dir in case tests use os.chdir
+        self._original_working_dir = os.getcwd()
+
+        self.cov = coverage.Coverage(
+            include=self.options.coverage_include, omit=self.options.coverage_omit
+        )
+        self.cov.erase()
+        self.cov.start()
+
+    def get_coverage(self):
+        if not self.options.collect_coverage:
+            return None
+        result = {}
+
+        # Switch back to the original working directory.
+        os.chdir(self._original_working_dir)
+
+        self.cov.stop()
+
+        try:
+            f = StringIO()
+            self.cov.report(file=f)
+            lines = f.getvalue().split("\n")
+        except coverage.misc.CoverageException:
+            # Nothing was covered. That's fine by us
+            return result
+
+        # N.B.: the format of the coverage library's output differs
+        # depending on whether one or more files are in the results
+        for line in lines[2:]:
+            if line.strip("-") == "":
+                break
+            r = line.split()[0]
+            analysis = self.cov.analysis2(r)
+            covString = self.convert_to_diff_cov_str(analysis)
+            if covString:
+                result[r] = covString
+
+        return result
+
+    def convert_to_diff_cov_str(self, analysis):
+        # Info on the format of analysis:
+        # http://nedbatchelder.com/code/coverage/api.html
+        if not analysis:
+            return None
+        numLines = max(
+            analysis[1][-1] if len(analysis[1]) else 0,
+            analysis[2][-1] if len(analysis[2]) else 0,
+            analysis[3][-1] if len(analysis[3]) else 0,
+        )
+        lines = ["N"] * numLines
+        for line in analysis[1]:
+            lines[line - 1] = "C"
+        for line in analysis[2]:
+            lines[line - 1] = "X"
+        for line in analysis[3]:
+            lines[line - 1] = "U"
+        return "".join(lines)
+
+
+def main(argv):
+    return MainProgram(sys.argv).run()
+
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv))
diff --git a/buck2/prelude/python/tools/compile.py b/buck2/prelude/python/tools/compile.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/compile.py
@@ -0,0 +1,192 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Example usage (internal):
+$ cat inputs.manifest
+[["foo.py", "input/foo.py", "//my_rule:foo"]]
+$ buck build //fbcode//python/build/compile:compile --show-full-output
+$ python <fulloutput/__main__.py> --output=out-dir --bytecode-manifest=output.manifest inputs.manifest
+$ find out-dir -type f
+out-dir/foo.pyc
+
+Or (external):
+compile.py --output=out-dir --bytecode-manifest=output.manifest --ignore-errors inputs.manifest
+"""
+
+import argparse
+import errno
+import importlib
+import importlib.util
+import json
+import os
+import re
+import sys
+import traceback
+from functools import partial
+from py_compile import compile, PycInvalidationMode, PyCompileError
+from types import TracebackType
+
+DEFAULT_FORMAT: str = importlib.util.cache_from_source("{pkg}/{name}.py")
+
+
+def get_py_path(module: str) -> str:
+    return module.replace(".", os.sep) + ".py"
+
+
+def get_pyc_path(module: str, fmt: str) -> str:
+    try:
+        package, name = module.rsplit(".", 1)
+    except ValueError:
+        package, name = "", module
+    parts = fmt.split(os.sep)
+    for idx in range(len(parts)):
+        if parts[idx] == "{pkg}":
+            parts[idx] = package.replace(".", os.sep)
+        elif parts[idx].startswith("{name}"):
+            parts[idx] = parts[idx].format(name=name)
+    return os.path.join(*parts)
+
+
+def _mkdirs(dirpath: str) -> None:
+    try:
+        os.makedirs(dirpath)
+    except OSError as e:
+        if e.errno != errno.EEXIST:
+            raise
+
+
+def _stderr_print(msg: str) -> None:
+    print(msg, file=sys.stderr, end="")
+
+
+def _hyperlink(file: str, line: int, text: str) -> str:
+    from urllib.parse import urlencode
+
+    OSC = "\033]"
+    ST = "\033\\"
+    params = urlencode({"project": "fbsource", "paths[0]": file, "lines[0]": line})
+    uri = f"https://www.internalfb.com/intern/nuclide/open/arc/?{params}"
+    return f"{OSC}8;;{uri}{ST}{text}{OSC}8;;{ST}"
+
+
+def pretty_exception(
+    typ: type[BaseException], exc: BaseException, tb: TracebackType, src: str
+) -> None:
+    try:
+        from colorama import Fore, just_fix_windows_console, Style
+
+        just_fix_windows_console()
+
+        trace = traceback.format_exception(typ, exc, tb)
+        line_number = None
+        if isinstance(exc, PyCompileError) and isinstance(exc.exc_value, SyntaxError):
+            line_number = exc.exc_value.lineno
+        if line_number is None:
+            line_number = 1
+        prev_line = ""
+        for line in trace:
+            if line.startswith(
+                "\nDuring handling of the above exception, another exception occurred:"
+            ):
+                # Drop everything beyond the original exception
+                return
+
+            if line.startswith("  File"):
+                prev_line = line
+            else:
+                if prev_line.startswith("  File"):
+                    # Magenta for last listed filename and line number
+                    s = re.sub(
+                        r"\b\d+$",
+                        lambda match: f"{Fore.MAGENTA}{match.group()}{Fore.RESET}",
+                        prev_line,
+                    )
+                    s = re.sub(
+                        r'"(.*?)"',
+                        lambda match: _hyperlink(
+                            src,
+                            line_number,
+                            f'{Fore.MAGENTA}"{match.group(1)}"{Fore.RESET}',
+                        ),
+                        s,
+                    )
+                    _stderr_print(s)
+                    prev_line = ""
+            if line.startswith("    "):
+                line = Fore.CYAN + line + Fore.RESET  # Cyan for code lines
+                _stderr_print(line)
+            elif line.startswith("SyntaxError") or line.startswith("ValueError"):
+                # Bold magenta for exception
+                line = Style.BRIGHT + Fore.MAGENTA + line + Style.RESET_ALL
+                _stderr_print(line)
+    except Exception:
+        # If anything goes wrong, fall back to the default exception printing
+        sys.excepthook = sys.__excepthook__
+        traceback.print_exception(typ, exc, tb)
+
+
+def main(argv: list[str]) -> None:
+    parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
+    parser.add_argument("-o", "--output", required=True)
+    parser.add_argument(
+        "--bytecode-manifest", required=True, type=argparse.FileType("w")
+    )
+    parser.add_argument("-f", "--format", default=DEFAULT_FORMAT)
+    parser.add_argument(
+        "--invalidation-mode",
+        type=str,
+        default=PycInvalidationMode.UNCHECKED_HASH.name,
+        choices=[PycInvalidationMode.UNCHECKED_HASH.name],
+    )
+    parser.add_argument(
+        "--debug",
+        action="store_true",
+        default=False,
+    )
+    parser.add_argument("manifests", nargs="*")
+    args = parser.parse_args(argv[1:])
+    invalidation_mode = PycInvalidationMode.__members__[args.invalidation_mode]
+    bytecode_manifest = []
+
+    _mkdirs(args.output)
+
+    for manifest_path in args.manifests:
+        with open(manifest_path) as mf:
+            manifest = json.load(mf)
+        for dst, src, _ in manifest:
+            # This is going to try to turn a path into a Python module, so
+            # reduce the scope for bugs in get_pyc_path by normalizing first.
+            dst = os.path.normpath(dst)
+            # We only care about python sources.
+            base, ext = os.path.splitext(dst)
+            if ext != ".py":
+                continue
+            module = base.replace(os.sep, ".")
+            dest_pyc = get_pyc_path(module, args.format)
+            pyc = os.path.join(args.output, dest_pyc)
+            _mkdirs(os.path.dirname(pyc))
+            try:
+                compile(
+                    src,
+                    cfile=pyc,
+                    dfile=get_py_path(module),
+                    doraise=True,
+                    invalidation_mode=invalidation_mode,
+                )
+            except PyCompileError:
+                if not args.debug:
+                    sys.excepthook = partial(pretty_exception, src=src)
+                raise
+            bytecode_manifest.append((dest_pyc, pyc, src))
+    json.dump(bytecode_manifest, args.bytecode_manifest, indent=2)
+
+
+sys.exit(main(sys.argv))
diff --git a/buck2/prelude/python/tools/create_link_tree.py b/buck2/prelude/python/tools/create_link_tree.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/create_link_tree.py
@@ -0,0 +1,78 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import json
+import os
+import shutil
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--output", required=True)
+    parser.add_argument(
+        "--link-manifest", dest="link_manifests", action="append", default=[]
+    )
+    parser.add_argument(
+        "--copy-manifest", dest="copy_manifests", action="append", default=[]
+    )
+    args = parser.parse_args()
+
+    os.makedirs(args.output)
+
+    pkgs: set[str] = set()
+    pkgs_with_init: set[str] = set()
+
+    def _add_pkg(pkg: str) -> None:
+        pkgs.add(pkg)
+        parent = os.path.dirname(pkg)
+        if parent:
+            _add_pkg(parent)
+
+    for symlink, manifest in [(True, m) for m in args.link_manifests] + [
+        (False, m) for m in args.copy_manifests
+    ]:
+        with open(manifest, "r") as f:
+            for dst, src, _ in json.load(f):
+                # Record pkgs and the ones w/ `__init__.py` files already.
+                if dst.endswith((".py", ".so")):
+                    pkg = os.path.dirname(dst)
+                    _add_pkg(pkg)
+                    if os.path.basename(dst) == "__init__.py":
+                        pkgs_with_init.add(pkg)
+
+                dst = os.path.join(args.output, dst)
+                os.makedirs(os.path.dirname(dst), exist_ok=True)
+
+                # Create symlink.
+                if symlink:
+                    src = os.path.relpath(src, start=os.path.dirname(dst))
+                    try:
+                        os.symlink(src, dst)
+                    except FileExistsError:
+                        # Only fail is the symlink we're going to create would be
+                        # different.
+                        current_src = os.readlink(dst)
+                        if current_src != src:
+                            raise RuntimeError(
+                                f"conflict for source {dst}: {src} and {current_src}"
+                            )
+                else:
+                    assert not os.path.exists(dst)
+                    shutil.copy2(src, dst, follow_symlinks=False)
+
+    # Create any missing ones.
+    for pkg in pkgs - pkgs_with_init:
+        with open(os.path.join(args.output, pkg, "__init__.py"), "wb") as _:
+            pass
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/python/tools/create_manifest_for_source_dir.py b/buck2/prelude/python/tools/create_manifest_for_source_dir.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/create_manifest_for_source_dir.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import json
+import os
+import re
+import sys
+
+
+def main(argv: list[str]) -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--output", type=argparse.FileType("w"), default=sys.stdout)
+    parser.add_argument("--origin", help="description of source origin")
+    parser.add_argument("--prefix", help="prefix to prepend to destinations")
+    parser.add_argument("--exclude", help="RE pattern to exclude files")
+    parser.add_argument("extracted", help="path to directory of sources")
+    args = parser.parse_args(argv[1:])
+
+    exclude = None
+    if args.exclude:
+        exclude = re.compile(args.exclude)
+
+    entries = []
+    for root, dirs, files in os.walk(args.extracted):
+        # Ensure a consistent iteration order.
+        # Sorting dirs in place affects the future iteration
+        # order of os.walk.
+        dirs.sort()
+        files.sort()
+        for name in files:
+            path = os.path.join(root, name)
+            if exclude is not None and exclude.search(path):
+                continue
+            dest = os.path.relpath(path, args.extracted)
+            if args.prefix is not None:
+                dest = os.path.join(args.prefix, dest)
+            entry = [dest, path]
+            if args.origin is not None:
+                entry.append(args.origin)
+            entries.append(entry)
+
+    json.dump(entries, args.output, indent=2)
+    args.output.close()
+
+
+sys.exit(main(sys.argv))
diff --git a/buck2/prelude/python/tools/discover_python_archives.sh b/buck2/prelude/python/tools/discover_python_archives.sh
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/discover_python_archives.sh
@@ -0,0 +1,83 @@
+#!/bin/bash
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+set -ueo pipefail
+
+version=${1:-3.13}
+release=${2:-}
+REPO="astral-sh/python-build-standalone"
+
+if [ -z "$release" ]; then
+    release=$(gh release -R "$REPO" list --limit 1 | awk '{print $1}')
+fi
+
+URL_PREFIX="https://github.com/$REPO/releases/download/$release"
+
+input=$(gh release -R "$REPO" download "$release" --pattern SHA256SUMS --output -)
+
+
+function get_entry() {
+    local version=$1
+    local arch=$2
+    local platform=$3
+
+    local match_count
+    local pat
+    pat="cpython-$version.*$arch.*$platform.*install_only_stripped.tar.gz"
+    match_count=$(echo "$input" | grep -c "$pat")
+    if [ "$match_count" -eq 0 ]; then
+        echo "No entry found for version $version, arch $arch, platform $platform" >&2
+        exit 1
+    fi
+
+    match=$(echo "$input" | grep "$pat")
+
+    if [[ "$match_count" -gt 1 ]]; then
+        echo "Multiple entries ($match_count) found for version $version, arch $arch, platform $platform:" >&2
+        echo "$match" >&2
+        exit 2
+    fi
+
+    echo "$match"
+}
+
+output="{\n"
+for platform in linux macos windows; do
+    case "$platform" in
+        linux)
+            archive_platform="unknown-linux-gnu"
+            ;;
+        macos)
+            archive_platform="apple-darwin"
+            ;;
+        windows)
+            archive_platform="pc-windows-msvc"
+            ;;
+    esac
+    output+="    \"$platform\": {\n"
+    for arch in arm64 x86_64; do
+        if [ "$platform" = "linux" ] && [ "$arch" = "x86_64" ]; then
+             # lowest arch level by default
+            # change this to x86_64_2 or 3 or 4 if you don't care about compatibility
+            archive_arch="x86_64-"
+        elif [ "$arch" = "arm64" ]; then
+            archive_arch="aarch64"
+        else
+            archive_arch="$arch"
+        fi
+        entry=$(get_entry "$version" "$archive_arch" "$archive_platform")
+        url="$URL_PREFIX/"$(awk '{print $2}' <<< "$entry")
+        sha256=$(awk '{print $1}' <<< "$entry")
+        output+="        \"$arch\": {\"sha256\": \"$sha256\", \"url\": \"$url\"},\n"
+    done
+    output+="    },\n"
+done
+output+="}"
+
+printf "%b\n" "$output"
diff --git a/buck2/prelude/python/tools/embedded_main.cpp b/buck2/prelude/python/tools/embedded_main.cpp
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/embedded_main.cpp
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+#include <Python.h>
+#include <stdlib.h>
+#include <sys/time.h>
+
+#include <functional>
+#include <optional>
+#include <string>
+
+namespace {
+
+std::optional<int> MaybeGetExitCode(PyStatus* status, PyConfig* config) {
+  if (PyStatus_IsExit(*status)) {
+    return status->exitcode;
+  }
+  PyConfig_Clear(config);
+  Py_ExitStatusException(*status);
+}
+
+} // namespace
+
+extern struct _inittab _static_extension_info[];
+PyMODINIT_FUNC PyInit__static_extension_utils();
+
+int main(int argc, char* argv[]) {
+  PyStatus status;
+  PyConfig config;
+
+  PyConfig_InitPythonConfig(&config);
+
+  status = PyConfig_SetBytesString(&config, &config.program_name, argv[0]);
+  if (PyStatus_Exception(status)) {
+    if (auto exit_code = MaybeGetExitCode(&status, &config)) {
+      return *exit_code;
+    }
+  }
+#if PY_VERSION_HEX >= 0x030a0000 // 3.10
+  status = PyConfig_SetBytesArgv(&config, argc, argv);
+#else
+  // Read all configuration at once.
+  status = PyConfig_Read(&config);
+#endif
+  if (PyStatus_Exception(status)) {
+    if (auto exit_code = MaybeGetExitCode(&status, &config)) {
+      return *exit_code;
+    }
+  }
+
+#if PY_VERSION_HEX >= 0x030a0000 // 3.10
+  // Read all configuration at once.
+  status = PyConfig_Read(&config);
+#else
+  status = PyConfig_SetBytesArgv(&config, argc, argv);
+#endif
+  if (PyStatus_Exception(status)) {
+    if (auto exit_code = MaybeGetExitCode(&status, &config)) {
+      return *exit_code;
+    }
+  }
+
+  // Check if we're using par_style="native", if so, modify sys.path to include
+  // the executable-zipfile to it, and set a main module to run when invoked.
+#ifdef NATIVE_PAR_STYLE
+  // Append path to the executable itself to sys.path.
+  status =
+      PyWideStringList_Append(&config.module_search_paths, config.executable);
+  if (PyStatus_Exception(status)) {
+    if (auto exit_code = MaybeGetExitCode(&status, &config)) {
+      return *exit_code;
+    }
+  }
+
+  // Run entry-point module at startup.
+  status =
+      PyConfig_SetBytesString(&config, &config.run_module, "__run_npar_main__");
+  if (PyStatus_Exception(status)) {
+    if (auto exit_code = MaybeGetExitCode(&status, &config)) {
+      return *exit_code;
+    }
+  }
+#endif /* NATIVE_PAR_STYLE */
+
+  // TODO (T129253406) We can do some code generation on build, we will have tho
+  // full library name and the symbol name. FYI the currently we mangle symbol
+  // names to avoid collision so PyInit_bye ->
+  // PyInit_python_efficiency_experimental_linking_tests_bye
+  // One issue with this is how we would resolve foo_bar.baz and foo.bar_baz in
+  // both cases the name would be mangled to PyInit_foo_bar_baz...
+  if (auto exit_code = PyImport_AppendInittab(
+          "_static_extension_utils", PyInit__static_extension_utils);
+      exit_code != 0) {
+    PyErr_Print();
+    fprintf(stderr, "Error: could not update inittab\n");
+    return exit_code;
+  }
+
+  if (std::getenv("FB_NATIVE_PYTHON_DEBUG")) {
+    fprintf(
+        stderr,
+        "Pausing for debugger, pid=%d. Press <return> to continue.\n",
+        (int)getpid());
+    fflush(stderr);
+    getchar();
+  }
+
+  status = Py_InitializeFromConfig(&config);
+  if (PyStatus_Exception(status)) {
+    if (auto exit_code = MaybeGetExitCode(&status, &config)) {
+      return *exit_code;
+    }
+  }
+
+  PyConfig_Clear(&config);
+  return Py_RunMain();
+}
diff --git a/buck2/prelude/python/tools/empty_typing_result.json b/buck2/prelude/python/tools/empty_typing_result.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/empty_typing_result.json
@@ -0,0 +1,1 @@
+{}
diff --git a/buck2/prelude/python/tools/extract.py b/buck2/prelude/python/tools/extract.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/extract.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""Prepare an archive or existing directory for a prebuilt Python library.
+
+Archives are extracted into ``--output``. Existing directories are inspected in
+place, without copying, when ``--output`` is omitted.
+"""
+
+import argparse
+import configparser
+import glob
+import json
+import os
+import shutil
+import stat
+import tarfile
+import tempfile
+import zipfile
+from pathlib import Path
+
+
+def strip_soabi_tag(path: Path) -> Path | None:
+    """
+    Helper to strip any SOABI tag from the given extension path.  Returns `None`
+    if no stripping is performed.
+    """
+
+    suffixes = path.suffixes[-2:]
+
+    # SOABI tagged extensions should have two suffixes.
+    if len(suffixes) != 2:
+        return None
+
+    # Not an extension.
+    ext = ""
+    for ext in (".so", ".pyd"):
+        if suffixes[1] == ext:
+            break
+    else:
+        return None
+
+    # TODO(agallagher): Is there a better way to detect these tags?
+    if not (suffixes[0].startswith(".cpython-") or suffixes[0] == ".abi3"):
+        return None
+
+    return path.with_suffix("").with_suffix(ext)
+
+
+# shutil.unpack_archive calls zipfile.extract which does *not* preserve file attributes
+# (see https://bugs.python.org/issue15795, https://stackoverflow.com/questions/39296101/python-zipfile-removes-execute-permissions-from-binaries).
+#
+# We need to preserve at least the executable bit.
+def extract(src: Path, dst_dir: Path, strip_soabi_tags: bool = False) -> None:
+    if src.suffixes[-2:] == [".tar", ".gz"]:
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            with tarfile.open(src) as tf:
+                tf.extractall(tmp_dir)
+
+            # We expect the tgz to contain a single top-level dir with all the
+            # items to unpack.
+            (path,) = glob.glob(os.path.join(tmp_dir, "*"))
+            for ent in os.listdir(path):
+                fsrc = os.path.join(path, ent)
+                fdst = Path(os.path.join(dst_dir, ent))
+                soabi_less_dst = strip_soabi_tag(fdst)
+                if soabi_less_dst is not None:
+                    fdst = soabi_less_dst
+                shutil.move(fsrc, fdst)
+
+    else:
+        with zipfile.ZipFile(src) as z:
+            for info in z.infolist():
+                outfile = Path(z.extract(info.filename, dst_dir))
+                if strip_soabi_tags:
+                    soabi_less_outfile = strip_soabi_tag(outfile)
+                    if soabi_less_outfile is not None:
+                        os.rename(outfile, soabi_less_outfile)
+                        outfile = soabi_less_outfile
+                execute_perms = (info.external_attr >> 16) & (
+                    stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
+                )
+                if execute_perms:
+                    st = os.stat(outfile)
+                    new_mode = stat.S_IMODE(st.st_mode | execute_perms)
+                    if new_mode != st.st_mode:
+                        os.chmod(outfile, new_mode)
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(
+        description="Prepare an archive or existing source directory for a prebuilt Python library"
+    )
+    parser.add_argument(
+        "--output",
+        type=Path,
+        help="The directory to extract an archive to; omit for an existing directory",
+    )
+    parser.add_argument("--strip-soabi-tags", action="store_true")
+    parser.add_argument("--entry-points", type=Path, help="The directory to write to")
+    parser.add_argument(
+        "--cxx-header-dirs",
+        type=Path,
+        help="A file to write out inferred C++ include dirs to",
+    )
+    parser.add_argument(
+        "--entry-points-manifest", type=Path, help="The directory to write to"
+    )
+    parser.add_argument(
+        "src", type=Path, help="An archive or existing source directory"
+    )
+    args = parser.parse_args()
+
+    if args.src.is_dir():
+        if args.output is not None:
+            parser.error("--output must be omitted when src is a directory")
+        if args.strip_soabi_tags:
+            parser.error(
+                "--strip-soabi-tags cannot mutate an existing source directory"
+            )
+        source_root = args.src
+    else:
+        if args.output is None:
+            parser.error("--output is required when src is an archive")
+        args.output.mkdir(parents=True, exist_ok=True)
+        extract(
+            src=args.src,
+            dst_dir=args.output,
+            strip_soabi_tags=args.strip_soabi_tags,
+        )
+        source_root = args.output
+
+    # Infer C++ header dirs.
+    if args.cxx_header_dirs is not None:
+        with open(args.cxx_header_dirs, mode="w") as f:
+            for root, dirs, _files in os.walk(source_root):
+                root = os.path.relpath(root, source_root)
+                if "include" in dirs:
+                    print(os.path.normpath(os.path.join(root, "include")), file=f)
+
+    # Extract any "entry points" from the wheel, and generate scripts from them
+    # (just like `pip install` would do).
+    if args.entry_points is not None:
+        entry_points = glob.glob(
+            os.path.join(source_root, "*.dist-info", "entry_points.txt")
+        )
+        os.makedirs(args.entry_points, exist_ok=True)
+        manifest = []
+        if entry_points:
+            (entry_points,) = entry_points
+            config = configparser.ConfigParser()
+            config.read(entry_points)
+            if config.has_section("console_scripts"):
+                for name, entry_point in config.items("console_scripts"):
+                    mod, func = entry_point.split(":")
+                    path = os.path.join(args.entry_points, name)
+                    manifest.append(
+                        (name, path, os.path.relpath(entry_points, source_root))
+                    )
+                    with open(path, mode="w") as bf:
+                        bf.write(
+                            """\
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+import re
+import sys
+from {mod} import {func}
+if __name__ == '__main__':
+    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])
+    sys.exit({func}())
+""".format(mod=mod, func=func)
+                        )
+                    os.chmod(path, 0o777)
+        with open(args.entry_points_manifest, mode="w") as f:
+            json.dump(manifest, f)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/python/tools/fail_with_message.py b/buck2/prelude/python/tools/fail_with_message.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/fail_with_message.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import sys
+from pathlib import Path
+
+
+def main() -> None:
+    print(Path(sys.argv[1]).read_text())
+    if len(sys.argv) == 3:
+        Path(sys.argv[2]).touch()
+    sys.exit(1)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/python/tools/gather_libpython_symbols.py b/buck2/prelude/python/tools/gather_libpython_symbols.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/gather_libpython_symbols.py
@@ -0,0 +1,62 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import subprocess
+import sys
+import sysconfig
+from pathlib import Path
+from shutil import which
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--nm", type=Path, help="Path to nm tool")
+    parser.add_argument("output", help="Output file path")
+    args = parser.parse_args()
+
+    nm: Path | None = args.nm
+    if nm is None:
+        maybe_nm = which("nm")
+        if not maybe_nm:
+            raise ValueError("nm tool was not specified and also not available on PATH")
+        nm = Path(maybe_nm)
+    if not nm.exists():
+        raise ValueError(f"nm tool not found at specified location: {nm!r}")
+
+    lib_dir = Path(sysconfig.get_config_var("installed_platbase")) / str(
+        sysconfig.get_config_var("platlibdir")
+    )
+    libpython = lib_dir / str(sysconfig.get_config_var("LDLIBRARY"))
+
+    if not libpython.exists():
+        raise RuntimeError(f"No libpython found in {libpython} ({lib_dir=})")
+
+    # Run nm on the library file
+    nm_output = subprocess.check_output([nm, libpython], text=True)
+
+    # Process the output and write linker args
+    with open(args.output, "w") as f:
+        for line in nm_output.splitlines():
+            # Look for lines containing ' T ' which indicates text (code) symbols
+            if " T " not in line:
+                continue
+            # Get the symbol name (third column)
+            symbol = line.split()[2]
+            # Write linker arguments
+            if sys.platform == "linux":
+                f.write(f"-Wl,--undefined={symbol}\n")
+            else:
+                f.write("-Wl,-U\n")
+                f.write(f"-Wl,{symbol}\n")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/python/tools/gen_bytecode_bundle.py b/buck2/prelude/python/tools/gen_bytecode_bundle.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/gen_bytecode_bundle.py
@@ -0,0 +1,145 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""Pack the `.pyc` files produced by `compile.py` into one blob.
+
+Each `python_library` contributes a bytecode manifest and its matching
+`py_compile` output directory.
+
+Format (little endian):
+
+    header     <8sII: magic, pyc_magic length, index length
+    pyc_magic  importlib.util.MAGIC_NUMBER
+    index      marshalled `{tree relative source path: (payload offset, size)}`
+    payload    concatenated `.pyc` bodies with the 16-byte header stripped
+
+The index is keyed by path, not by module name, because
+`__par__.bytecode_bundle` hangs a `FileFinder` off `sys.path_hooks`: the tree
+decides which file answers an import and the blob only supplies that file's
+bytecode. Keys are `/` separated on every platform.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import marshal
+import os
+import shutil
+import struct
+import sys
+from importlib.util import MAGIC_NUMBER, source_from_cache
+
+MAGIC = b"PYCBNDL4"
+HEADER: struct.Struct = struct.Struct("<8sII")
+PYC_HEADER_LEN = 16
+_UINT32_MAX: int = (1 << 32) - 1
+
+
+def source_key(cache_relpath: str) -> str:
+    """`pkg/__pycache__/mod.cpython-312.pyc` -> `pkg/mod.py`."""
+    return source_from_cache(cache_relpath).replace(os.sep, "/")
+
+
+def collect(
+    manifest_paths: list[str], bytecode_dirs: list[str]
+) -> list[tuple[str, str]]:
+    """Return `(source path, .pyc path)` entries.
+
+    Each manifest is paired with its `bytecode_dir`. The real `.pyc` path is
+    `bytecode_dir/dest`; the manifest's placeholder path is ignored.
+    """
+    if len(manifest_paths) != len(bytecode_dirs):
+        raise ValueError(
+            "Got {} bytecode manifests but {} bytecode directories".format(
+                len(manifest_paths), len(bytecode_dirs)
+            )
+        )
+
+    entries = []
+    for manifest_path, bytecode_dir in zip(manifest_paths, bytecode_dirs):
+        with open(manifest_path) as f:
+            manifest = json.load(f)
+        for dest, _pyc, _source in manifest:
+            dest = os.path.normpath(dest)
+            entries.append((source_key(dest), os.path.join(bytecode_dir, dest)))
+
+    entries.sort(key=lambda entry: entry[0])
+    return entries
+
+
+def build(entries: list[tuple[str, str]], out_path: str) -> None:
+    index: dict[str, tuple[int, int]] = {}
+    selected: list[tuple[str, int]] = []
+    payload_end = 0
+    for source_relpath, pyc_path in entries:
+        if source_relpath in index:
+            # Two libraries own the same path in the tree, which make_par
+            # tolerates for bytecode. Keep the first: `collect` fixed the order.
+            continue
+        with open(pyc_path, "rb") as f:
+            header = f.read(PYC_HEADER_LEN)
+            body_size = os.fstat(f.fileno()).st_size - PYC_HEADER_LEN
+        if len(header) != PYC_HEADER_LEN or body_size <= 0:
+            raise ValueError(f"Truncated .pyc has no bytecode payload: {pyc_path}")
+        if header[: len(MAGIC_NUMBER)] != MAGIC_NUMBER:
+            raise ValueError(f".pyc has the wrong interpreter magic: {pyc_path}")
+        index[source_relpath] = (payload_end, body_size)
+        payload_end += body_size
+        selected.append((pyc_path, body_size))
+
+    # `collect` sorted the entries and dicts keep insertion order, so the
+    # marshalled index is byte-identical across builds.
+    index_bytes = marshal.dumps(index)
+    if len(index_bytes) > _UINT32_MAX:
+        raise ValueError("Bytecode bundle index is too large")
+    with open(out_path, "wb") as f:
+        f.write(HEADER.pack(MAGIC, len(MAGIC_NUMBER), len(index_bytes)))
+        f.write(MAGIC_NUMBER)
+        f.write(index_bytes)
+        for pyc_path, expected_size in selected:
+            start = f.tell()
+            with open(pyc_path, "rb") as pyc:
+                pyc.seek(PYC_HEADER_LEN)
+                shutil.copyfileobj(pyc, f, length=1024 * 1024)
+            if f.tell() - start != expected_size:
+                raise OSError(f".pyc changed while bundling: {pyc_path}")
+
+
+def _read_lines(path: str) -> list[str]:
+    with open(path) as f:
+        return [line.rstrip("\n") for line in f if line.rstrip("\n")]
+
+
+def main(argv: list[str]) -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--output", required=True)
+    parser.add_argument(
+        "--bytecode-manifests-from",
+        required=True,
+        help="file listing py_compile bytecode manifests, one per line",
+    )
+    parser.add_argument(
+        "--bytecode-artifacts-from",
+        required=True,
+        help="file listing py_compile output directories, one per line, in the "
+        "same order as --bytecode-manifests-from",
+    )
+    args = parser.parse_args(argv[1:])
+
+    entries = collect(
+        _read_lines(args.bytecode_manifests_from),
+        _read_lines(args.bytecode_artifacts_from),
+    )
+    build(entries, args.output)
+
+
+if __name__ == "__main__":
+    main(sys.argv)
diff --git a/buck2/prelude/python/tools/generate_static_extension_info.py b/buck2/prelude/python/tools/generate_static_extension_info.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/generate_static_extension_info.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import sys
+
+
+def main(argv: list[str]) -> int:
+    parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
+    parser.add_argument("--output", type=argparse.FileType("w"), default=sys.stdout)
+    parser.add_argument("--extension", action="append", default=[])
+    args = parser.parse_args(argv[1:])
+    out_file = args.output
+
+    externs = []
+    table = [
+        "std::unordered_map<std::string_view, pyinitfunc> _static_extension_info = {",
+    ]
+    i = 0
+    for python_name in args.extension:
+        module_name, pyinit_func = python_name.split(":")
+        # Use of the 'asm' directive allows us to use symbol names that would otherwise be invalid in C
+        # For example foo.bar/baz would be foo.bar$baz which is invalid as a c function name
+        externs.append(f'PyMODINIT_FUNC dummy_name_{i}(void) asm ("{pyinit_func}");')
+        table.append(f'  {{ "{module_name}", dummy_name_{i} }},')
+        i += 1
+    table.append("};")
+
+    out_lines = (
+        [
+            '#include "Python.h"',
+            '#include "import.h"',
+            "#include <unordered_map>",
+            "#include <string_view>",
+            "typedef PyObject* (*pyinitfunc)();",
+        ]
+        + externs
+        + table
+    )
+
+    for line in out_lines:
+        print(line, file=out_file)
+    out_file.close()
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv))
diff --git a/buck2/prelude/python/tools/make_par/BUCK b/buck2/prelude/python/tools/make_par/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_par/BUCK
@@ -0,0 +1,63 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("plf_experience")
+
+prelude = native
+
+source_listing()
+
+prelude.export_file(
+    name = "__run_lpar_main__.py",
+    src = "__run_lpar_main__.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.export_file(
+    name = "sitecustomize.py",
+    src = "sitecustomize.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.export_file(
+    name = "_lpar_bootstrap.sh.template",
+    src = "_lpar_bootstrap.sh.template",
+    visibility = ["PUBLIC"],
+)
+
+prelude.export_file(
+    name = "live_builder.py",
+    src = "live_builder.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_library(
+    name = "live_builder",
+    srcs = [
+        "fbcode//tools/make_par:errors.py",
+        "fbcode//tools/make_par:util.py",
+        "live_builder.py",
+        "par_builder.py",
+    ],
+)
+
+prelude.export_file(
+    name = "par_builder.py",
+    src = "par_builder.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "gen_lpar_bootstrap_bin",
+    main = "gen_lpar_bootstrap.py",
+    deps = [":live_builder"],
+)
+
+prelude.command_alias(
+    name = "gen_lpar_bootstrap",
+    args = [
+        "--template",
+        "$(location :_lpar_bootstrap.sh.template)",
+    ],
+    exe = ":gen_lpar_bootstrap_bin",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/python/tools/make_par/__run_lpar_main__.py b/buck2/prelude/python/tools/make_par/__run_lpar_main__.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_par/__run_lpar_main__.py
@@ -0,0 +1,46 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+def __invoke_main() -> None:
+    import os
+    import sys
+
+    # Remove PYTHONHOME set by the bootstrap script which we use in order to make
+    # sure the bundled runtime uses the correct standard library. We are safe
+    # to remove it once we have initialized the runtime.
+    # leaving it may cause errors if the user code calls a subprocess that
+    # expects to be using the system python distribution eg: buck
+    os.environ.pop("PYTHONHOME", None)
+
+    module = os.getenv("FB_PAR_MAIN_MODULE")
+    main_function = os.getenv("FB_PAR_MAIN_FUNCTION")
+
+    sys.argv[0] = os.getenv("FB_LPAR_INVOKED_NAME", sys.argv[0])
+
+    if os.environ.get("FB_PAR_FIX_OS_ARGV"):
+        # pyre-fixme[21]: Could not find module `__par__.meta_only.process_title`.
+        from __par__.meta_only.process_title import set_os_argv
+
+        set_os_argv(sys.argv)
+
+    del sys.path[0]
+
+    main_runner_module = os.environ["FB_PAR_MAIN_RUNNER_MODULE"]
+    main_runner_function = os.environ["FB_PAR_MAIN_RUNNER_FUNCTION"]
+
+    from importlib import import_module
+
+    mod = import_module(main_runner_module)
+    run_as_main = getattr(mod, main_runner_function)
+    run_as_main(module, main_function)
+
+
+__invoke_main()
diff --git a/buck2/prelude/python/tools/make_par/_lpar_bootstrap.sh.template b/buck2/prelude/python/tools/make_par/_lpar_bootstrap.sh.template
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_par/_lpar_bootstrap.sh.template
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# {argcomplete_hint}
+
+BASE_DIR={base_dir}
+DIR={base_dir}
+
+# Older macOS date versions may not support the %N nanoseconds format.
+if [[ $(uname) == "Darwin" ]]
+then
+    if DATE_OUTPUT=$(/bin/date +%s.%N 2>/dev/null) &&
+        [[ "$DATE_OUTPUT" =~ ^[0-9]+\.[0-9]{{9}}$ ]]
+    then
+        export PAR_LAUNCH_TIMESTAMP=$DATE_OUTPUT
+    else
+        export PAR_LAUNCH_TIMESTAMP=$(/bin/date +%s.000000000)
+    fi
+else
+    export PAR_LAUNCH_TIMESTAMP=$(date +%s.%N)
+fi
+if [ -n "${{{lib_path_env}+SET}}" ]; then
+    export FB_SAVED_{lib_path_env}=${lib_path_env}
+fi
+export {lib_path_env}={ld_library_path}
+if [ -n "${{PYTHONPATH+SET}}" ]; then
+    export FB_SAVED_PYTHONPATH=$PYTHONPATH
+fi
+
+# The following expands to ":PAR_APPEND_PYTHONPATH" when $PAR_APPEND_PYTHONPATH is set
+# This is important: we don't want a trailing colon in $PYTHONPATH.
+export PYTHONPATH=$BASE_DIR${{PAR_APPEND_PYTHONPATH:+:$PAR_APPEND_PYTHONPATH}}
+if [ -n "${{PYTHONHOME+SET}}" ]; then
+    export FB_SAVED_PYTHONHOME=$PYTHONHOME
+fi
+if [ -n "${{{lib_preload_env}+SET}}" ]; then
+    export FB_SAVED_{lib_preload_env}=${lib_preload_env}
+fi
+unset PYTHONHOME
+export FB_PAR_MAIN_MODULE="{main_module}"
+export FB_PAR_MAIN_FUNCTION="{main_function}"
+export FB_PAR_MAIN_RUNNER_MODULE="{main_runner_module}"
+export FB_PAR_MAIN_RUNNER_FUNCTION="{main_runner_function}"
+export FB_PAR_RUNTIME_FILES=$BASE_DIR
+: ${{FB_LPAR_INVOKED_NAME:="$0"}}
+export FB_LPAR_INVOKED_NAME
+# This environment variable is immediately unset on startup but will also appear
+# in e.g. `multiprocessing` workers, and so serves as an audit trail back to
+# the originating PAR (and can be read via e.g. `/proc/<pid>/environ`).
+export PAR_INVOKED_NAME_TAG="$FB_LPAR_INVOKED_NAME"
+{ld_preload}
+{env}
+exec {cmd} "$@"
diff --git a/buck2/prelude/python/tools/make_par/gen_lpar_bootstrap.py b/buck2/prelude/python/tools/make_par/gen_lpar_bootstrap.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_par/gen_lpar_bootstrap.py
@@ -0,0 +1,45 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-ignore-all-errors
+
+import os
+import sys
+
+from live_builder import LiveBuilder
+from util import get_args_parser, get_target_info
+
+
+def main():
+    parser = get_args_parser(fromfile_prefix_chars="@")
+    parser.add_argument("--template")
+    parser.add_argument(
+        "--bootstrap-output",
+        help="write the archive to bootstrap script",
+        required=True,
+    )
+    parser.add_argument("--linktree-suffix", default="#link-tree")
+    args, _ = parser.parse_known_args(sys.argv[1:])
+    args.target = get_target_info(args.target)
+
+    builder = LiveBuilder(
+        options=args, manifest=None, linktree_suffix=args.linktree_suffix
+    )
+    bootstrap_contents = builder._gen_interp_file(args.template)
+    with open(args.bootstrap_output, "w") as f:
+        f.write(bootstrap_contents)
+        os.chmod(f.name, 0o755)
+
+    header_contents = builder._gen_header()
+    with open(args.output, "w") as f:
+        f.write(header_contents)
+        os.chmod(f.name, 0o755)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/python/tools/make_par/live_builder.py b/buck2/prelude/python/tools/make_par/live_builder.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_par/live_builder.py
@@ -0,0 +1,186 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-ignore-all-errors
+
+import os
+import shutil
+
+from par_builder import ParBuilder
+from util import (
+    get_user_main,
+    make_clean_dir,
+    make_ld_library_path,
+    make_ld_preload,
+    RUN_LIVEPAR_MAIN_MODULE,
+    SOURCE_SUFFIX,
+)
+
+
+class LiveBuilder(ParBuilder):
+    def __init__(self, options, manifest, mode=0o755, linktree_suffix="#linktree"):
+        # Default to "default" warnings, as per buck1/buck2.
+        super().__init__(options, manifest, mode)
+        # foo.par -> foo#linktree
+        # foo.bar.par -> foo.bar#linktree
+        if self.python_home:
+            if not os.path.isabs(self.python_home):
+                self.python_home = os.path.join("$DIR", self.python_home)
+            self.runtime_env.append(f"PYTHONHOME={self.python_home}")
+
+        if options.live_link_tree is not None:
+            self.linktree = options.live_link_tree
+        else:
+            self.linktree = options.output.rsplit(".", 1)[0] + linktree_suffix
+        self.copy_files = options.copy_files is True
+
+    def _postbuild(self):
+        pass
+
+    def _gen_contents(self, output_file):
+        manifest = self.manifest
+        with open(
+            os.path.join(
+                os.path.dirname(__file__), RUN_LIVEPAR_MAIN_MODULE + SOURCE_SUFFIX
+            )
+        ) as f:
+            manifest.add_autogen_module(RUN_LIVEPAR_MAIN_MODULE, f.read())
+
+        linktree = self.linktree
+        make_clean_dir(linktree)
+
+        dirs = {linktree}
+        for entry in manifest.entries:
+            dest_path = os.path.join(linktree, entry.dest_path)
+            dest_dir = os.path.dirname(dest_path)
+            if dest_dir not in dirs:
+                os.makedirs(dest_dir)
+                while dest_dir not in dirs:
+                    dirs.add(dest_dir)
+                    dest_dir = os.path.dirname(dest_dir)
+
+            if entry.src_data is None:
+                assert entry.src_path is not None
+                if self.copy_files:
+                    shutil.copyfile(entry.src_path, dest_path)
+                    os.chmod(dest_path, os.stat(entry.src_path).st_mode)
+                else:
+                    # Add a symlink to the source file
+                    if entry.src_path.startswith("/"):
+                        # if src_path is absolute, use it as link_path (no need to calculate relative path).
+                        link_path = entry.src_path
+                    else:
+                        link_path = os.path.relpath(
+                            entry.src_path, os.path.dirname(dest_path)
+                        )
+                    os.symlink(link_path, dest_path)
+            else:
+                # For auto-generated files, write them out as
+                # regular files in the linktree.
+                assert entry.src_path is None
+                with open(dest_path, "w") as handle:
+                    handle.write(entry.src_data)
+
+        header = self._gen_header()
+        output_file.write(bytes(header, "UTF-8"))
+
+        bootstrap_template = os.path.join(
+            os.path.dirname(__file__), "_lpar_bootstrap.sh.template"
+        )
+        with open(linktree + "/_bootstrap.sh", "w") as f:
+            f.write(self._gen_interp_file(bootstrap_template))
+            os.chmod(f.name, self.mode)
+
+    def _gen_header(self):
+        linktreedir = self.linktree.rsplit("/", 1)[-1]
+
+        base_dir = '$(dirname $(readlink -f "$0"))/' + linktreedir
+        absolute_base_dir = os.path.abspath(self.linktree)
+        if absolute_base_dir.startswith("/re_cwd"):
+            # This is a remote execution job, the actual path will be different
+            # when execute locally. Updating the absolute path accordingly.
+            # This change assumes fbsource is always under $HOME, which is generally true for linux.
+            absolute_base_dir = "${HOME}/fbsource/" + self.linktree
+        script = (
+            "#!/bin/bash\n"
+            "# {argcomplete_hint}\n"
+            "# LINKTREEDIR={linktreedir}\n"
+            "\n"
+            'export FB_LPAR_INVOKED_NAME="$0"\n'
+            "# This environment variable is immediately unset on startup but will\n"
+            "# also appear in e.g. `multiprocessing` workers, and so serves as an\n"
+            "# audit trail back to the originating PAR (and can be read via e.g.\n"
+            "# `/proc/<pid>/environ`)\n"
+            'export PAR_INVOKED_NAME_TAG="$0"\n'
+            "# Make live par compatible with the par_builder and export the same environment variable\n"
+            "# See https://fburl.com/workplace/u561pr0v for more details\n"
+            'export FB_XAR_INVOKED_NAME="$0"\n'
+            'if [ -f "{base_dir}/_bootstrap.sh" ]; then\n'
+            '  MAIN_MODULE="{base_dir}/{run_livepar}"\n'
+            '  exec {base_dir}/_bootstrap.sh "${{MAIN_MODULE}}" "$@"\n'
+            "else\n"
+            '  MAIN_MODULE="{absolute_base_dir}/{run_livepar}"\n'
+            '  exec {absolute_base_dir}/_bootstrap.sh "${{MAIN_MODULE}}" "$@"\n'
+            "fi\n"
+        )
+        return script.format(
+            base_dir=base_dir,
+            absolute_base_dir=absolute_base_dir,
+            linktreedir=linktreedir,
+            argcomplete_hint=self.options.argcomplete_hint,
+            run_livepar=RUN_LIVEPAR_MAIN_MODULE + SOURCE_SUFFIX,
+        )
+
+    def _gen_interp_file(self, template, interp=None):
+        options = self.options
+        # We do not use readlink because the generated _bootstrap.sh may be a symlink
+        base_dir = '$(dirname "$0")'
+        ld_library_path = make_ld_library_path(
+            options, options.target.lib_path_env, ["$BASE_DIR"]
+        )
+        main_module, main_function = get_user_main(options, self.manifest)
+        py_cmd = self._get_python_command(base_dir="$BASE_DIR")
+        cmd = interp or py_cmd
+
+        if self.runtime_env:
+            env_list = ["export"]
+            env_list.extend(self.runtime_env)
+            env = " ".join(env_list)
+        else:
+            env = ""
+
+        with open(template, "r") as f:
+            script = f.read()
+
+        lib_preload_env = options.target.lib_preload_env
+        if options.ld_preload:
+            ld_preload_list = make_ld_preload(
+                options.target.lib_preload_env,
+                options.ld_preload,
+                base_dir="$BASE_DIR",
+            )
+            ld_preload = f"export {lib_preload_env}={ld_preload_list}\n"
+        else:
+            ld_preload = ""
+
+        main_runner_module, main_runner_function = options.main_runner.rsplit(".", 1)
+
+        return script.format(
+            base_dir=base_dir,
+            ld_library_path=ld_library_path,
+            ld_preload=ld_preload,
+            argcomplete_hint=options.argcomplete_hint,
+            main_module=main_module,
+            main_function=main_function,
+            main_runner_module=main_runner_module,
+            main_runner_function=main_runner_function,
+            lib_path_env=options.target.lib_path_env,
+            lib_preload_env=lib_preload_env,
+            env=env,
+            cmd=cmd,
+        )
diff --git a/buck2/prelude/python/tools/make_par/par_builder.py b/buck2/prelude/python/tools/make_par/par_builder.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_par/par_builder.py
@@ -0,0 +1,95 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-ignore-all-errors
+
+import os
+import tempfile
+
+
+class ParBuilder:
+    """
+    Abstract class that represents the process of building a .par file
+    """
+
+    def __init__(self, options, manifest, mode=None):
+        self.options = options
+        self.manifest = manifest
+        self.output = options.output
+        self.strict_tabs = options.strict_tabs
+        self.warnings = options.warnings
+        self.mode = mode
+        self.runtime_env = list(options.runtime_env)
+        self.runtime_env.append(
+            "FB_PAR_FIX_OS_ARGV={}".format("1" if options.fix_os_argv else "")
+        )
+        self.interpreter_flags = options.interpreter_flags
+        self.ld_preload = options.ld_preload
+
+        self.python = options.python
+        self.python_home = options.python_home or None
+        self.entry_point = options.runtime_binary or None
+
+    def build(self):
+        self._gen_file()
+        self._postbuild()
+
+    def _gen_file(self):
+        (dirname, basename) = os.path.split(self.output)
+        prefix = basename + ".tmp."
+        with tempfile.TemporaryDirectory(dir=dirname, prefix=prefix) as tempdir:
+            output_filename = os.path.join(tempdir, "output")
+            with open(output_filename, "w+b") as output_file:
+                # Call the function to generate the file contents
+                self._gen_contents(output_file)
+
+            # Rename the temporary output file to the real destination
+            os.rename(output_filename, self.output)
+            if self.mode:
+                os.chmod(self.output, self.mode)
+
+    def _gen_contents(self, output_file):
+        raise NotImplementedError
+
+    def _postbuild(self):
+        raise NotImplementedError
+
+    def _get_python_command(self, shebang=False, interp=None, base_dir=None):
+        if self.entry_point:
+            if not os.path.isabs(self.entry_point) and base_dir:
+                cmd = [f"{base_dir}/{self.entry_point}"]
+            else:
+                cmd = [self.entry_point]
+        elif interp:
+            cmd = [interp]
+        else:
+            if shebang and not os.path.isabs(self.python):
+                # If shebang is true, the command will be used as the #! line in a
+                # script.  Unfortunately, the #! line can only parse at most 2
+                # arguments, so if we need to use env we can't use any other
+                # arguments.  Therefore we ignore strict_tabs in this case.
+                #
+                # We also need to specify an absolute path to env in this case.
+                return "/usr/bin/env " + self.python
+
+            cmd = [self.python]
+            if not os.path.isabs(self.python):
+                cmd.insert(0, "env")
+
+        flags = []
+        if self.strict_tabs:
+            flags.append("tt")
+        if self.warnings is not None:
+            flags.append(f"W{self.warnings}")
+        if flags:
+            cmd.append("-" + "".join(flags))
+
+        if self.interpreter_flags:
+            cmd.extend(self.interpreter_flags)
+
+        return " ".join(cmd)
diff --git a/buck2/prelude/python/tools/make_par/sitecustomize.py b/buck2/prelude/python/tools/make_par/sitecustomize.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_par/sitecustomize.py
@@ -0,0 +1,581 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+import itertools
+import os
+import stat
+import sys
+import threading
+import warnings
+from collections.abc import Callable, MutableMapping
+from importlib.machinery import PathFinder
+from importlib.util import module_from_spec
+
+lock = threading.Lock()
+
+
+def __patch_ctypes(saved_env: dict[str, str]) -> None:
+    from ctypes import util as ctypes_util
+
+    orig_find_library: Callable[[str], str | None] = ctypes_util.find_library
+
+    def _patched_find_library(name: str) -> str | None:
+        if sys.platform == "darwin":
+            from ctypes.macholib.dyld import dyld_find
+
+            env = {**os.environ, **saved_env}
+            for candidate in [
+                f"lib{name}.dylib",
+                f"{name}.dylib",
+                f"{name}.framework/{name}",
+            ]:
+                try:
+                    return dyld_find(candidate, env=env)
+                except ValueError:
+                    continue
+        elif os.name == "posix":
+            from pathlib import Path
+
+            for path in saved_env.get("LD_LIBRARY_PATH", "").split(os.pathsep):
+                if not path:
+                    continue
+                p = Path(path)
+                try:
+                    if not p.exists() or not p.is_dir():
+                        continue
+                    for candidate in [
+                        f"{name}.so",
+                        f"lib{name}.so",
+                        f"{name}.so.[0-9]",
+                        f"lib{name}.so.[0-9]",
+                    ]:
+                        for item in p.glob(candidate):
+                            return str(item)
+                except Exception:
+                    continue
+
+        return orig_find_library(name)
+
+    # the weird lambda is just to satisfy Pyre:
+    # ctypes.util.find_library is declared to have type
+    # `typing.Callable(ctypes_util.find_library)[[Named(name, str)],
+    # Optional[str]]` but is used as type
+    # `typing.Callable(__patch_ctypes._patched_find_library)[[Named(name, str)],
+    # Optional[str]]`
+    ctypes_util.find_library = lambda name: _patched_find_library(name)
+
+
+_PATH_PROPAGATING_FINDER_SENTINEL: str = "_fb_par_path_propagating_finder_installed"
+
+
+def __install_path_propagating_finder() -> None:
+    """Install a meta-path finder that grafts the unpack tree onto package __path__.
+
+    Standalone PARs extract .so files (but not .py / .pyc / .pyo) into the
+    unpack dir at FB_PAR_RUNTIME_FILES / FB_PAR_UNZIP_LOCATION. For ext-bearing
+    packages, __init__.py lives only in the PAR zip while the .so lives only
+    in the unpack dir; zipimport cannot load .so from a zip. This finder
+    appends the matching unpack subdirectory to a parent package's __path__ on
+    first submodule import, so Python's standard PathFinder can resolve the
+    on-disk .so.
+
+    Runs in the parent (via __run_par_main__.py: `import sitecustomize`) AND
+    in spawn / forkserver / subprocess.run children (via __patch_spawn /
+    __patch_subprocess_run, which export PYTHONPATH so the child finds this
+    sitecustomize during Py_Initialize). Idempotent.
+    """
+    if any(getattr(f, _PATH_PROPAGATING_FINDER_SENTINEL, False) for f in sys.meta_path):
+        return
+
+    expanded_par_tree = os.environ.get("FB_PAR_RUNTIME_FILES") or os.environ.get(
+        "FB_PAR_UNZIP_LOCATION"
+    )
+    if not expanded_par_tree or not os.path.isdir(expanded_par_tree):
+        return
+
+    _stat = os.stat
+    _S_ISDIR = stat.S_ISDIR
+    _join = os.path.join
+    _sep = os.sep
+
+    class PathPropagatingFinder:
+        def __init__(self, expanded_par_tree: str) -> None:
+            self.expanded_par_tree = expanded_par_tree
+            self._propagated: set[str] = set()
+
+        def find_spec(self, fullname, path=None, target=None):
+            if "." not in fullname:
+                return None
+            parent_name = fullname.rsplit(".", 1)[0]
+            parent = sys.modules.get(parent_name)
+            if parent is None or not hasattr(parent, "__path__"):
+                return None
+            if parent_name in self._propagated:
+                return None
+            extracted_dir = _join(
+                self.expanded_par_tree, parent_name.replace(".", _sep)
+            )
+            try:
+                st = _stat(extracted_dir)
+            except (OSError, ValueError, TypeError):
+                return None
+            if _S_ISDIR(st.st_mode):
+                parent.__path__.append(extracted_dir)
+                self._propagated.add(parent_name)
+            return None
+
+    finder = PathPropagatingFinder(expanded_par_tree)
+    setattr(finder, _PATH_PROPAGATING_FINDER_SENTINEL, True)
+    sys.meta_path.insert(0, finder)
+
+
+_SITECUSTOMIZE_SUBDIR: str = "__par_sitecustomize_proxy__"
+
+
+def _extract_sitecustomize() -> str | None:
+    """Extract sitecustomize.py from the PAR zip to a subdir of the unpack dir.
+
+    Returns the directory containing the extracted file, or None if not needed.
+    Uses a dedicated subdirectory to prevent unrelated Python processes from
+    picking it up when the unpack dir appears on PYTHONPATH.
+    """
+    import zipimport
+
+    # If sitecustomize wasn't loaded from a zip the child process
+    # can find it the same way the parent did.
+    if not isinstance(__loader__, zipimport.zipimporter):
+        return None
+
+    unpack_dir = os.environ.get("FB_PAR_RUNTIME_FILES") or os.environ.get(
+        "FB_PAR_UNZIP_LOCATION"
+    )
+    par_filename = os.environ.get("FB_PAR_FILENAME") or __loader__.archive
+    if not unpack_dir or not par_filename:
+        return None
+
+    sitecustomize = os.path.basename(__file__)
+    extract_dir = os.path.join(unpack_dir, _SITECUSTOMIZE_SUBDIR)
+    extract_path = os.path.join(extract_dir, sitecustomize)
+    if os.path.exists(extract_path):
+        return extract_dir  # Already extracted
+
+    try:
+        import zipfile
+
+        os.makedirs(extract_dir, exist_ok=True)
+        with zipfile.ZipFile(par_filename) as zf:
+            with zf.open(sitecustomize) as src, open(extract_path, "wb") as dst:
+                dst.write(src.read())
+        return extract_dir
+    except (OSError, KeyError, zipfile.BadZipFile):
+        return None  # Best effort
+
+
+def _runtime_lib_path_var() -> str:
+    return "DYLD_LIBRARY_PATH" if sys.platform == "darwin" else "LD_LIBRARY_PATH"
+
+
+def _par_runtime_lib_dir() -> str | None:
+    """Absolute path to the PAR's runtime/lib dir, or None if unavailable.
+
+    Under NativeLinkStrategy("native"), sys.executable is the native-main ELF,
+    whose $ORIGIN-relative RPATH only resolves to runtime/lib when the ELF is
+    materialized adjacent to the link-tree. When it is materialized elsewhere
+    (e.g. the content-addressed anon-target outputs produced under
+    python.use_anon_target_for_analysis), $ORIGIN realpath-resolves into an
+    unrelated tree and the bundled .so's cannot be found. FB_PAR_RUNTIME_FILES
+    points at the link-tree root at runtime, so runtime/lib is reconstructable
+    here regardless of where the ELF itself lives.
+    """
+    runtime_files = os.environ.get("FB_PAR_RUNTIME_FILES")
+    if not runtime_files:
+        return None
+    lib_dir = os.path.join(runtime_files, "runtime", "lib")
+    return lib_dir if os.path.isdir(lib_dir) else None
+
+
+def _inject_runtime_lib_path(env: MutableMapping[str, str], lib_path_var: str) -> None:
+    """Prepend the PAR's runtime/lib to `lib_path_var` in `env`, if resolvable.
+
+    A bare self-re-exec of sys.executable cannot rely on the parent's scrubbed
+    lib-path env, so reconstruct it from FB_PAR_RUNTIME_FILES. Any existing
+    value is preserved by appending after ours.
+    """
+    lib_dir = _par_runtime_lib_dir()
+    if lib_dir is None:
+        return
+    existing = env.get(lib_path_var)
+    if not existing:
+        env[lib_path_var] = lib_dir
+        return
+    # Dedup against canonicalized entries, so the same directory reached via a
+    # symlink, redundant separators, or a relative spelling is not prepended a
+    # second time and does not accumulate across chained re-execs.
+    lib_real = os.path.realpath(lib_dir)
+    for entry in existing.split(os.pathsep):
+        if entry == lib_dir or os.path.realpath(entry) == lib_real:
+            return
+    env[lib_path_var] = lib_dir + os.pathsep + existing
+
+
+def __patch_spawn(var_names: list[str], saved_env: dict[str, str]) -> None:
+    # Compute resolved PYTHONPATH once at patch time (not per-spawn).
+    # dirs_only=True filters out zip files to avoid RecursionError from
+    # zipimport's lazy `import struct` cycle.
+    resolved_pythonpath = os.path.pathsep.join(
+        _resolve_path_entries(sys.path, dirs_only=True)
+    )
+
+    # pyre-fixme[53]: Captured variable is not annotated.
+    def _setup_child_env() -> None:
+        proxy_dir = _extract_sitecustomize()
+        for var in var_names:
+            val = os.environ.get(var, None)
+            if val is not None:
+                os.environ["FB_SAVED_" + var] = val
+            saved_val = saved_env.get(var, None)
+            if saved_val is not None:
+                os.environ[var] = saved_val
+
+        # Ensure PYTHONPATH includes resolved sys.path dirs so the
+        # child interpreter finds sitecustomize.py during Py_Initialize.
+        # The extraction dir (if any) is prepended so the child finds
+        # the extracted sitecustomize.py first.
+        parts = []
+        if proxy_dir:
+            parts.append(proxy_dir)
+        existing = os.environ.get("PYTHONPATH", "")
+        if existing:
+            parts.append(existing)
+        parts.append(resolved_pythonpath)
+        os.environ["PYTHONPATH"] = os.path.pathsep.join(parts)
+
+        # Reconstruct the lib path for native-strategy self-re-exec: the
+        # saved_env restore above is empty when the C++ RestoreEnv scrubbed the
+        # bootstrap LD_LIBRARY_PATH before Python captured it. __clear_env in the
+        # finally clause pops this back out after the child is spawned.
+        _inject_runtime_lib_path(os.environ, _runtime_lib_path_var())
+
+    if sys.platform == "win32":
+        import multiprocessing.popen_spawn_win32 as popen_win32
+
+        orig_init = popen_win32.Popen.__init__
+
+        def _patched_init(self, process_obj) -> None:
+            with lock:
+                try:
+                    _setup_child_env()
+                    orig_init(self, process_obj)
+                finally:
+                    __clear_env(apply_monkeypatching=False)
+
+        popen_win32.Popen.__init__ = _patched_init
+    else:
+        import multiprocessing.util as mp_util
+
+        std_spawn = mp_util.spawnv_passfds
+
+        # pyre-fixme[53]: Captured variable is not annotated.
+        # pyre-fixme[2]: Parameter must be annotated.
+        def spawnv_passfds(path, args, passfds) -> None | int:
+            with lock:
+                try:
+                    _setup_child_env()
+                    return std_spawn(path, args, passfds)
+                finally:
+                    __clear_env(apply_monkeypatching=False)
+
+        mp_util.spawnv_passfds = spawnv_passfds
+
+
+def _resolve_path_entries(path: list[str], dirs_only: bool = False) -> list[str]:
+    resolved = []
+    for entry in path:
+        if entry.startswith("/proc/self/fd/"):
+            try:
+                entry = os.readlink(entry)
+            except OSError:
+                pass
+        elif entry.startswith("/dev/fd/"):
+            # On macOS, /dev/fd/N is not a symlink (it has dup() semantics),
+            # so os.readlink doesn't work.  Resolve to the original PAR path
+            # via the FB_PAR_FILENAME environment variable.
+            par_filename = os.environ.get("FB_PAR_FILENAME", "")
+            if par_filename:
+                entry = par_filename
+        if not dirs_only or os.path.isdir(entry):
+            resolved.append(entry)
+    return resolved
+
+
+def __patch_spawn_preparation_data() -> None:
+    # Only needed for fastzip PARs, which use /proc/self/fd/<N> (Linux) or
+    # /dev/fd/<N> (macOS) paths in sys.path. Other PAR styles (e.g. xar) use
+    # real filesystem paths and don't need this patch.
+    #
+    # We must also avoid importing multiprocessing.spawn during sitecustomize
+    # for xar PARs: importing it captures sys.executable in a module-level
+    # _python_exe variable (via set_executable(sys.executable)), but xar PARs
+    # fix up sys.executable later in __run_xar_main__.py. Importing too early
+    # would cause multiprocessing to spawn subprocesses (e.g. the resource
+    # tracker) with the wrong executable, crashing them.
+    if not any(entry.startswith(("/proc/self/fd/", "/dev/fd/")) for entry in sys.path):
+        return
+
+    import multiprocessing.spawn as mp_spawn
+
+    orig_get_preparation_data = mp_spawn.get_preparation_data
+
+    def get_preparation_data(name):  # type: ignore
+        d = orig_get_preparation_data(name)
+        if "sys_path" in d:
+            d["sys_path"] = _resolve_path_entries(d["sys_path"])
+        return d
+
+    mp_spawn.get_preparation_data = get_preparation_data
+
+
+def __patch_subprocess_run(saved_env: dict[str, str]) -> None:
+    import subprocess
+    from functools import wraps
+
+    std_run = subprocess.run
+
+    if sys.platform == "darwin":
+        _lib_path_vars = ("DYLD_LIBRARY_PATH", "DYLD_INSERT_LIBRARIES")
+    else:
+        _lib_path_vars = ("LD_LIBRARY_PATH", "LD_PRELOAD")
+
+    @wraps(std_run)
+    # pyre-fixme[2]: Parameter must be annotated.
+    # pyre-fixme[53]: Captured variable `std_run` is not annotated.
+    def _patched_run(args, env=None, **kwargs) -> subprocess.CompletedProcess[str]:
+        if (
+            args
+            and isinstance(args, (list, tuple))
+            # We use is for a few reasons:
+            # 1) It's super conservative, you must literally be passing sys.executable
+            # 2) We don't need to worry about checking the type if you're passing a path
+            and args[0] is sys.executable
+            and (env is None or "PYTHONPATH" not in env)
+            and (env is None or "PYTHONHOME" not in env)
+        ):
+            # make subprocess.run work with par files when invoking sys.executable
+            if env is None:
+                env = os.environ.copy()
+            # Resolve /proc/self/fd/<N> paths (used by fastzip PARs) to real
+            # filesystem paths so the child process can find modules (including
+            # sitecustomize.py which clears PYTHONHOME).
+            # dirs_only=True filters out .par zip files from PYTHONPATH to
+            # avoid RecursionError during early Python init (zipimport's
+            # _read_directory triggers a lazy `import struct` cycle).
+            resolved = _resolve_path_entries(sys.path, dirs_only=True)
+            # Extract sitecustomize.py from the PAR zip to a namespaced
+            # subdir so the child interpreter can find it via PYTHONPATH.
+            proxy_dir = _extract_sitecustomize()
+            parts = []
+            if proxy_dir:
+                parts.append(proxy_dir)
+            parts.extend(resolved)
+            env["PYTHONPATH"] = os.path.pathsep.join(parts)
+            # Only set PYTHONHOME if the child will find sitecustomize.py
+            # (which clears it). Otherwise PYTHONHOME leaks and the child
+            # uses the PAR's prefix for stdlib, causing hangs.
+            if proxy_dir is not None or any(
+                os.path.isfile(os.path.join(d, "sitecustomize.py")) for d in resolved
+            ):
+                env["PYTHONHOME"] = sys.prefix
+            # Restore library path env vars so the child process can find
+            # bundled native libraries (e.g. libpython, libX11).
+            for var in _lib_path_vars:
+                if var not in env and var in saved_env:
+                    env[var] = saved_env[var]
+            # saved_env is empty when the bootstrap lib path was scrubbed before
+            # Python captured it, so also reconstruct runtime/lib directly. This
+            # is what lets a native-strategy sys.executable child load its
+            # bundled .so's when $ORIGIN doesn't resolve to the link-tree.
+            _inject_runtime_lib_path(env, _runtime_lib_path_var())
+
+        return std_run(args, env=env, **kwargs)
+
+    subprocess.run = _patched_run
+
+
+def __patch_resource_tracker_fork() -> None:
+    """
+    Fix deadlock between multiprocessing resource tracker and forked children.
+
+    SEV: S630420
+    Upstream Python issue: https://github.com/python/cpython/issues/88887
+
+    Problem: Python 3.12 added ResourceTracker.__del__ which calls waitpid() on
+    the tracker subprocess during shutdown. The tracker subprocess exits when it
+    sees EOF on its pipe. However, if a child process was forked (e.g., by
+    jetter's get_temp_dir), it inherits the tracker's pipe FD. The parent's
+    close() doesn't produce EOF because the child still holds the FD open.
+    Result: waitpid() blocks forever → DEADLOCK.
+
+    Fix: Register an after_in_child callback that closes the inherited tracker
+    pipe FD and resets tracker state. This ensures:
+    1. The child doesn't keep the tracker pipe alive
+    2. If the child later uses multiprocessing, it starts a fresh tracker
+    """
+    # only relevant for Linux
+    if sys.platform != "linux":
+        return
+
+    def _reset_tracker_in_child() -> None:
+        # Check sys.modules instead of importing to avoid pulling in
+        # multiprocessing for processes that never use it
+        rt_mod = sys.modules.get("multiprocessing.resource_tracker")
+        if rt_mod is None:
+            return
+        tracker = getattr(rt_mod, "_resource_tracker", None)
+        if tracker is None:
+            return
+        fd = getattr(tracker, "_fd", None)
+        if fd is not None:
+            # Reset state before closing to avoid TOCTOU race where another
+            # thread could see the stale _fd between close() and reset
+            tracker._fd = None
+            tracker._pid = None
+            try:
+                os.close(fd)
+            except OSError:
+                pass
+
+    os.register_at_fork(after_in_child=_reset_tracker_in_child)
+
+
+def __add_win_dll_directories() -> None:
+    """
+    Windows requires explicit os.add_dll_directory() calls for Python
+    extension modules to find their DLL dependencies.
+    """
+    if sys.platform != "win32":
+        return
+    dll_dirs = os.environ.get("FB_PAR_WIN_DLL_DIRS", "")
+    if not dll_dirs:
+        return
+    for d in dll_dirs.split(os.pathsep):
+        if d and os.path.isdir(d):
+            try:
+                os.add_dll_directory(d)
+            except OSError:
+                pass
+
+
+def __clear_env(
+    apply_monkeypatching: bool = True,
+) -> None:
+    saved_env = {}
+
+    var_names = [
+        "PYTHONPATH",
+        "PYTHONHOME",
+        # We use this env var to tag the process and it's `multiprocessing`
+        # workers.  It's important that we clear it out (so that unrelated sub-
+        # processes don't inherit it), but it can be read via
+        # `/proc/<pid>/environ`.
+        "PAR_INVOKED_NAME_TAG",
+        # PYTHON_GIL=0 is set by the PAR bootstrap for free-threading builds
+        # to force-disable the GIL.  The interpreter reads it once during
+        # Py_Initialize and stores the result in config->enable_gil, so the
+        # env var is not needed after startup.  Clearing it prevents leakage
+        # to child processes that may use non-free-threading Python builds,
+        # which would crash with "Disabling the GIL is not supported".
+        "PYTHON_GIL",
+    ]
+
+    if sys.platform == "darwin":
+        var_names.extend(
+            [
+                "DYLD_LIBRARY_PATH",
+                "DYLD_INSERT_LIBRARIES",
+            ]
+        )
+    else:
+        var_names.extend(
+            [
+                "LD_LIBRARY_PATH",
+                "LD_PRELOAD",
+            ]
+        )
+
+    # Restore the original value of environment variables that we altered
+    # as part of the startup process.
+    for var in var_names:
+        curr_val = os.environ.pop(var, None)
+        if curr_val is not None:
+            saved_env[var] = curr_val
+        val = os.environ.pop("FB_SAVED_" + var, None)
+        if val is not None:
+            os.environ[var] = val
+
+    if apply_monkeypatching:
+        __add_win_dll_directories()
+        __patch_spawn(var_names, saved_env)
+        __patch_spawn_preparation_data()
+        __patch_ctypes(saved_env)
+        __patch_subprocess_run(saved_env)
+        __patch_resource_tracker_fork()
+
+
+def __startup__() -> None:
+    try:
+        # pyre-fixme[21]: Could not find module `__par__.__startup_function_loader__`.
+        from __par__.__startup_function_loader__ import load_startup_functions
+    except ImportError:
+        par = os.environ.get("FB_PAR_FILENAME", "")
+        if par and os.path.isfile(par) and par not in sys.path:
+            sys.path.insert(0, par)
+            # pex requires bootstrap dir to be in the path
+            bootstrap = os.environ.get("FB_PAR_BOOTSTRAP_DIR", "")
+            if bootstrap and bootstrap not in sys.path:
+                sys.path.append(bootstrap)
+            try:
+                from __par__.__startup_function_loader__ import load_startup_functions
+            except ImportError:
+                warnings.warn("could not load startup functions", stacklevel=1)
+                return
+        else:
+            warnings.warn("could not load startup functions", stacklevel=1)
+            return
+    except Exception:
+        warnings.warn("could not load startup functions", stacklevel=1)
+        return
+
+    try:
+        load_startup_functions()
+    except Exception:
+        warnings.warn("could not load startup functions", stacklevel=1)
+
+
+def __passthrough_exec_module() -> None:
+    # Delegate this module execution to the next module in the path, if any,
+    # effectively making this sitecustomize.py a passthrough module.
+    paths = itertools.dropwhile(lambda p: not __file__.startswith(p), sys.path)
+    spec = PathFinder.find_spec(
+        __name__, path=[p for p in paths if not __file__.startswith(p)]
+    )
+    if spec:
+        mod = module_from_spec(spec)
+        sys.modules[__name__] = mod
+        # pyre-fixme[16]: Optional type has no attribute `exec_module`.
+        spec.loader.exec_module(mod)
+
+
+__install_path_propagating_finder()
+__clear_env()
+__startup__()
+__passthrough_exec_module()
diff --git a/buck2/prelude/python/tools/make_py_package_inplace.py b/buck2/prelude/python/tools/make_py_package_inplace.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_py_package_inplace.py
@@ -0,0 +1,270 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Create a bootstrapper pex for inplace python binaries
+
+This script:
+    - Writes out a bootstrapper pex script that knows where this symlink tree is,
+      and uses it, along with the provided entry point to run the python script.
+      It does this by replacing a few special strings like <MODULES_DIR> and
+      <MAIN_MODULE>
+
+A full usage might be something like this:
+
+$ cat template.in
+(see prelude/python/run_inplace.py.in)
+$ ./make_py_package_inplace.py  \\
+    --template prelude/python/run_inplace.py.in \\
+    # These two args create the hashbang for the bootstrapper script \\
+    --python="/usr/bin/python3" \\
+    --python-interpreter-flags="-Xgil=0" \\
+    # This is based on the path in dests. This is the module that gets executed \\
+    # to start program execution \\
+    --entry-point=lib.foo  \\
+    --output=bin.pex \\
+    # This is the symlink tree \\
+    --modules-dir=bin__link-tree
+$ ./bin.pex
+...
+"""
+
+import argparse
+import os
+import platform
+import stat
+from pathlib import Path
+
+# Substituted for `<PYTHON>` in the template, i.e. it is what follows the `#!`.
+#
+# A shell/Python polyglot: `/bin/sh` runs the lines between `"true" '''` and the
+# closing `'''`, while Python parses the same text as two implicitly concatenated
+# string literals and keeps it as the module docstring. Windows has no `#!` support
+# and invokes the bootstrapper as `python <pex>`, where it is likewise inert.
+#
+# `<REL_PYTHON>` is the interpreter's path relative to the bootstrapper.
+_SH_TRAMPOLINE = r"""/bin/sh
+"true" '''\'
+# Resolve this script, following symlinks, so the interpreter can be found next to it.
+_self=$0
+case $_self in */*) ;; *) _self=./$_self ;; esac
+_hops=0
+while [ -L "$_self" ] && [ "$_hops" -lt 32 ]; do
+    # `readlink` is not a shell builtin and `$PATH` may be scrubbed. Without it the
+    # best we can do is assume the symlink sits alongside the interpreter.
+    _link=$(readlink "$_self" 2>/dev/null) || break
+    [ -n "$_link" ] || break
+    case $_link in
+        /*) _self=$_link ;;
+        *) _self=${_self%/*}/$_link ;;
+    esac
+    _hops=$((_hops + 1))
+done
+exec "${_self%/*}/<REL_PYTHON>" "$0" "$@"
+'''"""
+
+
+def parse_args() -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description=(
+            "Create a python inplace binary, writing a symlink tree to a directory, "
+            "and a bootstrapper pex file to file"
+        ),
+        fromfile_prefix_chars="@",
+    )
+    parser.add_argument(
+        "--template",
+        required=True,
+        type=Path,
+        help="The template file for the .pex bootstrapper script",
+    )
+    parser.add_argument(
+        "--preload",
+        type=Path,
+        dest="preload_libraries",
+        action="append",
+        default=[],
+        help="A list of native libraries to add to LD_PRELOAD",
+    )
+    parser.add_argument(
+        "--python",
+        required=True,
+        help=(
+            "The python binary to launch the bootstrapper with. An absolute path or a"
+            " bare name goes straight into the hashbang; a project-root-relative path"
+            " is resolved at runtime against the bootstrapper, see launcher()"
+        ),
+    )
+    parser.add_argument(
+        "--host-python",
+        required=True,
+        help="The host python binary to use to e.g. compiling bytecode",
+    )
+    entry_point = parser.add_mutually_exclusive_group(required=True)
+    entry_point.add_argument(
+        "--entry-point",
+        help="The main module to execute. Mutually exclusive with --main-function.",
+    )
+    entry_point.add_argument(
+        "--main-function",
+        help=(
+            "Fully qualified name of the function that serves as the entry point."
+            " Mutually exclusive with --entry-point."
+        ),
+    )
+    parser.add_argument(
+        "--main-runner",
+        help=(
+            "Fully qualified name of a function that handles invoking the"
+            " executable's entry point."
+        ),
+        required=True,
+    )
+    parser.add_argument(
+        "--modules-dir",
+        required=True,
+        type=Path,
+        help="The link tree directory to use at runtime",
+    )
+    parser.add_argument(
+        "output",
+        type=Path,
+        help="Where to write the bootstrapper script to",
+    )
+    parser.add_argument(
+        "--native-libs-env-var",
+        default=(
+            "DYLD_LIBRARY_PATH" if platform.system() == "Darwin" else "LD_LIBRARY_PATH"
+        ),
+        help="The dynamic loader env used to find native library deps",
+    )
+    parser.add_argument(
+        "--native-library-runtime-path",
+        dest="native_library_runtime_paths",
+        default=[],
+        action="append",
+        help="The dynamic loader env used to find native library deps",
+    )
+    parser.add_argument(
+        "-e",
+        "--runtime_env",
+        action="append",
+        default=[],
+        help="environment variables to set before launching the runtime. (e.g. -e FOO=BAR BAZ=QUX)",
+    )
+    parser.add_argument(
+        "--python-interpreter-flags",
+        action="append",
+        default=[],
+        help="additional flags to pass to the Python interpreter (e.g. -Xgil=0)",
+    )
+    # Compatibility with existing make_par scripts
+    parser.add_argument("--passthrough", action="append", default=[])
+    # No-op, added for compatibility with existing make_par scripts
+    parser.add_argument(
+        "--omnibus-debug-info", choices=["separate", "strip", "extract"]
+    )
+
+    return parser.parse_args()
+
+
+def launcher(python: str, output_dir: Path) -> str:
+    """Build the body of the bootstrapper's `#!` line, i.e. how to start `python`.
+
+    The result must not depend on where the project root happens to sit on this
+    machine. The action's command line doesn't, so neither does its cache key, and an
+    output holding a local absolute path would poison the cache for every other reader.
+    """
+
+    separators = (os.path.sep, os.path.altsep)
+    if os.path.isabs(python) or not any(sep and sep in python for sep in separators):
+        # An absolute path is machine-independent already, and a bare word is for
+        # `/usr/bin/env` to look up on `$PATH`. Both work directly in a `#!` line.
+        #
+        # TODO(nmj): Remove this hack. So, if arg0 in your shebang is a bash script
+        #                 (like /usr/local/fbcode/platform007/bin/python3.7 on macs is)
+        #                 OSX just sort of ignores it and tries to run your thing with
+        #                 the current shell. So, we hack in /usr/bin/env in the front
+        #                 for now, and let it do the lifting. OSX: Bringing you the best
+        #                 of 1980s BSD in 2021...
+        return f"/usr/bin/env {python}"
+
+    # The interpreter is a build artifact, so buck2 handed us a path relative to the
+    # project root. A `#!` line can't carry one, because the kernel resolves it against
+    # the caller's cwd, so defer to a shell that resolves it against the bootstrapper.
+    relative_python = os.path.relpath(python, output_dir)
+    return _SH_TRAMPOLINE.replace(
+        "<REL_PYTHON>", relative_python.replace(os.path.sep, "/")
+    )
+
+
+def write_bootstrapper(args: argparse.Namespace) -> None:
+    """Write the .pex bootstrapper script using a template"""
+
+    with open(args.template, "r", encoding="utf8") as fin:
+        data = fin.read()
+
+    # Because this can be invoked from other directories, find the relative path
+    # from this .par to the modules dir, and use that.
+    relative_modules_dir = os.path.relpath(args.modules_dir, args.output.parent)
+    native_lib_dirs = [relative_modules_dir] + args.native_library_runtime_paths
+
+    ld_preload = None
+    if args.preload_libraries:
+        ld_preload = [p.name for p in args.preload_libraries]
+
+    new_data = data.replace("<PYTHON>", launcher(str(args.python), args.output.parent))
+    # Interpreter flags go to the Python variable that the re-exec path reads (e.g.
+    # -Xgil=0 for free-threaded builds) rather than onto the `#!` line, which on Linux
+    # can carry at most one argument.
+    new_data = new_data.replace(
+        "<PYTHON_INTERPRETER_FLAGS>", " ".join(args.python_interpreter_flags or [])
+    )
+
+    new_data = new_data.replace("<MODULES_DIR>", str(relative_modules_dir))
+    main_module = args.entry_point
+    main_function = ""
+    if args.main_function:
+        main_module, main_function = args.main_function.rsplit(".", 1)
+    new_data = new_data.replace("<MAIN_MODULE>", main_module)
+    new_data = new_data.replace("<MAIN_FUNCTION>", main_function)
+
+    main_runner_module, main_runner_function = args.main_runner.rsplit(".", 1)
+    new_data = new_data.replace("<MAIN_RUNNER_MODULE>", main_runner_module)
+    new_data = new_data.replace("<MAIN_RUNNER_FUNCTION>", main_runner_function)
+
+    # Things that are only required for the full template
+    new_data = new_data.replace("<NATIVE_LIBS_ENV_VAR>", args.native_libs_env_var)
+    new_data = new_data.replace("<NATIVE_LIBS_DIRS>", repr(native_lib_dirs))
+    new_data = new_data.replace("<NATIVE_LIBS_PRELOAD_ENV_VAR>", "LD_PRELOAD")
+    new_data = new_data.replace("<NATIVE_LIBS_PRELOAD>", repr(ld_preload))
+
+    if args.runtime_env:
+        runtime_env = dict(e.split("=", maxsplit=1) for e in args.runtime_env)
+        env = f"os.environ.update({runtime_env!r})"
+    else:
+        env = ""
+    new_data = new_data.replace("<ENV>", env)
+
+    args.output.parent.mkdir(parents=True, exist_ok=True)
+    with open(args.output, "w", encoding="utf8") as fout:
+        fout.write(new_data)
+    mode = os.stat(args.output).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
+    os.chmod(args.output, mode)
+
+
+def main() -> None:
+    args = parse_args()
+    write_bootstrapper(args)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/python/tools/make_py_package_manifest_module.py b/buck2/prelude/python/tools/make_py_package_manifest_module.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_py_package_manifest_module.py
@@ -0,0 +1,124 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Generate a __manifest__.py module containing build metadata for a Python package.
+"""
+
+import argparse
+import json
+from pathlib import Path
+
+
+def parse_args() -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description=__file__.__doc__,
+        fromfile_prefix_chars="@",
+    )
+    parser.add_argument(
+        "--module-manifests",
+        help="A path to a list of JSON file with modules contained in the PEX.",
+        type=Path,
+        default=None,
+    )
+    parser.add_argument(
+        "--manifest-entries",
+        help="Path to a JSON file with build metadata entries.",
+        type=Path,
+        default=None,
+    )
+    parser.add_argument(
+        "--manifest-entries-overlay",
+        help="Path to JSON entries to merge into the base manifest entries.",
+        type=Path,
+        default=None,
+    )
+    parser.add_argument(
+        "--output",
+        type=Path,
+        help="Output path for the generated module.",
+        required=True,
+    )
+    parser.add_argument("--output-json", type=Path, default=None)
+    return parser.parse_args()
+
+
+def path_to_module(path: str) -> str | None:
+    for suffix in (".py", ".so", ".pyd"):
+        if path.endswith(suffix):
+            return path[: -len(suffix)].replace("/", ".").replace("\\", ".")
+
+
+def merge_entries(entries: dict[str, object], overlay: dict[str, object]) -> None:
+    for key, value in overlay.items():
+        existing = entries.get(key)
+        if isinstance(existing, dict) and isinstance(value, dict):
+            existing.update(value)
+        else:
+            entries[key] = value
+
+
+def load_entries(path: Path | None) -> dict[str, object]:
+    if path is None:
+        return {}
+    with open(path) as f:
+        entries = json.load(f)
+    if not isinstance(entries, dict):
+        raise ValueError(f"Manifest entries in {path} aren't a dictionary")
+    return entries
+
+
+def main() -> None:
+    args = parse_args()
+    output: Path = args.output
+    if output.exists():
+        raise ValueError(
+            f"Output path '{output}' already exists, refusing to overwrite."
+        )
+
+    modules: dict[str, str] = {}
+
+    with open(args.module_manifests) as me:
+        module_manifests = me.read().splitlines()
+        for module_manifest_file in module_manifests:
+            with open(module_manifest_file) as f:
+                for pkg_path, _, origin_desc in json.load(f):
+                    module = path_to_module(pkg_path)
+                    if module:
+                        modules[module] = origin_desc
+                    # Add artificial __init__.py files like in make_py_package_modules.py
+                    for parent in Path(pkg_path).parents:
+                        if parent == Path("") or parent == Path("."):
+                            continue
+                        path = str(parent / "__init__.py")
+                        parent_module = path_to_module(path)
+                        if parent_module and parent_module not in modules:
+                            modules[parent_module] = origin_desc
+                        elif parent_module != module:
+                            break
+
+    entries = load_entries(args.manifest_entries)
+    if args.manifest_entries_overlay:
+        merge_entries(entries, load_entries(args.manifest_entries_overlay))
+    if "modules" in entries:
+        raise ValueError("'modules' can't be a key in manifest entries")
+    if args.output_json:
+        args.output_json.write_text(json.dumps(entries, sort_keys=True) + "\n")
+    sorted_modules = sorted(modules.items())
+    entries["modules"] = [m[0] for m in sorted_modules]
+    entries["origins"] = tuple(m[1] for m in sorted_modules)
+    output.write_text(
+        "\n".join((f"{key} = {repr(value)}" for key, value in entries.items()))
+    )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/python/tools/make_py_package_modules.py b/buck2/prelude/python/tools/make_py_package_modules.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_py_package_modules.py
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Create the link tree for inplace Python binaries.
+
+This does a few things:
+    - Allows remapping of source files (via the srcs/dests arguments) and resources.
+    - Merges extracted .whl files into the tree
+    - Adds __init__.py where needed
+    - Writes out a bootstrapper pex script that knows where this symlink tree is,
+      and uses it, along with the provided entry point to run the python script.
+      It does this by replacing a few special strings like <MODULES_DIR> and
+      <MAIN_MODULE>
+
+A full usage might be something like this:
+
+$ cat srcs
+srcs/foo.py
+srcs/bar.py
+third-party/baz.whl__extracted
+$ cat dests
+lib/foo.py
+bar.py
+.
+$ ls third-party/baz.whl__extracted
+baz/tp_foo.py
+baz/tp_bar.py
+$ cat template.in
+(see prelude/python/run_inplace.py.in)
+$ ./make_py_package_inplace.py  \\
+    --template prelude/python/run_inplace.py.in \\
+    --module-srcs=@srcs \\
+    --module-dests=@dests \\
+    # This is the symlink tree \\
+    --modules-dir=bin__link-tree
+$ find bin__link-tree
+lib/__init__.py
+lib/foo.py
+bar.py
+baz/tp_foo.py
+baz/tp_bar.py
+"""
+
+import argparse
+import errno
+import json
+import os
+import platform
+import re
+import shutil
+from pathlib import Path
+
+# Suffixes which should trigger `__init__.py` additions.
+# TODO(agallaher): This was copied from v1, but some things below probably
+# don't need to be here (e.g. `.pyd`).
+_MODULE_SUFFIXES = {
+    ".dll",
+    ".py",
+    ".pyd",
+    ".so",
+}
+
+_CONTENT_HASH_PLACEHOLDER: str = "/output_artifacts/"
+
+
+def create_pyc_hash_dict(args: argparse.Namespace) -> dict[str, str]:
+    """Construct a map of bytecode artifact path prefixes to content hashes."""
+    pyc_hash_dict: dict[str, str] = {}
+    pattern = re.compile(r"(.*)/([a-fA-F0-9]{16})/bytecode_UNCHECKED_HASH")
+    for bytecode_artifact in args.bytecode_artifacts:
+        with open(bytecode_artifact) as f:
+            for line in f:
+                match = pattern.search(line)
+                if match:
+                    prefix = match.group(1)
+                    content_hash = match.group(2)
+                    pyc_hash_dict[prefix] = content_hash
+    return pyc_hash_dict
+
+
+def replace_pyc_hash_placeholder(path: str, pyc_hash_dict: dict[str, str]) -> str:
+    """Replace the placeholder string in a bytecode artifact path with the actual content hash."""
+    if _CONTENT_HASH_PLACEHOLDER in path:
+        prefix = path.split(_CONTENT_HASH_PLACEHOLDER)[0]
+        content_hash = pyc_hash_dict.get(prefix)
+        if content_hash:
+            path = path.replace(_CONTENT_HASH_PLACEHOLDER, f"/{content_hash}/")
+    return path
+
+
+def parse_args() -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description=(
+            "Create a python inplace binary, writing a symlink tree to a directory, "
+            "and a bootstrapper pex file to file"
+        ),
+        fromfile_prefix_chars="@",
+    )
+    parser.add_argument(
+        "--module-manifest",
+        action="append",
+        dest="module_manifests",
+        default=[],
+        help="A path to a JSON file with modules to be linked.",
+    )
+    parser.add_argument(
+        "--resource-manifest",
+        action="append",
+        dest="resource_manifests",
+        default=[],
+        help="A path to a JSON file with resources to be linked.",
+    )
+    parser.add_argument(
+        "--native-library-src",
+        type=Path,
+        dest="native_library_srcs",
+        action="append",
+        default=[],
+        help="A list of native libraries to use",
+    )
+    parser.add_argument(
+        "--native-library-dest",
+        type=Path,
+        dest="native_library_dests",
+        action="append",
+        default=[],
+        help=(
+            "A list of relative destination paths for each of the native "
+            "libraries in --native-library-src"
+        ),
+    )
+    parser.add_argument(
+        "--dwp-src",
+        type=Path,
+        dest="dwp_srcs",
+        action="append",
+        default=[],
+        help="A list of dwp for native libraries to use",
+    )
+    parser.add_argument(
+        "--dwp-dest",
+        type=Path,
+        dest="dwp_dests",
+        action="append",
+        default=[],
+        help=(
+            "A list of relative destination paths for each of the dwp for native "
+            "libraries in --dwp-src"
+        ),
+    )
+    parser.add_argument(
+        "--native-library-manifest",
+        action="append",
+        dest="native_library_manifests",
+        default=[],
+        help="A path to a JSON file with native libraries to be linked.",
+    )
+    parser.add_argument(
+        "--modules-dir",
+        required=True,
+        type=Path,
+        help="The link tree directory to write to",
+    )
+    parser.add_argument(
+        "--copy-files",
+        default=False,
+        action="store_true",
+        help="Copy files instead of symlinking them",
+    )
+    parser.add_argument(
+        "--bytecode-artifacts",
+        action="append",
+        dest="bytecode_artifacts",
+        default=[],
+        help="A file listing resolved bytecode artifact paths for content-based path resolution.",
+    )
+
+    return parser.parse_args()
+
+
+def _same_pyc(src1: tuple[Path, str], src2: tuple[Path, str]) -> bool:
+    """
+    Given two paths to .pyc files, return True if they are the same.
+    """
+    # As of 3.7, .pyc files are deterministic and have a hash of the original source
+    # file in their first 16 bytes. See https://peps.python.org/pep-0552/#specification
+    src1_path, src1_origin = src1
+    src2_path, src2_origin = src2
+    try:
+        total_size = os.path.getsize(src1_path)
+        if total_size != os.path.getsize(src2_path):
+            return False
+        to_read = min(total_size, 16)
+        buf_size = 4096
+        with open(src1_path, mode="rb") as fa, open(src2_path, mode="rb") as fb:
+            while to_read > 0:
+                chunk_size = min(to_read, buf_size)
+                if fa.read(chunk_size) != fb.read(chunk_size):
+                    return False
+                to_read -= chunk_size
+    except FileNotFoundError:
+        # pyc files might not be materialized yet; in these cases we fall back to comparing the origins,
+        # which should be the path of the original source file
+        return src1_origin == src2_origin
+    return True
+
+
+def add_path_mapping(
+    path_mapping: dict[Path, tuple[str, str]],
+    dirs_to_create: set[Path],
+    src: Path,
+    new_dest: Path,
+    origin: str = "unknown",
+    copy_files: bool = False,
+) -> None:
+    """
+    Add the mapping of a destination path into `path_mapping`, by getting the
+    relative path to the source, and making sure that there are no
+    collisions (and erroring in that case)
+    """
+
+    def format_src(src: str, origin: str) -> str:
+        out = "`{}`".format(src)
+        if origin is not None:
+            out += " (from {})".format(origin)
+        return out
+
+    def _realpath(src: Path) -> str:
+        "get the realpath of a path, but if we are on windows, we strip the longpath prefix"
+        real_src = os.path.realpath(src)
+        if platform.system() == "Windows":
+            real_src = real_src.removeprefix("\\\\?\\")
+        return real_src
+
+    if copy_files:
+        link_path = os.path.realpath(src)
+    else:
+        link_path = os.path.relpath(_realpath(src), _realpath(new_dest.parent))
+    if new_dest in path_mapping:
+        prev, prev_origin = path_mapping[new_dest]
+        if prev != link_path and not (
+            new_dest.suffix == ".pyc"
+            and _same_pyc(
+                (src, origin), ((new_dest.parent / prev).resolve(), prev_origin)
+            )
+        ):
+            raise ValueError(
+                "Destination path `{}` specified at both {} and {} (`{}` before relativisation)".format(
+                    new_dest,
+                    format_src(link_path, origin),
+                    format_src(prev, prev_origin),
+                    src,
+                )
+            )
+    path_mapping[new_dest] = (link_path, origin)
+    dirs_to_create.add(new_dest.parent)
+
+
+def _lexists(path: Path) -> bool:
+    """
+    Like `Path.exists()` but works on dangling. symlinks
+    """
+
+    try:
+        path.lstat()
+    except FileNotFoundError:
+        return False
+    except OSError as e:
+        if e.errno == errno.ENOENT:
+            return False
+        raise
+    return True
+
+
+def create_modules_dir(args: argparse.Namespace) -> None:
+    args.modules_dir.mkdir(parents=True, exist_ok=True)
+
+    # Build a mapping of content-based path prefixes to resolved content hashes.
+    # This is used to replace placeholder "/output_artifacts/" paths in bytecode
+    # manifest entries with their actual content-hashed paths.
+    pyc_hash_dict = create_pyc_hash_dict(args)
+
+    # Mapping of destination files -> the symlink target (e.g. "../foo")
+    path_mapping: dict[Path, tuple[str, str]] = {}
+    # Set of directories that need to be created in the link tree before
+    # symlinking
+    dirs_to_create: set[Path] = set()
+    # Set of __init__.py files that need to be created at the end of the
+    # link tree building if they don't exist, so that python recognizes them
+    # as modules.
+    init_py_paths = set()
+
+    # Link entries from manifests.
+    for manifest in args.module_manifests:
+        with open(manifest) as manifest_file:
+            for dest, src, origin in json.load(manifest_file):
+                dest = Path(dest)
+                src = Path(replace_pyc_hash_placeholder(src, pyc_hash_dict))
+
+                # Add `__init__.py` files for all parent dirs (except the root).
+                if dest.suffix in _MODULE_SUFFIXES:
+                    package = dest.parent
+                    while package != Path("") and package not in init_py_paths:
+                        init_py_paths.add(package)
+                        package = package.parent
+
+                add_path_mapping(
+                    path_mapping,
+                    dirs_to_create,
+                    src,
+                    args.modules_dir / dest,
+                    origin=origin,
+                    copy_files=args.copy_files,
+                )
+
+    for manifest in args.resource_manifests + args.native_library_manifests:
+        with open(manifest) as manifest_file:
+            for dest, src, origin in json.load(manifest_file):
+                src = Path(src)
+                add_path_mapping(
+                    path_mapping,
+                    dirs_to_create,
+                    src,
+                    args.modules_dir / dest,
+                    origin=origin,
+                    copy_files=args.copy_files,
+                )
+
+    if args.native_library_srcs:
+        for src, dest in zip(args.native_library_srcs, args.native_library_dests):
+            new_dest = args.modules_dir / dest
+            add_path_mapping(
+                path_mapping, dirs_to_create, src, new_dest, copy_files=args.copy_files
+            )
+
+    if args.dwp_srcs:
+        for src, dest in zip(args.dwp_srcs, args.dwp_dests):
+            new_dest = args.modules_dir / dest
+            add_path_mapping(
+                path_mapping, dirs_to_create, src, new_dest, copy_files=args.copy_files
+            )
+
+    for d in dirs_to_create:
+        d.mkdir(parents=True, exist_ok=True)
+
+    for dest, (target, _origin) in path_mapping.items():
+        if args.copy_files:
+            shutil.copyfile(target, dest)
+            os.chmod(dest, os.stat(target).st_mode)
+        else:
+            try:
+                os.symlink(target, dest)
+            except OSError:
+                if _lexists(dest):
+                    if os.path.islink(dest):
+                        raise ValueError(
+                            "{} already exists, and is linked to {}. Cannot link to {}".format(
+                                dest, os.readlink(dest), target
+                            )
+                        )
+                    else:
+                        raise ValueError(
+                            "{} already exists. Cannot link to {}".format(dest, target)
+                        )
+                else:
+                    raise
+
+    # Fill in __init__.py for sources that were provided by the user
+    # These are filtered such that we only create this for sources specified
+    # by the user; if a .whl forgets an __init__.py file, that's their problem
+    for init_py_dir in init_py_paths:
+        init_py_path = args.modules_dir / init_py_dir / "__init__.py"
+        # We still do this check because python insists on touching some read only
+        # files and blows up sometimes.
+        if not _lexists(init_py_path):
+            init_py_path.touch(exist_ok=True)
+
+
+def main() -> None:
+    args = parse_args()
+    create_modules_dir(args)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/python/tools/make_source_db.py b/buck2/prelude/python/tools/make_source_db.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_source_db.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Creates a Python Source DB JSON file containing both a rule's immediate sources
+and the sources of all transitive dependencies (e.g. for use with Pyre).
+
+Sources and dependencies are passed in via source manifest files, which are
+merged by this script:
+
+$ ./make_source_db.py \
+      --sources my_rule.manifest.json \
+      --dependency_manifests manifest_paths.txt
+
+The output format of the source DB is:
+
+{
+  "sources": {
+    <source1-name>: <source1-path>,
+    <source2-name>: <source2-path>,
+    ...
+  },
+  "dependencies": {
+    <dep-source1-name>: <dep-source1-path>,
+    <dep-source2-name>: <dep-source2-path>,
+    ...
+  },
+}
+"""
+
+import argparse
+import json
+import sys
+
+
+def _load(path: str) -> list[tuple[str, str, str]]:
+    with open(path) as f:
+        return json.load(f)
+
+
+def _read_dependency_paths(manifest_file: str) -> list[str]:
+    with open(manifest_file) as f:
+        return [line.strip() for line in f if line.strip()]
+
+
+def main(argv: list[str]) -> None:
+    parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
+    parser.add_argument("--output", type=argparse.FileType("w"), default=sys.stdout)
+    parser.add_argument("--sources")
+    parser.add_argument("--dependency_manifests")
+    args = parser.parse_args(argv[1:])
+
+    db = {}
+
+    # Add sources.
+    sources = {}
+    if args.sources is not None:
+        for name, path, _ in _load(args.sources):
+            sources[name] = path
+    db["sources"] = sources
+
+    # Add dependencies.
+    dependencies = {}
+    deps_paths = (
+        _read_dependency_paths(args.dependency_manifests)
+        if args.dependency_manifests
+        else []
+    )
+    for dep in deps_paths:
+        for name, path, origin in _load(dep):
+            prev = dependencies.get(name)
+            if prev is not None and prev[0] != path:
+                raise Exception(
+                    "Duplicate entries for {}: {} ({}) and {} ({})".format(
+                        name, path, origin, *prev
+                    ),
+                )
+            dependencies[name] = path, origin
+    db["dependencies"] = {n: p for n, (p, _) in dependencies.items()}
+
+    # Write db out.
+    json.dump(db, args.output, indent=2)
+    args.output.close()
+
+
+sys.exit(main(sys.argv))
diff --git a/buck2/prelude/python/tools/make_source_db_no_deps.py b/buck2/prelude/python/tools/make_source_db_no_deps.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/make_source_db_no_deps.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+"""
+Creates a Python Source DB JSON file from Python manifest JSON file (e.g. for use with Pyre).
+
+Sources and dependencies are passed in via source manifest files, which are
+merged by this script:
+
+$ ./make_source_db_no_deps.py \
+      my_rule.manifest.json \
+      --output db_no_deps.json
+
+The output format of the source DB is:
+
+{
+  <source1-name>: <source1-path>,
+  <source2-name>: <source2-path>,
+  ...
+}
+"""
+
+import argparse
+import json
+import sys
+
+
+def _load(path: str) -> list[tuple[str, str, str]]:
+    with open(path) as f:
+        return json.load(f)
+
+
+def main(argv: list[str]) -> None:
+    parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
+    parser.add_argument("--output", type=argparse.FileType("w"), default=sys.stdout)
+    parser.add_argument("sources")
+    args = parser.parse_args(argv[1:])
+
+    sources = {name: path for name, path, _ in _load(args.sources)}
+    json.dump(sources, args.output, indent=2)
+    args.output.close()
+
+
+sys.exit(main(sys.argv))
diff --git a/buck2/prelude/python/tools/patchelf.py b/buck2/prelude/python/tools/patchelf.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/patchelf.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import subprocess
+import sys
+
+
+def main(argv: list[str]) -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--patchelf", action="append", required=True)
+    parser.add_argument("-f", action="store_true")
+    parser.add_argument("--rpath", action="append", dest="rpaths", default=[])
+    parser.add_argument("-o", "--output", required=True)
+    parser.add_argument("path")
+    args = parser.parse_args(argv[1:])
+
+    if args.patchelf is None:
+        args.patchelf = ["patchelf"]
+
+    if not args.rpaths:
+        parser.error("no rpaths specified")
+
+    # If this path isn't an ELF file, then there's nothing to do.
+    with open(args.path, "rb") as f:
+        if f.read(4) != b"\x7fELF":
+            # do a reflink copy from path to output
+            subprocess.check_call(["cp", "--reflink=auto", args.path, args.output])
+            return
+
+    # Otherwise, patch in the rpaths.
+    subprocess.check_call(
+        args.patchelf
+        + [
+            "--force-rpath",
+            "--add-rpath",
+            ":".join(args.rpaths),
+            "--output",
+            args.output,
+            args.path,
+        ]
+    )
+
+
+if __name__ == "__main__":
+    main(sys.argv)
diff --git a/buck2/prelude/python/tools/run_inplace.py.in b/buck2/prelude/python/tools/run_inplace.py.in
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/run_inplace.py.in
@@ -0,0 +1,217 @@
+#!<PYTHON>
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under both the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree and the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree.
+
+# N.B. When the interpreter is a build artifact, the `#!` line above expands to several
+# lines of shell/Python polyglot that resolve it relative to this file.
+
+# LINKTREEDIR=<MODULES_DIR>
+
+main_module = "<MAIN_MODULE>"
+main_function = "<MAIN_FUNCTION>"
+modules_dir = "<MODULES_DIR>"
+native_libs_env_var = "<NATIVE_LIBS_ENV_VAR>"
+native_libs_dirs = <NATIVE_LIBS_DIRS>
+native_libs_preload_env_var = "<NATIVE_LIBS_PRELOAD_ENV_VAR>"
+native_libs_preload = <NATIVE_LIBS_PRELOAD>
+interpreter_flags = "<PYTHON_INTERPRETER_FLAGS>"
+unc_prefix = "\\\\?\\"
+
+import os
+import platform
+import signal
+import subprocess
+import sys
+import time
+
+os.environ["PAR_LAUNCH_TIMESTAMP"] = str(time.time())
+
+dirpath = os.path.dirname(os.path.realpath(__file__))
+
+# Enable long path support on Windows
+if platform.system() == "Windows" and not dirpath.startswith(unc_prefix):
+    dirpath = unc_prefix + dirpath
+
+env_vals_to_restore = {}
+# Update the environment variable for the dynamic loader to the native
+# libraries location.
+if native_libs_dirs is not None:
+    old_native_libs_dirs = os.environ.get(native_libs_env_var)
+    os.environ[native_libs_env_var] = os.pathsep.join([
+        os.path.join(dirpath, native_libs_dir)
+        for native_libs_dir in native_libs_dirs
+    ])
+    env_vals_to_restore[native_libs_env_var] = old_native_libs_dirs
+if os.environ.get("PAR_APPEND_LD_LIBRARY_PATH") is not None:
+   os.environ[native_libs_env_var] = (
+      (os.environ[native_libs_env_var] + ":" + os.environ["PAR_APPEND_LD_LIBRARY_PATH"])
+      if os.environ.get(native_libs_env_var) is not None
+      else os.environ["PAR_APPEND_LD_LIBRARY_PATH"]
+   )
+
+# Update the environment variable for the dynamic loader to find libraries
+# to preload.
+if native_libs_preload is not None:
+    old_native_libs_preload = os.environ.get(native_libs_preload_env_var)
+    env_vals_to_restore[native_libs_preload_env_var] = old_native_libs_preload
+
+    # On macos, preloaded libs are found via paths.
+    if platform.system() == "Darwin":
+        full_path_preloads = []
+        for lib in native_libs_preload:
+            for native_libs_dir in native_libs_dirs:
+                fpath = os.path.join(dirpath, native_libs_dir, lib)
+                if os.path.exists(fpath):
+                    full_path_preloads.append(fpath)
+                    break
+            else:
+                raise Exception(
+                    "cannot find preload lib {!r} in paths {!r}".format(
+                        lib,
+                        native_libs_dirs,
+                    ),
+                )
+        native_libs_preload = full_path_preloads
+
+    os.environ[native_libs_preload_env_var] = os.pathsep.join(native_libs_preload)
+
+<ENV>
+
+# Note: this full block of code will be included as the argument to Python,
+# and will be the first thing that shows up in the process arguments as displayed
+# by programs like ps and top.
+#
+# We include sys.argv[0] at the start of this comment just to make it more visible what program
+# is being run in the ps and top output.
+STARTUP = f"""\
+# {sys.argv[0]}
+# Wrap everything in a private function to prevent globals being captured by
+# the `runpy._run_module_as_main` below.
+def __run():
+    import sys
+
+    # We set the paths beforehand to have a minimal amount of imports before
+    # nuking PWD from sys.path. Otherwise, there can be problems if someone runs
+    # from a directory with a similarly named file, even if their code is properly
+    # namespaced. e.g. if one has foo/bar/contextlib.py and while in foo/bar runs
+    # `buck run foo/bar:bin`, runpy will fail as it tries to import
+    # foo/bar/contextlib.py. You're just out of luck if you have sys.py
+
+    # Set `argv[0]` to the executing script.
+    assert sys.argv[0] == '-c'
+    sys.argv[0] = {sys.argv[0]!r}
+
+    # Remove the working directory.
+    assert sys.path[0] == ''
+    del sys.path[0]
+
+    import os
+    import runpy
+
+    def setenv(var, val):
+        if val is None:
+            os.environ.pop(var, None)
+        else:
+            os.environ[var] = val
+
+    def restoreenv(d):
+        for k, v in d.items():
+            setenv(k, v)
+
+    restoreenv({env_vals_to_restore!r})
+
+    # On windows, adjust os.add_dll_directory and PATH (for `ctypes.util.find_library`)
+    # so that native libraries can be found by the dynamic linker or ctypes
+    if sys.platform.startswith("win"):
+        path = os.environ.get("PATH", "")
+        dll_dirs = []
+        for native_libs_dir in {native_libs_dirs!r}:
+            d = os.path.join({dirpath!r}, native_libs_dir)
+            os.add_dll_directory(d)
+            dll_dirs.append(d)
+            if path and not path.endswith(os.pathsep):
+                path += os.pathsep
+            path += d
+        setenv("PATH", path)
+        # Persist DLL directories for child processes. sitecustomize.py will
+        # read this and call os.add_dll_directory() in each child, since
+        # those calls are process-local and don't propagate across spawns.
+        if dll_dirs:
+            os.environ["FB_PAR_WIN_DLL_DIRS"] = os.pathsep.join(dll_dirs)
+
+    from <MAIN_RUNNER_MODULE> import <MAIN_RUNNER_FUNCTION> as run_as_main
+    run_as_main({main_module!r}, {main_function!r})
+
+
+__run()
+"""
+
+args = [sys.executable]
+if interpreter_flags:
+    args.extend(interpreter_flags.split())
+args.extend(["-c", STARTUP])
+
+# Default to 'd' warnings, but allow users to control this via PYTHONWARNINGS
+# The -E causes python to ignore all PYTHON* environment vars so we have to
+# pass this down using the command line.
+warnings = os.environ.get("PYTHONWARNINGS", "d").split(",")
+for item in reversed(warnings):
+    args.insert(1, f"-W{item.strip()}")
+
+# Allow users to disable byte code generation by setting the standard environment var.
+# Same as above, because of -E we have to pass this down using the command line.
+if "PYTHONDONTWRITEBYTECODE" in os.environ:
+    args.insert(1, "-B")
+
+# Pass through PYTHONPROFILEIMPORTTIME as -X importtime. Similar issues to
+# PYTHONDONTWRITEBYTECODE above — because of -E we have to pass this via the
+# command line. Only supported on CPython.
+if "PYTHONPROFILEIMPORTTIME" in os.environ and platform.python_implementation() == "CPython":
+    args[1:1] = ["-X", "importtime"]
+
+# Save the variables that will be restored back into the environment by
+# fbcode/buck2/prelude/python/tools/make_par/sitecustomize.py
+for env in ("PYTHONPATH", "LD_LIBRARY_PATH", "LD_PRELOAD",
+            "DYLD_LIBRARY_PATH", "DYLD_INSERT_LIBRARIES"):
+    if env in os.environ:
+        os.environ["FB_SAVED_" + env] = os.environ[env]
+
+path = os.path.join(dirpath, modules_dir)
+os.environ["PYTHONPATH"] = path
+if "PAR_APPEND_PYTHONPATH" in os.environ:
+   os.environ["PYTHONPATH"] += ":" + os.environ["PAR_APPEND_PYTHONPATH"]
+
+# This environment variable is immediately unset on startup but will also appear
+# in e.g. `multiprocessing` workers, and so serves as an audit trail back to
+# the originating PAR (and can be read via e.g. `/proc/<pid>/environ`).
+os.environ["PAR_INVOKED_NAME_TAG"] = sys.argv[0]
+
+if platform.system() == "Windows":
+    # exec on Windows is not true exec - there is only 'spawn' ('CreateProcess').
+    # However, creating processes unnecessarily is painful, so we only do the spawn
+    # path if we have to, which is on Windows. That said, this complicates signal
+    # handling, so we need to set up some signal forwarding logic.
+
+    p = subprocess.Popen(args + sys.argv[1:])
+
+    def handler(signum, frame):
+        # If we're getting this, we need to forward signum to subprocesses
+        if signum == signal.SIGINT:
+            p.send_signal(signal.CTRL_C_EVENT)
+        elif signum == signal.SIGBREAK:
+            p.send_signal(signal.CTRL_BREAK_EVENT)
+        else:
+            # shouldn't happen, we should be killed instead
+            p.terminate()
+
+    signal.signal(signal.SIGINT, handler)
+    signal.signal(signal.SIGBREAK, handler)
+
+    p.wait()
+    sys.exit(p.returncode)
+else:
+    os.execv(sys.executable, args + sys.argv[1:])
diff --git a/buck2/prelude/python/tools/sourcedb_merger/BUCK b/buck2/prelude/python/tools/sourcedb_merger/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/BUCK
@@ -0,0 +1,43 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("plf_experience")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_library(
+    name = "library",
+    srcs = [
+        "inputs.py",
+        "legacy_outputs.py",
+        "outputs.py",
+    ],
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "merge",
+    main = "merge.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":library",
+    ],
+)
+
+prelude.python_bootstrap_binary(
+    name = "legacy_merge",
+    main = "legacy_merge.py",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":library",
+    ],
+)
+
+# Run the test suite with this command:
+# buck2 run prelude//python/tools/sourcedb_merger:tests --target-platforms prelude//platforms:default
+prelude.sh_binary(
+    name = "tests",
+    main = "tests/main.sh",
+    resources = glob(["**/*.py"]),
+)
diff --git a/buck2/prelude/python/tools/sourcedb_merger/inputs.py b/buck2/prelude/python/tools/sourcedb_merger/inputs.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/inputs.py
@@ -0,0 +1,88 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+import dataclasses
+import json
+import pathlib
+from collections.abc import Iterable, Mapping
+
+
+class BuildMapLoadError(Exception):
+    pass
+
+
+@dataclasses.dataclass(frozen=True)
+class Target:
+    name: str
+
+
+@dataclasses.dataclass(frozen=True)
+class PartialBuildMap:
+    content: Mapping[str, str] = dataclasses.field(default_factory=dict)
+
+    @staticmethod
+    def load_from_json(input_json: object) -> "PartialBuildMap":
+        if not isinstance(input_json, dict):
+            raise BuildMapLoadError(
+                "Input JSON for build map should be a dict."
+                f"Got {type(input_json)} instead"
+            )
+        result: dict[str, str] = {}
+        for key, value in input_json.items():
+            if not isinstance(key, str):
+                raise BuildMapLoadError(
+                    f"Build map keys are expected to be strings. Got `{key}`."
+                )
+            if not isinstance(value, str):
+                raise BuildMapLoadError(
+                    f"Build map values are expected to be strings. Got `{value}`."
+                )
+            if pathlib.Path(key).suffix not in (".py", ".pyi"):
+                continue
+            result[key] = value
+        return PartialBuildMap(result)
+
+    @staticmethod
+    def load_from_path(input_path: pathlib.Path) -> "PartialBuildMap":
+        with open(input_path) as input_file:
+            return PartialBuildMap.load_from_json(json.load(input_file))
+
+
+@dataclasses.dataclass(frozen=True)
+class TargetEntry:
+    target: Target
+    build_map: PartialBuildMap
+
+
+def load_targets_and_build_maps_from_json(input_json: object) -> Iterable[TargetEntry]:
+    if not isinstance(input_json, dict):
+        raise BuildMapLoadError(
+            f"Input JSON should be a dict. Got {type(input_json)} instead"
+        )
+    for key, value in input_json.items():
+        if not isinstance(key, str):
+            raise BuildMapLoadError(
+                f"Target keys are expected to be strings. Got `{key}`."
+            )
+        if not isinstance(value, str):
+            raise BuildMapLoadError(
+                f"Sourcedb file paths are expected to be strings. Got `{value}`."
+            )
+        yield TargetEntry(
+            target=Target(key),
+            # pyre-fixme[6]: For 1st argument expected `Path` but got `str`.
+            build_map=PartialBuildMap.load_from_path(value),
+        )
+
+
+def load_targets_and_build_maps_from_path(input_path: str) -> Iterable[TargetEntry]:
+    with open(input_path) as input_file:
+        return load_targets_and_build_maps_from_json(json.load(input_file))
diff --git a/buck2/prelude/python/tools/sourcedb_merger/legacy_merge.py b/buck2/prelude/python/tools/sourcedb_merger/legacy_merge.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/legacy_merge.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+import argparse
+import pathlib
+import sys
+from collections.abc import Sequence
+
+import inputs
+import legacy_outputs
+
+
+def run_merge(input_file: str, output_file: str) -> None:
+    target_entries = inputs.load_targets_and_build_maps_from_path(input_file)
+    merge_result = legacy_outputs.merge_partial_build_maps(target_entries)
+    merge_result.write_json_file(pathlib.Path(output_file))
+
+
+def main(argv: Sequence[str]) -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("input", type=str)
+    parser.add_argument("-o", "--output", required=True, type=str)
+    arguments = parser.parse_args(argv[1:])
+
+    run_merge(arguments.input, arguments.output)
+
+
+if __name__ == "__main__":
+    main(sys.argv)
diff --git a/buck2/prelude/python/tools/sourcedb_merger/legacy_outputs.py b/buck2/prelude/python/tools/sourcedb_merger/legacy_outputs.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/legacy_outputs.py
@@ -0,0 +1,148 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+import dataclasses
+import json
+import pathlib
+from collections.abc import Iterable, Mapping
+
+import inputs
+import outputs
+
+
+@dataclasses.dataclass(frozen=True)
+class ConflictInfo:
+    conflict_with: inputs.Target
+    artifact_path: str
+    preserved_source_path: str
+    dropped_source_path: str
+
+    def to_json(self) -> dict[str, str]:
+        return {
+            "conflict_with": self.conflict_with.name,
+            "artifact_path": self.artifact_path,
+            "preserved_source_path": self.preserved_source_path,
+            "dropped_source_path": self.dropped_source_path,
+        }
+
+
+@dataclasses.dataclass(frozen=True)
+class FullBuildMap:
+    content: Mapping[str, outputs.SourceInfo] = dataclasses.field(default_factory=dict)
+
+    def get_all_targets(self) -> set[inputs.Target]:
+        return {source_info.target for _, source_info in self.content.items()}
+
+    def to_json(self) -> dict[str, str]:
+        return {
+            artifact_path: source_info.source_path
+            for artifact_path, source_info in self.content.items()
+        }
+
+
+@dataclasses.dataclass(frozen=True)
+class ConflictMap:
+    content: Mapping[inputs.Target, ConflictInfo] = dataclasses.field(
+        default_factory=dict
+    )
+
+    def to_json(self) -> dict[str, dict[str, str]]:
+        return {
+            target.name: conflict_info.to_json()
+            for target, conflict_info in self.content.items()
+        }
+
+
+@dataclasses.dataclass(frozen=True)
+class MergeResult:
+    build_map: FullBuildMap
+    dropped_targets: ConflictMap
+
+    def to_json(self) -> dict[str, object]:
+        return {
+            "build_map": self.build_map.to_json(),
+            "built_targets_count": len(
+                [target.name for target in self.build_map.get_all_targets()]
+            ),
+            "dropped_targets": self.dropped_targets.to_json(),
+        }
+
+    def write_json_file(self, path: pathlib.Path) -> None:
+        with open(path, "w") as output_file:
+            json.dump(self.to_json(), output_file, indent=2)
+
+
+def detect_conflict(
+    build_map: Mapping[str, outputs.SourceInfo],
+    target: inputs.Target,
+    merge_candidate: Mapping[str, str],
+) -> ConflictInfo | None:
+    for artifact_path, source_path in merge_candidate.items():
+        existing_source_info = build_map.get(artifact_path, None)
+        if (
+            existing_source_info is not None
+            and source_path != existing_source_info.source_path
+        ):
+            return ConflictInfo(
+                conflict_with=existing_source_info.target,
+                artifact_path=artifact_path,
+                preserved_source_path=existing_source_info.source_path,
+                dropped_source_path=source_path,
+            )
+    return None
+
+
+def insert_build_map_inplace(
+    build_map: dict[str, outputs.SourceInfo],
+    target: inputs.Target,
+    merge_candidate: Mapping[str, str],
+) -> None:
+    for artifact_path, source_path in merge_candidate.items():
+        build_map.setdefault(
+            artifact_path, outputs.SourceInfo(source_path=source_path, target=target)
+        )
+
+
+def merge_partial_build_map_inplace(
+    build_map: dict[str, outputs.SourceInfo],
+    dropped_targets: dict[inputs.Target, ConflictInfo],
+    target_entry: inputs.TargetEntry,
+) -> None:
+    target = target_entry.target
+    filtered_mappings = {
+        artifact_path: source_path
+        for artifact_path, source_path in target_entry.build_map.content.items()
+        if artifact_path
+        not in (
+            "__manifest__.py",
+            "__test_main__.py",
+            "__test_modules__.py",
+        )
+    }
+    conflict = detect_conflict(build_map, target, filtered_mappings)
+    if conflict is not None:
+        dropped_targets[target_entry.target] = conflict
+    else:
+        insert_build_map_inplace(build_map, target, filtered_mappings)
+
+
+def merge_partial_build_maps(
+    target_entries: Iterable[inputs.TargetEntry],
+) -> MergeResult:
+    build_map: dict[str, outputs.SourceInfo] = {}
+    dropped_targets: dict[inputs.Target, ConflictInfo] = {}
+    for target_entry in sorted(target_entries, key=lambda entry: entry.target.name):
+        merge_partial_build_map_inplace(
+            build_map,
+            dropped_targets,
+            target_entry,
+        )
+    return MergeResult(FullBuildMap(build_map), ConflictMap(dropped_targets))
diff --git a/buck2/prelude/python/tools/sourcedb_merger/merge.py b/buck2/prelude/python/tools/sourcedb_merger/merge.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/merge.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env fbpython
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+import argparse
+import pathlib
+import sys
+from collections.abc import Sequence
+
+import inputs
+import outputs
+
+
+def run_merge(input_file: str, output_file: str) -> None:
+    target_entries = inputs.load_targets_and_build_maps_from_path(input_file)
+    merged_build_map = outputs.merge_partial_build_maps(target_entries)
+    merged_build_map.write_build_map_json_file(pathlib.Path(output_file))
+
+
+def main(argv: Sequence[str]) -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("input", type=str)
+    parser.add_argument("-o", "--output", required=True, type=str)
+    arguments = parser.parse_args(argv[1:])
+
+    run_merge(arguments.input, arguments.output)
+
+
+if __name__ == "__main__":
+    main(sys.argv)
diff --git a/buck2/prelude/python/tools/sourcedb_merger/outputs.py b/buck2/prelude/python/tools/sourcedb_merger/outputs.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/outputs.py
@@ -0,0 +1,58 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+import dataclasses
+import json
+import pathlib
+from collections.abc import Iterable, Mapping
+
+import inputs
+
+
+@dataclasses.dataclass(frozen=True)
+class SourceInfo:
+    source_path: str
+    target: inputs.Target
+
+
+@dataclasses.dataclass(frozen=True)
+class FullBuildMap:
+    content: Mapping[str, SourceInfo] = dataclasses.field(default_factory=dict)
+
+    def to_build_map_json(self) -> dict[str, str]:
+        return {
+            artifact_path: source_info.source_path
+            for artifact_path, source_info in self.content.items()
+        }
+
+    def write_build_map_json_file(self, path: pathlib.Path) -> None:
+        with open(path, "w") as output_file:
+            json.dump(self.to_build_map_json(), output_file, indent=2)
+
+
+def merge_partial_build_map_inplace(
+    sofar: dict[str, SourceInfo],
+    target_entry: inputs.TargetEntry,
+) -> None:
+    for artifact_path, source_path in target_entry.build_map.content.items():
+        sofar.setdefault(
+            artifact_path,
+            SourceInfo(source_path=source_path, target=target_entry.target),
+        )
+
+
+def merge_partial_build_maps(
+    target_entries: Iterable[inputs.TargetEntry],
+) -> FullBuildMap:
+    result: dict[str, SourceInfo] = {}
+    for target_entry in target_entries:
+        merge_partial_build_map_inplace(result, target_entry)
+    return FullBuildMap(result)
diff --git a/buck2/prelude/python/tools/sourcedb_merger/tests/__init__.py b/buck2/prelude/python/tools/sourcedb_merger/tests/__init__.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/tests/__init__.py
@@ -0,0 +1,37 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+# pyre-fixme[21]: Could not find name `BuildMapLoadError` in `tests.inputs_test`.
+# pyre-fixme[21]: Could not find name `PartialBuildMap` in `tests.inputs_test`.
+# pyre-fixme[21]: Could not find name `Target` in `tests.inputs_test`.
+# pyre-fixme[21]: Could not find name `TargetEntry` in `tests.inputs_test`.
+# pyre-fixme[21]: Could not find name `load_targets_and_build_maps_from_json` in
+#  `tests.inputs_test`.
+from .inputs_test import *  # noqa
+
+# pyre-fixme[21]: Could not find name `ConflictInfo` in `tests.legacy_output_test`.
+# pyre-fixme[21]: Could not find name `ConflictMap` in `tests.legacy_output_test`.
+# pyre-fixme[21]: Could not find name `FullBuildMap` in `tests.legacy_output_test`.
+# pyre-fixme[21]: Could not find name `MergeResult` in `tests.legacy_output_test`.
+# pyre-fixme[21]: Could not find name `PartialBuildMap` in `tests.legacy_output_test`.
+# pyre-fixme[21]: Could not find name `SourceInfo` in `tests.legacy_output_test`.
+# pyre-fixme[21]: Could not find name `Target` in `tests.legacy_output_test`.
+# pyre-fixme[21]: Could not find name `TargetEntry` in `tests.legacy_output_test`.
+# pyre-fixme[21]: Could not find name `merge_partial_build_maps` in
+#  `tests.legacy_output_test`.
+from .legacy_output_test import *  # noqa
+
+# pyre-fixme[21]: Could not find name `PartialBuildMap` in `tests.outputs_test`.
+# pyre-fixme[21]: Could not find name `Target` in `tests.outputs_test`.
+# pyre-fixme[21]: Could not find name `TargetEntry` in `tests.outputs_test`.
+# pyre-fixme[21]: Could not find name `merge_partial_build_maps` in
+#  `tests.outputs_test`.
+from .outputs_test import *  # noqa
diff --git a/buck2/prelude/python/tools/sourcedb_merger/tests/inputs_test.py b/buck2/prelude/python/tools/sourcedb_merger/tests/inputs_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/tests/inputs_test.py
@@ -0,0 +1,117 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+import contextlib
+import json
+import os
+import tempfile
+import unittest
+from collections.abc import Generator, Mapping
+from pathlib import Path
+
+# pyre-fixme[21]: Could not find module `sourcedb_merger.inputs`.
+from sourcedb_merger.inputs import (
+    BuildMapLoadError,
+    load_targets_and_build_maps_from_json,
+    PartialBuildMap,
+    Target,
+    TargetEntry,
+)
+
+
+@contextlib.contextmanager
+def switch_working_directory(directory: Path) -> Generator[None, None, None]:
+    original_directory = Path(".").resolve()
+    try:
+        os.chdir(str(directory))
+        yield None
+    finally:
+        os.chdir(str(original_directory))
+
+
+def write_files(contents: Mapping[str, str]) -> None:
+    for name, text in contents.items():
+        Path(name).write_text(text)
+
+
+class InputsTest(unittest.TestCase):
+    def test_load_partial_build_map(self) -> None:
+        def assert_loaded(input_json: object, expected: object) -> None:
+            self.assertEqual(
+                PartialBuildMap.load_from_json(input_json).content, expected
+            )
+
+        def assert_not_loaded(input_json: object) -> None:
+            with self.assertRaises(BuildMapLoadError):
+                PartialBuildMap.load_from_json(input_json)
+
+        assert_not_loaded(42)
+        assert_not_loaded("derp")
+        assert_not_loaded([True, False])
+        assert_not_loaded({1: 2})
+        assert_not_loaded({"foo": {"bar": "baz"}})
+
+        assert_loaded(
+            {"foo.py": "source/foo.py", "bar.pyi": "source/bar.pyi"},
+            expected={"foo.py": "source/foo.py", "bar.pyi": "source/bar.pyi"},
+        )
+        assert_loaded({"Kratos": "Axe", "Atreus": "Bow"}, expected={})
+        assert_loaded(
+            {"Kratos.py": "Axe", "Atreus": "Bow"}, expected={"Kratos.py": "Axe"}
+        )
+        assert_loaded(
+            {"Kratos": "Axe", "Atreus.pyi": "Bow"},
+            expected={"Atreus.pyi": "Bow"},
+        )
+
+    def test_load_targets_and_build_map(self) -> None:
+        with (
+            tempfile.TemporaryDirectory() as root,
+            switch_working_directory(Path(root)),
+        ):
+            write_files(
+                {
+                    "a.json": json.dumps({"crucible.py": "red"}),
+                    "b.json": json.dumps({"bfg.py": "green", "unmakyr.py": "red"}),
+                    "c.txt": "not a json",
+                    "d.json": "42",
+                },
+            )
+
+            self.assertCountEqual(
+                load_targets_and_build_maps_from_json(
+                    {"//target0": "a.json", "//target1": "b.json"}
+                ),
+                [
+                    TargetEntry(
+                        target=Target("//target0"),
+                        build_map=PartialBuildMap({"crucible.py": "red"}),
+                    ),
+                    TargetEntry(
+                        target=Target("//target1"),
+                        build_map=PartialBuildMap(
+                            {"bfg.py": "green", "unmakyr.py": "red"}
+                        ),
+                    ),
+                ],
+            )
+
+            # NOTE: Use `list()` to force eager construction of all target entries
+            with self.assertRaises(FileNotFoundError):
+                list(
+                    load_targets_and_build_maps_from_json(
+                        {"//target0": "nonexistent.json"}
+                    )
+                )
+            with self.assertRaises(json.JSONDecodeError):
+                list(load_targets_and_build_maps_from_json({"//target0": "c.txt"}))
+            with self.assertRaises(BuildMapLoadError):
+                list(load_targets_and_build_maps_from_json({"//target0": "d.json"}))
diff --git a/buck2/prelude/python/tools/sourcedb_merger/tests/legacy_output_test.py b/buck2/prelude/python/tools/sourcedb_merger/tests/legacy_output_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/tests/legacy_output_test.py
@@ -0,0 +1,232 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+import unittest
+from collections.abc import Mapping
+
+# pyre-fixme[21]: Could not find module `sourcedb_merger.inputs`.
+from sourcedb_merger.inputs import PartialBuildMap, Target, TargetEntry
+
+# pyre-fixme[21]: Could not find module `sourcedb_merger.legacy_outputs`.
+from sourcedb_merger.legacy_outputs import (
+    ConflictInfo,
+    ConflictMap,
+    FullBuildMap,
+    merge_partial_build_maps,
+    MergeResult,
+)
+
+# pyre-fixme[21]: Could not find module `sourcedb_merger.outputs`.
+from sourcedb_merger.outputs import SourceInfo
+
+
+class LegacyOutputsTest(unittest.TestCase):
+    def test_json(self) -> None:
+        self.assertDictEqual(
+            MergeResult(
+                build_map=FullBuildMap(
+                    {
+                        "a.py": SourceInfo(
+                            source_path="fbcode/a.py", target=Target("//test:foo")
+                        ),
+                        "b.py": SourceInfo(
+                            source_path="fbcode/b.py", target=Target("//test:bar")
+                        ),
+                        "c.py": SourceInfo(
+                            source_path="fbcode/c.py", target=Target("//test:foo")
+                        ),
+                    }
+                ),
+                dropped_targets=ConflictMap(
+                    {
+                        Target("//test:baz"): ConflictInfo(
+                            conflict_with=Target("//test:foo"),
+                            artifact_path="a.py",
+                            preserved_source_path="fbcode/a.py",
+                            dropped_source_path="fbcode/another/a.py",
+                        ),
+                    }
+                ),
+            ).to_json(),
+            {
+                "build_map": {
+                    "a.py": "fbcode/a.py",
+                    "b.py": "fbcode/b.py",
+                    "c.py": "fbcode/c.py",
+                },
+                "built_targets_count": 2,
+                "dropped_targets": {
+                    "//test:baz": {
+                        "artifact_path": "a.py",
+                        "conflict_with": "//test:foo",
+                        "dropped_source_path": "fbcode/another/a.py",
+                        "preserved_source_path": "fbcode/a.py",
+                    }
+                },
+            },
+        )
+
+    def test_merge_by_path(self) -> None:
+        def assert_merged(
+            build_maps: Mapping[str, Mapping[str, str]],
+            expected_build_map: Mapping[str, str],
+            expected_conflicts: Mapping[str, Mapping[str, str]],
+        ) -> None:
+            merge_result = merge_partial_build_maps(
+                TargetEntry(
+                    target=Target(target),
+                    build_map=PartialBuildMap.load_from_json(content),
+                )
+                for target, content in build_maps.items()
+            )
+            self.assertDictEqual(
+                merge_result.build_map.to_json(),
+                expected_build_map,
+            )
+            self.assertDictEqual(
+                merge_result.dropped_targets.to_json(),
+                expected_conflicts,
+            )
+
+        assert_merged({}, expected_build_map={}, expected_conflicts={})
+        assert_merged(
+            {"//test:foo": {"foo.py": "source/foo.py"}},
+            expected_build_map={"foo.py": "source/foo.py"},
+            expected_conflicts={},
+        )
+        assert_merged(
+            {
+                "//test:foo": {
+                    "foo.py": "source/foo.py",
+                    "__manifest__.py": "generated/__manifest__.py",
+                }
+            },
+            expected_build_map={"foo.py": "source/foo.py"},
+            expected_conflicts={},
+        )
+        assert_merged(
+            {
+                "//test:foo": {
+                    "foo.py": "source/foo.py",
+                    "__test_main__.py": "generated/__test_main__.py",
+                }
+            },
+            expected_build_map={"foo.py": "source/foo.py"},
+            expected_conflicts={},
+        )
+        assert_merged(
+            {
+                "//test:foo": {
+                    "foo.py": "source/foo.py",
+                    "__test_modules__.py": "generated/__test_modules__.py",
+                }
+            },
+            expected_build_map={"foo.py": "source/foo.py"},
+            expected_conflicts={},
+        )
+        assert_merged(
+            {
+                "//foo:bar": {
+                    "a.py": "source/a.py",
+                },
+                "//foo:baz": {"b.py": "source/b.py"},
+            },
+            expected_build_map={"a.py": "source/a.py", "b.py": "source/b.py"},
+            expected_conflicts={},
+        )
+        assert_merged(
+            {
+                "//foo:bar": {
+                    "a.py": "source/a.py",
+                    "__manifest__.py": "generated/__manifest__.py",
+                },
+                "//foo:baz": {
+                    "b.py": "source/b.py",
+                    "__manifest__.py": "generated/__manifest__.py",
+                },
+            },
+            {"a.py": "source/a.py", "b.py": "source/b.py"},
+            expected_conflicts={},
+        )
+        assert_merged(
+            {
+                "//foo:bar": {"a.py": "source/a.py", "b.py": "source/b.py"},
+                "//foo:baz": {"b.py": "source/b.py"},
+            },
+            {"a.py": "source/a.py", "b.py": "source/b.py"},
+            expected_conflicts={},
+        )
+        assert_merged(
+            {
+                "//foo:bar": {"a.py": "source/a.py", "x.py": "source/b.py"},
+                # Conflict on x.py
+                "//foo:baz": {"d.py": "source/d.py", "x.py": "source/c.py"},
+                "//foo:qux": {"e.py": "source/e.py"},
+            },
+            expected_build_map={
+                "a.py": "source/a.py",
+                "x.py": "source/b.py",
+                "e.py": "source/e.py",
+            },
+            expected_conflicts={
+                "//foo:baz": {
+                    "conflict_with": "//foo:bar",
+                    "artifact_path": "x.py",
+                    "preserved_source_path": "source/b.py",
+                    "dropped_source_path": "source/c.py",
+                }
+            },
+        )
+        assert_merged(
+            {
+                "//foo:bar": {"a.py": "source/a.py"},
+                "//foo:baz": {"b.py": "source/b.py", "x.py": "source/c.py"},
+                # Conflict on x.py
+                "//foo:qux": {"e.py": "source/e.py", "x.py": "source/d.py"},
+            },
+            expected_build_map={
+                "a.py": "source/a.py",
+                "b.py": "source/b.py",
+                "x.py": "source/c.py",
+            },
+            expected_conflicts={
+                "//foo:qux": {
+                    "conflict_with": "//foo:baz",
+                    "artifact_path": "x.py",
+                    "preserved_source_path": "source/c.py",
+                    "dropped_source_path": "source/d.py",
+                }
+            },
+        )
+        assert_merged(
+            {
+                "//foo:bar": {"a.py": "source/a.py", "x.py": "source/b.py"},
+                # Conflict on x.py
+                "//foo:baz": {"d.py": "source/d.py", "x.py": "source/c.py"},
+                # Conflict on x.py
+                "//foo:qux": {"e.py": "source/e.py", "x.py": "source/f.py"},
+            },
+            expected_build_map={"a.py": "source/a.py", "x.py": "source/b.py"},
+            expected_conflicts={
+                "//foo:baz": {
+                    "conflict_with": "//foo:bar",
+                    "artifact_path": "x.py",
+                    "preserved_source_path": "source/b.py",
+                    "dropped_source_path": "source/c.py",
+                },
+                "//foo:qux": {
+                    "conflict_with": "//foo:bar",
+                    "artifact_path": "x.py",
+                    "preserved_source_path": "source/b.py",
+                    "dropped_source_path": "source/f.py",
+                },
+            },
+        )
diff --git a/buck2/prelude/python/tools/sourcedb_merger/tests/main.sh b/buck2/prelude/python/tools/sourcedb_merger/tests/main.sh
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/tests/main.sh
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+PYTHONPATH="$(dirname "$(dirname "$(dirname "$(realpath "$0")")")")"
+export PYTHONPATH
+exec python3 -m unittest sourcedb_merger.tests
diff --git a/buck2/prelude/python/tools/sourcedb_merger/tests/outputs_test.py b/buck2/prelude/python/tools/sourcedb_merger/tests/outputs_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/sourcedb_merger/tests/outputs_test.py
@@ -0,0 +1,71 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+import unittest
+from collections.abc import Mapping
+
+# pyre-fixme[21]: Could not find module `sourcedb_merger.inputs`.
+from sourcedb_merger.inputs import PartialBuildMap, Target, TargetEntry
+
+# pyre-fixme[21]: Could not find module `sourcedb_merger.outputs`.
+from sourcedb_merger.outputs import merge_partial_build_maps
+
+
+class OutputsTest(unittest.TestCase):
+    def test_merge(self) -> None:
+        def assert_merged(
+            build_maps: Mapping[str, Mapping[str, str]],
+            expected: Mapping[str, str],
+        ) -> None:
+            self.assertDictEqual(
+                merge_partial_build_maps(
+                    TargetEntry(
+                        target=Target(target),
+                        build_map=PartialBuildMap.load_from_json(content),
+                    )
+                    for target, content in build_maps.items()
+                ).to_build_map_json(),
+                expected,
+            )
+
+        assert_merged({}, {})
+        assert_merged({"//target0": {"a.py": "foo/a.py"}}, {"a.py": "foo/a.py"})
+        assert_merged(
+            {"//target0": {"a.py": "foo/a.py"}, "//target1": {"b.py": "bar/b.py"}},
+            {
+                "a.py": "foo/a.py",
+                "b.py": "bar/b.py",
+            },
+        )
+        assert_merged(
+            {"//target0": {"a.py": "foo/a.py"}, "//target1": {"a.py": "bar/b.py"}},
+            {
+                "a.py": "foo/a.py",
+            },
+        )
+        assert_merged(
+            {"//target0": {"a.py": "foo/a.py"}, "//target1": {"b.py": "foo/a.py"}},
+            {
+                "a.py": "foo/a.py",
+                "b.py": "foo/a.py",
+            },
+        )
+        assert_merged(
+            {
+                "//target0": {"a.py": "baz/a.py", "b.py": "baz/b.py"},
+                "//target1": {"a.py": "foo/a.py"},
+                "//target2": {"b.py": "bar/b.py"},
+            },
+            {
+                "a.py": "baz/a.py",
+                "b.py": "baz/b.py",
+            },
+        )
diff --git a/buck2/prelude/python/tools/static_extension_finder.py b/buck2/prelude/python/tools/static_extension_finder.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/static_extension_finder.py
@@ -0,0 +1,50 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+
+# Add a try except to force eager importing
+try:
+    # pyre-fixme[21]: Could not find module `_static_extension_utils`.
+    from _static_extension_utils import _check_module, StaticExtensionLoader
+except BaseException:
+    raise
+
+
+class StaticExtensionFinder:
+    # pyre-fixme
+    ModuleSpec = None
+
+    @classmethod
+    # pyre-fixme[3]: Return type must be annotated.
+    # pyre-fixme[2]: Parameter must be annotated.
+    def find_spec(cls, fullname, path, target=None):
+        """
+        Use fullname to look up the PyInit function in the main binary. Returns None if not present.
+        This allows importing CExtensions that have been statically linked in.
+        """
+
+        if not fullname:
+            return None
+        if not _check_module(fullname):
+            return None
+        spec = cls.ModuleSpec(
+            fullname, StaticExtensionLoader, origin="static-extension", is_package=False
+        )
+        return spec
+
+
+def _initialize() -> None:
+    # This imports are here to avoid tricking circular dependencies. see S389486
+    import sys
+    from importlib.machinery import ModuleSpec
+
+    StaticExtensionFinder.ModuleSpec = ModuleSpec
+
+    sys.meta_path.insert(0, StaticExtensionFinder)
diff --git a/buck2/prelude/python/tools/static_extension_utils.cpp b/buck2/prelude/python/tools/static_extension_utils.cpp
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/static_extension_utils.cpp
@@ -0,0 +1,257 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+#include <stdexcept>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+#include "Python.h"
+
+typedef PyObject* (*pyinitfunc)();
+
+typedef struct {
+} StaticExtensionFinderObject;
+
+// This map is generated at build time by generate_static_extension_info.py
+// and should not be modified at runtime.
+extern std::unordered_map<std::string_view, pyinitfunc> _static_extension_info;
+
+namespace {
+
+#if PY_VERSION_HEX < 0x030E0000
+static PyObject* _handle_single_phase_initialization(
+    PyObject* mod,
+    PyObject* name,
+    PyObject* spec,
+    pyinitfunc initfunc,
+    PyObject* modules) {
+  /* Remember pointer to module init function. */
+  PyModuleDef* def = PyModule_GetDef(mod);
+  if (def == nullptr) {
+    Py_DECREF(name);
+    return nullptr;
+  }
+  PyObject* path = PyObject_GetAttrString(spec, "origin");
+  if (PyModule_AddObject(mod, "__file__", path) < 0) {
+    PyErr_Clear();
+  } else {
+    Py_INCREF(path);
+  }
+  def->m_base.m_init = initfunc;
+  if (modules == nullptr) {
+    modules = PyImport_GetModuleDict();
+  }
+
+  int result = _PyImport_FixupExtensionObject(mod, name, name, modules);
+  Py_DECREF(path);
+  Py_DECREF(name);
+  if (result < 0) {
+    return nullptr;
+  }
+  return mod;
+}
+#endif
+
+static PyObject* _create_module(PyObject* self, PyObject* spec) {
+  PyObject* name;
+  PyObject* mod;
+
+  name = PyObject_GetAttrString(spec, "name");
+  if (name == nullptr) {
+    return nullptr;
+  }
+  // Attempt to import the module normally (builtins, etc)
+  mod = PyImport_GetModule(name);
+  if (mod || PyErr_Occurred()) {
+    Py_DECREF(name);
+    Py_XINCREF(mod);
+    return mod;
+  }
+
+  // If the module is not found, try to find it in the static extension map
+  // its generated at build time by generate_static_extension_info.py
+  const std::string namestr = PyUnicode_AsUTF8(name);
+  if (namestr.empty()) {
+    Py_DECREF(name);
+    return nullptr;
+  }
+
+  pyinitfunc initfunc = nullptr;
+  if (auto result = _static_extension_info.find(namestr);
+      result != _static_extension_info.end())
+    initfunc = result->second;
+
+  if (initfunc == nullptr) {
+    PyErr_SetString(
+        PyExc_ImportError, "Module unknown to static extension finder");
+    return nullptr;
+  }
+
+#if PY_VERSION_HEX >= 0x030E0000
+  // Python 3.14+ uses PyImport_CreateModuleFromInitfunc. This API was
+  // upstreamed in 3.15 (gh-116146) and backported to Meta Python 3.14
+  // (patched/Include/cpython/import.h). The older Meta-specific
+  // _Ci_PyImport_CreateBuiltinFromSpecAndInitfunc is now obsolete and
+  // can be avoided.
+  mod = PyImport_CreateModuleFromInitfunc(spec, initfunc);
+#elif PY_VERSION_HEX >= 0x030C0000
+  // Python 3.12-3.13: directly call the init function. Meta Python 3.12
+  // exposes a custom C-API for package context handling; there is no
+  // supported Meta/Cinder Python 3.13 build, so 3.13 falls back to the stock
+  // path.
+#if defined(META_PYTHON)
+  mod = _Ci_PyImport_CallInitFuncWithContext(namestr.c_str(), initfunc);
+#else
+  mod = initfunc();
+#endif
+#else
+  throw std::runtime_error(
+      "Native python does not support Python 3.11 and earlier.");
+#endif
+  if (mod == nullptr) {
+    Py_DECREF(name);
+    return nullptr;
+  }
+#if PY_VERSION_HEX < 0x030E0000
+  // If the result is a PyModuleDef, then this is multi-phase initialization
+  // Return the PyModule so module_exec can be called on it later
+  if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
+    Py_DECREF(name);
+    return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
+  }
+  PyObject* modules = nullptr;
+  // At this point we know this is single-phase initialization
+  return _handle_single_phase_initialization(
+      mod, name, spec, initfunc, modules);
+#else
+  return mod;
+#endif
+}
+
+static PyObject* _exec_module(PyObject* self, PyObject* module) {
+  PyModuleDef* def;
+
+  // TODO errors
+  if (!PyModule_Check(module)) {
+    // TODO
+    Py_RETURN_NONE;
+  }
+
+  def = PyModule_GetDef(module);
+  if (def == nullptr) {
+    // TODO
+    Py_RETURN_NONE;
+  }
+
+  // TODO check this result
+  PyModule_ExecDef(module, def);
+
+  Py_RETURN_NONE;
+}
+
+static PyObject* _get_source(PyObject* self, PyObject* /* module_name */) {
+  // TODO properly implement the function
+  Py_RETURN_NONE;
+}
+
+PyDoc_STRVAR(
+    StaticExtensionLoader_doc,
+    "static_extension_loader(name: str)\n\
+\n\
+a loader for extensions linked statically into the binary");
+
+static PyMethodDef StaticExtensionLoaderType_methods[] = {
+    {"create_module",
+     (PyCFunction)(void (*)(void))_create_module,
+     METH_STATIC | METH_O,
+     nullptr},
+    {"exec_module",
+     (PyCFunction)(void (*)(void))_exec_module,
+     METH_STATIC | METH_O,
+     nullptr},
+    {"get_source",
+     (PyCFunction)(void (*)(void))_get_source,
+     METH_STATIC | METH_O,
+     nullptr},
+    {}};
+
+static PyType_Slot StaticExtensionLoader_slots[] = {
+    {Py_tp_doc, (void*)StaticExtensionLoader_doc},
+    {Py_tp_methods, StaticExtensionLoaderType_methods},
+    {}};
+
+static PyType_Spec StaticExtensionLoader_spec = {
+    "static_extension_utils.StaticExtensionLoader",
+    0,
+    0,
+    Py_TPFLAGS_DEFAULT,
+    StaticExtensionLoader_slots};
+
+static int _static_extension_utils_exec(PyObject* m) {
+  PyObject* loader_type = PyType_FromSpec(&StaticExtensionLoader_spec);
+  if (loader_type == nullptr) {
+    return -1;
+  }
+  int result = PyModule_AddObject(m, "StaticExtensionLoader", loader_type);
+  if (result == -1) {
+    Py_DECREF(loader_type);
+    return -1;
+  }
+  return 0;
+}
+
+PyDoc_STRVAR(
+    _check_module_doc,
+    "Check if a module is contained in the C Extension map \n");
+
+static PyObject* _check_module(PyObject* self, PyObject* fullname) {
+  if (!PyUnicode_Check(fullname)) {
+    PyErr_SetString(PyExc_TypeError, "Expected a unicode object");
+    return nullptr;
+  }
+  const std::string modname = PyUnicode_AsUTF8(fullname);
+  if (_static_extension_info.find(modname) != _static_extension_info.end()) {
+    Py_INCREF(Py_True);
+    return Py_True;
+  }
+  Py_INCREF(Py_False);
+  return Py_False;
+}
+
+static PyModuleDef_Slot _static_extension_utils_slots[] = {
+    {Py_mod_exec, (void*)_static_extension_utils_exec},
+#ifdef Py_GIL_DISABLED
+    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
+#endif
+    {}};
+
+static PyMethodDef _static_extension_utils_methods[] = {
+    {"_check_module", _check_module, METH_O, _check_module_doc},
+    {}};
+
+PyDoc_STRVAR(
+    module_doc,
+    "Utils for importing modules statically linked into the python binary \n");
+
+static struct PyModuleDef _static_extension_utils_def = {
+    PyModuleDef_HEAD_INIT,
+    "_static_extension_utils_def",
+    module_doc,
+    0,
+    _static_extension_utils_methods,
+    _static_extension_utils_slots,
+    nullptr,
+    nullptr,
+    nullptr};
+
+PyMODINIT_FUNC PyInit__static_extension_utils(void) {
+  return PyModuleDef_Init(&_static_extension_utils_def);
+}
+} // namespace
diff --git a/buck2/prelude/python/tools/tests/gen_bytecode_bundle_test.py b/buck2/prelude/python/tools/tests/gen_bytecode_bundle_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/tests/gen_bytecode_bundle_test.py
@@ -0,0 +1,299 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+from __future__ import annotations
+
+import json
+import marshal
+import os
+import py_compile
+import tempfile
+import tracemalloc
+import unittest
+from dataclasses import dataclass
+from importlib.util import cache_from_source, MAGIC_NUMBER
+from pathlib import Path
+from types import CodeType
+
+import gen_bytecode_bundle
+
+
+@dataclass
+class Library:
+    """What one `python_library`'s `compile.py` action leaves behind."""
+
+    name: str
+    manifest: Path
+    bytecode_dir: Path
+    # Keyed by source path in the tree.
+    pycs: dict[str, Path]
+
+
+@dataclass
+class Bundle:
+    """A built bundle, split back into its four sections."""
+
+    magic: bytes
+    pyc_magic: bytes
+    index: dict[str, tuple[int, int]]
+    payload: bytes
+
+    def code(self, source_relpath: str) -> CodeType:
+        offset, size = self.index[source_relpath]
+        code = marshal.loads(self.payload[offset : offset + size])
+        assert isinstance(code, CodeType)
+        return code
+
+    def run(self, source_relpath: str) -> dict[str, object]:
+        """Execute a bundled module and return its globals."""
+        namespace: dict[str, object] = {}
+        exec(self.code(source_relpath), namespace)
+        return namespace
+
+
+class BundleTestBase(unittest.TestCase):
+    def setUp(self) -> None:
+        tmpdir = tempfile.TemporaryDirectory()
+        self.addCleanup(tmpdir.cleanup)
+        self.root = Path(tmpdir.name)
+
+    def _library(
+        self, name: str, sources: dict[str, str], pyc_field: str | None = None
+    ) -> Library:
+        """Compile one `python_library` the way `compile.py` does.
+
+        Leaves a `__pycache__` tree under the action's output directory, plus a
+        manifest of `(destination, .pyc path, source)` for what it wrote.
+        `pyc_field` overrides that middle field, which is where a real build
+        puts a content-hash placeholder.
+        """
+        bytecode_dir = self.root / name / "bytecode"
+        entries = []
+        pycs = {}
+        for source_relpath, source in sources.items():
+            src = self.root / name / "src" / source_relpath
+            src.parent.mkdir(parents=True, exist_ok=True)
+            src.write_text(source, encoding="utf8")
+
+            dest = cache_from_source(source_relpath)
+            pyc = bytecode_dir / dest
+            pyc.parent.mkdir(parents=True, exist_ok=True)
+            py_compile.compile(
+                str(src), cfile=str(pyc), dfile=source_relpath, doraise=True
+            )
+            entries.append([dest, pyc_field or str(pyc), str(src)])
+            pycs[source_relpath] = pyc
+
+        manifest = self.root / name / "bytecode.manifest"
+        manifest.write_text(json.dumps(entries), encoding="utf8")
+        return Library(name, manifest, bytecode_dir, pycs)
+
+    def _build(self, *libraries: Library) -> Path:
+        """Bundle `libraries` and return the file the tool wrote."""
+        out = self.root / "{}.bundle".format("-".join(lib.name for lib in libraries))
+        gen_bytecode_bundle.build(
+            gen_bytecode_bundle.collect(
+                [str(lib.manifest) for lib in libraries],
+                [str(lib.bytecode_dir) for lib in libraries],
+            ),
+            str(out),
+        )
+        return out
+
+    def _bundle(self, *libraries: Library) -> Bundle:
+        return self._unpack(self._build(*libraries))
+
+    @staticmethod
+    def _unpack(path: Path) -> Bundle:
+        data = path.read_bytes()
+        magic, pyc_magic_len, index_len = gen_bytecode_bundle.HEADER.unpack_from(data)
+        index_start = gen_bytecode_bundle.HEADER.size + pyc_magic_len
+        payload_start = index_start + index_len
+        return Bundle(
+            magic,
+            data[gen_bytecode_bundle.HEADER.size : index_start],
+            marshal.loads(data[index_start:payload_start]),
+            data[payload_start:],
+        )
+
+
+class SourceKeyTest(unittest.TestCase):
+    """The inverse of the `get_pyc_path` mapping `compile.py` applies."""
+
+    def test_keys_are_posix_on_every_platform(self) -> None:
+        self.assertEqual(
+            gen_bytecode_bundle.source_key(
+                cache_from_source(os.path.join("a", "b", "c", "d.py"))
+            ),
+            "a/b/c/d.py",
+        )
+
+
+class BuildTest(BundleTestBase):
+    def test_header_pins_the_format_and_interpreter(self) -> None:
+        bundle = self._bundle(self._library("lib", {"pkg/mod.py": "VALUE = 1"}))
+
+        self.assertEqual(bundle.magic, b"PYCBNDL4")
+        self.assertEqual(bundle.pyc_magic, MAGIC_NUMBER)
+
+    def test_index_is_keyed_by_path_not_by_module_name(self) -> None:
+        # `pkg.py` and `pkg/__init__.py` are the same module name and both
+        # stay, because the finder - not the packer - is what decides which one
+        # an import resolves to. The top-level `__init__.py` is one
+        # rust_make_par synthesizes for a namespace directory; whether it is
+        # importable at all is likewise not the packer's business.
+        paths = ["top.py", "__init__.py", "pkg.py", "pkg/__init__.py", "pkg/mod.py"]
+        # pyre-fixme[6]: For 2nd argument expected `Dict[str, str]` but got
+        #  `Dict[str, Literal['VALUE = 1']]`.
+        bundle = self._bundle(self._library("lib", dict.fromkeys(paths, "VALUE = 1")))
+
+        self.assertEqual(set(bundle.index), set(paths))
+
+    def test_payload_slices_unmarshal_to_runnable_code(self) -> None:
+        bundle = self._bundle(self._library("lib", {"pkg/mod.py": "VALUE = 41 + 1"}))
+
+        self.assertEqual(bundle.run("pkg/mod.py")["VALUE"], 42)
+
+    def test_code_keeps_the_tree_relative_filename(self) -> None:
+        # `BundleLoader` rewrites this to an absolute path at import time, so a
+        # bundle that shipped an absolute build path would leak it into every
+        # traceback.
+        bundle = self._bundle(self._library("lib", {"pkg/mod.py": "VALUE = 1"}))
+
+        self.assertEqual(bundle.code("pkg/mod.py").co_filename, "pkg/mod.py")
+
+    def test_bundle_is_byte_identical_regardless_of_input_order(self) -> None:
+        # The blob is a cached build artifact, so it may not depend on the
+        # order buck2 lists the libraries in, nor on the order `compile.py`
+        # happened to write entries within one.
+        modules = {
+            "a.py": "VALUE = 1",
+            "b/__init__.py": "VALUE = 2",
+            "b/c.py": "VALUE = 3",
+        }
+        forward = self._library("forward", modules)
+        backward = self._library("backward", dict(reversed(list(modules.items()))))
+        other = self._library("other", {"d.py": "VALUE = 4"})
+
+        self.assertEqual(
+            self._build(forward, other).read_bytes(),
+            self._build(other, backward).read_bytes(),
+        )
+
+    def test_duplicate_path_keeps_the_first_library(self) -> None:
+        # Two libraries can legitimately land the same path in the tree.
+        left = self._library("left", {"dup.py": "OWNER = 'left'"})
+        right = self._library("right", {"dup.py": "OWNER = 'right'"})
+
+        bundle = self._bundle(left, right)
+
+        self.assertEqual(list(bundle.index), ["dup.py"])
+        self.assertEqual(bundle.run("dup.py")["OWNER"], "left")
+
+    def test_the_pyc_path_in_the_manifest_is_never_read(self) -> None:
+        # It addresses the action's own output through an `/output_artifacts/`
+        # placeholder standing in for a content hash that does not exist while
+        # the action runs. The bytes come from the paired directory instead, so
+        # a manifest full of nonsense there still bundles correctly.
+        library = self._library(
+            "lib",
+            {"pkg/mod.py": "VALUE = 42"},
+            pyc_field="buck-out/v2/gen/fbcode/output_artifacts/aaaaaaaaaaaaaaaa/x",
+        )
+
+        self.assertEqual(self._bundle(library).run("pkg/mod.py")["VALUE"], 42)
+
+    def test_rejects_pyc_from_a_different_interpreter(self) -> None:
+        library = self._library("lib", {"mod.py": "VALUE = 1"})
+        pyc = library.pycs["mod.py"]
+        pyc.write_bytes(
+            b"\0" * len(MAGIC_NUMBER) + pyc.read_bytes()[len(MAGIC_NUMBER) :]
+        )
+
+        with self.assertRaisesRegex(ValueError, "wrong interpreter magic"):
+            self._build(library)
+
+    def test_rejects_truncated_pyc(self) -> None:
+        library = self._library("lib", {"mod.py": "VALUE = 1"})
+        pyc = library.pycs["mod.py"]
+        data = pyc.read_bytes()
+
+        for size in (
+            gen_bytecode_bundle.PYC_HEADER_LEN - 1,
+            gen_bytecode_bundle.PYC_HEADER_LEN,
+        ):
+            with self.subTest(size=size):
+                pyc.write_bytes(data[:size])
+                with self.assertRaisesRegex(
+                    ValueError, "Truncated .pyc has no bytecode payload"
+                ):
+                    self._build(library)
+
+    def test_payload_is_streamed_rather_than_buffered(self) -> None:
+        # A binary's whole bytecode must never be resident at once.
+        blob = "x" * (8 * 1024 * 1024)
+        library = self._library("large", {"large.py": f"VALUE = '{blob}'"})
+
+        # `get_traced_memory` reports the whole process, and `start()` is a
+        # no-op while tracing is already on, so measure what `_build` adds on
+        # top of what is already live rather than the absolute peak.
+        was_tracing = tracemalloc.is_tracing()
+        tracemalloc.start()
+        tracemalloc.reset_peak()
+        baseline, _peak = tracemalloc.get_traced_memory()
+        try:
+            out = self._build(library)
+            _current, peak = tracemalloc.get_traced_memory()
+        finally:
+            if not was_tracing:
+                tracemalloc.stop()
+
+        self.assertGreater(out.stat().st_size, len(blob))
+        self.assertLess(peak - baseline, len(blob) // 2)
+
+
+class CollectTest(unittest.TestCase):
+    def test_unequal_lengths_are_an_error(self) -> None:
+        # Position is the only thing tying the two lists together. If they stop
+        # lining up, every pair past the mismatch reads one library's manifest
+        # against another library's directory - silently wrong rather than
+        # broken, so refuse to build at all.
+        for manifests, dirs in ((["unused"], []), ([], ["unused"])):
+            with self.subTest(manifests=manifests, dirs=dirs):
+                with self.assertRaises(ValueError):
+                    gen_bytecode_bundle.collect(manifests, dirs)
+
+
+class MainTest(BundleTestBase):
+    def test_reads_its_inputs_from_files(self) -> None:
+        # Large binaries have thousands of libraries, well past the argv limit,
+        # so both lists arrive as files.
+        libraries = [
+            self._library("left", {"pkg/one.py": "VALUE = 1"}),
+            self._library("right", {"pkg/two.py": "VALUE = 2"}),
+        ]
+        (self.root / "manifests.txt").write_text(
+            "".join(f"{lib.manifest}\n" for lib in libraries), encoding="utf8"
+        )
+        (self.root / "artifacts.txt").write_text(
+            "".join(f"{lib.bytecode_dir}\n" for lib in libraries), encoding="utf8"
+        )
+        out = self.root / "bundle.bin"
+
+        gen_bytecode_bundle.main(
+            [
+                "gen_bytecode_bundle.py",
+                f"--output={out}",
+                f"--bytecode-manifests-from={self.root / 'manifests.txt'}",
+                f"--bytecode-artifacts-from={self.root / 'artifacts.txt'}",
+            ]
+        )
+
+        self.assertEqual(set(self._unpack(out).index), {"pkg/one.py", "pkg/two.py"})
diff --git a/buck2/prelude/python/tools/tests/main.sh b/buck2/prelude/python/tools/tests/main.sh
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/tests/main.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+set -euo pipefail
+
+TOOLS_DIR="$(dirname "$(dirname "$(realpath "$0")")")"
+export PYTHONPATH="$TOOLS_DIR"
+exec python3 -m unittest discover -s "$TOOLS_DIR/tests" -p '*_test.py'
diff --git a/buck2/prelude/python/tools/tests/make_py_package_inplace_test.py b/buck2/prelude/python/tools/tests/make_py_package_inplace_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/tests/make_py_package_inplace_test.py
@@ -0,0 +1,218 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import contextlib
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from typing import Iterator, Sequence
+
+import make_py_package_inplace
+
+TEMPLATE: Path = Path(__file__).resolve().parent.parent / "run_inplace.py.in"
+
+# An interpreter that some other rule built, as buck2 spells it: relative to the
+# project root, which is also the cwd the action runs in.
+ARTIFACT_PYTHON = "buck-out/v2/gen/toolchains/cpython/bin/python3"
+
+STUB_RUNNER = """\
+def run_as_main(main_module, main_function):
+    import runpy
+
+    runpy.run_module(main_module, run_name="__main__", alter_sys=True)
+"""
+
+APP = """\
+import os
+
+print("ran with PYTHONPATH", os.environ["PYTHONPATH"])
+"""
+
+
+@contextlib.contextmanager
+def _cwd(path: Path) -> Iterator[None]:
+    old = os.getcwd()
+    os.chdir(path)
+    try:
+        yield
+    finally:
+        os.chdir(old)
+
+
+def _make_bootstrapper(
+    project_root: Path,
+    python: str,
+    output: str = "out/bin.pex",
+    modules_dir: str = "out/bin#link-tree",
+) -> Path:
+    """Invoke the tool the way buck2 does: from the project root, with relative paths."""
+
+    argv = [
+        "make_py_package_inplace.py",
+        "--template",
+        str(TEMPLATE),
+        "--python",
+        python,
+        "--host-python",
+        sys.executable,
+        "--entry-point",
+        "app",
+        "--main-runner",
+        "stub_runner.run_as_main",
+        "--modules-dir",
+        modules_dir,
+        output,
+    ]
+
+    old_argv = sys.argv
+    sys.argv = argv
+    try:
+        with _cwd(project_root):
+            make_py_package_inplace.main()
+    finally:
+        sys.argv = old_argv
+    return project_root / output
+
+
+class ShebangTest(unittest.TestCase):
+    def test_bare_interpreter_is_left_to_env(self) -> None:
+        with tempfile.TemporaryDirectory() as tmpdir:
+            pex = _make_bootstrapper(Path(tmpdir), "python3")
+            self.assertEqual(
+                pex.read_text(encoding="utf8").splitlines()[0],
+                "#!/usr/bin/env python3",
+            )
+
+    def test_absolute_interpreter_is_used_verbatim(self) -> None:
+        with tempfile.TemporaryDirectory() as tmpdir:
+            pex = _make_bootstrapper(Path(tmpdir), "/usr/bin/python3")
+            self.assertEqual(
+                pex.read_text(encoding="utf8").splitlines()[0],
+                "#!/usr/bin/env /usr/bin/python3",
+            )
+
+    def test_artifact_interpreter_uses_sh_trampoline(self) -> None:
+        with tempfile.TemporaryDirectory() as tmpdir:
+            pex = _make_bootstrapper(Path(tmpdir), ARTIFACT_PYTHON)
+            lines = pex.read_text(encoding="utf8").splitlines()
+
+            self.assertEqual(lines[0], "#!/bin/sh")
+            self.assertIn(
+                'exec "${_self%/*}/../buck-out/v2/gen/toolchains/cpython/bin/python3"'
+                ' "$0" "$@"',
+                lines,
+            )
+
+    def test_output_holds_no_absolute_path(self) -> None:
+        # The whole point: an absolute path here is this machine's, and gets shipped to
+        # everyone else that reads the action out of the cache.
+        with tempfile.TemporaryDirectory() as tmpdir:
+            pex = _make_bootstrapper(Path(tmpdir), ARTIFACT_PYTHON)
+            self.assertNotIn(tmpdir, pex.read_text(encoding="utf8"))
+
+    def test_output_does_not_depend_on_project_root(self) -> None:
+        outputs = []
+        for name in ("short", "a/much/deeper/checkout/path"):
+            with tempfile.TemporaryDirectory() as tmpdir:
+                root = Path(tmpdir) / name
+                root.mkdir(parents=True)
+                outputs.append(_make_bootstrapper(root, ARTIFACT_PYTHON).read_bytes())
+        self.assertEqual(outputs[0], outputs[1])
+
+    def test_bootstrapper_is_valid_python(self) -> None:
+        # Windows ignores `#!` and runs the bootstrapper as `python <pex>`, so the shell
+        # trampoline has to parse as Python too.
+        with tempfile.TemporaryDirectory() as tmpdir:
+            pex = _make_bootstrapper(Path(tmpdir), ARTIFACT_PYTHON)
+            compile(pex.read_text(encoding="utf8"), str(pex), "exec")
+
+
+@unittest.skipIf(sys.platform == "win32", "no #! support on Windows")
+class TrampolineRuntimeTest(unittest.TestCase):
+    def _make_project(self, tmpdir: str, name: str = "project") -> Path:
+        root = Path(tmpdir) / name
+        (root / "out/bin#link-tree").mkdir(parents=True)
+        (root / "out/bin#link-tree/stub_runner.py").write_text(
+            STUB_RUNNER, encoding="utf8"
+        )
+        (root / "out/bin#link-tree/app.py").write_text(APP, encoding="utf8")
+
+        # Stand in for a hermetic interpreter built by some other rule.
+        (root / "buck-out/interpreter").mkdir(parents=True)
+        os.symlink(
+            os.path.realpath(sys.executable), root / "buck-out/interpreter/python3"
+        )
+
+        _make_bootstrapper(root, "buck-out/interpreter/python3")
+        return root
+
+    def _run(self, argv: Sequence[str], cwd: str) -> str:
+        proc = subprocess.run(
+            list(argv),
+            cwd=cwd,
+            capture_output=True,
+            encoding="utf8",
+        )
+        self.assertEqual(proc.returncode, 0, proc.stderr)
+        return proc.stdout
+
+    def test_runs_from_an_unrelated_cwd(self) -> None:
+        with tempfile.TemporaryDirectory() as tmpdir:
+            root = self._make_project(tmpdir)
+            out = self._run([str(root / "out/bin.pex")], cwd=tempfile.gettempdir())
+            self.assertIn(
+                "ran with PYTHONPATH {}".format(root / "out/bin#link-tree"), out
+            )
+
+    def test_runs_with_a_relative_argv0(self) -> None:
+        with tempfile.TemporaryDirectory() as tmpdir:
+            root = self._make_project(tmpdir)
+            out = self._run(["./out/bin.pex"], cwd=str(root))
+            self.assertIn(
+                "ran with PYTHONPATH {}".format(root / "out/bin#link-tree"), out
+            )
+
+    def test_runs_from_a_path_with_spaces(self) -> None:
+        with tempfile.TemporaryDirectory() as tmpdir:
+            root = self._make_project(tmpdir, name="a project")
+            out = self._run([str(root / "out/bin.pex")], cwd=tempfile.gettempdir())
+            self.assertIn(
+                "ran with PYTHONPATH {}".format(root / "out/bin#link-tree"), out
+            )
+
+    def test_runs_through_a_chain_of_symlinks(self) -> None:
+        with tempfile.TemporaryDirectory() as tmpdir:
+            root = self._make_project(tmpdir)
+            # A relative link, then an absolute one pointing at it.
+            os.symlink("out/bin.pex", root / "relative-link.pex")
+            os.symlink(root / "relative-link.pex", Path(tmpdir) / "absolute-link.pex")
+            out = self._run(
+                [str(Path(tmpdir) / "absolute-link.pex")], cwd=tempfile.gettempdir()
+            )
+            self.assertIn(
+                "ran with PYTHONPATH {}".format(root / "out/bin#link-tree"), out
+            )
+
+    def test_runs_without_a_usable_path(self) -> None:
+        # Pexes get used as build tools, where buck2 scrubs the environment. Nothing in
+        # the trampoline may depend on finding a helper on $PATH.
+        with tempfile.TemporaryDirectory() as tmpdir:
+            pex = self._make_project(tmpdir) / "out/bin.pex"
+            proc = subprocess.run(
+                [str(pex)],
+                env={},
+                capture_output=True,
+                encoding="utf8",
+            )
+            self.assertEqual(proc.returncode, 0, proc.stderr)
+            self.assertIn("ran with PYTHONPATH", proc.stdout)
diff --git a/buck2/prelude/python/tools/tests/make_py_package_manifest_module_test.py b/buck2/prelude/python/tools/tests/make_py_package_manifest_module_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/tests/make_py_package_manifest_module_test.py
@@ -0,0 +1,86 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+import make_py_package_manifest_module
+
+
+class MakePyPackageManifestModuleTest(unittest.TestCase):
+    def test_merge_entries(self) -> None:
+        entries: dict[str, object] = {
+            "fbmake": {"preserved": "base", "replaced": "old"},
+            "replaced": "old",
+        }
+
+        make_py_package_manifest_module.merge_entries(
+            entries,
+            {
+                "fbmake": {"replaced": "new"},
+                "new": "value",
+                "replaced": {"nested": True},
+            },
+        )
+
+        self.assertEqual(
+            {
+                "fbmake": {"preserved": "base", "replaced": "new"},
+                "new": "value",
+                "replaced": {"nested": True},
+            },
+            entries,
+        )
+
+    def test_main_writes_merged_json_before_module_entries(self) -> None:
+        with tempfile.TemporaryDirectory() as temp_dir:
+            root = Path(temp_dir)
+            entries = root / "entries.json"
+            overlay = root / "overlay.json"
+            module_manifest = root / "module-manifest.json"
+            module_manifests = root / "module-manifests.txt"
+            output = root / "__manifest__.py"
+            output_json = root / "__manifest__.json"
+            entries.write_text(json.dumps({"fbmake": {"preserved": "base"}}))
+            overlay.write_text(json.dumps({"fbmake": {"revision": "fresh"}}))
+            module_manifest.write_text(
+                json.dumps([["pkg/module.py", "unused", "origin"]])
+            )
+            module_manifests.write_text(str(module_manifest) + "\n")
+
+            old_argv = sys.argv
+            sys.argv = [
+                "make_py_package_manifest_module.py",
+                "--manifest-entries",
+                str(entries),
+                "--manifest-entries-overlay",
+                str(overlay),
+                "--module-manifests",
+                str(module_manifests),
+                "--output",
+                str(output),
+                "--output-json",
+                str(output_json),
+            ]
+            try:
+                make_py_package_manifest_module.main()
+            finally:
+                sys.argv = old_argv
+
+            self.assertEqual(
+                {"fbmake": {"preserved": "base", "revision": "fresh"}},
+                json.loads(output_json.read_text()),
+            )
+            module_text = output.read_text()
+            self.assertIn("'pkg.module'", module_text)
+            self.assertIn("'pkg.__init__'", module_text)
diff --git a/buck2/prelude/python/tools/tests/type_check_result_to_validation_test.py b/buck2/prelude/python/tools/tests/type_check_result_to_validation_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/tests/type_check_result_to_validation_test.py
@@ -0,0 +1,125 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import json
+import tempfile
+import unittest
+from pathlib import Path
+
+from type_check_result_to_validation import convert_type_check_result
+
+
+class ConvertTypeCheckResultTest(unittest.TestCase):
+    def _convert(self, type_check_result: object) -> dict[str, object]:
+        with tempfile.TemporaryDirectory() as tmpdir:
+            input_path = Path(tmpdir) / "type_check_result.json"
+            output_path = Path(tmpdir) / "validation.json"
+            input_path.write_text(json.dumps(type_check_result))
+            convert_type_check_result(input_path, output_path)
+            return json.loads(output_path.read_text())
+
+    def test_no_errors_produces_success(self) -> None:
+        self.assertEqual(
+            self._convert({"errors": []}),
+            {"version": 1, "data": {"status": "success"}},
+        )
+
+    def test_only_blocking_diagnostics_appear_in_failure(self) -> None:
+        result = self._convert(
+            {
+                "errors": [
+                    {"code": 0, "name": "unused-ignore"},
+                    {"code": 0, "name": "other-error"},
+                    {"code": 6, "name": "reveal-type", "severity": "info"},
+                    {"code": 6, "name": "warning-kind", "severity": "warn"},
+                    {"code": 6, "name": "ignored-error", "severity": "ignore"},
+                    {
+                        "code": 6,
+                        "name": "incompatible-variable-type",
+                        "severity": "error",
+                        "path": "foo.py",
+                        "line": 10,
+                        "column": 5,
+                        "description": "Expected int, got str",
+                    },
+                    {
+                        "code": 7,
+                        "name": "legacy-error",
+                        "path": "bar.py",
+                        "line": 20,
+                        "column": 3,
+                        "description": "Bad type",
+                    },
+                ]
+            }
+        )
+        self.assertEqual(
+            result,
+            {
+                "version": 1,
+                "data": {
+                    "status": "failure",
+                    "message": (
+                        "foo.py:10:5 Expected int, got str\nbar.py:20:3 Bad type"
+                    ),
+                },
+            },
+        )
+
+    def test_unused_ignores_never_block(self) -> None:
+        for name in ("unused-ignore", "unused-type-ignore"):
+            with self.subTest(name=name):
+                self.assertEqual(
+                    self._convert(
+                        {"errors": [{"code": -2, "name": name, "severity": "error"}]}
+                    ),
+                    {"version": 1, "data": {"status": "success"}},
+                )
+
+    def test_malformed_error_preserves_blocking_diagnostics(self) -> None:
+        result = self._convert(
+            {
+                "errors": [
+                    {"code": 6},
+                    {
+                        "code": 7,
+                        "path": "foo.py",
+                        "line": 10,
+                        "column": 5,
+                        "description": "Expected int, got str",
+                    },
+                ]
+            }
+        )
+        self.assertEqual(
+            result,
+            {
+                "version": 1,
+                "data": {
+                    "status": "failure",
+                    "message": (
+                        "foo.py:10:5 Expected int, got str\n"
+                        "Malformed type checker output"
+                    ),
+                },
+            },
+        )
+
+    def test_non_object_result_produces_failure(self) -> None:
+        self.assertEqual(
+            self._convert([]),
+            {
+                "version": 1,
+                "data": {
+                    "status": "failure",
+                    "message": "Malformed type checker output",
+                },
+            },
+        )
diff --git a/buck2/prelude/python/tools/tests/wheel_test.py b/buck2/prelude/python/tools/tests/wheel_test.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/tests/wheel_test.py
@@ -0,0 +1,75 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import csv
+import io
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+
+import wheel
+
+
+class WheelBuilderTest(unittest.TestCase):
+    def test_readme_sets_metadata_body_and_content_type(self) -> None:
+        with tempfile.TemporaryDirectory() as tmpdir:
+            tmp = Path(tmpdir)
+            output = tmp / "demo-1.0-py3-none-any.whl"
+            readme = tmp / "README.md"
+            module = tmp / "demo.py"
+
+            readme.write_text("# Demo\n\nLong description.\n", encoding="utf-8")
+            module.write_text("print('ok')\n", encoding="utf-8")
+
+            with wheel.WheelBuilder(
+                name="demo",
+                version="1.0",
+                output=str(output),
+                readme=str(readme),
+            ) as whl:
+                whl.write("demo.py", str(module))
+
+            with zipfile.ZipFile(output) as archive:
+                metadata = archive.read("demo-1.0.dist-info/METADATA").decode("utf-8")
+
+            self.assertIn("Description-Content-Type: text/markdown\n", metadata)
+            self.assertTrue(metadata.endswith("\n# Demo\n\nLong description.\n"))
+
+    def test_record_round_trips_paths_containing_commas(self) -> None:
+        # Resource filenames with commas are real: vLLM ships fused-MoE configs
+        # named like `E=128,N=768,device_name=NVIDIA_H100.json`.
+        comma_path = "demo/E=128,N=768,device_name=X.json"
+
+        with tempfile.TemporaryDirectory() as tmpdir:
+            tmp = Path(tmpdir)
+            output = tmp / "demo-1.0-py3-none-any.whl"
+            plain = tmp / "demo.py"
+            config = tmp / "config.json"
+
+            plain.write_text("print('ok')\n", encoding="utf-8")
+            config.write_text("{}\n", encoding="utf-8")
+
+            with wheel.WheelBuilder(
+                name="demo", version="1.0", output=str(output)
+            ) as whl:
+                whl.write("demo.py", str(plain))
+                whl.write(comma_path, str(config))
+
+            with zipfile.ZipFile(output) as archive:
+                record = archive.read("demo-1.0.dist-info/RECORD").decode("utf-8")
+
+            rows = [row for row in csv.reader(io.StringIO(record)) if row]
+            self.assertTrue(all(len(row) == 3 for row in rows), record)
+            paths = [row[0] for row in rows]
+            self.assertIn(comma_path, paths)
+            # Paths needing no quoting stay byte-identical to the plain form,
+            # so this change is inert for wheels that have no such filenames.
+            self.assertIn("demo.py,,\n", record)
diff --git a/buck2/prelude/python/tools/type_check_result_to_validation.py b/buck2/prelude/python/tools/type_check_result_to_validation.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/type_check_result_to_validation.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# pyre-strict
+
+import argparse
+import json
+from pathlib import Path
+from typing import Any
+
+
+def convert_type_check_result(input_path: Path, output_path: Path) -> None:
+    """Convert a Python type-check result to Buck2's ValidationSpec format."""
+    validation: dict[str, object] = {
+        "version": 1,
+        "data": {"status": "success"},
+    }
+
+    try:
+        with input_path.open() as input_file:
+            data: Any = json.load(input_file)
+    except (OSError, json.JSONDecodeError):
+        validation["data"] = {
+            "status": "failure",
+            "message": "Failed to read type checker output",
+        }
+    else:
+        messages = []
+        malformed = False
+        errors = data.get("errors", []) if isinstance(data, dict) else None
+        if not isinstance(errors, list):
+            errors = []
+            malformed = True
+
+        for error in errors:
+            if not isinstance(error, dict) or "code" not in error:
+                malformed = True
+                continue
+            if (
+                error["code"] == 0
+                or error.get("name") in ("unused-ignore", "unused-type-ignore")
+                or error.get("severity") in ("info", "ignore", "warn")
+            ):
+                continue
+            try:
+                messages.append(
+                    f"{error['path']}:{error['line']}:{error['column']} {error['description']}"
+                )
+            except KeyError:
+                malformed = True
+
+        if malformed:
+            messages.append("Malformed type checker output")
+        if messages:
+            validation["data"] = {
+                "status": "failure",
+                "message": "\n".join(messages),
+            }
+
+    with output_path.open("w") as output_file:
+        json.dump(validation, output_file)
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("input", type=Path, help="Path to type_check_result.json")
+    parser.add_argument(
+        "--output",
+        type=Path,
+        required=True,
+        help="Path to write ValidationSpec JSON",
+    )
+    args = parser.parse_args()
+    convert_type_check_result(args.input, args.output)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/python/tools/wheel.py b/buck2/prelude/python/tools/wheel.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/tools/wheel.py
@@ -0,0 +1,256 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+from __future__ import annotations
+
+# pyre-strict
+
+import argparse
+import configparser
+import contextlib
+import csv
+import io
+import json
+import os
+import re
+import shutil
+import sys
+import zipfile
+from types import TracebackType
+from typing import cast
+
+
+def normalize_name(name: str) -> str:
+    """
+    Per:
+      * https://packaging.python.org/en/latest/specifications/recording-installed-packages/#the-dist-info-directory
+      * https://packaging.python.org/en/latest/specifications/name-normalization/
+    Normalize package names according to PEP503 then replace "-" with "_" as to not conflict with the "-" separating
+    the name of the package with the version specification.
+
+    Example: "torch-nightly" normalizes to "torch_nightly.dist-info/" and "torch_nightly.data/"
+    """
+    pep503_normalized_name = re.sub(r"[-_.]+", "-", name).lower()
+    return pep503_normalized_name.replace("-", "_")
+
+
+def readme_content_type(path: str) -> str:
+    _, ext = os.path.splitext(path.lower())
+    if ext in (".md", ".markdown"):
+        return "text/markdown"
+    if ext == ".rst":
+        return "text/x-rst"
+    return "text/plain"
+
+
+# pyre-fixme[24]: Generic type `AbstractContextManager` expects 1 type parameter.
+class WheelBuilder(contextlib.AbstractContextManager):
+    def __init__(
+        self,
+        *,
+        name: str,
+        version: str,
+        output: str,
+        python_tag: str = "py3",
+        abi_tag: str = "none",
+        platform_tag: str = "any",
+        entry_points: dict[str, str] | None = None,
+        metadata: list[tuple[str, str]] | None = None,
+        readme: str | None = None,
+    ) -> None:
+        self._name = name
+
+        self._normalized_name: str = normalize_name(name)
+
+        # TODO normalize version like we normalized name above
+        #  can follow pypi/packaging.utils.canonicalize_version (see: https://fburl.com/code/amuvl3d2)
+        #  punted for later since it was not a clean copy/paste and
+        #  taking a dep to tp from toolchains is not straightforward
+        self._version = version
+        self._python_tag = python_tag
+        self._abi_tag = abi_tag
+        self._platform_tag = platform_tag
+        self._record: list[str] = []
+        self._outf = zipfile.ZipFile(output, mode="w")
+        self._entry_points: dict[str, str] | None = entry_points
+        self._metadata: list[tuple[str, str]] = []
+        self._readme = readme
+        self._metadata.append(("Name", name))
+        self._metadata.append(("Version", version))
+        if readme is not None:
+            self._metadata.append(
+                ("Description-Content-Type", readme_content_type(readme))
+            )
+        if metadata is not None:
+            self._metadata.extend(metadata)
+
+    def _dist_info(self, *path: str) -> str:
+        return os.path.join(f"{self._normalized_name}-{self._version}.dist-info", *path)
+
+    def _data(self, *path: str) -> str:
+        return os.path.join(f"{self._normalized_name}-{self._version}.data", *path)
+
+    def write(self, dst: str, src: str) -> None:
+        if os.path.isdir(src):
+            for root, _, files in os.walk(src):
+                for file in files:
+                    file_src = os.path.join(root, file)
+                    file_dst = os.path.join(dst, os.path.relpath(file_src, src))
+                    self.write(file_dst, file_src)
+        else:
+            self._record.append(dst)
+            zinfo = zipfile.ZipInfo.from_file(
+                filename=src,
+                arcname=dst,
+                # Allow older timestamps, as we're gonna overwrite them below anyway.
+                strict_timestamps=False,
+            )
+            zinfo.date_time = (1980, 1, 1, 0, 0, 0)
+            with open(src, "rb") as fsrc, self._outf.open(zinfo, "w") as fdst:
+                shutil.copyfileobj(fsrc, fdst, 1024 * 8)
+
+    def write_data(self, dst: str, src: str) -> None:
+        self.write(self._data(dst), src)
+
+    def writestr(self, dst: str, contents: str) -> None:
+        self._record.append(dst)
+        self._outf.writestr(
+            zinfo_or_arcname=zipfile.ZipInfo(filename=dst),
+            data=contents,
+        )
+
+    def _write_record(self) -> None:
+        record = self._dist_info("RECORD")
+        # RECORD is CSV, so a path containing a comma has to be quoted or it
+        # parses as extra fields and strict installers reject the wheel. For
+        # paths needing no quoting csv.writer emits exactly `path,,`.
+        buf = io.StringIO()
+        writer = csv.writer(buf, lineterminator="\n")
+        for path in self._record + [record]:
+            writer.writerow([path, "", ""])
+        self._outf.writestr(
+            zinfo_or_arcname=zipfile.ZipInfo(filename=record),
+            data=buf.getvalue(),
+        )
+
+    def close(self) -> None:
+        metadata = "".join([f"{key}: {val}\n" for key, val in self._metadata])
+        if self._readme is not None:
+            with open(self._readme, encoding="utf-8") as readme:
+                metadata += "\n" + readme.read()
+
+        self.writestr(
+            self._dist_info("METADATA"),
+            metadata,
+        )
+
+        # Determine Root-Is-Purelib based on platform tag
+        # Pure Python wheels use platform "any", platform-specific wheels are not purelib
+        root_is_purelib = "true" if self._platform_tag == "any" else "false"
+
+        self.writestr(
+            self._dist_info("WHEEL"),
+            f"""\
+Wheel-Version: 1.0
+Generator: buck2
+Root-Is-Purelib: {root_is_purelib}
+Tag: {self._python_tag}-{self._abi_tag}-{self._platform_tag}
+""",
+        )
+
+        # Write entry points.
+        if self._entry_points is not None:
+            config = configparser.ConfigParser()
+            config.read_dict(cast(dict[str, dict[str, str]], self._entry_points))
+            with io.TextIOWrapper(
+                self._outf.open(self._dist_info("entry_points.txt"), mode="w"),
+                encoding="utf-8",
+            ) as f:
+                config.write(f)
+
+        self._write_record()
+        self._outf.close()
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        exc_tb: TracebackType | None,
+    ) -> None:
+        self.close()
+
+
+def main(argv: list[str]) -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--output", required=True)
+    parser.add_argument("--name", required=True)
+    parser.add_argument("--version", required=True)
+    parser.add_argument("--python-tag", default="py3")
+    parser.add_argument("--abi-tag", default="none")
+    parser.add_argument("--platform-tag", default="any")
+    parser.add_argument("--entry-points", default=None)
+    parser.add_argument("--manifest", dest="manifests", action="append", default=[])
+    parser.add_argument(
+        "--src-path", nargs=2, dest="src_paths", action="append", default=[]
+    )
+    parser.add_argument("--metadata", nargs=2, action="append", default=[])
+    parser.add_argument("--readme", default=None)
+    parser.add_argument("--data", nargs=2, action="append", default=[])
+    args = parser.parse_args(argv[1:])
+
+    pkgs: set[str] = set()
+    pkgs_with_init = set()
+
+    def _add_pkg(pkg: str) -> None:
+        # root (of 'site-packages/') should not be considered a pkg
+        if not pkg:
+            return
+
+        pkgs.add(pkg)
+        parent = os.path.dirname(pkg)
+        _add_pkg(parent)
+
+    with WheelBuilder(
+        name=args.name,
+        version=args.version,
+        output=args.output,
+        python_tag=args.python_tag,
+        abi_tag=args.abi_tag,
+        platform_tag=args.platform_tag,
+        entry_points=(
+            json.loads(args.entry_points) if args.entry_points is not None else None
+        ),
+        metadata=args.metadata,
+        readme=args.readme,
+    ) as whl:
+        all_srcs = {}
+        for src in args.manifests:
+            with open(src) as f:
+                manifest = json.load(f)
+            for dst, src, *_ in manifest:
+                all_srcs[dst] = src
+        for dst, src in args.src_paths:
+            all_srcs[dst] = src
+
+        for dst, src in sorted(all_srcs.items()):
+            if dst.endswith((".py", ".so")):
+                pkg = os.path.dirname(dst)
+                _add_pkg(pkg)
+                if os.path.basename(dst) == "__init__.py":
+                    pkgs_with_init.add(pkg)
+            whl.write(dst, src)
+
+        for pkg in sorted(pkgs - pkgs_with_init):
+            whl.writestr(os.path.join(pkg, "__init__.py"), "")
+
+        for dst, src in args.data:
+            whl.write_data(dst, src)
+
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv))
diff --git a/buck2/prelude/python/transitions.bzl b/buck2/prelude/python/transitions.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/transitions.bzl
@@ -0,0 +1,122 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Apply python specific constraints such as opt-by-default
+"""
+
+load("@prelude//cfg/modifier:name.bzl", "cfg_name")
+
+# This is used in prelude//transitions:constraints_override.bzl
+def _transition_opt_by_default_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:
+    constraints = platform.configuration.constraints
+    linux_key = refs._opt_by_default__linux[ConstraintValueInfo].setting.label
+
+    # if not linux cancel the transition
+    if linux_key not in constraints or constraints[linux_key].label != refs._opt_by_default__linux[ConstraintValueInfo].label:
+        return platform
+
+    if refs._opt_by_default__opt[ConstraintValueInfo].setting.label not in constraints:
+        return platform
+
+    # if this is an execution platform then cancel the transition
+    if refs._opt_by_default__execution_platform_marker[ConstraintValueInfo].setting.label in constraints:
+        return platform
+
+    # check if native debug is enabled, if so cancel the transition
+    maybe_native_debug_constraints = getattr(constraints.get(refs._opt_by_default_native_debug_enabled[ConstraintValueInfo].setting.label), "label", None)
+    if maybe_native_debug_constraints == refs._opt_by_default_native_debug_enabled[ConstraintValueInfo].label:
+        return platform
+
+    mode_constraint = constraints[refs._opt_by_default__opt[ConstraintValueInfo].setting.label].label
+    is_dev = mode_constraint == refs._opt_by_default__dev[ConstraintValueInfo].label
+
+    # This transition upgrades dev to opt: cancel it unless the build mode is
+    # dev. In particular, an opt configuration is left untouched so that python
+    # targets and their dependencies share the configuration -- and its
+    # outputs -- with everything else built in that opt configuration.
+    if not is_dev:
+        return platform
+
+    no_san_label = refs._opt_by_default__no_san[ConstraintValueInfo].setting.label
+    sanitizer_constraint = constraints[no_san_label].label if no_san_label in constraints else None
+    is_default_dev_sanitizer = (
+        sanitizer_constraint == refs._opt_by_default__dev_san[ConstraintValueInfo].label
+    )  # this bad boy only shows up in default dev mode 🙏
+    is_no_san = sanitizer_constraint == refs._opt_by_default__no_san[ConstraintValueInfo].label
+
+    if not (is_default_dev_sanitizer or is_no_san):
+        # dev-tsan/dev-asan etc modes still appear as dev, here we check that the user has not specifically requested sanitizers
+        # returning here preserves the original behaviour of opt-by-default, but we can likely give a opt + sanitizer config here later
+        return platform
+
+    # if opt-by-default is not enabled then cancel the transition
+    if not attrs.opt_by_default_enabled:
+        return platform
+
+    # Dev: apply the constraint values the opt mode sets, and nothing else, so
+    # the result is as close to a plain opt configuration as possible. Values
+    # an opt configuration derives from these (native linking, split debug info
+    # handling) follow the same way they do in opt.
+    #
+    # `default_opt_cxx[enabled]` is required on top of `opt`, not redundant with
+    # it: a mode file that sets `fbcode.build_mode_partially_selectified_test_label`
+    # (dev-nosan and every other partially selectified mode) pins the fbcode C/C++
+    # toolchain's mode at loading time, so `core_build_mode[opt]` alone leaves the
+    # deps compiling with the dev mode's flags -- no `-DNDEBUG` -- while targets
+    # that select on the opt constraint themselves do get it, which breaks the
+    # link (e.g. rocksdb's `TEST_SYNC_POINT`).
+    #
+    # The default python package style is deliberately not forced to the opt
+    # value: the python target itself is configured with the transitioned
+    # configuration, so that would also repackage dev python binaries as
+    # standalone.
+    opt_by_default_constraints = [
+        refs._opt_by_default__fbcode_build_info_mode_full[ConstraintValueInfo],
+        refs._opt_by_default__static[ConstraintValueInfo],
+        refs._opt_by_default__opt_cxx_enabled[ConstraintValueInfo],
+        refs._opt_by_default__no_san[ConstraintValueInfo],
+        refs._opt_by_default__opt[ConstraintValueInfo],
+    ]
+    for constraint in opt_by_default_constraints:
+        constraints[constraint.setting.label] = constraint
+
+    new_cfg = ConfigurationInfo(
+        constraints = constraints,
+        values = platform.configuration.values,
+    )
+
+    return PlatformInfo(
+        label = cfg_name(new_cfg),
+        configuration = new_cfg,
+    )
+
+def _refs():
+    return {
+        "_opt_by_default__dev": "@config//build_mode/constraints:dev",
+        "_opt_by_default__dev_san": "@config//build_mode:sanitizer_type[asan-ubsan-dev]",
+        "_opt_by_default__execution_platform_marker": "@config//platform/execution/constraints:execution-platform-transitioned",
+        "_opt_by_default__fbcode_build_info_mode_full": "@config//build_mode/constraints:fbcode-build-info-mode[full]",
+        "_opt_by_default__linux": "@config//os/constraints:linux",
+        "_opt_by_default__no_san": "@config//build_mode:sanitizer_type[no-san]",
+        "_opt_by_default__opt": "@config//build_mode/constraints:opt",
+        "_opt_by_default__opt_cxx_enabled": "@config//build_mode/default_opt_cxx:enabled",
+        "_opt_by_default__static": "@config//build_mode/constraints:default_link_style[static]",
+        "_opt_by_default_native_debug_enabled": "@config//build_mode/constraints:native-debugging[supported]",
+    }
+
+def _attrs():
+    return {
+        "opt_by_default_enabled": attrs.bool(default = False),
+    }
+
+python_transitions = struct(
+    transition_opt_by_default_impl = _transition_opt_by_default_impl,
+    attrs = _attrs,
+    refs = _refs,
+)
diff --git a/buck2/prelude/python/typecheck/batch.bxl b/buck2/prelude/python/typecheck/batch.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/typecheck/batch.bxl
@@ -0,0 +1,107 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//python/sourcedb:filter.bxl", "BUCK_PYTHON_RULE_KINDS")
+load("@prelude//utils:utils.bzl", "flatten")
+
+def _check_targets_batched(ctx: bxl.Context, checked_targets: list[Label]) -> typing.Any:
+    build_result = ctx.build(checked_targets)
+    output = ctx.output.ensure_multiple(build_result)
+    return {label.raw_target(): [artifact.rel_path() for artifact in artifacts] for label, artifacts in output.items()}
+
+def _is_python_target(rule_type: str) -> bool:
+    for kind in BUCK_PYTHON_RULE_KINDS:
+        if rule_type.endswith(kind):
+            return True
+    return False
+
+def _should_type_check_unconfigured(unconfigured_target: bxl.UnconfiguredTargetNode) -> bool:
+    return _is_python_target(unconfigured_target.rule_type)
+
+def _should_type_check_configured(configured_target: bxl.ConfiguredTargetNode, analysis_result: bxl.AnalysisResult) -> bool:
+    # NOTE(grievejia): This is NOT the same as `configured_target.sources()`.
+    # See https://fb.workplace.com/groups/617497306123691/permalink/1104965664043517/
+    srcs = configured_target.get_attr("srcs")
+    return (
+        # NOTE(grievejia): This is NOT the same as checking `srcs` on the unconfigured target, as
+        # empty `srcs` on unconfigured target does not necessarily imply empty `srcs` on configured
+        # target (due to, e.g. `select()`).
+        srcs != None and len(srcs) > 0 and "typecheck" in analysis_result.providers()[DefaultInfo].sub_targets
+    )
+
+def _filter_unconfigured_targets(targets: bxl.UnconfiguredTargetSet) -> list[bxl.UnconfiguredTargetNode]:
+    return [target for target in targets if _should_type_check_unconfigured(target)]
+
+def filter_and_get_typecheck_subtargets(ctx: bxl.Context, targets: bxl.UnconfiguredTargetSet) -> list[Label]:
+    unconfigured_targets = _filter_unconfigured_targets(targets)
+    configured_targets = ctx.configured_targets(unconfigured_targets, modifiers = ctx.modifiers)
+    analysis_results = ctx.analysis(configured_targets)
+
+    return [
+        configured_target.label.with_sub_target("typecheck")
+        for configured_target in configured_targets
+        if _should_type_check_configured(configured_target, analysis_results[configured_target.label.with_sub_target()])
+    ]
+
+def filter_and_get_typecheck_subtargets_keep_going(ctx: bxl.Context, targets: bxl.UnconfiguredTargetSet) -> list[Label]:
+    unconfigured_targets = _filter_unconfigured_targets(targets)
+
+    configured_targets = []
+    errors = []  # TODO: collect the errors and print them at the end
+    for t in unconfigured_targets:
+        result = ctx.lazy.configured_target_node(t, modifiers = ctx.modifiers).catch().resolve()
+        if result.is_ok():
+            configured_targets.append(result.unwrap())
+        else:
+            errors.append(result.unwrap_err())
+
+    analysis_results = ctx.analysis(configured_targets)
+
+    return [
+        configured_target.label.with_sub_target("typecheck")
+        for configured_target in configured_targets
+        if _should_type_check_configured(configured_target, analysis_results[configured_target.label.with_sub_target()])
+    ]
+
+def check_targets(ctx: bxl.Context, targets: bxl.UnconfiguredTargetSet) -> None:
+    if ctx.cli_args.keep_going:
+        checked_targets = filter_and_get_typecheck_subtargets_keep_going(ctx, targets)
+    else:
+        checked_targets = filter_and_get_typecheck_subtargets(ctx, targets)
+    artifacts = _check_targets_batched(ctx, checked_targets)
+
+    ctx.output.print_json(
+        {
+            "artifacts": artifacts,
+            "root": ctx.root(),
+        },
+    )
+
+def _run_entry_point(ctx: bxl.Context) -> None:
+    targets = flatten(ctx.cli_args.target)
+    check_targets(ctx, ctx.unconfigured_targets(targets))
+
+run = bxl_main(
+    doc = "Run [typecheck] on a set of targets or target patterns.",
+    impl = _run_entry_point,
+    cli_args = {
+        "enable-sharding": cli_args.bool(
+            default = False,
+            doc = "Shard type checking within each target",
+        ),
+        "keep-going": cli_args.bool(
+            default = False,
+            doc = "Keep going on unconfigured target failures",
+        ),
+        "target": cli_args.list(
+            cli_args.target_expr(
+                doc = "Target pattern to run type checking on",
+            ),
+        ),
+    },
+)
diff --git a/buck2/prelude/python/typecheck/batch_files.bxl b/buck2/prelude/python/typecheck/batch_files.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/typecheck/batch_files.bxl
@@ -0,0 +1,30 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":batch.bxl", "check_targets")
+
+def _run_entry_point(ctx: bxl.Context) -> None:
+    targets = ctx.uquery().owner(ctx.cli_args.source)
+    check_targets(ctx, targets)
+
+run = bxl_main(
+    doc = "Run [typecheck] on the owning targets of given files.",
+    impl = _run_entry_point,
+    cli_args = {
+        "client-metadata": cli_args.option(cli_args.string(doc = "Passed through to buck as --client-metadata")),
+        "keep-going": cli_args.bool(
+            default = False,
+            doc = "Keep going on unconfigured target failures",
+        ),
+        "source": cli_args.list(
+            cli_args.string(
+                doc = "Files whose owning targets need to be checked",
+            ),
+        ),
+    },
+)
diff --git a/buck2/prelude/python/typing.bzl b/buck2/prelude/python/typing.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/typing.bzl
@@ -0,0 +1,234 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//python:python.bzl", "PythonLibraryInfo")
+# @oss-disable[end= ]: load("@prelude//python/meta_only:config.bzl", "DEFAULT_PY_VERSION")
+load(":internal_tools.bzl", "PythonInternalToolsInfo")
+load(
+    ":manifest.bzl",
+    "ManifestInfo",  # @unused Used as a type
+    "create_manifest_for_entries",
+)
+load(":python.bzl", "PythonLibraryManifestsTSet")
+
+DEFAULT_PY_VERSION = "3.12" # @oss-enable
+
+# Best-effort guess on what the host sys.platform is
+def get_default_sys_platform() -> str | None:
+    os_info = host_info().os
+    if os_info.is_linux:
+        return "linux"
+    elif os_info.is_macos:
+        return "darwin"
+    elif os_info.is_windows:
+        return "win32"
+    return None
+
+def _create_all_dep_manifests(source_manifests: list[Artifact], dep_manifests: typing.Any) -> typing.Any:
+    return source_manifests + [dep for dep in dep_manifests.traverse() if dep]
+
+def _create_batched_type_check(
+    ctx: AnalysisContext,
+    executable: RunInfo,
+    typeshed_manifest: Artifact,
+    py_version: str | None,
+    source_manifests: list[Artifact],
+    dep_manifests: typing.Any,
+    hidden: typing.Any,
+    is_sharded_fallback: bool,
+) -> Artifact:
+    # Create input configs
+    input_config = {
+        "dependencies": dep_manifests,
+        "py_version": py_version or DEFAULT_PY_VERSION,
+        "sources": source_manifests,
+        "system_platform": get_default_sys_platform(),
+        "typeshed": typeshed_manifest,
+    }
+
+    file_suffix = "_sharding_fallback" if is_sharded_fallback else ""
+
+    input_file = ctx.actions.write_json(
+        "type_check_config{}.json".format(file_suffix),
+        input_config,
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+    output_file = ctx.actions.declare_output("type_check_result{}.json".format(file_suffix), has_content_based_path = False)
+    cmd = cmd_args(
+        executable,
+        input_file,
+        "--output",
+        output_file.as_output(),
+        hidden = hidden,
+    )
+
+    identifier = "_sharding_fallback" if is_sharded_fallback else "batched"
+    ctx.actions.run(cmd, category = "type_check", identifier = identifier)
+
+    return output_file
+
+def _create_sharded_type_check(
+    ctx: AnalysisContext,
+    executable: RunInfo,
+    typeshed_manifest: Artifact,
+    py_version: str | None,
+    source_manifests: list[Artifact],
+    source_artifacts: list[typing.Any],
+    dep_manifests: typing.Any,
+    hidden: typing.Any,
+    sharding_enabled: bool | None,
+) -> dict[str, list[DefaultInfo]]:
+    if not sharding_enabled:
+        return {
+            "shard_default": [
+                DefaultInfo(
+                    default_output = _create_batched_type_check(
+                        ctx,
+                        executable,
+                        typeshed_manifest,
+                        py_version,
+                        source_manifests,
+                        dep_manifests,
+                        hidden,
+                        True,
+                    )
+                )
+            ],
+        }
+
+    commands = {}
+    output_files = []
+    all_dep_manifests = _create_all_dep_manifests(source_manifests, dep_manifests)
+    for shard in source_artifacts:
+        artifact_project_path, artifact_cell_path = shard
+        sanitized_path = artifact_cell_path.replace("/", "+")
+        shard_name = "shard_{}".format(sanitized_path)
+
+        shard_manifest = create_manifest_for_entries(
+            ctx,
+            shard_name,
+            [(artifact_cell_path, artifact_project_path, "sharding")],
+        )
+
+        # Create input configs
+        input_config = {
+            "dependencies": all_dep_manifests,
+            "py_version": py_version or DEFAULT_PY_VERSION,
+            "sources": [shard_manifest.manifest],
+            "system_platform": get_default_sys_platform(),
+            "typeshed": typeshed_manifest,
+        }
+
+        input_file_name = "type_checking_config_shard_{}.json".format(sanitized_path)
+        output_file_name = "type_check_result_shard_{}.json".format(sanitized_path)
+        input_file = ctx.actions.write_json(
+            input_file_name,
+            input_config,
+            with_inputs = True,
+            has_content_based_path = False,
+        )
+        output_file = ctx.actions.declare_output(output_file_name, has_content_based_path = False)
+        output_files.append(output_file)
+
+        cmd = cmd_args(
+            executable,
+            input_file,
+            "--output",
+            output_file.as_output(),
+            hidden = hidden,
+        )
+        ctx.actions.run(cmd, category = "type_check", identifier = shard_name)
+        commands[shard_name] = [DefaultInfo(default_output = output_file)]
+
+    return commands
+
+def create_type_check_validation(ctx: AnalysisContext, type_check_result: Artifact) -> Artifact:
+    """Create a separate action converting type check result to ValidationSpec JSON.
+
+    This must be a separate action because ValidationSpec requires the validation
+    result artifact to be the sole output of its producing action.
+    """
+    validation_output = ctx.actions.declare_output("type_check_validation.json", has_content_based_path = False)
+    cmd = cmd_args(
+        ctx.attrs._python_internal_tools[PythonInternalToolsInfo].type_check_result_to_validation,
+        type_check_result,
+        "--output",
+        validation_output.as_output(),
+    )
+    ctx.actions.run(cmd, category = "type_check_validation")
+    return validation_output
+
+def create_per_target_type_check(
+    ctx: AnalysisContext,
+    executable: RunInfo,
+    srcs: ManifestInfo | None,
+    deps: list[PythonLibraryInfo],
+    typeshed: ManifestInfo | None,
+    py_version: str | None,
+    typing_enabled: bool,
+    sharding_enabled: bool | None = None,
+) -> DefaultInfo:
+    if not typing_enabled:
+        # Use empty dict to signal that no type checking was performed.
+        empty_result = ctx.attrs._python_internal_tools[PythonInternalToolsInfo].empty_typing_result
+        return DefaultInfo(
+            default_output = empty_result,
+            sub_targets = {
+                "shard_default": [DefaultInfo(default_output = empty_result)],
+            },
+        )
+
+    hidden = []
+
+    # Dep artifacts
+    dep_manifest_tset = ctx.actions.tset(
+        PythonLibraryManifestsTSet,
+        children = [d.manifests for d in deps],
+    )
+    dep_manifests = dep_manifest_tset.project_as_args("source_type_manifests")
+    hidden.append(dep_manifest_tset.project_as_args("source_type_artifacts"))
+
+    # Typeshed artifacts
+    if typeshed != None:
+        hidden.extend([a for a, _ in typeshed.artifacts])
+        typeshed_manifest = typeshed.manifest
+    else:
+        typeshed_manifest = None
+
+    # Source artifacts
+    source_manifests = []
+    source_artifacts = []
+    if srcs != None:
+        source_manifests = [srcs.manifest]
+        source_artifacts = srcs.artifacts
+        hidden.extend([a for a, _ in srcs.artifacts])
+
+    return DefaultInfo(
+        default_output = _create_batched_type_check(
+            ctx,
+            executable,
+            typeshed_manifest,
+            py_version,
+            source_manifests,
+            dep_manifests,
+            hidden,
+            False,
+        ),
+        sub_targets = _create_sharded_type_check(
+            ctx,
+            executable,
+            typeshed_manifest,
+            py_version,
+            source_manifests,
+            source_artifacts,
+            dep_manifests,
+            hidden,
+            sharding_enabled,
+        ),
+    )
diff --git a/buck2/prelude/python/versions.bzl b/buck2/prelude/python/versions.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python/versions.bzl
@@ -0,0 +1,109 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+LibraryVersion = record(value = str)
+LibraryName = record(value = str)
+
+VersionedDependency = record(
+    default_version = LibraryVersion,
+    name = LibraryName,
+    versions = dict[LibraryVersion, Dependency],
+)
+
+VersionedDependenciesInfo = provider(
+    doc = """
+        Represents all available versioned libraries in the current target and its recursive dependencies.
+    """,
+    fields = {
+        "dependencies": provider_field(dict[LibraryName, VersionedDependency]),
+    },
+)
+
+def gather_versioned_dependencies(raw_deps: list[Dependency]) -> VersionedDependenciesInfo:
+    vdeps = {}
+    for dep in raw_deps:
+        if VersionedDependenciesInfo not in dep:
+            continue
+        info = dep[VersionedDependenciesInfo]
+        for name in info.dependencies:
+            vdep = info.dependencies[name]
+
+            # NOTE: versioned deps with the same name should always be the same
+            if name in vdeps and vdeps[name] != vdep:
+                fail("Found conflicting contents of versioned dependency '{}'".format(name))
+            vdeps[name] = vdep
+    return VersionedDependenciesInfo(dependencies = vdeps)
+
+def resolve_versions(versioned_deps: VersionedDependenciesInfo, version_selections: dict[LibraryName, LibraryVersion]) -> list[Dependency]:
+    deps = {}
+    for name in versioned_deps.dependencies:
+        vdep = versioned_deps.dependencies[name]
+        ver = version_selections.get(name, vdep.default_version)
+        if ver not in vdep.versions:
+            fail(
+                "No such version for dependency '{}': '{}'. Available versions: {}".format(
+                    name,
+                    ver.value,
+                    vdep.versions.keys(),
+                )
+            )
+        deps[name] = vdep.versions[ver]
+
+    # validate version_selections
+    for name in version_selections:
+        if name not in deps:
+            fail(
+                "No such versioned dependency: '{}'. Available choices: {}".format(
+                    name,
+                    [name.value for name in deps.keys()],
+                )
+            )
+
+    return deps.values()
+
+def _versioned_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    if ctx.label == None:
+        fail("Versioned libraries are not supported for `dynamic_output`")
+    name = LibraryName(value = ctx.label.name)
+    default = LibraryVersion(value = ctx.attrs.default)
+    versions = {LibraryVersion(value = key): ctx.attrs.versions[key] for key in ctx.attrs.versions}
+
+    if default not in versions:
+        fail("Default version ({}) is not present. Available versions: {}".format(default, versions.keys()))
+
+    return [
+        DefaultInfo(),
+        VersionedDependenciesInfo(
+            dependencies = {
+                name: VersionedDependency(
+                    name = name,
+                    versions = versions,
+                    default_version = default,
+                ),
+            }
+        ),
+    ]
+
+versioned_library = rule(
+    doc = """
+        Represents multiple versions of the same library. This is a less flexible option than simply using [`select()`](https://buck2.build/docs/rule_authors/configurations/) in `deps` attributes of targets, and setting the right constraints on the build to allow [select resolution](https://buck2.build/docs/rule_authors/configurations_by_example/) to resolve the desired version.
+
+        Most notably, `versioned_library` can only be used with rules that specifically support it, unlike `select()`s which work with every rule.
+    """,
+    impl = _versioned_library_impl,
+    attrs = {
+        "default": attrs.string(
+            doc = "The default version to use, if nothing is specified. Must match a key in `versions`.",
+        ),
+        "versions": attrs.dict(
+            key = attrs.string(),
+            value = attrs.dep(),
+            doc = "A dictionary that maps versions to existing targets.",
+        ),
+    },
+)
diff --git a/buck2/prelude/python_bootstrap/python_bootstrap.bzl b/buck2/prelude/python_bootstrap/python_bootstrap.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/python_bootstrap/python_bootstrap.bzl
@@ -0,0 +1,69 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:utils.bzl", "flatten")
+
+PythonBootstrapSources = provider(fields = {"srcs": provider_field(typing.Any, default = None)})
+
+PythonBootstrapToolchainInfo = provider(fields = {"interpreter": provider_field(str | cmd_args)})
+
+def python_bootstrap_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    has_content_based_path = ctx.attrs.has_content_based_path
+    tree = {src.short_path: src for src in ctx.attrs.srcs}
+    output = ctx.actions.symlinked_dir("__{}__".format(ctx.attrs.name), tree, has_content_based_path = has_content_based_path)
+    return [
+        DefaultInfo(default_output = output),
+        PythonBootstrapSources(srcs = dedupe(flatten([ctx.attrs.srcs] + [dep[PythonBootstrapSources].srcs for dep in ctx.attrs.deps]))),
+    ]
+
+def python_bootstrap_binary_impl(ctx: AnalysisContext) -> list[Provider]:
+    """
+    Declares a Python binary that is intended to be used in scripts that
+    bootstrap other aspects of the Buck2 prelude. Python bootstrap binaries do
+    not use the Python toolchain and, as such, are highly restricted in what
+    they can and can't do. In particular, bootstrap binaries can only depend on
+    bootstrap libraries and can only consist of a single file.
+    """
+    has_content_based_path = ctx.attrs.has_content_based_path
+    copy_deps = ctx.attrs.copy_deps
+    run_tree_inputs = {}
+    run_tree_recorded_deps = {}  # For a better error message when files collide
+    for dep in ctx.attrs.deps:
+        dep_srcs = dep[PythonBootstrapSources].srcs
+        for src in dep_srcs:
+            if src.short_path in run_tree_recorded_deps and src != run_tree_inputs[src.short_path]:
+                original_dep = run_tree_recorded_deps[src.short_path]
+                fail(
+                    "dependency `{}` and `{}` both declare a source file named `{}`, consider renaming one of these files to avoid collision".format(
+                        original_dep.label, dep.label, src.short_path
+                    )
+                )
+            run_tree_inputs[src.short_path] = src
+            run_tree_recorded_deps[src.short_path] = dep
+
+    main = ctx.attrs.main
+    if main.short_path in run_tree_inputs:
+        original_dep = run_tree_recorded_deps[main.short_path].label
+        fail("dependency `{}` declares a source file with the same name as main file; consider renaming it".format(original_dep))
+
+    run_tree_inputs[main.short_path] = main
+    if copy_deps:
+        run_tree = ctx.actions.copied_dir("__%s__" % ctx.attrs.name, run_tree_inputs, has_content_based_path = has_content_based_path)
+    else:
+        run_tree = ctx.actions.symlinked_dir("__%s__" % ctx.attrs.name, run_tree_inputs, has_content_based_path = has_content_based_path)
+
+    interpreter = ctx.attrs._python_bootstrap_toolchain[PythonBootstrapToolchainInfo].interpreter
+    main_artifact = run_tree.project(main.short_path)
+    run_args = cmd_args(
+        [interpreter, run_tree.project(main.short_path)],
+        hidden = run_tree,
+    )
+    return [
+        DefaultInfo(default_output = main_artifact, other_outputs = [run_tree]),
+        RunInfo(args = run_args),
+    ]
diff --git a/buck2/prelude/remote_file.bzl b/buck2/prelude/remote_file.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/remote_file.bzl
@@ -0,0 +1,79 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:http_file.bzl", "http_file_shared")
+load("@prelude//utils:expect.bzl", "expect")
+load("@prelude//utils:utils.bzl", "value_or")
+
+_DEFAULT_MAVEN_REPO = read_config("http", "maven_repo", "https://repo1.maven.org/maven2")
+_MAVEN_REPO_OVERRIDE = read_config("http", "maven_repo_override")
+
+def _from_mvn_url(url: str) -> str:
+    """
+    Convert `mvn:` style URIs to a URL.
+    """
+
+    count = url.count(":")
+    mod = ""
+
+    if count == 4:
+        mvn, group, id, typ, version = url.split(":")
+        repo = _DEFAULT_MAVEN_REPO
+    elif count == 5:
+        mvn, group, id, typ, mod, version = url.split(":")
+        mod = "-" + mod
+        repo = _DEFAULT_MAVEN_REPO
+    elif count == 6:
+        mvn, repo_protocol, repo_host, group, id, typ, version = url.split(":")
+        repo = repo_protocol + ":" + repo_host
+    elif count == 7:
+        mvn, repo_protocol, repo_host, group, id, typ, mod, version = url.split(":")
+        mod = "-" + mod
+        repo = repo_protocol + ":" + repo_host
+    else:
+        fail("Unsupported mvn URL scheme: " + url + " (" + str(count) + ")")
+
+    expect(mvn == "mvn")
+
+    group = group.replace(".", "/")
+
+    if typ == "src":
+        ext = "-sources.jar"
+    else:
+        ext = "." + typ
+
+    if _MAVEN_REPO_OVERRIDE:
+        repo = _MAVEN_REPO_OVERRIDE
+
+    return "{repo}/{group}/{id}/{version}/{id}-{version}{mod}{ext}".format(
+        repo = repo,
+        group = group,
+        id = id,
+        version = version,
+        ext = ext,
+        mod = mod,
+    )
+
+# Implementation of the `remote_file` build rule.
+def remote_file_impl(ctx: AnalysisContext) -> list[Provider]:
+    url = ctx.attrs.url
+    if url.startswith("mvn:"):
+        url = _from_mvn_url(url)
+    return http_file_shared(
+        ctx.actions,
+        name = value_or(ctx.attrs.out, ctx.label.name),
+        url = url,
+        vpnless_url = ctx.attrs.vpnless_url,
+        is_executable = ctx.attrs.type == "executable",
+        is_exploded_zip = ctx.attrs.type == "exploded_zip",
+        unzip_tool = ctx.attrs._unzip_tool[RunInfo],
+        sha1 = ctx.attrs.sha1,
+        sha256 = ctx.attrs.sha256,
+        size_bytes = ctx.attrs.size_bytes,
+        has_content_based_path = ctx.attrs.has_content_based_path,
+    )
diff --git a/buck2/prelude/resources.bzl b/buck2/prelude/resources.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/resources.bzl
@@ -0,0 +1,105 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifacts.bzl", "ArtifactOutputs")
+load("@prelude//utils:arglike.bzl", "ArgLike")  # @unused Used as a type
+
+# Resources for transitive deps, shared by C++ and Rust.
+ResourceInfo = provider(
+    fields = {
+        # A map containing all resources from transitive dependencies.  The keys
+        # are rule labels and the values are maps of resource names (the name used
+        # to lookup the resource at runtime) and the actual resource artifact.
+        "resources": provider_field(dict[Label, dict[str, ArtifactOutputs]]),
+    }
+)
+
+_EMPTY_RESOURCE_INFO = ResourceInfo(resources = {})
+
+def make_resource_info(resources: dict[Label, dict[str, ArtifactOutputs]]) -> ResourceInfo:
+    return _EMPTY_RESOURCE_INFO if not resources else ResourceInfo(resources = resources)
+
+def create_relocatable_resources_info(
+    ctx: AnalysisContext, name: str, resources: dict[str, ArtifactOutputs], has_content_based_path: bool = False
+) -> [ArgLike, Artifact]:
+    """
+    Generate a resource DB (a JSON map of resource to its relative path) for the given
+    binary in a way that is usable in relocatable contexts (where binaries must be fully
+    self-contained). Paths in the DB are relative to the dir containing the binary, and
+    point to a local dir that contains symlinks to the resources.
+
+    Resources are packaged in a structure like:
+      binary_name                                 (main executable)
+      binary_name.resources.json                  (manifest pointing to the resources)
+      __binary_name__resources/                   (dir containing resource files)
+        resource_name_1/resource_file_1 -> ../../foo
+        resource_name_2/resource_file_2 -> ../../bar
+    """
+
+    resources_dir_mapping = {}
+    packaged_resource_name_to_json = {}
+
+    # The name of the single resources directory for this binary
+    resources_dir_name = "__{}__resources".format(name)
+    for resource_name, resource_output in resources.items():
+        # Sanitize resource name to create a valid subdir
+        sanitized_resource_name = resource_name.replace("/", "__")
+
+        # Create path within resources directory: <resource_name>/<filename>
+        resource_filename = resource_output.default_output.basename
+        resource_subdir_path = "{}/{}".format(sanitized_resource_name, resource_filename)
+
+        resources_dir_mapping[resource_subdir_path] = resource_output.default_output
+
+        # Update JSON to point to the packaged location, where path is relative to the
+        # binary: (i.e. ./__binary_name__resources__/<resource_name>/<filename>)
+        packaged_resource_name_to_json[resource_name] = "{}/{}".format(
+            resources_dir_name,
+            resource_subdir_path,
+        )
+
+    resources_dir = ctx.actions.symlinked_dir(
+        resources_dir_name,
+        resources_dir_mapping,
+        has_content_based_path = has_content_based_path,
+    )
+
+    packaged_resources_json = ctx.actions.write_json(
+        name + ".resources_pkg.json",
+        packaged_resource_name_to_json,
+        has_content_based_path = has_content_based_path,
+    )
+
+    return (packaged_resources_json, resources_dir)
+
+def gather_resources(label: Label, resources: dict[str, ArtifactOutputs] = {}, deps: list[Dependency] = []) -> dict[Label, dict[str, ArtifactOutputs]]:
+    """
+    Return the resources for this rule and its transitive deps.
+    """
+
+    all_resources = {}
+
+    # Resources for self.
+    if resources:
+        all_resources[label] = resources
+
+    # Merge in resources for deps.
+    for dep in deps:
+        if ResourceInfo in dep:
+            all_resources.update(dep[ResourceInfo].resources)
+
+    return all_resources
+
+def create_resource_db(ctx: AnalysisContext, name: str, binary: Artifact, resources: dict[str, ArtifactOutputs]) -> Artifact:
+    """
+    Generate a resource DB for resources for the given binary, relativized to
+    the binary's working directory.
+    """
+
+    db = {name: cmd_args(resource.default_output, delimiter = "", relative_to = (binary, 1)) for (name, resource) in resources.items()}
+    return ctx.actions.write_json(name, db, has_content_based_path = False)
diff --git a/buck2/prelude/rules.bzl b/buck2/prelude/rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rules.bzl
@@ -0,0 +1,171 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+# Combine the attributes we generate, we the custom implementations we have.
+load("@prelude//:rules_impl.bzl", "categorized_extra_attributes", "categorized_rule_decl_records", "extra_implemented_rules", "toolchain_rule_names")
+load("@prelude//apple:apple_platforms.bzl", "APPLE_PLATFORMS_KEY")
+load("@prelude//configurations:rules.bzl", _config_implemented_rules = "implemented_rules")
+load("@prelude//decls:common.bzl", "prelude_rule")
+
+def _unimplemented(name, ctx):
+    fail("Unimplemented rule type `{}` for target `{}`.".format(name, ctx.label))
+
+def _unimplemented_impl(name):
+    # We could use a lambda here, but then it means every single parse evaluates a lambda.
+    # Lambda's have tricky semantics, so using partial lets us test Starlark prototypes with
+    # some features disabled.
+    return partial(_unimplemented, name)
+
+def _mk_rule(rule_spec: typing.Any, extra_attrs: dict[str, typing.Any] = dict(), impl_override: [typing.Callable, None] = None, **kwargs):
+    name = rule_spec.name
+    attributes = rule_spec.attrs
+
+    # We want native code-containing rules to be marked incompatible with fat
+    # platforms. Getting the ones that use cxx/apple toolchains is a little
+    # overly broad as it includes things like python that don't themselves have
+    # native code but need the toolchains if they depend on native code and in
+    # that case incompatibility is transitive and they'll get it.
+    fat_platform_compatible = True
+    if name not in ("python_library", "python_binary", "python_test"):
+        for toolchain_attr in ("_apple_toolchain", "_cxx_toolchain", "_go_toolchain"):
+            if toolchain_attr in attributes:
+                fat_platform_compatible = False
+
+    # Fat platforms is an idea specific to our toolchains, so doesn't apply to
+    # open source. Ideally this restriction would be done at the toolchain level.
+    if not is_full_meta_repo():
+        fat_platform_compatible = True
+
+    attributes = dict(attributes)
+    attributes.update(extra_attrs)
+    if not fat_platform_compatible:
+        # copy so we don't try change the passed in object
+        attributes["_cxx_toolchain_target_configuration"] = attrs.dep(default = "prelude//platforms:fat_platform_incompatible")
+
+    # Add _apple_platforms to all rules so that we may query the target platform to use until we support configuration
+    # modifiers and can use them to set the configuration to use for operations.
+    # Map of string identifier to platform.
+    attributes[APPLE_PLATFORMS_KEY] = attrs.dict(key = attrs.string(), value = attrs.dep(), sorted = False, default = {})
+
+    cfg = rule_spec.cfg
+
+    if cfg != None:
+        kwargs["cfg"] = cfg
+
+    if rule_spec.docs:
+        doc = rule_spec.docs
+
+        # This is awkward. When generating documentation, we'll strip leading whitespace
+        # like it's a python docstring. For that to work here, we need the "Examples:" line
+        # to match the other lines for leading whitespace. We've just hardcoded this to
+        # be what its expected to be in prelude.
+        # TODO(cjhopman): Figure out something better here.
+        if rule_spec.examples:
+            # NOTE: DocString needs 'Examples:' to render the sections properly, that code should be updated along with this
+            doc += "\n{}Examples:\n{}".format(" " * 8, rule_spec.examples)
+        if rule_spec.further:
+            doc += "\n{}Additional notes:\n{}".format(" " * 8, rule_spec.further)
+
+        kwargs["doc"] = doc
+
+    impl = rule_spec.impl
+    extra_impl = getattr(extra_implemented_rules, name, None)
+    if extra_impl:
+        if impl:
+            fail("{} had an impl in the declaration and in the extra_implemented_rules overrides".format(name))
+        impl = extra_impl
+    if not impl:
+        impl = _unimplemented_impl(name)
+    if impl_override != None:
+        impl = impl_override
+    if rule_spec.uses_plugins != None:
+        kwargs["uses_plugins"] = rule_spec.uses_plugins
+    if rule_spec.supports_incoming_transition != None:
+        kwargs["supports_incoming_transition"] = rule_spec.supports_incoming_transition
+
+    is_toolchain_rule = rule_spec.is_toolchain_rule
+    is_toolchain_rule_via_rule_name = name in toolchain_rule_names
+    if is_toolchain_rule == None:
+        is_toolchain_rule = is_toolchain_rule_via_rule_name
+    elif is_toolchain_rule_via_rule_name:
+        fail("Cannot set `is_toolchain_rule` on `prelude_rule` and also via `toolchain_rule_names`")
+
+    kwargs.setdefault("is_configuration_rule", name in _config_implemented_rules)
+    kwargs.setdefault("is_toolchain_rule", is_toolchain_rule)
+    return rule(impl = impl, attrs = attributes, **kwargs)
+
+def _categorized_decls():
+    grouped_decls = {}
+    for group_name, decl_set in categorized_rule_decl_records.items():
+        group_rules = {}
+        for rule in dir(decl_set):
+            group_rules[rule] = getattr(decl_set, rule)
+        grouped_decls[group_name] = group_rules
+    return grouped_decls
+
+Attributes = dict[str, Attr]
+
+def _update_categorized_rules(categorized_rules: dict[str, dict[str, prelude_rule]], categorized_extra_attributes: dict[str, dict[str, Attributes]]):
+    flatten_rules = {}
+    for category, rules in categorized_rules.items():
+        for rule_name, rule_spec in rules.items():
+            flatten_rules[rule_name] = (category, rule_spec)
+    for attr_category, extra_attributes_dict in categorized_extra_attributes.items():
+        for rule_name, extra_attributes in extra_attributes_dict.items():
+            if rule_name in flatten_rules:
+                category, rule_spec = flatten_rules[rule_name]
+                d = dict(rule_spec.attrs)
+                d.update(extra_attributes)
+
+                # Use the category from the categorized_rules not categorized_extra_attributes
+                categorized_rules[category][rule_name] = prelude_rule(
+                    name = rule_spec.name,
+                    impl = rule_spec.impl,
+                    attrs = d,
+                    docs = rule_spec.docs,
+                    examples = rule_spec.examples,
+                    further = rule_spec.further,
+                    uses_plugins = rule_spec.uses_plugins,
+                    supports_incoming_transition = rule_spec.supports_incoming_transition,
+                    is_toolchain_rule = rule_spec.is_toolchain_rule,
+                    cfg = rule_spec.cfg,
+                )
+            else:
+                if attr_category not in categorized_rules:
+                    categorized_rules[attr_category] = {}
+                categorized_rules[attr_category][rule_name] = prelude_rule(
+                    name = rule_name,
+                    impl = None,
+                    attrs = extra_attributes,
+                    docs = None,
+                    examples = None,
+                    further = None,
+                    uses_plugins = None,
+                    supports_incoming_transition = None,
+                )
+
+_categorized_declared_rules = _categorized_decls()
+_update_categorized_rules(_categorized_declared_rules, categorized_extra_attributes)
+
+_declared_rules = {rule_name: rule for category in _categorized_declared_rules.values() for rule_name, rule in category.items()}
+
+categorized_rules = {
+    group_name: {rule_name: _mk_rule(rule_decl) for rule_name, rule_decl in group_rules.items()}
+    for group_name, group_rules in _categorized_declared_rules.items()
+}
+rules = {rule_name: rule for category in categorized_rules.values() for rule_name, rule in category.items()}
+
+# The rules are accessed by doing module.name, so we have to put them on the correct module.
+load_symbols(rules)
+
+# TODO(akrieger): Remove this and instead refactor to allow impl bzl files to export attrs.
+def clone_rule(rule: str, extra_attrs: dict[str, typing.Any] = dict(), impl_override = None, **kwargs):
+    if not rule in _declared_rules:
+        fail("Tried clone rule {} which does not exist".format(rule))
+    return _mk_rule(_declared_rules[rule], extra_attrs, impl_override, **kwargs)
diff --git a/buck2/prelude/rules_impl.bzl b/buck2/prelude/rules_impl.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rules_impl.bzl
@@ -0,0 +1,582 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:alias.bzl", "alias_impl", "configured_alias_impl", "versioned_alias_impl")
+load("@prelude//:command_alias.bzl", "command_alias_impl")
+load("@prelude//:export_file.bzl", "export_file_impl")
+load("@prelude//:filegroup.bzl", "filegroup_impl")
+load("@prelude//:genrule.bzl", "genrule_attributes", "genrule_impl")
+load("@prelude//:http_file.bzl", "http_file_impl")
+load("@prelude//:remote_file.bzl", "remote_file_impl")
+load("@prelude//:sh_binary.bzl", "sh_binary_impl")
+load("@prelude//:sh_test.bzl", "sh_test_impl")
+load("@prelude//:test_suite.bzl", "test_suite_impl")
+load("@prelude//android:android.bzl", _android_implemented_rules = "implemented_rules")
+load("@prelude//android:configuration.bzl", "is_building_android_binary_attr")
+load("@prelude//android:native_build_commands.bzl", "EMIT_NATIVE_BUILD_COMMANDS")
+load("@prelude//apple:apple_common.bzl", "apple_common")
+load("@prelude//apple:apple_rules_decls.bzl", "apple_rules")
+load("@prelude//apple:apple_rules_impl.bzl", _apple_extra_attributes = "extra_attributes", _apple_implemented_rules = "implemented_rules")
+load("@prelude//configurations:rules.bzl", _config_extra_attributes = "extra_attributes", _config_implemented_rules = "implemented_rules")
+load("@prelude//csharp:csharp.bzl", "csharp_library_impl", "prebuilt_dotnet_library_impl")
+load("@prelude//cxx:bitcode.bzl", "llvm_link_bitcode_impl")
+load("@prelude//cxx:cuda.bzl", "CudaCompileStyle")
+load("@prelude//cxx:cxx.bzl", "cxx_binary_impl", "cxx_library_impl", "cxx_precompiled_header_impl", "cxx_test_impl", "prebuilt_cxx_library_impl")
+load("@prelude//cxx:cxx_flags.bzl", "cxx_flags_impl")
+load("@prelude//cxx:cxx_toolchain.bzl", "cxx_toolchain_extra_attributes", "cxx_toolchain_impl")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxPlatformInfo", "CxxToolchainInfo")
+load("@prelude//cxx:headers.bzl", "CPrecompiledHeaderInfo", "HeaderMode")
+load("@prelude//cxx:link_groups_types.bzl", "LINK_GROUP_MAP_ATTR")
+load("@prelude//cxx:prebuilt_cxx_library_group.bzl", "prebuilt_cxx_library_group_impl")
+load("@prelude//cxx:transformation_spec.bzl", "TransformationKind", "transformation_spec_impl")
+load("@prelude//cxx:windows_resource.bzl", "windows_resource_impl")
+load("@prelude//decls:android_rules.bzl", "android_rules")
+load("@prelude//decls:common.bzl", "IncludeType", "buck")
+load("@prelude//decls:core_rules.bzl", "core_rules")
+load("@prelude//decls:cxx_rules.bzl", "BUILD_INFO_ATTR", "cxx_rules")
+load("@prelude//decls:cython_rules.bzl", "cython_rules")
+load("@prelude//decls:dotnet_rules.bzl", "dotnet_rules")
+load("@prelude//decls:erlang_rules.bzl", "erlang_rules")
+load("@prelude//decls:git_rules.bzl", "git_rules")
+load("@prelude//decls:go_rules.bzl", "go_rules")
+load("@prelude//decls:haskell_rules.bzl", "haskell_rules")
+load("@prelude//decls:java_rules.bzl", "java_rules")
+load("@prelude//decls:js_rules.bzl", "js_rules")
+load("@prelude//decls:kotlin_rules.bzl", "kotlin_rules")
+load("@prelude//decls:lua_rules.bzl", "lua_rules")
+load("@prelude//decls:ocaml_rules.bzl", "ocaml_rules")
+load("@prelude//decls:python_rules.bzl", "python_rules")
+load("@prelude//decls:re_test_common.bzl", "re_test_common")
+load("@prelude//decls:rust_rules.bzl", "rust_rules")
+load("@prelude//decls:shell_rules.bzl", "shell_rules")
+load("@prelude//decls:third_party_common.bzl", "third_party_common")
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//decls:uncategorized_rules.bzl", "uncategorized_rules")
+load("@prelude//erlang:erlang.bzl", _erlang_implemented_rules = "implemented_rules")
+load("@prelude//git:git_fetch.bzl", "git_fetch_impl")
+load("@prelude//go:coverage.bzl", "GoCoverageMode")
+load("@prelude//go:go_binary.bzl", "go_binary_impl")
+load("@prelude//go:go_exported_library.bzl", "go_exported_library_impl")
+load("@prelude//go:go_library.bzl", "go_library_impl")
+load("@prelude//go:go_stdlib.bzl", "go_stdlib_impl")
+load("@prelude//go:go_test.bzl", "go_test_impl")
+load("@prelude//go/transitions:defs.bzl", "build_tags_attr", "cgo_enabled_attr", "coverage_mode_attr")
+load("@prelude//go_bootstrap:go_bootstrap.bzl", "go_bootstrap_binary_impl")
+load("@prelude//haskell:haskell.bzl", "haskell_binary_impl", "haskell_library_impl", "haskell_prebuilt_library_impl")
+load("@prelude//haskell:haskell_ghci.bzl", "haskell_ghci_impl")
+load("@prelude//haskell:haskell_haddock.bzl", "haskell_haddock_impl")
+load("@prelude//haskell:haskell_ide.bzl", "haskell_ide_impl")
+load("@prelude//haskell:library_info.bzl", "HaskellLibraryProvider")
+load("@prelude//http_archive:http_archive.bzl", "http_archive_impl")
+load("@prelude//java:java.bzl", _java_implemented_rules = "implemented_rules")
+load("@prelude//js:js.bzl", _js_extra_attributes = "extra_attributes", _js_implemented_rules = "implemented_rules")
+load("@prelude//js:worker_tool.bzl", "worker_tool")
+load("@prelude//julia:julia.bzl", _julia_extra_attributes = "extra_attributes", _julia_implemented_rules = "implemented_rules")
+load("@prelude//kotlin:kotlin.bzl", _kotlin_implemented_rules = "implemented_rules")
+load("@prelude//linking:execution_preference.bzl", "link_execution_preference_attr")
+load("@prelude//linking:link_info.bzl", "LinkOrdering")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//lua:cxx_lua_extension.bzl", "cxx_lua_extension_impl")
+load("@prelude//lua:lua_binary.bzl", "lua_binary_impl")
+load("@prelude//lua:lua_library.bzl", "lua_library_impl")
+load("@prelude//matlab:matlab.bzl", _matlab_extra_attributes = "extra_attributes", _matlab_implemented_rules = "implemented_rules")
+load("@prelude//ocaml:attrs.bzl", _ocaml_extra_attributes = "ocaml_extra_attributes")
+load("@prelude//ocaml:ocaml.bzl", "ocaml_binary_impl", "ocaml_library_impl", "ocaml_object_impl", "ocaml_shared_impl", "prebuilt_ocaml_library_impl")
+load("@prelude//python:cxx_python_extension.bzl", "cxx_python_extension_impl")
+load("@prelude//python:prebuilt_python_library.bzl", "prebuilt_python_library_impl")
+load("@prelude//python:python_binary.bzl", "python_binary_impl")
+load("@prelude//python:python_library.bzl", "python_library_impl")
+load("@prelude//python:python_needed_coverage_test.bzl", "python_needed_coverage_test_impl")
+load("@prelude//python:python_runtime_bundle.bzl", "python_runtime_bundle_impl")
+load("@prelude//python:python_test.bzl", "python_test_impl")
+load("@prelude//python/cython:cython_library.bzl", "cython_library_impl")
+load("@prelude//python/cython:cython_static_extension.bzl", "cython_static_extension_impl")
+load("@prelude//python/cython:cython_toolchain.bzl", "cython_toolchain_impl")
+load("@prelude//python_bootstrap:python_bootstrap.bzl", "PythonBootstrapSources", "python_bootstrap_binary_impl", "python_bootstrap_library_impl")
+load("@prelude//third-party:providers.bzl", "ThirdPartyBuildInfo")
+load("@prelude//transitions:constraint_overrides.bzl", "constraint_overrides")
+load("@prelude//zip_file:zip_file.bzl", _zip_file_extra_attributes = "extra_attributes", _zip_file_implemented_rules = "implemented_rules")
+
+_ANDROID_RULES_KEY = "android"
+_CORE_RULES_KEY = "core"
+_CXX_RULES_KEY = "cxx"
+_CYTHON_RULES_KEY = "cython"
+_DOTNET_RULES_KEY = ".NET"
+_ERLANG_RULES_KEY = "erlang"
+_GIT_RULES_KEY = "git"
+_GO_RULES_KEY = "go"
+_HASKELL_RULES_KEY = "haskell"
+_APPLE_RULES_KEY = "apple"
+_JAVA_RULES_KEY = "java"
+_JS_RULES_KEY = "js"
+_KOTLIN_RULES_KEY = "kotlin"
+_LUA_RULES_KEY = "lua"
+_OCAML_RULES_KEY = "ocaml"
+_PYTHON_RULES_KEY = "python"
+_RUST_RULES_KEY = "rust"
+_SHELL_RULES_KEY = "shell"
+_UNCATEGORIZED_RULES_KEY = "uncategorized"
+
+_JULIA_RULES_KEY = "julia"
+_MATLAB_RULES_KEY = "matlab"
+
+categorized_rule_decl_records = {
+    _ANDROID_RULES_KEY: android_rules,
+    _CORE_RULES_KEY: core_rules,
+    _CXX_RULES_KEY: cxx_rules,
+    _CYTHON_RULES_KEY: cython_rules,
+    _DOTNET_RULES_KEY: dotnet_rules,
+    _ERLANG_RULES_KEY: erlang_rules,
+    _GIT_RULES_KEY: git_rules,
+    _GO_RULES_KEY: go_rules,
+    _HASKELL_RULES_KEY: haskell_rules,
+    _APPLE_RULES_KEY: apple_rules,
+    _JAVA_RULES_KEY: java_rules,
+    _JS_RULES_KEY: js_rules,
+    _KOTLIN_RULES_KEY: kotlin_rules,
+    _LUA_RULES_KEY: lua_rules,
+    _OCAML_RULES_KEY: ocaml_rules,
+    _PYTHON_RULES_KEY: python_rules,
+    _RUST_RULES_KEY: rust_rules,
+    _SHELL_RULES_KEY: shell_rules,
+    _UNCATEGORIZED_RULES_KEY: uncategorized_rules,
+}
+
+def _merge_dictionaries(dicts):
+    result = {}
+    for d in dicts:
+        for key, value in d.items():
+            if key in result:
+                fail("Duplicate key: '{}' while merging dictionaries".format(key))
+            result[key] = value
+
+    return result
+
+extra_implemented_rules = struct(
+    # common rules
+    alias = alias_impl,
+    command_alias = command_alias_impl,
+    configured_alias = configured_alias_impl,
+    export_file = export_file_impl,
+    filegroup = filegroup_impl,
+    genrule = genrule_impl,
+    http_archive = http_archive_impl,
+    http_file = http_file_impl,
+    remote_file = remote_file_impl,
+    sh_binary = sh_binary_impl,
+    sh_test = sh_test_impl,
+    test_suite = test_suite_impl,
+    toolchain_alias = alias_impl,
+    versioned_alias = versioned_alias_impl,
+    worker_tool = worker_tool,
+    # c#
+    csharp_library = csharp_library_impl,
+    prebuilt_dotnet_library = prebuilt_dotnet_library_impl,
+    # c++
+    cxx_binary = cxx_binary_impl,
+    cxx_flags = cxx_flags_impl,
+    cxx_test = cxx_test_impl,
+    cxx_toolchain = cxx_toolchain_impl,
+    cxx_genrule = genrule_impl,
+    cxx_library = cxx_library_impl,
+    cxx_precompiled_header = cxx_precompiled_header_impl,
+    cxx_python_extension = cxx_python_extension_impl,
+    prebuilt_cxx_library = prebuilt_cxx_library_impl,
+    prebuilt_cxx_library_group = prebuilt_cxx_library_group_impl,
+    windows_resource = windows_resource_impl,
+    transformation_spec = transformation_spec_impl,
+    # cython
+    cython_library = cython_library_impl,
+    cython_static_extension = cython_static_extension_impl,
+    cython_toolchain = cython_toolchain_impl,
+    # C++ / LLVM
+    llvm_link_bitcode = llvm_link_bitcode_impl,
+    # git
+    git_fetch = git_fetch_impl,
+    # go
+    go_binary = go_binary_impl,
+    go_bootstrap_binary = go_bootstrap_binary_impl,
+    go_exported_library = go_exported_library_impl,
+    go_library = go_library_impl,
+    go_test = go_test_impl,
+    go_stdlib = go_stdlib_impl,
+    # haskell
+    haskell_library = haskell_library_impl,
+    haskell_binary = haskell_binary_impl,
+    haskell_ghci = haskell_ghci_impl,
+    haskell_haddock = haskell_haddock_impl,
+    haskell_ide = haskell_ide_impl,
+    haskell_prebuilt_library = haskell_prebuilt_library_impl,
+    # lua
+    cxx_lua_extension = cxx_lua_extension_impl,
+    lua_binary = lua_binary_impl,
+    lua_library = lua_library_impl,
+    # ocaml
+    ocaml_binary = ocaml_binary_impl,
+    ocaml_object = ocaml_object_impl,
+    ocaml_shared = ocaml_shared_impl,
+    ocaml_library = ocaml_library_impl,
+    prebuilt_ocaml_library = prebuilt_ocaml_library_impl,
+    # python
+    prebuilt_python_library = prebuilt_python_library_impl,
+    python_binary = python_binary_impl,
+    python_library = python_library_impl,
+    python_runtime_bundle = python_runtime_bundle_impl,
+    python_test = python_test_impl,
+    python_needed_coverage_test = python_needed_coverage_test_impl,
+    # python bootstrap
+    python_bootstrap_binary = python_bootstrap_binary_impl,
+    python_bootstrap_library = python_bootstrap_library_impl,
+    # merged **kwargs
+    **_merge_dictionaries([
+        _android_implemented_rules,
+        _apple_implemented_rules,
+        _config_implemented_rules,
+        _erlang_implemented_rules,
+        _java_implemented_rules,
+        _js_implemented_rules,
+        _julia_implemented_rules,
+        _kotlin_implemented_rules,
+        _matlab_implemented_rules,
+        _zip_file_implemented_rules,
+    ]),
+)
+
+def _python_runtime_bundle_attrs():
+    return (
+        {
+            "include": attrs.string(doc = "Header files required for linking python extensions"),
+            "install_root": attrs.dep(doc = "The filegroup containing the runtime artifacts, all the paths are relative to this location"),
+            "libpython": attrs.option(
+                attrs.string(doc = "libpyhon.so required at runtime for the python executable and native extensions."),
+                default = None,
+            ),
+            "py_bin": attrs.string(doc = "The runtime executable"),
+            "py_version": attrs.string(doc = "The version of python this represents"),
+            "shared_libs": attrs.list(attrs.dep(), default = [], doc = "Additional shared libraries required by this runtime"),
+            "stdlib": attrs.string(doc = "The python standard library"),
+        }
+        | buck.labels_arg()
+        | buck.contacts_arg()
+    )
+
+_dotnet_extra_attributes = {
+    "csharp_library": {
+        "_csharp_toolchain": toolchains_common.csharp(),
+    },
+}
+
+_cxx_extra_library_attrs = (
+    {
+        "auto_link_groups": attrs.bool(default = False),
+        # These flags will only be used to instrument a target
+        # when coverage for that target is enabled by `exported_needs_coverage_instrumentation`
+        # or by any of the target's dependencies.
+        "coverage_instrumentation_compiler_flags": attrs.list(attrs.string(), default = []),
+        # Optional clang_profile_list target for selective coverage instrumentation via -fprofile-list.
+        "coverage_profile_list": attrs.option(attrs.dep(), default = None),
+        "cuda_compile_style": attrs.enum(CudaCompileStyle.values(), default = "mono"),
+        "deps_query": attrs.option(attrs.query(), default = None),
+        "exported_needs_coverage_instrumentation": attrs.bool(default = False),
+        "extra_dwp_flags": attrs.list(attrs.string(), default = []),
+        "header_mode": attrs.option(attrs.enum(HeaderMode.values()), default = None),
+        "link_deps_query_whole": attrs.bool(default = False),
+        "link_execution_preference": link_execution_preference_attr(),
+        "link_group_map": LINK_GROUP_MAP_ATTR,
+        "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),
+        "precompiled_header": attrs.option(attrs.dep(providers = [CPrecompiledHeaderInfo]), default = None),
+        "prefer_stripped_objects": attrs.bool(default = False),
+        "preferred_linkage": attrs.enum(
+            Linkage.values(),
+            default = "any",
+            doc = """
+Determines what linkage is used when the library is depended on by another target. To
+control how the dependencies of this library are linked, use `link_style` instead.
+""",
+        ),
+        "resources": attrs.named_set(attrs.one_of(attrs.dep(), attrs.source(allow_directory = True)), sorted = True, default = []),
+        "separate_debug_info": attrs.bool(default = False),
+        "stub": attrs.bool(default = False),
+        "supports_header_symlink_subtarget": attrs.bool(default = False),
+        "supports_python_dlopen": attrs.option(attrs.bool(), default = None),
+        "supports_shlib_interfaces": attrs.bool(default = True),
+        "third_party_project": attrs.option(attrs.string(), default = None),
+        "_cxx_hacks": attrs.default_only(attrs.dep(default = "prelude//cxx/tools:cxx_hacks")),
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_emit_native_build_commands": attrs.default_only(attrs.bool(default = EMIT_NATIVE_BUILD_COMMANDS)),
+        "_is_building_android_binary": is_building_android_binary_attr(),
+    }
+    | apple_common.extra_xcode_sources()
+    | third_party_common.create_third_party_build_root_attrs()
+)
+
+cxx_extra_attributes = {
+    "cxx_binary": {
+        "_gen_build_info": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "_generated_build_info_data": attrs.option(attrs.source(), default = None),
+        "_generated_build_info_enabled": attrs.bool(default = False),
+        "_generated_build_info_mode": attrs.enum(["full", "stable"], default = "stable"),
+        "_generated_build_info_spec": BUILD_INFO_ATTR,
+    },
+    "cxx_genrule": genrule_attributes()
+    | {
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_exec_os_type": buck.exec_os_type_arg(),
+    },
+    "cxx_library": _cxx_extra_library_attrs,
+    "cxx_precompiled_header": _cxx_extra_library_attrs,
+    "cxx_test": re_test_common.test_args()
+    | {
+        "_gen_build_info": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "_generated_build_info_data": attrs.option(attrs.source(), default = None),
+        "_generated_build_info_enabled": attrs.bool(default = False),
+        "_generated_build_info_mode": attrs.enum(["full", "stable"], default = "stable"),
+        "_generated_build_info_spec": BUILD_INFO_ATTR,
+    },
+    "cxx_toolchain": cxx_toolchain_extra_attributes(is_toolchain_rule = False),
+    "llvm_link_bitcode": {
+        "_cxx_toolchain": toolchains_common.cxx(),
+    },
+    "prebuilt_cxx_library": (
+        {
+            "exported_header_style": attrs.enum(IncludeType, default = "system"),
+            "header_dirs": attrs.option(attrs.list(attrs.source(allow_directory = True)), default = None),
+            "linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "post_linker_flags": attrs.list(attrs.arg(anon_target_compatible = True), default = []),
+            "preferred_linkage": attrs.enum(
+                Linkage.values(),
+                default = "any",
+                doc = """
+Determines what linkage is used when the library is depended on by another target. To
+control how the dependencies of this library are linked, use `link_style` instead.
+""",
+            ),
+            "public_include_directories": attrs.set(attrs.string(), sorted = True, default = []),
+            "public_system_include_directories": attrs.set(attrs.string(), sorted = True, default = []),
+            "raw_headers": attrs.set(attrs.source(), sorted = True, default = []),
+            "stub": attrs.bool(default = False),
+            "supports_lto": attrs.bool(default = False),
+            "supports_python_dlopen": attrs.bool(default = True),
+            "third_party_build": attrs.option(attrs.dep(providers = [ThirdPartyBuildInfo]), default = None),
+            "versioned_header_dirs": attrs.option(attrs.versioned(attrs.list(attrs.source(allow_directory = True))), default = None),
+            "_cxx_toolchain": toolchains_common.cxx(),
+            "_target_os_type": buck.target_os_type_arg(),
+        }
+        | third_party_common.create_third_party_build_root_attrs()
+    ),
+    "prebuilt_cxx_library_group": {
+        "_create_third_party_build_root": attrs.default_only(attrs.exec_dep(default = "prelude//third-party/tools:create_build")),
+        "_cxx_toolchain": toolchains_common.cxx(),
+    },
+    "transformation_spec": {
+        "transformations": attrs.list(
+            attrs.tuple(
+                attrs.one_of(attrs.dep(), attrs.string()),
+                attrs.enum(TransformationKind.values()),
+            ),
+            default = [],
+        ),
+    },
+    "windows_resource": {
+        "_cxx_toolchain": toolchains_common.cxx(),
+    },
+}
+
+_go_extra_attributes = {
+    "go_binary": {
+        "coverage_mode": attrs.option(attrs.enum(GoCoverageMode.values()), default = None),
+        "resources": attrs.list(attrs.one_of(attrs.dep(), attrs.source(allow_directory = True)), default = []),
+        "_build_info": BUILD_INFO_ATTR,
+        "_build_tags": build_tags_attr,
+        "_cgo_enabled": cgo_enabled_attr,
+        "_coverage_mode": coverage_mode_attr,
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_exec_os_type": buck.exec_os_type_arg(),
+        "_go_stdlib": attrs.default_only(attrs.dep(default = "prelude//go/tools:stdlib")),
+        "_go_toolchain": toolchains_common.go(),
+    },
+    "go_bootstrap_binary": {
+        "_exec_os_type": buck.exec_os_type_arg(),
+        "_go_bootstrap_toolchain": toolchains_common.go_bootstrap(),
+    },
+    "go_exported_library": {
+        "_build_info": BUILD_INFO_ATTR,
+        "_build_tags": build_tags_attr,
+        "_cgo_enabled": cgo_enabled_attr,
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_exec_os_type": buck.exec_os_type_arg(),
+        "_go_stdlib": attrs.default_only(attrs.dep(default = "prelude//go/tools:stdlib")),
+        "_go_toolchain": toolchains_common.go(),
+    },
+    "go_library": {
+        "_build_tags": build_tags_attr,
+        "_cgo_enabled": cgo_enabled_attr,
+        "_coverage_mode": coverage_mode_attr,
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_exec_os_type": buck.exec_os_type_arg(),
+        "_go_stdlib": attrs.default_only(attrs.dep(default = "prelude//go/tools:stdlib")),
+        "_go_toolchain": toolchains_common.go(),
+    },
+    "go_stdlib": {
+        "_build_tags": build_tags_attr,
+        "_cgo_enabled": cgo_enabled_attr,
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_exec_os_type": buck.exec_os_type_arg(),
+        "_go_toolchain": toolchains_common.go(),
+    },
+    "go_test": {
+        "coverage_mode": attrs.option(attrs.enum(GoCoverageMode.values()), default = None),
+        "resources": attrs.list(attrs.source(allow_directory = True), default = []),
+        "_build_info": BUILD_INFO_ATTR,
+        "_build_tags": build_tags_attr,
+        "_cgo_enabled": cgo_enabled_attr,
+        "_coverage_mode": coverage_mode_attr,
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_exec_os_type": buck.exec_os_type_arg(),
+        "_go_stdlib": attrs.default_only(attrs.dep(default = "prelude//go/tools:stdlib")),
+        "_go_toolchain": toolchains_common.go(),
+        "_list_tests": attrs.default_only(attrs.dep(providers = [RunInfo], default = "prelude//go/tools:list_tests")),
+        "_testmaingen": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//go/tools:testmaingen")),
+    },
+}
+
+_haskell_extra_attributes = {
+    "haskell_binary": {
+        "auto_link_groups": attrs.bool(default = False),
+        "link_group_map": LINK_GROUP_MAP_ATTR,
+        "template_deps": attrs.list(attrs.exec_dep(providers = [HaskellLibraryProvider]), default = []),
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_haskell_toolchain": toolchains_common.haskell(),
+    },
+    "haskell_ghci": {
+        "template_deps": attrs.list(attrs.exec_dep(providers = [HaskellLibraryProvider]), default = []),
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_haskell_toolchain": toolchains_common.haskell(),
+    },
+    "haskell_haddock": {
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_haskell_toolchain": toolchains_common.haskell(),
+    },
+    "haskell_ide": {
+        "include_projects": attrs.list(attrs.dep(), default = []),
+        "_haskell_toolchain": toolchains_common.haskell(),
+    },
+    "haskell_library": {
+        "preferred_linkage": attrs.enum(Linkage.values(), default = "any"),
+        "template_deps": attrs.list(attrs.exec_dep(providers = [HaskellLibraryProvider]), default = []),
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_haskell_toolchain": toolchains_common.haskell(),
+    },
+}
+
+_python_extra_attributes = {
+    # python bootstrap
+    "python_bootstrap_binary": {
+        "copy_deps": attrs.bool(default = True),
+        "deps": attrs.list(attrs.dep(providers = [PythonBootstrapSources]), default = []),
+        "has_content_based_path": attrs.bool(default = False),
+        "main": attrs.source(),
+        "_python_bootstrap_toolchain": toolchains_common.python_bootstrap(),
+    }
+    | buck.labels_arg()
+    | buck.contacts_arg(),
+    "python_bootstrap_library": {
+        "deps": attrs.list(attrs.dep(providers = [PythonBootstrapSources]), default = []),
+        "has_content_based_path": attrs.bool(default = False),
+        "srcs": attrs.list(attrs.source()),
+    }
+    | buck.labels_arg()
+    | buck.contacts_arg(),
+    "python_needed_coverage_test": dict(
+        contacts = attrs.list(attrs.string(), default = []),
+        env = attrs.dict(key = attrs.string(), value = attrs.arg(), sorted = False, default = {}),
+        labels = attrs.list(attrs.string(), default = []),
+        needed_coverage = attrs.list(attrs.tuple(attrs.int(), attrs.dep(), attrs.option(attrs.string())), default = []),
+        supports_test_execution_caching = attrs.bool(default = False),
+        test = attrs.dep(providers = [ExternalRunnerTestInfo]),
+        **(re_test_common.test_args() | buck.inject_test_env_arg()),
+    ),
+    "python_runtime_bundle": _python_runtime_bundle_attrs(),
+}
+
+_rust_extra_attributes = {
+    "rust_binary": {
+        "_gen_build_info": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "_generated_build_info_args": attrs.list(attrs.arg(), default = []),
+        "_generated_build_info_data": attrs.option(attrs.source(), default = None),
+        "_generated_build_info_enabled": attrs.bool(default = False),
+        "_generated_build_info_mode": attrs.enum(["full", "stable"], default = "stable"),
+        "_generated_build_info_spec": BUILD_INFO_ATTR,
+    },
+    "rust_test": {
+        "_gen_build_info": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "_generated_build_info_args": attrs.list(attrs.arg(), default = []),
+        "_generated_build_info_data": attrs.option(attrs.source(), default = None),
+        "_generated_build_info_enabled": attrs.bool(default = False),
+        "_generated_build_info_mode": attrs.enum(["full", "stable"], default = "stable"),
+        "_generated_build_info_spec": BUILD_INFO_ATTR,
+    },
+}
+
+_core_extra_attributes = (
+    {
+        "export_file": constraint_overrides.attributes,
+        "filegroup": constraint_overrides.attributes,
+        "genrule": genrule_attributes() | constraint_overrides.attributes,
+        "remote_file": {
+            "sha1": attrs.option(attrs.string(), default = None),
+            "sha256": attrs.option(attrs.string(), default = None),
+            "_unzip_tool": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//zip_file/tools:unzip")),
+        },
+    }
+    | _zip_file_extra_attributes
+    | _config_extra_attributes
+)
+
+_shell_extra_attributes = {
+    "sh_test": constraint_overrides.attributes,
+}
+
+_uncategorized_extra_attributes = {
+    "ndk_toolchain": {
+        "cxx_toolchain": attrs.toolchain_dep(providers = [CxxToolchainInfo, CxxPlatformInfo]),
+    },
+}
+
+_cython_extra_attributes = {
+    "cython_library": _cxx_extra_library_attrs,
+    "cython_static_extension": _cxx_extra_library_attrs,
+}
+
+categorized_extra_attributes = {
+    _ANDROID_RULES_KEY: {},
+    _CORE_RULES_KEY: _core_extra_attributes,
+    _CXX_RULES_KEY: cxx_extra_attributes,
+    _CYTHON_RULES_KEY: _cython_extra_attributes,
+    _DOTNET_RULES_KEY: _dotnet_extra_attributes,
+    _GO_RULES_KEY: _go_extra_attributes,
+    _HASKELL_RULES_KEY: _haskell_extra_attributes,
+    _APPLE_RULES_KEY: _apple_extra_attributes,
+    _JAVA_RULES_KEY: {},
+    _JS_RULES_KEY: _js_extra_attributes,
+    _JULIA_RULES_KEY: _julia_extra_attributes,
+    _KOTLIN_RULES_KEY: {},
+    _MATLAB_RULES_KEY: _matlab_extra_attributes,
+    _OCAML_RULES_KEY: _ocaml_extra_attributes,
+    _PYTHON_RULES_KEY: _python_extra_attributes,
+    _RUST_RULES_KEY: _rust_extra_attributes,
+    _SHELL_RULES_KEY: _shell_extra_attributes,
+    _UNCATEGORIZED_RULES_KEY: _uncategorized_extra_attributes,
+}
+
+toolchain_rule_names = [
+    "apple_toolchain",
+    "swift_macro_toolchain",
+    "swift_toolchain",
+    "toolchain_alias",
+]
diff --git a/buck2/prelude/runtime/BUCK b/buck2/prelude/runtime/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/runtime/BUCK
@@ -0,0 +1,12 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+# Used by open source projects to support `prelude//`
+
+config_setting(
+    name = "fbcode",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/runtime/constraints/BUCK b/buck2/prelude/runtime/constraints/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/runtime/constraints/BUCK
@@ -0,0 +1,25 @@
+load("@prelude//configurations:constraint_alias.bzl", "constraint_with_aliases")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+# Used by open source projects to support `prelude//`
+
+constraint_with_aliases(
+    name = "test_runtime",
+    aliases = {
+        "android-host-test": "android-host",
+        "android-instrumentation-test": "android-instrumentation",
+        "android-unit-test": "android-unit",
+    },
+    default = "unspecified",
+    values = [
+        "android-host",
+        "android-unit",
+        "android-instrumentation",
+        "unspecified",
+    ],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/rust/build.bzl b/buck2/prelude/rust/build.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/build.bzl
@@ -0,0 +1,2286 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+    "make_artifact_tset",
+    "project_artifacts",
+)
+load("@prelude//:local_only.bzl", "link_cxx_binary_locally")
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//:resources.bzl", "create_resource_db", "gather_resources")
+load(
+    "@prelude//apple:apple_frameworks.bzl",
+    "apple_build_link_args_with_deduped_flags",
+    "apple_get_link_info_by_deduping_link_infos",
+)
+load("@prelude//cxx:archive.bzl", "archive_flags")
+load("@prelude//cxx:cxx_library_utility.bzl", "cxx_attr_deps")
+load(
+    "@prelude//cxx:cxx_link_utility.bzl",
+    "executable_shared_lib_arguments",
+    "make_link_args",
+)
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "LinkerType",
+)
+load("@prelude//cxx:debug.bzl", "SplitDebugMode")
+load("@prelude//cxx:dwp.bzl", "dwp", "dwp_available")
+load(
+    "@prelude//cxx:link.bzl",
+    "CxxLinkResult",  # @unused Used as a type
+    "cxx_link_into",
+    "cxx_link_shared_library",
+)
+load(
+    "@prelude//cxx:link_types.bzl",
+    "CxxLinkResultType",
+    "link_options",
+)
+load(
+    "@prelude//cxx:linker.bzl",
+    "get_import_library",
+    "get_shared_library_name_linker_flags",
+)
+load(
+    "@prelude//cxx:transformation_spec.bzl",
+    "TransformationSpecContext",  # @unused Used as a type
+)
+load(
+    "@prelude//linking:execution_preference.bzl",
+    "LinkExecutionPreference",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "Archive",
+    "ArchiveLinkable",
+    "LibOutputStyle",  # @unused Used as a type
+    "LinkArgs",
+    "LinkInfo",
+    "LinkInfos",  # @unused Used as a type
+    "LinkStrategy",
+    "LinkedObject",  # @unused Used as a type
+    "create_merged_link_info",
+    "get_link_args_for_strategy",
+    "set_link_info_link_whole",
+)
+load("@prelude//linking:lto.bzl", "LtoMode")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "merge_shared_libraries",
+)
+load("@prelude//linking:strip.bzl", "strip_debug_info")
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//os_lookup:defs.bzl", "OsLookup")
+load("@prelude//rust/tools:attrs.bzl", "RustInternalToolsInfo")
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load("@prelude//utils:cmd_script.bzl", "cmd_script")
+load(
+    "@prelude//utils:utils.bzl",
+    "flatten_dict",
+)
+load(
+    ":build_params.bzl",
+    "BuildParams",  # @unused Used as a type
+    "CrateType",
+    "Emit",
+    "MetadataKind",
+    "ProfileMode",  # @unused Used as a type
+    "RelocModel",
+    "crate_type_linked",
+    "dep_metadata_of_emit",
+)
+load(":clippy_configuration.bzl", "ClippyConfiguration")
+load(
+    ":context.bzl",
+    "CommonArgsInfo",
+    "CompileContext",
+    "DependencyArgsInfo",
+    "output_filename",
+    "strip_build_info_linker_flags",
+)
+load(
+    ":crate_name.bzl",
+    "CrateName",  # @unused Used as a type
+)
+load(":dep_context.bzl", "DepCollectionContext")
+load(
+    ":extern.bzl",
+    "crate_map_arg",
+    "extern_arg",
+)
+load(
+    ":failure_filter.bzl",
+    "failure_filter",
+)
+load(
+    ":link_info.bzl",
+    "RustArtifact",
+    "RustCxxLinkGroupInfo",  # @unused Used as a type
+    "RustDependency",
+    "RustLinkInfo",
+    "TransitiveDeps",
+    "attr_crate",
+    "attr_simple_crate_for_filenames",
+    "executable_shared_lib_arguments_from_shared_library_info",
+    "get_available_proc_macros",
+    "inherited_external_debug_info",
+    "inherited_merged_link_infos",
+    "inherited_shared_libs",
+    "normalize_crate",
+    "resolve_deps",
+    "resolve_rust_deps",
+    "strategy_info",
+)
+load(":outputs.bzl", "RustcCompileOutput", "RustcLinkOutput", "RustcOutput")
+load(":resources.bzl", "rust_attr_resources")
+load(":rust_toolchain.bzl", "PanicRuntime", "RustToolchainInfo")
+load(
+    ":sources.bzl",
+    "RustSources",
+    "RustSourcesTSet",
+)
+
+def generate_rustdoc(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    # link style doesn't matter, but caller should pass in build params
+    # with static-pic (to get best cache hits for deps)
+    params: BuildParams,
+    default_roots: list[str],
+    document_private_items: bool,
+) -> Artifact:
+    toolchain_info = compile_ctx.toolchain_info
+
+    common_args = _compute_common_args(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        dep_ctx = compile_ctx.dep_ctx,
+        # to make sure we get the rmeta's generated for the crate dependencies,
+        # rather than full .rlibs
+        emit = Emit("metadata-fast"),
+        params = params,
+        default_roots = default_roots,
+        infallible_diagnostics = False,
+        incremental_enabled = False,
+        is_rustdoc_test = False,
+        profile_mode = None,
+    )
+
+    subdir = common_args.subdir + "-rustdoc"
+    use_cbp = getattr(ctx.attrs, "use_content_based_paths", False)
+    output = ctx.actions.declare_output(subdir, has_content_based_path = use_cbp)
+
+    plain_env, path_env = process_env(compile_ctx, toolchain_info.rustdoc_env | ctx.attrs.env)
+    plain_env["RUSTDOC_BUCK_TARGET"] = cmd_args(str(ctx.label.raw_target()))
+
+    # The toolchain's `rustdoc_flags` may rely on unstable functionality, e.g.
+    # `--generate-link-to-definition`.
+    if toolchain_info.nightly_features and "RUSTC_BOOTSTRAP" not in plain_env:
+        plain_env["RUSTC_BOOTSTRAP"] = cmd_args("1")
+
+    if toolchain_info.rust_target_path != None:
+        path_env["RUST_TARGET_PATH"] = toolchain_info.rust_target_path[DefaultInfo].default_outputs[0]
+
+    rustdoc_cmd = cmd_args(
+        toolchain_info.rustdoc,
+        "--rustc-action-separator",
+        toolchain_info.rustdoc_flags,
+        ctx.attrs.rustdoc_flags,
+        common_args.args,
+        cmd_args(output.as_output(), format = "--out-dir={}"),
+        hidden = [toolchain_info.rustdoc, compile_ctx.symlinked_srcs],
+    )
+
+    if document_private_items:
+        rustdoc_cmd.add("--document-private-items")
+
+    rustdoc_cmd_action = cmd_args(
+        [cmd_args("--env=", k, "=", v, delimiter = "") for k, v in plain_env.items()],
+        [cmd_args("--path-env=", k, "=", v, delimiter = "") for k, v in path_env.items()],
+        rustdoc_cmd,
+    )
+
+    rustdoc_cmd = _long_command(
+        ctx = ctx,
+        exe = compile_ctx.internal_tools_info.rustc_action,
+        args = rustdoc_cmd_action,
+        argfile_name = "{}.args".format(subdir),
+        has_content_based_path = use_cbp,
+    )
+
+    ctx.actions.run(rustdoc_cmd, category = "rustdoc")
+
+    return output
+
+def generate_rustdoc_coverage(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    # link strategy doesn't matter, but caller should pass in build params
+    # with static-pic (to get best cache hits for deps)
+    params: BuildParams,
+    default_roots: list[str],
+) -> Artifact:
+    toolchain_info = compile_ctx.toolchain_info
+
+    if not toolchain_info.nightly_features:
+        fail("Doc coverage uses the unstable `--show-coverage` flag and requires a toolchain with `nightly_features = True`")
+
+    common_args = _compute_common_args(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        dep_ctx = compile_ctx.dep_ctx,
+        # to make sure we get the rmeta's generated for the crate dependencies,
+        # rather than full .rlibs
+        emit = Emit("metadata-fast"),
+        params = params,
+        default_roots = default_roots,
+        infallible_diagnostics = False,
+        incremental_enabled = False,
+        is_rustdoc_test = False,
+        profile_mode = None,
+    )
+
+    file = common_args.subdir + "-rustdoc-coverage"
+    use_cbp = getattr(ctx.attrs, "use_content_based_paths", False)
+    output = ctx.actions.declare_output(file, has_content_based_path = use_cbp)
+
+    plain_env, path_env = process_env(compile_ctx, ctx.attrs.env)
+    plain_env["RUSTDOC_BUCK_TARGET"] = cmd_args(str(ctx.label.raw_target()))
+
+    if toolchain_info.rust_target_path != None:
+        path_env["RUST_TARGET_PATH"] = toolchain_info.rust_target_path[DefaultInfo].default_outputs[0]
+
+    # `--show-coverage` is unstable.
+    plain_env["RUSTC_BOOTSTRAP"] = cmd_args("1")
+    unstable_options = ["-Zunstable-options"]
+
+    rustdoc_cmd_action = cmd_args(
+        [cmd_args("--env=", k, "=", v, delimiter = "") for k, v in plain_env.items()],
+        [cmd_args("--path-env=", k, "=", v, delimiter = "") for k, v in path_env.items()],
+        toolchain_info.rustdoc,
+        "--rustc-action-separator",
+        toolchain_info.rustdoc_flags,
+        ctx.attrs.rustdoc_flags,
+        common_args.args,
+        unstable_options,
+        "--show-coverage",
+    )
+
+    rustdoc_cmd = _long_command(
+        ctx = ctx,
+        exe = compile_ctx.internal_tools_info.rustc_action,
+        args = rustdoc_cmd_action,
+        argfile_name = "{}.args".format(file),
+        has_content_based_path = use_cbp,
+    )
+
+    cmd = cmd_args([compile_ctx.internal_tools_info.rustdoc_coverage, output.as_output(), rustdoc_cmd])
+
+    ctx.actions.run(cmd, category = "rustdoc_coverage")
+
+    return output
+
+def generate_rustdoc_test(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    rlib: Artifact,
+    link_infos: dict[LibOutputStyle, LinkInfos],
+    params: BuildParams,
+    default_roots: list[str],
+) -> cmd_args:
+    toolchain_info = compile_ctx.toolchain_info
+
+    if not toolchain_info.nightly_features:
+        fail("Doctests use the unstable `--test-runtool` flag and require a toolchain with `nightly_features = True`")
+
+    internal_tools_info = compile_ctx.internal_tools_info
+    doc_dep_ctx = DepCollectionContext(
+        advanced_unstable_linking = compile_ctx.dep_ctx.advanced_unstable_linking,
+        include_doc_deps = True,
+        is_proc_macro = False,
+        explicit_sysroot_deps = compile_ctx.dep_ctx.explicit_sysroot_deps,
+        panic_runtime = compile_ctx.dep_ctx.panic_runtime,
+    )
+    transitive_srcs = ctx.actions.tset(
+        RustSourcesTSet,
+        value = compile_ctx.symlinked_srcs,
+        children = [d.dep[RustSources].tset for d in resolve_deps(ctx, doc_dep_ctx) if RustSources in d.dep],
+    )
+
+    resources = create_resource_db(
+        ctx = ctx,
+        name = "doctest/resources.json",
+        binary = rlib,
+        resources = flatten_dict(
+            gather_resources(
+                label = ctx.label,
+                resources = rust_attr_resources(ctx),
+                deps = cxx_attr_deps(ctx),
+            ).values()
+        ),
+    )
+
+    # Gather and setup symlink tree of transitive shared library deps.
+    if params.dep_link_strategy == LinkStrategy("shared"):
+        shlib_info = merge_shared_libraries(
+            ctx.actions,
+            deps = inherited_shared_libs(ctx, doc_dep_ctx),
+        )
+        executable_args = executable_shared_lib_arguments_from_shared_library_info(
+            ctx,
+            compile_ctx.cxx_toolchain_info,
+            compile_ctx.internal_tools_info,
+            resources,
+            shlib_info,
+        )
+    else:
+        executable_args = executable_shared_lib_arguments(
+            ctx,
+            compile_ctx.cxx_toolchain_info,
+            resources,
+            shared_libs = [],
+        )
+
+    common_args = _compute_common_args(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        dep_ctx = doc_dep_ctx,
+        emit = Emit("link"),
+        params = params,
+        default_roots = default_roots,
+        infallible_diagnostics = False,
+        is_rustdoc_test = True,
+        incremental_enabled = False,
+        profile_mode = None,
+    )
+
+    link_args_output = make_link_args(
+        ctx,
+        ctx.actions,
+        compile_ctx.cxx_toolchain_info,
+        [
+            LinkArgs(flags = executable_args.extra_link_args),
+            get_link_args_for_strategy(
+                ctx.actions,
+                ctx.label,
+                compile_ctx.cxx_toolchain_info.linker_info,
+                # Since we pass the rlib in and treat it as a dependency to the rustdoc test harness,
+                # we need to ensure that the rlib's link info is added to the linker, otherwise we may
+                # end up with missing symbols that are defined within the crate.
+                [
+                    create_merged_link_info(
+                        ctx,
+                        compile_ctx.cxx_toolchain_info.pic_behavior,
+                        link_infos,
+                        deps = inherited_merged_link_infos(ctx, doc_dep_ctx),
+                        preferred_linkage = Linkage("static"),
+                    )
+                ]
+                + inherited_merged_link_infos(ctx, doc_dep_ctx),
+                params.dep_link_strategy,
+                prefer_stripped = False,
+                transformation_spec_context = None,
+            ),
+        ],
+    )
+
+    link_args_output.link_args.add(ctx.attrs.doc_linker_flags or [])
+
+    linker_argsfile, _ = ctx.actions.write(
+        "{}/__{}_linker_args.txt".format(common_args.subdir, common_args.tempfile),
+        link_args_output.link_args,
+        allow_args = True,
+        has_content_based_path = False,
+    )
+
+    if compile_ctx.exec_is_windows:
+        runtool = ["--test-runtool=cmd.exe", "--test-runtool-arg=/V:OFF", "--test-runtool-arg=/C"]
+    else:
+        runtool = ["--test-runtool=/usr/bin/env"]
+
+    plain_env, path_env = process_env(compile_ctx, ctx.attrs.env)
+    doc_plain_env, doc_path_env = process_env(compile_ctx, ctx.attrs.doc_env)
+    for k, v in doc_plain_env.items():
+        path_env.pop(k, None)
+        plain_env[k] = v
+    for k, v in doc_path_env.items():
+        plain_env.pop(k, None)
+        path_env[k] = v
+
+    # `--test-runtool` is unstable.
+    plain_env["RUSTC_BOOTSTRAP"] = cmd_args("1")
+    unstable_options = ["-Zunstable-options"]
+
+    if toolchain_info.rust_target_path != None:
+        path_env["RUST_TARGET_PATH"] = toolchain_info.rust_target_path[DefaultInfo].default_outputs[0]
+
+    rustdoc_cmd = cmd_args(
+        [cmd_args("--env=", k, "=", v, delimiter = "") for k, v in plain_env.items()],
+        [cmd_args("--path-env=", k, "=", v, delimiter = "") for k, v in path_env.items()],
+        toolchain_info.rustdoc,
+        "--rustc-action-separator",
+        "--test",
+        unstable_options,
+        cmd_args("--test-builder=", toolchain_info.compiler, delimiter = ""),
+        toolchain_info.rustdoc_flags,
+        ctx.attrs.rustdoc_flags,
+        common_args.args,
+        extern_arg([], attr_crate(ctx), rlib),
+        "--extern=proc_macro" if ctx.attrs.proc_macro else [],
+        cmd_args(compile_ctx.linker_with_pre_args, format = "-Clinker={}"),
+        cmd_args(linker_argsfile, format = "-Clink-arg=@{}"),
+        runtool,
+        cmd_args(internal_tools_info.rustdoc_test_with_resources, format = "--test-runtool-arg={}"),
+        cmd_args("--test-runtool-arg=--resources=", resources, delimiter = ""),
+        "--color=always",
+        "--test-args=--color=always",
+        cmd_args(
+            "--remap-path-prefix=",
+            compile_ctx.symlinked_srcs,
+            compile_ctx.path_sep,
+            "=",
+            compile_ctx.symlinked_srcs.owner.path,
+            compile_ctx.path_sep,
+            delimiter = "",
+        ),
+        hidden = [
+            transitive_srcs.project_as_args("artifacts"),
+            link_args_output.hidden,
+            executable_args.runtime_files,
+        ],
+    )
+
+    return _long_command(
+        ctx = ctx,
+        exe = internal_tools_info.rustc_action,
+        args = rustdoc_cmd,
+        argfile_name = "{}.args".format(common_args.subdir),
+        has_content_based_path = getattr(ctx.attrs, "use_content_based_paths", False),
+    )
+
+LinkExtraction = record(
+    # cmd_script set via `-Clinker=`.
+    linker_wrapper = field(typing.Any),
+    # The retained linker args. Contains no paths, only flags, and so is safe
+    # to pass along verbatim even under content-based paths.
+    out_argsfile = field(Artifact),
+    # Extracted link inputs directory.
+    out_artifacts_dir = field(Artifact),
+    # Basenames of the extracted objects, one per line, in link order.
+    out_manifest = field(Artifact),
+    # Archive of the rustc-produced objects. Only built when used by
+    # distributed thinlto.
+    out_archive = field(Artifact | None),
+)
+
+def _archiver_command(ctx: AnalysisContext, compile_ctx: CompileContext, subdir: str, archive_cbp: bool) -> cmd_args:
+    linker_info = compile_ctx.cxx_toolchain_info.linker_info
+    archiver_type = linker_info.archiver_type
+
+    if archiver_type not in ["gnu", "llvm", "bsd"]:
+        fail("archiving rust link objects is unsupported for archiver type '{}'".format(archiver_type))
+
+    archiver_cmd = cmd_args(
+        linker_info.archiver,
+        archive_flags(
+            archiver_type,
+            linker_info.type,
+            linker_info.use_archiver_flags,
+            linker_info.archive_symbol_table,
+            thin = False,
+        ),
+    )
+    if linker_info.use_archiver_flags and linker_info.archiver_flags != None:
+        archiver_cmd.add(linker_info.archiver_flags)
+
+    argsfile, _ = ctx.actions.write(
+        subdir + "/archiver.args",
+        archiver_cmd,
+        allow_args = True,
+        has_content_based_path = archive_cbp,
+    )
+    return cmd_args(argsfile, hidden = linker_info.archiver)
+
+def _setup_link_extraction(ctx: AnalysisContext, compile_ctx: CompileContext, subdir: str, emit_cbp: bool, archive_objects: bool) -> LinkExtraction:
+    out_argsfile = ctx.actions.declare_output(subdir + "/extracted-link-args.args", has_content_based_path = emit_cbp)
+    out_artifacts_dir = ctx.actions.declare_output(subdir + "/extracted-link-artifacts", dir = True, has_content_based_path = emit_cbp)
+    out_manifest = ctx.actions.declare_output(subdir + "/extracted-link-manifest.txt", has_content_based_path = emit_cbp)
+    linker_cmd = cmd_args(
+        compile_ctx.internal_tools_info.extract_link_action,
+        cmd_args(out_argsfile.as_output(), format = "--out_argsfile={}"),
+        cmd_args(out_artifacts_dir.as_output(), format = "--out_artifacts={}"),
+        cmd_args(out_manifest.as_output(), format = "--out_manifest={}"),
+    )
+
+    out_archive = None
+    if archive_objects:
+        archive_cbp = compile_ctx.cxx_toolchain_info.linker_info.supports_content_based_paths_for_archiving == True
+        out_archive = ctx.actions.declare_output(subdir + "/extracted-objects.a", has_content_based_path = archive_cbp)
+        linker_cmd.add(cmd_args(out_archive.as_output(), format = "--out_archive={}"))
+        linker_cmd.add(cmd_args(_archiver_command(ctx, compile_ctx, subdir, archive_cbp), format = "--archiver_argsfile={}"))
+
+    linker_cmd.add(compile_ctx.linker_with_pre_args)
+    linker_wrapper = cmd_script(
+        actions = ctx.actions,
+        name = subdir + "/linker_wrapper",
+        cmd = linker_cmd,
+        language = ctx.attrs._exec_os_type[OsLookup].script,
+        has_content_based_path = True,
+    )
+    return LinkExtraction(
+        linker_wrapper = linker_wrapper,
+        out_argsfile = out_argsfile,
+        out_artifacts_dir = out_artifacts_dir,
+        out_manifest = out_manifest,
+        out_archive = out_archive,
+    )
+
+# Generate a compilation action. A single instance of rustc can emit
+# numerous output artifacts, so return an artifact object for each of
+# them.
+def rust_compile(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    emit: Emit,
+    params: BuildParams,
+    default_roots: list[str],
+    incremental_enabled: bool,
+    extra_link_args: list[typing.Any] = [],
+    predeclared_output: Artifact | None = None,
+    # Whether `predeclared_output` was declared with a content-based path. The
+    # linker writes its side outputs (the `.pdb` on Windows) beside the binary,
+    # so they must be declared with the binary's path mode to be found.
+    predeclared_output_has_content_based_path: bool = False,
+    extra_flags: list[str | ResolvedStringWithMacros | Artifact] = [],
+    allow_cache_upload: bool = False,
+    # Setting this to true causes the diagnostic outputs that are generated
+    # from this action to always be successfully generated, even if
+    # compilation fails. This should not generally be used if the "real"
+    # output of the action is going to be depended on
+    infallible_diagnostics: bool = False,
+    transformation_spec_context: TransformationSpecContext | None = None,
+    profile_mode: ProfileMode | None = None,
+    precomputed_inherited_link_args: LinkArgs | None = None,
+) -> RustcOutput:
+    toolchain_info = compile_ctx.toolchain_info
+
+    if not toolchain_info.nightly_features:
+        if emit == Emit("expand"):
+            fail("Expansion uses the unstable `-Zunpretty` flag and requires a toolchain with `nightly_features = True`")
+        if profile_mode in (ProfileMode("llvm-time-trace"), ProfileMode("self-profile")):
+            fail("`{}` profiling uses unstable `-Z` flags and requires a toolchain with `nightly_features = True`".format(profile_mode.value))
+
+    lints = _lint_flags(compile_ctx, infallible_diagnostics, emit == Emit("clippy"))
+
+    common_args = _compute_common_args(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        dep_ctx = compile_ctx.dep_ctx,
+        emit = emit,
+        params = params,
+        default_roots = default_roots,
+        infallible_diagnostics = infallible_diagnostics,
+        incremental_enabled = incremental_enabled,
+        is_rustdoc_test = False,
+        profile_mode = profile_mode,
+    )
+
+    requires_linking = crate_type_linked(params.crate_type) and emit == Emit("link")
+    extracts_objects = emit == Emit("rlib") and params.crate_type == CrateType("bin")
+
+    if (
+        emit == Emit("link")
+        and compile_ctx.toolchain_info.advanced_unstable_linking
+        # FIXME(JakobDegen): We should probably not support cdylib or staticlib under AUL
+        and params.crate_type not in [CrateType("rlib"), CrateType("proc-macro"), CrateType("staticlib"), CrateType("cdylib")]
+    ):
+        fail('rustc-driven linking is not supported with `advanced_unstable_linking`: binaries compile via `Emit("rlib")` and link through cxx')
+
+    if extracts_objects:
+        if not compile_ctx.toolchain_info.advanced_unstable_linking:
+            fail(
+                '`Emit("rlib")` for a bin crate requires `advanced_unstable_linking`: without it, dependency link providers do not carry the rlibs for cxx to link'
+            )
+        if predeclared_output != None:
+            fail("extraction produces no linked output; the caller owns the linked artifact and must produce it via `rust_link_binary`")
+
+    use_cbp = getattr(ctx.attrs, "use_content_based_paths", False)
+    emit_cbp = use_cbp if predeclared_output == None else predeclared_output_has_content_based_path
+
+    rustc_cmd = cmd_args(
+        # Lints go first to allow other args to override them.
+        lints,
+        # Report unused --extern crates in the notification stream.
+        ["--json=unused-externs-silent", "-Wunused-crate-dependencies"] if toolchain_info.report_unused_deps else [],
+        common_args.args,
+        cmd_args(
+            "--remap-path-prefix=",
+            compile_ctx.symlinked_srcs,
+            compile_ctx.path_sep,
+            "=",
+            compile_ctx.symlinked_srcs.owner.path,
+            compile_ctx.path_sep,
+            delimiter = "",
+        ),
+        ["-Zremap-cwd-prefix=."] if toolchain_info.nightly_features else [],
+        extra_flags,
+    )
+
+    rustc_bin = compile_ctx.clippy_wrapper if emit == Emit("clippy") else toolchain_info.compiler
+
+    # If we're using failure filtering then we need to make sure the final
+    # artifact location is the predeclared one since its specific path may have
+    # already been encoded into the other compile args (eg rpath). So we still
+    # let rustc_emit generate its own output artifacts, and then make sure we
+    # use the predeclared one as the output after the failure filter action
+    # below. Otherwise we'll use the predeclared outputs directly.
+    if infallible_diagnostics:
+        emit_op = _rustc_emit(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = emit,
+            subdir = common_args.subdir,
+            params = params,
+            incremental_enabled = incremental_enabled,
+            profile_mode = profile_mode,
+        )
+    else:
+        emit_op = _rustc_emit(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = emit,
+            subdir = common_args.subdir,
+            params = params,
+            predeclared_output = predeclared_output,
+            incremental_enabled = incremental_enabled,
+            profile_mode = profile_mode,
+        )
+
+    if emit == Emit("clippy"):
+        clippy_toml = None
+        if ctx.attrs.clippy_configuration:
+            clippy_toml = ctx.attrs.clippy_configuration[ClippyConfiguration].clippy_toml
+        elif toolchain_info.clippy_toml:
+            clippy_toml = toolchain_info.clippy_toml
+
+        if clippy_toml:
+            # Clippy wants to be given a path to a directory containing a
+            # clippy.toml (or .clippy.toml). Our buckconfig accepts an arbitrary
+            # label like //path/to:my-clippy.toml which may not have the
+            # filename that clippy looks for. Here we make a directory that
+            # symlinks the requested configuration file under the required name.
+            clippy_conf_dir = ctx.actions.symlinked_dir(
+                common_args.subdir + "-clippy-configuration",
+                {"clippy.toml": clippy_toml},
+                has_content_based_path = use_cbp,
+            )
+            emit_op.env["CLIPPY_CONF_DIR"] = clippy_conf_dir
+
+    split_debug_mode = compile_ctx.cxx_toolchain_info.split_debug_mode or SplitDebugMode("none")
+    has_split_debug = split_debug_mode != SplitDebugMode("none")
+
+    strip_dwo_members = _strip_dwo_members_args(
+        compile_ctx = compile_ctx,
+        emit = emit,
+        crate_type = params.crate_type,
+        output = emit_op.output,
+        has_split_debug = has_split_debug,
+    )
+
+    import_library = None
+    pdb_artifact = None
+    dwp_inputs = []
+    link_extraction = None
+    if requires_linking:
+        if params.crate_type in [CrateType("cdylib"), CrateType("dylib")]:
+            linker_info = compile_ctx.cxx_toolchain_info.linker_info
+            shlib_name = compile_ctx.soname
+            rustc_cmd.add(
+                cmd_args(
+                    get_shared_library_name_linker_flags(linker_info.type, shlib_name),
+                    format = "-Clink-arg={}",
+                )
+            )
+            (import_library, import_library_args) = get_import_library(
+                ctx = ctx,
+                linker_type = compile_ctx.cxx_toolchain_info.linker_info.type,
+                output_short_path = emit_op.output.short_path,
+            )
+        else:
+            import_library_args = []
+
+        subdir = common_args.subdir
+        tempfile = common_args.tempfile
+
+        inherited_link_args = precomputed_inherited_link_args
+        if inherited_link_args == None:
+            inherited_link_args = get_inherited_link_args(
+                ctx,
+                compile_ctx,
+                params.dep_link_strategy,
+                None,  # link group info
+                transformation_spec_context,
+            )
+
+        link_args_output = make_link_args(
+            ctx,
+            ctx.actions,
+            compile_ctx.cxx_toolchain_info,
+            [
+                LinkArgs(flags = extra_link_args),
+                inherited_link_args,
+                LinkArgs(flags = import_library_args),
+            ],
+            output_short_path = emit_op.output.short_path,
+            has_content_based_path = emit_cbp,
+        )
+
+        separate_debug_info_args = cmd_args()
+        if has_split_debug:
+            inherited_debug_info = inherited_external_debug_info(
+                ctx = ctx,
+                dep_ctx = compile_ctx.dep_ctx,
+                dep_link_strategy = params.dep_link_strategy,
+            )
+            external_debug_infos = project_artifacts(ctx.actions, inherited_debug_info)
+            dwp_inputs.extend(external_debug_infos)
+
+            # Pass to the link wrapper the paths to the .dwo/.o files to rewrite, if we are
+            # using split debug with content-based paths.
+            if (
+                compile_ctx.cxx_toolchain_info.cxx_compiler_info.supports_content_based_paths
+                and
+                # Darwin does not embed paths in object files themselves, but rather
+                # the linker writes those paths based on the location of object files passed
+                # to the link.
+                compile_ctx.cxx_toolchain_info.linker_info.type != LinkerType("darwin")
+            ):
+                # Note: Unlike in C++, Rust does binary linking and object code generation in the same
+                # action. As a result, the .dwo files generated by that action are missing from the
+                # inputs here and so do not participate in the re-writing. Right now that doesn't matter
+                # anyway because Rust doesn't have content addressed artifacts. In the future that may
+                # be a source of bugs though.
+                separate_debug_info_path_file, _ = ctx.actions.write(
+                    "{}/__{}_dwo_paths.txt".format(subdir, tempfile),
+                    external_debug_infos,
+                    allow_args = True,
+                    has_content_based_path = False,
+                )
+                separate_debug_info_args = cmd_args(
+                    "--rewrite-content-based-dwo-paths",
+                    separate_debug_info_path_file,
+                    "--content-based-dwo-suffix",
+                    ".dwo" if split_debug_mode == SplitDebugMode("split") else ".o",
+                )
+
+        linker_argsfile, _ = ctx.actions.write(
+            "{}/__{}_linker_args.txt".format(subdir, tempfile),
+            cmd_args(link_args_output.link_args, separate_debug_info_args),
+            allow_args = True,
+            has_content_based_path = False,
+        )
+        linker_argsfile = cmd_args(
+            linker_argsfile,
+            hidden = [link_args_output.hidden, separate_debug_info_args],
+        )
+
+        pdb_artifact = link_args_output.pdb_artifact
+        dwp_inputs.append(link_args_output.link_args)
+
+        rustc_cmd.add(cmd_args(linker_argsfile, format = "-Clink-arg=@{}"))
+        rustc_cmd.add(cmd_args(compile_ctx.linker_with_pre_args, format = "-Clinker={}"))
+    elif extracts_objects:
+        # rustc only compiles; the caller links the extracted objects through
+        # cxx (see `rust_link_binary`), and the link args are constructed
+        # there. rustc never sees them.
+        link_extraction = _setup_link_extraction(
+            ctx,
+            compile_ctx,
+            common_args.subdir,
+            emit_cbp,
+            # FIXME(JakobDegen): Better explain why this is needed
+            archive_objects = _dist_thinlto_enabled(ctx, compile_ctx),
+        )
+        rustc_cmd.add(cmd_args(link_extraction.linker_wrapper, format = "-Clinker={}"))
+
+    if toolchain_info.rust_target_path != None:
+        emit_op.env["RUST_TARGET_PATH"] = toolchain_info.rust_target_path[DefaultInfo].default_outputs[0]
+
+    invoke = _rustc_invoke(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        common_args = common_args,
+        prefix = "{}/{}".format(common_args.subdir, common_args.tempfile),
+        rustc_cmd = cmd_args(
+            rustc_bin,
+            "--rustc-action-separator",
+            rustc_cmd,
+            emit_op.args,
+        ),
+        required_outputs = [emit_op.output] if emit_op.output else [],
+        is_clippy = emit.value == "clippy",
+        infallible_diagnostics = infallible_diagnostics,
+        allow_cache_upload = allow_cache_upload and emit != Emit("clippy"),
+        crate_map = common_args.crate_map,
+        env = emit_op.env,
+        incremental_enabled = incremental_enabled,
+        profile_mode = profile_mode,
+        strip_dwo_members = strip_dwo_members,
+    )
+
+    if extracts_objects:
+        # There is no linked artifact; stand in with the manifest of extracted
+        # objects, which is the closest thing this compile produced.
+        filtered_output = link_extraction.out_manifest
+    elif infallible_diagnostics and emit != Emit("clippy"):
+        # This is only needed when this action's output is being used as an
+        # input, so we only need standard diagnostics (clippy is always
+        # asked for explicitly).
+        filtered_output = failure_filter(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            predeclared_output = predeclared_output,
+            build_status = invoke.build_status,
+            required = emit_op.output,
+            stderr = invoke.diag_txt,
+            identifier = invoke.identifier,
+        )
+    else:
+        filtered_output = emit_op.output
+
+    singleton_tset = ctx.actions.tset(
+        TransitiveDeps,
+        value = RustArtifact(
+            artifact = filtered_output,
+            crate = attr_crate(ctx),
+        ),
+    )
+
+    if (emit == Emit("link") or emit == Emit("rlib")) and has_split_debug:
+        dwo_output_directory = emit_op.extra_out
+        dwp_inputs.append(dwo_output_directory)
+    else:
+        dwo_output_directory = None
+
+    if requires_linking and dwp_available(compile_ctx.cxx_toolchain_info):
+        dwp_output = dwp(
+            ctx,
+            compile_ctx.cxx_toolchain_info,
+            emit_op.output,
+            identifier = "{}/__{}_{}_dwp".format(common_args.subdir, common_args.tempfile, emit.value),
+            category_suffix = "rust",
+            # TODO(T110378142): Ideally, referenced objects are a list of
+            # artifacts, but currently we don't track them properly.  So, we
+            # just pass in the full link line and extract all inputs from that,
+            # which is a bit of an overspecification.
+            referenced_objects = dwp_inputs,
+        )
+    else:
+        dwp_output = None
+
+    # FIXME(JakobDegen): What's going on with stripped objects in binaries? What is this what cxx does?
+    if emit in [Emit("rlib"), Emit("link")] and not extracts_objects:
+        stripped_output = strip_debug_info(
+            ctx.actions,
+            paths.join(
+                common_args.subdir,
+                "stripped",
+                output_filename(
+                    compile_ctx,
+                    attr_simple_crate_for_filenames(ctx),
+                    Emit("link"),
+                    params,
+                ),
+            ),
+            filtered_output,
+            compile_ctx.cxx_toolchain_info,
+            has_content_based_path = getattr(ctx.attrs, "use_content_based_paths", False),
+        )
+    else:
+        stripped_output = None
+
+    # When profile_mode is remarks, the remarks are included in the diagnostic stream
+    # (same as diag_txt/diag_json), not a separate artifact
+    remarks_txt = invoke.diag_txt if profile_mode == ProfileMode("remarks") else None
+    remarks_json = invoke.diag_json if profile_mode == ProfileMode("remarks") else None
+
+    return RustcOutput(
+        output = filtered_output,
+        singleton_tset = singleton_tset,
+        compile_output = RustcCompileOutput(
+            stripped_output = stripped_output,
+            diag_txt = invoke.diag_txt,
+            diag_json = invoke.diag_json,
+            dwo_output_directory = dwo_output_directory,
+            profile_output = emit_op.profile_out,
+            remarks_txt = remarks_txt,
+            remarks_json = remarks_json,
+        ),
+        link_output = RustcLinkOutput(
+            import_library = import_library,
+            pdb = pdb_artifact,
+            dwp_output = dwp_output,
+        )
+        if emit == Emit("link")
+        else None,
+        link_extraction = link_extraction,
+    )
+
+# --extern <crate>=<path> for direct dependencies
+# -Ldependency=<dir> for transitive dependencies
+# For native dependencies, we use -Clink-arg=@argsfile
+#
+# Second element of returned tuple is an @argsfile containing the -Ldependency=<dir> for transitive dependencies.
+# It is separate from the first element because some commands (e.g., rustc) do NOT support nested @argsfiles.
+#
+# Third element of returned tuple is a mapping from crate names back to target
+# label, needed for applying autofixes for rustc's unused_crate_dependencies
+# lint by tracing Rust crate names in the compiler diagnostic back to which
+# dependency entry in the BUCK file needs to be removed.
+#
+# The `compile_ctx` may be omitted if there are no dependencies with dynamic
+# crate names.
+#
+# cwd: Optional directory the @argsfiles contents will be relative to (e.g., relative -Ldependency paths for rustc).
+def dependency_args(
+    ctx: AnalysisContext,
+    internal_tools_info: RustInternalToolsInfo,
+    transitive_dependency_dirs: set[Artifact],
+    toolchain_info: RustToolchainInfo,
+    deps: list[RustDependency],
+    subdir: str,
+    dep_link_strategy: LinkStrategy,
+    dep_metadata_kind: MetadataKind,
+    is_rustdoc_test: bool,
+    cwd: Artifact | None = None,
+) -> (cmd_args, cmd_args, list[(CrateName, Label)]):
+    args = cmd_args()
+    transitive_deps = []
+    crate_targets = []
+    available_proc_macros = get_available_proc_macros(ctx)
+    for dep in deps:
+        if dep.name:
+            crate = CrateName(
+                simple = normalize_crate(dep.name),
+                dynamic = None,
+            )
+        else:
+            crate = dep.info.crate
+
+        strategy = strategy_info(toolchain_info, dep.info, dep_link_strategy)
+
+        artifact = strategy.outputs[dep_metadata_kind]
+        singleton_tset = strategy.singleton_tset[dep_metadata_kind]
+        transitive_artifacts = strategy.transitive_deps[dep_metadata_kind]
+
+        for marker in strategy.transitive_proc_macro_deps:
+            info = available_proc_macros[marker.label][RustLinkInfo]
+            strategy = strategy_info(toolchain_info, info, dep_link_strategy)
+            transitive_deps.append(strategy.singleton_tset[MetadataKind("link")])
+
+        args.add(extern_arg(dep.flags, crate, artifact))
+        crate_targets.append((crate, dep.label))
+
+        # Because deps of this *target* can also be transitive deps of this
+        # compiler invocation, pass the artifact (under its original crate name)
+        # through `-L` unconditionally for doc tests.
+        if is_rustdoc_test:
+            transitive_deps.append(singleton_tset)
+
+        # Unwanted transitive_deps have already been excluded
+        transitive_deps.append(transitive_artifacts)
+
+    prefix = "{}-deps{}".format(subdir, dep_metadata_kind.value)
+    transitive_deps = ctx.actions.tset(TransitiveDeps, children = transitive_deps)
+    argsfile = symlinked_dirs(ctx, internal_tools_info, transitive_dependency_dirs, prefix, transitive_deps, cwd)
+
+    return (args, argsfile, crate_targets)
+
+def symlinked_dirs(
+    ctx: AnalysisContext,
+    internal_tools_info: RustInternalToolsInfo,
+    transitive_dependency_dirs: set,
+    prefix: str,
+    transitive_deps: TransitiveDeps,
+    cwd: Artifact | None,
+) -> cmd_args:
+    name = "{}-symlinked_dirs".format(prefix)
+
+    transitive_dependency_dir = ctx.actions.declare_output(name, dir = True, has_content_based_path = False)
+
+    artifacts = transitive_deps.project_as_json("artifacts")
+
+    # Pass the list of rlibs to transitive_dependency_symlinks.py through a file
+    # because there can be a lot of them. This avoids running out of command
+    # line length, particularly on Windows.
+    artifacts_json = ctx.actions.write_json(
+        "{}-symlinked_dirs.json".format(prefix),
+        artifacts,
+        pretty = True,
+        has_content_based_path = getattr(ctx.attrs, "use_content_based_paths", False),
+    )
+
+    arguments = [
+        internal_tools_info.transitive_dependency_symlinks_tool,
+        cmd_args(ctx.label.name, format = "--name={}"),
+        cmd_args(transitive_dependency_dir.as_output(), format = "--out-dir={}"),
+        cmd_args(
+            artifacts_json,
+            format = "--artifacts={}",
+            # Don't take a dependency on all the artifacts in here, just the dynamic names; the
+            # rmetas/rlibs we only want to create symlinks to, so there's no need for them to
+            # actually be available
+            hidden = transitive_deps.project_as_args("dynamic_name_args"),
+        ),
+    ]
+
+    if cwd:
+        arguments.append(
+            cmd_args(
+                transitive_dependency_dir.as_output(),
+                format = "--out-dir-relative-to-cwd={}",
+                relative_to = cwd,
+            )
+        )
+
+    ctx.actions.run(
+        arguments,
+        category = "deps",
+        identifier = str(len(transitive_dependency_dirs)),
+    )
+
+    transitive_dependency_dirs.add(transitive_dependency_dir)
+
+    return cmd_args(
+        # Reference the directory Artifact (not the dirs file), so all of its children are included.
+        transitive_dependency_dir,
+        format = "@{}/dirs",
+        hidden = transitive_deps.project_as_args("artifacts_args"),
+    )
+
+def _lintify(flag: str, clippy: bool, lints: list[str | ResolvedStringWithMacros]) -> cmd_args:
+    return cmd_args(
+        [lint for lint in lints if clippy or not str(lint).startswith('"clippy::')],
+        format = "-{}{{}}".format(flag),
+    )
+
+def _lint_flags(compile_ctx: CompileContext, infallible_diagnostics: bool, is_clippy: bool) -> cmd_args:
+    toolchain_info = compile_ctx.toolchain_info
+
+    return cmd_args(
+        _lintify("A", is_clippy, toolchain_info.allow_lints),
+        _lintify("D", is_clippy, toolchain_info.deny_lints),
+        _lintify("D" if infallible_diagnostics else "W", is_clippy, toolchain_info.deny_on_check_lints),
+        _lintify("W", is_clippy, toolchain_info.warn_lints),
+    )
+
+def _check_restricted_rustc_flags(flags: list[str | ResolvedStringWithMacros | Artifact], toolchain_info: RustToolchainInfo):
+    if not toolchain_info.restricted_rustc_flags:
+        return
+    for flag in flags:
+        if isinstance(flag, str):
+            for restricted in toolchain_info.restricted_rustc_flags:
+                if restricted in flag:
+                    fail(
+                        "rustc flag `{}` is not allowed on individual targets ".format(flag)
+                        + "(matched restricted pattern `{}`). ".format(restricted)
+                        + "This flag must be set in the Rust toolchain, not on individual targets, "
+                        + "to ensure consistent compilation across the build graph. "
+                        + "If you have a legitimate need, set `uses_restricted_rustc_flags = True` on your target.",
+                    )
+
+def _rustc_flags(flags: list[str | ResolvedStringWithMacros | Artifact], toolchain_info: RustToolchainInfo) -> list[str | ResolvedStringWithMacros | Artifact]:
+    # Rustc's "-g" flag is documented as being exactly equivalent to
+    # "-Cdebuginfo=2". Rustdoc supports the latter, it just doesn't have the
+    # "-g" shorthand for it.
+    for i, flag in enumerate(flags):
+        flag = str(flag).strip('"')
+        if flag == "-g":
+            flags[i] = "-Cdebuginfo=2"
+        if toolchain_info.advanced_unstable_linking:
+            # The extraction drops rustc's linker argv apart from its synthesized
+            # inputs, so flags injected via `-Clink-arg` would be silently lost.
+            # `uses_restricted_rustc_flags` does not exempt this: unlike the flags
+            # that attribute normally guards, these would not merely be
+            # unsupported, they would silently not happen.
+            if "-Clink-arg" in flag or (flag == "-C" and i + 1 < len(flags) and str(flags[i + 1]).strip('"').startswith("link-arg")):
+                fail("flags passed via `-Clink-arg` are dropped when linking through cxx; use the target's or toolchain's `linker_flags` instead")
+
+            # Additional flags that rustc only forwards to the linker
+            if "-Cstrip" in flag or (flag == "-C" and i + 1 < len(flags) and str(flags[i + 1]).strip('"').startswith("strip")):
+                fail("`-Cstrip` has no effect when linking through cxx; use the `symbols` strip_mode, or `-Wl,--strip-all`/`-Wl,-S` in `linker_flags`, instead")
+            if "-Crpath" in flag or (flag == "-C" and i + 1 < len(flags) and str(flags[i + 1]).strip('"').startswith("rpath")):
+                fail("`-Crpath` has no effect when linking through cxx; pass `-Wl,-rpath,...` in `linker_flags` instead")
+            if "-Clink-dead-code" in flag or (flag == "-C" and i + 1 < len(flags) and str(flags[i + 1]).strip('"').startswith("link-dead-code")):
+                fail("`-Clink-dead-code` has no effect when linking through cxx; pass `-Wl,--no-gc-sections` in `linker_flags` instead")
+
+        if toolchain_info.explicit_sysroot_deps:
+            # `-Clink-self-contained` selects linker inputs bundled in the
+            # sysroot, and explicit sysroot deps point rustc at an empty one,
+            # so everything it can enable is a dangling reference. Only the
+            # subtractive forms make sense (the toolchain itself uses them to
+            # keep rustc from consulting the empty sysroot).
+            value = None
+            if flag.startswith("-Clink-self-contained"):
+                value = flag.removeprefix("-Clink-self-contained").removeprefix("=")
+            elif flag == "-C" and i + 1 < len(flags):
+                next_flag = str(flags[i + 1]).strip('"')
+                if next_flag.startswith("link-self-contained"):
+                    value = next_flag.removeprefix("link-self-contained").removeprefix("=")
+            if value != None:
+                for part in value.split(","):
+                    if part == "" or part in ("y", "yes", "on", "true") or part.startswith("+"):
+                        fail(
+                            "`-Clink-self-contained` cannot enable bundled linker inputs: explicit sysroot deps leave the sysroot empty, so there is nothing there to link"
+                        )
+
+    return flags
+
+# Differently parameterized build outputs need to be assigned nonoverlapping
+# output paths. For example the pic and non-pic rlib cannot both be written to
+# libfoo.rlib. We place artifacts into a unique subdirectory for each
+# permutation of build parameters.
+#
+# Keep this short or it exacerbates filepath length limits on Windows.
+#
+# Common examples:
+#     rlib pic static_pic metadata-fast diag => "LPPMD"
+#     bin pic shared link => "XPHL"
+def _abbreviated_subdir(
+    crate_type: CrateType,
+    reloc_model: RelocModel,
+    dep_link_strategy: LinkStrategy,
+    emit: Emit,
+    is_rustdoc_test: bool,
+    infallible_diagnostics: bool,
+    incremental_enabled: bool,
+    profile_mode: ProfileMode | None,
+) -> str:
+    crate_type = {
+        CrateType("bin"): "X",  # mnemonic: "eXecutable"
+        CrateType("rlib"): "L",  # "Library"
+        CrateType("dylib"): "D",
+        CrateType("proc-macro"): "M",  # "Macro"
+        CrateType("cdylib"): "C",
+        CrateType("staticlib"): "S",
+    }[crate_type]
+
+    reloc_model = {
+        RelocModel("static"): "S",
+        RelocModel("pic"): "P",
+        RelocModel("pie"): "I",
+        RelocModel("dynamic-no-pic"): "N",
+        RelocModel("ropi"): "O",
+        RelocModel("rwpi"): "W",
+        RelocModel("ropi-rwpi"): "R",
+        RelocModel("default"): "D",
+    }[reloc_model]
+
+    dep_link_strategy = {
+        LinkStrategy("static"): "T",
+        LinkStrategy("static_pic"): "P",
+        LinkStrategy("shared"): "H",
+    }[dep_link_strategy]
+
+    emit = {
+        Emit("asm"): "s",
+        Emit("llvm-bc"): "b",
+        Emit("llvm-ir"): "i",
+        Emit("llvm-ir-noopt"): "n",
+        Emit("obj"): "o",
+        Emit("link"): "L",
+        Emit("rlib"): "R",
+        Emit("dep-info"): "d",
+        Emit("mir"): "m",
+        Emit("expand"): "e",
+        Emit("clippy"): "c",
+        Emit("metadata-full"): "F",  # "Full metadata"
+        Emit("metadata-fast"): "M",  # "Metadata"
+    }[emit]
+
+    profile_mode = {
+        None: "",
+        ProfileMode("llvm-time-trace"): "L",
+        ProfileMode("self-profile"): "P",
+        ProfileMode("remarks"): "R",
+    }[profile_mode]
+
+    return (
+        crate_type
+        + reloc_model
+        + dep_link_strategy
+        + emit
+        + ("T" if is_rustdoc_test else "")
+        + ("D" if infallible_diagnostics else "")
+        + ("I" if incremental_enabled else "")
+        + profile_mode
+    )
+
+# Compute which are common to both rustc and rustdoc
+def _compute_common_args(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    dep_ctx: DepCollectionContext,
+    emit: Emit,
+    params: BuildParams,
+    default_roots: list[str],
+    infallible_diagnostics: bool,
+    incremental_enabled: bool,
+    is_rustdoc_test: bool,
+    profile_mode: ProfileMode | None,
+) -> CommonArgsInfo:
+    crate_type = params.crate_type
+
+    args_key = (crate_type, emit, params.dep_link_strategy, is_rustdoc_test, infallible_diagnostics, incremental_enabled, profile_mode)
+    if args_key in compile_ctx.common_args:
+        return compile_ctx.common_args[args_key]
+
+    subdir = _abbreviated_subdir(
+        crate_type = crate_type,
+        reloc_model = params.reloc_model,
+        dep_link_strategy = params.dep_link_strategy,
+        emit = emit,
+        is_rustdoc_test = is_rustdoc_test,
+        infallible_diagnostics = infallible_diagnostics,
+        incremental_enabled = incremental_enabled,
+        profile_mode = profile_mode,
+    )
+
+    # Included in tempfiles
+    tempfile = "{}-{}".format(attr_simple_crate_for_filenames(ctx), emit.value)
+
+    root = crate_root(ctx, default_roots)
+    if compile_ctx.exec_is_windows:
+        root = root.replace("/", "\\")
+
+    dep_metadata_kind = dep_metadata_of_emit(emit)
+
+    if dep_metadata_kind == MetadataKind("link") and (is_rustdoc_test or (compile_ctx.dep_ctx.advanced_unstable_linking and crate_type_linked(crate_type))):
+        # AUL rlibs compile against full metadata, so Rustdoc tests and
+        # rustc-linked outputs need the same full metadata deps to avoid crate
+        # hash mismatches. The linker receives the real rlibs through inherited
+        # link args.
+        dep_metadata_kind = MetadataKind("full")
+
+    dependency_args_key = (crate_type, params.dep_link_strategy, dep_metadata_kind, is_rustdoc_test)
+    cached_dependency_args = compile_ctx.dependency_args.get(dependency_args_key)
+    if cached_dependency_args == None:
+        dep_args, dep_argsfiles, crate_map = dependency_args(
+            ctx = ctx,
+            internal_tools_info = compile_ctx.internal_tools_info,
+            transitive_dependency_dirs = compile_ctx.transitive_dependency_dirs,
+            toolchain_info = compile_ctx.toolchain_info,
+            deps = resolve_rust_deps(ctx, dep_ctx),
+            subdir = subdir,
+            dep_link_strategy = params.dep_link_strategy,
+            dep_metadata_kind = dep_metadata_kind,
+            is_rustdoc_test = is_rustdoc_test,
+        )
+
+        dep_args.add(
+            cmd_args(
+                hidden = compile_ctx.transitive_srcs.project_as_args("artifacts") if compile_ctx else [],
+            )
+        )
+
+        # Add dep_argsfiles to dep_args because rustc_action supports nested @argfiles.
+        dep_args.add(dep_argsfiles)
+
+        if crate_type == CrateType("proc-macro"):
+            dep_args.add("--extern=proc_macro")
+
+        cached_dependency_args = DependencyArgsInfo(
+            args = dep_args,
+            crate_map = crate_map,
+        )
+        compile_ctx.dependency_args[dependency_args_key] = cached_dependency_args
+
+    dep_args = cached_dependency_args.args
+    crate_map = cached_dependency_args.crate_map
+
+    toolchain_info = compile_ctx.toolchain_info
+    edition = ctx.attrs.edition or toolchain_info.default_edition or fail("missing 'edition' attribute, and there is no 'default_edition' set by the toolchain")
+
+    crate = attr_crate(ctx)
+    if crate.dynamic:
+        crate_name_arg = cmd_args("--crate-name", cmd_args("@", crate.dynamic, delimiter = ""))
+    else:
+        crate_name_arg = cmd_args("--crate-name=", crate.simple, delimiter = "")
+
+    # The `-Cprefer-dynamic` flag controls rustc's choice of artifacts for
+    # transitive dependencies, both for loading metadata and linking them.
+    # Direct dependencies are given to rustc one-by-one using `--extern` with a
+    # path to a specific artifact, so there is never ambiguity what artifact to
+    # use for a direct dependency. But transitive dependencies are passed in
+    # bulk via zero or more `-Ldependency` flags, which are directories
+    # containing artifacts. Within those directories, information about a
+    # specific crate might be available from more than one artifact, such as a
+    # dylib and rlib for the same crate.
+    #
+    # With `-Cprefer-dynamic=no` (the default), when a transitive dependency
+    # exists as both rlib and dylib, metadata is loaded from the rlib. If some
+    # dependencies are available in dylib but not rlib, the dylib is used for
+    # those. With `-Cprefer-dynamic=yes`, when a transitive dependency exists as
+    # both rlib and dylib, instead the dylib is used.
+    #
+    # The ambiguity over whether to use rlib or dylib for a particular
+    # transitive dependency only occurs if the rlib and dylib both describe the
+    # same crate i.e. contain the same crate hash.
+    #
+    # Buck-built libraries never produce an rlib and dylib containing the same
+    # crate hash, since that only occurs when outputting multiple crate types
+    # through a single rustc invocation: `--crate-type=rlib --crate-type=dylib`.
+    # In Buck, different crate types are built by different rustc invocations.
+    # But Cargo does invoke rustc with multiple crate types when you write
+    # `[lib] crate-type = ["rlib", "dylib"]` in Cargo.toml, and in fact the
+    # standard libraries built by x.py and distributed by Rustup are built this
+    # way.
+    if toolchain_info.explicit_sysroot_deps:
+        # Standard libraries are being passed explicitly, and Buck-built
+        # dependencies never collide on crate hash, so `-Cprefer-dynamic` cannot
+        # make a difference.
+        prefer_dynamic_flags = []
+    elif crate_type == CrateType("dylib") and toolchain_info.advanced_unstable_linking:
+        # Use standard library dylibs from the implicit sysroot.
+        prefer_dynamic_flags = ["-Cprefer-dynamic=yes"]
+    else:
+        # Use standard library rlibs from the implicit sysroot.
+        prefer_dynamic_flags = ["-Cprefer-dynamic=no"]  # (the default)
+
+    split_debuginfo_flags = {
+        # Rustc's default behavior: debug info is put into every rlib and
+        # staticlib, then copied into the executables and shared libraries by
+        # the linker. This corresponds to `-gno-split-dwarf` in Clang.
+        SplitDebugMode("none"): [],
+        # Split DWARF: debug info is placed into *.dwo files in the directory
+        # specified by `--out-dir`. In Buck, this directory is usually called
+        # "extras" that is a sibling of the main output artifact (rlib,
+        # staticlib, executable, or shared library).
+        #
+        # Rustc produces one *.dwo per LLVM codegen unit, meaning potentially
+        # multiple per crate. The only debug info included into the main output
+        # artifact is the list of the associated *.dwo filenames in which the
+        # real debug info is provided.
+        #
+        # For each binary target, we have a separate step which involves
+        # `llvm-dwp` to combine all the *.dwo files from the dependency graph
+        # into one *.dwp. This is handled as a separate Buck action from the
+        # compiler/linker invocation responsible for linking the executable or
+        # shared library artifact.
+        #
+        # Rust's `-Csplit-debuginfo=unpacked` corresponds to `-gsplit-dwarf=split`
+        # in Clang, which behaves as just described.
+        #
+        # There is a second Clang debug mode, `-gsplit-dwarf=single`, that we
+        # also implement using `-Csplit-debuginfo=unpacked` in Rust. In Clang,
+        # "single" means include debug info into object files conceptually like
+        # `-gno-split-dwarf`, but do _not_ copy it at link time into executables
+        # and shared libraries. Similar to "split", there is an `llvm-dwp` step,
+        # separate from linking, to combine debug info from the dependency graph
+        # into one *.dwp output. Rustc has an option `-Csplit-debuginfo=packed`
+        # which works this way, putting split debug info into rlibs for
+        # libraries but keeping it separate for binaries. We have not been able
+        # to use `-Csplit-debuginfo=packed` because it runs into an error "unit
+        # referenced by executable was not found" when dealing with chains of
+        # dependencies from Rust -> C++ -> Rust (T147665047).
+        SplitDebugMode("single"): ["-Csplit-debuginfo=unpacked"],
+        SplitDebugMode("split"): ["-Csplit-debuginfo=unpacked"],
+    }[compile_ctx.cxx_toolchain_info.split_debug_mode or SplitDebugMode("none")]
+
+    if not getattr(ctx.attrs, "uses_restricted_rustc_flags", False):
+        _check_restricted_rustc_flags(ctx.attrs.rustc_flags, toolchain_info)
+
+    args = cmd_args(
+        cmd_args(compile_ctx.symlinked_srcs, compile_ctx.path_sep, root, delimiter = ""),
+        crate_name_arg,
+        "--crate-type={}".format(crate_type.value),
+        "-Crelocation-model={}".format(params.reloc_model.value),
+        "--edition={}".format(edition),
+        "-Cmetadata={}".format(_metadata(compile_ctx, ctx.label, is_rustdoc_test)[0]),
+        # Make diagnostics json with the option to extract rendered text
+        ["--error-format=json", "--json=diagnostic-rendered-ansi"] if not is_rustdoc_test else [],
+        prefer_dynamic_flags,
+        ["--target={}".format(toolchain_info.rustc_target_triple)] if toolchain_info.rustc_target_triple else [],
+        split_debuginfo_flags,
+        compile_ctx.sysroot_args,
+        # `-Zpanic-abort-tests` makes the test harness work despite the abort
+        # runtime. Without nightly features it can't be passed; test targets
+        # will be rejected by rustc.
+        (["-Cpanic=abort"] + (["-Zpanic-abort-tests=yes"] if toolchain_info.nightly_features else []))
+        if toolchain_info.panic_runtime == PanicRuntime("abort")
+        else [],
+        ["-Zsanitizer={}".format(toolchain_info.sanitizer.value)] if toolchain_info.sanitizer else [],
+        ["-Cprofile-generate={}".format(toolchain_info.pgo_generate_dir), "-Zno-profiler-runtime"]
+        if toolchain_info.pgo_generate_dir and toolchain_info.explicit_sysroot_deps and toolchain_info.explicit_sysroot_deps.core
+        else [],
+        [cmd_args(toolchain_info.pgo_profile, format = "-Cprofile-use={}")]
+        if toolchain_info.pgo_profile and toolchain_info.explicit_sysroot_deps and toolchain_info.explicit_sysroot_deps.core
+        else [],
+        _rustc_flags(toolchain_info.rustc_flags, toolchain_info),
+        # `rustc_check_flags` is specifically interpreted as flags that are used
+        # only on the metadata-fast graph.
+        _rustc_flags(toolchain_info.rustc_check_flags, toolchain_info) if dep_metadata_kind == MetadataKind("fast") else [],
+        _rustc_flags(toolchain_info.rustc_coverage_flags, toolchain_info) if ctx.attrs.coverage else [],
+        _rustc_flags(ctx.attrs.rustc_flags, toolchain_info),
+        _rustc_flags(toolchain_info.extra_rustc_flags, toolchain_info),
+        cmd_args(ctx.attrs.features, format = '--cfg=feature="{}"'),
+        dep_args,
+    )
+
+    common_args = CommonArgsInfo(
+        args = args,
+        subdir = subdir,
+        tempfile = tempfile,
+        crate_type = crate_type,
+        params = params,
+        emit = emit,
+        crate_map = crate_map,
+    )
+
+    compile_ctx.common_args[args_key] = common_args
+    return common_args
+
+def rust_compile_invalidation_inputs(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    emit: Emit,
+    params: BuildParams,
+    default_roots: list[str],
+    incremental_enabled: bool,
+) -> cmd_args:
+    return _compute_common_args(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        dep_ctx = compile_ctx.dep_ctx,
+        emit = emit,
+        params = params,
+        default_roots = default_roots,
+        infallible_diagnostics = False,
+        incremental_enabled = incremental_enabled,
+        is_rustdoc_test = False,
+        profile_mode = None,
+    ).args
+
+# Returns the full label and its hash. The full label is used for `-Cmetadata`
+# which provided the primary disambiguator for two otherwise identically named
+# crates. The hash is added to the filename to give them a lower likelihood of
+# duplicate names, but it doesn't matter if they collide.
+def _metadata(compile_ctx: CompileContext, label: Label, is_rustdoc_test: bool) -> (str, str):
+    raw_target = str(label.raw_target())
+    configuration_hash = compile_ctx.toolchain_info.configuration_hash or label.configured_target().config().hash
+    metadata = "{}#{}".format(raw_target, configuration_hash)
+
+    if is_rustdoc_test:
+        metadata = "doctest/" + metadata
+
+    int_hash = hash(metadata)
+    if int_hash < 0:
+        int_hash = -int_hash
+
+    hex_hash = "%x" % int_hash
+    hex_hash = "0" * (8 - len(hex_hash)) + hex_hash
+
+    return (metadata, hex_hash)
+
+def crate_root(ctx: AnalysisContext, default_roots: list[str]) -> str:
+    if ctx.attrs.crate_root:
+        return ctx.attrs.crate_root
+
+    srcs = [s.short_path for s in ctx.attrs.srcs] + ctx.attrs.mapped_srcs.values()
+
+    candidates = set()
+    if getattr(ctx.attrs, "crate_dynamic", None):
+        crate_with_suffix = None
+    else:
+        crate_with_suffix = attr_crate(ctx).simple + ".rs"
+    for src in srcs:
+        filename = src.split("/")[-1]
+        if filename in default_roots or filename == crate_with_suffix:
+            candidates.add(src)
+
+    if len(candidates) == 1:
+        return candidates.pop()
+
+    fail(
+        "Could not infer crate_root."
+        + "\nMake sure you have one of {} in your `srcs` attribute.".format(default_roots)
+        + "\nOr add 'crate_root = \"src/example.rs\"' to your attributes to disambiguate. candidates={}".format(candidates)
+    )
+
+def _explain(
+    crate_type: CrateType,
+    link_strategy: LinkStrategy,
+    emit: Emit,
+    infallible_diagnostics: bool,
+    profile_mode: ProfileMode | None,
+    advanced_unstable_linking: bool,
+) -> str:
+    base = None
+    if emit == Emit("metadata-full"):
+        link_strategy_suffix = {
+            LinkStrategy("static"): " [static]",
+            LinkStrategy("static_pic"): " [pic]",
+            LinkStrategy("shared"): " [shared]",
+        }[link_strategy]
+        base = "metadata" + link_strategy_suffix
+
+    if emit == Emit("metadata-fast"):
+        base = "diag" if infallible_diagnostics else "check"
+
+    if emit == Emit("rlib"):
+        if crate_type == CrateType("rlib"):
+            base = "rlib-no-meta" if advanced_unstable_linking else "rlib"
+        else:
+            base = "rlib-from-link"
+        base += {
+            LinkStrategy("static"): "",
+            LinkStrategy("static_pic"): " [pic]",
+            LinkStrategy("shared"): " [shared]",
+        }[link_strategy]
+
+    if emit == Emit("link"):
+        link_strategy_suffix = {
+            LinkStrategy("static"): "",
+            LinkStrategy("static_pic"): " [pic]",
+            LinkStrategy("shared"): " [shared]",
+        }[link_strategy]
+        if crate_type == CrateType("bin"):
+            base = "link" + link_strategy_suffix
+        if crate_type == CrateType("rlib"):
+            base = "rlib" + link_strategy_suffix
+        if crate_type == CrateType("dylib"):
+            base = "dylib" + link_strategy_suffix
+        if crate_type == CrateType("proc-macro"):
+            base = "proc-macro"  # always static_pic
+        if crate_type == CrateType("cdylib"):
+            base = "cdylib" + link_strategy_suffix
+        if crate_type == CrateType("staticlib"):
+            base = "staticlib" + link_strategy_suffix
+
+    if emit == Emit("expand"):
+        base = "expand"
+
+    for emit_type in ["asm", "llvm-ir", "mir"]:
+        if emit == Emit(emit_type):
+            link_strategy_suffix = {
+                LinkStrategy("static"): " [static]",
+                LinkStrategy("static_pic"): " [pic]",
+                LinkStrategy("shared"): " [shared]",
+            }[link_strategy]
+            base = emit_type + link_strategy_suffix
+
+    if emit == Emit("llvm-ir-noopt"):
+        base = "llvm-ir-noopt"
+
+    if base == None:
+        fail("unrecognized rustc action:", crate_type, link_strategy, emit)
+
+    if profile_mode:
+        return "{} [{}]".format(base, profile_mode.value)
+    else:
+        return base
+
+EmitOperation = record(
+    # None exactly for bin-crate `Emit("rlib")`: the caller owns the linked
+    # artifact, and rustc produces only the extraction outputs.
+    output = field(Artifact | None),
+    args = field(cmd_args),
+    env = field(dict[str, str]),
+    extra_out = field(Artifact | None),
+    profile_out = field(Artifact | None),
+)
+
+# Take a desired output and work out how to convince rustc to generate it
+def _rustc_emit(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    emit: Emit,
+    subdir: str,
+    params: BuildParams,
+    incremental_enabled: bool,
+    profile_mode: ProfileMode | None,
+    predeclared_output: Artifact | None = None,
+) -> EmitOperation:
+    simple_crate = attr_simple_crate_for_filenames(ctx)
+    crate_type = params.crate_type
+
+    emit_args = cmd_args()
+    emit_env = {}
+    extra_out = None
+    profile_out = None
+    use_cbp = getattr(ctx.attrs, "use_content_based_paths", False)
+
+    # When a predeclared_output is used (e.g. from rust_binary), all related
+    # outputs must match its content-based path setting (False) so that
+    # side-effect outputs like PDB are consistent with the binary.
+    emit_cbp = use_cbp if predeclared_output == None else False
+
+    if predeclared_output:
+        emit_output = predeclared_output
+
+        # Don't support profiles with predeclared outputs
+        crate_name_and_extra_for_profile = None
+    else:
+        extra_hash = "-" + _metadata(compile_ctx, ctx.label, False)[1]
+        emit_args.add("-Cextra-filename={}".format(extra_hash))
+        crate_name_and_extra_for_profile = simple_crate + extra_hash
+
+        if emit == Emit("rlib") and params.crate_type == CrateType("bin"):
+            # The caller links the extracted objects through cxx and owns the
+            # linked artifact; there is no rustc output to declare.
+            emit_output = None
+        else:
+            filename = subdir + "/" + output_filename(compile_ctx, simple_crate, emit, params, extra_hash)
+            emit_output = ctx.actions.declare_output(filename, has_content_based_path = emit_cbp)
+
+    if emit == Emit("expand"):
+        emit_args.add(
+            "-Zunpretty=expanded",
+            cmd_args(emit_output.as_output(), format = "-o{}"),
+        )
+    else:
+        if emit == Emit("metadata-full"):
+            if crate_type not in (CrateType("rlib"), CrateType("dylib")):
+                # Nothing ever needs the metadata from these crate types, so we can
+                # fall back to the `metadata-fast` behavior. Normally though, this
+                # artifact should be unused and so this shouldn't matter.
+                effective_emit = "metadata"
+            else:
+                # As we're doing a pipelined build, instead of emitting an actual rmeta
+                # we emit a "hollow" .rlib - ie, it only contains lib.rmeta and no object
+                # code. It should contain full information needed by any dependent
+                # crate which is generating code (MIR, etc).
+                #
+                # IMPORTANT: this flag is the only way that the Emit("metadata") and
+                # Emit("link") operations are allowed to diverge without causing them to
+                # get different crate hashes.
+                if not compile_ctx.toolchain_info.nightly_features:
+                    fail("Pipelined builds use the unstable `-Zno-codegen` flag and require a toolchain with `nightly_features = True`")
+                emit_args.add("-Zno-codegen")
+                effective_emit = "link"
+        elif emit == Emit("metadata-fast") or emit == Emit("clippy"):
+            effective_emit = "metadata"
+        elif emit == Emit("llvm-ir-noopt"):
+            effective_emit = "llvm-ir"
+            emit_args.add("-Cno-prepopulate-passes")
+        elif emit == Emit("rlib"):
+            # rlibs are `--emit=link` products of the rlib crate type. For bin
+            # crates there is additionally no output to bind: the extraction
+            # wrapper set via `-Clinker=` captures the objects instead.
+            effective_emit = "link"
+        else:
+            effective_emit = emit.value
+
+        # Pipelined builds still need metadata in `metadata-full`'s hollow rlib;
+        # native-linkable artifacts can omit it.
+        if compile_ctx.toolchain_info.advanced_unstable_linking and (
+            (emit == Emit("rlib") and crate_type == CrateType("rlib")) or (emit == Emit("link") and crate_type == CrateType("dylib"))
+        ):
+            emit_args.add("-Zembed-metadata=no")
+
+        if emit_output == None:
+            emit_args.add(cmd_args("--emit=", effective_emit, delimiter = ""))
+        else:
+            emit_args.add(cmd_args("--emit=", effective_emit, "=", emit_output.as_output(), delimiter = ""))
+
+        # Strip file extension from directory name.
+        base, _ext = paths.split_extension(output_filename(compile_ctx, simple_crate, emit, params))
+        extra_dir = subdir + "/extras/" + base
+        extra_out = ctx.actions.declare_output(extra_dir, dir = True, has_content_based_path = False)
+        emit_args.add(cmd_args(extra_out.as_output(), format = "--out-dir={}"))
+
+        if incremental_enabled:
+            incremental_out = ctx.actions.declare_output("{}/extras/incremental".format(subdir), has_content_based_path = False)
+            incremental_cmd = cmd_args(incremental_out.as_output(), format = "-Cincremental={}")
+            emit_args.add(incremental_cmd)
+
+        if profile_mode == ProfileMode("llvm-time-trace"):
+            emit_args.add("-Zllvm-time-trace=yes")
+            profile_out = extra_out.project(crate_name_and_extra_for_profile + ".llvm_timings.json")
+        elif profile_mode == ProfileMode("self-profile"):
+            self_profile = ctx.actions.declare_output("{}/extra/self-profile".format(subdir), dir = True, has_content_based_path = False)
+            emit_args.add("-Zself-profile-events=default,args")
+            emit_args.add(cmd_args("-Zself-profile=", self_profile.as_output(), delimiter = ""))
+            profile_out = self_profile
+        elif profile_mode == ProfileMode("remarks"):
+            # Enable LLVM remarks - they appear in the diagnostic stream (stderr)
+            # Use the configured filter, or default to "all"
+            # Allow comma-separated values for convenience (rustc expects space-separated)
+            remarks_filter = (compile_ctx.toolchain_info.remarks or "all").replace(",", " ")
+            emit_args.add("-Cremark={}".format(remarks_filter))
+
+    return EmitOperation(
+        output = emit_output,
+        args = emit_args,
+        env = emit_env,
+        extra_out = extra_out,
+        profile_out = profile_out,
+    )
+
+Invoke = record(
+    diag_txt = field(Artifact),
+    diag_json = field(Artifact),
+    build_status = field(Artifact | None),
+    identifier = field(str | None),
+)
+
+# Under `-Csplit-debuginfo=unpacked` (see `split_debuginfo_flags` in
+# `_compute_common_args`), rustc writes each codegen unit's `.dwo` to
+# `--out-dir` and also packs a copy of it into the rlib or staticlib, so that a
+# downstream `-Csplit-debuginfo=packed` link could build a dwp from the archive
+# alone. These rules never link that way: `dwp` reads the `--out-dir` files,
+# which flow to it as external debug info, and linkers never pull archive
+# members that define no symbols. A toolchain that sets `strip_dwo_from_rlibs`
+# has `rustc_action.py` delete those members inside the compile action, so the
+# archive is never cached or handed to a consumer with them.
+def _strip_dwo_members_args(compile_ctx: CompileContext, emit: Emit, crate_type: CrateType, output: Artifact | None, has_split_debug: bool) -> cmd_args | None:
+    if not compile_ctx.toolchain_info.strip_dwo_from_rlibs or not has_split_debug:
+        return None
+
+    # Only the `--emit=link` products of the archive crate types carry `.dwo`
+    # members. `Emit("rlib")` of an rlib crate is that product; the hollow
+    # rlibs of `metadata-full` are built without codegen and have none.
+    if crate_type not in [CrateType("rlib"), CrateType("staticlib")]:
+        return None
+    if emit not in [Emit("link"), Emit("rlib")] or output == None:
+        return None
+
+    linker_info = compile_ctx.cxx_toolchain_info.linker_info
+
+    # rustc emits DWARF objects only for targets whose debuginfo is plain DWARF
+    # (`Session::target_can_use_split_dwarf`): Apple (dSYM) and Windows (PDB)
+    # archives never carry `.dwo` members, so skip the archiver round-trip.
+    if linker_info.type in [LinkerType("darwin"), LinkerType("windows")]:
+        return None
+
+    # `d` is the member-deletion verb of the GNU, llvm and BSD archivers; the
+    # others (`lib.exe`, amdclang) have no equivalent this tool speaks, so
+    # toolchains using them keep the members.
+    if linker_info.archiver_type not in ["gnu", "llvm", "bsd"]:
+        return None
+
+    return cmd_args(
+        cmd_args(output.as_output(), format = "--strip-dwo-members={}"),
+        cmd_args(linker_info.archiver, format = "--archiver={}"),
+        # As in `archive_flags`: GNU-style archivers need `D` to leave
+        # timestamps out of the archive they write.
+        ["--archiver-deterministic"] if linker_info.type == LinkerType("gnu") else [],
+    )
+
+# Invoke rustc and capture outputs
+def _rustc_invoke(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    common_args: CommonArgsInfo,
+    prefix: str,
+    rustc_cmd: cmd_args,
+    required_outputs: list[Artifact],
+    is_clippy: bool,
+    infallible_diagnostics: bool,
+    allow_cache_upload: bool,
+    incremental_enabled: bool,
+    crate_map: list[(CrateName, Label)],
+    env: dict[str, str | ResolvedStringWithMacros | Artifact],
+    profile_mode: ProfileMode | None,
+    strip_dwo_members: cmd_args | None,
+) -> Invoke:
+    toolchain_info = compile_ctx.toolchain_info
+
+    plain_env, path_env = process_env(compile_ctx, toolchain_info.rustc_env | ctx.attrs.env)
+
+    more_plain_env, more_path_env = process_env(compile_ctx, env)
+    plain_env.update(more_plain_env)
+    path_env.update(more_path_env)
+
+    # `nightly_features` grants the rules use of unstable functionality. Both
+    # internally and in OSS the compiler is typically a stable-channel build,
+    # where that functionality must be unlocked by setting `RUSTC_BOOTSTRAP=1`;
+    # on an actual nightly compiler the variable is harmless. This must be
+    # uniform across all invocations for a crate: rustc includes the variable
+    # in its crate hashes, so differences between e.g. the metadata and link
+    # commands cause "found possibly newer version of crate" errors.
+    if toolchain_info.nightly_features and "RUSTC_BOOTSTRAP" not in plain_env:
+        plain_env["RUSTC_BOOTSTRAP"] = "1"
+
+    # Save diagnostic outputs
+    diag = "clippy" if is_clippy else "diag"
+    use_cbp = getattr(ctx.attrs, "use_content_based_paths", False)
+    diag_json = ctx.actions.declare_output("{}-{}.json".format(prefix, diag), has_content_based_path = use_cbp)
+    diag_txt = ctx.actions.declare_output("{}-{}.txt".format(prefix, diag), has_content_based_path = use_cbp)
+
+    compile_cmd = cmd_args(
+        cmd_args(diag_json.as_output(), format = "--diag-json={}"),
+        cmd_args(diag_txt.as_output(), format = "--diag-txt={}"),
+        ["--remap-cwd-prefix=."] if not toolchain_info.nightly_features else [],
+        "--buck-target={}".format(ctx.label.raw_target()),
+        hidden = [toolchain_info.compiler, compile_ctx.transitive_srcs.project_as_args("artifacts")],
+    )
+
+    for k, v in crate_map:
+        compile_cmd.add(crate_map_arg(k, v))
+    for k, v in plain_env.items():
+        compile_cmd.add(cmd_args("--env=", k, "=", v, delimiter = ""))
+    for k, v in path_env.items():
+        compile_cmd.add(cmd_args("--path-env=", k, "=", v, delimiter = ""))
+
+    build_status = None
+    if infallible_diagnostics:
+        # Build status for fail filter
+        build_status = ctx.actions.declare_output("{}_build_status-{}.json".format(prefix, diag), has_content_based_path = use_cbp)
+        compile_cmd.add(cmd_args(build_status.as_output(), format = "--failure-filter={}"))
+        for out in required_outputs:
+            compile_cmd.add("--required-output", out.short_path, out.as_output())
+
+    if strip_dwo_members != None:
+        compile_cmd.add(strip_dwo_members)
+
+    compile_cmd.add(rustc_cmd)
+
+    compile_cmd = _long_command(
+        ctx = ctx,
+        exe = compile_ctx.internal_tools_info.rustc_action,
+        args = compile_cmd,
+        argfile_name = "{}-{}.args".format(prefix, diag),
+        has_content_based_path = use_cbp,
+    )
+
+    local_only = False
+    prefer_local = False
+    if incremental_enabled:
+        local_only = True
+    elif common_args.crate_type == CrateType("bin") and common_args.emit == Emit("link") and link_cxx_binary_locally(ctx):
+        prefer_local = True
+
+    if is_clippy:
+        category = "clippy"
+        identifier = ""
+    else:
+        category = "rustc"
+        identifier = _explain(
+            crate_type = common_args.crate_type,
+            link_strategy = common_args.params.dep_link_strategy,
+            emit = common_args.emit,
+            infallible_diagnostics = infallible_diagnostics,
+            profile_mode = profile_mode,
+            advanced_unstable_linking = toolchain_info.advanced_unstable_linking,
+        )
+
+    if incremental_enabled:
+        if not identifier.endswith("]"):
+            identifier += " "
+        identifier += "[incr]"
+
+    # None defers the choice to the `buck2.default_allow_cache_upload` config; an
+    # explicit False overrides it. Actions without a preference pass None.
+    if incremental_enabled:
+        # Incremental compilation should not publish any action output to a shared cache:
+        # 1. the incremental compilation state is not useful for any other user. unfortunately,
+        #    there is no mechanism in buck2 that allows for uploading part of an action output
+        #    and not another.
+        # 2. even if there were, the rlib is not byte-for-byte reproducible
+        #    under `-Cincremental`, even if the source binary is unchanged, because of
+        #    https://github.com/rust-lang/rust/pull/139453.
+        # For additional context, please see this zulip conversation:
+        # https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/Possible.20Reproducibility.20Bug.20in.20Soundness.20Fix.3F/with/616729102.
+        action_allow_cache_upload = False
+    elif allow_cache_upload:
+        action_allow_cache_upload = True
+    elif is_clippy:
+        # Clippy never uploads.
+        action_allow_cache_upload = False
+    else:
+        # Libraries (check, metadata, rlib) have no preference.
+        action_allow_cache_upload = None
+
+    ctx.actions.run(
+        compile_cmd,
+        local_only = local_only,
+        prefer_local = prefer_local,
+        category = category,
+        identifier = identifier,
+        no_outputs_cleanup = incremental_enabled,
+        allow_cache_upload = action_allow_cache_upload,
+        error_handler = toolchain_info.rust_error_handler,
+    )
+
+    return Invoke(
+        diag_txt = diag_txt,
+        diag_json = diag_json,
+        build_status = build_status,
+        identifier = identifier,
+    )
+
+# Our rustc and rustdoc commands can have arbitrarily large number of `--extern`
+# flags, so write to file to avoid hitting the platform's limit on command line
+# length. This limit is particularly small on Windows.
+def _long_command(ctx: AnalysisContext, exe: RunInfo, args: cmd_args, argfile_name: str, has_content_based_path: bool = False) -> cmd_args:
+    return cmd_args(
+        exe,
+        at_argfile(
+            actions = ctx.actions,
+            name = argfile_name,
+            args = args,
+            allow_args = True,
+            has_content_based_path = has_content_based_path,
+        ),
+    )
+
+_DOUBLE_ESCAPED_NEWLINE_RE = regex("\\\\n")
+_ESCAPED_NEWLINE_RE = regex("\\n")
+_ESCAPED_CARRIAGE_RETURN_RE = regex("\\r")
+_DIRECTORY_ENV = [
+    "CARGO_MANIFEST_DIR",
+    "OUT_DIR",
+]
+
+# Separate env settings into "plain" and "with path". Path env vars are often
+# used in Rust `include!()` and similar directives, which always interpret the
+# path relative to the source file containing the directive. Since paths in env
+# vars are often expanded from macros such as `$(location)`, they will be
+# cell-relative which will not work properly. To solve this, we canonicalize
+# paths to absolute paths so they'll work in any context. Hence the need to
+# distinguish path from non-path. (This will not work if the value contains both
+# path and non-path content, but we'll burn that bridge when we get to it.)
+def process_env(
+    compile_ctx: CompileContext, env: dict[str, str | ResolvedStringWithMacros | Artifact], escape_for_rustc_action: bool = True
+) -> (dict[str, cmd_args], dict[str, cmd_args]):
+    # Values with inputs (ie artifact references).
+    path_env = {}
+
+    # Plain strings.
+    plain_env = {}
+
+    for k, v in env.items():
+        arg = cmd_args(v)
+        if len(arg.inputs) > 0:
+            path_env[k] = arg
+        elif escape_for_rustc_action:
+            # Environment variables may have newlines, escape them for now.
+            # Will be unescaped in rustc_action.
+            # Variable may have "\\n" as well.
+            # Example: \\n\n -> \\\n\n -> \\\\n\\n
+            plain_env[k] = cmd_args(
+                v,
+                replace_regex = [
+                    (_DOUBLE_ESCAPED_NEWLINE_RE, "\\\n"),
+                    (_ESCAPED_NEWLINE_RE, "\\n"),
+                    (_ESCAPED_CARRIAGE_RETURN_RE, "\\r"),
+                ],
+            )
+        else:
+            plain_env[k] = arg
+
+    # If CARGO_MANIFEST_DIR is not already expressed in terms of $(location ...)
+    # of some target, then interpret it as a relative path inside of the crate's
+    # sources.
+    #
+    # For example in the following case:
+    #
+    #     http_archive(
+    #         name = "foo.crate",
+    #         ...
+    #     )
+    #
+    #     rust_library(
+    #         name = "foo",
+    #         srcs = [":foo.crate"],
+    #         crate_root = "foo.crate/src/lib.rs",
+    #         env = {
+    #             "CARGO_MANIFEST_DIR": "foo.crate",
+    #         },
+    #     )
+    #
+    # then the manifest directory refers to the directory which is the parent of
+    # `src` inside the archive.
+    #
+    # By putting the environment variable into path_env, rustc_action.py will
+    # take care of turning this into an absolute path before rustc sees it. This
+    # matches Cargo which also always provides CARGO_MANIFEST_DIR as an absolute
+    # path. A relative path would be problematic because it can't simultaneously
+    # support both of the following real-world cases: `include!` which resolves
+    # relative paths relative to the file containing the include:
+    #
+    #     include!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/thing.rs"));
+    #
+    # and proc macros using std::fs to read thing like .pest grammars, which
+    # would need paths relative to the directory that rustc got invoked in
+    # (which is the repo root in Buck builds).
+    for key in _DIRECTORY_ENV:
+        value = plain_env.pop(key, None)
+        if value:
+            path_env[key] = cmd_args(
+                compile_ctx.symlinked_srcs,
+                compile_ctx.path_sep,
+                value,
+                delimiter = "",
+            )
+
+    return (plain_env, path_env)
+
+def _dist_thinlto_enabled(ctx: AnalysisContext, compile_ctx: CompileContext) -> bool:
+    if not getattr(ctx.attrs, "enable_distributed_thinlto", False):
+        return False
+    linker_info = compile_ctx.cxx_toolchain_info.linker_info
+    return linker_info.supports_distributed_thinlto and linker_info.lto_mode == LtoMode("thin")
+
+def get_inherited_link_args(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    dep_link_style: LinkStrategy,
+    rust_cxx_link_group_info: RustCxxLinkGroupInfo | None,
+    transformation_spec_context: TransformationSpecContext | None,
+) -> LinkArgs:
+    if rust_cxx_link_group_info:
+        filtered_links = rust_cxx_link_group_info.filtered_links
+
+        # Unfortunately, link_groups does not use MergedLinkInfo to represent the args
+        # for the resolved nodes in the graph.
+        # Thus, we have no choice but to traverse all the nodes to dedupe the framework linker args.
+        additional_links = apple_get_link_info_by_deduping_link_infos(
+            ctx,
+            infos = filtered_links,
+            framework_linkable = None,
+            swiftmodule_linkable = None,
+        )
+        if additional_links:
+            filtered_links.append(additional_links)
+
+        inherited_link_args = LinkArgs(
+            infos = filtered_links + [rust_cxx_link_group_info.symbol_files_info],
+        )
+    else:
+        inherited_link_args = apple_build_link_args_with_deduped_flags(
+            ctx,
+            deps_merged_link_infos = inherited_merged_link_infos(
+                ctx,
+                compile_ctx.dep_ctx,
+            ),
+            frameworks_linkable = None,
+            link_strategy = dep_link_style,
+            swiftmodule_linkable = None,
+            prefer_stripped = False,
+            transformation_spec_context = transformation_spec_context,
+        )
+
+    return inherited_link_args
+
+def rust_link_shared(ctx: AnalysisContext, compile_ctx: CompileContext, dep_link_style: LinkStrategy, static_lib: LinkInfo) -> LinkedObject:
+    inherited_link_args = get_inherited_link_args(
+        ctx,
+        compile_ctx,
+        dep_link_style,
+        rust_cxx_link_group_info = None,
+        transformation_spec_context = None,
+    )
+    link_args = [
+        LinkArgs(
+            flags = cmd_args(
+                compile_ctx.toolchain_info.linker_flags,
+                ctx.attrs.linker_flags,
+            )
+        ),
+        # Need link whole because otherwise the linker doesn't include anything at all (normally
+        # you'd be passing in `.o`s but that's not really an option)
+        #
+        # FIXME(JakobDegen): Normally, this is where rustc would include the `symbols.o` and the
+        # linker version file/deffile to make sure the right things get linked in and remain
+        # visible. However, we don't have those, which might not be great in the case of `symbols.o`
+        # and will certainly break things if we try this on Windows.
+        #
+        # Principally, it would actually be pretty easy to get us access to those. When building the
+        # `pic_archive`, we could just pass `--crate-type=dylib` to rustc anyway and use the linker
+        # extraction tricks to pull out the files we need (in addition to the object files) to then
+        # be consumed here. The only problem is that rustc is 50-100% slower to do dylib builds
+        # vs equivalent rlib builds, even without the linking. So until that's fixed we can't really
+        # use it.
+        LinkArgs(infos = [set_link_info_link_whole(static_lib)]),
+        inherited_link_args,
+    ]
+
+    return cxx_link_shared_library(
+        ctx = ctx,
+        output = "shared/" + compile_ctx.soname,
+        opts = link_options(
+            links = link_args,
+            link_execution_preference = LinkExecutionPreference("any"),
+            category_suffix = "rust_shared",
+            # `rust_library` has no `allow_cache_upload` attribute
+            allow_cache_upload = None,
+        ),
+        name = compile_ctx.soname,
+    ).linked_object
+
+def rust_link_binary(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    extraction: LinkExtraction,
+    dep_link_strategy: LinkStrategy,
+    reloc_model: RelocModel,
+    extra_link_args: list[typing.Any],
+    binary_link_args: list[typing.Any],
+    inherited_link_args: LinkArgs,
+    dwo_output_directory: Artifact | None,
+    output: Artifact,
+    output_has_content_based_path: bool,
+    identifier: str | None,
+    allow_cache_upload: bool,
+) -> CxxLinkResult:
+    """Link an executable from the objects that a bin-crate `Emit("rlib")`
+    `rust_compile` extracted, plus the link args of the dependency graph."""
+    linker_flags = ctx.attrs.linker_flags
+    if getattr(ctx.attrs, "_generated_build_info_enabled", False):
+        linker_flags = strip_build_info_linker_flags(linker_flags)
+    dist_thinlto = extraction.out_archive != None
+
+    retained_flags = cmd_args(extraction.out_argsfile, format = "@{}")
+    if not dist_thinlto:
+        # Which objects rustc produced is only known once it has run, so the
+        # argsfile listing them is written by a dynamic action after the
+        # manifest is available. Resolving the manifest's names against the
+        # artifacts directory here — rather than having the extraction write
+        # paths into a file itself — keeps the paths buck-rendered, which is
+        # what makes them correct under content-based paths.
+        objects_argsfile = ctx.actions.declare_output(output.short_path + ".rust_objects.args", has_content_based_path = False)
+
+        def write_objects_argsfile(ctx: AnalysisContext, artifacts, outputs):
+            names = artifacts[extraction.out_manifest].read_string().splitlines()
+            ctx.actions.write(
+                outputs[objects_argsfile],
+                cmd_args([extraction.out_artifacts_dir.project(name) for name in names]),
+            )
+
+        ctx.actions.dynamic_output(
+            dynamic = [extraction.out_manifest],
+            inputs = [],
+            outputs = [objects_argsfile.as_output()],
+            f = write_objects_argsfile,
+        )
+
+        rust_objects = LinkArgs(
+            flags = [
+                retained_flags,
+                cmd_args(objects_argsfile, format = "@{}", hidden = extraction.out_artifacts_dir),
+            ]
+        )
+    else:
+        rust_objects = LinkArgs(
+            infos = [
+                LinkInfo(
+                    name = "rust_objects",
+                    # The opt actions re-run codegen and take their relocation
+                    # model from their own command line, so they must match the
+                    # relocation model rustc's own codegen used: PIC for every
+                    # strategy but `static` (see `_get_reloc_model`).
+                    dist_thin_lto_codegen_flags = (compile_ctx.toolchain_info.dist_thin_lto_codegen_flags if dep_link_strategy != LinkStrategy("static") else []),
+                    pre_flags = [retained_flags],
+                    linkables = [
+                        ArchiveLinkable(
+                            archive = Archive(artifact = extraction.out_archive),
+                            linker_type = compile_ctx.cxx_toolchain_info.linker_info.type,
+                            # link_whole because everything rustc emits has to end up in the input.
+                            link_whole = True,
+                        )
+                    ],
+                )
+            ]
+        )
+
+    split_debug_mode = compile_ctx.cxx_toolchain_info.split_debug_mode or SplitDebugMode("none")
+    if split_debug_mode != SplitDebugMode("none"):
+        inherited_debug_info = inherited_external_debug_info(
+            ctx = ctx,
+            dep_ctx = compile_ctx.dep_ctx,
+            dep_link_strategy = dep_link_strategy,
+        )
+    else:
+        inherited_debug_info = ArtifactTSet()
+    external_debug_info = make_artifact_tset(
+        actions = ctx.actions,
+        label = ctx.label,
+        artifacts = [dwo_output_directory] if dwo_output_directory else [],
+        children = [inherited_debug_info],
+    )
+
+    links = [
+        # The flags this link needs beyond what `cxx_link` applies on its own;
+        # `binary_linker_flags` mirrors `cxx_executable`'s use of them.
+        LinkArgs(
+            flags = cmd_args(
+                compile_ctx.cxx_toolchain_info.linker_info.binary_linker_flags,
+                compile_ctx.toolchain_info.linker_flags,
+                linker_flags,
+            )
+        ),
+        LinkArgs(flags = extra_link_args),
+    ]
+
+    if compile_ctx.cxx_toolchain_info.linker_info.type == LinkerType("gnu"):
+        flags = [
+            # FIXME(JakobDegen): This is here becuase rustc used to pass it, but it's not something
+            # we should be passing blindly on the user's behalf. Unfortunately some builds break if
+            # you take it out.
+            "-Wl,--as-needed",
+            # lld deduplicates `.debug_str` only at `-O1`, and rustc always
+            # passes this for links it drives, overriding toolchains that link
+            # at `-O0` for speed (fbcode's opt-lg). Without the deduplication,
+            # very large binaries overflow the 32-bit `.debug_str` offsets in
+            # `.debug_names`.
+            "-Wl,-O1",
+            # The objects were codegened at the relocation model chosen in
+            # `_get_reloc_model`, which the toolchain's link flags cannot know
+            # about. Pin the PIE-ness of the executable to match, as rustc does
+            # for links it drives.
+            "-no-pie" if reloc_model == RelocModel("static") else "-pie",
+        ]
+
+        # On ELF, rustc-instrumented objects carry no reference to the
+        # profile runtime's registration object (clang-instrumented ones
+        # do), so nothing would pull it out of the `profiler_builtins`
+        # archive and the binary would silently write no profile. rustc
+        # compensates with this flag on links it drives; do the same,
+        # gated exactly like the `-Cinstrument-coverage` the compile gets.
+        if getattr(ctx.attrs, "coverage", False) and compile_ctx.toolchain_info.rustc_coverage_flags:
+            flags.append("-Wl,-u,__llvm_profile_runtime")
+
+        links.append(LinkArgs(flags = flags))
+
+    links += [
+        rust_objects,
+        inherited_link_args,
+        LinkArgs(infos = [LinkInfo(external_debug_info = external_debug_info)]),
+    ]
+
+    if link_cxx_binary_locally(ctx, compile_ctx.cxx_toolchain_info):
+        link_execution_preference = LinkExecutionPreference("local")
+    else:
+        link_execution_preference = LinkExecutionPreference("any")
+
+    return cxx_link_into(
+        ctx = ctx,
+        output = output,
+        result_type = CxxLinkResultType("executable"),
+        output_has_content_based_path = output_has_content_based_path,
+        opts = link_options(
+            binary_links = [LinkArgs(flags = binary_link_args)] if binary_link_args else [],
+            links = links,
+            link_execution_preference = link_execution_preference,
+            # The link is local only so the fbcode linker wrapper can stamp
+            # build info from the repo (D115067153); dwp needs no repo and is
+            # memory-hungry enough that pinning it to the link's host thrashes
+            # small workers. Let it schedule anywhere, matching the
+            # rustc-linked path, which runs dwp with no preference.
+            dwp_execution_preference = LinkExecutionPreference("any"),
+            category_suffix = "rust_binary",
+            identifier = identifier,
+            enable_distributed_thinlto = dist_thinlto,
+            allow_cache_upload = allow_cache_upload,
+        ),
+    )
diff --git a/buck2/prelude/rust/build_params.bzl b/buck2/prelude/rust/build_params.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/build_params.bzl
@@ -0,0 +1,360 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Rules for mapping requirements to options
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerType")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkStrategy",
+)
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//utils:expect.bzl", "expect")
+
+# --crate-type=
+# Excludes `lib` because we want to explicitly choose the library flavour
+CrateType = enum(
+    # Binary
+    "bin",
+    # Rust linkage
+    "rlib",
+    "dylib",
+    "proc-macro",
+    # Native linkage
+    "cdylib",
+    "staticlib",
+)
+
+# Crate type requires linking
+def crate_type_linked(crate_type: CrateType) -> bool:
+    return crate_type.value in ("bin", "dylib", "proc-macro", "cdylib")
+
+# -Crelocation-model= from --print relocation-models
+RelocModel = enum(
+    # Common
+    "static",
+    "pic",
+    "pie",
+    # Various obscure types
+    "dynamic-no-pic",
+    "ropi",
+    "rwpi",
+    "ropi-rwpi",
+    "default",
+)
+
+# --emit=
+Emit = enum(
+    "asm",
+    "llvm-bc",
+    "llvm-ir",
+    "llvm-ir-noopt",
+    "obj",
+    # A real link, performed by rustc: non-AUL binaries and dylibs/cdylibs,
+    # proc macros (which rustc itself loads), and staticlib bundling (not a
+    # true link, but like one in that it pulls together all dependencies).
+    "link",
+    # The crate's static-library-shaped artifact. For `rlib` crates this is
+    # the rlib itself. For `bin` crates (AUL only) rustc compiles exactly as
+    # for `link`, but the extraction wrapper captures the objects it would
+    # have handed the linker.
+    "rlib",
+    "dep-info",
+    "mir",
+    "expand",  # pseudo emit alias for -Zunpretty=expanded
+    "clippy",
+    # Rustc actually has two different forms of metadata:
+    #  - The full flavor, which is what's outputted when passing
+    #    `--emit link,metadata` and can be used as a part of pipelined builds
+    #  - The fast flavor, which is emitted from `--emit metadata`, is faster to
+    #    build, but cannot be used in pipelined builds.
+    "metadata-full",
+    "metadata-fast",
+)
+
+ProfileMode = enum(
+    "llvm-time-trace",
+    "self-profile",
+    "remarks",
+)
+
+# The different quantities of Rust metadata that can be requested from
+# dependencies. Each one corresponds to an `Emit` variant, but not all `Emit`
+# variants output metadata
+MetadataKind = enum(
+    "fast",
+    "full",
+    "link",
+)
+
+# Emitting this artifact generates code
+def dep_metadata_of_emit(emit: Emit) -> MetadataKind:
+    return {
+        Emit("asm"): MetadataKind("full"),
+        Emit("llvm-bc"): MetadataKind("full"),
+        Emit("llvm-ir"): MetadataKind("full"),
+        Emit("llvm-ir-noopt"): MetadataKind("full"),
+        Emit("obj"): MetadataKind("full"),
+        Emit("link"): MetadataKind("link"),
+        # rlibs are consumed as archives by cxx-driven links, never loaded by
+        # a downstream rustc link, so their deps never need real object code.
+        Emit("rlib"): MetadataKind("full"),
+        Emit("mir"): MetadataKind("full"),
+        Emit("metadata-fast"): MetadataKind("fast"),
+        Emit("clippy"): MetadataKind("fast"),
+        Emit("dep-info"): MetadataKind("fast"),
+        Emit("expand"): MetadataKind("fast"),
+        Emit("metadata-full"): MetadataKind("full"),
+    }[emit]
+
+# Represents a way of invoking rustc to produce an artifact. These values are computed from
+# information such as the rule type, linkstyle, crate type, etc.
+BuildParams = record(
+    crate_type = field(CrateType),
+    reloc_model = field(RelocModel),
+    dep_link_strategy = field(LinkStrategy),
+    # A prefix and suffix to use for the name of the produced artifact. Note that although we store
+    # these in this type, they are in principle computable from the remaining fields and the OS.
+    # Keeping them here just turns out to be a little more convenient.
+    prefix = field(str),
+    suffix = field(str),
+)
+
+RustcFlags = record(
+    crate_type = field(CrateType),
+    platform_to_affix = field(typing.Callable),
+    link_strategy = field(LinkStrategy | None),
+)
+
+# Rule type - 'binary' also covers 'test'
+RuleType = enum("binary", "library")
+
+# Controls how we build our rust libraries, largely dependent on whether rustc
+# or buck is driving the final linking and whether we are linking the artifact
+# into other rust targets.
+#
+# Rust: In this mode, we build standard rlibs/dylibs. This is the approach that
+# we use either when the artifacts will subsequently be consumed by rust, or
+# when `advanced_unstable_linking` is enabled (or both). In the
+# `advanced_unstable_linking` case, this approach mitigates the duplicate symbol
+# downside of the "Native" approach. However, this option is not formally
+# supported by rustc, and depends on an implementation detail of rlibs (they're
+# effectively .a archives and can be linked with other native code using the CXX
+# linker).
+#
+# See https://github.com/rust-lang/rust/issues/73632 for more details on
+# stabilizing this approach.
+#
+# native-bundled: In this mode, we build rust libraries as staticlibs, where
+# rustc will bundle all of this target's rust dependencies into a single library
+# artifact. This approach is the most standardized OSS way to build rust
+# libraries for linkage in non-rust code.
+
+LinkageLang = enum(
+    "rust",
+    "native-bundled",
+)
+
+_BINARY = 0
+_RUST_PROC_MACRO_RUSTDOC_TEST = 1
+_NATIVE_LINKABLE_SHARED_OBJECT = 3
+_RUST_DYLIB_SHARED = 4
+_RUST_PROC_MACRO = 5
+_RUST_STATIC_PIC_LIBRARY = 6
+_RUST_STATIC_NON_PIC_LIBRARY = 7
+_NATIVE_LINKABLE_STATIC_PIC = 8
+_NATIVE_LINKABLE_STATIC_NON_PIC = 9
+
+def _executable_prefix_suffix(linker_type: LinkerType, target_os_type: OsLookup) -> (str, str):
+    return {
+        LinkerType("darwin"): ("", ""),
+        LinkerType("gnu"): ("", ".exe") if target_os_type.os == Os("windows") else ("", ""),
+        LinkerType("wasm"): ("", ".wasm"),
+        LinkerType("windows"): ("", ".exe"),
+    }[linker_type]
+
+def _library_prefix_suffix(linker_type: LinkerType, target_os_type: OsLookup) -> (str, str):
+    return {
+        LinkerType("darwin"): ("lib", ".dylib"),
+        LinkerType("gnu"): ("", ".dll") if target_os_type.os == Os("windows") else ("lib", ".so"),
+        LinkerType("wasm"): ("", ".wasm"),
+        LinkerType("windows"): ("", ".dll"),
+    }[linker_type]
+
+_BUILD_PARAMS = {
+    _BINARY: RustcFlags(
+        crate_type = CrateType("bin"),
+        platform_to_affix = _executable_prefix_suffix,
+        # link_strategy is provided by the rust_binary attribute
+        link_strategy = None,
+    ),
+    # It's complicated: this is a rustdoc test for a procedural macro crate.
+    # We need deps built as if this were a binary, while passing crate-type
+    # proc_macro to the rustdoc invocation.
+    _RUST_PROC_MACRO_RUSTDOC_TEST: RustcFlags(
+        crate_type = CrateType("proc-macro"),
+        platform_to_affix = _executable_prefix_suffix,
+        link_strategy = LinkStrategy("static_pic"),
+    ),
+    _NATIVE_LINKABLE_SHARED_OBJECT: RustcFlags(
+        crate_type = CrateType("cdylib"),
+        platform_to_affix = _library_prefix_suffix,
+        # cdylibs statically link all rust code and export a single C-style dylib
+        # for consumption by other languages
+        link_strategy = LinkStrategy("static_pic"),
+    ),
+    _RUST_DYLIB_SHARED: RustcFlags(
+        crate_type = CrateType("dylib"),
+        platform_to_affix = _library_prefix_suffix,
+        link_strategy = LinkStrategy("shared"),
+    ),
+    _RUST_PROC_MACRO: RustcFlags(
+        crate_type = CrateType("proc-macro"),
+        platform_to_affix = _library_prefix_suffix,
+        # FIXME(JakobDegen): It's not really clear what we should do about
+        # proc macros. The principled thing is probably to treat them sort
+        # of like a normal library, except that they always have preferred
+        # linkage shared? Preserve existing behavior for now
+        link_strategy = LinkStrategy("static_pic"),
+    ),
+    # FIXME(JakobDegen): Add a comment explaining why `.a`s need reloc-strategy
+    # dependent names while `.rlib`s don't.
+    _RUST_STATIC_PIC_LIBRARY: RustcFlags(
+        crate_type = CrateType("rlib"),
+        platform_to_affix = lambda _l, _t: ("lib", ".rlib"),
+        link_strategy = LinkStrategy("static_pic"),
+    ),
+    _RUST_STATIC_NON_PIC_LIBRARY: RustcFlags(
+        crate_type = CrateType("rlib"),
+        platform_to_affix = lambda _l, _t: ("lib", ".rlib"),
+        link_strategy = LinkStrategy("static"),
+    ),
+    _NATIVE_LINKABLE_STATIC_PIC: RustcFlags(
+        crate_type = CrateType("staticlib"),
+        platform_to_affix = lambda _l, _t: ("lib", "_pic.a"),
+        link_strategy = LinkStrategy("static_pic"),
+    ),
+    _NATIVE_LINKABLE_STATIC_NON_PIC: RustcFlags(
+        crate_type = CrateType("staticlib"),
+        platform_to_affix = lambda _l, _t: ("lib", ".a"),
+        link_strategy = LinkStrategy("static"),
+    ),
+}
+
+_INPUTS = {
+    # Binary
+    ("binary", False, None, "rust"): _BINARY,
+    ("binary", True, None, "rust"): _RUST_PROC_MACRO_RUSTDOC_TEST,
+    # Native linkable shared object
+    ("library", False, "shared_lib", "native-bundled"): _NATIVE_LINKABLE_SHARED_OBJECT,
+    # Rust dylib shared object
+    ("library", False, "shared_lib", "rust"): _RUST_DYLIB_SHARED,
+    # Rust proc-macro
+    ("library", True, "archive", "rust"): _RUST_PROC_MACRO,
+    ("library", True, "pic_archive", "rust"): _RUST_PROC_MACRO,
+    ("library", True, "shared_lib", "rust"): _RUST_PROC_MACRO,
+    # Rust static_pic library
+    ("library", False, "pic_archive", "rust"): _RUST_STATIC_PIC_LIBRARY,
+    # Rust static (non-pic) library
+    ("library", False, "archive", "rust"): _RUST_STATIC_NON_PIC_LIBRARY,
+    # Native linkable static_pic
+    ("library", False, "pic_archive", "native-bundled"): _NATIVE_LINKABLE_STATIC_PIC,
+    # Native linkable static non-pic
+    ("library", False, "archive", "native-bundled"): _NATIVE_LINKABLE_STATIC_NON_PIC,
+}
+
+# Check types of _INPUTS, writing these out as types is too verbose, but let's make sure we don't have any typos.
+[
+    (RuleType(rule_type), LibOutputStyle(lib_output_style) if lib_output_style else None, LinkageLang(linkage_lang))
+    for (rule_type, _, lib_output_style, linkage_lang), _ in _INPUTS.items()
+]
+
+def _get_reloc_model(rule: RuleType, link_strategy: LinkStrategy, target_os_type: OsLookup) -> RelocModel:
+    if target_os_type.os == Os("windows"):
+        return RelocModel("pic")
+    if link_strategy == LinkStrategy("static"):
+        return RelocModel("static")
+    if rule == RuleType("binary"):
+        return RelocModel("pie")
+    return RelocModel("pic")
+
+# Compute crate type, relocation model and name mapping given what rule we're building, whether its
+# a proc-macro, linkage information and language.
+#
+# Binaries should pass the link strategy and not the lib output style, while libraries should do the
+# opposite.
+#
+# The linking information that's passed here is different from what one might expect in the C++
+# rules. There's a good reason for that, so let's go over it. First, let's recap how C++ handles
+# this, as of December 2023 (I say "recap" but I don't think this is actually documented anywhere):
+#
+#  1. C++ libraries can be built in three different ways: Archives, pic archives, and shared
+#     libraries. Which one of these is used for a given link strategy is determined by the preferred
+#     linkage using `linking/link_info.bzl:get_lib_output_style`.
+#  2. When a C++ library is built as a shared library, the link strategy used for its dependencies
+#     is determined by the link style attribute on the C++ library.
+#  3. When a C++ library is built as an archive (either kind), there's no need to know a link
+#     strategy for the dependencies. None of the per-link-strategy providers of the dependencies
+#     need to be accessed.
+#
+# There are two relevant ways in which Rust differs:
+#
+#  1. There are more ways of building Rust libraries than are represented by `LibOutputStyle`. The
+#     Rust analogue is the `BuildParams` type, which implicitly holds a `LibOutputStyle` as well as
+#     a bunch of additional information - this is why `LibOutputStyle` is relatively rarely used
+#     directly in the Rust rules.
+#  2. Rust does not have the property in point three above, ie building a Rust library into an
+#     archive does require knowing per-link-strategy properties of the dependencies. This is
+#     fundamental in cases without native unbundled deps - with native unbundled deps it may be
+#     fixable, but that's not super clear.
+def build_params(
+    rule: RuleType,
+    proc_macro: bool,
+    link_strategy: LinkStrategy | None,
+    lib_output_style: LibOutputStyle | None,
+    lang: LinkageLang,
+    linker_type: LinkerType,
+    target_os_type: OsLookup,
+) -> BuildParams:
+    if rule == RuleType("binary"):
+        expect(link_strategy != None)
+        expect(lib_output_style == None)
+    else:
+        expect(lib_output_style != None)
+
+    input = (rule.value, proc_macro, lib_output_style.value if lib_output_style else None, lang.value)
+
+    expect(
+        input in _INPUTS,
+        "missing case for rule_type={} proc_macro={} lib_output_style={} lang={}",
+        rule,
+        proc_macro,
+        lib_output_style,
+        lang,
+    )
+
+    flags = _BUILD_PARAMS[_INPUTS[input]]
+
+    # FIXME(JakobDegen): We deal with Rust needing to know the link strategy
+    # even for building archives by using a default link strategy specifically
+    # for those cases. I've gone through the code and checked all the places
+    # where the link strategy is used to determine that this won't do anything
+    # too bad, but it would be nice to enforce that more strictly or not have
+    # this at all.
+    link_strategy = link_strategy or flags.link_strategy
+    reloc_model = _get_reloc_model(rule, link_strategy, target_os_type)
+    prefix, suffix = flags.platform_to_affix(linker_type, target_os_type)
+
+    return BuildParams(
+        crate_type = flags.crate_type,
+        reloc_model = reloc_model,
+        dep_link_strategy = link_strategy,
+        prefix = prefix,
+        suffix = suffix,
+    )
diff --git a/buck2/prelude/rust/buildscript/BUCK b/buck2/prelude/rust/buildscript/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/buildscript/BUCK
@@ -0,0 +1,23 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load(":buildscript_platform.bzl", "transitions_for_constraint")
+
+oncall("build_infra")
+
+source_listing()
+
+constraint(
+    name = "buildscript_for_platform",
+    default = "none",
+    values = map(
+        str,
+        range(1000),
+    )
+    + ["none"],
+    visibility = ["PUBLIC"],
+)
+
+transitions_for_constraint(
+    name = "buildscript_platform_transition",
+    constraint = ":buildscript_for_platform",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/rust/buildscript/buildscript_platform.bzl b/buck2/prelude/rust/buildscript/buildscript_platform.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/buildscript/buildscript_platform.bzl
@@ -0,0 +1,59 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Used like this:
+#
+#     transition_alias(
+#         name = "anyhow-1.0.100-build-script-build-riscv64gc",
+#         actual = ":anyhow-1.0.100-build-script-build",
+#         incoming_transition = "prelude//rust/buildscript:buildscript_platform_transition[99]",
+#     )
+#
+# This allows `anyhow-1.0.100-build-script-run` to take an exec dependency on
+# this target, transition to the build-script-run's execution platform (which
+# discards knowledge of build-script-run's target platform), and transition
+# again to set a riscv64gc constraint in the execution platform.
+transition_alias = rule(
+    impl = lambda ctx: ctx.attrs.actual.providers,
+    attrs = {
+        "actual": attrs.dep(),
+        "labels": attrs.list(attrs.string(), default = []),
+    },
+    supports_incoming_transition = True,
+)
+
+def _transitions_for_constraint_impl(ctx: AnalysisContext) -> list[Provider]:
+    sub_targets = {}
+
+    for name, constraint_value in ctx.attrs.constraint[DefaultInfo].sub_targets.items():
+        sub_targets[name] = [
+            TransitionInfo(
+                impl = lambda platform, constraint = constraint_value[ConstraintValueInfo]: PlatformInfo(
+                    label = platform.label,
+                    configuration = ConfigurationInfo(
+                        constraints = platform.configuration.constraints
+                        | {
+                            constraint.setting.label: constraint,
+                        },
+                        values = platform.configuration.values,
+                    ),
+                ),
+            )
+        ]
+
+    return [DefaultInfo(sub_targets = sub_targets)]
+
+# Take a constraint setting and turn each of its constraint values into a
+# transition adding that constraint value into the platform configuration.
+transitions_for_constraint = rule(
+    impl = _transitions_for_constraint_impl,
+    attrs = {
+        "constraint": attrs.dep(),
+    },
+    is_configuration_rule = True,
+)
diff --git a/buck2/prelude/rust/cargo_buildscript.bzl b/buck2/prelude/rust/cargo_buildscript.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/cargo_buildscript.bzl
@@ -0,0 +1,466 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Cargo build script runner compatible with Reindeer-generated targets.
+#
+# Use this reindeer.toml configuration to refer to this rule:
+#
+#     [buck]
+#     buckfile_imports = """
+#     load("@prelude//rust:cargo_buildscript.bzl", "buildscript_run")
+#     """
+#
+#     # optional (this matches the default rule name):
+#     buildscript_genrule = "buildscript_run"
+#
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load(
+    "@prelude//cxx:preprocessor.bzl",
+    "cxx_inherited_preprocessor_infos",
+    "cxx_merge_cpreprocessors",
+)
+load("@prelude//cxx:target_sdk_version.bzl", "get_target_triple")
+load("@prelude//decls:common.bzl", "buck")
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//linking:link_info.bzl", "LinkInfosTSet", "LinkStrategy", "MergedLinkInfo")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup", "ScriptLanguage")
+load("@prelude//rust:rust_toolchain.bzl", "RustToolchainInfo")
+load("@prelude//rust:targets.bzl", "targets")
+load("@prelude//rust/buildscript:buildscript_platform.bzl", "transition_alias")
+load("@prelude//rust/tools:attrs.bzl", "RustInternalToolsInfo")
+load("@prelude//utils:cmd_script.bzl", "cmd_script")
+load("@prelude//utils:selects.bzl", "selects")
+load(":build.bzl", "dependency_args")
+load(":build_params.bzl", "MetadataKind")
+load(
+    ":cargo_package.bzl",
+    "apply_platform_attrs",
+    "get_reindeer_platform_names",
+    "get_reindeer_platforms",
+)
+load(":dep_context.bzl", "DepCollectionContext")
+load(
+    ":link_info.bzl",
+    "DEFAULT_STATIC_LINK_STRATEGY",
+    "RustProcMacroPlugin",
+    "gather_explicit_sysroot_deps",
+    "resolve_rust_deps_inner",
+)
+load(":rust_toolchain.bzl", "PanicRuntime")
+
+def _make_rustc_shim(ctx: AnalysisContext, cwd: Artifact) -> cmd_args:
+    # Build scripts expect to receive a `rustc` which "just works." However,
+    # our rustc sometimes has no sysroot available, so we need to make a shim
+    # which supplies the sysroot deps if necessary
+    toolchain_info = ctx.attrs._rust_toolchain[RustToolchainInfo]
+    explicit_sysroot_deps = toolchain_info.explicit_sysroot_deps
+    if explicit_sysroot_deps:
+        dep_ctx = DepCollectionContext(
+            advanced_unstable_linking = False,
+            include_doc_deps = False,
+            is_proc_macro = False,
+            explicit_sysroot_deps = explicit_sysroot_deps,
+            panic_runtime = PanicRuntime("unwind"),  # not actually used
+        )
+        deps = gather_explicit_sysroot_deps(dep_ctx)
+        deps = resolve_rust_deps_inner(ctx, deps)
+        dep_args, dep_argsfiles, _ = dependency_args(
+            ctx = ctx,
+            internal_tools_info = ctx.attrs._rust_internal_tools_toolchain[RustInternalToolsInfo],
+            transitive_dependency_dirs = set(),
+            toolchain_info = toolchain_info,
+            deps = deps,
+            subdir = "any",
+            dep_link_strategy = DEFAULT_STATIC_LINK_STRATEGY,
+            dep_metadata_kind = MetadataKind("full"),
+            is_rustdoc_test = False,
+            cwd = cwd,
+        )
+
+        null_path = "nul" if ctx.attrs._exec_os_type[OsLookup].os == Os("windows") else "/dev/null"
+        dep_args = cmd_args("--sysroot=" + null_path, dep_args, relative_to = cwd)
+        dep_file, _ = ctx.actions.write("rustc_dep_file", dep_args, allow_args = True, has_content_based_path = False)
+        sysroot_args = cmd_args(
+            cmd_args("@", dep_file, delimiter = "", hidden = dep_args),
+            # add dep_argsfiles as a separate argument because rustc does NOT support nested @argsfiles
+            dep_argsfiles,
+        )
+    else:
+        sysroot_args = cmd_args()
+
+    shim = cmd_script(
+        actions = ctx.actions,
+        name = "__rustc_shim",
+        cmd = cmd_args(toolchain_info.compiler, sysroot_args, relative_to = cwd),
+        language = ctx.attrs._exec_os_type[OsLookup].script,
+    )
+
+    return cmd_args(shim, relative_to = cwd)
+
+def _make_cc_shim(ctx: AnalysisContext, name: str, cmd: cmd_args) -> cmd_args:
+    """
+    Wrap cmd, which can contain relative paths to executables and various
+    resources, in a script that can be invoked from any directory.
+
+    Different crates' build scripts run $CC from inside of $OUT_DIR, or from
+    /tmp, not necessarily only from the directory that Buck gives to the build
+    script execution. Also they pass arguments to $CC which are relative to the
+    directory they chose to run it in.
+
+    For a cmd like this:
+
+        buck-out/v2/art/fbcode/tools/build/buck/wrappers/__fbcc__/0cdd64957fa390c4/fbcc \
+        -resource-dir \
+        fbcode/third-party-buck/platform010/build/llvm-fb/21/lib/clang/stable \
+        -Bfbcode/third-party-buck/platform010/build/binutils/x86_64-facebook-linux/bin
+
+    we use `absolute_prefix` to insert a recognizable marker `${..}/` in front
+    of every argument that is a path. The markers are later substituted with an
+    appropriate value after learning the buildscript-selected working directory.
+
+        python3 \
+        fbcode/buck2/prelude/rust/tools/from_any_dir.py \
+        --cwd=/re_cwd/buck-out/v2/art/fbsource/eef091ffd45259ca/third-party/rust/vendor/gmp-mpfr-sys/__1-build-script-run__/cwd \
+        ${..}/buck-out/v2/art/fbcode/tools/build/buck/wrappers/__fbcc__/0cdd64957fa390c4/fbcc \
+        -resource-dir \
+        ${..}/fbcode/third-party-buck/platform010/build/llvm-fb/21/lib/clang/stable \
+        -B${..}/fbcode/third-party-buck/platform010/build/binutils/x86_64-facebook-linux/bin
+
+    There are 4 categories of paths which are relative to different locations.
+
+    1. Paths in the RunInfo of the from_any_dir tool, including the path of that
+       Python program and paths in the toolchain's Python interpreter and global
+       arguments to the Python interpreter. These are relative to the repo root
+       and we do not prepend the marker. The wrapper script must change
+       directory to the repo root before evaluating these paths.
+
+    2. The buildscript-selected working directory. This is captured as an
+       absolute path by the wrapper script and passed to from_any_dir's `--cwd`
+       flag.
+
+    3. Paths in `cmd`. We mark these for from_any_dir to rewrite relative to the
+       buildscript-selected working directory. From_any_dir must change to that
+       directory before evaluating these paths.
+
+    4. Paths in the arguments passed by the build script to $CC. These are
+       relative to the buildscript-selected working directory and we must have
+       changed back to that directory before evaluating these paths.
+    """
+
+    internal_tools_info = ctx.attrs._rust_internal_tools_toolchain[RustInternalToolsInfo]
+
+    language = ctx.attrs._exec_os_type[OsLookup].script
+    if language == ScriptLanguage("sh"):
+        script = ctx.actions.declare_output("{}.sh".format(name), has_content_based_path = True)
+        wrapper, _ = ctx.actions.write(
+            script,
+            [
+                "#!/usr/bin/env bash",
+                # Capture buildscript-selected working directory.
+                "cc_original_dir=$(pwd)",
+                # Change directory to the script's location in buck-out, then up
+                # to the repo root.
+                'cd -- "$(dirname -- "$(realpath "${BASH_SOURCE[0]}")")"',
+                cmd_args(ctx.label.project_root, relative_to = (script, 1), format = "cd {}"),
+                # Run from_any_dir.py.
+                cmd_args(
+                    cmd_args(
+                        cmd_args(internal_tools_info.from_any_dir, quote = "shell"),
+                        '--cwd="${cc_original_dir}"',
+                        cmd_args(cmd, absolute_prefix = "${..}/", quote = "shell"),
+                        delimiter = " \\\n",
+                    ),
+                    # For linker, prepend every argument with `-Wl,`. Without this,
+                    # when using Clang for the linker, arguments are intercepted
+                    # by Clang instead of making it to the actual linker.
+                    # >> clang++: error: unknown argument: '--as-needed'
+                    format = '{} "${@/#/-Wl,}"\n' if name == "__ld_shim" else '{} "$@"\n',
+                ),
+            ],
+            is_executable = True,
+            allow_args = True,
+        )
+    elif language == ScriptLanguage("bat"):
+        script = ctx.actions.declare_output("{}.bat".format(name), has_content_based_path = True)
+        wrapper, _ = ctx.actions.write(
+            script,
+            [
+                "@echo off",
+                [
+                    # Prepend every argument with `-Wl,`.
+                    "setlocal enabledelayedexpansion",
+                    'set "wl_args="',
+                    "for %%a in (%*) do (",
+                    '    set "wl_args=!wl_args! -Wl,%%~a"',
+                    ")",
+                ]
+                if name == "__ld_shim"
+                else [],
+                "set cc_original_dir=%CD%",
+                'cd /d "%~dp0"',
+                cmd_args(ctx.label.project_root, relative_to = (script, 1), format = "cd {}"),
+                cmd_args(
+                    cmd_args(
+                        cmd_args(internal_tools_info.from_any_dir, quote = "shell"),
+                        '--cwd="%cc_original_dir%"',
+                        cmd_args(cmd, absolute_prefix = "${..}\\", quote = "shell"),
+                        delimiter = " ^\n  ",
+                    ),
+                    format = "{} !args!\n" if name == "__ld_shim" else "{} %*\n",
+                ),
+            ],
+            is_executable = True,
+            allow_args = True,
+        )
+    else:
+        fail(language)
+
+    return cmd_args(wrapper, hidden = [internal_tools_info.from_any_dir, cmd])
+
+def _cargo_buildscript_impl(ctx: AnalysisContext) -> list[Provider]:
+    cxx_toolchain_info = ctx.attrs._cxx_toolchain[CxxToolchainInfo]
+    rust_toolchain_info = ctx.attrs._rust_toolchain[RustToolchainInfo]
+
+    cwd = ctx.actions.declare_output("cwd", dir = True, has_content_based_path = True)
+    out_dir = ctx.actions.declare_output("OUT_DIR", dir = True, has_content_based_path = True)
+    rustc_flags = ctx.actions.declare_output("rustc_flags", has_content_based_path = True)
+
+    if ctx.attrs.manifest_dir != None:
+        manifest_dir = ctx.attrs.manifest_dir[DefaultInfo].default_outputs[0]
+    else:
+        manifest_dir = ctx.actions.symlinked_dir("manifest_dir", ctx.attrs.filegroup_for_manifest_dir, has_content_based_path = True)
+
+    cmd = [
+        ctx.attrs.runner[RunInfo],
+        cmd_args("--buildscript=", ctx.attrs.buildscript[RunInfo], delimiter = ""),
+        cmd_args("--rustc-cfg=", ctx.attrs.rustc_cfg[DefaultInfo].default_outputs[0], delimiter = ""),
+        cmd_args("--manifest-dir=", manifest_dir, delimiter = ""),
+        cmd_args("--create-cwd=", cwd.as_output(), delimiter = ""),
+        cmd_args("--outfile=", rustc_flags.as_output(), delimiter = ""),
+    ]
+
+    if ctx.attrs.rustc_link_lib:
+        cmd.append("--rustc-link-lib")
+    if ctx.attrs.rustc_link_search:
+        cmd.append("--rustc-link-search")
+
+    # See https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
+
+    env = {}
+    env["CARGO"] = "/bin/false"
+    env["CARGO_PKG_NAME"] = ctx.attrs.package_name
+    env["CARGO_PKG_VERSION"] = ctx.attrs.version
+    env["OUT_DIR"] = out_dir.as_output()
+    env["RUSTC"] = _make_rustc_shim(ctx, cwd)
+    env["RUSTC_LINKER"] = "/bin/false"
+    env["RUST_BACKTRACE"] = "1"
+
+    if rust_toolchain_info.rustc_target_triple:
+        env["TARGET"] = rust_toolchain_info.rustc_target_triple
+    else:
+        cmd.append(cmd_args("--rustc-host-tuple=", ctx.attrs.rustc_host_tuple[DefaultInfo].default_outputs[0], delimiter = ""))
+
+    # \037 == \x1f == the magic delimiter specified in the environment variable
+    # reference above.
+    env["CARGO_ENCODED_RUSTFLAGS"] = cmd_args(
+        rust_toolchain_info.rustc_flags,
+        "-Cunsafe-allow-abi-mismatch=sanitizer",
+        delimiter = "\037",
+    )
+
+    host_triple = targets.exec_triple(ctx)
+    if host_triple:
+        env["HOST"] = host_triple
+
+    for feature in ctx.attrs.features:
+        upper_feature = feature.upper().replace("-", "_")
+        env["CARGO_FEATURE_{}".format(upper_feature)] = "1"
+
+    for flag in rust_toolchain_info.rustc_flags:
+        if isinstance(flag, ResolvedStringWithMacros):
+            flag = str(flag)[1:-1]
+        if flag.startswith("-Copt-level="):
+            opt_level = flag.removeprefix("-Copt-level=")
+            if opt_level.isdigit():
+                env["OPT_LEVEL"] = opt_level
+
+    # C and C++ compilers for bindgen.
+    target_triple = get_target_triple(ctx)
+    preprocessor = cxx_merge_cpreprocessors(
+        ctx.actions,
+        [],
+        cxx_inherited_preprocessor_infos(ctx.attrs.cxx_deps),
+    )
+    deps_preprocessor_flags = preprocessor.set.project_as_args("args")
+    deps_tset = ctx.actions.tset(
+        LinkInfosTSet,
+        children = [dep[MergedLinkInfo]._infos[LinkStrategy("static_pic")] for dep in ctx.attrs.cxx_deps],
+    )
+    deps_link = deps_tset.project_as_args("default")
+    sanitizer_flags = ["-fno-sanitize=all"]
+    cc_is_clang = cxx_toolchain_info.c_compiler_info.compiler_type.startswith("clang")
+    cxx_is_clang = cxx_toolchain_info.cxx_compiler_info.compiler_type.startswith("clang")
+    env["LD"] = _make_cc_shim(
+        ctx = ctx,
+        name = "__ld_shim",
+        cmd = cmd_args(
+            cxx_toolchain_info.linker_info.linker,
+            cxx_toolchain_info.linker_info.linker_flags or [],
+            rust_toolchain_info.linker_flags,
+            sanitizer_flags,
+        ),
+    )
+    env["CC"] = _make_cc_shim(
+        ctx = ctx,
+        name = "__cc_shim",
+        cmd = cmd_args(
+            cxx_toolchain_info.c_compiler_info.compiler,
+            cmd_args(env["LD"], format = "--ld-path={}") if cc_is_clang else cmd_args(),
+            cxx_toolchain_info.c_compiler_info.preprocessor_flags,
+            cxx_toolchain_info.c_compiler_info.compiler_flags,
+            deps_preprocessor_flags,
+            deps_link,
+            sanitizer_flags,
+            ctx.attrs.cxx_flags,
+            ["--target={}".format(target_triple)] if target_triple else [],
+        ),
+    )
+    env["CXX"] = _make_cc_shim(
+        ctx = ctx,
+        name = "__cxx_shim",
+        cmd = cmd_args(
+            cxx_toolchain_info.cxx_compiler_info.compiler,
+            cmd_args(env["LD"], format = "--ld-path={}") if cxx_is_clang else cmd_args(),
+            cxx_toolchain_info.cxx_compiler_info.preprocessor_flags,
+            cxx_toolchain_info.cxx_compiler_info.compiler_flags,
+            deps_preprocessor_flags,
+            deps_link,
+            sanitizer_flags,
+            ctx.attrs.cxx_flags,
+            ["--target={}".format(target_triple)] if target_triple else [],
+        ),
+    )
+    env["AR"] = _make_cc_shim(
+        ctx = ctx,
+        name = "__ar_shim",
+        cmd = cmd_args(cxx_toolchain_info.linker_info.archiver),
+    )
+
+    # Environment variables specified in the target's attributes get priority
+    # over all the above.
+    for k, v in ctx.attrs.env.items():
+        env[k] = cmd_args(v, relative_to = cwd)
+
+    ctx.actions.run(
+        cmd,
+        env = env,
+        category = "buildscript",
+    )
+
+    return [
+        DefaultInfo(
+            default_output = None,
+            sub_targets = {
+                "out_dir": [DefaultInfo(default_output = out_dir)],
+                "rustc_flags": [DefaultInfo(default_output = rustc_flags)],
+            },
+        )
+    ]
+
+_cargo_buildscript_rule = rule(
+    impl = _cargo_buildscript_impl,
+    attrs = {
+        "buildscript": attrs.exec_dep(providers = [RunInfo]),
+        "cxx_deps": attrs.list(attrs.dep(), default = []),
+        "cxx_flags": attrs.list(attrs.arg(), default = []),
+        "env": attrs.dict(key = attrs.string(), value = attrs.arg(), default = {}),
+        "features": attrs.list(attrs.string(), default = []),
+        "filegroup_for_manifest_dir": attrs.option(attrs.dict(key = attrs.string(), value = attrs.source()), default = None),
+        "manifest_dir": attrs.option(attrs.dep(), default = None),
+        "package_name": attrs.string(),
+        "runner": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//rust/tools:buildscript_run")),
+        # *IMPORTANT* rustc_cfg must be a `dep` and not an `exec_dep` because
+        # we want the `rustc --cfg` for the target platform, not the exec platform.
+        "rustc_cfg": attrs.dep(default = "prelude//rust/tools:rustc_cfg"),
+        "rustc_host_tuple": attrs.dep(default = "prelude//rust/tools:rustc_host_tuple"),
+        "rustc_link_lib": attrs.bool(default = False),
+        "rustc_link_search": attrs.bool(default = False),
+        "version": attrs.string(),
+        "_cxx_toolchain": toolchains_common.cxx(),
+        "_exec_os_type": buck.exec_os_type_arg(),
+        "_rust_internal_tools_toolchain": attrs.default_only(
+            attrs.toolchain_dep(default = "prelude//rust/tools:internal_tools_toolchain"),
+        ),
+        "_rust_toolchain": toolchains_common.rust(),
+    },
+    # Always empty, but needed to prevent errors
+    uses_plugins = [RustProcMacroPlugin],
+)
+
+def buildscript_run(
+    name,
+    buildscript_rule,
+    package_name,
+    version,
+    platform = {},
+    # path to crate's directory in source tree, e.g. "vendor/serde-1.0.100"
+    local_manifest_dir = None,
+    # target or subtarget containing crate, e.g. ":serde.git[serde]"
+    manifest_dir = None,
+    buildscript_compatible_with = None,
+    **kwargs,
+):
+    kwargs = apply_platform_attrs(platform, kwargs)
+
+    if manifest_dir == None and local_manifest_dir == None:
+        existing_filegroup_name = "{}-{}.crate".format(package_name, version)
+        if rule_exists(existing_filegroup_name):
+            manifest_dir = ":{}".format(existing_filegroup_name)
+        else:
+            local_manifest_dir = "vendor/{}-{}".format(package_name, version)
+
+    filegroup_for_manifest_dir = None
+    if local_manifest_dir != None:
+        prefix_with_trailing_slash = "{}/".format(local_manifest_dir)
+        filegroup_for_manifest_dir = {path.removeprefix(prefix_with_trailing_slash): path for path in glob(["{}/**".format(local_manifest_dir)])}
+
+    def platform_buildscript_build_name(plat):
+        if name.endswith("-build-script-run"):
+            # This is the expected case for Reindeer-generated targets, which
+            # come in pairs build-script-run and build-script-build.
+            return "{}-build-script-build-{}".format(
+                name.removesuffix("-build-script-run"),
+                plat,
+            )
+        else:
+            return "{}-{}".format(name, plat)
+
+    for i, plat in enumerate(get_reindeer_platform_names()):
+        transition_alias(
+            name = platform_buildscript_build_name(plat),
+            actual = buildscript_rule,
+            incoming_transition = "prelude//rust/buildscript:buildscript_platform_transition[{}]".format(i),
+            target_compatible_with = buildscript_compatible_with,
+            visibility = [],
+        )
+
+    buildscript_rule = selects.apply(
+        get_reindeer_platforms(),
+        lambda plat: buildscript_rule if plat == None else ":{}".format(platform_buildscript_build_name(plat)),
+    )
+
+    _cargo_buildscript_rule(
+        name = name,
+        buildscript = buildscript_rule,
+        package_name = package_name,
+        version = version,
+        filegroup_for_manifest_dir = filegroup_for_manifest_dir,
+        manifest_dir = manifest_dir,
+        **kwargs,
+    )
diff --git a/buck2/prelude/rust/cargo_package.bzl b/buck2/prelude/rust/cargo_package.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/cargo_package.bzl
@@ -0,0 +1,192 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+This file exports utilities for building third-party code with reindeer.
+These are not used anywhere else in prelude and are not exported as prelude globals.
+
+These should not be used for first-party code where lints are desired.
+"""
+
+load("@prelude//:prelude.bzl", "native")
+load("@prelude//utils:selects.bzl", "selects")
+load("@prelude//utils:type_defs.bzl", "is_dict", "is_list")
+
+def set_reindeer_platforms(platforms) -> None:
+    """
+    Call from a PACKAGE or BUCK_TREE file to make the macros in this file
+    recognize your own non-default platforms.
+
+        load("@prelude//rust:cargo_package.bzl", "DEFAULT_REINDEER_PLATFORMS", "set_reindeer_platforms")
+
+        set_reindeer_platforms(select({
+            "DEFAULT": DEFAULT_REINDEER_PLATFORMS,  # (optional)
+            "ovr_config//cpu:arm32-embedded-fpu": "thumbv7em-none-eabihf",
+        }))
+    """
+
+    native.write_package_value(
+        "rust.reindeer_platforms",
+        platforms,
+        overwrite = True,
+    )
+    native.write_package_value(
+        "rust.reindeer_platform_names",
+        _reindeer_platform_names(platforms),
+        overwrite = True,
+    )
+
+def get_reindeer_platforms():
+    platforms = native.read_package_value("rust.reindeer_platforms")
+    if platforms != None:
+        return platforms
+    return DEFAULT_REINDEER_PLATFORMS
+
+def get_reindeer_platform_names() -> set[str]:
+    platform_names = native.read_package_value("rust.reindeer_platform_names")
+    if platform_names != None:
+        return platform_names
+    return _DEFAULT_REINDEER_PLATFORM_NAMES
+
+DEFAULT_REINDEER_PLATFORMS = select({
+    "DEFAULT": None,
+    "prelude//os:linux": select({
+        "DEFAULT": None,
+        "prelude//cpu:arm64": "linux-arm64",
+        "prelude//cpu:riscv64": "linux-riscv64",
+        "prelude//cpu:x86_64": "linux-x86_64",
+    }),
+    "prelude//os:macos": select({
+        "DEFAULT": None,
+        "prelude//cpu:arm64": "macos-arm64",
+        "prelude//cpu:x86_64": "macos-x86_64",
+    }),
+    "prelude//os:none": select({
+        "DEFAULT": None,
+        "prelude//cpu:wasm32": "wasm32",
+    }),
+    "prelude//os:wasi": select({
+        "DEFAULT": None,
+        "prelude//cpu:wasm32": "wasi",
+    }),
+    "prelude//os:windows": select({
+        "DEFAULT": "windows-msvc",
+        "prelude//abi:gnu": "windows-gnu",
+        "prelude//abi:msvc": "windows-msvc",
+    }),
+})
+
+def _reindeer_platform_names(platform_select) -> set[str]:
+    names = set()
+    selects.apply(
+        platform_select,
+        lambda plat: names.add(plat) if plat != None else None,
+    )
+    return names
+
+_DEFAULT_REINDEER_PLATFORM_NAMES = _reindeer_platform_names(DEFAULT_REINDEER_PLATFORMS)
+
+def apply_platform_attrs(platform_attrs, universal_attrs, platform_select = None):
+    if platform_select == None:
+        platform_select = get_reindeer_platforms()
+
+    platform_attr_defaults = {}
+    for attrs in platform_attrs.values():
+        for attr, value in attrs.items():
+            if native.select_test(value, is_list):
+                platform_attr_defaults[attr] = []
+            elif native.select_test(value, is_dict):
+                platform_attr_defaults[attr] = {}
+            else:
+                platform_attr_defaults[attr] = None
+
+    combined_attrs = dict(universal_attrs)
+    for attr, default_value in platform_attr_defaults.items():
+        conditional_value = selects.apply(
+            platform_select,
+            lambda platform: platform_attrs.get(platform, {}).get(attr, default_value),
+        )
+        if attr in combined_attrs:
+            combined_attrs[attr] = combined_attrs[attr] + conditional_value
+        else:
+            combined_attrs[attr] = conditional_value
+
+    return combined_attrs
+
+# Build scripts need to evaluate `platform` according to the target platform of
+# the corresponding build-script-run target, not the current platform they are
+# configured for (which is the execution platform of the build-script-run
+# target).
+def apply_platform_attrs_for_buildscript_build(platform_attrs, universal_attrs):
+    return apply_platform_attrs(
+        platform_attrs,
+        universal_attrs,
+        select(
+            {
+                "DEFAULT": get_reindeer_platforms(),
+            }
+            | {"prelude//rust/buildscript:buildscript_for_platform[{}]".format(i): plat for i, plat in enumerate(get_reindeer_platform_names())}
+        ),
+    )
+
+def _cargo_rust_binary(name, crate = None, platform = {}, **kwargs):
+    """
+    Build a third-party rust binary for reindeer, suppressing lints.
+    """
+
+    if crate == "build_script_build":
+        kwargs = apply_platform_attrs_for_buildscript_build(platform, kwargs)
+    else:
+        kwargs = apply_platform_attrs(platform, kwargs)
+
+    rustc_flags = kwargs.get("rustc_flags", [])
+    kwargs["rustc_flags"] = ["--cap-lints=allow"] + rustc_flags
+
+    native.rust_binary(name = name, crate = crate, **kwargs)
+
+def _cargo_rust_library(name, platform = {}, **kwargs):
+    """
+    Build a third-party rust library for reindeer, suppressing lints.
+    """
+
+    kwargs = apply_platform_attrs(platform, kwargs)
+
+    rustc_flags = kwargs.get("rustc_flags", [])
+    kwargs["rustc_flags"] = ["--cap-lints=allow"] + rustc_flags
+
+    kwargs.setdefault("doctests", False)
+
+    # Support for reindeer's `python_ext` fixup is not implemented yet.
+    kwargs.pop("dlopen_enable", None)
+    kwargs.pop("linkable_alias", None)
+
+    native.rust_library(name = name, **kwargs)
+
+def alias(name, actual, platforms = None, visibility = None):
+    if platforms == None:
+        target_compatible_with = selects.apply(
+            get_reindeer_platforms(),
+            lambda plat: ["prelude//:none"] if plat == None else [],
+        )
+    else:
+        target_compatible_with = selects.apply(
+            get_reindeer_platforms(),
+            lambda plat: [] if plat in platforms else ["prelude//:none"],
+        )
+
+    native.alias(
+        name = name,
+        actual = actual,
+        target_compatible_with = target_compatible_with,
+        visibility = visibility,
+    )
+
+cargo = struct(
+    rust_binary = _cargo_rust_binary,
+    rust_library = _cargo_rust_library,
+)
diff --git a/buck2/prelude/rust/clippy_configuration.bzl b/buck2/prelude/rust/clippy_configuration.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/clippy_configuration.bzl
@@ -0,0 +1,65 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//rust:rust_toolchain.bzl", "RustToolchainInfo")
+
+# Configurations for Clippy runs.
+ClippyConfiguration = provider(
+    fields = {
+        "clippy_toml": provider_field(Artifact),
+    },
+)
+
+def _clippy_configuration_impl(ctx: AnalysisContext) -> list[Provider]:
+    toolchain_ctx = ctx.attrs._rust_toolchain[RustToolchainInfo]
+    toolchain_clippy_toml = toolchain_ctx.clippy_toml
+
+    if not toolchain_clippy_toml:
+        clippy_toml = ctx.attrs.clippy_toml_src
+    else:
+        toml_merge_tool = ctx.attrs.toml_merge_tool
+
+        clippy_toml = ctx.actions.declare_output("clippy.toml", has_content_based_path = False)
+        ctx.actions.run(
+            [
+                toml_merge_tool[RunInfo],
+                cmd_args(clippy_toml.as_output(), format = "--output={}"),
+                cmd_args(toolchain_clippy_toml, format = "--file={}"),
+                cmd_args(ctx.attrs.clippy_toml_src, format = "--file={}"),
+            ],
+            category = "clippy_toml_merge",
+        )
+
+    return [
+        DefaultInfo(
+            default_output = clippy_toml,
+        ),
+        ClippyConfiguration(
+            clippy_toml = clippy_toml,
+        ),
+    ]
+
+# Generate a Clippy configuration that is merged with the toolchain specified
+# Clippy configuration (if defined).
+clippy_configuration = rule(
+    impl = _clippy_configuration_impl,
+    attrs = {
+        "clippy_toml_src": attrs.source(),
+        # TODO(emersonford): figure out how to store this in `_rust_toolchain`
+        # without causing a circular dependency on the toolchain target when
+        # `toml_merge_tool` is a `rust_binary`.
+        #
+        # Tool used to recursively merge multiple TOML files, e.g. for merging
+        # clippy.toml files. Must support taking multiple `--file <FILENAME>` flags
+        # as source files to merge and `--output <FILENAME>` flag to write the
+        # merged TOML table to.
+        "toml_merge_tool": attrs.exec_dep(providers = [RunInfo]),
+        "_rust_toolchain": toolchains_common.rust(),
+    },
+)
diff --git a/buck2/prelude/rust/context.bzl b/buck2/prelude/rust/context.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/context.bzl
@@ -0,0 +1,312 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo", "LinkerInfo")
+load(
+    "@prelude//cxx:linker.bzl",
+    "get_default_shared_library_name",
+    "get_shared_library_name_for_param",
+)
+load("@prelude//linking:link_info.bzl", "LinkStrategy")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+load("@prelude//rust/tools:attrs.bzl", "RustInternalToolsInfo")
+load("@prelude//utils:cmd_script.bzl", "cmd_script")
+load(":build_params.bzl", "BuildParams", "CrateType", "Emit", "MetadataKind", "ProfileMode")
+load(
+    ":crate_name.bzl",
+    "CrateName",  # @unused Used as a type
+)
+load(":dep_context.bzl", "DepCollectionContext")
+load(
+    ":link_info.bzl",
+    "resolve_deps",
+)
+load(":rust_toolchain.bzl", "RustToolchainInfo")
+load(
+    ":sources.bzl",
+    "RustSources",
+    "RustSourcesTSet",
+    "symlinked_srcs",
+)
+
+# Struct for sharing common args between rustc and rustdoc
+# (rustdoc just relays bunch of the same args to rustc when trying to gen docs)
+CommonArgsInfo = record(
+    args = field(cmd_args),
+    subdir = field(str),
+    tempfile = field(str),
+    crate_type = field(CrateType),
+    params = field(BuildParams),
+    emit = field(Emit),
+    crate_map = field(list[(CrateName, Label)]),
+)
+
+DependencyArgsInfo = record(
+    args = field(cmd_args),
+    crate_map = field(list[(CrateName, Label)]),
+)
+
+# Compile info which is reusable between multiple compilation command performed
+# by the same rule.
+CompileContext = record(
+    # Clippy wrapper (wrapping clippy-driver so it has the same CLI as rustc).
+    clippy_wrapper = field(cmd_args),
+    # Memoized common args for reuse.
+    common_args = field(dict[(CrateType, Emit, LinkStrategy, bool, bool, bool, ProfileMode), CommonArgsInfo]),
+    # Memoized dependency args for reuse across emits with the same inputs.
+    dependency_args = field(dict[(CrateType, LinkStrategy, MetadataKind, bool), DependencyArgsInfo]),
+    cxx_toolchain_info = field(CxxToolchainInfo),
+    dep_ctx = field(DepCollectionContext),
+    exec_is_windows = field(bool),
+    internal_tools_info = field(RustInternalToolsInfo),
+    # The linker that we pass to `-Clinker`. This needs to be a wrapper script for two reasons:
+    #  1. The `linker` in the cxx toolchain is a `cmd_args` which might have multiple args, we need
+    #     this to be a single script.
+    #  2. We need to pass some linker args that are applied before the ones rustc passes. There's
+    #     unstable `-Zpre-link-arg` for that, but until that stabilizes, we pass them from within
+    #     this script.
+    linker_with_pre_args = field(cmd_args),
+    path_sep = field(str),
+    # Dylib name override, if any was provided by the target's `soname` attribute.
+    soname = field(str | None),
+    # Symlink root containing all sources.
+    symlinked_srcs = field(Artifact),
+    # All sources of transitive Rust dependencies, not including doc dependencies.
+    transitive_srcs = field(RustSourcesTSet),
+    # Linker args to pass the linker wrapper to rustc.
+    sysroot_args = field(cmd_args),
+    toolchain_info = field(RustToolchainInfo),
+    transitive_dependency_dirs = field(set[Artifact]),
+)
+
+def compile_context(ctx: AnalysisContext, binary: bool = False) -> CompileContext:
+    toolchain_info = ctx.attrs._rust_toolchain[RustToolchainInfo]
+    _validate_nightly_features(toolchain_info)
+    internal_tools_info = ctx.attrs._rust_internal_tools_toolchain[RustInternalToolsInfo]
+    cxx_toolchain_info = get_cxx_toolchain_info(ctx)
+
+    srcs = symlinked_srcs(ctx)
+
+    linker_with_pre_args = _linker(ctx, cxx_toolchain_info.linker_info, binary = binary)
+    clippy_wrapper = _clippy_wrapper(ctx, toolchain_info)
+
+    dep_ctx = DepCollectionContext(
+        advanced_unstable_linking = toolchain_info.advanced_unstable_linking,
+        include_doc_deps = False,
+        is_proc_macro = getattr(ctx.attrs, "proc_macro", False),
+        explicit_sysroot_deps = toolchain_info.explicit_sysroot_deps,
+        panic_runtime = toolchain_info.panic_runtime,
+    )
+
+    transitive_srcs = ctx.actions.tset(
+        RustSourcesTSet,
+        value = srcs,
+        children = [d.dep[RustSources].tset for d in resolve_deps(ctx, dep_ctx) if RustSources in d.dep],
+    )
+
+    # When we pass explicit sysroot deps, we need to override the default
+    # sysroot to avoid accidentally linking against the prebuilt sysroot libs
+    # provided by the toolchain.
+    if toolchain_info.explicit_sysroot_deps:
+        # Construct an empty sysroot dir with the similar structure as the real one
+        # in order to appease rustc. For instance, even with -Zexternal-clangrt, rustc will emit a
+        # -L{sysroot}/lib/rustlib/{target}/lib on the link line, which will fail if the sysroot dir is empty.
+        empty_sysroot = ctx.actions.copied_dir(
+            "empty_dir",
+            {
+                "lib/rustlib/{}/lib".format(toolchain_info.rustc_target_triple): ctx.actions.copied_dir("__empty__", {}, has_content_based_path = True),
+            },
+            has_content_based_path = True,
+        )
+        sysroot_args = cmd_args("--sysroot=", empty_sysroot, delimiter = "")
+    elif toolchain_info.sysroot_path:
+        sysroot_args = cmd_args("--sysroot=", toolchain_info.sysroot_path, delimiter = "")
+    else:
+        sysroot_args = cmd_args()
+
+    exec_is_windows = ctx.attrs._exec_os_type[OsLookup].os == Os("windows")
+    path_sep = "\\" if exec_is_windows else "/"
+
+    return CompileContext(
+        clippy_wrapper = clippy_wrapper,
+        common_args = {},
+        dependency_args = {},
+        cxx_toolchain_info = cxx_toolchain_info,
+        dep_ctx = dep_ctx,
+        exec_is_windows = exec_is_windows,
+        internal_tools_info = internal_tools_info,
+        linker_with_pre_args = linker_with_pre_args,
+        path_sep = path_sep,
+        soname = _attr_soname(ctx),
+        symlinked_srcs = srcs,
+        transitive_srcs = transitive_srcs,
+        sysroot_args = sysroot_args,
+        toolchain_info = toolchain_info,
+        transitive_dependency_dirs = set(),
+    )
+
+# Reject toolchain configurations that implicitly rely on unstable compiler
+# functionality if the toolchain does not also allow such functionality.
+def _validate_nightly_features(toolchain_info: RustToolchainInfo):
+    if toolchain_info.nightly_features:
+        return
+
+    requires_nightly = [
+        ("advanced_unstable_linking", toolchain_info.advanced_unstable_linking),
+        # Sysroot deps are passed via the unstable `--extern noprelude:...`
+        ("explicit_sysroot_deps", toolchain_info.explicit_sysroot_deps != None),
+        # `--json=unused-externs-silent` is unstable
+        ("report_unused_deps", toolchain_info.report_unused_deps),
+        # Custom target JSON files are unstable
+        ("rust_target_path", toolchain_info.rust_target_path != None),
+        # `-Zsanitizer` is unstable
+        ("sanitizer", toolchain_info.sanitizer != None),
+    ]
+    for name, enabled in requires_nightly:
+        if enabled:
+            fail(
+                "The Rust toolchain sets `{}`, which relies on unstable compiler functionality. It requires a toolchain with `nightly_features = True`.".format(
+                    name
+                )
+            )
+
+def _linker(ctx: AnalysisContext, linker_info: LinkerInfo, binary: bool = False) -> cmd_args:
+    linker_flags = ctx.attrs.linker_flags
+    if getattr(ctx.attrs, "_generated_build_info_enabled", False):
+        linker_flags = strip_build_info_linker_flags(linker_flags)
+    return cmd_script(
+        actions = ctx.actions,
+        name = "linker_wrapper",
+        cmd = cmd_args(
+            linker_info.linker,
+            linker_info.linker_flags or [],
+            # For "binary" rules, add C++ toolchain binary-specific linker flags.
+            # TODO(agallagher): This feels a bit wrong -- it might be better to have
+            # the Rust toolchain have it's own `binary_linker_flags` instead of
+            # implicitly using the one from the C++ toolchain.
+            linker_info.binary_linker_flags if binary else [],
+            ctx.attrs._rust_toolchain[RustToolchainInfo].linker_flags,
+            linker_flags,
+        ),
+        language = ctx.attrs._exec_os_type[OsLookup].script,
+        has_content_based_path = True,
+    )
+
+def strip_build_info_linker_flags(linker_flags):
+    return [flag for flag in linker_flags if not flag.startswith("--build-info")]
+
+# Return wrapper script for clippy-driver to make sure sysroot is set right
+# We need to make sure clippy is using the same sysroot - compiler, std libraries -
+# as rustc itself, so explicitly invoke rustc to get the path. This is a
+# (small - ~15ms per invocation) perf hit but only applies when generating
+# specifically requested clippy diagnostics.
+def _clippy_wrapper(ctx: AnalysisContext, toolchain_info: RustToolchainInfo) -> cmd_args:
+    clippy_driver = cmd_args(toolchain_info.clippy_driver)
+    rustc_print_sysroot = cmd_args(toolchain_info.compiler, "--print=sysroot", delimiter = " ")
+    uses_custom_target = toolchain_info.rust_target_path != None
+    if toolchain_info.rustc_target_triple:
+        rustc_print_sysroot.add("--target={}".format(toolchain_info.rustc_target_triple))
+        if uses_custom_target:
+            rustc_print_sysroot.add("-Zunstable-options")
+
+    skip_setting_sysroot = toolchain_info.explicit_sysroot_deps != None or toolchain_info.sysroot_path != None
+
+    if ctx.attrs._exec_os_type[OsLookup].os == Os("windows"):
+        wrapper_file, _ = ctx.actions.write(
+            ctx.actions.declare_output("__clippy_driver_wrapper.bat", has_content_based_path = True),
+            [
+                "@echo off",
+                "set __CLIPPY_INTERNAL_TESTS=true",
+            ]
+            + (
+                [
+                    "set RUSTC_BOOTSTRAP=1",
+                    cmd_args(
+                        toolchain_info.rust_target_path[DefaultInfo].default_outputs[0],
+                        format = "set RUST_TARGET_PATH={}",
+                    ),
+                ]
+                if uses_custom_target
+                else []
+            )
+            + []
+            + [
+                cmd_args(rustc_print_sysroot, format = 'FOR /F "tokens=* USEBACKQ" %%F IN (`{}`) DO (set SYSROOT=%%F)') if not skip_setting_sysroot else "",
+                cmd_args(clippy_driver, format = "{} %*"),
+            ],
+            allow_args = True,
+            has_content_based_path = True,
+        )
+    else:
+        wrapper_file, _ = ctx.actions.write(
+            ctx.actions.declare_output("__clippy_driver_wrapper.sh", has_content_based_path = True),
+            [
+                "#!/usr/bin/env bash",
+                # Force clippy to be clippy: https://github.com/rust-lang/rust-clippy/blob/e405c68b3c1265daa9a091ed9b4b5c5a38c0c0ba/src/driver.rs#L334
+                "export __CLIPPY_INTERNAL_TESTS=true",
+            ]
+            + (
+                [
+                    "export RUSTC_BOOTSTRAP=1",
+                    cmd_args(
+                        toolchain_info.rust_target_path[DefaultInfo].default_outputs[0],
+                        format = "export RUST_TARGET_PATH={}",
+                    ),
+                ]
+                if uses_custom_target
+                else []
+            )
+            + ([] if skip_setting_sysroot else [cmd_args(rustc_print_sysroot, format = "export SYSROOT=$({})")])
+            + [
+                cmd_args(clippy_driver, format = '{} "$@"\n'),
+            ],
+            is_executable = True,
+            allow_args = True,
+            has_content_based_path = True,
+        )
+
+    return cmd_args(wrapper_file, hidden = [clippy_driver, rustc_print_sysroot])
+
+def _attr_soname(ctx: AnalysisContext) -> str:
+    """
+    Get the shared library name to set for the given rust library.
+    """
+    linker_info = get_cxx_toolchain_info(ctx).linker_info
+    if getattr(ctx.attrs, "soname", None) != None:
+        return get_shared_library_name_for_param(linker_info, ctx.attrs.soname)
+    return get_default_shared_library_name(linker_info, ctx.label)
+
+# Filenames used for various emitted forms
+# `None` for a prefix or suffix means use the build_param version
+_EMIT_PREFIX_SUFFIX = {
+    Emit("asm"): ("", ".s"),
+    Emit("llvm-bc"): ("", ".bc"),
+    Emit("llvm-ir"): ("", ".ll"),
+    Emit("llvm-ir-noopt"): ("", ".ll"),
+    Emit("obj"): ("", ".o"),
+    Emit("metadata-fast"): ("lib", ".rmeta"),  # even binaries get called 'libfoo.rmeta'
+    Emit("metadata-full"): (None, None),  # Hollow rlibs, so they get the same name
+    Emit("link"): (None, None),  # crate type and reloc model dependent
+    Emit("rlib"): (None, None),  # crate type dependent, like `link`
+    Emit("dep-info"): ("", ".d"),
+    Emit("mir"): (None, ".mir"),
+    Emit("expand"): (None, ".rs"),
+    Emit("clippy"): ("lib", ".rmeta"),  # Treated like metadata-fast
+}
+
+# Return the filename for a particular emitted artifact type
+def output_filename(compile_ctx: CompileContext, cratename: str, emit: Emit, buildparams: BuildParams, extra: str | None = None) -> str:
+    # Allow for overriding the soname via the `soname` attribute.
+    if emit == Emit("link") and buildparams.crate_type in (CrateType("dylib"), CrateType("cdylib")):
+        return compile_ctx.soname
+
+    epfx, esfx = _EMIT_PREFIX_SUFFIX[emit]
+    prefix = epfx if epfx != None else buildparams.prefix
+    suffix = esfx if esfx != None else buildparams.suffix
+    return prefix + cratename + (extra or "") + suffix
diff --git a/buck2/prelude/rust/crate_name.bzl b/buck2/prelude/rust/crate_name.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/crate_name.bzl
@@ -0,0 +1,20 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+CrateName = record(
+    simple = field(str | ResolvedStringWithMacros),
+    dynamic = field(Artifact | None),
+)
+
+def crate_name_as_cmd_arg(crate: CrateName) -> cmd_args | str | ResolvedStringWithMacros:
+    if crate.dynamic:
+        # TODO: consider using `cmd_args(crate.dynamic, quote = "json")` so it
+        # doesn't fall apart on paths containing ')'
+        return cmd_args(crate.dynamic, format = "$(cat {})")
+    else:
+        return crate.simple
diff --git a/buck2/prelude/rust/custom-targets/BUCK b/buck2/prelude/rust/custom-targets/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/custom-targets/BUCK
@@ -0,0 +1,13 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.export_file(
+    name = "targets",
+    has_content_based_path = True,
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/rust/custom-targets/targets/riscv64emc-unknown-none-elf.json b/buck2/prelude/rust/custom-targets/targets/riscv64emc-unknown-none-elf.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/custom-targets/targets/riscv64emc-unknown-none-elf.json
@@ -0,0 +1,28 @@
+{
+    "arch": "riscv64",
+    "code-model": "medium",
+    "cpu": "generic-rv64",
+    "crt-objects-fallback": "false",
+    "data-layout": "e-m:e-p:64:64-i64:64-i128:128-n32:64-S64",
+    "eh-frame-header": false,
+    "emit-debug-gdb-scripts": false,
+    "features": "+e,+c,+zicsr,+zba,+zbb,+zbc,+zbs",
+    "linker": "rust-lld",
+    "linker-flavor": "gnu-lld",
+    "llvm-abiname": "lp64e",
+    "llvm-target": "riscv64",
+    "max-atomic-width": 0,
+    "metadata": {
+      "description": "Bare RISC-V (RV64EC ISA + Zb*)",
+      "host_tools": false,
+      "std": false,
+      "tier": 2
+    },
+    "panic-strategy": "abort",
+    "relocation-model": "static",
+    "supported-sanitizers": [
+      "shadow-call-stack",
+      "kernel-address"
+    ],
+    "target-pointer-width": 64
+}
diff --git a/buck2/prelude/rust/custom-targets/targets/riscv64imacf-unknown-none-elf.json b/buck2/prelude/rust/custom-targets/targets/riscv64imacf-unknown-none-elf.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/custom-targets/targets/riscv64imacf-unknown-none-elf.json
@@ -0,0 +1,28 @@
+{
+    "arch": "riscv64",
+    "code-model": "medium",
+    "cpu": "generic-rv64",
+    "crt-objects-fallback": "false",
+    "data-layout": "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128",
+    "eh-frame-header": false,
+    "emit-debug-gdb-scripts": false,
+    "features": "+m,+a,+c,+f",
+    "linker": "rust-lld",
+    "linker-flavor": "gnu-lld",
+    "llvm-abiname": "lp64f",
+    "llvm-target": "riscv64",
+    "max-atomic-width": 64,
+    "metadata": {
+      "description": "Bare RISC-V (RV64IMAC ISA)",
+      "host_tools": false,
+      "std": false,
+      "tier": 2
+    },
+    "panic-strategy": "abort",
+    "relocation-model": "static",
+    "supported-sanitizers": [
+      "shadow-call-stack",
+      "kernel-address"
+    ],
+    "target-pointer-width": 64
+}
diff --git a/buck2/prelude/rust/custom-targets/targets/riscv64imacfv-unknown-none-elf.json b/buck2/prelude/rust/custom-targets/targets/riscv64imacfv-unknown-none-elf.json
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/custom-targets/targets/riscv64imacfv-unknown-none-elf.json
@@ -0,0 +1,28 @@
+{
+    "arch": "riscv64",
+    "code-model": "medium",
+    "cpu": "generic-rv64",
+    "crt-objects-fallback": "false",
+    "data-layout": "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128",
+    "eh-frame-header": false,
+    "emit-debug-gdb-scripts": false,
+    "features": "+m,+a,+c,+f,+v",
+    "linker": "rust-lld",
+    "linker-flavor": "gnu-lld",
+    "llvm-abiname": "lp64f",
+    "llvm-target": "riscv64",
+    "max-atomic-width": 64,
+    "metadata": {
+      "description": "Bare RISC-V (RV64IMACFV ISA)",
+      "host_tools": false,
+      "std": false,
+      "tier": 2
+    },
+    "panic-strategy": "abort",
+    "relocation-model": "static",
+    "supported-sanitizers": [
+      "shadow-call-stack",
+      "kernel-address"
+    ],
+    "target-pointer-width": 64
+}
diff --git a/buck2/prelude/rust/dep_context.bzl b/buck2/prelude/rust/dep_context.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/dep_context.bzl
@@ -0,0 +1,23 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":rust_toolchain.bzl", "PanicRuntime", "RustExplicitSysrootDeps")
+
+# Information that determines how dependencies should be collected
+DepCollectionContext = record(
+    advanced_unstable_linking = field(bool),
+    include_doc_deps = field(bool),
+    # Is the target a proc-macro target? This is ignored if `include_doc_deps`
+    # is set, since doc tests in proc macro crates are not built with
+    # `--extern proc_macro`
+    is_proc_macro = field(bool),
+    # From the toolchain, if available
+    explicit_sysroot_deps = field(RustExplicitSysrootDeps | None),
+    # Only needed if `advanced_unstable_linking` is set
+    panic_runtime = field(PanicRuntime),
+)
diff --git a/buck2/prelude/rust/extern.bzl b/buck2/prelude/rust/extern.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/extern.bzl
@@ -0,0 +1,62 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    ":crate_name.bzl",
+    "CrateName",
+    "crate_name_as_cmd_arg",
+)
+
+# Create `--extern` flag. For crates with a name computed during analysis:
+#
+#     --extern=NAME=path/to/libNAME.rlib
+#
+# For crates with a name computed during build:
+#
+#     --extern=$(cat path/to/REALNAME)=path/to/libPROVISIONAL.rlib
+#
+def extern_arg(flags: list[str], crate: CrateName, lib: Artifact) -> cmd_args:
+    if flags == []:
+        flags = ""
+    else:
+        flags = ",".join(flags) + ":"
+
+    if type(crate.simple) == "string" and crate.dynamic == None:
+        return cmd_args(
+            lib,
+            format = "--extern={}{}={{}}".format(flags, crate.simple),
+        )
+
+    return cmd_args(
+        "--extern=",
+        flags,
+        crate_name_as_cmd_arg(crate),
+        "=",
+        lib,
+        delimiter = "",
+    )
+
+# Create `--crate-map` flag. For crates with a name computed during analysis:
+#
+#     --crate-map=NAME=//path/to:target
+#
+# For crates with a name computed during build:
+#
+#     --crate-map=$(cat path/to/REALNAME)=//path/to:target
+#
+def crate_map_arg(crate: CrateName, label: Label) -> cmd_args | str:
+    if type(crate.simple) == "string" and crate.dynamic == None:
+        return "--crate-map={}={}".format(crate.simple, str(label.raw_target()))
+
+    return cmd_args(
+        "--crate-map=",
+        crate_name_as_cmd_arg(crate),
+        "=",
+        str(label.raw_target()),
+        delimiter = "",
+    )
diff --git a/buck2/prelude/rust/failure_filter.bzl b/buck2/prelude/rust/failure_filter.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/failure_filter.bzl
@@ -0,0 +1,51 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":context.bzl", "CompileContext")
+
+# This creates an action which takes a buildstatus json artifact as an input, and a list of other
+# artifacts. If all those artifacts are present in the buildstatus as successfully generated, then
+# the action will succeed with those artifacts as outputs. Otherwise it fails.
+# Either way it streams whatever stderr content there is to stream.
+def failure_filter(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    predeclared_output: Artifact | None,
+    build_status: Artifact,
+    required: Artifact,
+    stderr: Artifact,
+    identifier: str,
+) -> Artifact:
+    failure_filter_action = compile_ctx.internal_tools_info.failure_filter_action
+
+    if predeclared_output:
+        output = predeclared_output
+    else:
+        output = ctx.actions.declare_output("out/" + required.short_path, has_content_based_path = getattr(ctx.attrs, "use_content_based_paths", False))
+
+    cmd = cmd_args(
+        failure_filter_action,
+        "--stderr",
+        stderr,
+        "--required-file",
+        required.short_path,
+        required,
+        output.as_output(),
+        "--build-status",
+        build_status,
+    )
+
+    toolchain_info = compile_ctx.toolchain_info
+    ctx.actions.run(
+        cmd,
+        category = "failure_filter",
+        identifier = identifier,
+        error_handler = toolchain_info.rust_error_handler,
+    )
+
+    return output
diff --git a/buck2/prelude/rust/link_info.bzl b/buck2/prelude/rust/link_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/link_info.bzl
@@ -0,0 +1,769 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Implementation of the Rust build rules.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+    "make_artifact_tset",
+)
+load(
+    "@prelude//cxx:cxx.bzl",
+    "get_auto_link_group_specs",
+)
+load(
+    "@prelude//cxx:cxx_library_utility.bzl",
+    "cxx_is_gnu",
+)
+load(
+    "@prelude//cxx:cxx_link_utility.bzl",
+    "ExecutableSharedLibArguments",  # @unused Used as a type
+    "executable_shared_lib_arguments_template",
+)
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "CxxToolchainInfo",  # @unused Used as a type
+    "PicBehavior",
+)
+load(
+    "@prelude//cxx:link_groups.bzl",
+    "BuildLinkGroupsContext",
+    "LinkGroupLinkInfo",  # @unused Used as a type
+    "collect_linkables",
+    "create_link_groups",
+    "get_filtered_labels_to_links_map",
+    "get_filtered_links",
+    "get_filtered_targets",
+    "get_link_group",
+    "get_link_group_info",
+    "get_link_group_preferred_linkage",
+    "get_public_link_group_nodes",
+)
+load(
+    "@prelude//cxx:link_groups_types.bzl",
+    "LinkGroupInfo",  # @unused Used as a type
+)
+load(
+    "@prelude//cxx:transformation_spec.bzl",
+    "TransformationSpecContext",  # @unused Used as a type
+)
+load(
+    "@prelude//linking:link_groups.bzl",
+    "LinkGroupLib",  # @unused Used as a type
+    "LinkGroupLibInfo",  # @unused Used as a type
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkInfo",
+    "LinkStrategy",
+    "MergedLinkInfo",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "LinkableGraph",
+    "create_linkable_graph",
+    "reduce_linkable_graph",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",
+    "traverse_shared_library_info",
+)
+load(
+    "@prelude//linking:types.bzl",
+    "Linkage",  # @unused Used as a type
+)
+load(
+    "@prelude//rust/tools:attrs.bzl",
+    "RustInternalToolsInfo",  # @unused Used as a type
+)
+load("@prelude//third-party:providers.bzl", "ThirdPartyBuildInfo")
+load(
+    "@prelude//utils:type_defs.bzl",
+    "is_dict",
+    "is_string",
+)
+load(
+    ":build_params.bzl",
+    "MetadataKind",  # @unused Used as a type
+)
+load(
+    ":crate_name.bzl",
+    "CrateName",  # @unused Used as a type
+)
+load(
+    ":dep_context.bzl",
+    "DepCollectionContext",  # @unused Used as a type
+)
+load(":rust_toolchain.bzl", "PanicRuntime", "RustToolchainInfo")
+
+# Link strategy for targets which do not set an explicit `link_style` attribute.
+#
+# These values are also used as the defaults for check/clippy subtargets on
+# libraries, and are the only way in which metadata-fast output can be built.
+#
+# Internally at Meta, these are a good choice for a default because they allow
+# sharing work between check builds and dev mode builds, which have shared link
+# strategy, and so consume their dependencies as `static_pic`.
+DEFAULT_STATIC_LINK_STRATEGY = LinkStrategy("static_pic")
+DEFAULT_STATIC_LIB_OUTPUT_STYLE = LibOutputStyle("pic_archive")
+
+RustProcMacroPlugin = plugins.kind()
+
+# This provider is used for proc macros in those places where `RustLinkInfo` would typically be used
+# for libraries. It represents a proc macro in the dependency graph, and contains as a field the
+# `target_label` of that proc macro. The actual providers will always be accessed later through
+# `ctx.plugins`
+RustProcMacroMarker = provider(
+    fields = {
+        "label": typing.Any,
+    }
+)
+
+# Artifact produced by a Rust compiler invocation.
+#
+# The artifact is assigned a provisional filepath at analysis time. However, the
+# real name of the crate may not be known until build time. For loading this
+# artifact as a transitive dependency, the filename matters and must match the
+# real crate name. We keep track of the crate name in its own artifact and use
+# it to create a symlink to make the Rust artifact appear with the required name
+# to later rustc executions.
+RustArtifact = record(
+    artifact = field(Artifact),
+    crate = field(CrateName),
+)
+
+def _project_artifacts(dep: RustArtifact) -> (Artifact, Artifact | None):
+    return (dep.artifact, dep.crate.dynamic)
+
+def _project_as_dynamic_name_args(dep: RustArtifact) -> Artifact | cmd_args:
+    return dep.crate.dynamic or cmd_args()
+
+def _project_artifacts_args(dep: RustArtifact) -> Artifact:
+    return dep.artifact
+
+# Set of RustArtifact.
+TransitiveDeps = transitive_set(
+    args_projections = {
+        "artifacts_args": _project_artifacts_args,
+        "dynamic_name_args": _project_as_dynamic_name_args,
+    },
+    json_projections = {
+        "artifacts": _project_artifacts,
+    },
+)
+
+# Information which is keyed on link_style
+RustLinkStrategyInfo = record(
+    # Path to the rlib, rmeta, dylib, etc.
+    outputs = field(dict[MetadataKind, Artifact]),
+    # Same as `outputs`, but wrapped in a 1-element transitive set.
+    singleton_tset = field(dict[MetadataKind, TransitiveDeps]),
+    # Transitive dependencies which are relevant to the consumer. For crate types which do not
+    # propagate their deps (specifically proc macros), this set is empty
+    # This does not include the proc macros, which are passed separately in `RustLinkInfo`
+    transitive_deps = field(dict[MetadataKind, TransitiveDeps]),
+    transitive_proc_macro_deps = field(set[RustProcMacroMarker]),
+    # Rustc-generated debug info which is referenced -- but not included -- by the
+    # linkable rlib. Does not include external debug info from non-Rust native deps.
+    #
+    # In the `advanced_unstable_linking` case, this is left empty; split debug info is just
+    # tracked in the native link providers like it usually would be.
+    rust_debug_info = ArtifactTSet | None,
+)
+
+# Set of list[(ConfiguredTargetLabel, MergedLinkInfo)]
+RustNativeLinkDeps = transitive_set()
+
+# Set of list[LinkableGraph]
+RustLinkableGraphs = transitive_set()
+
+# Set of list[Dependency]
+RustExportedLinkDeps = transitive_set()
+
+# Output of a Rust compilation
+RustLinkInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        # crate - crate name
+        "crate": CrateName,
+        # strategies - information about each LinkStrategy as RustLinkStrategyInfo
+        "strategies": dict[LinkStrategy, RustLinkStrategyInfo],
+        # Rust interacts with the native link graph in a non-standard way.
+        #
+        # The first difference is in the re-export behavior of Rust compared to C++. The native link
+        # providers make an assumption that if one node in the link graph references a symbol in
+        # another node in the link graph, there is also a corresponding edge in the link graph.
+        # Specifically, the first node must declare a direct dependency on the second, a transitive
+        # dependency is not enough. For C++, this just means that each library depends in the link
+        # graph on its direct deps and their exported deps.
+        #
+        # For Rust, the situation is different. Because of re-exports and generics causing delayed
+        # codegen, the generated object files for a Rust library can generate symbol references to
+        # any of the library's transitive Rust dependencies, as well as to the immediate C++
+        # dependencies of those libraries. So to account for that, each Rust library reports direct
+        # dependencies on all of those libraries in the link graph. The `native_link_deps` and
+        # `linkable_graphs` lists are the providers from all of those libraries.
+        #
+        # The second difference is unique to the case where `advanced_unstable_linking` is not set
+        # on the toolchain. Imagine we have a Rust library `:B` with its only one dependency `:A`,
+        # another Rust library. The Rust rules give Rust -> Rust dependencies special treatment in
+        # the non-`advanced_unstable_linking` case. As a result, the `MergedLinkInfo` provided from
+        # `:B` is not a "superset" of the `MergedLinkInfo` provided from `:A` (concrete differences
+        # discussed below).
+        #
+        # This distinction is implemented by effectively having each Rust library provide two sets
+        # of link providers. The first is the link providers used across Rust -> Rust dependency
+        # edges - this is what the fields below are. The second set is the one that is used by C++
+        # and other non-Rust dependents, and is returned from the rule like normal. The second set
+        # is a superset of the first, that is it includes anything that the first link providers
+        # added.
+        #
+        # The concrete difference is that the Rust `MergedLinkInfo` provided by `:A` is only the
+        # result of merging the `MergedLinkInfo`s from `:A`'s deps, and does not contain anything
+        # about `:A`. Instead, when `:B` produces the native `MergedLinkInfo`, it will add a single
+        # static library that bundles all transitive Rust deps, including `:A` (and similarly for
+        # the DSO case).
+        #
+        # With `advanced_unstable_linking`, Rust libraries essentially behave just like C++
+        # libraries in the link graph, with the handling of transitive dependencies being the only
+        # difference.
+        "native_link_deps": RustNativeLinkDeps,
+        "linkable_graphs": RustLinkableGraphs,
+        "shared_libs": SharedLibraryInfo,
+        "third_party_build_info": ThirdPartyBuildInfo,
+        # LinkGroupLibInfo intentionally omitted because the Rust -> Rust version
+        # never needs to be different from the Rust -> native version
+        #
+        # Rust currently treats all native dependencies as being exported, in
+        # the sense of C++ `exported_deps`. However, they are not only exported
+        # from the Rust library that directly depends on them, they are also
+        # exported through any further chains of Rust libraries. This list
+        # tracks those dependencies
+        #
+        # FIXME(JakobDegen): We should not default to treating all native deps
+        # as exported.
+        "exported_link_deps": RustExportedLinkDeps,
+    },
+)
+
+def _adjust_link_strategy_for_rust_dependencies(toolchain_info: RustToolchainInfo, dep_link_strategy: LinkStrategy) -> LinkStrategy:
+    if dep_link_strategy == LinkStrategy("shared") and not toolchain_info.advanced_unstable_linking:
+        return DEFAULT_STATIC_LINK_STRATEGY
+    else:
+        return dep_link_strategy
+
+def strategy_info(toolchain_info: RustToolchainInfo, info: RustLinkInfo, dep_link_strategy: LinkStrategy) -> RustLinkStrategyInfo:
+    rust_dep_link_strategy = _adjust_link_strategy_for_rust_dependencies(toolchain_info, dep_link_strategy)
+
+    return info.strategies[rust_dep_link_strategy]
+
+# Any dependency of a Rust crate
+RustOrNativeDependency = record(
+    # The actual dependency
+    dep = field(Dependency),
+    # The local name, if any (for `named_deps`)
+    name = field(None | str | ResolvedStringWithMacros),
+    # Any flags for the dependency (`flagged_deps`), which are passed on to rustc.
+    flags = field(list[str]),
+)
+
+RustDependency = record(
+    info = field(RustLinkInfo),
+    label = field(ConfiguredProvidersLabel),
+    dep = field(Dependency),
+    name = field(None | str | ResolvedStringWithMacros),
+    flags = field(list[str]),
+    proc_macro_marker = field(RustProcMacroMarker | None),
+)
+
+# Information about cxx link groups that rust depends on
+RustCxxLinkGroupInfo = record(
+    # cxx link infos to link against
+    filtered_links = field(list[LinkInfo]),
+    # symbol files args to ensure we export the required symbols
+    symbol_files_info = field(LinkInfo),
+    # targets to link against
+    filtered_targets = field(list[TargetLabel]),
+    # information about the link groups
+    link_group_info = field(LinkGroupInfo | None),
+    # shared libraries created from link groups
+    link_group_libs = field(dict[str, LinkGroupLib | None]),
+    # mapping from target labels to the corresponding link group link_info
+    labels_to_links_map = field(dict[Label, LinkGroupLinkInfo]),
+    # Target to link group name where it was actually linked into
+    targets_consumed_by_link_groups = field(dict[Label, str]),
+    # preferred linkage mode for link group libraries
+    link_group_preferred_linkage = field(dict[Label, Linkage]),
+)
+
+# Returns all first-order dependencies.
+def _do_resolve_deps(
+    deps: list[Dependency], named_deps: dict[str, Dependency] | list[(ResolvedStringWithMacros, Dependency)], flagged_deps: list[(Dependency, list[str])] = []
+) -> list[RustOrNativeDependency]:
+    named_deps_items = named_deps.items() if is_dict(named_deps) else named_deps
+
+    return [
+        RustOrNativeDependency(name = name, dep = dep, flags = flags)
+        for name, dep, flags in [(None, dep, []) for dep in deps]
+        + [(name, dep, []) for name, dep in named_deps_items]
+        + [(None, dep, flags) for dep, flags in flagged_deps]
+    ]
+
+def gather_explicit_sysroot_deps(dep_ctx: DepCollectionContext) -> list[RustOrNativeDependency]:
+    explicit_sysroot_deps = dep_ctx.explicit_sysroot_deps
+    if not explicit_sysroot_deps:
+        if dep_ctx.advanced_unstable_linking:
+            fail("Explicit sysroot deps are required when advanced_unstable_linking is on")
+        return []
+
+    out = []
+    if explicit_sysroot_deps.core:
+        out.append(
+            RustOrNativeDependency(
+                dep = explicit_sysroot_deps.core,
+                name = None,
+                flags = ["noprelude", "nounused"],
+            )
+        )
+    if explicit_sysroot_deps.std:
+        out.append(
+            RustOrNativeDependency(
+                dep = explicit_sysroot_deps.std,
+                name = None,
+                # "force" is used here in order to link std internals (like alloc hooks) even if the rest
+                # of std is otherwise unused (e.g. we are building a no_std crate that needs to link with
+                # other std-enabled crates as a standalone dylib).
+                flags = ["noprelude", "nounused", "force"],
+            )
+        )
+    if explicit_sysroot_deps.proc_macro:
+        out.append(
+            RustOrNativeDependency(
+                dep = explicit_sysroot_deps.proc_macro,
+                name = None,
+                flags = ["noprelude", "nounused"],
+            )
+        )
+
+    # When advanced_unstable_linking is on, we only add the dep that matches the
+    # panic runtime. Without advanced_unstable_linking, we just let rustc deal
+    # with it
+    if explicit_sysroot_deps.panic_unwind:
+        if not dep_ctx.advanced_unstable_linking or dep_ctx.panic_runtime == PanicRuntime("unwind"):
+            out.append(
+                RustOrNativeDependency(
+                    dep = explicit_sysroot_deps.panic_unwind,
+                    name = None,
+                    flags = ["noprelude", "nounused"],
+                )
+            )
+    if explicit_sysroot_deps.panic_abort:
+        if not dep_ctx.advanced_unstable_linking or dep_ctx.panic_runtime == PanicRuntime("abort"):
+            out.append(
+                RustOrNativeDependency(
+                    dep = explicit_sysroot_deps.panic_abort,
+                    name = None,
+                    flags = ["noprelude", "nounused"],
+                )
+            )
+    for d in explicit_sysroot_deps.others:
+        out.append(
+            RustOrNativeDependency(
+                dep = d,
+                name = None,
+                flags = ["noprelude", "nounused"],
+            )
+        )
+    return out
+
+def resolve_deps(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> list[RustOrNativeDependency]:
+    dependencies = _do_resolve_deps(
+        deps = ctx.attrs.deps,
+        named_deps = ctx.attrs.named_deps,
+        flagged_deps = ctx.attrs.flagged_deps,
+    )
+
+    if dep_ctx.include_doc_deps:
+        dependencies.extend(
+            _do_resolve_deps(
+                deps = getattr(ctx.attrs, "doc_deps", []),
+                named_deps = getattr(ctx.attrs, "doc_named_deps", {}),
+            )
+        )
+
+    return dependencies + gather_explicit_sysroot_deps(dep_ctx)
+
+def resolve_rust_deps_inner(ctx: AnalysisContext, all_deps: list[RustOrNativeDependency]) -> list[RustDependency]:
+    rust_deps = []
+    available_proc_macros = get_available_proc_macros(ctx)
+    for dep in all_deps:
+        proc_macro_marker = dep.dep.get(RustProcMacroMarker)
+        if proc_macro_marker != None:
+            # Confusingly, this is not `proc_macro_marker.label`, since that has type
+            # `target_label`, but this wants a `label`
+            label = available_proc_macros[proc_macro_marker.label].label
+            info = available_proc_macros[proc_macro_marker.label][RustLinkInfo]
+        else:
+            label = dep.dep.label
+            info = dep.dep.get(RustLinkInfo)
+            if info == None:
+                continue
+
+        rust_deps.append(
+            RustDependency(
+                info = info,
+                label = label,
+                dep = dep.dep,
+                name = dep.name,
+                flags = dep.flags,
+                proc_macro_marker = proc_macro_marker,
+            )
+        )
+    return rust_deps
+
+def resolve_rust_deps(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> list[RustDependency]:
+    all_deps = resolve_deps(ctx, dep_ctx)
+    return resolve_rust_deps_inner(ctx, all_deps)
+
+def get_available_proc_macros(ctx: AnalysisContext) -> dict[TargetLabel, Dependency]:
+    return {x.label.raw_target(): x for x in ctx.plugins[RustProcMacroPlugin]}
+
+# Returns native link dependencies.
+def _native_link_dependencies(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> list[Dependency]:
+    """
+    Return all first-order native linkable dependencies of all transitive Rust
+    libraries.
+
+    This emulates v1's graph walk, where it traverses through Rust libraries
+    looking for non-Rust native link infos (and terminating the search there).
+    """
+    first_order_deps = [dep.dep for dep in resolve_deps(ctx, dep_ctx)]
+
+    return [d for d in first_order_deps if RustLinkInfo not in d and MergedLinkInfo in d]
+
+# Returns the rust link infos for non-proc macro deps.
+#
+# This is intended to be used to access the Rust -> Rust link providers
+def _rust_non_proc_macro_link_infos(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> list[RustLinkInfo]:
+    return [d.info for d in resolve_rust_deps(ctx, dep_ctx) if d.proc_macro_marker == None]
+
+def inherited_exported_link_deps(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> RustExportedLinkDeps:
+    return ctx.actions.tset(
+        RustExportedLinkDeps,
+        value = _native_link_dependencies(ctx, dep_ctx),
+        children = [dep.info.exported_link_deps for dep in resolve_rust_deps(ctx, dep_ctx) if dep.proc_macro_marker == None],
+    )
+
+def inherited_third_party_builds(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> list[ThirdPartyBuildInfo]:
+    infos = []
+    infos.extend([d[ThirdPartyBuildInfo] for d in _native_link_dependencies(ctx, dep_ctx) if ThirdPartyBuildInfo in d])
+    for dep in _rust_non_proc_macro_link_infos(ctx, dep_ctx):
+        infos.append(dep.third_party_build_info)
+    return infos
+
+def inherited_rust_cxx_link_group_info(
+    ctx: AnalysisContext, dep_ctx: DepCollectionContext, link_strategy: LinkStrategy, transformation_spec_context: TransformationSpecContext | None
+) -> RustCxxLinkGroupInfo | None:
+    # Check minimum requirements
+    if not cxx_is_gnu(ctx) or not ctx.attrs.auto_link_groups:
+        return None
+
+    link_graphs = dfs_dedupe_by_label(inherited_linkable_graphs(ctx, dep_ctx))
+
+    link_group = get_link_group(ctx)
+
+    # Assume a rust executable wants to use link groups if a link group map
+    # is present
+    link_group_info = get_link_group_info(ctx, link_graphs, link_strategy)
+    if link_group_info == None:
+        return None
+
+    link_groups = link_group_info.groups
+    link_group_mappings = link_group_info.mappings
+    link_group_preferred_linkage = get_link_group_preferred_linkage(link_groups.values())
+
+    auto_link_group_specs = get_auto_link_group_specs(ctx, link_group_info)
+    linkable_graph = create_linkable_graph(
+        ctx,
+        deps = link_graphs,
+    )
+    reduced_linkable_graph = reduce_linkable_graph(linkable_graph)
+    linkable_graph_node_map = reduced_linkable_graph.nodes
+
+    executable_deps = []
+    for g in link_graphs:
+        if g.label in linkable_graph_node_map:
+            executable_deps.append(g.label)
+        else:
+            # handle labels that are mutated by version alias
+            executable_deps.append(g.nodes.value.label)
+
+    public_link_group_nodes = get_public_link_group_nodes(
+        linkable_graph_node_map,
+        link_group_mappings,
+        executable_deps,
+        link_group,
+    )
+
+    linked_link_groups = create_link_groups(
+        ctx = ctx,
+        link_groups = link_groups,
+        link_strategy = link_strategy,
+        linkable_graph = reduced_linkable_graph,
+        link_group_mappings = link_group_mappings,
+        link_group_preferred_linkage = link_group_preferred_linkage,
+        executable_deps = executable_deps,
+        linker_flags = [],
+        link_group_specs = auto_link_group_specs,
+        other_roots = [],
+        prefer_stripped_objects = False,  # Does Rust ever use stripped objects?
+        anonymous = ctx.attrs.anonymous_link_groups,
+        public_nodes = public_link_group_nodes,
+        transformation_spec_context = transformation_spec_context,
+    )
+
+    auto_link_groups = {}
+    link_group_libs = {}
+
+    for name, linked_link_group in linked_link_groups.libs.items():
+        auto_link_groups[name] = linked_link_group.artifact
+        if linked_link_group.library != None:
+            link_group_libs[name] = linked_link_group.library
+
+    roots = set(executable_deps)
+    pic_behavior = PicBehavior("always_enabled") if link_strategy == LinkStrategy("static_pic") else PicBehavior("supported")
+    is_executable_link = True
+    exec_linkables = collect_linkables(
+        reduced_linkable_graph,
+        is_executable_link,
+        link_strategy,
+        link_group_preferred_linkage,
+        pic_behavior,
+        roots,
+    )
+    build_context = BuildLinkGroupsContext(
+        public_nodes = public_link_group_nodes,
+        linkable_graph = reduced_linkable_graph,
+        link_groups = link_groups,
+        link_group_mappings = link_group_mappings,
+        link_group_preferred_linkage = link_group_preferred_linkage,
+        link_strategy = link_strategy,
+        pic_behavior = pic_behavior,
+        link_group_libs = {name: (lib.label, lib.shared_link_infos) for name, lib in link_group_libs.items()},
+        prefer_stripped = False,
+        prefer_optimized = False,
+    )
+    labels_to_links = get_filtered_labels_to_links_map(
+        link_group = link_group,
+        linkables = exec_linkables,
+        is_executable_link = is_executable_link,
+        build_context = build_context,
+        force_static_follows_dependents = True,
+    )
+
+    return RustCxxLinkGroupInfo(
+        filtered_links = get_filtered_links(labels_to_links.map),
+        symbol_files_info = LinkInfo(
+            pre_flags = linked_link_groups.symbol_ldflags,
+        ),
+        filtered_targets = get_filtered_targets(labels_to_links.map),
+        link_group_info = link_group_info,
+        link_group_libs = link_group_libs,
+        labels_to_links_map = labels_to_links.map,
+        targets_consumed_by_link_groups = linked_link_groups.targets_consumed_by_link_groups,
+        link_group_preferred_linkage = link_group_preferred_linkage,
+    )
+
+def inherited_native_link_deps(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> RustNativeLinkDeps:
+    return ctx.actions.tset(
+        RustNativeLinkDeps,
+        value = [(dep.label.configured_target(), dep[MergedLinkInfo]) for dep in _native_link_dependencies(ctx, dep_ctx)],
+        children = [info.native_link_deps for info in _rust_non_proc_macro_link_infos(ctx, dep_ctx)],
+    )
+
+def inherited_merged_link_infos(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> list[MergedLinkInfo]:
+    return dfs_dedupe_by_label(inherited_native_link_deps(ctx, dep_ctx))
+
+def inherited_shared_libs(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> list[SharedLibraryInfo]:
+    infos = []
+    infos.extend([d[SharedLibraryInfo] for d in _native_link_dependencies(ctx, dep_ctx)])
+    infos.extend([d.shared_libs for d in _rust_non_proc_macro_link_infos(ctx, dep_ctx)])
+    return infos
+
+def inherited_linkable_graphs(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> RustLinkableGraphs:
+    return ctx.actions.tset(
+        RustLinkableGraphs,
+        value = [d[LinkableGraph] for d in _native_link_dependencies(ctx, dep_ctx) if LinkableGraph in d],
+        children = [info.linkable_graphs for info in _rust_non_proc_macro_link_infos(ctx, dep_ctx)],
+    )
+
+def inherited_link_group_lib_infos(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> list[LinkGroupLibInfo]:
+    # There are no special Rust -> Rust versions of this provider
+    deps = {}
+    for d in resolve_deps(ctx, dep_ctx):
+        i = d.dep.get(LinkGroupLibInfo)
+        if i:
+            deps[d.dep.label] = i
+    return deps.values()
+
+def inherited_rust_external_debug_info(ctx: AnalysisContext, dep_ctx: DepCollectionContext, link_strategy: LinkStrategy) -> list[ArtifactTSet]:
+    toolchain_info = ctx.attrs._rust_toolchain[RustToolchainInfo]
+    return filter(None, [strategy_info(toolchain_info, d.info, link_strategy).rust_debug_info for d in resolve_rust_deps(ctx, dep_ctx)])
+
+def inherited_external_debug_info(ctx: AnalysisContext, dep_ctx: DepCollectionContext, dep_link_strategy: LinkStrategy) -> ArtifactTSet:
+    inherited_debug_infos = []
+    for d in inherited_merged_link_infos(ctx, dep_ctx):
+        native_debug_info = d._external_debug_info.get(dep_link_strategy)
+        if native_debug_info:
+            inherited_debug_infos.append(native_debug_info)
+
+    inherited_debug_infos.extend(inherited_rust_external_debug_info(ctx, dep_ctx, dep_link_strategy))
+
+    return make_artifact_tset(
+        actions = ctx.actions,
+        children = inherited_debug_infos,
+    )
+
+def normalize_crate(label: str | ResolvedStringWithMacros) -> str | ResolvedStringWithMacros:
+    return label.replace("-", "_") if is_string(label) else label
+
+def attr_simple_crate_for_filenames(ctx: AnalysisContext) -> str:
+    """
+    A "good enough" identifier to use in filenames. Buck wants to have filenames
+    of artifacts figured out before we begin building them. Normally we want a
+    crate foo to produce artifact libfoo.rlib; but if crate_dynamic is being
+    used, the true crate name is not known until later. In this situation we use
+    the rule's name in place of the true crate name in filenames.
+
+    # produces libordinary.rlib
+    rust_library(
+        name = "ordinary",
+        crate = "ordinary",
+    )
+
+    # produces libthrift_generated.rlib
+    rust_library(
+        name = "thrift-generated",
+        crate_dynamic = ":get-namespace-from-thrift-file",
+    )
+    """
+    return normalize_crate(ctx.attrs.crate or ctx.label.name)
+
+def attr_crate(ctx: AnalysisContext) -> CrateName:
+    """
+    The true user-facing name of the crate, which may only be known at build
+    time, not during analysis.
+    """
+    dynamic = getattr(ctx.attrs, "crate_dynamic", None)
+    if dynamic:
+        dynamic = dynamic.get(DefaultInfo).default_outputs[0]
+    return CrateName(
+        simple = normalize_crate(ctx.attrs.crate or ctx.label.name),
+        dynamic = dynamic,
+    )
+
+def dfs_dedupe_by_label(tset: TransitiveSet) -> list[typing.Any]:
+    entries = {}
+    for node in tset.traverse(ordering = "dfs"):
+        for item in node:
+            if isinstance(item, tuple):
+                label, value = item
+            else:
+                label, value = item.label, item
+            if label in entries and entries[label] != value:
+                fail(
+                    "cannot depend on {} in multiple inconsistent ways:\n{}\n{}".format(
+                        label,
+                        entries[label],
+                        value,
+                    )
+                )
+            entries[label] = value
+    return entries.values()
+
+def run_action_shlib_symlink_tree(
+    actions: AnalysisActions,
+    internal_tools_info: RustInternalToolsInfo,
+    shared_library_info: SharedLibraryInfo,
+    shared_libs_symlink_tree_name_arg: str,
+    dwp_symlink_tree_name_arg: str,
+) -> (Artifact, Artifact):
+    """Runs an action that creates 2 shared library symlink trees from a `SharedLibraryInfo` (i.e., a `TransitiveSet`).
+
+    Returns:
+      A pair of artifacts that it creates.  The 1st is the shared library symlink tree.  The 2nd is the dwp symlink tree.
+    """
+    shared_libs_symlink_tree = actions.declare_output(shared_libs_symlink_tree_name_arg, has_content_based_path = False)
+    dwp_symlink_tree = actions.declare_output(dwp_symlink_tree_name_arg, has_content_based_path = False)
+
+    shared_library_info_json = actions.write_json(
+        "shared_library_info.json",
+        shared_library_info.set.project_as_json("symlink_tree"),
+        with_inputs = True,
+        has_content_based_path = False,
+    )
+
+    actions.run(
+        [
+            internal_tools_info.shared_libraries_symlink_tree,
+            cmd_args(shared_libs_symlink_tree.as_output(), format = "--shared_libs_symlink_tree={}"),
+            cmd_args(dwp_symlink_tree.as_output(), format = "--dwp_symlink_tree={}"),
+            cmd_args(shared_library_info_json, format = "--shared_libraries_info_json={}"),
+        ],
+        category = "rust_shared_library_symlinks",
+    )
+    return (shared_libs_symlink_tree, dwp_symlink_tree)
+
+def executable_shared_lib_arguments_from_shared_library_info(
+    ctx: AnalysisContext, cxx_toolchain: CxxToolchainInfo, internal_tools_info: RustInternalToolsInfo, output: Artifact, shared_library_info: SharedLibraryInfo
+) -> ExecutableSharedLibArguments:
+    """A version of `prelude/cxx/cxx_link_utilit.bzl#executable_shared_lib_arguments`
+    that uses the `TransitiveSet` properties of `SharedLibraryInfo` to save memory and
+    runtime costs of `TransitiveSet#traversal` calls.
+    """
+
+    def create_external_debug_info() -> list[TransitiveSetArgsProjection]:
+        if shared_library_info and shared_library_info.set:
+            external_debug_info = shared_library_info.set.project_as_args("external_debug_info")
+            return [external_debug_info]
+        else:
+            return []
+
+    def create_shared_libs_symlink_tree_windows() -> list[Artifact]:
+        shared_libs = traverse_shared_library_info(shared_library_info, transformation_provider = None)
+        return [
+            ctx.actions.symlink_file(
+                shlib.lib.output.basename,
+                shlib.lib.output,
+                has_content_based_path = False,
+            )
+            for shlib in shared_libs
+        ]
+
+    def create_shared_libs_symlink_trees(shared_libs_symlink_tree_name_arg: str, dwp_symlink_tree_name_arg: str) -> (Artifact, Artifact) | None:
+        if not shared_library_info.set:
+            return None
+
+        return run_action_shlib_symlink_tree(
+            ctx.actions,
+            internal_tools_info,
+            shared_library_info,
+            shared_libs_symlink_tree_name_arg,
+            dwp_symlink_tree_name_arg,
+        )
+
+    return executable_shared_lib_arguments_template(
+        cxx_toolchain,
+        output,
+        create_external_debug_info,
+        create_shared_libs_symlink_trees,
+        create_shared_libs_symlink_tree_windows,
+    )
diff --git a/buck2/prelude/rust/linkable_symbol.bzl b/buck2/prelude/rust/linkable_symbol.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/linkable_symbol.bzl
@@ -0,0 +1,157 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Example:
+
+    buck_genrule(
+        name = "my-generated-data"
+        bash = "something slow",
+    )
+
+    rust_linkable_symbol(
+        name = "my-generated-data-symbol",
+        content_str = ":my-generated-data",  # or `content_bytes` for non-utf8
+    )
+
+    rust_binary(
+        name = "whoa",
+        srcs = ...,
+        deps = [
+            ...
+            ":my-generated-data-symbol",
+        ],
+    )
+
+The generated Rust library contains a get() function that returns your symbol's
+data as &'static str or &'static [u8], depending on whether you used str or
+bytes in the rust_linkable_symbol target.
+
+    fn main() {
+        let my_generated_data = my_generated_data_symbol::get();
+        println!("{:?}", my_generated_data);
+    }
+
+The major advantage of rust_linkable_symbol over directly using include_bytes
+with a mapped_srcs in your Rust target is that your slow genrule does not have
+to get built when you're doing typecheck-only builds of the Rust code. That
+applies to all of the following situations:
+
+  - `arc rust-check` a.k.a. `buck2 build :whoa[check]`
+
+  - documentation builds: `buck2 build :whoa[doc]`
+
+  - all building performed by IDE
+"""
+
+load("@prelude//rust:link_info.bzl", "RustLinkInfo") # @oss-enable
+load("@prelude//prelude.bzl", prelude = "native") # @oss-enable
+load("@prelude//rust:sources.bzl", "RustSources") # @oss-enable
+# @oss-disable[end= ]: load("@fbcode//buck2/facebook:autodeps_hacks.bzl", "RustLinkInfo", "RustSources", "prelude")
+
+def _remove_rust_providers_impl(ctx: AnalysisContext) -> list[Provider]:
+    out = []
+    for p in ctx.attrs.base.providers:
+        # Remove RustLinkInfo so the dep is treated as a C++ dep rather than
+        # a Rust dep, avoiding the need to build @symbol during type checking.
+        # Remove RustSources so the @symbol's transitive sources (which include
+        # the potentially slow genrule content) are not pulled into downstream
+        # compile actions as hidden inputs.
+        if not isinstance(p, RustLinkInfo) and not isinstance(p, RustSources):
+            out.append(p)
+    return out
+
+_remove_rust_providers = rule(
+    impl = _remove_rust_providers_impl,
+    attrs = {
+        "base": attrs.dep(),
+        "labels": attrs.list(attrs.string()),
+    },
+)
+
+def rust_linkable_symbol(name, content_str = None, content_bytes = None, align_bytes = None, visibility = None, rust_library_macro = None):
+    if (content_str == None) == (content_bytes == None):
+        fail("rust_linkable_symbol requires exactly one of `content_str =` or `content_bytes =` to be passed")
+
+    if align_bytes != None:
+        if content_bytes == None:
+            fail("rust_linkable_symbol's align_bytes is only supported when using content_bytes")
+        if align_bytes not in [2, 4, 8]:
+            fail("unsupported rust_linkable_symbol alignment")
+
+    kind, content = ("str", content_str) if content_str else ("bytes", content_bytes)
+
+    rust_library_macro = rust_library_macro or prelude.rust_library
+
+    # Generate a globally unique symbol name that also works as a regular C style symbol
+    # to be compatible with all flavors of linkers.
+    linkable_symbol = "rust_linkable_symbol_{}__{}".format(package_name().replace("/", "_"), name)
+
+    # Rustc shouldn't be the easiest way to accomplish this but here we are.
+    #
+    # Background reading:
+    # https://tratt.net/laurie/blog/2022/whats_the_most_portable_way_to_include_binary_blobs_in_an_executable.html
+    #
+    # Maybe use `#embed` eventually (several years from now?).
+    # https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3017.htm
+    rust_library_macro(
+        name = "{}@symbol".format(name),
+        crate = name,
+        doctests = False,
+        env = {
+            "LINKABLE_SYMBOL": linkable_symbol,
+        },
+        labels = [
+            "generated",
+            "rustc_do_not_check",
+        ],
+        mapped_srcs = {
+            "prelude//rust/tools:linkable_symbol.rs": "lib.rs",
+            content: "content",
+        },
+        rustc_flags = [
+            "--cfg=rust_linkable_symbol_content_{}".format(kind),
+            '--cfg=rust_linkable_symbol_align_bytes="{}"'.format(align_bytes or 1),
+            "@$(location prelude//rust/tools:linkable_symbol_supports_no_std)",
+        ],
+        visibility = [],
+    )
+
+    # Alias the Rust library with a rule that removes the `RustLinkInfo` and `RustSources`.
+    # This causes the dependent library to be treated more like a C++ dep than a
+    # Rust dep, and thereby not be needed during type checking.
+    _remove_rust_providers(
+        name = "{}@link".format(name),
+        base = ":{}@symbol".format(name),
+        labels = ["generated"],
+    )
+
+    rust_library_macro(
+        name = name,
+        deps = [
+            ":{}@link".format(name),
+        ],
+        doctests = False,
+        env = {
+            "LINKABLE_SYMBOL": linkable_symbol,
+        },
+        labels = [
+            "generated",
+        ],
+        mapped_srcs = {
+            "prelude//rust/tools:linkable_symbol.rs": "lib.rs",
+        },
+        rustc_flags = [
+            "--cfg=rust_linkable_symbol_getter_{}".format(kind),
+            '--cfg=rust_linkable_symbol_align_bytes="{}"'.format(align_bytes or 1),
+            # Setting `no_std` here is unconditionally fine - a panic handler will
+            # be provided by whatever uses this library.
+            "--cfg=set_nostd",
+        ],
+        visibility = visibility,
+    )
diff --git a/buck2/prelude/rust/named_deps.bzl b/buck2/prelude/rust/named_deps.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/named_deps.bzl
@@ -0,0 +1,36 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:argfile.bzl", "at_argfile")
+load("@prelude//utils:type_defs.bzl", "is_list")
+load(":context.bzl", "CompileContext")
+
+# Write a file containing all the dynamically-generated dependency names. This
+# isn't used in the course of any Buck builds, but is needed by rust-project to
+# supply an accurate dependency graph to rust-analyzer..
+def write_named_deps_names(ctx: AnalysisContext, compile_ctx: CompileContext) -> Artifact | None:
+    if not is_list(ctx.attrs.named_deps):
+        return None
+
+    use_cbp = getattr(ctx.attrs, "use_content_based_paths", False)
+    named_deps_names = ctx.actions.declare_output("named_deps", has_content_based_path = use_cbp)
+    ctx.actions.run(
+        cmd_args(
+            compile_ctx.internal_tools_info.rustc_action,
+            cmd_args(named_deps_names.as_output(), format = "--echo={}"),
+            at_argfile(
+                actions = ctx.actions,
+                name = "named_deps.args",
+                args = [name for name, _dep in ctx.attrs.named_deps],
+                allow_args = True,
+                has_content_based_path = use_cbp,
+            ),
+        ),
+        category = "named_deps",
+    )
+    return named_deps_names
diff --git a/buck2/prelude/rust/outputs.bzl b/buck2/prelude/rust/outputs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/outputs.bzl
@@ -0,0 +1,75 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":link_info.bzl", "TransitiveDeps")
+
+# Outputs that are generally associated with object code compilation, as opposed to linking
+RustcCompileOutput = record(
+    # A stripped version of the output, only available if the main output is not linked and
+    # stripping makes sense for it
+    stripped_output = Artifact | None,
+    diag_txt = field(Artifact),
+    diag_json = field(Artifact),
+    # Zero or more Split DWARF debug info files are emitted into this directory
+    # with unpredictable filenames.
+    dwo_output_directory = field(Artifact | None),
+    # The output of the profiler. Set only if `rust_compile` was invoked with a
+    # `profile_mode`
+    profile_output = field(Artifact | None),
+    # LLVM remarks output. Set when profile_mode=ProfileMode("remarks").
+    # These point to diag_txt/diag_json since remarks are part of the diagnostic stream.
+    remarks_txt = field(Artifact | None),
+    remarks_json = field(Artifact | None),
+)
+
+RustcLinkOutput = record(
+    # Windows .lib artifact for linking against .dll
+    import_library = field(Artifact | None),
+    pdb = field(Artifact | None),
+    dwp_output = field(Artifact | None),
+)
+
+RustcOutput = record(
+    # For bin-crate `Emit("rlib")` compiles this is the `out_manifest` of
+    # `link_extraction` — the list of extracted objects — since rustc produces
+    # no linked artifact; the executable is produced by `rust_link_binary`.
+    output = Artifact,
+    singleton_tset = TransitiveDeps,
+    compile_output = RustcCompileOutput,
+    # Only available when the combination of params requires linking and rustc
+    # itself performs the link (i.e. not for bin-crate `Emit("rlib")`).
+    link_output = RustcLinkOutput | None,
+    # A `LinkExtraction`, set exactly when this was a bin-crate `Emit("rlib")`
+    # compile: rustc compiled and its synthesized link inputs were extracted
+    # for the caller to link via `rust_link_binary`.
+    link_extraction = typing.Any,
+)
+
+def output_as_diag_subtargets(o: RustcOutput, clippy: RustcOutput) -> dict[str, Artifact]:
+    return {
+        "check": o.output,
+        "clippy.json": clippy.compile_output.diag_json,
+        "clippy.txt": clippy.compile_output.diag_txt,
+        "diag.json": o.compile_output.diag_json,
+        "diag.txt": o.compile_output.diag_txt,
+    }
+
+# Access to additional outputs from Rust compilation.
+#
+# This provider is intended to be available from all rules that compile Rust
+# code. As a result, it must be different from `RustLinkInfo`, since it should
+# not exist on a prebuilt Rust library, but should exist on a binary.
+RustcExtraOutputsInfo = provider(
+    fields = {
+        "clippy": RustcOutput,
+        "clippy_incr": RustcOutput,
+        "metadata": RustcOutput,
+        "metadata_incr": RustcOutput,
+        "remarks": RustcOutput | None,
+    },
+)
diff --git a/buck2/prelude/rust/proc_macro_alias.bzl b/buck2/prelude/rust/proc_macro_alias.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/proc_macro_alias.bzl
@@ -0,0 +1,44 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Helper rule which introduces proc macros into the dependency graph
+
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load(":link_info.bzl", "RustProcMacroMarker", "RustProcMacroPlugin")
+
+def _impl(ctx):
+    # FIXME(JakobDegen): The rules themselves do not need any of the exec configured providers.
+    # They only ever access the `RustProcMacroMarker` provider and do everything else through
+    # plugins. However, we cannot return just that provider, since it results in
+    # `buck2 build :proc_macro` building nothing. We would get the right behavior out of the
+    # command line build invocation by taking a regular target dep on the aliased target and
+    # returning those targets. However, that also does not work because it would result the target
+    # configuration for a Rust library needing to be compatible with the target configuration for
+    # its proc macro deps (a Linux-only proc macro should still be usable in a Rust build targeting
+    # Mac).
+    #
+    # Instead, we take an exec dep on the aliased target and return those providers. This is a
+    # compromise solution. The upside is that it avoids introducing any unnecessary compatibility
+    # constraints. The downside is that it's still slightly wrong - because of the exec transition,
+    # the returned artifacts won't correctly obey opt level/sanitizer/platform constraints in the
+    # target configuration. However, this matches the behavior in fbsource today.
+    #
+    # Once config modifiers are implemented and roll out, it should not be too hard to get the fully
+    # correct behavior
+    providers = list(ctx.attrs.actual_exec.providers)
+    providers.append(RustProcMacroMarker(label = ctx.attrs.actual_plugin))
+    return providers
+
+rust_proc_macro_alias = rule(
+    impl = _impl,
+    attrs = {
+        "actual_exec": attrs.exec_dep(),
+        "actual_plugin": attrs.plugin_dep(kind = RustProcMacroPlugin),
+        "_rust_toolchain": toolchains_common.rust(),
+    },
+)
diff --git a/buck2/prelude/rust/profile.bzl b/buck2/prelude/rust/profile.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/profile.bzl
@@ -0,0 +1,88 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":context.bzl", "CompileContext")  # @unused: Used as type
+load(":outputs.bzl", "RustcOutput")
+
+def _make_trace_providers(compile_ctx: CompileContext, a: Artifact) -> list[Provider]:
+    p = [DefaultInfo(default_output = a)]
+    make_trace_upload = compile_ctx.toolchain_info.make_trace_upload
+    if make_trace_upload != None:
+        p.append(make_trace_upload(a))
+    return p
+
+def _analyze_llvm_lines(ctx: AnalysisContext, compile_ctx: CompileContext, llvm_ir_noopt: Artifact) -> list[Provider] | None:
+    if compile_ctx.toolchain_info.llvm_lines_tool == None:
+        return None
+    llvm_lines = ctx.actions.declare_output("llvm_lines.txt", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(
+            compile_ctx.internal_tools_info.redirect_stdout,
+            llvm_lines.as_output(),
+            compile_ctx.toolchain_info.llvm_lines_tool,
+            "llvm-lines",
+            "--files",
+            llvm_ir_noopt,
+        ),
+        category = "analyze_llvm_lines",
+    )
+    return [DefaultInfo(default_output = llvm_lines)]
+
+def _llvm_time_trace(compile_ctx: CompileContext, llvm_time_trace: RustcOutput) -> list[Provider]:
+    return _make_trace_providers(compile_ctx, llvm_time_trace.compile_output.profile_output)
+
+def _self_profile(ctx: AnalysisContext, compile_ctx: CompileContext, self_profile: RustcOutput) -> list[Provider]:
+    sub_targets = {}
+
+    profdata = ctx.actions.declare_output("self_profile.mm_profdata", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(
+            compile_ctx.internal_tools_info.symlink_only_dir_entry,
+            self_profile.compile_output.profile_output,
+            profdata.as_output(),
+        ),
+        category = "find_profdata",
+    )
+    sub_targets["raw"] = [DefaultInfo(default_output = profdata)]
+
+    crox = compile_ctx.toolchain_info.measureme_crox
+    if crox != None:
+        proftrace = ctx.actions.declare_output("self_profile_trace/chrome_profiler.json", has_content_based_path = False)
+        ctx.actions.run(
+            # `crox` outputs to the cwd, so we have to do this dance
+            cmd_args(
+                compile_ctx.internal_tools_info.cd_run,
+                cmd_args(proftrace.as_output(), parent = 1),
+                cmd_args(
+                    crox,
+                    profdata,
+                    relative_to = (proftrace, 1),
+                ),
+            ),
+            category = "run_crox",
+        )
+        sub_targets["trace"] = _make_trace_providers(compile_ctx, proftrace)
+    return [DefaultInfo(sub_targets = sub_targets)]
+
+# `llvm_time_trace` and `self_profile` are `None` on toolchains without
+# `nightly_features`, where the corresponding `-Z` flags cannot be used.
+def make_profile_providers(
+    ctx: AnalysisContext, compile_ctx: CompileContext, llvm_ir_noopt: Artifact, llvm_time_trace: RustcOutput | None, self_profile: RustcOutput | None
+) -> list[Provider]:
+    sub_targets = {}
+
+    llvm_lines = _analyze_llvm_lines(ctx, compile_ctx, llvm_ir_noopt)
+    if llvm_lines != None:
+        sub_targets["llvm_lines"] = llvm_lines
+
+    if llvm_time_trace != None:
+        sub_targets["llvm_passes"] = _llvm_time_trace(compile_ctx, llvm_time_trace)
+    if self_profile != None:
+        sub_targets["rustc_stages"] = _self_profile(ctx, compile_ctx, self_profile)
+
+    return [DefaultInfo(sub_targets = sub_targets)]
diff --git a/buck2/prelude/rust/resources.bzl b/buck2/prelude/rust/resources.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/resources.bzl
@@ -0,0 +1,27 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifacts.bzl",
+    "ArtifactOutputs",  # @unused Used as a type
+    "single_artifact",
+)
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//utils:utils.bzl", "from_named_set")
+
+def rust_attr_resources(ctx: AnalysisContext) -> dict[str, ArtifactOutputs]:
+    """
+    Return the resources provided by this rule, as a map of resource name to
+    a tuple of the resource artifact and any "other" outputs exposed by it.
+    """
+    resources = {}
+
+    for name, resource in from_named_set(ctx.attrs.resources).items():
+        resources[paths.join(ctx.label.package, name)] = single_artifact(resource)
+
+    return resources
diff --git a/buck2/prelude/rust/rust-analyzer/check.bxl b/buck2/prelude/rust/rust-analyzer/check.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/rust-analyzer/check.bxl
@@ -0,0 +1,57 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//rust:outputs.bzl", "RustcExtraOutputsInfo")
+
+def _check_targets_impl(ctx: bxl.Context) -> list[bxl.EnsuredArtifact]:
+    uquery_owners = ctx.uquery().owner(ctx.cli_args.file)
+    target_universe = ctx.target_universe(uquery_owners)
+    owners = ctx.cquery().owner(ctx.cli_args.file, target_universe.target_set())
+    nodes = ctx.cquery().kind("^(rust_binary|rust_library|rust_test)$", owners)
+
+    if len(nodes) == 0:
+        return []
+
+    analysis = ctx.analysis(nodes).values()
+
+    artifacts = []
+    for a in analysis:
+        o = a.providers()[RustcExtraOutputsInfo]
+        # Temporarily disabled due to ICE reports in https://fb.workplace.com/groups/rust.analyzer/posts/1512577186779084
+        # and https://github.com/rust-lang/rust/issues/141540
+        # if ctx.cli_args.use_clippy:
+        #     artifacts.append(o.clippy_incr.compile_output.diag_json)
+        # else:
+        #     artifacts.append(o.metadata_incr.compile_output.diag_json)
+
+        if ctx.cli_args.use_clippy:
+            artifacts.append(o.clippy.compile_output.diag_json)
+        else:
+            artifacts.append(o.metadata.compile_output.diag_json)
+
+    art_output = ctx.output.ensure_multiple(artifacts)
+
+    return [artifact.abs_path() for artifact in art_output]
+
+def _run(ctx: bxl.Context) -> None:
+    diagnostic_paths = _check_targets_impl(ctx)
+
+    out = {
+        "diagnostic_paths": diagnostic_paths,
+        "project_root": ctx.root(),
+    }
+
+    ctx.output.print_json(out)
+
+check = bxl_main(
+    impl = _run,
+    cli_args = {
+        "file": cli_args.string(),
+        "use-clippy": cli_args.bool(),
+    },
+)
diff --git a/buck2/prelude/rust/rust-analyzer/provider.bzl b/buck2/prelude/rust/rust-analyzer/provider.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/rust-analyzer/provider.bzl
@@ -0,0 +1,102 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//rust:build.bzl", "crate_root", "process_env")
+load(
+    "@prelude//rust:context.bzl",
+    "CompileContext",  # @unused Used as a type
+)
+load(
+    "@prelude//rust:crate_name.bzl",
+    "CrateName",  # @unused Used as a type
+)
+load(
+    "@prelude//rust:dep_context.bzl",
+    "DepCollectionContext",  # @unused Used as a type
+)
+load("@prelude//rust:link_info.bzl", "attr_crate", "get_available_proc_macros", "resolve_rust_deps")
+
+RustAnalyzerTargetKind = enum("bin", "lib", "test")
+
+RustAnalyzerInfo = provider(
+    fields = {
+        "available_proc_macros": list[Dependency],
+        # The name of the crate for the target.
+        "crate": CrateName,
+        # The root source for the rust target (typically lib.rs, main.rs), relative to the buck target file.
+        "crate_root": str,
+        "edition": str,
+        # The processed env as produced by the buck build prelude. Some env vars like `OUT_DIR` and `CARGO_MANIFEST_DIR`
+        # will be made into absolute paths.
+        "env": dict[str, cmd_args],
+        "features": list[str],
+        # The list of rust deps needed for RustAnalyzer to function. Namely, this excludes things like
+        # exec deps used as inputs to genrules and other non-rust dependencies.
+        "rust_deps": list[Dependency],
+        "rustc_flags": cmd_args,
+        "target_kind": RustAnalyzerTargetKind,
+        # The list of recursive rust dependencies for this target, including proc macros. Useful for
+        # identifying the targets needing to be collected into Rust Analyzer's crate graph. Notably,
+        # excludes rust dependencies that are used in build tools (e.g. build scripts).
+        "transitive_target_set": set[ConfiguredTargetLabel],
+    },
+)
+
+def _compute_rust_deps(ctx: AnalysisContext, dep_ctx: DepCollectionContext) -> list[Dependency]:
+    dep_ctx = DepCollectionContext(
+        advanced_unstable_linking = False,
+        # Include doc deps here for any doctests that may be present in the target.
+        include_doc_deps = True,
+        is_proc_macro = dep_ctx.is_proc_macro,
+        # Rust Analyzer handles the sysroot separately. We omit the sysroot deps here and will
+        # instead pass a path to the sysroot as a separate config.
+        explicit_sysroot_deps = None,
+        panic_runtime = dep_ctx.panic_runtime,
+    )
+
+    first_order_deps = resolve_rust_deps(ctx, dep_ctx)
+    available_proc_macros = get_available_proc_macros(ctx)
+
+    return [dep.dep for dep in first_order_deps] + available_proc_macros.values()
+
+def _compute_transitive_target_set(ctx: AnalysisContext, first_order_deps: list[Dependency]) -> set[ConfiguredTargetLabel]:
+    transitive_targets = set([ctx.label.configured_target()])
+    for dep in first_order_deps:
+        target_sets = dep[RustAnalyzerInfo].transitive_target_set
+        for target_set in target_sets:
+            transitive_targets.add(target_set)
+    return transitive_targets
+
+def _compute_env(ctx: AnalysisContext, compile_ctx: CompileContext) -> dict[str, cmd_args]:
+    # Disable rustc_action processing, as rust-project will handle windows + any escaping necessary.
+    plain_env, path_env = process_env(compile_ctx, ctx.attrs.env, False)
+    return plain_env | path_env
+
+def _compute_rustc_flags(ctx: AnalysisContext, compile_ctx: CompileContext) -> cmd_args:
+    toolchain_info = compile_ctx.toolchain_info
+    return cmd_args(
+        toolchain_info.rustc_flags,
+        ctx.attrs.rustc_flags,
+        toolchain_info.extra_rustc_flags,
+    )
+
+def rust_analyzer_provider(ctx: AnalysisContext, compile_ctx: CompileContext, default_roots: list[str]) -> RustAnalyzerInfo:
+    toolchain_info = compile_ctx.toolchain_info
+    rust_deps = _compute_rust_deps(ctx, compile_ctx.dep_ctx)
+    return RustAnalyzerInfo(
+        available_proc_macros = get_available_proc_macros(ctx).values(),
+        crate = attr_crate(ctx),
+        crate_root = crate_root(ctx, default_roots),
+        edition = ctx.attrs.edition or toolchain_info.default_edition,
+        env = _compute_env(ctx, compile_ctx),
+        features = ctx.attrs.features,
+        rust_deps = rust_deps,
+        rustc_flags = _compute_rustc_flags(ctx, compile_ctx),
+        target_kind = RustAnalyzerTargetKind(ctx.attrs._rust_analyzer_target_kind),
+        transitive_target_set = _compute_transitive_target_set(ctx, rust_deps),
+    )
diff --git a/buck2/prelude/rust/rust-analyzer/resolve_deps.bxl b/buck2/prelude/rust/rust-analyzer/resolve_deps.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/rust-analyzer/resolve_deps.bxl
@@ -0,0 +1,514 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//linking:link_info.bzl", "LinkStrategy")
+load("@prelude//rust:build_params.bzl", "MetadataKind")
+load("@prelude//rust:link_info.bzl", "RustLinkInfo")
+load("@prelude//rust/rust-analyzer:provider.bzl", "RustAnalyzerInfo")
+load("@prelude//utils:type_defs.bzl", "is_list")
+
+TargetInfo = dict[str, typing.Any]
+
+MacroOutput = record(
+    actual = TargetLabel,
+    dylib = Artifact,
+)
+
+ExpandedAndResolved = record(
+    expanded_targets = list[TargetLabel],
+    queried_proc_macros = dict[TargetLabel, MacroOutput],
+    resolved_deps = dict[TargetLabel, TargetInfo],
+)
+
+def materialize(ctx: bxl.Context, target: bxl.ConfiguredTargetNode) -> Artifact:
+    analysis = ctx.analysis(target)
+    sources = analysis.providers()[DefaultInfo].sub_targets["sources"][DefaultInfo].default_outputs[0]
+    return sources
+
+def _get_nullable_attr(attrs, key: str) -> typing.Any:
+    nullable = getattr(attrs, key, None)
+    return nullable.value() if nullable != None else None
+
+def _process_target_config(ctx: bxl.Context, target: bxl.ConfiguredTargetNode, analysis: bxl.AnalysisResult, in_workspace: bool) -> TargetInfo:
+    target = target.unwrap_forward()
+
+    providers = analysis.providers()
+    ra_info = providers[RustAnalyzerInfo]
+
+    # convert all source paths to absolute paths
+    resolved_attrs = target.resolved_attrs_eager(ctx)
+
+    # Using srcs instead of .sources() gives the resolved artifacts if provided with a buck rule as a src label.
+    # For example, this is used in cxx powered crates internally
+    srcs = []
+    for src in resolved_attrs.srcs:
+        srcs.append(src)
+
+    # remove the configured platform from the deps. for example,
+    # `fbsource//third-party/rust:tracing (ovr_config//platform/linux:x86_64-fbcode-platform010-clang-9f23200ddcddc3cb)`
+    # becomes `fbsource//third-party/rust:tracing`.
+    deps = [dep.label.raw_target() for dep in ra_info.rust_deps]
+
+    # Grab only the values that the the gen-rules are being mapped to.
+    mapped_srcs = {}
+    for key, v in resolved_attrs.mapped_srcs.items():
+        mapped_srcs[v] = key
+
+    # remove the configured platform from named deps.
+    if is_list(resolved_attrs.named_deps):
+        named_deps_names = providers[DefaultInfo].sub_targets["named_deps"][DefaultInfo].default_outputs[0]
+        named_deps = [named_deps_names]
+        for _alias, dep in resolved_attrs.named_deps:
+            named_deps.append(dep.label.raw_target())
+    else:
+        named_deps = {}
+        for dep, alias in resolved_attrs.named_deps.items():
+            named_deps[dep] = alias.label.raw_target()
+
+    # remove the configured platform for tests
+    tests = []
+    for test in resolved_attrs.tests:
+        tests.append(test.raw_target())
+
+    env = {k: cmd_args(v, delimiter = "") for k, v in ra_info.env.items()}
+
+    # copy over the absolute paths and raw targets into the output
+    attrs = target.attrs_eager()
+    return {
+        "crate": ra_info.crate.simple,
+        "crate_dynamic": ra_info.crate.dynamic,
+        "crate_root": ra_info.crate_root,
+        "deps": deps,
+        "edition": ra_info.edition,
+        "env": env,
+        "features": ra_info.features,
+        "in_workspace": in_workspace,
+        "kind": ra_info.target_kind.value,
+        "label": target.label.raw_target(),
+        "labels": resolved_attrs.labels if hasattr(resolved_attrs, "labels") else [],
+        "mapped_srcs": mapped_srcs,
+        "name": resolved_attrs.name,
+        "named_deps": named_deps,
+        "proc_macro": _get_nullable_attr(attrs, "proc_macro"),
+        "project_relative_buildfile": ctx.fs.project_rel_path(target.buildfile_path),
+        "rustc_flags": ra_info.rustc_flags,
+        "source_folder": materialize(ctx, target),  # Always generate the source folder. Let rust-project resolve whether or not to use it
+        "srcs": srcs,
+        "tests": tests,
+    }
+
+def _select_assume_default(value):
+    """Unwrap select() values, assuming the DEFAULT value is always used."""
+    if isinstance(value, bxl.SelectConcat):
+        items = []
+        for raw_item in value.select_iter():
+            if isinstance(raw_item, list):
+                items.extend(raw_item)
+            else:
+                unwrapped = _select_assume_default(raw_item)
+                if isinstance(unwrapped, list):
+                    items.extend(unwrapped)
+
+        return items
+
+    if isinstance(value, bxl.SelectDict):
+        return value.get_select_entry("DEFAULT")
+
+    return value
+
+def _get_attr_no_select(target: bxl.UnconfiguredTargetNode, attr: str) -> typing.Any:
+    return _select_assume_default(target.get_attr(attr))
+
+def gather_unconfigured_deps(ctx: bxl.Context, targets: list[TargetLabel]) -> dict[TargetLabel, TargetInfo]:
+    """Make a best-effort attempt to gather target and dependency information for
+    the targets given.
+
+    This intended for targets where we cannot use the configured target nodes,
+    typically because they have compatible_with constraints that do not match the
+    current machine.
+
+    """
+    out = {}
+
+    unconfigured_targets = ctx.unconfigured_targets(targets)
+
+    for target in unconfigured_targets:
+        deps = []
+        for dep in _get_attr_no_select(target, "deps") or []:
+            deps.append(dep.raw_target())
+
+        raw_env = _get_attr_no_select(target, "env") or {}
+        env = {k: cmd_args(v, delimiter = "") for k, v in raw_env.items()}
+
+        srcs = [src.short_path for src in _get_attr_no_select(target, "srcs") or []]
+
+        mapped_srcs = {}
+        raw_mapped_srcs = _get_attr_no_select(target, "mapped_srcs") or {}
+        for src, dst in raw_mapped_srcs.items():
+            # A mapped_srcs key is either a target label (e.g. a filegroup or
+            # genrule), which has `raw_target`, or a plain source file, which the
+            # unconfigured node surfaces as an Artifact addressed by `short_path`.
+            if hasattr(src, "raw_target"):
+                mapped_srcs[src.raw_target()] = dst
+            else:
+                mapped_srcs[src.short_path] = dst
+
+        abs_buildfile_path = ctx.root() + "/" + target.buildfile_path.cell + "/" + target.buildfile_path.path
+        source_folder = abs_buildfile_path.removesuffix("/TARGETS").removesuffix("/BUCK")
+
+        crate_root = _get_attr_no_select(target, "crate_root")
+        if not crate_root:
+            for src in srcs:
+                if src.endswith("/lib.rs") or src.endswith("/main.rs"):
+                    crate_root = src
+                    break
+
+        if not crate_root:
+            continue
+
+        tests = []
+        for test in _get_attr_no_select(target, "tests") or []:
+            tests.append(test.raw_target())
+
+        info = {
+            "crate": _get_attr_no_select(target, "crate"),
+            "crate_dynamic": _get_attr_no_select(target, "crate_dynamic"),
+            "crate_root": crate_root,
+            "deps": deps,
+            "edition": _get_attr_no_select(target, "edition"),
+            "env": env,
+            "features": _get_attr_no_select(target, "features"),
+            "in_workspace": False,
+            "kind": _get_attr_no_select(target, "_rust_analyzer_target_kind"),
+            "label": target.label,
+            "labels": _get_attr_no_select(target, "labels") or [],
+            "mapped_srcs": mapped_srcs,
+            "name": target.get_attr("name"),
+            "named_deps": {},
+            "proc_macro": _get_attr_no_select(target, "proc_macro"),
+            "project_relative_buildfile": ctx.fs.project_rel_path(target.buildfile_path),
+            "rustc_flags": _get_attr_no_select(target, "rustc_flags"),
+            "source_folder": source_folder,
+            "srcs": srcs,
+            "tests": tests,
+        }
+
+        out[target.label] = info
+
+    return out
+
+def gather_deps(ctx: bxl.Context, target_analysis: dict[Label, bxl.AnalysisResult], workspaces: list[TargetLabel]) -> dict[TargetLabel, TargetInfo]:
+    targets = set()
+    for _target, analysis in target_analysis.items():
+        info = analysis.providers().get(RustAnalyzerInfo)
+        if info:
+            for target_set in info.transitive_target_set:
+                targets.add(target_set)
+
+    # TODO(romanp) support set as target_universe arg
+    outputs = ctx.target_universe(list(targets)).target_set()
+    out = {}
+
+    # Eagerly analyze targets
+    analysis = ctx.analysis(outputs)
+
+    for target in outputs:
+        attrs = target.attrs_lazy()
+        label = target.label.with_sub_target()
+
+        in_workspace = label in target_analysis
+        candidate_workspaces = attrs.get("_workspaces")
+        if candidate_workspaces:
+            for candidate_workspace in candidate_workspaces.value():
+                if candidate_workspace.raw_target() in workspaces:
+                    in_workspace = True
+                    break
+
+        target_info = _process_target_config(
+            ctx = ctx,
+            target = target,
+            analysis = analysis[target.label.with_sub_target()],
+            in_workspace = in_workspace,
+        )
+
+        out[target.label.raw_target()] = target_info
+
+    return out
+
+def expand_proc_macros(ctx: bxl.Context, target_analysis: dict[Label, bxl.AnalysisResult]) -> dict[TargetLabel, MacroOutput]:
+    macros = set()
+    for _target, analysis in target_analysis.items():
+        info = analysis.providers().get(RustAnalyzerInfo)
+        if info:
+            macros.update([d.label for d in info.available_proc_macros])
+
+    proc_macro_analysis = ctx.analysis(list(macros))
+    out = {}
+    for target, analysis in proc_macro_analysis.items():
+        rlib = analysis.providers()[RustLinkInfo].strategies[LinkStrategy("shared")].outputs[MetadataKind("link")]
+        label = target.raw_target()
+        out[label] = MacroOutput(
+            actual = label,
+            dylib = rlib,
+        )
+    return out
+
+# Returns a list of all the expanded targets including any workspaces, followed by just the workspaces
+def expand_targets(ctx: bxl.Context, targets: list[TargetLabel], exclude_workspaces: bool) -> (dict[Label, bxl.AnalysisResult], list[TargetLabel]):
+    target_universe = ctx.target_universe(targets).target_set()
+    # Pick up any rule that sets RustAnalyzerTargetKind and so exposes RustAnalyzerInfo, regardless of its rule name.
+    # Custom rules that wrap/override our rust_* builtins but don't use the same names will be picked up here.
+    attr_target_list = ctx.cquery().attrregexfilter("_rust_analyzer_target_kind", "^(bin|lib|test)$", target_universe)
+
+    # Aliases don't set RustAnalyzerTargetKind, so we must fallback to grabbing all of them
+    alias_target_list = ctx.cquery().kind("^(alias|_?transitioned)$", target_universe)
+
+    # Allow targets to opt-in to being treated as rust-analyzer-compatible.
+    # This is used for cross-compilation targets that apply Buck transitions to Rust rules.
+    labeled_target_list = ctx.cquery().attrfilter("labels", "rust_analyzer_target", target_universe)
+    expanded_targets = {t.label.raw_target(): t for t in attr_target_list + alias_target_list + labeled_target_list}
+
+    # Map of potential workspaces to a list of the targets that name these as potential workspaces
+    possible_workspaces = {}
+    if not exclude_workspaces:
+        for label, t in expanded_targets.items():
+            workspaces = t.attrs_lazy().get("_workspaces")
+            if workspaces:
+                for workspace in workspaces.value():
+                    if not ctx.target_exists(str(workspace.raw_target())):
+                        continue
+
+                    possible_workspaces.setdefault(workspace.raw_target(), []).append(label)
+
+    workspace_analysis = ctx.analysis(ctx.target_universe(possible_workspaces.keys()).target_set())
+
+    active_workspaces = {}
+    for workspace_label, analysis in workspace_analysis.items():
+        workspace = workspace_label.raw_target()
+        candidate_deps = possible_workspaces[workspace]
+        workspace_info = analysis.providers().get(RustAnalyzerInfo)
+        if workspace_info:
+            workspace_deps = {t.raw_target(): () for t in workspace_info.transitive_target_set}
+        else:
+            workspace_deps = {}
+
+        for d in candidate_deps:
+            if d in workspace_deps:
+                active_workspaces[workspace] = ()
+
+                # Remove the target from the expanded targets. This is correct because we know
+                # that the target will reappear later as a dep of the workspace. To understand why
+                # it's necessary, consider the case where the target is a proc macro: Later doing
+                # cquery deps(proc_macro + workspace) will result in the proc macro appearing twice,
+                # once in its exec configuration and once in its target configuration
+                # FIXME: Add a test for this. It's currently a bit hard to test because proc macros
+                # in the prelude are a bit hard in general
+                expanded_targets.pop(d, None)
+    target_set = ctx.target_universe(expanded_targets.keys() + active_workspaces.keys()).target_set()
+    target_analysis = ctx.analysis(target_set)
+    return target_analysis, sorted(possible_workspaces.keys())
+
+def resolve_targets_impl(ctx: bxl.Context) -> None:
+    # equivalent of `flat_map`ing
+    targets = [target for sublist in ctx.cli_args.targets for target in sublist]
+    actions = ctx.bxl_actions().actions
+
+    target_analysis, workspaces = expand_targets(ctx, targets, ctx.cli_args.exclude_workspaces)
+    queried_proc_macros = expand_proc_macros(ctx, target_analysis)
+    resolved_deps = gather_deps(ctx, target_analysis, workspaces)
+
+    expanded_targets = sorted([t.raw_target() for t in target_analysis.keys()])
+    if not expanded_targets:
+        # ctx.analysis() drops targets that are incompatible with the current buck
+        # configuration (see the `skip_incompatible` keyword argument).
+        #
+        # If we have no expanded targets at all, try to find sufficient metadata about
+        # the requested targets using unconfigured buck targets.
+        expanded_targets = targets
+        resolved_deps = gather_unconfigured_deps(ctx, targets)
+
+    artifact = actions.declare_output("resolve_targets.json", has_content_based_path = False)
+    artifacts = actions.write_json(
+        artifact,
+        ExpandedAndResolved(
+            expanded_targets = expanded_targets,
+            queried_proc_macros = queried_proc_macros,
+            resolved_deps = resolved_deps,
+        ),
+        with_inputs = True,
+        absolute = True,
+        pretty = ctx.cli_args.pretty,
+    )
+    ctx.output.ensure_multiple(artifacts)
+    ctx.output.print(ctx.output.ensure(artifact).abs_path())
+
+def _short_version(version: str) -> str:
+    """Return the short version string used in target names.
+
+    Uses the leftmost non-zero semver component as the compatibility boundary:
+    - >=1.0.0: major only (e.g. "3")
+    - 0.y.z where y >= 1: major.minor (e.g. "0.2")
+    - 0.0.z: full version (e.g. "0.0.3")
+    """
+    parts = version.split(".")
+    if len(parts) < 3:
+        return version
+    major, minor, _patch = parts[0], parts[1], parts[2]
+    if major != "0":
+        return major
+    if minor != "0":
+        return "{}.{}".format(major, minor)
+    return version
+
+def _resolve_vendor_rust_libraries(ctx: bxl.Context, targets: bxl.UnconfiguredTargetSet) -> bxl.UnconfiguredTargetSet:
+    """Rust files in third-party/rust/vendor/ are owned by rust_filegroup targets,
+    but a rust_filegroup is just a set of files, without any information about
+    the crate.
+
+    For example:
+
+    file: third-party/rust/vendor/nix-0.30.1/src/fcntl.rs
+    owner: fbsource//third-party/rust/vendor/nix-0.30.1:srcs
+    library: fbsource//third-party/rust/vendor/nix:0.30
+
+    Look up the relevant rust_library by taking advantage of the fact that
+    target names follow a predictable pattern. Target names use the short
+    version: major-only for >=1.0.0, major.minor for 0.y.z, full semver
+    for 0.0.z.
+
+    """
+    filegroups = ctx.uquery().kind("^rust_filegroup$", targets)
+
+    rust_libraries = utarget_set()
+    for fg in filegroups:
+        # E.g. third-party/rust/vendor/nix-0.30.1
+        package_path = fg.label.package
+
+        if not package_path.startswith("third-party/rust/vendor/"):
+            continue
+        crate_version = package_path.removeprefix("third-party/rust/vendor/")
+
+        # "nix-0.30.1" -> ("nix", "0.30.1")
+        parts = crate_version.rsplit("-", 1)
+        if len(parts) != 2:
+            continue
+        crate_name, version = parts
+
+        # E.g. fbsource//third-party/rust/vendor/nix:0.30
+        short_ver = _short_version(version)
+        lib_target_str = "{}//third-party/rust/vendor/{}:{}".format(fg.label.cell, crate_name, short_ver)
+
+        # Since we're using string conventions to find the library, defensively
+        # check that the target actually exists.
+        if ctx.target_exists(lib_target_str):
+            rust_libraries += ctx.unconfigured_targets([lib_target_str])
+
+    return (targets - filegroups) + rust_libraries
+
+def resolve_owning_buildfile_impl(ctx: bxl.Context) -> None:
+    # depending on the input, determine the initial set of targets
+
+    if ctx.cli_args.files:
+        # Find targets that own these files and are relevant to rust.
+        targets = ctx.uquery().owner(ctx.cli_args.files)
+        attr_targets = ctx.uquery().attrregexfilter("_rust_analyzer_target_kind", "^(bin|lib|test)$", targets)
+        filegroup_targets = ctx.uquery().kind("^rust_filegroup$", targets)
+        targets = attr_targets + filegroup_targets
+
+        # Convert rust_filegroup targets to rust_library targets.
+        targets = _resolve_vendor_rust_libraries(ctx, targets)
+    elif ctx.cli_args.buildfiles:
+        targets = [ctx.uquery().targets_in_buildfile(buildfile) for buildfile in ctx.cli_args.buildfiles]
+
+        # equivalent of `flat_map`ing
+        targets = [target for sublist in targets for target in sublist]
+        attr_targets = ctx.uquery().attrregexfilter("_rust_analyzer_target_kind", "^(bin|lib|test)$", targets)
+        transitioned_targets = ctx.uquery().kind("^_?transitioned$", targets)
+        labeled_targets = ctx.uquery().attrfilter("labels", "rust_analyzer_target", targets)
+        targets = attr_targets + transitioned_targets + labeled_targets
+    elif ctx.cli_args.targets:
+        # equivalent of `flat_map`ing
+        targets = [target for sublist in ctx.cli_args.targets for target in sublist]
+        targets = ctx.unconfigured_targets(targets)
+    else:
+        fail("Neither `--files`, `--targets`, nor `--buildfiles` were specified; this is a bug")
+
+    # group targets by their buildfile
+    targets_by_buildfile = {}
+    for target in targets:
+        buildfile_path = ctx.fs.abs_path_unsafe(target.buildfile_path)
+
+        if buildfile_path not in targets_by_buildfile:
+            targets_by_buildfile[buildfile_path] = utarget_set()
+        targets_by_buildfile[buildfile_path] += utarget_set([target])
+
+    # collect extra targets from each buildfile
+    extra_targets_by_buildfile = {}
+    for buildfile_path in targets_by_buildfile:
+        if "third-party/rust/vendor/" in buildfile_path:
+            continue
+
+        all_buildfile_targets = ctx.uquery().targets_in_buildfile(buildfile_path)
+        extra_targets = ctx.uquery().attrregexfilter("_rust_analyzer_target_kind", "^(bin|lib|test)$", all_buildfile_targets)
+        extra_targets += ctx.uquery().kind("^_?transitioned$", all_buildfile_targets)
+        extra_targets += ctx.uquery().attrfilter("labels", "rust_analyzer_target", all_buildfile_targets)
+
+        # Exclude targets with the rustc_do_no_check label from the extra targets. This
+        # label is used for foo@symbol targets (generated by rust_linkable_symbols), which
+        # are slow to build and never a direct dependencies of rust targets.
+        extra_targets -= ctx.uquery().attrfilter(
+            "labels",
+            "rustc_do_not_check",
+            extra_targets,
+        )
+
+        # explicitly included targets aren't "extra"
+        extra_targets -= targets_by_buildfile[buildfile_path]
+
+        extra_targets_by_buildfile[buildfile_path] = extra_targets
+
+    # add as many extra targets as we can according to max_extra_targets.
+    # note that which extra targets we add is arbitrary since it depends on the
+    # iteration order of the dict and the target_set.
+    remaining_extra_targets = ctx.cli_args.max_extra_targets
+    for buildfile_path, extra_targets in extra_targets_by_buildfile.items():
+        extra_targets = utarget_set(list(extra_targets)[:remaining_extra_targets])
+        targets_by_buildfile[buildfile_path] += extra_targets
+
+        remaining_extra_targets -= len(extra_targets)
+        if remaining_extra_targets <= 0:
+            break
+
+    # output just the target labels by buildfile
+    out = {}
+    for buildfile_path, targets in targets_by_buildfile.items():
+        out[buildfile_path] = [target.label for target in targets]
+    ctx.output.print_json(out)
+
+# Writes a json file as an artifact and returns the absolute path to that artifact to stdout.
+resolve_targets = bxl_main(
+    impl = resolve_targets_impl,
+    cli_args = {
+        "exclude_workspaces": cli_args.bool(default = False),
+        "pretty": cli_args.bool(default = False),
+        "targets": cli_args.list(cli_args.target_expr()),
+    },
+)
+
+resolve_owning_buildfile = bxl_main(
+    impl = resolve_owning_buildfile_impl,
+    cli_args = {
+        # while buildfiles, files, and targets can all be passed, only files will be used.
+        # this file is driven primarily by rust-project's needs and is a private implementation
+        # detail.
+        "buildfiles": cli_args.option(cli_args.list(cli_args.string())),
+        "files": cli_args.option(cli_args.list(cli_args.string())),
+        "max_extra_targets": cli_args.int(),
+        "targets": cli_args.option(cli_args.list(cli_args.target_expr())),
+    },
+)
diff --git a/buck2/prelude/rust/rust_binary.bzl b/buck2/prelude/rust/rust_binary.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/rust_binary.bzl
@@ -0,0 +1,861 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "project_artifacts",
+)
+load("@prelude//:content_based_dist.bzl", "make_content_based_dist")
+load(
+    "@prelude//:resources.bzl",
+    "create_relocatable_resources_info",
+    "create_resource_db",
+    "gather_resources",
+)
+load("@prelude//cxx:cxx_bolt.bzl", "cxx_use_bolt")
+load("@prelude//cxx:cxx_executable.bzl", "get_cxx_post_link_suffix")
+load(
+    "@prelude//cxx:cxx_library_utility.bzl",
+    "cxx_attr_deps",
+)
+load("@prelude//cxx:cxx_link_utility.bzl", "executable_shared_lib_arguments")
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "PicBehavior",
+    "RuntimeDependencyHandling",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_attrs_get_allow_cache_upload")
+load(
+    "@prelude//cxx:link_groups.bzl",
+    "LINK_GROUP_MAPPINGS_FILENAME_SUFFIX",
+    "LINK_GROUP_MAPPINGS_SUB_TARGET",
+    "LINK_GROUP_MAP_DATABASE_SUB_TARGET",
+    "LinkGroupContext",
+    "build_shared_libs_for_symlink_tree",
+    "get_link_group_map_json",
+)
+load("@prelude//cxx:linker.bzl", "DUMPBIN_SUB_TARGET", "PDB_SUB_TARGET", "get_dumpbin_providers", "get_pdb_providers")
+load("@prelude//cxx:transformation_spec.bzl", "build_transformation_spec_context")
+load(
+    "@prelude//dist:dist_info.bzl",
+    "DistInfo",
+)
+load("@prelude//linking:add_elf_sections.bzl", "get_elf_sections")
+load("@prelude//linking:generated_build_info.bzl", "compile_generated_build_info", "generate_build_info")
+load(
+    "@prelude//linking:link_info.bzl",
+    "LibOutputStyle",
+    "LinkStrategy",
+    "get_lib_output_style",
+    "process_link_strategy_for_pic_behavior",
+    "unpack_link_args",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "create_linkable_graph",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "merge_shared_libraries",
+    "traverse_shared_library_info",
+)
+load("@prelude//linking:stamp_build_info.bzl", "cxx_stamp_build_info", "stamp_build_info")
+load("@prelude//os_lookup:defs.bzl", "OsLookup")
+load("@prelude//rust/rust-analyzer:provider.bzl", "rust_analyzer_provider")
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+load(
+    "@prelude//tests:re_utils.bzl",
+    "get_re_executors_from_props",
+)
+load(
+    "@prelude//utils:build_graph_pattern.bzl",
+    "new_build_graph_info",
+)
+load("@prelude//utils:utils.bzl", "flatten_dict")
+load(
+    ":build.bzl",
+    "generate_rustdoc",
+    "get_inherited_link_args",
+    "rust_compile",
+    "rust_compile_invalidation_inputs",
+    "rust_link_binary",
+)
+load(
+    ":build_params.bzl",
+    "BuildParams",  # @unused Used as a type
+    "Emit",
+    "LinkageLang",
+    "ProfileMode",  # @unused Used as a type
+    "RuleType",
+    "build_params",
+)
+load(
+    ":context.bzl",
+    "CompileContext",
+    "compile_context",
+    "output_filename",
+)
+load(
+    ":link_info.bzl",
+    "DEFAULT_STATIC_LINK_STRATEGY",
+    "attr_simple_crate_for_filenames",
+    "inherited_external_debug_info",
+    "inherited_linkable_graphs",
+    "inherited_rust_cxx_link_group_info",
+    "inherited_shared_libs",
+)
+load(":named_deps.bzl", "write_named_deps_names")
+load(":outputs.bzl", "RustcExtraOutputsInfo", "output_as_diag_subtargets")
+load(":profile.bzl", "make_profile_providers")
+load(":resources.bzl", "rust_attr_resources")
+
+def _get_runtime_dependency_handling(ctx: AnalysisContext, compile_ctx: CompileContext) -> RuntimeDependencyHandling:
+    """Read runtime_dependency_handling from attribute, falling back to CXX toolchain default."""
+    if ctx.attrs.runtime_dependency_handling:
+        return RuntimeDependencyHandling(ctx.attrs.runtime_dependency_handling)
+
+    # Toolchains that don't support shared libraries (e.g. WASM, bare-metal)
+    # cannot create symlink trees, so skip runtime dependency handling.
+    if not compile_ctx.cxx_toolchain_info.linker_info.supports_shared_libraries:
+        return RuntimeDependencyHandling("no_symlink")
+    return compile_ctx.cxx_toolchain_info.runtime_dependency_handling
+
+def _strategy_params(ctx: AnalysisContext, compile_ctx: CompileContext) -> dict[LinkStrategy, BuildParams]:
+    target_os_type = ctx.attrs._target_os_type[OsLookup]
+    linker_type = compile_ctx.cxx_toolchain_info.linker_info.type
+
+    params = {}
+    for link_strategy in LinkStrategy:
+        params[link_strategy] = build_params(
+            rule = RuleType("binary"),
+            proc_macro = False,
+            link_strategy = link_strategy,
+            lib_output_style = None,
+            lang = LinkageLang("rust"),
+            linker_type = linker_type,
+            target_os_type = target_os_type,
+        )
+    return params
+
+def _create_content_based_dist(
+    ctx: AnalysisContext,
+    name: str,
+    exe: Artifact,
+    relocatable_resources_json: Artifact | None,
+    relocatable_resources_contents: Artifact | None,
+    shlib_tree: Artifact | list | None,
+) -> (Artifact, Artifact):
+    """
+    Build the content-based `assembled_dir` bundle for a `rust_binary` that opts
+    into `has_content_based_path` and has adjacent files: the relocatable resource
+    DB (copied) + the content-based `__resources` dir (symlinked), and the shlib
+    symlink-tree (symlinked). The exe and the copy/symlink contract are handled by
+    `make_content_based_dist`. Returns `(bundle_dir, projected exe)`.
+    """
+    exe_rel = exe.short_path
+    copies = {}
+    symlinks = {}
+
+    # Resources: reuse the relocatable DB + `__<name>__resources` symlink dir
+    # from `create_relocatable_resources_info` -- which is CONTENT-BASED for this
+    # binary (rust_binary threads `has_content_based_path` through). Copy the DB
+    # (its bytes are captured in the bundle); symlink the content-based resource
+    # dir. The dir being content-based is load-bearing: its path is immutable and
+    # re-hashes when a content-based resource changes, so the bundle's symlink to
+    # it is trample-safe -- unlike the config-based default, which would be
+    # rewritten in place under a running bundle.
+    if relocatable_resources_json != None:
+        copies[exe_rel + ".resources.json"] = relocatable_resources_json
+        symlinks[relocatable_resources_contents.short_path] = relocatable_resources_contents
+
+    # Shared libraries: symlink the whole prebuilt shlib symlink-tree into the
+    # bundle at the `$ORIGIN/<tree>`-relative offset the exe's RPATH already
+    # encodes (`get_rpath_origin` => `$ORIGIN` for the gnu linker). Symlinking
+    # the tree the linker already targets -- rather than reconstructing it
+    # per-soname -- reuses the tree tool's exact layout, so binaries with
+    # computed (non-string) sonames are handled too, and the loader follows the
+    # symlinked dir like any RPATH entry.
+    if isinstance(shlib_tree, list) and shlib_tree:
+        # Windows produces a list of per-DLL symlink artifacts (no `$ORIGIN`
+        # RPATH); co-locating them here is unimplemented. Fail loudly rather
+        # than ship a bundle that silently can't find its DLLs at runtime.
+        fail(
+            "content-based `assembled_dir` bundle does not support a Windows shared-library tree; a content-based rust_binary with shared libraries is not supported on Windows yet"
+        )
+    if isinstance(shlib_tree, Artifact):
+        symlinks[shlib_tree.short_path] = shlib_tree
+
+    return make_content_based_dist(ctx, name, exe, copies = copies, symlinks = symlinks)
+
+def _rust_binary_common(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    default_roots: list[str],
+    extra_flags: list[str],
+    allow_cache_upload: bool,
+) -> (list[Provider], cmd_args):
+    toolchain_info = compile_ctx.toolchain_info
+
+    simple_crate = attr_simple_crate_for_filenames(ctx)
+
+    link_strategy = LinkStrategy(ctx.attrs.link_style) if ctx.attrs.link_style else DEFAULT_STATIC_LINK_STRATEGY
+    link_strategy = process_link_strategy_for_pic_behavior(link_strategy, compile_ctx.cxx_toolchain_info.pic_behavior)
+
+    cxx_deps = cxx_attr_deps(ctx)
+    generated_build_info_enabled = getattr(ctx.attrs, "_generated_build_info_enabled", False)
+    generated_build_info_args = ctx.attrs._generated_build_info_args if generated_build_info_enabled else []
+
+    generated_build_info_link_args = []
+    generated_build_info_link_objects = []
+
+    resources = flatten_dict(
+        gather_resources(
+            label = ctx.label,
+            resources = rust_attr_resources(ctx),
+            deps = cxx_deps,
+        ).values()
+    )
+
+    extra_flags = toolchain_info.rustc_binary_flags + (extra_flags or [])
+
+    strategy_param = _strategy_params(ctx, compile_ctx)
+
+    params = strategy_param[link_strategy]
+    name = output_filename(compile_ctx, simple_crate, Emit("link"), params)
+
+    # Under advanced_unstable_linking, the binary is compiled via
+    # `Emit("rlib")` and linked through cxx below (`rust_link_binary`),
+    # mirroring how rust_library produces dylibs via `rust_link_shared`.
+    links_via_cxx = toolchain_info.advanced_unstable_linking
+    bin_emit = Emit("rlib") if links_via_cxx else Emit("link")
+
+    use_bolt = cxx_use_bolt(ctx)
+    if use_bolt and not links_via_cxx:
+        fail(
+            "`bolt_profile` is set, but BOLT runs as part of the cxx link. "
+            + "This target links via rustc; BOLT requires `advanced_unstable_linking` on the Rust toolchain."
+        )
+    elf_sections = get_elf_sections(ctx)
+    if elf_sections and not links_via_cxx:
+        fail(
+            "`elf_sections` is set, but the sections are added as part of the cxx link. "
+            + "This target links via rustc; `elf_sections` requires `advanced_unstable_linking` on the Rust toolchain."
+        )
+    enable_late_build_info_stamping = cxx_stamp_build_info(ctx)
+    content_based_output = getattr(ctx.attrs, "has_content_based_path", False)
+    unstamped_name = None
+    if enable_late_build_info_stamping:
+        allow_cache_upload = True
+        unstamped_name = output_filename(compile_ctx, simple_crate, Emit("link"), params, "-unstamped")
+
+    # The exe output is declared below, once we know whether it ships in a
+    # content-based `copied_dir` bundle (see the `will_bundle` decision after
+    # `shared_libs` is computed).
+
+    build_graph_info = new_build_graph_info(ctx, cxx_deps)
+    transformation_spec_context = build_transformation_spec_context(ctx, build_graph_info)
+
+    rust_cxx_link_group_info = inherited_rust_cxx_link_group_info(
+        ctx,
+        compile_ctx.dep_ctx,
+        link_strategy = link_strategy,
+        transformation_spec_context = transformation_spec_context,
+    )
+
+    # Link groups repartition the dependency graph's code — including the
+    # Rust code — into group libraries, filtering the main link accordingly.
+    # Without advanced_unstable_linking, rustc links the full dep rlib set no
+    # matter what, so the grouped code would be linked twice; this cannot be
+    # made correct.
+    if rust_cxx_link_group_info != None and not toolchain_info.advanced_unstable_linking:
+        fail("link groups on Rust binaries require `advanced_unstable_linking`")
+    if rust_cxx_link_group_info != None:
+        link_group_mappings = rust_cxx_link_group_info.link_group_info.mappings
+        link_group_libs = rust_cxx_link_group_info.link_group_libs
+        link_group_preferred_linkage = rust_cxx_link_group_info.link_group_preferred_linkage
+        labels_to_links_map = rust_cxx_link_group_info.labels_to_links_map
+        targets_consumed_by_link_groups = rust_cxx_link_group_info.targets_consumed_by_link_groups
+        filtered_targets = rust_cxx_link_group_info.filtered_targets
+    else:
+        link_group_mappings = {}
+        link_group_libs = {}
+        link_group_preferred_linkage = {}
+        labels_to_links_map = {}
+        targets_consumed_by_link_groups = {}
+        filtered_targets = []
+
+    native_link_args = get_inherited_link_args(
+        ctx,
+        compile_ctx,
+        params.dep_link_strategy,
+        rust_cxx_link_group_info,
+        transformation_spec_context,
+    )
+
+    runtime_dep_handling = _get_runtime_dependency_handling(ctx, compile_ctx)
+
+    shlib_deps = []
+    if link_strategy == LinkStrategy("shared") or rust_cxx_link_group_info != None:
+        shlib_deps = inherited_shared_libs(ctx, compile_ctx.dep_ctx)
+    elif runtime_dep_handling == RuntimeDependencyHandling("symlink"):
+        # Include all transitive runtime shared library deps in a symlink tree.
+        # Only collect libs that would actually be built as shared libraries
+        # given the current link strategy, matching cxx_binary behavior.
+        linkable_graphs_tset = inherited_linkable_graphs(ctx, compile_ctx.dep_ctx)
+        all_graphs = []
+        for graphs in linkable_graphs_tset.traverse():
+            all_graphs.extend(graphs)
+        linkable_graph = create_linkable_graph(ctx, deps = all_graphs)
+        for linkable_node in linkable_graph.nodes.traverse():
+            if linkable_node.linkable == None:
+                continue
+            preferred_linkage = linkable_node.linkable.preferred_linkage
+            output_style = get_lib_output_style(link_strategy, preferred_linkage, PicBehavior("supported"))
+            if output_style == LibOutputStyle("shared_lib") and not linkable_node.linkable.stub:
+                shlib_deps.append(merge_shared_libraries(ctx.actions, node = linkable_node.linkable.shared_libs))
+
+    shlib_info = merge_shared_libraries(ctx.actions, deps = shlib_deps)
+
+    link_group_ctx = LinkGroupContext(
+        link_group_mappings = link_group_mappings,
+        link_group_libs = link_group_libs,
+        link_group_preferred_linkage = link_group_preferred_linkage,
+        labels_to_links_map = labels_to_links_map,
+        targets_consumed_by_link_groups = targets_consumed_by_link_groups,
+    )
+
+    # Gather and setup symlink tree of transitive shared library deps.
+    shared_libs = build_shared_libs_for_symlink_tree(
+        use_link_groups = rust_cxx_link_group_info != None,
+        link_group_ctx = link_group_ctx,
+        link_strategy = link_strategy,
+        shared_libraries = traverse_shared_library_info(shlib_info, transformation_provider = transformation_spec_context),
+        extra_shared_libraries = [],
+    )
+
+    # Decide whether the content-based output ships as a bare exe or a
+    # `assembled_dir` bundle (see `_create_content_based_dist`). A binary with
+    # adjacent files -- resources and/or a shared-lib tree -- goes in a bundle,
+    # and its exe must stay config-based: a content-based exe sits at a deep
+    # content-hash path, so the linker bakes a long buck-out-relative `$ORIGIN`
+    # RPATH that no longer points at the shlib tree once the exe is copied into
+    # the bundle. A config-based exe is a direct sibling of the tree, yielding a
+    # clean `$ORIGIN/<tree>` RPATH that survives co-location; the bundle dir
+    # provides the content-addressing instead.
+    # `needs_shlib_tree` = a shlib symlink-tree (and a baked `$ORIGIN/<tree>`
+    # RPATH) was produced for this exe. That is exactly when `shared_libs` is
+    # non-empty: `link_strategy == shared`, a link-group binary (auto link groups
+    # are on by DEFAULT, so `link_strategy == shared` alone is NOT sufficient --
+    # a static_pic link-group binary still gets a tree + RPATH), or
+    # `runtime_dependency_handling = "symlink"` dlopen deps. In every such case
+    # the exe carries an `$ORIGIN/<tree>` RPATH, so a content-based (deep-hash)
+    # exe would bake a dangling RPATH; bundle, and keep the exe config-based, so
+    # the RPATH resolves against the co-located tree. A binary with NO shared
+    # libs (e.g. the fully-static node) has no tree/RPATH and stays a bare
+    # content-based exe.
+    needs_shlib_tree = bool(shared_libs)
+    will_bundle = content_based_output and (bool(resources) or needs_shlib_tree)
+
+    # The bare exe stays content-based -- so it is trample-safe when consumed by
+    # path or as another target's resource (e.g. clio's `:web-server` embeds the
+    # node) -- EXCEPT when it needs a shlib tree at startup. A content-based exe
+    # sits at a deep content-hash path, so the linker bakes a long
+    # buck-out-relative `$ORIGIN` RPATH that no longer points at the tree once
+    # the exe is copied into the bundle. Dynamic binaries therefore use a
+    # config-based exe (a direct sibling of the tree => clean `$ORIGIN/<tree>`
+    # RPATH that survives co-location) and get content-addressing from the
+    # bundle dir instead. Static binaries reuse their content-based exe in the
+    # bundle directly (no RPATH to break).
+    exe_content_based = content_based_output and not needs_shlib_tree and not use_bolt
+    if links_via_cxx:
+        # cxx performs the terminal link (see `rust_link_binary` below) and its
+        # own post-link processing, so the output has to be named the way those
+        # stages expect; we must not stamp again here.
+        predeclared_output = ctx.actions.declare_output(
+            output_filename(compile_ctx, simple_crate, Emit("link"), params, get_cxx_post_link_suffix(ctx)),
+            has_content_based_path = exe_content_based,
+        )
+
+        # final_output is whatever cxx returns, set after the link below.
+        final_output = None
+        # rpath and symlink-tree are computed against the pre-stamped output
+        shlib_args_output = predeclared_output
+    elif enable_late_build_info_stamping:
+        predeclared_output = ctx.actions.declare_output(unstamped_name, has_content_based_path = exe_content_based)
+        final_output = ctx.actions.declare_output(name, has_content_based_path = exe_content_based)
+        shlib_args_output = final_output
+    else:
+        # If not using late build info stamping, then the output will be stamped eagerly in rust_compile
+        predeclared_output = ctx.actions.declare_output(name, has_content_based_path = exe_content_based)
+        final_output = predeclared_output
+        shlib_args_output = final_output
+
+    # link groups shared libraries link args are directly added to the link command,
+    # we don't have to add them here
+    executable_shlib_args = executable_shared_lib_arguments(
+        ctx,
+        compile_ctx.cxx_toolchain_info,
+        shlib_args_output,
+        shared_libs,
+    )
+    if generated_build_info_enabled and not links_via_cxx:
+        generated_build_info = generate_build_info(
+            ctx,
+            generator_args = generated_build_info_args,
+            invalidation_inputs = [
+                rust_compile_invalidation_inputs(
+                    ctx = ctx,
+                    compile_ctx = compile_ctx,
+                    emit = bin_emit,
+                    params = params,
+                    default_roots = default_roots,
+                    incremental_enabled = ctx.attrs.incremental_enabled,
+                ),
+                unpack_link_args(native_link_args),
+                executable_shlib_args.extra_link_args,
+            ],
+        )
+        if generated_build_info:
+            generated_build_info_link_args.extend(generated_build_info.linker_flags)
+            generated_build_info_link_args.extend(compile_generated_build_info(ctx, generated_build_info).objects)
+    extra_link_args = executable_shlib_args.extra_link_args + generated_build_info_link_args
+
+    # Compile rust binary. Under `Emit("rlib")`, this only compiles: rustc's
+    # synthesized objects are extracted and linked below.
+    link = rust_compile(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        emit = bin_emit,
+        params = params,
+        default_roots = default_roots,
+        extra_link_args = extra_link_args,
+        predeclared_output = None if links_via_cxx else predeclared_output,
+        predeclared_output_has_content_based_path = exe_content_based,
+        extra_flags = extra_flags,
+        allow_cache_upload = allow_cache_upload,
+        transformation_spec_context = transformation_spec_context,
+        incremental_enabled = ctx.attrs.incremental_enabled,
+        precomputed_inherited_link_args = native_link_args,
+    )
+
+    dwp_output = link.link_output.dwp_output if link.link_output else None
+    pdb_output = link.link_output.pdb if link.link_output else None
+    prebolt_output = None
+    if links_via_cxx:
+        rust_link_inputs = [
+            link.link_extraction.out_argsfile,
+            link.link_extraction.out_artifacts_dir,
+            link.link_extraction.out_manifest,
+        ]
+        if link.link_extraction.out_archive != None:
+            rust_link_inputs.append(link.link_extraction.out_archive)
+        if generated_build_info_enabled:
+            generated_build_info = generate_build_info(
+                ctx,
+                generator_args = generated_build_info_args,
+                invalidation_inputs = rust_link_inputs
+                + [
+                    unpack_link_args(native_link_args),
+                    executable_shlib_args.extra_link_args,
+                ],
+            )
+            if generated_build_info:
+                generated_build_info_link_args.extend(generated_build_info.linker_flags)
+                generated_build_info_link_objects.extend(compile_generated_build_info(ctx, generated_build_info).objects)
+        link_result = rust_link_binary(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            extraction = link.link_extraction,
+            dep_link_strategy = params.dep_link_strategy,
+            reloc_model = params.reloc_model,
+            extra_link_args = executable_shlib_args.extra_link_args,
+            binary_link_args = generated_build_info_link_objects + generated_build_info_link_args,
+            inherited_link_args = native_link_args,
+            dwo_output_directory = link.compile_output.dwo_output_directory,
+            output = predeclared_output,
+            output_has_content_based_path = exe_content_based,
+            identifier = name,
+            allow_cache_upload = allow_cache_upload,
+        )
+        final_output = link_result.linked_object.output
+        dwp_output = link_result.linked_object.dwp
+        pdb_output = link_result.linked_object.pdb
+        prebolt_output = link_result.linked_object.prebolt_output
+    elif enable_late_build_info_stamping:
+        stamp_build_info(ctx, link.output, final_output)
+
+    args = cmd_args(final_output, hidden = executable_shlib_args.runtime_files)
+    external_debug_info = project_artifacts(
+        actions = ctx.actions,
+        tsets = inherited_external_debug_info(
+            ctx,
+            compile_ctx.dep_ctx,
+            link_strategy,
+        ),
+    )
+    if link.compile_output.dwo_output_directory:
+        external_debug_info.append(link.compile_output.dwo_output_directory)
+
+    # If we have some resources, write it to the resources JSON file and add
+    # it and all resources to "runtime_files" so that we make to materialize
+    # them with the final binary.
+    runtime_files = list(executable_shlib_args.runtime_files)
+    relocatable_resources_json = None
+    relocatable_resources_contents = None
+    if resources:
+        resources_hidden = [
+            create_resource_db(
+                ctx = ctx,
+                name = name + ".resources.json",
+                binary = final_output,
+                resources = resources,
+            )
+        ]
+        for resource in resources.values():
+            resources_hidden.append(resource.default_output)
+            resources_hidden.extend(resource.other_outputs)
+        args.add(cmd_args(hidden = resources_hidden))
+        runtime_files.extend(resources_hidden)
+        relocatable_resources_json, relocatable_resources_contents = create_relocatable_resources_info(
+            ctx = ctx,
+            name = name,
+            resources = resources,
+            has_content_based_path = content_based_output,
+        )
+
+    # If opted into content-based output and the binary has adjacent files
+    # (resources and/or a shared-lib tree), package everything into a single
+    # content-based `assembled_dir` and point both the run command and
+    # `DefaultInfo.default_output` at the exe projected out of the bundle, so
+    # by-path and resource consumers get the self-contained, co-located form.
+    dist_bundle = None
+    dist_exe = None
+    if will_bundle:
+        dist_bundle, dist_exe = _create_content_based_dist(
+            ctx = ctx,
+            name = name,
+            exe = final_output,
+            relocatable_resources_json = relocatable_resources_json,
+            relocatable_resources_contents = relocatable_resources_contents,
+            shlib_tree = executable_shlib_args.shared_libs_symlink_tree,
+        )
+        # Run the bundled exe (projected out of the content-based bundle). The
+        # bundle carries the co-located resources / shlib tree; `runtime_files`
+        # is still added so a resource's own `other_outputs` (e.g. a resource
+        # that is itself a dynamic exe) materialize too, mirroring the
+        # non-bundle contract.
+        args = cmd_args(dist_exe, hidden = [dist_bundle] + runtime_files)
+
+    # A simple dict of sub-target key to artifact, which we'll convert to
+    # DefaultInfo providers at the end
+    extra_compiled_targets = {
+        "sources": compile_ctx.symlinked_srcs,
+    }
+    sub_targets = {}
+
+    # TODO(agallagher) There appears to be pre-existing soname conflicts
+    # when building this (when using link groups), which prevents using
+    # `with_unique_str_sonames`.
+    str_soname_shlibs = {shlib.soname.ensure_str(): shlib for shlib in shared_libs if shlib.soname.is_str}
+    sub_targets["shared-libraries"] = [
+        DefaultInfo(
+            default_output = ctx.actions.write_json(
+                name + ".shared-libraries.json",
+                {
+                    "libraries": ["{}:{}[shared-libraries][{}]".format(ctx.label.path, ctx.label.name, soname) for soname in str_soname_shlibs],
+                    "librariesdwp": [
+                        "{}:{}[shared-libraries][{}][dwp]".format(ctx.label.path, ctx.label.name, soname)
+                        for soname, shlib in str_soname_shlibs.items()
+                        if shlib.lib.dwp
+                    ],
+                    "rpathtree": ["{}:{}[rpath-tree]".format(ctx.label.path, ctx.label.name)] if executable_shlib_args.shared_libs_symlink_tree else [],
+                },
+                has_content_based_path = False,
+            ),
+            sub_targets = {
+                soname: [
+                    DefaultInfo(
+                        default_output = shlib.lib.output,
+                        sub_targets = {"dwp": [DefaultInfo(default_output = shlib.lib.dwp)]} if shlib.lib.dwp else {},
+                    )
+                ]
+                for soname, shlib in str_soname_shlibs.items()
+            },
+        )
+    ]
+
+    if isinstance(executable_shlib_args.shared_libs_symlink_tree, Artifact):
+        sub_targets["rpath-tree"] = [
+            DefaultInfo(
+                default_output = executable_shlib_args.shared_libs_symlink_tree,
+                other_outputs = [shlib.lib.output for shlib in shared_libs] + [shlib.lib.dwp for shlib in shared_libs if shlib.lib.dwp],
+            )
+        ]
+
+    if rust_cxx_link_group_info:
+        sub_targets[LINK_GROUP_MAP_DATABASE_SUB_TARGET] = [get_link_group_map_json(ctx, filtered_targets)]
+        readable_mappings = {}
+        for node, group in link_group_mappings.items():
+            readable_mappings[group] = readable_mappings.get(group, []) + ["{}//{}:{}".format(node.cell, node.package, node.name)]
+        sub_targets[LINK_GROUP_MAPPINGS_SUB_TARGET] = [
+            DefaultInfo(
+                default_output = ctx.actions.write_json(
+                    name + LINK_GROUP_MAPPINGS_FILENAME_SUFFIX,
+                    readable_mappings,
+                    has_content_based_path = False,
+                ),
+            )
+        ]
+
+    # `infallible_diagnostics` allows us to circumvent compilation failures and
+    # treat the resulting rustc action as a success, even if a metadata
+    # artifact was not generated. This allows us to generate diagnostics
+    # even when the target has bugs.
+    diag_artifacts = {}
+    clippy_artifacts = {}
+    for incr in (True, False):
+        diag_artifacts[incr] = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = Emit("metadata-fast"),
+            params = strategy_param[DEFAULT_STATIC_LINK_STRATEGY],
+            default_roots = default_roots,
+            extra_flags = extra_flags,
+            infallible_diagnostics = True,
+            incremental_enabled = incr,
+            transformation_spec_context = transformation_spec_context,
+        )
+        clippy_artifacts[incr] = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = Emit("clippy"),
+            params = strategy_param[DEFAULT_STATIC_LINK_STRATEGY],
+            default_roots = default_roots,
+            extra_flags = extra_flags,
+            infallible_diagnostics = True,
+            incremental_enabled = incr,
+            transformation_spec_context = transformation_spec_context,
+        )
+
+    providers = [
+        RustcExtraOutputsInfo(
+            metadata = diag_artifacts[False],
+            metadata_incr = diag_artifacts[True],
+            clippy = clippy_artifacts[False],
+            clippy_incr = clippy_artifacts[True],
+            remarks = None,  # Exposed via subtargets, not this provider
+        )
+    ]
+
+    incr_enabled = ctx.attrs.incremental_enabled
+    extra_compiled_targets.update(output_as_diag_subtargets(diag_artifacts[incr_enabled], clippy_artifacts[incr_enabled]))
+
+    # Add remarks subtargets (lazy - only built when subtarget requested)
+    # Uses `params` to match the actual binary's link strategy
+    remarks = rust_compile(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        emit = bin_emit,
+        params = params,
+        default_roots = default_roots,
+        extra_link_args = extra_link_args,
+        extra_flags = extra_flags,
+        incremental_enabled = False,
+        profile_mode = ProfileMode("remarks"),
+        transformation_spec_context = transformation_spec_context,
+    )
+    if remarks.compile_output.remarks_txt:
+        extra_compiled_targets["remarks.txt"] = remarks.compile_output.remarks_txt
+    if remarks.compile_output.remarks_json:
+        extra_compiled_targets["remarks.json"] = remarks.compile_output.remarks_json
+
+    if compile_ctx.toolchain_info.nightly_features:
+        # `-Zunpretty=expanded` is unstable
+        extra_compiled_targets["expand"] = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = Emit("expand"),
+            params = strategy_param[DEFAULT_STATIC_LINK_STRATEGY],
+            default_roots = default_roots,
+            extra_flags = extra_flags,
+            incremental_enabled = ctx.attrs.incremental_enabled,
+        ).output
+
+    llvm_ir_noopt = rust_compile(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        emit = Emit("llvm-ir-noopt"),
+        params = strategy_param[DEFAULT_STATIC_LINK_STRATEGY],
+        default_roots = default_roots,
+        extra_flags = extra_flags,
+        incremental_enabled = ctx.attrs.incremental_enabled,
+    ).output
+    if compile_ctx.toolchain_info.nightly_features:
+        llvm_time_trace = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = bin_emit,
+            params = params,
+            default_roots = default_roots,
+            extra_link_args = extra_link_args,
+            extra_flags = extra_flags,
+            incremental_enabled = ctx.attrs.incremental_enabled,
+            profile_mode = ProfileMode("llvm-time-trace"),
+        )
+        self_profile = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = bin_emit,
+            params = params,
+            default_roots = default_roots,
+            extra_link_args = extra_link_args,
+            extra_flags = extra_flags,
+            incremental_enabled = ctx.attrs.incremental_enabled,
+            profile_mode = ProfileMode("self-profile"),
+        )
+    else:
+        # `-Zllvm-time-trace` and `-Zself-profile` are unstable
+        llvm_time_trace = None
+        self_profile = None
+    profiles = make_profile_providers(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        llvm_ir_noopt = llvm_ir_noopt,
+        llvm_time_trace = llvm_time_trace,
+        self_profile = self_profile,
+    )
+    sub_targets["profile"] = profiles
+
+    for emit_type in ["asm", "llvm-ir", "mir"]:
+        extra_compiled_targets[emit_type] = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = Emit(emit_type),
+            params = params,
+            default_roots = default_roots,
+            extra_flags = extra_flags,
+            incremental_enabled = ctx.attrs.incremental_enabled,
+        ).output
+
+    doc_output = generate_rustdoc(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        params = strategy_param[DEFAULT_STATIC_LINK_STRATEGY],
+        default_roots = default_roots,
+        document_private_items = True,
+    )
+    extra_compiled_targets["doc"] = doc_output
+
+    named_deps_names = write_named_deps_names(ctx, compile_ctx)
+    if named_deps_names:
+        extra_compiled_targets["named_deps"] = named_deps_names
+
+    if dwp_output:
+        sub_targets["dwp"] = [
+            DefaultInfo(
+                default_output = dwp_output,
+                other_outputs = [shlib.lib.dwp for shlib in shared_libs if shlib.lib.dwp]
+                + ([executable_shlib_args.dwp_symlink_tree] if executable_shlib_args.dwp_symlink_tree else []),
+            ),
+        ]
+
+    if pdb_output:
+        sub_targets[PDB_SUB_TARGET] = get_pdb_providers(pdb = pdb_output, binary = final_output)
+
+    if use_bolt and prebolt_output:
+        sub_targets["prebolt"] = [DefaultInfo(default_output = prebolt_output)]
+
+    dupmbin_toolchain = compile_ctx.cxx_toolchain_info.dumpbin_toolchain_path
+    if dupmbin_toolchain:
+        sub_targets[DUMPBIN_SUB_TARGET] = get_dumpbin_providers(ctx, final_output, dupmbin_toolchain)
+
+    sub_targets.update({k: [DefaultInfo(default_output = v)] for (k, v) in extra_compiled_targets.items()})
+
+    if dist_bundle:
+        sub_targets["dist"] = [DefaultInfo(default_output = dist_bundle)]
+
+    providers += [
+        DefaultInfo(
+            default_output = dist_exe if dist_bundle else final_output,
+            other_outputs = runtime_files
+            + (executable_shlib_args.external_debug_info + external_debug_info if compile_ctx.cxx_toolchain_info.materialize_external_debug_info else [])
+            + ([dist_bundle] if dist_bundle else []),
+            sub_targets = sub_targets,
+        ),
+        DistInfo(
+            shared_libs = shlib_info.set,
+            # The bundle is load-bearing at runtime for a bundled binary: the
+            # projected exe resolves its manifest / shlib tree as bundle
+            # siblings, so dist consumers that materialize only
+            # `nondebug_runtime_files` must get the bundle too.
+            nondebug_runtime_files = runtime_files + ([dist_bundle] if dist_bundle else []),
+            relocatable_resources_contents = relocatable_resources_contents,
+            relocatable_resources_json = relocatable_resources_json,
+        ),
+    ]
+    providers.append(
+        rust_analyzer_provider(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            default_roots = default_roots,
+        )
+    )
+    return (providers, args)
+
+def rust_binary_impl(ctx: AnalysisContext) -> list[Provider]:
+    compile_ctx = compile_context(ctx, binary = True)
+
+    providers, args = _rust_binary_common(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        default_roots = ["main.rs"],
+        extra_flags = [],
+        allow_cache_upload = cxx_attrs_get_allow_cache_upload(ctx.attrs),
+    )
+
+    return providers + [RunInfo(args = args)]
+
+def rust_test_impl(ctx: AnalysisContext) -> list[Provider]:
+    compile_ctx = compile_context(ctx, binary = True)
+    toolchain_info = compile_ctx.toolchain_info
+
+    extra_flags = toolchain_info.rustc_test_flags or []
+    if ctx.attrs.framework:
+        extra_flags += ["--test"]
+
+    providers, args = _rust_binary_common(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        # Unless default_roots are provided, it is ambiguous whether this test rule is invoked
+        # to test a binary, or to test a library. As such, we must consider both main.rs and
+        # lib.rs as potential candidates.
+        default_roots = ctx.attrs.default_roots or ["main.rs", "lib.rs"],
+        extra_flags = extra_flags,
+        allow_cache_upload = False,
+    )
+
+    # Setup RE executors based on the `remote_execution` param.
+    re_executors = get_re_executors_from_props(ctx)
+
+    return (
+        inject_test_run_info(
+            ctx,
+            ExternalRunnerTestInfo(
+                type = "rust",
+                command = [args],
+                env = ctx.attrs.env | ctx.attrs.run_env,
+                labels = ctx.attrs.labels,
+                contacts = ctx.attrs.contacts,
+                default_executor = re_executors.default_executor,
+                executor_overrides = re_executors.executor_overrides,
+                run_from_project_root = True,
+                use_project_relative_paths = True,
+            ),
+        )
+        + providers
+    )
diff --git a/buck2/prelude/rust/rust_common.bzl b/buck2/prelude/rust/rust_common.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/rust_common.bzl
@@ -0,0 +1,16 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":with_workspace.bzl", "package_key")
+
+def rust_common_macro_wrapper(rust_rule):
+    def rust_common_impl(**kwargs):
+        workspaces = read_package_value(package_key) or []
+        rust_rule(_workspaces = workspaces, **kwargs)
+
+    return rust_common_impl
diff --git a/buck2/prelude/rust/rust_library.bzl b/buck2/prelude/rust/rust_library.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/rust_library.bzl
@@ -0,0 +1,1270 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//:artifact_tset.bzl",
+    "ArtifactTSet",
+    "make_artifact_tset",
+)
+load("@prelude//:resources.bzl", "gather_resources", "make_resource_info")
+load(
+    "@prelude//android:android_providers.bzl",
+    "merge_android_packageable_info",
+)
+load(
+    "@prelude//cxx:linker.bzl",
+    "IMPORT_LIBRARY_SUB_TARGET",
+    "PDB_SUB_TARGET",
+    "get_pdb_providers",
+)
+load(
+    "@prelude//cxx:omnibus.bzl",
+    "create_linkable_root",
+)
+load(
+    "@prelude//linking:link_groups.bzl",
+    "merge_link_group_lib_info",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "Archive",
+    "ArchiveLinkable",
+    "LibOutputStyle",
+    "LinkInfo",
+    "LinkInfos",
+    "LinkStrategy",
+    "LinkedObject",
+    "LinkerFlags",
+    "MergedLinkInfo",  # @unused Used as a type
+    "SharedLibLinkable",
+    "create_merged_link_info",
+    "get_lib_output_style",
+    "get_output_styles_for_linkage",
+    "set_link_info_link_whole",
+)
+load(
+    "@prelude//linking:linkable_graph.bzl",
+    "DLOPENABLE_LIBRARY_INFO_MARKER",
+    "create_linkable_graph",
+    "create_linkable_graph_node",
+    "create_linkable_node",
+)
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibraryInfo",  # @unused Used as a type
+    "create_shared_libraries",
+    "merge_shared_libraries",
+)
+load("@prelude//linking:types.bzl", "Linkage")
+load("@prelude//os_lookup:defs.bzl", "OsLookup")
+load("@prelude//rust/rust-analyzer:provider.bzl", "rust_analyzer_provider")
+load(
+    "@prelude//tests:re_utils.bzl",
+    "RemoteTestExecutorConfig",
+    "get_re_executors_from_explicit_props",
+)
+load(
+    "@prelude//third-party:build.bzl",
+    "create_third_party_build_info",
+)
+load(
+    "@prelude//third-party:providers.bzl",
+    "ThirdPartyBuildInfo",  # @unused Used as a type
+    "third_party_build_info",
+)
+load("@prelude//unix:providers.bzl", "UnixEnv", "create_unix_env_info")
+load(
+    ":build.bzl",
+    "generate_rustdoc",
+    "generate_rustdoc_coverage",
+    "generate_rustdoc_test",
+    "rust_compile",
+    "rust_link_shared",
+)
+load(
+    ":build_params.bzl",
+    "BuildParams",  # @unused Used as a type
+    "CrateType",
+    "Emit",
+    "LinkageLang",
+    "MetadataKind",
+    "ProfileMode",  # @unused Used as a type
+    "RuleType",
+    "build_params",
+)
+load(
+    ":context.bzl",
+    "CompileContext",  # @unused Used as a type
+    "compile_context",
+)
+load(":dep_context.bzl", "DepCollectionContext")
+load(
+    ":link_info.bzl",
+    "DEFAULT_STATIC_LIB_OUTPUT_STYLE",
+    "DEFAULT_STATIC_LINK_STRATEGY",
+    "RustExportedLinkDeps",
+    "RustLinkInfo",
+    "RustLinkStrategyInfo",
+    "RustLinkableGraphs",
+    "RustNativeLinkDeps",
+    "RustProcMacroMarker",  # @unused Used as a type
+    "TransitiveDeps",
+    "attr_crate",
+    "dfs_dedupe_by_label",
+    "inherited_exported_link_deps",
+    "inherited_link_group_lib_infos",
+    "inherited_linkable_graphs",
+    "inherited_merged_link_infos",
+    "inherited_native_link_deps",
+    "inherited_rust_external_debug_info",
+    "inherited_shared_libs",
+    "inherited_third_party_builds",
+    "resolve_deps",
+    "resolve_rust_deps",
+    "strategy_info",
+)
+load(":named_deps.bzl", "write_named_deps_names")
+load(
+    ":outputs.bzl",
+    "RustcExtraOutputsInfo",
+    "RustcOutput",  # @unused Used as a type
+    "output_as_diag_subtargets",
+)
+load(":proc_macro_alias.bzl", "rust_proc_macro_alias")
+load(":profile.bzl", "make_profile_providers")
+load(":resources.bzl", "rust_attr_resources")
+load(":rust_toolchain.bzl", "RustToolchainInfo")
+load(
+    ":sources.bzl",
+    "RustSources",
+    "RustSourcesTSet",
+)
+load(":targets.bzl", "targets")
+
+_DEFAULT_ROOTS = ["lib.rs"]
+
+# Add provider for default output, and for each lib output style...
+_SUB_TARGET_BUILD_LANG_STYLE = {
+    "cdylib": (LinkageLang("native-bundled"), LibOutputStyle("shared_lib")),
+    "dylib": (LinkageLang("rust"), LibOutputStyle("shared_lib")),
+    # FIXME(JakobDegen): Ideally we'd use the same
+    # `subtarget_for_output_style` as C++, but that uses `static-pic`
+    # instead of `static_pic`. Would be nice if that were consistent
+    "static": (LinkageLang("rust"), LibOutputStyle("archive")),
+    "static_pic": (LinkageLang("rust"), LibOutputStyle("pic_archive")),
+    "staticlib": (LinkageLang("native-bundled"), LibOutputStyle("archive")),
+}
+
+def rust_library_impl(ctx: AnalysisContext) -> list[Provider]:
+    compile_ctx = compile_context(ctx)
+    toolchain_info = compile_ctx.toolchain_info
+
+    # Multiple styles and language linkages could generate the same crate types
+    # (eg procmacro or using preferred_linkage), so we need to see how many
+    # distinct kinds of build we actually need to deal with.
+    param_lang, lang_style_param = _build_params_for_styles(ctx, compile_ctx)
+
+    # Grab the artifacts to use for the check subtargets. Picking a good
+    # `LibOutputStyle` ensures that the subtarget shares work with the main
+    # build if possible
+    meta_params = lang_style_param[(LinkageLang("rust"), DEFAULT_STATIC_LIB_OUTPUT_STYLE)]
+
+    meta_fast = rust_compile(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        emit = Emit("metadata-fast"),
+        params = meta_params,
+        default_roots = _DEFAULT_ROOTS,
+        incremental_enabled = ctx.attrs.incremental_enabled,
+    )
+
+    # Generate the actions to build various output artifacts. Given the set of
+    # parameters we need, populate maps to the linkable and metadata
+    # artifacts by linkage lang.
+    param_metadata_outputs = {}
+    param_output = {}
+    param_subtargets = {}
+    for params, langs in param_lang.items():
+        link = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = Emit("rlib") if params.crate_type == CrateType("rlib") else Emit("link"),
+            params = params,
+            default_roots = _DEFAULT_ROOTS,
+            incremental_enabled = ctx.attrs.incremental_enabled,
+        )
+        param_output[params] = link
+
+        param_subtargets.setdefault(params, {})
+        if LinkageLang("rust") in langs:
+            metadata_link = link
+            if toolchain_info.advanced_unstable_linking and params.crate_type == CrateType("rlib"):
+                # Rustc-produced staticlibs need code and metadata in one rlib.
+                rlib_for_staticlib = rust_compile(
+                    ctx = ctx,
+                    compile_ctx = compile_ctx,
+                    emit = Emit("link"),
+                    params = params,
+                    default_roots = _DEFAULT_ROOTS,
+                    incremental_enabled = ctx.attrs.incremental_enabled,
+                )
+                metadata_link = rlib_for_staticlib
+
+            if toolchain_info.nightly_features:
+                # Pipelined build: dependents that need full metadata compile
+                # against the `-Zno-codegen` "hollow rlib" instead of waiting
+                # for this crate's codegen.
+                metadata_full = rust_compile(
+                    ctx = ctx,
+                    compile_ctx = compile_ctx,
+                    emit = Emit("metadata-full"),
+                    params = params,
+                    default_roots = _DEFAULT_ROOTS,
+                    incremental_enabled = ctx.attrs.incremental_enabled,
+                )
+            else:
+                # Pipelining requires the unstable `-Zno-codegen`; dependents
+                # wait for the real rlib instead.
+                metadata_full = link
+            param_metadata_outputs[params] = {
+                MetadataKind("link"): metadata_link,
+                MetadataKind("full"): metadata_full,
+                MetadataKind("fast"): meta_fast,
+            }
+
+            subtargets_to_add = {}
+            for emit_type in ["asm", "llvm-ir", "mir"]:
+                subtargets_to_add[emit_type] = rust_compile(
+                    ctx = ctx,
+                    compile_ctx = compile_ctx,
+                    emit = Emit(emit_type),
+                    params = params,
+                    default_roots = _DEFAULT_ROOTS,
+                    incremental_enabled = ctx.attrs.incremental_enabled,
+                )
+            param_subtargets[params].update(subtargets_to_add)
+
+    link_infos, linked_object = _link_infos(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        lang_style_param = lang_style_param,
+        param_artifact = param_output,
+    )
+
+    if (
+        toolchain_info.advanced_unstable_linking
+        and (LibOutputStyle("shared_lib") in get_output_styles_for_linkage(Linkage(ctx.attrs.preferred_linkage)))
+        and not ctx.attrs.proc_macro
+    ):
+        if not compile_ctx.cxx_toolchain_info.linker_info.supports_shared_libraries:
+            if ctx.attrs.preferred_linkage == "shared":
+                fail("{}: cannot build shared library for a toolchain that does not support shared libraries".format(ctx.label))
+
+            # Bare-metal toolchains don't support shared libraries (ld lacks -shared).
+            # Provide the static archive as fallback to satisfy the linkable graph.
+            link_infos[LibOutputStyle("shared_lib")] = link_infos[LibOutputStyle("pic_archive")]
+        else:
+            # Rely on iteration order having produced this first but that's probably ok
+            linked_object = rust_link_shared(
+                ctx,
+                compile_ctx,
+                # Unlike `cxx_library`, `link_style` is not consulted here: the deps of a Rust DSO
+                # always use the shared link strategy.
+                dep_link_style = LinkStrategy("shared"),
+                static_lib = link_infos[LibOutputStyle("pic_archive")].default,
+            )
+            link_infos[LibOutputStyle("shared_lib")] = _make_shared_lib_link_infos(
+                ctx,
+                linked_object,
+            )
+
+    rust_artifacts = _rust_artifacts(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        lang_style_param = lang_style_param,
+        param_metadata_outputs = param_metadata_outputs,
+    )
+
+    # For doctests, we need to know two things to know how to link them. The
+    # first is that we need a link strategy, which affects how deps of this
+    # target are handled
+    if ctx.attrs.doc_link_style:
+        doc_link_strategy = LinkStrategy(ctx.attrs.doc_link_style)
+    else:
+        # FIXME(JakobDegen): In this position, a binary would just fall back to
+        # the default link style. However, we have a little bit of additional
+        # information in the form of the preferred linkage that we can use to
+        # make a different decision. There's nothing technically wrong with
+        # that, but a comment explaining why we want to do it would be nice
+        doc_link_strategy = {
+            "any": LinkStrategy("shared"),
+            "shared": LinkStrategy("shared"),
+            "static": DEFAULT_STATIC_LINK_STRATEGY,
+        }[ctx.attrs.preferred_linkage]
+
+    # The second thing we need is a lib output style of the regular, non-doctest
+    # version of this target that we want. Rustdoc does not handle this library
+    # being built in a "shared" way well, so this must be a static output style.
+    if ctx.attrs.doc_link_style:
+        doc_output_style = {
+            "shared": DEFAULT_STATIC_LIB_OUTPUT_STYLE,
+            "static": LibOutputStyle("archive"),
+            "static_pic": LibOutputStyle("pic_archive"),
+        }[ctx.attrs.doc_link_style]
+    else:
+        doc_output_style = DEFAULT_STATIC_LIB_OUTPUT_STYLE
+    static_library_params = lang_style_param[(LinkageLang("rust"), doc_output_style)]
+
+    # Among {rustdoc, doctests, macro expand}, doctests are the only one which
+    # cares about linkage. So whatever build params we picked for the doctests,
+    # reuse them for the other two as well
+    rustdoc = generate_rustdoc(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        params = static_library_params,
+        default_roots = _DEFAULT_ROOTS,
+        document_private_items = False,
+    )
+
+    if toolchain_info.nightly_features:
+        rustdoc_coverage = generate_rustdoc_coverage(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            params = static_library_params,
+            default_roots = _DEFAULT_ROOTS,
+        )
+
+        expand = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = Emit("expand"),
+            params = static_library_params,
+            default_roots = _DEFAULT_ROOTS,
+            # This is needed as rustc can generate expanded sources that do not
+            # fully compile, but will report an error even if it succeeds.
+            # TODO(pickett): Handle this at the rustc action level, we shouldn't
+            # need to pass a special arg here, expand should just work.
+            infallible_diagnostics = True,
+            incremental_enabled = ctx.attrs.incremental_enabled,
+        ).output
+    else:
+        # `--show-coverage` and `-Zunpretty=expanded` are unstable
+        rustdoc_coverage = None
+        expand = None
+
+    llvm_ir_noopt = rust_compile(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        emit = Emit("llvm-ir-noopt"),
+        params = static_library_params,
+        default_roots = _DEFAULT_ROOTS,
+        incremental_enabled = ctx.attrs.incremental_enabled,
+    ).output
+    if toolchain_info.nightly_features:
+        llvm_time_trace = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = Emit("rlib"),
+            params = static_library_params,
+            default_roots = _DEFAULT_ROOTS,
+            incremental_enabled = ctx.attrs.incremental_enabled,
+            profile_mode = ProfileMode("llvm-time-trace"),
+        )
+        self_profile = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = Emit("rlib"),
+            params = static_library_params,
+            default_roots = _DEFAULT_ROOTS,
+            incremental_enabled = ctx.attrs.incremental_enabled,
+            profile_mode = ProfileMode("self-profile"),
+        )
+    else:
+        # `-Zllvm-time-trace` and `-Zself-profile` are unstable
+        llvm_time_trace = None
+        self_profile = None
+    profiles = make_profile_providers(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        llvm_ir_noopt = llvm_ir_noopt,
+        llvm_time_trace = llvm_time_trace,
+        self_profile = self_profile,
+    )
+
+    # If doctests=True or False is set on the individual target, respect that.
+    # Otherwise look at the global setting on the toolchain.
+    if ctx.attrs.doctests != None:
+        doctests_enabled = ctx.attrs.doctests
+    else:
+        doctests_enabled = toolchain_info.doctests
+
+    # No doctests if cross-compiling.
+    #
+    # I tried `cargo test --doc --target aarch64-unknown-linux-gnu` and Cargo
+    # silently did not run doc tests. We could probably make this work, but it
+    # seems low value, and Cargo not running them tells me we'd be very likely
+    # to hit issues with this not being supported well in rustdoc.
+    if toolchain_info.rustc_target_triple != None and toolchain_info.rustc_target_triple != targets.exec_triple(ctx):
+        doctests_enabled = False
+
+    if toolchain_info.nightly_features:
+        rustdoc_test_metadata_kind = MetadataKind("full") if toolchain_info.advanced_unstable_linking and not ctx.attrs.proc_macro else MetadataKind("link")
+        rustdoc_test_params = build_params(
+            rule = RuleType("binary"),
+            proc_macro = ctx.attrs.proc_macro,
+            link_strategy = doc_link_strategy,
+            lib_output_style = None,
+            lang = LinkageLang("rust"),
+            linker_type = compile_ctx.cxx_toolchain_info.linker_info.type,
+            target_os_type = ctx.attrs._target_os_type[OsLookup],
+        )
+        rustdoc_test = generate_rustdoc_test(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            rlib = param_metadata_outputs[static_library_params][rustdoc_test_metadata_kind].output,
+            link_infos = link_infos,
+            params = rustdoc_test_params,
+            default_roots = _DEFAULT_ROOTS,
+        )
+    else:
+        # Doctests are invoked via rustdoc's unstable `--test-runtool`
+        doctests_enabled = False
+        rustdoc_test = None
+
+    # infallible_diagnostics allows us to circumvent compilation failures and
+    # treat the resulting rustc action as a success, even if a metadata
+    # artifact was not generated. This allows us to generate diagnostics
+    # even when the target has bugs.
+    diag_artifacts = {}
+    clippy_artifacts = {}
+    for incr in (True, False):
+        diag_artifacts[incr] = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = Emit("metadata-fast"),
+            params = meta_params,
+            default_roots = _DEFAULT_ROOTS,
+            infallible_diagnostics = True,
+            incremental_enabled = incr,
+        )
+        clippy_artifacts[incr] = rust_compile(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            emit = Emit("clippy"),
+            params = meta_params,
+            default_roots = _DEFAULT_ROOTS,
+            infallible_diagnostics = True,
+            incremental_enabled = incr,
+        )
+
+    # Generate single remarks artifact (lazy - only built when subtarget requested)
+    # Uses meta_params to share configuration with diag/clippy builds
+    remarks_artifact = rust_compile(
+        ctx = ctx,
+        compile_ctx = compile_ctx,
+        emit = Emit("rlib"),
+        params = meta_params,
+        default_roots = _DEFAULT_ROOTS,
+        incremental_enabled = False,
+        profile_mode = ProfileMode("remarks"),
+    )
+
+    incr_enabled = ctx.attrs.incremental_enabled
+    re_executors = RemoteTestExecutorConfig()
+    if ctx.attrs.doc_remote_execution != None:
+        re_executors = get_re_executors_from_explicit_props(ctx, ctx.attrs.doc_remote_execution)
+
+    providers = []
+    providers += _default_providers(
+        lang_style_param = lang_style_param,
+        param_output = param_output,
+        param_subtargets = param_subtargets,
+        linked_object = linked_object,
+        remarks_artifact = remarks_artifact,
+        rustdoc = rustdoc,
+        rustdoc_test = rustdoc_test,
+        doctests_enabled = doctests_enabled,
+        re_executors = re_executors,
+        check_artifacts = output_as_diag_subtargets(diag_artifacts[incr_enabled], clippy_artifacts[incr_enabled]),
+        expand = expand,
+        sources = compile_ctx.symlinked_srcs,
+        transitive_srcs = compile_ctx.transitive_srcs,
+        rustdoc_coverage = rustdoc_coverage,
+        named_deps_names = write_named_deps_names(ctx, compile_ctx),
+        profiles = profiles,
+    )
+    providers += _rust_metadata_providers(
+        diag_artifacts = diag_artifacts,
+        clippy_artifacts = clippy_artifacts,
+    )
+
+    if ctx.attrs.proc_macro:
+        providers += _proc_macro_link_providers(
+            ctx = ctx,
+            rust_artifacts = rust_artifacts,
+        )
+    elif toolchain_info.advanced_unstable_linking:
+        providers += _advanced_unstable_link_providers(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            rust_artifacts = rust_artifacts,
+            link_infos = link_infos,
+            linked_object = linked_object,
+        )
+    else:
+        providers += _stable_link_providers(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            rust_artifacts = rust_artifacts,
+            link_infos = link_infos,
+            linked_object = linked_object,
+        )
+
+    deps = [dep.dep for dep in resolve_deps(ctx, compile_ctx.dep_ctx)]
+    providers.append(
+        make_resource_info(
+            gather_resources(
+                label = ctx.label,
+                resources = rust_attr_resources(ctx),
+                deps = deps,
+            ),
+        ),
+    )
+
+    providers.append(merge_android_packageable_info(ctx.label, ctx.actions, deps))
+
+    providers.append(
+        rust_analyzer_provider(
+            ctx = ctx,
+            compile_ctx = compile_ctx,
+            default_roots = _DEFAULT_ROOTS,
+        )
+    )
+
+    return providers
+
+def _build_params_for_styles(
+    ctx: AnalysisContext, compile_ctx: CompileContext
+) -> (
+    dict[BuildParams, list[LinkageLang]],
+    dict[(LinkageLang, LibOutputStyle), BuildParams],
+):
+    """
+    For a given rule, return two things:
+    - a set of build params we need for all combinations of linkage langages and
+      link styles, mapped to which languages they apply to
+    - a mapping from linkage language and link style to build params
+
+    This is needed because different combinations may end up using the same set
+    of params, and we want to minimize invocations to rustc, both for
+    efficiency's sake, but also to avoid duplicate objects being linked
+    together.
+    """
+
+    param_lang = {}  # param -> linkage_lang
+    style_param = {}  # (linkage_lang, output_style) -> param
+
+    target_os_type = ctx.attrs._target_os_type[OsLookup]
+    linker_type = compile_ctx.cxx_toolchain_info.linker_info.type
+    output_styles = get_output_styles_for_linkage(Linkage(ctx.attrs.preferred_linkage))
+
+    # Styles+lang linkage to params
+    for linkage_lang in LinkageLang:
+        # Skip proc_macro + non-rust combinations
+        if ctx.attrs.proc_macro and linkage_lang != LinkageLang("rust"):
+            continue
+
+        for lib_output_style in output_styles:
+            if (
+                ctx.attrs._rust_toolchain[RustToolchainInfo].advanced_unstable_linking
+                and linkage_lang == LinkageLang("rust")
+                and lib_output_style == LibOutputStyle("shared_lib")
+            ):
+                # This gets linked directly instead of using rustc
+                continue
+            params = build_params(
+                rule = RuleType("library"),
+                proc_macro = ctx.attrs.proc_macro,
+                link_strategy = None,
+                lib_output_style = lib_output_style,
+                lang = linkage_lang,
+                linker_type = linker_type,
+                target_os_type = target_os_type,
+            )
+            if params not in param_lang:
+                param_lang[params] = []
+            param_lang[params] = param_lang[params] + [linkage_lang]
+            style_param[(linkage_lang, lib_output_style)] = params
+
+    return (param_lang, style_param)
+
+def _make_shared_lib_link_infos(ctx: AnalysisContext, linked_object: LinkedObject) -> LinkInfos:
+    exported_shlib = linked_object.output
+
+    # Link against import library on Windows.
+    if linked_object.import_library:
+        exported_shlib = linked_object.import_library
+
+    return LinkInfos(
+        default = LinkInfo(
+            linkables = [SharedLibLinkable(lib = exported_shlib)],
+            pre_flags = ctx.attrs.exported_linker_flags,
+            post_flags = ctx.attrs.exported_post_linker_flags,
+        ),
+    )
+
+def _link_infos(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    lang_style_param: dict[(LinkageLang, LibOutputStyle), BuildParams],
+    param_artifact: dict[BuildParams, RustcOutput],
+) -> (dict[LibOutputStyle, LinkInfos], LinkedObject | None):
+    if ctx.attrs.proc_macro:
+        # Don't need any of this for proc macros
+        return ({}, None)
+
+    advanced_unstable_linking = compile_ctx.toolchain_info.advanced_unstable_linking
+    lang = LinkageLang("rust") if advanced_unstable_linking else LinkageLang("native-bundled")
+    linker_type = compile_ctx.cxx_toolchain_info.linker_info.type
+    output_styles = get_output_styles_for_linkage(Linkage(ctx.attrs.preferred_linkage))
+
+    link_infos = {}
+    linked_object = None
+    for output_style in output_styles:
+        if output_style == LibOutputStyle("shared_lib") and advanced_unstable_linking:
+            # Skip it here, we're going to handle it separately above
+            continue
+        params = lang_style_param[(lang, output_style)]
+        lib = param_artifact[params]
+        external_debug_infos_to_bundle = []
+        if lang == LinkageLang("native-bundled"):
+            # staticlibs and cdylibs are "bundled" in the sense that they are used
+            # without their dependencies by the rest of the rules. This is normally
+            # correct, except that the split debuginfo rustc emits for these crate
+            # types is not bundled. This is arguably inconsistent behavior from
+            # rustc, but in any case, it means we need to do this bundling manually
+            # by collecting all the external debuginfo from dependencies
+            external_debug_infos_to_bundle = inherited_rust_external_debug_info(
+                ctx = ctx,
+                dep_ctx = compile_ctx.dep_ctx,
+                link_strategy = params.dep_link_strategy,
+            )
+        external_debug_info = make_artifact_tset(
+            actions = ctx.actions,
+            label = ctx.label,
+            artifacts = filter(None, [lib.compile_output.dwo_output_directory]),
+            children = external_debug_infos_to_bundle,
+        )
+        if output_style == LibOutputStyle("shared_lib"):
+            linked_object = LinkedObject(
+                output = lib.output,
+                unstripped_output = lib.output,
+                external_debug_info = external_debug_info,
+                import_library = lib.link_output.import_library,
+                pdb = lib.link_output.pdb,
+                dwp = lib.link_output.dwp_output,
+            )
+
+            link_infos[output_style] = _make_shared_lib_link_infos(
+                ctx,
+                linked_object,
+            )
+        else:
+            link_whole = ctx.attrs.link_whole or False
+            link_infos[output_style] = LinkInfos(
+                default = LinkInfo(
+                    linkables = [
+                        ArchiveLinkable(
+                            archive = Archive(artifact = lib.output),
+                            linker_type = linker_type,
+                            link_whole = link_whole,
+                        )
+                    ],
+                    external_debug_info = external_debug_info,
+                    pre_flags = ctx.attrs.exported_linker_flags,
+                    post_flags = ctx.attrs.exported_post_linker_flags,
+                ),
+                stripped = LinkInfo(
+                    linkables = [
+                        ArchiveLinkable(
+                            archive = Archive(artifact = lib.compile_output.stripped_output),
+                            linker_type = linker_type,
+                            link_whole = link_whole,
+                        )
+                    ],
+                    pre_flags = ctx.attrs.exported_linker_flags,
+                    post_flags = ctx.attrs.exported_post_linker_flags,
+                ),
+            )
+    return (link_infos, linked_object)
+
+def _rust_artifacts(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    lang_style_param: dict[(LinkageLang, LibOutputStyle), BuildParams],
+    param_metadata_outputs: dict[BuildParams, dict[MetadataKind, RustcOutput]],
+) -> dict[LinkStrategy, RustLinkStrategyInfo]:
+    pic_behavior = compile_ctx.cxx_toolchain_info.pic_behavior
+    preferred_linkage = Linkage(ctx.attrs.preferred_linkage)
+
+    rust_artifacts = {}
+    for link_strategy in LinkStrategy:
+        lib_output_style = get_lib_output_style(link_strategy, preferred_linkage, pic_behavior)
+        if ctx.attrs._rust_toolchain[RustToolchainInfo].advanced_unstable_linking:
+            # Unfortunately for the purpose of downstream Rust we still need metadata for this,
+            # despite not having built the shared lib via rustc; we reuse the metadata from
+            # the pic_archive case, which is functionally equivalent
+            lib_output_style = LibOutputStyle("pic_archive")
+        params = lang_style_param[(LinkageLang("rust"), lib_output_style)]
+        rust_artifacts[link_strategy] = _handle_rust_artifact(ctx, compile_ctx.dep_ctx, link_strategy, param_metadata_outputs[params])
+    return rust_artifacts
+
+def _handle_rust_artifact(
+    ctx: AnalysisContext, dep_ctx: DepCollectionContext, link_strategy: LinkStrategy, outputs: dict[MetadataKind, RustcOutput]
+) -> RustLinkStrategyInfo:
+    """
+    Return the RustLinkStrategyInfo for a given set of artifacts. The main consideration
+    is computing the right set of dependencies.
+    """
+
+    # If we're a crate where our consumers should care about transitive deps,
+    # then compute them (specifically, not proc-macro).
+    link_output = outputs[MetadataKind("link")]
+    if not ctx.attrs.proc_macro:
+        tdeps, rust_debug_info, tprocmacrodeps = _compute_transitive_deps(ctx, dep_ctx, link_strategy)
+
+        toolchain_info = ctx.attrs._rust_toolchain[RustToolchainInfo]
+        if toolchain_info.advanced_unstable_linking:
+            rust_debug_info = None
+        else:
+            rust_debug_info = make_artifact_tset(
+                actions = ctx.actions,
+                label = ctx.label,
+                artifacts = filter(None, [link_output.compile_output.dwo_output_directory]),
+                children = rust_debug_info,
+            )
+        return RustLinkStrategyInfo(
+            outputs = {m: x.output for m, x in outputs.items()},
+            singleton_tset = {m: x.singleton_tset for m, x in outputs.items()},
+            transitive_deps = tdeps,
+            transitive_proc_macro_deps = tprocmacrodeps,
+            rust_debug_info = rust_debug_info,
+        )
+    else:
+        # Proc macro deps are always the real thing
+        no_transitive_deps = ctx.actions.tset(TransitiveDeps)
+        return RustLinkStrategyInfo(
+            outputs = {m: link_output.output for m in MetadataKind},
+            singleton_tset = {m: link_output.singleton_tset for m in MetadataKind},
+            transitive_deps = {m: no_transitive_deps for m in MetadataKind},
+            transitive_proc_macro_deps = set(),
+            rust_debug_info = ArtifactTSet(),
+        )
+
+def _default_providers(
+    lang_style_param: dict[(LinkageLang, LibOutputStyle), BuildParams],
+    param_output: dict[BuildParams, RustcOutput],
+    param_subtargets: dict[BuildParams, dict[str, RustcOutput]],
+    linked_object: LinkedObject | None,
+    remarks_artifact: RustcOutput,
+    rustdoc: Artifact,
+    rustdoc_test: cmd_args | None,
+    doctests_enabled: bool,
+    re_executors: RemoteTestExecutorConfig,
+    check_artifacts: dict[str, Artifact | None],
+    expand: Artifact | None,
+    sources: Artifact,
+    transitive_srcs: RustSourcesTSet,
+    rustdoc_coverage: Artifact | None,
+    named_deps_names: Artifact | None,
+    profiles: list[Provider],
+) -> list[Provider]:
+    targets = {}
+    targets.update(check_artifacts)
+    targets["sources"] = sources
+    if expand != None:
+        targets["expand"] = expand
+    targets["doc"] = rustdoc
+    if rustdoc_coverage != None:
+        targets["doc-coverage"] = rustdoc_coverage
+    targets["remarks.txt"] = remarks_artifact.compile_output.remarks_txt
+    targets["remarks.json"] = remarks_artifact.compile_output.remarks_json
+    if named_deps_names:
+        targets["named_deps"] = named_deps_names
+
+    sub_targets = {k: [DefaultInfo(default_output = v)] for (k, v) in targets.items()}
+    sub_targets["profile"] = profiles
+    if linked_object:
+        # FIXME(JakobDegen): Should this have some debuginfo or such in `other_outputs`? Fix or
+        # leave a comment explaining
+        sub_targets["shared"] = [DefaultInfo(default_output = linked_object.output)]
+        if linked_object.pdb:
+            sub_targets[PDB_SUB_TARGET] = get_pdb_providers(pdb = linked_object.pdb, binary = linked_object.output)
+        if linked_object.import_library:
+            sub_targets[IMPORT_LIBRARY_SUB_TARGET] = [DefaultInfo(default_output = linked_object.import_library)]
+
+    for name, lang_style in _SUB_TARGET_BUILD_LANG_STYLE.items():
+        if lang_style not in lang_style_param:
+            continue
+
+        param = lang_style_param[lang_style]
+        artifact = param_output[param]
+
+        nested_sub_targets = {k: [DefaultInfo(default_output = v.output)] for k, v in param_subtargets[param].items()}
+        if artifact.compile_output.stripped_output:
+            nested_sub_targets["stripped"] = [DefaultInfo(default_output = artifact.compile_output.stripped_output)]
+
+        sub_targets[name] = [
+            DefaultInfo(
+                default_output = artifact.output,
+                sub_targets = nested_sub_targets,
+            )
+        ]
+
+    providers = []
+
+    if rustdoc_test != None:
+        rustdoc_test_info = ExternalRunnerTestInfo(
+            type = "rustdoc",
+            command = [rustdoc_test],
+            default_executor = re_executors.default_executor,
+            executor_overrides = re_executors.executor_overrides,
+            # Doctests always run from the project root with project-relative paths,
+            # executor or not, so `re_executors.run_from_project_root` and
+            # `.use_project_relative_paths` are deliberately ignored: configuring an
+            # executor must not move a doctest's cwd out from under it.
+            run_from_project_root = True,
+            use_project_relative_paths = True,
+        )
+
+        # Always let the user run doctests via `buck2 test :crate[doc]`
+        sub_targets["doc"].append(rustdoc_test_info)
+
+        # But only run it as a part of `buck2 test :crate` if it's not disabled
+        if doctests_enabled:
+            providers.append(rustdoc_test_info)
+
+    providers.append(
+        DefaultInfo(
+            default_output = check_artifacts["check"],
+            sub_targets = sub_targets,
+        )
+    )
+
+    providers.append(
+        RustSources(
+            tset = transitive_srcs,
+        )
+    )
+
+    return providers
+
+def _rust_metadata_providers(diag_artifacts: dict[bool, RustcOutput], clippy_artifacts: dict[bool, RustcOutput]) -> list[Provider]:
+    return [
+        RustcExtraOutputsInfo(
+            metadata = diag_artifacts[False],
+            metadata_incr = diag_artifacts[True],
+            clippy = clippy_artifacts[False],
+            clippy_incr = clippy_artifacts[True],
+            remarks = None,  # Exposed via subtargets, not this provider
+        ),
+    ]
+
+def _proc_macro_link_providers(ctx: AnalysisContext, rust_artifacts: dict[LinkStrategy, RustLinkStrategyInfo]) -> list[Provider]:
+    # These are never accessed in the case of proc macros, so just return some dummy
+    # values
+    return [
+        RustLinkInfo(
+            crate = attr_crate(ctx),
+            strategies = rust_artifacts,
+            native_link_deps = ctx.actions.tset(RustNativeLinkDeps),
+            exported_link_deps = ctx.actions.tset(RustExportedLinkDeps),
+            shared_libs = merge_shared_libraries(ctx.actions),
+            third_party_build_info = third_party_build_info(actions = ctx.actions),
+            linkable_graphs = ctx.actions.tset(RustLinkableGraphs),
+        )
+    ]
+
+def _linker_flags(ctx: AnalysisContext) -> LinkerFlags:
+    return LinkerFlags(
+        flags = ctx.attrs.linker_flags,
+        exported_flags = ctx.attrs.exported_linker_flags,
+        exported_post_flags = ctx.attrs.exported_post_linker_flags,
+    )
+
+def _advanced_unstable_link_providers(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    rust_artifacts: dict[LinkStrategy, RustLinkStrategyInfo],
+    link_infos: dict[LibOutputStyle, LinkInfos],
+    linked_object: LinkedObject | None,
+) -> list[Provider]:
+    crate = attr_crate(ctx)
+    pic_behavior = compile_ctx.cxx_toolchain_info.pic_behavior
+    preferred_linkage = Linkage(ctx.attrs.preferred_linkage)
+
+    providers = []
+
+    dep_ctx = compile_ctx.dep_ctx
+
+    inherited_link_infos = inherited_merged_link_infos(ctx, dep_ctx)
+    inherited_shlibs = inherited_shared_libs(ctx, dep_ctx)
+    inherited_graphs_tset = inherited_linkable_graphs(ctx, dep_ctx)
+    inherited_exported_deps_tset = inherited_exported_link_deps(ctx, dep_ctx)
+    inherited_third_party = inherited_third_party_builds(ctx, dep_ctx)
+
+    inherited_graphs = dfs_dedupe_by_label(inherited_graphs_tset)
+    inherited_exported_deps = dfs_dedupe_by_label(inherited_exported_deps_tset)
+
+    # Native link provider.
+    merged_link_info = create_merged_link_info(
+        ctx,
+        pic_behavior,
+        link_infos,
+        deps = inherited_link_infos,
+        exported_deps = filter(None, [d.get(MergedLinkInfo) for d in inherited_exported_deps]),
+        preferred_linkage = preferred_linkage,
+    )
+    providers.append(merged_link_info)
+
+    solibs = {}
+
+    # Add the shared library to the list of shared libs.
+    shlib_name = compile_ctx.soname
+
+    # Only add a shared library if we generated one.
+    if linked_object:
+        solibs[shlib_name] = linked_object
+
+    # Native shared library provider.
+    shared_libs = create_shared_libraries(ctx, solibs)
+    shared_library_info = merge_shared_libraries(
+        ctx.actions,
+        shared_libs,
+        inherited_shlibs,
+    )
+    providers.append(shared_library_info)
+
+    third_party_build_info = create_third_party_build_info(
+        ctx = ctx,
+        shared_libs = shared_libs.libraries,
+        children = inherited_third_party,
+    )
+    providers.append(third_party_build_info)
+
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            linkable_node = create_linkable_node(
+                ctx = ctx,
+                preferred_linkage = preferred_linkage,
+                deps = inherited_graphs,
+                exported_deps = inherited_exported_deps,
+                link_infos = link_infos,
+                shared_libs = shared_libs,
+                linker_flags = _linker_flags(ctx),
+                default_soname = shlib_name,
+                # Link groups have a heuristic in which they assume that a
+                # preferred_linkage = "static" library needs to be linked
+                # into every single link group, instead of just one.
+                # Applying that same heuristic to Rust seems right, but only
+                # if this target actually requested that. Opt ourselves out
+                # if it didn't.
+                ignore_force_static_follows_dependents = preferred_linkage != Linkage("static"),
+                include_in_android_mergemap = getattr(ctx.attrs, "include_in_android_merge_map_output", True),
+            ),
+        ),
+        deps = inherited_graphs + inherited_exported_deps,
+    )
+
+    providers.append(linkable_graph)
+
+    # Omnibus root provider.
+    linkable_root = create_linkable_root(
+        label = ctx.label,
+        name = shlib_name,
+        link_infos = LinkInfos(
+            default = set_link_info_link_whole(link_infos[LibOutputStyle("pic_archive")].default),
+        ),
+        deps = inherited_graphs,
+    )
+    providers.append(linkable_root)
+
+    # Mark libraries that support `dlopen`.
+    if getattr(ctx.attrs, "supports_python_dlopen", False):
+        providers.append(DLOPENABLE_LIBRARY_INFO_MARKER)
+
+    # We never need to add anything to this provider because Rust libraries
+    # cannot act as link group libs, especially given that they only support
+    # auto link groups anyway
+    providers.append(merge_link_group_lib_info(children = inherited_link_group_lib_infos(ctx, compile_ctx.dep_ctx)))
+
+    # Create rust library provider.
+    providers.append(
+        RustLinkInfo(
+            crate = crate,
+            strategies = rust_artifacts,
+            native_link_deps = ctx.actions.tset(
+                RustNativeLinkDeps,
+                children = [
+                    inherited_native_link_deps(ctx, dep_ctx),
+                    # Must be visited after inherited_native_link_deps in dfs order.
+                    ctx.actions.tset(
+                        RustNativeLinkDeps,
+                        value = [(ctx.label.configured_target(), merged_link_info)],
+                    ),
+                ],
+            ),
+            exported_link_deps = inherited_exported_deps_tset,
+            shared_libs = shared_library_info,
+            third_party_build_info = third_party_build_info,
+            linkable_graphs = ctx.actions.tset(
+                RustLinkableGraphs,
+                children = [
+                    inherited_graphs_tset,
+                    # Must be visited after inherited_graphs_tset in dfs order.
+                    ctx.actions.tset(RustLinkableGraphs, value = [linkable_graph]),
+                ],
+            ),
+        )
+    )
+
+    providers.append(
+        create_unix_env_info(
+            actions = ctx.actions,
+            env = UnixEnv(
+                label = ctx.label,
+                native_libs = [shared_libs],
+            ),
+            deps = [dep.dep for dep in resolve_deps(ctx, compile_ctx.dep_ctx)],
+        ),
+    )
+
+    return providers
+
+def _stable_link_providers(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    rust_artifacts: dict[LinkStrategy, RustLinkStrategyInfo],
+    link_infos: dict[LibOutputStyle, LinkInfos],
+    linked_object: LinkedObject | None,
+) -> list[Provider]:
+    providers = []
+
+    crate = attr_crate(ctx)
+
+    native_link_deps, shared_libs, linkable_graphs, exported_link_deps, third_party_builds = _rust_link_providers(ctx, compile_ctx.dep_ctx)
+
+    # Create rust library provider.
+    rust_link_info = RustLinkInfo(
+        crate = crate,
+        strategies = rust_artifacts,
+        native_link_deps = native_link_deps,
+        exported_link_deps = exported_link_deps,
+        shared_libs = shared_libs,
+        third_party_build_info = third_party_build_info(
+            actions = ctx.actions,
+            children = third_party_builds,
+        ),
+        linkable_graphs = linkable_graphs,
+    )
+
+    providers.append(rust_link_info)
+    providers += _native_link_providers(ctx, compile_ctx, link_infos, linked_object, rust_link_info)
+    return providers
+
+def _rust_link_providers(
+    ctx: AnalysisContext, dep_ctx: DepCollectionContext
+) -> (
+    RustNativeLinkDeps,
+    SharedLibraryInfo,
+    RustLinkableGraphs,
+    RustExportedLinkDeps,
+    list[ThirdPartyBuildInfo],
+):
+    native_link_deps = inherited_native_link_deps(ctx, dep_ctx)
+    inherited_shlibs = inherited_shared_libs(ctx, dep_ctx)
+    inherited_graphs = inherited_linkable_graphs(ctx, dep_ctx)
+    inherited_exported_deps = inherited_exported_link_deps(ctx, dep_ctx)
+    inherited_third_party = inherited_third_party_builds(ctx, dep_ctx)
+
+    shared_libs = merge_shared_libraries(
+        ctx.actions,
+        deps = inherited_shlibs,
+    )
+    return (native_link_deps, shared_libs, inherited_graphs, inherited_exported_deps, inherited_third_party)
+
+def _native_link_providers(
+    ctx: AnalysisContext,
+    compile_ctx: CompileContext,
+    link_infos: dict[LibOutputStyle, LinkInfos],
+    linked_object: LinkedObject | None,
+    rust_link_info: RustLinkInfo,
+) -> list[Provider]:
+    """
+    Return the set of providers needed to link Rust as a dependency for native
+    (ie C/C++) code, along with relevant dependencies.
+    """
+
+    # We collected transitive deps in the Rust link providers
+    inherited_shlibs = [rust_link_info.shared_libs]
+    inherited_third_party = rust_link_info.third_party_build_info
+
+    inherited_link_infos = dfs_dedupe_by_label(rust_link_info.native_link_deps)
+    inherited_link_graphs = dfs_dedupe_by_label(rust_link_info.linkable_graphs)
+    inherited_exported_deps = dfs_dedupe_by_label(rust_link_info.exported_link_deps)
+
+    providers = []
+
+    preferred_linkage = Linkage(ctx.attrs.preferred_linkage)
+
+    # Native link provider.
+    providers.append(
+        create_merged_link_info(
+            ctx,
+            compile_ctx.cxx_toolchain_info.pic_behavior,
+            link_infos,
+            deps = inherited_link_infos,
+            exported_deps = filter(None, [d.get(MergedLinkInfo) for d in inherited_exported_deps]),
+            preferred_linkage = preferred_linkage,
+        )
+    )
+
+    solibs = {}
+
+    # Add the shared library to the list of shared libs.
+    shlib_name = compile_ctx.soname
+
+    # Only add a shared library if we generated one.
+    if linked_object:
+        solibs[shlib_name] = linked_object
+
+    # Native shared library provider.
+    shared_libs = create_shared_libraries(ctx, solibs)
+    providers.append(
+        merge_shared_libraries(
+            ctx.actions,
+            shared_libs,
+            inherited_shlibs,
+        )
+    )
+
+    third_party_build_info = create_third_party_build_info(
+        ctx = ctx,
+        shared_libs = shared_libs.libraries,
+        children = [inherited_third_party],
+    )
+    providers.append(third_party_build_info)
+
+    # Omnibus root provider.
+    linkable_root = create_linkable_root(
+        label = ctx.label,
+        name = shlib_name,
+        link_infos = LinkInfos(
+            default = set_link_info_link_whole(link_infos[LibOutputStyle("pic_archive")].default),
+        ),
+        deps = inherited_link_graphs,
+    )
+    providers.append(linkable_root)
+
+    # Mark libraries that support `dlopen`.
+    if getattr(ctx.attrs, "supports_python_dlopen", False):
+        providers.append(DLOPENABLE_LIBRARY_INFO_MARKER)
+
+    linkable_graph = create_linkable_graph(
+        ctx,
+        node = create_linkable_graph_node(
+            ctx,
+            linkable_node = create_linkable_node(
+                ctx = ctx,
+                preferred_linkage = preferred_linkage,
+                deps = inherited_link_graphs,
+                exported_deps = inherited_exported_deps,
+                link_infos = link_infos,
+                shared_libs = shared_libs,
+                linker_flags = _linker_flags(ctx),
+                default_soname = shlib_name,
+                include_in_android_mergemap = getattr(ctx.attrs, "include_in_android_merge_map_output", True),
+            ),
+        ),
+        deps = inherited_link_graphs + inherited_exported_deps,
+    )
+
+    providers.append(linkable_graph)
+
+    # We never need to add anything to this provider because Rust libraries
+    # cannot act as link group libs, especially given that they only support
+    # auto link groups anyway
+    providers.append(merge_link_group_lib_info(children = inherited_link_group_lib_infos(ctx, compile_ctx.dep_ctx)))
+
+    providers.append(
+        create_unix_env_info(
+            actions = ctx.actions,
+            env = UnixEnv(
+                label = ctx.label,
+                native_libs = [shared_libs],
+            ),
+            deps = inherited_exported_deps,
+        ),
+    )
+
+    return providers
+
+# Compute transitive deps. Caller decides whether this is necessary.
+def _compute_transitive_deps(
+    ctx: AnalysisContext, dep_ctx: DepCollectionContext, dep_link_strategy: LinkStrategy
+) -> (
+    dict[MetadataKind, TransitiveDeps],
+    list[ArtifactTSet],
+    set[RustProcMacroMarker],
+):
+    toolchain_info = ctx.attrs._rust_toolchain[RustToolchainInfo]
+    transitive_deps = {m: [] for m in MetadataKind}
+    rust_debug_info = []
+    transitive_proc_macro_deps = set()
+
+    for dep in resolve_rust_deps(ctx, dep_ctx):
+        if dep.proc_macro_marker != None:
+            transitive_proc_macro_deps.add(dep.proc_macro_marker)
+
+            # We don't want to propagate proc macros directly, and they have no transitive deps
+            continue
+        strategy = strategy_info(toolchain_info, dep.info, dep_link_strategy)
+        for m in MetadataKind:
+            transitive_deps[m].append(strategy.singleton_tset[m])
+            transitive_deps[m].append(strategy.transitive_deps[m])
+
+        if strategy.rust_debug_info:
+            rust_debug_info.append(strategy.rust_debug_info)
+
+        transitive_proc_macro_deps.update(strategy.transitive_proc_macro_deps)
+
+    transitive_deps = {m: ctx.actions.tset(TransitiveDeps, children = children) for m, children in transitive_deps.items()}
+
+    return transitive_deps, rust_debug_info, transitive_proc_macro_deps
+
+def rust_library_macro_wrapper(rust_library: typing.Callable) -> typing.Callable:
+    def wrapper(**kwargs):
+        if kwargs.get("proc_macro") == True:
+            name = kwargs["name"]
+            if kwargs.get("crate", None) == None and kwargs.get("crate_dynamic", None) == None:
+                kwargs["crate"] = name.replace("-", "_")
+
+            rust_proc_macro_alias(
+                name = name,
+                actual_exec = ":_" + name,
+                actual_plugin = ":_" + name,
+                default_target_platform = kwargs.get("default_target_platform", None),
+                visibility = kwargs.pop("visibility", []),
+            )
+            kwargs["name"] = "_" + name
+
+        rust_library(**kwargs)
+
+    return wrapper
diff --git a/buck2/prelude/rust/rust_toolchain.bzl b/buck2/prelude/rust/rust_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/rust_toolchain.bzl
@@ -0,0 +1,197 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Typically, rustc has access to a "sysroot," which is a directory tree with a known layout that
+# contains a number of pre-compiled rlibs that are available by default. This includes, for example,
+# the standard library. If explicit sysroot deps are passed on the toolchain, the sysroot is not
+# made available to rustc. Instead, all crates which would normally be members of the sysroot must
+# be passed explicitly here.
+#
+# Most sysroot deps typically behave as if they were transitive dependencies of the crate being
+# compiled. That means they are not guaranteed to be included in the link, and the user must write
+# `extern crate;` to access them. The crates singled out here behave differently in that regard,
+# which is why they are singled out.
+#
+# Toolchains are free to omit any crates they like from this list; those crates will simply not be
+# available in the compilation.
+RustExplicitSysrootDeps = record(
+    core = Dependency | None,
+    proc_macro = Dependency | None,
+    std = Dependency | None,
+    panic_unwind = Dependency | None,
+    panic_abort = Dependency | None,
+    others = list[Dependency],
+)
+
+PanicRuntime = enum("unwind", "abort", "none")
+
+RustSanitizer = enum("address", "cfi", "hwaddress", "kcfi", "leak", "memory", "memtag", "safestack", "shadow-call-stack", "thread")
+
+# FIXME(JakobDegen): These all have default values for historical reasons. Some of them certainly
+# should, but some of them probably shouldn't?
+# @unsorted-dict-items
+rust_toolchain_attrs = {
+    # Report unused dependencies. Requires `nightly_features`.
+    "report_unused_deps": provider_field(bool, default = False),
+    # Rustc target triple to use
+    # https://doc.rust-lang.org/rustc/platform-support.html
+    "rustc_target_triple": provider_field(str | None, default = None),
+    # Extra env variables that should be made available to the rustc executable.
+    "rustc_env": provider_field(dict[str, typing.Any], default = {}),
+    # Baseline compiler config
+    "rustc_flags": provider_field(list[typing.Any], default = []),
+    # Rustc flags, except that they are applied on the command line after the
+    # target's rustc flags
+    "extra_rustc_flags": provider_field(list[typing.Any], default = []),
+    # Path to search for custom target .json files. Requires `nightly_features`.
+    "rust_target_path": provider_field(Dependency | None, default = None),
+    # Flags applied only on check builds
+    "rustc_check_flags": provider_field(list[typing.Any], default = []),
+    # Extra flags when building binaries
+    "rustc_binary_flags": provider_field(list[typing.Any], default = []),
+    # Extra flags for doing building tests
+    "rustc_test_flags": provider_field(list[typing.Any], default = []),
+    # Extra flags when coverage is enabled for a target
+    # FIXME(JakobDegen): Can't use `list[str]` here, because then the default is wrong, but can't
+    # use a non-empty list as the default because lists are mutable
+    "rustc_coverage_flags": provider_field(typing.Any, default = ("-Cinstrument-coverage",)),
+    # Extra env variables that should be made available to the rustdoc executable.
+    "rustdoc_env": provider_field(dict[str, typing.Any], default = {}),
+    # Extra flags for rustdoc invocations
+    "rustdoc_flags": provider_field(list[typing.Any], default = []),
+    # Extra flags to pass to the linker
+    "linker_flags": provider_field(list[typing.Any], default = []),
+    # When you `buck test` a library, also compile and run example code in its
+    # documentation comments.
+    "doctests": provider_field(bool, default = False),
+    # The Rust compiler (rustc)
+    "compiler": provider_field(RunInfo | None, default = None),
+    # Rust documentation extractor (rustdoc)
+    "rustdoc": provider_field(RunInfo | None, default = None),
+    # Clippy (linter) version of the compiler
+    "clippy_driver": provider_field(RunInfo | None, default = None),
+    # The default edition to use, if not specified.
+    "default_edition": provider_field(str | None, default = None),
+    # Lints
+    "allow_lints": provider_field(list[typing.Any], default = []),
+    "deny_lints": provider_field(list[typing.Any], default = []),
+    "warn_lints": provider_field(list[typing.Any], default = []),
+    # Deny-on-Check lints are handled differently depending on the build.
+    #
+    # For check builds, e.g. [check], [diag.json], [clippy.json] subtargets, or the default target
+    # for `rust_library` rules, these lints will be applied as Deny Lints. Importantly, this means
+    # that when you call `buck build :rust_lib` or use tools like arc rust-check or rustfix, these
+    # lints will be surfaced as errors.
+    #
+    # However, for "regular" builds, e.g. when building tests or binaries, or building this target
+    # as a dependency of another target, these flags will be surfaced only as warnings. The primary
+    # benefit here is that you can develop + test your code as normal and will not be blocked by
+    # these lints. However, once you run rust check, or submit your code to phabricator, these
+    # lints will prevent you from landing your code. This way we can introduce lints that we'd like
+    # to deny from our codebase without slowing down your inner dev loop, or encouraging you to
+    # --cap-warns=lint for your projects.
+    "deny_on_check_lints": provider_field(list[typing.Any], default = []),
+    # Clippy configuration file clippy.toml
+    "clippy_toml": provider_field(Artifact | None, default = None),
+    # Setting this enables additional behaviors that improves linking at the
+    # cost of using unstable implementation details of rustc. At the moment,
+    # this is only used for linking rlibs into C++/C builds, instead of using
+    # staticlibs, but that's expected to change. Requires `nightly_features`.
+    #
+    # FIXME(JakobDegen): This should require `explicit_sysroot_deps` in the
+    # future.
+    "advanced_unstable_linking": provider_field(bool, default = False),
+    # Codegen flags for the distributed ThinLTO opt actions.
+    "dist_thin_lto_codegen_flags": provider_field(list[typing.Any], default = []),
+    # Override the implicit sysroot with the provided Artifact containing a directory to
+    # a prebuilt sysroot. Will be forwarded to rustc as `--sysroot=<sysroot_path>`. Only
+    # one of this and `explicit_sysroot_deps` may be set.
+    "sysroot_path": provider_field(Artifact | None, default = None),
+    # See the documentation on the type for details
+    "explicit_sysroot_deps": provider_field(RustExplicitSysrootDeps | None, default = None),
+    # The panic runtime to use. This is a part of the target definition and is
+    # normally inferred by rustc. This field:
+    #
+    #  - Should be set to `"none"` on nostd targets
+    #  - Must be set correctly if `explicit_sysroot_deps` and
+    #    `advanced_unstable_linking` are used. You can find the correct value
+    #    for a given target triple via `rustc --print target-spec-json`
+    #  - Otherwise can typically be safely defaulted to `"unwind"`. It is,
+    #    however, still the preferred way of configuring `-Cpanic=abort`, since
+    #    it makes sure that the flag is consistent across the crate graph.
+    #
+    # It's worth pointing out that the way that rustc handles this is a bit
+    # weird. It requires the panic runtime to be a nostd crate, despite the fact
+    # that it is only ever useful in combination with std. We don't impose such
+    # a requirement.
+    #
+    # FIXME(JakobDegen): Fix `enum` so that we can set `unwind` as the default
+    "panic_runtime": provider_field(PanicRuntime),
+    # Grants the rules permission to use unstable compiler functionality.
+    #
+    # When set, the rules pass `RUSTC_BOOTSTRAP=1` to compiler invocations,
+    # which makes unstable functionality available even on stable-channel
+    # compiler builds. The rules use this for pipelined builds (`-Zno-codegen`)
+    # and to implement the `[expand]`, `[doc-coverage]`, and profiling
+    # subtargets as well as doctests. Toolchains must also set this if their
+    # own flags or the code being compiled rely on unstable functionality
+    # (`-Z` flags, `#![feature(...)]`).
+    #
+    # When unset, builds only use stable compiler functionality: the features
+    # listed above are implemented differently or unavailable, and toolchain
+    # fields that inherently require unstable functionality (see their docs)
+    # may not be set.
+    "nightly_features": provider_field(bool, default = True),
+    # The `cargo llvm-lines` binary - if present, Rust targets have a
+    # `llvm-lines` subtarget
+    "llvm_lines_tool": provider_field(RunInfo | None, default = None),
+    # The `crox` binary from measure-me, if present, used to generate a
+    # self-profile trace subtarget
+    "measureme_crox": provider_field(RunInfo | None, default = None),
+    # Constructs an upload command for the given chrome trace
+    "make_trace_upload": provider_field(typing.Callable[[Artifact], RunInfo] | None, default = None),
+    # Suffix to append onto all -Cmetadata arguments to differentiate the same
+    # crate in different configurations
+    "configuration_hash": provider_field(str | None, default = None),
+    # Error handler used to categorize rust errors encountered by users
+    "rust_error_handler": provider_field(typing.Any, default = None),
+    # LLVM remarks filter (e.g., "all", "inline") - used with -Cremark flag
+    "remarks": provider_field(str | None, default = None),
+    # PGO instrumentation: directory for -Cprofile-generate=<dir>.
+    # Skipped for profiler_builtins to avoid circular dependency.
+    "pgo_generate_dir": provider_field(str | None, default = None),
+    # PGO optimization: profile for -Cprofile-use=<path>.
+    "pgo_profile": provider_field(Artifact | None, default = None),
+    # Sanitizer to enable via -Zsanitizer=<value> (e.g., "address", "thread", "memory", "leak", "cfi", "hwaddress")
+    # See https://doc.rust-lang.org/beta/unstable-book/compiler-flags/sanitizer.html
+    # Requires `nightly_features`.
+    "sanitizer": provider_field(RustSanitizer | None, default = None),
+    # Substrings that are restricted in target-level rustc_flags. Each entry is
+    # checked via a contains() match against every flag. For example, specifying
+    # "target-feature" will block both "-Ctarget-feature=..." and the split
+    # form "-C" followed by "target-feature=...".
+    "restricted_rustc_flags": provider_field(list[typing.Any], default = []),
+    # Under `-Csplit-debuginfo=unpacked`, which the rules pass for the cxx
+    # toolchain's `single` and `split` debug modes, rustc writes each codegen
+    # unit's `.dwo` to `--out-dir` and also packs a copy of it into the rlib or
+    # staticlib, so that a downstream `-Csplit-debuginfo=packed` link could
+    # build a dwp from the archive alone. The rules never link that way: `dwp`
+    # reads the `--out-dir` files, which are tracked as external debug info,
+    # and linkers never pull archive members that define no symbols. The
+    # copies only add to what every dependent compile downloads and every
+    # link materializes, and in debug-heavy builds they are a large share of
+    # rlib bytes. When set, the compile action deletes the `.dwo` members from
+    # rlibs and staticlibs right after rustc writes them, using the cxx
+    # toolchain's archiver (`gnu`, `llvm` or `bsd` archiver types; others keep
+    # the members). No effect when the cxx toolchain's split debug mode is
+    # `none`, or for Apple and Windows targets, whose archives never carry
+    # `.dwo` members.
+    "strip_dwo_from_rlibs": provider_field(bool, default = False),
+}
+
+RustToolchainInfo = provider(fields = rust_toolchain_attrs)
diff --git a/buck2/prelude/rust/sources.bzl b/buck2/prelude/rust/sources.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/sources.bzl
@@ -0,0 +1,144 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _get_artifacts(sources: Artifact) -> list[Artifact]:
+    return [sources]
+
+RustSourcesTSet = transitive_set(
+    args_projections = {
+        "artifacts": _get_artifacts,
+    },
+)
+
+# Sources of all transitive Rust dependencies. This is required for compilation in order to
+# guarantee consistent crate hashes between local and remote actions.
+# See https://github.com/rust-lang/rust/issues/153898
+RustSources = provider(
+    fields = {
+        "tset": RustSourcesTSet,
+    }
+)
+
+def srcs_arg():
+    return {
+        "srcs": attrs.list(
+            attrs.source(),
+            default = [],
+            doc = """
+    The set of Rust source files to be compiled by this target.
+
+    One of the source files is the root module of the crate. By default this is
+    `lib.rs` for libraries, `main.rs` for executables, or the crate's name with
+    `.rs` appended. This can be overridden with the `crate_root` attribute.
+""",
+        ),
+    }
+
+def mapped_srcs_arg():
+    return {
+        "mapped_srcs": attrs.dict(
+            key = attrs.source(),
+            value = attrs.string(),
+            sorted = False,
+            default = {},
+            doc = """
+    Add source files along with a local path mapping. Rust is sensitive to the
+    layout of source files, as the directory structure follows the module
+    structure. However this is awkward if the source file is, for example,
+    generated by another rule. In this case, you can set up a mapping from the
+    actual source path to something that makes sense locally. For example
+    `mapped_srcs = {":generate-module": "src/generated.rs"}`. These are added to
+    the regular `srcs`, so a file should not be listed in both.
+""",
+        ),
+    }
+
+def srcs_filegroup_arg():
+    return {
+        "srcs_filegroup": attrs.option(
+            attrs.dep(providers = [RustSources]),
+            default = None,
+            doc = """
+    Directory of sources already combined together from `srcs` + `mapped_srcs`.
+    This allows sources to be located in a different Buck package than the one
+    containing the rust_library target which compiles those sources.
+
+    When using `srcs_filegroup`, the attributes `srcs` and `mapped_srcs` cannot
+    also be passed, and `crate_root` must be passed.
+""",
+        ),
+    }
+
+def symlinked_srcs(ctx: AnalysisContext) -> Artifact:
+    srcs_filegroup = getattr(ctx.attrs, "srcs_filegroup", None)
+    if srcs_filegroup:
+        if ctx.attrs.srcs:
+            fail("srcs and srcs_filegroup cannot be used together")
+        if ctx.attrs.mapped_srcs:
+            fail("mapped_srcs and srcs_filegroup cannot be used together")
+        if not ctx.attrs.crate_root:
+            fail("crate_root is required when using srcs_filegroup")
+        return srcs_filegroup[DefaultInfo].default_outputs[0]
+
+    if not ctx.attrs.srcs and not ctx.attrs.mapped_srcs:
+        fail("crate has no srcs, mapped_srcs, or srcs_filegroup")
+
+    srcs = {src.short_path: src for src in ctx.attrs.srcs}
+    srcs.update({k: v for v, k in ctx.attrs.mapped_srcs.items()})
+
+    use_cbp = getattr(ctx.attrs, "use_content_based_paths", False)
+
+    if "generated" in getattr(ctx.attrs, "labels", []):
+        # For generated code targets, we always want to copy files in the [sources]
+        # subtarget, never symlink.
+        #
+        # This ensures that IDEs that open the generated file always see the correct
+        # directory structure.
+        #
+        # VS Code will expand symlinks when doing go-to-definition. In normal source
+        # files this takes us back to the correct path, but for generated files the
+        # expanded path may not be a well-formed crate layout.
+        return ctx.actions.copied_dir("__srcs", srcs, has_content_based_path = use_cbp)
+    else:
+        # Decide whether to use symlinked_dir or copied_dir.
+        #
+        # If a source is a prefix of any other source, use copied_dir. This supports
+        # e.g. `srcs = [":foo.crate"]` where :foo.crate is an http_archive, together
+        # with a `mapped_srcs` which overlays additional generated files into that
+        # directory. Symlinked_dir would error in this situation.
+        prefixes = {}
+        for src in sorted(srcs.keys(), key = len, reverse = True):
+            if src in prefixes:
+                return ctx.actions.copied_dir("__srcs", srcs, has_content_based_path = use_cbp)
+            components = src.split("/")
+            for i in range(1, len(components)):
+                prefixes["/".join(components[:i])] = None
+
+    # Otherwise, symlink it.
+    return ctx.actions.symlinked_dir("__srcs", srcs, has_content_based_path = use_cbp)
+
+def _rust_filegroup_impl(ctx: AnalysisContext) -> list[Provider]:
+    srcs = symlinked_srcs(ctx)
+    tset = ctx.actions.tset(
+        RustSourcesTSet,
+        value = srcs,
+        children = [],
+    )
+    return [
+        DefaultInfo(default_output = srcs),
+        RustSources(tset = tset),
+    ]
+
+rust_filegroup = rule(
+    impl = _rust_filegroup_impl,
+    attrs = srcs_arg()
+    | mapped_srcs_arg()
+    | {
+        "use_content_based_paths": attrs.bool(default = True),
+    },
+)
diff --git a/buck2/prelude/rust/targets.bzl b/buck2/prelude/rust/targets.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/targets.bzl
@@ -0,0 +1,33 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:core_rules.bzl", "TargetCpuType")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+
+_cpu = enum(*TargetCpuType)
+
+_OS_TRIPLES = {
+    (Os("linux"), _cpu("arm64")): "aarch64-unknown-linux-gnu",
+    (Os("linux"), _cpu("x86_64")): "x86_64-unknown-linux-gnu",
+    (Os("linux"), _cpu("riscv64")): "riscv64gc-unknown-linux-gnu",
+    (Os("macos"), _cpu("arm64")): "aarch64-apple-darwin",
+    (Os("macos"), _cpu("x86_64")): "x86_64-apple-darwin",
+    (Os("windows"), _cpu("arm64")): "aarch64-pc-windows-msvc",
+    (Os("windows"), _cpu("x86_64")): "x86_64-pc-windows-msvc",
+}
+
+def _exec_triple(ctx: AnalysisContext) -> str | None:
+    exec_os = ctx.attrs._exec_os_type[OsLookup]
+    if exec_os.cpu:
+        return _OS_TRIPLES.get((exec_os.os, _cpu(exec_os.cpu)))
+    else:
+        return None
+
+targets = struct(
+    exec_triple = _exec_triple,
+)
diff --git a/buck2/prelude/rust/tools/BUCK b/buck2/prelude/rust/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/BUCK
@@ -0,0 +1,149 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load(":attrs.bzl", "rust_internal_tools_toolchain")
+load(
+    ":tool_rules.bzl",
+    "get_rustc_cfg",
+    "get_rustc_host_tuple",
+    "linkable_symbol_supports_no_std",
+)
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+get_rustc_cfg(
+    name = "rustc_cfg",
+    visibility = ["PUBLIC"],
+)
+
+get_rustc_host_tuple(
+    name = "rustc_host_tuple",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "extract_link_action",
+    has_content_based_path = True,
+    main = "extract_link_action.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "rustc_action",
+    has_content_based_path = True,
+    main = "rustc_action.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "rustdoc_test_with_resources",
+    has_content_based_path = True,
+    main = "rustdoc_test_with_resources.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "failure_filter_action",
+    has_content_based_path = True,
+    main = "failure_filter_action.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "transitive_dependency_symlinks",
+    has_content_based_path = True,
+    main = "transitive_dependency_symlinks.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "buildscript_run",
+    has_content_based_path = True,
+    main = "buildscript_run.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "from_any_dir",
+    has_content_based_path = True,
+    main = "from_any_dir.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "rustdoc_coverage",
+    has_content_based_path = True,
+    main = "rustdoc_coverage.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "redirect_stdout",
+    has_content_based_path = True,
+    main = "redirect_stdout.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "symlink_only_dir_entry",
+    has_content_based_path = True,
+    main = "symlink_only_dir_entry.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "shared_libraries_symlink_tree",
+    has_content_based_path = True,
+    main = "shared_libraries_symlink_tree.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.python_bootstrap_binary(
+    name = "cd_run",
+    has_content_based_path = True,
+    main = "cd_run.py",
+    visibility = ["PUBLIC"],
+)
+
+prelude.export_file(
+    name = "linkable_symbol.rs",
+    has_content_based_path = True,
+    visibility = ["PUBLIC"],
+)
+
+linkable_symbol_supports_no_std(
+    name = "linkable_symbol_supports_no_std",
+    visibility = ["PUBLIC"],
+)
+
+rust_internal_tools_toolchain(
+    name = "internal_tools_toolchain",
+    visibility = ["PUBLIC"],
+)
+
+prelude.export_file(
+    name = "attrs.bzl",
+    has_content_based_path = True,
+    visibility = ["PUBLIC"],
+)
+
+# Type checking target for Python tool scripts
+prelude.python_library(
+    name = "scripts-typing",
+    srcs = [
+        "buildscript_run.py",
+        "cd_run.py",
+        "extract_link_action.py",
+        "failure_filter_action.py",
+        "redirect_stdout.py",
+        "rustc_action.py",
+        "rustdoc_coverage.py",
+        "rustdoc_test_with_resources.py",
+        "shared_libraries_symlink_tree.py",
+        "symlink_only_dir_entry.py",
+        "transitive_dependency_symlinks.py",
+    ],
+    typing = True,
+)
diff --git a/buck2/prelude/rust/tools/attrs.bzl b/buck2/prelude/rust/tools/attrs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/attrs.bzl
@@ -0,0 +1,39 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _internal_tool(default: str) -> Attr:
+    return attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = default))
+
+# Factored out of prelude//toolchains/rust.bzl to keep only the user-facing
+# configurable attributes there. This list of internal tools is distracting and
+# expected to grow.
+_internal_tool_attrs = {
+    "cd_run": _internal_tool("prelude//rust/tools:cd_run"),
+    "extract_link_action": _internal_tool("prelude//rust/tools:extract_link_action"),
+    "failure_filter_action": _internal_tool("prelude//rust/tools:failure_filter_action"),
+    "from_any_dir": _internal_tool("prelude//rust/tools:from_any_dir"),
+    "redirect_stdout": _internal_tool("prelude//rust/tools:redirect_stdout"),
+    "rustc_action": _internal_tool("prelude//rust/tools:rustc_action"),
+    "rustdoc_coverage": _internal_tool("prelude//rust/tools:rustdoc_coverage"),
+    "rustdoc_test_with_resources": _internal_tool("prelude//rust/tools:rustdoc_test_with_resources"),
+    "shared_libraries_symlink_tree": _internal_tool("prelude//rust/tools:shared_libraries_symlink_tree"),
+    "symlink_only_dir_entry": _internal_tool("prelude//rust/tools:symlink_only_dir_entry"),
+    "transitive_dependency_symlinks_tool": _internal_tool("prelude//rust/tools:transitive_dependency_symlinks"),
+}
+
+RustInternalToolsInfo = provider(fields = {tool: RunInfo for tool in _internal_tool_attrs.keys()})
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    info = RustInternalToolsInfo(**{tool: getattr(ctx.attrs, tool)[RunInfo] for tool in _internal_tool_attrs.keys()})
+    return [DefaultInfo(), info]
+
+rust_internal_tools_toolchain = rule(
+    impl = _impl,
+    attrs = _internal_tool_attrs,
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/rust/tools/buildscript_run.py b/buck2/prelude/rust/tools/buildscript_run.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/buildscript_run.py
@@ -0,0 +1,310 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Run a crate's Cargo buildscript.
+"""
+
+import argparse
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any, IO, NamedTuple, Optional
+
+
+IS_WINDOWS: bool = os.name == "nt"
+TOOL_CWD: str = os.path.join(os.getcwd(), "")
+
+# Sentinel used to mark OUT_DIR-relative paths emitted by buildscripts.
+# We later replace this sentinel with the actual content-addressed path, once that is known.
+OUT_DIR_SENTINEL: str = "${__BUILDSCRIPT_OUT_DIR__}"
+
+
+def eprint(*args: Any, **kwargs: Any) -> None:
+    print(*args, end="\n", file=sys.stderr, flush=True, **kwargs)
+
+
+def cfg_env(rustc_cfg: Path) -> dict[str, str]:
+    with rustc_cfg.open(encoding="utf-8") as f:
+        lines = f.readlines()
+
+    cfgs: dict[str, str] = {}
+    for line in lines:
+        if (
+            line.startswith("unix")
+            or line.startswith("windows")
+            or line.startswith("target_")
+        ):
+            keyval = line.strip().split("=")
+            key = keyval[0]
+            val = keyval[1].replace('"', "") if len(keyval) > 1 else "1"
+
+            key = "CARGO_CFG_" + key.upper()
+            if key in cfgs:
+                cfgs[key] = cfgs[key] + "," + val
+            else:
+                cfgs[key] = val
+
+    return cfgs
+
+
+def create_cwd(path: Path, manifest_dir: Path) -> Path:
+    """Create a directory with most of the same contents as manifest_dir, but
+    excluding Rustup's rust-toolchain.toml configuration file.
+
+    Keeping rust-toolchain.toml goes wrong in the situation that all of the
+    following happen:
+
+      1. toolchains//:rust uses compiler = "rustc", like the
+         system_rust_toolchain.
+
+      2. The rustc in $PATH is rustup's rustc shim.
+
+      3. A third-party dependency has both a rust-toolchain.toml and a build.rs
+         that runs "rustc" or env::var_os("RUSTC"), such as to inspect `rustc
+         --version` or to compile autocfg-style probe code.
+
+    Cargo defines that build scripts run using the package's manifest directory
+    as the current directory, so the rustc subprocess spawned from build.rs
+    would also run in that manifest directory. But other rustc invocations
+    performed by Buck run from the repo root.
+
+    Rustup only looks at one rust-toolchain.toml file, using the nearest one
+    present in any parent directory. The file can set `channel` to control which
+    installed version of rustc to run.
+
+    It is bad if it's possible for the rustc run by a build script vs rustc run
+    by the rest of the build to be different toolchains. In order to configure
+    their crate appropriately, build scripts rely on using the same rustc that
+    their crate will be later compiled by.
+
+    This problem doesn't happen during Cargo-based builds because rustup
+    installs both a cargo shim and a rustc shim. When you run a rustup-managed
+    Cargo, one of the first things it does is define a RUSTUP_TOOLCHAIN
+    environment variable pointing to the rustup channel id of the currently
+    selected cargo. Subsequent invocations of the rustup cargo shim or rustc
+    shim with this variable in the environment no longer pay attention to any
+    rust-toolchain.toml file.
+
+    We cannot follow the same approach because there is no API in rustup for
+    finding out a suitable RUSTUP_TOOLCHAIN value consistent with which
+    toolchain "rustc" currently refers to, and even if there were, it isn't
+    guaranteed that "rustc" refers to a rustup-managed toolchain in the first
+    place.
+    """
+
+    path.mkdir(exist_ok=True)
+
+    for dir_entry in manifest_dir.iterdir():
+        if dir_entry.name not in ["rust-toolchain", "rust-toolchain.toml"]:
+            link = path.joinpath(dir_entry.name)
+            link.unlink(missing_ok=True)
+            link.symlink_to(
+                os.path.relpath(dir_entry, path), target_is_directory=dir_entry.is_dir()
+            )
+
+    return path
+
+
+# In some environments, invoking the rustc binary may actually invoke another
+# tool that fetches the binary from a remote location. This fetch may encounter
+# network errors. Ideally, build scripts that invoke rustc would reliably fail
+# when such a thing happens, but in practice they don't. To mitigate, we
+# manually invoke `rustc --version` and make sure that succeeds.
+def ensure_rustc_available(
+    env: dict[str, str],
+    cwd: Path,
+    target: str,
+) -> None:
+    rustc = env.get("RUSTC")
+    assert rustc is not None, "RUSTC env is missing"
+
+    # NOTE: `HOST` is optional.
+    host = env.get("HOST")
+
+    try:
+        # Run through cmd.exe on Windows so if rustc is a batch script
+        # (like the command_alias trampoline is), it is found relative to
+        # cwd.
+        #
+        # Executing `os.path.join(cwd, rustc)` would also work, but because
+        # of `../` in the path, it's possible to hit path length limits.
+        # Resolving it would remove the `..` but then sometimes things
+        # fail with exit code `3221225725` ("out of stack memory").
+        # I suspect it's some infinite loop brought about by the trampoline
+        # and symlinks.
+        subprocess.check_output(  # noqa: P204
+            [rustc, "--version"],
+            cwd=cwd,
+            shell=IS_WINDOWS,
+        )
+        # A multiplexed sysroot may involve another fetch,
+        # so pass `--target` to check that too.
+        if host != target:
+            subprocess.check_output(  # noqa: P204
+                [rustc, f"--target={target}", "--version"],
+                cwd=cwd,
+                shell=IS_WINDOWS,
+            )
+    except OSError as ex:
+        eprint(f"Failed to run {rustc} because {ex}")
+        sys.exit(1)
+    except subprocess.CalledProcessError as ex:
+        eprint(f"Command failed with exit code {ex.returncode}")
+        eprint(f"Command: {ex.cmd}")
+        if ex.stdout:
+            eprint(f"Stdout: {ex.stdout}")
+        sys.exit(1)
+
+
+def run_buildscript(
+    buildscript: str,
+    env: dict[str, str],
+    cwd: Path,
+) -> str:
+    try:
+        return subprocess.check_output(
+            os.path.abspath(buildscript),
+            encoding="utf-8",
+            env=env,
+            cwd=cwd,
+        )
+    except OSError as ex:
+        print(f"Failed to run {buildscript} because {ex}", file=sys.stderr)
+        sys.exit(1)
+    except subprocess.CalledProcessError as ex:
+        sys.exit(ex.returncode)
+
+
+class Args(NamedTuple):
+    buildscript: str
+    rustc_cfg: Path
+    rustc_host_tuple: Optional[Path]
+    manifest_dir: Path
+    create_cwd: Path
+    outfile: IO[str]
+    rustc_link_lib: bool
+    rustc_link_search: bool
+
+
+def arg_parse() -> Args:
+    parser = argparse.ArgumentParser(description="Run Rust build script")
+    parser.add_argument("--buildscript", type=str, required=True)
+    parser.add_argument("--rustc-cfg", type=Path, required=True)
+    parser.add_argument("--rustc-host-tuple", type=Path)
+    parser.add_argument("--manifest-dir", type=Path, required=True)
+    parser.add_argument("--create-cwd", type=Path, required=True)
+    parser.add_argument("--outfile", type=argparse.FileType("w"), required=True)
+    parser.add_argument("--rustc-link-lib", action="store_true")
+    parser.add_argument("--rustc-link-search", action="store_true")
+
+    return Args(**vars(parser.parse_args()))
+
+
+def main() -> None:  # noqa: C901
+    args = arg_parse()
+
+    env = cfg_env(args.rustc_cfg)
+
+    out_dir = os.getenv("OUT_DIR")
+    assert out_dir is not None, "OUT_DIR env is missing"
+    os.makedirs(out_dir, exist_ok=True)
+    env["OUT_DIR"] = os.path.abspath(out_dir)
+
+    cwd = create_cwd(args.create_cwd, args.manifest_dir)
+    env["CARGO_MANIFEST_DIR"] = os.path.abspath(cwd)
+
+    env = dict(os.environ, **env)
+
+    target = env.get("TARGET")
+    if target is None:
+        assert args.rustc_host_tuple, "TARGET env is missing"
+        with args.rustc_host_tuple.open(encoding="utf-8") as f:
+            target = f.read().strip()
+            env["TARGET"] = target
+
+    if os.sep in env.get("LD", ""):
+        env["LD"] = os.path.abspath(env["LD"])
+    if os.sep in env.get("CC", ""):
+        env["CC"] = os.path.abspath(env["CC"])
+    if os.sep in env.get("CXX", ""):
+        env["CXX"] = os.path.abspath(env["CXX"])
+    if os.sep in env.get("AR", ""):
+        env["AR"] = os.path.abspath(env["AR"])
+
+    ensure_rustc_available(
+        env=env,
+        cwd=cwd,
+        target=target,
+    )
+
+    script_output = run_buildscript(args.buildscript, env=env, cwd=cwd)
+
+    cargo_rustc_cfg_pattern = re.compile("^cargo::?rustc-cfg=(.*)")
+    cargo_rustc_env_pattern = re.compile("^cargo::?rustc-env=(.+?)=(.*)")
+    cargo_rustc_link_lib_pattern = re.compile("^cargo::?rustc-link-lib=(.*)")
+    cargo_rustc_link_search_pattern = re.compile(
+        "^cargo::?rustc-link-search=([a-z]+=)?(.+)"
+    )
+    out_dir_abs = env["OUT_DIR"]
+
+    # Rewrite a path inside OUT_DIR to OUT_DIR_SENTINEL; None if it is elsewhere.
+    def reanchor_out_dir(path: str) -> Optional[str]:
+        if path == out_dir_abs:
+            return OUT_DIR_SENTINEL
+        if path.startswith(out_dir_abs + os.sep):
+            return OUT_DIR_SENTINEL + path[len(out_dir_abs) :]
+        return None
+
+    flags = ""
+    for line in script_output.split("\n"):
+        cargo_rustc_cfg_match = cargo_rustc_cfg_pattern.match(line)
+        if cargo_rustc_cfg_match:
+            value = cargo_rustc_cfg_match.group(1)
+            flags += f"--cfg={value}\n"
+            continue
+        cargo_rustc_env_match = cargo_rustc_env_pattern.match(line)
+        if cargo_rustc_env_match:
+            key = cargo_rustc_env_match.group(1)
+            value = cargo_rustc_env_match.group(2)
+            reanchored = reanchor_out_dir(value)
+            if reanchored is not None:
+                flags += f"--env-set={key}={reanchored}\n"
+            elif value.startswith(TOOL_CWD):
+                relative_path = value[len(TOOL_CWD) :]
+                flags += f"--env-set={key}=$(abspath {relative_path})\n"
+            else:
+                flags += f"--env-set={key}={value}\n"
+            continue
+        cargo_rustc_link_lib_match = cargo_rustc_link_lib_pattern.match(line)
+        if args.rustc_link_lib and cargo_rustc_link_lib_match:
+            value = cargo_rustc_link_lib_match.group(1)
+            flags += f"-l{value}\n"
+            continue
+        cargo_rustc_link_search_match = cargo_rustc_link_search_pattern.match(line)
+        if args.rustc_link_search and cargo_rustc_link_search_match:
+            kind = cargo_rustc_link_search_match.group(1) or ""
+            path = cargo_rustc_link_search_match.group(2)
+            reanchored = reanchor_out_dir(path)
+            if reanchored is not None:
+                flags += f"-L{kind}{reanchored}\n"
+            elif path.startswith(TOOL_CWD):
+                relative_path = path[len(TOOL_CWD) :]
+                flags += f"-L{kind}$(abspath {relative_path})\n"
+            else:
+                # Disregard link search not located within the build script's out dir.
+                pass
+            continue
+        print(line, end="\n")
+    args.outfile.write(flags)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/rust/tools/cd_run.py b/buck2/prelude/rust/tools/cd_run.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/cd_run.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Changes directory and then runs a command
+
+import subprocess
+import sys
+
+
+def main():
+    d = sys.argv[1]
+    res = subprocess.run(sys.argv[2:], cwd=d)
+    sys.exit(res.returncode)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/rust/tools/extract_link_action.py b/buck2/prelude/rust/tools/extract_link_action.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/extract_link_action.py
@@ -0,0 +1,305 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# A "fake" linker command meant to be provided to rustc as `-Clinker={}`. This script extracts
+# from rustc's linker invocation the link inputs that only rustc can provide — the objects it
+# synthesized for this crate — and exports them as outputs to later be consumed by the cxx-driven
+# link of this crate.
+#
+# Everything else on the argv is discarded: the link is performed by cxx, and every flag and
+# library it needs is provided by the toolchain and the dependency graph, the same way it is for
+# a `cxx_binary`. See `process_link_args()` for the exact contract.
+
+import argparse
+import os
+import re
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any, IO, NamedTuple
+
+
+def eprint(*args: Any, **kwargs: Any) -> None:
+    print(*args, end="\n", file=sys.stderr, flush=True, **kwargs)
+
+
+class Args(NamedTuple):
+    out_argsfile: IO[str]
+    out_artifacts: Path
+    out_manifest: IO[str]
+    out_archive: Path | None
+    archiver_argsfile: Path | None
+    linker: list[str]
+
+
+def arg_parse() -> Args:
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--out_argsfile",
+        type=argparse.FileType("w"),
+        required=True,
+    )
+    parser.add_argument(
+        "--out_artifacts",
+        type=Path,
+        required=True,
+    )
+    parser.add_argument(
+        "--out_manifest",
+        type=argparse.FileType("w"),
+        required=True,
+        help="Receives the basenames of the extracted objects, one per line",
+    )
+    # When --out_archive and archiver_argsfile are set, the rustc objects are
+    # additionally collected into an archive. Distributed ThinLTO needs
+    # the objects to arrive as an `ArchiveLinkable` so it can plan a per-object
+    # opt action for each linkable.
+    parser.add_argument(
+        "--out_archive",
+        type=Path,
+        default=None,
+    )
+    parser.add_argument(
+        "--archiver_argsfile",
+        type=Path,
+        default=None,
+        help="File holding the archiver command, one argument per line",
+    )
+    parser.add_argument(
+        "linker",
+        nargs=argparse.REMAINDER,
+        type=str,
+        help="Linker command line",
+    )
+
+    return Args(**vars(parser.parse_args()))
+
+
+def expand_response_files(args: list[str]) -> list[str]:
+    """Inline the contents of any `@file` argument.
+
+    When the argv would exceed the OS command-line limit (which a Rust link
+    line always does on Windows), rustc re-invokes the linker with all
+    arguments in a single `@file`, one argument per line. Three formats are
+    seen in the wild:
+     - UTF-16 with each argument quoted and embedded quotes doubled, for
+       msvc-flavored linkers;
+     - UTF-8 with the same quoting, for direct (non-cc-driver) linkers
+       invoked on a Windows host, e.g. wasm-ld;
+     - UTF-8 with backslashes and spaces escaped by a backslash, for
+       gcc-flavored linkers.
+    The quoted forms leave backslashes raw, so quoting is detected per line
+    before falling back to backslash-unescaping. A backslash-escaped line
+    can never begin with a bare quote (it would be written as `\\"`), so the
+    detection is unambiguous.
+    """
+    expanded = []
+    for arg in args:
+        if not arg.startswith("@"):
+            expanded.append(arg)
+            continue
+        data = Path(arg[1:]).read_bytes()
+        utf16 = data.startswith(b"\xff\xfe") or data.startswith(b"\xfe\xff")
+        text = data.decode("utf-16") if utf16 else data.decode("utf-8-sig")
+        for line in text.splitlines():
+            if not line:
+                continue
+            if len(line) >= 2 and line.startswith('"') and line.endswith('"'):
+                expanded.append(line[1:-1].replace('""', '"'))
+            elif utf16:
+                expanded.append(line)
+            else:
+                expanded.append(re.sub(r"\\(.)", r"\1", line))
+    return expanded
+
+
+def process_link_args(
+    args: list[str], out_artifacts: Path
+) -> tuple[list[str], list[str]]:
+    """Extract rustc's synthesized objects from its linker argv, returning
+    (retained args, objects).
+
+    The objects are the only thing extracted:
+     - the codegen unit objects of the crate itself, which includes the
+       allocator shim module when rustc generates one, and
+     - `symbols.o`, which carries undefined references to the exported and
+       `#[used]` symbols of every linked crate so that the corresponding
+       archive members survive the link.
+
+    The only args retained are wasm-ld `--export` args, which carry the same
+    per-program symbol metadata that `symbols.o` does on ELF (see the comment
+    at the branch). All other flags and libraries rustc puts on its link line
+    are deliberately dropped: the toolchain and the dependency graph are the
+    sole owners of the flags and libraries on the cxx-driven link. A
+    rustc-synthesized file we don't recognize is an error, not something to
+    pass through: it would be a dangling path by the time the link action
+    runs. Version scripts are one known such case, so dylib and cdylib crates
+    cannot currently be linked through this.
+    """
+    retained_args = []
+    objects = []
+    # Original argv entries we handled, and the directories rustc placed
+    # synthesized files in, used to detect files we don't know about.
+    handled = set()
+    temp_dirs = set()
+
+    i = 0
+    size = len(args)
+    while i < size:
+        arg = args[i]
+        if arg.endswith("rcgu.o") or arg.endswith("symbols.o"):
+            path = Path(arg)
+            if path.parent.is_absolute():
+                temp_dirs.add(str(path.parent))
+            handled.add(arg)
+
+            objects.append(shutil.copy(path, out_artifacts))
+            i += 1
+            continue
+
+        # wasm has no `symbols.o`: rustc communicates the crate graph's
+        # exported/kept-alive symbols to wasm-ld as `--export` arguments
+        # instead. Retaining these is acceptable for the same reason
+        # extracting `symbols.o` is — they are per-program symbol metadata,
+        # the analogue of what C compilers embed in object files as wasm
+        # export flags — NOT a precedent for preserving arbitrary flags.
+        elif arg in ("--export", "--export-if-defined"):
+            retained_args.append(arg)
+            if i + 1 < size:
+                handled.add(args[i + 1])
+                retained_args.append(args[i + 1])
+            i += 2
+            continue
+        elif arg.startswith("--export=") or arg.startswith("--export-if-defined="):
+            retained_args.append(arg)
+            i += 1
+            continue
+
+        # Entry-point metadata is the same category: rustc knows whether the
+        # program's entry is a `_start`-style symbol or an exported `main`
+        # with no native entry (`--no-entry`). In C that information is
+        # carried by whether an object defines the entry symbol.
+        elif arg == "--no-entry":
+            retained_args.append(arg)
+            i += 1
+            continue
+        elif arg == "--entry":
+            retained_args.append(arg)
+            if i + 1 < size:
+                handled.add(args[i + 1])
+                retained_args.append(args[i + 1])
+            i += 2
+            continue
+        elif arg.startswith("--entry="):
+            retained_args.append(arg)
+            i += 1
+            continue
+
+        # Debugger-visualizer files (crate-graph natvis, embedded into the
+        # PDB by the linker). Deliberately dropped rather than extracted: the
+        # natvis set is declarable in the dependency graph — the attribute
+        # names an ordinary source file — and C++ treats visualizers as
+        # build/debugger configuration, not compiler output. Marked handled
+        # so the temp-file check stays quiet.
+        elif arg.startswith("/NATVIS:"):
+            handled.add(arg)
+            i += 1
+            continue
+
+        # The msvc-style spelling of `-o` below; the temporary output path
+        # is embedded in the token, so mark it handled.
+        elif arg.startswith("/OUT:"):
+            handled.add(arg)
+            i += 1
+            continue
+
+        # `-o`'s value is a temporary output location that rustc would copy to
+        # the `--emit=link={}` path; the link action provides its own output
+        # path instead. `-L` carries only search paths (the dummy sysroot and
+        # rustc's raw-dylibs temp directory), never a file. Both are marked
+        # handled so their values don't trip the unrecognized-file check
+        # below.
+        elif arg == "-o" or arg == "-L":
+            if i + 1 < size:
+                handled.add(args[i + 1])
+            i += 2  # also skip the flag's value
+            continue
+
+        i += 1
+
+    # Anything left referencing a directory rustc synthesized files into is a
+    # file this tool doesn't know about. It won't exist anymore when the link
+    # action runs (possibly on another host), so it cannot be passed along;
+    # fail loudly rather than silently dropping a link input.
+    leaked = [a for a in args if a not in handled and any(d in a for d in temp_dirs)]
+    if leaked:
+        eprint(
+            "rustc passed link inputs that extract_link_action.py does not know how to extract:"
+        )
+        for a in leaked:
+            eprint(f"  {a}")
+        eprint("Teach process_link_args() about them.")
+        sys.exit(1)
+
+    # rustc always passes at least the crate's own codegen-unit objects, so
+    # extracting nothing means the argv was misparsed. This also backstops the
+    # check above, which is blind when no extraction established `temp_dirs`.
+    if not objects:
+        eprint(
+            "extract_link_action.py: extracted no objects from rustc's link line; teach process_link_args() about whatever form it took:"
+        )
+        for a in args:
+            eprint(f"  {a!r}")
+        sys.exit(1)
+
+    return retained_args, objects
+
+
+def archive_objects(
+    archiver_argsfile: Path, out_archive: Path, objects: list[str]
+) -> None:
+    archiver = archiver_argsfile.read_text().split("\n")
+    archiver = [arg for arg in archiver if arg]
+
+    env = {**os.environ, "ZERO_AR_DATE": "1"}
+    subprocess.check_call([*archiver, str(out_archive), *objects], env=env)
+
+
+def main() -> int:
+    args = arg_parse()
+
+    if args.out_artifacts.exists():
+        shutil.rmtree(args.out_artifacts)
+    os.mkdir(args.out_artifacts)
+
+    archiver_argsfile = args.archiver_argsfile
+    out_archive = args.out_archive
+    archiving = archiver_argsfile is not None and out_archive is not None
+
+    retained_args, objects = process_link_args(
+        expand_response_files(args.linker[1:]),
+        out_artifacts=args.out_artifacts,
+    )
+    args.out_argsfile.write("\n".join(retained_args))
+    args.out_argsfile.close()
+
+    # The manifest carries only basenames: the consumer knows the artifacts
+    # directory as an artifact and resolves members against it, so the
+    # execution-time path of the directory never appears in any output.
+    args.out_manifest.write("\n".join(os.path.basename(o) for o in objects))
+    args.out_manifest.close()
+
+    if archiving:
+        archive_objects(archiver_argsfile, out_archive, objects)
+
+    return 0
+
+
+sys.exit(main())
diff --git a/buck2/prelude/rust/tools/failure_filter_action.py b/buck2/prelude/rust/tools/failure_filter_action.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/failure_filter_action.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Implement a "failure filter" - that is, look at the output of a previous
+# action and see if it failed with respect to downstream actions which need its
+# outputs. This is to allow us to report success if rustc generated the artifact
+# we needed (ie diagnostics) even if the compilation itself failed.
+
+import argparse
+import json
+import os
+import shutil
+import sys
+from typing import Any, IO, NamedTuple, Optional
+
+
+def eprint(*args: Any, **kwargs: Any) -> None:
+    print(*args, end="\n", file=sys.stderr, flush=True, **kwargs)
+
+
+class Args(NamedTuple):
+    build_status: IO[str]
+    required_file: Optional[list[tuple[str, str, str]]]
+    stderr: Optional[IO[str]]
+
+
+def arg_parse() -> Args:
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--build-status",
+        type=argparse.FileType(),
+        required=True,
+    )
+    parser.add_argument(
+        "--required-file",
+        action="append",
+        nargs=3,
+        metavar=("SHORT", "INPUT", "OUTPUT"),
+    )
+    parser.add_argument(
+        "--stderr",
+        type=argparse.FileType(),
+    )
+
+    return Args(**vars(parser.parse_args()))
+
+
+def main() -> int:
+    args = arg_parse()
+
+    if args.stderr:
+        stderr = args.stderr.read()
+        sys.stderr.write(stderr)
+
+    build_status = json.load(args.build_status)
+
+    # Copy all required files to output, and fail with the original exit status
+    # if any are missing. (Ideally we could just do the copy by referring to the
+    # same underlying CAS object, which would avoid having to move the actual
+    # bytes around at all.)
+    if args.required_file:
+        for short, inp, out in args.required_file:
+            if short in build_status["files"]:
+                try:
+                    # Try a hard link to avoid unnecessary copies
+                    os.link(inp, out)
+                except OSError:
+                    # Fall back to real copy if that doesn't work
+                    shutil.copy(inp, out)
+            else:
+                eprint(f"Missing required input file {short} ({inp})")
+                return build_status["status"]
+
+    # If all the required files were present, then success regardless of
+    # original status.
+    return 0
+
+
+sys.exit(main())
diff --git a/buck2/prelude/rust/tools/from_any_dir.py b/buck2/prelude/rust/tools/from_any_dir.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/from_any_dir.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+See explanation in buck2/prelude/rust/cargo_buildscript.bzl:_make_cc_shim
+"""
+
+import argparse
+import os
+import sys
+from pathlib import Path
+from pprint import pformat
+from typing import NamedTuple
+
+
+class Args(NamedTuple):
+    cwd: Path
+    cc: list[str]
+
+
+def arg_parse() -> Args:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--cwd", type=Path, required=True)
+    parser.add_argument("cc", nargs=argparse.REMAINDER, type=str)
+    return Args(**vars(parser.parse_args()))
+
+
+def main():
+    args = arg_parse()
+
+    original_cwd = args.cwd.resolve()
+    interim_cwd = Path.cwd().resolve()
+    if original_cwd.is_relative_to(interim_cwd):
+        interim_cwd = interim_cwd.relative_to(original_cwd, walk_up=True)
+
+    placeholder = "\\${..}\\" if os.name == "nt" else "${..}/"
+    cc = [arg.replace(placeholder, f"{interim_cwd}{os.sep}") for arg in args.cc]
+
+    # TODO: figure out where this comes from and why it doesn't work
+    #   Action failed: fbsource//third-party/rust/vendor/aws-lc-sys:0.37-build-script-main-run (buildscript)
+    #   COMPILER: buck-out/v2/art/fbsource/220d36cb84017ab6/third-party/rust/vendor/aws-lc-sys/__0.37-build-script-main-run__/__cc_shim.sh
+    #   ARGS: ["-Wall", "-Wextra", "-gdwarf-5", "-fembed-bitcode=off", "buck-out/v2/art/fbsource/220d36cb84017ab6/third-party/rust/vendor/aws-lc-sys/__0.37-build-script-main-run__/cwd/aws-lc/tests/compiler_features_tests/memcmp_invalid_stripped_check.c", "-Wno-unused-parameter", "-o", "buck-out/v2/art/fbsource/220d36cb84017ab6/third-party/rust/vendor/aws-lc-sys/__0.37-build-script-main-run__/OUT_DIR/memcmp_invalid_stripped_check"]
+    #   ERROR: ld.lld: error: unable to find library -lomp
+    #   OUTPUT: Failed to compile memcmp_invalid_stripped_check
+    cc = list(filter(lambda arg: arg != "-Wl,-lomp", cc))
+
+    # TODO: figure out why this flag passes `is_flag_supported` and is then rejected by the assembler.
+    #
+    #   Action failed: fbsource//third-party/rust/vendor/aws-lc-sys:0.42-build (buildscript)
+    #   clang: error: unsupported argument '--debug-prefix-map=/re_cwd/buck-out/v2/art/fbsource/third-party/rust/vendor/aws-lc-sys/__0.42-build__/output_artifacts/cwd=' to option '-Wa,'
+    #
+    # The relevant code in third-party/rust/vendor/aws-lc-sys-0.42.0/builder/cc_builder.rs is:
+    #
+    #   let asm_flag = format!("-Wa,--debug-prefix-map={path_str}=");
+    #   if cc_build.is_flag_supported(&asm_flag).unwrap_or(false) {
+    #       cc_build.asm_flag(asm_flag);
+    #   }
+    cc = list(filter(lambda arg: not arg.startswith("-Wa,--debug-prefix-map="), cc))
+
+    os.chdir(args.cwd)
+    try:
+        os.execl(cc[0], cc[0], *cc[1:])
+    except Exception:
+        print(f"exec failed: {pformat(cc)}", file=sys.stderr)
+        raise
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/rust/tools/linkable_symbol.rs b/buck2/prelude/rust/tools/linkable_symbol.rs
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/linkable_symbol.rs
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+#![cfg_attr(set_nostd, no_std)]
+
+#[cfg(any(rust_linkable_symbol_content_bytes, rust_linkable_symbol_getter_bytes))]
+#[repr(C)]
+#[cfg_attr(rust_linkable_symbol_align_bytes = "2", repr(align(2)))]
+#[cfg_attr(rust_linkable_symbol_align_bytes = "4", repr(align(4)))]
+#[cfg_attr(rust_linkable_symbol_align_bytes = "8", repr(align(8)))]
+struct Aligned<Bytes: ?Sized> {
+    bytes: Bytes,
+}
+
+#[cfg(rust_linkable_symbol_content_str)]
+#[used]
+#[unsafe(export_name = env!("LINKABLE_SYMBOL"))]
+pub static LINKABLE_SYMBOL: &str = include_str!("content");
+
+#[cfg(rust_linkable_symbol_content_bytes)]
+#[used]
+#[unsafe(export_name = env!("LINKABLE_SYMBOL"))]
+pub static LINKABLE_SYMBOL: &Aligned<[u8]> = &Aligned {
+    bytes: *include_bytes!("content"),
+};
+
+#[cfg(rust_linkable_symbol_getter_str)]
+pub const fn get() -> &'static str {
+    unsafe extern "Rust" {
+        #[link_name = env!("LINKABLE_SYMBOL")]
+        static LINKABLE_SYMBOL: &'static str;
+    }
+    unsafe { LINKABLE_SYMBOL }
+}
+
+#[cfg(rust_linkable_symbol_getter_bytes)]
+pub const fn get() -> &'static [u8] {
+    unsafe extern "Rust" {
+        #[link_name = env!("LINKABLE_SYMBOL")]
+        static LINKABLE_SYMBOL: &'static Aligned<[u8]>;
+    }
+    unsafe { &LINKABLE_SYMBOL.bytes }
+}
diff --git a/buck2/prelude/rust/tools/redirect_stdout.py b/buck2/prelude/rust/tools/redirect_stdout.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/redirect_stdout.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Wrapper around `cargo llvm-lines` that redirects stdout to a file
+
+import subprocess
+import sys
+
+
+def main():
+    if len(sys.argv) < 3:
+        raise ValueError("expected at least 2 arguments")
+    out = sys.argv[1]
+    with open(out, "w") as f:
+        res = subprocess.run(sys.argv[2:], stdout=f)
+    sys.exit(res.returncode)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/rust/tools/rustc_action.py b/buck2/prelude/rust/tools/rustc_action.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/rustc_action.py
@@ -0,0 +1,557 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Wrapper for rustc (or similar, like rustdoc). This wrapper does a few pieces
+# of post-processing on the json-formatted diagnostics:
+# - (preprocessing) resolve env vars referring to paths to absolute paths
+# - write the rendered form to a text diagnostic output, and also to stderr
+# - annotate unused crate messages with buck target info for downstream tooling,
+#   and also generated a rendered version
+# - generate a build status json when using failure filtering
+#
+# This is closely coupled to `_rustc_invoke` in `build.bzl`
+
+import argparse
+import asyncio
+import json
+import os
+import platform
+import shlex
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+from typing import Any, IO, NamedTuple, Optional
+
+
+# Sentinel used to mark OUT_DIR-relative paths emitted by buildscripts.
+# We later replace this sentinel with the actual content-addressed path, once that is known.
+OUT_DIR_SENTINEL: str = "${__BUILDSCRIPT_OUT_DIR__}"
+
+DEBUG = False
+
+INHERITED_ENV = [
+    "RUSTC_LOG",
+    "RUST_BACKTRACE",
+    "PATH",
+    "PWD",
+    "HOME",
+    "RUSTUP_HOME",
+    "TMPDIR",
+    # Required on Windows
+    "LOCALAPPDATA",
+    "PROGRAMDATA",
+    "TEMP",
+    "TMP",
+    # TODO(andirauter): Required by RE. Remove them when no longer required T119466023
+    "EXECUTION_ID",
+    "SESSION_ID",
+    "ACTION_DIGEST",
+    "RE_PLATFORM",
+    "CAS_DAEMON_PORT",
+    "CAS_DAEMON_ADDR",
+    # Required by Dotslash, which is how the Rust toolchain is shipped on Mac.
+    "USER",
+    "DOTSLASH_CACHE",
+    # Required to run Python on Windows (for linker wrapper).
+    "SYSTEMROOT",
+    # Required on Windows for getpass.getuser() to work.
+    "USERNAME",
+    # Option to disable hg pre-fork client.
+    # We might pass it to avoid long-running process created inside a per-action cgroup.
+    # Such long-running process make it impossible to clean up systemd slices.
+    # Context https://fb.workplace.com/groups/mercurialusers/permalink/2901424916673036/
+    "CHGDISABLE",
+    # Nix
+    "NIX_BINTOOLS",
+    "NIX_BINTOOLS_FOR_TARGET",
+    "NIX_BINTOOLS_WRAPPER_TARGET_HOST_*",
+    "NIX_BINTOOLS_WRAPPER_TARGET_TARGET_*",
+    "NIX_CC",
+    "NIX_CC_FOR_TARGET",
+    "NIX_CC_WRAPPER_TARGET_HOST_*",
+    "NIX_CC_WRAPPER_TARGET_TARGET_*",
+    "NIX_CFLAGS_COMPILE",
+    "NIX_CFLAGS_COMPILE_FOR_TARGET",
+    "NIX_COREFOUNDATION_RPATH",
+    "NIX_DEBUG",
+    "NIX_DONT_SET_RPATH",
+    "NIX_DONT_SET_RPATH_FOR_BUILD",
+    "NIX_ENFORCE_NO_NATIVE",
+    "NIX_HARDENING_ENABLE",
+    "NIX_IGNORE_LD_THROUGH_GCC",
+    "NIX_LDFLAGS",
+    "NIX_LDFLAGS_FOR_TARGET",
+    "NIX_NO_SELF_RPATH",
+]
+
+
+def eprint(*args: Any, **kwargs: Any) -> None:
+    print(*args, end="\n", file=sys.stderr, flush=True, **kwargs)
+
+
+if sys.version_info[:2] < (3, 7):
+    eprint("Python 3.7 or newer is required!")
+    eprint(f"Using {platform.python_version()} from {sys.executable}")
+    sys.exit(1)
+
+
+def key_value_arg(s: str) -> tuple[str, str]:
+    s = arg_eval(s)
+    key_value = s.split("=", maxsplit=1)
+    if len(key_value) == 2:
+        return (key_value[0], key_value[1])
+    raise argparse.ArgumentTypeError(f"expected the form `key=value` for `{s}`")
+
+
+class Args(NamedTuple):
+    diag_json: Optional[IO[bytes]]
+    diag_txt: Optional[IO[bytes]]
+    env: Optional[list[tuple[str, str]]]
+    path_env: Optional[list[tuple[str, str]]]
+    remap_cwd_prefix: Optional[str]
+    crate_map: Optional[list[tuple[str, str]]]
+    buck_target: Optional[str]
+    failure_filter: Optional[IO[bytes]]
+    required_output: Optional[list[tuple[str, str]]]
+    echo: Optional[IO[bytes]]
+    strip_dwo_members: Optional[str]
+    archiver: Optional[list[str]]
+    archiver_deterministic: bool
+    rustc: list[str]
+
+
+def arg_parse() -> Args:
+    # Command line is <action.py> [args] -- rustc command line
+    parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
+    parser.add_argument(
+        "--diag-json",
+        type=argparse.FileType("wb"),
+        help="Json-formatted diagnostic output "
+        "(assumes compiler is invoked with --error-format=json)",
+    )
+    parser.add_argument(
+        "--diag-txt",
+        type=argparse.FileType("wb"),
+        help="Rendered text diagnostic output (also streamed to stderr)",
+    )
+    parser.add_argument(
+        "--env",
+        action="append",
+        type=key_value_arg,
+        metavar="NAME=VALUE",
+        help="Set environment",
+    )
+    parser.add_argument(
+        "--path-env",
+        action="append",
+        type=key_value_arg,
+        metavar="NAME=PATH",
+        help="Set path environment (to be made absolute)",
+    )
+    parser.add_argument(
+        "--remap-cwd-prefix",
+        help="Remap paths under the current working directory to this path prefix",
+    )
+    parser.add_argument(
+        "--crate-map",
+        action="append",
+        type=key_value_arg,
+        metavar="CRATE=TARGET",
+        help="Crate name to target map for unused crate diagnostics",
+    )
+    parser.add_argument(
+        "--buck-target",
+        help="Buck target for crate, used for unused crate diagnostics",
+    )
+    parser.add_argument(
+        "--failure-filter",
+        type=argparse.FileType("wb"),
+        help="Consider a failure as success so long as we got some usable diagnostics",
+        metavar="build-status.json",
+    )
+    parser.add_argument(
+        "--required-output",
+        action="append",
+        nargs=2,
+        metavar=("SHORT", "PATH"),
+        help="Required output path we expect rustc to generate "
+        "(and filled with a placeholder on a filtered failure)",
+    )
+    parser.add_argument(
+        "--echo",
+        type=argparse.FileType("wb"),
+        help="Write the input command line to this file, without running it",
+    )
+    parser.add_argument(
+        "--strip-dwo-members",
+        metavar="ARCHIVE",
+        help="Archive (rlib or staticlib) written by the compiler from which "
+        "to delete every `.dwo` member after a successful compile",
+    )
+    parser.add_argument(
+        "--archiver",
+        action="append",
+        metavar="ARG",
+        help="Archiver command used by --strip-dwo-members, one argument per occurrence",
+    )
+    parser.add_argument(
+        "--archiver-deterministic",
+        action="store_true",
+        help="Pass the `D` modifier to the archiver so the rewritten archive carries no timestamps",
+    )
+    parser.add_argument(
+        "rustc",
+        nargs=argparse.REMAINDER,
+        type=arg_eval,
+        help="Compiler command line",
+    )
+
+    args = Args(**vars(parser.parse_args()))
+    if args.strip_dwo_members is not None and not args.archiver:
+        parser.error("--strip-dwo-members requires --archiver")
+    return args
+
+
+def arg_eval(arg: str) -> str:
+    """
+    Expand the following two special cases:
+        --extern=$(cat buck-out/v2/gen/foo.txt)=buck-out/dev/gen/libfoo.rlib
+        --env-set=FOO=$(abspath buck-out/v2/gen/foo.txt)
+    """
+    expanded = ""
+
+    while True:
+        begin = arg.find("$(")
+        if begin == -1:
+            return expanded + arg
+        expanded += arg[:begin]
+        if arg[begin:].startswith("$(cat "):
+            begin += len("$(cat ")
+            path, rest = arg[begin:].split(")", maxsplit=1)
+            with open(path, encoding="utf-8") as f:
+                expanded += f.read().strip()
+            arg = rest
+        elif arg[begin:].startswith("$(abspath "):
+            begin += len("$(abspath ")
+            path, rest = arg[begin:].split(")", maxsplit=1)
+            expanded += os.path.abspath(path)
+            arg = rest
+        else:
+            expanded += "$("
+            arg = arg[begin + len("$(") :]
+
+
+def inherited_env() -> dict[str, str]:
+    env = {}
+    for pattern in INHERITED_ENV:
+        if pattern.endswith("*"):
+            for k in os.environ:
+                if k.startswith(pattern[:-1]):
+                    env[k] = os.environ[k]
+        elif pattern in os.environ:
+            env[pattern] = os.environ[pattern]
+    return env
+
+
+# The archiver's `d` operation names each member to delete and rewrites the
+# whole archive, so all members should go in one invocation. Keep each
+# invocation's argv under the smallest command-line limit of the hosts the
+# rules run on (Windows: 32767 characters).
+ARCHIVER_ARGV_BUDGET = 30_000
+
+
+def strip_dwo_members(
+    archiver: list[str], archive: str, deterministic: bool, env: dict[str, str]
+) -> int:
+    """Delete the `.dwo` members the compiler packed into an rlib or staticlib.
+
+    Under `-Csplit-debuginfo=unpacked`, rustc writes each codegen unit's `.dwo`
+    to `--out-dir` and also copies it into the archive, so that a downstream
+    `-Csplit-debuginfo=packed` link could build a dwp from the archive alone.
+    The rules never link that way: `dwp` reads the `--out-dir` files, and
+    linkers never pull archive members that define no symbols. The copies are
+    dead weight for every consumer of the archive. The archive is left
+    untouched when it has no `.dwo` members.
+    """
+    # Apple's archiver takes its deterministic mode from the environment.
+    env = {**env, "ZERO_AR_DATE": "1"}
+
+    def members() -> list[str]:
+        listing = subprocess.run(
+            [*archiver, "t", archive], stdout=subprocess.PIPE, env=env, check=True
+        )
+        return [m for m in listing.stdout.decode().splitlines() if m.endswith(".dwo")]
+
+    try:
+        dwo_members = members()
+        if not dwo_members:
+            return 0
+
+        # GNU-style archivers delete one member per name given, so a name that
+        # occurs twice must be given twice. rustc never produces duplicates
+        # within one archive; the check below catches it if that changes.
+        delete = [*archiver, "dD" if deterministic else "d", archive]
+        budget = ARCHIVER_ARGV_BUDGET - sum(len(arg) + 1 for arg in delete)
+        chunks: list[list[str]] = [[]]
+        used = 0
+        for member in dwo_members:
+            if chunks[-1] and used + len(member) + 1 > budget:
+                chunks.append([])
+                used = 0
+            chunks[-1].append(member)
+            used += len(member) + 1
+        for chunk in chunks:
+            subprocess.run([*delete, *chunk], env=env, check=True)
+
+        remaining = members()
+        if remaining:
+            eprint(f"{archive} still has .dwo members after deleting them: {remaining}")
+            return 1
+    except subprocess.CalledProcessError as e:
+        eprint(f"failed to strip .dwo members from {archive}: {e}")
+        return e.returncode or 1
+
+    return 0
+
+
+async def handle_output(  # noqa: C901
+    proc: asyncio.subprocess.Process,
+    args: Args,
+    crate_map: dict[str, str],
+) -> bool:
+    got_error_diag = False
+
+    proc_stderr = proc.stderr
+    assert proc_stderr is not None
+
+    while True:
+        line = await proc_stderr.readline()
+
+        if line is None or line == b"":
+            break
+
+        try:
+            diag = json.loads(line)
+        except json.JSONDecodeError:
+            sys.stderr.buffer.write(line + b"\n")  # Passthrough
+            continue
+
+        if DEBUG:
+            print(f"diag={repr(diag)}", end="\n")
+
+        if "unused_extern_names" in diag:
+            unused_names = diag["unused_extern_names"]
+
+            # Empty unused_extern_names is just noise.
+            # This happens when there are no unused crates.
+            if not unused_names:
+                continue
+
+            # Treat error-level unused dep warnings as errors
+            if diag.get("lint_level") in ("deny", "forbid"):
+                got_error_diag = True
+
+            # Add more information to unused crate warnings.
+            if args.buck_target:
+                rendered_unused = []
+                for name in unused_names:
+                    if name in crate_map:
+                        rendered_unused.append(f"{crate_map[name]}: {name}")
+                    else:
+                        rendered_unused.append(f"{name}")
+                rendered_unused.sort()
+                rendered_unused = "\n    ".join(rendered_unused)
+
+                diag["buck_target"] = args.buck_target
+                diag["rendered"] = (
+                    f"Target `{args.buck_target}` has unused dependencies:\n"
+                    f"    {rendered_unused}"
+                )
+            diag["unused_deps"] = {
+                name: crate_map[name] for name in unused_names if name in crate_map
+            }
+        else:
+            if diag.get("level") == "error":
+                got_error_diag = True
+
+        # Emit json
+        if args.diag_json:
+            args.diag_json.write(
+                json.dumps(diag, separators=(",", ":")).encode() + b"\n"
+            )
+
+        # Emit rendered text version
+        if "rendered" in diag:
+            rendered = diag["rendered"].encode() + b"\n"
+            if args.diag_txt:
+                args.diag_txt.write(rendered)
+            sys.stderr.buffer.write(rendered)
+
+    if args.diag_json:
+        args.diag_json.close()
+    if args.diag_txt:
+        args.diag_txt.close()
+
+    return got_error_diag
+
+
+async def main() -> int:  # noqa: C901
+    args = arg_parse()
+
+    if args.echo:
+        args.echo.write("".join(arg + "\n" for arg in args.rustc).encode("utf-8"))
+        return 0
+
+    # Inherit a very limited initial environment, then add the new things
+    env = inherited_env()
+    if args.env:
+        # Unescape previously escaped newlines.
+        # Example: \\\\n\\n -> \\\n\n -> \\n\n
+        env.update(
+            {k: v.replace("\\n", "\n").replace("\\\n", "\\n") for k, v in args.env}
+        )
+    if args.path_env:
+        env.update({k: os.path.abspath(v) for k, v in args.path_env})
+
+    crate_map = dict(args.crate_map) if args.crate_map else {}
+
+    if DEBUG:
+        print(f"args {repr(args)} env {env} crate_map {crate_map}", end="\n")
+
+    separator = args.rustc.index("--rustc-action-separator")
+    rustc_cmd, rustc_args_orig = args.rustc[:separator], args.rustc[separator + 1 :]
+
+    out_dir = env.get("OUT_DIR")
+
+    rustc_args = []
+    for arg in rustc_args_orig:
+        # Resolve OUT_DIR_SENTINEL to the consumer's canonical OUT_DIR.
+        if out_dir is not None and OUT_DIR_SENTINEL in arg:
+            arg = arg.replace(OUT_DIR_SENTINEL, out_dir)
+        # Build.bzl uses the following expression to generate remap flags:
+        #   cmd_args("--remap-path-prefix=", ... "=", ctx.label.path, path_sep, delimiter = "")
+        # The ctx.label.path (which is of type StarlarkCellPath) has the
+        # inconvenient behavior that if the label's package has fewer than two
+        # components, it gets an extra "./" prepended. So for targets //:repro
+        # and //one:repro and //one/two:repro we would get remap flags with the
+        # right-hand side as "./" and "./one/" and "one/two/". In compiler
+        # diagnostics we would never want this leading "./" so strip it off.
+        if arg.startswith("--remap-path-prefix="):
+            flag, buck_out, mapped = arg.split("=", 2)
+            if mapped.startswith("./"):
+                mapped = mapped[2:]
+            arg = f"{flag}={buck_out}={mapped}"
+
+        # While the env-set feature is unstable, allow it to be used with stable
+        # rustc by translating from a rustc flag to environment variables set
+        # during the execution of the rustc subprocess. Our handling of Cargo
+        # build scripts relies on `--env-set` as the implementation of "cargo:rustc-env".
+        # Tracking issue: https://github.com/rust-lang/rust/issues/118372
+        if arg.startswith("--env-set="):
+            flag, key, value = arg.split("=", 2)
+            env[key] = value
+            continue
+
+        rustc_args.append(arg)
+
+    if args.remap_cwd_prefix is not None:
+        rustc_args.append(f"--remap-path-prefix={os.getcwd()}={args.remap_cwd_prefix}")
+        rustc_args.append(
+            "--remap-path-prefix={}={}".format(
+                os.path.realpath(os.getcwd()), args.remap_cwd_prefix
+            )
+        )
+
+    with tempfile.NamedTemporaryFile(
+        mode="wb",
+        prefix="rustc-args-",
+        suffix=".txt",
+        delete=False,
+        # This isn't set when running doctests. Once that's fixed, we won't need
+        # `tempfile`
+        dir=os.environ.get("BUCK_SCRATCH_PATH", None),
+    ) as args_file:
+        args_file.write("\n".join(rustc_args).encode() + b"\n")
+        args_file.flush()
+        args_file.close()
+        # Kick off the action
+        proc = await asyncio.create_subprocess_exec(
+            *rustc_cmd,
+            "@" + args_file.name,
+            env=env,
+            stdin=subprocess.DEVNULL,
+            stdout=None,  # Inherit
+            stderr=subprocess.PIPE,
+            limit=20_000_000,
+        )
+        got_error_diag = await handle_output(proc, args, crate_map)
+        res = await proc.wait()
+
+        # TODO: When Python 3.12 becomes the baseline, replace this with:
+        #   `NamedTemporaryFile(delete=True, delete_on_close=False)`
+        os.unlink(args_file.name)
+
+    if DEBUG:
+        print(
+            f"res={repr(res)} "
+            f"got_error_diag={got_error_diag} "
+            f"args.failure_filter {args.failure_filter}",
+            end="\n",
+        )
+
+    # If rustc is reporting a silent error, make it loud
+    if res == 0 and got_error_diag:
+        res = 1
+
+    if res == 0 and args.strip_dwo_members is not None:
+        assert args.archiver is not None
+        res = strip_dwo_members(
+            args.archiver, args.strip_dwo_members, args.archiver_deterministic, env
+        )
+
+    # Check for death by signal - this is always considered a failure
+    if res < 0:
+        cmdline = shlex.join(rustc_cmd + rustc_args)
+        eprint(f"Command exited with signal {-res}: command line: {cmdline}")
+    elif args.failure_filter:
+        # If failure filtering is enabled, then getting an error diagnostic is also
+        # considered a success. That is, if rustc exited with an error status, but
+        # we saw a fatal error diagnostic, we can still report a zero exit status.
+        # This still means we had an error if someone wanted one of the other output
+        # artifacts as an input, but the failure filter action will handle that by
+        # examining the build_status json output.
+
+        required_output = args.required_output or []
+
+        # We need to create a build status output, including the list of output
+        # files which were *actuallyq* created. We use the short paths as the
+        # logical filename rather than the actual full path, since that won't
+        # mean much to a downstream action.
+        build_status = {
+            "status": res,
+            "files": [short for short, path in required_output if Path(path).exists()],
+        }
+        args.failure_filter.write(
+            json.dumps(build_status, separators=(",", ":")).encode() + b"\n"
+        )
+
+        # OK to actually report success, but keep buck happy by making sure all
+        # the required outputs are present
+        if got_error_diag and res != 0:
+            for _short, path in required_output:
+                path = Path(path)
+                if not path.exists():
+                    path.touch()
+            res = 0
+
+    return res
+
+
+sys.exit(asyncio.run(main()))
diff --git a/buck2/prelude/rust/tools/rustdoc_coverage.py b/buck2/prelude/rust/tools/rustdoc_coverage.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/rustdoc_coverage.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+import re
+import subprocess
+from pathlib import Path
+from typing import NamedTuple
+
+
+class Args(NamedTuple):
+    out: Path
+    cmd: list[str]
+
+
+def arg_parse() -> Args:
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "out",
+        type=Path,
+        help="path to output",
+    )
+    parser.add_argument("cmd", nargs=argparse.REMAINDER, help="command to run")
+    return Args(**vars(parser.parse_args()))
+
+
+_REGEX = re.compile(r"(\d+(?:\.\d+)?)")
+
+
+def main():
+    args = arg_parse()
+    stdout = subprocess.check_output(args.cmd, text=True)
+
+    with open(args.out, "w") as f:
+        # not using json output until https://github.com/rust-lang/rust/issues/117291 is fixed
+        # stdout looks like...
+        # +--------+------------+------------+------------+------------+
+        # | File   | Documented | Percentage |   Examples | Percentage |
+        # +--------+------------+------------+------------+------------+
+        # | foo.rs |          1 |       1.0% |          0 |       0.0% |
+        # | bar.rs |          2 |       2.1% |          0 |       0.0% |
+        # +--------+------------+------------+------------+------------+
+        # | Total  |          3 |       3.1% |          0 |       0.0% |
+        # +--------+------------+------------+------------+------------+
+        total_line = stdout.splitlines()[-2]
+        nums = _REGEX.findall(total_line)
+        if len(nums) != 4:
+            raise Exception(
+                f"using regex `{_REGEX.pattern}`, expected to find 4 numbers, got {len(nums)} "
+                f"for line: '{total_line}'"
+            )
+        json.dump(
+            {
+                "documented": nums[0],
+                "documented_percentage": nums[1],
+                "examples": nums[2],
+                "examples_percentage": nums[3],
+            },
+            f,
+        )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/rust/tools/rustdoc_test_with_resources.py b/buck2/prelude/rust/tools/rustdoc_test_with_resources.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/rustdoc_test_with_resources.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""
+Wrapper for a rustdoc-generated doctest binary, to relocate the executable into
+the location from which shared object dependencies using relative paths for
+dynamic linking can be resolved correctly, and where the resources.json required
+by Folly's resources implementation is available.
+
+    rustdoc_test_with_resources.py \
+        --resources buck-out/path/to/resources.json \
+        /tmp/rustdoctestABCXYZ/rust_out [ARGS]...
+
+This will copy the executable rust_out to buck-out/path/to/rustdoctestABCXYZ and
+exec it from there with the rest of the args.
+"""
+
+import argparse
+import os
+import shutil
+from pathlib import Path
+from typing import NamedTuple
+
+
+class Args(NamedTuple):
+    resources: Path
+    test: list[str]
+
+
+def arg_parse() -> Args:
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--resources",
+        type=Path,
+        help="path of resources.json file",
+        metavar="resources.json",
+        required=True,
+    )
+    parser.add_argument(
+        "test",
+        nargs=argparse.REMAINDER,
+        type=str,
+        help="command line invocation of the compiled rustdoc test",
+    )
+    return Args(**vars(parser.parse_args()))
+
+
+def main():
+    args = arg_parse()
+
+    test_binary, rest = Path(args.test[0]), args.test[1:]
+
+    # Create directory.
+    buck_tmpdir = args.resources.parent.parent / test_binary.parent.name
+    os.makedirs(buck_tmpdir, exist_ok=True)
+
+    # Copy executable.
+    buck_executable = buck_tmpdir / test_binary.name
+    shutil.copy2(test_binary, buck_executable)
+
+    # Copy resources.json.
+    # Folly looks for a sibling of the executable, with this suffix.
+    buck_resources_json = buck_tmpdir / (test_binary.name + ".resources.json")
+    shutil.copy2(args.resources, buck_resources_json)
+
+    # Run test.
+    os.execl(buck_executable, buck_executable, *rest)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/rust/tools/shared_libraries_symlink_tree.py b/buck2/prelude/rust/tools/shared_libraries_symlink_tree.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/shared_libraries_symlink_tree.py
@@ -0,0 +1,128 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Creates a symlink tree for shared libraries (.so) and their debug files (.dwp).
+# The input is an output directory to construct the symlink tree in and a JSON file of the shared libraries to link.
+#
+#
+# Example:
+# `shared_libraries_symlink_tree.py --shared_libs_symlink_tree /tmp/my_tree --shared_libraries_info_json /path/to/libraries.json``
+#
+# /path/to/libraries.json
+# ```
+# [
+#     [
+#         (
+#             True,
+#             "libthird-party_rust_vendor_anyhow_1.0.100.so",
+#             "buck-out/v2/gen/fbsource/577ba3460b84e891/third-party/rust/vendor/anyhow/__1.0.100__/DPHL/libthird-party_rust_vendor_anyhow_1.0.100.so",
+#             "buck-out/v2/gen/fbsource/577ba3460b84e891/third-party/rust/vendor/anyhow/__1.0.100__/DPHL/libthird-party_rust_vendor_anyhow_1.0.100.so.dwp",
+#         ),
+#         ....
+#     ],
+#     ...
+# ]
+# ```
+#
+# Each entry in the JSON file is a tuple of (is_str: bool, soname: str | Path, output: Path, dwp: Path | None)
+# - is_str: whether the field `soname` is read literally as a string or if the field `soname` is a Path to a file containing the soname.
+# - soname: The name of the link to the output. See its companion field `is_str`.
+# - output: The Path to the .so. This is the target of the symlink.
+# - dwp: An optional .dwp (DWARF Package) (i.e., debug info) file to symlink in a separate directory.
+#
+# Constructs symlink tree /tmp/my_tree
+# ```
+# libthird-party_rust_vendor_anyhow_1.0.100.so -> buck-out/v2/gen/fbsource/577ba3460b84e891/third-party/rust/vendor/anyhow/__1.0.100__/DPHL/libthird-party_rust_vendor_anyhow_1.0.100.so
+# ...
+# ```
+
+import argparse
+import json
+import os
+import sys
+from pathlib import Path
+from typing import IO, NamedTuple
+
+
+class Args(NamedTuple):
+    shared_libs_symlink_tree: Path
+    dwp_symlink_tree: Path
+    shared_libraries_info_json: IO[str]
+
+
+def symlink_relative(link: Path, target: Path) -> None:
+    """Create a symlink from link_name to target.
+
+    The link is created by constructing a path to the target that is relative to link_name's parent.
+    """
+    symlink = os.path.relpath(target, start=os.path.dirname(link))
+    os.symlink(symlink, link)
+
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--shared_libs_symlink_tree",
+        type=Path,
+        required=True,
+    )
+    parser.add_argument(
+        "--dwp_symlink_tree",
+        type=Path,
+        required=True,
+    )
+    parser.add_argument(
+        "--shared_libraries_info_json",
+        type=argparse.FileType(),
+        required=True,
+    )
+    args = Args(**vars(parser.parse_args()))
+
+    args.shared_libs_symlink_tree.mkdir(exist_ok=True)
+    args.dwp_symlink_tree.mkdir(exist_ok=True)
+
+    shared_libraries_info = json.load(args.shared_libraries_info_json)
+
+    seen: dict[str, str] = {}
+
+    for shared_libraries in shared_libraries_info:
+        for shared_library in shared_libraries:
+            is_str, soname, output, dwp = shared_library
+            if is_str:
+                link_name = soname
+            else:
+                link_name = Path(soname).read_text().strip()
+
+            existing = seen.get(link_name)
+            if existing is not None:
+                if existing != output:
+                    print(
+                        f"Warning: Duplicate shared library {link_name}:\n"
+                        f"  first:  {existing}\n"
+                        f"  second: {output}\n"
+                        f"  Using the first one.",
+                        file=sys.stderr,
+                    )
+                continue
+
+            seen[link_name] = output
+            target = output
+
+            symlink_relative(args.shared_libs_symlink_tree / link_name, target)
+
+            has_dwp = dwp is not None
+            if has_dwp:
+                symlink_relative(
+                    link=(args.dwp_symlink_tree / link_name).with_suffix(".dwp"),
+                    target=dwp,
+                )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/rust/tools/symlink_only_dir_entry.py b/buck2/prelude/rust/tools/symlink_only_dir_entry.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/symlink_only_dir_entry.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Simple python script that symlinks a provided path to the only file in a directory
+
+import os
+import sys
+
+
+def main():
+    d = sys.argv[1]
+    linkname = sys.argv[2]
+    entries = os.listdir(d)
+    if len(entries) != 1:
+        raise ValueError("expected exactly one entry in directory")
+    dest = os.path.join(d, entries[0])
+
+    symlink = os.path.relpath(dest, start=os.path.dirname(linkname))
+    os.symlink(symlink, linkname)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/rust/tools/tool_rules.bzl b/buck2/prelude/rust/tools/tool_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/tool_rules.bzl
@@ -0,0 +1,86 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//rust:rust_toolchain.bzl", "RustToolchainInfo")
+
+def _get_rustc_cfg_impl(ctx: AnalysisContext) -> list[Provider]:
+    toolchain_info = ctx.attrs._rust_toolchain[RustToolchainInfo]
+
+    out = ctx.actions.declare_output("rustc.cfg", has_content_based_path = True)
+
+    cmd = [
+        toolchain_info.compiler,
+        cmd_args("--print=cfg=", out.as_output(), delimiter = ""),
+        cmd_args("--sysroot="),  # We do not need a sysroot here, and not all platforms we support have one available (e.g. mips64-unknown-linux-gnuabi64)
+        toolchain_info.rustc_flags,
+    ]
+
+    uses_custom_target = toolchain_info.rust_target_path != None
+
+    if toolchain_info.rustc_target_triple:
+        cmd.append(cmd_args("--target=", toolchain_info.rustc_target_triple, delimiter = ""))
+        if uses_custom_target:
+            cmd.append("-Zunstable-options")
+
+    env = {}
+    if ctx.attrs.enable_nightly_cfgs or uses_custom_target:
+        env["RUSTC_BOOTSTRAP"] = "1"
+
+    if toolchain_info.rust_target_path != None:
+        env["RUST_TARGET_PATH"] = toolchain_info.rust_target_path[DefaultInfo].default_outputs[0]
+
+    ctx.actions.run(cmd, category = "rustc_cfg", env = env)
+
+    return [DefaultInfo(default_output = out)]
+
+get_rustc_cfg = rule(
+    impl = _get_rustc_cfg_impl,
+    attrs = {
+        "enable_nightly_cfgs": attrs.bool(default = False),
+        "_rust_toolchain": toolchains_common.rust(),
+    },
+)
+
+def _get_rustc_host_tuple_impl(ctx: AnalysisContext) -> list[Provider]:
+    toolchain_info = ctx.attrs._rust_toolchain[RustToolchainInfo]
+
+    out = ctx.actions.declare_output("rustc.host_tuple", has_content_based_path = True)
+
+    cmd = [
+        toolchain_info.compiler,
+        cmd_args("--print=host-tuple=", out.as_output(), delimiter = ""),
+    ]
+
+    ctx.actions.run(cmd, category = "rustc_host_tuple")
+
+    return [DefaultInfo(default_output = out)]
+
+get_rustc_host_tuple = rule(
+    impl = _get_rustc_host_tuple_impl,
+    attrs = {
+        "_rust_toolchain": toolchains_common.rust(),
+    },
+)
+
+def _linkable_symbol_supports_no_std_impl(ctx: AnalysisContext) -> list[Provider]:
+    toolchain_info = ctx.attrs._rust_toolchain[RustToolchainInfo]
+
+    # `#[no_std]` requires use of `advanced_unstable_linking` on the toolchain,
+    # as otherwise the panic handler is missing.
+    cfg = "--cfg=set_nostd\n" if toolchain_info.advanced_unstable_linking else ""
+
+    flagfile = ctx.actions.write("cfg", cfg, has_content_based_path = True)
+    return [DefaultInfo(default_output = flagfile)]
+
+linkable_symbol_supports_no_std = rule(
+    impl = _linkable_symbol_supports_no_std_impl,
+    attrs = {
+        "_rust_toolchain": toolchains_common.rust(),
+    },
+)
diff --git a/buck2/prelude/rust/tools/transitive_dependency_symlinks.py b/buck2/prelude/rust/tools/transitive_dependency_symlinks.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/tools/transitive_dependency_symlinks.py
@@ -0,0 +1,151 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# A tool to produce a directory structure compatible with rustc's `-Ldependency`
+# flag for simple and dynamically named crates.
+#
+# Rustc needs all the .rlib files which are transitive dependencies of the crate
+# being built. Importantly, the filename for each rlib must contain the correct
+# crate name or else rustc won't find the file.
+#
+# Most crates have a crate name determined during analysis: value of the `crate`
+# attribute, or derived using a simple heuristic from the rust_library target's
+# `name` attribute. For these it's easy to give the rlib a correct filename up
+# front and use buck's `ctx.actions.symlinked_dir` to collect them into a
+# directory. These do not go through this tool.
+#
+# Crates that use `crate_dynamic` have a crate name computed at build time, for
+# example by extracting the name from a .thrift file. Buck needs a filename at
+# analysis time for all artifacts, so we name those rlib files using a
+# provisional name and then this tool at build time will symlink them under the
+# real crate name that rustc will recognize.
+#
+# Example:
+#
+#     transitive_dependency_symlinks.py \
+#         --out-dir path/to/out \
+#         --artifacts path/to/artifacts.json
+#
+# The input file artifacts.json is an array of pairs.
+# The first element is the rlib paths, the second element is an optional path to a file containing
+# the build-time crate name for the corresponding rlib.
+#
+#     [
+#         [ "../../libprovisional.rlib", "path/to/cratename" ],
+#         [ "../../libfoo.rlib", null ],
+#         ...
+#     ]
+#
+# The tool reads the crate name from the file at "path/to/cratename". Suppose it's
+# "thriftgenerated". It symlinks the given artifact as "0/libthriftgenerated.rlib"
+# within the specified output directory. In the event of collisions, there might
+# be multiple dirs created.
+#
+# If the cratename is null, then the artifact is simply symlinked from the basename
+# (e.g., "0/libprovisional.rlib").
+#
+# --out-dir-relative-to-cwd is an optional path to the output directory that is relative to
+#                           the current working directory (cwd) of the tool that consumes this script's output.
+#                           This path is the the output directory path used in -Ldependency.
+
+import argparse
+import json
+import os
+from pathlib import Path
+from typing import IO, NamedTuple, Optional
+
+
+class Args(NamedTuple):
+    name: str
+    out_dir: Path
+    out_dir_relative_to_cwd: Optional[Path]
+    artifacts: IO[str]
+
+
+def symlink_relative(link: Path, target: Path) -> None:
+    """Create a symlink from link_name to target.
+
+    The link is created by constructing a path to the target that is relative to link_name's parent.
+    """
+    target_relative = os.path.relpath(target, start=os.path.dirname(link))
+    os.symlink(target_relative, link)
+
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "--out-dir",
+        type=Path,
+        required=True,
+    )
+    parser.add_argument(
+        "--out-dir-relative-to-cwd",
+        type=Path,
+        required=False,
+    )
+    parser.add_argument(
+        "--artifacts",
+        type=argparse.FileType(),
+        required=True,
+    )
+    parser.add_argument(
+        "--name",
+        type=str,
+        required=True,
+    )
+    args = Args(**vars(parser.parse_args()))
+
+    args.out_dir.mkdir(exist_ok=True)
+
+    # Add as many -Ldependency dirs as we need to avoid name conflicts
+    deps_dirs = [{}]
+
+    for artifact, crate_name in json.load(args.artifacts):
+        is_dynamic = crate_name is not None
+        if is_dynamic:
+            crate_name = Path(crate_name).read_text().strip()
+            original_filename = os.path.basename(artifact)
+            new_filename = "lib{}-{}".format(
+                crate_name,
+                original_filename.rsplit("-", 1)[1],
+            )
+            filename = new_filename
+        else:
+            filename = os.path.basename(artifact)
+
+        if filename in deps_dirs[-1]:
+            deps_dirs.append({})
+        deps_dirs[-1][filename] = artifact
+
+    flags = ""
+
+    for idx, srcs in enumerate(deps_dirs):
+        if srcs:
+            directory = args.out_dir.joinpath(str(idx))
+            directory.mkdir()
+
+            dependency_path = (
+                args.out_dir_relative_to_cwd.joinpath(str(idx))
+                # The -Ldependency output path gets a relative path if there is one,
+                # because the tools consuming this expect a path relative to cwd.
+                if args.out_dir_relative_to_cwd
+                else directory
+            )
+
+            flags += "-Ldependency={}\n".format(dependency_path)
+            for filename, artifact in srcs.items():
+                # Create the symlinks in the directory (i.e., not the relative path)
+                # because this script is NOT executing relative to the cwd.
+                symlink_relative(directory.joinpath(filename), artifact)
+
+    args.out_dir.joinpath("dirs").write_text(flags)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/rust/with_workspace.bzl b/buck2/prelude/rust/with_workspace.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/rust/with_workspace.bzl
@@ -0,0 +1,16 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+package_key = "rust.workspaces"
+
+def with_rust_workspace(targets):
+    if isinstance(targets, str):
+        targets = [targets]
+
+    parent = read_parent_package_value(package_key) or []
+    write_package_value(package_key, parent + targets, overwrite = True)
diff --git a/buck2/prelude/sh_binary.bzl b/buck2/prelude/sh_binary.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/sh_binary.bzl
@@ -0,0 +1,148 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+
+def _derive_link(artifact):
+    if artifact.is_source:
+        return artifact.short_path
+
+    # TODO(cjhopman): Reject cross-repo resources. Buck1 does that. It's probably
+    # easier for us (compared to v1) to construct a scheme for them that is
+    # correct, but not necessary yet.
+
+    return paths.join(artifact.owner.package, artifact.owner.name)
+
+def _generate_script(
+    name: str,
+    main: Artifact,
+    resources: list[Artifact],
+    append_script_extension: bool,
+    actions: AnalysisActions,
+    is_windows: bool,
+    copy_resources: bool,
+    has_content_based_path: bool,
+) -> (Artifact, Artifact):
+    main_path = main.short_path
+    if not append_script_extension:
+        main_link = main_path
+    elif is_windows:
+        main_link = main_path if main_path.endswith(".bat") or main_path.endswith(".cmd") else main_path + ".bat"
+    else:
+        main_link = main_path if main_path.endswith(".sh") else main_path + ".sh"
+    resources = {_derive_link(src): src for src in resources}
+    resources[main_link] = main
+
+    # windows isn't stable with resources passed in as symbolic links for
+    # remote execution. Allow using copies instead.
+    if copy_resources:
+        resources_dir = actions.copied_dir("resources", resources, has_content_based_path = has_content_based_path)
+    else:
+        resources_dir = actions.symlinked_dir("resources", resources, has_content_based_path = has_content_based_path)
+
+    script_name = name + (".bat" if is_windows else "")
+    script = actions.declare_output(script_name, has_content_based_path = has_content_based_path)
+
+    # This is much, much simpler than the buck1 sh_binary template. A couple reasons:
+    # 1. we don't invoke the script through a symlink and so don't need to use and implement a cross-platform `readlink -e`
+    # 2. we don't construct an invocation-specific sandbox. The implementation of
+    # that in buck1 is pretty crazy and it shouldn't actually be necessary.
+    # 3. we don't construct the cell symlinks. those were also strange. They were
+    # used for the links in the invocation-specific sandbox (so things would
+    # point through the cell symlinks to their original locations). Instead we
+    # construct links directly to things (which buck1 actually also did for its
+    # BUCK_DEFAULT_RUNTIME_RESOURCES).
+    if not is_windows:
+        script_content = cmd_args(
+            "#!/usr/bin/env bash",
+            "set -e",
+            # If we access this sh_binary via a unhashed symlink we need to
+            # update the relative source.
+            '__SRC="${BASH_SOURCE[0]}"',
+            '__SRC="$(realpath "$__SRC")"',
+            '__SCRIPT_DIR=$(dirname "$__SRC")',
+            # The format of the directory tree is different in v1 and v2. We
+            # should unify the two, but prior to doing this we should also
+            # identify what the right format is. For now, this variable lets
+            # callees disambiguate (see D28960177 for more context).
+            "export BUCK_SH_BINARY_VERSION_UNSTABLE=2",
+            cmd_args('export BUCK_PROJECT_ROOT="$__SCRIPT_DIR/', resources_dir, '"', delimiter = ""),
+            # Normalize backslashes to forward slashes for the Windows-host /
+            # Linux-target (RE) case where relative_to produces Windows-style separators.
+            'export BUCK_PROJECT_ROOT="${BUCK_PROJECT_ROOT//\\\\//}"',
+            # In buck1, the paths for resources that are outputs of rules have
+            # different paths in BUCK_PROJECT_ROOT and
+            # BUCK_DEFAULT_RUNTIME_RESOURCES, but we use the same paths. buck1's
+            # BUCK_PROJECT_ROOT paths would use the actual buck-out path rather
+            # than something derived from the target and so to use that people
+            # would need to hardcode buck-out paths into their scripts. For repo
+            # sources, the paths are the same for both.
+            'export BUCK_DEFAULT_RUNTIME_RESOURCES="$BUCK_PROJECT_ROOT"',
+            'exec "$BUCK_PROJECT_ROOT/{}" "$@"'.format(main_link),
+            relative_to = (script, 1),
+        )
+    else:
+        script_content = cmd_args(
+            "@echo off",
+            "setlocal EnableDelayedExpansion",
+            # Fully qualified script path.
+            "set __SRC=%~f0",
+            # Symbolic links on windows RE systems may not be stable depending on implementation.
+            # Don't try to resolve the links when using copies.
+            'for /f "tokens=2 delims=[]" %%a in (\'dir %__SRC% ^|%SYSTEMROOT%\\System32\\find.exe "<SYMLINK>"\') do set "__SRC=%%a"'
+            if not copy_resources
+            else "",
+            # Get parent folder.
+            'for %%a in ("%__SRC%") do set "__SCRIPT_DIR=%%~dpa"',
+            "set BUCK_SH_BINARY_VERSION_UNSTABLE=2",
+            cmd_args("set BUCK_PROJECT_ROOT=%__SCRIPT_DIR%\\", resources_dir, delimiter = ""),
+            "set BUCK_DEFAULT_RUNTIME_RESOURCES=%BUCK_PROJECT_ROOT%",
+            "%BUCK_PROJECT_ROOT%\\{} %*".format(main_link),
+            relative_to = (script, 1),
+        )
+    actions.write(
+        script,
+        script_content,
+        is_executable = True,
+    )
+
+    return (script, resources_dir)
+
+# Attrs:
+# "deps": attrs.list(attrs.dep(), default = []),
+# "main": attrs.source(),
+# "resources": attrs.list(attrs.source(), default = []),
+# "copy_resources": attrs.bool(default = False),
+def sh_binary_impl(ctx):
+    # TODO: implement deps (not sure what those even do, though)
+    if len(ctx.attrs.deps) > 0:
+        fail("sh_binary deps unsupported. Got `{}`".format(repr(ctx.attrs)))
+
+    is_windows = ctx.attrs._target_os_type[OsLookup].os == Os("windows")
+    (script, resources_dir) = _generate_script(
+        ctx.label.name,
+        ctx.attrs.main,
+        ctx.attrs.resources,
+        ctx.attrs.append_script_extension,
+        ctx.actions,
+        is_windows,
+        ctx.attrs.copy_resources,
+        ctx.attrs.has_content_based_path,
+    )
+
+    script = script.with_associated_artifacts([resources_dir])
+
+    return [
+        DefaultInfo(default_output = script, other_outputs = [resources_dir]),
+        RunInfo(
+            # TODO(cjhopman): Figure out if we need to specify the link targets
+            # as inputs. We shouldn't need to, but need to verify it.
+            args = cmd_args(script, hidden = resources_dir),
+        ),
+    ]
diff --git a/buck2/prelude/sh_test.bzl b/buck2/prelude/sh_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/sh_test.bzl
@@ -0,0 +1,75 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//test:inject_test_run_info.bzl", "inject_test_run_info")
+load("@prelude//tests:re_utils.bzl", "get_re_executors_from_props")
+
+def sh_test_impl(ctx: AnalysisContext) -> list[Provider]:
+    # This does not exist in v1 either, but v1 has those attributes presumably
+    # to be compatible with this. We just fail if they're passed.
+    if ctx.attrs.list_args or ctx.attrs.list_env or ctx.attrs.run_args or ctx.attrs.run_env:
+        fail("An unsupported attribute was passed")
+
+    args_args = []
+    args_hidden = []
+
+    if ctx.attrs.test != None:
+        if isinstance(ctx.attrs.test, Artifact):
+            args_args.append(ctx.attrs.test)
+        elif isinstance(ctx.attrs.test, Dependency):
+            run_info = ctx.attrs.test.get(RunInfo)
+            if run_info != None:
+                args_args.append(run_info.args)
+            else:
+                info = ctx.attrs.test[DefaultInfo]
+                args_args.append(info.default_outputs)
+                args_hidden.append(info.other_outputs)
+        else:
+            fail("Unexpected type for test attribute")
+
+    args_hidden.append(ctx.attrs.resources)
+
+    deps = []
+    for dep in ctx.attrs.deps:
+        info = dep[DefaultInfo]
+        deps.extend(info.default_outputs)
+        deps.extend(info.other_outputs)
+
+    args_hidden.append(deps)
+
+    args = cmd_args(args_args, hidden = args_hidden)
+
+    command = [args] + ctx.attrs.args
+
+    # Setup a RE executor based on the `remote_execution` param.
+    re_executors = get_re_executors_from_props(ctx)
+
+    # We implicitly make the target run from the project root if remote
+    # execution options were specified
+    run_from_project_root = "buck2_run_from_project_root" in (ctx.attrs.labels or []) or re_executors.run_from_project_root
+    use_project_relative_paths = "buck2_run_from_project_root" in (ctx.attrs.labels or []) or re_executors.use_project_relative_paths
+
+    # TODO support default info and runinfo properly by writing a sh script that invokes the command properly
+
+    return inject_test_run_info(
+        ctx,
+        ExternalRunnerTestInfo(
+            type = ctx.attrs.type or "custom",
+            command = command,
+            env = ctx.attrs.env,
+            labels = ctx.attrs.labels,
+            contacts = ctx.attrs.contacts,
+            default_executor = re_executors.default_executor,
+            executor_overrides = re_executors.executor_overrides,
+            run_from_project_root = run_from_project_root,
+            use_project_relative_paths = use_project_relative_paths,
+            supports_test_execution_caching = ctx.attrs.supports_test_execution_caching,
+        ),
+    ) + [
+        DefaultInfo(),
+    ]
diff --git a/buck2/prelude/target_stats/target_stats.bzl b/buck2/prelude/target_stats/target_stats.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/target_stats/target_stats.bzl
@@ -0,0 +1,197 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Shared implementation for the target_stats integration.
+
+load("@prelude//:paths.bzl", "paths")
+load(":target_stats_config.bzl", "TARGET_STATS_ENABLED")
+load(":target_stats_tools.bzl", "TargetStatsToolsInfo")
+load(
+    ":target_stats_types.bzl",
+    "TargetStatsInfo",
+    "TargetStatsInfoTSet",
+    "TargetStatsRecord",
+)
+
+CycleMode = enum("file", "package", "none")
+
+_OUT_DIR = "__target_stats__"
+
+def _content_based_input(ctx: AnalysisContext, artifact: Artifact, name: str) -> Artifact:
+    """Return an input whose path can participate in cross-config dedupe.
+
+    Source files are already eligible. Generated files are not necessarily
+    content-addressed, so normalize those through a cheap copy before feeding
+    them to the target_stats tools.
+    """
+    if artifact.is_source:
+        return artifact
+    return ctx.actions.copy_file(
+        _OUT_DIR + "/inputs/" + name,
+        artifact,
+        has_content_based_path = True,
+    )
+
+def _file_stats_action(ctx: AnalysisContext, tools: TargetStatsToolsInfo, src: Artifact, name: str) -> Artifact:
+    out = ctx.actions.declare_output(_OUT_DIR, name + ".file_stats.json", has_content_based_path = True)
+    content_based_src = _content_based_input(ctx, src, name)
+    ctx.actions.run(
+        cmd_args([tools.file_stats, "--input", content_based_src, "--output", out.as_output()]),
+        category = "target_stats_file_stats",
+        identifier = name,
+        allow_cache_upload = True,
+        expect_eligible_for_dedupe = True,
+    )
+    return out
+
+def _extract_target_data_action(ctx: AnalysisContext, tools: TargetStatsToolsInfo, file_stats_by_path: dict[str, Artifact]) -> Artifact:
+    manifest = ctx.actions.write_json(
+        _OUT_DIR + "/extract_manifest.json",
+        file_stats_by_path,
+        with_inputs = True,
+        has_content_based_path = True,
+    )
+    out = ctx.actions.declare_output(_OUT_DIR, "target_data.json", has_content_based_path = True)
+    ctx.actions.run(
+        cmd_args([tools.extract_target_data, "--manifest", manifest, "--output", out.as_output()]),
+        category = "target_stats_extract_target_data",
+        allow_cache_upload = True,
+        expect_eligible_for_dedupe = True,
+    )
+    return out
+
+def _cycles_action(
+    ctx: AnalysisContext, tools: TargetStatsToolsInfo, cycle_mode: CycleMode, target_data: Artifact, module_name: str, swift_dot: Artifact | None
+) -> Artifact | None:
+    if cycle_mode == CycleMode("none"):
+        return None
+    out = ctx.actions.declare_output(_OUT_DIR, "cycles.json", has_content_based_path = True)
+    if cycle_mode == CycleMode("file"):
+        args = cmd_args([
+            tools.file_cycles,
+            "--target-data",
+            target_data,
+            "--module-name",
+            module_name,
+            "--target-path",
+            str(ctx.label.raw_target()),
+            "--output",
+            out.as_output(),
+        ])
+        if swift_dot != None:
+            # Swift compilation deliberately uses configuration-based paths.
+            # Copy the finished graph into the content-addressed namespace so
+            # this analysis action can still dedupe when two configurations
+            # produced byte-for-byte identical dependency graphs. The cheap
+            # copy itself remains configuration-specific.
+            content_based_swift_dot = _content_based_input(ctx, swift_dot, "swift-dependencies.dot")
+            args.add("--swift-dot", content_based_swift_dot)
+    else:
+        args = cmd_args([
+            tools.package_cycles,
+            "--target-data",
+            target_data,
+            "--output",
+            out.as_output(),
+        ])
+    ctx.actions.run(
+        args,
+        category = "target_stats_cycles",
+        allow_cache_upload = True,
+        expect_eligible_for_dedupe = True,
+    )
+    return out
+
+def _all_target_stats_subtarget(ctx: AnalysisContext, tset: TargetStatsInfoTSet) -> list[Provider]:
+    """A JSON object mapping every transitive target's label to its manifest."""
+    manifest_by_target = {record.label: record.manifest for record in tset.traverse()}
+    out = ctx.actions.declare_output(_OUT_DIR, "all_target_stats.json", has_content_based_path = True)
+    out_with_inputs = ctx.actions.write_json(out, manifest_by_target, with_inputs = True)
+    return [
+        DefaultInfo(
+            default_output = out,
+            other_outputs = [out_with_inputs, tset.project_as_args("manifests")],
+        )
+    ]
+
+def target_stats_aggregate_providers_and_subtargets(
+    ctx: AnalysisContext,
+    *,
+    deps: list[Dependency],
+) -> (list[Provider], dict[str, list[Provider]]):
+    """target_stats for a rule that contributes no sources of its own.
+
+    A no-op when target_stats is disabled, so aggregating rules can call it
+    unconditionally.
+    """
+    if not TARGET_STATS_ENABLED:
+        return [], {}
+    children = [dep[TargetStatsInfo].tset for dep in deps if dep.get(TargetStatsInfo) != None]
+    tset = ctx.actions.tset(TargetStatsInfoTSet, children = children)
+    info = TargetStatsInfo(label = str(ctx.label.raw_target()), tset = tset)
+    subtargets = {
+        "all_target_stats": _all_target_stats_subtarget(ctx, tset),
+    }
+    return [info], subtargets
+
+def target_stats_providers_and_subtargets(
+    ctx: AnalysisContext,
+    *,
+    tools: TargetStatsToolsInfo,
+    srcs: dict[str, Artifact],
+    deps: list[Dependency],
+    cycle_mode: CycleMode,
+    module_name: str,
+    swift_dot: Artifact | None = None,
+) -> (list[Provider], dict[str, list[Provider]]):
+    """Build the target_stats actions, provider and sub-targets for one target."""
+    label = str(ctx.label.raw_target())
+
+    file_stats_by_path = {}
+    for name, src in srcs.items():
+        # A header map key need not be normalized, and it becomes an output
+        # path. third-party/libvpx maps each generated header under both "name"
+        # and "./name", so the same file arrives twice and normalizes to one
+        # name; measure it once rather than declaring the output twice.
+        name = paths.normalize(name)
+        if name in file_stats_by_path:
+            continue
+        file_stats_by_path[name] = _file_stats_action(ctx, tools, src, name)
+
+    target_data = _extract_target_data_action(ctx, tools, file_stats_by_path)
+    cycles = _cycles_action(ctx, tools, cycle_mode, target_data, module_name, swift_dot)
+
+    manifest = ctx.actions.declare_output(_OUT_DIR, "target_stats.json", has_content_based_path = True)
+    manifest_inputs = ctx.actions.write_json(
+        manifest,
+        {
+            "cycles": cycles,
+            "file_stats": file_stats_by_path,
+            "target": label,
+            "target_data": target_data,
+        },
+        with_inputs = True,
+    )
+
+    children = [dep[TargetStatsInfo].tset for dep in deps if dep.get(TargetStatsInfo) != None]
+    tset = ctx.actions.tset(
+        TargetStatsInfoTSet,
+        value = TargetStatsRecord(
+            label = label,
+            manifest = manifest,
+            manifest_with_inputs = manifest_inputs,
+        ),
+        children = children,
+    )
+    info = TargetStatsInfo(label = label, tset = tset)
+
+    subtargets = {
+        "all_target_stats": _all_target_stats_subtarget(ctx, tset),
+        "target_stats": [DefaultInfo(default_output = manifest, other_outputs = [manifest_inputs]), info],
+    }
+    return [info], subtargets
diff --git a/buck2/prelude/target_stats/target_stats_config.bzl b/buck2/prelude/target_stats/target_stats_config.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/target_stats/target_stats_config.bzl
@@ -0,0 +1,12 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:buckconfig.bzl", "read_bool")
+
+# Read at load time: rule implementations cannot call read_config.
+TARGET_STATS_ENABLED = read_bool("target_stats", "enabled", default = False, root_cell = True)
diff --git a/buck2/prelude/target_stats/target_stats_tools.bzl b/buck2/prelude/target_stats/target_stats_tools.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/target_stats/target_stats_tools.bzl
@@ -0,0 +1,39 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Attached to a platform toolchain so any supporting rule can reach the tools.
+
+TargetStatsToolsInfo = provider(
+    fields = {
+        "extract_target_data": provider_field(RunInfo),
+        "file_cycles": provider_field(RunInfo),
+        "file_stats": provider_field(RunInfo),
+        "package_cycles": provider_field(RunInfo),
+    },
+)
+
+def _target_stats_tools_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        TargetStatsToolsInfo(
+            file_cycles = ctx.attrs.file_cycles[RunInfo],
+            file_stats = ctx.attrs.file_stats[RunInfo],
+            package_cycles = ctx.attrs.package_cycles[RunInfo],
+            extract_target_data = ctx.attrs.extract_target_data[RunInfo],
+        ),
+    ]
+
+target_stats_tools = rule(
+    impl = _target_stats_tools_impl,
+    attrs = {
+        "extract_target_data": attrs.exec_dep(providers = [RunInfo]),
+        "file_cycles": attrs.exec_dep(providers = [RunInfo]),
+        "file_stats": attrs.exec_dep(providers = [RunInfo]),
+        "package_cycles": attrs.exec_dep(providers = [RunInfo]),
+    },
+)
diff --git a/buck2/prelude/target_stats/target_stats_types.bzl b/buck2/prelude/target_stats/target_stats_types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/target_stats/target_stats_types.bzl
@@ -0,0 +1,31 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Per-target codebase statistics, propagated across the dependency graph.
+
+TargetStatsRecord = record(
+    label = field(str),
+    manifest = field(Artifact),
+    manifest_with_inputs = field(typing.Any),
+)
+
+def _project_manifests(record: TargetStatsRecord) -> typing.Any:
+    return record.manifest_with_inputs
+
+TargetStatsInfoTSet = transitive_set(
+    args_projections = {
+        "manifests": _project_manifests,
+    },
+)
+
+TargetStatsInfo = provider(
+    fields = {
+        "label": provider_field(str),
+        "tset": provider_field(TargetStatsInfoTSet),
+    },
+)
diff --git a/buck2/prelude/test/inject_test_run_info.bzl b/buck2/prelude/test/inject_test_run_info.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/test/inject_test_run_info.bzl
@@ -0,0 +1,48 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//tests:re_utils.bzl",
+    "maybe_add_run_as_bundle_label",
+)
+
+def inject_test_run_info(ctx: AnalysisContext, test_info: ExternalRunnerTestInfo) -> list[Provider]:
+    # Access this here so we get failures in CI if we forget to inject it
+    # anywhere, regardless of whether an `env` is used.
+    inject_test_env = ctx.attrs._inject_test_env[RunInfo]
+
+    # `if test_info.labels != None` doesn't work because `None` is not of type `list[str]`,
+    # yet it is None in some cases... this hack lets us check for None without a type error.
+    if getattr(test_info, "labels", None) != None:
+        # If forcing RE on tpx, check if the test suite should be run as a bundle
+        maybe_add_run_as_bundle_label(ctx, test_info.labels)
+
+    if (not test_info.env) or _exclude_test_env_from_run_info(ctx):
+        return [test_info, RunInfo(args = test_info.command)]
+
+    cell_root = ctx.label.cell_root
+
+    env_file = ctx.actions.write_json(
+        "test_env.json",
+        {k: _maybe_relativize_path(test_info, cell_root, cmd_args(v, delimiter = " ")) for (k, v) in test_info.env.items()},
+        with_inputs = True,
+        absolute = True,
+        has_content_based_path = False,
+    )
+
+    return [test_info, RunInfo(args = [inject_test_env, env_file, "--", test_info.command])]
+
+def _maybe_relativize_path(test_info: ExternalRunnerTestInfo, cell_root: CellRoot, arg: cmd_args) -> cmd_args:
+    if test_info.run_from_project_root:
+        return arg
+    return arg.relative_to(cell_root)
+
+def _exclude_test_env_from_run_info(ctx: AnalysisContext):
+    # Antlir assumes that $(exe ...) is a single, relative path, so if we make
+    # it multiple commands here, it'll break.
+    return "antlir_inner_test" in ctx.attrs.labels
diff --git a/buck2/prelude/test/tools/BUCK b/buck2/prelude/test/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/test/tools/BUCK
@@ -0,0 +1,13 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "inject_test_env",
+    main = "inject_test_env.py",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/test/tools/inject_test_env.py b/buck2/prelude/test/tools/inject_test_env.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/test/tools/inject_test_env.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+import os
+import shlex
+import subprocess
+import sys
+
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "env_file", help="A JSON file containing the environment to inject"
+    )
+    parser.add_argument(
+        "--dry-run",
+        action="store_true",
+        help="Print a command line that can be used to run this command in the current environment. Useful for debugging",
+    )
+    parser.add_argument("executable")
+    parser.add_argument("args", nargs="*")
+
+    args = parser.parse_args()
+
+    with open(args.env_file) as env_file:
+        env_from_file = json.load(env_file)
+        env = {**os.environ, **env_from_file}
+
+    if args.dry_run:
+        env_str = (
+            "; ".join(f"export {k}={shlex.quote(v)}" for k, v in env_from_file.items())
+            + "; "
+            if env_from_file
+            else ""
+        )
+        inner_cmd = env_str + shlex.join([args.executable, *args.args])
+        if sys.platform == "win32":
+            print_str = subprocess.list2cmdline(["bash", "-c", inner_cmd])
+        else:
+            print_str = "(" + inner_cmd + ")"
+        print(print_str)
+        return
+    os.execve(args.executable, [args.executable, *args.args], env)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/test_suite.bzl b/buck2/prelude/test_suite.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/test_suite.bzl
@@ -0,0 +1,20 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def test_suite_impl(ctx: AnalysisContext) -> list[Provider]:
+    # There is nothing to implement here: test_suite exists as a mechanism to "group" tests using
+    # the `tests` attribute, and the `tests` attribute is supported for all rules.
+    # We fill in the DefaultInfo so building the test_suite will build all the underlying test rules.
+    test_targets = []
+    other_outputs = []
+    for test_dep in ctx.attrs.test_deps:
+        test_targets.append(test_dep.label.raw_target())
+        default_info = test_dep[DefaultInfo]
+        other_outputs.extend(default_info.default_outputs)
+        other_outputs.extend(default_info.other_outputs)
+    return [DefaultInfo(default_outputs = [ctx.actions.write("test_targets.txt", test_targets, has_content_based_path = False)], other_outputs = other_outputs)]
diff --git a/buck2/prelude/tests/re_utils.bzl b/buck2/prelude/tests/re_utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/tests/re_utils.bzl
@@ -0,0 +1,230 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//tests:remote_test_execution_toolchain.bzl", "RemoteTestExecutionToolchainInfo")
+load("@prelude//utils:expect.bzl", "expect_non_none")
+load("@prelude//utils:type_defs.bzl", "type_utils")
+
+ReArg = record(
+    disabled = field(bool | None, default = None),
+    re_props = field(dict | None, default = None),
+    default_run_as_bundle = field(bool | None, default = None),
+)
+
+# Result of `get_re_executors_from_props`.
+#
+# `run_from_project_root` and `use_project_relative_paths` report whether the
+# returned executor is remote-execution eligible and therefore the test must run
+# from the project root with project-relative paths. They are currently the same
+# value, but keep them separate from each other and from "is there an executor at
+# all?" so callers can evolve cwd and path behavior independently.
+RemoteTestExecutorConfig = record(
+    default_executor = field([CommandExecutorConfig, None], default = None),
+    executor_overrides = field(dict[str, CommandExecutorConfig], default = {}),
+    run_from_project_root = field(bool, default = False),
+    use_project_relative_paths = field(bool, default = False),
+)
+
+def _network_access_kwargs(network_access: str | None) -> dict[str, str]:
+    if network_access == None:
+        return {}
+    return {"network_access": network_access}
+
+_FORCE_RUN_AS_BUNDLE = read_root_config("tpx", "force_run_as_bundle", "False")
+
+def _force_local_re_tests() -> bool:
+    # Must agree with the `read_bool` of this key in
+    # `tools/build_defs/fb_native_wrapper.bzl`, which strips `remote_execution` off
+    # test targets: when the two disagree a target keeps its RE props but loses its
+    # executor, or vice versa. `read_bool` itself is not reusable here because its
+    # `read_config` binding is unavailable during analysis, so mirror its coercion —
+    # including rejecting values it cannot coerce rather than guessing.
+    value = read_root_config("fbcode", "disable_re_tests", "")
+
+    # An empty value means "unset", so that a later config can clear an earlier one.
+    if value == "":
+        return False
+    lowered = value.lower()
+    if lowered == "true":
+        return True
+    if lowered == "false":
+        return False
+    fail("`fbcode:disable_re_tests`: cannot coerce {!r} to bool".format(value))
+
+def _get_re_arg(ctx: AnalysisContext) -> ReArg:
+    if _force_local_re_tests() or not hasattr(ctx.attrs, "remote_execution"):
+        # NOTE: this is kinda weird, we take this path if the attr is missing completely
+        # Even if the value is None we still follow. Adding force.local to give users
+        # some means of bypassing.
+        # Example usecase: SGW wants to run kotlin_test targets on MBP/OSX locally
+        # eg: buck2 test --local-only -c fbcode.disable_re_tests=True //signals/cloudbridge/v2/libs/cb-meters:test
+        return ReArg(re_props = None, default_run_as_bundle = False)
+
+    if ctx.attrs.remote_execution != None:
+        if ctx.attrs.remote_execution == "disabled":
+            return ReArg(disabled = True)
+        elif type_utils.is_string(ctx.attrs.remote_execution):
+            # If this is a string, look up the re_props on the RE toolchain.
+            expect_non_none(ctx.attrs._remote_test_execution_toolchain)
+            return ReArg(
+                re_props = ctx.attrs._remote_test_execution_toolchain[RemoteTestExecutionToolchainInfo].profiles[ctx.attrs.remote_execution],
+                default_run_as_bundle = ctx.attrs._remote_test_execution_toolchain[RemoteTestExecutionToolchainInfo].default_run_as_bundle,
+            )
+
+        return ReArg(re_props = ctx.attrs.remote_execution, default_run_as_bundle = False)
+
+    # Check for a default RE option on the toolchain.
+    re_toolchain = ctx.attrs._remote_test_execution_toolchain
+    if re_toolchain != None and re_toolchain[RemoteTestExecutionToolchainInfo].default_profile != None:
+        return ReArg(
+            re_props = re_toolchain[RemoteTestExecutionToolchainInfo].default_profile,
+            default_run_as_bundle = re_toolchain[RemoteTestExecutionToolchainInfo].default_run_as_bundle,
+        )
+
+    return ReArg(re_props = None, default_run_as_bundle = False)
+
+def maybe_add_run_as_bundle_label(ctx: AnalysisContext, labels: list[str]) -> None:
+    if "re_ignore_force_run_as_bundle" in labels:
+        return
+    re_arg = _get_re_arg(ctx)
+    if re_arg.default_run_as_bundle or _FORCE_RUN_AS_BUNDLE == "True":
+        labels.extend(["run_as_bundle"])
+
+def get_re_executors_from_props(ctx: AnalysisContext, dynamic_image_override: [dict, None] = None) -> RemoteTestExecutorConfig:
+    """
+    Convert the `remote_execution` properties param into `CommandExecutorConfig` objects to use with test providers.
+
+    The target's `network_access` policy (if any) is attached to the returned
+    `CommandExecutorConfig`(s) so it is enforced for both local and remote test
+    execution. When a target has no RE profile, a local-only executor is synthesized
+    so Buck does not fall back to a remote-only build execution platform for a test
+    whose cell-relative paths make it ineligible for RE. The executor is reported with
+    `run_from_project_root = False` so the test keeps running in-place rather than
+    being switched to project-root/RE-style execution.
+
+    Args:
+        ctx: The analysis context.
+        dynamic_image_override: If provided, overrides the `remote_execution_dynamic_image`
+            from `remote_execution` props. Use this to inject a resolved snapshotted fbpkg
+            image (with pinned uuid) at analysis time.
+
+    Returns a `RemoteTestExecutorConfig`.
+    """
+
+    return _get_re_executors(ctx, _get_re_arg(ctx), dynamic_image_override)
+
+def get_re_executors_from_explicit_props(ctx: AnalysisContext, re_props: dict | None) -> RemoteTestExecutorConfig:
+    """
+    Like `get_re_executors_from_props`, but for a rule that carries RE properties in
+    some attribute other than `remote_execution`.
+
+    `re_props` must already be a resolved property dict. The string form of
+    `remote_execution` — the name of a profile on the remote test execution toolchain —
+    is deliberately not accepted here: resolving one requires
+    `_remote_test_execution_toolchain`, and a rule that runs RE only for a secondary
+    test (a rustdoc doctest, say) should not have to take a toolchain dependency to
+    express that.
+
+    Returns a `RemoteTestExecutorConfig`.
+    """
+
+    if _force_local_re_tests():
+        re_props = None
+
+    return _get_re_executors(
+        ctx,
+        ReArg(re_props = re_props, default_run_as_bundle = False),
+        None,
+    )
+
+def _get_re_executors(
+    ctx: AnalysisContext,
+    re_arg: ReArg,
+    dynamic_image_override: [dict, None],
+) -> RemoteTestExecutorConfig:
+    network_access = getattr(ctx.attrs, "network_access", None)
+
+    if re_arg.disabled:
+        executor = CommandExecutorConfig(local_enabled = True, remote_enabled = False, **_network_access_kwargs(network_access))
+        # A `remote_execution = "disabled"` target has always produced an executor
+        # and therefore run from the project root; preserve that behavior.
+        return RemoteTestExecutorConfig(default_executor = executor, run_from_project_root = True, use_project_relative_paths = True)
+
+    re_props = re_arg.re_props
+    if re_props == None:
+        # A test without an RE profile uses cell-relative paths, which makes the test
+        # action local-only. Give it an explicit local executor instead of inheriting
+        # the rule's build execution platform: that platform may be remote-only when
+        # cross-building, even though the target binary must run on the local host.
+        #
+        # `remote_cache_enabled = False` keeps this a plain `Executor::Local`
+        # (parity: the unset default is True in fbcode but False in OSS), and nothing
+        # is uploaded from here anyway (`allow_cache_uploads` is False).
+        executor = CommandExecutorConfig(local_enabled = True, remote_enabled = False, remote_cache_enabled = False, **_network_access_kwargs(network_access))
+        return RemoteTestExecutorConfig(default_executor = executor)
+
+    re_props_copy = dict(re_props)
+    missing_props = [name for name in ("capabilities", "use_case") if name not in re_props_copy]
+    if missing_props:
+        fail("{}: re props are missing required fields: {}".format(ctx.label, ", ".join(missing_props)))
+    capabilities = re_props_copy.pop("capabilities")
+    use_case = re_props_copy.pop("use_case")
+    listing_capabilities = re_props_copy.pop("listing_capabilities", None)
+    remote_cache_enabled = re_props_copy.pop("remote_cache_enabled", None)
+    re_dependencies = re_props_copy.pop("dependencies", [])
+    re_gang_workers = re_props_copy.pop("gang_workers", [])
+    re_gang = re_props_copy.pop("gang", None)
+    local_enabled = re_props_copy.pop("local_enabled", False)
+    local_listing_enabled = re_props_copy.pop("local_listing_enabled", None)
+    re_resource_units = re_props_copy.pop("resource_units", None)
+    re_listing_resource_units = re_props_copy.pop("listing_resource_units", re_resource_units)
+    re_dynamic_image = re_props_copy.pop("remote_execution_dynamic_image", None)
+    meta_internal_extra_params = re_props_copy.pop("meta_internal_extra_params", None)
+    if dynamic_image_override != None:
+        re_dynamic_image = dynamic_image_override
+    if re_props_copy:
+        unexpected_props = ", ".join(re_props_copy.keys())
+        fail("{}: found unexpected re props: {}".format(ctx.label, unexpected_props))
+
+    if re_gang != None:
+        meta_internal_extra_params = dict(meta_internal_extra_params or {})
+        meta_internal_extra_params["remote_execution_gang"] = re_gang
+
+    default_executor = CommandExecutorConfig(
+        local_enabled = local_enabled,
+        remote_enabled = True,
+        remote_execution_properties = capabilities,
+        remote_execution_use_case = use_case or "tpx-default",
+        remote_cache_enabled = remote_cache_enabled,
+        remote_execution_dependencies = re_dependencies,
+        remote_execution_gang_workers = re_gang_workers,
+        remote_execution_resource_units = re_resource_units,
+        remote_execution_dynamic_image = re_dynamic_image,
+        meta_internal_extra_params = meta_internal_extra_params,
+        **_network_access_kwargs(network_access),
+    )
+
+    listing_executor = default_executor
+    if listing_capabilities != None or local_listing_enabled != None:
+        listing_executor = CommandExecutorConfig(
+            local_enabled = local_listing_enabled if local_listing_enabled != None else local_enabled,
+            remote_enabled = True,
+            remote_execution_properties = listing_capabilities if listing_capabilities != None else capabilities,
+            remote_execution_use_case = use_case or "tpx-default",
+            remote_cache_enabled = remote_cache_enabled,
+            remote_execution_resource_units = re_listing_resource_units,
+            remote_execution_dynamic_image = re_dynamic_image,
+            meta_internal_extra_params = meta_internal_extra_params,
+            **_network_access_kwargs(network_access),
+        )
+    return RemoteTestExecutorConfig(
+        default_executor = default_executor,
+        executor_overrides = {"listing": listing_executor},
+        run_from_project_root = True,
+        use_project_relative_paths = True,
+    )
diff --git a/buck2/prelude/tests/remote_test_execution_toolchain.bzl b/buck2/prelude/tests/remote_test_execution_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/tests/remote_test_execution_toolchain.bzl
@@ -0,0 +1,21 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+RemoteTestExecutionToolchainInfo = provider(
+    fields = [
+        # The profile to use by default.
+        "default_profile",
+        # A dictionary of string names to pre-registered profiles.  Rules can
+        # use the profile name to references these.
+        "profiles",
+        # A bool indicating whether the test suites executed by this toolchain
+        # should be run in a bundle. This makes all tests in a suite run in
+        # a single RE action as opposed to one action per test.
+        "default_run_as_bundle",
+    ],
+)
diff --git a/buck2/prelude/tests/test_listing.bzl b/buck2/prelude/tests/test_listing.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/tests/test_listing.bzl
@@ -0,0 +1,14 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+TestListingInfo = provider(
+    doc = "Info for how to list tests for a target",
+    fields = {
+        "list_tests": provider_field(typing.Any, default = None),
+    },
+)
diff --git a/buck2/prelude/tests/test_toolchain.bzl b/buck2/prelude/tests/test_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/tests/test_toolchain.bzl
@@ -0,0 +1,30 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:asserts.bzl", "asserts")
+
+TestToolchainInfo = provider(
+    fields = {
+        # Used to populate sanitizer field in test infra.
+        "sanitizer": str | None,
+    }
+)
+
+def _impl(_ctx: AnalysisContext) -> list[Provider]:
+    return [DefaultInfo(), TestToolchainInfo(sanitizer = None)]
+
+noop_test_toolchain = rule(
+    impl = _impl,
+    attrs = {},
+    is_toolchain_rule = True,
+)
+
+def test_toolchain_labels(test_toolchain: Dependency) -> list[str]:
+    asserts.true(TestToolchainInfo in test_toolchain, "Expected a TestToolchainInfo provider")
+    test_toolchain = test_toolchain[TestToolchainInfo]
+    return [test_toolchain.sanitizer] if test_toolchain.sanitizer else []
diff --git a/buck2/prelude/third-party/build.bzl b/buck2/prelude/third-party/build.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/third-party/build.bzl
@@ -0,0 +1,182 @@
+load("@prelude//:artifacts.bzl", "ArtifactExt", "artifact_ext")
+load("@prelude//:paths.bzl", path_utils = "paths")
+load("@prelude//cxx:cxx_context.bzl", "get_opt_cxx_toolchain_info")
+load("@prelude//cxx:headers.bzl", "as_headers")
+load("@prelude//cxx:preprocessor.bzl", "CPreprocessorInfo")
+load(
+    "@prelude//linking:shared_libraries.bzl",
+    "SharedLibrary",
+    "gen_shared_libs_action",
+)
+load(
+    "@prelude//python:manifest.bzl",
+    "ManifestInfo",  # @unused Used as a type
+)
+load(":providers.bzl", "ThirdPartyBuild", "ThirdPartyBuildInfo", "third_party_build_info")
+
+def prefix_from_label(label: Label, prefix: str = "/usr/local") -> str:
+    """
+    Generate a unique third-party prefix for the given label.
+    """
+    return path_utils.join(prefix, "{}-{}".format(label.name, sha256(str(label.raw_target()))[:7]))
+
+def _get_sh_ext(ctx: AnalysisContext) -> str | None:
+    toolchain_info = get_opt_cxx_toolchain_info(ctx)
+    if toolchain_info:
+        return toolchain_info.linker_info.shared_library_name_format.format("")
+    return None
+
+def is_empty(cxx_headers: list[CPreprocessorInfo]):
+    for pps in cxx_headers:
+        for pp in pps.set.value:
+            for _ in pp.headers:
+                return False
+            for _ in pp.raw_headers:
+                return False
+    return True
+
+def create_third_party_build_root(
+    ctx: AnalysisContext,
+    out: str = "__third_party_build__",
+    manifests: list[(str, ManifestInfo)] = [],
+    shared_libs: list[SharedLibrary] = [],
+    cxx_headers: list[CPreprocessorInfo] = [],
+    paths: list[(str, Artifact)] = [],
+) -> ArtifactExt:
+    """
+    Installs components into a unix-y install dir which can by used by other
+    third-party builds.
+    """
+
+    cmd = cmd_args()
+    cmd.add(ctx.attrs._create_third_party_build_root[RunInfo])
+
+    for dst, manifest in manifests:
+        cmd.add(
+            "--manifest",
+            dst,
+            cmd_args(manifest.manifest, hidden = [a for a, _ in manifest.artifacts]),
+        )
+
+    for pps in cxx_headers:
+        for pp in pps.set.value:
+            for hdr in pp.headers:
+                cmd.add("--path", path_utils.join("include", hdr.namespace, hdr.name), hdr.artifact)
+
+            # Convert raw_headers to proper header paths using as_headers.
+            if pp.raw_headers:
+                raw_dirs = pp.raw_include_dirs + pp.raw_system_include_dirs
+                if raw_dirs:
+                    for hdr in as_headers(ctx, pp.raw_headers, raw_dirs):
+                        cmd.add("--path", path_utils.join("include", hdr.namespace, hdr.name), hdr.artifact)
+
+    for dst, path in paths:
+        cmd.add("--path", dst, path)
+
+    sh_ext = _get_sh_ext(ctx)
+
+    def gen(actions, output, shared_libs):
+        lines = []
+        if shared_libs:
+            for soname, shared_lib in shared_libs.items():
+                lines.append(cmd_args("--file-follow", path_utils.join("lib", soname), shared_lib.lib.output))
+
+                # Linker link `-l<name>` dynamically (by default) by looking for `lib<name>.so`,
+                # so make sure this exists by creating it as a symlink (to the versioned name)
+                # if it doesn't already.
+                if sh_ext in soname and not soname.endswith(sh_ext):
+                    idx = soname.index(sh_ext)
+                    link_name = soname[: idx + 3]
+                    lines.append(cmd_args("--symlink", path_utils.join("lib", link_name), soname))
+        return actions.write(output.as_output(), lines)
+
+    # Add shlibs via argfsile.
+    argsfile = gen_shared_libs_action(
+        actions = ctx.actions,
+        out = "shared_libs_args.txt",
+        shared_libs = shared_libs,
+        gen_action = gen,
+    )
+    cmd.add(cmd_args(argsfile, format = "@{}", hidden = [s.lib.output for s in shared_libs]))
+
+    out = ctx.actions.declare_output(out, dir = True, has_content_based_path = False)
+    cmd.add(out.as_output())
+
+    ctx.actions.run(cmd, category = "third_party_build_root")
+
+    return artifact_ext(out)
+
+def create_third_party_build_info(
+    ctx: AnalysisContext,
+    project: str | None = None,
+    prefix: str | None = None,
+    out: str = "__third_party_build__",
+    manifests: list[(str, ManifestInfo)] = [],
+    shared_libs: list[SharedLibrary] = [],
+    cxx_headers: list[CPreprocessorInfo] = [],
+    cxx_header_dirs: list[str] = [],
+    paths: list[(str, Artifact)] = [],
+    children: list[ThirdPartyBuildInfo] = [],
+    deps: list[Dependency] = [],
+) -> ThirdPartyBuildInfo:
+    if prefix == None:
+        prefix = prefix_from_label(ctx.label)
+
+    root = create_third_party_build_root(
+        ctx = ctx,
+        out = out,
+        manifests = manifests,
+        cxx_headers = cxx_headers,
+        shared_libs = shared_libs,
+        paths = paths,
+    )
+
+    sh_ext = _get_sh_ext(ctx)
+
+    include_paths = []
+    if not is_empty(cxx_headers):
+        include_paths.append("include")
+    include_paths.extend(cxx_header_dirs)
+
+    # Build manifest.
+    def gen_manifest(actions, output, shared_libs):
+        manifest = {}
+        if project != None:
+            manifest["project"] = project
+        manifest["prefix"] = prefix
+        manifest["bin_paths"] = []
+        manifest["c_include_paths"] = include_paths
+        manifest["cxx_include_paths"] = include_paths
+        if shared_libs:
+            manifest["lib_paths"] = ["lib"]
+            manifest["runtime_lib_paths"] = ["lib"]
+            libs = []
+            for soname in shared_libs:
+                if sh_ext in soname:
+                    lib = soname.split(sh_ext)[0].removeprefix("lib")
+                    libs.append("-l{}".format(lib))
+            manifest["libs"] = libs
+        else:
+            manifest["lib_paths"] = []
+            manifest["runtime_lib_paths"] = []
+            manifest["libs"] = []
+        return actions.write_json(output.as_output(), manifest, pretty = True)
+
+    manifest = gen_shared_libs_action(
+        actions = ctx.actions,
+        out = out + ".json",
+        shared_libs = shared_libs,
+        gen_action = gen_manifest,
+    )
+
+    return third_party_build_info(
+        actions = ctx.actions,
+        build = ThirdPartyBuild(
+            project = project,
+            prefix = prefix,
+            root = root,
+            manifest = manifest,
+        ),
+        deps = deps,
+        children = children,
+    )
diff --git a/buck2/prelude/third-party/hmaptool/BUCK b/buck2/prelude/third-party/hmaptool/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/third-party/hmaptool/BUCK
@@ -0,0 +1,13 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native  # Avoid warnings and auto-formatters
+
+prelude.export_file(
+    name = "hmaptool",
+    src = "hmaptool",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/third-party/hmaptool/METADATA.bzl b/buck2/prelude/third-party/hmaptool/METADATA.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/third-party/hmaptool/METADATA.bzl
@@ -0,0 +1,4 @@
+METADATA = {
+    "name": "hmaptool",
+    "owner": "build_infra",
+}
diff --git a/buck2/prelude/third-party/hmaptool/README.md b/buck2/prelude/third-party/hmaptool/README.md
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/third-party/hmaptool/README.md
@@ -0,0 +1,22 @@
+# hmaptool
+
+This tool was copied from llvm-project. See https://github.com/llvm/llvm-project/blob/main/clang/utils/hmaptool/hmaptool
+
+## About
+
+Header maps are binary files used by Xcode, which are used to map
+header names or paths to other locations. Clang has support for
+those since its inception, but there's not a lot of header map
+testing around.
+
+Since it's a binary format, testing becomes pretty much brittle
+and its hard to even know what's inside if you don't have the
+appropriate tools.
+
+Add a python based tool that allows creating and dumping header
+maps based on a json description of those. While here, rewrite
+tests to use the tool and remove the binary files from the tree.
+
+This tool was initially written by Daniel Dunbar.
+
+Thanks to Stella Stamenova for helping make this work on Windows.
diff --git a/buck2/prelude/third-party/hmaptool/hmaptool b/buck2/prelude/third-party/hmaptool/hmaptool
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/third-party/hmaptool/hmaptool
@@ -0,0 +1,328 @@
+#!/usr/bin/env python3
+
+# ===----------------------------------------------------------------------=== #
+# 
+#  Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+#  See https://llvm.org/LICENSE.txt for license information.
+#  SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+# 
+# ===----------------------------------------------------------------------=== #
+
+from __future__ import absolute_import, division, print_function
+
+import json
+import optparse
+import os
+import struct
+import sys
+
+###
+
+k_header_magic_LE = b'pamh'
+k_header_magic_BE = b'hmap'
+
+def hmap_hash(str):
+    """hash(str) -> int
+
+    Apply the "well-known" headermap hash function.
+    """
+
+    return sum((ord(c.lower()) * 13
+                for c in str), 0)
+
+class HeaderMap(object):
+    @staticmethod
+    def frompath(path):
+        with open(path, 'rb') as f:
+            magic = f.read(4)
+            if magic == k_header_magic_LE:
+                endian_code = '<'
+            elif magic == k_header_magic_BE:
+                endian_code = '>'
+            else:
+                raise SystemExit("error: %s: not a headermap" % (
+                        path,))
+
+            # Read the header information.
+            header_fmt = endian_code + 'HHIIII'
+            header_size = struct.calcsize(header_fmt)
+            data = f.read(header_size)
+            if len(data) != header_size:
+                raise SystemExit("error: %s: truncated headermap header" % (
+                        path,))
+
+            (version, reserved, strtable_offset, num_entries,
+             num_buckets, max_value_len) = struct.unpack(header_fmt, data)
+
+            if version != 1:
+                raise SystemExit("error: %s: unknown headermap version: %r" % (
+                        path, version))
+            if reserved != 0:
+                raise SystemExit("error: %s: invalid reserved value in header" % (
+                        path,))
+
+            # The number of buckets must be a power of two.
+            if num_buckets == 0 or (num_buckets & num_buckets - 1) != 0:
+                raise SystemExit("error: %s: invalid number of buckets" % (
+                        path,))
+
+            # Read all of the buckets.
+            bucket_fmt = endian_code + 'III'
+            bucket_size = struct.calcsize(bucket_fmt)
+            buckets_data = f.read(num_buckets * bucket_size)
+            if len(buckets_data) != num_buckets * bucket_size:
+                raise SystemExit("error: %s: truncated headermap buckets" % (
+                        path,))
+            buckets = [struct.unpack(bucket_fmt,
+                                     buckets_data[i*bucket_size:(i+1)*bucket_size])
+                       for i in range(num_buckets)]
+
+            # Read the string table; the format doesn't explicitly communicate the
+            # size of the string table (which is dumb), so assume it is the rest of
+            # the file.
+            f.seek(0, 2)
+            strtable_size = f.tell() - strtable_offset
+            f.seek(strtable_offset)
+
+            if strtable_size == 0:
+                raise SystemExit("error: %s: unable to read zero-sized string table"%(
+                        path,))
+            strtable = f.read(strtable_size)
+
+            if len(strtable) != strtable_size:
+                raise SystemExit("error: %s: unable to read complete string table"%(
+                        path,))
+            if strtable[-1] != 0:
+                raise SystemExit("error: %s: invalid string table in headermap" % (
+                        path,))
+
+            return HeaderMap(num_entries, buckets, strtable)
+
+    def __init__(self, num_entries, buckets, strtable):
+        self.num_entries = num_entries
+        self.buckets = buckets
+        self.strtable = strtable
+
+    def get_string(self, idx):
+        if idx >= len(self.strtable):
+            raise SystemExit("error: %s: invalid string index" % (
+                    path,))
+        end_idx = self.strtable.index(b'\0', idx)
+        return self.strtable[idx:end_idx].decode()
+
+    @property
+    def mappings(self):
+        for key_idx,prefix_idx,suffix_idx in self.buckets:
+            if key_idx == 0:
+                continue
+            yield (self.get_string(key_idx),
+                   self.get_string(prefix_idx) + self.get_string(suffix_idx))
+
+class StringTable:
+    def __init__(self):
+        # A string table offset of 0 is interpreted as an empty bucket, so it's
+        # important we don't assign an actual string to that offset.
+        self.table = "\0"
+        # For the same reason we don't want the empty string having a 0 offset.
+        self.offsets = {}
+
+    def add(self, string):
+        offset = self.offsets.get(string)
+        if offset:
+            return offset
+
+        offset = len(self.table)
+        self.table += string + "\0"
+        self.offsets[string] = offset
+        return offset
+
+###
+
+def action_dump(name, args):
+    "dump a headermap file"
+
+    parser = optparse.OptionParser("%%prog %s [options] <headermap path>" % (
+            name,))
+    parser.add_option("-v", "--verbose", dest="verbose",
+                      help="show more verbose output [%default]",
+                      action="store_true", default=False)
+    parser.add_option("--json", dest="json",
+                      help="output as JSON [%default]",
+                      action="store_true", default=False)
+    (opts, args) = parser.parse_args(args)
+
+    if len(args) != 1:
+        parser.error("invalid number of arguments")
+
+    path, = args
+
+    hmap = HeaderMap.frompath(path)
+
+    # Dump all of the buckets.
+    if opts.verbose:
+        print ('headermap: %r' % (path,))
+        print ('  num entries: %d' % (hmap.num_entries,))
+        print ('  num buckets: %d' % (len(hmap.buckets),))
+        print ('  string table size: %d' % (len(hmap.strtable),))
+        for i,bucket in enumerate(hmap.buckets):
+            key_idx,prefix_idx,suffix_idx = bucket
+
+            if key_idx == 0:
+                continue
+
+            # Get the strings.
+            key = hmap.get_string(key_idx)
+            prefix = hmap.get_string(prefix_idx)
+            suffix = hmap.get_string(suffix_idx)
+
+            print ("  bucket[%d]: %r -> (%r, %r) -- %d" % (
+                i, key, prefix, suffix, (hmap_hash(key) & (len(hmap.buckets) - 1))))
+    elif opts.json:
+        print(json.dumps({"mappings": dict(hmap.mappings)}, indent=4))
+    else:
+        print ('Header Map: %s' % (path,))
+        mappings = sorted(hmap.mappings)
+        for key,value in mappings:
+            print ("%s -> %s" % (key, value))
+    print ()
+
+def next_power_of_two(value):
+    if value < 0:
+        raise ArgumentError
+    return 1 if value == 0 else 2**(value - 1).bit_length()
+
+def action_write(name, args):
+    "write a headermap file from a JSON definition"
+
+    parser = optparse.OptionParser("%%prog %s [options] <input path> <output path>" % (
+            name,))
+    (opts, args) = parser.parse_args(args)
+
+    if len(args) != 2:
+        parser.error("invalid number of arguments")
+
+    input_path,output_path = args
+
+    with open(input_path, "r") as f:
+        input_data = json.load(f)
+
+    # Compute the headermap contents, we make a table that is 1/3 full.
+    mappings = input_data['mappings']
+    num_buckets = next_power_of_two(len(mappings) * 3)
+
+    table = [(0, 0, 0)
+             for i in range(num_buckets)]
+    max_value_len = 0
+    strtable = StringTable()
+    for key,value in mappings.items():
+        if not isinstance(key, str):
+            key = key.decode('utf-8')
+        if not isinstance(value, str):
+            value = value.decode('utf-8')
+        max_value_len = max(max_value_len, len(value))
+
+        key_idx = strtable.add(key)
+        prefix, suffix = os.path.split(value)
+        # This guarantees that prefix + suffix == value in all cases, including when
+        # prefix is empty or contains a trailing slash or suffix is empty (hence the use
+        # of `len(value) - len(suffix)` instead of just `-len(suffix)`.
+        prefix += value[len(prefix) : len(value) - len(suffix)]
+        prefix_idx = strtable.add(prefix)
+        suffix_idx = strtable.add(suffix)
+
+        hash = hmap_hash(key)
+        for i in range(num_buckets):
+            idx = (hash + i) % num_buckets
+            if table[idx][0] == 0:
+                table[idx] = (key_idx, prefix_idx, suffix_idx)
+                break
+        else:
+            raise RuntimeError
+
+    endian_code = '<'
+    magic = k_header_magic_LE
+    magic_size = 4
+    header_fmt = endian_code + 'HHIIII'
+    header_size = struct.calcsize(header_fmt)
+    bucket_fmt = endian_code + 'III'
+    bucket_size = struct.calcsize(bucket_fmt)
+    strtable_offset = magic_size + header_size + num_buckets * bucket_size
+    header = (1, 0, strtable_offset, len(mappings),
+              num_buckets, max_value_len)
+
+    # Write out the headermap.
+    with open(output_path, 'wb') as f:
+        f.write(magic)
+        f.write(struct.pack(header_fmt, *header))
+        for bucket in table:
+            f.write(struct.pack(bucket_fmt, *bucket))
+        f.write(strtable.table.encode())
+
+def action_tovfs(name, args):
+    "convert a headermap to a VFS layout"
+
+    parser = optparse.OptionParser("%%prog %s [options] <headermap path>" % (
+            name,))
+    parser.add_option("", "--build-path", dest="build_path",
+                      help="build path prefix",
+                      action="store", type=str)
+    (opts, args) = parser.parse_args(args)
+
+    if len(args) != 2:
+        parser.error("invalid number of arguments")
+    if opts.build_path is None:
+        parser.error("--build-path is required")
+
+    input_path,output_path = args
+
+    hmap = HeaderMap.frompath(input_path)
+
+    # Create the table for all the objects.
+    vfs = {}
+    vfs['version'] = 0
+    build_dir_contents = []
+    vfs['roots'] = [{
+            'name' : opts.build_path,
+            'type' : 'directory',
+            'contents' : build_dir_contents }]
+
+    # We assume we are mapping framework paths, so a key of "Foo/Bar.h" maps to
+    # "<build path>/Foo.framework/Headers/Bar.h".
+    for key,value in hmap.mappings:
+        # If this isn't a framework style mapping, ignore it.
+        components = key.split('/')
+        if len(components) != 2:
+            continue
+        framework_name,header_name = components
+        build_dir_contents.append({
+                'name' : '%s.framework/Headers/%s' % (framework_name,
+                                                      header_name),
+                'type' : 'file',
+                'external-contents' : value })
+
+    with open(output_path, 'w') as f:
+        json.dump(vfs, f, indent=2)
+
+commands = dict((name[7:].replace("_","-"), f)
+                for name,f in locals().items()
+                if name.startswith('action_'))
+
+def usage():
+    print ("Usage: %s command [options]" % (
+        os.path.basename(sys.argv[0])), file=sys.stderr)
+    print (file=sys.stderr)
+    print ("Available commands:", file=sys.stderr)
+    cmds_width = max(map(len, commands))
+    for name,func in sorted(commands.items()):
+        print ("  %-*s - %s" % (cmds_width, name, func.__doc__), file=sys.stderr)
+    sys.exit(1)
+
+def main():
+    if len(sys.argv) < 2 or sys.argv[1] not in commands:
+        usage()
+
+    cmd = sys.argv[1]
+    commands[cmd](cmd, sys.argv[2:])
+
+if __name__ == '__main__':
+    main()
diff --git a/buck2/prelude/third-party/pkgconfig.bzl b/buck2/prelude/third-party/pkgconfig.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/third-party/pkgconfig.bzl
@@ -0,0 +1,89 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under both the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree and the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree.
+
+load("@prelude//:prelude.bzl", "native")
+
+# NB: Meta engineers should not use this! Please use tp2 instead:
+# https://fburl.com/wiki/oyy0fi5j
+#
+# If a system has a package installed and that package provides a `.pc` file
+# this rule can be used to make that library visible to other rules. The `name`
+# of this rule should be the pkg-config name. For example, if
+# `pkg-config --libs gtest` prints out the flags to link against gtest, then
+# `external_pkgconfig_library(name = "gtest")` would allow other rules to
+# depend on gtest.
+#
+# WARNING: dependencies are not resolved by pkg-config, so these must be specified
+# manually with `deps`. Additionally, ABI/platform differences are not handled
+# by this rule so be careful not to cache it in Remote Execution etc to prevent
+# different machines from reusing the outputs of these rules.
+#
+# LOCAL FORK: the cflags genrule below always appends a harmless
+# `-I.nonexistent` after whatever pkg-config (or the fallback)
+# actually produces, guaranteeing its output file is never
+# empty. Reason: when a Haskell compile passes these flags to GHC it
+# prepends an `-optP=` prefix, so we get `-optP=@file`, and GHC then
+# passes this onto the C compiler as `-Xpreprocessor @file`. If @file
+# is empty, this causes the C compiler to interpret the next argument
+# as the argument to `-Xpreprocessor`, resulting in a misparsing of
+# the command line. Therefore we ensure that @file is never empty.
+
+def external_pkgconfig_library(
+    name, package = None, visibility = ["PUBLIC"], labels = [], default_target_platform = "prelude//platforms:default", deps = [], fallback = None
+):
+    if package == None:
+        package = name
+
+    cmd_cflags = "pkg-config --cflags {} > $OUT; echo '-I.nonexistent' >> $OUT".format(package)
+    cmd_libs = "pkg-config --libs {} > $OUT".format(package)
+
+    if fallback != None:
+        preprocessor_flags = fallback.preprocessor_flags if hasattr(fallback, "preprocessor_flags") else []
+        linker_flags = fallback.linker_flags if hasattr(fallback, "linker_flags") else []
+
+        cmd_cflags = "if pkg-config --exists {}; then {}; else echo {} > $OUT; fi".format(
+            package,
+            cmd_cflags,
+            " ".join(preprocessor_flags) + " -I.nonexistent",
+        )
+
+        cmd_libs = "if pkg-config --exists {}; then {}; else echo {} > $OUT; fi".format(
+            package,
+            cmd_libs,
+            " ".join(linker_flags),
+        )
+
+    pkg_config_cflags = name + "__pkg_config_cflags"
+    native.genrule(
+        name = pkg_config_cflags,
+        default_target_platform = default_target_platform,
+        out = "out",
+        cmd = cmd_cflags,
+        remote = False,
+    )
+
+    pkg_config_libs = name + "__pkg_config_libs"
+    native.genrule(
+        name = pkg_config_libs,
+        default_target_platform = default_target_platform,
+        out = "out",
+        cmd = cmd_libs,
+        remote = False,
+    )
+
+    labels = list(labels)
+    labels.append("third-party:pkg-config:{}".format(package))
+
+    native.prebuilt_cxx_library(
+        name = name,
+        default_target_platform = default_target_platform,
+        visibility = visibility,
+        exported_preprocessor_flags = ["@$(location :{})".format(pkg_config_cflags)],
+        exported_linker_flags = ["@$(location :{})".format(pkg_config_libs)],
+        exported_deps = deps,
+        labels = labels,
+    )
diff --git a/buck2/prelude/third-party/providers.bzl b/buck2/prelude/third-party/providers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/third-party/providers.bzl
@@ -0,0 +1,46 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under both the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree and the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree.
+
+load("@prelude//:artifacts.bzl", "ArtifactExt")
+
+ThirdPartyBuild = record(
+    # A logical project name for the project, currently used for logging.
+    project = field(str | None, None),
+    # The directory containing the build output.
+    root = field(ArtifactExt),
+    # The prefix to install the build output.
+    prefix = field(str, "/"),
+    # A manifest of build env settings to use to build against this build.
+    manifest = field(Artifact | None, None),
+    # Environment variables to set to build against this project.
+    # TODO(agallagher): Can this move into the manifest?
+    exported_env = field(dict[str, str], {}),
+)
+
+# Work-around for buck2 bug causing "transitive values must be of the same
+# transitive set type" errors:
+# https://fb.prod.workplace.com/groups/buck2users/posts/3637287806527574/
+ThirdPartyBuildTSet = transitive_set()
+ThirdPartyBuildInfo = provider(
+    fields = {
+        "build": provider_field(ThirdPartyBuild | None),
+        "_tset": provider_field(ThirdPartyBuildTSet),
+    }
+)
+
+def third_party_build_info(
+    actions, build: [ThirdPartyBuild, None] = None, children: list[ThirdPartyBuildInfo] = [], deps: list[Dependency] = []
+) -> ThirdPartyBuildInfo:
+    kwargs = {}
+    if build != None:
+        kwargs["value"] = build
+    if deps or children:
+        kwargs["children"] = [child._tset for child in children] + [dep[ThirdPartyBuildInfo]._tset for dep in deps if ThirdPartyBuildInfo in dep]
+    return ThirdPartyBuildInfo(
+        build = build,
+        _tset = actions.tset(ThirdPartyBuildTSet, **kwargs),
+    )
diff --git a/buck2/prelude/third-party/tools/BUCK b/buck2/prelude/third-party/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/third-party/tools/BUCK
@@ -0,0 +1,13 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.python_bootstrap_binary(
+    name = "create_build",
+    main = "create_build.py",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/third-party/tools/create_build.py b/buck2/prelude/third-party/tools/create_build.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/third-party/tools/create_build.py
@@ -0,0 +1,84 @@
+import argparse
+import shutil
+import stat
+import json
+import sys
+import os
+
+
+# Copy only file contents and exec permission bit.
+def _copy(src, dst, follow_symlinks=True):
+    if os.path.islink(src) and not follow_symlinks:
+        target = os.readlink(src)
+        os.symlink(target, dst)
+    else:
+        shutil.copyfile(src, dst)
+        src_mode = os.lstat(src).st_mode
+        dst_mode = os.lstat(dst).st_mode
+        os.chmod(
+            dst,
+            dst_mode | (src_mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)),
+        )
+
+
+def _copy_tree(src, dst, *, dirs_exist_ok=False):
+    os.makedirs(dst, exist_ok=dirs_exist_ok)
+
+    for root, dirs, files in os.walk(src):
+        rel_root = os.path.relpath(root, src)
+
+        for f in files:
+            src_path = os.path.join(root, f)
+            dst_path = os.path.join(dst, rel_root, f)
+            _copy(src_path, dst_path, follow_symlinks=False)
+
+        for d in dirs:
+            dst_path = os.path.join(dst, rel_root, d)
+            os.makedirs(dst_path, exist_ok=dirs_exist_ok)
+
+
+def main(argv):
+    parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
+    parser.add_argument(
+        "--manifest", dest="manifests", nargs=2, action="append", default=[]
+    )
+    parser.add_argument("--path", dest="paths", nargs=2, action="append", default=[])
+    parser.add_argument("--file-follow", dest="files_follow", nargs=2, action="append", default=[])
+    parser.add_argument(
+        "--symlink", dest="symlinks", nargs=2, action="append", default=[]
+    )
+    parser.add_argument("output")
+    args = parser.parse_args(argv[1:])
+
+    os.makedirs(args.output)
+
+    all_paths = []
+    all_paths.extend(args.paths)
+
+    for bdst, manifest in args.manifests:
+        with open(manifest) as mf:
+            manifest = json.load(mf)
+        for dst, src, _ in manifest:
+            dst = os.path.join(bdst, dst)
+            all_paths.append((dst, src))
+
+    for dst, src in all_paths:
+        fdst = os.path.join(args.output, dst)
+        os.makedirs(os.path.dirname(fdst), exist_ok=True)
+        if os.path.isdir(src):
+            _copy_tree(src, fdst, dirs_exist_ok=True)
+        else:
+            _copy(src, fdst, follow_symlinks=False)
+
+    for dst, src in args.files_follow:
+        fdst = os.path.join(args.output, dst)
+        os.makedirs(os.path.dirname(fdst), exist_ok=True)
+        _copy(src, fdst, follow_symlinks=True)
+
+    for dst, target in args.symlinks:
+        fdst = os.path.join(args.output, dst)
+        os.makedirs(os.path.dirname(fdst), exist_ok=True)
+        os.symlink(target, fdst)
+
+
+sys.exit(main(sys.argv))
diff --git a/buck2/prelude/toolchains/android.bzl b/buck2/prelude/toolchains/android.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android.bzl
@@ -0,0 +1,305 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android:android_toolchain.bzl", "AidlToolchainInfo", "AndroidPlatformInfo", "AndroidToolchainInfo")
+load("@prelude//target_stats:target_stats_tools.bzl", "TargetStatsToolsInfo")
+load("@prelude//tests:test_listing.bzl", "TestListingInfo")
+
+def _android_sdk_tools_impl(ctx):
+    sub_targets = {}
+
+    sub_targets["aapt2"] = [RunInfo(args = ["{}/build-tools/{}/aapt2".format(ctx.attrs.android_sdk_path, ctx.attrs.build_tools_version)])]
+    sub_targets["aidl"] = [RunInfo(args = ["{}/build-tools/{}/aidl".format(ctx.attrs.android_sdk_path, ctx.attrs.build_tools_version)])]
+    sub_targets["zipalign"] = [RunInfo(args = ["{}/build-tools/{}/zipalign".format(ctx.attrs.android_sdk_path, ctx.attrs.build_tools_version)])]
+
+    sub_targets["adb"] = [RunInfo(args = ["{}/build-tools/platform-tools/adb".format(ctx.attrs.android_sdk_path)])]
+
+    android_jar = ctx.actions.declare_output("android.jar", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(["ln", "-s", "{}/platforms/{}/android.jar".format(ctx.attrs.android_sdk_path, ctx.attrs.compile_sdk_version), android_jar.as_output()]),
+        category = "android_jar_symlink",
+    )
+    sub_targets["android.jar"] = [DefaultInfo(default_output = android_jar)]
+
+    core_for_system_modules_jar = ctx.actions.declare_output("core-for-system-modules.jar", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args([
+            "ln",
+            "-s",
+            "{}/platforms/{}/core-for-system-modules.jar".format(ctx.attrs.android_sdk_path, ctx.attrs.compile_sdk_version),
+            core_for_system_modules_jar.as_output(),
+        ]),
+        category = "core_for_system_modules_jar_symlink",
+    )
+    sub_targets["core-for-system-modules.jar"] = [DefaultInfo(default_output = core_for_system_modules_jar)]
+
+    framework_aidl_file = ctx.actions.declare_output("framework.aidl", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(
+            ["ln", "-s", "{}/platforms/{}/framework.aidl".format(ctx.attrs.android_sdk_path, ctx.attrs.compile_sdk_version), framework_aidl_file.as_output()]
+        ),
+        category = "framework_aidl_symlink",
+    )
+    sub_targets["framework.aidl"] = [DefaultInfo(default_output = framework_aidl_file)]
+
+    optimized_proguard_config = ctx.actions.declare_output("proguard-android-optimize.txt", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(
+            ["ln", "-s", "{}/platforms/tools/proguard/proguard-android-optimize.txt".format(ctx.attrs.android_sdk_path), optimized_proguard_config.as_output()]
+        ),
+        category = "optimized_proguard_config_symlink",
+    )
+    sub_targets["optimized_proguard_config"] = [DefaultInfo(default_output = optimized_proguard_config)]
+
+    proguard_config = ctx.actions.declare_output("proguard-android.txt", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(["ln", "-s", "{}/platforms/tools/proguard/proguard-android.txt".format(ctx.attrs.android_sdk_path), proguard_config.as_output()]),
+        category = "proguard_config_symlink",
+    )
+    sub_targets["proguard_config"] = [DefaultInfo(default_output = proguard_config)]
+
+    proguard_jar = ctx.actions.declare_output("proguard.jar", has_content_based_path = False)
+    ctx.actions.run(
+        cmd_args(["ln", "-s", "{}/platforms/tools/proguard/lib/proguard.jar".format(ctx.attrs.android_sdk_path), proguard_jar.as_output()]),
+        category = "proguard_jar_symlink",
+    )
+    sub_targets["proguard.jar"] = [DefaultInfo(default_output = proguard_jar)]
+
+    return [
+        DefaultInfo(sub_targets = sub_targets),
+    ]
+
+android_sdk_tools = rule(
+    impl = _android_sdk_tools_impl,
+    attrs = {
+        "android_sdk_path": attrs.string(default = read_root_config("android", "sdk_path", "/opt/android_sdk")),
+        "build_tools_version": attrs.string(default = read_root_config("android", "build_tools_version", "35.0.0")),
+        "compile_sdk_version": attrs.string(default = read_root_config("android", "compile_sdk_version", "android-35")),
+    },
+)
+
+def system_android_aidl_toolchain(name, android_sdk_tools_target, **kwargs):
+    kwargs["aidl"] = "{}[aidl]".format(android_sdk_tools_target)
+    kwargs["framework_aidl_file"] = "{}[framework.aidl]".format(android_sdk_tools_target)
+    _system_android_aidl_toolchain_rule(name = name, **kwargs)
+
+def _system_android_aidl_toolchain_rule_impl(ctx):
+    return [
+        DefaultInfo(),
+        AidlToolchainInfo(
+            aidl = ctx.attrs.aidl[RunInfo],
+            framework_aidl_file = ctx.attrs.framework_aidl_file,
+        ),
+    ]
+
+_system_android_aidl_toolchain_rule = rule(
+    attrs = {
+        "aidl": attrs.exec_dep(providers = [RunInfo]),
+        "framework_aidl_file": attrs.source(),
+    },
+    impl = _system_android_aidl_toolchain_rule_impl,
+    is_toolchain_rule = True,
+)
+
+def system_android_toolchain(name, android_sdk_tools_target, jdk_system_image, **kwargs):
+    kwargs["aapt2_filter_resources"] = "prelude//android/tools:filter_extra_resources"
+    kwargs["aapt2"] = "{}[aapt2]".format(android_sdk_tools_target)
+    kwargs["aar_builder"] = "prelude//toolchains/android/src/com/facebook/buck/android/aar:aar_builder_binary"
+    kwargs["adb"] = "{}[adb]".format(android_sdk_tools_target)
+    kwargs["android_jar"] = "{}[android.jar]".format(android_sdk_tools_target)
+    kwargs["android_optional_jars"] = []
+    kwargs["apk_builder"] = "prelude//toolchains/android/src/com/facebook/buck/android/apk:apk_builder_binary"
+    kwargs["apk_module_graph"] = "prelude//toolchains/android/src/com/facebook/buck/android/apkmodule:apkmodule_binary"
+    kwargs["app_without_resources_stub"] = "prelude//android/tools:app_without_resources_stub"
+    kwargs["bundle_apks_builder"] = "prelude//toolchains/android/src/com/facebook/buck/android/bundle:bundle_apks_builder_binary"
+    kwargs["bundle_builder"] = "prelude//toolchains/android/src/com/facebook/buck/android/bundle:bundle_builder_binary"
+    kwargs["combine_native_library_dirs"] = "prelude//android/tools:combine_native_library_dirs"
+    kwargs["consolidate_class_names"] = "prelude//android/tools:consolidate_class_names"
+    kwargs["copy_string_resources"] = "prelude//toolchains/android/src/com/facebook/buck/android/resources/strings:copy_string_resources_binary"
+    kwargs["cross_module_native_deps_check"] = True
+    kwargs["d8_command"] = "prelude//toolchains/android/src/com/facebook/buck/android/dex:run_d8_binary"
+    kwargs["duplicate_class_checker"] = "prelude//android/tools:duplicate_class_checker"
+    kwargs["exo_resources_rewriter"] = "prelude//toolchains/android/src/com/facebook/buck/android/resources:exo_resources_rewriter_binary"
+    kwargs["filter_dex_class_names"] = "prelude//android/tools:filter_dex"
+    kwargs["filter_prebuilt_native_library_dir"] = "prelude//android/tools:filter_prebuilt_native_library_dir"
+    kwargs["filter_resources"] = "prelude//toolchains/android/src/com/facebook/buck/android/resources/filter:filter_resources_binary"
+    # @oss-disable[end= ]: kwargs["gatorade_mergemap_tool"] = "prelude//android/tools/meta_only:gatorade_mergemap_tool"
+    kwargs["generate_build_config"] = "prelude//toolchains/android/src/com/facebook/buck/android/build_config:generate_build_config_binary"
+    kwargs["generate_manifest"] = "prelude//toolchains/android/src/com/facebook/buck/android/manifest:generate_manifest_binary"
+    kwargs["sort_pre_dexed_files"] = "prelude//android/tools:sort_pre_dexed_files"
+    kwargs["installer"] = "prelude//toolchains/android/src/com/facebook/buck/installer/android:android_installer"
+    kwargs["instrumentation_test_can_run_locally"] = True
+    kwargs["collect_perfetto"] = False
+    kwargs["instrumentation_test_runner_classpath"] = [
+        "prelude//toolchains/android/src/com/facebook/buck/testrunner:testrunner-bin-android-fixed",
+        "prelude//toolchains/android/third-party:android-common",
+        "prelude//toolchains/android/third-party:ddmlib",
+        "prelude//toolchains/android/third-party:guava-jar",
+        "prelude//toolchains/android/third-party:failureaccess",
+        "prelude//toolchains/android/third-party:listenablefuture",
+        "prelude//toolchains/android/third-party:kxml2",
+        "prelude//toolchains/android/third-party:protobuf",
+        "prelude//toolchains/android/third-party:jackson-annotations",
+        "prelude//toolchains/android/third-party:jackson-core",
+        "prelude//toolchains/android/third-party:jackson-databind-jar",
+    ]
+    kwargs["instrumentation_test_runner_main_class"] = "com.facebook.buck.testrunner.InstrumentationMain"
+    kwargs["jar_splitter_command"] = "prelude//toolchains/android/src/com/facebook/buck/android/dex:jar_splitter_binary"
+    kwargs["jdk_system_image"] = jdk_system_image
+    kwargs["manifest_utils"] = "prelude//toolchains/android/src/com/facebook/buck/android:manifest_utils_binary"
+    kwargs["merge_android_resource_sources"] = "prelude//toolchains/android/src/com/facebook/buck/android/aapt:merge_android_resource_sources_binary"
+    kwargs["merge_android_resources"] = "prelude//toolchains/android/src/com/facebook/buck/android/resources:merge_android_resources_binary"
+    kwargs["merge_assets"] = "prelude//toolchains/android/src/com/facebook/buck/android/resources:merge_assets_binary"
+    kwargs["mergemap_tool"] = "prelude//android/tools:compute_merge_sequence"
+    kwargs["mini_aapt"] = "prelude//toolchains/android/src/com/facebook/buck/android/aapt:mini_aapt_binary"
+    kwargs["multi_dex_command"] = "prelude//toolchains/android/src/com/facebook/buck/android/dex:multi_dex_binary"
+    kwargs["native_libs_as_assets_metadata"] = "prelude//android/tools:native_libs_as_assets_metadata"
+    kwargs["optimized_proguard_config"] = "{}[optimized_proguard_config]".format(android_sdk_tools_target)
+    kwargs["package_meta_inf_version_files"] = False
+    kwargs["package_strings_as_assets"] = "prelude//toolchains/android/src/com/facebook/buck/android/resources/strings:package_strings_as_assets_binary"
+    kwargs["proguard_config"] = "{}[proguard_config]".format(android_sdk_tools_target)
+    kwargs["proguard_jar"] = "{}[proguard.jar]".format(android_sdk_tools_target)
+    kwargs["r_dot_java_weight_factor"] = 8
+    kwargs["replace_application_id_placeholders"] = (
+        "prelude//toolchains/android/src/com/facebook/buck/android/manifest:replace_application_id_placeholders_binary"
+    )
+    kwargs["secondary_dex_compression_command"] = "prelude//toolchains/android/src/com/facebook/buck/android/dex:secondary_dex_compression_binary"
+    kwargs["secondary_dex_weight_limit"] = 1024
+    kwargs["unpack_aar"] = "prelude//android/tools:unpack_aar"
+    kwargs["zipalign"] = "{}[zipalign]".format(android_sdk_tools_target)
+
+    system_android_toolchain_rule(name = name, **kwargs)
+
+def system_android_toolchain_rule_impl(ctx):
+    return [
+        DefaultInfo(),
+        AndroidPlatformInfo(
+            name = ctx.attrs.name,
+        ),
+        TestListingInfo(
+            list_tests = ctx.attrs.list_tests,
+        ),
+        AndroidToolchainInfo(
+            target_stats_tools = ctx.attrs.target_stats_tools[TargetStatsToolsInfo] if ctx.attrs.target_stats_tools else None,
+            aapt2 = ctx.attrs.aapt2[RunInfo],
+            aapt2_filter_resources = ctx.attrs.aapt2_filter_resources[RunInfo],
+            aar_builder = ctx.attrs.aar_builder[RunInfo],
+            adb = ctx.attrs.adb[RunInfo],
+            android_bootclasspath = [ctx.attrs.android_jar],
+            android_jar = ctx.attrs.android_jar,
+            android_optional_jars = ctx.attrs.android_optional_jars,
+            apk_builder = ctx.attrs.apk_builder,
+            apk_module_graph = ctx.attrs.apk_module_graph,
+            app_without_resources_stub = ctx.attrs.app_without_resources_stub,
+            bundle_apks_builder = ctx.attrs.bundle_apks_builder,
+            bundle_builder = ctx.attrs.bundle_builder,
+            combine_native_library_dirs = ctx.attrs.combine_native_library_dirs,
+            consolidate_class_names = ctx.attrs.consolidate_class_names,
+            copy_string_resources = ctx.attrs.copy_string_resources,
+            cross_module_native_deps_check = ctx.attrs.cross_module_native_deps_check,
+            d8_command = ctx.attrs.d8_command,
+            duplicate_class_checker = ctx.attrs.duplicate_class_checker,
+            exo_resources_rewriter = ctx.attrs.exo_resources_rewriter,
+            filter_dex_class_names = ctx.attrs.filter_dex_class_names,
+            filter_prebuilt_native_library_dir = ctx.attrs.filter_prebuilt_native_library_dir,
+            filter_resources = ctx.attrs.filter_resources,
+            # @oss-disable[end= ]: gatorade_mergemap_tool = ctx.attrs.gatorade_mergemap_tool[RunInfo],
+            generate_build_config = ctx.attrs.generate_build_config,
+            generate_manifest = ctx.attrs.generate_manifest,
+            installer = ctx.attrs.installer,
+            instrumentation_test_can_run_locally = ctx.attrs.instrumentation_test_can_run_locally,
+            collect_perfetto = ctx.attrs.collect_perfetto,
+            instrumentation_test_runner_classpath = ctx.attrs.instrumentation_test_runner_classpath,
+            instrumentation_test_runner_main_class = ctx.attrs.instrumentation_test_runner_main_class,
+            jar_splitter_command = ctx.attrs.jar_splitter_command,
+            jdk_system_image = ctx.attrs.jdk_system_image,
+            jni_onload_check = ctx.attrs.jni_onload_check,
+            manifest_utils = ctx.attrs.manifest_utils,
+            merge_android_resource_sources = ctx.attrs.merge_android_resource_sources,
+            merge_android_resources = ctx.attrs.merge_android_resources,
+            merge_assets = ctx.attrs.merge_assets,
+            mergemap_tool = ctx.attrs.mergemap_tool[RunInfo],
+            mini_aapt = ctx.attrs.mini_aapt,
+            multi_dex_command = ctx.attrs.multi_dex_command,
+            native_libs_as_assets_metadata = ctx.attrs.native_libs_as_assets_metadata,
+            optimized_proguard_config = ctx.attrs.optimized_proguard_config,
+            p7zip = None,
+            package_meta_inf_version_files = ctx.attrs.package_meta_inf_version_files,
+            package_strings_as_assets = ctx.attrs.package_strings_as_assets,
+            proguard_config = ctx.attrs.proguard_config,
+            proguard_jar = ctx.attrs.proguard_jar,
+            r_dot_java_weight_factor = ctx.attrs.r_dot_java_weight_factor,
+            replace_application_id_placeholders = ctx.attrs.replace_application_id_placeholders,
+            secondary_dex_compression_command = ctx.attrs.secondary_dex_compression_command,
+            secondary_dex_weight_limit = ctx.attrs.secondary_dex_weight_limit,
+            sort_pre_dexed_files = ctx.attrs.sort_pre_dexed_files,
+            unpack_aar = ctx.attrs.unpack_aar,
+            zipalign = ctx.attrs.zipalign,
+        ),
+    ]
+
+system_android_toolchain_rule = rule(
+    attrs = {
+        "aapt2": attrs.dep(providers = [RunInfo]),
+        "aapt2_filter_resources": attrs.dep(providers = [RunInfo]),
+        "aar_builder": attrs.dep(providers = [RunInfo]),
+        "adb": attrs.dep(providers = [RunInfo]),
+        "android_jar": attrs.source(),
+        "android_optional_jars": attrs.list(attrs.source()),
+        "apk_builder": attrs.dep(providers = [RunInfo]),
+        "apk_module_graph": attrs.dep(providers = [RunInfo]),
+        "app_without_resources_stub": attrs.source(),
+        "bundle_apks_builder": attrs.dep(providers = [RunInfo]),
+        "bundle_builder": attrs.dep(providers = [RunInfo]),
+        "collect_perfetto": attrs.bool(),
+        "combine_native_library_dirs": attrs.dep(providers = [RunInfo]),
+        "consolidate_class_names": attrs.option(attrs.dep(providers = [RunInfo]), default = None),
+        "copy_string_resources": attrs.dep(providers = [RunInfo]),
+        "cross_module_native_deps_check": attrs.bool(),
+        "d8_command": attrs.dep(providers = [RunInfo]),
+        "duplicate_class_checker": attrs.option(attrs.dep(providers = [RunInfo]), default = None),
+        "exo_resources_rewriter": attrs.dep(providers = [RunInfo]),
+        "filter_dex_class_names": attrs.dep(providers = [RunInfo]),
+        "filter_prebuilt_native_library_dir": attrs.dep(providers = [RunInfo]),
+        "filter_resources": attrs.dep(providers = [RunInfo]),
+        # @oss-disable[end= ]: "gatorade_mergemap_tool": attrs.dep(providers = [RunInfo]),
+        "generate_build_config": attrs.dep(providers = [RunInfo]),
+        "generate_manifest": attrs.dep(providers = [RunInfo]),
+        "installer": attrs.label(),
+        "instrumentation_test_can_run_locally": attrs.bool(),
+        "instrumentation_test_runner_classpath": attrs.list(attrs.source()),
+        "instrumentation_test_runner_main_class": attrs.string(),
+        "jar_splitter_command": attrs.dep(providers = [RunInfo]),
+        "jdk_system_image": attrs.source(),
+        "jni_onload_check": attrs.option(attrs.dep(providers = [RunInfo]), default = None),
+        "list_tests": attrs.option(attrs.dep(providers = [RunInfo]), default = None),
+        "manifest_utils": attrs.dep(providers = [RunInfo]),
+        "merge_android_resource_sources": attrs.dep(providers = [RunInfo]),
+        "merge_android_resources": attrs.dep(providers = [RunInfo]),
+        "merge_assets": attrs.dep(providers = [RunInfo]),
+        "mergemap_tool": attrs.dep(providers = [RunInfo]),
+        "mini_aapt": attrs.dep(providers = [RunInfo]),
+        "multi_dex_command": attrs.dep(providers = [RunInfo]),
+        "native_libs_as_assets_metadata": attrs.dep(providers = [RunInfo]),
+        "optimized_proguard_config": attrs.source(),
+        "package_meta_inf_version_files": attrs.bool(),
+        "package_strings_as_assets": attrs.dep(providers = [RunInfo]),
+        "proguard_config": attrs.source(),
+        "proguard_jar": attrs.source(),
+        "r_dot_java_weight_factor": attrs.int(),
+        "replace_application_id_placeholders": attrs.dep(providers = [RunInfo]),
+        "secondary_dex_compression_command": attrs.dep(providers = [RunInfo]),
+        "secondary_dex_weight_limit": attrs.int(),
+        "sort_pre_dexed_files": attrs.dep(providers = [RunInfo]),
+        "target_stats_tools": attrs.option(attrs.dep(providers = [TargetStatsToolsInfo]), default = None),
+        "unpack_aar": attrs.dep(providers = [RunInfo]),
+        "zipalign": attrs.dep(providers = [RunInfo]),
+    },
+    impl = system_android_toolchain_rule_impl,
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/android/BUCK b/buck2/prelude/toolchains/android/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/BUCK
@@ -0,0 +1,5 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
diff --git a/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ApplicationLike.java b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ApplicationLike.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ApplicationLike.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.support.exopackage;
+
+import android.app.Application;
+import android.content.res.Configuration;
+
+/**
+ * This interface is used to delegate calls from main Application object.
+ *
+ * <p>Implementations of this interface must have a one-argument constructor that takes an argument
+ * of type {@link Application}.
+ */
+public interface ApplicationLike {
+
+  /** Same as {@link Application#onCreate()}. */
+  void onCreate();
+
+  /** Same as {@link Application#onLowMemory()}. */
+  void onLowMemory();
+
+  /**
+   * Same as {@link Application#onTrimMemory(int level)}.
+   *
+   * @param level
+   */
+  void onTrimMemory(int level);
+
+  /** Same as {@link Application#onTerminate()}. */
+  void onTerminate();
+
+  /** Same as {@link Application#onConfigurationChanged(Configuration newconfig)}. */
+  void onConfigurationChanged(Configuration newConfig);
+
+  /** Same as {@link Application#getSystemService(String name)}. */
+  Object getSystemService(String name);
+}
diff --git a/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/BUCK b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/BUCK
@@ -0,0 +1,14 @@
+load("@prelude//toolchains/android/tools/build_rules:fb_native.bzl", "fb_native")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+fb_native.android_library(
+    name = "exopackage",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/DefaultApplicationLike.java b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/DefaultApplicationLike.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/DefaultApplicationLike.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.support.exopackage;
+
+import android.app.Application;
+import android.content.res.Configuration;
+
+/** Empty implementation of {@link ApplicationLike}. */
+public class DefaultApplicationLike implements ApplicationLike {
+  public DefaultApplicationLike() {}
+
+  @SuppressWarnings("unused")
+  public DefaultApplicationLike(Application application) {}
+
+  @Override
+  public void onCreate() {}
+
+  @Override
+  public void onLowMemory() {}
+
+  @Override
+  public void onTrimMemory(int level) {}
+
+  @Override
+  public void onTerminate() {}
+
+  @Override
+  public void onConfigurationChanged(Configuration newConfig) {}
+
+  @Override
+  public Object getSystemService(String name) {
+    return null;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageApplication.java b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageApplication.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageApplication.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.support.exopackage;
+
+import android.annotation.TargetApi;
+import android.app.Application;
+import android.content.Context;
+import android.content.res.Configuration;
+import java.lang.reflect.Constructor;
+
+/**
+ * A base class for implementing an Application that delegates to an {@link ApplicationLike}
+ * instance. This is used in conjunction with secondary dex files so that the logic that would
+ * normally live in the Application class is loaded after the secondary dexes are loaded.
+ */
+public abstract class ExopackageApplication<T extends ApplicationLike> extends Application {
+
+  protected static final int SECONDARY_DEX_MASK = 1;
+  protected static final int NATIVE_LIBRARY_MASK = 2;
+  protected static final int RESOURCES_MASK = 4;
+  protected static final int MODULES_MASK = 8;
+
+  private final String delegateClassName;
+  private final int exopackageFlags;
+  private T delegate;
+
+  /**
+   * @param exopackageFlags Bitmask used to determine which exopackage feature is enabled in the
+   *     current build. This should usually be {@code BuildConfig.EXOPACKAGE_FLAGS}.
+   */
+  protected ExopackageApplication(int exopackageFlags) {
+    this(DefaultApplicationLike.class.getName(), exopackageFlags);
+  }
+
+  /**
+   * @param delegateClassName The fully-qualified name of the {@link ApplicationLike} class that
+   *     will act as the delegate for application lifecycle callbacks.
+   * @param exopackageFlags Bitmask used to determine which exopackage feature is enabled in the
+   *     current build. This should usually be {@code BuildConfig.EXOPACKAGE_FLAGS}.
+   */
+  protected ExopackageApplication(String delegateClassName, int exopackageFlags) {
+    this.delegateClassName = delegateClassName;
+    this.exopackageFlags = exopackageFlags;
+  }
+
+  protected boolean isExopackageEnabledForSecondaryDex() {
+    return (exopackageFlags & SECONDARY_DEX_MASK) != 0;
+  }
+
+  protected boolean isExopackageEnabledForNativeLibraries() {
+    return (exopackageFlags & NATIVE_LIBRARY_MASK) != 0;
+  }
+
+  protected boolean isExopackageEnabledForResources() {
+    return (exopackageFlags & RESOURCES_MASK) != 0;
+  }
+
+  protected T createDelegate() {
+    if (isExopackageEnabledForSecondaryDex()) {
+      ExopackageDexLoader.loadExopackageJars(this);
+    }
+
+    if (isExopackageEnabledForNativeLibraries()) {
+      ExopackageSoLoader.init(this);
+    }
+
+    if (isExopackageEnabledForResources()) {
+      ResourcesLoader.init(this);
+    }
+
+    try {
+      // Use reflection to create the delegate so it doesn't need to go into the primary dex.
+      Class<T> implClass = (Class<T>) Class.forName(delegateClassName);
+      Constructor<T> constructor = implClass.getConstructor(Application.class);
+      return constructor.newInstance(this);
+    } catch (Exception e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private synchronized void ensureDelegate() {
+    if (delegate == null) {
+      delegate = createDelegate();
+    }
+  }
+
+  /**
+   * Hook for sub-classes to run logic after the {@link Application#attachBaseContext} has been
+   * called but before the delegate is created. Implementors should be very careful what they do
+   * here since {@link android.app.Application#onCreate} will not have yet been called.
+   */
+  protected void onBaseContextAttached() {}
+
+  /**
+   * @return the delegate, or {@code null} if not set up.
+   */
+  // @Nullable  - Don't want to force a reference to that annotation in the primary dex.
+  public final T getDelegateIfPresent() {
+    return delegate;
+  }
+
+  @Override
+  protected void attachBaseContext(Context base) {
+    super.attachBaseContext(base);
+    onBaseContextAttached();
+    ensureDelegate();
+  }
+
+  @Override
+  public void onCreate() {
+    super.onCreate();
+    if (isExopackageEnabledForResources()) {
+      ResourcesLoader.onAppCreated(this);
+    }
+    ensureDelegate();
+    delegate.onCreate();
+  }
+
+  @Override
+  public final void onTerminate() {
+    super.onTerminate();
+    if (delegate != null) {
+      delegate.onTerminate();
+    }
+  }
+
+  @Override
+  public final void onLowMemory() {
+    super.onLowMemory();
+    if (delegate != null) {
+      delegate.onLowMemory();
+    }
+  }
+
+  @TargetApi(14)
+  @Override
+  public final void onTrimMemory(int level) {
+    super.onTrimMemory(level);
+    if (delegate != null) {
+      delegate.onTrimMemory(level);
+    }
+  }
+
+  @Override
+  public void onConfigurationChanged(Configuration newConfig) {
+    super.onConfigurationChanged(newConfig);
+    if (delegate != null) {
+      delegate.onConfigurationChanged(newConfig);
+    }
+  }
+
+  @Override
+  public Object getSystemService(String name) {
+    if (delegate != null) {
+      Object service = delegate.getSystemService(name);
+      if (service != null) {
+        return service;
+      }
+    }
+    return super.getSystemService(name);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageDexLoader.java b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageDexLoader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageDexLoader.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.support.exopackage;
+
+import android.content.Context;
+import android.util.Log;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Loads pre-dexed jars installed by the exopackage installer into our ClassLoader.
+ *
+ * <p>See http://android-developers.blogspot.com/2011/07/custom-class-loading-in-dalvik.html for an
+ * explanation of how an app can load pre-dexed libraries. This class goes a step further and then
+ * hacks the system class loader so these can be referenced by default. This logic has to run before
+ * any class that references the code in these dexes is loaded.
+ */
+public class ExopackageDexLoader {
+
+  private static final String TAG = "ExopackageDexLoader";
+
+  private ExopackageDexLoader() {}
+
+  /**
+   * Load JARs installed by Buck's Exopackage installer and add them to the Application ClassLoader.
+   *
+   * @param context The application context.
+   */
+  @SuppressWarnings("PMD.CollapsibleIfStatements")
+  public static void loadExopackageJars(Context context) {
+    // Normal exopackage jars go to system CL
+    File secondaryDirectory =
+        new File("/data/local/tmp/exopackage/" + context.getPackageName() + "/secondary-dex");
+    final List<File> dexJars = getJarFilesFromContainingDirectory(secondaryDirectory);
+    File dexOptDir = context.getDir("exopackage_dex_opt", Context.MODE_PRIVATE);
+    SystemClassLoaderAdder.installDexJars(context.getClassLoader(), dexOptDir, dexJars);
+    cleanUpOldOdexFiles(dexOptDir, dexJars);
+  }
+
+  /** Find all .dex.jar files in the given directory */
+  public static List<File> getJarFilesFromContainingDirectory(File containingDirectory) {
+    List<File> dexJars = new ArrayList();
+    try {
+      final File metadataFile = new File(containingDirectory, "metadata.txt");
+      if (!metadataFile.exists()) {
+        return dexJars;
+      }
+      BufferedReader metadataReader =
+          new BufferedReader(new InputStreamReader(new FileInputStream(metadataFile)));
+      try {
+        String line;
+        while ((line = metadataReader.readLine()) != null) {
+          int space = line.indexOf(' ');
+          if (space == -1) {
+            throw new RuntimeException("Found no space in line: " + line);
+          }
+          String baseName = line.substring(0, space);
+          dexJars.add(new File(containingDirectory, baseName));
+        }
+      } finally {
+        metadataReader.close();
+      }
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+    return dexJars;
+  }
+
+  /**
+   * Clean up any odex files that do not belong to the specified set of jars
+   *
+   * @param dexOptDir the directory to clean
+   * @param dexJars odex files pertaining to these jars will be kept
+   */
+  public static void cleanUpOldOdexFiles(File dexOptDir, List<File> dexJars) {
+    Set<String> expectedOdexSet = new HashSet<>();
+    for (File file : dexJars) {
+      expectedOdexSet.add(file.getName().replaceFirst("\\.jar$", ".dex"));
+    }
+    File[] odexes = dexOptDir.listFiles();
+    if (odexes != null) {
+      for (File odex : odexes) {
+        if (!expectedOdexSet.contains(odex.getName())) {
+          if (!odex.delete()) {
+            Log.w(TAG, "Failed to delete stale odex: " + odex.getAbsolutePath());
+          }
+        }
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageSoLoader.java b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageSoLoader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ExopackageSoLoader.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.support.exopackage;
+
+import android.content.Context;
+import android.os.Build;
+import android.util.Log;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Loads native library files installed by the exopackage installer. This class requires
+ * initialization before use; {@link ExopackageApplication#attachBaseContext} is responsible for
+ * calling {@link #init} so that application-specific code doesn't need to.
+ */
+public class ExopackageSoLoader {
+
+  private static final String TAG = "ExopackageSoLoader";
+
+  private static boolean initialized = false;
+  private static String nativeLibsDir = null;
+
+  private static File privateNativeLibsDir = null;
+  private static Map<String, String> abi1Libraries = new HashMap<String, String>();
+  private static Map<String, String> abi2Libraries = new HashMap<String, String>();
+
+  private ExopackageSoLoader() {}
+
+  public static void init(Context context) {
+    if (initialized) {
+      Log.d(TAG, "init() already called, so nothing to do.");
+      return;
+    }
+    nativeLibsDir = "/data/local/tmp/exopackage/" + context.getPackageName() + "/native-libs/";
+    verifyMetadataFile();
+
+    preparePrivateDirectory(context);
+    parseMetadata();
+    initialized = true;
+  }
+
+  private static void verifyMetadataFile() {
+    File abiMetadata = getAbi1Metadata();
+    if (abiMetadata.exists()) {
+      return;
+    }
+    abiMetadata = getAbi2Metadata();
+    if (abiMetadata == null || abiMetadata.exists()) {
+      return;
+    }
+    throw new RuntimeException(
+        "Either 'native' exopackage is not turned on for this build, "
+            + "or the installation did not complete successfully.");
+  }
+
+  private static void preparePrivateDirectory(Context context) {
+    privateNativeLibsDir = context.getDir("exo-libs", Context.MODE_PRIVATE);
+    for (File file : privateNativeLibsDir.listFiles()) {
+      file.delete();
+    }
+  }
+
+  private static void parseMetadata() {
+    doParseMetadata(getAbi1Metadata(), abi1Libraries);
+    doParseMetadata(getAbi2Metadata(), abi2Libraries);
+  }
+
+  private static void doParseMetadata(File metadata, Map<String, String> libraries) {
+    if (metadata == null || !metadata.exists()) {
+      return;
+    }
+
+    BufferedReader br = null;
+    try {
+      br = new BufferedReader(new FileReader(metadata));
+      String line;
+      try {
+        while ((line = br.readLine()) != null) {
+          line = line.trim();
+          if (line.isEmpty()) {
+            continue;
+          }
+          int spaceIndex = line.indexOf(' ');
+          if (spaceIndex == -1) {
+            throw new RuntimeException("Error parsing metadata.txt; invalid line: " + line);
+          }
+          String libname = line.substring(0, spaceIndex);
+          String filename = line.substring(spaceIndex + 1);
+          libraries.put(libname, filename);
+        }
+      } finally {
+        br.close();
+      }
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  public static void loadLibrary(String shortName) throws UnsatisfiedLinkError {
+    if (!initialized) {
+      Log.d(TAG, "ExopackageSoLoader not initialized, falling back to System.loadLibrary()");
+      System.loadLibrary(shortName);
+      return;
+    }
+
+    String libname = shortName.startsWith("lib") ? shortName : "lib" + shortName;
+
+    File libraryFile = copySoFileIfRequired(libname);
+
+    if (libraryFile == null) {
+      throw new UnsatisfiedLinkError("Could not find library file for either ABIs.");
+    }
+
+    String path = libraryFile.getAbsolutePath();
+
+    Log.d(TAG, "Attempting to load library: " + path);
+    System.load(path);
+    Log.d(TAG, "Successfully loaded library: " + path);
+  }
+
+  private static File copySoFileIfRequired(String libname) {
+    File libraryFile = new File(privateNativeLibsDir, libname + ".so");
+    if (libraryFile.exists()) {
+      return libraryFile;
+    }
+
+    if (!abi1Libraries.containsKey(libname) && !abi2Libraries.containsKey(libname)) {
+      return null;
+    }
+
+    String abiDir;
+    String sourceFilename;
+    if (abi1Libraries.containsKey(libname)) {
+      sourceFilename = abi1Libraries.get(libname);
+      abiDir = Build.CPU_ABI;
+    } else {
+      sourceFilename = abi2Libraries.get(libname);
+      abiDir = Build.CPU_ABI2;
+    }
+    String sourcePath = nativeLibsDir + abiDir + "/" + sourceFilename;
+
+    try {
+      InputStream in = null;
+      OutputStream out = null;
+      try {
+        in = new BufferedInputStream(new FileInputStream(sourcePath));
+        out = new BufferedOutputStream(new FileOutputStream(libraryFile));
+        byte[] buffer = new byte[4 * 1024];
+        int len;
+        while ((len = in.read(buffer)) > 0) {
+          out.write(buffer, 0, len);
+        }
+      } finally {
+        if (in != null) {
+          in.close();
+        }
+        if (out != null) {
+          out.close();
+        }
+      }
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+
+    return libraryFile;
+  }
+
+  private static File getAbi1Metadata() {
+    return new File(nativeLibsDir + Build.CPU_ABI + "/metadata.txt");
+  }
+
+  private static File getAbi2Metadata() {
+    if (Build.CPU_ABI2.equals("unknown")) {
+      return null;
+    }
+
+    return new File(nativeLibsDir + Build.CPU_ABI2 + "/metadata.txt");
+  }
+}
diff --git a/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/Reflect.java b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/Reflect.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/Reflect.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.support.exopackage;
+
+import java.lang.reflect.Field;
+
+class Reflect {
+  private Reflect() {}
+
+  static Object getField(Object object, Class<?> clazz, String fieldName)
+      throws NoSuchFieldException, IllegalAccessException {
+    Field field = clazz.getDeclaredField(fieldName);
+    field.setAccessible(true);
+    return field.get(object);
+  }
+
+  static void setField(Object object, Class<?> clazz, String fieldName, Object fieldValue)
+      throws NoSuchFieldException, IllegalAccessException {
+    Field field = clazz.getDeclaredField(fieldName);
+    field.setAccessible(true);
+    field.set(object, fieldValue);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ResourcesLoader.java b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ResourcesLoader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/ResourcesLoader.java
@@ -0,0 +1,537 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.support.exopackage;
+
+import static android.os.Build.VERSION.SDK_INT;
+import static android.os.Build.VERSION_CODES.KITKAT;
+import static android.os.Build.VERSION_CODES.LOLLIPOP;
+
+import android.annotation.TargetApi;
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.res.AssetManager;
+import android.content.res.Resources;
+import android.util.ArrayMap;
+import android.util.Log;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.lang.ref.WeakReference;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+
+public class ResourcesLoader {
+
+  private static final String TAG = "ResourcesLoader";
+
+  private static final int NOUGAT = 24;
+  private static Resources sResourcesFromPackageManager = null;
+  private static AssetManagerInternal sAssetManager = null;
+  private static String sOriginalResourcePath = null;
+  private static List<String> sExoResourcesPaths = null;
+
+  private static class AssetManagerInternal {
+
+    private static Method sAddAssetPathMethod;
+    private static Method sEnsureStringBlocksMethod;
+    private static Method sAddAssetPathAsSharedLibMethod;
+
+    static {
+      try {
+        // ensureStringBlocks is required on KitKat and doesn't hurt elsewhere.
+        sEnsureStringBlocksMethod = AssetManager.class.getDeclaredMethod("ensureStringBlocks");
+        sEnsureStringBlocksMethod.setAccessible(true);
+
+        sAddAssetPathMethod = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
+        sAddAssetPathMethod.setAccessible(true);
+        if (SDK_INT >= NOUGAT) {
+          sAddAssetPathAsSharedLibMethod =
+              AssetManager.class.getDeclaredMethod("addAssetPathAsSharedLibrary", String.class);
+          sAddAssetPathAsSharedLibMethod.setAccessible(true);
+        } else {
+          sAddAssetPathAsSharedLibMethod = sAddAssetPathMethod;
+        }
+      } catch (NoSuchMethodException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    private final AssetManager assetManager;
+
+    AssetManagerInternal()
+        throws NoSuchMethodException,
+            IllegalAccessException,
+            InvocationTargetException,
+            InstantiationException {
+      this.assetManager = AssetManager.class.getConstructor().newInstance();
+    }
+
+    void addAssetPaths(Iterable<String> paths, boolean asSharedLib)
+        throws InvocationTargetException, IllegalAccessException {
+      for (String path : paths) {
+        if (asSharedLib) {
+          if ((int) sAddAssetPathAsSharedLibMethod.invoke(assetManager, path) == 0) {
+            throw new RuntimeException("Unable to add resources.");
+          }
+        } else {
+          if ((int) sAddAssetPathMethod.invoke(assetManager, path) == 0) {
+            throw new RuntimeException("Unable to add resources.");
+          }
+        }
+      }
+      ensureStringBlocks();
+    }
+
+    private void ensureStringBlocks() throws InvocationTargetException, IllegalAccessException {
+      sEnsureStringBlocksMethod.invoke(assetManager);
+    }
+
+    AssetManager get() {
+      return assetManager;
+    }
+  }
+
+  private static class ResourcesInternal {
+
+    private final Resources resources;
+
+    ResourcesInternal(Resources resources) {
+      this.resources = resources;
+    }
+
+    void setAssetManager(AssetManager assetManager)
+        throws NoSuchFieldException, IllegalAccessException {
+      try {
+        Reflect.setField(resources, Resources.class, "mAssets", assetManager);
+      } catch (NoSuchFieldException e) {
+        Object resourcesImpl = Reflect.getField(resources, Resources.class, "mResourcesImpl");
+        Reflect.setField(resourcesImpl, resourcesImpl.getClass(), "mAssets", assetManager);
+      }
+      resources.updateConfiguration(resources.getConfiguration(), resources.getDisplayMetrics());
+      // Should this clear caches like instant-run?
+    }
+  }
+
+  private static class ResourcesManagerInternal {
+
+    private static Class<?> sResourcesManagerClass;
+    private static Method sGetInstanceMethod;
+
+    static {
+      try {
+        sResourcesManagerClass = Class.forName("android.app.ResourcesManager");
+        sGetInstanceMethod = sResourcesManagerClass.getDeclaredMethod("getInstance");
+        sGetInstanceMethod.setAccessible(true);
+      } catch (Exception e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    private final Object resourcesManager;
+
+    private ResourcesManagerInternal(Object resourcesManager) {
+      this.resourcesManager = resourcesManager;
+    }
+
+    public static ResourcesManagerInternal getInstance()
+        throws InvocationTargetException, IllegalAccessException {
+      return new ResourcesManagerInternal(sGetInstanceMethod.invoke(sResourcesManagerClass));
+    }
+
+    public ArrayMap<?, WeakReference<Resources>> getActiveResources()
+        throws NoSuchFieldException, IllegalAccessException {
+      return (ArrayMap<?, WeakReference<Resources>>)
+          Reflect.getField(resourcesManager, sResourcesManagerClass, "mActiveResources");
+    }
+
+    public Collection<WeakReference<Resources>> getResourceReferences()
+        throws NoSuchFieldException, IllegalAccessException {
+      return (Collection<WeakReference<Resources>>)
+          Reflect.getField(resourcesManager, sResourcesManagerClass, "mResourceReferences");
+    }
+
+    @TargetApi(NOUGAT)
+    public ArrayMap<?, WeakReference<?>> getResourceImpls()
+        throws NoSuchFieldException, IllegalAccessException {
+      return (ArrayMap<?, WeakReference<?>>)
+          Reflect.getField(resourcesManager, sResourcesManagerClass, "mResourceImpls");
+    }
+
+    public void setResourceImpls(ArrayMap<Object, Object> resourceImpls)
+        throws NoSuchFieldException, IllegalAccessException {
+      Reflect.setField(resourcesManager, sResourcesManagerClass, "mResourceImpls", resourceImpls);
+    }
+  }
+
+  private static class ActivityThreadInternal {
+
+    private static Class<?> sActivityThreadClass;
+    private static Method sGetCurrentActivityThreadMethod;
+
+    static {
+      try {
+        sActivityThreadClass = Class.forName("android.app.ActivityThread");
+        sGetCurrentActivityThreadMethod = sActivityThreadClass.getMethod("currentActivityThread");
+        sGetCurrentActivityThreadMethod.setAccessible(true);
+      } catch (Exception e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    private final Object activityThread;
+
+    private ActivityThreadInternal(Object activityThread) {
+      this.activityThread = activityThread;
+    }
+
+    public static ActivityThreadInternal currentActivityThread()
+        throws InvocationTargetException, IllegalAccessException {
+      return new ActivityThreadInternal(sGetCurrentActivityThreadMethod.invoke(null));
+    }
+
+    public HashMap<?, WeakReference<Resources>> getActiveResources()
+        throws NoSuchFieldException, IllegalAccessException {
+      return (HashMap<?, WeakReference<Resources>>)
+          Reflect.getField(activityThread, sActivityThreadClass, "mActiveResources");
+    }
+
+    @TargetApi(KITKAT)
+    public List<LoadedApkInternal> getLoadedApks()
+        throws NoSuchFieldException, IllegalAccessException {
+      List<LoadedApkInternal> loadedApks = new ArrayList<>();
+      for (String field : new String[] {"mPackages", "mResourcePackages"}) {
+        ArrayMap packages =
+            (ArrayMap) Reflect.getField(activityThread, sActivityThreadClass, field);
+        for (Object loadedApkRef : packages.values()) {
+          Object loadedApk = ((WeakReference) loadedApkRef).get();
+          if (loadedApk == null) {
+            continue;
+          }
+          loadedApks.add(new LoadedApkInternal(loadedApk));
+        }
+      }
+      return loadedApks;
+    }
+  }
+
+  private static class LoadedApkInternal {
+
+    private static Class<?> sLoadedApkClass;
+
+    static {
+      try {
+        sLoadedApkClass = Class.forName("android.app.LoadedApk");
+      } catch (Exception e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    private final Object loadedApk;
+
+    private LoadedApkInternal(Object loadedApk) {
+      this.loadedApk = loadedApk;
+    }
+
+    public Context getApplication() throws NoSuchFieldException, IllegalAccessException {
+      return (Context) Reflect.getField(loadedApk, sLoadedApkClass, "mApplication");
+    }
+
+    public void setResDir(String resDir) throws NoSuchFieldException, IllegalAccessException {
+      Reflect.setField(loadedApk, sLoadedApkClass, "mResDir", resDir);
+    }
+
+    public void setSplitResDirs(String[] splitResDirs)
+        throws NoSuchFieldException, IllegalAccessException {
+      Reflect.setField(loadedApk, sLoadedApkClass, "mSplitResDirs", splitResDirs);
+    }
+  }
+
+  private static class ResourcesKeyInternal {
+    private static Class<?> sResourcesKeyClass;
+
+    static {
+      try {
+        sResourcesKeyClass = Class.forName("android.content.res.ResourcesKey");
+      } catch (Exception e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    Object key;
+
+    public ResourcesKeyInternal(Object key) {
+      this.key = key;
+    }
+
+    void setResDir(String resDir) throws NoSuchFieldException, IllegalAccessException {
+      Reflect.setField(key, sResourcesKeyClass, "mResDir", resDir);
+    }
+
+    void setSplitResDirs(String[] splitResDirs)
+        throws NoSuchFieldException, IllegalAccessException {
+      Reflect.setField(key, sResourcesKeyClass, "mSplitResDirs", splitResDirs);
+    }
+
+    public String getResDir() throws NoSuchFieldException, IllegalAccessException {
+      return (String) Reflect.getField(key, sResourcesKeyClass, "mResDir");
+    }
+  }
+
+  private ResourcesLoader() {}
+
+  // init() will replace the underlying AssetManager for all currently created resources. It should
+  // be called in Application.attachBaseContext() if the app is going to access resources before
+  // Application.onCreate().
+  public static void init(Context context) {
+    try {
+      Log.e(TAG, "Initializing ResourcesLoader.");
+      sOriginalResourcePath = context.getPackageResourcePath();
+      hookAssetManagers(context);
+    } catch (RuntimeException e) {
+      throw e;
+    } catch (Exception e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  // This should be called as soon as possible after Application.attachBaseContext() hasReturned
+  // (Application.onCreate() for example). It modifies a LoadedApk object that is not created until
+  // after that point. This data in the LoadedApk is used to create new Resources objects (on
+  // Android L+).
+  public static void onAppCreated(Context context) {
+    try {
+      Log.e(TAG, "Updating more internals for ResourcesLoader.");
+      if (SDK_INT >= LOLLIPOP) {
+        updateLoadedApkResDirs(context);
+      }
+      if (SDK_INT >= NOUGAT) {
+        // In some cases, Android's ResourcesManager will derive new Resources from an existing
+        // ResourceKey -> ResourceImpl mapping. Before LoadedApk is updated, those keys won't have
+        // the correct res/splitResDirs, and so we need to create the mapping with the correct
+        // ResourceKeys.
+        updateResourceKeys(context, sOriginalResourcePath);
+      }
+      // This Resources instance should have the same ResourceKey as any future Resources acquired
+      // through the ApplicationInfo returned from the PackageManager and so should map to this
+      // hooked instance.
+      sResourcesFromPackageManager =
+          context.getPackageManager().getResourcesForApplication(context.getPackageName());
+      hookAssetManagers(context);
+    } catch (Exception e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @TargetApi(NOUGAT)
+  private static void updateResourceKeys(Context context, String originalResourcePath)
+      throws InvocationTargetException, IllegalAccessException, NoSuchFieldException, IOException {
+    List<String> exoResourcePaths = getExoPaths(context);
+    if (exoResourcePaths.isEmpty()) {
+      return;
+    }
+    String resDir = exoResourcePaths.get(0);
+    String[] splitResDirs =
+        exoResourcePaths
+            .subList(1, exoResourcePaths.size())
+            .toArray(new String[exoResourcePaths.size() - 1]);
+
+    ArrayMap<?, ?> resourceImpls = ResourcesManagerInternal.getInstance().getResourceImpls();
+    ArrayMap<Object, Object> newResourceImpls = new ArrayMap<>(resourceImpls.size());
+    for (Map.Entry<?, ?> entry : resourceImpls.entrySet()) {
+      Object key = entry.getKey();
+      ResourcesKeyInternal keyInternal = new ResourcesKeyInternal(key);
+      if (keyInternal.getResDir().equals(originalResourcePath)) {
+        keyInternal.setResDir(resDir);
+        keyInternal.setSplitResDirs(splitResDirs);
+        newResourceImpls.put(key, entry.getValue());
+      }
+    }
+    ResourcesManagerInternal.getInstance().setResourceImpls(newResourceImpls);
+  }
+
+  public static void hookAssetManagers(Context context) throws Exception {
+    AssetManagerInternal assetManager = getAssetManager(context);
+    Collection<WeakReference<Resources>> activeResources = getActiveResources();
+    for (WeakReference<Resources> ref : activeResources) {
+      Resources res = ref.get();
+      if (res == null) {
+        continue;
+      }
+      new ResourcesInternal(res).setAssetManager(assetManager.get());
+    }
+  }
+
+  private static List<String> getWebViewAssets(Context context)
+      throws InvocationTargetException,
+          IllegalAccessException,
+          NoSuchMethodException,
+          ClassNotFoundException,
+          PackageManager.NameNotFoundException {
+    if (SDK_INT >= NOUGAT) {
+      Class webViewFactoryClass = Class.forName("android.webkit.WebViewFactory");
+      Method getWebviewContextAndSetProviderMethod =
+          webViewFactoryClass.getDeclaredMethod("getWebViewContextAndSetProvider");
+      getWebviewContextAndSetProviderMethod.setAccessible(true);
+      Context webViewContext =
+          (Context) getWebviewContextAndSetProviderMethod.invoke(webViewFactoryClass);
+      return Collections.singletonList(webViewContext.getApplicationInfo().sourceDir);
+    } else if (SDK_INT >= LOLLIPOP) {
+      Class webViewFactoryClass = Class.forName("android.webkit.WebViewFactory");
+      Method getWebViewPackageNameMethod =
+          webViewFactoryClass.getDeclaredMethod("getWebViewPackageName");
+      getWebViewPackageNameMethod.setAccessible(true);
+      String packageName = (String) getWebViewPackageNameMethod.invoke(webViewFactoryClass);
+      PackageInfo packageInfo =
+          context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_META_DATA);
+      return Collections.singletonList(packageInfo.applicationInfo.sourceDir);
+    }
+    return Collections.emptyList();
+  }
+
+  private static AssetManagerInternal getAssetManager(Context context)
+      throws ClassNotFoundException,
+          NoSuchMethodException,
+          IllegalAccessException,
+          InvocationTargetException,
+          IOException,
+          InstantiationException {
+    if (sAssetManager == null) {
+      List<String> exoResourcePaths = getExoPaths(context);
+      sAssetManager = new AssetManagerInternal();
+      sAssetManager.addAssetPaths(exoResourcePaths, false);
+    }
+    return sAssetManager;
+  }
+
+  // On Android L and above, the runtime might create multiple Resources objects for the same
+  // process. These new Resources are created from the resource directories specified in the
+  // LoadedApk object. Luckily, Android L also introduced split resources which allow us to
+  // configure the LoadedApk to construct Resources that reference multiple zip files (if this
+  // weren't the case, we could still install resources at runtime, but would be limited to a single
+  // zip/directory).
+  @TargetApi(LOLLIPOP)
+  public static void updateLoadedApkResDirs(Context context) throws Exception {
+    List<String> exoResourcePaths = getExoPaths(context);
+    if (exoResourcePaths.isEmpty()) {
+      return;
+    }
+    // Split resource loading doesn't interact correctly with WebView's asset loading, so we add
+    // the webview assets directly (in the same way that the webview asset-loading does it).
+    // If split resource loading didn't replace the base source dir (and just added split resource
+    // dirs), I think it would interact fine with webview assets. I'm not sure if this would work
+    // on Android <5.0, and it would require using different package id or type ids in the split
+    // resources.
+    List<String> webviewAssets = getWebViewAssets(context);
+    getAssetManager(context).addAssetPaths(webviewAssets, true);
+    ApplicationInfo applicationInfo = context.getApplicationInfo();
+    LinkedHashSet<String> sharedLibraryFiles = new LinkedHashSet<>();
+    if (applicationInfo.sharedLibraryFiles != null) {
+      sharedLibraryFiles.addAll(Arrays.asList(applicationInfo.sharedLibraryFiles));
+    }
+    sharedLibraryFiles.addAll(webviewAssets);
+    applicationInfo.sharedLibraryFiles =
+        sharedLibraryFiles.toArray(new String[sharedLibraryFiles.size()]);
+
+    String resDir = exoResourcePaths.get(0);
+    String[] splitResDirs = new String[exoResourcePaths.size() - 1];
+    for (int i = 1; i < exoResourcePaths.size(); i++) {
+      splitResDirs[i - 1] = exoResourcePaths.get(i);
+    }
+    ActivityThreadInternal activityThread = ActivityThreadInternal.currentActivityThread();
+    for (LoadedApkInternal loadedApk : activityThread.getLoadedApks()) {
+      if (loadedApk.getApplication() == context) {
+        loadedApk.setResDir(resDir);
+        loadedApk.setSplitResDirs(splitResDirs);
+      }
+    }
+  }
+
+  private static List<String> getExoPaths(Context context) throws IOException {
+    if (sExoResourcesPaths == null) {
+      sExoResourcesPaths = readMetadata(context);
+    }
+    return sExoResourcesPaths;
+  }
+
+  private static Collection<WeakReference<Resources>> getActiveResources() {
+    Collection<WeakReference<Resources>> activeResources = getActiveResourcesFromResourcesManager();
+    if (activeResources != null) {
+      return activeResources;
+    }
+    return getActiveResourcesFromActivityThread();
+  }
+
+  private static Collection<WeakReference<Resources>> getActiveResourcesFromActivityThread() {
+    try {
+      return ActivityThreadInternal.currentActivityThread().getActiveResources().values();
+    } catch (Exception e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @TargetApi(KITKAT)
+  private static Collection<WeakReference<Resources>> getActiveResourcesFromResourcesManager() {
+    if (SDK_INT < KITKAT) {
+      return null;
+    }
+    try {
+      ResourcesManagerInternal resourcesManager = ResourcesManagerInternal.getInstance();
+      if (SDK_INT < NOUGAT) {
+        return resourcesManager.getActiveResources().values();
+      }
+      return resourcesManager.getResourceReferences();
+    } catch (RuntimeException e) {
+      throw e;
+    } catch (Exception e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static List<String> readMetadata(Context context) throws IOException {
+    File resourcesDirectory =
+        new File("/data/local/tmp/exopackage/" + context.getPackageName() + "/resources");
+    BufferedReader br = null;
+    try {
+      br = new BufferedReader(new FileReader(new File(resourcesDirectory, "metadata.txt")));
+      ArrayList<String> resources = new ArrayList<>();
+      for (String line; (line = br.readLine()) != null; ) {
+        String[] values = line.split(" ");
+        if (values.length != 2) {
+          throw new RuntimeException("Bad metadata for resources... (" + line + ")");
+        }
+        if (!values[0].equals("resources")) {
+          throw new RuntimeException("Unrecognized resource type: (" + line + ")");
+        }
+        File apk = new File(resourcesDirectory, values[1] + ".apk");
+        if (!apk.exists()) {
+          throw new RuntimeException("resources don't exist... (" + line + ")");
+        }
+        resources.add(apk.getAbsolutePath());
+      }
+      return resources;
+    } finally {
+      if (br != null) {
+        br.close();
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/SystemClassLoaderAdder.java b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/SystemClassLoaderAdder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/android/com/facebook/buck/android/support/exopackage/SystemClassLoaderAdder.java
@@ -0,0 +1,213 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.support.exopackage;
+
+import android.annotation.TargetApi;
+import android.os.Build;
+import dalvik.system.BaseDexClassLoader;
+import dalvik.system.DexClassLoader;
+import dalvik.system.PathClassLoader;
+import java.io.File;
+import java.lang.reflect.Array;
+import java.util.List;
+
+/**
+ * Uses reflection to modify the system class loader. There's no way to override or replace the
+ * system class loader with our own class loader that knows how to load our pre-dexed jars. This
+ * uses reflection to modify the system class loader. This was written based on careful inspection
+ * of the source Android source for {@link DexClassLoader} and {@link PathClassLoader}.
+ */
+public class SystemClassLoaderAdder {
+
+  private SystemClassLoaderAdder() {}
+
+  /**
+   * Installs a list of .dex.jar files into the application class loader.
+   *
+   * @param appClassLoader The application ClassLoader, which can be retrieved by calling {@code
+   *     getClassLoader} on the application Context.
+   * @param optimizedDirectory Directory for storing optimized dex files.
+   * @param dexJars The list of .dex.jar files to load.
+   */
+  public static void installDexJars(
+      ClassLoader appClassLoader, File optimizedDirectory, List<File> dexJars) {
+    SystemClassLoaderAdder classLoaderAdder = new SystemClassLoaderAdder();
+
+    for (File dexJar : dexJars) {
+      DexClassLoader newClassLoader =
+          new DexClassLoader(
+              dexJar.getAbsolutePath(), optimizedDirectory.getAbsolutePath(), null, appClassLoader);
+      classLoaderAdder.addPathsOfClassLoaderToSystemClassLoader(
+          newClassLoader, (PathClassLoader) appClassLoader);
+    }
+  }
+
+  /**
+   * Adds the paths in {@code newClassLoader} to the paths in {@code systemClassLoader} using
+   * reflection since there's no way to do this with public APIs.
+   *
+   * @param newClassLoader the class loader with the new paths
+   * @param systemClassLoader the system class loader
+   */
+  private void addPathsOfClassLoaderToSystemClassLoader(
+      DexClassLoader newClassLoader, PathClassLoader systemClassLoader) {
+
+    try {
+      if (existsBaseDexClassLoader()) {
+        // In ICS, PathClassLoader and DexClassLoader are built on a common base class called
+        // BaseDexClassLoader.
+        addNewClassLoaderToSystemClassLoaderWithBaseDex(newClassLoader, systemClassLoader);
+      } else {
+        // In earlier versions, PathClassLoader and DexClassLoader have similar layout but
+        // don't share code.
+        addNewClassLoaderToSystemClassLoaderPreBaseDex(newClassLoader, systemClassLoader);
+      }
+    } catch (NoSuchFieldException e) {
+      throw new RuntimeException(e);
+    } catch (IllegalAccessException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private boolean existsBaseDexClassLoader() {
+    try {
+      Class.forName("dalvik.system.BaseDexClassLoader");
+      return true;
+    } catch (ClassNotFoundException e) {
+      return false;
+    }
+  }
+
+  /**
+   * Adds the paths in {@code newClassLoader} to the paths in {@code systemClassLoader}. This works
+   * with versions of Android that have {@link BaseDexClassLoader}.
+   *
+   * @param newClassLoader the class loader with the new paths
+   * @param systemClassLoader the system class loader
+   */
+  private void addNewClassLoaderToSystemClassLoaderWithBaseDex(
+      DexClassLoader newClassLoader, PathClassLoader systemClassLoader)
+      throws NoSuchFieldException, IllegalAccessException {
+    Object currentElementsArray = getDexElementsArray(getDexPathList(systemClassLoader));
+    Object newElementsArray = getDexElementsArray(getDexPathList(newClassLoader));
+    Object mergedElementsArray = mergeArrays(currentElementsArray, newElementsArray);
+    setDexElementsArray(getDexPathList(systemClassLoader), mergedElementsArray);
+  }
+
+  /**
+   * Adds the paths in {@code newClassLoader} to the paths in {@code systemClassLoader}. This works
+   * with versions of Android that pre-date {@link BaseDexClassLoader}.
+   *
+   * @param newClassLoader the class loader with the new paths
+   * @param systemClassLoader the system class loader
+   */
+  @SuppressWarnings("PMD.EmptyCatchBlock")
+  private void addNewClassLoaderToSystemClassLoaderPreBaseDex(
+      DexClassLoader newClassLoader, PathClassLoader systemClassLoader)
+      throws NoSuchFieldException, IllegalAccessException {
+
+    try {
+      // The class loader is lazily initialized. Loading any class forces it to be initialized.
+      newClassLoader.loadClass("foo");
+    } catch (ClassNotFoundException e) {
+      // Expected to fail.
+    }
+
+    // Copy value in scalar field newClassLoader.mRawDexPath and array field
+    // systemClassLoader.mPaths to a new array that replaces systemClassLoader.mPaths.
+    Reflect.setField(
+        systemClassLoader,
+        PathClassLoader.class,
+        "mPaths",
+        mergeArrayAndScalar(
+            Reflect.getField(systemClassLoader, PathClassLoader.class, "mPaths"),
+            Reflect.getField(newClassLoader, DexClassLoader.class, "mRawDexPath")));
+
+    // Copy values in array field newClassLoader.mFiles and array field systemClassLoader.mFiles
+    // to a new array that replaces systemClassLoader.mFiles.
+    Reflect.setField(
+        systemClassLoader,
+        PathClassLoader.class,
+        "mFiles",
+        mergeArrays(
+            Reflect.getField(systemClassLoader, PathClassLoader.class, "mFiles"),
+            Reflect.getField(newClassLoader, DexClassLoader.class, "mFiles")));
+
+    // Copy values in array field newClassLoader.mZips and array field systemClassLoader.mZips
+    // to a new array that replaces systemClassLoader.mZips.
+    Reflect.setField(
+        systemClassLoader,
+        PathClassLoader.class,
+        "mZips",
+        mergeArrays(
+            Reflect.getField(systemClassLoader, PathClassLoader.class, "mZips"),
+            Reflect.getField(newClassLoader, DexClassLoader.class, "mZips")));
+
+    // Copy values in array field newClassLoader.mDexs and array field systemClassLoader.mDexs
+    // to a new array that replaces systemClassLoader.mDexs.
+    Reflect.setField(
+        systemClassLoader,
+        PathClassLoader.class,
+        "mDexs",
+        mergeArrays(
+            Reflect.getField(systemClassLoader, PathClassLoader.class, "mDexs"),
+            Reflect.getField(newClassLoader, DexClassLoader.class, "mDexs")));
+  }
+
+  @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
+  private Object getDexPathList(BaseDexClassLoader classLoader)
+      throws NoSuchFieldException, IllegalAccessException {
+    return Reflect.getField(classLoader, BaseDexClassLoader.class, "pathList");
+  }
+
+  private Object getDexElementsArray(Object dexPathList)
+      throws NoSuchFieldException, IllegalAccessException {
+    return Reflect.getField(dexPathList, dexPathList.getClass(), "dexElements");
+  }
+
+  private void setDexElementsArray(Object dexPathList, Object newElementArray)
+      throws NoSuchFieldException, IllegalAccessException {
+    Reflect.setField(dexPathList, dexPathList.getClass(), "dexElements", newElementArray);
+  }
+
+  private Object mergeArrays(Object array1, Object array2) {
+    Class<?> arrayClass = array1.getClass();
+    Class<?> itemClass = arrayClass.getComponentType();
+    int array1Size = Array.getLength(array1);
+    int array2Size = Array.getLength(array2);
+    int newSize = array1Size + array2Size;
+    Object newArray = Array.newInstance(itemClass, newSize);
+    for (int i = 0; i < newSize; i++) {
+      if (i < array1Size) {
+        Array.set(newArray, i, Array.get(array1, i));
+      } else {
+        Array.set(newArray, i, Array.get(array2, i - array1Size));
+      }
+    }
+    return newArray;
+  }
+
+  private Object mergeArrayAndScalar(Object array, Object scalar) {
+    Class<?> arrayClass = array.getClass();
+    Class<?> itemClass = arrayClass.getComponentType();
+    int array1Size = Array.getLength(array);
+    int newSize = array1Size + 1;
+    Object newArray = Array.newInstance(itemClass, newSize);
+    for (int i = 0; i < newSize; i++) {
+      if (i < array1Size) {
+        Array.set(newArray, i, Array.get(array, i));
+      } else {
+        Array.set(newArray, i, scalar);
+      }
+    }
+    return newArray;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/config/BUCK b/buck2/prelude/toolchains/android/config/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/config/BUCK
@@ -0,0 +1,26 @@
+# @oss-disable[end= ]: load("@fbcode//buck2/platform:java_toolchains.bzl", "config_backed_java_toolchain")
+# @oss-disable[end= ]: load("@fbcode//buck2/platform:kotlin_toolchains.bzl", "config_backed_kotlin_toolchain")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load("@prelude//toolchains/android/config:oss_toolchains.bzl", "config_backed_java_toolchain", "config_backed_kotlin_toolchain") # @oss-enable
+
+oncall("android_devxx")
+
+source_listing()
+
+config_backed_java_toolchain(
+    name = "java_bootstrap",
+    is_bootstrap_toolchain = True,
+    # This causes us to always use the classic protocol instead of javacd as the bootstrap toolchain needs to build javacd itself.
+    javac = "fbsource//third-party/toolchains/jdk:javac",
+    visibility = [
+        "PUBLIC",
+    ],
+)
+
+config_backed_kotlin_toolchain(
+    name = "kotlin_bootstrap",
+    is_bootstrap_toolchain = True,
+    visibility = [
+        "PUBLIC",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/config/oss_toolchains.bzl b/buck2/prelude/toolchains/android/config/oss_toolchains.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/config/oss_toolchains.bzl
@@ -0,0 +1,13 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def config_backed_java_toolchain(name, is_bootstrap_toolchain = False, javac = None, java = None, java_for_tests = None, visibility = None, global_code_config = {}):
+    _unused = (name, is_bootstrap_toolchain, javac, java, java_for_tests, visibility, global_code_config)
+
+def config_backed_kotlin_toolchain(name, kotlinc = None, is_bootstrap_toolchain = False, extra_kotlin_home_libraries = [], **kwargs):
+    _unused = (name, kotlinc, is_bootstrap_toolchain, extra_kotlin_home_libraries, kwargs)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbExecutionContext.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbExecutionContext.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbExecutionContext.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android;
+
+import com.facebook.buck.util.environment.EnvVariablesProvider;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableMap;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AdbExecutionContext {
+
+  public ImmutableMap<String, String> getEnvironment() {
+    return EnvVariablesProvider.getSystemEnv();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbHelper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbHelper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbHelper.java
@@ -0,0 +1,998 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android;
+
+import static com.google.common.util.concurrent.MoreExecutors.listeningDecorator;
+
+import com.facebook.buck.android.apex.ApexManifestProto.ApexManifest;
+import com.facebook.buck.android.device.TargetDeviceOptions;
+import com.facebook.buck.android.exopackage.AdbUtils;
+import com.facebook.buck.android.exopackage.AndroidDevice;
+import com.facebook.buck.android.exopackage.AndroidDeviceInfo;
+import com.facebook.buck.android.exopackage.AndroidDevicesHelper;
+import com.facebook.buck.android.exopackage.AndroidIntent;
+import com.facebook.buck.android.exopackage.ExopackageInstaller;
+import com.facebook.buck.android.exopackage.InstallTimings;
+import com.facebook.buck.android.exopackage.IsolatedExopackageInfo;
+import com.facebook.buck.android.exopackage.SetDebugAppMode;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.util.MoreSuppliers;
+import com.facebook.buck.util.Threads;
+import com.facebook.buck.util.environment.EnvVariablesProvider;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import org.jetbrains.annotations.Nullable;
+
+/** Helper for executing commands over ADB, especially for multiple devices. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AdbHelper implements AndroidDevicesHelper {
+
+  private static final Logger LOG = Logger.get(AdbHelper.class);
+
+  /** Pattern that matches safe package names. (Must be a full string match). */
+  public static final Pattern PACKAGE_NAME_PATTERN = Pattern.compile("[\\w.-]+");
+
+  private static Optional<Supplier<ImmutableList<AndroidDevice>>> devicesSupplierForTests =
+      Optional.empty();
+
+  private static final Set<String> SUPPORTED_ABIS =
+      ImmutableSet.of("armeabi-v7a", "arm64-v8a", "x86", "x86_64");
+
+  public static final Path BUILD_METADATA_INSTALL_ROOT =
+      Paths.get("/data/local/tmp/build_metadata/");
+
+  /**
+   * If this environment variable is set, the device with the specified serial number is targeted.
+   * The -s option overrides this.
+   */
+  static final String SERIAL_NUMBER_ENV = "ANDROID_SERIAL";
+
+  private static final String ABI_PROPERTY = "ro.product.cpu.abi";
+  private static final String ABI_LIST_PROPERTY = "ro.product.cpu.abilist";
+
+  static final int NUM_TRIES = 5;
+  static final int RETRY_DELAY_MS = 1000;
+
+  /**
+   * The next port number to use for communicating with the agent on a device. This resets for every
+   * instance of AdbHelper, but is incremented for every device on every call to adbCall().
+   */
+  private final AdbOptions options;
+
+  private final TargetDeviceOptions deviceOptions;
+  private final AdbExecutionContext adbExecutionContext;
+  private final boolean restartAdbOnFailure;
+  // Caches the list of android devices for this execution
+  private final Supplier<GetDevicesResult> devicesSupplier;
+  private final Supplier<ImmutableMap<String, ImmutableSet<String>>> deviceAbisSupplier;
+  private final AndroidInstallPrinter androidPrinter;
+  private final SetDebugAppMode setDebugAppMode;
+  private final InstallTimings timings;
+
+  @Nullable private ListeningExecutorService executorService = null;
+
+  private final AdbUtils adbUtils;
+
+  public AdbHelper(
+      AdbUtils adbUtils,
+      AdbOptions adbOptions,
+      TargetDeviceOptions deviceOptions,
+      AdbExecutionContext adbExecutionContext,
+      AndroidInstallPrinter androidPrinter,
+      boolean restartAdbOnFailure,
+      SetDebugAppMode setDebugAppMode) {
+    this(
+        adbUtils,
+        adbOptions,
+        deviceOptions,
+        adbExecutionContext,
+        androidPrinter,
+        restartAdbOnFailure,
+        setDebugAppMode,
+        InstallTimings.NONE);
+  }
+
+  public AdbHelper(
+      AdbUtils adbUtils,
+      AdbOptions adbOptions,
+      TargetDeviceOptions deviceOptions,
+      AdbExecutionContext adbExecutionContext,
+      AndroidInstallPrinter androidPrinter,
+      boolean restartAdbOnFailure,
+      SetDebugAppMode setDebugAppMode,
+      InstallTimings timings) {
+    this.timings = timings;
+    this.adbUtils = adbUtils;
+    this.options = adbOptions;
+    this.deviceOptions = deviceOptions;
+    this.adbExecutionContext = adbExecutionContext;
+    this.restartAdbOnFailure = restartAdbOnFailure;
+    this.devicesSupplier = MoreSuppliers.memoize(this::getDevicesImpl);
+    this.deviceAbisSupplier = MoreSuppliers.memoize(this::deviceAbisBySerialImpl);
+    this.androidPrinter = androidPrinter;
+    this.setDebugAppMode = setDebugAppMode;
+  }
+
+  @VisibleForTesting
+  public static void setDevicesSupplierForTests(
+      Optional<Supplier<ImmutableList<AndroidDevice>>> devicesSupplierForTests) {
+    AdbHelper.devicesSupplierForTests = devicesSupplierForTests;
+  }
+
+  /**
+   * Of the devices this helper resolved, those adb no longer reports.
+   *
+   * <p>The resolved set is fixed at its first use; this asks adb afresh on every call, so it is for
+   * deciding once whether to go on rather than for polling. What it asks for is every serial adb
+   * reports, not the filtered set: a superset can only shrink the answer, and a device that never
+   * matched the filter was never resolved, so it can never be reported gone.
+   */
+  public ImmutableSet<String> departedSerials() {
+    ImmutableSet<String> connected =
+        adbUtils.getDevices().stream()
+            .map(AndroidDevice::getSerialNumber)
+            .collect(ImmutableSet.toImmutableSet());
+    if (connected.isEmpty()) {
+      // Adb answering with nothing is far more likely to be adb than every device at once. Reading
+      // it as a mass departure would fail installs that a retry would have completed, and a device
+      // that really has gone still fails the moment it is used.
+      LOG.warn("adb reported no devices at all; not treating that as a disconnection");
+      return ImmutableSet.of();
+    }
+    return devicesSupplier.get().devices.stream()
+        .map(AndroidDevice::getSerialNumber)
+        .filter(serial -> !connected.contains(serial))
+        .collect(ImmutableSet.toImmutableSet());
+  }
+
+  @Override
+  public ImmutableList<AndroidDevice> getDevices(boolean quiet) {
+    GetDevicesResult result = devicesSupplier.get();
+    if (!quiet && result.devices.size() > 1) {
+      // Report if multiple devices are matching the filter.
+      androidPrinter.printMessage("Found " + result.devices.size() + " matching devices.\n");
+    }
+    result.errorMessage.ifPresent(androidPrinter::printError);
+    return result.devices;
+  }
+
+  /**
+   * Execute an {@link AdbDeviceCallable} for all matching devices. This functions performs device
+   * filtering based on three possible arguments:
+   *
+   * <p>-e (emulator-only) - only emulators are passing the filter -d (device-only) - only real
+   * devices are passing the filter -s (serial) - only device/emulator with specific serial number
+   * are passing the filter
+   *
+   * <p>If more than one device matches the filter this function will fail unless multi-install mode
+   * is enabled (-x). This flag is used as a marker that user understands that multiple devices will
+   * be used to install the apk if needed.
+   */
+  @SuppressWarnings("PMD.EmptyCatchBlock")
+  @Override
+  public synchronized void adbCall(String description, AdbDeviceCallable func, boolean quiet)
+      throws InterruptedException {
+    List<AndroidDevice> devices;
+
+    try {
+      GetDevicesResult result = devicesSupplier.get();
+      if (!quiet && result.devices.size() > 1) {
+        // Report if multiple devices are matching the filter.
+        androidPrinter.printMessage("Found " + result.devices.size() + " matching devices.\n");
+      }
+      if (result.errorMessage.isPresent()) {
+        throw new RuntimeException(result.errorMessage.get());
+      } else if (result.devices.isEmpty()) {
+        if (options.getIgnoreMissingDevice()) {
+          androidPrinter.printMessage(
+              "Proceeding anyway, even though we didn't find any attached Android"
+                  + " devices/emulators.\n");
+          return;
+        }
+        throw new RuntimeException("Didn't find any attached Android devices/emulators.");
+      }
+      devices = result.devices;
+    } catch (Exception e) {
+      throw new RuntimeException(e.toString());
+    }
+
+    // Start executions on all matching devices.
+    List<ListenableFuture<Boolean>> futures = new ArrayList<>();
+    for (AndroidDevice device : devices) {
+      futures.add(
+          getExecutorService()
+              .submit(
+                  () -> {
+                    return func.apply(device);
+                  }));
+    }
+
+    // Wait for all executions to complete or fail.
+    List<Boolean> results;
+    try {
+      results = Futures.allAsList(futures).get();
+    } catch (ExecutionException ex) {
+      throw new RuntimeException(ex.getCause());
+    } catch (InterruptedException e) {
+      try {
+        Futures.allAsList(futures).cancel(true);
+      } catch (CancellationException ignored) {
+        // Rethrow original InterruptedException instead.
+      }
+      Threads.interruptCurrentThread();
+      throw e;
+    }
+
+    int successCount = 0;
+    for (boolean result : results) {
+      if (result) {
+        successCount++;
+      }
+    }
+    int failureCount = results.size() - successCount;
+
+    // Report results.
+    if (successCount > 0 && !quiet) {
+      androidPrinter.printSuccess(
+          String.format("Successfully ran %s on %d device(s)", description, successCount));
+    }
+
+    if (failureCount != 0) {
+      throw new RuntimeException(
+          String.format("Failed to %s on %d device(s).", description, failureCount));
+    }
+  }
+
+  private synchronized ListeningExecutorService getExecutorService() {
+    if (executorService != null) {
+      return executorService;
+    }
+    int deviceCount;
+    deviceCount = getDevices(true).size();
+    int adbThreadCount = options.getAdbThreadCount();
+    if (adbThreadCount <= 0) {
+      adbThreadCount = deviceCount;
+    }
+    adbThreadCount = Math.min(deviceCount, adbThreadCount);
+    executorService =
+        listeningDecorator(
+            Executors.newFixedThreadPool(
+                adbThreadCount,
+                new ThreadFactoryBuilder().setNameFormat(getClass().getSimpleName()).build()));
+    return executorService;
+  }
+
+  public void installApk(
+      IsolatedApkInfo isolatedApkInfo,
+      Optional<IsolatedExopackageInfo> optionalIsolatedExopackageInfo,
+      AbsPath rootPath,
+      boolean installViaSd,
+      boolean quiet,
+      String fullyQualifiedName,
+      String packageName)
+      throws InterruptedException {
+    Optional<String> buck2BuildUuid =
+        Optional.ofNullable(EnvVariablesProvider.getSystemEnv().get("BUCK2_UUID"));
+
+    AtomicBoolean success = new AtomicBoolean();
+
+    if (optionalIsolatedExopackageInfo.isPresent()) {
+      IsolatedExopackageInfo isolatedExopackageInfo = optionalIsolatedExopackageInfo.get();
+      installApkExopackageWithRetries(
+          rootPath, isolatedExopackageInfo, isolatedApkInfo, packageName, quiet, buck2BuildUuid);
+    } else {
+      installApkDirectly(
+          installViaSd,
+          quiet,
+          isolatedApkInfo,
+          fullyQualifiedName,
+          packageName,
+          setDebugAppMode,
+          buck2BuildUuid);
+    }
+    success.set(true);
+  }
+
+  @Override
+  public Set<AndroidDeviceInfo> getAndroidDeviceInfo(IsolatedApkInfo isolatedApkInfo)
+      throws InterruptedException {
+    Set<AndroidDeviceInfo> deviceInfos = new HashSet<>();
+
+    adbCall(
+        "Get device info",
+        (device) -> {
+          try {
+            // Need to call both ro.product.cpu.abi and ro.product.cpu.abilist
+            // as sticking to ro.product.cpu.abi helped fixing the issue of
+            // exopackage install when the app was already installed in the device.
+            String abi = device.getProperty(ABI_PROPERTY);
+            Set<String> abiList =
+                new HashSet<>(Arrays.asList(device.getProperty(ABI_LIST_PROPERTY).split(",")));
+            String locale = getDeviceLocale(device);
+            String buildFingerprint = device.getProperty("ro.build.fingerprint");
+            String dpi = getDeviceDpi(device);
+            String sdk = device.getProperty("ro.build.version.sdk");
+            List<String> diskSpace = device.getDiskSpace(/* humanReadable= */ true);
+            LOG.info(
+                "Device disk size: %s, used: %s, available: %s",
+                diskSpace.get(0), diskSpace.get(1), diskSpace.get(2));
+            boolean isEmulator = device.isEmulator();
+
+            AndroidDeviceInfo deviceInfo =
+                new AndroidDeviceInfo(
+                    locale,
+                    abi,
+                    abiList,
+                    buildFingerprint,
+                    dpi,
+                    AndroidDeviceInfo.DensityClass.forPhysicalDensity(dpi),
+                    sdk,
+                    isEmulator,
+                    AndroidDeviceInfo.transportOf(device.getSerialNumber()));
+            LOG.info("Device info [%s]: %s", device.getSerialNumber(), deviceInfo);
+            deviceInfos.add(deviceInfo);
+          } catch (IncompatibleAbiException e) {
+            throw e;
+          } catch (Exception e) {
+            // Don't log.
+          }
+          return true;
+        },
+        true);
+    return deviceInfos;
+  }
+
+  /**
+   * What each targeted device can run, by serial, read through the configured adb rather than
+   * whatever `adb` is on the path. A device that will not say is left out rather than recorded as
+   * running nothing, so callers can tell "cannot run this" from "would not answer".
+   *
+   * <p>Answered once per helper: these are boot-time properties of a fixed set of devices, and the
+   * check that reads them is offered every time an artifact arrives.
+   */
+  public ImmutableMap<String, ImmutableSet<String>> deviceAbisBySerial() {
+    return deviceAbisSupplier.get();
+  }
+
+  private ImmutableMap<String, ImmutableSet<String>> deviceAbisBySerialImpl() {
+    ImmutableMap.Builder<String, ImmutableSet<String>> abis = ImmutableMap.builder();
+    for (AndroidDevice device : getDevices(true)) {
+      // Both properties, trimmed, blanks dropped: the list is comma separated and devices do put
+      // spaces after the commas. Read separately so a device that answers one still contributes
+      // it.
+      ImmutableSet<String> forDevice =
+          Stream.concat(
+                  readProperty(device, ABI_PROPERTY).stream(),
+                  readProperty(device, ABI_LIST_PROPERTY).stream()
+                      .flatMap(list -> Arrays.stream(list.split(","))))
+              .map(String::trim)
+              .filter(abi -> !abi.isEmpty())
+              .collect(ImmutableSet.toImmutableSet());
+      if (!forDevice.isEmpty()) {
+        abis.put(device.getSerialNumber(), forDevice);
+      }
+    }
+    ImmutableMap<String, ImmutableSet<String>> bySerial = abis.build();
+    if (bySerial.isEmpty()) {
+      LOG.info("No targeted device would report an ABI");
+    }
+    return bySerial;
+  }
+
+  /** One property of one device, or empty if the device will not answer for it. */
+  private Optional<String> readProperty(AndroidDevice device, String property) {
+    try {
+      return Optional.ofNullable(device.getProperty(property));
+    } catch (Exception e) {
+      LOG.warn(e, "Could not read %s of %s", property, device.getSerialNumber());
+      return Optional.empty();
+    }
+  }
+
+  public void throwIfIncompatibleAbi(
+      AndroidDeviceInfo androidDeviceInfo, IsolatedApkInfo isolatedApkInfo)
+      throws IncompatibleAbiException {
+    Set<String> abis = getDeviceAbis(androidDeviceInfo.getAbi(), androidDeviceInfo.getAbiList());
+    File apk = isolatedApkInfo.getApkPath().toFile();
+    Set<String> apkAbis = getApkAbis(apk);
+    if (!apkAbis.isEmpty() && Sets.intersection(abis, apkAbis).isEmpty()) {
+      String errorMsg =
+          String.format(
+              "You are trying to install %s%s onto a device with the following CPU(s): %s. "
+                  + "Please try again with a correct one. If you used an alias, "
+                  + "some default aliases may have changed: https://fburl.com/workplace/p4ty6uvo.",
+              apk.getName(),
+              String.format(" (CPU(s): %s)", String.join(", ", apkAbis)),
+              String.join(", ", abis));
+      throw new IncompatibleAbiException(errorMsg);
+    }
+  }
+
+  private Set<String> getDeviceAbis(String abi, Set<String> abiList) {
+    return ImmutableSet.<String>builder().add(abi).addAll(abiList).build();
+  }
+
+  private Set<String> getApkAbis(File apk) {
+    Set<String> abis = new HashSet<>();
+    Pattern cpuPattern = Pattern.compile("lib/([^/]*)/");
+
+    try (ZipFile zipFile = new ZipFile(apk)) {
+      Enumeration<? extends ZipEntry> entries = zipFile.entries();
+      while (entries.hasMoreElements()) {
+        ZipEntry entry = entries.nextElement();
+        Matcher m = cpuPattern.matcher(entry.getName());
+        if (m.find()) {
+          String abi = m.group(1);
+          if (SUPPORTED_ABIS.contains(abi)) {
+            abis.add(abi);
+          }
+        }
+      }
+    } catch (IOException e) {
+      LOG.warn(e, "Failed to infer ABIs from apk: %s", apk);
+    }
+
+    return abis;
+  }
+
+  private static ImmutableMap<String, String> convertToMap(Set<AndroidDeviceInfo> infos) {
+    ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
+
+    map.put("install_device_locales", toCommaList(infos, AndroidDeviceInfo::getLocale));
+    map.put("install_device_abis", toCommaList(infos, AndroidDeviceInfo::getAbi));
+    map.put(
+        "install_device_build_fingerprint",
+        toCommaList(infos, AndroidDeviceInfo::getBuildFingerprint));
+    map.put("install_device_densities", toCommaList(infos, i -> i.getDensity().toString()));
+    map.put("install_device_dpi", toCommaList(infos, AndroidDeviceInfo::getDotsPerInch));
+    map.put("install_device_sdk", toCommaList(infos, AndroidDeviceInfo::getSdk));
+    map.put("install_device_is_emulator", toCommaList(infos, i -> String.valueOf(i.isEmulator())));
+
+    return map.build();
+  }
+
+  private static String toCommaList(
+      Set<AndroidDeviceInfo> infos, Function<AndroidDeviceInfo, String> mapper) {
+    return infos.stream().map(mapper).collect(Collectors.joining(","));
+  }
+
+  private static String getDeviceLocale(AndroidDevice device) throws Exception {
+    // It's a bit tortuous to get the locale; there are 6 separate properties
+    // we need to check to accurately record this.
+
+    // First try "persist.sys" properties, which are the user's chosen language.
+    String locale = device.getProperty("persist.sys.locale");
+    // Try persist.sys.language + persist.sys.country
+    if (Strings.isNullOrEmpty(locale)) {
+      String language = device.getProperty("persist.sys.language");
+      if (!Strings.isNullOrEmpty(language)) {
+        String country = device.getProperty("persist.sys.country");
+        if (!Strings.isNullOrEmpty(country)) {
+          locale = language + "-" + country;
+        }
+      }
+    }
+    // Next try ro.product.locale properties which are the default system locale
+    if (Strings.isNullOrEmpty(locale)) {
+      locale = device.getProperty("ro.product.locale");
+    }
+    if (Strings.isNullOrEmpty(locale)) {
+      String language = device.getProperty("ro.product.locale.language");
+      String country = device.getProperty("ro.product.locale.region");
+
+      // Default to en-US if all else fails
+      if (Strings.isNullOrEmpty(language)) {
+        language = "en";
+      }
+      if (Strings.isNullOrEmpty(country)) {
+        country = "US-presumed";
+      }
+      locale = language + "-" + country;
+    }
+    return locale;
+  }
+
+  private static String getDeviceDpi(AndroidDevice device) throws Exception {
+    // First, try getting it from a property
+    String dpi = device.getProperty("ro.sf.lcd_density");
+    if (Strings.isNullOrEmpty(dpi)) {
+      // Try getting it from the WindowManager
+      dpi = device.getProperty("density");
+    }
+    return dpi;
+  }
+
+  public void startActivityForIsolatedApk(
+      IsolatedApkInfo isolatedApkInfo,
+      String fullyQualifiedName,
+      @Nullable String activity,
+      @Nullable String intentUri,
+      boolean waitForDebugger,
+      boolean skipSetDebugApp)
+      throws IOException {
+
+    // Might need the package name and activities from the AndroidManifest.
+    AndroidManifestReader reader =
+        DefaultAndroidManifestReader.forPath(isolatedApkInfo.getManifestPath().getPath());
+
+    final String packageName = reader.getPackage();
+
+    final AndroidIntent intent;
+    final String intentTargetNiceName;
+    if (intentUri != null) {
+      intent =
+          new AndroidIntent(
+              packageName,
+              null,
+              AndroidIntent.ACTION_VIEW,
+              null,
+              intentUri,
+              null,
+              waitForDebugger,
+              skipSetDebugApp);
+      intentTargetNiceName = intentUri;
+    } else {
+      if (activity == null) {
+        // Get list of activities that show up in the launcher.
+        List<String> launcherActivities = reader.getLauncherActivities();
+
+        // Sanity check.
+        if (launcherActivities.isEmpty()) {
+          throw new RuntimeException("No launchable activities found.");
+        } else if (launcherActivities.size() > 1) {
+          throw new RuntimeException("Default activity is ambiguous.");
+        }
+
+        // Construct a component for the '-n' argument of 'adb shell am start'.
+        activity = packageName + "/" + launcherActivities.get(0);
+      } else if (!activity.contains("/")) {
+        // If no package name was provided, assume the one in the manifest.
+        activity = packageName + "/" + activity;
+      }
+
+      //  0x10200000 is FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | FLAG_ACTIVITY_NEW_TASK; the
+      // constant values are public ABI.  This way of invoking "am start" makes buck install -r
+      // act just like the launcher, avoiding activity duplication on subsequent
+      // launcher starts.
+      intent =
+          new AndroidIntent(
+              packageName,
+              activity,
+              AndroidIntent.ACTION_MAIN,
+              AndroidIntent.CATEGORY_LAUNCHER,
+              null,
+              "0x10200000",
+              waitForDebugger,
+              skipSetDebugApp);
+      intentTargetNiceName = activity;
+    }
+
+    androidPrinter.printMessage(String.format("Starting activity %s...", intentTargetNiceName));
+
+    try {
+      adbCallOrThrow(
+          "start activity",
+          (device) -> {
+            device.deviceStartIntent(intent);
+            return true;
+          },
+          false);
+    } catch (Exception e) {
+    }
+  }
+
+  /**
+   * Uninstall apk from all matching devices.
+   *
+   * @see #installApk(IsolatedApkInfo, Optional, AbsPath, boolean, boolean, String)
+   */
+  @Override
+  public void uninstallApp(String packageName, boolean shouldKeepUserData)
+      throws InterruptedException {
+    Preconditions.checkArgument(AdbHelper.PACKAGE_NAME_PATTERN.matcher(packageName).matches());
+
+    try {
+      adbCall(
+          "uninstall apk",
+          (device) -> {
+            device.uninstallApkFromDevice(packageName, shouldKeepUserData);
+            return true;
+          },
+          false);
+    } catch (RuntimeException e) {
+      throw e;
+    }
+  }
+
+  public static String tryToExtractPackageNameFromManifest(Path pathToManifest) {
+    // Note that the file may not exist if AndroidManifest.xml is a generated file
+    // and the rule has not been built yet.
+    if (!Files.isRegularFile(pathToManifest)) {
+      throw new RuntimeException(
+          String.format(
+              "Manifest file %s does not exist, so could not extract package name.",
+              pathToManifest));
+    }
+
+    try {
+      return DefaultAndroidManifestReader.forPath(pathToManifest).getPackage();
+    } catch (IOException e) {
+      throw new RuntimeException(
+          String.format("Could not extract package name from %s", pathToManifest));
+    }
+  }
+
+  /**
+   * Returns list of devices that pass the filter. If there is an invalid combination or no devices
+   * are left after filtering this function prints an error and returns null.
+   */
+  @VisibleForTesting
+  List<AndroidDevice> filterDevices(List<AndroidDevice> allDevices) {
+    if (allDevices.isEmpty()) {
+      androidPrinter.printError("No devices are found.");
+      return Collections.emptyList();
+    }
+
+    List<AndroidDevice> devices = new ArrayList<>();
+    Optional<Boolean> emulatorsOnly = Optional.empty();
+    if (deviceOptions.isEmulatorsOnlyModeEnabled() && options.isMultiInstallModeEnabled()) {
+      emulatorsOnly = Optional.empty();
+    } else if (deviceOptions.isEmulatorsOnlyModeEnabled()) {
+      emulatorsOnly = Optional.of(true);
+    } else if (deviceOptions.isRealDevicesOnlyModeEnabled()) {
+      emulatorsOnly = Optional.of(false);
+    }
+
+    int onlineDevices = 0;
+    for (AndroidDevice device : allDevices) {
+      boolean passed = false;
+      if (device.isOnline()) {
+        LOG.info("Found online device: %s", device.getSerialNumber());
+        onlineDevices++;
+
+        boolean serialMatches = true;
+        // -s option or $ANDROID_SERIAL could contain
+        // "tcp:" prefixed serial number for TCP connected device.
+        // It is valid but the following logic needs to remove it.
+        if (deviceOptions.getSerialNumber().isPresent()
+            || getEnvironment().containsKey(SERIAL_NUMBER_ENV)) {
+          String expectedSerialNumber =
+              deviceOptions
+                  .getSerialNumber()
+                  .orElse(getEnvironment().get(SERIAL_NUMBER_ENV))
+                  .replaceFirst("^tcp:", "");
+          serialMatches = expectedSerialNumber.equals(device.getSerialNumber());
+          LOG.info(
+              "Device: %s %s expected serial#: %s",
+              device.getSerialNumber(),
+              serialMatches ? "matches" : "does not match",
+              expectedSerialNumber);
+        }
+
+        // Only devices of specific type are accepted:
+        // either real devices only or emulators only.
+        // All online devices match.
+        boolean isDeviceEmulator = device.isEmulator();
+        boolean deviceTypeMatches =
+            emulatorsOnly.map(isEmulatorOnly -> (isEmulatorOnly == isDeviceEmulator)).orElse(true);
+        LOG.info(
+            "Device: %s %s expected device type. Actual: %s - expected: %s",
+            device.getSerialNumber(),
+            deviceTypeMatches ? "matches" : "does not match",
+            isDeviceEmulator ? "emulator" : "real",
+            emulatorsOnly.map(p -> p ? "emulator" : "real").orElse("any"));
+        passed = serialMatches && deviceTypeMatches;
+      } else {
+        LOG.info("Found offline device: %s", device.getSerialNumber());
+      }
+
+      if (passed) {
+        LOG.info("Device: %s passed filter", device.getSerialNumber());
+        devices.add(device);
+      } else {
+        LOG.info("Device: %s did not pass filter", device.getSerialNumber());
+      }
+    }
+
+    // Filtered out all devices.
+    if (onlineDevices == 0) {
+      androidPrinter.printError("No devices are found.");
+      return Collections.emptyList();
+    }
+
+    if (devices.isEmpty()) {
+      androidPrinter.printError(
+          String.format(
+              "Found %d connected device(s), but none of them matches specified filter.",
+              onlineDevices));
+      return Collections.emptyList();
+    }
+
+    return devices;
+  }
+
+  private ImmutableMap<String, String> getEnvironment() {
+    return adbExecutionContext.getEnvironment();
+  }
+
+  private static class GetDevicesResult {
+
+    private final ImmutableList<AndroidDevice> devices;
+    private final Optional<String> errorMessage;
+
+    private GetDevicesResult(ImmutableList<AndroidDevice> devices, Optional<String> errorMessage) {
+      this.devices = devices;
+      this.errorMessage = errorMessage;
+    }
+
+    static GetDevicesResult createSuccess(ImmutableList<AndroidDevice> devices) {
+      return new GetDevicesResult(devices, Optional.empty());
+    }
+
+    static GetDevicesResult createFailure(String message) {
+      return new GetDevicesResult(ImmutableList.of(), Optional.of(message));
+    }
+  }
+
+  private GetDevicesResult getDevicesImpl() {
+    if (devicesSupplierForTests.isPresent()) {
+      return GetDevicesResult.createSuccess(devicesSupplierForTests.get().get());
+    }
+
+    // Build list of matching devices.
+    List<AndroidDevice> devices = filterDevices(adbUtils.getDevices());
+    // Found multiple devices but multi-install mode is not enabled.
+    if (devices.size() > 1 && !options.isMultiInstallModeEnabled()) {
+      return GetDevicesResult.createFailure(
+          String.format(
+              "%d devices match specified device filter (1 expected).\n"
+                  + "Either disconnect other devices or enable multi-install mode (%s).",
+              devices.size(), AdbOptions.MULTI_INSTALL_MODE_SHORT_ARG));
+    }
+
+    if (devices.isEmpty() && restartAdbOnFailure) {
+      androidPrinter.printError("No devices found with adb, restarting adb-server.");
+      adbUtils.restart();
+      devices = filterDevices(adbUtils.getDevices());
+    }
+
+    return GetDevicesResult.createSuccess(
+        devices.stream().collect(ImmutableList.toImmutableList()));
+  }
+
+  @Override
+  public synchronized void close() {
+    // getExecutorService() requires the context for lazy initialization, so explicitly check if it
+    // has been initialized.
+    if (executorService != null) {
+      if (!MoreExecutors.shutdownAndAwaitTermination(executorService, 10, TimeUnit.MINUTES)) {
+        throw new RuntimeException("Failed to shutdown ExecutorService.");
+      }
+      executorService = null;
+    }
+  }
+
+  private void installApkExopackageWithRetries(
+      AbsPath rootPath,
+      IsolatedExopackageInfo isolatedExopackageInfo,
+      IsolatedApkInfo isolatedApkInfo,
+      String packageName,
+      boolean quiet,
+      Optional<String> buck2BuildUuid)
+      throws InterruptedException {
+    int attempt = 1;
+    while (true) {
+      try {
+        installApkExopackage(
+            rootPath, isolatedExopackageInfo, isolatedApkInfo, packageName, quiet, buck2BuildUuid);
+        LOG.info("Installing the APK using exopackage succeeded on attempt %d", attempt);
+        return;
+      } catch (RuntimeException e) {
+        if (attempt >= NUM_TRIES) {
+          LOG.error(e, "Failed to install the APK using exopackage after %d attempts.", NUM_TRIES);
+
+          throw e;
+        } else {
+          // installation failed, so log the error and continue with the next retry
+          LOG.warn(e, "Error installing APK using exopackage (attempt %d/%d).", attempt, NUM_TRIES);
+
+          Thread.sleep(RETRY_DELAY_MS);
+          ++attempt;
+        }
+      }
+    }
+  }
+
+  /**
+   * Pushes exopackage payloads to the matching devices ahead of the install itself.
+   *
+   * <p>Only pushes content. Metadata, collection of stale files and the apk all need the complete
+   * artifact set, so they stay in {@link ExopackageInstaller#doInstall}, which lists the directory
+   * again and skips whatever landed here.
+   */
+  public void streamExopackagePayloads(
+      AbsPath rootPath, IsolatedExopackageInfo isolatedExopackageInfo, String packageName)
+      throws InterruptedException {
+    adbCall(
+        "push exopackage files",
+        device -> {
+          new ExopackageInstaller(
+                  isolatedExopackageInfo,
+                  androidPrinter,
+                  rootPath,
+                  packageName,
+                  device,
+                  Optional.empty(),
+                  timings)
+              .streamPayloads();
+          return true;
+        },
+        /* quiet= */ true);
+  }
+
+  private void installApkExopackage(
+      AbsPath rootPath,
+      IsolatedExopackageInfo isolatedExopackageInfo,
+      IsolatedApkInfo isolatedApkInfo,
+      String packageName,
+      boolean quiet,
+      Optional<String> buck2BuildUuid)
+      throws InterruptedException {
+    adbCall(
+        "install exopackage apk",
+        device -> {
+          new ExopackageInstaller(
+                  isolatedExopackageInfo,
+                  androidPrinter,
+                  rootPath,
+                  packageName,
+                  device,
+                  buck2BuildUuid,
+                  timings)
+              .doInstall(isolatedApkInfo, setDebugAppMode);
+          return true;
+        },
+        quiet);
+  }
+
+  private void installApkDirectly(
+      boolean installViaSd,
+      boolean quiet,
+      IsolatedApkInfo isolatedApkInfo,
+      String buildTarget,
+      String packageName,
+      SetDebugAppMode setDebugAppMode,
+      Optional<String> buck2BuildUuid)
+      throws InterruptedException {
+    File apk = isolatedApkInfo.getApkPath().toFile();
+    if (setDebugAppMode == SetDebugAppMode.SET) {
+      adbCall("set debug app", (device) -> device.setDebugAppPackageName(packageName), true);
+    }
+    adbCall(
+        String.format("install apk %s", buildTarget),
+        (device) -> {
+          if (options.isApexModeEnabled()) {
+
+            boolean restart = false;
+            if (options.getRestartMode().equals("yes")) { // Restart
+              restart = true;
+            } else if (options.getRestartMode().equals("no")) { // Don't Restart
+              restart = false;
+            } else { // Auto - Only restart shell if rebootless is supported
+              restart = isApexFileSupportsRebootlessUpdate(apk);
+            }
+            return device.installApexOnDevice(apk, quiet, restart, options.getWaitForDeviceReady());
+          } else {
+            return device.installApkOnDevice(
+                apk, installViaSd, quiet, options.isStagedInstallModeEnabled(), packageName);
+          }
+        },
+        quiet);
+
+    if (buck2BuildUuid.isPresent()) {
+      adbCall(
+          "install build_uuid.txt",
+          (device) ->
+              device.installBuildUuidFile(
+                  BUILD_METADATA_INSTALL_ROOT, packageName, buck2BuildUuid.get()),
+          true);
+    }
+  }
+
+  private boolean isApexFileSupportsRebootlessUpdate(File apexFile) {
+    try {
+      // Open APEX file as a zip archive
+      try (ZipFile zipFile = new ZipFile(apexFile)) {
+        // Find the apex_manifest.pb entry
+        ZipEntry manifestEntry = zipFile.getEntry("apex_manifest.pb");
+
+        if (manifestEntry == null) {
+          LOG.warn("apex_manifest.pb not found in APEX file: %s", apexFile.getName());
+          return false;
+        }
+
+        // Extract the manifest directly to byte array
+        byte[] manifestBytes;
+        try (java.io.InputStream inputStream =
+                Objects.requireNonNull(zipFile.getInputStream(manifestEntry));
+            java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream()) {
+          byte[] buffer = new byte[8192];
+          int bytesRead;
+          while ((bytesRead = inputStream.read(buffer)) != -1) {
+            outputStream.write(buffer, 0, bytesRead);
+          }
+          manifestBytes = outputStream.toByteArray();
+        }
+
+        LOG.info(
+            "Extracted apex_manifest.pb from %s (%d bytes)",
+            apexFile.getName(), manifestBytes.length);
+
+        // Parse manifestBytes to check for rebootless update support
+        ApexManifest apexManifest = ApexManifest.parseFrom(manifestBytes);
+
+        LOG.info(
+            "supportsRebootlessUpdate: %s",
+            apexManifest.getSupportsRebootlessUpdate() ? "true" : "false");
+
+        return apexManifest.getSupportsRebootlessUpdate();
+      }
+    } catch (IOException e) {
+      LOG.warn(e, "Failed to extract apex_manifest.pb from %s", apexFile.getName());
+      return false;
+    }
+  }
+
+  private static class IncompatibleAbiException extends InterruptedException {
+    public IncompatibleAbiException(String message) {
+      super(message);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbOptions.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbOptions.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AdbOptions.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android;
+
+import com.facebook.infer.annotation.Nullsafe;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AdbOptions {
+
+  public static final String MULTI_INSTALL_MODE_SHORT_ARG = "-x";
+
+  private String adbExecutablePath;
+  private int adbThreadCount;
+  private int adbServerPort;
+  private boolean multiInstallMode;
+  private boolean stagedInstallMode;
+  private boolean ignoreMissingDevice;
+  private boolean apexMode;
+  private String restartMode;
+  private boolean waitForDeviceReady;
+
+  public AdbOptions(
+      String adbExecutablePath,
+      int adbThreadCount,
+      int adbServerPort,
+      boolean multiInstallMode,
+      boolean stagedInstallMode,
+      boolean ignoreMissingDevice,
+      boolean apexMode,
+      String restartMode,
+      boolean waitForDeviceReady) {
+    this.adbExecutablePath = adbExecutablePath;
+    this.adbThreadCount = adbThreadCount;
+    this.adbServerPort = adbServerPort;
+    this.multiInstallMode = multiInstallMode;
+    this.stagedInstallMode = stagedInstallMode;
+    this.ignoreMissingDevice = ignoreMissingDevice;
+    this.apexMode = apexMode;
+    this.restartMode = restartMode;
+    this.waitForDeviceReady = waitForDeviceReady;
+  }
+
+  public String getAdbExecutablePath() {
+    return adbExecutablePath;
+  }
+
+  public int getAdbThreadCount() {
+    return adbThreadCount;
+  }
+
+  public int getAdbServerPort() {
+    return adbServerPort;
+  }
+
+  public boolean isMultiInstallModeEnabled() {
+    return multiInstallMode;
+  }
+
+  public boolean isStagedInstallModeEnabled() {
+    return stagedInstallMode;
+  }
+
+  public boolean isApexModeEnabled() {
+    return apexMode;
+  }
+
+  public boolean getIgnoreMissingDevice() {
+    return ignoreMissingDevice;
+  }
+
+  public String getRestartMode() {
+    return restartMode;
+  }
+
+  public boolean getWaitForDeviceReady() {
+    return waitForDeviceReady;
+  }
+
+  @Override
+  public String toString() {
+    return "AdbOptions{"
+        + "adbExecutablePath="
+        + adbExecutablePath
+        + ", adbThreadCount="
+        + adbThreadCount
+        + ", adbServerPort="
+        + adbServerPort
+        + ", multiInstallMode="
+        + multiInstallMode
+        + ", stagedInstallMode="
+        + stagedInstallMode
+        + ", ignoreMissingDevice="
+        + ignoreMissingDevice
+        + ", apexMode="
+        + apexMode
+        + ", restartMode="
+        + restartMode
+        + ", waitForDeviceReady="
+        + waitForDeviceReady
+        + '}';
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidInstallPrinter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidInstallPrinter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidInstallPrinter.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android;
+
+import com.facebook.infer.annotation.Nullsafe;
+
+/** Interface for logging android installs in the AdbHelper */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface AndroidInstallPrinter {
+  void printMessage(String message);
+
+  void printSuccess(String message);
+
+  void printWarning(String message);
+
+  void printError(String message);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidManifestReader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidManifestReader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidManifestReader.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.util.List;
+
+/** Allows querying an Android manifest file for various types of information. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface AndroidManifestReader {
+
+  /**
+   * @return list of names (as they appear in the manifest) of activities that should appear in the
+   *     Android app drawer.
+   */
+  List<String> getLauncherActivities();
+
+  /**
+   * @return the value of the package attribute to the manifest element.
+   */
+  String getPackage();
+
+  /**
+   * @return the value of the versionCode attribute to the manifest element.
+   */
+  String getVersionCode();
+
+  /**
+   * @return the name of the instrumentation test runner.
+   */
+  String getInstrumentationTestRunner();
+
+  /**
+   * @return the value of the target package attribute to the manifest element.
+   */
+  String getTargetPackage();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidManifestReaderExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidManifestReaderExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/AndroidManifestReaderExecutableMain.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for executing {@link AndroidManifestReader} calls. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AndroidManifestReaderExecutableMain {
+
+  @Option(name = "--manifest-path", required = true)
+  private String manifestPath;
+
+  @Option(name = "--target-package-output")
+  private @Nullable String targetPackageOutputPath = null;
+
+  @Option(name = "--package-output")
+  private @Nullable String packageOutputPath = null;
+
+  @Option(name = "--instrumentation-test-runner-output")
+  private @Nullable String instrumentationTestRunnerOutputPath = null;
+
+  public static void main(String[] args) throws IOException {
+    AndroidManifestReaderExecutableMain main = new AndroidManifestReaderExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    AndroidManifestReader androidManifestReader =
+        DefaultAndroidManifestReader.forPath(Paths.get(manifestPath));
+
+    if (targetPackageOutputPath != null) {
+      Files.write(
+          Paths.get(targetPackageOutputPath), androidManifestReader.getTargetPackage().getBytes());
+    }
+
+    if (packageOutputPath != null) {
+      Files.write(Paths.get(packageOutputPath), androidManifestReader.getPackage().getBytes());
+    }
+
+    if (instrumentationTestRunnerOutputPath != null) {
+      Files.write(
+          Paths.get(instrumentationTestRunnerOutputPath),
+          androidManifestReader.getInstrumentationTestRunner().getBytes());
+    }
+
+    System.exit(0);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/BUCK
@@ -0,0 +1,119 @@
+load(
+    "@prelude//toolchains/android/tools:build_rules.bzl",
+    "buck_java_binary",
+    "buck_java_library",
+    "buck_kotlin_library",
+)
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+HELPERS_SRCS = [
+    "AdbHelper.java",
+    "AdbOptions.java",
+    "AdbExecutionContext.java",
+    "AndroidInstallPrinter.java",
+    "exopackage/ExoHelper.java",
+    "exopackage/DexExoHelper.java",
+    "exopackage/ExopackageInstaller.java",
+    "exopackage/ExopackageMode.java",
+    "exopackage/ExopackageUtil.java",
+    "exopackage/NativeExoHelper.java",
+    "exopackage/AdbUtils.kt",
+    "exopackage/AndroidDeviceImpl.kt",
+    "exopackage/ResourcesExoHelper.java",
+]
+
+buck_kotlin_library(
+    name = "helpers",
+    srcs = HELPERS_SRCS,
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/android:unit",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/apex:apex_manifest",
+        "prelude//toolchains/android/src/com/facebook/buck/android/device:device",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/installer/android:exceptions",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/src/com/facebook/buck/util:process_executor",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:environment",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        "prelude//toolchains/android/third-party:kotlinx-coroutines-core-jvm",
+        "prelude//toolchains/android/third-party:zstd-jni",
+        ":manifest_utils",
+        ":utils_api",
+    ],
+    exported_deps = [],
+)
+
+MANIFEST_UTILS_SRCS = [
+    "AndroidManifestReader.java",
+    "AndroidManifestReaderExecutableMain.java",
+    "DefaultAndroidManifestReader.java",
+]
+
+buck_java_binary(
+    name = "manifest_utils_binary",
+    main_class = "com.facebook.buck.android.AndroidManifestReaderExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":manifest_utils",
+    ],
+)
+
+buck_java_library(
+    name = "manifest_utils",
+    srcs = MANIFEST_UTILS_SRCS,
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/android:unit",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/util/xml:xml",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
+
+UTILS_API_SRCS = [
+    "exopackage/AndroidDevicesHelper.java",
+    "exopackage/IsolatedExopackageInfo.kt",
+    "exopackage/AndroidDeviceInfo.kt",
+    "exopackage/AndroidDevice.java",
+    "exopackage/AndroidIntent.java",
+    "exopackage/InstallTimings.java",
+    "IsolatedApkInfo.java",
+    "exopackage/PackageInfo.java",
+]
+
+buck_kotlin_library(
+    name = "utils_api",
+    srcs = UTILS_API_SRCS,
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/src/com/facebook/buck/util/xml:xml",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/DefaultAndroidManifestReader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/DefaultAndroidManifestReader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/DefaultAndroidManifestReader.java
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android;
+
+import com.facebook.buck.util.xml.XmlDomParser;
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpression;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class DefaultAndroidManifestReader implements AndroidManifestReader {
+
+  /**
+   * XPath expression to retrieve the names of activities with an intent-filter that gets them to
+   * show up in the launcher.
+   */
+  private static final String XPATH_LAUNCHER_ACTIVITIES =
+      "/manifest/application/*  [self::activity[not(@android:enabled) or @android:enabled='true']"
+          + " or                  self::activity-alias[not(@android:enabled) or"
+          + " @android:enabled='true']] "
+          + " [intent-filter[action/@android:name='android.intent.action.MAIN' and                 "
+          + " category/@android:name='android.intent.category.LAUNCHER']]  /@android:name";
+
+  /**
+   * XPath expression to get the package. For a manifest as {@code <manifest
+   * package="com.facebook.katana" />}, this results in {@code com.facebook.katana}.
+   */
+  private static final String XPATH_PACKAGE = "/manifest/@package";
+
+  /**
+   * XPath expression to get the version code. For a manifest as {@code <manifest
+   * android:versionCode="1" />}, this results in {@code 1}.
+   */
+  private static final String XPATH_VERSION_CODE = "/manifest/@android:versionCode";
+
+  /** XPath expression to get the instrumentation test runner. */
+  private static final String XPATH_INSTRUMENTATION_TEST_RUNNER =
+      "/manifest/instrumentation/@android:name";
+
+  /** XPath expression to get the target package. */
+  private static final String XPATH_TARGET_PACKAGE =
+      "/manifest/instrumentation/@android:targetPackage";
+
+  private final XPathExpression packageExpression;
+  private final XPathExpression versionCodeExpression;
+  private final XPathExpression instrumentationTestRunnerExpression;
+  private final XPathExpression targetPackageExpression;
+  private final XPathExpression launchableActivitiesExpression;
+  private final Document doc;
+
+  private DefaultAndroidManifestReader(InputSource src) throws IOException {
+    try {
+      // Parse the XML.
+      doc = XmlDomParser.parse(src, true);
+
+      // Compile the XPath expressions.
+      XPath xPath = XPathFactory.newInstance().newXPath();
+      xPath.setNamespaceContext(androidNamespaceContext);
+      launchableActivitiesExpression = xPath.compile(XPATH_LAUNCHER_ACTIVITIES);
+      packageExpression = xPath.compile(XPATH_PACKAGE);
+      targetPackageExpression = xPath.compile(XPATH_TARGET_PACKAGE);
+      versionCodeExpression = xPath.compile(XPATH_VERSION_CODE);
+      instrumentationTestRunnerExpression = xPath.compile(XPATH_INSTRUMENTATION_TEST_RUNNER);
+    } catch (XPathExpressionException | SAXException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @Override
+  public List<String> getLauncherActivities() {
+    try {
+      NodeList nodes;
+      nodes =
+          Objects.requireNonNull(
+              (NodeList) launchableActivitiesExpression.evaluate(doc, XPathConstants.NODESET));
+
+      List<String> activities = new ArrayList<>();
+      for (int i = 0; i < nodes.getLength(); i++) {
+        activities.add(Objects.requireNonNull(nodes.item(i)).getTextContent());
+      }
+      return activities;
+
+    } catch (XPathExpressionException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @Override
+  public String getPackage() {
+    try {
+      return Objects.requireNonNull(
+          (String) packageExpression.evaluate(doc, XPathConstants.STRING));
+    } catch (XPathExpressionException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @Override
+  public String getVersionCode() {
+    try {
+      return Objects.requireNonNull(
+          (String) versionCodeExpression.evaluate(doc, XPathConstants.STRING));
+    } catch (XPathExpressionException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @Override
+  public String getInstrumentationTestRunner() {
+    try {
+      return Objects.requireNonNull(
+          (String) instrumentationTestRunnerExpression.evaluate(doc, XPathConstants.STRING));
+    } catch (XPathExpressionException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @Override
+  public String getTargetPackage() {
+    try {
+      return Objects.requireNonNull(
+          (String) targetPackageExpression.evaluate(doc, XPathConstants.STRING));
+    } catch (XPathExpressionException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  /** This allows querying the AndroidManifest for e.g. attributes like android:name using XPath */
+  private static NamespaceContext androidNamespaceContext =
+      new NamespaceContext() {
+        @Override
+        public Iterator<String> getPrefixes(String namespaceURI) {
+          throw new UnsupportedOperationException();
+        }
+
+        @Override
+        public String getPrefix(String namespaceURI) {
+          throw new UnsupportedOperationException();
+        }
+
+        @Override
+        public String getNamespaceURI(String prefix) {
+          if (prefix.equals("android")) {
+            return "http://schemas.android.com/apk/res/android";
+          } else {
+            throw new IllegalArgumentException();
+          }
+        }
+      };
+
+  /**
+   * Parses an XML given via its path and returns an {@link AndroidManifestReader} for it.
+   *
+   * @param path path to an AndroidManifest.xml file
+   * @return an {@code AndroidManifestReader} for {@code path}
+   * @throws IOException
+   */
+  public static AndroidManifestReader forPath(Path path) throws IOException {
+    try (Reader reader = Files.newBufferedReader(path)) {
+      return forReader(reader);
+    }
+  }
+
+  /**
+   * Parses an XML given as a string and returns an {@link AndroidManifestReader} for it.
+   *
+   * @param xmlString a string representation of an XML document
+   * @return an {@code AndroidManifestReader} for the XML document
+   * @throws IOException
+   */
+  public static AndroidManifestReader forString(String xmlString) throws IOException {
+    return forReader(new StringReader(xmlString));
+  }
+
+  private static AndroidManifestReader forReader(Reader reader) throws IOException {
+    return new DefaultAndroidManifestReader(new InputSource(reader));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/IsolatedApkInfo.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/IsolatedApkInfo.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/IsolatedApkInfo.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.infer.annotation.Nullsafe;
+import java.util.Objects;
+import org.jetbrains.annotations.Nullable;
+
+/** Isolated Apk Info. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class IsolatedApkInfo {
+
+  private final AbsPath manifestPath;
+  private final AbsPath apkPath;
+
+  public IsolatedApkInfo(final AbsPath manifestPath, final AbsPath apkPath) {
+    this.manifestPath = manifestPath;
+    this.apkPath = apkPath;
+  }
+
+  /**
+   * @return the path to the AndroidManifest.xml. Note that this file might be a symlink, and might
+   *     not exist at all before this rule has been built.
+   */
+  public AbsPath getManifestPath() {
+    return manifestPath;
+  }
+
+  /**
+   * @return The APK at this path is the final one that points to an APK that a user should install.
+   */
+  public AbsPath getApkPath() {
+    return apkPath;
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(manifestPath, apkPath);
+  }
+
+  @Override
+  public boolean equals(@Nullable Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (obj == null || getClass() != obj.getClass()) {
+      return false;
+    }
+    final IsolatedApkInfo other = (IsolatedApkInfo) obj;
+    return Objects.equals(manifestPath, other.manifestPath)
+        && Objects.equals(apkPath, other.apkPath);
+  }
+
+  public static IsolatedApkInfo of(AbsPath manifestPath, AbsPath apkPath) {
+    return new IsolatedApkInfo(manifestPath, apkPath);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/BUCK
@@ -0,0 +1,134 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "SIGNED_JAR_BLOCKLIST", "buck_java_binary", "buck_java_library", "buck_kotlin_library")
+load("@prelude//toolchains/android/tools/build_rules:fb_native.bzl", "fb_native")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+MERGE_ANDROID_RESOURCE_SOURCES_SRCS = [
+    "MergeAndroidResourceSourcesExecutableMain.java",
+    "MergeAndroidResourceSourcesUtils.java",
+]
+
+MINI_AAPT_SOURCES = [
+    "MiniAapt.java",
+    "MiniAaptExecutableMain.java",
+]
+
+R_DOT_TXT_SOURCES = [
+    "RDotTxtEntry.java",
+    "FakeRDotTxtEntry.java",
+]
+
+buck_java_library(
+    name = "r_dot_txt",
+    srcs = R_DOT_TXT_SOURCES,
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/android/aapt:aapt",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
+
+buck_java_library(
+    name = "mini_aapt",
+    srcs = MINI_AAPT_SOURCES,
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/...",
+        "prelude//toolchains/android/test/com/facebook/buck/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/util:throwing_print_writer",
+        "prelude//toolchains/android/src/com/facebook/buck/util/xml:xml",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        ":r_dot_txt",
+    ],
+)
+
+buck_java_binary(
+    name = "mini_aapt_binary",
+    main_class = "com.facebook.buck.android.aapt.MiniAaptExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":mini_aapt",
+    ],
+)
+
+fb_native.kotlin_library(
+    name = "resource_source_map_format",
+    srcs = ["ResourceSourceMapFormat.kt"],
+    _kotlin_toolchain = "toolchains//:kotlin_bootstrap",
+    provided_deps = [
+        "prelude//toolchains/android/third-party:kotlin-stdlib",
+    ],
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = ["PUBLIC"],
+)
+
+buck_kotlin_library(
+    name = "resource_source_map",
+    srcs = ["ResourceSourceMapExecutableMain.kt"],
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/android/aapt:aapt",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        ":mini_aapt",
+        ":r_dot_txt",
+        ":resource_source_map_format",
+    ],
+)
+
+buck_java_binary(
+    name = "resource_source_map_binary",
+    main_class = "com.facebook.buck.android.aapt.ResourceSourceMapExecutableMain",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":resource_source_map",
+    ],
+)
+
+buck_java_library(
+    name = "merge_android_resource_sources",
+    srcs = MERGE_ANDROID_RESOURCE_SOURCES_SRCS,
+    deps = [
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:layoutlib-api",
+        "prelude//toolchains/android/third-party:tools-sdk-common",
+    ],
+)
+
+buck_java_binary(
+    name = "merge_android_resource_sources_binary",
+    blocklist = SIGNED_JAR_BLOCKLIST,
+    main_class = "com.facebook.buck.android.aapt.MergeAndroidResourceSourcesExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:kotlin-stdlib",
+        ":merge_android_resource_sources",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/FakeRDotTxtEntry.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/FakeRDotTxtEntry.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/FakeRDotTxtEntry.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.aapt;
+
+import com.facebook.infer.annotation.Nullsafe;
+
+/**
+ * An {@link RDotTxtEntry} with fake {@link #idValue}, useful for comparing two resource entries for
+ * equality, since {@link RDotTxtEntry#compareTo(RDotTxtEntry)} ignores the id value.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class FakeRDotTxtEntry extends RDotTxtEntry {
+
+  private static final String FAKE_ID = "0x00000000";
+
+  public FakeRDotTxtEntry(IdType idType, RType type, String name) {
+    super(idType, type, name, FAKE_ID);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MergeAndroidResourceSourcesExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MergeAndroidResourceSourcesExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MergeAndroidResourceSourcesExecutableMain.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.aapt;
+
+import com.android.ide.common.resources.MergingException;
+import com.android.utils.StdLogger;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for executing {@link MergeAndroidResourceSourcesUtils} calls. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class MergeAndroidResourceSourcesExecutableMain {
+
+  @Option(name = "--resource-paths", required = true)
+  private String resourcePathsList;
+
+  @Option(name = "--output", required = true)
+  private Path output;
+
+  public static void main(String[] args) throws IOException {
+    MergeAndroidResourceSourcesExecutableMain main =
+        new MergeAndroidResourceSourcesExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    try {
+      ImmutableList<Path> resPaths =
+          Files.readAllLines(Paths.get(resourcePathsList)).stream()
+              .map(Paths::get)
+              .collect(ImmutableList.toImmutableList());
+      Files.createDirectories(output);
+      MergeAndroidResourceSourcesUtils.mergeResPaths(
+          resPaths,
+          output,
+          Files.createTempDirectory("merge_android_resource_sources_temp"),
+          new StdLogger(StdLogger.Level.WARNING));
+    } catch (MergingException e) {
+      throw new RuntimeException(e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MergeAndroidResourceSourcesUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MergeAndroidResourceSourcesUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MergeAndroidResourceSourcesUtils.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.aapt;
+
+import com.android.ide.common.rendering.api.ResourceNamespace;
+import com.android.ide.common.resources.MergedResourceWriter;
+import com.android.ide.common.resources.MergingException;
+import com.android.ide.common.resources.NoOpResourcePreprocessor;
+import com.android.ide.common.resources.ResourceMerger;
+import com.android.ide.common.resources.ResourcePathEncoding;
+import com.android.ide.common.resources.ResourceSet;
+import com.android.utils.ILogger;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import java.nio.file.Path;
+import java.util.Objects;
+
+/** Merges multiple directories containing Android resource sources into one directory. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+class MergeAndroidResourceSourcesUtils {
+
+  public static void mergeResPaths(
+      ImmutableList<Path> resPaths, Path outFolderPath, Path tmpFolderPath, ILogger logger)
+      throws MergingException {
+    ResourceMerger merger = new ResourceMerger(1);
+    for (Path resPath : resPaths) {
+      ResourceSet set =
+          new ResourceSet(
+              resPath.toString(),
+              Objects.requireNonNull(ResourceNamespace.RES_AUTO),
+              /* libraryName */ null,
+              /* validateEnabled */ true,
+              /* aaptEnv */ null);
+      set.setDontNormalizeQualifiers(true);
+      set.addSource(resPath.toFile());
+      set.loadFromFiles(logger);
+      merger.addDataSet(set);
+    }
+    MergedResourceWriter writer =
+        MergedResourceWriter.createWriterWithoutPngCruncher(
+            outFolderPath.toFile(),
+            null /*publicFile*/,
+            null /*blameLogFolder*/,
+            Objects.requireNonNull(NoOpResourcePreprocessor.INSTANCE),
+            tmpFolderPath.toFile(),
+            "unused_package_name",
+            new ResourcePathEncoding.AbsoluteNotRelocatable("Android Gradle Plugin only feature"));
+    merger.mergeData(writer, /* cleanUp */ false);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MiniAapt.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MiniAapt.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MiniAapt.java
@@ -0,0 +1,619 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.aapt;
+
+import com.facebook.buck.android.aapt.RDotTxtEntry.IdType;
+import com.facebook.buck.android.aapt.RDotTxtEntry.RType;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.file.MorePaths;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.util.xml.XmlDomParser;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpression;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import org.jetbrains.annotations.Nullable;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+/**
+ * Step which parses resources in an android {@code res} directory and compiles them into a {@code
+ * R.txt} file, following the exact same format as the Android build tool {@code aapt}.
+ *
+ * <p>
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class MiniAapt {
+
+  private static final String GRAYSCALE_SUFFIX = "_g.png";
+
+  // Ignore .orig files that Mercurial creates
+  public static final ImmutableList<String> IGNORED_FILE_EXTENSIONS =
+      ImmutableList.of("orig", "scc");
+
+  private static final String ID_DEFINITION_PREFIX = "@+id/";
+  private static final String ITEM_TAG = "item";
+  private static final String OVERLAYABLE_TAG = "overlayable";
+  private static final String PUBLIC_TAG = "public";
+  private static final String PUBLIC_FILENAME = "public.xml";
+
+  private static final XPathExpression ANDROID_ID_AND_ATTR_USAGE =
+      createExpression(
+          "//@*[(starts-with(., '@') and "
+              + "not(starts-with(., '@+')) and "
+              + "not(starts-with(., '@android:')) and "
+              + "not(starts-with(., '@null'))) or "
+              + "starts-with(., '?attr')]");
+
+  private static final XPathExpression ANDROID_ATTR_USAGE_FOR_STYLES =
+      createExpression(
+          "//item/@name[not(starts-with(., 'android'))] | //item[@name]/text()[starts-with(.,"
+              + " '?attr')]");
+
+  private static final XPathExpression ANDROID_ID_DEFINITION =
+      createExpression("//@*[starts-with(., '@+') and " + "not(starts-with(., '@+android:id'))]");
+
+  private static final ImmutableMap<String, RType> RESOURCE_TYPES = getResourceTypes();
+
+  /**
+   * {@code <overlayable>} is for configuring the policies around what resources are overlayable.
+   * Since these policies are not included into R.txt we can just skip handling them.
+   *
+   * <p>{@code <public>} is a special type of resource that is not be handled by aapt, but can be
+   * analyzed by Android Lint.
+   *
+   * @see <a href="https://source.android.com/docs/core/runtime/rros">RRO Documentation</a>
+   * @see <a
+   *     href="https://developer.android.com/studio/projects/android-library#PrivateResources">Private
+   *     resources</a>
+   */
+  private static final ImmutableSet<String> IGNORED_TAGS =
+      ImmutableSet.of("eat-comment", "skip", OVERLAYABLE_TAG, PUBLIC_TAG);
+
+  // aapt, unless specified a pattern, ignores certain files and directories. We follow the same
+  // logic as the default pattern found at http://goo.gl/OTTK88 and line 61.
+  public static boolean isSilentlyIgnored(Path path) {
+    String fileName = Objects.requireNonNull(path.getFileName()).toString();
+    return ".gitkeep".equalsIgnoreCase(fileName)
+        || ".svn".equalsIgnoreCase(fileName)
+        || ".git".equalsIgnoreCase(fileName)
+        || ".ds_store".equalsIgnoreCase(fileName)
+        || "cvs".equalsIgnoreCase(fileName)
+        || "thumbs.db".equalsIgnoreCase(fileName)
+        || "picasa.ini".equalsIgnoreCase(fileName)
+        || fileName.endsWith("~");
+  }
+
+  private final ImmutableSet<Path> pathsToSymbolsOfDeps;
+  private final RDotTxtResourceCollector resourceCollector;
+
+  public MiniAapt(ImmutableSet<Path> pathsToSymbolsOfDeps) {
+    this.pathsToSymbolsOfDeps = pathsToSymbolsOfDeps;
+    this.resourceCollector = new RDotTxtResourceCollector();
+  }
+
+  private static XPathExpression createExpression(String expressionStr) {
+    try {
+      return XPathFactory.newInstance().newXPath().compile(expressionStr);
+    } catch (XPathExpressionException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static ImmutableMap<String, RType> getResourceTypes() {
+    ImmutableMap.Builder<String, RType> types = ImmutableMap.builder();
+    for (RType rType : RType.values()) {
+      types.put(rType.toString(), rType);
+    }
+    types.put("string-array", RType.ARRAY);
+    types.put("integer-array", RType.ARRAY);
+    types.put("declare-styleable", RType.STYLEABLE);
+    return types.build();
+  }
+
+  public RDotTxtResourceCollector getResourceCollector() {
+    return resourceCollector;
+  }
+
+  /** Recursively gets all resources files under a given directory */
+  public static ImmutableMap<Path, Path> getAllResourceFiles(
+      AbsPath root, RelPath resourceDirectory) throws IOException {
+    return ProjectFilesystemUtils.getFilesUnderPath(
+            root,
+            resourceDirectory.getPath(),
+            ProjectFilesystemUtils.getDefaultVisitOptions(),
+            ProjectFilesystemUtils.getEmptyIgnoreFilter())
+        .stream()
+        .collect(
+            ImmutableMap.toImmutableMap(
+                path -> MorePaths.relativize(resourceDirectory.getPath(), path),
+                path -> ProjectFilesystemUtils.getPathForRelativePath(root, path)));
+  }
+
+  public ImmutableSet<RDotTxtEntry> processAllFiles(ImmutableMap<Path, Path> files)
+      throws IOException, ResourceParseException, XPathExpressionException {
+    ImmutableSet.Builder<RDotTxtEntry> references = ImmutableSet.builder();
+    for (Map.Entry<Path, Path> entry : files.entrySet()) {
+      Path relativePath = entry.getKey();
+      Path fullPath = entry.getValue();
+      if (shouldIgnoreFile(fullPath)) {
+        continue;
+      }
+
+      String dirName = relativePath.getName(0).toString();
+      if (dirName.equals(relativePath.toString())) {
+        // File in root directory, ignore
+        continue;
+      }
+      if (dirName.startsWith("values")) {
+        if (!isAValuesDir(dirName)) {
+          throw new ResourceParseException("'%s' is not a valid values directory.", dirName);
+        }
+        processValuesFile(fullPath);
+      } else {
+        processNonValuesFile(fullPath, dirName);
+        if (fullPath.endsWith("styles.xml")) {
+          processStyleFile(fullPath, references);
+        } else if (fullPath.toString().endsWith(".xml")) {
+          processXmlFile(fullPath, references);
+        }
+      }
+    }
+
+    return references.build();
+  }
+
+  /**
+   * Collects file names under the {@code res} directory, except those under directories starting
+   * with {@code values}, as resources based on their parent directory.
+   *
+   * <p>So for instance, if the directory structure is something like:
+   *
+   * <pre>
+   *   res/
+   *       values/ ...
+   *       values-es/ ...
+   *       drawable/
+   *                image.png
+   *                nine_patch.9.png
+   *       layout/
+   *              my_view.xml
+   *              another_view.xml
+   * </pre>
+   *
+   * the resulting resources would contain:
+   *
+   * <ul>
+   *   <li>R.drawable.image
+   *   <li>R.drawable.nine_patch
+   *   <li>R.layout.my_view
+   *   <li>R.layout.another_view
+   * </ul>
+   */
+  void processNonValuesFile(Path fullPath, String dirName)
+      throws IOException, ResourceParseException {
+    String filename = Objects.requireNonNull(fullPath.getFileName()).toString();
+
+    int dotIndex = filename.indexOf('.');
+    String resourceName = dotIndex != -1 ? filename.substring(0, dotIndex) : filename;
+
+    int dashIndex = dirName.indexOf('-');
+    String standardizedDirName = dashIndex == -1 ? dirName : dirName.substring(0, dashIndex);
+    if (!RESOURCE_TYPES.containsKey(standardizedDirName)) {
+      throw new ResourceParseException(
+          "'%s' is not a valid resource sub-directory.", standardizedDirName);
+    }
+
+    RType rType = Objects.requireNonNull(RESOURCE_TYPES.get(standardizedDirName));
+    if (rType == RType.DRAWABLE) {
+      processDrawables(fullPath);
+    } else {
+      resourceCollector.addIntResourceIfNotPresent(rType, resourceName);
+    }
+  }
+
+  void processDrawables(Path resourceFile) throws IOException, ResourceParseException {
+    String filename = Objects.requireNonNull(resourceFile.getFileName()).toString();
+    int dotIndex = filename.indexOf('.');
+    String resourceName = dotIndex != -1 ? filename.substring(0, dotIndex) : filename;
+
+    // .g.png is no longer an allowed filename in newer versions of aapt2, hence the two spellings.
+    if (!filename.endsWith(".xml")
+        && (filename.endsWith(".g.png") || filename.endsWith(GRAYSCALE_SUFFIX))) {
+      // Trim _g or .g from the resource name
+      resourceName = filename.substring(0, filename.length() - GRAYSCALE_SUFFIX.length());
+    }
+
+    resourceCollector.addIntResourceIfNotPresent(RType.DRAWABLE, resourceName);
+  }
+
+  /**
+   * Processes an {@code xml} file immediately under a {@code values} directory. See <a
+   * href="http://developer.android.com/guide/topics/resources/more-resources.html>More Resource
+   * Types</a> to find out more about how resources are defined.
+   *
+   * <p>For an input file with contents like:
+   *
+   * <pre>
+   *   <?xml version="1.0" encoding="utf-8"?>
+   *   <resources>
+   *     <integer name="number">42</integer>
+   *     <dimen name="dimension">10px</dimen>
+   *     <string name="hello">World</string>
+   *     <item name="my_fraction" type="fraction">1.5</item>
+   *   </resources>
+   * </pre>
+   *
+   * the resulting resources would be:
+   *
+   * <ul>
+   *   <li>R.integer.number
+   *   <li>R.dimen.dimension
+   *   <li>R.string.hello
+   *   <li>R.fraction.my_fraction
+   * </ul>
+   */
+  @VisibleForTesting
+  void processValuesFile(Path valuesFile) throws IOException, ResourceParseException {
+    try (InputStream stream = new BufferedInputStream(Files.newInputStream(valuesFile))) {
+      Document dom = parseXml(valuesFile, stream);
+      Element root = Objects.requireNonNull(dom.getDocumentElement());
+
+      // Exclude resources annotated with the attribute {@code exclude-from-resource-map}.
+      // This is useful to exclude using generated strings to build the
+      // resource map, which ensures a build break will show up at build time
+      // rather than being hidden until generated resources are updated.
+      if (root.getAttribute("exclude-from-buck-resource-map").equals("true")) {
+        return;
+      }
+
+      for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) {
+        if (node.getNodeType() != Node.ELEMENT_NODE) {
+          continue;
+        }
+
+        String resourceType = node.getNodeName();
+        if (resourceType.equals(ITEM_TAG)) {
+          Node typeNode = verifyNodeHasTypeAttribute(valuesFile, node);
+          resourceType = Objects.requireNonNull(typeNode.getNodeValue());
+        } else if (resourceType.equals(PUBLIC_TAG)) {
+          Node nameAttribute = Objects.requireNonNull(node.getAttributes()).getNamedItem("name");
+          if (nameAttribute == null
+              || Objects.requireNonNull(nameAttribute.getNodeValue()).isEmpty()) {
+            throw new ResourceParseException(
+                "Error parsing file '%s', expected a 'name' attribute in \n'%s'\n",
+                Objects.requireNonNull(valuesFile.getFileName()), node.toString());
+          }
+          String type =
+              Objects.requireNonNull(verifyNodeHasTypeAttribute(valuesFile, node).getNodeValue());
+
+          if (!RESOURCE_TYPES.containsKey(type)) {
+            throw new ResourceParseException(
+                "Invalid resource type '%s' in <public> resource '%s' in file '%s'.",
+                type,
+                nameAttribute.getNodeValue(),
+                Objects.requireNonNull(valuesFile.getFileName()));
+          }
+
+          if (!PUBLIC_FILENAME.equals(
+              Objects.requireNonNull(valuesFile.getFileName()).toString())) {
+            throw new ResourceParseException(
+                "<public> resource '%s' must be declared in res/values/public.xml, but was declared"
+                    + " in '%s'",
+                nameAttribute.getNodeValue(), Objects.requireNonNull(valuesFile.getFileName()));
+          }
+        }
+
+        if (IGNORED_TAGS.contains(resourceType)) {
+          continue;
+        }
+
+        if (!RESOURCE_TYPES.containsKey(resourceType)) {
+          throw new ResourceParseException(
+              "Invalid resource type '<%s>' in '%s'.", resourceType, valuesFile);
+        }
+
+        RType rType = Objects.requireNonNull(RESOURCE_TYPES.get(resourceType));
+        addToResourceCollector(node, rType);
+      }
+    }
+  }
+
+  private Node verifyNodeHasTypeAttribute(Path valuesFile, Node node)
+      throws ResourceParseException {
+    Node typeNode = Objects.requireNonNull(node.getAttributes()).getNamedItem("type");
+    if (typeNode == null || Objects.requireNonNull(typeNode.getNodeValue()).isEmpty()) {
+      throw new ResourceParseException(
+          "Error parsing file '%s', expected a 'type' attribute in: \n'%s'\n",
+          Objects.requireNonNull(valuesFile.getFileName()), node.toString());
+    }
+    return typeNode;
+  }
+
+  private void addToResourceCollector(Node node, RType rType) throws ResourceParseException {
+    String resourceName = sanitizeName(extractNameAttribute(node));
+
+    if (rType.equals(RType.STYLEABLE)) {
+      int count = 0;
+      for (Node attrNode = node.getFirstChild();
+          attrNode != null;
+          attrNode = attrNode.getNextSibling()) {
+        if (attrNode.getNodeType() != Node.ELEMENT_NODE || !attrNode.getNodeName().equals("attr")) {
+          continue;
+        }
+
+        String rawAttrName = extractNameAttribute(attrNode);
+        String attrName = sanitizeName(rawAttrName);
+        resourceCollector.addResource(
+            RType.STYLEABLE,
+            IdType.INT,
+            String.format("%s_%s", resourceName, attrName),
+            Integer.toString(count++),
+            resourceName);
+
+        if (!rawAttrName.startsWith("android:")) {
+          resourceCollector.addIntResourceIfNotPresent(RType.ATTR, attrName);
+        }
+      }
+
+      resourceCollector.addIntArrayResourceIfNotPresent(rType, resourceName, count);
+    } else {
+      resourceCollector.addIntResourceIfNotPresent(rType, resourceName);
+    }
+  }
+
+  @VisibleForTesting
+  void processStyleFile(Path xmlFile, ImmutableSet.Builder<RDotTxtEntry> references)
+      throws IOException, XPathExpressionException, ResourceParseException {
+    try (InputStream stream = new BufferedInputStream(Files.newInputStream(xmlFile))) {
+      Document dom = parseXml(xmlFile, stream);
+
+      XPathExpression expression = ANDROID_ATTR_USAGE_FOR_STYLES;
+      NodeList nodesUsingIds =
+          (NodeList)
+              Objects.requireNonNull(
+                  expression.evaluate(dom, Objects.requireNonNull(XPathConstants.NODESET)));
+      for (int i = 0; i < nodesUsingIds.getLength(); i++) {
+        String resourceName =
+            Objects.requireNonNull(Objects.requireNonNull(nodesUsingIds.item(i)).getNodeValue());
+        if (resourceName.startsWith("?attr")) {
+          resourceName = resourceName.substring("?attr/".length());
+        } else {
+          int colonPosition = resourceName.indexOf(":");
+          if (colonPosition > 0) {
+            resourceName = resourceName.substring(colonPosition + 1);
+          }
+        }
+        references.add(new FakeRDotTxtEntry(IdType.INT, RType.ATTR, sanitizeName(resourceName)));
+      }
+    }
+  }
+
+  @VisibleForTesting
+  void processXmlFile(Path xmlFile, ImmutableSet.Builder<RDotTxtEntry> references)
+      throws IOException, XPathExpressionException, ResourceParseException {
+    try (InputStream stream = new BufferedInputStream(Files.newInputStream(xmlFile))) {
+      Document dom = parseXml(xmlFile, stream);
+      NodeList nodesWithIds =
+          (NodeList)
+              Objects.requireNonNull(
+                  ANDROID_ID_DEFINITION.evaluate(
+                      dom, Objects.requireNonNull(XPathConstants.NODESET)));
+      for (int i = 0; i < nodesWithIds.getLength(); i++) {
+        String resourceName =
+            Objects.requireNonNull(Objects.requireNonNull(nodesWithIds.item(i)).getNodeValue());
+        if (!resourceName.startsWith(ID_DEFINITION_PREFIX)) {
+          throw new ResourceParseException("Invalid definition of a resource: '%s'", resourceName);
+        }
+        Preconditions.checkState(resourceName.startsWith(ID_DEFINITION_PREFIX));
+        resourceCollector.addIntResourceIfNotPresent(
+            RType.ID, resourceName.substring(ID_DEFINITION_PREFIX.length()));
+      }
+
+      NodeList nodesUsingIds =
+          (NodeList)
+              Objects.requireNonNull(
+                  ANDROID_ID_AND_ATTR_USAGE.evaluate(
+                      dom, Objects.requireNonNull(XPathConstants.NODESET)));
+      for (int i = 0; i < nodesUsingIds.getLength(); i++) {
+        String resourceName =
+            Objects.requireNonNull(Objects.requireNonNull(nodesUsingIds.item(i)).getNodeValue());
+        int slashPosition = resourceName.indexOf('/');
+        if ((resourceName.charAt(0) != '@' && resourceName.charAt(0) != '?')
+            || slashPosition == -1) {
+          throw new ResourceParseException("Invalid definition of a resource: '%s'", resourceName);
+        }
+
+        String rawRType = resourceName.substring(1, slashPosition);
+        String name = resourceName.substring(slashPosition + 1);
+
+        String nodeName = Objects.requireNonNull(nodesUsingIds.item(i)).getNodeName();
+        if (name.startsWith("android:") || nodeName.startsWith("tools:")) {
+          continue;
+        }
+        if (!RESOURCE_TYPES.containsKey(rawRType)) {
+          throw new ResourceParseException("Invalid reference '%s' in '%s'", resourceName, xmlFile);
+        }
+        RType rType = Objects.requireNonNull(RESOURCE_TYPES.get(rawRType));
+
+        references.add(new FakeRDotTxtEntry(IdType.INT, rType, sanitizeName(name)));
+      }
+    }
+  }
+
+  private static Document parseXml(Path filepath, InputStream inputStream)
+      throws IOException, ResourceParseException {
+    try {
+      return XmlDomParser.parse(inputStream);
+    } catch (SAXException e) {
+      throw new ResourceParseException("Error parsing xml file '%s': %s.", filepath, e.toString());
+    }
+  }
+
+  private static String extractNameAttribute(Node node) throws ResourceParseException {
+    Node attribute = Objects.requireNonNull(node.getAttributes()).getNamedItem("name");
+    if (attribute == null) {
+      throw new ResourceParseException(
+          "Error: expected a 'name' attribute in node '%s' with value '%s'",
+          node.getNodeName(), node.getTextContent());
+    }
+    return Objects.requireNonNull(attribute.getNodeValue());
+  }
+
+  private static String sanitizeName(String rawName) {
+    return rawName.replaceAll("[.:]", "_");
+  }
+
+  private static boolean isAValuesDir(String dirname) {
+    return dirname.equals("values") || dirname.startsWith("values-");
+  }
+
+  @VisibleForTesting
+  static boolean shouldIgnoreFile(Path path) throws IOException {
+    return Files.isHidden(path)
+        || IGNORED_FILE_EXTENSIONS.contains(
+            com.google.common.io.Files.getFileExtension(
+                Objects.requireNonNull(path.getFileName()).toString()))
+        || isSilentlyIgnored(path);
+  }
+
+  public ImmutableSet<RDotTxtEntry> verifyReferences(ImmutableSet<RDotTxtEntry> references)
+      throws IOException {
+    ImmutableSet.Builder<RDotTxtEntry> unresolved = ImmutableSet.builder();
+    ImmutableSet.Builder<RDotTxtEntry> definitionsBuilder = ImmutableSet.builder();
+    definitionsBuilder.addAll(resourceCollector.getResources());
+    for (Path depRTxt : pathsToSymbolsOfDeps) {
+      Iterable<String> lines =
+          Files.readAllLines(depRTxt).stream()
+              .filter(input -> !Strings.isNullOrEmpty(input))
+              .collect(Collectors.toList());
+      for (String line : lines) {
+        Optional<RDotTxtEntry> entry = RDotTxtEntry.parse(line);
+        Preconditions.checkState(entry.isPresent());
+        definitionsBuilder.add(entry.get());
+      }
+    }
+
+    Set<RDotTxtEntry> definitions = definitionsBuilder.build();
+    for (RDotTxtEntry reference : references) {
+      if (!definitions.contains(reference)) {
+        unresolved.add(reference);
+      }
+    }
+    return unresolved.build();
+  }
+
+  public static class ResourceParseException extends Exception {
+
+    ResourceParseException(String messageFormat, Object... args) {
+      super(String.format(messageFormat, args));
+    }
+  }
+
+  /**
+   * Responsible for collecting resources parsed by {@link MiniAapt} and assigning unique integer
+   * ids to those resources. Resource ids are of the type {@code 0x7fxxyyyy}, where {@code xx}
+   * represents the resource type, and {@code yyyy} represents the id within that resource type.
+   */
+  public static class RDotTxtResourceCollector {
+
+    private int currentTypeId;
+    private final Map<RType, ResourceIdEnumerator> enumerators;
+    private final Set<RDotTxtEntry> resources;
+
+    public RDotTxtResourceCollector() {
+      this.enumerators = new HashMap<>();
+      this.resources = new HashSet<>();
+      this.currentTypeId = 1;
+    }
+
+    public void addIntResourceIfNotPresent(RType rType, String name) {
+      RDotTxtEntry entry = new FakeRDotTxtEntry(IdType.INT, rType, name);
+      if (!resources.contains(entry)) {
+        addResource(rType, IdType.INT, name, getNextIdValue(rType), null);
+      }
+    }
+
+    public void addIntArrayResourceIfNotPresent(RType rType, String name, int numValues) {
+      addResource(rType, IdType.INT_ARRAY, name, getNextArrayIdValue(rType, numValues), null);
+    }
+
+    public void addResource(
+        RType rType, IdType idType, String name, String idValue, @Nullable String parent) {
+      resources.add(new RDotTxtEntry(idType, rType, name, idValue, parent));
+    }
+
+    public Set<RDotTxtEntry> getResources() {
+      return Collections.unmodifiableSet(resources);
+    }
+
+    ResourceIdEnumerator getEnumerator(RType rType) {
+      if (!enumerators.containsKey(rType)) {
+        enumerators.put(rType, new ResourceIdEnumerator(currentTypeId++));
+      }
+      return Objects.requireNonNull(enumerators.get(rType));
+    }
+
+    String getNextIdValue(RType rType) {
+      return String.format("0x%08x", getEnumerator(rType).next());
+    }
+
+    String getNextArrayIdValue(RType rType, int numValues) {
+      // Robolectric expects the array to be populated with the right number of values, irrespective
+      // of what the values are.
+      ImmutableList.Builder<String> values = ImmutableList.builder();
+      for (int id = 0; id < numValues; id++) {
+        values.add(String.format("0x%x", getEnumerator(rType).next()));
+      }
+
+      return String.format(
+          "{ %s }", Joiner.on(RDotTxtEntry.INT_ARRAY_SEPARATOR).join(values.build()));
+    }
+
+    private static class ResourceIdEnumerator {
+
+      private int currentId;
+
+      ResourceIdEnumerator(int typeId) {
+        this.currentId = 0x7f000000 + 0x10000 * typeId + 1;
+      }
+
+      int next() {
+        return currentId++;
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MiniAaptExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MiniAaptExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/MiniAaptExecutableMain.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.aapt;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.util.ThrowingPrintWriter;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.collect.Ordering;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Set;
+import javax.xml.xpath.XPathExpressionException;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for executing {@link MiniAapt} calls. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class MiniAaptExecutableMain {
+
+  @Option(name = "--resource-paths", required = true)
+  private String resourcePathsDir;
+
+  @Option(name = "--dep-symbol-paths", required = true)
+  private String depSymbolsPathsList;
+
+  @Option(name = "--output-path", required = true)
+  private String outputPath;
+
+  public static void main(String[] args) throws IOException {
+    MiniAaptExecutableMain main = new MiniAaptExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    AbsPath root = AbsPath.of(Paths.get(".").normalize().toAbsolutePath());
+    RelPath resourceDirectory = RelPath.get(resourcePathsDir);
+    ImmutableMap<Path, Path> resourcePaths = MiniAapt.getAllResourceFiles(root, resourceDirectory);
+
+    ImmutableSet<Path> depSymbolsFilePaths =
+        Files.readAllLines(Paths.get(depSymbolsPathsList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableSet.toImmutableSet());
+    ImmutableSet<RDotTxtEntry> references;
+
+    MiniAapt miniAapt = new MiniAapt(depSymbolsFilePaths);
+    try {
+      references = miniAapt.processAllFiles(resourcePaths);
+    } catch (MiniAapt.ResourceParseException | XPathExpressionException e) {
+      throw new RuntimeException(e);
+    }
+
+    Set<RDotTxtEntry> missing = miniAapt.verifyReferences(references);
+    if (!missing.isEmpty()) {
+      throw new RuntimeException(
+          String.format(
+              "The following resources were not found: \n%s\n", Joiner.on('\n').join(missing)));
+    }
+
+    try (ThrowingPrintWriter writer = new ThrowingPrintWriter(new FileOutputStream(outputPath))) {
+      Set<RDotTxtEntry> sortedResources =
+          ImmutableSortedSet.copyOf(
+              Ordering.natural(), miniAapt.getResourceCollector().getResources());
+      for (RDotTxtEntry entry : sortedResources) {
+        writer.printf("%s %s %s %s\n", entry.idType, entry.type, entry.name, entry.idValue);
+      }
+    }
+
+    System.exit(0);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/RDotTxtEntry.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/RDotTxtEntry.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/RDotTxtEntry.java
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.aapt;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.MoreObjects;
+import com.google.common.base.Objects;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ComparisonChain;
+import java.util.Optional;
+import java.util.function.Function;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.jetbrains.annotations.Nullable;
+
+/** Represents a row from a symbols file generated by {@code aapt}. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class RDotTxtEntry implements Comparable<RDotTxtEntry> {
+
+  // Taken from http://developer.android.com/reference/android/R.html
+  public enum RType {
+    ANIM,
+    ANIMATOR,
+    ARRAY,
+    ATTR,
+    BOOL,
+    COLOR,
+    DIMEN,
+    DRAWABLE,
+    FRACTION,
+    FONT,
+    ID,
+    INTEGER,
+    INTERPOLATOR,
+    LAYOUT,
+    MENU,
+    NAVIGATION,
+    MIPMAP,
+    PLURALS,
+    RAW,
+    STRING,
+    STYLE,
+    STYLEABLE,
+    TRANSITION,
+    XML;
+
+    @Override
+    public String toString() {
+      return super.toString().toLowerCase();
+    }
+  }
+
+  public enum IdType {
+    INT,
+    INT_ARRAY;
+
+    public static IdType from(String raw) {
+      if (raw.equals("int")) {
+        return INT;
+      } else if (raw.equals("int[]")) {
+        return INT_ARRAY;
+      }
+      throw new IllegalArgumentException(String.format("'%s' is not a valid ID type.", raw));
+    }
+
+    @Override
+    public String toString() {
+      if (this.equals(INT)) {
+        return "int";
+      }
+      return "int[]";
+    }
+  }
+
+  public static final Function<String, RDotTxtEntry> TO_ENTRY =
+      input -> {
+        Optional<RDotTxtEntry> entry = parse(input);
+        Preconditions.checkState(entry.isPresent(), "Could not parse R.txt entry: '%s'", input);
+        return entry.get();
+      };
+
+  public static final String INT_ARRAY_SEPARATOR = ",";
+  // The id group is ".+" rather than "\S+" because an int[] value spans several whitespace-
+  // separated tokens: "int[] styleable MyView { 0x7f020001,0x7f020002 }".
+  private static final Pattern TEXT_SYMBOLS_LINE = Pattern.compile("(\\S+) (\\S+) (\\S+) (.+)");
+
+  // A symbols file may look like:
+  //
+  //    int id placeholder 0x7f020000
+  //    int string debug_http_proxy_dialog_title 0x7f030004
+  //    int string debug_http_proxy_hint 0x7f030005
+  //    int string debug_http_proxy_summary 0x7f030003
+  //    int string debug_http_proxy_title 0x7f030002
+  //    int string debug_ssl_cert_check_summary 0x7f030001
+  //    int string debug_ssl_cert_check_title 0x7f030000
+  //
+  // Note that there are four columns of information:
+  // - the type of the resource id (always seems to be int or int[], in practice)
+  // - the type of the resource
+  // - the name of the resource
+  // - the value of the resource id
+  //
+  // Note that styleable attributes (f.i. "int styleable Anchor_Layout_android_gravity") should be
+  // grouped together based on parent name ("Anchor_Layout" in example above). Since due to
+  // naming flexibility, it is not possible to infer parent name from attribute name. That's why
+  // we decided to introduce optional "parent" field which will keep information about parent, so
+  // later we can properly sort all attributes. At the moment this field only used by IdType#INT
+  // RType#STYLEABLE attributes. To make "compareTo" logic simpler, if parent is "null" - it will be
+  // set to "name" value
+  public final IdType idType;
+  public final RType type;
+  public final String name;
+  public final String idValue;
+  public final String parent;
+
+  public RDotTxtEntry(IdType idType, RType type, String name, String idValue) {
+    this(idType, type, name, idValue, name);
+  }
+
+  public RDotTxtEntry(
+      IdType idType, RType type, String name, String idValue, @Nullable String parent) {
+    this.idType = idType;
+    this.type = type;
+    this.name = name;
+    this.idValue = hexDecimalStringValue(idType, type, idValue);
+    this.parent = parent != null ? parent : name;
+  }
+
+  /*
+   * Convert integer string values to hex decimal string for
+   * non integer arrays and non styleable entries.
+   */
+  private static String hexDecimalStringValue(IdType idType, RType type, String idValue) {
+    if (idType == IdType.INT_ARRAY || type == RType.STYLEABLE) {
+      return idValue;
+    }
+    if (idValue.length() == 0 || idValue.startsWith("0x")) {
+      return idValue;
+    } else {
+      return String.format("0x%08x", Integer.parseInt(idValue));
+    }
+  }
+
+  public RDotTxtEntry copyWithNewIdValue(String newIdValue) {
+    return new RDotTxtEntry(idType, type, name, newIdValue, parent);
+  }
+
+  public RDotTxtEntry copyWithNewParent(String parent) {
+    return new RDotTxtEntry(idType, type, name, idValue, parent);
+  }
+
+  public static Optional<RDotTxtEntry> parse(String rDotTxtLine) {
+    Matcher matcher = TEXT_SYMBOLS_LINE.matcher(rDotTxtLine);
+    if (!matcher.matches()) {
+      return Optional.empty();
+    }
+
+    IdType idType = IdType.from(java.util.Objects.requireNonNull(matcher.group(1)));
+    RType type = RType.valueOf(java.util.Objects.requireNonNull(matcher.group(2)).toUpperCase());
+    String name = java.util.Objects.requireNonNull(matcher.group(3));
+    String idValue = java.util.Objects.requireNonNull(matcher.group(4));
+
+    return Optional.of(new RDotTxtEntry(idType, type, name, idValue));
+  }
+
+  /**
+   * A collection of Resources should be sorted such that Resources of the same type should be
+   * grouped together, and should be alphabetized within that group.
+   */
+  @Override
+  public int compareTo(RDotTxtEntry that) {
+    if (this == that) {
+      return 0;
+    }
+
+    ComparisonChain comparisonChain =
+        ComparisonChain.start()
+            .compare(this.type, that.type)
+            .compare(this.parent, that.parent)
+            .compare(this.name, that.name);
+
+    return comparisonChain.result();
+  }
+
+  @Override
+  public boolean equals(@Nullable Object obj) {
+    if (!(obj instanceof RDotTxtEntry)) {
+      return false;
+    }
+
+    RDotTxtEntry that = (RDotTxtEntry) obj;
+    return Objects.equal(this.type, that.type) && Objects.equal(this.name, that.name);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hashCode(type, name);
+  }
+
+  @Override
+  public String toString() {
+    return MoreObjects.toStringHelper(RDotTxtEntry.class)
+        .add("idType", idType)
+        .add("type", type)
+        .add("name", name)
+        .add("idValue", idValue)
+        .add("parent", parent)
+        .toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/ResourceSourceMapExecutableMain.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/ResourceSourceMapExecutableMain.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/ResourceSourceMapExecutableMain.kt
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.aapt
+
+import com.facebook.buck.android.aapt.RDotTxtEntry.RType
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.io.pathformat.PathFormatter
+import com.google.common.collect.ImmutableMap
+import com.google.common.collect.ImmutableSet
+import java.nio.charset.StandardCharsets
+import java.nio.file.Files
+import java.nio.file.Path
+import java.nio.file.Paths
+import java.util.Locale
+import java.util.TreeSet
+import java.util.concurrent.Callable
+import java.util.concurrent.Executors
+import org.kohsuke.args4j.CmdLineParser
+import org.kohsuke.args4j.Option
+
+/** Builds source provenance for the resources packaged into a Robolectric test. */
+object ResourceSourceMapExecutableMain {
+  private const val MAX_RESOURCE_WORKERS = 8
+
+  @JvmStatic
+  fun main(args: Array<String>) {
+    val fallbackOutput = outputPath(args)
+    try {
+      run(args)
+    } catch (failure: Throwable) {
+      if (failure is VirtualMachineError || failure is ThreadDeath) throw failure
+      System.err.println(
+          "Robolectric resource source-map generation failed; " +
+              "continuing coverage with resource attribution disabled.",
+      )
+      failure.printStackTrace(System.err)
+      val output = fallbackOutput ?: throw failure
+      try {
+        output.parent?.let(Files::createDirectories)
+        Files.writeString(output, "", StandardCharsets.UTF_8)
+      } catch (writeFailure: Throwable) {
+        writeFailure.addSuppressed(failure)
+        throw writeFailure
+      }
+    }
+  }
+
+  private fun run(args: Array<String>) {
+    val options = Options()
+    CmdLineParser(options).parseArgument(*args)
+    generate(options.resourceDirs, options.assetDirs, options.output)
+  }
+
+  private fun outputPath(args: Array<String>): Path? {
+    val index = args.indexOf("--output")
+    if (index >= 0 && index + 1 < args.size) return Paths.get(args[index + 1])
+    val inlineValue = args.firstOrNull { it.startsWith("--output=") }?.substringAfter('=')
+    return inlineValue?.takeIf(String::isNotEmpty)?.let(Paths::get)
+  }
+
+  internal fun generate(resourceDirsFile: Path, assetDirsFile: Path, output: Path) {
+    val root = Paths.get(".").toAbsolutePath().normalize()
+    val resourceRoots = readRoots(resourceDirsFile)
+    val assetRoots = readRoots(assetDirsFile)
+    val lines = TreeSet<String>()
+
+    val resourceFiles = resourceRoots.flatMapIndexed { priority, input ->
+      val resourceDir = resolve(root, input.path)
+      filesUnder(resourceDir).mapNotNull { (relative, file) ->
+        if (relative.nameCount < 2) {
+          null
+        } else {
+          ResourceFile(relative, file, input.ownerBuildFile, priority)
+        }
+      }
+    }
+    collectResources(root, resourceFiles, lines)
+    assetRoots.forEachIndexed { priority, input ->
+      collectAssets(root, input, priority, lines)
+    }
+    output.parent?.let(Files::createDirectories)
+    val contents = lines.joinToString(separator = "\n", postfix = if (lines.isEmpty()) "" else "\n")
+    Files.writeString(output, contents, StandardCharsets.UTF_8)
+  }
+
+  private fun readRoots(path: Path): List<InputRoot> =
+      Files.readAllLines(path, StandardCharsets.UTF_8).mapNotNull { line ->
+        if (line.isBlank()) {
+          null
+        } else {
+          val parts = line.split('\t', limit = 2)
+          InputRoot(Paths.get(parts[0]), parts.getOrElse(1) { "" })
+        }
+      }
+
+  private fun collectResources(
+      root: Path,
+      files: List<ResourceFile>,
+      output: MutableSet<String>,
+  ) {
+    val (valuesFiles, otherFiles) =
+        files.partition {
+          val directory = it.relative.getName(0).toString()
+          directory == "values" || directory.startsWith("values-")
+        }
+    // MiniAapt uses shared XPathExpression instances for non-values XML, and XPathExpression is
+    // not thread-safe. Values parsing does not use those expressions, so only values files run in
+    // parallel.
+    val workerCount = minOf(MAX_RESOURCE_WORKERS, Runtime.getRuntime().availableProcessors())
+    if (valuesFiles.size > 1 && workerCount > 1) {
+      val executor = Executors.newFixedThreadPool(workerCount)
+      try {
+        executor
+            .invokeAll(valuesFiles.map { file -> Callable { resourceLinesOrEmpty(root, file) } })
+            .forEach { output.addAll(it.get()) }
+      } finally {
+        executor.shutdownNow()
+      }
+    } else {
+      valuesFiles.forEach { output.addAll(resourceLinesOrEmpty(root, it)) }
+    }
+    otherFiles.forEach { output.addAll(resourceLinesOrEmpty(root, it)) }
+  }
+
+  private fun resourceLinesOrEmpty(root: Path, file: ResourceFile): List<String> {
+    try {
+      return resourceLines(root, file)
+    } catch (failure: Throwable) {
+      if (failure is VirtualMachineError || failure is ThreadDeath) throw failure
+      System.err.println(
+          "Failed to map Robolectric resource file ${file.path}; skipping this file.",
+      )
+      failure.printStackTrace(System.err)
+      return emptyList()
+    }
+  }
+
+  private fun resourceLines(root: Path, file: ResourceFile): List<String> {
+    val miniAapt = MiniAapt(ImmutableSet.of())
+    miniAapt.processAllFiles(ImmutableMap.of(file.relative, file.path))
+    val source = sourcePath(root, file.path, file.ownerBuildFile)
+    val qualifiers = qualifiers(file.relative.getName(0).toString())
+    return miniAapt.resourceCollector.resources.mapNotNull { entry ->
+      // Styleables are generated arrays and indices, not runtime resource-table entries. MiniAapt
+      // emits their underlying attributes separately as R.attr entries.
+      if (entry.type == RType.STYLEABLE) {
+        null
+      } else {
+        ResourceSourceMapFormat.ResourceRow(
+                file.priority,
+                entry.type.name.lowercase(Locale.ROOT),
+                entry.name,
+                qualifiers,
+                source,
+                file.ownerBuildFile,
+            )
+            .serialize()
+      }
+    }
+  }
+
+  private fun collectAssets(
+      root: Path,
+      input: InputRoot,
+      priority: Int,
+      output: MutableSet<String>,
+  ) {
+    val assetDir = resolve(root, input.path)
+    val assetFiles =
+        try {
+          filesUnder(assetDir)
+        } catch (failure: Throwable) {
+          if (failure is VirtualMachineError || failure is ThreadDeath) throw failure
+          System.err.println(
+              "Failed to enumerate Robolectric asset directory $assetDir; skipping this directory.",
+          )
+          failure.printStackTrace(System.err)
+          return
+        }
+    for ((relative, file) in assetFiles) {
+      try {
+        output.add(
+            ResourceSourceMapFormat.AssetRow(
+                    priority,
+                    PathFormatter.pathWithUnixSeparators(relative),
+                    sourcePath(root, file, input.ownerBuildFile),
+                    input.ownerBuildFile,
+                )
+                .serialize(),
+        )
+      } catch (failure: Throwable) {
+        if (failure is VirtualMachineError || failure is ThreadDeath) throw failure
+        System.err.println(
+            "Failed to map Robolectric asset file $file; skipping this file.",
+        )
+        failure.printStackTrace(System.err)
+      }
+    }
+  }
+
+  private fun filesUnder(directory: Path): List<Map.Entry<Path, Path>> =
+      MiniAapt.getAllResourceFiles(AbsPath.of(directory), RelPath.get("")).entries.sortedBy {
+        PathFormatter.pathWithUnixSeparators(it.key)
+      }
+
+  private fun resolve(root: Path, path: Path): Path =
+      if (path.isAbsolute) path.normalize() else root.resolve(path).normalize()
+
+  private fun sourcePath(root: Path, path: Path, ownerBuildFile: String): String {
+    val realPath = path.toRealPath()
+    if (realPath.startsWith(root)) {
+      val relative = PathFormatter.pathWithUnixSeparators(root.relativize(realPath))
+      if (!relative.startsWith("buck-out/")) return relative
+    }
+    return ownerBuildFile
+  }
+
+  private fun qualifiers(resourceDirectory: String): String =
+      resourceDirectory.substringAfter('-', missingDelimiterValue = "")
+
+  private data class InputRoot(val path: Path, val ownerBuildFile: String)
+
+  private data class ResourceFile(
+      val relative: Path,
+      val path: Path,
+      val ownerBuildFile: String,
+      val priority: Int,
+  )
+
+  private class Options {
+    @field:Option(name = "--resource-dirs", required = true) lateinit var resourceDirs: Path
+
+    @field:Option(name = "--asset-dirs", required = true) lateinit var assetDirs: Path
+
+    @field:Option(name = "--output", required = true) lateinit var output: Path
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/ResourceSourceMapFormat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/ResourceSourceMapFormat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aapt/ResourceSourceMapFormat.kt
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.aapt
+
+import java.nio.charset.StandardCharsets
+import java.util.Base64
+
+/** Serialization contract for Robolectric resource source-map rows. */
+object ResourceSourceMapFormat {
+  private const val DELIMITER = '\t'
+  private val fieldEncoder = Base64.getUrlEncoder().withoutPadding()
+  private val fieldDecoder = Base64.getUrlDecoder()
+
+  interface Row {
+    fun serialize(): String
+  }
+
+  /** Format: `R\tpriority\ttype\tname\tqualifiers\tsource\townerBuildFile`. */
+  data class ResourceRow(
+      val priority: Int,
+      val type: String,
+      val name: String,
+      val qualifiers: String,
+      val source: String,
+      val ownerBuildFile: String,
+  ) : Row {
+    override fun serialize(): String =
+        listOf(TAG, priority.toString(), type, name, qualifiers, source, ownerBuildFile)
+            .joinToString(DELIMITER.toString())
+
+    companion object {
+      private const val TAG = "R"
+
+      private enum class Attribute {
+        TAG,
+        PRIORITY,
+        TYPE,
+        NAME,
+        QUALIFIERS,
+        SOURCE,
+        OWNER_BUILD_FILE,
+      }
+
+      internal fun parse(fields: List<String>): ResourceRow? {
+        if (fields.size != Attribute.entries.size || fields[Attribute.TAG.ordinal] != TAG)
+            return null
+        return ResourceRow(
+            fields[Attribute.PRIORITY.ordinal].toIntOrNull() ?: return null,
+            fields[Attribute.TYPE.ordinal],
+            fields[Attribute.NAME.ordinal],
+            fields[Attribute.QUALIFIERS.ordinal],
+            fields[Attribute.SOURCE.ordinal],
+            fields[Attribute.OWNER_BUILD_FILE.ordinal],
+        )
+      }
+    }
+  }
+
+  /** Format: `A\tpriority\tencodedPath\tencodedSource\tencodedOwnerBuildFile`. */
+  data class AssetRow(
+      val priority: Int,
+      val path: String,
+      val source: String,
+      val ownerBuildFile: String,
+  ) : Row {
+    override fun serialize(): String = listOf(
+        TAG,
+        priority.toString(),
+        encodeField(path),
+        encodeField(source),
+        encodeField(ownerBuildFile),
+    )
+        .joinToString(DELIMITER.toString())
+
+    companion object {
+      private const val TAG = "A"
+
+      private enum class Attribute {
+        TAG,
+        PRIORITY,
+        PATH,
+        SOURCE,
+        OWNER_BUILD_FILE,
+      }
+
+      internal fun parse(fields: List<String>): AssetRow? {
+        if (fields.size != Attribute.entries.size || fields[Attribute.TAG.ordinal] != TAG)
+            return null
+        return try {
+          AssetRow(
+              fields[Attribute.PRIORITY.ordinal].toIntOrNull() ?: return null,
+              decodeField(fields[Attribute.PATH.ordinal]),
+              decodeField(fields[Attribute.SOURCE.ordinal]),
+              decodeField(fields[Attribute.OWNER_BUILD_FILE.ordinal]),
+          )
+        } catch (_: IllegalArgumentException) {
+          null
+        }
+      }
+    }
+  }
+
+  fun parse(line: String): Row? {
+    val fields = line.split(DELIMITER)
+    return ResourceRow.parse(fields) ?: AssetRow.parse(fields)
+  }
+
+  fun encodeField(value: String): String =
+      fieldEncoder.encodeToString(value.toByteArray(StandardCharsets.UTF_8))
+
+  fun decodeField(value: String): String =
+      String(fieldDecoder.decode(value), StandardCharsets.UTF_8)
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aar/AarBuilderExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aar/AarBuilderExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aar/AarBuilderExecutableMain.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.aar;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.util.relativepathmap.RelativePathMapUtils;
+import com.facebook.buck.util.zip.collect.OnDuplicateEntry;
+import com.facebook.buck.util.zip.collect.ZipEntrySourceCollectionBuilder;
+import com.facebook.buck.util.zip.collect.ZipEntrySourceCollectionWriter;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AarBuilderExecutableMain {
+  private static final AbsPath CURRENT_DIRECTORY =
+      AbsPath.of(Paths.get(".").normalize().toAbsolutePath());
+
+  @Option(name = "--output_path", required = true)
+  private Path outputPath;
+
+  @Option(name = "--on_duplicate_entry", required = true)
+  private OnDuplicateEntry onDuplicateEntry;
+
+  @Option(name = "--entries_file", required = true)
+  private Path entriesFile;
+
+  @Option(name = "--hardcode_permissions_for_deterministic_output")
+  private boolean hardcodePermissionsForDeterministicOutput;
+
+  @Option(name = "--native_libs_file", required = true)
+  private Path nativeLibsFile;
+
+  @Option(name = "--native_libs_assets_file", required = true)
+  private Path nativeLibsAssetsFile;
+
+  @Option(name = "--proguard_config_file", required = false)
+  @Nullable
+  private Path proguardConfigFile;
+
+  public static void main(String[] args) throws IOException {
+    AarBuilderExecutableMain main = new AarBuilderExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    ZipEntrySourceCollectionBuilder builder =
+        new ZipEntrySourceCollectionBuilder(ImmutableSet.of(), onDuplicateEntry);
+
+    Map<Path, AbsPath> entriesMap = new LinkedHashMap<>();
+    for (String entry : Files.readAllLines(entriesFile)) {
+      AbsPath zipEntryAbsPath = CURRENT_DIRECTORY.resolve(entry);
+      RelativePathMapUtils.addPathToRelativePathMap(
+          CURRENT_DIRECTORY,
+          entriesMap,
+          Objects.requireNonNull(zipEntryAbsPath.getPath().getParent()),
+          zipEntryAbsPath,
+          zipEntryAbsPath.getFileName());
+    }
+
+    for (Map.Entry<Path, AbsPath> pathEntry : entriesMap.entrySet()) {
+      String entryName = pathEntry.getKey().toString();
+      builder.addFile(entryName, pathEntry.getValue().getPath());
+    }
+
+    // We resolve native libs relative to themselves, and then put them into the
+    // "jni" folder.
+    Map<Path, AbsPath> nativeLibsMap = new LinkedHashMap<>();
+    for (String nativeLibsEntry : Files.readAllLines(nativeLibsFile)) {
+      AbsPath zipEntryAbsPath = CURRENT_DIRECTORY.resolve(nativeLibsEntry);
+      RelativePathMapUtils.addPathToRelativePathMap(
+          CURRENT_DIRECTORY,
+          nativeLibsMap,
+          zipEntryAbsPath.getPath(),
+          zipEntryAbsPath,
+          zipEntryAbsPath.getFileName());
+    }
+
+    Path jniPath = Paths.get("jni");
+    for (Map.Entry<Path, AbsPath> pathEntry : nativeLibsMap.entrySet()) {
+      String entryName = jniPath.resolve(pathEntry.getKey()).toString();
+      builder.addFile(entryName, pathEntry.getValue().getPath());
+    }
+
+    // Native lib assets are resolved relative to themselves, and we throw away
+    // the metadata.txt files.
+    Map<Path, AbsPath> nativeLibsAssetsEntriesMap = new LinkedHashMap<>();
+    for (String entry : Files.readAllLines(nativeLibsAssetsFile)) {
+      AbsPath zipEntryAbsPath = CURRENT_DIRECTORY.resolve(entry);
+      RelativePathMapUtils.addPathToRelativePathMap(
+          CURRENT_DIRECTORY,
+          nativeLibsAssetsEntriesMap,
+          zipEntryAbsPath.getPath(),
+          zipEntryAbsPath,
+          zipEntryAbsPath.getFileName());
+    }
+
+    for (Map.Entry<Path, AbsPath> pathEntry : nativeLibsAssetsEntriesMap.entrySet()) {
+      if (Objects.requireNonNull(pathEntry.getKey().getFileName())
+          .toString()
+          .equals("metadata.txt")) {
+        continue;
+      }
+
+      String entryName = pathEntry.getKey().toString();
+      builder.addFile(entryName, pathEntry.getValue().getPath());
+    }
+
+    if (proguardConfigFile != null) {
+      builder.addFile("proguard.txt", proguardConfigFile);
+    }
+
+    new ZipEntrySourceCollectionWriter(CURRENT_DIRECTORY, hardcodePermissionsForDeterministicOutput)
+        .copyToZip(builder.build(), outputPath);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aar/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aar/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/aar/BUCK
@@ -0,0 +1,31 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "aar_builder",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/features/zip/rules/utils:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/util/relativepathmap:relativepathmap",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip/collect:collect",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
+
+buck_java_binary(
+    name = "aar_builder_binary",
+    main_class = "com.facebook.buck.android.aar.AarBuilderExecutableMain",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":aar_builder",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apex/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apex/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apex/BUCK
@@ -0,0 +1,20 @@
+load("@prelude//toolchains/android/tools:protobuf.bzl", "protobuf_src_gen")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("product_os_devx")
+
+source_listing()
+
+protobuf_src_gen(
+    name = "apex_manifest",
+    srcs = [
+        "apex_manifest.proto",
+    ],
+    proto_path = [],
+    deps = [
+        "prelude//toolchains/android/third-party:jakarta.annotation-api",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/third-party:protobuf",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apex/apex_manifest.proto b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apex/apex_manifest.proto
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apex/apex_manifest.proto
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * 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.
+ */
+syntax = "proto3";
+package apex.proto;
+option java_package = "com.facebook.buck.android.apex";
+option java_outer_classname = "ApexManifestProto";
+message ApexManifest {
+  // APEX Name. Note that this can be different from what PackageManager sees.
+  // This is used to identify an APEX and to mount under /apex directory.
+  string name = 1;
+  // Version Number
+  int64 version = 2;
+  // Pre Install Hook
+  string preInstallHook = 3;
+  // Post Install Hook
+  // This feature is not supported.
+  string postInstallHook = 4 [ deprecated = true ];
+  // Version Name
+  string versionName = 5;
+  // Signals whenever this APEX doesn't contain any executable code.
+  // If this field is set to true, then apexd will mount this apex
+  // with MS_NOEXEC flag.
+  bool noCode = 6;
+  // List of native libs which can be used by other apexes or system.
+  repeated string provideNativeLibs = 7;
+  // List of native libs which this apex uses from other apexes or system.
+  repeated string requireNativeLibs = 8;
+  // List of JNI libs.
+  // linkerconfig/libnativeloader use this field so that java libraries can
+  // load JNI libraries in the same apex.
+  // This is supposed to be filled by the build system with libraries which are
+  // marked as "is_jni: true" from the list of "native_shared_libs".
+  repeated string jniLibs = 9;
+  // List of libs required that are located in a shared libraries APEX.  The
+  // Android platform only checks whether this list is non-empty, and by default
+  // the Android build system never sets this. This field can be used when
+  // producing or processing an APEX using libraries in /apex/sharedlibs (see
+  // `provideSharedApexLibs` field) to store some information about the
+  // libraries.
+  repeated string requireSharedApexLibs = 10;
+  // Whether this APEX provides libraries to be shared with other APEXs. This
+  // causes libraries contained in the APEX to be made available under
+  // /apex/sharedlibs .
+  bool provideSharedApexLibs = 11;
+  message CompressedApexMetadata {
+    // Valid only for compressed APEX. This field contains the root digest of
+    // the original_apex contained inside CAPEX.
+    string originalApexDigest = 1;
+  }
+  // Exists only for compressed APEX
+  CompressedApexMetadata capexMetadata = 12;
+  // Indicates that this APEX can be updated without rebooting device.
+  bool supportsRebootlessUpdate = 13;
+  // VNDK version for apexes depending on a specific version of VNDK libs.
+  string vndkVersion = 14;
+  // Deprecated.
+  // Whether this vendor APEX needs to be activated in bootstrap phase.
+  // For new APEX, please use `bootstrap` instead.
+  // Vendor APEX become bootstrap APEX if either `vendorBootstrap`
+  // or `bootstrap` is set to true.
+  bool vendorBootstrap = 15 [ deprecated = true ];
+  // Whether this APEX needs to be activated in bootstrap phase.
+  bool bootstrap = 16;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkBuilderExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkBuilderExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkBuilderExecutableMain.java
@@ -0,0 +1,299 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apk;
+
+import com.android.apksig.ApkSigner;
+import com.facebook.buck.android.apk.sdk.ApkCreationException;
+import com.facebook.buck.android.apk.sdk.DuplicateFileException;
+import com.facebook.buck.android.apk.sdk.SealedApkException;
+import com.facebook.buck.android.zipalign.ZipAlign;
+import com.facebook.buck.util.zip.RepackZipEntries;
+import com.facebook.buck.util.zip.ZipCompressionLevel;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.io.MoreFiles;
+import com.google.common.io.RecursiveDeleteOption;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.regex.Pattern;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for executing {@link ApkBuilderUtils} calls. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ApkBuilderExecutableMain {
+  @Option(name = "--output-apk", required = true)
+  private String outputApk;
+
+  @Option(name = "--resource-apk", required = true)
+  private String resourceApk;
+
+  @Option(name = "--dex-file", required = true)
+  private String dexFile;
+
+  @Option(name = "--keystore-path", required = true)
+  private String keystore;
+
+  @Option(name = "--keystore-properties-path", required = true)
+  private String keystoreProperties;
+
+  @Option(name = "--asset-directories-list", required = true)
+  private String assetDirectoriesList;
+
+  @Option(name = "--native-libraries-directories-list", required = true)
+  private String nativeLibrariesDirectoriesList;
+
+  @Option(name = "--zip-files-list", required = true)
+  private String zipFilesList;
+
+  @Option(name = "--jar-files-that-may-contain-resources-list", required = true)
+  private String jarFilesThatMayContainResourcesList;
+
+  @Option(name = "--zipalign_tool", required = true)
+  private String zipalignTool;
+
+  @Option(name = "--compress-resources-dot-arsc")
+  private boolean compressResourcesDotArsc;
+
+  @Option(name = "--package-meta-inf-version-files")
+  private boolean packageMetaInfVersionFiles;
+
+  @Option(name = "--excluded-resources")
+  @Nullable
+  private String excludedResourcesList = null;
+
+  @Option(name = "--uncompressed-files")
+  @Nullable
+  private String uncompressedFilesList = null;
+
+  @Option(name = "--build-info-generator-args")
+  @Nullable
+  private String buildInfoGeneratorArgs = null;
+
+  public static void main(String[] args) throws IOException {
+    ApkBuilderExecutableMain main = new ApkBuilderExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    ImmutableSet<Path> assetDirectories =
+        Files.readAllLines(Paths.get(assetDirectoriesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableSet.toImmutableSet());
+
+    Path buildInfoDir = null;
+    if (buildInfoGeneratorArgs != null) {
+      buildInfoDir = generateBuildInfoAssetDir(buildInfoGeneratorArgs);
+      assetDirectories =
+          ImmutableSet.<Path>builder().addAll(assetDirectories).add(buildInfoDir).build();
+    }
+
+    ImmutableSet<Path> nativeLibraryDirectories =
+        Files.readAllLines(Paths.get(nativeLibrariesDirectoriesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableSet.toImmutableSet());
+
+    ImmutableSet<Path> zipFiles =
+        Files.readAllLines(Paths.get(zipFilesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableSet.toImmutableSet());
+
+    ImmutableSet<Path> jarFilesThatMayContainResources =
+        Files.readAllLines(Paths.get(jarFilesThatMayContainResourcesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableSet.toImmutableSet());
+
+    ImmutableSet<String> excludedResources =
+        excludedResourcesList == null
+            ? ImmutableSet.of()
+            : ImmutableSet.copyOf(Files.readAllLines(Paths.get(excludedResourcesList)));
+
+    ImmutableSet<String> uncompressedFiles =
+        uncompressedFilesList == null
+            ? ImmutableSet.of()
+            : ImmutableSet.copyOf(Files.readAllLines(Paths.get(uncompressedFilesList)));
+
+    Path keystorePath = Paths.get(keystore);
+    Path keystorePropertiesPath = Paths.get(keystoreProperties);
+
+    Path intermediateApk = Files.createTempFile("intermediate", "output.apk");
+    Path zipalignApk = Files.createTempFile("zipalign", "output.apk");
+    KeystoreProperties keystoreProperties =
+        KeystoreProperties.createFromPropertiesFile(keystorePath, keystorePropertiesPath);
+
+    try {
+      ApkBuilderUtils.buildApk(
+          Paths.get(resourceApk),
+          intermediateApk,
+          Paths.get(dexFile),
+          assetDirectories,
+          nativeLibraryDirectories,
+          zipFiles,
+          jarFilesThatMayContainResources,
+          keystorePath,
+          keystoreProperties,
+          packageMetaInfVersionFiles,
+          null,
+          excludedResources);
+
+      if (compressResourcesDotArsc) {
+        Path intermediateApkWithCompressedResources =
+            Files.createTempFile("intermediate", "output_with_compressed_resources.apk");
+        RepackZipEntries.repack(
+            intermediateApk,
+            intermediateApkWithCompressedResources,
+            ImmutableSet.of("resources.arsc"),
+            ZipCompressionLevel.MAX);
+        intermediateApk = intermediateApkWithCompressedResources;
+      }
+
+      if (!uncompressedFiles.isEmpty()) {
+        ImmutableSet<String> expandedUncompressedFiles =
+            expandRegexPatterns(intermediateApk, uncompressedFiles);
+        if (!expandedUncompressedFiles.isEmpty()) {
+          Path intermediateApkWithUncompressedFiles =
+              Files.createTempFile("intermediate", "output_with_uncompressed_files.apk");
+          RepackZipEntries.repack(
+              intermediateApk,
+              intermediateApkWithUncompressedFiles,
+              expandedUncompressedFiles,
+              ZipCompressionLevel.NONE);
+          intermediateApk = intermediateApkWithUncompressedFiles;
+        }
+      }
+
+      ZipAlign zipAlign =
+          new ZipAlign(zipalignTool, intermediateApk.toString(), zipalignApk.toString());
+      zipAlign.run();
+
+      ImmutableList<ApkSigner.SignerConfig> signerConfigs =
+          ApkSignerUtils.getSignerConfigs(keystoreProperties, Files.newInputStream(keystorePath));
+      ApkSignerUtils.signApkFile(
+          zipalignApk.toFile(), Paths.get(outputApk).toFile(), signerConfigs);
+    } catch (UnrecoverableKeyException
+        | NoSuchAlgorithmException
+        | ApkCreationException
+        | SealedApkException
+        | KeyStoreException
+        | InterruptedException e) {
+      throw new RuntimeException(e);
+    } catch (DuplicateFileException e) {
+      throw new RuntimeException(
+          String.format(
+              "Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s",
+              e.getArchivePath(), e.getFile1(), e.getFile2()));
+    } finally {
+      if (buildInfoDir != null) {
+        // Clean up the synthesized build-info temp dir (the bundler does the same on iOS); the
+        // action sandbox would reclaim it anyway.
+        try {
+          MoreFiles.deleteRecursively(buildInfoDir, RecursiveDeleteOption.ALLOW_INSECURE);
+        } catch (IOException e) {
+          // Best-effort cleanup.
+        }
+      }
+    }
+
+    System.exit(0);
+  }
+
+  /**
+   * Runs the toolchain's build-info generator into a temp dir and returns it for inclusion as an
+   * APK asset. {@code argsFile} holds the generator's run command, one token per line; the
+   * generator reads {@code BUCK_BUILD_ID} from this action's environment, inherited by the
+   * subprocess. Keeping the build-info-writing logic in that separate toolchain tool, but running
+   * it from the apk packaging action, ties the baked id to the APK content (re-baked only when the
+   * APK changes).
+   */
+  private static Path generateBuildInfoAssetDir(String argsFile) throws IOException {
+    List<String> command = new ArrayList<>(Files.readAllLines(Paths.get(argsFile)));
+    Path dir = Files.createTempDirectory("build_info");
+    command.add("--output-dir");
+    command.add(dir.toString());
+    Process process = new ProcessBuilder(command).inheritIO().start();
+    int exitCode;
+    try {
+      exitCode = process.waitFor();
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+      throw new RuntimeException("Interrupted while running build-info generator", e);
+    }
+    if (exitCode != 0) {
+      throw new RuntimeException("Build-info generator failed with exit code " + exitCode);
+    }
+    return dir;
+  }
+
+  /**
+   * Expands regex patterns in the given set of patterns to actual file names found in the APK.
+   * Patterns are treated as regex patterns and matched against APK entries.
+   *
+   * @param apkPath Path to the APK file to scan for matching entries
+   * @param patterns Set of regex patterns to match against APK entries
+   * @return Set of actual file names that match the patterns
+   */
+  private static ImmutableSet<String> expandRegexPatterns(
+      Path apkPath, ImmutableSet<String> patterns) throws IOException {
+    Set<Pattern> regexPatterns = new HashSet<>();
+
+    // Compile all patterns as regex
+    for (String pattern : patterns) {
+      regexPatterns.add(Pattern.compile(pattern));
+    }
+
+    // If no patterns, return empty set
+    if (regexPatterns.isEmpty()) {
+      return ImmutableSet.of();
+    }
+
+    // Scan the APK to find entries matching regex patterns
+    Set<String> result = new HashSet<>();
+    try (BufferedInputStream bufferedIn = new BufferedInputStream(Files.newInputStream(apkPath));
+        ZipInputStream zipIn = new ZipInputStream(bufferedIn)) {
+      ZipEntry entry;
+      while ((entry = zipIn.getNextEntry()) != null) {
+        String entryName = entry.getName();
+        for (Pattern regexPattern : regexPatterns) {
+          if (regexPattern.matcher(entryName).matches()) {
+            result.add(entryName);
+            break;
+          }
+        }
+      }
+    }
+
+    return ImmutableSet.copyOf(result);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkBuilderUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkBuilderUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkBuilderUtils.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apk;
+
+import com.facebook.buck.android.apk.sdk.ApkBuilder;
+import com.facebook.buck.android.apk.sdk.ApkCreationException;
+import com.facebook.buck.android.apk.sdk.DuplicateFileException;
+import com.facebook.buck.android.apk.sdk.SealedApkException;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import org.jetbrains.annotations.Nullable;
+
+/** A class that provides methods useful for building an APK. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ApkBuilderUtils {
+
+  /**
+   * The type of a keystore created via the {@code jarsigner} command in Sun/Oracle Java. See
+   * http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyStore.
+   */
+  public static void buildApk(
+      Path resourceApk,
+      Path pathToOutputApkFile,
+      Path dexFile,
+      ImmutableSet<Path> assetDirectories,
+      ImmutableSet<Path> nativeLibraryDirectories,
+      ImmutableSet<Path> zipFiles,
+      ImmutableSet<Path> jarFilesThatMayContainResources,
+      Path pathToKeystore,
+      KeystoreProperties keystoreProperties,
+      boolean packageMetaInfVersionFiles,
+      @Nullable PrintStream output,
+      ImmutableSet<String> excludedResources)
+      throws IOException,
+          ApkCreationException,
+          KeyStoreException,
+          NoSuchAlgorithmException,
+          SealedApkException,
+          UnrecoverableKeyException,
+          DuplicateFileException {
+    ApkBuilder builder =
+        new ApkBuilder(
+            pathToOutputApkFile.toFile(),
+            resourceApk.toFile(),
+            dexFile.toFile(),
+            packageMetaInfVersionFiles,
+            output,
+            excludedResources);
+    for (Path nativeLibraryDirectory : nativeLibraryDirectories.stream().sorted().toList()) {
+      builder.addNativeLibraries(nativeLibraryDirectory.toFile());
+    }
+    for (Path assetDirectory : assetDirectories.stream().sorted().toList()) {
+      builder.addSourceFolder(assetDirectory.toFile());
+    }
+    for (Path zipFile : zipFiles.stream().sorted().toList()) {
+      // TODO(natthu): Skipping silently is bad. These should really be assertions.
+      if (Files.exists(zipFile) && Files.isRegularFile(zipFile)) {
+        builder.addZipFile(zipFile.toFile());
+      }
+    }
+    for (Path jarFileThatMayContainResources :
+        jarFilesThatMayContainResources.stream().sorted().toList()) {
+      builder.addResourcesFromJar(jarFileThatMayContainResources.toFile());
+    }
+    builder.sealApk();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkSignerUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkSignerUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/ApkSignerUtils.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apk;
+
+import com.android.apksig.ApkSigner;
+import com.facebook.buck.android.apk.sdk.ApkCreationException;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import java.io.File;
+import java.io.InputStream;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+/** Use Google apksigner to v1 + v2 sign the final APK */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ApkSignerUtils {
+
+  /** Sign the APK using Google's {@link ApkSigner} */
+  public static void signApkFile(
+      File inputApk, File outputApk, ImmutableList<ApkSigner.SignerConfig> signerConfigs)
+      throws ApkCreationException {
+    ApkSigner.Builder apkSignerBuilder = new ApkSigner.Builder(signerConfigs);
+    try {
+      apkSignerBuilder
+          .setV1SigningEnabled(true)
+          .setV2SigningEnabled(true)
+          .setV3SigningEnabled(false)
+          .setInputApk(inputApk)
+          .setOutputApk(outputApk)
+          .build()
+          .sign();
+    } catch (Exception e) {
+      throw new ApkCreationException(e, "Failed to sign APK");
+    }
+  }
+
+  public static ImmutableList<ApkSigner.SignerConfig> getSignerConfigs(
+      KeystoreProperties keystoreProperties, InputStream keystoreInputStream)
+      throws KeyStoreException {
+    char[] keystorePassword = keystoreProperties.getStorepass().toCharArray();
+    String keyAlias = keystoreProperties.getAlias();
+    char[] keyPassword = keystoreProperties.getKeypass().toCharArray();
+    KeyStore keystore = loadKeyStore(keystoreInputStream, keystorePassword);
+    PrivateKey key = loadPrivateKey(keystore, keyAlias, keyPassword);
+    List<X509Certificate> certs = loadCertificates(keystore, keyAlias);
+    ApkSigner.SignerConfig signerConfig =
+        new ApkSigner.SignerConfig.Builder("CERT", key, certs).build();
+    return ImmutableList.of(signerConfig);
+  }
+
+  private static KeyStore loadKeyStore(InputStream keystoreInputStream, char[] keystorePassword)
+      throws KeyStoreException {
+    try {
+      String ksType = KeyStore.getDefaultType();
+      KeyStore keystore = KeyStore.getInstance(ksType);
+      keystore.load(keystoreInputStream, keystorePassword);
+      return keystore;
+    } catch (Exception e) {
+      throw new KeyStoreException("Failed to load keystore", e);
+    }
+  }
+
+  private static PrivateKey loadPrivateKey(KeyStore keystore, String keyAlias, char[] keyPassword)
+      throws KeyStoreException {
+    PrivateKey key;
+    try {
+      key = (PrivateKey) keystore.getKey(keyAlias, keyPassword);
+      // key can be null if alias/password is incorrect.
+      Objects.requireNonNull(key);
+    } catch (Exception e) {
+      throw new KeyStoreException(
+          "key.alias [" + keyAlias + "] does not exist or does not identify a key-related entry");
+    }
+    return key;
+  }
+
+  private static List<X509Certificate> loadCertificates(KeyStore keystore, String keyAlias)
+      throws KeyStoreException {
+    Certificate[] certChain = keystore.getCertificateChain(keyAlias);
+    if ((certChain == null) || (certChain.length == 0)) {
+      throw new KeyStoreException(
+          keystore + " entry \"" + keyAlias + "\" does not contain certificates");
+    }
+    List<X509Certificate> certs = new ArrayList<>(certChain.length);
+    for (Certificate cert : certChain) {
+      certs.add((X509Certificate) cert);
+    }
+    return certs;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/BUCK
@@ -0,0 +1,39 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "apk",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/apk/sdk:apk_builder",
+        "prelude//toolchains/android/src/com/facebook/buck/android/zipalign:zipalign",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        "prelude//toolchains/android/third-party/aosp:apksig",
+    ],
+)
+
+buck_java_binary(
+    name = "apk_builder_binary",
+    java_args_for_run_info = [
+        "--add-opens=java.base/sun.security.pkcs=ALL-UNNAMED",
+        "--add-opens=java.base/sun.security.x509=ALL-UNNAMED",
+    ],
+    main_class = "com.facebook.buck.android.apk.ApkBuilderExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":apk",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/KeystoreProperties.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/KeystoreProperties.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/KeystoreProperties.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apk;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Strings;
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Properties;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class KeystoreProperties {
+
+  private final Path keystore;
+  private final String storepass;
+  private final String keypass;
+  private final String alias;
+
+  public KeystoreProperties(Path keystore, String storepass, String keypass, String alias) {
+    this.keystore = keystore;
+    this.storepass = storepass;
+    this.keypass = keypass;
+    this.alias = alias;
+  }
+
+  public Path getKeystore() {
+    return keystore;
+  }
+
+  public String getStorepass() {
+    return storepass;
+  }
+
+  public String getKeypass() {
+    return keypass;
+  }
+
+  public String getAlias() {
+    return alias;
+  }
+
+  public static KeystoreProperties createFromPropertiesFile(
+      Path pathToStore, Path pathToKeystorePropertiesFile) throws IOException {
+    Properties properties = readPropertiesFile(pathToKeystorePropertiesFile);
+
+    String keystorePassword =
+        getOrThrowException(properties, "key.store.password", pathToKeystorePropertiesFile);
+    String alias = getOrThrowException(properties, "key.alias", pathToKeystorePropertiesFile);
+    String aliasPassword =
+        getOrThrowException(properties, "key.alias.password", pathToKeystorePropertiesFile);
+
+    return new KeystoreProperties(pathToStore, keystorePassword, aliasPassword, alias);
+  }
+
+  private static Properties readPropertiesFile(Path propertiesFile) throws IOException {
+    Properties properties = new Properties();
+    try (BufferedReader reader =
+        new BufferedReader(
+            new InputStreamReader(
+                new BufferedInputStream(Files.newInputStream(propertiesFile)),
+                StandardCharsets.UTF_8))) {
+      properties.load(reader);
+    }
+
+    return properties;
+  }
+
+  /**
+   * @return a non-null, non-empty value for the specified property
+   * @throws RuntimeException if there is no value for the specified property
+   */
+  private static String getOrThrowException(
+      Properties properties, String propertyName, Path pathToKeystorePropertiesFile) {
+    String value = Strings.nullToEmpty(properties.getProperty(propertyName)).trim();
+    if (value.isEmpty()) {
+      throw new RuntimeException(
+          String.format(
+              "properties file %s did not contain a value for the property %s",
+              pathToKeystorePropertiesFile, propertyName));
+    } else {
+      return value;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkBuilder.java
@@ -0,0 +1,784 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apk.sdk;
+
+import com.facebook.buck.android.apk.sdk.ApkJarBuilder.IZipEntryFilter;
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Class making the final apk packaging. The inputs are: - packaged resources (output of aapt) -
+ * code file (output of dx) - Java resources coming from the project, its libraries, and its jar
+ * files - Native libraries from the project or its library.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public final class ApkBuilder implements IArchiveBuilder {
+  /** Native lib folder inside the APK: "lib" */
+  public static final String FD_APK_NATIVE_LIBS = "lib"; // $NON-NLS-1$
+
+  /** Dex filename inside the APK. i.e. "classes.dex" */
+  public static final String FN_APK_CLASSES_DEX = "classes.dex"; // $NON-NLS-1$
+
+  /** filename for wrap.sh */
+  public static final String FN_WRAP_SH = "wrap.sh";
+
+  /** filename for gdbserver. */
+  public static final String FN_GDBSERVER = "gdbserver"; // $NON-NLS-1$
+
+  private static final Pattern PATTERN_NATIVELIB_EXT =
+      Pattern.compile("^.+\\.so$", Pattern.CASE_INSENSITIVE);
+  private static final Pattern PATTERN_BITCODELIB_EXT =
+      Pattern.compile("^.+\\.bc$", Pattern.CASE_INSENSITIVE);
+
+  /** A No-op zip filter. It's used to detect conflicts. */
+  private final class NullZipFilter implements IZipEntryFilter {
+    /** Null until {@link #reset} names the archive whose entries are about to be filtered. */
+    @Nullable private File mInputFile;
+
+    void reset(File inputFile) {
+      mInputFile = inputFile;
+    }
+
+    @Override
+    public boolean checkEntry(String archivePath) throws IZipEntryFilter.ZipAbortException {
+      verbosePrintln("=> %s", archivePath);
+
+      File inputFile = Objects.requireNonNull(mInputFile, "reset() must precede checkEntry()");
+      File duplicate = checkFileForDuplicate(archivePath);
+      if (duplicate != null) {
+        throw new DuplicateFileException(archivePath, duplicate, inputFile);
+      } else {
+        mAddedFiles.put(archivePath, inputFile);
+      }
+
+      return true;
+    }
+  }
+
+  /**
+   * Custom {@link IZipEntryFilter} to filter out everything that is not a standard java resources,
+   * and also record whether the zip file contains native libraries.
+   *
+   * <p>Used in {@link ApkJarBuilder#writeZip(java.io.InputStream, IZipEntryFilter)} when we only
+   * want the java resources from external jars.
+   */
+  private final class JavaAndNativeResourceFilter implements IZipEntryFilter {
+    private final Set<String> mExcludedResources;
+    private final List<String> mNativeLibs = new ArrayList<String>();
+    private boolean mNativeLibsConflict = false;
+
+    /** Null until {@link #reset} names the archive whose entries are about to be filtered. */
+    @Nullable private File mInputFile;
+
+    JavaAndNativeResourceFilter(Set<String> excludedResources) {
+      mExcludedResources = excludedResources;
+    }
+
+    @Override
+    public boolean checkEntry(String archivePath) throws IZipEntryFilter.ZipAbortException {
+      if (isExcludedResource(archivePath)) {
+        return false;
+      }
+
+      // split the path into segments.
+      String[] segments = archivePath.split("/");
+
+      // empty path? skip to next entry.
+      if (segments.length == 0) {
+        return false;
+      }
+
+      // Check each folders to make sure they should be included.
+      // Folders like CVS, .svn, etc.. should already have been excluded from the
+      // jar file, but we need to exclude some other folder (like /META-INF) so
+      // we check anyway.
+      for (int i = 0; i < segments.length - 1; i++) {
+        if (!checkFolderForPackaging(segments[i])) {
+          return false;
+        }
+      }
+
+      // get the file name from the path
+      String fileName = segments[segments.length - 1];
+
+      boolean check = checkFileForPackaging(fileName);
+
+      // only do additional checks if the file passes the default checks.
+      if (check) {
+        verbosePrintln("=> %s", archivePath);
+
+        File inputFile = Objects.requireNonNull(mInputFile, "reset() must precede checkEntry()");
+        File duplicate = checkFileForDuplicate(archivePath);
+        if (duplicate != null) {
+          throw new DuplicateFileException(archivePath, duplicate, inputFile);
+        } else {
+          mAddedFiles.put(archivePath, inputFile);
+        }
+
+        if (archivePath.endsWith(".so") || archivePath.endsWith(".bc")) {
+          mNativeLibs.add(archivePath);
+
+          // only .so located in lib/ will interfere with the installation
+          if (archivePath.startsWith(FD_APK_NATIVE_LIBS + "/")) {
+            mNativeLibsConflict = true;
+          }
+        } else if (archivePath.endsWith(".jnilib")) {
+          mNativeLibs.add(archivePath);
+        }
+      }
+
+      return check;
+    }
+
+    public boolean isExcludedResource(String archivePath) {
+      return mExcludedResources.contains(archivePath);
+    }
+
+    List<String> getNativeLibs() {
+      return mNativeLibs;
+    }
+
+    boolean getNativeLibsConflict() {
+      return mNativeLibsConflict;
+    }
+
+    void reset(File inputFile) {
+      mInputFile = inputFile;
+      mNativeLibs.clear();
+      mNativeLibsConflict = false;
+    }
+  }
+
+  private File mApkFile;
+  private File mResFile;
+  @Nullable private File mDexFile;
+  @Nullable private PrintStream mVerboseStream;
+  private ApkJarBuilder mBuilder;
+  private boolean mDebugMode = false;
+  private boolean mIsSealed = false;
+
+  private final NullZipFilter mNullFilter = new NullZipFilter();
+  private final JavaAndNativeResourceFilter mFilter;
+  private final Map<String, File> mAddedFiles = new HashMap<String, File>();
+
+  /**
+   * Status for the addition of a jar file resources into the APK. This indicates possible issues
+   * with native library inside the jar file.
+   */
+  public interface JarStatus {
+    /** Returns the list of native libraries found in the jar file. */
+    List<String> getNativeLibs();
+
+    /**
+     * Returns whether some of those libraries were located in the location that Android expects its
+     * native libraries.
+     */
+    boolean hasNativeLibsConflicts();
+  }
+
+  /** Internal implementation of {@link JarStatus}. */
+  private static final class JarStatusImpl implements JarStatus {
+    public final List<String> mLibs;
+    public final boolean mNativeLibsConflict;
+
+    private JarStatusImpl(List<String> libs, boolean nativeLibsConflict) {
+      mLibs = libs;
+      mNativeLibsConflict = nativeLibsConflict;
+    }
+
+    @Override
+    public List<String> getNativeLibs() {
+      return mLibs;
+    }
+
+    @Override
+    public boolean hasNativeLibsConflicts() {
+      return mNativeLibsConflict;
+    }
+  }
+
+  /**
+   * Creates a new instance.
+   *
+   * <p>This creates a new builder that will create the specified output file, using the two
+   * mandatory given input files.
+   *
+   * <p>An optional {@link PrintStream} can also be provided for verbose output. If null, there will
+   * be no output.
+   *
+   * @param apkFile the file to create
+   * @param resFile the file representing the packaged resource file.
+   * @param dexFile the file representing the dex file. This can be null for apk with no code.
+   * @param verboseStream the stream to which verbose output should go. If null, verbose mode is not
+   *     enabled.
+   * @throws ApkCreationException
+   */
+  public ApkBuilder(
+      File apkFile,
+      File resFile,
+      @Nullable File dexFile,
+      boolean packageMetaInfVersionFiles,
+      @Nullable PrintStream verboseStream,
+      Set<String> excludedResources)
+      throws ApkCreationException {
+    mFilter = new JavaAndNativeResourceFilter(excludedResources);
+    init(apkFile, resFile, dexFile, packageMetaInfVersionFiles, verboseStream);
+  }
+
+  private void init(
+      File apkFile,
+      File resFile,
+      @Nullable File dexFile,
+      boolean packageMetaInfVersionFiles,
+      @Nullable PrintStream verboseStream)
+      throws ApkCreationException {
+
+    try {
+      checkOutputFile(mApkFile = apkFile);
+      checkInputFile(mResFile = resFile);
+      if (dexFile != null) {
+        checkInputFile(mDexFile = dexFile);
+      } else {
+        mDexFile = null;
+      }
+      mVerboseStream = verboseStream;
+
+      mBuilder =
+          new ApkJarBuilder(
+              new FileOutputStream(mApkFile, false /* append */), packageMetaInfVersionFiles);
+
+      verbosePrintln("Packaging %s", mApkFile.getName());
+
+      // add the resources
+      addZipFile(mResFile);
+
+      // add the class dex file at the root of the apk
+      if (mDexFile != null) {
+        addFile(mDexFile, FN_APK_CLASSES_DEX);
+      }
+
+    } catch (ApkCreationException e) {
+      if (mBuilder != null) {
+        mBuilder.cleanUp();
+      }
+      throw e;
+    } catch (Exception e) {
+      if (mBuilder != null) {
+        mBuilder.cleanUp();
+      }
+      throw new ApkCreationException(e);
+    }
+  }
+
+  /**
+   * Sets the debug mode. In debug mode, when native libraries are present, the packaging will also
+   * include one or more copies of gdbserver in the final APK file.
+   *
+   * <p>These are used for debugging native code, to ensure that gdbserver is accessible to the
+   * application.
+   *
+   * <p>There will be one version of gdbserver for each ABI supported by the application.
+   *
+   * <p>the gbdserver files are placed in the libs/abi/ folders automatically by the NDK.
+   *
+   * @param debugMode the debug mode flag.
+   */
+  public void setDebugMode(boolean debugMode) {
+    mDebugMode = debugMode;
+  }
+
+  /**
+   * Adds a file to the APK at a given path
+   *
+   * @param file the file to add
+   * @param archivePath the path of the file inside the APK archive.
+   * @throws ApkCreationException if an error occurred
+   * @throws SealedApkException if the APK is already sealed.
+   * @throws DuplicateFileException if a file conflicts with another already added to the APK at the
+   *     same location inside the APK archive.
+   */
+  @Override
+  public void addFile(File file, String archivePath)
+      throws ApkCreationException, SealedApkException, DuplicateFileException {
+    if (mIsSealed) {
+      throw new SealedApkException("APK is already sealed");
+    }
+
+    try {
+      doAddFile(file, archivePath);
+    } catch (DuplicateFileException e) {
+      mBuilder.cleanUp();
+      throw e;
+    } catch (Exception e) {
+      mBuilder.cleanUp();
+      throw new ApkCreationException(e, "Failed to add %s", file);
+    }
+  }
+
+  /**
+   * Adds the content from a zip file. All file keep the same path inside the archive.
+   *
+   * @param zipFile the zip File.
+   * @throws ApkCreationException if an error occurred
+   * @throws SealedApkException if the APK is already sealed.
+   * @throws DuplicateFileException if a file conflicts with another already added to the APK at the
+   *     same location inside the APK archive.
+   */
+  public void addZipFile(File zipFile)
+      throws ApkCreationException, SealedApkException, DuplicateFileException {
+    if (mIsSealed) {
+      throw new SealedApkException("APK is already sealed");
+    }
+
+    try {
+      verbosePrintln("%s:", zipFile);
+
+      // reset the filter with this input.
+      mNullFilter.reset(zipFile);
+
+      // ask the builder to add the content of the file.
+      FileInputStream fis = new FileInputStream(zipFile);
+      mBuilder.writeZip(fis, mNullFilter);
+      fis.close();
+    } catch (DuplicateFileException e) {
+      mBuilder.cleanUp();
+      throw e;
+    } catch (Exception e) {
+      mBuilder.cleanUp();
+      throw new ApkCreationException(e, "Failed to add %s", zipFile);
+    }
+  }
+
+  /**
+   * Adds the resources from a jar file.
+   *
+   * @param jarFile the jar File.
+   * @return a {@link JarStatus} object indicating if native libraries where found in the jar file.
+   * @throws ApkCreationException if an error occurred
+   * @throws SealedApkException if the APK is already sealed.
+   * @throws DuplicateFileException if a file conflicts with another already added to the APK at the
+   *     same location inside the APK archive.
+   */
+  public JarStatus addResourcesFromJar(File jarFile)
+      throws ApkCreationException, SealedApkException, DuplicateFileException {
+    if (mIsSealed) {
+      throw new SealedApkException("APK is already sealed");
+    }
+
+    try {
+      verbosePrintln("%s:", jarFile);
+
+      // reset the filter with this input.
+      mFilter.reset(jarFile);
+
+      // ask the builder to add the content of the file, filtered to only let through
+      // the java resources.
+      FileInputStream fis = new FileInputStream(jarFile);
+      mBuilder.writeZip(fis, mFilter);
+      fis.close();
+
+      // check if native libraries were found in the external library. This should
+      // constitutes an error or warning depending on if they are in lib/
+      return new JarStatusImpl(mFilter.getNativeLibs(), mFilter.getNativeLibsConflict());
+    } catch (DuplicateFileException e) {
+      mBuilder.cleanUp();
+      throw e;
+    } catch (Exception e) {
+      mBuilder.cleanUp();
+      throw new ApkCreationException(e, "Failed to add %s", jarFile);
+    }
+  }
+
+  /**
+   * Adds the resources from a source folder.
+   *
+   * @param sourceFolder the source folder.
+   * @throws ApkCreationException if an error occurred
+   * @throws SealedApkException if the APK is already sealed.
+   * @throws DuplicateFileException if a file conflicts with another already added to the APK at the
+   *     same location inside the APK archive.
+   */
+  public void addSourceFolder(File sourceFolder)
+      throws ApkCreationException, SealedApkException, DuplicateFileException {
+    if (mIsSealed) {
+      throw new SealedApkException("APK is already sealed");
+    }
+
+    addSourceFolder(this, sourceFolder);
+  }
+
+  /**
+   * Adds the resources from a source folder to a given {@link IArchiveBuilder}
+   *
+   * @param sourceFolder the source folder.
+   * @throws ApkCreationException if an error occurred
+   * @throws DuplicateFileException if a file conflicts with another already added to the APK at the
+   *     same location inside the APK archive.
+   */
+  public static void addSourceFolder(IArchiveBuilder builder, File sourceFolder)
+      throws ApkCreationException, DuplicateFileException {
+    if (sourceFolder.isDirectory()) {
+      try {
+        // file is a directory, process its content.
+        File[] files = sourceFolder.listFiles();
+        if (files != null) {
+          for (File file : files) {
+            processFileForResource(builder, file, null);
+          }
+        }
+      } catch (DuplicateFileException e) {
+        throw e;
+      } catch (Exception e) {
+        throw new ApkCreationException(e, "Failed to add %s", sourceFolder);
+      }
+    } else {
+      // not a directory? check if it's a file or doesn't exist
+      if (sourceFolder.exists()) {
+        throw new ApkCreationException("%s is not a folder", sourceFolder);
+      } else {
+        throw new ApkCreationException("%s does not exist", sourceFolder);
+      }
+    }
+  }
+
+  /**
+   * Adds the native libraries from the top native folder. The content of this folder must be the
+   * various ABI folders.
+   *
+   * <p>This may or may not copy gdbserver into the apk based on whether the debug mode is set.
+   *
+   * @param nativeFolder the native folder.
+   * @throws ApkCreationException if an error occurred
+   * @throws SealedApkException if the APK is already sealed.
+   * @throws DuplicateFileException if a file conflicts with another already added to the APK at the
+   *     same location inside the APK archive.
+   * @see #setDebugMode(boolean)
+   */
+  public void addNativeLibraries(File nativeFolder)
+      throws ApkCreationException, SealedApkException, DuplicateFileException {
+    if (mIsSealed) {
+      throw new SealedApkException("APK is already sealed");
+    }
+
+    if (!nativeFolder.isDirectory()) {
+      // not a directory? check if it's a file or doesn't exist
+      if (nativeFolder.exists()) {
+        throw new ApkCreationException("%s is not a folder", nativeFolder);
+      } else {
+        throw new ApkCreationException("%s does not exist", nativeFolder);
+      }
+    }
+
+    File[] abiList = nativeFolder.listFiles();
+
+    verbosePrintln("Native folder: %s", nativeFolder);
+
+    if (abiList != null) {
+      for (File abi : abiList) {
+        if (abi.isDirectory()) { // ignore files
+
+          File[] libs = abi.listFiles();
+          if (libs != null) {
+            for (File lib : libs) {
+              // only consider files that are .so or, if in debug mode, that
+              // are gdbserver executables. Also permit wrap shell scripts (see
+              // https://developer.android.com/ndk/guides/wrap-script).
+              if (shouldAddNativeLib(lib)) {
+                String path = FD_APK_NATIVE_LIBS + "/" + abi.getName() + "/" + lib.getName();
+
+                try {
+                  doAddFile(lib, path);
+                } catch (IOException e) {
+                  mBuilder.cleanUp();
+                  throw new ApkCreationException(e, "Failed to add %s", lib);
+                }
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * @return Whether or not a given native lib should be added to the final binary.
+   */
+  public boolean shouldAddNativeLib(File lib) {
+    return lib.isFile()
+        && !mFilter.isExcludedResource(lib.getName())
+        && (PATTERN_NATIVELIB_EXT.matcher(lib.getName()).matches()
+            || PATTERN_BITCODELIB_EXT.matcher(lib.getName()).matches()
+            || FN_WRAP_SH.equals(lib.getName())
+            || (mDebugMode && FN_GDBSERVER.equals(lib.getName())));
+  }
+
+  /**
+   * Seals the APK, and signs it if necessary.
+   *
+   * @throws ApkCreationException
+   * @throws ApkCreationException if an error occurred
+   * @throws SealedApkException if the APK is already sealed.
+   */
+  public void sealApk() throws ApkCreationException, SealedApkException {
+    if (mIsSealed) {
+      throw new SealedApkException("APK is already sealed");
+    }
+
+    // close and sign the application package.
+    try {
+      mBuilder.close();
+      mIsSealed = true;
+    } catch (Exception e) {
+      throw new ApkCreationException(e, "Failed to seal APK");
+    } finally {
+      mBuilder.cleanUp();
+    }
+  }
+
+  /**
+   * Output a given message if the verbose mode is enabled.
+   *
+   * @param format the format string for {@link String#format(String, Object...)}
+   * @param args the string arguments
+   */
+  private void verbosePrintln(String format, Object... args) {
+    if (mVerboseStream != null) {
+      mVerboseStream.println(String.format(format, args));
+    }
+  }
+
+  private void doAddFile(File file, String archivePath) throws DuplicateFileException, IOException {
+    verbosePrintln("%1$s => %2$s", file, archivePath);
+
+    File duplicate = checkFileForDuplicate(archivePath);
+    if (duplicate != null) {
+      throw new DuplicateFileException(archivePath, duplicate, file);
+    }
+
+    mAddedFiles.put(archivePath, file);
+    mBuilder.writeFile(file, archivePath);
+  }
+
+  /**
+   * Processes a {@link File} that could be an APK {@link File}, or a folder containing java
+   * resources.
+   *
+   * @param file the {@link File} to process.
+   * @param path the relative path of this file to the source folder. Can be <code>null</code> to
+   *     identify a root file.
+   * @throws IOException
+   * @throws DuplicateFileException if a file conflicts with another already added to the APK at the
+   *     same location inside the APK archive.
+   * @throws SealedApkException if the APK is already sealed.
+   * @throws ApkCreationException if an error occurred
+   */
+  private static void processFileForResource(
+      IArchiveBuilder builder, File file, @Nullable String path)
+      throws IOException, DuplicateFileException, ApkCreationException, SealedApkException {
+    if (file.isDirectory()) {
+      // a directory? we check it
+      if (checkFolderForPackaging(file.getName())) {
+        // if it's valid, we append its name to the current path.
+        if (path == null) {
+          path = file.getName();
+        } else {
+          path = path + "/" + file.getName();
+        }
+
+        // and process its content.
+        File[] files = file.listFiles();
+        if (files != null) {
+          for (File contentFile : files) {
+            processFileForResource(builder, contentFile, path);
+          }
+        }
+      }
+    } else {
+      // a file? we check it to make sure it should be added
+      if (checkFileForPackaging(file.getName())) {
+        // we append its name to the current path
+        if (path == null) {
+          path = file.getName();
+        } else {
+          path = path + "/" + file.getName();
+        }
+
+        // and add it to the apk
+        builder.addFile(file, path);
+      }
+    }
+  }
+
+  /**
+   * Checks if the given path in the APK archive has not already been used and if it has been, then
+   * returns a {@link File} object for the source of the duplicate
+   *
+   * @param archivePath the archive path to test.
+   * @return A File object of either a file at the same location or an archive that contains a file
+   *     that was put at the same location.
+   */
+  @Nullable
+  private File checkFileForDuplicate(String archivePath) {
+    return mAddedFiles.get(archivePath);
+  }
+
+  /**
+   * Checks an output {@link File} object. This checks the following: - the file is not an existing
+   * directory. - if the file exists, that it can be modified. - if it doesn't exists, that a new
+   * file can be created.
+   *
+   * @param file the File to check
+   * @throws ApkCreationException If the check fails
+   */
+  private void checkOutputFile(File file) throws ApkCreationException {
+    if (file.isDirectory()) {
+      throw new ApkCreationException("%s is a directory!", file);
+    }
+
+    if (file.exists()) { // will be a file in this case.
+      if (!file.canWrite()) {
+        throw new ApkCreationException("Cannot write %s", file);
+      }
+    } else {
+      try {
+        if (!file.createNewFile()) {
+          throw new ApkCreationException("Failed to create %s", file);
+        }
+      } catch (IOException e) {
+        throw new ApkCreationException("Failed to create '%1$ss': %2$s", file, e.toString());
+      }
+    }
+  }
+
+  /**
+   * Checks an input {@link File} object. This checks the following: - the file is not an existing
+   * directory. - that the file exists (if <var>throwIfDoesntExist</var> is <code>false</code>) and
+   * can be read.
+   *
+   * @param file the File to check
+   * @throws FileNotFoundException if the file is not here.
+   * @throws ApkCreationException If the file is a folder or a file that cannot be read.
+   */
+  private static void checkInputFile(File file) throws FileNotFoundException, ApkCreationException {
+    if (file.isDirectory()) {
+      throw new ApkCreationException("%s is a directory!", file);
+    }
+
+    if (file.exists()) {
+      if (!file.canRead()) {
+        throw new ApkCreationException("Cannot read %s", file);
+      }
+    } else {
+      throw new FileNotFoundException(String.format("%s does not exist", file));
+    }
+  }
+
+  /**
+   * Checks whether a folder and its content is valid for packaging into the .apk as standard Java
+   * resource.
+   *
+   * @param folderName the name of the folder.
+   */
+  public static boolean checkFolderForPackaging(String folderName) {
+    return !folderName.equalsIgnoreCase("CVS")
+        && !folderName.equalsIgnoreCase(".svn")
+        && !folderName.equalsIgnoreCase("SCCS")
+        && !folderName.equalsIgnoreCase("META-INF")
+        && !folderName.equalsIgnoreCase("nonJvmMain")
+        // nonJvmMain is only useful when build multiplatform and we are building an APK here
+        // commonMain folder is part of multiple AndroidX libraries, exclude it to avoid
+        // duplicate file error
+        && !folderName.equalsIgnoreCase("commonMain")
+        // nativeMain holds platform-specific code for native environments like iOS and macOS,
+        // exclude it to avoid duplicate file error
+        // see https://kotlinlang.org/docs/multiplatform-discover-project.html
+        && !folderName.equalsIgnoreCase("nativeMain");
+  }
+
+  /**
+   * Checks a file to make sure it should be packaged as standard resources.
+   *
+   * @param fileName the name of the file (including extension)
+   * @return true if the file should be packaged as standard java resources.
+   */
+  public static boolean checkFileForPackaging(String fileName) {
+    String[] fileSegments = fileName.split("\\.");
+    String fileExt = "";
+    if (fileSegments.length > 1) {
+      fileExt = fileSegments[fileSegments.length - 1];
+    }
+
+    return checkFileForPackaging(fileName, fileExt);
+  }
+
+  /**
+   * Checks a file to make sure it should be packaged as standard resources.
+   *
+   * @param fileName the name of the file (including extension)
+   * @param extension the extension of the file (excluding '.')
+   * @return true if the file should be packaged as standard java resources.
+   */
+  public static boolean checkFileForPackaging(String fileName, String extension) {
+    // ignore hidden files and backup files
+    if (fileName.charAt(0) == '.' || fileName.charAt(fileName.length() - 1) == '~') {
+      return false;
+    }
+
+    return !"aidl".equalsIgnoreCase(extension)
+        && // Aidl files
+        !"rs".equalsIgnoreCase(extension)
+        && // RenderScript files
+        !"fs".equalsIgnoreCase(extension)
+        && // FilterScript files
+        !"rsh".equalsIgnoreCase(extension)
+        && // RenderScript header files
+        !"d".equalsIgnoreCase(extension)
+        && // Dependency files
+        !"java".equalsIgnoreCase(extension)
+        && // Java files
+        !"scala".equalsIgnoreCase(extension)
+        && // Scala files
+        !"class".equalsIgnoreCase(extension)
+        && // Java class files
+        !"scc".equalsIgnoreCase(extension)
+        && // VisualSourceSafe
+        !"swp".equalsIgnoreCase(extension)
+        && // Kotlin Metadata file
+        !"kotlin_metadata".equalsIgnoreCase(extension)
+        && // vi swap file
+        !"thumbs.db".equalsIgnoreCase(fileName)
+        && // image index file
+        !"picasa.ini".equalsIgnoreCase(fileName)
+        && // image index file
+        !"package.html".equalsIgnoreCase(fileName)
+        && // Javadoc
+        !"overview.html".equalsIgnoreCase(fileName)
+        && // License files
+        !"LICENSE".equalsIgnoreCase(fileName)
+        && !"LICENSE.txt".equalsIgnoreCase(fileName)
+        && // Notice files
+        !"NOTICE".equalsIgnoreCase(fileName)
+        && !"NOTICE.txt".equalsIgnoreCase(fileName);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkCreationException.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkCreationException.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkCreationException.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apk.sdk;
+
+import com.facebook.infer.annotation.Nullsafe;
+
+/** An exception thrown during packaging of an APK file. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public final class ApkCreationException extends Exception {
+  private static final long serialVersionUID = 1L;
+
+  public ApkCreationException(String format, Object... args) {
+    super(String.format(format, args));
+  }
+
+  public ApkCreationException(Throwable cause, String format, Object... args) {
+    super(String.format(format, args), cause);
+  }
+
+  public ApkCreationException(Throwable cause) {
+    super(cause);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkJarBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkJarBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/ApkJarBuilder.java
@@ -0,0 +1,253 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apk.sdk;
+
+import com.facebook.buck.android.apk.sdk.ApkJarBuilder.IZipEntryFilter.ZipAbortException;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableSet;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Calendar;
+import java.util.Objects;
+import java.util.Set;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import org.jetbrains.annotations.Nullable;
+
+/** A Jar file builder. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ApkJarBuilder {
+  private static final long DOS_FAKE_TIME;
+
+  /**
+   * {@link java.util.zip.ZipEntry#setTime(long)} is timezone-sensitive. Use this value instead of a
+   * hardcoded constant to produce timezone-agnostic .zip files.
+   *
+   * @return time in milliseconds that represents a fixed date in the current timezone.
+   */
+  static {
+    // Using any timestamp before 1980 (which is supposedly the earliest time supported by the .zip
+    // format) causes files created by JRE 1.7 to be different than JRE 1.8. This is because 1.8
+    // actually supports setting timestamps to earlier than 1980, whereas 1.7 rounds up to 1980.
+    // We also need to resort to the deprecated date constructor as the ZipEntry uses deprecated
+    // Date methods that depend on the current timezone.
+    // Finally 1980.01.01 doesn't work across all timezones across Java 1.7 and 1.8. Fun times.
+    Calendar c = Calendar.getInstance();
+    c.set(1985, Calendar.FEBRUARY, 1, 0, 0, 0);
+    DOS_FAKE_TIME = c.getTimeInMillis();
+  }
+
+  public static final Set<String> ALLOWLISTED_META_INF_SERVICES_FILES =
+      ImmutableSet.of(
+          "META-INF/services/kotlin.reflect.jvm.internal.impl.builtins.BuiltInsLoader",
+          "META-INF/services/kotlin.reflect.jvm.internal.impl.km.internal.extensions.MetadataExtensions",
+          "META-INF/services/kotlinx.coroutines.CoroutineExceptionHandler",
+          "META-INF/androidx.compose.ui_ui.version");
+  @Nullable private JarOutputStream mOutputJar;
+  private byte[] mBuffer = new byte[256 * 1024];
+  private boolean mPackageMetaInfVersionFiles;
+
+  /**
+   * Classes which implement this interface provides a method to check whether a file should be
+   * added to a Jar file.
+   */
+  public interface IZipEntryFilter {
+
+    /**
+     * An exception thrown during packaging of a zip file into APK file. This is typically thrown by
+     * implementations of {@link IZipEntryFilter#checkEntry(String)}.
+     */
+    class ZipAbortException extends Exception {
+      private static final long serialVersionUID = 1L;
+
+      public ZipAbortException() {
+        super();
+      }
+
+      public ZipAbortException(String format, Object... args) {
+        super(String.format(format, args));
+      }
+
+      public ZipAbortException(Throwable cause, String format, Object... args) {
+        super(String.format(format, args), cause);
+      }
+
+      public ZipAbortException(Throwable cause) {
+        super(cause);
+      }
+    }
+
+    /**
+     * Checks a file for inclusion in a Jar archive.
+     *
+     * @param archivePath the archive file path of the entry
+     * @return <code>true</code> if the file should be included.
+     * @throws ZipAbortException if writing the file should be aborted.
+     */
+    boolean checkEntry(String archivePath) throws ZipAbortException;
+  }
+
+  /**
+   * Creates a {@link ApkJarBuilder} with a given output stream.
+   *
+   * @param out the {@link OutputStream} where to write the Jar archive.
+   * @throws IOException
+   */
+  public ApkJarBuilder(OutputStream out, boolean packageMetaInfVersionFiles) throws IOException {
+    mOutputJar = new JarOutputStream(new BufferedOutputStream(out));
+    mOutputJar.setLevel(4);
+    mPackageMetaInfVersionFiles = packageMetaInfVersionFiles;
+  }
+
+  /**
+   * Writes a new {@link File} into the archive.
+   *
+   * @param inputFile the {@link File} to write.
+   * @param jarPath the filepath inside the archive.
+   * @throws IOException
+   */
+  public void writeFile(File inputFile, String jarPath) throws IOException {
+    // Get an input stream on the file.
+    FileInputStream fis = new FileInputStream(inputFile);
+    try {
+
+      // create the zip entry
+      JarEntry entry = new JarEntry(jarPath);
+      entry.setTime(DOS_FAKE_TIME);
+
+      writeEntry(fis, entry);
+    } finally {
+      // close the file stream used to read the file
+      fis.close();
+    }
+  }
+
+  /**
+   * Copies the content of a Jar/Zip archive into the receiver archive.
+   *
+   * <p>An optional {@link IZipEntryFilter} allows to selectively choose which files to copy over.
+   *
+   * @param input the {@link InputStream} for the Jar/Zip to copy.
+   * @param filter the filter or <code>null</code>
+   * @throws IOException
+   * @throws ZipAbortException if the {@link IZipEntryFilter} filter indicated that the write must
+   *     be aborted.
+   */
+  public void writeZip(InputStream input, IZipEntryFilter filter)
+      throws IOException, ZipAbortException {
+    ZipInputStream zis = new ZipInputStream(input);
+
+    try {
+      // loop on the entries of the intermediary package and put them in the final package.
+      ZipEntry entry;
+      while ((entry = zis.getNextEntry()) != null) {
+        String name = entry.getName();
+
+        // do not take directories
+        if (entry.isDirectory()) {
+          continue;
+        }
+
+        // Do not take anything inside a potential META-INF folder, except for some
+        // META-INF/services files that we know we need.
+        // TODO(T139016417) This hack is only necessary because we are using an old and deprecated
+        // version of this class. We should migrate to Android-Builder instead.
+        if (name.startsWith("META-INF/")) {
+          if (!isMetaInfFileAllowed(name)) {
+            continue;
+          }
+
+          // if we have a filter, we check the entry against it
+        } else if (filter != null && filter.checkEntry(name) == false) {
+          continue;
+        }
+
+        JarEntry newEntry;
+
+        // Preserve the STORED method of the input entry.
+        if (entry.getMethod() == JarEntry.STORED) {
+          newEntry = new JarEntry(entry);
+        } else {
+          // Create a new entry so that the compressed len is recomputed.
+          newEntry = new JarEntry(name);
+        }
+
+        newEntry.setTime(DOS_FAKE_TIME);
+        writeEntry(zis, newEntry);
+
+        zis.closeEntry();
+      }
+    } finally {
+      zis.close();
+    }
+  }
+
+  private boolean isMetaInfFileAllowed(String name) {
+    if (ALLOWLISTED_META_INF_SERVICES_FILES.contains(name)) {
+      return true;
+    }
+    if (mPackageMetaInfVersionFiles && name.endsWith(".version")) {
+      return true;
+    }
+    return false;
+  }
+
+  /**
+   * Closes the Jar archive.
+   *
+   * @throws IOException
+   */
+  public void close() throws IOException {
+    Objects.requireNonNull(mOutputJar).close();
+    mOutputJar = null;
+  }
+
+  /**
+   * Clean up of the builder for interrupted workflow. This does nothing if {@link #close()} was
+   * called successfully.
+   */
+  public void cleanUp() {
+    if (mOutputJar != null) {
+      try {
+        mOutputJar.close();
+      } catch (IOException e) {
+        // pass
+      }
+    }
+  }
+
+  /**
+   * Adds an entry to the output jar, and write its content from the {@link InputStream}
+   *
+   * @param input The input stream from where to write the entry content.
+   * @param entry the entry to write in the jar.
+   * @throws IOException
+   */
+  private void writeEntry(InputStream input, JarEntry entry) throws IOException {
+    // add the entry to the jar archive
+    Objects.requireNonNull(mOutputJar).putNextEntry(entry);
+
+    // read the content of the entry from the input stream, and write it into the archive.
+    int count;
+    while ((count = input.read(mBuffer)) != -1) {
+      Objects.requireNonNull(mOutputJar).write(mBuffer, 0, count);
+    }
+
+    // close the entry for this file
+    Objects.requireNonNull(mOutputJar).closeEntry();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/BUCK
@@ -0,0 +1,18 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "apk_builder",
+    srcs = glob(["*.java"]),
+    required_for_source_only_abi = True,
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/DuplicateFileException.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/DuplicateFileException.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/DuplicateFileException.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apk.sdk;
+
+import com.facebook.buck.android.apk.sdk.ApkJarBuilder.IZipEntryFilter.ZipAbortException;
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.File;
+
+/** An exception thrown during packaging of an APK file. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public final class DuplicateFileException extends ZipAbortException {
+  private static final long serialVersionUID = 1L;
+  private final String mArchivePath;
+  private final File mFile1;
+  private final File mFile2;
+
+  public DuplicateFileException(String archivePath, File file1, File file2) {
+    super();
+    mArchivePath = archivePath;
+    mFile1 = file1;
+    mFile2 = file2;
+  }
+
+  public String getArchivePath() {
+    return mArchivePath;
+  }
+
+  public File getFile1() {
+    return mFile1;
+  }
+
+  public File getFile2() {
+    return mFile2;
+  }
+
+  @Override
+  public String getMessage() {
+    return "Duplicate files at the same path inside the APK";
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/IArchiveBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/IArchiveBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/IArchiveBuilder.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apk.sdk;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.File;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface IArchiveBuilder {
+
+  /**
+   * Adds a file to the archive at a given path
+   *
+   * @param file the file to add
+   * @param archivePath the path of the file inside the APK archive.
+   * @throws ApkCreationException if an error occurred
+   * @throws SealedApkException if the APK is already sealed.
+   * @throws DuplicateFileException if a file conflicts with another already added to the APK at the
+   *     same location inside the APK archive.
+   */
+  void addFile(File file, String archivePath)
+      throws ApkCreationException, SealedApkException, DuplicateFileException;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/SealedApkException.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/SealedApkException.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apk/sdk/SealedApkException.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apk.sdk;
+
+import com.facebook.infer.annotation.Nullsafe;
+
+/** An exception thrown when trying to add files to a sealed APK. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public final class SealedApkException extends Exception {
+  private static final long serialVersionUID = 1L;
+
+  public SealedApkException(String format, Object... args) {
+    super(String.format(format, args));
+  }
+
+  public SealedApkException(Throwable cause, String format, Object... args) {
+    super(String.format(format, args), cause);
+  }
+
+  public SealedApkException(Throwable cause) {
+    super(cause);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModule.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModule.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModule.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apkmodule
+
+data class APKModule(val name: String) : Comparable<APKModule> {
+  val isRootModule: Boolean
+    get() = isRootModule(name)
+
+  val canaryClassName: String
+    get() =
+        if (isRootModule) {
+          "secondary"
+        } else {
+          String.format("store%04x", name.hashCode() and 0xFFFF)
+        }
+
+  override fun compareTo(o: APKModule): Int {
+    if (this == o) {
+      return 0
+    }
+
+    return name.compareTo(o.name)
+  }
+
+  companion object {
+    const val ROOT_APKMODULE_NAME: String = "dex"
+
+    @JvmStatic
+    fun isRootModule(moduleName: String): Boolean {
+      return moduleName == ROOT_APKMODULE_NAME
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleGraph.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleGraph.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleGraph.java
@@ -0,0 +1,740 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apkmodule;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.util.graph.AbstractBreadthFirstTraversal;
+import com.facebook.buck.core.util.graph.DirectedAcyclicGraph;
+import com.facebook.buck.core.util.graph.MutableDirectedGraph;
+import com.facebook.buck.io.file.PathMatcher;
+import com.facebook.buck.jvm.java.classes.ClasspathTraversal;
+import com.facebook.buck.jvm.java.classes.ClasspathTraverser;
+import com.facebook.buck.jvm.java.classes.DefaultClasspathTraverser;
+import com.facebook.buck.jvm.java.classes.FileLike;
+import com.facebook.buck.util.MoreSuppliers;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMap.Builder;
+import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSetMultimap;
+import com.google.common.collect.ImmutableSortedMap;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.collect.Multimap;
+import com.google.common.collect.MultimapBuilder;
+import com.google.common.collect.Ordering;
+import com.google.common.collect.Sets;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Utility class for grouping sets of targets and their dependencies into APK Modules containing
+ * their exclusive dependencies. Targets that are dependencies of the root target are included in
+ * the root. Targets that have dependencies in two are more groups are put the APKModule that
+ * represents the dependent modules minimal cover based on the declared dependencies given. If the
+ * minimal cover contains more than one APKModule, the target will belong to a new shared APKModule
+ * that is a dependency of all APKModules in the minimal cover.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class APKModuleGraph<BuildTargetType extends Comparable<BuildTargetType>> {
+
+  private final TargetGraphInterface<BuildTargetType> targetGraph;
+  private final BuildTargetType target;
+
+  private final Optional<ImmutableMap<String, ImmutableList<BuildTargetType>>>
+      suppliedSeedConfigMap;
+
+  private final Optional<ImmutableMap<String, ImmutableList<String>>> appModuleDependencies;
+
+  private final Optional<List<BuildTargetType>> denylistModules;
+
+  /**
+   * This is the computed in the constructor - this is the global view of how every module is laid
+   * out
+   */
+  private final ImmutableSortedMap<APKModule, ImmutableSet<BuildTargetType>> moduleToTarget;
+
+  private final Set<UndeclaredDependency> undeclaredDependencies = new HashSet<>();
+
+  /** This is the set of targets reachable by the root that does NOT pass through a seed. */
+  private final Supplier<ImmutableSet<BuildTargetType>> rootTargetsSupplier =
+      MoreSuppliers.memoize(this::generateRootTargets);
+
+  private final Supplier<ImmutableMap<BuildTargetType, APKModule>> targetToModuleMapSupplier =
+      MoreSuppliers.memoize(
+          () -> {
+            Builder<BuildTargetType, APKModule> mapBuilder = ImmutableMap.builder();
+            new AbstractBreadthFirstTraversal<APKModule>(getGraph().getNodesWithNoIncomingEdges()) {
+              @Override
+              public ImmutableSet<APKModule> visit(APKModule node) {
+                if (node.equals(getRootAPKModule())) {
+                  return ImmutableSet.of();
+                }
+                getBuildTargets(node).forEach(input -> mapBuilder.put(input, node));
+                return getGraph().getOutgoingNodesFor(node);
+              }
+            }.start();
+            return mapBuilder.build();
+          });
+
+  private APKModule rootAPKModule = new APKModule(APKModule.ROOT_APKMODULE_NAME);
+
+  private final DirectedAcyclicGraph<APKModule> graph;
+
+  private final Supplier<DirectedAcyclicGraph<String>> declaredDependencyGraphSupplier =
+      MoreSuppliers.memoize(this::generateDeclaredDependencyGraph);
+
+  private final Supplier<DirectedAcyclicGraph<String>> detectedDepAndDeclaredDepGraphSupplier =
+      MoreSuppliers.memoize(this::generateDetectedDependencyAndDeclaredDependencyGraph);
+
+  private final Supplier<ImmutableSet<APKModule>> modulesSupplier =
+      MoreSuppliers.memoize(
+          () -> {
+            ImmutableSet.Builder<APKModule> moduleBuilder = ImmutableSet.builder();
+            new AbstractBreadthFirstTraversal<APKModule>(getRootAPKModule()) {
+              @Override
+              public Iterable<APKModule> visit(APKModule apkModule) throws RuntimeException {
+                moduleBuilder.add(apkModule);
+                return getGraph().getIncomingNodesFor(apkModule);
+              }
+            }.start();
+            return moduleBuilder.build();
+          });
+
+  private final Supplier<ImmutableMultimap<BuildTargetType, String>> sharedSeedsSupplier =
+      MoreSuppliers.memoize(this::generateSharedSeeds);
+
+  private final Supplier<Optional<ImmutableMap<String, ImmutableList<BuildTargetType>>>>
+      configMapSupplier = MoreSuppliers.memoize(this::generateSeedConfigMap);
+
+  private final Supplier<Optional<ImmutableMap<BuildTargetType, String>>> seedTargetMapSupplier =
+      MoreSuppliers.memoize(this::generateSeedTargetMap);
+
+  /**
+   * Constructor for the {@code APKModule} graph generator object that produces a graph with only a
+   * root module.
+   */
+  public APKModuleGraph(TargetGraphInterface<BuildTargetType> targetGraph, BuildTargetType target) {
+    this(targetGraph, target, Optional.empty(), Optional.empty(), Optional.empty());
+  }
+
+  /**
+   * Constructor for the {@code APKModule} graph generator object
+   *
+   * @param targetGraph The full target graph of the build
+   * @param target The root target to use to traverse the graph
+   * @param suppliedSeedConfigMap A map of names to seed targets to use for creating {@code
+   *     APKModule}.
+   * @param appModuleDependencies
+   *     <p>a mapping of declared dependencies between module names. If a APKModule <b>m1</b>
+   *     depends on <b>m2</b>, it implies to buck that in order for <b>m1</b> to be available for
+   *     execution <b>m2</b> must be available for use as well. Because of this, we can say that
+   *     including a buck target in <b>m2</b> effectively includes the buck-target in <b>m2's</b>
+   *     dependent <b>m1</b>. In other words, <b>m2</b> covers <b>m1</b>. Therefore, if a buck
+   *     target is required by both these modules, we can safely place it in the minimal cover which
+   *     is the APKModule <b>m2</b>.
+   * @param denylistModules A list of targets that will NOT be included in any module.
+   */
+  public APKModuleGraph(
+      TargetGraphInterface<BuildTargetType> targetGraph,
+      BuildTargetType target,
+      Optional<ImmutableMap<String, ImmutableList<BuildTargetType>>> suppliedSeedConfigMap,
+      Optional<ImmutableMap<String, ImmutableList<String>>> appModuleDependencies,
+      Optional<List<BuildTargetType>> denylistModules) {
+    this.targetGraph = targetGraph;
+    this.target = target;
+    this.suppliedSeedConfigMap = suppliedSeedConfigMap;
+    this.appModuleDependencies = appModuleDependencies;
+    this.denylistModules = denylistModules;
+
+    Map<APKModule, ImmutableSet.Builder<BuildTargetType>> builder = new HashMap<>();
+    graph = generateGraph(builder);
+
+    ImmutableSortedMap.Builder<APKModule, ImmutableSet<BuildTargetType>> mapBuilder =
+        ImmutableSortedMap.naturalOrder();
+    mapBuilder.put(getRootAPKModule(), ImmutableSortedSet.copyOf(rootTargetsSupplier.get()));
+    for (Map.Entry<APKModule, ImmutableSet.Builder<BuildTargetType>> entry : builder.entrySet()) {
+      mapBuilder.put(entry.getKey(), ImmutableSortedSet.copyOf(entry.getValue().build()));
+    }
+    moduleToTarget = mapBuilder.build();
+  }
+
+  public ImmutableSortedMap<APKModule, ImmutableSortedSet<APKModule>> toOutgoingEdgesMap() {
+    return getAPKModules().stream()
+        .collect(
+            ImmutableSortedMap.toImmutableSortedMap(
+                Ordering.natural(),
+                module -> module,
+                module -> ImmutableSortedSet.copyOf(getGraph().getOutgoingNodesFor(module))));
+  }
+
+  private Optional<ImmutableMap<String, ImmutableList<BuildTargetType>>> generateSeedConfigMap() {
+    return suppliedSeedConfigMap;
+  }
+
+  private Optional<ImmutableMap<BuildTargetType, String>> generateSeedTargetMap() {
+    if (suppliedSeedConfigMap.isPresent()) {
+      final Map<BuildTargetType, String> seedTargetMap = new HashMap<>();
+      for (final ImmutableMap.Entry<String, ImmutableList<BuildTargetType>> suppliedSeedConfig :
+          suppliedSeedConfigMap.get().entrySet()) {
+        for (final BuildTargetType seedTarget : suppliedSeedConfig.getValue()) {
+          seedTargetMap.put(seedTarget, suppliedSeedConfig.getKey());
+        }
+      }
+      return Optional.of(ImmutableMap.copyOf(seedTargetMap));
+    }
+
+    return Optional.empty();
+  }
+
+  /**
+   * Lazy generate the graph on first use
+   *
+   * @return the DAG representing APKModules and their dependency relationships
+   */
+  public DirectedAcyclicGraph<APKModule> getGraph() {
+    return graph;
+  }
+
+  /**
+   * Lazy generate the declared dependency graph.
+   *
+   * @return the DAG representing the declared dependency relationship of declared app module
+   *     configurations.
+   */
+  private DirectedAcyclicGraph<String> getDeclaredDependencyGraph() {
+    return declaredDependencyGraphSupplier.get();
+  }
+
+  /**
+   * Lazy generate the detected dep and declared dependency graph. Undeclared dependencies are
+   * detected and automatically added to this DAG.
+   *
+   * @return the DAG representing the declared dependency relationship of declared app module
+   *     configurations.
+   */
+  private DirectedAcyclicGraph<String> getDetectedDepAndDeclaredDepGraph() {
+    return detectedDepAndDeclaredDepGraphSupplier.get();
+  }
+
+  /**
+   * Get the APKModule representing the core application that is always included in the apk
+   *
+   * @return the root APK Module
+   */
+  public APKModule getRootAPKModule() {
+    return rootAPKModule;
+  }
+
+  public ImmutableSet<APKModule> getAPKModules() {
+    return modulesSupplier.get();
+  }
+
+  public Optional<ImmutableMap<String, ImmutableList<BuildTargetType>>> getSeedConfigMap() {
+    verifyNoSharedSeeds();
+    return configMapSupplier.get();
+  }
+
+  public Optional<ImmutableMap<BuildTargetType, String>> getSeedTargetMap() {
+    return seedTargetMapSupplier.get();
+  }
+
+  /**
+   * Get the Module that contains the given target
+   *
+   * @param target target to serach for in modules
+   * @return the module that contains the target
+   */
+  public APKModule findModuleForTarget(BuildTargetType target) {
+    APKModule module = targetToModuleMapSupplier.get().get(target);
+    return (module == null ? getRootAPKModule() : module);
+  }
+
+  public Optional<List<BuildTargetType>> getDenyListModules() {
+    return denylistModules;
+  }
+
+  /**
+   * Group the classes in the input jars into a multimap based on the APKModule they belong to
+   *
+   * @param apkModuleToJarPathMap the mapping of APKModules to the path for the jar files
+   * @param translatorFunction function used to translate the class names to obfuscated names
+   * @return The mapping of APKModules to the class names they contain
+   * @throws IOException
+   */
+  public static ImmutableMultimap<APKModule, String> getAPKModuleToClassesMap(
+      ImmutableMultimap<APKModule, Path> apkModuleToJarPathMap,
+      Function<String, String> translatorFunction,
+      AbsPath rootPath,
+      ImmutableSet<PathMatcher> ignoredPaths)
+      throws IOException {
+    ImmutableMultimap.Builder<APKModule, String> builder = ImmutableSetMultimap.builder();
+    if (!apkModuleToJarPathMap.isEmpty()) {
+      for (APKModule dexStore : apkModuleToJarPathMap.keySet()) {
+        for (Path jarFilePath : apkModuleToJarPathMap.get(dexStore)) {
+          ClasspathTraverser classpathTraverser = new DefaultClasspathTraverser();
+          classpathTraverser.traverse(
+              new ClasspathTraversal(ImmutableSet.of(jarFilePath), rootPath, ignoredPaths) {
+                @Override
+                public void visit(FileLike entry) {
+                  if (!entry.getRelativePath().endsWith(".class")) {
+                    // ignore everything but class files in the jar.
+                    return;
+                  }
+
+                  String classpath = entry.getRelativePath().replaceAll("\\.class$", "");
+
+                  if (translatorFunction.apply(classpath) != null) {
+                    builder.put(dexStore, translatorFunction.apply(classpath));
+                  }
+                }
+              });
+        }
+      }
+    }
+    return builder.build();
+  }
+
+  /**
+   * Generate the graph by identifying root targets, then marking targets with the seeds they are
+   * reachable with, then consolidating the targets reachable by multiple seeds into shared modules
+   *
+   * @return The graph of APKModules with edges representing dependencies between modules
+   */
+  private DirectedAcyclicGraph<APKModule> generateGraph(
+      Map<APKModule, ImmutableSet.Builder<BuildTargetType>> builder) {
+    MutableDirectedGraph<APKModule> apkModuleGraph = new MutableDirectedGraph<>();
+
+    apkModuleGraph.addNode(getRootAPKModule());
+
+    if (getSeedConfigMap().isPresent()) {
+      Multimap<BuildTargetType, String> targetToContainingApkModulesMap =
+          mapTargetsToContainingModules();
+      generateSharedModules(apkModuleGraph, targetToContainingApkModulesMap, builder);
+      // add declared dependencies as well.
+      Map<String, APKModule> nameToAPKModules = new HashMap<>();
+      for (APKModule node : apkModuleGraph.getNodes()) {
+        nameToAPKModules.put(node.getName(), node);
+      }
+      final DirectedAcyclicGraph<String> detectedDepAndDeclaredDepGraph =
+          getDetectedDepAndDeclaredDepGraph();
+      for (String source : detectedDepAndDeclaredDepGraph.getNodes()) {
+        for (String sink : detectedDepAndDeclaredDepGraph.getOutgoingNodesFor(source)) {
+          apkModuleGraph.addEdge(
+              Objects.requireNonNull(nameToAPKModules.get(source)),
+              Objects.requireNonNull(nameToAPKModules.get(sink)));
+        }
+      }
+    }
+
+    return new DirectedAcyclicGraph<>(apkModuleGraph);
+  }
+
+  private DirectedAcyclicGraph<String> generateDetectedDependencyAndDeclaredDependencyGraph() {
+    final DirectedAcyclicGraph<String> declaredDependencies = generateDeclaredDependencyGraph();
+    final DirectedAcyclicGraph.Builder<String> graph = DirectedAcyclicGraph.serialBuilder();
+    for (final String node : declaredDependencies.getNodes()) {
+      graph.addNode(node);
+      for (final String outgoingNode : declaredDependencies.getOutgoingNodesFor(node)) {
+        graph.addEdge(node, outgoingNode);
+      }
+    }
+    for (final UndeclaredDependency undeclaredDependency : undeclaredDependencies) {
+      graph.addEdge(undeclaredDependency.sourceModule, undeclaredDependency.depModule);
+    }
+    return graph.build();
+  }
+
+  private DirectedAcyclicGraph<String> generateDeclaredDependencyGraph() {
+    DirectedAcyclicGraph.Builder<String> declaredDependencyGraph =
+        DirectedAcyclicGraph.serialBuilder();
+
+    if (appModuleDependencies.isPresent()) {
+      for (Map.Entry<String, ImmutableList<String>> moduleDependencies :
+          appModuleDependencies.get().entrySet()) {
+        for (String moduleDep : moduleDependencies.getValue()) {
+          declaredDependencyGraph.addEdge(moduleDependencies.getKey(), moduleDep);
+        }
+      }
+    }
+
+    DirectedAcyclicGraph<String> result = declaredDependencyGraph.build();
+    verifyNoUnrecognizedModulesInDependencyGraph(result);
+    return result;
+  }
+
+  private void verifyNoUnrecognizedModulesInDependencyGraph(
+      DirectedAcyclicGraph<String> dependencyGraph) {
+    Set<String> configModules =
+        getSeedConfigMap().isPresent() ? getSeedConfigMap().get().keySet() : new HashSet<>();
+    Set<String> unrecognizedModules = new HashSet<>(dependencyGraph.getNodes());
+    unrecognizedModules.removeAll(configModules);
+    if (!unrecognizedModules.isEmpty()) {
+      StringBuilder errorString =
+          new StringBuilder("Unrecognized App Modules in Dependency Graph: ");
+      for (String module : unrecognizedModules) {
+        errorString.append(module).append(" ");
+      }
+      throw new IllegalStateException(errorString.toString());
+    }
+  }
+
+  /**
+   * This walks through the target graph starting from the root target and adds all reachable
+   * targets that are not seed targets to the root module
+   *
+   * @return all reachable targets that are not seed targets to the root module
+   */
+  private ImmutableSet<BuildTargetType> generateRootTargets() {
+    ImmutableSet.Builder<BuildTargetType> rootTargetsBuilder = new ImmutableSet.Builder<>();
+    if (!targetGraph.isEmpty()) {
+      Set<HasBuildTargetAndBuildDeps<BuildTargetType>> rootNodes = new HashSet<>();
+      rootNodes.add(targetGraph.get(target));
+      if (denylistModules.isPresent()) {
+        for (BuildTargetType targetModule : denylistModules.get()) {
+          rootNodes.add(targetGraph.get(targetModule));
+          rootTargetsBuilder.add(targetModule);
+        }
+      }
+      new AbstractBreadthFirstTraversal<HasBuildTargetAndBuildDeps<BuildTargetType>>(rootNodes) {
+        @Override
+        public Iterable<HasBuildTargetAndBuildDeps<BuildTargetType>> visit(
+            HasBuildTargetAndBuildDeps<BuildTargetType> node) {
+
+          ImmutableSet.Builder<HasBuildTargetAndBuildDeps<BuildTargetType>> depsBuilder =
+              ImmutableSet.builder();
+          for (BuildTargetType depTarget : node.getBuildDeps()) {
+            if (!isSeedTarget(depTarget)) {
+              depsBuilder.add(targetGraph.get(depTarget));
+              rootTargetsBuilder.add(depTarget);
+            }
+          }
+          return depsBuilder.build();
+        }
+      }.start();
+    }
+    return rootTargetsBuilder.build();
+  }
+
+  /**
+   * For each seed target, find its reachable targets and mark them in a multimap as being reachable
+   * by that module for later sorting into exclusive and shared targets
+   *
+   * @return the Multimap containing targets and the seed modules that contain them
+   */
+  private Multimap<BuildTargetType, String> mapTargetsToContainingModules() {
+    final DirectedAcyclicGraph<String> declaredDependencies = getDeclaredDependencyGraph();
+    final DirectedAcyclicGraph.Builder<String> moduleGraph = DirectedAcyclicGraph.serialBuilder();
+    Multimap<BuildTargetType, String> targetToContainingApkModuleNameMap =
+        MultimapBuilder.treeKeys().treeSetValues().build();
+    for (Map.Entry<String, ImmutableList<BuildTargetType>> seedConfig :
+        getSeedConfigMap().get().entrySet()) {
+      final String seedModuleName = seedConfig.getKey();
+      for (BuildTargetType seedTarget : seedConfig.getValue()) {
+        final Set<BuildTargetType> seedBuildDeps = targetGraph.get(seedTarget).getBuildDeps();
+        targetToContainingApkModuleNameMap.put(seedTarget, seedModuleName);
+        new AbstractBreadthFirstTraversal<HasBuildTargetAndBuildDeps<BuildTargetType>>(
+            targetGraph.get(seedTarget)) {
+          @Override
+          public ImmutableSet<HasBuildTargetAndBuildDeps<BuildTargetType>> visit(
+              HasBuildTargetAndBuildDeps<BuildTargetType> node) {
+            ImmutableSet.Builder<HasBuildTargetAndBuildDeps<BuildTargetType>> depsBuilder =
+                ImmutableSet.builder();
+            for (final BuildTargetType depTarget : node.getBuildDeps()) {
+              final String depTargetModuleName = getSeedModule(depTarget);
+              if (depTargetModuleName != null) {
+                moduleGraph.addNode(depTargetModuleName);
+              }
+              if (!rootTargetsSupplier.get().contains(depTarget)) {
+                if (isSeedTarget(depTarget)) {
+                  if (depTargetModuleName != null
+                      && depTargetModuleName != seedModuleName
+                      && seedBuildDeps.contains(depTarget)) {
+                    // Mark depTargetModuleName as a dependency of seedModuleName
+                    moduleGraph.addEdge(seedModuleName, depTargetModuleName);
+                  }
+                } else {
+                  depsBuilder.add(targetGraph.get(depTarget));
+                  targetToContainingApkModuleNameMap.put(depTarget, seedModuleName);
+                }
+              }
+            }
+            return depsBuilder.build();
+          }
+        }.start();
+      }
+    }
+    undeclaredDependencies.addAll(getUndeclaredDeps(moduleGraph.build(), declaredDependencies));
+
+    // Now to generate the minimal covers of APKModules for each set of APKModules that contain
+    // a buildTarget
+    Multimap<BuildTargetType, String> targetModuleEntriesToRemove =
+        MultimapBuilder.treeKeys().treeSetValues().build();
+    for (BuildTargetType key : targetToContainingApkModuleNameMap.keySet()) {
+      Collection<String> modulesForTarget = targetToContainingApkModuleNameMap.get(key);
+      new AbstractBreadthFirstTraversal<String>(modulesForTarget) {
+        @Override
+        public Iterable<String> visit(String moduleName) throws RuntimeException {
+          Collection<String> dependentModules =
+              declaredDependencies.getIncomingNodesFor(moduleName);
+          for (String dependent : dependentModules) {
+            if (modulesForTarget.contains(dependent)) {
+              targetModuleEntriesToRemove.put(key, dependent);
+            }
+          }
+          return dependentModules;
+        }
+      }.start();
+    }
+    for (Map.Entry<BuildTargetType, String> entryToRemove : targetModuleEntriesToRemove.entries()) {
+      targetToContainingApkModuleNameMap.remove(entryToRemove.getKey(), entryToRemove.getValue());
+    }
+    return targetToContainingApkModuleNameMap;
+  }
+
+  private Set<UndeclaredDependency> getUndeclaredDeps(
+      final DirectedAcyclicGraph<String> detectedModuleGraph,
+      final DirectedAcyclicGraph<String> declaredDeps) {
+    final Set<UndeclaredDependency> undeclaredDependencies = new HashSet<>();
+    final Set<String> addedModules = new HashSet<>();
+    final Queue<String> moduleGraphQueue = new LinkedList<>();
+    moduleGraphQueue.addAll(detectedModuleGraph.getNodesWithNoIncomingEdges());
+    addedModules.addAll(detectedModuleGraph.getNodesWithNoIncomingEdges());
+    while (!moduleGraphQueue.isEmpty()) {
+      final String currentModule = Objects.requireNonNull(moduleGraphQueue.poll());
+      final Set<String> outgoingModuleGraphNodes =
+          detectedModuleGraph.getOutgoingNodesFor(currentModule);
+      final Set<String> outgoingDeclaredDepNodes = declaredDeps.getOutgoingNodesFor(currentModule);
+      final Set<String> undeclaredDepNodes =
+          Sets.difference(outgoingModuleGraphNodes, outgoingDeclaredDepNodes);
+      if (!undeclaredDepNodes.isEmpty()) {
+        for (final String undeclaredDepNode : undeclaredDepNodes) {
+          if (undeclaredDepNode != null) {
+            undeclaredDependencies.add(new UndeclaredDependency(currentModule, undeclaredDepNode));
+          }
+        }
+      }
+      for (final String edgeModule : outgoingModuleGraphNodes) {
+        if (!addedModules.contains(edgeModule)) {
+          moduleGraphQueue.add(edgeModule);
+          addedModules.add(edgeModule);
+        }
+      }
+    }
+    return undeclaredDependencies;
+  }
+
+  /**
+   * Loop through each of the targets we visited while generating seed modules: If the are exclusive
+   * to that module, add them to that module. If they are not exclusive to that module, find or
+   * create an appropriate shared module and fill out its dependencies
+   *
+   * @param apkModuleGraph the current graph we're building
+   * @param targetToContainingApkModulesMap the targets mapped to the seed targets they are
+   *     reachable from
+   */
+  private void generateSharedModules(
+      MutableDirectedGraph<APKModule> apkModuleGraph,
+      Multimap<BuildTargetType, String> targetToContainingApkModulesMap,
+      Map<APKModule, ImmutableSet.Builder<BuildTargetType>> builder) {
+
+    // Sort the module-covers of all targets to determine shared module names.
+    TreeSet<TreeSet<String>> sortedContainingModuleSets =
+        new TreeSet<>(
+            new Comparator<TreeSet<String>>() {
+              @Override
+              public int compare(TreeSet<String> left, TreeSet<String> right) {
+                int sizeDiff = left.size() - right.size();
+                if (sizeDiff != 0) {
+                  return sizeDiff;
+                }
+                Iterator<String> leftIter = left.iterator();
+                Iterator<String> rightIter = right.iterator();
+                while (leftIter.hasNext()) {
+                  String leftElement = leftIter.next();
+                  String rightElement = rightIter.next();
+                  int stringComparison = leftElement.compareTo(rightElement);
+                  if (stringComparison != 0) {
+                    return stringComparison;
+                  }
+                }
+                return 0;
+              }
+            });
+    for (Map.Entry<BuildTargetType, Collection<String>> entry :
+        targetToContainingApkModulesMap.asMap().entrySet()) {
+      TreeSet<String> containingModuleSet = new TreeSet<>(entry.getValue());
+      sortedContainingModuleSets.add(containingModuleSet);
+    }
+
+    // build modules based on all entries.
+    Map<ImmutableSet<String>, APKModule> combinedModuleHashToModuleMap = new HashMap<>();
+    final Set<String> hashedSharedModuleSet = new HashSet<>();
+    for (TreeSet<String> moduleCover : sortedContainingModuleSets) {
+      final List<String> moduleCoverList = new ArrayList<>(moduleCover);
+      Collections.sort(moduleCoverList);
+      final String joinedModuleName = String.join("_", moduleCoverList);
+      String moduleName = moduleCoverList.size() > 1 ? "s_" + joinedModuleName : joinedModuleName;
+      // there is a hard requirement that module names cannot exceed 50 chars.
+      if (moduleCoverList.size() > 1 && moduleName.length() > 49) {
+        moduleName = "s_" + String.valueOf(moduleName.hashCode() & 0x7FFFFFFF);
+        if (hashedSharedModuleSet.contains(moduleName)) {
+          throw new RuntimeException(
+              "Collision while hashing shared module name " + joinedModuleName);
+        }
+        hashedSharedModuleSet.add(moduleName);
+      }
+      APKModule module = new APKModule(moduleName);
+      combinedModuleHashToModuleMap.put(ImmutableSet.copyOf(moduleCover), module);
+    }
+
+    // add Targets per module;
+    for (Map.Entry<BuildTargetType, Collection<String>> entry :
+        targetToContainingApkModulesMap.asMap().entrySet()) {
+      ImmutableSet<String> containingModuleSet = ImmutableSet.copyOf(entry.getValue());
+      for (Map.Entry<ImmutableSet<String>, APKModule> existingEntry :
+          combinedModuleHashToModuleMap.entrySet()) {
+        if (existingEntry.getKey().equals(containingModuleSet)) {
+          APKModule key = existingEntry.getValue();
+          if (!builder.containsKey(key)) {
+            builder.put(key, new ImmutableSet.Builder<>());
+          }
+          Objects.requireNonNull(builder.get(key)).add(entry.getKey());
+          break;
+        }
+      }
+    }
+
+    // Find the seed modules and add them to the graph
+    Map<String, APKModule> seedModules = new HashMap<>();
+    for (Map.Entry<ImmutableSet<String>, APKModule> entry :
+        combinedModuleHashToModuleMap.entrySet()) {
+      if (entry.getKey().size() == 1) {
+        APKModule seed = entry.getValue();
+        apkModuleGraph.addNode(seed);
+        seedModules.put(entry.getKey().iterator().next(), seed);
+        apkModuleGraph.addEdge(seed, getRootAPKModule());
+      }
+    }
+
+    // Find the shared modules and add them to the graph
+    for (Map.Entry<ImmutableSet<String>, APKModule> entry :
+        combinedModuleHashToModuleMap.entrySet()) {
+      if (entry.getKey().size() > 1) {
+        APKModule shared = entry.getValue();
+        apkModuleGraph.addNode(shared);
+        apkModuleGraph.addEdge(shared, getRootAPKModule());
+        for (String seedName : entry.getKey()) {
+          apkModuleGraph.addEdge(Objects.requireNonNull(seedModules.get(seedName)), shared);
+        }
+      }
+    }
+  }
+
+  private boolean isSeedTarget(BuildTargetType depTarget) {
+    if (!getSeedConfigMap().isPresent()) {
+      return false;
+    }
+    return getSeedModule(depTarget) != null;
+  }
+
+  @Nullable
+  private String getSeedModule(final BuildTargetType seedTarget) {
+    return getSeedTargetMap().get().get(seedTarget);
+  }
+
+  private void verifyNoSharedSeeds() {
+    ImmutableMultimap<BuildTargetType, String> sharedSeeds = sharedSeedsSupplier.get();
+    if (!sharedSeeds.isEmpty()) {
+      StringBuilder errorMessage = new StringBuilder();
+      for (BuildTargetType seed : sharedSeeds.keySet()) {
+        errorMessage
+            .append("BuildTargetType: ")
+            .append(seed)
+            .append(" is used as seed in multiple modules: ");
+        for (String module : sharedSeeds.get(seed)) {
+          errorMessage.append(module).append(' ');
+        }
+        errorMessage.append('\n');
+      }
+      throw new IllegalArgumentException(errorMessage.toString());
+    }
+  }
+
+  private ImmutableMultimap<BuildTargetType, String> generateSharedSeeds() {
+    Optional<ImmutableMap<String, ImmutableList<BuildTargetType>>> seedConfigMap =
+        configMapSupplier.get();
+    HashMultimap<BuildTargetType, String> sharedSeedMapBuilder = HashMultimap.create();
+    if (!seedConfigMap.isPresent()) {
+      return ImmutableMultimap.copyOf(sharedSeedMapBuilder);
+    }
+    // first: invert the seedConfigMap to get BuildTargetType -> Seeds
+    for (Map.Entry<String, ImmutableList<BuildTargetType>> entry : seedConfigMap.get().entrySet()) {
+      for (BuildTargetType buildTarget : entry.getValue()) {
+        sharedSeedMapBuilder.put(buildTarget, entry.getKey());
+      }
+    }
+    // second: remove keys that have only one value.
+    Set<BuildTargetType> nonSharedSeeds = new HashSet<>();
+    for (BuildTargetType buildTarget : sharedSeedMapBuilder.keySet()) {
+      if (sharedSeedMapBuilder.get(buildTarget).size() <= 1) {
+        nonSharedSeeds.add(buildTarget);
+      }
+    }
+    for (BuildTargetType targetToRemove : nonSharedSeeds) {
+      sharedSeedMapBuilder.removeAll(targetToRemove);
+    }
+    return ImmutableMultimap.copyOf(sharedSeedMapBuilder);
+  }
+
+  public ImmutableSet<BuildTargetType> getBuildTargets(APKModule module) {
+    if (moduleToTarget.containsKey(module)) {
+      return moduleToTarget.get(module);
+    } else {
+      return ImmutableSet.of();
+    }
+  }
+
+  private class UndeclaredDependency {
+    final String sourceModule;
+    final String depModule;
+
+    public UndeclaredDependency(final String sourceModule, final String depModule) {
+      this.sourceModule = sourceModule;
+      this.depModule = depModule;
+    }
+
+    @Override
+    public String toString() {
+      return "sourceModule:" + sourceModule + " depModule:" + depModule;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleGraphExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleGraphExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleGraphExecutableMain.java
@@ -0,0 +1,307 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apkmodule;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.util.json.ObjectMappers;
+import com.facebook.infer.annotation.Nullsafe;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSetMultimap;
+import com.google.common.collect.Ordering;
+import com.google.common.collect.TreeMultimap;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Comparator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for constructing an {@link APKModuleGraph} from an external graph. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class APKModuleGraphExecutableMain {
+
+  @Option(name = "--root-target", required = true)
+  private String rootTarget;
+
+  @Option(name = "--target-graph", required = true)
+  private String targetGraphPath;
+
+  @Option(name = "--seed-config-map", required = true)
+  private String seedConfigMapPath;
+
+  @Option(name = "--app-module-dependencies-map", required = true)
+  private String appModuleDependenciesPath;
+
+  @Option(name = "--output", required = true)
+  private String outputPath;
+
+  @Option(name = "--always-in-main-apk-seeds")
+  @Nullable
+  private String alwaysInMainApkSeedsPath = null;
+
+  @Option(name = "--targets-to-jars")
+  @Nullable
+  private String targetsToJarsPath = null;
+
+  @Option(name = "--targets-to-so-names")
+  @Nullable
+  private String targetsToSoNamesPath = null;
+
+  @Option(name = "--targets-to-non-asset-prebuilt-native-library-dirs")
+  @Nullable
+  private String targetsToNonAssetPrebuiltNativeLibraryDirsPath = null;
+
+  @Option(name = "--output-module-info-and-target-to-module-only")
+  private boolean outputModuleInfoAndTargetToModuleOnly;
+
+  public static void main(String[] args) throws IOException {
+    APKModuleGraphExecutableMain main = new APKModuleGraphExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    Map<String, ImmutableList<String>> rawTargetGraphMap =
+        Objects.requireNonNull(
+            ObjectMappers.READER.readValue(
+                ObjectMappers.createParser(Paths.get(targetGraphPath)),
+                new TypeReference<Map<String, ImmutableList<String>>>() {}),
+            "Expected non-null target graph from " + targetGraphPath);
+
+    ExternalTargetGraph targetGraph = buildTargetGraph(rawTargetGraphMap);
+
+    Map<String, ImmutableList<String>> rawSeedConfigMap =
+        Objects.requireNonNull(
+            ObjectMappers.READER.readValue(
+                ObjectMappers.createParser(Paths.get(seedConfigMapPath)),
+                new TypeReference<Map<String, ImmutableList<String>>>() {}),
+            "Expected non-null seed config map from " + seedConfigMapPath);
+    ImmutableMap<String, ImmutableList<ExternalTargetGraph.ExternalBuildTarget>> seedConfigMap =
+        rawSeedConfigMap.entrySet().stream()
+            .collect(
+                ImmutableMap.toImmutableMap(
+                    Map.Entry::getKey,
+                    e ->
+                        e.getValue().stream()
+                            .map(
+                                buildTargetName -> {
+                                  ExternalTargetGraph.ExternalBuildTarget buildTarget =
+                                      targetGraph.getBuildTarget(buildTargetName);
+                                  Preconditions.checkState(
+                                      buildTarget != null,
+                                      "Expected to find a build target for: " + buildTargetName);
+                                  return buildTarget;
+                                })
+                            .collect(ImmutableList.toImmutableList())));
+
+    ImmutableMap<String, ImmutableList<String>> appModuleDependenciesMap =
+        Objects.requireNonNull(
+            ObjectMappers.READER.readValue(
+                ObjectMappers.createParser(Paths.get(appModuleDependenciesPath)),
+                new TypeReference<ImmutableMap<String, ImmutableList<String>>>() {}),
+            "Expected non-null app module dependencies map from " + appModuleDependenciesPath);
+
+    Optional<List<ExternalTargetGraph.ExternalBuildTarget>> alwaysInMainApkSeeds =
+        alwaysInMainApkSeedsPath == null
+            ? Optional.empty()
+            : Optional.of(
+                Files.readAllLines(Paths.get(alwaysInMainApkSeedsPath)).stream()
+                    .map(targetGraph::getBuildTarget)
+                    .filter(Objects::nonNull)
+                    .collect(ImmutableList.toImmutableList()));
+
+    ExternalTargetGraph.ExternalBuildTarget rootBuildTarget =
+        targetGraph.getBuildTarget(rootTarget);
+    Preconditions.checkState(
+        rootBuildTarget != null, "Expected to find a build target for root: " + rootTarget);
+
+    APKModuleGraph<ExternalTargetGraph.ExternalBuildTarget> apkModuleGraph =
+        new APKModuleGraph<>(
+            targetGraph,
+            rootBuildTarget,
+            Optional.of(seedConfigMap),
+            Optional.of(appModuleDependenciesMap),
+            alwaysInMainApkSeeds);
+
+    if (outputModuleInfoAndTargetToModuleOnly) {
+      Files.write(
+          Paths.get(outputPath), getModuleInfoAndTargetToModuleMappingLines(apkModuleGraph));
+      return;
+    }
+
+    Optional<ImmutableMultimap<APKModule, String>> apkModuleToClassesMap = Optional.empty();
+    if (targetsToJarsPath != null) {
+      ImmutableMultimap.Builder<APKModule, Path> builder = ImmutableSetMultimap.builder();
+      for (String line : Files.readAllLines(Paths.get(targetsToJarsPath))) {
+        String[] parts = line.split(" ");
+        Preconditions.checkState(parts.length == 2);
+        ExternalTargetGraph.ExternalBuildTarget target = targetGraph.getBuildTarget(parts[0]);
+        APKModule module =
+            target != null
+                ? apkModuleGraph.findModuleForTarget(target)
+                : apkModuleGraph.getRootAPKModule();
+        builder.put(module, Paths.get(parts[1]));
+      }
+
+      apkModuleToClassesMap =
+          Optional.of(
+              APKModuleGraph.getAPKModuleToClassesMap(
+                  builder.build(),
+                  Function.identity(),
+                  AbsPath.of(Paths.get(".").normalize().toAbsolutePath()),
+                  ImmutableSet.of()));
+    }
+
+    ImmutableMultimap.Builder<APKModule, String> builder = ImmutableSetMultimap.builder();
+    if (targetsToSoNamesPath != null) {
+      for (String line : Files.readAllLines(Paths.get(targetsToSoNamesPath))) {
+        String[] parts = line.split(" ");
+        // First part is the target string, second part is the so name.
+        Preconditions.checkState(parts.length == 2);
+        ExternalTargetGraph.ExternalBuildTarget target = targetGraph.getBuildTarget(parts[0]);
+        APKModule module =
+            target != null
+                ? apkModuleGraph.findModuleForTarget(target)
+                : apkModuleGraph.getRootAPKModule();
+        builder.put(module, parts[1]);
+      }
+    }
+
+    if (targetsToNonAssetPrebuiltNativeLibraryDirsPath != null) {
+      for (String line :
+          Files.readAllLines(Paths.get(targetsToNonAssetPrebuiltNativeLibraryDirsPath))) {
+        String[] parts = line.split(" ");
+        // First part is the target string, second part is the prebuilt native library dir.
+        Preconditions.checkState(parts.length == 2);
+        ExternalTargetGraph.ExternalBuildTarget target = targetGraph.getBuildTarget(parts[0]);
+        APKModule module =
+            target != null
+                ? apkModuleGraph.findModuleForTarget(target)
+                : apkModuleGraph.getRootAPKModule();
+        Path nonAssetPrebuiltNativeLibraryDir = Paths.get(parts[1]);
+        try (Stream<Path> paths = Files.walk(nonAssetPrebuiltNativeLibraryDir)) {
+          paths.forEach(
+              libPath -> {
+                if (!libPath.toFile().isFile()) {
+                  return;
+                }
+                final String soName = libPath.getFileName().toString();
+                builder.put(module, soName);
+              });
+        }
+      }
+    }
+
+    ImmutableMultimap<APKModule, String> apkModuleToNativeLibraryMap = builder.build();
+
+    List<String> metadataLines =
+        APKModuleMetadataUtil.getMetadataLines(
+            apkModuleGraph,
+            ExternalTargetGraph.ExternalBuildTarget::getName,
+            apkModuleToClassesMap,
+            apkModuleToNativeLibraryMap.isEmpty()
+                ? Optional.empty()
+                : Optional.of(apkModuleToNativeLibraryMap));
+
+    Files.write(Paths.get(outputPath), metadataLines);
+  }
+
+  private ExternalTargetGraph buildTargetGraph(
+      Map<String, ImmutableList<String>> rawTargetGraphMap) {
+    ImmutableMap<String, ExternalTargetGraph.ExternalBuildTarget> buildTargetMap =
+        rawTargetGraphMap.keySet().stream()
+            .collect(
+                ImmutableMap.toImmutableMap(
+                    Function.identity(), ExternalTargetGraph.ExternalBuildTarget::new));
+
+    ImmutableMap<ExternalTargetGraph.ExternalBuildTarget, ExternalTargetGraph.ExternalTargetNode>
+        underlyingMap =
+            rawTargetGraphMap.entrySet().stream()
+                .collect(
+                    ImmutableMap.toImmutableMap(
+                        entry -> buildTargetMap.get(entry.getKey()),
+                        entry ->
+                            new ExternalTargetGraph.ExternalTargetNode(
+                                Objects.requireNonNull(buildTargetMap.get(entry.getKey())),
+                                entry.getValue().stream()
+                                    .map(buildTargetMap::get)
+                                    .collect(ImmutableSet.toImmutableSet()))));
+
+    return new ExternalTargetGraph(underlyingMap, buildTargetMap);
+  }
+
+  /**
+   * API is: first line contains single integer N, the number of modules next N lines contain
+   * 'module_name canary_class_name module_dep1 module_dep2 ... module_depN' all other lines contain
+   * 'target module_containing_target'
+   */
+  private List<String> getModuleInfoAndTargetToModuleMappingLines(
+      APKModuleGraph<ExternalTargetGraph.ExternalBuildTarget> apkModuleGraph) {
+    // Module to module deps map is already sorted
+    SortedMap<APKModule, ? extends SortedSet<APKModule>> moduleToDepsMap =
+        apkModuleGraph.toOutgoingEdgesMap();
+    LinkedList<String> metadataLines = new LinkedList<>();
+    metadataLines.add(Integer.toString(moduleToDepsMap.size()));
+    for (Map.Entry<APKModule, ? extends SortedSet<APKModule>> entry : moduleToDepsMap.entrySet()) {
+      APKModule module = entry.getKey();
+      ImmutableList<String> moduleDeps =
+          entry.getValue().stream()
+              .map(APKModule::getName)
+              .collect(ImmutableList.toImmutableList());
+      metadataLines.add(
+          String.format(
+              "%s %s %s",
+              module.getName(), module.getCanaryClassName(), String.join(" ", moduleDeps)));
+    }
+
+    TreeMultimap<APKModule, String> orderedModuleToTargetsMap =
+        TreeMultimap.create(Comparator.comparing(APKModule::getName), Ordering.natural());
+    for (APKModule module : apkModuleGraph.getAPKModules()) {
+      for (ExternalTargetGraph.ExternalBuildTarget target :
+          apkModuleGraph.getBuildTargets(module)) {
+        orderedModuleToTargetsMap.put(module, target.getName());
+      }
+    }
+    for (APKModule module : orderedModuleToTargetsMap.keySet()) {
+      String moduleName = module.getName();
+      for (String target : orderedModuleToTargetsMap.get(module)) {
+        metadataLines.add(String.format("%s %s", target, moduleName));
+      }
+    }
+
+    return metadataLines;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleMetadataUtil.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleMetadataUtil.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/APKModuleMetadataUtil.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apkmodule;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.Multimap;
+import com.google.common.collect.Ordering;
+import com.google.common.collect.TreeMultimap;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.function.Function;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class APKModuleMetadataUtil {
+
+  public static final String CLASS_SECTION_HEADER = "CLASSES";
+  public static final String TARGETS_SECTION_HEADER = "TARGETS";
+  public static final String DEPS_SECTION_HEADER = "DEPS";
+  public static final String LIBRARIES_SECTION_HEADER = "LIBRARIES";
+  public static final String BLACKLIST_SECTION_HEADER = "BLACKLIST";
+  public static final String MODULE_INDENTATION = "  ";
+  public static final String ITEM_INDENTATION = "    ";
+
+  public static <BuildTarget extends Comparable<BuildTarget>> List<String> getMetadataLines(
+      APKModuleGraph<BuildTarget> apkModuleGraph,
+      Function<BuildTarget, String> getFullyQualifiedName,
+      Optional<ImmutableMultimap<APKModule, String>> moduleToClassesMap,
+      Optional<ImmutableMultimap<APKModule, String>> apkModuleToNativeLibraryMap) {
+    TreeMultimap<APKModule, String> orderedModuleToTargetsMap =
+        TreeMultimap.create(Comparator.comparing(APKModule::getName), Ordering.natural());
+    for (APKModule module : apkModuleGraph.getAPKModules()) {
+      for (BuildTarget target : apkModuleGraph.getBuildTargets(module)) {
+        orderedModuleToTargetsMap.put(module, getFullyQualifiedName.apply(target));
+      }
+    }
+
+    // Module to module deps map is already sorted
+    SortedMap<APKModule, ? extends SortedSet<APKModule>> moduleToDepsMap =
+        apkModuleGraph.toOutgoingEdgesMap();
+
+    // Write metadata lines to output
+    LinkedList<String> metadataLines = new LinkedList<>();
+    if (moduleToClassesMap.isPresent()) {
+      // Get module to classes map in sorted order for build determinism and testing
+      TreeMultimap<APKModule, String> orderedModuleToClassesMap =
+          sortModuleToStringsMultimap(moduleToClassesMap.get());
+
+      metadataLines.add(APKModuleMetadataUtil.CLASS_SECTION_HEADER);
+      addModuleToStringsMultimap(orderedModuleToClassesMap, metadataLines);
+    }
+    metadataLines.add(APKModuleMetadataUtil.TARGETS_SECTION_HEADER);
+    addModuleToStringsMultimap(orderedModuleToTargetsMap, metadataLines);
+    if (apkModuleGraph.getDenyListModules().isPresent()) {
+      metadataLines.add(APKModuleMetadataUtil.BLACKLIST_SECTION_HEADER);
+      addBuildTargetList(
+          apkModuleGraph.getDenyListModules().get(), metadataLines, getFullyQualifiedName);
+    }
+    metadataLines.add(APKModuleMetadataUtil.DEPS_SECTION_HEADER);
+    addModuleToModulesMap(moduleToDepsMap, metadataLines);
+
+    // Add libraries metadata
+    if (apkModuleToNativeLibraryMap.isPresent()) {
+      TreeMultimap<APKModule, String> orderedModuleToLibrariesMap =
+          TreeMultimap.create(Comparator.comparing(APKModule::getName), Ordering.natural());
+      orderedModuleToLibrariesMap.putAll(apkModuleToNativeLibraryMap.get());
+      metadataLines.add(APKModuleMetadataUtil.LIBRARIES_SECTION_HEADER);
+      addModuleToStringsMultimap(orderedModuleToLibrariesMap, metadataLines);
+    }
+
+    return metadataLines;
+  }
+
+  private static TreeMultimap<APKModule, String> sortModuleToStringsMultimap(
+      ImmutableMultimap<APKModule, String> multimap) {
+    TreeMultimap<APKModule, String> orderedMap =
+        TreeMultimap.create(Comparator.comparing(APKModule::getName), Ordering.natural());
+    orderedMap.putAll(multimap);
+    return orderedMap;
+  }
+
+  private static void addModuleToStringsMultimap(
+      Multimap<APKModule, String> map, Collection<String> dest) {
+    for (APKModule dexStore : map.keySet()) {
+      dest.add(APKModuleMetadataUtil.MODULE_INDENTATION + dexStore.getName());
+      for (String item : map.get(dexStore)) {
+        dest.add(APKModuleMetadataUtil.ITEM_INDENTATION + item);
+      }
+    }
+  }
+
+  private static void addModuleToModulesMap(
+      Map<APKModule, ? extends Iterable<APKModule>> map, Collection<String> dest) {
+    for (Map.Entry<APKModule, ? extends Iterable<APKModule>> entry : map.entrySet()) {
+      dest.add(APKModuleMetadataUtil.MODULE_INDENTATION + entry.getKey().getName());
+      for (APKModule item : entry.getValue()) {
+        dest.add(APKModuleMetadataUtil.ITEM_INDENTATION + item.getName());
+      }
+    }
+  }
+
+  private static <BuildTarget extends Comparable<BuildTarget>> void addBuildTargetList(
+      List<BuildTarget> buildTargets,
+      Collection<String> dest,
+      Function<BuildTarget, String> getFullyQualifiedName) {
+    for (BuildTarget target : buildTargets) {
+      dest.add(APKModuleMetadataUtil.MODULE_INDENTATION + getFullyQualifiedName.apply(target));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/BUCK
@@ -0,0 +1,77 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+APK_MODULE_ONLY = [
+    "APKModule.kt",
+]
+
+BINARY_SRCS = ["APKModuleGraphExecutableMain.java"]
+
+buck_kotlin_library(
+    name = "module-only",
+    srcs = APK_MODULE_ONLY,
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/android/apkmodule:apkmodule",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [],
+    exported_deps = [],
+)
+
+buck_java_library(
+    name = "apkmodule",
+    srcs = glob(
+        ["*.java"],
+        exclude = APK_MODULE_ONLY + BINARY_SRCS,
+    ),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/android/apkmodule:apkmodule",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/graph:graph",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/classes:classes",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+    exported_deps = [
+        ":module-only",
+    ],
+)
+
+buck_java_library(
+    name = "apkmodule-binary-lib",
+    srcs = BINARY_SRCS,
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/android/apkmodule:apkmodule",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+        "prelude//toolchains/android/src/com/facebook/buck/util/json:json",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        ":apkmodule",
+    ],
+)
+
+buck_java_binary(
+    name = "apkmodule_binary",
+    main_class = "com.facebook.buck.android.apkmodule.APKModuleGraphExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":apkmodule-binary-lib",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/ExternalTargetGraph.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/ExternalTargetGraph.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/ExternalTargetGraph.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apkmodule;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableMap;
+import java.util.Objects;
+import java.util.Set;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * A "target graph" that is constructed based on an external graph, that can then be used to create
+ * an {@link APKModuleGraph}
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+class ExternalTargetGraph implements TargetGraphInterface<ExternalTargetGraph.ExternalBuildTarget> {
+  private final ImmutableMap<ExternalBuildTarget, ExternalTargetNode> map;
+  private final ImmutableMap<String, ExternalBuildTarget> nameToBuildTargetMap;
+
+  public ExternalTargetGraph(
+      ImmutableMap<ExternalBuildTarget, ExternalTargetNode> map,
+      ImmutableMap<String, ExternalBuildTarget> nameToBuildTargetMap) {
+    this.map = map;
+    this.nameToBuildTargetMap = nameToBuildTargetMap;
+  }
+
+  @Nullable
+  ExternalBuildTarget getBuildTarget(String buildTargetName) {
+    return nameToBuildTargetMap.get(buildTargetName);
+  }
+
+  @Override
+  public boolean isEmpty() {
+    return false;
+  }
+
+  @Override
+  public HasBuildTargetAndBuildDeps<ExternalBuildTarget> get(ExternalBuildTarget buildTarget) {
+    return Objects.requireNonNull(map.get(buildTarget));
+  }
+
+  /** A node in an external target graph. */
+  static class ExternalTargetNode implements HasBuildTargetAndBuildDeps<ExternalBuildTarget> {
+    private final ExternalBuildTarget buildTarget;
+    private final Set<ExternalBuildTarget> buildDeps;
+
+    public ExternalTargetNode(ExternalBuildTarget buildTarget) {
+      this(buildTarget, Set.of());
+    }
+
+    public ExternalTargetNode(ExternalBuildTarget buildTarget, Set<ExternalBuildTarget> buildDeps) {
+      this.buildTarget = buildTarget;
+      this.buildDeps = buildDeps;
+    }
+
+    @Override
+    public ExternalBuildTarget getBuildTarget() {
+      return buildTarget;
+    }
+
+    @Override
+    public Set<ExternalBuildTarget> getBuildDeps() {
+      return buildDeps;
+    }
+  }
+
+  /** A representation of a build target that just uses the build target's name */
+  static class ExternalBuildTarget implements Comparable<ExternalBuildTarget> {
+    private final String name;
+
+    public ExternalBuildTarget(String name) {
+      this.name = name;
+    }
+
+    @Override
+    public int compareTo(ExternalBuildTarget o) {
+      return this.name.compareTo(o.name);
+    }
+
+    String getName() {
+      return name;
+    }
+
+    @Override
+    public String toString() {
+      return getClass().getSimpleName() + ":" + Integer.toHexString(hashCode()) + "(" + name + ")";
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/HasBuildTargetAndBuildDeps.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/HasBuildTargetAndBuildDeps.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/HasBuildTargetAndBuildDeps.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apkmodule;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.util.Set;
+
+/** Some object that has a build target. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface HasBuildTargetAndBuildDeps<BuildTarget> {
+  BuildTarget getBuildTarget();
+
+  Set<BuildTarget> getBuildDeps();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/TargetGraphInterface.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/TargetGraphInterface.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/apkmodule/TargetGraphInterface.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.apkmodule;
+
+import com.facebook.infer.annotation.Nullsafe;
+
+/**
+ * Interface for a directed graph of targets that can be traversed by getting the dependencies of
+ * each node.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface TargetGraphInterface<BuildTarget> {
+  boolean isEmpty();
+
+  HasBuildTargetAndBuildDeps<BuildTarget> get(BuildTarget buildTarget);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BUCK
@@ -0,0 +1,51 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "build_config",
+    srcs = [
+        "BuildConfigFields.java",
+        "BuildConfigs.java",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+    exported_deps = [],
+)
+
+buck_java_library(
+    name = "executable",
+    srcs = ["GenerateBuildConfigExecutableMain.java"],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/build_config:generate_build_config_binary",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/util:throwing_print_writer",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        ":build_config",
+    ],
+)
+
+buck_java_binary(
+    name = "generate_build_config_binary",
+    main_class = "com.facebook.buck.android.build_config.GenerateBuildConfigExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":build_config",
+        ":executable",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BuildConfigFields.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BuildConfigFields.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BuildConfigFields.java
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.build_config;
+
+import com.facebook.buck.android.build_config.BuildConfigFields.Field;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Joiner;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * List of fields to add to a generated {@code BuildConfig.java} file. Each field knows its Java
+ * type, variable name, and value.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class BuildConfigFields implements Iterable<Field> {
+
+  /** An individual field in a {@link BuildConfigFields}. */
+  public static class Field {
+
+    private final String type;
+    private final String name;
+    private final String value;
+
+    Field(String type, String name, String value) {
+      this.type = type;
+      this.name = name;
+      this.value = value;
+    }
+
+    public String getType() {
+      return type;
+    }
+
+    public String getName() {
+      return name;
+    }
+
+    public String getValue() {
+      return value;
+    }
+
+    public static Field of(String type, String name, String value) {
+      return new Field(type, name, value);
+    }
+
+    /**
+     * @return a string that could be passed to {@link
+     *     BuildConfigFields#fromFieldDeclarations(Iterable)} such that it could be parsed to return
+     *     a {@link Field} equal to this object.
+     */
+    @Override
+    public String toString() {
+      return String.format("%s %s = %s", getType(), getName(), getValue());
+    }
+
+    @Override
+    public int hashCode() {
+      return Objects.hash(type, name, value);
+    }
+
+    @Override
+    public boolean equals(@Nullable Object obj) {
+      if (this == obj) {
+        return true;
+      }
+      if (obj == null || getClass() != obj.getClass()) {
+        return false;
+      }
+      Field other = (Field) obj;
+      return Objects.equals(type, other.type)
+          && Objects.equals(name, other.name)
+          && Objects.equals(value, other.value);
+    }
+  }
+
+  private static final BuildConfigFields INSTANCE = new BuildConfigFields(ImmutableMap.of());
+
+  private static final Pattern VARIABLE_DEFINITION_PATTERN =
+      Pattern.compile(
+          "(?<type>[a-zA-Z_$][a-zA-Z0-9_.<>]+("
+              + Pattern.quote("[]")
+              + ")?)"
+              + "\\s+"
+              + "(?<name>[a-zA-Z_$][a-zA-Z0-9_$]+)"
+              + "\\s*=\\s*"
+              + "(?<value>.+)");
+
+  private static final ImmutableSet<String> PRIMITIVE_NUMERIC_TYPE_NAMES =
+      ImmutableSet.of("byte", "char", "double", "float", "int", "long", "short");
+
+  private static final Function<String, Field> TRANSFORM =
+      input -> {
+        Matcher matcher = VARIABLE_DEFINITION_PATTERN.matcher(input);
+        if (matcher.matches()) {
+          return Field.of(
+              Objects.requireNonNull(matcher.group("type")),
+              Objects.requireNonNull(matcher.group("name")),
+              Objects.requireNonNull(matcher.group("value")));
+        } else {
+          throw new RuntimeException(
+              String.format("Not a valid BuildConfig variable declaration: %s", input));
+        }
+      };
+
+  private Map<String, BuildConfigFields.Field> nameToField;
+
+  private BuildConfigFields(Map<String, BuildConfigFields.Field> nameToField) {
+    this.nameToField = nameToField;
+  }
+
+  public Map<String, BuildConfigFields.Field> getNameToField() {
+    return nameToField;
+  }
+
+  public static BuildConfigFields of(Map<String, BuildConfigFields.Field> nameToField) {
+    if (nameToField.isEmpty()) {
+      return INSTANCE;
+    }
+    return new BuildConfigFields(nameToField);
+  }
+
+  public static BuildConfigFields of() {
+    return INSTANCE;
+  }
+
+  public static BuildConfigFields fromFieldDeclarations(Iterable<String> declarations) {
+    return fromFields(FluentIterable.from(declarations).transform(TRANSFORM::apply));
+  }
+
+  /**
+   * @return a {@link BuildConfigFields} that contains the specified fields in iteration order.
+   */
+  public static BuildConfigFields fromFields(Iterable<Field> fields) {
+    ImmutableMap<String, Field> entries = FluentIterable.from(fields).uniqueIndex(Field::getName);
+    return of(entries);
+  }
+
+  /**
+   * @return A new {@link BuildConfigFields} with all of the fields from this object, combined with
+   *     all of the fields from the specified {@code fields}. If both objects have fields with the
+   *     same name, the entry from the {@code fields} parameter wins.
+   */
+  public BuildConfigFields putAll(BuildConfigFields fields) {
+
+    ImmutableMap.Builder<String, Field> nameToFieldBuilder = ImmutableMap.builder();
+    nameToFieldBuilder.putAll(fields.getNameToField());
+    for (Field field : this.getNameToField().values()) {
+      if (!fields.getNameToField().containsKey(field.getName())) {
+        nameToFieldBuilder.put(field.getName(), field);
+      }
+    }
+    return of(nameToFieldBuilder.build());
+  }
+
+  /**
+   * Creates the Java code for a {@code BuildConfig.java} file in the specified {@code javaPackage}.
+   *
+   * @param source The build target of the rule that is responsible for generating this
+   *     BuildConfig.java file.
+   * @param javaPackage The Java package for the generated file.
+   * @param useConstantExpressions Whether the value of each field in the generated Java code should
+   *     be the literal value from the {@link Field} (i.e., a constant expression) or a
+   *     non-constant-expression that is guaranteed to evaluate to the literal value.
+   */
+  public String generateBuildConfigDotJava(
+      String source, String javaPackage, boolean useConstantExpressions) {
+
+    StringBuilder builder = new StringBuilder();
+    // By design, we drop the flavor from the BuildTarget (if present), so this debug text makes
+    // more sense to users.
+    builder.append(String.format("// Generated by %s. DO NOT MODIFY.\n", source));
+    builder.append("package ").append(javaPackage).append(";\n");
+    builder.append("public class BuildConfig {\n");
+    builder.append("  private BuildConfig() {}\n");
+
+    String prefix = "  public static final ";
+    for (Field field : ImmutableSortedMap.copyOf(getNameToField()).values()) {
+      String type = field.getType();
+      if ("boolean".equals(type)) {
+        // type is a non-numeric primitive.
+        boolean isTrue = "true".equals(field.getValue());
+        if (!(isTrue || "false".equals(field.getValue()))) {
+          throw new RuntimeException(
+              String.format("expected boolean literal but was: %s", field.getValue()));
+        }
+        String value;
+        if (useConstantExpressions) {
+          value = String.valueOf(isTrue);
+        } else {
+          value = "Boolean.parseBoolean(null)";
+          if (isTrue) {
+            value = "!" + value;
+          }
+        }
+        builder
+            .append(prefix)
+            .append("boolean ")
+            .append(field.getName())
+            .append(" = ")
+            .append(value)
+            .append(";\n");
+      } else {
+        String typeSafeZero = PRIMITIVE_NUMERIC_TYPE_NAMES.contains(type) ? "0" : "null";
+        String defaultValue = field.getValue();
+        if (!useConstantExpressions) {
+          defaultValue = "!Boolean.parseBoolean(null) ? " + defaultValue + " : " + typeSafeZero;
+        }
+        builder
+            .append(prefix)
+            .append(type)
+            .append(" ")
+            .append(field.getName())
+            .append(" = ")
+            .append(defaultValue)
+            .append(";\n");
+      }
+    }
+
+    builder.append("}\n");
+    return builder.toString();
+  }
+
+  /**
+   * @return iterator that enumerates the fields used to construct this {@link BuildConfigFields}.
+   *     The {@link Iterator#remove()} method of the return value is not supported.
+   */
+  @Override
+  public Iterator<Field> iterator() {
+    return getNameToField().values().iterator();
+  }
+
+  @Override
+  public String toString() {
+    return Joiner.on(';').join(getNameToField().values());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BuildConfigs.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BuildConfigs.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/BuildConfigs.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.build_config;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+
+/** Utilities for generating a {@code BuildConfig.java} file for Android. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class BuildConfigs {
+
+  /**
+   * Name of the boolean global variable provided by the standard Android tools to indicate whether
+   * an app was built in debug mode or not.
+   */
+  public static final String DEBUG_CONSTANT = "DEBUG";
+
+  /**
+   * Name of a Buck-specific global variable that indicates whether an app was built using
+   * exopackage.
+   */
+  public static final String IS_EXO_CONSTANT = "IS_EXOPACKAGE";
+
+  /** Name of a global variable that includes the exopackage configuration as a bitmask. */
+  public static final String EXOPACKAGE_FLAGS = "EXOPACKAGE_FLAGS";
+
+  /**
+   * @see #getDefaultBuildConfigFields()
+   */
+  private static final BuildConfigFields DEFAULT_BUILD_CONFIG_CONSTANTS =
+      BuildConfigFields.fromFields(
+          ImmutableList.of(
+              // DEBUG is expected by the standard Android tools.
+              BuildConfigFields.Field.of("boolean", DEBUG_CONSTANT, "true"),
+              // IS_EXOPACKAGE is a value we use internally for checking whether exopackage is being
+              // used.
+              BuildConfigFields.Field.of("boolean", IS_EXO_CONSTANT, "false"),
+              BuildConfigFields.Field.of("int", EXOPACKAGE_FLAGS, "0")));
+
+  /** Utility class: do not instantiate. */
+  private BuildConfigs() {}
+
+  /**
+   * Returns a list of fields (with values) that every {@code BuildConfig.java} should declare. The
+   * default value of each constant may be overridden by the {@code userFields} passed to {@link
+   * #generateBuildConfigDotJava(String, String, boolean, BuildConfigFields)} when generating a
+   * {@code BuildConfig.java}.
+   */
+  public static BuildConfigFields getDefaultBuildConfigFields() {
+    return DEFAULT_BUILD_CONFIG_CONSTANTS;
+  }
+
+  /**
+   * Generates the source code for an Android {@code BuildConfig.java} file with fields specified by
+   * {@code userFields}.
+   *
+   * <p>The output will also contain a constant for every entry in the collection returned by {@link
+   * #getDefaultBuildConfigFields()}.
+   *
+   * <p>If the name of a field in {@code userFields} matches one in the collection returned by
+   * {@link #getDefaultBuildConfigFields()}, the value in the {@code userFields} map will be used.
+   *
+   * @param javaPackage The package for the Java class generated by this method.
+   * @param useConstantExpressions If {@code true}, the value for each static final field in the
+   *     generated class will be declared as the literal value in {@code userFields}. The values of
+   *     such fields can be inlined by {@code javac}.
+   *     <p>If {@code false}, the value for each static final field in the generated class will be
+   *     declared as a non-constant expression that is guaranteed to evaluate to the same value in
+   *     {@code userFields}. This ensures that the generated {@code BuildConfig.java} can still be
+   *     used in Robolectric tests, but does not run the risk of its values being inlined by {@code
+   *     javac}. This is important if the generated {@code BuildConfig} class is going to be swapped
+   *     out by a different implementation by an Android APK.
+   * @param userFields represents the fields that should be declared in the generated {@code
+   *     BuildConfig} class.
+   */
+  public static String generateBuildConfigDotJava(
+      String source,
+      String javaPackage,
+      boolean useConstantExpressions,
+      BuildConfigFields userFields) {
+
+    BuildConfigFields totalFields = getDefaultBuildConfigFields().putAll(userFields);
+    return totalFields.generateBuildConfigDotJava(source, javaPackage, useConstantExpressions);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/GenerateBuildConfigExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/GenerateBuildConfigExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/build_config/GenerateBuildConfigExecutableMain.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.build_config;
+
+import com.facebook.buck.util.ThrowingPrintWriter;
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for generating BuildConfig.java. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class GenerateBuildConfigExecutableMain {
+  @Option(name = "--source", required = true)
+  private String source;
+
+  @Option(name = "--java-package", required = true)
+  private String javaPackage;
+
+  @Option(name = "--use-constant-expressions", required = true)
+  private String useConstantExpressions;
+
+  @Option(name = "--default-values-file", required = true)
+  private String defaultValuesFile;
+
+  @Option(name = "--values-file")
+  @Nullable
+  private String valuesFile;
+
+  @Option(name = "--output", required = true)
+  private String output;
+
+  public static void main(String[] args) throws IOException {
+    GenerateBuildConfigExecutableMain main = new GenerateBuildConfigExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    Path defaultValuesPath = Paths.get(defaultValuesFile);
+    Path outputPath = Paths.get(output);
+
+    BuildConfigFields defaultValues =
+        BuildConfigFields.fromFieldDeclarations(Files.readAllLines(defaultValuesPath));
+
+    BuildConfigFields fields;
+    if (valuesFile == null) {
+      fields = defaultValues;
+    } else {
+      Path valuesPath = Paths.get(valuesFile);
+      fields =
+          defaultValues.putAll(
+              BuildConfigFields.fromFieldDeclarations(Files.readAllLines(valuesPath)));
+    }
+
+    String java =
+        BuildConfigs.generateBuildConfigDotJava(
+            source, javaPackage, Boolean.parseBoolean(useConstantExpressions), fields);
+
+    try (ThrowingPrintWriter writer =
+        new ThrowingPrintWriter(new FileOutputStream(outputPath.toFile()))) {
+      writer.printf(java);
+    }
+
+    System.exit(0);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/buildinfo/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/buildinfo/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/buildinfo/BUCK
@@ -0,0 +1,30 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "SIGNED_JAR_BLOCKLIST", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "buildinfo",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/...",
+        "prelude//toolchains/android/test/com/facebook/buck/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
+
+buck_java_binary(
+    name = "build_info_generator_binary",
+    blocklist = SIGNED_JAR_BLOCKLIST,
+    main_class = "com.facebook.buck.android.buildinfo.BuildInfoGeneratorExecutableMain",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":buildinfo",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/buildinfo/BuildInfoGeneratorExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/buildinfo/BuildInfoGeneratorExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/buildinfo/BuildInfoGeneratorExecutableMain.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.buildinfo;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Objects;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/**
+ * Writes {@code <output-dir>/assets/BuildInfo.json} = {@code {"build_uuid": "<BUCK_BUILD_ID>"}} so
+ * an installed build can be resolved back to the buck2 build that produced the APK (and from there
+ * to its source commit). {@code BUCK_BUILD_ID} is the buck2 trace id that buck2 sets on every
+ * action's environment.
+ *
+ * <p>The {@code apk_build} action invokes this tool, so the baked id refreshes when the APK content
+ * changes and a no-op (cache-hit) rebuild keeps a prior, equally valid id.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class BuildInfoGeneratorExecutableMain {
+  @Option(name = "--output-dir", required = true)
+  private String outputDir;
+
+  public static void main(String[] args) throws IOException {
+    BuildInfoGeneratorExecutableMain main = new BuildInfoGeneratorExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    String buildId = Objects.requireNonNullElse(System.getenv("BUCK_BUILD_ID"), "");
+    Path assetsDir = Files.createDirectories(Paths.get(outputDir).resolve("assets"));
+    // BUCK_BUILD_ID is a buck2 trace id (a UUID), so it needs no JSON escaping.
+    Files.writeString(assetsDir.resolve("BuildInfo.json"), "{\"build_uuid\": \"" + buildId + "\"}");
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleApksBuilderExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleApksBuilderExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleApksBuilderExecutableMain.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.bundle;
+
+import com.android.apksig.ApkSigner;
+import com.android.tools.build.bundletool.androidtools.Aapt2Command;
+import com.android.tools.build.bundletool.androidtools.P7ZipCommand;
+import com.android.tools.build.bundletool.commands.BuildApksCommand;
+import com.facebook.buck.android.apk.ApkSignerUtils;
+import com.facebook.buck.android.apk.KeystoreProperties;
+import com.facebook.buck.android.zipalign.ZipAlign;
+import com.facebook.buck.util.zip.ZipScrubber;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AndroidBundleApksBuilderExecutableMain {
+
+  @Option(name = "--output-apk", required = true)
+  private Path outputApk;
+
+  @Option(name = "--input-bundle", required = true)
+  private Path inputBundle;
+
+  @Option(name = "--p7zip", required = true)
+  private Path p7zipBinaryPath;
+
+  @Option(name = "--aapt2", required = true)
+  private Path aapt2BinaryPath;
+
+  @Option(name = "--zipalign", required = true)
+  private String zipalignTool;
+
+  @Option(name = "--keystore", depends = "--keystore-properties")
+  @Nullable
+  private Path keystorePath = null;
+
+  @Option(name = "--keystore-properties", depends = "--keystore")
+  @Nullable
+  private Path keystorePropertiesPath = null;
+
+  private void run() throws Exception {
+    Path apksDirectory = Files.createTempDirectory("derived.apks");
+    BuildApksCommand.Builder buildApksCommandBuilder =
+        BuildApksCommand.builder()
+            .setApkBuildMode(BuildApksCommand.ApkBuildMode.UNIVERSAL)
+            .setAapt2Command(Aapt2Command.createFromExecutablePath(aapt2BinaryPath))
+            .setP7ZipCommand(P7ZipCommand.defaultP7ZipCommand(p7zipBinaryPath, 4))
+            .setOutputFormat(BuildApksCommand.OutputFormat.DIRECTORY)
+            .setOutputFile(apksDirectory)
+            .setBundlePath(inputBundle);
+
+    buildApksCommandBuilder.build().execute();
+
+    Path universalApkPath = apksDirectory.resolve("universal.apk");
+    Path zipalignedApk = apksDirectory.resolve("universal-zipaligned.apk");
+
+    ZipScrubber.scrubZip(universalApkPath);
+
+    ZipAlign zipAlign =
+        new ZipAlign(zipalignTool, universalApkPath.toString(), zipalignedApk.toString());
+    zipAlign.run();
+
+    if (keystorePath != null && keystorePropertiesPath != null) {
+      KeystoreProperties keystoreProperties =
+          KeystoreProperties.createFromPropertiesFile(keystorePath, keystorePropertiesPath);
+
+      ImmutableList<ApkSigner.SignerConfig> signerConfigs =
+          ApkSignerUtils.getSignerConfigs(keystoreProperties, Files.newInputStream(keystorePath));
+      ApkSignerUtils.signApkFile(zipalignedApk.toFile(), outputApk.toFile(), signerConfigs);
+    } else {
+      Files.copy(zipalignedApk, outputApk);
+    }
+  }
+
+  public static void main(String[] args) throws IOException {
+    AndroidBundleApksBuilderExecutableMain main = new AndroidBundleApksBuilderExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    } catch (Exception e) {
+      System.err.println(e.toString());
+      System.exit(1);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleBuilderExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleBuilderExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleBuilderExecutableMain.java
@@ -0,0 +1,287 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.bundle;
+
+import com.android.tools.build.bundletool.commands.BuildBundleCommand;
+import com.facebook.buck.android.apk.sdk.ApkCreationException;
+import com.facebook.buck.android.apk.sdk.DuplicateFileException;
+import com.facebook.buck.android.apk.sdk.SealedApkException;
+import com.facebook.buck.util.zip.ZipScrubber;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashSet;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for building an Android bundle. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AndroidBundleBuilderExecutableMain {
+  @Option(name = "--output-bundle", required = true)
+  private String outputBundle;
+
+  @Option(name = "--path-to-bundle-config-file")
+  @Nullable
+  private String pathToBundleConfigFile = null;
+
+  @Option(name = "--resource-apk", required = true)
+  private String resourceApk;
+
+  @Option(name = "--dex-file", required = true)
+  private String dexFile;
+
+  @Option(name = "--root-module-asset-directories-list", required = true)
+  private String rootModuleAssetDirectoriesList;
+
+  @Option(name = "--non-root-module-asset-directories-list", required = true)
+  private String nonRootModuleAssetDirectoriesList;
+
+  @Option(name = "--non-root-module-asset-native-lib-directories-list", required = true)
+  private String nonRootModuleAssetNativeLibDirectoriesList;
+
+  @Option(name = "--native-libraries-directories-list", required = true)
+  private String nativeLibrariesDirectoriesList;
+
+  @Option(name = "--zip-files-list", required = true)
+  private String zipFilesList;
+
+  @Option(name = "--jar-files-that-may-contain-resources-list", required = true)
+  private String jarFilesThatMayContainResourcesList;
+
+  @Option(name = "--package-meta-inf-version-files")
+  private boolean packageMetaInfVersionFiles;
+
+  @Option(name = "--module-assets-dir")
+  @Nullable
+  private Path moduleAssetsDir = null;
+
+  @Option(name = "--excluded-resources")
+  @Nullable
+  private String excludedResourcesList = null;
+
+  public static void main(String[] args) throws IOException {
+    AndroidBundleBuilderExecutableMain main = new AndroidBundleBuilderExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    ImmutableMap<Path, String> rootModuleAssetDirectories =
+        Files.readAllLines(Paths.get(rootModuleAssetDirectoriesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableMap.toImmutableMap(Function.identity(), x -> ""));
+
+    ImmutableSet<Path> nativeLibraryDirectories =
+        Files.readAllLines(Paths.get(nativeLibrariesDirectoriesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableSet.toImmutableSet());
+
+    ImmutableSet<Path> zipFiles =
+        Files.readAllLines(Paths.get(zipFilesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableSet.toImmutableSet());
+
+    ImmutableSet<Path> jarFilesThatMayContainResources =
+        Files.readAllLines(Paths.get(jarFilesThatMayContainResourcesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableSet.toImmutableSet());
+
+    ImmutableSet<String> excludedResources =
+        excludedResourcesList == null
+            ? ImmutableSet.of()
+            : ImmutableSet.copyOf(Files.readAllLines(Paths.get(excludedResourcesList)));
+
+    ImmutableList.Builder<Path> modulePaths = ImmutableList.builder();
+
+    Path tempDir = Files.createTempDirectory("bundleTempDir");
+    Path rootModuleZip = tempDir.resolve("base.zip");
+    modulePaths.add(rootModuleZip);
+    Path fakeResourcesApk = Files.createFile(tempDir.resolve("fake.txt"));
+    Set<String> perModuleAddedFiles = new HashSet<>();
+    Set<Path> addedSourceFiles = new HashSet<>();
+    try {
+      AndroidBundleUtils.addModule(
+          new ThrowingDuplicateFileListener(),
+          rootModuleZip.toFile(),
+          fakeResourcesApk.toFile(),
+          packageMetaInfVersionFiles,
+          null,
+          /* isBaseModule */ true,
+          Paths.get(resourceApk),
+          ImmutableSet.of(Paths.get(dexFile)),
+          rootModuleAssetDirectories,
+          nativeLibraryDirectories,
+          zipFiles,
+          jarFilesThatMayContainResources,
+          perModuleAddedFiles,
+          addedSourceFiles,
+          excludedResources);
+    } catch (ApkCreationException | SealedApkException e) {
+      throw new RuntimeException(e);
+    } catch (DuplicateFileException e) {
+      throw new RuntimeException(
+          String.format(
+              "Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s",
+              e.getArchivePath(), e.getFile1(), e.getFile2()));
+    }
+
+    ImmutableList<Path> nonRootModuleAssetDirectories =
+        Files.readAllLines(Paths.get(nonRootModuleAssetDirectoriesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableList.toImmutableList());
+    ImmutableList<Path> nonRootModuleAssetNativeLibDirectories =
+        Files.readAllLines(Paths.get(nonRootModuleAssetNativeLibDirectoriesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableList.toImmutableList());
+
+    ImmutableMap.Builder<String, Path> moduleToAssetsApkBuilder = ImmutableMap.builder();
+    if (moduleAssetsDir != null) {
+      for (String module : Objects.requireNonNull(moduleAssetsDir.toFile().list())) {
+        Path assetsApk = moduleAssetsDir.resolve(module).resolve("assets.ap_");
+        Preconditions.checkState(Files.exists(assetsApk));
+        moduleToAssetsApkBuilder.put(module, assetsApk);
+      }
+    }
+    ImmutableMap<String, Path> moduleToAssetsApk = moduleToAssetsApkBuilder.build();
+
+    ImmutableMultimap.Builder<String, Path> moduleToAssetDirBuilder = ImmutableMultimap.builder();
+    ImmutableMultimap.Builder<String, Path> moduleToNativeLibDirBuilder =
+        ImmutableMultimap.builder();
+
+    for (Path nonRootModuleAssetDir : nonRootModuleAssetDirectories) {
+      Path assetsDir = nonRootModuleAssetDir.resolve("assets");
+      if (!assetsDir.toFile().exists()) {
+        continue;
+      }
+      for (String module : Objects.requireNonNull(assetsDir.toFile().list())) {
+        moduleToAssetDirBuilder.put(module, assetsDir.resolve(module));
+      }
+    }
+    /**
+     * Directory structure of nonRootModuleAssetNativeLibDirectories is as follows
+     *
+     * <pre>
+     * assets/
+     *     <module>/
+     *         assets/
+     *             <asset native libs>
+     *         lib/
+     *             <non asset native libs>
+     * </pre>
+     */
+    for (Path nonRootModuleAssetNativeLibDir : nonRootModuleAssetNativeLibDirectories) {
+      Path libDir = nonRootModuleAssetNativeLibDir.resolve("assets");
+      if (!libDir.toFile().exists()) {
+        continue;
+      }
+      for (String module : Objects.requireNonNull(libDir.toFile().list())) {
+        Path assetsDir = libDir.resolve(module).resolve("assets");
+        if (assetsDir.toFile().exists()) {
+          moduleToAssetDirBuilder.put(module, assetsDir);
+        }
+        Path nativeLibDir = libDir.resolve(module).resolve("lib");
+        if (nativeLibDir.toFile().exists()) {
+          moduleToNativeLibDirBuilder.put(module, nativeLibDir);
+        }
+      }
+    }
+
+    ImmutableMultimap<String, Path> moduleToAssetDir = moduleToAssetDirBuilder.build();
+    ImmutableMultimap<String, Path> moduleToNativeLibDir = moduleToNativeLibDirBuilder.build();
+
+    for (String moduleName : moduleToAssetDir.keySet()) {
+      Path outputZip = tempDir.resolve(moduleName + ".zip");
+      modulePaths.add(outputZip);
+      try {
+        perModuleAddedFiles.clear();
+        AndroidBundleUtils.addModule(
+            new ThrowingDuplicateFileListener(),
+            outputZip.toFile(),
+            moduleToAssetsApk.containsKey(moduleName)
+                ? moduleToAssetsApk.get(moduleName).toFile()
+                : fakeResourcesApk.toFile(),
+            false,
+            null,
+            /* isBaseModule */ false,
+            /* resourceApk */ null,
+            /* dexFile */ ImmutableSet.of(),
+            moduleToAssetDir.get(moduleName).stream()
+                .collect(
+                    ImmutableMap.toImmutableMap(
+                        p -> p, p -> String.format("assets/%s", moduleName))),
+            moduleToNativeLibDir.get(moduleName).stream().collect(ImmutableSet.toImmutableSet()),
+            /* zipFiles */ ImmutableSet.of(),
+            /* jarFilesThatMayContainResources */ ImmutableSet.of(),
+            perModuleAddedFiles,
+            addedSourceFiles,
+            excludedResources);
+      } catch (ApkCreationException | SealedApkException e) {
+        throw new RuntimeException(e);
+      } catch (DuplicateFileException e) {
+        throw new RuntimeException(
+            String.format(
+                "Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s",
+                e.getArchivePath(), e.getFile1(), e.getFile2()));
+      }
+    }
+
+    Path outputPath = Paths.get(outputBundle);
+    BuildBundleCommand.Builder bundleBuilder =
+        BuildBundleCommand.builder()
+            .setOutputPath(outputPath)
+            .setOverwriteOutput(true)
+            .setModulesPaths(modulePaths.build());
+
+    if (pathToBundleConfigFile != null) {
+      bundleBuilder.setBundleConfig(Paths.get(pathToBundleConfigFile));
+    }
+    bundleBuilder.build().execute();
+
+    ZipScrubber.scrubZip(outputPath);
+  }
+
+  private static class ThrowingDuplicateFileListener
+      implements AndroidBundleUtils.DuplicateFileListener {
+
+    @Override
+    public void onDuplicateFileAdded(String file) {
+      if (!file.endsWith("/")) {
+        throw new RuntimeException(String.format("File %s has already been added!", file));
+      }
+    }
+
+    @Override
+    public void onDuplicateSourceFileAdded(Path sourceFile) {
+      throw new RuntimeException(
+          String.format("Source file %s has already been added!", sourceFile));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/AndroidBundleUtils.java
@@ -0,0 +1,453 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.bundle;
+
+import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
+
+import com.android.tools.build.bundletool.model.BundleModule;
+import com.facebook.buck.android.apk.sdk.ApkBuilder;
+import com.facebook.buck.android.apk.sdk.ApkCreationException;
+import com.facebook.buck.android.apk.sdk.ApkJarBuilder;
+import com.facebook.buck.android.apk.sdk.DuplicateFileException;
+import com.facebook.buck.android.apk.sdk.IArchiveBuilder;
+import com.facebook.buck.android.apk.sdk.SealedApkException;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Enumeration;
+import java.util.Objects;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import org.jetbrains.annotations.Nullable;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AndroidBundleUtils {
+
+  public interface DuplicateFileListener {
+    void onDuplicateFileAdded(String file);
+
+    void onDuplicateSourceFileAdded(Path sourceFile);
+  }
+
+  public static void addModule(
+      DuplicateFileListener duplicateFileListener,
+      File moduleZipOutputFile,
+      File fakeResourceApkFile,
+      boolean packageMetaInfVersionFiles,
+      @Nullable PrintStream verboseStream,
+      boolean isBaseModule,
+      @Nullable Path resourceApk,
+      ImmutableSet<Path> dexFiles,
+      ImmutableMap<Path, String> assetDirectories,
+      ImmutableSet<Path> nativeLibraryDirectories,
+      ImmutableSet<Path> zipFiles,
+      ImmutableSet<Path> jarFilesThatMayContainResources,
+      Set<String> addedFiles,
+      Set<Path> addedSourceFiles,
+      Set<String> excludedResources)
+      throws ApkCreationException, SealedApkException, DuplicateFileException, IOException {
+
+    ApkBuilder moduleBuilder =
+        new ApkBuilder(
+            moduleZipOutputFile,
+            fakeResourceApkFile,
+            null,
+            packageMetaInfVersionFiles,
+            verboseStream,
+            excludedResources);
+    addModuleFiles(
+        moduleBuilder,
+        isBaseModule,
+        resourceApk,
+        dexFiles,
+        assetDirectories,
+        nativeLibraryDirectories,
+        zipFiles,
+        jarFilesThatMayContainResources,
+        addedFiles,
+        addedSourceFiles,
+        duplicateFileListener,
+        excludedResources);
+    // Build the APK
+    moduleBuilder.sealApk();
+  }
+
+  private static void addModuleFiles(
+      ApkBuilder moduleBuilder,
+      boolean isBaseModule,
+      @Nullable Path resourceApk,
+      ImmutableSet<Path> dexFiles,
+      ImmutableMap<Path, String> assetDirectories,
+      ImmutableSet<Path> nativeLibraryDirectories,
+      ImmutableSet<Path> zipFiles,
+      ImmutableSet<Path> jarFilesThatMayContainResources,
+      Set<String> addedFiles,
+      Set<Path> addedSourceFiles,
+      DuplicateFileListener duplicateFileListener,
+      Set<String> excludedResources)
+      throws ApkCreationException, DuplicateFileException, SealedApkException, IOException {
+
+    for (Path dexFile : dexFiles) {
+      addFile(
+          moduleBuilder,
+          dexFile,
+          Paths.get(BundleModule.DEX_DIRECTORY.toString())
+              .resolve(dexFile.getFileName())
+              .toString(),
+          addedFiles,
+          addedSourceFiles,
+          duplicateFileListener);
+    }
+    if (resourceApk != null) {
+      if (isBaseModule) {
+        packageFile(
+            moduleBuilder,
+            resourceApk.toFile(),
+            addedFiles,
+            addedSourceFiles,
+            duplicateFileListener,
+            excludedResources);
+      } else {
+        processFileForResource(
+            moduleBuilder,
+            resourceApk.toFile(),
+            "",
+            addedFiles,
+            addedSourceFiles,
+            duplicateFileListener);
+      }
+    }
+    for (Path nativeLibraryDirectory : nativeLibraryDirectories) {
+      addNativeLibraries(
+          moduleBuilder,
+          nativeLibraryDirectory.toFile(),
+          addedFiles,
+          addedSourceFiles,
+          duplicateFileListener);
+    }
+    for (Path assetDirectory : assetDirectories.keySet()) {
+      String subFolderName = assetDirectories.get(assetDirectory);
+      addSourceFolder(
+          moduleBuilder,
+          assetDirectory.toFile(),
+          // infer has a hard time detecting that subFolderName can't be nonnull
+          subFolderName == null || subFolderName.isEmpty() ? "" : subFolderName,
+          addedFiles,
+          addedSourceFiles,
+          duplicateFileListener);
+    }
+    for (Path zipFile : zipFiles) {
+      if (!Files.exists(zipFile) || !Files.isRegularFile(zipFile)) {
+        continue;
+      }
+      packageFile(
+          moduleBuilder,
+          zipFile.toFile(),
+          addedFiles,
+          addedSourceFiles,
+          duplicateFileListener,
+          excludedResources);
+    }
+    for (Path jarFile : jarFilesThatMayContainResources) {
+      packageFile(
+          moduleBuilder,
+          jarFile.toFile(),
+          addedFiles,
+          addedSourceFiles,
+          duplicateFileListener,
+          excludedResources);
+    }
+  }
+
+  private static void addFile(
+      IArchiveBuilder builder,
+      Path file,
+      String destination,
+      Set<String> addedFiles,
+      Set<Path> addedSourceFiles,
+      DuplicateFileListener duplicateFileListener)
+      throws SealedApkException, DuplicateFileException, ApkCreationException {
+    if (addedSourceFiles.contains((file))) {
+      duplicateFileListener.onDuplicateSourceFileAdded(file);
+      return;
+    }
+
+    if (addedFiles.contains(destination)) {
+      duplicateFileListener.onDuplicateFileAdded(destination);
+      return;
+    }
+
+    builder.addFile(file.toFile(), destination);
+    addedFiles.add(destination);
+    addedSourceFiles.add(file);
+  }
+
+  private static void addSourceFolder(
+      ApkBuilder builder,
+      File sourceFolder,
+      String destination,
+      Set<String> addedFiles,
+      Set<Path> addedSourceFiles,
+      DuplicateFileListener duplicateFileListener)
+      throws ApkCreationException, DuplicateFileException, SealedApkException {
+    if (sourceFolder.isDirectory()) {
+      File[] files = sourceFolder.listFiles();
+      if (files == null) {
+        return;
+      }
+      for (File file : files) {
+        processFileForResource(
+            builder, file, destination, addedFiles, addedSourceFiles, duplicateFileListener);
+      }
+    } else {
+      if (sourceFolder.exists()) {
+        throw new ApkCreationException("%s is not a folder", sourceFolder);
+      } else {
+        throw new ApkCreationException("%s does not exist", sourceFolder);
+      }
+    }
+  }
+
+  private static void processFileForResource(
+      IArchiveBuilder builder,
+      File file,
+      String path,
+      Set<String> addedFiles,
+      Set<Path> addedSourceFiles,
+      DuplicateFileListener duplicateFileListener)
+      throws DuplicateFileException, ApkCreationException, SealedApkException {
+    path = Paths.get(path).resolve(file.getName()).toString();
+    if (file.isDirectory() && ApkBuilder.checkFolderForPackaging(file.getName())) {
+      if (file.getName().equals(BundleModule.RESOURCES_DIRECTORY.toString())) {
+        path = BundleModule.RESOURCES_DIRECTORY.toString();
+      }
+      File[] files = file.listFiles();
+      if (files == null) {
+        return;
+      }
+      for (File contentFile : files) {
+        processFileForResource(
+            builder, contentFile, path, addedFiles, addedSourceFiles, duplicateFileListener);
+      }
+    } else if (!file.isDirectory() && ApkBuilder.checkFileForPackaging(file.getName())) {
+      if (file.getName().startsWith("classes") && file.getName().endsWith(".dex")) {
+        addFile(
+            builder,
+            file.toPath(),
+            Paths.get(BundleModule.DEX_DIRECTORY.toString()).resolve(file.getName()).toString(),
+            addedFiles,
+            addedSourceFiles,
+            duplicateFileListener);
+      } else if (file.getName().equals(BundleModule.MANIFEST_FILENAME)) {
+        addFile(
+            builder,
+            file.toPath(),
+            Paths.get(BundleModule.MANIFEST_DIRECTORY.toString())
+                .resolve(file.getName())
+                .toString(),
+            addedFiles,
+            addedSourceFiles,
+            duplicateFileListener);
+      } else if (file.getName()
+          .equals(BundleModule.SpecialModuleEntry.RESOURCE_TABLE.getPath().toString())) {
+        addFile(
+            builder,
+            file.toPath(),
+            Paths.get(file.getName()).toString(),
+            addedFiles,
+            addedSourceFiles,
+            duplicateFileListener);
+      } else {
+        addFile(builder, file.toPath(), path, addedFiles, addedSourceFiles, duplicateFileListener);
+      }
+    }
+  }
+
+  private static void addNativeLibraries(
+      ApkBuilder builder,
+      File nativeFolder,
+      Set<String> addedFiles,
+      Set<Path> addedSourceFiles,
+      DuplicateFileListener duplicateFileListener)
+      throws ApkCreationException, SealedApkException, DuplicateFileException {
+    if (!nativeFolder.isDirectory()) {
+      if (nativeFolder.exists()) {
+        throw new ApkCreationException("%s is not a folder", nativeFolder);
+      } else {
+        throw new ApkCreationException("%s does not exist", nativeFolder);
+      }
+    }
+    File[] abiList = nativeFolder.listFiles();
+    if (abiList == null) {
+      return;
+    }
+    for (File abi : abiList) {
+      if (!abi.isDirectory()) {
+        continue;
+      }
+      File[] libs = abi.listFiles();
+      if (libs == null) {
+        continue;
+      }
+      for (File lib : libs) {
+        if (!builder.shouldAddNativeLib(lib)) {
+          continue;
+        }
+        Path libPath =
+            Paths.get(BundleModule.LIB_DIRECTORY.toString())
+                .resolve(abi.getName())
+                .resolve(lib.getName());
+
+        addFile(
+            builder,
+            lib.toPath(),
+            libPath.toString(),
+            addedFiles,
+            addedSourceFiles,
+            duplicateFileListener);
+      }
+    }
+  }
+
+  private static void packageFile(
+      ApkBuilder builder,
+      File original,
+      Set<String> addedFiles,
+      Set<Path> addedSourceFiles,
+      DuplicateFileListener duplicateFileListener,
+      Set<String> excludedResources)
+      throws IOException, ApkCreationException, DuplicateFileException, SealedApkException {
+    if (addedSourceFiles.contains(original.toPath())) {
+      duplicateFileListener.onDuplicateSourceFileAdded(original.toPath());
+      return;
+    }
+    try (ZipFile zipFile = new ZipFile(original)) {
+      Enumeration<? extends ZipEntry> zipEntryEnumeration = zipFile.entries();
+      while (zipEntryEnumeration.hasMoreElements()) {
+        ZipEntry entry = zipEntryEnumeration.nextElement();
+
+        if (!excludedResources.contains(entry.getName()) && isEntryPackageable(entry)) {
+          String location = resolveFileInModule(entry);
+          String destination = Paths.get(location).resolve(entry.getName()).toString();
+          if (entry.isDirectory()) {
+            destination += "/";
+          }
+          addFile(
+              builder,
+              convertZipEntryToFile(zipFile, entry).toPath(),
+              destination,
+              addedFiles,
+              addedSourceFiles,
+              duplicateFileListener);
+        }
+      }
+    }
+  }
+
+  /**
+   * Checks whether a folder and its content is valid for packaging into the .apk as standard Java
+   * resource.
+   *
+   * @param folderName the name of the folder.
+   */
+  private static boolean checkFolderForPackaging(String folderName) {
+    return !folderName.equalsIgnoreCase("nonJvmMain")
+        // nonJvmMain is only useful when build multiplatform and we are building an APK here
+        // commonMain folder is part of multiple AndroidX libraries, exclude it to avoid
+        // duplicate file error
+        && !folderName.equalsIgnoreCase("commonMain")
+        // nativeMain holds platform-specific code for native environments like iOS and macOS,
+        // exclude it to avoid duplicate file error
+        // see https://kotlinlang.org/docs/multiplatform-discover-project.html
+        && !folderName.equalsIgnoreCase("nativeMain");
+  }
+
+  /**
+   * Defines if a zip entry should be packaged in the final bundle.
+   *
+   * @param entry
+   * @return true if entry should be packaged
+   */
+  private static boolean isEntryPackageable(ZipEntry entry) {
+    // split the path into segments.
+    String[] segments = entry.getName().split("/");
+
+    // empty path? skip to next entry.
+    if (segments.length == 0) {
+      return false;
+    }
+
+    // Check each folders to make sure they should be included.
+    // Folders like CVS, .svn, etc.. should already have been excluded from the
+    // jar file, but we need to exclude some other folder (like /META-INF) so
+    // we check anyway.
+    for (int i = 0; i < segments.length - 1; i++) {
+      if (!checkFolderForPackaging(segments[i])) {
+        return false;
+      }
+    }
+
+    return isFileEntryPackageable(entry);
+  }
+
+  private static boolean isFileEntryPackageable(ZipEntry entry) {
+    if (!ApkBuilder.checkFileForPackaging(entry.getName())) {
+      return false;
+    }
+
+    if (entry.getName().startsWith("META-INF")) {
+      return ApkJarBuilder.ALLOWLISTED_META_INF_SERVICES_FILES.contains(entry.getName());
+    } else {
+      return true;
+    }
+  }
+
+  private static String resolveFileInModule(ZipEntry entry) {
+    String location;
+    String fileSeparator = "/";
+    String empty = "";
+
+    if (entry.getName().equals(BundleModule.MANIFEST_FILENAME)) {
+      location = BundleModule.MANIFEST_DIRECTORY.toString();
+
+    } else if (entry.getName().startsWith(BundleModule.LIB_DIRECTORY.toString() + fileSeparator)
+        || entry.getName().startsWith(BundleModule.RESOURCES_DIRECTORY.toString() + fileSeparator)
+        || entry.getName().startsWith(BundleModule.ASSETS_DIRECTORY.toString() + fileSeparator)
+        || entry.getName().startsWith(BundleModule.DEX_DIRECTORY.toString() + fileSeparator)
+        || entry.getName().endsWith(".pb")) {
+      // They are already in the right folder
+      location = empty;
+
+    } else {
+      location = BundleModule.ROOT_DIRECTORY.toString();
+    }
+
+    return location;
+  }
+
+  private static File convertZipEntryToFile(ZipFile zipFile, ZipEntry ze) throws IOException {
+    Path tempFilePath = Files.createTempFile("tempRes", ".txt");
+    File tempFile = tempFilePath.toFile();
+    tempFile.deleteOnExit();
+    try (InputStream in = zipFile.getInputStream(ze)) {
+      Files.copy(Objects.requireNonNull(in), tempFilePath, REPLACE_EXISTING);
+    }
+    return tempFile;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/bundle/BUCK
@@ -0,0 +1,52 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "bundle",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/apk:apk",
+        "prelude//toolchains/android/src/com/facebook/buck/android/apk/sdk:apk_builder",
+        "prelude//toolchains/android/src/com/facebook/buck/android/zipalign:zipalign",
+        "prelude//toolchains/android/src/com/facebook/buck/core/build/execution/context:context",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:bundletool",
+        "prelude//toolchains/android/third-party:gson",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:jsr330",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        "prelude//toolchains/android/third-party/aosp:apksig",
+    ],
+)
+
+buck_java_binary(
+    name = "bundle_builder_binary",
+    main_class = "com.facebook.buck.android.bundle.AndroidBundleBuilderExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":bundle",
+    ],
+)
+
+buck_java_binary(
+    name = "bundle_apks_builder_binary",
+    main_class = "com.facebook.buck.android.bundle.AndroidBundleApksBuilderExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":bundle",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/BUCK
@@ -0,0 +1,17 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "device",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:infer-annotations",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/TargetDevice.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/TargetDevice.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/TargetDevice.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.device;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.util.Optional;
+
+/** Represents information about the device we're targeting. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class TargetDevice {
+
+  private final Type type;
+  private final Optional<String> identifier;
+
+  public enum Type {
+    REAL_DEVICE,
+    EMULATOR,
+    BY_SERIAL
+  }
+
+  public TargetDevice(Type type, Optional<String> identifier) {
+    this.type = type;
+    this.identifier = identifier;
+  }
+
+  public boolean isEmulator() {
+    return type == Type.EMULATOR;
+  }
+
+  public Optional<String> getIdentifier() {
+    return identifier;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/TargetDeviceOptions.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/TargetDeviceOptions.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/device/TargetDeviceOptions.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.device;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.util.Optional;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class TargetDeviceOptions {
+
+  private boolean useEmulatorsOnlyMode;
+
+  private boolean useRealDevicesOnlyMode;
+
+  private Optional<String> serialNumber;
+
+  public TargetDeviceOptions() {
+    this(false, false, Optional.empty());
+  }
+
+  public TargetDeviceOptions(
+      boolean useEmulatorsOnlyMode, boolean useRealDevicesOnlyMode, Optional<String> serialNumber) {
+    this.useEmulatorsOnlyMode = useEmulatorsOnlyMode;
+    this.useRealDevicesOnlyMode = useRealDevicesOnlyMode;
+    this.serialNumber = serialNumber;
+  }
+
+  public boolean isEmulatorsOnlyModeEnabled() {
+    return useEmulatorsOnlyMode;
+  }
+
+  public boolean isRealDevicesOnlyModeEnabled() {
+    return useRealDevicesOnlyMode;
+  }
+
+  public Optional<String> getSerialNumber() {
+    return serialNumber;
+  }
+
+  @Override
+  public String toString() {
+    return "TargetDeviceOptions{"
+        + "useEmulatorsOnlyMode="
+        + useEmulatorsOnlyMode
+        + ", useRealDevicesOnlyMode="
+        + useRealDevicesOnlyMode
+        + ", serialNumber="
+        + serialNumber
+        + '}';
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/BUCK
@@ -0,0 +1,179 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+CANARY = "CanaryUtils.java"
+
+D8_EXECUTABLE_MAIN = "D8ExecutableMain.java"
+
+JAR_SPLITTER_EXECUTABLE_MAIN = "JarSplitterExecutableMain.java"
+
+MULTI_DEX_EXECUTABLE_MAIN = "MultiDexExecutableMain.java"
+
+SECONDARY_DEX_COMPRESSION_EXECUTABLE_MAIN = "SecondaryDexCompressionExecutableMain.java"
+
+buck_java_library(
+    name = "canary",
+    srcs = [CANARY],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+    ],
+)
+
+buck_java_library(
+    name = "dex",
+    srcs = glob(
+        ["*.java"],
+        exclude = [
+            CANARY,
+            D8_EXECUTABLE_MAIN,
+            JAR_SPLITTER_EXECUTABLE_MAIN,
+            MULTI_DEX_EXECUTABLE_MAIN,
+            SECONDARY_DEX_COMPRESSION_EXECUTABLE_MAIN,
+        ],
+    ),
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/apkmodule:module-only",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:d8",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+    ],
+)
+
+buck_java_library(
+    name = "d8_executable_main",
+    srcs = [D8_EXECUTABLE_MAIN],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:d8",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        ":dex",
+    ],
+)
+
+buck_java_binary(
+    name = "run_d8_binary",
+    java_args_for_run_info = select({
+        "DEFAULT": [],
+        "config//os/constraints:windows": [
+            # Cap heap size to prevent JVM ergonomic sizing from requesting
+            # a 2GB mmap that exceeds the Windows paging file limit.
+            "-Xmx256m",
+            # Use SerialGC to minimize native memory overhead — G1GC's region
+            # reservations compound the paging file pressure on Windows.
+            "-XX:+UseSerialGC",
+        ],
+    }),
+    main_class = "com.facebook.buck.android.dex.D8ExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":d8_executable_main",
+        ":dex",
+    ],
+)
+
+buck_java_library(
+    name = "multi_dex_executable_main",
+    srcs = [MULTI_DEX_EXECUTABLE_MAIN],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/apkmodule:module-only",
+        "prelude//toolchains/android/src/com/facebook/buck/android/proguard:translator",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:d8",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        ":canary",
+        ":dex",
+    ],
+)
+
+buck_java_binary(
+    name = "multi_dex_binary",
+    main_class = "com.facebook.buck.android.dex.MultiDexExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":dex",
+        ":multi_dex_executable_main",
+    ],
+)
+
+buck_java_library(
+    name = "secondary_dex_compression_executable_main",
+    srcs = [SECONDARY_DEX_COMPRESSION_EXECUTABLE_MAIN],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/apkmodule:module-only",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        "prelude//toolchains/android/third-party:xz",
+        ":canary",
+        ":dex",
+    ],
+)
+
+buck_java_binary(
+    name = "secondary_dex_compression_binary",
+    main_class = "com.facebook.buck.android.dex.SecondaryDexCompressionExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":secondary_dex_compression_executable_main",
+    ],
+)
+
+buck_java_library(
+    name = "jar_splitter_executable_main",
+    srcs = [JAR_SPLITTER_EXECUTABLE_MAIN],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/proguard:translator",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        ":dex",
+    ],
+)
+
+buck_java_binary(
+    name = "jar_splitter_binary",
+    main_class = "com.facebook.buck.android.dex.JarSplitterExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":jar_splitter_executable_main",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/CanaryUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/CanaryUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/CanaryUtils.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.dex;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.primitives.Bytes;
+import java.nio.charset.StandardCharsets;
+
+/** Helper for creating a "canary" class for the secondary DEX. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class CanaryUtils {
+
+  /**
+   * Produced by:
+   *
+   * <pre>
+   * $ echo -e "package secondary.dex01;\npublic interface Canary {}" > Canary.java
+   * $ javac -target 6 -source 6 Canary.java
+   * $ xxd -c 4 -g 1 Canary.class | cut -d' ' -f2-5 | sed -E 's/(..) ?/(byte) 0x\1, /g'
+   * </pre>
+   */
+  private static final byte[] CANARY_START = {
+    (byte) 0xca, (byte) 0xfe, (byte) 0xba, (byte) 0xbe,
+    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x32,
+    (byte) 0x00, (byte) 0x07, (byte) 0x07, (byte) 0x00,
+    (byte) 0x05, (byte) 0x07, (byte) 0x00, (byte) 0x06,
+    (byte) 0x01, (byte) 0x00, (byte) 0x0a, (byte) 0x53,
+    (byte) 0x6f, (byte) 0x75, (byte) 0x72, (byte) 0x63,
+    (byte) 0x65, (byte) 0x46, (byte) 0x69, (byte) 0x6c,
+    (byte) 0x65, (byte) 0x01, (byte) 0x00, (byte) 0x0b,
+    (byte) 0x43, (byte) 0x61, (byte) 0x6e, (byte) 0x61,
+    (byte) 0x72, (byte) 0x79, (byte) 0x2e, (byte) 0x6a,
+    (byte) 0x61, (byte) 0x76, (byte) 0x61,
+  };
+
+  /*
+    The part between CANARY_START and CANARY_REMAINDER is regenerated
+    to rename the canary class.
+
+    (byte) 0x01, (byte) 0x00, (byte) 0x16,
+    (byte) 0x73, (byte) 0x65, (byte) 0x63, (byte) 0x6f,
+    (byte) 0x6e, (byte) 0x64, (byte) 0x61, (byte) 0x72,
+    (byte) 0x79, (byte) 0x2f, (byte) 0x64, (byte) 0x65,
+    (byte) 0x78, (byte) 0x30, (byte) 0x31, (byte) 0x2f,
+    (byte) 0x43, (byte) 0x61, (byte) 0x6e, (byte) 0x61,
+    (byte) 0x72, (byte) 0x79,
+
+    This corresponds to a constant pool entry of type CONSTANT_Utf8_info
+    CONSTANT_Utf8_info {
+        u1 tag;               0x01    (Utf8 string)
+        u2 length;            0x0016  (22)
+        u1 bytes[length];     secondary/dex01/Canary
+    }
+
+    u1,u2,etc. types in the java class file spec are big-endian
+
+    https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4
+    https://en.wikipedia.org/wiki/Java_class_file
+  */
+  private static final byte[] CANARY_REMAINDER = {
+    (byte) 0x01, (byte) 0x00, (byte) 0x10, (byte) 0x6a,
+    (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2f,
+    (byte) 0x6c, (byte) 0x61, (byte) 0x6e, (byte) 0x67,
+    (byte) 0x2f, (byte) 0x4f, (byte) 0x62, (byte) 0x6a,
+    (byte) 0x65, (byte) 0x63, (byte) 0x74, (byte) 0x06,
+    (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x00,
+    (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+    (byte) 0x01, (byte) 0x00, (byte) 0x03, (byte) 0x00,
+    (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00,
+    (byte) 0x04,
+  };
+
+  /** Utility class: do not instantiate */
+  private CanaryUtils() {}
+
+  /**
+   * Adds a "canary" class to a secondary dex that can be safely loaded on any system. This avoids
+   * an issue where, during secondary dex loading, we attempt to verify a secondary dex by loading
+   * an arbitrary class, but the class we try to load isn't valid on that system (e.g., it depends
+   * on Google Maps, but we are on AOSP).
+   */
+  public static byte[] createCanaryClassByteCode(String className) {
+    byte[] classNameBytes = className.getBytes(StandardCharsets.UTF_8);
+    // See above comment regarding CONSTANT_Utf8_info
+    byte[] stringInfo = new byte[3];
+    stringInfo[0] = (byte) 0x01;
+    stringInfo[1] = (byte) ((classNameBytes.length & 0x0000FF00) >> 8);
+    stringInfo[2] = (byte) (classNameBytes.length & 0x000000FF);
+
+    byte[] canaryClass = Bytes.concat(CANARY_START, stringInfo, classNameBytes, CANARY_REMAINDER);
+
+    return canaryClass;
+  }
+
+  static String getFullyQualifiedCanaryClassName(String className, int index) {
+    return String.format("%s.dex%02d.Canary", className, index + 1);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/ClassNameFilter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/ClassNameFilter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/ClassNameFilter.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.dex;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import java.util.regex.Pattern;
+
+/**
+ * Filter for internal class names.
+ *
+ * <p>We use this to determine if a class must be placed in our primary dex. It supports prefix,
+ * suffix, substring, regular expression and exact matches.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ClassNameFilter {
+  private static final Character PREFIX_MARKER = '^';
+  private static final Character SUFFIX_MARKER = '^';
+  private static final String REGEX_MARKER = "^-";
+
+  // We use naive algorithms for prefix, suffix, and substring, but these could easily be
+  // optimzied using RE2 or some other more specialized search algorithms.
+  private final ImmutableList<String> prefixes;
+  private final ImmutableList<String> suffixes;
+  private final ImmutableList<String> substrings;
+  private final ImmutableSet<String> exactMatches;
+  private final ImmutableSet<Pattern> regularExpressions;
+
+  private ClassNameFilter(
+      Iterable<String> prefixes,
+      Iterable<String> suffixes,
+      Iterable<String> substrings,
+      Iterable<String> exactMatches,
+      Iterable<Pattern> regularExpressions) {
+    this.prefixes = ImmutableList.copyOf(prefixes);
+    this.suffixes = ImmutableList.copyOf(suffixes);
+    this.substrings = ImmutableList.copyOf(substrings);
+    this.exactMatches = ImmutableSet.copyOf(exactMatches);
+    this.regularExpressions = ImmutableSet.copyOf(regularExpressions);
+  }
+
+  /**
+   * Convenience factory to produce a filter from a very simple pattern language.
+   *
+   * <p>patterns are substrings by default, but {@code ^} at the start or end of a pattern anchors
+   * it to the start or end of the class name. {@code ^-} at the start of a pattern specifies that
+   * pattern is a regular expression.
+   *
+   * @param patterns Patterns to include in the filter.
+   * @return A new filter.
+   */
+  public static ClassNameFilter fromConfiguration(Iterable<String> patterns) {
+    ImmutableList.Builder<String> prefixes = ImmutableList.builder();
+    ImmutableList.Builder<String> suffixes = ImmutableList.builder();
+    ImmutableList.Builder<String> substrings = ImmutableList.builder();
+    ImmutableSet.Builder<String> exactMatches = ImmutableSet.builder();
+    ImmutableSet.Builder<Pattern> regexes = ImmutableSet.builder();
+
+    for (String pattern : patterns) {
+      boolean isRegex = pattern.startsWith(REGEX_MARKER);
+      boolean isPrefix = !isRegex && pattern.charAt(0) == PREFIX_MARKER;
+      boolean isSuffix = !isRegex && pattern.charAt(pattern.length() - 1) == SUFFIX_MARKER;
+      if (isRegex) {
+        regexes.add(Pattern.compile(pattern.substring(2)));
+      } else if (isPrefix && isSuffix) {
+        exactMatches.add(pattern.substring(1, pattern.length() - 1));
+      } else if (isPrefix) {
+        prefixes.add(pattern.substring(1));
+      } else if (isSuffix) {
+        suffixes.add(pattern.substring(0, pattern.length() - 1));
+      } else {
+        substrings.add(pattern);
+      }
+    }
+
+    return new ClassNameFilter(
+        prefixes.build(),
+        suffixes.build(),
+        substrings.build(),
+        exactMatches.build(),
+        regexes.build());
+  }
+
+  public boolean matches(String internalClassName) {
+    if (exactMatches.contains(internalClassName)) {
+      return true;
+    }
+
+    for (Pattern pattern : regularExpressions) {
+      if (pattern.matcher(internalClassName).find()) {
+        return true;
+      }
+    }
+
+    for (String prefix : prefixes) {
+      if (internalClassName.startsWith(prefix)) {
+        return true;
+      }
+    }
+
+    for (String suffix : suffixes) {
+      if (internalClassName.endsWith(suffix)) {
+        return true;
+      }
+    }
+
+    for (String substring : substrings) {
+      if (internalClassName.contains(substring)) {
+        return true;
+      }
+    }
+
+    return false;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8ExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8ExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8ExecutableMain.java
@@ -0,0 +1,494 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.dex;
+
+import com.android.tools.r8.CompilationFailedException;
+import com.facebook.buck.util.zip.ZipScrubber;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for executing {@link com.android.tools.r8.D8Command} calls. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class D8ExecutableMain {
+  /** name suffix that identifies it as a Java class file. */
+  private static final String CLASS_NAME_SUFFIX = ".class";
+
+  @Option(name = "--output-dex-file", required = true)
+  private String outputDex;
+
+  @Option(name = "--files-to-dex-list")
+  @Nullable
+  private String filesToDexList = null;
+
+  @Option(name = "--file-to-dex")
+  @Nullable
+  private String fileToDex = null;
+
+  @Option(name = "--android-jar", required = true)
+  private String androidJar;
+
+  @Option(name = "--intermediate")
+  private boolean intermediate = false;
+
+  @Option(name = "--no-desugar")
+  private boolean noDesugar = false;
+
+  @Option(name = "--no-optimize")
+  private boolean noOptimize = false;
+
+  @Option(name = "--force-jumbo")
+  private boolean forceJumbo = false;
+
+  @Option(name = "--primary-dex-class-names-path")
+  @Nullable
+  private String primaryDexClassNamesList = null;
+
+  @Option(name = "--referenced-resources-path")
+  @Nullable
+  private String referencedResourcesList = null;
+
+  @Option(name = "--classpath-files")
+  @Nullable
+  private String classpathFilesList = null;
+
+  @Option(name = "--min-sdk-version")
+  @Nullable
+  private String minSdkVersionString = null;
+
+  @Option(name = "--weight-estimate-path")
+  @Nullable
+  private String weightEstimateOutput = null;
+
+  @Option(name = "--weight-factor")
+  @Nullable
+  private String weightFactor = null;
+
+  @Option(name = "--class-names-path")
+  @Nullable
+  private String classNamesOutput = null;
+
+  @Option(name = "--ref-count-path")
+  @Nullable
+  private String refCountOutput = null;
+
+  @Option(name = "--synthetic-contexts-path")
+  @Nullable
+  private String syntheticContextsOutput = null;
+
+  /**
+   * When using jar compression, the secondary dex directory consists of N secondary dex jars, each
+   * of which has a corresponding .meta file (the secondaryDexMetadataFile) containing a single line
+   * of the form:
+   *
+   * <p>jar:<size of secondary dex jar (in bytes)> dex:<size of uncompressed dex file (in bytes)>
+   *
+   * <p>When using jar or raw compression, it also contains a metadata.txt file, which consists of N
+   * lines, one for each secondary dex file. Those lines consist of:
+   *
+   * <p><secondary dex file name> <sha1 hash of secondary dex> <canary class>
+   *
+   * <p>We write the line that needs to be added to metadata.txt for this secondary dex to
+   * secondaryDexMetadataLine, and we use the secondaryDexCanaryClassName for the <canary class>.
+   */
+  @Option(name = "--secondary-dex-compression")
+  @Nullable
+  private String secondaryDexCompression = null;
+
+  @Option(name = "--secondary-dex-metadata-file")
+  @Nullable
+  private String secondaryDexMetadataFile = null;
+
+  @Option(name = "--secondary-dex-metadata-line")
+  @Nullable
+  private String secondaryDexMetadataLine = null;
+
+  @Option(name = "--secondary-dex-canary-class-name")
+  @Nullable
+  private String secondaryDexCanaryClassName = null;
+
+  private static final String DEX_JAR_SUFFIX = ".dex.jar";
+
+  // DEX file header offsets for method and field ID counts.
+  //
+  // Reference: https://source.android.com/docs/core/runtime/dex-format#header-item
+  //
+  // The header_item fields are laid out sequentially with no padding.
+  // Each field is a uint (4 bytes) unless noted otherwise:
+  //
+  //   Offset  Size  Field
+  //   ------  ----  -----
+  //        0     8  magic (ubyte[8])
+  //        8     4  checksum
+  //       12    20  signature (ubyte[20])
+  //       32     4  file_size
+  //       36     4  header_size
+  //       40     4  endian_tag
+  //       44     4  link_size
+  //       48     4  link_off
+  //       52     4  map_off
+  //       56     4  string_ids_size
+  //       60     4  string_ids_off
+  //       64     4  type_ids_size     <-- DEX_TYPE_IDS_SIZE_OFFSET
+  //       68     4  type_ids_off
+  //       72     4  proto_ids_size
+  //       76     4  proto_ids_off
+  //       80     4  field_ids_size    <-- DEX_FIELD_IDS_SIZE_OFFSET
+  //       84     4  field_ids_off
+  //       88     4  method_ids_size   <-- DEX_METHOD_IDS_SIZE_OFFSET
+  //       92     4  method_ids_off
+  //       96     4  class_defs_size
+  //      100     4  class_defs_off
+  //      104     4  data_size
+  //      108     4  data_off
+  //      ---  v40 header ends here (112 bytes = 0x70)  ---
+  //      112     4  container_size    (v41+ only)
+  //      116     4  header_offset     (v41+ only)
+  //      ---  v41 header ends here (120 bytes = 0x78)  ---
+  //
+  // field_ids_size and method_ids_size are at offsets 80 and 88 in both
+  // versions. We read 120 bytes to cover the larger v41+ header. For v40
+  // files the extra 8 bytes come from the data section, which is harmless
+  // since we only inspect offsets 80 and 88.
+  private static final int DEX_HEADER_SIZE = 120;
+  private static final int DEX_TYPE_IDS_SIZE_OFFSET = 64;
+  private static final int DEX_FIELD_IDS_SIZE_OFFSET = 80;
+  private static final int DEX_METHOD_IDS_SIZE_OFFSET = 88;
+
+  public static void main(String[] args) throws IOException {
+    D8ExecutableMain main = new D8ExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    ImmutableSet<Path> filesToDex;
+    if (filesToDexList != null) {
+      Preconditions.checkState(fileToDex == null);
+      filesToDex =
+          Files.readAllLines(Paths.get(filesToDexList)).stream()
+              .map(Paths::get)
+              .collect(ImmutableSet.toImmutableSet());
+    } else {
+      Preconditions.checkState(fileToDex != null);
+      filesToDex = ImmutableSet.of(Paths.get(fileToDex));
+    }
+
+    Optional<Path> primaryDexClassNamesPath =
+        Optional.ofNullable(primaryDexClassNamesList).map(Paths::get);
+    Optional<Path> referencedResourcesPath =
+        Optional.ofNullable(referencedResourcesList).map(Paths::get);
+
+    ImmutableSet<Path> classpathFiles =
+        classpathFilesList == null
+            ? ImmutableSet.of()
+            : Files.readAllLines(Paths.get(classpathFilesList)).stream()
+                .map(Paths::get)
+                .collect(ImmutableSet.toImmutableSet());
+
+    Optional<Integer> minSdkVersion =
+        Optional.ofNullable(minSdkVersionString).map(Integer::parseInt);
+    Optional<Path> weightEstimatePath = Optional.ofNullable(weightEstimateOutput).map(Paths::get);
+    Optional<Path> classNamesPath = Optional.ofNullable(classNamesOutput).map(Paths::get);
+    Optional<Path> syntheticContextsPath =
+        Optional.ofNullable(syntheticContextsOutput).map(Paths::get);
+
+    Path outputPath = Paths.get(outputDex);
+    Path d8Output =
+        primaryDexClassNamesPath.isPresent() ? Files.createTempDirectory("dexTmpDir") : outputPath;
+
+    try {
+      D8Output d8InternalData =
+          D8Utils.runD8Command(
+              new D8Utils.D8DiagnosticsHandler(),
+              d8Output,
+              filesToDex,
+              getD8Options(),
+              primaryDexClassNamesPath,
+              Paths.get(androidJar),
+              classpathFiles,
+              minSdkVersion);
+
+      Collection<String> referencedResources = d8InternalData.getResources();
+      Collection<String> writtenClassDescriptors = d8InternalData.getWrittenClassDescriptors();
+
+      if (d8Output.endsWith(DEX_JAR_SUFFIX)) {
+        ZipScrubber.scrubZip(d8Output);
+      }
+
+      Preconditions.checkState(
+          primaryDexClassNamesPath.isPresent() || secondaryDexCompression == null);
+      if (primaryDexClassNamesPath.isPresent()) {
+        Path classesDotDex = d8Output.resolve("classes.dex");
+        Preconditions.checkState(
+            classesDotDex.toFile().exists(), "D8 command must produce a classes.dex");
+
+        if ("jar".equals(secondaryDexCompression)) {
+          Preconditions.checkState(outputDex.endsWith(DEX_JAR_SUFFIX));
+          Preconditions.checkNotNull(secondaryDexMetadataFile);
+          Path secondaryDexMetadataFilePath = Paths.get(secondaryDexMetadataFile);
+          Preconditions.checkState(
+              outputPath
+                  .resolveSibling(outputPath.getFileName() + ".meta")
+                  .toString()
+                  .equals(secondaryDexMetadataFile));
+          D8Utils.writeSecondaryDexJarAndMetadataFile(
+              outputPath, secondaryDexMetadataFilePath, classesDotDex, "jar");
+        } else {
+          Preconditions.checkState(
+              outputDex.endsWith(".dex"),
+              String.format(
+                  "Expect the outputDex to end with '.dex' if not '%s', but it is %s",
+                  DEX_JAR_SUFFIX, outputDex));
+          Files.move(classesDotDex, outputPath);
+        }
+
+        if ("jar".equals(secondaryDexCompression) || "raw".equals(secondaryDexCompression)) {
+          Preconditions.checkNotNull(secondaryDexMetadataLine);
+          Preconditions.checkNotNull(secondaryDexCanaryClassName);
+          Files.write(
+              Paths.get(secondaryDexMetadataLine),
+              Collections.singletonList(
+                  D8Utils.getSecondaryDexMetadataString(outputPath, secondaryDexCanaryClassName)));
+        }
+      }
+
+      if (referencedResourcesPath.isPresent()) {
+        List<String> sortedReferencedResources = new ArrayList<>(referencedResources);
+        Collections.sort(sortedReferencedResources);
+        Files.write(referencedResourcesPath.get(), sortedReferencedResources);
+      }
+
+      // Read method and field reference counts from the output DEX file header.
+      // The DEX format has hard limits of 64K method_ids and 64K field_ids per file.
+      // Unlike the weight_estimate (which uses uncompressed .class byte sizes as a proxy),
+      // these counts are exact and can be used for precise secondary DEX splitting.
+      if (refCountOutput != null) {
+        Path refCountPath = Paths.get(refCountOutput);
+        int methodRefCount = 0;
+        int fieldRefCount = 0;
+        int typeRefCount = 0;
+
+        // For pre-dex (intermediate) mode, the output is a .dex.jar containing one or
+        // more .dex files (classes.dex, classes2.dex, ...).  We sum ref counts across
+        // all .dex entries so that the conservative upper bound covers multi-dex jars.
+        // For merge mode, the output is a bare .dex file.
+        // Some libraries produce empty .dex.jar files (no Java classes, e.g. resource-only
+        // AARs). In that case, writing "0 0 0" is correct -- the library contributes no
+        // method/field/type refs to any dex file.
+        if (outputPath.toString().endsWith(DEX_JAR_SUFFIX)) {
+          try (ZipFile dexJar = new ZipFile(outputPath.toFile())) {
+            DexRefCounts jarCounts = readDexRefCountsFromJar(dexJar);
+            methodRefCount = jarCounts.methodIds;
+            fieldRefCount = jarCounts.fieldIds;
+            typeRefCount = jarCounts.typeIds;
+          }
+        } else if (outputPath.toString().endsWith(".dex")) {
+          if (!outputPath.toFile().exists()) {
+            throw new IOException(
+                "--ref-count-path requested but output " + outputPath + " does not exist");
+          }
+          try (InputStream is = Files.newInputStream(outputPath)) {
+            DexRefCounts counts = readDexRefCounts(is);
+            methodRefCount = counts.methodIds;
+            fieldRefCount = counts.fieldIds;
+            typeRefCount = counts.typeIds;
+          }
+        } else {
+          throw new IOException(
+              "--ref-count-path requested but output "
+                  + outputPath
+                  + " is neither a .dex.jar nor a .dex file");
+        }
+
+        Files.write(
+            refCountPath,
+            Collections.singletonList(methodRefCount + " " + fieldRefCount + " " + typeRefCount));
+      }
+
+      if (syntheticContextsPath.isPresent()) {
+        Files.write(
+            syntheticContextsPath.get(),
+            toSyntheticContextLines(d8InternalData.getSyntheticToSynthesizingContext()));
+      }
+
+      if (weightEstimatePath.isPresent() || classNamesPath.isPresent()) {
+        int totalWeightEstimate = 0;
+
+        try (ZipFile zipFile = new ZipFile(Iterables.getOnlyElement(filesToDex).toFile())) {
+          Enumeration<? extends ZipEntry> entries = zipFile.entries();
+          while (entries.hasMoreElements()) {
+            ZipEntry zipEntry = entries.nextElement();
+            // Ignore non-.class files.
+            if (!zipEntry.getName().endsWith(CLASS_NAME_SUFFIX)) {
+              continue;
+            }
+            totalWeightEstimate += (int) zipEntry.getSize();
+          }
+        }
+
+        if (weightEstimatePath.isPresent()) {
+          Preconditions.checkState(
+              weightFactor != null,
+              "Must specify `--weight-factor` if `--weight-estimate-path` is specified!");
+          Files.write(
+              weightEstimatePath.get(),
+              Collections.singletonList(
+                  Integer.toString(Integer.parseInt(weightFactor) * totalWeightEstimate)));
+        }
+        if (classNamesPath.isPresent()) {
+          Files.write(classNamesPath.get(), toInternalClassNames(writtenClassDescriptors));
+        }
+      }
+    } catch (CompilationFailedException e) {
+      throw new IOException(e);
+    }
+
+    System.exit(0);
+  }
+
+  /** Exact ref counts from a DEX file header (method_ids_size, field_ids_size, type_ids_size). */
+  static class DexRefCounts {
+    final int methodIds;
+    final int fieldIds;
+    final int typeIds;
+
+    DexRefCounts(int methodIds, int fieldIds, int typeIds) {
+      this.methodIds = methodIds;
+      this.fieldIds = fieldIds;
+      this.typeIds = typeIds;
+    }
+  }
+
+  /** Reads the method_ids_size, field_ids_size, and type_ids_size from a DEX file header. */
+  static DexRefCounts readDexRefCounts(InputStream is) throws IOException {
+    byte[] header = new byte[DEX_HEADER_SIZE];
+    int bytesRead = 0;
+    while (bytesRead < DEX_HEADER_SIZE) {
+      int n = is.read(header, bytesRead, DEX_HEADER_SIZE - bytesRead);
+      if (n < 0) {
+        throw new IOException(
+            "Unexpected end of DEX file: read only "
+                + bytesRead
+                + " of "
+                + DEX_HEADER_SIZE
+                + " header bytes");
+      }
+      bytesRead += n;
+    }
+
+    ByteBuffer buf = ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN);
+    return new DexRefCounts(
+        buf.getInt(DEX_METHOD_IDS_SIZE_OFFSET),
+        buf.getInt(DEX_FIELD_IDS_SIZE_OFFSET),
+        buf.getInt(DEX_TYPE_IDS_SIZE_OFFSET));
+  }
+
+  /** Reads and sums ref counts across all .dex entries in a .dex.jar (handles multi-dex). */
+  static DexRefCounts readDexRefCountsFromJar(ZipFile dexJar) throws IOException {
+    int methodRefCount = 0;
+    int fieldRefCount = 0;
+    int typeRefCount = 0;
+    Enumeration<? extends ZipEntry> entries = dexJar.entries();
+    while (entries.hasMoreElements()) {
+      ZipEntry entry = entries.nextElement();
+      if (entry.getName().endsWith(".dex")) {
+        try (InputStream is = dexJar.getInputStream(entry)) {
+          // Only null when the entry is absent, but it came from dexJar.entries().
+          DexRefCounts counts = readDexRefCounts(Objects.requireNonNull(is));
+          methodRefCount += counts.methodIds;
+          fieldRefCount += counts.fieldIds;
+          typeRefCount += counts.typeIds;
+        }
+      }
+    }
+    return new DexRefCounts(methodRefCount, fieldRefCount, typeRefCount);
+  }
+
+  /** Converts D8 type descriptors ("Lcom/example/Foo;") to internal names ("com/example/Foo"). */
+  static ImmutableList<String> toInternalClassNames(Collection<String> descriptors) {
+    return descriptors.stream()
+        .filter(d -> d.length() > 2 && d.charAt(0) == 'L' && d.endsWith(";"))
+        .map(d -> d.substring(1, d.length() - 1))
+        .sorted()
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  /**
+   * Renders the synthetic-to-context map as "{@code <synthetic> <context>}" lines, sorted for
+   * deterministic output.
+   */
+  static ImmutableList<String> toSyntheticContextLines(Map<String, String> syntheticToContext) {
+    return syntheticToContext.entrySet().stream()
+        .map(entry -> entry.getKey() + " " + entry.getValue())
+        .sorted()
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  private Set<D8Options> getD8Options() {
+    ImmutableSet.Builder<D8Options> d8OptionsBuilder = ImmutableSet.builder();
+    if (intermediate) {
+      d8OptionsBuilder.add(D8Options.INTERMEDIATE);
+    } else {
+      // Non-intermediate (merge) mode expects a single DEX output.
+      // Fail loudly if D8 produces multiple files instead of silently
+      // discarding extras, which would produce a broken APK.
+      d8OptionsBuilder.add(D8Options.FAIL_ON_MULTIPLE_DEX);
+    }
+    if (noOptimize) {
+      d8OptionsBuilder.add(D8Options.NO_OPTIMIZE);
+    }
+    if (forceJumbo) {
+      d8OptionsBuilder.add(D8Options.FORCE_JUMBO);
+    }
+    if (noDesugar) {
+      d8OptionsBuilder.add(D8Options.NO_DESUGAR);
+    }
+    if (primaryDexClassNamesList != null) {
+      // Only add the specified classes
+      d8OptionsBuilder.add(D8Options.MINIMIZE_PRIMARY_DEX);
+    }
+
+    return d8OptionsBuilder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Options.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Options.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Options.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.dex;
+
+import com.facebook.infer.annotation.Nullsafe;
+
+/** Options to pass to {@code d8}. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public enum D8Options {
+  /** Specify the {@code --debug} flag. Otherwise --release is specified */
+  NO_OPTIMIZE,
+
+  /** Force the dexer to emit jumbo string references */
+  FORCE_JUMBO,
+
+  /** Disable java 8 desugaring when running D8 dexing tool. */
+  NO_DESUGAR,
+
+  /** Compile an intermediate result intended for later merging */
+  INTERMEDIATE,
+
+  /** Don't fill up the primary dex beyond classes that need to be in the primary dex */
+  MINIMIZE_PRIMARY_DEX,
+
+  /** Fill up the primary dex as much as possible */
+  MAXIMIZE_PRIMARY_DEX,
+
+  /** Fail if D8 produces multiple DEX files when a single output is expected */
+  FAIL_ON_MULTIPLE_DEX,
+  ;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Output.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Output.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Output.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.dex;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Collection;
+import java.util.Map;
+
+/** Info exposed from {@code d8}. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class D8Output {
+  /** Referenced resources returned by D8 */
+  private Collection<String> referencedResources;
+
+  /**
+   * Type descriptors ("Lcom/example/Foo;") of every class D8 wrote, as reported by the output
+   * consumer. Includes classes invented by desugaring, which have no counterpart among the inputs.
+   */
+  private Collection<String> writtenClassDescriptors;
+
+  /** Class descriptors emitted in each indexed dex output. */
+  private final ImmutableMap<Integer, ImmutableSet<String>> outputClassDescriptors;
+
+  /**
+   * Internal names ("com/example/Foo") of each synthetic class D8 created, mapped to the class it
+   * was synthesized from. Reported by D8 itself rather than derived from the synthetic's name,
+   * whose mangling is an unstable implementation detail.
+   */
+  private final ImmutableMap<String, String> syntheticToSynthesizingContext;
+
+  public D8Output(
+      Collection<String> referencedResources,
+      Collection<String> writtenClassDescriptors,
+      Map<Integer, ImmutableSet<String>> outputClassDescriptors,
+      Map<String, String> syntheticToSynthesizingContext) {
+    this.referencedResources = referencedResources;
+    this.writtenClassDescriptors = writtenClassDescriptors;
+    this.outputClassDescriptors = ImmutableMap.copyOf(outputClassDescriptors);
+    this.syntheticToSynthesizingContext = ImmutableMap.copyOf(syntheticToSynthesizingContext);
+  }
+
+  public Collection<String> getResources() {
+    return referencedResources;
+  }
+
+  public Collection<String> getWrittenClassDescriptors() {
+    return writtenClassDescriptors;
+  }
+
+  public ImmutableSet<String> getClassDescriptors(int outputIndex) {
+    return outputClassDescriptors.getOrDefault(outputIndex, ImmutableSet.of());
+  }
+
+  public ImmutableMap<String, String> getSyntheticToSynthesizingContext() {
+    return syntheticToSynthesizingContext;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8OutputOption.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8OutputOption.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8OutputOption.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.dex;
+
+import com.facebook.infer.annotation.Nullsafe;
+
+/** Additional metadata to capture while running D8. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public enum D8OutputOption {
+  CLASS_DESCRIPTORS,
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Utils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Utils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/D8Utils.java
@@ -0,0 +1,428 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.dex;
+
+import com.android.tools.r8.ByteDataView;
+import com.android.tools.r8.CompilationFailedException;
+import com.android.tools.r8.CompilationMode;
+import com.android.tools.r8.D8Command;
+import com.android.tools.r8.DexIndexedConsumer;
+import com.android.tools.r8.Diagnostic;
+import com.android.tools.r8.DiagnosticsHandler;
+import com.android.tools.r8.SyntheticInfoConsumer;
+import com.android.tools.r8.SyntheticInfoConsumerData;
+import com.android.tools.r8.graph.DexItemFactory;
+import com.android.tools.r8.utils.FileUtils;
+import com.android.tools.r8.utils.InternalOptions;
+import com.facebook.buck.android.apkmodule.APKModule;
+import com.facebook.buck.util.zip.CustomZipOutputStream;
+import com.facebook.buck.util.zip.ZipOutputStreams;
+import com.facebook.buck.util.zip.ZipScrubber;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import com.google.common.io.ByteStreams;
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Stream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/** Runs d8. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class D8Utils {
+
+  public static D8Output runD8Command(
+      D8DiagnosticsHandler diagnosticsHandler,
+      Path outputDexFile,
+      Iterable<Path> filesToDex,
+      Set<D8Options> options,
+      Optional<Path> primaryDexClassNamesPath,
+      Path androidJarPath,
+      Collection<Path> classpathFiles,
+      Optional<Integer> minSdkVersion)
+      throws CompilationFailedException, IOException {
+    return runD8Command(
+        diagnosticsHandler,
+        outputDexFile,
+        filesToDex,
+        options,
+        primaryDexClassNamesPath,
+        androidJarPath,
+        classpathFiles,
+        minSdkVersion,
+        OptionalInt.empty());
+  }
+
+  public static D8Output runD8Command(
+      D8DiagnosticsHandler diagnosticsHandler,
+      Path outputDexFile,
+      Iterable<Path> filesToDex,
+      Set<D8Options> options,
+      Optional<Path> primaryDexClassNamesPath,
+      Path androidJarPath,
+      Collection<Path> classpathFiles,
+      Optional<Integer> minSdkVersion,
+      OptionalInt threadCount)
+      throws CompilationFailedException, IOException {
+    return runD8Command(
+        diagnosticsHandler,
+        outputDexFile,
+        filesToDex,
+        options,
+        primaryDexClassNamesPath,
+        androidJarPath,
+        classpathFiles,
+        minSdkVersion,
+        threadCount,
+        ImmutableSet.of());
+  }
+
+  public static D8Output runD8CommandWithOutputClassDescriptors(
+      D8DiagnosticsHandler diagnosticsHandler,
+      Path outputDexFile,
+      Iterable<Path> filesToDex,
+      Set<D8Options> options,
+      Optional<Path> primaryDexClassNamesPath,
+      Path androidJarPath,
+      Collection<Path> classpathFiles,
+      Optional<Integer> minSdkVersion,
+      OptionalInt threadCount)
+      throws CompilationFailedException, IOException {
+    return runD8Command(
+        diagnosticsHandler,
+        outputDexFile,
+        filesToDex,
+        options,
+        primaryDexClassNamesPath,
+        androidJarPath,
+        classpathFiles,
+        minSdkVersion,
+        threadCount,
+        ImmutableSet.of(D8OutputOption.CLASS_DESCRIPTORS));
+  }
+
+  private static D8Output runD8Command(
+      D8DiagnosticsHandler diagnosticsHandler,
+      Path outputDexFile,
+      Iterable<Path> filesToDex,
+      Set<D8Options> options,
+      Optional<Path> primaryDexClassNamesPath,
+      Path androidJarPath,
+      Collection<Path> classpathFiles,
+      Optional<Integer> minSdkVersion,
+      OptionalInt threadCount,
+      Set<D8OutputOption> outputOptions)
+      throws CompilationFailedException, IOException {
+    Set<Path> inputs = new HashSet<>();
+    for (Path toDex : filesToDex) {
+      if (Files.isRegularFile(toDex)) {
+        inputs.add(toDex);
+      } else {
+        try (Stream<Path> paths = Files.walk(toDex)) {
+          paths.filter(path -> path.toFile().isFile()).forEach(inputs::add);
+        }
+      }
+    }
+
+    // D8 only outputs to dex if the output path is a directory. So we output to a temporary dir
+    // and move it over to the final location
+    boolean outputToDex = outputDexFile.getFileName().toString().endsWith(".dex");
+    Path output = outputToDex ? Files.createTempDirectory("buck-d8") : outputDexFile;
+
+    // Wrap the consumer that setOutput() would have installed so we can record which classes D8
+    // actually wrote.
+    Set<String> writtenDescriptors = Collections.synchronizedSet(new HashSet<>());
+    // Picks the consumer the same way setOutput() would, using the same predicate it uses.
+    DexIndexedConsumer outputConsumer =
+        FileUtils.isArchive(output)
+            ? new DexIndexedConsumer.ArchiveConsumer(output)
+            : new DexIndexedConsumer.DirectoryConsumer(output);
+    DexIndexedConsumer recordingConsumer =
+        new DexIndexedConsumer.ForwardingConsumer(outputConsumer) {
+          @Override
+          public void accept(
+              int fileIndex,
+              ByteDataView data,
+              Set<String> descriptors,
+              DiagnosticsHandler handler) {
+            if (descriptors != null) {
+              writtenDescriptors.addAll(descriptors);
+            }
+            super.accept(fileIndex, data, descriptors, handler);
+          }
+        };
+
+    // Ask D8 which class each synthetic was synthesized from. Synthetics have to be placed in the
+    // same dex as their context class, and their names are mangled in a format D8 does not treat
+    // as stable (see setEnableVerboseSyntheticNames), so the names cannot be parsed for this.
+    // D8 invokes acceptSyntheticInfo from its worker threads, so this has to be thread safe.
+    Map<String, String> syntheticToSynthesizingContext = new ConcurrentHashMap<>();
+    SyntheticInfoConsumer syntheticInfoConsumer =
+        new SyntheticInfoConsumer() {
+          @Override
+          public void acceptSyntheticInfo(SyntheticInfoConsumerData data) {
+            syntheticToSynthesizingContext.put(
+                data.getSyntheticClass().getBinaryName(),
+                data.getSynthesizingContextClass().getBinaryName());
+          }
+
+          @Override
+          public void finished() {}
+        };
+
+    D8Command.Builder builder =
+        D8Command.builder(diagnosticsHandler)
+            .setSyntheticInfoConsumer(syntheticInfoConsumer)
+            .addProgramFiles(inputs)
+            .setIntermediate(options.contains(D8Options.INTERMEDIATE))
+            .addLibraryFiles(androidJarPath)
+            .setMode(
+                options.contains(D8Options.NO_OPTIMIZE)
+                    ? CompilationMode.DEBUG
+                    : CompilationMode.RELEASE)
+            .setDisableDesugaring(options.contains(D8Options.NO_DESUGAR))
+            .setInternalOptionsModifier(
+                (InternalOptions opt) -> {
+                  opt.testing.forceJumboStringProcessing = options.contains(D8Options.FORCE_JUMBO);
+                  if (options.contains(D8Options.MINIMIZE_PRIMARY_DEX)) {
+                    opt.minimalMainDex = true;
+                  } else if (options.contains(D8Options.MAXIMIZE_PRIMARY_DEX)) {
+                    opt.minimalMainDex = false;
+                  }
+                  if (threadCount.isPresent()) {
+                    opt.threadCount = threadCount.getAsInt();
+                  }
+                });
+
+    OutputClassDescriptorConsumer outputClassDescriptorConsumer = null;
+    if (outputOptions.contains(D8OutputOption.CLASS_DESCRIPTORS)) {
+      outputClassDescriptorConsumer = new OutputClassDescriptorConsumer(recordingConsumer);
+      builder.setProgramConsumer(outputClassDescriptorConsumer);
+    } else {
+      builder.setProgramConsumer(recordingConsumer);
+    }
+
+    minSdkVersion.ifPresent(builder::setMinApiLevel);
+    if (minSdkVersion.orElse(0) <= 21) {
+      // addMainDexListFiles is not supported for minSdkVersion > 21
+      primaryDexClassNamesPath.ifPresent(builder::addMainDexListFiles);
+    }
+
+    if (classpathFiles != null) {
+      // classpathFiles is needed only for D8 Java 8 desugar
+      builder.addClasspathFiles(classpathFiles);
+    }
+
+    D8Command d8Command = builder.build();
+    com.android.tools.r8.D8.run(d8Command);
+
+    if (outputToDex) {
+      moveSingleDexOutput(output, outputDexFile, options);
+    }
+
+    // Only null for the help/version commands produced by D8Command.parse, never for a built one.
+    DexItemFactory dexItemFactory = Objects.requireNonNull(d8Command.getDexItemFactory());
+    return new D8Output(
+        dexItemFactory.computeReferencedResources(),
+        writtenDescriptors,
+        outputClassDescriptorConsumer == null
+            ? ImmutableMap.of()
+            : outputClassDescriptorConsumer.getOutputClassDescriptors(),
+        syntheticToSynthesizingContext);
+  }
+
+  private static class OutputClassDescriptorConsumer extends DexIndexedConsumer.ForwardingConsumer {
+    private final Map<Integer, ImmutableSet<String>> outputClassDescriptors =
+        new ConcurrentHashMap<>();
+
+    private OutputClassDescriptorConsumer(DexIndexedConsumer consumer) {
+      super(consumer);
+    }
+
+    @Override
+    public void accept(
+        int fileIndex, ByteDataView data, Set<String> descriptors, DiagnosticsHandler handler) {
+      Preconditions.checkState(
+          outputClassDescriptors.putIfAbsent(fileIndex, ImmutableSet.copyOf(descriptors)) == null,
+          "D8 reported output index %s more than once",
+          fileIndex);
+      super.accept(fileIndex, data, descriptors, handler);
+    }
+
+    private ImmutableMap<Integer, ImmutableSet<String>> getOutputClassDescriptors() {
+      return ImmutableMap.copyOf(outputClassDescriptors);
+    }
+  }
+
+  static void writeSecondaryDexJarAndMetadataFile(
+      Path secondaryDexOutputJarPath,
+      Path secondaryDexOutputJarMetadataPath,
+      Path rawSecondaryDexPath,
+      String compression)
+      throws IOException {
+
+    try (CustomZipOutputStream jarOutputStream =
+            ZipOutputStreams.newOutputStream(secondaryDexOutputJarPath);
+        InputStream secondaryDexInputStream =
+            new BufferedInputStream(new FileInputStream(rawSecondaryDexPath.toFile()))) {
+
+      ZipEntry customEntry = new ZipEntry("classes.dex");
+      if (compression.equals("xzs")) {
+        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
+          ByteStreams.copy(secondaryDexInputStream, bos);
+          byte[] bytes = bos.toByteArray();
+          customEntry.setCrc(Hashing.crc32().hashBytes(bytes).padToLong());
+          customEntry.setSize(bytes.length);
+          customEntry.setCompressedSize(bytes.length);
+          customEntry.setMethod(ZipEntry.STORED);
+          jarOutputStream.putNextEntry(customEntry);
+          ByteStreams.copy(new ByteArrayInputStream(bytes), jarOutputStream);
+          jarOutputStream.closeEntry();
+        }
+      } else {
+        jarOutputStream.putNextEntry(customEntry);
+        ByteStreams.copy(secondaryDexInputStream, jarOutputStream);
+        jarOutputStream.closeEntry();
+      }
+    }
+
+    ZipScrubber.scrubZip(secondaryDexOutputJarPath);
+
+    writeSecondaryDexMetadata(
+        secondaryDexOutputJarPath, secondaryDexOutputJarMetadataPath, compression);
+  }
+
+  /**
+   * Write a secondary dex jar metadata file. This is a .meta file with a single line containing:
+   *
+   * <p>jar:<size of secondary dex jar (in bytes)> dex:<size of uncompressed dex file (in bytes)>
+   */
+  static void writeSecondaryDexMetadata(
+      Path secondaryDexOutputJarPath, Path secondaryDexOutputJarMetadataPath, String compression)
+      throws IOException {
+    try (ZipFile zf = new ZipFile(secondaryDexOutputJarPath.toFile())) {
+      ZipEntry classesDexEntry = zf.getEntry("classes.dex");
+      if (classesDexEntry == null) {
+        throw new RuntimeException("could not find classes.dex in jar");
+      }
+
+      long uncompressedSize = classesDexEntry.getSize();
+      if (uncompressedSize == -1) {
+        throw new RuntimeException("classes.dex size should be known");
+      }
+
+      long jarSize = Files.size(secondaryDexOutputJarPath);
+      if (compression.equals("xzs")) {
+        Preconditions.checkState(
+            uncompressedSize + 120 == jarSize,
+            "For xzs compression, we expect the .dex to be stored uncompressed and the "
+                + "overhead of the .jar itself to be 120 bytes!");
+      }
+
+      Files.write(
+          secondaryDexOutputJarMetadataPath,
+          Collections.singletonList(
+              String.format(
+                  "jar:%s dex:%s", Files.size(secondaryDexOutputJarPath), uncompressedSize)));
+    }
+  }
+
+  /**
+   * The secondary dex directory contains a single metadata.txt file which has one line per
+   * secondary dex, consisting of:
+   *
+   * <p><secondary dex file name> <sha1 hash of secondary dex> <canary class>
+   */
+  static String getSecondaryDexMetadataString(Path secondaryDexPath, String canaryClassName)
+      throws IOException {
+    return String.format(
+        "%s %s %s",
+        secondaryDexPath.getFileName(),
+        com.google.common.io.Files.hash(secondaryDexPath.toFile(), Hashing.sha1()).toString(),
+        canaryClassName);
+  }
+
+  static String getRawSecondaryDexSubDir(String module) {
+    if (APKModule.isRootModule(module)) {
+      return "";
+    } else {
+      return String.format("assets/%s", module);
+    }
+  }
+
+  /**
+   * Moves a single DEX file from a D8 output directory to the final destination. When {@link
+   * D8Options#FAIL_ON_MULTIPLE_DEX} is present in the options set, throws {@link
+   * IllegalStateException} if D8 produced multiple DEX files. Otherwise, silently moves the first
+   * file (sorted lexicographically).
+   *
+   * <p>This is package-visible for testing.
+   */
+  static void moveSingleDexOutput(Path d8OutputDir, Path outputDexFile, Set<D8Options> options)
+      throws IOException {
+    File[] outputs = d8OutputDir.toFile().listFiles();
+    if (outputs == null || outputs.length == 0) {
+      return;
+    }
+    if (outputs.length > 1 && options.contains(D8Options.FAIL_ON_MULTIPLE_DEX)) {
+      StringBuilder fileList = new StringBuilder();
+      for (File f : outputs) {
+        fileList.append("\n  ").append(f.getName());
+      }
+      throw new IllegalStateException(
+          "D8 produced "
+              + outputs.length
+              + " DEX files but only a single output was expected:"
+              + fileList
+              + "\nThe combined input likely exceeds DEX reference limits."
+              + " Enable split_dex (use_split_dex = True) for this target.");
+    }
+    // File.listFiles() returns undefined order — sort for determinism.
+    Arrays.sort(outputs);
+    Files.move(outputs[0].toPath(), outputDexFile, StandardCopyOption.REPLACE_EXISTING);
+  }
+
+  public static class D8DiagnosticsHandler implements DiagnosticsHandler {
+
+    public final List<Diagnostic> diagnostics = new ArrayList<>();
+
+    @Override
+    public void warning(Diagnostic warning) {
+      diagnostics.add(warning);
+    }
+
+    @Override
+    public void info(Diagnostic info) {}
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/JarSplitterExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/JarSplitterExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/JarSplitterExecutableMain.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.dex;
+
+import com.facebook.buck.android.proguard.ProguardTranslatorFactory;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.io.ByteStreams;
+import java.io.BufferedOutputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Enumeration;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.function.Function;
+import java.util.jar.JarOutputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/**
+ * Main entry point for splitting a .jar into the .class files that should go into the primary .dex,
+ * and the .class files that should go into a secondary .dex.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class JarSplitterExecutableMain {
+  /** name suffix that identifies it as a Java class file. */
+  private static final String CLASS_NAME_SUFFIX = ".class";
+
+  @Option(name = "--input-jar", required = true)
+  private String inputJar;
+
+  @Option(name = "--primary-dex-patterns", required = true)
+  private String primaryDexPatterns;
+
+  @Option(name = "--proguard-configuration-file")
+  @Nullable
+  private String proguardConfigurationFileString = null;
+
+  @Option(name = "--proguard-mapping-file")
+  @Nullable
+  private String proguardMappingFileString = null;
+
+  @Option(name = "--primary-dex-classes-jar", required = true)
+  private String primaryDexClassesJar;
+
+  @Option(name = "--secondary-dex-classes-jar", required = true)
+  private String secondaryDexClassesJar;
+
+  public static void main(String[] args) throws IOException {
+    JarSplitterExecutableMain main = new JarSplitterExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    ProguardTranslatorFactory proguardTranslatorFactory =
+        ProguardTranslatorFactory.create(
+            Optional.ofNullable(proguardConfigurationFileString).map(Paths::get),
+            Optional.ofNullable(proguardMappingFileString).map(Paths::get),
+            false);
+    Function<String, String> deobfuscateFunction =
+        proguardTranslatorFactory.createDeobfuscationFunction();
+    ClassNameFilter primaryDexClassNameFilter =
+        ClassNameFilter.fromConfiguration(Files.readAllLines(Paths.get(primaryDexPatterns)));
+
+    try (JarOutputStream primaryJarOutputStream =
+            new JarOutputStream(
+                new BufferedOutputStream(
+                    new FileOutputStream(Paths.get(primaryDexClassesJar).toFile())));
+        JarOutputStream secondaryJarOutputStream =
+            new JarOutputStream(
+                new BufferedOutputStream(
+                    new FileOutputStream(Paths.get(secondaryDexClassesJar).toFile())));
+        ZipFile zipFile = new ZipFile(Paths.get(inputJar).toFile())) {
+      Enumeration<? extends ZipEntry> entries = zipFile.entries();
+      while (entries.hasMoreElements()) {
+        ZipEntry zipEntry = entries.nextElement();
+        String zipEntryName = zipEntry.getName();
+        // Ignore non-.class files.
+        if (!zipEntryName.endsWith(CLASS_NAME_SUFFIX)) {
+          continue;
+        }
+
+        String deobfuscatedClassName =
+            Objects.requireNonNull(
+                deobfuscateFunction.apply(
+                    zipEntryName.substring(0, zipEntryName.length() - CLASS_NAME_SUFFIX.length())));
+        JarOutputStream jarOutputStream =
+            primaryDexClassNameFilter.matches(deobfuscatedClassName)
+                ? primaryJarOutputStream
+                : secondaryJarOutputStream;
+        zipEntry.setCompressedSize(-1);
+        jarOutputStream.putNextEntry(zipEntry);
+        ByteStreams.copy(Objects.requireNonNull(zipFile.getInputStream(zipEntry)), jarOutputStream);
+        jarOutputStream.closeEntry();
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/MultiDexExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/MultiDexExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/MultiDexExecutableMain.java
@@ -0,0 +1,659 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.dex;
+
+import com.android.tools.r8.CompilationFailedException;
+import com.facebook.buck.android.apkmodule.APKModule;
+import com.facebook.buck.android.proguard.ProguardTranslatorFactory;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Executable for creating multiple DEX files from library jars. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class MultiDexExecutableMain {
+  /** name suffix that identifies it as a Java class file. */
+  private static final String CLASS_NAME_SUFFIX = ".class";
+
+  /** Thread count for main D8 compilation (capped to avoid diminishing returns). */
+  private static final OptionalInt D8_THREAD_COUNT =
+      OptionalInt.of(Math.min(Runtime.getRuntime().availableProcessors(), 48));
+
+  @Option(name = "--primary-dex")
+  @Nullable
+  private String primaryDexString = null;
+
+  @Option(name = "--secondary-dex-output-dir", required = true)
+  private String secondaryDexOutputDirString;
+
+  @Option(name = "--primary-dex-files-to-dex-list")
+  @Nullable
+  private String primaryDexFilesToDexList = null;
+
+  @Option(name = "--files-to-dex-list", required = true)
+  private String filesToDexList;
+
+  @Option(name = "--module", required = true)
+  private String module;
+
+  @Option(name = "--canary-class-name", required = true)
+  private String canaryClassName;
+
+  @Option(name = "--android-jar", required = true)
+  private String androidJar;
+
+  @Option(name = "--primary-dex-patterns-path")
+  @Nullable
+  private String primaryDexPatternsPathString = null;
+
+  @Option(name = "--primary-dex-class-names")
+  @Nullable
+  private String deobfuscatedPrimaryDexClassNamesPathString = null;
+
+  @Option(name = "--proguard-configuration-file")
+  @Nullable
+  private String proguardConfigurationFileString = null;
+
+  @Option(name = "--proguard-mapping-file")
+  @Nullable
+  private String proguardMappingFileString = null;
+
+  @Option(name = "--min-sdk-version")
+  @Nullable
+  private String minSdkVersionString = null;
+
+  @Option(name = "--no-optimize")
+  private boolean noOptimize = false;
+
+  @Option(name = "--minimize-primary-dex")
+  private boolean minimizePrimaryDex = false;
+
+  @Option(name = "--enable-bootstrap-dexes")
+  private boolean enableBootstrapDexes = false;
+
+  @Option(name = "--bootstrap-dex-output-dir")
+  @Nullable
+  private String bootstrapDexOutputDirString = null;
+
+  @Option(name = "--classpath-files")
+  @Nullable
+  private Path classpathFilesList = null;
+
+  @Option(name = "--pre-dexed-inputs")
+  private boolean preDexedInputs = false;
+
+  public static void main(String[] args) throws IOException {
+    MultiDexExecutableMain main = new MultiDexExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  // This handles a few scenarios:
+  // 1) Root module, minimize primary dex
+  //    a) Run d8 once to create the minimal primary dex with the given primary dex jars, and files
+  //       to dex as part of the class path.
+  //    b) Run d8 again to create N secondaries, creating and using a canary class as this run's
+  //       primary dex list.
+  //    c) For however many secondaries created in step b, minus 1, run d8 for each to merge in a
+  //       canary class.
+  // 2) Root module, non-minimal primary dex
+  //    a) Perform matching of primary dex patterns, applying ClassNameFilter against jar entries.
+  //    b) Run d8 to create the primary dex and N secondaries, with the given primary dex list
+  //       created by step a.
+  //    c) The first dex created by b is the primary, copy it to the designated output.
+  //    d) For however many secondaries created in step b, run d8 for each to merge in a canary
+  //       class.
+  // 3) Root module, bootstrap dex files. This is quite similar to scenario #1, except that in a)
+  //    potentially many dex files could be created for the pattern matching classes. The first will
+  //    be output to the normal path of the primary dex, and the rest will be put into a separate
+  //    directory. Execution will carry on as described in #1, except that naming conventions must
+  //    honor a different number of existing dex files.
+  // 4) Non-root module.
+  //    a) Assert no given primary dex patterns and no minimize options.
+  //    b) Run d8 to create N dexes, making a canary class as this run's primary dex list.
+  //    c) For each dex file beyond the first, run d8 again to merge in a canary class.
+  private void run() throws IOException {
+    Optional<Integer> minSdkVersion =
+        Optional.ofNullable(minSdkVersionString).map(Integer::parseInt);
+    Path d8OutputDir = Files.createTempDirectory("d8_output_dir");
+    Path canaryClassDirectory = Files.createTempDirectory("canary_classes");
+    ImmutableList<Path> filesToDex =
+        Files.readAllLines(Paths.get(filesToDexList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableList.toImmutableList());
+    ImmutableSet<Path> classpathFiles =
+        classpathFilesList == null
+            ? ImmutableSet.of()
+            : Files.readAllLines(classpathFilesList).stream()
+                .map(Paths::get)
+                .collect(ImmutableSet.toImmutableSet());
+    ImmutableSet<Path> classpath =
+        ImmutableSet.copyOf(Sets.difference(classpathFiles, ImmutableSet.copyOf(filesToDex)));
+
+    boolean deliberatelySculptingPrimaryDex = minimizePrimaryDex || enableBootstrapDexes;
+    if (preDexedInputs) {
+      Preconditions.checkState(
+          minSdkVersion.orElse(0) > 21,
+          "Pre-dexed native multidex inputs require a min SDK greater than 21");
+      Preconditions.checkState(
+          !deliberatelySculptingPrimaryDex,
+          "Pre-dexed native multidex inputs do not support primary dex sculpting");
+    }
+    Path primaryDexClassNamesPath = Files.createTempFile("primary_dex_class_names", "txt");
+    Path bootstrapDexOutputDir = null;
+    if (bootstrapDexOutputDirString != null) {
+      bootstrapDexOutputDir = Paths.get(bootstrapDexOutputDirString);
+      Files.createDirectories(bootstrapDexOutputDir);
+    }
+
+    Function<String, String> deobfuscateFunction = Function.identity();
+    int moduleDexFilesEmitted = 0;
+    if (!APKModule.isRootModule(module)) {
+      Preconditions.checkState(primaryDexPatternsPathString == null);
+      Preconditions.checkState(deobfuscatedPrimaryDexClassNamesPathString == null);
+      Preconditions.checkState(primaryDexFilesToDexList == null);
+      Preconditions.checkState(primaryDexString == null);
+      Preconditions.checkState(!deliberatelySculptingPrimaryDex);
+    } else {
+      Preconditions.checkState(primaryDexString != null);
+      ProguardTranslatorFactory proguardTranslatorFactory =
+          ProguardTranslatorFactory.create(
+              Optional.ofNullable(proguardConfigurationFileString).map(Paths::get),
+              Optional.ofNullable(proguardMappingFileString).map(Paths::get),
+              false);
+      deobfuscateFunction = proguardTranslatorFactory.createDeobfuscationFunction();
+      if (deliberatelySculptingPrimaryDex) {
+        Preconditions.checkState(primaryDexFilesToDexList != null);
+        Preconditions.checkState(primaryDexPatternsPathString == null);
+        ImmutableList<Path> primaryDexFilesToDex =
+            Files.readAllLines(Paths.get(primaryDexFilesToDexList)).stream()
+                .map(Paths::get)
+                .collect(ImmutableList.toImmutableList());
+        Predicate<String> matchesAllFiles = f -> true;
+        PrimaryDexClassNamesHolder primaryDexClassNamesHolder =
+            getPrimaryDexClassNames(primaryDexFilesToDex, matchesAllFiles, deobfuscateFunction);
+        ImmutableSet<Path> primaryDexClasspath =
+            ImmutableSet.copyOf(
+                Sets.difference(
+                    ImmutableSet.<Path>builder().addAll(filesToDex).addAll(classpath).build(),
+                    ImmutableSet.copyOf(primaryDexFilesToDex)));
+        classpath =
+            ImmutableSet.<Path>builder().addAll(primaryDexFilesToDex).addAll(classpath).build();
+        if (enableBootstrapDexes) {
+          Preconditions.checkNotNull(
+              bootstrapDexOutputDir,
+              "Need to supply --bootstrap-dex-output-dir with --enable-bootstrap-dexes");
+          Path d8OutputDirInitial = Files.createTempDirectory("d8_output_dir_bootstrap");
+          // Similar as the below minimizePrimaryDex case, but generate potentially many dex files
+          // for the base.apk file using the split up primary pattern matching jars (output path to
+          // d8 is a dir instead of single file as above). However many .dex files created beyond
+          // classes.dex will be used for naming of subsequent dex files.
+          Path hackMainDexListForBootstrapRun =
+              synthesizePrimaryDexClassNamesFileForDexes(primaryDexFilesToDex, "bootstrap");
+          try {
+            D8Utils.runD8Command(
+                new D8Utils.D8DiagnosticsHandler(),
+                d8OutputDirInitial,
+                primaryDexFilesToDex,
+                noOptimize ? EnumSet.of(D8Options.NO_OPTIMIZE) : EnumSet.noneOf(D8Options.class),
+                Optional.of(hackMainDexListForBootstrapRun),
+                Paths.get(androidJar),
+                primaryDexClasspath,
+                minSdkVersion,
+                D8_THREAD_COUNT);
+          } catch (CompilationFailedException e) {
+            throw new IOException(e);
+          }
+          // Since d8 is outputting to directory, copy individual files over.
+          Path createdClassesDotDex = d8OutputDirInitial.resolve("classes.dex");
+          Preconditions.checkState(Files.exists(createdClassesDotDex));
+          try (var stream = Files.list(d8OutputDirInitial)) {
+            moduleDexFilesEmitted = (int) stream.count();
+          }
+
+          Path primaryDexPath = Paths.get(primaryDexString);
+          Files.move(createdClassesDotDex, primaryDexPath);
+          // Create and fill the bootstrap dex dir. Perhaps it would be nicer if primary dex was
+          // just a dir of many. classes.dex was already moved away.
+          final int bootstrapDexFileCount = moduleDexFilesEmitted - 1;
+          for (int i = 0; i < bootstrapDexFileCount; i++) {
+            String dexName = String.format("classes%d.dex", i + 2);
+            Files.move(d8OutputDirInitial.resolve(dexName), bootstrapDexOutputDir.resolve(dexName));
+          }
+        } else if (minimizePrimaryDex) {
+          // d8 is not adhere directly to the main-dex-list when it is asked to sculpt a dex;
+          // it drags in more classes than strictly listed (based on the assumed low min sdk to
+          // comply with quirks of the Dalvik runtime).
+          // Instead, we just pass the .class files that we want to be in the primary dex to d8
+          // directly.
+          try {
+            D8Utils.runD8Command(
+                new D8Utils.D8DiagnosticsHandler(),
+                Paths.get(primaryDexString),
+                primaryDexFilesToDex,
+                noOptimize ? EnumSet.of(D8Options.NO_OPTIMIZE) : EnumSet.noneOf(D8Options.class),
+                Optional.empty(),
+                Paths.get(androidJar),
+                primaryDexClasspath,
+                minSdkVersion,
+                D8_THREAD_COUNT);
+          } catch (CompilationFailedException e) {
+            throw new IOException(e);
+          }
+          moduleDexFilesEmitted = 1;
+        }
+        // Common case for both minimize primary, and bootstrap primaries.
+        Files.write(
+            Paths.get(Objects.requireNonNull(deobfuscatedPrimaryDexClassNamesPathString)),
+            primaryDexClassNamesHolder.deobfuscatedPrimaryDexClassNames);
+      } else if (!preDexedInputs) {
+        List<String> primaryDexPatterns =
+            Files.readAllLines(Paths.get(Objects.requireNonNull(primaryDexPatternsPathString)));
+        ClassNameFilter primaryDexClassNameFilter =
+            ClassNameFilter.fromConfiguration(primaryDexPatterns);
+        Predicate<String> primaryDexPatternMatcher = primaryDexClassNameFilter::matches;
+        PrimaryDexClassNamesHolder primaryDexClassNamesHolder =
+            getPrimaryDexClassNames(filesToDex, primaryDexPatternMatcher, deobfuscateFunction);
+
+        Preconditions.checkState(
+            !primaryDexClassNamesHolder.primaryDexClassNames.isEmpty(),
+            "No primary dex classes were specified! Please add primary_dex_patterns "
+                + "to ensure that at least one class exists in the primary dex.");
+        Files.write(primaryDexClassNamesPath, primaryDexClassNamesHolder.primaryDexClassNames);
+        Files.write(
+            Paths.get(Objects.requireNonNull(deobfuscatedPrimaryDexClassNamesPathString)),
+            primaryDexClassNamesHolder.deobfuscatedPrimaryDexClassNames);
+      }
+    }
+
+    int canariesCreated = 0;
+    if ((!APKModule.isRootModule(module) || deliberatelySculptingPrimaryDex) && !preDexedInputs) {
+      // We're just creating secondary dexes, and if we don't pass a main-dex-list then d8
+      // will try to put everything into a single dex. Create our first "canary class" and
+      // put it in the main-dex-list.
+      Path firstSecondaryDexCanaryClass = createCanaryClass(canaryClassDirectory, 0);
+      canariesCreated = 1;
+      filesToDex =
+          new ImmutableList.Builder<Path>()
+              .addAll(filesToDex)
+              .add(firstSecondaryDexCanaryClass)
+              .build();
+      Files.write(
+          primaryDexClassNamesPath,
+          ImmutableList.of(
+              canaryClassDirectory.relativize(firstSecondaryDexCanaryClass).toString()));
+    }
+
+    D8Output d8Output;
+    try {
+      d8Output =
+          D8Utils.runD8CommandWithOutputClassDescriptors(
+              new D8Utils.D8DiagnosticsHandler(),
+              d8OutputDir,
+              filesToDex,
+              getD8Options(),
+              preDexedInputs ? Optional.empty() : Optional.of(primaryDexClassNamesPath),
+              Paths.get(androidJar),
+              classpath,
+              minSdkVersion,
+              D8_THREAD_COUNT);
+    } catch (CompilationFailedException e) {
+      throw new IOException(e);
+    }
+
+    Path secondaryDexesWithCanaries = Paths.get(secondaryDexOutputDirString);
+    Files.createDirectories(secondaryDexesWithCanaries);
+
+    Path createdClassesDotDex = d8OutputDir.resolve("classes.dex");
+    Preconditions.checkState(Files.exists(createdClassesDotDex));
+    if (APKModule.isRootModule(module) && !deliberatelySculptingPrimaryDex) {
+      Path primaryDexPath = Paths.get(Objects.requireNonNull(primaryDexString));
+      Files.move(createdClassesDotDex, primaryDexPath);
+      moduleDexFilesEmitted = 1;
+      if (preDexedInputs) {
+        // DexIndexedConsumer assigns index 0 to classes.dex, which is the primary dex moved above.
+        ImmutableList<String> primaryDexClassNames =
+            getDeobfuscatedClassNames(d8Output.getClassDescriptors(0), deobfuscateFunction);
+        Files.write(
+            Paths.get(Objects.requireNonNull(deobfuscatedPrimaryDexClassNamesPathString)),
+            primaryDexClassNames);
+      }
+    } else {
+      Path firstSecondaryDexPath =
+          secondaryDexesWithCanaries.resolve(
+              getRawSecondaryDexName(module, moduleDexFilesEmitted, 0));
+      if (preDexedInputs) {
+        mergeCanaryIntoDex(
+            createdClassesDotDex,
+            firstSecondaryDexPath,
+            canaryClassDirectory,
+            canariesCreated,
+            minSdkVersion);
+        Files.delete(createdClassesDotDex);
+        canariesCreated += 1;
+      } else {
+        Files.move(createdClassesDotDex, firstSecondaryDexPath);
+      }
+      moduleDexFilesEmitted += 1;
+    }
+
+    // Our d8 command created N secondary dexes. Per convention, a "canary class" should exist in
+    // each of them (for runtime invariants), so for each of them we create a canary class and then
+    // re-run d8 with the original secondary dex and the canary class path. Note that in certain
+    // situations above, a canary might already be created and manually used as a main-dex-list.
+    // Note: the canary class does not contribute any fields or methods, so this shouldn't cause an
+    // existing .dex file to overflow.
+    createSecondaryDexOutputWithCanaries(
+        d8OutputDir, moduleDexFilesEmitted, canariesCreated, minSdkVersion);
+  }
+
+  private static ImmutableList<String> getDeobfuscatedClassNames(
+      Set<String> descriptors, Function<String, String> deobfuscateFunction) {
+    Preconditions.checkState(
+        !descriptors.isEmpty(), "D8 did not report any classes for output index 0 (classes.dex)");
+    ImmutableList.Builder<String> classNames = ImmutableList.builder();
+    for (String descriptor : descriptors) {
+      Preconditions.checkState(
+          descriptor.startsWith("L") && descriptor.endsWith(";"),
+          "Invalid class descriptor: %s",
+          descriptor);
+      String className = descriptor.substring(1, descriptor.length() - 1);
+      String deobfuscatedClassName =
+          Objects.requireNonNull(
+              deobfuscateFunction.apply(className),
+              "No deobfuscated class name for descriptor " + descriptor);
+      classNames.add(deobfuscatedClassName + ".class");
+    }
+    return ImmutableList.sortedCopyOf(classNames.build());
+  }
+
+  /**
+   * D8 run will create N secondary dex files, but per convention canary classes should be added for
+   * loading at runtime and integrity checks. For each given dex we create a canary class and then
+   * re-run d8 with the original secondary dex and the canary class path. The canary class does not
+   * contribute any fields or methods, so this shouldn't cause a dex to overflow.
+   *
+   * @param d8OutputDir Where to find the dex files.
+   * @param moduleDexFilesEmitted How many dex files for the currently processed module were already
+   *     created and moved to their appropriate output dir. This will form the naming of subsequent
+   *     dex files moved by this function.
+   * @param canariesCreated How many canary classes were created by the earlier stage.
+   * @param minSdkVersion To pass to d8.
+   * @throws IOException
+   */
+  private void createSecondaryDexOutputWithCanaries(
+      Path d8OutputDir,
+      int moduleDexFilesEmitted,
+      int canariesCreated,
+      Optional<Integer> minSdkVersion)
+      throws IOException {
+    Path secondaryDexesWithCanaries = Paths.get(secondaryDexOutputDirString);
+    Files.createDirectories(secondaryDexesWithCanaries);
+    Path canaryClassDirectory = Files.createTempDirectory("canary_classes");
+    // Check if a previous step has already consumed the classes.dex file from this output dir. If
+    // so, count beyond it.
+    long secondaryDexCount;
+    try (var stream = Files.list(d8OutputDir)) {
+      secondaryDexCount = stream.count();
+    }
+
+    List<Callable<Void>> tasks = new ArrayList<>();
+    for (int rawIndex = 0; rawIndex < secondaryDexCount; rawIndex++) {
+      final int idx = rawIndex;
+      tasks.add(
+          () -> {
+            mergeCanaryIntoDex(
+                d8OutputDir,
+                secondaryDexesWithCanaries,
+                canaryClassDirectory,
+                moduleDexFilesEmitted,
+                idx,
+                canariesCreated,
+                minSdkVersion);
+            return null;
+          });
+    }
+
+    runInParallel(tasks, "Canary merging");
+  }
+
+  /** Merge a single canary class into a single secondary dex. Thread-safe. */
+  private void mergeCanaryIntoDex(
+      Path d8OutputDir,
+      Path secondaryDexesWithCanaries,
+      Path canaryClassDirectory,
+      int moduleDexFilesEmitted,
+      int rawIndex,
+      int canariesCreated,
+      Optional<Integer> minSdkVersion)
+      throws IOException {
+    String secondaryDexName = getRawSecondaryDexName(module, moduleDexFilesEmitted, rawIndex);
+    Path secondaryDexPath = secondaryDexesWithCanaries.resolve(secondaryDexName);
+    Path rawSecondaryDexPath = d8OutputDir.resolve(String.format("classes%d.dex", rawIndex + 2));
+    mergeCanaryIntoDex(
+        rawSecondaryDexPath,
+        secondaryDexPath,
+        canaryClassDirectory,
+        rawIndex + canariesCreated,
+        minSdkVersion);
+  }
+
+  private void mergeCanaryIntoDex(
+      Path rawSecondaryDexPath,
+      Path secondaryDexPath,
+      Path canaryClassDirectory,
+      int canaryIndex,
+      Optional<Integer> minSdkVersion)
+      throws IOException {
+    Preconditions.checkState(
+        !Files.exists(secondaryDexPath), "Path should not already exist: " + secondaryDexPath);
+    Preconditions.checkState(
+        Files.exists(rawSecondaryDexPath), "Expected file to exist at: " + rawSecondaryDexPath);
+    Path canaryClass = createCanaryClass(canaryClassDirectory, canaryIndex);
+    try {
+      D8Utils.runD8Command(
+          new D8Utils.D8DiagnosticsHandler(),
+          secondaryDexPath,
+          ImmutableList.of(rawSecondaryDexPath, canaryClass),
+          getD8Options(),
+          Optional.empty(),
+          Paths.get(androidJar),
+          ImmutableList.of(),
+          minSdkVersion);
+    } catch (CompilationFailedException e) {
+      throw new IOException(e);
+    }
+  }
+
+  private static void runInParallel(List<Callable<Void>> tasks, String label) throws IOException {
+    if (tasks.isEmpty()) {
+      return;
+    }
+    int threadCount = Math.min(tasks.size(), Runtime.getRuntime().availableProcessors());
+    ExecutorService executor = Executors.newFixedThreadPool(threadCount);
+    try {
+      for (Future<Void> future : executor.invokeAll(tasks)) {
+        future.get();
+      }
+    } catch (ExecutionException e) {
+      Throwable cause = e.getCause();
+      throw (cause instanceof IOException)
+          ? (IOException) cause
+          : new IOException(label + " failed", cause);
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+      throw new IOException(label + " interrupted", e);
+    } finally {
+      executor.shutdownNow();
+    }
+  }
+
+  private Path createCanaryClass(Path directory, int index) throws IOException {
+    String className =
+        CanaryUtils.getFullyQualifiedCanaryClassName(canaryClassName, index).replace('.', '/');
+    byte[] canaryClassBytes = CanaryUtils.createCanaryClassByteCode(className);
+
+    Path canaryClassPath = directory.resolve(className + ".class");
+    Files.createDirectories(Objects.requireNonNull(canaryClassPath.getParent()));
+    Files.write(canaryClassPath, canaryClassBytes);
+
+    return canaryClassPath;
+  }
+
+  private String getRawSecondaryDexName(String module, int emittedCount, int index) {
+    index += emittedCount;
+    if (APKModule.isRootModule(module)) {
+      Preconditions.checkState(emittedCount >= 1, "Expected to have generated primary dex already");
+      return String.format("classes%d.dex", index + 1);
+    } else if (index == 0) {
+      return "classes.dex";
+    } else {
+      return String.format("classes%d.dex", index + 1);
+    }
+  }
+
+  private static class PrimaryDexClassNamesHolder {
+    private final ImmutableList<String> primaryDexClassNames;
+    private final ImmutableList<String> deobfuscatedPrimaryDexClassNames;
+
+    private PrimaryDexClassNamesHolder(
+        ImmutableList<String> primaryDexClassNames,
+        ImmutableList<String> deobfuscatedPrimaryDexClassNames) {
+      this.primaryDexClassNames = primaryDexClassNames;
+      this.deobfuscatedPrimaryDexClassNames = deobfuscatedPrimaryDexClassNames;
+    }
+  }
+
+  private PrimaryDexClassNamesHolder getPrimaryDexClassNames(
+      ImmutableList<Path> filesToDex,
+      Predicate<String> primaryDexClassNameMatcher,
+      Function<String, String> deobfuscateFunction)
+      throws IOException {
+
+    ImmutableList.Builder<String> primaryDexClassNames = ImmutableList.builder();
+    ImmutableList.Builder<String> deobfuscatedPrimaryDexClassNames = ImmutableList.builder();
+
+    for (Path fileToDex : filesToDex) {
+      try (ZipFile zipFile = new ZipFile(fileToDex.toFile())) {
+        Enumeration<? extends ZipEntry> entries = zipFile.entries();
+        while (entries.hasMoreElements()) {
+          ZipEntry zipEntry = entries.nextElement();
+          String zipEntryName = zipEntry.getName();
+          // Ignore non-.class files.
+          if (!zipEntryName.endsWith(CLASS_NAME_SUFFIX)) {
+            continue;
+          }
+
+          String deobfuscatedClassName =
+              Objects.requireNonNull(
+                  deobfuscateFunction.apply(
+                      zipEntryName.substring(
+                          0, zipEntryName.length() - CLASS_NAME_SUFFIX.length())));
+          if (primaryDexClassNameMatcher.test(deobfuscatedClassName)) {
+            primaryDexClassNames.add(zipEntryName);
+            deobfuscatedPrimaryDexClassNames.add(deobfuscatedClassName + ".class");
+          }
+        }
+      }
+    }
+
+    return new PrimaryDexClassNamesHolder(
+        primaryDexClassNames.build(), deobfuscatedPrimaryDexClassNames.build());
+  }
+
+  /**
+   * Look into the given jars to dex, returning the first entry name that looks like a class.
+   *
+   * @param filesToDex
+   * @return
+   */
+  String extractFirstClassNameFromInputs(ImmutableList<Path> filesToDex) throws IOException {
+    for (Path fileToDex : filesToDex) {
+      try (ZipFile zipFile = new ZipFile(fileToDex.toFile())) {
+        Enumeration<? extends ZipEntry> entries = zipFile.entries();
+        while (entries.hasMoreElements()) {
+          ZipEntry zipEntry = entries.nextElement();
+          String zipEntryName = zipEntry.getName();
+          // Ignore non-.class files.
+          if (!zipEntryName.endsWith(CLASS_NAME_SUFFIX)) {
+            continue;
+          }
+          return zipEntryName;
+        }
+      }
+    }
+    throw new IllegalStateException("No classes to dex");
+  }
+
+  /**
+   * Most invocations to this tool neglect to pass in a minSdkVersion. As a result, d8 won't make
+   * multiple dex files unless its given a main dex list. How we are using d8 is a bit ridiculous,
+   * we pretend to be generating code as if it's the stone age without a modern minSdkVersion. So,
+   * this helper function is a way to grab 1 class name from the inputs for the main dex list, so
+   * that d8 has something to chew on.
+   *
+   * @param filesToDex The files that will be passed to d8.
+   * @param desc Part of the file name for the temp txt file returned
+   * @return A temp file path with one class name in it.
+   */
+  Path synthesizePrimaryDexClassNamesFileForDexes(ImmutableList<Path> filesToDex, String desc)
+      throws IOException {
+    Path primaryDexClassNamesPath = Files.createTempFile("primary_dex_class_names_" + desc, "txt");
+    String className = extractFirstClassNameFromInputs(filesToDex);
+    Files.write(primaryDexClassNamesPath, ImmutableList.of(className));
+    return primaryDexClassNamesPath;
+  }
+
+  private Set<D8Options> getD8Options() {
+    ImmutableSet.Builder<D8Options> d8OptionsBuilder = ImmutableSet.builder();
+    if (noOptimize) {
+      d8OptionsBuilder.add(D8Options.NO_OPTIMIZE);
+    }
+    d8OptionsBuilder.add(D8Options.MAXIMIZE_PRIMARY_DEX);
+
+    return d8OptionsBuilder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/SecondaryDexCompressionExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/SecondaryDexCompressionExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/dex/SecondaryDexCompressionExecutableMain.java
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.dex;
+
+import com.facebook.buck.android.apkmodule.APKModule;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.io.ByteStreams;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+import org.tukaani.xz.LZMA2Options;
+import org.tukaani.xz.XZ;
+import org.tukaani.xz.XZOutputStream;
+
+/** Executable for compressing secondary dex files. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class SecondaryDexCompressionExecutableMain {
+  @Option(name = "--secondary-dex-output-dir", required = true)
+  private String secondaryDexOutputDirString;
+
+  @Option(name = "--raw-secondary-dexes-dir", required = true)
+  private String rawSecondaryDexesDir;
+
+  @Option(name = "--module", required = true)
+  private String module;
+
+  @Nullable
+  @Option(name = "--module-deps")
+  private String moduleDepsPathString = null;
+
+  @Option(name = "--canary-class-name", required = true)
+  private String canaryClassName;
+
+  @Option(name = "--compression", required = true)
+  private String compression;
+
+  @Option(name = "--xz-compression-level")
+  private int xzCompressionLevel = -1;
+
+  // Optional, if this is the main module there may be N dex files that are being treated as
+  // preceding these given secondary dex files.
+  @Nullable
+  @Option(name = "--bootstrap-dexes-dir")
+  private String bootstrapDexDirString = null;
+
+  // Defaulted to 1 for the primary dex (classes.dex) upon which these secondaries will be numbered
+  // after. If enabling bootstrap dex files, secondaries could start at a higher index.
+  private int baseApkDexFileCount;
+
+  public static void main(String[] args) throws IOException {
+    SecondaryDexCompressionExecutableMain main = new SecondaryDexCompressionExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    Path rawSecondaryDexesDirPath = Paths.get(rawSecondaryDexesDir);
+    Preconditions.checkState(
+        ImmutableList.of("raw", "raw_subdir", "jar", "xzs").contains(compression),
+        "Only raw, raw_subdir, jar and xzs compression is supported!");
+    Preconditions.checkState(
+        compression.equals("raw")
+            || compression.equals("raw_subdir")
+            || compression.equals("jar")
+            || xzCompressionLevel != -1,
+        "Must specify a valid compression level when xzs compression is used!");
+
+    if (bootstrapDexDirString != null) {
+      Path bootstrapDexDir = Paths.get(bootstrapDexDirString);
+      baseApkDexFileCount = 1 + (int) Files.list(bootstrapDexDir).count();
+    } else {
+      baseApkDexFileCount = 1;
+    }
+    Path secondaryDexOutputDir = Paths.get(secondaryDexOutputDirString);
+    Files.createDirectories(secondaryDexOutputDir);
+    Path secondaryDexSubdir = secondaryDexOutputDir.resolve(getSecondaryDexSubDir(module));
+    Files.createDirectories(secondaryDexSubdir);
+
+    long secondaryDexCount = Files.list(rawSecondaryDexesDirPath).count();
+    ImmutableList.Builder<String> metadataLines = ImmutableList.builder();
+    if (!APKModule.isRootModule(module)) {
+      metadataLines.add(String.format(".id %s", module));
+    }
+    Preconditions.checkState((moduleDepsPathString == null) == APKModule.isRootModule(module));
+    if (moduleDepsPathString != null) {
+      metadataLines.addAll(
+          Files.readAllLines(Paths.get(moduleDepsPathString)).stream()
+              .map(moduleDep -> String.format(".requires %s", moduleDep))
+              .collect(ImmutableList.toImmutableList()));
+    }
+
+    if (compression.equals("raw") || compression.equals("raw_subdir")) {
+      if (APKModule.isRootModule(module) && compression.equals("raw")) {
+        metadataLines.add(".root_relative");
+      }
+      for (int i = 0; i < secondaryDexCount; i++) {
+        String secondaryDexName = getRawSecondaryDexName(module, i);
+        Path rawSecondaryDexPath = rawSecondaryDexesDirPath.resolve(secondaryDexName);
+        Path copiedDex =
+            compression.equals("raw")
+                ? secondaryDexOutputDir
+                    .resolve(D8Utils.getRawSecondaryDexSubDir(module))
+                    .resolve(secondaryDexName)
+                : secondaryDexSubdir.resolve(getSecondaryDexName(module, i, ""));
+        ;
+        Files.copy(rawSecondaryDexPath, copiedDex);
+        metadataLines.add(
+            D8Utils.getSecondaryDexMetadataString(
+                copiedDex, CanaryUtils.getFullyQualifiedCanaryClassName(canaryClassName, i)));
+      }
+    } else {
+      ImmutableList.Builder<Path> secondaryDexJarPaths = ImmutableList.builder();
+      for (int i = 0; i < secondaryDexCount; i++) {
+        String secondaryDexName = getRawSecondaryDexName(module, i);
+        Path rawSecondaryDexPath = rawSecondaryDexesDirPath.resolve(secondaryDexName);
+        Preconditions.checkState(
+            Files.exists(rawSecondaryDexPath), "Expected file to exist at: " + rawSecondaryDexPath);
+        Path secondaryDexOutputJarPath =
+            compression.equals("xzs")
+                ? secondaryDexSubdir.resolve(getSecondaryDexName(module, i, ".jar.xzs.tmp~"))
+                : secondaryDexSubdir.resolve(getSecondaryDexName(module, i, ".jar"));
+        secondaryDexJarPaths.add(secondaryDexOutputJarPath);
+
+        Path metadataPath =
+            secondaryDexOutputJarPath.resolveSibling(
+                secondaryDexOutputJarPath.getFileName() + ".meta");
+        D8Utils.writeSecondaryDexJarAndMetadataFile(
+            secondaryDexOutputJarPath, metadataPath, rawSecondaryDexPath, compression);
+
+        metadataLines.add(
+            D8Utils.getSecondaryDexMetadataString(
+                secondaryDexOutputJarPath,
+                CanaryUtils.getFullyQualifiedCanaryClassName(canaryClassName, i)));
+      }
+
+      if (compression.equals("xzs")) {
+        doXzsCompression(secondaryDexSubdir, secondaryDexJarPaths.build());
+      }
+    }
+
+    Files.write(secondaryDexSubdir.resolve("metadata.txt"), metadataLines.build());
+  }
+
+  private String getRawSecondaryDexName(String module, int index) {
+    if (APKModule.isRootModule(module)) {
+      return String.format("classes%d.dex", index + baseApkDexFileCount + 1);
+    } else if (index == 0) {
+      return "classes.dex";
+    } else {
+      return String.format("classes%d.dex", index + 1);
+    }
+  }
+
+  private String getSecondaryDexSubDir(String module) {
+    if (APKModule.isRootModule(module)) {
+      return "assets/secondary-program-dex-jars";
+    } else {
+      return String.format("assets/%s", module);
+    }
+  }
+
+  private String getSecondaryDexName(String module, int index, String suffix) {
+    return String.format(
+        "%s-%d.dex%s", APKModule.isRootModule(module) ? "secondary" : module, index + 1, suffix);
+  }
+
+  private void doXzsCompression(Path secondaryDexSubdir, ImmutableList<Path> secondaryDexJarPaths)
+      throws IOException {
+    try (OutputStream secondaryDexOutput =
+            new BufferedOutputStream(
+                new FileOutputStream(
+                    secondaryDexSubdir
+                        .resolve(
+                            String.format(
+                                "%s.dex.jar.xzs",
+                                APKModule.isRootModule(module) ? "secondary" : module))
+                        .toFile()));
+        XZOutputStream xzOutputStream =
+            new XZOutputStream(
+                secondaryDexOutput, new LZMA2Options(xzCompressionLevel), XZ.CHECK_CRC32)) {
+      for (Path secondaryDexJarPath : secondaryDexJarPaths) {
+        try (InputStream secondaryDexInputStream =
+            new BufferedInputStream(new FileInputStream(secondaryDexJarPath.toFile()))) {
+          ByteStreams.copy(secondaryDexInputStream, xzOutputStream);
+        }
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AdbUtils.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AdbUtils.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AdbUtils.kt
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage
+
+import com.facebook.buck.core.util.log.Logger
+import java.io.BufferedReader
+import java.io.InputStreamReader
+
+data class AdbCommandResult(val exitCode: Int, val output: String, val error: String? = null)
+
+class AdbCommandFailedException(message: String) : Exception(message)
+
+enum class SetDebugAppMode {
+  SKIP,
+  SET,
+}
+
+class AdbUtils(val adb: String, val adbServerPort: Int) {
+
+  fun executeAdbShellCommand(
+      command: String,
+      deviceId: String,
+      ignoreFailure: Boolean = false,
+  ): String {
+    return executeAdbCommand("shell $command", deviceId, ignoreFailure)
+  }
+
+  fun executeAdbCommand(
+      command: String,
+      deviceId: String?,
+      ignoreFailure: Boolean = false,
+  ): String {
+    val adbCommandResult: AdbCommandResult =
+        try {
+          runAdbCommand((deviceId?.let { "-s $deviceId " } ?: "") + command)
+        } catch (e: Exception) {
+          error("Failed to execute adb command 'adb $command' on device $deviceId.\n${e.message}")
+        }
+    return if (adbCommandResult.exitCode != 0) {
+      val error =
+          "Executing 'adb $command' on $deviceId failed with code ${adbCommandResult.exitCode}." +
+              (adbCommandResult.output.takeIf { it.isNotBlank() }?.let { "\nOutput:\n$it" } ?: "") +
+              (adbCommandResult.error?.let { "\nError:\n$it" } ?: "")
+      if (!ignoreFailure) {
+        LOG.error(error)
+        throw AdbCommandFailedException(error)
+      } else {
+        LOG.info("ignoreFailure=true: " + error)
+        adbCommandResult.output
+      }
+    } else {
+      adbCommandResult.output
+    }
+  }
+
+  private fun runAdbCommand(input: String): AdbCommandResult {
+    val command = "$adb " + (if (adbServerPort != 0) "-P $adbServerPort " else "") + "$input"
+    LOG.info("Running command: $command")
+    val processBuilder = ProcessBuilder(*command.split(" ").toTypedArray())
+    val process = processBuilder.start()
+    try {
+      return readAdbCommandResult(process)
+    } finally {
+      // Reading either stream can fail, and a child left running would hold its pipes open for the
+      // life of the installer. Already-exited is the normal case, where this does nothing.
+      if (process.isAlive) {
+        process.destroyForcibly()
+      }
+    }
+  }
+
+  private fun readAdbCommandResult(process: Process): AdbCommandResult {
+    // Drained on its own thread: a process blocked writing to a full pipe never exits, so reading
+    // one stream to the end before starting on the other hangs on any command whose unread stream
+    // outgrows the pipe buffer. `adb shell` reports per-file failures on stderr, so a command over
+    // many files reaches that in the failure case.
+    val errorOutput = StringBuilder()
+    var drainFailure: Throwable? = null
+    val drainError = Thread {
+      try {
+        BufferedReader(InputStreamReader(process.errorStream)).use { reader ->
+          var line: String? = reader.readLine()
+          while (line != null) {
+            errorOutput.append(line).append("\n")
+            line = reader.readLine()
+          }
+        }
+      } catch (t: Throwable) {
+        // Rethrown by the caller after the join below, which would otherwise hand back a result
+        // built from silently truncated stderr.
+        drainFailure = t
+      }
+    }
+        .apply {
+          isDaemon = true
+          name = "adb-stderr"
+          start()
+        }
+
+    val output = StringBuilder()
+    BufferedReader(InputStreamReader(process.inputStream)).use { reader ->
+      var line: String? = reader.readLine()
+      while (line != null) {
+        output.append(line).append("\n")
+        line = reader.readLine()
+      }
+    }
+    drainError.join()
+    drainFailure?.let { throw it }
+    val exitCode = process.waitFor()
+    return AdbCommandResult(
+        exitCode,
+        output = output.toString().trim(),
+        error = if (errorOutput.isNotEmpty()) errorOutput.toString() else null,
+    )
+  }
+
+  fun getDevices(): List<AndroidDevice> {
+    val devicesOutput: String = executeAdbCommand("devices", null)
+    val devices: List<String> = devicesOutput.split("\n").drop(1).filter { it.isNotBlank() }
+    return if (devices.isEmpty()) {
+      emptyList()
+    } else {
+      devices.map { AndroidDeviceImpl(it.split("\\s+".toRegex())[0], this) }
+    }
+  }
+
+  fun restart() {
+    executeAdbCommand("kill-server", null)
+    executeAdbCommand("start-server", null)
+  }
+
+  /**
+   * @return Command to register the app being installed as the system's current debug app,
+   *   silencing ANRs.
+   */
+  fun getAmSetDebugAppCommand(packageName: String): String {
+
+    // --persistent allows the developer to bypass ANRs on subsequent runs (i.e. if they resumed
+    // debugging later after disconnecting the device and relaunching), and set
+    // `Settings.Global.DEBUG_APP`. See: https://developer.android.com/studio/command-line/adb#am
+    return "am set-debug-app --persistent $packageName "
+  }
+
+  companion object {
+    val LOG: Logger = Logger.get(AdbUtils::class.java.name)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDevice.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDevice.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDevice.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableSortedSet;
+import java.io.File;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.jetbrains.annotations.Nullable;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface AndroidDevice {
+  default boolean installApkOnDevice(
+      File apk,
+      boolean installViaSd,
+      boolean quiet,
+      boolean stagedInstallMode,
+      String packageName) {
+    return installApkOnDevice(apk, installViaSd, quiet, true, stagedInstallMode, packageName);
+  }
+
+  default boolean installApkOnDevice(
+      File apk,
+      boolean installViaSd,
+      boolean quiet,
+      boolean verifyTempWritable,
+      boolean stagedInstallMode,
+      String packageName) {
+    return installApkOnDevice(
+        apk, installViaSd, quiet, verifyTempWritable, stagedInstallMode, null, packageName);
+  }
+
+  default boolean installApkOnDevice(
+      File apk,
+      boolean installViaSd,
+      boolean quiet,
+      boolean verifyTempWritable,
+      boolean stagedInstallMode,
+      @Nullable String userId,
+      String packageName) {
+    return installApkOnDevice(
+        apk, installViaSd, quiet, verifyTempWritable, stagedInstallMode, userId, true, packageName);
+  }
+
+  /**
+   * Install an APK on the device with optional user targeting, then confirm it actually landed.
+   *
+   * <p>After installing, the on-device apk is read back and compared to {@code apk}; if the package
+   * is missing or the on-device apk is stale (which adb can report as success, notably under {@code
+   * --fastdeploy}, where the real failure only reaches logcat), the install is retried without
+   * {@code --fastdeploy}. The call fails if the apk still does not match. Staged installs are not
+   * verified, since they are not applied until reboot.
+   *
+   * @param apk The APK file to install
+   * @param installViaSd Whether to install via SD card
+   * @param quiet If true, suppress output
+   * @param verifyTempWritable If true, verify temp folder is writable before install
+   * @param stagedInstallMode If true, use staged installation
+   * @param userId User to install for: "all" for all users, a specific user ID (e.g., "10"), or
+   *     null for default behavior (current user only)
+   * @param allowFastDeploy If true, this install may use `adb install --fastdeploy` on supported
+   *     devices.
+   * @param packageName The package name of {@code apk}, used to read the installed apk back and
+   *     verify the install took effect.
+   * @return true if installation succeeded
+   */
+  boolean installApkOnDevice(
+      File apk,
+      boolean installViaSd,
+      boolean quiet,
+      boolean verifyTempWritable,
+      boolean stagedInstallMode,
+      @Nullable String userId,
+      boolean allowFastDeploy,
+      String packageName);
+
+  default boolean installApexOnDevice(File apex, boolean quiet) {
+    return installApexOnDevice(apex, quiet, true);
+  }
+
+  default boolean installApexOnDevice(File apex, boolean quiet, boolean restart) {
+    return installApexOnDevice(apex, quiet, restart, false);
+  }
+
+  default boolean installApexOnDevice(
+      File apex, boolean quiet, boolean restart, boolean waitForDeviceReady) {
+    boolean softRebootAvailable = prepareForApexInstallation();
+    return installApexOnDevice(apex, quiet, restart, softRebootAvailable, waitForDeviceReady);
+  }
+
+  boolean installApexOnDevice(
+      File apex,
+      boolean quiet,
+      boolean restart,
+      boolean softRebootAvailable,
+      boolean waitForDeviceReady);
+
+  boolean prepareForApexInstallation();
+
+  void stopPackage(String packageName) throws Exception;
+
+  Optional<PackageInfo> getPackageInfo(String packageName) throws Exception;
+
+  void uninstallPackage(String packageName) throws Exception;
+
+  String getApkManifestDigest(String packagePath) throws Exception;
+
+  String getContentHash(String path) throws Exception;
+
+  ImmutableSortedSet<Path> listDirRecursive(Path dirPath) throws Exception;
+
+  void rmFiles(String dirPath, Iterable<String> filesToDelete);
+
+  /**
+   * Removes scratch this device left behind while installing {@code packageName}, including whole
+   * payloads orphaned by an install interrupted mid-transfer. Does not touch installed files.
+   */
+  void rmStaleFiles(String packageName) throws Exception;
+
+  /**
+   * Pushes {@code installPaths}, a map of device destination to local source.
+   *
+   * <p>Called concurrently for the same package: an install pushes its payload as several shards at
+   * once. Whatever an implementation stages under has to be unique per call, or concurrent shards
+   * overwrite each other on the way in.
+   *
+   * @param packageName the app these files belong to. Scopes whatever scratch the device needs, so
+   *     that installs of different apps cannot disturb each other's transfers.
+   */
+  void installFiles(String filesType, Map<Path, Path> installPaths, String packageName)
+      throws Exception;
+
+  void mkDirP(String dirpath) throws Exception;
+
+  String getProperty(String name) throws Exception;
+
+  List<String> getDeviceAbis() throws Exception;
+
+  void killProcess(String processName) throws Exception;
+
+  String getSerialNumber();
+
+  String getWindowManagerProperty(String propertyName) throws Exception;
+
+  boolean isEmulator();
+
+  boolean isOnline();
+
+  boolean installBuildUuidFile(Path dataRoot, String packageName, String buildUuid)
+      throws Exception;
+
+  String deviceStartIntent(@Nullable AndroidIntent intent) throws Exception;
+
+  boolean uninstallApkFromDevice(String packageName, boolean keepData) throws Exception;
+
+  /**
+   * Size, used and available space on the data partition, or {@code "_"} for each if it cannot be
+   * read.
+   *
+   * @param humanReadable values suffixed for display, e.g. {@code 17G}. Otherwise they are plain
+   *     counts of 1K blocks, which is what arithmetic wants.
+   */
+  default List<String> getDiskSpace(boolean humanReadable) {
+    return Arrays.asList("_", "_", "_");
+  }
+
+  default void fixRootDir(String rootDir) {}
+
+  boolean setDebugAppPackageName(@Nullable String packageName) throws Exception;
+
+  void enableAppLinks(@Nullable String packageName) throws Exception;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDeviceImpl.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDeviceImpl.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDeviceImpl.kt
@@ -0,0 +1,843 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage
+
+import com.facebook.buck.core.util.log.Logger
+import com.facebook.buck.installer.android.AndroidInstallException
+import com.google.common.base.Splitter
+import com.google.common.collect.ImmutableSortedSet
+import com.google.common.collect.Sets
+import java.io.File
+import java.io.IOException
+import java.lang.Thread.sleep
+import java.nio.file.Files
+import java.nio.file.Path
+import java.nio.file.Paths
+import java.nio.file.StandardCopyOption
+import java.security.MessageDigest
+import java.util.Optional
+import java.util.UUID
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.ConcurrentMap
+import java.util.regex.Pattern
+import kotlin.system.measureTimeMillis
+
+class AndroidDeviceImpl(val serial: String, val adbUtils: AdbUtils) : AndroidDevice {
+
+  private val properties: ConcurrentMap<String, String> = ConcurrentHashMap()
+
+  override fun installApkOnDevice(
+      apk: File,
+      installViaSd: Boolean,
+      quiet: Boolean,
+      verifyTempWritable: Boolean,
+      stagedInstallMode: Boolean,
+      userId: String?,
+      allowFastDeploy: Boolean,
+      packageName: String,
+  ): Boolean {
+    val elapsed = measureTimeMillis {
+      if (verifyTempWritable) {
+        try {
+          val uniqueFileName = "buck-experiment-${UUID.randomUUID()}"
+          executeAdbShellCommand("echo exo > /data/local/tmp/$uniqueFileName")
+          executeAdbShellCommand("rm /data/local/tmp/$uniqueFileName")
+        } catch (e: AdbCommandFailedException) {
+          // TODO: we should check for specific failure here
+          LOG.error("Failed to write to /data/local/tmp: ${e.message}")
+          throw AndroidInstallException.tempFolderNotWritable()
+        }
+      }
+
+      var installCommand: String
+      // Fast path: use --fastdeploy on SDK-supported devices.
+      // On any failure we fall back to a plain install.
+      if (allowFastDeploy && !stagedInstallMode && sdkSupportsFastDeploy()) {
+        installCommand = buildInstallCommand(apk, true, stagedInstallMode, userId)
+        try {
+          executeAdbCommandCatching(
+              installCommand,
+              "Failed to install ${apk.name} with --fastdeploy.",
+          )
+          verifyInstalledApkMatches(apk, packageName)
+          return@measureTimeMillis
+        } catch (e: AndroidInstallException) {
+          LOG.warn(
+              "The fast install failed or left the on-device apk missing or stale: ${e.message}.\n" +
+                  "Reinstalling ${apk.name} without --fastdeploy to recover.",
+          )
+        }
+      }
+
+      installCommand = buildInstallCommand(apk, false, stagedInstallMode, userId)
+      try {
+        executeAdbCommand(installCommand)
+      } catch (e: AdbCommandFailedException) {
+        val conflictingPackage = extractSignatureMismatchPackage(e.message)
+        if (conflictingPackage == null) {
+          throw AndroidInstallException.adbCommandFailedException(
+              "Failed to install ${apk.name}.",
+              e.message,
+          )
+        }
+        LOG.warn(
+            "Install of ${apk.name} failed because $conflictingPackage is already installed with a" +
+                " mismatched signature; uninstalling it and retrying the install.",
+        )
+        executeAdbCommandCatching(
+            "uninstall $conflictingPackage",
+            "Failed to uninstall $conflictingPackage while recovering from a signature mismatch.",
+        )
+        executeAdbCommandCatching(
+            installCommand,
+            "Failed to install ${apk.name} after uninstalling $conflictingPackage.",
+        )
+      }
+
+      if (!stagedInstallMode) {
+        verifyInstalledApkMatches(apk, packageName)
+      }
+    }
+    val userSuffix = if (userId != null) " for user $userId" else ""
+    val kbps = (apk.length() / 1024.0) / (elapsed / 1000.0)
+    LOG.info(
+        "Installed ${apk.name}$userSuffix (${apk.length()} bytes) in ${elapsed/1000.0} s ($kbps kB/s)",
+    )
+    return true
+  }
+
+  /**
+   * Verifies that the apk installed for [packageName] matches [apk] byte-for-byte (adb stores it
+   * verbatim). Always throws [AndroidInstallException] on failure: tagged
+   * [AndroidInstallErrorTag.INSTALLED_APK_MISMATCH] if the package is absent or the on-device apk
+   * differs, and tagged [AndroidInstallErrorTag.ADB_COMMAND_FAILED] if the on-device apk cannot be
+   * read back.
+   */
+  private fun verifyInstalledApkMatches(apk: File, packageName: String) {
+    val installedApk =
+        getPackageInfo(packageName).orElseThrow {
+          AndroidInstallException.installedApkMismatch(
+              "Install of ${apk.name} could not be verified: $packageName is not present on the" +
+                  " device after installing.",
+          )
+        }
+    val installedHash =
+        try {
+          getContentHash(installedApk.apkPath)
+        } catch (e: AdbCommandFailedException) {
+          throw AndroidInstallException.adbCommandFailedException(
+              "Could not read the on-device apk for $packageName to verify the install of" +
+                  " ${apk.name}.",
+              e.message,
+          )
+        }
+    val localApkHash = sha256Hex(apk)
+    if (!installedHash.equals(localApkHash, ignoreCase = true)) {
+      throw AndroidInstallException.installedApkMismatch(
+          "Install of ${apk.name} could not be verified: the on-device apk for $packageName does" +
+              " not match the local apk after installing.",
+      )
+    }
+  }
+
+  @Throws(Exception::class)
+  override fun getContentHash(path: String): String {
+    val output = executeAdbShellCommand("sha256sum $path").trim()
+    val hash = output.split(Regex("\\s+")).first()
+    // `sha256sum` can report an error on stdout (e.g. a missing file) while adb still exits 0, so
+    // the first token is not always a digest. Treat any non-hex output as a read failure so the
+    // caller surfaces ADB_COMMAND_FAILED rather than a misleading apk mismatch.
+    if (!hash.matches(Regex("[0-9a-fA-F]{64}"))) {
+      throw AdbCommandFailedException("sha256sum returned unexpected output for $path: \"$output\"")
+    }
+    return hash
+  }
+
+  private fun sha256Hex(file: File): String {
+    val digest = MessageDigest.getInstance("SHA-256")
+    file.inputStream().use { input ->
+      val buffer = ByteArray(8192)
+      var read = input.read(buffer)
+      while (read >= 0) {
+        digest.update(buffer, 0, read)
+        read = input.read(buffer)
+      }
+    }
+    return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xFF) }
+  }
+
+  /**
+   * Returns the package name from an adb `INSTALL_FAILED_UPDATE_INCOMPATIBLE` failure (signature
+   * mismatch), or null if the failure is not a signature mismatch. The package name is parsed from
+   * adb's message, e.g. "Existing package com.meta.ar.helixserver signatures do not match ...".
+   */
+  private fun extractSignatureMismatchPackage(message: String?): String? {
+    if (message == null || !message.contains(INSTALL_FAILED_UPDATE_INCOMPATIBLE)) {
+      return null
+    }
+    return SIGNATURE_MISMATCH_PACKAGE_PATTERN.find(message)?.groupValues?.getOrNull(1)?.takeIf {
+      PACKAGE_NAME_PATTERN.matches(it)
+    }
+  }
+
+  private fun buildInstallCommand(
+      apk: File,
+      fastDeploy: Boolean,
+      stagedInstallMode: Boolean,
+      userId: String?,
+  ): String = buildString {
+    append("install -r -d")
+    if (fastDeploy) append(" --fastdeploy")
+    if (stagedInstallMode) append(" --staged")
+    if (userId != null) append(" --user $userId")
+    append(" ${apk.absolutePath}")
+  }
+
+  private fun sdkSupportsFastDeploy(): Boolean {
+    val sdkVersion =
+        try {
+          getProperty("ro.build.version.sdk").toInt()
+        } catch (e: Exception) {
+          LOG.warn("Unable to determine SDK version, defaulting to legacy install: ${e.message}")
+          -1
+        }
+
+    return sdkVersion >= MIN_SDK_VERSION_FOR_FASTDEPLOY
+  }
+
+  override fun prepareForApexInstallation(): Boolean {
+    executeAdbCommand("root")
+    sleep(5000)
+    executeAdbCommand("wait-for-device")
+
+    // Root kills adbd, and sometimes, it takes a while for it to come back
+    for (i in 1..3) {
+      if (executeAdbShellCommand("whoami").equals("root")) {
+        break
+      }
+      sleep(1000)
+    }
+
+    val softRebootAvailable =
+        executeAdbShellCommand("pm", ignoreFailure = true).contains("force-non-staged")
+    LOG.info("Soft reboot available: $softRebootAvailable")
+    return softRebootAvailable
+  }
+
+  override fun installApexOnDevice(
+      apex: File,
+      quiet: Boolean,
+      restart: Boolean,
+      softRebootAvailable: Boolean,
+      waitForDeviceReady: Boolean,
+  ): Boolean {
+    val elapsed = measureTimeMillis {
+      try {
+        val installArgs = "--apex ${if (softRebootAvailable) "--force-non-staged" else ""}".trim()
+        executeAdbCommand("install $installArgs ${apex.absolutePath}")
+      } catch (e: AdbCommandFailedException) {
+        if ((e.message ?: "").contains("INSTALL_FAILED_VERIFICATION_FAILURE: Staged session ")) {
+          throw AndroidInstallException.rebootRequired(
+              "Device is already staged; You need to run 'adb reboot' on your device.",
+          )
+        }
+
+        // if the device can't install because the list of native libs is different,
+        // retry without the --force-non-staged flag. Then reboot automatically.
+        if (
+            (e.message ?: "").contains(
+                "INSTALL_FAILED_INTERNAL_ERROR: APEX installation failed: Set of native libs required",
+            )
+        ) {
+          // try install again without --force-non-staged
+          executeAdbCommandCatching(
+              "install -d --apex ${apex.absolutePath}",
+              "Failed to install ${apex.name}.",
+          )
+          throw AndroidInstallException.rebootRequired(
+              "Installed ${apex.name} on device; however --force-non-staged doesn't work when the" +
+                  " native lib dependencies of an apex have changed. You need to run 'adb" +
+                  " reboot' on your device to complete the install. See also:" +
+                  " https://www.internalfb.com/intern/wiki/RL/RL_Release_and_Reliability/Build_and_Release_Infra/APEX_in_fbsource/Pit_falls/",
+          )
+        }
+
+        // If the apex package has changed (e.g. not previously), fall back to
+        // remount + push so the apex lands directly in /system/apex.
+        if ((e.message ?: "").contains("INSTALL_FAILED_PACKAGE_CHANGED")) {
+          LOG.info(
+              "INSTALL_FAILED_PACKAGE_CHANGED for ${apex.name}, " +
+                  "attempting fallback install via remount and push",
+          )
+          try {
+            // Remount so that we can write to /system_ext/apex
+            executeAdbCommand("root")
+            executeAdbCommand("wait-for-device")
+            executeAdbCommand("remount")
+
+            // Remount sometimes requires a reboot because verity is enabled.
+            if (executeAdbShellCommand("getprop ro.boot.veritymode") == "enforcing") {
+              executeAdbCommand("reboot")
+              executeAdbCommand("wait-for-device")
+              waitForBootComplete()
+
+              executeAdbCommand("root")
+              executeAdbCommand("wait-for-device")
+              executeAdbCommand("remount")
+            }
+
+            // Potentially make this customizable in the future.
+            executeAdbCommand("push ${apex.absolutePath} /system_ext/apex/")
+
+            // Reboot to activate the apex
+            executeAdbCommand("reboot")
+            executeAdbCommand("wait-for-device")
+            waitForBootComplete()
+          } catch (fallbackError: AdbCommandFailedException) {
+            throw AndroidInstallException.adbCommandFailedException(
+                "Failed to install ${apex.name} via fallback remount+push.",
+                fallbackError.message,
+            )
+          }
+          return@measureTimeMillis
+        }
+
+        throw AndroidInstallException.adbCommandFailedException(
+            "Failed to install ${apex.name}.",
+            e.message,
+        )
+      }
+
+      if (!softRebootAvailable) {
+        throw AndroidInstallException.rebootRequired(
+            "--force-non-staged is not available on device" +
+                "(is the device running an older build?); " +
+                "${apex.name} was installed successfully but will not be active until " +
+                "you run 'adb reboot' on your device",
+        )
+      }
+
+      if (restart) {
+        try {
+          executeAdbShellCommand("stop")
+          executeAdbShellCommand("start")
+
+          if (waitForDeviceReady) {
+            // Wait for device to be fully ready after soft reboot
+            waitForBootComplete()
+            waitUntilPackageManagerReady()
+            waitForStorageReady()
+          }
+        } catch (e: AdbCommandFailedException) {
+          throw AndroidInstallException.rebootRequired(
+              "Failed to stop+start shell; ${apex.name} was installed successfully but device will be in an unknown state until you run 'adb reboot'",
+          )
+        }
+      }
+    }
+    val kbps = (apex.length() / 1024.0) / (elapsed / 1000.0)
+    LOG.info("Installed ${apex.name} (${apex.length()} bytes) in ${elapsed/1000.0} s ($kbps kB/s)")
+    return true
+  }
+
+  private fun waitForBootComplete() {
+    waitForCondition(
+        command = "getprop sys.boot_completed",
+        condition = { output -> output.trim() == "1" },
+        successMessage = "Boot completed after soft reboot",
+        timeoutMessage = "Device did not complete boot after soft reboot within timeout",
+        timeoutMs = 80000, // Account for Horizon OS Emulator.
+    )
+  }
+
+  private fun waitUntilPackageManagerReady() {
+    waitForCondition(
+        command = "pm",
+        condition = { output -> output.isNotEmpty() && !output.contains("Can't find service") },
+        successMessage = "Package manager service ready",
+        timeoutMessage = "Package manager service did not become ready within timeout",
+    )
+  }
+
+  private fun waitForStorageReady() {
+    waitForCondition(
+        command = "ls /storage/emulated/0 2>&1 || echo STORAGE_NOT_READY",
+        condition = { output ->
+          !output.contains("Transport endpoint is not connected") &&
+              !output.contains("STORAGE_NOT_READY") &&
+              !output.contains("No such file or directory")
+        },
+        successMessage = "Storage filesystem ready",
+        timeoutMessage = "Storage filesystem did not become ready within timeout",
+        timeoutMs = 30000,
+    )
+  }
+
+  /**
+   * Polls a shell command until a condition is met or timeout is reached.
+   *
+   * @param command the shell command to execute
+   * @param condition a predicate that returns true when the desired state is reached
+   * @param successMessage message to log on success
+   * @param timeoutMessage message for the exception if timeout is reached
+   * @param timeoutMs maximum time to wait in milliseconds
+   * @param pollIntervalMs time between polling attempts in milliseconds
+   * @throws AndroidInstallException if the condition is not met within the timeout
+   */
+  private fun waitForCondition(
+      command: String,
+      condition: (String) -> Boolean,
+      successMessage: String,
+      timeoutMessage: String,
+      timeoutMs: Long = 10000,
+      pollIntervalMs: Long = 100,
+  ) {
+    LOG.info("Waiting for condition (timeout: ${timeoutMs}ms): $successMessage")
+    val startTime = System.currentTimeMillis()
+    var attempt = 0
+
+    while (System.currentTimeMillis() - startTime < timeoutMs) {
+      attempt++
+      if (condition(executeAdbShellCommand(command, ignoreFailure = true))) {
+        LOG.info(successMessage)
+        return
+      }
+      LOG.info("Attempt $attempt: condition not met, retrying in ${pollIntervalMs}ms...")
+      sleep(pollIntervalMs)
+    }
+
+    throw AndroidInstallException.rebootRequired(timeoutMessage)
+  }
+
+  override fun stopPackage(packageName: String) {
+    executeAdbShellCommandCatching(
+        "am force-stop $packageName",
+        "Failed to stop package $packageName.",
+    )
+  }
+
+  @Throws(Exception::class)
+  override fun getPackageInfo(packageName: String): Optional<PackageInfo> {
+    val output: String =
+        try {
+          executeAdbShellCommand("pm path $packageName")
+        } catch (e: AdbCommandFailedException) {
+          LOG.warn("Failed to get package info for $packageName: ${e.message}")
+          return Optional.empty()
+        }
+    // `pm path` prints one `package:<path>` line per installed apk (base plus any config splits),
+    // and prints nothing for a package that is not installed. Use the base apk (first line); treat
+    // output with no `package:` line as "not installed".
+    val apkPath =
+        output
+            .lineSequence()
+            .map { it.trim() }
+            .firstOrNull { it.startsWith("package:") }
+            ?.removePrefix("package:") ?: return Optional.empty()
+    return Optional.of(PackageInfo(apkPath, "", ""))
+  }
+
+  @Throws(Exception::class)
+  override fun uninstallPackage(packageName: String) {
+    executeAdbCommandCatching("uninstall $packageName", "Failed to uninstall $packageName.")
+  }
+
+  @Throws(Exception::class)
+  override fun getApkManifestDigest(packagePath: String): String {
+    val entry: String =
+        executeAdbShellCommand("unzip -l $packagePath | grep -E -o 'META-INF/[A-Z]+\\.SF'").trim()
+    val result: String = executeAdbShellCommand(
+        "unzip -p $packagePath $entry | grep -E 'SHA1-Digest-Manifest:|SHA-256-Digest-Manifest:'",
+    )
+    val (_, digest) = result.split(":", limit = 2)
+    return digest.trim()
+  }
+
+  @Throws(Exception::class)
+  override fun listDirRecursive(root: Path): ImmutableSortedSet<Path> {
+    val lsOutput: String =
+        executeAdbCommandCatching("shell ls -R $root", "Failed to list path $root.")
+
+    val paths: MutableSet<Path> = HashSet()
+    val dirs: MutableSet<Path?> = HashSet()
+    var currentDir: Path? = null
+    for (line in Splitter.on(LINE_ENDING).omitEmptyStrings().split(lsOutput)) {
+      if (line.endsWith(":")) {
+        currentDir = root.relativize(Paths.get(line.removeSuffix(":")))
+        dirs.add(currentDir)
+      } else {
+        checkNotNull(currentDir)
+        paths.add(currentDir.resolve(line))
+      }
+    }
+    return ImmutableSortedSet.copyOf<Path>(Sets.difference(paths, dirs))
+  }
+
+  override fun rmFiles(dirPath: String, filesToDelete: Iterable<String>) {
+    val elapsed: Long = measureTimeMillis {
+      val tempFile = File.createTempFile("files_to_delete", ".txt")
+      try {
+        tempFile.writeText(
+            filesToDelete.joinToString("\n") { Paths.get(dirPath).resolve(it).toString() },
+        )
+        executeAdbCommand("push -z brotli ${tempFile.absolutePath} /data/local/tmp")
+        executeAdbShellCommand("cat /data/local/tmp/${tempFile.name} | xargs rm -f")
+      } catch (e: AdbCommandFailedException) {
+        throw AndroidInstallException.adbCommandFailedException(
+            "Failed delete ${filesToDelete.count()} files from $dirPath.",
+            e.message,
+        )
+      } finally {
+        tempFile.delete()
+        executeAdbShellCommand("rm -f /data/local/tmp/${tempFile.name}")
+      }
+    }
+    LOG.info("Deleted ${filesToDelete.count()} files from $dirPath in ${elapsed/1000.0} seconds.")
+  }
+
+  @Throws(Exception::class)
+  override fun installFiles(
+      filesType: String,
+      installPaths: Map<Path, Path>,
+      packageName: String,
+  ) {
+    LOG.debug(
+        "%s: %s",
+        filesType,
+        installPaths
+            .map { "${it.value.parent} -> ${it.key.parent}" }
+            .distinct()
+            .joinToString(separator = "\n\t", prefix = "[", postfix = "]"),
+    )
+    val timeSpent: Long = measureTimeMillis {
+      when (filesType) {
+        // 1- create a temp folder for each destination folder
+        // 2- copy all the files to the temp folder. adb does not support symbolic links so
+        // this is necessary
+        // 3- push the temp folder to the device using one call to adb. this is much faster
+        // than pushing each file individually
+        "secondary_dex",
+        "native_library",
+        "resources" -> {
+          // create a temp folder for each destination folder
+          val tempFolders = mutableMapOf<Path, Path>()
+          val stagingDir = scratchDirFor(packageName)
+          var pushFailure: Throwable? = null
+          try {
+            installPaths.keys
+                .stream()
+                .map { it.parent }
+                .distinct()
+                .forEach { tempFolders[it] = Files.createTempDirectory("${it.fileName}_") }
+            installPaths.forEach { (destination, source) ->
+              val targetPath = tempFolders[destination.parent]?.resolve(destination.fileName)
+              stageForPush(source, checkNotNull(targetPath))
+            }
+            // push the temp folder to the device
+            mkDirP(stagingDir)
+            tempFolders.forEach { (destination, source) ->
+              try {
+                executeAdbCommand("push -z brotli $source $stagingDir")
+                // In staging, where the glob covers this shard's files and nothing else. The
+                // destination holds every shard's, so chmodding there costs the whole directory
+                // once per shard. The app will not start if its dex files are writable.
+                executeAdbShellCommand("chmod 644 $stagingDir/${source.fileName}/*")
+                executeAdbShellCommand("mv $stagingDir/${source.fileName}/* $destination")
+              } catch (e: AdbCommandFailedException) {
+                throw AndroidInstallException.adbCommandFailedException(
+                    "Failed to push $source to $destination.",
+                    e.message,
+                )
+              }
+            }
+          } catch (t: Throwable) {
+            pushFailure = t
+            throw t
+          } finally {
+            // `values`, not `keys`: the keys are on-device destinations.
+            tempFolders.values.forEach { it.toFile().deleteRecursively() }
+            // Only what this call pushed, since concurrent calls share the package's staging
+            // directory.
+            if (tempFolders.isNotEmpty()) {
+              val pushed = tempFolders.values.joinToString(" ") { "$stagingDir/${it.fileName}" }
+              try {
+                executeAdbShellCommand("rm -rf $pushed")
+              } catch (e: Exception) {
+                // Leaving a payload behind is a failure in its own right, but not one worth losing
+                // the push failure over: while unwinding, attach it instead of replacing it.
+                pushFailure?.addSuppressed(e) ?: throw e
+              }
+            }
+          }
+        }
+        else -> {
+          installPaths.forEach { (destination, source) ->
+            LOG.debug("\tPushing $source to $destination")
+            executeAdbCommandCatching(
+                "push $source $destination",
+                "Failed to push $source to $destination.",
+            )
+            // As for the payloads above: nothing the app reads is left writable. One named file
+            // rather than a glob, since these are pushed one at a time.
+            executeAdbShellCommandCatching(
+                "chmod 644 $destination",
+                "Failed to set permissions on $destination.",
+            )
+          }
+        }
+      }
+    }
+    LOG.info("$filesType: Transferred ${installPaths.size} files in ${timeSpent/1000.0} seconds")
+  }
+
+  @Throws(Exception::class)
+  override fun rmStaleFiles(packageName: String) {
+    val scratchDir = scratchDirFor(packageName)
+    executeAdbShellCommandCatching("rm -rf $scratchDir", "Failed to remove $scratchDir.")
+  }
+
+  /**
+   * Where payloads for [packageName] are pushed before being moved into place. Per package, so that
+   * reclaiming one app's leftovers cannot destroy a transfer another install has in flight.
+   */
+  private fun scratchDirFor(packageName: String): String {
+    // Interpolated into the adb shell commands that move payloads into place.
+    require(PACKAGE_NAME_PATTERN.matches(packageName)) { "Not a package name: $packageName" }
+    return "$SCRATCH_ROOT/$packageName"
+  }
+
+  @Throws(Exception::class)
+  override fun mkDirP(dirpath: String) {
+    executeAdbShellCommandCatching(
+        "umask 022 && mkdir -p $dirpath",
+        "Failed to create dir $dirpath.",
+    )
+  }
+
+  @Throws(Exception::class)
+  override fun getProperty(name: String): String {
+    val read = { executeAdbShellCommandCatching("getprop $name", "Failed to get property $name.") }
+    // Only `ro.` properties are fixed at boot and so safe to hold on to; anything else can change
+    // under us mid-install. Caching is worth it because a single exopackage install otherwise
+    // re-queries ro.product.cpu.abilist five times over adb.
+    return if (name.startsWith("ro.")) properties.computeIfAbsent(name) { read() } else read()
+  }
+
+  /**
+   * Hardlinks an artifact into the staging directory, copying only if it cannot be linked -- a
+   * different filesystem, typically, when the temp directory is on another volume.
+   *
+   * Buck materialises exopackage payloads as symlink farms and adb will not follow symlinks, so
+   * something has to resolve them; staging also renames each file to the hash-based name it takes
+   * on the device. Neither needs the bytes copied, and a payload is several GB.
+   *
+   * The link shares an inode with the artifact in buck-out, so nothing may modify a staged file.
+   * The `chmod` after the push deliberately runs on the device, not here.
+   */
+  private fun stageForPush(source: Path, target: Path) {
+    try {
+      Files.createLink(target, source.toRealPath())
+    } catch (e: IOException) {
+      Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING)
+    } catch (e: UnsupportedOperationException) {
+      Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING)
+    }
+  }
+
+  @Throws(Exception::class)
+  override fun getDeviceAbis(): List<String> {
+    val abiListProperty = getProperty("ro.product.cpu.abilist")
+    if (abiListProperty.isNotEmpty()) {
+      return abiListProperty.split(',')
+    } else {
+      return listOf(getProperty("ro.product.cpu.abi"), getProperty("ro.product.cpu.abi2"))
+          .filter { it.isEmpty() }
+          .takeIf { it.isNotEmpty() } ?: throw AndroidInstallException.deviceAbiUnknown()
+    }
+  }
+
+  @Throws(Exception::class)
+  override fun killProcess(processName: String) {
+    throw AndroidInstallException.operationNotSupported("killProcess")
+  }
+
+  override fun getSerialNumber(): String {
+    return serial
+  }
+
+  @Throws(Exception::class)
+  override fun getWindowManagerProperty(propertyName: String): String {
+    throw AndroidInstallException.operationNotSupported("getWindowManagerProperty")
+  }
+
+  override fun uninstallApkFromDevice(packageName: String, keepData: Boolean): Boolean {
+    try {
+      executeAdbShellCommand("rm -rf ${ExopackageInstaller.EXOPACKAGE_INSTALL_ROOT}/$packageName")
+      executeAdbShellCommand("pm uninstall ${if (keepData) "-k " else ""} $packageName")
+      return true
+    } catch (e: AdbCommandFailedException) {
+      LOG.warn("Failed to uninstall $packageName: ${e.message}")
+      return false
+    }
+  }
+
+  /**
+   * Sometimes installation fails and leaves the root directory in a weird state. Adding a cheap
+   * fix-root at the beginning to make sure all the folders have access permission.
+   */
+  override fun fixRootDir(rootDir: String) {
+    LOG.info("Fixing root dir $rootDir")
+    executeAdbShellCommandCatching(
+        "find $rootDir -type d -exec chmod a+x {} +",
+        "Failed to fix root dir $rootDir.",
+    )
+  }
+
+  override fun setDebugAppPackageName(packageName: String?): Boolean {
+    if (packageName != null) {
+      executeAdbShellCommand(adbUtils.getAmSetDebugAppCommand(packageName))
+    }
+    return true
+  }
+
+  override fun enableAppLinks(packageName: String?) {
+    if (packageName != null) {
+      executeAdbShellCommand("pm set-app-links --package $packageName 1 all")
+    }
+  }
+
+  override fun getDiskSpace(humanReadable: Boolean): List<String> {
+    // `-k` rather than a bare `df`: POSIX leaves the default block size to the implementation, so
+    // the unit has to be pinned for the numbers to mean anything.
+    val units = if (humanReadable) "-h" else "-k"
+    try {
+      val result: String = executeAdbShellCommand("df $units /data | awk '{print \$2, \$3, \$4}'")
+      val (size, used, available) = result.lines()[1].split(" ", limit = 3)
+      return listOf(size, used, available)
+    } catch (e: Exception) {
+      LOG.warn("Failed to get disk space: $e")
+      return listOf("_", "_", "_")
+    }
+  }
+
+  override fun isEmulator(): Boolean {
+    return isLocalTransport() || getProperty("ro.kernel.qemu") == "1"
+  }
+
+  override fun isOnline(): Boolean {
+    return getState() == "device"
+  }
+
+  private fun getState(): String {
+    return try {
+      adbUtils.executeAdbCommand("get-state", serialNumber)
+    } catch (e: AdbCommandFailedException) {
+      // When a device is offline, adb get-state fails with exit code 1.
+      // Return "offline" to indicate the device state instead of throwing an exception.
+      // This allows the installer to continue with other available devices.
+      LOG.warn("Failed to get state for device $serialNumber: ${e.message}")
+      "offline"
+    }
+  }
+
+  /**
+   * To be consistent with adb, we treat all local transports (as opposed to USB transports) as
+   * emulators instead of devices.
+   */
+  private fun isLocalTransport(): Boolean {
+    /** Pattern that matches Genymotion serial numbers; ex. 127.0.0.1:15562 */
+    return Pattern.compile("\\d+\\.\\d+\\.\\d+\\.\\d+:\\d+").matcher(serialNumber).find()
+  }
+
+  @Throws(Exception::class)
+  override fun installBuildUuidFile(
+      dataRoot: Path,
+      packageName: String,
+      buildUuid: String,
+  ): Boolean {
+    val destinationPath: String = dataRoot.resolve(packageName).toString()
+    try {
+      // One `adb shell`, not two, because `umask` is per-process. Split across two shells the
+      // second one never runs the umask, so the file its redirect creates takes adbd's default
+      // mode rather than 0644. The directory is unaffected either way — the FIRST shell is what
+      // creates it — and that asymmetry is what makes this easy to miss: on a host whose default
+      // umask is already 022 both land 0644 and the split looks harmless. The file is read back
+      // as build provenance, so it should not be writable by anything but the installer.
+      executeAdbShellCommand(
+          "umask 022 && mkdir -p $destinationPath && " +
+              "echo $buildUuid > $destinationPath/build_uuid.txt",
+      )
+    } catch (e: Exception) {
+      // we don't want to fail the install if we can't install the build_uuid.txt file
+      LOG.warn("Failed to install build_uuid.txt file on $serial: ${e.message}")
+    }
+    return true
+  }
+
+  override fun deviceStartIntent(intent: AndroidIntent?): String {
+    if (intent == null) {
+      return ""
+    }
+
+    try {
+      executeAdbShellCommand(AndroidIntent.getAmStartCommand(intent))
+      return ""
+    } catch (e: AdbCommandFailedException) {
+      throw AndroidInstallException.adbCommandFailedException("Failed to start intent.", e.message)
+    }
+  }
+
+  private fun executeAdbShellCommandCatching(command: String, message: String): String {
+    try {
+      return adbUtils.executeAdbShellCommand(command, serialNumber)
+    } catch (e: AdbCommandFailedException) {
+      throw AndroidInstallException.adbCommandFailedException(message, e.message)
+    }
+  }
+
+  private fun executeAdbCommandCatching(command: String, message: String): String {
+    try {
+      return adbUtils.executeAdbCommand(command, serialNumber)
+    } catch (e: AdbCommandFailedException) {
+      throw AndroidInstallException.adbCommandFailedException(message, e.message)
+    }
+  }
+
+  private fun executeAdbShellCommand(command: String, ignoreFailure: Boolean = false): String =
+      adbUtils.executeAdbShellCommand(command, serialNumber, ignoreFailure)
+
+  private fun executeAdbCommand(command: String, ignoreFailure: Boolean = false): String =
+      adbUtils.executeAdbCommand(command, serialNumber, ignoreFailure)
+
+  companion object {
+    private val LINE_ENDING: Pattern = Pattern.compile("\r?\n")
+    private val LOG: Logger = Logger.get(AndroidDeviceImpl::class.java.name)
+
+    // --fastdeploy is only supported on Android 10+ (API 29+)
+    // https://developer.android.com/tools/releases/platform-tools#2905_october_2019
+    private const val MIN_SDK_VERSION_FOR_FASTDEPLOY = 29
+
+    private const val INSTALL_FAILED_UPDATE_INCOMPATIBLE = "INSTALL_FAILED_UPDATE_INCOMPATIBLE"
+
+    // Matches the package name in adb's signature-mismatch message, which is phrased as either
+    // "Existing package <pkg> signatures do not match ..." or "Package <pkg> signatures do not
+    // match ..." depending on the Android version.
+    private val SIGNATURE_MISMATCH_PACKAGE_PATTERN =
+        Regex("package (\\S+) signatures do not match", RegexOption.IGNORE_CASE)
+
+    private val PACKAGE_NAME_PATTERN = Regex("[\\w.]+")
+
+    // Payloads are pushed here and then moved into place. Keeping them under one directory, rather
+    // than loose in /data/local/tmp, is what makes leftovers from an interrupted install
+    // identifiable, and so reclaimable.
+    private const val SCRATCH_ROOT = "/data/local/tmp/buck-exo-staging"
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDeviceInfo.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDeviceInfo.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDeviceInfo.kt
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage
+
+/** Information gathered from a device during buck install. */
+data class AndroidDeviceInfo(
+    val locale: String,
+    val abi: String,
+    val abiList: Set<String>,
+    val buildFingerprint: String,
+    val dotsPerInch: String,
+    val density: DensityClass,
+    val sdk: String,
+    val isEmulator: Boolean,
+    val transport: String,
+) {
+  /** The display density category of the device. */
+  enum class DensityClass(private val maxDotsPerInch: Int) {
+    LDPI(120),
+    MDPI(160),
+    HDPI(240),
+    XHDPI(320),
+    XXHDPI(480),
+    XXXHDPI(640),
+    OTHER_DPI(-1),
+    TVDPI(-1);
+
+    companion object {
+      @JvmStatic
+      fun forPhysicalDensity(dpiString: String): DensityClass {
+        try {
+          val dpi = dpiString.toInt()
+          if (dpi == TVDPI_DPI) {
+            return TVDPI
+          }
+          for (d in entries) {
+            if (dpi <= d.maxDotsPerInch) {
+              return d
+            }
+          }
+          return OTHER_DPI
+        } catch (e: NumberFormatException) {
+          return OTHER_DPI
+        }
+      }
+    }
+  }
+
+  companion object {
+    var TVDPI_DPI: Int = 213
+
+    /**
+     * Classifies how adb reaches a device, from its serial. Transfer throughput differs enough
+     * between these that install timings are not comparable across them.
+     */
+    @JvmStatic
+    fun transportOf(serialNumber: String): String =
+        when {
+          // `adb connect` target: a networked device, or one tunnelled to a remote host.
+          serialNumber.contains(':') -> "tcp"
+          serialNumber.startsWith("emulator-") -> "emulator"
+          else -> "usb"
+        }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDevicesHelper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDevicesHelper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidDevicesHelper.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.buck.android.IsolatedApkInfo;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
+import java.io.Closeable;
+import java.util.Set;
+
+/**
+ * AndroidDevicesHelper provides a way to interact with multiple devices as AndroidDevices (rather
+ * than IDevices).
+ *
+ * <p>All of ExopackageInstaller's interaction with devices and adb goes through this class and
+ * AndroidDevice making it easy to provide different implementations in tests.
+ */
+@VisibleForTesting
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface AndroidDevicesHelper extends Closeable {
+  /**
+   * This is basically the same as AdbHelper.AdbCallable except that it takes an AndroidDevice
+   * instead of an IDevice.
+   */
+  interface AdbDeviceCallable {
+    boolean apply(AndroidDevice device) throws Exception;
+  }
+
+  /** A simple wrapper around adbCall that will throw if adbCall returns false. */
+  default void adbCallOrThrow(String description, AdbDeviceCallable func, boolean quiet)
+      throws InterruptedException {
+    adbCall(description, func, quiet);
+  }
+
+  void adbCall(String description, AdbDeviceCallable func, boolean quiet)
+      throws InterruptedException;
+
+  ImmutableList<AndroidDevice> getDevices(boolean quiet);
+
+  /** Uninstall apk from all matching devices. */
+  void uninstallApp(String packageName, boolean shouldKeepUserData) throws InterruptedException;
+
+  Set<AndroidDeviceInfo> getAndroidDeviceInfo(IsolatedApkInfo isolatedApkInfo)
+      throws InterruptedException;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidIntent.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidIntent.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/AndroidIntent.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.infer.annotation.Nullsafe;
+import org.jetbrains.annotations.Nullable;
+
+/** Data class for parameters to a `adb shell am start` command. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AndroidIntent {
+
+  public static final String ACTION_MAIN = "android.intent.action.MAIN";
+  public static final String ACTION_VIEW = "android.intent.action.VIEW";
+  public static final String CATEGORY_LAUNCHER = "android.intent.category.LAUNCHER";
+
+  public final String packageName;
+
+  // Each of these maps to an optional `am start` flag, omitted from the command when null.
+  @Nullable public final String componentName;
+  @Nullable public final String action;
+  @Nullable public final String category;
+  @Nullable public final String dataUri;
+  @Nullable public final String flags;
+
+  public final boolean waitForDebugger;
+  public final boolean skipSetDebugApp;
+
+  public AndroidIntent(
+      String packageName,
+      @Nullable String componentName,
+      @Nullable String action,
+      @Nullable String category,
+      @Nullable String dataUri,
+      @Nullable String flags,
+      boolean waitForDebugger,
+      boolean skipSetDebugApp) {
+    this.packageName = packageName;
+    this.componentName = componentName;
+    this.action = action;
+    this.category = category;
+    this.dataUri = dataUri;
+    this.flags = flags;
+    this.waitForDebugger = waitForDebugger;
+    this.skipSetDebugApp = skipSetDebugApp;
+  }
+
+  /**
+   * @return the `am start` command for this intent as a String
+   */
+  public static String getAmStartCommand(AndroidIntent intent) {
+    final StringBuilder builder = new StringBuilder("am start ");
+    if (intent.flags != null) {
+      builder.append("-f ").append(intent.flags).append(" ");
+    }
+    if (intent.action != null) {
+      builder.append("-a ").append(intent.action).append(" ");
+    }
+    if (intent.category != null) {
+      builder.append("-c ").append(intent.category).append(" ");
+    }
+    if (intent.dataUri != null) {
+      builder.append("-d ").append(intent.dataUri).append(" ");
+    }
+    if (intent.componentName != null) {
+      builder.append("-n ").append(intent.componentName).append(" ");
+    }
+    if (intent.waitForDebugger) {
+      builder.append("-D ");
+    }
+    return builder.toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/DexExoHelper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/DexExoHelper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/DexExoHelper.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMultimap;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Map;
+
+/** Installs secondary dexes for exo. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class DexExoHelper implements ExoHelper {
+  @VisibleForTesting public static final Path SECONDARY_DEX_DIR = Paths.get("secondary-dex");
+
+  private final AbsPath rootPath;
+  private final IsolatedExopackageInfo.IsolatedDexInfo dexInfo;
+
+  private static enum DexCompressionType {
+    RAW,
+    JAR,
+    UNKNOWN
+  };
+
+  DexExoHelper(AbsPath rootPath, IsolatedExopackageInfo.IsolatedDexInfo dexInfo) {
+    this.rootPath = rootPath;
+    this.dexInfo = dexInfo;
+  }
+
+  @Override
+  public String getType() {
+    return "secondary_dex";
+  }
+
+  @Override
+  public ImmutableMap<Path, Path> getFilesToInstall() throws IOException {
+    ImmutableMap<String, Path> dexFiles = getRequiredDexFiles();
+    if (dexFiles.isEmpty()) {
+      return ImmutableMap.of();
+    }
+    Path anyDexPath = dexFiles.entrySet().iterator().next().getValue();
+    switch (getDexCompressionType(anyDexPath.toString())) {
+      case JAR:
+        {
+          return ExopackageUtil.applyFilenameFormat(
+              dexFiles, SECONDARY_DEX_DIR, "secondary-%s.dex.jar");
+        }
+      case RAW:
+        {
+          return ExopackageUtil.applyFilenameFormat(
+              dexFiles, SECONDARY_DEX_DIR, "secondary-%s.dex");
+        }
+      case UNKNOWN:
+      default:
+        {
+          throw new IllegalStateException("Unknown dex compression type");
+        }
+    }
+  }
+
+  @Override
+  public ImmutableMap<Path, String> getMetadataToInstall() throws IOException {
+    return ImmutableMap.of(
+        SECONDARY_DEX_DIR.resolve("metadata.txt"), getSecondaryDexMetadataContents());
+  }
+
+  private DexCompressionType getDexCompressionType(String metadataPattern) {
+    return metadataPattern.contains("dex.jar") ? DexCompressionType.JAR : DexCompressionType.RAW;
+  }
+
+  private String getSecondaryDexMetadataContents() throws IOException {
+    // This is a bit gross.  It was a late addition.  Ideally, we could eliminate this, but
+    // it wouldn't be terrible if we don't.  We store the dexed jars on the device
+    // with the full SHA-1 hashes in their names.  This is the format that the loader uses
+    // internally, so ideally we would just load them in place.  However, the code currently
+    // expects to be able to copy the jars from a directory that matches the name in the
+    // metadata file, like "secondary-1.dex.jar".  We don't want to give up putting the
+    // hashes in the file names (because we use that to skip re-uploads), so just hack
+    // the metadata file to have hash-like names.
+    String originalMetadata =
+        com.google.common.io.Files.toString(dexInfo.getMetadata().toFile(), StandardCharsets.UTF_8);
+    switch (getDexCompressionType(originalMetadata)) {
+      case JAR:
+        {
+          return com.google.common.io.Files.toString(
+                  dexInfo.getMetadata().toFile(), StandardCharsets.UTF_8)
+              .replaceAll(
+                  "secondary-([\\d_]+)\\.dex\\.jar (\\p{XDigit}{40}) ", "secondary-$2.dex.jar $2 ");
+        }
+      case RAW:
+        {
+          return com.google.common.io.Files.toString(
+                  dexInfo.getMetadata().toFile(), StandardCharsets.UTF_8)
+              .replaceAll("secondary-([\\d_]+)\\.dex\\ (\\p{XDigit}{40}) ", "secondary-$2.dex $2 ");
+        }
+      case UNKNOWN:
+      default:
+        {
+          throw new IllegalStateException("Unknown dex compression type");
+        }
+    }
+  }
+
+  private ImmutableMap<String, Path> getRequiredDexFiles() throws IOException {
+    ImmutableMultimap<String, Path> multimap =
+        ExopackageInstaller.parseExopackageInfoMetadata(
+            dexInfo.getMetadata().getPath(), dexInfo.getDirectory().getPath(), rootPath);
+    // Convert multimap to a map, because every key should have only one value.
+    ImmutableMap.Builder<String, Path> builder = ImmutableMap.builder();
+    for (Map.Entry<String, Path> entry : multimap.entries()) {
+      builder.put(entry);
+    }
+    return builder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExoHelper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExoHelper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExoHelper.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.nio.file.Path;
+
+/** An exo installer helper. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+interface ExoHelper {
+  /** Returns the files to install. */
+  ImmutableMap<Path, Path> getFilesToInstall() throws IOException;
+
+  /** Returns metadata to install. */
+  ImmutableMap<Path, String> getMetadataToInstall() throws IOException;
+
+  /** Returns the type of this installer. */
+  String getType();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageInstaller.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageInstaller.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageInstaller.java
@@ -0,0 +1,647 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.buck.android.AdbHelper;
+import com.facebook.buck.android.AndroidInstallPrinter;
+import com.facebook.buck.android.IsolatedApkInfo;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.installer.android.AndroidInstallException;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.util.NamedTemporaryFile;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableListMultimap;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedMap;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.collect.Ordering;
+import com.google.common.io.Closer;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.OptionalLong;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.function.Function;
+
+/**
+ * ExopackageInstaller manages the installation of apps with the "exopackage" flag set to true.
+ *
+ * <p>Two ways in, one way down. {@link #doInstall} is the whole install; {@link #streamPayloads}
+ * sends a subset of the payloads while the build is still running. Both reach the device through
+ * {@code pushMissingFiles}, the only thing here that moves payload bytes.
+ *
+ * <p>Three names for sets of files:
+ *
+ * <ul>
+ *   <li>{@code filesOnDevice} -- what listing the data root found already there.
+ *   <li>{@code filesToDelete} -- on the device from previous installs and not wanted anymore.
+ *   <li>{@code filesToPush} -- wanted by one payload and not on the device.
+ * </ul>
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ExopackageInstaller {
+
+  private static final Logger LOG = Logger.get(ExopackageInstaller.class);
+
+  // When there are a small number of files to delete, it's faster (we issue
+  // fewer rm commands over adb) if we group them by the data root, so
+  //   cd /data/local/tmp/exopackage/foo && rm resources/bar.txt native-libs/baz.txt
+  // But when there are more files, because of the way RealAndroidDevice splits up
+  // commandlines to avoid hitting limits, it's more efficient to group by the
+  // subdirectories, so
+  //   cd /data/local/tmp/exopackage/foo/resources && rm bar.txt bap.txt boz.txt
+  //   cd /data/local/tmp/exopackage/foo/native-libs && rm baz.txt zog.txt
+  // We pick a heuristic number of files (10) at which to change behavior for this based
+  // on these assumptions:
+  //    approx available commandline length = 800
+  //    max length of a path from the dataRoot for a well known app = 77
+  private static final int RM_GROUPING_THRESHOLD = 10;
+
+  private static final long BYTES_PER_BLOCK = 1024L;
+
+  private static final int MAX_CONCURRENT_PUSHES = 8;
+
+  private static final long TARGET_SHARD_BYTES = 32L * 1024L * 1024L;
+
+  private static final ExecutorService PUSH_EXECUTOR =
+      Executors.newFixedThreadPool(
+          MAX_CONCURRENT_PUSHES,
+          new ThreadFactoryBuilder().setNameFormat("exopackage-push-%d").setDaemon(true).build());
+
+  public static final Path EXOPACKAGE_INSTALL_ROOT = Paths.get("/data/local/tmp/exopackage/");
+
+  private final IsolatedExopackageInfo exoInfo;
+  private final AndroidInstallPrinter androidPrinter;
+  private final AbsPath rootPath;
+  private final AndroidDevice device;
+  private final String packageName;
+  private final Optional<String> buck2BuildUuid;
+  private final Path dataRoot;
+  private final InstallTimings timings;
+
+  public ExopackageInstaller(
+      IsolatedExopackageInfo exoInfo,
+      AndroidInstallPrinter androidPrinter,
+      AbsPath rootPath,
+      String packageName,
+      AndroidDevice device,
+      Optional<String> buck2BuildUuid) {
+    this(
+        exoInfo,
+        androidPrinter,
+        rootPath,
+        packageName,
+        device,
+        buck2BuildUuid,
+        InstallTimings.NONE);
+  }
+
+  public ExopackageInstaller(
+      IsolatedExopackageInfo exoInfo,
+      AndroidInstallPrinter androidPrinter,
+      AbsPath rootPath,
+      String packageName,
+      AndroidDevice device,
+      Optional<String> buck2BuildUuid,
+      InstallTimings timings) {
+    this.timings = timings;
+    this.exoInfo = exoInfo;
+    this.androidPrinter = androidPrinter;
+    this.rootPath = rootPath;
+    this.device = device;
+    this.packageName = packageName;
+    this.dataRoot = EXOPACKAGE_INSTALL_ROOT.resolve(packageName);
+    this.buck2BuildUuid = buck2BuildUuid;
+
+    Preconditions.checkArgument(AdbHelper.PACKAGE_NAME_PATTERN.matcher(packageName).matches());
+  }
+
+  /** Installs an apk, restarting the running app if necessary. */
+  public void doInstall(IsolatedApkInfo isolatedApkInfo, SetDebugAppMode setDebugAppMode)
+      throws Exception {
+    if (setDebugAppMode == SetDebugAppMode.SET) {
+      device.setDebugAppPackageName(packageName);
+    }
+    if (exopackageEnabled()) {
+      long setupStart = System.currentTimeMillis();
+      prepareDataRoot();
+      ImmutableSortedSet<Path> filesOnDevice = device.listDirRecursive(dataRoot);
+      timings.recordDeviceSetup(setupStart, System.currentTimeMillis());
+      ImmutableList<ResolvedExoPayload> payloads = resolveExoPayloads();
+
+      // Reclaim space before pushing so a device that is already full can free room for the
+      // payload. Best effort on purpose: neither step is needed for the install to be correct.
+      // Scratch is read by nothing, and filesToDelete is disjoint from filesToPush, so the new app
+      // gets every file it needs either way -- a failure here leaves unreferenced files on the
+      // device and costs disk, not correctness. That disjointness is also why the push below still
+      // reads the pre-delete listing: nothing deleted is a file any payload asks about. Whether
+      // there is still room to proceed is the preflight's answer to give, from the space the
+      // device actually has.
+      try {
+        device.rmStaleFiles(packageName);
+        deleteFiles(filesToDelete(filesOnDevice, payloads));
+      } catch (Exception e) {
+        LOG.warn(e, "Could not reclaim exopackage space for %s; continuing", packageName);
+      }
+      pushMissingFiles(filesOnDevice, payloads);
+
+      // Metadata is what the app reads to find these files, so it must not land before them.
+      installMetadata(
+          payloads.stream()
+              .flatMap(payload -> payload.metadataToInstall.entrySet().stream())
+              .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)));
+    }
+    if (buck2BuildUuid.isPresent()) {
+      device.installBuildUuidFile(
+          AdbHelper.BUILD_METADATA_INSTALL_ROOT, packageName, buck2BuildUuid.get());
+    }
+    installAndRestartApk(isolatedApkInfo);
+  }
+
+  public void installAndRestartApk(IsolatedApkInfo isolatedApkInfo) throws Exception {
+    installApkIfNecessary(isolatedApkInfo);
+    killApp();
+  }
+
+  private void installApkIfNecessary(IsolatedApkInfo isolatedApkInfo) throws Exception {
+    File apk = isolatedApkInfo.getApkPath().toFile();
+
+    if (shouldAppBeInstalled(isolatedApkInfo)) {
+      long installStart = System.currentTimeMillis();
+      boolean success =
+          device.installApkOnDevice(
+              apk,
+              /* installViaSd= */ false,
+              /* quiet */ false,
+              /* verifyTempWritable= */ true,
+              /* stagedInstallMode= */ false,
+              /* userId= */ null,
+              /* allowFastDeploy= */ false,
+              packageName);
+      timings.recordApkInstall(installStart, System.currentTimeMillis());
+      if (!success) {
+        throw AndroidInstallException.Companion.adbCommandFailedException(
+            "Installing Apk failed.", null);
+      }
+    }
+  }
+
+  private void killApp() throws Exception {
+    device.stopPackage(packageName);
+  }
+
+  /**
+   * The exopackage payloads for this install, with their contents resolved exactly once.
+   *
+   * <p>Resolving a payload parses its metadata file and, for native libs, queries the device for
+   * its ABIs. The delete and push phases both need the same answers, so they share one resolution
+   * rather than recomputing it.
+   */
+  private ImmutableList<ResolvedExoPayload> resolveExoPayloads() throws Exception {
+    ImmutableList.Builder<ResolvedExoPayload> payloads = ImmutableList.builder();
+
+    Optional<IsolatedExopackageInfo.IsolatedDexInfo> dexInfo = exoInfo.getDexInfo();
+    if (dexInfo.isPresent()) {
+      payloads.add(new ResolvedExoPayload(new DexExoHelper(rootPath, dexInfo.get())));
+    }
+
+    Optional<IsolatedExopackageInfo.IsolatedNativeLibsInfo> nativeLibsInfo =
+        exoInfo.getNativeLibsInfo();
+    if (nativeLibsInfo.isPresent()) {
+      payloads.add(
+          new ResolvedExoPayload(
+              new NativeExoHelper(this::getDeviceAbis, rootPath, nativeLibsInfo.get())));
+    }
+
+    Optional<IsolatedExopackageInfo.IsolatedResourcesInfo> resourcesInfo =
+        exoInfo.getResourcesInfo();
+    if (resourcesInfo.isPresent()) {
+      payloads.add(new ResolvedExoPayload(new ResourcesExoHelper(rootPath, resourcesInfo.get())));
+    }
+
+    return payloads.build();
+  }
+
+  private List<String> getDeviceAbis() {
+    try {
+      return device.getDeviceAbis();
+    } catch (Exception e) {
+      throw AndroidInstallException.Companion.adbCommandFailedException(
+          "Unable to communicate with device.", e.getMessage());
+    }
+  }
+
+  /** Every path this install wants on the device; anything else under the data root is stale. */
+  /**
+   * Pushes whatever of {@code payloads} the device does not already have.
+   *
+   * <p>Every payload byte reaches a device through here, whether it goes while the build is still
+   * running or as part of the install. Free space is checked first, so a device without room says
+   * so rather than filling up partway through.
+   */
+  private void pushMissingFiles(
+      ImmutableSortedSet<Path> filesOnDevice, ImmutableList<ResolvedExoPayload> payloads)
+      throws Exception {
+    ImmutableMap.Builder<ResolvedExoPayload, ImmutableSortedMap<Path, Path>> transfers =
+        ImmutableMap.builder();
+    for (ResolvedExoPayload payload : payloads) {
+      transfers.put(payload, filesToPush(filesOnDevice, payload.filesToInstall));
+    }
+    ImmutableMap<ResolvedExoPayload, ImmutableSortedMap<Path, Path>> filesToTransfer =
+        transfers.build();
+
+    checkEnoughFreeSpace(filesToTransfer);
+
+    ImmutableList.Builder<PushShard> shards = ImmutableList.builder();
+    filesToTransfer.forEach(
+        (payload, files) ->
+            shards.addAll(
+                splitIntoShards(payload.type, files, rootPath, dataRoot, TARGET_SHARD_BYTES)));
+    pushShards(shards.build());
+  }
+
+  /**
+   * Pushes payload content ahead of the install proper.
+   *
+   * <p>Writes no metadata, collects no stale files and does not touch the apk: all three need the
+   * complete artifact set, and until metadata names them the pushed files are inert. The install
+   * lists the directory afterwards, so anything landed here is seen as already present and skipped
+   * -- which is what makes this safe to run more than once, and safe to fail.
+   */
+  public void streamPayloads() throws Exception {
+    if (!exopackageEnabled()) {
+      return;
+    }
+    // Not recorded as device setup: this happens while the build is still running, so charging it
+    // to the install would report time the install never spent.
+    prepareDataRoot();
+    pushMissingFiles(device.listDirRecursive(dataRoot), resolveExoPayloads());
+  }
+
+  /** Makes the data root usable. */
+  private void prepareDataRoot() throws Exception {
+    device.mkDirP(dataRoot.toString());
+    device.fixRootDir(dataRoot.toString());
+  }
+
+  @VisibleForTesting
+  static ImmutableSortedMap<Path, Path> filesToPush(
+      ImmutableSortedSet<Path> filesOnDevice, ImmutableMap<Path, Path> filesToInstall) {
+    return filesToInstall.entrySet().stream()
+        .filter(entry -> !filesOnDevice.contains(entry.getKey()))
+        .collect(
+            ImmutableSortedMap.toImmutableSortedMap(
+                Ordering.natural(), Map.Entry::getKey, Map.Entry::getValue));
+  }
+
+  /**
+   * Splits a payload into roughly equal chunks by size.
+   *
+   * <p>A single `adb push` is limited by per-stream round trips rather than by bandwidth or by the
+   * host, so concurrent pushes scale close to linearly. Sharding by bytes rather than by payload
+   * matters because native libs alone are over half the total, and pushing one payload per stream
+   * leaves that stream setting the wall time on its own.
+   */
+  @VisibleForTesting
+  static ImmutableList<PushShard> splitIntoShards(
+      String filesType,
+      ImmutableSortedMap<Path, Path> filesToInstall,
+      AbsPath rootPath,
+      Path dataRoot,
+      long targetShardBytes) {
+    ImmutableList.Builder<PushShard> shards = ImmutableList.builder();
+    ImmutableMap.Builder<Path, Path> current = ImmutableMap.builder();
+    long currentBytes = 0L;
+    boolean currentIsEmpty = true;
+
+    for (Map.Entry<Path, Path> file : filesToInstall.entrySet()) {
+      Path localPath = rootPath.resolve(file.getValue()).getPath();
+      current.put(dataRoot.resolve(file.getKey()), localPath);
+      currentBytes += localPath.toFile().length();
+      currentIsEmpty = false;
+      // A shard can never be smaller than a single file, so a payload of one huge file stays whole.
+      if (currentBytes >= targetShardBytes) {
+        shards.add(new PushShard(filesType, current.build()));
+        current = ImmutableMap.builder();
+        currentBytes = 0L;
+        currentIsEmpty = true;
+      }
+    }
+    if (!currentIsEmpty) {
+      shards.add(new PushShard(filesType, current.build()));
+    }
+    return shards.build();
+  }
+
+  /** Pushes every shard, up to {@link #MAX_CONCURRENT_PUSHES} at a time. */
+  private void pushShards(ImmutableList<PushShard> shards) throws Exception {
+    if (shards.isEmpty()) {
+      return;
+    }
+    // Create every destination directory up front: shards from one payload share a directory, and
+    // concurrent mkdir -p of the same path is pointless work at best.
+    ImmutableSet<Path> destinationDirs =
+        shards.stream()
+            .flatMap(shard -> shard.installPaths.keySet().stream())
+            .map(Path::getParent)
+            .filter(Objects::nonNull)
+            .collect(ImmutableSet.toImmutableSet());
+    for (Path destinationDir : destinationDirs) {
+      device.mkDirP(destinationDir.toString());
+    }
+
+    List<Future<Void>> pushes = new ArrayList<>(shards.size());
+    for (PushShard shard : shards) {
+      pushes.add(
+          PUSH_EXECUTOR.submit(
+              () -> {
+                pushShard(shard);
+                return null;
+              }));
+    }
+    awaitAll(pushes);
+  }
+
+  private void pushShard(PushShard shard) throws Exception {
+    long start = System.currentTimeMillis();
+    device.installFiles(shard.filesType, shard.installPaths, packageName);
+    // Each shard records its own window; the group's transfer time is their union.
+    timings.recordPush(shard.filesType, start, System.currentTimeMillis());
+  }
+
+  /**
+   * Waits for every push, reporting the first failure with any others attached.
+   *
+   * <p>Deliberately does not cancel the rest once one fails. A thread blocked reading an {@code
+   * adb} subprocess does not observe an interrupt, so cancelling would not stop the transfer -- it
+   * would only stop us waiting for it, leaving shards writing to the device after the install has
+   * been called failed, and skipping the scratch each one removes on its way out. The cost is that
+   * a failing install takes as long as its slowest shard.
+   *
+   * <p>Interruption is the exception: it means the process is going away, so it stops waiting and
+   * leaves whatever is in flight to die with the JVM.
+   */
+  private static void awaitAll(List<Future<Void>> pushes) throws Exception {
+    Exception failure = null;
+    for (Future<Void> push : pushes) {
+      try {
+        push.get();
+      } catch (ExecutionException e) {
+        Exception cause = e.getCause() instanceof Exception ? (Exception) e.getCause() : e;
+        if (failure == null) {
+          failure = cause;
+        } else {
+          // Every shard that failed, not just the first: they fail independently, and which one
+          // arrives first says nothing about which one explains the install.
+          failure.addSuppressed(cause);
+        }
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+        throw e;
+      }
+    }
+    if (failure != null) {
+      throw failure;
+    }
+  }
+
+  /** One concurrently pushable chunk of a payload. */
+  @VisibleForTesting
+  static final class PushShard {
+    final String filesType;
+    final ImmutableMap<Path, Path> installPaths;
+
+    PushShard(String filesType, ImmutableMap<Path, Path> installPaths) {
+      this.filesType = filesType;
+      this.installPaths = installPaths;
+    }
+  }
+
+  /**
+   * Fails the install if the payload cannot fit, rather than letting the push die partway through
+   * with a bare ENOSPC.
+   */
+  private void checkEnoughFreeSpace(
+      ImmutableMap<ResolvedExoPayload, ImmutableSortedMap<Path, Path>> filesToTransfer) {
+    OptionalLong availableBytes = availableBytesOnDevice();
+    if (availableBytes.isEmpty()) {
+      return;
+    }
+    long requiredBytes = 0L;
+    for (ImmutableSortedMap<Path, Path> files : filesToTransfer.values()) {
+      for (Path source : files.values()) {
+        File file = rootPath.resolve(source).toFile();
+        if (!file.isFile()) {
+          // Zero is what length() would answer, which would quietly shrink the estimate and let
+          // the check pass. The install cannot succeed without the file either way, so say which
+          // one is missing while there is still somewhere useful to say it.
+          throw AndroidInstallException.Companion.artifactMissing(file.toString());
+        }
+        requiredBytes += file.length();
+      }
+    }
+    if (requiredBytes > availableBytes.getAsLong()) {
+      throw AndroidInstallException.Companion.insufficientStorage(
+          requiredBytes, availableBytes.getAsLong());
+    }
+  }
+
+  /**
+   * Free space under the data partition, or empty if the device did not give a number for it.
+   *
+   * <p>Unsuffixed, {@link AndroidDevice#getDiskSpace} answers with three entries -- size, used,
+   * available -- each a count of 1K blocks, e.g. {@code ["32911312", "14799512", "17964344"]}. A
+   * device it cannot read reports {@code "_"} in their place.
+   */
+  private OptionalLong availableBytesOnDevice() {
+    List<String> diskSpace = device.getDiskSpace(/* humanReadable= */ false);
+    if (diskSpace.size() < 3) {
+      return OptionalLong.empty();
+    }
+    String availableBlocks = diskSpace.get(2).trim();
+    try {
+      return OptionalLong.of(Long.parseLong(availableBlocks) * BYTES_PER_BLOCK);
+    } catch (NumberFormatException e) {
+      // No number means nothing to check against, so the preflight is skipped rather than guessed
+      // at, and the install goes on to fail at the push if the space really is not there.
+      LOG.info("Could not read available device space from '%s'", availableBlocks);
+      return OptionalLong.empty();
+    }
+  }
+
+  /** One exopackage payload class, with its contents resolved exactly once. */
+  static final class ResolvedExoPayload {
+    private final String type;
+    private final ImmutableMap<Path, Path> filesToInstall;
+    private final ImmutableMap<Path, String> metadataToInstall;
+
+    ResolvedExoPayload(ExoHelper helper) throws IOException {
+      this.type = helper.getType();
+      this.filesToInstall = helper.getFilesToInstall();
+      this.metadataToInstall = helper.getMetadataToInstall();
+    }
+  }
+
+  /**
+   * @return true if the given apk info contains any items which need to be installed via exopackage
+   */
+  private boolean exopackageEnabled() {
+    return isExopackage(exoInfo);
+  }
+
+  /** True when {@code exoInfo} carries any payload to be pushed alongside the apk. */
+  public static boolean isExopackage(IsolatedExopackageInfo exoInfo) {
+    return exoInfo.getDexInfo().isPresent()
+        || exoInfo.getNativeLibsInfo().isPresent()
+        || exoInfo.getResourcesInfo().isPresent();
+  }
+
+  private Optional<PackageInfo> getPackageInfo(String packageName) throws Exception {
+    return device.getPackageInfo(packageName);
+  }
+
+  private boolean shouldAppBeInstalled(IsolatedApkInfo apkInfo) throws Exception {
+    Optional<PackageInfo> appPackageInfo = getPackageInfo(packageName);
+    if (appPackageInfo.isEmpty()) {
+      androidPrinter.printMessage("App not installed.  Installing now.");
+      return true;
+    }
+
+    LOG.debug("App path: %s", appPackageInfo.get().apkPath);
+    String installedAppManifestDigest = getInstalledAppManifestDigest(appPackageInfo.get().apkPath);
+    String localAppManifestDigest =
+        ExopackageUtil.getJarManifestDigest(apkInfo.getApkPath().toString());
+    LOG.info("Local APK manifest digest: %s", localAppManifestDigest);
+    LOG.info("Installed APK manifest digest: %s", installedAppManifestDigest);
+
+    if (!installedAppManifestDigest.equals(localAppManifestDigest)) {
+      LOG.info("APK manifest digests do not match.  Must re-install.");
+      return true;
+    }
+
+    LOG.info("APK manifest digests match.  No need to install.");
+    return false;
+  }
+
+  private String getInstalledAppManifestDigest(String packagePath) throws Exception {
+    String output = device.getApkManifestDigest(packagePath);
+
+    String result = output.trim();
+    if (result.contains("\n") || result.contains("\r")) {
+      throw new IllegalStateException("Unexpected APK manifest digest:\n" + output);
+    }
+
+    return result;
+  }
+
+  /** What the device holds that no payload wants. The lock file belongs to no payload and stays. */
+  @VisibleForTesting
+  static ImmutableSortedSet<Path> filesToDelete(
+      ImmutableSortedSet<Path> filesOnDevice, ImmutableList<ResolvedExoPayload> payloads) {
+    ImmutableSet.Builder<Path> wanted = ImmutableSet.builder();
+    for (ResolvedExoPayload payload : payloads) {
+      wanted.addAll(payload.filesToInstall.keySet());
+      wanted.addAll(payload.metadataToInstall.keySet());
+    }
+    ImmutableSet<Path> wantedFiles = wanted.build();
+    return filesOnDevice.stream()
+        .filter(p -> !p.getFileName().toString().equals("lock") && !wantedFiles.contains(p))
+        .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));
+  }
+
+  private void deleteFiles(ImmutableSortedSet<Path> toDelete) {
+    Function<Path, Path> toRootDirFn =
+        toDelete.size() <= RM_GROUPING_THRESHOLD
+            ? path -> dataRoot
+            : path -> dataRoot.resolve(path).getParent();
+    Function<Path, String> toFileFn =
+        toDelete.size() <= RM_GROUPING_THRESHOLD
+            ? Path::toString
+            : path -> path.getFileName().toString();
+
+    try {
+      toDelete.stream()
+          .collect(ImmutableListMultimap.toImmutableListMultimap(toRootDirFn, toFileFn))
+          .asMap()
+          .forEach((dir, files) -> device.rmFiles(dir.toString(), files));
+    } catch (Exception e) {
+      // Every failure, not just a tagged one: `rmFiles` also surfaces the IO of writing and
+      // pushing its manifest, and those would otherwise escape without the tag below.
+      throw AndroidInstallException.Companion.exopackageGarbageCollectionFailed(e.getMessage());
+    }
+  }
+
+  private void installMetadata(ImmutableMap<Path, String> metadataToInstall) throws Exception {
+    try (Closer closer = Closer.create()) {
+      ImmutableMap.Builder<Path, Path> filesToInstall = ImmutableMap.builder();
+      for (Map.Entry<Path, String> entry : metadataToInstall.entrySet()) {
+        NamedTemporaryFile temp =
+            Objects.requireNonNull(closer.register(new NamedTemporaryFile("metadata", "tmp")));
+        com.google.common.io.Files.write(
+            entry.getValue().getBytes(StandardCharsets.UTF_8), temp.get().toFile());
+        filesToInstall.put(
+            dataRoot.resolve(entry.getKey()), rootPath.resolve(temp.get()).getPath());
+      }
+      // Pushed as one shard, through the same path as every payload. It stays inside the closer:
+      // the temporary files it names are deleted when that closes.
+      pushShards(ImmutableList.of(new PushShard("metadata", filesToInstall.build())));
+    }
+  }
+
+  /**
+   * Parses a text file which is supposed to be in the following format: "file_path_without_spaces
+   * file_hash ...." i.e. it parses the first two columns of each line and ignores the rest of it.
+   *
+   * @return A multi map from the file hash to its path, which equals the raw path resolved against
+   *     {@code resolvePathAgainst}.
+   */
+  @VisibleForTesting
+  public static ImmutableMultimap<String, Path> parseExopackageInfoMetadata(
+      Path metadataTxt, Path resolvePathAgainst, AbsPath rootPath) throws IOException {
+    ImmutableMultimap.Builder<String, Path> builder = ImmutableMultimap.builder();
+    for (String line : ProjectFilesystemUtils.readLines(rootPath, metadataTxt)) {
+      // ignore lines that start with '.'
+      if (line.startsWith(".")) {
+        continue;
+      }
+      List<String> parts = Splitter.on(' ').splitToList(line);
+      if (parts.size() < 2) {
+        throw new RuntimeException("Illegal line in metadata file: " + line);
+      }
+      builder.put(parts.get(1), resolvePathAgainst.resolve(parts.get(0)));
+    }
+    return builder.build();
+  }
+
+  public static ImmutableMultimap<String, Path> parseExopackageInfoMetadata(
+      AbsPath metadataTxt, AbsPath resolvePathAgainst, AbsPath rootPath) throws IOException {
+    return parseExopackageInfoMetadata(
+        metadataTxt.getPath(), resolvePathAgainst.getPath(), rootPath);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageMode.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageMode.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageMode.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.util.EnumSet;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public enum ExopackageMode {
+  SECONDARY_DEX(1),
+  NATIVE_LIBRARY(2),
+  RESOURCES(4),
+  MODULES(8),
+  ARCH64(16),
+  ;
+
+  private final int code;
+
+  ExopackageMode(int code) {
+    this.code = code;
+  }
+
+  public static boolean enabledForSecondaryDexes(EnumSet<ExopackageMode> modes) {
+    return modes.contains(SECONDARY_DEX);
+  }
+
+  public static boolean enabledForNativeLibraries(EnumSet<ExopackageMode> modes) {
+    return modes.contains(NATIVE_LIBRARY);
+  }
+
+  public static boolean enabledForResources(EnumSet<ExopackageMode> modes) {
+    return modes.contains(RESOURCES);
+  }
+
+  public static boolean enabledForModules(EnumSet<ExopackageMode> modes) {
+    return modes.contains(MODULES);
+  }
+
+  public static boolean enabledForArch64(EnumSet<ExopackageMode> modes) {
+    return modes.contains(ARCH64);
+  }
+
+  public static int toBitmask(EnumSet<ExopackageMode> modes) {
+    int bitmask = 0;
+    for (ExopackageMode mode : modes) {
+      bitmask |= mode.code;
+    }
+    return bitmask;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageUtil.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageUtil.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ExopackageUtil.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.Multimap;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+import java.util.regex.Pattern;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ExopackageUtil {
+  public static ImmutableMap<Path, Path> applyFilenameFormat(
+      Map<String, Path> filesToHashes, Path deviceDir, String filenameFormat) {
+    ImmutableMap.Builder<Path, Path> filesBuilder = ImmutableMap.builder();
+    for (Map.Entry<String, Path> entry : filesToHashes.entrySet()) {
+      filesBuilder.put(
+          deviceDir.resolve(String.format(filenameFormat, entry.getKey())), entry.getValue());
+    }
+    return filesBuilder.build();
+  }
+
+  public static ImmutableMultimap<Path, Path> applyFilenameFormat(
+      Multimap<String, Path> filesToHashes, Path deviceDir, String filenameFormat) {
+    ImmutableMultimap.Builder<Path, Path> filesBuilder = ImmutableMultimap.builder();
+    for (Map.Entry<String, Path> entry : filesToHashes.entries()) {
+      filesBuilder.put(
+          deviceDir.resolve(String.format(filenameFormat, entry.getKey())), entry.getValue());
+    }
+    return filesBuilder.build();
+  }
+
+  public static String getJarManifestDigest(String packagePath) throws IOException {
+    Pattern signatureFilePattern = Pattern.compile("META-INF/[A-Z]+\\.SF");
+
+    ZipFile packageZip = null;
+    try {
+      packageZip = new ZipFile(packagePath);
+      // For each file in the zip.
+      for (ZipEntry entry : Collections.list(packageZip.entries())) {
+        // Ignore non-signature files.
+        if (!signatureFilePattern.matcher(entry.getName()).matches()) {
+          continue;
+        }
+
+        BufferedReader sigContents = null;
+        try {
+          sigContents =
+              new BufferedReader(
+                  new InputStreamReader(Objects.requireNonNull(packageZip.getInputStream(entry))));
+          // For each line in the signature file.
+          while (true) {
+            String line = sigContents.readLine();
+            if (line == null || line.equals("")) {
+              throw new IllegalArgumentException(
+                  "Failed to find manifest digest in " + entry.getName());
+            }
+            String prefix_sha1 = "SHA1-Digest-Manifest: ";
+            String prefix_sha256 = "SHA-256-Digest-Manifest: ";
+            if (line.startsWith(prefix_sha1)) {
+              return line.substring(prefix_sha1.length());
+            } else if (line.startsWith(prefix_sha256)) {
+              return line.substring(prefix_sha256.length());
+            }
+          }
+        } finally {
+          if (sigContents != null) {
+            sigContents.close();
+          }
+        }
+      }
+    } finally {
+      if (packageZip != null) {
+        packageZip.close();
+      }
+    }
+
+    throw new IllegalArgumentException("Failed to find signature file.");
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/InstallTimings.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/InstallTimings.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/InstallTimings.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+/**
+ * Collects how long each stage of an install took.
+ *
+ * <p>Paired with when each artifact arrived, this is enough to work out the earliest the install
+ * could have finished had it never waited for an artifact it did not yet need.
+ */
+public interface InstallTimings {
+
+  /** Preparing the device: creating the data root and listing what is already on it. */
+  void recordDeviceSetup(long startMillis, long endMillis);
+
+  /**
+   * Pushing one payload.
+   *
+   * @param group the payload type, as passed to {@link AndroidDevice#installFiles} -- e.g. {@code
+   *     secondary_dex}, {@code native_library}, {@code resources}, {@code metadata}.
+   */
+  void recordPush(String group, long startMillis, long endMillis);
+
+  /** Installing the apk itself. */
+  void recordApkInstall(long startMillis, long endMillis);
+
+  /**
+   * The whole device-side phase. Whatever this covers beyond the stages above -- collecting stale
+   * files, reading back digests, writing the build id -- has to happen regardless of when artifacts
+   * arrive, so it belongs on the critical path too.
+   */
+  void recordDeviceWork(long startMillis, long endMillis);
+
+  /** Discards everything. For call sites that are not part of a measured install. */
+  InstallTimings NONE =
+      new InstallTimings() {
+        @Override
+        public void recordDeviceSetup(long startMillis, long endMillis) {}
+
+        @Override
+        public void recordPush(String group, long startMillis, long endMillis) {}
+
+        @Override
+        public void recordApkInstall(long startMillis, long endMillis) {}
+
+        @Override
+        public void recordDeviceWork(long startMillis, long endMillis) {}
+      };
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/IsolatedExopackageInfo.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/IsolatedExopackageInfo.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/IsolatedExopackageInfo.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage
+
+import com.facebook.buck.core.filesystems.AbsPath
+import com.google.common.collect.ImmutableList
+import java.util.Optional
+
+/**
+ * Isolated ExopackageInfo. Doesn't have any references to SourcePath and other buck's internal data
+ * structures.
+ */
+data class IsolatedExopackageInfo(
+    val dexInfo: Optional<IsolatedDexInfo>,
+    val nativeLibsInfo: Optional<IsolatedNativeLibsInfo>,
+    val resourcesInfo: Optional<IsolatedResourcesInfo>,
+) {
+  /** Isolated DexInfo */
+  data class IsolatedDexInfo(val metadata: AbsPath, val directory: AbsPath)
+
+  /** Isolated NativeLibsInfo */
+  data class IsolatedNativeLibsInfo(val metadata: AbsPath, val directory: AbsPath)
+
+  /** Isolated ResourcesInfo */
+  data class IsolatedResourcesInfo(val resourcesPaths: ImmutableList<IsolatedExopackagePathAndHash>)
+
+  /** Isolated ExopackagePathAndHash */
+  data class IsolatedExopackagePathAndHash(val file: AbsPath, val hashFile: AbsPath)
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/NativeExoHelper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/NativeExoHelper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/NativeExoHelper.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Objects;
+import java.util.function.Supplier;
+
+/** Installs native code for exo. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class NativeExoHelper implements ExoHelper {
+  @VisibleForTesting public static final Path NATIVE_LIBS_DIR = Paths.get("native-libs");
+  private final Supplier<List<String>> abiSupplier;
+  private final AbsPath rootPath;
+  private final IsolatedExopackageInfo.IsolatedNativeLibsInfo nativeLibsInfo;
+
+  NativeExoHelper(
+      Supplier<List<String>> abiSupplier,
+      AbsPath rootPath,
+      IsolatedExopackageInfo.IsolatedNativeLibsInfo nativeLibsInfo) {
+    this.abiSupplier = abiSupplier;
+    this.rootPath = rootPath;
+    this.nativeLibsInfo = nativeLibsInfo;
+  }
+
+  @Override
+  public String getType() {
+    return "native_library";
+  }
+
+  /**
+   * @return a mapping from destinationPathOnDevice -> localPath
+   */
+  @Override
+  public ImmutableMap<Path, Path> getFilesToInstall() throws IOException {
+    ImmutableMap.Builder<Path, Path> filesToInstallBuilder = ImmutableMap.builder();
+    ImmutableMap<String, ImmutableMultimap<String, Path>> filesByHashForAbis =
+        getFilesByHashForAbis();
+    for (String abi : filesByHashForAbis.keySet()) {
+      ImmutableMultimap<String, Path> filesByHash =
+          Objects.requireNonNull(filesByHashForAbis.get(abi));
+      Path abiDir = NATIVE_LIBS_DIR.resolve(abi);
+      for (Entry<Path, Collection<Path>> entry :
+          ExopackageUtil.applyFilenameFormat(filesByHash, abiDir, "native-%s.so")
+              .asMap()
+              .entrySet()) {
+        // The files in the getValue collection should all be identical
+        // (because the key in their hash), so just pick the first one.
+        filesToInstallBuilder.put(entry.getKey(), entry.getValue().iterator().next());
+      }
+    }
+    return filesToInstallBuilder.build();
+  }
+
+  /**
+   * @return a mapping from destinationPathOnDevice -> contents of file for all native-libs metadata
+   *     files (one per abi)
+   */
+  @Override
+  public ImmutableMap<Path, String> getMetadataToInstall() throws IOException {
+    ImmutableMap<String, ImmutableMultimap<String, Path>> filesByHashForAbis =
+        getFilesByHashForAbis();
+    ImmutableMap.Builder<Path, String> metadataBuilder = ImmutableMap.builder();
+    for (String abi : filesByHashForAbis.keySet()) {
+      ImmutableMultimap<String, Path> filesByHash =
+          Objects.requireNonNull(filesByHashForAbis.get(abi));
+      Path abiDir = NATIVE_LIBS_DIR.resolve(abi);
+      metadataBuilder.put(
+          abiDir.resolve("metadata.txt"), getNativeLibraryMetadataContents(filesByHash));
+    }
+    return metadataBuilder.build();
+  }
+
+  private ImmutableMultimap<String, Path> getAllLibraries() throws IOException {
+    return ExopackageInstaller.parseExopackageInfoMetadata(
+        nativeLibsInfo.getMetadata(), nativeLibsInfo.getDirectory(), rootPath);
+  }
+
+  private ImmutableMap<String, ImmutableMultimap<String, Path>> getFilesByHashForAbis()
+      throws IOException {
+    List<String> deviceAbis = abiSupplier.get();
+    ImmutableMap.Builder<String, ImmutableMultimap<String, Path>> filesByHashForAbisBuilder =
+        ImmutableMap.builder();
+    ImmutableMultimap<String, Path> allLibraries = getAllLibraries();
+    ImmutableSet.Builder<String> providedLibraries = ImmutableSet.builder();
+    for (String abi : deviceAbis) {
+      ImmutableMultimap<String, Path> filesByHash =
+          getRequiredLibrariesForAbi(allLibraries, abi, providedLibraries.build());
+      if (filesByHash.isEmpty()) {
+        continue;
+      }
+      providedLibraries.addAll(filesByHash.keySet());
+      filesByHashForAbisBuilder.put(abi, filesByHash);
+    }
+    return filesByHashForAbisBuilder.build();
+  }
+
+  private ImmutableMultimap<String, Path> getRequiredLibrariesForAbi(
+      ImmutableMultimap<String, Path> allLibraries,
+      String abi,
+      ImmutableSet<String> ignoreLibraries) {
+    return filterLibrariesForAbi(nativeLibsInfo.getDirectory(), allLibraries, abi, ignoreLibraries);
+  }
+
+  @VisibleForTesting
+  public static ImmutableMultimap<String, Path> filterLibrariesForAbi(
+      AbsPath nativeLibsDir,
+      ImmutableMultimap<String, Path> allLibraries,
+      String abi,
+      ImmutableSet<String> ignoreLibraries) {
+    ImmutableMultimap.Builder<String, Path> filteredLibraries = ImmutableMultimap.builder();
+    for (Map.Entry<String, Path> entry : allLibraries.entries()) {
+      RelPath relativePath = nativeLibsDir.relativize(entry.getValue());
+      Preconditions.checkState(
+          relativePath.getNameCount() == 2 || relativePath.getNameCount() == 3,
+          "relativePath should be of the form x86/foo.so (for buck2) or either libs/x86/foo.so or"
+              + " assetLibs/x86/foo.so (for buck1), but was: "
+              + relativePath);
+      if (relativePath.getNameCount() == 3) {
+        Preconditions.checkState(
+            relativePath.getName(0).toString().equals("libs")
+                || relativePath.getName(0).toString().equals("assetLibs"));
+      }
+      String libAbi = relativePath.getParent().getFileName().toString();
+      String libName = relativePath.getFileName().toString();
+      if (libAbi.equals(abi) && !ignoreLibraries.contains(libName)) {
+        filteredLibraries.put(entry);
+      }
+    }
+    return filteredLibraries.build();
+  }
+
+  private String getNativeLibraryMetadataContents(ImmutableMultimap<String, Path> libraries) {
+    return Joiner.on('\n')
+        .join(
+            FluentIterable.from(libraries.entries())
+                .transform(
+                    input -> {
+                      String hash = input.getKey();
+                      String filename = input.getValue().getFileName().toString();
+                      int index = filename.lastIndexOf('.');
+                      String libname = index == -1 ? filename : filename.substring(0, index);
+                      return String.format("%s native-%s.so", libname, hash);
+                    }));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/PackageInfo.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/PackageInfo.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/PackageInfo.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+
+@VisibleForTesting
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class PackageInfo {
+  public final String apkPath;
+  public final String nativeLibPath;
+  public final String versionCode;
+
+  public PackageInfo(String apkPath, String nativeLibPath, String versionCode) {
+    this.nativeLibPath = nativeLibPath;
+    this.apkPath = apkPath;
+    this.versionCode = versionCode;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ResourcesExoHelper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ResourcesExoHelper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/exopackage/ResourcesExoHelper.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.exopackage;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableMap;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.stream.Stream;
+
+/** Installs resources for exo. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ResourcesExoHelper implements ExoHelper {
+
+  @VisibleForTesting public static final Path RESOURCES_DIR = Paths.get("resources");
+
+  private final AbsPath rootPath;
+  private final IsolatedExopackageInfo.IsolatedResourcesInfo resourcesInfo;
+
+  ResourcesExoHelper(AbsPath rootPath, IsolatedExopackageInfo.IsolatedResourcesInfo resourcesInfo) {
+    this.rootPath = rootPath;
+    this.resourcesInfo = resourcesInfo;
+  }
+
+  private static ImmutableMap<Path, Path> getFilesToInstall(
+      ImmutableMap<String, Path> filesByHash) {
+    return ExopackageUtil.applyFilenameFormat(filesByHash, RESOURCES_DIR, "%s.apk");
+  }
+
+  /** Returns a map of hash to path for resource files. */
+  private static ImmutableMap<String, Path> getResourceFilesByHash(
+      AbsPath rootPath,
+      Stream<IsolatedExopackageInfo.IsolatedExopackagePathAndHash> resourcesPaths) {
+    return resourcesPaths.collect(
+        ImmutableMap.toImmutableMap(
+            pathAndHash -> readHash(rootPath, pathAndHash),
+            pathAndHash -> pathAndHash.getFile().getPath()));
+  }
+
+  /**
+   * A resource's hash is what names it on the device, so a resource whose hash cannot be read
+   * cannot be installed. Fail loudly rather than dropping it: this map is used both to decide what
+   * to push and to decide what is still wanted, so a silently missing entry means the previous copy
+   * is collected, the new one is never pushed, and the install reports success anyway.
+   */
+  private static String readHash(
+      AbsPath rootPath, IsolatedExopackageInfo.IsolatedExopackagePathAndHash pathAndHash) {
+    Path hashFile = pathAndHash.getHashFile().getPath();
+    return ProjectFilesystemUtils.readFileIfItExists(rootPath, hashFile)
+        .orElseThrow(
+            () ->
+                new IllegalStateException(
+                    String.format(
+                        "Missing exopackage resource hash file %s for resource %s",
+                        hashFile, pathAndHash.getFile().getPath())))
+        .stripTrailing();
+  }
+
+  @Override
+  public String getType() {
+    return "resources";
+  }
+
+  @Override
+  public ImmutableMap<Path, Path> getFilesToInstall() {
+    return getFilesToInstall(getResourceFilesByHash());
+  }
+
+  @Override
+  public ImmutableMap<Path, String> getMetadataToInstall() {
+    return ImmutableMap.of(
+        RESOURCES_DIR.resolve("metadata.txt"),
+        getResourceMetadataContents(getResourceFilesByHash()));
+  }
+
+  private ImmutableMap<String, Path> getResourceFilesByHash() {
+    return getResourceFilesByHash(rootPath, resourcesInfo.getResourcesPaths().stream());
+  }
+
+  private static String getResourceMetadataContents(ImmutableMap<String, Path> filesByHash) {
+    return Joiner.on("\n")
+        .join(filesByHash.keySet().stream().map(h -> "resources " + h).iterator());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/BUCK
@@ -0,0 +1,47 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "SIGNED_JAR_BLOCKLIST", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "manifest",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/...",
+        "prelude//toolchains/android/test/com/facebook/buck/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android:manifest_utils",
+        "prelude//toolchains/android/src/com/facebook/buck/android/apkmodule:module-only",
+        "prelude//toolchains/android/src/com/facebook/buck/util:throwing_print_writer",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        "prelude//toolchains/android/third-party:manifest-merger",
+        "prelude//toolchains/android/third-party:tools-sdk-common",
+    ],
+)
+
+buck_java_binary(
+    name = "generate_manifest_binary",
+    blocklist = SIGNED_JAR_BLOCKLIST,
+    main_class = "com.facebook.buck.android.manifest.GenerateManifestExecutableMain",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":manifest",
+    ],
+)
+
+buck_java_binary(
+    name = "replace_application_id_placeholders_binary",
+    blocklist = SIGNED_JAR_BLOCKLIST,
+    main_class = "com.facebook.buck.android.manifest.ReplaceApplicationIdPlaceholdersExecutableMain",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":manifest",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/GenerateManifest.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/GenerateManifest.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/GenerateManifest.java
@@ -0,0 +1,605 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.manifest;
+
+import com.android.ide.common.xml.XmlFormatPreferences;
+import com.android.ide.common.xml.XmlFormatStyle;
+import com.android.ide.common.xml.XmlPrettyPrinter;
+import com.android.manifmerger.ManifestMerger2;
+import com.android.manifmerger.MergingReport;
+import com.android.manifmerger.PlaceholderHandler;
+import com.android.utils.ILogger;
+import com.facebook.buck.android.DefaultAndroidManifestReader;
+import com.facebook.buck.android.apkmodule.APKModule;
+import com.facebook.buck.util.environment.Platform;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.io.Files;
+import java.io.File;
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import org.jetbrains.annotations.Nullable;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class GenerateManifest {
+
+  public static final String ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android";
+
+  /** Holds SDK version information extracted from a manifest file. */
+  @VisibleForTesting
+  static class SdkVersions {
+    @Nullable private final String minSdkVersion;
+    @Nullable private final String targetSdkVersion;
+
+    SdkVersions(@Nullable String minSdkVersion, @Nullable String targetSdkVersion) {
+      this.minSdkVersion = minSdkVersion;
+      this.targetSdkVersion = targetSdkVersion;
+    }
+
+    @Nullable
+    String getMinSdkVersion() {
+      return minSdkVersion;
+    }
+
+    @Nullable
+    String getTargetSdkVersion() {
+      return targetSdkVersion;
+    }
+  }
+
+  public static String generateXml(
+      Path skeletonManifestPath,
+      String moduleName,
+      ImmutableList<Path> libraryManifestPaths,
+      ImmutableMap<String, String> placeholders,
+      Path outManifestPath,
+      Path mergeReportPath,
+      @Nullable Path preprocessLogPath,
+      ILogger logger)
+      throws IOException {
+    if (skeletonManifestPath.getNameCount() == 0) {
+      throw new RuntimeException("Skeleton manifest filepath is missing");
+    }
+
+    if (outManifestPath.getNameCount() == 0) {
+      throw new RuntimeException("Output Manifest filepath is missing");
+    }
+
+    Files.createParentDirs(outManifestPath.toFile());
+
+    // Create preprocess logger (always creates a log file, in /tmp if no path specified)
+    PreprocessLogger preprocessLogger = PreprocessLogger.create(preprocessLogPath, logger);
+    preprocessLogger.log("=== Manifest Preprocessing Log ===\n");
+    preprocessLogger.log("Skeleton manifest: %s\n", skeletonManifestPath.toAbsolutePath());
+    preprocessLogger.log("Module name: %s\n", moduleName);
+    preprocessLogger.log("Library manifests count: %d\n\n", libraryManifestPaths.size());
+
+    // Extract SDK versions from the skeleton manifest
+    SdkVersions sdkVersions = extractSdkVersions(skeletonManifestPath.toFile(), logger);
+
+    // Preprocess library manifests to inject targetSdkVersion and minSdkVersion if missing
+    String tmpDirEnv = System.getenv("BUCK_SCRATCH_PATH");
+    if (tmpDirEnv == null || tmpDirEnv.isEmpty()) {
+      throw new RuntimeException(
+          "BUCK_SCRATCH_PATH environment variable must be set and non-empty");
+    }
+    Path tmpDirPath = java.nio.file.Paths.get(tmpDirEnv);
+    Path tempDir = tmpDirPath.resolve("preprocessed_manifests");
+    java.nio.file.Files.createDirectories(tempDir);
+
+    List<File> libraryManifestFiles = new ArrayList<>();
+    for (Path libraryManifestPath : libraryManifestPaths) {
+      File processedFile =
+          preprocessLibraryManifest(
+              libraryManifestPath.toFile(), tempDir, sdkVersions, preprocessLogger, logger);
+      libraryManifestFiles.add(processedFile);
+    }
+
+    MergingReport mergingReport =
+        mergeManifests(
+            moduleName,
+            skeletonManifestPath.toFile(),
+            libraryManifestFiles,
+            mergeReportPath,
+            logger);
+
+    // Post-process merge report to make all paths relative to current directory
+    makePathsRelativeInMergeReport(mergeReportPath, logger);
+
+    // Absent only when the merge failed, which mergeManifests already turns into an exception.
+    String xmlText =
+        Objects.requireNonNull(
+            mergingReport.getMergedDocument(MergingReport.MergedManifestKind.MERGED));
+    xmlText = replacePlaceholders(xmlText, placeholders);
+    xmlText = moveActivityAliasesToEnd(xmlText);
+
+    if (Platform.detect() == Platform.WINDOWS) {
+      // Convert line endings to Lf on Windows.
+      xmlText = xmlText.replace("\r\n", "\n");
+    }
+
+    // Close preprocess logger
+    preprocessLogger.log("\n=== Preprocessing Complete ===\n");
+    preprocessLogger.close();
+
+    return xmlText;
+  }
+
+  public static String replaceApplicationIdPlaceholders(
+      String currentManifest, boolean verifyNoPlaceholdersLeft) throws IOException {
+    // Library manifests can set the applicationId placeholder in the expectation that it will
+    // be replaced by the actual applicationId in the final manifest. The applicationId is
+    // the "package" attribute in the final manifest, so we extract that here and then use it.
+    // See https://developer.android.com/studio/build/configure-app-module#set-application-id
+    final String applicationPackage =
+        DefaultAndroidManifestReader.forString(currentManifest).getPackage();
+
+    String manifest =
+        replacePlaceholders(
+            currentManifest,
+            ImmutableMap.of(PlaceholderHandler.APPLICATION_ID, applicationPackage));
+
+    if (verifyNoPlaceholdersLeft) {
+      verifyAllPlaceholdersAreReplacedInManifestOrThrow(manifest);
+    }
+
+    return manifest;
+  }
+
+  private static MergingReport mergeManifests(
+      String moduleName,
+      File mainManifestFile,
+      List<File> libraryManifestFiles,
+      Path mergeReportPath,
+      ILogger logger) {
+    try {
+      ManifestMerger2.Invoker manifestInvoker =
+          ManifestMerger2.newMerger(
+              mainManifestFile, logger, ManifestMerger2.MergeType.APPLICATION);
+      if (!APKModule.isRootModule(moduleName)) {
+        manifestInvoker.setPlaceHolderValue("split", moduleName);
+      } else {
+        manifestInvoker.withFeatures(ManifestMerger2.Invoker.Feature.NO_PLACEHOLDER_REPLACEMENT);
+      }
+
+      MergingReport mergingReport =
+          manifestInvoker
+              .withFeatures(
+                  ManifestMerger2.Invoker.Feature.REMOVE_TOOLS_DECLARATIONS,
+                  ManifestMerger2.Invoker.Feature.DISABLE_PACKAGE_NAME_UNIQUENESS_CHECK,
+                  ManifestMerger2.Invoker.Feature.USES_SDK_IN_MANIFEST_LENIENT_HANDLING)
+              .addLibraryManifests(Iterables.toArray(libraryManifestFiles, File.class))
+              .setMergeReportFile(mergeReportPath.toFile())
+              .merge();
+      if (mergingReport.getResult().isError()) {
+        for (MergingReport.Record record : mergingReport.getLoggingRecords()) {
+          logger.error(null, record.toString());
+        }
+        throw new RuntimeException("Error generating manifest file");
+      }
+
+      return mergingReport;
+    } catch (ManifestMerger2.MergeFailureException e) {
+      throw new RuntimeException(
+          String.format("Error generating manifest file: %s", String.valueOf(e.getMessage())),
+          e.getCause());
+    }
+  }
+
+  @VisibleForTesting
+  static String replacePlaceholders(String content, ImmutableMap<String, String> placeholders) {
+    Iterable<String> escaped = Iterables.transform(placeholders.keySet(), Pattern::quote);
+
+    Joiner joiner = Joiner.on("|");
+    String patternString =
+        Pattern.quote("${") + "(" + joiner.join(escaped) + ")" + Pattern.quote("}");
+    Pattern pattern = Pattern.compile(patternString);
+    Matcher matcher = pattern.matcher(content);
+
+    StringBuffer sb = new StringBuffer();
+    while (matcher.find()) {
+      final String value = Objects.requireNonNull(placeholders.get(matcher.group(1)));
+      // There are instances where the value of a placeholder points to another placeholder, having
+      // the form of `${key}`.
+      // This clashes with the implementation details of `Matcher.appendReplacement`, which uses the
+      // same form to identify what to replace. Escaping `$` prevents this conflict from happening.
+      final String escapedValue = value.replace("$", "\\$");
+      matcher.appendReplacement(sb, escapedValue);
+    }
+    matcher.appendTail(sb);
+    return sb.toString();
+  }
+
+  private static void verifyAllPlaceholdersAreReplacedInManifestOrThrow(String content) {
+    String contentWithoutComments = content.replaceAll("<!--[\\s\\S\\n]*?-->", "");
+    Pattern pattern = Pattern.compile(Pattern.quote("${") + "(.*?)" + Pattern.quote("}"));
+    Matcher matcher = pattern.matcher(contentWithoutComments);
+
+    Set<String> nonHandledPlaceholders = new HashSet<>();
+    while (matcher.find()) {
+      nonHandledPlaceholders.add(matcher.group(1));
+    }
+
+    if (!nonHandledPlaceholders.isEmpty()) {
+      throw new RuntimeException(
+          String.format(
+              "Not handled placeholders (%s) in manifest: %s", nonHandledPlaceholders, content));
+    }
+  }
+
+  /**
+   * At the moment all apps using manifest.py in fbsource already handle how activity-alias are
+   * sorted to guarantee they are in the manifest after the activity they target thanks to the post
+   * processing happening in @link{<a href="https://fburl.com/code/fsiow1yu">the manifest.py</a>}.
+   *
+   * <p>In WA this is not the case and we want to guarantee the order is maintained until we are
+   * able to update the ManifestMerging plugin to more recent version. This is a link to a @link{<a
+   * href="https://fburl.com/workplace/byshefjr">discussion</a>} regarding this specific manifest
+   * merging issue.
+   *
+   * <p>Once the latest version of the ManifestMerger will be updated we can clean up this step and
+   * the work is tracked in T239793438
+   */
+  @VisibleForTesting
+  static String moveActivityAliasesToEnd(String xmlContent) {
+    try {
+      // Parse the XML
+      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+      factory.setNamespaceAware(true);
+      DocumentBuilder builder = factory.newDocumentBuilder();
+      Document doc =
+          Objects.requireNonNull(builder.parse(new InputSource(new StringReader(xmlContent))));
+
+      // Find the application element
+      NodeList applicationNodes = doc.getElementsByTagName("application");
+      if (applicationNodes.getLength() == 0) {
+        return xmlContent; // No application element, nothing to do
+      }
+
+      Element application = (Element) Objects.requireNonNull(applicationNodes.item(0));
+      List<Element> earlyAliases = getEarlyAliases(application);
+
+      if (earlyAliases.isEmpty()) {
+        // No early aliases found, so let's just return the original xmlContent
+        return xmlContent;
+      }
+
+      // Move early aliases to the end
+      for (Element alias : earlyAliases) {
+        application.removeChild(alias);
+        application.appendChild(alias);
+      }
+
+      // Use XmlPrettyPrinter to format the output, matching the manifest merger's formatting
+      XmlFormatPreferences prefs = XmlFormatPreferences.defaults();
+      prefs.removeEmptyLines = true;
+
+      return XmlPrettyPrinter.prettyPrint(
+          doc,
+          prefs,
+          XmlFormatStyle.get(doc),
+          null, /* lineSeparator */
+          false /* endWithNewline */);
+
+    } catch (Exception e) {
+      // If XML processing fails, return original content
+      // This ensures the build doesn't break if there's an issue with the reordering
+      return xmlContent;
+    }
+  }
+
+  private static List<Element> getEarlyAliases(Element application) {
+    Set<String> activityNames = new HashSet<>();
+    List<Element> earlyAliases = new ArrayList<>();
+
+    // Iterate through children to find activities and early aliases
+    NodeList children = application.getChildNodes();
+    for (int i = 0; i < children.getLength(); i++) {
+      Node node = Objects.requireNonNull(children.item(i));
+      if (node.getNodeType() != Node.ELEMENT_NODE) {
+        continue;
+      }
+
+      Element element = (Element) node;
+      String tagName = element.getTagName();
+
+      if ("activity".equals(tagName)) {
+        String name = element.getAttributeNS(ANDROID_NAMESPACE, "name");
+        if (name != null && !name.isEmpty()) {
+          activityNames.add(name);
+        }
+      } else if ("activity-alias".equals(tagName)) {
+        String target = element.getAttributeNS(ANDROID_NAMESPACE, "targetActivity");
+        if (target != null && !target.isEmpty() && !activityNames.contains(target)) {
+          earlyAliases.add(element);
+        }
+      }
+    }
+    return earlyAliases;
+  }
+
+  /**
+   * Extracts both minSdkVersion and targetSdkVersion from the main/skeleton manifest in a single
+   * pass.
+   *
+   * @param skeletonManifest The main application manifest file
+   * @param logger Logger for debugging information
+   * @return SdkVersions object containing both SDK versions (may be null if not found)
+   */
+  @VisibleForTesting
+  static SdkVersions extractSdkVersions(File skeletonManifest, ILogger logger) {
+    String minSdkVersion = null;
+    String targetSdkVersion = null;
+
+    try {
+      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+      factory.setNamespaceAware(true);
+      DocumentBuilder builder = factory.newDocumentBuilder();
+      Document doc = Objects.requireNonNull(builder.parse(skeletonManifest));
+
+      NodeList usesSdkNodes = doc.getElementsByTagName("uses-sdk");
+      if (usesSdkNodes.getLength() > 0) {
+        Element usesSdk = (Element) Objects.requireNonNull(usesSdkNodes.item(0));
+
+        String docMinSdkVersion = usesSdk.getAttributeNS(ANDROID_NAMESPACE, "minSdkVersion");
+        String docTargetSdkVersion = usesSdk.getAttributeNS(ANDROID_NAMESPACE, "targetSdkVersion");
+
+        if (!Strings.isNullOrEmpty(docMinSdkVersion)) {
+          minSdkVersion = docMinSdkVersion;
+          logger.info(
+              "Extracted minSdkVersion=%s from skeleton manifest %s",
+              minSdkVersion, skeletonManifest.getPath());
+        } else {
+          logger.warning(
+              "No minSdkVersion found in skeleton manifest %s", skeletonManifest.getPath());
+        }
+
+        if (!Strings.isNullOrEmpty(docTargetSdkVersion)) {
+          targetSdkVersion = docTargetSdkVersion;
+          logger.info(
+              "Extracted targetSdkVersion=%s from skeleton manifest %s",
+              targetSdkVersion, skeletonManifest.getPath());
+        } else {
+          logger.warning(
+              "No targetSdkVersion found in skeleton manifest %s", skeletonManifest.getPath());
+        }
+      } else {
+        logger.warning(
+            "No <uses-sdk> element found in skeleton manifest %s", skeletonManifest.getPath());
+      }
+
+    } catch (Exception e) {
+      logger.warning(
+          "Failed to extract SDK versions from skeleton manifest %s: %s",
+          skeletonManifest.getPath(), String.valueOf(e.getMessage()));
+    }
+
+    return new SdkVersions(minSdkVersion, targetSdkVersion);
+  }
+
+  /**
+   * Preprocesses library manifests to inject targetSdkVersion and minSdkVersion when missing.
+   *
+   * <p>This prevents the manifest merger from assuming targetSdkVersion < 4 for library manifests
+   * that don't declare a <uses-sdk> element, which would cause Android to add implied permissions
+   * like READ_PHONE_STATE.
+   *
+   * <p>The targetSdkVersion and minSdkVersion are extracted from the main application manifest to
+   * ensure consistency across all merged manifests.
+   *
+   * @param originalFile Original library manifest file
+   * @param outputDir Directory to write preprocessed manifests
+   * @param sdkVersions SDK versions from the main manifest
+   * @param preprocessLogger Logger for logging preprocessing activities
+   * @param logger Logger for debugging information
+   * @return Preprocessed manifest file (or original if no processing needed)
+   * @throws IOException if logging fails
+   */
+  @VisibleForTesting
+  static File preprocessLibraryManifest(
+      File originalFile,
+      Path outputDir,
+      SdkVersions sdkVersions,
+      PreprocessLogger preprocessLogger,
+      ILogger logger)
+      throws IOException {
+    String targetSdkVersion = sdkVersions.getTargetSdkVersion();
+    String minSdkVersion = sdkVersions.getMinSdkVersion();
+
+    // Log the file being processed
+    preprocessLogger.log("Processing library manifest: %s\n", originalFile.getPath());
+
+    if (targetSdkVersion == null && minSdkVersion == null) {
+      preprocessLogger.log("  -> Skipped: No SDK versions to inject\n");
+      return originalFile;
+    }
+
+    try {
+      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+      factory.setNamespaceAware(true);
+      DocumentBuilder builder = factory.newDocumentBuilder();
+      Document doc = Objects.requireNonNull(builder.parse(originalFile));
+
+      Element usesSdk = getOrCreateUsesSdk(doc);
+
+      String existingTargetSdk = usesSdk.getAttributeNS(ANDROID_NAMESPACE, "targetSdkVersion");
+      String existingMinSdk = usesSdk.getAttributeNS(ANDROID_NAMESPACE, "minSdkVersion");
+      boolean patched = false;
+
+      if (Strings.isNullOrEmpty(existingTargetSdk) && targetSdkVersion != null) {
+        usesSdk.setAttributeNS(ANDROID_NAMESPACE, "android:targetSdkVersion", targetSdkVersion);
+        patched = true;
+        preprocessLogger.log("  -> Injected targetSdkVersion=%s (was missing)\n", targetSdkVersion);
+      }
+      if (Strings.isNullOrEmpty(existingMinSdk) && minSdkVersion != null) {
+        usesSdk.setAttributeNS(ANDROID_NAMESPACE, "android:minSdkVersion", minSdkVersion);
+        patched = true;
+        preprocessLogger.log("  -> Injected minSdkVersion=%s (was missing)\n", minSdkVersion);
+      }
+
+      if (patched) {
+        ensureAndroidNamespace(doc);
+        File processedFile = writeProcessedManifest(originalFile, outputDir, doc);
+        logger.info("%s -- preprocessed --> %s", originalFile.getPath(), processedFile.getPath());
+        preprocessLogger.log("  -> Written to: %s\n", processedFile.getPath());
+        return processedFile;
+      } else {
+        preprocessLogger.log("  -> No preprocessing needed (SDK versions already present)\n");
+      }
+    } catch (IOException e) {
+      // Rethrow IOException (from logging) to fail the build
+      throw e;
+    } catch (Exception e) {
+      // Catch XML parsing exceptions, log them, and use original manifest
+      logger.warning(
+          "Failed to preprocess library manifest %s: %s. Using original.",
+          originalFile.getPath(), String.valueOf(e.getMessage()));
+      preprocessLogger.log(
+          "  -> ERROR: Failed to preprocess: %s\n", String.valueOf(e.getMessage()));
+      preprocessLogger.log("  -> Using original manifest\n");
+    }
+    return originalFile;
+  }
+
+  /**
+   * Ensures the android namespace is declared on the manifest element.
+   *
+   * @param doc The manifest document
+   */
+  @VisibleForTesting
+  static void ensureAndroidNamespace(Document doc) {
+    Element manifestElement = Objects.requireNonNull(doc.getDocumentElement());
+    String androidNsAttr = manifestElement.getAttribute("xmlns:android");
+    if (Strings.isNullOrEmpty(androidNsAttr)) {
+      manifestElement.setAttribute("xmlns:android", ANDROID_NAMESPACE);
+    }
+  }
+
+  /**
+   * Gets the existing uses-sdk element from the document, or creates a new one if it doesn't exist.
+   *
+   * @param doc The manifest document
+   * @return The uses-sdk element (either existing or newly created)
+   */
+  @VisibleForTesting
+  static Element getOrCreateUsesSdk(Document doc) {
+    NodeList usesSdkNodes = doc.getElementsByTagName("uses-sdk");
+    if (usesSdkNodes.getLength() > 0) {
+      return (Element) Objects.requireNonNull(usesSdkNodes.item(0));
+    }
+
+    Element usesSdk = doc.createElement("uses-sdk");
+    Element manifestElement = Objects.requireNonNull(doc.getDocumentElement());
+
+    Node firstChild = manifestElement.getFirstChild();
+    if (firstChild != null) {
+      manifestElement.insertBefore(usesSdk, firstChild);
+    } else {
+      manifestElement.appendChild(usesSdk);
+    }
+
+    return usesSdk;
+  }
+
+  private static File writeProcessedManifest(File originalFile, Path outputDir, Document doc)
+      throws IOException {
+    // Write the modified manifest to a temporary file
+    File processedFile = outputDir.resolve(originalFile.getPath()).toFile();
+    Objects.requireNonNull(processedFile.getParentFile()).mkdirs();
+
+    XmlFormatPreferences prefs = XmlFormatPreferences.defaults();
+    prefs.removeEmptyLines = true;
+    String formattedXml =
+        XmlPrettyPrinter.prettyPrint(
+            doc,
+            prefs,
+            XmlFormatStyle.get(doc),
+            null, /* lineSeparator */
+            false /* endWithNewline */);
+
+    java.nio.file.Files.write(processedFile.toPath(), formattedXml.getBytes());
+    return processedFile;
+  }
+
+  /**
+   * Post-processes the merge report file to convert all absolute paths to relative paths.
+   *
+   * @param mergeReportPath Path to the merge report file
+   * @param logger Logger for debugging information
+   */
+  private static void makePathsRelativeInMergeReport(Path mergeReportPath, ILogger logger) {
+    try {
+      if (!java.nio.file.Files.exists(mergeReportPath)) {
+        logger.warning("Merge report file does not exist: " + mergeReportPath);
+        return;
+      }
+
+      String content =
+          new String(java.nio.file.Files.readAllBytes(mergeReportPath), StandardCharsets.UTF_8);
+      Path currentDir = java.nio.file.Paths.get("").toAbsolutePath();
+      String modifiedContent = makePathsRelative(content, currentDir);
+      java.nio.file.Files.write(mergeReportPath, modifiedContent.getBytes(StandardCharsets.UTF_8));
+      logger.info("Made paths relative in merge report: " + mergeReportPath);
+    } catch (IOException e) {
+      logger.warning(
+          "Failed to make paths relative in merge report: "
+              + String.valueOf(e.getMessage())
+              + ". Report will contain absolute paths.");
+    }
+  }
+
+  /**
+   * Replaces absolute paths in the content with relative paths from the current directory.
+   *
+   * <p>Only replaces paths that start with the current directory to avoid false matches with
+   * substring occurrences.
+   *
+   * @param content The content to process
+   * @param currentDir The current working directory
+   * @return Content with paths made relative
+   */
+  private static String makePathsRelative(String content, Path currentDir) {
+    String currentDirStr = currentDir.toString();
+    String result = content;
+
+    // Build patterns with path separators to match only actual path prefixes
+    // Handle both forward slashes and backslashes for cross-platform compatibility
+    String withForwardSlash = currentDirStr + "/";
+    String withBackslash = currentDirStr + "\\";
+
+    // Replace paths that start with currentDir followed by a separator
+    result = result.replace(withForwardSlash, "");
+    result = result.replace(withBackslash, "");
+
+    return result;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/GenerateManifestExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/GenerateManifestExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/GenerateManifestExecutableMain.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.manifest;
+
+import com.android.utils.StdLogger;
+import com.facebook.buck.util.ThrowingPrintWriter;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/**
+ * Main entry point for executing {@link GenerateManifest} calls.
+ *
+ * <p>Expected usage: {@code this_binary <skeleton_manifest_path> <module_name>
+ * <library_manifest_paths_file> <placeholder_entries_file> <output_path> <merge_report_path} .
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class GenerateManifestExecutableMain {
+  @Option(name = "--skeleton-manifest", required = true)
+  private String skeletonManifest;
+
+  @Option(name = "--module-name", required = true)
+  private String moduleName;
+
+  @Option(name = "--library-manifests-list", required = true)
+  private String libraryManifestsList;
+
+  @Option(name = "--placeholder-entries-list", required = true)
+  private String placeholderEntriesList;
+
+  @Option(name = "--output", required = true)
+  private String output;
+
+  @Option(name = "--merge-report", required = true)
+  private String mergeReport;
+
+  @Option(name = "--preprocess-log", required = false)
+  @Nullable
+  private String preprocessLog = null;
+
+  public static void main(String[] args) throws IOException {
+    GenerateManifestExecutableMain main = new GenerateManifestExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(String.valueOf(e.getMessage()));
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    ImmutableList<Path> libraryManifestsFilePaths =
+        Files.readAllLines(Paths.get(libraryManifestsList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableList.toImmutableList());
+
+    ImmutableMap<String, String> placeholderEntries =
+        Files.readAllLines(Paths.get(placeholderEntriesList)).stream()
+            .map(s -> s.split(" "))
+            .collect(ImmutableMap.toImmutableMap(arr -> arr[0], arr -> arr[1]));
+
+    Path outputPath = Paths.get(output);
+    Path preprocessLogPath = preprocessLog != null ? Paths.get(preprocessLog) : null;
+
+    String xmlText =
+        GenerateManifest.generateXml(
+            Paths.get(skeletonManifest),
+            moduleName,
+            libraryManifestsFilePaths,
+            placeholderEntries,
+            outputPath,
+            Paths.get(mergeReport),
+            preprocessLogPath,
+            new StdLogger(StdLogger.Level.ERROR));
+
+    try (ThrowingPrintWriter writer =
+        new ThrowingPrintWriter(new FileOutputStream(outputPath.toFile()))) {
+      writer.printf(xmlText);
+    }
+
+    System.exit(0);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/PreprocessLogger.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/PreprocessLogger.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/PreprocessLogger.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.manifest;
+
+import com.android.utils.ILogger;
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Logger for manifest preprocessing activities.
+ *
+ * <p>Always writes preprocessing logs to a file. If no path is specified, creates a temporary log
+ * file in /tmp. Throws exceptions if logging fails to ensure build transparency.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class PreprocessLogger implements Closeable {
+  private final BufferedWriter writer;
+  private final Path logPath;
+
+  private PreprocessLogger(BufferedWriter writer, Path logPath) {
+    this.writer = writer;
+    this.logPath = logPath;
+  }
+
+  /**
+   * Creates a PreprocessLogger that writes to the specified file, or a temp file if path is null.
+   *
+   * @param logPath Path to the log file, or null to create a temp file in /tmp
+   * @param logger Logger for reporting the log file location
+   * @return PreprocessLogger instance
+   * @throws IOException if the log file cannot be created
+   */
+  public static PreprocessLogger create(@Nullable Path logPath, ILogger logger) throws IOException {
+    Path actualLogPath;
+    if (logPath != null) {
+      actualLogPath = logPath;
+    } else {
+      // Create a temporary log file in /tmp with a unique name
+      String tempFileName = String.format("manifest_preprocess_%d.log", System.currentTimeMillis());
+      actualLogPath = Paths.get("/tmp", tempFileName);
+    }
+
+    BufferedWriter writer = new BufferedWriter(new FileWriter(actualLogPath.toFile()));
+    logger.info("Manifest preprocessing log: %s", actualLogPath.toAbsolutePath());
+    return new PreprocessLogger(writer, actualLogPath);
+  }
+
+  /**
+   * Gets the path to the log file.
+   *
+   * @return Path to the log file
+   */
+  public Path getLogPath() {
+    return logPath;
+  }
+
+  /**
+   * Writes a formatted line to the log file.
+   *
+   * @param format Format string
+   * @param args Format arguments
+   * @throws IOException if writing fails
+   */
+  public void log(String format, Object... args) throws IOException {
+    writer.write(String.format(format, args));
+    writer.flush();
+  }
+
+  /**
+   * Writes a line to the log file without formatting.
+   *
+   * @param message Message to write
+   * @throws IOException if writing fails
+   */
+  public void log(String message) throws IOException {
+    writer.write(message);
+    writer.flush();
+  }
+
+  @Override
+  public void close() throws IOException {
+    writer.close();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/ReplaceApplicationIdPlaceholdersExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/ReplaceApplicationIdPlaceholdersExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/manifest/ReplaceApplicationIdPlaceholdersExecutableMain.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.manifest;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/**
+ * Main entry point for executing {@link GenerateManifest#replaceApplicationIdPlaceholders(String,
+ * boolean)} calls.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ReplaceApplicationIdPlaceholdersExecutableMain {
+  @Option(name = "--manifest", required = true)
+  private String manifest;
+
+  @Option(name = "--output", required = true)
+  private String output;
+
+  @Option(name = "--sanity-check-placeholders")
+  private boolean runSanityCheck;
+
+  public static void main(String[] args) throws IOException {
+    System.exit(runMain(args));
+  }
+
+  static int runMain(String[] args) throws IOException {
+    ReplaceApplicationIdPlaceholdersExecutableMain main =
+        new ReplaceApplicationIdPlaceholdersExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.execute();
+      return 0;
+    } catch (CmdLineException e) {
+      System.err.println(String.valueOf(e.getMessage()));
+      parser.printUsage(System.err);
+      return 1;
+    }
+  }
+
+  private void execute() throws IOException {
+    String currentManifest = Files.readString(Paths.get(manifest));
+    String updatedManifest =
+        GenerateManifest.replaceApplicationIdPlaceholders(currentManifest, runSanityCheck);
+    Files.writeString(Paths.get(output), updatedManifest);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+TRANSLATOR_SRCS = [
+    "ProguardMapping.java",
+    "ProguardTranslatorFactory.java",
+]
+
+buck_java_library(
+    name = "translator",
+    srcs = TRANSLATOR_SRCS,
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/ProguardMapping.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/ProguardMapping.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/ProguardMapping.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.proguard;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableMap;
+import java.util.Objects;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/** Parser for ProGuard-generated mapping files. Currently only handles class mapping. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ProguardMapping {
+
+  /** Utility class: do not instantiate. */
+  private ProguardMapping() {}
+
+  private static final Pattern CLASS_LINE_PATTERN = Pattern.compile("([-\\w.$]+) -> ([-\\w.$]+):");
+
+  public static ImmutableMap<String, String> readClassMapping(Iterable<String> lines) {
+    ImmutableMap.Builder<String, String> classMappingBuilder = ImmutableMap.builder();
+
+    for (String line : lines) {
+      if (line.charAt(0) == ' ') {
+        // This is a member mapping, which we don't handle yet.
+        continue;
+      }
+
+      Matcher matcher = CLASS_LINE_PATTERN.matcher(line);
+      if (!matcher.matches()) {
+        throw new IllegalArgumentException("Invalid line in proguard mapping: " + line);
+      }
+
+      classMappingBuilder.put(
+          Objects.requireNonNull(matcher.group(1)), Objects.requireNonNull(matcher.group(2)));
+    }
+
+    return classMappingBuilder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/ProguardTranslatorFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/ProguardTranslatorFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/proguard/ProguardTranslatorFactory.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.proguard;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Functions;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Function;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * If we end up creating both an obfuscator function and a deobfuscator function, it would be nice
+ * to load the proguard mapping file once. This class enables sharing that work.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ProguardTranslatorFactory {
+
+  private final Optional<ImmutableMap<String, String>> rawMap;
+
+  private ProguardTranslatorFactory(Optional<ImmutableMap<String, String>> rawMap) {
+    this.rawMap = rawMap;
+  }
+
+  public static ProguardTranslatorFactory create(
+      Optional<Path> proguardFullConfigFile,
+      Optional<Path> proguardMappingFile,
+      boolean skipProguard)
+      throws IOException {
+    return new ProguardTranslatorFactory(
+        loadOptionalRawMap(proguardFullConfigFile, proguardMappingFile, skipProguard));
+  }
+
+  @VisibleForTesting
+  public static ProguardTranslatorFactory createForTest(
+      Optional<ImmutableMap<String, String>> rawMap) {
+    return new ProguardTranslatorFactory(rawMap);
+  }
+
+  private static Optional<ImmutableMap<String, String>> loadOptionalRawMap(
+      Optional<Path> proguardFullConfigFile,
+      Optional<Path> proguardMappingFile,
+      boolean skipProguard)
+      throws IOException {
+    if (skipProguard || !proguardFullConfigFile.isPresent()) {
+      return Optional.empty();
+    }
+
+    Path pathToProguardConfig = proguardFullConfigFile.get();
+
+    // Proguard doesn't print a mapping when obfuscation is disabled.
+    boolean obfuscationSkipped =
+        Iterables.any(Files.readAllLines(pathToProguardConfig), "-dontobfuscate"::equals);
+    if (obfuscationSkipped) {
+      return Optional.empty();
+    }
+
+    Path mappingFile = proguardMappingFile.get();
+    List<String> lines = Files.readAllLines(mappingFile);
+    return Optional.of(ProguardMapping.readClassMapping(lines));
+  }
+
+  public Function<String, String> createDeobfuscationFunction() {
+    return createNonNullableFunction(false);
+  }
+
+  public Function<String, String> createObfuscationFunction() {
+    return createNonNullableFunction(true);
+  }
+
+  public Function<String, @Nullable String> createNullableObfuscationFunction() {
+    return createNullableFunction(true);
+  }
+
+  private Function<String, String> createNonNullableFunction(final boolean isForObfuscation) {
+    if (!rawMap.isPresent()) {
+      return Functions.identity();
+    }
+
+    Map<String, String> map = buildMap(isForObfuscation);
+
+    return input -> {
+      String mapped = map.get(input);
+      if (mapped != null) {
+        return mapped;
+      } else {
+        return input;
+      }
+    };
+  }
+
+  private Function<String, @Nullable String> createNullableFunction(
+      final boolean isForObfuscation) {
+    if (!rawMap.isPresent()) {
+      return input -> input;
+    }
+
+    Map<String, String> map = buildMap(isForObfuscation);
+
+    return input -> map.get(input);
+  }
+
+  private Map<String, String> buildMap(boolean isForObfuscation) {
+    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
+    for (Map.Entry<String, String> entry : rawMap.get().entrySet()) {
+      String original = entry.getKey().replace('.', '/');
+      String obfuscated = entry.getValue().replace('.', '/');
+      builder.put(
+          isForObfuscation ? original : obfuscated, isForObfuscation ? obfuscated : original);
+    }
+    return builder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/BUCK
@@ -0,0 +1,119 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+EXO_RESOURCES_REWRITER_SRCS = ["ExoResourcesRewriterExecutableMain.java"]
+
+MERGE_ANDROID_RESOURCES_SRCS = [
+    "MergeAndroidResources.java",
+    "MergeAndroidResourcesExecutableMain.java",
+]
+
+MERGE_ASSETS_SRCS = [
+    "MergeAssetsUtils.java",
+    "MergeAssetsExecutableMain.java",
+]
+
+buck_java_library(
+    name = "resources",
+    srcs = glob(
+        ["*.java"],
+        exclude = EXO_RESOURCES_REWRITER_SRCS + MERGE_ANDROID_RESOURCES_SRCS + MERGE_ASSETS_SRCS,
+    ),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
+
+buck_java_library(
+    name = "merge_android_resources",
+    srcs = MERGE_ANDROID_RESOURCES_SRCS,
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/aapt:r_dot_txt",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/util:throwing_print_writer",
+        "prelude//toolchains/android/src/com/facebook/buck/util/json:json",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
+
+buck_java_binary(
+    name = "merge_android_resources_binary",
+    main_class = "com.facebook.buck.android.resources.MergeAndroidResourcesExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":merge_android_resources",
+    ],
+)
+
+buck_java_library(
+    name = "merge_assets",
+    srcs = MERGE_ASSETS_SRCS,
+    java_version = "11",
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/apkmodule:apkmodule",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/util/json:json",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        ":resources",
+    ],
+)
+
+buck_java_binary(
+    name = "merge_assets_binary",
+    main_class = "com.facebook.buck.android.resources.MergeAssetsExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":merge_assets",
+    ],
+)
+
+buck_java_library(
+    name = "exo_resources_rewriter",
+    srcs = EXO_RESOURCES_REWRITER_SRCS,
+    java_version = "11",
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        ":resources",
+    ],
+)
+
+buck_java_binary(
+    name = "exo_resources_rewriter_binary",
+    main_class = "com.facebook.buck.android.resources.ExoResourcesRewriterExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":exo_resources_rewriter",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/BringToFrontMapper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/BringToFrontMapper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/BringToFrontMapper.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.nio.IntBuffer;
+import java.util.Map;
+import java.util.SortedSet;
+import java.util.stream.IntStream;
+
+/**
+ * BringToFrontMapper supports "bring-to-front" reassignment of reference ids. Given a set of ids,
+ * it will construct an assignment that ensures that those ids are the first ones for each type.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class BringToFrontMapper implements ReferenceMapper {
+  private final int packageId;
+  private final int[][] mapping;
+  private final int[][] rewriters;
+
+  public BringToFrontMapper(int packageId, int[][] mapping, int[][] rewriters) {
+    this.packageId = packageId;
+    this.mapping = mapping;
+    this.rewriters = rewriters;
+  }
+
+  /**
+   * Constructs a ReferenceMapper that will reassign ids and adjust offsets such that for each key
+   * in idsByType, the ids in idsByType will be reassigned to the first n ids of that type. The ids
+   * provided should not include package or type ids.
+   */
+  public static BringToFrontMapper construct(
+      int packageId, Map<Integer, SortedSet<Integer>> idsByType) {
+    int maxType = 0;
+    for (int k : idsByType.keySet()) {
+      maxType = Math.max(k, maxType);
+    }
+    int[][] mapping = new int[maxType + 1][];
+    int[][] rewriters = new int[maxType + 1][];
+
+    idsByType.forEach(
+        (type, idsSet) -> {
+          int maxRef = 0;
+          int[] ids = idsSet.stream().mapToInt(i -> i).toArray();
+          for (int id : ids) {
+            maxRef = Math.max(maxRef, id);
+          }
+          int[] newMapping = IntStream.range(0, maxRef + 1).toArray();
+          // rewrite() does swaps iterating forward through ids. Doing those swaps in reverse will
+          // give us a mapping of the new ids.
+          for (int i = ids.length - 1; i >= 0; i--) {
+            // Since ids is sorted, it's guaranteed that newMapping[i] == i;
+            int id = ids[i];
+            newMapping[i] = newMapping[id];
+            newMapping[id] = i;
+          }
+          mapping[type] = newMapping;
+          rewriters[type] = ids;
+        });
+    return new BringToFrontMapper(packageId, mapping, rewriters);
+  }
+
+  @Override
+  public int map(int id) {
+    if ((id >> 24) != packageId) {
+      return id;
+    }
+    int type = (id >> 16) & 0xFF;
+    if (type < mapping.length) {
+      int[] typeMapping = mapping[type];
+      if (typeMapping == null) {
+        return id;
+      }
+      int entry = id & 0xFFFF;
+      if (entry < typeMapping.length) {
+        return (id & 0xFFFF0000) | typeMapping[entry];
+      }
+    }
+    return id;
+  }
+
+  @Override
+  public void rewrite(int type, IntBuffer buf) {
+    if (type < rewriters.length) {
+      int[] rewriter = rewriters[type];
+      if (rewriter != null) {
+        for (int i = 0; i < rewriter.length; i++) {
+          int id = rewriter[i];
+          // Swap the values at the old and new positions.
+          int temp = buf.get(id);
+          buf.put(id, buf.get(i));
+          buf.put(i, temp);
+        }
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ExoResourcesRewriter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ExoResourcesRewriter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ExoResourcesRewriter.java
@@ -0,0 +1,505 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.file.MostFiles;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.util.MoreSuppliers;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedMap;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Ordering;
+import com.google.common.io.ByteStreams;
+import java.io.ByteArrayInputStream;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import java.util.zip.CRC32;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import javax.annotation.Nullable;
+
+/**
+ * ExoResourceRewriter is the core of constructing build outputs for exo-for-resources.
+ *
+ * <p>Some background: Android's resources are packaged into the APK primarily in the resources.arsc
+ * file with some references out to other files in the APK's res/ directory (.png/.xml mostly). The
+ * resources.arsc file is a binary file in a format that isn't really well documented, but you can
+ * get a good idea of its structure by looking at ResourceTable and other classes in this package.
+ * At runtime, Android constructs an AssetManager from the APK and resource lookups go through that.
+ * While this is primarily done for an app's own resources, the framework may construct one to
+ * access an app's resources directly (e.g. for driving animations, for intent pickers, etc) and
+ * apps can access resources of other apps (e.g. a launcher app will access names/icons).
+ *
+ * <p>For exo-for-resources, we determine a minimal set of resources (including referenced files)
+ * that need to be in the main APK. This set includes all resources referenced from the
+ * AndroidManifest.xml or from any animation. We construct a resources.arsc for these resources and
+ * then the primary apk includes those resources. To avoid odd issues, we rewrite the full
+ * resources.arsc and all compiled .xml files such that references match between the primary apk and
+ * the exo resources (and without this, we have run into issues).
+ *
+ * <p>For assets, we don't package any into the main apk. For exo resources, assets are put into a
+ * separate zip from the exo .arsc (and resource files).
+ *
+ * <p>TODO(cjhopman): The underlying c++ resource handling supports some things that we should take
+ * advantage of. First, we are able to easily have multiple resource apks (including multiple .arsc
+ * with the same package id) as long as we don't have the same package-id/type-id pair in different
+ * .arsc files. Second, there's no restriction that all resources of the same type actually have the
+ * same type id (e.g. we could have strings with type id 0x01, 0x02, and 0x03). I'm pretty sure that
+ * aapt's --feature-of/--feature-after work by using different type ids for the same type.
+ *
+ * <p>Using these, we should be able to split resources across some larger number of .zips in such a
+ * way that users will typically only need to install a small number of resources (for example, in a
+ * particular large app that I've looked at, a vast majority of resource size is spent on just the
+ * 'strings' type). It's probably also possible for us to construct multiple top-level aapt targets
+ * that handle smaller subsets of the resources (e.g. construct a separate 'strings' top-level aapt
+ * rule). While it would be hard to construct multiple aapt rules for a particular type (adding
+ * restrictions on resource overriding would make it easier) we could still easily split a
+ * particular type into multiple exo resources zips (using different type ids).
+ *
+ * <p>It might be possible to get even more ids to work by using a different package id (other than
+ * 0x7f). I believe the package id space is partitioned like so:
+ *
+ * <ul>
+ *   <li>0x01- framework
+ *   <li>0x02 - 0x7f - potentially any of these are used by OEM overlays. OEM overlays, just like
+ *       the framework, will be loaded into the zygote.
+ *   <li>0x7f - the app
+ *   <li>0x80 and above - (KK+) dynamically loaded resource libraries (like GMS and WebView
+ *       resources), some of these get loaded after your process starts by the framework code that
+ *       processes your apps AndroidManifest, the WebView resources get loaded at runtime, the first
+ *       time you new up a WebView instance.
+ * </ul>
+ *
+ * <p>As the normal Android build system doesn't use anything other than 0x7f, and that's always
+ * been the only package id used by applications, and that we have some leeway in the type id space,
+ * I didn't think it was worth it now to further investigate the feasibility/difficulty of using
+ * different package ids.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ExoResourcesRewriter {
+  private ExoResourcesRewriter() {}
+
+  public static void rewrite(
+      AbsPath ruleCellRoot,
+      RelPath inputPath,
+      RelPath inputRDotTxt,
+      RelPath primaryResources,
+      Path exoResources,
+      RelPath outputRDotTxt)
+      throws IOException {
+    ReferenceMapper resMapping =
+        rewriteResources(ruleCellRoot, inputPath, primaryResources, exoResources);
+    rewriteRDotTxt(ruleCellRoot, resMapping, inputRDotTxt, outputRDotTxt);
+  }
+
+  static ReferenceMapper rewriteResources(
+      AbsPath ruleCellRoot, RelPath inputPath, RelPath primaryResources, Path exoResources)
+      throws IOException {
+    try (ApkZip apkZip =
+        new ApkZip(ProjectFilesystemUtils.getAbsPathForRelativePath(ruleCellRoot, inputPath))) {
+      UsedResourcesFinder.ResourceClosure closure =
+          UsedResourcesFinder.computePrimaryApkClosure(apkZip);
+      ReferenceMapper resMapping =
+          BringToFrontMapper.construct(ResTablePackage.APP_PACKAGE_ID, closure.idsByType);
+      // Rewrite the arsc.
+      apkZip.getResourceTable().reassignIds(resMapping);
+      // Update the references in xml files.
+      for (ResourcesXml xml : apkZip.getResourcesXmls()) {
+        xml.transformReferences(resMapping::map);
+      }
+      // Write the full (rearranged) resources to the exo resources.
+      try (ResourcesZipBuilder zipBuilder = new ResourcesZipBuilder(exoResources)) {
+        for (ZipEntry entry : apkZip.getEntries()) {
+          addEntryWithRawPassThrough(zipBuilder, apkZip, entry, COMPRESSION_LEVEL);
+        }
+      }
+      // Then, slice out the resources needed for the primary apk.
+      try (ResourcesZipBuilder zipBuilder =
+          new ResourcesZipBuilder(
+              ProjectFilesystemUtils.getPathForRelativePath(ruleCellRoot, primaryResources))) {
+        ResourceTable primaryResourceTable =
+            ResourceTable.slice(
+                apkZip.getResourceTable(),
+                ImmutableMap.copyOf(Maps.transformValues(closure.idsByType, Set::size)));
+        addEntry(
+            zipBuilder,
+            "resources.arsc",
+            primaryResourceTable.serialize(),
+            apkZip.getEntry("resources.arsc").getMethod() == ZipEntry.STORED
+                ? 0
+                : COMPRESSION_LEVEL,
+            false);
+        for (String path : closure.files.stream().sorted().collect(Collectors.toList())) {
+          ZipEntry entry = apkZip.getEntry(path);
+          addEntryWithRawPassThrough(zipBuilder, apkZip, entry, COMPRESSION_LEVEL);
+        }
+      }
+      return resMapping;
+    }
+  }
+
+  static void rewriteRDotTxt(
+      AbsPath ruleCellRoot,
+      ReferenceMapper refMapping,
+      RelPath inputRDotTxt,
+      RelPath outputRDotTxt) {
+    Map<String, String> cache = new HashMap<>();
+    Function<String, String> mapping =
+        (s) ->
+            cache.computeIfAbsent(
+                s, (k) -> String.format("0x%x", refMapping.map(Integer.parseInt(k, 16))));
+    try {
+      List<String> lines =
+          Files.readAllLines(
+              ProjectFilesystemUtils.getPathForRelativePath(ruleCellRoot, inputRDotTxt),
+              StandardCharsets.UTF_8);
+      List<String> mappedLines = new ArrayList<>(lines.size());
+      Pattern regular = Pattern.compile("int ([^ ]*) ([^ ]*) 0x(7f[0-9a-f]{6})");
+      Pattern styleable = Pattern.compile("int\\[] (styleable) ([^ ]*) \\{(.*) }");
+      Pattern index = Pattern.compile("int (styleable) ([^ ]*) ([0-9]*)");
+      Pattern number = Pattern.compile("0x([0-9a-f]{8})");
+
+      Iterator<String> iter = lines.iterator();
+      while (iter.hasNext()) {
+        String line = iter.next();
+        Matcher reg = regular.matcher(line);
+        if (reg.matches()) {
+          String newId = mapping.apply(Objects.requireNonNull(reg.group(3)));
+          mappedLines.add(String.format("int %s %s %s", reg.group(1), reg.group(2), newId));
+          continue;
+        }
+        Matcher stMatcher = styleable.matcher(line);
+        if (!stMatcher.matches()) {
+          throw new RuntimeException("Unmatched: " + line);
+        }
+        String values = stMatcher.group(3);
+        ArrayList<String> ids = new ArrayList<>();
+        Matcher m = number.matcher(Objects.requireNonNull(values));
+        while (m.find()) {
+          String id = mapping.apply(Objects.requireNonNull(m.group(1)));
+          ids.add(id);
+        }
+        Map<String, Integer> newIndex = new HashMap<>();
+        List<String> sortedIds = ids.stream().sorted().collect(Collectors.toList());
+        for (int i = 0; i < sortedIds.size(); i++) {
+          newIndex.put(sortedIds.get(i), i);
+        }
+        StringBuilder valuesBuilder = new StringBuilder();
+        String prefix = "";
+        for (String id : sortedIds) {
+          valuesBuilder.append(prefix);
+          valuesBuilder.append(id);
+          prefix = ", ";
+        }
+        mappedLines.add(
+            String.format(
+                "int[] styleable %s { %s }", stMatcher.group(2), valuesBuilder.toString()));
+        for (int i = 0; i < ids.size(); i++) {
+          line = iter.next();
+          m = index.matcher(line);
+          if (!m.matches()) {
+            throw new RuntimeException("Unmatched: " + line);
+          }
+          int idx = Integer.parseInt(Objects.requireNonNull(m.group(3)));
+          int newIdx = Objects.requireNonNull(newIndex.get(ids.get(idx)));
+          mappedLines.add(String.format("int styleable %s %d", m.group(2), newIdx));
+        }
+      }
+      MostFiles.writeLinesToFile(
+          mappedLines, ProjectFilesystemUtils.getPathForRelativePath(ruleCellRoot, outputRDotTxt));
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  // DEFAULT_COMPRESSION (-1) is not accepted by CustomZipEntry.setCompressionLevel(), so use the
+  // JDK's actual default level.
+  private static final int COMPRESSION_LEVEL = 6;
+
+  private static void addEntry(
+      ResourcesZipBuilder zipBuilder,
+      String name,
+      byte[] content,
+      int compressionLevel,
+      boolean isDirectory)
+      throws IOException {
+    // TODO(cjhopman): for files that we don't already have in memory, we should use the builder's
+    // stream api.
+    CRC32 crc32 = new CRC32();
+    crc32.update(content);
+    zipBuilder.addEntry(
+        new ByteArrayInputStream(content),
+        content.length,
+        crc32.getValue(),
+        name,
+        compressionLevel,
+        isDirectory);
+  }
+
+  private static void addEntryWithRawPassThrough(
+      ResourcesZipBuilder zipBuilder, ApkZip apkZip, ZipEntry entry, int compressionLevel)
+      throws IOException {
+    if (!apkZip.isModifiedEntry(entry.getName())
+        && entry.getMethod() == ZipEntry.DEFLATED
+        && entry.getCompressedSize() >= 0) {
+      byte[] rawBytes = apkZip.readRawCompressedBytes(entry);
+      zipBuilder.addRawEntry(
+          new ByteArrayInputStream(rawBytes),
+          rawBytes.length,
+          entry.getSize(),
+          entry.getCrc(),
+          entry.getMethod(),
+          entry.getName());
+    } else {
+      addEntry(
+          zipBuilder,
+          entry.getName(),
+          apkZip.getContent(entry.getName()),
+          entry.getMethod() == ZipEntry.STORED ? 0 : compressionLevel,
+          false);
+    }
+  }
+
+  private static class ApkZip implements Closeable, UsedResourcesFinder.ApkContentProvider {
+    private final ZipFile zipFile;
+    private final AbsPath inputPath;
+    private final SortedMap<String, ZipEntry> entries;
+    private final Map<String, ResourcesXml> xmlEntries;
+    private final Supplier<ResourceTable> resourceTable;
+    private @Nullable RandomAccessFile randomAccessFile;
+
+    public ApkZip(AbsPath inputPath) throws IOException {
+      this.inputPath = inputPath;
+      this.zipFile = new ZipFile(inputPath.toFile());
+      this.entries =
+          Collections.list(zipFile.entries()).stream()
+              .collect(
+                  ImmutableSortedMap.toImmutableSortedMap(
+                      Ordering.natural(), ZipEntry::getName, e -> e));
+      this.xmlEntries = new HashMap<>();
+      byte[] arscBytes = readEntryBytes("resources.arsc");
+      this.resourceTable = MoreSuppliers.memoize(() -> ResourceTable.get(ResChunk.wrap(arscBytes)));
+    }
+
+    @Override
+    public ResourceTable getResourceTable() {
+      return resourceTable.get();
+    }
+
+    @Override
+    public ResourcesXml getXml(String path) {
+      return xmlEntries.computeIfAbsent(path, this::extractXml);
+    }
+
+    @Override
+    public boolean hasFile(String path) {
+      return entries.containsKey(path);
+    }
+
+    @Override
+    public void close() throws IOException {
+      zipFile.close();
+      if (randomAccessFile != null) {
+        randomAccessFile.close();
+      }
+    }
+
+    public Iterable<ZipEntry> getEntries() {
+      return entries.values();
+    }
+
+    public ZipEntry getEntry(String path) {
+      return Objects.requireNonNull(entries.get(path));
+    }
+
+    Iterable<ResourcesXml> getResourcesXmls() {
+      return entries.keySet().stream()
+          .filter(
+              name ->
+                  name.equals("AndroidManifest.xml")
+                      || ((name.startsWith("res")
+                          && !name.startsWith("res/raw")
+                          && name.endsWith(".xml"))))
+          .map(this::getXml)
+          .collect(ImmutableList.toImmutableList());
+    }
+
+    byte[] getContent(String path) {
+      if (path.equals("resources.arsc")) {
+        return resourceTable.get().serialize();
+      }
+      ResourcesXml xml = xmlEntries.get(path);
+      if (xml != null) {
+        return xml.serialize();
+      }
+      return readEntryBytes(path);
+    }
+
+    private byte[] readEntryBytes(String path) {
+      try {
+        return ByteStreams.toByteArray(
+            Objects.requireNonNull(
+                zipFile.getInputStream(Objects.requireNonNull(entries.get(path)))));
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    private ResourcesXml extractXml(String path) {
+      try {
+        return ResourcesXml.get(ResChunk.wrap(readEntryBytes(path)));
+      } catch (Exception e) {
+        throw new RuntimeException("When extracting " + path, e);
+      }
+    }
+
+    /** Returns true if this entry was modified by the rewrite and needs recompression. */
+    boolean isModifiedEntry(String name) {
+      return name.equals("resources.arsc") || xmlEntries.containsKey(name);
+    }
+
+    /**
+     * Reads the raw compressed bytes for a zip entry directly from the file, bypassing
+     * decompression. This is used for pass-through entries that don't need modification.
+     */
+    byte[] readRawCompressedBytes(ZipEntry entry) throws IOException {
+      long compressedSize = entry.getCompressedSize();
+      if (compressedSize < 0 || entry.getMethod() == ZipEntry.STORED) {
+        // STORED entries don't benefit from raw copy; just read normally.
+        return readEntryBytes(entry.getName());
+      }
+
+      Map<String, Long> offsets = getLocalHeaderOffsets();
+      Long localHeaderOffset = offsets.get(entry.getName());
+      if (localHeaderOffset == null) {
+        throw new IOException(
+            "No local header offset found for entry: "
+                + entry.getName()
+                + ". The zip central directory may be corrupt or use ZIP64 extensions.");
+      }
+
+      RandomAccessFile raf = getRandomAccessFile();
+      // Local file header: 30 bytes fixed + nameLen + extraLen
+      raf.seek(localHeaderOffset + 26); // offset to name length field
+      int nameLen = readShortLE(raf);
+      int extraLen = readShortLE(raf);
+      long dataOffset = localHeaderOffset + 30 + nameLen + extraLen;
+
+      byte[] rawBytes = new byte[(int) compressedSize];
+      raf.seek(dataOffset);
+      raf.readFully(rawBytes);
+      return rawBytes;
+    }
+
+    private RandomAccessFile getRandomAccessFile() throws IOException {
+      if (randomAccessFile == null) {
+        randomAccessFile = new RandomAccessFile(inputPath.toFile(), "r");
+      }
+      return randomAccessFile;
+    }
+
+    private Map<String, Long> localHeaderOffsets;
+
+    /**
+     * Lazily parses the central directory to build a map of entry name → local header offset.
+     *
+     * <p>NOTE: This parser does not handle ZIP64 extensions. If the APK has more than 65,535
+     * entries or is larger than 4 GB, the EOCD64 locator would be at a different position and this
+     * parser will fail to find entries. Android APKs are currently well under these limits.
+     */
+    private Map<String, Long> getLocalHeaderOffsets() throws IOException {
+      if (localHeaderOffsets != null) {
+        return localHeaderOffsets;
+      }
+      localHeaderOffsets = new HashMap<>();
+      RandomAccessFile raf = getRandomAccessFile();
+      // Find End of Central Directory Record (EOCD)
+      long fileLen = raf.length();
+      long searchStart = Math.max(0, fileLen - 65557);
+      byte[] searchBuf = new byte[(int) (fileLen - searchStart)];
+      raf.seek(searchStart);
+      raf.readFully(searchBuf);
+
+      int eocdOffset = -1;
+      for (int i = searchBuf.length - 22; i >= 0; i--) {
+        if (searchBuf[i] == 0x50
+            && searchBuf[i + 1] == 0x4b
+            && searchBuf[i + 2] == 0x05
+            && searchBuf[i + 3] == 0x06) {
+          eocdOffset = i;
+          break;
+        }
+      }
+      if (eocdOffset < 0) {
+        return localHeaderOffsets;
+      }
+
+      long cdOffset =
+          (searchBuf[eocdOffset + 16] & 0xFFL)
+              | ((searchBuf[eocdOffset + 17] & 0xFFL) << 8)
+              | ((searchBuf[eocdOffset + 18] & 0xFFL) << 16)
+              | ((searchBuf[eocdOffset + 19] & 0xFFL) << 24);
+
+      // Parse central directory
+      raf.seek(cdOffset);
+      byte[] header = new byte[46];
+      while (true) {
+        if (raf.read(header, 0, 4) < 4) break;
+        if (header[0] != 0x50 || header[1] != 0x4b || header[2] != 0x01 || header[3] != 0x02) {
+          break;
+        }
+        raf.readFully(header, 4, 42);
+        int nameLen = (header[28] & 0xFF) | ((header[29] & 0xFF) << 8);
+        int extraLen = (header[30] & 0xFF) | ((header[31] & 0xFF) << 8);
+        int commentLen = (header[32] & 0xFF) | ((header[33] & 0xFF) << 8);
+        long localOffset =
+            (header[42] & 0xFFL)
+                | ((header[43] & 0xFFL) << 8)
+                | ((header[44] & 0xFFL) << 16)
+                | ((header[45] & 0xFFL) << 24);
+
+        byte[] nameBytes = new byte[nameLen];
+        raf.readFully(nameBytes);
+        localHeaderOffsets.put(new String(nameBytes, StandardCharsets.UTF_8), localOffset);
+        raf.skipBytes(extraLen + commentLen);
+      }
+      return localHeaderOffsets;
+    }
+
+    private static int readShortLE(RandomAccessFile raf) throws IOException {
+      int b0 = raf.read();
+      int b1 = raf.read();
+      return (b0 & 0xFF) | ((b1 & 0xFF) << 8);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ExoResourcesRewriterExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ExoResourcesRewriterExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ExoResourcesRewriterExecutableMain.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for executing {@link ExoResourcesRewriter} calls. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ExoResourcesRewriterExecutableMain {
+  @Option(name = "--original-r-dot-txt", required = true)
+  private String originalRDotTxt;
+
+  @Option(name = "--new-r-dot-txt", required = true)
+  private String newRDotTxt;
+
+  @Option(name = "--original-primary-apk-resources", required = true)
+  private String originalPrimaryApkResources;
+
+  @Option(name = "--new-primary-apk-resources", required = true)
+  private String newPrimaryApkResources;
+
+  @Option(name = "--exo-resources", required = true)
+  private String exoResources;
+
+  @Option(name = "--exo-resources-hash", required = true)
+  private String exoResourcesHash;
+
+  public static void main(String[] args) throws IOException {
+    ExoResourcesRewriterExecutableMain main = new ExoResourcesRewriterExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    AbsPath root = AbsPath.of(Paths.get(".").normalize().toAbsolutePath());
+
+    ExoResourcesRewriter.rewrite(
+        root,
+        RelPath.get(originalPrimaryApkResources),
+        RelPath.get(originalRDotTxt),
+        RelPath.get(newPrimaryApkResources),
+        Paths.get(exoResources),
+        RelPath.get(newRDotTxt));
+
+    Files.writeString(
+        Paths.get(exoResourcesHash),
+        com.google.common.io.Files.hash(Paths.get(exoResources).toFile(), Hashing.sha1())
+            .toString());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAndroidResources.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAndroidResources.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAndroidResources.java
@@ -0,0 +1,428 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.buck.android.aapt.RDotTxtEntry;
+import com.facebook.buck.android.aapt.RDotTxtEntry.RType;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.util.ThrowingPrintWriter;
+import com.facebook.buck.util.json.ObjectMappers;
+import com.facebook.infer.annotation.Nullsafe;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSetMultimap;
+import com.google.common.collect.SetMultimap;
+import com.google.common.collect.Sets;
+import com.google.common.collect.SortedSetMultimap;
+import com.google.common.collect.TreeMultimap;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class MergeAndroidResources {
+  private static final Logger LOG = Logger.get(MergeAndroidResources.class);
+
+  /**
+   * Merges text symbols files from {@code aapt} for each of the input {@code android_resource} into
+   * a set of resources per R.java package and writes an {@code R.java} file per package under the
+   * output directory. Also, if {@code uberRDotTxt} is present, the IDs in the output {@code R.java}
+   * file will be taken from the {@code R.txt} file.
+   */
+  public static void mergeAndroidResources(
+      ImmutableList<Path> uberRDotTxt,
+      ImmutableMap<Path, String> symbolsFileToRDotJavaPackage,
+      ImmutableMap<Path, String> symbolsFileToResourceDeps,
+      boolean forceFinalResourceIds,
+      EnumSet<RType> bannedDuplicateResourceTypes,
+      Optional<Path> duplicateResourceWhitelistPath,
+      ImmutableList<Path> overrideSymbolsPath,
+      Path outputDir,
+      Optional<Path> stringsOutputDir,
+      Optional<Path> idsOutputDir,
+      ImmutableSet<String> referencedResources)
+      throws DuplicateResourceException, IOException {
+    // In order to convert a symbols file to R.java, all resources of the same type are grouped
+    // into a static class of that name. The static class contains static values that correspond
+    // to the resource (type, name, value) tuples. See RDotTxtEntry.
+    //
+    // The first step is to merge symbol files of the same package type and resource type/name.
+    // That is, within a package type, each resource type/name pair must be unique. If there are
+    // multiple pairs, only one will be written to the R.java file.
+    //
+    // Because the resulting files do not match their respective resources.arsc, the values are
+    // meaningless and do not represent the usable final result.  This is why the R.java file is
+    // written without using final so that javac will not inline the values.
+    Optional<ImmutableMap<RDotTxtEntry, String>> uberRDotTxtIds;
+    if (uberRDotTxt.isEmpty()) {
+      uberRDotTxtIds = Optional.empty();
+    } else {
+      // re-assign Ids
+      ImmutableSet.Builder<RDotTxtEntry> uberRdotTxtEntries = ImmutableSet.builder();
+      uberRDotTxt.forEach(
+          rDot -> {
+            try {
+              readResources(rDot).forEach(uberRdotTxtEntries::add);
+            } catch (IOException e) {
+              throw new RuntimeException(e);
+            }
+          });
+      uberRDotTxtIds =
+          Optional.of(
+              uberRdotTxtEntries.build().stream()
+                  .collect(ImmutableMap.toImmutableMap(input -> input, input -> input.idValue)));
+    }
+
+    Optional<SetMultimap<String, RDotTxtEntry>> overrideSymbols =
+        loadOverrideSymbols(overrideSymbolsPath);
+
+    ImmutableSet<String> duplicateResourceWhitelist =
+        (duplicateResourceWhitelistPath.isPresent())
+            ? ImmutableSet.copyOf(Files.readAllLines(duplicateResourceWhitelistPath.get()))
+            : ImmutableSet.of();
+
+    SortedSetMultimap<String, RDotTxtEntry> rDotJavaPackageToResources =
+        sortSymbols(
+            symbolsFileToRDotJavaPackage,
+            uberRDotTxtIds,
+            symbolsFileToResourceDeps,
+            overrideSymbols,
+            bannedDuplicateResourceTypes,
+            duplicateResourceWhitelist);
+
+    ImmutableSet.Builder<String> requiredPackages = ImmutableSet.builder();
+
+    requiredPackages.addAll(symbolsFileToRDotJavaPackage.values());
+
+    Preconditions.checkState(
+        stringsOutputDir.isPresent() == idsOutputDir.isPresent(),
+        "Expect either both stringOutputDir and idsOutputDir, or neither");
+    boolean hasStringsAndIdsOutputDir = stringsOutputDir.isPresent();
+
+    Set<String> emptyPackages;
+    if (hasStringsAndIdsOutputDir) {
+      SortedSetMultimap<String, RDotTxtEntry> otherRDotJavaPackageToResources =
+          TreeMultimap.create();
+      SortedSetMultimap<String, RDotTxtEntry> stringsRDotJavaPackageToResources =
+          TreeMultimap.create();
+      SortedSetMultimap<String, RDotTxtEntry> idsRDotJavaPackageToResources = TreeMultimap.create();
+      for (Entry<String, RDotTxtEntry> entry : rDotJavaPackageToResources.entries()) {
+        RType resourceType = entry.getValue().type;
+        if (resourceType.equals(RType.STRING)) {
+          stringsRDotJavaPackageToResources.put(entry.getKey(), entry.getValue());
+        } else if (resourceType.equals(RType.ID)) {
+          idsRDotJavaPackageToResources.put(entry.getKey(), entry.getValue());
+        } else {
+          otherRDotJavaPackageToResources.put(entry.getKey(), entry.getValue());
+        }
+      }
+
+      writePerPackageRDotJava(
+          outputDir, otherRDotJavaPackageToResources, forceFinalResourceIds, referencedResources);
+      writePerPackageRDotJava(
+          stringsOutputDir.get(),
+          stringsRDotJavaPackageToResources,
+          forceFinalResourceIds,
+          referencedResources);
+      writePerPackageRDotJava(
+          idsOutputDir.get(),
+          idsRDotJavaPackageToResources,
+          forceFinalResourceIds,
+          referencedResources);
+      emptyPackages =
+          Sets.difference(requiredPackages.build(), otherRDotJavaPackageToResources.keySet());
+    } else {
+      Preconditions.checkState(referencedResources.isEmpty());
+      writePerPackageRDotJava(
+          outputDir, rDotJavaPackageToResources, forceFinalResourceIds, referencedResources);
+      emptyPackages =
+          Sets.difference(requiredPackages.build(), rDotJavaPackageToResources.keySet());
+    }
+
+    if (!emptyPackages.isEmpty()) {
+      writeEmptyRDotJavaForPackages(outputDir, emptyPackages);
+    }
+  }
+
+  /**
+   * Read resource IDs from a R.txt file and add them to a list of entries
+   *
+   * @param rDotTxt the path to the R.txt file to read
+   * @return a list of RDotTxtEntry objects read from the file
+   * @throws IOException
+   */
+  private static List<RDotTxtEntry> readResources(Path rDotTxt) throws IOException {
+    return Files.readAllLines(rDotTxt).stream()
+        .filter(input -> !Strings.isNullOrEmpty(input))
+        .map(RDotTxtEntry.TO_ENTRY)
+        .collect(Collectors.toList());
+  }
+
+  private static Optional<SetMultimap<String, RDotTxtEntry>> loadOverrideSymbols(
+      Iterable<Path> paths) throws IOException {
+    ImmutableSetMultimap.Builder<String, RDotTxtEntry> symbolsBuilder =
+        ImmutableSetMultimap.builder();
+    for (Path path : paths) {
+      if (!Files.isRegularFile(path)) {
+        LOG.info("Override-symbols file %s is not present or not regular.  Skipping.", path);
+        continue;
+      }
+      JsonNode jsonData = ObjectMappers.READER.readTree(ObjectMappers.createParser(path));
+      for (String packageName : (Iterable<String>) jsonData::fieldNames) {
+        Iterator<JsonNode> rDotTxtLines =
+            Objects.requireNonNull(jsonData.get(packageName)).elements();
+        while (rDotTxtLines.hasNext()) {
+          String rDotTxtLine = rDotTxtLines.next().asText();
+          symbolsBuilder.put(packageName, parseEntryOrThrow(rDotTxtLine));
+        }
+      }
+    }
+    return Optional.of(symbolsBuilder.build());
+  }
+
+  private static void writeEmptyRDotJavaForPackages(Path outputDir, Set<String> rDotJavaPackages)
+      throws IOException {
+    for (String rDotJavaPackage : rDotJavaPackages) {
+      Path outputFile = getPathToRDotJava(outputDir, rDotJavaPackage);
+      Files.createDirectories(Objects.requireNonNull(outputFile.getParent()));
+      Files.write(
+          outputFile,
+          String.format("package %s;\n\npublic class R {}\n", rDotJavaPackage)
+              .getBytes(StandardCharsets.UTF_8));
+    }
+  }
+
+  private static void writePerPackageRDotJava(
+      Path outputDir,
+      SortedSetMultimap<String, RDotTxtEntry> packageToResources,
+      boolean forceFinalResourceIds,
+      ImmutableSet<String> referencedResources)
+      throws IOException {
+    Files.createDirectories(outputDir);
+    for (String rDotJavaPackage : packageToResources.keySet()) {
+      Path outputFile = getPathToRDotJava(outputDir, rDotJavaPackage);
+      Files.createDirectories(Objects.requireNonNull(outputFile.getParent()));
+      try (ThrowingPrintWriter writer =
+          new ThrowingPrintWriter(new FileOutputStream(outputFile.toFile()))) {
+        writer.format("package %s;\n\n", rDotJavaPackage);
+        writer.write("public class R {\n");
+
+        RType lastType = null;
+
+        for (RDotTxtEntry res : packageToResources.get(rDotJavaPackage)) {
+          boolean isUsed =
+              referencedResources.isEmpty()
+                  || referencedResources.contains(rDotJavaPackage + "." + res.name);
+          if (isUsed) {
+            RType type = res.type;
+            if (!Objects.equals(type, lastType)) {
+              // If the previous type needs to be closed, close it.
+              if (lastType != null) {
+                writer.println("  }\n");
+              }
+
+              // Now start the block for the new type.
+              writer.format("  public static class %s {\n", type);
+              lastType = type;
+            }
+
+            // Write out the resource.
+            // Write as an int.
+            writer.format(
+                "    public static%s%s %s=%s;\n",
+                forceFinalResourceIds ? " final " : " ", res.idType, res.name, res.idValue);
+          }
+        }
+
+        // If some type was written (e.g., the for loop was entered), then the last type needs to be
+        // closed.
+        if (lastType != null) {
+          writer.println("  }\n");
+        }
+
+        // Close the class definition.
+        writer.println("}");
+      }
+    }
+  }
+
+  @VisibleForTesting
+  public static SortedSetMultimap<String, RDotTxtEntry> sortSymbols(
+      Map<Path, String> symbolsFileToRDotJavaPackage,
+      Optional<ImmutableMap<RDotTxtEntry, String>> uberRDotTxtIds,
+      ImmutableMap<Path, String> symbolsFileToResourceDeps,
+      Optional<SetMultimap<String, RDotTxtEntry>> overrides,
+      EnumSet<RType> bannedDuplicateResourceTypes,
+      Set<String> duplicateResourceWhitelist)
+      throws DuplicateResourceException {
+    Map<RDotTxtEntry, String> finalIds = null;
+    if (uberRDotTxtIds.isPresent()) {
+      finalIds = uberRDotTxtIds.get();
+    }
+
+    SortedSetMultimap<String, RDotTxtEntry> rDotJavaPackageToSymbolsFiles = TreeMultimap.create();
+    SortedSetMultimap<RDotTxtEntry, Path> bannedDuplicateResourceToSymbolsFiles =
+        TreeMultimap.create();
+
+    // Expand the package overrides into per-package self-maps.
+    // The self-maps are basically sets, but we need to be able to look up
+    // the actual RDotTxtEntry objects to get their ids (which are not included in .equals()).
+    Map<String, Map<RDotTxtEntry, RDotTxtEntry>> expandedPackageOverrides = ImmutableMap.of();
+    if (overrides.isPresent()) {
+      expandedPackageOverrides = new HashMap<>();
+      Map<String, Map<RDotTxtEntry, RDotTxtEntry>> ovr = expandedPackageOverrides;
+      overrides
+          .get()
+          .asMap()
+          .forEach(
+              (pkg, entries) ->
+                  ovr.put(pkg, entries.stream().collect(Collectors.toMap(k -> k, v -> v))));
+    }
+
+    for (Entry<Path, String> entry : symbolsFileToRDotJavaPackage.entrySet()) {
+      Path symbolsFile = entry.getKey();
+      // Read the symbols file and parse each line as a Resource.
+      List<RDotTxtEntry> linesInSymbolsFile;
+      try {
+        linesInSymbolsFile =
+            Files.readAllLines(symbolsFile).stream()
+                .filter(input -> !Strings.isNullOrEmpty(input))
+                .map(MergeAndroidResources::parseEntryOrThrow)
+                .collect(Collectors.toList());
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+
+      String packageName = entry.getValue();
+      Map<RDotTxtEntry, RDotTxtEntry> packageOverrides =
+          expandedPackageOverrides.getOrDefault(packageName, ImmutableMap.of());
+
+      if (!packageOverrides.isEmpty()) {
+        // RDotTxtEntry computes hash codes and checks equality only based on type and name,
+        // so we can use simple map lookup to find the overridden resource entry.
+        for (int i = 0; i < linesInSymbolsFile.size(); i++) {
+          RDotTxtEntry mappedEntry = packageOverrides.get(linesInSymbolsFile.get(i));
+          if (mappedEntry != null) {
+            linesInSymbolsFile.set(i, mappedEntry);
+          }
+        }
+      }
+
+      for (int index = 0; index < linesInSymbolsFile.size(); index++) {
+        RDotTxtEntry resource = linesInSymbolsFile.get(index);
+
+        if (uberRDotTxtIds.isPresent()) {
+          // TODO(natthu): Make this a hard error once we fix fbandroid and remove all unreferenced
+          // non-english strings.
+          Objects.requireNonNull(finalIds);
+          if (!finalIds.containsKey(resource)) {
+            LOG.debug("Cannot find resource '%s' in the uber R.txt.", resource);
+            continue;
+          }
+          resource = resource.copyWithNewIdValue(finalIds.get(resource));
+        }
+
+        if (bannedDuplicateResourceTypes.contains(resource.type)) {
+          bannedDuplicateResourceToSymbolsFiles.put(resource, symbolsFile);
+        }
+        rDotJavaPackageToSymbolsFiles.put(packageName, resource);
+      }
+    }
+
+    // Find any "overridden" resources that were actually new resources and add them.
+    Map<RDotTxtEntry, String> finalFinalIds = finalIds;
+    overrides.ifPresent(
+        ovr ->
+            ovr.forEach(
+                (pkg, resource) -> {
+                  Objects.requireNonNull(finalFinalIds);
+                  if (!rDotJavaPackageToSymbolsFiles.containsEntry(pkg, resource)) {
+                    String realId = finalFinalIds.get(resource);
+                    Preconditions.checkState(
+                        realId != null,
+                        "ID for resource created by filtering is not present in R.txt: %s",
+                        resource);
+                    rDotJavaPackageToSymbolsFiles.put(pkg, resource.copyWithNewIdValue(realId));
+                  }
+                }));
+
+    StringBuilder duplicateResourcesMessage = new StringBuilder();
+    for (Entry<RDotTxtEntry, Collection<Path>> resourceAndSymbolsFiles :
+        bannedDuplicateResourceToSymbolsFiles.asMap().entrySet()) {
+      Collection<Path> paths = resourceAndSymbolsFiles.getValue();
+      RDotTxtEntry resource = resourceAndSymbolsFiles.getKey();
+      if (paths.size() > 1 && !duplicateIsWhitelisted(resource, duplicateResourceWhitelist)) {
+        duplicateResourcesMessage.append(
+            String.format(
+                "Resource '%s' (%s) is duplicated across: ", resource.name, resource.type));
+        duplicateResourcesMessage.append(
+            Joiner.on(", ")
+                .join(
+                    paths.stream()
+                        .map(symbolsFileToResourceDeps::get)
+                        .filter(Objects::nonNull)
+                        .collect(Collectors.toList())));
+        duplicateResourcesMessage.append("\n");
+      }
+    }
+
+    if (duplicateResourcesMessage.length() > 0) {
+      throw new DuplicateResourceException(duplicateResourcesMessage.toString());
+    }
+
+    return rDotJavaPackageToSymbolsFiles;
+  }
+
+  private static boolean duplicateIsWhitelisted(RDotTxtEntry resource, Set<String> whitelist) {
+    return whitelist.contains(resource.type.toString().toLowerCase() + " " + resource.name);
+  }
+
+  private static RDotTxtEntry parseEntryOrThrow(String line) {
+    Optional<RDotTxtEntry> parsedEntry = RDotTxtEntry.parse(line);
+    Preconditions.checkState(parsedEntry.isPresent(), "Should be able to match '%s'.", line);
+
+    return parsedEntry.get();
+  }
+
+  /** Returns {@link Path} to R. java file */
+  public static Path getPathToRDotJava(Path outputDir, String rDotJavaPackage) {
+    return getPathToJavaFile(outputDir, rDotJavaPackage, "R.java");
+  }
+
+  static Path getPathToJavaFile(Path outputDir, String javaPackage, String fileName) {
+    return outputDir.resolve(javaPackage.replace('.', '/')).resolve(fileName);
+  }
+
+  public static class DuplicateResourceException extends Exception {
+    DuplicateResourceException(String messageFormat, Object... args) {
+      super(String.format(messageFormat, args));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAndroidResourcesExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAndroidResourcesExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAndroidResourcesExecutableMain.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.buck.android.aapt.RDotTxtEntry;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.util.zip.JarBuilder;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.EnumSet;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for executing {@link MergeAndroidResources} calls. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class MergeAndroidResourcesExecutableMain {
+  @Option(name = "--symbol-file-info", required = true)
+  private String symbolFileInfo;
+
+  @Option(name = "--output-dir", required = true)
+  private String outputDirString;
+
+  @Option(name = "--output-dir-zipped", required = true)
+  private String outputDirZippedString;
+
+  @Option(name = "--strings-output-dir")
+  private @Nullable String stringsOutputDirString = null;
+
+  @Option(name = "--strings-output-dir-zipped")
+  private @Nullable String stringsOutputDirZippedString = null;
+
+  @Option(name = "--ids-output-dir")
+  private @Nullable String idsOutputDirString = null;
+
+  @Option(name = "--ids-output-dir-zipped")
+  private @Nullable String idsOutputDirZippedString = null;
+
+  @Option(name = "--force-final-resource-ids")
+  private boolean forceFinalResourceIds = false;
+
+  @Option(name = "--uber-r-dot-txt")
+  private @Nullable String uberRDotTxtFilesList = null;
+
+  @Option(name = "--banned-duplicate-resource-types")
+  private @Nullable String bannedDuplicateResourceTypesList = null;
+
+  @Option(name = "--override-symbols")
+  private @Nullable String overrideSymbolsList = null;
+
+  @Option(name = "--duplicate-resource-allowlist-path")
+  private @Nullable String duplicateResourceAllowlist = null;
+
+  @Option(name = "--referenced-resources-lists")
+  private @Nullable String referencedResourcesLists = null;
+
+  public static void main(String[] args) throws IOException {
+    MergeAndroidResourcesExecutableMain main = new MergeAndroidResourcesExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    ImmutableMap.Builder<Path, String> symbolsFileToRDotJavaPackage = ImmutableMap.builder();
+    ImmutableMap.Builder<Path, String> symbolsFileToTargetName = ImmutableMap.builder();
+
+    for (String line : Files.readAllLines(Paths.get(symbolFileInfo))) {
+      String[] parts = line.split(" ");
+      Preconditions.checkState(parts.length == 3);
+      Path symbolsFilePath = Paths.get(parts[0]);
+      Path rDotJavaPackageFilePath = Paths.get(parts[1]);
+      String rDotJavaPackage = new String(Files.readAllBytes(rDotJavaPackageFilePath));
+      symbolsFileToRDotJavaPackage.put(symbolsFilePath, rDotJavaPackage);
+      symbolsFileToTargetName.put(symbolsFilePath, parts[2]);
+    }
+
+    ImmutableList<Path> uberRDotTxt =
+        uberRDotTxtFilesList != null
+            ? Files.readAllLines(Paths.get(uberRDotTxtFilesList)).stream()
+                .map(Paths::get)
+                .collect(ImmutableList.toImmutableList())
+            : ImmutableList.of();
+    EnumSet<RDotTxtEntry.RType> bannedDuplicateResourceTypes =
+        bannedDuplicateResourceTypesList != null
+            ? EnumSet.copyOf(
+                Files.readAllLines(Paths.get(bannedDuplicateResourceTypesList)).stream()
+                    .map(type -> RDotTxtEntry.RType.valueOf(type.toUpperCase()))
+                    .collect(Collectors.toList()))
+            : EnumSet.noneOf(RDotTxtEntry.RType.class);
+    ImmutableList<Path> overrideSymbols =
+        overrideSymbolsList != null
+            ? Files.readAllLines(Paths.get(overrideSymbolsList)).stream()
+                .map(Paths::get)
+                .collect(ImmutableList.toImmutableList())
+            : ImmutableList.of();
+    Optional<Path> duplicateResourceAllowlistPath =
+        Optional.ofNullable(duplicateResourceAllowlist).map(Paths::get);
+    Path outputDir = Paths.get(outputDirString);
+    Optional<Path> stringsOutputDirPath =
+        Optional.ofNullable(stringsOutputDirString).map(Paths::get);
+    Optional<Path> idsOutputDirPath = Optional.ofNullable(idsOutputDirString).map(Paths::get);
+
+    ImmutableSet.Builder<String> referencedResources = ImmutableSet.builder();
+    if (referencedResourcesLists != null) {
+      for (String referencedResourcesList :
+          Files.readAllLines(Paths.get(referencedResourcesLists))) {
+        referencedResources.addAll(Files.readAllLines(Paths.get(referencedResourcesList)));
+      }
+    }
+
+    try {
+      MergeAndroidResources.mergeAndroidResources(
+          uberRDotTxt,
+          symbolsFileToRDotJavaPackage.build(),
+          symbolsFileToTargetName.build(),
+          forceFinalResourceIds,
+          bannedDuplicateResourceTypes,
+          duplicateResourceAllowlistPath,
+          overrideSymbols,
+          outputDir,
+          stringsOutputDirPath,
+          idsOutputDirPath,
+          referencedResources.build());
+    } catch (MergeAndroidResources.DuplicateResourceException e) {
+      throw new RuntimeException(e);
+    }
+
+    Path outputDirZipped = Paths.get(outputDirZippedString);
+    createZip(outputDir, outputDirZipped);
+
+    Optional<Path> stringsOutputDirZippedPath =
+        Optional.ofNullable(stringsOutputDirZippedString).map(Paths::get);
+    Preconditions.checkState(
+        stringsOutputDirPath.isPresent() == stringsOutputDirZippedPath.isPresent());
+    if (stringsOutputDirZippedPath.isPresent()) {
+      createZip(stringsOutputDirPath.get(), stringsOutputDirZippedPath.get());
+    }
+
+    Optional<Path> idsOutputDirZippedPath =
+        Optional.ofNullable(idsOutputDirZippedString).map(Paths::get);
+    Preconditions.checkState(idsOutputDirPath.isPresent() == idsOutputDirZippedPath.isPresent());
+    if (idsOutputDirZippedPath.isPresent()) {
+      createZip(idsOutputDirPath.get(), idsOutputDirZippedPath.get());
+    }
+
+    System.exit(0);
+  }
+
+  private void createZip(Path outputDir, Path outputDirZipped) throws IOException {
+    AbsPath root = AbsPath.of(Paths.get(".").normalize().toAbsolutePath());
+    new JarBuilder()
+        .setEntriesToJar(ImmutableList.of(root.resolve(outputDir)))
+        .createJarFile(root.resolve(outputDirZipped).getPath());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAssetsExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAssetsExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAssetsExecutableMain.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.util.json.ObjectMappers;
+import com.facebook.infer.annotation.Nullsafe;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+import org.kohsuke.args4j.spi.StringArrayOptionHandler;
+
+/** Main entry point for merging assets. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class MergeAssetsExecutableMain {
+
+  @Option(name = "--output-apk", required = true, usage = "path to output APK")
+  private String outputApk;
+
+  @Option(name = "--module-assets-apks-dir", usage = "path to module assets APKs")
+  private @Nullable String moduleAssetsApksDir = null;
+
+  @Option(name = "--base-apk", usage = "path to existing APK containing resources")
+  private @Nullable String baseApk = null;
+
+  @Option(name = "--assets-dirs", required = true, usage = "directory containing assets")
+  private String assetsDirs;
+
+  @Option(
+      name = "--output-apk-hash",
+      usage = "output path of a file containing the hash of output APK")
+  private @Nullable String outputApkHash = null;
+
+  @Option(
+      name = "--extra-no-compress-asset-extensions",
+      handler = StringArrayOptionHandler.class,
+      usage = "list of asset extensions that should not be compressed")
+  private List<String> extraNoCompressAssetExtensions = new ArrayList<>();
+
+  @Option(
+      name = "--extra_no_compress_asset_regex",
+      usage = "regex pattern to match asset paths that should not be compressed")
+  private @Nullable String extraNoCompressRegex = null;
+
+  @Option(name = "--binary-type", usage = "either 'apk' or 'aab'")
+  private @Nullable String binaryType = null;
+
+  public static void main(String[] args) throws IOException {
+    MergeAssetsExecutableMain main = new MergeAssetsExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    // readValue only yields null for a literal JSON `null` document.
+    ImmutableMap<String, ImmutableSet<Path>> rawDirs =
+        Objects.requireNonNull(
+            ObjectMappers.READER.readValue(
+                ObjectMappers.createParser(Paths.get(assetsDirs)),
+                new TypeReference<ImmutableMap<String, ImmutableSet<Path>>>() {}));
+
+    ImmutableMap<String, ImmutableSet<RelPath>> dirs =
+        rawDirs.entrySet().stream()
+            .collect(
+                ImmutableMap.toImmutableMap(
+                    Map.Entry::getKey,
+                    x ->
+                        x.getValue().stream()
+                            .map(RelPath::of)
+                            .collect(ImmutableSet.toImmutableSet())));
+
+    Path outputApkPath = Paths.get(outputApk);
+    MergeAssetsUtils.mergeAssets(
+        outputApkPath,
+        Optional.ofNullable(moduleAssetsApksDir).map(Paths::get),
+        Optional.ofNullable(baseApk).map(Paths::get),
+        AbsPath.of(Paths.get(".").normalize().toAbsolutePath()),
+        dirs,
+        ImmutableSet.copyOf(extraNoCompressAssetExtensions),
+        Optional.ofNullable(extraNoCompressRegex),
+        MergeAssetsUtils.BinaryType.valueOf(Objects.requireNonNull(binaryType).toUpperCase()));
+
+    if (outputApkHash != null) {
+      Files.writeString(
+          Paths.get(outputApkHash),
+          com.google.common.io.Files.hash(outputApkPath.toFile(), Hashing.sha1()).toString());
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAssetsUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAssetsUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/MergeAssetsUtils.java
@@ -0,0 +1,256 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.buck.android.apkmodule.APKModule;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.io.Files;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.FileVisitOption;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.regex.Pattern;
+import java.util.zip.CRC32;
+import java.util.zip.Deflater;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/** Utils for merging assets into an apk. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class MergeAssetsUtils {
+  public enum BinaryType {
+    APK,
+    AAB,
+  }
+
+  // See
+  // https://android.googlesource.com/platform/frameworks/base.git/+/nougat-release/tools/aapt/Package.cpp
+  static final ImmutableSet<String> DEFAULT_NO_COMPRESS_EXTENSIONS =
+      ImmutableSet.of(
+          "jpg", "jpeg", "png", "gif", "wav", "mp2", "mp3", "ogg", "aac", "mpg", "mpeg", "mid",
+          "midi", "smf", "jet", "rtttl", "imy", "xmf", "mp4", "m4a", "m4v", "3gp", "3gpp", "3g2",
+          "3gpp2", "amr", "awb", "wma", "wmv", "webm", "mkv", "tflite");
+
+  /**
+   * Construct an APK containing assets. If a "baseApk" was provided, also include everything from
+   * that APK.
+   *
+   * @param outputApk path to the output APK file
+   * @param moduleAssetsOutputDir optional directory for module assets APKs (used for AAB builds)
+   * @param baseApk optional path to existing APK containing resources to merge
+   * @param root absolute path to the project root directory
+   * @param moduleToAssetsDirectories map of module names to sets of asset directory paths
+   * @param extraNoCompressExtensions set of file extensions or path patterns that should not be
+   *     compressed (e.g., "zip", "bank/bank")
+   * @param noCompressRegex optional regex pattern used to match asset paths that should not be
+   *     compressed. This lets us support the same --no-compress-regex pattern used by the Android
+   *     SDK aapt2 C++ tool upstream when building the base APK. Note that C++ uses std::regex, so
+   *     this pattern is going to be ECMAScript regex.
+   * @param binaryType type of binary being built (APK or AAB)
+   * @throws IOException if an error occurs during asset merging
+   */
+  public static void mergeAssets(
+      Path outputApk,
+      Optional<Path> moduleAssetsOutputDir,
+      Optional<Path> baseApk,
+      AbsPath root,
+      ImmutableMap<String, ImmutableSet<RelPath>> moduleToAssetsDirectories,
+      ImmutableSet<String> extraNoCompressExtensions,
+      Optional<String> noCompressRegex,
+      BinaryType binaryType)
+      throws IOException {
+    ImmutableSet<String> allNoCompressExtensions =
+        new ImmutableSet.Builder<String>()
+            .addAll(DEFAULT_NO_COMPRESS_EXTENSIONS)
+            .addAll(extraNoCompressExtensions)
+            .build();
+    Optional<Pattern> noCompressPattern = getNoCompressPattern(noCompressRegex);
+    if (moduleAssetsOutputDir.isPresent()) {
+      Preconditions.checkState(binaryType == BinaryType.AAB);
+      java.nio.file.Files.createDirectories(moduleAssetsOutputDir.get());
+    }
+
+    try (ResourcesZipBuilder outputApkResources =
+        new ResourcesZipBuilder(outputApk, /* addManifestIfMissing */ true)) {
+      if (baseApk.isPresent()) {
+        try (ZipFile base = new ZipFile(baseApk.get().toFile())) {
+          for (ZipEntry inputEntry : Collections.list(base.entries())) {
+            String apkPath = inputEntry.getName();
+            // Only compress if aapt compressed it and the extension looks compressible.
+            // This is a workaround for aapt2 compressing everything.
+            boolean shouldCompress =
+                inputEntry.getMethod() != ZipEntry.STORED
+                    && !isNoCompress(apkPath, allNoCompressExtensions, noCompressPattern);
+            try (InputStream stream = Objects.requireNonNull(base.getInputStream(inputEntry))) {
+              outputApkResources.addEntry(
+                  stream,
+                  inputEntry.getSize(),
+                  inputEntry.getCrc(),
+                  inputEntry.getName(),
+                  shouldCompress ? Deflater.BEST_COMPRESSION : 0,
+                  inputEntry.isDirectory());
+            }
+          }
+        }
+      }
+
+      for (Map.Entry<String, ImmutableSet<RelPath>> entry : moduleToAssetsDirectories.entrySet()) {
+        String moduleName = entry.getKey();
+        ImmutableMap<Path, Path> assets = getAllAssets(root, entry.getValue());
+        boolean isRootModule = APKModule.isRootModule(moduleName);
+        if (isRootModule || binaryType == BinaryType.APK) {
+          Path assetsZipRoot =
+              isRootModule
+                  ? Paths.get("assets")
+                  : Paths.get("assets").resolve(moduleName).resolve("assets");
+          addAllAssets(
+              outputApkResources,
+              assets,
+              assetsZipRoot,
+              allNoCompressExtensions,
+              noCompressPattern);
+        } else {
+          Path moduleDir = moduleAssetsOutputDir.orElseThrow().resolve(moduleName);
+          java.nio.file.Files.createDirectory(moduleDir);
+          try (ResourcesZipBuilder moduleOutputApk =
+              new ResourcesZipBuilder(
+                  moduleDir.resolve("assets.ap_"), /* addManifestIfMissing */ false)) {
+            Path assetsZipRoot = Paths.get("assets").resolve(moduleName);
+            addAllAssets(
+                moduleOutputApk, assets, assetsZipRoot, allNoCompressExtensions, noCompressPattern);
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * Compile the optional --no-compress-regex pattern for matching complex asset paths.
+   *
+   * @param noCompressRegex optional raw regex pattern from additional_aapt_params
+   *     (--no-compress-regex)
+   * @return optional compiled pattern, or empty if no regex provided
+   */
+  private static Optional<Pattern> getNoCompressPattern(Optional<String> noCompressRegex) {
+    if (noCompressRegex.isPresent() && !noCompressRegex.get().isEmpty()) {
+      String regex = noCompressRegex.get();
+      try {
+        return Optional.of(Pattern.compile(regex));
+      } catch (java.util.regex.PatternSyntaxException e) {
+        throw new IllegalArgumentException(
+            String.format(
+                "Invalid regex pattern in additional_aapt_params --no-compress-regex: '%s'. Error:"
+                    + " %s",
+                regex, e.toString()),
+            e);
+      }
+    }
+    return Optional.empty();
+  }
+
+  /**
+   * Checks if an asset path should not be compressed.
+   *
+   * @param apkPath the normalized path of the asset in the APK (using forward slashes)
+   * @param allNoCompressExtensions set of all file extensions that should not be compressed
+   * @param noCompressPattern optional compiled regex pattern for complex path matching
+   * @return true if the asset should not be compressed, false otherwise
+   */
+  static boolean isNoCompress(
+      String apkPath,
+      ImmutableSet<String> allNoCompressExtensions,
+      Optional<Pattern> noCompressPattern) {
+    String extension = Files.getFileExtension(apkPath);
+    if (allNoCompressExtensions.contains(extension)) {
+      return true;
+    }
+
+    if (noCompressPattern.isPresent()) {
+      return noCompressPattern.get().matcher(apkPath).find();
+    }
+
+    return false;
+  }
+
+  private static ImmutableMap<Path, Path> getAllAssets(
+      AbsPath root, ImmutableSet<RelPath> assetsDirectories) throws IOException {
+    ImmutableMap.Builder<Path, Path> assets = ImmutableMap.builder();
+
+    for (RelPath assetDirectory : assetsDirectories) {
+      AbsPath absolutePath = ProjectFilesystemUtils.getAbsPathForRelativePath(root, assetDirectory);
+
+      ProjectFilesystemUtils.walkFileTree(
+          root,
+          assetDirectory.getPath(),
+          ImmutableSet.of(FileVisitOption.FOLLOW_LINKS),
+          new SimpleFileVisitor<>() {
+            @Override
+            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+                throws IOException {
+              Preconditions.checkState(
+                  !Files.getFileExtension(file.toString()).equals("gz"),
+                  "BUCK doesn't support adding .gz files to assets (%s).",
+                  file);
+              Path normalized = file.normalize();
+              assets.put(absolutePath.getPath().relativize(normalized), normalized);
+              return super.visitFile(file, attrs);
+            }
+          },
+          ProjectFilesystemUtils.getEmptyIgnoreFilter());
+    }
+
+    return assets.build();
+  }
+
+  private static void addAllAssets(
+      ResourcesZipBuilder output,
+      ImmutableMap<Path, Path> assets,
+      Path assetsZipRoot,
+      ImmutableSet<String> allNoCompressExtensions,
+      Optional<Pattern> noCompressPattern)
+      throws IOException {
+    for (Map.Entry<Path, Path> assetPaths : assets.entrySet()) {
+      Path packagingPathForAsset = assetPaths.getKey();
+      Path fullPathToAsset = assetPaths.getValue();
+      int compression =
+          isNoCompress(packagingPathForAsset.toString(), allNoCompressExtensions, noCompressPattern)
+              ? 0
+              : Deflater.BEST_COMPRESSION;
+      byte[] assetBytes = java.nio.file.Files.readAllBytes(fullPathToAsset);
+      CRC32 crc32 = new CRC32();
+      crc32.update(assetBytes);
+      try (InputStream assetStream = new ByteArrayInputStream(assetBytes)) {
+        output.addEntry(
+            assetStream,
+            assetBytes.length,
+            crc32.getValue(),
+            assetsZipRoot.resolve(packagingPathForAsset).toString(),
+            compression,
+            false);
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ReferenceMapper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ReferenceMapper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ReferenceMapper.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.nio.IntBuffer;
+
+/**
+ * A ReferenceMapper is used to reassign ids in Android's .arsc/.xml files.
+ *
+ * <p>Android .arsc/.xml files include many resource references. These are ints of the form
+ * 0xPPTTIIII encoding three things: package, type, index. The index part is an index into an array
+ * of integers (or rather, into multiple arrays of integers).
+ *
+ * <p>A ReferenceMapper implements a method to update references and to rewrite those arrays that
+ * they refer to.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface ReferenceMapper {
+  /** Converts an id to its new value under this mapping. */
+  int map(int id);
+
+  /**
+   * Given an IntBuffer with an entry for every value of the given type, rearranges the entries in
+   * the buffer to match the id reassignment.
+   */
+  void rewrite(int type, IntBuffer buf);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResChunk.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResChunk.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResChunk.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.primitives.Shorts;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.Arrays;
+
+/**
+ * ResChunk is the base of most structures in Android's .arsc and compiled .xml files. It consists
+ * of: u16 chunkType u16 headerSize u32 chunkSize
+ *
+ * <p>Some common types used by different chunks:
+ *
+ * <p>StringRef is a u32 string id ResRef is a u32 resource id ResValue is a chunk of: u16 size u8
+ * 0x00 u8 dataType (one of ResChunk.RES_XXXXXXX) u32 data
+ *
+ * <p>See
+ * https://android.googlesource.com/platform/frameworks/base/+/kitkat-release/include/androidfw/ResourceTypes.h
+ * for full specification.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public abstract class ResChunk {
+  public static final short CHUNK_STRING_POOL = 0x001;
+  public static final short CHUNK_RESOURCE_TABLE = 0x002;
+  public static final short CHUNK_XML_TREE = 0x003;
+
+  public static final short CHUNK_XML_REF_MAP = 0x180;
+
+  public static final short CHUNK_RES_TABLE_PACKAGE = 0x0200;
+  public static final short CHUNK_RES_TABLE_TYPE = 0x201;
+  public static final short CHUNK_RES_TABLE_TYPE_SPEC = 0x202;
+
+  static final int RES_REFERENCE = 0x1;
+  static final int RES_ATTRIBUTE = 0x2;
+  static final int RES_STRING = 0x3;
+
+  static final int RES_FLOAT = 0x4;
+  static final int RES_DIMENSION = 0x5;
+  static final int RES_FRACTION = 0x6;
+
+  static final int RES_DYNAMIC_REFERENCE = 0x07;
+  static final int RES_DYNAMIC_ATTRIBUTE = 0x08;
+
+  static final int RES_DECIMAL = 0x10;
+  static final int RES_HEX = 0x11;
+  static final int RES_BOOL = 0x12;
+
+  static final int RES_COLOR_ARGB8 = 0x1c;
+  static final int RES_COLOR_RGB8 = 0x1d;
+  static final int RES_COLOR_ARGB4 = 0x1e;
+  static final int RES_COLOR_RGB4 = 0x1f;
+
+  private final short type;
+  private final short headerSize;
+  private final int chunkSize;
+
+  ResChunk(int chunkType, int headerSize, int chunkSize) {
+    this.type = Shorts.checkedCast(chunkType);
+    this.headerSize = Shorts.checkedCast(headerSize);
+    this.chunkSize = chunkSize;
+    Preconditions.checkState((chunkSize % 4) == 0);
+  }
+
+  public final int getType() {
+    return type;
+  }
+
+  public final int getHeaderSize() {
+    return headerSize;
+  }
+
+  public final int getChunkSize() {
+    return chunkSize;
+  }
+
+  /**
+   * For most chunk's totalSize == chunkSize. For some types, the type logically consists of
+   * multiple chunks. In these cases, totalSize is the sum of all the chunks. This is the full size
+   * written/read from a buffer for get/put.
+   */
+  public int getTotalSize() {
+    return chunkSize;
+  }
+
+  public final byte[] serialize() {
+    byte[] data = new byte[getTotalSize()];
+    ByteBuffer output = wrap(data);
+    put(output);
+    Preconditions.checkState(output.position() == data.length);
+    return data;
+  }
+
+  public abstract void put(ByteBuffer output);
+
+  void putChunkHeader(ByteBuffer output) {
+    output.putShort(type);
+    output.putShort(headerSize);
+    output.putInt(chunkSize);
+  }
+
+  public interface RefTransformer {
+    int transform(int ref);
+  }
+
+  public interface RefVisitor {
+    void visit(int ref);
+  }
+
+  /** Functional interface for processing a reference at a buffer offset. */
+  interface RefHandler {
+    void process(ByteBuffer buf, int offset);
+  }
+
+  static RefHandler transformHandler(RefTransformer transformer) {
+    return (buf, offset) -> transformEntryDataOffset(buf, offset, transformer);
+  }
+
+  static RefHandler visitHandler(RefVisitor visitor) {
+    return (buf, offset) -> visitEntryDataOffset(buf, offset, visitor);
+  }
+
+  static void transformEntryDataOffset(ByteBuffer buf, int offset, RefTransformer visitor) {
+    int oldValue = buf.getInt(offset);
+    int newValue = visitor.transform(oldValue);
+    if (oldValue != newValue) {
+      buf.putInt(offset, newValue);
+    }
+  }
+
+  static void visitEntryDataOffset(ByteBuffer buf, int offset, RefVisitor visitor) {
+    visitor.visit(buf.getInt(offset));
+  }
+
+  // These are some utilities used widely by subclasses for dealing with ByteBuffers.
+  static ByteBuffer copy(ByteBuffer buf) {
+    return wrap(
+        Arrays.copyOfRange(buf.array(), buf.arrayOffset(), buf.arrayOffset() + buf.limit()));
+  }
+
+  public static ByteBuffer wrap(byte[] data) {
+    ByteBuffer buf = ByteBuffer.wrap(data);
+    buf.order(ByteOrder.LITTLE_ENDIAN);
+    return buf;
+  }
+
+  public static ByteBuffer slice(ByteBuffer map, int offset) {
+    ByteBuffer result = map.duplicate();
+    result.position(offset);
+    result = result.slice();
+    result.order(ByteOrder.LITTLE_ENDIAN);
+    return result;
+  }
+
+  public static ByteBuffer slice(ByteBuffer map, int offset, int length) {
+    ByteBuffer result = slice(map, offset);
+    result.limit(length);
+    return result;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTablePackage.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTablePackage.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTablePackage.java
@@ -0,0 +1,257 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.buck.util.MoreSuppliers;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.collect.Maps;
+import java.io.PrintStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Supplier;
+import java.util.stream.IntStream;
+
+/**
+ * A Package consists of a header: ResTable_header u16 chunk_type u16 header_size u32 chunk_size u32
+ * package_id u16[128] name u32 typeStringOffset u32 lastPublicTypeOffset u32 keyStringOffset u32
+ * lastPublicKeyOffset u32 typeIdOffset
+ *
+ * <p>The header is followed by a types string pool (containing types like "id", "attr", "drawable",
+ * ...) and a keys string pool (containing the names of resources). Then follows a TypeSpec for each
+ * type (# of types can be derived from the size of the types stringpool).
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ResTablePackage extends ResChunk {
+  public static final int HEADER_SIZE = 288;
+  public static final int APP_PACKAGE_ID = 0x7F;
+  public static final int NAME_DATA_LENGTH = 256;
+
+  private final int packageId;
+  private final byte[] nameData;
+  private final Supplier<String> name;
+  private final StringPool types;
+  private final StringPool keys;
+  private final List<ResTableTypeSpec> typeSpecs;
+  private final ResTableTypeSpec[] typeSpecByType;
+
+  public void reassignIds(ReferenceMapper refMapping) {
+    for (ResTableTypeSpec spec : typeSpecs) {
+      spec.reassignIds(refMapping);
+    }
+  }
+
+  private void assertValidIds(Iterable<Integer> ids) {
+    ids.forEach(this::getTypeSpec);
+  }
+
+  public static ResTablePackage slice(
+      ResTablePackage resPackage, Map<Integer, Integer> countsToSlice) {
+    resPackage.assertValidIds(countsToSlice.keySet());
+
+    int packageId = resPackage.packageId;
+    byte[] nameData = Arrays.copyOf(resPackage.nameData, NAME_DATA_LENGTH);
+
+    List<ResTableTypeSpec> newSpecs =
+        resPackage.getTypeSpecs().stream()
+            .map(
+                spec ->
+                    ResTableTypeSpec.slice(
+                        spec, countsToSlice.getOrDefault(spec.getResourceType(), 0)))
+            .collect(ImmutableList.toImmutableList());
+
+    StringPool keys = resPackage.keys;
+
+    // Figure out what keys are used by the retained references.
+    ImmutableSortedSet.Builder<Integer> keyRefs =
+        ImmutableSortedSet.orderedBy(Comparator.comparing(keys::getString));
+    newSpecs.forEach(spec -> spec.visitKeyReferences(keyRefs::add));
+    ImmutableList<Integer> keysToExtract = keyRefs.build().asList();
+    Map<Integer, Integer> keyMapping =
+        Maps.uniqueIndex(IntStream.range(0, keysToExtract.size())::iterator, keysToExtract::get);
+
+    // Extract a StringPool that contains just the keys used by the new specs.
+    StringPool newKeys = StringPool.create(keysToExtract.stream().map(keys::getString)::iterator);
+
+    // Adjust the key references.
+    for (ResTableTypeSpec spec : newSpecs) {
+      spec.transformKeyReferences(keyMapping::get);
+    }
+
+    StringPool types = resPackage.types.copy();
+
+    int chunkSize = HEADER_SIZE + types.getChunkSize() + newKeys.getChunkSize();
+    for (ResTableTypeSpec spec : newSpecs) {
+      chunkSize += spec.getTotalSize();
+    }
+
+    return new ResTablePackage(chunkSize, packageId, nameData, types, newKeys, newSpecs);
+  }
+
+  static ResTablePackage get(ByteBuffer buf) {
+    int chunkType = buf.getShort();
+    int headerSize = buf.getShort();
+    int chunkSize = buf.getInt();
+    int packageId = buf.getInt();
+    byte[] nameData = new byte[NAME_DATA_LENGTH];
+    buf.get(nameData);
+
+    int typeStringOffset = buf.getInt();
+    int lastPublicType = buf.getInt();
+    int keyStringOffset = buf.getInt();
+    int lastPublicKey = buf.getInt();
+    int typeIdOffset = buf.getInt();
+
+    Preconditions.checkState(chunkType == CHUNK_RES_TABLE_PACKAGE);
+    Preconditions.checkState(headerSize == HEADER_SIZE);
+    Preconditions.checkState(packageId == APP_PACKAGE_ID);
+    Preconditions.checkState(typeIdOffset == 0);
+    Preconditions.checkState(typeStringOffset == HEADER_SIZE);
+
+    StringPool types = StringPool.get(slice(buf, typeStringOffset));
+    StringPool keys = StringPool.get(slice(buf, keyStringOffset));
+
+    // TODO(cjhopman): aapt1 generates a lastPublicType/lastPublicKey at the end of types/keys.
+    // aapt2
+    // generates them as 0. Does this value matter?
+    Preconditions.checkState(lastPublicType == types.getStringCount() || lastPublicType == 0);
+    Preconditions.checkState(lastPublicKey == keys.getStringCount() || lastPublicKey == 0);
+    Preconditions.checkState(keyStringOffset == HEADER_SIZE + types.getChunkSize());
+
+    ImmutableList.Builder<ResTableTypeSpec> typeSpecs = ImmutableList.builder();
+    buf.position(keyStringOffset + keys.getChunkSize());
+    while (buf.position() < chunkSize) {
+      ByteBuffer specBuf = slice(buf, buf.position());
+      ResTableTypeSpec spec = ResTableTypeSpec.get(specBuf);
+      typeSpecs.add(spec);
+      buf.position(buf.position() + spec.getTotalSize());
+    }
+
+    Preconditions.checkState(buf.position() == chunkSize);
+
+    return new ResTablePackage(chunkSize, packageId, nameData, types, keys, typeSpecs.build());
+  }
+
+  @Override
+  public void put(ByteBuffer output) {
+    Preconditions.checkState(output.remaining() >= getChunkSize());
+    int start = output.position();
+    putChunkHeader(output);
+    output.putInt(APP_PACKAGE_ID);
+    output.put(nameData);
+    output.putInt(HEADER_SIZE);
+    output.putInt(types.getStringCount());
+    output.putInt(HEADER_SIZE + types.getChunkSize());
+    output.putInt(keys.getStringCount());
+    output.putInt(0);
+    Preconditions.checkState(output.position() == start + HEADER_SIZE);
+    types.put(output);
+    Preconditions.checkState(output.position() == start + HEADER_SIZE + types.getChunkSize());
+    keys.put(output);
+    Preconditions.checkState(
+        output.position() == start + HEADER_SIZE + types.getChunkSize() + keys.getChunkSize());
+    typeSpecs.forEach(s -> s.put(output));
+    Preconditions.checkState(output.position() == start + getChunkSize());
+  }
+
+  public ResTablePackage(
+      int chunkSize,
+      int packageId,
+      byte[] nameData,
+      StringPool types,
+      StringPool keys,
+      List<ResTableTypeSpec> typeSpecs) {
+    super(CHUNK_RES_TABLE_PACKAGE, HEADER_SIZE, chunkSize);
+    this.packageId = packageId;
+    this.nameData = nameData;
+    this.types = types;
+    this.keys = keys;
+    this.typeSpecs = typeSpecs;
+
+    int maxType = 0;
+    for (ResTableTypeSpec spec : typeSpecs) {
+      maxType = Math.max(maxType, spec.getResourceType());
+    }
+    this.typeSpecByType = new ResTableTypeSpec[maxType + 1];
+    for (ResTableTypeSpec spec : typeSpecs) {
+      typeSpecByType[spec.getResourceType()] = spec;
+    }
+
+    name =
+        MoreSuppliers.memoize(
+            () -> {
+              // Construct a string from the full name data. This will end with a bunch of \0.
+              String fullData = new String(nameData, StandardCharsets.UTF_16LE);
+              return fullData.substring(0, fullData.indexOf(0));
+            });
+    Preconditions.checkState(this.packageId == APP_PACKAGE_ID);
+  }
+
+  public void dump(StringPool strings, PrintStream out) {
+    out.format("Package Group 0 id=0x%02x packageCount=1 name=%s\n", packageId, getPackageName());
+    out.format("  Package 0 id=0x%02x name=%s\n", packageId, getPackageName());
+    for (ResTableTypeSpec spec : typeSpecs) {
+      spec.dump(strings, this, out);
+    }
+  }
+
+  String getPackageName() {
+    return name.get();
+  }
+
+  public List<ResTableTypeSpec> getTypeSpecs() {
+    return typeSpecs;
+  }
+
+  public StringPool getKeys() {
+    return keys;
+  }
+
+  public ResTableTypeSpec getTypeSpec(int type) {
+    if (type >= 0 && type < typeSpecByType.length) {
+      ResTableTypeSpec spec = typeSpecByType[type];
+      if (spec != null) {
+        return spec;
+      }
+    }
+    throw new IllegalArgumentException();
+  }
+
+  public StringPool getTypes() {
+    return types;
+  }
+
+  public byte[] getNameData() {
+    return nameData;
+  }
+
+  public void transformStringReferences(RefTransformer visitor) {
+    typeSpecs.forEach(c -> c.transformStringReferences(visitor));
+  }
+
+  public void visitStringReferences(RefVisitor visitor) {
+    typeSpecs.forEach(c -> c.visitStringReferences(visitor));
+  }
+
+  public String getRefName(int i) {
+    int type = (i >> 16) & 0xFF;
+    int idx = i & 0xFFFF;
+    ResTableTypeSpec spec = typeSpecs.get(type - 1);
+    Preconditions.checkState(spec.getResourceType() == type);
+    return spec.getResourceName(this, idx);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTableType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTableType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTableType.java
@@ -0,0 +1,549 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.nio.ByteBuffer;
+import java.text.DecimalFormat;
+import java.util.Arrays;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * ResTableType is a ResChunk holding the resource values for a given type and configuration. It
+ * consists of: ResChunk_header u32 chunk_type u32 header_size u32 chunk_size u8 id u32 entry_count
+ * u32 entry_start Config u32 config_size u8[config_size - 4] data
+ *
+ * <p>This is followed by entry_count u32s containing offsets from entry_start to the data for each
+ * entry. If the offset for a resource is -1, that resource has no value in this configuration.
+ *
+ * <p>After the offsets comes the entry data. Each entry is of the form: u16 size u16 flags
+ * StringRef key
+ *
+ * <p>If `(flags & FLAG_COMPLEX) == 0` this data is then followed by: ResValue value
+ *
+ * <p>Else it's followed by a map header: ResRef parent u32 count
+ *
+ * <p>and `count` map entries of the form: ResRef name ResValue value
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ResTableType extends ResChunk {
+  private static final int CONFIG_OFFSET = 20;
+  private static final int FLAG_COMPLEX = 0x1;
+
+  // Offsets within a resource entry (Res_ENTRY header + value)
+  private static final int ENTRY_FLAGS_OFFSET = 2;
+  private static final int ENTRY_KEY_OFFSET = 4;
+  // Simple entry: value fields follow the 8-byte Res_ENTRY header
+  private static final int SIMPLE_VALUE_SIZE_OFFSET = 8;
+  private static final int SIMPLE_VALUE_TYPE_OFFSET = 11;
+  private static final int SIMPLE_VALUE_DATA_OFFSET = 12;
+  // Complex (bag) entry: parent ref and map count follow the 8-byte header
+  private static final int COMPLEX_PARENT_OFFSET = 8;
+  private static final int COMPLEX_COUNT_OFFSET = 12;
+  private static final int COMPLEX_ENTRIES_START_OFFSET = 16;
+  // Map entry offsets (relative to the entry base, not the map entry itself)
+  private static final int MAP_ENTRY_NAME_OFFSET = 16;
+  private static final int MAP_ENTRY_VALUE_SIZE_OFFSET = 20;
+  private static final int MAP_ENTRY_VALUE_TYPE_OFFSET = 23;
+  private static final int MAP_ENTRY_VALUE_DATA_OFFSET = 24;
+
+  public static final int ATTRIBUTE_NAME_REF_OFFSET = 0;
+  public static final int ATTRIBUTE_SIZE_OFFSET = 4;
+  public static final int ATTRIBUTE_TYPE_OFFSET = 7;
+  public static final int ATTRIBUTE_DATA_OFFSET = 8;
+
+  private final int id;
+  private final int entryCount;
+  private final ByteBuffer config;
+  private final ByteBuffer entryOffsets;
+  private final ByteBuffer entryData;
+
+  @Nullable
+  public static ResTableType slice(ResTableType type, int count) {
+    ByteArrayOutputStream output = new ByteArrayOutputStream();
+    int currentOffset = 0;
+    ByteBuffer entryOffsets = wrap(new byte[count * 4]);
+    for (int i = 0; i < count; i++) {
+      int offset = type.getEntryValueOffset(i);
+      if (offset == -1) {
+        entryOffsets.putInt(i * 4, -1);
+      } else {
+        entryOffsets.putInt(i * 4, currentOffset);
+        int dataSize = type.getEntrySizeAtOffset(offset);
+        currentOffset += dataSize;
+        output.write(type.entryData.array(), type.entryData.arrayOffset() + offset, dataSize);
+      }
+    }
+
+    byte[] entryData = output.toByteArray();
+    if (entryData.length == 0) {
+      return null;
+    }
+    int headerSize = type.getHeaderSize();
+    int chunkSize = headerSize + count * 4 + entryData.length;
+
+    return new ResTableType(
+        headerSize, chunkSize, type.id, count, copy(type.config), entryOffsets, wrap(entryData));
+  }
+
+  private int getEntrySizeAtOffset(int offset) {
+    int size = entryData.getShort(offset);
+    int flags = entryData.getShort(offset + ENTRY_FLAGS_OFFSET);
+    if ((flags & FLAG_COMPLEX) == 0) {
+      return size + entryData.getShort(offset + size);
+    } else {
+      int count = entryData.getInt(offset + COMPLEX_COUNT_OFFSET);
+      for (int i = 0; i < count; i++) {
+        size += 4 + entryData.getShort(offset + size + 4);
+      }
+      return size;
+    }
+  }
+
+  @Override
+  public void put(ByteBuffer output) {
+    Preconditions.checkState(output.remaining() >= getChunkSize());
+    int start = output.position();
+    putChunkHeader(output);
+    output.put((byte) (id + 1));
+    output.put((byte) 0);
+    output.putShort((byte) 0);
+    output.putInt(entryCount);
+    output.putInt(getHeaderSize() + 4 * entryCount);
+    output.put(slice(config, 0));
+    output.put(slice(entryOffsets, 0));
+    output.put(slice(entryData, 0));
+    Preconditions.checkState(output.position() == start + getChunkSize());
+  }
+
+  public static ResTableType get(ByteBuffer buf) {
+    int type = buf.getShort();
+    int headerSize = buf.getShort();
+    int chunkSize = buf.getInt();
+    int id = (buf.get() & 0xFF) - 1;
+    buf.get(); // ignored
+    buf.getShort(); // ignored
+    int entryCount = buf.getInt();
+    int entriesOffset = buf.getInt();
+    int configSize = buf.getInt(buf.position());
+    int entryDataSize = chunkSize - headerSize - 4 * entryCount;
+
+    Preconditions.checkState(type == CHUNK_RES_TABLE_TYPE);
+    Preconditions.checkState(headerSize == configSize + CONFIG_OFFSET);
+
+    return new ResTableType(
+        headerSize,
+        chunkSize,
+        id,
+        entryCount,
+        slice(buf, CONFIG_OFFSET, configSize),
+        slice(buf, headerSize, entryCount * 4),
+        slice(buf, entriesOffset, entryDataSize));
+  }
+
+  private ResTableType(
+      int headerSize,
+      int chunkSize,
+      int id,
+      int entryCount,
+      ByteBuffer config,
+      ByteBuffer entryOffsets,
+      ByteBuffer entryData) {
+    super(CHUNK_RES_TABLE_TYPE, headerSize, chunkSize);
+    this.id = id;
+    this.entryCount = entryCount;
+    this.config = config;
+    this.entryOffsets = entryOffsets;
+    this.entryData = entryData;
+  }
+
+  public void dump(StringPool strings, ResTablePackage resPackage, PrintStream out) {
+    out.format("      config (unknown):\n");
+    for (int entryIdx = 0; entryIdx < entryCount; entryIdx++) {
+      int offset = getEntryValueOffset(entryIdx);
+      if (offset != -1) {
+        int size = entryData.getShort(offset);
+        int flags = entryData.getShort(offset + ENTRY_FLAGS_OFFSET);
+        int refId = entryData.getInt(offset + ENTRY_KEY_OFFSET);
+        Preconditions.checkState(size > 0);
+        // Some of the formatting of this line is shared between maps/non-maps.
+        out.format(
+            "        resource 0x7f%02x%04x %s:%s/%s:",
+            getResourceType(),
+            entryIdx,
+            resPackage.getPackageName(),
+            getTypeName(resPackage),
+            resPackage.getKeys().getString(refId));
+        if ((flags & FLAG_COMPLEX) != 0) {
+          out.format(" <bag>\n");
+          int parent = entryData.getInt(offset + COMPLEX_PARENT_OFFSET);
+          int count = entryData.getInt(offset + COMPLEX_COUNT_OFFSET);
+          out.format(
+              "          Parent=0x%08x(Resolved=0x%08x), Count=%d\n",
+              parent, parent == 0 ? 0x7F000000 : parent, count);
+          int entryOffset = offset;
+          for (int attrIdx = 0; attrIdx < count; attrIdx++) {
+            int name = entryData.getInt(entryOffset + MAP_ENTRY_NAME_OFFSET);
+            int vsize = entryData.getShort(entryOffset + MAP_ENTRY_VALUE_SIZE_OFFSET);
+            int type = entryData.get(entryOffset + MAP_ENTRY_VALUE_TYPE_OFFSET);
+            int data = entryData.getInt(entryOffset + MAP_ENTRY_VALUE_DATA_OFFSET);
+            String dataString = formatTypeForDump(strings, type, data);
+            out.format("          #%d (Key=0x%08x): %s\n", attrIdx, name, dataString);
+            entryOffset += 4 + vsize;
+          }
+        } else {
+          int vsize = entryData.getShort(offset + SIMPLE_VALUE_SIZE_OFFSET);
+          // empty(offset + 10)
+          int type = entryData.get(offset + SIMPLE_VALUE_TYPE_OFFSET);
+          int data = entryData.getInt(offset + SIMPLE_VALUE_DATA_OFFSET);
+          out.format(" t=0x%02x d=0x%08x (s=0x%04x r=0x00)\n", type, data, vsize);
+          String dataString = formatTypeForDump(strings, type, data);
+          out.format("          %s\n", dataString);
+        }
+      }
+    }
+  }
+
+  private String getTypeName(ResTablePackage resPackage) {
+    return resPackage.getTypes().getString(id);
+  }
+
+  private String formatTypeForDump(StringPool strings, int type, int data) {
+    String typeString;
+    String dataString;
+    switch (type) {
+      case RES_REFERENCE:
+        typeString = "reference";
+        dataString = String.format("0x%08x", data);
+        break;
+      case RES_ATTRIBUTE:
+        typeString = "attribute";
+        dataString = String.format("0x%08x", data);
+        break;
+      case RES_STRING:
+        typeString = "string" + (strings.isUtf8() ? "8" : "16");
+        dataString = String.format("\"%s\"", strings.getOutputNormalizedString(data));
+        break;
+      case RES_FLOAT:
+        typeString = "float";
+        dataString = new DecimalFormat("0.######").format(Float.intBitsToFloat(data));
+        break;
+      case RES_DIMENSION:
+        typeString = "dimension";
+        dataString = formatComplex(data, false);
+        break;
+      case RES_FRACTION:
+        typeString = "fraction";
+        dataString = formatComplex(data, true);
+        break;
+      case RES_DECIMAL:
+      case RES_HEX:
+      case RES_BOOL:
+      case RES_COLOR_ARGB4:
+      case RES_COLOR_RGB4:
+      case RES_COLOR_ARGB8:
+      case RES_COLOR_RGB8:
+        typeString = "color";
+        dataString = String.format("#%08x", data);
+        break;
+      default:
+        typeString = String.format("unknown %02x", type);
+        dataString = String.format("xxx 0x%08x", data);
+    }
+    return String.format("(%s) %s", typeString, dataString);
+  }
+
+  private static final int RADIX_SHIFT = 4;
+  private static final int RADIX_MASK = 0x3;
+  private static final int MANTISSA_SHIFT = 8;
+  private static final int MANTISSA_MASK = 0xFFFFFF;
+  private static final int[] RADIX_MULTS = {0, 7, 15, 23};
+
+  private static final int UNIT_MASK = 0xF;
+
+  private static final int UNIT_PX = 0;
+  private static final int UNIT_DIP = 1;
+  private static final int UNIT_SP = 2;
+  private static final int UNIT_PT = 3;
+  private static final int UNIT_IN = 4;
+  private static final int UNIT_MM = 5;
+  private static final int UNIT_FRACTION = 0;
+  private static final int UNIT_FRACTION_PARENT = 1;
+
+  // See print_complex() at
+  // https://android.googlesource.com/platform/frameworks/base/+/kitkat-release/libs/androidfw/ResourceTypes.cpp
+  // The implementation there is really silly and results in different values if implemented in Java
+  // directly.
+  private String formatComplex(int data, boolean isFraction) {
+    int mantissa = (data >> MANTISSA_SHIFT) & MANTISSA_MASK;
+    int exp = RADIX_MULTS[(data >> RADIX_SHIFT) & RADIX_MASK];
+    float value = mantissa;
+    if (exp != 0) {
+      value = value / (1 << exp);
+    }
+    String unit;
+    if (isFraction) {
+      switch (data & UNIT_MASK) {
+        case UNIT_FRACTION:
+          unit = "%";
+          break;
+        case UNIT_FRACTION_PARENT:
+          unit = "%p";
+          break;
+        default:
+          unit = " (unknown unit)";
+          break;
+      }
+    } else {
+      switch (data & UNIT_MASK) {
+        case UNIT_PX:
+          unit = "px";
+          break;
+        case UNIT_DIP:
+          unit = "dp";
+          break;
+        case UNIT_SP:
+          unit = "sp";
+          break;
+        case UNIT_PT:
+          unit = "pt";
+          break;
+        case UNIT_IN:
+          unit = "in";
+          break;
+        case UNIT_MM:
+          unit = "mm";
+          break;
+        default:
+          unit = " (unknown unit)";
+          break;
+      }
+    }
+    return String.format("%f%s", value, unit);
+  }
+
+  int getResourceType() {
+    return id + 1;
+  }
+
+  public int getResourceRef(int id) {
+    int offset = getEntryValueOffset(id);
+    if (offset == -1) {
+      return -1;
+    }
+    return entryData.getInt(offset + ENTRY_KEY_OFFSET);
+  }
+
+  public int getEntryValueOffset(int i) {
+    return entryOffsets.getInt(i * 4);
+  }
+
+  public int getEntryCount() {
+    return entryCount;
+  }
+
+  public void transformKeyReferences(RefTransformer visitor) {
+    for (int i = 0; i < entryCount; i++) {
+      int offset = getEntryValueOffset(i);
+      if (offset != -1) {
+        transformEntryDataOffset(entryData, offset + ENTRY_KEY_OFFSET, visitor);
+      }
+    }
+  }
+
+  public void visitKeyReferences(RefVisitor visitor) {
+    for (int i = 0; i < entryCount; i++) {
+      int offset = getEntryValueOffset(i);
+      if (offset != -1) {
+        visitEntryDataOffset(entryData, offset + ENTRY_KEY_OFFSET, visitor);
+      }
+    }
+  }
+
+  private void transformStringReferencesAt(RefTransformer visitor, int offset) {
+    processStringReferencesAt(transformHandler(visitor), offset);
+  }
+
+  private void visitStringReferencesAt(RefVisitor visitor, int offset) {
+    processStringReferencesAt(visitHandler(visitor), offset);
+  }
+
+  private void processStringReferencesAt(RefHandler handler, int offset) {
+    int flags = entryData.getShort(offset + ENTRY_FLAGS_OFFSET);
+    if ((flags & FLAG_COMPLEX) != 0) {
+      int count = entryData.getInt(offset + COMPLEX_COUNT_OFFSET);
+      int entryOffset = offset;
+      for (int j = 0; j < count; j++) {
+        int name = entryData.getInt(entryOffset + MAP_ENTRY_NAME_OFFSET);
+        if ((name >> 24) == ResTablePackage.APP_PACKAGE_ID) {
+          Preconditions.checkState(((name >> 16) & 0xFF) != 0);
+        }
+        int vsize = entryData.getShort(entryOffset + MAP_ENTRY_VALUE_SIZE_OFFSET);
+        int type = entryData.get(entryOffset + MAP_ENTRY_VALUE_TYPE_OFFSET);
+        if (type == RES_STRING) {
+          handler.process(entryData, entryOffset + MAP_ENTRY_VALUE_DATA_OFFSET);
+        }
+        entryOffset += 4 + vsize;
+      }
+    } else {
+      int type = entryData.get(offset + SIMPLE_VALUE_TYPE_OFFSET);
+      if (type == RES_STRING) {
+        handler.process(entryData, offset + SIMPLE_VALUE_DATA_OFFSET);
+      }
+    }
+  }
+
+  public void transformStringReferences(RefTransformer visitor) {
+    for (int i = 0; i < entryCount; i++) {
+      int offset = getEntryValueOffset(i);
+      if (offset != -1) {
+        transformStringReferencesAt(visitor, offset);
+      }
+    }
+  }
+
+  public void transformStringReferences(int[] idsToVisit, RefTransformer visitor) {
+    for (int i : idsToVisit) {
+      int offset = getEntryValueOffset(i);
+      if (offset != -1) {
+        transformStringReferencesAt(visitor, offset);
+      }
+    }
+  }
+
+  public void visitStringReferences(RefVisitor visitor) {
+    for (int i = 0; i < entryCount; i++) {
+      int offset = getEntryValueOffset(i);
+      if (offset != -1) {
+        visitStringReferencesAt(visitor, offset);
+      }
+    }
+  }
+
+  public void visitStringReferences(int[] idsToVisit, RefVisitor visitor) {
+    for (int i : idsToVisit) {
+      int offset = getEntryValueOffset(i);
+      if (offset != -1) {
+        visitStringReferencesAt(visitor, offset);
+      }
+    }
+  }
+
+  private void transformReferencesAt(RefTransformer visitor, int offset) {
+    processReferencesAt(transformHandler(visitor), offset, true);
+  }
+
+  private void visitReferencesAt(RefVisitor visitor, int offset) {
+    processReferencesAt(visitHandler(visitor), offset, false);
+  }
+
+  private void processReferencesAt(RefHandler handler, int offset, boolean sortAttrs) {
+    int flags = entryData.getShort(offset + ENTRY_FLAGS_OFFSET);
+    if ((flags & FLAG_COMPLEX) != 0) {
+      int parent = entryData.getInt(offset + COMPLEX_PARENT_OFFSET);
+      if (parent != 0) {
+        handler.process(entryData, offset + COMPLEX_PARENT_OFFSET);
+      }
+      int count = entryData.getInt(offset + COMPLEX_COUNT_OFFSET);
+      int entryStart = offset + COMPLEX_ENTRIES_START_OFFSET;
+      int entryOffset = entryStart;
+      for (int j = 0; j < count; j++) {
+        handler.process(entryData, entryOffset + ATTRIBUTE_NAME_REF_OFFSET);
+        int type = entryData.get(entryOffset + ATTRIBUTE_TYPE_OFFSET);
+        if (type == RES_REFERENCE || type == RES_ATTRIBUTE) {
+          handler.process(entryData, entryOffset + ATTRIBUTE_DATA_OFFSET);
+        } else if (type == RES_DYNAMIC_REFERENCE || type == RES_DYNAMIC_ATTRIBUTE) {
+          throw new UnsupportedOperationException();
+        }
+        int size = entryData.getShort(entryOffset + ATTRIBUTE_SIZE_OFFSET);
+        entryOffset += 4 + size;
+      }
+      if (sortAttrs) {
+        sortAttributesAt(entryData, count, entryStart);
+      }
+    } else {
+      int type = entryData.get(offset + SIMPLE_VALUE_TYPE_OFFSET);
+      if (type == RES_REFERENCE || type == RES_ATTRIBUTE) {
+        handler.process(entryData, offset + SIMPLE_VALUE_DATA_OFFSET);
+      } else if (type == RES_DYNAMIC_REFERENCE || type == RES_DYNAMIC_ATTRIBUTE) {
+        throw new UnsupportedOperationException();
+      }
+    }
+  }
+
+  private void sortAttributesAt(ByteBuffer entryData, int attrCount, int attrStart) {
+    class AttrRef implements Comparable<AttrRef> {
+      final int offset;
+      final int size;
+      final int resId;
+
+      AttrRef(int offset) {
+        this.offset = offset;
+        this.resId = entryData.getInt(offset + ATTRIBUTE_NAME_REF_OFFSET);
+        this.size = 4 + entryData.getShort(offset + ATTRIBUTE_SIZE_OFFSET);
+      }
+
+      @Override
+      public int compareTo(AttrRef other) {
+        return Integer.compare(resId, other.resId);
+      }
+    }
+
+    AttrRef[] refs = new AttrRef[attrCount];
+    int entryOffset = attrStart;
+    for (int j = 0; j < attrCount; j++) {
+      refs[j] = new AttrRef(entryOffset);
+      entryOffset += refs[j].size;
+    }
+    Arrays.sort(refs);
+    byte[] newData = new byte[entryOffset - attrStart];
+    ByteBuffer newBuf = wrap(newData);
+    for (AttrRef ref : refs) {
+      newBuf.put(slice(entryData, ref.offset, ref.size));
+    }
+    slice(entryData, attrStart).put(newData);
+  }
+
+  public void transformReferences(RefTransformer visitor) {
+    for (int i = 0; i < entryCount; i++) {
+      int offset = getEntryValueOffset(i);
+      if (offset != -1) {
+        transformReferencesAt(visitor, offset);
+      }
+    }
+  }
+
+  public void transformReferences(int[] ids, RefTransformer visitor) {
+    for (int i : ids) {
+      int offset = getEntryValueOffset(i);
+      if (offset != -1) {
+        transformReferencesAt(visitor, offset);
+      }
+    }
+  }
+
+  public void visitReferences(int[] ids, RefVisitor visitor) {
+    for (int i : ids) {
+      int offset = getEntryValueOffset(i);
+      if (offset != -1) {
+        visitReferencesAt(visitor, offset);
+      }
+    }
+  }
+
+  public void reassignIds(ReferenceMapper refMapping) {
+    transformReferences(refMapping::map);
+    refMapping.rewrite(getResourceType(), entryOffsets.asIntBuffer());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTableTypeSpec.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTableTypeSpec.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResTableTypeSpec.java
@@ -0,0 +1,193 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import java.io.PrintStream;
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * ResTableTypeSpec is a ResChunk specifying the flags for each resource of a given type. These
+ * flags specify which types of configuration contain multiple values for a given resource. A
+ * ResTableTypeSpec consists of: ResChunk_header u16 type u16 header_size u32 chunk_size u8 id u8
+ * 0x00 u16 0x0000 u32 entry_count
+ *
+ * <p>This is then followed by entry_count u32s giving the flags for each resource of this type.
+ *
+ * <p>In practice, this is then followed by a ResTableType for each configuration that has resources
+ * of this type. For convenience, those are considered to be part of the ResTableTypeSpec.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ResTableTypeSpec extends ResChunk {
+  private static final int HEADER_SIZE = 16;
+
+  private final int id;
+  private final int entryCount;
+  private final List<ResTableType> configs;
+  private final int totalSize;
+  private final ByteBuffer entryFlags;
+
+  public static ResTableTypeSpec slice(ResTableTypeSpec spec, int count) {
+    ImmutableList<ResTableType> configs =
+        spec.getConfigs().stream()
+            .map(config -> ResTableType.slice(config, count))
+            .filter(Objects::nonNull)
+            .collect(ImmutableList.toImmutableList());
+
+    return new ResTableTypeSpec(
+        spec.id, count, copy(slice(spec.entryFlags, 0, 4 * count)), configs);
+  }
+
+  @Override
+  public void put(ByteBuffer output) {
+    Preconditions.checkState(output.remaining() >= totalSize);
+    int start = output.position();
+    putChunkHeader(output);
+    output.put((byte) (id + 1));
+    output.put((byte) 0);
+    output.putShort((short) 0);
+    output.putInt(entryCount);
+    output.put(slice(entryFlags, 0));
+    configs.forEach(c -> c.put(output));
+    Preconditions.checkState(output.position() == start + totalSize);
+  }
+
+  public static ResTableTypeSpec get(ByteBuffer buf) {
+    int type = buf.getShort();
+    int headerSize = buf.getShort();
+    int chunkSize = buf.getInt();
+    int id = (buf.get() & 0xFF) - 1;
+    buf.get();
+    buf.getShort();
+    int entryCount = buf.getInt();
+    // ignored u8
+    // ignored u16
+    Preconditions.checkState(type == CHUNK_RES_TABLE_TYPE_SPEC);
+    Preconditions.checkState(headerSize == HEADER_SIZE);
+    Preconditions.checkState(chunkSize == HEADER_SIZE + 4 * entryCount);
+
+    return new ResTableTypeSpec(
+        id,
+        entryCount,
+        slice(buf, HEADER_SIZE, 4 * entryCount),
+        getConfigsFromBuffer(slice(buf, chunkSize)));
+  }
+
+  private ResTableTypeSpec(
+      int id, int entryCount, ByteBuffer entryFlags, List<ResTableType> configs) {
+    super(CHUNK_RES_TABLE_TYPE_SPEC, HEADER_SIZE, HEADER_SIZE + 4 * entryCount);
+    this.id = id;
+    this.entryCount = entryCount;
+    this.entryFlags = entryFlags;
+    this.configs = configs;
+    int configsSize = 0;
+    for (ResTableType config : configs) {
+      Preconditions.checkState(getResourceType() == config.getResourceType());
+      configsSize += config.getChunkSize();
+    }
+    this.totalSize = getChunkSize() + configsSize;
+  }
+
+  private static List<ResTableType> getConfigsFromBuffer(ByteBuffer buf) {
+    ImmutableList.Builder<ResTableType> configs = ImmutableList.builder();
+    while (buf.position() < buf.limit() && buf.getShort(buf.position()) == 0x201) {
+      ResTableType config = ResTableType.get(slice(buf, buf.position()));
+      configs.add(config);
+      buf.position(buf.position() + config.getChunkSize());
+    }
+    return configs.build();
+  }
+
+  @Override
+  public int getTotalSize() {
+    return totalSize;
+  }
+
+  String getResourceName(ResTablePackage resPackage, int id) {
+    // We need to find an actual entry in one of the configs to find the name of this resource.
+    for (ResTableType t : configs) {
+      int refId = t.getResourceRef(id);
+      if (refId >= 0) {
+        return resPackage.getKeys().getString(refId);
+      }
+    }
+    throw new RuntimeException();
+  }
+
+  public String getResourceTypeName(ResTablePackage resPackage) {
+    return resPackage.getTypes().getString(id);
+  }
+
+  public void dump(StringPool strings, ResTablePackage resPackage, PrintStream out) {
+    if (entryCount == 0) {
+      return;
+    }
+    out.format("    type %d configCount=%d entryCount=%d\n", id, configs.size(), entryCount);
+    for (int i = 0; i < entryCount; i++) {
+      out.format(
+          "      spec resource 0x7f%02x%04x %s:%s/%s: flags=0x%08x\n",
+          getResourceType(),
+          i,
+          resPackage.getPackageName(),
+          getResourceTypeName(resPackage),
+          getResourceName(resPackage, i),
+          entryFlags.getInt(i * 4));
+    }
+    for (ResTableType type : configs) {
+      type.dump(strings, resPackage, out);
+    }
+  }
+
+  public int getResourceType() {
+    return id + 1;
+  }
+
+  public List<ResTableType> getConfigs() {
+    return configs;
+  }
+
+  public void transformKeyReferences(RefTransformer visitor) {
+    configs.forEach(c -> c.transformKeyReferences(visitor));
+  }
+
+  public void visitKeyReferences(RefVisitor visitor) {
+    configs.forEach(c -> c.visitKeyReferences(visitor));
+  }
+
+  public void transformStringReferences(RefTransformer visitor) {
+    configs.forEach(c -> c.transformStringReferences(visitor));
+  }
+
+  public void visitStringReferences(RefVisitor visitor) {
+    configs.forEach(c -> c.visitStringReferences(visitor));
+  }
+
+  public void visitStringReferences(int[] ids, RefVisitor visitor) {
+    configs.forEach(c -> c.visitStringReferences(ids, visitor));
+  }
+
+  public void visitReferences(int[] ids, RefVisitor visitor) {
+    configs.forEach(c -> c.visitReferences(ids, visitor));
+  }
+
+  public void reassignIds(ReferenceMapper refMapping) {
+    refMapping.rewrite(getResourceType(), entryFlags.asIntBuffer());
+    configs.forEach(c -> c.reassignIds(refMapping));
+  }
+
+  public int getEntryCount() {
+    return entryCount;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourceTable.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourceTable.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourceTable.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.collect.Maps;
+import java.io.PrintStream;
+import java.nio.ByteBuffer;
+import java.util.Comparator;
+import java.util.Map;
+import java.util.stream.IntStream;
+
+/**
+ * A ResourceTable is the top-level representation of resources.arsc. It consists of a header:
+ * ResTable_header u32 chunk_type u32 header_size u32 chunk_size u32 package_count
+ *
+ * <p>The header is followed by a StringPool and then package_count packages.
+ *
+ * <p>In practice, aapt always generates .arsc files with package_count == 1.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ResourceTable extends ResChunk {
+  public static final int HEADER_SIZE = 12;
+
+  private final StringPool strings;
+  private final ResTablePackage resPackage;
+
+  public ResourceTable(StringPool strings, ResTablePackage resPackage) {
+    super(
+        CHUNK_RESOURCE_TABLE,
+        HEADER_SIZE,
+        HEADER_SIZE + strings.getChunkSize() + resPackage.getChunkSize());
+    this.strings = strings;
+    this.resPackage = resPackage;
+  }
+
+  public static ResourceTable get(ByteBuffer buf) {
+    int type = buf.getShort();
+    int headerSize = buf.getShort();
+    int chunkSize = buf.getInt();
+    int packageCount = buf.getInt();
+
+    Preconditions.checkState(type == CHUNK_RESOURCE_TABLE);
+    Preconditions.checkState(headerSize == HEADER_SIZE);
+    Preconditions.checkState(packageCount == 1);
+
+    StringPool strings = StringPool.get(slice(buf, buf.position()));
+    ResTablePackage resPackage =
+        ResTablePackage.get(slice(buf, HEADER_SIZE + strings.getChunkSize()));
+
+    Preconditions.checkState(
+        chunkSize == HEADER_SIZE + strings.getChunkSize() + resPackage.getChunkSize());
+
+    return new ResourceTable(strings, resPackage);
+  }
+
+  @Override
+  public void put(ByteBuffer buf) {
+    putChunkHeader(buf);
+    buf.putInt(1); // packageCount
+    Preconditions.checkState(buf.position() == HEADER_SIZE);
+    strings.put(buf);
+    Preconditions.checkState(buf.position() == HEADER_SIZE + strings.getChunkSize());
+    resPackage.put(buf);
+  }
+
+  public void reassignIds(ReferenceMapper refMapping) {
+    resPackage.reassignIds(refMapping);
+  }
+
+  public static ResourceTable slice(ResourceTable table, Map<Integer, Integer> countsToExtract) {
+    ResTablePackage newPackage = ResTablePackage.slice(table.resPackage, countsToExtract);
+
+    StringPool strings = table.strings;
+    // Figure out what strings are used by the retained references.
+    ImmutableSortedSet.Builder<Integer> stringRefs =
+        ImmutableSortedSet.orderedBy(
+            Comparator.comparing(strings::getString).thenComparingInt(i -> i));
+    newPackage.visitStringReferences(stringRefs::add);
+    ImmutableList<Integer> stringsToExtract = stringRefs.build().asList();
+    ImmutableMap<Integer, Integer> stringMapping =
+        Maps.uniqueIndex(
+            IntStream.range(0, stringsToExtract.size())::iterator, stringsToExtract::get);
+
+    // Extract a StringPool that contains just the strings used by the new package.
+    // This drops styles.
+    StringPool newStrings =
+        StringPool.create(stringsToExtract.stream().map(strings::getString)::iterator);
+
+    // Adjust the string references.
+    newPackage.transformStringReferences(stringMapping::get);
+
+    return new ResourceTable(newStrings, newPackage);
+  }
+
+  public void dump(PrintStream out) {
+    out.format("Package Groups (1)\n");
+    resPackage.dump(strings, out);
+  }
+
+  public StringPool getStrings() {
+    return strings;
+  }
+
+  public ResTablePackage getPackage() {
+    return resPackage;
+  }
+
+  public void dumpStrings(PrintStream out) {
+    strings.dump(out);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourcesXml.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourcesXml.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourcesXml.java
@@ -0,0 +1,387 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import java.io.PrintStream;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * ResourcesXml handles Android's compiled xml format. It consists of: ResChunk_header u16
+ * chunk_type u16 header_size u32 chunk_size
+ *
+ * <p>The header is followed by a StringPool containing all the strings used in the xml. This is
+ * then followed by an optional RefMap. After the StringPool/RefMap comes a list of xml nodes of the
+ * form: ResChunk_header u16 chunk_type u16 header_size u32 chunk_size u32 lineNumber StringRef
+ * comment
+ *
+ * <p>Each node contains extra information depending on the type:
+ *
+ * <p>XML_START_NS: StringRef prefix StringRef uri
+ *
+ * <p>XML_END_NS: StringRef prefix StringRef uri
+ *
+ * <p>XML_CDATA: StringRef data Res_value typedData
+ *
+ * <p>XML_END_ELEMENT: StringRef namespace StringRef name
+ *
+ * <p>XML_START_ELEMENT: StringRef namespace StringRef name u16 attrStart u16 attrSize u16 attrCount
+ * u16 idIndex u16 classIndex u16 styleIndex
+ *
+ * <p>XML_START_ELEMENT is then followed by attrCount attributes of the form: StringRef namespace
+ * StringRef name StringRef rawValue Res_value typedValue
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ResourcesXml extends ResChunk {
+  private static final boolean DEBUG = false;
+
+  public static final int HEADER_SIZE = 8;
+
+  private static final int XML_FIRST_TYPE = 0x100;
+  private static final int XML_START_NS = 0x100;
+  private static final int XML_END_NS = 0x101;
+  private static final int XML_START_ELEMENT = 0x102;
+  private static final int XML_END_ELEMENT = 0x103;
+  private static final int XML_CDATA = 0x104;
+  private static final int XML_LAST_TYPE = 0x104;
+  public static final int ATTRIBUTE_SIZE = 20;
+
+  private final StringPool strings;
+  private final Optional<RefMap> refMap;
+  private final ByteBuffer nodeBuf;
+
+  public static ResourcesXml get(ByteBuffer buf) {
+    int type = buf.getShort();
+    int headerSize = buf.getShort();
+    int chunkSize = buf.getInt();
+
+    Preconditions.checkState(type == CHUNK_XML_TREE);
+    Preconditions.checkState(headerSize == HEADER_SIZE);
+    Preconditions.checkState(chunkSize == buf.limit());
+
+    // The header should be immediately followed by a string pool.
+    StringPool strings = StringPool.get(slice(buf, HEADER_SIZE));
+    buf.position(HEADER_SIZE + strings.getChunkSize());
+
+    int nextType = buf.getShort(buf.position());
+    Optional<RefMap> refMap = Optional.empty();
+    if (nextType == ResChunk.CHUNK_XML_REF_MAP) {
+      RefMap map = new RefMap(slice(buf, buf.position()));
+      refMap = Optional.of(map);
+      buf.position(buf.position() + map.getChunkSize());
+    }
+
+    int position = buf.position();
+    while (position < buf.limit()) {
+      nextType = buf.getShort(position);
+      Preconditions.checkState(
+          nextType >= XML_FIRST_TYPE && nextType <= XML_LAST_TYPE, "Got: " + nextType);
+      position += buf.getInt(position + 4);
+    }
+    Preconditions.checkState(position == buf.limit());
+    return new ResourcesXml(buf.limit(), strings, refMap, slice(buf, buf.position()));
+  }
+
+  @Override
+  public void put(ByteBuffer buf) {
+    putChunkHeader(buf);
+    strings.put(buf);
+    refMap.ifPresent(m -> m.put(buf));
+    buf.put(slice(nodeBuf, 0));
+  }
+
+  private ResourcesXml(
+      int chunkSize, StringPool strings, Optional<RefMap> refMap, ByteBuffer nodeBuf) {
+    super(CHUNK_XML_TREE, HEADER_SIZE, chunkSize);
+    this.strings = strings;
+    this.refMap = refMap;
+    this.nodeBuf = nodeBuf;
+  }
+
+  public void transformReferences(RefTransformer visitor) {
+    // Make sure to rewrite the refMap first so that fixupAttrs works correctly.
+    refMap.ifPresent(m -> m.visitReferences(visitor));
+    int offset = 0;
+    while (offset < nodeBuf.limit()) {
+      int type = nodeBuf.getShort(offset);
+      if (type == XML_START_ELEMENT) {
+        int nodeHeaderSize = nodeBuf.getShort(offset + 2);
+
+        int extOffset = offset + nodeHeaderSize;
+        int attrStart = extOffset + nodeBuf.getShort(extOffset + 8);
+        Preconditions.checkState(attrStart == extOffset + 20);
+        if (DEBUG) {
+          int attrSize = nodeBuf.getShort(extOffset + 10);
+          Preconditions.checkState(attrSize == ATTRIBUTE_SIZE);
+        }
+        int attrCount = nodeBuf.getShort(extOffset + 12);
+        for (int i = 0; i < attrCount; i++) {
+          int attrOffset = attrStart + i * ATTRIBUTE_SIZE;
+          int attrType = nodeBuf.get(attrOffset + 15);
+          switch (attrType) {
+            case RES_REFERENCE:
+            case RES_ATTRIBUTE:
+              transformEntryDataOffset(nodeBuf, attrOffset + 16, visitor);
+              break;
+            case RES_DYNAMIC_ATTRIBUTE:
+            case RES_DYNAMIC_REFERENCE:
+              throw new UnsupportedOperationException();
+            default:
+              break;
+          }
+        }
+        fixupAttrs(attrStart, attrCount);
+      }
+      int chunkSize = nodeBuf.getInt(offset + 4);
+      offset += chunkSize;
+    }
+  }
+
+  private int getAttributeNameResId(int attrOffset) {
+    if (!refMap.isPresent()) {
+      return -1;
+    }
+    int id = nodeBuf.getInt(attrOffset + 4);
+    return refMap.get().getRef(id);
+  }
+
+  // Android resource handling makes several assumptions about xml node attribute ordering:
+  //
+  // > 1) The input has the same sorting rules applied to it as
+  // >    the attribute data contained by this class.
+  // > 2) Attributes are grouped by package ID.
+  // > 3) Among attributes with the same package ID, the attributes are
+  // >    sorted by increasing resource ID.
+  //
+  // After reassigning ids, we need to make sure that these assumptions still
+  // hold.
+  //
+  // See
+  // https://android.googlesource.com/platform/frameworks/base/+/nougat-release/include/androidfw/AttributeFinder.h
+  //
+  // If there's no refmap, this doesn't ensure that the attributes are sorted correctly, but in
+  // that case, Android doesn't need them sorted anyway.
+  private void fixupAttrs(int attrStart, int attrCount) {
+    if (!refMap.isPresent()) {
+      return;
+    }
+
+    while (attrCount > 0 && getAttributeNameResId(attrStart) == -1) {
+      --attrCount;
+      attrStart += ATTRIBUTE_SIZE;
+    }
+
+    while (attrCount > 0
+        && getAttributeNameResId(attrStart + ATTRIBUTE_SIZE * (attrCount - 1)) == -1) {
+      --attrCount;
+    }
+
+    if (attrCount < 2) {
+      return;
+    }
+
+    class AttrRef implements Comparable<AttrRef> {
+      final int offset;
+      final int resId;
+
+      AttrRef(int offset) {
+        this.offset = offset;
+        this.resId = getAttributeNameResId(offset);
+      }
+
+      @Override
+      public int compareTo(AttrRef other) {
+        return Integer.compare(resId, other.resId);
+      }
+    }
+
+    AttrRef[] refs = new AttrRef[attrCount];
+    for (int i = 0; i < attrCount; i++) {
+      refs[i] = new AttrRef(attrStart + ATTRIBUTE_SIZE * i);
+    }
+    Arrays.sort(refs);
+    byte[] newData = new byte[ATTRIBUTE_SIZE * attrCount];
+    ByteBuffer newBuf = wrap(newData);
+    for (AttrRef ref : refs) {
+      newBuf.put(slice(nodeBuf, ref.offset, ATTRIBUTE_SIZE));
+    }
+    slice(nodeBuf, attrStart).put(newData);
+  }
+
+  public void visitReferences(RefVisitor visitor) {
+    transformReferences(
+        i -> {
+          visitor.visit(i);
+          return i;
+        });
+  }
+
+  public void dump(PrintStream out) {
+    int indent = 0;
+    Map<String, String> nsMap = new HashMap<>();
+    nodeBuf.position(0);
+    while (nodeBuf.position() < nodeBuf.limit()) {
+      int nodeSize = nodeBuf.get(nodeBuf.position() + 4) & 0xFF;
+      indent =
+          dumpNode(
+              out, strings, refMap, indent, nsMap, slice(nodeBuf, nodeBuf.position(), nodeSize));
+      nodeBuf.position(nodeBuf.position() + nodeSize);
+    }
+  }
+
+  private static int dumpNode(
+      PrintStream out,
+      StringPool strings,
+      Optional<RefMap> refMap,
+      int indent,
+      Map<String, String> nsMap,
+      ByteBuffer buf) {
+    int type = buf.getShort(0);
+    Preconditions.checkState(type >= XML_FIRST_TYPE && type <= XML_LAST_TYPE);
+    switch (type) {
+      case XML_START_NS:
+        {
+          // start namespace
+          int prefixId = buf.getInt(16);
+          String prefix = prefixId == -1 ? "" : strings.getString(prefixId);
+          int uriId = buf.getInt(20);
+          String uri = strings.getString(uriId);
+          out.format("%sN: %s=%s\n", Strings.padEnd("", indent * 2, ' '), prefix, uri);
+          indent++;
+          nsMap.put(uri, prefix);
+          break;
+        }
+      case XML_END_NS:
+        indent--;
+        break;
+      case XML_START_ELEMENT:
+        {
+          // start element
+          int lineNumber = buf.getInt(8);
+          int nameId = buf.getInt(20);
+          String name = strings.getString(nameId);
+          int attrCount = buf.getShort(28);
+          ByteBuffer attrExt = slice(buf, 36);
+          out.format("%sE: %s (line=%d)\n", Strings.padEnd("", indent * 2, ' '), name, lineNumber);
+          indent++;
+          for (int i = 0; i < attrCount; i++) {
+            dumpAttribute(out, strings, refMap, slice(attrExt, attrExt.position()), indent, nsMap);
+            attrExt.position(attrExt.position() + 20);
+          }
+          break;
+        }
+      case XML_END_ELEMENT:
+        indent--;
+        break;
+      case XML_CDATA:
+        throw new UnsupportedOperationException();
+    }
+    return indent;
+  }
+
+  public StringPool getStrings() {
+    return strings;
+  }
+
+  private static void dumpAttribute(
+      PrintStream out,
+      StringPool strings,
+      Optional<RefMap> refMap,
+      ByteBuffer buf,
+      int indent,
+      Map<String, String> nsMap) {
+    int nsId = buf.getInt(0);
+    String namespace = nsId == -1 ? "" : strings.getString(nsId);
+    String shortNs = nsMap.get(namespace);
+    int nameIndex = buf.getInt(4);
+    String name = strings.getString(nameIndex);
+    int resValue = refMap.map(ref -> ref.getRef(nameIndex)).orElse(-1);
+    int rawValueIndex = buf.getInt(8);
+    String rawValue = rawValueIndex < 0 ? null : strings.getOutputNormalizedString(rawValueIndex);
+    int attrType = buf.get(15);
+    int data = buf.getInt(16);
+    String dumpValue = getValueForDump(strings, rawValue, attrType, data);
+    out.format(
+        "%sA: %s%s%s=%s%s\n",
+        Strings.padEnd("", indent * 2, ' '),
+        shortNs == null ? "" : shortNs + ":",
+        name,
+        resValue == -1 ? "" : String.format("(0x%08x)", resValue),
+        dumpValue,
+        rawValue == null ? "" : String.format(" (Raw: \"%s\")", rawValue));
+  }
+
+  @Nullable
+  private static String getValueForDump(
+      StringPool strings, @Nullable String rawValue, int attrType, int data) {
+    switch (attrType) {
+      case RES_REFERENCE:
+        return String.format("@0x%x", data);
+      case RES_STRING:
+        return String.format("\"%s\"", strings.getString(data).replace("\\", "\\\\"));
+      case RES_FLOAT:
+      case RES_DECIMAL:
+      case RES_HEX:
+      case RES_BOOL:
+        return String.format("(type 0x%x)0x%x", attrType, data);
+      case RES_DYNAMIC_ATTRIBUTE:
+      case RES_DYNAMIC_REFERENCE:
+        throw new UnsupportedOperationException();
+      default:
+        return rawValue;
+    }
+  }
+
+  /**
+   * A RefMap is an optional entry in a compiled xml that provides the reference ids for some of the
+   * strings in the stringpool. It consists of ResTable_header u32 chunk_type u32 header_size u32
+   * chunk_size
+   *
+   * <p>The header is followed by an array of u32 ids of size (chunk_size - header_size) / 4. Each
+   * entry is the reference id for the string with the same position in the string pool.
+   */
+  private static class RefMap extends ResChunk {
+    private final ByteBuffer buf;
+    private final int refCount;
+
+    RefMap(ByteBuffer buf) {
+      super(buf.getShort(), buf.getShort(), buf.getInt());
+      this.buf = slice(buf, 0, getChunkSize());
+      this.refCount = (getChunkSize() - getHeaderSize()) / 4;
+      Preconditions.checkState(refCount >= 0);
+    }
+
+    @Override
+    public void put(ByteBuffer output) {
+      output.put(slice(buf, 0));
+    }
+
+    int getRef(int index) {
+      if (index < refCount) {
+        return buf.getInt(getHeaderSize() + index * 4);
+      }
+      return -1;
+    }
+
+    public void visitReferences(RefTransformer visitor) {
+      for (int i = 0; i < refCount; i++) {
+        transformEntryDataOffset(buf, getHeaderSize() + i * 4, visitor);
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourcesZipBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourcesZipBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/ResourcesZipBuilder.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.buck.util.zip.DeterministicZipBuilder;
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.ByteArrayInputStream;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.util.zip.CRC32;
+import java.util.zip.Deflater;
+
+/**
+ * Some versions of Android require that any zip file that contains resources/assets contains an
+ * AndroidManifest.xml (though it doesn't actually read it). This is just a zip builder that will
+ * add an empty (*) manifest if none has been added when it is closed.
+ *
+ * <p>See
+ * https://android.googlesource.com/platform/frameworks/base/+/lollipop-release/libs/androidfw/AssetManager.cpp#209
+ *
+ * <p>(*) Due to a bug in Android's zip handling, we actually create a 1-byte manifest... See
+ * https://android.googlesource.com/platform/system/core/+/48953a1b8fdcf1d6fa1aeeb40c57821d33fc87d2
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ResourcesZipBuilder implements Closeable {
+  public static final String ANDROID_MANIFEST_XML = "AndroidManifest.xml";
+  private boolean needsManifest;
+  private DeterministicZipBuilder builder;
+
+  public ResourcesZipBuilder(Path path) throws IOException {
+    this(path, true);
+  }
+
+  public ResourcesZipBuilder(Path path, boolean addManifestIfMissing) throws IOException {
+    builder = new DeterministicZipBuilder(path);
+    needsManifest = addManifestIfMissing;
+  }
+
+  public void addEntry(
+      InputStream stream,
+      long size,
+      long crc,
+      String name,
+      int compressionLevel,
+      boolean isDirectory)
+      throws IOException {
+    builder.addEntry(stream, size, crc, name, compressionLevel, isDirectory);
+    if (name.equals(ANDROID_MANIFEST_XML)) {
+      needsManifest = false;
+    }
+  }
+
+  /**
+   * Adds a pre-compressed entry to the zip without decompressing or re-compressing. The raw
+   * compressed bytes are written directly to the output.
+   */
+  public void addRawEntry(
+      InputStream compressedData,
+      long compressedSize,
+      long uncompressedSize,
+      long crc,
+      int method,
+      String name)
+      throws IOException {
+    builder.addRawEntry(compressedData, compressedSize, uncompressedSize, crc, method, name);
+    if (name.equals(ANDROID_MANIFEST_XML)) {
+      needsManifest = false;
+    }
+  }
+
+  @Override
+  public void close() throws IOException {
+    if (needsManifest) {
+      byte[] data = new byte[1];
+      CRC32 crc32 = new CRC32();
+      crc32.update(data);
+      addEntry(
+          new ByteArrayInputStream(data),
+          1,
+          crc32.getValue(),
+          ANDROID_MANIFEST_XML,
+          Deflater.NO_COMPRESSION,
+          false);
+    }
+    builder.close();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/StringPool.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/StringPool.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/StringPool.java
@@ -0,0 +1,265 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+/**
+ * A StringPool consists of a header: ResChunk_header u32 chunk_type u32 header_size u32 chunk_size
+ * u32 string_count u32 style_count u32 flags - 0x1 sorted, 0x100 utf-8 encoded u32 strings_start -
+ * byte offset from the beginning to the style data u32 styles_start - byte offset from the
+ * beginning to the style data
+ *
+ * <p>The header is followed by an u32[string_count] array of strings offsets (relative to
+ * strings_start) where the strings reside. This is then followed by a similar array for styles.
+ *
+ * <p>In a utf-8 encoded string pool, a string data consists of: utf-16 length, utf-8 length, string
+ * bytes, \0.
+ *
+ * <p>In a utf-16 encoded string pool, a string data consists of: utf-16 length, string bytes, \0\0.
+ *
+ * <p>A style is an array of tuples (u32 stringref, u32 start, u32 end). A stringref of 0xFFFFFFFF
+ * indicates the end of a style array (note that the next array may start at the immediately
+ * following word).
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class StringPool extends ResChunk {
+  private static final short HEADER_SIZE = 28;
+  private static final int SORTED_FLAG = 0x1;
+  private static final int UTF8_FLAG = 0x100;
+
+  private final int stringCount;
+  private final int styleCount;
+  private final boolean utf8;
+  private final boolean sorted;
+  private final ByteBuffer stringOffsets;
+  private final ByteBuffer styleOffsets;
+  private final ByteBuffer stringData;
+  private final ByteBuffer styleData;
+
+  private StringPool(
+      int stringCount,
+      int styleCount,
+      boolean utf8,
+      boolean sorted,
+      ByteBuffer stringOffsets,
+      ByteBuffer styleOffsets,
+      ByteBuffer stringData,
+      ByteBuffer styleData) {
+    super(
+        CHUNK_STRING_POOL,
+        HEADER_SIZE,
+        HEADER_SIZE
+            + stringOffsets.limit()
+            + styleOffsets.limit()
+            + stringData.limit()
+            + styleData.limit());
+    this.stringCount = stringCount;
+    this.styleCount = styleCount;
+    this.utf8 = utf8;
+    this.sorted = sorted;
+    this.stringOffsets = stringOffsets;
+    this.styleOffsets = styleOffsets;
+    this.stringData = stringData;
+    this.styleData = styleData;
+  }
+
+  public static StringPool create(Iterable<String> strings) {
+    List<String> stringsList = ImmutableList.copyOf(strings);
+    int stringCount = stringsList.size();
+
+    ByteBuffer stringOffsets = wrap(new byte[4 * stringCount]);
+    ByteArrayOutputStream stringData = new ByteArrayOutputStream();
+
+    byte[] encodedLength = new byte[4];
+    ByteBuffer lengthBuf = wrap(encodedLength);
+    for (int i = 0; i < stringsList.size(); i++) {
+      lengthBuf.position(0);
+      String value = stringsList.get(i);
+      putEncodedLength(lengthBuf, value.length());
+      ByteBuffer encoded = StandardCharsets.UTF_8.encode(value);
+      putEncodedLength(lengthBuf, encoded.limit());
+
+      stringOffsets.putInt(i * 4, stringData.size());
+      stringData.write(encodedLength, 0, lengthBuf.position());
+      stringData.write(encoded.array(), encoded.arrayOffset(), encoded.limit());
+      stringData.write(0);
+    }
+
+    // Pad to 4-byte boundary.
+    lengthBuf.putInt(0, 0);
+    stringData.write(encodedLength, 0, (4 - (stringData.size() % 4)) % 4);
+
+    return new StringPool(
+        stringCount,
+        0,
+        true,
+        false,
+        stringOffsets,
+        wrap(new byte[0]),
+        wrap(stringData.toByteArray()),
+        wrap(new byte[0]));
+  }
+
+  private static void putEncodedLength(ByteBuffer buf, int length) {
+    if (length < (1 << 7)) {
+      buf.put((byte) length);
+    } else {
+      buf.put((byte) ((1 << 7) | (length >> 8)));
+      buf.put((byte) (length & 0xFF));
+    }
+  }
+
+  public static StringPool get(ByteBuffer buf) {
+    int type = buf.getShort();
+    int headerSize = buf.getShort();
+    int chunkSize = buf.getInt();
+    int stringCount = buf.getInt();
+    int styleCount = buf.getInt();
+    int flags = buf.getInt();
+    boolean utf8 = (flags & UTF8_FLAG) != 0;
+    boolean sorted = (flags & SORTED_FLAG) != 0;
+    int stringsStart = buf.getInt();
+    int stylesStart = buf.getInt();
+
+    Preconditions.checkState(type == CHUNK_STRING_POOL);
+    Preconditions.checkState(headerSize == HEADER_SIZE);
+    Preconditions.checkState(stringsStart == headerSize + 4 * (stringCount + styleCount));
+
+    buf = slice(buf, 0, chunkSize);
+    // Adjust stylesStart to actually point at the end of the string data.
+    stylesStart = stylesStart == 0 ? buf.limit() : stylesStart;
+    return new StringPool(
+        stringCount,
+        styleCount,
+        utf8,
+        sorted,
+        slice(buf, headerSize, 4 * stringCount),
+        slice(buf, headerSize + 4 * stringCount, 4 * styleCount),
+        slice(buf, stringsStart, stylesStart - stringsStart),
+        slice(buf, stylesStart, buf.limit() - stylesStart));
+  }
+
+  @Override
+  public void put(ByteBuffer output) {
+    putChunkHeader(output);
+    output.putInt(stringCount);
+    output.putInt(styleCount);
+    output.putInt((utf8 ? UTF8_FLAG : 0) | (sorted ? SORTED_FLAG : 0));
+    int stringsStart = HEADER_SIZE + 4 * (stringCount + styleCount);
+    output.putInt(stringsStart);
+    output.putInt(styleCount == 0 ? 0 : stringsStart + stringData.limit());
+    output.put(slice(stringOffsets, 0));
+    output.put(slice(styleOffsets, 0));
+    output.put(slice(stringData, 0));
+    output.put(slice(styleData, 0));
+  }
+
+  private int getUtf8Length(int offset) {
+    int hi = stringData.get(offset);
+    if (hi < 0) {
+      hi = ((hi & 0x7F) << 8) + (stringData.get(offset + 1) & 0xFF);
+    }
+    return hi;
+  }
+
+  private int getUtf16Length(int offset) {
+    int hi = stringData.getShort(offset);
+    if (hi < 0) {
+      hi = ((hi & 0x7FFF) << 16) + (stringData.getShort(offset + 2) & 0xFFFF);
+    }
+    return hi;
+  }
+
+  private int getEncodedStringOffset(int id) {
+    return stringOffsets.getInt(id * 4);
+  }
+
+  public String getString(int id) {
+    return getStringAtOffset(getEncodedStringOffset(id), false);
+  }
+
+  private String getStringAtOffset(int offset, boolean forDump) {
+    int length;
+    if (utf8) {
+      // For utf8 strings, both the length in code points and the length in bytes is encoded.
+      int utf16Length = getUtf8Length(offset);
+      offset += (utf16Length < (1 << 7)) ? 1 : 2;
+      int utf8length = getUtf8Length(offset);
+      offset += (utf8length < (1 << 7)) ? 1 : 2;
+      // For `aapt dump strings`, aapt has a bug where they use the decoded length rather than the
+      // encoded length when extracting string data...
+      length = forDump ? utf16Length : utf8length;
+    } else {
+      length = getUtf16Length(offset);
+      offset += (length < (1 << 15)) ? 2 : 4;
+      length *= 2;
+    }
+    return decodeString(offset, length);
+  }
+
+  private String getStringForDump(int id) {
+    return getStringAtOffset(getEncodedStringOffset(id), true);
+  }
+
+  private String decodeString(int start, int utf16Length) {
+    byte[] data = new byte[utf16Length];
+    stringData.position(start);
+    stringData.get(data);
+    stringData.position(0);
+    return new String(data, utf8 ? StandardCharsets.UTF_8 : StandardCharsets.UTF_16LE);
+  }
+
+  public void dump(PrintStream out) {
+    out.format(
+        "String pool of %d unique %s %s strings, %d entries and %d styles using %d bytes:\n",
+        stringCount,
+        utf8 ? "UTF-8" : "UTF-16",
+        sorted ? "sorted" : "non-sorted",
+        stringCount,
+        styleCount,
+        getChunkSize());
+    for (int i = 0; i < stringCount; i++) {
+      out.format("String #%d: %s\n", i, getStringForDump(i));
+    }
+  }
+
+  public int getStringCount() {
+    return stringCount;
+  }
+
+  public boolean isUtf8() {
+    return utf8;
+  }
+
+  public String getOutputNormalizedString(int data) {
+    return getString(data).replace("\\", "\\\\").replace("\n", "\\n").replace("\"", "\\\"");
+  }
+
+  public StringPool copy() {
+    return new StringPool(
+        stringCount,
+        styleCount,
+        utf8,
+        sorted,
+        copy(stringOffsets),
+        copy(styleOffsets),
+        copy(stringData),
+        copy(styleData));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/UsedResourcesFinder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/UsedResourcesFinder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/UsedResourcesFinder.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.stream.IntStream;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class UsedResourcesFinder {
+  interface ApkContentProvider {
+    ResourceTable getResourceTable();
+
+    ResourcesXml getXml(String path);
+
+    boolean hasFile(String path);
+  }
+
+  public static ResourceClosure computeClosure(
+      ApkContentProvider apkContentProvider,
+      Iterable<String> rootFiles,
+      Iterable<Integer> rootIds) {
+    State state = new State(apkContentProvider, rootFiles, rootIds);
+    state.process();
+    return new ResourceClosure(
+        state.processedFiles.stream()
+            .filter(apkContentProvider::hasFile)
+            .collect(ImmutableSet.toImmutableSet()),
+        state.processedIds);
+  }
+
+  public static ResourceClosure computePrimaryApkClosure(ApkContentProvider apkContentProvider) {
+    // The Android framework (and other apps) have easy access to the values in the manifest and
+    // anything reachable from there. Also, the framework needs access to animation references to
+    // drive some animations (requested by the app itself).
+    ImmutableList.Builder<Integer> rootIds = ImmutableList.builder();
+    ResTablePackage resPackage = apkContentProvider.getResourceTable().getPackage();
+    for (ResTableTypeSpec spec : resPackage.getTypeSpecs()) {
+      if (spec.getResourceTypeName(resPackage).equals("anim")) {
+        int startId = (ResTablePackage.APP_PACKAGE_ID << 24) | (spec.getResourceType() << 16);
+        rootIds.addAll(IntStream.range(startId, startId + spec.getEntryCount())::iterator);
+      }
+    }
+    return computeClosure(
+        apkContentProvider, ImmutableList.of("AndroidManifest.xml"), rootIds.build());
+  }
+
+  public static class ResourceClosure {
+    final Set<String> files;
+    final Map<Integer, SortedSet<Integer>> idsByType;
+
+    public ResourceClosure(Set<String> files, Map<Integer, SortedSet<Integer>> idsByType) {
+      this.files = files;
+      this.idsByType = idsByType;
+    }
+  }
+
+  private UsedResourcesFinder() {}
+
+  private static class State {
+    final ApkContentProvider apkContent;
+    final Map<Integer, SortedSet<Integer>> processedIds;
+    final Map<Integer, SortedSet<Integer>> idsToProcess;
+    final List<String> xmlToProcess;
+    final Set<String> processedFiles;
+
+    public State(
+        ApkContentProvider apkContentProvider,
+        Iterable<String> rootFiles,
+        Iterable<Integer> rootIds) {
+      this.apkContent = apkContentProvider;
+      processedIds = new HashMap<>();
+      idsToProcess = new HashMap<>();
+      processedFiles = new HashSet<>();
+      xmlToProcess = new ArrayList<>();
+
+      rootFiles.forEach(this::addPossibleFileToExtract);
+      rootIds.forEach(this::addIdToProcess);
+    }
+
+    void process() {
+      while (!idsToProcess.isEmpty() || !xmlToProcess.isEmpty()) {
+        processXml();
+        processIds();
+      }
+    }
+
+    void addIdToProcess(int id) {
+      int pkg = id >> 24;
+      if (pkg == ResTablePackage.APP_PACKAGE_ID) {
+        int type = (id >> 16) & 0xFF;
+        int k = id & 0xFFFF;
+        Set<Integer> processedIdsForType =
+            Objects.requireNonNull(processedIds.computeIfAbsent(type, v -> new TreeSet<>()));
+        if (processedIdsForType.add(k)) {
+          Objects.requireNonNull(idsToProcess.computeIfAbsent(type, v -> new TreeSet<>())).add(k);
+        }
+      }
+    }
+
+    void processIds() {
+      ImmutableMap<Integer, SortedSet<Integer>> ids = ImmutableMap.copyOf(idsToProcess);
+      idsToProcess.clear();
+      iterateArsc(ids);
+    }
+
+    void iterateArsc(ImmutableMap<Integer, SortedSet<Integer>> ids) {
+      ResTablePackage resPackage = apkContent.getResourceTable().getPackage();
+      StringPool strings = apkContent.getResourceTable().getStrings();
+      ids.forEach(
+          (k, v) -> {
+            ResTableTypeSpec spec = resPackage.getTypeSpec(k);
+            String resourceTypeName = spec.getResourceTypeName(resPackage);
+            int[] idsToVisit = v.stream().mapToInt(i -> i).toArray();
+            spec.visitReferences(idsToVisit, this::addIdToProcess);
+            if (!resourceTypeName.equals("string") && !resourceTypeName.equals("id")) {
+              spec.visitStringReferences(
+                  idsToVisit,
+                  (stringRef) -> addPossibleFileToExtract(strings.getString(stringRef)));
+            }
+          });
+    }
+
+    private void addPossibleFileToExtract(String val) {
+      if (!processedFiles.contains(val)) {
+        processedFiles.add(val);
+        if (val.endsWith(".xml") && apkContent.hasFile(val)) {
+          xmlToProcess.add(val);
+        }
+      }
+    }
+
+    void processXml() {
+      // This doesn't add new xml to process.
+      xmlToProcess.forEach(s -> apkContent.getXml(s).visitReferences(this::addIdToProcess));
+      xmlToProcess.clear();
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/BUCK
@@ -0,0 +1,34 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "filter",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/src/com/facebook/buck/util/json:json",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
+
+buck_java_binary(
+    name = "filter_resources_binary",
+    main_class = "com.facebook.buck.android.resources.filter.FilterResourcesExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":filter",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/DrawableFinder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/DrawableFinder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/DrawableFinder.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.filter;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Collection;
+import java.util.regex.Pattern;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class DrawableFinder {
+
+  private static final Pattern DRAWABLE_PATH_PATTERN =
+      Pattern.compile(".*drawable.*/.*(png|jpg|jpeg|gif|webp|xml)", Pattern.CASE_INSENSITIVE);
+  // Android doesn't scale these, so we don't need to scale or filter them either.
+  private static final Pattern DRAWABLE_EXCLUDE_PATTERN =
+      Pattern.compile(".*-nodpi.*", Pattern.CASE_INSENSITIVE);
+
+  /** Utility class: do not instantiate. */
+  private DrawableFinder() {}
+
+  public static ImmutableSet<Path> findDrawables(
+      AbsPath projectRoot, Collection<Path> dirs, DirectoryStream.Filter<? super Path> ignoreFilter)
+      throws IOException {
+    ImmutableSet.Builder<Path> drawableBuilder = ImmutableSet.builder();
+    for (Path dir : dirs) {
+      ProjectFilesystemUtils.walkRelativeFileTree(
+          projectRoot,
+          dir,
+          ProjectFilesystemUtils.getDefaultVisitOptions(),
+          new SimpleFileVisitor<>() {
+            @Override
+            public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) {
+              String unixPath = PathFormatter.pathWithUnixSeparators(path);
+              if (DRAWABLE_PATH_PATTERN.matcher(unixPath).matches()
+                  && !DRAWABLE_EXCLUDE_PATTERN.matcher(unixPath).matches()) {
+                // The path is normalized so that the value can be matched against patterns.
+                drawableBuilder.add(path);
+              }
+              return FileVisitResult.CONTINUE;
+            }
+          },
+          ignoreFilter);
+    }
+    return drawableBuilder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilterResourcesExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilterResourcesExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilterResourcesExecutableMain.java
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.filter;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.file.GlobPatternMatcher;
+import com.facebook.buck.io.file.PathMatcher;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.util.json.ObjectMappers;
+import com.facebook.infer.annotation.Nullsafe;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableBiMap;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Entry point for filtering resources. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class FilterResourcesExecutableMain {
+  private static final ImmutableList<PathMatcher> NON_ASSET_FILENAMES_MATCHERS =
+      ImmutableList.of(GlobPatternMatcher.of("**/.DS_Store"));
+
+  @Option(name = "--in-res-dir-to-out-res-dir-map", required = true)
+  private String inResDirToOutResDirMapPath;
+
+  @Option(name = "--voltron-in-res-dir-to-out-res-dir-map")
+  @Nullable
+  private String voltronInResDirToOutResDirMapPath = null;
+
+  @Option(name = "--target-densities")
+  @Nullable
+  private String targetDensities = null;
+
+  @Option(name = "--enable-string-as-assets-filtering")
+  private boolean enableStringsAsAssetsFiltering;
+
+  @Option(name = "--not-filtered-string-dirs")
+  @Nullable
+  private String notFilteredStringDirsFile = null;
+
+  @Option(name = "--string-files-list-output")
+  @Nullable
+  private String stringFilesListOutput = null;
+
+  @Option(name = "--locales")
+  @Nullable
+  private String localesString = null;
+
+  @Option(name = "--packaged-locales")
+  @Nullable
+  private String packagedLocalesString = null;
+
+  @Option(name = "--post-filter-resources-cmd")
+  @Nullable
+  private String postFilterResourcesCmd = null;
+
+  @Option(name = "--post-filter-resources-cmd-override-symbols-output")
+  @Nullable
+  private String postFilterResourcesCmdOverrideSymbols = null;
+
+  @Option(name = "--allowlisted-locales")
+  @Nullable
+  private String allowlistedLocalesFile = null;
+
+  public static void main(String[] args) throws IOException {
+    FilterResourcesExecutableMain main = new FilterResourcesExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    AbsPath root = AbsPath.of(Paths.get(".").normalize().toAbsolutePath());
+    // readValue only yields null for a literal JSON `null` document.
+    Map<String, ImmutableBiMap<Path, Path>> rawMap =
+        Objects.requireNonNull(
+            ObjectMappers.READER.readValue(
+                ObjectMappers.createParser(Paths.get(inResDirToOutResDirMapPath)),
+                new TypeReference<Map<String, ImmutableBiMap<Path, Path>>>() {}));
+    ImmutableBiMap<Path, Path> inResDirToOutResDirMap =
+        Objects.requireNonNull(rawMap.get("res_dir_map"));
+    ImmutableSet<ResourceFilters.Density> targetDensitiesSet =
+        targetDensities != null
+            ? Arrays.stream(targetDensities.split(","))
+                .map(ResourceFilters.Density::from)
+                .collect(ImmutableSet.toImmutableSet())
+            : ImmutableSet.of();
+    ImmutableSet<String> locales =
+        localesString != null ? ImmutableSet.copyOf(localesString.split(",")) : ImmutableSet.of();
+    ImmutableSet<String> packagedLocales =
+        packagedLocalesString != null
+            ? ImmutableSet.copyOf(packagedLocalesString.split(","))
+            : ImmutableSet.of();
+    ImmutableSet<Path> notFilteredStringDirs =
+        notFilteredStringDirsFile != null
+            ? Files.readAllLines(Paths.get(notFilteredStringDirsFile)).stream()
+                .map(Paths::get)
+                .collect(ImmutableSet.toImmutableSet())
+            : ImmutableSet.of();
+
+    ImmutableMap<Path, ImmutableSet<String>> allowlistedLocalesDirs =
+        allowlistedLocalesFile != null
+            ? Objects.requireNonNull(
+                ObjectMappers.READER.readValue(
+                    ObjectMappers.createParser(Paths.get(allowlistedLocalesFile)),
+                    new TypeReference<ImmutableMap<Path, ImmutableSet<String>>>() {}))
+            : ImmutableMap.of();
+
+    Predicate<Path> filteringPredicate =
+        FilteringPredicate.getFilteringPredicate(
+            root,
+            ProjectFilesystemUtils.getIgnoreFilter(root, true, NON_ASSET_FILENAMES_MATCHERS),
+            inResDirToOutResDirMap,
+            !targetDensitiesSet.isEmpty(),
+            targetDensitiesSet,
+            locales,
+            packagedLocales,
+            enableStringsAsAssetsFiltering,
+            notFilteredStringDirs,
+            allowlistedLocalesDirs);
+
+    timed(
+        "Copying & filtering resources",
+        () -> {
+          FilteredDirectoryCopier.copyDirsParallel(
+              root,
+              ProjectFilesystemUtils.getIgnoreFilter(root, true, NON_ASSET_FILENAMES_MATCHERS),
+              inResDirToOutResDirMap,
+              filteringPredicate);
+        });
+
+    String voltronMapPath = voltronInResDirToOutResDirMapPath;
+    if (voltronMapPath != null) {
+      timed(
+          "Copying & filtering voltron resources",
+          () -> {
+            Map<String, ImmutableBiMap<Path, Path>> rawVoltronMap =
+                Objects.requireNonNull(
+                    ObjectMappers.READER.readValue(
+                        ObjectMappers.createParser(Paths.get(voltronMapPath)),
+                        new TypeReference<Map<String, ImmutableBiMap<Path, Path>>>() {}));
+            ImmutableBiMap<Path, Path> voltronInResDirToOutResDirMap =
+                Objects.requireNonNull(rawVoltronMap.get("res_dir_map"));
+
+            FilteredDirectoryCopier.copyDirsParallel(
+                root,
+                ProjectFilesystemUtils.getEmptyIgnoreFilter(),
+                voltronInResDirToOutResDirMap,
+                FilteringPredicate.getVoltronLanguagePackPredicate());
+          });
+    }
+
+    String postFilterCmd = postFilterResourcesCmd;
+    if (postFilterCmd != null) {
+      timed(
+          "Running post-filter-resources command",
+          () -> {
+            Preconditions.checkState(
+                postFilterResourcesCmdOverrideSymbols != null,
+                "Must specify an override symbols file if a post-filter-resources-cmd is"
+                    + " specified!");
+            ImmutableList.Builder<String> postFilterResourcesCmdList = ImmutableList.builder();
+            postFilterResourcesCmdList
+                .addAll(Arrays.stream(postFilterCmd.split("\\s+")).collect(Collectors.toList()))
+                .add(inResDirToOutResDirMapPath)
+                .add(postFilterResourcesCmdOverrideSymbols);
+            Process postFilterResourcesProcess =
+                new ProcessBuilder().command(postFilterResourcesCmdList.build()).start();
+            try {
+              int exitCode = postFilterResourcesProcess.waitFor();
+              if (exitCode != 0) {
+                String error =
+                    new String(
+                        Objects.requireNonNull(postFilterResourcesProcess.getErrorStream())
+                            .readAllBytes());
+                throw new RuntimeException("post_filter_resources_cmd failed with error: " + error);
+              }
+            } catch (InterruptedException e) {
+              throw new RuntimeException(e);
+            }
+          });
+    }
+
+    // We need to output a list of all the string files if and only if we are doing
+    // strings-as-assets filtering.
+    String stringFilesList = stringFilesListOutput;
+    Preconditions.checkState(enableStringsAsAssetsFiltering == (stringFilesList != null));
+    if (stringFilesList != null) {
+      timed(
+          "Writing string files list",
+          () -> {
+            Files.write(
+                Paths.get(stringFilesList),
+                (Iterable<String>)
+                    GetStringsFiles.getFilesAsStream(
+                                root,
+                                ProjectFilesystemUtils.getEmptyIgnoreFilter(),
+                                inResDirToOutResDirMap.keySet().asList())
+                            .map(Path::toString)
+                        ::iterator);
+          });
+    }
+
+    System.exit(0);
+  }
+
+  private static <E extends Exception> void timed(String name, ThrowingRunnable<E> runnable)
+      throws E {
+    long start = System.currentTimeMillis();
+    try {
+      runnable.run();
+    } finally {
+      long end = System.currentTimeMillis();
+      System.err.println(name + " took " + (end - start) + "ms");
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilteredDirectoryCopier.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilteredDirectoryCopier.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilteredDirectoryCopier.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.filter;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.filesystem.CopySourceMode;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Map;
+import java.util.function.Predicate;
+
+/**
+ * This class allows the creation of copies of multiple directories, while filtering out files which
+ * do not match a specified predicate.
+ *
+ * <p>Current caveats:
+ *
+ * <ul>
+ *   <li>Existing content in destination directories is deleted.
+ *   <li>Empty directories will not be created.
+ * </ul>
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class FilteredDirectoryCopier {
+
+  private FilteredDirectoryCopier() {}
+
+  public static void copyDirs(
+      AbsPath projectRoot,
+      DirectoryStream.Filter<? super Path> ignoreFilter,
+      Map<Path, Path> sourcesToDestinations,
+      Predicate<Path> pred)
+      throws IOException {
+    for (Map.Entry<Path, Path> e : sourcesToDestinations.entrySet()) {
+      copyDir(projectRoot, ignoreFilter, e.getKey(), e.getValue(), pred);
+    }
+  }
+
+  public static void copyDirsParallel(
+      AbsPath projectRoot,
+      DirectoryStream.Filter<? super Path> ignoreFilter,
+      Map<Path, Path> sourcesToDestinations,
+      Predicate<Path> pred)
+      throws IOException {
+    sourcesToDestinations.entrySet().parallelStream()
+        .forEach(e -> copyDirExcWrapper(projectRoot, ignoreFilter, e.getKey(), e.getValue(), pred));
+  }
+
+  private static void copyDirExcWrapper(
+      AbsPath projectRoot,
+      DirectoryStream.Filter<? super Path> ignoreFilter,
+      Path srcDir,
+      Path destDir,
+      Predicate<Path> pred) {
+    try {
+      copyDir(projectRoot, ignoreFilter, srcDir, destDir, pred);
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static void copyDir(
+      AbsPath projectRoot,
+      DirectoryStream.Filter<? super Path> ignoreFilter,
+      Path srcDir,
+      Path destDir,
+      Predicate<Path> pred)
+      throws IOException {
+
+    // Remove existing contents if any.
+    if (ProjectFilesystemUtils.exists(projectRoot, destDir)) {
+      ProjectFilesystemUtils.deleteRecursivelyIfExists(projectRoot, destDir);
+    }
+    ProjectFilesystemUtils.mkdirs(projectRoot, destDir);
+
+    ProjectFilesystemUtils.walkRelativeFileTree(
+        projectRoot,
+        srcDir,
+        ProjectFilesystemUtils.getDefaultVisitOptions(),
+        new SimpleFileVisitor<>() {
+          @Override
+          public FileVisitResult visitFile(Path srcPath, BasicFileAttributes attributes)
+              throws IOException {
+            if (pred.test(srcPath)) {
+              Path destPath = destDir.resolve(srcDir.relativize(srcPath));
+              ProjectFilesystemUtils.createParentDirs(projectRoot, destPath);
+              ProjectFilesystemUtils.copy(projectRoot, srcPath, destPath, CopySourceMode.FILE);
+            }
+            return FileVisitResult.CONTINUE;
+          }
+        },
+        ignoreFilter);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilteringPredicate.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilteringPredicate.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/FilteringPredicate.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.filter;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableBiMap;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class FilteringPredicate {
+
+  /** Utility class: do not instantiate. */
+  private FilteringPredicate() {}
+
+  @VisibleForTesting
+  public static final Pattern NON_ENGLISH_STRINGS_FILE_PATH =
+      Pattern.compile(".*/values-([a-z]{2})(?:-r([A-Z]{2}))*/strings.xml");
+
+  public static Predicate<Path> getFilteringPredicate(
+      AbsPath projectRoot,
+      DirectoryStream.Filter<? super Path> ignoreFilter,
+      ImmutableBiMap<Path, Path> inResDirToOutResDirMap,
+      boolean filterByDensity,
+      Set<ResourceFilters.Density> targetDensities,
+      ImmutableSet<String> locales,
+      ImmutableSet<String> packagedLocales,
+      boolean enableStringWhitelisting,
+      ImmutableSet<Path> whitelistedStringDirs,
+      ImmutableMap<Path, ImmutableSet<String>> allowlistedLocalesDirs)
+      throws IOException {
+    List<Predicate<Path>> pathPredicates = new ArrayList<>();
+
+    if (filterByDensity) {
+      Objects.requireNonNull(targetDensities);
+      Set<Path> rootResourceDirs = inResDirToOutResDirMap.keySet();
+
+      pathPredicates.add(ResourceFilters.createDensityFilter(projectRoot, targetDensities));
+
+      Set<Path> drawables =
+          DrawableFinder.findDrawables(projectRoot, rootResourceDirs, ignoreFilter);
+      pathPredicates.add(ResourceFilters.createImageDensityFilter(drawables, targetDensities));
+    }
+
+    boolean localeFilterEnabled = !locales.isEmpty();
+    if (localeFilterEnabled || enableStringWhitelisting) {
+      pathPredicates.add(
+          path -> {
+            String filePath = PathFormatter.pathWithUnixSeparators(path);
+            Matcher matcher = NON_ENGLISH_STRINGS_FILE_PATH.matcher(filePath);
+            if (!matcher.matches()) {
+              return true;
+            }
+            String locale = Objects.requireNonNull(matcher.group(1));
+            if (matcher.group(2) != null) {
+              locale += "_" + matcher.group(2);
+            }
+            if (enableStringWhitelisting) {
+              return isPathWhitelisted(
+                  path, locale, packagedLocales, whitelistedStringDirs, allowlistedLocalesDirs);
+
+            } else {
+              return locales.contains(locale);
+            }
+          });
+    }
+    return pathPredicates.stream().reduce(p -> true, Predicate::and);
+  }
+
+  public static Predicate<Path> getVoltronLanguagePackPredicate() {
+    return path -> {
+      String filePath = PathFormatter.pathWithUnixSeparators(path);
+      Matcher matcher = NON_ENGLISH_STRINGS_FILE_PATH.matcher(filePath);
+      return matcher.matches();
+    };
+  }
+
+  private static boolean isPathWhitelisted(
+      Path path,
+      String locale,
+      ImmutableSet<String> packagedLocales,
+      ImmutableSet<Path> whitelistedStringDirs,
+      ImmutableMap<Path, ImmutableSet<String>> allowlistedLocalesDirs) {
+    if (packagedLocales.contains(locale)) {
+      return true;
+    }
+    for (Path whitelistedStringDir : whitelistedStringDirs) {
+      if (path.startsWith(whitelistedStringDir)) {
+        return true;
+      }
+    }
+    for (Map.Entry<Path, ImmutableSet<String>> entry : allowlistedLocalesDirs.entrySet()) {
+      if (path.startsWith(entry.getKey()) && entry.getValue().contains(locale)) {
+        return true;
+      }
+    }
+
+    return false;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/GetStringsFiles.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/GetStringsFiles.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/GetStringsFiles.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.filter;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Path;
+import java.util.function.Predicate;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+/**
+ * Generates a list of strings.xml files
+ *
+ * <p>The ordering of strings files is consistent with the order of the input resource directories
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class GetStringsFiles {
+  @VisibleForTesting
+  public static final Pattern STRINGS_FILE_PATH =
+      Pattern.compile("(\\b|.*/)res/values(-.+)*/strings.xml", Pattern.CASE_INSENSITIVE);
+
+  public static ImmutableList<Path> getFiles(
+      AbsPath root, DirectoryStream.Filter<? super Path> ignoreFilter, ImmutableList<Path> resDirs)
+      throws IOException {
+    Predicate<Path> isStringsFile =
+        pathRelativeToProjectRoot -> {
+          String filePath = PathFormatter.pathWithUnixSeparators(pathRelativeToProjectRoot);
+          return STRINGS_FILE_PATH.matcher(filePath).matches();
+        };
+
+    ImmutableList.Builder<Path> stringFilesBuilder = ImmutableList.builder();
+    for (Path resDir : resDirs) {
+      stringFilesBuilder.addAll(
+          ProjectFilesystemUtils.getFilesUnderPath(
+              root,
+              resDir,
+              isStringsFile,
+              ProjectFilesystemUtils.getDefaultVisitOptions(),
+              ignoreFilter));
+    }
+
+    return stringFilesBuilder.build();
+  }
+
+  public static Stream<Path> getFilesAsStream(
+      AbsPath root, DirectoryStream.Filter<? super Path> ignoreFilter, ImmutableList<Path> resDirs)
+      throws IOException {
+    Predicate<Path> isStringsFile =
+        pathRelativeToProjectRoot -> {
+          String filePath = PathFormatter.pathWithUnixSeparators(pathRelativeToProjectRoot);
+          return STRINGS_FILE_PATH.matcher(filePath).matches();
+        };
+
+    return resDirs.stream()
+        .flatMap(resDir -> getFilesUnderPathExcWrapper(root, resDir, isStringsFile, ignoreFilter));
+  }
+
+  private static Stream<Path> getFilesUnderPathExcWrapper(
+      AbsPath root,
+      Path resDir,
+      Predicate<Path> isStringsFile,
+      DirectoryStream.Filter<? super Path> ignoreFilter) {
+    try {
+      return ProjectFilesystemUtils.getFilesUnderPath(
+          root,
+          resDir,
+          isStringsFile,
+          ProjectFilesystemUtils.getDefaultVisitOptions(),
+          ignoreFilter)
+          .stream();
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/ResourceFilters.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/ResourceFilters.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/ResourceFilters.java
@@ -0,0 +1,303 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.filter;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.HashBasedTable;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Ordering;
+import com.google.common.collect.Sets;
+import com.google.common.collect.Table;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Predicate;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ResourceFilters {
+
+  /** Utility class: do not instantiate. */
+  private ResourceFilters() {}
+
+  /**
+   * The set of supported directories in resource folders. This is defined in
+   * http://developer.android.com/guide/topics/resources/providing-resources.html#table1
+   */
+  @VisibleForTesting
+  public static final ImmutableSet<String> SUPPORTED_RESOURCE_DIRECTORIES =
+      ImmutableSet.of(
+          "animator",
+          "anim",
+          "color",
+          "drawable",
+          "font",
+          "mipmap",
+          "layout",
+          "menu",
+          "raw",
+          "values",
+          "xml",
+          // "interpolator" is not officially documented in the above
+          // link, but several support library aar files use it.
+          "interpolator",
+          // "transition" is not documented in the above link,
+          // but the docs below claim it can be used
+          // https://developer.android.com/reference/android/transition/Transition
+          "transition",
+          "navigation");
+
+  /**
+   * Represents the names and values of valid densities for resources as defined in
+   * http://developer.android.com/guide/topics/resources/providing-resources.html#DensityQualifier
+   */
+  public enum Density {
+    // Note: ordering here matters and must be increasing by number!
+    LDPI("ldpi", 120.0),
+    NO_QUALIFIER("", 160.0),
+    MDPI("mdpi", 160.0),
+    TVDPI("tvdpi", 213.0),
+    HDPI("hdpi", 240.0),
+    XHDPI("xhdpi", 320.0),
+    XXHDPI("xxhdpi", 480.0),
+    XXXHDPI("xxxhdpi", 640.0);
+
+    private final String qualifier;
+    private final double value;
+
+    public static final Ordering<Density> ORDERING = Ordering.natural();
+
+    Density(String qualifier, double value) {
+      this.qualifier = qualifier;
+      this.value = value;
+    }
+
+    public double value() {
+      return value;
+    }
+
+    @Override
+    public String toString() {
+      return qualifier;
+    }
+
+    public static Density from(String s) {
+      return s.isEmpty() ? NO_QUALIFIER : valueOf(s.toUpperCase());
+    }
+
+    public static boolean isDensity(String s) {
+      for (Density choice : values()) {
+        if (choice.toString().equals(s)) {
+          return true;
+        }
+      }
+      return false;
+    }
+  }
+
+  public static class Qualifiers {
+    /** e.g. "xhdpi" */
+    public final ResourceFilters.Density density;
+
+    /** e.g. "de-v11" */
+    public final String others;
+
+    /**
+     * Creates a Qualfiers given the Path to a resource folder, pulls out the density filters and
+     * leaves the rest.
+     */
+    public static Qualifiers from(Path path) {
+      ResourceFilters.Density density = Density.NO_QUALIFIER;
+      StringBuilder othersBuilder = new StringBuilder();
+      String[] parts = path.getFileName().toString().split("-");
+      Preconditions.checkState(parts.length > 0);
+      Preconditions.checkState(SUPPORTED_RESOURCE_DIRECTORIES.contains(parts[0]));
+      for (int i = 1; i < parts.length; i++) {
+        String qualifier = parts[i];
+        if (ResourceFilters.Density.isDensity(qualifier)) {
+          density = Density.from(qualifier);
+        } else {
+          othersBuilder.append(othersBuilder.length() == 0 ? "" : "-").append(qualifier);
+        }
+      }
+      return new Qualifiers(density, othersBuilder.toString());
+    }
+
+    private Qualifiers(Density density, String others) {
+      this.density = density;
+      this.others = others;
+    }
+  }
+
+  /**
+   * Takes a list of image files (as paths), and a target density (mdpi, hdpi, xhdpi), and returns a
+   * list of files which can be safely left out when building an APK for phones with that screen
+   * density. That APK will run on other screens as well but look worse due to scaling.
+   *
+   * <p>Each combination of non-density qualifiers is processed separately. For example, if we have
+   * {@code drawable-hdpi, drawable-mdpi, drawable-xhdpi, drawable-hdpi-ro}, for a target of {@code
+   * mdpi}, we'll be keeping {@code drawable-mdpi, drawable-hdpi-ro}.
+   *
+   * <p>This method is based on {@code D621945}.
+   *
+   * @param candidates list of paths to image files
+   * @param targetDensities densities we want to keep
+   * @return set of files to remove
+   */
+  @VisibleForTesting
+  static ImmutableSet<Path> filterByDensity(
+      Collection<Path> candidates, Set<ResourceFilters.Density> targetDensities) {
+    ImmutableSet.Builder<Path> removals = ImmutableSet.builder();
+
+    Table<String, Density, Path> imageValues = HashBasedTable.create();
+
+    // Create mappings for drawables. If candidate == "<base>/drawable-<dpi>-<other>/<filename>",
+    // then we'll record a mapping of the form ("<base>/<filename>/<other>", "<dpi>") -> candidate.
+    // For example:
+    //                                    mdpi                               hdpi
+    //                       --------------------------------------------------------------------
+    // key: res/some.png/    |  res/drawable-mdpi/some.png          res/drawable-hdpi/some.png
+    // key: res/some.png/fr  |  res/drawable-fr-hdpi/some.png
+    for (Path candidate : candidates) {
+      Qualifiers qualifiers = Qualifiers.from(Objects.requireNonNull(candidate.getParent()));
+
+      String filename = candidate.getFileName().toString();
+      Density density = qualifiers.density;
+      String resDirectory =
+          Objects.requireNonNull(Objects.requireNonNull(candidate.getParent()).getParent())
+              .toString();
+      String key = String.format("%s/%s/%s", resDirectory, filename, qualifiers.others);
+      imageValues.put(key, density, candidate);
+    }
+
+    for (String key : imageValues.rowKeySet()) {
+      Map<Density, Path> options = imageValues.row(key);
+      Set<Density> available = options.keySet();
+
+      // This is to make sure we preserve the existing structure of drawable/ files.
+      Set<Density> targets = targetDensities;
+      if (available.contains(Density.NO_QUALIFIER) && !available.contains(Density.MDPI)) {
+        targets =
+            Sets.newHashSet(
+                Iterables.transform(
+                    targetDensities,
+                    input -> (input == Density.MDPI) ? Density.NO_QUALIFIER : input));
+      }
+
+      // We intend to keep all available targeted densities.
+      Set<Density> toKeep = Sets.newHashSet(Sets.intersection(available, targets));
+
+      // Make sure we have a decent fit for the largest target density.
+      Density largestTarget = Density.ORDERING.max(targets);
+      if (!available.contains(largestTarget)) {
+        Density fallback = null;
+        // We want to minimize size, so we'll go for the smallest available density that's
+        // still larger than the missing one and, missing that, for the largest available.
+        for (Density candidate : Density.ORDERING.reverse().sortedCopy(available)) {
+          if (fallback == null || Density.ORDERING.compare(candidate, largestTarget) > 0) {
+            fallback = candidate;
+          }
+        }
+        toKeep.add(fallback);
+      }
+
+      // Mark remaining densities for removal.
+      for (Density density : Sets.difference(available, toKeep)) {
+        removals.add(Objects.requireNonNull(options.get(density)));
+      }
+    }
+
+    return removals.build();
+  }
+
+  /**
+   * Given a list of paths of available drawables, and a target screen density, returns a {@link
+   * com.google.common.base.Predicate} that fails for drawables of a different density, whenever
+   * they can be safely removed.
+   *
+   * @param candidates list of available drawables
+   * @param targetDensities set of e.g. {@code "mdpi"}, {@code "ldpi"} etc.
+   * @return a predicate as above
+   */
+  public static Predicate<Path> createImageDensityFilter(
+      Collection<Path> candidates, Set<ResourceFilters.Density> targetDensities) {
+    Set<Path> pathsToRemove = filterByDensity(candidates, targetDensities);
+    return path -> !pathsToRemove.contains(path);
+  }
+
+  private static String getResourceType(Path resourceFolder) {
+    String[] parts = resourceFolder.getFileName().toString().split("-");
+    return parts[0];
+  }
+
+  private static Path getResourceFolder(Path resourceFile) {
+    for (int i = 0; i < resourceFile.getNameCount(); i++) {
+      Path part = resourceFile.getName(i);
+      if (SUPPORTED_RESOURCE_DIRECTORIES.contains(getResourceType(part))) {
+        return resourceFile.subpath(0, i + 1);
+      }
+    }
+    throw new RuntimeException(
+        String.format(
+            "Resource file at %s is not in a valid resource folder.  See"
+                + " http://developer.android.com/guide/topics/resources/providing-resources.html#table1"
+                + " for a list of valid resource folders.",
+            resourceFile));
+  }
+
+  /**
+   * Given a set of target densities, returns a {@link Predicate} that fails for any non-drawable
+   * resource of a different density. Special consideration exists for the default density ({@link
+   * Density#NO_QUALIFIER} when the target does not exists.
+   */
+  public static Predicate<Path> createDensityFilter(
+      AbsPath projectRoot, Set<Density> targetDensities) {
+    return resourceFile -> {
+      Path resourceFolder = getResourceFolder(resourceFile);
+      if (resourceFolder.getFileName().toString().startsWith("drawable")) {
+        // Drawables are handled independently, so do not do anything with them.
+        return true;
+      }
+      Density density = Qualifiers.from(resourceFolder).density;
+
+      // We should include the resource in these situations:
+      // * it is one of the target densities
+      // * this is a "values" resource, which we include the fallback and any targets so we do not
+      //   have to parse the XML to determine if there are differences.
+      // * there is no resource at any one of the target densities, and this is the fallback.
+      if (targetDensities.contains(density)) {
+        return true;
+      }
+
+      if (density.equals(Density.NO_QUALIFIER)) {
+        String resourceType = getResourceType(resourceFolder);
+        return resourceType.equals("values")
+            || FluentIterable.from(targetDensities)
+                .anyMatch(
+                    target -> {
+                      Path targetResourceFile =
+                          resourceFolder
+                              .resolveSibling(String.format("%s-%s", resourceType, target))
+                              .resolve(resourceFolder.relativize(resourceFile));
+                      return !ProjectFilesystemUtils.exists(projectRoot, targetResourceFile);
+                    });
+      }
+      return false;
+    };
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/ThrowingRunnable.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/ThrowingRunnable.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/filter/ThrowingRunnable.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.filter;
+
+/**
+ * A {@link Runnable} that can throw checked exceptions.
+ *
+ * @param <E> the type of exception that can be thrown
+ */
+@FunctionalInterface
+public interface ThrowingRunnable<E extends Exception> {
+  void run() throws E;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/BUCK
@@ -0,0 +1,46 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "strings",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/src/com/facebook/buck/util/xml:xml",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
+
+buck_java_binary(
+    name = "copy_string_resources_binary",
+    main_class = "com.facebook.buck.android.resources.strings.CopyStringResourcesExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":strings",
+    ],
+)
+
+buck_java_binary(
+    name = "package_strings_as_assets_binary",
+    main_class = "com.facebook.buck.android.resources.strings.PackageStringsAsAssetsExecutableMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":strings",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/CompileStrings.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/CompileStrings.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/CompileStrings.java
@@ -0,0 +1,448 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.strings;
+
+import com.facebook.buck.android.resources.strings.StringResources.Gender;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.facebook.buck.util.xml.XmlDomParser;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.function.Function;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.jetbrains.annotations.Nullable;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+/**
+ * This takes a list of string resource files (strings.xml), groups them by locales, and for each
+ * locale generates a file with all the string resources for that locale. Strings.xml files without
+ * a resource qualifier are mapped to the "en" locale.
+ *
+ * <p>A typical strings.xml file looks like:
+ *
+ * <pre>{@code
+ * <?xml version="1.0" encoding="utf-8"?>
+ * <resources>
+ *   <string name="resource_name1">I am a string.</string>
+ *   <string name="resource_name2">I am another string.</string>
+ *   <plurals name="time_hours_ago">
+ *     <item quantity="one">1 minute ago</item>
+ *     <item quantity="other">%d minutes ago</item>
+ *   </plurals>
+ *   <string-array name="logging_levels">
+ *     <item>Default</item>
+ *     <item>Verbose</item>
+ *     <item>Debug</item>
+ *   </string-array>
+ * </resources>
+ *
+ * }</pre>
+ *
+ * <p>For more information on the xml file format, refer to: <a
+ * href="http://developer.android.com/guide/topics/resources/string-resource.html">String Resources
+ * - Android Developers </a>
+ *
+ * <p>So for each supported locale in a project, this step goes through all such xml files for that
+ * locale, and builds a map of resource name to resource value, where resource value is either:
+ *
+ * <ol>
+ *   <li>a string
+ *   <li>a map of plurals
+ *   <li>a list of strings
+ * </ol>
+ *
+ * and dumps this map into the output file. See {@link StringResources} for the file format.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class CompileStrings {
+
+  private static final String ENGLISH_STRING_PATH_SUFFIX = "res/values/strings.xml";
+  private static final String ENGLISH_LOCALE = "en";
+  private static final String FEMALE_SUFFIX = "_f1gender";
+  private static final String MALE_SUFFIX = "_m2gender";
+  private static final int FEMALE_SUFFIX_LENGTH = FEMALE_SUFFIX.length();
+  private static final int MALE_SUFFIX_LENGTH = MALE_SUFFIX.length();
+
+  @VisibleForTesting
+  public static final Pattern NON_ENGLISH_STRING_FILE_PATTERN =
+      Pattern.compile(
+          ".*res/values-(?:b\\+)*([a-z]{2})(?:-r([A-Z]{2}))*(?:\\+[a-zA-Z]{4})*/strings.xml");
+
+  @VisibleForTesting
+  public static final Pattern R_DOT_TXT_STRING_RESOURCE_PATTERN =
+      Pattern.compile("^int (string|plurals|array) (\\w+) 0x([0-9a-f]+)$");
+
+  /**
+   * The pattern to be bypassed if we see mcc qualifier in the path. See more context in:
+   * https://fb.workplace.com/groups/i18n.QandA/permalink/4066577280057523/
+   */
+  private static final Pattern BYPASSING_STRING_PATH_PATTERN =
+      Pattern.compile(".*res/values-mcc[0-9]{3}/strings.xml");
+
+  private final Map<String, String> regionSpecificToBaseLocaleMap = new HashMap<>();
+  private final Map<String, Integer> stringResourceNameToIdMap = new HashMap<>();
+  private final Map<String, Integer> pluralsResourceNameToIdMap = new HashMap<>();
+  private final Map<String, Integer> arrayResourceNameToIdMap = new HashMap<>();
+
+  /**
+   * Note: The ordering of files in the input list determines which resource value ends up in the
+   * output .fbstr file, in the event of multiple xml files of a locale sharing the same string
+   * resource name - file that appears first in the list wins.
+   *
+   * @param stringFiles Set containing paths to strings.xml files matching {@link
+   *     com.facebook.buck.android.resources.filter.GetStringsFiles#STRINGS_FILE_PATH}
+   * @param rDotTxtFile Path to the R.txt file generated by aapt.
+   * @param pathBuilder Builds a path to store a .fbstr file at.
+   */
+  public void compileStrings(
+      AbsPath root,
+      ImmutableList<Path> stringFiles,
+      Path rDotTxtFile,
+      Function<String, Path> pathBuilder)
+      throws IOException, SAXException {
+    buildResourceNameToIdMap(
+        root,
+        rDotTxtFile,
+        stringResourceNameToIdMap,
+        pluralsResourceNameToIdMap,
+        arrayResourceNameToIdMap);
+
+    ImmutableMultimap<String, Path> filesByLocale = groupFilesByLocale(stringFiles);
+    Map<String, StringResources> resourcesByLocale = new HashMap<>();
+    for (String locale : filesByLocale.keySet()) {
+      resourcesByLocale.put(locale, compileStringFiles(root, filesByLocale.get(locale)));
+    }
+
+    // Merge region specific locale resources with the corresponding base locale resources.
+    //
+    // For example, if there are separate string resources in an android project for locale
+    // "es" and "es_US", when an application running on a device with locale set to "Spanish
+    // (United States)" requests for a string, the Android runtime first looks for the string in
+    // "es_US" set of resources, and if not found, returns the resource from the "es" set.
+    // We merge these because we want the individual .fbstr files to be self contained for
+    // simplicity except for "en" because the string is already in Android resources.
+    for (String regionSpecificLocale : regionSpecificToBaseLocaleMap.keySet()) {
+      String baseLocale =
+          Objects.requireNonNull(regionSpecificToBaseLocaleMap.get(regionSpecificLocale));
+      if (!resourcesByLocale.containsKey(baseLocale) || ENGLISH_LOCALE.equals(baseLocale)) {
+        continue;
+      }
+
+      resourcesByLocale.put(
+          regionSpecificLocale,
+          Objects.requireNonNull(resourcesByLocale.get(regionSpecificLocale))
+              .getMergedResources(Objects.requireNonNull(resourcesByLocale.get(baseLocale))));
+    }
+
+    for (String locale : filesByLocale.keySet()) {
+      ProjectFilesystemUtils.writeBytesToPath(
+          root,
+          Objects.requireNonNull(resourcesByLocale.get(locale)).getBinaryFileContent(),
+          pathBuilder.apply(locale));
+    }
+  }
+
+  /**
+   * Groups a list of strings.xml files by locale. String files with no resource qualifier (eg.
+   * values/strings.xml) are mapped to the "en" locale
+   *
+   * <p>eg. given the following list:
+   *
+   * <p>ImmutableList.of( Paths.get("one/res/values-es/strings.xml"),
+   * Paths.get("two/res/values-es/strings.xml"), Paths.get("three/res/values-pt-rBR/strings.xml"),
+   * Paths.get("four/res/values-pt-rPT/strings.xml"), Paths.get("five/res/values/strings.xml"));
+   *
+   * <p>returns:
+   *
+   * <p>ImmutableMap.of( "es", ImmutableList.of(Paths.get("one/res/values-es/strings.xml"),
+   * Paths.get("two/res/values-es/strings.xml")), "pt_BR",
+   * ImmutableList.of(Paths.get("three/res/values-pt-rBR/strings.xml'), "pt_PT",
+   * ImmutableList.of(Paths.get("four/res/values-pt-rPT/strings.xml"), "en",
+   * ImmutableList.of(Paths.get("five/res/values/strings.xml")));
+   */
+  @VisibleForTesting
+  public ImmutableMultimap<String, Path> groupFilesByLocale(ImmutableList<Path> files) {
+    ImmutableMultimap.Builder<String, Path> localeToFiles = ImmutableMultimap.builder();
+
+    for (Path filepath : files) {
+      String path = PathFormatter.pathWithUnixSeparators(filepath);
+      Matcher matcher = NON_ENGLISH_STRING_FILE_PATTERN.matcher(path);
+
+      if (matcher.matches()) {
+        String baseLocale = Objects.requireNonNull(matcher.group(1));
+        String country = matcher.group(2);
+        String locale = country == null ? baseLocale : baseLocale + "_" + country;
+        if (country != null && !regionSpecificToBaseLocaleMap.containsKey(locale)) {
+          regionSpecificToBaseLocaleMap.put(locale, baseLocale);
+        }
+
+        localeToFiles.put(locale, filepath);
+      } else {
+        if (!path.endsWith(ENGLISH_STRING_PATH_SUFFIX)) {
+          Matcher bypassingPathMatcher = BYPASSING_STRING_PATH_PATTERN.matcher(path);
+          if (bypassingPathMatcher.matches()) {
+            continue;
+          }
+
+          throw new RuntimeException(
+              String.format(
+                  "Invalid path passed to compile strings. Expected path to end with %s, got path"
+                      + " %s.",
+                  ENGLISH_STRING_PATH_SUFFIX, path));
+        }
+
+        localeToFiles.put(ENGLISH_LOCALE, filepath);
+      }
+    }
+
+    return localeToFiles.build();
+  }
+
+  /**
+   * Parses the R.txt file generated by aapt, looks for resources of type {@code string}, {@code
+   * plurals} and {@code array}, and builds a map of resource names to their corresponding ids.
+   */
+  private static void buildResourceNameToIdMap(
+      AbsPath root,
+      Path pathToRDotTxtFile,
+      Map<String, Integer> stringResourceNameToIdMap,
+      Map<String, Integer> pluralsResourceNameToIdMap,
+      Map<String, Integer> arrayResourceNameToIdMap)
+      throws IOException {
+    List<String> fileLines = ProjectFilesystemUtils.readLines(root, pathToRDotTxtFile);
+    for (String line : fileLines) {
+      Matcher matcher = R_DOT_TXT_STRING_RESOURCE_PATTERN.matcher(line);
+      if (!matcher.matches()) {
+        continue;
+      }
+
+      String type = Objects.requireNonNull(matcher.group(1));
+      String resourceName = Objects.requireNonNull(matcher.group(2));
+      Integer resourceId = Integer.parseInt(Objects.requireNonNull(matcher.group(3)), 16);
+      switch (type) {
+        case "string":
+          stringResourceNameToIdMap.put(resourceName, resourceId);
+          break;
+        case "plurals":
+          pluralsResourceNameToIdMap.put(resourceName, resourceId);
+          break;
+        case "array":
+          arrayResourceNameToIdMap.put(resourceName, resourceId);
+          break;
+        default:
+          throw new IllegalArgumentException("Invalid resource type: " + type);
+      }
+    }
+  }
+
+  private StringResources compileStringFiles(AbsPath root, Collection<Path> filepaths)
+      throws IOException, SAXException {
+    TreeMap<Integer, EnumMap<Gender, String>> stringsMap = new TreeMap<>();
+    TreeMap<Integer, EnumMap<Gender, ImmutableMap<String, String>>> pluralsMap = new TreeMap<>();
+    TreeMap<Integer, EnumMap<Gender, ImmutableList<String>>> arraysMap = new TreeMap<>();
+
+    for (Path stringFilePath : filepaths) {
+      Document dom =
+          XmlDomParser.parse(ProjectFilesystemUtils.getPathForRelativePath(root, stringFilePath));
+
+      NodeList stringNodes = dom.getElementsByTagName("string");
+      scrapeStringNodes(stringNodes, stringsMap);
+
+      NodeList pluralNodes = dom.getElementsByTagName("plurals");
+      scrapePluralsNodes(pluralNodes, pluralsMap);
+
+      NodeList arrayNodes = dom.getElementsByTagName("string-array");
+      scrapeStringArrayNodes(arrayNodes, arraysMap);
+    }
+
+    return new StringResources(stringsMap, pluralsMap, arraysMap);
+  }
+
+  /**
+   * Scrapes string resource names and values from the list of xml nodes passed and populates {@code
+   * stringsMap}, ignoring resource names that are already present in the map.
+   *
+   * @param stringNodes A list of {@code <string></string>} nodes.
+   * @param stringsMap Map from string resource id to its values.
+   */
+  @VisibleForTesting
+  public void scrapeStringNodes(
+      NodeList stringNodes, Map<Integer, EnumMap<Gender, String>> stringsMap) {
+    for (int i = 0; i < stringNodes.getLength(); ++i) {
+      Element element = (Element) Objects.requireNonNull(stringNodes.item(i));
+      String resourceName = element.getAttribute("name");
+      Gender gender = getGender(element);
+
+      Integer resId = getResourceId(resourceName, gender, stringResourceNameToIdMap);
+      // Ignore a resource if R.txt does not contain an entry for it.
+      if (resId == null) {
+        continue;
+      }
+
+      EnumMap<Gender, String> genderMap = stringsMap.get(resId);
+      if (genderMap == null) {
+        genderMap = Maps.newEnumMap(Gender.class);
+      } else if (genderMap.containsKey(gender)) { // Ignore a resource if it has already been found
+        continue;
+      }
+
+      genderMap.put(gender, Objects.requireNonNull(element.getTextContent()));
+      stringsMap.put(resId, genderMap);
+    }
+  }
+
+  /** Similar to {@code scrapeStringNodes}, but for plurals nodes. */
+  @VisibleForTesting
+  public void scrapePluralsNodes(
+      NodeList pluralNodes,
+      Map<Integer, EnumMap<Gender, ImmutableMap<String, String>>> pluralsMap) {
+
+    for (int i = 0; i < pluralNodes.getLength(); ++i) {
+      Element element = (Element) Objects.requireNonNull(pluralNodes.item(i));
+      String resourceName = element.getAttribute("name");
+      Gender gender = getGender(element);
+
+      Integer resourceId = getResourceId(resourceName, gender, pluralsResourceNameToIdMap);
+      // Ignore a resource if R.txt does not contain an entry for it.
+      if (resourceId == null) {
+        continue;
+      }
+
+      EnumMap<Gender, ImmutableMap<String, String>> genderMap = pluralsMap.get(resourceId);
+      if (genderMap == null) {
+        genderMap = Maps.newEnumMap(Gender.class);
+      } else if (genderMap.containsKey(gender)) { // Ignore a resource if it has already been found
+        continue;
+      }
+
+      ImmutableMap.Builder<String, String> quantityToStringBuilder = ImmutableMap.builder();
+
+      NodeList itemNodes = element.getElementsByTagName("item");
+      for (int j = 0; j < itemNodes.getLength(); ++j) {
+        Node itemNode = Objects.requireNonNull(itemNodes.item(j));
+        String quantity =
+            Objects.requireNonNull(
+                Objects.requireNonNull(
+                        Objects.requireNonNull(itemNode.getAttributes()).getNamedItem("quantity"))
+                    .getNodeValue());
+        quantityToStringBuilder.put(quantity, Objects.requireNonNull(itemNode.getTextContent()));
+      }
+
+      genderMap.put(gender, quantityToStringBuilder.build());
+      pluralsMap.put(resourceId, genderMap);
+    }
+  }
+
+  /** Similar to {@code scrapeStringNodes}, but for string array nodes. */
+  @VisibleForTesting
+  public void scrapeStringArrayNodes(
+      NodeList arrayNodes, Map<Integer, EnumMap<Gender, ImmutableList<String>>> arraysMap) {
+
+    for (int i = 0; i < arrayNodes.getLength(); ++i) {
+      Element element = (Element) Objects.requireNonNull(arrayNodes.item(i));
+      String resourceName = element.getAttribute("name");
+      Gender gender = getGender(element);
+
+      Integer resourceId = getResourceId(resourceName, gender, arrayResourceNameToIdMap);
+      // Ignore a resource if R.txt does not contain an entry for it.
+      if (resourceId == null) {
+        continue;
+      }
+
+      EnumMap<Gender, ImmutableList<String>> genderMap = arraysMap.get(resourceId);
+      if (genderMap == null) {
+        genderMap = Maps.newEnumMap(Gender.class);
+      } else if (genderMap.containsKey(gender)) { // Ignore a resource if it has already been found
+        continue;
+      }
+
+      ImmutableList.Builder<String> arrayValues = ImmutableList.builder();
+      NodeList itemNodes = element.getElementsByTagName("item");
+      if (itemNodes.getLength() == 0) {
+        continue;
+      }
+      for (int j = 0; j < itemNodes.getLength(); ++j) {
+        arrayValues.add(
+            Objects.requireNonNull(Objects.requireNonNull(itemNodes.item(j)).getTextContent()));
+      }
+
+      genderMap.put(gender, arrayValues.build());
+      arraysMap.put(resourceId, genderMap);
+    }
+  }
+
+  /** Used in unit tests to inject the resource name to id map. */
+  @VisibleForTesting
+  public void addStringResourceNameToIdMap(Map<String, Integer> nameToIdMap) {
+    stringResourceNameToIdMap.putAll(nameToIdMap);
+  }
+
+  @VisibleForTesting
+  public void addPluralsResourceNameToIdMap(Map<String, Integer> nameToIdMap) {
+    pluralsResourceNameToIdMap.putAll(nameToIdMap);
+  }
+
+  @VisibleForTesting
+  public void addArrayResourceNameToIdMap(Map<String, Integer> nameToIdMap) {
+    arrayResourceNameToIdMap.putAll(nameToIdMap);
+  }
+
+  @Nullable
+  private static Integer getResourceId(
+      String name, Gender gender, Map<String, Integer> resourceToIdMap) {
+    Integer resId = null;
+    if (name.endsWith(FEMALE_SUFFIX) && gender.equals(Gender.female)) {
+      resId = resourceToIdMap.get(name.substring(0, name.length() - FEMALE_SUFFIX_LENGTH));
+    } else if (name.endsWith(MALE_SUFFIX) && gender.equals(Gender.male)) {
+      resId = resourceToIdMap.get(name.substring(0, name.length() - MALE_SUFFIX_LENGTH));
+    }
+
+    if (resId == null) {
+      resId = resourceToIdMap.get(name);
+    }
+
+    return resId;
+  }
+
+  /**
+   * Returns the Gender present in the passed in element's attribute, defaults to unknown gender
+   *
+   * @param element the element for which gender attribute is to be determined
+   * @return gender present in the element and unknown gender if not
+   */
+  private static Gender getGender(Element element) {
+    Gender gender = Gender.unknown;
+    boolean hasGender = element.hasAttribute("gender");
+    if (hasGender) {
+      gender = Gender.valueOf(element.getAttribute("gender"));
+    }
+    return gender;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/CopyStringResourcesExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/CopyStringResourcesExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/CopyStringResourcesExecutableMain.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.strings;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Entry point for copying string resources. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class CopyStringResourcesExecutableMain {
+  @Option(name = "--res-dirs", required = true)
+  private String resDirsFileString;
+
+  @Option(name = "--output", required = true)
+  private String outputPathString;
+
+  @Option(name = "--is-voltron")
+  private boolean isVoltron;
+
+  public static void main(String[] args) throws IOException {
+    CopyStringResourcesExecutableMain main = new CopyStringResourcesExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    AbsPath root = AbsPath.of(Paths.get(".").normalize().toAbsolutePath());
+    ImmutableList<Path> resDirs =
+        Files.readAllLines(Paths.get(resDirsFileString)).stream()
+            .map(Paths::get)
+            .collect(ImmutableList.toImmutableList());
+    Path outputPath = Paths.get(outputPathString);
+
+    if (isVoltron) {
+      StringResourcesUtils.copyVoltronStringResources(
+          root, resDirs, ImmutableList.of(), outputPath);
+    } else {
+      StringResourcesUtils.copyResources(root, resDirs, outputPath);
+    }
+
+    System.exit(0);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/PackageStringsAsAssetsExecutableMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/PackageStringsAsAssetsExecutableMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/PackageStringsAsAssetsExecutableMain.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.strings;
+
+import static com.facebook.buck.util.zip.ZipOutputStreams.HandleDuplicates.THROW_EXCEPTION;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.util.zip.CustomZipEntryWithPath;
+import com.facebook.buck.util.zip.CustomZipOutputStream;
+import com.facebook.buck.util.zip.Zip;
+import com.facebook.buck.util.zip.ZipCompressionLevel;
+import com.facebook.buck.util.zip.ZipOutputStreams;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.function.Function;
+import org.jetbrains.annotations.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+import org.xml.sax.SAXException;
+
+/** Entry point for packaging string resources as assets. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class PackageStringsAsAssetsExecutableMain {
+  private static final String STRING_ASSET_FILE_EXTENSION = ".fbstr";
+
+  @Option(name = "--string-files-list", required = true)
+  private String stringFilesList;
+
+  @Option(name = "--r-dot-txt", required = true)
+  private String rDotTxt;
+
+  @Option(name = "--string-assets-dir", required = true)
+  private String stringAssetsDir;
+
+  @Option(name = "--string-assets-zip", required = true)
+  private String stringAssetsZip;
+
+  @Option(name = "--all-locales-string-assets-zip", required = true)
+  private String allLocalesStringAssetsZip;
+
+  @Option(name = "--locales")
+  @Nullable
+  private String localesString = null;
+
+  public static void main(String[] args) throws IOException {
+    PackageStringsAsAssetsExecutableMain main = new PackageStringsAsAssetsExecutableMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.toString());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  private void run() throws IOException {
+    AbsPath root = AbsPath.of(Paths.get(".").normalize().toAbsolutePath());
+    ImmutableList<Path> stringFiles =
+        Files.readAllLines(Paths.get(stringFilesList)).stream()
+            .map(Paths::get)
+            .collect(ImmutableList.toImmutableList());
+    ImmutableSet<String> locales =
+        localesString != null ? ImmutableSet.copyOf(localesString.split(",")) : ImmutableSet.of();
+
+    Path stringAssetsDirPath = Paths.get(stringAssetsDir);
+    Path stringsDir = stringAssetsDirPath.resolve("assets").resolve("strings");
+    ProjectFilesystemUtils.mkdirs(root, stringsDir);
+    Function<String, Path> assetPathBuilder =
+        locale -> stringsDir.resolve(locale + STRING_ASSET_FILE_EXTENSION);
+
+    CompileStrings compileStrings = new CompileStrings();
+    try {
+      compileStrings.compileStrings(root, stringFiles, Paths.get(rDotTxt), assetPathBuilder);
+    } catch (SAXException e) {
+      throw new RuntimeException(e);
+    }
+
+    Path pathToStringAssetsZip = Paths.get(stringAssetsZip);
+    Path pathToAllLocalesStringAssetsZip = Paths.get(allLocalesStringAssetsZip);
+
+    zipEntries(
+        root,
+        pathToStringAssetsZip,
+        stringAssetsDirPath,
+        locales.stream().map(assetPathBuilder).collect(ImmutableSet.toImmutableSet()));
+    zipEntries(root, pathToAllLocalesStringAssetsZip, stringAssetsDirPath, ImmutableSet.of());
+
+    System.exit(0);
+  }
+
+  private void zipEntries(
+      AbsPath root, Path pathToZipFile, Path assetsDir, ImmutableSet<Path> pathsToInclude)
+      throws IOException {
+    Map<String, CustomZipEntryWithPath> entries = new TreeMap<>();
+
+    try (BufferedOutputStream baseOut =
+            new BufferedOutputStream(
+                ProjectFilesystemUtils.newFileOutputStream(root, pathToZipFile));
+        CustomZipOutputStream out = ZipOutputStreams.newOutputStream(baseOut, THROW_EXCEPTION)) {
+      Zip.walkBaseDirectoryToCreateEntries(
+          root,
+          entries,
+          assetsDir,
+          ImmutableSet.of(),
+          pathsToInclude,
+          false,
+          ZipCompressionLevel.MAX);
+      Zip.writeEntriesToZip(root, out, entries);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/StringResources.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/StringResources.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/StringResources.java
@@ -0,0 +1,285 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.strings;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.EnumMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/**
+ * Represents string resources of types string, plural and array for a locale. Also responsible for
+ * generating a custom format binary file for the resources.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class StringResources {
+
+  /**
+   * The values here need to be lowercase as we follow the standard in android xml files of using
+   * lower case
+   */
+  public enum Gender {
+    unknown,
+    female,
+    male
+  }
+
+  /**
+   * Bump this whenever there's a change in the file format. The parser can decide to abort parsing
+   * if the version it finds in the file does not match it's own version, thereby avoiding potential
+   * data corruption issues.
+   */
+  private static final int FORMAT_VERSION = 2;
+
+  public final SortedMap<Integer, EnumMap<Gender, String>> strings;
+  public final SortedMap<Integer, EnumMap<Gender, ImmutableMap<String, String>>> plurals;
+  // This is not a TreeMultimap because we only want the keys to be sorted by their natural
+  // ordering, not the values array. The values should be in the same order as insertion.
+  public final SortedMap<Integer, EnumMap<Gender, ImmutableList<String>>> arrays;
+
+  /**
+   * These are the 6 fixed plural categories for string resources in Android. This mapping is not
+   * expected to change over time. We encode them as integers to optimize space.
+   *
+   * <p>For more information, refer to: <a
+   * href="http://developer.android.com/guide/topics/resources/string-resource.html#Plurals">String
+   * Resources | Android Developers </a>
+   */
+  private static final ImmutableMap<String, Integer> PLURAL_CATEGORY_MAP =
+      ImmutableMap.<String, Integer>builder()
+          .put("zero", 0)
+          .put("one", 1)
+          .put("two", 2)
+          .put("few", 3)
+          .put("many", 4)
+          .put("other", 5)
+          .build();
+
+  private static Charset charset = StandardCharsets.UTF_8;
+
+  public StringResources(
+      SortedMap<Integer, EnumMap<Gender, String>> strings,
+      SortedMap<Integer, EnumMap<Gender, ImmutableMap<String, String>>> plurals,
+      SortedMap<Integer, EnumMap<Gender, ImmutableList<String>>> arrays) {
+    this.strings = strings;
+    this.plurals = plurals;
+    this.arrays = arrays;
+  }
+
+  public StringResources getMergedResources(StringResources otherResources) {
+    TreeMap<Integer, EnumMap<Gender, String>> stringsMap = Maps.newTreeMap(otherResources.strings);
+    TreeMap<Integer, EnumMap<Gender, ImmutableMap<String, String>>> pluralsMap =
+        Maps.newTreeMap(otherResources.plurals);
+    TreeMap<Integer, EnumMap<Gender, ImmutableList<String>>> arraysMap =
+        Maps.newTreeMap(otherResources.arrays);
+
+    stringsMap.putAll(strings);
+    pluralsMap.putAll(plurals);
+    arraysMap.putAll(arrays);
+
+    return new StringResources(stringsMap, pluralsMap, arraysMap);
+  }
+
+  /**
+   * Returns a byte array that represents the entire set of strings, plurals and string arrays in
+   * the following binary file format:
+   *
+   * <p>
+   *
+   * <pre>
+   *   [Int: Version]
+   *
+   *   [Int: # of strings]
+   *   [Int: Smallest resource id among strings]
+   *   [[Short: resource id delta] [Byte: #genders] [[Byte: gender enum ordinal] [Short: length of
+   *    the string]] x #genders] x # of strings
+   *   [Byte array of the string value] x # summation of genders over # of strings
+   *
+   *   [Int: # of plurals]
+   *   [Int: Smallest resource id among plurals]
+   *   [[Short: resource id delta] [Byte: #genders] [[Byte: gender enum ordinal] [Byte: #categories]
+   *    [[Byte: category] [Short: length of plural value]] x #categories] x # of genders]
+   *    x # of plurals
+   *   [Byte array of plural value] x Summation of genders over plural categories over # of plurals
+   *
+   *   [Int: # of arrays]
+   *   [Int: Smallest resource id among arrays]
+   *   [[Short: resource id delta] [Byte: #genders] [[Byte: gender enum ordinal] [Int: #elements]
+   *    [Short: length of element] x # phaof elements] x # of genders] x # of arrays
+   *   [Byte array of string value] x Summation of genders over array elements over # of arrays
+   * </pre>
+   */
+  public byte[] getBinaryFileContent() {
+    try (ByteArrayOutputStream bytesStream = new ByteArrayOutputStream();
+        DataOutputStream outputStream = new DataOutputStream(bytesStream)) {
+      outputStream.writeInt(FORMAT_VERSION);
+
+      writeStrings(outputStream);
+      writePlurals(outputStream);
+      writeArrays(outputStream);
+
+      return bytesStream.toByteArray();
+    } catch (IOException e) {
+      // This should never happen since DataOutputStream redirects all calls to the underlying
+      // stream and ByteArrayOutputStream does not throw IOException.
+      throw new RuntimeException(e);
+    }
+  }
+
+  /**
+   * Writes the metadata and strings in the following format to the output stream: [Int: # of
+   * strings] [Int: Smallest resource id among strings] [[Short: resource id delta] [Byte: #genders]
+   * [[Byte: gender enum ordinal] [Short: length of the string] [Byte array of the string value]] x
+   * #genders] x # of strings
+   *
+   * @param outputStream
+   * @throws IOException
+   */
+  private void writeStrings(DataOutputStream outputStream) throws IOException {
+    outputStream.writeInt(strings.size());
+    if (strings.isEmpty()) {
+      return;
+    }
+    int previousResourceId = strings.firstKey();
+    outputStream.writeInt(previousResourceId);
+
+    try (ByteArrayOutputStream dataStream = new ByteArrayOutputStream()) {
+      for (Map.Entry<Integer, EnumMap<Gender, String>> entry : strings.entrySet()) {
+        writeShort(outputStream, entry.getKey() - previousResourceId);
+        EnumMap<Gender, String> genderMap = entry.getValue();
+        outputStream.writeByte(genderMap.size());
+
+        for (Map.Entry<Gender, String> gender : genderMap.entrySet()) {
+          outputStream.writeByte(gender.getKey().ordinal());
+          byte[] genderValue = getUnescapedStringBytes(gender.getValue());
+          writeShort(outputStream, genderValue.length);
+          dataStream.write(genderValue);
+        }
+
+        previousResourceId = entry.getKey();
+      }
+      outputStream.write(dataStream.toByteArray());
+    }
+  }
+
+  /**
+   * Writes the metadata and strings in the following format to the output stream: [Int: # of
+   * plurals] [Int: Smallest resource id among plurals] [[Short: resource id delta] [Byte: #genders]
+   * [[Byte: gender enum ordinal] [Byte: #categories] [[Byte: category] [Short: length of plural
+   * value]] x #categories] x # of genders] x # of plurals [Byte array of plural value] x Summation
+   * of gedners over plural categories over # of plurals
+   *
+   * @param outputStream
+   * @throws IOException
+   */
+  private void writePlurals(DataOutputStream outputStream) throws IOException {
+    outputStream.writeInt(plurals.size());
+    if (plurals.isEmpty()) {
+      return;
+    }
+    int previousResourceId = plurals.firstKey();
+    outputStream.writeInt(previousResourceId);
+
+    try (ByteArrayOutputStream dataStream = new ByteArrayOutputStream()) {
+      for (Map.Entry<Integer, EnumMap<Gender, ImmutableMap<String, String>>> entry :
+          plurals.entrySet()) {
+        writeShort(outputStream, entry.getKey() - previousResourceId);
+
+        EnumMap<Gender, ImmutableMap<String, String>> genderMap = entry.getValue();
+        outputStream.writeByte(genderMap.size());
+
+        for (Map.Entry<Gender, ImmutableMap<String, String>> gender : genderMap.entrySet()) {
+          outputStream.writeByte(gender.getKey().ordinal());
+
+          ImmutableMap<String, String> categoryMap = gender.getValue();
+          outputStream.writeByte(categoryMap.size());
+
+          for (Map.Entry<String, String> cat : categoryMap.entrySet()) {
+            outputStream.writeByte(
+                Objects.requireNonNull(PLURAL_CATEGORY_MAP.get(cat.getKey())).byteValue());
+            byte[] pluralValue = getUnescapedStringBytes(cat.getValue());
+            writeShort(outputStream, pluralValue.length);
+            dataStream.write(pluralValue);
+          }
+        }
+
+        previousResourceId = entry.getKey();
+      }
+
+      outputStream.write(dataStream.toByteArray());
+    }
+  }
+
+  /**
+   * Writes the metadata and strings in the following format to the output stream: [Int: # of
+   * arrays] [Int: Smallest resource id among arrays] [[Short: resource id delta] [Byte: #genders]
+   * [[Byte: gender enum ordinal] [Int: #elements] [[Short: length of element] x # of elements]] x #
+   * of genders] x # of arrays [Byte array of string value] x Summation of genders over array
+   * elements over # of arrays
+   *
+   * @param outputStream
+   * @throws IOException
+   */
+  private void writeArrays(DataOutputStream outputStream) throws IOException {
+    outputStream.writeInt(arrays.keySet().size());
+    if (arrays.keySet().isEmpty()) {
+      return;
+    }
+    int previousResourceId = arrays.firstKey();
+    outputStream.writeInt(previousResourceId);
+
+    try (ByteArrayOutputStream dataStream = new ByteArrayOutputStream()) {
+      for (Map.Entry<Integer, EnumMap<Gender, ImmutableList<String>>> entry : arrays.entrySet()) {
+        writeShort(outputStream, entry.getKey() - previousResourceId);
+
+        EnumMap<Gender, ImmutableList<String>> genderMap = entry.getValue();
+        outputStream.writeByte(genderMap.size());
+
+        for (Map.Entry<Gender, ImmutableList<String>> gender : genderMap.entrySet()) {
+          outputStream.writeByte(gender.getKey().ordinal());
+
+          ImmutableList<String> arrayElements = gender.getValue();
+          outputStream.writeByte(arrayElements.size());
+          for (String arrayValue : arrayElements) {
+            byte[] byteValue = getUnescapedStringBytes(arrayValue);
+            writeShort(outputStream, byteValue.length);
+            dataStream.write(byteValue);
+          }
+        }
+        previousResourceId = entry.getKey();
+      }
+      outputStream.write(dataStream.toByteArray());
+    }
+  }
+
+  private void writeShort(DataOutputStream stream, int number) throws IOException {
+    Preconditions.checkState(
+        number <= Short.MAX_VALUE, "Error attempting to compact a numeral to short: " + number);
+    stream.writeShort(number);
+  }
+
+  @VisibleForTesting
+  static byte[] getUnescapedStringBytes(String value) {
+    return value.replace("\\\"", "\"").replace("\\'", "'").getBytes(charset);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/StringResourcesUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/StringResourcesUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/resources/strings/StringResourcesUtils.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.resources.strings;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.file.PathMatcher;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableCollection;
+import com.google.common.collect.ImmutableList;
+import java.io.IOException;
+import java.nio.file.Path;
+
+/**
+ * Copy filtered string resources (values/strings.xml) files to output directory. These will be used
+ * by i18n to map resource_id to fbt_hash with resource_name as the intermediary
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class StringResourcesUtils {
+  private static final String VALUES = "values";
+  private static final String STRINGS_XML = "strings.xml";
+  private static final String NEW_RES_DIR_FORMAT = "%04x";
+
+  // "4 digit hex" => 65536 files
+
+  /*
+   * Copy all strings.xml under resDir/values to output Path
+   */
+  public static void copyResources(
+      AbsPath projectRoot, ImmutableList<Path> resDirs, Path outputDirPath) throws IOException {
+    int i = 0;
+    for (Path resDir : resDirs) {
+      Path stringsFilePath = resDir.resolve(VALUES).resolve(STRINGS_XML);
+      if (ProjectFilesystemUtils.exists(projectRoot, stringsFilePath)) {
+        // create <output_dir>/<new_res_dir>/values
+        Path newStringsFileDir =
+            outputDirPath.resolve(String.format(NEW_RES_DIR_FORMAT, i++)).resolve(VALUES);
+        ProjectFilesystemUtils.mkdirs(projectRoot, newStringsFileDir);
+        // copy <res_dir>/values/strings.xml ->
+        // <output_dir>/<new_res_dir>/values/strings.xml
+        ProjectFilesystemUtils.copyFile(
+            projectRoot, stringsFilePath, newStringsFileDir.resolve(STRINGS_XML));
+      }
+    }
+  }
+
+  /**
+   * Copy all strings.xml under resDir/values-xx to output Path
+   *
+   * @param resDirs List of directories that contains values-xx/strings.
+   */
+  public static void copyVoltronStringResources(
+      AbsPath projectRoot,
+      ImmutableList<Path> resDirs,
+      ImmutableCollection<PathMatcher> ignores,
+      Path outputDirPath)
+      throws IOException {
+    int i = 0;
+    for (Path resDir : resDirs) {
+      if (ProjectFilesystemUtils.exists(projectRoot, resDir)) {
+        ImmutableCollection<Path> dirs =
+            ProjectFilesystemUtils.getDirectoryContents(projectRoot, ignores, resDir);
+        boolean containNonEnglishStrings = false;
+        for (Path dir : dirs) {
+          String filename = dir.getFileName().toString();
+          if (filename.startsWith(VALUES) && !filename.equals(VALUES)) {
+            Path stringsFilePath = resDir.resolve(filename).resolve(STRINGS_XML);
+            if (ProjectFilesystemUtils.exists(projectRoot, stringsFilePath)) {
+              // create <output_dir>/<new_res_dir>/values-xx
+              Path newStringsFileDir =
+                  outputDirPath.resolve(String.format(NEW_RES_DIR_FORMAT, i)).resolve(filename);
+              ProjectFilesystemUtils.mkdirs(projectRoot, newStringsFileDir);
+              // copy <res_dir>/values-es/strings.xml ->
+              // <output_dir>/<new_res_dir>/values-es/strings.xml
+              ProjectFilesystemUtils.copyFile(
+                  projectRoot, stringsFilePath, newStringsFileDir.resolve(STRINGS_XML));
+              containNonEnglishStrings = true;
+            }
+          }
+        }
+        if (containNonEnglishStrings) {
+          ++i;
+        }
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/zipalign/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/zipalign/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/zipalign/BUCK
@@ -0,0 +1,16 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "zipalign",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/android/zipalign/ZipAlign.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/zipalign/ZipAlign.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/android/zipalign/ZipAlign.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.android.zipalign;
+
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.io.CharStreams;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.util.Objects;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ZipAlign {
+
+  private final String zipalignPath;
+
+  private final String intermediateApkPath;
+
+  private final String zipalignApkPath;
+
+  public ZipAlign(String zipalignPath, String intermediateApkPath, String zipalignApkPath) {
+    this.zipalignPath = zipalignPath;
+    this.intermediateApkPath = intermediateApkPath;
+    this.zipalignApkPath = zipalignApkPath;
+  }
+
+  public void run() throws InterruptedException, IOException {
+    Process zipalignProcess =
+        new ProcessBuilder()
+            .command(zipalignPath, "-f", "4", intermediateApkPath, zipalignApkPath)
+            .start();
+    zipalignProcess.waitFor();
+    if (zipalignProcess.exitValue() != 0) {
+      String errorMessage;
+      try (Reader reader =
+          new InputStreamReader(Objects.requireNonNull(zipalignProcess.getErrorStream()))) {
+        errorMessage = CharStreams.toString(reader);
+      }
+      if (errorMessage.contains("Unable to open")) {
+        errorMessage =
+            errorMessage.concat(
+                "\n"
+                    + "This issue is usually caused by having more than 2^^16 files in the APK. Try"
+                    + " filtering out some resources, or follow D75775793 to only pack single"
+                    + " preferred density resource as mitigation\n");
+      }
+
+      throw new RuntimeException("zipalign failed to process apk file:\n" + errorMessage);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/BUCK
@@ -0,0 +1,60 @@
+load("@prelude//toolchains/android/tools:protobuf.bzl", "protobuf_src_gen")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+filegroup(
+    name = "jvm_cd_proto",
+    srcs = glob(["*.proto"]),
+)
+
+protobuf_src_gen(
+    name = "cd-model",
+    srcs = [
+        "common.proto",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:jakarta.annotation-api",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/third-party:protobuf",
+    ],
+)
+
+protobuf_src_gen(
+    name = "javacd-model",
+    srcs = [
+        "common.proto",
+        "javacd.proto",
+    ],
+    proto_path = [
+        "$(location :cd-model)",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:jakarta.annotation-api",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/third-party:protobuf",
+    ],
+)
+
+protobuf_src_gen(
+    name = "kotlincd-model",
+    srcs = [
+        "common.proto",
+        "kotlincd.proto",
+    ],
+    proto_path = [
+        "$(location :jvm_cd_proto)",
+        "$(location :cd-model)",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:jakarta.annotation-api",
+        ":javacd-model",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/third-party:protobuf",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/common.proto b/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/common.proto
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/common.proto
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+//----------------------------------------------
+//  Generate command
+//----------------------------------------------
+//
+// When modifying this file, please run the following generate command,
+// and include generated code in your commit
+//
+// fbcode/buck2/prelude/toolchains/android/tools/protobuf/gen.py
+//
+//-----------------------
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+option java_package = "com.facebook.buck.cd.model.common";
+option java_outer_classname = "CommonCDProto";
+
+// protobuf map doesn't support custom type as map key, so would present a map
+// as list of entries.
+message RelPathMapEntry {
+  string key = 1;
+  string value = 2;
+}
+
+message PostBuildParams {
+  string libraryJar = 1;
+  string abiJar = 2;
+  string jvmAbiGen = 4;
+  string abiOutputDir = 5;
+  repeated string usedClasses = 6;
+  string depFile = 7;
+  reserved 8;
+  reserved "jarToJarDirMap";
+  repeated string optionalDirs = 9;
+  string incrementalStateDir = 10;
+  bool shouldCreateClassAbi = 11;
+  string usedJarsFile = 12;
+  string postProcessorCmd = 13;
+  string filesWhichSkippedCompilation = 14;
+  string jvmAbiFilesWhichSkippedCompilation = 15;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/javacd.proto b/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/javacd.proto
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/javacd.proto
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+//----------------------------------------------
+//  Generate command
+//----------------------------------------------
+//
+// When modifying this file, please run the following generate command,
+// and include generated code in your commit
+//
+// fbcode/buck2/prelude/toolchains/android/tools/protobuf/gen.py
+//
+//-----------------------
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+option java_package = "com.facebook.buck.cd.model.java";
+option java_outer_classname = "JavaCDProto";
+
+// best practices to include version number in package
+package javacd.api.v1;
+
+import "common.proto";
+
+// Represents a single rule command either library or abi jar
+message BuildJavaCommand {
+  BuildCommand buildCommand = 1;
+  PostBuildParams postBuildParams = 3;
+}
+
+message BuildCommand {
+  BuildMode buildMode = 1;
+  BaseJarCommand baseJarCommand = 2;
+}
+
+enum BuildMode {
+  BUILD_MODE_UNSPECIFIED = 0;
+  // Represents a build command that generates full library
+  LIBRARY = 1;
+  // Represents a build command that generates abi
+  ABI = 2;
+}
+
+// Common parameters for build jar commands (abi and library jar ones)
+message BaseJarCommand {
+  reserved 1;
+  reserved "abiCompatibilityMode";
+  AbiGenerationMode abiGenerationMode = 2;
+  bool isRequiredForSourceOnlyAbi = 3;
+  bool trackClassUsage = 4;
+  reserved 6;
+  reserved "configuredBuckOut";
+  BuildTargetValue buildTargetValue = 7;
+  OutputPathsValue outputPathsValue = 8;
+  repeated string compileTimeClasspathPaths = 9;
+  repeated string javaSrcs = 10;
+  repeated RelPathMapEntry resourcesMap = 13;
+  JarParameters jarParameters = 15;
+  string buildCellRootPath = 16;
+  reserved 17;
+  reserved "resolvedJavac";
+  ResolvedJavacOptions resolvedJavacOptions = 18;
+  repeated string compileTimeClasspathSnapshotPaths = 19;
+  reserved 20;
+  reserved "pathToClasses";
+  // Optional. When omitted, generated sources stay in BUCK_SCRATCH_PATH.
+  string annotationsPath = 23;
+  // Alternating ABI jar and directory paths, in classpath order. An empty
+  // directory keeps jar-level dep-file tracking. Mutually exclusive with
+  // compileTimeClasspathPaths.
+  repeated string compileTimeClasspathAbiAndDirPaths = 24;
+}
+
+enum AbiGenerationMode {
+  UNKNOWN = 0;
+  /** Generate ABIs by stripping .class files */
+  CLASS = 1;
+  /** Generate ABIs by parsing .java files with dependency ABIs available */
+  SOURCE = 2;
+  /**
+   * Output warnings for things that aren't legal when generating ABIs from
+   * source without dependency ABIs
+   */
+  MIGRATING_TO_SOURCE_ONLY = 3;
+  /**
+   * Generate ABIs by parsing .java files without dependency ABIs available (has
+   * some limitations)
+   */
+  SOURCE_ONLY = 4;
+}
+
+message BuildTargetValue {
+  string fullyQualifiedName = 1;
+  Type type = 2;
+  // reserved = 3;
+  enum Type {
+    UNKNOWN = 0;
+    LIBRARY = 1;
+    SOURCE_ABI = 2;
+    SOURCE_ONLY_ABI = 3;
+  }
+}
+
+message OutputPathsValue {
+  OutputPaths libraryPaths = 1;
+  OutputPaths sourceAbiPaths = 2;
+  OutputPaths sourceOnlyAbiPaths = 3;
+  string libraryTargetFullyQualifiedName = 4;
+
+  message OutputPaths {
+    reserved 1;
+    reserved "classesDir";
+    string outputJarDirPath = 2;
+    string abiJarPath = 3;
+    // Optional. When omitted, generated sources stay in BUCK_SCRATCH_PATH.
+    string annotationPath = 4;
+    string pathToSourcesList = 5;
+    string workingDirectory = 6;
+    string outputJarPath = 7;
+  }
+}
+
+message ResolvedJavacOptions {
+  // reserved = 1;
+  repeated string bootclasspathList = 2;
+  JavacLanguageLevelOptions languageLevelOptions = 3;
+  reserved 4;
+  reserved "debug";
+  bool verbose = 5;
+  JavacPluginParams javaAnnotationProcessorParams = 6;
+  JavacPluginParams standardJavacPluginParams = 7;
+  repeated string extraArguments = 8;
+
+  // reserved = 9;
+  // reserved = 10;
+  // reserved = 11;
+
+  string systemImage = 12;
+
+  message JavacLanguageLevelOptions {
+    string sourceLevel = 1;
+    string targetLevel = 2;
+  }
+
+  message JavacPluginParams {
+    repeated string parameters = 1;
+    repeated ResolvedJavacPluginProperties pluginProperties = 2;
+  }
+
+  message ResolvedJavacPluginProperties {
+    bool canReuseClassLoader = 1;
+    bool doesNotAffectAbi = 2;
+    bool supportsAbiGenerationFromSource = 3;
+    bool runsOnJavaOnly = 4;
+    repeated string processorNames = 5;
+    repeated string classpath = 6;
+    reserved 7;
+    reserved "pathParams";
+    repeated string arguments = 8;
+  }
+}
+
+message JarParameters {
+  bool hashEntries = 1;
+  bool mergeManifests = 2;
+  string jarPath = 3;
+  RemoveClassesPatternsMatcher removeEntryPredicate = 4;
+  repeated string entriesToJar = 5;
+  repeated string overrideEntriesToJar = 6;
+  string mainClass = 7;
+  string manifestFile = 8;
+  reserved 9;
+  reserved "duplicatesLogLevel";
+
+  message RemoveClassesPatternsMatcher {
+    repeated string patterns = 1;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/kotlincd.proto b/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/kotlincd.proto
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/cd/resources/proto/kotlincd.proto
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+option java_package = "com.facebook.buck.cd.model.kotlin";
+option java_outer_classname = "KotlinCDProto";
+
+// best practices to include version number in package
+package kotlincd.api.v1;
+
+import "javacd.proto";
+import "common.proto";
+
+message BuildKotlinCommand {
+  BuildCommand buildCommand = 1;
+  PostBuildParams postBuildParams = 2;
+}
+
+message BuildCommand {
+  javacd.api.v1.BuildMode buildMode = 1;
+  javacd.api.v1.BaseJarCommand baseJarCommand = 2;
+  KotlinExtraParams kotlinExtraParams = 3;
+}
+
+message KotlinExtraParams {
+  repeated string extraClassPaths = 2;
+  string standardLibraryClassPath = 3;
+  string annotationProcessingClassPath = 4;
+  reserved 5;
+  repeated string extraKotlincArguments = 6;
+  // kotlinCompilerPlugin keys are strings encoded as strings due to limitations
+  // in proto3.
+  map<string, PluginParams> kotlinCompilerPlugins = 7;
+  map<string, string> kosabiPluginOptions = 8;
+  reserved 9;
+  reserved "kosabiJvmAbiGenEarlyTerminationMessagePrefix";
+  repeated string friendPaths = 10;
+  repeated string kotlinHomeLibraries = 11;
+  string jvmTarget = 12;
+  reserved 13;
+  bool shouldUseJvmAbiGen = 14;
+  string jvmAbiGenPlugin = 15;
+  bool shouldVerifySourceOnlyAbiConstraints = 16;
+  bool shouldRemoveKotlinCompilerFromClassPath = 17;
+  string depTrackerPlugin = 18;
+  bool shouldKotlincRunIncrementally = 21;
+  string incrementalStateDir = 22;
+  string languageVersion = 23;
+  repeated string extraClassPathSnapshots = 24;
+  bool shouldKsp2RunIncrementally = 26;
+  reserved 27; // was shouldKosabiJvmAbiGenUseK2, unused (kotlincd derives K2
+               // from LanguageVersion.getSupportsK2())
+  reserved 28;
+  reserved "kotlinClassesDir";
+  reserved 29; // was skipClasspathRemovalRebuild, removed after KT-85740 fix
+  string javaBinary = 30;
+  // Reduced SO-ABI classpath for the applicability plugin (only deps with
+  // required_for_source_only_abi=True or in source_only_abi_deps). Distinct
+  // from compileTimeClasspathPaths which contains the full dep set during
+  // library builds.
+  repeated string applicabilityClasspath = 31;
+}
+
+message PluginParams {
+  map<string, string> params = 1;
+}
+
+/** Model for metadata provided by Buck2 incremental action see:
+ * https://buck2.build/docs/rule_authors/incremental_actions */
+message ActionMetadata {
+  Metadata previousMetadata = 1;
+  Metadata currentMetadata = 2;
+}
+
+message Metadata {
+  repeated Digests digests = 1;
+}
+
+message Digests {
+  string path = 1;
+  string digest = 2;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/BUCK
@@ -0,0 +1,50 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_binary(
+    name = "bootstrapper",
+    main_class = "com.facebook.buck.cli.bootstrapper.ClassLoaderBootstrapper",
+    visibility = [
+        "fbcode//buck2/platform/...",
+        "fbsource//xplat/buck2/platform/...",
+        "prelude//toolchains/android/config:",
+        "prelude//toolchains/android/meta_only/src/com/facebook/buck/jvm/remote_worker/...",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/worker:",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/worker:",
+        "toolchains//...",
+        # @oss-disable[end= ]: "wa_android//buck2/toolchains/...",
+    ],
+    deps = [
+        ":bootstrapper_lib",
+    ],
+)
+
+buck_java_library(
+    name = "bootstrapper_lib",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+        "prelude//toolchains/android/test/...",
+        "prelude//toolchains/android/third-party/aosp:aosp",
+        "prelude//toolchains/android/tools/...",
+    ],
+    deps = [
+        # Be very careful what is added here, and leave comments justifying
+        # each addition. The bootstrapper is intended to keep the
+        # system ClassLoader free of classes that might conflict with
+        # those used by compiler plugins and annotation processors. As such,
+        # it cannot depend on third-party libraries, directly or indirectly.
+        # This is an internal API used to communicate between Buck and the source-based ABI validator
+        # running inside javac.
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api:api",
+        # This is a set of utility classes for working with javax.lang.model that are useful both
+        # from Buck and the compiler
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/lang/model:model",
+        # This is an internal API used to communicate between Buck and the compiler plugin
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/api:api",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapper.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.cli.bootstrapper;
+
+import java.util.Arrays;
+
+/**
+ * This class sets up a separate ClassLoader for most of Buck's implementation, leaving only the
+ * bare minimum bootstrapping classes (and a few classes for compatibility with library code that is
+ * not ClassLoader-aware) in the system ClassLoader. This is done so that annotation processors do
+ * not have their classpaths polluted with Buck's dependencies when Buck is compiling Java code
+ * in-process.
+ *
+ * <p>Under JSR-199, when the Java compiler is run in-process it uses a ClassLoader that is a child
+ * of the system ClassLoader. In order for annotation processors to access the Compiler Tree API
+ * (which lives in tools.jar with the compiler itself), they must be loaded with a ClassLoader
+ * descended from the compiler's. If Buck used the system ClassLoader as a normal Java application
+ * would, this would result in annotation processors getting Buck's versions of Guava, Jackson, etc.
+ * instead of their own.
+ */
+public final class ClassLoaderBootstrapper {
+
+  static {
+    // On macOS, this will suppress the Dock icon if any libraries try to use AWT somewhere.
+    System.setProperty("apple.awt.UIElement", "true");
+  }
+
+  private static final ClassLoader classLoader = ClassLoaderFactory.withEnv().create();
+
+  private ClassLoaderBootstrapper() {}
+
+  /** Main method */
+  public static void main(String[] args) {
+    // Some things (notably Jetty) use the context class loader to load stuff
+    Thread.currentThread().setContextClassLoader(classLoader);
+
+    String mainClassName = args[0];
+    String[] remainingArgs = Arrays.copyOfRange(args, 1, args.length);
+    ClassLoaderBootstrapperUtils.invokeMainMethod(classLoader, mainClassName, remainingArgs);
+  }
+
+  public static Class<?> loadClass(String name) {
+    try {
+      return classLoader.loadClass(name);
+    } catch (ClassNotFoundException e) {
+      throw new NoClassDefFoundError(name);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapperUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapperUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapperUtils.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.cli.bootstrapper;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+/** Utility class for {@link ClassLoaderBootstrapper} */
+class ClassLoaderBootstrapperUtils {
+
+  private ClassLoaderBootstrapperUtils() {}
+
+  static void invokeMainMethod(ClassLoader classLoader, String mainClassName, String[] args) {
+    Method mainMethod = getMainMethod(classLoader, mainClassName);
+    try {
+      mainMethod.invoke(null, (Object) args);
+    } catch (IllegalAccessException e) {
+      throw new IllegalStateException("Can't access main() method.", e);
+    } catch (InvocationTargetException e) {
+      throw new IllegalStateException("Exception during main() method execution", e.getCause());
+    }
+  }
+
+  private static Method getMainMethod(ClassLoader classLoader, String mainClassName) {
+    Class<?> mainClass = loadClassWithMainFunction(classLoader, mainClassName);
+    try {
+      return mainClass.getMethod("main", String[].class);
+    } catch (NoSuchMethodException e) {
+      throw new IllegalStateException("Can't find a main() method in class: " + mainClassName, e);
+    }
+  }
+
+  private static Class<?> loadClassWithMainFunction(ClassLoader classLoader, String mainClassName) {
+    try {
+      return classLoader.loadClass(mainClassName);
+    } catch (ClassNotFoundException e) {
+      throw new IllegalStateException("Can't find class: " + mainClassName, e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/cli/bootstrapper/ClassLoaderFactory.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.cli.bootstrapper;
+
+import static java.util.Objects.requireNonNull;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.Paths;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+/** Creates a ClassLoader from {@code System.getenv()}. classpath entries. */
+public class ClassLoaderFactory {
+
+  /** Expose a provider to facilitate mock tests. */
+  @FunctionalInterface
+  public interface ClassPathProvider extends Function<String, String> {}
+
+  static final String BUCK_CLASSPATH = "BUCK_CLASSPATH";
+  static final String EXTRA_BUCK_CLASSPATH = "EXTRA_BUCK_CLASSPATH";
+
+  private final ClassPathProvider classPathProvider;
+
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  static ClassLoaderFactory withEnv() {
+    return new ClassLoaderFactory(System.getenv()::get);
+  }
+
+  ClassLoaderFactory(ClassPathProvider classPathProvider) {
+    this.classPathProvider = requireNonNull(classPathProvider);
+  }
+
+  /**
+   * Create a new ClassLoader that concats {@value BUCK_CLASSPATH} and {@value EXTRA_BUCK_CLASSPATH}
+   *
+   * @return ClassLoader instance to env classpath.
+   */
+  public ClassLoader create() {
+    // BUCK_CLASSPATH is not set by a user, no need to use EnvVariablesProvider.
+    String classPath = classPathProvider.apply(BUCK_CLASSPATH);
+    String extraClassPath = classPathProvider.apply(EXTRA_BUCK_CLASSPATH);
+
+    if (classPath == null) {
+      throw new RuntimeException(BUCK_CLASSPATH + " not set");
+    }
+
+    URL[] urls =
+        Stream.of(classPath, extraClassPath)
+            .flatMap(this::splitPaths)
+            .filter(this::nonBlank)
+            .map(this::toUrl)
+            .toArray(URL[]::new);
+
+    return new URLClassLoader(urls);
+  }
+
+  private Stream<String> splitPaths(String paths) {
+    if (paths == null) {
+      return Stream.empty();
+    }
+    return Stream.of(paths.split(File.pathSeparator));
+  }
+
+  private boolean nonBlank(String path) {
+    return !path.isBlank();
+  }
+
+  private URL toUrl(String path) {
+    try {
+      return Paths.get(path).toUri().toURL();
+    } catch (MalformedURLException e) {
+      throw new RuntimeException(e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/build/execution/context/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/build/execution/context/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/build/execution/context/BUCK
@@ -0,0 +1,23 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "context",
+    srcs = glob(["*.kt"]),
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/util:process_executor",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/build/execution/context/IsolatedExecutionContext.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/build/execution/context/IsolatedExecutionContext.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/build/execution/context/IsolatedExecutionContext.kt
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.build.execution.context
+
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.util.ClassLoaderCache
+import com.facebook.buck.util.Console
+import com.facebook.buck.util.Verbosity
+import com.google.common.io.Closer
+import java.io.Closeable
+import java.io.IOException
+import java.io.PrintStream
+import java.util.Optional
+
+/** The context exposed for executing `IsolatedStep`s */
+data class IsolatedExecutionContext(
+    val classLoaderCache: ClassLoaderCache,
+    val console: Console,
+    val ruleCellRoot: AbsPath,
+) : Closeable {
+  val verbosity: Verbosity
+    get() = console.verbosity
+
+  val stdErr: PrintStream
+    get() = console.stdErr
+
+  val stdOut: PrintStream
+    get() = console.stdErr
+
+  @Throws(IOException::class)
+  override fun close() {
+    // Using a Closer makes it easy to ensure that exceptions from one of the closeables don't
+    // cancel the others.
+    Closer.create().use { closer -> registerCloseables(closer) }
+  }
+
+  protected fun registerCloseables(closer: Closer) {
+    closer.register(Closeable { classLoaderCache.close() })
+  }
+
+  /** Creates SubContext */
+  fun createSubContext(
+      newStdout: PrintStream?,
+      newStderr: PrintStream?,
+      verbosityOverride: Optional<Verbosity?>,
+  ): IsolatedExecutionContext {
+    val console = this.console
+    val newConsole = Console(verbosityOverride.orElse(console.verbosity), newStdout, newStderr)
+
+    // This should replace (or otherwise retain) all of the closeable parts of the context.
+    return IsolatedExecutionContext(
+        classLoaderCache.addRef(),
+        newConsole,
+        ruleCellRoot,
+    )
+  }
+
+  companion object {
+    /** Returns an [IsolatedExecutionContext]. */
+    @JvmStatic
+    fun of(
+        classLoaderCache: ClassLoaderCache,
+        console: Console,
+        ruleCellRoot: AbsPath,
+    ): IsolatedExecutionContext {
+      return IsolatedExecutionContext(
+          classLoaderCache.addRef(),
+          console,
+          ruleCellRoot,
+      )
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/AbsPath.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/AbsPath.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/AbsPath.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.filesystems;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Comparator;
+
+/** Absolute path. */
+public interface AbsPath extends PathWrapper {
+  /**
+   * Cosnstruct using {@link java.nio.file.Path} object.
+   *
+   * @throws RuntimeException the path is not absolute.
+   */
+  static AbsPath of(Path path) {
+    if (path instanceof AbsPath) {
+      return (AbsPath) path;
+    } else {
+      return new AbsPathImpl(path);
+    }
+  }
+
+  static AbsPath get(String path) {
+    return AbsPath.of(Paths.get(path));
+  }
+
+  /** Behaves exactly like {@link Path#normalize()}. */
+  default AbsPath normalize() {
+    return of(getPath().normalize());
+  }
+
+  default AbsPath toRealPath(LinkOption... options) throws IOException {
+    return AbsPath.of(getPath().toRealPath(options));
+  }
+
+  default AbsPath resolve(RelPath other) {
+    return resolve(other.getPath());
+  }
+
+  default boolean startsWith(AbsPath path) {
+    return startsWith(path.getPath());
+  }
+
+  /**
+   * Remove prefix from this path, return {@code null} if this path does not start with given
+   * prefix.
+   */
+  // @Nullable
+  default RelPath removePrefixIfStartsWith(AbsPath prefix) {
+    if (!this.startsWith(prefix)) {
+      return null;
+    }
+    return prefix.relativize(this);
+  }
+
+  /** Remove prefix from this path, throw if this path does not start with given prefix. */
+  default RelPath removePrefix(AbsPath prefix) {
+    RelPath relPath = removePrefixIfStartsWith(prefix);
+    if (relPath == null) {
+      throw new IllegalArgumentException(
+          String.format("path %s does not start with %s", this, prefix));
+    }
+    return relPath;
+  }
+
+  default AbsPath resolve(Path path) {
+    return AbsPath.of(getPath().resolve(path));
+  }
+
+  default AbsPath resolve(String path) {
+    return AbsPath.of(getPath().resolve(path));
+  }
+
+  default AbsPath getParent() {
+    Path parent = getPath().getParent();
+    return parent != null ? AbsPath.of(parent) : null;
+  }
+
+  default RelPath relativize(Path other) {
+    return RelPath.of(this.getPath().relativize(other));
+  }
+
+  default RelPath relativize(AbsPath other) {
+    return relativize(other.getPath());
+  }
+
+  /**
+   * Get the filesystem root of the current path. Note unlike {@link Path#getRoot()} this function
+   * never returns {@code null} because absolute paths always have root.
+   */
+  default AbsPath getRoot() {
+    Path root = getPath().getRoot();
+    if (root == null) {
+      throw new IllegalStateException("abs path must have a root: " + this);
+    }
+    return AbsPath.of(root);
+  }
+
+  default File toFile() {
+    return getPath().toFile();
+  }
+
+  /** We cannot implement {@link java.lang.Comparable} directly. */
+  static Comparator<AbsPath> comparator() {
+    return Comparator.comparing(AbsPath::getPath);
+  }
+
+  default URI toUri() {
+    return getPath().toUri();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/AbsPathImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/AbsPathImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/AbsPathImpl.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.filesystems;
+
+import java.nio.file.Path;
+
+/** Implementation of {@link com.facebook.buck.core.filesystems.AbsPath} */
+class AbsPathImpl extends PathWrapperImpl implements AbsPath {
+  public AbsPathImpl(Path path) {
+    super(path);
+    if (!path.isAbsolute()) {
+      throw new IllegalArgumentException("path must be absolute: " + path);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/BUCK
@@ -0,0 +1,19 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "filesystems",
+    srcs = glob(["*.java"]),
+    tests = ["prelude//toolchains/android/test/com/facebook/buck/core/filesystems:filesystems"],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/...",
+        "prelude//toolchains/android/test/...",
+    ],
+    deps = [
+        # Do NOT add deps here. This library is loaded into the JVM bootstrap classloader in Java 9+.
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/PathWrapper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/PathWrapper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/PathWrapper.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.filesystems;
+
+import java.nio.file.FileSystem;
+import java.nio.file.Path;
+import java.util.Objects;
+
+/** {@link java.nio.file.Path} wrapper object, either absolute or relative. */
+public interface PathWrapper {
+  Path getPath();
+
+  @Override
+  boolean equals(Object that);
+
+  /**
+   * This overload should not be used.
+   *
+   * <p>This code is incorrect: <code>
+   * AbsPath p1 = ...
+   * Path p2 = ...
+   * p1.equals(p2);
+   * </code> because {@code AbsPath} and {@link Path} are different "types" and should not be equal
+   * according to {@link Object#equals(Object)} contract.
+   *
+   * <p>This overload helps to catch this error.
+   */
+  @Deprecated
+  default boolean equals(Path that) {
+    // mark parameter used for PMD
+    Objects.hashCode(that);
+
+    throw new AssertionError();
+  }
+
+  @Override
+  int hashCode();
+
+  @Override
+  String toString();
+
+  default boolean endsWith(String other) {
+    return getPath().endsWith(other);
+  }
+
+  default boolean endsWith(Path path) {
+    return getPath().endsWith(path);
+  }
+
+  default FileSystem getFileSystem() {
+    return getPath().getFileSystem();
+  }
+
+  default boolean startsWith(Path other) {
+    return getPath().startsWith(other);
+  }
+
+  default boolean startsWith(String other) {
+    return getPath().startsWith(other);
+  }
+
+  default Path getFileName() {
+    return getPath().getFileName();
+  }
+
+  default Path getName(int index) {
+    return getPath().getName(index);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/PathWrapperImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/PathWrapperImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/PathWrapperImpl.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.filesystems;
+
+import java.nio.file.Path;
+
+/** Base implementation of two path wrappers. Not visible to users. */
+abstract class PathWrapperImpl implements PathWrapper {
+  protected final Path path;
+
+  protected PathWrapperImpl(Path path) {
+    this.path = path;
+  }
+
+  @Override
+  public Path getPath() {
+    return path;
+  }
+
+  @Override
+  public String toString() {
+    return path.toString();
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (obj == null || this.getClass() != obj.getClass()) {
+      return false;
+    }
+    return this.path.equals(((PathWrapperImpl) obj).path);
+  }
+
+  @Override
+  public int hashCode() {
+    return path.hashCode();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/RelPath.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/RelPath.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/RelPath.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.filesystems;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Comparator;
+
+/** Relative path. */
+public interface RelPath extends PathWrapper {
+
+  /**
+   * Construct using {@link java.nio.file.Path} object.
+   *
+   * @throws RuntimeException the path is not relative.
+   */
+  static RelPath of(Path path) {
+    if (path instanceof RelPath) {
+      return (RelPath) path;
+    } else {
+      return new RelPathImpl(path);
+    }
+  }
+
+  /**
+   * Construct a path.
+   *
+   * @throws RuntimeException if the path is absolute.
+   */
+  static RelPath get(String first, String... more) {
+    return of(Paths.get(first, more));
+  }
+
+  /** Behaves exactly like {@link Path#normalize()}. */
+  default RelPath normalize() {
+    return of(getPath().normalize());
+  }
+
+  default RelPath getParent() {
+    Path parent = getPath().getParent();
+    return parent != null ? RelPath.of(parent) : null;
+  }
+
+  default Path resolve(String other) {
+    return getPath().resolve(other);
+  }
+
+  default Path resolve(Path other) {
+    return getPath().resolve(other);
+  }
+
+  default RelPath resolveRel(String other) {
+    return RelPath.of(resolve(other));
+  }
+
+  default RelPath resolve(RelPath other) {
+    return RelPath.of(getPath().resolve(other.getPath()));
+  }
+
+  default RelPath subpath(int beginIndex, int endIndex) {
+    return RelPath.of(getPath().subpath(beginIndex, endIndex));
+  }
+
+  default int getNameCount() {
+    return getPath().getNameCount();
+  }
+
+  /** Convert path to an absolute path resolving it from current directory. */
+  default AbsPath toAbsolutePath() {
+    return AbsPath.of(getPath().toAbsolutePath());
+  }
+
+  default RelPath relativize(Path path) {
+    return RelPath.of(getPath().relativize(path));
+  }
+
+  default RelPath relativize(RelPath path) {
+    return relativize(path.getPath());
+  }
+
+  default boolean startsWith(RelPath path) {
+    return getPath().startsWith(path.getPath());
+  }
+
+  /** We cannot implement {@link java.lang.Comparable} directly. */
+  static Comparator<RelPath> comparator() {
+    return Comparator.comparing(RelPath::getPath);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/RelPathImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/RelPathImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/filesystems/RelPathImpl.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.filesystems;
+
+import java.nio.file.Path;
+
+/** Implementation of {@link com.facebook.buck.core.filesystems.RelPath} */
+class RelPathImpl extends PathWrapperImpl implements RelPath {
+  public RelPathImpl(Path path) {
+    super(path);
+    if (path.isAbsolute()) {
+      throw new IllegalArgumentException("path must be relative: " + path);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/AbstractBreadthFirstThrowingTraversal.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/AbstractBreadthFirstThrowingTraversal.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/AbstractBreadthFirstThrowingTraversal.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.util.graph;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.Set;
+
+/**
+ * Performs a breadth-first traversal of dependencies of a graph node.
+ *
+ * <p>In cases where the cost of allocating {@link Iterable}s for node dependencies is
+ * expensive/costly, {@link ConsumingTraverser#breadthFirst(Iterable, ForEachSuccessorFunction)}
+ * provides a lighter-weight option.
+ *
+ * <p>TODO: Implement via {@link ConsumingTraverser}.
+ */
+public abstract class AbstractBreadthFirstThrowingTraversal<Node, E extends Throwable> {
+
+  private final Queue<Node> toExplore;
+  private final Set<Node> explored;
+
+  public AbstractBreadthFirstThrowingTraversal(Node initialNode) {
+    this(ImmutableSet.of(initialNode));
+  }
+
+  public AbstractBreadthFirstThrowingTraversal(Iterable<? extends Node> initialNodes) {
+    toExplore = new LinkedList<>();
+    Iterables.addAll(toExplore, initialNodes);
+    explored = new HashSet<>();
+  }
+
+  public final void start() throws E {
+    while (!toExplore.isEmpty()) {
+      Node currentNode = toExplore.remove();
+      if (explored.contains(currentNode)) {
+        continue;
+      }
+
+      Iterable<? extends Node> depsToVisit = this.visit(currentNode);
+      explored.add(currentNode);
+
+      for (Node dep : depsToVisit) {
+        if (!explored.contains(dep)) {
+          toExplore.add(dep);
+        }
+      }
+    }
+
+    this.onComplete();
+  }
+
+  /** Override this method with any logic that should be run when {@link #start()} completes. */
+  protected void onComplete() throws E {}
+
+  /**
+   * To perform a full traversal of the the {@code initialNode}'s transitive dependencies, this
+   * function should return all of {@code node}'s direct dependencies.
+   *
+   * @param node Visited graph node
+   * @return The set of direct dependencies to visit after visiting this node.
+   */
+  public abstract Iterable<? extends Node> visit(Node node) throws E;
+
+  /**
+   * This will typically be implemented as a lambda passed to {@link #traverse(Object, Visitor)} or
+   * {@link #traverse(Iterable, Visitor)}
+   */
+  public interface Visitor<Node, E extends Throwable> {
+    Iterable<Node> visit(Node node) throws E;
+  }
+
+  protected static class StaticBreadthFirstTraversal<Node>
+      extends AbstractBreadthFirstThrowingTraversal<Node, RuntimeException> {
+
+    private final Visitor<Node, RuntimeException> visitor;
+
+    protected StaticBreadthFirstTraversal(
+        Node initialNode, Visitor<Node, RuntimeException> visitor) {
+      super(initialNode);
+      this.visitor = visitor;
+    }
+
+    protected StaticBreadthFirstTraversal(
+        Iterable<? extends Node> initialNodes, Visitor<Node, RuntimeException> visitor) {
+      super(initialNodes);
+      this.visitor = visitor;
+    }
+
+    @Override
+    public Iterable<Node> visit(Node node) throws RuntimeException {
+      return visitor.visit(node);
+    }
+  }
+
+  /**
+   * Traverse a graph without explicitly creating a {@code new
+   * AbstractBreadthFirstThrowingTraversal} and overriding {@link #visit(Object)}
+   *
+   * @param visitor Typically a lambda expression
+   */
+  public static <Node> void traverse(Node initialNode, Visitor<Node, RuntimeException> visitor) {
+    new StaticBreadthFirstTraversal<>(initialNode, visitor).start();
+  }
+
+  /**
+   * Traverse a graph without explicitly creating a {@code new
+   * AbstractBreadthFirstThrowingTraversal} and overriding {@link #visit(Object)}
+   *
+   * @param visitor Typically a lambda expression
+   */
+  public static <Node> void traverse(
+      Iterable<? extends Node> initialNodes, Visitor<Node, RuntimeException> visitor) {
+    new StaticBreadthFirstTraversal<>(initialNodes, visitor).start();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/AbstractBreadthFirstTraversal.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/AbstractBreadthFirstTraversal.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/AbstractBreadthFirstTraversal.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.util.graph;
+
+/** Performs a breadth-first traversal of dependencies of a graph node. */
+public abstract class AbstractBreadthFirstTraversal<Node>
+    extends AbstractBreadthFirstThrowingTraversal<Node, RuntimeException> {
+
+  public AbstractBreadthFirstTraversal(Node initialNode) {
+    super(initialNode);
+  }
+
+  public AbstractBreadthFirstTraversal(Iterable<? extends Node> initialNodes) {
+    super(initialNodes);
+  }
+
+  /**
+   * Traverse a graph without explicitly creating a {@code new
+   * AbstractBreadthFirstThrowingTraversal} and overriding {@link #visit(Object)}
+   *
+   * @param visitor Typically a lambda expression
+   */
+  public static <Node> void traverse(Node initialNode, Visitor<Node, RuntimeException> visitor) {
+    new StaticBreadthFirstTraversal<>(initialNode, visitor).start();
+  }
+
+  /**
+   * Traverse a graph without explicitly creating a {@code new
+   * AbstractBreadthFirstThrowingTraversal} and overriding {@link #visit(Object)}
+   *
+   * @param visitor Typically a lambda expression
+   */
+  public static <Node> void traverse(
+      Iterable<? extends Node> initialNodes, Visitor<Node, RuntimeException> visitor) {
+    new StaticBreadthFirstTraversal<>(initialNodes, visitor).start();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/BUCK
@@ -0,0 +1,23 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "graph",
+    srcs = glob(["*.java"]),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/core/util/graph:graph",
+    ],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/apkmodule:apkmodule",
+        "prelude//toolchains/android/test/com/facebook/buck/android/apkmodule:apkmodule",
+        "prelude//toolchains/android/test/com/facebook/buck/core/util/graph:graph",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/DirectedAcyclicGraph.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/DirectedAcyclicGraph.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/DirectedAcyclicGraph.java
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.util.graph;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Suppliers;
+import com.google.common.collect.ImmutableCollection;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public class DirectedAcyclicGraph<T> implements TraversableGraph<T> {
+
+  private final ImmutableSet<T> nodes;
+  private final ImmutableMap<T, ImmutableSet<T>> outgoingEdges;
+  private final Supplier<ImmutableMap<T, ImmutableCollection<T>>> incomingEdges;
+
+  /** Constructor used by builders. */
+  private DirectedAcyclicGraph(
+      ImmutableSet<T> nodes, ImmutableMap<T, ImmutableSet<T>> outgoingEdges) {
+    Preconditions.checkState(
+        TraversableGraphs.isAcyclic(nodes, n -> outgoingEdges.getOrDefault(n, ImmutableSet.of())),
+        "Graph must by acyclic");
+    this.nodes = nodes;
+    this.outgoingEdges = outgoingEdges;
+    this.incomingEdges =
+        Suppliers.memoize(() -> computeIncomingEdges(this.nodes, this.outgoingEdges));
+  }
+
+  /** Copy constructor. */
+  protected DirectedAcyclicGraph(DirectedAcyclicGraph<T> other) {
+    this.nodes = other.nodes;
+    this.outgoingEdges = other.outgoingEdges;
+    this.incomingEdges = other.incomingEdges;
+  }
+
+  /**
+   * Legacy constructor to convert form {@link MutableDirectedGraph}.
+   *
+   * @deprecated Use {@link DirectedAcyclicGraph#serialBuilder()} to build a graph.
+   */
+  @Deprecated
+  @SuppressWarnings({"unchecked", "rawtypes"})
+  public DirectedAcyclicGraph(MutableDirectedGraph<T> graph) {
+    Preconditions.checkState(
+        TraversableGraphs.isAcyclic(graph.getNodes(), graph::getOutgoingNodesFor),
+        "Graph must by acyclic");
+    this.nodes = graph.createImmutableCopyOfNodes();
+    this.outgoingEdges = graph.createImmutableCopyOfOutgoingEdges();
+    this.incomingEdges =
+        Suppliers.ofInstance((ImmutableMap) graph.createImmutableCopyOfIncomingEdges());
+  }
+
+  /**
+   * Consume a {@link Map} of map of nodes to builders and produce an {@link ImmutableMap} of their
+   * built collections. The input map will be empty once complete.
+   *
+   * @return an {@link ImmutableMap} built from a {@link Map} of builders.
+   */
+  private static <T, C extends ImmutableCollection<T>, B> ImmutableMap<T, C> toImmutableMap(
+      Function<B, C> build, Map<T, B> map) {
+    ImmutableMap.Builder<T, C> builder = ImmutableMap.builderWithExpectedSize(map.size());
+    for (Iterator<Map.Entry<T, B>> itr = map.entrySet().iterator(); itr.hasNext(); ) {
+      Map.Entry<T, B> entry = itr.next();
+      // Remove the builder from the map before building it.  This allows the builder to be garbage
+      // collected while we're processing remaining builders, to help prevent this function from
+      // requiring 2x the size of the input map to run.
+      itr.remove();
+      builder.put(entry.getKey(), Preconditions.checkNotNull(build.apply(entry.getValue())));
+    }
+    return builder.build();
+  }
+
+  /**
+   * @return the map of incoming node edges, computed from the map of outgoing node edges.
+   */
+  private static <T> ImmutableMap<T, ImmutableCollection<T>> computeIncomingEdges(
+      ImmutableSet<T> nodes, ImmutableMap<T, ImmutableSet<T>> outgoingEdges) {
+    Map<T, ImmutableList.Builder<T>> builder = new HashMap<>();
+    for (T source : nodes) {
+      for (T sink : outgoingEdges.getOrDefault(source, ImmutableSet.of())) {
+        builder.computeIfAbsent(sink, n -> ImmutableList.builder()).add(source);
+      }
+    }
+    return toImmutableMap(ImmutableList.Builder::build, builder);
+  }
+
+  @Override
+  public ImmutableSet<T> getOutgoingNodesFor(T source) {
+    return outgoingEdges.getOrDefault(source, ImmutableSet.of());
+  }
+
+  @Override
+  public ImmutableCollection<T> getIncomingNodesFor(T sink) {
+    return incomingEdges.get().getOrDefault(sink, ImmutableSet.of());
+  }
+
+  @Override
+  public ImmutableSet<T> getNodesWithNoOutgoingEdges() {
+    return ImmutableSet.copyOf(Sets.difference(nodes, outgoingEdges.keySet()));
+  }
+
+  @Override
+  public ImmutableSet<T> getNodesWithNoIncomingEdges() {
+    return ImmutableSet.copyOf(Sets.difference(nodes, incomingEdges.get().keySet()));
+  }
+
+  @Override
+  public ImmutableSet<T> getNodes() {
+    return nodes;
+  }
+
+  @Override
+  public boolean equals(Object other) {
+    if (!(other instanceof DirectedAcyclicGraph)) {
+      return false;
+    }
+
+    DirectedAcyclicGraph<?> that = (DirectedAcyclicGraph<?>) other;
+    return Objects.equals(this.nodes, that.nodes)
+        && Objects.equals(this.outgoingEdges, that.outgoingEdges);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(nodes, outgoingEdges, incomingEdges);
+  }
+
+  public static <T> Builder<T> serialBuilder() {
+    return new DirectedAcyclicGraph.Builder<>();
+  }
+
+  public static class Builder<T> {
+
+    // To avoid copying, we only support a single use of this builder.
+    protected boolean finished = false;
+
+    protected Collection<T> nodes = new ArrayList<>();
+    protected Map<T, Collection<T>> outgoingEdges = new HashMap<>();
+
+    private Builder() {}
+
+    /** Insert node into the graph. */
+    public Builder<T> addNode(T node) {
+      Preconditions.checkState(!finished);
+      nodes.add(node);
+      return this;
+    }
+
+    protected void putEdge(Collection<T> edges, T edge) {
+      edges.add(edge);
+    }
+
+    /** Add an edge from {@code source} to {@code sink}. */
+    public Builder<T> addEdge(T source, T sink) {
+      Preconditions.checkState(!source.equals(sink));
+      Preconditions.checkState(!finished);
+      nodes.add(source);
+      nodes.add(sink);
+      putEdge(outgoingEdges.computeIfAbsent(source, s -> new ArrayList<>()), sink);
+      return this;
+    }
+
+    /** Consumes the given node collection and converts to an {@link ImmutableSet}. */
+    private ImmutableSet<T> buildImmutableSet(Collection<T> nodes) {
+      // NOTE: `ImmutableSet.copyOf()` doesn't pre-size the builder, so we do it ourselves as, in
+      // practice, we don't add duplicate nodes/edges.
+      ImmutableSet.Builder<T> builder =
+          ImmutableSet.<T>builderWithExpectedSize(nodes.size()).addAll(nodes);
+
+      // Clear out the existing node list before building, to potentially free up memory.
+      nodes.clear();
+      if (nodes instanceof ArrayList) {
+        ((ArrayList<T>) nodes).trimToSize();
+      }
+
+      return builder.build();
+    }
+
+    /**
+     * Build a {@link DirectedAcyclicGraph}. This builder cannot be modified once this has been
+     * called.
+     */
+    public DirectedAcyclicGraph<T> build() {
+      Preconditions.checkState(!finished);
+      finished = true;
+
+      // Create an immutable copy of the nodes, and clear out the builder set to free up memory.
+      ImmutableSet<T> nodes = buildImmutableSet(this.nodes);
+      this.nodes = null;
+
+      // Create an immutable copy of the outgoing edges, which frees up the builder map to free up
+      // memory.
+      ImmutableMap<T, ImmutableSet<T>> outgoingEdges =
+          DirectedAcyclicGraph.toImmutableMap(this::buildImmutableSet, this.outgoingEdges);
+      this.outgoingEdges = null;
+
+      return new DirectedAcyclicGraph<>(nodes, outgoingEdges);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/MutableDirectedGraph.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/MutableDirectedGraph.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/MutableDirectedGraph.java
@@ -0,0 +1,230 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.util.graph;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Supplier;
+
+/**
+ * Represents a directed graph with unweighted edges. For a given source and sink node pair, there
+ * is at most one directed edge connecting them in the graph. The graph is not required to be
+ * connected or acyclic.
+ *
+ * @param <T> the type of object stored as nodes in this graph
+ */
+public final class MutableDirectedGraph<T> implements TraversableGraph<T> {
+
+  /**
+   * It is possible to have a node in the graph without any edges, which is why we must maintain a
+   * separate collection for nodes in the graph, rather than just using the keySet of {@link
+   * #outgoingEdges}.
+   */
+  private final Set<T> nodes;
+
+  /**
+   * Represents the edges in the graph. Keys are source nodes; values are corresponding sync nodes.
+   */
+  private final Map<T, Collection<T>> outgoingEdges;
+
+  /**
+   * Represents the edges in the graph. Keys are sink nodes; values are corresponding source nodes.
+   */
+  private final Map<T, Collection<T>> incomingEdges;
+
+  /** Creates a new edge list. Used when a edge is added for a node for the first time. */
+  private final Supplier<Collection<T>> createEdgeCollection;
+
+  private MutableDirectedGraph(
+      Set<T> nodes,
+      Map<T, Collection<T>> outgoingEdges,
+      Map<T, Collection<T>> incomingEdges,
+      Supplier<Collection<T>> createEdgeCollection) {
+    this.nodes = nodes;
+    this.outgoingEdges = outgoingEdges;
+    this.incomingEdges = incomingEdges;
+    this.createEdgeCollection = createEdgeCollection;
+  }
+
+  /** Creates a new graph with no nodes or edges. */
+  public MutableDirectedGraph() {
+    this(new LinkedHashSet<>(), new HashMap<>(), new HashMap<>(), LinkedHashSet::new);
+  }
+
+  public static <T> MutableDirectedGraph<T> createConcurrent() {
+    return new MutableDirectedGraph<>(
+        Collections.newSetFromMap(new ConcurrentHashMap<>()),
+        new ConcurrentHashMap<>(),
+        new ConcurrentHashMap<>(),
+        () -> Collections.synchronizedSet(new HashSet<>()));
+  }
+
+  /**
+   * @return the number of nodes in the graph
+   */
+  public int getNodeCount() {
+    return nodes.size();
+  }
+
+  /**
+   * @return the number of edges in the graph
+   */
+  public int getEdgeCount() {
+    return outgoingEdges.size();
+  }
+
+  /**
+   * @return whether the specified node is present in the graph
+   */
+  public boolean containsNode(T node) {
+    return nodes.contains(node);
+  }
+
+  /**
+   * @return whether an edge from the source to the sink is present in the graph
+   */
+  public boolean containsEdge(T source, T sink) {
+    return outgoingEdges.getOrDefault(source, ImmutableSet.of()).contains(sink);
+  }
+
+  /** Adds the specified node to the graph. */
+  public boolean addNode(T node) {
+    return nodes.add(node);
+  }
+
+  /** Removes the specified node from the graph. */
+  public boolean removeNode(T node) {
+    boolean isRemoved = nodes.remove(node);
+    Collection<T> nodesReachableFromTheSpecifiedNode = outgoingEdges.remove(node);
+    if (nodesReachableFromTheSpecifiedNode != null) {
+      for (T reachableNode : nodesReachableFromTheSpecifiedNode) {
+        incomingEdges.get(reachableNode).remove(node);
+      }
+    }
+    return isRemoved;
+  }
+
+  /**
+   * Adds an edge between {@code source} and {@code sink}. Adds the nodes to the graph if they are
+   * not already present.
+   */
+  public void addEdge(T source, T sink) {
+    nodes.add(source);
+    nodes.add(sink);
+    outgoingEdges.computeIfAbsent(source, s -> createEdgeCollection.get()).add(sink);
+    incomingEdges.computeIfAbsent(sink, s -> createEdgeCollection.get()).add(source);
+  }
+
+  /**
+   * Sets all outgoing edges between {@code source} and {@code sinks} to the given collections. Note
+   * that the given collection is used as-is -- the caller must make sure it can be used safely by
+   * this graph (e.g. concurrent modifications when used with a concurrent builder).
+   */
+  public void setEdges(T source, Collection<T> sinks) {
+    nodes.add(source);
+    nodes.addAll(sinks);
+    Preconditions.checkState(outgoingEdges.putIfAbsent(source, sinks) == null);
+    sinks.forEach(
+        sink -> incomingEdges.computeIfAbsent(sink, s -> createEdgeCollection.get()).add(source));
+  }
+
+  /**
+   * Removes the edge between {@code source} and {@code sink}. This does not remove {@code source}
+   * or {@code sink} from the graph. Note that this may leave either {@code source} or {@code sink}
+   * as unconnected nodes in the graph.
+   */
+  public void removeEdge(T source, T sink) {
+    outgoingEdges.get(source).remove(sink);
+    incomingEdges.get(sink).remove(source);
+  }
+
+  @Override
+  public Iterable<T> getOutgoingNodesFor(T source) {
+    return Collections.unmodifiableCollection(
+        outgoingEdges.getOrDefault(source, ImmutableList.of()));
+  }
+
+  @Override
+  public Iterable<T> getIncomingNodesFor(T sink) {
+    return Collections.unmodifiableCollection(incomingEdges.getOrDefault(sink, ImmutableList.of()));
+  }
+
+  public boolean hasIncomingEdges(T node) {
+    return this.incomingEdges.containsKey(node);
+  }
+
+  @Override
+  public Set<T> getNodes() {
+    return Collections.unmodifiableSet(nodes);
+  }
+
+  public boolean isAcyclic() {
+    return TraversableGraphs.isAcyclic(nodes, this::getOutgoingNodesFor);
+  }
+
+  public ImmutableSet<ImmutableSet<T>> findCycles() {
+    ImmutableSet.Builder<ImmutableSet<T>> builder = ImmutableSet.builder();
+    TraversableGraphs.findStronglyConnectedComponents(this).stream()
+        .filter(s -> s.size() > 1)
+        .forEach(builder::add);
+    // Tarjan's algorithm (as pseudo-coded on Wikipedia) does not appear to account for single-node
+    // cycles. Therefore, we must check for them exclusively.
+    for (T node : nodes) {
+      if (containsEdge(node, node)) {
+        builder.add(ImmutableSet.of(node));
+      }
+    }
+    return builder.build();
+  }
+
+  @Override
+  public Iterable<T> getNodesWithNoIncomingEdges() {
+    return Sets.difference(nodes, incomingEdges.keySet());
+  }
+
+  @Override
+  public Iterable<T> getNodesWithNoOutgoingEdges() {
+    return Sets.difference(nodes, outgoingEdges.keySet());
+  }
+
+  ImmutableSet<T> createImmutableCopyOfNodes() {
+    return ImmutableSet.copyOf(nodes);
+  }
+
+  ImmutableMap<T, ImmutableSet<T>> createImmutableCopyOfOutgoingEdges() {
+    ImmutableMap.Builder<T, ImmutableSet<T>> builder =
+        ImmutableMap.builderWithExpectedSize(outgoingEdges.size());
+    outgoingEdges.forEach(
+        (n, e) ->
+            builder.put(n, ImmutableSet.<T>builderWithExpectedSize(e.size()).addAll(e).build()));
+    return builder.build();
+  }
+
+  ImmutableMap<T, ImmutableSet<T>> createImmutableCopyOfIncomingEdges() {
+    ImmutableMap.Builder<T, ImmutableSet<T>> builder =
+        ImmutableMap.builderWithExpectedSize(incomingEdges.size());
+    incomingEdges.forEach(
+        (n, e) ->
+            builder.put(n, ImmutableSet.<T>builderWithExpectedSize(e.size()).addAll(e).build()));
+    return builder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/TraversableGraph.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/TraversableGraph.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/TraversableGraph.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.util.graph;
+
+/** Minimal interface needed by {@link AbstractBottomUpTraversal} to traverse a graph. */
+public interface TraversableGraph<T> {
+
+  /**
+   * @return {@link Iterable} that the caller is not allowed to mutate.
+   */
+  Iterable<T> getNodesWithNoIncomingEdges();
+
+  /**
+   * @return {@link Iterable} that the caller is not allowed to mutate.
+   */
+  Iterable<T> getNodesWithNoOutgoingEdges();
+
+  /**
+   * @return {@link Iterable} that the caller is not allowed to mutate.
+   */
+  Iterable<T> getIncomingNodesFor(T sink);
+
+  /**
+   * @return {@link Iterable} that the caller is not allowed to mutate.
+   */
+  Iterable<T> getOutgoingNodesFor(T source);
+
+  /**
+   * @return an unmodifiable view of the nodes in this graph
+   */
+  Iterable<T> getNodes();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/TraversableGraphs.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/TraversableGraphs.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/graph/TraversableGraphs.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.util.graph;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Function;
+
+public class TraversableGraphs {
+
+  private TraversableGraphs() {}
+
+  /**
+   * For this graph, returns the set of strongly connected components using Tarjan's algorithm. Note
+   * this is {@code O(|V| + |E|)}.
+   *
+   * @return an unmodifiable {@link Set} of sets, each of which is also an unmodifiable {@link Set}
+   *     and represents a strongly connected component.
+   */
+  public static <T> ImmutableSet<ImmutableSet<T>> findStronglyConnectedComponents(
+      TraversableGraph<T> graph) {
+    TraversableGraphs.Tarjan<T> tarjan = new TraversableGraphs.Tarjan<>(graph);
+    return tarjan.findStronglyConnectedComponents();
+  }
+
+  /**
+   * Implementation of
+   * http://en.wikipedia.org/wiki/Tarjan%E2%80%99s_strongly_connected_components_algorithm used to
+   * find cycles in the graph.
+   */
+  static class Tarjan<S> {
+    private final TraversableGraph<S> graph;
+    private final Map<S, Integer> indexes;
+    private final Map<S, Integer> lowlinks;
+    private final Deque<S> nodeStack;
+    private final ImmutableSet.Builder<ImmutableSet<S>> stronglyConnectedComponents;
+    private int index;
+
+    private Tarjan(TraversableGraph<S> graph) {
+      this.graph = graph;
+      this.indexes = new HashMap<>();
+      this.lowlinks = new HashMap<>();
+      this.nodeStack = new LinkedList<>();
+      this.stronglyConnectedComponents = ImmutableSet.builder();
+      this.index = 0;
+    }
+
+    public ImmutableSet<ImmutableSet<S>> findStronglyConnectedComponents() {
+      for (S node : graph.getNodes()) {
+        if (!indexes.containsKey(node)) {
+          doStrongConnect(node);
+        }
+      }
+      return stronglyConnectedComponents.build();
+    }
+
+    private void doStrongConnect(S node) {
+      // Set the depth index for node to the smallest unused index.
+      indexes.put(node, index);
+      lowlinks.put(node, index);
+      index++;
+      nodeStack.push(node);
+
+      // Consider successors of node.
+      for (S sink : graph.getOutgoingNodesFor(node)) {
+        if (!indexes.containsKey(sink)) {
+          doStrongConnect(sink);
+          int lowlink =
+              Math.min(
+                  Objects.requireNonNull(lowlinks.get(node)),
+                  Objects.requireNonNull(lowlinks.get(sink)));
+          lowlinks.put(node, lowlink);
+        } else if (nodeStack.contains(sink)) {
+          // TODO(mbolin): contains() is O(N), consider maintaining an index so it is O(1)?
+          int lowlink =
+              Math.min(
+                  Objects.requireNonNull(lowlinks.get(node)),
+                  Objects.requireNonNull(indexes.get(sink)));
+          lowlinks.put(node, lowlink);
+        }
+      }
+
+      // If node is a root node, then pop the stack and generate a strongly connected component.
+      if (Objects.requireNonNull(lowlinks.get(node)).equals(indexes.get(node))) {
+        ImmutableSet.Builder<S> stronglyConnectedComponent = ImmutableSet.builder();
+        S componentElement;
+        do {
+          componentElement = nodeStack.pop();
+          stronglyConnectedComponent.add(componentElement);
+        } while (componentElement != node);
+        stronglyConnectedComponents.add(stronglyConnectedComponent.build());
+      }
+    }
+  }
+
+  /** Fast cycle-checker using a iterative DFS. */
+  public static <T> boolean isAcyclic(Iterable<T> roots, Function<T, Iterable<T>> successors) {
+    HashMap<T, NodeStatus> status =
+        roots instanceof Collection
+            ? new HashMap<>(((Collection<T>) roots).size())
+            : new HashMap<>();
+    Deque<T> stack = new ArrayDeque<>();
+
+    // Process all roots/nodes.
+    for (T root : roots) {
+
+      // Check if we're already processed this node.
+      NodeStatus rootStatus = status.get(root);
+      Preconditions.checkState(rootStatus == null || rootStatus == NodeStatus.DONE);
+      if (rootStatus == NodeStatus.DONE) {
+        continue;
+      }
+
+      // Initialize a stack for a DFS search from the this root.
+      stack.push(root);
+      status.put(root, NodeStatus.INITIALIZED);
+
+      // Keep going until we're out of elements.
+      while (!stack.isEmpty()) {
+        T node = stack.pop();
+        NodeStatus nodeStatus = status.get(node);
+        Preconditions.checkState(
+            nodeStatus == NodeStatus.ENTERED || nodeStatus == NodeStatus.INITIALIZED);
+
+        // If we've already entered this node, then it means this pass is exiting, so mark it done.
+        if (nodeStatus == NodeStatus.ENTERED) {
+          status.put(node, NodeStatus.DONE);
+        } else {
+
+          // Mark this node as entered, and push it again to handle the exit.
+          status.put(node, NodeStatus.ENTERED);
+          stack.push(node);
+
+          // Process all dependencies.
+          for (T succ : successors.apply(node)) {
+            NodeStatus succVisited = status.get(succ);
+            if (succVisited == null) {
+              stack.push(succ);
+              status.put(succ, NodeStatus.INITIALIZED);
+            } else if (succVisited == NodeStatus.ENTERED) {
+              return false;
+            }
+          }
+        }
+      }
+    }
+
+    return true;
+  }
+
+  private enum NodeStatus {
+    INITIALIZED,
+    ENTERED,
+    DONE,
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/BUCK
@@ -0,0 +1,16 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "log",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log/appendablelogrecord:appendablelogrecord",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/Logger.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/Logger.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/Logger.java
@@ -0,0 +1,392 @@
+/*
+ * Portions Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under both the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree and the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree.
+ */
+
+/*
+ * Copyright 2010 Proofpoint, Inc.
+ *
+ * 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.
+ */
+
+package com.facebook.buck.core.util.log;
+
+import static java.util.logging.Level.FINE;
+import static java.util.logging.Level.FINER;
+import static java.util.logging.Level.INFO;
+import static java.util.logging.Level.SEVERE;
+import static java.util.logging.Level.WARNING;
+
+import com.facebook.buck.core.util.log.appendablelogrecord.AppendableLogRecord;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import javax.annotation.Nullable;
+
+@SuppressWarnings("PMD")
+public class Logger {
+  private final java.util.logging.Logger logger;
+
+  Logger(java.util.logging.Logger logger) {
+    this.logger = logger;
+  }
+
+  /**
+   * Gets a logger named after a class' fully qualified name.
+   *
+   * @param clazz the class
+   * @return the named logger
+   */
+  public static Logger get(Class<?> clazz) {
+    return get(clazz.getName().replace('$', '.'));
+  }
+
+  /**
+   * Gets a named logger
+   *
+   * @param name the name of the logger
+   * @return the named logger
+   */
+  public static Logger get(String name) {
+    java.util.logging.Logger logger = java.util.logging.Logger.getLogger(name);
+    return new Logger(logger);
+  }
+
+  /**
+   * Logs a message at VERBOSE level.
+   *
+   * @param exception an exception associated with the verbose message being logged
+   * @param message a literal message to log
+   */
+  public void verbose(Throwable exception, String message) {
+    logger.log(FINER, message, exception);
+  }
+
+  /**
+   * Logs a message at VERBOSE level.
+   *
+   * @param message a literal message to log
+   */
+  public void verbose(String message) {
+    logger.finer(message);
+  }
+
+  /**
+   * Logs a message at VERBOSE level. <br>
+   * Usage example:
+   *
+   * <pre>
+   *    logger.verbose("value is %s (%d ms)", value, time);
+   * </pre>
+   *
+   * If the format string is invalid or the arguments are insufficient, an error will be logged and
+   * execution will continue.
+   *
+   * @param format a format string compatible with String.format()
+   * @param args arguments for the format string
+   */
+  public void verbose(String format, Object... args) {
+    verbose(null, format, args);
+  }
+
+  /**
+   * Logs a message at VERBOSE level. <br>
+   * Usage example:
+   *
+   * <pre>
+   *    logger.verbose(e, "value is %s (%d ms)", value, time);
+   * </pre>
+   *
+   * If the format string is invalid or the arguments are insufficient, an error will be logged and
+   * execution will continue.
+   *
+   * @param exception an exception associated with the verbose message being logged
+   * @param format a format string compatible with String.format()
+   * @param args arguments for the format string
+   */
+  public void verbose(@Nullable Throwable exception, String format, Object... args) {
+    logAppendableLogRecord(FINER, exception, format, args);
+  }
+
+  /**
+   * Logs a message at DEBUG level.
+   *
+   * @param exception an exception associated with the debug message being logged
+   * @param message a literal message to log
+   */
+  public void debug(Throwable exception, String message) {
+    logger.log(FINE, message, exception);
+  }
+
+  /**
+   * Logs a message at DEBUG level.
+   *
+   * @param message a literal message to log
+   */
+  public void debug(String message) {
+    logger.fine(message);
+  }
+
+  /**
+   * Logs a message at DEBUG level. <br>
+   * Usage example:
+   *
+   * <pre>
+   *    logger.debug("value is %s (%d ms)", value, time);
+   * </pre>
+   *
+   * If the format string is invalid or the arguments are insufficient, an error will be logged and
+   * execution will continue.
+   *
+   * @param format a format string compatible with String.format()
+   * @param args arguments for the format string
+   */
+  public void debug(String format, Object... args) {
+    debug(null, format, args);
+  }
+
+  /**
+   * Logs a message at DEBUG level. <br>
+   * Usage example:
+   *
+   * <pre>
+   *    logger.debug(e, "value is %s (%d ms)", value, time);
+   * </pre>
+   *
+   * If the format string is invalid or the arguments are insufficient, an error will be logged and
+   * execution will continue.
+   *
+   * @param exception an exception associated with the debug message being logged
+   * @param format a format string compatible with String.format()
+   * @param args arguments for the format string
+   */
+  public void debug(@Nullable Throwable exception, String format, Object... args) {
+    logAppendableLogRecord(FINE, exception, format, args);
+  }
+
+  /**
+   * Logs a message at INFO level.
+   *
+   * @param message a literal message to log
+   */
+  public void info(String message) {
+    logger.info(message);
+  }
+
+  /**
+   * Logs a message at INFO level. <br>
+   * Usage example:
+   *
+   * <pre>
+   *    logger.info("value is %s (%d ms)", value, time);
+   * </pre>
+   *
+   * If the format string is invalid or the arguments are insufficient, an error will be logged and
+   * execution will continue.
+   *
+   * @param exception an exception associated with the warning being logged
+   * @param format a format string compatible with String.format()
+   * @param args arguments for the format string
+   */
+  public void info(@Nullable Throwable exception, String format, Object... args) {
+    logAppendableLogRecord(INFO, exception, format, args);
+  }
+
+  /**
+   * Logs a message at INFO level.
+   *
+   * @param format a format string compatible with String.format()
+   * @param args arguments for the format string
+   */
+  public void info(String format, Object... args) {
+    info(null, format, args);
+  }
+
+  /**
+   * Logs a message at WARN level.
+   *
+   * @param exception an exception associated with the warning being logged
+   * @param message a literal message to log
+   */
+  public void warn(Throwable exception, String message) {
+    logger.log(WARNING, message, exception);
+  }
+
+  /**
+   * Logs a message at WARN level.
+   *
+   * @param message a literal message to log
+   */
+  public void warn(String message) {
+    logger.warning(message);
+  }
+
+  /**
+   * Logs a message at WARN level. <br>
+   * Usage example:
+   *
+   * <pre>
+   *    logger.warn(e, "something bad happened when connecting to %s:%d", host, port);
+   * </pre>
+   *
+   * If the format string is invalid or the arguments are insufficient, an error will be logged and
+   * execution will continue.
+   *
+   * @param exception an exception associated with the warning being logged
+   * @param format a format string compatible with String.format()
+   * @param args arguments for the format string
+   */
+  public void warn(@Nullable Throwable exception, String format, Object... args) {
+    logAppendableLogRecord(WARNING, exception, format, args);
+  }
+
+  /**
+   * Logs a message at WARN level. <br>
+   * Usage example:
+   *
+   * <pre>
+   *    logger.warn("something bad happened when connecting to %s:%d", host, port);
+   * </pre>
+   *
+   * If the format string is invalid or the arguments are insufficient, an error will be logged and
+   * execution will continue.
+   *
+   * @param format a format string compatible with String.format()
+   * @param args arguments for the format string
+   */
+  public void warn(String format, Object... args) {
+    warn(null, format, args);
+  }
+
+  /**
+   * Logs a message at ERROR level.
+   *
+   * @param exception an exception associated with the error being logged
+   * @param message a literal message to log
+   */
+  public void error(Throwable exception, String message) {
+    logger.log(SEVERE, message, exception);
+  }
+
+  /**
+   * Logs a message at ERROR level.
+   *
+   * @param message a literal message to log
+   */
+  public void error(String message) {
+    logger.severe(message);
+  }
+
+  /**
+   * Logs a message at ERROR level. <br>
+   * Usage example:
+   *
+   * <pre>
+   *    logger.error(e, "something really bad happened when connecting to %s:%d", host, port);
+   * </pre>
+   *
+   * If the format string is invalid or the arguments are insufficient, an error will be logged and
+   * execution will continue.
+   *
+   * @param exception an exception associated with the error being logged
+   * @param format a format string compatible with String.format()
+   * @param args arguments for the format string
+   */
+  public void error(@Nullable Throwable exception, String format, Object... args) {
+    logAppendableLogRecord(SEVERE, exception, format, args);
+  }
+
+  /**
+   * Logs a message at ERROR level. The value of {@code exception.getMessage()} will be used as the
+   * log message. <br>
+   * Usage example:
+   *
+   * <pre>
+   *    logger.error(e);
+   * </pre>
+   *
+   * @param exception an exception associated with the error being logged
+   */
+  public void error(Throwable exception) {
+    if (logger.isLoggable(SEVERE)) {
+      logger.log(SEVERE, exception.getMessage(), exception);
+    }
+  }
+
+  /**
+   * Logs a message at ERROR level. <br>
+   * Usage example:
+   *
+   * <pre>
+   *    logger.error("something really bad happened when connecting to %s:%d", host, port);
+   * </pre>
+   *
+   * If the format string is invalid or the arguments are insufficient, an error will be logged and
+   * execution will continue.
+   *
+   * @param format a format string compatible with String.format()
+   * @param args arguments for the format string
+   */
+  public void error(String format, Object... args) {
+    error(null, format, args);
+  }
+
+  private void logAppendableLogRecord(
+      Level level, @Nullable Throwable exception, String format, Object... args) {
+    if (logger.isLoggable(level)) {
+      String message = args.length != 0 ? String.format(format, args) : format;
+      AppendableLogRecord lr = new AppendableLogRecord(level, message);
+      lr.setThrown(exception);
+      lr.setLoggerName(logger.getName());
+      logger.log(lr);
+    }
+  }
+
+  public boolean isVerboseEnabled() {
+    return logger.isLoggable(FINER);
+  }
+
+  public boolean isDebugEnabled() {
+    return logger.isLoggable(FINE);
+  }
+
+  public Level getLevel() {
+    return logger.getLevel();
+  }
+
+  public void setLevel(Level newLevel) {
+    logger.setLevel(newLevel);
+  }
+
+  public boolean isLoggable(Level level) {
+    return logger.isLoggable(level);
+  }
+
+  public void addHandler(Handler handler) {
+    logger.addHandler(handler);
+  }
+
+  public Handler[] getHandlers() {
+    return logger.getHandlers();
+  }
+
+  /** Cleans existing handlers associated with the logger. */
+  public void cleanHandlers() {
+    for (Handler handler : getHandlers()) {
+      logger.removeHandler(handler);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/appendablelogrecord/AppendableLogRecord.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/appendablelogrecord/AppendableLogRecord.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/appendablelogrecord/AppendableLogRecord.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.core.util.log.appendablelogrecord;
+
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+
+/**
+ * Subclass of LogRecord that only accepts preformatted strings. LogFormatter downcasts if it
+ * receives AppendableLogRecord instances, allowing us to avoid string allocations.
+ */
+public class AppendableLogRecord extends LogRecord {
+  public AppendableLogRecord(Level level, String msg) {
+    super(level, msg);
+  }
+
+  public void appendFormattedMessage(StringBuilder sb) {
+    sb.append(getMessage());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/appendablelogrecord/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/appendablelogrecord/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/core/util/log/appendablelogrecord/BUCK
@@ -0,0 +1,20 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "appendablelogrecord",
+    srcs = glob(["*.java"]),
+    # This target is pulled in by testrunner, which needs to compile against Java 8.
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/testrunner:junit",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/BUCK
@@ -0,0 +1,28 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "utils",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/util/relativepathmap:relativepathmap",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip/collect:collect",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
+
+buck_java_binary(
+    name = "zip_binary",
+    main_class = "com.facebook.buck.features.zip.rules.utils.ZipMain",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":utils",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/ZipMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/ZipMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/ZipMain.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.features.zip.rules.utils;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.util.relativepathmap.RelativePathMapUtils;
+import com.facebook.buck.util.zip.collect.OnDuplicateEntry;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+import org.kohsuke.args4j.spi.StringArrayOptionHandler;
+
+/** Main entry point for generating Zip files */
+public class ZipMain {
+
+  private static final AbsPath CURRENT_DIRECTORY =
+      AbsPath.of(Paths.get(".").normalize().toAbsolutePath());
+
+  @Option(name = "--output_path", required = true)
+  private String outputPath;
+
+  @Option(name = "--on_duplicate_entry", required = true)
+  private OnDuplicateEntry onDuplicateEntry;
+
+  @Option(name = "--zip_sources", handler = StringArrayOptionHandler.class)
+  private List<String> zipSources;
+
+  @Option(name = "--entries_to_exclude", handler = StringArrayOptionHandler.class)
+  private List<String> entriesToExclude;
+
+  @Option(name = "--entries_file")
+  private File entriesFile;
+
+  @Option(name = "--hardcode_permissions_for_deterministic_output")
+  private boolean hardcodePermissionsForDeterministicOutput;
+
+  public static void main(String[] args) throws IOException {
+    ZipMain main = new ZipMain();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.getMessage());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  /** Main entry point into ZipFile binary */
+  private void run() throws IOException {
+    RelPath outputPath = RelPath.get(this.outputPath);
+    ImmutableList.Builder<RelPath> zipSourcesBuilder = ImmutableList.builder();
+    if (zipSources != null) {
+      for (String zipSource : zipSources) {
+        zipSourcesBuilder.add(RelPath.get(zipSource));
+      }
+    }
+
+    ImmutableSet.Builder<Pattern> entriesToExcludeBuilder = ImmutableSet.builder();
+    if (entriesToExclude != null) {
+      for (String entryToExclude : entriesToExclude) {
+        entriesToExcludeBuilder.add(Pattern.compile(entryToExclude));
+      }
+    }
+
+    Map<Path, AbsPath> map = new LinkedHashMap<>();
+    if (entriesFile != null) {
+      AbsPath entriesFilePath = CURRENT_DIRECTORY.resolve(entriesFile.toPath());
+      List<String> entriesLines = Files.readAllLines(entriesFilePath.getPath());
+
+      for (int lineIndex = 0; lineIndex < entriesLines.size(); lineIndex += 3) {
+        String entry = entriesLines.get(lineIndex);
+        AbsPath zipEntryAbsPath = CURRENT_DIRECTORY.resolve(entry);
+        RelPath shortPath = RelPath.get(entriesLines.get(lineIndex + 1));
+        boolean isSourceFlag = Boolean.parseBoolean(entriesLines.get(lineIndex + 2));
+
+        if (isSourceFlag) {
+          RelativePathMapUtils.addPathToRelativePathMap(
+              CURRENT_DIRECTORY,
+              map,
+              CURRENT_DIRECTORY.getPath(),
+              zipEntryAbsPath,
+              shortPath.getPath());
+        } else {
+          RelativePathMapUtils.addPathToRelativePathMap(
+              CURRENT_DIRECTORY,
+              map,
+              zipEntryAbsPath.getPath().getParent(),
+              zipEntryAbsPath,
+              zipEntryAbsPath.getFileName());
+        }
+      }
+    }
+    ImmutableMap<RelPath, RelPath> entryMap =
+        ZipUtils.toRelPathEntryMap(ImmutableMap.copyOf(map), CURRENT_DIRECTORY);
+
+    ZipUtils.createZipFile(
+        CURRENT_DIRECTORY,
+        entryMap,
+        zipSourcesBuilder.build(),
+        entriesToExcludeBuilder.build(),
+        onDuplicateEntry,
+        outputPath,
+        hardcodePermissionsForDeterministicOutput);
+
+    System.exit(0);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/ZipUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/ZipUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/features/zip/rules/utils/ZipUtils.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.features.zip.rules.utils;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.util.zip.collect.OnDuplicateEntry;
+import com.facebook.buck.util.zip.collect.ZipEntrySourceCollection;
+import com.facebook.buck.util.zip.collect.ZipEntrySourceCollectionBuilder;
+import com.facebook.buck.util.zip.collect.ZipEntrySourceCollectionWriter;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+/** Utilities method related to zip_file rule */
+public class ZipUtils {
+
+  /** Creates zip file */
+  public static void createZipFile(
+      AbsPath ruleCellRoot,
+      ImmutableMap<RelPath, RelPath> entryMap,
+      ImmutableList<RelPath> zipSources,
+      ImmutableSet<Pattern> entriesToExclude,
+      OnDuplicateEntry onDuplicateEntry,
+      RelPath outputPath,
+      boolean requiresDeterministicOutput)
+      throws IOException {
+    ZipEntrySourceCollection zipEntrySourceCollection =
+        buildCollection(
+            ruleCellRoot,
+            entryMap,
+            zipSources,
+            entriesToExclude,
+            onDuplicateEntry,
+            requiresDeterministicOutput);
+    new ZipEntrySourceCollectionWriter(ruleCellRoot, requiresDeterministicOutput)
+        .copyToZip(zipEntrySourceCollection, outputPath.getPath());
+  }
+
+  private static ZipEntrySourceCollection buildCollection(
+      AbsPath ruleCellRoot,
+      ImmutableMap<RelPath, RelPath> entryMap,
+      ImmutableList<RelPath> zipSources,
+      ImmutableSet<Pattern> entriesToExclude,
+      OnDuplicateEntry onDuplicateEntry,
+      boolean requiresDeterministicOutput) {
+    ZipEntrySourceCollectionBuilder builder =
+        new ZipEntrySourceCollectionBuilder(entriesToExclude, onDuplicateEntry);
+    for (RelPath zipPath : zipSources) {
+      AbsPath zipSourceAbsPath = ruleCellRoot.resolve(zipPath);
+      try {
+        builder.addZipFile(zipSourceAbsPath.getPath());
+      } catch (IOException e) {
+        throw new RuntimeException(
+            String.format(
+                "Error while reading archive entries from %s: %s",
+                zipSourceAbsPath, e.getMessage()),
+            e);
+      }
+    }
+    for (Map.Entry<RelPath, RelPath> pathEntry : entryMap.entrySet()) {
+      String entryName = pathEntry.getKey().toString();
+      AbsPath entryAbsPath = ruleCellRoot.resolve(pathEntry.getValue());
+      builder.addFile(entryName, entryAbsPath.getPath());
+    }
+    return builder.build();
+  }
+
+  /**
+   * Returns a map where given {@link AbsPath} instances are resolved relatively to the given root
+   * path.
+   */
+  public static ImmutableMap<RelPath, RelPath> toRelPathEntryMap(
+      ImmutableMap<Path, AbsPath> entryPathToAbsolutePathMap, AbsPath rootPath) {
+    return entryPathToAbsolutePathMap.entrySet().stream()
+        .collect(
+            ImmutableMap.toImmutableMap(
+                e -> RelPath.of(e.getKey()), e -> rootPath.relativize(e.getValue())));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/BUCK
@@ -0,0 +1,21 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "installer_server",
+    srcs = glob([
+        "*.java",
+        "*.kt",
+    ]),
+    visibility = [
+        "PUBLIC",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/installer/proto:installer-model",
+        "prelude//toolchains/android/third-party:grpc-netty-shaded",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallCommand.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallCommand.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallCommand.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer;
+
+import java.nio.file.Path;
+import java.util.Set;
+
+/**
+ * Install Command interface. Support for a specific installer such as iOS or Android is implemented
+ * as subclasses of this interface. *
+ */
+public interface InstallCommand {
+  /**
+   * Names this implementation, e.g. {@code android}. Reported with every install so telemetry can
+   * tell one installer's installs from another's.
+   */
+  String name();
+
+  /** Installs an artifact from a given path/location. */
+  InstallResult fileReady(String artifact, Path artifactPath, InstallId installId);
+
+  /** Indicate that all files have been received by the installer */
+  InstallResult allFilesReady(InstallId installId);
+
+  /**
+   * Notifies which artifacts the client intends to send, before any of them arrive.
+   *
+   * <p>Lets an implementation tell "this build has no such artifact" apart from "it has not turned
+   * up yet", which is not otherwise decidable while artifacts are still in flight.
+   */
+  default void onInstallStarted(InstallId installId, Set<String> expectedArtifacts) {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallError.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallError.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallError.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer;
+
+import java.util.Comparator;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class InstallError {
+  private final String message;
+  private final Set<InstallErrorTag> tags;
+
+  public InstallError(String message, InstallErrorTag installErrorTag) {
+    this(message, Set.of(installErrorTag));
+  }
+
+  public InstallError(String message, Set<InstallErrorTag> installErrorTags) {
+    this.message = message;
+    this.tags = installErrorTags;
+  }
+
+  public String getMessage() {
+    return String.format(
+        "%s: %s",
+        tags.stream().findFirst().map(InstallErrorTag::getName).orElse("UNKNOWN"), message);
+  }
+
+  public Set<InstallErrorTag> getTags() {
+    return tags;
+  }
+
+  public com.facebook.buck.install.model.ErrorDetail toProtoModel() {
+
+    InstallErrorCategory highestInstallErrorCategory =
+        tags.stream()
+            .map(InstallErrorTag::getErrorCategory)
+            .min(
+                Comparator.comparingInt(
+                    token -> {
+                      switch (token) {
+                        case INFRA:
+                          return 0;
+                        case ENVIRONMENT:
+                          return 1;
+                        case USER:
+                          return 2;
+                        default:
+                          return 3;
+                      }
+                    }))
+            .orElse(InstallErrorCategory.UNKNOWN);
+    return com.facebook.buck.install.model.ErrorDetail.newBuilder()
+        // TODO(T213306104) Add a wiki link to guide users on troubleshooting installation errors.
+        .setMessage(message)
+        .addAllTags(tags.stream().map(InstallErrorTag::getName).collect(Collectors.toSet()))
+        // Report highest priority category: Infra, then Environment, then User
+        .setCategory(highestInstallErrorCategory.toProtoModel())
+        .build();
+  }
+
+  @Override
+  public String toString() {
+    return "InstallError{" + "message='" + message + '\'' + ", tags=" + tags + '}';
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallErrorCategory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallErrorCategory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallErrorCategory.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer;
+
+import com.facebook.buck.install.model.ErrorCategory;
+
+public enum InstallErrorCategory {
+  UNKNOWN,
+  INFRA,
+  USER,
+  ENVIRONMENT;
+
+  public ErrorCategory toProtoModel() {
+    switch (this) {
+      case INFRA:
+        return ErrorCategory.TIER_0;
+      case USER:
+        return ErrorCategory.INPUT;
+      case ENVIRONMENT:
+        return ErrorCategory.ENVIRONMENT;
+      default:
+        return ErrorCategory.ERROR_CATEGORY_UNSPECIFIED;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallErrorTag.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallErrorTag.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallErrorTag.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer
+
+interface InstallErrorTag {
+  fun getErrorCategory(): InstallErrorCategory
+
+  fun getName(): String
+}
+
+object DefaultInstallErrorTag : InstallErrorTag {
+  override fun getErrorCategory(): InstallErrorCategory = InstallErrorCategory.INFRA
+
+  override fun getName(): String = "UNKNOWN"
+}
+
+object InfraTimeoutErrorTag : InstallErrorTag {
+  override fun getErrorCategory(): InstallErrorCategory = InstallErrorCategory.INFRA
+
+  override fun getName(): String = "Timeout"
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallId.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallId.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallId.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import java.util.Objects;
+
+/** Install id. Typically represents fully qualified name of the build target. */
+public class InstallId {
+
+  private final String value;
+
+  private InstallId(final String value) {
+    this.value = value;
+  }
+
+  public String getValue() {
+    return value;
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(value);
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (obj == null || getClass() != obj.getClass()) {
+      return false;
+    }
+    return value.equals(((InstallId) obj).value);
+  }
+
+  public static InstallId of(String value) {
+    Preconditions.checkState(!Strings.isNullOrEmpty(value), "install id has to be not empty");
+    return new InstallId(value);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallResult.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallResult.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallResult.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/** Represents a result from an install attempt */
+public class InstallResult {
+
+  private static final InstallResult SUCCESS = new InstallResult(List.of(), Optional.empty());
+
+  private final List<Map<String, String>> deviceMetadata;
+  private final Optional<InstallError> installError;
+
+  public InstallResult(
+      List<Map<String, String>> deviceMetadata, Optional<InstallError> installError) {
+    this.deviceMetadata = deviceMetadata;
+    this.installError = installError;
+  }
+
+  public static InstallResult success() {
+    return SUCCESS;
+  }
+
+  /**
+   * @deprecated use {@link this.error(InstallError)} instead
+   */
+  @Deprecated
+  public static InstallResult error(String errorMessage) {
+    return new InstallResult(
+        List.of(), Optional.of(new InstallError(errorMessage, DefaultInstallErrorTag.INSTANCE)));
+  }
+
+  public static InstallResult error(InstallError installError) {
+    return new InstallResult(List.of(), Optional.of(installError));
+  }
+
+  public boolean isError() {
+    return installError.isPresent();
+  }
+
+  public InstallError getInstallError() {
+    return installError.orElseThrow(
+        () ->
+            new IllegalStateException(
+                "installError is not present. `isError()` has to be called before invoking"
+                    + " `getInstallError()`"));
+  }
+
+  public List<Map<String, String>> getDeviceMetadata() {
+    return deviceMetadata;
+  }
+
+  public String getErrorMessage() {
+    return installError
+        .orElseThrow(
+            () ->
+                new IllegalStateException(
+                    "Error message is not present. `isError()` has to be called before invoking"
+                        + " `getErrorMessage()`"))
+        .getMessage();
+  }
+
+  @Override
+  public String toString() {
+    return "InstallResult{"
+        + "deviceMetadata="
+        + deviceMetadata
+        + ", installError="
+        + installError.orElse(null)
+        + '}';
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallerServer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallerServer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallerServer.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer;
+
+import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
+
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.SettableFuture;
+import io.grpc.Attributes;
+import io.grpc.Server;
+import io.grpc.ServerTransportFilter;
+import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
+import io.grpc.netty.shaded.io.netty.channel.EventLoopGroup;
+import io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoopGroup;
+import io.grpc.netty.shaded.io.netty.channel.socket.nio.NioServerSocketChannel;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
+import java.util.logging.Logger; // NOPMD
+
+public class InstallerServer extends ServerTransportFilter {
+  private static final Logger LOG = Logger.getLogger(InstallerServer.class.getName());
+
+  Server grpcServer;
+  boolean clientConnected = false;
+
+  public InstallerServer(InstallCommand installer, int tcpPort, long installTimeoutSeconds) {
+    SettableFuture<Void> isDone = SettableFuture.create();
+    InstallerService installerService =
+        new InstallerService(installer, isDone, installTimeoutSeconds);
+    this.grpcServer = buildServer(installerService, tcpPort);
+    Futures.addCallback(
+        isDone,
+        new FutureCallback<Void>() {
+          @Override
+          public void onSuccess(Void result) {
+            LOG.info("Installer Server shutting down...");
+            stopServer();
+          }
+
+          @Override
+          public void onFailure(Throwable t) {
+            LOG.log(Level.WARNING, "Execution exception...", t);
+          }
+        },
+        directExecutor());
+
+    Runtime.getRuntime()
+        .addShutdownHook(
+            new Thread(
+                () -> {
+                  // Use stderr here since the logger may have been reset by its JVM shutdown hook.
+                  System.err.println("*** shutting down gRPC server since JVM is shutting down");
+                  stopServer();
+                  System.err.println("*** server shut down");
+                }));
+  }
+
+  public void run() throws IOException, InterruptedException {
+    this.grpcServer.start();
+    Instant serverStartTime = Instant.now();
+
+    do {
+      try {
+        if (!isParentAlive()) {
+          LOG.info("Parent process has been killed, shutting down");
+          stopServer();
+        }
+        long serverUptime = Duration.between(serverStartTime, Instant.now()).toSeconds();
+        if (!this.clientConnected && serverUptime > 20) {
+          LOG.info("No client connected for 20 seconds, shutting down");
+          stopServer();
+        }
+      } catch (Exception e) {
+        LOG.log(Level.SEVERE, "Error checking parent process liveness", e);
+      }
+    } while (!this.grpcServer.awaitTermination(10, TimeUnit.SECONDS));
+  }
+
+  /** Called when buck2 connects */
+  public Attributes transportReady(Attributes transportAttrs) {
+    if (this.clientConnected) {
+      this.LOG.log(
+          Level.SEVERE,
+          "Unexpected state, multiple connections detected. Should be 1 connection per server.");
+    }
+    this.clientConnected = true;
+    return transportAttrs;
+  }
+
+  /** Called when buck2 disconnects */
+  public void transportTerminated(Attributes transportAttrs) {
+    this.LOG.log(Level.SEVERE, "Client disconnected, shutting down");
+    stopServer();
+  }
+
+  /** Build an installer server at requested {@code TCP}. */
+  private Server buildServer(InstallerService service, int tcpPort) {
+    LOG.info(String.format("Starting Installer Server using TCP on %s", tcpPort));
+    return getTCPServer(service, tcpPort);
+  }
+
+  private Server getTCPServer(InstallerService service, int tcpPort) {
+    EventLoopGroup group = new NioEventLoopGroup();
+    SocketAddress addr = new InetSocketAddress("127.0.0.1", tcpPort); // NOPMD
+
+    Server server =
+        NettyServerBuilder.forAddress(addr)
+            .channelType(NioServerSocketChannel.class)
+            .workerEventLoopGroup(group)
+            .bossEventLoopGroup(group)
+            .addService(service)
+            .addTransportFilter(this)
+            .build();
+    LOG.info(String.format("Starting server listening on TCP port %s", tcpPort));
+    return server;
+  }
+
+  /** Shuts down installer server. */
+  private void stopServer() {
+    if (this.grpcServer != null && !this.grpcServer.isTerminated()) {
+      try {
+        this.grpcServer.shutdown().awaitTermination(5, TimeUnit.SECONDS);
+        if (!this.grpcServer.isTerminated()) {
+          this.grpcServer.shutdownNow();
+        }
+      } catch (InterruptedException e) {
+        this.grpcServer.shutdownNow();
+      }
+    }
+  }
+
+  private static boolean isParentAlive() {
+    Optional<ProcessHandle> parent = ProcessHandle.current().parent();
+    return parent.isPresent() && parent.get().pid() != 1 && parent.get().isAlive();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallerService.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallerService.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/InstallerService.java
@@ -0,0 +1,263 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer;
+
+import com.facebook.buck.install.model.DeviceMetadata;
+import com.facebook.buck.install.model.FileReadyRequest;
+import com.facebook.buck.install.model.FileResponse;
+import com.facebook.buck.install.model.InstallInfoRequest;
+import com.facebook.buck.install.model.InstallResponse;
+import com.facebook.buck.install.model.InstallerGrpc;
+import com.facebook.buck.install.model.ShutdownRequest;
+import com.facebook.buck.install.model.ShutdownResponse;
+import com.google.common.base.Throwables;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.common.util.concurrent.SettableFuture;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import io.grpc.stub.StreamObserver;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Function;
+import java.util.logging.Level;
+import java.util.logging.Logger; // NOPMD
+import java.util.stream.Collectors;
+
+/**
+ * Installer Service that implements {@code install.proto}
+ *
+ * <p>The workflow:
+ *
+ * <ol>
+ *   <li>client (buck2) sends `install` request with install id and file map. It could be multiple
+ *       targets that would have different install id associated with them.
+ *   <li>client sends multiple `fileReady` requests (file data + install id)
+ *   <li>{@link InstallerService} tracks all received `fileReady` requests associated with the same
+ *       install id. When all files received then {@link InstallerService} calls {@link
+ *       InstallCommand} to actually install all received files for the specific install id into the
+ *       device/emulator.
+ *   <li>client sends `shutdownServer` when wants to stop interactions and asks {@link
+ *       InstallerService} to terminate.
+ * </ol>
+ */
+public class InstallerService extends InstallerGrpc.InstallerImplBase {
+
+  private static final ThreadPoolExecutor THREAD_POOL =
+      new ThreadPoolExecutor(
+          0,
+          Integer.MAX_VALUE,
+          1,
+          TimeUnit.SECONDS,
+          new SynchronousQueue<>(),
+          new ThreadFactoryBuilder().setNameFormat("Installer").build());
+
+  private static final ListeningExecutorService LISTENING_EXECUTOR_SERVICE =
+      MoreExecutors.listeningDecorator(THREAD_POOL);
+
+  private static final Logger LOG = Logger.getLogger(InstallerService.class.getName());
+  private final InstallCommand installer;
+  private final SettableFuture<Void> installFinished;
+  private final Map<InstallId, Map<String, Optional<Path>>> installIdToFilesMap = new HashMap<>();
+  // Installs where at least one artifact failed. Guarded by installIdToFilesMap.
+  private final Set<InstallId> failedInstalls = new HashSet<>();
+  private final long installTimeoutSeconds;
+
+  public InstallerService(
+      InstallCommand installer, SettableFuture<Void> installFinished, long installTimeoutSeconds) {
+    this.installer = installer;
+    this.installFinished = installFinished;
+    this.installTimeoutSeconds = installTimeoutSeconds;
+    LOG.info("Install timeout configured to " + this.installTimeoutSeconds + "s");
+  }
+
+  @Override
+  public void install(
+      InstallInfoRequest request, StreamObserver<InstallResponse> responseObserver) {
+    try {
+      InstallResponse response = handleInstallRequest(request);
+      responseObserver.onNext(response);
+      responseObserver.onCompleted();
+    } catch (Exception e) {
+      handleException(responseObserver, e);
+    }
+  }
+
+  private InstallResponse handleInstallRequest(InstallInfoRequest request) {
+    InstallId installId = InstallId.of(request.getInstallId());
+    Set<String> fileNames = new HashSet<>(request.getFileNamesList());
+    LOG.info(
+        String.format(
+            "Received install id: %s with %d file names", installId.getValue(), fileNames.size()));
+    // Before the install is registered: a file is only accepted for an install that is in the map,
+    // so declaring first leaves no window where an artifact can arrive for an install that has not
+    // been told what to expect.
+    installer.onInstallStarted(installId, fileNames);
+    synchronized (installIdToFilesMap) {
+      installIdToFilesMap.put(
+          installId,
+          fileNames.stream()
+              .collect(Collectors.toMap(Function.identity(), ignore -> Optional.empty())));
+    }
+    return InstallResponse.newBuilder()
+        .setInstallId(installId.getValue())
+        .setInstallerName(installer.name())
+        .build();
+  }
+
+  @Override
+  public void fileReady(FileReadyRequest request, StreamObserver<FileResponse> responseObserver) {
+    try {
+      FileResponse fileResponse = handleFileReadyRequest(request);
+      responseObserver.onNext(fileResponse);
+      responseObserver.onCompleted();
+    } catch (Exception e) {
+      handleException(responseObserver, e);
+    }
+  }
+
+  private FileResponse handleFileReadyRequest(FileReadyRequest request)
+      throws InterruptedException {
+    InstallId installId = InstallId.of(request.getInstallId());
+    String name = request.getName();
+    String path = request.getPath();
+    LOG.info(
+        String.format(
+            "Received artifact %s located at %s for install id: %s",
+            name, path, installId.getValue()));
+
+    FileResponse.Builder fileResponseBuilder =
+        FileResponse.newBuilder().setName(name).setPath(path).setInstallId(installId.getValue());
+
+    synchronized (installIdToFilesMap) {
+      // Absent once the install has been decided, so a repeat or unknown delivery is ignored
+      // rather than handed over again -- doing the work would cost a timeout and be discarded.
+      if (!installIdToFilesMap.containsKey(installId)) {
+        LOG.info(String.format("Ignoring artifact %s for a finished install", name));
+        return fileResponseBuilder.build();
+      }
+    }
+
+    InstallResult result = runBounded(() -> installer.fileReady(name, Paths.get(path), installId));
+    // Reported by whichever step produced it. Handing the artifact over runs before the install
+    // does, so keeping only the last result would drop anything the first one had to say.
+    List<Map<String, String>> deviceMetadata = new ArrayList<>(result.getDeviceMetadata());
+
+    boolean readyToInstall = false;
+    synchronized (installIdToFilesMap) {
+      Map<String, Optional<Path>> filesMap = installIdToFilesMap.get(installId);
+      if (filesMap != null) {
+        filesMap.put(name, Optional.of(Paths.get(path)));
+        if (result.isError()) {
+          failedInstalls.add(installId);
+        }
+        // Install once every artifact is in and none of them failed.
+        if (filesMap.values().stream().allMatch(Optional::isPresent)) {
+          readyToInstall = !failedInstalls.contains(installId);
+          // Nothing looks these up again, and one server handles many installs.
+          installIdToFilesMap.remove(installId);
+          failedInstalls.remove(installId);
+        }
+      }
+    }
+
+    if (readyToInstall) {
+      LOG.info(String.format("Starting install for install id: %s", installId.getValue()));
+      result = runBounded(() -> installer.allFilesReady(installId));
+      LOG.info("Install [" + installId.getValue() + "] finished with result: " + result);
+      deviceMetadata.addAll(result.getDeviceMetadata());
+    }
+
+    if (result.isError()) {
+      fileResponseBuilder.setErrorDetail(result.getInstallError().toProtoModel());
+    }
+    for (Map<String, String> metadata : deviceMetadata) {
+      DeviceMetadata.Builder metadataBuilder = DeviceMetadata.newBuilder();
+      for (Map.Entry<String, String> entry : metadata.entrySet()) {
+        metadataBuilder.addEntry(
+            DeviceMetadata.Entry.newBuilder().setKey(entry.getKey()).setValue(entry.getValue()));
+      }
+      fileResponseBuilder.addDeviceMetadata(metadataBuilder);
+    }
+
+    return fileResponseBuilder.build();
+  }
+
+  /**
+   * Runs one step of an install on a worker thread, bounded by the configured timeout.
+   *
+   * <p>Handing an artifact over can block -- an implementation may shell out to the device -- so
+   * the bound covers per-artifact work as well as the install. Anything thrown is turned into a
+   * tagged error, rather than escaping as a bare RPC failure that loses the tag.
+   *
+   * <p>The bound is on the answer, not on the work. Timing out interrupts the step, but a thread
+   * blocked reading an {@code adb} subprocess does not observe an interrupt, so it may run on and
+   * finish into a result nobody reads. What that guarantees is that the client always gets a
+   * response; reclaiming the thread would need the blocking calls themselves to be bounded. In
+   * practice the installer serves one install and exits, so a stranded thread dies with it.
+   */
+  private InstallResult runBounded(Callable<InstallResult> step) throws InterruptedException {
+    ListenableFuture<InstallResult> running = LISTENING_EXECUTOR_SERVICE.submit(step);
+    try {
+      return running.get(installTimeoutSeconds, TimeUnit.SECONDS);
+    } catch (TimeoutException e) {
+      running.cancel(true);
+      return failed(
+          "Timeout of " + installTimeoutSeconds + "s has been exceeded. Install failed.",
+          InfraTimeoutErrorTag.INSTANCE);
+    } catch (ExecutionException e) {
+      return failed(
+          Throwables.getStackTraceAsString(e.getCause()), DefaultInstallErrorTag.INSTANCE);
+    }
+  }
+
+  private static InstallResult failed(String message, InstallErrorTag tag) {
+    return new InstallResult(List.of(), Optional.of(new InstallError(message, tag)));
+  }
+
+  @Override
+  public void shutdownServer(
+      ShutdownRequest request, StreamObserver<ShutdownResponse> responseObserver) {
+    try {
+      handleShutdownServerRequest(responseObserver);
+    } catch (Exception e) {
+      handleException(responseObserver, e);
+    }
+  }
+
+  private void handleShutdownServerRequest(StreamObserver<ShutdownResponse> responseObserver) {
+    LOG.info("Received shutting down request");
+    responseObserver.onNext(ShutdownResponse.getDefaultInstance());
+    responseObserver.onCompleted();
+    installFinished.set(null);
+  }
+
+  private void handleException(StreamObserver<?> responseObserver, Exception e) {
+    LOG.log(Level.SEVERE, "Unexpected exception", e);
+    responseObserver.onError(
+        io.grpc.Status.INTERNAL
+            .withDescription("Unexpected exception: " + Throwables.getStackTraceAsString(e))
+            .asException());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AdbHelperFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AdbHelperFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AdbHelperFactory.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.facebook.buck.android.AdbExecutionContext;
+import com.facebook.buck.android.AdbHelper;
+import com.facebook.buck.android.AdbOptions;
+import com.facebook.buck.android.device.TargetDeviceOptions;
+import com.facebook.buck.android.exopackage.AdbUtils;
+import com.facebook.buck.android.exopackage.InstallTimings;
+import com.facebook.buck.android.exopackage.SetDebugAppMode;
+import java.util.Optional;
+import java.util.logging.Logger; // NOPMD
+
+/**
+ * Builds the {@link AdbHelper} for an install.
+ *
+ * <p>The one place the command line and the install options are turned into the objects adb needs,
+ * so a second construction cannot drift from it and reach a different set of devices.
+ */
+class AdbHelperFactory {
+
+  private AdbHelperFactory() {}
+
+  static AdbHelper create(
+      Logger logger,
+      AndroidCommandLineOptions cliOptions,
+      AndroidInstallApkOptions apkOptions,
+      SetDebugAppMode setDebugAppMode,
+      InstallTimings timings) {
+    AdbOptions adbOptions =
+        new AdbOptions(
+            cliOptions.adbExecutablePath,
+            cliOptions.adbThreadCount,
+            cliOptions.adbServerPort,
+            cliOptions.multiInstallMode,
+            apkOptions.stagedInstallMode,
+            cliOptions.ignoreMissingDevices,
+            apkOptions.apexMode,
+            cliOptions.restartMode.name(),
+            cliOptions.waitForDeviceReady);
+    logger.info("adbOptions: " + adbOptions);
+
+    TargetDeviceOptions targetDeviceOptions =
+        new TargetDeviceOptions(
+            cliOptions.useEmulatorsOnlyMode,
+            cliOptions.useRealDevicesOnlyMode,
+            Optional.ofNullable(cliOptions.serialNumber));
+    logger.info("targetDeviceOptions: " + targetDeviceOptions);
+
+    AdbUtils adbUtils =
+        new AdbUtils(
+            Optional.ofNullable(apkOptions.adbExecutable)
+                .orElseThrow(AndroidInstallException.Companion::adbPathNotFound),
+            adbOptions.getAdbServerPort());
+
+    return new AdbHelper(
+        adbUtils,
+        adbOptions,
+        targetDeviceOptions,
+        new AdbExecutionContext(),
+        new IsolatedAndroidInstallerPrinter(logger),
+        apkOptions.restartAdbOnFailure,
+        setDebugAppMode,
+        timings);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidArtifacts.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidArtifacts.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidArtifacts.java
@@ -0,0 +1,273 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import javax.annotation.Nullable;
+
+/**
+ * Holds android install related artifacts (apk options, manifest path, etc)
+ *
+ * <p>Shared across the gRPC handler threads that deliver artifacts, the threads that push them, and
+ * the install that reads them, so every member is guarded by this object's monitor.
+ */
+class AndroidArtifacts {
+  private AbsPath androidManifestPath;
+  private AndroidInstallApkOptions apkOptions;
+  private AbsPath apk;
+  private ImmutableSet<String> apkAbis;
+  private Optional<AbsPath> secondaryDexExopackageInfoDirectory = Optional.empty();
+  private Optional<AbsPath> secondaryDexExopackageInfoMetadata = Optional.empty();
+  private Optional<AbsPath> nativeLibraryExopackageInfoDirectory = Optional.empty();
+  private Optional<AbsPath> nativeLibraryExopackageInfoMetadata = Optional.empty();
+  private Optional<AbsPath> resourcesExopackageInfoAssets = Optional.empty();
+  private Optional<AbsPath> resourcesExopackageInfoAssetsHash = Optional.empty();
+  private Optional<AbsPath> resourcesExopackageInfoRes = Optional.empty();
+  private Optional<AbsPath> resourcesExopackageInfoResHash = Optional.empty();
+  // Artifact name -> wall-clock arrival.
+  private final Map<String, Long> fileArrivalMillis = new HashMap<>();
+  // What buck said it would send, split by payload. A class with no entry is one this build does
+  // not produce, which is why it can never be complete.
+  private final Map<ArtifactClass, Set<String>> expectedByClass =
+      new EnumMap<>(ArtifactClass.class);
+
+  /** Records which artifacts buck said it would send, before any of them arrive. */
+  public synchronized void setExpectedArtifacts(Set<String> expectedArtifacts) {
+    expectedByClass.clear();
+    for (String artifactName : expectedArtifacts) {
+      expectedByClass
+          .computeIfAbsent(ArtifactClass.of(artifactName), unused -> new HashSet<>())
+          .add(artifactName);
+    }
+  }
+
+  /**
+   * True once every artifact this build declared for {@code artifactClass} has arrived, and false
+   * if it declared none.
+   *
+   * <p>Checked against what buck said it would send, not against what happens to be on disk: assets
+   * are optional for a build, so their absence is otherwise indistinguishable from their not having
+   * turned up yet.
+   */
+  public synchronized boolean hasAllArtifactsFor(ArtifactClass artifactClass) {
+    Set<String> declared = expectedByClass.get(artifactClass);
+    return declared != null && fileArrivalMillis.keySet().containsAll(declared);
+  }
+
+  /**
+   * True once every artifact buck declared has arrived, and false if it declared none.
+   *
+   * <p>Independent of how names bucket into classes: it asks whether anything is still coming, not
+   * which payload it belongs to.
+   */
+  public synchronized boolean allArtifactsArrived() {
+    return !expectedByClass.isEmpty() && undeliveredArtifacts().isEmpty();
+  }
+
+  /**
+   * Artifacts buck declared but never delivered.
+   *
+   * <p>Only meaningful once buck says it has sent everything; before that an artifact is missing
+   * simply because it has not arrived. A name here means the two sides disagree about what an
+   * artifact is called, which leaves its class permanently incomplete and its payload unstreamed.
+   */
+  public synchronized ImmutableSet<String> undeliveredArtifacts() {
+    return expectedByClass.values().stream()
+        .flatMap(Set::stream)
+        .filter(artifactName -> !fileArrivalMillis.containsKey(artifactName))
+        .collect(ImmutableSet.toImmutableSet());
+  }
+
+  /**
+   * Records that {@code artifactName} was delivered by buck at {@code timestampMillis}. Must be
+   * called when the file is actually received, not when the installer gets around to consuming it,
+   * or every artifact is stamped with the same instant and the spans below all collapse to zero.
+   */
+  public synchronized void recordFileArrival(String artifactName, long timestampMillis) {
+    fileArrivalMillis.putIfAbsent(artifactName, timestampMillis);
+  }
+
+  /** When each artifact was delivered, for whoever is measuring the install. */
+  public synchronized ImmutableMap<String, Long> arrivals() {
+    return ImmutableMap.copyOf(fileArrivalMillis);
+  }
+
+  /** Groups install artifacts by the exopackage payload they belong to. */
+  enum ArtifactClass {
+    SECONDARY_DEX("dex"),
+    NATIVE_LIBRARY("native"),
+    RESOURCES("resources"),
+    CONTROL("control"),
+    APK("apk");
+
+    final String metricName;
+
+    ArtifactClass(String metricName) {
+      this.metricName = metricName;
+    }
+
+    /** The classes that are exopackage payloads, each pushable to the device on its own. */
+    static final ImmutableSet<ArtifactClass> EXOPACKAGE_PAYLOADS =
+        Sets.immutableEnumSet(SECONDARY_DEX, NATIVE_LIBRARY, RESOURCES);
+
+    /** The class whose arrival gates pushing {@code pushGroup}, or null if it is derived. */
+    @Nullable
+    static ArtifactClass forPushGroup(String pushGroup) {
+      switch (pushGroup) {
+        case "secondary_dex":
+          return SECONDARY_DEX;
+        case "native_library":
+          return NATIVE_LIBRARY;
+        case "resources":
+          return RESOURCES;
+        default:
+          return null;
+      }
+    }
+
+    static ArtifactClass of(String artifactName) {
+      if (artifactName.startsWith("secondary_dex")) {
+        return SECONDARY_DEX;
+      }
+      if (artifactName.startsWith("native_library")) {
+        return NATIVE_LIBRARY;
+      }
+      if (artifactName.startsWith("resources_exopackage")) {
+        return RESOURCES;
+      }
+      if (artifactName.equals("options")
+          || artifactName.equals("manifest")
+          || artifactName.equals("cpu_filters")) {
+        return CONTROL;
+      }
+      // AndroidInstallerManager#fileReady treats any unrecognised name as the apk.
+      return APK;
+    }
+  }
+
+  public synchronized void setAndroidManifestPath(AbsPath androidManifestPath) {
+    this.androidManifestPath = androidManifestPath;
+  }
+
+  public synchronized AbsPath getAndroidManifestPath() {
+    return this.androidManifestPath;
+  }
+
+  public synchronized void setApkOptions(AndroidInstallApkOptions apkOptions) {
+    this.apkOptions = apkOptions;
+  }
+
+  public synchronized AndroidInstallApkOptions getApkOptions() {
+    return this.apkOptions;
+  }
+
+  /**
+   * The ABIs the apk carries native code for, or null until buck has sent the cpu filters. Empty
+   * means the filters named nothing this installer recognises.
+   */
+  @Nullable
+  public synchronized ImmutableSet<String> getApkAbis() {
+    return apkAbis;
+  }
+
+  public synchronized void setApkAbis(ImmutableSet<String> apkAbis) {
+    this.apkAbis = apkAbis;
+  }
+
+  public synchronized AbsPath getApk() {
+    return apk;
+  }
+
+  public synchronized void setApk(AbsPath apk) {
+    this.apk = apk;
+  }
+
+  public synchronized Optional<AbsPath> getSecondaryDexExopackageInfoDirectory() {
+    return secondaryDexExopackageInfoDirectory;
+  }
+
+  public synchronized void setSecondaryDexExopackageInfoDirectory(
+      Optional<AbsPath> secondaryDexExopackageInfoDirectory) {
+    this.secondaryDexExopackageInfoDirectory = secondaryDexExopackageInfoDirectory;
+  }
+
+  public synchronized Optional<AbsPath> getSecondaryDexExopackageInfoMetadata() {
+    return secondaryDexExopackageInfoMetadata;
+  }
+
+  public synchronized void setSecondaryDexExopackageInfoMetadata(
+      Optional<AbsPath> secondaryDexExopackageInfoMetadata) {
+    this.secondaryDexExopackageInfoMetadata = secondaryDexExopackageInfoMetadata;
+  }
+
+  public synchronized Optional<AbsPath> getNativeLibraryExopackageInfoDirectory() {
+    return nativeLibraryExopackageInfoDirectory;
+  }
+
+  public synchronized void setNativeLibraryExopackageInfoDirectory(
+      Optional<AbsPath> nativeLibraryExopackageInfoDirectory) {
+    this.nativeLibraryExopackageInfoDirectory = nativeLibraryExopackageInfoDirectory;
+  }
+
+  public synchronized Optional<AbsPath> getNativeLibraryExopackageInfoMetadata() {
+    return nativeLibraryExopackageInfoMetadata;
+  }
+
+  public synchronized void setNativeLibraryExopackageInfoMetadata(
+      Optional<AbsPath> nativeLibraryExopackageInfoMetadata) {
+    this.nativeLibraryExopackageInfoMetadata = nativeLibraryExopackageInfoMetadata;
+  }
+
+  public synchronized Optional<AbsPath> getResourcesExopackageInfoAssets() {
+    return resourcesExopackageInfoAssets;
+  }
+
+  public synchronized void setResourcesExopackageInfoAssets(
+      Optional<AbsPath> resourcesExopackageInfoAssets) {
+    this.resourcesExopackageInfoAssets = resourcesExopackageInfoAssets;
+  }
+
+  public synchronized Optional<AbsPath> getResourcesExopackageInfoAssetsHash() {
+    return resourcesExopackageInfoAssetsHash;
+  }
+
+  public synchronized void setResourcesExopackageInfoAssetsHash(
+      Optional<AbsPath> resourcesExopackageInfoAssetsHash) {
+    this.resourcesExopackageInfoAssetsHash = resourcesExopackageInfoAssetsHash;
+  }
+
+  public synchronized Optional<AbsPath> getResourcesExopackageInfoRes() {
+    return resourcesExopackageInfoRes;
+  }
+
+  public synchronized void setResourcesExopackageInfoRes(
+      Optional<AbsPath> resourcesExopackageInfoRes) {
+    this.resourcesExopackageInfoRes = resourcesExopackageInfoRes;
+  }
+
+  public synchronized Optional<AbsPath> getResourcesExopackageInfoResHash() {
+    return resourcesExopackageInfoResHash;
+  }
+
+  public synchronized void setResourcesExopackageInfoResHash(
+      Optional<AbsPath> resourcesExopackageInfoResHash) {
+    this.resourcesExopackageInfoResHash = resourcesExopackageInfoResHash;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidCommandLineOptions.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidCommandLineOptions.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidCommandLineOptions.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.google.common.annotations.VisibleForTesting;
+import javax.annotation.Nullable;
+import org.kohsuke.args4j.Option;
+
+/**
+ * Constructs the Command Line Options to Support Android Install. The majority of these were copied
+ * from {@code com.facebook.buck.cli.TargetDeviceCommandLineOptions}.
+ */
+class AndroidCommandLineOptions {
+  @VisibleForTesting public static final String EMULATOR_MODE_SHORT_ARG = "-e";
+
+  @VisibleForTesting static final String EMULATOR_MODE_LONG_ARG = "--emulator";
+
+  @Option(
+      name = EMULATOR_MODE_LONG_ARG,
+      aliases = {EMULATOR_MODE_SHORT_ARG},
+      usage = "Use this option to use emulators only.")
+  public boolean useEmulatorsOnlyMode;
+
+  @VisibleForTesting static final String DEVICE_MODE_SHORT_ARG = "-d";
+  @VisibleForTesting static final String DEVICE_MODE_LONG_ARG = "--device";
+
+  @Option(
+      name = DEVICE_MODE_LONG_ARG,
+      aliases = {DEVICE_MODE_SHORT_ARG},
+      usage = "Use this option to use real devices only.")
+  public boolean useRealDevicesOnlyMode;
+
+  @VisibleForTesting static final String SERIAL_NUMBER_SHORT_ARG = "-s";
+  @VisibleForTesting static final String SERIAL_NUMBER_LONG_ARG = "--serial";
+  static final String UDID_ARG = "--udid";
+
+  @Option(
+      name = SERIAL_NUMBER_LONG_ARG,
+      aliases = {SERIAL_NUMBER_SHORT_ARG, UDID_ARG},
+      metaVar = "<serial-number>",
+      usage = "Use device or emulator with specific serial or UDID number.")
+  @Nullable
+  public String serialNumber;
+
+  static final String ADB_EXECUTABLE_PATH_LONG_ARG = "--adb-executable-path";
+
+  @Option(
+      name = ADB_EXECUTABLE_PATH_LONG_ARG,
+      metaVar = "<Adb-executable-path>",
+      usage = "Use specified adb executable.")
+  public String adbExecutablePath;
+
+  @VisibleForTesting static final String ADB_THREADS_LONG_ARG = "--adb-threads";
+  @VisibleForTesting static final String ADB_THREADS_SHORT_ARG = "-T";
+
+  @Option(
+      name = ADB_THREADS_LONG_ARG,
+      aliases = {ADB_THREADS_SHORT_ARG},
+      usage =
+          "Number of threads to use for adb operations. "
+              + "Defaults to number of connected devices.")
+  public int adbThreadCount = 0;
+
+  static final String ADB_SERVER_PORT_LONG_ARG = "--adb-server-port";
+
+  @Option(
+      name = ADB_SERVER_PORT_LONG_ARG,
+      metaVar = "<TCP-port>",
+      usage = "Use ADB server with specific TCP port.")
+  public int adbServerPort = 0;
+
+  @VisibleForTesting static final String MULTI_INSTALL_MODE_SHORT_ARG = "-x";
+  @VisibleForTesting static final String MULTI_INSTALL_MODE_LONG_ARG = "--all-devices";
+
+  @Option(
+      name = MULTI_INSTALL_MODE_LONG_ARG,
+      aliases = {MULTI_INSTALL_MODE_SHORT_ARG},
+      usage = "Install .apk on all connected devices and/or emulators (multi-install mode)")
+  public boolean multiInstallMode;
+
+  @Option(
+      name = "--tcp-port",
+      usage = "TCP port used for connection in case TCP protocol is chosen")
+  private int tcpPort;
+
+  @Option(name = "--log-path", usage = "Use this option to set the log path for the install")
+  private String logPath;
+
+  @Option(
+      name = "--install-timeout",
+      metaVar = "<seconds>",
+      usage =
+          "Maximum time in seconds to wait for install to complete. Defaults to 600 seconds (10"
+              + " minutes).")
+  private long installTimeoutSeconds = 600;
+
+  @Option(
+      name = "--run",
+      aliases = {"-r"},
+      usage = "Run an activity (the default activity for package unless -a is specified).")
+  public boolean run = false;
+
+  @Option(
+      name = "--activity",
+      aliases = {"-a"},
+      metaVar = "<pkg/activity>",
+      usage = "Activity to launch e.g. com.facebook.katana/.LoginActivity. Implies -r.")
+  @Nullable
+  public String activity = null;
+
+  @Option(
+      name = "--intent-uri",
+      aliases = {"-i"},
+      metaVar = "<pkg/intent_uri>",
+      usage = "Intent URI to launch e.g. fb://profile. Implies -r.")
+  @Nullable
+  public String intentUri = null;
+
+  @Option(
+      name = "--wait-for-debugger",
+      aliases = {"-w"},
+      usage = "Have the launched process wait for the debugger")
+  public boolean waitForDebugger = false;
+
+  @Option(
+      name = "--skip-set-debug-app",
+      aliases = {"-b"},
+      usage =
+          "Bypass default invocation of Android's set-debug-app which silences ANRs while running"
+              + " and debugging.")
+  public boolean skipSetDebugApp = false;
+
+  @Option(
+      name = "--clean-up",
+      aliases = {"-c"},
+      usage = "Cleans up installed app.")
+  public boolean cleanUp = false;
+
+  @Option(
+      name = "--keep",
+      aliases = {"-k"},
+      usage = "Keeps user data when uninstalling an app")
+  public boolean keepUserData = false;
+
+  @Option(
+      name = "--uninstall",
+      aliases = {"-u"},
+      usage = "Uninstall before installing an app")
+  public boolean uninstallFirst = false;
+
+  @VisibleForTesting
+  static final String IGNORE_MISSING_DEVICES_LONG_ARG = "--ignore-missing-device";
+
+  @VisibleForTesting static final String IGNORE_MISSING_DEVICES_SHORT_ARG = "-m";
+
+  @Option(
+      name = IGNORE_MISSING_DEVICES_LONG_ARG,
+      aliases = {IGNORE_MISSING_DEVICES_SHORT_ARG},
+      usage = "Do not exit with nonzero, even if ADB detects no devices connected.")
+  public boolean ignoreMissingDevices = false;
+
+  @Option(
+      name = "--enable-app-links",
+      usage =
+          "Enable app links after installation. If not specified, only enables for allowlisted"
+              + " packages.")
+  @Nullable
+  public Boolean enableAppLinks = null;
+
+  public enum RestartMode {
+    auto,
+    yes,
+    no,
+  }
+
+  @Option(name = "--restart", usage = "Restart the device after installing APEX files.")
+  public RestartMode restartMode = RestartMode.auto;
+
+  @Option(
+      name = "--wait-for-device-ready",
+      usage = "Wait for the device to be ready after installation.")
+  public boolean waitForDeviceReady = false;
+
+  public AndroidCommandLineOptions() {}
+
+  public int getTcpPort() {
+    return tcpPort;
+  }
+
+  public String getLogPath() {
+    return logPath;
+  }
+
+  public long getInstallTimeoutSeconds() {
+    return installTimeoutSeconds;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstall.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstall.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstall.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.facebook.buck.android.AdbHelper;
+import com.facebook.buck.android.IsolatedApkInfo;
+import com.facebook.buck.android.exopackage.AndroidDeviceInfo;
+import com.facebook.buck.android.exopackage.ExopackageInstaller;
+import com.facebook.buck.android.exopackage.IsolatedExopackageInfo;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.installer.InstallId;
+import com.facebook.buck.installer.InstallResult;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger; // NOPMD
+
+/** Installs an Android Apk */
+class AndroidInstall {
+  private static final Logger LOG = Logger.getLogger(AndroidInstall.class.getName());
+  private static final DateTimeFormatter INSTALL_COMPLETION_TIME_FORMAT =
+      DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+  private static final Set<String> ENABLE_APP_LINKS_ALLOWLIST =
+      Set.of("com.facebook.wakizashi", "com.facebook.lite", "com.instagram.lite");
+
+  private final IsolatedApkInfo apkInfo;
+  private final Optional<IsolatedExopackageInfo> exopackageInfo;
+  private final AbsPath rootPath;
+  private final InstallId installId;
+  private final AndroidCommandLineOptions cliOptions;
+  private final boolean installViaSd = false;
+  private final Logger logger;
+  private final AdbHelper adbHelper;
+  private final InstallState state;
+
+  public AndroidInstall(
+      Logger logger,
+      AbsPath rootPath,
+      AndroidCommandLineOptions cliOptions,
+      IsolatedApkInfo apkInfo,
+      Optional<IsolatedExopackageInfo> exopackageInfo,
+      InstallId installId,
+      InstallState state,
+      AdbHelper adbHelper) {
+    this.logger = logger;
+    this.rootPath = rootPath;
+    this.apkInfo = apkInfo;
+    this.exopackageInfo = exopackageInfo;
+    this.installId = installId;
+    this.cliOptions = cliOptions;
+    this.state = state;
+    this.adbHelper = adbHelper;
+  }
+
+  /** Uses AdbHelper to do actual install with APK */
+  public synchronized InstallResult installApk() {
+    List<Map<String, String>> deviceInfos = new ArrayList();
+    try {
+      if (cliOptions.cleanUp) {
+        adbHelper.uninstallApp(state.packageName(), cliOptions.keepUserData);
+      } else {
+        if (cliOptions.uninstallFirst) {
+          adbHelper.uninstallApp(state.packageName(), cliOptions.keepUserData);
+        }
+        logger.info(String.format("Attempting install of %s", apkInfo.getApkPath()));
+        Instant start = Instant.now();
+        // Everything from here on is device work, including probing it for its properties.
+        long deviceWorkStart = System.currentTimeMillis();
+
+        boolean isExopackage = exopackageInfo.map(ExopackageInstaller::isExopackage).orElse(false);
+        Set<AndroidDeviceInfo> androidDeviceInfos = adbHelper.getAndroidDeviceInfo(apkInfo);
+        for (AndroidDeviceInfo deviceInfo : androidDeviceInfos) {
+          Map<String, String> infoMap = new LinkedHashMap<>();
+          infoMap.put("sdk", deviceInfo.getSdk());
+          infoMap.put("abi", deviceInfo.getAbi());
+          infoMap.put("locale", deviceInfo.getLocale());
+          infoMap.put("build_fingerprint", deviceInfo.getBuildFingerprint());
+          infoMap.put("is_emulator", deviceInfo.isEmulator() ? "1" : "0");
+          infoMap.put("density", deviceInfo.getDensity().toString());
+          infoMap.put("transport", deviceInfo.getTransport());
+          // With the device fields rather than the timings below, so that it is still reported
+          // when an install fails before any timing is complete.
+          infoMap.put("is_exopackage", isExopackage ? "1" : "0");
+          deviceInfos.add(infoMap);
+        }
+        for (AndroidDeviceInfo deviceInfo : androidDeviceInfos) {
+          adbHelper.throwIfIncompatibleAbi(deviceInfo, apkInfo);
+        }
+
+        adbHelper.installApk(
+            apkInfo,
+            exopackageInfo,
+            rootPath,
+            installViaSd,
+            /* quiet= */ false,
+            installId.getValue(),
+            state.packageName());
+        state.metrics().recordDeviceWork(deviceWorkStart, System.currentTimeMillis());
+
+        // Only now are the stage timings complete, so the metrics cannot be gathered any earlier.
+        Map<String, String> installMetrics =
+            state.metrics().summarise(System.currentTimeMillis(), state.artifacts().arrivals());
+        deviceInfos.forEach(infoMap -> infoMap.putAll(installMetrics));
+        Instant completedAt = Instant.now();
+        logger.info(
+            formatCompletionMessage(
+                apkInfo.getApkPath().getFileName().toString(),
+                start,
+                completedAt,
+                ZoneId.systemDefault()));
+
+        String packageName = state.packageName();
+
+        // Determine if app links should be enabled based on command line option or allowlist
+        boolean shouldEnableAppLinks = false;
+        if (cliOptions.enableAppLinks != null) {
+          // Explicit option provided by user
+          shouldEnableAppLinks = cliOptions.enableAppLinks;
+        } else {
+          // No option provided, check allowlist
+          shouldEnableAppLinks = ENABLE_APP_LINKS_ALLOWLIST.contains(packageName);
+        }
+
+        if (shouldEnableAppLinks) {
+          try {
+            adbHelper.adbCall(
+                "enable app links",
+                (device) -> {
+                  device.enableAppLinks(packageName);
+                  return true;
+                },
+                true);
+          } catch (Exception e) {
+            logger.warning("Failed to enable app links: " + e.getMessage());
+          }
+        }
+
+        if (cliOptions.run || cliOptions.activity != null || cliOptions.intentUri != null) {
+          adbHelper.startActivityForIsolatedApk(
+              apkInfo,
+              installId.getValue(),
+              cliOptions.activity,
+              cliOptions.intentUri,
+              cliOptions.waitForDebugger,
+              cliOptions.skipSetDebugApp);
+        }
+      }
+      return new InstallResult(deviceInfos, Optional.empty());
+    } catch (AndroidInstallException exc) {
+      return new InstallResult(deviceInfos, Optional.of(exc.getInstallError()));
+    } catch (Exception err) {
+      String errMsg = err.getMessage();
+      logger.log(
+          Level.SEVERE,
+          String.format("Error while installing %s. Error message: %s", installId, errMsg),
+          err);
+      return new InstallResult(
+          deviceInfos,
+          Optional.of(errMsg).map(AndroidInstallErrorClassifier.INSTANCE::fromErrorMessage));
+    }
+  }
+
+  static String formatCompletionMessage(
+      String apkName, Instant start, Instant completedAt, ZoneId zoneId) {
+    return String.format(
+        "Install of %s finished in %d seconds at %s",
+        apkName,
+        Duration.between(start, completedAt).getSeconds(),
+        INSTALL_COMPLETION_TIME_FORMAT.withZone(zoneId).format(completedAt));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallApkOptions.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallApkOptions.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallApkOptions.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.facebook.buck.util.environment.EnvVariablesProvider;
+import com.facebook.buck.util.environment.Platform;
+import com.facebook.buck.util.json.ObjectMappers;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.type.TypeReference;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Map;
+import java.util.Optional;
+import java.util.TreeMap;
+import java.util.logging.Logger;
+
+/**
+ * Constructs configurations for an android install that are set in install_android_options.json and
+ * sent to the AndroidInstaller
+ */
+public class AndroidInstallApkOptions {
+  private static final Logger LOG = Logger.getLogger(AndroidInstallApkOptions.class.getName());
+  public final String adbExecutable;
+  public final boolean restartAdbOnFailure;
+  public final boolean stagedInstallMode;
+  public final boolean apexMode;
+
+  AndroidInstallApkOptions(Path jsonArtifactPath, String adbExecutablePath)
+      throws RuntimeException, IOException {
+    JsonParser parser = ObjectMappers.createParser(jsonArtifactPath);
+    Map<String, String> jsonData =
+        parser.readValueAs(new TypeReference<TreeMap<String, String>>() {});
+    this.adbExecutable = getAdbExecutable(adbExecutablePath, jsonData);
+    this.restartAdbOnFailure = readBoolean(jsonData, "adb_restart_on_failure");
+    this.stagedInstallMode = readBoolean(jsonData, "staged_install_mode");
+    this.apexMode = readBoolean(jsonData, "apex_mode");
+  }
+
+  private boolean readBoolean(Map<String, String> jsonData, String name) {
+    return Boolean.parseBoolean(jsonData.getOrDefault(name, Boolean.FALSE.toString()));
+  }
+
+  private int readInt(Map<String, String> jsonData, String name, int defaultValue) {
+    String readValue = jsonData.getOrDefault(name, "");
+    if (readValue.isEmpty()) {
+      return defaultValue;
+    }
+    return Integer.parseInt(readValue);
+  }
+
+  /*
+   * Here is the order of precedence for adb_executable:
+   * 1. --adb-executable-path from command line option
+   * 2. adb_executable from json artifact
+   * 3. adb from PATH
+   * 4. /opt/android_sdk/platform-tools/adb
+   */
+  private String getAdbExecutable(String adbExecutablePath, Map<String, String> jsonData) {
+    String adbExecutable =
+        Optional.ofNullable(adbExecutablePath)
+            .orElse(
+                Optional.ofNullable(jsonData.get("adb_executable"))
+                    .orElse(getAdbFromPath().orElse("/opt/android_sdk/platform-tools/adb")));
+    LOG.info("adbExecutable: " + adbExecutable);
+    return adbExecutable;
+  }
+
+  private Optional<String> getAdbFromPath() {
+    String path = EnvVariablesProvider.getSystemEnv().get("PATH");
+    if (path != null) {
+      String binaryExtension = Platform.detect() == Platform.WINDOWS ? ".exe" : "";
+      String adbBinary = "adb" + binaryExtension;
+      for (String pathEntry : path.split(File.pathSeparator)) {
+        Path entry = Paths.get(pathEntry);
+        Path adb = entry.resolve(adbBinary);
+        if (adb.toFile().exists()) {
+          return Optional.of(adb.toString());
+        }
+      }
+    }
+    return Optional.empty();
+  }
+
+  @Override
+  public String toString() {
+    return "AndroidInstallApkOptions{"
+        + "adbExecutable='"
+        + adbExecutable
+        + '\''
+        + ", restartAdbOnFailure="
+        + restartAdbOnFailure
+        + ", stagedInstallMode="
+        + stagedInstallMode
+        + ", apexMode="
+        + apexMode
+        + '}';
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallErrorClassifier.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallErrorClassifier.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallErrorClassifier.kt
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android
+
+import com.facebook.buck.installer.InstallError
+
+object AndroidInstallErrorClassifier {
+  fun fromErrorMessage(input: String): InstallError {
+    if (isInsufficientStorageFailure(input)) {
+      return createInstallError(
+          AndroidInstallErrorTag.NO_SPACE_LEFT_ON_DEVICE,
+          "No space left on device. Free up space on the device and try again.",
+      )
+    }
+    for ((pattern, handler) in errorPatterns) {
+      if (input.contains(pattern)) {
+        return handler(input)
+      }
+    }
+    return InstallError(input, AndroidInstallErrorTag.OTHER_INFRA)
+  }
+
+  private val errorPatterns = listOf<Pair<String, (String) -> InstallError>>(
+      "stderr message: " to this::decorateStdErrMessages,
+  )
+
+  private fun decorateStdErrMessages(input: String): InstallError {
+    val message = input.substringAfter("stderr message: ")
+    return when {
+      message.contains("Could not find `adb` in PATH") ->
+          createInstallError(AndroidInstallErrorTag.ADB_NOT_FOUND, message)
+      message.contains("Failed to connect to adb.") ->
+          createInstallError(AndroidInstallErrorTag.FAILED_TO_CONNECT_TO_ADB, message)
+      message.contains("Didn't find any attached Android devices/emulators.") ->
+          createInstallError(AndroidInstallErrorTag.DEVICE_NOT_FOUND, message)
+      message.contains("devices match specified device filter") ->
+          createInstallError(AndroidInstallErrorTag.MULTIPLE_DEVICES_MATCH_FILTER, message)
+      Regex("You are trying to install .* onto a device with the following CPU")
+          .containsMatchIn(message) ->
+          createInstallError(AndroidInstallErrorTag.INCOMPATIBLE_ABI, message)
+      Regex("You are trying to install an APK with incompatible native libraries")
+          .containsMatchIn(message) ->
+          createInstallError(AndroidInstallErrorTag.INCOMPATIBLE_NATIVE_LIB, message)
+      else -> createInstallError(AndroidInstallErrorTag.OTHER_INFRA, message)
+    }
+  }
+
+  private fun createInstallError(tag: AndroidInstallErrorTag, msg: String): InstallError {
+    return InstallError(msg, tag)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallErrorTag.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallErrorTag.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallErrorTag.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android
+
+import com.facebook.buck.installer.InstallErrorCategory
+import com.facebook.buck.installer.InstallErrorCategory.ENVIRONMENT
+import com.facebook.buck.installer.InstallErrorCategory.INFRA
+import com.facebook.buck.installer.InstallErrorCategory.USER
+import com.facebook.buck.installer.InstallErrorTag
+
+enum class AndroidInstallErrorTag(val category: InstallErrorCategory) : InstallErrorTag {
+  ERROR_MATERIALIZING_ARTIFACT(INFRA),
+  OTHER_INFRA(INFRA),
+  ADB_PROTOCOL_VERSION_MISMATCH(ENVIRONMENT),
+  ADB_NOT_FOUND(ENVIRONMENT),
+  FAILED_TO_CONNECT_TO_ADB(ENVIRONMENT),
+  TEMP_FOLDER_NOT_WRITABLE(USER),
+  ADB_COMMAND_REJECTED(USER),
+  ADB_COMMAND_FAILED(USER),
+  ADB_CONNECTION_RESET_BY_PEER(USER),
+  ADB_CONNECTION_TIMED_OUT(USER),
+  NO_ATTACHED_DEVICE(USER),
+  MULTIPLE_DEVICES_MATCH_FILTER(USER),
+  DEVICE_NOT_FOUND(USER),
+  DEVICE_OFFLINE(USER),
+  NO_SPACE_LEFT_ON_DEVICE(USER),
+  REQUIRE_NEWER_SDK(USER),
+  INCOMPATIBLE_NATIVE_LIB(USER),
+  INCOMPATIBLE_ABI(USER),
+  UPDATE_INCOMPATIBLE(USER),
+  MISSING_SHARED_LIBRARY(USER),
+  VERIFICATION_FAILED(USER),
+  INSTALLED_APK_MISMATCH(USER),
+  INVALID_APK(USER),
+  INSTALL_CANCELLED_BY_USER(USER),
+  UNKNOWN_DEVICE_ABI(USER),
+  MANUAL_REBOOT_REQUIRED(USER),
+  EXOPACKAGE_GARBAGE_COLLECTION_FAILED(USER);
+
+  override fun getErrorCategory(): InstallErrorCategory {
+    return category
+  }
+
+  override fun getName(): String {
+    return name
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallException.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallException.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallException.kt
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android
+
+import com.facebook.buck.core.util.log.Logger
+import com.facebook.buck.installer.InstallError
+
+private const val INSUFFICIENT_STORAGE_ERROR = "INSTALL_FAILED_INSUFFICIENT_STORAGE"
+private const val NO_SPACE_LEFT_ON_DEVICE_ERROR = "No space left on device"
+private const val KILOBYTE = 1024L
+private const val MEGABYTE = 1024L * KILOBYTE
+
+/** At a scale that does not round an amount worth reporting down to zero. */
+private fun describeBytes(bytes: Long): String =
+    when {
+      bytes >= MEGABYTE -> "${bytes / MEGABYTE}MB"
+      bytes >= KILOBYTE -> "${bytes / KILOBYTE}KB"
+      else -> "${bytes}B"
+    }
+
+internal fun isInsufficientStorageFailure(message: String): Boolean =
+    message.contains(INSUFFICIENT_STORAGE_ERROR) || message.contains(NO_SPACE_LEFT_ON_DEVICE_ERROR)
+
+class AndroidInstallException(val installError: InstallError) :
+    RuntimeException(installError.message) {
+  init {
+    LOG.error(installError.message)
+  }
+
+  companion object {
+    private val LOG: Logger = Logger.get(AndroidInstallException::class.java.name)
+
+    fun rebootRequired(msg: String) =
+        AndroidInstallException(InstallError(msg, AndroidInstallErrorTag.MANUAL_REBOOT_REQUIRED))
+
+    fun tempFolderNotWritable(): AndroidInstallException = AndroidInstallException(
+        InstallError(
+            "Temp folder is not writable.",
+            AndroidInstallErrorTag.TEMP_FOLDER_NOT_WRITABLE,
+        ),
+    )
+
+    fun operationNotSupported(operation: String): AndroidInstallException = AndroidInstallException(
+        InstallError(
+            "Operation $operation is not supported.",
+            AndroidInstallErrorTag.OTHER_INFRA,
+        ),
+    )
+
+    fun deviceAbiUnknown() = AndroidInstallException(
+        InstallError("Device ABI is unknown.", AndroidInstallErrorTag.UNKNOWN_DEVICE_ABI),
+    )
+
+    fun insufficientStorage(requiredBytes: Long, availableBytes: Long) = AndroidInstallException(
+        InstallError(
+            "Not enough space on device: the exopackage files for this build need " +
+                "${describeBytes(requiredBytes)} but only ${describeBytes(availableBytes)} is " +
+                "free " +
+                "under /data. Free some space, or run `adb uninstall` on apps you no longer " +
+                "need -- their exopackage files under /data/local/tmp/exopackage are only " +
+                "reclaimed by installing them again.",
+            AndroidInstallErrorTag.NO_SPACE_LEFT_ON_DEVICE,
+        ),
+    )
+
+    fun exopackageGarbageCollectionFailed(message: String?) = AndroidInstallException(
+        InstallError(
+            "Failed to delete stale exopackage files, aborting before pushing new ones. " +
+                "Continuing would leak several GB per install and eventually fill the device." +
+                (message?.let { "\n$it" } ?: ""),
+            AndroidInstallErrorTag.EXOPACKAGE_GARBAGE_COLLECTION_FAILED,
+        ),
+    )
+
+    fun artifactMissing(path: String) = AndroidInstallException(
+        InstallError(
+            "Exopackage artifact is missing from the build output: $path",
+            AndroidInstallErrorTag.ERROR_MATERIALIZING_ARTIFACT,
+        ),
+    )
+
+    fun devicesDeparted(serials: Collection<String>) = AndroidInstallException(
+        InstallError(
+            "Device(s) disconnected while the build was running, so the install could not " +
+                "reach them: ${serials.sorted().joinToString(", ")}",
+            AndroidInstallErrorTag.DEVICE_NOT_FOUND,
+        ),
+    )
+
+    fun adbPathNotFound() = AndroidInstallException(
+        InstallError("Adb path not found.", AndroidInstallErrorTag.ADB_NOT_FOUND),
+    )
+
+    fun installedApkMismatch(message: String) = AndroidInstallException(
+        InstallError(message, AndroidInstallErrorTag.INSTALLED_APK_MISMATCH),
+    )
+
+    fun adbCommandFailedException(
+        message: String,
+        exceptionMessage: String?,
+    ): AndroidInstallException {
+      val errorMessage = exceptionMessage?.let { "\n" + it } ?: ""
+      val fullMessage = "$message.$errorMessage"
+      val tag =
+          if (isInsufficientStorageFailure(fullMessage)) {
+            AndroidInstallErrorTag.NO_SPACE_LEFT_ON_DEVICE
+          } else {
+            AndroidInstallErrorTag.ADB_COMMAND_FAILED
+          }
+      return AndroidInstallException(InstallError(fullMessage, tag))
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallerMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallerMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallerMain.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.facebook.buck.installer.InstallerServer;
+import java.io.IOException;
+import java.util.logging.FileHandler;
+import java.util.logging.Level;
+import java.util.logging.Logger; // NOPMD
+import java.util.logging.SimpleFormatter;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+
+/**
+ * Main entry point for executing {@code Installs for buck2 android}.
+ *
+ * <p>Expected usage: {@code this_binary options}.
+ */
+public class AndroidInstallerMain {
+  static {
+    // set java.util.logging (JUL) simple formatter to 1 liner.
+    System.setProperty(
+        "java.util.logging.SimpleFormatter.format",
+        "[%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS] [%4$s] %3$s - %5$s%6$s%n");
+  }
+
+  /** Main Entry Point */
+  public static void main(String[] args) throws IOException, InterruptedException {
+    AndroidInstallerMain installer = new AndroidInstallerMain();
+    AndroidCommandLineOptions options = new AndroidCommandLineOptions();
+    CmdLineParser parser = new CmdLineParser(options);
+    try {
+      parser.parseArgument(args);
+      Logger.getLogger("").addHandler(getFileHandler(options.getLogPath()));
+      Logger logger = getLogger();
+      installer.run(options);
+      logger.info("server shutdown, exiting");
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.out.println(e.getMessage());
+      parser.printUsage(System.out);
+      System.exit(1);
+    }
+  }
+
+  private static Logger getLogger() throws IOException {
+    return Logger.getLogger(AndroidInstallerMain.class.getName());
+  }
+
+  private static FileHandler getFileHandler(String logPath) throws IOException {
+    FileHandler fileHandler = new FileHandler(logPath);
+    fileHandler.setFormatter(new SimpleFormatter());
+    fileHandler.setLevel(Level.INFO);
+    return fileHandler;
+  }
+
+  private void run(AndroidCommandLineOptions options) throws IOException, InterruptedException {
+    AndroidInstallerManager androidInstallerManager = new AndroidInstallerManager(options);
+    InstallerServer server =
+        new InstallerServer(
+            androidInstallerManager, options.getTcpPort(), options.getInstallTimeoutSeconds());
+    server.run();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallerManager.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallerManager.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/AndroidInstallerManager.java
@@ -0,0 +1,513 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.facebook.buck.android.AdbHelper;
+import com.facebook.buck.android.IsolatedApkInfo;
+import com.facebook.buck.android.exopackage.IsolatedExopackageInfo;
+import com.facebook.buck.android.exopackage.SetDebugAppMode;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.installer.InstallCommand;
+import com.facebook.buck.installer.InstallError;
+import com.facebook.buck.installer.InstallId;
+import com.facebook.buck.installer.InstallResult;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.logging.Level;
+import java.util.logging.Logger; // NOPMD
+
+/**
+ * Coordinates an Android Install of an APK. We need three artifacts: the apk,
+ * install_android_options.json (configuration options), and an AndroidManifest.xml
+ */
+class AndroidInstallerManager implements InstallCommand {
+
+  private static final Logger LOG = Logger.getLogger(AndroidInstallerManager.class.getName());
+  private final AndroidCommandLineOptions options;
+  private final AndroidInstallErrorClassifier errorClassifier =
+      AndroidInstallErrorClassifier.INSTANCE;
+  private final Map<InstallId, InstallState> installs = new ConcurrentHashMap<>();
+
+  private static final AbsPath ROOT_PATH = AbsPath.of(Paths.get(".").normalize().toAbsolutePath());
+
+  private static final ExecutorService STREAM_EXECUTOR =
+      Executors.newCachedThreadPool(
+          new ThreadFactoryBuilder().setNameFormat("exopackage-stream-%d").setDaemon(true).build());
+
+  private static final ImmutableMap<String, String> SHORT_TO_FULL_ABI_MAP =
+      ImmutableMap.of(
+          "armv7", "armeabi-v7a", "arm64", "arm64-v8a", "x86", "x86", "x86_64", "x86_64");
+
+  AndroidInstallerManager(AndroidCommandLineOptions options) {
+    this.options = options;
+  }
+
+  @Override
+  public String name() {
+    return "android";
+  }
+
+  /**
+   * Coordinates the install artifacts needed for an install. The install_android_options.json is
+   * parsed into a AndroidInstallApkOptions and the manifest is later set in the apkInstallOptions
+   * as a separate field.
+   */
+  @Override
+  public InstallResult fileReady(String artifactName, Path artifactPath, InstallId installId) {
+    try {
+      AndroidArtifacts androidArtifacts = installState(installId).artifacts();
+      long arrivedAt = System.currentTimeMillis();
+
+      // Path before arrival: an artifact counted as arrived while its path is still unset reads as
+      // usable to anyone judging readiness from arrivals. Delivery is all this records -- what the
+      // install then makes of the artifact is not the artifact's business.
+      recordArtifactPath(installState(installId), artifactName, artifactPath);
+      androidArtifacts.recordFileArrival(artifactName, arrivedAt);
+
+      if (artifactName.equals("options")) {
+        resolveDevices(installId, androidArtifacts);
+      }
+      Optional<InstallError> incompatible = checkAbiCompatibility(installId);
+      if (incompatible.isPresent()) {
+        return InstallResult.error(incompatible.get());
+      }
+      maybeStreamReadyPayloads(installId, androidArtifacts);
+      return InstallResult.success();
+    } catch (Exception err) {
+      String errMsg = Throwables.getStackTraceAsString(err);
+      LOG.log(
+          Level.SEVERE,
+          String.format(
+              "Error installing %s from %s due to %s", artifactName, artifactPath, errMsg),
+          err);
+      return InstallResult.error(errorClassifier.fromErrorMessage(errMsg));
+    }
+  }
+
+  @Override
+  public void onInstallStarted(InstallId installId, Set<String> expectedArtifacts) {
+    installState(installId).artifacts().setExpectedArtifacts(expectedArtifacts);
+  }
+
+  /**
+   * Records an artifact as it arrives. The install_android_options.json is parsed into an
+   * AndroidInstallApkOptions and the manifest is later set in the apkInstallOptions as a separate
+   * field.
+   */
+  private void recordArtifactPath(
+      InstallState installState, String artifactName, Path artifactPath) {
+    AndroidArtifacts androidArtifacts = installState.artifacts();
+    switch (artifactName) {
+      case "cpu_filters":
+        androidArtifacts.setApkAbis(readApkAbis(artifactPath));
+        break;
+      case "options":
+        try {
+          androidArtifacts.setApkOptions(
+              new AndroidInstallApkOptions(artifactPath, options.adbExecutablePath));
+        } catch (IOException e) {
+          // Surfaces as an install failure: InstallerService turns this into an error response.
+          throw new UncheckedIOException("Could not read install options " + artifactPath, e);
+        }
+        LOG.log(Level.INFO, androidArtifacts.getApkOptions().toString());
+        break;
+      case "manifest":
+        androidArtifacts.setAndroidManifestPath(AbsPath.of(artifactPath));
+        // Read now rather than when a later stage wants it: a manifest that cannot be parsed names
+        // no package, and no part of the install can proceed without one.
+        installState.setPackageName(AdbHelper.tryToExtractPackageNameFromManifest(artifactPath));
+        break;
+      case "secondary_dex_exopackage_info_directory":
+        androidArtifacts.setSecondaryDexExopackageInfoDirectory(
+            Optional.of(AbsPath.of(artifactPath)));
+        break;
+      case "secondary_dex_exopackage_info_metadata":
+        androidArtifacts.setSecondaryDexExopackageInfoMetadata(
+            Optional.of(AbsPath.of(artifactPath)));
+        break;
+      case "native_library_exopackage_info_directory":
+        androidArtifacts.setNativeLibraryExopackageInfoDirectory(
+            Optional.of(AbsPath.of(artifactPath)));
+        break;
+      case "native_library_exopackage_info_metadata":
+        androidArtifacts.setNativeLibraryExopackageInfoMetadata(
+            Optional.of(AbsPath.of(artifactPath)));
+        break;
+      case "resources_exopackage_assets":
+        androidArtifacts.setResourcesExopackageInfoAssets(Optional.of(AbsPath.of(artifactPath)));
+        break;
+      case "resources_exopackage_assets_hash":
+        androidArtifacts.setResourcesExopackageInfoAssetsHash(
+            Optional.of(AbsPath.of(artifactPath)));
+        break;
+      case "resources_exopackage_res":
+        androidArtifacts.setResourcesExopackageInfoRes(Optional.of(AbsPath.of(artifactPath)));
+        break;
+      case "resources_exopackage_res_hash":
+        androidArtifacts.setResourcesExopackageInfoResHash(Optional.of(AbsPath.of(artifactPath)));
+        break;
+      default:
+        androidArtifacts.setApk(AbsPath.of(artifactPath));
+        break;
+    }
+  }
+
+  @Override
+  public InstallResult allFilesReady(InstallId installId) {
+    try {
+      AndroidArtifacts androidArtifacts = installState(installId).artifacts();
+
+      // Before anything else, and before any path can return: a push cannot be stopped once it has
+      // started, so the install waits it out rather than leaving one writing into the directories
+      // it is about to write itself.
+      installState(installId).streamedPushes().sealAndAwait();
+
+      ImmutableSet<String> undelivered = androidArtifacts.undeliveredArtifacts();
+      if (!undelivered.isEmpty()) {
+        LOG.log(
+            Level.WARNING,
+            String.format(
+                "Install %s: buck declared these artifacts and never sent them, so their payload"
+                    + " never counted as complete and was pushed by the install rather than"
+                    + " ahead of it: %s",
+                installId.getValue(), undelivered));
+      }
+
+      String adbPath = androidArtifacts.getApkOptions().adbExecutable;
+      if (!Files.exists(Paths.get(adbPath))) {
+        return InstallResult.error(
+            errorClassifier.fromErrorMessage(
+                String.format(
+                    "Could not find `adb` in PATH, and could not find `adb` "
+                        + "at %s. Please add `adb` to your PATH",
+                    adbPath)));
+      }
+
+      AdbHelper adbHelper = resolveDevices(installId, androidArtifacts);
+      ImmutableSet<String> departed = adbHelper.departedSerials();
+      if (!departed.isEmpty()) {
+        return InstallResult.error(
+            AndroidInstallException.Companion.devicesDeparted(departed).getInstallError());
+      }
+
+      Optional<IsolatedExopackageInfo> isolatedExopackageInfo =
+          buildExopackageInfo(androidArtifacts, AndroidArtifacts.ArtifactClass.EXOPACKAGE_PAYLOADS);
+
+      AndroidInstall androidInstaller =
+          new AndroidInstall(
+              LOG,
+              ROOT_PATH,
+              options,
+              IsolatedApkInfo.of(
+                  androidArtifacts.getAndroidManifestPath(), androidArtifacts.getApk()),
+              isolatedExopackageInfo,
+              installId,
+              installState(installId),
+              adbHelper);
+      return androidInstaller.installApk();
+
+    } catch (Exception err) {
+      String errMsg = Throwables.getStackTraceAsString(err);
+      LOG.log(Level.SEVERE, String.format("Install error due to %s", errMsg), err);
+      return InstallResult.error(errorClassifier.fromErrorMessage(errMsg));
+    }
+  }
+
+  /**
+   * Starts pushing exopackage payloads as soon as they are complete, rather than waiting for the
+   * apk.
+   *
+   * <p>Payloads finish at different points in the build, so the device would otherwise sit idle
+   * until the last of them. Readiness is judged per payload, so one that finishes early does not
+   * wait behind one that finishes late; payloads that are ready together go in a single push, which
+   * pays for the device setup once rather than once each.
+   */
+  private void maybeStreamReadyPayloads(InstallId installId, AndroidArtifacts androidArtifacts) {
+    if (options.cleanUp) {
+      // This install only uninstalls, so nothing it sends would ever be read -- and the payload
+      // would outlive the app it belongs to.
+      return;
+    }
+    // Check if it is too early to start streaming.
+    AdbHelper adbHelper = installState(installId).adbHelper();
+    if (androidArtifacts.getAndroidManifestPath() == null || adbHelper == null) {
+      // No package name, or no devices to reach yet. Before anything is claimed, because a claim
+      // is permanent: claiming a payload that cannot be sent leaves it to the install to push.
+      return;
+    }
+    // Check if it is too late to start streaming.
+    if (androidArtifacts.allArtifactsArrived()) {
+      // Nothing left to wait for, so there is no idle device time to fill.
+      return;
+    }
+    Set<AndroidArtifacts.ArtifactClass> ready =
+        AndroidArtifacts.ArtifactClass.EXOPACKAGE_PAYLOADS.stream()
+            .filter(androidArtifacts::hasAllArtifactsFor)
+            .collect(ImmutableSet.toImmutableSet());
+    installState(installId)
+        .streamedPushes()
+        .dispatch(
+            ready,
+            pending ->
+                STREAM_EXECUTOR.submit(
+                    () -> streamPayloads(installState(installId), adbHelper, pending)));
+  }
+
+  private void streamPayloads(
+      InstallState state, AdbHelper adbHelper, Set<AndroidArtifacts.ArtifactClass> payloads) {
+    try {
+      Optional<IsolatedExopackageInfo> exopackageInfo =
+          buildExopackageInfo(state.artifacts(), payloads);
+      if (exopackageInfo.isEmpty()) {
+        return;
+      }
+      // Read here rather than where the push is dispatched: an unreadable manifest is this
+      // method's problem to swallow, not a reason to fail the artifact that triggered it.
+      String packageName = state.packageName();
+      if (packageName == null) {
+        LOG.log(Level.WARNING, "No package name in the manifest; leaving the payloads to install");
+        return;
+      }
+      // The devices the install itself will use, so a payload never streams somewhere the install
+      // is not going. Counted like any other push: whatever lands here the install then finds
+      // already present, so no payload is recorded twice.
+      adbHelper.streamExopackagePayloads(ROOT_PATH, exopackageInfo.get(), packageName);
+    } catch (InterruptedException e) {
+      // Only reachable through adbCall's signature; nothing interrupts these threads. Rethrown so
+      // the future carries the failure rather than reporting a push that did not happen.
+      LOG.log(Level.WARNING, String.format("Streaming %s was interrupted", payloads), e);
+      throw new RuntimeException(e);
+    } catch (Exception e) {
+      // Best effort. Whatever did not make it is pushed by the install, which lists the directory
+      // and so sees exactly what is missing.
+      LOG.log(
+          Level.WARNING,
+          String.format("Could not stream %s; the install will push instead", payloads),
+          e);
+    }
+  }
+
+  /**
+   * Assembles the payloads named in {@code payloads} from the artifacts that have arrived.
+   *
+   * <p>A payload left out is reported absent rather than empty, so the caller pushes only what it
+   * asked for. Only payloads known to be complete may be named: a half-delivered one fails the
+   * pairing checks below.
+   */
+  @VisibleForTesting
+  static Optional<IsolatedExopackageInfo> buildExopackageInfo(
+      AndroidArtifacts androidArtifacts, Set<AndroidArtifacts.ArtifactClass> payloads) {
+    boolean includeSecondaryDex = payloads.contains(AndroidArtifacts.ArtifactClass.SECONDARY_DEX);
+    boolean includeNativeLibrary = payloads.contains(AndroidArtifacts.ArtifactClass.NATIVE_LIBRARY);
+    boolean includeResources = payloads.contains(AndroidArtifacts.ArtifactClass.RESOURCES);
+    Optional<AbsPath> secondaryDexExopackageInfoDirectory =
+        includeSecondaryDex
+            ? androidArtifacts.getSecondaryDexExopackageInfoDirectory()
+            : Optional.empty();
+    Optional<AbsPath> secondaryDexExopackageInfoMetadata =
+        includeSecondaryDex
+            ? androidArtifacts.getSecondaryDexExopackageInfoMetadata()
+            : Optional.empty();
+    Optional<AbsPath> nativeLibraryExopackageInfoDirectory =
+        includeNativeLibrary
+            ? androidArtifacts.getNativeLibraryExopackageInfoDirectory()
+            : Optional.empty();
+    Optional<AbsPath> nativeLibraryExopackageInfoMetadata =
+        includeNativeLibrary
+            ? androidArtifacts.getNativeLibraryExopackageInfoMetadata()
+            : Optional.empty();
+    ImmutableList.Builder<IsolatedExopackageInfo.IsolatedExopackagePathAndHash> pathAndHashBuilder =
+        ImmutableList.builder();
+    if (includeResources) {
+      // Assets are optional for a build, but a resource and its hash always ship together. Without
+      // this, a half-delivered pair is indistinguishable from a build that has no assets at all.
+      Preconditions.checkState(
+          androidArtifacts.getResourcesExopackageInfoAssets().isPresent()
+              == androidArtifacts.getResourcesExopackageInfoAssetsHash().isPresent(),
+          "Exopackage resource assets and their hash must be present together");
+      Preconditions.checkState(
+          androidArtifacts.getResourcesExopackageInfoRes().isPresent()
+              == androidArtifacts.getResourcesExopackageInfoResHash().isPresent(),
+          "Exopackage resources and their hash must be present together");
+      androidArtifacts
+          .getResourcesExopackageInfoAssets()
+          .ifPresent(
+              assets ->
+                  pathAndHashBuilder.add(
+                      new IsolatedExopackageInfo.IsolatedExopackagePathAndHash(
+                          assets, androidArtifacts.getResourcesExopackageInfoAssetsHash().get())));
+      androidArtifacts
+          .getResourcesExopackageInfoRes()
+          .ifPresent(
+              res ->
+                  pathAndHashBuilder.add(
+                      new IsolatedExopackageInfo.IsolatedExopackagePathAndHash(
+                          res, androidArtifacts.getResourcesExopackageInfoResHash().get())));
+    }
+    ImmutableList<IsolatedExopackageInfo.IsolatedExopackagePathAndHash> exopackageResources =
+        pathAndHashBuilder.build();
+
+    Optional<IsolatedExopackageInfo> isolatedExopackageInfo = Optional.empty();
+    if (secondaryDexExopackageInfoDirectory.isPresent()
+        || secondaryDexExopackageInfoMetadata.isPresent()
+        || nativeLibraryExopackageInfoDirectory.isPresent()
+        || nativeLibraryExopackageInfoMetadata.isPresent()
+        || !exopackageResources.isEmpty()) {
+      Preconditions.checkState(
+          secondaryDexExopackageInfoDirectory.isPresent()
+              == secondaryDexExopackageInfoMetadata.isPresent());
+      Optional<IsolatedExopackageInfo.IsolatedDexInfo> dexInfo =
+          secondaryDexExopackageInfoDirectory.map(
+              directory ->
+                  new IsolatedExopackageInfo.IsolatedDexInfo(
+                      secondaryDexExopackageInfoMetadata.get(), directory));
+
+      Preconditions.checkState(
+          nativeLibraryExopackageInfoDirectory.isPresent()
+              == nativeLibraryExopackageInfoMetadata.isPresent());
+      Optional<IsolatedExopackageInfo.IsolatedNativeLibsInfo> nativeLibsInfo =
+          nativeLibraryExopackageInfoDirectory.map(
+              absPath ->
+                  new IsolatedExopackageInfo.IsolatedNativeLibsInfo(
+                      nativeLibraryExopackageInfoMetadata.get(), absPath));
+
+      Optional<IsolatedExopackageInfo.IsolatedResourcesInfo> resourcesInfo;
+      if (!exopackageResources.isEmpty()) {
+        resourcesInfo =
+            Optional.of(new IsolatedExopackageInfo.IsolatedResourcesInfo(exopackageResources));
+      } else {
+        resourcesInfo = Optional.empty();
+      }
+
+      isolatedExopackageInfo =
+          Optional.of(new IsolatedExopackageInfo(dexInfo, nativeLibsInfo, resourcesInfo));
+    }
+    return isolatedExopackageInfo;
+  }
+
+  /**
+   * Fixes the devices this install targets, as soon as there are options to reach them with.
+   *
+   * <p>Pinned here rather than at install time so that everything the install does reaches one set
+   * of devices. A device connected after this point is not installed to; one that disconnects
+   * before the install fails it, rather than being dropped silently.
+   */
+  private AdbHelper resolveDevices(InstallId installId, AndroidArtifacts androidArtifacts) {
+    InstallState state = installState(installId);
+    // Per install, not process wide: resolution asks adb, and two installs arriving together have
+    // no reason to wait for each other.
+    return state.resolveDevices(
+        () -> {
+          AdbHelper adbHelper =
+              AdbHelperFactory.create(
+                  LOG,
+                  options,
+                  androidArtifacts.getApkOptions(),
+                  options.skipSetDebugApp ? SetDebugAppMode.SKIP : SetDebugAppMode.SET,
+                  state.metrics());
+          // Asking now is what fixes the set: the helper resolves its devices once, on
+          // first use, and answers from that for the rest of the install. Leaving it to
+          // whoever asks first would move the instant this install is pinned to.
+          ImmutableSet<String> serials =
+              adbHelper.getDevices(true).stream()
+                  .map(device -> device.getSerialNumber())
+                  .collect(ImmutableSet.toImmutableSet());
+          LOG.log(Level.INFO, "Install targets " + serials);
+          return adbHelper;
+        });
+  }
+
+  private InstallState installState(InstallId installId) {
+    return installs.computeIfAbsent(installId, ignore -> new InstallState());
+  }
+
+  /**
+   * The ABIs the apk carries native code for, from the cpu filters buck sent.
+   *
+   * <p>Empty when the filters name nothing this installer recognises, or cannot be read at all.
+   * Either way the check has nothing to compare and the install goes ahead -- an ABI we cannot
+   * determine is not treated as incompatible.
+   */
+  private static ImmutableSet<String> readApkAbis(Path cpuFiltersPath) {
+    try {
+      // A filter this installer does not know is dropped rather than carried through as null: it
+      // would never match a device ABI, and would reach the user as the word "null".
+      return Files.readAllLines(cpuFiltersPath).stream()
+          .map(abi -> SHORT_TO_FULL_ABI_MAP.get(abi.trim()))
+          .filter(Objects::nonNull)
+          .collect(ImmutableSet.toImmutableSet());
+    } catch (IOException e) {
+      LOG.log(Level.WARNING, "Could not read the apk cpu filters; skipping the ABI check", e);
+      return ImmutableSet.of();
+    }
+  }
+
+  /**
+   * Fails early when the apk has no native code the targeted devices can run.
+   *
+   * <p>Offered every arrival and answers for itself: it needs the cpu filters and the devices,
+   * which turn up in either order, and does nothing until both are there. Empty means compatible,
+   * or that no device would report an ABI -- unknown is not treated as incompatible.
+   */
+  private Optional<InstallError> checkAbiCompatibility(InstallId installId) {
+    InstallState state = installState(installId);
+    ImmutableSet<String> apkAbis = state.artifacts().getApkAbis();
+    AdbHelper adbHelper = state.adbHelper();
+    if (apkAbis == null || adbHelper == null) {
+      return Optional.empty();
+    }
+    if (apkAbis.isEmpty()) {
+      // No native code this installer recognises, so there is nothing a device could be wrong for.
+      return Optional.empty();
+    }
+    ImmutableMap<String, ImmutableSet<String>> abisByDevice = adbHelper.deviceAbisBySerial();
+    if (abisByDevice.isEmpty()) {
+      return Optional.empty();
+    }
+    // Every device, not their union: an install reaches all of them, so one that cannot run the
+    // apk fails it, and failing here is the point -- the alternative is finding out after the
+    // build.
+    ImmutableList<String> incompatible =
+        abisByDevice.entrySet().stream()
+            .filter(device -> Sets.intersection(apkAbis, device.getValue()).isEmpty())
+            .map(device -> device.getKey() + " (" + String.join(",", device.getValue()) + ")")
+            .sorted()
+            .collect(ImmutableList.toImmutableList());
+    if (incompatible.isEmpty()) {
+      return Optional.empty();
+    }
+    return Optional.of(
+        new InstallError(
+            String.format(
+                "You are trying to install an APK with native libraries built for %s, onto "
+                    + "device(s) that cannot run any of them: %s.",
+                String.join(",", apkAbis), String.join("; ", incompatible)),
+            AndroidInstallErrorTag.INCOMPATIBLE_NATIVE_LIB));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/BUCK
@@ -0,0 +1,56 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "exceptions",
+    srcs = [
+        "AndroidInstallErrorTag.kt",
+        "AndroidInstallException.kt",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/installer:installer_server",
+    ],
+)
+
+buck_kotlin_library(
+    name = "installer_android_lib",
+    srcs = glob([
+        "*.java",
+        "*.kt",
+    ]),
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android:helpers",
+        "prelude//toolchains/android/src/com/facebook/buck/android:utils_api",
+        "prelude//toolchains/android/src/com/facebook/buck/android/device:device",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/installer:installer_server",
+        "prelude//toolchains/android/src/com/facebook/buck/util:process_executor",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:environment",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/src/com/facebook/buck/util/json:json",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
+
+buck_java_binary(
+    name = "android_installer",
+    main_class = "com.facebook.buck.installer.android.AndroidInstallerMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":installer_android_lib",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/InstallMetrics.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/InstallMetrics.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/InstallMetrics.java
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.facebook.buck.android.exopackage.InstallTimings;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.EnumMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+/**
+ * How long each stage of one install took, and what that says about the time it spent waiting.
+ *
+ * <p>Written from the push threads and read once the install is over, so every member is guarded by
+ * this object's monitor. Arrival times live with the artifacts that arrived; {@link #summarise}
+ * takes them as an argument rather than tracking them twice.
+ */
+final class InstallMetrics implements InstallTimings {
+  // Stage timings, written from the push threads and read once the install is over.
+  // Every shard's window, per push group. Kept separately rather than spanned: shards of a group
+  // overlap each other and queue behind other groups, so only the union of these is time the group
+  // was actually transferring.
+  private final Map<String, List<long[]>> pushWindows = new LinkedHashMap<>();
+  private long deviceSetupMillis;
+  private long apkInstallMillis;
+  private long deviceWorkMillis;
+  private long deviceWorkStartMillis;
+
+  @Override
+  public synchronized void recordDeviceSetup(long startMillis, long endMillis) {
+    deviceSetupMillis += endMillis - startMillis;
+  }
+
+  @Override
+  public synchronized void recordPush(String group, long startMillis, long endMillis) {
+    pushWindows
+        .computeIfAbsent(group, unused -> new ArrayList<>())
+        .add(new long[] {startMillis, endMillis});
+  }
+
+  @Override
+  public synchronized void recordApkInstall(long startMillis, long endMillis) {
+    apkInstallMillis += endMillis - startMillis;
+  }
+
+  @Override
+  public synchronized void recordDeviceWork(long startMillis, long endMillis) {
+    deviceWorkStartMillis =
+        deviceWorkStartMillis == 0L ? startMillis : Math.min(deviceWorkStartMillis, startMillis);
+    deviceWorkMillis += endMillis - startMillis;
+  }
+
+  /**
+   * How the install went, as one timeline. Every value is seconds.milliseconds, measured from the
+   * first artifact arriving.
+   *
+   * <p>Each class of artifact reports when buck finished delivering it ({@code _arrival_s}) and how
+   * long moving it to the device took ({@code _transfer_s}), in arrival order. Control artifacts
+   * are read on the host, so they never transfer.
+   *
+   * <p>{@code critical_path_s} replays this same install against these same durations, but starts
+   * each payload the moment its own artifacts were there instead of waiting for all of them. {@code
+   * potential_saving_s} is {@code total_s} minus that: time the device spent waiting for an
+   * artifact it did not yet need. Neither says anything about transferring faster, only about
+   * waiting less.
+   */
+  public synchronized Map<String, String> summarise(
+      long installCompleteMillis, Map<String, Long> fileArrivalMillis) {
+    if (fileArrivalMillis.isEmpty()) {
+      return Map.of();
+    }
+    long first = Collections.min(fileArrivalMillis.values());
+
+    Map<AndroidArtifacts.ArtifactClass, Long> readyByClass =
+        new EnumMap<>(AndroidArtifacts.ArtifactClass.class);
+    for (Map.Entry<String, Long> arrival : fileArrivalMillis.entrySet()) {
+      readyByClass.merge(
+          AndroidArtifacts.ArtifactClass.of(arrival.getKey()), arrival.getValue(), Math::max);
+    }
+    long controlReady = readyByClass.getOrDefault(AndroidArtifacts.ArtifactClass.CONTROL, first);
+    long apkReady = readyByClass.getOrDefault(AndroidArtifacts.ArtifactClass.APK, first);
+
+    // Replay: one pusher, each payload started as soon as it was available.
+    List<long[]> payloads = new ArrayList<>(); // {availableAt, durationMillis}
+    long metadataMillis = 0L;
+    for (Map.Entry<String, List<long[]>> push : pushWindows.entrySet()) {
+      long duration = unionMillis(push.getValue());
+      AndroidArtifacts.ArtifactClass pushed =
+          AndroidArtifacts.ArtifactClass.forPushGroup(push.getKey());
+      if (pushed == null) {
+        metadataMillis += duration; // metadata is derived, so it can only follow every payload
+        continue;
+      }
+      long availableAt = readyByClass.getOrDefault(pushed, controlReady);
+      payloads.add(new long[] {Math.max(availableAt, controlReady), duration});
+    }
+    payloads.sort(Comparator.comparingLong(payload -> payload[0]));
+
+    // Replay onto as many pushers as the install actually used, so the estimate tracks the
+    // implementation. With one pusher this is a queue; with several it is a list schedule.
+    long[] pushers = new long[observedConcurrency()];
+    Arrays.fill(pushers, controlReady + deviceSetupMillis);
+    for (long[] payload : payloads) {
+      int earliest = 0;
+      for (int i = 1; i < pushers.length; i++) {
+        if (pushers[i] < pushers[earliest]) {
+          earliest = i;
+        }
+      }
+      pushers[earliest] = Math.max(pushers[earliest], payload[0]) + payload[1];
+    }
+    long clock = controlReady + deviceSetupMillis;
+    for (long pusher : pushers) {
+      clock = Math.max(clock, pusher);
+    }
+    clock += metadataMillis;
+    clock = Math.max(clock, apkReady) + apkInstallMillis;
+    // Device work that is not one of the stages above still has to happen, so charge it too.
+    // Without this the replay looks faster than anything achievable and every install appears to
+    // have a saving.
+    long modelled = deviceSetupMillis + apkInstallMillis;
+    for (List<long[]> windows : pushWindows.values()) {
+      // Only the pushes the install itself made. A streamed push finished before the device phase
+      // began, so it is not part of deviceWorkMillis, and subtracting it would cancel the whole
+      // correction out for any install that streamed anything.
+      modelled +=
+          unionMillis(
+              windows.stream()
+                  .filter(window -> window[0] >= deviceWorkStartMillis)
+                  .collect(Collectors.toList()));
+    }
+    clock += Math.max(0L, deviceWorkMillis - modelled);
+
+    long total = installCompleteMillis - first;
+    long criticalPath = clock - first;
+
+    Map<String, String> metrics = new LinkedHashMap<>();
+    readyByClass.entrySet().stream()
+        .sorted(Map.Entry.comparingByValue())
+        .forEach(
+            ready -> {
+              String artifactClass = ready.getKey().metricName;
+              metrics.put(artifactClass + "_arrival_s", seconds(ready.getValue() - first));
+              metrics.put(artifactClass + "_transfer_s", seconds(transferMillis(ready.getKey())));
+            });
+    metrics.put("device_setup_s", seconds(deviceSetupMillis));
+    if (metadataMillis > 0L) {
+      metrics.put("metadata_transfer_s", seconds(metadataMillis));
+    }
+    metrics.put("critical_path_s", seconds(criticalPath));
+    metrics.put("total_s", seconds(total));
+    metrics.put("potential_saving_s", seconds(Math.max(0L, total - criticalPath)));
+    return metrics;
+  }
+
+  /** How long this class of artifact took to reach the device, or zero if it is not transferred. */
+  private long transferMillis(AndroidArtifacts.ArtifactClass artifactClass) {
+    if (artifactClass == AndroidArtifacts.ArtifactClass.APK) {
+      return apkInstallMillis;
+    }
+    for (Map.Entry<String, List<long[]>> push : pushWindows.entrySet()) {
+      if (AndroidArtifacts.ArtifactClass.forPushGroup(push.getKey()) == artifactClass) {
+        return unionMillis(push.getValue());
+      }
+    }
+    return 0L;
+  }
+
+  /**
+   * Time a group spent transferring: the union of its shards' windows. Overlapping shards count
+   * once, and a gap where every shard was queued behind another group counts for nothing -- the
+   * span between the first start and the last end would charge the group for both.
+   */
+  private static long unionMillis(List<long[]> windows) {
+    long total = 0L;
+    for (long[] window : coalesce(windows)) {
+      total += window[1] - window[0];
+    }
+    return total;
+  }
+
+  /** The windows in order, with overlapping ones fused so each instant appears once. */
+  private static List<long[]> coalesce(List<long[]> windows) {
+    List<long[]> sorted = new ArrayList<>(windows);
+    sorted.sort(Comparator.comparingLong(window -> window[0]));
+    List<long[]> fused = new ArrayList<>();
+    for (long[] window : sorted) {
+      long[] open = fused.isEmpty() ? null : fused.get(fused.size() - 1);
+      if (open != null && window[0] <= open[1]) {
+        open[1] = Math.max(open[1], window[1]);
+      } else {
+        fused.add(new long[] {window[0], window[1]});
+      }
+    }
+    return fused;
+  }
+
+  private static String seconds(long millis) {
+    return String.format(Locale.ROOT, "%.3f", millis / 1000.0);
+  }
+
+  /**
+   * How many payloads the install had in flight at once, from their observed windows. One if the
+   * pushes did not overlap.
+   */
+  private int observedConcurrency() {
+    List<long[]> edges = new ArrayList<>();
+    for (List<long[]> windows : pushWindows.values()) {
+      // Fused first: a group's own shards overlapping is not two payloads in flight.
+      for (long[] window : coalesce(windows)) {
+        if (window[1] > window[0]) {
+          edges.add(new long[] {window[0], 1L});
+          edges.add(new long[] {window[1], -1L});
+        }
+      }
+    }
+    // Ends before starts at the same instant, so touching windows are not counted as overlapping.
+    edges.sort(
+        Comparator.<long[]>comparingLong(edge -> edge[0]).thenComparingLong(edge -> edge[1]));
+    int concurrent = 0;
+    int peak = 0;
+    for (long[] edge : edges) {
+      concurrent += (int) edge[1];
+      peak = Math.max(peak, concurrent);
+    }
+    return Math.max(1, peak);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/InstallState.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/InstallState.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/InstallState.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.facebook.buck.android.AdbHelper;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+
+/**
+ * Everything one install accumulates, so that something new to track is a field here rather than
+ * another map keyed by install id.
+ */
+final class InstallState {
+  private final AndroidArtifacts artifacts = new AndroidArtifacts();
+  private final InstallMetrics metrics = new InstallMetrics();
+  private final StreamedPushes streamedPushes = new StreamedPushes();
+
+  // Written once, under this object's monitor; read without it, from the threads delivering
+  // artifacts. Those reads happen on every arrival, so they must not queue behind a resolution
+  // that is talking to adb.
+  @Nullable private volatile AdbHelper adbHelper;
+
+  // Read when the manifest arrives, because the manifest does not change during an install and
+  // several stages of one ask for the package.
+  @Nullable private volatile String packageName;
+
+  AndroidArtifacts artifacts() {
+    return artifacts;
+  }
+
+  InstallMetrics metrics() {
+    return metrics;
+  }
+
+  /** The package this install is for, or null until the manifest has arrived. */
+  @Nullable
+  String packageName() {
+    return packageName;
+  }
+
+  void setPackageName(String packageName) {
+    this.packageName = packageName;
+  }
+
+  /** What has already been sent ahead of this install, so no payload is sent twice. */
+  StreamedPushes streamedPushes() {
+    return streamedPushes;
+  }
+
+  /** Bound to the devices this install targets, or null until its options have arrived. */
+  @Nullable
+  AdbHelper adbHelper() {
+    return adbHelper;
+  }
+
+  /**
+   * Resolves the devices if they are not resolved already, and answers with them.
+   *
+   * <p>Resolution happens once however many arrivals ask for it: the answer is what pins this
+   * install to a set of devices, so a second resolution would move that instant.
+   */
+  synchronized AdbHelper resolveDevices(Supplier<AdbHelper> resolver) {
+    if (adbHelper == null) {
+      adbHelper = resolver.get();
+    }
+    return adbHelper;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/IsolatedAndroidInstallerPrinter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/IsolatedAndroidInstallerPrinter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/IsolatedAndroidInstallerPrinter.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.facebook.buck.android.AndroidInstallPrinter;
+import java.util.logging.Level;
+import java.util.logging.Logger; // NOPMD
+
+/** Handles logging for android installs */
+public class IsolatedAndroidInstallerPrinter implements AndroidInstallPrinter {
+
+  private final Logger logger;
+
+  public IsolatedAndroidInstallerPrinter(Logger logger) {
+    this.logger = logger;
+  }
+
+  @Override
+  public void printMessage(String message) {
+    logger.log(Level.INFO, message);
+  }
+
+  @Override
+  public void printSuccess(String successMessage) {
+    logger.log(Level.INFO, successMessage);
+  }
+
+  @Override
+  public void printWarning(String message) {
+    logger.log(Level.WARNING, message);
+  }
+
+  @Override
+  public void printError(String failureMessage) {
+    logger.log(Level.WARNING, failureMessage);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/StreamedPushes.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/StreamedPushes.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/android/StreamedPushes.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.android;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.function.Function;
+import java.util.logging.Level;
+import java.util.logging.Logger; // NOPMD
+
+/**
+ * The payloads sent ahead of an install, and the pushes carrying them.
+ *
+ * <p>Guards itself. Claiming a payload and recording the push that carries it have to happen
+ * together, so that pair is one method rather than a contract callers are trusted to keep, and the
+ * pushes are waited on and stopped from here rather than handed out.
+ */
+final class StreamedPushes {
+  private static final Logger LOG = Logger.getLogger(StreamedPushes.class.getName());
+
+  private final Set<AndroidArtifacts.ArtifactClass> dispatched =
+      EnumSet.noneOf(AndroidArtifacts.ArtifactClass.class);
+  private final List<Future<?>> pushes = new ArrayList<>();
+  private boolean sealed;
+
+  /**
+   * Sends whatever of {@code ready} has not gone yet, and records the push. Does nothing when
+   * everything ready has already gone, or once the install has sealed them.
+   */
+  synchronized void dispatch(
+      Set<AndroidArtifacts.ArtifactClass> ready,
+      Function<Set<AndroidArtifacts.ArtifactClass>, Future<?>> push) {
+    if (sealed) {
+      return;
+    }
+    Set<AndroidArtifacts.ArtifactClass> pending =
+        EnumSet.noneOf(AndroidArtifacts.ArtifactClass.class);
+    pending.addAll(ready);
+    pending.removeAll(dispatched);
+    if (pending.isEmpty()) {
+      return;
+    }
+    // Recorded only once the push exists: a payload marked sent with nothing carrying it would
+    // never be offered again.
+    Future<?> started = push.apply(pending);
+    dispatched.addAll(pending);
+    pushes.add(started);
+  }
+
+  /**
+   * Hands the pushes to the install and waits for them, so nothing is still writing into the
+   * directories it is about to. Sealing and waiting are one method because waiting without sealing
+   * first lets a dispatch slip in behind the wait.
+   */
+  void sealAndAwait() throws InterruptedException {
+    seal();
+    await();
+  }
+
+  private synchronized void seal() {
+    sealed = true;
+  }
+
+  /** Waits for every push to finish. A push that failed is left for the install to redo. */
+  private void await() throws InterruptedException {
+    List<Future<?>> streaming = started();
+    for (Future<?> streamed : streaming) {
+      try {
+        streamed.get();
+      } catch (InterruptedException e) {
+        // Interrupting does not stop a push: the pool hands each task straight to a thread, which
+        // then blocks on adb's monitor and inside a subprocess read, neither of which is
+        // interruptible. So the install gives up rather than pretending the device is quiet.
+        Thread.currentThread().interrupt();
+        throw e;
+      } catch (ExecutionException e) {
+        LOG.log(Level.WARNING, "A streamed push failed; the install will push instead", e);
+      }
+    }
+  }
+
+  /**
+   * The pushes so far. Copied under the monitor and used outside it: waiting on a push while
+   * holding it would block the arrivals that are still trying to dispatch.
+   */
+  private synchronized List<Future<?>> started() {
+    return List.copyOf(pushes);
+  }
+
+  @VisibleForTesting
+  synchronized int pushCount() {
+    return pushes.size();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/common/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/common/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/common/BUCK
@@ -0,0 +1,15 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "options_handler",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+    ],
+    exported_deps = ["prelude//toolchains/android/third-party:args4j"],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/common/ConsumeAllOptionsHandler.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/common/ConsumeAllOptionsHandler.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/common/ConsumeAllOptionsHandler.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.installer.common;
+
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.OptionDef;
+import org.kohsuke.args4j.spi.OptionHandler;
+import org.kohsuke.args4j.spi.Parameters;
+import org.kohsuke.args4j.spi.Setter;
+
+/** Consume all options handler for args4j library */
+public class ConsumeAllOptionsHandler extends OptionHandler<String> {
+
+  public ConsumeAllOptionsHandler(
+      CmdLineParser parser, OptionDef option, Setter<? super String> setter) {
+    super(parser, option, setter);
+  }
+
+  @Override
+  public int parseArguments(Parameters params) throws CmdLineException {
+    for (int idx = 0; idx < params.size(); idx += 1) {
+      setter.addValue(params.getParameter(idx));
+    }
+    return params.size();
+  }
+
+  @Override
+  public String getDefaultMetaVariable() {
+    return "LIST<STRING>";
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/proto/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/proto/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/proto/BUCK
@@ -0,0 +1,21 @@
+load("@prelude//toolchains/android/tools:protobuf.bzl", "protobuf_src_gen")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+protobuf_src_gen(
+    name = "installer-model",
+    srcs = [
+        "install.proto",
+    ],
+    proto_path = [],
+    deps = [
+        "prelude//toolchains/android/third-party:jakarta.annotation-api",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/third-party:protobuf",
+        "prelude//toolchains/android/third-party:remote-apis",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/proto/install.proto b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/proto/install.proto
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/installer/proto/install.proto
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+// Copied from fbcode/buck2/install_proto/install.proto
+// (https://fburl.com/code/y9zjtzvn)
+
+//----------------------------------------------
+//  Generate command
+//----------------------------------------------
+//
+// When modifying this file, please run the following generate command,
+// and include generated code in your commit
+//
+// xplat/toolchains/android/sdk/tools/protobuf/gen.py
+//
+//-----------------------
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+option java_package = "com.facebook.buck.install.model";
+option java_outer_classname = "InstallerProto";
+
+package install;
+
+service Installer {
+  rpc Install(InstallInfoRequest) returns (InstallResponse) {};
+  rpc FileReady(FileReadyRequest) returns (FileResponse) {};
+  rpc ShutdownServer(ShutdownRequest) returns (ShutdownResponse) {};
+}
+
+message InstallInfoRequest {
+  string install_id = 1;
+  reserved 2;
+  // Set of file names to expect. The actual paths are delivered later via
+  // FileReady requests.
+  repeated string file_names = 3;
+}
+
+message InstallResponse {
+  string install_id = 1;
+  // Names the installer implementation, e.g. `android`. Reported at the
+  // handshake rather than alongside a device, so an install that reaches the
+  // installer says which one ran it even when it resolves no device.
+  string installer_name = 2;
+}
+
+message FileReadyRequest {
+  string install_id = 1;
+  string name = 2;
+  string sha1 = 3;
+  string path = 4;
+}
+
+message FileResponse {
+  string install_id = 1;
+  string name = 2;
+  string path = 3;
+  ErrorDetail error_detail = 4;
+  // Connected device metadata to be logged to scuba.
+  // Should be sent once per device per install command,
+  // not per FileReadyRequest.
+  // Returned here in case the installer needs information
+  // from received files in order to connect.
+  repeated DeviceMetadata device_metadata = 5;
+}
+
+// Metadata about a connected device for logging.
+// ex. device name, os version.
+message DeviceMetadata {
+  message Entry {
+    string key = 1;
+    string value = 2;
+  }
+  repeated Entry entry = 1;
+}
+
+message ErrorDetail {
+  // Error message
+  string message = 1;
+  ErrorCategory category = 2;
+  repeated string tags = 3;
+}
+
+// Error category for installer errors.
+enum ErrorCategory {
+  ERROR_CATEGORY_UNSPECIFIED = 0;
+  // Unexpected errors in installer. AKA Infra error.
+  TIER_0 = 1;
+  // Expected errors in inputs explicitly tracked by buck. AKA User error.
+  INPUT = 2;
+  // Errors that may be triggered by issues with the host,
+  // resource limits, non-explicit dependencies or potentially
+  // ambiguous input errors.
+  // These can be tracked but not eliminated.
+  ENVIRONMENT = 3;
+}
+
+message ShutdownRequest {
+  reserved 1;
+}
+
+message ShutdownResponse {
+  reserved 1;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/BUCK
@@ -0,0 +1,28 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "file",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/src/com/facebook/buck/util:process_executor",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/io/windowsfs:windowsfs",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/FileExtensionMatcher.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/FileExtensionMatcher.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/FileExtensionMatcher.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.file;
+
+import com.facebook.buck.core.filesystems.RelPath;
+import com.google.common.io.Files;
+import java.util.Objects;
+
+/** Matcher that matches file paths with specific extension. */
+public class FileExtensionMatcher implements PathMatcher {
+
+  private final String extension;
+
+  private FileExtensionMatcher(String extension) {
+    this.extension = extension;
+  }
+
+  @Override
+  public boolean equals(Object other) {
+    if (this == other) {
+      return true;
+    }
+    if (!(other instanceof FileExtensionMatcher)) {
+      return false;
+    }
+    FileExtensionMatcher that = (FileExtensionMatcher) other;
+    return Objects.equals(extension, that.extension);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(extension);
+  }
+
+  @Override
+  public String toString() {
+    return String.format("%s extension=%s", super.toString(), extension);
+  }
+
+  @Override
+  public boolean matches(RelPath path) {
+    return extension.equals(Files.getFileExtension(path.toString()));
+  }
+
+  public String getExtension() {
+    return extension;
+  }
+
+  /**
+   * @return The matcher for paths that have {@code extension} as an extension.
+   */
+  public static FileExtensionMatcher of(String extension) {
+    return new FileExtensionMatcher(extension);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/GlobPatternMatcher.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/GlobPatternMatcher.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/GlobPatternMatcher.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.file;
+
+import com.facebook.buck.core.filesystems.RelPath;
+import java.nio.file.FileSystems;
+import java.nio.file.Path;
+import java.util.Objects;
+
+/** Matcher that matches paths described by the glob pattern. */
+public class GlobPatternMatcher implements PathMatcher {
+
+  private final String globPattern;
+  private final java.nio.file.PathMatcher globPatternMatcher;
+
+  private GlobPatternMatcher(String gloPattern, java.nio.file.PathMatcher globPatternMatcher) {
+    this.globPattern = gloPattern;
+    this.globPatternMatcher = globPatternMatcher;
+  }
+
+  @Override
+  public boolean equals(Object other) {
+    if (this == other) {
+      return true;
+    }
+    if (!(other instanceof GlobPatternMatcher)) {
+      return false;
+    }
+    GlobPatternMatcher that = (GlobPatternMatcher) other;
+    // We don't compare globPatternMatcher here, since
+    // sun.nio.fs.UnixFileSystem.getPathMatcher()
+    // returns an anonymous class which doesn't implement equals().
+    return Objects.equals(globPattern, that.globPattern);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(globPattern);
+  }
+
+  @Override
+  public String toString() {
+    return String.format("%s globPattern=%s", super.toString(), globPattern);
+  }
+
+  @Override
+  public boolean matches(RelPath path) {
+    return matches(path.getPath());
+  }
+
+  public boolean matches(Path path) {
+    return globPatternMatcher.matches(path);
+  }
+
+  /**
+   * @return The matcher for paths that start with {@code basePath}.
+   */
+  public static GlobPatternMatcher of(String globPattern) {
+    return new GlobPatternMatcher(
+        globPattern, FileSystems.getDefault().getPathMatcher("glob:" + globPattern));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MorePaths.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MorePaths.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MorePaths.java
@@ -0,0 +1,429 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.file;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.PathWrapper;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.facebook.buck.io.windowsfs.WindowsFS;
+import com.facebook.buck.util.environment.Platform;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Streams;
+import com.google.common.io.ByteSource;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.FileSystem;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+
+/** Common functions that are done with a {@link Path}. */
+public class MorePaths {
+
+  private static final boolean IS_WINDOWS = Platform.detect() == Platform.WINDOWS;
+
+  @Nullable public static final WindowsFS WIN_FS_INSTANCE = IS_WINDOWS ? new WindowsFS() : null;
+
+  /** Utility class: do not instantiate. */
+  private MorePaths() {}
+
+  public static String pathWithPlatformSeparators(String path) {
+    return pathWithPlatformSeparators(Paths.get(path));
+  }
+
+  public static String pathWithPlatformSeparators(Path path) {
+    if (IS_WINDOWS) {
+      return PathFormatter.pathWithWindowsSeparators(path);
+    } else {
+      return PathFormatter.pathWithUnixSeparators(path);
+    }
+  }
+
+  public static String pathWithPlatformSeparators(PathWrapper path) {
+    return pathWithPlatformSeparators(path.getPath());
+  }
+
+  public static Path getParentOrEmpty(Path path) {
+    Path parent = path.getParent();
+    if (parent == null) {
+      parent = emptyOf(path);
+    }
+    return parent;
+  }
+
+  public static RelPath getParentOrEmpty(RelPath path) {
+    return RelPath.of(getParentOrEmpty(path.getPath()));
+  }
+
+  public static RelPath appendSuffix(RelPath path, String suffix) {
+    return RelPath.of(getParentOrEmpty(path).resolve(path.getFileName() + suffix));
+  }
+
+  /**
+   * Get the path of a file relative to a base directory.
+   *
+   * @param path must reference a file, not a directory.
+   * @param baseDir must reference a directory that is relative to a common directory with the path.
+   *     may be null if referencing the same directory as the path.
+   * @return the relative path of path from the directory baseDir.
+   */
+  public static RelPath getRelativePath(RelPath path, @Nullable RelPath baseDir) {
+    if (baseDir == null) {
+      // This allows callers to use this method with "file.parent()" for files from the project
+      // root dir.
+      baseDir = RelPath.of(emptyOf(path.getPath()));
+    }
+    return relativize(baseDir, path);
+  }
+
+  /**
+   * Get a relative path from path1 to path2, first normalizing each path.
+   *
+   * <p>This method is a workaround for JDK-6925169 (Path.relativize returns incorrect result if
+   * path contains "." or "..").
+   */
+  public static Path relativize(Path path1, Path path2) {
+    assertSamePathType(path1, path2);
+
+    path1 = normalize(path1);
+    path2 = normalize(path2);
+
+    // On Windows, if path1 is "" then Path.relativize returns ../path2 instead of path2 or ./path2
+    if (isEmpty(path1)) {
+      return path2;
+    }
+    return path1.relativize(path2);
+  }
+
+  private static String getPathTypeString(Path path) {
+    return path.isAbsolute() ? "absolute" : "relative";
+  }
+
+  public static RelPath relativize(PathWrapper path1, PathWrapper path2) {
+    return RelPath.of(relativize(path1.getPath(), path2.getPath()));
+  }
+
+  /**
+   * Returns a child path relative to a base path. This is similar to `Path.relativize`, but
+   * supports base paths that start with "..", even in Java 11. JCL implementations of
+   * `Path.relativize` support base paths like this in Java 8, but not in Java 11.
+   *
+   * @param basePath the path against which childPath will be relativized
+   * @param childPath the path to relativize against {@code basePath}
+   * @return {@code childPath} relativized against {@code basePath}
+   */
+  public static Path relativizeWithDotDotSupport(Path basePath, Path childPath) {
+    FileSystem fileSystem = basePath.getFileSystem();
+    if (basePath.equals(childPath)) {
+      return fileSystem.getPath("");
+    }
+
+    assertSamePathType(basePath, childPath);
+
+    // Skip past equal prefixes.
+    int idx = 0;
+    while (idx < basePath.getNameCount()
+        && idx < childPath.getNameCount()
+        && basePath.getName(idx).equals(childPath.getName(idx))) {
+      idx++;
+    }
+
+    // Add ".."s to get to the root of the remainder of the base path.
+    StringBuilder result = new StringBuilder();
+    for (int i = idx; i < basePath.getNameCount(); i++) {
+      if (!basePath.getName(i).toString().isEmpty()) {
+        result.append("..");
+        result.append(File.separatorChar);
+      }
+    }
+
+    // Now add the remainder of the child path.
+    if (idx < childPath.getNameCount()) {
+      result.append(childPath.getName(idx).toString());
+    }
+    for (int i = idx + 1; i < childPath.getNameCount(); i++) {
+      result.append(File.separatorChar);
+      result.append(childPath.getName(i).toString());
+    }
+
+    return fileSystem.getPath(result.toString());
+  }
+
+  private static void assertSamePathType(Path basePath, Path childPath) {
+    Preconditions.checkArgument(
+        basePath.isAbsolute() == childPath.isAbsolute(),
+        "Both paths must be absolute or both paths must be relative. (%s is %s, %s is %s)",
+        basePath,
+        getPathTypeString(basePath),
+        childPath,
+        getPathTypeString(childPath));
+  }
+
+  /**
+   * Get a path without unnecessary path parts.
+   *
+   * <p>This method is a workaround for JDK-8037945 (Paths.get("").normalize() throws
+   * ArrayIndexOutOfBoundsException).
+   */
+  public static Path normalize(Path path) {
+    if (!isEmpty(path)) {
+      path = path.normalize();
+    }
+    return path;
+  }
+
+  /** Type-safer version of {@link #normalize(Path)}. */
+  public static AbsPath normalize(AbsPath path) {
+    return AbsPath.of(normalize(path.getPath()));
+  }
+
+  /** Return empty path with the same filesystem as provided path */
+  public static Path emptyOf(Path path) {
+    return path.getFileSystem().getPath("");
+  }
+
+  /** Return true if provided path is empty path ("") */
+  public static boolean isEmpty(Path path) {
+    return emptyOf(path).equals(path);
+  }
+
+  /**
+   * Filters out {@link Path} objects from {@code paths} that aren't a subpath of {@code root} and
+   * returns a set of paths relative to {@code root}.
+   */
+  public static ImmutableSet<Path> filterForSubpaths(Iterable<Path> paths, Path root) {
+    Path normalizedRoot = root.toAbsolutePath().normalize();
+    return Streams.stream(paths)
+        .filter(
+            input -> {
+              if (input.isAbsolute()) {
+                return input.normalize().startsWith(normalizedRoot);
+              } else {
+                return true;
+              }
+            })
+        .map(
+            input -> {
+              if (input.isAbsolute()) {
+                return relativize(normalizedRoot, input);
+              } else {
+                return input;
+              }
+            })
+        .collect(ImmutableSet.toImmutableSet());
+  }
+
+  /** Expands "~/foo" into "/home/zuck/foo". Returns regular paths unmodified. */
+  public static Path expandHomeDir(Path path) {
+    if (!path.startsWith("~")) {
+      return path;
+    }
+    Path homePath = path.getFileSystem().getPath(System.getProperty("user.home"));
+    if (path.equals(path.getFileSystem().getPath("~"))) {
+      return homePath;
+    }
+    return homePath.resolve(path.subpath(1, path.getNameCount()));
+  }
+
+  public static ByteSource asByteSource(Path path) {
+    return new ByteSource() {
+      @Override
+      public InputStream openStream() throws IOException {
+        return Files.newInputStream(path);
+      }
+    };
+  }
+
+  public static String getFileExtension(Path path) {
+    String name = path.getFileName().toString();
+    int index = name.lastIndexOf('.');
+    return index == -1 ? "" : name.substring(index + 1);
+  }
+
+  public static String getFileExtension(PathWrapper path) {
+    return getFileExtension(path.getPath());
+  }
+
+  public static String getNameWithoutExtension(Path file) {
+    String name = file.getFileName().toString();
+    int index = name.lastIndexOf('.');
+    return index == -1 ? name : name.substring(0, index);
+  }
+
+  public static String getNameWithoutExtension(PathWrapper file) {
+    return getNameWithoutExtension(file.getPath());
+  }
+
+  public static String stripPathPrefixAndExtension(Path fileName, String prefix) {
+    String nameWithoutExtension = getNameWithoutExtension(fileName);
+
+    if (!nameWithoutExtension.startsWith(prefix)
+        || nameWithoutExtension.length() < prefix.length()) {
+      throw new RuntimeException(
+          String.format(
+              "Invalid prefix on filename in path %s (file %s) - expecting %s",
+              fileName, nameWithoutExtension, prefix));
+    }
+
+    return nameWithoutExtension.substring(prefix.length());
+  }
+
+  /**
+   * @return strip {@code suffix} from the end of {@code p} and return the result, or {@code
+   *     Optional.empty()} if {@code p} does not end with {@code suffix}.
+   */
+  public static Optional<Path> stripSuffix(Path p, Path suffix) {
+    if (suffix.getNameCount() > p.getNameCount()) {
+      return Optional.empty();
+    }
+    for (int i = 1; i <= suffix.getNameCount(); ++i) {
+      if (!suffix.getName(suffix.getNameCount() - i).equals(p.getName(p.getNameCount() - i))) {
+        return Optional.empty();
+      }
+    }
+    if (p.getNameCount() == suffix.getNameCount()) {
+      return Optional.of(p.getFileSystem().getPath(""));
+    }
+    return Optional.of(p.subpath(0, p.getNameCount() - suffix.getNameCount()));
+  }
+
+  public static Optional<RelPath> stripSuffix(RelPath p, RelPath suffix) {
+    return stripSuffix(p.getPath(), suffix.getPath()).map(RelPath::of);
+  }
+
+  public static Optional<Path> stripPrefix(Path p, Path prefix) {
+    if (prefix.getNameCount() > p.getNameCount()) {
+      return Optional.empty();
+    }
+    for (int i = 0; i < prefix.getNameCount(); ++i) {
+      if (!prefix.getName(i).equals(p.getName(i))) {
+        return Optional.empty();
+      }
+    }
+    return Optional.of(p.subpath(prefix.getNameCount(), p.getNameCount()));
+  }
+
+  public static Optional<RelPath> stripPrefix(RelPath p, RelPath prefix) {
+    return stripPrefix(p.getPath(), prefix.getPath()).map(RelPath::of);
+  }
+
+  public static Function<String, Path> toPathFn(FileSystem fileSystem) {
+    return input -> fileSystem.getPath(input);
+  }
+
+  private static Path dropPathPart(Path p, int i) {
+    if (i == 0) {
+      return p.subpath(1, p.getNameCount());
+    } else if (i == p.getNameCount() - 1) {
+      return p.subpath(0, p.getNameCount() - 1);
+    } else {
+      return p.subpath(0, i).resolve(p.subpath(i + 1, p.getNameCount()));
+    }
+  }
+
+  /**
+   * Drop any "." parts (useless). Do keep ".." parts; don't normalize them away.
+   *
+   * <p>Note that while Path objects provide a {@link Path#normalize()} method for eliminating
+   * redundant parts of paths like in {@code foo/a/../b/c}, changing its internal parts (and
+   * actually using the filesystem), we don't use those methods to clean up the incoming paths; we
+   * only strip empty parts, and those consisting only of {@code .} because doing so maps
+   * exactly-same paths together, and can't influence where it may point to, whereas {@code ..} and
+   * symbolic links might.
+   */
+  public static Path fixPath(Path p) {
+    int i = 0;
+    while (i < p.getNameCount()) {
+      if (p.getName(i).toString().equals(".")) {
+        p = dropPathPart(p, i);
+      } else {
+        i++;
+      }
+    }
+    return p;
+  }
+
+  /**
+   * Drop the cache in Path object.
+   *
+   * <p>Path's implementation class {@code UnixPath}, will lazily initialize a String representation
+   * and store it in the object when {@code #toString()} is called for the first time. This doubles
+   * the memory requirement for the Path object.
+   *
+   * <p>This hack constructs a new path, dropping the cached toString value.
+   *
+   * <p>Due to the nature of what this function does, it's very sensitive to the implementation. Any
+   * calls to {@code #toString()} on the returned object would also recreate the cached string
+   * value.
+   */
+  public static Path dropInternalCaches(Path p) {
+    return p.getFileSystem().getPath(p.toString());
+  }
+
+  /**
+   * Creates a symlink.
+   *
+   * @param winFS WindowsFS object that creates symlink on Windows using different permission level
+   *     implementations.
+   * @param symLink the symlink to create.
+   * @param target the target of the symlink.
+   * @throws IOException if an I/O error occurs
+   */
+  public static void createSymLink(@Nullable WindowsFS winFS, Path symLink, Path target)
+      throws IOException {
+    try {
+      if (IS_WINDOWS) {
+        Objects.requireNonNull(winFS);
+        target = MorePaths.normalize(symLink.getParent().resolve(target));
+        // `isDirectory()` here returns false if target doesn’t exist, causing a problem with
+        // Windows build.
+        // Ideally we should crash or log if target doesn't exist. More detail can be found at
+        // D27587133.
+        winFS.createSymbolicLink(symLink, target, isDirectory(target));
+      } else {
+        Files.createSymbolicLink(symLink, target);
+      }
+    } catch (IllegalArgumentException e) {
+      // On windows, if one creates a symlink on a different filesystem, the error is not
+      // particularly useful. ("'other' has different root"). Add some extra context
+      if (e.getMessage().endsWith("has different root")) {
+        String msg = String.format("Could not link %s to %s: %s", target, symLink, e.getMessage());
+        throw new IllegalArgumentException(msg, e);
+      } else {
+        throw e;
+      }
+    }
+  }
+
+  public static void createSymLink(@Nullable WindowsFS winFS, AbsPath symLink, Path target)
+      throws IOException {
+    createSymLink(winFS, symLink.getPath(), target);
+  }
+
+  /**
+   * Returns whether a path is a directory..
+   *
+   * @param path An absolute file name
+   * @param linkOptions Link options
+   * @return Whether the path is a directory.
+   */
+  public static boolean isDirectory(Path path, LinkOption... linkOptions) {
+    return Files.isDirectory(normalize(path).toAbsolutePath(), linkOptions);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MorePosixFilePermissions.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MorePosixFilePermissions.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MorePosixFilePermissions.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.file;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.nio.file.attribute.FileAttribute;
+import java.nio.file.attribute.PosixFilePermission;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.util.Set;
+
+public class MorePosixFilePermissions {
+
+  public static final FileAttribute<?> READ_ONLY_FILE_ATTRIBUTE =
+      PosixFilePermissions.asFileAttribute(
+          ImmutableSet.of(
+              PosixFilePermission.OWNER_READ,
+              PosixFilePermission.GROUP_READ,
+              PosixFilePermission.OTHERS_READ));
+
+  private MorePosixFilePermissions() {}
+
+  private static final ImmutableList<PosixFilePermission> ORDERED_PERMISSIONS =
+      ImmutableList.of(
+          PosixFilePermission.OTHERS_EXECUTE,
+          PosixFilePermission.OTHERS_WRITE,
+          PosixFilePermission.OTHERS_READ,
+          PosixFilePermission.GROUP_EXECUTE,
+          PosixFilePermission.GROUP_WRITE,
+          PosixFilePermission.GROUP_READ,
+          PosixFilePermission.OWNER_EXECUTE,
+          PosixFilePermission.OWNER_WRITE,
+          PosixFilePermission.OWNER_READ);
+
+  private static final ImmutableMap<PosixFilePermission, PosixFilePermission> READ_TO_EXECUTE_MAP =
+      ImmutableMap.of(
+          PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_EXECUTE,
+          PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_EXECUTE,
+          PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_EXECUTE);
+
+  /** Convert a set of posix file permissions the unix bit representation (e.g. 0644). */
+  public static long toMode(Set<PosixFilePermission> permissions) {
+    long mode = 0;
+
+    for (int index = 0; index < ORDERED_PERMISSIONS.size(); index++) {
+      PosixFilePermission permission = ORDERED_PERMISSIONS.get(index);
+      if (permissions.contains(permission)) {
+        mode |= (1 << index);
+      }
+    }
+
+    return mode;
+  }
+
+  /** Convert a unix bit representation (e.g. 0644) into a set of posix file permissions. */
+  public static ImmutableSet<PosixFilePermission> fromMode(long mode) {
+    ImmutableSet.Builder<PosixFilePermission> permissions = ImmutableSet.builder();
+
+    for (int index = 0; index < ORDERED_PERMISSIONS.size(); index++) {
+      if ((mode & (1 << index)) != 0) {
+        permissions.add(ORDERED_PERMISSIONS.get(index));
+      }
+    }
+
+    return permissions.build();
+  }
+
+  /**
+   * Return a new set of permissions which include execute permission for each of the roles that
+   * already have read permissions (e.g. 0606 =&gt; 0707).
+   */
+  public static ImmutableSet<PosixFilePermission> addExecutePermissionsIfReadable(
+      Set<PosixFilePermission> permissions) {
+
+    ImmutableSet.Builder<PosixFilePermission> newPermissions = ImmutableSet.builder();
+
+    // The new permissions are a superset of the current ones.
+    newPermissions.addAll(permissions);
+
+    // If we see a read permission for the given role, add in the corresponding
+    // execute permission.
+    for (ImmutableMap.Entry<PosixFilePermission, PosixFilePermission> ent :
+        READ_TO_EXECUTE_MAP.entrySet()) {
+      if (permissions.contains(ent.getKey())) {
+        newPermissions.add(ent.getValue());
+      }
+    }
+
+    return newPermissions.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MostFiles.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MostFiles.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/MostFiles.java
@@ -0,0 +1,514 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.file;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.io.windowsfs.WindowsFS;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Functions;
+import com.google.common.base.Objects;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.io.ByteStreams;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.DirectoryNotEmptyException;
+import java.nio.file.FileSystems;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.nio.file.attribute.PosixFilePermission;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public final class MostFiles {
+
+  private static final Logger LOG = Logger.get(MostFiles.class);
+
+  // Extended attribute bits for directories and symlinks; see:
+  // http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute
+  @SuppressWarnings("PMD.AvoidUsingOctalValues")
+  public static final long S_IFDIR = 0040000;
+
+  @SuppressWarnings("PMD.AvoidUsingOctalValues")
+  public static final long S_IFREG = 0100000;
+
+  @SuppressWarnings("PMD.AvoidUsingOctalValues")
+  public static final long S_IFLNK = 0120000;
+
+  public enum DeleteRecursivelyOptions {
+    IGNORE_NO_SUCH_FILE_EXCEPTION,
+    DELETE_CONTENTS_ONLY,
+  }
+
+  // Unix has two illegal characters - '/', and '\0'.  Windows has ten, which includes those two.
+  // The full list can be found at https://msdn.microsoft.com/en-us/library/aa365247
+  private static final String ILLEGAL_FILE_NAME_CHARACTERS = "<>:\"/\\|?*\0";
+
+  private static final WindowsFS winFS = new WindowsFS();
+
+  private static class FileAccessedEntry {
+    public final File file;
+    public final FileTime lastAccessTime;
+
+    public File getFile() {
+      return file;
+    }
+
+    public FileTime getLastAccessTime() {
+      return lastAccessTime;
+    }
+
+    private FileAccessedEntry(File file, FileTime lastAccessTime) {
+      this.file = file;
+      this.lastAccessTime = lastAccessTime;
+    }
+  }
+
+  /** Sorts by the lastAccessTime in descending order (more recently accessed files are first). */
+  private static final Comparator<FileAccessedEntry> SORT_BY_LAST_ACCESSED_TIME_DESC =
+      (a, b) -> b.getLastAccessTime().compareTo(a.getLastAccessTime());
+
+  /** Utility class: do not instantiate. */
+  private MostFiles() {}
+
+  /**
+   * Deletes the file tree rooted at {@code path} while excluding any paths from {@code
+   * excludedAbsPaths}. If any files are not deleted due to presence in {@code excludedAbsPaths},
+   * then any parent directories will not be deleted, either.
+   */
+  public static void deleteRecursivelyIfExists(AbsPath path, ImmutableSet<AbsPath> excludedAbsPaths)
+      throws IOException {
+    ImmutableSet<Path> excludedPaths =
+        excludedAbsPaths.stream()
+            .map(absPath -> absPath.getPath())
+            .collect(ImmutableSet.toImmutableSet());
+    deleteRecursivelyWithOptions(
+        path.getPath(),
+        EnumSet.of(DeleteRecursivelyOptions.IGNORE_NO_SUCH_FILE_EXCEPTION),
+        excludedPaths);
+  }
+
+  public static void deleteRecursivelyIfExists(Path path) throws IOException {
+    deleteRecursivelyWithOptions(
+        path, EnumSet.of(DeleteRecursivelyOptions.IGNORE_NO_SUCH_FILE_EXCEPTION));
+  }
+
+  public static void deleteRecursivelyIfExists(AbsPath path) throws IOException {
+    deleteRecursivelyIfExists(path.getPath());
+  }
+
+  /** Recursively copies all files under {@code fromPath} to {@code toPath}. */
+  public static void copyRecursively(Path fromPath, Path toPath) throws IOException {
+    copyRecursively(fromPath, toPath, Functions.identity());
+  }
+
+  /** Recursively copies all files under {@code fromPath} to {@code toPath}. */
+  public static void copyRecursively(AbsPath fromPath, AbsPath toPath) throws IOException {
+    copyRecursively(fromPath.getPath(), toPath.getPath());
+  }
+
+  /**
+   * Recursively copies all files under {@code fromPath} to {@code toPath}. The {@code transform}
+   * will be applied after the destination path for a file has been relativized. This will remove
+   * any existing files in the toPath if there is a conflict.
+   *
+   * @param fromPath item to copy
+   * @param toPath destination of copy
+   * @param transform renaming function to apply when copying. If this function returns null, then
+   *     the file is not copied.
+   */
+  public static void copyRecursively(Path fromPath, Path toPath, Function<Path, Path> transform)
+      throws IOException {
+    copyRecursively(fromPath, toPath, transform, input -> true);
+  }
+
+  public static void copyRecursively(
+      Path fromPath, Path toPath, Function<Path, Path> transform, Function<Path, Boolean> filter)
+      throws IOException {
+    // Adapted from http://codingjunkie.net/java-7-copy-move/.
+    SimpleFileVisitor<Path> copyDirVisitor =
+        new SimpleFileVisitor<Path>() {
+
+          @Override
+          public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
+              throws IOException {
+            Path targetPath = toPath.resolve(fromPath.relativize(dir));
+            if (!Files.exists(targetPath)) {
+              Files.createDirectory(targetPath);
+            }
+            return FileVisitResult.CONTINUE;
+          }
+
+          @Override
+          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+              throws IOException {
+            if (!filter.apply(file)) {
+              return FileVisitResult.CONTINUE;
+            }
+            Path destPath = toPath.resolve(fromPath.relativize(file));
+            Path transformedDestPath = transform.apply(destPath);
+            if (transformedDestPath != null) {
+              if (Files.isSymbolicLink(file)) {
+                Files.deleteIfExists(transformedDestPath);
+                MorePaths.createSymLink(winFS, transformedDestPath, Files.readSymbolicLink(file));
+              } else {
+                Files.copy(file, transformedDestPath, StandardCopyOption.REPLACE_EXISTING);
+              }
+            }
+            return FileVisitResult.CONTINUE;
+          }
+        };
+    Files.walkFileTree(fromPath, copyDirVisitor);
+  }
+
+  public static void deleteRecursively(Path path) throws IOException {
+    deleteRecursivelyWithOptions(path, EnumSet.noneOf(DeleteRecursivelyOptions.class));
+  }
+
+  public static void deleteRecursively(AbsPath path) throws IOException {
+    deleteRecursively(path.getPath());
+  }
+
+  public static void deleteRecursivelyWithOptions(
+      Path path, EnumSet<DeleteRecursivelyOptions> options) throws IOException {
+    deleteRecursivelyWithOptions(path, options, ImmutableSet.of());
+  }
+
+  /**
+   * Returns {@code true} if the given {@code path} or any of its ancestors are contained in {@code
+   * excludedPaths}. For example, if {@code excludedPaths} contains "/a/b" and and {@code path} is
+   * "/a/b/c/d", then this function will return {@code true}. On the other hand, if {@code path} is
+   * "/a/f/g, then the function returns {@code false}.
+   */
+  public static boolean shouldSkipDeletingPath(Path path, ImmutableSet<Path> excludedPaths) {
+    Preconditions.checkArgument(path.isAbsolute());
+
+    if (excludedPaths.contains(path)) {
+      return true;
+    }
+
+    for (Path excludedPath : excludedPaths) {
+      // Required so that `excludedPaths` can contain directories
+      if (path.startsWith(excludedPath)) {
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  /**
+   * Deletes the file element rooted at {@code path}, recursively if a directory, by excluding any
+   * elements from {@code excludedPaths}. If {@code excludedPaths} contains directories, then all
+   * elements contain in those directories are excluded as well.
+   */
+  public static void deleteRecursivelyWithOptions(
+      Path path, EnumSet<DeleteRecursivelyOptions> options, ImmutableSet<Path> excludedPaths)
+      throws IOException {
+    try {
+      if (!Files.isDirectory(path)) {
+        if (options.contains(DeleteRecursivelyOptions.IGNORE_NO_SUCH_FILE_EXCEPTION)) {
+          if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
+            return;
+          }
+        }
+        if (options.contains(DeleteRecursivelyOptions.DELETE_CONTENTS_ONLY)) {
+          throw new IOException(String.format("Can't delete contents of regular file %s.", path));
+        }
+        Preconditions.checkArgument(excludedPaths.isEmpty());
+        Files.delete(path);
+      } else {
+        // `nonEmptyDirectories` is a list of directories which contains elements (files/dirs)
+        // that were excluded from deletion, so these parent directories must be kept. Note that
+        // semantics of `nonEmptyDirectories` are different from `excludedPaths`, namely:
+        // `excludedPaths` are _recursive_ while `nonEmptyDirectories` are _not_.
+        //
+        // That is, a directory in `nonEmptyDirectories` does not mean that _all_ elements
+        // inside that directories must be kept but only the directory _itself_.
+        Set<Path> nonEmptyDirectories = new HashSet<>();
+        Consumer<Path> skipDeletingParentsOf =
+            (Path excludedPath) -> {
+              Path currentParent = excludedPath.getParent();
+              while (currentParent != null) {
+                nonEmptyDirectories.add(currentParent);
+                currentParent = currentParent.getParent();
+              }
+            };
+
+        // Adapted from http://codingjunkie.net/java-7-copy-move/.
+        SimpleFileVisitor<Path> deleteDirVisitor =
+            new SimpleFileVisitor<Path>() {
+
+              @Override
+              public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+                  throws IOException {
+                try {
+                  if (!shouldSkipDeletingPath(file.toAbsolutePath(), excludedPaths)) {
+                    Files.delete(file);
+                  } else {
+                    skipDeletingParentsOf.accept(file);
+                  }
+                } catch (IOException e) {
+                  LOG.warn("%s, could not delete file", e);
+                }
+                return FileVisitResult.CONTINUE;
+              }
+
+              @Override
+              public FileVisitResult postVisitDirectory(Path dir, IOException e)
+                  throws IOException {
+                if (e == null) {
+                  // Allow leaving the top-level directory in place (e.g. for deleting the contents
+                  // of
+                  // the trash dir but not the trash dir itself)
+                  if (!(options.contains(DeleteRecursivelyOptions.DELETE_CONTENTS_ONLY)
+                          && dir.equals(path))
+                      && !nonEmptyDirectories.contains(dir)) {
+                    try {
+                      if (!shouldSkipDeletingPath(dir.toAbsolutePath(), excludedPaths)) {
+                        Files.delete(dir);
+                      } else {
+                        skipDeletingParentsOf.accept(dir);
+                      }
+                    } catch (DirectoryNotEmptyException notEmpty) {
+                      try (Stream<Path> paths = Files.list(dir)) {
+                        LOG.warn(
+                            String.format(
+                                "Could not delete non-empty directory %s. Contents:\n%s",
+                                dir, paths.map(Path::toString).collect(Collectors.joining("\n"))));
+                      }
+                    } catch (IOException ioException) {
+                      LOG.warn("%s, could not delete directory", ioException);
+                    }
+                  }
+                  return FileVisitResult.CONTINUE;
+                } else {
+                  throw e;
+                }
+              }
+            };
+        Files.walkFileTree(path, deleteDirVisitor);
+      }
+    } catch (NoSuchFileException e) {
+      if (!options.contains(DeleteRecursivelyOptions.IGNORE_NO_SUCH_FILE_EXCEPTION)) {
+        throw e;
+      }
+    }
+  }
+
+  /** Writes the specified lines to the specified file, encoded as UTF-8. */
+  public static void writeLinesToFile(Iterable<String> lines, Path file) throws IOException {
+    try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
+      for (String line : lines) {
+        writer.write(line);
+        writer.newLine();
+      }
+    }
+  }
+
+  /** Writes the specified lines to the specified file, encoded as UTF-8. */
+  public static void writeLinesToFile(Iterable<String> lines, AbsPath file) throws IOException {
+    writeLinesToFile(lines, file.getPath());
+  }
+
+  /** Log a simplistic diff between lines and the contents of file. */
+  @VisibleForTesting
+  static List<String> diffFileContents(Iterable<String> lines, File file) throws IOException {
+    List<String> diffLines = new ArrayList<>();
+    Iterator<String> iter = lines.iterator();
+    try (BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
+      while (iter.hasNext()) {
+        String lineA = reader.readLine();
+        String lineB = iter.next();
+        if (!Objects.equal(lineA, lineB)) {
+          diffLines.add(String.format("| %s | %s |", lineA == null ? "" : lineA, lineB));
+        }
+      }
+
+      String lineA;
+      while ((lineA = reader.readLine()) != null) {
+        diffLines.add(String.format("| %s |  |", lineA));
+      }
+    }
+    return diffLines;
+  }
+
+  /**
+   * Does an in-place sort of the specified {@code files} array. Most recently accessed files will
+   * be at the front of the array when sorted.
+   */
+  public static void sortFilesByAccessTime(File[] files) {
+    FileAccessedEntry[] fileAccessedEntries = new FileAccessedEntry[files.length];
+    for (int i = 0; i < files.length; ++i) {
+      FileTime lastAccess;
+      try {
+        lastAccess =
+            Files.readAttributes(files[i].toPath(), BasicFileAttributes.class).lastAccessTime();
+      } catch (IOException e) {
+        lastAccess = FileTime.fromMillis(files[i].lastModified());
+      }
+      fileAccessedEntries[i] = new FileAccessedEntry(files[i], lastAccess);
+    }
+    Arrays.sort(fileAccessedEntries, SORT_BY_LAST_ACCESSED_TIME_DESC);
+
+    for (int i = 0; i < files.length; i++) {
+      files[i] = fileAccessedEntries[i].getFile();
+    }
+  }
+
+  /**
+   * Tries to make the specified file executable. For file systems that do support the POSIX-style
+   * permissions, the executable permission is set for each category of users that already has the
+   * read permission.
+   *
+   * <p>If the file system does not support the executable permission or the operation fails, a
+   * {@code java.io.IOException} is thrown.
+   */
+  public static void makeExecutable(Path file) throws IOException {
+    if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
+      Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(file);
+
+      if (permissions.contains(PosixFilePermission.OWNER_READ)) {
+        permissions.add(PosixFilePermission.OWNER_EXECUTE);
+      }
+      if (permissions.contains(PosixFilePermission.GROUP_READ)) {
+        permissions.add(PosixFilePermission.GROUP_EXECUTE);
+      }
+      if (permissions.contains(PosixFilePermission.OTHERS_READ)) {
+        permissions.add(PosixFilePermission.OTHERS_EXECUTE);
+      }
+
+      Files.setPosixFilePermissions(file, permissions);
+    } else {
+      if (!file.toFile().setExecutable(/* executable */ true, /* ownerOnly */ true)) {
+        throw new IOException("The file could not be made executable");
+      }
+    }
+  }
+
+  /**
+   * Tries to make the specified file writable. For file systems that do support the POSIX-style
+   * permissions, the writable permission is set for each category of users that already has the
+   * read permission.
+   *
+   * <p>If the file system does not support the writable permission or the operation fails, a {@code
+   * java.io.IOException} is thrown.
+   */
+  public static void makeWritable(Path file) throws IOException {
+    if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
+      Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(file);
+
+      if (permissions.contains(PosixFilePermission.OWNER_READ)) {
+        permissions.add(PosixFilePermission.OWNER_WRITE);
+      }
+      if (permissions.contains(PosixFilePermission.GROUP_READ)) {
+        permissions.add(PosixFilePermission.GROUP_WRITE);
+      }
+      if (permissions.contains(PosixFilePermission.OTHERS_READ)) {
+        permissions.add(PosixFilePermission.OTHERS_WRITE);
+      }
+
+      Files.setPosixFilePermissions(file, permissions);
+    } else {
+      if (!file.toFile().setWritable(/* writable */ true, /* ownerOnly */ true)) {
+        throw new IOException("The file could not be made writable");
+      }
+    }
+  }
+
+  /** Abs-path version of {@link #makeExecutable(Path)}. */
+  public static void makeExecutable(AbsPath file) throws IOException {
+    makeExecutable(file.getPath());
+  }
+
+  /**
+   * Given a file name, replace any illegal characters from it.
+   *
+   * @param name The file name to sanitize
+   * @return a properly sanitized filename
+   */
+  public static String sanitize(String name) {
+    return CharMatcher.anyOf(ILLEGAL_FILE_NAME_CHARACTERS).replaceFrom(name, "_");
+  }
+
+  /**
+   * Concatenates the contents of one or more files.
+   *
+   * @param dest The path to which the concatenated files' contents are written.
+   * @param pathsToConcatenate The paths whose contents are concatenated to {@code dest}.
+   * @return {@code true} if any data was concatenated to {@code dest}, {@code false} otherwise.
+   */
+  public static boolean concatenateFiles(Path dest, Iterable<Path> pathsToConcatenate)
+      throws IOException {
+    // Concatenate all the logs to a temp file, then atomically rename it to the
+    // passed-in concatenatedPath if any log data was collected.
+    String tempFilename = "." + dest.getFileName() + ".concat.tmp." + UUID.randomUUID();
+    Path tempPath = dest.resolveSibling(tempFilename);
+
+    try {
+      long bytesCollected = 0;
+      try (OutputStream os =
+          Files.newOutputStream(
+              tempPath,
+              StandardOpenOption.CREATE,
+              StandardOpenOption.TRUNCATE_EXISTING,
+              StandardOpenOption.WRITE)) {
+        for (Path path : pathsToConcatenate) {
+          try (InputStream is = Files.newInputStream(path)) {
+            bytesCollected += ByteStreams.copy(is, os);
+          } catch (NoSuchFileException e) {
+            continue;
+          }
+        }
+      }
+      if (bytesCollected > 0) {
+        Files.move(
+            tempPath, dest, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
+        return true;
+      } else {
+        return false;
+      }
+    } finally {
+      Files.deleteIfExists(tempPath);
+    }
+  }
+
+  /** Write given string to the file using UTF-8 charset. */
+  public static void write(AbsPath path, String content) throws IOException {
+    Files.write(path.getPath(), content.getBytes(StandardCharsets.UTF_8));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/PathListing.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/PathListing.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/PathListing.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.file;
+
+import com.google.common.base.Functions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.collect.Ordering;
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.attribute.FileTime;
+import java.util.Optional;
+import java.util.OptionalInt;
+
+/** Utility class to list files which match a pattern, applying ordering and filtering. */
+public class PathListing {
+  // Utility class, do not instantiate.
+  private PathListing() {}
+
+  /** Whether to include files which match the filter, or exclude them. */
+  public enum FilterMode {
+    INCLUDE,
+    EXCLUDE,
+  }
+
+  /** Fetches last-modified time from a path. */
+  public interface PathModifiedTimeFetcher {
+    FileTime getLastModifiedTime(Path path) throws IOException;
+  }
+
+  /** Uses {@code Files.getLastModifiedTime()} to get the last modified time for a Path. */
+  public static final PathModifiedTimeFetcher GET_PATH_MODIFIED_TIME =
+      path -> Files.getLastModifiedTime(path);
+
+  /** Lists matching paths in descending modified time order. */
+  public static ImmutableSortedSet<Path> listMatchingPaths(
+      Path pathToGlob, String globPattern, PathModifiedTimeFetcher pathModifiedTimeFetcher)
+      throws IOException {
+    return listMatchingPathsWithFilters(
+        pathToGlob,
+        globPattern,
+        pathModifiedTimeFetcher,
+        FilterMode.INCLUDE,
+        OptionalInt.empty(),
+        Optional.empty());
+  }
+
+  /**
+   * Lists paths in descending modified time order, excluding any paths which bring the number of
+   * files over {@code maxNumPaths} or over {@code totalSizeFilter} bytes in size.
+   */
+  public static ImmutableSortedSet<Path> listMatchingPathsWithFilters(
+      Path pathToGlob,
+      String globPattern,
+      PathModifiedTimeFetcher pathModifiedTimeFetcher,
+      FilterMode filterMode,
+      OptionalInt maxPathsFilter,
+      Optional<Long> totalSizeFilter)
+      throws IOException {
+
+    // Fetch the modification time of each path and build a map of
+    // (path => modification time) pairs.
+    ImmutableMap.Builder<Path, FileTime> pathFileTimesBuilder = ImmutableMap.builder();
+    try (DirectoryStream<Path> stream = Files.newDirectoryStream(pathToGlob, globPattern)) {
+      for (Path path : stream) {
+        try {
+          pathFileTimesBuilder.put(path, pathModifiedTimeFetcher.getLastModifiedTime(path));
+        } catch (NoSuchFileException e) {
+          // Ignore the path.
+          continue;
+        }
+      }
+    }
+    ImmutableMap<Path, FileTime> pathFileTimes = pathFileTimesBuilder.build();
+
+    ImmutableSortedSet<Path> paths =
+        ImmutableSortedSet.copyOf(
+            Ordering.natural()
+                // Order the keys of the map (the paths) by their values (the file modification
+                // times).
+                .onResultOf(Functions.forMap(pathFileTimes))
+                // If two keys of the map have the same value, fall back to key order.
+                .compound(Ordering.natural())
+                // Use descending order.
+                .reverse(),
+            pathFileTimes.keySet());
+
+    paths = applyNumPathsFilter(paths, filterMode, maxPathsFilter);
+    paths = applyTotalSizeFilter(paths, filterMode, totalSizeFilter);
+    return paths;
+  }
+
+  private static ImmutableSortedSet<Path> applyNumPathsFilter(
+      ImmutableSortedSet<Path> paths, FilterMode filterMode, OptionalInt maxPathsFilter) {
+    if (maxPathsFilter.isPresent()) {
+      int limitIndex = Math.min(maxPathsFilter.getAsInt(), paths.size());
+      paths = subSet(paths, filterMode, limitIndex);
+    }
+    return paths;
+  }
+
+  @SuppressWarnings("PMD.EmptyCatchBlock")
+  private static ImmutableSortedSet<Path> applyTotalSizeFilter(
+      ImmutableSortedSet<Path> paths, FilterMode filterMode, Optional<Long> totalSizeFilter)
+      throws IOException {
+    if (totalSizeFilter.isPresent()) {
+      int limitIndex = 0;
+      long totalSize = 0;
+      for (Path path : paths) {
+        try {
+          totalSize += Files.size(path);
+        } catch (NoSuchFileException e) {
+          // Path was deleted; ignore it.
+        }
+
+        if (totalSize < totalSizeFilter.get()) {
+          limitIndex++;
+        } else {
+          break;
+        }
+      }
+      paths = subSet(paths, filterMode, limitIndex);
+    }
+    return paths;
+  }
+
+  private static ImmutableSortedSet<Path> subSet(
+      ImmutableSortedSet<Path> paths, FilterMode filterMode, int limitIndex) {
+    // This doesn't copy the contents of the ImmutableSortedSet. We use it
+    // as a simple way to get O(1) access to the set's contents, as otherwise
+    // we would have to iterate to find the Nth element.
+    ImmutableList<Path> pathsList = paths.asList();
+    boolean fullSet = limitIndex == paths.size();
+    switch (filterMode) {
+      case INCLUDE:
+        // Make sure we don't call pathsList.get(pathsList.size()).
+        if (!fullSet) {
+          paths = paths.headSet(pathsList.get(limitIndex));
+        }
+        break;
+      case EXCLUDE:
+        if (fullSet) {
+          // Make sure we don't call pathsList.get(pathsList.size()).
+          paths = ImmutableSortedSet.of();
+        } else {
+          paths = paths.tailSet(pathsList.get(limitIndex));
+        }
+        break;
+    }
+    return paths;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/PathMatcher.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/PathMatcher.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/file/PathMatcher.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.file;
+
+import com.facebook.buck.core.filesystems.RelPath;
+import java.nio.file.Path;
+
+/** A contract for matching {@link Path}s. */
+public interface PathMatcher {
+
+  /** Check if given path matches pattern. */
+  boolean matches(RelPath path);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/BUCK
@@ -0,0 +1,19 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "filesystem",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/CopySourceMode.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/CopySourceMode.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/CopySourceMode.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.filesystem;
+
+/** Controls the behavior of how the source should be treated when copying. */
+public enum CopySourceMode {
+  /** Copy the single source file into the destination path. */
+  FILE,
+
+  /**
+   * Treat the source as a directory and copy each file inside it to the destination path, which
+   * must be a directory.
+   */
+  DIRECTORY_CONTENTS_ONLY,
+
+  /**
+   * Treat the source as a directory. Copy the directory and its contents to the destination path,
+   * which must be a directory.
+   */
+  DIRECTORY_AND_CONTENTS,
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/impl/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/impl/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/impl/BUCK
@@ -0,0 +1,27 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+UTILS_SRCS = [
+    "ProjectFilesystemUtils.java",
+]
+
+buck_java_library(
+    name = "utils",
+    srcs = UTILS_SRCS,
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+        "prelude//toolchains/android/src/com/facebook/buck/io/windowsfs:windowsfs",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/impl/ProjectFilesystemUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/impl/ProjectFilesystemUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/filesystem/impl/ProjectFilesystemUtils.java
@@ -0,0 +1,693 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.filesystem.impl;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.file.MorePaths;
+import com.facebook.buck.io.file.MorePosixFilePermissions;
+import com.facebook.buck.io.file.MostFiles;
+import com.facebook.buck.io.file.PathMatcher;
+import com.facebook.buck.io.filesystem.CopySourceMode;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableCollection;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.UnmodifiableIterator;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.nio.channels.Channels;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.DirectoryStream;
+import java.nio.file.FileAlreadyExistsException;
+import java.nio.file.FileSystemLoopException;
+import java.nio.file.FileVisitOption;
+import java.nio.file.FileVisitResult;
+import java.nio.file.FileVisitor;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileAttribute;
+import java.nio.file.attribute.FileTime;
+import java.nio.file.attribute.PosixFileAttributeView;
+import java.nio.file.attribute.PosixFilePermission;
+import java.util.ArrayDeque;
+import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import javax.annotation.Nullable;
+
+/**
+ * A stateless filesystem utils that helps to interact with the filesystem relative to the project
+ * root.
+ */
+public class ProjectFilesystemUtils {
+
+  private ProjectFilesystemUtils() {}
+
+  /**
+   * Gets a list of paths of the contents of the given directory, obeying the ignores. All paths are
+   * relative to the root of this view.
+   */
+  public static ImmutableCollection<Path> getDirectoryContents(
+      AbsPath root, ImmutableCollection<PathMatcher> ignores, Path pathRelativeToProjectRoot)
+      throws IOException {
+    Path path = getPathForRelativePath(root, pathRelativeToProjectRoot);
+    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
+      return FluentIterable.from(stream)
+          .filter(input -> !isIgnored(relativize(root, input), ignores))
+          .transform(absolutePath -> MorePaths.relativize(root.getPath(), absolutePath))
+          .toSortedList(Comparator.naturalOrder());
+    }
+  }
+
+  /** Get path that is an absolute path resolved against the root path. */
+  public static Path getPathForRelativePath(AbsPath root, Path pathRelativeToProjectRoot) {
+    return getAbsPathForRelativePath(root, pathRelativeToProjectRoot).getPath();
+  }
+
+  /** Get path that is an absolute path resolved against the root path. */
+  public static Path getPathForRelativePath(AbsPath root, RelPath pathRelativeToProjectRoot) {
+    return getPathForRelativePath(root, pathRelativeToProjectRoot.getPath());
+  }
+
+  /** Get absolute path that is resolved against the root path. */
+  public static AbsPath getAbsPathForRelativePath(AbsPath root, Path pathRelativeToProjectRoot) {
+    AbsPath result;
+    // We often create {@link Path} instances using
+    // {@link java.nio.file.Paths#get(String, String...)}, but there's no guarantee that the
+    // underlying {@link FileSystem} is the default one.
+    if (pathRelativeToProjectRoot.getFileSystem().equals(root.getFileSystem())) {
+      result = root.resolve(pathRelativeToProjectRoot);
+    } else {
+      result = root.resolve(pathRelativeToProjectRoot.toString());
+    }
+
+    return MorePaths.normalize(result);
+  }
+
+  /** Get absolute path that is resolved against the root path. */
+  public static AbsPath getAbsPathForRelativePath(AbsPath root, RelPath pathRelativeToProjectRoot) {
+    return getAbsPathForRelativePath(root, pathRelativeToProjectRoot.getPath());
+  }
+
+  /** Construct a relative path between the project root and a given path. */
+  public static RelPath relativize(AbsPath root, Path path) {
+    return root.relativize(path);
+  }
+
+  /** Construct a relative path between the project root and a given path. */
+  public static RelPath relativize(AbsPath root, AbsPath path) {
+    return root.relativize(path);
+  }
+
+  /**
+   * @param path the path to check.
+   * @return whether ignored paths contains path or any of its ancestors.
+   */
+  public static boolean isIgnored(
+      RelPath path, ImmutableCollection<? extends PathMatcher> ignores) {
+    return ignores.stream().anyMatch(pathMatcher -> pathMatcher.matches(path));
+  }
+
+  /**
+   * @return the absolute path of {@code pathRelativeToProjectRoot} resolved against {@code root}.
+   */
+  public static AbsPath getPathForRelativePath(AbsPath root, String pathRelativeToProjectRoot) {
+    return MorePaths.normalize(root.resolve(pathRelativeToProjectRoot));
+  }
+
+  /** Tests whether a file exists. */
+  public static boolean exists(
+      AbsPath root, Path pathRelativeToProjectRoot, LinkOption... options) {
+    return Files.exists(getPathForRelativePath(root, pathRelativeToProjectRoot), options);
+  }
+
+  /** Returns the posix file mode of a file */
+  public static long getPosixFileModes(AbsPath root, Path pathRelativeToProjectRoot)
+      throws IOException {
+    long mode = 0;
+    // Support executable files.  If we detect this file is executable, store this
+    // information as 0100 in the field typically used in zip implementations for
+    // POSIX file permissions.  We'll use this information when unzipping.
+    Path path = getPathForRelativePath(root, pathRelativeToProjectRoot);
+    if (isExecutable(root, path)) {
+      mode |= MorePosixFilePermissions.toMode(EnumSet.of(PosixFilePermission.OWNER_EXECUTE));
+    }
+
+    if (isDirectory(root, path)) {
+      mode |= MostFiles.S_IFDIR;
+    } else if (isFile(root, path)) {
+      mode |= MostFiles.S_IFREG;
+    }
+
+    // Propagate any additional permissions
+    mode |= MorePosixFilePermissions.toMode(getPosixFilePermissions(root, path));
+
+    return mode;
+  }
+
+  /**
+   * Deletes a file specified by its path relative to the project root.
+   *
+   * @param pathRelativeToProjectRoot path to the file
+   */
+  public static void deleteFileAtPath(AbsPath root, Path pathRelativeToProjectRoot)
+      throws IOException {
+    Files.delete(getPathForRelativePath(root, pathRelativeToProjectRoot));
+  }
+
+  /** Opens a file, returning an input stream to read from the file. */
+  public static InputStream newFileInputStream(AbsPath root, Path pathRelativeToProjectRoot)
+      throws IOException {
+    return new BufferedInputStream(
+        Files.newInputStream(getPathForRelativePath(root, pathRelativeToProjectRoot)));
+  }
+
+  /** Checks whether there is a normal file at the specified path. */
+  public static boolean isFile(
+      AbsPath root, Path pathRelativeToProjectRoot, LinkOption... options) {
+    return Files.isRegularFile(getPathForRelativePath(root, pathRelativeToProjectRoot), options);
+  }
+
+  /** Allows {@link Files#isDirectory} to be faked in tests. */
+  public static boolean isDirectory(
+      AbsPath root, Path pathRelativeToProjectRoot, LinkOption... linkOptions) {
+    return MorePaths.isDirectory(
+        getPathForRelativePath(root, pathRelativeToProjectRoot), linkOptions);
+  }
+
+  /** Allows {@link Files#isExecutable} to be faked in tests. */
+  public static boolean isExecutable(AbsPath root, Path pathRelativeToProjectRoot) {
+    return Files.isExecutable(getPathForRelativePath(root, pathRelativeToProjectRoot));
+  }
+
+  /** Sets the last modified time for the given path. */
+  public static Path setLastModifiedTime(
+      AbsPath root, Path pathRelativeToProjectRoot, FileTime time) throws IOException {
+    Path path = getPathForRelativePath(root, pathRelativeToProjectRoot);
+    return Files.setLastModifiedTime(path, time);
+  }
+
+  /**
+   * Recursively delete everything under the specified path. Ignore the failure if the file at the
+   * specified path does not exist.
+   */
+  public static void deleteRecursivelyIfExists(AbsPath root, Path pathRelativeToProjectRoot)
+      throws IOException {
+    MostFiles.deleteRecursivelyIfExists(getPathForRelativePath(root, pathRelativeToProjectRoot));
+  }
+
+  /**
+   * @param pathRelativeToProjectRoot Must identify a file, not a directory. (Unfortunately, we have
+   *     no way to assert this because the path is not expected to exist yet.)
+   */
+  public static void createParentDirs(AbsPath root, Path pathRelativeToProjectRoot)
+      throws IOException {
+    Path path = getPathForRelativePath(root, pathRelativeToProjectRoot);
+    mkdirs(root, path.getParent());
+  }
+
+  /**
+   * Resolves the relative path against the project root and then calls {@link
+   * Files#createDirectories(Path, FileAttribute[])}
+   */
+  public static void mkdirs(AbsPath root, Path pathRelativeToProjectRoot) throws IOException {
+    Path resolved = getPathForRelativePath(root, pathRelativeToProjectRoot);
+    try {
+      Files.createDirectories(resolved);
+    } catch (FileAlreadyExistsException e) {
+      // Don't complain if the file is a symlink that points to a valid directory.
+      // This check is done only on exception as it's a rare case, and lstat is not free.
+      if (!Files.isDirectory(resolved)) {
+        throw e;
+      }
+    }
+  }
+
+  /**
+   * Writes each line in {@code lines} with a trailing newline to a file at the specified path.
+   *
+   * <p>The parent path of {@code pathRelativeToProjectRoot} must exist.
+   */
+  public static void writeLinesToPath(
+      AbsPath root,
+      Iterable<String> lines,
+      Path pathRelativeToProjectRoot,
+      FileAttribute<?>... attrs)
+      throws IOException {
+    try (Writer writer =
+        new BufferedWriter(
+            new OutputStreamWriter(
+                newFileOutputStream(root, pathRelativeToProjectRoot, attrs),
+                StandardCharsets.UTF_8))) {
+      for (String line : lines) {
+        writer.write(line);
+        writer.write('\n');
+      }
+    }
+  }
+
+  /** Returns a new buffered file output stream */
+  public static OutputStream newFileOutputStream(
+      AbsPath root, Path pathRelativeToProjectRoot, FileAttribute<?>... attrs) throws IOException {
+    return newFileOutputStream(root, pathRelativeToProjectRoot, /* append */ false, attrs);
+  }
+
+  /** Returns a new buffered file output stream */
+  public static OutputStream newFileOutputStream(
+      AbsPath root, Path pathRelativeToProjectRoot, boolean append, FileAttribute<?>... attrs)
+      throws IOException {
+    return new BufferedOutputStream(
+        newUnbufferedFileOutputStream(root, pathRelativeToProjectRoot, append, attrs));
+  }
+
+  /** Returns a new uUnbuffered file output stream */
+  public static OutputStream newUnbufferedFileOutputStream(
+      AbsPath root, Path pathRelativeToProjectRoot, boolean append, FileAttribute<?>... attrs)
+      throws IOException {
+    return Channels.newOutputStream(
+        Files.newByteChannel(
+            getPathForRelativePath(root, pathRelativeToProjectRoot),
+            append
+                ? ImmutableSet.of(StandardOpenOption.CREATE, StandardOpenOption.APPEND)
+                : ImmutableSet.of(
+                    StandardOpenOption.CREATE,
+                    StandardOpenOption.TRUNCATE_EXISTING,
+                    StandardOpenOption.WRITE),
+            attrs));
+  }
+
+  /** Writes bytes to a path. */
+  public static void writeBytesToPath(
+      AbsPath root, byte[] bytes, Path pathRelativeToProjectRoot, FileAttribute<?>... attrs)
+      throws IOException {
+    // No need to buffer writes when writing a single piece of data.
+    try (OutputStream outputStream =
+        newUnbufferedFileOutputStream(root, pathRelativeToProjectRoot, /* append */ false, attrs)) {
+      outputStream.write(bytes);
+    }
+  }
+
+  /** Reads a file content if file exists. */
+  public static Optional<String> readFileIfItExists(AbsPath root, Path pathRelativeToProjectRoot) {
+    Path fileToRead = getPathForRelativePath(root, pathRelativeToProjectRoot);
+    return readFileIfItExists(fileToRead, pathRelativeToProjectRoot.toString());
+  }
+
+  /** Reads a file content if file exists. */
+  private static Optional<String> readFileIfItExists(
+      Path fileToRead, String pathRelativeToProjectRoot) {
+    if (Files.isRegularFile(fileToRead)) {
+      String contents;
+      try {
+        contents = Files.readString(fileToRead);
+      } catch (IOException e) {
+        // Alternatively, we could return Optional.empty(), though something seems suspicious if we
+        // have already verified that fileToRead is a file and then we cannot read it.
+        throw new RuntimeException("Error reading " + pathRelativeToProjectRoot, e);
+      }
+      return Optional.of(contents);
+    } else {
+      return Optional.empty();
+    }
+  }
+
+  /**
+   * Converts a path string (or sequence of strings) to a Path with the same VFS as this instance.
+   */
+  public static Path getPath(AbsPath root, String first, String... rest) {
+    return root.getFileSystem().getPath(first, rest);
+  }
+
+  /** Reads a file content as list of lines. */
+  public static List<String> readLines(AbsPath root, Path pathRelativeToProjectRoot)
+      throws IOException {
+    Path file = getPathForRelativePath(root, pathRelativeToProjectRoot);
+    return Files.readAllLines(file, StandardCharsets.UTF_8);
+  }
+
+  /** Copies a file. */
+  public static void copy(AbsPath root, Path source, Path target, CopySourceMode sourceMode)
+      throws IOException {
+    switch (sourceMode) {
+      case FILE:
+        Files.copy(
+            getPathForRelativePath(root, source),
+            getPathForRelativePath(root, target),
+            StandardCopyOption.REPLACE_EXISTING);
+        break;
+      case DIRECTORY_CONTENTS_ONLY:
+        MostFiles.copyRecursively(
+            getPathForRelativePath(root, source), getPathForRelativePath(root, target));
+        break;
+      case DIRECTORY_AND_CONTENTS:
+        MostFiles.copyRecursively(
+            getPathForRelativePath(root, source),
+            getPathForRelativePath(root, target.resolve(source.getFileName())));
+        break;
+    }
+  }
+
+  /** Copies a file. */
+  public static void copyFile(AbsPath root, Path source, Path target) throws IOException {
+    copy(root, source, target, CopySourceMode.FILE);
+  }
+
+  /** Creates a symlink. */
+  public static void createSymLink(AbsPath root, Path symLink, Path realFile, boolean force)
+      throws IOException {
+    symLink = getPathForRelativePath(root, symLink);
+    if (force) {
+      MostFiles.deleteRecursivelyIfExists(symLink);
+    }
+    MorePaths.createSymLink(MorePaths.WIN_FS_INSTANCE, symLink, realFile);
+  }
+
+  /**
+   * Returns the set of POSIX file permissions, or the empty set if the underlying file system does
+   * not support POSIX file attributes.
+   */
+  public static Set<PosixFilePermission> getPosixFilePermissions(
+      AbsPath root, Path pathRelativeToProjectRoot) throws IOException {
+    Path resolvedPath = getPathForRelativePath(root, pathRelativeToProjectRoot);
+    if (Files.getFileAttributeView(resolvedPath, PosixFileAttributeView.class) != null) {
+      return Files.getPosixFilePermissions(resolvedPath);
+    } else {
+      return ImmutableSet.of();
+    }
+  }
+
+  /**
+   * @param root Absolute path that defines a project root
+   * @param buckOut Relative path that defines a buck out directory
+   * @param path Absolute or relative path to the project root.
+   * @return If {@code path} is relative, it is returned. If it is absolute and is inside the
+   *     project root, it is relativized to the project root and returned. Otherwise an absent value
+   *     is returned.
+   */
+  public static Optional<Path> getPathRelativeToProjectRoot(
+      AbsPath root, RelPath buckOut, Path path) {
+    Path normalizedPath = MorePaths.normalize(path);
+    if (normalizedPath.isAbsolute()) {
+      AbsPath pathAbs = AbsPath.of(normalizedPath);
+      AbsPath configuredBuckOut = MorePaths.normalize(root.resolve(buckOut));
+      // If the path is in the configured buck-out, it's also part of the filesystem.
+      if (pathAbs.startsWith(configuredBuckOut) || pathAbs.startsWith(root)) {
+        return Optional.of(MorePaths.relativize(root.getPath(), normalizedPath));
+      } else {
+        return Optional.empty();
+      }
+    } else {
+      return Optional.of(normalizedPath);
+    }
+  }
+
+  /** Walks a project-root relative file tree with a visitor and visit options. */
+  public static void walkRelativeFileTree(
+      AbsPath projectRoot,
+      Path pathRelativeToProjectRoot,
+      EnumSet<FileVisitOption> visitOptions,
+      FileVisitor<Path> fileVisitor,
+      DirectoryStream.Filter<? super Path> ignoreFilter)
+      throws IOException {
+    Path rootPath = getPathForRelativePath(projectRoot, pathRelativeToProjectRoot);
+    Function<Path, Path> pathMapper = path -> relativize(projectRoot, path).getPath();
+    FileVisitor<Path> pathMappingVisitor =
+        new FileVisitor<Path>() {
+          @Override
+          public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
+              throws IOException {
+            return fileVisitor.preVisitDirectory(pathMapper.apply(dir), attrs);
+          }
+
+          @Override
+          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+              throws IOException {
+            return fileVisitor.visitFile(pathMapper.apply(file), attrs);
+          }
+
+          @Override
+          public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
+            return fileVisitor.visitFileFailed(pathMapper.apply(file), exc);
+          }
+
+          @Override
+          public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
+            return fileVisitor.postVisitDirectory(pathMapper.apply(dir), exc);
+          }
+        };
+    walkFileTree(projectRoot, rootPath, visitOptions, pathMappingVisitor, ignoreFilter);
+  }
+
+  /** Returns ignore filter. */
+  public static DirectoryStream.Filter<? super Path> getIgnoreFilter(
+      @Nullable AbsPath projectRoot,
+      boolean skipIgnored,
+      ImmutableCollection<PathMatcher> ignores) {
+    return skipIgnored
+        ? input -> !isIgnored(relativize(projectRoot, input), ignores)
+        : input -> true;
+  }
+
+  public static DirectoryStream.Filter<? super Path> getEmptyIgnoreFilter() {
+    return getIgnoreFilter(null, false, ImmutableSet.of());
+  }
+
+  public static EnumSet<FileVisitOption> getDefaultVisitOptions() {
+    return EnumSet.of(FileVisitOption.FOLLOW_LINKS);
+  }
+
+  public static void walkFileTree(
+      AbsPath root,
+      Path path,
+      Set<FileVisitOption> options,
+      FileVisitor<Path> fileVisitor,
+      DirectoryStream.Filter<? super Path> ignoreFilter)
+      throws IOException {
+    new FileTreeWalker(getPathForRelativePath(root, path), options, fileVisitor, ignoreFilter)
+        .walk();
+  }
+
+  /** Returns relative paths for all files under the given path */
+  public static ImmutableSet<Path> getFilesUnderPath(
+      AbsPath root,
+      Path pathRelativeToProjectRoot,
+      EnumSet<FileVisitOption> visitOptions,
+      DirectoryStream.Filter<? super Path> ignoresFilter)
+      throws IOException {
+    return getFilesUnderPath(
+        root, pathRelativeToProjectRoot, x -> true, visitOptions, ignoresFilter);
+  }
+
+  /** Returns relative paths for all files under the given path */
+  public static ImmutableSet<Path> getFilesUnderPath(
+      AbsPath root,
+      Path pathRelativeToProjectRoot,
+      Predicate<Path> predicate,
+      EnumSet<FileVisitOption> visitOptions,
+      DirectoryStream.Filter<? super Path> ignoresFilter)
+      throws IOException {
+    ImmutableSet.Builder<Path> paths = ImmutableSet.builder();
+    walkRelativeFileTree(
+        root,
+        pathRelativeToProjectRoot,
+        visitOptions,
+        new SimpleFileVisitor<Path>() {
+          @Override
+          public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) {
+            if (predicate.test(path)) {
+              paths.add(path);
+            }
+            return FileVisitResult.CONTINUE;
+          }
+        },
+        ignoresFilter);
+
+    return paths.build();
+  }
+
+  /**
+   * FileTreeWalker is used to walk files similar to Files.walkFileTree.
+   *
+   * <p>It has two major differences from walkFileTree.
+   *
+   * <ol>
+   *   <li>It ignores files and directories ignored by this ProjectFilesystem.
+   *   <li>The walk is in a deterministic order.
+   * </ol>
+   *
+   * <p>And it has three minor differences.
+   *
+   * <ol>
+   *   <li>It doesn't accept a depth limit.
+   *   <li>It doesn't handle the presence of a security manager the same way.
+   *   <li>It skips symlinks which create cycles instead of calling visitFileFailed method with the
+   *       FileSystemLoopException.
+   * </ol>
+   */
+  private static class FileTreeWalker {
+    private final FileVisitor<Path> visitor;
+    private final Path root;
+    private final boolean followLinks;
+    private final ArrayDeque<DirWalkState> state;
+    private final DirectoryStream.Filter<? super Path> ignoreFilter;
+
+    FileTreeWalker(
+        Path root,
+        Set<FileVisitOption> options,
+        FileVisitor<Path> pathFileVisitor,
+        DirectoryStream.Filter<? super Path> ignoreFilter) {
+      this.followLinks = options.contains(FileVisitOption.FOLLOW_LINKS);
+      this.visitor = pathFileVisitor;
+      this.root = root;
+      this.state = new ArrayDeque<>();
+      this.ignoreFilter = ignoreFilter;
+    }
+
+    private ImmutableList<Path> getContents(Path root) throws IOException {
+      try (DirectoryStream<Path> stream = Files.newDirectoryStream(root, ignoreFilter)) {
+        return FluentIterable.from(stream).toSortedList(Comparator.naturalOrder());
+      }
+    }
+
+    private class DirWalkState {
+      private final Path dir;
+      private final BasicFileAttributes attrs;
+      private final boolean isRootSentinel;
+      private UnmodifiableIterator<Path> iter;
+      private @Nullable IOException ioe = null;
+
+      DirWalkState(Path directory, BasicFileAttributes attributes, boolean isRootSentinel) {
+        this.dir = directory;
+        this.attrs = attributes;
+        this.isRootSentinel = isRootSentinel;
+
+        if (isRootSentinel) {
+          this.iter = ImmutableList.of(root).iterator();
+        } else {
+          try {
+            this.iter = getContents(directory).iterator();
+          } catch (IOException e) {
+            this.iter = ImmutableList.<Path>of().iterator();
+            this.ioe = e;
+          }
+        }
+      }
+    }
+
+    private void walk() throws IOException {
+      state.add(new DirWalkState(root, getAttributes(root), true));
+
+      while (true) {
+        FileVisitResult result;
+        if (state.getLast().iter.hasNext()) {
+          result = visitPath(state.getLast().iter.next());
+        } else {
+          DirWalkState dirState = state.removeLast();
+          if (dirState.isRootSentinel) {
+            return;
+          }
+          result = visitor.postVisitDirectory(dirState.dir, dirState.ioe);
+        }
+        Objects.requireNonNull(result, "FileVisitor returned a null FileVisitResult.");
+        if (result == FileVisitResult.SKIP_SIBLINGS) {
+          state.getLast().iter = ImmutableList.<Path>of().iterator();
+        } else if (result == FileVisitResult.TERMINATE) {
+          return;
+        }
+      }
+    }
+
+    private FileVisitResult visitPath(Path p) throws IOException {
+      BasicFileAttributes attrs;
+      try {
+        attrs = getAttributes(p);
+        ensureNoLoops(p, attrs);
+      } catch (FileSystemLoopException ex) {
+        // Skip loop if found
+        return FileVisitResult.CONTINUE;
+      } catch (IOException ioe) {
+        return visitor.visitFileFailed(p, ioe);
+      }
+
+      if (attrs.isDirectory()) {
+        FileVisitResult result = visitor.preVisitDirectory(p, attrs);
+        if (result == FileVisitResult.CONTINUE) {
+          state.add(new DirWalkState(p, attrs, false));
+        }
+        return result;
+      } else {
+        return visitor.visitFile(p, attrs);
+      }
+    }
+
+    private void ensureNoLoops(Path p, BasicFileAttributes attrs) throws FileSystemLoopException {
+      if (!followLinks) {
+        return;
+      }
+      if (!attrs.isDirectory()) {
+        return;
+      }
+      if (willLoop(p, attrs)) {
+        throw new FileSystemLoopException(p.toString());
+      }
+    }
+
+    private boolean willLoop(Path p, BasicFileAttributes attrs) {
+      try {
+        Object thisKey = attrs.fileKey();
+        for (DirWalkState s : state) {
+          if (s.isRootSentinel) {
+            continue;
+          }
+          Object thatKey = s.attrs.fileKey();
+          if (thisKey != null && thatKey != null) {
+            if (thisKey.equals(thatKey)) {
+              return true;
+            }
+          } else if (Files.isSameFile(p, s.dir)) {
+            return true;
+          }
+        }
+      } catch (IOException e) {
+        return true;
+      }
+      return false;
+    }
+
+    private BasicFileAttributes getAttributes(Path root) throws IOException {
+      if (!followLinks) {
+        return Files.readAttributes(root, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+      }
+      try {
+        return Files.readAttributes(root, BasicFileAttributes.class);
+      } catch (IOException e) {
+        return Files.readAttributes(root, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/pathformat/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/pathformat/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/pathformat/BUCK
@@ -0,0 +1,17 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "pathformat",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/pathformat/PathFormatter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/pathformat/PathFormatter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/pathformat/PathFormatter.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.pathformat;
+
+import com.facebook.buck.core.filesystems.PathWrapper;
+import java.nio.file.Path;
+
+/** Utilities to format paths with predictable path separators. */
+public class PathFormatter {
+  /** Utility class: do not instantiate. */
+  private PathFormatter() {}
+
+  public static String pathWithUnixSeparators(String path) {
+    return path.replace('\\', '/');
+  }
+
+  public static String pathWithUnixSeparators(Path path) {
+    return pathWithUnixSeparators(path.toString());
+  }
+
+  public static String pathWithUnixSeparators(PathWrapper path) {
+    return pathWithUnixSeparators(path.getPath());
+  }
+
+  public static String pathWithWindowsSeparators(Path path) {
+    return path.toString().replace('/', '\\');
+  }
+
+  public static String pathWithUnixSeparatorsAndTrailingSlash(Path path) {
+    return pathWithUnixSeparators(path) + "/";
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/BUCK
@@ -0,0 +1,13 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "windowsfs",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = ["prelude//toolchains/android/third-party:jna"],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/WindowsFS.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/WindowsFS.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/WindowsFS.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.windowsfs;
+
+import java.io.IOException;
+import java.nio.file.FileAlreadyExistsException;
+import java.nio.file.Path;
+
+/** Utility class for working with windows FS */
+public class WindowsFS {
+
+  /**
+   * The Windows build we are running could be ones that contain the createSymlink with non
+   * privileged flag support or not.
+   *
+   * <p>The reason for this enum is to keep state as of what Windows version we are using.
+   *
+   * <p>Win 10 Creator added a flag to allow creation of symlink when not elevated. There is no easy
+   * way to distinguish between builds of Win 10. Windows versioning group suggests to code things
+   * in a defensive way, so we can detect the version by a failure and falling to an older API.
+   */
+  enum WindowsPrivilegedApiUsage {
+    Unknown,
+    UseUnprivilegedApi,
+    UsePrivilegedApi
+  }
+
+  private WindowsPrivilegedApiUsage windowsPrivilegedApiStatus = WindowsPrivilegedApiUsage.Unknown;
+
+  /** A POD type that wraps the result of a call to the Java RT createSymbolicLink. */
+  static class NativeCreateSymlinkResult {
+    private final boolean result;
+    private final int errorCode;
+
+    public NativeCreateSymlinkResult(boolean result, int errorCode) {
+      this.result = result;
+      this.errorCode = errorCode;
+    }
+
+    public boolean getResult() {
+      return result;
+    }
+
+    public int getErrorCode() {
+      return errorCode;
+    }
+  }
+
+  /**
+   * Creates a symbolic link (using CreateSymbolicLink winapi call under the hood), passing the
+   * SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE which was introduced in Win 10 Creator that allows
+   * creation of symlinks not assuming elevated execution.
+   *
+   * @param symlink the path of the symbolic link to create
+   * @param target the target of the symbolic link
+   * @param dirLink whether the target is a directory
+   * @return The result of CreateSymbolicLink with the error code for the operation.
+   */
+  private NativeCreateSymlinkResult unPrivilegedCreateSymbolicLink(
+      String symlink, String target, boolean dirLink) {
+    int flags =
+        (dirLink ? WindowsFSLibrary.SYMBOLIC_LINK_FLAG_DIRECTORY : 0)
+            | WindowsFSLibrary.SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
+    boolean created = WindowsFSLibrary.INSTANCE.CreateSymbolicLinkW(symlink, target, flags) != 0;
+    int lastError = WindowsFSLibrary.INSTANCE.GetLastError();
+    return new NativeCreateSymlinkResult(created, lastError);
+  }
+
+  /**
+   * Creates a symbolic link (using CreateSymbolicLink winapi call under the hood), not passing the
+   * SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE, thus assuming this is an elevated execution.
+   *
+   * @param symlink the path of the symbolic link to create
+   * @param target the target of the symbolic link
+   * @param dirLink whether the target is a directory
+   * @return The result of CreateSymbolicLink with the error code for the operation.
+   */
+  private NativeCreateSymlinkResult privilegedCreateSymbolicLink(
+      String symlink, String target, boolean dirLink) {
+    int flags = (dirLink ? WindowsFSLibrary.SYMBOLIC_LINK_FLAG_DIRECTORY : 0);
+    boolean created = WindowsFSLibrary.INSTANCE.CreateSymbolicLinkW(symlink, target, flags) != 0;
+    int lastError = WindowsFSLibrary.INSTANCE.GetLastError();
+    return new NativeCreateSymlinkResult(created, lastError);
+  }
+
+  /**
+   * Creates a symbolic link (using CreateSymbolicLink winapi call under the hood).
+   *
+   * @param symlink the path of the symbolic link to create
+   * @param target the target of the symbolic link
+   * @param dirLink whether the target is a directory
+   * @throws IOException if an underlying system call fails
+   */
+  public void createSymbolicLink(Path symlink, Path target, boolean dirLink) throws IOException {
+    String symlinkPathString = (symlink.isAbsolute() ? "\\\\?\\" : "") + symlink;
+    String targetPathString = (target.isAbsolute() ? "\\\\?\\" : "") + target;
+
+    NativeCreateSymlinkResult nativeResult;
+    boolean failureDueToDevModeNotEnabled = false;
+
+    switch (windowsPrivilegedApiStatus) {
+      case Unknown:
+        // First try creating the symlink using the NON_PRIVILEGED flag.
+        nativeResult = unPrivilegedCreateSymbolicLink(symlinkPathString, targetPathString, dirLink);
+        if (!nativeResult.getResult()
+            && (nativeResult.getErrorCode() == WindowsFSLibrary.INVALID_PARAMETER_ERROR
+                || nativeResult.getErrorCode() == WindowsFSLibrary.ERROR_PRIVILEGE_NOT_HELD)) {
+          // Failed! Try without the NON_PRIVILEGED flag (this requires elevated run).
+          NativeCreateSymlinkResult nativeResultPrivileged =
+              privilegedCreateSymbolicLink(symlinkPathString, targetPathString, dirLink);
+
+          // Set to use the PRIVILEGED call if that succeeds.
+          if (nativeResultPrivileged.getResult()) {
+            nativeResult = nativeResultPrivileged;
+            windowsPrivilegedApiStatus = WindowsPrivilegedApiUsage.UsePrivilegedApi;
+          } else if (nativeResult.getErrorCode() == WindowsFSLibrary.ERROR_PRIVILEGE_NOT_HELD) {
+            // Failed to used non-privileged API! The Developer Mode not enabled.
+            failureDueToDevModeNotEnabled = true;
+          }
+        } else {
+          // Success for using the non privileged API - it is there and it is enabled.
+          // From now on use the NON_PRIVILEGED flag only.
+          windowsPrivilegedApiStatus = WindowsPrivilegedApiUsage.UseUnprivilegedApi;
+        }
+        break;
+      case UseUnprivilegedApi:
+        nativeResult = unPrivilegedCreateSymbolicLink(symlinkPathString, targetPathString, dirLink);
+        break;
+      case UsePrivilegedApi:
+        nativeResult = privilegedCreateSymbolicLink(symlinkPathString, targetPathString, dirLink);
+        break;
+      default:
+        nativeResult = new NativeCreateSymlinkResult(false, -1);
+        assert false : "Invalid WindowsPrivilegedApiUsage value!";
+    }
+
+    if (!nativeResult.getResult()) {
+      if (nativeResult.getErrorCode() == WindowsFSLibrary.ERROR_ALREADY_EXISTS) {
+        throw new FileAlreadyExistsException(symlinkPathString);
+      }
+
+      String message =
+          "Tried to link "
+              + symlinkPathString
+              + " to "
+              + targetPathString
+              + " (winapi error: "
+              + nativeResult.getErrorCode()
+              + ", API used: "
+              + windowsPrivilegedApiStatus
+              + ")";
+
+      if (failureDueToDevModeNotEnabled) {
+        message +=
+            ". You seem to be running Win 10 Creator or later OS with no Developer Mode"
+                + " enabled.\r\n"
+                + " Please enable Developer Mode for non-privileged symlink creation to work.\r\n"
+                + " Running Buck in elevated mode will also allow symlink creation.";
+      } else if (windowsPrivilegedApiStatus == WindowsPrivilegedApiUsage.Unknown
+          && nativeResult.getErrorCode() == WindowsFSLibrary.INVALID_PARAMETER_ERROR) {
+        message +=
+            ". You are running an OS earlier than Windows 10 Creator. Either upgrade to a\r\n"
+                + "post-Creator version and enable Developer Mode, or run Buck in elevated mode\r\n"
+                + "for symlink creation to work.\r\n"
+                + "See https://dev.buck.build/setup/getting_started.html for more details.";
+      }
+      throw new IOException(message);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/WindowsFSLibrary.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/WindowsFSLibrary.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/io/windowsfs/WindowsFSLibrary.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.io.windowsfs;
+
+import com.sun.jna.Library;
+import com.sun.jna.Native;
+import com.sun.jna.win32.W32APIOptions;
+
+/** Utility class to bridge native windows FS calls to Java using JNA. */
+public interface WindowsFSLibrary extends Library {
+  WindowsFSLibrary INSTANCE =
+      Native.loadLibrary("kernel32", WindowsFSLibrary.class, W32APIOptions.UNICODE_OPTIONS);
+
+  int SYMBOLIC_LINK_FLAG_DIRECTORY = 1;
+  int SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 2;
+
+  // Native Windows error codes.
+  int INVALID_PARAMETER_ERROR = 87;
+  int ERROR_ALREADY_EXISTS = 183;
+  int ERROR_PRIVILEGE_NOT_HELD = 1314;
+
+  /*
+   * The CreateSymbolicLinkW API on Windows returns
+   * a BOOLEAN, which is really a byte in Java (8 bit numeric value).
+   * At the JVM level, boolean, byte, short, char, and int are all treated as ints, and boolean is
+   * indeed represented as 0 and 1. The API is successful if the return value is not 0.
+   * So, returning 0xD0 should be a success, but the 0th bit is not set and Java will interpret this
+   * as boolean false. This is fixed by making the function imported from native as a byte return
+   * and compering the return value explicitly to 0.
+   *
+   * @param lpSymlinkFileName The new symlink name.
+   * @param lpTargetFileName The existing file to link into.
+   * @param dwFlags Whether it is a directiory.
+   * @return Anh 8 bit integer which is interpreted as success if not 0, and failure as 0.
+   */
+  byte CreateSymbolicLinkW(String lpSymlinkFileName, String lpTargetFileName, int dwFlags);
+
+  int GetLastError();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/AbiDirWriter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/AbiDirWriter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/AbiDirWriter.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Enumeration;
+import java.util.Objects;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AbiDirWriter {
+
+  public static void writeAbiOutputDir(Path existingAbi, Path outputDir) throws IOException {
+    try (ZipFile zipFile = new ZipFile(existingAbi.toFile())) {
+      Enumeration<? extends ZipEntry> entries = zipFile.entries();
+      while (entries.hasMoreElements()) {
+        ZipEntry zipEntry = entries.nextElement();
+        if (!zipEntry.isDirectory()) {
+          Path abiDirSubPath = outputDir.resolve(zipEntry.getName());
+          Files.createDirectories(Objects.requireNonNull(abiDirSubPath.getParent()));
+          Files.writeString(abiDirSubPath, Long.toHexString(zipEntry.getCrc()));
+        }
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/AbiStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/AbiStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/AbiStepsBuilder.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.CompileToJarStepFactory;
+import com.facebook.buck.jvm.java.CompilerOutputPathsValue;
+import com.facebook.buck.jvm.java.JarParameters;
+import com.facebook.buck.jvm.java.ResolvedJavac;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import org.jetbrains.annotations.Nullable;
+
+/** Builder that creates abi jar steps. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface AbiStepsBuilder extends CompileStepsBuilder {
+
+  void addBuildStepsForAbi(
+      AbiGenerationMode abiCompatibilityMode,
+      AbiGenerationMode abiGenerationMode,
+      boolean isRequiredForSourceOnlyAbi,
+      boolean trackClassUsage,
+      RelPath buckOut,
+      BuildTargetValue buildTargetValue,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      ImmutableList<RelPath> compileTimeClasspathPaths,
+      ImmutableSortedSet<RelPath> javaSrcs,
+      ImmutableMap<RelPath, RelPath> resourcesMap,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters,
+      AbsPath buildCellRootPath,
+      ResolvedJavac resolvedJavac,
+      CompileToJarStepFactory.ExtraParams extraParams);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/BUCK
@@ -0,0 +1,36 @@
+load(
+    "@prelude//toolchains/android/tools:build_rules.bzl",
+    "buck_java_library",
+)
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "cd",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "prelude//toolchains/android/meta_only/src/com/facebook/buck/jvm/remote_worker/...",
+        "prelude//toolchains/android/src/com/facebook/buck/...",
+        "prelude//toolchains/android/test/com/facebook/buck/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:cd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:kotlincd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:command",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:serialization",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java:java",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/workertool:workertool",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api:api",
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps/java:java",
+        "prelude//toolchains/android/src/com/facebook/buck/util/json:json",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/BuildCommandStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/BuildCommandStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/BuildCommandStepsBuilder.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface BuildCommandStepsBuilder {
+
+  ImmutableList<IsolatedStep> getSteps();
+
+  AbsPath getRuleCellRoot();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompileStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompileStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompileStepsBuilder.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+
+/** Builder for java compilation steps. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface CompileStepsBuilder {
+
+  ImmutableList<IsolatedStep> buildIsolatedSteps();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompileStepsBuilderFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompileStepsBuilderFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompileStepsBuilderFactory.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.infer.annotation.Nullsafe;
+
+/** Factory that creates {@link CompileStepsBuilder} instances */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface CompileStepsBuilderFactory {
+
+  /** Creates an appropriate {@link LibraryStepsBuilder} instance */
+  LibraryStepsBuilder getLibraryBuilder();
+
+  /** Creates an appropriate {@link AbiStepsBuilder} instance */
+  AbiStepsBuilder getAbiBuilder();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompilerDaemonLoggerUtil.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompilerDaemonLoggerUtil.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompilerDaemonLoggerUtil.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.logging.ConsoleHandler;
+import java.util.logging.FileHandler;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.SimpleFormatter;
+
+/** Utility class for setting up default logger for compiler daemon worker tool. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class CompilerDaemonLoggerUtil {
+  static {
+    // set java.util.logging (JUL) simple formatter to 1 liner.
+    System.setProperty(
+        "java.util.logging.SimpleFormatter.format",
+        "[%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS] [%4$s] %3$s - %5$s%6$s%n");
+  }
+
+  private static final Level DEFALUT_LOG_LEVEL = Level.INFO;
+
+  public static void setDefaultLogger(String logFilePrefix, String logPath) throws IOException {
+    setDefaultLogger(logFilePrefix, logPath, DEFALUT_LOG_LEVEL);
+  }
+
+  /**
+   * Sets default logger for compiler daemon worker tool.
+   *
+   * @param logFilePrefix prefix for log file name
+   * @param logPath path to store log files
+   * @param logLevel log level
+   * @throws IOException if failed to create log file
+   */
+  public static void setDefaultLogger(String logFilePrefix, String logPath, Level logLevel)
+      throws IOException {
+    String logFileName =
+        String.format(
+            "%s/%s_%s_%s.log",
+            logPath,
+            logFilePrefix,
+            new SimpleDateFormat("yyyyMMdd_HHmmss_SSS").format(new Date().getTime()),
+            UUID.randomUUID().toString().substring(0, 8));
+    Files.createDirectories(Objects.requireNonNull(Paths.get(logFileName).getParent()));
+    FileHandler fileHandler = new FileHandler(logFileName);
+    fileHandler.setFormatter(new SimpleFormatter());
+    fileHandler.setLevel(logLevel);
+    Logger.get("").addHandler(fileHandler);
+  }
+
+  /**
+   * Sets console handler log level to given level.
+   *
+   * @param level
+   */
+  public static void setConsoleHandlerLogLevelTo(Level level) {
+    for (Handler handler : Logger.get("").getHandlers()) {
+      if (handler instanceof ConsoleHandler) {
+        handler.setLevel(level);
+        break;
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompilerDaemonRunner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompilerDaemonRunner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/CompilerDaemonRunner.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.jvm.cd.workertool.MainUtils;
+import com.facebook.buck.step.StepExecutionResult;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.step.isolatedsteps.IsolatedStepsRunner;
+import com.facebook.buck.util.ClassLoaderCache;
+import com.facebook.buck.util.Console;
+import com.facebook.buck.util.Verbosity;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Holds state needed to execute compilation commands. Can be used for a single command or stored
+ * and re-used by a worker tool.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class CompilerDaemonRunner implements Closeable {
+  private final OutputStream eventsOutputStream;
+  private final ClassLoaderCache classLoaderCache;
+  private final Console console;
+
+  private static final List<String> COMPILER_ERRORS =
+      List.of(
+          "Failed to execute isolated step <kotlinc>", "Failed to execute isolated step <javac>");
+
+  static {
+    // On macOS, this will suppress the Dock icon if any libraries try to use AWT somewhere.
+    // We've seen this occasionally occur with kotlinc
+    System.setProperty("apple.awt.UIElement", "true");
+    // To prevent "Can't connect to X11 window server" errors seen on some linux hosts.
+    System.setProperty("java.awt.headless", "true");
+  }
+
+  public CompilerDaemonRunner(OutputStream eventsOutputStream, Console console) {
+    this.eventsOutputStream = eventsOutputStream;
+    this.classLoaderCache = new ClassLoaderCache();
+    this.console = console;
+  }
+
+  @Override
+  public void close() throws IOException {
+    eventsOutputStream.close();
+    classLoaderCache.close();
+  }
+
+  private class CommandExecutionContext implements Closeable {
+    IsolatedExecutionContext executionContext;
+
+    public CommandExecutionContext(JvmCDCommand command) {
+      this.executionContext =
+          IsolatedExecutionContext.of(
+              classLoaderCache, console, command.getBuildCommand().getRuleCellRoot());
+    }
+
+    @Override
+    public void close() throws IOException {
+      executionContext.close();
+    }
+  }
+
+  /** Execute a single build command */
+  public StepExecutionResult execute(JvmCDCommand command) throws IOException {
+    try (CommandExecutionContext context = new CommandExecutionContext(command)) {
+      ImmutableList<IsolatedStep> steps = command.getBuildCommand().getSteps();
+      return IsolatedStepsRunner.executeWithDefaultExceptionHandling(
+          steps, context.executionContext);
+    }
+  }
+
+  /** Create a new runner, execute a single build command, close it and return */
+  public static void run(JvmCDCommand command) throws IOException {
+    Verbosity verbosity = getVerbosityForLevel(command.getLoggingLevel());
+    Console console = new Console(verbosity, System.out, System.err);
+
+    Thread.setDefaultUncaughtExceptionHandler(
+        (t, e) -> MainUtils.handleExceptionAndTerminate(t, console, e));
+
+    if (verbosity.shouldPrintStandardInformation()) {
+      Executors.newSingleThreadScheduledExecutor()
+          .scheduleAtFixedRate(MainUtils::logCurrentCDState, 1, 10, TimeUnit.SECONDS);
+    }
+    try (CompilerDaemonRunner runner =
+        new CompilerDaemonRunner(OutputStream.nullOutputStream(), console)) {
+      StepExecutionResult stepExecutionResult = runner.execute(command);
+
+      if (!stepExecutionResult.isSuccess()) {
+        String errorMessage = stepExecutionResult.getErrorMessage();
+        System.err.println(errorMessage);
+        // if there is a compiling error, we don't want to print buck stack trace
+        if (!CompilerDaemonRunner.isCompilerError(errorMessage)) {
+          stepExecutionResult.getCause().ifPresent(Throwable::printStackTrace);
+        }
+        throw new RuntimeException(
+            "Compiler Daemon failed to execute command. Exit code: "
+                + stepExecutionResult.getExitCode());
+      }
+    }
+  }
+
+  public static boolean isCompilerError(String errorMessage) {
+    return COMPILER_ERRORS.stream().anyMatch(errorMessage::contains);
+  }
+
+  private static Verbosity getVerbosityForLevel(int loggingLevel) {
+    if (loggingLevel >= 8) {
+      return Verbosity.ALL;
+    } else if (loggingLevel >= 5) {
+      return Verbosity.COMMANDS_AND_OUTPUT;
+    } else if (loggingLevel >= 4) {
+      return Verbosity.COMMANDS_AND_SPECIAL_OUTPUT;
+    } else if (loggingLevel >= 3) {
+      return Verbosity.COMMANDS;
+    } else if (loggingLevel >= 2) {
+      return Verbosity.BINARY_OUTPUTS;
+    } else if (loggingLevel >= 1) {
+      return Verbosity.STANDARD_INFORMATION;
+    } else {
+      return Verbosity.SILENT;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultAbiStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultAbiStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultAbiStepsBuilder.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.CompileToJarStepFactory;
+import com.facebook.buck.jvm.java.CompilerOutputPathsValue;
+import com.facebook.buck.jvm.java.CompilerParameters;
+import com.facebook.buck.jvm.java.JarParameters;
+import com.facebook.buck.jvm.java.ResolvedJavac;
+import com.facebook.buck.step.isolatedsteps.common.MakeCleanDirectoryIsolatedStep;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import org.jetbrains.annotations.Nullable;
+
+/** Default implementation of {@link AbiStepsBuilder} */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+class DefaultAbiStepsBuilder<T extends CompileToJarStepFactory.ExtraParams>
+    extends DefaultCompileStepsBuilderBase<T> implements AbiStepsBuilder {
+
+  DefaultAbiStepsBuilder(CompileToJarStepFactory<T> configuredCompiler) {
+    super(configuredCompiler);
+  }
+
+  @Override
+  public void addBuildStepsForAbi(
+      AbiGenerationMode abiCompatibilityMode,
+      AbiGenerationMode abiGenerationMode,
+      boolean isRequiredForSourceOnlyAbi,
+      boolean trackClassUsage,
+      RelPath buckOut,
+      BuildTargetValue buildTargetValue,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      ImmutableList<RelPath> compileTimeClasspathPaths,
+      ImmutableSortedSet<RelPath> javaSrcs,
+      ImmutableMap<RelPath, RelPath> resourcesMap,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters,
+      AbsPath buildCellRootPath,
+      ResolvedJavac resolvedJavac,
+      CompileToJarStepFactory.ExtraParams extraParams) {
+
+    stepsBuilder.addAll(
+        MakeCleanDirectoryIsolatedStep.of(
+            compilerOutputPathsValue.getByType(buildTargetValue.getType()).getWorkingDirectory()));
+
+    CompilerParameters compilerParameters =
+        JavaLibraryRules.getCompilerParameters(
+            compileTimeClasspathPaths,
+            ImmutableList.of(),
+            javaSrcs,
+            buildTargetValue.getFullyQualifiedName(),
+            trackClassUsage,
+            abiGenerationMode,
+            abiCompatibilityMode,
+            isRequiredForSourceOnlyAbi,
+            compilerOutputPathsValue.getByType(buildTargetValue.getType()));
+
+    configuredCompiler.createCompileToJarStep(
+        buckOut,
+        buildCellRootPath,
+        buildTargetValue,
+        compilerOutputPathsValue,
+        compilerParameters,
+        abiJarParameters,
+        libraryJarParameters,
+        stepsBuilder,
+        resourcesMap,
+        resolvedJavac,
+        null,
+        configuredCompiler.castExtraParams(extraParams));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultCompileStepsBuilderBase.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultCompileStepsBuilderBase.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultCompileStepsBuilderBase.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.jvm.java.CompileToJarStepFactory;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+
+/** Creates a list of {@link IsolatedStep} that is ready for in process execute. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+abstract class DefaultCompileStepsBuilderBase<T extends CompileToJarStepFactory.ExtraParams>
+    implements CompileStepsBuilder {
+
+  protected final ImmutableList.Builder<IsolatedStep> stepsBuilder = ImmutableList.builder();
+  protected final CompileToJarStepFactory<T> configuredCompiler;
+
+  DefaultCompileStepsBuilderBase(CompileToJarStepFactory<T> configuredCompiler) {
+    this.configuredCompiler = configuredCompiler;
+  }
+
+  @Override
+  public final ImmutableList<IsolatedStep> buildIsolatedSteps() {
+    return stepsBuilder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultCompileStepsBuilderFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultCompileStepsBuilderFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultCompileStepsBuilderFactory.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.jvm.java.CompileToJarStepFactory;
+import com.facebook.infer.annotation.Nullsafe;
+
+/**
+ * Factory that creates {@link CompileStepsBuilder } builders instances that returns steps that is
+ * ready to be executed in the current process.
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class DefaultCompileStepsBuilderFactory<T extends CompileToJarStepFactory.ExtraParams>
+    implements CompileStepsBuilderFactory {
+
+  private final CompileToJarStepFactory<T> configuredCompiler;
+
+  public DefaultCompileStepsBuilderFactory(CompileToJarStepFactory<T> configuredCompiler) {
+    this.configuredCompiler = configuredCompiler;
+  }
+
+  /** Creates an appropriate {@link LibraryStepsBuilder} instance */
+  @Override
+  public LibraryStepsBuilder getLibraryBuilder() {
+    return new DefaultLibraryStepsBuilder<>(configuredCompiler);
+  }
+
+  /** Creates an appropriate {@link AbiStepsBuilder} instance */
+  @Override
+  public AbiStepsBuilder getAbiBuilder() {
+    return new DefaultAbiStepsBuilder<>(configuredCompiler);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultLibraryStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultLibraryStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DefaultLibraryStepsBuilder.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.ActionMetadata;
+import com.facebook.buck.jvm.java.CompileToJarStepFactory;
+import com.facebook.buck.jvm.java.CompilerOutputPathsValue;
+import com.facebook.buck.jvm.java.CompilerParameters;
+import com.facebook.buck.jvm.java.JarParameters;
+import com.facebook.buck.jvm.java.ResolvedJavac;
+import com.facebook.buck.step.isolatedsteps.common.MakeCleanDirectoryIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.java.MakeMissingOutputsStep;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import org.jetbrains.annotations.Nullable;
+
+/** Default implementation of {@link LibraryStepsBuilder} */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+class DefaultLibraryStepsBuilder<T extends CompileToJarStepFactory.ExtraParams>
+    extends DefaultCompileStepsBuilderBase<T> implements LibraryStepsBuilder {
+
+  DefaultLibraryStepsBuilder(CompileToJarStepFactory<T> configuredCompiler) {
+    super(configuredCompiler);
+  }
+
+  @Override
+  public void addMakeMissingOutputsStep(RelPath annotationsPath) {
+    stepsBuilder.add(new MakeMissingOutputsStep(annotationsPath));
+  }
+
+  @Override
+  public void addBuildStepsForLibrary(
+      AbiGenerationMode abiCompatibilityMode,
+      AbiGenerationMode abiGenerationMode,
+      boolean isRequiredForSourceOnlyAbi,
+      boolean trackClassUsage,
+      RelPath buckOut,
+      BuildTargetValue buildTargetValue,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      ImmutableList<RelPath> compileTimeClasspathPaths,
+      ImmutableList<RelPath> compileTimeClasspathSnapshotPaths,
+      ImmutableSortedSet<RelPath> javaSrcs,
+      ImmutableMap<RelPath, RelPath> resourcesMap,
+      @Nullable JarParameters libraryJarParameters,
+      AbsPath buildCellRootPath,
+      ResolvedJavac resolvedJavac,
+      @Nullable ActionMetadata actionMetadata,
+      CompileToJarStepFactory.ExtraParams extraParams) {
+
+    CompilerParameters compilerParameters =
+        JavaLibraryRules.getCompilerParameters(
+            compileTimeClasspathPaths,
+            compileTimeClasspathSnapshotPaths,
+            javaSrcs,
+            buildTargetValue.getFullyQualifiedName(),
+            trackClassUsage,
+            abiGenerationMode,
+            abiCompatibilityMode,
+            isRequiredForSourceOnlyAbi,
+            compilerOutputPathsValue.getByType(buildTargetValue.getType()));
+
+    stepsBuilder.addAll(
+        MakeCleanDirectoryIsolatedStep.of(
+            compilerOutputPathsValue.getByType(buildTargetValue.getType()).getWorkingDirectory()));
+
+    configuredCompiler.createCompileToJarStep(
+        buckOut,
+        buildCellRootPath,
+        buildTargetValue,
+        compilerOutputPathsValue,
+        compilerParameters,
+        null,
+        libraryJarParameters,
+        stepsBuilder,
+        resourcesMap,
+        resolvedJavac,
+        actionMetadata,
+        configuredCompiler.castExtraParams(extraParams));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DepFileUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DepFileUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/DepFileUtils.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.util.json.ObjectMappers;
+import com.facebook.infer.annotation.Nullsafe;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedMap;
+import com.google.common.collect.ImmutableSortedSet;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class DepFileUtils {
+
+  /** Maps used-classes.json files to a dep-file that can be used by buck2. */
+  public static void usedClassesToDepFile(
+      List<Path> usedClassesMapPaths,
+      Path depFileOutput,
+      Map<Path, Path> jarToJarDirMap,
+      boolean append)
+      throws IOException {
+    List<Path> allUsedPaths = new ArrayList<>();
+    for (Path usedClassesMapPath : usedClassesMapPaths) {
+      ImmutableMap<Path, Set<Path>> usedClassesMap =
+          ObjectMappers.readValue(usedClassesMapPath, new TypeReference<>() {});
+
+      for (Map.Entry<Path, Set<Path>> usedClassesEntry : usedClassesMap.entrySet()) {
+        Path usedJarPath = usedClassesEntry.getKey();
+        Path usedJarDir = jarToJarDirMap.get(usedJarPath);
+        if (usedJarDir == null) {
+          allUsedPaths.add(usedJarPath);
+        } else {
+          for (Path usedClass : usedClassesEntry.getValue()) {
+            allUsedPaths.add(usedJarDir.resolve(usedClass));
+          }
+        }
+      }
+    }
+
+    if (append && Files.exists(depFileOutput)) {
+      Files.readAllLines(depFileOutput).stream().forEach(path -> allUsedPaths.add(Paths.get(path)));
+    }
+
+    Files.write(
+        depFileOutput,
+        allUsedPaths.stream().map(Path::toString).distinct().sorted().collect(Collectors.toList()));
+  }
+
+  /**
+   * Maps used-classes.json files to a used-jars.json that can be used to remove unused
+   * dependencies.
+   */
+  public static void usedClassesToUsedJars(
+      List<Path> usedClassesJsonPaths, Path usedJarsFileOutput, boolean append) throws IOException {
+    Map<Path, List<Path>> usedJarsToClasses = new TreeMap<>();
+
+    if (append && Files.exists(usedJarsFileOutput)) {
+      Map<Path, List<Path>> existingEntries =
+          ObjectMappers.readValue(usedJarsFileOutput, new TypeReference<>() {});
+      usedJarsToClasses.putAll(existingEntries);
+    }
+
+    // Merge multiple used-classes.json files into a single map of jar to classes
+    for (Path usedClassesJsonPath : usedClassesJsonPaths) {
+      ImmutableMap<Path, Set<Path>> usedClassesMap =
+          ObjectMappers.readValue(usedClassesJsonPath, new TypeReference<>() {});
+
+      usedClassesMap.forEach(
+          (usedJarPath, classes) -> {
+            usedJarsToClasses.computeIfAbsent(usedJarPath, k -> new ArrayList<>()).addAll(classes);
+          });
+    }
+
+    ObjectMappers.WRITER.writeValue(
+        usedJarsFileOutput.toFile(),
+        usedJarsToClasses.entrySet().stream()
+            .collect(
+                ImmutableSortedMap.toImmutableSortedMap(
+                    Comparator.naturalOrder(),
+                    Map.Entry::getKey,
+                    v -> ImmutableSortedSet.copyOf(v.getValue()))));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/ErrorInterceptor.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/ErrorInterceptor.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/ErrorInterceptor.java
@@ -0,0 +1,391 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.File;
+import java.io.PrintStream;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * A PrintStream implementation that intercepts stderr output and applies syntax highlighting to
+ * compiler messages based on the file type
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ErrorInterceptor extends PrintStream {
+
+  private static final String RED = "\033[91m";
+  private static final String YELLOW = "\033[93m";
+  private static final String GREEN = "\033[92m";
+  private static final String MAGENTA = "\033[95m";
+  private static final String BLUE = "\033[94m";
+  private static final String BOLD = "\033[1m";
+  private static final String RESET = "\033[0m";
+
+  // Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
+  private static final String[] JAVA_KEYWORDS = {
+    "abstract",
+    "assert",
+    "boolean",
+    "break",
+    "byte",
+    "case",
+    "catch",
+    "char",
+    "class",
+    "const",
+    "continue",
+    "default",
+    "do",
+    "double",
+    "else",
+    "enum",
+    "extends",
+    "final",
+    "finally",
+    "float",
+    "for",
+    "goto",
+    "if",
+    "implements",
+    "import",
+    "instanceof",
+    "int",
+    "interface",
+    "long",
+    "native",
+    "new",
+    "package",
+    "private",
+    "protected",
+    "public",
+    "return",
+    "short",
+    "static",
+    "strictfp",
+    "super",
+    "switch",
+    "synchronized",
+    "this",
+    "throw",
+    "throws",
+    "transient",
+    "try",
+    "void",
+    "volatile",
+    "while",
+    "null",
+    "true",
+    "false",
+    "record",
+    "sealed",
+    "permits",
+    "non-sealed",
+    "var"
+  };
+
+  // Source: https://kotlinlang.org/docs/keyword-reference.html
+  private static final String[] KOTLIN_KEYWORDS = {
+    "as",
+    "as?",
+    "break",
+    "class",
+    "continue",
+    "do",
+    "else",
+    "false",
+    "for",
+    "fun",
+    "if",
+    "in",
+    "!in",
+    "interface",
+    "is",
+    "!is",
+    "null",
+    "object",
+    "package",
+    "return",
+    "super",
+    "this",
+    "throw",
+    "true",
+    "try",
+    "typealias",
+    "val",
+    "var",
+    "when",
+    "while",
+    "by",
+    "catch",
+    "constructor",
+    "delegate",
+    "dynamic",
+    "field",
+    "file",
+    "finally",
+    "get",
+    "import",
+    "init",
+    "param",
+    "property",
+    "receiver",
+    "set",
+    "setparam",
+    "where",
+    "actual",
+    "abstract",
+    "annotation",
+    "companion",
+    "const",
+    "crossinline",
+    "data",
+    "enum",
+    "expect",
+    "external",
+    "final",
+    "infix",
+    "inline",
+    "inner",
+    "internal",
+    "lateinit",
+    "noinline",
+    "open",
+    "operator",
+    "out",
+    "override",
+    "private",
+    "protected",
+    "public",
+    "reified",
+    "sealed",
+    "suspend",
+    "tailrec",
+    "vararg",
+    "field",
+    "it"
+  };
+
+  private static final Pattern ERROR_PATTERN =
+      Pattern.compile("\\berror\\b(:.*?\\n)((?:.*?\\n)+?\\s*)(\\^+)\\n", Pattern.CASE_INSENSITIVE);
+  private static final Pattern WARNING_PATTERN =
+      Pattern.compile("\\bwarning\\b(:.*?)\\n", Pattern.CASE_INSENSITIVE);
+  private static final Pattern JAVA_FILE_PATTERN =
+      Pattern.compile("(?:\\x1b\\[[0-9;]*m)*(/?(?:[\\w-]+/)*[\\w-]+\\.java)\\b:(\\d+):");
+  private static final Pattern KOTLIN_FILE_PATTERN =
+      Pattern.compile("(?:\\x1b\\[[0-9;]*m)*(/?(?:[\\w-]+/)*[\\w-]+\\.kt)\\b:(\\d+):(\\d+):");
+
+  /** Enum representing supported file types with their associated patterns and keywords. */
+  public enum FileType {
+    JAVA(JAVA_FILE_PATTERN, JAVA_KEYWORDS),
+    KOTLIN(KOTLIN_FILE_PATTERN, KOTLIN_KEYWORDS),
+    UNKNOWN(null, new String[0]);
+
+    @Nullable private final Pattern filePattern;
+    private final String[] keywords;
+
+    FileType(@Nullable Pattern filePattern, String[] keywords) {
+      this.filePattern = filePattern;
+      this.keywords = keywords;
+    }
+
+    /** Null for {@link #UNKNOWN}, which by definition matches no file. */
+    @Nullable
+    public Pattern getFilePattern() {
+      return filePattern;
+    }
+
+    public String[] getKeywords() {
+      return keywords;
+    }
+  }
+
+  public ErrorInterceptor() {
+    super(System.err);
+  }
+
+  @Override
+  public void print(@Nullable String message) {
+    super.print(prettyPrint(message));
+  }
+
+  @Nullable
+  public static String prettyPrint(@Nullable String exception) {
+    if (exception == null || exception.isEmpty()) {
+      return exception;
+    }
+
+    if (System.getenv("NO_COLOR") != null) {
+      return exception;
+    }
+
+    FileType fileType = determineFileType(exception);
+
+    switch (fileType) {
+      case JAVA:
+        return prettyPrintJavaException(exception);
+      case KOTLIN:
+        return prettyPrintKotlinException(exception);
+      default:
+        return exception;
+    }
+  }
+
+  // Creates a clickable hyperlink in the terminal using OSC 8 escape sequences.
+  // Supports both VS Code and Android Studio links based on ANDROID_EDITOR environment variable.
+  private static String createHyperlink(String file, int line, String text) {
+    // Keep in sync with fbcode/buck2/prelude/java/tools/utils.py
+    boolean isVsCode =
+        "vscode".equals(System.getenv("TERM_PROGRAM"))
+            || "od".equals(System.getenv("FBVSCODE_REMOTE_ENV_NAME"));
+
+    boolean isHyperlinkDisabled =
+        new File(System.getProperty("user.home") + "/.disable_buck_jvm_path_hyperlink").exists();
+
+    if (isVsCode || isHyperlinkDisabled) {
+      return text;
+    }
+
+    String OSC = "\033]";
+    String ST = "\033\\";
+    String uri;
+
+    boolean isJetBrains =
+        System.getenv("ANDROID_EDITOR") != null
+            || new File(
+                    System.getProperty("user.home")
+                        + "/.jetbrains-fb/.buck_path_hyperlink_uses_jetbrains")
+                .isFile();
+
+    if (isJetBrains) {
+      uri = "fb-ide-opener://open/?ide=intellij&filepath=/fbsource/" + file + "&line=" + line;
+    } else {
+      uri =
+          "https://www.internalfb.com/intern/nuclide/open/arc/?project=fbsource&paths[0]="
+              + file
+              + "&lines[0]="
+              + line;
+    }
+
+    return OSC + "8;;" + uri + ST + text + OSC + "8;;" + ST;
+  }
+
+  private static FileType determineFileType(String exception) {
+    for (FileType type : FileType.values()) {
+      Pattern filePattern = type.getFilePattern();
+      if (filePattern != null && filePattern.matcher(exception).find()) {
+        return type;
+      }
+    }
+
+    // Default to "UNKNOWN" if file type cannot be determined
+    return FileType.UNKNOWN;
+  }
+
+  private static String prettyPrintJavaException(String exception) {
+    exception =
+        colorizePattern(
+            ERROR_PATTERN, exception, match -> highlightError(match, FileType.JAVA.getKeywords()));
+    exception = colorizePattern(WARNING_PATTERN, exception, ErrorInterceptor::highlightWarning);
+    exception = colorizePattern(JAVA_FILE_PATTERN, exception, ErrorInterceptor::highlightJavaFile);
+    return exception;
+  }
+
+  private static String prettyPrintKotlinException(String exception) {
+    exception =
+        colorizePattern(
+            ERROR_PATTERN,
+            exception,
+            match -> highlightError(match, FileType.KOTLIN.getKeywords()));
+    exception = colorizePattern(WARNING_PATTERN, exception, ErrorInterceptor::highlightWarning);
+    exception =
+        colorizePattern(KOTLIN_FILE_PATTERN, exception, ErrorInterceptor::highlightKotlinFile);
+    return exception;
+  }
+
+  /**
+   * Applies a colorizer function to all matches of a pattern in a string.
+   *
+   * @param pattern The pattern to match
+   * @param message The string to search
+   * @param colorizer The function to apply to each match
+   * @return The colorized string
+   */
+  private static String colorizePattern(
+      Pattern pattern, String message, Function<Matcher, String> colorizer) {
+    Matcher matcher = pattern.matcher(message);
+    StringBuffer result = new StringBuffer();
+    while (matcher.find()) {
+      String replacement = colorizer.apply(matcher);
+      matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
+    }
+    matcher.appendTail(result);
+    return result.toString();
+  }
+
+  private static String highlightError(Matcher match, String[] keywords) {
+    return RED
+        + "error"
+        + RESET
+        + BOLD
+        + match.group(1)
+        + RESET
+        + highlightCode(Objects.requireNonNull(match.group(2)), keywords)
+        + RED
+        + match.group(3)
+        + RESET
+        + "\n";
+  }
+
+  private static String highlightWarning(Matcher match) {
+    return YELLOW + "warning" + RESET + BOLD + match.group(1) + RESET + "\n";
+  }
+
+  private static String highlightJavaFile(Matcher match) {
+    String file = Objects.requireNonNull(match.group(1));
+    int line = Integer.parseInt(Objects.requireNonNull(match.group(2)));
+
+    return GREEN
+        + createHyperlink(file, line, file)
+        + RESET
+        + ":"
+        + MAGENTA
+        + match.group(2)
+        + RESET
+        + ":";
+  }
+
+  private static String highlightKotlinFile(Matcher match) {
+    String file = Objects.requireNonNull(match.group(1));
+    int line = Integer.parseInt(Objects.requireNonNull(match.group(2)));
+
+    return GREEN
+        + createHyperlink(file, line, file)
+        + RESET
+        + ":"
+        + MAGENTA
+        + match.group(2)
+        + RESET
+        + ":"
+        + MAGENTA
+        + match.group(3)
+        + RESET
+        + ":";
+  }
+
+  private static String highlightCode(String code, String[] keywords) {
+    return code.replaceAll("\\b(" + String.join("|", keywords) + ")\\b", BLUE + "$1" + RESET);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/JavaLibraryRules.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/JavaLibraryRules.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/JavaLibraryRules.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.java.CompilerOutputPaths;
+import com.facebook.buck.jvm.java.CompilerParameters;
+import com.facebook.buck.jvm.java.DefaultSourceOnlyAbiRuleInfoFactory;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSortedSet;
+
+/** Common utilities. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class JavaLibraryRules {
+
+  /** Utility class: do not instantiate. */
+  private JavaLibraryRules() {}
+
+  /** Creates {@link CompilerParameters} */
+  public static CompilerParameters getCompilerParameters(
+      ImmutableList<RelPath> compileTimeClasspathPaths,
+      ImmutableList<RelPath> compileTimeClasspathSnapshotPaths,
+      ImmutableSortedSet<RelPath> javaSrcs,
+      String fullyQualifiedBuildTargetName,
+      boolean trackClassUsage,
+      AbiGenerationMode abiGenerationMode,
+      AbiGenerationMode abiCompatibilityMode,
+      boolean isRequiredForSourceOnlyAbi,
+      CompilerOutputPaths compilerOutputPaths) {
+    return new CompilerParameters(
+        javaSrcs,
+        compileTimeClasspathPaths,
+        compileTimeClasspathSnapshotPaths,
+        compilerOutputPaths,
+        abiGenerationMode,
+        abiCompatibilityMode,
+        trackClassUsage,
+        new DefaultSourceOnlyAbiRuleInfoFactory(
+            fullyQualifiedBuildTargetName, isRequiredForSourceOnlyAbi));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/JvmCDCommand.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/JvmCDCommand.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/JvmCDCommand.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.io.IOException;
+
+/** A single compilation action created from command line or worker args */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface JvmCDCommand {
+  String WORKING_DIRECTORY_ENV_VAR = "BUCK_SCRATCH_PATH";
+
+  BuildCommandStepsBuilder getBuildCommand();
+
+  String getActionId();
+
+  int getLoggingLevel();
+
+  void postExecute() throws IOException;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/LibraryStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/LibraryStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/LibraryStepsBuilder.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.ActionMetadata;
+import com.facebook.buck.jvm.java.CompileToJarStepFactory;
+import com.facebook.buck.jvm.java.CompilerOutputPathsValue;
+import com.facebook.buck.jvm.java.JarParameters;
+import com.facebook.buck.jvm.java.ResolvedJavac;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import org.jetbrains.annotations.Nullable;
+
+/** Builder that creates library jar steps. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public interface LibraryStepsBuilder extends CompileStepsBuilder {
+
+  void addMakeMissingOutputsStep(RelPath annotationsPath);
+
+  void addBuildStepsForLibrary(
+      AbiGenerationMode abiCompatibilityMode,
+      AbiGenerationMode abiGenerationMode,
+      boolean isRequiredForSourceOnlyAbi,
+      boolean trackClassUsage,
+      RelPath buckOut,
+      BuildTargetValue buildTargetValue,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      ImmutableList<RelPath> compileTimeClasspathPaths,
+      ImmutableList<RelPath> compileTimeClasspathSnapshotPaths,
+      ImmutableSortedSet<RelPath> javaSrcs,
+      ImmutableMap<RelPath, RelPath> resourcesMap,
+      @Nullable JarParameters libraryJarParameters,
+      AbsPath buildCellRootPath,
+      ResolvedJavac resolvedJavac,
+      @Nullable ActionMetadata actionMetadata,
+      CompileToJarStepFactory.ExtraParams extraParams);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BUCK
@@ -0,0 +1,27 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "command",
+    srcs = glob([
+        "*.kt",
+    ]),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin:kotlin",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:kotlincd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:serialization",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java:java",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/core:core",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BaseJarCommand.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BaseJarCommand.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BaseJarCommand.kt
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.command
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode
+import com.facebook.buck.cd.model.java.BaseJarCommand as ProtoBaseJarCommand
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.jvm.cd.serialization.AbsPathSerializer
+import com.facebook.buck.jvm.cd.serialization.RelPathSerializer
+import com.facebook.buck.jvm.cd.serialization.java.BuildTargetValueSerializer
+import com.facebook.buck.jvm.cd.serialization.java.CompilerOutputPathsValueSerializer
+import com.facebook.buck.jvm.cd.serialization.java.JarParametersSerializer
+import com.facebook.buck.jvm.cd.serialization.java.ResolvedJavacOptionsSerializer
+import com.facebook.buck.jvm.core.BuildTargetValue
+import com.facebook.buck.jvm.java.CompilerOutputPathsValue
+import com.facebook.buck.jvm.java.JarParameters
+import com.facebook.buck.jvm.java.JdkProvidedInMemoryJavac
+import com.facebook.buck.jvm.java.ResolvedJavac
+import com.facebook.buck.jvm.java.ResolvedJavacOptions
+import com.google.common.collect.ImmutableList
+import com.google.common.collect.ImmutableMap
+import com.google.common.collect.ImmutableSortedSet
+import java.nio.file.Path
+import java.nio.file.Paths
+import java.util.Optional
+
+class BaseJarCommand(
+    val abiCompatibilityMode: AbiGenerationMode,
+    val abiGenerationMode: AbiGenerationMode,
+    val isRequiredForSourceOnlyAbi: Boolean,
+    val trackClassUsage: Boolean,
+    val compilerOutputPathsValue: CompilerOutputPathsValue,
+    val compileTimeClasspathPaths: ImmutableList<RelPath>,
+    val compileTimeClasspathSnapshotPathsMap: ImmutableList<RelPath>,
+    val javaSrcs: ImmutableSortedSet<RelPath>,
+    val resourcesMap: ImmutableMap<RelPath, RelPath>,
+    val jarParameters: JarParameters?,
+    val buildCellRootPath: AbsPath,
+    val resolvedJavac: ResolvedJavac,
+    val resolvedJavacOptions: ResolvedJavacOptions,
+    val buildTargetValue: BuildTargetValue,
+    val buckOut: RelPath,
+    val annotationPath: RelPath?,
+    val jarToJarDirMap: ImmutableMap<Path, Path>,
+) {
+
+  companion object {
+    fun fromProto(model: ProtoBaseJarCommand, scratchDir: Optional<RelPath>): BaseJarCommand {
+      val paths = model.compileTimeClasspathAbiAndDirPathsList
+      require(paths.size % 2 == 0) { "Expected alternating ABI jar and directory paths" }
+      require(paths.isEmpty() || model.compileTimeClasspathPathsCount == 0) {
+        "Specify either compileTimeClasspathPaths or compileTimeClasspathAbiAndDirPaths"
+      }
+      val classpath = ImmutableList.builder<RelPath>()
+      val jarToJarDirMap = mutableMapOf<Path, Path>()
+      for (i in paths.indices step 2) {
+        val jar = RelPath.get(paths[i])
+        classpath.add(jar)
+        if (paths[i + 1].isNotEmpty()) {
+          val dir = Paths.get(paths[i + 1])
+          // TODO(ianc) fix this, we shouldn't be adding the same jar to the classpath multiple
+          // times
+          val previous = jarToJarDirMap.putIfAbsent(jar.path, dir)
+          require(previous == null || previous == dir) { "Conflicting ABI directories for $jar" }
+        }
+      }
+      if (paths.isEmpty()) {
+        classpath.addAll(RelPathSerializer.toListOfRelPath(model.compileTimeClasspathPathsList))
+      }
+      val buildTarget = BuildTargetValueSerializer.deserialize(model.buildTargetValue)
+      val outputPathsValue =
+          CompilerOutputPathsValueSerializer.deserialize(model.outputPathsValue, scratchDir)
+      val outputPaths =
+          when {
+            buildTarget.isSourceOnlyAbi -> outputPathsValue.sourceOnlyAbiCompilerOutputPath
+            buildTarget.isSourceAbi -> outputPathsValue.sourceAbiCompilerOutputPath
+            else -> outputPathsValue.libraryCompilerOutputPath
+          }
+      val resources = RelPathSerializer.toResourceMap(model.resourcesMapList)
+      val jarParameters =
+          if (model.hasJarParameters()) {
+            val parameters = JarParametersSerializer.deserialize(model.jarParameters)
+            if (parameters.entriesToJar.isEmpty()) {
+              parameters.copy(
+                  entriesToJar =
+                      ImmutableSortedSet.orderedBy(RelPath.comparator())
+                          .add(outputPaths.classesDir)
+                          .build(),
+              )
+            } else {
+              parameters
+            }
+          } else {
+            null
+          }
+      return BaseJarCommand(
+          AbiGenerationMode.CLASS,
+          model.abiGenerationMode,
+          model.trackClassUsage,
+          model.trackClassUsage,
+          outputPathsValue,
+          classpath.build(),
+          RelPathSerializer.toListOfRelPath(model.compileTimeClasspathSnapshotPathsList),
+          RelPathSerializer.toSortedSetOfRelPath(model.getJavaSrcsList()),
+          ImmutableMap.copyOf(
+              resources.mapValues { (_, destination) ->
+                outputPaths.classesDir.resolveRel(destination.toString())
+              },
+          ),
+          jarParameters,
+          AbsPathSerializer.deserialize(""),
+          JdkProvidedInMemoryJavac.createJsr199Javac(),
+          ResolvedJavacOptionsSerializer.deserialize(model.resolvedJavacOptions),
+          buildTarget,
+          RelPath.get("buck-out/v2"),
+          if (model.annotationsPath.isEmpty()) scratchDir.get().resolveRel("__gen__")
+          else RelPathSerializer.deserialize(model.annotationsPath),
+          ImmutableMap.copyOf(jarToJarDirMap),
+      )
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BuildMode.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BuildMode.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/BuildMode.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.command
+
+import com.facebook.buck.cd.model.java.BuildMode as ProtoBuildMode
+
+enum class BuildMode {
+  LIBRARY,
+  ABI;
+
+  companion object {
+    fun fromProto(model: ProtoBuildMode): BuildMode {
+      return when (model) {
+        ProtoBuildMode.LIBRARY -> LIBRARY
+        ProtoBuildMode.ABI -> ABI
+        ProtoBuildMode.BUILD_MODE_UNSPECIFIED,
+        ProtoBuildMode.UNRECOGNIZED -> error("${model} is not supported")
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/PostBuildParams.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/PostBuildParams.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/PostBuildParams.kt
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.command
+
+import com.facebook.buck.cd.model.common.PostBuildParams as PostBuildParamsProto
+import java.nio.file.Path
+import java.nio.file.Paths
+
+class PostBuildParams(
+    val libraryJar: Path?,
+    val abiJar: Path?,
+    val jvmAbiGen: Path?,
+    val abiOutputDir: Path?,
+    val usedClassesPaths: List<Path>,
+    val depFile: Path?,
+    val optionalDirsPaths: List<Path>,
+    val incrementalStateDir: Path?,
+    val shouldCreateClassAbi: Boolean,
+    val usedJarsPath: Path?,
+    val postProcessorCmd: String?,
+    val filesWhichSkippedCompilation: Path?,
+    val jvmAbiFilesWhichSkippedCompilation: Path?,
+) {
+  companion object {
+    fun fromProto(model: PostBuildParamsProto): PostBuildParams = PostBuildParams(
+        model.libraryJar.takeIf { it.isNotEmpty() }?.let(Paths::get),
+        model.abiJar.takeIf { it.isNotEmpty() }?.let(Paths::get),
+        model.jvmAbiGen.takeIf { it.isNotEmpty() }?.let(Paths::get),
+        model.abiOutputDir.takeIf { it.isNotEmpty() }?.let(Paths::get),
+        model.usedClassesList?.map(Paths::get).orEmpty(),
+        model.depFile.takeIf { it.isNotEmpty() }?.let(Paths::get),
+        model.optionalDirsList?.map(Paths::get).orEmpty(),
+        model.incrementalStateDir.takeIf { it.isNotEmpty() }?.let(Paths::get),
+        model.shouldCreateClassAbi,
+        model.usedJarsFile.takeIf { it.isNotEmpty() }?.let(Paths::get),
+        model.postProcessorCmd.takeIf { it.isNotEmpty() },
+        model.filesWhichSkippedCompilation.takeIf { it.isNotEmpty() }?.let(Paths::get),
+        model.jvmAbiFilesWhichSkippedCompilation.takeIf { it.isNotEmpty() }?.let(Paths::get),
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/java/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/java/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/java/BUCK
@@ -0,0 +1,25 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "command",
+    srcs = glob(["*.kt"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:kotlincd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:serialization",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java:java",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/core:core",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command:command",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/java/BuildJavaCommand.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/java/BuildJavaCommand.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/java/BuildJavaCommand.kt
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.command.java
+
+import com.facebook.buck.cd.model.java.BuildCommand as ProtoBuildCommand
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.jvm.cd.command.BaseJarCommand
+import com.facebook.buck.jvm.cd.command.BuildMode
+import java.util.Optional
+
+class BuildJavaCommand(
+    val baseJarCommand: BaseJarCommand,
+    val buildMode: BuildMode,
+) {
+
+  companion object {
+    fun fromProto(model: ProtoBuildCommand, buckScratchPath: Optional<RelPath>): BuildJavaCommand {
+      val baseJarCommand: BaseJarCommand =
+          BaseJarCommand.fromProto(model.baseJarCommand, buckScratchPath)
+      val buildMode: BuildMode = BuildMode.fromProto(model.buildMode)
+      return BuildJavaCommand(baseJarCommand, buildMode)
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/BUCK
@@ -0,0 +1,53 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "language-version",
+    srcs = ["LanguageVersion.kt"],
+    labels = ["codegen_rule"],
+    visibility = ["PUBLIC"],
+)
+
+buck_kotlin_library(
+    name = "support",
+    srcs = [
+        "KotlinExtraParams.kt",
+    ],
+    labels = ["codegen_rule"],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/third-party:guava",
+        ":language-version",
+    ],
+)
+
+buck_kotlin_library(
+    name = "command",
+    srcs = ["BuildKotlinCommand.kt"],
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin:kotlin",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:kotlincd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:serialization",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java:java",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin:kotlin",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/core:core",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/third-party:guava",
+        ":support",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command:command",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:support",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/BuildKotlinCommand.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/BuildKotlinCommand.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/BuildKotlinCommand.kt
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.command.kotlin
+
+import com.facebook.buck.cd.model.kotlin.BuildCommand as ProtoBuildCommand
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.jvm.cd.command.BaseJarCommand
+import com.facebook.buck.jvm.cd.command.BuildMode
+import com.facebook.buck.jvm.cd.serialization.kotlin.KotlinExtraParamsSerializer
+import java.util.Optional
+
+class BuildKotlinCommand(
+    val kotlinExtraParams: KotlinExtraParams,
+    val baseJarCommand: BaseJarCommand,
+    val buildMode: BuildMode,
+) {
+
+  companion object {
+    fun fromProto(model: ProtoBuildCommand, scratchDir: Optional<RelPath>): BuildKotlinCommand {
+
+      val buildMode: BuildMode = BuildMode.fromProto(model.buildMode)
+      val baseJarCommand: BaseJarCommand =
+          BaseJarCommand.fromProto(model.baseJarCommand, scratchDir)
+      val kotlinExtraParams: KotlinExtraParams =
+          KotlinExtraParamsSerializer.deserialize(
+              model.baseJarCommand.resolvedJavacOptions,
+              model.kotlinExtraParams,
+              scratchDir,
+          )
+
+      return BuildKotlinCommand(kotlinExtraParams, baseJarCommand, buildMode)
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/KotlinExtraParams.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/KotlinExtraParams.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/KotlinExtraParams.kt
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.command.kotlin
+
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.jvm.java.CompileToJarStepFactory
+import com.facebook.buck.jvm.java.ResolvedJavacOptions
+import com.google.common.collect.ImmutableList
+import com.google.common.collect.ImmutableMap
+import com.google.common.collect.ImmutableSortedSet
+import java.util.Optional
+
+data class KotlinExtraParams(
+    val extraClassPaths: ImmutableList<AbsPath>,
+    val extraClassPathSnapshots: ImmutableList<AbsPath>,
+    val standardLibraryClassPath: AbsPath,
+    val annotationProcessingClassPath: AbsPath,
+    val extraKotlincArguments: ImmutableList<String>,
+    val kotlinCompilerPlugins: ImmutableMap<AbsPath, ImmutableMap<String, String>>,
+    val kosabiPluginOptions: ImmutableMap<String, AbsPath>,
+    val kosabiJvmAbiGenEarlyTerminationMessagePrefix: Optional<String>,
+    val friendPaths: ImmutableSortedSet<AbsPath>,
+    val kotlinHomeLibraries: ImmutableList<AbsPath>,
+    val resolvedJavacOptions: ResolvedJavacOptions,
+    val jvmTarget: Optional<String>,
+    val shouldUseJvmAbiGen: Boolean,
+    val jvmAbiGenPlugin: Optional<AbsPath>,
+    val shouldVerifySourceOnlyAbiConstraints: Boolean,
+    val depTrackerPlugin: Optional<AbsPath>,
+    val shouldKotlincRunIncrementally: Boolean,
+    val incrementalStateDir: Optional<AbsPath>,
+    val shouldKsp2RunIncrementally: Boolean,
+    private val languageVersionString: String,
+    val kotlinClassesDir: AbsPath,
+    val javaBinary: Optional<String>,
+    val applicabilityClasspath: ImmutableList<AbsPath> = ImmutableList.of(),
+) : CompileToJarStepFactory.ExtraParams {
+
+  val shouldActionRunIncrementally: Boolean =
+      shouldKotlincRunIncrementally || shouldKsp2RunIncrementally
+
+  val kotlincWorkingDir: Optional<AbsPath> = incrementalStateDir.map { dir: AbsPath ->
+    dir.resolve(KOTLINC_WORKING_DIR)
+  }
+
+  val ksp2CachesDir: Optional<AbsPath> = incrementalStateDir.map { dir: AbsPath ->
+    dir.resolve(KSP2_CACHES_DIR)
+  }
+
+  val jvmAbiGenWorkingDir: Optional<AbsPath> = incrementalStateDir.map { dir: AbsPath ->
+    dir.resolve(KOTLINC_JVM_ABI_GEN_WORKING_DIR)
+  }
+
+  val languageVersion: LanguageVersion = LanguageVersion(languageVersionString)
+
+  companion object {
+    private val KOTLINC_WORKING_DIR: String = "kotlinc_working_dir"
+    private val KSP2_CACHES_DIR: String = "ksp2_caches_dir"
+    private val KOTLINC_JVM_ABI_GEN_WORKING_DIR: String = "jvm_abi_gen_working_dir"
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/LanguageVersion.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/LanguageVersion.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin/LanguageVersion.kt
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.command.kotlin
+
+enum class KotlinSupportedLanguageVersion(val value: String) {
+  v1_6("1.6"),
+  V2_0("2.0"),
+  V2_1("2.1"),
+}
+
+@RequiresOptIn(level = RequiresOptIn.Level.ERROR) annotation class LanguageVersionForLogs
+
+class LanguageVersion(private val internalValue: String) {
+
+  init {
+    validateLanguageVersion()
+  }
+
+  private fun validateLanguageVersion() {
+    val versionComponents = internalValue.split(".")
+    require(versionComponents.size in (2..3)) { "Invalid language version: $internalValue" }
+    require(versionComponents.all { it.toIntOrNull() != null }) {
+      "Invalid language version: $internalValue"
+    }
+  }
+
+  @LanguageVersionForLogs val valueForLogs: String? = internalValue
+
+  val value: String
+    get() {
+      check(supportsLanguageVersion) { "Language version is not supported" }
+      return internalValue
+    }
+
+  val compilerArgs: String
+    get() = LANGUAGE_VERSION_ARG + value
+
+  fun isGreaterOrEqual(version: KotlinSupportedLanguageVersion): Boolean {
+    // Compare numerically per version component so that e.g. "2.10" >= "2.2" holds.
+    // A plain string comparison is lexicographic and breaks once a minor reaches 2 digits.
+    val current = internalValue.split(".")
+    val target = version.value.split(".")
+    for (i in 0 until maxOf(current.size, target.size)) {
+      val c = current.getOrNull(i)?.toIntOrNull() ?: 0
+      val t = target.getOrNull(i)?.toIntOrNull() ?: 0
+      if (c != t) return c > t
+    }
+    return true
+  }
+
+  // Kotlinc 1.6+ can properly recognize `-language-version` flag
+  val supportsLanguageVersion: Boolean = isGreaterOrEqual(LANGUAGE_VERSION_PARAM_SUPPORTED_FROM)
+
+  val supportsK2: Boolean = isGreaterOrEqual(KotlinSupportedLanguageVersion.V2_0)
+
+  companion object {
+    private val LANGUAGE_VERSION_PARAM_SUPPORTED_FROM = KotlinSupportedLanguageVersion.v1_6
+    private const val LANGUAGE_VERSION_ARG: String = "-language-version="
+    @JvmStatic val K2: LanguageVersion = LanguageVersion(KotlinSupportedLanguageVersion.V2_0.value)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/AbsPathSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/AbsPathSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/AbsPathSerializer.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.util.environment.EnvVariablesProvider;
+import com.facebook.infer.annotation.Nullsafe;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+/** {@link AbsPath} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class AbsPathSerializer {
+  private static final String EXPECT_RELATIVE_PATHS_ENV_VAR =
+      "JAVACD_ABSOLUTE_PATHS_ARE_RELATIVE_TO_CWD";
+
+  private static final boolean EXPECT_RELATIVE_PATHS =
+      EnvVariablesProvider.getSystemEnv().get(EXPECT_RELATIVE_PATHS_ENV_VAR) != null;
+
+  private AbsPathSerializer() {}
+
+  /** Deserializes javacd model into {@link AbsPath}. */
+  public static AbsPath deserialize(String absPath) {
+    Path path = Paths.get(absPath);
+    if (EXPECT_RELATIVE_PATHS) {
+      RelPath relPath = RelPath.of(path);
+
+      return AbsPath.of(Paths.get("").toAbsolutePath()).resolve(relPath);
+    } else {
+      return AbsPath.of(path);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/BUCK
@@ -0,0 +1,37 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "serialization",
+    srcs = glob(
+        ["*.java"],
+        exclude = ["SerializationUtil.java"],
+    ),
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:cd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:environment",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+    ],
+)
+
+buck_java_library(
+    name = "util",
+    srcs = ["SerializationUtil.java"],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:infer-annotations",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/PathSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/PathSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/PathSerializer.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization;
+
+import com.facebook.infer.annotation.Nullsafe;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+/** {@link Path} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class PathSerializer {
+
+  private PathSerializer() {}
+
+  /** Deserializes javacd model into {@link Path}. */
+  public static Path deserialize(String path) {
+    return Paths.get(path);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/RelPathSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/RelPathSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/RelPathSerializer.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization;
+
+import com.facebook.buck.cd.model.common.RelPathMapEntry;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import java.util.List;
+import java.util.Map;
+
+/** {@link RelPath} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class RelPathSerializer {
+
+  private RelPathSerializer() {}
+
+  /** Deserializes list of {@link RelPathMapEntry} into a map of resources */
+  public static ImmutableMap<RelPath, RelPath> toResourceMap(
+      List<RelPathMapEntry> resourcesMapList) {
+    ImmutableMap.Builder<RelPath, RelPath> builder =
+        ImmutableMap.builderWithExpectedSize(resourcesMapList.size());
+    for (RelPathMapEntry entry : resourcesMapList) {
+      builder.put(
+          RelPathSerializer.deserialize(entry.getKey()),
+          RelPathSerializer.deserialize(entry.getValue()));
+    }
+    return builder.build();
+  }
+
+  /** Deserializes list of paths into a sorted set of {@link RelPath} */
+  public static ImmutableSortedSet<RelPath> toSortedSetOfRelPath(List<String> list) {
+    ImmutableSortedSet.Builder<RelPath> builder =
+        ImmutableSortedSet.orderedBy(RelPath.comparator());
+    for (String item : list) {
+      builder.add(RelPathSerializer.deserialize(item));
+    }
+    return builder.build();
+  }
+
+  /** Deserializes list of paths into a map of {@link RelPath} to {@link RelPath} */
+  public static ImmutableMap<RelPath, RelPath> toMap(Map<String, String> map) {
+    return map.entrySet().stream()
+        .filter(e -> !e.getValue().isEmpty())
+        .collect(
+            ImmutableMap.toImmutableMap(
+                e -> RelPathSerializer.deserialize(e.getKey()),
+                e -> RelPathSerializer.deserialize(e.getValue())));
+  }
+
+  /** Deserializes list of paths into a list of {@link RelPath} */
+  public static ImmutableList<RelPath> toListOfRelPath(List<String> list) {
+    return list.stream()
+        .map(RelPathSerializer::deserialize)
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  /** Deserializes javacd model into {@link RelPath}. */
+  public static RelPath deserialize(String relPath) {
+    return RelPath.get(relPath);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/SerializationUtil.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/SerializationUtil.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/SerializationUtil.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization;
+
+import com.facebook.infer.annotation.Nullsafe;
+
+/** CD serialization utilities. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class SerializationUtil {
+
+  private SerializationUtil() {}
+
+  public static RuntimeException createNotSupportedException(Enum<?> value) {
+    return new IllegalStateException(value.name() + " enum value is not supported!");
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "java",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/cd/serialization/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:serialization",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:util",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/BuildTargetValueSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/BuildTargetValueSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/BuildTargetValueSerializer.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.java;
+
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.infer.annotation.Nullsafe;
+
+/** {@link BuildTargetValue} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class BuildTargetValueSerializer {
+
+  private BuildTargetValueSerializer() {}
+
+  /**
+   * Deserializes javacd model's {@link com.facebook.buck.cd.model.java.BuildTargetValue} into
+   * {@link BuildTargetValue}.
+   */
+  public static BuildTargetValue deserialize(
+      com.facebook.buck.cd.model.java.BuildTargetValue buildTargetValue) {
+    return new BuildTargetValue(
+        buildTargetValue.getType(), buildTargetValue.getFullyQualifiedName());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/CompilerOutputPathsSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/CompilerOutputPathsSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/CompilerOutputPathsSerializer.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.java;
+
+import com.facebook.buck.cd.model.java.OutputPathsValue;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.cd.serialization.RelPathSerializer;
+import com.facebook.buck.jvm.java.CompilerOutputPaths;
+import com.facebook.infer.annotation.Nullsafe;
+import java.util.Optional;
+
+/** {@link CompilerOutputPaths} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class CompilerOutputPathsSerializer {
+
+  private CompilerOutputPathsSerializer() {}
+
+  /**
+   * Deserializes javacd model's {@link OutputPathsValue.OutputPaths} into {@link
+   * CompilerOutputPaths}.
+   */
+  public static CompilerOutputPaths deserialize(OutputPathsValue.OutputPaths outputPaths) {
+    return deserialize(outputPaths, Optional.empty());
+  }
+
+  public static CompilerOutputPaths deserialize(
+      OutputPathsValue.OutputPaths outputPaths, Optional<RelPath> tmpDir) {
+    return new CompilerOutputPaths(
+        tmpDir.get().resolveRel("__classes__"),
+        toRelPath(outputPaths.getOutputJarDirPath()),
+        toOptionalRelPath(outputPaths.getAbiJarPath()),
+        toOptionalRelPath(outputPaths.getAnnotationPath())
+            .orElseGet(() -> tmpDir.get().resolveRel("__gen__")),
+        outputPaths.getPathToSourcesList().isEmpty()
+            ? tmpDir.map(p -> p.resolveRel("__srcs__")).get()
+            : toRelPath(outputPaths.getPathToSourcesList()),
+        outputPaths.getWorkingDirectory().isEmpty()
+            ? tmpDir.get()
+            : toRelPath(outputPaths.getWorkingDirectory()),
+        toOptionalRelPath(outputPaths.getOutputJarPath()));
+  }
+
+  private static RelPath toRelPath(String relPath) {
+    return RelPathSerializer.deserialize(relPath);
+  }
+
+  private static Optional<RelPath> toOptionalRelPath(String value) {
+    return Optional.of(value)
+        .filter(s -> !s.isEmpty())
+        .map(CompilerOutputPathsSerializer::toRelPath);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/CompilerOutputPathsValueSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/CompilerOutputPathsValueSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/CompilerOutputPathsValueSerializer.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.java;
+
+import com.facebook.buck.cd.model.java.OutputPathsValue;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.java.CompilerOutputPaths;
+import com.facebook.buck.jvm.java.CompilerOutputPathsValue;
+import com.facebook.infer.annotation.Nullsafe;
+import java.util.Optional;
+
+/** {@link CompilerOutputPathsValue} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class CompilerOutputPathsValueSerializer {
+
+  private CompilerOutputPathsValueSerializer() {}
+
+  /** Deserializes javacd model's {@link OutputPathsValue} into {@link CompilerOutputPathsValue}. */
+  public static CompilerOutputPathsValue deserialize(OutputPathsValue outputPathsValue) {
+    return deserialize(outputPathsValue, Optional.empty());
+  }
+
+  public static CompilerOutputPathsValue deserialize(
+      OutputPathsValue outputPathsValue, Optional<RelPath> tmpDir) {
+    return CompilerOutputPathsValue.of(
+        outputPathsValue.getLibraryTargetFullyQualifiedName(),
+        toCompilerOutputPaths(outputPathsValue.getLibraryPaths(), tmpDir),
+        toCompilerOutputPaths(outputPathsValue.getSourceAbiPaths(), tmpDir),
+        toCompilerOutputPaths(outputPathsValue.getSourceOnlyAbiPaths(), tmpDir));
+  }
+
+  private static CompilerOutputPaths toCompilerOutputPaths(
+      OutputPathsValue.OutputPaths outputPaths, Optional<RelPath> tmpDir) {
+    return CompilerOutputPathsSerializer.deserialize(outputPaths, tmpDir);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JarParametersSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JarParametersSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JarParametersSerializer.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.java;
+
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.cd.serialization.RelPathSerializer;
+import com.facebook.buck.jvm.java.JarParameters;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableSortedSet;
+import java.util.Optional;
+import java.util.logging.Level;
+
+/** {@link JarParameters} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class JarParametersSerializer {
+
+  private JarParametersSerializer() {}
+
+  /**
+   * Deserializes javacd model's {@link com.facebook.buck.cd.model.java.JarParameters} into {@link
+   * JarParameters}.
+   */
+  public static JarParameters deserialize(
+      com.facebook.buck.cd.model.java.JarParameters jarParameters) {
+    Optional<String> mainClass =
+        Optional.of(jarParameters.getMainClass()).filter(s -> !s.isEmpty());
+    Optional<RelPath> manifestFile =
+        Optional.of(jarParameters.getManifestFile())
+            .filter(s -> !s.isEmpty())
+            .map(RelPathSerializer::deserialize);
+
+    return new JarParameters(
+        jarParameters.getHashEntries(),
+        jarParameters.getMergeManifests(),
+        RelPathSerializer.deserialize(jarParameters.getJarPath()),
+        RemoveClassesPatternsMatcherSerializer.deserialize(jarParameters.getRemoveEntryPredicate()),
+        jarParameters.getEntriesToJarList().stream()
+            .map(RelPathSerializer::deserialize)
+            .collect(ImmutableSortedSet.toImmutableSortedSet(RelPath.comparator())),
+        jarParameters.getOverrideEntriesToJarList().stream()
+            .map(RelPathSerializer::deserialize)
+            .collect(ImmutableSortedSet.toImmutableSortedSet(RelPath.comparator())),
+        mainClass,
+        manifestFile,
+        Level.FINE);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JavacLanguageLevelOptionsSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JavacLanguageLevelOptionsSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JavacLanguageLevelOptionsSerializer.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.java;
+
+import com.facebook.buck.cd.model.java.ResolvedJavacOptions;
+import com.facebook.buck.jvm.java.JavacLanguageLevelOptions;
+import com.facebook.infer.annotation.Nullsafe;
+
+/** {@link JavacLanguageLevelOptions} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+class JavacLanguageLevelOptionsSerializer {
+
+  private JavacLanguageLevelOptionsSerializer() {}
+
+  /**
+   * Deserializes javacd model's {@link ResolvedJavacOptions.JavacLanguageLevelOptions} into {@link
+   * JavacLanguageLevelOptions}.
+   */
+  public static JavacLanguageLevelOptions deserialize(
+      ResolvedJavacOptions.JavacLanguageLevelOptions javacLanguageLevelOptions) {
+    return new JavacLanguageLevelOptions(
+        javacLanguageLevelOptions.getSourceLevel(), javacLanguageLevelOptions.getTargetLevel());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JavacPluginParamsSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JavacPluginParamsSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/JavacPluginParamsSerializer.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.java;
+
+import com.facebook.buck.cd.model.java.ResolvedJavacOptions;
+import com.facebook.buck.jvm.java.JavacPluginParams;
+import com.facebook.buck.jvm.java.ResolvedJavacPluginProperties;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSortedSet;
+import java.util.List;
+
+/** {@link JavacPluginParams} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+class JavacPluginParamsSerializer {
+
+  private JavacPluginParamsSerializer() {}
+
+  /**
+   * Deserializes javacd model's {@link ResolvedJavacOptions.JavacPluginParams } into {@link
+   * JavacPluginParams}.
+   */
+  public static JavacPluginParams deserialize(
+      ResolvedJavacOptions.JavacPluginParams javacPluginParams) {
+    return new JavacPluginParams(
+        toPluginProperties(javacPluginParams.getPluginPropertiesList()),
+        ImmutableSortedSet.copyOf(javacPluginParams.getParametersList()));
+  }
+
+  private static ImmutableList<ResolvedJavacPluginProperties> toPluginProperties(
+      List<ResolvedJavacOptions.ResolvedJavacPluginProperties> pluginPropertiesList) {
+    ImmutableList.Builder<ResolvedJavacPluginProperties> builder =
+        ImmutableList.builderWithExpectedSize(pluginPropertiesList.size());
+    for (ResolvedJavacOptions.ResolvedJavacPluginProperties item : pluginPropertiesList) {
+      builder.add(ResolvedJavacPluginPropertiesSerializer.deserialize(item));
+    }
+    return builder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/RemoveClassesPatternsMatcherSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/RemoveClassesPatternsMatcherSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/RemoveClassesPatternsMatcherSerializer.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.java;
+
+import com.facebook.buck.cd.model.java.JarParameters;
+import com.facebook.buck.jvm.java.RemoveClassesPatternsMatcher;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableSet;
+import java.util.regex.Pattern;
+
+/** {@link RemoveClassesPatternsMatcher} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+class RemoveClassesPatternsMatcherSerializer {
+
+  private RemoveClassesPatternsMatcherSerializer() {}
+
+  /**
+   * Deserializes javacd model's {@link JarParameters.RemoveClassesPatternsMatcher} into {@link
+   * RemoveClassesPatternsMatcher}.
+   */
+  public static RemoveClassesPatternsMatcher deserialize(
+      JarParameters.RemoveClassesPatternsMatcher removeClassesPatternsMatcher) {
+    ImmutableSet<Pattern> patterns =
+        removeClassesPatternsMatcher.getPatternsList().stream()
+            .map(Pattern::compile)
+            .collect(ImmutableSet.toImmutableSet());
+    return new RemoveClassesPatternsMatcher(patterns);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/ResolvedJavacOptionsSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/ResolvedJavacOptionsSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/ResolvedJavacOptionsSerializer.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.java;
+
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.cd.serialization.RelPathSerializer;
+import com.facebook.buck.jvm.java.ResolvedJavacOptions;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import java.util.Optional;
+
+/** {@link ResolvedJavacOptions} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ResolvedJavacOptionsSerializer {
+
+  private ResolvedJavacOptionsSerializer() {}
+
+  /**
+   * Deserializes javacd model's {@link com.facebook.buck.cd.model.java.ResolvedJavacOptions} into
+   * {@link ResolvedJavacOptions}.
+   */
+  public static ResolvedJavacOptions deserialize(
+      com.facebook.buck.cd.model.java.ResolvedJavacOptions options) {
+    var bootclasspathListList = options.getBootclasspathListList();
+    ImmutableList<RelPath> bootclasspathList =
+        bootclasspathListList.stream()
+            .map(RelPathSerializer::deserialize)
+            .collect(ImmutableList.toImmutableList());
+
+    return new ResolvedJavacOptions(
+        bootclasspathList,
+        JavacLanguageLevelOptionsSerializer.deserialize(options.getLanguageLevelOptions()),
+        true,
+        options.getVerbose(),
+        JavacPluginParamsSerializer.deserialize(options.getJavaAnnotationProcessorParams()),
+        JavacPluginParamsSerializer.deserialize(options.getStandardJavacPluginParams()),
+        ImmutableList.copyOf(options.getExtraArgumentsList()),
+        options.getSystemImage().isEmpty() ? null : options.getSystemImage());
+  }
+
+  private static Optional<String> toOptionalString(String value) {
+    return value.isEmpty() ? Optional.empty() : Optional.of(value);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/ResolvedJavacPluginPropertiesSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/ResolvedJavacPluginPropertiesSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java/ResolvedJavacPluginPropertiesSerializer.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.java;
+
+import com.facebook.buck.cd.model.java.ResolvedJavacOptions;
+import com.facebook.buck.jvm.cd.serialization.RelPathSerializer;
+import com.facebook.buck.jvm.java.ResolvedJavacPluginProperties;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+
+/** {@link ResolvedJavacPluginProperties} to protobuf serializer */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+class ResolvedJavacPluginPropertiesSerializer {
+
+  private ResolvedJavacPluginPropertiesSerializer() {}
+
+  /**
+   * Deserializes javacd model's {@link ResolvedJavacOptions.ResolvedJavacPluginProperties} into
+   * {@link ResolvedJavacPluginProperties}.
+   */
+  public static ResolvedJavacPluginProperties deserialize(
+      ResolvedJavacOptions.ResolvedJavacPluginProperties pluginProperties) {
+    return new ResolvedJavacPluginProperties(
+        pluginProperties.getCanReuseClassLoader(),
+        pluginProperties.getDoesNotAffectAbi(),
+        pluginProperties.getSupportsAbiGenerationFromSource(),
+        pluginProperties.getRunsOnJavaOnly(),
+        ImmutableSortedSet.copyOf(pluginProperties.getProcessorNamesList()),
+        pluginProperties.getClasspathList().stream()
+            .map(RelPathSerializer::deserialize)
+            .collect(ImmutableList.toImmutableList()),
+        ImmutableMap.of(),
+        ImmutableList.copyOf(pluginProperties.getArgumentsList()));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/ActionMetadataSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/ActionMetadataSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/ActionMetadataSerializer.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.kotlin;
+
+import com.facebook.buck.jvm.cd.serialization.PathSerializer;
+import com.facebook.buck.jvm.java.ActionMetadata;
+import com.facebook.infer.annotation.Nullsafe;
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+/**
+ * Marshalling between:
+ *
+ * <ul>
+ *   <li>{@link ActionMetadata} (metadata provided by incremental actions, see: <a
+ *       href="https://buck2.build/docs/rule_authors/incremental_actions/">...</a>), and
+ *   <li>{@link com.facebook.buck.cd.model.kotlin.ActionMetadata} (part of the protocol buffer
+ *       model).
+ * </ul>
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class ActionMetadataSerializer {
+
+  private ActionMetadataSerializer() {}
+
+  /** Protocol buffer model to internal buck representation. */
+  public static ActionMetadata deserialize(
+      Path incrementalMetadataFilePath,
+      com.facebook.buck.cd.model.kotlin.ActionMetadata actionMetadata) {
+    Map<Path, String> previousDigest =
+        actionMetadata.getPreviousMetadata().getDigestsList().stream()
+            .collect(
+                Collectors.toMap(
+                    digest -> PathSerializer.deserialize(digest.getPath()),
+                    com.facebook.buck.cd.model.kotlin.Digests::getDigest));
+    Map<Path, String> currentDigest =
+        actionMetadata.getCurrentMetadata().getDigestsList().stream()
+            .collect(
+                Collectors.toMap(
+                    digest -> PathSerializer.deserialize(digest.getPath()),
+                    com.facebook.buck.cd.model.kotlin.Digests::getDigest));
+
+    return new ActionMetadata(incrementalMetadataFilePath, previousDigest, currentDigest);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/BUCK
@@ -0,0 +1,31 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "kotlin",
+    srcs = glob(["*.java"]),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/cd/serialization/kotlin:kotlin",
+    ],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:command",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/cd/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:kotlincd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:language-version",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:support",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:serialization",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java:java",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/DigestSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/DigestSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/DigestSerializer.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.kotlin;
+
+import com.facebook.buck.jvm.cd.serialization.PathSerializer;
+import com.facebook.infer.annotation.Nullsafe;
+import java.nio.file.Path;
+import java.util.AbstractMap;
+import java.util.Map;
+
+/**
+ * Marshalling between:
+ *
+ * <ul>
+ *   <li>{@link Map.Entry<Path-String>} (metadata provided by incremental actions, see: <a
+ *       href="https://buck2.build/docs/rule_authors/incremental_actions/">...</a>), and
+ *   <li>{@link com.facebook.buck.cd.model.kotlin.Digests} (part of the protocol buffer model).
+ * </ul>
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class DigestSerializer {
+
+  private DigestSerializer() {}
+
+  /** Protocol buffer model to internal buck representation. */
+  public static Map.Entry<Path, String> deserialize(
+      com.facebook.buck.cd.model.kotlin.Digests digests) {
+    return new AbstractMap.SimpleEntry<>(
+        PathSerializer.deserialize(digests.getPath()), digests.getDigest());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/KotlinExtraParamsSerializer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/KotlinExtraParamsSerializer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin/KotlinExtraParamsSerializer.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.serialization.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.cd.command.kotlin.KotlinExtraParams;
+import com.facebook.buck.jvm.cd.serialization.AbsPathSerializer;
+import com.facebook.buck.jvm.cd.serialization.java.ResolvedJavacOptionsSerializer;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Marshalling between:
+ *
+ * <ul>
+ *   <li>{@link com.facebook.buck.jvm.cd.command.kotlin.KotlinExtraParams} (the parameters needed to
+ *       create the steps for compiling Kotlin libraries), and
+ *   <li>{@link com.facebook.buck.cd.model.kotlin.KotlinExtraParams} (part of the protocol buffer
+ *       model).
+ * </ul>
+ */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class KotlinExtraParamsSerializer {
+
+  private KotlinExtraParamsSerializer() {}
+
+  /** Protocol buffer model to internal buck representation. */
+  public static KotlinExtraParams deserialize(
+      com.facebook.buck.cd.model.java.ResolvedJavacOptions resolvedJavacOptions,
+      com.facebook.buck.cd.model.kotlin.KotlinExtraParams kotlinExtraParams,
+      Optional<RelPath> scratchDir) {
+    return new KotlinExtraParams(
+        kotlinExtraParams.getExtraClassPathsList().stream()
+            .map(AbsPathSerializer::deserialize)
+            .collect(ImmutableList.toImmutableList()),
+        kotlinExtraParams.getExtraClassPathSnapshotsList().stream()
+            .map(AbsPathSerializer::deserialize)
+            .collect(ImmutableList.toImmutableList()),
+        AbsPathSerializer.deserialize(kotlinExtraParams.getStandardLibraryClassPath()),
+        AbsPathSerializer.deserialize(kotlinExtraParams.getAnnotationProcessingClassPath()),
+        kotlinExtraParams.getExtraKotlincArgumentsList().stream()
+            .collect(ImmutableList.toImmutableList()),
+        kotlinExtraParams.getKotlinCompilerPluginsMap().entrySet().stream()
+            .collect(
+                ImmutableMap.toImmutableMap(
+                    e -> AbsPathSerializer.deserialize(e.getKey()),
+                    e -> ImmutableMap.copyOf(e.getValue().getParamsMap()))),
+        kotlinExtraParams.getKosabiPluginOptionsMap().entrySet().stream()
+            .collect(
+                ImmutableMap.toImmutableMap(
+                    Map.Entry::getKey, e -> AbsPathSerializer.deserialize(e.getValue()))),
+        Optional.of(
+            "exception: java.lang.RuntimeException: Terminating compilation. We're done with ABI."),
+        kotlinExtraParams.getFriendPathsList().stream()
+            .map(AbsPathSerializer::deserialize)
+            .collect(ImmutableSortedSet.toImmutableSortedSet(AbsPath.comparator())),
+        kotlinExtraParams.getKotlinHomeLibrariesList().stream()
+            .map(AbsPathSerializer::deserialize)
+            .collect(ImmutableSortedSet.toImmutableSortedSet(AbsPath.comparator()))
+            .stream()
+            .collect(ImmutableList.toImmutableList()),
+        ResolvedJavacOptionsSerializer.deserialize(resolvedJavacOptions),
+        Optional.ofNullable(kotlinExtraParams.getJvmTarget()),
+        kotlinExtraParams.getShouldUseJvmAbiGen(),
+        Optional.of(kotlinExtraParams.getJvmAbiGenPlugin())
+            .filter(s -> !s.isEmpty())
+            .map(AbsPathSerializer::deserialize),
+        kotlinExtraParams.getShouldVerifySourceOnlyAbiConstraints(),
+        Optional.of(kotlinExtraParams.getDepTrackerPlugin())
+            .filter(s -> !s.isEmpty())
+            .map(AbsPathSerializer::deserialize),
+        kotlinExtraParams.getShouldKotlincRunIncrementally(),
+        Optional.of(kotlinExtraParams.getIncrementalStateDir())
+            .filter(s -> !s.isEmpty())
+            .map(AbsPathSerializer::deserialize),
+        kotlinExtraParams.getShouldKsp2RunIncrementally(),
+        kotlinExtraParams.getLanguageVersion(),
+        (kotlinExtraParams.getShouldKotlincRunIncrementally()
+                    || kotlinExtraParams.getShouldKsp2RunIncrementally()
+                ? AbsPathSerializer.deserialize(kotlinExtraParams.getIncrementalStateDir())
+                : scratchDir.get().toAbsolutePath())
+            .resolve("__kotlin_classes__"),
+        Optional.of(kotlinExtraParams.getJavaBinary()).filter(s -> !s.isEmpty()),
+        kotlinExtraParams.getApplicabilityClasspathList().stream()
+            .map(AbsPathSerializer::deserialize)
+            .collect(ImmutableList.toImmutableList()));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/BUCK
@@ -0,0 +1,26 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "workertool",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "prelude//toolchains/android/meta_only/src/com/facebook/buck/jvm/remote_worker/...",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps:isolatedsteps",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:environment",
+        "prelude//toolchains/android/src/com/facebook/buck/util/perf:perf",
+        "prelude//toolchains/android/src/com/facebook/buck/util/unit:unit",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/MainUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/MainUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/MainUtils.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.workertool;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.util.Console;
+import com.facebook.buck.util.perf.PerfStatsTracking;
+import com.facebook.buck.util.unit.SizeUnit;
+import com.facebook.infer.annotation.Nullsafe;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+/** Shared utilities for the compiler daemon entry points. */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class MainUtils {
+  private static final Logger LOG = Logger.get(MainUtils.class);
+
+  private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
+
+  public static void logCurrentCDState() {
+    PerfStatsTracking.MemoryPerfStatsEvent memory = PerfStatsTracking.getMemoryPerfStatsEvent();
+    long totalMemoryBytes = memory.getTotalMemoryBytes();
+    long freeMemoryBytes = memory.getFreeMemoryBytes();
+    long usedMemory = SizeUnit.BYTES.toMegabytes(totalMemoryBytes - freeMemoryBytes);
+    long freeMemory = SizeUnit.BYTES.toMegabytes(freeMemoryBytes);
+    long totalMemory = SizeUnit.BYTES.toMegabytes(totalMemoryBytes);
+    long maxMemory = SizeUnit.BYTES.toMegabytes(memory.getMaxMemoryBytes());
+    long timeSpendInGc = TimeUnit.MILLISECONDS.toSeconds(memory.getTimeSpentInGcMs());
+    String pools =
+        memory.getCurrentMemoryBytesUsageByPool().entrySet().stream()
+            .map(e -> e.getKey() + "=" + SizeUnit.BYTES.toMegabytes(e.getValue()))
+            .collect(Collectors.joining(", "));
+
+    LOG.info(
+        "CD state: executing tasks: %s, completed tasks: %s, largest pool size: %s, task count: %s."
+            + " Available processors: %s, Time spend in GC: %s seconds, Used Memory: %s, Free"
+            + " Memory: %s, Total Memory: %s, Max Memory: %s, Pools: %s",
+        0,
+        0,
+        0,
+        0,
+        AVAILABLE_PROCESSORS,
+        timeSpendInGc,
+        usedMemory,
+        freeMemory,
+        totalMemory,
+        maxMemory,
+        pools);
+  }
+
+  public static void handleExceptionAndTerminate(
+      Thread thread, Console console, Throwable throwable) {
+    // Remove an existing `ExternalLogHandler` handler that depend on the closed event pipe stream.
+    Logger logger = Logger.get("");
+    logger.cleanHandlers();
+
+    // this method logs the message with log.warn that would be noop as all logger handlers have
+    // been cleaned and prints the message into a std err.
+    console.printErrorText("Failed to execute compilation action. Thread: " + thread);
+    throwable.printStackTrace(console.getStdErr());
+
+    System.exit(3);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/BUCK
@@ -0,0 +1,29 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "workertool_grpc",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd:cd",
+        "prelude//toolchains/android/src/com/facebook/buck/step:step",
+        "prelude//toolchains/android/src/com/facebook/buck/util:process_executor",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:environment",
+        "prelude//toolchains/android/src/com/facebook/buck/util/perf:perf",
+        "prelude//toolchains/android/src/com/facebook/buck/util/unit:unit",
+        "prelude//toolchains/android/src/com/facebook/buck/workertool/resources/proto:worker-model",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:grpc-netty",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        "prelude//toolchains/android/third-party:netty",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/WorkerGrpcServer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/WorkerGrpcServer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/WorkerGrpcServer.java
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.workertool.grpc;
+
+import static com.facebook.buck.util.environment.EnvVariablesProvider.getRequiredEnvVar;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.cd.CompilerDaemonRunner;
+import com.facebook.buck.util.Console;
+import com.facebook.buck.util.Verbosity;
+import com.facebook.buck.util.perf.PerfStatsTracking;
+import com.facebook.buck.util.unit.SizeUnit;
+import com.facebook.infer.annotation.Nullsafe;
+import io.grpc.ForwardingServerCallListener;
+import io.grpc.Metadata;
+import io.grpc.Server;
+import io.grpc.ServerCall;
+import io.grpc.ServerCallHandler;
+import io.grpc.ServerInterceptor;
+import io.grpc.netty.NettyServerBuilder;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.MultithreadEventLoopGroup;
+import io.netty.channel.epoll.Epoll;
+import io.netty.channel.epoll.EpollEventLoopGroup;
+import io.netty.channel.epoll.EpollServerDomainSocketChannel;
+import io.netty.channel.kqueue.KQueue;
+import io.netty.channel.kqueue.KQueueEventLoopGroup;
+import io.netty.channel.kqueue.KQueueServerDomainSocketChannel;
+import io.netty.channel.unix.DomainSocketAddress;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+/** Worker tool grpc server using unix domain sockets */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class WorkerGrpcServer implements ServerInterceptor {
+  private static final Logger LOG = Logger.get(WorkerGrpcServer.class);
+
+  // The gRPC server handles sequential compilation requests from a single buck2 client
+  // over UDS, so minimal threads suffice. Default Netty thread count is 2x CPU cores
+  // (~144 on production hosts), which wastes ~140MB of memory on thread stacks.
+  static final int EVENT_LOOP_THREADS = 1;
+
+  String serverName;
+  EventLoopGroup eventLoopGroup;
+  Server grpcServer;
+
+  /** main function */
+  public static void runServer(
+      String serverName, WorkerGrpcService.JvmCDCommandFactory commandFactory) {
+    Path workerSocketPath = Paths.get(getRequiredEnvVar("WORKER_SOCKET"));
+
+    try {
+      Console console = new Console(Verbosity.STANDARD_INFORMATION, System.out, System.err);
+
+      try (CompilerDaemonRunner runner =
+          new CompilerDaemonRunner(OutputStream.nullOutputStream(), console)) {
+        WorkerGrpcService workerService = new WorkerGrpcService(commandFactory, runner);
+        WorkerGrpcServer server = new WorkerGrpcServer(serverName, workerSocketPath, workerService);
+        server.run();
+      }
+    } catch (InterruptedException | IOException e) {
+      System.err.println(e.toString());
+      System.exit(1);
+    }
+    System.exit(0);
+  }
+
+  public WorkerGrpcServer(
+      String serverName, Path unixDomainSocket, WorkerGrpcService workerService) {
+    this.serverName = serverName;
+    this.grpcServer = buildServer(workerService, unixDomainSocket);
+    Runtime.getRuntime()
+        .addShutdownHook(
+            new Thread(
+                () -> {
+                  // Use stderr here since the logger may have been reset by its JVM shutdown hook.
+                  System.err.println("*** shutting down gRPC server since JVM is shutting down");
+                  stopServer(grpcServer);
+                  System.err.println("*** server shut down");
+                }));
+
+    Executors.newSingleThreadScheduledExecutor(
+            r -> {
+              Thread t = new Thread(r, serverName + "-health-check");
+              t.setDaemon(true);
+              return t;
+            })
+        .scheduleAtFixedRate(this::checkCDState, 1, 10, TimeUnit.SECONDS);
+  }
+
+  private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
+
+  private boolean isParentAlive() {
+    Optional<ProcessHandle> parent = ProcessHandle.current().parent();
+    return parent.isPresent() && parent.get().pid() != 1 && parent.get().isAlive();
+  }
+
+  private void checkCDState() {
+    try {
+      logCurrentCDState();
+      if (!isParentAlive()) {
+        LOG.info("Parent process has been killed, shutting down");
+        stopServer(this.grpcServer);
+      }
+    } catch (Exception e) {
+      LOG.error(e);
+    }
+  }
+
+  private void logCurrentCDState() {
+    PerfStatsTracking.MemoryPerfStatsEvent memory = PerfStatsTracking.getMemoryPerfStatsEvent();
+    long totalMemoryBytes = memory.getTotalMemoryBytes();
+    long freeMemoryBytes = memory.getFreeMemoryBytes();
+    long usedMemory = SizeUnit.BYTES.toMegabytes(totalMemoryBytes - freeMemoryBytes);
+    long freeMemory = SizeUnit.BYTES.toMegabytes(freeMemoryBytes);
+    long totalMemory = SizeUnit.BYTES.toMegabytes(totalMemoryBytes);
+    long maxMemory = SizeUnit.BYTES.toMegabytes(memory.getMaxMemoryBytes());
+    long timeSpendInGc = TimeUnit.MILLISECONDS.toSeconds(memory.getTimeSpentInGcMs());
+    String pools =
+        memory.getCurrentMemoryBytesUsageByPool().entrySet().stream()
+            .map(e -> e.getKey() + "=" + SizeUnit.BYTES.toMegabytes(e.getValue()))
+            .collect(Collectors.joining(", "));
+
+    LOG.info(
+        "%s state: Executing tasks: %s, Completed tasks: %s, Available processors: %s, Time spent"
+            + " in GC: %s seconds, Used Memory: %s, Free Memory: %s, Total Memory: %s, Max Memory:"
+            + " %s, Pools: %s",
+        serverName,
+        activeTasks.get(),
+        completedTasks.get(),
+        AVAILABLE_PROCESSORS,
+        timeSpendInGc,
+        usedMemory,
+        freeMemory,
+        totalMemory,
+        maxMemory,
+        pools);
+  }
+
+  /** Start the server and wait, clients can connect to the socket after this */
+  public void run() throws IOException, InterruptedException {
+    LOG.info("Server started");
+    grpcServer.start();
+    grpcServer.awaitTermination();
+  }
+
+  private final AtomicInteger activeTasks = new AtomicInteger(0);
+  private final AtomicInteger completedTasks = new AtomicInteger(0);
+
+  @Override
+  public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
+      ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
+    activeTasks.incrementAndGet();
+    return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
+        next.startCall(call, headers)) {
+      @Override
+      public void onComplete() {
+        activeTasks.decrementAndGet();
+        completedTasks.incrementAndGet();
+        super.onComplete();
+      }
+    };
+  }
+
+  private Server buildServer(WorkerGrpcService service, Path unixDomainSocket) {
+    LOG.info(
+        String.format("Starting %s Worker Server using UDS: %s", serverName, unixDomainSocket));
+
+    DomainSocketAddress socketAddress = new DomainSocketAddress(unixDomainSocket.toString());
+    NettyServerBuilder builder =
+        NettyServerBuilder.forAddress(socketAddress).addService(service).intercept(this);
+    if (KQueue.isAvailable()) {
+      this.eventLoopGroup = new KQueueEventLoopGroup(EVENT_LOOP_THREADS);
+      builder = builder.channelType(KQueueServerDomainSocketChannel.class);
+    } else if (Epoll.isAvailable()) {
+      this.eventLoopGroup = new EpollEventLoopGroup(EVENT_LOOP_THREADS);
+      builder = builder.channelType(EpollServerDomainSocketChannel.class);
+    } else {
+      throw new RuntimeException("Server only supports epoll and kqueue (windows not supported)");
+    }
+    builder = builder.workerEventLoopGroup(eventLoopGroup).bossEventLoopGroup(eventLoopGroup);
+    return builder.build();
+  }
+
+  int getEventLoopThreadCount() {
+    return ((MultithreadEventLoopGroup) eventLoopGroup).executorCount();
+  }
+
+  private void stopServer(Server grpcServer) {
+    if (grpcServer != null && !grpcServer.isTerminated()) {
+      try {
+        grpcServer.shutdown().awaitTermination();
+        if (!grpcServer.isTerminated()) {
+          grpcServer.shutdownNow();
+        }
+      } catch (InterruptedException e) {
+        grpcServer.shutdownNow();
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/WorkerGrpcService.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/WorkerGrpcService.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc/WorkerGrpcService.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.cd.workertool.grpc;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.cd.CompilerDaemonRunner;
+import com.facebook.buck.jvm.cd.ErrorInterceptor;
+import com.facebook.buck.jvm.cd.JvmCDCommand;
+import com.facebook.buck.step.StepExecutionResult;
+import com.facebook.buck.worker.model.ExecuteCommand;
+import com.facebook.buck.worker.model.ExecuteResponse;
+import com.facebook.buck.worker.model.WorkerGrpc;
+import com.facebook.infer.annotation.Nullsafe;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableMap;
+import com.google.protobuf.ByteString;
+import io.grpc.stub.StreamObserver;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import org.kohsuke.args4j.CmdLineException;
+
+/** Worker Service that implements {@code workertool.v2.proto} */
+@Nullsafe(Nullsafe.Mode.LOCAL)
+public class WorkerGrpcService extends WorkerGrpc.WorkerImplBase {
+  private static final Logger LOG = Logger.get(WorkerGrpcService.class);
+
+  /** Used to supply executable commands for a specific JvmCD server */
+  public interface JvmCDCommandFactory {
+    JvmCDCommand createCommand(String[] args, ImmutableMap<String, String> env)
+        throws CmdLineException, IOException;
+  }
+
+  private final JvmCDCommandFactory commandFactory;
+  private final CompilerDaemonRunner runner;
+
+  public WorkerGrpcService(JvmCDCommandFactory commandFactory, CompilerDaemonRunner runner) {
+    this.commandFactory = commandFactory;
+    this.runner = runner;
+  }
+
+  @Override
+  public void execute(ExecuteCommand request, StreamObserver<ExecuteResponse> responseObserver) {
+    try {
+      JvmCDCommand command = createCommand(request);
+      StepExecutionResult result = runner.execute(command);
+      ExecuteResponse response = handleCompletedExecution(command, result);
+      responseObserver.onNext(response);
+      responseObserver.onCompleted();
+    } catch (Exception e) {
+      handleException(responseObserver, "executing", e);
+    }
+  }
+
+  private JvmCDCommand createCommand(ExecuteCommand request) throws IOException, CmdLineException {
+    String[] argv =
+        request.getArgvList().stream().map(ByteString::toStringUtf8).toArray(String[]::new);
+
+    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
+    for (ExecuteCommand.EnvironmentEntry entry : request.getEnvList()) {
+      builder.put(entry.getKey().toStringUtf8(), entry.getValue().toStringUtf8());
+    }
+    ImmutableMap<String, String> env = builder.build();
+    LOG.info("Execute\nargs: %s\nenv: %s", String.join(" ", argv), env);
+
+    return commandFactory.createCommand(argv, env);
+  }
+
+  private ExecuteResponse handleCompletedExecution(JvmCDCommand command, StepExecutionResult result)
+      throws IOException {
+    if (!result.isSuccess()) {
+
+      String errorMessage = result.getErrorMessage();
+      String stackTrace = "";
+      // if there is a compiling error, we don't want to print buck stack trace
+      if (!CompilerDaemonRunner.isCompilerError(errorMessage)) {
+        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+        PrintStream ps = new PrintStream(outputStream);
+        result.getCause().ifPresent(c -> c.printStackTrace(ps));
+        stackTrace = outputStream.toString();
+      }
+      String error = String.join("\n", errorMessage, stackTrace);
+      LOG.info("Command failed %s", command.getActionId());
+      LOG.error(error);
+      return ExecuteResponse.newBuilder()
+          .setExitCode(result.getExitCode())
+          .setStderr(java.util.Objects.requireNonNull(ErrorInterceptor.prettyPrint(error)))
+          .build();
+    }
+    command.postExecute();
+    LOG.info("Command succeeded %s", command.getActionId());
+    // value of 0 is equivalent to unset in proto3 so this looks like an empty response in logs
+    return ExecuteResponse.newBuilder().setExitCode(0).build();
+  }
+
+  private void handleException(StreamObserver<?> responseObserver, String context, Throwable e) {
+    String message = String.format("Unexpected exception while %s", context);
+    LOG.error(message);
+    LOG.error(e);
+    responseObserver.onError(
+        io.grpc.Status.INTERNAL
+            .withDescription(message)
+            .augmentDescription(Throwables.getStackTraceAsString(e))
+            .asException());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BUCK
@@ -0,0 +1,31 @@
+load(
+    "@prelude//toolchains/android/tools:build_rules.bzl",
+    "buck_kotlin_library",
+)
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "core",
+    srcs = glob(
+        [
+            "*.java",
+            "*.kt",
+        ],
+    ),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:serialization",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/src/com/facebook/buck/util/unarchive:unarchive",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BuildTargetValue.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BuildTargetValue.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BuildTargetValue.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.core
+
+import com.facebook.buck.cd.model.java.BuildTargetValue.Type
+
+/**
+ * Build target representation used in java compilation. This class include only fields that used in
+ * java compilation.
+ */
+data class BuildTargetValue(val type: Type, val fullyQualifiedName: String) {
+  fun hasAbiJar(): Boolean {
+    return isSourceAbi || isSourceOnlyAbi
+  }
+
+  val isLibraryJar: Boolean
+    get() = this.type == Type.LIBRARY
+
+  val isSourceAbi: Boolean
+    get() = this.type == Type.SOURCE_ABI
+
+  val isSourceOnlyAbi: Boolean
+    get() = this.type == Type.SOURCE_ONLY_ABI
+
+  override fun toString(): String {
+    return this.fullyQualifiedName
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BuildTargetValueExtraParams.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BuildTargetValueExtraParams.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/core/BuildTargetValueExtraParams.kt
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.core
+
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.jvm.cd.serialization.RelPathSerializer
+import com.facebook.buck.util.environment.Platform
+import com.google.common.base.Preconditions
+import com.google.common.base.Strings
+import java.util.Optional
+import java.util.regex.Pattern
+
+/** Extra params from [BuildTargetValue] needed for Kotlin. */
+data class BuildTargetValueExtraParams(
+    val cellRelativeBasePath: RelPath,
+    val flavored: Boolean,
+    val basePathForBaseName: RelPath,
+    val shortNameAndFlavorPostfix: String,
+    val shortName: String,
+    val scratchDir: RelPath,
+) {
+  val moduleName: String
+    get() {
+      val pathSeparator = cellRelativeBasePath.fileSystem.separator
+      return (cellRelativeBasePath.toString().replace(pathSeparator, ".") + "." + shortName)
+    }
+
+  val kaptAnnotationGenPath: RelPath
+    get() = genPath.resolveRel("__kapt_generated__")
+
+  val kspAnnotationGenPath: RelPath
+    get() = genPath.resolveRel("__ksp_generated__")
+
+  val annotationOutputBasePath: RelPath =
+      scratchDir.resolveRel("annotation").resolve(basePathForBaseName)
+
+  /** Returns annotation path for the given `target` and `format` */
+  fun getAnnotationOutputPath(format: String): RelPath {
+    require(!format.startsWith("/")) { "format string should not start with a slash" }
+
+    return annotationOutputBasePath.resolveRel(formatLastSegment(format, shortNameAndFlavorPostfix))
+  }
+
+  val genPath: RelPath
+    /** Returns `gen` directory path for the given `target` */
+    get() {
+      val format = if (flavored) "%s" else "%s__"
+      return getGenPath(format)
+    }
+
+  /** Returns `gen` directory path for the given `target` and `format` */
+  fun getGenPath(format: String): RelPath {
+    Preconditions.checkArgument(
+        !format.startsWith("/"),
+        "format string should not start with a slash",
+    )
+    return getRelativePath(format, scratchDir.resolveRel("gen"))
+  }
+
+  /** Returns `gen` directory path for the given `target` and `format` */
+  fun getScratchPath(format: String): RelPath {
+    Preconditions.checkArgument(
+        !format.startsWith("/"),
+        "format string should not start with a slash",
+    )
+    return getRelativePath(format, scratchDir.resolveRel("bin"))
+  }
+
+  fun getRelativePath(format: String, directory: RelPath): RelPath {
+    return directory.resolve(getBasePath(format))
+  }
+
+  fun getBasePath(format: String): RelPath {
+    Preconditions.checkArgument(
+        !format.startsWith("/"),
+        "format string should not start with a slash",
+    )
+    return basePathForBaseName.resolveRel(formatLastSegment(format, shortNameAndFlavorPostfix))
+  }
+
+  companion object {
+    /** Creates [BuildTargetValueExtraParams] */
+    fun of(
+        cellRelativeBasePath: RelPath,
+        flavored: Boolean,
+        basePathForBaseName: RelPath,
+        shortNameAndFlavorPostfix: String,
+        shortName: String,
+        scratchDir: RelPath,
+    ): BuildTargetValueExtraParams {
+      Preconditions.checkArgument(
+          shortNameAndFlavorPostfix.startsWith(shortName),
+          "shortNameAndFlavorPostfix:%s should start with shortName:%s",
+          shortNameAndFlavorPostfix,
+          shortName,
+      )
+      return BuildTargetValueExtraParams(
+          cellRelativeBasePath,
+          flavored,
+          basePathForBaseName,
+          shortNameAndFlavorPostfix,
+          shortName,
+          scratchDir,
+      )
+    }
+
+    @JvmStatic
+    fun of(buildTargetValue: BuildTargetValue, buckOut: RelPath): BuildTargetValueExtraParams {
+      // in buck1: cell//base_path:target#flavor vs. in buck2: cell//base_path:target[flavor]
+      val buck1Style = "(#(.*))"
+      val buck2Style = "(\\[([^\\]]*)\\])"
+      val pattern =
+          Pattern.compile(String.format("(.*)//([^:]*):([^#\\[]*)(%s|%s)?", buck1Style, buck2Style))
+      val matcher = pattern.matcher(buildTargetValue.fullyQualifiedName)
+      if (!matcher.matches()) {
+        throw RuntimeException(
+            "Can't reconstruct extra params from fullyQualifiedName: " +
+                buildTargetValue.fullyQualifiedName,
+        )
+      }
+      val basePath = matcher.group(2)
+      val targetName = matcher.group(3)
+      var flavor = Optional.empty<String>()
+      if (!Strings.isNullOrEmpty(matcher.group(4))) {
+        flavor =
+            if (!Strings.isNullOrEmpty(matcher.group(6))) Optional.of(matcher.group(6))
+            else Optional.of(matcher.group(8))
+      }
+      val shortNameAndFlavorPostfix = targetName + flavor.map { str: String -> "#$str" }.orElse("")
+      return of(
+          RelPathSerializer.deserialize(basePath),
+          flavor.isPresent,
+          RelPathSerializer.deserialize(basePath),
+          shortNameAndFlavorPostfix,
+          targetName,
+          buckOut,
+      )
+    }
+
+    /**
+     * Returns a formatted string using the specified format string and a given argument. In case of
+     * windows platform back slashes would be replaced with forward slashes before applying string
+     * formatting.
+     *
+     * @param format [String.format] string for the path name. It should contain one "%s", which
+     *   will be filled in with the rule's short name. It should not start with a slash.
+     * @param arg an argument referenced by the format specifier in the format string.
+     * @return A formatted string
+     */
+    private fun formatLastSegment(format: String, arg: String): String {
+      var format = format
+      Preconditions.checkArgument(
+          !format.startsWith("/"),
+          "format string should not start with a slash",
+      )
+
+      if (Platform.detect() == Platform.WINDOWS) {
+        // TODO(nga): prohibit backslashes in format
+        format = format.replace('\\', '/')
+      }
+
+      return String.format(format, arg)
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ActionMetadata.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ActionMetadata.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ActionMetadata.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.Objects;
+import javax.annotation.Nullable;
+
+public class ActionMetadata {
+
+  private final Map<Path, String> previousDigest;
+  private final Map<Path, String> currentDigest;
+  private final Path incrementalConfigFilePath;
+
+  public ActionMetadata(
+      Path incrementalConfigFilePath,
+      Map<Path, String> previousDigest,
+      Map<Path, String> currentDigest) {
+    this.previousDigest = previousDigest;
+    this.currentDigest = currentDigest;
+    this.incrementalConfigFilePath = incrementalConfigFilePath;
+  }
+
+  public Map<Path, String> getPreviousDigest() {
+    return previousDigest;
+  }
+
+  public Map<Path, String> getCurrentDigest() {
+    return currentDigest;
+  }
+
+  @Nullable
+  public String getPreviousIncrementalConfigDigest() {
+    return previousDigest.get(incrementalConfigFilePath);
+  }
+
+  @Nullable
+  public String getCurrentIncrementalConfigDigest() {
+    return currentDigest.get(incrementalConfigFilePath);
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+    ActionMetadata that = (ActionMetadata) o;
+    return Objects.equals(previousDigest, that.previousDigest)
+        && Objects.equals(currentDigest, that.currentDigest)
+        && Objects.equals(incrementalConfigFilePath, that.incrementalConfigFilePath);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(previousDigest, currentDigest, incrementalConfigFilePath);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/AnnotationProcessorFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/AnnotationProcessorFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/AnnotationProcessorFactory.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.util.ClassLoaderCache;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
+import java.io.IOException;
+import java.util.List;
+import javax.annotation.processing.Processor;
+
+class AnnotationProcessorFactory implements AutoCloseable {
+  private final ClassLoader compilerClassLoader;
+  private final ClassLoaderCache globalClassLoaderCache;
+  private final ClassLoaderCache localClassLoaderCache = new ClassLoaderCache();
+  private final String buildTargetName;
+
+  AnnotationProcessorFactory(
+      ClassLoader compilerClassLoader,
+      ClassLoaderCache globalClassLoaderCache,
+      String buildTargetName) {
+    this.compilerClassLoader = compilerClassLoader;
+    this.globalClassLoaderCache = globalClassLoaderCache;
+    this.buildTargetName = buildTargetName;
+  }
+
+  @Override
+  public void close() throws IOException {
+    localClassLoaderCache.close();
+  }
+
+  public List<Processor> createProcessors(
+      JavacExecutionContext context, JavacPluginParams processorParams) {
+    ImmutableList.Builder<Processor> builder = ImmutableList.builder();
+    for (ResolvedJavacPluginProperties plugin : processorParams.getPluginProperties()) {
+      ClassLoader classLoader = getClassLoaderForProcessorGroup(plugin, context.getRuleCellRoot());
+      plugin.getProcessorNames().stream()
+          .map(name -> createProcessor(classLoader, name))
+          .forEach((v) -> builder.add(v));
+    }
+    return builder.build();
+  }
+
+  private Processor createProcessor(ClassLoader classLoader, String name) {
+    try {
+      Class<? extends Processor> aClass = classLoader.loadClass(name).asSubclass(Processor.class);
+      return aClass.newInstance();
+    } catch (ReflectiveOperationException e) {
+      // If this happens, then the build is really in trouble. Better warn the user.
+      throw new RuntimeException(
+          String.format("%s: javac unable to load annotation processor: %s", buildTargetName, name),
+          e);
+    }
+  }
+
+  @VisibleForTesting
+  ClassLoader getClassLoaderForProcessorGroup(
+      ResolvedJavacPluginProperties pluginParams, AbsPath relPathRoot) {
+    ClassLoaderCache cache;
+    // We can avoid lots of overhead in large builds by reusing the same classloader for java
+    // plugins. However, some plugins use static variables in a way that assumes
+    // there is only one instance running in the process at a time (or at all), and such plugin
+    // would break running inside of Buck. So we default to creating a new ClassLoader
+    // if any plugins meets those requirements.
+    if (pluginParams.getCanReuseClassLoader()) {
+      cache = globalClassLoaderCache;
+    } else {
+      cache = localClassLoaderCache;
+    }
+    return cache.getClassLoaderForClassPath(
+        compilerClassLoader, pluginParams.toUrlClasspath(relPathRoot));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BUCK
@@ -0,0 +1,181 @@
+load(
+    "@prelude//toolchains/android/tools:build_rules.bzl",
+    "buck_java_library",
+    "buck_kotlin_library",
+)
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "javac-internals",
+    srcs = [
+        "ZipEntryJavaFileObject.java",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
+
+buck_kotlin_library(
+    name = "support",
+    srcs = [
+        "ActionMetadata.java",
+        "AnnotationProcessorFactory.java",
+        "ClassUsageFileWriter.java",
+        "ClassUsageTracker.java",
+        "ClassUsageURIParser.java",
+        "CompileToJarStepFactory.java",
+        "CompilerOutputPaths.kt",
+        "CompilerOutputPathsValue.kt",
+        "CompilerParameters.kt",
+        "DefaultClassUsageFileWriter.java",
+        "DefaultSourceOnlyAbiRuleInfo.java",
+        "DefaultSourceOnlyAbiRuleInfoFactory.kt",
+        "DiagnosticCleaner.java",
+        "DiagnosticPrettyPrinter.java",
+        "DowngradeMissingAnnotationErrorMessager.java",
+        "FileManagerListener.java",
+        "ForwardingStandardJavaFileManager.java",
+        "JarDiffer.java",
+        "JarDumper.java",
+        "JarFileObject.java",
+        "JarParameters.kt",
+        "JavaInMemoryFileManager.java",
+        "JavaInMemoryFileObject.java",
+        "JavaNoOpFileObject.java",
+        "JavaPaths.java",
+        "JavacExecutionContext.kt",
+        "JavacLanguageLevelOptions.kt",
+        "JavacPluginParams.kt",
+        "JdkProvidedInMemoryJavac.java",
+        "Jsr199Javac.java",
+        "Jsr199JavacInvocation.java",
+        "ListenableFileManager.java",
+        "OptionsConsumer.java",
+        "PluginFactory.java",
+        "PluginLoaderJavaFileManager.java",
+        "ResolvedJavac.java",
+        "ResolvedJavacOptions.kt",
+        "ResolvedJavacPluginProperties.java",
+    ],
+    provided_deps = [
+        # Plugin API is loaded by the bootstrapper at runtime; don't need to depend on it strongly
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/api:api",
+    ],
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java:java",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/core:core",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:javac-internals",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api:api",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/javax:javax",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/lang/model:model",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin:plugin",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/version/utils:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses:usedclasses",
+        "prelude//toolchains/android/src/com/facebook/buck/step:step",
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps:isolatedsteps",
+        "prelude//toolchains/android/src/com/facebook/buck/util:process_executor",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/function:function",
+        "prelude//toolchains/android/src/com/facebook/buck/util/json:json",
+        "prelude//toolchains/android/src/com/facebook/buck/util/unarchive:unarchive",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:asm",
+        "prelude//toolchains/android/third-party:diffutils",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jackson-annotations",
+        "prelude//toolchains/android/third-party:jackson-core",
+        "prelude//toolchains/android/third-party:jackson-databind",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/core:core",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi:abi",
+        ":remove_classes_patterns_matcher",
+    ],
+)
+
+buck_java_library(
+    name = "remove_classes_patterns_matcher",
+    srcs = [
+        "RemoveClassesPatternsMatcher.java",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+    ],
+    exported_deps = [],
+)
+
+buck_kotlin_library(
+    name = "steps",
+    srcs = [
+        "BaseCompileToJarStepFactory.java",
+        "BaseJavacToJarStepFactory.java",
+        "CalculateClassAbiStep.java",
+        "CompileToJarStepFactory.java",
+        "CopyResourcesStep.java",
+        "DaemonJavacToJarStepFactory.java",
+        "JavaExtraParams.kt",
+        "JavaStepsBuilder.java",
+        "JavacPipelineState.java",
+        "JavacStep.java",
+    ],
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java:java",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command:command",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/java:command",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:serialization",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java:java",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/core:core",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi:abi",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api:api",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/runner:runner",
+        "prelude//toolchains/android/src/com/facebook/buck/step:step",
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps:isolatedsteps",
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps/java:java",
+        "prelude//toolchains/android/src/com/facebook/buck/util:process_executor",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:environment",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/src/com/facebook/buck/util/unarchive:unarchive",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jackson-annotations",
+        "prelude//toolchains/android/third-party:jackson-databind",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd:cd",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BaseCompileToJarStepFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BaseCompileToJarStepFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BaseCompileToJarStepFactory.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MakeCleanDirectoryIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MkdirIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.java.JarDirectoryStep;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableList.Builder;
+import com.google.common.collect.ImmutableMap;
+import java.util.Optional;
+import javax.annotation.Nullable;
+
+/** Provides a base implementation for post compile steps. */
+public abstract class BaseCompileToJarStepFactory<T extends CompileToJarStepFactory.ExtraParams>
+    implements CompileToJarStepFactory<T> {
+
+  protected BaseCompileToJarStepFactory() {}
+
+  @Override
+  public final void createCompileToJarStep(
+      RelPath buckOut,
+      AbsPath buildCellRootPath,
+      BuildTargetValue buildTargetValue,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      CompilerParameters compilerParameters,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters,
+      Builder<IsolatedStep> steps,
+      ImmutableMap<RelPath, RelPath> resourcesMap,
+      ResolvedJavac resolvedJavac,
+      @Nullable ActionMetadata actionMetadata,
+      T extraParams) {
+    Preconditions.checkArgument(libraryJarParameters != null || abiJarParameters == null);
+
+    steps.addAll(
+        getCompilerSetupIsolatedSteps(
+            resourcesMap,
+            compilerParameters.getOutputPaths(),
+            compilerParameters.getSourceFilePaths().isEmpty()));
+
+    JarParameters jarParameters =
+        abiJarParameters != null ? abiJarParameters : libraryJarParameters;
+    if (jarParameters != null) {
+      addJarSetupSteps(jarParameters, steps);
+    }
+
+    // Only run javac if there are .java or .kt files to compile or we need to shovel the manifest
+    // file
+    // into the built jar.
+    if (!compilerParameters.getSourceFilePaths().isEmpty()) {
+      // This adds the javac command, along with any supporting commands.
+      createCompileToJarStepImpl(
+          buckOut,
+          buildCellRootPath,
+          buildTargetValue,
+          compilerOutputPathsValue,
+          compilerParameters,
+          abiJarParameters,
+          libraryJarParameters,
+          steps,
+          resolvedJavac,
+          actionMetadata,
+          extraParams);
+    }
+
+    if (jarParameters != null) {
+      addJarCreationSteps(compilerParameters, steps, jarParameters);
+    }
+  }
+
+  /** Returns Compiler Setup steps */
+  public ImmutableList<IsolatedStep> getCompilerSetupIsolatedSteps(
+      ImmutableMap<RelPath, RelPath> resourcesMap,
+      CompilerOutputPaths outputPaths,
+      boolean emptySources) {
+    // Always create the output directory, even if there are no .java files to compile because there
+    // might be resources that need to be copied there.
+
+    Builder<IsolatedStep> steps = ImmutableList.builder();
+
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(outputPaths.getClassesDir()));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(outputPaths.getAnnotationPath()));
+
+    // If there are resources, then link them to the appropriate place in the classes directory.
+    steps.addAll(CopyResourcesStep.of(resourcesMap));
+
+    if (!emptySources) {
+      steps.add(new MkdirIsolatedStep(outputPaths.getPathToSourcesList().getParent()));
+      steps.add(new MkdirIsolatedStep(outputPaths.getWorkingDirectory()));
+    }
+
+    return steps.build();
+  }
+
+  protected void addJarSetupSteps(JarParameters jarParameters, Builder<IsolatedStep> steps) {
+    steps.add(new MkdirIsolatedStep(jarParameters.getJarPath().getParent()));
+  }
+
+  void addJarCreationSteps(
+      CompilerParameters compilerParameters,
+      Builder<IsolatedStep> steps,
+      JarParameters jarParameters) {
+    // No source files, only resources
+    if (compilerParameters.getSourceFilePaths().isEmpty()) {
+      steps.add(new JarDirectoryStep(jarParameters));
+    }
+  }
+
+  protected void createCompileToJarStepImpl(
+      RelPath buckOut,
+      AbsPath buildCellRootPath,
+      BuildTargetValue target,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      CompilerParameters compilerParameters,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters,
+      Builder<IsolatedStep> steps,
+      ResolvedJavac resolvedJavac,
+      @Nullable ActionMetadata actionMetadata,
+      T extraParams) {
+    Preconditions.checkArgument(abiJarParameters == null);
+    Preconditions.checkArgument(
+        libraryJarParameters != null
+            && libraryJarParameters
+                .getEntriesToJar()
+                .contains(compilerParameters.getOutputPaths().getClassesDir()));
+
+    createCompileStep(
+        buckOut,
+        buildCellRootPath,
+        target,
+        compilerOutputPathsValue,
+        compilerParameters,
+        steps,
+        resolvedJavac,
+        actionMetadata,
+        extraParams,
+        null,
+        false);
+
+    steps.add(new JarDirectoryStep(libraryJarParameters));
+  }
+
+  /**
+   * This can be used make the bootclasspath if available, to the postprocess classes commands.
+   *
+   * @return the bootclasspath.
+   */
+  protected Optional<String> getBootClasspath() {
+    return Optional.empty();
+  }
+
+  public abstract void createCompileStep(
+      RelPath buckOut,
+      AbsPath buildCellRootPath,
+      BuildTargetValue invokingRule,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      CompilerParameters parameters,
+      Builder<IsolatedStep> steps,
+      ResolvedJavac resolvedJavac,
+      @Nullable ActionMetadata actionMetadata,
+      T extraParams,
+      JarParameters abiJarParameters,
+      boolean mixedCompilationMode);
+
+  public boolean supportsCompilationDaemon() {
+    return false;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BaseJavacToJarStepFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BaseJavacToJarStepFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/BaseJavacToJarStepFactory.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MkdirIsolatedStep;
+import com.google.common.collect.ImmutableList;
+import javax.annotation.Nullable;
+
+/**
+ * Java implementation of compile to jar steps factory that doesn't depend on internal build graph
+ * datastructures, and only knows how to create compile steps.
+ */
+public class BaseJavacToJarStepFactory extends BaseCompileToJarStepFactory<JavaExtraParams> {
+  public BaseJavacToJarStepFactory() {}
+
+  @Override
+  public JavaExtraParams castExtraParams(ExtraParams extraParams) {
+    return (JavaExtraParams) extraParams;
+  }
+
+  @Override
+  public void createCompileStep(
+      RelPath buckOut,
+      AbsPath buildCellRootPath,
+      BuildTargetValue invokingRule,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      CompilerParameters parameters,
+      ImmutableList.Builder<IsolatedStep> steps,
+      ResolvedJavac resolvedJavac,
+      @Nullable ActionMetadata actionMetadata,
+      JavaExtraParams extraParams,
+      JarParameters abiJarParameters,
+      boolean mixedCompilation) {
+
+    CompilerOutputPaths outputPath = compilerOutputPathsValue.getByType(invokingRule.getType());
+    if (extraParams.getAddAnnotationPath()) {
+      addAnnotationGenFolderStep(steps, outputPath.getAnnotationPath());
+    }
+
+    ResolvedJavacOptions resolvedJavacOptions = extraParams.getResolvedJavacOptions();
+    steps.add(
+        new JavacStep(
+            resolvedJavac,
+            resolvedJavacOptions,
+            invokingRule,
+            buckOut,
+            compilerOutputPathsValue,
+            parameters,
+            extraParams.getSkipIfNoCompilationUnits(),
+            abiJarParameters,
+            null,
+            mixedCompilation));
+  }
+
+  protected void addAnnotationGenFolderStep(
+      ImmutableList.Builder<IsolatedStep> steps, RelPath annotationGenFolder) {
+    steps.add(new MkdirIsolatedStep(annotationGenFolder));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CalculateClassAbiStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CalculateClassAbiStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CalculateClassAbiStep.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.jvm.java.abi.StubJar;
+import com.facebook.buck.step.StepExecutionResult;
+import com.facebook.buck.step.StepExecutionResults;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.nio.file.Path;
+import javax.annotation.Nullable;
+
+/** Calculates class abi from the library.jar */
+public class CalculateClassAbiStep implements IsolatedStep {
+
+  private final RelPath binaryJar;
+  @Nullable private final RelPath existingAbiJar;
+  private final RelPath abiJar;
+  private final AbiGenerationMode compatibilityMode;
+
+  public CalculateClassAbiStep(
+      RelPath binaryJar,
+      @Nullable RelPath existingAbiJar,
+      RelPath abiJar,
+      AbiGenerationMode compatibilityMode) {
+    this.binaryJar = binaryJar;
+    this.existingAbiJar = existingAbiJar;
+    this.abiJar = abiJar;
+    this.compatibilityMode = compatibilityMode;
+  }
+
+  @Override
+  public StepExecutionResult executeIsolatedStep(IsolatedExecutionContext context)
+      throws IOException {
+    AbsPath ruleCellRoot = context.getRuleCellRoot();
+    AbsPath output = toAbsOutputPath(ruleCellRoot, abiJar);
+
+    try {
+      StubJar stubJar =
+          new StubJar(ruleCellRoot.resolve(binaryJar), false)
+              .setCompatibilityMode(compatibilityMode);
+      if (existingAbiJar != null
+          && ProjectFilesystemUtils.exists(ruleCellRoot, existingAbiJar.getPath())) {
+        stubJar = stubJar.setExistingAbiJar(ruleCellRoot.resolve(existingAbiJar));
+      }
+      stubJar.writeTo(output);
+    } catch (IllegalArgumentException e) {
+      throw new RuntimeException(String.format("Failed to calculate ABI for %s.", binaryJar), e);
+    }
+
+    return StepExecutionResults.SUCCESS;
+  }
+
+  private AbsPath toAbsOutputPath(AbsPath root, RelPath relativeOutputPath) throws IOException {
+    Path outputPath = ProjectFilesystemUtils.getPathForRelativePath(root, relativeOutputPath);
+    Preconditions.checkState(
+        !ProjectFilesystemUtils.exists(root, outputPath),
+        "Output file already exists: %s",
+        relativeOutputPath);
+
+    if (outputPath.getParent() != null
+        && !ProjectFilesystemUtils.exists(root, outputPath.getParent())) {
+      ProjectFilesystemUtils.createParentDirs(root, outputPath);
+    }
+    return root.resolve(relativeOutputPath);
+  }
+
+  @Override
+  public String getShortName() {
+    return "class_abi";
+  }
+
+  @Override
+  public String getIsolatedStepDescription(IsolatedExecutionContext context) {
+    return String.format("%s %s", getShortName(), binaryJar);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageFileWriter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageFileWriter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageFileWriter.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.google.common.collect.ImmutableMap;
+import java.nio.file.Path;
+import java.util.Set;
+
+public interface ClassUsageFileWriter {
+
+  void writeFile(
+      ImmutableMap<Path, Set<Path>> classUsages,
+      RelPath relativePath,
+      AbsPath rootPath,
+      RelPath configuredBuckOut);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageTracker.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageTracker.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageTracker.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.google.common.collect.ImmutableMap;
+import java.net.URI;
+import java.nio.file.Path;
+import java.util.Set;
+import javax.tools.FileObject;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+
+/**
+ * Tracks which classes are actually read by the compiler by providing a special {@link
+ * JavaFileManager}.
+ */
+class ClassUsageTracker implements FileManagerListener {
+
+  private final ClassUsageURIParser parser = new ClassUsageURIParser();
+
+  /**
+   * Returns a map from JAR path on disk to .class file paths within the jar for any classes that
+   * were used, and the count for how often those classes were read.
+   */
+  public ImmutableMap<Path, Set<Path>> getClassUsageMap() {
+    return parser.getClassUsageMap();
+  }
+
+  @Override
+  public void onFileRead(FileObject fileObject) {
+    if (!(fileObject instanceof JavaFileObject)) {
+      return;
+    }
+    JavaFileObject javaFileObject = (JavaFileObject) fileObject;
+    URI classFileJarUri = javaFileObject.toUri();
+    parser.parseAndRecordURI(classFileJarUri);
+  }
+
+  @Override
+  public void onFileWritten(FileObject file) {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageURIParser.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageURIParser.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClassUsageURIParser.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import java.net.URI;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+/** Take URI input for class usage data, and output the total class usage as map */
+public class ClassUsageURIParser {
+
+  private static final String FILE_SCHEME = "file";
+  private static final String JAR_SCHEME = "jar";
+  private static final String JIMFS_SCHEME = "jimfs"; // Used in tests
+
+  // Examples: First anonymous class is Foo$1.class. First local class named Bar is Foo$1Bar.class.
+  private static final Pattern LOCAL_OR_ANONYMOUS_CLASS = Pattern.compile("^.*\\$\\d.*.class$");
+
+  private final Map<Path, Set<Path>> resultBuilder = new HashMap<>();
+
+  /**
+   * Returns a map from JAR path on disk to .class file paths within the jar for any classes that
+   * were used, and the count for how often those classes were read.
+   */
+  public ImmutableMap<Path, Set<Path>> getClassUsageMap() {
+    return ImmutableMap.copyOf(resultBuilder);
+  }
+
+  /** Parse URI input and record it in class usage cache */
+  public void parseAndRecordURI(URI classFileJarUri) {
+    if (classFileJarUri.getScheme() == null || !classFileJarUri.getScheme().equals(JAR_SCHEME)) {
+      // Not in a jar; must not have been built with java_library
+      return;
+    }
+
+    // The jar: scheme is somewhat underspecified. See the JarURLConnection docs
+    // for the closest thing it has to documentation.
+    String jarUriSchemeSpecificPart = classFileJarUri.getRawSchemeSpecificPart();
+    String[] split = jarUriSchemeSpecificPart.split("!/");
+    Preconditions.checkState(split.length == 2);
+
+    if (isLocalOrAnonymousClass(split[1])) {
+      // The compiler reads local and anonymous classes because of the naive way in which it
+      // completes the enclosing class, but changes to them can't affect compilation of dependent
+      // classes so we don't need to consider them "used".
+      return;
+    }
+
+    URI jarFileUri = URI.create(split[0]);
+    Preconditions.checkState(
+        jarFileUri.getScheme().equals(FILE_SCHEME)
+            || jarFileUri.getScheme().equals(JIMFS_SCHEME)); // jimfs is used in tests
+    Path jarFilePath = Paths.get(jarFileUri);
+
+    // Using URI.create here for de-escaping
+    Path classPath = Paths.get(URI.create(split[1]).toString());
+
+    Preconditions.checkState(jarFilePath.isAbsolute());
+    Preconditions.checkState(!classPath.isAbsolute());
+
+    Set<Path> classpaths = resultBuilder.computeIfAbsent(jarFilePath, _path -> new HashSet<>());
+    classpaths.add(classPath);
+  }
+
+  private boolean isLocalOrAnonymousClass(String className) {
+    return LOCAL_OR_ANONYMOUS_CLASS.matcher(className).matches();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClasspathChecker.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClasspathChecker.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ClasspathChecker.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.io.file.PathListing;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
+import com.google.common.base.Splitter;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import java.io.File;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Locale;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import java.util.function.Predicate;
+
+public class ClasspathChecker {
+
+  private static final ImmutableSet<String> ALLOWED_EXTENSIONS_SET = ImmutableSet.of("jar", "zip");
+
+  private final String separator;
+  private final String pathSeparator;
+  private final Function<String, Path> toPathFunc;
+  private final Predicate<Path> isDirectoryFunc;
+  private final Predicate<Path> isFileFunc;
+  private final BiFunction<Path, String, Iterable<Path>> globberFunc;
+
+  public ClasspathChecker() {
+    this(
+        File.separator,
+        File.pathSeparator,
+        Paths::get,
+        Files::isDirectory,
+        Files::isRegularFile,
+        (path, glob) -> {
+          try {
+            return PathListing.listMatchingPaths(path, glob, PathListing.GET_PATH_MODIFIED_TIME);
+          } catch (IOException e) {
+            throw new UncheckedIOException(e);
+          }
+        });
+  }
+
+  @VisibleForTesting
+  ClasspathChecker(
+      String separator,
+      String pathSeparator,
+      Function<String, Path> toPathFunc,
+      Predicate<Path> isDirectoryFunc,
+      Predicate<Path> isFileFunc,
+      BiFunction<Path, String, Iterable<Path>> globberFunc) {
+    this.separator = separator;
+    this.pathSeparator = pathSeparator;
+    this.toPathFunc = toPathFunc;
+    this.isDirectoryFunc = isDirectoryFunc;
+    this.isFileFunc = isFileFunc;
+    this.globberFunc = globberFunc;
+  }
+
+  /**
+   * Parses a Java classpath string ("path/to/foo:baz.jar:blech.zip:path/to/*") and checks if at
+   * least one entry is valid (exists on disk).
+   *
+   * <p>From http://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html :
+   *
+   * <p>Class path entries can contain the basename wildcard character *, which is considered
+   * equivalent to specifying a list of all the files in the directory with the extension .jar or
+   * .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named
+   * foo. A classpath entry consisting simply of * expands to a list of all the jar files in the
+   * current directory.
+   */
+  public boolean validateClasspath(String classpath) {
+    for (String entry : Splitter.on(pathSeparator).split(classpath)) {
+      // On Windows, Path.endsWith("*") throws an error:
+      //
+      // java.nio.file.InvalidPathException: Illegal char <*> at index 0
+      //
+      // So, we split manually.
+      List<String> classpathComponents = Splitter.on(separator).splitToList(entry);
+      if (classpathComponents.isEmpty()) {
+        continue;
+      }
+
+      if (Iterables.getLast(classpathComponents).equals("*")) {
+        // Trim the * off the path.
+        List<String> dirComponents = classpathComponents.subList(0, classpathComponents.size() - 1);
+        Path entryDir = toPathFunc.apply(Joiner.on(separator).join(dirComponents));
+        if (!Iterables.isEmpty(globberFunc.apply(entryDir, "*.jar"))) {
+          return true;
+        } else if (!Iterables.isEmpty(globberFunc.apply(entryDir, "*.JAR"))) {
+          return true;
+        }
+      } else {
+        Path entryPath = toPathFunc.apply(entry);
+        if (isDirectoryFunc.test(entryPath)) {
+          return true;
+        } else if (isFileFunc.test(entryPath)
+            && ALLOWED_EXTENSIONS_SET.contains(
+                com.google.common.io.Files.getFileExtension(
+                    entryPath.toString().toLowerCase(Locale.US)))) {
+          return true;
+        }
+      }
+    }
+    return false;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompileToJarStepFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompileToJarStepFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompileToJarStepFactory.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import javax.annotation.Nullable;
+
+/**
+ * Interface for adding the steps for compiling source to producing a JAR, for JVM languages.
+ *
+ * @param <T> Type of extra parameters needed to create these steps.
+ */
+public interface CompileToJarStepFactory<T extends CompileToJarStepFactory.ExtraParams> {
+
+  /**
+   * Add the steps to {@code steps} to compile the sources (in {@code compilerParameters}) with java
+   * compiler {@code resolvedJavac} for the build target {@code buildTargetValue} to a JAR, located
+   * in {@code compilerOutputPathsValue}.
+   *
+   * <p>Language-specific parameters are passed through {@code extraParams}, which is instantiated
+   * to a concrete type by implementations of this interface.
+   */
+  void createCompileToJarStep(
+      RelPath buckOut,
+      AbsPath buildCellRootPath,
+      BuildTargetValue buildTargetValue,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      CompilerParameters compilerParameters,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters,
+      ImmutableList.Builder<IsolatedStep> steps,
+      ImmutableMap<RelPath, RelPath> resourcesMap,
+      ResolvedJavac resolvedJavac,
+      @Nullable ActionMetadata actionMetadata,
+      T extraParams);
+
+  /** Upcasts {@code extraParams} to the type of parameter expected by this factory. */
+  T castExtraParams(ExtraParams extraParams);
+
+  /** Extra params marker interface. */
+  interface ExtraParams {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerOutputPaths.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerOutputPaths.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerOutputPaths.kt
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java
+
+import com.facebook.buck.core.filesystems.RelPath
+import java.util.Optional
+
+/** Provides access to the various output paths for a java library. */
+data class CompilerOutputPaths(
+    val classesDir: RelPath,
+    val outputJarDirPath: RelPath,
+    val abiJarPath: Optional<RelPath>,
+    val annotationPath: RelPath,
+    val pathToSourcesList: RelPath,
+    val workingDirectory: RelPath,
+    val outputJarPath: Optional<RelPath>,
+) {
+  companion object {
+    /**
+     * Returns a path to a file that contains dependencies used in the compilation to be consumed by
+     * buck2
+     */
+    @JvmStatic
+    fun getDepFilePath(outputJarDirPath: RelPath): RelPath {
+      return outputJarDirPath.resolveRel("dep-file.txt")
+    }
+
+    /** Returns a path to a file that contains the .jars used in the compilation */
+    @JvmStatic
+    fun getUsedJarsFilePath(outputJarDirPath: RelPath): RelPath {
+      return outputJarDirPath.resolveRel("used-jars.json")
+    }
+
+    /** Returns a path to a file that contains dependencies used in the compilation */
+    @JvmStatic
+    fun getJavaDepFilePath(outputJarDirPath: RelPath): RelPath {
+      return outputJarDirPath.resolveRel("used-classes.json")
+    }
+
+    /** Returns a path to a file that contains all dependencies used in Kotlin compilation */
+    @JvmStatic
+    fun getKotlinDepFilePath(outputJarDirPath: RelPath): RelPath {
+      return outputJarDirPath.resolveRel("kotlin-used-classes.json")
+    }
+
+    @JvmStatic
+    fun getJvmAbiGenFilePath(outputJarDirPath: RelPath): RelPath {
+      return outputJarDirPath.resolveRel("jvm-abi-gen.jar")
+    }
+
+    /**
+     * Returns a path to the temp file that contains dependencies directly used in Kotlin compiler
+     */
+    @JvmStatic
+    fun getKotlinTempDepFilePath(reportDirPath: RelPath): RelPath {
+      return reportDirPath.resolveRel("kotlin-used-classes-tmp.txt")
+    }
+
+    /** Returns a path to a file that contains files accessed by KAPT in Kotlin compilation */
+    @JvmStatic
+    fun getKAPTDepFilePath(reportDirPath: RelPath): RelPath {
+      return reportDirPath.resolveRel("kapt-used-classes-tmp.txt")
+    }
+
+    /** Returns a path to a file that contains files accessed by KSP in Kotlin compilation */
+    @JvmStatic
+    fun getKspDepFilePath(reportDirPath: RelPath): RelPath {
+      return reportDirPath.resolveRel("ksp-used-classes-tmp.txt")
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerOutputPathsValue.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerOutputPathsValue.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerOutputPathsValue.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java
+
+import com.facebook.buck.cd.model.java.BuildTargetValue
+
+/**
+ * Value object that contains [CompilerOutputPaths] for library, source abi and source only abi
+ * targets as well as library target fully qualified name.
+ */
+data class CompilerOutputPathsValue(
+    val libraryTargetFullyQualifiedName: String,
+    val libraryCompilerOutputPath: CompilerOutputPaths,
+    val sourceAbiCompilerOutputPath: CompilerOutputPaths,
+    val sourceOnlyAbiCompilerOutputPath: CompilerOutputPaths,
+) {
+  /** Returns [CompilerOutputPaths] by given `type` */
+  fun getByType(type: BuildTargetValue.Type): CompilerOutputPaths {
+    return when (type) {
+      BuildTargetValue.Type.LIBRARY -> libraryCompilerOutputPath
+      BuildTargetValue.Type.SOURCE_ABI -> sourceAbiCompilerOutputPath
+      BuildTargetValue.Type.SOURCE_ONLY_ABI -> sourceOnlyAbiCompilerOutputPath
+      BuildTargetValue.Type.UNKNOWN,
+      BuildTargetValue.Type.UNRECOGNIZED -> throw IllegalStateException("$type is not supported")
+
+      else -> throw IllegalStateException("$type is not supported")
+    }
+  }
+
+  companion object {
+    /** Creates [CompilerOutputPathsValue] */
+    @JvmStatic
+    fun of(
+        libraryTargetFullyQualifiedName: String,
+        libraryCompilerOutputPath: CompilerOutputPaths,
+        sourceAbiCompilerOutputPath: CompilerOutputPaths,
+        sourceOnlyAbiCompilerOutputPath: CompilerOutputPaths,
+    ): CompilerOutputPathsValue {
+      return CompilerOutputPathsValue(
+          libraryTargetFullyQualifiedName,
+          libraryCompilerOutputPath,
+          sourceAbiCompilerOutputPath,
+          sourceOnlyAbiCompilerOutputPath,
+      )
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerParameters.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerParameters.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CompilerParameters.kt
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory
+import com.google.common.collect.ImmutableList
+import com.google.common.collect.ImmutableSortedSet
+
+data class CompilerParameters(
+    val sourceFilePaths: ImmutableSortedSet<RelPath>,
+    val classpathEntries: ImmutableList<RelPath>,
+    val classpathSnapshots: ImmutableList<RelPath>,
+    val outputPaths: CompilerOutputPaths,
+    val abiGenerationMode: AbiGenerationMode,
+    val abiCompatibilityMode: AbiGenerationMode,
+    val shouldTrackClassUsage: Boolean,
+    val sourceOnlyAbiRuleInfoFactory: SourceOnlyAbiRuleInfoFactory?,
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CopyResourcesStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CopyResourcesStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/CopyResourcesStep.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MkdirIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.SymlinkIsolatedStep;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+
+/** Copies (by creating symlinks) resources from existing paths to desired paths. */
+public class CopyResourcesStep {
+
+  private CopyResourcesStep() {}
+
+  /** Copies (by creating symlinks) resources from existing paths to desired paths. */
+  public static ImmutableList<IsolatedStep> of(ImmutableMap<RelPath, RelPath> resources) {
+    ImmutableList.Builder<IsolatedStep> steps =
+        ImmutableList.builderWithExpectedSize(resources.size() * 2);
+    for (Map.Entry<RelPath, RelPath> entry : resources.entrySet()) {
+      RelPath existingPath = entry.getKey();
+      RelPath linkPath = entry.getValue();
+
+      steps.add(new MkdirIsolatedStep(linkPath.getParent()));
+      steps.add(new SymlinkIsolatedStep(existingPath, linkPath));
+    }
+    return steps.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DaemonJavacToJarStepFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DaemonJavacToJarStepFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DaemonJavacToJarStepFactory.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.abi.AbiGenerationModeUtils;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import javax.annotation.Nullable;
+
+/**
+ * Java implementation of compile to jar steps factory that doesn't depend on an internal build
+ * graph datastructures, intended to be used from the Daemon worker.
+ */
+public class DaemonJavacToJarStepFactory extends BaseJavacToJarStepFactory {
+
+  private static final Logger LOG = Logger.get(DaemonJavacToJarStepFactory.class);
+
+  public DaemonJavacToJarStepFactory() {}
+
+  @Override
+  public void createCompileToJarStepImpl(
+      RelPath buckOut,
+      AbsPath buildCellRootPath,
+      BuildTargetValue invokingRule,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      CompilerParameters compilerParameters,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters,
+      ImmutableList.Builder<IsolatedStep> steps,
+      ResolvedJavac resolvedJavac,
+      @Nullable ActionMetadata actionMetadata,
+      JavaExtraParams extraParams) {
+    Preconditions.checkArgument(
+        libraryJarParameters == null
+            || libraryJarParameters
+                .getEntriesToJar()
+                .contains(compilerParameters.getOutputPaths().getClassesDir()));
+
+    // In order to use direct spooling to the Jar:
+    // (1) It must be enabled through a .buckconfig.
+    // (2) The target must have 0 postprocessing steps.
+    // (3) Tha compile API must be JSR 199.
+    boolean isSpoolingToJarEnabled =
+        AbiGenerationModeUtils.isNotClassAbi(compilerParameters.getAbiGenerationMode())
+            || resolvedJavac instanceof Jsr199Javac.ResolvedJsr199Javac;
+
+    if (isSpoolingToJarEnabled) {
+      steps.add(
+          new JavacStep(
+              resolvedJavac,
+              extraParams.getResolvedJavacOptions(),
+              invokingRule,
+              buckOut,
+              compilerOutputPathsValue,
+              compilerParameters,
+              // javac writes libraryJarParameters here, so it must run even with nothing to compile
+              /* skipIfNoCompilationUnits */ false,
+              abiJarParameters,
+              libraryJarParameters,
+              false));
+    } else {
+      super.createCompileToJarStepImpl(
+          buckOut,
+          buildCellRootPath,
+          invokingRule,
+          compilerOutputPathsValue,
+          compilerParameters,
+          null,
+          libraryJarParameters,
+          steps,
+          resolvedJavac,
+          actionMetadata,
+          extraParams);
+    }
+  }
+
+  @Override
+  public boolean supportsCompilationDaemon() {
+    return true;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultClassUsageFileWriter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultClassUsageFileWriter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultClassUsageFileWriter.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.util.json.ObjectMappers;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedMap;
+import com.google.common.collect.ImmutableSortedSet;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.Set;
+
+public class DefaultClassUsageFileWriter implements ClassUsageFileWriter {
+
+  @Override
+  public void writeFile(
+      ImmutableMap<Path, Set<Path>> classUsages,
+      RelPath relativePath,
+      AbsPath rootPath,
+      RelPath configuredBuckOut) {
+    try {
+      AbsPath parent = rootPath.resolve(relativePath).getParent();
+      Path parentRelativePath = rootPath.relativize(parent).getPath();
+      Preconditions.checkState(
+          ProjectFilesystemUtils.exists(rootPath, parentRelativePath),
+          "directory must exist: %s",
+          parent);
+
+      ObjectMappers.WRITER.writeValue(
+          rootPath.resolve(relativePath).toFile(),
+          relativizeMap(classUsages, rootPath, configuredBuckOut));
+    } catch (IOException e) {
+      throw new RuntimeException("Unable to write used classes file.", e);
+    }
+  }
+
+  protected static ImmutableSortedMap<Path, Set<Path>> relativizeMap(
+      ImmutableMap<Path, Set<Path>> classUsages, AbsPath rootPath, RelPath configuredBuckOut) {
+    ImmutableSortedMap.Builder<Path, Set<Path>> builder = ImmutableSortedMap.naturalOrder();
+
+    for (Map.Entry<Path, Set<Path>> jarClassesEntry : classUsages.entrySet()) {
+      Path jarAbsolutePath = jarClassesEntry.getKey();
+      // Don't include jars that are outside of the project
+      // Paths outside the project would make these class usage files problematic for caching.
+      // Fortunately, such paths are also not interesting for the main use cases that these files
+      // address, namely understanding the dependencies one java rule has on others. Jar files
+      // outside the project are coming from a build tool (e.g. JDK or Android SDK).
+      // Here we first check to see if the path is inside the root filesystem of the build
+      // If not, we check to see if it's under one of the other cell roots.
+      // If the the absolute path does not reside under any cell root, we exclude it
+      ProjectFilesystemUtils.getPathRelativeToProjectRoot(
+              rootPath, configuredBuckOut, jarAbsolutePath)
+          .ifPresent(
+              projectPath ->
+                  builder.put(projectPath, ImmutableSortedSet.copyOf(jarClassesEntry.getValue())));
+    }
+
+    return builder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultSourceOnlyAbiRuleInfo.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultSourceOnlyAbiRuleInfo.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultSourceOnlyAbiRuleInfo.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory.SourceOnlyAbiRuleInfo;
+import com.facebook.buck.jvm.java.lang.model.MoreElements;
+import java.io.IOException;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import javax.annotation.Nullable;
+import javax.lang.model.element.Element;
+import javax.lang.model.util.Elements;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardLocation;
+
+class DefaultSourceOnlyAbiRuleInfo implements SourceOnlyAbiRuleInfo {
+
+  private final String fullyQualifiedBuildTargetName;
+  private final boolean ruleIsRequiredForSourceOnlyAbi;
+
+  private final Map<String, Set<String>> packagesContents = new HashMap<>();
+  private final JavaFileManager fileManager;
+
+  public DefaultSourceOnlyAbiRuleInfo(
+      JavaFileManager fileManager,
+      String fullyQualifiedBuildTargetName,
+      boolean ruleIsRequiredForSourceOnlyAbi) {
+    this.fullyQualifiedBuildTargetName = fullyQualifiedBuildTargetName;
+    this.ruleIsRequiredForSourceOnlyAbi = ruleIsRequiredForSourceOnlyAbi;
+    this.fileManager = fileManager;
+  }
+
+  private JavaFileManager getFileManager() {
+    return Objects.requireNonNull(fileManager);
+  }
+
+  @Override
+  public String getRuleName() {
+    return fullyQualifiedBuildTargetName;
+  }
+
+  @Override
+  public boolean ruleIsRequiredForSourceOnlyAbi() {
+    return ruleIsRequiredForSourceOnlyAbi;
+  }
+
+  @Override
+  @Nullable
+  public String getOwningTarget(Elements elements, Element element) {
+    return null;
+  }
+
+  @Override
+  public boolean elementIsAvailableForSourceOnlyAbi(Elements elements, Element element) {
+    return classIsOnBootClasspath(elements, element);
+  }
+
+  private boolean classIsOnBootClasspath(Elements elements, Element element) {
+    String binaryName = elements.getBinaryName(MoreElements.getTypeElement(element)).toString();
+    String packageName = getPackageName(binaryName);
+    Set<String> packageContents = getBootclasspathPackageContents(packageName);
+    return packageContents.contains(binaryName);
+  }
+
+  private Set<String> getBootclasspathPackageContents(String packageName) {
+    Set<String> packageContents = packagesContents.get(packageName);
+    if (packageContents == null) {
+      packageContents = new HashSet<>();
+
+      try {
+        JavaFileManager fileManager = getFileManager();
+        for (JavaFileObject javaFileObject :
+            fileManager.list(
+                StandardLocation.PLATFORM_CLASS_PATH,
+                packageName,
+                EnumSet.of(JavaFileObject.Kind.CLASS),
+                true)) {
+          packageContents.add(
+              fileManager.inferBinaryName(StandardLocation.PLATFORM_CLASS_PATH, javaFileObject));
+        }
+      } catch (IOException e) {
+        throw new RuntimeException("Failed to list boot classpath contents.", e);
+        // Do nothing
+      }
+      packagesContents.put(packageName, packageContents);
+    }
+    return packageContents;
+  }
+
+  private String getPackageName(String binaryName) {
+    int lastDot = binaryName.lastIndexOf('.');
+    if (lastDot < 0) {
+      return "";
+    }
+
+    return binaryName.substring(0, lastDot);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultSourceOnlyAbiRuleInfoFactory.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultSourceOnlyAbiRuleInfoFactory.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DefaultSourceOnlyAbiRuleInfoFactory.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java
+
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory.SourceOnlyAbiRuleInfo
+import javax.tools.JavaFileManager
+
+/** Default factory for SourceOnlyAbiRuleInfos. */
+data class DefaultSourceOnlyAbiRuleInfoFactory(
+    val fullyQualifiedBuildTargetName: String,
+    val ruleIsRequiredForSourceOnlyAbi: Boolean,
+) : SourceOnlyAbiRuleInfoFactory {
+  override fun create(fileManager: JavaFileManager): SourceOnlyAbiRuleInfo {
+    return DefaultSourceOnlyAbiRuleInfo(
+        fileManager,
+        fullyQualifiedBuildTargetName,
+        ruleIsRequiredForSourceOnlyAbi,
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DiagnosticCleaner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DiagnosticCleaner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DiagnosticCleaner.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import javax.tools.Diagnostic;
+import javax.tools.JavaFileObject;
+
+public final class DiagnosticCleaner {
+
+  private static final Set<String> RECOVERABLE_ERRORS =
+      new HashSet<String>() {
+        {
+          add("compiler.err.cant.resolve.location");
+          add("compiler.err.doesnt.exist");
+        }
+      };
+
+  private DiagnosticCleaner() {}
+
+  public static List<Diagnostic<? extends JavaFileObject>> clean(
+      List<Diagnostic<? extends JavaFileObject>> diagnostics) {
+    List<Diagnostic<? extends JavaFileObject>> result = removeDuplicates(diagnostics);
+
+    sortRecoverableErrorsLast(result);
+
+    return result;
+  }
+
+  private static void sortRecoverableErrorsLast(List<Diagnostic<? extends JavaFileObject>> result) {
+    result.sort(
+        (o1, o2) -> {
+          String code1 = o1.getCode();
+          String code2 = o2.getCode();
+
+          if (isRecoverableErrorCode(code1)) {
+            if (isRecoverableErrorCode(code2)) {
+              return 0;
+            }
+            return 1;
+          } else if (isRecoverableErrorCode(code2)) {
+            return -1;
+          }
+
+          return 0;
+        });
+  }
+
+  private static List<Diagnostic<? extends JavaFileObject>> removeDuplicates(
+      List<Diagnostic<? extends JavaFileObject>> diagnostics) {
+    Set<String> seenDiagnostics = new HashSet<>();
+    List<Diagnostic<? extends JavaFileObject>> result = new ArrayList<>(diagnostics.size());
+
+    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
+      String diagnosticString = diagnosticToString(diagnostic);
+      if (!seenDiagnostics.contains(diagnosticString)) {
+        result.add(diagnostic);
+      }
+      seenDiagnostics.add(diagnosticString);
+    }
+    return result;
+  }
+
+  static String diagnosticToString(Diagnostic<? extends JavaFileObject> diagnostic) {
+    return String.format(
+        "%s %s %d %d %d %d %d %s",
+        diagnostic.getKind(),
+        diagnostic.getSource(),
+        diagnostic.getPosition(),
+        diagnostic.getStartPosition(),
+        diagnostic.getEndPosition(),
+        diagnostic.getLineNumber(),
+        diagnostic.getColumnNumber(),
+        diagnostic.getCode());
+  }
+
+  private static boolean isRecoverableErrorCode(String code) {
+    return RECOVERABLE_ERRORS.contains(code);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DiagnosticPrettyPrinter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DiagnosticPrettyPrinter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DiagnosticPrettyPrinter.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Locale;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import javax.tools.Diagnostic;
+import javax.tools.JavaFileObject;
+
+/**
+ * Take a {@link Diagnostic} and pretty print it, using the same formatting as you'd find in the
+ * Oracle javac implementation. This ensures that no matter which compiler is being used, output to
+ * the user is consistent.
+ *
+ * <p>Output is given in the following format, where "summary" is the first line of {@link
+ * Diagnostic#getMessage(Locale)} and "Remainder of message" are all the other lines.
+ *
+ * <pre>
+ * Path-to-file:line-number: kind-of-error: summary\n
+ *
+ * Context from code
+ *      ^
+ * Remainder of message
+ * </pre>
+ */
+public class DiagnosticPrettyPrinter {
+
+  private DiagnosticPrettyPrinter() {
+    // utility class
+  }
+
+  public static String format(Diagnostic<? extends JavaFileObject> diagnostic) {
+    return format(diagnostic, Optional.empty());
+  }
+
+  public static String format(
+      Diagnostic<? extends JavaFileObject> diagnostic, Optional<AbsPath> sourceRoot) {
+    /*
+    In BasicDiagnosticFormatter.class, the default format used is: "%f:%l:%_%p%L%m"
+    This expands to:
+
+    "filename":"line":" ""kind""lint category""format message"
+
+    Format message is implemented in the BasicDiagnosticFormatter. This splits the message into
+    lines and picks the first one as the summary (seems reasonable to do). If details are
+    requested, then the remaining lines are added. Details are always requested.
+    */
+
+    StringBuilder builder = new StringBuilder();
+
+    JavaFileObject source = diagnostic.getSource();
+    if (source != null && !source.getName().isEmpty()) {
+      String sourcePathString = source.getName();
+      try {
+        Path sourcePath = Paths.get(source.getName());
+        if (sourceRoot.isPresent() && sourcePath.isAbsolute()) {
+          sourcePathString = sourceRoot.get().getPath().relativize(sourcePath).toString();
+        }
+      } catch (Exception e) {
+        // Do nothing. We'll just leave the path as is.
+      }
+
+      builder.append(sourcePathString).append(":").append(diagnostic.getLineNumber());
+    }
+
+    builder
+        .append(": ")
+        .append(diagnostic.getKind().toString().toLowerCase(Locale.US))
+        .append(": ");
+
+    String formattedMessage = diagnostic.getMessage(Locale.getDefault());
+    String[] parts = formattedMessage.split(System.lineSeparator());
+    if (parts.length == 0) {
+      parts = new String[] {""};
+    }
+
+    // Use the first line as a summary. With the normal Oracle JSR199 javac, the remaining lines are
+    // more detailed diagnostics, which we don't normally display. With ECJ, there's no additional
+    // information anyway, so it doesn't matter that we discard the remaining output.
+    builder.append(parts[0]).append(System.lineSeparator());
+
+    appendContext(builder, diagnostic, source);
+
+    // If there was additional information in the message, append it now.
+    for (int i = 1; i < parts.length; i++) {
+      builder.append(System.lineSeparator()).append(parts[i]);
+    }
+
+    return builder.toString();
+  }
+
+  private static void appendContext(
+      StringBuilder builder,
+      Diagnostic<? extends JavaFileObject> diagnostic,
+      @Nullable JavaFileObject source) {
+
+    if (source == null) {
+      return;
+    }
+
+    Optional<String> line = getLine(source, diagnostic.getLineNumber());
+    if (line.isPresent()) {
+      builder.append(line.get()).append(System.lineSeparator());
+      for (long i = 1; i < diagnostic.getColumnNumber(); i++) {
+        builder.append(" ");
+      }
+      builder.append("^");
+    }
+  }
+
+  private static Optional<String> getLine(JavaFileObject source, long line) {
+    if (line < 0) {
+      return Optional.empty();
+    }
+
+    String toReturn = null;
+    try (BufferedReader reader = new BufferedReader(source.openReader(true))) {
+      for (long i = 0; i < line; i++) {
+        toReturn = reader.readLine();
+      }
+    } catch (IOException e) {
+      // Do nothing. We're just trying to get some context, but we've failed.
+      return Optional.empty();
+    }
+
+    return Optional.ofNullable(toReturn);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DowngradeMissingAnnotationErrorMessager.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DowngradeMissingAnnotationErrorMessager.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/DowngradeMissingAnnotationErrorMessager.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import javax.annotation.processing.Messager;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.tools.Diagnostic;
+
+public class DowngradeMissingAnnotationErrorMessager implements Messager {
+
+  private final Messager delegate;
+
+  public DowngradeMissingAnnotationErrorMessager(Messager delegate) {
+    this.delegate = delegate;
+  }
+
+  @Override
+  public void printMessage(Diagnostic.Kind kind, CharSequence charSequence) {
+    delegate.printMessage(kind, charSequence);
+  }
+
+  @Override
+  public void printMessage(Diagnostic.Kind kind, CharSequence charSequence, Element element) {
+    delegate.printMessage(kind, charSequence, element);
+  }
+
+  @Override
+  public void printMessage(
+      Diagnostic.Kind kind,
+      CharSequence charSequence,
+      Element element,
+      AnnotationMirror annotationMirror) {
+    if (annotationMirror != null && kind == Diagnostic.Kind.ERROR) {
+      delegate.printMessage(Diagnostic.Kind.WARNING, charSequence, element, annotationMirror);
+    } else {
+      delegate.printMessage(kind, charSequence, element, annotationMirror);
+    }
+  }
+
+  @Override
+  public void printMessage(
+      Diagnostic.Kind kind,
+      CharSequence charSequence,
+      Element element,
+      AnnotationMirror annotationMirror,
+      AnnotationValue annotationValue) {
+    delegate.printMessage(kind, charSequence, element, annotationMirror, annotationValue);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/FileManagerListener.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/FileManagerListener.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/FileManagerListener.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import javax.tools.FileObject;
+
+interface FileManagerListener {
+  void onFileRead(FileObject file);
+
+  void onFileWritten(FileObject file);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ForwardingStandardJavaFileManager.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ForwardingStandardJavaFileManager.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ForwardingStandardJavaFileManager.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import java.io.File;
+import java.io.IOException;
+import javax.tools.ForwardingJavaFileManager;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardJavaFileManager;
+
+public class ForwardingStandardJavaFileManager
+    extends ForwardingJavaFileManager<StandardJavaFileManager> implements StandardJavaFileManager {
+
+  public ForwardingStandardJavaFileManager(StandardJavaFileManager fileManager) {
+    super(fileManager);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(
+      Iterable<? extends File> files) {
+    return fileManager.getJavaFileObjectsFromFiles(files);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) {
+    return fileManager.getJavaFileObjects(files);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
+    return fileManager.getJavaFileObjectsFromStrings(names);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) {
+    return fileManager.getJavaFileObjects(names);
+  }
+
+  @Override
+  public void setLocation(Location location, Iterable<? extends File> path) throws IOException {
+    fileManager.setLocation(location, path);
+  }
+
+  @Override
+  public Iterable<? extends File> getLocation(Location location) {
+    return fileManager.getLocation(location);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarDiffer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarDiffer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarDiffer.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.google.common.io.Files;
+import difflib.DiffUtils;
+import difflib.Patch;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.List;
+
+public final class JarDiffer {
+  private final Path left;
+  private final Path right;
+  private final JarDumper jarDumper = new JarDumper();
+
+  public static List<String> diffJars(Path left, Path right) throws IOException {
+    return new JarDiffer(left, right).diff();
+  }
+
+  public JarDiffer(Path left, Path right) {
+    this.left = left;
+    this.right = right;
+  }
+
+  public JarDiffer setAsmFlags(int asmFlags) {
+    jarDumper.setAsmFlags(asmFlags);
+    return this;
+  }
+
+  public List<String> diff() throws IOException {
+    if (Files.equal(left.toFile(), right.toFile())) {
+      return Collections.emptyList();
+    }
+
+    List<String> leftDump = jarDumper.dump(left);
+    List<String> rightDump = jarDumper.dump(right);
+
+    Patch<String> diff = DiffUtils.diff(leftDump, rightDump);
+    return DiffUtils.generateUnifiedDiff(left.toString(), right.toString(), leftDump, diff, 4);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarDumper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarDumper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarDumper.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.google.common.hash.Hashing;
+import com.google.common.hash.HashingInputStream;
+import com.google.common.io.ByteStreams;
+import com.google.common.io.CharStreams;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintWriter; // NOPMD required by API
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.stream.Stream;
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.util.Textifier;
+import org.objectweb.asm.util.TraceClassVisitor;
+
+public class JarDumper {
+  private int asmFlags = 0;
+
+  /**
+   * Sets the flags that are passed to ASM's {@link ClassReader} when dumping class files. See
+   * {@link ClassReader#accept(ClassVisitor, int)};
+   *
+   * @param asmFlags
+   * @return
+   */
+  public JarDumper setAsmFlags(int asmFlags) {
+    this.asmFlags = asmFlags;
+    return this;
+  }
+
+  public List<String> dump(Path jarPath) throws IOException {
+    List<String> result = new ArrayList<>();
+    result.add("Directory:");
+    try (JarFile abiJar = new JarFile(jarPath.toFile())) {
+      abiJar.stream().map(JarEntry::toString).forEach(result::add);
+
+      result.add("");
+      result.add("Contents:");
+      abiJar.stream()
+          .flatMap(
+              entry ->
+                  Stream.concat(
+                      Stream.of(String.format("%s:", entry.getName())),
+                      Stream.concat(dumpEntry(abiJar, entry), Stream.of(""))))
+          .forEach(result::add);
+    }
+
+    return result;
+  }
+
+  public Stream<String> dumpEntry(JarFile file, JarEntry entry) {
+    try (InputStream inputStream = file.getInputStream(entry)) {
+      String fileName = entry.getName();
+      if (fileName.endsWith(".class")) {
+        return dumpClassFile(inputStream);
+      } else if (isTextFile(fileName)) {
+        return dumpTextFile(inputStream);
+      } else {
+        return dumpBinaryFile(fileName, inputStream);
+      }
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  protected static boolean isTextFile(String fileName) {
+    return fileName.equals(JarFile.MANIFEST_NAME)
+        || fileName.endsWith(".java")
+        || fileName.endsWith(".json")
+        || fileName.endsWith(".txt");
+  }
+
+  private Stream<String> dumpClassFile(InputStream stream) throws IOException {
+    byte[] textifiedClass;
+    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        PrintWriter pw = new PrintWriter(bos)) { // NOPMD required by API
+      ClassReader reader = new ClassReader(stream);
+      TraceClassVisitor traceVisitor = new TraceClassVisitor(null, new Textifier(), pw);
+      reader.accept(traceVisitor, asmFlags);
+      textifiedClass = bos.toByteArray();
+    }
+
+    try (InputStreamReader streamReader =
+        new InputStreamReader(new ByteArrayInputStream(textifiedClass))) {
+      return CharStreams.readLines(streamReader).stream();
+    }
+  }
+
+  private Stream<String> dumpTextFile(InputStream inputStream) throws IOException {
+    try (InputStreamReader streamReader = new InputStreamReader(inputStream)) {
+      return CharStreams.readLines(streamReader).stream();
+    }
+  }
+
+  private Stream<String> dumpBinaryFile(String name, InputStream inputStream) throws IOException {
+    try (HashingInputStream is = new HashingInputStream(Hashing.murmur3_128(), inputStream)) {
+      ByteStreams.exhaust(is);
+      return Stream.of(String.format("Murmur3-128 of %s: %s", name, is.hash().toString()));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarFileObject.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarFileObject.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarFileObject.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.util.zip.JarBuilder;
+import java.net.URI;
+import javax.annotation.Nullable;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.NestingKind;
+import javax.tools.FileObject;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+
+/**
+ * A {@link JavaFileObject} implementation that allows using jar URIs unlike {@link
+ * SimpleJavaFileObject} that assumes the uri used is a file system uri. This implementation can be
+ * used when the CLASS_OUTPUT is represented by a straight to jar write. The only content that it
+ * stores is the full uri, the relative path within the jar and the kind of the {@link FileObject}.
+ */
+public abstract class JarFileObject implements JavaFileObject {
+
+  protected final URI uri;
+  protected final String pathInJar;
+  protected final Kind kind;
+
+  public JarFileObject(URI uri, String pathInJar, Kind kind) {
+    this.uri = uri;
+    this.pathInJar = pathInJar;
+    this.kind = kind;
+  }
+
+  @Override
+  public URI toUri() {
+    return uri;
+  }
+
+  @Override
+  public String getName() {
+    return pathInJar;
+  }
+
+  @Override
+  public long getLastModified() {
+    return 0L;
+  }
+
+  @Override
+  public boolean delete() {
+    return false;
+  }
+
+  @Override
+  public Kind getKind() {
+    return this.kind;
+  }
+
+  @Override
+  public boolean isNameCompatible(String simpleName, Kind kind) {
+    String baseName = simpleName + kind.extension;
+    return kind.equals(getKind())
+        && (baseName.equals(pathInJar) || pathInJar.endsWith("/" + baseName));
+  }
+
+  @Override
+  @Nullable
+  public NestingKind getNestingKind() {
+    return null;
+  }
+
+  @Override
+  @Nullable
+  public Modifier getAccessLevel() {
+    return null;
+  }
+
+  @Override
+  public String toString() {
+    return this.getClass().getName() + "[" + toUri() + "]";
+  }
+
+  public abstract void writeToJar(JarBuilder jarBuilder);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarParameters.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarParameters.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JarParameters.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java
+
+import com.facebook.buck.core.filesystems.RelPath
+import com.google.common.collect.ImmutableSortedSet
+import java.util.Optional
+import java.util.function.Predicate
+import java.util.logging.Level
+
+data class JarParameters(
+    val hashEntries: Boolean,
+    val mergeManifests: Boolean,
+    val jarPath: RelPath,
+    val removeEntryPredicate: Predicate<Any>,
+    val entriesToJar: ImmutableSortedSet<RelPath>,
+    val overrideEntriesToJar: ImmutableSortedSet<RelPath>,
+    val mainClass: Optional<String>,
+    val manifestFile: Optional<RelPath>,
+    val duplicatesLogLevel: Level,
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaExtraParams.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaExtraParams.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaExtraParams.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java
+
+import com.facebook.buck.jvm.java.CompileToJarStepFactory.ExtraParams
+
+/** Extra params instance used to create Java related compile build steps */
+data class JavaExtraParams(
+    val resolvedJavacOptions: ResolvedJavacOptions,
+    val addAnnotationPath: Boolean,
+    /**
+     * Only safe where javac does not own the rule's jar, since a skipped invocation writes no
+     * output.
+     */
+    val skipIfNoCompilationUnits: Boolean = false,
+) : ExtraParams {
+  companion object {
+    @JvmStatic
+    fun of(resolvedJavacOptions: ResolvedJavacOptions): JavaExtraParams {
+      return JavaExtraParams(resolvedJavacOptions, true)
+    }
+
+    @JvmStatic
+    fun of(
+        resolvedJavacOptions: ResolvedJavacOptions,
+        addAnnotationPath: Boolean,
+    ): JavaExtraParams {
+      return JavaExtraParams(resolvedJavacOptions, addAnnotationPath)
+    }
+
+    @JvmStatic
+    fun of(
+        resolvedJavacOptions: ResolvedJavacOptions,
+        addAnnotationPath: Boolean,
+        skipIfNoCompilationUnits: Boolean,
+    ): JavaExtraParams {
+      return JavaExtraParams(resolvedJavacOptions, addAnnotationPath, skipIfNoCompilationUnits)
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaInMemoryFileManager.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaInMemoryFileManager.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaInMemoryFileManager.java
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import static javax.tools.StandardLocation.CLASS_OUTPUT;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.util.zip.JarBuilder;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Predicate;
+import javax.tools.FileObject;
+import javax.tools.ForwardingJavaFileManager;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardJavaFileManager;
+
+/**
+ * A {@link StandardJavaFileManager} that creates and writes the content of files directly into a
+ * Jar output stream instead of writing the files to disk.
+ */
+public class JavaInMemoryFileManager extends ForwardingJavaFileManager<StandardJavaFileManager>
+    implements StandardJavaFileManager {
+  private static final Logger LOG = Logger.get(JavaInMemoryFileManager.class);
+
+  private final Path jarPath;
+  private final String jarPathUri;
+  private final StandardJavaFileManager delegate;
+  private final Set<String> directoryPaths;
+  private final Map<String, JarFileObject> fileForOutputPaths;
+  private final Predicate<? super String> removeClassesPredicate;
+
+  private static final int FILENAME_LENGTH_LIMIT = 255;
+
+  public JavaInMemoryFileManager(
+      StandardJavaFileManager standardManager,
+      Path jarPath,
+      Predicate<? super String> removeClassesPredicate) {
+    super(standardManager);
+    this.delegate = standardManager;
+    this.jarPath = jarPath;
+    this.jarPathUri = "jar:" + jarPath.toUri() + "!/";
+    this.directoryPaths = new HashSet<>();
+    this.fileForOutputPaths = new HashMap<>();
+    this.removeClassesPredicate = removeClassesPredicate;
+  }
+
+  private static String getPath(String className) {
+    return className.replace('.', '/');
+  }
+
+  private static String getPath(String className, JavaFileObject.Kind kind) {
+    return className.replace('.', '/') + kind.extension;
+  }
+
+  private static String getPath(String packageName, String relativeName) {
+    return !packageName.isEmpty()
+        ? packageName.replace('.', '/') + '/' + relativeName
+        : relativeName;
+  }
+
+  @Override
+  public JavaFileObject getJavaFileForOutput(
+      Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
+      throws IOException {
+    // Use the normal FileObject that writes to the disk for source files.
+    if (shouldDelegate(location)) {
+      return delegate.getJavaFileForOutput(location, className, kind, sibling);
+    }
+    String path = getPath(className, kind);
+    // Check that the filename does not exceed the filesystem limt
+    if (Paths.get(path).getFileName().toString().length() > FILENAME_LENGTH_LIMIT) {
+      throw new IOException(String.format("%s (File name too long)", path));
+    }
+
+    boolean includeInOutput = true;
+    if (removeClassesPredicate.test(className)) {
+      LOG.info(
+          "%s was excluded from the Jar because it matched a remove_classes pattern.", className);
+      // If the class is to be removed from the Jar then don't add it to the fileForOutputPaths.
+      includeInOutput = false;
+    }
+
+    return getJavaMemoryFileObject(kind, path, includeInOutput);
+  }
+
+  @Override
+  public FileObject getFileForOutput(
+      Location location, String packageName, String relativeName, FileObject sibling)
+      throws IOException {
+    if (shouldDelegate(location)) {
+      return delegate.getFileForOutput(location, packageName, relativeName, sibling);
+    }
+
+    String path = getPath(packageName, relativeName);
+    return getJavaMemoryFileObject(JavaFileObject.Kind.OTHER, path, true);
+  }
+
+  @Override
+  public boolean isSameFile(FileObject a, FileObject b) {
+    boolean aInMemoryJavaFileInstance = a instanceof JavaInMemoryFileObject;
+    boolean bInMemoryJavaFileInstance = b instanceof JavaInMemoryFileObject;
+    if (aInMemoryJavaFileInstance || bInMemoryJavaFileInstance) {
+      return aInMemoryJavaFileInstance
+          && bInMemoryJavaFileInstance
+          && a.getName().equals(b.getName());
+    }
+    return super.isSameFile(a, b);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(
+      Iterable<? extends File> files) {
+    return delegate.getJavaFileObjectsFromFiles(files);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) {
+    return delegate.getJavaFileObjects(files);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
+    return delegate.getJavaFileObjectsFromStrings(names);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) {
+    return delegate.getJavaFileObjects(names);
+  }
+
+  @Override
+  public void setLocation(Location location, Iterable<? extends File> path) throws IOException {
+    delegate.setLocation(location, path);
+  }
+
+  @Override
+  public Iterable<? extends File> getLocation(Location location) {
+    return delegate.getLocation(location);
+  }
+
+  @Override
+  public Iterable<JavaFileObject> list(
+      Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse)
+      throws IOException {
+    if (shouldDelegate(location)) {
+      return delegate.list(location, packageName, kinds, recurse);
+    }
+
+    ArrayList<JavaFileObject> results = new ArrayList<>();
+    for (JavaFileObject fromSuper : delegate.list(location, packageName, kinds, recurse)) {
+      results.add(fromSuper);
+    }
+
+    String packageDirPath = getPath(packageName) + '/';
+    for (String filepath : fileForOutputPaths.keySet()) {
+      if (recurse && filepath.startsWith(packageDirPath)) {
+        results.add(fileForOutputPaths.get(filepath));
+      } else if (!recurse
+          && filepath.startsWith(packageDirPath)
+          && filepath.substring(packageDirPath.length()).indexOf('/') < 0) {
+        results.add(fileForOutputPaths.get(filepath));
+      }
+    }
+
+    return results;
+  }
+
+  public ImmutableSet<String> writeToJar(JarBuilder jarBuilder) {
+    for (JarFileObject fileObject : fileForOutputPaths.values()) {
+      fileObject.writeToJar(jarBuilder);
+    }
+
+    return ImmutableSet.copyOf(Sets.union(directoryPaths, fileForOutputPaths.keySet()));
+  }
+
+  private boolean shouldDelegate(Location location) {
+    return location != CLASS_OUTPUT;
+  }
+
+  private JavaFileObject getJavaMemoryFileObject(
+      JavaFileObject.Kind kind, String path, boolean includeInOutput) {
+    if (!includeInOutput) {
+      return new JavaInMemoryFileObject(getUriPath(path), path, kind);
+    }
+    return fileForOutputPaths.computeIfAbsent(
+        path, p -> new JavaInMemoryFileObject(getUriPath(p), p, kind));
+  }
+
+  private String encodeURL(String path) {
+    return URLEncoder.encode(path, StandardCharsets.UTF_8).replace("%2F", "/");
+  }
+
+  private URI getUriPath(String relativePath) {
+    return URI.create(jarPathUri + encodeURL(relativePath));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaInMemoryFileObject.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaInMemoryFileObject.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaInMemoryFileObject.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.util.zip.CustomZipEntry;
+import com.facebook.buck.util.zip.JarBuilder;
+import com.facebook.buck.util.zip.JarEntrySupplier;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.Writer;
+import java.net.URI;
+import javax.tools.SimpleJavaFileObject;
+
+/**
+ * A {@link SimpleJavaFileObject} implementation that forwards the content of the file to a Jar
+ * output stream instead of writing it to disk. Since the Jar can be shared between multiple
+ * threads, a semaphore is used to ensure exclusive access to the output stream.
+ */
+public class JavaInMemoryFileObject extends JarFileObject {
+  // Bump the initial buffer size because usual file sizes using this are way more than 4K and the
+  // default buffer size of a ByteArrayOutputStream is just 32
+  private static final int BUFFER_SIZE = 4096;
+  private static final String ALREADY_OPENED = "Output stream or writer has already been opened.";
+
+  private boolean isOpened = false;
+  private boolean isWritten = false;
+  private final ByteArrayOutputStream bos = new ByteArrayOutputStream(BUFFER_SIZE);
+
+  public JavaInMemoryFileObject(URI uri, String pathInJar, Kind kind) {
+    super(uri, pathInJar, kind);
+  }
+
+  @Override
+  public InputStream openInputStream() throws IOException {
+    if (!isWritten) {
+      throw new FileNotFoundException(uri.toString());
+    }
+    return new ByteArrayInputStream(bos.toByteArray());
+  }
+
+  @Override
+  public synchronized OutputStream openOutputStream() throws IOException {
+    if (isOpened) {
+      throw new IOException(ALREADY_OPENED);
+    }
+    isOpened = true;
+    return new OutputStream() {
+      @Override
+      public void write(int b) {
+        bos.write(b);
+      }
+
+      @Override
+      public void close() throws IOException {
+        bos.close();
+        isWritten = true;
+      }
+    };
+  }
+
+  @Override
+  public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
+    return new InputStreamReader(openInputStream());
+  }
+
+  @Override
+  public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
+    if (!isWritten) {
+      throw new FileNotFoundException(uri.toString());
+    }
+    return bos.toString();
+  }
+
+  @Override
+  public Writer openWriter() throws IOException {
+    return new OutputStreamWriter(this.openOutputStream());
+  }
+
+  @Override
+  public void writeToJar(JarBuilder jarBuilder) {
+    if (!isWritten) {
+      // Nothing was written to this file, so it doesn't really exist.
+      return;
+    }
+    jarBuilder.addEntry(new JarEntrySupplier(new CustomZipEntry(getName()), this::openInputStream));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaNoOpFileObject.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaNoOpFileObject.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaNoOpFileObject.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.util.zip.JarBuilder;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.Writer;
+import java.net.URI;
+
+/**
+ * An {@link JarFileObject} implementation that represents a {@link javax.tools.FileObject} that has
+ * no operations and does not write the contents to any form of output.
+ */
+public class JavaNoOpFileObject extends JarFileObject {
+
+  public JavaNoOpFileObject(URI uri, String pathInJar, Kind kind) {
+    super(uri, pathInJar, kind);
+  }
+
+  @Override
+  public InputStream openInputStream() {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public OutputStream openOutputStream() {
+    return new OutputStream() {
+      @Override
+      public void write(int b) {}
+
+      @Override
+      public void close() {}
+    };
+  }
+
+  @Override
+  public Reader openReader(boolean ignoreEncodingErrors) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public Writer openWriter() {
+    return new OutputStreamWriter(openOutputStream());
+  }
+
+  @Override
+  public void writeToJar(JarBuilder jarBuilder) {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaPaths.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaPaths.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaPaths.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.util.unarchive.Unzip;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Enumeration;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/** Utilities for handling paths to java source files. */
+public class JavaPaths {
+
+  public static final String SRC_ZIP = ".src.zip";
+  public static final String SRC_JAR = "-sources.jar";
+
+  /**
+   * Processes a list of java source files, extracting and SRC_ZIP or SRC_JAR to the working
+   * directory and returns a list of all the resulting .java files.
+   */
+  static ImmutableList<RelPath> extractArchivesAndGetPaths(
+      AbsPath ruleCellPathRoot, ImmutableSet<RelPath> javaSourceFilePaths, Path workingDirectory)
+      throws IOException {
+
+    // Add sources file or sources list to command
+    ImmutableList.Builder<RelPath> sources = ImmutableList.builder();
+    for (RelPath path : javaSourceFilePaths) {
+      String pathString = path.toString();
+      if (pathString.endsWith(".java")) {
+        sources.add(path);
+      } else if (pathString.endsWith(SRC_ZIP) || pathString.endsWith(SRC_JAR)) {
+        // For a Zip of .java files, create a JavaFileObject for each .java entry.
+        ImmutableList<Path> zipPaths =
+            Unzip.extractArchive(
+                ruleCellPathRoot,
+                ruleCellPathRoot.resolve(path).getPath(),
+                ruleCellPathRoot.resolve(workingDirectory).getPath());
+        sources.addAll(
+            zipPaths.stream()
+                .filter(input -> input.toString().endsWith(".java"))
+                .map(ruleCellPathRoot::relativize)
+                .iterator());
+      }
+    }
+    return sources.build();
+  }
+
+  /**
+   * Whether the given source paths expand to at least one {@code .java} compilation unit. A
+   * SRC_ZIP/SRC_JAR staged by an annotation processor may hold no Java sources at all, so the
+   * archives are inspected rather than counted.
+   *
+   * <p>A path that is neither a Java source nor an archive counts as a compilation unit, leaving it
+   * to javac to reject.
+   */
+  static boolean hasJavaCompilationUnits(Iterable<Path> javaSourceFilePaths) throws IOException {
+    for (Path path : javaSourceFilePaths) {
+      String pathString = path.toString();
+      if (!pathString.endsWith(SRC_ZIP) && !pathString.endsWith(SRC_JAR)) {
+        return true;
+      }
+      try (ZipFile zipFile = new ZipFile(path.toFile())) {
+        Enumeration<? extends ZipEntry> entries = zipFile.entries();
+        while (entries.hasMoreElements()) {
+          if (entries.nextElement().getName().endsWith(".java")) {
+            return true;
+          }
+        }
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Traverses a list of java inputs return the list of all found files (for SRC_ZIP/SRC_JAR, it
+   * returns the paths from within the archive).
+   */
+  static ImmutableList<Path> getExpandedSourcePaths(Iterable<Path> javaSourceFilePaths)
+      throws IOException {
+    // Add sources file or sources list to command
+    ImmutableList.Builder<Path> sources = ImmutableList.builder();
+    for (Path path : javaSourceFilePaths) {
+      String pathString = path.toString();
+      if (pathString.endsWith(SRC_ZIP) || pathString.endsWith(SRC_JAR)) {
+        try (ZipFile zipFile = new ZipFile(path.toFile())) {
+          Enumeration<? extends ZipEntry> entries = zipFile.entries();
+          while (entries.hasMoreElements()) {
+            sources.add(Paths.get(entries.nextElement().getName()));
+          }
+        }
+      } else {
+        sources.add(path);
+      }
+    }
+    return sources.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavaStepsBuilder.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.jvm.cd.AbiStepsBuilder;
+import com.facebook.buck.jvm.cd.BuildCommandStepsBuilder;
+import com.facebook.buck.jvm.cd.DefaultCompileStepsBuilderFactory;
+import com.facebook.buck.jvm.cd.LibraryStepsBuilder;
+import com.facebook.buck.jvm.cd.command.BaseJarCommand;
+import com.facebook.buck.jvm.cd.command.BuildMode;
+import com.facebook.buck.jvm.cd.command.java.BuildJavaCommand;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.google.common.collect.ImmutableList;
+
+/** Java steps builder */
+public class JavaStepsBuilder implements BuildCommandStepsBuilder {
+
+  private final ImmutableList<IsolatedStep> steps;
+  private final AbsPath ruleCellRoot;
+
+  public JavaStepsBuilder(BuildJavaCommand buildJavaCommand) {
+    this.ruleCellRoot = buildJavaCommand.getBaseJarCommand().getBuildCellRootPath();
+    this.steps = buildSteps(buildJavaCommand);
+  }
+
+  /** Returns {@link IsolatedStep}s from the passed protobuf message */
+  @Override
+  public ImmutableList<IsolatedStep> getSteps() {
+    return steps;
+  }
+
+  /** Returns rule cell root. */
+  @Override
+  public AbsPath getRuleCellRoot() {
+    return ruleCellRoot;
+  }
+
+  private ImmutableList<IsolatedStep> buildSteps(BuildJavaCommand buildJavaCommand) {
+    DefaultCompileStepsBuilderFactory<JavaExtraParams> factory = createDefaultStepsFactory();
+
+    if (buildJavaCommand.getBuildMode() == BuildMode.LIBRARY) {
+      LibraryStepsBuilder libraryJarBuilder = factory.getLibraryBuilder();
+      handleLibraryJarCommand(libraryJarBuilder, buildJavaCommand.getBaseJarCommand());
+      return libraryJarBuilder.buildIsolatedSteps();
+    } else {
+      AbiStepsBuilder abiJarBuilder = factory.getAbiBuilder();
+      handleAbiJarCommand(abiJarBuilder, buildJavaCommand.getBaseJarCommand());
+      return abiJarBuilder.buildIsolatedSteps();
+    }
+  }
+
+  private void handleLibraryJarCommand(
+      LibraryStepsBuilder libraryJarBuilder, BaseJarCommand baseJarCommand) {
+
+    libraryJarBuilder.addBuildStepsForLibrary(
+        baseJarCommand.getAbiCompatibilityMode(),
+        baseJarCommand.getAbiGenerationMode(),
+        baseJarCommand.isRequiredForSourceOnlyAbi(),
+        baseJarCommand.getTrackClassUsage(),
+        baseJarCommand.getBuckOut(),
+        baseJarCommand.getBuildTargetValue(),
+        baseJarCommand.getCompilerOutputPathsValue(),
+        baseJarCommand.getCompileTimeClasspathPaths(),
+        baseJarCommand.getCompileTimeClasspathSnapshotPathsMap(),
+        baseJarCommand.getJavaSrcs(),
+        baseJarCommand.getResourcesMap(),
+        baseJarCommand.getJarParameters(),
+        baseJarCommand.getBuildCellRootPath(),
+        baseJarCommand.getResolvedJavac(),
+        null,
+        JavaExtraParams.of(baseJarCommand.getResolvedJavacOptions()));
+
+    maybeAddMakeMissingOutputStep(baseJarCommand, libraryJarBuilder);
+  }
+
+  private void handleAbiJarCommand(AbiStepsBuilder abiJarBuilder, BaseJarCommand command) {
+
+    abiJarBuilder.addBuildStepsForAbi(
+        command.getAbiCompatibilityMode(),
+        command.getAbiGenerationMode(),
+        command.isRequiredForSourceOnlyAbi(),
+        command.getTrackClassUsage(),
+        command.getBuckOut(),
+        command.getBuildTargetValue(),
+        command.getCompilerOutputPathsValue(),
+        command.getCompileTimeClasspathPaths(),
+        command.getJavaSrcs(),
+        command.getResourcesMap(),
+        command.getJarParameters(),
+        command.getJarParameters(),
+        command.getBuildCellRootPath(),
+        command.getResolvedJavac(),
+        JavaExtraParams.of(command.getResolvedJavacOptions()));
+  }
+
+  private static DefaultCompileStepsBuilderFactory<JavaExtraParams> createDefaultStepsFactory() {
+    DaemonJavacToJarStepFactory daemonJavacToJarStepFactory = getDaemonJavacToJarStepFactory();
+    return new DefaultCompileStepsBuilderFactory<>(daemonJavacToJarStepFactory);
+  }
+
+  /** Returns {@link DaemonJavacToJarStepFactory} */
+  public static DaemonJavacToJarStepFactory getDaemonJavacToJarStepFactory() {
+    return new DaemonJavacToJarStepFactory();
+  }
+
+  private void maybeAddMakeMissingOutputStep(
+      BaseJarCommand command, LibraryStepsBuilder javaCompileStepsBuilder) {
+
+    javaCompileStepsBuilder.addMakeMissingOutputsStep(command.getAnnotationPath());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacExecutionContext.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacExecutionContext.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacExecutionContext.kt
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java
+
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.util.ClassLoaderCache
+import com.facebook.buck.util.Verbosity
+import java.io.PrintStream
+
+data class JavacExecutionContext(
+    val stdErr: PrintStream,
+    val classLoaderCache: ClassLoaderCache,
+    val verbosity: Verbosity,
+    val ruleCellRoot: AbsPath,
+    val configuredBuckOut: RelPath,
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacLanguageLevelOptions.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacLanguageLevelOptions.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacLanguageLevelOptions.kt
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java
+
+import com.facebook.buck.jvm.java.version.utils.JavaVersionUtils
+
+data class JavacLanguageLevelOptions(val sourceLevel: String, val targetLevel: String) {
+  val sourceLevelValue: Int
+    get() = JavaVersionUtils.getMajorVersionFromString(sourceLevel)
+
+  val targetLevelValue: Int
+    get() = JavaVersionUtils.getMajorVersionFromString(targetLevel)
+
+  companion object {
+    // Default combined source and target level.
+    const val TARGETED_JAVA_VERSION: String = "8"
+
+    @JvmField
+    val DEFAULT: JavacLanguageLevelOptions =
+        JavacLanguageLevelOptions(TARGETED_JAVA_VERSION, TARGETED_JAVA_VERSION)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacPipelineState.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacPipelineState.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacPipelineState.java
@@ -0,0 +1,265 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.util.CapturingPrintStream;
+import com.facebook.buck.util.Verbosity;
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+
+public class JavacPipelineState implements AutoCloseable {
+
+  private static final Logger LOG = Logger.get(JavacPipelineState.class);
+
+  private final CompilerParameters compilerParameters;
+  private final ResolvedJavacOptions resolvedJavacOptions;
+  private final BuildTargetValue invokingRule;
+  private final ResolvedJavac resolvedJavac;
+  @Nullable private final JarParameters abiJarParameters;
+  @Nullable private final JarParameters libraryJarParameters;
+
+  private final List<AutoCloseable> closeables = new ArrayList<>();
+
+  @Nullable private CapturingPrintStream stdout;
+  @Nullable private CapturingPrintStream stderr;
+  @Nullable private ResolvedJavac.Invocation invocation;
+
+  public JavacPipelineState(
+      ResolvedJavac resolvedJavac,
+      ResolvedJavacOptions resolvedJavacOptions,
+      BuildTargetValue invokingRule,
+      CompilerParameters compilerParameters,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters) {
+    this.resolvedJavac = resolvedJavac;
+    this.invokingRule = invokingRule;
+    this.compilerParameters = compilerParameters;
+    this.abiJarParameters = abiJarParameters;
+    this.libraryJarParameters = libraryJarParameters;
+    this.resolvedJavacOptions = resolvedJavacOptions;
+  }
+
+  public boolean isRunning() {
+    return invocation != null;
+  }
+
+  /** Get the invocation instance. */
+  public ResolvedJavac.Invocation getJavacInvocation(
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      IsolatedExecutionContext context,
+      RelPath configuredBuckOut)
+      throws IOException {
+    if (invocation == null) {
+      stdout = new CapturingPrintStream();
+      closeables.add(stdout);
+      stderr = new CapturingPrintStream();
+      closeables.add(stderr);
+      Verbosity verbosity =
+          context.getVerbosity().isSilent()
+              ? Verbosity.STANDARD_INFORMATION
+              : context.getVerbosity();
+      IsolatedExecutionContext firstOrderContext =
+          context.createSubContext(stdout, stderr, Optional.of(verbosity));
+      closeables.add(firstOrderContext);
+
+      JavacExecutionContext javacExecutionContext =
+          new JavacExecutionContext(
+              stderr,
+              firstOrderContext.getClassLoaderCache(),
+              verbosity,
+              context.getRuleCellRoot(),
+              configuredBuckOut);
+
+      CompilerOutputPaths outputPaths = compilerParameters.getOutputPaths();
+      invocation =
+          getResolvedJavac()
+              .newBuildInvocation(
+                  javacExecutionContext,
+                  invokingRule,
+                  compilerOutputPathsValue,
+                  getOptions(context, compilerParameters.getClasspathEntries()),
+                  resolvedJavacOptions.getJavaAnnotationProcessorParams(),
+                  resolvedJavacOptions.getStandardJavacPluginParams(),
+                  compilerParameters.getSourceFilePaths(),
+                  outputPaths.getPathToSourcesList(),
+                  outputPaths.getWorkingDirectory(),
+                  compilerParameters.getShouldTrackClassUsage(),
+                  abiJarParameters,
+                  libraryJarParameters,
+                  compilerParameters.getAbiGenerationMode(),
+                  compilerParameters.getAbiCompatibilityMode(),
+                  compilerParameters.getSourceOnlyAbiRuleInfoFactory());
+
+      closeables.add(invocation);
+    }
+
+    return invocation;
+  }
+
+  public String getStdoutContents() {
+    return Objects.requireNonNull(stdout).getContentsAsString(StandardCharsets.UTF_8);
+  }
+
+  public String getStderrContents() {
+    return Objects.requireNonNull(stderr).getContentsAsString(StandardCharsets.UTF_8);
+  }
+
+  @Override
+  public void close() {
+    for (AutoCloseable closeable : Lists.reverse(closeables)) {
+      try {
+        if (closeable != null) {
+          closeable.close();
+        }
+      } catch (Exception e) {
+        LOG.warn(e, "Unable to close %s; we may be leaking memory.", closeable);
+      }
+    }
+
+    closeables.clear();
+    stdout = null;
+    stderr = null;
+    invocation = null;
+  }
+
+  ResolvedJavac getResolvedJavac() {
+    return resolvedJavac;
+  }
+
+  /**
+   * Returns a list of command-line options to pass to javac. These options reflect the
+   * configuration of this javac command.
+   *
+   * @return list of String command-line options.
+   */
+  ImmutableList<String> getOptions(
+      IsolatedExecutionContext context, ImmutableList<RelPath> buildClasspathEntries) {
+    CompilerOutputPaths outputPaths = compilerParameters.getOutputPaths();
+    return getOptions(
+        outputPaths.getClassesDir(),
+        outputPaths.getAnnotationPath().getPath(),
+        context,
+        buildClasspathEntries);
+  }
+
+  private ImmutableList<String> getOptions(
+      RelPath outputDirectory,
+      Path generatedCodeDirectory,
+      IsolatedExecutionContext context,
+      ImmutableList<RelPath> buildClasspathEntries) {
+    ImmutableList.Builder<String> builder = ImmutableList.builder();
+
+    AbsPath ruleCellRoot = context.getRuleCellRoot();
+    ResolvedJavacOptions.appendOptionsTo(
+        new OptionsConsumer() {
+          @Override
+          public void addOptionValue(String option, String value) {
+            if (option.equals("bootclasspath")) {
+              builder
+                  .add("-bootclasspath")
+                  .add(
+                      Arrays.stream(value.split(File.pathSeparator))
+                          .map(path -> ruleCellRoot.resolve(path).toString())
+                          .collect(Collectors.joining(File.pathSeparator)));
+            } else {
+              builder.add("-" + option).add(value);
+            }
+          }
+
+          @Override
+          public void addFlag(String flagName) {
+            builder.add("-" + flagName);
+          }
+
+          @Override
+          public void addExtras(Collection<String> extras) {
+            builder.addAll(extras);
+          }
+        },
+        resolvedJavacOptions,
+        ruleCellRoot);
+    Optional<String> bootclasspath =
+        ResolvedJavacOptions.Companion.getBootclasspathString(
+            resolvedJavacOptions.getBootclasspathList());
+
+    // verbose flag, if appropriate.
+    if (context.getVerbosity().shouldUseVerbosityFlagIfAvailable()) {
+      builder.add("-verbose");
+    }
+
+    // Specify the output directory.
+    builder.add("-d").add(ruleCellRoot.resolve(outputDirectory).toString());
+
+    if (resolvedJavacOptions.isJavaAnnotationProcessorParamsPresent()) {
+      builder.add("-s").add(ruleCellRoot.resolve(generatedCodeDirectory).toString());
+    }
+
+    List<String> classpathEntries = new ArrayList<>();
+    int targetRelease = resolvedJavacOptions.getLanguageLevelOptions().getTargetLevelValue();
+    if (targetRelease > 8) {
+      String systemImage = resolvedJavacOptions.getSystemImage();
+      if (systemImage != null) {
+        classpathEntries.add(bootclasspath.get());
+
+        builder.add("--system");
+        builder.add(systemImage);
+      }
+    }
+    // else, bootclasspath is already handled by the OptionsConsumer above
+
+    classpathEntries.addAll(
+        buildClasspathEntries.stream()
+            .map(ruleCellRoot::resolve)
+            .map(AbsPath::normalize)
+            .map(AbsPath::toString)
+            .toList());
+
+    // Build up and set the classpath.
+    if (!classpathEntries.isEmpty()) {
+      String classpath = Joiner.on(File.pathSeparator).join(classpathEntries);
+      builder.add("-classpath", classpath);
+    } else {
+      builder.add("-classpath", "''");
+    }
+
+    return builder.build();
+  }
+
+  public CompilerParameters getCompilerParameters() {
+    return compilerParameters;
+  }
+
+  Optional<JarParameters> getLibraryJarParameters() {
+    return Optional.ofNullable(libraryJarParameters);
+  }
+
+  Optional<JarParameters> getAbiJarParameters() {
+    return Optional.ofNullable(abiJarParameters);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacPluginParams.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacPluginParams.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacPluginParams.kt
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java
+
+import com.facebook.buck.core.filesystems.AbsPath
+import com.google.common.collect.ImmutableList
+import com.google.common.collect.ImmutableSortedSet
+import java.net.URL
+
+/**
+ * Information for javac plugins (includes annotation processors).
+ *
+ * Javac Plugins involves a set of plugin properties, their classpath(s), and a few other
+ * command-line options for javac. We want to be able to specify all this various information in a
+ * BUCK configuration file and use it when we generate the javac command. This facilitates threading
+ * the information through buck in a more descriptive package rather than passing all the components
+ * separately.
+ */
+data class JavacPluginParams(
+    val pluginProperties: ImmutableList<ResolvedJavacPluginProperties>,
+    val parameters: ImmutableSortedSet<String>,
+) {
+  val isEmpty: Boolean
+    get() = pluginProperties.isEmpty() && parameters.isEmpty()
+
+  /** Resolves classpath to a list of URL */
+  fun toUrlClasspath(relPathRoot: AbsPath): ImmutableList<URL> {
+    val builder = ImmutableList.builder<URL>()
+    for (plugin in pluginProperties) {
+      builder.addAll(plugin.toUrlClasspath(relPathRoot))
+    }
+    return builder.build()
+  }
+
+  companion object {
+    @JvmField
+    val EMPTY: JavacPluginParams = JavacPluginParams(ImmutableList.of(), ImmutableSortedSet.of())
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacStep.java
@@ -0,0 +1,219 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.step.StepExecutionResult;
+import com.facebook.buck.step.StepExecutionResults;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
+import com.google.common.base.MoreObjects;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSortedSet;
+import java.io.IOException;
+import java.util.Optional;
+import javax.annotation.Nullable;
+
+/** Command used to compile java libraries with a variety of ways to handle dependencies. */
+public class JavacStep implements IsolatedStep {
+
+  private final JavacPipelineState state;
+  private final BuildTargetValue invokingRule;
+  private final RelPath configuredBuckOut;
+  private final boolean ownsPipelineObject;
+  private final CompilerOutputPathsValue compilerOutputPathsValue;
+  private final boolean skipIfNoCompilationUnits;
+
+  private final boolean mixedModule;
+
+  public JavacStep(
+      ResolvedJavac resolvedJavac,
+      ResolvedJavacOptions javacOptions,
+      BuildTargetValue invokingRule,
+      RelPath configuredBuckOut,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      CompilerParameters compilerParameters,
+      boolean skipIfNoCompilationUnits,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters,
+      boolean mixedCompilation) {
+    this(
+        new JavacPipelineState(
+            resolvedJavac,
+            javacOptions,
+            invokingRule,
+            compilerParameters,
+            abiJarParameters,
+            libraryJarParameters),
+        invokingRule,
+        configuredBuckOut,
+        true,
+        compilerOutputPathsValue,
+        skipIfNoCompilationUnits,
+        mixedCompilation);
+  }
+
+  public JavacStep(
+      JavacPipelineState state,
+      BuildTargetValue invokingRule,
+      RelPath configuredBuckOut,
+      CompilerOutputPathsValue compilerOutputPathsValue) {
+    this(state, invokingRule, configuredBuckOut, false, compilerOutputPathsValue, false, false);
+  }
+
+  private JavacStep(
+      JavacPipelineState state,
+      BuildTargetValue invokingRule,
+      RelPath configuredBuckOut,
+      boolean ownsPipelineObject,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      boolean skipIfNoCompilationUnits,
+      boolean mixedModule) {
+    this.state = state;
+    this.invokingRule = invokingRule;
+    this.configuredBuckOut = configuredBuckOut;
+    this.ownsPipelineObject = ownsPipelineObject;
+    this.compilerOutputPathsValue = compilerOutputPathsValue;
+    this.skipIfNoCompilationUnits = skipIfNoCompilationUnits;
+    this.mixedModule = mixedModule;
+  }
+
+  @Override
+  public final StepExecutionResult executeIsolatedStep(IsolatedExecutionContext context)
+      throws IOException, InterruptedException {
+
+    if (skipIfNoCompilationUnits && !hasCompilationUnits(context.getRuleCellRoot())) {
+      return StepExecutionResults.SUCCESS;
+    }
+
+    int exitCode;
+    Optional<String> stderr = Optional.empty();
+    try {
+      ResolvedJavac.Invocation invocation =
+          state.getJavacInvocation(compilerOutputPathsValue, context, configuredBuckOut);
+
+      if (invokingRule.isSourceAbi()) {
+        exitCode = invocation.buildSourceAbiJar();
+      } else if (invokingRule.isSourceOnlyAbi()) {
+        exitCode = invocation.buildSourceOnlyAbiJar(mixedModule);
+      } else {
+        exitCode = invocation.buildClasses();
+      }
+
+      if (exitCode != StepExecutionResults.SUCCESS_EXIT_CODE) {
+        stderr = Optional.of(state.getStderrContents());
+      }
+
+    } finally {
+      if (ownsPipelineObject) {
+        state.close();
+      }
+    }
+
+    return new StepExecutionResult(exitCode, stderr);
+  }
+
+  /**
+   * KSP and KAPT stage a {@code .src.zip} into the Java source list before their processors have
+   * run, so whether javac has anything to compile is not known until this step executes.
+   */
+  private boolean hasCompilationUnits(AbsPath ruleCellRoot) throws IOException {
+    return JavaPaths.hasJavaCompilationUnits(
+        state.getCompilerParameters().getSourceFilePaths().stream()
+            .map(path -> ruleCellRoot.resolve(path).getPath())
+            .collect(ImmutableList.toImmutableList()));
+  }
+
+  @VisibleForTesting
+  ResolvedJavac getResolvedJavac() {
+    return state.getResolvedJavac();
+  }
+
+  @Override
+  public String getIsolatedStepDescription(IsolatedExecutionContext context) {
+    String description =
+        getResolvedJavac()
+            .getDescription(
+                getOptions(context, getClasspathEntries()),
+                state.getCompilerParameters().getOutputPaths().getPathToSourcesList());
+
+    if (invokingRule.isLibraryJar() && state.getLibraryJarParameters().isPresent()) {
+      JarParameters jarParameters = state.getLibraryJarParameters().get();
+      Optional<RelPath> manifestFile = jarParameters.getManifestFile();
+      ImmutableSortedSet<RelPath> entriesToJar = jarParameters.getEntriesToJar();
+      description =
+          description
+              + "; "
+              + String.format(
+                  "jar %s %s %s %s",
+                  manifestFile.map(ignore -> "cfm").orElse("cf"),
+                  jarParameters.getJarPath(),
+                  manifestFile.map(RelPath::toString).orElse(""),
+                  Joiner.on(' ').join(entriesToJar));
+    }
+
+    return description;
+  }
+
+  @Override
+  public String getShortName() {
+    String name;
+    if (invokingRule.isSourceAbi()) {
+      return "source_abi";
+    } else if (invokingRule.isSourceOnlyAbi()) {
+      return "source_only_abi";
+    } else if (state.getLibraryJarParameters().isPresent()) {
+      name = "javac";
+    } else {
+      name = getResolvedJavac().getShortName();
+    }
+
+    return name;
+  }
+
+  /**
+   * Returns a list of command-line options to pass to javac. These options reflect the
+   * configuration of this javac command.
+   *
+   * @param context the ExecutionContext with in which javac will run
+   * @return list of String command-line options.
+   */
+  @VisibleForTesting
+  ImmutableList<String> getOptions(
+      IsolatedExecutionContext context, ImmutableList<RelPath> buildClasspathEntries) {
+    return state.getOptions(context, buildClasspathEntries);
+  }
+
+  /**
+   * @return The classpath entries used to invoke javac.
+   */
+  @VisibleForTesting
+  ImmutableList<RelPath> getClasspathEntries() {
+    return state.getCompilerParameters().getClasspathEntries();
+  }
+
+  @VisibleForTesting
+  ImmutableSortedSet<RelPath> getSrcs() {
+    return state.getCompilerParameters().getSourceFilePaths();
+  }
+
+  @Override
+  public String toString() {
+    return MoreObjects.toStringHelper(this)
+        .add("invokingRule", invokingRule)
+        .add("ownsPipelineObject", ownsPipelineObject)
+        .toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacVersion.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacVersion.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JavacVersion.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.util.immutables.BuckStyleValue;
+
+@BuckStyleValue
+abstract class JavacVersion {
+
+  public abstract String getVersionString();
+
+  @Override
+  public String toString() {
+    return getVersionString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JdkProvidedInMemoryJavac.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JdkProvidedInMemoryJavac.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/JdkProvidedInMemoryJavac.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.jvm.java.javax.SynchronizedToolProvider;
+import com.google.common.base.MoreObjects;
+import javax.tools.JavaCompiler;
+
+public class JdkProvidedInMemoryJavac extends Jsr199Javac {
+
+  public static final JdkProvidedInMemoryJavac INSTANCE = new JdkProvidedInMemoryJavac();
+
+  private JdkProvidedInMemoryJavac() {}
+
+  /** Creates in memory javac */
+  public static ResolvedJsr199Javac createJsr199Javac() {
+    return new ResolvedJsr199Javac() {
+
+      @Override
+      protected JavaCompiler createCompiler(JavacExecutionContext context) {
+        JavaCompiler compiler = SynchronizedToolProvider.getSystemJavaCompiler();
+        if (compiler == null) {
+          throw new RuntimeException(
+              "No system compiler found. Did you install the JRE instead of the JDK?");
+        }
+        return compiler;
+      }
+    };
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) {
+      return true;
+    }
+    return o != null && getClass() == o.getClass();
+  }
+
+  @Override
+  public int hashCode() {
+    return super.hashCode();
+  }
+
+  @Override
+  public String toString() {
+    return MoreObjects.toStringHelper(this).toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/Jsr199Javac.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/Jsr199Javac.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/Jsr199Javac.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory;
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSortedSet;
+import javax.annotation.Nullable;
+import javax.tools.JavaCompiler;
+
+/** Command used to compile java libraries with a variety of ways to handle dependencies. */
+public abstract class Jsr199Javac {
+
+  /** Base class for a resolved javac in-process tool. */
+  public abstract static class ResolvedJsr199Javac implements ResolvedJavac {
+
+    protected abstract JavaCompiler createCompiler(JavacExecutionContext context);
+
+    @Override
+    public String getDescription(ImmutableList<String> options, RelPath pathToSrcsList) {
+      StringBuilder builder = new StringBuilder("javac ");
+      Joiner.on(" ").appendTo(builder, options);
+      builder.append(" ");
+      builder.append("@").append(pathToSrcsList);
+
+      return builder.toString();
+    }
+
+    @Override
+    public String getShortName() {
+      return "javac";
+    }
+
+    @Override
+    public ResolvedJavac.Invocation newBuildInvocation(
+        JavacExecutionContext context,
+        BuildTargetValue invokingRule,
+        CompilerOutputPathsValue compilerOutputPathsValue,
+        ImmutableList<String> options,
+        JavacPluginParams annotationProcessorParams,
+        JavacPluginParams pluginParams,
+        ImmutableSortedSet<RelPath> javaSourceFilePaths,
+        RelPath pathToSrcsList,
+        RelPath workingDirectory,
+        boolean trackClassUsage,
+        @Nullable JarParameters abiJarParameters,
+        @Nullable JarParameters libraryJarParameters,
+        AbiGenerationMode abiGenerationMode,
+        AbiGenerationMode abiCompatibilityMode,
+        @Nullable SourceOnlyAbiRuleInfoFactory ruleInfoFactory) {
+      return new Jsr199JavacInvocation(
+          () -> createCompiler(context),
+          context,
+          invokingRule,
+          compilerOutputPathsValue,
+          options,
+          annotationProcessorParams,
+          pluginParams,
+          javaSourceFilePaths,
+          pathToSrcsList,
+          trackClassUsage,
+          abiJarParameters,
+          libraryJarParameters,
+          abiGenerationMode,
+          abiCompatibilityMode,
+          ruleInfoFactory);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/Jsr199JavacInvocation.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/Jsr199JavacInvocation.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/Jsr199JavacInvocation.java
@@ -0,0 +1,716 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import static com.facebook.buck.jvm.java.abi.AbiGenerationModeUtils.checkForSourceOnlyAbiCompatibility;
+import static com.facebook.buck.jvm.java.abi.AbiGenerationModeUtils.getDiagnosticKindForSourceOnlyAbiCompatibility;
+import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.abi.SourceBasedAbiStubber;
+import com.facebook.buck.jvm.java.abi.SourceVersionUtils;
+import com.facebook.buck.jvm.java.abi.StubGenerator;
+import com.facebook.buck.jvm.java.abi.source.api.FrontendOnlyJavacTaskProxy;
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory;
+import com.facebook.buck.jvm.java.abi.source.api.StopCompilation;
+import com.facebook.buck.jvm.java.plugin.PluginLoader;
+import com.facebook.buck.jvm.java.plugin.api.BuckJavacTaskListener;
+import com.facebook.buck.jvm.java.plugin.api.BuckJavacTaskProxy;
+import com.facebook.buck.jvm.java.plugin.api.PluginClassLoader;
+import com.facebook.buck.jvm.java.plugin.api.PluginClassLoaderFactory;
+import com.facebook.buck.util.zip.JarBuilder;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.common.util.concurrent.SettableFuture;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.io.IOException;
+import java.io.Writer;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import javax.annotation.Nullable;
+import javax.lang.model.SourceVersion;
+import javax.tools.Diagnostic;
+import javax.tools.DiagnosticCollector;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardJavaFileManager;
+
+/** Jsr199Javac invocation object created during java compilation. */
+class Jsr199JavacInvocation implements ResolvedJavac.Invocation {
+
+  private static final Logger LOG = Logger.get(Jsr199JavacInvocation.class);
+
+  private static final ListeningExecutorService THREAD_POOL =
+      MoreExecutors.listeningDecorator(
+          Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("javac").build()));
+
+  private static final int SUCCESS_EXIT_CODE = 0;
+  private static final int ERROR_EXIT_CODE = 1;
+
+  static final String NO_JAVA_FILES_ERROR_MESSAGE =
+      "No Java files provided for library compilation";
+
+  private final Supplier<JavaCompiler> compilerConstructor;
+  private final JavacExecutionContext context;
+  private final BuildTargetValue invokingRule;
+  private final CompilerOutputPathsValue compilerOutputPathsValue;
+  private final AbiGenerationMode abiCompatibilityMode;
+  private final ImmutableList<String> options;
+  private final JavacPluginParams annotationProcessorParams;
+  private final JavacPluginParams pluginParams;
+  private final ImmutableSortedSet<RelPath> javaSourceFilePaths;
+  private final RelPath pathToSrcsList;
+  private final AbiGenerationMode abiGenerationMode;
+  @Nullable private final JarParameters abiJarParameters;
+  @Nullable private final JarParameters libraryJarParameters;
+  @Nullable private final SourceOnlyAbiRuleInfoFactory ruleInfoFactory;
+  private final boolean trackClassUsage;
+
+  @Nullable private CompilerWorker worker;
+
+  public Jsr199JavacInvocation(
+      Supplier<JavaCompiler> compilerConstructor,
+      JavacExecutionContext context,
+      BuildTargetValue invokingRule,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      ImmutableList<String> options,
+      JavacPluginParams annotationProcessorParams,
+      JavacPluginParams pluginParams,
+      ImmutableSortedSet<RelPath> javaSourceFilePaths,
+      RelPath pathToSrcsList,
+      boolean trackClassUsage,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters,
+      AbiGenerationMode abiGenerationMode,
+      AbiGenerationMode abiCompatibilityMode,
+      @Nullable SourceOnlyAbiRuleInfoFactory ruleInfoFactory) {
+    this.compilerConstructor = compilerConstructor;
+    this.context = context;
+    this.invokingRule = invokingRule;
+    this.compilerOutputPathsValue = compilerOutputPathsValue;
+    this.abiCompatibilityMode = abiCompatibilityMode;
+    this.options = options;
+    this.annotationProcessorParams = annotationProcessorParams;
+    this.pluginParams = pluginParams;
+    this.javaSourceFilePaths = javaSourceFilePaths;
+    this.pathToSrcsList = pathToSrcsList;
+    this.trackClassUsage = trackClassUsage;
+    this.abiJarParameters = abiJarParameters;
+    this.libraryJarParameters = libraryJarParameters;
+    this.abiGenerationMode = abiGenerationMode;
+    this.ruleInfoFactory = ruleInfoFactory;
+  }
+
+  @Override
+  public int buildSourceOnlyAbiJar(boolean isMixedModule) throws InterruptedException {
+    return getWorker()
+        .buildSourceOnlyAbiJar(
+            compilerOutputPathsValue.getSourceOnlyAbiCompilerOutputPath().getOutputJarDirPath(),
+            isMixedModule);
+  }
+
+  @Override
+  public int buildSourceAbiJar() throws InterruptedException {
+    return getWorker()
+        .buildSourceAbiJar(
+            compilerOutputPathsValue.getSourceAbiCompilerOutputPath().getOutputJarDirPath());
+  }
+
+  @Override
+  public int buildClasses() throws InterruptedException {
+    // write javaSourceFilePaths to classes file
+    // for buck user to have a list of all .java files to be compiled
+    // since we do not print them out to console in case of error
+    try {
+      AbsPath ruleCellRoot = context.getRuleCellRoot();
+
+      ProjectFilesystemUtils.writeLinesToPath(
+          ruleCellRoot,
+          () ->
+              javaSourceFilePaths.stream()
+                  .map(Object::toString)
+                  .map(ResolvedJavac.ARGFILES_ESCAPER)
+                  .iterator(),
+          pathToSrcsList.getPath());
+    } catch (IOException e) {
+      throw new RuntimeException("Error writing list of .java files to compile.", e);
+    }
+
+    return getWorker().buildClasses();
+  }
+
+  private CompilerWorker getWorker() {
+    if (worker == null) {
+      worker = new CompilerWorker(THREAD_POOL);
+    }
+
+    return worker;
+  }
+
+  @Override
+  public void close() {
+    // Must close the worker first so that the compiler has a chance to exit.
+    if (worker != null) {
+      worker.close();
+      worker = null;
+    }
+  }
+
+  private class CompilerWorker implements AutoCloseable {
+
+    private final ListeningExecutorService executor;
+
+    private final SettableFuture<Integer> compilerResult = SettableFuture.create();
+    private final SettableFuture<Boolean> shouldCompileFullJar = SettableFuture.create();
+    private final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
+    private final List<AutoCloseable> closeables = new ArrayList<>();
+
+    @Nullable private BuckJavacTaskProxy lazyJavacTask;
+
+    @Nullable private String compilerThreadName;
+    @Nullable private JavaInMemoryFileManager inMemoryFileManager;
+    @Nullable private final ClassUsageTracker classUsageTracker;
+
+    private CompilerWorker(ListeningExecutorService executor) {
+      this.executor = executor;
+      this.classUsageTracker = trackClassUsage ? new ClassUsageTracker() : null;
+    }
+
+    public int buildSourceOnlyAbiJar(RelPath outputJarDirPath, boolean isMixedModule)
+        throws InterruptedException {
+      return buildAbiJar(true, outputJarDirPath, isMixedModule);
+    }
+
+    public int buildSourceAbiJar(RelPath outputJarDirPath) throws InterruptedException {
+      return buildAbiJar(false, outputJarDirPath, false);
+    }
+
+    private int buildAbiJar(
+        boolean buildSourceOnlyAbi, RelPath outputJarDirPath, boolean isMixedModule)
+        throws InterruptedException {
+      SettableFuture<Integer> abiResult = SettableFuture.create();
+      // abi is ready when compiler task finished
+      Futures.addCallback(
+          compilerResult,
+          new FutureCallback<>() {
+            @Override
+            public void onSuccess(@Nullable Integer exitCode) {
+              abiResult.set(exitCode);
+            }
+
+            @Override
+            public void onFailure(Throwable t) {
+              // Propagate failure
+              abiResult.setException(t);
+            }
+          },
+          directExecutor());
+
+      JarParameters jarParameters = Objects.requireNonNull(abiJarParameters);
+      BuckJavacTaskProxy javacTask = getJavacTask(buildSourceOnlyAbi);
+      // abi could be ready when compiler phase finished
+      javacTask.addPostEnterCallback(
+          topLevelTypes -> {
+            try {
+              AbsPath ruleCellRoot = context.getRuleCellRoot();
+              if (buildSuccessful()) {
+                // Only attempt to build stubs if the build is successful so far; errors can
+                // put javac into an unknown state.
+                JarBuilder jarBuilder = null;
+                if (!isMixedModule) {
+                  jarBuilder = newJarBuilder(jarParameters).setShouldHashEntries(true);
+                }
+                StubGenerator stubGenerator =
+                    new StubGenerator(
+                        getTargetVersion(options),
+                        javacTask.getElements(),
+                        javacTask.getTypes(),
+                        isMixedModule
+                            ? new DowngradeMissingAnnotationErrorMessager(javacTask.getMessager())
+                            : javacTask.getMessager(),
+                        jarBuilder,
+                        abiCompatibilityMode,
+                        options.contains("-parameters"),
+                        false,
+                        isMixedModule
+                            ? abiJarParameters.getEntriesToJar().first().toAbsolutePath()
+                            : null);
+                stubGenerator.generate(topLevelTypes);
+
+                if (!isMixedModule) {
+                  jarBuilder.createJarFile(
+                      ProjectFilesystemUtils.getPathForRelativePath(
+                          ruleCellRoot, jarParameters.getJarPath()));
+                }
+              }
+
+              debugLogDiagnostics();
+              int exitCode;
+              if (buildSuccessful()) {
+                if (classUsageTracker != null) {
+                  new DefaultClassUsageFileWriter()
+                      .writeFile(
+                          classUsageTracker.getClassUsageMap(),
+                          CompilerOutputPaths.getJavaDepFilePath(outputJarDirPath),
+                          ruleCellRoot,
+                          context.getConfiguredBuckOut());
+                }
+                exitCode = SUCCESS_EXIT_CODE;
+              } else {
+                reportDiagnosticsToUser();
+                exitCode = ERROR_EXIT_CODE;
+              }
+
+              boolean waitingForPipeline = needToWaitForPipeline();
+              // abi result is ready.
+              abiResult.set(exitCode);
+
+              if (waitingForPipeline) {
+                // Blocks till `shouldCompileFullJar` is set
+                switchToFullJarIfRequested();
+              }
+
+            } catch (IOException e) {
+              abiResult.setException(e);
+            } catch (InterruptedException | ExecutionException e) {
+              // These come from the `shouldCompileFullJar.get()` in the
+              // `switchToFullJarIfRequested()`, which should never throw
+              throw new AssertionError(e);
+            }
+          });
+
+      try {
+        String threadName = startCompiler(javacTask);
+        return abiResult.get();
+      } catch (ExecutionException e) {
+        Throwables.throwIfUnchecked(e.getCause());
+        throw new RuntimeException("Failed to generate abi: %s", e.getCause());
+      }
+    }
+
+    private boolean needToWaitForPipeline() {
+      return invokingRule.isSourceAbi();
+    }
+
+    private void switchToFullJarIfRequested() throws InterruptedException, ExecutionException {
+      if (!shouldCompileFullJar.get()) {
+        throw new StopCompilation();
+      }
+    }
+
+    public int buildClasses() throws InterruptedException {
+      shouldCompileFullJar.set(true);
+      try {
+        String threadName = startCompiler(getJavacTask(false));
+        return compilerResult.get();
+      } catch (ExecutionException e) {
+        Throwables.throwIfUnchecked(e.getCause());
+        throw new RuntimeException("Failed to compile", e.getCause());
+      }
+    }
+
+    /**
+     * Returns a snapshot of the diagnostics gathered so far. Formatting a diagnostic can make javac
+     * lazily complete an annotation type and report a new diagnostic into the collector, so
+     * iterating the collector's live view directly risks a ConcurrentModificationException on the
+     * compiler thread. Iterate this copy instead.
+     */
+    private List<Diagnostic<? extends JavaFileObject>> diagnosticsSnapshot() {
+      return new ArrayList<>(diagnostics.getDiagnostics());
+    }
+
+    private void debugLogDiagnostics() {
+      for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticsSnapshot()) {
+        LOG.debug("javac: %s", DiagnosticPrettyPrinter.format(diagnostic));
+      }
+    }
+
+    private void reportDiagnosticsToUser() {
+      if (context.getVerbosity().shouldPrintStandardInformation()) {
+        List<Diagnostic<? extends JavaFileObject>> cleanDiagnostics =
+            DiagnosticCleaner.clean(diagnosticsSnapshot());
+
+        int numErrors = 0;
+        int numWarnings = 0;
+        for (Diagnostic<? extends JavaFileObject> diagnostic : cleanDiagnostics) {
+          Diagnostic.Kind kind = diagnostic.getKind();
+          if (kind == Diagnostic.Kind.ERROR) {
+            ++numErrors;
+          } else if (kind == Diagnostic.Kind.WARNING || kind == Diagnostic.Kind.MANDATORY_WARNING) {
+            ++numWarnings;
+          }
+
+          context
+              .getStdErr()
+              .println(
+                  DiagnosticPrettyPrinter.format(
+                      diagnostic, Optional.of(context.getRuleCellRoot())));
+        }
+
+        if (numErrors > 0 || numWarnings > 0) {
+          context.getStdErr().printf("Errors: %d. Warnings: %d.%n", numErrors, numWarnings);
+        }
+      }
+    }
+
+    private boolean buildSuccessful() {
+      return diagnosticsSnapshot().stream()
+          .noneMatch(diag -> diag.getKind() == Diagnostic.Kind.ERROR);
+    }
+
+    private void addCloseable(Object maybeCloseable) {
+      if (maybeCloseable instanceof AutoCloseable) {
+        closeables.add((AutoCloseable) maybeCloseable);
+      }
+    }
+
+    @Override
+    public void close() {
+      if (!compilerResult.isDone()) {
+        // Make sure `.get()` won't hang forever if `compilerResult` is not initialized.
+        // Note, `set` is no-op is `.setFuture` is already called.
+        compilerResult.set(ERROR_EXIT_CODE);
+
+        shouldCompileFullJar.set(false);
+        try {
+          compilerResult.get();
+        } catch (InterruptedException e) {
+          Thread.currentThread().interrupt();
+        } catch (ExecutionException e) {
+          throw new AssertionError(e);
+        }
+      }
+    }
+
+    private String startCompiler(BuckJavacTaskProxy javacTask)
+        throws ExecutionException, InterruptedException {
+      if (compilerThreadName == null) {
+        SettableFuture<String> threadName = SettableFuture.create();
+        compilerResult.setFuture(executor.submit(() -> runCompilerTask(javacTask, threadName)));
+        compilerThreadName = threadName.get();
+      }
+      return compilerThreadName;
+    }
+
+    private int runCompilerTask(BuckJavacTaskProxy javacTask, SettableFuture<String> threadName)
+        throws IOException {
+      threadName.set(Thread.currentThread().getName());
+      String fullyQualifiedName = invokingRule.getFullyQualifiedName();
+      try {
+        boolean success = false;
+        try {
+          success = javacTask.call();
+        } catch (IllegalStateException ex) {
+          if (ex.getLocalizedMessage().equals("no source files")
+              || ex.getLocalizedMessage().equals("error: no source files")) {
+            success = true;
+          }
+        }
+        if (javacTask instanceof FrontendOnlyJavacTaskProxy) {
+          if (success) {
+            return SUCCESS_EXIT_CODE;
+          } else {
+            debugLogDiagnostics();
+            reportDiagnosticsToUser();
+            return ERROR_EXIT_CODE;
+          }
+        }
+
+        debugLogDiagnostics();
+
+        AbsPath ruleCellRoot = context.getRuleCellRoot();
+        if (success && buildSuccessful()) {
+          if (classUsageTracker != null) {
+            new DefaultClassUsageFileWriter()
+                .writeFile(
+                    classUsageTracker.getClassUsageMap(),
+                    CompilerOutputPaths.getJavaDepFilePath(
+                        compilerOutputPathsValue
+                            .getLibraryCompilerOutputPath()
+                            .getOutputJarDirPath()),
+                    ruleCellRoot,
+                    context.getConfiguredBuckOut());
+          }
+        } else {
+          reportDiagnosticsToUser();
+          return ERROR_EXIT_CODE;
+        }
+
+        if (libraryJarParameters == null) {
+          return SUCCESS_EXIT_CODE;
+        }
+
+        newJarBuilder(libraryJarParameters)
+            .createJarFile(
+                Objects.requireNonNull(
+                    ProjectFilesystemUtils.getPathForRelativePath(
+                        ruleCellRoot, libraryJarParameters.getJarPath())));
+
+        return SUCCESS_EXIT_CODE;
+      } catch (RuntimeException e) {
+        if (e.getCause() instanceof StopCompilation) {
+          return SUCCESS_EXIT_CODE;
+        } else if (javacTask instanceof FrontendOnlyJavacTaskProxy) {
+          throw new RuntimeException(
+              String.format(
+                  "The compiler crashed attempting to generate a source-only ABI: %s.\n"
+                      + "Try building %s instead and fixing any errors that are emitted.\n"
+                      + "If there are none, file an issue, with the crash trace from the log.\n",
+                  fullyQualifiedName,
+                  compilerOutputPathsValue.getLibraryTargetFullyQualifiedName()),
+              e);
+        } else {
+          throw new RuntimeException(e.getCause() != null ? e.getCause() : e);
+        }
+      } finally {
+        for (AutoCloseable closeable : Lists.reverse(closeables)) {
+          try {
+            closeable.close();
+          } catch (Exception e) {
+            LOG.warn(e, "Unable to close %s; we may be leaking memory.", closeable);
+          }
+        }
+      }
+    }
+
+    private BuckJavacTaskProxy getJavacTask(boolean generatingSourceOnlyAbi) {
+      if (lazyJavacTask == null) {
+        try {
+          JavaCompiler compiler = compilerConstructor.get();
+
+          StandardJavaFileManager standardFileManager =
+              compiler.getStandardFileManager(null, null, null);
+          addCloseable(standardFileManager);
+
+          // Ensure plugins are loaded from their own classloader.
+          PluginFactory pluginFactory =
+              new PluginFactory(
+                  compiler.getClass().getClassLoader(), context.getClassLoaderCache());
+
+          PluginLoaderJavaFileManager fileManager;
+          AbsPath ruleCellRoot = context.getRuleCellRoot();
+          if (libraryJarParameters != null) {
+            Path directToJarPath =
+                ProjectFilesystemUtils.getPathForRelativePath(
+                    ruleCellRoot, libraryJarParameters.getJarPath());
+            inMemoryFileManager =
+                new JavaInMemoryFileManager(
+                    standardFileManager,
+                    directToJarPath,
+                    libraryJarParameters.getRemoveEntryPredicate());
+            addCloseable(inMemoryFileManager);
+            fileManager =
+                new PluginLoaderJavaFileManager(
+                    context, inMemoryFileManager, pluginFactory, pluginParams);
+          } else {
+            inMemoryFileManager = null;
+            fileManager =
+                new PluginLoaderJavaFileManager(
+                    context, standardFileManager, pluginFactory, pluginParams);
+          }
+
+          Iterable<? extends JavaFileObject> compilationUnits;
+          try {
+            compilationUnits =
+                createCompilationUnits(fileManager, ruleCellRoot::resolve, javaSourceFilePaths);
+            compilationUnits.forEach(this::addCloseable);
+          } catch (IOException e) {
+            LOG.warn(e, "Error building compilation units");
+            throw e;
+          }
+
+          List<String> classNamesForAnnotationProcessing = ImmutableList.of();
+          Writer compilerOutputWriter =
+              new java.io.PrintWriter(context.getStdErr()); // NOPMD required by API
+          PluginClassLoaderFactory loaderFactory =
+              PluginLoader.newFactory(context.getClassLoaderCache());
+
+          ListenableFileManager wrappedFileManager = new ListenableFileManager(fileManager);
+          if (classUsageTracker != null) {
+            wrappedFileManager.addListener(classUsageTracker);
+          }
+          BuckJavacTaskProxy javacTask;
+          if (generatingSourceOnlyAbi) {
+            javacTask =
+                FrontendOnlyJavacTaskProxy.getTask(
+                    loaderFactory,
+                    compiler,
+                    compilerOutputWriter,
+                    wrappedFileManager,
+                    diagnostics,
+                    options,
+                    classNamesForAnnotationProcessing,
+                    compilationUnits);
+          } else {
+            javacTask =
+                BuckJavacTaskProxy.getTask(
+                    loaderFactory,
+                    compiler,
+                    compilerOutputWriter,
+                    wrappedFileManager,
+                    diagnostics,
+                    options,
+                    classNamesForAnnotationProcessing,
+                    compilationUnits);
+          }
+
+          PluginClassLoader pluginLoader = loaderFactory.getPluginClassLoader(javacTask);
+
+          BuckJavacTaskListener taskListener = null;
+          if (checkForSourceOnlyAbiCompatibility(abiGenerationMode)
+              && !generatingSourceOnlyAbi
+              && ruleInfoFactory != null) {
+            taskListener =
+                SourceBasedAbiStubber.newValidatingTaskListener(
+                    pluginLoader,
+                    javacTask,
+                    ruleInfoFactory.create(fileManager),
+                    () ->
+                        diagnosticsSnapshot().stream()
+                            .anyMatch(diagnostic -> diagnostic.getKind() == Diagnostic.Kind.ERROR),
+                    getDiagnosticKindForSourceOnlyAbiCompatibility(abiGenerationMode));
+          }
+
+          // Ensure annotation processors are loaded from their own classloader. If we don't do
+          // this, then the evidence suggests that they get one polluted with Buck's own classpath,
+          // which means that libraries that have dependencies on different versions of Buck's deps
+          // may choke with novel errors that don't occur on the command line.
+          AnnotationProcessorFactory processorFactory =
+              new AnnotationProcessorFactory(
+                  compiler.getClass().getClassLoader(),
+                  context.getClassLoaderCache(),
+                  invokingRule.getFullyQualifiedName());
+          addCloseable(processorFactory);
+
+          javacTask.setProcessors(
+              processorFactory.createProcessors(context, annotationProcessorParams));
+          lazyJavacTask = javacTask;
+        } catch (IOException e) {
+          LOG.error(e);
+          throw new RuntimeException("IOException during compilation", e);
+        }
+      }
+
+      return lazyJavacTask;
+    }
+
+    private JarBuilder newJarBuilder(JarParameters jarParameters) {
+      JarBuilder jarBuilder = new JarBuilder();
+      Objects.requireNonNull(inMemoryFileManager).writeToJar(jarBuilder);
+      AbsPath rootPath = context.getRuleCellRoot();
+      return jarBuilder
+          .setEntriesToJar(jarParameters.getEntriesToJar().stream().map(rootPath::resolve))
+          .setOverrideEntriesToJar(
+              jarParameters.getOverrideEntriesToJar().stream().map(rootPath::resolve))
+          .setMainClass(jarParameters.getMainClass().orElse(null))
+          .setManifestFile(
+              jarParameters
+                  .getManifestFile()
+                  .map(rootPath::resolve)
+                  .map(AbsPath::getPath)
+                  .orElse(null))
+          .setShouldMergeManifests(true)
+          .setRemoveEntryPredicate(jarParameters.getRemoveEntryPredicate());
+    }
+
+    private Iterable<? extends JavaFileObject> createCompilationUnits(
+        StandardJavaFileManager fileManager,
+        Function<RelPath, AbsPath> absolutifier,
+        Set<RelPath> javaSourceFilePaths)
+        throws IOException {
+      List<JavaFileObject> compilationUnits = new ArrayList<>();
+      boolean seenZipOrJarSources = false;
+      for (RelPath path : javaSourceFilePaths) {
+        String pathString = path.toString();
+        if (pathString.endsWith(".java")) {
+          // For an ordinary .java file, create a corresponding JavaFileObject.
+          Iterable<? extends JavaFileObject> javaFileObjects =
+              fileManager.getJavaFileObjects(absolutifier.apply(path).toFile());
+          compilationUnits.add(Iterables.getOnlyElement(javaFileObjects));
+        } else if (pathString.endsWith(JavaPaths.SRC_ZIP)
+            || pathString.endsWith(JavaPaths.SRC_JAR)) {
+          // For a Zip of .java files, create a JavaFileObject for each .java entry.
+          ZipFile zipFile = new ZipFile(absolutifier.apply(path).toFile());
+          boolean hasZipFileBeenUsed = false;
+          seenZipOrJarSources = true;
+          for (Enumeration<? extends ZipEntry> entries = zipFile.entries();
+              entries.hasMoreElements(); ) {
+            ZipEntry entry = entries.nextElement();
+            if (!entry.getName().endsWith(".java")) {
+              continue;
+            }
+
+            hasZipFileBeenUsed = true;
+            compilationUnits.add(new ZipEntryJavaFileObject(zipFile, entry));
+          }
+
+          if (!hasZipFileBeenUsed) {
+            zipFile.close();
+          }
+        } else {
+          throw new RuntimeException(
+              String.format(
+                  "Unexpected file in java source paths: %s. Only .java files, .src.zip files, "
+                      + "and .src.jar files are allowed.",
+                  pathString));
+        }
+      }
+
+      // Bail now if none of the given files were Java files - we don't want to run non-Java files
+      // through javac and it's unlikely that this was the user's intention.
+      //
+      // If we've seen a source zip file that was empty, allow it. Annotation processor rules
+      // generate zip files of java sources which may not contain any java files if there were no
+      // annotations to process. Since this process is automated, it doesn't make sense to raise
+      // a human-facing error message in that case.
+      if (!seenZipOrJarSources && !javaSourceFilePaths.isEmpty() && compilationUnits.isEmpty()) {
+        throw new RuntimeException(NO_JAVA_FILES_ERROR_MESSAGE);
+      }
+      return compilationUnits;
+    }
+  }
+
+  private static SourceVersion getTargetVersion(Iterable<String> options) {
+    boolean foundTarget = false;
+    for (String option : options) {
+      if (option.equals("-target")) {
+        foundTarget = true;
+      } else if (foundTarget) {
+        return SourceVersionUtils.getSourceVersionFromTarget(option);
+      }
+    }
+
+    throw new AssertionError("Unreachable code");
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ListenableFileManager.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ListenableFileManager.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ListenableFileManager.java
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.NotThreadSafe;
+import javax.tools.FileObject;
+import javax.tools.ForwardingJavaFileObject;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+
+@NotThreadSafe
+class ListenableFileManager extends ForwardingStandardJavaFileManager {
+
+  private final FileObjectWrapper fileTracker;
+  private final List<FileManagerListener> listeners = new ArrayList<>();
+
+  public ListenableFileManager(StandardJavaFileManager fileManager) {
+    super(fileManager);
+    fileTracker = new FileObjectWrapper();
+  }
+
+  public void addListener(FileManagerListener listener) {
+    listeners.add(listener);
+  }
+
+  public void removeListener(FileManagerListener listener) {
+    listeners.remove(listener);
+  }
+
+  @Override
+  public String inferBinaryName(Location location, JavaFileObject file) {
+    // javac does not play nice with wrapped file objects in this method; so we unwrap
+    return super.inferBinaryName(location, unwrap(file));
+  }
+
+  @Override
+  public boolean isSameFile(FileObject a, FileObject b) {
+    // javac does not play nice with wrapped file objects in this method; so we unwrap
+    return super.isSameFile(unwrap(a), unwrap(b));
+  }
+
+  private JavaFileObject unwrap(JavaFileObject file) {
+    if (file instanceof ListenableJavaFileObject) {
+      return ((ListenableJavaFileObject) file).getJavaFileObject();
+    }
+    return file;
+  }
+
+  private FileObject unwrap(FileObject file) {
+    if (file instanceof JavaFileObject) {
+      return unwrap((JavaFileObject) file);
+    }
+
+    return file;
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(
+      Iterable<? extends File> files) {
+    return fileManager.getJavaFileObjectsFromFiles(files);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) {
+    return fileManager.getJavaFileObjects(files);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
+    return fileManager.getJavaFileObjectsFromStrings(names);
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) {
+    return fileManager.getJavaFileObjects(names);
+  }
+
+  @Override
+  public Iterable<JavaFileObject> list(
+      Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse)
+      throws IOException {
+    Iterable<JavaFileObject> listIterator = super.list(location, packageName, kinds, recurse);
+    if (location == StandardLocation.ANNOTATION_PROCESSOR_PATH) {
+      return listIterator;
+    } else {
+      return new TrackingIterable(listIterator);
+    }
+  }
+
+  @Override
+  @Nullable
+  public JavaFileObject getJavaFileForInput(
+      Location location, String className, JavaFileObject.Kind kind) throws IOException {
+    JavaFileObject javaFileObject = super.getJavaFileForInput(location, className, kind);
+    if (javaFileObject == null) {
+      return null;
+    }
+    if (location == StandardLocation.ANNOTATION_PROCESSOR_PATH) {
+      return javaFileObject;
+    } else {
+      return fileTracker.wrap(javaFileObject);
+    }
+  }
+
+  @Override
+  public JavaFileObject getJavaFileForOutput(
+      Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
+      throws IOException {
+    JavaFileObject javaFileObject = super.getJavaFileForOutput(location, className, kind, sibling);
+    if (location == StandardLocation.ANNOTATION_PROCESSOR_PATH) {
+      return javaFileObject;
+    } else {
+      return fileTracker.wrap(javaFileObject);
+    }
+  }
+
+  @Override
+  public FileObject getFileForInput(Location location, String packageName, String relativeName)
+      throws IOException {
+    FileObject fileObject = super.getFileForInput(location, packageName, relativeName);
+    if (location == StandardLocation.ANNOTATION_PROCESSOR_PATH) {
+      return fileObject;
+    } else {
+      return fileTracker.wrap(fileObject);
+    }
+  }
+
+  @Override
+  public FileObject getFileForOutput(
+      Location location, String packageName, String relativeName, FileObject sibling)
+      throws IOException {
+    FileObject fileObject = super.getFileForOutput(location, packageName, relativeName, sibling);
+    if (location == StandardLocation.ANNOTATION_PROCESSOR_PATH) {
+      return fileObject;
+    } else {
+      return fileTracker.wrap(fileObject);
+    }
+  }
+
+  private class TrackingIterable implements Iterable<JavaFileObject> {
+    private final Iterable<? extends JavaFileObject> inner;
+
+    public TrackingIterable(Iterable<? extends JavaFileObject> inner) {
+      this.inner = inner;
+    }
+
+    @Override
+    public Iterator<JavaFileObject> iterator() {
+      return new TrackingIterator(inner.iterator());
+    }
+  }
+
+  private class TrackingIterator implements Iterator<JavaFileObject> {
+
+    private final Iterator<? extends JavaFileObject> inner;
+
+    public TrackingIterator(Iterator<? extends JavaFileObject> inner) {
+      this.inner = inner;
+    }
+
+    @Override
+    public boolean hasNext() {
+      return inner.hasNext();
+    }
+
+    @Override
+    public JavaFileObject next() {
+      return fileTracker.wrap(inner.next());
+    }
+
+    @Override
+    public void remove() {
+      inner.remove();
+    }
+  }
+
+  private class FileObjectWrapper {
+    public FileObject wrap(FileObject inner) {
+      if (inner instanceof JavaFileObject) {
+        return wrap((JavaFileObject) inner);
+      }
+      return inner;
+    }
+
+    public JavaFileObject wrap(JavaFileObject inner) {
+      return new ListenableJavaFileObject(Objects.requireNonNull(inner));
+    }
+  }
+
+  private class ListenableJavaFileObject extends ForwardingJavaFileObject<JavaFileObject> {
+    public ListenableJavaFileObject(JavaFileObject fileObject) {
+      super(fileObject);
+    }
+
+    @Override
+    public String toString() {
+      return fileObject.getName();
+    }
+
+    public JavaFileObject getJavaFileObject() {
+      return fileObject;
+    }
+
+    @Override
+    public InputStream openInputStream() throws IOException {
+      listeners.forEach(it -> it.onFileRead(fileObject));
+      return super.openInputStream();
+    }
+
+    @Override
+    public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
+      listeners.forEach(it -> it.onFileRead(fileObject));
+      return super.openReader(ignoreEncodingErrors);
+    }
+
+    @Override
+    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
+      listeners.forEach(it -> it.onFileRead(fileObject));
+      return super.getCharContent(ignoreEncodingErrors);
+    }
+
+    @Override
+    public OutputStream openOutputStream() throws IOException {
+      listeners.forEach(it -> it.onFileWritten(fileObject));
+      return super.openOutputStream();
+    }
+
+    @Override
+    public Writer openWriter() throws IOException {
+      listeners.forEach(it -> it.onFileWritten(fileObject));
+      return super.openWriter();
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/OptionsConsumer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/OptionsConsumer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/OptionsConsumer.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import java.util.Collection;
+
+public interface OptionsConsumer {
+  void addOptionValue(String option, String value);
+
+  void addFlag(String flagName);
+
+  void addExtras(Collection<String> extras);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/PluginFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/PluginFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/PluginFactory.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.util.ClassLoaderCache;
+
+// Counter part of AnnotationProcessorFactory
+public class PluginFactory implements AutoCloseable {
+
+  private final ClassLoader compilerClassLoader;
+  private final ClassLoaderCache globalClassLoaderCache;
+  private final ClassLoaderCache localClassLoaderCache = new ClassLoaderCache();
+
+  PluginFactory(ClassLoader compilerClassLoader, ClassLoaderCache globalClassLoaderCache) {
+    this.compilerClassLoader = compilerClassLoader;
+    this.globalClassLoaderCache = globalClassLoaderCache;
+  }
+
+  @Override
+  public void close() throws Exception {
+    localClassLoaderCache.close();
+  }
+
+  ClassLoader getClassLoaderForProcessorGroups(
+      JavacPluginParams pluginParams, AbsPath relPathRoot) {
+    ClassLoaderCache cache;
+    // We can avoid lots of overhead in large builds by reusing the same classloader for java
+    // plugins. However, some plugins use static variables in a way that assumes
+    // there is only one instance running in the process at a time (or at all), and such plugin
+    // would break running inside of Buck. So we default to creating a new ClassLoader
+    // if any plugins meets those requirements.
+    if (pluginParams.getPluginProperties().stream()
+        .allMatch(ResolvedJavacPluginProperties::getCanReuseClassLoader)) {
+      cache = globalClassLoaderCache;
+    } else {
+      cache = localClassLoaderCache;
+    }
+    return cache.getClassLoaderForClassPath(
+        compilerClassLoader, pluginParams.toUrlClasspath(relPathRoot));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/PluginLoaderJavaFileManager.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/PluginLoaderJavaFileManager.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/PluginLoaderJavaFileManager.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+
+public class PluginLoaderJavaFileManager extends ForwardingStandardJavaFileManager
+    implements StandardJavaFileManager {
+
+  private final JavacExecutionContext context;
+  private final PluginFactory pluginFactory;
+  private final JavacPluginParams javacPlugins;
+
+  /**
+   * Creates a new instance of ForwardingJavaFileManager.
+   *
+   * @param fileManager delegate to this file manager
+   * @param javacPlugins
+   */
+  protected PluginLoaderJavaFileManager(
+      JavacExecutionContext context,
+      StandardJavaFileManager fileManager,
+      PluginFactory pluginFactory,
+      JavacPluginParams javacPlugins) {
+    super(fileManager);
+    this.context = context;
+    this.pluginFactory = pluginFactory;
+    this.javacPlugins = javacPlugins;
+  }
+
+  @Override
+  public ClassLoader getClassLoader(Location location) {
+    // We only provide the shared classloader if there are plugins defined.
+    if (StandardLocation.ANNOTATION_PROCESSOR_PATH.equals(location)
+        && javacPlugins.getPluginProperties().size() > 0) {
+      return pluginFactory.getClassLoaderForProcessorGroups(
+          javacPlugins, context.getRuleCellRoot());
+    }
+    return super.getClassLoader(location);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/RemoveClassesPatternsMatcher.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/RemoveClassesPatternsMatcher.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/RemoveClassesPatternsMatcher.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.google.common.base.MoreObjects;
+import com.google.common.base.Objects;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import java.util.function.Predicate;
+import java.util.regex.Pattern;
+import java.util.zip.ZipEntry;
+
+public class RemoveClassesPatternsMatcher implements Predicate<Object> {
+  public static final RemoveClassesPatternsMatcher EMPTY =
+      new RemoveClassesPatternsMatcher(ImmutableSet.of());
+
+  private final ImmutableList<Pattern> patterns;
+  private final boolean removeNonClassFiles;
+
+  public RemoveClassesPatternsMatcher(ImmutableSet<Pattern> patterns) {
+    this(patterns, false);
+  }
+
+  public RemoveClassesPatternsMatcher(ImmutableSet<Pattern> patterns, boolean removeNonClassFiles) {
+    this.patterns = ImmutableList.copyOf(patterns);
+    this.removeNonClassFiles = removeNonClassFiles;
+  }
+
+  private boolean shouldRemoveClass(ZipEntry entry) {
+    if (patterns.isEmpty()) {
+      return false;
+    }
+
+    if (!removeNonClassFiles && !entry.getName().endsWith(".class")) {
+      return false;
+    }
+
+    return shouldRemoveClass(pathToClassName(entry.getName()));
+  }
+
+  private boolean shouldRemoveClass(String className) {
+    if (patterns.isEmpty()) {
+      return false;
+    }
+
+    for (Pattern pattern : patterns) {
+      if (pattern.matcher(className).find()) {
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  private static String pathToClassName(String classFilePath) {
+    return classFilePath.replace('/', '.').replace(".class", "");
+  }
+
+  @Override
+  public boolean test(Object o) {
+    if (o instanceof ZipEntry) {
+      return shouldRemoveClass((ZipEntry) o);
+    } else {
+      return shouldRemoveClass((String) o);
+    }
+  }
+
+  public ImmutableList<Pattern> getPatterns() {
+    return patterns;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) {
+      return true;
+    }
+    if (o == null || getClass() != o.getClass()) {
+      return false;
+    }
+    RemoveClassesPatternsMatcher that = (RemoveClassesPatternsMatcher) o;
+    return Objects.equal(patterns, that.patterns);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hashCode(patterns);
+  }
+
+  @Override
+  public String toString() {
+    return MoreObjects.toStringHelper(this).add("patterns", patterns).toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavac.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavac.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavac.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory;
+import com.facebook.buck.util.Escaper;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSortedSet;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+
+/** Interface for a resolved javac tool. */
+public interface ResolvedJavac {
+
+  /** An escaper for arguments written to @argfiles. */
+  Function<String, String> ARGFILES_ESCAPER = Escaper.javacEscaper();
+
+  /** Prepares an invocation of the compiler with the given parameters. */
+  ResolvedJavac.Invocation newBuildInvocation(
+      JavacExecutionContext context,
+      BuildTargetValue invokingRule,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      ImmutableList<String> options,
+      JavacPluginParams annotationProcessorParams,
+      JavacPluginParams pluginParams,
+      ImmutableSortedSet<RelPath> javaSourceFilePaths,
+      RelPath pathToSrcsList,
+      RelPath workingDirectory,
+      boolean trackClassUsage,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters,
+      AbiGenerationMode abiGenerationMode,
+      AbiGenerationMode abiCompatibilityMode,
+      @Nullable SourceOnlyAbiRuleInfoFactory ruleInfoFactory);
+
+  String getDescription(ImmutableList<String> options, RelPath pathToSrcsList);
+
+  /** Returns a short name of the tool */
+  String getShortName();
+
+  /** Interface that defines invocation object created during java compilation. */
+  interface Invocation extends AutoCloseable {
+
+    /**
+     * Produces a source-only ABI jar. {@link #buildClasses} may not be called on an invocation on
+     * which this has been called.
+     */
+    int buildSourceOnlyAbiJar(boolean isMixedModule) throws InterruptedException;
+
+    /** Produces a source ABI jar. Must be called before {@link #buildClasses} */
+    int buildSourceAbiJar() throws InterruptedException;
+
+    int buildClasses() throws InterruptedException;
+
+    @Override
+    void close();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavacOptions.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavacOptions.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavacOptions.kt
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java
+
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.core.filesystems.RelPath
+import com.google.common.collect.ImmutableList
+import com.google.common.collect.ImmutableSortedSet
+import java.io.File
+import java.util.*
+import java.util.stream.Collectors
+
+/** Resolved JavacOptions used in [JavacPipelineState] */
+data class ResolvedJavacOptions(
+    val bootclasspathList: ImmutableList<RelPath>,
+    val languageLevelOptions: JavacLanguageLevelOptions,
+    val debug: Boolean,
+    val verbose: Boolean,
+    val javaAnnotationProcessorParams: JavacPluginParams,
+    val standardJavacPluginParams: JavacPluginParams,
+    val extraArguments: ImmutableList<String>,
+    val systemImage: String? = null,
+) {
+  val isJavaAnnotationProcessorParamsPresent: Boolean
+    get() = !javaAnnotationProcessorParams.isEmpty
+
+  fun withJavaAnnotationProcessorParams(
+      javaAnnotationProcessorParams: JavacPluginParams,
+  ): ResolvedJavacOptions {
+    if (this.javaAnnotationProcessorParams == javaAnnotationProcessorParams) {
+      return this
+    }
+    return ResolvedJavacOptions(
+        bootclasspathList,
+        languageLevelOptions,
+        debug,
+        verbose,
+        javaAnnotationProcessorParams,
+        standardJavacPluginParams,
+        extraArguments,
+        systemImage,
+    )
+  }
+
+  companion object {
+
+    /** Add options method */
+    @JvmStatic
+    fun appendOptionsTo(
+        optionsConsumer: OptionsConsumer,
+        resolvedJavacOptions: ResolvedJavacOptions,
+        rootCellRoot: AbsPath,
+    ) {
+      appendOptionsTo(
+          rootCellRoot,
+          optionsConsumer,
+          getBootclasspathString(resolvedJavacOptions.bootclasspathList),
+          resolvedJavacOptions.languageLevelOptions,
+          resolvedJavacOptions.debug,
+          resolvedJavacOptions.verbose,
+          resolvedJavacOptions.javaAnnotationProcessorParams,
+          resolvedJavacOptions.standardJavacPluginParams,
+          resolvedJavacOptions.extraArguments,
+      )
+    }
+
+    private fun appendOptionsTo(
+        ruleCellRoot: AbsPath,
+        optionsConsumer: OptionsConsumer,
+        bootclasspathString: Optional<String>,
+        languageLevelOptions: JavacLanguageLevelOptions,
+        isDebug: Boolean,
+        isVerbose: Boolean,
+        javaAnnotationProcessorParams: JavacPluginParams,
+        standardJavacPluginParams: JavacPluginParams,
+        extraArguments: List<String?>,
+    ) {
+      // Add some standard options.
+
+      val sourceLevel = languageLevelOptions.sourceLevelValue
+      val targetLevel = languageLevelOptions.targetLevelValue
+      optionsConsumer.addOptionValue("source", sourceLevel.toString())
+      optionsConsumer.addOptionValue("target", targetLevel.toString())
+
+      // Set the sourcepath to stop us reading source files out of jars by mistake.
+      optionsConsumer.addOptionValue("sourcepath", "")
+
+      if (isDebug) {
+        optionsConsumer.addFlag("g")
+      }
+
+      if (isVerbose) {
+        optionsConsumer.addFlag("verbose")
+      }
+
+      // Override the bootclasspath if Buck is building Java code for Android.
+      if (languageLevelOptions.targetLevelValue <= 8) {
+        bootclasspathString.ifPresent { bootclasspath: String? ->
+          optionsConsumer.addOptionValue("bootclasspath", bootclasspath)
+        }
+      }
+
+      val allPluginsBuilder = ImmutableList.builder<ResolvedJavacPluginProperties>()
+      // Add annotation processors.
+      if (!javaAnnotationProcessorParams.isEmpty) {
+        val annotationProcessors = javaAnnotationProcessorParams.pluginProperties
+        allPluginsBuilder.addAll(annotationProcessors)
+
+        // Specify names of processors.
+        optionsConsumer.addOptionValue(
+            "processor",
+            annotationProcessors
+                .stream()
+                .map { obj: ResolvedJavacPluginProperties -> obj.processorNames }
+                .flatMap { obj: ImmutableSortedSet<String> -> obj.stream() }
+                .collect(Collectors.joining(",")),
+        )
+
+        // Add processor parameters.
+        for (parameter in javaAnnotationProcessorParams.parameters) {
+          optionsConsumer.addFlag("A$parameter")
+        }
+      } else {
+        // Disable automatic annotation processor lookup
+        optionsConsumer.addFlag("proc:none")
+      }
+
+      if (!standardJavacPluginParams.isEmpty) {
+        val javacPlugins = standardJavacPluginParams.pluginProperties
+        allPluginsBuilder.addAll(javacPlugins)
+
+        for (properties in javacPlugins) {
+          val name = properties.processorNames.first()
+          val xplugin = StringBuilder("Xplugin:")
+          xplugin.append(name)
+          for (argument in properties.arguments) {
+            xplugin.append(' ')
+            xplugin.append(argument)
+          }
+
+          optionsConsumer.addFlag(xplugin.toString())
+
+          // Add plugin's SourcePath params with RelPath's resolved relative to root
+          for ((key, value) in properties.pathParams) {
+            optionsConsumer.addFlag(String.format("A%s=%s", key, ruleCellRoot.resolve(value)))
+          }
+        }
+
+        // Add plugin parameters.
+        optionsConsumer.addExtras(standardJavacPluginParams.parameters)
+      }
+
+      // Specify classpath to include javac plugins and annotation processors.
+      val allPlugins = allPluginsBuilder.build()
+      if (!allPlugins.isEmpty()) {
+        optionsConsumer.addOptionValue(
+            "processorpath",
+            ResolvedJavacPluginProperties.getJoinedClasspath(allPlugins, ruleCellRoot),
+        )
+      }
+
+      // Add extra arguments.
+      optionsConsumer.addExtras(extraArguments)
+    }
+
+    fun getBootclasspathString(bootclasspathList: ImmutableList<RelPath>): Optional<String> {
+      if (bootclasspathList.isEmpty()) {
+        return Optional.empty()
+      }
+
+      return Optional.of(
+          bootclasspathList
+              .stream()
+              .map(RelPath::toString)
+              .collect(Collectors.joining(File.pathSeparator)),
+      )
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavacPluginProperties.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavacPluginProperties.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ResolvedJavacPluginProperties.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.stream.Collectors;
+
+/** Resolved JavacPluginProperties used in {@link JavacPipelineState} */
+public class ResolvedJavacPluginProperties {
+
+  private final boolean canReuseClassLoader;
+  private final boolean doesNotAffectAbi;
+  private final boolean supportsAbiGenerationFromSource;
+  private final boolean runsOnJavaOnly;
+  private final ImmutableSortedSet<String> processorNames;
+
+  private final ImmutableList<String> arguments;
+
+  private final ImmutableList<RelPath> classpath;
+
+  private final ImmutableMap<String, RelPath> pathParams;
+
+  public ResolvedJavacPluginProperties(
+      boolean canReuseClassLoader,
+      boolean doesNotAffectAbi,
+      boolean supportsAbiGenerationFromSource,
+      boolean runsOnJavaOnly,
+      ImmutableSortedSet<String> processorNames,
+      ImmutableList<RelPath> classpath,
+      ImmutableMap<String, RelPath> pathParams,
+      ImmutableList<String> arguments) {
+    this.canReuseClassLoader = canReuseClassLoader;
+    this.doesNotAffectAbi = doesNotAffectAbi;
+    this.supportsAbiGenerationFromSource = supportsAbiGenerationFromSource;
+    this.runsOnJavaOnly = runsOnJavaOnly;
+    this.processorNames = processorNames;
+    this.classpath = classpath;
+    this.pathParams = pathParams;
+    this.arguments = arguments;
+  }
+
+  public boolean getCanReuseClassLoader() {
+    return canReuseClassLoader;
+  }
+
+  public boolean getDoesNotAffectAbi() {
+    return doesNotAffectAbi;
+  }
+
+  public boolean getSupportAbiGenerationFromSource() {
+    return supportsAbiGenerationFromSource;
+  }
+
+  public boolean getRunsOnJavaOnly() {
+    return runsOnJavaOnly;
+  }
+
+  public ImmutableSortedSet<String> getProcessorNames() {
+    return processorNames;
+  }
+
+  /** Get the classpath for the plugin. */
+  public ImmutableList<RelPath> getClasspath() {
+    return classpath;
+  }
+
+  public ImmutableMap<String, RelPath> getPathParams() {
+    return pathParams;
+  }
+
+  public ImmutableList<String> getArguments() {
+    return arguments;
+  }
+
+  public static String getJoinedClasspath(
+      ImmutableList<ResolvedJavacPluginProperties> resolvedProperties, AbsPath root) {
+    return resolvedProperties.stream()
+        .flatMap(p -> p.classpath.stream())
+        .distinct()
+        .map(root::resolve)
+        .map(AbsPath::normalize)
+        .map(ResolvedJavacPluginProperties::toUrl)
+        .map(ResolvedJavacPluginProperties::toURI)
+        .map(Paths::get)
+        .map(Path::toString)
+        .collect(Collectors.joining(File.pathSeparator));
+  }
+
+  static URI toURI(URL url) {
+    try {
+      return url.toURI();
+    } catch (URISyntaxException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  static URL toUrl(AbsPath absPath) {
+    try {
+      return absPath.toUri().toURL();
+    } catch (MalformedURLException e) {
+      // The paths we're being given should have all been resolved from the file system already.
+      // We'd need to be unfortunate to get here. Bubble up a runtime exception.
+      throw new RuntimeException(e);
+    }
+  }
+
+  /** Resolves classpath to a list of URL */
+  public ImmutableList<URL> toUrlClasspath(AbsPath relPathRoot) {
+    ImmutableList.Builder<URL> builder = ImmutableList.builder();
+    for (RelPath relPath : getClasspath()) {
+      AbsPath path = relPathRoot.resolve(relPath).normalize();
+      builder.add(toUrl(path));
+    }
+    return builder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ZipEntryJavaFileObject.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ZipEntryJavaFileObject.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/ZipEntryJavaFileObject.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java;
+
+import com.google.common.io.CharStreams;
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.charset.StandardCharsets;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+
+class ZipEntryJavaFileObject extends SimpleJavaFileObject implements Closeable {
+
+  private final ZipFile zipFile;
+  private final ZipEntry zipEntry;
+
+  @GuardedBy("this")
+  @Nullable
+  private String contents;
+
+  public ZipEntryJavaFileObject(ZipFile zipFile, ZipEntry zipEntry) {
+    super(createURIFromEntry(zipEntry), JavaFileObject.Kind.SOURCE);
+    this.zipFile = zipFile;
+    this.zipEntry = zipEntry;
+  }
+
+  /**
+   * Creates a canonical URI that represents the {@link ZipEntry}. This URI starts with {@code
+   * "string:///"} because {@link JavaCompiler} does not seem to tolerate URIs that start with
+   * {@code "jar:///"}, even though that would be more appropriate.
+   */
+  private static URI createURIFromEntry(ZipEntry entry) {
+    try {
+      URI fileUri = new File(entry.getName()).toURI();
+      return new URI("string", fileUri.getHost(), fileUri.getPath(), fileUri.getFragment());
+    } catch (URISyntaxException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  /**
+   * Returns the contents of the {@link ZipEntry} as a string. Ensures that the entry is read at
+   * most once.
+   */
+  private synchronized String getContentsAsString() {
+    if (contents != null) {
+      return contents;
+    }
+
+    try (InputStream inputStream = zipFile.getInputStream(zipEntry);
+        InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
+      contents = CharStreams.toString(isr);
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+
+    return contents;
+  }
+
+  /** Closes the {@link ZipFile} this entry was loaded from. Use with care. */
+  @Override
+  public void close() throws IOException {
+    zipFile.close();
+  }
+
+  @Override
+  public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+    return getContentsAsString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AbiFilteringClassVisitor.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AbiFilteringClassVisitor.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AbiFilteringClassVisitor.java
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.objectweb.asm.Attribute;
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.FieldVisitor;
+import org.objectweb.asm.Handle;
+import org.objectweb.asm.Label;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.Type;
+
+/** A {@link ClassVisitor} that only passes to its delegate events for the class's ABI. */
+class AbiFilteringClassVisitor extends ClassVisitor {
+
+  private final List<String> methodsWithRetainedBody;
+  @Nullable private final Set<String> referencedClassNames;
+
+  @Nullable private String name;
+  @Nullable private String outerName = null;
+  private int classAccess;
+  private int classVersion;
+  private boolean hasVisibleConstructor = false;
+  private final Set<String> includedInnerClasses = new HashSet<>();
+  private final List<String> nestMembers = new ArrayList<>();
+  private boolean keepSynthetic;
+
+  public AbiFilteringClassVisitor(
+      ClassVisitor cv, List<String> methodsWithRetainedBody, boolean keepSynthetic) {
+    this(cv, methodsWithRetainedBody, null, keepSynthetic);
+  }
+
+  public AbiFilteringClassVisitor(
+      ClassVisitor cv,
+      List<String> methodsWithRetainedBody,
+      @Nullable Set<String> referencedClassNames,
+      boolean keepSynthetic) {
+    super(Opcodes.ASM9, cv);
+    this.methodsWithRetainedBody = methodsWithRetainedBody;
+    this.referencedClassNames = referencedClassNames;
+    this.keepSynthetic = keepSynthetic;
+  }
+
+  @Override
+  public void visit(
+      int version,
+      int access,
+      String name,
+      String signature,
+      String superName,
+      String[] interfaces) {
+    this.name = name;
+    classAccess = access;
+    classVersion = version;
+    super.visit(version, access, name, signature, superName, interfaces);
+  }
+
+  @Override
+  public void visitInnerClass(String name, String outerName, String innerName, int access) {
+    if (name.equals(this.name)) {
+      this.outerName = outerName;
+    }
+
+    if (!shouldIncludeInnerClass(access, name, outerName)) {
+      return;
+    }
+
+    includedInnerClasses.add(name);
+    super.visitInnerClass(name, outerName, innerName, access);
+  }
+
+  @Override
+  public void visitNestMember(String nestMember) {
+    Preconditions.checkState(classVersion >= Opcodes.V11);
+    nestMembers.add(nestMember);
+  }
+
+  @Override
+  @Nullable
+  public FieldVisitor visitField(
+      int access, String name, String desc, String signature, Object value) {
+    if (!shouldInclude(access)) {
+      return null;
+    }
+    return super.visitField(access, name, desc, signature, value);
+  }
+
+  @Override
+  @Nullable
+  public MethodVisitor visitMethod(
+      int access, String name, String desc, String signature, String[] exceptions) {
+    if (methodsWithRetainedBody.contains(name)
+        || (name.endsWith("$annotations"))
+        || (name.endsWith("$default")
+            && methodsWithRetainedBody.contains(name.substring(0, name.length() - 8)))) {
+      if (name.equals("<init>") && (access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC)) == 0) {
+        hasVisibleConstructor = true;
+      }
+
+      return super.visitMethod(access, name, desc, signature, exceptions);
+    }
+
+    // Per JVMS8 2.9, "Class and interface initialization methods are invoked
+    // implicitly by the Java Virtual Machine; they are never invoked directly from any
+    // Java Virtual Machine instruction, but are invoked only indirectly as part of the class
+    // initialization process." Thus we don't need to emit a stub of <clinit>.
+    if (!shouldInclude(access) || (name.equals("<clinit>") && (access & Opcodes.ACC_STATIC) > 0)) {
+      return null;
+    }
+
+    // We don't stub private constructors, but if stripping these constructors results in no
+    // constructors at all, we want to include a default private constructor. This is because
+    // removing all these private methods will make the class look like it has no constructors at
+    // all, which is not possible. We track if this class has a public, non-synthetic constructor
+    // and is not an interface or annotation to determine if a default private constructor is
+    // generated when visitEnd() is called.
+    if (name.equals("<init>") && (access & Opcodes.ACC_SYNTHETIC) == 0) {
+      hasVisibleConstructor = true;
+    }
+
+    // Bridge methods are created by the compiler, and don't appear in source. It would be nice to
+    // skip them, but they're used by the compiler to cover the fact that type erasure has occurred.
+    // Normally the compiler adds these as public methods, but if you're compiling against a stub
+    // produced using our ABI generator, we don't want people calling it accidentally. Oh well, I
+    // guess it happens IRL too.
+    //
+    // Synthetic methods are also generated by the compiler, unless it's one of the methods named in
+    // section 4.7.8 of the JVM spec, which are "<init>" and "Enum.valueOf()" and "Enum.values".
+    // None of these are actually harmful to the ABI, so we allow synthetic methods through.
+    // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.8
+    return new SkipCodeMethodVisitor(
+        Opcodes.ASM9, super.visitMethod(access, name, desc, signature, exceptions));
+  }
+
+  @Override
+  public void visitEnd() {
+    if (!hasVisibleConstructor && !isInterface(classAccess) && !isAnnotation(classAccess)) {
+      String desc;
+      if (isEnum(classAccess)) {
+        desc =
+            Type.getMethodType(
+                    Type.VOID_TYPE, Type.getObjectType("java/lang/String"), Type.INT_TYPE)
+                .getDescriptor();
+      } else {
+        desc =
+            outerName == null
+                ? Type.getMethodType(Type.VOID_TYPE).getDescriptor()
+                : Type.getMethodType(Type.VOID_TYPE, Type.getObjectType(outerName)).getDescriptor();
+      }
+      super.visitMethod(Opcodes.ACC_PRIVATE, "<init>", desc, null, null);
+    }
+
+    // Filter nest members to included inner classes. Other nest members don't matter for ABI
+    // purposes. Even though other members will point to this class as their nest host, this
+    // asymmetry only matters at runtime when access control checks happen.
+    for (String nestMember : nestMembers) {
+      if (includedInnerClasses.contains(nestMember)) {
+        super.visitNestMember(nestMember);
+      }
+    }
+
+    super.visitEnd();
+  }
+
+  private boolean shouldIncludeInnerClass(int access, String name, @Nullable String outerName) {
+    if (referencedClassNames == null || referencedClassNames.contains(name)) {
+      // Either it's the first pass, and we're not filtering inner classes yet,
+      // or it's the second one, and this inner class is part of the ABI and should
+      // therefore be included
+      return true;
+    }
+
+    String currentClassName = Objects.requireNonNull(this.name);
+    if (name.equals(currentClassName)) {
+      // Must always include the entry for our own class, since that's what makes it an inner class.
+      return true;
+    }
+
+    boolean isAnonymousOrLocalClass = (outerName == null);
+    if (isAnonymousOrLocalClass) {
+      // Anonymous and local classes are never part of the ABI.
+      return false;
+    }
+
+    if ((access & (Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE)) == Opcodes.ACC_SYNTHETIC) {
+      // Don't include synthetic classes
+      return false;
+    }
+
+    return currentClassName.equals(outerName);
+  }
+
+  private boolean shouldInclude(int access) {
+    if ((access & Opcodes.ACC_PRIVATE) == Opcodes.ACC_PRIVATE) {
+      return false;
+    }
+
+    int accessFilter = (Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE);
+    if (!isInterface(classAccess) && !isAbstract(classAccess)) {
+      // If this isn't an interface or abstract class, then we can include deprecated methods for
+      // backwards compat.
+      accessFilter |= Opcodes.ACC_DEPRECATED;
+    }
+
+    // for kotlin compilation in some cases when JvmSynthetic annotation is used together with
+    // JvmName
+    // we need to keep the method even if it is synthetic
+    return keepSynthetic || ((access & accessFilter) != Opcodes.ACC_SYNTHETIC);
+  }
+
+  private boolean isInterface(int access) {
+    return (access & Opcodes.ACC_INTERFACE) > 0;
+  }
+
+  private boolean isAbstract(int access) {
+    return (access & Opcodes.ACC_ABSTRACT) > 0;
+  }
+
+  private boolean isAnnotation(int access) {
+    return (access & Opcodes.ACC_ANNOTATION) > 0;
+  }
+
+  private boolean isEnum(int access) {
+    return (access & Opcodes.ACC_ENUM) > 0;
+  }
+
+  /** A {@link MethodVisitor} that replicates the behavior of {@link ClassReader#SKIP_CODE}. */
+  private static class SkipCodeMethodVisitor extends MethodVisitor {
+    public SkipCodeMethodVisitor(int api, MethodVisitor methodVisitor) {
+      super(api, methodVisitor);
+    }
+
+    @Override
+    public void visitAttribute(Attribute attribute) {}
+
+    @Override
+    public void visitCode() {}
+
+    @Override
+    public void visitFrame(int type, int numLocal, Object[] local, int numStack, Object[] stack) {}
+
+    @Override
+    public void visitInsn(int opcode) {}
+
+    @Override
+    public void visitIntInsn(int opcode, int operand) {}
+
+    @Override
+    public void visitVarInsn(int opcode, int var) {}
+
+    @Override
+    public void visitTypeInsn(int opcode, String type) {}
+
+    @Override
+    public void visitFieldInsn(int opcode, String owner, String name, String descriptor) {}
+
+    /**
+     * @deprecated
+     */
+    @Override
+    @Deprecated
+    public void visitMethodInsn(int opcode, String owner, String name, String descriptor) {}
+
+    @Override
+    public void visitMethodInsn(
+        int opcode, String owner, String name, String descriptor, boolean isInterface) {}
+
+    @Override
+    public void visitInvokeDynamicInsn(
+        String name,
+        String descriptor,
+        Handle bootstrapMethodHandle,
+        Object... bootstrapMethodArguments) {}
+
+    @Override
+    public void visitJumpInsn(int opcode, Label label) {}
+
+    @Override
+    public void visitLabel(Label label) {}
+
+    @Override
+    public void visitLdcInsn(Object value) {}
+
+    @Override
+    public void visitIincInsn(int var, int increment) {}
+
+    @Override
+    public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) {}
+
+    @Override
+    public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) {}
+
+    @Override
+    public void visitMultiANewArrayInsn(String descriptor, int numDimensions) {}
+
+    @Override
+    public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {}
+
+    @Override
+    public void visitLocalVariable(
+        String name, String descriptor, String signature, Label start, Label end, int index) {}
+
+    @Override
+    public void visitLineNumber(int line, Label start) {}
+
+    @Override
+    public void visitMaxs(int maxStack, int maxLocals) {}
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AbiGenerationModeUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AbiGenerationModeUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AbiGenerationModeUtils.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+import javax.tools.Diagnostic;
+
+/** Utilities method for {@link AbiGenerationMode} */
+public class AbiGenerationModeUtils {
+
+  private static final Map<AbiGenerationMode, Diagnostic.Kind> DIAGNOSTICS_MAP =
+      ImmutableMap.of(
+          AbiGenerationMode.MIGRATING_TO_SOURCE_ONLY, Diagnostic.Kind.WARNING,
+          AbiGenerationMode.SOURCE_ONLY, Diagnostic.Kind.ERROR);
+
+  private AbiGenerationModeUtils() {}
+
+  public static boolean checkForSourceOnlyAbiCompatibility(AbiGenerationMode abiGenerationMode) {
+    return DIAGNOSTICS_MAP.containsKey(abiGenerationMode);
+  }
+
+  public static Diagnostic.Kind getDiagnosticKindForSourceOnlyAbiCompatibility(
+      AbiGenerationMode abiGenerationMode) {
+    return DIAGNOSTICS_MAP.get(abiGenerationMode);
+  }
+
+  public static boolean isNotClassAbi(AbiGenerationMode abiGenerationMode) {
+    return abiGenerationMode != AbiGenerationMode.CLASS;
+  }
+
+  public static boolean isSourceAbi(AbiGenerationMode abiGenerationMode) {
+    return abiGenerationMode == AbiGenerationMode.SOURCE;
+  }
+
+  public static boolean isSourceOnlyAbi(AbiGenerationMode abiGenerationMode) {
+    return abiGenerationMode == AbiGenerationMode.SOURCE_ONLY;
+  }
+
+  public static boolean usesDependencies(AbiGenerationMode abiGenerationMode) {
+    return abiGenerationMode != AbiGenerationMode.SOURCE_ONLY;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AccessFlags.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AccessFlags.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/AccessFlags.java
@@ -0,0 +1,223 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.jvm.java.abi.source.api.CannotInferException;
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import com.google.common.base.Preconditions;
+import java.util.List;
+import java.util.Set;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.NestingKind;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.util.ElementFilter;
+import org.objectweb.asm.Opcodes;
+
+/** Computes the access flags (see JVMS8 4.1, 4.5, 4.6) for {@link Element}s. */
+public final class AccessFlags {
+  private final ElementsExtended elements;
+
+  public AccessFlags(ElementsExtended elements) {
+    this.elements = elements;
+  }
+
+  /**
+   * Gets the class access flags (see JVMS8 4.1) for the given type element as they should appear in
+   * the ClassNode of a class file. Inner-class specific flags are not allowed in that node,
+   * presumably for compatibility reasons.
+   */
+  public int getAccessFlagsForClassNode(TypeElement e) {
+    // Static never makes it into the file for classes
+    int accessFlags = getAccessFlags(e) & ~Opcodes.ACC_STATIC;
+    if (e.getNestingKind() != NestingKind.TOP_LEVEL) {
+      if (e.getModifiers().contains(Modifier.PROTECTED)) {
+        // It looks like inner classes with protected visibility get marked as public, and then
+        // their InnerClasses attributes override that more specifically
+        accessFlags = (accessFlags & ~Opcodes.ACC_PROTECTED) | Opcodes.ACC_PUBLIC;
+      } else if (e.getModifiers().contains(Modifier.PRIVATE)) {
+        // It looks like inner classes with private visibility get marked as package, and then
+        // their InnerClasses attributes override that more specifically
+        accessFlags = (accessFlags & ~Opcodes.ACC_PRIVATE);
+      }
+    }
+
+    return accessFlags;
+  }
+
+  /**
+   * Gets the class access flags (see JVMS8 4.1) for the given type element, augmented by the
+   * special ASM pseudo-access flag for @Deprecated types.
+   */
+  public int getAccessFlags(TypeElement typeElement) {
+    ElementKind kind;
+    try {
+      kind = typeElement.getKind();
+    } catch (CannotInferException e) {
+      Preconditions.checkState(typeElement.getNestingKind().isNested());
+
+      // We cannot know the access flags of an inferred type element. However, the only
+      // flag that matters in the InnerClasses table is ACC_STATIC. When reading the
+      // InnerClasses table, the compiler may create ClassSymbols for types it hasn't
+      // seen before, and the absence of ACC_STATIC will cause it to mark those
+      // ClassSymbols as inner classes, and it will not correct that when later loading
+      // the class from its definitive class file. However, it is safe to mark
+      // everything with ACC_STATIC, because the compiler *will* properly update
+      // non-static classes when loading their definitive class files.
+      // (http://hg.openjdk.java.net/jdk8u/jdk8u/langtools/file/9986bf97a48d/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java#l2272)
+      return Opcodes.ACC_STATIC;
+    }
+
+    int result = getCommonAccessFlags(typeElement);
+    switch (kind) {
+      case ANNOTATION_TYPE:
+        // No ACC_SUPER here per JVMS 4.1
+        result = result | Opcodes.ACC_ANNOTATION;
+        result = result | Opcodes.ACC_INTERFACE;
+        result = result | Opcodes.ACC_ABSTRACT;
+        break;
+      case ENUM:
+        result = result | Opcodes.ACC_SUPER; // JVMS 4.1
+        result = result | Opcodes.ACC_ENUM;
+
+        if (isAbstractEnum(typeElement)) {
+          result = result & ~Opcodes.ACC_FINAL | Opcodes.ACC_ABSTRACT;
+        }
+        break;
+      case INTERFACE:
+        // No ACC_SUPER here per JVMS 4.1
+        result = result | Opcodes.ACC_ABSTRACT;
+        result = result | Opcodes.ACC_INTERFACE;
+        break;
+      // $CASES-OMITTED$
+      default:
+        result = result | Opcodes.ACC_SUPER; // JVMS 4.1
+        break;
+    }
+
+    return result;
+  }
+
+  private boolean isAbstractEnum(TypeElement typeElement) {
+    List<ExecutableElement> methods = ElementFilter.methodsIn(elements.getAllMembers(typeElement));
+
+    return methods.stream()
+        .filter(
+            it ->
+                !isOverridden(
+                    it, elements.getAllMethods(typeElement, it.getSimpleName()), typeElement))
+        .anyMatch(it -> it.getModifiers().contains(Modifier.ABSTRACT));
+  }
+
+  private boolean isOverridden(
+      ExecutableElement overridden, List<ExecutableElement> methods, TypeElement inType) {
+    for (ExecutableElement overriding : methods) {
+      if (elements.overrides(overriding, overridden, inType)) {
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  /**
+   * Gets the method access flags (see JVMS8 4.6) for the given executable element, augmented by the
+   * special ASM pseudo-access flag for @Deprecated methods.
+   */
+  public int getAccessFlags(ExecutableElement executableElement) {
+    int result = getCommonAccessFlags(executableElement);
+
+    if (executableElement.isVarArgs()) {
+      result = result | Opcodes.ACC_VARARGS;
+    }
+
+    return result;
+  }
+
+  /**
+   * Gets the field access flags (see JVMS8 4.5) for the given variable element, augmented by the
+   * special ASM pseudo-access flag for @Deprecated fields.
+   */
+  public int getAccessFlags(VariableElement variableElement) {
+    int result = getCommonAccessFlags(variableElement);
+
+    if (variableElement.getKind() == ElementKind.ENUM_CONSTANT) {
+      result = result | Opcodes.ACC_ENUM;
+    }
+
+    return result;
+  }
+
+  /**
+   * Gets the access flags (see JVMS8 4.1, 4.5, 4.6) for the given element, from among those that
+   * are common to all kinds of elements.
+   */
+  private int getCommonAccessFlags(Element element) {
+    try {
+      int result = modifiersToAccessFlags(element.getModifiers());
+
+      if (elements.isDeprecated(element)) {
+        result = result | Opcodes.ACC_DEPRECATED;
+      }
+
+      return result;
+    } catch (CannotInferException e) {
+      // We should never call this method with an inferred type.
+      throw new AssertionError("Unexpected call to getAccessFlags with an inferred type.", e);
+    }
+  }
+
+  /**
+   * Gets the access flags (see JVMS8 4.1, 4.5, 4.6) corresponding to the given set of modifiers.
+   */
+  private static int modifiersToAccessFlags(Set<Modifier> modifiers) {
+    int result = 0;
+    for (Modifier modifier : modifiers) {
+      result = result | modifierToAccessFlag(modifier);
+    }
+    return result;
+  }
+
+  /** Gets the access flag (see JVMS8 4.1, 4.5, 4.6) corresponding to the given modifier. */
+  private static int modifierToAccessFlag(Modifier modifier) {
+    switch (modifier) {
+      case PUBLIC:
+        return Opcodes.ACC_PUBLIC;
+      case PROTECTED:
+        return Opcodes.ACC_PROTECTED;
+      case PRIVATE:
+        return Opcodes.ACC_PRIVATE;
+      case ABSTRACT:
+        return Opcodes.ACC_ABSTRACT;
+      case DEFAULT:
+        return 0;
+      case STATIC:
+        return Opcodes.ACC_STATIC;
+      case FINAL:
+        return Opcodes.ACC_FINAL;
+      case TRANSIENT:
+        return Opcodes.ACC_TRANSIENT;
+      case VOLATILE:
+        return Opcodes.ACC_VOLATILE;
+      case SYNCHRONIZED:
+        return Opcodes.ACC_SYNCHRONIZED;
+      case NATIVE:
+        return Opcodes.ACC_NATIVE;
+      case STRICTFP:
+        return Opcodes.ACC_STRICT;
+      default:
+        throw new IllegalArgumentException(String.format("Unexpected modifier: %s", modifier));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ApiStubber.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ApiStubber.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ApiStubber.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+public class ApiStubber {
+
+  private ApiStubber() {
+    // Command line utility.
+  }
+
+  public static void main(String[] args) throws IOException {
+    Path source = Paths.get(args[0]);
+    Path destination = Paths.get(args[1]);
+    boolean keepSynthetic = false;
+
+    if (args.length > 2) {
+      keepSynthetic = args[2].equals("--keep-synthetic");
+    }
+
+    AbsPath workingDirectory = AbsPath.of(Paths.get(".").toAbsolutePath().normalize());
+    AbsPath sourceJar = toAbsPath(source, workingDirectory);
+    AbsPath outputPath = toAbsPath(destination, workingDirectory);
+    new StubJar(sourceJar, keepSynthetic).writeTo(outputPath);
+  }
+
+  private static AbsPath toAbsPath(Path path, AbsPath root) {
+    return path.isAbsolute() ? AbsPath.of(path) : root.resolve(path);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/BUCK
@@ -0,0 +1,93 @@
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library", "buck_prebuilt_artifact", "buck_prebuilt_jar")
+load("@prelude//toolchains/android/tools/build_rules:fb_native.bzl", "fb_native")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "abi",
+    srcs = glob(
+        ["*.java"],
+        exclude = [
+            "ApiStubber.java",
+        ],
+    ),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi:abi",
+    ],
+    versioned_java_srcs = True,
+    visibility = [
+        "prelude//toolchains/android/meta_only/src/com/facebook/buck/jvm/remote_worker/...",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:steps",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main:command_lib",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool:command_lib",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors:postexecutors",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors:postexecutors",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin:kotlin",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api:api",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/lang/extra:extra",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/lang/model:model",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/api:api",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/function:function",
+        "prelude//toolchains/android/third-party:asm",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:infer-annotations",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+    ],
+)
+
+fb_native.alias(
+    name = "api-stubber",
+    actual = ":api-stubber_prebuilt" if is_full_meta_repo() else ":api-stubber-main",
+    visibility = ["PUBLIC"],
+)
+
+buck_java_binary(
+    name = "api-stubber-main",
+    main_class = "com.facebook.buck.jvm.java.abi.ApiStubber",
+    deps = [
+        ":lib-api-stubber",
+    ],
+)
+
+# This is a prebuilt jar so that it can be part of the buck2 bootstrap toolchain.
+buck_prebuilt_jar(
+    name = "api-stubber_prebuilt",
+    _dex_toolchain = "toolchains//:empty_dex",
+    binary_jar = ":api-stubber-main_jar.jar",
+    is_executable = True,
+    should_generate_snapshot = False,
+    visibility = ["PUBLIC"],
+)
+
+# To rebuild the jar and upload it to CAS, do:
+# buck build prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi:api-stubber-main --show-simple-output | xargs frecli --use-case android_build_infra_tools cas upload-blob
+buck_prebuilt_artifact(
+    name = "api-stubber-main_jar.jar",
+    # @oss-disable[end= ]: cas_digest = "3ea4825239cf3cd3afc0a244c6a87c9270c7c0d2ff0ffe6bf2c4ef9292f6fc01:27183911",
+    oss_sha1 = "59b1fcca9ec544a86df64fb544fce3bfcee7eaa8",
+    oss_url = "https://github.com/facebook/buck2/releases/download/androidToolchain%2F2025-04-03/api-stubber-main_jar.jar",
+)
+
+buck_java_library(
+    name = "lib-api-stubber",
+    srcs = ["ApiStubber.java"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        ":abi",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ClassReferenceTracker.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ClassReferenceTracker.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ClassReferenceTracker.java
@@ -0,0 +1,321 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.google.common.collect.ImmutableSortedSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedSet;
+import javax.annotation.Nullable;
+import org.objectweb.asm.AnnotationVisitor;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.FieldVisitor;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.Type;
+import org.objectweb.asm.TypePath;
+import org.objectweb.asm.signature.SignatureReader;
+import org.objectweb.asm.signature.SignatureVisitor;
+import org.objectweb.asm.tree.InnerClassNode;
+
+/**
+ * A {@link ClassVisitor} that records references to other classes. This is intended to be driven by
+ * another {@link ClassVisitor} which is filtering down to just the ABI of the class.
+ */
+class ClassReferenceTracker extends ClassVisitor {
+  private Set<String> referencedClassNames = new HashSet<>();
+  @Nullable private String className;
+
+  private final Map<String, InnerClassNode> innerClasses = new HashMap<>();
+
+  public ClassReferenceTracker() {
+    super(Opcodes.ASM9);
+  }
+
+  public ClassReferenceTracker(ClassVisitor cv) {
+    super(Opcodes.ASM9, cv);
+  }
+
+  public SortedSet<String> getReferencedClassNames() {
+    return ImmutableSortedSet.copyOf(referencedClassNames);
+  }
+
+  @Override
+  public void visitInnerClass(String name, String outerName, String innerName, int access) {
+    if (name.equals(className) && outerName != null) {
+      // If this class is an inner class, its outer class is considered referenced automatically
+      addReferencedClassName(outerName);
+    }
+    innerClasses.put(name, new InnerClassNode(name, outerName, innerName, access));
+    super.visitInnerClass(name, outerName, innerName, access);
+  }
+
+  @Override
+  public void visit(
+      int version,
+      int access,
+      String name,
+      String signature,
+      String superName,
+      String[] interfaces) {
+    className = name;
+    if (superName != null) {
+      addReferencedClassName(superName);
+    }
+    addReferencedClassNames(interfaces);
+    visitSignature(signature);
+
+    super.visit(version, access, name, signature, superName, interfaces);
+  }
+
+  @Override
+  public void visitEnd() {
+    // If we reference inner classes, we must also reference their outer class(es).
+    Set<String> newSet = new HashSet<>();
+    for (String referencedClassName : referencedClassNames) {
+      newSet.add(referencedClassName);
+      InnerClassNode innerClassNode = innerClasses.get(referencedClassName);
+      while (innerClassNode != null) {
+        newSet.add(innerClassNode.name);
+        innerClassNode = innerClasses.get(innerClassNode.outerName);
+      }
+    }
+    referencedClassNames = newSet;
+    super.visitEnd();
+  }
+
+  @Override
+  public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
+    visitDescriptor(desc);
+    return new TrackingAnnotationVisitor(api, super.visitAnnotation(desc, visible));
+  }
+
+  @Override
+  public AnnotationVisitor visitTypeAnnotation(
+      int typeRef, TypePath typePath, String desc, boolean visible) {
+    visitDescriptor(desc);
+    return new TrackingAnnotationVisitor(
+        api, super.visitTypeAnnotation(typeRef, typePath, desc, visible));
+  }
+
+  @Override
+  public FieldVisitor visitField(
+      int access, String name, String desc, String signature, Object value) {
+    if ((access & Opcodes.ACC_ENUM) != 0) {
+      // Enum values don't count as references
+      return super.visitField(access, name, desc, signature, value);
+    }
+
+    visitDescriptor(desc);
+    visitSignature(signature);
+
+    return new TrackingFieldVisitor(api, super.visitField(access, name, desc, signature, value));
+  }
+
+  @Override
+  public MethodVisitor visitMethod(
+      int access, String name, String desc, String signature, String[] exceptions) {
+    visitType(Type.getMethodType(desc));
+    visitSignature(signature);
+    addReferencedClassNames(exceptions);
+
+    return new TrackingMethodVisitor(
+        api, super.visitMethod(access, name, desc, signature, exceptions));
+  }
+
+  void visitDescriptor(String desc) {
+    visitType(Type.getType(desc));
+  }
+
+  private void visitTypes(Type[] types) {
+    for (Type type : types) {
+      visitType(type);
+    }
+  }
+
+  private void visitType(Type type) {
+    switch (type.getSort()) {
+      case Type.ARRAY:
+        visitType(type.getElementType());
+        break;
+      case Type.METHOD:
+        visitType(type.getReturnType());
+        visitTypes(type.getArgumentTypes());
+        break;
+      case Type.OBJECT:
+        addReferencedClassName(type.getInternalName());
+        break;
+      // $CASES-OMITTED
+      default:
+        // Others are primitives or void; don't care
+        break;
+    }
+  }
+
+  void addReferencedClassName(String className) {
+    referencedClassNames.add(className);
+  }
+
+  void addReferencedClassNames(@Nullable String[] classNames) {
+    if (classNames == null) {
+      return;
+    }
+
+    for (String className : classNames) {
+      addReferencedClassName(className);
+    }
+  }
+
+  private void visitSignature(@Nullable String signature) {
+    if (signature == null) {
+      return;
+    }
+
+    SignatureReader reader = new SignatureReader(signature);
+    reader.accept(new TrackingSignatureVisitor(api));
+  }
+
+  private class TrackingMethodVisitor extends MethodVisitor {
+    public TrackingMethodVisitor(int api, MethodVisitor mv) {
+      super(api, mv);
+    }
+
+    @Override
+    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
+      visitDescriptor(desc);
+      return new TrackingAnnotationVisitor(api, super.visitAnnotation(desc, visible));
+    }
+
+    @Override
+    public AnnotationVisitor visitTypeAnnotation(
+        int typeRef, TypePath typePath, String desc, boolean visible) {
+      visitDescriptor(desc);
+      return new TrackingAnnotationVisitor(
+          api, super.visitTypeAnnotation(typeRef, typePath, desc, visible));
+    }
+
+    @Override
+    public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) {
+      visitDescriptor(desc);
+      return new TrackingAnnotationVisitor(
+          api, super.visitParameterAnnotation(parameter, desc, visible));
+    }
+  }
+
+  private class TrackingFieldVisitor extends FieldVisitor {
+    public TrackingFieldVisitor(int api, FieldVisitor fv) {
+      super(api, fv);
+    }
+
+    @Override
+    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
+      visitDescriptor(desc);
+      return new TrackingAnnotationVisitor(api, super.visitAnnotation(desc, visible));
+    }
+
+    @Override
+    public AnnotationVisitor visitTypeAnnotation(
+        int typeRef, TypePath typePath, String desc, boolean visible) {
+      visitDescriptor(desc);
+      return new TrackingAnnotationVisitor(
+          api, super.visitTypeAnnotation(typeRef, typePath, desc, visible));
+    }
+  }
+
+  private class TrackingAnnotationVisitor extends AnnotationVisitor {
+    public TrackingAnnotationVisitor(int api, AnnotationVisitor av) {
+      super(api, av);
+    }
+
+    @Override
+    public void visit(String name, Object value) {
+      if (value instanceof Type) {
+        visitDescriptor(((Type) value).getDescriptor());
+      }
+      super.visit(name, value);
+    }
+
+    @Override
+    public void visitEnum(String name, String desc, String value) {
+      visitDescriptor(desc);
+      super.visitEnum(name, desc, value);
+    }
+
+    @Override
+    public AnnotationVisitor visitArray(String name) {
+      return new TrackingAnnotationVisitor(api, super.visitArray(name));
+    }
+
+    @Override
+    public AnnotationVisitor visitAnnotation(String name, String desc) {
+      visitDescriptor(desc);
+      return new TrackingAnnotationVisitor(api, super.visitAnnotation(name, desc));
+    }
+  }
+
+  private class TrackingSignatureVisitor extends SignatureVisitor {
+    public TrackingSignatureVisitor(int api) {
+      super(api);
+    }
+
+    @Override
+    public SignatureVisitor visitClassBound() {
+      return this;
+    }
+
+    @Override
+    public SignatureVisitor visitInterfaceBound() {
+      return this;
+    }
+
+    @Override
+    public SignatureVisitor visitSuperclass() {
+      return this;
+    }
+
+    @Override
+    public SignatureVisitor visitInterface() {
+      return this;
+    }
+
+    @Override
+    public SignatureVisitor visitParameterType() {
+      return this;
+    }
+
+    @Override
+    public SignatureVisitor visitReturnType() {
+      return this;
+    }
+
+    @Override
+    public SignatureVisitor visitExceptionType() {
+      return this;
+    }
+
+    @Override
+    public SignatureVisitor visitArrayType() {
+      return this;
+    }
+
+    @Override
+    public void visitClassType(String name) {
+      addReferencedClassName(name);
+    }
+
+    @Override
+    public SignatureVisitor visitTypeArgument(char wildcard) {
+      return this;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ClassVisitorDriverFromElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ClassVisitorDriverFromElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ClassVisitorDriverFromElement.java
@@ -0,0 +1,538 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.jvm.java.abi.source.api.CannotInferException;
+import com.facebook.buck.jvm.java.lang.extra.MoreTypeAnnotations;
+import com.facebook.buck.jvm.java.lang.model.BridgeMethod;
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import com.facebook.buck.jvm.java.lang.model.MoreElements;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.Multimap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import javax.annotation.Nullable;
+import javax.annotation.processing.Messager;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.ExecutableType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.ElementScanner8;
+import javax.lang.model.util.SimpleAnnotationValueVisitor8;
+import javax.lang.model.util.Types;
+import javax.tools.Diagnostic.Kind;
+import org.objectweb.asm.AnnotationVisitor;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.FieldVisitor;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.TypePath;
+import org.objectweb.asm.TypeReference;
+
+class ClassVisitorDriverFromElement {
+
+  private final DescriptorFactory descriptorFactory;
+  private final Messager messager;
+  private final SignatureFactory signatureFactory;
+  private final SourceVersion targetVersion;
+  private final ElementsExtended elements;
+  private final Types types;
+  private final AccessFlags accessFlagsUtils;
+  private final boolean includeParameterMetadata;
+
+  /**
+   * @param targetVersion the class file version to target, expressed as the corresponding Java
+   *     source version
+   */
+  ClassVisitorDriverFromElement(
+      SourceVersion targetVersion,
+      ElementsExtended elements,
+      Messager messager,
+      Types types,
+      boolean includeParameterMetadata) {
+    this.targetVersion = targetVersion;
+    this.elements = elements;
+    descriptorFactory = new DescriptorFactory(elements);
+    this.messager = messager;
+    this.types = types;
+    // TODO: Fully remove includeParameterMetadata. This feature is no longer needed and wasn't
+    // fully supported during the Jacoco 0.8.7 upgrade.
+    this.includeParameterMetadata = includeParameterMetadata;
+    signatureFactory = new SignatureFactory(descriptorFactory);
+    accessFlagsUtils = new AccessFlags(elements);
+  }
+
+  public void driveVisitor(Element fullElement, ClassVisitor visitor) {
+    fullElement.accept(new ElementVisitorAdapter(), visitor);
+    visitor.visitEnd();
+  }
+
+  private interface VisitorWithAnnotations {
+
+    AnnotationVisitor visitAnnotation(String desc, boolean visible);
+  }
+
+  private interface VisitorWithTypeAnnotations {
+
+    AnnotationVisitor visitTypeAnnotation(
+        final int typeRef, final TypePath typePath, final String descriptor, final boolean visible);
+  }
+
+  private class ElementVisitorAdapter extends ElementScanner8<Void, ClassVisitor> {
+
+    boolean classVisitorStarted = false;
+
+    @Override
+    public Void visitPackage(PackageElement e, ClassVisitor classVisitor) {
+      classVisitor.visit(
+          SourceVersionUtils.sourceVersionToClassFileVersion(targetVersion),
+          Opcodes.ACC_SYNTHETIC | Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE,
+          e.getQualifiedName().toString().replace('.', '/') + "/package-info",
+          null,
+          "java/lang/Object",
+          new String[0]);
+
+      visitAnnotations(e, classVisitor::visitAnnotation);
+
+      new InnerClassesTable(descriptorFactory, accessFlagsUtils, elements, e)
+          .reportInnerClassReferences(classVisitor);
+
+      classVisitor.visitEnd();
+
+      return null;
+    }
+
+    @Override
+    public Void visitType(TypeElement e, ClassVisitor visitor) {
+      if (classVisitorStarted) {
+        // We'll get inner class references later
+        return null;
+      }
+
+      TypeMirror superclass = e.getSuperclass();
+      if (superclass.getKind() == TypeKind.NONE) {
+        superclass = Objects.requireNonNull(elements.getTypeElement("java.lang.Object")).asType();
+      }
+
+      int classFileVersion = SourceVersionUtils.sourceVersionToClassFileVersion(targetVersion);
+      visitor.visit(
+          classFileVersion,
+          accessFlagsUtils.getAccessFlagsForClassNode(e),
+          descriptorFactory.getInternalName(e),
+          signatureFactory.getSignature(e),
+          descriptorFactory.getInternalName(superclass),
+          e.getInterfaces().stream()
+              .map(descriptorFactory::getInternalName)
+              .toArray(String[]::new));
+      classVisitorStarted = true;
+
+      // Handle nests in Java 11+. See JEP 181 (https://openjdk.java.net/jeps/181) for details.
+      if (classFileVersion >= Opcodes.V11) {
+        if (e.getNestingKind().isNested()) {
+          visitNestHost(e, visitor);
+        } else {
+          visitNestMembers(e, visitor);
+        }
+      }
+
+      visitAnnotations(e, visitor::visitAnnotation);
+      visitTypeAnnotations(e, visitor::visitTypeAnnotation);
+
+      super.visitType(e, visitor);
+
+      InnerClassesTable innerClassesTable =
+          new InnerClassesTable(descriptorFactory, accessFlagsUtils, elements, e);
+      if (e.getKind().isClass() || classFileVersion >= Opcodes.V1_8) {
+        try {
+          generateBridges(e, visitor, innerClassesTable);
+        } catch (UnsupportedOperationException | CannotInferException ex) { // NOPMD
+          // Can't generate bridges in source-only mode
+        }
+      }
+
+      innerClassesTable.reportInnerClassReferences(visitor);
+
+      return null;
+    }
+
+    private void visitNestHost(TypeElement e, ClassVisitor visitor) {
+      TypeElement nestHost = e;
+      while (nestHost.getNestingKind().isNested()) {
+        nestHost = (TypeElement) nestHost.getEnclosingElement();
+      }
+
+      visitor.visitNestHost(descriptorFactory.getInternalName(nestHost));
+    }
+
+    private void visitNestMembers(TypeElement e, ClassVisitor visitor) {
+      if (e.getNestingKind().isNested()) {
+        visitor.visitNestMember(descriptorFactory.getInternalName(e));
+      }
+
+      for (Element child : e.getEnclosedElements()) {
+        if (child.getKind().isClass() || child.getKind().isInterface()) {
+          visitNestMembers((TypeElement) child, visitor);
+        }
+      }
+    }
+
+    private void generateBridges(
+        TypeElement subclass, ClassVisitor visitor, InnerClassesTable innerClassesTable) {
+      new BridgeBuilder(subclass, visitor, innerClassesTable).generateBridges();
+    }
+
+    /** Creates bridge methods in a given subclass as needed. */
+    private class BridgeBuilder {
+
+      private final TypeElement subclass;
+      private final ClassVisitor visitor;
+      private final InnerClassesTable innerClassesTable;
+      private final Multimap<Name, String> bridgedDescriptors = HashMultimap.create();
+
+      private BridgeBuilder(
+          TypeElement subclass, ClassVisitor visitor, InnerClassesTable innerClassesTable) {
+        this.subclass = subclass;
+        this.visitor = visitor;
+        this.innerClassesTable = innerClassesTable;
+      }
+
+      public void generateBridges() {
+        for (BridgeMethod bridgeMethod : elements.getAllBridgeMethods(subclass)) {
+          generateBridge(bridgeMethod.from, bridgeMethod.to);
+        }
+      }
+
+      private void generateBridge(ExecutableElement fromMethod, ExecutableElement toMethod) {
+        ExecutableType toErasure = (ExecutableType) types.erasure(toMethod.asType());
+        String bridgeDescriptor = descriptorFactory.getDescriptor(toErasure);
+        if (bridgedDescriptors.get(toMethod.getSimpleName()).contains(bridgeDescriptor)) {
+          return;
+        }
+
+        innerClassesTable.addTypeReferences(toErasure);
+
+        String[] exceptions =
+            toErasure.getThrownTypes().stream()
+                .map(descriptorFactory::getInternalName)
+                .toArray(String[]::new);
+
+        MethodVisitor methodVisitor =
+            visitor.visitMethod(
+                getBridgeAccessFlags(fromMethod),
+                toMethod.getSimpleName().toString(),
+                bridgeDescriptor,
+                signatureFactory.getSignature(toErasure),
+                exceptions);
+        if (methodVisitor != null) {
+          List<? extends VariableElement> fromMethodParameters = fromMethod.getParameters();
+          for (int i = 0; i < fromMethodParameters.size(); i++) {
+            VariableElement fromMethodParameter = fromMethodParameters.get(i);
+            List<? extends AnnotationMirror> annotations =
+                fromMethodParameter.getAnnotationMirrors();
+            innerClassesTable.addTypeReferences(annotations);
+            visitParameter(
+                i,
+                fromMethodParameter,
+                fromMethodParameter.getSimpleName(),
+                accessFlagsUtils.getAccessFlags(fromMethodParameter) | Opcodes.ACC_SYNTHETIC,
+                annotations,
+                methodVisitor);
+          }
+          innerClassesTable.addTypeReferences(fromMethod.getAnnotationMirrors());
+          visitAnnotations(fromMethod, methodVisitor::visitAnnotation);
+          methodVisitor.visitEnd();
+
+          bridgedDescriptors.put(toMethod.getSimpleName(), bridgeDescriptor);
+        }
+      }
+
+      private int getBridgeAccessFlags(ExecutableElement method) {
+        return accessFlagsUtils.getAccessFlags(method)
+                & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE)
+            | Opcodes.ACC_SYNTHETIC
+            | Opcodes.ACC_BRIDGE;
+      }
+    }
+
+    @Override
+    public Void visitExecutable(ExecutableElement e, ClassVisitor visitor) {
+      if (e.getModifiers().contains(Modifier.PRIVATE)) {
+        return null;
+      }
+
+      String[] exceptions =
+          e.getThrownTypes().stream()
+              .map(descriptorFactory::getInternalName)
+              .toArray(String[]::new);
+
+      MethodVisitor methodVisitor =
+          visitor.visitMethod(
+              accessFlagsUtils.getAccessFlags(e),
+              e.getSimpleName().toString(),
+              descriptorFactory.getDescriptor(e),
+              signatureFactory.getSignature(e),
+              exceptions);
+
+      if (methodVisitor != null) {
+        visitParameters(e.getParameters(), methodVisitor, MoreElements.isInnerClassConstructor(e));
+        visitDefaultValue(e, methodVisitor);
+        visitAnnotations(e, methodVisitor::visitAnnotation);
+        visitTypeAnnotations(e, methodVisitor::visitTypeAnnotation);
+        methodVisitor.visitEnd();
+      }
+
+      return null;
+    }
+
+    private void visitParameters(
+        List<? extends VariableElement> parameters,
+        MethodVisitor methodVisitor,
+        boolean isInnerClassConstructor) {
+      for (int i = 0; i < parameters.size(); i++) {
+        VariableElement parameter = parameters.get(i);
+        visitParameter(
+            i,
+            parameter,
+            parameter.getSimpleName(),
+            accessFlagsUtils.getAccessFlags(parameter),
+            parameter.getAnnotationMirrors(),
+            methodVisitor);
+      }
+      if (isInnerClassConstructor) {
+        // As of ASM 6.1, ASM no longer attempts to map bytecode parameter indices to source level
+        // parameter indices for parameter annotations. To maintain binary compatibility with class
+        // ABI jars, we override the default behavior of emitting a
+        // Runtime[In]VisibleParameterAnnotations entry (even if empty) for all parameters in the
+        // method descriptor, including synthetic ones. Note that the <code>parameters</code> list
+        // here does not include synthetic parameters. See comment in <code>visitParameter</code>.
+        // See https://gitlab.ow2.org/asm/asm/merge_requests/56 for more details.
+        methodVisitor.visitAnnotableParameterCount(parameters.size(), false);
+        methodVisitor.visitAnnotableParameterCount(parameters.size(), true);
+      }
+    }
+
+    private void visitParameter(
+        int index,
+        VariableElement parameter,
+        Name name,
+        int access,
+        List<? extends AnnotationMirror> annotationMirrors,
+        MethodVisitor methodVisitor) {
+      if (includeParameterMetadata) {
+        methodVisitor.visitParameter(name.toString(), access);
+      }
+
+      for (AnnotationMirror annotationMirror : annotationMirrors) {
+        try {
+          if (MoreElements.isSourceRetention(annotationMirror)) {
+            continue;
+          }
+        } catch (CannotInferException e) {
+          reportMissingAnnotationType(parameter, annotationMirror);
+          continue;
+        }
+        // Note: We purposely don't attempt to remap source level parameter indices to bytecode
+        //       parameter indices here when we have a synthetic first parameter for an inner class
+        //       constructor, as this would cause ASM to emit an empty parameter annotation entry
+        //       for the synthetic parameter. See comment in <code>visitParameters</code>.
+        visitAnnotationValues(
+            annotationMirror,
+            methodVisitor.visitParameterAnnotation(
+                index,
+                descriptorFactory.getDescriptor(annotationMirror.getAnnotationType()),
+                MoreElements.isRuntimeRetention(annotationMirror)));
+      }
+    }
+
+    private void reportMissingAnnotationType(Element element, AnnotationMirror annotationMirror) {
+      DeclaredType annotationType = annotationMirror.getAnnotationType();
+      messager.printMessage(
+          Kind.ERROR,
+          String.format(
+              "Could not find the annotation %1$s.\n"
+                  + "This can happen for one of two reasons:\n"
+                  + "1. A dependency is missing in the BUCK file for the current target. "
+                  + "Try building the current rule without the #source-only-abi flavor, "
+                  + "fix any errors that are reported, and then build this flavor again.\n"
+                  + "2. The rule that owns %1$s is not marked with "
+                  + "required_for_source_only_abi = True. Add that parameter to the rule and try "
+                  + "again.",
+              annotationType),
+          element,
+          annotationMirror);
+    }
+
+    private void visitDefaultValue(ExecutableElement e, MethodVisitor methodVisitor) {
+      AnnotationValue defaultValue = e.getDefaultValue();
+      if (defaultValue == null) {
+        return;
+      }
+
+      AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotationDefault();
+      visitAnnotationValue(null, defaultValue, annotationVisitor);
+      annotationVisitor.visitEnd();
+    }
+
+    @Override
+    public Void visitVariable(VariableElement e, ClassVisitor classVisitor) {
+      if (e.getModifiers().contains(Modifier.PRIVATE)) {
+        return null;
+      }
+
+      FieldVisitor fieldVisitor =
+          classVisitor.visitField(
+              accessFlagsUtils.getAccessFlags(e),
+              e.getSimpleName().toString(),
+              descriptorFactory.getDescriptor(e),
+              signatureFactory.getSignature(e),
+              e.getConstantValue());
+      visitAnnotations(e, fieldVisitor::visitAnnotation);
+      visitTypeAnnotations(e, fieldVisitor::visitTypeAnnotation);
+      fieldVisitor.visitEnd();
+
+      return null;
+    }
+
+    private void visitAnnotations(Element enclosingElement, VisitorWithAnnotations visitor) {
+      enclosingElement
+          .getAnnotationMirrors()
+          .forEach(annotation -> visitAnnotation(enclosingElement, annotation, visitor));
+    }
+
+    private void visitAnnotation(
+        Element enclosingElement, AnnotationMirror annotation, VisitorWithAnnotations visitor) {
+      try {
+        if (MoreElements.isSourceRetention(annotation)) {
+          return;
+        }
+        AnnotationVisitor annotationVisitor =
+            visitor.visitAnnotation(
+                descriptorFactory.getDescriptor(annotation.getAnnotationType()),
+                MoreElements.isRuntimeRetention(annotation));
+        visitAnnotationValues(annotation, annotationVisitor);
+        annotationVisitor.visitEnd();
+      } catch (CannotInferException e) {
+        reportMissingAnnotationType(enclosingElement, annotation);
+      }
+    }
+
+    private void visitTypeAnnotations(Element element, VisitorWithTypeAnnotations visitor) {
+      List<? extends AnnotationMirror> typeAnnotations = elements.getAllTypeAnnotations(element);
+
+      for (AnnotationMirror annotation : typeAnnotations) {
+        visitTypeAnnotation(element, annotation, visitor);
+      }
+    }
+
+    private void visitTypeAnnotation(
+        Element enclosingElement, AnnotationMirror annotation, VisitorWithTypeAnnotations visitor) {
+      try {
+        if (MoreElements.isSourceRetention(annotation)) {
+          return;
+        }
+        TypeReference typeRef = MoreTypeAnnotations.getAnnotationTypeReference(annotation);
+        if (typeRef == null) {
+          return;
+        }
+
+        AnnotationVisitor annotationVisitor =
+            visitor.visitTypeAnnotation(
+                typeRef.getValue(),
+                MoreTypeAnnotations.getAnnotationTypePath(annotation),
+                descriptorFactory.getDescriptor(annotation.getAnnotationType()),
+                MoreElements.isRuntimeRetention(annotation));
+        visitAnnotationValues(annotation, annotationVisitor);
+        annotationVisitor.visitEnd();
+      } catch (CannotInferException e) {
+        reportMissingAnnotationType(enclosingElement, annotation);
+      }
+    }
+
+    private void visitAnnotationValues(
+        AnnotationMirror annotation, AnnotationVisitor annotationVisitor) {
+      visitAnnotationValues(annotation.getElementValues(), annotationVisitor);
+    }
+
+    private void visitAnnotationValues(
+        Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues,
+        AnnotationVisitor visitor) {
+      elementValues.forEach(
+          (key, value) -> visitAnnotationValue(key.getSimpleName().toString(), value, visitor));
+    }
+
+    private void visitAnnotationValue(
+        @Nullable String name, AnnotationValue value, AnnotationVisitor visitor) {
+      value.accept(new AnnotationVisitorAdapter(name, visitor), null);
+    }
+
+    private class AnnotationVisitorAdapter extends SimpleAnnotationValueVisitor8<Void, Void> {
+
+      @Nullable private final String name;
+      private final AnnotationVisitor visitor;
+
+      private AnnotationVisitorAdapter(@Nullable String name, AnnotationVisitor visitor) {
+        this.name = name;
+        this.visitor = visitor;
+      }
+
+      @Override
+      protected Void defaultAction(Object value, Void aVoid) {
+        visitor.visit(name, value);
+        return null;
+      }
+
+      @Override
+      public Void visitType(TypeMirror value, Void aVoid) {
+        visitor.visit(name, descriptorFactory.getType(value));
+        return null;
+      }
+
+      @Override
+      public Void visitEnumConstant(VariableElement value, Void aVoid) {
+        visitor.visitEnum(
+            name,
+            descriptorFactory.getDescriptor(value.getEnclosingElement().asType()),
+            value.getSimpleName().toString());
+        return null;
+      }
+
+      @Override
+      public Void visitAnnotation(AnnotationMirror value, Void aVoid) {
+        AnnotationVisitor annotationValueVisitor =
+            visitor.visitAnnotation(
+                name, descriptorFactory.getDescriptor(value.getAnnotationType()));
+        visitAnnotationValues(value, annotationValueVisitor);
+        annotationValueVisitor.visitEnd();
+        return null;
+      }
+
+      @Override
+      public Void visitArray(List<? extends AnnotationValue> listValue, Void aVoid) {
+        AnnotationVisitor arrayMemberVisitor = visitor.visitArray(name);
+        listValue.forEach(
+            annotationValue -> visitAnnotationValue(null, annotationValue, arrayMemberVisitor));
+        arrayMemberVisitor.visitEnd();
+        return null;
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/DescriptorFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/DescriptorFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/DescriptorFactory.java
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.jvm.java.lang.model.MoreElements;
+import java.util.Objects;
+import java.util.stream.Stream;
+import javax.annotation.Nullable;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.ArrayType;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.ErrorType;
+import javax.lang.model.type.ExecutableType;
+import javax.lang.model.type.IntersectionType;
+import javax.lang.model.type.NoType;
+import javax.lang.model.type.PrimitiveType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.SimpleElementVisitor8;
+import javax.lang.model.util.SimpleTypeVisitor8;
+import org.objectweb.asm.Type;
+
+/** Computes type descriptors from {@link Element}s or {@link TypeMirror}s. */
+class DescriptorFactory {
+  private final Elements elements;
+
+  public DescriptorFactory(Elements elements) {
+    this.elements = elements;
+  }
+
+  public String getDescriptor(TypeMirror type) {
+    return getType(type).getDescriptor();
+  }
+
+  @Nullable
+  public String getDescriptor(Element element) {
+    ElementKind kind = element.getKind();
+    if (kind.isClass() || kind.isInterface()) {
+      return null;
+    }
+    return getType(element).getDescriptor();
+  }
+
+  private Type getType(Element element) {
+    return Objects.requireNonNull(
+        element.accept(
+            new SimpleElementVisitor8<Type, Void>() {
+              @Override
+              protected Type defaultAction(Element e, Void aVoid) {
+                throw new IllegalArgumentException(
+                    String.format("Unexpected element kind: %s", element.getKind()));
+              }
+
+              @Override
+              public Type visitExecutable(ExecutableElement e, Void aVoid) {
+                Stream<TypeMirror> parameterTypeStream =
+                    e.getParameters().stream().map(Element::asType);
+
+                if (MoreElements.isInnerClassConstructor(e)) {
+                  parameterTypeStream =
+                      Stream.concat(
+                          Stream.of(MoreElements.getOuterClass(e).asType()), parameterTypeStream);
+                }
+
+                return Type.getMethodType(
+                    getType(e.getReturnType()),
+                    parameterTypeStream.map(DescriptorFactory.this::getType).toArray(Type[]::new));
+              }
+
+              @Override
+              public Type visitVariable(VariableElement e, Void aVoid) {
+                return getType(e.asType());
+              }
+            },
+            null));
+  }
+
+  public Type getType(TypeMirror typeMirror) {
+    return Objects.requireNonNull(
+        typeMirror.accept(
+            new SimpleTypeVisitor8<Type, Void>() {
+              @Override
+              protected Type defaultAction(TypeMirror t, Void aVoid) {
+                throw new IllegalArgumentException(
+                    String.format("Unexpected type kind: %s", t.getKind()));
+              }
+
+              @Override
+              public Type visitExecutable(ExecutableType e, Void aVoid) {
+                Stream<? extends TypeMirror> parameterTypeStream = e.getParameterTypes().stream();
+
+                return Type.getMethodType(
+                    getType(e.getReturnType()),
+                    parameterTypeStream.map(DescriptorFactory.this::getType).toArray(Type[]::new));
+              }
+
+              @Override
+              public Type visitPrimitive(PrimitiveType type, Void aVoid) {
+                switch (type.getKind()) {
+                  case BOOLEAN:
+                    return Type.BOOLEAN_TYPE;
+                  case BYTE:
+                    return Type.BYTE_TYPE;
+                  case CHAR:
+                    return Type.CHAR_TYPE;
+                  case SHORT:
+                    return Type.SHORT_TYPE;
+                  case INT:
+                    return Type.INT_TYPE;
+                  case LONG:
+                    return Type.LONG_TYPE;
+                  case FLOAT:
+                    return Type.FLOAT_TYPE;
+                  case DOUBLE:
+                    return Type.DOUBLE_TYPE;
+                  // $CASES-OMITTED$
+                  default:
+                    throw new IllegalArgumentException(
+                        String.format("Unexpected type kind: %s", type.getKind()));
+                }
+              }
+
+              @Override
+              public Type visitNoType(NoType t, Void aVoid) {
+                if (t.getKind() != TypeKind.VOID) {
+                  throw new IllegalArgumentException(
+                      String.format("Unexpected type kind: %s", t.getKind()));
+                }
+
+                return Type.VOID_TYPE;
+              }
+
+              @Override
+              public Type visitArray(ArrayType t, Void aVoid) {
+                return Type.getObjectType("[" + getDescriptor(t.getComponentType()));
+              }
+
+              @Override
+              public Type visitDeclared(DeclaredType t, Void aVoid) {
+                // The erasure of a parameterized type is just the unparameterized version (JLS8
+                // 4.6)
+                TypeElement typeElement = (TypeElement) t.asElement();
+
+                if (typeElement.getQualifiedName().contentEquals("")) {
+                  // javac 7 uses a DeclaredType to model an intersection type
+                  if (typeElement.getKind() == ElementKind.INTERFACE) {
+                    return getType(typeElement.getInterfaces().get(0));
+                  }
+
+                  return getType(typeElement.getSuperclass());
+                }
+
+                return Type.getObjectType(getInternalName(typeElement));
+              }
+
+              @Override
+              public Type visitError(ErrorType t, Void aVoid) {
+                // If there's an ErrorType, compilation is going to fail anyway, so it doesn't
+                // matter what we return.
+                return Type.getObjectType("java/lang/Object");
+              }
+
+              @Override
+              public Type visitTypeVariable(TypeVariable t, Void aVoid) {
+                // The erasure of a type variable is the erasure of its leftmost bound (JLS8 4.6)
+                // If there's only one bound, getUpperBound returns it directly; if there's more
+                // than
+                // one it returns an IntersectionType
+                return getType(t.getUpperBound());
+              }
+
+              @Override
+              public Type visitIntersection(IntersectionType t, Void aVoid) {
+                // The erasure of a type variable is the erasure of its leftmost bound (JLS8 4.6)
+                return getType(t.getBounds().get(0));
+              }
+            },
+            null));
+  }
+
+  /** Gets the internal form of the binary name; see JVMS8 4.2.1 */
+  public String getInternalName(TypeMirror typeMirror) {
+    return getType(typeMirror).getInternalName();
+  }
+
+  /** Gets the internal form of the binary name; see JVMS8 4.2.1 */
+  public String getInternalName(TypeElement typeElement) {
+    return elements.getBinaryName(typeElement).toString().replace('.', '/');
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/DirectoryReader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/DirectoryReader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/DirectoryReader.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassVisitor;
+
+/** A {@link LibraryReader} that reads from a directory (recursively). */
+class DirectoryReader implements LibraryReader {
+  private final Path root;
+
+  public DirectoryReader(Path root) {
+    this.root = root;
+  }
+
+  @Override
+  public List<Path> getRelativePaths() throws IOException {
+    try (Stream<Path> paths = Files.walk(root)) {
+      return paths
+          .filter(path -> !Files.isDirectory(path))
+          .map(root::relativize)
+          .collect(Collectors.toList());
+    }
+  }
+
+  @Override
+  public InputStream openResourceFile(Path relativePath) throws IOException {
+    if (!isResource(relativePath)) {
+      throw new IllegalArgumentException();
+    }
+    return openInputStream(relativePath);
+  }
+
+  @Override
+  public void visitClass(Path relativePath, ClassVisitor cv, boolean skipCode) throws IOException {
+    if (!isClass(relativePath)) {
+      throw new IllegalArgumentException();
+    }
+
+    int parsingOptions = ClassReader.SKIP_FRAMES;
+    if (skipCode) {
+      parsingOptions |= ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE;
+    }
+
+    try (InputStream inputStream = openInputStream(relativePath)) {
+      ClassReader reader = new ClassReader(inputStream);
+      reader.accept(cv, parsingOptions);
+    }
+  }
+
+  @Override
+  public void close() {
+    // Nothing in particular needed
+  }
+
+  @Override
+  public InputStream openInputStream(Path relativePath) throws IOException {
+    return new BufferedInputStream(Files.newInputStream(root.resolve(relativePath)));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ElementsReader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ElementsReader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/ElementsReader.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import com.facebook.buck.util.MoreSuppliers;
+import java.io.File;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Supplier;
+import javax.annotation.processing.Messager;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.Types;
+import org.objectweb.asm.ClassVisitor;
+
+/** A {@link LibraryReader} that reads from a list of {@link Element}s and their inner types. */
+class ElementsReader implements LibraryReader {
+  private final SourceVersion targetVersion;
+  private final ElementsExtended elements;
+  private final Types types;
+  private final Messager messager;
+  private final Supplier<Map<Path, Element>> allElements;
+  private final boolean includeParameterMetadata;
+
+  ElementsReader(
+      SourceVersion targetVersion,
+      ElementsExtended elements,
+      Types types,
+      Messager messager,
+      Iterable<Element> topLevelElements,
+      boolean includeParameterMetadata) {
+    this.targetVersion = targetVersion;
+    this.elements = elements;
+    this.types = types;
+    this.messager = messager;
+    this.allElements =
+        MoreSuppliers.memoize(
+            () -> {
+              Map<Path, Element> allElements = new LinkedHashMap<>();
+              topLevelElements.forEach(element -> addAllElements(element, allElements));
+              return allElements;
+            });
+    this.includeParameterMetadata = includeParameterMetadata;
+  }
+
+  @Override
+  public List<Path> getRelativePaths() {
+    return new ArrayList<>(allElements.get().keySet());
+  }
+
+  @Override
+  public InputStream openResourceFile(Path relativePath) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public InputStream openInputStream(Path relativePath) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public void visitClass(Path relativePath, ClassVisitor cv, boolean skipCodeUnused) {
+    Element element = Objects.requireNonNull(allElements.get().get(relativePath));
+    new ClassVisitorDriverFromElement(
+            targetVersion, elements, messager, types, includeParameterMetadata)
+        .driveVisitor(element, cv);
+  }
+
+  @Override
+  public void close() {
+    // Nothing
+  }
+
+  private void addAllElements(Element rootElement, Map<Path, Element> elements) {
+    if (rootElement.getKind() == ElementKind.PACKAGE) {
+      PackageElement packageElement = (PackageElement) rootElement;
+      if (!packageElement.getAnnotationMirrors().isEmpty()) {
+        elements.put(
+            getRelativePathToClass(packageElement.getQualifiedName() + ".package-info"),
+            packageElement);
+      }
+    }
+
+    if (!rootElement.getKind().isClass() && !rootElement.getKind().isInterface()) {
+      return;
+    }
+
+    TypeElement typeElement = (TypeElement) rootElement;
+    elements.put(getRelativePath(typeElement), typeElement);
+    for (Element enclosed : typeElement.getEnclosedElements()) {
+      addAllElements(enclosed, elements);
+    }
+  }
+
+  private Path getRelativePathToClass(CharSequence classBinaryName) {
+    return Paths.get(
+        String.format("%s.class", classBinaryName.toString().replace('.', File.separatorChar)));
+  }
+
+  private Path getRelativePath(TypeElement typeElement) {
+    return getRelativePathToClass(elements.getBinaryName(typeElement));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/FilesystemStubJarWriter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/FilesystemStubJarWriter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/FilesystemStubJarWriter.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.facebook.buck.util.function.ThrowingSupplier;
+import com.facebook.buck.util.zip.CustomZipEntry;
+import com.facebook.buck.util.zip.JarBuilder;
+import com.facebook.buck.util.zip.JarEntrySupplier;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+
+/** A {@link StubJarWriter} that writes to a file. */
+class FilesystemStubJarWriter implements StubJarWriter {
+
+  private final AbsPath outputPath;
+  private final JarBuilder jarBuilder;
+  private boolean closed = false;
+
+  public FilesystemStubJarWriter(AbsPath outputPath) {
+    this.outputPath = outputPath;
+    this.jarBuilder = new JarBuilder().setShouldHashEntries(true).setShouldMergeManifests(true);
+  }
+
+  @Override
+  public void writeEntry(
+      Path relativePath, ThrowingSupplier<InputStream, IOException> streamSupplier) {
+    jarBuilder.addEntry(
+        new JarEntrySupplier(
+            new CustomZipEntry(PathFormatter.pathWithUnixSeparators(relativePath)),
+            streamSupplier));
+  }
+
+  @Override
+  public void close() throws IOException {
+    if (!closed) {
+      jarBuilder.createJarFile(outputPath.getPath());
+    }
+    closed = true;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/InnerClassesTable.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/InnerClassesTable.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/InnerClassesTable.java
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.jvm.java.abi.source.api.CannotInferException;
+import com.facebook.buck.jvm.java.lang.model.AnnotationValueScanner8;
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import javax.annotation.Nullable;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.NestingKind;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.TypeParameterElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.ElementScanner8;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.tree.InnerClassNode;
+
+/**
+ * Aids in constructing a table of {@link InnerClassNode}s when generating bytecode for a {@link
+ * TypeElement}.
+ */
+public class InnerClassesTable {
+  private final DescriptorFactory descriptorFactory;
+  private final AccessFlags accessFlagsUtils;
+  private final ElementsExtended elements;
+  private final Element topElement;
+  private final Set<TypeElement> referencesToInners = new HashSet<>();
+
+  public InnerClassesTable(
+      DescriptorFactory descriptorFactory,
+      AccessFlags accessFlagsUtils,
+      ElementsExtended elements,
+      Element topElement) {
+    this.descriptorFactory = descriptorFactory;
+    this.accessFlagsUtils = accessFlagsUtils;
+    this.elements = elements;
+    this.topElement = topElement;
+  }
+
+  public void addTypeReferences(Element element) {
+    new ElementScanner8<Void, Void>() {
+      @Override
+      public Void visitType(TypeElement e, Void aVoid) {
+        if (e != element) {
+          return null;
+        }
+
+        addTypeReferences(e.getAnnotationMirrors());
+        addTypeReferences(elements.getAllTypeAnnotations(e));
+        e.getTypeParameters().forEach(typeParam -> scan(typeParam, aVoid));
+        addTypeReferences(e.getSuperclass());
+        e.getInterfaces().forEach(InnerClassesTable.this::addTypeReferences);
+        // Members will be visited in the call to super, below
+
+        return super.visitType(e, aVoid);
+      }
+
+      @Override
+      public Void visitExecutable(ExecutableElement e, Void aVoid) {
+        addTypeReferences(e.getAnnotationMirrors());
+        addTypeReferences(elements.getAllTypeAnnotations(e));
+        e.getTypeParameters().forEach(typeParam -> scan(typeParam, aVoid));
+        addTypeReferences(e.getReturnType());
+        addTypeReferences(e.getDefaultValue());
+        // Parameters will be visited in the call to super, below
+        e.getThrownTypes().forEach(InnerClassesTable.this::addTypeReferences);
+        return super.visitExecutable(e, aVoid);
+      }
+
+      @Override
+      public Void visitVariable(VariableElement e, Void aVoid) {
+        addTypeReferences(e.getAnnotationMirrors());
+        addTypeReferences(elements.getAllTypeAnnotations(e));
+        addTypeReferences(e.asType());
+        return super.visitVariable(e, aVoid);
+      }
+
+      @Override
+      public Void visitTypeParameter(TypeParameterElement e, Void aVoid) {
+        addTypeReferences(e.getAnnotationMirrors());
+        addTypeReferences(elements.getAllTypeAnnotations(e));
+        addTypeReferences(e.asType());
+        return super.visitTypeParameter(e, aVoid);
+      }
+    }.scan(element);
+  }
+
+  public void addTypeReferences(TypeMirror type) {
+    new TypeScanner8<Void, Void>() {
+      @Override
+      public Void scan(@Nullable TypeMirror t, Void aVoid) {
+        if (t == null) {
+          return null;
+        }
+        return super.scan(t, aVoid);
+      }
+
+      @Override
+      public Void visitDeclared(DeclaredType t, Void aVoid) {
+        TypeElement element = (TypeElement) t.asElement();
+        if (element.getNestingKind() == NestingKind.MEMBER) {
+          referencesToInners.add(element);
+          element.getEnclosingElement().asType().accept(this, null);
+        }
+
+        try {
+          return super.visitDeclared(t, aVoid);
+        } catch (CannotInferException e) {
+          // We cannot know the enclosing type or type arguments of an inferred type, so
+          // we can't visit them for type references. However, inferred type mirrors are
+          // only returned from asType on an inferred type element. If there were
+          // type arguments in the code, we'd have a StandaloneDeclaredType instead of
+          // an InferredType. Similarly, the enclosing type will be visited by way of
+          // visiting the enclosing element above. So it's safe to just ignore the
+          // exception.
+
+          return null;
+        }
+      }
+    }.scan(type);
+  }
+
+  public void addTypeReferences(List<? extends AnnotationMirror> annotationMirrors) {
+    annotationMirrors.forEach(this::addTypeReferences);
+  }
+
+  private void addTypeReferences(AnnotationMirror annotationMirror) {
+    addTypeReferences(annotationMirror.getAnnotationType());
+    annotationMirror.getElementValues().values().forEach(this::addTypeReferences);
+  }
+
+  private void addTypeReferences(@Nullable AnnotationValue annotationValue) {
+    if (annotationValue == null) {
+      return;
+    }
+    new AnnotationValueScanner8<Void, Void>() {
+      @Override
+      public Void visitType(TypeMirror t, Void aVoid) {
+        addTypeReferences(t);
+        return super.visitType(t, aVoid);
+      }
+
+      @Override
+      public Void visitEnumConstant(VariableElement c, Void aVoid) {
+        addTypeReferences(c.asType());
+        return super.visitEnumConstant(c, aVoid);
+      }
+
+      @Override
+      public Void visitAnnotation(AnnotationMirror a, Void aVoid) {
+        addTypeReferences(a.getAnnotationType());
+        return super.visitAnnotation(a, aVoid);
+      }
+    }.scan(annotationValue);
+  }
+
+  public void reportInnerClassReferences(ClassVisitor visitor) {
+    List<TypeElement> enclosingClasses = new ArrayList<>();
+    List<TypeElement> memberClasses = new ArrayList<>();
+
+    ElementKind elementKind = topElement.getKind();
+    if (elementKind.isClass() || elementKind.isInterface()) {
+      TypeElement walker = (TypeElement) topElement;
+      while (walker.getNestingKind() == NestingKind.MEMBER) {
+        enclosingClasses.add(walker);
+        walker = (TypeElement) walker.getEnclosingElement();
+      }
+    }
+
+    ElementScanner8<Void, Void> elementScanner =
+        new ElementScanner8<>() {
+          @Override
+          public Void visitPackage(PackageElement e, Void aVoid) {
+            addTypeReferences(e.getAnnotationMirrors());
+
+            // If we're being asked to report inner class references of a package, it really means
+            // we're being asked to report inner class references of package-info.java; i.e., just
+            // the package annotations. We therefore return without chaining to super to avoid
+            // recursing into enclosed elements.
+            return null;
+          }
+
+          @Override
+          public Void visitType(TypeElement e, Void aVoid) {
+            if (e != topElement && !memberClasses.contains(e)) {
+              memberClasses.add(e);
+              return null;
+            }
+
+            addTypeReferences(e);
+
+            return super.visitType(e, aVoid);
+          }
+        };
+    elementScanner.scan(topElement);
+
+    Set<TypeElement> reported = new HashSet<>();
+    for (TypeElement element : Lists.reverse(enclosingClasses)) {
+      if (reported.add(element)) {
+        visitor.visitInnerClass(
+            descriptorFactory.getInternalName(element),
+            descriptorFactory.getInternalName((TypeElement) element.getEnclosingElement()),
+            element.getSimpleName().toString(),
+            accessFlagsUtils.getAccessFlags(element) & ~Opcodes.ACC_SUPER);
+      }
+    }
+
+    for (TypeElement element : Lists.reverse(memberClasses)) {
+      if (reported.add(element)) {
+        visitor.visitInnerClass(
+            descriptorFactory.getInternalName(element),
+            descriptorFactory.getInternalName((TypeElement) element.getEnclosingElement()),
+            element.getSimpleName().toString(),
+            accessFlagsUtils.getAccessFlags(element) & ~Opcodes.ACC_SUPER);
+      }
+    }
+
+    referencesToInners.stream()
+        .filter(reported::add)
+        .sorted(Comparator.comparing(e -> e.getQualifiedName().toString()))
+        .forEach(
+            element ->
+                visitor.visitInnerClass(
+                    descriptorFactory.getInternalName(element),
+                    descriptorFactory.getInternalName((TypeElement) element.getEnclosingElement()),
+                    element.getSimpleName().toString(),
+                    accessFlagsUtils.getAccessFlags(element) & ~Opcodes.ACC_SUPER));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/JarBuilderStubJarWriter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/JarBuilderStubJarWriter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/JarBuilderStubJarWriter.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.util.function.ThrowingSupplier;
+import com.facebook.buck.util.zip.CustomZipEntry;
+import com.facebook.buck.util.zip.JarBuilder;
+import com.facebook.buck.util.zip.JarEntrySupplier;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+
+public class JarBuilderStubJarWriter implements StubJarWriter {
+  private final JarBuilder jarBuilder;
+
+  public JarBuilderStubJarWriter(JarBuilder jarBuilder) {
+    this.jarBuilder = jarBuilder;
+    jarBuilder.setShouldMergeManifests(true).setShouldHashEntries(true);
+  }
+
+  @Override
+  public void writeEntry(
+      Path relativePath, ThrowingSupplier<InputStream, IOException> streamSupplier) {
+    jarBuilder.addEntry(new JarEntrySupplier(new CustomZipEntry(relativePath), streamSupplier));
+  }
+
+  @Override
+  public void close() {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/JarReader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/JarReader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/JarReader.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Path;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.objectweb.asm.ClassVisitor;
+
+/** A {@link LibraryReader} that reads from a jar file. */
+class JarReader implements LibraryReader {
+  private final Path jarPath;
+  @Nullable FileSystem fileSystem;
+  @Nullable private DirectoryReader inner;
+  private boolean closed = false;
+
+  JarReader(Path jarPath) {
+    this.jarPath = jarPath;
+  }
+
+  @Override
+  public List<Path> getRelativePaths() throws IOException {
+    return getInner().getRelativePaths();
+  }
+
+  @Override
+  public InputStream openResourceFile(Path relativePath) throws IOException {
+    return getInner().openResourceFile(relativePath);
+  }
+
+  @Override
+  public InputStream openInputStream(Path relativePath) throws IOException {
+    return getInner().openInputStream(relativePath);
+  }
+
+  @Override
+  public void visitClass(Path relativePath, ClassVisitor cv, boolean skipCode) throws IOException {
+    getInner().visitClass(relativePath, cv, skipCode);
+  }
+
+  @Override
+  public void close() throws IOException {
+    if (fileSystem != null) {
+      fileSystem.close();
+      fileSystem = null;
+      inner = null;
+      closed = true;
+    }
+  }
+
+  private DirectoryReader getInner() throws IOException {
+    // Actually had a file descriptor leak because something was reopening this after it was closed,
+    // so let's make sure we crash and detect it if it happens again.
+    Preconditions.checkState(!closed);
+    if (inner == null) {
+      fileSystem = FileSystems.newFileSystem(jarPath, (ClassLoader) null);
+      inner = new DirectoryReader(Iterables.getOnlyElement(fileSystem.getRootDirectories()));
+    }
+
+    return inner;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/LibraryReader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/LibraryReader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/LibraryReader.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import javax.annotation.processing.Messager;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.Element;
+import javax.lang.model.util.Types;
+import org.objectweb.asm.ClassVisitor;
+
+/** An interface for reading and listing resources and classes in a library. */
+interface LibraryReader extends AutoCloseable {
+  static LibraryReader of(Path path) {
+    if (Files.isDirectory(path)) {
+      return new DirectoryReader(path);
+    } else {
+      return new JarReader(path);
+    }
+  }
+
+  static LibraryReader of(
+      SourceVersion targetVersion,
+      ElementsExtended elements,
+      Types types,
+      Messager messager,
+      Iterable<Element> topLevelElements,
+      boolean includeParameterMetadata) {
+    return new ElementsReader(
+        targetVersion, elements, types, messager, topLevelElements, includeParameterMetadata);
+  }
+
+  List<Path> getRelativePaths() throws IOException;
+
+  InputStream openResourceFile(Path relativePath) throws IOException;
+
+  InputStream openInputStream(Path relativePath) throws IOException;
+
+  void visitClass(Path relativePath, ClassVisitor cv, boolean skipCode) throws IOException;
+
+  @Override
+  void close() throws IOException;
+
+  default boolean isResource(Path path) {
+    return !isClass(path);
+  }
+
+  default boolean isClass(Path path) {
+    return path.toString().endsWith(".class");
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SignatureFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SignatureFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SignatureFactory.java
@@ -0,0 +1,415 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.jvm.java.abi.source.api.CannotInferException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import javax.annotation.Nullable;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementVisitor;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.TypeParameterElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.ArrayType;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.ErrorType;
+import javax.lang.model.type.ExecutableType;
+import javax.lang.model.type.NoType;
+import javax.lang.model.type.PrimitiveType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+import javax.lang.model.type.TypeVisitor;
+import javax.lang.model.type.WildcardType;
+import javax.lang.model.util.SimpleElementVisitor8;
+import javax.lang.model.util.SimpleTypeVisitor8;
+import org.objectweb.asm.signature.SignatureVisitor;
+import org.objectweb.asm.signature.SignatureWriter;
+
+/** Computes type signatures for {@link Element}s that require them. */
+class SignatureFactory {
+  private final DescriptorFactory descriptorFactory;
+
+  /**
+   * Adapts a SignatureVisitor to the ElementVisitor contract, so we can drive it from an Element.
+   */
+  private final ElementVisitor<Void, SignatureVisitor> elementVisitorAdapter =
+      new SimpleElementVisitor8<>() {
+        @Override
+        protected Void defaultAction(Element e, SignatureVisitor signatureVisitor) {
+          throw new IllegalArgumentException(
+              String.format("Unexpected element kind: %s", e.getKind()));
+        }
+
+        @Override
+        public Void visitType(TypeElement element, SignatureVisitor visitor) {
+          if (!signatureRequired(element)) {
+            return null;
+          }
+
+          for (TypeParameterElement typeParameterElement : element.getTypeParameters()) {
+            typeParameterElement.accept(this, visitor);
+          }
+
+          TypeMirror superclass = element.getSuperclass();
+          if (superclass.getKind() != TypeKind.NONE) {
+            superclass.accept(typeVisitorAdapter, visitor.visitSuperclass());
+          } else {
+            // Interface type; implicit superclass of Object
+            SignatureVisitor superclassVisitor = visitor.visitSuperclass();
+            superclassVisitor.visitClassType("java/lang/Object");
+            superclassVisitor.visitEnd();
+          }
+
+          for (TypeMirror interfaceType : element.getInterfaces()) {
+            interfaceType.accept(typeVisitorAdapter, visitor.visitInterface());
+          }
+
+          return null;
+        }
+
+        @Override
+        public Void visitTypeParameter(TypeParameterElement element, SignatureVisitor visitor) {
+          visitor.visitFormalTypeParameter(element.getSimpleName().toString());
+          for (TypeMirror boundType : element.getBounds()) {
+            boolean isClass;
+            try {
+              if (boundType.getKind() == TypeKind.DECLARED) {
+                isClass = ((DeclaredType) boundType).asElement().getKind().isClass();
+              } else {
+                isClass = boundType.getKind() == TypeKind.TYPEVAR;
+              }
+            } catch (CannotInferException e) {
+              // We can't know whether an inferred type is a class or interface, but it turns out
+              // the compiler does not distinguish between them when reading signatures, so we can
+              // write inferred types as interface bounds. We go ahead and write all bounds as
+              // interface bounds to make the SourceAbiCompatibleSignatureVisitor possible.
+              isClass = false;
+            }
+
+            boundType.accept(
+                typeVisitorAdapter,
+                isClass ? visitor.visitClassBound() : visitor.visitInterfaceBound());
+          }
+
+          return null;
+        }
+
+        @Override
+        public Void visitExecutable(ExecutableElement element, SignatureVisitor visitor) {
+          return element.asType().accept(typeVisitorAdapter, visitor);
+        }
+
+        @Override
+        public Void visitVariable(VariableElement element, SignatureVisitor visitor) {
+          if (!signatureRequired(element)) {
+            return null;
+          }
+
+          element.asType().accept(typeVisitorAdapter, visitor);
+          return null;
+        }
+      };
+
+  /**
+   * Adapts a SignatureVisitor to the TypeVisitor contract, so we can drive it from a TypeMirror.
+   */
+  private final TypeVisitor<Void, SignatureVisitor> typeVisitorAdapter =
+      new SimpleTypeVisitor8<>() {
+        @Override
+        protected Void defaultAction(TypeMirror e, SignatureVisitor signatureVisitor) {
+          throw new IllegalArgumentException(
+              String.format("Unexpected type kind: %s", e.getKind()));
+        }
+
+        @Override
+        public Void visitError(ErrorType t, SignatureVisitor visitor) {
+          // We don't really know, but if there's an error type the compilation is going to fail
+          // anyway, so just pretend it's Object.
+          visitor.visitClassType("java/lang/Object");
+          visitor.visitEnd();
+          return null;
+        }
+
+        @Override
+        public Void visitNoType(NoType t, SignatureVisitor visitor) {
+          if (t.getKind() == TypeKind.VOID) {
+            visitor.visitBaseType(descriptorFactory.getDescriptor(t).charAt(0));
+            return null;
+          }
+
+          return defaultAction(t, visitor);
+        }
+
+        @Override
+        public Void visitExecutable(ExecutableType t, SignatureVisitor visitor) {
+          if (!signatureRequired(t)) {
+            return null;
+          }
+
+          for (TypeVariable typeVariable : t.getTypeVariables()) {
+            typeVariable.asElement().accept(elementVisitorAdapter, visitor);
+          }
+
+          for (TypeMirror parameter : t.getParameterTypes()) {
+            parameter.accept(this, visitor.visitParameterType());
+          }
+
+          t.getReturnType().accept(this, visitor.visitReturnType());
+
+          if (throwsATypeVar(t)) {
+            for (TypeMirror thrownType : t.getThrownTypes()) {
+              thrownType.accept(typeVisitorAdapter, visitor.visitExceptionType());
+            }
+          }
+
+          return null;
+        }
+
+        @Override
+        public Void visitPrimitive(PrimitiveType t, SignatureVisitor visitor) {
+          visitor.visitBaseType(descriptorFactory.getDescriptor(t).charAt(0));
+          return null;
+        }
+
+        @Override
+        public Void visitTypeVariable(TypeVariable t, SignatureVisitor visitor) {
+          visitor.visitTypeVariable(t.asElement().getSimpleName().toString());
+          return null;
+        }
+
+        @Override
+        public Void visitArray(ArrayType t, SignatureVisitor visitor) {
+          t.getComponentType().accept(this, visitor.visitArrayType());
+          return null;
+        }
+
+        @Override
+        public Void visitWildcard(WildcardType t, SignatureVisitor visitor) {
+          TypeMirror bound = t.getExtendsBound();
+          if (bound != null) {
+            bound.accept(this, visitor.visitTypeArgument(SignatureVisitor.EXTENDS));
+            return null;
+          }
+
+          bound = t.getSuperBound();
+          if (bound != null) {
+            bound.accept(this, visitor.visitTypeArgument(SignatureVisitor.SUPER));
+            return null;
+          }
+
+          visitor.visitTypeArgument();
+          return null;
+        }
+
+        @Override
+        public Void visitDeclared(DeclaredType t, SignatureVisitor visitor) {
+          List<DeclaredType> enclosingTypes = findEnclosingTypes(t);
+
+          // Signatures are weird with inner classes. They use $ as the separator until you
+          // encounter a class with type arguments, then . as the separator thereafter.
+          //
+          // What this means for visiting a class type with a SignatureVisitor is that we don't
+          // start the visiting (by calling visitClassType) at the top-level class; we start at the
+          // outermost class with type arguments. Then we visit the type arguments, and then
+          // every inner class from there to the type for which we're generating a signature.
+          boolean calledVisitClassType = false;
+          int numTypes = enclosingTypes.size();
+          for (int i = 0; i < numTypes; i++) {
+            DeclaredType type = enclosingTypes.get(i);
+            List<? extends TypeMirror> typeArguments;
+            try {
+              typeArguments = type.getTypeArguments();
+            } catch (CannotInferException e) {
+              // InferredDeclaredTypes can only be obtained by calling asType on an
+              // InferredTypeElement. Types that are used in signature generation are not obtained
+              // in this manner, so they should always be StandaloneDeclaredTypes and this exception
+              // should never happen.
+              throw new AssertionError("Unexpected inferred type.", e);
+            }
+            if (calledVisitClassType) {
+              visitor.visitInnerClassType(type.asElement().getSimpleName().toString());
+            } else if (!typeArguments.isEmpty() || i == numTypes - 1) {
+              visitor.visitClassType(descriptorFactory.getInternalName(type));
+              calledVisitClassType = true;
+            } else {
+              // Keep looking for the outermost enclosing generic type
+              continue;
+            }
+
+            for (TypeMirror typeArgument : typeArguments) {
+              typeArgument.accept(this, visitor.visitTypeArgument(SignatureVisitor.INSTANCEOF));
+            }
+          }
+          visitor.visitEnd();
+
+          return null;
+        }
+
+        private List<DeclaredType> findEnclosingTypes(DeclaredType t) {
+          List<DeclaredType> result = new ArrayList<>();
+
+          TypeMirror walker = t;
+          while (walker.getKind() != TypeKind.NONE) {
+            result.add((DeclaredType) walker);
+            walker = ((DeclaredType) walker).getEnclosingType();
+          }
+          Collections.reverse(result);
+
+          return result;
+        }
+      };
+
+  public SignatureFactory(DescriptorFactory descriptorFactory) {
+    this.descriptorFactory = descriptorFactory;
+  }
+
+  /**
+   * Returns the type signature of the given element. If none is required by the VM spec, returns
+   * null.
+   */
+  @Nullable
+  public String getSignature(Element element) {
+    SignatureWriter writer = new SignatureWriter();
+    element.accept(elementVisitorAdapter, writer);
+    String result = writer.toString();
+    return result.isEmpty() ? null : result;
+  }
+
+  @Nullable
+  public String getSignature(TypeMirror type) {
+    SignatureWriter writer = new SignatureWriter();
+    type.accept(typeVisitorAdapter, writer);
+    String result = writer.toString();
+    return result.isEmpty() ? null : result;
+  }
+
+  /**
+   * Returns true if the JVM spec requires a signature to be emitted for this type. See JVMS8
+   * 4.7.9.1
+   */
+  private static boolean signatureRequired(TypeElement element) {
+    if (!element.getTypeParameters().isEmpty()) {
+      return true;
+    }
+
+    if (usesGenerics(element.getSuperclass())) {
+      return true;
+    }
+
+    for (TypeMirror interfaceType : element.getInterfaces()) {
+      if (usesGenerics(interfaceType)) {
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  /**
+   * Returns true if the JVM spec requires a signature to be emitted for this method. See JVMS8
+   * 4.7.9.1
+   */
+  private static boolean signatureRequired(ExecutableType type) {
+    if (!type.getTypeVariables().isEmpty()) {
+      return true;
+    }
+
+    if (usesGenerics(type.getReturnType())) {
+      return true;
+    }
+
+    for (TypeMirror parameterType : type.getParameterTypes()) {
+      if (usesGenerics(parameterType)) {
+        return true;
+      }
+    }
+
+    return throwsATypeVar(type);
+  }
+
+  private static boolean throwsATypeVar(ExecutableType type) {
+    for (TypeMirror thrownType : type.getThrownTypes()) {
+      if (thrownType.getKind() == TypeKind.TYPEVAR) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Returns true if the JVM spec requires a signature to be emitted for this field. See JVMS8
+   * 4.7.9.1
+   */
+  private static boolean signatureRequired(VariableElement element) {
+    return usesGenerics(element.asType());
+  }
+
+  private static boolean usesGenerics(TypeMirror type) {
+    return type.accept(
+        new SimpleTypeVisitor8<Boolean, Void>() {
+          @Override
+          protected Boolean defaultAction(TypeMirror e, Void aVoid) {
+            throw new IllegalArgumentException(
+                String.format("Unexpected type kind: %s", e.getKind()));
+          }
+
+          @Override
+          public Boolean visitError(ErrorType t, Void aVoid) {
+            // We don't really know, but if there's an ErrorType it means compilation is going to
+            // fail anyway so it doesn't matter.
+            return false;
+          }
+
+          @Override
+          public Boolean visitPrimitive(PrimitiveType t, Void aVoid) {
+            return false;
+          }
+
+          @Override
+          public Boolean visitTypeVariable(TypeVariable t, Void aVoid) {
+            return true;
+          }
+
+          @Override
+          public Boolean visitNoType(NoType t, Void aVoid) {
+            return false;
+          }
+
+          @Override
+          public Boolean visitArray(ArrayType t, Void aVoid) {
+            return usesGenerics(t.getComponentType());
+          }
+
+          @Override
+          public Boolean visitWildcard(WildcardType t, Void aVoid) {
+            return true;
+          }
+
+          @Override
+          public Boolean visitDeclared(DeclaredType t, Void aVoid) {
+            try {
+              return !t.getTypeArguments().isEmpty() || usesGenerics(t.getEnclosingType());
+            } catch (CannotInferException e) {
+              // InferredDeclaredTypes can only be obtained by calling asType on an
+              // InferredTypeElement. Types that are used in signature generation are not obtained
+              // in this manner, so they should always be StandaloneDeclaredTypes and this exception
+              // should never happen.
+              throw new AssertionError("Unexpected inferred type", e);
+            }
+          }
+        },
+        null);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SignatureVisitorWrapper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SignatureVisitorWrapper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SignatureVisitorWrapper.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import org.objectweb.asm.signature.SignatureVisitor;
+
+/**
+ * A {@link SignatureVisitor} that chains to another one. Most of the other visitors in ASM can
+ * already do this; {@link SignatureVisitor} is an exception for some reason.
+ */
+class SignatureVisitorWrapper extends SignatureVisitor {
+  private final SignatureVisitor sv;
+
+  public SignatureVisitorWrapper(int api, SignatureVisitor sv) {
+    super(api);
+    this.sv = sv;
+  }
+
+  @Override
+  public void visitFormalTypeParameter(String name) {
+    sv.visitFormalTypeParameter(name);
+  }
+
+  @Override
+  public SignatureVisitor visitClassBound() {
+    return sv.visitClassBound();
+  }
+
+  @Override
+  public SignatureVisitor visitInterfaceBound() {
+    return sv.visitInterfaceBound();
+  }
+
+  @Override
+  public SignatureVisitor visitSuperclass() {
+    return sv.visitSuperclass();
+  }
+
+  @Override
+  public SignatureVisitor visitInterface() {
+    return sv.visitInterface();
+  }
+
+  @Override
+  public SignatureVisitor visitParameterType() {
+    return sv.visitParameterType();
+  }
+
+  @Override
+  public SignatureVisitor visitReturnType() {
+    return sv.visitReturnType();
+  }
+
+  @Override
+  public SignatureVisitor visitExceptionType() {
+    return sv.visitExceptionType();
+  }
+
+  @Override
+  public void visitBaseType(char descriptor) {
+    sv.visitBaseType(descriptor);
+  }
+
+  @Override
+  public void visitTypeVariable(String name) {
+    sv.visitTypeVariable(name);
+  }
+
+  @Override
+  public SignatureVisitor visitArrayType() {
+    return sv.visitArrayType();
+  }
+
+  @Override
+  public void visitClassType(String name) {
+    sv.visitClassType(name);
+  }
+
+  @Override
+  public void visitInnerClassType(String name) {
+    sv.visitInnerClassType(name);
+  }
+
+  @Override
+  public void visitTypeArgument() {
+    sv.visitTypeArgument();
+  }
+
+  @Override
+  public SignatureVisitor visitTypeArgument(char wildcard) {
+    return sv.visitTypeArgument(wildcard);
+  }
+
+  @Override
+  public void visitEnd() {
+    sv.visitEnd();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceAbiCompatibleSignatureVisitor.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceAbiCompatibleSignatureVisitor.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceAbiCompatibleSignatureVisitor.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.signature.SignatureVisitor;
+
+class SourceAbiCompatibleSignatureVisitor extends SignatureVisitorWrapper {
+  public SourceAbiCompatibleSignatureVisitor(SignatureVisitor sv) {
+    super(Opcodes.ASM9, sv);
+  }
+
+  @Override
+  public SignatureVisitor visitClassBound() {
+    // Because we can't know whether inferred types are classes or interfaces, we treat everything
+    // as interfaces.
+    return visitInterfaceBound();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceAbiCompatibleVisitor.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceAbiCompatibleVisitor.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceAbiCompatibleVisitor.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import static com.facebook.buck.jvm.java.abi.AbiGenerationModeUtils.usesDependencies;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.infer.annotation.PropagatesNullable;
+import java.util.Objects;
+import javax.annotation.Nullable;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.FieldVisitor;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.signature.SignatureReader;
+import org.objectweb.asm.signature.SignatureWriter;
+
+/**
+ * This class fixes up a few details of class ABIs so that they match the way source ABIs generate
+ * the same details. It allows us to take potentially risky shortcuts in source ABIs without losing
+ * the ability to verify them by binary comparison against class ABIs.
+ */
+public class SourceAbiCompatibleVisitor extends ClassVisitor {
+
+  private final AbiGenerationMode compatibilityMode;
+  @Nullable private String name;
+
+  public SourceAbiCompatibleVisitor(ClassVisitor cv, AbiGenerationMode compatibilityMode) {
+    super(Opcodes.ASM9, cv);
+    this.compatibilityMode = compatibilityMode;
+  }
+
+  @Override
+  public void visit(
+      int version,
+      int access,
+      String name,
+      String signature,
+      String superName,
+      String[] interfaces) {
+    this.name = name;
+    access = stripAbstractFromEnums(access);
+    super.visit(version, access, name, fixupSignature(signature), superName, interfaces);
+  }
+
+  @Override
+  @Nullable
+  public MethodVisitor visitMethod(
+      int access, String name, String desc, String signature, String[] exceptions) {
+    if (!usesDependencies(compatibilityMode) && (access & Opcodes.ACC_BRIDGE) != 0) {
+      return null;
+    }
+
+    return super.visitMethod(access, name, desc, fixupSignature(signature), exceptions);
+  }
+
+  @Override
+  public FieldVisitor visitField(
+      int access, String name, String desc, String signature, Object value) {
+    return super.visitField(access, name, desc, fixupSignature(signature), value);
+  }
+
+  @Override
+  public void visitInnerClass(String name, String outerName, String innerName, int access) {
+    Objects.requireNonNull(this.name);
+    if (!usesDependencies(compatibilityMode)
+        && !this.name.equals(name)
+        && !this.name.equals(outerName)) {
+      // Because we can't know the flags for inferred types, InnerClassesTable marks all entries
+      // as ACC_STATIC except for the class itself and its member classes. It could technically
+      // use the correct flags for non-inferred types, but then it becomes impossible for us to
+      // fix up the class ABI to match.
+      access = Opcodes.ACC_STATIC;
+    }
+    access = stripAbstractFromEnums(access);
+    super.visitInnerClass(name, outerName, innerName, access);
+  }
+
+  private String fixupSignature(@PropagatesNullable String signature) {
+    if (signature == null || usesDependencies(compatibilityMode)) {
+      return signature;
+    }
+
+    SignatureReader reader = new SignatureReader(signature);
+    SignatureWriter writer = new SignatureWriter();
+
+    reader.accept(new SourceAbiCompatibleSignatureVisitor(writer));
+
+    return writer.toString();
+  }
+
+  private int stripAbstractFromEnums(int access) {
+    if (usesDependencies(compatibilityMode)) {
+      return access;
+    }
+
+    if ((access & Opcodes.ACC_ENUM) == Opcodes.ACC_ENUM) {
+      access = access & ~Opcodes.ACC_ABSTRACT;
+    }
+    return access;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceBasedAbiStubber.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceBasedAbiStubber.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/SourceBasedAbiStubber.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory.SourceOnlyAbiRuleInfo;
+import com.facebook.buck.jvm.java.plugin.api.BuckJavacTaskListener;
+import com.facebook.buck.jvm.java.plugin.api.BuckJavacTaskProxy;
+import com.facebook.buck.jvm.java.plugin.api.PluginClassLoader;
+import java.lang.reflect.Constructor;
+import java.util.function.Supplier;
+import javax.tools.Diagnostic;
+
+public final class SourceBasedAbiStubber {
+  public static BuckJavacTaskListener newValidatingTaskListener(
+      PluginClassLoader pluginLoader,
+      BuckJavacTaskProxy task,
+      SourceOnlyAbiRuleInfo ruleInfo,
+      Supplier<Boolean> errorsExist,
+      Diagnostic.Kind messageKind) {
+    try {
+      Class<?> validatingTaskListenerClass =
+          pluginLoader.loadClass(
+              "com.facebook.buck.jvm.java.abi.source.ValidatingTaskListener", Object.class);
+      Constructor<?> constructor =
+          validatingTaskListenerClass.getConstructor(
+              BuckJavacTaskProxy.class,
+              SourceOnlyAbiRuleInfo.class,
+              Supplier.class,
+              Diagnostic.Kind.class);
+
+      return BuckJavacTaskListener.wrapRealTaskListener(
+          pluginLoader, constructor.newInstance(task, ruleInfo, errorsExist, messageKind));
+    } catch (ReflectiveOperationException e) {
+      throw new RuntimeException(
+          "Could not load source-generated ABI validator. Your compiler might not support this. "
+              + "If it doesn't, you may need to disable source-based ABI generation.",
+          e);
+    }
+  }
+
+  private SourceBasedAbiStubber() {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubClassFileWriter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubClassFileWriter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubClassFileWriter.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.util.function.ThrowingSupplier;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+
+/*
+ * Class to write stub jar entries as class files
+ * */
+public class StubClassFileWriter implements StubJarWriter {
+
+  private final AbsPath outputPath;
+  private boolean closed = false;
+
+  public StubClassFileWriter(AbsPath outputPath) {
+    this.outputPath = outputPath;
+  }
+
+  @Override
+  public void writeEntry(
+      Path relativePath, ThrowingSupplier<InputStream, IOException> streamSupplier) {
+
+    if (!outputPath.toFile().isDirectory()) {
+      throw new IllegalArgumentException("Output Path should be a directory");
+    }
+
+    try {
+      // Ensure parent directory exists, throw if creation fails
+      File parentDir = new File(outputPath.toFile(), relativePath.getParent().toString());
+      if (!parentDir.exists() && !parentDir.mkdirs()) {
+        throw new IOException("Failed to create directory: " + parentDir);
+      }
+
+      File classFile = new File(parentDir, relativePath.getFileName().toString());
+
+      // Use try-with-resources for automatic resource management
+      try (InputStream inputStream = streamSupplier.get();
+          FileOutputStream fos = new FileOutputStream(classFile)) {
+
+        byte[] buffer = new byte[8192];
+        int bytesRead;
+        while ((bytesRead = inputStream.read(buffer)) != -1) {
+          fos.write(buffer, 0, bytesRead);
+        }
+      }
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @Override
+  public void close() throws IOException {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubGenerator.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubGenerator.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubGenerator.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import com.facebook.buck.util.zip.JarBuilder;
+import java.io.IOException;
+import java.util.Set;
+import javax.annotation.Nullable;
+import javax.annotation.processing.Messager;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.Element;
+import javax.lang.model.util.Types;
+
+public class StubGenerator {
+  private final SourceVersion version;
+  private final ElementsExtended elements;
+  private final Types types;
+  private final Messager messager;
+  private final JarBuilder jarBuilder;
+  private final AbiGenerationMode abiCompatibilityMode;
+  private final boolean includeParameterMetadata;
+  private final boolean keepSynthetic;
+
+  private final AbsPath classOutputPath;
+
+  public StubGenerator(
+      SourceVersion version,
+      ElementsExtended elements,
+      Types types,
+      Messager messager,
+      @Nullable JarBuilder jarBuilder,
+      AbiGenerationMode abiCompatibilityMode,
+      boolean includeParameterMetadata,
+      boolean keepSynthetic,
+      AbsPath classOutputPath) {
+    this.version = version;
+    this.elements = elements;
+    this.types = types;
+    this.messager = messager;
+    this.jarBuilder = jarBuilder;
+    this.abiCompatibilityMode = abiCompatibilityMode;
+    this.includeParameterMetadata = includeParameterMetadata;
+    this.keepSynthetic = keepSynthetic;
+    this.classOutputPath = classOutputPath;
+  }
+
+  public void generate(Set<Element> topLevelElements) {
+    try {
+      StubJar stubJar =
+          new StubJar(
+                  version,
+                  elements,
+                  types,
+                  messager,
+                  topLevelElements,
+                  includeParameterMetadata,
+                  keepSynthetic)
+              .setCompatibilityMode(abiCompatibilityMode);
+
+      if (classOutputPath != null) {
+        stubJar.writeClasses(classOutputPath);
+      } else {
+        stubJar.writeTo(jarBuilder);
+      }
+    } catch (IOException e) {
+      throw new RuntimeException(String.format("Failed to generate abi: %s", e.getMessage()));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJar.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJar.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJar.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.jvm.java.abi.kotlin.InlineFunctionScope;
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import com.facebook.buck.util.zip.JarBuilder;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.annotation.processing.Messager;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.Element;
+import javax.lang.model.util.Types;
+
+public class StubJar {
+  private final Supplier<LibraryReader> libraryReaderSupplier;
+  @Nullable private AbiGenerationMode compatibilityMode = null;
+  @Nullable private Supplier<LibraryReader> existingAbiSupplier = null;
+  private boolean keepSynthetic = false;
+
+  public StubJar(AbsPath jarPath) {
+    libraryReaderSupplier = () -> LibraryReader.of(jarPath.getPath());
+  }
+
+  public StubJar(AbsPath jarPath, boolean keepSynthetic) {
+    libraryReaderSupplier = () -> LibraryReader.of(jarPath.getPath());
+    this.keepSynthetic = keepSynthetic;
+  }
+
+  /**
+   * @param targetVersion the class file version to output, expressed as the corresponding Java
+   *     source version
+   */
+  public StubJar(
+      SourceVersion targetVersion,
+      ElementsExtended elements,
+      Types types,
+      Messager messager,
+      Iterable<Element> topLevelElements,
+      boolean includeParameterMetadata,
+      boolean keepSynthetic) {
+    libraryReaderSupplier =
+        () ->
+            LibraryReader.of(
+                targetVersion,
+                elements,
+                types,
+                messager,
+                topLevelElements,
+                includeParameterMetadata);
+  }
+
+  /**
+   * Filters the stub jar through {@link SourceAbiCompatibleVisitor}. See that class for details.
+   */
+  public StubJar setCompatibilityMode(AbiGenerationMode compatibilityMode) {
+    this.compatibilityMode = compatibilityMode;
+    return this;
+  }
+
+  /** Specify a directory of existing abi we need to inherit */
+  public StubJar setExistingAbiJar(AbsPath existingAbiJar) {
+    this.existingAbiSupplier = () -> LibraryReader.of(existingAbiJar.getPath());
+    return this;
+  }
+
+  public void writeClasses(AbsPath classesDir) throws IOException {
+    try (LibraryReader input = libraryReaderSupplier.get();
+        StubJarWriter writer = new StubClassFileWriter(classesDir)) {
+      writeTo(input, writer, null);
+    }
+  }
+
+  /** Writes output into the passed absolute path. */
+  public void writeTo(AbsPath outputAbsPath) throws IOException {
+    // The order of these declarations is important -- FilesystemStubJarWriter must be declared
+    // after LibraryReader. This is because FilesystemStubJarWriter actually uses the LibraryReader
+    // in its close method, and try-with-resources closes the items in the opposite order of their
+    // creation.
+    try (LibraryReader input = libraryReaderSupplier.get();
+        LibraryReader existingAbiInput =
+            existingAbiSupplier != null ? existingAbiSupplier.get() : null;
+        StubJarWriter writer = new FilesystemStubJarWriter(outputAbsPath)) {
+      writeTo(input, writer, existingAbiInput);
+    }
+  }
+
+  public void writeTo(JarBuilder jarBuilder) throws IOException {
+    try (LibraryReader input = libraryReaderSupplier.get();
+        LibraryReader existingAbiInput =
+            existingAbiSupplier != null ? existingAbiSupplier.get() : null;
+        StubJarWriter writer = new JarBuilderStubJarWriter(jarBuilder)) {
+      writeTo(input, writer, existingAbiInput);
+    }
+  }
+
+  private void writeTo(
+      LibraryReader input, StubJarWriter writer, @Nullable LibraryReader existingAbiInput)
+      throws IOException {
+    List<Path> relativePaths = input.getRelativePaths();
+    Comparator<Path> visitOuterClassesFirst = Comparator.comparing(StubJar::pathWithoutClassSuffix);
+    List<Path> paths =
+        relativePaths.stream().sorted(visitOuterClassesFirst).collect(Collectors.toList());
+
+    boolean isKotlinModule = isKotlinModule(relativePaths);
+
+    InlineFunctionScope inlineFunctionScope = isKotlinModule ? new InlineFunctionScope() : null;
+
+    if (!isKotlinModule && keepSynthetic) {
+      throw new IllegalStateException(
+          "keepSynthetic is intended only to be used on Kotlin modules");
+    }
+
+    // Calculate all existingAbiPathStrings here outside of for-loop,
+    // to save calculation for each path / StubJarEntry
+    Set<String> existingAbiPathStrings =
+        existingAbiInput != null
+            ? existingAbiInput.getRelativePaths().stream()
+                .map(Path::toString)
+                .collect(Collectors.toSet())
+            : Collections.emptySet();
+
+    for (Path path : paths) {
+      StubJarEntry entry =
+          StubJarEntry.of(
+              input,
+              path,
+              existingAbiInput,
+              existingAbiPathStrings,
+              compatibilityMode,
+              inlineFunctionScope,
+              keepSynthetic);
+      if (entry == null) {
+        continue;
+      }
+      entry.write(writer);
+      if (inlineFunctionScope != null) {
+        String pathNoSuffix = pathWithoutClassSuffix(path);
+        inlineFunctionScope.createScopes(pathNoSuffix, entry.getInlineFunctions());
+        if (entry.extendsInlineFunctionScope()) {
+          inlineFunctionScope.extendScope(pathNoSuffix);
+        }
+      }
+    }
+  }
+
+  private boolean isKotlinModule(List<Path> relativePaths) {
+    return relativePaths.stream().anyMatch(path -> path.toString().endsWith(".kotlin_module"));
+  }
+
+  static String pathWithoutClassSuffix(Path path) {
+    final String pathString = path.toString();
+    return pathString.endsWith(".class")
+        ? pathString.substring(0, pathString.length() - ".class".length())
+        : pathString;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarClassEntry.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarClassEntry.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarClassEntry.java
@@ -0,0 +1,277 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.jvm.java.abi.kotlin.InlineFunctionScope;
+import com.facebook.buck.jvm.java.abi.kotlin.KotlinMetadataReader;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.ClassWriter;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.tree.AnnotationNode;
+import org.objectweb.asm.tree.ClassNode;
+import org.objectweb.asm.tree.InnerClassNode;
+
+class StubJarClassEntry extends StubJarEntry {
+  @Nullable private final Set<String> referencedClassNames;
+  private final Path path;
+  private final ClassNode stub;
+  private final List<String> kotlinInlineFunctions;
+  private final boolean isWithinInlineFunctionScope;
+  private final boolean keepSynthetic;
+
+  @Nullable
+  public static StubJarClassEntry of(
+      LibraryReader input,
+      Path path,
+      @Nullable AbiGenerationMode compatibilityMode,
+      @Nullable InlineFunctionScope inlineFunctionScope,
+      boolean keepSynthetic)
+      throws IOException {
+
+    List<String> inlineFunctions = Collections.emptyList();
+    boolean isKotlinModule = inlineFunctionScope != null;
+    boolean isKotlinClass = false;
+    boolean isWithinInlineFunctionScope = false;
+
+    if (isKotlinModule) {
+      // Visit the class (skipping code) without filtering, to gather its annotations and class
+      // relationships
+      ClassNode classMetadata = new ClassNode(Opcodes.ASM9);
+      input.visitClass(path, classMetadata, true);
+
+      AnnotationNode kotlinMetadataAnnotation = findKotlinMetadataAnnotation(classMetadata);
+      if (kotlinMetadataAnnotation != null) {
+        isKotlinClass = true;
+
+        KotlinMetadataReader.ParsedMetadata parsedMetadata =
+            KotlinMetadataReader.readMetadata(kotlinMetadataAnnotation);
+
+        // Exclude Kotlin file-private classes from class-abi. These are compiled to
+        // package-private in bytecode (so ACC_PRIVATE doesn't catch them), but they
+        // are not part of the module's public API. Source-only-abi already excludes them.
+        if (KotlinMetadataReader.isFilePrivateClass(parsedMetadata)) {
+          return null;
+        }
+
+        isWithinInlineFunctionScope = inlineFunctionScope.captures(path, classMetadata);
+        inlineFunctions = KotlinMetadataReader.getInlineFunctions(parsedMetadata);
+      }
+    }
+
+    // As we read the class in, we create a partial stub that removes non-ABI methods and fields
+    // but leaves the entire InnerClasses table. We record all classes that are referenced from
+    // ABI methods and fields, and will use that information later to filter the InnerClasses table.
+    //
+    // If this class is within a Kotlin inline function's scope its ABI is unfiltered, because it
+    // will be copied in its entirety in the calling context.
+    ClassNode stub = new ClassNode(Opcodes.ASM9);
+    ClassReferenceTracker referenceTracker = new ClassReferenceTracker(stub);
+    ClassVisitor visitor = referenceTracker;
+    if (!isWithinInlineFunctionScope) {
+      visitor = new AbiFilteringClassVisitor(visitor, inlineFunctions, keepSynthetic);
+    }
+
+    // If we want ABIs that are compatible with those generated from source, we add a visitor
+    // at the very start of the chain which transforms the event stream coming out of `ClassNode`
+    // to look like what ClassVisitorDriverFromElement would have produced.
+    if (compatibilityMode != null && compatibilityMode != AbiGenerationMode.CLASS) {
+      visitor = new SourceAbiCompatibleVisitor(visitor, compatibilityMode);
+    }
+
+    // Don't skip the code if this is a Kotlin Class so that (a) we have a chance to visit the the
+    // classes referenced in inline function bodies, and (b) to retain debug information that
+    // Kotlin's
+    // own jvm-abi-gen plugin would retain.
+    input.visitClass(path, visitor, /* skipCode */ !isKotlinClass);
+
+    // Kotlin top functions reside in synthetic classes, we should output ABIs for them.
+    if ((isSyntheticClass(stub) && isKotlinModule)
+        || !(isSyntheticClass(stub) || isAnonymousOrLocalClass(stub))
+        || isWithinInlineFunctionScope
+        // The synthetic package-info class is how package annotations are recorded; that one is
+        // actually used by the compiler
+        || stub.name.endsWith("/package-info")) {
+      return new StubJarClassEntry(
+          path,
+          stub,
+          referenceTracker.getReferencedClassNames(),
+          inlineFunctions,
+          isWithinInlineFunctionScope,
+          keepSynthetic);
+    }
+
+    return null;
+  }
+
+  private StubJarClassEntry(
+      Path path,
+      ClassNode stub,
+      Set<String> referencedClassNames,
+      List<String> kotlinInlineFunctions,
+      boolean isWithinInlineFunctionScope,
+      boolean keepSynthetic) {
+    this.path = path;
+    this.stub = stub;
+    this.referencedClassNames = referencedClassNames;
+    this.kotlinInlineFunctions = kotlinInlineFunctions;
+    this.isWithinInlineFunctionScope = isWithinInlineFunctionScope;
+    this.keepSynthetic = keepSynthetic;
+  }
+
+  @Override
+  public void write(StubJarWriter writer) {
+    writer.writeEntry(path, this::openInputStream);
+  }
+
+  @Override
+  public List<String> getInlineFunctions() {
+    return kotlinInlineFunctions;
+  }
+
+  @Override
+  public boolean extendsInlineFunctionScope() {
+    return isWithinInlineFunctionScope;
+  }
+
+  private InputStream openInputStream() {
+    ClassWriter writer = new ClassWriter(0);
+    ClassVisitor visitor = writer;
+    if (!isWithinInlineFunctionScope) {
+      visitor = new InnerClassSortingClassVisitor(stub.name, visitor);
+      visitor =
+          new AbiFilteringClassVisitor(
+              visitor, kotlinInlineFunctions, referencedClassNames, keepSynthetic);
+    }
+
+    stub.accept(visitor);
+
+    return new ByteArrayInputStream(writer.toByteArray());
+  }
+
+  private static boolean isSyntheticClass(ClassNode node) {
+    return ((node.access & Opcodes.ACC_SYNTHETIC) == Opcodes.ACC_SYNTHETIC);
+  }
+
+  private static boolean isAnonymousOrLocalClass(ClassNode node) {
+    InnerClassNode innerClass = getInnerClassMetadata(node);
+    while (innerClass != null) {
+      if (innerClass.outerName == null) {
+        return true;
+      }
+      innerClass = getInnerClassMetadata(node, innerClass.outerName);
+    }
+
+    return false;
+  }
+
+  @Nullable
+  private static InnerClassNode getInnerClassMetadata(ClassNode node) {
+    String name = node.name;
+    return getInnerClassMetadata(node, name);
+  }
+
+  @Nullable
+  private static AnnotationNode findKotlinMetadataAnnotation(ClassNode node) {
+    if (node.visibleAnnotations == null) {
+      return null;
+    }
+    return node.visibleAnnotations.stream()
+        .filter(annotation -> "Lkotlin/Metadata;".equals(annotation.desc))
+        .findFirst()
+        .orElse(null);
+  }
+
+  @Nullable
+  private static InnerClassNode getInnerClassMetadata(ClassNode node, String className) {
+    for (InnerClassNode innerClass : node.innerClasses) {
+      if (innerClass.name.equals(className)) {
+        return innerClass;
+      }
+    }
+
+    return null;
+  }
+
+  private static class InnerClassSortingClassVisitor extends ClassVisitor {
+    private final String className;
+    private final List<InnerClassNode> innerClasses = new ArrayList<>();
+    private final List<String> nestMembers = new ArrayList<>();
+
+    private InnerClassSortingClassVisitor(String className, ClassVisitor cv) {
+      super(Opcodes.ASM9, cv);
+      this.className = className;
+    }
+
+    @Override
+    public void visitInnerClass(String name, String outerName, String innerName, int access) {
+      innerClasses.add(new InnerClassNode(name, outerName, innerName, access));
+    }
+
+    @Override
+    public void visitNestMember(String nestMember) {
+      nestMembers.add(nestMember);
+    }
+
+    @Override
+    public void visitEnd() {
+      innerClasses.sort(
+          (o1, o2) -> {
+            // Enclosing classes and member classes should come first, with their order preserved
+            boolean o1IsEnclosingOrMember = isEnclosingOrMember(o1);
+            boolean o2IsEnclosingOrMember = isEnclosingOrMember(o2);
+            if (o1IsEnclosingOrMember && o2IsEnclosingOrMember) {
+              // Preserve order among these
+              return 0;
+            } else if (o1IsEnclosingOrMember) {
+              return -1;
+            } else if (o2IsEnclosingOrMember) {
+              return 1;
+            }
+
+            // References to other classes get sorted.
+            return o1.name.compareTo(o2.name);
+          });
+
+      for (InnerClassNode innerClass : innerClasses) {
+        innerClass.accept(cv);
+      }
+
+      nestMembers.stream().sorted().forEach(nestMember -> cv.visitNestMember(nestMember));
+
+      super.visitEnd();
+    }
+
+    private boolean isEnclosingOrMember(InnerClassNode innerClass) {
+      if (className.equals(innerClass.name)) {
+        // Self!
+        return true;
+      }
+
+      if (className.equals(innerClass.outerName)) {
+        // Member class
+        return true;
+      }
+
+      // Enclosing class
+      return className.startsWith(innerClass.name + "$");
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarEntry.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarEntry.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarEntry.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.cd.model.java.AbiGenerationMode;
+import com.facebook.buck.jvm.java.abi.kotlin.InlineFunctionScope;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Set;
+import javax.annotation.Nullable;
+
+public abstract class StubJarEntry {
+  @Nullable
+  static StubJarEntry of(
+      LibraryReader input,
+      Path path,
+      @Nullable LibraryReader existingAbiInput,
+      Set<String> existingAbiPathStrings,
+      AbiGenerationMode compatibilityMode,
+      @Nullable InlineFunctionScope inlineFunctionScope,
+      boolean keepSynthetic)
+      throws IOException {
+    if (isStubbableResource(input, path)) {
+      return StubJarResourceEntry.of(input, path);
+    } else if (input.isClass(path)) {
+      if (existingAbiInput != null && existingAbiPathStrings.contains(path.toString())) {
+        return StubJarExistingEntry.of(existingAbiInput, path);
+      } else {
+        return StubJarClassEntry.of(
+            input, path, compatibilityMode, inlineFunctionScope, keepSynthetic);
+      }
+    }
+
+    return null;
+  }
+
+  public abstract void write(StubJarWriter writer);
+
+  public abstract List<String> getInlineFunctions();
+
+  public abstract boolean extendsInlineFunctionScope();
+
+  private static boolean isStubbableResource(LibraryReader input, Path path) {
+    return input.isResource(path);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarExistingEntry.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarExistingEntry.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarExistingEntry.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.List;
+
+/** Write an entry to stub jar by directly copy an existing abi. */
+class StubJarExistingEntry extends StubJarEntry {
+  private final LibraryReader existingAbiInput;
+  private final Path path;
+
+  public static StubJarExistingEntry of(LibraryReader existingAbiInput, Path path) {
+    return new StubJarExistingEntry(existingAbiInput, path);
+  }
+
+  private StubJarExistingEntry(LibraryReader existingAbiInput, Path path) {
+    this.existingAbiInput = existingAbiInput;
+    this.path = path;
+  }
+
+  @Override
+  public void write(StubJarWriter writer) {
+    writer.writeEntry(path, () -> existingAbiInput.openInputStream(path));
+  }
+
+  @Override
+  public List<String> getInlineFunctions() {
+    return Collections.emptyList();
+  }
+
+  @Override
+  public boolean extendsInlineFunctionScope() {
+    return false;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarResourceEntry.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarResourceEntry.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarResourceEntry.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.List;
+
+class StubJarResourceEntry extends StubJarEntry {
+  private final LibraryReader input;
+  private final Path path;
+
+  public static StubJarResourceEntry of(LibraryReader input, Path path) {
+    return new StubJarResourceEntry(input, path);
+  }
+
+  private StubJarResourceEntry(LibraryReader input, Path path) {
+    this.input = input;
+    this.path = path;
+  }
+
+  @Override
+  public void write(StubJarWriter writer) {
+    writer.writeEntry(path, () -> input.openResourceFile(path));
+  }
+
+  @Override
+  public List<String> getInlineFunctions() {
+    return Collections.emptyList();
+  }
+
+  @Override
+  public boolean extendsInlineFunctionScope() {
+    return false;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarWriter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarWriter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/StubJarWriter.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import com.facebook.buck.util.function.ThrowingSupplier;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+
+/** An interface for writing to stub jars. */
+interface StubJarWriter extends AutoCloseable {
+  void writeEntry(Path relativePath, ThrowingSupplier<InputStream, IOException> streamSupplier);
+
+  @Override
+  void close() throws IOException;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/TypeScanner8.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/TypeScanner8.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/TypeScanner8.java
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.annotation.Nullable;
+import javax.lang.model.element.TypeParameterElement;
+import javax.lang.model.type.ArrayType;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.ErrorType;
+import javax.lang.model.type.ExecutableType;
+import javax.lang.model.type.IntersectionType;
+import javax.lang.model.type.NoType;
+import javax.lang.model.type.NullType;
+import javax.lang.model.type.PrimitiveType;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+import javax.lang.model.type.UnionType;
+import javax.lang.model.type.WildcardType;
+import javax.lang.model.util.AbstractTypeVisitor8;
+
+/**
+ * A scanning visitor of {@link TypeMirror}s for {@link javax.lang.model.SourceVersion#RELEASE_8}.
+ */
+public class TypeScanner8<R, P> extends AbstractTypeVisitor8<R, P> {
+  private final Set<TypeParameterElement> visitedTypeVars = new HashSet<>();
+  @Nullable private final R defaultValue;
+
+  protected TypeScanner8() {
+    this(null);
+  }
+
+  protected TypeScanner8(@Nullable R defaultValue) {
+    this.defaultValue = defaultValue;
+  }
+
+  @Nullable
+  public final R scan(Iterable<? extends TypeMirror> iterable, P p) {
+    R result = defaultValue;
+    for (TypeMirror t : iterable) {
+      result = scan(t, p);
+    }
+    return result;
+  }
+
+  @Nullable
+  public R scan(TypeMirror t, P p) {
+    return t.accept(this, p);
+  }
+
+  @Nullable
+  public final R scan(TypeMirror t) {
+    return t.accept(this, null);
+  }
+
+  @Override
+  @Nullable
+  public R visitPrimitive(PrimitiveType t, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitNull(NullType t, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitArray(ArrayType t, P p) {
+    return scan(t.getComponentType(), p);
+  }
+
+  @Override
+  @Nullable
+  public R visitDeclared(DeclaredType t, P p) {
+    scan(t.getEnclosingType(), p);
+    return scan(t.getTypeArguments(), p);
+  }
+
+  @Override
+  @Nullable
+  public R visitError(ErrorType t, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitTypeVariable(TypeVariable t, P p) {
+    // Avoid infinite recursion in cases like T extends List<T>
+    TypeParameterElement typeParameterElement = (TypeParameterElement) t.asElement();
+    if (visitedTypeVars.contains(typeParameterElement)) {
+      return defaultValue;
+    }
+    visitedTypeVars.add(typeParameterElement);
+
+    scan(t.getLowerBound(), p);
+    return scan(t.getUpperBound(), p);
+  }
+
+  @Override
+  @Nullable
+  public R visitWildcard(WildcardType t, P p) {
+    R result = defaultValue;
+    TypeMirror extendsBound = t.getExtendsBound();
+    if (extendsBound != null) {
+      result = scan(extendsBound, p);
+    }
+
+    TypeMirror superBound = t.getSuperBound();
+    if (superBound != null) {
+      result = scan(superBound, p);
+    }
+
+    return result;
+  }
+
+  @Override
+  @Nullable
+  public R visitExecutable(ExecutableType t, P p) {
+    // TODO(jkeljo): Either make this adaptive or just wait until we drop javac 7 support to
+    // uncomment:
+    // scan(t.getReceiverType(), p);
+    scan(t.getTypeVariables(), p);
+    scan(t.getReturnType(), p);
+    scan(t.getParameterTypes(), p);
+    return scan(t.getThrownTypes(), p);
+  }
+
+  @Override
+  @Nullable
+  public R visitNoType(NoType t, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitIntersection(IntersectionType t, P p) {
+    return scan(t.getBounds(), p);
+  }
+
+  @Override
+  @Nullable
+  public R visitUnion(UnionType t, P p) {
+    throw new UnsupportedOperationException("NYI");
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/java17/SourceVersionUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/java17/SourceVersionUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/java17/SourceVersionUtils.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import javax.lang.model.SourceVersion;
+import org.objectweb.asm.Opcodes;
+
+/** Utility methods for working with source versions. */
+public class SourceVersionUtils {
+  /** Gets the class file version corresponding to the given source version constant. */
+  public static int sourceVersionToClassFileVersion(SourceVersion version) {
+    switch (version) {
+      case RELEASE_0:
+      case RELEASE_1:
+        return Opcodes.V1_1; // JVMS8 4.1: 1.0 and 1.1 both support version 45.3 (Opcodes.V1_1)
+      case RELEASE_2:
+        return Opcodes.V1_2;
+      case RELEASE_3:
+        return Opcodes.V1_3;
+      case RELEASE_4:
+        return Opcodes.V1_4;
+      case RELEASE_5:
+        return Opcodes.V1_5;
+      case RELEASE_6:
+        return Opcodes.V1_6;
+      case RELEASE_7:
+        return Opcodes.V1_7;
+      case RELEASE_8:
+        return Opcodes.V1_8;
+      case RELEASE_9:
+        return Opcodes.V9;
+      case RELEASE_10:
+        return Opcodes.V10;
+      case RELEASE_11:
+        return Opcodes.V11;
+      case RELEASE_17:
+        return Opcodes.V17;
+      default:
+        throw new IllegalArgumentException(String.format("Unexpected source version: %s", version));
+    }
+  }
+
+  /** Gets the source version corresponding to the given target string. */
+  public static SourceVersion getSourceVersionFromTarget(String target) {
+    switch (target) {
+      case "1.3":
+        return SourceVersion.RELEASE_3;
+      case "1.4":
+        return SourceVersion.RELEASE_4;
+      case "1.5":
+      case "5":
+        return SourceVersion.RELEASE_5;
+      case "1.6":
+      case "6":
+        return SourceVersion.RELEASE_6;
+      case "1.7":
+      case "7":
+        return SourceVersion.RELEASE_7;
+      case "1.8":
+      case "8":
+        return SourceVersion.RELEASE_8;
+      case "9":
+        return SourceVersion.RELEASE_9;
+      case "10":
+        return SourceVersion.RELEASE_10;
+      case "11":
+        return SourceVersion.RELEASE_11;
+      case "17":
+        return SourceVersion.RELEASE_17;
+      default:
+        throw new RuntimeException(String.format("target %s not supported", target));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/java21/SourceVersionUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/java21/SourceVersionUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/java21/SourceVersionUtils.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi;
+
+import javax.lang.model.SourceVersion;
+import org.objectweb.asm.Opcodes;
+
+/** Utility methods for working with source versions. */
+public class SourceVersionUtils {
+  /** Gets the class file version corresponding to the given source version constant. */
+  public static int sourceVersionToClassFileVersion(SourceVersion version) {
+    switch (version) {
+      case RELEASE_0:
+      case RELEASE_1:
+        return Opcodes.V1_1; // JVMS8 4.1: 1.0 and 1.1 both support version 45.3 (Opcodes.V1_1)
+      case RELEASE_2:
+        return Opcodes.V1_2;
+      case RELEASE_3:
+        return Opcodes.V1_3;
+      case RELEASE_4:
+        return Opcodes.V1_4;
+      case RELEASE_5:
+        return Opcodes.V1_5;
+      case RELEASE_6:
+        return Opcodes.V1_6;
+      case RELEASE_7:
+        return Opcodes.V1_7;
+      case RELEASE_8:
+        return Opcodes.V1_8;
+      case RELEASE_9:
+        return Opcodes.V9;
+      case RELEASE_10:
+        return Opcodes.V10;
+      case RELEASE_11:
+        return Opcodes.V11;
+      case RELEASE_17:
+        return Opcodes.V17;
+      case RELEASE_21:
+        return Opcodes.V21;
+      default:
+        throw new IllegalArgumentException(String.format("Unexpected source version: %s", version));
+    }
+  }
+
+  /** Gets the source version corresponding to the given target string. */
+  public static SourceVersion getSourceVersionFromTarget(String target) {
+    switch (target) {
+      case "1.3":
+        return SourceVersion.RELEASE_3;
+      case "1.4":
+        return SourceVersion.RELEASE_4;
+      case "1.5":
+      case "5":
+        return SourceVersion.RELEASE_5;
+      case "1.6":
+      case "6":
+        return SourceVersion.RELEASE_6;
+      case "1.7":
+      case "7":
+        return SourceVersion.RELEASE_7;
+      case "1.8":
+      case "8":
+        return SourceVersion.RELEASE_8;
+      case "9":
+        return SourceVersion.RELEASE_9;
+      case "10":
+        return SourceVersion.RELEASE_10;
+      case "11":
+        return SourceVersion.RELEASE_11;
+      case "17":
+        return SourceVersion.RELEASE_17;
+      case "21":
+        return SourceVersion.RELEASE_21;
+      default:
+        throw new RuntimeException(String.format("target %s not supported", target));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/BUCK
@@ -0,0 +1,28 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+KOTLIN_USE_OLD_VERSION = False
+
+buck_java_library(
+    name = "kotlin",
+    srcs = (["kotlin-1.4.2/KotlinMetadataReader.java"] if KOTLIN_USE_OLD_VERSION else ["KotlinMetadataReader.java"]) + ["InlineFunctionScope.java"],
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi:abi",
+    ],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi:abi",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:asm",
+        "prelude//toolchains/android/third-party:kotlin-metadata-jvm",
+        "prelude//toolchains/android/third-party:kotlin-stdlib",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/InlineFunctionScope.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/InlineFunctionScope.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/InlineFunctionScope.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.kotlin;
+
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import org.objectweb.asm.tree.ClassNode;
+
+/**
+ * Kotlin has the concept of "inline functions", which are guaranteed to be inlined into their call-
+ * -sites, even across JARs. To make this work, we need to retain more in the ABIs of Kotlin JARs:
+ *
+ * <p>- The body (bytecode) of inline functions which is what `kotlinc` bases the code it inlines
+ * on. - Nested classes defined within inline functions. Rather than referring to those classes in
+ * the defining JAR, they are duplicated in the calling JAR, and so their implementation details
+ * cannot be stripped either.
+ *
+ * <p>This class keeps track of Kotlin class' inline functions, and classes that are nested inside
+ * inline functions (or nested inside classes that are nested inside inline functions, and so on,
+ * transitively).
+ */
+public final class InlineFunctionScope {
+  private static final String DEFAULT_METHOD_SUFFIX = "$default";
+  private static final int DEFAULT_METHOD_SUFFIX_LENGTH = DEFAULT_METHOD_SUFFIX.length();
+
+  /**
+   * Maps from class names (canonical names, formatted as paths, i.e. parts separated by `/`, not
+   * `.`) to sets of their inline functions.
+   */
+  private Map<String, Set<String>> inlineFunctionsMap = new HashMap<>();
+
+  /** Classes within inline scopes, transitively (formatted same as [inlineFunctionsMap] keys) */
+  private Set<String> nestedInlineScopes = new HashSet<>();
+
+  /**
+   * Add a new set of inline scopes, from [inlineFunctions] that are part of [clazz]. Note that if
+   * {@code inlineFunctions.isEmpty()}, nothing is added, and if there are existing scopes added for
+   * [clazz], those are updated (extended) to include the new inline functions.
+   *
+   * @param clazz Canonical class name, formatted as a path.
+   * @param inlineFunctions Collection of simple method names.
+   */
+  public void createScopes(String clazz, Collection<String> inlineFunctions) {
+    if (!inlineFunctions.isEmpty()) {
+      this.inlineFunctionsMap.computeIfAbsent(clazz, c -> new HashSet<>()).addAll(inlineFunctions);
+    }
+  }
+
+  /** Indicate that [clazz] was defined nested within the scope of an inline function */
+  public void extendScope(String clazz) {
+    nestedInlineScopes.add(clazz);
+  }
+
+  /**
+   * Determine whether a class is captured by an inline scope recorded in this instance. This
+   * implies all its contents should be retained in the ABI of the JAR the defines these inline
+   * function scopes, and the class in question should be added to the set of scopes (but this needs
+   * to be done separately -- it is not a side-effect of this method).
+   *
+   * @param path The class' canonical name, formatted as a path, without the ".class" prefix.
+   * @param classNode ASM representation of the class referred to by [path], (no code needed).
+   * @return true if and only if this class is entirely captured by the ABI associated with this set
+   *     of inline function scopes.
+   */
+  public boolean captures(Path path, ClassNode classNode) {
+    // Classes whose names contain "$sam$i" are created as wrappers when SAM interfaces are
+    // implemented by Kotlin Lambdas.  This can happen within inline functions, and in those cases,
+    // like other nested classes, they will be duplicated in the calling context.  But unlike other
+    // nested classes, these are not recorded as inner classes in the JAR, so we need to treat them
+    // specially.
+    //
+    // TODO This is a pessimisation: not all "$sam$i" classes need to be retained, we can do better
+    //  by tracking the ones that are referenced from inline functions.
+    if (path.toString().contains("$sam$i")) {
+      return true;
+    }
+
+    if (classNode.outerClass == null) {
+      return false;
+    }
+
+    if (nestedInlineScopes.contains(classNode.outerClass)) {
+      return true;
+    }
+
+    Set<String> inlineFunctions = inlineFunctionsMap.get(classNode.outerClass);
+    if (inlineFunctions == null || classNode.outerMethod == null) {
+      return false;
+    }
+
+    return inlineFunctions.contains(sanitizeMethodName(classNode.outerMethod));
+  }
+
+  private static String sanitizeMethodName(String methodName) {
+    if (methodName.endsWith(DEFAULT_METHOD_SUFFIX)) {
+      return methodName.substring(0, methodName.length() - DEFAULT_METHOD_SUFFIX_LENGTH);
+    }
+
+    return methodName;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/KotlinMetadataReader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/KotlinMetadataReader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/KotlinMetadataReader.java
@@ -0,0 +1,207 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.kotlin;
+
+import com.google.common.collect.ImmutableList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Stream;
+import kotlin.Metadata;
+import kotlin.metadata.Attributes;
+import kotlin.metadata.KmClass;
+import kotlin.metadata.KmDeclarationContainer;
+import kotlin.metadata.KmProperty;
+import kotlin.metadata.Visibility;
+import kotlin.metadata.jvm.JvmExtensionsKt;
+import kotlin.metadata.jvm.JvmMetadataUtil;
+import kotlin.metadata.jvm.JvmMethodSignature;
+import kotlin.metadata.jvm.KotlinClassMetadata;
+import org.objectweb.asm.tree.AnnotationNode;
+
+/** Utilities to read Kotlin class metadata. */
+public class KotlinMetadataReader {
+
+  /**
+   * Opaque handle to parsed Kotlin metadata. Callers should obtain this via {@link #readMetadata}
+   * and pass it to {@link #getInlineFunctions} and {@link #isFilePrivateClass} to avoid redundant
+   * parsing.
+   */
+  public static final class ParsedMetadata {
+    final KotlinClassMetadata metadata;
+
+    ParsedMetadata(KotlinClassMetadata metadata) {
+      this.metadata = metadata;
+    }
+  }
+
+  /**
+   * Parses the @kotlin.Metadata annotation into a reusable handle. Call once and pass the result to
+   * both {@link #getInlineFunctions} and {@link #isFilePrivateClass}.
+   */
+  public static ParsedMetadata readMetadata(AnnotationNode annotationNode) {
+    Metadata classHeader = createHeader(annotationNode);
+    KotlinClassMetadata metadata = KotlinClassMetadata.readStrict(classHeader);
+    if (metadata == null) {
+      throw new AssertionError(
+          "Unsupported kind of Kotlin classes: ["
+              + classHeader.k()
+              + "] or has an unsupported metadata version: ["
+              + Arrays.toString(classHeader.mv())
+              + "]");
+    }
+    return new ParsedMetadata(metadata);
+  }
+
+  /**
+   * Finds the inline functions of a Kotlin class from its parsed metadata.
+   *
+   * @param parsed the result of {@link #readMetadata}
+   */
+  public static ImmutableList<String> getInlineFunctions(ParsedMetadata parsed) {
+    KotlinClassMetadata metadata = parsed.metadata;
+    KmDeclarationContainer container;
+    if (metadata instanceof KotlinClassMetadata.Class) {
+      container = ((KotlinClassMetadata.Class) metadata).getKmClass();
+    } else if (metadata instanceof KotlinClassMetadata.FileFacade) {
+      container = ((KotlinClassMetadata.FileFacade) metadata).getKmPackage();
+    } else if (metadata instanceof KotlinClassMetadata.MultiFileClassPart) {
+      container = ((KotlinClassMetadata.MultiFileClassPart) metadata).getKmPackage();
+    } else {
+      return ImmutableList.of();
+    }
+
+    ImmutableList<String> inlineFunctions =
+        container.getFunctions().stream()
+            .filter(Attributes::isInline)
+            .map(JvmExtensionsKt::getSignature)
+            .filter(Objects::nonNull)
+            .map(JvmMethodSignature::getName)
+            .collect(ImmutableList.toImmutableList());
+
+    ImmutableList<String> inlineProperties =
+        container.getProperties().stream()
+            .filter(
+                it ->
+                    Attributes.isInline(it.getGetter())
+                        || it.getSetter() != null && Attributes.isInline(it.getSetter()))
+            .map(KmProperty::getName)
+            .collect(ImmutableList.toImmutableList());
+
+    ImmutableList<String> inlineGetters =
+        container.getProperties().stream()
+            .filter(it -> Attributes.isInline(it.getGetter()))
+            .map(JvmExtensionsKt::getGetterSignature)
+            .filter(Objects::nonNull)
+            .map(JvmMethodSignature::getName)
+            .collect(ImmutableList.toImmutableList());
+
+    ImmutableList<String> inlineSetters =
+        container.getProperties().stream()
+            .filter(it -> it.getSetter() != null && Attributes.isInline(it.getSetter()))
+            .map(JvmExtensionsKt::getSetterSignature)
+            .filter(Objects::nonNull)
+            .map(JvmMethodSignature::getName)
+            .collect(ImmutableList.toImmutableList());
+
+    return Stream.of(inlineFunctions, inlineProperties, inlineGetters, inlineSetters)
+        .flatMap(Collection::stream)
+        .distinct()
+        .sorted()
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  /**
+   * Checks if a Kotlin class is file-private (declared with `private` visibility at the file
+   * level). Such classes are compiled to package-private in bytecode, so they pass the standard
+   * ACC_PRIVATE check, but they should NOT be included in class-abi since they are not part of the
+   * module's public API. Source-only-abi correctly excludes them; this method enables class-abi to
+   * match that behavior.
+   *
+   * @param parsed the result of {@link #readMetadata}
+   */
+  public static boolean isFilePrivateClass(ParsedMetadata parsed) {
+    KotlinClassMetadata metadata = parsed.metadata;
+    if (metadata instanceof KotlinClassMetadata.Class) {
+      KmClass kmClass = ((KotlinClassMetadata.Class) metadata).getKmClass();
+      if (Attributes.getVisibility(kmClass) != Visibility.PRIVATE) {
+        return false;
+      }
+      // Distinguish file-private top-level classes from private inner/nested classes.
+      // In Kotlin metadata, inner classes use '.' as a separator (e.g. "com/example/Outer.Inner"),
+      // while top-level classes have no '.' after the last '/' (e.g. "com/example/TopLevel").
+      String className = kmClass.getName();
+      int lastSlash = className.lastIndexOf('/');
+      String simpleName = lastSlash >= 0 ? className.substring(lastSlash + 1) : className;
+      return !simpleName.contains(".");
+    }
+    return false;
+  }
+
+  /**
+   * Converts the given AnnotationNode representing the @kotlin.Metadata annotation into
+   * KotlinClassHeader, to be able to use it in KotlinClassMetadata.read.
+   */
+  private static Metadata createHeader(AnnotationNode node) {
+    Integer kind = null;
+    int[] metadataVersion = null;
+    String[] data1 = null;
+    String[] data2 = null;
+    String extraString = null;
+    String packageName = null;
+    Integer extraInt = null;
+
+    Iterator<Object> it = node.values.iterator();
+    while (it.hasNext()) {
+      String name = (String) it.next();
+      Object value = it.next();
+
+      switch (name) {
+        case "k":
+          kind = (Integer) value;
+          break;
+        case "mv":
+          metadataVersion = listToIntArray(value);
+          break;
+        case "d1":
+          data1 = listToStringArray(value);
+          break;
+        case "d2":
+          data2 = listToStringArray(value);
+          break;
+        case "xs":
+          extraString = (String) value;
+          break;
+        case "pn":
+          packageName = (String) value;
+          break;
+        case "xi":
+          extraInt = (Integer) value;
+          break;
+      }
+    }
+
+    return JvmMetadataUtil.Metadata(
+        kind, metadataVersion, data1, data2, extraString, packageName, extraInt);
+  }
+
+  @SuppressWarnings("unchecked")
+  private static int[] listToIntArray(Object list) {
+    return ((List<Integer>) list).stream().mapToInt(i -> i).toArray();
+  }
+
+  @SuppressWarnings("unchecked")
+  private static String[] listToStringArray(Object list) {
+    return ((List<String>) list).toArray(new String[0]);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/kotlin-1.4.2/KotlinMetadataReader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/kotlin-1.4.2/KotlinMetadataReader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin/kotlin-1.4.2/KotlinMetadataReader.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.kotlin;
+
+import com.google.common.collect.ImmutableList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Stream;
+import kotlinx.metadata.Flag;
+import kotlinx.metadata.KmDeclarationContainer;
+import kotlinx.metadata.KmProperty;
+import kotlinx.metadata.jvm.JvmExtensionsKt;
+import kotlinx.metadata.jvm.JvmMethodSignature;
+import kotlinx.metadata.jvm.KotlinClassHeader;
+import kotlinx.metadata.jvm.KotlinClassMetadata;
+import org.objectweb.asm.tree.AnnotationNode;
+
+/** Utilities to read Kotlin class metadata. */
+public class KotlinMetadataReader {
+
+  /**
+   * Method to find the inline functions of a Kotlin class by finding the Kotlin metadata annotation
+   * and reading it.
+   */
+  public static ImmutableList<String> getInlineFunctions(AnnotationNode annotationNode) {
+    KotlinClassHeader classHeader = createHeader(annotationNode);
+    KotlinClassMetadata metadata = KotlinClassMetadata.read(classHeader);
+    if (metadata == null) {
+      throw new AssertionError(
+          "Unsupported kind of Kotlin classes: ["
+              + classHeader.k()
+              + "] or has an unsupported metadata version: ["
+              + Arrays.toString(classHeader.mv())
+              + "]");
+    }
+
+    KmDeclarationContainer container;
+    if (metadata instanceof KotlinClassMetadata.Class) {
+      container = ((KotlinClassMetadata.Class) metadata).toKmClass();
+    } else if (metadata instanceof KotlinClassMetadata.FileFacade) {
+      container = ((KotlinClassMetadata.FileFacade) metadata).toKmPackage();
+    } else if (metadata instanceof KotlinClassMetadata.MultiFileClassPart) {
+      container = ((KotlinClassMetadata.MultiFileClassPart) metadata).toKmPackage();
+    } else {
+      return ImmutableList.of();
+    }
+
+    ImmutableList<String> inlineFunctions =
+        container.getFunctions().stream()
+            .filter(it -> Flag.Function.IS_INLINE.invoke(it.getFlags()))
+            .map(JvmExtensionsKt::getSignature)
+            .filter(Objects::nonNull)
+            .map(JvmMethodSignature::getName)
+            .collect(ImmutableList.toImmutableList());
+
+    ImmutableList<String> inlineProperties =
+        container.getProperties().stream()
+            .filter(it -> Flag.PropertyAccessor.IS_INLINE.invoke(it.getFlags()))
+            .map(KmProperty::getName)
+            .collect(ImmutableList.toImmutableList());
+
+    ImmutableList<String> inlineGetters =
+        container.getProperties().stream()
+            .filter(it -> Flag.PropertyAccessor.IS_INLINE.invoke(it.getGetterFlags()))
+            .map(JvmExtensionsKt::getGetterSignature)
+            .filter(Objects::nonNull)
+            .map(JvmMethodSignature::getName)
+            .collect(ImmutableList.toImmutableList());
+
+    ImmutableList<String> inlineSetters =
+        container.getProperties().stream()
+            .filter(it -> Flag.PropertyAccessor.IS_INLINE.invoke(it.getSetterFlags()))
+            .map(JvmExtensionsKt::getSetterSignature)
+            .filter(Objects::nonNull)
+            .map(JvmMethodSignature::getName)
+            .collect(ImmutableList.toImmutableList());
+
+    return Stream.of(inlineFunctions, inlineProperties, inlineGetters, inlineSetters)
+        .flatMap(Collection::stream)
+        .distinct()
+        .sorted()
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  /**
+   * Converts the given AnnotationNode representing the @kotlin.Metadata annotation into
+   * KotlinClassHeader, to be able to use it in KotlinClassMetadata.read.
+   */
+  private static KotlinClassHeader createHeader(AnnotationNode node) {
+    Integer kind = null;
+    int[] metadataVersion = null;
+    String[] data1 = null;
+    String[] data2 = null;
+    String extraString = null;
+    String packageName = null;
+    Integer extraInt = null;
+
+    Iterator<Object> it = node.values.iterator();
+    while (it.hasNext()) {
+      String name = (String) it.next();
+      Object value = it.next();
+
+      switch (name) {
+        case "k":
+          kind = (Integer) value;
+          break;
+        case "mv":
+          metadataVersion = listToIntArray(value);
+          break;
+        case "d1":
+          data1 = listToStringArray(value);
+          break;
+        case "d2":
+          data2 = listToStringArray(value);
+          break;
+        case "xs":
+          extraString = (String) value;
+          break;
+        case "pn":
+          packageName = (String) value;
+          break;
+        case "xi":
+          extraInt = (Integer) value;
+          break;
+      }
+    }
+
+    return new KotlinClassHeader(
+        kind, metadataVersion, data1, data2, extraString, packageName, extraInt);
+  }
+
+  @SuppressWarnings("unchecked")
+  private static int[] listToIntArray(Object list) {
+    return ((List<Integer>) list).stream().mapToInt(i -> i).toArray();
+  }
+
+  @SuppressWarnings("unchecked")
+  private static String[] listToStringArray(Object list) {
+    return ((List<String>) list).toArray(new String[0]);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotatedConstruct.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotatedConstruct.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotatedConstruct.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.List;
+import javax.lang.model.AnnotatedConstruct;
+
+/**
+ * Interface for {@link AnnotatedConstruct}s that are implemented by something other than javac
+ * itself.
+ */
+interface ArtificialAnnotatedConstruct extends AnnotatedConstruct {
+  // TODO(jkeljo): I think we should be able to sometimes use the real annotation mirrors
+  @Override
+  List<? extends ArtificialAnnotationMirror> getAnnotationMirrors();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotationMirror.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotationMirror.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotationMirror.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import javax.lang.model.element.AnnotationMirror;
+
+/**
+ * Interface for {@link AnnotationMirror}s that are implemented by something other than javac
+ * itself.
+ */
+interface ArtificialAnnotationMirror extends AnnotationMirror {}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotationValue.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotationValue.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialAnnotationValue.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import javax.lang.model.element.AnnotationValue;
+
+/**
+ * Interface for {@link AnnotationValue}s that are implemented by something other than javac itself.
+ */
+interface ArtificialAnnotationValue extends AnnotationValue {}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialElement.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.util.List;
+import javax.lang.model.element.Element;
+
+/** Interface for {@link Element}s that are implemented by something other than javac itself. */
+interface ArtificialElement extends Element {
+  @Override
+  @Nullable
+  ArtificialElement getEnclosingElement();
+
+  @Override
+  List<? extends Element> getEnclosedElements();
+
+  void addEnclosedElement(Element element);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialExecutableElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialExecutableElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialExecutableElement.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.List;
+import javax.lang.model.element.ExecutableElement;
+
+/**
+ * Interface for {@link ExecutableElement}s that are implemented by something other than javac
+ * itself.
+ */
+interface ArtificialExecutableElement extends ExecutableElement, ArtificialParameterizable {
+  @Override
+  List<? extends ArtificialVariableElement> getParameters();
+
+  // TODO(jkeljo): We should be able to sometimes use the real AnnotationValue, much like we
+  // sometimes use real TypeMirrors
+  @Override
+  ArtificialAnnotationValue getDefaultValue();
+
+  @Override
+  List<? extends ArtificialElement> getEnclosedElements();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialPackageElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialPackageElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialPackageElement.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import javax.lang.model.element.PackageElement;
+
+/**
+ * Interface for {@link PackageElement}s that are implemented by something other than javac itself.
+ */
+interface ArtificialPackageElement
+    extends PackageElement, ArtificialElement, ArtificialQualifiedNameable {}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialParameterizable.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialParameterizable.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialParameterizable.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.List;
+import javax.lang.model.element.Parameterizable;
+
+/**
+ * Interface for {@link Parameterizable}s that are implemented by something other than javac itself.
+ */
+interface ArtificialParameterizable extends Parameterizable, ArtificialElement {
+  @Override
+  List<? extends ArtificialTypeParameterElement> getTypeParameters();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialQualifiedNameable.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialQualifiedNameable.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialQualifiedNameable.java
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import javax.lang.model.element.QualifiedNameable;
+
+/** Interface for {@link QualifiedNameable}s that are implemented by something other than javac. */
+interface ArtificialQualifiedNameable extends QualifiedNameable, ArtificialElement {}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialTypeElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialTypeElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialTypeElement.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.List;
+import javax.lang.model.element.TypeElement;
+
+/** Interface for {@link TypeElement}s that are implemented by something other than javac itself. */
+interface ArtificialTypeElement
+    extends ArtificialElement, ArtificialParameterizable, ArtificialQualifiedNameable, TypeElement {
+  @Override
+  List<? extends ArtificialElement> getEnclosedElements();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialTypeParameterElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialTypeParameterElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialTypeParameterElement.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.List;
+import javax.lang.model.element.TypeParameterElement;
+
+/**
+ * Interface for {@link TypeParameterElement}s that are implemented by something other than javac
+ * itself.
+ */
+interface ArtificialTypeParameterElement extends TypeParameterElement, ArtificialElement {
+  @Override
+  List<? extends ArtificialElement> getEnclosedElements();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialVariableElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialVariableElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ArtificialVariableElement.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.List;
+import javax.lang.model.element.VariableElement;
+
+/**
+ * Interface for {@link VariableElement}s that are implemented by something other than javac itself.
+ */
+interface ArtificialVariableElement extends VariableElement, ArtificialElement {
+  @Override
+  List<? extends ArtificialElement> getEnclosedElements();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/BUCK
@@ -0,0 +1,34 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "source",
+    srcs = glob(["*.java"]),
+    provided_deps = [
+        # Interface-only api module for communicating back to Buck core, also loaded by the bootstrapper
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api:api",
+        # Another interface-only api module for communicating back to Buck core, also loaded by the bootstrapper
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/api:api",
+    ],
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi/source:source",
+    ],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin:javac-plugin",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi:abi",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi/source:source",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi/source:testutil",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/testutil/compiler:compiler",
+    ],
+    deps = [
+        # This module is loaded as a plugin into the compiler itself; don't take dependencies on Buck
+        # internals (outside of stuff designed for use in plugins) or large libraries like Guava
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/lang/model:model",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter:adapter",
+        "prelude//toolchains/android/src/com/facebook/buck/util/liteinfersupport:liteinfersupport",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompilerErrorException.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompilerErrorException.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompilerErrorException.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+/**
+ * Thrown when an error in source code is detected in a place that doesn't have enough context to
+ * report a graceful compiler error. Caught at a higher level, where the message is reported as a
+ * compiler error with relevant context.
+ */
+class CompilerErrorException extends Exception {
+  public CompilerErrorException(String message) {
+    super(message);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompilerTypeResolutionSimulator.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompilerTypeResolutionSimulator.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompilerTypeResolutionSimulator.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.lang.model.MoreElements;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.facebook.buck.util.liteinfersupport.PropagatesNullable;
+import com.sun.source.tree.AnnotatedTypeTree;
+import com.sun.source.tree.IdentifierTree;
+import com.sun.source.tree.MemberSelectTree;
+import com.sun.source.tree.ParameterizedTypeTree;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.TreePathScanner;
+import com.sun.source.util.Trees;
+import java.util.HashSet;
+import java.util.Set;
+import javax.lang.model.element.NestingKind;
+import javax.lang.model.element.TypeElement;
+
+/**
+ * Simulates how {@code javac} resolves types, at least so far as to determine whether a given
+ * resolution would succeed or not under source-only ABI.
+ */
+class CompilerTypeResolutionSimulator {
+
+  private final Trees trees;
+  private final FileManagerSimulator fileManager;
+  private final CompletionSimulator completer;
+
+  @Nullable private ImportsTracker imports = null;
+
+  public CompilerTypeResolutionSimulator(Trees trees, FileManagerSimulator fileManager) {
+    this.trees = trees;
+    this.fileManager = fileManager;
+    this.completer = new CompletionSimulator(fileManager);
+  }
+
+  public void setImports(ImportsTracker imports) {
+    this.imports = imports;
+  }
+
+  public ResolvedType resolve(@PropagatesNullable TreePath referencingPath) {
+    if (referencingPath == null) {
+      return null;
+    }
+
+    return new TreePathScanner<ResolvedType, Void>() {
+      @Override
+      public ResolvedType visitAnnotatedType(AnnotatedTypeTree node, Void aVoid) {
+        return scan(node.getUnderlyingType(), aVoid);
+      }
+
+      @Override
+      public ResolvedType visitParameterizedType(ParameterizedTypeTree node, Void aVoid) {
+        return scan(node.getType(), aVoid);
+      }
+
+      @Override
+      public ResolvedType visitIdentifier(IdentifierTree node, Void aVoid) {
+        TypeElement typeElement = (TypeElement) trees.getElement(getCurrentPath());
+        return newResolvedType(typeElement);
+      }
+
+      private ResolvedType newResolvedType(TypeElement typeElement) {
+        ResolvedTypeKind kind = ResolvedTypeKind.RESOLVED_TYPE;
+        Set<String> missingDependencies = new HashSet<>();
+
+        if (!fileManager.typeWillBeAvailable(typeElement)) {
+          kind = ResolvedTypeKind.ERROR_TYPE;
+          missingDependencies.add(fileManager.getOwningTarget(typeElement));
+        }
+
+        return new ResolvedType(kind, typeElement, missingDependencies);
+      }
+
+      @Override
+      public ResolvedType visitMemberSelect(MemberSelectTree node, Void aVoid) {
+        TypeElement type = (TypeElement) trees.getElement(getCurrentPath());
+        return new Object() {
+          private ResolvedTypeKind kind = ResolvedTypeKind.RESOLVED_TYPE;
+          private final Set<String> missingDependencies = new HashSet<>();
+
+          {
+            CompletionSimulator.CompletedType completedType = completer.complete(type, false);
+            if (completedType.kind != CompletedTypeKind.COMPLETED_TYPE) {
+              kind = kind.merge(ResolvedTypeKind.ERROR_TYPE);
+              missingDependencies.addAll(completedType.getMissingDependencies());
+            }
+          }
+
+          public ResolvedType resolve() {
+            if (type.getNestingKind() != NestingKind.TOP_LEVEL) {
+              ResolvedType referencedEnclosingType = scan(node.getExpression(), aVoid);
+              missingDependencies.addAll(referencedEnclosingType.missingDependencies);
+              resolveMemberType(type, referencedEnclosingType.type);
+
+              if (referencedEnclosingType.kind == ResolvedTypeKind.ERROR_TYPE) {
+                // If the originally referenced enclosing type was not found, the compiler would
+                // actually have stopped right there. We kept going because we wanted to get all
+                // the things that would be necessary to convert that error type into a resolved
+                // type
+                kind = ResolvedTypeKind.ERROR_TYPE;
+              }
+            }
+            return new ResolvedType(kind, type, missingDependencies);
+          }
+
+          private boolean resolveMemberType(
+              TypeElement type, @Nullable TypeElement referencedEnclosingType) {
+            if (referencedEnclosingType == null) {
+              // Ran out of places to look
+              return false;
+            }
+
+            if (type.getEnclosingElement() == referencedEnclosingType) {
+              // Found it!
+              return true;
+            }
+
+            TypeElement superclass = MoreElements.getSuperclass(referencedEnclosingType);
+            markAsCrashIfNotResolvable(superclass);
+            if (resolveMemberType(type, superclass)) {
+              return true;
+            }
+
+            Iterable<TypeElement> interfaces =
+                MoreElements.getInterfaces(referencedEnclosingType)::iterator;
+            for (TypeElement interfaceElement : interfaces) {
+              markAsCrashIfNotResolvable(interfaceElement);
+              if (resolveMemberType(type, interfaceElement)) {
+                return true;
+              }
+            }
+
+            return false;
+          }
+
+          private void markAsCrashIfNotResolvable(@Nullable TypeElement type) {
+            if (type == null) {
+              return;
+            }
+
+            CompletionSimulator.CompletedType completedType = completer.complete(type, false);
+            if (completedType.kind != CompletedTypeKind.COMPLETED_TYPE) {
+              kind = kind.merge(ResolvedTypeKind.CRASH);
+              missingDependencies.addAll(completedType.getMissingDependencies());
+            }
+          }
+        }.resolve();
+      }
+    }.scan(referencingPath, null);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompletedTypeKind.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompletedTypeKind.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompletedTypeKind.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+public enum CompletedTypeKind {
+  COMPLETED_TYPE,
+  PARTIALLY_COMPLETED_TYPE,
+  ERROR_TYPE,
+  CRASH;
+
+  public CompletedTypeKind merge(CompletedTypeKind other) {
+    if (this.compareTo(other) >= 0) {
+      return this;
+    }
+
+    return other;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompletionSimulator.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompletionSimulator.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/CompletionSimulator.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * Simulates {@code javac}'s symbol completion logic for a given type under the source-only ABI
+ * classpath to determine what would be required for it to succeed.
+ */
+class CompletionSimulator {
+
+  private final FileManagerSimulator fileManager;
+
+  public CompletionSimulator(FileManagerSimulator fileManager) {
+    this.fileManager = fileManager;
+  }
+
+  @Nullable
+  public CompletedType complete(Element element, boolean transitive) {
+    ElementKind kind = element.getKind();
+    if (!kind.isClass() && !kind.isInterface()) {
+      return null;
+    }
+
+    return complete((TypeElement) element, transitive);
+  }
+
+  public CompletedType complete(TypeElement type, boolean transitive) {
+    return new CompletedType(type, transitive);
+  }
+
+  @Nullable
+  private CompletedType complete(TypeMirror type, boolean transitive) {
+    if (type.getKind() != TypeKind.DECLARED) {
+      return null;
+    }
+
+    DeclaredType declaredType = (DeclaredType) type;
+    TypeElement element = (TypeElement) declaredType.asElement();
+    return complete(element, transitive);
+  }
+
+  public class CompletedType {
+
+    public final TypeElement element;
+    @Nullable public final CompletedType enclosingType;
+    @Nullable public final CompletedType superclass;
+    public final List<CompletedType> interfaces;
+    public final CompletedTypeKind kind;
+
+    @Nullable private List<String> missingDependencies = null;
+
+    private CompletedType(TypeElement element, boolean transitive) {
+      this.element = element;
+      enclosingType = complete(element.getEnclosingElement(), transitive);
+
+      if (transitive) {
+        superclass = complete(element.getSuperclass(), transitive);
+        interfaces =
+            element.getInterfaces().stream()
+                .map(it -> complete(it, transitive))
+                .filter(Objects::nonNull)
+                .collect(Collectors.toList());
+      } else {
+        superclass = null;
+        interfaces = Collections.emptyList();
+      }
+
+      this.kind = computeKind();
+    }
+
+    private CompletedTypeKind computeKind() {
+      CompletedTypeKind kind = CompletedTypeKind.COMPLETED_TYPE;
+      if (!fileManager.typeWillBeAvailable(element)) {
+        kind = CompletedTypeKind.ERROR_TYPE;
+      }
+      if (enclosingType != null) {
+        kind = enclosingType.kind;
+      }
+      if (kind == CompletedTypeKind.ERROR_TYPE) {
+        return kind;
+      }
+
+      kind =
+          kind.merge(
+              superAndInterfacesStream()
+                  .map(type -> type.kind)
+                  .map(
+                      typeKind -> {
+                        if (typeKind != CompletedTypeKind.ERROR_TYPE) {
+                          return typeKind;
+                        }
+                        return fileManager.isCompiledInCurrentRun(element)
+                            ? CompletedTypeKind.PARTIALLY_COMPLETED_TYPE
+                            : CompletedTypeKind.CRASH;
+                      })
+                  .reduce(CompletedTypeKind.COMPLETED_TYPE, CompletedTypeKind::merge));
+      return kind;
+    }
+
+    private boolean superclassesMayBeMissing() {
+      return fileManager.isCompiledInCurrentRun(element);
+    }
+
+    /**
+     * Returns the list of build target dependencies that must be added so that completion can get
+     * one level further with this element. That is, move from {@link CompletedTypeKind#CRASH}/
+     * {@link CompletedTypeKind#ERROR_TYPE} to {@link CompletedTypeKind#PARTIALLY_COMPLETED_TYPE},
+     * or from {@link CompletedTypeKind#PARTIALLY_COMPLETED_TYPE} to {@link
+     * CompletedTypeKind#COMPLETED_TYPE}.
+     */
+    public List<String> getMissingDependencies() {
+      if (missingDependencies == null) {
+        missingDependencies = new ArrayList<>();
+
+        if (kind == CompletedTypeKind.ERROR_TYPE) {
+          // Realistically the only way we get to be an error type is if our class itself is
+          // missing.
+          missingDependencies.add(fileManager.getOwningTarget(element));
+        }
+
+        // Our kind will always be at least as "bad" as our enclosing type, so if it's holding
+        // us back we must move it forward too.
+        if (enclosingType != null && enclosingType.kind == kind) {
+          missingDependencies.addAll(enclosingType.getMissingDependencies());
+        }
+
+        superAndInterfacesStream()
+            .filter(
+                supertype -> {
+                  if (kind == CompletedTypeKind.PARTIALLY_COMPLETED_TYPE) {
+                    // If this type is partially completed, it's because supers are missing, so we
+                    // want to fill in their missing deps.
+                    return true;
+                  } else if (kind == CompletedTypeKind.COMPLETED_TYPE) {
+                    // Small optimization -- if this type is completed, there are no missing deps by
+                    // definition.
+                    return false;
+                  } else if (!superclassesMayBeMissing()
+                      && supertype.kind == CompletedTypeKind.ERROR_TYPE) {
+                    // If this type is crashing due to missing supers, we want it to stop
+                    // If it's an error type, we don't want it to start crashing due to missing
+                    // supers
+                    // once it becomes available.
+                    return true;
+                  }
+
+                  // Any crash of a supertype will crash the immediate subtype, so we want to add
+                  // deps to prevent that
+                  return supertype.kind == CompletedTypeKind.CRASH;
+                })
+            .map(CompletedType::getMissingDependencies)
+            .forEach(missingDependencies::addAll);
+      }
+
+      return missingDependencies;
+    }
+
+    private Stream<CompletedType> superAndInterfacesStream() {
+      return Stream.concat(Stream.of(superclass), interfaces.stream()).filter(Objects::nonNull);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ElementTreeFinder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ElementTreeFinder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ElementTreeFinder.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.BlockTree;
+import com.sun.source.tree.ClassTree;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.MethodTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.tree.TypeParameterTree;
+import com.sun.source.tree.VariableTree;
+import com.sun.source.util.TreePathScanner;
+import com.sun.source.util.Trees;
+import java.util.HashMap;
+import java.util.Map;
+import javax.lang.model.element.Element;
+
+/**
+ * This class is more complete than {@link Trees#getTree(Element)} in that it will return a tree for
+ * method and type parameters. It is also faster for doing a lot of lookups within a given
+ * compilation unit.
+ */
+class ElementTreeFinder {
+
+  public static ElementTreeFinder forCompilationUnit(CompilationUnitTree tree, Trees trees) {
+    // Trees.getTree, in addition to being blind to method and type parameters, does an expensive
+    // linear-time iteration whenever asked for a tree for a method or variable. We scan the trees
+    // once using the much cheaper Trees.getElement and build a map.
+    Map<Element, Tree> elementToTreeMap = new HashMap<>();
+    new TreePathScanner<Void, Void>() {
+      @Override
+      public Void visitClass(ClassTree node, Void aVoid) {
+        elementToTreeMap.put(trees.getElement(getCurrentPath()), node);
+        return super.visitClass(node, aVoid);
+      }
+
+      @Override
+      public Void visitMethod(MethodTree node, Void aVoid) {
+        elementToTreeMap.put(trees.getElement(getCurrentPath()), node);
+        return super.visitMethod(node, aVoid);
+      }
+
+      @Override
+      public Void visitVariable(VariableTree node, Void aVoid) {
+        elementToTreeMap.put(trees.getElement(getCurrentPath()), node);
+        // Don't recurse into variable initializers
+        return null;
+      }
+
+      @Override
+      public Void visitTypeParameter(TypeParameterTree node, Void aVoid) {
+        elementToTreeMap.put(trees.getElement(getCurrentPath()), node);
+        return super.visitTypeParameter(node, aVoid);
+      }
+
+      @Override
+      public Void visitBlock(BlockTree node, Void aVoid) {
+        // Don't recurse into method bodies
+        return null;
+      }
+    }.scan(tree, null);
+
+    return new ElementTreeFinder(elementToTreeMap);
+  }
+
+  private final Map<Element, Tree> elementToTreeMap;
+
+  private ElementTreeFinder(Map<Element, Tree> elementToTreeMap) {
+    this.elementToTreeMap = elementToTreeMap;
+  }
+
+  @Nullable
+  public Tree getTree(Element element) {
+    return elementToTreeMap.get(element);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/EnteringPlugin.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/EnteringPlugin.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/EnteringPlugin.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.plugin.adapter.BuckJavacPlugin;
+import com.facebook.buck.jvm.java.plugin.adapter.BuckJavacTask;
+import com.sun.source.util.TaskEvent;
+import com.sun.source.util.TaskListener;
+
+/**
+ * Watches the phases of the compiler and keeps our parallel symbol table in sync. Put task
+ * listeners that need access to our symbol tables inside this one.
+ */
+class EnteringPlugin implements BuckJavacPlugin {
+  @Override
+  public String getName() {
+    return "EnteringPlugin";
+  }
+
+  @Override
+  public void init(BuckJavacTask task, String... args) {
+    FrontendOnlyJavacTask frontendTask = (FrontendOnlyJavacTask) task;
+    task.addTaskListener(
+        new EnteringTaskListener(
+            frontendTask.getElements(), frontendTask.getTypes(), frontendTask.getTrees()));
+  }
+
+  private static class EnteringTaskListener implements TaskListener {
+    private final TreeBackedElements elements;
+    private final TreeBackedTrees trees;
+    private final TreeBackedEnter enter;
+    private int classesEnteredThisRound = 0;
+    private int entersInProgress = 0;
+
+    public EnteringTaskListener(
+        TreeBackedElements elements, TreeBackedTypes types, TreeBackedTrees trees) {
+      this.elements = elements;
+      this.trees = trees;
+      enter = new TreeBackedEnter(this.elements, types, this.trees.getJavacTrees());
+    }
+
+    @Override
+    public void started(TaskEvent e) {
+      if (e.getKind() == TaskEvent.Kind.ENTER) {
+        entersInProgress += 1;
+        if (classesEnteredThisRound == 0) {
+          // We want to clear our tables between rounds, and leave them intact after the last enter
+          // phase. However, javac sends the round start after the enter phase, so we must do some
+          // bookkeeping to detect the first enter event *after* a round and clear the table then.
+          elements.clear();
+          trees.clear();
+        }
+      }
+    }
+
+    @Override
+    public void finished(TaskEvent e) {
+      if (e.getKind() == TaskEvent.Kind.ENTER) {
+        enter.enter(e.getCompilationUnit());
+        classesEnteredThisRound += 1;
+        entersInProgress -= 1;
+
+        if (entersInProgress == 0) {
+          elements.complete();
+        }
+      } else if (e.getKind() == TaskEvent.Kind.ANNOTATION_PROCESSING_ROUND) {
+        // Reset counter for next round
+        classesEnteredThisRound = 0;
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FileManagerSimulator.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FileManagerSimulator.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FileManagerSimulator.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory.SourceOnlyAbiRuleInfo;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.util.Trees;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.Elements;
+
+/** Simulates the behavior of {@code javac}'s file manager for source-only ABI classpaths. */
+public class FileManagerSimulator {
+  private final Elements elements;
+  private final Trees trees;
+  private final SourceOnlyAbiRuleInfo ruleInfo;
+
+  public FileManagerSimulator(Elements elements, Trees trees, SourceOnlyAbiRuleInfo ruleInfo) {
+    this.elements = elements;
+    this.trees = trees;
+    this.ruleInfo = ruleInfo;
+  }
+
+  @Nullable
+  public String getOwningTarget(Element element) {
+    return ruleInfo.getOwningTarget(elements, element);
+  }
+
+  public boolean typeWillBeAvailable(TypeElement type) {
+    return isCompiledInCurrentRun(type)
+        || ruleInfo.elementIsAvailableForSourceOnlyAbi(elements, type);
+  }
+
+  public boolean isCompiledInCurrentRun(TypeElement typeElement) {
+    return trees.getTree(typeElement) != null;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FrontendOnlyJavacTask.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FrontendOnlyJavacTask.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FrontendOnlyJavacTask.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.abi.source.api.SourceCodeWillNotCompileException;
+import com.facebook.buck.jvm.java.abi.source.api.StopCompilation;
+import com.facebook.buck.jvm.java.plugin.adapter.BuckJavacTask;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.util.JavacTask;
+import com.sun.source.util.Trees;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+import javax.annotation.processing.Processor;
+import javax.lang.model.element.Element;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.Types;
+import javax.tools.JavaFileObject;
+
+/**
+ * An implementation of {@link JavacTask} that implements only the frontend portions of the task,
+ * using only the parse phase of the underlying compiler and without requiring a complete classpath.
+ * This effectively does the same thing as the Enter phase of the compiler (see
+ * http://openjdk.java.net/groups/compiler/doc/compilation-overview/index.html), but applying
+ * heuristics when dependencies are missing. This necessarily requires some assumptions to be made
+ * about references to symbols defined in those dependencies. See the documentation of {@link
+ * com.facebook.buck.jvm.java.abi.source} for details.
+ */
+public class FrontendOnlyJavacTask extends BuckJavacTask {
+  private final JavacTask javacTask;
+
+  @Nullable private TreeBackedElements elements;
+  @Nullable private TreeBackedTrees trees;
+  @Nullable private TreeBackedTypes types;
+
+  @Nullable private Iterable<? extends CompilationUnitTree> parsedCompilationUnits;
+  @Nullable private List<Element> topLevelElements;
+  private boolean stopCompilationAfterEnter = false;
+
+  public FrontendOnlyJavacTask(JavacTask task) {
+    super(task);
+    javacTask = task;
+
+    // Add the entering plugin first so that all other plugins and annotation processors will
+    // run with the TreeBackedElements already entered
+    addPlugin(new EnteringPlugin());
+  }
+
+  @Override
+  public Iterable<? extends CompilationUnitTree> parse() throws IOException {
+    if (parsedCompilationUnits == null) {
+      parsedCompilationUnits = javacTask.parse();
+    }
+
+    return parsedCompilationUnits;
+  }
+
+  @Override
+  public Iterable<? extends Element> enter() throws IOException {
+    Iterable<? extends Element> javacTopLevelElements = super.enter();
+
+    topLevelElements =
+        StreamSupport.stream(javacTopLevelElements.spliterator(), false)
+            .map(getElements()::getCanonicalElement)
+            .collect(Collectors.toList());
+
+    return topLevelElements;
+  }
+
+  @Override
+  public Iterable<? extends Element> analyze() {
+    throw new UnsupportedOperationException("Code analysis not supported");
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> generate() {
+    throw new UnsupportedOperationException("Code generation not supported");
+  }
+
+  @Override
+  public TypeMirror getTypeMirror(Iterable<? extends Tree> path) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public TreeBackedElements getElements() {
+    if (elements == null) {
+      initUtils();
+    }
+    return Objects.requireNonNull(elements);
+  }
+
+  @Override
+  public TreeBackedTrees getTrees() {
+    if (trees == null) {
+      initUtils();
+    }
+    return Objects.requireNonNull(trees);
+  }
+
+  @Override
+  public TreeBackedTypes getTypes() {
+    if (types == null) {
+      initUtils();
+    }
+    return Objects.requireNonNull(types);
+  }
+
+  private void initUtils() {
+    Elements javacElements = javacTask.getElements();
+    Trees javacTrees = super.getTrees();
+    Types javacTypes = javacTask.getTypes();
+    elements = new TreeBackedElements(javacElements, javacTypes, javacTrees);
+    this.types = new TreeBackedTypes(javacTypes);
+    trees =
+        new TreeBackedTrees(
+            javacTrees, new PostEnterCanonicalizer(elements, this.types, javacTrees));
+  }
+
+  @Override
+  public void setProcessors(Iterable<? extends Processor> processors) {
+    javacTask.setProcessors(wrap(processors));
+  }
+
+  private List<TreeBackedProcessorWrapper> wrap(Iterable<? extends Processor> processors) {
+    List<TreeBackedProcessorWrapper> result = new ArrayList<>();
+    for (Processor processor : processors) {
+      result.add(new TreeBackedProcessorWrapper(this, processor));
+    }
+
+    return result;
+  }
+
+  @Override
+  public void setLocale(Locale locale) {
+    throw new UnsupportedOperationException("NYI");
+  }
+
+  @Override
+  public Boolean call() {
+    try {
+      stopCompilationAfterEnter = true;
+      return javacTask.call();
+    } catch (RuntimeException e) {
+      if (e.getCause() instanceof StopCompilation) {
+        return true;
+      } else if (e.getCause() instanceof SourceCodeWillNotCompileException) {
+        return false;
+      }
+
+      throw e;
+    }
+  }
+
+  @Override
+  protected void onPostEnter(Set<Element> topLevelElements) {
+    super.onPostEnter(topLevelElements);
+
+    if (stopCompilationAfterEnter) {
+      throw new StopCompilation();
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FrontendOnlyJavacTaskProxyImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FrontendOnlyJavacTaskProxyImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/FrontendOnlyJavacTaskProxyImpl.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.abi.source.api.FrontendOnlyJavacTaskProxy;
+import com.facebook.buck.jvm.java.plugin.adapter.BuckJavacTaskProxyImpl;
+import com.sun.source.util.JavacTask;
+import javax.tools.JavaCompiler;
+
+public class FrontendOnlyJavacTaskProxyImpl extends BuckJavacTaskProxyImpl
+    implements FrontendOnlyJavacTaskProxy {
+  private final FrontendOnlyJavacTask javacTask;
+
+  public FrontendOnlyJavacTaskProxyImpl(JavaCompiler.CompilationTask task) {
+    this(new FrontendOnlyJavacTask((JavacTask) task));
+  }
+
+  public FrontendOnlyJavacTaskProxyImpl(FrontendOnlyJavacTask javacTask) {
+    super(javacTask);
+    this.javacTask = javacTask;
+  }
+
+  @Override
+  public FrontendOnlyJavacTask getInner() {
+    return javacTask;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ImportsTracker.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ImportsTracker.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ImportsTracker.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.util.TreePath;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.QualifiedNameable;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.Types;
+
+/** Simulates import resolution scopes in a source-only ABI classpath. */
+class ImportsTracker {
+  private static class StaticImport {
+    public final TypeElement container;
+    public final Name identifier;
+
+    private StaticImport(TypeElement container, Name identifier) {
+      this.container = container;
+      this.identifier = identifier;
+    }
+  }
+
+  private final Map<TypeElement, TreePath> importedTypes = new HashMap<>();
+  private final Map<QualifiedNameable, TreePath> importedOwners = new HashMap<>();
+  private final Set<TypeElement> staticImportedOwners = new HashSet<>();
+  private final Map<Name, StaticImport> staticImports = new HashMap<>();
+  private final Types types;
+
+  public ImportsTracker(Elements elements, Types types, PackageElement enclosingPackage) {
+    this.types = types;
+    importMembers(Objects.requireNonNull(elements.getPackageElement("java.lang")), null);
+    importMembers(enclosingPackage, null);
+  }
+
+  public void importType(TypeElement type, TreePath location) {
+    importedTypes.put(type, location);
+  }
+
+  public void importMembers(QualifiedNameable typeOrPackage, @Nullable TreePath location) {
+    importedOwners.put(typeOrPackage, location);
+  }
+
+  public void importStatic(TypeElement container, Name identifier) {
+    StaticImport newImport = new StaticImport(container, identifier);
+    staticImports.put(newImport.identifier, newImport);
+  }
+
+  public void importStaticMembers(TypeElement container) {
+    staticImportedOwners.add(container);
+  }
+
+  public boolean isStaticImported(TypeElement element) {
+    return getStaticImportContainer(element) != null;
+  }
+
+  public boolean nameIsStaticImported(Name name) {
+    return staticImports.containsKey(name);
+  }
+
+  @Nullable
+  public TypeElement getStaticImportContainer(TypeElement element) {
+    if (!element.getModifiers().contains(Modifier.STATIC)) {
+      return null;
+    }
+
+    StaticImport candidate = staticImports.get(element.getSimpleName());
+
+    if (candidate != null
+        && types.isSubtype(candidate.container.asType(), element.getEnclosingElement().asType())) {
+      return candidate.container;
+    }
+
+    return null;
+  }
+
+  public boolean isSingleTypeImported(Element element) {
+    return getSingleTypeImportLocation(element) != null;
+  }
+
+  @Nullable
+  public TreePath getSingleTypeImportLocation(Element element) {
+    return importedTypes.get(element);
+  }
+
+  public boolean isOnDemandImported(Element element) {
+    return getOnDemandImportLocation(element) != null;
+  }
+
+  @Nullable
+  public TreePath getOnDemandImportLocation(Element element) {
+    return importedOwners.get(element.getEnclosingElement());
+  }
+
+  public boolean isOnDemandStaticImported(TypeElement element) {
+    return getOnDemandStaticImportContainer(element) != null;
+  }
+
+  @Nullable
+  public TypeElement getOnDemandStaticImportContainer(TypeElement element) {
+    if (!element.getModifiers().contains(Modifier.STATIC)) {
+      return null;
+    }
+
+    TypeElement container = (TypeElement) element.getEnclosingElement();
+    for (TypeElement staticImportedOwner : staticImportedOwners) {
+      if (types.isSubtype(staticImportedOwner.asType(), container.asType())) {
+        return staticImportedOwner;
+      }
+    }
+
+    return null;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredDeclaredType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredDeclaredType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredDeclaredType.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.abi.source.api.CannotInferException;
+import java.util.List;
+import javax.lang.model.type.TypeMirror;
+
+/** Returned as the type of an {@link InferredTypeElement}. */
+class InferredDeclaredType extends StandaloneDeclaredType {
+  public InferredDeclaredType(InferredTypeElement inferredTypeElement) {
+    super(inferredTypeElement);
+  }
+
+  @Override
+  public TypeMirror getEnclosingType() {
+    throw new CannotInferException("enclosing type", this);
+  }
+
+  @Override
+  public List<? extends TypeMirror> getTypeArguments() {
+    throw new CannotInferException("type parameters", this);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredElement.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.abi.source.api.CannotInferException;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.lang.annotation.Annotation;
+import java.util.List;
+import java.util.Set;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.Name;
+
+/**
+ * Represents an {@link javax.lang.model.element.Element} whose existence has been inferred from
+ * references to it in the code.
+ */
+abstract class InferredElement implements ArtificialElement {
+  private final Name simpleName;
+  @Nullable private final ArtificialElement enclosingElement;
+
+  protected InferredElement(Name simpleName, @Nullable ArtificialElement enclosingElement) {
+    this.simpleName = simpleName;
+    this.enclosingElement = enclosingElement;
+  }
+
+  @Override
+  public void addEnclosedElement(Element element) {
+    // getEnclosedElements throws, so don't bother keeping track of them.
+  }
+
+  @Override
+  public Set<Modifier> getModifiers() {
+    throw new CannotInferException("modifiers", this);
+  }
+
+  @Override
+  public final Name getSimpleName() {
+    return simpleName;
+  }
+
+  @Override
+  @Nullable
+  public ArtificialElement getEnclosingElement() {
+    return enclosingElement;
+  }
+
+  @Override
+  public List<? extends Element> getEnclosedElements() {
+    throw new CannotInferException("enclosed elements", this);
+  }
+
+  @Override
+  public final List<? extends AnnotationMirror> getAnnotationMirrors() {
+    throw new CannotInferException("annotations", this);
+  }
+
+  @Override
+  public final <A extends Annotation> A getAnnotation(Class<A> annotationType) {
+    throw new CannotInferException("annotations", this);
+  }
+
+  @Override
+  public final <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) {
+    throw new CannotInferException("annotations", this);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredPackageElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredPackageElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredPackageElement.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.Collections;
+import java.util.Set;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ElementVisitor;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.Name;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * A {@link javax.lang.model.element.PackageElement} whose existence is inferred from references to
+ * it in the code.
+ */
+class InferredPackageElement extends InferredElement implements ArtificialPackageElement {
+  private final Name qualifiedName;
+  private final TypeMirror typeMirror;
+
+  public InferredPackageElement(Name simpleName, Name qualifiedName) {
+    super(simpleName, null);
+    this.qualifiedName = qualifiedName;
+    typeMirror = new StandalonePackageType(this);
+  }
+
+  @Override
+  public Set<Modifier> getModifiers() {
+    // Packages have no modifiers, so we can implememnt this method here
+    return Collections.emptySet();
+  }
+
+  @Override
+  public Name getQualifiedName() {
+    return qualifiedName;
+  }
+
+  @Override
+  public boolean isUnnamed() {
+    return qualifiedName.length() == 0;
+  }
+
+  @Override
+  public TypeMirror asType() {
+    return typeMirror;
+  }
+
+  @Override
+  public ElementKind getKind() {
+    return ElementKind.PACKAGE;
+  }
+
+  @Override
+  public <R, P> R accept(ElementVisitor<R, P> v, P p) {
+    return v.visitPackage(this, p);
+  }
+
+  @Override
+  public String toString() {
+    return qualifiedName.toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredTypeElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredTypeElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InferredTypeElement.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.abi.source.api.CannotInferException;
+import java.util.List;
+import java.util.Objects;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ElementVisitor;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.NestingKind;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * Represents a {@link javax.lang.model.element.TypeElement} whose existence has been inferred from
+ * references to it in the code.
+ */
+class InferredTypeElement extends InferredElement implements ArtificialTypeElement {
+  private final Name qualifiedName;
+  private final TypeMirror typeMirror;
+
+  protected InferredTypeElement(
+      Name simpleName, Name qualifiedName, ArtificialElement enclosingElement) {
+    super(simpleName, enclosingElement);
+    this.qualifiedName = qualifiedName;
+    typeMirror = new InferredDeclaredType(this);
+
+    enclosingElement.addEnclosedElement(this);
+  }
+
+  @Override
+  public List<ArtificialElement> getEnclosedElements() {
+    throw new UnsupportedOperationException(
+        String.format(
+            "We cannot know the enclosed elements of an inferred type: %s.", qualifiedName));
+  }
+
+  @Override
+  public ArtificialElement getEnclosingElement() {
+    return Objects.requireNonNull(super.getEnclosingElement());
+  }
+
+  @Override
+  public List<? extends ArtificialTypeParameterElement> getTypeParameters() {
+    throw new CannotInferException("type parameters", this);
+  }
+
+  @Override
+  public TypeMirror asType() {
+    return typeMirror;
+  }
+
+  @Override
+  public ElementKind getKind() {
+    throw new CannotInferException("kind", this);
+  }
+
+  @Override
+  public <R, P> R accept(ElementVisitor<R, P> v, P p) {
+    return v.visitType(this, p);
+  }
+
+  @Override
+  public NestingKind getNestingKind() {
+    // We'll never need to infer local or anonymous classes, so there are only two options left
+    // and we can tell the difference:
+    if (getEnclosingElement() instanceof InferredTypeElement) {
+      return NestingKind.MEMBER;
+    }
+
+    return NestingKind.TOP_LEVEL;
+  }
+
+  @Override
+  public TypeMirror getSuperclass() {
+    throw new CannotInferException("superclass", this);
+  }
+
+  @Override
+  public List<? extends TypeMirror> getInterfaces() {
+    throw new CannotInferException("interfaces", this);
+  }
+
+  @Override
+  public Name getQualifiedName() {
+    return qualifiedName;
+  }
+
+  @Override
+  public String toString() {
+    return qualifiedName.toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InterfaceScanner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InterfaceScanner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InterfaceScanner.java
@@ -0,0 +1,283 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.BlockTree;
+import com.sun.source.tree.ClassTree;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.IdentifierTree;
+import com.sun.source.tree.ImportTree;
+import com.sun.source.tree.MemberSelectTree;
+import com.sun.source.tree.MethodTree;
+import com.sun.source.tree.VariableTree;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.Trees;
+import java.util.Objects;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.QualifiedNameable;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * Examines the non-private interfaces of types defined in one or more {@link CompilationUnitTree}s
+ * and finds references to types or compile-time constants. This is intended for use during full
+ * compilation, to expose references that may be problematic when generating ABIs without
+ * dependencies.
+ */
+class InterfaceScanner {
+  public interface Listener {
+    void onTypeDeclared(TypeElement type, TreePath path);
+
+    /**
+     * An import statement was encountered.
+     *
+     * @param isStatic true for static imports
+     * @param isStarImport true for star imports
+     * @param leafmostElementPath the path of the leafmost known element in the imported type
+     *     expression
+     * @param leafmostElement the leafmost known element in the imported type expression. For
+     *     single-type imports, this is the imported type. For the rest, this is the type or package
+     *     enclosing the imported element(s).
+     * @param memberName for named static imports, the name of the static members to import.
+     *     Otherwise null.
+     */
+    void onImport(
+        boolean isStatic,
+        boolean isStarImport,
+        TreePath leafmostElementPath,
+        QualifiedNameable leafmostElement,
+        @Nullable Name memberName);
+
+    void onTypeReferenceFound(TypeElement type, TreePath path, Element referencingElement);
+
+    void onConstantReferenceFound(
+        VariableElement constant, TreePath path, Element referencingElement);
+  }
+
+  private final Trees trees;
+
+  public InterfaceScanner(Trees trees) {
+    this.trees = trees;
+  }
+
+  public void findReferences(CompilationUnitTree file, Listener listener) {
+    // Scan the non-private interface portions of the tree, and report any references to types
+    // or constants that are found.
+    new TreeContextScanner<Void, Void>(trees) {
+      private boolean inInitializer = false;
+
+      @Override
+      public Void visitCompilationUnit(CompilationUnitTree node, Void aVoid) {
+        // We change the order relative to our superclass so that the imports get scanned first
+        // (in case they are needed to resolve the package annotations), and we don't bother
+        // scanning the package name because it is not needed.
+        scan(node.getImports(), aVoid);
+        scan(node.getPackageAnnotations(), aVoid);
+
+        // getTypeDecls has a bug whereby it can return some imports in addition to types, but
+        // since getImports returns all of the imports in that case we can still iterate this last
+        // like the superclass does.
+        scan(node.getTypeDecls(), aVoid);
+        return null;
+      }
+
+      /** Reports types that are imported via single-type imports */
+      @Override
+      public Void visitImport(ImportTree importTree, Void aVoid) {
+        TreePath importTreePath = getCurrentPath();
+        MemberSelectTree importedExpression =
+            (MemberSelectTree) importTree.getQualifiedIdentifier();
+        TreePath importedExpressionPath = new TreePath(importTreePath, importedExpression);
+        Name simpleName = importedExpression.getIdentifier();
+
+        boolean isStatic = importTree.isStatic();
+        boolean isStarImport = simpleName.contentEquals("*");
+
+        TreePath leafmostElementPath = importedExpressionPath;
+        if (isStarImport || isStatic) {
+          leafmostElementPath =
+              new TreePath(importedExpressionPath, importedExpression.getExpression());
+        }
+        QualifiedNameable leafmostElement =
+            (QualifiedNameable) Objects.requireNonNull(trees.getElement(leafmostElementPath));
+
+        listener.onImport(isStatic, isStarImport, leafmostElementPath, leafmostElement, simpleName);
+
+        return null;
+      }
+
+      /** Restricts the search to non-private classes. */
+      @Override
+      public Void visitClass(ClassTree node, Void aVoid) {
+        Element element = getEnclosingElement();
+
+        listener.onTypeDeclared((TypeElement) element, getCurrentPath());
+
+        // Skip private since they're not part of the interface
+        if (!element.getKind().isClass() && isPrivate(element)) {
+          return null;
+        }
+
+        return super.visitClass(node, aVoid);
+      }
+
+      /** Restricts the search to non-private methods */
+      @Override
+      public Void visitMethod(MethodTree node, Void aVoid) {
+        Element element = getEnclosingElement();
+        // Skip private since they're not part of the interface
+        if (isPrivate(element)) {
+          return null;
+        }
+
+        return super.visitMethod(node, aVoid);
+      }
+
+      /**
+       * Restricts the search to non-private variables, and only searches the initializer if the
+       * variable is a compile-time constant field.
+       */
+      @Override
+      public Void visitVariable(VariableTree node, Void aVoid) {
+        VariableElement element = (VariableElement) getEnclosingElement();
+        // Skip private since they're not part of the interface
+        if (isPrivate(element)) {
+          return null;
+        }
+
+        scan(node.getModifiers(), aVoid);
+        scan(node.getType(), aVoid);
+
+        // Skip the initializers of variables that aren't compile-time constants since they're not
+        // part of the interface
+        if (element.getConstantValue() == null) {
+          return null;
+        }
+
+        inInitializer = true;
+        try {
+          scan(node.getInitializer(), aVoid);
+        } finally {
+          inInitializer = false;
+        }
+
+        return null;
+      }
+
+      /** Prevents the search from descending into method bodies. */
+      @Override
+      public Void visitBlock(BlockTree node, Void aVoid) {
+        // We care only about the interface, so we don't need to recurse into code blocks
+        return null;
+      }
+
+      /**
+       * Reports references to types or constants via fully or partially-qualified names, wherever
+       * they might appear in the interface.
+       */
+      @Override
+      public Void visitMemberSelect(MemberSelectTree node, Void aVoid) {
+        Element currentElement = getCurrentElement();
+        if (currentElement == null) {
+          // This can happen with the package name tree at compilation unit level
+          return null;
+        }
+
+        // The other visit methods have ensured that we're only seeing MemberSelectTrees that are
+        // part of the non-private interface, so let's figure out if this one represents a type
+        // reference or constant reference that we need to report
+        ElementKind kind = currentElement.getKind();
+        if (kind.isClass() || kind.isInterface()) {
+          reportType();
+        } else {
+          // If it's not a class reference, it could be a reference to a constant field, either
+          // as part of initializing a constant field or as a parameter to an annotation
+          VariableElement variableElement = (VariableElement) currentElement;
+          if (variableElement.getConstantValue() != null) {
+            reportConstant();
+          } else {
+            if (variableElement.getKind() == ElementKind.ENUM_CONSTANT) {
+              // Not technically a compile-time constant, but still needs to be present for
+              // stuff to resolve properly.
+              reportConstant();
+            }
+
+            // Keep looking for the type reference.
+            return super.visitMemberSelect(node, aVoid);
+          }
+        }
+
+        return null;
+      }
+
+      /**
+       * Reports references to types or constants via simple name, wherever it might appear in the
+       * interface
+       */
+      @Override
+      public Void visitIdentifier(IdentifierTree node, Void aVoid) {
+        Element currentElement = getCurrentElement();
+        if (currentElement == null) {
+          // This can happen with the package name tree at compilation unit level
+          return null;
+        }
+
+        ElementKind kind = currentElement.getKind();
+        if (kind.isClass() || kind.isInterface()) {
+          // Identifier represents a type (either imported, from the same package, or a member of
+          // the current class or a supertype/interface); report it
+          reportType();
+        } else if (kind == ElementKind.FIELD) {
+          // Identifier is a field name. Check if it's a constant and report if so.
+          VariableElement variableElement = (VariableElement) currentElement;
+          if (variableElement.getConstantValue() != null
+              || variableElement.getKind() == ElementKind.ENUM_CONSTANT) {
+            reportConstant();
+          }
+        }
+
+        // Ignore other types of identifiers
+        return null;
+      }
+
+      private void reportType() {
+        if (inInitializer) {
+          return;
+        }
+
+        TypeMirror currentType = Objects.requireNonNull(getCurrentType());
+        if (currentType.getKind() != TypeKind.DECLARED) {
+          return;
+        }
+
+        listener.onTypeReferenceFound(
+            (TypeElement) Objects.requireNonNull(getCurrentElement()),
+            getCurrentPath(),
+            getEnclosingElement());
+      }
+
+      private void reportConstant() {
+        VariableElement variable = (VariableElement) Objects.requireNonNull(getCurrentElement());
+        listener.onConstantReferenceFound(variable, getCurrentPath(), getEnclosingElement());
+      }
+    }.scan(file, null);
+  }
+
+  private static boolean isPrivate(Element element) {
+    return element.getModifiers().contains(Modifier.PRIVATE);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InterfaceValidator.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InterfaceValidator.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/InterfaceValidator.java
@@ -0,0 +1,314 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.abi.source.CompletionSimulator.CompletedType;
+import com.facebook.buck.jvm.java.abi.source.TreeBackedTypeResolutionSimulator.TreeBackedResolvedType;
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory.SourceOnlyAbiRuleInfo;
+import com.facebook.buck.jvm.java.plugin.adapter.BuckJavacTask;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.ClassTree;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.Trees;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.QualifiedNameable;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.Types;
+import javax.tools.Diagnostic;
+
+/**
+ * Validates the type and compile-time-constant references in the non-private interface of classes
+ * being compiled in the current compilation run, ensuring that they are compatible with correctly
+ * generating ABIs from source. When generating ABIs from source, we may be missing some (or most)
+ * dependencies.
+ *
+ * <p>In order to be compatible, type references to missing classes in the non-private interface of
+ * a class being compiled must be one of the following:
+ *
+ * <ul>
+ *   <li>The fully-qualified name of the type
+ *   <li>The simple name of a type that appears in an import statement
+ *   <li>The simple name of a top-level type in the same package as the type being compiled
+ * </ul>
+ *
+ * <p>In order to be compatible, compile-time constants in missing classes may not be referenced
+ * from the non-private interface of a class being compiled.
+ */
+class InterfaceValidator {
+  private final Elements elements;
+  private final Diagnostic.Kind messageKind;
+  private final Types types;
+  private final Trees trees;
+  private final SourceOnlyAbiRuleInfo ruleInfo;
+  private final FileManagerSimulator fileManager;
+  private final CompilerTypeResolutionSimulator compilerResolver;
+
+  public InterfaceValidator(
+      Diagnostic.Kind messageKind, BuckJavacTask task, SourceOnlyAbiRuleInfo ruleInfo) {
+    this.messageKind = messageKind;
+    trees = task.getTrees();
+    types = task.getTypes();
+    elements = task.getElements();
+    this.ruleInfo = ruleInfo;
+    fileManager = new FileManagerSimulator(elements, trees, ruleInfo);
+    compilerResolver = new CompilerTypeResolutionSimulator(trees, fileManager);
+  }
+
+  public void validate(List<? extends CompilationUnitTree> compilationUnits) {
+    InterfaceScanner interfaceScanner = new InterfaceScanner(trees);
+    for (CompilationUnitTree compilationUnit : compilationUnits) {
+      interfaceScanner.findReferences(
+          compilationUnit,
+          new ValidatingListener(
+              messageKind,
+              elements,
+              types,
+              trees,
+              ruleInfo,
+              fileManager,
+              compilerResolver,
+              compilationUnit));
+    }
+  }
+
+  private static class ValidatingListener implements InterfaceScanner.Listener {
+    private final Diagnostic.Kind messageKind;
+    private final Trees trees;
+    private final SourceOnlyAbiRuleInfo ruleInfo;
+    private final TreeBackedTypeResolutionSimulator treeBackedResolver;
+    private final FileManagerSimulator fileManager;
+    private final CompletionSimulator completer;
+    private final CompilerTypeResolutionSimulator compilerResolver;
+    private final ImportsTracker imports;
+
+    public ValidatingListener(
+        Diagnostic.Kind messageKind,
+        Elements elements,
+        Types types,
+        Trees trees,
+        SourceOnlyAbiRuleInfo ruleInfo,
+        FileManagerSimulator fileManager,
+        CompilerTypeResolutionSimulator compilerResolver,
+        CompilationUnitTree compilationUnit) {
+      this.messageKind = messageKind;
+      this.trees = trees;
+      this.ruleInfo = ruleInfo;
+      this.fileManager = fileManager;
+      this.compilerResolver = compilerResolver;
+      completer = new CompletionSimulator(fileManager);
+      imports =
+          new ImportsTracker(
+              elements,
+              types,
+              (PackageElement)
+                  Objects.requireNonNull(trees.getElement(new TreePath(compilationUnit))));
+      treeBackedResolver = new TreeBackedTypeResolutionSimulator(elements, trees, compilationUnit);
+    }
+
+    @Override
+    public void onTypeDeclared(TypeElement type, TreePath path) {
+      if (type.getKind() == ElementKind.ANNOTATION_TYPE
+          && !ruleInfo.ruleIsRequiredForSourceOnlyAbi()) {
+        trees.printMessage(
+            messageKind,
+            String.format(
+                "Annotation definitions must be in rules with required_for_source_only_abi ="
+                    + " True.\n"
+                    + "For a quick fix, add required_for_source_only_abi = True to %s.\n"
+                    + "A better fix is to move %s to a new rule that contains only\n"
+                    + "annotations, and mark that rule required_for_source_only_abi.\n",
+                ruleInfo.getRuleName(), type.getSimpleName()),
+            path.getLeaf(),
+            path.getCompilationUnit());
+      }
+
+      ClassTree classTree = (ClassTree) path.getLeaf();
+
+      // The compiler can handle superclasses and interfaces that are outright missing
+      // (because it is possible for those to be generated by annotation processors).
+      // However, if a superclass or interface is present, the compiler expects
+      // the entire class hierarchy of that class/interface to also be present, and
+      // gives a sketchy error if they are missing.
+      Tree extendsClause = classTree.getExtendsClause();
+      if (extendsClause != null) {
+        ensureAbsentOrComplete(type.getSuperclass(), new TreePath(path, extendsClause));
+      }
+
+      List<? extends Tree> implementsClause = classTree.getImplementsClause();
+      if (implementsClause != null) {
+        List<? extends TypeMirror> interfaces = type.getInterfaces();
+        for (int i = 0; i < implementsClause.size(); i++) {
+          ensureAbsentOrComplete(interfaces.get(i), new TreePath(path, implementsClause.get(i)));
+        }
+      }
+    }
+
+    private void ensureAbsentOrComplete(TypeMirror typeMirror, TreePath path) {
+      if (typeMirror.getKind() != TypeKind.DECLARED) {
+        return;
+      }
+
+      DeclaredType declaredType = (DeclaredType) typeMirror;
+      TypeElement typeElement = (TypeElement) declaredType.asElement();
+      CompletedType completedType = Objects.requireNonNull(completer.complete(typeElement, true));
+
+      switch (completedType.kind) {
+        case COMPLETED_TYPE:
+        case PARTIALLY_COMPLETED_TYPE:
+        case ERROR_TYPE:
+          // These are all fine
+          break;
+        case CRASH:
+          reportMissingDeps(completedType, path);
+          break;
+      }
+    }
+
+    public void reportMissingDeps(CompletedType type, TreePath path) {
+      // TODO: Different message based on kind.
+      trees.printMessage(
+          messageKind,
+          String.format(
+              "Source-only ABI generation requires that this type be unavailable, or that all of"
+                  + " its superclasses/interfaces be available.\n"
+                  + "To fix, add the following rules to source_only_abi_deps in %s: %s",
+              ruleInfo.getRuleName(),
+              type.getMissingDependencies().stream().sorted().collect(Collectors.joining(", "))),
+          path.getLeaf(),
+          path.getCompilationUnit());
+    }
+
+    public void reportMissingDeps(ResolvedType type, TreePath path) {
+      trees.printMessage(
+          messageKind,
+          String.format(
+              "Source-only ABI generation requires that this type be unavailable, or that all of"
+                  + " its superclasses/interfaces be available.\n"
+                  + "To fix, add the following rules to source_only_abi_deps in %s: %s",
+              ruleInfo.getRuleName(),
+              type.missingDependencies.stream().sorted().collect(Collectors.joining(", "))),
+          path.getLeaf(),
+          path.getCompilationUnit());
+    }
+
+    @Override
+    public void onImport(
+        boolean isStatic,
+        boolean isStarImport,
+        TreePath leafmostElementPath,
+        QualifiedNameable leafmostElement,
+        @Nullable Name memberName) {
+      if (leafmostElement.getKind() != ElementKind.PACKAGE) {
+        if (isStatic) {
+          CompletedType completedType = completer.complete(leafmostElement, true);
+          if (completedType != null
+              && (completedType.kind == CompletedTypeKind.CRASH
+                  || completedType.kind == CompletedTypeKind.PARTIALLY_COMPLETED_TYPE)) {
+            reportMissingDeps(completedType, leafmostElementPath);
+          }
+        } else {
+          ResolvedType compilerResolvedType = compilerResolver.resolve(leafmostElementPath);
+          if (compilerResolvedType != null) {
+            switch (compilerResolvedType.kind) {
+              case CRASH:
+                reportMissingDeps(compilerResolvedType, leafmostElementPath);
+                break;
+              case RESOLVED_TYPE:
+                // Nothing to do; it would resolve fine
+                break;
+              // $CASES-OMITTED$
+              default:
+                {
+                  TreeBackedResolvedType treeBackedResolvedType =
+                      treeBackedResolver.resolve(leafmostElementPath);
+                  if (!treeBackedResolvedType.isCorrect()) {
+                    if (treeBackedResolvedType.isCorrectable()) {
+                      treeBackedResolvedType.reportErrors(messageKind);
+                    } else {
+                      reportMissingDeps(compilerResolvedType, leafmostElementPath);
+                    }
+                  }
+                }
+                break;
+            }
+          }
+        }
+      }
+
+      if (!isStatic) {
+        if (!isStarImport) {
+          imports.importType((TypeElement) leafmostElement, leafmostElementPath);
+        } else {
+          imports.importMembers(leafmostElement, leafmostElementPath);
+        }
+      } else if (!isStarImport) {
+        imports.importStatic((TypeElement) leafmostElement, Objects.requireNonNull(memberName));
+      } else {
+        imports.importStaticMembers((TypeElement) leafmostElement);
+      }
+    }
+
+    @Override
+    public void onTypeReferenceFound(
+        TypeElement canonicalTypeElement, TreePath path, Element referencingElement) {
+      compilerResolver.setImports(imports);
+      treeBackedResolver.setImports(imports);
+      ResolvedType compilerResolvedType = compilerResolver.resolve(path);
+
+      if (compilerResolvedType.kind != ResolvedTypeKind.RESOLVED_TYPE) {
+        TreeBackedResolvedType treeBackedResolvedType = treeBackedResolver.resolve(path);
+        if (!treeBackedResolvedType.isCorrect()) {
+          if (treeBackedResolvedType.isCorrectable()) {
+            treeBackedResolvedType.reportErrors(messageKind);
+          } else {
+            reportMissingDeps(compilerResolvedType, path);
+          }
+        }
+      }
+    }
+
+    @Override
+    public void onConstantReferenceFound(
+        VariableElement constant, TreePath path, Element referencingElement) {
+      TypeElement constantEnclosingType = (TypeElement) constant.getEnclosingElement();
+
+      if (fileManager.typeWillBeAvailable(constantEnclosingType)) {
+        // All good!
+        return;
+      }
+
+      String owningTarget = fileManager.getOwningTarget(constant);
+      trees.printMessage(
+          messageKind,
+          String.format(
+              "This constant will not be available during source-only ABI generation.\n"
+                  + "For a quick fix, add required_for_source_only_abi = True to %s.\n"
+                  + "A better fix is to move %s to a new rule that contains only\n"
+                  + "constants, and mark that rule required_for_source_only_abi.\n",
+              owningTarget, constant.getEnclosingElement().getSimpleName()),
+          path.getLeaf(),
+          path.getCompilationUnit());
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/PostEnterCanonicalizer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/PostEnterCanonicalizer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/PostEnterCanonicalizer.java
@@ -0,0 +1,503 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.facebook.buck.util.liteinfersupport.PropagatesNullable;
+import com.sun.source.tree.AnnotatedTypeTree;
+import com.sun.source.tree.ArrayTypeTree;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.ExpressionTree;
+import com.sun.source.tree.IdentifierTree;
+import com.sun.source.tree.ImportTree;
+import com.sun.source.tree.MemberSelectTree;
+import com.sun.source.tree.NewArrayTree;
+import com.sun.source.tree.ParameterizedTypeTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.tree.WildcardTree;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.Trees;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.NestingKind;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.ArrayType;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+import javax.lang.model.type.WildcardType;
+import javax.lang.model.util.SimpleAnnotationValueVisitor8;
+import javax.tools.Diagnostic;
+import javax.tools.Diagnostic.Kind;
+
+/**
+ * After the enter phase is complete, this class can obtain the "canonical" version of any {@link
+ * javax.lang.model.element.Element}, {@link TypeMirror}, or {@link AnnotationValue}. The canonical
+ * versions of these are the artificial ones if they exist, otherwise the javac one.
+ */
+class PostEnterCanonicalizer {
+
+  private final TreeBackedElements elements;
+  private final TreeBackedTypes types;
+  private final Trees javacTrees;
+  private final Map<CompilationUnitTree, Map<Name, TreePath>> imports = new HashMap<>();
+
+  public PostEnterCanonicalizer(
+      TreeBackedElements elements, TreeBackedTypes types, Trees javacTrees) {
+    this.elements = elements;
+    this.types = types;
+    this.javacTrees = javacTrees;
+  }
+
+  public Element getCanonicalElement(@PropagatesNullable Element element) {
+    return elements.getCanonicalElement(element);
+  }
+
+  public ExecutableElement getCanonicalElement(ExecutableElement element) {
+    return Objects.requireNonNull(elements.getCanonicalElement(element));
+  }
+
+  public List<TypeMirror> getCanonicalTypes(
+      List<? extends TypeMirror> types,
+      @Nullable TreePath parent,
+      @Nullable List<? extends Tree> children) {
+    List<TypeMirror> result = new ArrayList<>();
+    for (int i = 0; i < types.size(); i++) {
+      result.add(
+          getCanonicalType(
+              types.get(i),
+              parent,
+              children == null || children.isEmpty() ? null : children.get(i)));
+    }
+    return result;
+  }
+
+  protected TypeMirror getCanonicalType(TreePath classNamePath) {
+    return getCanonicalType(getUnderlyingType(classNamePath), classNamePath);
+  }
+
+  public TypeMirror getCanonicalType(
+      @PropagatesNullable TypeMirror typeMirror, @Nullable TreePath parent, @Nullable Tree child) {
+    return getCanonicalType(
+        typeMirror, (parent != null && child != null) ? new TreePath(parent, child) : null);
+  }
+
+  public TypeMirror getCanonicalType(
+      @PropagatesNullable TypeMirror typeMirror, @Nullable TreePath treePath) {
+    if (typeMirror == null) {
+      return null;
+    }
+
+    Tree tree = treePath == null ? null : treePath.getLeaf();
+    TypeMirror canonicalType;
+    switch (typeMirror.getKind()) {
+      case ARRAY:
+        {
+          ArrayType arrayType = (ArrayType) typeMirror;
+          canonicalType =
+              types.getArrayType(
+                  getCanonicalType(
+                      arrayType.getComponentType(),
+                      treePath,
+                      tree == null ? null : ((ArrayTypeTree) tree).getType()));
+          break;
+        }
+      case TYPEVAR:
+        {
+          TypeVariable typeVar = (TypeVariable) typeMirror;
+          canonicalType = elements.getCanonicalElement(typeVar.asElement()).asType();
+          break;
+        }
+      case WILDCARD:
+        {
+          WildcardType wildcardType = (WildcardType) typeMirror;
+          Tree boundTree = tree == null ? null : ((WildcardTree) tree).getBound();
+          canonicalType =
+              types.getWildcardType(
+                  getCanonicalType(wildcardType.getExtendsBound(), treePath, boundTree),
+                  getCanonicalType(wildcardType.getSuperBound(), treePath, boundTree));
+          break;
+        }
+      case DECLARED:
+        {
+          DeclaredType declaredType = (DeclaredType) typeMirror;
+
+          // It is possible to have a DeclaredType with ErrorTypes for arguments, so we must
+          // compute the TreePaths while canonicalizing type arguments
+          List<? extends TypeMirror> underlyingTypeArgs = declaredType.getTypeArguments();
+          TypeMirror[] canonicalTypeArgs;
+          if (underlyingTypeArgs.isEmpty()) {
+            canonicalTypeArgs = new TypeMirror[0];
+          } else {
+            canonicalTypeArgs =
+                getCanonicalTypes(
+                        underlyingTypeArgs,
+                        treePath,
+                        tree == null ? null : ((ParameterizedTypeTree) tree).getTypeArguments())
+                    .toArray(new TypeMirror[0]);
+          }
+
+          // While it is not possible to have a DeclaredType with an enclosing ErrorType (the only
+          // way to get a DeclaredType in the first place is if the compiler can resolve all
+          // enclosing types), it *is* possible to have a DeclaredType with an enclosing
+          // DeclaredType that has ErrorTypes for type arguments. So we need to check if there's an
+          // explicitly specified enclosing type and provide the tree if so.
+          TypeMirror enclosingType = declaredType.getEnclosingType();
+          DeclaredType canonicalEnclosingType = null;
+          if (enclosingType.getKind() != TypeKind.NONE) {
+            TreePath enclosingTypePath = treePath;
+            if (enclosingTypePath != null
+                && enclosingTypePath.getLeaf().getKind() == Tree.Kind.PARAMETERIZED_TYPE) {
+              enclosingTypePath =
+                  new TreePath(
+                      enclosingTypePath,
+                      ((ParameterizedTypeTree) enclosingTypePath.getLeaf()).getType());
+            }
+            if (enclosingTypePath != null
+                && enclosingTypePath.getLeaf().getKind() == Tree.Kind.MEMBER_SELECT) {
+              enclosingTypePath =
+                  new TreePath(
+                      enclosingTypePath,
+                      ((MemberSelectTree) enclosingTypePath.getLeaf()).getExpression());
+            } else {
+              enclosingTypePath = null;
+            }
+            canonicalEnclosingType =
+                (DeclaredType) getCanonicalType(enclosingType, enclosingTypePath);
+          }
+
+          TypeElement canonicalElement =
+              (TypeElement) elements.getCanonicalElement(declaredType.asElement());
+          // If an import statement for a type that is not available would shadow a type from a
+          // star-imported package (such as java.lang), the compiler will happily resolve to the
+          // star-imported type (expecting that the imported type will be filled in by an annotation
+          // processor). We check whether we would have inferred something different.
+          if (canonicalElement.getNestingKind() == NestingKind.TOP_LEVEL
+              && treePath != null
+              && treePath.getLeaf().getKind() == Tree.Kind.IDENTIFIER) {
+            DeclaredType inferredType = (DeclaredType) getImportedType(treePath);
+            if (inferredType != null) {
+              canonicalElement =
+                  (TypeElement) elements.getCanonicalElement(inferredType.asElement());
+            }
+          }
+
+          canonicalType =
+              types.getDeclaredType(canonicalEnclosingType, canonicalElement, canonicalTypeArgs);
+          break;
+        }
+      case PACKAGE:
+      case ERROR:
+        {
+          if (treePath == null) {
+            throw new IllegalArgumentException("Cannot resolve error types without a Tree.");
+          }
+
+          try {
+            canonicalType = getInferredType(treePath);
+          } catch (CompilerErrorException e) {
+            javacTrees.printMessage(
+                Kind.ERROR, e.getMessage(), treePath.getLeaf(), treePath.getCompilationUnit());
+            canonicalType = typeMirror;
+          }
+          break;
+        }
+      case BOOLEAN:
+      case BYTE:
+      case SHORT:
+      case INT:
+      case LONG:
+      case CHAR:
+      case FLOAT:
+      case DOUBLE:
+      case VOID:
+      case NONE:
+      case NULL:
+        canonicalType = typeMirror;
+        break;
+      case EXECUTABLE:
+      case OTHER:
+      case UNION:
+      case INTERSECTION:
+      // Temporary. Remove once migration to Java 10/11 is complete.
+      // $CASES-OMITTED$
+      default:
+        throw new UnsupportedOperationException();
+    }
+
+    if (types.isArtificialType(canonicalType)) {
+      StandaloneTypeMirror standaloneCanonicalType = (StandaloneTypeMirror) canonicalType;
+      return standaloneCanonicalType.cloneWithAnnotationMirrors(typeMirror.getAnnotationMirrors());
+    } else {
+      // To preserve type annotations, return the original type when we would return real java type
+      // anyway
+      return typeMirror;
+    }
+  }
+
+  private TypeMirror getUnderlyingType(TreePath treePath) {
+    return Objects.requireNonNull(javacTrees.getTypeMirror(treePath));
+  }
+
+  private TypeMirror getInferredType(TreePath treePath) throws CompilerErrorException {
+    Tree tree = treePath.getLeaf();
+    switch (tree.getKind()) {
+      case PARAMETERIZED_TYPE:
+        {
+          ParameterizedTypeTree parameterizedTypeTree = (ParameterizedTypeTree) tree;
+          TypeMirror[] typeArguments =
+              parameterizedTypeTree.getTypeArguments().stream()
+                  .map(
+                      arg -> {
+                        TreePath argPath = new TreePath(treePath, arg);
+                        return getCanonicalType(argPath);
+                      })
+                  .toArray(TypeMirror[]::new);
+
+          TreePath baseTypeTreePath = new TreePath(treePath, parameterizedTypeTree.getType());
+          DeclaredType baseType = (DeclaredType) getCanonicalType(baseTypeTreePath);
+
+          TypeMirror enclosingType = baseType.getEnclosingType();
+          if (enclosingType.getKind() == TypeKind.NONE) {
+            enclosingType = null;
+          }
+
+          return types.getDeclaredType(
+              (DeclaredType) enclosingType, (TypeElement) baseType.asElement(), typeArguments);
+        }
+      case UNBOUNDED_WILDCARD:
+        return types.getWildcardType(null, null);
+      case SUPER_WILDCARD:
+        {
+          WildcardTree wildcardTree = (WildcardTree) tree;
+          TreePath boundTreePath = new TreePath(treePath, wildcardTree.getBound());
+          return types.getWildcardType(null, getCanonicalType(boundTreePath));
+        }
+      case EXTENDS_WILDCARD:
+        {
+          WildcardTree wildcardTree = (WildcardTree) tree;
+          TreePath boundTreePath = new TreePath(treePath, wildcardTree.getBound());
+          return types.getWildcardType(getCanonicalType(boundTreePath), null);
+        }
+      case MEMBER_SELECT:
+        {
+          MemberSelectTree memberSelectTree = (MemberSelectTree) tree;
+          TypeMirror canonicalBaseType =
+              getCanonicalType(new TreePath(treePath, memberSelectTree.getExpression()));
+          if (!(canonicalBaseType instanceof StandaloneTypeMirror)) {
+            javacTrees.printMessage(
+                Kind.ERROR,
+                String.format(
+                    "cannot find symbol\nsymbol: class %s\nlocation: class %s",
+                    memberSelectTree.getIdentifier(), canonicalBaseType),
+                treePath.getLeaf(),
+                treePath.getCompilationUnit());
+            return canonicalBaseType; // This isn't right, but it doesn't matter what we return
+            // since we're failing anyway
+          }
+          StandaloneTypeMirror baseType = (StandaloneTypeMirror) canonicalBaseType;
+          ArtificialQualifiedNameable baseElement;
+          Name identifier = memberSelectTree.getIdentifier();
+          if (baseType.getKind() == TypeKind.PACKAGE) {
+            baseElement = ((StandalonePackageType) baseType).asElement();
+            if (isProbablyPackageName(identifier)) {
+              return types.getPackageType(
+                  elements.getOrCreatePackageElement((PackageElement) baseElement, identifier));
+            }
+          } else {
+            baseElement = (ArtificialQualifiedNameable) ((DeclaredType) baseType).asElement();
+          }
+
+          DeclaredType enclosingType = null;
+          if (baseType.getKind() == TypeKind.DECLARED
+              && !(baseType instanceof InferredDeclaredType)) {
+            DeclaredType baseDeclaredType = (DeclaredType) baseType;
+            if (!baseDeclaredType.getTypeArguments().isEmpty()
+                || baseDeclaredType.getEnclosingType().getKind() != TypeKind.NONE) {
+              enclosingType = baseDeclaredType;
+            }
+          }
+
+          ArtificialTypeElement typeElement =
+              elements.getOrCreateTypeElement(baseElement, identifier);
+          return types.getDeclaredType(enclosingType, typeElement);
+        }
+      case IDENTIFIER:
+        {
+          // If it's imported, then it must be a class; look it up
+          TypeMirror importedType = getImportedType(treePath);
+          if (importedType != null) {
+            return importedType;
+          }
+
+          // Infer the type by heuristic
+          IdentifierTree identifierTree = (IdentifierTree) tree;
+          Name identifier = identifierTree.getName();
+          if (isProbablyPackageName(identifier)) {
+            return types.getPackageType(elements.getOrCreatePackageElement(null, identifier));
+          }
+          ArtificialPackageElement packageElement =
+              (ArtificialPackageElement)
+                  elements.getCanonicalElement(
+                      Objects.requireNonNull(
+                          javacTrees.getElement(new TreePath(treePath.getCompilationUnit()))));
+          return types.getDeclaredType(elements.getOrCreateTypeElement(packageElement, identifier));
+        }
+      case ANNOTATED_TYPE:
+        AnnotatedTypeTree annotatedTypeTree = (AnnotatedTypeTree) tree;
+        ExpressionTree underlyingTree = annotatedTypeTree.getUnderlyingType();
+        TreePath underlyingTreePath = TreePath.getPath(treePath, underlyingTree);
+        return getInferredType(underlyingTreePath);
+      // $CASES-OMITTED$
+      default:
+        throw new AssertionError(String.format("Unexpected tree kind %s", tree.getKind()));
+    }
+  }
+
+  @Nullable
+  private TypeMirror getImportedType(TreePath treePath) {
+    TreePath importedIdentifierPath = getImportedIdentifier(treePath);
+    if (importedIdentifierPath != null) {
+      return getCanonicalType(importedIdentifierPath);
+    }
+
+    return null;
+  }
+
+  private boolean isProbablyPackageName(CharSequence identifier) {
+    return Character.isLowerCase(identifier.charAt(0));
+  }
+
+  /**
+   * Canonicalizes any {@link javax.lang.model.element.Element}s, {@link TypeMirror}s, or {@link
+   * AnnotationValue}s found in the given object, which is expected to have been obtained by calling
+   * {@link AnnotationValue#getValue()}.
+   */
+  /* package */ Object getCanonicalValue(AnnotationValue annotationValue, TreePath valueTreePath) {
+    return annotationValue.accept(
+        new SimpleAnnotationValueVisitor8<Object, Void>() {
+          @Override
+          public Object visitType(TypeMirror t, Void aVoid) {
+            return getCanonicalType(t, valueTreePath);
+          }
+
+          @Override
+          public Object visitEnumConstant(VariableElement c, Void aVoid) {
+            return Objects.requireNonNull(elements.getCanonicalElement(c));
+          }
+
+          @Override
+          public Object visitAnnotation(AnnotationMirror a, Void aVoid) {
+            return new TreeBackedAnnotationMirror(a, valueTreePath, PostEnterCanonicalizer.this);
+          }
+
+          @Override
+          public Object visitArray(List<? extends AnnotationValue> values, Void aVoid) {
+            Tree valueTree = valueTreePath.getLeaf();
+            if (valueTree instanceof NewArrayTree) {
+              NewArrayTree tree = (NewArrayTree) valueTree;
+              List<? extends ExpressionTree> valueTrees = tree.getInitializers();
+
+              List<TreeBackedAnnotationValue> result = new ArrayList<>();
+              for (int i = 0; i < values.size(); i++) {
+                result.add(
+                    new TreeBackedAnnotationValue(
+                        values.get(i),
+                        new TreePath(valueTreePath, valueTrees.get(i)),
+                        PostEnterCanonicalizer.this));
+              }
+              return result;
+            } else {
+              return Collections.singletonList(
+                  new TreeBackedAnnotationValue(
+                      values.get(0),
+                      new TreePath(valueTreePath, valueTree),
+                      PostEnterCanonicalizer.this));
+            }
+          }
+
+          @Override
+          public Object visitString(String s, Void aVoid) {
+            if (getUnderlyingType(valueTreePath).getKind() == TypeKind.ERROR) {
+              Tree leaf = valueTreePath.getLeaf();
+              if (leaf instanceof MemberSelectTree
+                  && ((MemberSelectTree) leaf).getIdentifier().contentEquals("class")) {
+                TreePath classNamePath =
+                    new TreePath(valueTreePath, ((MemberSelectTree) leaf).getExpression());
+
+                return getCanonicalType(classNamePath);
+              } else {
+                javacTrees.printMessage(
+                    Diagnostic.Kind.ERROR,
+                    "Could not resolve constant. Either inline the value or add"
+                        + " required_for_source_only_abi = True to the build rule that contains"
+                        + " it.",
+                    leaf,
+                    valueTreePath.getCompilationUnit());
+              }
+            }
+
+            return super.visitString(s, aVoid);
+          }
+
+          @Override
+          protected Object defaultAction(Object o, Void aVoid) {
+            // Everything else (primitives, Strings, enums) doesn't need canonicalization
+            return o;
+          }
+        },
+        null);
+  }
+
+  @Nullable
+  private TreePath getImportedIdentifier(TreePath identifierTreePath) {
+    IdentifierTree identifierTree = (IdentifierTree) identifierTreePath.getLeaf();
+
+    Map<Name, TreePath> imports =
+        this.imports.computeIfAbsent(
+            identifierTreePath.getCompilationUnit(),
+            compilationUnitTree -> {
+              Map<Name, TreePath> result = new HashMap<>();
+              TreePath rootPath = new TreePath(compilationUnitTree);
+              for (ImportTree importTree : compilationUnitTree.getImports()) {
+                if (importTree.isStatic()) {
+                  continue;
+                }
+
+                MemberSelectTree importedIdentifierTree =
+                    (MemberSelectTree) importTree.getQualifiedIdentifier();
+                if (importedIdentifierTree.getIdentifier().contentEquals("*")) {
+                  continue;
+                }
+
+                TreePath importTreePath = new TreePath(rootPath, importTree);
+                TreePath importedIdentifierTreePath =
+                    new TreePath(importTreePath, importedIdentifierTree);
+                result.put(importedIdentifierTree.getIdentifier(), importedIdentifierTreePath);
+              }
+              return result;
+            });
+
+    return imports.get(identifierTree.getName());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ResolvedType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ResolvedType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ResolvedType.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.Collections;
+import java.util.Set;
+import javax.lang.model.element.TypeElement;
+
+/**
+ * Represents a resolved type as simulated by {@link
+ * com.facebook.buck.jvm.java.abi.source.CompilerTypeResolutionSimulator}.
+ */
+class ResolvedType {
+  public final ResolvedTypeKind kind;
+  public final TypeElement type;
+  public final Set<String> missingDependencies;
+
+  public ResolvedType(ResolvedTypeKind kind, TypeElement type) {
+    this(kind, type, Collections.emptySet());
+  }
+
+  public ResolvedType(ResolvedTypeKind kind, TypeElement type, Set<String> missingDependencies) {
+    this.kind = kind;
+    this.type = type;
+    this.missingDependencies = missingDependencies;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ResolvedTypeKind.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ResolvedTypeKind.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ResolvedTypeKind.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+enum ResolvedTypeKind {
+  /** Type would resolve successfully. */
+  RESOLVED_TYPE,
+  /** Type would resolve as an {@link javax.lang.model.type.ErrorType}. */
+  ERROR_TYPE,
+  /** The compiler would crash trying to resolve the type. */
+  CRASH;
+
+  public ResolvedTypeKind merge(ResolvedTypeKind other) {
+    return (this.compareTo(other) >= 0) ? this : other;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneArrayType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneArrayType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneArrayType.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.Collections;
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.type.ArrayType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * An implementation of {@link ArrayType} that is not dependent on any particular compiler
+ * implementation. It requires a {@link TypeMirror}, but does not depend on any particular
+ * implementation of it (beyond the spec).
+ */
+class StandaloneArrayType extends StandaloneTypeMirror implements ArrayType {
+
+  private final TypeMirror componentType;
+
+  public StandaloneArrayType(TypeMirror componentType) {
+    this(componentType, Collections.emptyList());
+  }
+
+  public StandaloneArrayType(
+      TypeMirror componentType, List<? extends AnnotationMirror> annotations) {
+    super(TypeKind.ARRAY, annotations);
+    this.componentType = componentType;
+  }
+
+  @Override
+  public TypeMirror getComponentType() {
+    return componentType;
+  }
+
+  @Override
+  public String toString() {
+    return String.format("%s[]", componentType.toString());
+  }
+
+  @Override
+  public StandaloneArrayType cloneWithAnnotationMirrors(
+      List<? extends AnnotationMirror> newAnnotations) {
+    return new StandaloneArrayType(this.componentType, newAnnotations);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneDeclaredType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneDeclaredType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneDeclaredType.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.Collections;
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.Types;
+
+/**
+ * An implementation of {@link DeclaredType} that is not dependent on any particular compiler
+ * implementation. It requires {@link javax.lang.model.element.Element} and {@link TypeMirror}
+ * objects, but does not depend on any particular implementation of them (beyond the spec).
+ */
+class StandaloneDeclaredType extends StandaloneTypeMirror implements DeclaredType {
+
+  private final TypeElement typeElement;
+  private final TypeMirror enclosingType;
+  private final List<? extends TypeMirror> typeArguments;
+
+  public StandaloneDeclaredType(Types types, TypeElement typeElement) {
+    this(types, typeElement, Collections.emptyList());
+  }
+
+  public StandaloneDeclaredType(
+      Types types, TypeElement typeElement, List<? extends TypeMirror> typeArguments) {
+    this(typeElement, typeArguments, types.getNoType(TypeKind.NONE));
+  }
+
+  public StandaloneDeclaredType(
+      TypeElement typeElement, List<? extends TypeMirror> typeArguments, TypeMirror enclosingType) {
+    this(typeElement, typeArguments, enclosingType, Collections.emptyList());
+  }
+
+  public StandaloneDeclaredType(
+      TypeElement typeElement,
+      List<? extends TypeMirror> typeArguments,
+      TypeMirror enclosingType,
+      List<? extends AnnotationMirror> annotations) {
+    super(TypeKind.DECLARED, annotations);
+    this.typeElement = typeElement;
+    this.typeArguments = List.copyOf(typeArguments);
+    this.enclosingType = enclosingType;
+  }
+
+  /* package */ StandaloneDeclaredType(TypeElement typeElement) {
+    super(TypeKind.DECLARED, Collections.emptyList());
+    this.typeElement = typeElement;
+    this.typeArguments = Collections.emptyList();
+    this.enclosingType = this;
+  }
+
+  @Override
+  public Element asElement() {
+    return typeElement;
+  }
+
+  @Override
+  public TypeMirror getEnclosingType() {
+    return enclosingType;
+  }
+
+  @Override
+  public List<? extends TypeMirror> getTypeArguments() {
+    return typeArguments;
+  }
+
+  @Override
+  public String toString() {
+    StringBuilder builder = new StringBuilder();
+
+    builder.append(typeElement);
+    if (!typeArguments.isEmpty()) {
+      builder.append('<');
+      for (int i = 0; i < typeArguments.size(); i++) {
+        if (i > 0) {
+          builder.append(',');
+        }
+        builder.append(typeArguments.get(i));
+      }
+      builder.append('>');
+    }
+    return builder.toString();
+  }
+
+  @Override
+  public StandaloneDeclaredType cloneWithAnnotationMirrors(
+      List<? extends AnnotationMirror> newAnnotations) {
+    return new StandaloneDeclaredType(
+        this.typeElement, this.typeArguments, this.enclosingType, newAnnotations);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneExecutableType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneExecutableType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneExecutableType.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.type.ExecutableType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+
+/**
+ * An implementation of {@link ExecutableType} that is not dependent on any particular compiler
+ * implementation. It requires {@link javax.lang.model.element.Element} and {@link TypeMirror}
+ * objects, but does not depend on any particular implementation of them (beyond the spec).
+ */
+class StandaloneExecutableType extends StandaloneTypeMirror implements ExecutableType {
+
+  private final TypeMirror returnType;
+  private final List<? extends TypeVariable> typeVariables;
+  private final List<? extends TypeMirror> parameterTypes;
+  private final List<? extends TypeMirror> thrownTypes;
+
+  public StandaloneExecutableType(
+      TypeMirror returnType,
+      List<? extends TypeVariable> typeVariables,
+      List<? extends TypeMirror> parameterTypes,
+      List<? extends TypeMirror> thrownTypes,
+      List<? extends AnnotationMirror> annotations) {
+    super(TypeKind.EXECUTABLE, annotations);
+    this.returnType = returnType;
+    this.typeVariables = List.copyOf(typeVariables);
+    this.parameterTypes = List.copyOf(parameterTypes);
+    this.thrownTypes = List.copyOf(thrownTypes);
+  }
+
+  @Override
+  public List<? extends TypeVariable> getTypeVariables() {
+    return typeVariables;
+  }
+
+  @Override
+  public TypeMirror getReturnType() {
+    return returnType;
+  }
+
+  @Override
+  public List<? extends TypeMirror> getParameterTypes() {
+    return parameterTypes;
+  }
+
+  @Override
+  @Nullable
+  public TypeMirror getReceiverType() {
+    // TODO(jkeljo): Either implement this adaptively or wait until we eliminate javac 7 support
+    return null;
+  }
+
+  @Override
+  public List<? extends TypeMirror> getThrownTypes() {
+    return thrownTypes;
+  }
+
+  @Override
+  public StandaloneExecutableType cloneWithAnnotationMirrors(
+      List<? extends AnnotationMirror> annotations) {
+    throw new UnsupportedOperationException("Cannot add annotations to a method type");
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneIntersectionType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneIntersectionType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneIntersectionType.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.type.IntersectionType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * An implementation of {@link IntersectionType} that is not dependent on any particular compiler
+ * implementation. It requires a {@link TypeMirror}, but does not depend on any particular
+ * implementation of it (beyond the spec).
+ */
+class StandaloneIntersectionType extends StandaloneTypeMirror implements IntersectionType {
+
+  private final List<TypeMirror> bounds;
+
+  public StandaloneIntersectionType(List<? extends TypeMirror> bounds) {
+    super(TypeKind.INTERSECTION);
+
+    this.bounds = List.copyOf(bounds);
+  }
+
+  @Override
+  public List<? extends TypeMirror> getBounds() {
+    return bounds;
+  }
+
+  @Override
+  public String toString() {
+    StringBuilder builder = new StringBuilder();
+    builder.append("java.lang.Object");
+
+    for (TypeMirror bound : bounds) {
+      builder.append("&");
+      builder.append(bound);
+    }
+
+    return builder.toString();
+  }
+
+  @Override
+  public StandaloneIntersectionType cloneWithAnnotationMirrors(
+      List<? extends AnnotationMirror> annotations) {
+    throw new UnsupportedOperationException("Cannot add annotations to an intersection type");
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandalonePackageType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandalonePackageType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandalonePackageType.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.type.NoType;
+import javax.lang.model.type.TypeKind;
+
+public class StandalonePackageType extends StandaloneTypeMirror implements NoType {
+
+  private final ArtificialPackageElement packageElement;
+
+  public StandalonePackageType(
+      ArtificialPackageElement packageElement, List<? extends AnnotationMirror> annotations) {
+    super(TypeKind.PACKAGE, annotations);
+    this.packageElement = packageElement;
+  }
+
+  public StandalonePackageType(ArtificialPackageElement packageElement) {
+    super(TypeKind.PACKAGE);
+    this.packageElement = packageElement;
+  }
+
+  public ArtificialPackageElement asElement() {
+    return packageElement;
+  }
+
+  @Override
+  public String toString() {
+    return packageElement.getQualifiedName().toString();
+  }
+
+  @Override
+  public StandalonePackageType cloneWithAnnotationMirrors(
+      List<? extends AnnotationMirror> annotations) {
+    return new StandalonePackageType(this.packageElement, annotations);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneTypeMirror.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneTypeMirror.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneTypeMirror.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.lang.annotation.Annotation;
+import java.util.Collections;
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.type.ArrayType;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.ErrorType;
+import javax.lang.model.type.ExecutableType;
+import javax.lang.model.type.IntersectionType;
+import javax.lang.model.type.NoType;
+import javax.lang.model.type.NullType;
+import javax.lang.model.type.PrimitiveType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+import javax.lang.model.type.TypeVisitor;
+import javax.lang.model.type.UnionType;
+import javax.lang.model.type.WildcardType;
+
+/**
+ * An implementation of {@link TypeMirror} that is not dependent on any particular compiler
+ * implementation. Subclasses may require {@link javax.lang.model.element.Element}s and/or {@link
+ * javax.lang.model.type.TypeMirror}s, but do not depend on any particular implementation of them
+ * (beyond the spec).
+ */
+abstract class StandaloneTypeMirror implements TypeMirror {
+
+  private final TypeKind kind;
+  private final List<? extends AnnotationMirror> annotations;
+
+  protected StandaloneTypeMirror(TypeKind kind) {
+    this(kind, Collections.emptyList());
+  }
+
+  protected StandaloneTypeMirror(TypeKind kind, List<? extends AnnotationMirror> annotations) {
+    this.kind = kind;
+    this.annotations = List.copyOf(annotations);
+  }
+
+  @Override
+  public TypeKind getKind() {
+    return kind;
+  }
+
+  @Override
+  public <R, P> R accept(TypeVisitor<R, P> v, P p) {
+    switch (kind) {
+      case BOOLEAN:
+      case BYTE:
+      case SHORT:
+      case INT:
+      case LONG:
+      case CHAR:
+      case FLOAT:
+      case DOUBLE:
+        return v.visitPrimitive((PrimitiveType) this, p);
+      case PACKAGE:
+      case MODULE:
+      case VOID:
+      case NONE:
+        return v.visitNoType((NoType) this, p);
+      case NULL:
+        return v.visitNull((NullType) this, p);
+      case ARRAY:
+        return v.visitArray((ArrayType) this, p);
+      case DECLARED:
+        return v.visitDeclared((DeclaredType) this, p);
+      case ERROR:
+        return v.visitError((ErrorType) this, p);
+      case TYPEVAR:
+        return v.visitTypeVariable((TypeVariable) this, p);
+      case WILDCARD:
+        return v.visitWildcard((WildcardType) this, p);
+      case EXECUTABLE:
+        return v.visitExecutable((ExecutableType) this, p);
+      case OTHER:
+        return v.visit(this, p);
+      case UNION:
+        return v.visitUnion((UnionType) this, p);
+      case INTERSECTION:
+        return v.visitIntersection((IntersectionType) this, p);
+      default:
+        throw new AssertionError(String.format("Unknown TypeKind: %s", kind));
+    }
+  }
+
+  @Override
+  public List<? extends AnnotationMirror> getAnnotationMirrors() {
+    return this.annotations;
+  }
+
+  public abstract StandaloneTypeMirror cloneWithAnnotationMirrors(
+      List<? extends AnnotationMirror> annotations);
+
+  @Override
+  public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
+    // This one is really difficult to implement, and also generally a bad thing to use anyway
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) {
+    // This one is really difficult to implement, and also generally a bad thing to use anyway
+    throw new UnsupportedOperationException();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneTypeVariable.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneTypeVariable.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneTypeVariable.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.util.Collections;
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.TypeParameterElement;
+import javax.lang.model.type.NullType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+import javax.lang.model.util.Types;
+
+/**
+ * An implementation of {@link TypeVariable} that is not dependent on any particular compiler
+ * implementation. It requires {@link javax.lang.model.element.Element} and {@link TypeMirror}
+ * objects, but does not depend on any particular implementation of them (beyond the spec).
+ */
+class StandaloneTypeVariable extends StandaloneTypeMirror implements TypeVariable {
+
+  private final TypeParameterElement element;
+  private final NullType lowerBound;
+  @Nullable private TypeMirror upperBound;
+
+  public StandaloneTypeVariable(Types types, TypeParameterElement element) {
+    this(types, element, Collections.emptyList());
+  }
+
+  public StandaloneTypeVariable(
+      Types types, TypeParameterElement element, List<? extends AnnotationMirror> annotations) {
+    super(TypeKind.TYPEVAR, annotations);
+    this.element = element;
+    lowerBound = types.getNullType();
+  }
+
+  private StandaloneTypeVariable(
+      TypeParameterElement element,
+      NullType lowerBound,
+      List<? extends AnnotationMirror> annotations) {
+    super(TypeKind.TYPEVAR, annotations);
+    this.element = element;
+    this.lowerBound = lowerBound;
+  }
+
+  @Override
+  public Element asElement() {
+    return element;
+  }
+
+  @Override
+  public TypeMirror getUpperBound() {
+    if (upperBound == null) {
+      List<? extends TypeMirror> bounds = element.getBounds();
+
+      if (bounds.size() == 1) {
+        upperBound = bounds.get(0);
+      } else {
+        upperBound = new StandaloneIntersectionType(bounds);
+      }
+    }
+    return upperBound;
+  }
+
+  @Override
+  public TypeMirror getLowerBound() {
+    // TODO(jkeljo): Capture conversion can create a non-null lower bound, but we don't need it yet.
+    return lowerBound;
+  }
+
+  @Override
+  public String toString() {
+    return element.toString();
+  }
+
+  @Override
+  public StandaloneTypeVariable cloneWithAnnotationMirrors(
+      List<? extends AnnotationMirror> newAnnotations) {
+    return new StandaloneTypeVariable(this.element, this.lowerBound, newAnnotations);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneWildcardType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneWildcardType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/StandaloneWildcardType.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.WildcardType;
+
+/**
+ * An implementation of {@link WildcardType} that is not dependent on any particular compiler
+ * implementation. It requires a {@link TypeMirror}, but does not depend on any particular
+ * implementation of it (beyond the spec).
+ */
+class StandaloneWildcardType extends StandaloneTypeMirror implements WildcardType {
+
+  @Nullable private final TypeMirror extendsBound;
+  @Nullable private final TypeMirror superBound;
+
+  public StandaloneWildcardType(
+      @Nullable TypeMirror extendsBound, @Nullable TypeMirror superBound) {
+    super(TypeKind.WILDCARD);
+    this.extendsBound = extendsBound;
+    this.superBound = superBound;
+  }
+
+  public StandaloneWildcardType(
+      @Nullable TypeMirror extendsBound,
+      @Nullable TypeMirror superBound,
+      List<? extends AnnotationMirror> annotations) {
+    super(TypeKind.WILDCARD, annotations);
+    this.extendsBound = extendsBound;
+    this.superBound = superBound;
+  }
+
+  @Override
+  @Nullable
+  public TypeMirror getExtendsBound() {
+    return extendsBound;
+  }
+
+  @Override
+  @Nullable
+  public TypeMirror getSuperBound() {
+    return superBound;
+  }
+
+  @Override
+  public String toString() {
+    StringBuilder builder = new StringBuilder();
+
+    builder.append('?');
+    if (extendsBound != null) {
+      builder.append(" extends ");
+      builder.append(extendsBound);
+    } else if (superBound != null) {
+      builder.append(" super ");
+      builder.append(superBound);
+    }
+
+    return builder.toString();
+  }
+
+  @Override
+  public StandaloneTypeMirror cloneWithAnnotationMirrors(
+      List<? extends AnnotationMirror> newAnnotations) {
+    return new StandaloneWildcardType(this.extendsBound, this.superBound, newAnnotations);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotatedConstruct.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotatedConstruct.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotatedConstruct.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.lang.model.AnnotationValueScanner8;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.lang.annotation.Annotation;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import javax.lang.model.AnnotatedConstruct;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * An implementation of {@link javax.lang.model.AnnotatedConstruct} that uses only the information
+ * available from a {@link com.sun.source.tree.Tree}. This results in an incomplete implementation;
+ * see documentation for individual methods and {@link com.facebook.buck.jvm.java.abi.source} for
+ * more information.
+ */
+public class TreeBackedAnnotatedConstruct implements ArtificialAnnotatedConstruct {
+  private final AnnotatedConstruct underlyingConstruct;
+  private final List<TreeBackedAnnotationMirror> annotationMirrors = new ArrayList<>();
+
+  public TreeBackedAnnotatedConstruct(AnnotatedConstruct underlyingConstruct) {
+    this.underlyingConstruct = underlyingConstruct;
+  }
+
+  /* package */ void addAnnotationMirror(TreeBackedAnnotationMirror annotationMirror) {
+    annotationMirrors.add(annotationMirror);
+  }
+
+  @Override
+  public List<? extends ArtificialAnnotationMirror> getAnnotationMirrors() {
+    return Collections.unmodifiableList(annotationMirrors);
+  }
+
+  @Override
+  public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
+    return TreeBackedAnnotationFactory.createOrGetUnderlying(
+        this, underlyingConstruct, annotationType);
+  }
+
+  @Override
+  public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) {
+    return underlyingConstruct.getAnnotationsByType(annotationType);
+  }
+
+  /**
+   * Attempt to call {@link AnnotatedConstruct#getAnnotation(Class)} on the underlying construct,
+   * but throw a more useful exception if it throws.
+   */
+  /* package */ <A extends Annotation> A getAnnotationWithBetterErrors(Class<A> annotationType) {
+    try {
+      return underlyingConstruct.getAnnotation(annotationType);
+    } catch (RuntimeException e) {
+      Set<String> problematicTypes = new LinkedHashSet<>();
+      for (TreeBackedAnnotationMirror mirror : annotationMirrors) {
+        if (!mirror
+            .getAnnotationType()
+            .asElement()
+            .getSimpleName()
+            .contentEquals(annotationType.getSimpleName())) {
+          continue;
+        }
+        for (TreeBackedAnnotationValue value : mirror.getElementValues().values()) {
+          new ArgumentCheckingValueVisitor().scan(value, problematicTypes);
+        }
+      }
+      throw new RuntimeException(
+          String.format(
+              "Exception when trying to get annotation %s from element %s.  "
+                  + "These types are not available: %s",
+              annotationType.getSimpleName(), this, problematicTypes),
+          e);
+    }
+  }
+
+  private static class ArgumentCheckingValueVisitor
+      extends AnnotationValueScanner8<Void, Set<String>> {
+    @Nullable
+    @Override
+    public Void visitType(TypeMirror t, Set<String> problems) {
+      if (t instanceof StandaloneDeclaredType
+          && ((StandaloneDeclaredType) t).asElement() instanceof InferredTypeElement) {
+        problems.add(t.toString());
+      }
+      return super.visitType(t, problems);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationFactory.java
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.lang.model.AnnotatedConstruct;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.AbstractAnnotationValueVisitor8;
+
+/**
+ * Support for @{link TreeBackedAnnotatedConstruct#getAnnotation}.
+ *
+ * <p>{@code getAnnotation} can throw unexpected exceptions when building source-only ABIs, due to
+ * some of the classes it tries to load being unavailable. We try to return our own implementations
+ * of the annotations instead, bypassing javac's support altogether. However, if the annotation
+ * processor requests a field that we can't fake, we have to fall back to the underlying annotation.
+ */
+public class TreeBackedAnnotationFactory {
+  public static <A extends Annotation> A createOrGetUnderlying(
+      TreeBackedAnnotatedConstruct annotatedConstruct,
+      AnnotatedConstruct underlyingConstruct,
+      Class<A> annotationType) {
+    for (AnnotationMirror mirror : underlyingConstruct.getAnnotationMirrors()) {
+      if (mirror.getAnnotationType().toString().equals(annotationType.getName()))
+        return annotationType.cast(
+            Proxy.newProxyInstance(
+                annotationType.getClassLoader(),
+                new Class[] {annotationType},
+                new Handler(annotatedConstruct, annotationType, mirror)));
+    }
+    // Either the annotation doesn't exist or name comparison failed in some weird way.
+    // Either way, fall back to the underlying construct.
+    return annotatedConstruct.getAnnotationWithBetterErrors(annotationType);
+  }
+
+  static class Handler implements InvocationHandler {
+    /** Used to get the fallback if we can't satisfy a request. */
+    private final TreeBackedAnnotatedConstruct annotatedConstruct;
+
+    /** Type of this annotation, which the caller can request. */
+    private final Class<? extends Annotation> annotationType;
+
+    /** Safe "bag of values" object that we use to supply values whenever possible. */
+    private final AnnotationMirror mirror;
+
+    /** Cached underlying annotation from {@code underlyingConstruct}, or null if not set yet. */
+    @Nullable Annotation annotationCache;
+
+    /** Cached values from {@code mirror}. */
+    @Nullable private Map<String, AnnotationValue> valueCache = null;
+
+    public Handler(
+        TreeBackedAnnotatedConstruct annotatedConstruct,
+        Class<? extends Annotation> annotationType,
+        AnnotationMirror mirror) {
+      this.annotatedConstruct = annotatedConstruct;
+      this.annotationType = annotationType;
+      this.mirror = mirror;
+    }
+
+    @Override
+    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+      if (method.getName().equals("annotationType")) {
+        return annotationType;
+      }
+
+      if (method.getName().equals("equals")) {
+        // Fall back to comparing the actual annotations.
+        populateAnnotation();
+        if (!Proxy.isProxyClass(args[0].getClass())) {
+          return false;
+        }
+        InvocationHandler rawHandler = Proxy.getInvocationHandler(args[0]);
+        if (!(rawHandler instanceof Handler)) {
+          return false;
+        }
+        Handler other = (Handler) rawHandler;
+        other.populateAnnotation();
+        return annotationCache.equals(other.annotationCache);
+      }
+
+      populateValues();
+      if (!valueCache.containsKey(method.getName())) {
+        throw new IllegalArgumentException("Unrecognized method: " + method.getName());
+      }
+      AnnotationValue value = valueCache.get(method.getName());
+      Object rawValue = new ValueVisitor(method.getReturnType()).visit(value);
+      if (rawValue != null) {
+        return rawValue;
+      }
+
+      // Fall back to trying the annotation.
+      populateAnnotation();
+      try {
+        return method.invoke(annotationCache, args);
+      } catch (InvocationTargetException e) {
+        throw e.getCause();
+      }
+    }
+
+    private void populateAnnotation() {
+      annotationCache = annotatedConstruct.getAnnotationWithBetterErrors(annotationType);
+    }
+
+    private synchronized void populateValues() {
+      if (valueCache == null) {
+        valueCache = new HashMap<>();
+        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
+            TreeBackedElements.getElementValuesWithDefaultsStatic(mirror).entrySet()) {
+          valueCache.put(entry.getKey().getSimpleName().toString(), entry.getValue());
+        }
+      }
+    }
+  }
+
+  /**
+   * Validate the type of the annotation value and return it.
+   *
+   * <p>Returns null if we don't/can't support it.
+   */
+  static class ValueVisitor extends AbstractAnnotationValueVisitor8<Object, Void> {
+    private final Class<?> type;
+
+    ValueVisitor(Class<?> type) {
+      this.type = type;
+    }
+
+    @Override
+    public Object visitBoolean(boolean b, Void aVoid) {
+      if (!type.equals(Boolean.TYPE)) {
+        throw new IllegalArgumentException("Wrong type.");
+      }
+      return b;
+    }
+
+    @Override
+    public Object visitByte(byte b, Void aVoid) {
+      if (!type.equals(Byte.TYPE)) {
+        throw new IllegalArgumentException("Wrong type.");
+      }
+      return b;
+    }
+
+    @Override
+    public Object visitChar(char c, Void aVoid) {
+      if (!type.equals(Character.TYPE)) {
+        throw new IllegalArgumentException("Wrong type.");
+      }
+      return c;
+    }
+
+    @Override
+    public Object visitDouble(double d, Void aVoid) {
+      if (!type.equals(Double.TYPE)) {
+        throw new IllegalArgumentException("Wrong type.");
+      }
+      return d;
+    }
+
+    @Override
+    public Object visitFloat(float f, Void aVoid) {
+      if (!type.equals(Float.TYPE)) {
+        throw new IllegalArgumentException("Wrong type.");
+      }
+      return f;
+    }
+
+    @Override
+    public Object visitInt(int i, Void aVoid) {
+      if (!type.equals(Integer.TYPE)) {
+        throw new IllegalArgumentException("Wrong type.");
+      }
+      return i;
+    }
+
+    @Override
+    public Object visitLong(long i, Void aVoid) {
+      if (!type.equals(Long.TYPE)) {
+        throw new IllegalArgumentException("Wrong type.");
+      }
+      return i;
+    }
+
+    @Override
+    public Object visitShort(short s, Void aVoid) {
+      if (!type.equals(Short.TYPE)) {
+        throw new IllegalArgumentException("Wrong type.");
+      }
+      return s;
+    }
+
+    @Override
+    @Nullable
+    public Object visitString(String s, Void aVoid) {
+      if (type.equals(Class.class)) {
+        // Error types call visitString for some reason.
+        return null;
+      }
+
+      if (!type.equals(String.class)) {
+        throw new IllegalArgumentException("Wrong type.");
+      }
+      return s;
+    }
+
+    @Override
+    @Nullable
+    public Object visitType(TypeMirror t, Void aVoid) {
+      return null;
+    }
+
+    @Override
+    @Nullable
+    public Object visitEnumConstant(VariableElement c, Void aVoid) {
+      return null;
+    }
+
+    @Override
+    @Nullable
+    public Object visitAnnotation(AnnotationMirror a, Void aVoid) {
+      return null;
+    }
+
+    @Override
+    @Nullable
+    public Object visitArray(List<? extends AnnotationValue> vals, Void aVoid) {
+      // TODO: Maybe support this for primitives and strings?
+      return null;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationMirror.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationMirror.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationMirror.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.AnnotationTree;
+import com.sun.source.tree.AssignmentTree;
+import com.sun.source.tree.ExpressionTree;
+import com.sun.source.tree.IdentifierTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.util.TreePath;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Name;
+import javax.lang.model.type.DeclaredType;
+
+class TreeBackedAnnotationMirror implements ArtificialAnnotationMirror {
+  private final AnnotationMirror underlyingAnnotationMirror;
+  private final TreePath treePath;
+  private final AnnotationTree tree;
+  private final PostEnterCanonicalizer canonicalizer;
+
+  @Nullable private DeclaredType type;
+  @Nullable private Map<ExecutableElement, TreeBackedAnnotationValue> elementValues;
+
+  TreeBackedAnnotationMirror(
+      AnnotationMirror underlyingAnnotationMirror,
+      TreePath treePath,
+      PostEnterCanonicalizer canonicalizer) {
+    this.underlyingAnnotationMirror = underlyingAnnotationMirror;
+    this.treePath = treePath;
+    this.tree = (AnnotationTree) treePath.getLeaf();
+    this.canonicalizer = canonicalizer;
+  }
+
+  /* package */ AnnotationMirror getUnderlyingAnnotationMirror() {
+    return underlyingAnnotationMirror;
+  }
+
+  public TreePath getTreePath() {
+    return treePath;
+  }
+
+  @Override
+  public DeclaredType getAnnotationType() {
+    if (type == null) {
+      type =
+          (DeclaredType)
+              canonicalizer.getCanonicalType(
+                  underlyingAnnotationMirror.getAnnotationType(),
+                  treePath,
+                  tree.getAnnotationType());
+    }
+    return type;
+  }
+
+  @Override
+  public Map<ExecutableElement, TreeBackedAnnotationValue> getElementValues() {
+    if (elementValues == null) {
+      Map<ExecutableElement, TreeBackedAnnotationValue> result = new LinkedHashMap<>();
+      Map<String, Tree> trees = new HashMap<>();
+
+      List<? extends ExpressionTree> arguments = tree.getArguments();
+      for (ExpressionTree argument : arguments) {
+        if (argument.getKind() != Tree.Kind.ASSIGNMENT) {
+          trees.put("value", argument);
+        } else {
+          AssignmentTree assignment = (AssignmentTree) argument;
+          IdentifierTree nameTree = (IdentifierTree) assignment.getVariable();
+          trees.put(nameTree.getName().toString(), argument);
+        }
+      }
+
+      for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
+          underlyingAnnotationMirror.getElementValues().entrySet()) {
+        ExecutableElement underlyingKeyElement = entry.getKey();
+
+        Tree valueTree =
+            Objects.requireNonNull(trees.get(entry.getKey().getSimpleName().toString()));
+
+        result.put(
+            canonicalizer.getCanonicalElement(underlyingKeyElement),
+            new TreeBackedAnnotationValue(
+                entry.getValue(), new TreePath(treePath, valueTree), canonicalizer));
+      }
+
+      elementValues = Collections.unmodifiableMap(result);
+    }
+    return elementValues;
+  }
+
+  @Override
+  public String toString() {
+    StringBuilder result = new StringBuilder();
+    result.append("@");
+    result.append(getAnnotationType());
+    Map<ExecutableElement, TreeBackedAnnotationValue> elementValues = getElementValues();
+    if (!elementValues.isEmpty()) {
+      result.append("(");
+      result.append(
+          elementValues.entrySet().stream()
+              .map(
+                  entry -> {
+                    Name key = entry.getKey().getSimpleName();
+                    TreeBackedAnnotationValue value = entry.getValue();
+                    if (elementValues.size() == 1 && key.contentEquals("value")) {
+                      return value.toString();
+                    } else {
+                      return String.format("%s=%s", key, value);
+                    }
+                  })
+              .collect(Collectors.joining(", ")));
+      result.append(")");
+    }
+
+    return result.toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationValue.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationValue.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedAnnotationValue.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.AssignmentTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.util.TreePath;
+import java.util.List;
+import java.util.stream.Collectors;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.AnnotationValueVisitor;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.SimpleAnnotationValueVisitor8;
+
+class TreeBackedAnnotationValue implements ArtificialAnnotationValue {
+  private final AnnotationValue underlyingAnnotationValue;
+  private final TreePath treePath;
+  private final Tree valueTree;
+  private final PostEnterCanonicalizer canonicalizer;
+
+  @Nullable private Object value;
+
+  TreeBackedAnnotationValue(
+      AnnotationValue underlyingAnnotationValue,
+      TreePath treePath,
+      PostEnterCanonicalizer canonicalizer) {
+    this.underlyingAnnotationValue = underlyingAnnotationValue;
+    Tree tree = treePath.getLeaf();
+    if (tree instanceof AssignmentTree) {
+      AssignmentTree assignmentTree = (AssignmentTree) tree;
+      valueTree = assignmentTree.getExpression();
+      this.treePath = new TreePath(treePath, valueTree);
+    } else {
+      valueTree = tree;
+      this.treePath = treePath;
+    }
+    this.canonicalizer = canonicalizer;
+  }
+
+  /* package */ AnnotationValue getUnderlyingAnnotationValue() {
+    return underlyingAnnotationValue;
+  }
+
+  @Override
+  public Object getValue() {
+    if (value == null) {
+      value = canonicalizer.getCanonicalValue(underlyingAnnotationValue, treePath);
+    }
+    return value;
+  }
+
+  @Override
+  public <R, P> R accept(AnnotationValueVisitor<R, P> v, @Nullable P p) {
+    Object underlyingValue = underlyingAnnotationValue.getValue();
+    Object value = getValue();
+
+    if (underlyingValue.equals(value)) {
+      return underlyingAnnotationValue.accept(v, p);
+    }
+
+    if (value instanceof TreeBackedVariableElement) {
+      return v.visitEnumConstant((TreeBackedVariableElement) value, p);
+    } else if (value instanceof TypeMirror) {
+      return v.visitType((TypeMirror) value, p);
+    } else if (value instanceof TreeBackedAnnotationMirror) {
+      return v.visitAnnotation((TreeBackedAnnotationMirror) value, p);
+    } else if (value instanceof List) {
+      @SuppressWarnings("unchecked")
+      List<? extends AnnotationValue> valuesList = (List<? extends AnnotationValue>) value;
+      return v.visitArray(valuesList, p);
+    } else {
+      throw new IllegalStateException(String.format("Unexpected annotation value: %s", value));
+    }
+  }
+
+  @Override
+  public String toString() {
+    return accept(
+        new SimpleAnnotationValueVisitor8<String, Void>() {
+          @Override
+          protected String defaultAction(Object o, Void aVoid) {
+            return o.toString();
+          }
+
+          @Override
+          public String visitByte(byte b, Void aVoid) {
+            return String.format("(byte)0x%x", b);
+          }
+
+          @Override
+          public String visitChar(char c, Void aVoid) {
+            return String.format("'%c'", c);
+          }
+
+          @Override
+          public String visitString(String s, Void aVoid) {
+            return String.format("\"%s\"", s);
+          }
+
+          @Override
+          public String visitLong(long l, Void aVoid) {
+            return String.format("%dL", l);
+          }
+
+          @Override
+          public String visitFloat(float f, Void aVoid) {
+            return String.format("%.1ff", f);
+          }
+
+          @Override
+          public String visitEnumConstant(VariableElement c, Void aVoid) {
+            return c.toString();
+          }
+
+          @Override
+          public String visitType(TypeMirror t, Void aVoid) {
+            return String.format("%s.class", t.toString());
+          }
+
+          @Override
+          public String visitArray(List<? extends AnnotationValue> vals, Void aVoid) {
+            return String.format(
+                "{%s}",
+                vals.stream().map(val -> val.accept(this, null)).collect(Collectors.joining(", ")));
+          }
+        },
+        null);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedElement.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.Tree;
+import com.sun.source.util.TreePath;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.Name;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * An implementation of {@link Element} that uses only the information available from a {@link
+ * com.sun.source.tree.Tree}. This results in an incomplete implementation; see documentation for
+ * individual methods and {@link com.facebook.buck.jvm.java.abi.source} for more information.
+ */
+public abstract class TreeBackedElement extends TreeBackedAnnotatedConstruct
+    implements ArtificialElement {
+  private final Element underlyingElement;
+  @Nullable private final TreeBackedElement enclosingElement;
+  private final List<Element> enclosedElements = new ArrayList<>();
+  @Nullable private final PostEnterCanonicalizer canonicalizer;
+
+  @Nullable private final TreePath treePath;
+
+  public TreeBackedElement(
+      Element underlyingElement,
+      @Nullable TreeBackedElement enclosingElement,
+      @Nullable TreePath treePath,
+      @Nullable PostEnterCanonicalizer canonicalizer) {
+    super(underlyingElement);
+    this.underlyingElement = underlyingElement;
+    this.enclosingElement = enclosingElement;
+    // Some element types don't appear as members of enclosingElement.getEnclosedElements, so
+    // it's up to each subtype's constructor to decide whether to add itself or not.
+    this.treePath = treePath;
+    this.canonicalizer = canonicalizer;
+  }
+
+  public Element getUnderlyingElement() {
+    return underlyingElement;
+  }
+
+  protected final PostEnterCanonicalizer getCanonicalizer() {
+    return Objects.requireNonNull(canonicalizer);
+  }
+
+  public abstract void complete();
+
+  @Nullable
+  /* package */ TreePath getTreePath() {
+    return treePath;
+  }
+
+  @Nullable
+  /* package */ Tree getTree() {
+    return treePath == null ? null : treePath.getLeaf();
+  }
+
+  @Override
+  public ElementKind getKind() {
+    return underlyingElement.getKind();
+  }
+
+  @Override
+  public Set<Modifier> getModifiers() {
+    return underlyingElement.getModifiers();
+  }
+
+  @Override
+  public Name getSimpleName() {
+    return underlyingElement.getSimpleName();
+  }
+
+  @Override
+  @Nullable
+  public TreeBackedElement getEnclosingElement() {
+    return enclosingElement;
+  }
+
+  @Override
+  public List<? extends Element> getEnclosedElements() {
+    return Collections.unmodifiableList(enclosedElements);
+  }
+
+  @Override
+  public void addEnclosedElement(Element element) {
+    enclosedElements.add(element);
+  }
+
+  @Override
+  public abstract TypeMirror asType();
+
+  @Override
+  public String toString() {
+    return underlyingElement.toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedElements.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedElements.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedElements.java
@@ -0,0 +1,369 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.plugin.adapter.ElementsExtendedImpl;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.facebook.buck.util.liteinfersupport.PropagatesNullable;
+import com.sun.source.util.Trees;
+import java.io.Writer;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.QualifiedNameable;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.ElementFilter;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.Types;
+
+/**
+ * An implementation of {@link Elements} using just the AST of a single module, without its
+ * dependencies. Of necessity, such an implementation will need to make assumptions about the
+ * meanings of some names, and thus must be used with care. See documentation for individual methods
+ * and {@link com.facebook.buck.jvm.java.abi.source} for more information.
+ */
+class TreeBackedElements extends ElementsExtendedImpl {
+
+  private final Elements javacElements;
+  private final Map<Element, TreeBackedElement> treeBackedElements = new HashMap<>();
+  private final Map<Name, ArtificialTypeElement> knownTypes = new HashMap<>();
+  private final Map<Name, ArtificialPackageElement> knownPackages = new HashMap<>();
+
+  public TreeBackedElements(Elements javacElements, Types javacTypes, Trees trees) {
+    super(javacElements, javacTypes, trees);
+    this.javacElements = javacElements;
+  }
+
+  /* package */ void clear() {
+    treeBackedElements.clear();
+    knownTypes.clear();
+    knownPackages.clear();
+  }
+
+  public void complete() {
+    for (TreeBackedElement element : treeBackedElements.values()) {
+      element.complete();
+    }
+  }
+
+  public <UnderlyingElement extends Element, WrappedElement extends TreeBackedElement>
+      WrappedElement enterElement(
+          UnderlyingElement underlyingElement,
+          Function<UnderlyingElement, WrappedElement> constructor) {
+    @SuppressWarnings("unchecked") // This function is the only one that inserts to this map
+    WrappedElement result = (WrappedElement) treeBackedElements.get(underlyingElement);
+    if (result != null) {
+      return result;
+    }
+
+    result = constructor.apply(underlyingElement);
+    treeBackedElements.put(underlyingElement, result);
+    if (result instanceof TreeBackedTypeElement) {
+      TreeBackedTypeElement typeElement = (TreeBackedTypeElement) result;
+      knownTypes.put(typeElement.getQualifiedName(), typeElement);
+    } else if (result instanceof TreeBackedPackageElement) {
+      TreeBackedPackageElement packageElement = (TreeBackedPackageElement) result;
+      knownPackages.put(packageElement.getQualifiedName(), packageElement);
+    }
+    return result;
+  }
+
+  @Nullable
+  /* package */ PackageElement getCanonicalElement(@Nullable PackageElement element) {
+    return (PackageElement) getCanonicalElement((Element) element);
+  }
+
+  @Nullable
+  /* package */ TypeElement getCanonicalElement(@Nullable TypeElement element) {
+    return (TypeElement) getCanonicalElement((Element) element);
+  }
+
+  @Nullable
+  /* package */ ExecutableElement getCanonicalElement(@Nullable ExecutableElement element) {
+    return (ExecutableElement) getCanonicalElement((Element) element);
+  }
+
+  /**
+   * Given a javac Element, gets the element that should be used by callers to refer to it. For
+   * elements that have ASTs, that will be a TreeBackedElement; otherwise the javac Element itself.
+   */
+  /* package */ Element getCanonicalElement(@PropagatesNullable Element element) {
+    Element result = treeBackedElements.get(element);
+    if (result == null) {
+      result = element;
+    }
+
+    return result;
+  }
+
+  /* package */ Element[] getJavacElements(Element[] elements) {
+    return Arrays.stream(elements).map(this::getJavacElement).toArray(Element[]::new);
+  }
+
+  /* package */ TypeElement getJavacElement(TypeElement element) {
+    return (TypeElement) getJavacElement((Element) element);
+  }
+
+  /* package */ ExecutableElement getJavacElement(ExecutableElement element) {
+    return (ExecutableElement) getJavacElement((Element) element);
+  }
+
+  /* package */ Element getJavacElement(Element element) {
+    if (element instanceof TreeBackedElement) {
+      TreeBackedElement treeBackedElement = (TreeBackedElement) element;
+      return treeBackedElement.getUnderlyingElement();
+    } else if (element instanceof InferredElement) {
+      throw new IllegalArgumentException("Inferred elements have no javac element");
+    }
+
+    return element;
+  }
+
+  /* package */ AnnotationMirror getJavacAnnotation(AnnotationMirror annotation) {
+    if (annotation instanceof TreeBackedAnnotationMirror) {
+      TreeBackedAnnotationMirror treeBackedAnnotation = (TreeBackedAnnotationMirror) annotation;
+      return treeBackedAnnotation.getUnderlyingAnnotationMirror();
+    }
+
+    return annotation;
+  }
+
+  /* package */ AnnotationValue getJavacAnnotationValue(AnnotationValue value) {
+    if (value instanceof TreeBackedAnnotationValue) {
+      TreeBackedAnnotationValue treeBackedValue = (TreeBackedAnnotationValue) value;
+      return treeBackedValue.getUnderlyingAnnotationValue();
+    }
+
+    return value;
+  }
+
+  public ArtificialPackageElement getOrCreatePackageElement(
+      @Nullable PackageElement enclosingPackage, Name simpleName) {
+    Name qualifiedName = getFullyQualifiedName(enclosingPackage, simpleName);
+    ArtificialPackageElement result = getPackageElement(qualifiedName);
+    if (result == null) {
+      result = new InferredPackageElement(simpleName, qualifiedName);
+      knownPackages.put(qualifiedName, result);
+    }
+    return result;
+  }
+
+  /**
+   * Gets the package element with the given name. If a package with the given name is referenced in
+   * the code or exists in the classpath, returns the corresponding element. Otherwise returns null.
+   */
+  @Override
+  @Nullable
+  public ArtificialPackageElement getPackageElement(CharSequence qualifiedNameString) {
+    Name qualifiedName = getName(qualifiedNameString);
+
+    if (!knownPackages.containsKey(qualifiedName)) {
+      PackageElement javacElement = javacElements.getPackageElement(qualifiedName);
+      if (javacElement != null) {
+        // If none of the packages for which we have parse trees matches this fully-qualified name,
+        // ask javac. javac will check the classpath, which will pick up built-ins (like java.lang)
+        // and any packages from dependency targets that are already compiled and on the classpath.
+        // Because we may need to add inferred types to the package, we wrap it up in our own.
+        knownPackages.put(qualifiedName, new TreeBackedPackageElement(javacElement));
+      }
+    }
+
+    return knownPackages.get(qualifiedName);
+  }
+
+  public ArtificialTypeElement getOrCreateTypeElement(
+      ArtificialQualifiedNameable enclosingElement, Name simpleName) throws CompilerErrorException {
+    Name fullyQualifiedName = getFullyQualifiedName(enclosingElement, simpleName);
+    ArtificialTypeElement result = (ArtificialTypeElement) getTypeElement(fullyQualifiedName);
+    if (result == null) {
+      if (enclosingElement instanceof TreeBackedTypeElement) {
+        throw new CompilerErrorException(
+            String.format(
+                "cannot find symbol generating source-only ABI%nBuild the #source-abi flavor of"
+                    + " this rule to see if the symbol is truly missing or if the rule just needs a"
+                    + " source_only_abi_dep."));
+      }
+      result = new InferredTypeElement(simpleName, fullyQualifiedName, enclosingElement);
+      knownTypes.put(fullyQualifiedName, result);
+    }
+    return result;
+  }
+
+  /**
+   * Gets the type element with the given name. If a class with the given name is referenced in the
+   * code or exists in the classpath, returns the corresponding element. Otherwise returns null.
+   */
+  @Override
+  @Nullable
+  public TypeElement getTypeElement(CharSequence fullyQualifiedCharSequence) {
+    Name fullyQualifiedName = getName(fullyQualifiedCharSequence);
+    if (!knownTypes.containsKey(fullyQualifiedName)) {
+      // If none of the types for which we have parse trees matches this fully-qualified name,
+      // ask javac. javac will check the classpath, which will pick up built-ins (like java.lang)
+      // and any types from dependency targets that are already compiled and on the classpath.
+      // Because our tree-backed elements and javac's elements are sharing a name table, we
+      // should be able to mix implementations without causing too much trouble.
+      TypeElement javacElement = javacElements.getTypeElement(fullyQualifiedName);
+      if (javacElement != null) {
+        return javacElement;
+      }
+    }
+
+    return knownTypes.get(fullyQualifiedName);
+  }
+
+  @Override
+  public Map<? extends ExecutableElement, ? extends AnnotationValue> getElementValuesWithDefaults(
+      AnnotationMirror a) {
+    return getElementValuesWithDefaultsStatic(a);
+  }
+
+  static Map<? extends ExecutableElement, ? extends AnnotationValue>
+      getElementValuesWithDefaultsStatic(AnnotationMirror a) {
+    Map<ExecutableElement, AnnotationValue> result = new HashMap<>(a.getElementValues());
+
+    TypeElement annotationType = (TypeElement) a.getAnnotationType().asElement();
+    List<ExecutableElement> parameters =
+        ElementFilter.methodsIn(annotationType.getEnclosedElements());
+    for (ExecutableElement parameter : parameters) {
+      if (!result.containsKey(parameter) && parameter.getDefaultValue() != null) {
+        result.put(parameter, parameter.getDefaultValue());
+      }
+    }
+
+    return result;
+  }
+
+  @Override
+  @Nullable
+  public String getDocComment(Element e) {
+    return javacElements.getDocComment(getJavacElement(e));
+  }
+
+  @Override
+  public boolean isDeprecated(Element e) {
+    return javacElements.isDeprecated(getJavacElement(e));
+  }
+
+  @Override
+  public Name getBinaryName(TypeElement type) {
+    if (type instanceof InferredTypeElement) {
+      StringBuilder nameBuilder = new StringBuilder();
+      Element enclosingElement = type.getEnclosingElement();
+      if (enclosingElement instanceof InferredTypeElement) {
+        nameBuilder.append(getBinaryName((TypeElement) enclosingElement));
+        nameBuilder.append("$");
+      } else {
+        // package
+        nameBuilder.append(enclosingElement);
+        nameBuilder.append(".");
+      }
+      nameBuilder.append(type.getSimpleName());
+
+      return getName(nameBuilder);
+    }
+    return javacElements.getBinaryName(getJavacElement(type));
+  }
+
+  @Override
+  public PackageElement getPackageOf(Element type) {
+    return Objects.requireNonNull(
+        getCanonicalElement(javacElements.getPackageOf(getJavacElement(type))));
+  }
+
+  @Override
+  public List<? extends Element> getAllMembers(TypeElement type) {
+    if (type instanceof TreeBackedTypeElement) {
+      return javacElements.getAllMembers(getJavacElement(type)).stream()
+          .map(this::getCanonicalElement)
+          .collect(Collectors.toList());
+    }
+
+    return javacElements.getAllMembers(type);
+  }
+
+  @Override
+  public List<? extends AnnotationMirror> getAllAnnotationMirrors(Element e) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public boolean hides(Element hider, Element hidden) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public boolean overrides(
+      ExecutableElement overrider, ExecutableElement overridden, TypeElement type) {
+    if (type instanceof InferredTypeElement) {
+      throw new UnsupportedOperationException();
+    }
+
+    return javacElements.overrides(
+        getJavacElement(overrider), getJavacElement(overridden), getJavacElement(type));
+  }
+
+  @Override
+  public String getConstantExpression(Object value) {
+    return javacElements.getConstantExpression(value);
+  }
+
+  @Override
+  public void printElements(Writer w, Element... elements) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public Name getName(CharSequence cs) {
+    return javacElements.getName(cs);
+  }
+
+  @Override
+  public boolean isFunctionalInterface(TypeElement type) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public List<? extends AnnotationMirror> getAllTypeAnnotations(Element element) {
+    // NOTE: we need to fetch type annotations from the underlying element since otherwise type
+    // annotation position may not be available.
+    if (element instanceof TreeBackedElement) {
+      element = ((TreeBackedElement) element).getUnderlyingElement();
+    }
+
+    return super.getAllTypeAnnotations(element);
+  }
+
+  private Name getFullyQualifiedName(
+      @Nullable QualifiedNameable enclosingElement, Name simpleName) {
+    for (int i = 0; i < simpleName.length(); i++) {
+      if (simpleName.charAt(i) == '.') {
+        throw new IllegalArgumentException(String.format("%s is not a simple name", simpleName));
+      }
+    }
+
+    if (enclosingElement == null || enclosingElement.getQualifiedName().length() == 0) {
+      return simpleName;
+    } else {
+      return getName(String.format("%s.%s", enclosingElement.getQualifiedName(), simpleName));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedEnter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedEnter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedEnter.java
@@ -0,0 +1,341 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.AnnotationTree;
+import com.sun.source.tree.ClassTree;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.tree.Tree.Kind;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.TreePathScanner;
+import com.sun.source.util.Trees;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Queue;
+import java.util.Set;
+import java.util.stream.Collectors;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.TypeParameterElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.util.ElementScanner8;
+import javax.tools.JavaFileObject;
+
+/**
+ * Creates {@link TreeBackedElement}s for each element in the {@link CompilationUnitTree}s known to
+ * the compiler. This is analogous to the "Enter" phase of javac.
+ */
+class TreeBackedEnter {
+
+  private final TreeBackedElements elements;
+  private final TreeBackedTypes types;
+  private final Trees javacTrees;
+  // asdf
+  private final EnteringElementScanner elementScanner = new EnteringElementScanner();
+  private final PostEnterCanonicalizer canonicalizer;
+
+  TreeBackedEnter(TreeBackedElements elements, TreeBackedTypes types, Trees javacTrees) {
+    this.elements = elements;
+    this.types = types;
+    this.javacTrees = javacTrees;
+    canonicalizer = new PostEnterCanonicalizer(elements, types, javacTrees);
+  }
+
+  public void enter(CompilationUnitTree compilationUnit) {
+    elementScanner.enter(compilationUnit);
+  }
+
+  private class EnteringElementScanner extends ElementScanner8<Void, Void> {
+
+    private final Deque<TreeBackedElement> contextStack = new ArrayDeque<>();
+    @Nullable private TreePath currentPath;
+    @Nullable private Tree currentTree;
+    @Nullable private ElementTreeFinder elementTreeFinder;
+    @Nullable private TreeBackedPackageElement currentPackage;
+
+    private TreeBackedElement getCurrentContext() {
+      return contextStack.peek();
+    }
+
+    private TreePath getCurrentPath() {
+      return Objects.requireNonNull(currentPath);
+    }
+
+    public void enter(CompilationUnitTree compilationUnitTree) {
+      new TreePathScanner<Void, Void>() {
+        @Override
+        public Void visitCompilationUnit(CompilationUnitTree node, Void aVoid) {
+          elementTreeFinder = ElementTreeFinder.forCompilationUnit(compilationUnitTree, javacTrees);
+          currentPath = getCurrentPath();
+          currentTree = currentPath.getLeaf();
+          try {
+            return super.visitCompilationUnit(node, aVoid);
+          } finally {
+            exitPackageContextIfNecessary();
+            currentPath = null;
+            currentTree = null;
+          }
+        }
+
+        @Override
+        public Void visitAnnotation(AnnotationTree node, Void aVoid) {
+          enterPackageContextIfNecessary();
+          return null;
+        }
+
+        @Override
+        public Void visitClass(ClassTree node, Void aVoid) {
+          enterPackageContextIfNecessary();
+
+          // We use the Tree to find the top-level type elements in a given compilation unit,
+          // then switch to Element scanning so that we can catch elements created by the compiler
+          // that don't have a tree, such as default constructors or the generated methods on enums.
+          TreePath previousPath = currentPath;
+          Tree previousTree = currentTree;
+          currentPath = getCurrentPath();
+          currentTree = currentPath.getLeaf();
+          try {
+            Element element = javacTrees.getElement(currentPath);
+            if (element != null) {
+              EnteringElementScanner.this.scan(element, null);
+            } else if (node.getKind() != Tree.Kind.EMPTY_STATEMENT) {
+              throw new AssertionError(String.format("Unexpected tree kind %s", node.getKind()));
+            }
+          } finally {
+            currentPath = previousPath;
+            currentTree = previousTree;
+          }
+          return null;
+        }
+
+        private void enterPackageContextIfNecessary() {
+          if (currentPackage == null) {
+            currentPackage = enterPackageElement();
+            contextStack.push(currentPackage);
+          }
+        }
+
+        private void exitPackageContextIfNecessary() {
+          if (currentPackage != null) {
+            contextStack.pop();
+            currentPackage = null;
+          }
+        }
+      }.scan(compilationUnitTree, null);
+    }
+
+    private TreeBackedPackageElement enterPackageElement() {
+      CompilationUnitTree compilationUnitTree = getCurrentPath().getCompilationUnit();
+      PackageElement packageElement =
+          (PackageElement) Objects.requireNonNull(javacTrees.getElement(getCurrentPath()));
+      TreeBackedPackageElement treeBackedPackageElement =
+          elements.enterElement(packageElement, this::newTreeBackedPackage);
+      if (compilationUnitTree
+          .getSourceFile()
+          .isNameCompatible("package-info", JavaFileObject.Kind.SOURCE)) {
+        treeBackedPackageElement.setTreePath(getCurrentPath());
+        enterAnnotationMirrors(treeBackedPackageElement);
+      }
+      return treeBackedPackageElement;
+    }
+
+    @Override
+    public Void scan(Element e, @Nullable Void aVoid) {
+      TreePath previousPath = currentPath;
+      Tree previousTree = currentTree;
+      currentTree = Objects.requireNonNull(elementTreeFinder).getTree(e);
+      currentPath = currentTree == null ? null : new TreePath(currentPath, currentTree);
+      try {
+        if (currentPath != null && javacTrees.getElement(currentPath) != e) {
+          throw new AssertionError(
+              String.format(
+                  "Element mismatch!\n  Expected: %s\n  Found: %s\n",
+                  e, javacTrees.getElement(currentPath)));
+        }
+        return super.scan(e, aVoid);
+      } finally {
+        currentPath = previousPath;
+        currentTree = previousTree;
+      }
+    }
+
+    @Override
+    public Void visitType(TypeElement e, Void v) {
+      TreeBackedTypeElement newClass = elements.enterElement(e, this::newTreeBackedType);
+      try (ElementContext c = new ElementContext(newClass)) {
+        scan(reallyGetEnclosedElements(e, getCurrentPath()), v);
+        scan(e.getTypeParameters(), v);
+        return null;
+      }
+    }
+
+    /**
+     * When some method parameters might be ErrorTypes, javac will ignore overloads when entering
+     * elements. On the flip side, there are no trees for generated elements like default
+     * constructors. To make sure we find all the elements, we look at both sources and merge the
+     * lists.
+     */
+    private List<? extends Element> reallyGetEnclosedElements(TypeElement e, TreePath path) {
+      // fromElement contains the elements that the compiler found or generated. Because of
+      // the weird ErrorType behavior, this will be missing elements that the user wrote.
+      List<? extends Element> fromElement = e.getEnclosedElements();
+      Queue<? extends Element> fromElementQueue = new ArrayDeque<>(fromElement);
+      Set<? extends Element> fromElementSet = new HashSet<>(fromElement);
+
+      // fromTree contains the elements that the user wrote. It will be missing compiler-generated
+      // elements.
+      List<? extends Element> fromTree =
+          ((ClassTree) path.getLeaf())
+              .getMembers().stream()
+                  // Top level blocks (static initializers and anonymous blocks) are only used at
+                  // runtime, so we can safely skip them for ABI generation purposes. In Java 9 and
+                  // later, it's actually necessary to skip them, as getElement will attempt to
+                  // attribute the parent class node when given block nodes, effectively doing an
+                  // analyze compiler phase, which we need to avoid. In Java 8 and earlier,
+                  // getElement
+                  // just returns null in these cases.
+                  .filter(tree -> tree.getKind() != Kind.BLOCK)
+                  .map(tree -> javacTrees.getElement(new TreePath(path, tree)))
+                  .collect(Collectors.toList());
+      Set<? extends Element> fromTreeSet = new HashSet<>(fromTree);
+
+      List<Element> result = new ArrayList<>();
+      for (Element elementFromTree : fromTree) {
+        if (fromElementSet.contains(elementFromTree)) {
+          // Output any compiler-generated elements that come before this one in the compiler's
+          // element list.
+          Element elementFromElement = fromElementQueue.poll();
+          while (elementFromElement != null && !fromTreeSet.contains(elementFromElement)) {
+            result.add(elementFromElement);
+            elementFromElement = fromElementQueue.poll();
+          }
+        }
+        result.add(elementFromTree);
+      }
+
+      return result;
+    }
+
+    @Override
+    public Void visitTypeParameter(TypeParameterElement e, Void v) {
+      TreeBackedTypeParameterElement typeParameter =
+          elements.enterElement(e, this::newTreeBackedTypeParameter);
+
+      try (ElementContext c = new ElementContext(typeParameter)) {
+        return super.visitTypeParameter(e, v);
+      }
+    }
+
+    @Override
+    public Void visitExecutable(ExecutableElement e, Void v) {
+      TreeBackedExecutableElement method = elements.enterElement(e, this::newTreeBackedExecutable);
+
+      try (ElementContext c = new ElementContext(method)) {
+        super.visitExecutable(e, v);
+        scan(e.getTypeParameters(), v);
+        return null;
+      }
+    }
+
+    @Override
+    public Void visitVariable(VariableElement e, Void v) {
+      elements.enterElement(e, this::newTreeBackedVariable);
+      return super.visitVariable(e, v);
+    }
+
+    private TreeBackedPackageElement newTreeBackedPackage(PackageElement underlyingPackage) {
+      return new TreeBackedPackageElement(underlyingPackage);
+    }
+
+    private TreeBackedTypeElement newTreeBackedType(TypeElement underlyingType) {
+      TreeBackedTypeElement typeElement =
+          new TreeBackedTypeElement(
+              types, underlyingType, getCurrentContext(), getCurrentPath(), canonicalizer);
+      enterAnnotationMirrors(typeElement);
+      return typeElement;
+    }
+
+    private TreeBackedTypeParameterElement newTreeBackedTypeParameter(
+        TypeParameterElement underlyingTypeParameter) {
+      TreeBackedParameterizable enclosingElement = (TreeBackedParameterizable) getCurrentContext();
+
+      // TreeBackedExecutables with a null tree occur only for compiler-generated methods such
+      // as default construvtors. Those never have type parameters, so we should never find
+      // ourselves here without a tree.
+      TreeBackedTypeParameterElement result =
+          new TreeBackedTypeParameterElement(
+              types, underlyingTypeParameter, getCurrentPath(), enclosingElement, canonicalizer);
+      enterAnnotationMirrors(result);
+
+      enclosingElement.addTypeParameter(result);
+      return result;
+    }
+
+    private TreeBackedExecutableElement newTreeBackedExecutable(
+        ExecutableElement underlyingExecutable) {
+      TreeBackedExecutableElement result =
+          new TreeBackedExecutableElement(
+              underlyingExecutable, getCurrentContext(), currentPath, canonicalizer);
+      enterAnnotationMirrors(result);
+      return result;
+    }
+
+    private TreeBackedVariableElement newTreeBackedVariable(VariableElement underlyingVariable) {
+      TreeBackedElement enclosingElement = getCurrentContext();
+      TreeBackedVariableElement result =
+          new TreeBackedVariableElement(
+              underlyingVariable, enclosingElement, currentPath, canonicalizer);
+      enterAnnotationMirrors(result);
+      return result;
+    }
+
+    private void enterAnnotationMirrors(TreeBackedElement element) {
+      List<? extends AnnotationMirror> underlyingAnnotations =
+          element.getUnderlyingElement().getAnnotationMirrors();
+      if (underlyingAnnotations.isEmpty()) {
+        return;
+      }
+
+      for (var underlyingAnnotation : underlyingAnnotations) {
+        var annotationTreePath =
+            javacTrees.getPath(element.getUnderlyingElement(), underlyingAnnotation);
+        if (annotationTreePath == null) {
+          throw new IllegalArgumentException(
+              String.format("Annotation node of element %s could not be found.", element));
+        }
+        element.addAnnotationMirror(
+            new TreeBackedAnnotationMirror(
+                underlyingAnnotation, annotationTreePath, canonicalizer));
+      }
+    }
+
+    private class ElementContext implements AutoCloseable {
+
+      public ElementContext(TreeBackedElement newContext) {
+        contextStack.push(newContext);
+      }
+
+      @Override
+      public void close() {
+        contextStack.pop();
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedExecutableElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedExecutableElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedExecutableElement.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.MethodTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.tree.VariableTree;
+import com.sun.source.util.TreePath;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.ElementVisitor;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.TypeParameterElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+
+/**
+ * An implementation of {@link ExecutableElement} that uses only the information available from a
+ * {@link MethodTree}. This results in an incomplete implementation; see documentation for
+ * individual methods and {@link com.facebook.buck.jvm.java.abi.source} for more information.
+ */
+class TreeBackedExecutableElement extends TreeBackedParameterizable
+    implements ArtificialExecutableElement {
+  private final ExecutableElement underlyingElement;
+  private final List<TreeBackedVariableElement> parameters = new ArrayList<>();
+  @Nullable private final MethodTree tree;
+
+  @Nullable private TypeMirror returnType;
+  @Nullable private TypeMirror receiverType;
+  @Nullable private List<TypeMirror> thrownTypes;
+  @Nullable private TreeBackedAnnotationValue defaultValue;
+  @Nullable private StandaloneExecutableType typeMirror;
+
+  TreeBackedExecutableElement(
+      ExecutableElement underlyingElement,
+      TreeBackedElement enclosingElement,
+      @Nullable TreePath treePath,
+      PostEnterCanonicalizer canonicalizer) {
+    super(underlyingElement, enclosingElement, treePath, canonicalizer);
+    this.underlyingElement = underlyingElement;
+    this.tree = treePath == null ? null : (MethodTree) treePath.getLeaf();
+    enclosingElement.addEnclosedElement(this);
+  }
+
+  @Override
+  public List<? extends ArtificialElement> getEnclosedElements() {
+    return Collections.emptyList();
+  }
+
+  @Override
+  @Nullable
+  MethodTree getTree() {
+    return tree;
+  }
+
+  @Override
+  public void complete() {
+    asType();
+    getReturnType();
+    getReceiverType();
+    getThrownTypes();
+    getDefaultValue();
+  }
+
+  @Override
+  public StandaloneTypeMirror asType() {
+    if (typeMirror == null) {
+      typeMirror =
+          new StandaloneExecutableType(
+              getReturnType(),
+              getTypeParameters().stream()
+                  .map(TypeParameterElement::asType)
+                  .map(type -> (TypeVariable) type)
+                  .collect(Collectors.toList()),
+              getParameters().stream().map(VariableElement::asType).collect(Collectors.toList()),
+              getThrownTypes(),
+              getAnnotationMirrors());
+    }
+    return typeMirror;
+  }
+
+  @Override
+  public TypeMirror getReturnType() {
+    if (returnType == null) {
+      returnType =
+          getCanonicalizer()
+              .getCanonicalType(
+                  underlyingElement.getReturnType(),
+                  getTreePath(),
+                  tree == null ? null : tree.getReturnType());
+    }
+    return returnType;
+  }
+
+  @Override
+  public List<TreeBackedVariableElement> getParameters() {
+    return Collections.unmodifiableList(parameters);
+  }
+
+  /* package */ void addParameter(TreeBackedVariableElement parameter) {
+    parameters.add(parameter);
+  }
+
+  @Override
+  @Nullable
+  public TypeMirror getReceiverType() {
+    if (receiverType == null) {
+      TreePath methodTreePath = getTreePath();
+      TreePath receiverParameterPath = null;
+      Tree receiverTypeTree = null;
+      if (methodTreePath != null && tree != null) {
+        VariableTree receiverParameterTree = tree.getReceiverParameter();
+        if (receiverParameterTree != null) {
+          receiverParameterPath = new TreePath(methodTreePath, receiverParameterTree);
+          receiverTypeTree = receiverParameterTree.getType();
+        }
+      }
+      receiverType =
+          getCanonicalizer()
+              .getCanonicalType(
+                  underlyingElement.getReceiverType(), receiverParameterPath, receiverTypeTree);
+    }
+    return receiverType;
+  }
+
+  @Override
+  public boolean isVarArgs() {
+    return underlyingElement.isVarArgs();
+  }
+
+  @Override
+  public boolean isDefault() {
+    return underlyingElement.isDefault();
+  }
+
+  @Override
+  public List<? extends TypeMirror> getThrownTypes() {
+    if (thrownTypes == null) {
+      thrownTypes =
+          Collections.unmodifiableList(
+              getCanonicalizer()
+                  .getCanonicalTypes(
+                      underlyingElement.getThrownTypes(),
+                      getTreePath(),
+                      tree == null ? null : tree.getThrows()));
+    }
+
+    return thrownTypes;
+  }
+
+  @Override
+  @Nullable
+  public TreeBackedAnnotationValue getDefaultValue() {
+    if (defaultValue == null) {
+      AnnotationValue underlyingValue = underlyingElement.getDefaultValue();
+      if (underlyingValue != null) {
+        defaultValue =
+            new TreeBackedAnnotationValue(
+                underlyingValue,
+                new TreePath(
+                    Objects.requireNonNull(getTreePath()),
+                    Objects.requireNonNull(tree).getDefaultValue()),
+                getCanonicalizer());
+      }
+    }
+    return defaultValue;
+  }
+
+  @Override
+  public <R, P> R accept(ElementVisitor<R, P> v, P p) {
+    return v.visitExecutable(this, p);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedFiler.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedFiler.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedFiler.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.io.IOException;
+import javax.annotation.processing.Filer;
+import javax.lang.model.element.Element;
+import javax.tools.FileObject;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+
+class TreeBackedFiler implements Filer {
+  private final FrontendOnlyJavacTask task;
+  private final Filer javacFiler;
+
+  public TreeBackedFiler(FrontendOnlyJavacTask task, Filer javacFiler) {
+    this.task = task;
+    this.javacFiler = javacFiler;
+  }
+
+  @Override
+  public JavaFileObject createSourceFile(CharSequence name, Element... originatingElements)
+      throws IOException {
+    return javacFiler.createSourceFile(
+        name, task.getElements().getJavacElements(originatingElements));
+  }
+
+  @Override
+  public JavaFileObject createClassFile(CharSequence name, Element... originatingElements)
+      throws IOException {
+    return javacFiler.createClassFile(
+        name, task.getElements().getJavacElements(originatingElements));
+  }
+
+  @Override
+  public FileObject createResource(
+      JavaFileManager.Location location,
+      CharSequence pkg,
+      CharSequence relativeName,
+      Element... originatingElements)
+      throws IOException {
+    return javacFiler.createResource(
+        location, pkg, relativeName, task.getElements().getJavacElements(originatingElements));
+  }
+
+  @Override
+  public FileObject getResource(
+      JavaFileManager.Location location, CharSequence pkg, CharSequence relativeName)
+      throws IOException {
+    return javacFiler.getResource(location, pkg, relativeName);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedMessager.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedMessager.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedMessager.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import javax.annotation.processing.Messager;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.tools.Diagnostic;
+
+class TreeBackedMessager implements Messager {
+  private final Messager javacMessager;
+  private final FrontendOnlyJavacTask task;
+
+  public TreeBackedMessager(FrontendOnlyJavacTask task, Messager javacMessager) {
+    this.task = task;
+    this.javacMessager = javacMessager;
+  }
+
+  @Override
+  public void printMessage(Diagnostic.Kind kind, CharSequence msg) {
+    javacMessager.printMessage(kind, msg);
+  }
+
+  @Override
+  public void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e) {
+    javacMessager.printMessage(kind, msg, task.getElements().getJavacElement(e));
+  }
+
+  @Override
+  public void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a) {
+    javacMessager.printMessage(
+        kind, msg, task.getElements().getJavacElement(e), task.getElements().getJavacAnnotation(a));
+  }
+
+  @Override
+  public void printMessage(
+      Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a, AnnotationValue v) {
+    javacMessager.printMessage(
+        kind,
+        msg,
+        task.getElements().getJavacElement(e),
+        task.getElements().getJavacAnnotation(a),
+        task.getElements().getJavacAnnotationValue(v));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedPackageElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedPackageElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedPackageElement.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.util.TreePath;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementVisitor;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+
+/**
+ * An implementation of {@link TypeElement} that uses only the information available from one or
+ * more {@link com.sun.source.tree.CompilationUnitTree}s. This results in an incomplete
+ * implementation; see documentation for individual methods and {@link
+ * com.facebook.buck.jvm.java.abi.source} for more information.
+ */
+class TreeBackedPackageElement extends TreeBackedElement implements ArtificialPackageElement {
+  private final PackageElement javacPackage;
+  private final StandalonePackageType typeMirror;
+  @Nullable private TreePath treePath;
+  private boolean completed = false;
+
+  public TreeBackedPackageElement(PackageElement javacPackage) {
+    super(javacPackage, null, null, null);
+    this.javacPackage = javacPackage;
+    typeMirror = new StandalonePackageType(this);
+  }
+
+  /* package */ void setTreePath(TreePath treePath) {
+    if (this.treePath != null) {
+      throw new IllegalStateException();
+    }
+    this.treePath = treePath;
+  }
+
+  @Override
+  public List<? extends Element> getEnclosedElements() {
+    complete();
+
+    return super.getEnclosedElements();
+  }
+
+  @Override
+  public void complete() {
+    if (completed) {
+      return;
+    }
+
+    if (javacPackage != null) {
+      // Java allows packages to be split across modules, so once we've found all the tree-backed
+      // elements (i.e., elements from the current module), we fill in the ones from modules on
+      // the classpath.
+
+      List<? extends Element> treeBackedEnclosedElements = super.getEnclosedElements();
+      Set<Name> enclosedElementNames =
+          treeBackedEnclosedElements.stream()
+              .map(Element::getSimpleName)
+              .collect(Collectors.toSet());
+
+      for (Element element : javacPackage.getEnclosedElements()) {
+        if (enclosedElementNames.contains(element.getSimpleName())) {
+          // This was already added when parsing the tree-backed elements
+          continue;
+        }
+
+        addEnclosedElement(element);
+      }
+    }
+
+    completed = true;
+  }
+
+  @Override
+  public Name getQualifiedName() {
+    return javacPackage.getQualifiedName();
+  }
+
+  @Override
+  public boolean isUnnamed() {
+    return javacPackage.isUnnamed();
+  }
+
+  @Override
+  public StandalonePackageType asType() {
+    return typeMirror;
+  }
+
+  @Override
+  public <R, P> R accept(ElementVisitor<R, P> v, P p) {
+    return v.visitPackage(this, p);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedParameterizable.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedParameterizable.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedParameterizable.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.util.TreePath;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import javax.lang.model.element.Element;
+
+abstract class TreeBackedParameterizable extends TreeBackedElement
+    implements ArtificialParameterizable {
+  private final List<TreeBackedTypeParameterElement> typeParameters = new ArrayList<>();
+
+  public TreeBackedParameterizable(
+      Element underlyingElement,
+      TreeBackedElement enclosingElement,
+      @Nullable TreePath treePath,
+      PostEnterCanonicalizer canonicalizer) {
+    super(underlyingElement, enclosingElement, treePath, canonicalizer);
+  }
+
+  /* package */ void addTypeParameter(TreeBackedTypeParameterElement typeParameter) {
+    typeParameters.add(typeParameter);
+  }
+
+  @Override
+  public List<TreeBackedTypeParameterElement> getTypeParameters() {
+    return Collections.unmodifiableList(typeParameters);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedProcessingEnvironment.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedProcessingEnvironment.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedProcessingEnvironment.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.sun.source.util.Trees;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import javax.annotation.processing.Filer;
+import javax.annotation.processing.Messager;
+import javax.annotation.processing.ProcessingEnvironment;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.Types;
+
+class TreeBackedProcessingEnvironment implements ProcessingEnvironment {
+  private final FrontendOnlyJavacTask task;
+  private final ProcessingEnvironment javacProcessingEnvironment;
+  private final TreeBackedMessager messager;
+  private final TreeBackedFiler filer;
+  private final Map<String, String> options = new HashMap<>();
+
+  public TreeBackedProcessingEnvironment(
+      FrontendOnlyJavacTask task, ProcessingEnvironment javacProcessingEnvironment) {
+    this.task = task;
+    this.javacProcessingEnvironment = javacProcessingEnvironment;
+    messager = new TreeBackedMessager(task, javacProcessingEnvironment.getMessager());
+    filer = new TreeBackedFiler(task, javacProcessingEnvironment.getFiler());
+
+    options.putAll(javacProcessingEnvironment.getOptions());
+    options.put("com.facebook.buck.java.generating_abi", "true");
+  }
+
+  @Override
+  public Map<String, String> getOptions() {
+    return options;
+  }
+
+  @Override
+  public Messager getMessager() {
+    return messager;
+  }
+
+  @Override
+  public Filer getFiler() {
+    return filer;
+  }
+
+  @Override
+  public Elements getElementUtils() {
+    return task.getElements();
+  }
+
+  @Override
+  public Types getTypeUtils() {
+    return task.getTypes();
+  }
+
+  public Trees getTreeUtils() {
+    return task.getTrees();
+  }
+
+  @Override
+  public SourceVersion getSourceVersion() {
+    return javacProcessingEnvironment.getSourceVersion();
+  }
+
+  @Override
+  public Locale getLocale() {
+    return javacProcessingEnvironment.getLocale();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedProcessorWrapper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedProcessorWrapper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedProcessorWrapper.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+import java.util.stream.Collector;
+import java.util.stream.Collectors;
+import javax.annotation.processing.Completion;
+import javax.annotation.processing.ProcessingEnvironment;
+import javax.annotation.processing.Processor;
+import javax.annotation.processing.RoundEnvironment;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.TypeElement;
+
+/**
+ * Wraps an annotation processor to ensure that it always sees canonical elements -- that is, {@link
+ * TreeBackedElement}s when they are available, javac elements when they are not.
+ *
+ * <p>Annotation processors that depend on compiler internals or {@link com.sun.source.util.Trees}
+ * will not run properly (typically they will crash) when run inside this wrapper.
+ */
+class TreeBackedProcessorWrapper implements Processor {
+  private final Processor inner;
+  private final FrontendOnlyJavacTask task;
+
+  TreeBackedProcessorWrapper(FrontendOnlyJavacTask task, Processor inner) {
+    this.task = task;
+    this.inner = inner;
+  }
+
+  @Override
+  public Set<String> getSupportedOptions() {
+    return inner.getSupportedOptions();
+  }
+
+  @Override
+  public Set<String> getSupportedAnnotationTypes() {
+    return inner.getSupportedAnnotationTypes();
+  }
+
+  @Override
+  public SourceVersion getSupportedSourceVersion() {
+    return inner.getSupportedSourceVersion();
+  }
+
+  @Override
+  public synchronized void init(ProcessingEnvironment processingEnv) {
+    inner.init(new TreeBackedProcessingEnvironment(task, processingEnv));
+  }
+
+  @Override
+  public Iterable<? extends Completion> getCompletions(
+      Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
+    // This method is only ever called from IDEs, which is not a scenario for Buck right now
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
+    return inner.process(
+        annotations.stream().map(task.getElements()::getCanonicalElement).collect(toSet()),
+        new TreeBackedRoundEnvironment(task, roundEnv));
+  }
+
+  private Collector<TypeElement, ?, Set<TypeElement>> toSet() {
+    return Collectors.toCollection(LinkedHashSet::new);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedRoundEnvironment.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedRoundEnvironment.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedRoundEnvironment.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import java.lang.annotation.Annotation;
+import java.util.LinkedHashSet;
+import java.util.Set;
+import java.util.stream.Collector;
+import java.util.stream.Collectors;
+import javax.annotation.processing.RoundEnvironment;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.TypeElement;
+
+class TreeBackedRoundEnvironment implements RoundEnvironment {
+  private final FrontendOnlyJavacTask task;
+  private final RoundEnvironment javacRoundEnvironment;
+
+  public TreeBackedRoundEnvironment(
+      FrontendOnlyJavacTask task, RoundEnvironment javacRoundEnvironment) {
+    this.task = task;
+    this.javacRoundEnvironment = javacRoundEnvironment;
+  }
+
+  @Override
+  public boolean processingOver() {
+    return javacRoundEnvironment.processingOver();
+  }
+
+  @Override
+  public boolean errorRaised() {
+    return javacRoundEnvironment.errorRaised();
+  }
+
+  @Override
+  public Set<? extends Element> getRootElements() {
+    return javacRoundEnvironment.getRootElements().stream()
+        .map(task.getElements()::getCanonicalElement)
+        .collect(toSet());
+  }
+
+  @Override
+  public Set<? extends Element> getElementsAnnotatedWith(TypeElement a) {
+    return javacRoundEnvironment
+        .getElementsAnnotatedWith(task.getElements().getJavacElement(a))
+        .stream()
+        .map(task.getElements()::getCanonicalElement)
+        .collect(toSet());
+  }
+
+  @Override
+  public Set<? extends Element> getElementsAnnotatedWith(Class<? extends Annotation> a) {
+    return javacRoundEnvironment.getElementsAnnotatedWith(a).stream()
+        .map(task.getElements()::getCanonicalElement)
+        .collect(toSet());
+  }
+
+  private Collector<Element, ?, Set<Element>> toSet() {
+    return Collectors.toCollection(LinkedHashSet::new);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTrees.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTrees.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTrees.java
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.AnnotatedTypeTree;
+import com.sun.source.tree.CatchTree;
+import com.sun.source.tree.ClassTree;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.IdentifierTree;
+import com.sun.source.tree.MemberSelectTree;
+import com.sun.source.tree.MethodTree;
+import com.sun.source.tree.ParameterizedTypeTree;
+import com.sun.source.tree.Scope;
+import com.sun.source.tree.Tree;
+import com.sun.source.util.SimpleTreeVisitor;
+import com.sun.source.util.SourcePositions;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.Trees;
+import java.util.HashMap;
+import java.util.Map;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.ErrorType;
+import javax.lang.model.type.TypeMirror;
+import javax.tools.Diagnostic;
+import javax.tools.JavaCompiler;
+
+/**
+ * An implementation of {@link Trees} that uses our tree-backed elements and types when available.
+ */
+class TreeBackedTrees extends Trees {
+  private final Trees javacTrees;
+  private final PostEnterCanonicalizer canonicalizer;
+  private final Map<Tree, TypeMirror> canonicalTypes = new HashMap<>();
+
+  public static TreeBackedTrees instance(JavaCompiler.CompilationTask task) {
+    return ((FrontendOnlyJavacTask) task).getTrees();
+  }
+
+  /* package */ TreeBackedTrees(Trees javacTrees, PostEnterCanonicalizer canonicalizer) {
+    this.javacTrees = javacTrees;
+    this.canonicalizer = canonicalizer;
+  }
+
+  /* package */ Trees getJavacTrees() {
+    return javacTrees;
+  }
+
+  /* package */ void clear() {
+    canonicalTypes.clear();
+  }
+
+  @Override
+  public SourcePositions getSourcePositions() {
+    return javacTrees.getSourcePositions();
+  }
+
+  @Override
+  @Nullable
+  public Tree getTree(Element element) {
+    if (element.getKind() == ElementKind.TYPE_PARAMETER) {
+      // This is a weird javac behavior that we're emulating.
+      return null;
+    }
+
+    TreePath path = getPath(element);
+    if (path == null) {
+      return null;
+    }
+    return path.getLeaf();
+  }
+
+  @Override
+  @Nullable
+  public ClassTree getTree(TypeElement element) {
+    return (ClassTree) getTree((Element) element);
+  }
+
+  @Override
+  @Nullable
+  public MethodTree getTree(ExecutableElement method) {
+    return (MethodTree) getTree((Element) method);
+  }
+
+  @Override
+  public Tree getTree(Element e, AnnotationMirror a) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public Tree getTree(Element e, AnnotationMirror a, AnnotationValue v) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public TreePath getPath(CompilationUnitTree unit, Tree node) {
+    return javacTrees.getPath(unit, node);
+  }
+
+  @Override
+  @Nullable
+  public TreePath getPath(Element e) {
+    if (e instanceof TreeBackedElement) {
+      return javacTrees.getPath(((TreeBackedElement) e).getUnderlyingElement());
+    }
+    if (e instanceof InferredElement) {
+      // Inferred elements come from dependencies, and you never have trees for those.
+      return null;
+    }
+
+    TreePath result = javacTrees.getPath(e);
+    if (result != null) {
+      // If we've properly hidden all the javac implementations of things, the only way a caller
+      // should be able to get a non-`TreeBackedElement` is by looking at classes on the classpath.
+      // Those come from .class files, and thus by definition do not have ASTs.
+
+      throw new AssertionError(String.format("Leaked a javac element for: %s", e));
+    }
+
+    return null;
+  }
+
+  @Override
+  public TreePath getPath(Element e, AnnotationMirror a) {
+    if (a instanceof TreeBackedAnnotationMirror) {
+      return ((TreeBackedAnnotationMirror) a).getTreePath();
+    }
+
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public TreePath getPath(Element e, AnnotationMirror a, AnnotationValue v) {
+    if (e instanceof TreeBackedElement) {
+      return javacTrees.getPath(e, a, v);
+    }
+
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  @Nullable
+  public Element getElement(TreePath path) {
+    return canonicalizer.getCanonicalElement(javacTrees.getElement(path));
+  }
+
+  @Override
+  @Nullable
+  public TypeMirror getTypeMirror(TreePath path) {
+    Tree leaf = path.getLeaf();
+    TypeMirror result = canonicalTypes.get(leaf);
+    if (result == null) {
+      result = canonicalizer.getCanonicalType(javacTrees.getTypeMirror(path), path);
+      canonicalTypes.put(leaf, result);
+    }
+
+    return result;
+  }
+
+  @Override
+  public Scope getScope(TreePath path) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  @Nullable
+  public String getDocComment(TreePath path) {
+    return javacTrees.getDocComment(path);
+  }
+
+  @Override
+  public boolean isAccessible(Scope scope, TypeElement type) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public boolean isAccessible(Scope scope, Element member, DeclaredType type) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public TypeMirror getOriginalType(ErrorType errorType) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public void printMessage(
+      Diagnostic.Kind kind, CharSequence msg, Tree t, CompilationUnitTree root) {
+    javacTrees.printMessage(kind, msg, t, root);
+  }
+
+  @Override
+  public TypeMirror getLub(CatchTree tree) {
+    throw new UnsupportedOperationException();
+  }
+
+  /**
+   * Takes a type reference expression and returns the base name of the type it represents (without
+   * any type arguments or annotations).
+   */
+  /* package */
+  static CharSequence treeToName(Tree tree) {
+    if (tree == null) {
+      return "";
+    }
+
+    return tree.accept(
+        new SimpleTreeVisitor<CharSequence, Void>() {
+          @Override
+          protected CharSequence defaultAction(Tree node, Void aVoid) {
+            throw new AssertionError(String.format("Unexpected tree of kind: %s", node.getKind()));
+          }
+
+          @Override
+          public CharSequence visitAnnotatedType(AnnotatedTypeTree node, Void aVoid) {
+            return node.getUnderlyingType().accept(this, aVoid);
+          }
+
+          @Override
+          public CharSequence visitParameterizedType(ParameterizedTypeTree node, Void aVoid) {
+            return node.getType().accept(this, aVoid);
+          }
+
+          @Override
+          public CharSequence visitMemberSelect(MemberSelectTree node, Void aVoid) {
+            return String.format(
+                "%s.%s", node.getExpression().accept(this, aVoid), node.getIdentifier());
+          }
+
+          @Override
+          public CharSequence visitIdentifier(IdentifierTree node, Void aVoid) {
+            return node.getName();
+          }
+        },
+        null);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeElement.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.ClassTree;
+import com.sun.source.util.TreePath;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementVisitor;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.NestingKind;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.TypeParameterElement;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * An implementation of {@link TypeElement} that uses only the information available from a {@link
+ * ClassTree}. This results in an incomplete implementation; see documentation for individual
+ * methods and {@link com.facebook.buck.jvm.java.abi.source} for more information.
+ */
+class TreeBackedTypeElement extends TreeBackedParameterizable implements ArtificialTypeElement {
+  private final TreeBackedTypes types;
+  private final TypeElement underlyingElement;
+  private final ClassTree tree;
+  @Nullable private StandaloneDeclaredType typeMirror;
+  @Nullable private TypeMirror superclass;
+  @Nullable private List<? extends TypeMirror> interfaces;
+
+  TreeBackedTypeElement(
+      TreeBackedTypes types,
+      TypeElement underlyingElement,
+      TreeBackedElement enclosingElement,
+      TreePath treePath,
+      PostEnterCanonicalizer canonicalizer) {
+    super(underlyingElement, enclosingElement, treePath, canonicalizer);
+    this.types = types;
+    this.underlyingElement = underlyingElement;
+    this.tree = (ClassTree) treePath.getLeaf();
+    enclosingElement.addEnclosedElement(this);
+  }
+
+  @Override
+  public void complete() {
+    asType();
+    getSuperclass();
+    getInterfaces();
+  }
+
+  @Override
+  TreePath getTreePath() {
+    return Objects.requireNonNull(super.getTreePath());
+  }
+
+  @Override
+  ClassTree getTree() {
+    return tree;
+  }
+
+  @Override
+  public TreeBackedElement getEnclosingElement() {
+    return Objects.requireNonNull(super.getEnclosingElement());
+  }
+
+  @Override
+  public void addEnclosedElement(Element element) {
+    if (!(element instanceof TreeBackedElement)) {
+      throw new IllegalArgumentException(
+          String.format(
+              "A type named %s does not exist. Make sure it is a canonical reference.", element));
+    }
+    super.addEnclosedElement(element);
+  }
+
+  @Override
+  public List<TreeBackedElement> getEnclosedElements() {
+    @SuppressWarnings("unchecked")
+    List<TreeBackedElement> enclosedElements =
+        (List<TreeBackedElement>) super.getEnclosedElements();
+    return enclosedElements;
+  }
+
+  @Override
+  public NestingKind getNestingKind() {
+    return underlyingElement.getNestingKind();
+  }
+
+  @Override
+  public Name getQualifiedName() {
+    return underlyingElement.getQualifiedName();
+  }
+
+  @Override
+  public StandaloneDeclaredType asType() {
+    if (typeMirror == null) {
+      typeMirror =
+          (StandaloneDeclaredType)
+              types.getDeclaredType(
+                  this,
+                  getTypeParameters().stream()
+                      .map(TypeParameterElement::asType)
+                      .toArray(TypeMirror[]::new));
+    }
+    return typeMirror;
+  }
+
+  @Override
+  public TypeMirror getSuperclass() {
+    if (superclass == null) {
+      superclass =
+          getCanonicalizer()
+              .getCanonicalType(
+                  underlyingElement.getSuperclass(), getTreePath(), tree.getExtendsClause());
+    }
+
+    return superclass;
+  }
+
+  @Override
+  public List<? extends TypeMirror> getInterfaces() {
+    if (interfaces == null) {
+      interfaces =
+          Collections.unmodifiableList(
+              getCanonicalizer()
+                  .getCanonicalTypes(
+                      underlyingElement.getInterfaces(),
+                      getTreePath(),
+                      tree.getImplementsClause()));
+    }
+    return interfaces;
+  }
+
+  @Override
+  public <R, P> R accept(ElementVisitor<R, P> v, P p) {
+    return v.visitType(this, p);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeParameterElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeParameterElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeParameterElement.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.TypeParameterTree;
+import com.sun.source.util.TreePath;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementVisitor;
+import javax.lang.model.element.TypeParameterElement;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * An implementation of {@link TypeParameterElement} that uses only the information available from a
+ * {@link TypeParameterTree}. This results in an incomplete implementation; see documentation for
+ * individual methods and {@link com.facebook.buck.jvm.java.abi.source} for more information.
+ */
+class TreeBackedTypeParameterElement extends TreeBackedElement
+    implements ArtificialTypeParameterElement {
+  private final TypeParameterElement underlyingElement;
+  private final TypeParameterTree tree;
+  private final StandaloneTypeVariable typeVar;
+  @Nullable private List<TypeMirror> bounds;
+
+  public TreeBackedTypeParameterElement(
+      TreeBackedTypes types,
+      TypeParameterElement underlyingElement,
+      TreePath treePath,
+      TreeBackedElement enclosingElement,
+      PostEnterCanonicalizer canonicalizer) {
+    super(underlyingElement, enclosingElement, treePath, canonicalizer);
+    this.underlyingElement = underlyingElement;
+    this.tree = (TypeParameterTree) treePath.getLeaf();
+    typeVar = new StandaloneTypeVariable(types, this);
+
+    // In javac's implementation, enclosingElement does not have type parameters in the return
+    // value of getEnclosedElements
+  }
+
+  @Override
+  public void complete() {
+    getBounds();
+  }
+
+  @Override
+  public List<? extends ArtificialElement> getEnclosedElements() {
+    return Collections.emptyList();
+  }
+
+  @Override
+  public StandaloneTypeVariable asType() {
+    return typeVar;
+  }
+
+  @Override
+  public Element getGenericElement() {
+    // Our constructor does not allow null enclosing elements for this element type
+    return Objects.requireNonNull(getEnclosingElement());
+  }
+
+  @Override
+  public List<? extends TypeMirror> getBounds() {
+    if (bounds == null) {
+      bounds =
+          Collections.unmodifiableList(
+              getCanonicalizer()
+                  .getCanonicalTypes(
+                      underlyingElement.getBounds(),
+                      getTreePath(),
+                      tree == null ? null : tree.getBounds()));
+    }
+
+    return bounds;
+  }
+
+  @Override
+  public <R, P> R accept(ElementVisitor<R, P> v, P p) {
+    return v.visitTypeParameter(this, p);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeResolutionSimulator.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeResolutionSimulator.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypeResolutionSimulator.java
@@ -0,0 +1,375 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.lang.model.MoreElements;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.Scope;
+import com.sun.source.tree.Tree.Kind;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.Trees;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.NestingKind;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.QualifiedNameable;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.SimpleElementVisitor8;
+import javax.tools.Diagnostic;
+
+/** Simulates the type resolution performed by {@link TreeBackedEnter} for source-only ABIs. */
+class TreeBackedTypeResolutionSimulator {
+
+  private final Elements elements;
+  private final Trees trees;
+  private final PackageElement enclosingPackage;
+  @Nullable private ImportsTracker imports = null;
+
+  public TreeBackedTypeResolutionSimulator(
+      Elements elements, Trees trees, CompilationUnitTree compilationUnit) {
+    this.elements = elements;
+    this.trees = trees;
+    enclosingPackage =
+        (PackageElement) Objects.requireNonNull(trees.getElement(new TreePath(compilationUnit)));
+  }
+
+  public void setImports(ImportsTracker imports) {
+    this.imports = imports;
+  }
+
+  private boolean isTopLevelInReferencingPackage(TypeElement type) {
+    return type.getEnclosingElement() == enclosingPackage;
+  }
+
+  public TreeBackedResolvedType resolve(TreePath referencingPath) {
+    return new ResolvedElementQualifiedNameableTreePathScannerForTypeResolution()
+        .scan(referencingPath, null);
+  }
+
+  private interface Remediation {
+    boolean canBeApplied();
+
+    @Nullable
+    String getMessage();
+  }
+
+  public class TreeBackedResolvedType {
+    public final TreePath location;
+    public final QualifiedNameable referencedElement;
+    public final QualifiedNameable canonicalElement;
+    @Nullable public final TreeBackedResolvedType enclosingElement;
+    private final Scope scope;
+    @Nullable private final String message;
+    private final List<Remediation> remediations;
+
+    public TreeBackedResolvedType(
+        TreePath referencingPath,
+        QualifiedNameable canonicalElement,
+        @Nullable TreeBackedResolvedType enclosingElement) {
+      this.location = referencingPath;
+      this.canonicalElement = canonicalElement;
+      this.referencedElement =
+          (QualifiedNameable) Objects.requireNonNull(trees.getElement(referencingPath));
+      this.enclosingElement = enclosingElement;
+      scope = Objects.requireNonNull(trees.getScope(location));
+      try {
+        remediations = new ArrayList<>();
+        if (!isCanonicalReference()) {
+          message =
+              "Source-only ABI generation requires that this type be referred to by its canonical"
+                  + " name.";
+          if (enclosingElement == null) {
+            remediations.add(new ImportTypeRemediation((TypeElement) canonicalElement));
+          }
+          remediations.add(new CanonicalizeReferenceRemediation());
+        } else if (!isResolvable()) {
+          TypeElement referencedType = (TypeElement) referencedElement;
+          if (imports != null && imports.isOnDemandImported(referencedElement)
+              || (imports != null
+                  && imports.isOnDemandStaticImported(referencedType)
+                  && imports.getOnDemandStaticImportContainer(referencedType)
+                      == referencedType.getEnclosingElement())) {
+            message =
+                "Source-only ABI generation requires that this type be explicitly imported (star"
+                    + " imports are not accepted).";
+            remediations.add(new ImportTypeRemediation((TypeElement) referencedElement));
+          } else if (imports != null
+              && (imports.isOnDemandStaticImported(referencedType)
+                  || imports.isStaticImported(referencedType))) {
+            message = null;
+            remediations.add(new CannotFixRemediation());
+          } else {
+            message =
+                "Source-only ABI generation requires that this member type reference be more"
+                    + " explicit.";
+            remediations.add(
+                new ImportTypeRemediation((TypeElement) referencedElement.getEnclosingElement()));
+            remediations.add(new QualifyNameRemediation(referencedType));
+          }
+        } else if (!nameIsCorrectCase()) {
+          message =
+              referencedElement.accept(
+                  new SimpleElementVisitor8<String, Void>() {
+                    @Override
+                    public String visitPackage(PackageElement e, Void aVoid) {
+                      remediations.add(
+                          new RenameRemediation(
+                              e.getSimpleName(), fixNameCase(e, Character::toLowerCase)));
+                      return "Source-only ABI generation requires package names to start with a"
+                          + " lowercase letter.";
+                    }
+
+                    @Override
+                    public String visitType(TypeElement e, Void aVoid) {
+                      remediations.add(
+                          new RenameRemediation(
+                              e.getSimpleName(), fixNameCase(e, Character::toUpperCase)));
+                      return "Source-only ABI generation requires top-level class names to start"
+                          + " with a capital letter.";
+                    }
+
+                    @Override
+                    protected String defaultAction(Element e, Void aVoid) {
+                      throw new IllegalArgumentException(
+                          String.format("Unexpected element of kind %s: %s", e.getKind(), e));
+                    }
+                  },
+                  null);
+        } else {
+          message = null;
+        }
+      } catch (RuntimeException e) {
+        throw new RuntimeException(
+            String.format("When resolving %s at %s.", referencedElement, location), e);
+      }
+    }
+
+    public boolean isCorrect() {
+      boolean enclosingIsCorrect = enclosingElement == null || enclosingElement.isCorrect();
+
+      return enclosingIsCorrect && isCanonicalReference() && isResolvable() && nameIsCorrectCase();
+    }
+
+    public boolean isCorrectable() {
+      boolean enclosingIsCorrectable = enclosingElement == null || enclosingElement.isCorrectable();
+
+      return enclosingIsCorrectable
+          && remediations.stream().map(Remediation::canBeApplied).reduce(true, Boolean::logicalAnd);
+    }
+
+    public void reportErrors(Diagnostic.Kind messageKind) {
+      String errorMessage = getErrorMessage();
+      if (errorMessage != null) {
+        trees.printMessage(
+            messageKind, errorMessage, location.getLeaf(), location.getCompilationUnit());
+      }
+
+      if (enclosingElement != null) {
+        enclosingElement.reportErrors(messageKind);
+      }
+    }
+
+    @Nullable
+    public String getErrorMessage() {
+      if (message == null) {
+        return null;
+      }
+      return String.format(
+          "%s\nTo fix: \n%s\n",
+          message,
+          remediations.stream().map(Remediation::getMessage).collect(Collectors.joining("\n")));
+    }
+
+    private boolean isCanonicalReference() {
+      return referencedElement == canonicalElement;
+    }
+
+    private boolean isResolvable() {
+      if (location.getLeaf().getKind() == Kind.MEMBER_SELECT) {
+        return true;
+      } else if (referencedElement.getKind() == ElementKind.PACKAGE) {
+        return true;
+      }
+
+      TypeElement referencedType = (TypeElement) referencedElement;
+      return (imports != null && imports.isSingleTypeImported(referencedType))
+          || isTopLevelInReferencingPackage(referencedType);
+    }
+
+    private boolean nameIsCorrectCase() {
+      return referencedElement.accept(
+          new SimpleElementVisitor8<Boolean, Void>() {
+            @Override
+            public Boolean visitType(TypeElement e, Void aVoid) {
+              return e.getNestingKind() != NestingKind.TOP_LEVEL
+                  || Character.isUpperCase(e.getSimpleName().toString().charAt(0));
+            }
+
+            @Override
+            public Boolean visitPackage(PackageElement e, Void aVoid) {
+              return Character.isLowerCase(e.getSimpleName().toString().charAt(0));
+            }
+
+            @Override
+            protected Boolean defaultAction(Element e, Void aVoid) {
+              throw new IllegalArgumentException(
+                  String.format("Unexpected element of kind %s: %s", e.getKind(), e));
+            }
+          },
+          null);
+    }
+
+    private String fixNameCase(Element element, Function<Character, Character> fix) {
+      String simpleName = element.getSimpleName().toString();
+      char firstLetter = simpleName.charAt(0);
+      return String.format("%c%s", fix.apply(firstLetter), simpleName.substring(1));
+    }
+
+    private class QualifyNameRemediation implements Remediation {
+      private final TypeElement toQualify;
+
+      private QualifyNameRemediation(TypeElement toQualify) {
+        this.toQualify = toQualify;
+      }
+
+      @Override
+      public boolean canBeApplied() {
+        return true;
+      }
+
+      @Override
+      public String getMessage() {
+        TypeElement enclosingType = (TypeElement) toQualify.getEnclosingElement();
+        return String.format(
+            "Use \"%s.%s\" here instead of \"%s\".",
+            enclosingType.getSimpleName(), toQualify.getSimpleName(), toQualify.getSimpleName());
+      }
+    }
+
+    private class ImportTypeRemediation implements Remediation {
+      private final TypeElement toImport;
+
+      private ImportTypeRemediation(TypeElement toImport) {
+        this.toImport = toImport;
+      }
+
+      @Override
+      public boolean canBeApplied() {
+        return trees.isAccessible(scope, toImport)
+            && !Objects.requireNonNull(imports).nameIsStaticImported(toImport.getSimpleName());
+      }
+
+      @Override
+      public String getMessage() {
+        return String.format("Add an import for \"%s\"", toImport.getQualifiedName());
+      }
+    }
+
+    private class CanonicalizeReferenceRemediation implements Remediation {
+      @Override
+      public boolean canBeApplied() {
+        return trees.isAccessible(scope, (TypeElement) canonicalElement);
+      }
+
+      @Override
+      @Nullable
+      public String getMessage() {
+        if (canonicalElement == referencedElement) {
+          return null;
+        }
+        return String.format(
+            "Use \"%s\" here instead of \"%s\".",
+            canonicalElement.getSimpleName(), referencedElement.getSimpleName());
+      }
+    }
+
+    private class CannotFixRemediation implements Remediation {
+      @Override
+      public boolean canBeApplied() {
+        return false;
+      }
+
+      @Override
+      @Nullable
+      public String getMessage() {
+        return null;
+      }
+    }
+  }
+
+  private static class RenameRemediation implements Remediation {
+    private final CharSequence from;
+    private final CharSequence to;
+
+    public RenameRemediation(CharSequence from, CharSequence to) {
+      this.from = from;
+      this.to = to;
+    }
+
+    @Override
+    public boolean canBeApplied() {
+      return true;
+    }
+
+    @Override
+    public String getMessage() {
+      return String.format("Rename \"%s\" to \"%s\".", from, to);
+    }
+  }
+
+  private class ResolvedElementQualifiedNameableTreePathScannerForTypeResolution
+      extends TreePathScannerForTypeResolution<TreeBackedResolvedType, QualifiedNameable> {
+
+    public ResolvedElementQualifiedNameableTreePathScannerForTypeResolution() {
+      super(TreeBackedTypeResolutionSimulator.this.trees);
+    }
+
+    @Override
+    protected TreeBackedResolvedType resolveType(
+        TreePath referencingPath, TypeElement referencedType, QualifiedNameable canonicalType) {
+      if (canonicalType == null) {
+        canonicalType = referencedType;
+      }
+      return new TreeBackedResolvedType(
+          referencingPath,
+          canonicalType,
+          resolveEnclosingElement((QualifiedNameable) canonicalType.getEnclosingElement()));
+    }
+
+    @Override
+    protected TreeBackedResolvedType resolvePackage(
+        TreePath referencingPath,
+        PackageElement referencedPackage,
+        QualifiedNameable canonicalPackage) {
+      // PackageElements are not considered to be enclosed by their parent elements, but
+      // our logic is a lot simpler if we can pretend they are.
+      TreeBackedResolvedType enclosingElement = null;
+      String qualifiedName = canonicalPackage.getQualifiedName().toString();
+      int lastDot = qualifiedName.lastIndexOf('.');
+      if (lastDot > 0) {
+        String enclosingPackageQualifiedName = qualifiedName.substring(0, lastDot);
+        PackageElement enclosingPackage =
+            Objects.requireNonNull(
+                MoreElements.getPackageElementEvenIfEmpty(elements, enclosingPackageQualifiedName));
+        enclosingElement = resolveEnclosingElement(enclosingPackage);
+      }
+
+      return new TreeBackedResolvedType(referencingPath, canonicalPackage, enclosingElement);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypes.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypes.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedTypes.java
@@ -0,0 +1,316 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.util.Arrays;
+import java.util.List;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.ArrayType;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.ExecutableType;
+import javax.lang.model.type.IntersectionType;
+import javax.lang.model.type.NoType;
+import javax.lang.model.type.NullType;
+import javax.lang.model.type.PrimitiveType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+import javax.lang.model.type.WildcardType;
+import javax.lang.model.util.Types;
+
+/**
+ * An implementation of {@link Types} using just the AST of a single module, without its
+ * dependencies. Of necessity, such an implementation will need to make assumptions about the
+ * meanings of some names, and thus must be used with care. See documentation for individual methods
+ * and {@link com.facebook.buck.jvm.java.abi.source} for more information.
+ */
+class TreeBackedTypes implements Types {
+
+  private final Types javacTypes;
+
+  TreeBackedTypes(Types javacTypes) {
+    this.javacTypes = javacTypes;
+  }
+
+  @Override
+  @Nullable
+  public Element asElement(TypeMirror t) {
+    if (t.getKind() == TypeKind.DECLARED) {
+      return ((DeclaredType) t).asElement();
+    } else if (t.getKind() == TypeKind.TYPEVAR) {
+      throw new UnsupportedOperationException("Type variables not yet implemented");
+    }
+
+    return null;
+  }
+
+  @Override
+  public boolean isSameType(TypeMirror t1, TypeMirror t2) {
+    boolean t1Artificial = isArtificialType(t1);
+    boolean t2Artificial = isArtificialType(t2);
+
+    if (!t1Artificial && !t2Artificial) {
+      return javacTypes.isSameType(t1, t2);
+    }
+
+    // IMPORTANT: We can't early-out on reference equality, because wildcard types are never
+    // considered the same type as one another.
+
+    if (t1Artificial != t2Artificial || t1.getKind() != t2.getKind()) {
+      return false;
+    }
+
+    assert t1Artificial && t2Artificial;
+
+    switch (t1.getKind()) {
+      case BOOLEAN:
+      case BYTE:
+      case CHAR:
+      case SHORT:
+      case INT:
+      case LONG:
+      case FLOAT:
+      case DOUBLE:
+      case NULL:
+        return true;
+      case WILDCARD:
+        return false; // Wildcard types are never the same as one another; see docs
+      case DECLARED:
+        return isSameDeclaredType((DeclaredType) t1, (DeclaredType) t2);
+      case TYPEVAR:
+        return isSameTypeVariable((TypeVariable) t1, (TypeVariable) t2);
+      case INTERSECTION:
+        return isSameIntersectionType((IntersectionType) t1, (IntersectionType) t2);
+      case ARRAY:
+        return isSameType(((ArrayType) t1).getComponentType(), ((ArrayType) t2).getComponentType());
+      // $CASES-OMITTED$
+      default:
+        throw new UnsupportedOperationException(
+            String.format("isSameType NYI for kind %s", t1.getKind()));
+    }
+  }
+
+  private boolean isSameDeclaredType(DeclaredType t1, DeclaredType t2) {
+    if (!t1.asElement().equals(t2.asElement())) {
+      return false;
+    }
+
+    List<? extends TypeMirror> args1 = t1.getTypeArguments();
+    List<? extends TypeMirror> args2 = t2.getTypeArguments();
+    if (args1.size() != args2.size()) {
+      // TODO(jkeljo): This is impossible in code that will compile, but we will eventually need
+      // to gracefully error out on code with some kinds of errors (such as providing the
+      // wrong number of type arguments). Whenever we do that work, the body of this statement
+      // should throw.
+      return false;
+    }
+
+    for (int i = 0; i < args1.size(); i++) {
+      if (!isSameType(args1.get(i), args2.get(i))) {
+        return false;
+      }
+    }
+
+    return true;
+  }
+
+  private boolean isSameTypeVariable(TypeVariable t1, TypeVariable t2) {
+    return t1.asElement().equals(t2.asElement());
+
+    // TODO(jkeljo): Upper and lower bounds could also matter if the type variable is the result of
+    // capture conversion, but we don't support capture conversion yet (or maybe ever).
+  }
+
+  private boolean isSameIntersectionType(IntersectionType t1, IntersectionType t2) {
+    List<? extends TypeMirror> t1Bounds = t1.getBounds();
+    List<? extends TypeMirror> t2Bounds = t2.getBounds();
+    if (t1Bounds.size() != t2Bounds.size()) {
+      return false;
+    }
+
+    for (TypeMirror t1Bound : t1Bounds) {
+      if (!listContainsType(t2Bounds, t1Bound)) {
+        return false;
+      }
+    }
+
+    return true;
+  }
+
+  private boolean listContainsType(List<? extends TypeMirror> list, TypeMirror type) {
+    boolean found = false;
+    for (TypeMirror t2Bound : list) {
+      if (isSameType(type, t2Bound)) {
+        found = true;
+        break;
+      }
+    }
+    return found;
+  }
+
+  @Override
+  public boolean isSubtype(TypeMirror t1, TypeMirror t2) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public boolean isAssignable(TypeMirror t1, TypeMirror t2) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public boolean contains(TypeMirror t1, TypeMirror t2) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public boolean isSubsignature(ExecutableType m1, ExecutableType m2) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public List<? extends TypeMirror> directSupertypes(TypeMirror t) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public TypeMirror erasure(TypeMirror t) {
+    if (isArtificialType(t)) {
+      return erasure((StandaloneTypeMirror) t);
+    }
+
+    return javacTypes.erasure(t);
+  }
+
+  private TypeMirror erasure(StandaloneTypeMirror t) {
+    switch (t.getKind()) {
+      case ARRAY:
+        {
+          ArrayType arrayType = (ArrayType) t;
+          return getArrayType(erasure(arrayType.getComponentType()));
+        }
+      case DECLARED:
+        {
+          DeclaredType declaredType = (DeclaredType) t;
+          TypeElement typeElement = (TypeElement) declaredType.asElement();
+          if (declaredType.getEnclosingType().getKind() == TypeKind.DECLARED) {
+            DeclaredType enclosingType = (DeclaredType) declaredType.getEnclosingType();
+
+            return getDeclaredType((DeclaredType) erasure(enclosingType), typeElement);
+          }
+
+          return getDeclaredType(typeElement);
+        }
+      // $CASES-OMITTED$
+      default:
+        throw new UnsupportedOperationException();
+    }
+  }
+
+  @Override
+  public TypeElement boxedClass(PrimitiveType p) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public PrimitiveType unboxedType(TypeMirror t) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public TypeMirror capture(TypeMirror t) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public PrimitiveType getPrimitiveType(TypeKind kind) {
+    return javacTypes.getPrimitiveType(kind);
+  }
+
+  @Override
+  public NullType getNullType() {
+    return javacTypes.getNullType();
+  }
+
+  @Override
+  public NoType getNoType(TypeKind kind) {
+    return javacTypes.getNoType(kind);
+  }
+
+  /* package */ StandalonePackageType getPackageType(ArtificialPackageElement element) {
+    return new StandalonePackageType(element);
+  }
+
+  @Override
+  public ArrayType getArrayType(TypeMirror componentType) {
+    if (isArtificialType(componentType)) {
+      return new StandaloneArrayType(componentType);
+    }
+
+    return javacTypes.getArrayType(componentType);
+  }
+
+  @Override
+  public WildcardType getWildcardType(
+      @Nullable TypeMirror extendsBound, @Nullable TypeMirror superBound) {
+    if (containsArtificialTypes(extendsBound, superBound)) {
+      return new StandaloneWildcardType(extendsBound, superBound);
+    }
+
+    return javacTypes.getWildcardType(extendsBound, superBound);
+  }
+
+  @Override
+  public DeclaredType getDeclaredType(TypeElement typeElem, TypeMirror... typeArgs) {
+    return getDeclaredType(null, typeElem, typeArgs);
+  }
+
+  @Override
+  public DeclaredType getDeclaredType(
+      @Nullable DeclaredType containing, TypeElement typeElem, TypeMirror... typeArgs) {
+    if (isArtificialType(containing)
+        || isArtificialElement(typeElem)
+        || containsArtificialTypes(typeArgs)) {
+      if (containing != null) {
+        return new StandaloneDeclaredType(typeElem, Arrays.asList(typeArgs), containing);
+      } else {
+        return new StandaloneDeclaredType(this, typeElem, Arrays.asList(typeArgs));
+      }
+    }
+
+    return javacTypes.getDeclaredType(containing, typeElem, typeArgs);
+  }
+
+  private boolean isArtificialElement(Element element) {
+    return element instanceof ArtificialElement;
+  }
+
+  public boolean isArtificialType(@Nullable TypeMirror typeMirror) {
+    return typeMirror instanceof StandaloneTypeMirror;
+  }
+
+  private boolean containsArtificialTypes(TypeMirror... typeMirrors) {
+    for (TypeMirror typeMirror : typeMirrors) {
+      if (isArtificialType(typeMirror)) {
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  @Override
+  public TypeMirror asMemberOf(DeclaredType containing, Element element) {
+    throw new UnsupportedOperationException();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedVariableElement.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedVariableElement.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeBackedVariableElement.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.VariableTree;
+import com.sun.source.util.TreePath;
+import java.util.Collections;
+import java.util.List;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ElementVisitor;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.TypeMirror;
+
+class TreeBackedVariableElement extends TreeBackedElement implements ArtificialVariableElement {
+  private final VariableElement underlyingElement;
+
+  @Nullable private final VariableTree tree;
+
+  @Nullable private TypeMirror type;
+
+  TreeBackedVariableElement(
+      VariableElement underlyingElement,
+      TreeBackedElement enclosingElement,
+      @Nullable TreePath treePath,
+      PostEnterCanonicalizer canonicalizer) {
+    super(underlyingElement, enclosingElement, treePath, canonicalizer);
+    this.underlyingElement = underlyingElement;
+    this.tree = treePath == null ? null : (VariableTree) treePath.getLeaf();
+    if (underlyingElement.getKind() == ElementKind.PARAMETER) {
+      ((TreeBackedExecutableElement) enclosingElement).addParameter(this);
+    } else {
+      enclosingElement.addEnclosedElement(this);
+    }
+  }
+
+  @Override
+  public void complete() {
+    asType();
+  }
+
+  @Override
+  public List<? extends ArtificialElement> getEnclosedElements() {
+    return Collections.emptyList();
+  }
+
+  @Override
+  @Nullable
+  VariableTree getTree() {
+    return tree;
+  }
+
+  @Override
+  public TypeMirror asType() {
+    if (type == null) {
+      type =
+          getCanonicalizer()
+              .getCanonicalType(
+                  underlyingElement.asType(), getTreePath(), tree == null ? null : tree.getType());
+    }
+    return type;
+  }
+
+  @Override
+  @Nullable
+  public Object getConstantValue() {
+    return underlyingElement.getConstantValue();
+  }
+
+  @Override
+  public <R, P> R accept(ElementVisitor<R, P> v, P p) {
+    return v.visitVariable(this, p);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeContextScanner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeContextScanner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreeContextScanner.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.Tree;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.TreeScanner;
+import com.sun.source.util.Trees;
+import java.util.Objects;
+import javax.lang.model.element.Element;
+import javax.lang.model.type.TypeMirror;
+
+/**
+ * A {@link TreeScanner} that keeps track of the following as it is scanning:
+ *
+ * <ul>
+ *   <li>The {@link TreePath} from the {@link com.sun.source.tree.CompilationUnitTree}
+ *   <li>The nearest {@link Element} that encloses the current {@link Tree}
+ * </ul>
+ */
+class TreeContextScanner<R, P> extends TreeScanner<R, P> {
+
+  private final Trees trees;
+
+  @Nullable private TreePath currentPath;
+  @Nullable private Element enclosingElement;
+
+  public TreeContextScanner(Trees trees) {
+    this.trees = trees;
+  }
+
+  protected final TreePath getCurrentPath() {
+    return Objects.requireNonNull(currentPath);
+  }
+
+  /** Returns the {@link Element} that encloses the current tree path. */
+  protected final Element getEnclosingElement() {
+    return Objects.requireNonNull(enclosingElement);
+  }
+
+  /**
+   * Returns the {@link Element} for the type of the current tree. (Equivalent to {@code
+   * getCurrentType().asElement()} when the current tree represents a type for which there is an
+   * element.)
+   */
+  @Nullable
+  protected final Element getCurrentElement() {
+    return trees.getElement(getCurrentPath());
+  }
+
+  @Nullable
+  protected final TypeMirror getCurrentType() {
+    return trees.getTypeMirror(getCurrentPath());
+  }
+
+  @Override
+  @Nullable
+  public R scan(Tree tree, @Nullable P p) {
+    if (tree == null) {
+      return null;
+    }
+
+    TreePath previousPath = currentPath;
+    Element previousEnclosingElement = enclosingElement;
+
+    currentPath = new TreePath(currentPath, tree);
+    switch (tree.getKind()) {
+      case ANNOTATION_TYPE:
+      case CLASS:
+      case COMPILATION_UNIT:
+      case ENUM:
+      case INTERFACE:
+      case METHOD:
+      case VARIABLE:
+      case TYPE_PARAMETER:
+        enclosingElement = Objects.requireNonNull(trees.getElement(currentPath));
+        break;
+      // $CASES-OMITTED$
+      default:
+        break;
+    }
+    try {
+      // This super call will actually visit the tree, now with all the context set up
+      return super.scan(tree, p);
+    } finally {
+      currentPath = previousPath;
+      enclosingElement = previousEnclosingElement;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreePathScannerForTypeResolution.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreePathScannerForTypeResolution.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/TreePathScannerForTypeResolution.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.AnnotatedTypeTree;
+import com.sun.source.tree.IdentifierTree;
+import com.sun.source.tree.MemberSelectTree;
+import com.sun.source.tree.ParameterizedTypeTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.tree.Tree.Kind;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.TreePathScanner;
+import com.sun.source.util.Trees;
+import java.util.Objects;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.SimpleElementVisitor8;
+
+/**
+ * A {@link TreePathScanner} that forms the scaffolding of any kind of type reference resolution
+ * logic. Scans a {@link TreePath} that represents a reference to a type element and
+ */
+abstract class TreePathScannerForTypeResolution<R, P> extends TreePathScanner<R, P> {
+
+  private final Trees trees;
+
+  protected TreePathScannerForTypeResolution(Trees trees) {
+    this.trees = trees;
+  }
+
+  @Override
+  @Nullable
+  public final R visitAnnotatedType(AnnotatedTypeTree node, P p) {
+    return scan(node.getUnderlyingType(), p);
+  }
+
+  @Override
+  @Nullable
+  public final R visitParameterizedType(ParameterizedTypeTree node, P p) {
+    return scan(node.getType(), p);
+  }
+
+  @Override
+  @Nullable
+  public final R visitMemberSelect(MemberSelectTree node, P p) {
+    TreePath referencingPath = getCurrentPath();
+    Element referencedElement = Objects.requireNonNull(trees.getElement(referencingPath));
+    return resolveElement(referencingPath, referencedElement, p);
+  }
+
+  @Override
+  @Nullable
+  public final R visitIdentifier(IdentifierTree node, P p) {
+    TreePath referencingPath = getCurrentPath();
+    Element referencedElement = Objects.requireNonNull(trees.getElement(referencingPath));
+    return resolveElement(referencingPath, referencedElement, p);
+  }
+
+  @Nullable
+  protected final R resolveEnclosingElement(P p) {
+    Tree leaf = getCurrentPath().getLeaf();
+    if (leaf.getKind() == Kind.MEMBER_SELECT) {
+      MemberSelectTree memberSelect = (MemberSelectTree) leaf;
+      return super.visitMemberSelect(memberSelect, p);
+    } else {
+      return null;
+    }
+  }
+
+  @Nullable
+  private R resolveElement(TreePath referencingPath, Element referencedElement, P p) {
+    return referencedElement.accept(
+        new SimpleElementVisitor8<R, P>() {
+          @Override
+          @Nullable
+          public R visitType(TypeElement e, P p) {
+            return resolveType(referencingPath, e, p);
+          }
+
+          @Override
+          @Nullable
+          public R visitPackage(PackageElement e, P p) {
+            return resolvePackage(referencingPath, e, p);
+          }
+
+          @Override
+          protected R defaultAction(Element e, P p) {
+            throw new IllegalArgumentException(
+                String.format("Unexpected element of kind %s: %s", e.getKind(), e));
+          }
+        },
+        p);
+  }
+
+  @Nullable
+  protected abstract R resolveType(TreePath referencingPath, TypeElement referencedType, P p);
+
+  @Nullable
+  protected abstract R resolvePackage(
+      TreePath referencingPath, PackageElement referencedPackage, P p);
+
+  @Override
+  @Nullable
+  public final R scan(Tree tree, P p) {
+    switch (tree.getKind()) {
+      case ANNOTATED_TYPE:
+      case IDENTIFIER:
+      case MEMBER_SELECT:
+      case PARAMETERIZED_TYPE:
+        return super.scan(tree, p);
+      // $CASES-OMITTED$
+      default:
+        throw new IllegalArgumentException(
+            String.format("Unexpected tree of kind %s: %s", tree.getKind(), tree));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ValidatingTaskListener.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ValidatingTaskListener.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/ValidatingTaskListener.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source;
+
+import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfoFactory.SourceOnlyAbiRuleInfo;
+import com.facebook.buck.jvm.java.plugin.adapter.BuckJavacTask;
+import com.facebook.buck.jvm.java.plugin.adapter.BuckJavacTaskProxyImpl;
+import com.facebook.buck.jvm.java.plugin.api.BuckJavacTaskProxy;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.util.TaskEvent;
+import com.sun.source.util.TaskListener;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Supplier;
+import javax.tools.Diagnostic;
+
+/**
+ * A {@link TaskListener} that is used during full compilation to validate the guesses made by
+ * source-based ABI generation.
+ */
+public class ValidatingTaskListener implements TaskListener {
+  private final BuckJavacTask javacTask;
+  private final List<CompilationUnitTree> compilationUnits = new ArrayList<>();
+  private final SourceOnlyAbiRuleInfo ruleInfo;
+  private final Supplier<Boolean> errorsExist;
+  private final Diagnostic.Kind messageKind;
+
+  @Nullable private InterfaceValidator validator;
+  private int enterDepth = 0;
+  private boolean annotationProcessing = false;
+
+  public ValidatingTaskListener(
+      BuckJavacTaskProxy task,
+      SourceOnlyAbiRuleInfo ruleInfo,
+      Supplier<Boolean> errorsExist,
+      Diagnostic.Kind messageKind) {
+    this.javacTask = ((BuckJavacTaskProxyImpl) task).getInner();
+    this.ruleInfo = ruleInfo;
+    this.errorsExist = errorsExist;
+    this.messageKind = messageKind;
+  }
+
+  private InterfaceValidator getValidator() {
+    // We can't do this on construction, because the Task might not be fully initialized yet
+    if (validator == null) {
+      validator = new InterfaceValidator(messageKind, javacTask, ruleInfo);
+    }
+
+    return Objects.requireNonNull(validator);
+  }
+
+  @Override
+  public void started(TaskEvent e) {
+    TaskEvent.Kind kind = e.getKind();
+
+    if (kind == TaskEvent.Kind.ENTER) {
+      enterDepth += 1;
+    } else if (kind == TaskEvent.Kind.ANNOTATION_PROCESSING) {
+      annotationProcessing = true;
+    }
+  }
+
+  @Override
+  public void finished(TaskEvent e) {
+    TaskEvent.Kind kind = e.getKind();
+    if (kind == TaskEvent.Kind.PARSE) {
+      CompilationUnitTree compilationUnit = e.getCompilationUnit();
+      compilationUnits.add(compilationUnit);
+    } else if (kind == TaskEvent.Kind.ENTER) {
+      enterDepth -= 1;
+      // We wait until we've received all enter events so that the validation time shows up
+      // separately from compiler enter time in the traces. We wait until after annotation
+      // processing so we catch all the types.
+      if (!annotationProcessing && enterDepth == 0 && !errorsExist.get()) {
+        getValidator().validate(compilationUnits);
+      }
+    } else if (kind == TaskEvent.Kind.ANNOTATION_PROCESSING) {
+      annotationProcessing = false;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/BUCK
@@ -0,0 +1,19 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "api",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        # Don't add deps that aren't already in the plugin; this is a super-light library
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/api:api",
+        "prelude//toolchains/android/src/com/facebook/buck/util/liteinfersupport:liteinfersupport",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/CannotInferException.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/CannotInferException.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/CannotInferException.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source.api;
+
+import javax.lang.model.element.Element;
+import javax.lang.model.type.TypeMirror;
+
+public class CannotInferException extends RuntimeException {
+  public CannotInferException(String what, Element owner) {
+    super(formatMessage(what, owner));
+  }
+
+  public CannotInferException(String what, TypeMirror owner) {
+    super(formatMessage(what, owner));
+  }
+
+  private static String formatMessage(String what, Object owner) {
+    return String.format(
+        "Buck had to infer the existence of %1$s for source-only ABI generation, and thus cannot"
+            + " know the %2$s of the type.\n"
+            + "One of three things is happening:\n"
+            + "  1. The BUCK file is missing a dependency for %1$s\n"
+            + "  2. The module containing %1$s needs to be marked with required_for_source_only_abi"
+            + " or referenced as a source_only_abi_dep\n"
+            + "  3. An annotation processor is accessing a type that it shouldn't be",
+        owner, what);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/ErrorSuppressingDiagnosticListener.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/ErrorSuppressingDiagnosticListener.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/ErrorSuppressingDiagnosticListener.java
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source.api;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Objects;
+import java.util.Set;
+import javax.tools.Diagnostic;
+import javax.tools.DiagnosticListener;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+
+/**
+ * When running the compiler with some dependencies missing (as when generating ABIs from source),
+ * by default it will abort after the last round of annotation processing because it believes there
+ * are missing types. This diagnostic listener tricks the compiler into ignoring those errors (which
+ * it marks as "recoverable") so that the compiler will keep going and run one more enter phase
+ * after annotation processing. We must be careful to not allow it to run further, because the
+ * analyze phase will not be happy to have missing types.
+ */
+public class ErrorSuppressingDiagnosticListener implements DiagnosticListener<JavaFileObject> {
+  private final DiagnosticListener<? super JavaFileObject> inner;
+  @Nullable private JavaCompiler.CompilationTask task;
+  @Nullable private Field contextField;
+  @Nullable private Method instanceMethod;
+  @Nullable private Field nErrorsField;
+  @Nullable private Field recordedField;
+  @Nullable private Enum<?> recoverableError;
+  @Nullable private Method isFlagSetMethod;
+  @Nullable private Field diagnosticField;
+  @Nullable private Field pairFirstField;
+  @Nullable private Field pairSecondField;
+
+  public ErrorSuppressingDiagnosticListener(DiagnosticListener<? super JavaFileObject> inner) {
+    this.inner = inner;
+  }
+
+  public void setTask(JavaCompiler.CompilationTask task) {
+    this.task = task;
+  }
+
+  @Override
+  public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
+    ensureInitialized();
+    if (diagnostic.getKind() != Diagnostic.Kind.ERROR || !isRecoverable(diagnostic)) {
+      inner.report(diagnostic);
+    } else {
+      // Don't pass the error on to Buck. Also, decrement nerrors in the compiler so that it
+      // won't prematurely stop compilation.
+      decrementNErrors();
+
+      // Log uses a set of file, offset pairs to prevent reporting the same error twice. Since
+      // we suppressed this error, we should allow other (non-suppressed) errors to be reported
+      // in the same location
+      removeFromRecordedSet(diagnostic);
+    }
+  }
+
+  private void decrementNErrors() {
+    Field nErrorsField = Objects.requireNonNull(this.nErrorsField);
+
+    try {
+      int nerrors = (Integer) nErrorsField.get(getLog());
+      nerrors -= 1;
+      nErrorsField.set(getLog(), nerrors);
+    } catch (IllegalAccessException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private void removeFromRecordedSet(Diagnostic<? extends JavaFileObject> diagnostic) {
+    JavaFileObject file = diagnostic.getSource();
+    if (file == null) {
+      return;
+    }
+
+    try {
+      Set<?> recorded = (Set<?>) Objects.requireNonNull(recordedField).get(getLog());
+      if (recorded != null) {
+        boolean removed = false;
+        for (Object recordedPair : recorded) {
+          JavaFileObject fst =
+              (JavaFileObject) Objects.requireNonNull(pairFirstField).get(recordedPair);
+          Integer snd = (Integer) Objects.requireNonNull(pairSecondField).get(recordedPair);
+
+          if (snd == diagnostic.getPosition() && fst.getName().equals(file.getName())) {
+            removed = recorded.remove(recordedPair);
+            break;
+          }
+        }
+        if (!removed) {
+          throw new AssertionError(
+              String.format(
+                  "BUG! Failed to remove %s: %d", file.getName(), diagnostic.getPosition()));
+        }
+      }
+    } catch (IllegalAccessException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  /**
+   * Gets the current log object, since the Log and the Context change for each round of annotation
+   * processing.
+   */
+  private Object getLog() {
+    try {
+      Object context = Objects.requireNonNull(contextField).get(task);
+      return Objects.requireNonNull(instanceMethod).invoke(null, context);
+    } catch (IllegalAccessException | InvocationTargetException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private boolean isRecoverable(Diagnostic<? extends JavaFileObject> diagnostic) {
+    try {
+      // There's a bug in javac whereby under certain circumstances it will assign its default
+      // flag set to a Diagnostic object without copying it first, and then mutate the set
+      // such that it contains the "recoverable" flag. That can cause missing class file errors
+      // to be reported as recoverable, when they're really not.
+      if (diagnostic.getCode().equals("compiler.err.cant.access")
+          || diagnostic.getCode().equals("compiler.err.proc.messager")) {
+        return false;
+      }
+
+      return (boolean)
+          Objects.requireNonNull(isFlagSetMethod)
+              .invoke(Objects.requireNonNull(diagnosticField).get(diagnostic), recoverableError);
+    } catch (IllegalAccessException | InvocationTargetException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private void ensureInitialized() {
+    if (nErrorsField != null) {
+      return;
+    }
+
+    try {
+      Class<? extends JavaCompiler.CompilationTask> compilerClass =
+          Objects.requireNonNull(task).getClass();
+      contextField = compilerClass.getSuperclass().getDeclaredField("context");
+      contextField.setAccessible(true);
+      Object context = contextField.get(task);
+
+      ClassLoader compilerClassLoader = compilerClass.getClassLoader();
+      Class<?> logClass = Class.forName("com.sun.tools.javac.util.Log", false, compilerClassLoader);
+      instanceMethod = logClass.getMethod("instance", context.getClass());
+      nErrorsField = logClass.getField("nerrors");
+      recordedField = logClass.getDeclaredField("recorded");
+      recordedField.setAccessible(true);
+
+      Class<?> diagnosticClass =
+          Class.forName("com.sun.tools.javac.util.JCDiagnostic", false, compilerClassLoader);
+      @SuppressWarnings("unchecked")
+      Class<Enum<?>> diagnosticFlagClass =
+          (Class<Enum<?>>)
+              Class.forName(
+                  "com.sun.tools.javac.util.JCDiagnostic$DiagnosticFlag",
+                  false,
+                  compilerClassLoader);
+      isFlagSetMethod = diagnosticClass.getMethod("isFlagSet", diagnosticFlagClass);
+      for (Enum<?> enumConstant : diagnosticFlagClass.getEnumConstants()) {
+        if (enumConstant.name().equals("RECOVERABLE")) {
+          recoverableError = enumConstant;
+          break;
+        }
+      }
+      Objects.requireNonNull(recoverableError);
+
+      Class<?> diagnosticSourceUnwrapperClass =
+          Class.forName(
+              "com.sun.tools.javac.api.ClientCodeWrapper$DiagnosticSourceUnwrapper",
+              false,
+              compilerClassLoader);
+      diagnosticField = diagnosticSourceUnwrapperClass.getField("d");
+
+      Class<?> pairClass =
+          Class.forName("com.sun.tools.javac.util.Pair", false, compilerClassLoader);
+      pairFirstField = pairClass.getField("fst");
+      pairSecondField = pairClass.getField("snd");
+    } catch (ClassNotFoundException
+        | IllegalAccessException
+        | NoSuchFieldException
+        | NoSuchMethodException e) {
+      throw new RuntimeException(e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/FrontendOnlyJavacTaskProxy.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/FrontendOnlyJavacTaskProxy.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/FrontendOnlyJavacTaskProxy.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source.api;
+
+import com.facebook.buck.jvm.java.plugin.api.BuckJavacTaskProxy;
+import com.facebook.buck.jvm.java.plugin.api.PluginClassLoader;
+import com.facebook.buck.jvm.java.plugin.api.PluginClassLoaderFactory;
+import java.io.Writer;
+import javax.tools.DiagnosticListener;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+
+public interface FrontendOnlyJavacTaskProxy extends BuckJavacTaskProxy {
+  static FrontendOnlyJavacTaskProxy getTask(
+      PluginClassLoaderFactory loaderFactory,
+      JavaCompiler compiler,
+      Writer out,
+      JavaFileManager fileManager,
+      DiagnosticListener<? super JavaFileObject> diagnosticListener,
+      Iterable<String> options,
+      Iterable<String> classes,
+      Iterable<? extends JavaFileObject> compilationUnits) {
+    ErrorSuppressingDiagnosticListener errorSuppressingDiagnosticListener =
+        new ErrorSuppressingDiagnosticListener(diagnosticListener);
+    JavaCompiler.CompilationTask task =
+        compiler.getTask(
+            out,
+            fileManager,
+            errorSuppressingDiagnosticListener,
+            options,
+            classes,
+            compilationUnits);
+    errorSuppressingDiagnosticListener.setTask(task);
+
+    PluginClassLoader loader = loaderFactory.getPluginClassLoader(task);
+    Class<? extends FrontendOnlyJavacTaskProxy> proxyImplClass =
+        loader.loadClass(
+            "com.facebook.buck.jvm.java.abi.source.FrontendOnlyJavacTaskProxyImpl",
+            FrontendOnlyJavacTaskProxy.class);
+
+    try {
+      return proxyImplClass.getConstructor(JavaCompiler.CompilationTask.class).newInstance(task);
+    } catch (ReflectiveOperationException e) {
+      throw new RuntimeException(e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/SourceCodeWillNotCompileException.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/SourceCodeWillNotCompileException.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/SourceCodeWillNotCompileException.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source.api;
+
+/**
+ * Thrown when a source ABI cannot be generated because the source code will not compile. Correct
+ * handling is to simply stop attempting to generate the ABI and allow the compiler to fail.
+ */
+public class SourceCodeWillNotCompileException extends RuntimeException {}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/SourceOnlyAbiRuleInfoFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/SourceOnlyAbiRuleInfoFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/SourceOnlyAbiRuleInfoFactory.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source.api;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import javax.lang.model.element.Element;
+import javax.lang.model.util.Elements;
+import javax.tools.JavaFileManager;
+
+/** Used to create the SourceOnlyAbiRuleInfo for a target given a JavaFileManager. */
+public interface SourceOnlyAbiRuleInfoFactory {
+  SourceOnlyAbiRuleInfo create(JavaFileManager fileManager);
+
+  /** Provides information related to source-only abi support. */
+  interface SourceOnlyAbiRuleInfo {
+
+    @Nullable
+    String getOwningTarget(Elements elements, Element element);
+
+    boolean elementIsAvailableForSourceOnlyAbi(Elements elements, Element element);
+
+    String getRuleName();
+
+    boolean ruleIsRequiredForSourceOnlyAbi();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/StopCompilation.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/StopCompilation.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api/StopCompilation.java
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.abi.source.api;
+
+/** Thrown by our ABI generating plugin to stop the compiler. */
+public class StopCompilation extends RuntimeException {}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/package-info.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/package-info.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/abi/source/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+/**
+ * Enables generation of ABI jars using only the Java source code of a single target, without
+ * requiring access to the source or ABI of dependencies.
+ *
+ * <p>If the ABI of a dependency target is available, it will be used. However, when one or more
+ * dependency ABIs are missing, certain language constructs become ambiguous, and we have to make
+ * assumptions. Most of those assumptions can be worked around with small changes to coding style.
+ *
+ * <p>See {@link com.facebook.buck.jvm.java.abi.source.InterfaceValidator} for more information on
+ * the restrictions.
+ */
+package com.facebook.buck.jvm.java.abi.source;
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/AbstractFileLike.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/AbstractFileLike.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/AbstractFileLike.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.classes;
+
+public abstract class AbstractFileLike implements FileLike {
+
+  @Override
+  public String toString() {
+    return getRelativePath() + " (in " + getContainer() + ")";
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/BUCK
@@ -0,0 +1,23 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "classes",
+    srcs = glob(["*.java"]),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/classes:classes",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/ClasspathTraversal.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/ClasspathTraversal.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/ClasspathTraversal.java
@@ -0,0 +1,213 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.classes;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.file.MorePaths;
+import com.facebook.buck.io.file.PathMatcher;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.facebook.buck.util.ZipFileTraversal;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.FileVisitOption;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Collection;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/**
+ * Traversal strategy for traversing a set of paths that themselves are traversed. The provided
+ * paths can point to zip/jar files, directories of resource/class files, or individual files
+ * themselves.
+ *
+ * <p>For example, given the input paths of { foo.zip, foo/, and foo.txt }, traverse would first
+ * expand foo.zip and traverse its contents, then list the files recursively in foo/, and finally
+ * visit the single file foo.txt.
+ */
+public abstract class ClasspathTraversal {
+  private final Iterable<Path> paths;
+  private final AbsPath rootPath;
+  private final ImmutableSet<PathMatcher> ignoredPaths;
+
+  public ClasspathTraversal(
+      Collection<Path> paths, AbsPath rootPath, ImmutableSet<PathMatcher> ignoredPaths) {
+    this.paths = paths;
+    this.rootPath = rootPath;
+    this.ignoredPaths = ignoredPaths;
+  }
+
+  public abstract void visit(FileLike fileLike) throws IOException;
+
+  public final void traverse() throws IOException {
+    for (Path path : paths) {
+      // This check is unnecessary for normal builds but when building #nullsafex or
+      // #nullsafex-json flavours of java/android libraries we may run only javac frontend tasks
+      // without producing any jars in the end.
+      if (!ProjectFilesystemUtils.exists(rootPath, path)) {
+        continue;
+      }
+      ClasspathTraverser adapter =
+          createTraversalAdapter(ProjectFilesystemUtils.getPathForRelativePath(rootPath, path));
+      adapter.traverse(this);
+    }
+  }
+
+  private ClasspathTraverser createTraversalAdapter(Path path) {
+    String extension = MorePaths.getFileExtension(path);
+    if (ProjectFilesystemUtils.isDirectory(rootPath, path)) {
+      return new DirectoryTraversalAdapter(rootPath, ignoredPaths, path);
+    } else if (ProjectFilesystemUtils.isFile(rootPath, path)) {
+      if (extension.equalsIgnoreCase("jar") || extension.equalsIgnoreCase("zip")) {
+        return new ZipFileTraversalAdapter(path);
+      } else {
+        return new FileTraversalAdapter(path);
+      }
+    } else {
+      throw new IllegalArgumentException(
+          "Unsupported classpath traversal input: " + path + ". Root: " + rootPath);
+    }
+  }
+
+  private static class ZipFileTraversalAdapter implements ClasspathTraverser {
+    private final Path file;
+
+    public ZipFileTraversalAdapter(Path file) {
+      this.file = file;
+    }
+
+    @Override
+    public void traverse(ClasspathTraversal traversal) throws IOException {
+      ZipFileTraversal impl =
+          new ZipFileTraversal(file) {
+            @Override
+            public void visit(ZipFile zipFile, ZipEntry zipEntry) throws IOException {
+              traversal.visit(new FileLikeInZip(file, zipFile, zipEntry));
+            }
+          };
+      impl.traverse();
+    }
+
+    private static class FileLikeInZip extends AbstractFileLike {
+      private final Path container;
+      private final ZipFile zipFile;
+      private final ZipEntry entry;
+
+      public FileLikeInZip(Path container, ZipFile zipFile, ZipEntry entry) {
+        this.container = container;
+        this.zipFile = zipFile;
+        this.entry = entry;
+      }
+
+      @Override
+      public Path getContainer() {
+        return container;
+      }
+
+      @Override
+      public String getRelativePath() {
+        return entry.getName();
+      }
+
+      @Override
+      public long getSize() {
+        return entry.getSize();
+      }
+
+      @Override
+      public InputStream getInput() throws IOException {
+        return zipFile.getInputStream(entry);
+      }
+    }
+  }
+
+  private static class DirectoryTraversalAdapter implements ClasspathTraverser {
+    private final AbsPath rootPath;
+    private final ImmutableSet<PathMatcher> ignoredPaths;
+    private final Path directory;
+
+    public DirectoryTraversalAdapter(
+        AbsPath rootPath, ImmutableSet<PathMatcher> ignoredPaths, Path directory) {
+      this.rootPath = rootPath;
+      this.ignoredPaths = ignoredPaths;
+      this.directory = directory;
+    }
+
+    @Override
+    public void traverse(ClasspathTraversal traversal) throws IOException {
+      ProjectFilesystemUtils.walkFileTree(
+          rootPath,
+          directory,
+          ImmutableSet.of(FileVisitOption.FOLLOW_LINKS),
+          new SimpleFileVisitor<>() {
+            @Override
+            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+                throws IOException {
+              String relativePath =
+                  PathFormatter.pathWithUnixSeparators(MorePaths.relativize(directory, file));
+              traversal.visit(new FileLikeInDirectory(file, relativePath));
+              return FileVisitResult.CONTINUE;
+            }
+          },
+          ProjectFilesystemUtils.getIgnoreFilter(rootPath, true, ignoredPaths));
+    }
+  }
+
+  private static class FileTraversalAdapter implements ClasspathTraverser {
+    private final Path file;
+
+    public FileTraversalAdapter(Path file) {
+      this.file = file;
+    }
+
+    @Override
+    public void traverse(ClasspathTraversal traversal) throws IOException {
+      traversal.visit(new FileLikeInDirectory(file, file.getFileName().toString()));
+    }
+  }
+
+  private static class FileLikeInDirectory extends AbstractFileLike {
+    private final Path file;
+    private final String relativePath;
+
+    public FileLikeInDirectory(Path file, String relativePath) {
+      // Currently, the only instances of FileLikeInDirectory appear to be the .class files
+      // generated from an R.java in Android. The only exception is in unit tests.
+      this.file = file;
+      this.relativePath = relativePath;
+    }
+
+    @Override
+    public Path getContainer() {
+      return file;
+    }
+
+    @Override
+    public String getRelativePath() {
+      return relativePath;
+    }
+
+    @Override
+    public long getSize() throws IOException {
+      return Files.size(file);
+    }
+
+    @Override
+    public InputStream getInput() throws IOException {
+      return Files.newInputStream(file);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/ClasspathTraverser.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/ClasspathTraverser.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/ClasspathTraverser.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.classes;
+
+import java.io.IOException;
+
+public interface ClasspathTraverser {
+
+  void traverse(ClasspathTraversal traversal) throws IOException;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/DefaultClasspathTraverser.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/DefaultClasspathTraverser.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/DefaultClasspathTraverser.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.classes;
+
+import java.io.IOException;
+
+/**
+ * @see ClasspathTraversal
+ */
+public class DefaultClasspathTraverser implements ClasspathTraverser {
+
+  public DefaultClasspathTraverser() {}
+
+  @Override
+  public void traverse(ClasspathTraversal traversal) throws IOException {
+    traversal.traverse();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLike.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLike.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLike.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.classes;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+
+/**
+ * Provides a file-like interface for objects which may be present within more specialized
+ * containers (like zip files).
+ */
+public interface FileLike {
+  /** Returns the containing file for this file-like entry. */
+  Path getContainer();
+
+  /**
+   * Returns the relative path for the entry. For example, if this were a zip file, this would be
+   * the relative path of a particular item in the zip file.
+   */
+  String getRelativePath();
+
+  /** Returns the size of the entry in bytes. */
+  long getSize() throws IOException;
+
+  /**
+   * Opens a new input stream for the entry. This can be repeated to open the file-like object
+   * multiple times.
+   *
+   * @return Newly opened input stream.
+   * @throws java.io.IOException An error occurred opening the stream.
+   */
+  InputStream getInput() throws IOException;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLikeCharSource.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLikeCharSource.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLikeCharSource.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.classes;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import com.google.common.io.CharSource;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+
+public class FileLikeCharSource extends CharSource {
+  private final FileLike fileLike;
+
+  public FileLikeCharSource(FileLike fileLike) {
+    this.fileLike = fileLike;
+  }
+
+  @Override
+  public Reader openStream() throws IOException {
+    InputStream is = fileLike.getInput();
+    return new InputStreamReader(is, UTF_8) {
+      @Override
+      public void close() throws IOException {
+        super.close();
+        is.close();
+      }
+    };
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLikes.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLikes.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/classes/FileLikes.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.classes;
+
+/** Utilities for common operations when working with {@link FileLike}s. */
+public class FileLikes {
+
+  /** {@link FileLike} name suffix that identifies it as a Java class file. */
+  private static final String CLASS_NAME_SUFFIX = ".class";
+
+  /** Utility class: do not instantiate. */
+  private FileLikes() {}
+
+  public static boolean isClassFile(FileLike fileLike) {
+    return fileLike.getRelativePath().endsWith(CLASS_NAME_SUFFIX);
+  }
+
+  public static String getFileNameWithoutClassSuffix(FileLike fileLike) {
+    String name = fileLike.getRelativePath();
+    return name.substring(0, name.length() - CLASS_NAME_SUFFIX.length());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/BUCK
@@ -0,0 +1,58 @@
+load(
+    "@prelude//toolchains/android/tools:build_rules.bzl",
+    "buck_java_binary",
+    "buck_java_library",
+)
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "fat_jar_utils",
+    srcs = [
+        "WindowsCreateProcessEscape.java",
+    ],
+    # Maximum compatibility
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/test/com/facebook/buck/util:util",
+    ],
+)
+
+buck_java_library(
+    name = "fat-jar-main",
+    srcs = [
+        "FatJarMain.java",
+    ],
+    # Maximum compatibility
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        # Don't add more dependencies! We package these sources and compile them into fat JARs,
+        # so it's important that they don't bring along any additional dependencies.
+        ":fat_jar_utils",
+    ],
+)
+
+# Binary used to collect all class files from dependencies, used for creating
+# fatjars with buck2.
+buck_java_binary(
+    name = "fat-jar-main-binary",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":fat-jar-main",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/FatJarMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/FatJarMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/FatJarMain.java
@@ -0,0 +1,422 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.fatjar;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.management.ManagementFactory;
+import java.lang.management.RuntimeMXBean;
+import java.net.JarURLConnection;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.security.CodeSource;
+import java.security.ProtectionDomain;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+public class FatJarMain {
+
+  public static final String FAT_JAR_INNER_JAR = "inner.jar";
+  public static final String FAT_JAR_NATIVE_LIBRARIES_DIR = "nativelibs";
+  public static final String WRAPPER_SCRIPT_MARKER_FILE = "wrapper_script";
+
+  private static final String DEBUG_OPTION = "--debug";
+
+  private FatJarMain() {}
+
+  /**
+   * Main method for fat jar. Unpacks artifact and native libraries into a temporary folder and then
+   * launches original artifact as java process.
+   */
+  @SuppressWarnings("PMD.BlacklistedDefaultProcessMethod")
+  public static void main(String[] args) throws Exception {
+
+    boolean debug = args.length > 0 && args[0].equals(DEBUG_OPTION);
+
+    ProcessBuilder processBuilder = new ProcessBuilder();
+    Map<String, String> environment = processBuilder.environment();
+
+    if (debug) {
+      printDebugInfo("System envs: " + environment);
+    }
+
+    ClassLoader classLoader = FatJarMain.class.getClassLoader();
+
+    // Create a temp dir to house the native libraries.
+    int exitCode;
+    try (ManagedTemporaryDirectory temp = new ManagedTemporaryDirectory("fatjar.", !debug)) {
+      Path workingDirectory = temp.getPath();
+      if (debug) {
+        printDebugInfo("Created a temporary directory: " + workingDirectory);
+      }
+
+      // Unpack the real, inner artifact (JAR or wrapper script).
+      boolean isWrapperScript = isWrapperScript();
+      Path innerArtifact = workingDirectory.resolve(isWrapperScript ? "wrapper.sh" : "main.jar");
+      if (debug) {
+        printDebugInfo("Extracting inner artifact into: " + innerArtifact);
+      }
+      unpackInnerArtifactTo(classLoader, innerArtifact);
+      if (isWrapperScript) {
+        makeExecutable(innerArtifact);
+      }
+
+      // Unpack all the native libraries, since the system loader will need to find these on disk.
+      Path nativeLibs = workingDirectory.resolve("native_libs");
+      Files.createDirectory(nativeLibs);
+      unpackNativeLibrariesInto(nativeLibs, debug);
+
+      // Update the appropriate environment variable with the location of our native libraries
+      // and start the real main class in a new process so that it picks it up.
+      List<String> command =
+          getCommand(
+              isWrapperScript,
+              innerArtifact,
+              debug,
+              debug ? Arrays.copyOfRange(args, 1, args.length) : args);
+      if (debug) {
+        printDebugInfo("Executing command: " + command);
+      }
+      processBuilder.command(command);
+      if (isWrapperScript) {
+        Path rootDirectory = getRootDirectory();
+        if (debug) {
+          String currentDirectory = System.getProperty("user.dir");
+          printDebugInfo(
+              String.format(
+                  "Changing working directory from %s to %s", currentDirectory, rootDirectory));
+        }
+        processBuilder.directory(rootDirectory.toFile());
+      }
+      updateEnvironment(environment, nativeLibs, debug);
+      processBuilder.inheritIO();
+
+      // Wait for the inner process, then let the try-with-resources delete the unpacked
+      // native libraries before we exit
+      exitCode = processBuilder.start().waitFor();
+    }
+    System.exit(exitCode);
+  }
+
+  private static Path getRootDirectory() throws IOException, InterruptedException {
+    // TODO: @classpath_args are relative to repo root for buck2
+    String command = "hg root";
+    Process process = Runtime.getRuntime().exec(command);
+    Path path;
+    try (BufferedReader reader =
+        new BufferedReader(new InputStreamReader(process.getInputStream()))) {
+      path = Paths.get(reader.readLine());
+    }
+    int exitCode = process.waitFor();
+    if (exitCode != 0) {
+      throw new IllegalStateException(
+          String.format("Command '%s' execution failed. Exit code: %s.", command, exitCode));
+    }
+    return path;
+  }
+
+  private static boolean isWrapperScript() throws IOException {
+    try (JarFile jar = new JarFile(getJarPath())) {
+      JarEntry entry = jar.getJarEntry(WRAPPER_SCRIPT_MARKER_FILE);
+      return entry != null;
+    }
+  }
+
+  private static void unpackNativeLibrariesInto(Path destination, boolean debug)
+      throws IOException {
+    try (JarFile jar = new JarFile(getJarPath())) {
+      Enumeration<JarEntry> enumEntries = jar.entries();
+      while (enumEntries.hasMoreElements()) {
+        JarEntry jarEntry = enumEntries.nextElement();
+        String entryName = jarEntry.getName();
+        if (jarEntry.isDirectory() || !entryName.startsWith(FAT_JAR_NATIVE_LIBRARIES_DIR)) {
+          continue;
+        }
+
+        String fileName = entryName.substring(FAT_JAR_NATIVE_LIBRARIES_DIR.length() + 1);
+        if (debug) {
+          printDebugInfo("Extracting native library: " + fileName);
+        }
+        Files.copy(jar.getInputStream(jarEntry), destination.resolve(fileName));
+      }
+    }
+  }
+
+  private static String getJarPath() throws IOException {
+    ProtectionDomain protectionDomain = FatJarMain.class.getProtectionDomain();
+    CodeSource codeSource = protectionDomain.getCodeSource();
+    URL jarUrl = new URL("jar:" + codeSource.getLocation().toExternalForm() + "!/");
+    URL jarFileUrl = ((JarURLConnection) jarUrl.openConnection()).getJarFileURL();
+    return jarFileUrl.getPath();
+  }
+
+  private static void unpackInnerArtifactTo(ClassLoader loader, Path destination)
+      throws IOException {
+    try (InputStream input = loader.getResourceAsStream(FAT_JAR_INNER_JAR);
+        BufferedInputStream bufferedInput =
+            new BufferedInputStream(Objects.requireNonNull(input))) {
+      Files.copy(bufferedInput, destination);
+    }
+  }
+
+  /**
+   * Update the library search path environment variable with the given native library directory.
+   */
+  private static void updateEnvironment(Map<String, String> env, Path libDir, boolean debug) {
+    String librarySearchPathName = getLibrarySearchPathName();
+    String originalLibPath = getEnvValue(librarySearchPathName);
+    String newLibPath =
+        libDir + (originalLibPath == null ? "" : File.pathSeparator + originalLibPath);
+
+    if (debug) {
+      printDebugInfo(
+          String.format(
+              "Setting/Updating env variable: '%s' with '%s' value",
+              librarySearchPathName, newLibPath));
+    }
+    env.put(librarySearchPathName, newLibPath);
+  }
+
+  private static List<String> getJVMArguments() {
+    RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
+    try {
+      return runtimeMxBean.getInputArguments();
+    } catch (java.lang.SecurityException e) {
+      // Do not have the ManagementPermission("monitor") permission
+      return Collections.emptyList();
+    }
+  }
+
+  /**
+   * @return a command to start a new JVM process to execute the given main class.
+   */
+  private static List<String> getCommand(
+      boolean wrapperScript, Path artifact, boolean isDebug, String[] args) throws IOException {
+    List<String> cmd = new ArrayList<>();
+
+    // Check if wrapper uses script that provides java runtime by itself
+    boolean javaRuntimeProvided =
+        wrapperScript && "true".equalsIgnoreCase(getEnvValue("FAT_JAR_SKIP_ADDING_JAVA_RUNTIME"));
+    if (!javaRuntimeProvided) {
+      // Look for the Java binary given in an alternate location if given,
+      // otherwise use the Java binary that started us
+      String javaHome =
+          System.getProperty("buck.fatjar.java.home", System.getProperty("java.home"));
+      cmd.add(Paths.get(javaHome, "bin", "java").toString());
+    }
+    // Pass through any VM arguments to the child process
+    cmd.addAll(getJVMArguments());
+    if (!cmd.contains("-XX:-MaxFDLimit")) {
+      // Directs the VM to refrain from setting the file descriptor limit to the default maximum.
+      // https://stackoverflow.com/a/16535804/5208808
+      cmd.add("-XX:-MaxFDLimit");
+    }
+
+    if (wrapperScript) {
+
+      List<String> nonJvmArgs = new ArrayList<>();
+      if (isDebug) {
+        printDebugInfo(
+            "extracting -J prefix args for JVM positional options for generate_wrapper format");
+      }
+
+      for (String arg : args) {
+        if (arg.startsWith("-J")) {
+          if (isDebug) {
+            printDebugInfo("extracting arg: " + arg.substring(2));
+          }
+          cmd.add(arg.substring(2));
+        } else {
+          nonJvmArgs.add(arg);
+        }
+      }
+
+      args = nonJvmArgs.toArray(new String[0]);
+
+      String customWrapper = getEnvValue("FAT_JAR_CUSTOM_SCRIPT");
+      if (customWrapper != null) {
+        if (isDebug) {
+          printDebugInfo("Using custom script wrapper: " + customWrapper);
+        }
+        cmd.add(0, customWrapper);
+      }
+
+      List<String> strings = Files.readAllLines(artifact, StandardCharsets.UTF_8);
+      if (strings.size() != 1) {
+        throw new IllegalStateException(
+            String.format(
+                "Expected to read only 1 line from the wrapper script: %s, but read: %s",
+                artifact, strings.size()));
+      }
+      String command = strings.iterator().next();
+      String[] wrapperCommand = command.split("\\s+");
+
+      // classpath
+      cmd.add(wrapperCommand[1]);
+      cmd.add(wrapperCommand[2]);
+      if (wrapperCommand.length > 4) {
+        // main class
+        String mainClass = wrapperCommand[3];
+        cmd.add(mainClass);
+      }
+    } else {
+      cmd.add("-jar");
+      // Lookup our current JAR context.
+      cmd.add(artifact.toString());
+    }
+    // pass args to new java process
+    Collections.addAll(cmd, args);
+
+    /* On Windows, we need to escape the arguments we hand off to `CreateProcess`.  See
+     * http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
+     * for more details.
+     */
+    if (isWindowsOs(getOsPlatform())) {
+      List<String> escapedCommand = new ArrayList<>(cmd.size());
+      for (String c : cmd) {
+        escapedCommand.add(WindowsCreateProcessEscape.quote(c));
+      }
+      return escapedCommand;
+    }
+
+    return cmd;
+  }
+
+  private static void makeExecutable(Path file) throws IOException {
+    if (!file.toFile().setExecutable(true, true)) {
+      throw new IOException("The file could not be made executable");
+    }
+  }
+
+  /**
+   * @return the platform specific environment variable for setting the native library search path.
+   */
+  private static String getLibrarySearchPathName() {
+    String platform = getOsPlatform();
+    if (platform.startsWith("Linux")) {
+      return "LD_LIBRARY_PATH";
+    } else if (platform.startsWith("Mac OS")) {
+      return "DYLD_LIBRARY_PATH";
+    } else if (isWindowsOs(platform)) {
+      return "PATH";
+    } else {
+      System.err.println(
+          "WARNING: using \"LD_LIBRARY_PATH\" for unrecognized platform " + platform);
+      return "LD_LIBRARY_PATH";
+    }
+  }
+
+  // Avoid using EnvVariablesProvider to avoid extra dependencies.
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  private static String getEnvValue(String envVariableName) {
+    if (isWindowsOs(getOsPlatform())) {
+      return findMapValueIgnoreKeyCase(envVariableName, System.getenv());
+    } else {
+      return System.getenv(envVariableName);
+    }
+  }
+
+  private static String findMapValueIgnoreKeyCase(String key, Map<String, String> map) {
+    for (Map.Entry<String, String> entry : map.entrySet()) {
+      if (entry.getKey().equalsIgnoreCase(key)) {
+        return entry.getValue();
+      }
+    }
+    return null;
+  }
+
+  private static String getOsPlatform() {
+    return Objects.requireNonNull(System.getProperty("os.name"));
+  }
+
+  private static boolean isWindowsOs(String osPlatform) {
+    return osPlatform.startsWith("Windows");
+  }
+
+  private static void printDebugInfo(String message) {
+    System.out.println("DEBUG: " + message);
+  }
+
+  /**
+   * A temporary directory that automatically cleans itself up when used via a try-resource block.
+   */
+  private static class ManagedTemporaryDirectory implements AutoCloseable {
+
+    private final Path path;
+    private final boolean removeTempDirectory;
+
+    private ManagedTemporaryDirectory(Path path, boolean removeTempDirectory) {
+      this.path = path;
+      this.removeTempDirectory = removeTempDirectory;
+    }
+
+    public ManagedTemporaryDirectory(String prefix, boolean removeTempDirectory)
+        throws IOException {
+      this(Files.createTempDirectory(prefix), removeTempDirectory);
+    }
+
+    @Override
+    public void close() {
+      if (!removeTempDirectory) {
+        printDebugInfo("Skipping temp directory removal. Temp directory: " + path);
+        return;
+      }
+      try {
+        Files.walkFileTree(
+            path,
+            new SimpleFileVisitor<Path>() {
+
+              @Override
+              public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+                  throws IOException {
+                Files.delete(file);
+                return FileVisitResult.CONTINUE;
+              }
+
+              @Override
+              public FileVisitResult postVisitDirectory(Path dir, IOException e)
+                  throws IOException {
+                if (e != null) {
+                  throw e;
+                }
+                Files.delete(dir);
+                return FileVisitResult.CONTINUE;
+              }
+            });
+      } catch (IOException e) {
+        // Best-effort: a failure to delete scratch must not mask the child's exit code or the
+        // primary failure. Warn (stderr is captured by callers) and leave it for the tmp reaper.
+        System.err.println("WARNING: failed to remove fat jar temp directory " + path + ": " + e);
+      }
+    }
+
+    public Path getPath() {
+      return path;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/WindowsCreateProcessEscape.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/WindowsCreateProcessEscape.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/fatjar/WindowsCreateProcessEscape.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.fatjar;
+
+/**
+ * Helps quote arguments when launching a process on Windows.
+ *
+ * <p>Unix's process spawning syscall accepts an array of arguments, but Windows' equivalent accepts
+ * a single string and splits the strings according to some different rules.
+ */
+public class WindowsCreateProcessEscape {
+  private WindowsCreateProcessEscape() {}
+
+  /** Same as {@link #quote(String)} except appends to a {@code StringBuilder}. */
+  public static void quote(StringBuilder buf, String arg) {
+    if (!mightNeedQuotes(arg)) {
+      buf.append(arg);
+      return;
+    }
+    buf.append('"');
+
+    // The length of the current run of backslashes.
+    int nPending = 0;
+
+    for (int i = 0; i < arg.length(); i++) {
+      char c = arg.charAt(i);
+
+      if (c == '\\') {
+        nPending++;
+      } else {
+        if (c == '"') {
+          // Escape all the backslashes we've collected up till now.
+          for (int j = 0; j < nPending; j++) {
+            buf.append('\\');
+          }
+          // Escape the quote.
+          buf.append('\\');
+        }
+        nPending = 0;
+      }
+
+      buf.append(c);
+    }
+
+    // Escape all the backslashes that appear before the final closing quote.
+    for (int j = 0; j < nPending; j++) {
+      buf.append('\\');
+    }
+
+    buf.append('"');
+  }
+
+  /**
+   * Given a string X, this function returns a string that, when passed through the Windows
+   * implementation of Java's {@link Runtime#exec(String[])} or {@link ProcessBuilder}, will appear
+   * to the spawned process as X.
+   *
+   * @param arg The argument to quote.
+   * @return The quote version of 'arg'.
+   */
+  public static String quote(String arg) {
+    StringBuilder buf = new StringBuilder(2 + arg.length() * 2);
+    quote(buf, arg);
+    return buf.toString();
+  }
+
+  private static boolean mightNeedQuotes(String arg) {
+    if (arg.length() == 0) {
+      return true;
+    }
+
+    for (int i = 0; i < arg.length(); i++) {
+      char c = arg.charAt(i);
+      if (c == '"' || c == ' ' || c == '\t') {
+        return true;
+      }
+    }
+
+    return false;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/javax/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/javax/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/javax/BUCK
@@ -0,0 +1,17 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "javax",
+    srcs = glob([
+        "*.java",
+    ]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/version/utils:utils",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/javax/SynchronizedToolProvider.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/javax/SynchronizedToolProvider.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/javax/SynchronizedToolProvider.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.javax;
+
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+
+/**
+ * ToolProvider has no synchronization internally, so if we don't synchronize from the outside we
+ * could wind up loading the compiler classes multiple times from different class loaders.
+ */
+public class SynchronizedToolProvider {
+
+  public static JavaCompiler getSystemJavaCompiler() {
+    JavaCompiler compiler;
+    synchronized (ToolProvider.class) {
+      compiler = ToolProvider.getSystemJavaCompiler();
+    }
+    return compiler;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/extra/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/extra/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/extra/BUCK
@@ -0,0 +1,26 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+# This target is for code that needs access to internal Java compiler APIs. We should keep it
+# as small as possible to have good compatibility with different versions of the compiler.
+buck_java_library(
+    name = "extra",
+    srcs = glob(["*.java"]),
+    extra_arguments = [
+        "--add-exports",
+        "jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
+        "--add-exports",
+        "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:asm",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/extra/MoreTypeAnnotations.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/extra/MoreTypeAnnotations.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/extra/MoreTypeAnnotations.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.lang.extra;
+
+import com.sun.tools.javac.code.Attribute;
+import com.sun.tools.javac.code.TypeAnnotationPosition;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.List;
+import javax.annotation.Nullable;
+import javax.lang.model.element.AnnotationMirror;
+import org.objectweb.asm.TypePath;
+import org.objectweb.asm.TypeReference;
+
+/**
+ * Helper methods for working with type annotations.
+ *
+ * <p>NOTE 1: This class is separate from {@code MoreAnnotations} because the latter is in the
+ * bootstrapper where we cannot depend on ASM which is required here.
+ *
+ * <p>NOTE 2: This code uses internal compiler APIs to extra a type position of a javac type
+ * annotation. It should be compatible with up to JDK 19 but further updates may require revising
+ * this code.
+ */
+public class MoreTypeAnnotations {
+
+  /** Extract and re-encode annotation's position type as ASM's {@link TypeReference}. */
+  @Nullable
+  public static TypeReference getAnnotationTypeReference(AnnotationMirror annotation) {
+    TypeAnnotationPosition position = getAnnotationPosition(annotation);
+    if (position == null) {
+      return null;
+    }
+
+    switch (position.type) {
+      case CLASS_TYPE_PARAMETER:
+        return TypeReference.newTypeParameterReference(
+            TypeReference.CLASS_TYPE_PARAMETER, position.parameter_index);
+      case METHOD_TYPE_PARAMETER:
+        return TypeReference.newTypeParameterReference(
+            TypeReference.METHOD_TYPE_PARAMETER, position.parameter_index);
+      case CLASS_EXTENDS:
+        return TypeReference.newSuperTypeReference(position.type_index);
+      case CLASS_TYPE_PARAMETER_BOUND:
+        return TypeReference.newTypeParameterBoundReference(
+            TypeReference.CLASS_TYPE_PARAMETER_BOUND,
+            position.parameter_index,
+            position.bound_index);
+      case METHOD_TYPE_PARAMETER_BOUND:
+        return TypeReference.newTypeParameterBoundReference(
+            TypeReference.METHOD_TYPE_PARAMETER_BOUND,
+            position.parameter_index,
+            position.bound_index);
+      case FIELD:
+        return TypeReference.newTypeReference(TypeReference.FIELD);
+      case METHOD_RETURN:
+        return TypeReference.newTypeReference(TypeReference.METHOD_RETURN);
+      case METHOD_RECEIVER:
+        return TypeReference.newTypeReference(TypeReference.METHOD_RECEIVER);
+      case METHOD_FORMAL_PARAMETER:
+        return TypeReference.newFormalParameterReference(position.parameter_index);
+      // $CASES-OMITTED$
+      default:
+        // We're not interested in other types of annotations to generate an ABI
+        return null;
+    }
+  }
+
+  /** Extract and re-encode annotation's location as ASM's {@link TypePath}. */
+  @Nullable
+  public static TypePath getAnnotationTypePath(AnnotationMirror annotation) {
+    TypeAnnotationPosition position = getAnnotationPosition(annotation);
+    if (position == null) {
+      return null;
+    }
+
+    if (position.location.isEmpty()) {
+      return null;
+    }
+
+    int encodingLength =
+        1 + position.location.size() * TypeAnnotationPosition.TypePathEntry.bytesPerEntry;
+    byte[] encodedPath = new byte[encodingLength];
+    encodedPath[0] = (byte) position.location.size();
+    List<Integer> binaryLocation = TypeAnnotationPosition.getBinaryFromTypePath(position.location);
+    for (int i = 0; i < binaryLocation.size(); ++i) {
+      encodedPath[i + 1] = binaryLocation.get(i).byteValue();
+    }
+
+    return createTypePath(encodedPath);
+  }
+
+  @Nullable
+  private static TypeAnnotationPosition getAnnotationPosition(AnnotationMirror annotation) {
+    if (!(annotation instanceof Attribute.Compound)) {
+      return null;
+    }
+
+    return ((Attribute.Compound) annotation).getPosition();
+  }
+
+  /**
+   * NOTE: this method is needed because {@link TypePath} doesn't have a public constructor but is
+   * required for visiting type annotations. Reflection seems the only way to build an instance.
+   *
+   * @param encoded binary encoded representation of a type path
+   * @return a type path
+   */
+  private static TypePath createTypePath(byte[] encoded) {
+    try {
+      Constructor<TypePath> ctor = TypePath.class.getDeclaredConstructor(byte[].class, int.class);
+      ctor.setAccessible(true);
+      return ctor.newInstance(encoded, 0);
+    } catch (NoSuchMethodException
+        | InvocationTargetException
+        | InstantiationException
+        | IllegalAccessException e) {
+      return null;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/AnnotationValueScanner8.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/AnnotationValueScanner8.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/AnnotationValueScanner8.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.lang.model;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.AbstractAnnotationValueVisitor8;
+
+public class AnnotationValueScanner8<R, P> extends AbstractAnnotationValueVisitor8<R, P> {
+  @Nullable private final R defaultValue;
+
+  protected AnnotationValueScanner8() {
+    this(null);
+  }
+
+  protected AnnotationValueScanner8(@Nullable R defaultValue) {
+    this.defaultValue = defaultValue;
+  }
+
+  @Nullable
+  public final R scan(Iterable<? extends AnnotationValue> iterable, P p) {
+    R result = defaultValue;
+    for (AnnotationValue value : iterable) {
+      result = scan(value, p);
+    }
+    return result;
+  }
+
+  public R scan(AnnotationValue value, P p) {
+    return value.accept(this, p);
+  }
+
+  public final R scan(AnnotationValue value) {
+    return value.accept(this, null);
+  }
+
+  @Override
+  @Nullable
+  public R visitBoolean(boolean b, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitByte(byte b, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitChar(char c, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitDouble(double d, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitFloat(float f, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitInt(int i, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitLong(long i, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitShort(short s, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitString(String s, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitType(TypeMirror t, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitEnumConstant(VariableElement c, P p) {
+    return defaultValue;
+  }
+
+  @Override
+  @Nullable
+  public R visitAnnotation(AnnotationMirror a, P p) {
+    return scan(a.getElementValues().values(), p);
+  }
+
+  @Override
+  @Nullable
+  public R visitArray(List<? extends AnnotationValue> vals, P p) {
+    return scan(vals, p);
+  }
+
+  @Override
+  @Nullable
+  public R visitUnknown(AnnotationValue av, P p) {
+    return defaultValue;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "model",
+    srcs = glob(["*.java"]),
+    extra_arguments = [
+        "--add-exports",
+        "jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/version/utils:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/util/liteinfersupport:liteinfersupport",
+        # Don't add deps that aren't already in the bootstrapper; any dependencies
+        # here will pollute the compiler and annotation processor class loaders
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/BridgeMethod.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/BridgeMethod.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/BridgeMethod.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.lang.model;
+
+import javax.lang.model.element.ExecutableElement;
+
+/**
+ * A bridge method is used in Java to translate certain language constructs (like overriding methods
+ * with covariant return types) into a form that can be understood by the VM.
+ */
+public class BridgeMethod {
+
+  /**
+   * For a normal override bridge, this is the overriding method. For an accessibility bridge, this
+   * is the same as {@link #to}.
+   */
+  public final ExecutableElement from;
+
+  /**
+   * For a normal override bridge, this is the method being overridden. For an accessibility bridge,
+   * this is a public method in a non-public superclass of the current class.
+   */
+  public final ExecutableElement to;
+
+  public BridgeMethod(ExecutableElement from, ExecutableElement to) {
+    this.from = from;
+    this.to = to;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) {
+      return true;
+    }
+    if (o == null || getClass() != o.getClass()) {
+      return false;
+    }
+
+    BridgeMethod that = (BridgeMethod) o;
+
+    if (!from.equals(that.from)) {
+      return false;
+    }
+    return to.equals(that.to);
+  }
+
+  @Override
+  public int hashCode() {
+    int result = from.hashCode();
+    result = 31 * result + to.hashCode();
+    return result;
+  }
+
+  @Override
+  public String toString() {
+    return "BridgeMethod{"
+        + "from="
+        + from.getEnclosingElement()
+        + "."
+        + from
+        + ", to="
+        + to.getEnclosingElement()
+        + "."
+        + to
+        + '}';
+  }
+
+  /**
+   * Bridge methods may be generated for public methods of non-public superclasses to (as the
+   * compiler source puts it) "work around a horrible but permanent reflection design error."
+   *
+   * @return true if this is such a bridge method
+   */
+  public boolean isAccessibilityBridge() {
+    return from == to;
+  }
+
+  /**
+   * Bridge methods may be generated when an overriding method has a different erasure than the
+   * overridden method, or a different return type. (The VM only sees erased types, and at the VM
+   * level overloading on return type is legal, so these bridge methods are necessary to implement
+   * overriding as the Java language specifies it.)
+   *
+   * @return true if this is such a bridge method
+   */
+  public boolean isOverrideBridge() {
+    return from != to;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/ElementsExtended.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/ElementsExtended.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/ElementsExtended.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.lang.model;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.Elements;
+
+/**
+ * Wraps and extends {@link javax.lang.model.util.Elements} with methods that cannot be added as
+ * pure extension methods on {@link MoreElements} because they require per-instance state.
+ */
+public interface ElementsExtended extends Elements {
+
+  List<ExecutableElement> getDeclaredMethods(TypeElement owner, CharSequence name);
+
+  List<ExecutableElement> getAllMethods(TypeElement owner, CharSequence name);
+
+  List<BridgeMethod> getBridgeMethods(TypeElement owner, CharSequence name);
+
+  List<BridgeMethod> getAllBridgeMethods(TypeElement type);
+
+  @Nullable
+  ExecutableElement getImplementation(ExecutableElement method, TypeElement inType);
+
+  @Nullable
+  TypeElement getBinaryImplementationOwner(ExecutableElement method, TypeElement inType);
+
+  boolean isCompiledInCurrentRun(Element element);
+
+  /**
+   * Return type annotations present on an element.
+   *
+   * <p>Examples:
+   *
+   * <ul>
+   *   <li>For methods this means type annotations present on method's type parameters and types of
+   *       formal parameters.
+   *   <li>For classes it's type annotations on a class and its superclasses and superinterfaces.
+   *   <li>For fields it's type annotations on a field's type.
+   * </ul>
+   */
+  List<? extends AnnotationMirror> getAllTypeAnnotations(Element element);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/MoreAnnotations.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/MoreAnnotations.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/MoreAnnotations.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.lang.model;
+
+import com.sun.tools.javac.code.Symbol;
+import java.util.List;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+
+/** Helper methods for working with annotations. */
+public class MoreAnnotations {
+
+  /**
+   * Get all type annotations attached to an element.
+   *
+   * <p>NOTE: this method should not be used outside of {@code ElementsExtendedImpl}. It uses
+   * internal compiler APIs to fetch type annotations of javac Elements <b>in the right order.</b>
+   * This code should be compatible with up to JDK 19, but further compiler upgrades may require
+   * revising this code.
+   */
+  public static List<? extends AnnotationMirror> getAllTypeAnnotations(Element element) {
+    if (element instanceof Symbol) {
+      Symbol sym = (Symbol) element;
+      return sym.getRawTypeAttributes();
+    }
+
+    return List.of();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/MoreElements.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/MoreElements.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/lang/model/MoreElements.java
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.lang.model;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Stream;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.NestingKind;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.Elements;
+
+/**
+ * More utility functions for working with {@link Element}s, along the lines of those found on
+ * {@link javax.lang.model.util.Elements}.
+ */
+public final class MoreElements {
+
+  private MoreElements() {}
+
+  /** Get a package by name, even if it has no members. */
+  @Nullable
+  public static PackageElement getPackageElementEvenIfEmpty(
+      Elements elements, CharSequence packageName) {
+    // In Java 9 and later, only the new {@link
+    // javax.lang.model.util.Elements#getPackageElement(ModuleElement, CharSequence)},
+    // which {@link javax.lang.mode.util.Elements#getAllPackageElements} calls, returns empty
+    // packages.
+    Set<? extends PackageElement> packages = elements.getAllPackageElements(packageName);
+    if (packages.isEmpty()) {
+      return null;
+    }
+    if (packages.size() > 1) {
+      // TODO(jtorkkola): Add proper Java 9+ module support.
+      throw new IllegalStateException("Found more than one package matching " + packageName);
+    }
+    return packages.iterator().next();
+  }
+
+  @Nullable
+  public static TypeElement getSuperclass(TypeElement type) {
+    TypeMirror superclassType = type.getSuperclass();
+    switch (superclassType.getKind()) {
+      case DECLARED:
+      case ERROR:
+        return (TypeElement) ((DeclaredType) superclassType).asElement();
+      case NONE:
+        return null;
+      // $CASES-OMITTED$
+      default:
+        throw new IllegalArgumentException(superclassType.toString());
+    }
+  }
+
+  public static Stream<TypeElement> getInterfaces(TypeElement type) {
+    return type.getInterfaces().stream()
+        .filter(it -> it.getKind() == TypeKind.DECLARED || it.getKind() == TypeKind.ERROR)
+        .map(it -> (TypeElement) ((DeclaredType) it).asElement());
+  }
+
+  public static Stream<TypeElement> getTransitiveSuperclasses(TypeElement type) {
+    Stream.Builder<TypeElement> builder = Stream.builder();
+
+    TypeElement walker = getSuperclass(type);
+    while (walker != null) {
+      builder.add(walker);
+      walker = getSuperclass(walker);
+    }
+
+    return builder.build();
+  }
+
+  public static boolean isTransitiveMemberClass(TypeElement inner, TypeElement outer) {
+    Element walker = inner.getEnclosingElement();
+    while (walker != null) {
+      if (walker == outer) {
+        return true;
+      }
+      walker = walker.getEnclosingElement();
+    }
+
+    return false;
+  }
+
+  public static TypeElement getTypeElement(Element element) {
+    if (element.getKind() == ElementKind.PACKAGE) {
+      throw new IllegalArgumentException();
+    }
+
+    Element walker = element;
+    while (!walker.getKind().isClass() && !walker.getKind().isInterface()) {
+      walker = Objects.requireNonNull(walker.getEnclosingElement());
+    }
+
+    return (TypeElement) walker;
+  }
+
+  public static TypeElement getTopLevelTypeElement(Element element) {
+    if (element.getKind() == ElementKind.PACKAGE) {
+      throw new IllegalArgumentException();
+    }
+
+    Element walker = element;
+    while (walker.getEnclosingElement() != null
+        && walker.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
+      walker = Objects.requireNonNull(walker.getEnclosingElement());
+    }
+
+    return (TypeElement) walker;
+  }
+
+  public static PackageElement getPackageElement(Element element) {
+    Element walker = element;
+    while (walker.getKind() != ElementKind.PACKAGE) {
+      walker = Objects.requireNonNull(walker.getEnclosingElement());
+    }
+
+    return (PackageElement) walker;
+  }
+
+  public static boolean isInnerClassConstructor(ExecutableElement e) {
+    return isConstructor(e) && isInnerClass((TypeElement) e.getEnclosingElement());
+  }
+
+  public static boolean isConstructor(ExecutableElement e) {
+    return e.getSimpleName().contentEquals("<init>");
+  }
+
+  public static boolean isInnerClass(TypeElement e) {
+    return e.getNestingKind() == NestingKind.MEMBER && !e.getModifiers().contains(Modifier.STATIC);
+  }
+
+  public static Element getOuterClass(ExecutableElement e) {
+    Element innerClass = e.getEnclosingElement();
+    Element outerClass = innerClass.getEnclosingElement();
+    if (outerClass == null) {
+      throw new IllegalArgumentException(
+          String.format("Cannot get outer class of element which isn't an inner class: %s", e));
+    }
+    return outerClass;
+  }
+
+  public static boolean isRuntimeRetention(AnnotationMirror annotation) {
+    DeclaredType annotationType = annotation.getAnnotationType();
+    TypeElement annotationTypeElement = (TypeElement) annotationType.asElement();
+
+    AnnotationMirror retentionAnnotation =
+        findAnnotation("java.lang.annotation.Retention", annotationTypeElement);
+    if (retentionAnnotation == null) {
+      return false;
+    }
+
+    VariableElement retentionPolicy =
+        (VariableElement) Objects.requireNonNull(findAnnotationValue(retentionAnnotation, "value"));
+
+    return retentionPolicy.getSimpleName().contentEquals("RUNTIME");
+  }
+
+  public static boolean isSourceRetention(AnnotationMirror annotation) {
+    DeclaredType annotationType = annotation.getAnnotationType();
+    TypeElement annotationTypeElement = (TypeElement) annotationType.asElement();
+
+    AnnotationMirror retentionAnnotation =
+        findAnnotation("java.lang.annotation.Retention", annotationTypeElement);
+    if (retentionAnnotation == null) {
+      return false;
+    }
+
+    VariableElement retentionPolicy =
+        (VariableElement) Objects.requireNonNull(findAnnotationValue(retentionAnnotation, "value"));
+
+    return retentionPolicy.getSimpleName().contentEquals("SOURCE");
+  }
+
+  @Nullable
+  private static AnnotationMirror findAnnotation(CharSequence name, Element element) {
+    for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
+      DeclaredType annotationType = annotationMirror.getAnnotationType();
+      TypeElement annotationTypeElement = (TypeElement) annotationType.asElement();
+
+      if (annotationTypeElement.getQualifiedName().contentEquals(name)) {
+        return annotationMirror;
+      }
+    }
+
+    return null;
+  }
+
+  @Nullable
+  private static Object findAnnotationValue(AnnotationMirror annotation, String name) {
+    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
+        annotation.getElementValues().entrySet()) {
+      if (entry.getKey().getSimpleName().contentEquals(name)) {
+        return entry.getValue().getValue();
+      }
+    }
+
+    return null;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/BUCK
@@ -0,0 +1,33 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "plugin",
+    srcs = glob(["*.java"]),
+    resources = [
+        ":javac-plugin",
+    ],
+    # This is required to ensure javac-plugin is placed in the same package as the code, i.e. com.facebook.buck.jvm.java.plugin
+    resources_root = "../../../../../..",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/api:api",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
+
+buck_java_binary(
+    name = "javac-plugin",
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source:source",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter:adapter",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/PluginLoader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/PluginLoader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/PluginLoader.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin;
+
+import com.facebook.buck.jvm.java.plugin.api.PluginClassLoader;
+import com.facebook.buck.jvm.java.plugin.api.PluginClassLoaderFactory;
+import com.facebook.buck.util.ClassLoaderCache;
+import com.google.common.collect.ImmutableList;
+import com.google.common.io.ByteStreams;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URL;
+import javax.annotation.Nullable;
+import javax.tools.JavaCompiler;
+
+/**
+ * Loads the Buck javac plugin JAR using the {@link ClassLoader} of a particular compiler instance.
+ *
+ * <p>{@link com.sun.source.tree} and {@link com.sun.source.util} packages are public APIs whose
+ * implementation is packaged with javac rather than in the Java runtime jar. Code that needs to
+ * work with these must be loaded using the same {@link ClassLoader} as the instance of javac with
+ * which it will be working.
+ */
+public final class PluginLoader implements PluginClassLoader {
+  private static final String JAVAC_PLUGIN_JAR_RESOURCE_PATH = "javac-plugin.jar";
+  private static final URL JAVAC_PLUGIN_JAR_URL = extractJavacPluginJar();
+
+  private final ClassLoader classLoader;
+
+  /**
+   * Extracts the jar containing the Buck javac plugin and returns a URL that can be given to a
+   * {@link java.net.URLClassLoader} to load it.
+   */
+  private static URL extractJavacPluginJar() {
+    @Nullable URL resourceURL = PluginLoader.class.getResource(JAVAC_PLUGIN_JAR_RESOURCE_PATH);
+    if (resourceURL == null) {
+      throw new RuntimeException("Could not find javac plugin jar; Buck may be corrupted.");
+    } else if ("file".equals(resourceURL.getProtocol())) {
+      // When Buck is running from the repo, the jar is actually already on disk, so no extraction
+      // is necessary
+      return resourceURL;
+    } else {
+      // Running from a .pex file, extraction is required
+      try (InputStream resourceStream =
+          PluginLoader.class.getResourceAsStream(JAVAC_PLUGIN_JAR_RESOURCE_PATH)) {
+        File tempFile = File.createTempFile("javac-plugin", ".jar");
+        tempFile.deleteOnExit();
+        try (OutputStream tempFileStream = new FileOutputStream(tempFile)) {
+          ByteStreams.copy(resourceStream, tempFileStream);
+          return tempFile.toURI().toURL();
+        }
+      } catch (IOException e) {
+        throw new RuntimeException("Failed to extract javac plugin jar; cannot continue", e);
+      }
+    }
+  }
+
+  /** Returns a class loader that can be used to load classes from the compiler plugin jar. */
+  public static ClassLoader getPluginClassLoader(
+      ClassLoaderCache classLoaderCache, JavaCompiler.CompilationTask compiler) {
+    ClassLoader compilerClassLoader = compiler.getClass().getClassLoader();
+    return classLoaderCache.getClassLoaderForClassPath(
+        compilerClassLoader, ImmutableList.of(JAVAC_PLUGIN_JAR_URL));
+  }
+
+  public static PluginLoader newInstance(
+      ClassLoaderCache classLoaderCache, JavaCompiler.CompilationTask compiler) {
+    return new PluginLoader(getPluginClassLoader(classLoaderCache, compiler));
+  }
+
+  public static PluginClassLoaderFactory newFactory(ClassLoaderCache cache) {
+    return task -> PluginLoader.newInstance(cache, task);
+  }
+
+  private PluginLoader(ClassLoader classLoader) {
+    this.classLoader = classLoader;
+  }
+
+  @Override
+  public <T> Class<? extends T> loadClass(String name, Class<T> superclass) {
+    if (classLoader == null) {
+      // No log here because we logged when the plugin itself failed to load
+      return null;
+    }
+
+    try {
+      return Class.forName(name, false, classLoader).asSubclass(superclass);
+    } catch (ClassNotFoundException e) {
+      throw new RuntimeException(String.format("Failed loading %s", name), e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BUCK
@@ -0,0 +1,31 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "adapter",
+    # We use conditional compilation to support building against both Java 8 and 11, despite
+    # breaking interface changes in the JDK.
+    srcs = glob(["*.java"]),
+    provided_deps = [
+        # api modules are included in the bootstrapper at runtime, so we don't need direct deps on them
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/api:api",
+    ],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source:source",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin:javac-plugin",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi/source:",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/plugin/adapter:",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/testutil/compiler:compiler",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/version/utils:utils",
+        # This module is loaded as a plugin into the compiler itself; don't take dependencies on Buck
+        # internals or large libraries like Guava
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/lang/model:model",
+        "prelude//toolchains/android/src/com/facebook/buck/util/liteinfersupport:liteinfersupport",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BridgeMethods.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BridgeMethods.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BridgeMethods.java
@@ -0,0 +1,210 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.facebook.buck.jvm.java.lang.model.BridgeMethod;
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import com.facebook.buck.jvm.java.lang.model.MoreElements;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.ExecutableType;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.ElementFilter;
+import javax.lang.model.util.Types;
+
+public class BridgeMethods {
+  private final Map<TypeElement, List<BridgeMethod>> allBridgeMethods = new HashMap<>();
+  private final Map<TypeElement, Map<Name, List<BridgeMethod>>> bridgeMethodsByName =
+      new HashMap<>();
+  private final ElementsExtended elements;
+  private final Types types;
+
+  public BridgeMethods(ElementsExtended elements, Types types) {
+    this.elements = elements;
+    this.types = types;
+  }
+
+  public List<BridgeMethod> getBridgeMethods(TypeElement typeElement) {
+    List<BridgeMethod> result = allBridgeMethods.get(typeElement);
+    if (result != null) {
+      return result;
+    }
+    result = calculateBridgeMethods(typeElement);
+    allBridgeMethods.put(typeElement, result);
+    return result;
+  }
+
+  public List<BridgeMethod> getBridgeMethods(TypeElement typeElement, Name name) {
+    return bridgeMethodsByName
+        .computeIfAbsent(typeElement, this::calculateBridgeMethodsByName)
+        .getOrDefault(name, Collections.emptyList());
+  }
+
+  public List<BridgeMethod> getBridgeMethodsNoCreate(TypeElement typeElement, Name name) {
+    if (allBridgeMethods.containsKey(typeElement)) {
+      return getBridgeMethods(typeElement, name);
+    }
+
+    return Collections.emptyList();
+  }
+
+  private Map<Name, List<BridgeMethod>> calculateBridgeMethodsByName(TypeElement inType) {
+    Map<Name, List<BridgeMethod>> result = new HashMap<>();
+
+    for (BridgeMethod bridgeMethod : getBridgeMethods(inType)) {
+      result
+          .computeIfAbsent(bridgeMethod.from.getSimpleName(), name -> new ArrayList<>())
+          .add(bridgeMethod);
+    }
+
+    return result;
+  }
+
+  private List<BridgeMethod> calculateBridgeMethods(TypeElement inType) {
+    List<TypeElement> supertypes =
+        MoreElements.getTransitiveSuperclasses(inType).collect(Collectors.toList());
+
+    for (int i = supertypes.size() - 1; i >= 0; i--) {
+      TypeElement supertype = supertypes.get(i);
+      if (!MoreElements.isTransitiveMemberClass(inType, supertype)) {
+        allBridgeMethods.computeIfAbsent(
+            supertype, it -> new BridgeMethodsFinder(it).findBridges());
+      }
+    }
+
+    return new BridgeMethodsFinder(inType).findBridges();
+  }
+
+  private class BridgeMethodsFinder {
+    private final TypeElement subclass;
+    private final List<BridgeMethod> bridgesNeeded = new ArrayList<>();
+
+    private BridgeMethodsFinder(TypeElement subclass) {
+      this.subclass = subclass;
+    }
+
+    public List<BridgeMethod> findBridges() {
+      MoreElements.getTransitiveSuperclasses(subclass).forEach(this::findBridges);
+      MoreElements.getInterfaces(subclass).forEach(this::findBridges);
+      return bridgesNeeded;
+    }
+
+    private void findBridges(TypeElement supertype) {
+      findBridgesToType(supertype);
+      MoreElements.getInterfaces(supertype).forEach(this::findBridges);
+    }
+
+    private void findBridgesToType(TypeElement supertype) {
+      if (supertype == subclass) {
+        return;
+      }
+
+      List<ExecutableElement> supertypeMethods =
+          new ArrayList<>(ElementFilter.methodsIn(supertype.getEnclosedElements()));
+      // For whatever reason, the members field in the compiler is reversed
+      Collections.reverse(supertypeMethods);
+      for (ExecutableElement supertypeMethod : supertypeMethods) {
+        if (supertypeMethod.getModifiers().contains(Modifier.PRIVATE)
+            || supertypeMethod.getModifiers().contains(Modifier.STATIC)
+            || supertypeMethod.getModifiers().contains(Modifier.FINAL)
+            || isHiddenInType(supertypeMethod, subclass)) {
+          continue;
+        }
+
+        ExecutableElement languageResolvedMethod =
+            elements.getImplementation(supertypeMethod, subclass);
+        TypeElement vmResolvedMethodOwner =
+            elements.getBinaryImplementationOwner(supertypeMethod, subclass);
+
+        if (vmResolvedMethodOwner == null
+            || vmResolvedMethodOwner == supertypeMethod.getEnclosingElement()
+            || (languageResolvedMethod != null
+                && !types.isSubtype(
+                    types.erasure(vmResolvedMethodOwner.asType()),
+                    types.erasure(languageResolvedMethod.getEnclosingElement().asType())))) {
+          if (languageResolvedMethod != null
+              && isBridgeNeeded(supertypeMethod, languageResolvedMethod, subclass)) {
+            if (languageResolvedMethod.getEnclosingElement() != vmResolvedMethodOwner) {
+              bridgesNeeded.add(new BridgeMethod(languageResolvedMethod, supertypeMethod));
+            }
+            // There's a comment in the compiler source about there being a design flaw in
+            // Reflection
+            // that requires bridge methods to be created if a public class inherits a public method
+            // from a non-public supertype.
+          } else if (languageResolvedMethod == supertypeMethod
+              && languageResolvedMethod.getEnclosingElement() != subclass
+              && !languageResolvedMethod.getModifiers().contains(Modifier.FINAL)
+              && !supertypeMethod.getModifiers().contains(Modifier.ABSTRACT)
+              && !supertypeMethod.getModifiers().contains(Modifier.DEFAULT)
+              && supertypeMethod.getModifiers().contains(Modifier.PUBLIC)
+              && subclass.getModifiers().contains(Modifier.PUBLIC)
+              && !languageResolvedMethod
+                  .getEnclosingElement()
+                  .getModifiers()
+                  .contains(Modifier.PUBLIC)) {
+            bridgesNeeded.add(new BridgeMethod(supertypeMethod, supertypeMethod));
+          }
+        }
+      }
+    }
+
+    private boolean isBridgeNeeded(
+        ExecutableElement method, ExecutableElement languageImplementation, TypeElement inType) {
+      if (method != languageImplementation) {
+        ExecutableType methodErasure = (ExecutableType) types.erasure(method.asType());
+        if (!isSameMemberWhenErased(inType, method, methodErasure)) {
+          return true;
+        }
+
+        ExecutableType languageImplementationErasure =
+            (ExecutableType) types.erasure(languageImplementation.asType());
+        if (!isSameMemberWhenErased(
+            inType, languageImplementation, languageImplementationErasure)) {
+          return true;
+        }
+
+        return !types.isSameType(
+            methodErasure.getReturnType(), languageImplementationErasure.getReturnType());
+      } else if (!method.getModifiers().contains(Modifier.ABSTRACT)
+          && !method.getModifiers().contains(Modifier.DEFAULT)) {
+        return !isSameMemberWhenErased(inType, method, types.erasure(method.asType()));
+      }
+
+      return false;
+    }
+
+    private boolean isSameMemberWhenErased(
+        TypeElement inType, ExecutableElement method, TypeMirror erasedType) {
+      return types.isSameType(
+          types.erasure(types.asMemberOf((DeclaredType) inType.asType(), method)), erasedType);
+    }
+
+    private boolean isHiddenInType(ExecutableElement hidden, TypeElement subclass) {
+      for (TypeElement type = subclass; type != null; type = MoreElements.getSuperclass(type)) {
+        for (ExecutableElement hider : elements.getDeclaredMethods(type, hidden.getSimpleName())) {
+          if (elements.hides(hider, hidden)) {
+            return true;
+          }
+        }
+      }
+      return false;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacPlugin.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacPlugin.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacPlugin.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+/**
+ * Analogue to javac 8's {@link com.sun.source.util.Plugin} class for use within Buck, even on older
+ * versions of javac.
+ */
+public interface BuckJavacPlugin {
+  String getName();
+
+  void init(BuckJavacTask task, String... args);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTask.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTask.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTask.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.util.JavacTask;
+import com.sun.source.util.TaskEvent;
+import com.sun.source.util.TaskListener;
+import com.sun.source.util.Trees;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import javax.lang.model.element.Element;
+import javax.lang.model.util.Elements;
+
+/**
+ * Extends {@link JavacTask} with functionality that is useful for Buck:
+ *
+ * <ul>
+ *   <li>Exposes the enter method from JavacTaskImpl
+ *   <li>Pre-javac-8 support for addTaskListener/removeTaskListener
+ *   <li>Wraps {@link Elements} with some extended functionality
+ * </ul>
+ */
+public class BuckJavacTask extends JavacTaskWrapper {
+  private final Map<BuckJavacPlugin, String[]> pluginsAndArgs = new LinkedHashMap<>();
+  private final MultiplexingTaskListener taskListeners = new MultiplexingTaskListener();
+  private final PostEnterTaskListener postEnterTaskListener;
+  private final List<Consumer<Set<Element>>> postEnterCallbacks = new ArrayList<>();
+
+  private boolean pluginsInstalled = false;
+
+  @Nullable private TaskListener singleTaskListener;
+  @Nullable private ElementsExtended elements;
+
+  public BuckJavacTask(JavacTask inner) {
+    super(inner);
+    if (inner instanceof BuckJavacTask) {
+      throw new IllegalArgumentException();
+    }
+
+    inner.setTaskListener(
+        new TaskListener() {
+          @Override
+          public void started(TaskEvent e) {
+            BuckJavacTask.this.started(e);
+          }
+
+          @Override
+          public void finished(TaskEvent e) {
+            BuckJavacTask.this.finished(e);
+          }
+        });
+
+    postEnterTaskListener = new PostEnterTaskListener(this, this::onPostEnter);
+  }
+
+  public Iterable<? extends Element> enter() throws IOException {
+    try {
+      @SuppressWarnings("unchecked")
+      Iterable<? extends Element> result =
+          (Iterable<? extends Element>) inner.getClass().getMethod("enter").invoke(inner);
+      return result;
+    } catch (IllegalAccessException | NoSuchMethodException e) {
+      throw new RuntimeException(e);
+    } catch (InvocationTargetException e) {
+      if (e.getCause() instanceof IOException) {
+        throw (IOException) e.getCause();
+      } else if (e.getCause() instanceof RuntimeException) {
+        throw (RuntimeException) e.getCause();
+      } else if (e.getCause() instanceof Error) {
+        throw (Error) e.getCause();
+      }
+
+      throw new RuntimeException(e);
+    }
+  }
+
+  /**
+   * Sets a {@link TaskListener}. Like {@link JavacTask}'s implementation of this method, the
+   * listener does not replace listeners added with {@link #addTaskListener(TaskListener)}. Instead,
+   * it replaces only the listener provided in the previous call to this method, if any.
+   *
+   * <p>Presumably this behavior was to enable {@link com.sun.source.util.Plugin}s to work properly
+   * with build systems that were written when only a single {@link TaskListener} was supported at a
+   * time.
+   */
+  @Override
+  public void setTaskListener(@Nullable TaskListener taskListener) {
+    if (singleTaskListener != null) {
+      removeTaskListener(singleTaskListener);
+    }
+    singleTaskListener = taskListener;
+    if (singleTaskListener != null) {
+      addTaskListener(singleTaskListener);
+    }
+  }
+
+  @Override
+  public void addTaskListener(TaskListener taskListener) {
+    taskListeners.addListener(taskListener);
+  }
+
+  @Override
+  public void removeTaskListener(TaskListener taskListener) {
+    taskListeners.removeListener(taskListener);
+  }
+
+  @Override
+  public ElementsExtended getElements() {
+    if (elements == null) {
+      elements = new ElementsExtendedImpl(super.getElements(), getTypes(), getTrees());
+    }
+    return elements;
+  }
+
+  public void addPlugin(BuckJavacPlugin plugin, String... args) {
+    pluginsAndArgs.put(plugin, args);
+  }
+
+  public void addPostEnterCallback(Consumer<Set<Element>> callback) {
+    postEnterCallbacks.add(callback);
+  }
+
+  public Trees getTrees() {
+    return Trees.instance(inner);
+  }
+
+  protected void started(TaskEvent e) {
+    // Initialize plugins just before sending the first event to registered listeners. We do it
+    // this way (rather than initializing plugins just before starting to run the task) because
+    // most plugins will call methods like getElements, which in javac 7 are not safe to call
+    // before the task is actually running.
+    installPlugins();
+
+    taskListeners.started(e);
+    postEnterTaskListener.started(e);
+  }
+
+  protected void finished(TaskEvent e) {
+    taskListeners.finished(e);
+    postEnterTaskListener.finished(e);
+  }
+
+  protected void onPostEnter(Set<Element> topLevelElements) {
+    postEnterCallbacks.forEach(callback -> callback.accept(topLevelElements));
+  }
+
+  private void installPlugins() {
+    if (pluginsInstalled) {
+      return;
+    }
+
+    for (Map.Entry<BuckJavacPlugin, String[]> pluginAndArgs : pluginsAndArgs.entrySet()) {
+      pluginAndArgs.getKey().init(BuckJavacTask.this, pluginAndArgs.getValue());
+    }
+
+    pluginsAndArgs.clear();
+    pluginsInstalled = true;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTaskListenerProxy.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTaskListenerProxy.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTaskListenerProxy.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.facebook.buck.jvm.java.plugin.api.BuckJavacTaskListener;
+import com.facebook.buck.jvm.java.plugin.api.CompilationUnitTreeProxy;
+import com.facebook.buck.jvm.java.plugin.api.TaskEventMirror;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.util.TaskEvent;
+import com.sun.source.util.TaskListener;
+
+/**
+ * Implements {@link TaskListener} by proxying calls to an inner {@link BuckJavacTaskListener}. This
+ * is the bridge that allows us to implement {@link TaskListener}s in Buck itself.
+ */
+public class BuckJavacTaskListenerProxy implements TaskListener {
+  private final BuckJavacTaskListener buckSideListener;
+
+  public BuckJavacTaskListenerProxy(BuckJavacTaskListener buckSideListener) {
+    if (buckSideListener instanceof TaskListenerProxy) {
+      throw new IllegalArgumentException(
+          "taskListener is a proxy, unwrap it rather than creating another proxy");
+    }
+    this.buckSideListener = buckSideListener;
+  }
+
+  @Override
+  public void started(TaskEvent e) {
+    this.buckSideListener.started(mirrorTaskEvent(e));
+  }
+
+  @Override
+  public void finished(TaskEvent e) {
+    this.buckSideListener.finished(mirrorTaskEvent(e));
+  }
+
+  private TaskEventMirror mirrorTaskEvent(TaskEvent e) {
+    return new TaskEventMirror(
+        e,
+        mirrorKind(e.getKind()),
+        e.getSourceFile(),
+        proxyCompilationUnit(e.getCompilationUnit()),
+        e.getTypeElement());
+  }
+
+  private TaskEventMirror.Kind mirrorKind(TaskEvent.Kind kind) {
+    return TaskEventMirror.Kind.valueOf(kind.name());
+  }
+
+  @Nullable
+  private CompilationUnitTreeProxy proxyCompilationUnit(@Nullable CompilationUnitTree tree) {
+    if (tree == null) {
+      return null;
+    }
+
+    return new CompilationUnitTreeProxyImpl(tree);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTaskProxyImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTaskProxyImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/BuckJavacTaskProxyImpl.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import com.facebook.buck.jvm.java.plugin.api.BuckJavacTaskListener;
+import com.facebook.buck.jvm.java.plugin.api.BuckJavacTaskProxy;
+import com.facebook.buck.jvm.java.plugin.api.CompilationUnitTreeProxy;
+import com.sun.source.util.JavacTask;
+import com.sun.source.util.TaskListener;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+import javax.annotation.processing.Messager;
+import javax.annotation.processing.Processor;
+import javax.lang.model.element.Element;
+import javax.lang.model.util.Types;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+
+/**
+ * NOTE: A Java8 copy of this file exists in ../java8/BuckJavacTaskProxyImpl.java. Please make sure
+ * to update the other copy when modifying this file.
+ */
+public class BuckJavacTaskProxyImpl implements BuckJavacTaskProxy {
+  private final BuckJavacTask javacTask;
+
+  public BuckJavacTaskProxyImpl(JavaCompiler.CompilationTask javacTask) {
+    this.javacTask = new BuckJavacTask((JavacTask) javacTask);
+  }
+
+  public BuckJavacTaskProxyImpl(BuckJavacTask javacTask) {
+    this.javacTask = javacTask;
+  }
+
+  public BuckJavacTask getInner() {
+    return javacTask;
+  }
+
+  @Override
+  public Iterable<CompilationUnitTreeProxy> parse() throws IOException {
+    return StreamSupport.stream(javacTask.parse().spliterator(), false)
+        .map(CompilationUnitTreeProxyImpl::new)
+        .collect(Collectors.toList());
+  }
+
+  @Override
+  public Iterable<? extends Element> enter() throws IOException {
+    return javacTask.enter();
+  }
+
+  @Override
+  public Iterable<? extends Element> analyze() throws IOException {
+    return javacTask.analyze();
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> generate() throws IOException {
+    return javacTask.generate();
+  }
+
+  @Override
+  public void setTaskListener(BuckJavacTaskListener buckTaskListener) {
+    javacTask.setTaskListener(getTaskListener(buckTaskListener));
+  }
+
+  @Override
+  public void addTaskListener(BuckJavacTaskListener buckTaskListener) {
+    javacTask.addTaskListener(getTaskListener(buckTaskListener));
+  }
+
+  @Override
+  public void removeTaskListener(BuckJavacTaskListener buckTaskListener) {
+    javacTask.removeTaskListener(getTaskListener(buckTaskListener));
+  }
+
+  private TaskListener getTaskListener(BuckJavacTaskListener taskListener) {
+    if (taskListener instanceof TaskListenerProxy) {
+      return ((TaskListenerProxy) taskListener).getInner();
+    }
+
+    return new BuckJavacTaskListenerProxy(taskListener);
+  }
+
+  @Override
+  public void addPostEnterCallback(Consumer<Set<Element>> callback) {
+    javacTask.addPostEnterCallback(callback);
+  }
+
+  @Override
+  public ElementsExtended getElements() {
+    return javacTask.getElements();
+  }
+
+  @Override
+  public Types getTypes() {
+    return javacTask.getTypes();
+  }
+
+  @Override
+  public Messager getMessager() {
+    return new TreesMessager(javacTask.getTrees());
+  }
+
+  @Override
+  public void setProcessors(Iterable<? extends Processor> processors) {
+    javacTask.setProcessors(processors);
+  }
+
+  @Override
+  public void setLocale(Locale locale) {
+    javacTask.setLocale(locale);
+  }
+
+  @Override
+  public Boolean call() {
+    return javacTask.call();
+  }
+
+  @Override
+  public void addModules(Iterable<String> moduleNames) {
+    javacTask.addModules(moduleNames);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/CompilationUnitTreeProxyImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/CompilationUnitTreeProxyImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/CompilationUnitTreeProxyImpl.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.facebook.buck.jvm.java.plugin.api.CompilationUnitTreeProxy;
+import com.sun.source.tree.CompilationUnitTree;
+
+public class CompilationUnitTreeProxyImpl implements CompilationUnitTreeProxy {
+  private final CompilationUnitTree compilationUnitTree;
+
+  public CompilationUnitTreeProxyImpl(CompilationUnitTree compilationUnitTree) {
+    this.compilationUnitTree = compilationUnitTree;
+  }
+
+  public CompilationUnitTree getCompilationUnit() {
+    return compilationUnitTree;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/DelegatingElements.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/DelegatingElements.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/DelegatingElements.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import java.io.Writer;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.ModuleElement;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.Elements;
+
+/** Delegates all method calls to an inner instance of {@link Elements}. */
+class DelegatingElements implements Elements {
+  private final Elements inner;
+
+  public DelegatingElements(Elements inner) {
+    this.inner = inner;
+  }
+
+  @Override
+  @Nullable
+  public PackageElement getPackageElement(CharSequence name) {
+    return inner.getPackageElement(name);
+  }
+
+  @Override
+  @Nullable
+  public PackageElement getPackageElement(ModuleElement module, CharSequence name) {
+    return inner.getPackageElement(module, name);
+  }
+
+  @Override
+  public Set<? extends PackageElement> getAllPackageElements(CharSequence name) {
+    return inner.getAllPackageElements(name);
+  }
+
+  @Override
+  @Nullable
+  public TypeElement getTypeElement(CharSequence name) {
+    return inner.getTypeElement(name);
+  }
+
+  @Override
+  @Nullable
+  public ModuleElement getModuleElement(CharSequence name) {
+    return inner.getModuleElement(name);
+  }
+
+  @Override
+  public Set<? extends ModuleElement> getAllModuleElements() {
+    return inner.getAllModuleElements();
+  }
+
+  @Override
+  public Map<? extends ExecutableElement, ? extends AnnotationValue> getElementValuesWithDefaults(
+      AnnotationMirror a) {
+    return inner.getElementValuesWithDefaults(a);
+  }
+
+  @Override
+  @Nullable
+  public String getDocComment(Element e) {
+    return inner.getDocComment(e);
+  }
+
+  @Override
+  public boolean isDeprecated(Element e) {
+    return inner.isDeprecated(e);
+  }
+
+  @Override
+  public Name getBinaryName(TypeElement type) {
+    return inner.getBinaryName(type);
+  }
+
+  @Override
+  public PackageElement getPackageOf(Element type) {
+    return inner.getPackageOf(type);
+  }
+
+  @Override
+  public List<? extends Element> getAllMembers(TypeElement type) {
+    return inner.getAllMembers(type);
+  }
+
+  @Override
+  public List<? extends AnnotationMirror> getAllAnnotationMirrors(Element e) {
+    return inner.getAllAnnotationMirrors(e);
+  }
+
+  @Override
+  public boolean hides(Element hider, Element hidden) {
+    return inner.hides(hider, hidden);
+  }
+
+  @Override
+  public boolean overrides(
+      ExecutableElement overrider, ExecutableElement overridden, TypeElement type) {
+    return inner.overrides(overrider, overridden, type);
+  }
+
+  @Override
+  public String getConstantExpression(Object value) {
+    return inner.getConstantExpression(value);
+  }
+
+  @Override
+  public void printElements(Writer w, Element... elements) {
+    inner.printElements(w, elements);
+  }
+
+  @Override
+  public Name getName(CharSequence cs) {
+    return inner.getName(cs);
+  }
+
+  @Override
+  public boolean isFunctionalInterface(TypeElement type) {
+    return inner.isFunctionalInterface(type);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/ElementsExtendedImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/ElementsExtendedImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/ElementsExtendedImpl.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.facebook.buck.jvm.java.lang.model.BridgeMethod;
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import com.facebook.buck.jvm.java.lang.model.MoreAnnotations;
+import com.facebook.buck.jvm.java.lang.model.MoreElements;
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import com.sun.source.util.Trees;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Function;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.ElementFilter;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.Types;
+
+/**
+ * Wraps and extends {@link javax.lang.model.util.Elements} with methods that cannot be added as
+ * pure extension methods on {@link MoreElements} because they require per-instance state.
+ */
+public class ElementsExtendedImpl extends DelegatingElements implements ElementsExtended {
+
+  private final Map<TypeElement, Map<Name, List<ExecutableElement>>> declaredMethodsMaps =
+      new HashMap<>();
+  private final Map<TypeElement, Map<Name, List<ExecutableElement>>> allMethodsMaps =
+      new HashMap<>();
+  private final BridgeMethods bridgeMethods;
+  private final Types types;
+  private final Trees trees;
+
+  public ElementsExtendedImpl(Elements inner, Types types, Trees trees) {
+    super(inner);
+    this.types = types;
+    this.trees = trees;
+
+    bridgeMethods = new BridgeMethods(this, types);
+  }
+
+  @Override
+  public List<ExecutableElement> getDeclaredMethods(TypeElement owner, CharSequence name) {
+    return getMethods(owner, name, declaredMethodsMaps, Element::getEnclosedElements);
+  }
+
+  @Override
+  public List<ExecutableElement> getAllMethods(TypeElement owner, CharSequence name) {
+    return getMethods(owner, name, allMethodsMaps, this::getAllMembers);
+  }
+
+  @Override
+  public List<BridgeMethod> getBridgeMethods(TypeElement owner, CharSequence name) {
+    return bridgeMethods.getBridgeMethods(owner, getName(name));
+  }
+
+  @Override
+  @Nullable
+  public ExecutableElement getImplementation(ExecutableElement baseMethod, TypeElement inType) {
+    ExecutableElement result = null;
+    for (ExecutableElement candidate : getAllMethods(inType, baseMethod.getSimpleName())) {
+      Element enclosingElement = candidate.getEnclosingElement();
+      if (enclosingElement != inType && enclosingElement.getKind().isInterface()) {
+        continue;
+      }
+
+      if (overrides(candidate, baseMethod, inType) || (result == null && candidate == baseMethod)) {
+        result = candidate;
+      }
+    }
+    return result;
+  }
+
+  @Nullable
+  @Override
+  public TypeElement getBinaryImplementationOwner(ExecutableElement method, TypeElement inType) {
+    TypeElement implementationOwner = null;
+    ExecutableElement implementation = getImplementation(method, inType);
+    if (implementation != null && binarySignaturesMatch(implementation, method)) {
+      implementationOwner = (TypeElement) implementation.getEnclosingElement();
+    }
+
+    for (TypeElement type = inType; type != null; type = MoreElements.getSuperclass(type)) {
+      if (implementationOwner != null
+          && !types.isSubtype(
+              types.erasure(type.asType()), types.erasure(implementationOwner.asType()))) {
+        break;
+      }
+
+      Name name = method.getSimpleName();
+      List<BridgeMethod> bridgeMethods = this.bridgeMethods.getBridgeMethodsNoCreate(type, name);
+
+      Optional<ExecutableElement> result =
+          bridgeMethods.stream()
+              .map(it -> it.to)
+              .filter(it -> binarySignaturesMatch(it, method))
+              .findFirst();
+      if (result.isPresent()) {
+        implementationOwner = type;
+        break;
+      }
+    }
+
+    return implementationOwner;
+  }
+
+  private boolean binarySignaturesMatch(ExecutableElement e1, ExecutableElement e2) {
+    return types.isSameType(types.erasure(e1.asType()), types.erasure(e2.asType()))
+        && types.isSameType(types.erasure(e1.getReturnType()), types.erasure(e2.getReturnType()));
+  }
+
+  @Override
+  public List<BridgeMethod> getAllBridgeMethods(TypeElement type) {
+    return bridgeMethods.getBridgeMethods(type);
+  }
+
+  private List<ExecutableElement> getMethods(
+      TypeElement owner,
+      CharSequence name,
+      Map<TypeElement, Map<Name, List<ExecutableElement>>> methodsMaps,
+      Function<? super TypeElement, List<? extends Element>> getMembersFn) {
+    Map<Name, List<ExecutableElement>> methodsMap =
+        methodsMaps.computeIfAbsent(owner, el -> buildMethodsMap(el, getMembersFn));
+
+    List<ExecutableElement> result = methodsMap.get(getName(name));
+    if (result == null) {
+      result = Collections.emptyList();
+    }
+    return result;
+  }
+
+  @Override
+  public boolean isCompiledInCurrentRun(Element element) {
+    return trees.getTree(element) != null;
+  }
+
+  @Override
+  public List<? extends AnnotationMirror> getAllTypeAnnotations(Element element) {
+    return MoreAnnotations.getAllTypeAnnotations(element);
+  }
+
+  private static Map<Name, List<ExecutableElement>> buildMethodsMap(
+      TypeElement owner, Function<? super TypeElement, List<? extends Element>> getMembersFn) {
+    Map<Name, List<ExecutableElement>> result = new HashMap<>();
+
+    for (ExecutableElement method : ElementFilter.methodsIn(getMembersFn.apply(owner))) {
+      List<ExecutableElement> methodsWithName =
+          result.computeIfAbsent(method.getSimpleName(), ignored -> new ArrayList<>());
+      methodsWithName.add(method);
+    }
+
+    return result;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/JavacTaskWrapper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/JavacTaskWrapper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/JavacTaskWrapper.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.util.JavacTask;
+import com.sun.source.util.TaskListener;
+import java.io.IOException;
+import java.util.Locale;
+import javax.annotation.processing.Processor;
+import javax.lang.model.element.Element;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.Types;
+import javax.tools.JavaFileObject;
+
+/**
+ * NOTE: A Java8 copy of this file exists in ../java8/JavacTaskWrapper.java. Please make sure to
+ * update the other copy when modifying this file.
+ */
+abstract class JavacTaskWrapper extends JavacTask {
+  protected final JavacTask inner;
+
+  public JavacTaskWrapper(JavacTask inner) {
+    this.inner = inner;
+  }
+
+  @Override
+  public Iterable<? extends CompilationUnitTree> parse() throws IOException {
+    return inner.parse();
+  }
+
+  @Override
+  public Iterable<? extends Element> analyze() throws IOException {
+    return inner.analyze();
+  }
+
+  @Override
+  public Iterable<? extends JavaFileObject> generate() throws IOException {
+    return inner.generate();
+  }
+
+  @Override
+  public void setTaskListener(TaskListener taskListener) {
+    inner.setTaskListener(taskListener);
+  }
+
+  @Override
+  public void addTaskListener(TaskListener taskListener) {
+    inner.addTaskListener(taskListener);
+  }
+
+  @Override
+  public void removeTaskListener(TaskListener taskListener) {
+    inner.removeTaskListener(taskListener);
+  }
+
+  @Override
+  public TypeMirror getTypeMirror(Iterable<? extends Tree> path) {
+    return inner.getTypeMirror(path);
+  }
+
+  @Override
+  public Elements getElements() {
+    return inner.getElements();
+  }
+
+  @Override
+  public Types getTypes() {
+    return inner.getTypes();
+  }
+
+  @Override
+  public void setProcessors(Iterable<? extends Processor> processors) {
+    inner.setProcessors(processors);
+  }
+
+  @Override
+  public void setLocale(Locale locale) {
+    inner.setLocale(locale);
+  }
+
+  @Override
+  public Boolean call() {
+    return inner.call();
+  }
+
+  @Override
+  public void addModules(Iterable<String> moduleNames) {
+    inner.addModules(moduleNames);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/MultiplexingTaskListener.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/MultiplexingTaskListener.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/MultiplexingTaskListener.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.sun.source.util.TaskEvent;
+import com.sun.source.util.TaskListener;
+import java.util.concurrent.CopyOnWriteArraySet;
+
+/**
+ * Multiplexes messages to several other task listeners. Messages are dispatched to listeners in the
+ * order in which the listeners were registered.
+ */
+class MultiplexingTaskListener implements TaskListener {
+  private final CopyOnWriteArraySet<TaskListener> listeners = new CopyOnWriteArraySet<>();
+
+  public void addListener(TaskListener listener) {
+    listeners.add(listener);
+  }
+
+  public void removeListener(TaskListener listener) {
+    listeners.remove(listener);
+  }
+
+  @Override
+  public void started(TaskEvent e) {
+    for (TaskListener listener : listeners) {
+      listener.started(e);
+    }
+  }
+
+  @Override
+  public void finished(TaskEvent e) {
+    for (TaskListener listener : listeners) {
+      listener.finished(e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/PostEnterTaskListener.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/PostEnterTaskListener.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/PostEnterTaskListener.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.sun.source.tree.ClassTree;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.util.TaskEvent;
+import com.sun.source.util.TaskListener;
+import com.sun.source.util.TreePathScanner;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Consumer;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.Elements;
+import javax.tools.JavaFileObject;
+
+/** A {@link TaskListener} that runs some code after the final enter phase. */
+public class PostEnterTaskListener implements TaskListener {
+
+  private final BuckJavacTask task;
+  private final Consumer<Set<Element>> callback;
+  private final Set<Element> topLevelElements = new LinkedHashSet<>();
+
+  private boolean annotationProcessing = false;
+  private int pendingEnterCalls = 0;
+
+  public PostEnterTaskListener(BuckJavacTask task, Consumer<Set<Element>> callback) {
+    this.task = task;
+    this.callback = callback;
+  }
+
+  @Override
+  public void started(TaskEvent e) {
+    switch (e.getKind()) {
+      case ANNOTATION_PROCESSING:
+        // The raw event stream from javac will start with this event if there are any APs present
+        if (!topLevelElements.isEmpty()) {
+          // Though we can get multiple annotation processing rounds within the context of
+          // annotation processing, annotation processing at a high level shouldn't happen more than
+          // once.
+          throw new IllegalStateException("Annotation processing happened more than once");
+        }
+        annotationProcessing = true;
+        break;
+      case ENTER:
+        if (pendingEnterCalls == 0) {
+          // We may enter the tree multiple times as part of multiple annotation processing rounds.
+          // Make sure we grab the most up-to-date top level elements from the last time they are
+          // entered.
+          topLevelElements.clear();
+        }
+        pendingEnterCalls += 1;
+        break;
+      // $CASES-OMITTED$
+      default:
+        break;
+    }
+  }
+
+  @Override
+  public void finished(TaskEvent e) {
+    switch (e.getKind()) {
+      case ANNOTATION_PROCESSING:
+        annotationProcessing = false;
+        break;
+      case ENTER:
+        pendingEnterCalls -= 1;
+        CompilationUnitTree compilationUnit = e.getCompilationUnit();
+        new TreePathScanner<Void, Void>() {
+          @Override
+          public Void visitCompilationUnit(CompilationUnitTree node, Void aVoid) {
+            if (e.getSourceFile().isNameCompatible("package-info", JavaFileObject.Kind.SOURCE)) {
+              Elements elements = task.getElements();
+              Element packageElement =
+                  Objects.requireNonNull(
+                      elements.getPackageElement(node.getPackageName().toString()));
+              topLevelElements.add(packageElement);
+            }
+
+            // Technically getTypeDecls can also return some imports due to a bug in javac, but
+            // that's fine in this case because we'll just ignore them.
+            return scan(node.getTypeDecls(), null);
+          }
+
+          @Override
+          public Void visitClass(ClassTree node, Void aVoid) {
+            TypeElement typeElement = (TypeElement) task.getTrees().getElement(getCurrentPath());
+            topLevelElements.add(typeElement);
+            return null;
+          }
+        }.scan(compilationUnit, null);
+        break;
+      // $CASES-OMITTED$
+      default:
+        break;
+    }
+
+    // For source ABI generation, we want to short circuit the compiler as early as possible to reap
+    // the performance benefits. When annotation processing isn't involved, the last ENTER finished
+    // event, which comes before the ANALYZE and GENERATE phases, tells us the right time to do
+    // this. In Java 9+, the last set of ENTER events happen right *before* the
+    // ANNOTATION_PROCESSING finished event, so we have to rely on the ANNOTATION_PROCESSING
+    // finished event itself.
+    if ((e.getKind() == TaskEvent.Kind.ENTER && !annotationProcessing && pendingEnterCalls == 0)
+        || e.getKind() == TaskEvent.Kind.ANNOTATION_PROCESSING) {
+      Set<Element> unmodifiableTopLevelElements = Collections.unmodifiableSet(topLevelElements);
+      callback.accept(unmodifiableTopLevelElements);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TaskListenerProxy.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TaskListenerProxy.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TaskListenerProxy.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.facebook.buck.jvm.java.plugin.api.BuckJavacTaskListener;
+import com.facebook.buck.jvm.java.plugin.api.TaskEventMirror;
+import com.sun.source.util.TaskEvent;
+import com.sun.source.util.TaskListener;
+
+/**
+ * Implements {@link BuckJavacTaskListener} by proxying calls to an inner {@link TaskListener}. This
+ * is the bridge that allows Buck to call {@link TaskListener}s that are loaded in the compiler's
+ * {@link ClassLoader}.
+ */
+public class TaskListenerProxy implements BuckJavacTaskListener {
+  private final TaskListener taskListener;
+
+  public TaskListenerProxy(Object taskListener) {
+    if (taskListener instanceof BuckJavacTaskListenerProxy) {
+      throw new IllegalArgumentException(
+          "taskListener is a proxy, unwrap it rather than creating another proxy");
+    }
+    this.taskListener = (TaskListener) taskListener;
+  }
+
+  public TaskListener getInner() {
+    return taskListener;
+  }
+
+  @Override
+  public void started(TaskEventMirror e) {
+    taskListener.started(unmirror(e));
+  }
+
+  @Override
+  public void finished(TaskEventMirror e) {
+    taskListener.finished(unmirror(e));
+  }
+
+  private TaskEvent unmirror(TaskEventMirror mirror) {
+    return (TaskEvent) mirror.getOriginal();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TaskListenerWrapper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TaskListenerWrapper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TaskListenerWrapper.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.sun.source.util.TaskEvent;
+import com.sun.source.util.TaskListener;
+
+public class TaskListenerWrapper implements TaskListener {
+  private final TaskListener inner;
+
+  public TaskListenerWrapper(TaskListener inner) {
+    this.inner = inner;
+  }
+
+  @Override
+  public void started(TaskEvent e) {
+    if (inner != null) {
+      inner.started(e);
+    }
+  }
+
+  @Override
+  public void finished(TaskEvent e) {
+    if (inner != null) {
+      inner.finished(e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TreesMessager.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TreesMessager.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter/TreesMessager.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.adapter;
+
+import com.sun.source.util.TreePath;
+import com.sun.source.util.Trees;
+import java.util.Objects;
+import javax.annotation.processing.Messager;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.tools.Diagnostic;
+
+public class TreesMessager implements Messager {
+  private final Trees trees;
+
+  public TreesMessager(Trees trees) {
+    this.trees = trees;
+  }
+
+  @Override
+  public void printMessage(Diagnostic.Kind kind, CharSequence msg) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e) {
+    printMessage(kind, msg, Objects.requireNonNull(trees.getPath(e)));
+  }
+
+  @Override
+  public void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a) {
+    printMessage(kind, msg, Objects.requireNonNull(trees.getPath(e, a)));
+  }
+
+  @Override
+  public void printMessage(
+      Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a, AnnotationValue v) {
+    printMessage(kind, msg, Objects.requireNonNull(trees.getPath(e, a, v)));
+  }
+
+  private void printMessage(Diagnostic.Kind kind, CharSequence msg, TreePath path) {
+    trees.printMessage(kind, msg, path.getLeaf(), path.getCompilationUnit());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BUCK
@@ -0,0 +1,20 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "api",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/lang/model:model",
+        "prelude//toolchains/android/src/com/facebook/buck/util/liteinfersupport:liteinfersupport",
+        # Don't add deps that aren't already in the plugin; this is a super-light library that can be
+        # used outside of Buck
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BuckJavacTaskListener.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BuckJavacTaskListener.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BuckJavacTaskListener.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.api;
+
+/**
+ * Listens to events coming from the Java compiler. This is analogous to {@link
+ * com.sun.source.util.TaskListener}, but loads in Buck's {@link ClassLoader} instead of the
+ * compiler's.
+ */
+public interface BuckJavacTaskListener {
+  static BuckJavacTaskListener wrapRealTaskListener(PluginClassLoader loader, Object taskListener) {
+    Class<? extends BuckJavacTaskListener> taskListenerProxyClass =
+        loader.loadClass(
+            "com.facebook.buck.jvm.java.plugin.adapter.TaskListenerProxy",
+            BuckJavacTaskListener.class);
+
+    try {
+      return taskListenerProxyClass.getConstructor(Object.class).newInstance(taskListener);
+    } catch (ReflectiveOperationException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  void started(TaskEventMirror e);
+
+  void finished(TaskEventMirror e);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BuckJavacTaskProxy.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BuckJavacTaskProxy.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/BuckJavacTaskProxy.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.api;
+
+import com.facebook.buck.jvm.java.lang.model.ElementsExtended;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.Set;
+import java.util.function.Consumer;
+import javax.annotation.processing.Messager;
+import javax.lang.model.element.Element;
+import javax.lang.model.util.Types;
+import javax.tools.DiagnosticListener;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+
+/**
+ * {@link com.sun.source.util.JavacTask} is included with the compiler and is thus not directly
+ * accessible from within Buck's class loader. This interface is used as a proxy within Buck's class
+ * loader to allow access to commonly-used methods.
+ */
+public interface BuckJavacTaskProxy extends JavaCompiler.CompilationTask {
+  static BuckJavacTaskProxy getTask(
+      PluginClassLoaderFactory loaderFactory,
+      JavaCompiler compiler,
+      Writer out,
+      JavaFileManager fileManager,
+      DiagnosticListener<? super JavaFileObject> diagnosticListener,
+      Iterable<String> options,
+      Iterable<String> classes,
+      Iterable<? extends JavaFileObject> compilationUnits) {
+    JavaCompiler.CompilationTask task =
+        compiler.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits);
+
+    PluginClassLoader loader = loaderFactory.getPluginClassLoader(task);
+    Class<? extends BuckJavacTaskProxy> proxyImplClass =
+        loader.loadClass(
+            "com.facebook.buck.jvm.java.plugin.adapter.BuckJavacTaskProxyImpl",
+            BuckJavacTaskProxy.class);
+
+    try {
+      return proxyImplClass.getConstructor(JavaCompiler.CompilationTask.class).newInstance(task);
+    } catch (ReflectiveOperationException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  Iterable<CompilationUnitTreeProxy> parse() throws IOException;
+
+  Iterable<? extends Element> enter() throws IOException;
+
+  Iterable<? extends Element> analyze() throws IOException;
+
+  Iterable<? extends JavaFileObject> generate() throws IOException;
+
+  void setTaskListener(BuckJavacTaskListener taskListener);
+
+  void addTaskListener(BuckJavacTaskListener taskListener);
+
+  void removeTaskListener(BuckJavacTaskListener taskListener);
+
+  void addPostEnterCallback(Consumer<Set<Element>> callback);
+
+  ElementsExtended getElements();
+
+  Types getTypes();
+
+  Messager getMessager();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/CompilationUnitTreeProxy.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/CompilationUnitTreeProxy.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/CompilationUnitTreeProxy.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.api;
+
+/**
+ * {@link com.sun.source.tree.CompilationUnitTree} is included with the compiler and is thus not
+ * directly accessible from within Buck's class loader. This interface is used to identify objects
+ * that serve as proxies for {@link com.sun.source.tree.CompilationUnitTree}'s within Buck's class
+ * loader. These are translated back into the underlying {@link
+ * com.sun.source.tree.CompilationUnitTree} when passed back into the compiler.
+ */
+public interface CompilationUnitTreeProxy {}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/PluginClassLoader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/PluginClassLoader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/PluginClassLoader.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.api;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+
+/** Utility interface for loading classes that live in Buck's Java compiler plugin. */
+public interface PluginClassLoader {
+  @Nullable
+  <T> Class<? extends T> loadClass(String name, Class<T> superclass);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/PluginClassLoaderFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/PluginClassLoaderFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/PluginClassLoaderFactory.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.api;
+
+import javax.tools.JavaCompiler;
+
+/** Factory interface for {@link PluginClassLoader}s for different compiler instances */
+public interface PluginClassLoaderFactory {
+  PluginClassLoader getPluginClassLoader(JavaCompiler.CompilationTask task);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/TaskEventMirror.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/TaskEventMirror.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/api/TaskEventMirror.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.plugin.api;
+
+import com.facebook.buck.util.liteinfersupport.Nullable;
+import javax.lang.model.element.TypeElement;
+import javax.tools.JavaFileObject;
+
+/**
+ * {@link com.sun.source.util.TaskEvent} is included with the compiler and is thus not directly
+ * accessible from within Buck's class loader. This class is used as a mirror within Buck's class
+ * loader for a {@link com.sun.source.util.TaskEvent} within the compiler's.
+ */
+public final class TaskEventMirror {
+  public enum Kind {
+    /** For events related to the parsing of a file. */
+    PARSE,
+    /** For events relating to elements being entered. */
+    ENTER,
+    /** For events relating to elements being analyzed for errors. */
+    ANALYZE,
+    /** For events relating to class files being generated. */
+    GENERATE,
+    /** For events relating to overall annotation processing. */
+    ANNOTATION_PROCESSING,
+    /** For events relating to an individual annotation processing round. */
+    ANNOTATION_PROCESSING_ROUND,
+    /**
+     * Sent before parsing first source file, and after writing the last output file. This event is
+     * not sent when using {@code JavacTask#parse()}, {@code JavacTask#analyze()} or {@code
+     * JavacTask#generate()}.
+     *
+     * @since 9
+     */
+    COMPILATION,
+  }
+
+  private final Object original;
+  private final Kind kind;
+  @Nullable private final JavaFileObject sourceFile;
+  @Nullable private final CompilationUnitTreeProxy compilationUnitTreeProxy;
+  @Nullable private final TypeElement typeElement;
+
+  public TaskEventMirror(
+      Object original,
+      Kind kind,
+      @Nullable JavaFileObject sourceFile,
+      @Nullable CompilationUnitTreeProxy compilationUnitTreeProxy,
+      @Nullable TypeElement typeElement) {
+    this.original = original;
+    this.kind = kind;
+    this.sourceFile = sourceFile;
+    this.compilationUnitTreeProxy = compilationUnitTreeProxy;
+    this.typeElement = typeElement;
+  }
+
+  public Object getOriginal() {
+    return original;
+  }
+
+  public Kind getKind() {
+    return kind;
+  }
+
+  @Nullable
+  public JavaFileObject getSourceFile() {
+    return sourceFile;
+  }
+
+  @Nullable
+  public CompilationUnitTreeProxy getCompilationUnit() {
+    return compilationUnitTreeProxy;
+  }
+
+  @Nullable
+  public TypeElement getTypeElement() {
+    return typeElement;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/javac-plugin.jar b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/javac-plugin.jar
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/plugin/javac-plugin.jar
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/runner/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/runner/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/runner/BUCK
@@ -0,0 +1,26 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "runner",
+    srcs = glob(["*.java"]),
+    # We need to support a java_for_tests that points at Java 8 for now.
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:steps",
+        "prelude//toolchains/android/src/com/facebook/buck/testrunner:junit",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java:java",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/runner:runner",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/version/utils:utils",
+        # DO NOT add any deps here.
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/runner/FileClassPathRunner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/runner/FileClassPathRunner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/runner/FileClassPathRunner.java
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.runner;
+
+import com.facebook.buck.jvm.java.version.utils.JavaVersionUtils;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * This class handles extra large classpaths by allowing the client to pass the classpath via file
+ * specified by {@code buck.classpath_file}. This is to sidestep commandline length limits.
+ *
+ * <p>There are 3 modes:
+ *
+ * <ul>
+ *   <li>Java 8 or older launched: We manually add the entries from `buck.classpath_file` to the
+ *       system classloader.
+ *   <li>Java 9 or newer launched, and Buck is aware of this: We rely on `@argfile` support in newer
+ *       versions of `java` to pass in our long `-classpath` argument. Here, the JVM adds all the
+ *       classpath entries itself.
+ *   <li>Java 9 or newer launched, and Buck isn't aware of this: We create a new classloader and add
+ *       entries from `buck.classpath_file` manually. This approach has problems, e.g. classloading
+ *       for in-process Java compilation does not work for Buck's own tests, but is provided to
+ *       support cases where the version of `java` on the path is 9+, but we're targeting 8- for the
+ *       target under test.
+ * </ul>
+ *
+ * <p>Note: this class only depends on classes present in the JRE, since we don't want to have to
+ * push more things on to the classpath when using it.
+ */
+public class FileClassPathRunner {
+  public static final String CLASSPATH_FILE_PROPERTY = "buck.classpath_file";
+  public static final String TESTRUNNER_CLASSES_PROPERTY = "buck.testrunner_classes";
+
+  static {
+    // On macOS, this will suppress the Dock icon if any libraries try to use AWT somewhere.
+    System.setProperty("apple.awt.UIElement", "true");
+  }
+
+  private FileClassPathRunner() {
+    // Do not instantiate.
+  }
+
+  public static void main(String[] args) throws IOException, ReflectiveOperationException {
+    // We must have the name of the class to delegate to added.
+    if (args.length < 1) {
+      System.exit(-1);
+    }
+
+    ClassLoader classLoader;
+    if (shouldPopulateClassLoader()) {
+      // We need to manually populate the classloader from a file containing the (potentially very
+      // long) classpath. This happens either because we're running on Java 8 or older, which do
+      // not support argfiles in `java` invocations, or we're running on Java 9 or later, but Buck
+      // isn't aware that it's launching a version of Java newer than 8.
+      StringBuilder classPathProperty = new StringBuilder();
+      URL[] classpath = getClassPath(classPathProperty);
+      System.setProperty("java.class.path", classPathProperty.toString());
+      classLoader = getClassLoaderForTests(classpath);
+    } else {
+      // We've passed an argfile containing our full (potentially very long) classpath into `java`,
+      // which the JVM has already populated the system classloader with. Nothing to do.
+      classLoader = ClassLoader.getSystemClassLoader();
+    }
+
+    // Now read the main class from the args and invoke it
+    Method main = getMainMethod(classLoader, args);
+    String[] mainArgs = constructArgs(args);
+    main.invoke(null, new Object[] {mainArgs});
+  }
+
+  private static boolean shouldPopulateClassLoader() {
+    return JavaVersionUtils.getMajorVersion() <= 8
+        || System.getProperty(CLASSPATH_FILE_PROPERTY) != null;
+  }
+
+  private static ClassLoader getClassLoaderForTests(URL[] classpath) {
+    if (JavaVersionUtils.getMajorVersion() <= 8) {
+      URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
+      try {
+        Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
+        addURL.setAccessible(true);
+        for (URL entry : classpath) {
+          addURL.invoke(urlClassLoader, entry);
+        }
+      } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
+        throw new RuntimeException(
+            String.format(
+                "Couldn't add classpath URLs to (URLClassLoader) ClassLoader.getSystemClassLoader()"
+                    + " on java version %d",
+                JavaVersionUtils.getMajorVersion()),
+            e);
+      }
+      return urlClassLoader;
+    } else {
+      ClassLoader classLoader = URLClassLoader.newInstance(classpath, findPlatformClassLoader());
+      Thread.currentThread().setContextClassLoader(classLoader);
+      return classLoader;
+    }
+  }
+
+  // VisibleForTesting (can not use guava as dependency)
+  static URL[] getClassPath(StringBuilder classPathPropertyOut) throws IOException {
+    List<Path> classPath = new ArrayList<>();
+    String testRunnerClassPath = System.getProperty(TESTRUNNER_CLASSES_PROPERTY);
+    if (testRunnerClassPath != null) {
+      classPath.add(Paths.get(testRunnerClassPath));
+    }
+
+    String classPathFileProperty = System.getProperty(CLASSPATH_FILE_PROPERTY);
+    if (classPathFileProperty != null) {
+      classPath.addAll(getTestClassPath(Paths.get(classPathFileProperty)));
+    }
+
+    URL[] result = new URL[classPath.size()];
+    for (int i = 0; i < result.length; i++) {
+      Path entry = classPath.get(i);
+      result[i] = entry.toUri().toURL();
+
+      classPathPropertyOut.append(entry);
+      classPathPropertyOut.append(":");
+    }
+    classPathPropertyOut.deleteCharAt(classPathPropertyOut.length() - 1);
+    return result;
+  }
+
+  // VisibleForTesting (can not use guava as dependency)
+  static List<Path> getTestClassPath(Path classpathFile) throws IOException {
+    return Files.readAllLines(classpathFile).stream()
+        .map(Paths::get)
+        .filter(Files::exists)
+        .collect(Collectors.toList());
+  }
+
+  // VisibleForTesting (can not use guava as dependency)
+  static String[] constructArgs(String[] args) {
+    String[] mainArgs;
+
+    if (args.length == 1) {
+      mainArgs = new String[0];
+    } else {
+      mainArgs = new String[args.length - 1];
+      System.arraycopy(args, 1, mainArgs, 0, mainArgs.length);
+    }
+    return mainArgs;
+  }
+
+  private static Method getMainMethod(ClassLoader classLoader, String[] args)
+      throws ReflectiveOperationException {
+    Class<?> mainClazz = classLoader.loadClass(args[0]);
+    Method main = mainClazz.getMethod("main", args.getClass());
+    int modifiers = main.getModifiers();
+    if (!Modifier.isStatic(modifiers)) {
+      System.exit(-4);
+    }
+    return main;
+  }
+
+  /**
+   * Returns ClassLoader that is a sibling on "current" class loader, in java 8 that is "Ext" class
+   * loader, on java 9+ that is "platform" classloader.
+   */
+  // VisibleForTesting (can not use guava as dependency)
+  static ClassLoader findPlatformClassLoader() {
+    try {
+      // use platform class loader on Java 9+ if exists
+      Method method = ClassLoader.class.getMethod("getPlatformClassLoader");
+      return (ClassLoader) method.invoke(null);
+    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
+      throw new AssertionError("Cannot find platform class loader", e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/BUCK
@@ -0,0 +1,96 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//toolchains/android/tools/build_rules:fb_native.bzl", "fb_native")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "command_lib",
+    srcs = [
+        "JavaCDCommand.java",
+    ],
+    visibility = [
+        "prelude//toolchains/android/meta_only/src/com/facebook/buck/jvm/remote_worker/...",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/...",
+        "prelude//toolchains/android/test/com/facebook/buck/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd:cd",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/java:command",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:serialization",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java:java",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:steps",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi:abi",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:protobuf-util",
+    ],
+)
+
+buck_java_library(
+    name = "main_lib",
+    srcs = [
+        "JavaCDMain.java",
+    ],
+    visibility = [
+        "prelude//toolchains/android/meta_only/src/com/facebook/buck/jvm/remote_worker/...",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/...",
+        "prelude//toolchains/android/test/com/facebook/buck/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd:cd",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        ":command_lib",
+    ],
+)
+
+buck_java_library(
+    name = "grpc_worker_lib",
+    srcs = ["JavaCDGrpcWorkerToolMain.java"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd:cd",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/workertool:workertool",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc:workertool_grpc",
+        "prelude//toolchains/android/src/com/facebook/buck/workertool/resources/proto:worker-model",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        ":command_lib",
+    ],
+)
+
+buck_java_binary(
+    name = "javacd_tool_grpc-main",
+    main_class = "com.facebook.buck.jvm.java.stepsbuilder.javacd.main.JavaCDGrpcWorkerToolMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":grpc_worker_lib",
+        ":main_lib",
+    ],
+)
+
+fb_native.alias(
+    name = "javacd_tool",
+    actual = ":javacd_tool_grpc-main",
+    visibility = ["PUBLIC"],
+)
+
+buck_java_binary(
+    name = "javacd_tool-main",
+    java_args_for_run_info = ["-Dfile.encoding=UTF-8"],
+    main_class = "com.facebook.buck.jvm.java.stepsbuilder.javacd.main.JavaCDMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":main_lib",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDCommand.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDCommand.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDCommand.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.stepsbuilder.javacd.main;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.cd.AbiDirWriter;
+import com.facebook.buck.jvm.cd.BuildCommandStepsBuilder;
+import com.facebook.buck.jvm.cd.DepFileUtils;
+import com.facebook.buck.jvm.cd.JvmCDCommand;
+import com.facebook.buck.jvm.cd.command.PostBuildParams;
+import com.facebook.buck.jvm.cd.command.java.BuildJavaCommand;
+import com.facebook.buck.jvm.java.JavaStepsBuilder;
+import com.facebook.buck.jvm.java.abi.StubJar;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import com.google.protobuf.util.JsonFormat;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Optional;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Represents a javacd command invocation, on the command line or sent to a worker */
+public class JavaCDCommand implements JvmCDCommand {
+  @Option(name = "--action-id", required = true)
+  public String actionId;
+
+  @Option(name = "--command-file", required = true)
+  public Path commandFile;
+
+  @Option(name = "--logging-level")
+  private int loggingLevel = 0;
+
+  private final JavaStepsBuilder stepsBuilder;
+  private final ImmutableMap<Path, Path> jarToJarDirMap;
+  private final PostBuildParams postBuildParams;
+
+  public JavaCDCommand(String[] args, ImmutableMap<String, String> env)
+      throws CmdLineException, IOException {
+    CmdLineParser parser = new CmdLineParser(this);
+    try {
+      parser.parseArgument(args);
+    } catch (CmdLineException e) {
+      System.err.println(e.getMessage());
+      parser.printUsage(System.err);
+      throw e;
+    }
+    com.facebook.buck.cd.model.java.BuildJavaCommand.Builder builder =
+        com.facebook.buck.cd.model.java.BuildJavaCommand.newBuilder();
+    try (Reader reader = new FileReader(commandFile.toFile())) {
+      JsonFormat.parser().ignoringUnknownFields().merge(reader, builder);
+    }
+    RelPath buckScratchPath = RelPath.get(env.get(WORKING_DIRECTORY_ENV_VAR));
+
+    com.facebook.buck.cd.model.java.BuildJavaCommand proto = builder.build();
+    BuildJavaCommand buildJavaCommand =
+        BuildJavaCommand.Companion.fromProto(proto.getBuildCommand(), Optional.of(buckScratchPath));
+    this.postBuildParams = PostBuildParams.Companion.fromProto(proto.getPostBuildParams());
+    this.stepsBuilder = new JavaStepsBuilder(buildJavaCommand);
+    this.jarToJarDirMap = buildJavaCommand.getBaseJarCommand().getJarToJarDirMap();
+  }
+
+  public void maybeWriteClassAbi() throws IOException {
+    if (!postBuildParams.getShouldCreateClassAbi()) {
+      return;
+    }
+
+    AbsPath root = AbsPath.of(Paths.get(".").toAbsolutePath().normalize());
+    Preconditions.checkState(postBuildParams.getAbiJar() != null);
+    StubJar stubJar = new StubJar(root.resolve(postBuildParams.getLibraryJar()), false);
+    stubJar.writeTo(root.resolve(postBuildParams.getAbiJar()));
+  }
+
+  public void maybeWriteAbiDir() throws IOException {
+    if (postBuildParams.getAbiOutputDir() == null) {
+      Preconditions.checkState(postBuildParams.getAbiJar() == null);
+      return;
+    }
+
+    if (postBuildParams.getAbiJar() != null) {
+      AbiDirWriter.writeAbiOutputDir(
+          postBuildParams.getAbiJar(), postBuildParams.getAbiOutputDir());
+    } else {
+      throw new RuntimeException("Asked for an ABI dir but there is no ABI!");
+    }
+  }
+
+  public void maybeWriteDepFile() throws IOException {
+    Preconditions.checkState(
+        (postBuildParams.getDepFile() == null)
+            == (postBuildParams.getUsedClassesPaths().isEmpty()));
+    if (postBuildParams.getDepFile() != null) {
+      DepFileUtils.usedClassesToDepFile(
+          postBuildParams.getUsedClassesPaths(),
+          postBuildParams.getDepFile(),
+          jarToJarDirMap,
+          false);
+    }
+  }
+
+  public void maybeWriteUsedJarsFile() throws IOException {
+    if (postBuildParams.getUsedJarsPath() == null) {
+      return;
+    }
+
+    DepFileUtils.usedClassesToUsedJars(
+        postBuildParams.getUsedClassesPaths(), postBuildParams.getUsedJarsPath(), false);
+  }
+
+  @Override
+  public BuildCommandStepsBuilder getBuildCommand() {
+    return stepsBuilder;
+  }
+
+  @Override
+  public String getActionId() {
+    return actionId;
+  }
+
+  @Override
+  public int getLoggingLevel() {
+    return loggingLevel;
+  }
+
+  @Override
+  public void postExecute() throws IOException {
+    maybeWriteClassAbi();
+    maybeWriteAbiDir();
+    maybeWriteDepFile();
+    maybeWriteUsedJarsFile();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDGrpcWorkerToolMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDGrpcWorkerToolMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDGrpcWorkerToolMain.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.stepsbuilder.javacd.main;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.cd.CompilerDaemonLoggerUtil;
+import com.facebook.buck.jvm.cd.workertool.grpc.WorkerGrpcServer;
+import java.io.IOException;
+
+/**
+ * JavaCD grpc worker tool daemon, for use by buck2
+ *
+ * <p>This starts a grpc service over a uds socket, that accepts javacd compilation commands
+ */
+public class JavaCDGrpcWorkerToolMain {
+  private static final String LOG_PATH = "buck-out/v2/javacd";
+
+  public static void main(String[] args) throws IOException {
+    CompilerDaemonLoggerUtil.setDefaultLogger("javacd_grpc_worker", LOG_PATH);
+    Logger logger = Logger.get(JavaCDGrpcWorkerToolMain.class.getName());
+    logger.info("Starting JavaCD Worker GRPC Server");
+    WorkerGrpcServer.runServer("JavaCD", JavaCDCommand::new);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main/JavaCDMain.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.stepsbuilder.javacd.main;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.cd.CompilerDaemonLoggerUtil;
+import com.facebook.buck.jvm.cd.CompilerDaemonRunner;
+import com.facebook.buck.jvm.cd.ErrorInterceptor;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.util.logging.Level;
+
+/**
+ * JavaCD main class.
+ *
+ * <p>This provides a simple executable that can run any of the javacd actions.
+ */
+public class JavaCDMain {
+  private static final String LOG_PATH = "buck-out/v2/javacd";
+
+  /** Main entrypoint of JavaCD worker tool. */
+  public static void main(String[] args) throws IOException {
+    try {
+      JavaCDCommand command = new JavaCDCommand(args, ImmutableMap.copyOf(System.getenv()));
+      CompilerDaemonLoggerUtil.setDefaultLogger("javacd_worker", LOG_PATH);
+      CompilerDaemonLoggerUtil.setConsoleHandlerLogLevelTo(Level.WARNING);
+      Logger logger = Logger.get(JavaCDMain.class.getName());
+      System.setErr(new ErrorInterceptor());
+      Runtime.getRuntime()
+          .addShutdownHook(
+              new Thread(
+                  () -> {
+                    System.out.flush();
+                    System.err.flush();
+                  }));
+      CompilerDaemonRunner.run(command);
+      logger.info(String.format("Starting JavaCDWorkerTool %s", command));
+      command.postExecute();
+      System.err.println("JavaCDWorkerTool succeeded!");
+      System.exit(0);
+    } catch (Exception e) {
+      System.err.println("JavaCDWorkerTool failed: " + e.getMessage());
+    }
+    System.exit(2);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/worker/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/worker/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/worker/BUCK
@@ -0,0 +1,26 @@
+load("@prelude//toolchains/android/tools/build_rules:worker.bzl", "worker")
+load("@prelude//utils:buckconfig.bzl", "read", "read_list")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+worker(
+    name = "javacd_grpc_worker_tool",
+    concurrency = 16,
+    exe = "prelude//toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main:javacd_tool",
+    jvm_args = read_list(
+        "javacd",
+        "jvm_args",
+        delimiter = " ",
+        required = False,
+    )
+    or []
+    if not read("javacd", "jvm_args_target")
+    else [],
+    main_class = "com.facebook.buck.jvm.java.stepsbuilder.javacd.main.JavaCDGrpcWorkerToolMain",
+    visibility = [
+        "PUBLIC",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/version/utils/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/version/utils/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/version/utils/BUCK
@@ -0,0 +1,21 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "utils",
+    srcs = glob(["*.java"]),
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        # Do NOT add any deps here. This library is used by code that cannot depend on the rest of Buck.
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/version/utils/JavaVersionUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/version/utils/JavaVersionUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/java/version/utils/JavaVersionUtils.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.java.version.utils;
+
+import java.util.Objects;
+
+/** Utility class for retrieving Java version information. */
+public class JavaVersionUtils {
+  private static int majorVersion = 0;
+
+  /**
+   * Returns the major version of the current JVM instance (e.g. 8 for Java 1.8, and 10 for Java
+   * 10.0).
+   */
+  public static int getMajorVersion() {
+    if (majorVersion == 0) {
+      majorVersion =
+          getMajorVersionFromString(Objects.requireNonNull(System.getProperty("java.version")));
+    }
+    return majorVersion;
+  }
+
+  /** Returns the major version from a Java version string (e.g. 8 for "1.8", and 10 for "10.0"). */
+  public static int getMajorVersionFromString(String version) {
+    String[] versionParts = Objects.requireNonNull(version).split("\\.|-");
+    return Integer.parseInt((versionParts[0].equals("1")) ? versionParts[1] : versionParts[0]);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/AnnotationProcessorUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/AnnotationProcessorUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/AnnotationProcessorUtils.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.jvm.java.JavacPluginParams;
+import com.facebook.buck.jvm.java.ResolvedJavacPluginProperties;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.nio.file.Paths;
+import java.util.Base64;
+import java.util.Map;
+
+public class AnnotationProcessorUtils {
+  public static final String KSP_PROCESSOR_NAME_PREFIX = "KSP:";
+
+  static ImmutableList<ResolvedJavacPluginProperties> getAnnotationProcessors(
+      JavacPluginParams annotationProcessorParams) {
+    return annotationProcessorParams.isEmpty()
+        ? ImmutableList.of()
+        : annotationProcessorParams.getPluginProperties().asList();
+  }
+
+  static String encodeOptions(Map<String, String> options) {
+    try (ByteArrayOutputStream os = new ByteArrayOutputStream();
+        ObjectOutputStream oos = new ObjectOutputStream(os)) {
+
+      oos.writeInt(options.size());
+      for (Map.Entry<String, String> entry : options.entrySet()) {
+        oos.writeUTF(entry.getKey());
+        oos.writeUTF(entry.getValue());
+      }
+
+      oos.flush();
+      return Base64.getEncoder().encodeToString(os.toByteArray());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  /**
+   * Safely converts a URL to a File path. Use this instead of {@link URL#getFile} to ensure that
+   * htmlencoded literals are not present in the file path.
+   */
+  public static String urlToFile(URL url) {
+    try {
+      return Paths.get(url.toURI()).toFile().getPath();
+    } catch (URISyntaxException e) {
+      // In case of error, fall back to the original implementation.
+      return url.getFile();
+    }
+  }
+
+  /**
+   * KSP Annotation processors are defined like Java's, but their name starts with
+   * KSP_PROCESSOR_NAME_PREFIX
+   */
+  public static boolean isKSPProcessor(ResolvedJavacPluginProperties prop) {
+    return !prop.getProcessorNames().isEmpty()
+        && Iterables.getFirst(prop.getProcessorNames(), "").startsWith(KSP_PROCESSOR_NAME_PREFIX);
+  }
+
+  /** Java only processors that run on Javac instead of KotlinC for java files in mix modules */
+  public static boolean isRunsOnJavaOnlyProcessor(ResolvedJavacPluginProperties prop) {
+    return prop.getRunsOnJavaOnly();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/BUCK
@@ -0,0 +1,49 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "steps",
+    srcs = glob([
+        "*.java",
+        "**/*.kt",
+    ]),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin:kotlin",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:kotlincd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/core:core",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization:serialization",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/java:java",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin:kotlin",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:steps",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/javax:javax",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:command",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools:buildtools",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics:analytics",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot:cp_snapshot_generator_lib",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc:kotlinc",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental:incremental",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses:usedclasses",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp:ksp",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin:plugin-loader",
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps/java:java",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api:api",
+        # TODO(sergei): util/json is a source of [ObjectMapper] that is very heavy for class loading
+        "prelude//toolchains/android/src/com/facebook/buck/util/json:json",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:language-version",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting:abtesting",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ksic:ksic",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental:incremental",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClassUsageFileWriterFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClassUsageFileWriterFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClassUsageFileWriterFactory.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.jvm.java.ClassUsageFileWriter;
+import com.facebook.buck.jvm.java.DefaultClassUsageFileWriter;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode;
+
+public class ClassUsageFileWriterFactory {
+
+  private ClassUsageFileWriterFactory() {}
+
+  public static ClassUsageFileWriter create(KotlincMode mode) {
+    return new DefaultClassUsageFileWriter();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClasspathChangesFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClasspathChangesFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClasspathChangesFactory.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.ClasspathChanges;
+import com.google.common.collect.ImmutableList;
+import java.util.stream.Collectors;
+
+public class ClasspathChangesFactory {
+
+  private static final Logger LOG = Logger.get(KotlinSourceChangesFactory.class);
+
+  private ClasspathChangesFactory() {}
+
+  public static ClasspathChanges create(
+      SnapshotsActionMetadata actionMetadata, ImmutableList<AbsPath> classpathSnapshots) {
+    if (actionMetadata.hasClasspathChanged()) {
+      ImmutableList<java.io.File> snapshotFiles =
+          ImmutableList.copyOf(
+              classpathSnapshots.stream().map(AbsPath::toFile).collect(Collectors.toList()));
+
+      LOG.info("Classpath changes: Detected changes on the classpath");
+      return new ClasspathChanges.ToBeComputedByIncrementalCompiler(snapshotFiles);
+    }
+
+    LOG.info("Classpath changes: No changes on the classpath");
+    return new ClasspathChanges.NoChanges(
+        ImmutableList.copyOf(
+            classpathSnapshots.stream().map(AbsPath::toFile).collect(Collectors.toList())));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClasspathUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClasspathUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ClasspathUtils.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.filesystem.CopySourceMode;
+import com.facebook.buck.jvm.core.BuildTargetValueExtraParams;
+import com.facebook.buck.jvm.java.CompilerParameters;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.CopyIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MakeCleanDirectoryIsolatedStep;
+import com.google.common.collect.ImmutableCollection;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.common.collect.Ordering;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Map;
+
+public class ClasspathUtils {
+  private final AbsPath buildCellRootPath;
+  private final ImmutableSortedSet<AbsPath> resolvedFriendPaths;
+  private final ImmutableList<RelPath> classpaths;
+  private final ImmutableList<AbsPath> extraClasspaths;
+  private final BuildTargetValueExtraParams buildTargetValueExtraParams;
+
+  private Map<AbsPath, AbsPath> remappedClasspathEntries = new HashMap<>();
+
+  public ClasspathUtils(
+      AbsPath buildCellRootPath,
+      ImmutableSortedSet<AbsPath> resolvedFriendPaths,
+      ImmutableList<RelPath> classpaths,
+      ImmutableList<AbsPath> extraClasspaths,
+      BuildTargetValueExtraParams buildTargetValueExtraParams) {
+    this.buildCellRootPath = buildCellRootPath;
+    this.resolvedFriendPaths = resolvedFriendPaths;
+    this.classpaths = classpaths;
+    this.extraClasspaths = extraClasspaths;
+    this.buildTargetValueExtraParams = buildTargetValueExtraParams;
+  }
+
+  public String getFriendPathArgs(ImmutableList.Builder<IsolatedStep> steps) {
+    ImmutableCollection<AbsPath> friendPathsSourcePaths = getFriendAbsPaths(steps);
+    if (friendPathsSourcePaths.isEmpty()) {
+      return "";
+    }
+
+    // https://youtrack.jetbrains.com/issue/KT-29933
+    ImmutableSortedSet<String> absoluteFriendPaths =
+        friendPathsSourcePaths.stream()
+            .map(AbsPath::toString)
+            .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));
+
+    return "-Xfriend-paths=" + String.join(",", absoluteFriendPaths);
+  }
+
+  private ImmutableSortedSet<AbsPath> getFriendAbsPaths(ImmutableList.Builder<IsolatedStep> steps) {
+    ImmutableSortedSet.Builder<AbsPath> friendAbsPathsBuilder =
+        ImmutableSortedSet.orderedBy(Comparator.comparing(AbsPath::getPath));
+
+    // Currently, kotlinc can't handle commas (`,`) in paths when passed to the `-Xfriend-paths`
+    // flag, so if we see a comma, we copy the JAR to a new path w/o one.
+    RelPath friendPathScratchDir =
+        buildTargetValueExtraParams.getScratchPath("__%s_friend_path_jars__");
+    friendPathScratchDir =
+        friendPathScratchDir
+            .getParent()
+            .resolveRel(friendPathScratchDir.getFileName().toString().replace(",", "__"));
+
+    for (AbsPath friendPath : resolvedFriendPaths) {
+      // If this path has a comma, copy to a new location that doesn't have one.
+      if (friendPath.getPath().toString().contains(",")) {
+        if (remappedClasspathEntries.isEmpty()) {
+          steps.addAll(MakeCleanDirectoryIsolatedStep.of(friendPathScratchDir));
+        }
+        AbsPath dest =
+            buildCellRootPath.resolve(friendPathScratchDir.resolve(friendPath.getFileName()));
+        steps.add(CopyIsolatedStep.of(friendPath.getPath(), dest.getPath(), CopySourceMode.FILE));
+        remappedClasspathEntries.put(friendPath, dest);
+        friendPath = dest;
+      }
+      friendAbsPathsBuilder.add(friendPath);
+    }
+    ImmutableSortedSet<AbsPath> friendAbsPaths = friendAbsPathsBuilder.build();
+    return friendAbsPaths;
+  }
+
+  public static boolean assertValidClasspathsPattern(AbsPath absPath) {
+    String path = absPath.toString();
+    if (!(path.endsWith(".jar") || path.endsWith(".zip") || path.contains("buck-out/"))) {
+      throw new AssertionError(
+          String.format(
+              "classpath %s is not supported, only jar, zip file or a directory inside `buck-out/`"
+                  + " are allowed",
+              path));
+    }
+    return true;
+  }
+
+  public ImmutableList<AbsPath> getAllClasspaths(ImmutableList.Builder<IsolatedStep> steps) {
+    ImmutableList.Builder<AbsPath> classpathBuilder =
+        ImmutableList.<AbsPath>builder()
+            .addAll(
+                classpaths.stream()
+                    .map(buildCellRootPath::resolve)
+                    .map(AbsPath::normalize)
+                    .map(p -> remappedClasspathEntries.getOrDefault(p, p))
+                    .filter(path -> path != null && assertValidClasspathsPattern(path))
+                    .iterator())
+            .addAll(
+                extraClasspaths.stream()
+                    .map(p -> remappedClasspathEntries.getOrDefault(p, p))
+                    .filter(path -> path != null && assertValidClasspathsPattern(path))
+                    .iterator());
+    ImmutableList<AbsPath> allClasspaths = classpathBuilder.build();
+    return allClasspaths;
+  }
+
+  /**
+   * Returns a list of classpath snapshots for all `.jar`s in the classpath - uses snapshot for
+   * `.jar` if provided - adds a step to generate snapshot for a `.jar` if not provided
+   *
+   * @param parameters Compiler parameters including output paths and provided classpath snapshots.
+   * @param steps A step builder to which new steps might be added to generate snapshots.
+   * @param rootPath The root path of the project.
+   * @param allClasspaths A list of all classpaths to consider for snapshot generation.
+   * @return An immutable list of paths to the classpath snapshots.
+   */
+  public static ImmutableList<AbsPath> getClasspathSnapshots(
+      CompilerParameters parameters,
+      ImmutableList.Builder<IsolatedStep> steps,
+      AbsPath rootPath,
+      ImmutableList<AbsPath> allClasspaths,
+      ImmutableList<AbsPath> extraClassPathSnapshots) {
+    ImmutableList.Builder<AbsPath> classpathSnapshotsBuilder = ImmutableList.builder();
+    classpathSnapshotsBuilder.addAll(extraClassPathSnapshots);
+    parameters.getClasspathSnapshots().stream()
+        .map(rootPath::resolve)
+        .map(AbsPath::normalize)
+        .forEach(classpathSnapshotsBuilder::add);
+    ImmutableList<AbsPath> classpathSnapshots = classpathSnapshotsBuilder.build();
+
+    if (classpathSnapshots.size() < allClasspaths.size()) {
+      throw new IllegalStateException(
+          String.format(
+              "Classpath snapshots size (%d) does not match classpath size (%d). "
+                  + "When compiling incrementally, there must be a classpath snapshot "
+                  + "for every classpath item. Please ensure all classpath entries have "
+                  + "corresponding snapshots.",
+              classpathSnapshots.size(), allClasspaths.size()));
+    }
+
+    return classpathSnapshotsBuilder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/CompilerPluginUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/CompilerPluginUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/CompilerPluginUtils.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+import java.util.function.BiPredicate;
+
+public class CompilerPluginUtils {
+
+  public static final String X_PLUGIN_ARG = "-Xplugin=";
+  public static final String KOTLIN_PLUGIN_OUT_PLACEHOLDER = "__codegen_dir__";
+  static final String MODULE_NAME = "-module-name";
+  static final String NO_STDLIB = "-no-stdlib";
+  static final String VERBOSE = "-verbose";
+  static final String JB_JVM_ABI_OUTPUT_DIR = "plugin:org.jetbrains.kotlin.jvm.abi:outputDir";
+  private static final String PLUGIN = "-P";
+  private static final String PLUGIN_KOTLIN_DI_KSP_ACTIVE =
+      "plugin:com.facebook.kotlin.di:kspActive";
+
+  public static ImmutableList<String> getKotlinCompilerPluginsArgs(
+      ImmutableMap<AbsPath, ImmutableMap<String, String>> resolvedKotlinCompilerPlugins,
+      String outputDir,
+      BiPredicate<AbsPath, ImmutableMap<String, String>> filter) {
+    ImmutableList.Builder<String> pluginArgs = ImmutableList.builder();
+    for (Map.Entry<AbsPath, ImmutableMap<String, String>> entry :
+        resolvedKotlinCompilerPlugins.entrySet()) {
+      AbsPath pluginPath = entry.getKey();
+      ImmutableMap<String, String> pluginOptions = entry.getValue();
+
+      if (!filter.test(pluginPath, pluginOptions)) {
+        continue;
+      }
+
+      pluginArgs.addAll(getKotlinCompilerPluginsArgs(pluginPath, pluginOptions, outputDir));
+    }
+    return pluginArgs.build();
+  }
+
+  // I'll add unit tests to this here
+  public static ImmutableList<String> getKotlinCompilerPluginsArgs(
+      AbsPath pluginPath,
+      ImmutableMap<String, String> kotlinCompilerPluginParams,
+      String outputDir) {
+    ImmutableList.Builder<String> pluginArgs = ImmutableList.builder();
+
+    // Add plugin basic string, e.g. "-Xplugins=<pluginPath>"
+    pluginArgs.add(X_PLUGIN_ARG + pluginPath);
+
+    // If plugin options exist, add plugin option string,
+    // e.g. "-P" and "<optionKey>=<optionValue>,<optionKey2>=<optionValue2>,..."
+    if (kotlinCompilerPluginParams != null && !kotlinCompilerPluginParams.isEmpty()) {
+      ImmutableList.Builder<String> pluginOptionStrings = ImmutableList.builder();
+
+      for (String pluginOptionKey : kotlinCompilerPluginParams.keySet()) {
+        String pluginOptionValue = kotlinCompilerPluginParams.get(pluginOptionKey);
+
+        if (pluginOptionValue.equals(KOTLIN_PLUGIN_OUT_PLACEHOLDER)) {
+          pluginOptionValue = outputDir;
+        }
+
+        pluginOptionStrings.add(pluginOptionKey + "=" + pluginOptionValue);
+      }
+      String pluginOptionString = Joiner.on(",").join(pluginOptionStrings.build());
+      pluginArgs.add(PLUGIN).add(pluginOptionString);
+    }
+    return pluginArgs.build();
+  }
+
+  public static boolean isDiK1PluginForKapt(
+      AbsPath sourcePath, ImmutableMap<String, String> options) {
+    return isDiK1Plugin(sourcePath) && !isDiKspActive(options);
+  }
+
+  public static boolean isDiK1PluginForKsp(
+      AbsPath sourcePath, ImmutableMap<String, String> options) {
+    return isDiK1Plugin(sourcePath) && isDiKspActive(options);
+  }
+
+  private static boolean isDiK1Plugin(AbsPath sourcePath) {
+    return sourcePath.endsWith("di.jar");
+  }
+
+  private static boolean isDiKspActive(ImmutableMap<String, String> options) {
+    return "True".equals(options.get(PLUGIN_KOTLIN_DI_KSP_ACTIVE));
+  }
+
+  public static boolean isKotlinAllOpenPlugin(
+      AbsPath sourcePath, ImmutableMap<String, String> options) {
+    return sourcePath.endsWith("kotlin-allopen.jar");
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/DaemonKotlincToJarStepFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/DaemonKotlincToJarStepFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/DaemonKotlincToJarStepFactory.java
@@ -0,0 +1,390 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import static com.facebook.buck.jvm.kotlin.ClasspathUtils.getClasspathSnapshots;
+import static com.facebook.buck.jvm.kotlin.KosabiStubgenStepsBuilder.prepareKosabiStubgenIfNeeded;
+import static com.facebook.buck.jvm.kotlin.KspStepsBuilder.prepareKspProcessorsIfNeeded;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.file.FileExtensionMatcher;
+import com.facebook.buck.io.file.GlobPatternMatcher;
+import com.facebook.buck.io.file.PathMatcher;
+import com.facebook.buck.io.filesystem.CopySourceMode;
+import com.facebook.buck.jvm.cd.command.kotlin.KotlinExtraParams;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.core.BuildTargetValueExtraParams;
+import com.facebook.buck.jvm.java.ActionMetadata;
+import com.facebook.buck.jvm.java.BaseCompileToJarStepFactory;
+import com.facebook.buck.jvm.java.CompilerOutputPaths;
+import com.facebook.buck.jvm.java.CompilerOutputPathsValue;
+import com.facebook.buck.jvm.java.CompilerParameters;
+import com.facebook.buck.jvm.java.JarParameters;
+import com.facebook.buck.jvm.java.JavacPluginParams;
+import com.facebook.buck.jvm.java.ResolvedJavac;
+import com.facebook.buck.jvm.java.ResolvedJavacOptions;
+import com.facebook.buck.jvm.java.ResolvedJavacPluginProperties;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics;
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.CopyIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MakeCleanDirectoryIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MkdirIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.java.JarDirectoryStep;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableList.Builder;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import java.nio.file.Path;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+
+/**
+ * Factory that creates Kotlin related compile build steps, but doesn't depend on any internal build
+ * graph data structured. Intended to be used from the Daemon worker.
+ */
+public class DaemonKotlincToJarStepFactory extends BaseCompileToJarStepFactory<KotlinExtraParams> {
+  static final PathMatcher KOTLIN_PATH_MATCHER = FileExtensionMatcher.of("kt");
+  static final PathMatcher SRC_ZIP_MATCHER = GlobPatternMatcher.of("**.src.zip");
+
+  private final KotlinCDAnalytics kotlinCDAnalytics;
+
+  public DaemonKotlincToJarStepFactory(KotlinCDAnalytics kotlinCDAnalytics) {
+    this.kotlinCDAnalytics = kotlinCDAnalytics;
+  }
+
+  @Override
+  public KotlinExtraParams castExtraParams(ExtraParams extraParams) {
+    return (KotlinExtraParams) extraParams;
+  }
+
+  @Override
+  public void createCompileStep(
+      RelPath buckOut,
+      AbsPath buildCellRootPath,
+      BuildTargetValue invokingRule,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      CompilerParameters parameters,
+      Builder<IsolatedStep> steps,
+      ResolvedJavac resolvedJavac,
+      @Nullable ActionMetadata actionMetadata,
+      KotlinExtraParams extraParams,
+      @Nullable JarParameters abiJarParameters,
+      boolean mixedCompilation) {
+
+    Kotlinc kotlinc = KotlincFactory.create();
+
+    CompilerOutputPaths compilerOutputPaths = parameters.getOutputPaths();
+    BuildTargetValueExtraParams buildTargetValueExtraParams =
+        BuildTargetValueExtraParams.of(invokingRule, compilerOutputPaths.getWorkingDirectory());
+
+    ImmutableSortedSet<RelPath> sourceFilePaths = parameters.getSourceFilePaths();
+    RelPath outputDirectory = compilerOutputPaths.getClassesDir();
+    RelPath kotlinOutputDirectory = buildCellRootPath.relativize(extraParams.getKotlinClassesDir());
+    if (!extraParams.getShouldActionRunIncrementally()) {
+      steps.addAll(MakeCleanDirectoryIsolatedStep.of(kotlinOutputDirectory));
+    } else {
+      steps.add(new MkdirIsolatedStep(kotlinOutputDirectory));
+    }
+    RelPath annotationGenFolder = compilerOutputPaths.getAnnotationPath();
+    Path pathToSrcsList = compilerOutputPaths.getPathToSourcesList().getPath();
+
+    boolean hasKotlinSources =
+        sourceFilePaths.stream().anyMatch(KOTLIN_PATH_MATCHER::matches)
+            || sourceFilePaths.stream().anyMatch(SRC_ZIP_MATCHER::matches);
+
+    ImmutableSortedSet.Builder<RelPath> sourceWithStubsAndKaptOutputBuilder =
+        ImmutableSortedSet.orderedBy(RelPath.comparator()).addAll(sourceFilePaths);
+    ImmutableSortedSet.Builder<RelPath> sourceWithStubsAndKaptAndKspOutputBuilder =
+        ImmutableSortedSet.orderedBy(RelPath.comparator()).addAll(sourceFilePaths);
+    ImmutableSortedSet.Builder<RelPath> javacSourceBuilder =
+        ImmutableSortedSet.orderedBy(RelPath.comparator()).addAll(sourceFilePaths);
+
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(annotationGenFolder));
+    // Only invoke kotlinc if we have kotlin or src zip files.
+    if (hasKotlinSources) {
+      RelPath reportsOutput = buildTargetValueExtraParams.getAnnotationOutputPath("__%s_reports__");
+
+      RelPath kotlincPluginGeneratedOutput =
+          buildTargetValueExtraParams.getAnnotationOutputPath("__%s_kotlinc_plugin_generated__");
+
+      // Javac requires that the root directory for generated sources already exist.
+      steps.addAll(MakeCleanDirectoryIsolatedStep.of(kotlincPluginGeneratedOutput));
+      steps.addAll(MakeCleanDirectoryIsolatedStep.of(reportsOutput));
+
+      ClasspathUtils classpathUtils =
+          new ClasspathUtils(
+              buildCellRootPath,
+              extraParams.getFriendPaths(),
+              parameters.getClasspathEntries(),
+              extraParams.getExtraClassPaths(),
+              buildTargetValueExtraParams);
+
+      String friendPathsArg = classpathUtils.getFriendPathArgs(steps);
+
+      ImmutableList<AbsPath> allClasspaths = classpathUtils.getAllClasspaths(steps);
+
+      ImmutableList<AbsPath> classpathSnapshots =
+          extraParams.getShouldKotlincRunIncrementally()
+              ? getClasspathSnapshots(
+                  parameters,
+                  steps,
+                  buildCellRootPath,
+                  allClasspaths,
+                  extraParams.getExtraClassPathSnapshots())
+              : ImmutableList.of();
+
+      KosabiPluginOptions kosabiPluginOptions =
+          new KosabiPluginOptions(extraParams.getKosabiPluginOptions());
+
+      String moduleName = buildTargetValueExtraParams.getModuleName();
+      String kotlinPluginGeneratedFullPath =
+          buildCellRootPath.resolve(kotlincPluginGeneratedOutput).toString();
+
+      Builder<IsolatedStep> postKotlinCompilationSteps = ImmutableList.builder();
+      Builder<IsolatedStep> postKotlinCompilationFailureSteps = ImmutableList.builder();
+
+      postKotlinCompilationSteps.add(
+          CopyIsolatedStep.forDirectory(
+              kotlincPluginGeneratedOutput,
+              annotationGenFolder,
+              CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+
+      JavacPluginParams annotationProcessorParams =
+          extraParams.getResolvedJavacOptions().getJavaAnnotationProcessorParams();
+
+      ImmutableList<AbsPath> kotlinHomeLibraries = extraParams.getKotlinHomeLibraries();
+
+      KaptStepsBuilder.prepareKaptProcessorsIfNeeded(
+          invokingRule,
+          buildCellRootPath,
+          steps,
+          buildTargetValueExtraParams,
+          extraParams.getJvmTarget(),
+          extraParams.getStandardLibraryClassPath(),
+          extraParams.getAnnotationProcessingClassPath(),
+          outputDirectory,
+          annotationGenFolder,
+          javacSourceBuilder,
+          reportsOutput,
+          parameters.getShouldTrackClassUsage(),
+          postKotlinCompilationSteps,
+          annotationProcessorParams,
+          extraParams.getExtraKotlincArguments(),
+          sourceFilePaths,
+          pathToSrcsList,
+          allClasspaths,
+          kotlinHomeLibraries,
+          kotlinc,
+          compilerOutputPaths,
+          buckOut,
+          extraParams.getKotlinCompilerPlugins(),
+          kotlinPluginGeneratedFullPath,
+          moduleName,
+          kotlinCDAnalytics,
+          sourceWithStubsAndKaptAndKspOutputBuilder,
+          sourceWithStubsAndKaptOutputBuilder,
+          extraParams.getLanguageVersion());
+      ImmutableList.Builder<AbsPath> compilationClasspathBuilder =
+          buildCompilationClasspath(parameters, extraParams);
+
+      prepareKosabiStubgenIfNeeded(
+          buckOut,
+          buildCellRootPath,
+          invokingRule,
+          parameters,
+          steps,
+          extraParams,
+          buildTargetValueExtraParams,
+          sourceWithStubsAndKaptOutputBuilder,
+          sourceWithStubsAndKaptAndKspOutputBuilder,
+          outputDirectory,
+          sourceFilePaths,
+          pathToSrcsList,
+          allClasspaths,
+          reportsOutput,
+          kotlinc,
+          kosabiPluginOptions.getAllKosabiPlugins(),
+          compilationClasspathBuilder,
+          postKotlinCompilationFailureSteps,
+          kotlinCDAnalytics,
+          extraParams.getLanguageVersion());
+
+      prepareKspProcessorsIfNeeded(
+          Optional.ofNullable(actionMetadata),
+          extraParams,
+          invokingRule,
+          buildCellRootPath,
+          steps,
+          postKotlinCompilationSteps,
+          buildTargetValueExtraParams,
+          outputDirectory,
+          annotationGenFolder,
+          javacSourceBuilder,
+          reportsOutput,
+          parameters.getShouldTrackClassUsage(),
+          allClasspaths,
+          kotlinPluginGeneratedFullPath,
+          buildTargetValueExtraParams.getCellRelativeBasePath(),
+          annotationProcessorParams,
+          sourceWithStubsAndKaptOutputBuilder.build(),
+          pathToSrcsList,
+          kotlinHomeLibraries,
+          kotlinc,
+          compilerOutputPaths,
+          buckOut,
+          kosabiPluginOptions.getKosabiPlugins(),
+          sourceWithStubsAndKaptAndKspOutputBuilder,
+          compilationClasspathBuilder.build(),
+          moduleName,
+          kotlinCDAnalytics);
+
+      // Reduced SO-ABI classpath for the applicability plugin (rfsoa +
+      // source_only_abi_deps only). Distinct from compilationClasspath which
+      // contains the full dep set during library builds.
+      ImmutableList<AbsPath> applicabilityClasspath = extraParams.getApplicabilityClasspath();
+
+      KotlinCStepsBuilder.prepareKotlinCompilation(
+          buckOut,
+          buildCellRootPath,
+          invokingRule,
+          parameters,
+          steps,
+          actionMetadata,
+          extraParams,
+          friendPathsArg,
+          kotlinPluginGeneratedFullPath,
+          moduleName,
+          kotlinOutputDirectory,
+          sourceWithStubsAndKaptAndKspOutputBuilder,
+          pathToSrcsList,
+          allClasspaths,
+          reportsOutput,
+          kotlinc,
+          kosabiPluginOptions,
+          compilationClasspathBuilder.build(),
+          applicabilityClasspath,
+          postKotlinCompilationFailureSteps,
+          classpathSnapshots,
+          kotlinCDAnalytics);
+      steps.addAll(postKotlinCompilationSteps.build());
+    }
+
+    ResolvedJavacOptions resolvedJavacOptions = extraParams.getResolvedJavacOptions();
+    if (hasKotlinSources) {
+      // Most of the time, KotlinC have ran annotation processing,
+      // so only run "java on mix" processors (very uncommon) on Javac
+      resolvedJavacOptions =
+          resolvedJavacOptions.withJavaAnnotationProcessorParams(
+              getRunsOnJavaOnlyProcessors(resolvedJavacOptions));
+    }
+
+    JavacStepsBuilder.prepareJavaCompilationIfNeeded(
+        invokingRule,
+        buildCellRootPath,
+        steps,
+        buckOut,
+        compilerOutputPathsValue,
+        parameters,
+        resolvedJavac,
+        resolvedJavacOptions,
+        parameters.getClasspathEntries(),
+        extraParams.getExtraClassPaths(),
+        hasKotlinSources
+            ? ImmutableList.of(kotlinOutputDirectory, outputDirectory)
+            : ImmutableList.of(outputDirectory),
+        javacSourceBuilder,
+        abiJarParameters);
+  }
+
+  @Override
+  protected void createCompileToJarStepImpl(
+      RelPath buckOut,
+      AbsPath buildCellRootPath,
+      BuildTargetValue target,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      CompilerParameters compilerParameters,
+      @Nullable JarParameters abiJarParameters,
+      @Nullable JarParameters libraryJarParameters,
+      Builder<IsolatedStep> steps,
+      ResolvedJavac resolvedJavac,
+      @Nullable ActionMetadata actionMetadata,
+      KotlinExtraParams extraParams) {
+
+    createCompileStep(
+        buckOut,
+        buildCellRootPath,
+        target,
+        compilerOutputPathsValue,
+        compilerParameters,
+        steps,
+        resolvedJavac,
+        actionMetadata,
+        extraParams,
+        abiJarParameters,
+        true);
+    steps.add(
+        new JarDirectoryStep(
+            abiJarParameters == null ? libraryJarParameters : abiJarParameters,
+            ImmutableSet.of(extraParams.getKotlinClassesDir())));
+  }
+
+  /**
+   * Retrieve Java only processors. They should run on javac even in kotlin modules. This means they
+   * would only take effect on java files in mix modules
+   */
+  static JavacPluginParams getRunsOnJavaOnlyProcessors(ResolvedJavacOptions resolvedJavacOptions) {
+    JavacPluginParams javaAnnotationProcessorParams =
+        resolvedJavacOptions.getJavaAnnotationProcessorParams();
+    ImmutableList<ResolvedJavacPluginProperties> filteredPluginProperties =
+        javaAnnotationProcessorParams.getPluginProperties().stream()
+            .filter(AnnotationProcessorUtils::isRunsOnJavaOnlyProcessor)
+            .collect(ImmutableList.toImmutableList());
+    // See https://fburl.com/diff/d1msdqm8
+    // If pluginProperties is empty, make sure parameters is empty too, or javac will complain
+    if (filteredPluginProperties.isEmpty()) {
+      return JavacPluginParams.EMPTY;
+    }
+    return new JavacPluginParams(
+        filteredPluginProperties, javaAnnotationProcessorParams.getParameters());
+  }
+
+  /**
+   * Builds the compilation classpath by combining regular classpath entries with the bootclasspath
+   * (which includes android.jar for Android targets). For library builds this is the full dep set;
+   * for SO-ABI builds it is the reduced set (rfsoa deps only).
+   *
+   * @param parameters Compiler parameters containing classpath entries
+   * @param extraParams Kotlin-specific parameters containing resolved javac options with
+   *     bootclasspath
+   * @return A builder containing all classpath entries (regular + bootclasspath) as absolute paths
+   */
+  static ImmutableList.Builder<AbsPath> buildCompilationClasspath(
+      CompilerParameters parameters, KotlinExtraParams extraParams) {
+    ImmutableList.Builder<AbsPath> compilationClasspathBuilder =
+        ImmutableList.<AbsPath>builder()
+            .addAll(
+                parameters.getClasspathEntries().stream()
+                    .map(RelPath::toAbsolutePath)
+                    .filter(ClasspathUtils::assertValidClasspathsPattern)
+                    .collect(Collectors.toList()));
+
+    compilationClasspathBuilder.addAll(
+        extraParams.getResolvedJavacOptions().getBootclasspathList().stream()
+            .map(RelPath::toAbsolutePath)
+            .filter(ClasspathUtils::assertValidClasspathsPattern)
+            .collect(Collectors.toList()));
+
+    return compilationClasspathBuilder;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/IncrementalCompilationValidator.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/IncrementalCompilationValidator.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/IncrementalCompilationValidator.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.java.ActionMetadata;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.RebuildReason;
+import com.google.common.collect.ImmutableList;
+import javax.annotation.Nullable;
+
+public class IncrementalCompilationValidator {
+
+  public IncrementalCompilationValidator() {}
+
+  public @Nullable RebuildReason validate(
+      ImmutableList<RelPath> kotlinCompilerPlugins,
+      ActionMetadata actionMetadata,
+      @Nullable AbsPath depFile,
+      @Nullable AbsPath usedJars,
+      @Nullable AbsPath jvmAbiGenWorkingDir) {
+    if (actionMetadata.getPreviousIncrementalConfigDigest() == null) {
+      return RebuildReason.NO_LAST_BUILD_CONFIGURATION;
+    }
+
+    if (!actionMetadata
+        .getPreviousIncrementalConfigDigest()
+        .equals(actionMetadata.getCurrentIncrementalConfigDigest())) {
+      return RebuildReason.BUILD_CONFIGURATION_CHANGED;
+    }
+
+    if (depFile != null && !depFile.toFile().exists()) {
+      return RebuildReason.NO_LAST_DEP_FILE;
+    }
+
+    if (usedJars != null && !usedJars.toFile().exists()) {
+      return RebuildReason.NO_LAST_USED_JARS;
+    }
+
+    if (jvmAbiGenWorkingDir != null && !jvmAbiGenWorkingDir.toFile().exists()) {
+      return RebuildReason.NO_JVM_ABI_WORKING_DIR;
+    }
+
+    JarsActionMetadata jarsActionMetadata = new JarsActionMetadata(actionMetadata);
+    if (kotlinCompilerPlugins.stream().anyMatch(jarsActionMetadata::hasChanged)) {
+      return RebuildReason.KOTLIN_COMPILER_PLUGIN_CHANGED;
+    }
+
+    return null;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/JarsActionMetadata.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/JarsActionMetadata.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/JarsActionMetadata.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin
+
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.io.file.FileExtensionMatcher
+import com.facebook.buck.jvm.java.ActionMetadata
+import java.nio.file.Path
+
+class JarsActionMetadata(actionMetaData: ActionMetadata) {
+
+  val previousJarsDigest: Map<Path, String> =
+      actionMetaData.previousDigest.filter { (path, _) ->
+        val relPath = RelPath.of(path)
+        JAR_PATH_MATCHER.matches(relPath)
+      }
+
+  val currentJarsDigest: Map<Path, String> =
+      actionMetaData.currentDigest.filter { (path, _) ->
+        val relPath = RelPath.of(path)
+        JAR_PATH_MATCHER.matches(relPath)
+      }
+
+  fun hasChanged(relPath: RelPath): Boolean {
+    require(JAR_PATH_MATCHER.matches(relPath))
+
+    return previousJarsDigest[relPath.path] != currentJarsDigest[relPath.path]
+  }
+
+  companion object {
+    private val JAR_PATH_MATCHER = FileExtensionMatcher.of("jar")
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/JavacStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/JavacStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/JavacStepsBuilder.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.file.FileExtensionMatcher;
+import com.facebook.buck.io.file.PathMatcher;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.BaseJavacToJarStepFactory;
+import com.facebook.buck.jvm.java.CompilerOutputPathsValue;
+import com.facebook.buck.jvm.java.CompilerParameters;
+import com.facebook.buck.jvm.java.JarParameters;
+import com.facebook.buck.jvm.java.JavaExtraParams;
+import com.facebook.buck.jvm.java.ResolvedJavac;
+import com.facebook.buck.jvm.java.ResolvedJavacOptions;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSortedSet;
+
+public class JavacStepsBuilder {
+  private static final PathMatcher KOTLIN_PATH_MATCHER = FileExtensionMatcher.of("kt");
+
+  /**
+   * Prepares the Java compilation step for any Java files left to compile in this rule. This also
+   * compiles any Java files generated from annotation processors using KAPT and KSP.
+   */
+  public static void prepareJavaCompilationIfNeeded(
+      BuildTargetValue invokingRule,
+      AbsPath buildCellRootPath,
+      ImmutableList.Builder<IsolatedStep> steps,
+      RelPath buckOut,
+      CompilerOutputPathsValue compilerOutputPathsValue,
+      CompilerParameters parameters,
+      ResolvedJavac resolvedJavac,
+      ResolvedJavacOptions resolvedJavacOptions,
+      ImmutableList<RelPath> declaredClasspathEntries,
+      ImmutableList<AbsPath> extraClassPaths,
+      ImmutableList<RelPath> outputDirectories,
+      ImmutableSortedSet.Builder<RelPath> sourceBuilder,
+      JarParameters abiJarParameter) {
+
+    // Note that this filters out only .kt files, so this keeps both .java and .src.zip files.
+    ImmutableSortedSet<RelPath> javaSourceFiles =
+        sourceBuilder.build().stream()
+            .filter(input -> !KOTLIN_PATH_MATCHER.matches(input))
+            .collect(ImmutableSortedSet.toImmutableSortedSet(RelPath.comparator()));
+
+    // No point running javac if there is no source file
+    if (javaSourceFiles.isEmpty()) {
+      return;
+    }
+
+    CompilerParameters javacParameters =
+        new CompilerParameters(
+            javaSourceFiles,
+            buildClasspathEntries(
+                buildCellRootPath, outputDirectories, extraClassPaths, declaredClasspathEntries),
+            parameters.getClasspathSnapshots(),
+            parameters.getOutputPaths(),
+            parameters.getAbiGenerationMode(),
+            parameters.getAbiCompatibilityMode(),
+            parameters.getShouldTrackClassUsage(),
+            parameters.getSourceOnlyAbiRuleInfoFactory());
+
+    // Indicate no annotation processing required from this factory.  It is already handled by the
+    // Kotlin factory, when it resolves javac's options.
+    BaseJavacToJarStepFactory javacToJarStepFactory = new BaseJavacToJarStepFactory();
+
+    javacToJarStepFactory.createCompileStep(
+        buckOut,
+        buildCellRootPath,
+        invokingRule,
+        compilerOutputPathsValue,
+        javacParameters,
+        steps,
+        resolvedJavac,
+        null,
+        JavaExtraParams.of(
+            resolvedJavacOptions,
+            /* addAnnotationPath */ false,
+            /* skipIfNoCompilationUnits */ true),
+        abiJarParameter,
+        true);
+  }
+
+  private static ImmutableList<RelPath> buildClasspathEntries(
+      AbsPath buildCellRootPath,
+      ImmutableList<RelPath> outputDirectories,
+      ImmutableList<AbsPath> extraClassPaths,
+      ImmutableList<RelPath> declaredClasspathEntries) {
+    // Build classpath with outputDirectories first (preserving order), then other entries sorted
+    ImmutableList.Builder<RelPath> classpathBuilder = ImmutableList.builder();
+
+    classpathBuilder.addAll(outputDirectories);
+    classpathBuilder.addAll(
+        ImmutableSortedSet.orderedBy(RelPath.comparator())
+            .addAll(extraClassPaths.stream().map(buildCellRootPath::relativize).iterator())
+            .addAll(declaredClasspathEntries)
+            .build());
+
+    return classpathBuilder.build();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KaptStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KaptStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KaptStep.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersion;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.CompilerOutputPaths;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics;
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import java.nio.file.Path;
+import java.util.Optional;
+
+public class KaptStep extends KotlincStep {
+
+  private static final String VERBOSE = "-verbose";
+
+  KaptStep(
+      BuildTargetValue invokingRule,
+      Path outputDirectory,
+      ImmutableSortedSet<RelPath> sourceFilePaths,
+      Path pathToSrcsList,
+      ImmutableList<AbsPath> combinedClassPathEntries,
+      ImmutableList<AbsPath> kotlinHomeLibraries,
+      RelPath reportDirPath,
+      Kotlinc kotlinc,
+      ImmutableList<String> extraArguments,
+      CompilerOutputPaths outputPaths,
+      RelPath configuredBuckOut,
+      KotlinCDAnalytics kotlinCDAnalytics,
+      LanguageVersion languageVersion) {
+    super(
+        invokingRule,
+        outputDirectory,
+        sourceFilePaths,
+        pathToSrcsList,
+        combinedClassPathEntries,
+        kotlinHomeLibraries,
+        reportDirPath,
+        kotlinc,
+        extraArguments,
+        ImmutableList.of(VERBOSE),
+        outputPaths,
+        false,
+        configuredBuckOut,
+        ImmutableMap.of(),
+        null,
+        ImmutableList.of(),
+        ImmutableList.of(),
+        false,
+        ImmutableList.of(),
+        Optional.empty(),
+        KotlincMode.NonIncremental.INSTANCE,
+        kotlinCDAnalytics,
+        languageVersion,
+        // Flag turning on/off K2 support for jvm-abi-gen actions
+        // not part of KAPT, since jvm-abi-gen doesn't run on KAPT steps
+        false);
+  }
+
+  @Override
+  public String getShortName() {
+    return "kapt";
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KaptStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KaptStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KaptStepsBuilder.java
@@ -0,0 +1,367 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import static com.facebook.buck.jvm.java.CompilerOutputPaths.getKAPTDepFilePath;
+import static com.facebook.buck.jvm.java.JavaPaths.SRC_ZIP;
+import static com.facebook.buck.jvm.kotlin.AnnotationProcessorUtils.encodeOptions;
+import static com.facebook.buck.jvm.kotlin.AnnotationProcessorUtils.isKSPProcessor;
+import static com.facebook.buck.jvm.kotlin.AnnotationProcessorUtils.isRunsOnJavaOnlyProcessor;
+import static com.facebook.buck.jvm.kotlin.AnnotationProcessorUtils.urlToFile;
+import static com.facebook.buck.jvm.kotlin.CompilerPluginUtils.MODULE_NAME;
+import static com.facebook.buck.jvm.kotlin.CompilerPluginUtils.getKotlinCompilerPluginsArgs;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.filesystem.CopySourceMode;
+import com.facebook.buck.jvm.cd.command.kotlin.KotlinSupportedLanguageVersion;
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersion;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.core.BuildTargetValueExtraParams;
+import com.facebook.buck.jvm.java.CompilerOutputPaths;
+import com.facebook.buck.jvm.java.JavacPluginParams;
+import com.facebook.buck.jvm.java.ResolvedJavacPluginProperties;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics;
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.CopyIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MakeCleanDirectoryIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.ZipIsolatedStep;
+import com.facebook.buck.util.zip.ZipCompressionLevel;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class KaptStepsBuilder {
+
+  private static final String KAPT3_PLUGIN = "plugin:org.jetbrains.kotlin.kapt3:";
+  private static final String AP_CLASSPATH_ARG = KAPT3_PLUGIN + "apclasspath=";
+  private static final String AP_PROCESSORS_ARG = KAPT3_PLUGIN + "processors=";
+  // output path for generated sources;
+  private static final String SOURCES_ARG = KAPT3_PLUGIN + "sources=";
+  private static final String CLASSES_ARG = KAPT3_PLUGIN + "classes=";
+  // output path for java stubs;
+  private static final String STUBS_ARG = KAPT3_PLUGIN + "stubs=";
+  private static final String LIGHT_ANALYSIS = KAPT3_PLUGIN + "useLightAnalysis=";
+  private static final String CORRECT_ERROR_TYPES = KAPT3_PLUGIN + "correctErrorTypes=";
+  private static final String JAVAC_ARG = KAPT3_PLUGIN + "javacArguments=";
+  private static final String AP_OPTIONS = KAPT3_PLUGIN + "apoptions=";
+  private static final String AP_FILE_ACCESS_HIST_REPORT_ARG =
+      KAPT3_PLUGIN + "dumpFileReadHistory=";
+  private static final String KAPT_USE_K2 = KAPT3_PLUGIN + "useK2=";
+  private static final String KAPT_GENERATED = "kapt.kotlin.generated";
+  public static final String PLUGIN = "-P";
+  public static final String AP_STATS_REPORT_FILE = "ap_stats.report";
+  public static final String AP_ERROR_REPORT_PATH = "ap_error.report";
+  public static final String AP_ERROR_REPORT_OPTION_NAME = "error_report";
+  public static final String APT_MODE = "aptMode=";
+  public static final String X_PLUGIN_ARG = "-Xplugin=";
+  private static final String KOTLINC_KAPT_USE_USE_KAPT4_OLD = "-Xuse-kapt4";
+  private static final String KOTLINC_KAPT_USE_K2 = "-Xuse-k2-kapt";
+
+  /**
+   * Creates the necessary steps, folders and parameters needed to run annotation processors using
+   * KAPT.
+   *
+   * <p>This method will do nothing if there are no relevant annotation processors to run.
+   */
+  public static void prepareKaptProcessorsIfNeeded(
+      BuildTargetValue invokingRule,
+      AbsPath rootCellPath,
+      ImmutableList.Builder<IsolatedStep> steps,
+      BuildTargetValueExtraParams buildTargetValueExtraParams,
+      Optional<String> jvmTarget,
+      AbsPath resolvedKotlinStandardLibraryClassPath,
+      AbsPath resolvedAnnotationProcessingClassPath,
+      RelPath outputDirectory,
+      RelPath annotationGenFolder,
+      ImmutableSortedSet.Builder<RelPath> javacSourceBuilder,
+      RelPath reportsOutput,
+      boolean shouldTrackClassUsage,
+      ImmutableList.Builder<IsolatedStep> postKotlinCompilationSteps,
+      JavacPluginParams javaAnnotationProcessorParams,
+      ImmutableList<String> extraKotlincArguments,
+      ImmutableSortedSet<RelPath> sourceFilePaths,
+      Path pathToSrcsList,
+      ImmutableList<AbsPath> allClasspaths,
+      ImmutableList<AbsPath> kotlinHomeLibraries,
+      Kotlinc kotlinc,
+      CompilerOutputPaths compilerOutputPaths,
+      RelPath configuredBuckOut,
+      ImmutableMap<AbsPath, ImmutableMap<String, String>> resolvedKotlinCompilerPlugins,
+      String kotlinPluginGeneratedOutFullPath,
+      String moduleName,
+      KotlinCDAnalytics kotlinCDAnalytics,
+      ImmutableSortedSet.Builder<RelPath> sourceWithStubsAndKaptAndKspOutputBuilder,
+      ImmutableSortedSet.Builder<RelPath> sourceWithStubsAndKaptOutputBuilder,
+      LanguageVersion kotlinLanguageVersion) {
+    // We don't need the Kapt processor to run for source-only-abi
+    if (invokingRule.isSourceOnlyAbi()) {
+      return;
+    }
+
+    // We need to generate the KAPT generation folder anyway, to help IntelliJ with red symbols.
+    RelPath kaptAnnotationGenFolder = buildTargetValueExtraParams.getKaptAnnotationGenPath();
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kaptAnnotationGenFolder));
+
+    ImmutableList<ResolvedJavacPluginProperties> kaptAnnotationProcessors =
+        getKaptAnnotationProcessors(
+            AnnotationProcessorUtils.getAnnotationProcessors(javaAnnotationProcessorParams));
+
+    // No annotation processors for KAPT
+    if (kaptAnnotationProcessors.isEmpty()) {
+      return;
+    }
+
+    // KAPT folders
+    RelPath kaptSourcesOutput =
+        buildTargetValueExtraParams.getAnnotationOutputPath("__%s_kapt_sources__");
+    RelPath kaptClassesOutput =
+        buildTargetValueExtraParams.getAnnotationOutputPath("__%s_kapt_classes__");
+    RelPath stubsOutput = buildTargetValueExtraParams.getAnnotationOutputPath("__%s_kapt_stubs__");
+    RelPath kaptGeneratedOutput =
+        buildTargetValueExtraParams.getAnnotationOutputPath("__%s_kapt_generated__");
+    RelPath kaptGenOutputFolder = buildTargetValueExtraParams.getGenPath("__%s_kapt_gen_sources__");
+    RelPath kaptGenOutput =
+        buildTargetValueExtraParams.getGenPath("__%s_kapt_gen_sources__/generated" + SRC_ZIP);
+
+    // Creating KAPT dirs
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kaptClassesOutput));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kaptSourcesOutput));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(stubsOutput));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kaptGeneratedOutput));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kaptGenOutputFolder));
+
+    ImmutableList<String> kaptProcessorsArg =
+        ImmutableList.copyOf(
+            kaptAnnotationProcessors.stream()
+                .map(ResolvedJavacPluginProperties::getProcessorNames)
+                .flatMap(Set::stream)
+                .map(name -> AP_PROCESSORS_ARG + name)
+                .collect(Collectors.toList()));
+
+    ImmutableList<String> kaptPluginsClasspath =
+        ImmutableList.copyOf(
+            kaptAnnotationProcessors.stream()
+                .map(p -> p.toUrlClasspath(rootCellPath))
+                .flatMap(List::stream)
+                .map(url -> AP_CLASSPATH_ARG + rootCellPath.resolve(urlToFile(url)))
+                .collect(Collectors.toList()));
+
+    ImmutableMap.Builder<String, String> apOptions = new ImmutableMap.Builder<>();
+
+    ImmutableSortedSet<String> javacAnnotationProcessorParams =
+        javaAnnotationProcessorParams.getParameters();
+    for (String param : javacAnnotationProcessorParams) {
+      String[] splitParam = param.split("=");
+      Preconditions.checkState(splitParam.length == 2);
+      apOptions.put(splitParam[0], splitParam[1]);
+    }
+    Path annotationProcessorsStatsFilePath =
+        rootCellPath.resolve(reportsOutput).resolve(AP_STATS_REPORT_FILE).getPath();
+
+    // write annotation processor error reports to this path
+    Path annotationProcessorsErrorReportPath =
+        rootCellPath.resolve(reportsOutput).resolve(AP_ERROR_REPORT_PATH).getPath();
+    apOptions.put(AP_ERROR_REPORT_OPTION_NAME, annotationProcessorsErrorReportPath.toString());
+
+    ImmutableList.Builder<String> kaptPluginOptionsBuilder =
+        ImmutableList.<String>builder()
+            .add(
+                AP_CLASSPATH_ARG
+                    + rootCellPath.resolve(resolvedAnnotationProcessingClassPath.getPath()))
+            .add(
+                AP_CLASSPATH_ARG
+                    + rootCellPath.resolve(resolvedKotlinStandardLibraryClassPath.getPath()))
+            .addAll(kaptPluginsClasspath)
+            .addAll(kaptProcessorsArg)
+            .add(SOURCES_ARG + rootCellPath.resolve(kaptSourcesOutput))
+            .add(CLASSES_ARG + rootCellPath.resolve(kaptClassesOutput))
+            .add(STUBS_ARG + rootCellPath.resolve(stubsOutput))
+            .add(
+                AP_OPTIONS
+                    + encodeKaptApOptions(
+                        apOptions.build(), rootCellPath.resolve(kaptGeneratedOutput).toString()))
+            .add(JAVAC_ARG + encodeOptions(getJavacArguments(jvmTarget)))
+            .add(LIGHT_ANALYSIS + "true") // TODO: Provide value as argument
+            .add(CORRECT_ERROR_TYPES + "true");
+
+    if (isKapt4SupportedForCurrentKotlinLanguageVersion(kotlinLanguageVersion)) {
+      kaptPluginOptionsBuilder.add(KAPT_USE_K2 + "true");
+    }
+
+    if (shouldTrackClassUsage) {
+      kaptPluginOptionsBuilder.add(
+          AP_FILE_ACCESS_HIST_REPORT_ARG + rootCellPath.resolve(getKAPTDepFilePath(reportsOutput)));
+    }
+    ImmutableList.Builder<String> annotationProcessingOptionsBuilder =
+        ImmutableList.<String>builder()
+            .add(X_PLUGIN_ARG + resolvedAnnotationProcessingClassPath)
+            .add(PLUGIN)
+            .add(
+                KAPT3_PLUGIN
+                    + APT_MODE
+                    + "stubsAndApt,"
+                    + Joiner.on(",").join(kaptPluginOptionsBuilder.build()))
+            .add(MODULE_NAME)
+            .add(moduleName);
+
+    // Use kapt4 or kapt3 base on language version is 1.9 or 2.0+
+    if (isKapt4SupportedForCurrentKotlinLanguageVersion(kotlinLanguageVersion)) {
+      // Notice K2 and KAPT4 can no longer use K1 DI plugin, so we no longer pass it
+      // What it miss is the DI plugin's analysis part, which is needed BEFORE annotation
+      // processing, the main KotlincStep still get k2 DI transformation plugin
+      // Because of that, KAPT+DI should be avoided and migrate to KSP+DI ASAP,
+      // and modules who still use KAPT+DI must turn off k2 and fallback to k1 and kapt3.
+      annotationProcessingOptionsBuilder.add(getKapt4Flag(kotlinLanguageVersion));
+      annotationProcessingOptionsBuilder.addAll(
+          getOtherPluginsRequiredForKapt4(
+              resolvedKotlinCompilerPlugins, kotlinPluginGeneratedOutFullPath));
+    } else {
+      annotationProcessingOptionsBuilder.addAll(
+          getOtherPluginsRequiredForKapt3(
+              resolvedKotlinCompilerPlugins, kotlinPluginGeneratedOutFullPath));
+    }
+
+    steps.add(
+        new KaptStep(
+            invokingRule,
+            outputDirectory.getPath(),
+            sourceFilePaths,
+            pathToSrcsList,
+            allClasspaths,
+            kotlinHomeLibraries,
+            reportsOutput,
+            kotlinc,
+            annotationProcessingOptionsBuilder.build(),
+            compilerOutputPaths,
+            configuredBuckOut,
+            kotlinCDAnalytics,
+            kotlinLanguageVersion));
+
+    steps.add(
+        CopyIsolatedStep.forDirectory(
+            kaptSourcesOutput, kaptAnnotationGenFolder, CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+    steps.add(
+        CopyIsolatedStep.forDirectory(
+            kaptClassesOutput, kaptAnnotationGenFolder, CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+    steps.add(
+        CopyIsolatedStep.forDirectory(
+            kaptGeneratedOutput, kaptAnnotationGenFolder, CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+
+    steps.add(
+        new ZipIsolatedStep(
+            rootCellPath,
+            kaptGenOutput.getPath(),
+            ImmutableSet.of(),
+            ImmutableSet.of(),
+            false,
+            ZipCompressionLevel.DEFAULT,
+            kaptAnnotationGenFolder.getPath()));
+
+    steps.add(
+        CopyIsolatedStep.forDirectory(
+            kaptAnnotationGenFolder, annotationGenFolder, CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+
+    // Generated classes should be part of the output. This way generated files
+    // such as META-INF dirs will also be added to the final jar.
+    postKotlinCompilationSteps.add(
+        CopyIsolatedStep.forDirectory(
+            kaptClassesOutput.getPath(),
+            outputDirectory.getPath(),
+            CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+
+    sourceWithStubsAndKaptAndKspOutputBuilder.add(kaptGenOutput);
+    sourceWithStubsAndKaptOutputBuilder.add(kaptGenOutput);
+    javacSourceBuilder.add(kaptGenOutput);
+  }
+
+  private static String getKapt4Flag(LanguageVersion kotlinLanguageVersion) {
+    if (kotlinLanguageVersion.isGreaterOrEqual(KotlinSupportedLanguageVersion.V2_1)) {
+      return KOTLINC_KAPT_USE_K2;
+    }
+
+    return KOTLINC_KAPT_USE_USE_KAPT4_OLD;
+  }
+
+  /**
+   * KAPT4 should only be turned on for k2 targets. Targets that can't use k2 or can't use kapt4
+   * shall use [k2=False] which ensure they get [-language-version=1.9] and fail the condition here.
+   */
+  public static boolean isKapt4SupportedForCurrentKotlinLanguageVersion(
+      LanguageVersion kotlinLanguageVersion) {
+    return kotlinLanguageVersion.getSupportsK2();
+  }
+
+  static ImmutableList<ResolvedJavacPluginProperties> getKaptAnnotationProcessors(
+      ImmutableList<ResolvedJavacPluginProperties> annotationProcessors) {
+    return annotationProcessors.stream()
+        .filter(prop -> !isKSPProcessor(prop) && !isRunsOnJavaOnlyProcessor(prop))
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  private static String encodeKaptApOptions(
+      Map<String, String> kaptApOptions, String kaptGeneratedPath) {
+    Map<String, String> kaptApOptionsToEncode = new HashMap<>();
+    kaptApOptionsToEncode.put(KAPT_GENERATED, kaptGeneratedPath);
+    kaptApOptionsToEncode.putAll(kaptApOptions);
+
+    return encodeOptions(kaptApOptionsToEncode);
+  }
+
+  private static Map<String, String> getJavacArguments(Optional<String> jvmTarget) {
+    Map<String, String> arguments = new HashMap<>();
+    jvmTarget.ifPresent(
+        target -> {
+          arguments.put("-source", target);
+          arguments.put("-target", target);
+        });
+    return arguments;
+  }
+
+  /**
+   * Plugins required to run on the KotlincStep for KAPT3, excluding kapt3 itself. So far it's DI
+   * and Kotlin all-open, because (1) KAPT+DI need DI K1 plugin to do an analysis and codegen before
+   * it, (2) kotlin all-open also need to run before KAPT to avoid crashing during KAPT
+   */
+  private static ImmutableList<String> getOtherPluginsRequiredForKapt3(
+      ImmutableMap<AbsPath, ImmutableMap<String, String>> resolvedKotlinCompilerPlugins,
+      String outputDir) {
+    return getKotlinCompilerPluginsArgs(
+        resolvedKotlinCompilerPlugins,
+        outputDir,
+        (sourcePath, pluginOptions) ->
+            CompilerPluginUtils.isDiK1PluginForKapt(sourcePath, pluginOptions)
+                || CompilerPluginUtils.isKotlinAllOpenPlugin(sourcePath, pluginOptions));
+  }
+
+  /**
+   * Plugins required to run on the KotlincStep for KAPT4, excluding kapt4 itself. So far just
+   * Kotlin all-open. Notice DI K2 plugin only kept the transform functionality, which is only
+   * useful in main KotlincStep, no need to run on KAPT KotlincStep.
+   */
+  private static ImmutableList<String> getOtherPluginsRequiredForKapt4(
+      ImmutableMap<AbsPath, ImmutableMap<String, String>> resolvedKotlinCompilerPlugins,
+      String outputDir) {
+    return getKotlinCompilerPluginsArgs(
+        resolvedKotlinCompilerPlugins, outputDir, CompilerPluginUtils::isKotlinAllOpenPlugin);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiConfig.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiConfig.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiConfig.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+/** Configuration for Kosabi plugin. */
+public abstract class KosabiConfig {
+  public static final String PROPERTY_KOSABI_APPLICABILITY_PLUGIN = "kosabi_applicability_plugin";
+
+  public static final String PROPERTY_KOSABI_APPLICABILITY_CELL_ROOT =
+      "kosabi_applicability_cell_root";
+
+  public static final String PROPERTY_KOSABI_STUBS_GEN_K2_PLUGIN = "kosabi_stubs_gen_k2_plugin";
+
+  public static final String PROPERTY_KOSABI_JVM_ABI_GEN_K2_PLUGIN = "kosabi_jvm_abi_gen_k2_plugin";
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiPluginOptions.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiPluginOptions.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiPluginOptions.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+
+public class KosabiPluginOptions {
+  private final ImmutableMap<String, AbsPath> resolvedKosabiPluginOptionPath;
+
+  public KosabiPluginOptions(ImmutableMap<String, AbsPath> resolvedKosabiPluginOptionPath) {
+    this.resolvedKosabiPluginOptionPath = resolvedKosabiPluginOptionPath;
+  }
+
+  public ImmutableMap<String, AbsPath> getAllKosabiPlugins() {
+    return resolvedKosabiPluginOptionPath;
+  }
+
+  private ImmutableMap<String, AbsPath> getAllKosabiPluginsExceptStubgen() {
+    return resolvedKosabiPluginOptionPath.entrySet().stream()
+        .filter(entry -> !KosabiConfig.PROPERTY_KOSABI_STUBS_GEN_K2_PLUGIN.equals(entry.getKey()))
+        .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
+  }
+
+  public ImmutableMap<String, AbsPath> getKosabiPlugins() {
+    return getAllKosabiPluginsExceptStubgen();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiStubgenStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiStubgenStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiStubgenStep.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersion;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.CompilerOutputPaths;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics;
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import java.nio.file.Path;
+import java.util.Optional;
+import javax.annotation.Nullable;
+
+/**
+ * Kosabi Stubgen Step A step to run Kosabi's stubgen (generate stubs & run source modifier to
+ * stripped srcs) for source only build Currently, it's based on KotlinC and simply run existing
+ * stubgen plugins with configurations to output stripped srcs as artifact for further compilation
+ * steps Later we could move away from KotlinC and explore possibility to use Kotlin Analysis API
+ * for output stripped srcs
+ */
+public class KosabiStubgenStep extends KotlincStep {
+  private final RelPath stubgenDir;
+  private final RelPath stubClassOutputDir;
+
+  private final String pluginPath;
+
+  KosabiStubgenStep(
+      BuildTargetValue invokingRule,
+      Path outputDirectory,
+      ImmutableSortedSet<RelPath> sourceFilePaths,
+      Path pathToSrcsList,
+      ImmutableList<AbsPath> combinedClassPathEntries,
+      ImmutableList<AbsPath> kotlinHomeLibraries,
+      RelPath reportDirPath,
+      Kotlinc kotlinc,
+      ImmutableList<String> extraArguments,
+      ImmutableList<String> verboseModeOnlyExtraArguments,
+      CompilerOutputPaths outputPaths,
+      boolean trackClassUsage,
+      RelPath configuredBuckOut,
+      ImmutableMap<String, AbsPath> resolvedKosabiPluginOptionPath,
+      @Nullable String kosabiJvmAbiGenEarlyTerminationMessagePrefix,
+      ImmutableList<AbsPath> compilationClasspath,
+      boolean verifySourceOnlyAbiConstraints,
+      ImmutableList<IsolatedStep> postKotlinCompilationFailureSteps,
+      Optional<AbsPath> depTrackerPath,
+      RelPath stubgenDir,
+      @Nullable RelPath stubClassOutputDir,
+      KotlinCDAnalytics kotlinCDAnalytics,
+      LanguageVersion languageVersion) {
+
+    super(
+        invokingRule,
+        outputDirectory,
+        sourceFilePaths,
+        pathToSrcsList,
+        combinedClassPathEntries,
+        kotlinHomeLibraries,
+        reportDirPath,
+        kotlinc,
+        extraArguments,
+        verboseModeOnlyExtraArguments,
+        outputPaths,
+        false, // trackClassUsage
+        configuredBuckOut,
+        resolvedKosabiPluginOptionPath,
+        kosabiJvmAbiGenEarlyTerminationMessagePrefix,
+        compilationClasspath,
+        ImmutableList.of(),
+        verifySourceOnlyAbiConstraints,
+        postKotlinCompilationFailureSteps,
+        depTrackerPath,
+        KotlincMode.NonIncremental.INSTANCE,
+        kotlinCDAnalytics,
+        languageVersion,
+        // Flag turning on/off K2 support for jvm-abi-gen actions
+        // not part of stubsgen, since jvm-abi-gen doesn't run on stubsgen steps
+        false);
+    this.stubgenDir = stubgenDir;
+    this.stubClassOutputDir = stubClassOutputDir;
+    this.pluginPath = "plugin:com.facebook.kotlin.compilerplugins.kosabi.stubsgen_k2";
+  }
+
+  @Override
+  public String getShortName() {
+    return KosabiStubgenStep.class.getSimpleName();
+  }
+
+  @Override
+  protected void configureSourceOnlyOptions(
+      ImmutableList.Builder<String> builder,
+      LanguageVersion languageVersion,
+      AbsPath ruleCellRoot) {
+    super.configureSourceOnlyOptions(builder, languageVersion, ruleCellRoot);
+    builder.add("-P");
+    builder.add(pluginPath + ":stubsgen-dir=" + stubgenDir.toString());
+
+    if (stubClassOutputDir != null) {
+      builder.add("-P");
+      builder.add(pluginPath + ":stubs-class-dir=" + stubClassOutputDir.toString());
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiStubgenStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiStubgenStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KosabiStubgenStepsBuilder.java
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import static com.facebook.buck.jvm.java.JavaPaths.SRC_ZIP;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.cd.command.kotlin.KotlinExtraParams;
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersion;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.core.BuildTargetValueExtraParams;
+import com.facebook.buck.jvm.java.CompilerParameters;
+import com.facebook.buck.jvm.java.JarParameters;
+import com.facebook.buck.jvm.java.RemoveClassesPatternsMatcher;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics;
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MakeCleanDirectoryIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.ZipIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.java.JarDirectoryStep;
+import com.facebook.buck.util.zip.ZipCompressionLevel;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.Optional;
+import java.util.logging.Level;
+
+public class KosabiStubgenStepsBuilder {
+  private static final String VERBOSE = "-verbose";
+
+  public static void prepareKosabiStubgenIfNeeded(
+      RelPath buckOut,
+      AbsPath buildCellRootPath,
+      BuildTargetValue invokingRule,
+      CompilerParameters parameters,
+      ImmutableList.Builder<IsolatedStep> steps,
+      KotlinExtraParams extraParams,
+      BuildTargetValueExtraParams buildTargetValueExtraParams,
+      ImmutableSortedSet.Builder<RelPath> sourceWithStubsOutputBuilder,
+      ImmutableSortedSet.Builder<RelPath> sourceWithKSPOutputBuilder,
+      RelPath outputDirectory,
+      ImmutableSortedSet<RelPath> sourceFilePaths,
+      Path pathToSrcsList,
+      ImmutableList<AbsPath> allClasspaths,
+      RelPath reportsOutput,
+      Kotlinc kotlinc,
+      ImmutableMap<String, AbsPath> allKosabiPluginOptionPath,
+      ImmutableList.Builder<AbsPath> compilationClasspathBuilder,
+      ImmutableList.Builder<IsolatedStep> postKotlinCompilationFailureSteps,
+      KotlinCDAnalytics kotlinCDAnalytics,
+      LanguageVersion languageVersion) {
+    ImmutableSortedSet<RelPath> stubsGenOutputPath;
+    if (invokingRule.isSourceOnlyAbi()) {
+
+      if (allKosabiPluginOptionPath.isEmpty()) {
+        throw new RuntimeException(
+            "Building Kotlin SourceOnlyAbi without Kosabi plugins setup, please check if Kosabi is"
+                + " turn off (kotlin.enable_source_only_abi == false), or remove"
+                + " abi_generation_mode=\"source_only\" from the target.");
+      }
+
+      RelPath stubgenOutputDir = buildTargetValueExtraParams.getGenPath("__%s_stubgen_stubs__");
+      RelPath stubgenClassOutputDir =
+          buildTargetValueExtraParams.getGenPath("__%s_stubgen_stubs_class__");
+
+      RelPath stubsJar = buildTargetValueExtraParams.getGenPath("__%s_stubgen_stubs.jar");
+      compilationClasspathBuilder.add(stubsJar.toAbsolutePath());
+
+      RelPath stubsOutputZipDir =
+          buildTargetValueExtraParams.getGenPath("__%s_stubgen_stubs_zip__");
+
+      // As we don't know all the files that will be generated by stubgen, we need to have a zip
+      // step to archive the stubs to get a deterministic path, so that we can use it as
+      // input for further compilation step.
+      RelPath stubsZip =
+          buildTargetValueExtraParams.getGenPath("__%s_stubgen_stubs_zip__/stubs" + SRC_ZIP);
+
+      ImmutableSortedSet.Builder<RelPath> stubgenSrcPathBuilder = null;
+      stubgenSrcPathBuilder = ImmutableSortedSet.orderedBy(RelPath.comparator());
+      stubgenSrcPathBuilder.add(stubsZip);
+      stubsGenOutputPath = stubgenSrcPathBuilder.build();
+      sourceWithStubsOutputBuilder.addAll(stubsGenOutputPath);
+      sourceWithKSPOutputBuilder.addAll(stubsGenOutputPath);
+
+      steps.addAll(MakeCleanDirectoryIsolatedStep.of(stubgenOutputDir));
+      steps.addAll(MakeCleanDirectoryIsolatedStep.of(stubsOutputZipDir));
+
+      steps.add(
+          new KosabiStubgenStep(
+              invokingRule,
+              outputDirectory.getPath(),
+              sourceFilePaths,
+              pathToSrcsList,
+              allClasspaths,
+              extraParams.getKotlinHomeLibraries(),
+              reportsOutput,
+              kotlinc,
+              ImmutableList.of(),
+              ImmutableList.of(VERBOSE),
+              parameters.getOutputPaths(),
+              parameters.getShouldTrackClassUsage(),
+              buckOut,
+              allKosabiPluginOptionPath.entrySet().stream()
+                  .filter(
+                      entry ->
+                          KosabiConfig.PROPERTY_KOSABI_STUBS_GEN_K2_PLUGIN.equals(entry.getKey()))
+                  .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)),
+              "Terminating compilation. We're done with Stubgen.",
+              compilationClasspathBuilder.build(),
+              extraParams.getShouldVerifySourceOnlyAbiConstraints(),
+              postKotlinCompilationFailureSteps.build(),
+              extraParams.getDepTrackerPlugin(),
+              stubgenOutputDir,
+              stubgenClassOutputDir,
+              kotlinCDAnalytics,
+              languageVersion));
+
+      steps.add(
+          new ZipIsolatedStep(
+              buildCellRootPath,
+              stubsZip.getPath(),
+              ImmutableSet.of(),
+              ImmutableSet.of(),
+              false,
+              ZipCompressionLevel.DEFAULT,
+              stubgenOutputDir.getPath()));
+
+      steps.add(
+          new JarDirectoryStep(
+              new JarParameters(
+                  false,
+                  true,
+                  stubsJar,
+                  RemoveClassesPatternsMatcher.EMPTY,
+                  ImmutableSortedSet.orderedBy(RelPath.comparator())
+                      .add(stubgenClassOutputDir)
+                      .build(),
+                  ImmutableSortedSet.of(),
+                  Optional.empty(),
+                  Optional.empty(),
+                  Level.INFO)));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCDLoggingContextFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCDLoggingContextFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCDLoggingContextFactory.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersion;
+import com.facebook.buck.jvm.kotlin.cd.analytics.ClasspathChangesParam;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDLoggingContext;
+import com.facebook.buck.jvm.kotlin.cd.analytics.ModeParam;
+import com.facebook.buck.jvm.kotlin.cd.analytics.StepParam;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.ClasspathChanges;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlinSourceChanges;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class KotlinCDLoggingContextFactory {
+
+  private KotlinCDLoggingContextFactory() {}
+
+  public static KotlinCDLoggingContext create(
+      KotlincStep kotlincStep, LanguageVersion languageVersion, KotlincMode kotlincMode) {
+    return new KotlinCDLoggingContext(create(kotlincStep), languageVersion, create(kotlincMode));
+  }
+
+  private static ModeParam create(KotlincMode kotlincMode) {
+    if (kotlincMode instanceof KotlincMode.NonIncremental) {
+      return ModeParam.NonIncremental.INSTANCE;
+    } else if (kotlincMode instanceof KotlincMode.Incremental) {
+      KotlincMode.Incremental incrementalMode = (KotlincMode.Incremental) kotlincMode;
+      Set<AbsPath> removedFiles = null;
+      Set<AbsPath> modifiedFiles = null;
+
+      if (incrementalMode.getKotlinSourceChanges() instanceof KotlinSourceChanges.Known) {
+        KotlinSourceChanges.Known knownSourceChanges =
+            (KotlinSourceChanges.Known) incrementalMode.getKotlinSourceChanges();
+
+        modifiedFiles =
+            knownSourceChanges.getAddedAndModifiedFiles().stream().collect(Collectors.toSet());
+        removedFiles = knownSourceChanges.getRemovedFiles().stream().collect(Collectors.toSet());
+      }
+
+      return new ModeParam.Incremental(
+          create(incrementalMode.getClasspathChanges()), modifiedFiles, removedFiles);
+    } else {
+      throw new IllegalArgumentException("Unsupported kotlinc mode: " + kotlincMode);
+    }
+  }
+
+  private static ClasspathChangesParam create(ClasspathChanges classpathChanges) {
+    if (classpathChanges instanceof ClasspathChanges.ToBeComputedByIncrementalCompiler) {
+      return ClasspathChangesParam.TO_BE_COMPUTED_BY_INCREMENTAL_COMPILER;
+    } else if (classpathChanges instanceof ClasspathChanges.NoChanges) {
+      return ClasspathChangesParam.NO_CHANGES;
+    } else if (classpathChanges instanceof ClasspathChanges.Unknown) {
+      return ClasspathChangesParam.UNKNOWN;
+    } else {
+      throw new IllegalArgumentException("Unsupported classpathChanges mode: " + classpathChanges);
+    }
+  }
+
+  private static StepParam create(KotlincStep kotlincStep) {
+    // KSP2 step is emitted by its own factory
+    // TODO asoshin: move all other steps to use KSP2 pattern for logging
+    if (kotlincStep instanceof KosabiStubgenStep) {
+      return StepParam.KOSABI_STUBGEN;
+    } else if (kotlincStep instanceof KaptStep) {
+      return StepParam.KAPT;
+    } else {
+      return StepParam.KOTLINC;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCDModelHelper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCDModelHelper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCDModelHelper.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+// TODO(navidq) Deserialize BuildKotlinCommand into our own data model and use it everywhere
+public class KotlinCDModelHelper {
+  private static final Pattern LANGUAGE_VERSION_REGEX =
+      Pattern.compile("-language-version=\\d+\\.\\d+");
+
+  public static String getLanguageVersion(ImmutableList<String> args) {
+    for (String arg : args) {
+      Matcher matcher = LANGUAGE_VERSION_REGEX.matcher(arg);
+      if (matcher.matches()) {
+        String[] splitArg = arg.split("=");
+        Preconditions.checkState(splitArg.length == 2);
+        return splitArg[1];
+      }
+    }
+    return "1.9";
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinCStepsBuilder.java
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import static com.facebook.buck.jvm.kotlin.CompilerPluginUtils.getKotlinCompilerPluginsArgs;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.cd.command.kotlin.KotlinExtraParams;
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersion;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.ActionMetadata;
+import com.facebook.buck.jvm.java.CompilerOutputPaths;
+import com.facebook.buck.jvm.java.CompilerParameters;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics;
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import java.nio.file.Path;
+import java.util.Optional;
+
+public class KotlinCStepsBuilder {
+
+  static void prepareKotlinCompilation(
+      RelPath buckOut,
+      AbsPath buildCellRootPath,
+      BuildTargetValue invokingRule,
+      CompilerParameters parameters,
+      ImmutableList.Builder<IsolatedStep> steps,
+      ActionMetadata actionMetadata,
+      KotlinExtraParams extraParams,
+      String friendPathsArg,
+      String kotlinPluginGeneratedFullPath,
+      String moduleName,
+      RelPath kotlinOutputDirectory,
+      ImmutableSortedSet.Builder<RelPath> sourceWithKSPOutputBuilder,
+      Path pathToSrcsList,
+      ImmutableList<AbsPath> allClasspaths,
+      RelPath reportsOutput,
+      Kotlinc kotlinc,
+      KosabiPluginOptions kosabiPluginOptions,
+      ImmutableList<AbsPath> compilationClasspath,
+      ImmutableList<AbsPath> applicabilityClasspath,
+      ImmutableList.Builder<IsolatedStep> postKotlinCompilationFailureSteps,
+      ImmutableList<AbsPath> classpathSnapshots,
+      KotlinCDAnalytics kotlinCDAnalytics) {
+    ImmutableList.Builder<String> extraArguments =
+        getKotlincExtraArguments(
+            buildCellRootPath,
+            invokingRule,
+            parameters,
+            extraParams,
+            friendPathsArg,
+            kotlinPluginGeneratedFullPath,
+            moduleName);
+
+    LanguageVersion kotlincLanguageVersion = extraParams.getLanguageVersion();
+
+    KotlincStep kotlincStep =
+        new KotlincStep(
+            invokingRule,
+            kotlinOutputDirectory.getPath(),
+            sourceWithKSPOutputBuilder.build(),
+            pathToSrcsList,
+            allClasspaths,
+            extraParams.getKotlinHomeLibraries(),
+            reportsOutput,
+            kotlinc,
+            extraArguments.build(),
+            ImmutableList.of(CompilerPluginUtils.VERBOSE),
+            parameters.getOutputPaths(),
+            parameters.getShouldTrackClassUsage(),
+            buckOut,
+            kosabiPluginOptions.getKosabiPlugins(),
+            extraParams.getKosabiJvmAbiGenEarlyTerminationMessagePrefix().orElse(null),
+            compilationClasspath,
+            applicabilityClasspath,
+            extraParams.getShouldVerifySourceOnlyAbiConstraints(),
+            postKotlinCompilationFailureSteps.build(),
+            extraParams.getDepTrackerPlugin(),
+            new KotlincModeFactory()
+                .create(
+                    invokingRule.isSourceOnlyAbi(),
+                    buildCellRootPath,
+                    kotlinOutputDirectory.getParent().toAbsolutePath(),
+                    parameters.getShouldTrackClassUsage(),
+                    CompilerOutputPaths.getDepFilePath(
+                        parameters.getOutputPaths().getOutputJarDirPath()),
+                    CompilerOutputPaths.getUsedJarsFilePath(
+                        parameters.getOutputPaths().getOutputJarDirPath()),
+                    extraParams,
+                    Optional.ofNullable(actionMetadata),
+                    classpathSnapshots),
+            kotlinCDAnalytics,
+            kotlincLanguageVersion,
+            kotlincLanguageVersion.getSupportsK2());
+    steps.add(kotlincStep);
+  }
+
+  private static ImmutableList.Builder<String> getKotlincExtraArguments(
+      AbsPath buildCellRootPath,
+      BuildTargetValue invokingRule,
+      CompilerParameters parameters,
+      KotlinExtraParams extraParams,
+      String friendPathsArg,
+      String kotlinPluginGeneratedFullPath,
+      String moduleName) {
+    ImmutableList.Builder<String> extraArguments =
+        ImmutableList.<String>builder()
+            .add(friendPathsArg)
+            .addAll(
+                getKotlinCompilerPluginsArgs(
+                    extraParams.getKotlinCompilerPlugins(),
+                    kotlinPluginGeneratedFullPath,
+                    KspStepsBuilder::isNotKspPlugin))
+            .add(CompilerPluginUtils.MODULE_NAME)
+            .add(moduleName)
+            .add(CompilerPluginUtils.NO_STDLIB);
+
+    extraParams
+        .getJvmTarget()
+        .ifPresent(
+            target -> {
+              extraArguments.add("-jvm-target");
+              extraArguments.add(target);
+            });
+
+    extraArguments.addAll(extraParams.getExtraKotlincArguments());
+
+    ImmutableList<String> jvmAbiPluginArgs =
+        createJvmAbiPluginArgs(
+            buildCellRootPath,
+            invokingRule,
+            parameters,
+            extraParams,
+            kotlinPluginGeneratedFullPath);
+    extraArguments.addAll(jvmAbiPluginArgs);
+    return extraArguments;
+  }
+
+  private static ImmutableList<String> createJvmAbiPluginArgs(
+      AbsPath buildCellRootPath,
+      BuildTargetValue invokingRule,
+      CompilerParameters parameters,
+      KotlinExtraParams extraParams,
+      String kotlinPluginGeneratedFullPath) {
+    // Use jvm-abi-gen for the kotlin part of class-abi, in order to get more accurate class-abi.
+    // But since it is a kotlinc plugin, we produce it during library build.
+    if (extraParams.getShouldUseJvmAbiGen() && invokingRule.isLibraryJar()) {
+      final AbsPath jvmAbiPlugin = extraParams.getJvmAbiGenPlugin().orElseThrow();
+
+      ImmutableMap<String, String> jvmPluginOptions =
+          extraParams.getKotlinCompilerPlugins().get(jvmAbiPlugin);
+      boolean hasOutputDirParam =
+          Optional.ofNullable(jvmPluginOptions)
+              .map(opts -> opts.containsKey(CompilerPluginUtils.JB_JVM_ABI_OUTPUT_DIR))
+              .orElse(false);
+
+      // we add 'outputDir' param, if it is missing
+      if (!hasOutputDirParam) {
+        final AbsPath jvmOutputDir =
+            getJvmAbiGenOutputPath(buildCellRootPath, parameters, extraParams);
+        ImmutableMap.Builder<String, String> jvmPluginOptionsBuilder = ImmutableMap.builder();
+        if (jvmPluginOptions != null) {
+          jvmPluginOptionsBuilder.putAll(jvmPluginOptions);
+        }
+        jvmPluginOptionsBuilder.put(
+            CompilerPluginUtils.JB_JVM_ABI_OUTPUT_DIR, jvmOutputDir.toString());
+
+        jvmPluginOptions = jvmPluginOptionsBuilder.build();
+      }
+
+      final ImmutableList<String> jvmAbiPluginArgs =
+          getKotlinCompilerPluginsArgs(
+              jvmAbiPlugin, jvmPluginOptions, kotlinPluginGeneratedFullPath);
+      return jvmAbiPluginArgs;
+    }
+    return ImmutableList.of();
+  }
+
+  // when incremental compiler is on, we need to work with directory, not jar (which is used by
+  // default)
+  private static AbsPath getJvmAbiGenOutputPath(
+      AbsPath buildCellRootPath, CompilerParameters parameters, KotlinExtraParams extraParams) {
+    if (extraParams.getShouldKotlincRunIncrementally()) {
+      return extraParams.getJvmAbiGenWorkingDir().get();
+    }
+
+    return buildCellRootPath.resolve(
+        CompilerOutputPaths.getJvmAbiGenFilePath(
+            parameters.getOutputPaths().getOutputJarDirPath()));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinClassUsageHelper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinClassUsageHelper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinClassUsageHelper.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import static com.facebook.buck.jvm.java.CompilerOutputPaths.getKAPTDepFilePath;
+import static com.facebook.buck.jvm.java.CompilerOutputPaths.getKotlinTempDepFilePath;
+import static com.facebook.buck.jvm.java.CompilerOutputPaths.getKspDepFilePath;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.java.ClassUsageURIParser;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Java used-class optimization directly inject FileManager into javac process. However, that is no
+ * longer possible for Kotlin. We have to modify KAPT, KSP and compiler plugin to output
+ * dependencies into separate report files, then parse and merge them to get a complete map of class
+ * usages.
+ *
+ * <p>This class includes utility functions for parsing and merging kotlin temp dep files.
+ */
+public class KotlinClassUsageHelper {
+
+  /**
+   * Returns a map of all the files used by the Kotlin compiler and the its annotation processors.
+   */
+  static ImmutableMap<Path, Set<Path>> getClassUsageData(
+      RelPath reportDirPath, AbsPath ruleCellRoot) throws IOException {
+    // read compiler plugin generated class usage report file
+    Path kotlinGeneralClassUsageReportPath =
+        ruleCellRoot.resolve(getKotlinTempDepFilePath(reportDirPath)).getPath();
+    ImmutableMap<Path, Set<Path>> classUsages =
+        readUriBasedClassUsageFile(kotlinGeneralClassUsageReportPath);
+
+    // merge kapt generated class usage report file if it exist
+    Path kaptClassUsageReportPath =
+        ruleCellRoot.resolve(getKAPTDepFilePath(reportDirPath)).getPath();
+    if (kaptClassUsageReportPath.toFile().exists()) {
+      classUsages = merge(classUsages, readUriBasedClassUsageFile(kaptClassUsageReportPath));
+    }
+
+    // merge ksp generated class usage report file if it exist
+    Path kspClassUsageReportPath = ruleCellRoot.resolve(getKspDepFilePath(reportDirPath)).getPath();
+    if (kspClassUsageReportPath.toFile().exists()) {
+      classUsages = merge(classUsages, readUriBasedClassUsageFile(kspClassUsageReportPath));
+    }
+
+    return classUsages;
+  }
+
+  /** Read a class usage report that is in the raw format one URI per line */
+  @VisibleForTesting
+  static ImmutableMap<Path, Set<Path>> readUriBasedClassUsageFile(Path path) throws IOException {
+    if (!Files.exists(path)) {
+      return ImmutableMap.of();
+    }
+
+    final ClassUsageURIParser parser = new ClassUsageURIParser();
+    Files.readAllLines(path).forEach(line -> parser.parseAndRecordURI(URI.create(line)));
+    return parser.getClassUsageMap();
+  }
+
+  /** Merge two class usage map */
+  @VisibleForTesting
+  static ImmutableMap<Path, Set<Path>> merge(Map<Path, Set<Path>> mapA, Map<Path, Set<Path>> mapB) {
+    // Merge map A to resultBuilder, and ensure both inner and outer map is mutable
+    HashMap<Path, Set<Path>> resultBuilder = new HashMap<>();
+    for (Map.Entry<Path, Set<Path>> jarEntry : mapA.entrySet()) {
+      resultBuilder.put(jarEntry.getKey(), new HashSet<>(jarEntry.getValue()));
+    }
+    // Merge map B to result builder. Increment count if same entry exist.
+    for (Map.Entry<Path, Set<Path>> jarEntry : mapB.entrySet()) {
+      Set<Path> resultClassPaths =
+          resultBuilder.computeIfAbsent(jarEntry.getKey(), _path -> new HashSet<>());
+      resultClassPaths.addAll(jarEntry.getValue());
+    }
+    return ImmutableMap.copyOf(resultBuilder);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinSourceChangesFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinSourceChangesFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinSourceChangesFactory.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlinSourceChanges;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class KotlinSourceChangesFactory {
+
+  private static final Logger LOG = Logger.get(KotlinSourceChangesFactory.class);
+
+  public static KotlinSourceChanges create(
+      final AbsPath rootProjectDir, final SourceFilesActionMetadata actionMetadata) {
+    List<Path> modifiedFiles = actionMetadata.calculateAddedAndModifiedSourceFiles();
+    List<Path> removedFiles = actionMetadata.calculateRemovedFiles();
+
+    LOG.debug(
+        "Source file changes: \n" + "modified files: [%s], \n" + "removed files: [%s]",
+        modifiedFiles, removedFiles);
+
+    return new KotlinSourceChanges.Known(
+        modifiedFiles.stream().map(rootProjectDir::resolve).collect(Collectors.toList()),
+        removedFiles.stream().map(rootProjectDir::resolve).collect(Collectors.toList()));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlinStepsBuilder.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.jvm.cd.AbiStepsBuilder;
+import com.facebook.buck.jvm.cd.BuildCommandStepsBuilder;
+import com.facebook.buck.jvm.cd.DefaultCompileStepsBuilderFactory;
+import com.facebook.buck.jvm.cd.LibraryStepsBuilder;
+import com.facebook.buck.jvm.cd.command.BaseJarCommand;
+import com.facebook.buck.jvm.cd.command.BuildMode;
+import com.facebook.buck.jvm.cd.command.kotlin.BuildKotlinCommand;
+import com.facebook.buck.jvm.cd.command.kotlin.KotlinExtraParams;
+import com.facebook.buck.jvm.java.ActionMetadata;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.google.common.collect.ImmutableList;
+import javax.annotation.Nullable;
+
+/** Converts serialized protobuf commands into steps to compile Kotlin targets. */
+public class KotlinStepsBuilder implements BuildCommandStepsBuilder {
+  private final ImmutableList<IsolatedStep> steps;
+  private final AbsPath ruleCellRoot;
+
+  public KotlinStepsBuilder(
+      BuildKotlinCommand buildKotlinCommand,
+      @Nullable ActionMetadata actionMetadata,
+      KotlinCDAnalytics kotlinCDAnalytics) {
+    steps = buildSteps(buildKotlinCommand, actionMetadata, kotlinCDAnalytics);
+    ruleCellRoot = buildKotlinCommand.getBaseJarCommand().getBuildCellRootPath();
+  }
+
+  /**
+   * @return the steps corresponding to the protobuf command
+   */
+  @Override
+  public ImmutableList<IsolatedStep> getSteps() {
+    return steps;
+  }
+
+  /**
+   * @return the rule cell root.
+   */
+  @Override
+  public AbsPath getRuleCellRoot() {
+    return ruleCellRoot;
+  }
+
+  private ImmutableList<IsolatedStep> buildSteps(
+      BuildKotlinCommand buildKotlinCommand,
+      @Nullable ActionMetadata actionMetadata,
+      KotlinCDAnalytics kotlinCDAnalytics) {
+    DaemonKotlincToJarStepFactory kotlincToJarStepFactory =
+        new DaemonKotlincToJarStepFactory(kotlinCDAnalytics);
+
+    DefaultCompileStepsBuilderFactory<KotlinExtraParams> stepsBuilderFactory =
+        new DefaultCompileStepsBuilderFactory<>(kotlincToJarStepFactory);
+
+    if (buildKotlinCommand.getBuildMode() == BuildMode.LIBRARY) {
+      return handleLibaryJarCommand(
+          stepsBuilderFactory,
+          buildKotlinCommand.getBaseJarCommand(),
+          buildKotlinCommand.getKotlinExtraParams(),
+          actionMetadata);
+    } else {
+      return handleAbiJarCommand(
+          stepsBuilderFactory,
+          buildKotlinCommand.getBaseJarCommand(),
+          buildKotlinCommand.getKotlinExtraParams());
+    }
+  }
+
+  private ImmutableList<IsolatedStep> handleLibaryJarCommand(
+      DefaultCompileStepsBuilderFactory<KotlinExtraParams> stepsBuilderFactory,
+      BaseJarCommand baseJarCommand,
+      KotlinExtraParams kotlinExtraParams,
+      @Nullable ActionMetadata actionMetadata) {
+
+    LibraryStepsBuilder libraryStepsBuilder = stepsBuilderFactory.getLibraryBuilder();
+    libraryStepsBuilder.addBuildStepsForLibrary(
+        baseJarCommand.getAbiCompatibilityMode(),
+        baseJarCommand.getAbiGenerationMode(),
+        baseJarCommand.isRequiredForSourceOnlyAbi(),
+        baseJarCommand.getTrackClassUsage(),
+        baseJarCommand.getBuckOut(),
+        baseJarCommand.getBuildTargetValue(),
+        baseJarCommand.getCompilerOutputPathsValue(),
+        baseJarCommand.getCompileTimeClasspathPaths(),
+        baseJarCommand.getCompileTimeClasspathSnapshotPathsMap(),
+        baseJarCommand.getJavaSrcs(),
+        baseJarCommand.getResourcesMap(),
+        baseJarCommand.getJarParameters(),
+        baseJarCommand.getBuildCellRootPath(),
+        baseJarCommand.getResolvedJavac(),
+        actionMetadata,
+        kotlinExtraParams);
+
+    libraryStepsBuilder.addMakeMissingOutputsStep(baseJarCommand.getAnnotationPath());
+
+    return libraryStepsBuilder.buildIsolatedSteps();
+  }
+
+  private ImmutableList<IsolatedStep> handleAbiJarCommand(
+      DefaultCompileStepsBuilderFactory<KotlinExtraParams> stepsBuilderFactory,
+      BaseJarCommand baseJarCommand,
+      KotlinExtraParams kotlinExtraParams) {
+    AbiStepsBuilder abiStepsBuilder = stepsBuilderFactory.getAbiBuilder();
+
+    abiStepsBuilder.addBuildStepsForAbi(
+        baseJarCommand.getAbiCompatibilityMode(),
+        baseJarCommand.getAbiGenerationMode(),
+        baseJarCommand.isRequiredForSourceOnlyAbi(),
+        baseJarCommand.getTrackClassUsage(),
+        baseJarCommand.getBuckOut(),
+        baseJarCommand.getBuildTargetValue(),
+        baseJarCommand.getCompilerOutputPathsValue(),
+        baseJarCommand.getCompileTimeClasspathPaths(),
+        baseJarCommand.getJavaSrcs(),
+        baseJarCommand.getResourcesMap(),
+        baseJarCommand.getJarParameters(),
+        baseJarCommand.getJarParameters(),
+        baseJarCommand.getBuildCellRootPath(),
+        baseJarCommand.getResolvedJavac(),
+        kotlinExtraParams);
+
+    return abiStepsBuilder.buildIsolatedSteps();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincFactory.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.kotlin.buildtools.BuildToolsKotlinc;
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc;
+
+public class KotlincFactory {
+
+  private static final Logger LOG = Logger.get(KotlincFactory.class);
+
+  public static Kotlinc create() {
+    LOG.info("Kotlinc implementation used: " + BuildToolsKotlinc.class.getSimpleName());
+    return new BuildToolsKotlinc();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincModeFactory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincModeFactory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincModeFactory.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.cd.command.kotlin.KotlinExtraParams;
+import com.facebook.buck.jvm.java.ActionMetadata;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlinSourceChanges;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode;
+import com.google.common.collect.ImmutableList;
+import java.util.Optional;
+import javax.annotation.Nullable;
+
+public class KotlincModeFactory {
+  private static final Logger LOG = Logger.get(KotlincModeFactory.class);
+
+  private final IncrementalCompilationValidator incrementalCompilationValidator;
+
+  public KotlincModeFactory() {
+    this(new IncrementalCompilationValidator());
+  }
+
+  public KotlincModeFactory(IncrementalCompilationValidator incrementalCompilationValidator) {
+    this.incrementalCompilationValidator = incrementalCompilationValidator;
+  }
+
+  public KotlincMode create(
+      boolean isSourceOnly,
+      final AbsPath rootProjectDir,
+      final AbsPath buildDir,
+      final boolean isTrackClassUsageEnabled,
+      final RelPath depFilePath,
+      final RelPath usedJarsPath,
+      final KotlinExtraParams extraParams,
+      final Optional<ActionMetadata> actionMetadata,
+      final ImmutableList<AbsPath> classpathSnapshots) {
+    if (!extraParams.getShouldKotlincRunIncrementally()) {
+      LOG.info("Non-incremental mode applied: incremental property disabled");
+      return KotlincMode.NonIncremental.INSTANCE;
+    } else if (isSourceOnly) {
+      LOG.info("Non-incremental mode applied: source-only build requested");
+      return KotlincMode.NonIncremental.INSTANCE;
+    } else {
+      @Nullable
+      AbsPath depFile = isTrackClassUsageEnabled ? rootProjectDir.resolve(depFilePath) : null;
+      @Nullable
+      AbsPath usedJars = isTrackClassUsageEnabled ? rootProjectDir.resolve(usedJarsPath) : null;
+
+      AbsPath kotlicWorkingDir =
+          extraParams
+              .getKotlincWorkingDir()
+              .orElseThrow(
+                  () ->
+                      new IllegalStateException(
+                          "incremental_state_dir/kotlinc_working_dir is not created"));
+      ActionMetadata metadata =
+          actionMetadata.orElseThrow(
+              () -> new IllegalStateException("actionMetadata is not created"));
+      LOG.info("Incremental mode applied");
+
+      return new KotlincMode.Incremental(
+          rootProjectDir,
+          buildDir,
+          kotlicWorkingDir,
+          KotlinSourceChanges.ToBeCalculated.INSTANCE,
+          ClasspathChangesFactory.create(new SnapshotsActionMetadata(metadata), classpathSnapshots),
+          depFile,
+          incrementalCompilationValidator.validate(
+              extraParams.getKotlinCompilerPlugins().keySet().stream()
+                  .map(rootProjectDir::relativize)
+                  .collect(ImmutableList.toImmutableList()),
+              metadata,
+              depFile,
+              usedJars,
+              getJvmAbiGenWorkingDir(
+                  extraParams.getShouldUseJvmAbiGen(), extraParams.getJvmAbiGenWorkingDir())));
+    }
+  }
+
+  private static @Nullable AbsPath getJvmAbiGenWorkingDir(
+      boolean shouldUseJvmAbiGen, Optional<AbsPath> jvmAbiGenWorkingDir) {
+    if (!shouldUseJvmAbiGen) {
+      return null;
+    }
+
+    return jvmAbiGenWorkingDir.orElseThrow(
+        () -> new IllegalStateException("jvm_abi_gen_working_dir is not created"));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KotlincStep.java
@@ -0,0 +1,463 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import static com.facebook.buck.jvm.java.CompilerOutputPaths.getKotlinTempDepFilePath;
+import static com.google.common.collect.Iterables.transform;
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersion;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.java.CompilerOutputPaths;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDLoggingContext;
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode;
+import com.facebook.buck.jvm.kotlin.plugin.PluginLoader;
+import com.facebook.buck.step.StepExecutionResult;
+import com.facebook.buck.step.StepExecutionResults;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.util.CapturingPrintStream;
+import com.facebook.buck.util.Verbosity;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Optional;
+import javax.annotation.Nullable;
+
+/** Kotlin compile Step */
+public class KotlincStep implements IsolatedStep {
+  private static final Logger LOG = Logger.get(KotlincStep.class);
+
+  private static final String CLASSPATH_FLAG = "-classpath";
+  private static final String DESTINATION_FLAG = "-d";
+  private static final String X_PLUGIN_ARG = "-Xplugin=";
+  private static final String PLUGIN = "-P";
+  private static final String APPLICABILITY_PLUGIN_ID =
+      "com.facebook.kotlin.compilerplugins.kosabiapplicability";
+
+  private static final int EXPECTED_SOURCE_ONLY_ABI_EXIT_CODE = 2;
+
+  private final Kotlinc kotlinc;
+  private final ImmutableList<AbsPath> combinedClassPathEntries;
+  private final ImmutableList<AbsPath> kotlinHomeLibraries;
+  private final Path outputDirectory;
+  private final ImmutableList<String> extraArguments;
+  private final ImmutableList<String> verboseModeOnlyExtraArguments;
+  private final ImmutableSortedSet<RelPath> sourceFilePaths;
+  private final Path pathToSrcsList;
+  private final RelPath reportDirPath;
+  private final BuildTargetValue invokingRule;
+  private final CompilerOutputPaths outputPaths;
+  private final boolean trackClassUsage;
+  private final RelPath configuredBuckOut;
+  private final ImmutableMap<String, AbsPath> resolvedKosabiPluginOptionPath;
+  private final @Nullable String kosabiEarlyTerminationMessagePrefix;
+  // For SO-ABI builds: reduced classpath (rfsoa deps only), used as kotlinc -classpath.
+  // For library builds: full dep set, used only by KosabiStubgen/KSP — NOT for applicability.
+  private final ImmutableList<AbsPath> compilationClasspath;
+  // Reduced SO-ABI classpath for the applicability plugin (rfsoa + source_only_abi_deps only).
+  private final ImmutableList<AbsPath> applicabilityClasspath;
+  private final boolean verifySourceOnlyAbiConstraints;
+  private ImmutableList<IsolatedStep> postKotlinCompilationFailureSteps;
+  private final Optional<AbsPath> depTrackerPath;
+  private final KotlincMode kotlincMode;
+  private final KotlinCDAnalytics kotlinCDAnalytics;
+  private final LanguageVersion languageVersion;
+  private final boolean shouldKosabiJvmAbiGenUseK2;
+
+  private static final String COMPOSE_PLUGIN_PATH_FRAGMENT = "compose-compiler-plugin";
+
+  KotlincStep(
+      BuildTargetValue invokingRule,
+      Path outputDirectory,
+      ImmutableSortedSet<RelPath> sourceFilePaths,
+      Path pathToSrcsList,
+      ImmutableList<AbsPath> combinedClassPathEntries,
+      ImmutableList<AbsPath> kotlinHomeLibraries,
+      RelPath reportDirPath,
+      Kotlinc kotlinc,
+      ImmutableList<String> extraArguments,
+      ImmutableList<String> verboseModeOnlyExtraArguments,
+      CompilerOutputPaths outputPaths,
+      boolean trackClassUsage,
+      RelPath configuredBuckOut,
+      ImmutableMap<String, AbsPath> resolvedKosabiPluginOptionPath,
+      @Nullable String kosabiEarlyTerminationMessagePrefix,
+      ImmutableList<AbsPath> compilationClasspath,
+      ImmutableList<AbsPath> applicabilityClasspath,
+      boolean verifySourceOnlyAbiConstraints,
+      ImmutableList<IsolatedStep> postKotlinCompilationFailureSteps,
+      Optional<AbsPath> depTrackerPath,
+      KotlincMode kotlincMode,
+      KotlinCDAnalytics kotlinCDAnalytics,
+      LanguageVersion languageVersion,
+      boolean shouldKosabiJvmAbiGenUseK2) {
+    this.invokingRule = invokingRule;
+    this.outputDirectory = outputDirectory;
+    this.sourceFilePaths = sourceFilePaths;
+    this.pathToSrcsList = pathToSrcsList;
+    this.reportDirPath = reportDirPath;
+    this.kotlinc = kotlinc;
+    this.combinedClassPathEntries = combinedClassPathEntries;
+    this.kotlinHomeLibraries = kotlinHomeLibraries;
+    this.extraArguments = extraArguments;
+    this.verboseModeOnlyExtraArguments = verboseModeOnlyExtraArguments;
+    this.outputPaths = outputPaths;
+    this.trackClassUsage = trackClassUsage;
+    this.configuredBuckOut = configuredBuckOut;
+    this.resolvedKosabiPluginOptionPath = resolvedKosabiPluginOptionPath;
+    this.kosabiEarlyTerminationMessagePrefix = kosabiEarlyTerminationMessagePrefix;
+    this.compilationClasspath = compilationClasspath;
+    this.applicabilityClasspath = applicabilityClasspath;
+    this.verifySourceOnlyAbiConstraints = verifySourceOnlyAbiConstraints;
+    this.postKotlinCompilationFailureSteps = postKotlinCompilationFailureSteps;
+    this.depTrackerPath = depTrackerPath;
+    this.kotlincMode = kotlincMode;
+    this.kotlinCDAnalytics = kotlinCDAnalytics;
+    this.languageVersion = languageVersion;
+    this.shouldKosabiJvmAbiGenUseK2 = shouldKosabiJvmAbiGenUseK2;
+  }
+
+  @Override
+  public String getShortName() {
+    return getKotlinc().getShortName();
+  }
+
+  @Override
+  public StepExecutionResult executeIsolatedStep(IsolatedExecutionContext context) {
+    ImmutableList<String> compilerOptions = getOptions(context, combinedClassPathEntries);
+    Verbosity verbosity =
+        context.getVerbosity().isSilent() ? Verbosity.STANDARD_INFORMATION : context.getVerbosity();
+    try (CapturingPrintStream stdout = new CapturingPrintStream();
+        CapturingPrintStream stderr = new CapturingPrintStream();
+        IsolatedExecutionContext firstOrderContext =
+            context.createSubContext(stdout, stderr, Optional.of(verbosity))) {
+
+      KotlinCDLoggingContext loggingContext =
+          KotlinCDLoggingContextFactory.create(this, languageVersion, kotlincMode);
+      Instant compilationStart = Instant.now();
+
+      int declaredDepsBuildResult =
+          kotlinc.buildWithClasspath(
+              firstOrderContext,
+              invokingRule,
+              compilerOptions,
+              kotlinHomeLibraries,
+              sourceFilePaths,
+              pathToSrcsList,
+              Optional.of(outputPaths.getWorkingDirectory().getPath()),
+              context.getRuleCellRoot(),
+              kotlincMode,
+              loggingContext);
+
+      Instant compilationEnd = Instant.now();
+      Duration compilationDuration = Duration.between(compilationStart, compilationEnd);
+      LOG.info(
+          "KOTLINCD_STEP_DURATION|%s|%s|%d|%d",
+          invokingRule.getFullyQualifiedName(),
+          this.getClass().getSimpleName(),
+          compilationDuration.toMillis(),
+          sourceFilePaths.size());
+      loggingContext.addExtras(
+          this.getClass().getSimpleName(),
+          "Kotlinc step duration: " + compilationDuration.toMillis() + " ms");
+      loggingContext.setDurationMs(compilationDuration.toMillis());
+      kotlinCDAnalytics.log(loggingContext);
+
+      String firstOrderStderr = stderr.getContentsAsString(StandardCharsets.UTF_8);
+      Optional<String> returnedStderr;
+
+      // We're generating Kotlin source-only-abi with Kosabi, a set of Kotlin compiler
+      // plugins.
+      // see `Kosabi.java`
+      //
+      // `jvm-abi-gen` is one of Kosabi plugins responsible for ABI class files
+      // generation.
+      // `jvm-abi-gen` could pass only the Kotlin Frontend Compiler stage, thus it's
+      // intentionally
+      // throws an Internal Compiler Error and exits with the corresponding exit code.
+      //
+      // EXPECTED_SOURCE_ONLY_ABI_EXIT_CODE is Kotlin compiler Internal Error code.
+      // We should treat Internal Compiler Error in source-only-abi as an abi-generation
+      // Success.
+      // In addition to an exit code we're expecting a specific `firstOrderStderr` message
+      // We both need an exit code and a message to prevent cache poisoning in cases when
+      // Kotlin compiler had a legit Internal Error
+      boolean shouldCheckSourceOnlyAbiErrorMessage = kosabiEarlyTerminationMessagePrefix != null;
+
+      boolean isExpectedSourceOnlyAbiTermination =
+          !shouldCheckSourceOnlyAbiErrorMessage
+              || validateEarlyTerminationErrorMessage(context, firstOrderStderr);
+
+      if (invokingRule.isSourceOnlyAbi()
+          && declaredDepsBuildResult == EXPECTED_SOURCE_ONLY_ABI_EXIT_CODE
+          && isExpectedSourceOnlyAbiTermination) {
+        declaredDepsBuildResult = StepExecutionResults.SUCCESS_EXIT_CODE;
+        returnedStderr = Optional.empty();
+      } else if (declaredDepsBuildResult != StepExecutionResults.SUCCESS_EXIT_CODE) {
+        for (IsolatedStep step : postKotlinCompilationFailureSteps) {
+          LOG.debug("Executing step [%s] after KotlinC failure", step.getShortName());
+          step.executeIsolatedStep(context);
+        }
+        returnedStderr = Optional.of(firstOrderStderr);
+      } else {
+        returnedStderr = Optional.empty();
+      }
+
+      if (declaredDepsBuildResult == StepExecutionResults.SUCCESS_EXIT_CODE && trackClassUsage) {
+        AbsPath ruleCellRoot = context.getRuleCellRoot();
+        RelPath outputJarDirPath = outputPaths.getOutputJarDirPath();
+        ClassUsageFileWriterFactory.create(kotlincMode)
+            .writeFile(
+                KotlinClassUsageHelper.getClassUsageData(reportDirPath, ruleCellRoot),
+                CompilerOutputPaths.getKotlinDepFilePath(outputJarDirPath),
+                ruleCellRoot,
+                configuredBuckOut);
+      }
+
+      return new StepExecutionResult(declaredDepsBuildResult, returnedStderr);
+    } catch (IOException | InterruptedException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @VisibleForTesting
+  Kotlinc getKotlinc() {
+    return kotlinc;
+  }
+
+  @Override
+  public String getIsolatedStepDescription(IsolatedExecutionContext context) {
+    return getKotlinc()
+        .getDescription(
+            getOptions(context, getClasspathEntries()), sourceFilePaths, pathToSrcsList);
+  }
+
+  /**
+   * Returns a list of command-line options to pass to javac. These options reflect the
+   * configuration of this javac command.
+   *
+   * @param context the ExecutionContext with in which javac will run
+   * @return list of String command-line options.
+   */
+  @VisibleForTesting
+  ImmutableList<String> getOptions(
+      IsolatedExecutionContext context, ImmutableList<AbsPath> buildClasspathEntries) {
+    ImmutableList.Builder<String> builder = ImmutableList.builder();
+
+    AbsPath ruleCellRoot = context.getRuleCellRoot();
+
+    if (outputDirectory != null) {
+      builder.add(DESTINATION_FLAG, ruleCellRoot.resolve(outputDirectory).toString());
+    }
+
+    if (invokingRule.isSourceOnlyAbi()) {
+      configureSourceOnlyOptions(builder, languageVersion, ruleCellRoot);
+    } else if (invokingRule.isSourceAbi()) {
+      throw new Error("Source ABI flavor is not supported for Kotlin targets");
+    } else if (!buildClasspathEntries.isEmpty()) {
+      addClasspath(builder, buildClasspathEntries);
+    }
+
+    configureKosabiApplicability(builder, ruleCellRoot);
+
+    if (trackClassUsage) {
+      depTrackerPath.ifPresentOrElse(
+          // New plugin, runtime dependency
+          path -> {
+            builder.add(X_PLUGIN_ARG + path);
+          },
+          // Fallback to a Buck internal plugin
+          () -> builder.add(X_PLUGIN_ARG + PluginLoader.DEP_TRACKER_KOTLINC_PLUGIN_JAR_PATH));
+      builder.add(PLUGIN);
+      builder.add(
+          "plugin:buck_deps_tracker:out="
+              + ruleCellRoot.resolve(getKotlinTempDepFilePath(reportDirPath)));
+    }
+
+    if (!extraArguments.isEmpty()) {
+      for (String extraArgument : extraArguments) {
+        if (!extraArgument.isEmpty()) {
+          builder.add(extraArgument);
+        }
+      }
+    }
+
+    if (languageVersion.getSupportsLanguageVersion()) {
+      builder.add(languageVersion.getCompilerArgs());
+    }
+
+    if (context.getVerbosity().shouldUseVerbosityFlagIfAvailable()
+        && !verboseModeOnlyExtraArguments.isEmpty()) {
+      for (String extraArgument : verboseModeOnlyExtraArguments) {
+        if (!extraArgument.isEmpty()) {
+          builder.add(extraArgument);
+        }
+      }
+    }
+
+    return builder.build();
+  }
+
+  private void configureKosabiApplicability(
+      ImmutableList.Builder<String> builder, AbsPath sourceRoot) {
+    if (!verifySourceOnlyAbiConstraints || !invokingRule.isLibraryJar()) return;
+
+    builder.add(
+        X_PLUGIN_ARG + getRequiredKosabiApplicabilityPlugin(resolvedKosabiPluginOptionPath));
+    builder.addAll(
+        getKosabiApplicabilityPluginOptions(
+            invokingRule.getFullyQualifiedName(),
+            sourceRoot,
+            applicabilityClasspath,
+            Optional.ofNullable(
+                resolvedKosabiPluginOptionPath.get(
+                    KosabiConfig.PROPERTY_KOSABI_APPLICABILITY_CELL_ROOT))));
+  }
+
+  @VisibleForTesting
+  static AbsPath getRequiredKosabiApplicabilityPlugin(
+      ImmutableMap<String, AbsPath> resolvedPluginPaths) {
+    AbsPath plugin = resolvedPluginPaths.get(KosabiConfig.PROPERTY_KOSABI_APPLICABILITY_PLUGIN);
+    if (plugin == null) {
+      throw new IllegalStateException(
+          "Structured Kosabi applicability was enabled, but the plugin path is missing");
+    }
+    return plugin;
+  }
+
+  @VisibleForTesting
+  static ImmutableList<String> getKosabiApplicabilityPluginOptions(
+      String targetLabel,
+      AbsPath sourceRoot,
+      ImmutableList<AbsPath> classpath,
+      Optional<AbsPath> cellRoot) {
+    int cellSeparator = targetLabel.indexOf("//");
+    if (cellSeparator <= 0) {
+      throw new IllegalStateException(
+          "Kosabi applicability requires a fully-qualified target label: " + targetLabel);
+    }
+    AbsPath resolvedCellRoot =
+        cellRoot.orElseThrow(
+            () -> new IllegalStateException("Kosabi applicability cell root path is missing"));
+    if (!resolvedCellRoot.startsWith(sourceRoot)) {
+      throw new IllegalStateException(
+          "Kosabi applicability cell root path must be within the project source root");
+    }
+    String sourceRootPrefix =
+        sourceRoot
+            .relativize(resolvedCellRoot)
+            .getPath()
+            .toString()
+            .replace(File.separatorChar, '/');
+    if (sourceRootPrefix.isEmpty()) sourceRootPrefix = ".";
+
+    ImmutableList.Builder<String> builder = ImmutableList.builder();
+    addApplicabilityPluginOption(builder, "target-label", targetLabel);
+    addApplicabilityPluginOption(builder, "source-root", sourceRoot.getPath().toString());
+    addApplicabilityPluginOption(builder, "source-root-prefix", sourceRootPrefix);
+    addApplicabilityPluginOption(
+        builder,
+        "source-only-abi-classpath",
+        Joiner.on(File.pathSeparator)
+            .join(transform(classpath, path -> path.getPath().toString())));
+    return builder.build();
+  }
+
+  private static void addApplicabilityPluginOption(
+      ImmutableList.Builder<String> builder, String name, String value) {
+    builder.add(PLUGIN);
+    builder.add("plugin:" + APPLICABILITY_PLUGIN_ID + ":" + name + "=" + value);
+  }
+
+  protected void configureSourceOnlyOptions(
+      ImmutableList.Builder<String> builder,
+      LanguageVersion languageVersion,
+      AbsPath ruleCellRoot) {
+    if (resolvedKosabiPluginOptionPath.containsKey(
+        KosabiConfig.PROPERTY_KOSABI_STUBS_GEN_K2_PLUGIN)) {
+      AbsPath stubPlugin =
+          resolvedKosabiPluginOptionPath.get(KosabiConfig.PROPERTY_KOSABI_STUBS_GEN_K2_PLUGIN);
+      builder.add(X_PLUGIN_ARG + stubPlugin);
+    }
+
+    if (shouldKosabiJvmAbiGenUseK2) {
+      if (!resolvedKosabiPluginOptionPath.containsKey(
+          KosabiConfig.PROPERTY_KOSABI_JVM_ABI_GEN_K2_PLUGIN)) {
+        throw new RuntimeException("KosabiJvmAbiGenK2Plugin is not provided");
+      }
+      AbsPath jvmAbiPlugin =
+          resolvedKosabiPluginOptionPath.get(KosabiConfig.PROPERTY_KOSABI_JVM_ABI_GEN_K2_PLUGIN);
+      builder.add(X_PLUGIN_ARG + jvmAbiPlugin);
+      builder.add(PLUGIN);
+      builder.add(
+          "plugin:com.facebook.k2.jvm.abi.gen:outputDir="
+              + ruleCellRoot.resolve(outputDirectory).toString());
+      // Enable Compose ABI emulation only when the Compose compiler plugin is active.
+      // The emulation adds $stable fields and @StabilityInferred annotations to match
+      // the real Compose compiler output. Only targets with the Compose plugin should
+      // get these artifacts — otherwise @StabilityInferred leaks into ABI jars of
+      // non-Compose targets and causes downstream javac failures.
+      if (shouldEnableComposeAbiEmulation()) {
+        builder.add(PLUGIN);
+        builder.add("plugin:com.facebook.k2.jvm.abi.gen:enableComposeAbiEmulation=true");
+      }
+    }
+
+    addClasspath(builder, this.compilationClasspath);
+  }
+
+  private boolean shouldEnableComposeAbiEmulation() {
+    if (!shouldKosabiJvmAbiGenUseK2) return false;
+    return extraArguments.stream()
+        .filter(arg -> arg.startsWith("-Xplugin="))
+        .anyMatch(arg -> arg.contains(COMPOSE_PLUGIN_PATH_FRAGMENT));
+  }
+
+  private void addClasspath(ImmutableList.Builder<String> builder, Iterable<AbsPath> pathElements) {
+    builder.add(
+        CLASSPATH_FLAG,
+        Joiner.on(File.pathSeparator)
+            .join(transform(pathElements, path -> path.getPath().toString())));
+  }
+
+  private boolean validateEarlyTerminationErrorMessage(
+      IsolatedExecutionContext context, String fullErrorMessage) {
+    if (fullErrorMessage.isEmpty()) return false;
+
+    int earlyTerminationMessageIndex =
+        fullErrorMessage.indexOf(kosabiEarlyTerminationMessagePrefix);
+    if (earlyTerminationMessageIndex >= 0) {
+      return true;
+    }
+    return false;
+  }
+
+  /**
+   * @return The classpath entries used to invoke javac.
+   */
+  @VisibleForTesting
+  ImmutableList<AbsPath> getClasspathEntries() {
+    return combinedClassPathEntries;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/Ksp2ModeFactory.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/Ksp2ModeFactory.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/Ksp2ModeFactory.kt
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:JvmName("Ksp2ModeFactory")
+@file:OptIn(ExperimentalPathApi::class)
+
+package com.facebook.buck.jvm.kotlin
+
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.core.util.log.Logger
+import com.facebook.buck.io.file.MostFiles
+import com.facebook.buck.jvm.cd.command.kotlin.KotlinExtraParams
+import com.facebook.buck.jvm.java.ActionMetadata
+import com.facebook.buck.jvm.kotlin.ksp.incremental.Ksp2Mode
+import com.facebook.buck.jvm.kotlin.ksp.incremental.ReprocessReason
+import java.nio.file.Files
+import kotlin.io.path.ExperimentalPathApi
+
+@JvmName("create")
+fun Ksp2Mode(
+    rootProjectDir: AbsPath,
+    isSourceOnly: Boolean,
+    kspCachesOutput: RelPath,
+    extraParams: KotlinExtraParams,
+    actionMetadata: ActionMetadata?,
+): Ksp2Mode {
+  when {
+    !extraParams.shouldKsp2RunIncrementally -> {
+      LOG.info("Non-incremental mode applied: incremental property disabled")
+      return Ksp2Mode.NonIncremental(kspCachesOutput)
+    }
+    isSourceOnly -> {
+      LOG.info("Non-incremental mode applied: source-only build requested")
+      return Ksp2Mode.NonIncremental(kspCachesOutput)
+    }
+    else -> {
+      val cachesDir =
+          extraParams.ksp2CachesDir.orElseThrow {
+            IllegalStateException("incremental_state_dir/ksp2_caches_dir is not created")
+          }
+      val sourceFilesMetadata = SourceFilesActionMetadata(requireNotNull(actionMetadata))
+      val snapshotsActionMetadata = SnapshotsActionMetadata(requireNotNull(actionMetadata))
+      val hasClasspathChanged = snapshotsActionMetadata.hasClasspathChanged()
+
+      if (hasClasspathChanged) {
+        // TODO(ijurcikova) implement support for classpath changes and move the logic into Ksp2Step
+        LOG.info(
+            "Non-incremental processing will be performed: Incremental processing after classpath change is not supported yet",
+        )
+        createCleanDirectory(cachesDir)
+      }
+
+      LOG.info("Incremental mode applied")
+
+      return Ksp2Mode.Incremental(
+          cachesDir,
+          true,
+          sourceFilesMetadata.calculateAddedAndModifiedSourceFiles().map(rootProjectDir::resolve),
+          sourceFilesMetadata.calculateRemovedFiles().map(rootProjectDir::resolve),
+          emptyList(),
+          if (hasClasspathChanged) ReprocessReason.CLASSPATH_CHANGED else null,
+      )
+    }
+  }
+}
+
+private fun createCleanDirectory(dir: AbsPath) {
+  MostFiles.deleteRecursivelyIfExists(dir.getPath())
+  Files.createDirectories(dir.getPath())
+}
+
+private val LOG = Logger.get("Ksp2ModeFactory")
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KspStepsBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KspStepsBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/KspStepsBuilder.java
@@ -0,0 +1,320 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin;
+
+import static com.facebook.buck.jvm.java.JavaPaths.SRC_ZIP;
+import static com.facebook.buck.jvm.kotlin.AnnotationProcessorUtils.getAnnotationProcessors;
+import static com.facebook.buck.jvm.kotlin.CompilerPluginUtils.getKotlinCompilerPluginsArgs;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.filesystem.CopySourceMode;
+import com.facebook.buck.jvm.cd.command.kotlin.KotlinExtraParams;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.core.BuildTargetValueExtraParams;
+import com.facebook.buck.jvm.java.ActionMetadata;
+import com.facebook.buck.jvm.java.CompilerOutputPaths;
+import com.facebook.buck.jvm.java.JavacPluginParams;
+import com.facebook.buck.jvm.java.ResolvedJavacPluginProperties;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics;
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc;
+import com.facebook.buck.jvm.kotlin.ksp.Ksp2Step;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.CopyIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MakeCleanDirectoryIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.MkdirIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.RmIsolatedStep;
+import com.facebook.buck.step.isolatedsteps.common.ZipIsolatedStep;
+import com.facebook.buck.util.zip.ZipCompressionLevel;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Optional;
+
+public class KspStepsBuilder {
+  private static final String KSP_PLUGIN_ID = "plugin:com.google.devtools.ksp.symbol-processing:";
+  private static final String MODULE_NAME = "-module-name";
+  private static final String PLUGIN = "-P";
+  private static final ImmutableSet<String> PROCESSORS_USING_FINAL_ROUND_PLACEHOLDER =
+      ImmutableSet.of(
+          "KSP:com.facebook.annotationprocessors.inject.ksp.InjectorKspProcessorProvider",
+          "KSP:com.facebook.metagen.processor.kspmetagen.MetagenKspProcessorProvider",
+          "KSP:com.facebook.annotationprocessors.gatekeepers.ksp.GatekeeperDeclarationKspProcessor",
+          "KSP:com.facebook.annotationprocessors.qe.ksp.QEKspProcessorProvider");
+
+  /** Initialize all the folders, steps and parameters needed to run KSP plugins for this rule. */
+  public static KSPInvocationStatus prepareKspProcessorsIfNeeded(
+      Optional<ActionMetadata> actionMetadata,
+      KotlinExtraParams extraParams,
+      BuildTargetValue invokingRule,
+      AbsPath rootPath,
+      ImmutableList.Builder<IsolatedStep> steps,
+      ImmutableList.Builder<IsolatedStep> postKotlinCompilationSteps,
+      BuildTargetValueExtraParams buildTargetValueExtraParams,
+      RelPath outputDirectory,
+      RelPath annotationGenFolder,
+      ImmutableSortedSet.Builder<RelPath> javacSourceBuilder,
+      RelPath reportsOutput,
+      boolean shouldTrackClassUsage,
+      ImmutableList<AbsPath> allClasspaths,
+      String kotlinPluginGeneratedOutFullPath,
+      RelPath projectBaseDir,
+      JavacPluginParams annotationProcessorParams,
+      ImmutableSortedSet<RelPath> sourceFilePaths,
+      Path pathToSrcsList,
+      ImmutableList<AbsPath> kotlinHomeLibraries,
+      Kotlinc kotlinc,
+      CompilerOutputPaths compilerOutputPaths,
+      RelPath configuredBuckOut,
+      ImmutableMap<String, AbsPath> resolvedKosabiPluginOptionPath,
+      ImmutableSortedSet.Builder<RelPath> sourceBuilderWithKspOutputs,
+      ImmutableList<AbsPath> compilationClasspath,
+      String moduleName,
+      KotlinCDAnalytics kotlinCDAnalytics) {
+
+    ImmutableList<ResolvedJavacPluginProperties> kspAnnotationProcessors =
+        getKspAnnotationProcessors(getAnnotationProcessors(annotationProcessorParams));
+
+    KSPInvocationStatus kspInvocationStatus = KSPInvocationStatus.NOT_INVOKED;
+
+    // We need to generate the KSP generation folder anyway, to help IntelliJ with red
+    // symbols.
+    RelPath kspAnnotationGenFolder = buildTargetValueExtraParams.getKspAnnotationGenPath();
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kspAnnotationGenFolder));
+
+    if (kspAnnotationProcessors.isEmpty()) {
+      return kspInvocationStatus;
+    }
+
+    steps.add(new MkdirIsolatedStep(outputDirectory));
+    // KSP folders
+    RelPath kspOutputBaseDir = buildTargetValueExtraParams.getAnnotationOutputBasePath();
+    RelPath kspClassesOutput =
+        buildTargetValueExtraParams.getAnnotationOutputPath("__%s_ksp_classes__");
+    RelPath kspKotlinOutput =
+        buildTargetValueExtraParams.getAnnotationOutputPath("__%s_ksp_generated_kotlin__");
+    RelPath kspJavaOutput =
+        buildTargetValueExtraParams.getAnnotationOutputPath("__%s_ksp_generated_java__");
+    RelPath kspResOutput =
+        buildTargetValueExtraParams.getAnnotationOutputPath("__%s_ksp_res_output__");
+    RelPath kspCachesOutput =
+        buildTargetValueExtraParams.getAnnotationOutputPath("__%s_ksp_cache_output__");
+    RelPath kspMetaOutput =
+        buildTargetValueExtraParams.getAnnotationOutputPath("__%s_ksp_meta_output__");
+
+    // More KSP folders
+    RelPath kspGenOutputFolder = buildTargetValueExtraParams.getGenPath("__%s_ksp_gen_sources__");
+    RelPath kspGenOutput =
+        buildTargetValueExtraParams.getGenPath("__%s_ksp_gen_sources__/generated" + SRC_ZIP);
+
+    // Creating KSP dirs
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kspClassesOutput));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kspKotlinOutput));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kspJavaOutput));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kspResOutput));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kspCachesOutput));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kspMetaOutput));
+    steps.addAll(MakeCleanDirectoryIsolatedStep.of(kspGenOutputFolder));
+
+    ImmutableList<String> kspProcessorsClasspathList =
+        kspAnnotationProcessors.stream()
+            .map(p -> p.toUrlClasspath(rootPath))
+            .flatMap(List::stream)
+            .map(AnnotationProcessorUtils::urlToFile)
+            .collect(ImmutableList.toImmutableList());
+
+    kspInvocationStatus = KSPInvocationStatus.KSP2_INVOKED;
+
+    ImmutableList.Builder<AbsPath> allClassPathsBuilder = ImmutableList.builder();
+
+    allClassPathsBuilder.addAll(allClasspaths);
+
+    if (invokingRule.isSourceOnlyAbi()) {
+      allClassPathsBuilder.addAll(
+          compilationClasspath.stream().filter(p -> !allClasspaths.contains(p)).toList());
+    }
+
+    Ksp2Step ksp2Step =
+        new Ksp2Step(
+            invokingRule,
+            compilerOutputPaths,
+            rootPath,
+            shouldTrackClassUsage,
+            allClassPathsBuilder.build(),
+            kotlinPluginGeneratedOutFullPath,
+            annotationProcessorParams.getParameters(),
+            sourceFilePaths,
+            CompilerOutputPaths.getKspDepFilePath(reportsOutput),
+            moduleName,
+            kspProcessorsClasspathList,
+            kspClassesOutput,
+            kspKotlinOutput,
+            kspJavaOutput,
+            kspOutputBaseDir,
+            extraParams.getJvmTarget(),
+            extraParams.getLanguageVersion(),
+            getJvmDefaultMode(extraParams.getExtraKotlincArguments()),
+            extraParams.getJavaBinary(),
+            kotlinCDAnalytics,
+            Ksp2ModeFactory.create(
+                rootPath,
+                invokingRule.isSourceOnlyAbi(),
+                kspCachesOutput,
+                extraParams,
+                actionMetadata.orElse(null)));
+    steps.add(ksp2Step);
+    steps.addAll(
+        createKspOutputStagingSteps(
+            rootPath,
+            kspKotlinOutput,
+            kspJavaOutput,
+            kspClassesOutput,
+            kspAnnotationGenFolder,
+            kspGenOutput,
+            annotationGenFolder,
+            kspAnnotationProcessors));
+
+    // Generated classes should be part of the output. This way generated files such as
+    // META-INF dirs will also be added to the final jar.
+    postKotlinCompilationSteps.add(
+        CopyIsolatedStep.forDirectory(
+            kspClassesOutput.getPath(),
+            outputDirectory.getPath(),
+            CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+
+    sourceBuilderWithKspOutputs.add(kspGenOutput);
+
+    javacSourceBuilder.add(kspGenOutput);
+
+    return kspInvocationStatus;
+  }
+
+  static ImmutableList<IsolatedStep> createKspOutputStagingSteps(
+      AbsPath rootPath,
+      RelPath kspKotlinOutput,
+      RelPath kspJavaOutput,
+      RelPath kspClassesOutput,
+      RelPath kspAnnotationGenFolder,
+      RelPath kspGenOutput,
+      RelPath annotationGenFolder,
+      ImmutableList<ResolvedJavacPluginProperties> kspAnnotationProcessors) {
+    ImmutableList.Builder<IsolatedStep> stagingSteps = ImmutableList.builder();
+    stagingSteps.add(
+        CopyIsolatedStep.forDirectory(
+            kspKotlinOutput, kspAnnotationGenFolder, CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+    stagingSteps.add(
+        CopyIsolatedStep.forDirectory(
+            kspJavaOutput, kspAnnotationGenFolder, CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+    stagingSteps.add(
+        CopyIsolatedStep.forDirectory(
+            kspClassesOutput, kspAnnotationGenFolder, CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+
+    if (usesFinalRoundPlaceholder(kspAnnotationProcessors)) {
+      // The KSP adapter generates this empty source only to force KSP's final processing round.
+      // Keep it in KSP's own output for round and incremental bookkeeping, but exclude it from the
+      // staged generated sources consumed by Kotlin and javac.
+      stagingSteps.add(
+          new RmIsolatedStep(
+              kspAnnotationGenFolder.resolveRel("com/facebook/Dummy.java"),
+              false,
+              ImmutableSet.of()));
+    }
+
+    stagingSteps.add(
+        new ZipIsolatedStep(
+            rootPath,
+            kspGenOutput.getPath(),
+            ImmutableSet.of(),
+            ImmutableSet.of(),
+            false,
+            ZipCompressionLevel.DEFAULT,
+            kspAnnotationGenFolder.getPath()));
+    stagingSteps.add(
+        CopyIsolatedStep.forDirectory(
+            kspAnnotationGenFolder, annotationGenFolder, CopySourceMode.DIRECTORY_CONTENTS_ONLY));
+    return stagingSteps.build();
+  }
+
+  static boolean usesFinalRoundPlaceholder(
+      ImmutableList<ResolvedJavacPluginProperties> kspAnnotationProcessors) {
+    return kspAnnotationProcessors.stream()
+        .flatMap(processor -> processor.getProcessorNames().stream())
+        .anyMatch(PROCESSORS_USING_FINAL_ROUND_PLACEHOLDER::contains);
+  }
+
+  private static ImmutableList<String> getKspPluginsArgs(
+      ImmutableMap<AbsPath, ImmutableMap<String, String>> resolvedKotlinCompilerPlugins,
+      String outputDir) {
+    return getKotlinCompilerPluginsArgs(
+        resolvedKotlinCompilerPlugins,
+        outputDir,
+        KspStepsBuilder::isPluginRequiredForStandaloneKsp);
+  }
+
+  private static String getJvmDefaultMode(ImmutableList<String> args) {
+    for (String arg : args) {
+      String[] splitArg = arg.split("=");
+      if (splitArg.length == 2) {
+        if (splitArg[0].equals("-Xjvm-default")) {
+          return splitArg[1];
+        }
+        // Kotlin 2.3 renamed -Xjvm-default to -jvm-default with new mode names. Map them back to
+        // the legacy mode names KSP expects to preserve behavior.
+        if (splitArg[0].equals("-jvm-default")) {
+          switch (splitArg[1]) {
+            case "no-compatibility":
+              return "all";
+            case "enable":
+              return "all-compatibility";
+            case "disable":
+              return "disable";
+            default:
+              return splitArg[1];
+          }
+        }
+      }
+    }
+    return "disabled";
+  }
+
+  private static boolean isPluginRequiredForStandaloneKsp(
+      AbsPath sourcePath, ImmutableMap<String, String> options) {
+    return isKspPlugin(sourcePath) || CompilerPluginUtils.isDiK1PluginForKsp(sourcePath, options);
+  }
+
+  private static boolean isPluginNotRequiredForStandaloneKsp(
+      AbsPath sourcePath, ImmutableMap<String, String> options) {
+    return !isPluginRequiredForStandaloneKsp(sourcePath, options);
+  }
+
+  private static boolean isKspPlugin(AbsPath sourcePath) {
+    return sourcePath.toString().contains("symbol-processing");
+  }
+
+  public static boolean isNotKspPlugin(AbsPath sourcePath, ImmutableMap<String, String> options) {
+    return !isKspPlugin(sourcePath);
+  }
+
+  static ImmutableList<ResolvedJavacPluginProperties> getKspAnnotationProcessors(
+      ImmutableList<ResolvedJavacPluginProperties> annotationProcessors) {
+    return annotationProcessors.stream()
+        .filter(AnnotationProcessorUtils::isKSPProcessor)
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  public enum KSPInvocationStatus {
+    KSP2_INVOKED,
+    NOT_INVOKED
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/SnapshotsActionMetadata.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/SnapshotsActionMetadata.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/SnapshotsActionMetadata.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin
+
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.io.file.FileExtensionMatcher
+import com.facebook.buck.jvm.java.ActionMetadata
+import java.nio.file.Path
+import kotlin.collections.Map
+import kotlin.collections.component1
+import kotlin.collections.component2
+
+class SnapshotsActionMetadata(actionMetaData: ActionMetadata) {
+
+  val previousSnapshotsDigest: Map<Path, String> =
+      actionMetaData.previousDigest.filter { (path, _) ->
+        val relPath = RelPath.of(path)
+        SNAPSHOT_PATH_MATCHER.matches(relPath)
+      }
+
+  val currentSnapshotsDigest: Map<Path, String> =
+      actionMetaData.currentDigest.filter { (path, _) ->
+        val relPath = RelPath.of(path)
+        SNAPSHOT_PATH_MATCHER.matches(relPath)
+      }
+
+  fun hasClasspathChanged(): Boolean {
+    if (currentSnapshotsDigest.size != previousSnapshotsDigest.size) {
+      return true
+    }
+
+    return currentSnapshotsDigest.any { (path, digest) ->
+      !previousSnapshotsDigest.contains(path) || digest != previousSnapshotsDigest.getValue(path)
+    }
+  }
+
+  companion object {
+    private val SNAPSHOT_PATH_MATCHER = FileExtensionMatcher.of("bin")
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/SourceFilesActionMetadata.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/SourceFilesActionMetadata.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/SourceFilesActionMetadata.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin
+
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.io.file.FileExtensionMatcher
+import com.facebook.buck.jvm.java.ActionMetadata
+import java.nio.file.Path
+import kotlin.collections.Map
+import kotlin.collections.component1
+import kotlin.collections.component2
+
+class SourceFilesActionMetadata(actionMetaData: ActionMetadata) {
+
+  val previousSourceFilesDigest: Map<Path, String> =
+      actionMetaData.previousDigest.filter { (path, _) ->
+        val relPath = RelPath.of(path)
+        KT_PATH_MATCHER.matches(relPath) || JAVA_PATH_MATCHER.matches(relPath)
+      }
+
+  val currentSourceFilesDigest: Map<Path, String> =
+      actionMetaData.currentDigest.filter { (path, _) ->
+        val relPath = RelPath.of(path)
+        KT_PATH_MATCHER.matches(relPath) || JAVA_PATH_MATCHER.matches(relPath)
+      }
+
+  fun calculateAddedAndModifiedSourceFiles(): List<Path> = buildList {
+    for ((path, digest) in currentSourceFilesDigest) {
+      if (previousSourceFilesDigest[path] != digest) {
+        add(path)
+      }
+    }
+  }
+
+  fun calculateRemovedFiles(): List<Path> = buildList {
+    for ((path, digest) in previousSourceFilesDigest) {
+      if (!currentSourceFilesDigest.containsKey(path)) {
+        add(path)
+      }
+    }
+  }
+
+  companion object {
+    private val KT_PATH_MATCHER = FileExtensionMatcher.of("kt")
+    private val JAVA_PATH_MATCHER = FileExtensionMatcher.of("java")
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/BUCK
@@ -0,0 +1,16 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "abtesting",
+    srcs = glob(["**/*.kt"]),
+    visibility = [
+        "prelude//toolchains/android/meta_only/src/com/facebook/buck/jvm/kotlin/abtesting/...",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/...",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ExperimentConfig.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ExperimentConfig.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ExperimentConfig.kt
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.abtesting
+
+interface ExperimentConfig {
+
+  fun getBoolParam(param: String, default: Boolean): Boolean
+
+  fun getIntParam(param: String, default: Int): Int
+
+  fun getStringParam(param: String, default: String): String
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ExperimentConfigService.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ExperimentConfigService.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ExperimentConfigService.kt
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.abtesting
+
+import java.util.ServiceLoader
+
+interface ExperimentConfigService {
+
+  fun loadConfig(universeName: String): ExperimentConfig
+
+  companion object {
+    @JvmStatic
+    fun loadImplementation(): ExperimentConfigService {
+      val implementations = ServiceLoader.load(ExperimentConfigService::class.java)
+      implementations.firstOrNull()
+          ?: error(
+              "The classpath contains no implementation for ${ExperimentConfigService::class.qualifiedName}",
+          )
+      return implementations.singleOrNull()
+          ?: error(
+              "The classpath contains more than one implementation for ${ExperimentConfigService::class.qualifiedName}",
+          )
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ksic/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ksic/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ksic/BUCK
@@ -0,0 +1,15 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "ksic",
+    srcs = glob(["**/*.kt"]),
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/...",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ksic/KsicExperimentConstants.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ksic/KsicExperimentConstants.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/ksic/KsicExperimentConstants.kt
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.abtesting.ksic
+
+const val UNIVERSE_NAME: String = "devx_ksic_universe"
+const val PARAM_KSIC_ENABLED: String = "ksic_enabled"
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/BUCK
@@ -0,0 +1,21 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "noop",
+    srcs = glob(["**/*.kt"]),
+    labels = ["codegen_rule"],
+    resources = glob(["resources/**/*"]),
+    resources_root = "resources",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting:abtesting",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/NoopExperimentConfig.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/NoopExperimentConfig.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/NoopExperimentConfig.kt
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.abtesting.noop
+
+import com.facebook.buck.jvm.kotlin.abtesting.ExperimentConfig
+
+internal object NoopExperimentConfig : ExperimentConfig {
+  override fun getBoolParam(param: String, default: Boolean): Boolean = default
+
+  override fun getIntParam(param: String, default: Int): Int = default
+
+  override fun getStringParam(param: String, default: String): String = default
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/NoopExperimentConfigService.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/NoopExperimentConfigService.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/NoopExperimentConfigService.kt
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.abtesting.noop
+
+import com.facebook.buck.jvm.kotlin.abtesting.ExperimentConfig
+import com.facebook.buck.jvm.kotlin.abtesting.ExperimentConfigService
+
+class NoopExperimentConfigService : ExperimentConfigService {
+  override fun loadConfig(universeName: String): ExperimentConfig = NoopExperimentConfig
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/resources/META-INF/services/com.facebook.buck.jvm.kotlin.abtesting.ExperimentConfigService b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/resources/META-INF/services/com.facebook.buck.jvm.kotlin.abtesting.ExperimentConfigService
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/abtesting/noop/resources/META-INF/services/com.facebook.buck.jvm.kotlin.abtesting.ExperimentConfigService
@@ -0,0 +1,1 @@
+com.facebook.buck.jvm.kotlin.abtesting.noop.NoopExperimentConfigService
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BUCK
@@ -0,0 +1,33 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "buildtools",
+    srcs = glob(["**/*.kt"]),
+    extra_kotlinc_arguments = ["-Xopt-in=kotlin.ExperimentalStdlibApi"],
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/buildtools:buildtools",
+    ],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/...",
+    ],
+    deps = [
+        # @oss-disable[end= ]: "fbsource//fbandroid/java/com/facebook/kotlin/compilercompat:compilercompat",
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:javacd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/build/execution/context:context",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/javax:javax",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics:analytics",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc:kotlinc",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental:incremental",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:kotlin-build-tools-api",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BuckKotlinLogger.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BuckKotlinLogger.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BuckKotlinLogger.kt
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.buildtools
+
+import org.jetbrains.kotlin.buildtools.api.KotlinLogger // @oss-enable
+import com.facebook.buck.core.util.log.Logger
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDLoggingContext
+// @oss-disable: import com.facebook.kotlin.compilercompat.KotlinLoggerCompat
+import java.io.PrintStream
+import java.util.logging.Level
+
+internal class BuckKotlinLogger(
+    private val stdErr: PrintStream,
+    private val loggingContext: KotlinCDLoggingContext,
+)
+: KotlinLogger // @oss-enable
+// @oss-disable: : KotlinLoggerCompat()
+{
+
+  override val isDebugEnabled: Boolean
+    get() = LOG.isDebugEnabled
+
+  override fun debug(msg: String) {
+    if (!LOG.isDebugEnabled) return
+    LOG.debug(msg)
+  }
+
+  override fun error(msg: String, throwable: Throwable?) {
+    if (!LOG.isLoggable(Level.SEVERE)) return
+    stdErr.println(msg)
+    throwable?.printStackTrace(stdErr)
+  }
+
+  override fun info(msg: String) {
+    if (msg.startsWith("Non-incremental compilation will be performed")) {
+      loggingContext.addExtras(BuckKotlinLogger::class.java.simpleName, msg)
+    }
+    if (msg.startsWith("KOTLIN_BUILD_METRIC|")) {
+      loggingContext.addExtras("BuildMetrics", msg.removePrefix("KOTLIN_BUILD_METRIC|"))
+    }
+
+    if (!LOG.isLoggable(Level.INFO)) return
+    LOG.info(msg)
+  }
+
+  override fun lifecycle(msg: String) {
+    if (!LOG.isLoggable(Level.INFO)) return
+    LOG.info(msg)
+  }
+
+  override fun warn(msg: String) {
+    if (!LOG.isLoggable(Level.WARNING)) return
+    stdErr.println(msg)
+  }
+
+  // OSS-only: the internal `KotlinLoggerCompat` supertype lacks this Kotlin 2.2
+  // overload on some toolchain configurations.
+    override fun warn(msg: String, throwable: Throwable?) { // @oss-enable
+      if (!LOG.isLoggable(Level.WARNING)) return // @oss-enable
+      stdErr.println(msg) // @oss-enable
+      throwable?.printStackTrace(stdErr) // @oss-enable
+    } // @oss-enable
+
+  companion object {
+    private val LOG: Logger = Logger.get(BuckKotlinLogger::class.java)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BuildToolsKotlinc.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BuildToolsKotlinc.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/BuildToolsKotlinc.kt
@@ -0,0 +1,271 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.buildtools
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.core.util.log.Logger
+import com.facebook.buck.jvm.core.BuildTargetValue
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDLoggingContext
+import com.facebook.buck.jvm.kotlin.cd.analytics.SourceTokenCounter
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode
+import com.facebook.buck.util.ClassLoaderCache
+import com.google.common.collect.ImmutableList
+import com.google.common.collect.ImmutableSortedSet
+import java.io.IOException
+import java.io.PrintStream
+import java.nio.file.Path
+import java.util.Optional
+import java.util.UUID
+import kotlin.io.path.extension
+import org.jetbrains.kotlin.buildtools.api.CompilationService
+import org.jetbrains.kotlin.buildtools.api.ExperimentalBuildToolsApi
+import org.jetbrains.kotlin.buildtools.api.ProjectId
+
+/**
+ * Entry point for Kotlin compilation using BuildToolsApi. See:
+ * https://github.com/JetBrains/kotlin/blob/master/compiler/build-tools/kotlin-build-tools-api/README.md
+ */
+@OptIn(ExperimentalBuildToolsApi::class)
+class BuildToolsKotlinc : Kotlinc {
+
+  override fun buildWithClasspath(
+      context: IsolatedExecutionContext,
+      invokingRule: BuildTargetValue,
+      options: ImmutableList<String>,
+      kotlinHomeLibraries: ImmutableList<AbsPath>,
+      kotlinSourceFilePaths: ImmutableSortedSet<RelPath>,
+      pathToSrcsList: Path,
+      workingDirectory: Optional<Path>,
+      ruleCellRoot: AbsPath,
+      mode: KotlincMode,
+      kotlinCDLoggingContext: KotlinCDLoggingContext,
+  ): Int {
+    val argsStart = System.nanoTime()
+    val compilerArgs = buildCompilerArgs(
+        ruleCellRoot,
+        kotlinSourceFilePaths,
+        workingDirectory,
+        invokingRule,
+        options,
+        kotlinCDLoggingContext,
+    )
+    val argsMs = (System.nanoTime() - argsStart) / 1_000_000
+
+    LOG.info(
+        "[KotlinC Toolchain Build Step from for target:${invokingRule.fullyQualifiedName} type:${invokingRule.type}] " +
+            "Running ${CompilationService::class.java.name} ${getIncrementalInfoMessage(mode)} " +
+            "with arguments:[${compilerArgs.joinToString()}] ",
+    )
+
+    // Machine-parseable log entry for tooling
+    // Format: KOTLINCD_INVOCATION|target|type|incremental|arg_count
+    // Followed by: KOTLINCD_ARG|<arg> for each argument
+    LOG.info(
+        "KOTLINCD_INVOCATION|${invokingRule.fullyQualifiedName}|${invokingRule.type}|${getIncrementalInfoMessage(mode)}|${compilerArgs.size}",
+    )
+    compilerArgs.forEach { arg -> LOG.info("KOTLINCD_ARG|$arg") }
+
+    val classLoaderStart = System.nanoTime()
+    val classLoader = context.classLoaderCache.getClassLoader(kotlinHomeLibraries)
+    val classLoaderMs = (System.nanoTime() - classLoaderStart) / 1_000_000
+
+    val serviceLoadStart = System.nanoTime()
+    val kotlinCompilationService = KotlinCompilationService(
+        CompilationService.loadImplementation(classLoader),
+        kotlinCDLoggingContext,
+    )
+    val serviceLoadMs = (System.nanoTime() - serviceLoadStart) / 1_000_000
+
+    val gcBefore = getGcStats()
+    val compileStart = System.nanoTime()
+    val result =
+        kotlinCompilationService.compile(
+            ProjectId.ProjectUUID(UUID.randomUUID()),
+            compilerArgs,
+            mode,
+            BuckKotlinLogger(UncloseablePrintStream(context.stdErr), kotlinCDLoggingContext),
+        )
+    val compileMs = (System.nanoTime() - compileStart) / 1_000_000
+    val gcAfter = getGcStats()
+    val gcDeltaMs = gcAfter.first - gcBefore.first
+    val gcDeltaCount = gcAfter.second - gcBefore.second
+
+    LOG.info(
+        "KOTLINCD_TIMING|${invokingRule.fullyQualifiedName}|args_ms=$argsMs|classloader_ms=$classLoaderMs|service_load_ms=$serviceLoadMs|compile_ms=$compileMs|gc_time_ms=$gcDeltaMs|gc_count=$gcDeltaCount",
+    )
+
+    return result.toExitCode.code
+  }
+
+  private fun getGcStats(): Pair<Long, Long> {
+    var totalMs = 0L
+    var totalCount = 0L
+    for (bean in java.lang.management.ManagementFactory.getGarbageCollectorMXBeans()) {
+      val time = bean.collectionTime
+      val count = bean.collectionCount
+      if (time >= 0) totalMs += time
+      if (count >= 0) totalCount += count
+    }
+    return Pair(totalMs, totalCount)
+  }
+
+  private fun getIncrementalInfoMessage(mode: KotlincMode) =
+      when (mode) {
+        is KotlincMode.Incremental -> "incrementally"
+        is KotlincMode.NonIncremental -> "non incrementally"
+        else -> throw UnsupportedOperationException("Unsupported KotlincMode")
+      }
+
+  private fun ClassLoaderCache.getClassLoader(kotlinHomeLibraries: List<AbsPath>): ClassLoader {
+    val classPathURLs = kotlinHomeLibraries.map { absPath -> absPath.path.toUri().toURL() }
+    return getClassLoaderForClassPath(
+        SharedApiClassesClassLoaderProvider.sharedApiClassesClassLoader,
+        ImmutableList.copyOf(classPathURLs),
+    )
+  }
+
+  private fun buildCompilerArgs(
+      ruleCellRoot: AbsPath,
+      kotlinSourceFilePaths: ImmutableSortedSet<RelPath>,
+      workingDirectory: Optional<Path>,
+      invokingRule: BuildTargetValue,
+      options: List<String>,
+      kotlinCDLoggingContext: KotlinCDLoggingContext,
+  ): List<String> {
+    val expandStart = System.nanoTime()
+    val expandedSources: ImmutableList<Path> = getExpandedSourcePathsOrThrow(
+        ruleCellRoot,
+        kotlinSourceFilePaths,
+        workingDirectory,
+        invokingRule,
+    )
+    val expandMs = (System.nanoTime() - expandStart) / 1_000_000
+    if (expandMs > 100) {
+      LOG.info(
+          "KOTLINCD_SOURCE_EXPAND|${invokingRule.fullyQualifiedName}|expand_ms=$expandMs|source_count=${expandedSources.size}",
+      )
+    }
+
+    expandedSources
+        .groupingBy { path -> path.extension }
+        .eachCount()
+        .forEach { (extension, count) ->
+          kotlinCDLoggingContext.addExtras(
+              BuildToolsKotlinc::class.java.simpleName,
+              "Total count of $extension files: $count",
+          )
+        }
+
+    try {
+      val tokenCounts = SourceTokenCounter.countTokens(expandedSources, ruleCellRoot.path)
+      kotlinCDLoggingContext.numKotlinTokens = tokenCounts.kotlinTokens
+      kotlinCDLoggingContext.numJavaTokens = tokenCounts.javaTokens
+    } catch (e: Exception) {
+      // Token counting is best-effort telemetry; don't fail the build
+      kotlinCDLoggingContext.addExtras(
+          BuildToolsKotlinc::class.java.simpleName,
+          "Token counting failed: ${e.message}",
+      )
+    }
+
+    val resolvedExpandedSources = expandedSources.map { path ->
+      ruleCellRoot.resolve(path).toString()
+    }
+
+    val isMultiPlatform = options.contains("-Xmulti-platform")
+
+    return buildList {
+      // Kotlin Multiplatform parameters pass-in source paths for each fragment
+      // Similar to main source paths, we need to expand them as well
+      if (isMultiPlatform) {
+        val expandedOptions =
+            getExpandedMultiPlatformSourcePathsOrThrow(options, resolvedExpandedSources)
+        addAll(expandedOptions)
+      } else {
+        addAll(options)
+      }
+
+      addAll(resolvedExpandedSources)
+    }
+  }
+
+  private fun getExpandedSourcePathsOrThrow(
+      ruleCellRoot: AbsPath,
+      kotlinSourceFilePaths: ImmutableSortedSet<RelPath>,
+      workingDirectory: Optional<Path>,
+      invokingRule: BuildTargetValue,
+  ) =
+      try {
+        getExpandedSourcePaths(ruleCellRoot, kotlinSourceFilePaths, workingDirectory)
+      } catch (exception: IOException) {
+        LOG.error(exception)
+        throw RuntimeException(
+            "Unable to expand sources for ${invokingRule.fullyQualifiedName} into $workingDirectory",
+        )
+      }
+
+  private fun getExpandedMultiPlatformSourcePathsOrThrow(
+      options: List<String>,
+      allSources: List<String>,
+  ): List<String> =
+      buildList() {
+        options
+            .filter { !it.isNullOrBlank() }
+            .forEach { option ->
+              if (option.startsWith("-Xfragment-sources")) {
+                val (fragmentSourcesKey, unresolvedSources) = option.split("=")
+                // construct `fragmentName:absolutePath` for each fragment source path
+                // e.g. `-Xfragment-sources=android:/abs/path/A.kt,common:/abs/path/B.kt`
+                val resolvedSourceOption =
+                    unresolvedSources.split(",").map { fragmentSourcePath ->
+                      val (fragmentName, fragmentPath) = fragmentSourcePath.split(":")
+                      val fragmentSourceAbsPath = allSources.firstOrNull {
+                        it.endsWith(fragmentPath)
+                      }
+
+                      if (fragmentSourceAbsPath == null) {
+                        throw RuntimeException("Invalid fragment source path: $fragmentSourcePath")
+                      }
+                      "$fragmentName:$fragmentSourceAbsPath"
+                    }
+                add("$fragmentSourcesKey=${resolvedSourceOption.joinToString(",")}")
+              } else {
+                add(option)
+              }
+            }
+      }
+
+  override fun getDescription(
+      options: ImmutableList<String>,
+      kotlinSourceFilePaths: ImmutableSortedSet<RelPath>,
+      pathToSrcsList: Path,
+  ): String = buildString {
+    append("kotlinc ")
+    append(options.joinToString(separator = " "))
+    append(" @")
+    append(pathToSrcsList)
+  }
+
+  override fun getShortName(): String = "kotlinc"
+
+  companion object {
+    private val LOG: Logger = Logger.get(BuildToolsKotlinc::class.java)
+  }
+}
+
+private class UncloseablePrintStream(delegate: PrintStream) : PrintStream(delegate) {
+  override fun close() {
+    // ignore
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/ExitCode.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/ExitCode.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/ExitCode.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.buildtools
+
+import com.facebook.buck.jvm.kotlin.kotlinc.Kotlinc
+import org.jetbrains.kotlin.buildtools.api.CompilationResult
+
+/**
+ * Copy of [org.jetbrains.kotlin.cli.common.ExitCode]. It allows [BuildToolsKotlinc] to implement
+ * the [Kotlinc] interface without depending on the Kotlin compiler directly.
+ */
+internal enum class ExitCode(val code: Int) {
+  OK(0),
+  COMPILATION_ERROR(1),
+  INTERNAL_ERROR(2),
+  OOM_ERROR(137),
+}
+
+internal val CompilationResult.toExitCode: ExitCode
+  get() =
+      when (this) {
+        CompilationResult.COMPILATION_SUCCESS -> ExitCode.OK
+        CompilationResult.COMPILATION_ERROR -> ExitCode.COMPILATION_ERROR
+        CompilationResult.COMPILER_INTERNAL_ERROR -> ExitCode.INTERNAL_ERROR
+        CompilationResult.COMPILATION_OOM_ERROR -> ExitCode.OOM_ERROR
+        else -> error("Unexpected exit code: $this")
+      }
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/JvmCompilationConfigurationFactory.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/JvmCompilationConfigurationFactory.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/JvmCompilationConfigurationFactory.kt
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.buildtools
+
+import com.facebook.buck.core.util.log.Logger
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDLoggingContext
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.ClasspathChanges
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode.Incremental
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode.NonIncremental
+import org.jetbrains.kotlin.buildtools.api.CompilationService
+import org.jetbrains.kotlin.buildtools.api.ExperimentalBuildToolsApi
+import org.jetbrains.kotlin.buildtools.api.jvm.ClasspathSnapshotBasedIncrementalCompilationApproachParameters
+import org.jetbrains.kotlin.buildtools.api.jvm.JvmCompilationConfiguration
+
+@OptIn(ExperimentalBuildToolsApi::class)
+internal class JvmCompilationConfigurationFactory(
+    private val compilationService: CompilationService,
+    private val kotlinCDLoggingContext: KotlinCDLoggingContext,
+) {
+
+  fun create(mode: KotlincMode): JvmCompilationConfiguration =
+      when (mode) {
+        is NonIncremental -> {
+          compilationService.makeJvmCompilationConfiguration()
+        }
+        is Incremental -> {
+          compilationService.makeJvmCompilationConfiguration().apply {
+            useIncrementalCompilation(
+                workingDirectory = mode.kotlicWorkingDir.toFile(),
+                sourcesChanges = mode.kotlinSourceChanges.toSourcesChanges(),
+                approachParameters =
+                    ClasspathSnapshotBasedIncrementalCompilationApproachParameters(
+                        newClasspathSnapshotFiles = mode.classpathChanges.classpathSnapshotFiles,
+                        shrunkClasspathSnapshot =
+                            mode.kotlicWorkingDir.resolve("shrunk-classpath-snapshot.bin").toFile(),
+                    ),
+                options =
+                    makeClasspathSnapshotBasedIncrementalCompilationConfiguration().apply {
+                      setRootProjectDir(mode.rootProjectDir.toFile())
+                      setBuildDir(mode.buildDir.toFile())
+                      usePreciseCompilationResultsBackup(true)
+                      keepIncrementalCompilationCachesInMemory(true)
+
+                      val rebuildReason = mode.rebuildReason
+                      if (rebuildReason != null) {
+                        LOG.info(
+                            "Non-incremental compilation will be performed: ${rebuildReason.message}",
+                        )
+                        kotlinCDLoggingContext.addExtras(
+                            JvmCompilationConfigurationFactory::class.java.simpleName,
+                            "Non-incremental compilation will be performed: ${rebuildReason.message}",
+                        )
+                        forceNonIncrementalMode(true)
+                      }
+
+                      when (mode.classpathChanges) {
+                        is ClasspathChanges.Unknown -> {
+                          LOG.info(
+                              "Non-incremental compilation will be performed: classpath changes not available",
+                          )
+                          kotlinCDLoggingContext.addExtras(
+                              JvmCompilationConfigurationFactory::class.java.simpleName,
+                              "Non-incremental compilation will be performed: classpath changes not available",
+                          )
+                          forceNonIncrementalMode(true)
+                        }
+                        is ClasspathChanges.NoChanges -> {
+                          assureNoClasspathSnapshotsChanges(true)
+                        }
+                        is ClasspathChanges.ToBeComputedByIncrementalCompiler -> {
+                          // The Kotlin incremental compiler handles classpath changes
+                          // (additions, modifications, and removals).
+                        }
+                      }
+                    },
+            )
+          }
+        }
+      }
+
+  companion object {
+    private val LOG: Logger = Logger.get(JvmCompilationConfigurationFactory::class.java)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/KotlinCompilationService.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/KotlinCompilationService.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/KotlinCompilationService.kt
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.buildtools
+
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDLoggingContext
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode
+import org.jetbrains.kotlin.buildtools.api.CompilationResult
+import org.jetbrains.kotlin.buildtools.api.CompilationService
+import org.jetbrains.kotlin.buildtools.api.ExperimentalBuildToolsApi
+import org.jetbrains.kotlin.buildtools.api.KotlinLogger
+import org.jetbrains.kotlin.buildtools.api.ProjectId
+
+@OptIn(ExperimentalBuildToolsApi::class)
+internal class KotlinCompilationService(
+    private val compilationService: CompilationService,
+    kotlinCDLoggingContext: KotlinCDLoggingContext,
+) {
+
+  private val jvmCompilationConfigurationFactory =
+      JvmCompilationConfigurationFactory(compilationService, kotlinCDLoggingContext)
+
+  fun compile(
+      projectId: ProjectId,
+      arguments: List<String>,
+      mode: KotlincMode,
+      logger: KotlinLogger? = null,
+  ): CompilationResult {
+    val compilerExecutionStrategyConfiguration =
+        compilationService.makeCompilerExecutionStrategyConfiguration()
+
+    val jvmCompilationConfiguration =
+        jvmCompilationConfigurationFactory.create(mode).apply {
+          if (logger != null) {
+            useLogger(logger)
+          }
+        }
+
+    return compilationService.compileJvm(
+        projectId,
+        compilerExecutionStrategyConfiguration,
+        jvmCompilationConfiguration,
+        emptyList(),
+        arguments,
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/SharedApiClassesClassLoaderProvider.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/SharedApiClassesClassLoaderProvider.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/SharedApiClassesClassLoaderProvider.kt
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.buildtools
+
+import org.jetbrains.kotlin.buildtools.api.ExperimentalBuildToolsApi
+import org.jetbrains.kotlin.buildtools.api.SharedApiClassesClassLoader
+
+@OptIn(ExperimentalBuildToolsApi::class)
+internal object SharedApiClassesClassLoaderProvider {
+  val sharedApiClassesClassLoader: ClassLoader = SharedApiClassesClassLoader()
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/SourceChangesExtensions.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/SourceChangesExtensions.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/SourceChangesExtensions.kt
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:OptIn(ExperimentalBuildToolsApi::class)
+
+package com.facebook.buck.jvm.kotlin.buildtools
+
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlinSourceChanges
+import org.jetbrains.kotlin.buildtools.api.ExperimentalBuildToolsApi
+import org.jetbrains.kotlin.buildtools.api.SourcesChanges
+
+internal fun KotlinSourceChanges.toSourcesChanges(): SourcesChanges =
+    when (this) {
+      is KotlinSourceChanges.ToBeCalculated -> {
+        SourcesChanges.ToBeCalculated
+      }
+      is KotlinSourceChanges.Known -> {
+        SourcesChanges.Known(
+            this.addedAndModifiedFiles.map { path -> path.toFile() },
+            this.removedFiles.map { it.toFile() },
+        )
+      }
+    }
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/BUCK
@@ -0,0 +1,59 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_kotlin_library", "buck_prebuilt_artifact", "buck_prebuilt_jar")
+load("@prelude//toolchains/android/tools/build_rules:fb_native.bzl", "fb_native")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "cp_snapshot_generator_lib",
+    srcs = glob(
+        ["**/*.kt"],
+    ),
+    extra_kotlinc_arguments = ["-Xopt-in=kotlin.ExperimentalStdlibApi"],
+    labels = ["codegen_rule"],  # see: https://fburl.com/workplace/fhud6fe6
+    visibility = ["PUBLIC"],
+    runtime_deps = [
+        "prelude//toolchains/android/third-party:kotlin-build-tools-impl",
+        "prelude//toolchains/android/third-party:kotlin-compiler-embeddable",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:kotlin-build-tools-api",
+    ],
+)
+
+buck_java_binary(
+    name = "cp_snapshot_generator_binary",
+    main_class = "com.facebook.buck.jvm.kotlin.buildtools.snapshot.Main",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":cp_snapshot_generator_lib",
+    ],
+)
+
+fb_native.alias(
+    name = "cp_snapshot_generator",
+    actual = ":cp_snapshot_generator_prebuilt",
+    visibility = ["PUBLIC"],
+)
+
+# This is a prebuilt jar so that it can be part of the buck2 bootstrap toolchain.
+buck_prebuilt_jar(
+    name = "cp_snapshot_generator_prebuilt",
+    binary_jar = ":cp_snapshot_generator.jar",
+    is_executable = True,
+    should_generate_snapshot = False,
+    visibility = ["PUBLIC"],
+)
+
+# To rebuild the jar and upload it to CAS, do:
+# buck build prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot:cp_snapshot_generator_binary --show-simple-output | xargs frecli --use-case android_build_infra_tools cas upload-blob
+buck_prebuilt_artifact(
+    name = "cp_snapshot_generator.jar",
+    # @oss-disable[end= ]: cas_digest = "0febd203f9e94fa652a9e26c18d50b17ffc6d3ba23ccde84b2f785a25b4adacf:60666465",
+    oss_sha1 = "1bbf0a79f5c88a4bb316ebd98dfca7b615aae52a",
+    oss_url = "https://github.com/facebook/buck2/releases/download/androidToolchain%2F2025-04-03/cp_snapshot_generator.jar",
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/ClasspathSnapshotGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/ClasspathSnapshotGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/ClasspathSnapshotGenerator.kt
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.buildtools.snapshot
+
+import com.facebook.buck.core.util.log.Logger
+import java.nio.file.Path
+import kotlin.system.measureTimeMillis
+import org.jetbrains.kotlin.buildtools.api.CompilationService
+import org.jetbrains.kotlin.buildtools.api.ExperimentalBuildToolsApi
+
+@OptIn(ExperimentalBuildToolsApi::class)
+class ClasspathSnapshotGenerator(
+    private val inputJar: Path,
+    private val outputSnapshot: Path,
+    private val granularity: SnapshotGranularity,
+) {
+
+  fun run() {
+    val timeSpent = measureTimeMillis {
+      val compilationService = CompilationService.loadImplementation(this.javaClass.classLoader!!)
+      val snapshot =
+          compilationService.calculateClasspathSnapshot(
+              inputJar.toFile(),
+              granularity.toClassSnapshotGranularity,
+          )
+      snapshot.saveSnapshot(outputSnapshot.toFile())
+    }
+    LOG.info("Classpath snapshot generation took $timeSpent ms for input jar: $inputJar")
+  }
+
+  companion object {
+    private val LOG: Logger = Logger.get(ClasspathSnapshotGenerator::class.java)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/Main.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/Main.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/Main.kt
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.buildtools.snapshot
+
+import java.nio.file.Path
+import org.kohsuke.args4j.CmdLineException
+import org.kohsuke.args4j.CmdLineParser
+import org.kohsuke.args4j.Option
+
+object Main {
+  @Option(name = "--input-jar", usage = "Path to input jar", required = true)
+  private lateinit var inputJar: Path
+  @Option(name = "--output-snapshot", usage = "Path to write output snapshot", required = true)
+  private lateinit var outputSnapshot: Path
+  @Option(name = "--granularity", usage = "Granulairyt of snapshot", required = true)
+  private lateinit var granularity: SnapshotGranularity
+
+  @JvmStatic
+  fun main(args: Array<String>) {
+    val parser = CmdLineParser(this)
+    try {
+      parser.parseArgument(*args)
+    } catch (e: CmdLineException) {
+      System.err.println(e.message.toString())
+      parser.printUsage(System.err)
+      throw e
+    }
+
+    val generator = ClasspathSnapshotGenerator(inputJar, outputSnapshot, granularity)
+    generator.run()
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/SnapshotGranularity.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/SnapshotGranularity.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot/SnapshotGranularity.kt
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.buildtools.snapshot
+
+import org.jetbrains.kotlin.buildtools.api.jvm.ClassSnapshotGranularity
+
+enum class SnapshotGranularity {
+  CLASS_LEVEL,
+  CLASS_MEMBER_LEVEL;
+
+  val toClassSnapshotGranularity: ClassSnapshotGranularity
+    get() =
+        when (this) {
+          CLASS_LEVEL -> ClassSnapshotGranularity.CLASS_LEVEL
+          CLASS_MEMBER_LEVEL -> ClassSnapshotGranularity.CLASS_MEMBER_LEVEL
+        }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/BUCK
@@ -0,0 +1,22 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "analytics",
+    srcs = glob(["**/*.kt"]),
+    extra_kotlinc_arguments = ["-Xopt-in=kotlin.ExperimentalStdlibApi"],
+    labels = ["codegen_rule"],
+    tests = ["prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/cd/analytics/logger:logger"],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:language-version",
+        "prelude//toolchains/android/third-party:kotlin-compiler",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDAnalytics.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDAnalytics.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDAnalytics.kt
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.analytics
+
+/**
+ * An utility class designed for logging operations in KotlinCD.
+ *
+ * @see KotlinCDLoggingContext for details on parameter handling.
+ */
+abstract class KotlinCDAnalytics {
+
+  /**
+   * Writes the accumulated data in the provided [KotlinCDLoggingContext] to the underlying logging
+   * system. This method must be implemented by concrete subclasses to handle the actual logging
+   * process.
+   */
+  abstract fun log(context: KotlinCDLoggingContext)
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDLoggingContext.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDLoggingContext.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDLoggingContext.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.analytics
+
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersion
+
+/** A logging context designed to accumulate data relevant to KotlinCD operations. */
+class KotlinCDLoggingContext(
+    val step: StepParam,
+    val languageVersion: LanguageVersion,
+    val mode: ModeParam?,
+) {
+
+  val classpathChangesParam = (mode as? ModeParam.Incremental)?.classpathChangesParam
+
+  var numKotlinTokens: Long = 0L
+  var numJavaTokens: Long = 0L
+
+  /** Wall-clock duration of the step, in milliseconds; null when the step does not time itself. */
+  var durationMs: Long? = null
+
+  private val _extras: MutableMap<String, MutableList<String>> = mutableMapOf()
+  val extras: Map<String, List<String>>
+    get() = _extras
+
+  fun addExtras(key: String, value: String) {
+    _extras.computeIfAbsent(key) { mutableListOf() }.add(value)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDLoggingParams.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDLoggingParams.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/KotlinCDLoggingParams.kt
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.analytics
+
+import com.facebook.buck.core.filesystems.AbsPath
+
+enum class StepParam(val value: String) {
+  KOTLINC("kotlinc"),
+  KOSABI_STUBGEN("kosabi_stubgen"),
+  KSP2("ksp2"),
+  KAPT("kapt"),
+}
+
+sealed class ModeParam(val value: String) {
+
+  data class Incremental(
+      val classpathChangesParam: ClasspathChangesParam,
+      // Null set indicates that the files are unknown, while empty set indicates that there are no
+      // files
+      val addedAndModifiedFiles: Set<AbsPath>? = null,
+      val removedFiles: Set<AbsPath>? = null,
+  ) : ModeParam("incremental")
+
+  data object NonIncremental : ModeParam("non_incremental")
+}
+
+enum class ClasspathChangesParam(val value: String) {
+  TO_BE_COMPUTED_BY_INCREMENTAL_COMPILER("to_be_computed_by_incremental_compiler"),
+  NO_CHANGES("no_changes"),
+  UNKNOWN("unknown"),
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/SourceTokenCounter.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/SourceTokenCounter.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/SourceTokenCounter.kt
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.analytics
+
+import java.nio.file.Files
+import java.nio.file.Path
+import org.jetbrains.kotlin.lexer.KotlinLexer
+import org.jetbrains.kotlin.lexer.KtTokens
+
+object SourceTokenCounter {
+  fun countTokens(sourcePaths: List<Path>, rootPath: Path): TokenCounts {
+    var kotlinTokens = 0L
+    var javaTokens = 0L
+    for (path in sourcePaths) {
+      val resolved = rootPath.resolve(path)
+      val ext = path.toString().substringAfterLast('.', "")
+      when (ext) {
+        "kt",
+        "kts" -> kotlinTokens += countKotlinTokens(resolved)
+        "java" -> javaTokens += countJavaTokens(resolved)
+      }
+    }
+    return TokenCounts(kotlinTokens, javaTokens)
+  }
+
+  private val SKIPPED_TOKEN_TYPES = setOf(
+      KtTokens.WHITE_SPACE,
+      KtTokens.EOL_COMMENT,
+      KtTokens.BLOCK_COMMENT,
+      KtTokens.DOC_COMMENT,
+      KtTokens.SHEBANG_COMMENT,
+  )
+
+  private fun countKotlinTokens(file: Path): Long {
+    val text = Files.readString(file)
+    val lexer = KotlinLexer()
+    lexer.start(text)
+    var count = 0L
+    while (lexer.tokenType != null) {
+      if (lexer.tokenType !in SKIPPED_TOKEN_TYPES) {
+        count++
+      }
+      lexer.advance()
+    }
+    return count
+  }
+
+  private fun countJavaTokens(file: Path): Long {
+    // Use StreamTokenizer for Java - lighter weight, no extra deps
+    val text = Files.readString(file)
+    val reader = java.io.StreamTokenizer(java.io.StringReader(text))
+    reader.slashSlashComments(true)
+    reader.slashStarComments(true)
+    reader.ordinaryChar('/'.code)
+    var count = 0L
+    while (reader.nextToken() != java.io.StreamTokenizer.TT_EOF) {
+      count++
+    }
+    return count
+  }
+}
+
+data class TokenCounts(val kotlinTokens: Long, val javaTokens: Long) {
+  val totalTokens: Long
+    get() = kotlinTokens + javaTokens
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/BUCK
@@ -0,0 +1,25 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "logger",
+    srcs = glob(["**/*.kt"]),
+    extra_kotlinc_arguments = ["-Xopt-in=kotlin.ExperimentalStdlibApi"],
+    labels = ["codegen_rule"],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:language-version",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics:analytics",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/model:model",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental:incremental",
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps:isolatedsteps",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/KotlinCDLogger.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/KotlinCDLogger.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/KotlinCDLogger.kt
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.analytics.logger
+
+import com.facebook.buck.jvm.kotlin.cd.analytics.logger.model.KotlinCDLogEntry
+import java.util.ServiceLoader
+
+interface KotlinCDLogger {
+  fun log(logEntry: KotlinCDLogEntry): Boolean
+
+  companion object {
+    @JvmStatic
+    fun loadImplementation(): KotlinCDLogger {
+      val implementations = ServiceLoader.load(KotlinCDLogger::class.java)
+      implementations.firstOrNull()
+          ?: error(
+              "The classpath contains no implementation for ${KotlinCDLogger::class.qualifiedName}",
+          )
+      return implementations.singleOrNull()
+          ?: error(
+              "The classpath contains more than one implementation for ${KotlinCDLogger::class.qualifiedName}",
+          )
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/KotlinCDLoggerAnalytics.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/KotlinCDLoggerAnalytics.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/KotlinCDLoggerAnalytics.kt
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.analytics.logger
+
+import com.facebook.buck.core.util.log.Logger
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersionForLogs
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDLoggingContext
+import com.facebook.buck.jvm.kotlin.cd.analytics.ModeParam
+import com.facebook.buck.jvm.kotlin.cd.analytics.logger.model.KotlinCDLogEntry
+import com.google.common.util.concurrent.ThreadFactoryBuilder
+import java.time.Clock
+import java.time.Duration
+import java.time.Instant
+import java.util.concurrent.ArrayBlockingQueue
+import java.util.concurrent.Executor
+import java.util.concurrent.RejectedExecutionHandler
+import java.util.concurrent.ThreadPoolExecutor
+import java.util.concurrent.TimeUnit
+
+class KotlinCDLoggerAnalytics
+@JvmOverloads
+constructor(
+    private val kotlinCDLogger: KotlinCDLogger,
+    private val buildUuid: String?,
+    private val target: String,
+    private val subtarget: String,
+    private val executionPlatform: String,
+    private val numJavaFiles: Long,
+    private val numKotlinFiles: Long,
+    private val incremental: Boolean,
+    private val clock: Clock = Clock.systemDefaultZone(),
+    private val executor: Executor = defaultLoggingExecutor,
+) : KotlinCDAnalytics() {
+
+  override fun log(context: KotlinCDLoggingContext) {
+    if (buildUuid == null) {
+      LOG.debug(
+          "No operation performed. This is expected when running an action downloaded from RE.",
+      )
+      return
+    }
+
+    // Build the log entry on the calling thread so its timestamps reflect when the
+    // action finished (and so an invalid language version fails fast here), then hand
+    // the blocking scribe write off the critical path.
+    val logEntry = createKotlinCDLogEntry(context)
+    executor.execute { writeLogEntry(logEntry) }
+  }
+
+  private fun writeLogEntry(logEntry: KotlinCDLogEntry) {
+    val start = Instant.now(clock)
+    val success: Boolean = kotlinCDLogger.log(logEntry)
+    val end = Instant.now(clock)
+
+    val duration = Duration.between(start, end)
+    if (success) {
+      LOG.info(
+          "Successfully wrote KotlinCD logs to scribe. Total time: " +
+              duration.toMillis() +
+              " milliseconds",
+      )
+    } else {
+      LOG.warn(
+          (("Failed to write KotlinCD logs to scribe. Total time: " +
+              duration.toMillis() +
+              " milliseconds")),
+      )
+    }
+  }
+
+  @OptIn(LanguageVersionForLogs::class)
+  private fun createKotlinCDLogEntry(context: KotlinCDLoggingContext): KotlinCDLogEntry {
+    val addedAndModifiedFiles: Set<String>? =
+        (context.mode as? ModeParam.Incremental)
+            ?.addedAndModifiedFiles
+            ?.map { it.toString() }
+            ?.toSet()
+    val removedFiles: Set<String>? =
+        (context.mode as? ModeParam.Incremental)?.removedFiles?.map { it.toString() }?.toSet()
+
+    return KotlinCDLogEntry(
+        time = Instant.now(clock).epochSecond,
+        eventTime = Instant.now(clock).epochSecond.toDouble(),
+        target = target,
+        subtarget = subtarget,
+        buildUuid = requireNotNull(buildUuid) { "buildUuid is required" },
+        executionPlatform = executionPlatform,
+        numKotlinFiles = numKotlinFiles,
+        numJavaFiles = numJavaFiles,
+        incremental = incremental,
+        mode = context.mode?.value,
+        classpathChanges = context.classpathChangesParam?.value,
+        step = context.step.value,
+        languageVersion = context.languageVersion.valueForLogs,
+        extras = buildJson(context.extras),
+        addedAndModifiedFiles = addedAndModifiedFiles,
+        removedFiles = removedFiles,
+        numKotlinTokens = context.numKotlinTokens.takeIf { it > 0 },
+        numJavaTokens = context.numJavaTokens.takeIf { it > 0 },
+        durationMs = context.durationMs,
+    )
+  }
+
+  private fun buildJson(extras: Map<String, List<String>>): String? {
+    if (extras.isEmpty()) {
+      return null
+    }
+
+    return "{${extras.map { (key, list) -> "\"${key}\": [${list.joinToString(transform = { "\"$it\"" })}]" }.joinToString()}}"
+  }
+
+  companion object {
+    private val LOG: Logger = Logger.get(KotlinCDLoggerAnalytics::class.java)
+
+    private const val LOGGER_THREAD_POOL_SIZE = 4
+    private const val MAX_QUEUED_LOG_ENTRIES = 1024
+
+    /**
+     * Scribe writes go through the `logger_cat` subprocess, which can block for several seconds
+     * under host load. That call previously ran on the compile action's critical path, so a slow
+     * `logger_cat` stalled action completion and starved worker threads. The write is offloaded
+     * here to a small, bounded, daemon-thread pool: the fixed thread count and capped queue keep a
+     * degraded `logger_cat` from growing the long-lived worker's heap, and saturating entries are
+     * dropped rather than queued without bound, since these analytics are best-effort.
+     */
+    private val defaultLoggingExecutor: Executor = ThreadPoolExecutor(
+        LOGGER_THREAD_POOL_SIZE,
+        LOGGER_THREAD_POOL_SIZE,
+        0L,
+        TimeUnit.MILLISECONDS,
+        ArrayBlockingQueue(MAX_QUEUED_LOG_ENTRIES),
+        ThreadFactoryBuilder().setDaemon(true).setNameFormat("kotlincd-scribe-logger-%d").build(),
+        RejectedExecutionHandler { _, _ ->
+          LOG.debug("Dropped KotlinCD scribe log entry; logging queue is full")
+        },
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/model/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/model/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/model/BUCK
@@ -0,0 +1,20 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "model",
+    srcs = glob([
+        "**/*.kt",
+        "**/*.java",
+    ]),
+    labels = ["codegen_rule"],  # see: https://fburl.com/workplace/fhud6fe6
+    visibility = [
+        "prelude//toolchains/android/meta_only/src/com/facebook/buck/jvm/kotlin/cd/logger/...",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/cd/analytics/...",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/model/KotlinCDLogEntry.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/model/KotlinCDLogEntry.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/model/KotlinCDLogEntry.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.analytics.logger.model
+
+data class KotlinCDLogEntry(
+    val time: Long,
+    val eventTime: Double,
+    val target: String,
+    val subtarget: String,
+    val buildUuid: String,
+    val executionPlatform: String,
+    val numJavaFiles: Long,
+    val numKotlinFiles: Long,
+    val incremental: Boolean,
+    val mode: String?,
+    val classpathChanges: String?,
+    val step: String,
+    val languageVersion: String?,
+    val extras: String?,
+    val addedAndModifiedFiles: Set<String>?,
+    val removedFiles: Set<String>?,
+    val numKotlinTokens: Long? = null,
+    val numJavaTokens: Long? = null,
+    /**
+     * Wall-clock duration of the step this entry describes, in milliseconds.
+     *
+     * Null when the step does not time itself. Without this there is no step-level timing anywhere
+     * in KotlinCD - `IsolatedStepsRunner.runStep` does not time steps, and
+     * `buck2_action_command_perf` only sees the whole `kotlincd_jar` action, which bundles ksp2,
+     * kotlinc, kosabi and copy/zip together.
+     */
+    val durationMs: Long? = null,
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/BUCK
@@ -0,0 +1,21 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "noop",
+    srcs = glob(["**/*.kt"]),
+    labels = ["codegen_rule"],
+    resources = glob(["resources/**/*"]),
+    resources_root = "resources",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger:logger",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/model:model",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/KotlinCDNoopLogger.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/KotlinCDNoopLogger.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/KotlinCDNoopLogger.kt
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.analytics.logger.noop
+
+import com.facebook.buck.jvm.kotlin.cd.analytics.logger.KotlinCDLogger
+import com.facebook.buck.jvm.kotlin.cd.analytics.logger.model.KotlinCDLogEntry
+
+/** No-op implementation of [KotlinCDAnalytics] */
+class KotlinCDNoopLogger : KotlinCDLogger {
+
+  override fun log(logEntry: KotlinCDLogEntry): Boolean = false
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/resources/META-INF/services/com.facebook.buck.jvm.kotlin.cd.analytics.logger.KotlinCDLogger b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/resources/META-INF/services/com.facebook.buck.jvm.kotlin.cd.analytics.logger.KotlinCDLogger
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop/resources/META-INF/services/com.facebook.buck.jvm.kotlin.cd.analytics.logger.KotlinCDLogger
@@ -0,0 +1,1 @@
+com.facebook.buck.jvm.kotlin.cd.analytics.logger.noop.KotlinCDNoopLogger
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/worker/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/worker/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/worker/BUCK
@@ -0,0 +1,25 @@
+load("@prelude//toolchains/android/tools/build_rules:worker.bzl", "worker")
+load("@prelude//utils:buckconfig.bzl", "read_list")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+worker(
+    name = "kotlincd_grpc_worker_tool",
+    class_loader_bootstrapper = "prelude//toolchains/android/src/com/facebook/buck/cli/bootstrapper:bootstrapper",
+    concurrency = 16,
+    exe = "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool:kotlincd_tool",
+    jvm_args = read_list(
+        "kotlincd",
+        "jvm_args",
+        delimiter = " ",
+        required = False,
+    )
+    or [],
+    main_class = "com.facebook.buck.jvm.kotlin.cd.workertool.KotlinCDGrpcWorkerToolMain",
+    visibility = [
+        "PUBLIC",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/BUCK
@@ -0,0 +1,103 @@
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "command_lib",
+    srcs = [
+        "KotlinCDCommand.java",
+    ],
+    visibility = [
+        "prelude//toolchains/android/meta_only/src/com/facebook/buck/jvm/remote_worker/...",
+    ],
+    runtime_deps = select({
+        "DEFAULT": [
+            "prelude//toolchains/android/meta_only/src/com/facebook/buck/jvm/kotlin/cd/logger/scribe:scribe",
+        ]
+        if is_full_meta_repo()
+        else [
+            "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop:noop",
+        ],
+        "config//os/constraints:windows": [
+            "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger/noop:noop",
+        ],
+    }),
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/cd/resources/proto:kotlincd-model",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd:cd",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:command",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/serialization/kotlin:kotlin",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi:abi",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin:steps",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics:analytics",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics/logger:logger",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors:postexecutors",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:protobuf-util",
+    ],
+)
+
+buck_java_library(
+    name = "main_lib",
+    srcs = [
+        "KotlinCDMain.java",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd:cd",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:gson",
+        "prelude//toolchains/android/third-party:guava",
+        ":command_lib",
+    ],
+)
+
+buck_java_library(
+    name = "grpc_worker_tool_lib",
+    srcs = ["KotlinCDGrpcWorkerToolMain.java"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd:cd",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/workertool:workertool",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc:workertool_grpc",
+        "prelude//toolchains/android/src/com/facebook/buck/workertool/resources/proto:worker-model",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        ":command_lib",
+    ],
+)
+
+buck_java_binary(
+    name = "kotlincd_tool-main",
+    main_class = "com.facebook.buck.jvm.kotlin.cd.workertool.KotlinCDMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":main_lib",
+    ],
+)
+
+buck_java_binary(
+    name = "kotlincd_tool",
+    main_class = "com.facebook.buck.jvm.kotlin.cd.workertool.KotlinCDGrpcWorkerToolMain",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":grpc_worker_tool_lib",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDCommand.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDCommand.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDCommand.java
@@ -0,0 +1,423 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.workertool;
+
+import com.facebook.buck.cd.model.kotlin.Metadata;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.io.file.FileExtensionMatcher;
+import com.facebook.buck.io.file.MostFiles;
+import com.facebook.buck.io.file.PathMatcher;
+import com.facebook.buck.jvm.cd.AbiDirWriter;
+import com.facebook.buck.jvm.cd.BuildCommandStepsBuilder;
+import com.facebook.buck.jvm.cd.DepFileUtils;
+import com.facebook.buck.jvm.cd.JvmCDCommand;
+import com.facebook.buck.jvm.cd.command.PostBuildParams;
+import com.facebook.buck.jvm.cd.command.kotlin.BuildKotlinCommand;
+import com.facebook.buck.jvm.cd.serialization.kotlin.ActionMetadataSerializer;
+import com.facebook.buck.jvm.java.ActionMetadata;
+import com.facebook.buck.jvm.kotlin.KotlinStepsBuilder;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics;
+import com.facebook.buck.jvm.kotlin.cd.analytics.logger.KotlinCDLogger;
+import com.facebook.buck.jvm.kotlin.cd.analytics.logger.KotlinCDLoggerAnalytics;
+import com.facebook.buck.jvm.kotlin.cd.workertool.postexecutors.ClassAbiWriter;
+import com.facebook.buck.jvm.kotlin.cd.workertool.postexecutors.ClassAbiWriterFactory;
+import com.facebook.buck.jvm.kotlin.cd.workertool.postexecutors.PreviousStateWriter;
+import com.facebook.buck.jvm.kotlin.cd.workertool.postexecutors.PreviousStateWriterFactory;
+import com.facebook.buck.jvm.kotlin.cd.workertool.postexecutors.SkippedCompilationTracker;
+import com.facebook.buck.jvm.kotlin.cd.workertool.postexecutors.SkippedCompilationTrackerFactory;
+import com.facebook.buck.util.zip.ZipScrubber;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedSet;
+import com.google.protobuf.util.JsonFormat;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.StringJoiner;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/**
+ * KotlinCD main class.
+ *
+ * <p>This provides a simple executable that can run any of the kotlincd actions.
+ */
+public class KotlinCDCommand implements JvmCDCommand {
+
+  private static final String ACTION_META_DATA_FILE = "action_metadata.json";
+  private static final PathMatcher KT_PATH_MATCHER = FileExtensionMatcher.of("kt");
+  private static final PathMatcher JAVA_PATH_MATCHER = FileExtensionMatcher.of("java");
+
+  @Option(name = "--action-id", required = true)
+  protected String actionId;
+
+  @Option(name = "--command-file", required = true)
+  protected Path commandFile;
+
+  @Option(name = "--incremental-config-file")
+  protected Path incrementalConfigFile;
+
+  @Option(name = "--logging-level")
+  private int loggingLevel = 0;
+
+  private final String buildUuid;
+  private final String executionPlatform;
+
+  private final KotlinStepsBuilder stepsBuilder;
+  private final BuildKotlinCommand buildKotlinCommand;
+  private final PostBuildParams postBuildParams;
+  private final Optional<Path> actionMetadataPath;
+  private final Logger logger;
+  private final SkippedCompilationTracker kotlinClassesTracker;
+  private final SkippedCompilationTracker jvmAbiTracker;
+
+  public KotlinCDCommand(String[] args, ImmutableMap<String, String> env)
+      throws CmdLineException, IOException {
+    logger = Logger.get(KotlinCDCommand.class.getName());
+    CmdLineParser parser = new CmdLineParser(this);
+    try {
+      parser.parseArgument(args);
+    } catch (CmdLineException e) {
+      System.err.println(e.getMessage());
+      parser.printUsage(System.err);
+      throw e;
+    }
+    actionMetadataPath = initCurrentActionMetadataPath(env);
+    com.facebook.buck.cd.model.kotlin.BuildKotlinCommand.Builder builder =
+        com.facebook.buck.cd.model.kotlin.BuildKotlinCommand.newBuilder();
+    try (Reader reader = new FileReader(commandFile.toFile())) {
+      JsonFormat.parser().ignoringUnknownFields().merge(reader, builder);
+    }
+    RelPath buckScratchPath = RelPath.get(env.get(WORKING_DIRECTORY_ENV_VAR));
+    com.facebook.buck.cd.model.kotlin.BuildKotlinCommand proto = builder.build();
+    this.buildKotlinCommand =
+        BuildKotlinCommand.Companion.fromProto(
+            proto.getBuildCommand(), Optional.ofNullable(buckScratchPath));
+    this.postBuildParams = PostBuildParams.Companion.fromProto(proto.getPostBuildParams());
+    this.buildUuid = env.get("BUCK_BUILD_ID");
+    this.executionPlatform = env.get("INSIDE_RE_WORKER") != null ? "remote_execution" : "local";
+    KotlinCDAnalytics kotlinCDAnalytics = initKotlinCDAnalytics();
+    cleanupOldPostBuildOutputs();
+
+    // Capture pre-compilation timestamps for tracking which files skip compilation.
+    this.kotlinClassesTracker =
+        SkippedCompilationTrackerFactory.create(
+            postBuildParams.getFilesWhichSkippedCompilation(),
+            buildKotlinCommand.getKotlinExtraParams().getKotlinClassesDir().getPath());
+    this.jvmAbiTracker =
+        SkippedCompilationTrackerFactory.create(
+            postBuildParams.getJvmAbiFilesWhichSkippedCompilation(),
+            buildKotlinCommand
+                .getKotlinExtraParams()
+                .getJvmAbiGenWorkingDir()
+                .map(absPath -> absPath.getPath())
+                .orElse(null));
+
+    this.stepsBuilder =
+        new KotlinStepsBuilder(
+            this.buildKotlinCommand, generateActionMetadata(), kotlinCDAnalytics);
+  }
+
+  private Optional<Path> initCurrentActionMetadataPath(ImmutableMap<String, String> env) {
+    String actionMetadata = env.get("ACTION_METADATA");
+    if (actionMetadata != null) {
+      logger.info("ACTION_METADATA: %s", actionMetadata);
+      return Optional.of(Paths.get(actionMetadata));
+    } else {
+      logger.info("ACTION_METADATA is not set");
+      return Optional.empty();
+    }
+  }
+
+  private @Nullable ActionMetadata generateActionMetadata() throws IOException {
+    if (!actionMetadataPath.isPresent()) {
+      return null;
+    }
+
+    com.facebook.buck.cd.model.kotlin.ActionMetadata.Builder builder =
+        com.facebook.buck.cd.model.kotlin.ActionMetadata.newBuilder();
+    builder.setCurrentMetadata(parseMetadata(actionMetadataPath.get().toFile()));
+
+    Optional<Path> previousActionMetadataPath = getPreviousActionMetadataPath();
+    if (previousActionMetadataPath.isPresent()) {
+      builder.setPreviousMetadata(
+          parseMetadata(previousActionMetadataPath.map(Path::toFile).get()));
+    }
+
+    Preconditions.checkNotNull(incrementalConfigFile);
+    return ActionMetadataSerializer.deserialize(incrementalConfigFile, builder.build());
+  }
+
+  private Optional<Path> getPreviousActionMetadataPath() {
+    Preconditions.checkState(postBuildParams.getIncrementalStateDir() != null);
+    Path previousMetadataPath =
+        postBuildParams.getIncrementalStateDir().resolve(ACTION_META_DATA_FILE);
+    if (Files.exists(previousMetadataPath)) {
+      logger.info("Previous ACTION_METADATA: %s", previousMetadataPath);
+      return Optional.of(previousMetadataPath);
+    } else {
+      logger.info("Previous ACTION_METADATA does not exist");
+      return Optional.empty();
+    }
+  }
+
+  private static Metadata parseMetadata(File jsonFile) throws IOException {
+    Metadata.Builder metadatabuilder = Metadata.newBuilder();
+
+    try (Reader reader = new FileReader(jsonFile)) {
+      JsonFormat.parser().ignoringUnknownFields().merge(reader, metadatabuilder);
+    }
+
+    return metadatabuilder.build();
+  }
+
+  private KotlinCDAnalytics initKotlinCDAnalytics() {
+    ImmutableSortedSet<RelPath> sources = buildKotlinCommand.getBaseJarCommand().getJavaSrcs();
+    long numKotlinFiles = countSourceFiles(sources, KT_PATH_MATCHER);
+    long numJavaFiles = countSourceFiles(sources, JAVA_PATH_MATCHER);
+    String[] parts = actionId.split("[\\[\\]]");
+    String target = parts[0];
+    String subtarget = parts.length > 1 ? parts[1] : "library";
+
+    return new KotlinCDLoggerAnalytics(
+        KotlinCDLogger.loadImplementation(),
+        buildUuid,
+        target,
+        subtarget,
+        executionPlatform,
+        numJavaFiles,
+        numKotlinFiles,
+        buildKotlinCommand.getKotlinExtraParams().getShouldKotlincRunIncrementally());
+  }
+
+  private static long countSourceFiles(
+      ImmutableSortedSet<RelPath> sources, PathMatcher pathMatcher) {
+    return sources.stream().filter(pathMatcher::matches).count();
+  }
+
+  private void cleanupOldPostBuildOutputs() throws IOException {
+    if (!buildKotlinCommand.getKotlinExtraParams().getShouldActionRunIncrementally()) {
+      return;
+    }
+
+    List<Path> oldPostBuildOutputs = new ArrayList<>();
+    oldPostBuildOutputs.add(postBuildParams.getLibraryJar());
+    oldPostBuildOutputs.add(postBuildParams.getAbiJar());
+    oldPostBuildOutputs.add(postBuildParams.getJvmAbiGen());
+    oldPostBuildOutputs.add(postBuildParams.getAbiOutputDir());
+    oldPostBuildOutputs.addAll(postBuildParams.getUsedClassesPaths());
+    oldPostBuildOutputs.addAll(postBuildParams.getOptionalDirsPaths());
+
+    removePaths(oldPostBuildOutputs);
+  }
+
+  private static void removePaths(List<Path> paths) throws IOException {
+    AbsPath root = AbsPath.of(Paths.get(".").toAbsolutePath().normalize());
+
+    for (Path path : paths) {
+      if (path == null) {
+        continue;
+      }
+
+      if (path.toFile().isDirectory()) {
+        MostFiles.deleteRecursivelyIfExists(root.resolve(path));
+      } else {
+        Files.deleteIfExists(root.resolve(path).getPath());
+      }
+    }
+  }
+
+  protected void maybeWriteClassAbi() {
+    if (!postBuildParams.getShouldCreateClassAbi()) {
+      Preconditions.checkState(postBuildParams.getJvmAbiGen() == null);
+      return;
+    }
+
+    ClassAbiWriter classAbiWriter =
+        ClassAbiWriterFactory.create(
+            buildKotlinCommand.getKotlinExtraParams().getShouldKotlincRunIncrementally(),
+            buildKotlinCommand.getKotlinExtraParams().getKotlinClassesDir(),
+            buildKotlinCommand.getKotlinExtraParams().getJvmAbiGenWorkingDir().orElse(null),
+            postBuildParams.getJvmAbiGen(),
+            postBuildParams.getLibraryJar(),
+            postBuildParams.getAbiJar());
+    classAbiWriter.execute();
+  }
+
+  protected void maybeWriteAbiDir() throws IOException {
+    if (postBuildParams.getAbiOutputDir() == null) {
+      Preconditions.checkState(postBuildParams.getAbiJar() == null);
+      return;
+    }
+    AbiDirWriter.writeAbiOutputDir(postBuildParams.getAbiJar(), postBuildParams.getAbiOutputDir());
+  }
+
+  public void maybeWriteDepFile() throws IOException {
+    Preconditions.checkState(
+        (postBuildParams.getDepFile() == null)
+            == (postBuildParams.getUsedClassesPaths().isEmpty()));
+
+    if (postBuildParams.getDepFile() != null) {
+      // we won't run javac if not necessary and used classes for java may not exist
+      List<Path> usedClassesMapPaths = filterExistingFiles(postBuildParams.getUsedClassesPaths());
+      Preconditions.checkState(!usedClassesMapPaths.isEmpty());
+
+      DepFileUtils.usedClassesToDepFile(
+          usedClassesMapPaths,
+          postBuildParams.getDepFile(),
+          buildKotlinCommand.getBaseJarCommand().getJarToJarDirMap(),
+          buildKotlinCommand.getKotlinExtraParams().getShouldActionRunIncrementally());
+    }
+  }
+
+  private static List<Path> filterExistingFiles(List<Path> paths) {
+    return paths.stream().filter(Files::exists).collect(Collectors.toList());
+  }
+
+  protected void maybeCreateOptionalDirs() throws IOException {
+    if (postBuildParams.getOptionalDirsPaths().isEmpty()) {
+      return;
+    }
+    for (Path path : postBuildParams.getOptionalDirsPaths()) {
+      if (Files.exists(path)) {
+        continue;
+      }
+      Files.createDirectory(path);
+    }
+  }
+
+  protected void maybeCreateIncrementalStateDir() throws IOException {
+    if (postBuildParams.getIncrementalStateDir() == null) {
+      return;
+    }
+    if (!Files.exists(postBuildParams.getIncrementalStateDir())) {
+      Files.createDirectory(postBuildParams.getIncrementalStateDir());
+    }
+  }
+
+  protected void maybeWritePreviousStateForNextIncrementalRun() {
+    PreviousStateWriter previousStateWriter =
+        PreviousStateWriterFactory.create(
+            buildKotlinCommand.getKotlinExtraParams().getShouldActionRunIncrementally(),
+            postBuildParams.getIncrementalStateDir(),
+            actionMetadataPath.orElse(null));
+
+    previousStateWriter.execute();
+  }
+
+  protected void maybeWriteUsedJarsFile() throws IOException {
+    if (postBuildParams.getUsedJarsPath() == null) {
+      return;
+    }
+
+    List<Path> usedClassesMapPaths =
+        postBuildParams.getUsedClassesPaths().stream()
+            .filter(Files::exists)
+            .collect(Collectors.toList());
+    Preconditions.checkState(!usedClassesMapPaths.isEmpty());
+
+    DepFileUtils.usedClassesToUsedJars(
+        usedClassesMapPaths,
+        postBuildParams.getUsedJarsPath(),
+        buildKotlinCommand.getKotlinExtraParams().getShouldActionRunIncrementally());
+  }
+
+  @Override
+  public BuildCommandStepsBuilder getBuildCommand() {
+    return stepsBuilder;
+  }
+
+  @Override
+  public String getActionId() {
+    return actionId;
+  }
+
+  @Override
+  public int getLoggingLevel() {
+    return loggingLevel;
+  }
+
+  @Override
+  public void postExecute() throws IOException {
+    maybeCreateIncrementalStateDir();
+    maybeRunPostProcessor();
+    maybeWriteClassAbi();
+    maybeWriteAbiDir();
+    kotlinClassesTracker.writeSkippedFiles();
+    jvmAbiTracker.writeSkippedFiles();
+    maybeWriteDepFile();
+    maybeCreateOptionalDirs();
+    maybeWriteUsedJarsFile();
+    maybeWritePreviousStateForNextIncrementalRun();
+  }
+
+  protected void maybeRunPostProcessor() throws IOException {
+    String postProcessorCmd = postBuildParams.getPostProcessorCmd();
+    if (postProcessorCmd == null) {
+      return;
+    }
+
+    Path libraryJar = postBuildParams.getLibraryJar();
+    Preconditions.checkNotNull(libraryJar, "libraryJar must be set when postProcessorCmd is set");
+
+    Path tempDir = Files.createTempDirectory("postprocessor");
+    try {
+      Path postprocessedJar = tempDir.resolve("postprocessed_output.jar");
+      List<String> cmd = new ArrayList<>(Arrays.asList(postProcessorCmd.split("\\s+")));
+      cmd.add(libraryJar.toString());
+      cmd.add(postprocessedJar.toString());
+
+      logger.info("Executing post-processor: %s", String.join(" ", cmd));
+      ProcessBuilder pb = new ProcessBuilder(cmd);
+      pb.inheritIO();
+      Process process = pb.start();
+      int exitCode;
+      try {
+        exitCode = process.waitFor();
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+        throw new IOException("Post-processor interrupted", e);
+      }
+      if (exitCode != 0) {
+        throw new IOException("Post-processor command failed with exit code " + exitCode);
+      }
+
+      Files.copy(postprocessedJar, libraryJar, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
+    } finally {
+      MostFiles.deleteRecursivelyIfExists(AbsPath.of(tempDir.toAbsolutePath()));
+    }
+
+    // Scrub the jar to normalize timestamps for deterministic builds
+    ZipScrubber.scrubZip(libraryJar);
+  }
+
+  @Override
+  public String toString() {
+    return new StringJoiner(", ", KotlinCDCommand.class.getSimpleName() + "[", "]")
+        .add("actionId='" + actionId + "'")
+        .add("commandFile=" + commandFile)
+        .add("loggingLevel=" + loggingLevel)
+        .toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDGrpcWorkerToolMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDGrpcWorkerToolMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDGrpcWorkerToolMain.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.workertool;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.cd.CompilerDaemonLoggerUtil;
+import com.facebook.buck.jvm.cd.workertool.grpc.WorkerGrpcServer;
+import java.io.IOException;
+
+/**
+ * KotlinCD grpc worker tool daemon, for use by buck2
+ *
+ * <p>This starts a grpc service over a uds socket, that accepts kotlincd compilation commands
+ */
+public class KotlinCDGrpcWorkerToolMain {
+  private static final String LOG_PATH = "buck-out/v2/kotlincd";
+
+  public static void main(String[] args) throws IOException {
+    CompilerDaemonLoggerUtil.setDefaultLogger("kotlincd_grpc_worker", LOG_PATH);
+    Logger logger = Logger.get(KotlinCDGrpcWorkerToolMain.class.getName());
+    logger.info("Starting KotlinCD Worker GRPC Server");
+    WorkerGrpcServer.runServer("KotlinCD", KotlinCDCommand::new);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/KotlinCDMain.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.workertool;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.jvm.cd.CompilerDaemonLoggerUtil;
+import com.facebook.buck.jvm.cd.CompilerDaemonRunner;
+import com.facebook.buck.jvm.cd.ErrorInterceptor;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.util.logging.Level;
+
+/**
+ * KotlinCD main class.
+ *
+ * <p>This provides a simple executable that can run any of the kotlincd actions.
+ */
+public class KotlinCDMain {
+  private static final String LOG_PATH = "buck-out/v2/kotlincd";
+
+  /** Main entrypoint of KotlinCD worker tool. */
+  public static void main(String[] args) throws IOException {
+    try {
+      CompilerDaemonLoggerUtil.setDefaultLogger("kotlincd_worker", LOG_PATH);
+      CompilerDaemonLoggerUtil.setConsoleHandlerLogLevelTo(Level.WARNING);
+      KotlinCDCommand command = new KotlinCDCommand(args, ImmutableMap.copyOf(System.getenv()));
+      Logger logger = Logger.get(KotlinCDMain.class.getName());
+      logger.info(String.format("Starting KotlinCDWorkerTool %s", command));
+      System.setErr(new ErrorInterceptor());
+      Runtime.getRuntime()
+          .addShutdownHook(
+              new Thread(
+                  () -> {
+                    System.out.flush();
+                    System.err.flush();
+                    // Your shutdown logic here...
+                  }));
+      CompilerDaemonRunner.run(command);
+      command.postExecute();
+      System.err.println("KotlinCDWorkerTool succeeded!");
+      System.exit(0);
+    } catch (Exception e) {
+      System.err.println("KotlinCDWorkerTool failed: " + e.getMessage());
+    }
+    System.exit(2);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/BUCK
@@ -0,0 +1,23 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "postexecutors",
+    srcs = glob(["**/*.kt"]),
+    labels = ["codegen_rule"],
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors:postexecutors",
+    ],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/cd/workertool/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi:abi",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/ClassAbiWriter.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/ClassAbiWriter.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/ClassAbiWriter.kt
@@ -0,0 +1,109 @@
+@file:JvmName("ClassAbiWriterFactory")
+
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.workertool.postexecutors
+
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.jvm.java.abi.StubJar
+import java.nio.file.Path
+import java.nio.file.Paths
+
+sealed interface ClassAbiWriter {
+
+  fun execute()
+}
+
+internal data class NonIncrementalAbiWriter(
+    private val libraryStubJar: StubJar,
+    private val jvmAbiGenJar: AbsPath,
+    private val abiJar: AbsPath,
+) : ClassAbiWriter {
+
+  constructor(
+      libraryJar: AbsPath,
+      jvmAbiGenJar: AbsPath,
+      abiJar: AbsPath,
+  ) : this(StubJar(libraryJar), jvmAbiGenJar, abiJar)
+
+  override fun execute() {
+    check(jvmAbiGenJar.toFile().exists())
+
+    libraryStubJar.apply {
+      setExistingAbiJar(jvmAbiGenJar)
+      writeTo(abiJar)
+    }
+  }
+}
+
+internal data class IncrementalAbiWriter(
+    private val kotlincOutputStubJar: StubJar,
+    private val jvmAbiGenWorkingDir: AbsPath,
+    private val jvmAbiGenJar: AbsPath,
+    private val libraryStubJar: StubJar,
+    private val abiJar: AbsPath,
+) : ClassAbiWriter {
+
+  constructor(
+      kotlincOutputDir: AbsPath,
+      jvmAbiGenWorkingDir: AbsPath,
+      jvmAbiGenJar: AbsPath,
+      libraryJar: AbsPath,
+      abiJar: AbsPath,
+  ) : this(
+      StubJar(kotlincOutputDir),
+      jvmAbiGenWorkingDir,
+      jvmAbiGenJar,
+      StubJar(libraryJar),
+      abiJar,
+  )
+
+  override fun execute() {
+    kotlincOutputStubJar.apply {
+      setExistingAbiJar(jvmAbiGenWorkingDir)
+      writeTo(jvmAbiGenJar)
+    }
+
+    libraryStubJar.apply {
+      setExistingAbiJar(jvmAbiGenJar)
+      writeTo(abiJar)
+    }
+  }
+}
+
+@JvmName("create")
+fun ClassAbiWriter(
+    shouldKotlincRunIncrementally: Boolean,
+    kotlincOutputDir: AbsPath,
+    jvmAbiGenWorkingDir: AbsPath?,
+    jvmAbiGenJar: Path?,
+    libraryJar: Path?,
+    abiJar: Path?,
+): ClassAbiWriter {
+
+  val root: AbsPath = AbsPath.of(Paths.get(".").toAbsolutePath().normalize())
+
+  return if (shouldKotlincRunIncrementally) {
+    IncrementalAbiWriter(
+        kotlincOutputDir = kotlincOutputDir,
+        jvmAbiGenWorkingDir = requireNotNull(jvmAbiGenWorkingDir),
+        jvmAbiGenJar = root.resolve(requireNotNull(jvmAbiGenJar)),
+        libraryJar = root.resolve(requireNotNull(libraryJar)),
+        abiJar = root.resolve(requireNotNull(abiJar)),
+    )
+  } else {
+    NonIncrementalAbiWriter(
+        libraryJar = root.resolve(requireNotNull(libraryJar)),
+        jvmAbiGenJar = root.resolve(requireNotNull(jvmAbiGenJar)),
+        abiJar = root.resolve(requireNotNull(abiJar)),
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/PreviousStateWriter.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/PreviousStateWriter.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/PreviousStateWriter.kt
@@ -0,0 +1,59 @@
+@file:JvmName("PreviousStateWriterFactory")
+
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.cd.workertool.postexecutors
+
+import java.nio.file.Files
+import java.nio.file.Path
+import java.nio.file.StandardCopyOption
+
+sealed interface PreviousStateWriter {
+
+  fun execute()
+}
+
+internal class IncrementalPreviousStateWriter(
+    val incrementalStateDir: Path,
+    val actionMetadataPath: Path,
+) : PreviousStateWriter {
+
+  override fun execute() {
+    Files.copy(
+        actionMetadataPath,
+        incrementalStateDir.resolve(actionMetadataPath.fileName),
+        StandardCopyOption.REPLACE_EXISTING,
+    )
+  }
+}
+
+internal data object DoNothingPreviousStateWriter : PreviousStateWriter {
+
+  override fun execute() {
+    // do nothing
+  }
+}
+
+@JvmName("create")
+fun PreviousStateWriter(
+    shouldActionRunIncrementally: Boolean,
+    incrementalStateDir: Path?,
+    actionMetadataPath: Path?,
+): PreviousStateWriter {
+  if (!shouldActionRunIncrementally) {
+    return DoNothingPreviousStateWriter
+  }
+
+  return IncrementalPreviousStateWriter(
+      requireNotNull(incrementalStateDir),
+      requireNotNull(actionMetadataPath),
+  )
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/SkippedCompilationTracker.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/SkippedCompilationTracker.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool/postexecutors/SkippedCompilationTracker.kt
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:JvmName("SkippedCompilationTrackerFactory")
+
+package com.facebook.buck.jvm.kotlin.cd.workertool.postexecutors
+
+import java.nio.file.Files
+import java.nio.file.Path
+
+/**
+ * Tracks which .class files were not recompiled during incremental compilation.
+ *
+ * Pre-compilation modification timestamps are captured at construction time. After compilation,
+ * [writeSkippedFiles] compares current timestamps to identify files that were not touched by the
+ * compiler.
+ */
+sealed interface SkippedCompilationTracker {
+
+  fun writeSkippedFiles()
+}
+
+internal class ActiveSkippedCompilationTracker(
+    private val classesDir: Path,
+    private val outputFile: Path,
+) : SkippedCompilationTracker {
+
+  private val preCompilationTimestamps: Map<String, Long> = getClassFileTimestamps(classesDir)
+
+  override fun writeSkippedFiles() {
+    val postCompilationTimestamps = getClassFileTimestamps(classesDir)
+    val skippedFiles =
+        postCompilationTimestamps.entries
+            .filter { (path, mtime) -> preCompilationTimestamps[path] == mtime }
+            .map { it.key }
+            .sorted()
+
+    outputFile.toFile().apply {
+      parentFile?.mkdirs()
+      writeText(
+          if (skippedFiles.isNotEmpty()) skippedFiles.joinToString("\n") + "\n" else "",
+      )
+    }
+  }
+}
+
+internal data object DoNothingSkippedCompilationTracker : SkippedCompilationTracker {
+
+  override fun writeSkippedFiles() {
+    // do nothing
+  }
+}
+
+@JvmName("create")
+fun SkippedCompilationTracker(
+    outputFile: Path?,
+    classesDir: Path?,
+): SkippedCompilationTracker {
+  if (outputFile == null || classesDir == null) {
+    return DoNothingSkippedCompilationTracker
+  }
+
+  return ActiveSkippedCompilationTracker(classesDir, outputFile)
+}
+
+private fun getClassFileTimestamps(dir: Path): Map<String, Long> {
+  if (!Files.isDirectory(dir)) return emptyMap()
+
+  val timestamps = mutableMapOf<String, Long>()
+  Files.walk(dir).use { stream ->
+    stream
+        .filter { Files.isRegularFile(it) && it.toString().endsWith(".class") }
+        .forEach { file ->
+          val relPath = dir.relativize(file).toString()
+          timestamps[relPath] = Files.getLastModifiedTime(file).toMillis()
+        }
+  }
+  return timestamps
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/BUCK
@@ -0,0 +1,22 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "common",
+    srcs = glob(["*.kt"]),
+    labels = ["codegen_rule"],
+    provided_deps = [
+        "prelude//toolchains/android/third-party:kotlin-compiler",
+    ],
+    tests = [
+        "fbsource//fbandroid/javatests/com/facebook/kotlin/compilerplugins/common:common",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/File.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/File.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/File.kt
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.common
+
+import java.io.File
+import org.jetbrains.kotlin.com.intellij.openapi.fileTypes.FileType
+import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile
+import org.jetbrains.kotlin.com.intellij.openapi.vfs.local.CoreLocalFileSystem
+import org.jetbrains.kotlin.com.intellij.openapi.vfs.local.CoreLocalVirtualFile
+import org.jetbrains.kotlin.com.intellij.psi.FileViewProvider
+import org.jetbrains.kotlin.com.intellij.psi.PsiManager
+import org.jetbrains.kotlin.com.intellij.psi.SingleRootFileViewProvider
+import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile
+import org.jetbrains.kotlin.idea.KotlinFileType
+import org.jetbrains.kotlin.psi.KtFile
+
+/**
+ * Create a new kt file, along with a virtual file.
+ *
+ * NOTE: A KtFile without a virtual file will result in an NPE when the next plugin (e.g. kapt)
+ * tries to read files.
+ *
+ * Inspired by [the arrow-meta compiler plugin](https://fburl.com/qbeodjkr).
+ *
+ * @param fileManager The PsiManager for file. A common way to acquire is from existing [KtFile] by
+ *   [KtFile.getManager].
+ * @param outputDir The directory to put the new file. For compiler plugin, a common way is to get
+ *   it from buck by a plugin option with value `__codegen_dir__`. See
+ *   [example](https://fburl.com/diffusion/1aczk9lk).
+ * @param name Name for new file
+ * @param content Content for new file
+ * @param writable Boolean whether to make the file writable or not. Default is false.
+ * @return The [KtFile] we created with a virtual file that physical exist
+ */
+fun createNewKtFile(
+    fileManager: PsiManager,
+    outputDir: String,
+    name: String,
+    content: String,
+    writable: Boolean = false,
+): KtFile {
+  val directory = File(outputDir).apply { mkdirs() }
+  val file =
+      File(directory, name).apply {
+        writeText(content)
+        setWritable(writable)
+      }
+  val virtualFile = CoreLocalVirtualFile(CoreLocalFileSystem(), file.toPath())
+  return KtFile(SingleRootFileViewProvider(fileManager, virtualFile), false)
+}
+
+/**
+ * Creates a [KtFile] which is based on a in-memory [LightVirtualFile].
+ * https://dploeger.github.io/intellij-api-doc/com/intellij/testFramework/LightVirtualFile.html
+ *
+ * @param fileManager The PsiManager for file. A common way to acquire is from existing [KtFile] by
+ *   [KtFile.getManager].
+ * @param virtualFilePath The fake virtual file path. Will be displayed in error message. For
+ *   example, if fake file is derived from slightly modifying an original file, the original file's
+ *   virtualFilePath can be applied here in order to point error message to original file
+ * @param name Name for new file
+ * @param content Content for new file
+ * @return The [KtFile] we created with a in-memory [LightVirtualFile]
+ */
+fun createFakeKtFile(
+    fileManager: PsiManager,
+    virtualFilePath: String,
+    name: String,
+    content: String,
+): KtFile {
+  val fakeVirtualFile = FakeVirtualFile(name, content, virtualFilePath = virtualFilePath)
+  return FakeKtFile(SingleRootFileViewProvider(fileManager, fakeVirtualFile), false)
+}
+
+/**
+ * One problem of using LightVirtualFile instead of generating a physical virtual file is,
+ * [KotlinCoreEnvironment.createForProduction] uses [virtualFile] name as a sort Key. However,
+ * KtFile here have [virtualFile] is null, even though it does have a [LightVirtualFile] in
+ * [viewProvider.virtualFile].
+ *
+ * <p> To resolve that, we had to manually overwrite [getVirtualFile] to also use
+ * [viewProvider.virtualFile]
+ */
+private class FakeKtFile(viewProvider: FileViewProvider, isCompiled: Boolean) :
+    KtFile(viewProvider, isCompiled) {
+  override fun getVirtualFile(): VirtualFile {
+    return viewProvider.virtualFile
+  }
+}
+
+/**
+ * Another problem of using LightVirtualFile instead of generating actual physical file is,
+ * LightVirtualFile have empty [getParent], so error message becomes "/MyClass.kt".
+ *
+ * <p> To solve that, we manually override getPath to be old file's path, so error message correctly
+ * redirect user to original file.
+ */
+private class FakeVirtualFile(
+    name: String,
+    content: String,
+    fileType: FileType = KotlinFileType.INSTANCE,
+    private val virtualFilePath: String,
+) : LightVirtualFile(name, fileType, content) {
+  override fun getPath(): String {
+    return virtualFilePath
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/FileChecks.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/FileChecks.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/FileChecks.kt
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.common
+
+import org.jetbrains.kotlin.psi.KtFile
+
+// A file in these directories is either generated and must not be codemoded or is compiler plugin
+const val COMPILATION_PATH: String = "/buck-out/"
+
+// Path fragment indicating a file has been generated from one or more compiler plugins
+const val COMPILER_PLUGIN_MID_FIX: String = "_kotlinc_plugin_generated__/"
+
+// Note: If we expand beyond fbandroid, this will need to be keyed to which repo as in jAST
+val GENERATED_FILE_PATHS: List<String> = listOf(COMPILATION_PATH, "/generated-graphql/", "/thrift/")
+
+val NON_LOCAL_SRC_PATHS: List<String> = listOf("/third-party/")
+
+val GENERATED_REGEX: Regex = Regex("${"@"}[Gg]enerated")
+
+@JvmInline
+value class SourcePath(val path: String) {
+
+  fun isGeneratedPath(): Boolean = GENERATED_FILE_PATHS.any { it in path }
+
+  fun isCompilerPluginGeneratedPath(): Boolean =
+      COMPILATION_PATH in path && COMPILER_PLUGIN_MID_FIX in path
+
+  // Will need to fix if we move out of fbandroid, and if kotlin compiler plugins change
+  fun getRepositoryPathFromPluginPath(): String {
+    if (!isCompilerPluginGeneratedPath()) {
+      return path
+    }
+
+    return path
+        .replace(Regex("/buck-out/[a-zA-Z0-9]+/[a-zA-Z0-9]+/fbandroid"), "/fbandroid")
+        .replace(Regex("/__[a-zA-Z0-9]+_kotlinc_plugin_generated__/"), "/")
+  }
+
+  fun isThirdPartyPath(): Boolean = NON_LOCAL_SRC_PATHS.any { it in path }
+
+  fun isGeneratedFile(ktFile: KtFile): Boolean {
+    val isCodemodFilePath = isCompilerPluginGeneratedPath()
+    val isGeneratedFilePath = if (isCodemodFilePath) false else isGeneratedPath()
+    // This is sadly expensive due to getting the full string of the file, would love to just peek
+    // at the top
+    return if (isGeneratedFilePath) isGeneratedFilePath else GENERATED_REGEX in ktFile.text
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/StubUtils.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/StubUtils.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/StubUtils.kt
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.compilerplugins.common
+
+import org.jetbrains.kotlin.backend.common.output.OutputFile
+import org.jetbrains.kotlin.com.intellij.psi.PsiComment
+import org.jetbrains.kotlin.psi.KtFile
+
+// TODO: pass as a compiler plugin parameter
+const val STUB_MARKUP = "// A stub @g" + "enerated by Kosabi"
+
+// TODO: If [KtFile] doesn't have a package element then
+//  [firstChild] will be an empty package element
+//  Need to fix it
+fun KtFile.isStub(): Boolean = firstChild is PsiComment && firstChild.text == STUB_MARKUP
+
+fun OutputFile.isGeneratedFromStub(stubs: List<KtFile>): Boolean {
+  // TODO(sergei): Do we want to cache this set?
+  val stubsPaths: Set<String> = stubs.map { it.viewProvider.virtualFile.path }.toSet()
+  val outPaths = sourceFiles.map { it.path }
+  return stubsPaths.containsAll(outPaths)
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/Types.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/Types.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common/Types.kt
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.common
+
+import org.jetbrains.kotlin.psi.KtFile
+import org.jetbrains.kotlin.resolve.BindingContext
+
+/**
+ * Returns true if the compiler has done type analysis on any of the files in the list (which
+ * implies that it has done it for all of them).
+ */
+fun hasTypesForAnyFiles(bindingContext: BindingContext, files: Collection<KtFile>): Boolean {
+  return files.any { ktFile ->
+    bindingContext.get(BindingContext.PACKAGE_TO_FILES, ktFile.packageFqName)?.contains(ktFile) ==
+        true
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/BUCK
@@ -0,0 +1,18 @@
+load("@prelude//kotlin/tools:defs.bzl", "kotlin_bootstrap_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+kotlin_bootstrap_library(
+    name = "common",
+    srcs = glob(["*.kt"]),
+    tests = [
+        "fbsource//fbandroid/javatests/com/facebook/kotlin/compilerplugins/kosabi/common:common",
+    ],
+    visibility = [
+        "fbsource//fbandroid/javatests/...",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/...",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/Common.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/Common.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/Common.kt
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common
+
+import java.io.File
+import java.io.IOException
+import java.util.Enumeration
+import java.util.jar.JarEntry
+import java.util.jar.JarFile
+
+/**
+ * returns a Pair of [1] Set<FullTypeQualifier>: set of outerClass FTQs in classpaths, [2]
+ * Set<List<String>>: set of strings of package segments in classpath. [1] used to determine the
+ * outerClass FTQ from class name so a/b/c.class -> a.b.C [2] used for ClassLevelFunction, these
+ * functions will exist in class [package]/[FileName]Kt.class. Since [FileName] is not known at
+ * function check, we are assuming same [package] will be in same classpath when checking
+ */
+@Suppress("detekt.SwallowedException")
+fun parseClasspathFileClassesAndPackages(
+    classpath: List<File>,
+): Pair<Set<FullTypeQualifier>, Set<List<String>>> {
+  val outerFTQs = mutableSetOf<FullTypeQualifier>()
+  val pkgs = mutableSetOf<List<String>>()
+  for (file in classpath) {
+    if (shouldSkipLookup(file.path)) {
+      continue
+    }
+    try {
+      JarFile(file).use { jarFile ->
+        val je: Enumeration<JarEntry> = jarFile.entries()
+        je.iterator().forEach { jarEntry ->
+          if (jarEntry.name.endsWith(".class")) {
+            val qualifier = FullTypeQualifier(getSegmentsFromJarEntry(jarEntry))
+            pkgs.add(qualifier.pkg)
+            val outerQualifier = qualifier.outerClassOnlyQualifier()
+            if (outerQualifier != null) {
+              outerFTQs.add(qualifier)
+            }
+          }
+        }
+      }
+    } catch (e: IOException) {
+      Logger.log("[Possible error]: failed to open jar file: ${file.canonicalPath}")
+    }
+  }
+  return Pair(outerFTQs, pkgs)
+}
+
+private fun getSegmentsFromJarEntry(jarEntry: JarEntry): List<String> {
+  return jarEntry.name.replace(".class", "").split("/")
+}
+
+private fun shouldSkipLookup(path: String): Boolean {
+  // skip lookup in large kotlin/java libraries that doesn't have known CONST val exports used in
+  // our codebase
+  if (
+      // Filtering out at least guava, failaccess, listeneablefuture
+      path.contains("/java/com/google/guava/") ||
+          // Filtering out at least stdlib, annotations, parcelize
+          path.contains("/org/jetbrains/kotlin/") ||
+          path.contains("/org/jetbrains/kotlinx/kotlinx-coroutines-android/") ||
+          path.contains("/org/jetbrains/kotlinx/kotlinx-coroutines-core-jvm/") ||
+          path.contains("/third-party/java/kotlin/")
+  ) {
+    return true
+  }
+
+  return false
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/FullTypeQualifier.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/FullTypeQualifier.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/FullTypeQualifier.kt
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common
+
+/**
+ * [FullTypeQualifier] is a data structure for full qualified name. It interprets package, names and
+ * member from segments.
+ *
+ * There are several import conditions in Java/Kotlin other than import package name
+ * 1. Nested class/interface - com.facebook.TopLevelClass.InnerClass.InnerClass2
+ * 2. Top level declaration - com.facebook.kotlin.someMethod
+ * 3. Static member - com.facebook.SomeClass.CONSTANT_VALUE
+ *
+ * @param segments ordered list from Fqname, ex: listOf("com", "facebook", "kotlin", "SomeName")
+ */
+class FullTypeQualifier : Comparable<FullTypeQualifier> {
+  val segments: List<String>
+
+  /** Package qualified name, ex: com.facebook.kotlin */
+  val pkg: List<String>
+
+  /** List of package name or inner classes/interface/enum class */
+  val names: List<String>
+
+  /** method or constant value property */
+  val member: String?
+
+  constructor(segments: List<String>) {
+    this.segments = segments
+    val firstUpperCaseIndex = segments.indexOfFirst { it.first().isUpperCase() }
+    if (firstUpperCaseIndex == -1) {
+      names = emptyList()
+      pkg = segments.dropLast(1)
+      member = segments.last()
+    } else {
+      pkg = segments.take(firstUpperCaseIndex)
+      val lastSegment = segments.last()
+      if (NonConventionalImports.classLikeDeclarations.contains(segments)) {
+        names = listOf(lastSegment)
+        member = null
+      } else if (lastSegment.isStaticConstQualifier() || lastSegment.isStaticMethodQualifier()) {
+        names = segments.subList(firstUpperCaseIndex, segments.lastIndex)
+        member = lastSegment
+      } else {
+        names = segments.drop(firstUpperCaseIndex)
+        member = null
+      }
+    }
+    if (names.isEmpty() && member == null) {
+      Logger.log(
+          "Topic: [FullTypeQualifier] Invalid segments: $segments caused empty names and null member in FullTypeQualifier",
+      )
+    }
+  }
+
+  private constructor(
+      segments: List<String>,
+      pkg: List<String> = emptyList(),
+      names: List<String> = emptyList(),
+      member: String? = null,
+  ) {
+    this.segments = segments
+    this.pkg = pkg
+    this.names = names
+    this.member = member
+  }
+
+  fun pkgAsString(): String = pkg.joinToString(separator = ".")
+
+  // TopLevelDeclaration:
+  // - com.some.package.method
+  fun isTopLevelDeclaration(): Boolean = names.isEmpty()
+
+  override fun compareTo(other: FullTypeQualifier): Int {
+    val thisSize = this.segments.size
+    val otherSize = other.segments.size
+    // Compare list sizes first
+    if (thisSize < otherSize) return -1
+    if (thisSize > otherSize) return 1
+    for (i in 0 until thisSize) {
+      val comparison = this.segments[i].compareTo(other.segments[i])
+      if (comparison != 0) return comparison
+    }
+    return 0
+  }
+
+  override fun equals(other: Any?): Boolean {
+    if (this === other) return true
+    if (javaClass != other?.javaClass) return false
+
+    other as FullTypeQualifier
+
+    if (segments != other.segments) return false
+
+    return true
+  }
+
+  override fun hashCode(): Int {
+    return segments.hashCode()
+  }
+
+  companion object {
+    fun unsafeBuildQualifier(
+        segments: List<String>,
+        pkg: List<String> = emptyList(),
+        names: List<String> = emptyList(),
+        member: String? = null,
+    ): FullTypeQualifier = FullTypeQualifier(segments, pkg, names, member)
+  }
+}
+
+/**
+ * Filter out same outer class full qualifier from set [qualifiersToFilter]
+ *
+ * @param qualifiersToFilter set of [FullTypeQualifier] to filter from current set
+ */
+fun Collection<FullTypeQualifier>.filterDifferentOuterClassIn(
+    qualifiersToFilter: Collection<FullTypeQualifier>,
+): List<FullTypeQualifier> = filterNot { qualifier ->
+  qualifiersToFilter.contains(qualifier.outerClassOnlyQualifier())
+}
+
+/**
+ * [FullTypeQualifier.outerClassOnlyQualifier] will return outerClass only [FullTypeQualifier]
+ * Example: com.facebook.kotlin.SampleClass.method -> com.facebook.kotlin.SampleClass
+ */
+fun FullTypeQualifier.outerClassOnlyQualifier(): FullTypeQualifier? =
+    if (names.isEmpty()) null
+    else FullTypeQualifier.unsafeBuildQualifier(pkg + names.first(), pkg, listOf(names.first()))
+
+// Regex matches:
+//  - non-empty upper screaming case
+// Examples:
+// "A"     - NO
+// "A_"    - YES
+// "AB"    - YES
+// "A_9"   - YES
+// "A___C" - YES
+// private val SCREAMING_UPPER_SNAKE_CASE = "[A-Z][_A-Z0-9]+(_[A-Z0-9]+)*".toRegex()
+
+private fun String.isStaticMethodQualifier() = first().isLowerCase()
+
+private fun String.isStaticConstQualifier(): Boolean {
+  if (length <= 1) return false
+  return this.all { it == it.uppercaseChar() }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/KosabiLogger.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/KosabiLogger.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/KosabiLogger.kt
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common
+
+import java.io.File
+
+object Logger {
+  var isEnabled: Boolean = false
+    private set
+
+  var userDefinedPath: String? = null
+    set(value: String?) {
+      field = value
+      isEnabled = if (value != null && value.isNotEmpty()) File(value).isValidPath() else false
+      // This will create an empty file if log is enabled. (for unit test purpose in case logger
+      // doesn't log anything)
+      if (isEnabled && value != null) {
+
+        File(value).appendText("")
+      }
+    }
+
+  fun log(msg: Any?) {
+    if (!isEnabled) {
+      // Do nothing if logger is disabled
+      return
+    }
+    userDefinedPath?.let {
+      val file = File(it)
+      file.appendText("${msg}\n", Charsets.UTF_8)
+    }
+  }
+}
+
+private fun File.isValidPath(): Boolean = canonicalPath.isNotEmpty() && !isDirectory
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/NonConventionalImports.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/NonConventionalImports.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/NonConventionalImports.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common
+
+object NonConventionalImports {
+  /** Exact FQNs parsed as class-like declarations despite their non-conventional names. */
+  val classLikeDeclarations: Set<List<String>> = setOf(
+      listOf("javax", "microedition", "khronos", "egl", "EGL"),
+      listOf("javax", "microedition", "khronos", "egl", "EGL10"),
+      listOf("javax", "microedition", "khronos", "egl", "EGL11"),
+      listOf("javax", "microedition", "khronos", "opengles", "GL"),
+      listOf("javax", "microedition", "khronos", "opengles", "GL10"),
+      listOf("javax", "microedition", "khronos", "opengles", "GL11"),
+      listOf("com", "whatsapp", "infra", "smax", "common", "RPC"),
+  )
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/BUCK
@@ -0,0 +1,25 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "stub",
+    srcs = glob(
+        ["**/*.kt"],
+    ),
+    labels = ["codegen_rule"],
+    provided_deps = [
+        "prelude//toolchains/android/third-party:kotlin-compiler-embeddable",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common:common",
+        "prelude//toolchains/android/third-party:kotlin-metadata-jvm",
+        "prelude//toolchains/android/third-party:kotlin-poet",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/FakeKtFile.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/FakeKtFile.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/FakeKtFile.kt
@@ -0,0 +1,51 @@
+// (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
+
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common.stub.model
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.render.RenderedKStub
+import org.jetbrains.kotlin.com.intellij.openapi.project.Project
+import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile
+import org.jetbrains.kotlin.com.intellij.psi.FileViewProvider
+import org.jetbrains.kotlin.psi.KtFile
+import org.jetbrains.kotlin.psi.KtPsiFactory
+
+/**
+ * [FakeKtFile] will be a part of the asttools common API. Currently this code has a duplicate in
+ * other Meta compiler plugins.
+ *
+ * It fakes a KtFile without having a properly created [VirtualFile] anywhere in the
+ * VirtualFileSystem, defaulting its path to a dummy .kt name.
+ */
+class FakeKtFile(viewProvider: FileViewProvider, isCompiled: Boolean) :
+    KtFile(viewProvider, isCompiled) {
+  constructor(f: KtFile) : this(f.viewProvider, f.isCompiled)
+
+  // `KotlinCoreEnvironment::createForProduction` uses virtualFile name as a sort Key
+  // Providing a default Dummy.kt
+  override fun getVirtualFile(): VirtualFile {
+    return viewProvider.virtualFile
+  }
+}
+
+fun generateFakeKtFile(project: Project, renderedKStub: RenderedKStub): FakeKtFile {
+  // KtPsiFactory creates a [LightVirtualFile] which is a in-memory implementation of [VirtualFile]
+  // https://dploeger.github.io/intellij-api-doc/com/intellij/testFramework/LightVirtualFile.html
+  // For Implementation details see KtPsiFactoryImpl
+  return FakeKtFile(
+      KtPsiFactory(project)
+          .createFile(
+              "kosabi_stub.${if (renderedKStub.stub.pkg?.isNotEmpty() == true) "${renderedKStub.stub.pkg}." else ""}${renderedKStub.stub.name}.kt",
+              renderedKStub.render,
+          ),
+  )
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KArrayType.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KArrayType.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KArrayType.kt
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common.stub.model
+
+/**
+ * The class to represent the Array type
+ * *
+ */
+class KArrayType(
+    val type: Type,
+    override val nullable: Boolean = false,
+    override val generics: List<Type> = emptyList(),
+) : Type {
+
+  override val names: List<String>
+    get() =
+        if (type is KArrayType) {
+          type.type.names
+        } else {
+          type.names
+        }
+
+  override val pkg: List<String>
+    get() =
+        if (type is KArrayType) {
+          type.type.pkg
+        } else {
+          type.pkg
+        }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KClassType.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KClassType.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KClassType.kt
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common.stub.model
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+
+/**
+ * [KClassType] does support some Java built-in types and customized class type. For example:
+ * java.lang.String > kotlin.String, java.lang.Object > kotlin.Any, java.lang.annotation >
+ * kotlin.Annotation ...
+ *
+ * More types info please refer to: https://kotlinlang.org/docs/java-interop.html#mapped-types
+ */
+class KClassType(
+    private val fullQualifiedName: String,
+    override val nullable: Boolean = false,
+    override val generics: List<Type> = emptyList(),
+) : Type {
+  private val fullTypeQualifier: FullTypeQualifier
+
+  init {
+    val mappedFullQualifiedName =
+        when (fullQualifiedName) {
+          "java.lang.Object" -> "kotlin.Any"
+          "java.lang.Cloneable" -> "kotlin.Cloneable"
+          "java.lang.Comparable" -> "kotlin.Comparable"
+          "java.lang.Enum" -> "kotlin.Enum"
+          "java.lang.annotation.Annotation" -> "kotlin.Annotation"
+          "java.lang.CharSequence" -> "kotlin.CharSequence"
+          "java.lang.String" -> "kotlin.String"
+          "java.lang.Number" -> "kotlin.Number"
+          "java.lang.Throwable" -> "kotlin.Throwable"
+          else -> fullQualifiedName
+        }
+    fullTypeQualifier = FullTypeQualifier(mappedFullQualifiedName.split("."))
+  }
+
+  override val names: List<String>
+    get() = fullTypeQualifier.names
+
+  override val pkg: List<String>
+    get() = fullTypeQualifier.pkg
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KFunStub.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KFunStub.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KFunStub.kt
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common.stub.model
+
+private typealias NamedArg = Pair<String, Type>
+
+open class KFunStub(val name: String, val namedArgs: List<NamedArg>) {
+  constructor(name: String, args: Int) : this(name, List(args) { "p$it" to KType.ANY_NULLABLE })
+
+  var ret: Type = KType.UNIT
+  var throws: List<KType> = emptyList()
+  var typeVariableList: List<KTypeVariableName> = emptyList()
+  // Only members in named objects and companion objects can be declared as static
+  // Top level functions are always static
+  var static: Boolean = false
+  var private: Boolean = false
+  var protected: Boolean = false
+  var isOverride: Boolean = false
+  var abstract: Boolean = false
+  var isConstructor: Boolean = false
+  var isOperator: Boolean = false
+  var isFinal: Boolean = false
+  var annotations: List<KAnnotation> = emptyList()
+  // Boolean: isSuper, super else this
+  // List<NamedArg>: constructor parameters name and value
+  var constructorSuperDelegate: Pair<Boolean, List<NamedArg>> = Pair(false, emptyList())
+
+  companion object {
+    fun withTypedArgs(name: String, args: List<Type>) =
+        KFunStub(name, args.mapIndexed { i, e -> "p$i" to e })
+  }
+}
+
+class KCtorStub(namedArgs: List<NamedArg>) : KFunStub("<init>", namedArgs) {
+  // Note
+  // It's not correct to pass Any? as an annotation argument
+  constructor(args: Int) : this(List(args) { "p$it" to KType.ANY_NULLABLE })
+}
+
+class KTypeVariableName(
+    val name: String,
+    val bounds: List<Type>,
+    override val pkg: List<String> = emptyList(),
+    override val generics: List<Type> = emptyList(),
+    override val nullable: Boolean = false,
+) : Type {
+  override val names: List<String> = listOf(name)
+}
+
+class KAnnotation(val pkg: String, val name: String, val attributesText: String)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KPropertyStub.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KPropertyStub.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KPropertyStub.kt
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common.stub.model
+
+open class KPropertyStub(val name: String, val value: String?, val args: List<Type> = emptyList()) {
+  var ret: Type = KType.UNIT
+  var static: Boolean = false
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KStub.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KStub.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KStub.kt
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common.stub.model
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.Logger
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.Type as IType
+
+class KStub(val pkg: String?, val name: String) {
+  constructor(name: String) : this(null, name)
+
+  var type: Type = Type.CLASS
+    set(value: Type) {
+      Logger.log(
+          """
+      |  [Update stub]
+      |    - name: $pkg:$name
+      |    - type: ${field.name} -> ${value.name}
+    """
+              .trimMargin(),
+      )
+      field = value
+    }
+
+  var genericTypes: Int = 0
+    set(value: Int) {
+      if (field != value) {
+        Logger.log(
+            """
+      |  [Update stub]
+      |    - name: $pkg:$name
+      |    - type: ${type.name}
+      |    - genericTypes: $field -> $value
+    """
+                .trimMargin(),
+        )
+      }
+      field = value
+    }
+
+  var ctor: KCtorStub? = null
+    set(value: KCtorStub?) {
+      Logger.log(
+          """
+        |  [Update stub]
+        |    - name: $pkg:$name
+        |    - type: ${type.name}
+        |    - ctorParams: $field -> $value
+      """,
+      )
+      field = value
+    }
+
+  // Add extends declaration here when we will need it
+  var extends: IType? = null
+  var implements: List<IType> = emptyList()
+  var typeVariableList: List<KTypeVariableName> = emptyList()
+  var stubAnnotations: List<KAnnotation> = emptyList()
+  var stubImports: List<String> = emptyList()
+
+  var abstract: Boolean = false
+  var doNotRenderAsKotlinObject: Boolean = false
+
+  // TODO: We might want to optimise [innerStubs] for find operation
+  val innerStubs: MutableSet<KStub> = mutableSetOf()
+  var funStubs: MutableList<KFunStub> = mutableListOf()
+
+  val propertyStubs: MutableList<KPropertyStub> = mutableListOf()
+
+  // In some cases we want to treat [KStub] not as a stub, but as something that
+  // came from a compilation context.
+  // Faking Annotation Processors shapes is one example.
+  var treatAsReal: Boolean = false
+
+  override fun equals(other: Any?): Boolean {
+    if (this === other) {
+      return true
+    }
+    if (javaClass != other?.javaClass) {
+      return false
+    }
+
+    other as KStub
+
+    if (pkg != other.pkg) {
+      return false
+    }
+    if (name != other.name) {
+      return false
+    }
+
+    return true
+  }
+
+  override fun hashCode(): Int {
+    var result = pkg?.hashCode() ?: 0
+    result = 31 * result + name.hashCode()
+    return result
+  }
+
+  enum class Type {
+    ANNOTATION,
+    CLASS,
+    INTERFACE,
+    OBJECT,
+    TOP_LEVEL_DECLARATION,
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KType.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KType.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KType.kt
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common.stub.model
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import kotlin.reflect.KClass
+
+class KType
+internal constructor(
+    private val ftq: FullTypeQualifier,
+    override val nullable: Boolean = false,
+    override val generics: List<Type> = emptyList(),
+) : Type {
+  /** @param qualifierName is a fullTypeQualifier string representation, example: com.foo.A.B.C */
+  constructor(
+      qualifierName: String,
+      nullable: Boolean = false,
+  ) : this(FullTypeQualifier(qualifierName.split(".")), nullable)
+
+  override val pkg: List<String>
+    get() = ftq.pkg
+
+  override val names: List<String>
+    get() = ftq.names
+
+  fun parametriseWith(generics: List<KType>): KType = KType(ftq, nullable, generics)
+
+  companion object {
+    val ANY_NULLABLE: KType = Any::class.asNullableKType()
+    val UNIT: KType = Unit::class.asKType()
+    val BOOLEAN: KType = Boolean::class.asKType()
+    val BOOLEAN_NULLABLE: KType = Boolean::class.asNullableKType()
+    val BYTE: KType = Byte::class.asKType()
+    val BYTE_NULLABLE: KType = Byte::class.asNullableKType()
+    val CHAR: KType = Char::class.asKType()
+    val CHAR_NULLABLE: KType = Char::class.asNullableKType()
+    val INT: KType = Int::class.asKType()
+    val INT_NULLABLE: KType = Int::class.asNullableKType()
+    val DOUBLE: KType = Double::class.asKType()
+    val DOUBLE_NULLABLE: KType = Double::class.asNullableKType()
+    val FLOAT: KType = Float::class.asKType()
+    val FLOAT_NULLABLE: KType = Float::class.asNullableKType()
+    val LONG: KType = Long::class.asKType()
+    val LONG_NULLABLE: KType = Long::class.asNullableKType()
+    val SHORT: KType = Short::class.asKType()
+    val SHORT_NULLABLE: KType = Short::class.asNullableKType()
+  }
+}
+
+fun KClass<out Any>.asKType(): KType = KType(this.qualifiedName!!)
+
+fun KClass<out Any>.asNullableKType(): KType = KType(this.qualifiedName!!, nullable = true)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KWildcardType.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KWildcardType.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/KWildcardType.kt
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common.stub.model
+
+/**
+ * [KWildcardType] represents a wildcard type. It will be rendered into WildcardTypename.
+ *
+ * @param type type extends or super of the wildcard. <? extends T>, T is the type
+ * @param bound UNBOUNDED - <?>, EXTENDS - <? extends T>, SUPER - <? super T>
+ */
+class KWildcardType(val type: Type, val bound: BoundType) : Type {
+  enum class BoundType {
+    UNBOUNDED,
+    EXTENDS,
+    SUPER,
+  }
+
+  override val names: List<String> = type.names
+  override val pkg: List<String> = type.pkg
+  override val nullable: Boolean = type.nullable
+  override val generics: List<Type> = emptyList()
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/Type.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/Type.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/model/Type.kt
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common.stub.model
+
+interface Type {
+  val names: List<String>
+  val pkg: List<String>
+  val nullable: Boolean
+  val generics: List<Type>
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/render/StubBytecodeRender.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/render/StubBytecodeRender.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/render/StubBytecodeRender.kt
@@ -0,0 +1,295 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.compilerplugins.kosabi.common.stub.render
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KPropertyStub
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+import java.io.File
+import java.io.FileOutputStream
+import kotlin.metadata.KmClassifier
+import kotlin.metadata.KmFunction
+import kotlin.metadata.KmPackage
+import kotlin.metadata.KmType
+import kotlin.metadata.KmValueParameter
+import kotlin.metadata.Visibility
+import kotlin.metadata.isNullable
+import kotlin.metadata.jvm.JvmMetadataVersion
+import kotlin.metadata.jvm.JvmMethodSignature
+import kotlin.metadata.jvm.KotlinClassMetadata
+import kotlin.metadata.jvm.signature
+import kotlin.metadata.visibility
+import org.jetbrains.org.objectweb.asm.AnnotationVisitor
+import org.jetbrains.org.objectweb.asm.ClassVisitor
+import org.jetbrains.org.objectweb.asm.ClassWriter
+import org.jetbrains.org.objectweb.asm.Opcodes
+
+// Kotlin metadata classifier names use '/' separated internal names.
+private const val UNIT_CLASSIFIER = "kotlin/Unit"
+private const val ANY_CLASSIFIER = "kotlin/Any"
+
+object StubBytecodeRender {
+
+  fun KStub.supportBytecode(): Boolean {
+    // For KStubs that should be treated as real (e.g JavaKStub for KSP output, or IG JsonHelper
+    // type), we don't want to generate bytecode, but should
+    // keep
+    // passing them as KTFile for compilation, as these classes needed to be part as final ABI
+    // output
+    if (treatAsReal) {
+      return false
+    }
+
+    return true
+  }
+
+  fun KPropertyStub.modifier(): Int {
+    var modifier = Opcodes.ACC_PUBLIC
+    if (static) {
+      modifier = modifier or Opcodes.ACC_STATIC
+    }
+    return modifier
+  }
+
+  fun KStub.accessFlags(): Int {
+    // A Kotlin file facade (the class holding top level declarations) is always a final class.
+    if (type == KStub.Type.TOP_LEVEL_DECLARATION) {
+      return Opcodes.ACC_PUBLIC or Opcodes.ACC_FINAL or Opcodes.ACC_SUPER
+    }
+
+    var flag =
+        when (type) {
+          // ACC_ANNOTATION alone is not a valid annotation type: JVMS 4.1 requires ACC_INTERFACE
+          // (and therefore ACC_ABSTRACT) alongside it, and the class must implement
+          // java/lang/annotation/Annotation. A class carrying only ACC_ANNOTATION does not resolve
+          // in an annotation position, so the use site keeps failing even once the stub exists.
+          KStub.Type.ANNOTATION ->
+              Opcodes.ACC_ANNOTATION or Opcodes.ACC_INTERFACE or Opcodes.ACC_ABSTRACT
+          KStub.Type.INTERFACE -> Opcodes.ACC_INTERFACE
+          else -> Opcodes.ACC_SUPER
+        }
+
+    if (abstract) {
+      flag = flag or Opcodes.ACC_ABSTRACT
+    }
+
+    flag = flag or Opcodes.ACC_PUBLIC
+
+    return flag
+  }
+
+  // The internal name of a class is its FQN,
+  // where '.' are replaced by '/') for the package name part, and $ are use to concat the name of
+  // inner classes
+  // e.g com.foo.bar.Outer.Inner -> com/foo/bar/Outer$Inner
+  private fun KStub.internalName(): String {
+
+    var internalName = "$pkg.$name".replace(".", "/")
+
+    var currentSlash = internalName.lastIndexOf('/')
+    while (currentSlash > 0) {
+      val previousSlash = internalName.lastIndexOf('/', currentSlash - 1)
+      internalName =
+          if (previousSlash > 0 && Character.isUpperCase(internalName[previousSlash + 1])) {
+            ("${internalName.substring(0, currentSlash)}$${internalName.substring(currentSlash + 1)}")
+          } else {
+            break
+          }
+      currentSlash = previousSlash
+    }
+    return internalName
+  }
+
+  // Where should we put the class file, respecting the package name hierarchy
+  // e.g com/foor/bar/Outer$Inner -> File(root, "com/foo/bar")
+  private fun KStub.classFilePath(root: File): File {
+    return if (pkg == null) root
+    else File(root, internalName().substring(0, internalName().lastIndexOf('/')))
+  }
+
+  // The name of the class file output
+  // e.g com/foor/bar/Outer$Inner -> "Outer$Inner.class"
+  private fun KStub.classFileName(): String {
+    return "${internalName().split("/").last()}.class"
+  }
+
+  private fun KStub.superClass(): String {
+    return "java/lang/Object"
+  }
+
+  private fun KStub.interfaces(): Array<String>? {
+    return if (type == KStub.Type.ANNOTATION) arrayOf("java/lang/annotation/Annotation") else null
+  }
+
+  fun KStub.signature(): String? {
+    if (genericTypes == 0) return null
+    return "<${(0 until genericTypes).map { "T$it:Ljava/lang/Object;" }.joinToString("")}>"
+  }
+
+  private fun KStub.renderInnerClass(visitor: ClassVisitor, dir: File) {
+    if (innerStubs.isEmpty()) return
+
+    val containerClassInternalName = internalName()
+    innerStubs.forEach { innerStub ->
+      renderKStubBytecode(innerStub, dir)
+      visitor.visitInnerClass(
+          innerStub.internalName(),
+          containerClassInternalName,
+          innerStub.name,
+          innerStub.accessFlags() or Opcodes.ACC_STATIC,
+      )
+    }
+  }
+
+  private fun KStub.renderConstructor(visitor: ClassVisitor) {
+    if (ctor == null) return
+    // An annotation type is an interface, and an interface has no <init>: emitting one makes the
+    // class file unverifiable, which would trade the unresolved use site for a worse failure.
+    if (type == KStub.Type.ANNOTATION) return
+    visitor.visitMethod(
+        Opcodes.ACC_PUBLIC,
+        "<init>",
+        "(${"Ljava/lang/Object;".repeat(ctor?.namedArgs?.size ?: 0)})V",
+        null,
+        null,
+    )
+  }
+
+  // A top level function resolved into the single source of truth shared by the emitted bytecode
+  // method and its `@kotlin/Metadata` entry: the JVM `signature` (name + descriptor) MUST be
+  // identical in both, otherwise the Kotlin compiler will not resolve the top level declaration
+  // against the emitted method. Deriving both from this one value keeps them in lockstep.
+  private class TopLevelFun(val paramNames: List<String>, val signature: JvmMethodSignature)
+
+  // Top level function stubs are always generated as `(Any?, ...) -> Unit` (see
+  // ClassLevelFunctionStubsGenerator), so their JVM descriptor is a fixed shape. Two stubs sharing
+  // the same name and arity would collapse into the same JVM method, so we deduplicate to avoid
+  // emitting an invalid class file with duplicate members.
+  private fun KStub.topLevelFuns(): List<TopLevelFun> =
+      funStubs
+          .distinctBy { it.name to it.namedArgs.size }
+          .map { funStub ->
+            val descriptor = "(${"Ljava/lang/Object;".repeat(funStub.namedArgs.size)})V"
+            TopLevelFun(
+                paramNames = funStub.namedArgs.map { (paramName, _) -> paramName },
+                signature = JvmMethodSignature(funStub.name, descriptor),
+            )
+          }
+
+  private fun renderTopLevelFunctions(visitor: ClassVisitor, topLevelFuns: List<TopLevelFun>) {
+    topLevelFuns.forEach { fn ->
+      val methodVisitor =
+          visitor.visitMethod(
+              Opcodes.ACC_PUBLIC or Opcodes.ACC_STATIC or Opcodes.ACC_FINAL,
+              fn.signature.name,
+              fn.signature.descriptor,
+              null,
+              null,
+          )
+      methodVisitor?.apply {
+        visitCode()
+        visitInsn(Opcodes.RETURN)
+        // Real values are recomputed by COMPUTE_MAXS.
+        visitMaxs(0, 0)
+        visitEnd()
+      }
+    }
+  }
+
+  private fun renderFileFacadeMetadata(visitor: ClassVisitor, topLevelFuns: List<TopLevelFun>) {
+    val kmPackage = KmPackage()
+    topLevelFuns.forEach { fn ->
+      val kmFunction =
+          KmFunction(fn.signature.name).apply {
+            visibility = Visibility.PUBLIC
+            returnType = KmType().apply { classifier = KmClassifier.Class(UNIT_CLASSIFIER) }
+            fn.paramNames.forEach { paramName ->
+              valueParameters.add(
+                  KmValueParameter(paramName).apply {
+                    type =
+                        KmType().apply {
+                          classifier = KmClassifier.Class(ANY_CLASSIFIER)
+                          isNullable = true
+                        }
+                  },
+              )
+            }
+            signature = fn.signature
+          }
+      kmPackage.functions.add(kmFunction)
+    }
+
+    val metadata =
+        KotlinClassMetadata.FileFacade(kmPackage, JvmMetadataVersion.LATEST_STABLE_SUPPORTED, 0)
+            .write()
+
+    visitor.visitAnnotation("Lkotlin/Metadata;", true)?.writeMetadata(metadata)
+  }
+
+  private fun AnnotationVisitor.writeMetadata(metadata: Metadata) {
+    visit("k", metadata.kind)
+    visit("mv", metadata.metadataVersion)
+    visitArray("d1")?.apply {
+      metadata.data1.forEach { visit(null, it) }
+      visitEnd()
+    }
+    visitArray("d2")?.apply {
+      metadata.data2.forEach { visit(null, it) }
+      visitEnd()
+    }
+    if (metadata.extraString.isNotEmpty()) visit("xs", metadata.extraString)
+    if (metadata.packageName.isNotEmpty()) visit("pn", metadata.packageName)
+    visit("xi", metadata.extraInt)
+    visitEnd()
+  }
+
+  fun renderKStubBytecode(stub: KStub?, outputRoot: File) {
+    if (stub == null) return
+
+    val classWriter = ClassWriter(ClassWriter.COMPUTE_MAXS)
+
+    classWriter.visit(
+        Opcodes.ASM9,
+        stub.accessFlags(),
+        stub.internalName(),
+        stub.signature(),
+        stub.superClass(),
+        stub.interfaces(),
+    )
+
+    stub.apply {
+      if (type == KStub.Type.TOP_LEVEL_DECLARATION) {
+        // A file facade has no constructor; it exposes its top level declarations as static
+        // methods and carries a @kotlin/Metadata annotation so the Kotlin compiler resolves them
+        // as top level declarations rather than plain Java statics. The bytecode methods and the
+        // metadata entries must be computed from the same list, so we resolve it once here.
+        val topLevelFuns = topLevelFuns()
+        renderFileFacadeMetadata(classWriter, topLevelFuns)
+        renderTopLevelFunctions(classWriter, topLevelFuns)
+      } else {
+        renderInnerClass(classWriter, outputRoot)
+        renderConstructor(classWriter)
+      }
+    }
+
+    classWriter.visitEnd()
+
+    val bytecode = classWriter.toByteArray()
+
+    val folder = stub.classFilePath(outputRoot)
+    if (!folder.exists()) folder.mkdirs()
+
+    val classFile = File(folder, stub.classFileName())
+    FileOutputStream(classFile).apply {
+      write(bytecode)
+      close()
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/render/StubRender.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/render/StubRender.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub/render/StubRender.kt
@@ -0,0 +1,354 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.common.stub.render
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KArrayType
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KCtorStub
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KFunStub
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KPropertyStub
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub.Type.ANNOTATION
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub.Type.CLASS
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub.Type.INTERFACE
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub.Type.OBJECT
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KType
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KTypeVariableName
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KWildcardType
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.Type
+import com.squareup.kotlinpoet.AnnotationSpec
+import com.squareup.kotlinpoet.ClassName
+import com.squareup.kotlinpoet.CodeBlock
+import com.squareup.kotlinpoet.FileSpec
+import com.squareup.kotlinpoet.FunSpec
+import com.squareup.kotlinpoet.KModifier
+import com.squareup.kotlinpoet.ParameterSpec
+import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
+import com.squareup.kotlinpoet.PropertySpec
+import com.squareup.kotlinpoet.STAR
+import com.squareup.kotlinpoet.TypeName
+import com.squareup.kotlinpoet.TypeSpec
+import com.squareup.kotlinpoet.TypeVariableName
+import com.squareup.kotlinpoet.WildcardTypeName
+import com.squareup.kotlinpoet.asClassName
+import kotlin.text.StringBuilder
+
+const val KOSABI_GENERATED_STUB_MARKER = "A stub @g" + "enerated by Kosabi"
+
+class RenderedKStub(val stub: KStub, val render: String)
+
+fun KStub.render(): String {
+  val className = name
+  // Only nested/inner classes should have pkg == null
+  val packageName = pkg ?: ""
+
+  val fileSpec =
+      FileSpec.builder(packageName, className)
+          .apply {
+            stubImports
+                .filterNot { import -> import.matches("""^(java|org\.jetbrains).*""".toRegex()) }
+                .forEach { import -> addImport("", import) }
+            if (!treatAsReal) {
+              // We want to pretend this stub is a real file.
+              addKosabiGeneratedMarker()
+            }
+            when (type) {
+              KStub.Type.TOP_LEVEL_DECLARATION -> renderTopLevelDeclaration(this@render)
+              else ->
+                  addType(
+                      renderType(
+                          if (doNotRenderAsKotlinObject) type else returnObjectTypeIfNeeded(),
+                      ),
+                  )
+            }
+          }
+          .build()
+
+  return StringBuilder().apply { fileSpec.writeTo(this) }.toString()
+}
+
+private fun FileSpec.Builder.renderTopLevelDeclaration(stub: KStub) = apply {
+  addAnnotation(
+      AnnotationSpec.builder(JvmName::class)
+          .addMember("%S", stub.name)
+          .useSiteTarget(AnnotationSpec.UseSiteTarget.FILE)
+          .build(),
+  )
+
+  stub.funStubs.map { it.renderFunction(isOpen = false) }.forEach { addFunction(it) }
+}
+
+// TODO: We might need to create different names for inner generic type parameters:
+//  Now:
+//    Outer<T0, T1> { Inner<T0, T1, T2> }
+//  We might need:
+//    Outer<T0, T1> { Inner<IT0, IT1, IT2> }
+private fun KStub.renderType(stubType: KStub.Type): TypeSpec {
+  return when (stubType) {
+        CLASS ->
+            TypeSpec.classBuilder(name).stubDefaultCtor(ctor).also {
+              if (!abstract) it.addModifiers(KModifier.OPEN)
+              else it.addModifiers(KModifier.ABSTRACT)
+            }
+        INTERFACE -> TypeSpec.interfaceBuilder(name)
+        ANNOTATION -> TypeSpec.annotationBuilder(name).stubAnnotationCtor(ctor)
+        OBJECT -> TypeSpec.objectBuilder(name)
+        // TODO(sergei): change to render Exception
+        else -> throw Error()
+      }
+      .stubGenericTypes(genericTypes, typeVariableList)
+      .apply {
+        stubAnnotations.forEach { annotation ->
+          addAnnotation(
+              AnnotationSpec.builder(ClassName(annotation.pkg, annotation.name))
+                  .apply {
+                    if (annotation.attributesText.isNotEmpty())
+                        addMember(CodeBlock.of(annotation.attributesText))
+                  }
+                  .build(),
+          )
+        }
+        extends?.let {
+          if (stubType == INTERFACE) addSuperinterface(it.asTypeName())
+          else superclass(it.asTypeName())
+        }
+        implements.map { it.asTypeName() }.forEach { addSuperinterface(it) }
+        // A static property on a CLASS only becomes a static JVM field from inside the companion;
+        // rendered on the class body it is an instance field. Scoped to the opted-in shape so the
+        // OBJECT-coercion path below keeps emitting the layout every other stub already relies on.
+        val companionProperties =
+            if (stubType == CLASS && doNotRenderAsKotlinObject) propertyStubs.filter { it.static }
+            else emptyList()
+        propertyStubs.filterNot { it in companionProperties }.forEach { addProperty(it.render()) }
+        innerStubs
+            .map {
+              it.renderType(
+                  if (it.doNotRenderAsKotlinObject) it.type else it.returnObjectTypeIfNeeded(),
+              )
+            }
+            .forEach { addType(it) }
+        val staticFunctions = funStubs.filter { it.static }
+        if (
+            stubType == CLASS && (staticFunctions.isNotEmpty() || companionProperties.isNotEmpty())
+        ) {
+          val companionObject = TypeSpec.companionObjectBuilder()
+          staticFunctions.map { it.renderFunction() }.forEach { companionObject.addFunction(it) }
+          companionProperties.map { it.render() }.forEach { companionObject.addProperty(it) }
+          addType(companionObject.build())
+          funStubs.filterNot { it.static }.forEach { addFunction(it.renderFunction()) }
+        } else {
+          if (stubType == OBJECT) {
+            funStubs.filterNot { it.isConstructor }.map { addFunction(it.renderFunction()) }
+          } else {
+            funStubs.map { addFunction(it.renderFunction()) }
+          }
+        }
+      }
+      .build()
+}
+
+private fun FileSpec.Builder.addKosabiGeneratedMarker(): FileSpec.Builder = apply {
+  addFileComment(KOSABI_GENERATED_STUB_MARKER)
+}
+
+private fun KFunStub.renderFunction(isOpen: Boolean = true): FunSpec {
+  val spec =
+      if (isConstructor) {
+        FunSpec.constructorBuilder().apply {
+          if (private) {
+            addModifiers(KModifier.PRIVATE)
+          }
+          if (constructorSuperDelegate.first) {
+            val values =
+                constructorSuperDelegate.second.map { nameArg ->
+                  val value = nameArg.first
+                  when (nameArg.second.pkg + nameArg.second.names) {
+                    listOf("kotlin", "String") -> "$value"
+                    else -> value
+                  }
+                }
+            callSuperConstructor(*values.toTypedArray())
+          }
+        }
+      } else {
+        FunSpec.builder(name).apply {
+          if (protected) {
+            addModifiers(KModifier.PROTECTED)
+          }
+          if (isOverride) {
+            addModifiers(KModifier.OVERRIDE)
+          }
+          // Operator function couldn't be open
+          if (isOperator) {
+            addModifiers(KModifier.OPERATOR)
+          } else if (abstract) {
+            addModifiers(KModifier.ABSTRACT)
+          } else if (isFinal) {
+            addModifiers(KModifier.FINAL)
+          } else if (isOpen && !isOverride) {
+            addModifiers(KModifier.OPEN)
+          }
+
+          returns(ret.asTypeName())
+          if (ret != KType.UNIT && !abstract) {
+            addStatement("return TODO()")
+          }
+
+          stubThrows(throws)
+          if (static) {
+            addAnnotation(JvmStatic::class)
+          }
+          typeVariableList.forEach { addTypeVariable(it.asTypeVariableName()) }
+        }
+      }
+
+  // apply the parameter spec
+  spec.apply {
+    namedArgs.forEach { (name, type) -> addParameter(ParameterSpec(name, type.asTypeName())) }
+  }
+
+  annotations.forEach { annotation ->
+    spec.addAnnotation(
+        AnnotationSpec.builder(ClassName(annotation.pkg, annotation.name))
+            .apply {
+              if (annotation.attributesText.isNotEmpty())
+                  addMember(CodeBlock.of(annotation.attributesText))
+            }
+            .build(),
+    )
+  }
+
+  return spec.build()
+}
+
+private fun TypeSpec.Builder.stubGenericTypes(
+    params: Int,
+    typeVariables: List<KTypeVariableName>,
+): TypeSpec.Builder = apply {
+  if (params <= 0 && typeVariables.isEmpty()) return@apply
+  if (typeVariables.isNotEmpty()) {
+    typeVariables.forEach { addTypeVariable(it.asTypeVariableName()) }
+  } else {
+    repeat(params) { addTypeVariable(TypeVariableName("T${it}")) }
+  }
+}
+
+private fun TypeSpec.Builder.stubDefaultCtor(ctorStub: KCtorStub?): TypeSpec.Builder = apply {
+  if (ctorStub == null || ctorStub.namedArgs.isEmpty()) return@apply
+
+  // Expecting ctor(p0: T1, p1: T2, p2: T3)
+  val ctor =
+      FunSpec.constructorBuilder()
+          .apply {
+            ctorStub.namedArgs.forEach { (name, type) -> addParameter(name, type.asTypeName()) }
+          }
+          .build()
+  primaryConstructor(ctor)
+
+  ctorStub.namedArgs.forEach { (name, type) ->
+    addProperty(
+        PropertySpec.builder(name, type.asTypeName()).initializer(name).mutable(true).build(),
+    )
+  }
+}
+
+private fun TypeSpec.Builder.stubAnnotationCtor(ctorStub: KCtorStub?): TypeSpec.Builder = apply {
+  if (ctorStub == null || ctorStub.namedArgs.isEmpty()) return@apply
+
+  val ctor =
+      FunSpec.constructorBuilder()
+          .apply {
+            ctorStub.namedArgs.forEach { (name, type) -> addParameter(name, type.asTypeName()) }
+          }
+          .build()
+  primaryConstructor(ctor)
+
+  ctorStub.namedArgs.forEach { (name, type) ->
+    addProperty(PropertySpec.builder(name, type.asTypeName()).initializer(name).build())
+  }
+}
+
+private fun FunSpec.Builder.stubThrows(e: List<KType>): FunSpec.Builder = apply {
+  if (e.isEmpty()) return@apply
+
+  val throwsAnno =
+      AnnotationSpec.builder(Throws::class)
+          .apply { e.map { it.asTypeName() }.forEach { addMember("$it::class") } }
+          .build()
+
+  addAnnotation(throwsAnno)
+}
+
+private fun KTypeVariableName.asTypeVariableName(): TypeVariableName =
+    TypeVariableName(name, *bounds.map { it.asTypeName() }.toTypedArray())
+
+// If the class contains all static functions (filter out private and constructor) or all inner
+// class is Object type, we will render as object class instead.
+// This is special handler for JavaKStub, as the companion object is not expected in Dex level.
+private fun KStub.returnObjectTypeIfNeeded(): KStub.Type {
+  val allPropertiesAreStatic = propertyStubs.isNotEmpty() && propertyStubs.all { it.static }
+  val innerFuns = funStubs.filterNot { it.private || it.isConstructor }
+  val allFunsAreStatic = innerFuns.isNotEmpty() && innerFuns.all { it.static }
+  val allInnerClassesAreObject =
+      innerStubs.isNotEmpty() && innerStubs.all { it.returnObjectTypeIfNeeded() == OBJECT }
+  return if (
+      type == CLASS &&
+          ctor == null &&
+          (allFunsAreStatic || allInnerClassesAreObject || allPropertiesAreStatic)
+  ) {
+    OBJECT
+  } else {
+    type
+  }
+}
+
+fun Type.asTypeName(): TypeName {
+  if (this is KTypeVariableName) {
+    return asTypeVariableName()
+  }
+  val type = ClassName(pkg.joinToString(separator = "."), names)
+
+  val typeName =
+      if (generics.isNotEmpty()) {
+            type.parameterizedBy(generics.map { it.asTypeName() })
+          } else {
+            type
+          }
+          .copy(nullable)
+
+  return when (this) {
+    is KArrayType -> {
+      Array::class.asClassName().parameterizedBy(typeName).copy(nullable)
+    }
+
+    is KWildcardType -> {
+      when (bound) {
+        KWildcardType.BoundType.SUPER -> WildcardTypeName.consumerOf(typeName)
+        KWildcardType.BoundType.EXTENDS -> WildcardTypeName.producerOf(typeName)
+        KWildcardType.BoundType.UNBOUNDED -> STAR
+      }
+    }
+
+    else -> {
+      typeName
+    }
+  }
+}
+
+private fun KPropertyStub.render(): PropertySpec {
+  val spec =
+      PropertySpec.builder(name, ret.asTypeName()).apply {
+        if (static) addAnnotation(JvmField::class)
+        if (value != null) {
+          initializer(value, *args.map { it.asTypeName() }.toTypedArray())
+        }
+      }
+  return spec.build()
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/BUCK
@@ -0,0 +1,46 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+# compilercompat shims are bucketed by Kotlin minor version: every 2.3.x compiler
+# uses the compilercompat/2.3.0 folder. Key off kotlin_version_for_upgrade_only_do_not_use
+# (the same config the kotlincd toolchain selects the compiler jar from) so the shims
+# always match the compiler actually run -- not kotlin_version, which can differ.
+_KOTLIN_VERSION_PARTS = read_root_config("kotlin", "kotlin_version_for_upgrade_only_do_not_use", "2.2.0").split(".")
+
+KOTLIN_VERSION = _KOTLIN_VERSION_PARTS[0] + "." + _KOTLIN_VERSION_PARTS[1] + ".0"
+
+buck_kotlin_library(
+    name = "k2-jvm-abi-gen-lib",
+    srcs = glob(
+        ["**/*.kt"],
+        exclude = ["src/main/kotlin/compilercompat/2.*/*.kt"],
+    )
+    + glob(["src/main/kotlin/compilercompat/" + KOTLIN_VERSION + "/*.kt"]),
+    labels = ["codegen_rule"],
+    provided_deps = [
+        "prelude//toolchains/android/third-party:kotlin-compiler-embeddable",
+    ],
+    resources = glob(["resources/**"]),
+    resources_root = "resources",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "fbsource//fbandroid/java/com/facebook/kotlin/compilercompat:compilercompat",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common:common",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub:stub",
+        "prelude//toolchains/android/third-party:kotlin-metadata-jvm",
+        "prelude//toolchains/android/third-party:kotlin-stdlib",
+        "prelude//toolchains/android/third-party:kotlinx-coroutines-core-jvm",
+    ],
+)
+
+buck_java_binary(
+    name = "k2-jvm-abi-gen",
+    visibility = ["PUBLIC"],
+    deps = [":k2-jvm-abi-gen-lib"],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
@@ -0,0 +1,1 @@
+com.facebook.K2JvmAbiCommandLineProcessor
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
@@ -0,0 +1,1 @@
+com.facebook.K2JvmAbiComponentRegistrar
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/BytecodeTransformer.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/BytecodeTransformer.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/BytecodeTransformer.kt
@@ -0,0 +1,316 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook
+
+import kotlin.metadata.Visibility
+import kotlin.metadata.jvm.KotlinClassMetadata
+import kotlin.metadata.visibility
+import org.jetbrains.org.objectweb.asm.AnnotationVisitor
+import org.jetbrains.org.objectweb.asm.ClassReader
+import org.jetbrains.org.objectweb.asm.ClassVisitor
+import org.jetbrains.org.objectweb.asm.ClassWriter
+import org.jetbrains.org.objectweb.asm.FieldVisitor
+import org.jetbrains.org.objectweb.asm.MethodVisitor
+import org.jetbrains.org.objectweb.asm.Opcodes
+
+/** Transforms class file bytecode. Returns null if no transformation was needed. */
+interface BytecodeTransformer {
+  fun transform(bytes: ByteArray): ByteArray?
+}
+
+/**
+ * Strips @Throws annotations from bytecode.
+ *
+ * K2 JVM backend writes @Throws to both the method's throws clause AND to
+ * RuntimeInvisibleAnnotations, while K1 only writes the throws clause. Safe Kotlin plugin reads
+ *
+ * @Throws from RuntimeInvisibleAnnotations and complains even when exceptions are properly caught.
+ *   We strip @Throws from annotations while keeping the throws clause intact.
+ */
+class ThrowsAnnotationStripper : BytecodeTransformer {
+  override fun transform(bytes: ByteArray): ByteArray? {
+    val reader = ClassReader(bytes)
+    val writer = ClassWriter(0) // Don't compute frames/maxs, just copy
+
+    var found = false
+    val visitor =
+        object : ClassVisitor(Opcodes.ASM9, writer) {
+          // Filter class-level annotations
+          override fun visitAnnotation(
+              descriptor: String,
+              visible: Boolean,
+          ): AnnotationVisitor? {
+            return if (isThrowsAnnotation(descriptor)) {
+              found = true
+              null // Skip @Throws annotation
+            } else {
+              super.visitAnnotation(descriptor, visible)
+            }
+          }
+
+          // Filter method-level annotations
+          override fun visitMethod(
+              access: Int,
+              name: String,
+              descriptor: String,
+              signature: String?,
+              exceptions: Array<out String>?,
+          ): MethodVisitor? {
+            val methodVisitor = super.visitMethod(access, name, descriptor, signature, exceptions)
+            return if (methodVisitor != null) {
+              object : MethodVisitor(Opcodes.ASM9, methodVisitor) {
+                override fun visitAnnotation(
+                    desc: String,
+                    visible: Boolean,
+                ): AnnotationVisitor? {
+                  return if (isThrowsAnnotation(desc)) {
+                    found = true
+                    null // Skip @Throws annotation
+                  } else {
+                    super.visitAnnotation(desc, visible)
+                  }
+                }
+              }
+            } else {
+              null
+            }
+          }
+
+          // Filter field-level annotations
+          override fun visitField(
+              access: Int,
+              name: String,
+              descriptor: String,
+              signature: String?,
+              value: Any?,
+          ): FieldVisitor? {
+            val fieldVisitor = super.visitField(access, name, descriptor, signature, value)
+            return if (fieldVisitor != null) {
+              object : FieldVisitor(Opcodes.ASM9, fieldVisitor) {
+                override fun visitAnnotation(
+                    desc: String,
+                    visible: Boolean,
+                ): AnnotationVisitor? {
+                  return if (isThrowsAnnotation(desc)) {
+                    found = true
+                    null // Skip @Throws annotation
+                  } else {
+                    super.visitAnnotation(desc, visible)
+                  }
+                }
+              }
+            } else {
+              null
+            }
+          }
+
+          private fun isThrowsAnnotation(descriptor: String): Boolean {
+            return descriptor == "Lkotlin/jvm/Throws;" || descriptor == "Lkotlin/Throws;"
+          }
+        }
+
+    reader.accept(visitor, 0)
+    return if (found) writer.toByteArray() else null
+  }
+}
+
+/**
+ * Strips private declarations from @Metadata annotation in bytecode.
+ *
+ * Private methods, properties, and constructors persist in Kotlin metadata (serialized into
+ *
+ * @Metadata annotation's d1/d2 arrays) even after being stripped from IR bytecode. This causes
+ *   KSP2/DI processors to see private interface methods and fail with errors.
+ *
+ * This transformer:
+ * 1. Reads the @Metadata annotation from each .class file
+ * 2. Parses the metadata using kotlinx-metadata-jvm
+ * 3. Filters out private functions, properties, and constructors
+ * 4. Writes the modified metadata back to the class file
+ */
+class PrivateMetadataStripper : BytecodeTransformer {
+  private val privateVisibilities =
+      setOf(Visibility.PRIVATE, Visibility.PRIVATE_TO_THIS, Visibility.LOCAL)
+
+  override fun transform(bytes: ByteArray): ByteArray? {
+    val reader = ClassReader(bytes)
+
+    // First pass: collect metadata annotation values
+    var metadataKind: Int? = null
+    var metadataVersion: IntArray? = null
+    var data1: Array<String>? = null
+    var data2: Array<String>? = null
+    var extraString: String? = null
+    var packageName: String? = null
+    var extraInt: Int? = null
+
+    reader.accept(
+        object : ClassVisitor(Opcodes.ASM9) {
+          override fun visitAnnotation(
+              descriptor: String,
+              visible: Boolean,
+          ): AnnotationVisitor? {
+            if (descriptor == "Lkotlin/Metadata;") {
+              return object : AnnotationVisitor(Opcodes.ASM9) {
+                override fun visit(name: String?, value: Any?) {
+                  when (name) {
+                    "k" -> metadataKind = value as? Int
+                    "mv" -> metadataVersion = value as? IntArray
+                    "xs" -> extraString = value as? String
+                    "pn" -> packageName = value as? String
+                    "xi" -> extraInt = value as? Int
+                  }
+                }
+
+                override fun visitArray(name: String?): AnnotationVisitor {
+                  return object : AnnotationVisitor(Opcodes.ASM9) {
+                    private val list = mutableListOf<String>()
+
+                    override fun visit(name: String?, value: Any?) {
+                      if (value is String) {
+                        list.add(value)
+                      }
+                    }
+
+                    override fun visitEnd() {
+                      when (name) {
+                        "d1" -> data1 = list.toTypedArray()
+                        "d2" -> data2 = list.toTypedArray()
+                      }
+                    }
+                  }
+                }
+              }
+            }
+            return null
+          }
+        },
+        ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES,
+    )
+
+    // If no metadata annotation found, skip this file
+    if (metadataKind == null || data1 == null || data2 == null) {
+      return null
+    }
+
+    // Parse the metadata
+    val header = Metadata(
+        kind = metadataKind!!,
+        metadataVersion = metadataVersion ?: intArrayOf(),
+        data1 = data1!!,
+        data2 = data2!!,
+        extraString = extraString ?: "",
+        packageName = packageName ?: "",
+        extraInt = extraInt ?: 0,
+    )
+
+    val metadata =
+        try {
+          KotlinClassMetadata.readStrict(header)
+        } catch (e: Exception) {
+          return null
+        }
+
+    // Filter private declarations based on metadata type
+    var modified = false
+    when (metadata) {
+      is KotlinClassMetadata.Class -> {
+        val kmClass = metadata.kmClass
+        val functionsRemoved = kmClass.functions.removeAll { it.visibility in privateVisibilities }
+        val propertiesRemoved =
+            kmClass.properties.removeAll { it.visibility in privateVisibilities }
+        val constructorsRemoved =
+            kmClass.constructors.removeAll { it.visibility in privateVisibilities }
+        // Note: Private supertype stripping is done at the FIR level in
+        // stripPrivateSupertypesFromFirMetadataSources() which has access to actual
+        // visibility info. The bytecode post-processing approach was too aggressive
+        // as it couldn't distinguish between private classes from the same target
+        // vs. dependencies from the same package.
+        modified = functionsRemoved || propertiesRemoved || constructorsRemoved
+      }
+      is KotlinClassMetadata.FileFacade -> {
+        val kmPackage = metadata.kmPackage
+        val functionsRemoved =
+            kmPackage.functions.removeAll { it.visibility in privateVisibilities }
+        val propertiesRemoved =
+            kmPackage.properties.removeAll { it.visibility in privateVisibilities }
+        modified = functionsRemoved || propertiesRemoved
+      }
+      is KotlinClassMetadata.MultiFileClassPart -> {
+        val kmPackage = metadata.kmPackage
+        val functionsRemoved =
+            kmPackage.functions.removeAll { it.visibility in privateVisibilities }
+        val propertiesRemoved =
+            kmPackage.properties.removeAll { it.visibility in privateVisibilities }
+        modified = functionsRemoved || propertiesRemoved
+      }
+      else -> {
+        // SyntheticClass, MultiFileClassFacade, Unknown - no declarations to filter
+      }
+    }
+
+    // If nothing was modified, skip rewriting the class file
+    if (!modified) {
+      return null
+    }
+
+    // Write the modified metadata back
+    val newHeader =
+        try {
+          metadata.write()
+        } catch (e: Exception) {
+          return null
+        }
+
+    // Second pass: rewrite the class file with updated metadata
+    val writer = ClassWriter(0)
+    val visitor =
+        object : ClassVisitor(Opcodes.ASM9, writer) {
+          override fun visitAnnotation(
+              descriptor: String,
+              visible: Boolean,
+          ): AnnotationVisitor? {
+            return if (descriptor == "Lkotlin/Metadata;") {
+              // Replace with new metadata
+              val av = super.visitAnnotation(descriptor, visible)
+              av?.visit("k", newHeader.kind)
+              av?.visit("mv", newHeader.metadataVersion)
+              av?.visitArray("d1")?.apply {
+                newHeader.data1.forEach { visit(null, it) }
+                visitEnd()
+              }
+              av?.visitArray("d2")?.apply {
+                newHeader.data2.forEach { visit(null, it) }
+                visitEnd()
+              }
+              if (newHeader.extraString.isNotEmpty()) {
+                av?.visit("xs", newHeader.extraString)
+              }
+              if (newHeader.packageName.isNotEmpty()) {
+                av?.visit("pn", newHeader.packageName)
+              }
+              av?.visit("xi", newHeader.extraInt)
+              // Return null to skip the original annotation values
+              object : AnnotationVisitor(Opcodes.ASM9) {
+                override fun visitEnd() {
+                  av?.visitEnd()
+                }
+              }
+            } else {
+              super.visitAnnotation(descriptor, visible)
+            }
+          }
+        }
+
+    reader.accept(visitor, 0)
+    return writer.toByteArray()
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiCommandLineProcessor.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiCommandLineProcessor.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiCommandLineProcessor.kt
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook
+
+import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption
+import org.jetbrains.kotlin.compiler.plugin.CliOption
+import org.jetbrains.kotlin.compiler.plugin.CliOptionProcessingException
+import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
+import org.jetbrains.kotlin.config.CompilerConfiguration
+
+@OptIn(org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi::class)
+@SuppressWarnings("PackageLocationMismatch")
+class K2JvmAbiCommandLineProcessor : CommandLineProcessor {
+  companion object {
+    const val COMPILER_PLUGIN_ID: String = "com.facebook.k2.jvm.abi.gen"
+
+    val OUTPUT_PATH_OPTION: CliOption = CliOption(
+        "outputDir",
+        "<path>",
+        "Output path for generated files. This can be either a directory or a jar file.",
+        true,
+    )
+
+    val EARLY_TERMINATION_OPTION: CliOption = CliOption(
+        "earlyTermination",
+        "<boolean>",
+        "Whether we should terminate K2JvmAbiGen early. Default is false.",
+        required = false,
+    )
+
+    val ENABLE_MIXED_COMPILATION: CliOption = CliOption(
+        "enableMixedCompilation",
+        "<boolean>",
+        "Enable to translate Java sources into ABI. Default is false.",
+        false,
+    )
+
+    val DEBUG_OUTPUT_OPTION: CliOption = CliOption(
+        "debugOutput",
+        "<boolean>",
+        "Enable debug output for K2 ABI generation. Default is false.",
+        false,
+    )
+
+    const val COMPOSE_PLUGIN_PATH_FRAGMENT: String = "compose-compiler-plugin"
+
+    val ENABLE_COMPOSE_ABI_EMULATION_OPTION: CliOption = CliOption(
+        "enableComposeAbiEmulation",
+        "<boolean>",
+        "Enable Compose ABI emulation. Default is false.",
+        false,
+    )
+
+    val ABI_VALIDATION_MODE_OPTION: CliOption = CliOption(
+        "abiValidationMode",
+        "off|warn|error",
+        "How to report ABI content that had to be repaired because a dependency was not on " +
+            "the source-only ABI classpath. `warn` reports each repair as a compiler warning, " +
+            "`error` fails the compilation instead of emitting a knowingly-wrong ABI. " +
+            "Default is off: fbsource builds Kotlin with `-Werror`, so `warn` also fails the " +
+            "compile and has to be opted into per target.",
+        false,
+    )
+  }
+
+  override val pluginId: String
+    get() = COMPILER_PLUGIN_ID
+
+  override val pluginOptions: Collection<CliOption>
+    get() = listOf(
+        OUTPUT_PATH_OPTION,
+        EARLY_TERMINATION_OPTION,
+        ENABLE_MIXED_COMPILATION,
+        DEBUG_OUTPUT_OPTION,
+        ENABLE_COMPOSE_ABI_EMULATION_OPTION,
+        ABI_VALIDATION_MODE_OPTION,
+    )
+
+  override fun processOption(
+      option: AbstractCliOption,
+      value: String,
+      configuration: CompilerConfiguration,
+  ) {
+    when (option) {
+      OUTPUT_PATH_OPTION -> configuration.put(K2JvmAbiConfigurationKeys.OUTPUT_PATH, value)
+      EARLY_TERMINATION_OPTION ->
+          configuration.put(K2JvmAbiConfigurationKeys.EARLY_TERMINATION, value == "true")
+      ENABLE_MIXED_COMPILATION ->
+          configuration.put(K2JvmAbiConfigurationKeys.ENABLE_MIXED_COMPILATION, value == "true")
+      DEBUG_OUTPUT_OPTION ->
+          configuration.put(K2JvmAbiConfigurationKeys.DEBUG_OUTPUT, value == "true")
+      ENABLE_COMPOSE_ABI_EMULATION_OPTION ->
+          configuration.put(
+              K2JvmAbiConfigurationKeys.ENABLE_COMPOSE_ABI_EMULATION,
+              value == "true",
+          )
+      ABI_VALIDATION_MODE_OPTION ->
+          configuration.put(K2JvmAbiConfigurationKeys.ABI_VALIDATION_MODE, value)
+      else -> throw CliOptionProcessingException("Unknown option: ${option.optionName}")
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiComponentRegistrar.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiComponentRegistrar.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiComponentRegistrar.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook
+
+import com.facebook.kotlin.compilercompat.CompilerPluginRegistrarCompat
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.fir.extensions.FirAnalysisHandlerExtension
+import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrarAdapter
+
+@OptIn(org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi::class)
+@SuppressWarnings("PackageLocationMismatch")
+class K2JvmAbiComponentRegistrar : CompilerPluginRegistrarCompat() {
+  override val pluginIdCompat: String = "com.facebook.kotlin.k2.jvm.abi.gen"
+
+  override fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration) {
+    val outputPath = configuration.get(K2JvmAbiConfigurationKeys.OUTPUT_PATH)
+
+    if (outputPath != null) {
+      // Register K2 FIR extension for ABI generation
+      FirAnalysisHandlerExtension.registerExtension(K2JvmAbiFirAnalysisHandlerExtension(outputPath))
+      FirExtensionRegistrarAdapter.registerExtension(AbiGenFirExtensionRegistrar())
+    }
+  }
+
+  override val supportsK2: Boolean
+    get() = true
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiConfigurationKeys.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiConfigurationKeys.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiConfigurationKeys.kt
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook
+
+import org.jetbrains.kotlin.config.CompilerConfigurationKey
+
+@SuppressWarnings("PackageLocationMismatch")
+object K2JvmAbiConfigurationKeys {
+  val OUTPUT_PATH: CompilerConfigurationKey<String> =
+      CompilerConfigurationKey.create("output path for K2 JVM ABI generation")
+
+  val EARLY_TERMINATION: CompilerConfigurationKey<Boolean> =
+      CompilerConfigurationKey.create("early termination flag for K2 JVM ABI generation")
+
+  val ENABLE_MIXED_COMPILATION: CompilerConfigurationKey<Boolean> =
+      CompilerConfigurationKey.create("enable mixed compilation for K2 JVM ABI generation")
+
+  val DEBUG_OUTPUT: CompilerConfigurationKey<Boolean> =
+      CompilerConfigurationKey.create("debug output flag for K2 JVM ABI generation")
+
+  val ENABLE_COMPOSE_ABI_EMULATION: CompilerConfigurationKey<Boolean> =
+      CompilerConfigurationKey.create("enable Compose ABI emulation for K2 JVM ABI generation")
+
+  val ABI_VALIDATION_MODE: CompilerConfigurationKey<String> =
+      CompilerConfigurationKey.create("ABI validation mode for K2 JVM ABI generation")
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiFirAnalysisHandlerExtension.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiFirAnalysisHandlerExtension.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/K2JvmAbiFirAnalysisHandlerExtension.kt
@@ -0,0 +1,1733 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("OPT_IN_USAGE_ERROR")
+@file:OptIn(
+    com.facebook.DeprecatedForRemovalCompilerApiCompat::class,
+    com.facebook.DirectDeclarationsAccessCompat::class,
+)
+
+package com.facebook
+
+import java.io.ByteArrayOutputStream
+import java.io.DataOutputStream
+import java.io.File
+import org.jetbrains.kotlin.backend.jvm.JvmIrDeserializerImpl
+import org.jetbrains.kotlin.cli.common.config.KotlinSourceRoot
+import org.jetbrains.kotlin.cli.common.config.kotlinSourceRoots
+import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
+import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
+import org.jetbrains.kotlin.cli.common.messages.MessageCollector
+import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
+import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
+import org.jetbrains.kotlin.cli.jvm.compiler.VfsBasedProjectEnvironment
+import org.jetbrains.kotlin.cli.jvm.compiler.createContextForIncrementalCompilation
+import org.jetbrains.kotlin.cli.jvm.compiler.report
+import org.jetbrains.kotlin.cli.jvm.config.jvmClasspathRoots
+import org.jetbrains.kotlin.com.intellij.openapi.diagnostic.Logger
+import org.jetbrains.kotlin.com.intellij.openapi.project.Project
+import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer
+import org.jetbrains.kotlin.com.intellij.openapi.vfs.StandardFileSystems
+import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile
+import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileManager
+import org.jetbrains.kotlin.com.intellij.psi.PsiManager
+import org.jetbrains.kotlin.config.CommonConfigurationKeys
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.config.JVMConfigurationKeys
+import org.jetbrains.kotlin.config.messageCollector
+import org.jetbrains.kotlin.descriptors.ClassKind
+import org.jetbrains.kotlin.descriptors.EffectiveVisibility
+import org.jetbrains.kotlin.descriptors.Modality
+import org.jetbrains.kotlin.descriptors.Visibilities
+import org.jetbrains.kotlin.extensions.CompilerConfigurationExtension
+import org.jetbrains.kotlin.extensions.PreprocessedFileCreator
+import org.jetbrains.kotlin.fir.FirElement
+import org.jetbrains.kotlin.fir.FirSession
+import org.jetbrains.kotlin.fir.backend.jvm.JvmFir2IrExtensions
+import org.jetbrains.kotlin.fir.declarations.FirConstructor
+import org.jetbrains.kotlin.fir.declarations.FirEnumEntry
+import org.jetbrains.kotlin.fir.declarations.FirRegularClass
+import org.jetbrains.kotlin.fir.declarations.FirTypeAlias
+import org.jetbrains.kotlin.fir.declarations.impl.FirResolvedDeclarationStatusImpl
+import org.jetbrains.kotlin.fir.declarations.utils.isConst
+import org.jetbrains.kotlin.fir.declarations.utils.isFromLibrary
+import org.jetbrains.kotlin.fir.expressions.FirAnonymousObjectExpression
+import org.jetbrains.kotlin.fir.expressions.builder.buildLiteralExpression
+import org.jetbrains.kotlin.fir.extensions.ExperimentalTopLevelDeclarationsGenerationApi
+import org.jetbrains.kotlin.fir.extensions.FirAnalysisHandlerExtension
+import org.jetbrains.kotlin.fir.extensions.FirDeclarationGenerationExtension
+import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrar
+import org.jetbrains.kotlin.fir.extensions.FirExtensionSessionComponent
+import org.jetbrains.kotlin.fir.extensions.MemberGenerationContext
+import org.jetbrains.kotlin.fir.pipeline.buildFirFromKtFiles
+import org.jetbrains.kotlin.fir.pipeline.runResolution
+import org.jetbrains.kotlin.fir.plugin.createMemberFunction
+import org.jetbrains.kotlin.fir.plugin.createMemberProperty
+import org.jetbrains.kotlin.fir.plugin.createTopLevelClass
+import org.jetbrains.kotlin.fir.resolve.providers.dependenciesSymbolProvider
+import org.jetbrains.kotlin.fir.resolve.providers.symbolProvider
+import org.jetbrains.kotlin.fir.symbols.SymbolInternals
+import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
+import org.jetbrains.kotlin.fir.symbols.impl.FirClassLikeSymbol
+import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
+import org.jetbrains.kotlin.fir.symbols.impl.FirEnumEntrySymbol
+import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol
+import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
+import org.jetbrains.kotlin.fir.types.ConeClassLikeType
+import org.jetbrains.kotlin.fir.types.ConeKotlinType
+import org.jetbrains.kotlin.fir.types.ConeKotlinTypeProjection
+import org.jetbrains.kotlin.fir.types.FirResolvedTypeRef
+import org.jetbrains.kotlin.fir.types.coneType
+import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitorVoid
+import org.jetbrains.kotlin.idea.KotlinFileType
+import org.jetbrains.kotlin.ir.declarations.IrClass
+import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
+import org.jetbrains.kotlin.ir.util.isFileClass
+import org.jetbrains.kotlin.metadata.jvm.JvmModuleProtoBuf
+import org.jetbrains.kotlin.modules.Module
+import org.jetbrains.kotlin.modules.TargetId
+import org.jetbrains.kotlin.name.CallableId
+import org.jetbrains.kotlin.name.ClassId
+import org.jetbrains.kotlin.name.FqName
+import org.jetbrains.kotlin.name.Name
+import org.jetbrains.kotlin.psi.KtAnnotationEntry
+import org.jetbrains.kotlin.psi.KtClass
+import org.jetbrains.kotlin.psi.KtFile
+import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
+import org.jetbrains.kotlin.resolve.multiplatform.hmppModuleName
+import org.jetbrains.kotlin.resolve.multiplatform.isCommonSource
+import org.jetbrains.kotlin.types.ConstantValueKind
+
+@SuppressWarnings("PackageLocationMismatch")
+class K2JvmAbiFirAnalysisHandlerExtension(private val outputPath: String) :
+    FirAnalysisHandlerExtension() {
+
+  private val pipeline = AbiGenPipeline()
+
+  override fun isApplicable(configuration: CompilerConfiguration): Boolean {
+    return true
+  }
+
+  override fun doAnalysis(project: Project, configuration: CompilerConfiguration): Boolean {
+    val updatedConfiguration =
+        configuration.copy().apply {
+          retainOutputInMemoryCompat()
+          put(JVMConfigurationKeys.OUTPUT_DIRECTORY, File(outputPath))
+          put(JVMConfigurationKeys.VALIDATE_BYTECODE, true)
+          put(JVMConfigurationKeys.SKIP_BODIES, true)
+        }
+    // the disposable is responsible to dispose the project after the analysis is done
+    val disposable = Disposer.newDisposable("K2KosabiSession.project")
+    try {
+      val projectEnvironment = createProjectEnvironmentCompat(
+          updatedConfiguration,
+          disposable,
+          EnvironmentConfigFiles.JVM_CONFIG_FILES,
+          configuration.messageCollector,
+      )
+      if (updatedConfiguration.messageCollector.hasErrors()) {
+        return false
+      }
+      val messageCollector =
+          updatedConfiguration.getNotNull(CommonConfigurationKeys.MESSAGE_COLLECTOR_KEY)
+      val module =
+          updatedConfiguration[JVMConfigurationKeys.MODULES]?.single()
+              ?: error(
+                  "Single module expected: ${updatedConfiguration[JVMConfigurationKeys.MODULES]}",
+              )
+
+      val sourceFiles = createSourceFilesFromSourceRoots(
+          updatedConfiguration,
+          projectEnvironment.project,
+          configuration.kotlinSourceRoots,
+      )
+
+      // Run FIR frontend to analyze source files
+      val analysisResults = runFrontendForKosabi(
+          projectEnvironment,
+          updatedConfiguration,
+          sourceFiles,
+          module,
+      )
+
+      // Collect class usage from the resolved FIR tree for dep file tracking.
+      // The DependencyTracker compiler plugin's FIR checkers don't run in kosabi's
+      // inner session (separate project, checkers skipped), so we walk the FIR tree
+      // directly to extract classpath class references.
+      KosabiClassUsageCollector().collectAndDump(analysisResults, configuration)
+
+      // Detect missing transitive dependencies by checking if all supertypes can be resolved.
+      // If any are found, strip their supertype references from FIR to prevent crashes
+      // during FIR-to-IR fake override building.
+      val missingTypes = collectMissingTypesFromFir(analysisResults)
+      if (missingTypes.isNotEmpty()) {
+        stripUnresolvableSupertypesFromFir(analysisResults, missingTypes)
+      }
+
+      runBackendForKosabi(
+          messageCollector,
+          projectEnvironment,
+          updatedConfiguration,
+          module,
+          analysisResults,
+          sourceFiles,
+      )
+    } finally {
+      Disposer.dispose(disposable)
+    }
+    return true
+  }
+
+  // Collect missing transitive dependencies by checking if supertypes can be resolved.
+  // When FIR loads a class from bytecode (e.g., from a stub JAR), it includes references
+  // to that class's supertypes. If those supertypes are not on the classpath (because
+  // they're transitive dependencies not included in the stub JAR), we detect them here.
+  private fun collectMissingTypesFromFir(analysisResults: FrontendOutputCompat): Set<ClassId> {
+    val missingTypes = mutableSetOf<ClassId>()
+
+    for (output in analysisResults.outputs) {
+      val session = output.session
+
+      for (firFile in output.fir) {
+        firFile.accept(MissingTypeCollectorVisitor(session, missingTypes))
+      }
+    }
+
+    return missingTypes
+  }
+
+  // Visitor that walks FIR and checks if all referenced types can be resolved,
+  // including the entire supertype hierarchy of dependency classes
+  @OptIn(SymbolInternals::class)
+  private class MissingTypeCollectorVisitor(
+      private val session: FirSession,
+      private val missingTypes: MutableSet<ClassId>,
+  ) : FirNamedFunctionVisitorCompat() {
+
+    // Track already-checked classes to avoid infinite recursion
+    private val checkedClasses = mutableSetOf<ClassId>()
+
+    override fun visitElement(element: FirElement) {
+      // Only visit declarations, not expressions/bodies (avoid deep recursion)
+      // We only care about type references in declarations
+    }
+
+    override fun visitFile(file: org.jetbrains.kotlin.fir.declarations.FirFile) {
+      // Visit top-level declarations
+      for (declaration in file.declarations) {
+        declaration.accept(this)
+      }
+    }
+
+    override fun visitRegularClass(regularClass: FirRegularClass) {
+      // Check if all supertypes can be resolved, including their supertypes.
+      // Use isFromDependencyChain=true because if a source class's supertype can't be
+      // resolved anywhere (not in deps, not in sources), it's a missing transitive
+      // dependency that will crash FIR-to-IR fake override building.
+      for (superTypeRef in regularClass.superTypeRefs) {
+        checkTypeResolvableRecursively(superTypeRef.coneType, isFromDependencyChain = true)
+      }
+      // Visit nested declarations (but not bodies)
+      for (declaration in regularClass.declarations) {
+        declaration.accept(this)
+      }
+    }
+
+    override fun visitNamedFunctionCompat(namedFunction: FirNamedFunctionCompat) {
+      // Check return type - these are from source, so start with isFromDependencyChain=false
+      checkTypeResolvableRecursively(
+          namedFunction.returnTypeRef.coneType,
+          isFromDependencyChain = false,
+      )
+
+      // Check parameter types
+      for (valueParameter in namedFunction.valueParameters) {
+        checkTypeResolvableRecursively(
+            valueParameter.returnTypeRef.coneType,
+            isFromDependencyChain = false,
+        )
+      }
+      // Do NOT call super - we don't need to visit function bodies
+    }
+
+    override fun visitProperty(property: org.jetbrains.kotlin.fir.declarations.FirProperty) {
+      // Check property type
+      checkTypeResolvableRecursively(property.returnTypeRef.coneType, isFromDependencyChain = false)
+      // Do NOT call super - we don't need to visit property initializers
+    }
+
+    override fun visitConstructor(
+        constructor: org.jetbrains.kotlin.fir.declarations.FirConstructor,
+    ) {
+      // Check parameter types
+      for (valueParameter in constructor.valueParameters) {
+        checkTypeResolvableRecursively(
+            valueParameter.returnTypeRef.coneType,
+            isFromDependencyChain = false,
+        )
+      }
+      // Do NOT call super - we don't need to visit constructor bodies
+    }
+
+    override fun visitTypeAlias(typeAlias: FirTypeAlias) {
+      // Check that the expanded type can be resolved - type aliases serialize
+      // expandedType into metadata, and if it references a missing transitive
+      // dependency the ABI jar will have corrupt TypeAlias protobuf
+      checkTypeResolvableRecursively(
+          typeAlias.expandedTypeRef.coneType,
+          isFromDependencyChain = false,
+      )
+    }
+
+    // Check if a type can be resolved via the symbol provider, and recursively
+    // check all supertypes of resolved classes. This is necessary because stub JARs
+    // may contain classes that extend other classes not in the stub JAR.
+    // The isFromDependencyChain parameter tracks whether we're checking a type that
+    // was found in the supertype chain of a dependency class.
+    private fun checkTypeResolvableRecursively(
+        type: org.jetbrains.kotlin.fir.types.ConeKotlinType,
+        isFromDependencyChain: Boolean = false,
+    ) {
+      when (type) {
+        is org.jetbrains.kotlin.fir.types.ConeErrorType -> {
+          // FIR couldn't resolve this type - it represents a missing dependency.
+          // ConeErrorType extends ConeClassLikeType, so we must check it first.
+          // Extract the original class ID and add to missing types unconditionally,
+          // since an error type always indicates something is unresolvable.
+          try {
+            val classId = type.lookupTag.classId
+            if (
+                !classId.isLocal &&
+                    !classId.packageFqName.asString().startsWith("kotlin") &&
+                    !classId.packageFqName.asString().startsWith("java")
+            ) {
+              missingTypes.add(classId)
+            }
+          } catch (_: Exception) {
+            // If we can't extract the classId from the error type, skip it.
+            // The error will surface later during FIR-to-IR conversion.
+          }
+        }
+        is org.jetbrains.kotlin.fir.types.ConeClassLikeType -> {
+          val classId = type.lookupTag.classId
+
+          // Skip if already checked
+          if (classId in checkedClasses) return
+          checkedClasses.add(classId)
+
+          // Skip standard library classes - they're always available
+          if (
+              classId.packageFqName.asString().startsWith("kotlin") ||
+                  classId.packageFqName.asString().startsWith("java")
+          ) {
+            return
+          }
+
+          // Skip local classes (anonymous classes, lambdas, object expressions)
+          // These are local to the source file and can't be missing transitive dependencies.
+          // Also, the symbol provider throws an error when trying to look them up.
+          if (classId.isLocal) {
+            return
+          }
+
+          // Try to resolve the class symbol from dependencies
+          val depSymbol = session.dependenciesSymbolProvider.getClassLikeSymbolByClassId(classId)
+          if (depSymbol == null) {
+            // Not in dependencies - could be a source class (Kotlin or Java)
+            // Try to resolve from all symbol providers (includes Java sources)
+            val sourceSymbol = session.symbolProvider.getClassLikeSymbolByClassId(classId)
+            if (sourceSymbol == null) {
+              // Cannot be resolved at all
+              if (isFromDependencyChain) {
+                // This class is in the supertype chain of a dependency or source class
+                // but cannot be resolved - it's a missing transitive dependency.
+                // This includes nested/inner classes that FIR's symbol provider cannot
+                // resolve by ClassId even when present in dependency JARs. We add ALL
+                // unresolvable classes so their supertype references get stripped from
+                // FIR before FIR-to-IR conversion (which would also fail to find them).
+                missingTypes.add(classId)
+              }
+              return
+            } else {
+              // Found in sources (Kotlin or Java) - recursively check its supertypes
+              // When checking source class supertypes, we're now in a dependency chain
+              // because any supertype not in sources must come from dependencies
+              when (val firDecl = sourceSymbol.fir) {
+                is FirRegularClass -> {
+                  for (superTypeRef in firDecl.superTypeRefs) {
+                    checkTypeResolvableRecursively(
+                        superTypeRef.coneType,
+                        isFromDependencyChain = true,
+                    )
+                  }
+                }
+                is FirTypeAlias -> {
+                  // Follow the expanded type of the type alias - any expanded type
+                  // not in sources must come from dependencies
+                  checkTypeResolvableRecursively(
+                      firDecl.expandedTypeRef.coneType,
+                      isFromDependencyChain = true,
+                  )
+                }
+                else -> {}
+              }
+            }
+          } else {
+            // Class IS resolvable from dependencies - now recursively check ITS supertypes
+            // These are now definitely from the dependency chain
+            when (val firDecl = depSymbol.fir) {
+              is FirRegularClass -> {
+                for (superTypeRef in firDecl.superTypeRefs) {
+                  checkTypeResolvableRecursively(
+                      superTypeRef.coneType,
+                      isFromDependencyChain = true,
+                  )
+                }
+              }
+              is FirTypeAlias -> {
+                // Follow the expanded type of the type alias - it may reference
+                // a transitive dependency not on the source-only ABI classpath
+                checkTypeResolvableRecursively(
+                    firDecl.expandedTypeRef.coneType,
+                    isFromDependencyChain = true,
+                )
+              }
+              else -> {}
+            }
+          }
+        }
+        is org.jetbrains.kotlin.fir.types.ConeTypeParameterType -> {
+          // Type parameters are always resolvable
+        }
+        is org.jetbrains.kotlin.fir.types.ConeFlexibleType -> {
+          // Check both bounds
+          checkTypeResolvableRecursively(type.lowerBound, isFromDependencyChain)
+          checkTypeResolvableRecursively(type.upperBound, isFromDependencyChain)
+        }
+        else -> {
+          // Other types don't need checking
+        }
+      }
+    }
+  }
+
+  // Strip supertypes that reference missing transitive dependencies from FIR classes.
+  // This walks source FIR classes and follows their supertype chains into dependency
+  // classes, removing any supertype reference whose ClassId is in the missing set.
+  // This is done BEFORE FIR-to-IR conversion to prevent crashes during fake override
+  // building (Fir2IrDeclarationStorage.findContainingIrClassSymbol).
+  @OptIn(SymbolInternals::class)
+  private fun stripUnresolvableSupertypesFromFir(
+      analysisResults: FrontendOutputCompat,
+      missingTypes: Set<ClassId>,
+  ) {
+    val visited = mutableSetOf<ClassId>()
+
+    fun stripFromClassRecursively(firClass: FirRegularClass, session: FirSession) {
+      val classId = firClass.symbol.classId
+      if (classId in visited) return
+      visited.add(classId)
+
+      // Strip supertypes that reference missing types
+      val toRemove =
+          firClass.superTypeRefs.filter { typeRef ->
+            val coneType =
+                (typeRef as? FirResolvedTypeRef)?.coneType as? ConeClassLikeType
+                    ?: return@filter false
+            coneType.lookupTag.classId in missingTypes
+          }
+      if (toRemove.isNotEmpty()) {
+        val filtered = firClass.superTypeRefs - toRemove.toSet()
+        try {
+          // Works for standard FirRegularClass (Kotlin classes from bytecode or source)
+          firClass.replaceSuperTypeRefs(filtered)
+        } catch (_: IllegalStateException) {
+          // FirJavaClass doesn't support replaceSuperTypeRefs because superTypeRefs
+          // is a lazy delegate. Use reflection to replace the lazy delegate's value.
+          try {
+            val delegateField = firClass.javaClass.getDeclaredField("superTypeRefs\$delegate")
+            delegateField.isAccessible = true
+            delegateField.set(firClass, lazyOf(filtered))
+          } catch (_: Exception) {
+            // If reflection fails, skip - the error will surface during FIR-to-IR
+          }
+        }
+      }
+
+      // Recursively process remaining supertypes' FIR classes (including dependency classes)
+      for (superTypeRef in firClass.superTypeRefs) {
+        val coneType =
+            (superTypeRef as? FirResolvedTypeRef)?.coneType as? ConeClassLikeType ?: continue
+        val superClassId = coneType.lookupTag.classId
+        if (
+            superClassId.packageFqName.asString().startsWith("kotlin") ||
+                superClassId.packageFqName.asString().startsWith("java")
+        ) {
+          continue
+        }
+        val superSymbol =
+            session.symbolProvider.getClassLikeSymbolByClassId(superClassId) ?: continue
+        val superClass = superSymbol.fir as? FirRegularClass ?: continue
+        stripFromClassRecursively(superClass, session)
+      }
+    }
+
+    for (output in analysisResults.outputs) {
+      val session = output.session
+
+      for (firFile in output.fir) {
+        firFile.accept(
+            object : FirDefaultVisitorVoid() {
+              override fun visitElement(element: FirElement) {}
+
+              override fun visitFile(file: org.jetbrains.kotlin.fir.declarations.FirFile) {
+                for (declaration in file.declarations) {
+                  declaration.accept(this)
+                }
+              }
+
+              override fun visitRegularClass(regularClass: FirRegularClass) {
+                stripFromClassRecursively(regularClass, session)
+                for (declaration in regularClass.declarations) {
+                  declaration.accept(this)
+                }
+              }
+            },
+        )
+      }
+    }
+  }
+
+  fun convertAnalyzedFirToIr(
+      configuration: CompilerConfiguration,
+      targetId: TargetId,
+      analysisResults: FrontendOutputCompat,
+      environment: ModuleCompilerEnvironmentCompat,
+      sourceFiles: List<KtFile>,
+      project: Project,
+  ): ModuleCompilerIrBackendInputCompat {
+    val extensions = JvmFir2IrExtensions(configuration, JvmIrDeserializerImpl())
+    val composeAbiEnabled =
+        configuration.get(K2JvmAbiConfigurationKeys.ENABLE_COMPOSE_ABI_EMULATION) == true
+    val allIrExtensions = buildList {
+      // Compose ABI emulation runs before the IR sanitizer so that any emulated
+      // declarations are present when non-ABI content is stripped.
+      if (composeAbiEnabled) {
+        add(pipeline.composeAbi.createExtension())
+      }
+      add(ParcelizeAbiEmulationExtension())
+      add(pipeline.irSanitizer.createExtension(sourceFiles))
+    }
+
+    val (moduleFragment, components, pluginContext, irActualizedResult, _, symbolTable) =
+        analysisResults.convertToIrAndActualizeForJvmCompat(
+            extensions,
+            configuration,
+            environment.diagnosticsReporter,
+            allIrExtensions,
+        )
+
+    return ModuleCompilerIrBackendInputCompat(
+        targetId,
+        configuration,
+        extensions,
+        moduleFragment,
+        components,
+        pluginContext,
+        irActualizedResult,
+        symbolTable,
+    )
+  }
+
+  // A backend entry point for Kosabi.
+  private fun runBackendForKosabi(
+      messageCollector: MessageCollector,
+      projectEnvironment: VfsBasedProjectEnvironment,
+      configuration: CompilerConfiguration,
+      module: Module,
+      analysisResults: FrontendOutputCompat,
+      sourceFiles: List<KtFile>,
+  ): ModuleCompilerOutputCompat {
+    val cleanDiagnosticReporter = createPendingReporterCompat(messageCollector)
+    val compilerEnvironment =
+        ModuleCompilerEnvironmentCompat(projectEnvironment, cleanDiagnosticReporter)
+
+    // Phase 1: FIR pre-IR cleanup
+    pipeline.firMetadataSanitizer.cleanupFirTree(analysisResults)
+
+    // Phase 2: FIR-to-IR conversion (includes IR sanitizer as extension)
+
+    val irInput = convertAnalyzedFirToIr(
+        configuration,
+        TargetId(module),
+        analysisResults,
+        compilerEnvironment,
+        sourceFiles,
+        projectEnvironment.project,
+    )
+
+    // Phase 3: FIR metadata post-IR cleanup
+    val firSession = analysisResults.outputs.last().session
+    pipeline.firMetadataSanitizer.cleanupFirMetadataSources(irInput.irModuleFragment, firSession)
+
+    // Phase 4: Code generation
+    val result = generateCodeFromIrCompat(irInput, compilerEnvironment)
+
+    // Write bytecode from generationState.factory to disk.
+    // Apply bytecode post-processing (strip @Throws annotations and private metadata)
+    // in-memory before writing to avoid a separate read-back pass.
+    val outputFiles =
+        result.classFileFactoryCompat.asList().map { outputFile ->
+          val originalBytes = outputFile.asByteArray()
+          val bytes =
+              if (outputFile.relativePath.endsWith(".class")) {
+                pipeline.bytecodeSanitizer.transform(originalBytes)
+              } else {
+                originalBytes
+              }
+          AbiValidationOutputFile(outputFile.relativePath, bytes)
+        }
+    val outputDir = configuration[JVMConfigurationKeys.OUTPUT_DIRECTORY]
+    if (outputDir != null) {
+      outputFiles.forEach { outputFile ->
+        val file = File(outputDir, outputFile.relativePath)
+        file.parentFile?.mkdirs()
+        file.writeBytes(outputFile.bytes)
+      }
+    }
+
+    // Phase 5: Validation. Needs the written output files and the classpath, so it runs after
+    // code generation rather than before it.
+    pipeline.validator.validate(
+        irInput.irModuleFragment,
+        messageCollector,
+        AbiRepairPolicy.parse(configuration.get(K2JvmAbiConfigurationKeys.ABI_VALIDATION_MODE)),
+        AbiValidationInputs(outputFiles, configuration.jvmClasspathRoots),
+    )
+
+    // Generate .kotlin_module file
+    generateKotlinModuleFile(irInput.irModuleFragment, module.getModuleName(), configuration)
+
+    return result
+  }
+
+  // Generate the .kotlin_module file manually.
+  // The standard generateCodeFromIr may not produce a complete .kotlin_module file
+  // for source-only ABI generation. We scan the IR for file facade classes (*Kt.class)
+  // and build the module metadata ourselves.
+  private fun generateKotlinModuleFile(
+      moduleFragment: IrModuleFragment,
+      moduleName: String,
+      configuration: CompilerConfiguration,
+  ) {
+    val outputDir = configuration[JVMConfigurationKeys.OUTPUT_DIRECTORY] ?: return
+
+    // Collect all packages that have Kotlin IR files
+    val allKotlinPackages = mutableSetOf<String>()
+    // Collect package-to-file-facade mappings by scanning IR for *Kt classes
+    val packageToFileFacades = mutableMapOf<String, MutableSet<String>>()
+
+    // Iterate through all IR files to:
+    // 1. Track all packages (for files with only objects/classes)
+    // 2. Find file facade classes (classes for top-level functions)
+    for (irFile in moduleFragment.files) {
+      val packageFqName = irFile.packageFqName.asString()
+      allKotlinPackages.add(packageFqName)
+
+      for (decl in irFile.declarations) {
+        if (decl is IrClass && decl.isFileClass) {
+          // File facade classes are synthetic classes generated by the compiler to hold
+          // top-level declarations. They are identified by their IrDeclarationOrigin
+          // (FILE_CLASS, SYNTHETIC_FILE_CLASS, or JVM_MULTIFILE_CLASS).
+          //
+          // Only actual file facades may be listed as package parts in the kotlin_module.
+          // Listing regular classes causes the consumer to read their Class protobuf as
+          // a Package protobuf, where field 5 (TypeParameter) is misinterpreted as
+          // TypeAlias — producing corrupt entries with no expandedType that crash with
+          // "No expandedType in ProtoBuf.TypeAlias".
+          packageToFileFacades.getOrPut(packageFqName) { mutableSetOf() }.add(decl.name.asString())
+        }
+      }
+    }
+
+    // Generate .kotlin_module if there are any Kotlin packages
+    // even if they don't have file facades (e.g., files with only objects/classes)
+    if (allKotlinPackages.isEmpty()) return
+
+    // Build the Module protobuf
+    val moduleBuilder = JvmModuleProtoBuf.Module.newBuilder()
+
+    // Iterate over all packages (including those without file facades)
+    for (packageFqName in allKotlinPackages.sorted()) {
+      val packagePartsBuilder = JvmModuleProtoBuf.PackageParts.newBuilder()
+      packagePartsBuilder.packageFqName = packageFqName
+
+      // Add file facades if this package has any
+      val fileFacades = packageToFileFacades[packageFqName]
+      if (fileFacades != null) {
+        for (fileFacade in fileFacades.sorted()) {
+          packagePartsBuilder.addShortClassName(fileFacade)
+        }
+      }
+
+      moduleBuilder.addPackageParts(packagePartsBuilder.build())
+    }
+
+    val moduleProto = moduleBuilder.build()
+
+    // Serialize the module
+    val versionArray = currentMetadataVersionArray()
+    // 4KB initial buffer - aligns with memory page size and is sufficient for most .kotlin_module
+    // files
+    val baos = ByteArrayOutputStream(4096)
+    val out = DataOutputStream(baos)
+    out.writeInt(versionArray.size)
+    versionArray.forEach { number -> out.writeInt(number) }
+    // Write flags for Kotlin 1.4+
+    out.writeInt(0)
+    moduleProto.writeTo(out)
+    out.flush()
+
+    // Write to META-INF/<moduleName>.kotlin_module
+    val metaInfDir = File(outputDir, "META-INF")
+    metaInfDir.mkdirs()
+    val moduleFile = File(metaInfDir, "$moduleName.kotlin_module")
+    moduleFile.writeBytes(baos.toByteArray())
+  }
+
+  // get all the source files from the source roots and allows the caller to process them
+  fun List<KotlinSourceRoot>.forAllFiles(
+      configuration: CompilerConfiguration,
+      project: Project,
+      reportLocation: CompilerMessageLocation? = null,
+      body: (VirtualFile, Boolean, moduleName: String?) -> Unit,
+  ) {
+    val localFileSystem =
+        VirtualFileManager.getInstance().getFileSystem(StandardFileSystems.FILE_PROTOCOL)
+
+    val processedFiles = mutableSetOf<VirtualFile>()
+
+    val virtualFileCreator = PreprocessedFileCreator(project)
+
+    var pluginsConfigured = false
+    fun ensurePluginsConfigured() {
+      if (!pluginsConfigured) {
+        for (extension in CompilerConfigurationExtension.getInstances(project)) {
+          extension.updateFileRegistry()
+        }
+        pluginsConfigured = true
+      }
+    }
+
+    for ((sourceRootPath, isCommon, hmppModuleName) in this) {
+      val sourceRoot = File(sourceRootPath)
+      val vFile = localFileSystem.findFileByPath(sourceRoot.normalize().path)
+      if (vFile == null) {
+        val message = "Source file or directory not found: $sourceRootPath"
+
+        val buildFilePath = configuration.get(JVMConfigurationKeys.MODULE_XML_FILE)
+        if (buildFilePath != null && Logger.isInitialized()) {
+          Logger.getInstance(KotlinCoreEnvironment::class.java)
+              .warn(
+                  "$message\n\nbuild file path: $buildFilePath\ncontent:\n${buildFilePath.readText()}",
+              )
+        }
+
+        configuration.report(CompilerMessageSeverity.ERROR, message, reportLocation)
+        continue
+      }
+
+      if (!vFile.isDirectory && vFile.extension != KotlinFileType.EXTENSION) {
+        ensurePluginsConfigured()
+        if (vFile.fileType != KotlinFileType.INSTANCE) {
+          configuration.report(
+              CompilerMessageSeverity.ERROR,
+              "Source entry is not a Kotlin file: $sourceRootPath",
+              reportLocation,
+          )
+          continue
+        }
+      }
+
+      for (file in sourceRoot.walkTopDown()) {
+        if (!file.isFile) continue
+
+        val virtualFile: VirtualFile? =
+            localFileSystem.findFileByPath(file.absoluteFile.normalize().path)?.let {
+              virtualFileCreator.create(it)
+            }
+        if (virtualFile != null) {
+          val hasNotBeenProcessedBefore = processedFiles.add(virtualFile)
+          if (!hasNotBeenProcessedBefore) continue
+          if (virtualFile.extension != KotlinFileType.EXTENSION) {
+            ensurePluginsConfigured()
+          }
+          if (
+              virtualFile.extension == KotlinFileType.EXTENSION ||
+                  virtualFile.fileType == KotlinFileType.INSTANCE
+          ) {
+            body(virtualFile, isCommon, hmppModuleName)
+          }
+        }
+      }
+    }
+  }
+
+  // get all the source files from the source roots and matches them with corresponding PSI
+  fun createSourceFilesFromSourceRoots(
+      configuration: CompilerConfiguration,
+      project: Project,
+      sourceRoots: List<KotlinSourceRoot>,
+      reportLocation: CompilerMessageLocation? = null,
+  ): MutableList<KtFile> {
+    val psiManager = PsiManager.getInstance(project)
+    val result = mutableListOf<KtFile>()
+    sourceRoots.forAllFiles(configuration, project, reportLocation) {
+        virtualFile,
+        isCommon,
+        moduleName ->
+      psiManager.findFile(virtualFile)?.let {
+        if (it is KtFile) {
+          it.isCommonSource = isCommon
+          if (moduleName != null) {
+            it.hmppModuleName = moduleName
+          }
+          result.add(it)
+        }
+      }
+    }
+    return result
+  }
+
+  /**
+   * A place where a constant is passed to an annotation parameter.
+   *
+   * The parameter's declared type is the only remaining evidence of a missing constant's type once
+   * the declaring class is off the classpath, so it is captured alongside the expression text.
+   */
+  private data class ConstUsageSite(
+      val expressionText: String,
+      val annotationShortName: String?,
+      val parameterName: String?,
+      val parameterIndex: Int,
+  )
+
+  private class MissingConstantsVisitor(
+      private val usedConstants: MutableSet<String>,
+      private val usageSites: MutableList<ConstUsageSite>,
+  ) : KtTreeVisitorVoid() {
+    override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) {
+      val annotationShortName = annotationEntry.shortName?.asString()
+      // Use getArgumentExpression()?.text to get just the value, not the parameter name
+      // For @Annotation(param = VALUE), we want "VALUE", not "param = VALUE"
+      // For array expressions like [A, B], extract individual elements
+      annotationEntry.valueArgumentList?.arguments?.forEachIndexed { index, argument ->
+        val expressionText = argument.getArgumentExpression()?.text ?: return@forEachIndexed
+        val parameterName = argument.getArgumentName()?.asName?.asString()
+        fun record(text: String) {
+          usedConstants.add(text)
+          usageSites.add(ConstUsageSite(text, annotationShortName, parameterName, index))
+        }
+        if (expressionText.startsWith("[") && expressionText.endsWith("]")) {
+          // Array expression: parse and extract individual elements
+          val arrayContent = expressionText.substring(1, expressionText.length - 1).trim()
+          if (arrayContent.isNotEmpty()) {
+            // Simple comma split - for annotation arguments, we don't expect complex nesting
+            arrayContent.split(",").forEach { element ->
+              val trimmed = element.trim()
+              if (trimmed.isNotEmpty()) {
+                record(trimmed)
+              }
+            }
+          }
+        } else {
+          // Regular expression: add as-is
+          record(expressionText)
+        }
+      }
+      return super.visitAnnotationEntry(annotationEntry)
+    }
+  }
+
+  /**
+   * Resolves the declared type of the annotation parameter [site] is passed to.
+   *
+   * This runs before `buildFirFromKtFiles`, so annotations declared in the module being compiled
+   * are only available as PSI while annotations from dependencies are only available as FIR; both
+   * are tried. Returns null whenever the answer is not certain - a wrong type here would be exactly
+   * the defect this exists to fix.
+   */
+  private fun resolveAnnotationParameterType(
+      site: ConstUsageSite,
+      sourceFile: KtFile,
+      sourceFiles: List<KtFile>,
+      session: FirSession,
+  ): ConstTypeHint? {
+    val annotationShortName = site.annotationShortName ?: return null
+
+    val importedFqName =
+        sourceFile.importDirectives
+            .mapNotNull { it.importedFqName }
+            .firstOrNull { it.shortName().asString() == annotationShortName }
+    val candidates = listOfNotNull(
+        importedFqName,
+        sourceFile.packageFqName.child(Name.identifier(annotationShortName)),
+    )
+
+    // Recovering the type is best-effort: without it the old assumed-String behaviour still
+    // applies. It must therefore never be able to turn a working compilation red, which querying
+    // half-resolved declarations at this stage otherwise can.
+    return try {
+      candidates.firstNotNullOfOrNull { candidate ->
+        annotationParameterTypeFromPsi(candidate, site, sourceFiles)
+            ?: annotationParameterTypeFromFir(candidate, site, session)
+      }
+    } catch (e: Exception) {
+      pipeline.repairLog.recordFailedRepair(
+          annotationShortName,
+          "could not read annotation parameter type: ${e.javaClass.simpleName}: ${e.message}",
+      )
+      null
+    }
+  }
+
+  private fun annotationParameterTypeFromPsi(
+      annotationFqName: FqName,
+      site: ConstUsageSite,
+      sourceFiles: List<KtFile>,
+  ): ConstTypeHint? {
+    val ktClass =
+        sourceFiles
+            .flatMap { it.declarations }
+            .filterIsInstance<KtClass>()
+            .firstOrNull { it.isAnnotation() && it.fqName == annotationFqName } ?: return null
+    val parameters = ktClass.primaryConstructor?.valueParameters ?: return null
+    val parameter =
+        if (site.parameterName != null) {
+          parameters.firstOrNull { it.name == site.parameterName }
+        } else {
+          parameters.getOrNull(site.parameterIndex)
+        } ?: return null
+    return constTypeHintFromTypeText(parameter.typeReference?.text)
+  }
+
+  /**
+   * This runs before source declarations exist in FIR, so it deliberately consults only
+   * `dependenciesSymbolProvider` - the same provider the surrounding missing-constant logic uses.
+   * Reaching into the full symbol provider here resolves source and Java declarations too early.
+   */
+  @OptIn(SymbolInternals::class)
+  private fun annotationParameterTypeFromFir(
+      annotationFqName: FqName,
+      site: ConstUsageSite,
+      session: FirSession,
+  ): ConstTypeHint? {
+    val classSymbol =
+        session.dependenciesSymbolProvider.getClassLikeSymbolByClassId(
+            ClassId.topLevel(annotationFqName),
+        ) as? FirClassSymbol<*> ?: return null
+    val firClass = classSymbol.fir as? FirRegularClass ?: return null
+    if (firClass.classKind != ClassKind.ANNOTATION_CLASS) return null
+    val primaryConstructor =
+        firClass.declarations.filterIsInstance<FirConstructor>().firstOrNull { it.isPrimary }
+            ?: return null
+    val parameter =
+        if (site.parameterName != null) {
+          primaryConstructor.valueParameters.firstOrNull {
+            it.name.asString() == site.parameterName
+          }
+        } else {
+          primaryConstructor.valueParameters.getOrNull(site.parameterIndex)
+        } ?: return null
+    // Java-declared annotations carry a FirJavaTypeRef at this point; asking such a ref for its
+    // cone type throws. No type is better than a crash, and better than a guessed one.
+    val typeRef = parameter.returnTypeRef as? FirResolvedTypeRef ?: return null
+    return constTypeHintFromConeType(typeRef.coneType)
+  }
+
+  // Collect missing constants from source files by analyzing imports
+  private fun collectMissingConstantsFromSourceFiles(
+      sourceFiles: List<KtFile>,
+      session: FirSession,
+      state: AbiGenState,
+  ): Map<ClassId, Set<String>> {
+    val missingConstants = mutableMapOf<ClassId, MutableSet<String>>()
+
+    // Collect all packages that are defined in the source files being compiled
+    // to exclude constants from those packages (they're not "missing")
+    val sourcePackages = sourceFiles.map { it.packageFqName }.toSet()
+
+    for (sourceFile in sourceFiles) {
+      val usedConstants = mutableSetOf<String>()
+      val usageSites = mutableListOf<ConstUsageSite>()
+      sourceFile.accept(MissingConstantsVisitor(usedConstants, usageSites))
+
+      // Records the annotation-parameter type for a constant we are about to synthesise. Two
+      // annotations disagreeing about the type means the evidence is unusable, so the constant is
+      // marked ambiguous and falls back rather than picking one arbitrarily.
+      fun recordTypeHint(classId: ClassId, propertyName: String, usage: String) {
+        val key = constHintKey(classId, propertyName)
+        if (key in state.ambiguousConstantTypeHints) return
+        val hint =
+            usageSites
+                .asSequence()
+                .filter { it.expressionText == usage }
+                .mapNotNull { resolveAnnotationParameterType(it, sourceFile, sourceFiles, session) }
+                .firstOrNull() ?: return
+        val existing = state.constantTypeHints[key]
+        if (existing == null) {
+          state.constantTypeHints[key] = hint
+        } else if (existing != hint) {
+          state.constantTypeHints.remove(key)
+          state.ambiguousConstantTypeHints.add(key)
+        }
+      }
+
+      for (importDirective in sourceFile.importDirectives) {
+        val importPath = importDirective.importedFqName ?: continue
+        val segments = importPath.pathSegments()
+        if (segments.size < 2) continue
+
+        val importedName = importPath.shortNameOrSpecial().asString()
+
+        // Check if this import is used in annotations
+        // usedConstants contains things like "THREAD_TAG" or "TestConstants.THREAD_TAG"
+        val matchingUsages = usedConstants.filter { it.contains(importedName) }
+        if (matchingUsages.isEmpty()) continue
+
+        // Determine if this is a class import or a constant import
+        // For class imports like "import pkg.Class", usages will be "Class.PROPERTY"
+        // For constant imports like "import pkg.Class.CONSTANT", usages will be "CONSTANT"
+        for (usage in matchingUsages) {
+          if (usage.startsWith("$importedName.")) {
+            // Class import: import pkg.Class, used as Class.PROPERTY
+            // Extract the property name from the usage
+            val propertyPath = usage.removePrefix("$importedName.")
+            // propertyPath could be "PROPERTY" or "Api.PROPERTY" (nested class)
+            val pathParts = propertyPath.split(".")
+            val propertyName = pathParts.last()
+
+            // Build full segments including nested class parts
+            // For import other_package.enums.VersionCodes, used as VersionCodes.Api.O:
+            //   segments = [other_package, enums, VersionCodes]
+            //   pathParts = [Api, O]
+            //   nestedClassParts = [Api] (all except the property name)
+            //   fullSegments = [other_package, enums, VersionCodes, Api]
+            val nestedClassParts = pathParts.dropLast(1)
+            val fullSegments = segments + nestedClassParts.map { Name.identifier(it) }
+
+            // For class imports, the full import path IS the class
+            val classId = findClassIdForImportWithProperty(
+                fullSegments,
+                propertyName,
+                session,
+                sourcePackages,
+                segments.size,
+            )
+            if (classId != null) {
+              missingConstants.getOrPut(classId) { mutableSetOf() }.add(propertyName)
+              recordTypeHint(classId, propertyName, usage)
+            }
+          } else if (usage == importedName) {
+            // Constant import: import pkg.Class.CONSTANT, used as CONSTANT
+            val classSegments = segments.dropLast(1)
+            val classId = findClassIdForImportWithProperty(
+                classSegments,
+                importedName,
+                session,
+                sourcePackages,
+                classSegments.size,
+            )
+            if (classId != null) {
+              missingConstants.getOrPut(classId) { mutableSetOf() }.add(importedName)
+              recordTypeHint(classId, importedName, usage)
+            }
+          }
+        }
+      }
+    }
+
+    return missingConstants
+  }
+
+  // Find the correct ClassId for an import path
+  // For import other_package.constants.TestConstants.THREAD_TAG, segments would be
+  // [other_package, constants, TestConstants] and we want ClassId(other_package.constants,
+  // TestConstants)
+  // Returns null if the class (or any parent class in the path) already exists in dependencies AND
+  // has the property or enum entry
+  @OptIn(SymbolInternals::class)
+  private fun findClassIdForImportWithProperty(
+      segments: List<Name>,
+      propertyName: String,
+      session: FirSession,
+      sourcePackages: Set<FqName>,
+      originalImportLength: Int,
+  ): ClassId? {
+    if (segments.size < 2) return null
+
+    // Try different package/class splits to find if any class in the path exists in dependencies
+    // For import like androidx.annotation.VisibleForTesting.Companion.PROTECTED (segments =
+    // [androidx, annotation, VisibleForTesting, Companion])
+    // We need to try:
+    // - Package: androidx, Class: annotation (unlikely)
+    // - Package: androidx.annotation, Class: VisibleForTesting (likely exists!)
+    // - Package: androidx.annotation.VisibleForTesting, Class: Companion (won't exist as top-level)
+    for (splitPoint in 1 until segments.size) {
+      val packageFqName = FqName.fromSegments(segments.take(splitPoint).map { it.asString() })
+      val classNameParts = segments.drop(splitPoint)
+
+      // Skip if this is from a package being compiled
+      if (packageFqName in sourcePackages) {
+        continue
+      }
+
+      // Build the ClassId - for nested classes like VisibleForTesting.Companion,
+      // we need to use the proper nested class syntax
+      val topLevelClassName = classNameParts.first()
+      val classId =
+          if (classNameParts.size == 1) {
+            ClassId(packageFqName, topLevelClassName)
+          } else {
+            // For nested classes, create ClassId with nested class path
+            ClassId(packageFqName, FqName.fromSegments(classNameParts.map { it.asString() }), false)
+          }
+
+      val classSymbol = session.dependenciesSymbolProvider.getClassLikeSymbolByClassId(classId)
+      if (classSymbol != null) {
+        val firClassSymbol = classSymbol as? FirClassSymbol<*>
+        if (firClassSymbol != null) {
+          // Check for property with matching name
+          // For const vals, also verify the initializer is resolvable (not an error expression)
+          // Source-only ABI JARs may have const vals with stripped initializers
+          val hasResolvableProperty =
+              firClassSymbol.declarationSymbols.filterIsInstance<FirPropertySymbol>().any { prop ->
+                if (prop.name.asString() != propertyName) {
+                  return@any false
+                }
+
+                // If it's not a const, it's usable as-is
+                if (!prop.isConst) {
+                  return@any true
+                }
+
+                // For const vals from library/bytecode dependencies, trust they have valid values
+                // even if the initializer is not available in FIR (bytecode doesn't preserve
+                // initializer expressions, but the ConstantValue is accessible at runtime)
+                if (prop.fir.isFromLibrary) {
+                  return@any true
+                }
+
+                // For source-compiled const vals, check if we can actually resolve the initializer
+                // Const vals from source-only ABI JARs may exist but have no evaluable value
+                val initializer = prop.fir.initializer
+                initializer != null &&
+                    !pipeline.firMetadataSanitizer.hasErrorExpressionRecursive(initializer)
+              }
+
+          // Check for any callable with matching name (covers Java static fields)
+          // Exclude FirPropertySymbol since those are already handled by hasResolvableProperty
+          // above.
+          // Properties with non-resolvable initializers (like TODO()) need stubs, so we must not
+          // let hasCallable short-circuit the check.
+          val hasCallable =
+              firClassSymbol.declarationSymbols.filterIsInstance<FirCallableSymbol<*>>().any {
+                it.name.asString() == propertyName && it !is FirPropertySymbol
+              }
+
+          // Also check for enum entry with matching name
+          val firRegularClass = firClassSymbol.fir as? FirRegularClass
+          val hasEnumEntry =
+              firRegularClass != null &&
+                  firRegularClass.classKind == ClassKind.ENUM_CLASS &&
+                  firClassSymbol.declarationSymbols.filterIsInstance<FirEnumEntrySymbol>().any {
+                    it.name.asString() == propertyName
+                  }
+
+          // For annotation classes, constants are Java static fields which may not be
+          // represented as FirPropertySymbol. Trust that the constant exists if the
+          // annotation class is on the classpath.
+          val isAnnotationClass =
+              firRegularClass != null && firRegularClass.classKind == ClassKind.ANNOTATION_CLASS
+
+          if (hasResolvableProperty || hasCallable || hasEnumEntry || isAnnotationClass) {
+            // Found a class in dependencies that has the member - no stub needed
+            return null
+          }
+
+          // Check companion object for const vals
+          // Companion object const vals are accessible as Class.PROPERTY in Kotlin bytecode,
+          // but from source-only ABI JARs, the initializer values may be stripped.
+          // We need to check if the companion has the property AND if it's resolvable.
+          val companionSymbol =
+              firClassSymbol.declarationSymbols.filterIsInstance<FirClassSymbol<*>>().firstOrNull {
+                it.name.asString() == "Companion"
+              }
+          if (companionSymbol != null) {
+            val hasResolvableCompanionProperty =
+                companionSymbol.declarationSymbols.filterIsInstance<FirPropertySymbol>().any { prop
+                  ->
+                  if (prop.name.asString() != propertyName) {
+                    return@any false
+                  }
+
+                  // Non-const properties in companion are usable
+                  if (!prop.isConst) {
+                    return@any true
+                  }
+
+                  // For const vals from library/bytecode dependencies, trust they have valid values
+                  if (prop.fir.isFromLibrary) {
+                    return@any true
+                  }
+
+                  // For source-compiled const vals, check if initializer is resolvable
+                  val initializer = prop.fir.initializer
+                  initializer != null &&
+                      !pipeline.firMetadataSanitizer.hasErrorExpressionRecursive(initializer)
+                }
+            if (hasResolvableCompanionProperty) {
+              // Found resolvable companion property - no stub needed
+              return null
+            }
+          }
+        }
+        // Class exists but doesn't have the property/entry - continue probing
+      }
+    }
+
+    // No class found in dependencies with the property - generate a stub using heuristic
+    // Use originalImportLength to determine package/class split
+    // For import other_package.enums.VersionCodes (originalImportLength=3), used as
+    // VersionCodes.Api.O:
+    //   segments = [other_package, enums, VersionCodes, Api] (length=4, originalImportLength=3)
+    //   packageFqName should be other_package.enums (first originalImportLength-1 segments)
+    //   className should be VersionCodes.Api (remaining segments)
+    val packageFqName =
+        FqName.fromSegments(segments.take(originalImportLength - 1).map { it.asString() })
+    val classNameParts = segments.drop(originalImportLength - 1)
+
+    // Skip if from source package or a class in a source package
+    // For self-imports like "import test.PermissionType.Companion.CONST" with package "test",
+    // packageFqName would be "test.PermissionType" which starts with source package "test".
+    // This indicates the constant is defined in source code, not in dependencies.
+    if (
+        sourcePackages.any { sourcePackage ->
+          packageFqName == sourcePackage ||
+              packageFqName.asString().startsWith(sourcePackage.asString() + ".")
+        }
+    ) {
+      return null
+    }
+
+    // Build the ClassId with potential nested class path
+    val topLevelClassName = classNameParts.first()
+    val baseClassId =
+        if (classNameParts.size == 1) {
+          ClassId(packageFqName, topLevelClassName)
+        } else {
+          // For nested classes, create ClassId with nested class path
+          ClassId(packageFqName, FqName.fromSegments(classNameParts.map { it.asString() }), false)
+        }
+
+    // If the class already exists in dependencies but doesn't have the property,
+    // the property might be in its Companion object. Check if a Companion exists
+    // and if so, generate the stub for the Companion class instead to avoid conflicts.
+    val existingClass = session.dependenciesSymbolProvider.getClassLikeSymbolByClassId(baseClassId)
+    if (existingClass != null) {
+      val companionClassId = baseClassId.createNestedClassId(Name.identifier("Companion"))
+      val existingCompanion =
+          session.dependenciesSymbolProvider.getClassLikeSymbolByClassId(companionClassId)
+      if (existingCompanion != null) {
+        // Companion exists but doesn't have the property - generate stub in Companion
+        return companionClassId
+      }
+      // Class exists but no Companion - can't generate stub without conflict
+      // Return null to avoid generating conflicting class
+      return null
+    }
+
+    return baseClassId
+  }
+
+  // A frontend entry point for Kosabi.
+  // Generates FIR for all the sources in the module.
+  fun runFrontendForKosabi(
+      environment: VfsBasedProjectEnvironment,
+      configuration: CompilerConfiguration,
+      sources: List<KtFile>,
+      module: Module,
+  ): FrontendOutputCompat {
+    return compileSourceFilesToAnalyzedFirViaPsi(
+        sources,
+        module.getModuleName(),
+        module.getFriendPaths(),
+        true,
+        environment,
+        configuration,
+    )!!
+  }
+
+  private fun compileSourceFilesToAnalyzedFirViaPsi(
+      ktFiles: List<KtFile>,
+      rootModuleName: String,
+      friendPaths: List<String>,
+      ignoreErrors: Boolean = false,
+      projectEnvironment: VfsBasedProjectEnvironment,
+      configuration: CompilerConfiguration,
+  ): FrontendOutputCompat? {
+
+    val sourceScope =
+        projectEnvironment.getSearchScopeByPsiFiles(ktFiles) +
+            projectEnvironment.getSearchScopeForProjectJavaSources()
+
+    var librariesScope = projectEnvironment.getSearchScopeForProjectLibraries()
+
+    val providerAndScopeForIncrementalCompilation =
+        createContextForIncrementalCompilation(projectEnvironment, configuration, sourceScope)
+
+    providerAndScopeForIncrementalCompilation?.precompiledBinariesFileScope?.let {
+      librariesScope -= it
+    }
+    val sessionsWithSources = prepareJvmSessionsCompat(
+        ktFiles,
+        rootModuleName,
+        friendPaths,
+        librariesScope,
+        configuration,
+        projectEnvironment,
+        providerAndScopeForIncrementalCompilation,
+    )
+
+    val outputs = sessionsWithSources.map { (session, sources) ->
+      val state = session.jvmAbiGenService.state
+      val missingConstants = collectMissingConstantsFromSourceFiles(sources, session, state)
+      state.missingConstants.putAll(missingConstants)
+      // Skip checkers - ABI generation only needs resolved types, and third-party
+      // plugin checkers (like Litho K2) crash on unresolved references from stubs.
+      val firFiles = session.buildFirFromKtFiles(sources)
+      val (scopeSession, fir) = session.runResolution(firFiles)
+      // Constants are synthesised lazily during resolution, so this is the earliest point at
+      // which the full set is known. Reporting here rather than in ValidationStage keeps the
+      // signal even when a later phase fails.
+      reportFabricatedConstants(state, configuration)
+      moduleFrontendOutputCompat(session, scopeSession, fir)
+    }
+
+    return frontendOutputCompat(outputs)
+  }
+
+  private fun reportFabricatedConstants(state: AbiGenState, configuration: CompilerConfiguration) {
+    if (state.fabricatedConstants.isEmpty()) return
+    pipeline.repairLog.fabricatedConstants.addAll(state.fabricatedConstants)
+
+    val policy =
+        AbiRepairPolicy.parse(configuration.get(K2JvmAbiConfigurationKeys.ABI_VALIDATION_MODE))
+    if (policy == AbiRepairPolicy.OFF) return
+
+    val severity =
+        if (policy == AbiRepairPolicy.ERROR) CompilerMessageSeverity.ERROR
+        else CompilerMessageSeverity.WARNING
+    for (constant in state.fabricatedConstants) {
+      configuration.messageCollector.report(
+          severity,
+          "Kosabi source-only ABI: the value of constant `${constant.classId}.${constant.name}` " +
+              "is not available, because no target on the source-only ABI classpath declares it. " +
+              "A placeholder of type `${constant.emittedType}` " +
+              "(${if (constant.typeSource == ConstTypeSource.ANNOTATION_PARAMETER)
+                  "type taken from the annotation parameter it is passed to"
+                else "type unknown, assumed String"}) " +
+              "was emitted instead, so this ABI does not match a class-ABI build. " +
+              "To fix, add the target that declares the constant to THIS target's " +
+              "`source_only_abi_deps`. Reach for `required_for_source_only_abi = True` on the " +
+              "declaring target only when many consumers need it: that is a global edge which " +
+              "puts its ABI on the source-only ABI classpath of every consumer, not just this " +
+              "one.",
+      )
+    }
+  }
+}
+
+class AbiGenFirExtensionRegistrar() : FirExtensionRegistrar() {
+  override fun ExtensionRegistrarContext.configurePlugin() {
+    +{ session: FirSession -> MissingConstantDeclarationGenerationExtension(session) }
+    +JvmAbiGenService.getFactory()
+  }
+}
+
+@OptIn(ExperimentalTopLevelDeclarationsGenerationApi::class)
+class MissingConstantDeclarationGenerationExtension(
+    session: FirSession,
+) : FirDeclarationGenerationExtension(session) {
+
+  override fun getTopLevelClassIds(): Set<ClassId> {
+    val missingConstants = session.jvmAbiGenService.state.missingConstants
+    return missingConstants.keys.toSet()
+  }
+
+  override fun getTopLevelCallableIds(): Set<CallableId> {
+    val missingConstants = session.jvmAbiGenService.state.missingConstants
+    return missingConstants
+        .flatMap { (classId, constants) ->
+          constants.map { constantName -> CallableId(classId, Name.identifier(constantName)) }
+        }
+        .toSet()
+  }
+
+  override fun generateTopLevelClassLikeDeclaration(classId: ClassId): FirClassLikeSymbol<*>? {
+    val missingConstants = session.jvmAbiGenService.state.missingConstants
+
+    if (classId !in missingConstants) {
+      return null
+    }
+
+    val createdClass = createTopLevelClass(classId, JvmAbiGenPlugin, ClassKind.OBJECT)
+    createdClass.replaceStatus(
+        FirResolvedDeclarationStatusImpl(
+            Visibilities.Public,
+            Modality.FINAL,
+            EffectiveVisibility.Public,
+        )
+            .apply { isStatic = true },
+    )
+    return createdClass.symbol
+  }
+
+  @OptIn(SymbolInternals::class)
+  override fun getCallableNamesForClass(
+      classSymbol: FirClassSymbol<*>,
+      context: MemberGenerationContext,
+  ): Set<Name> {
+    val classId = classSymbol.classId
+    val state = session.jvmAbiGenService.state
+
+    // Existing code for missing constants
+    val missingConstants = state.missingConstants
+    val constantNames =
+        (missingConstants[classId] ?: emptySet()).map { Name.identifier(it) }.toSet()
+
+    // Detect methods from internal interfaces
+    val internalMethodNames = mutableSetOf<Name>()
+    val classDecl = classSymbol.fir as? FirRegularClass
+
+    if (classDecl != null) {
+      // Check if this class is public
+      val classVisibility = classDecl.status.visibility
+      if (classVisibility == Visibilities.Public || classVisibility == Visibilities.Protected) {
+        // Find internal interface supertypes
+        val interfaceMethodInfos = mutableListOf<InterfaceMethodInfo>()
+
+        for (superTypeRef in classDecl.superTypeRefs) {
+          val coneType =
+              (superTypeRef as? FirResolvedTypeRef)?.coneType as? ConeClassLikeType ?: continue
+          val superClassId = coneType.lookupTag.classId
+          val superSymbol =
+              session.symbolProvider.getClassLikeSymbolByClassId(superClassId) as? FirClassSymbol<*>
+                  ?: continue
+          val superClass = superSymbol.fir as? FirRegularClass ?: continue
+
+          // Check if interface is internal/private
+          val superVisibility = superClass.status.visibility
+          val isInternal =
+              superVisibility != Visibilities.Public && superVisibility != Visibilities.Protected
+
+          if (isInternal && superClass.classKind == ClassKind.INTERFACE) {
+            // Collect methods from this internal interface
+            for (decl in superClass.declarations) {
+              if (decl is FirNamedFunctionCompat) {
+                val visibility = decl.status.visibility
+                if (visibility == Visibilities.Public || visibility == Visibilities.Protected) {
+                  // Check if method is not already declared in the class
+                  val alreadyDeclaredInClass =
+                      classDecl.declarations.any {
+                        it is FirNamedFunctionCompat && it.name == decl.name
+                      }
+
+                  // For enums, also check if method is overridden in any enum entry
+                  val alreadyDeclaredInEnumEntry =
+                      classDecl.classKind == ClassKind.ENUM_CLASS &&
+                          classDecl.declarations.any { entry ->
+                            if (entry is FirEnumEntry) {
+                              val entryInit = entry.initializer as? FirAnonymousObjectExpression
+                              entryInit?.anonymousObject?.declarations?.any {
+                                it is FirNamedFunctionCompat && it.name == decl.name
+                              } ?: false
+                            } else {
+                              false
+                            }
+                          }
+
+                  val alreadyDeclared = alreadyDeclaredInClass || alreadyDeclaredInEnumEntry
+                  if (!alreadyDeclared) {
+                    internalMethodNames.add(decl.name)
+                    interfaceMethodInfos.add(
+                        InterfaceMethodInfo(
+                            name = decl.name,
+                            returnType = decl.returnTypeRef.coneType,
+                            valueParameters =
+                                decl.valueParameters.map { param ->
+                                  param.name to param.returnTypeRef.coneType
+                                },
+                        ),
+                    )
+                  }
+                }
+              }
+            }
+          }
+        }
+
+        // Store for later generation
+        if (interfaceMethodInfos.isNotEmpty()) {
+          state.internalInterfaceMethods[classId] = interfaceMethodInfos.toMutableList()
+        }
+      }
+    }
+
+    return constantNames + internalMethodNames
+  }
+
+  override fun generateProperties(
+      callableId: CallableId,
+      context: MemberGenerationContext?,
+  ): List<FirPropertySymbol> {
+    val owner = context?.owner ?: return emptyList()
+    val classId = callableId.classId ?: return emptyList()
+
+    val missingConstants = session.jvmAbiGenService.state.missingConstants
+    val constantsForClass = missingConstants[classId] ?: return emptyList()
+
+    val constantName = callableId.callableName.asString()
+    if (constantName !in constantsForClass) {
+      return emptyList()
+    }
+
+    return listOf(generateConstantProperty(constantName, owner))
+  }
+
+  override fun generateFunctions(
+      callableId: CallableId,
+      context: MemberGenerationContext?,
+  ): List<FirNamedFunctionSymbol> {
+    val owner = context?.owner ?: return emptyList()
+    val classId = callableId.classId ?: return emptyList()
+
+    val state = session.jvmAbiGenService.state
+    val methodInfos = state.internalInterfaceMethods[classId] ?: return emptyList()
+
+    val methodName = callableId.callableName
+    val methodInfo = methodInfos.find { it.name == methodName } ?: return emptyList()
+
+    // Generate the function using the plugin utility
+    val function = createMemberFunction(
+        owner,
+        JvmAbiGenPlugin,
+        methodName,
+        methodInfo.returnType,
+    ) {
+      // Add value parameters
+      for ((paramName, paramType) in methodInfo.valueParameters) {
+        valueParameter(paramName, paramType)
+      }
+    }
+
+    // Set status: public and final (required for enum implementations)
+    function.replaceStatus(
+        FirResolvedDeclarationStatusImpl(
+            Visibilities.Public,
+            Modality.FINAL,
+            EffectiveVisibility.Public,
+        ),
+    )
+
+    return listOf(function.symbol)
+  }
+
+  override fun hasPackage(packageFqName: FqName): Boolean {
+    val missingConstants = session.jvmAbiGenService.state.missingConstants
+
+    // Return true for any package that contains classes we're generating
+    return missingConstants.keys.any { classId -> classId.packageFqName == packageFqName }
+  }
+
+  /**
+   * Synthesises a constant whose declaring class is not on the source-only ABI classpath.
+   *
+   * The real value is unrecoverable here by construction: the constant is being synthesised
+   * precisely because nothing on the classpath declares it, and Kosabi never reads the provider's
+   * sources. Only a placeholder can be emitted, so any constant reaching this function makes the
+   * resulting ABI differ from a class-ABI build. The correct repair is to put the declaring target
+   * on the consuming target's source-only ABI classpath, by adding it to that target's
+   * `source_only_abi_deps`; this function only limits the damage in the meantime and records it for
+   * [AbiGenRepairLog].
+   *
+   * The type, unlike the value, is often recoverable - see [resolveAnnotationParameterType]. Using
+   * it matters: emitting `String` for an `Int` constant makes constant evaluation fail outright
+   * (`ClassCastException` in `IrConstAnnotationTransformer`) rather than merely produce a wrong
+   * number.
+   */
+  private fun generateConstantProperty(
+      constantName: String,
+      owner: FirClassSymbol<*>,
+  ): FirPropertySymbol {
+    val state = session.jvmAbiGenService.state
+    val key = constHintKey(owner.classId, constantName)
+    val hint = state.constantTypeHints[key]
+
+    val property = createMemberProperty(
+        owner,
+        JvmAbiGenPlugin,
+        Name.identifier(constantName),
+        hint?.coneType(session) ?: session.builtinTypes.stringType.coneType,
+    )
+    property.replaceStatus(
+        FirResolvedDeclarationStatusImpl(
+            Visibilities.Public,
+            Modality.FINAL,
+            EffectiveVisibility.Public,
+        )
+            .apply { isConst = true },
+    )
+    property.replaceInitializer(
+        buildLiteralExpression(
+            source = null,
+            kind = hint?.constantValueKind ?: ConstantValueKind.String,
+            value = hint?.placeholderValue ?: "",
+            setType = true,
+        ),
+    )
+
+    state.fabricatedConstants.add(
+        FabricatedConstant(
+            classId = owner.classId.asString(),
+            name = constantName,
+            emittedType = hint?.typeName ?: "String",
+            typeSource =
+                if (hint != null) ConstTypeSource.ANNOTATION_PARAMETER
+                else ConstTypeSource.ASSUMED_STRING,
+        ),
+    )
+    return property.symbol
+  }
+}
+
+/** A constant type Kosabi is able to synthesise a placeholder literal for. */
+enum class ConstTypeHint(
+    val typeName: String,
+    val constantValueKind: ConstantValueKind,
+    val placeholderValue: Any,
+) {
+  BOOLEAN("Boolean", ConstantValueKind.Boolean, false),
+  BYTE("Byte", ConstantValueKind.Byte, 0.toByte()),
+  SHORT("Short", ConstantValueKind.Short, 0.toShort()),
+  INT("Int", ConstantValueKind.Int, 0),
+  LONG("Long", ConstantValueKind.Long, 0L),
+  FLOAT("Float", ConstantValueKind.Float, 0.0f),
+  DOUBLE("Double", ConstantValueKind.Double, 0.0),
+  CHAR("Char", ConstantValueKind.Char, '\u0000'),
+  STRING("String", ConstantValueKind.String, "");
+
+  fun coneType(session: FirSession): ConeKotlinType =
+      when (this) {
+        BOOLEAN -> session.builtinTypes.booleanType.coneType
+        BYTE -> session.builtinTypes.byteType.coneType
+        SHORT -> session.builtinTypes.shortType.coneType
+        INT -> session.builtinTypes.intType.coneType
+        LONG -> session.builtinTypes.longType.coneType
+        FLOAT -> session.builtinTypes.floatType.coneType
+        DOUBLE -> session.builtinTypes.doubleType.coneType
+        CHAR -> session.builtinTypes.charType.coneType
+        STRING -> session.builtinTypes.stringType.coneType
+      }
+
+  companion object {
+    fun bySimpleName(name: String): ConstTypeHint? = entries.firstOrNull { it.typeName == name }
+  }
+}
+
+internal fun constHintKey(classId: ClassId, constantName: String): String =
+    "${classId.asString()}.$constantName"
+
+/**
+ * Maps a type as written in source to a constant kind.
+ *
+ * Array types are unwrapped once because no constant can itself be an array - an array-typed
+ * annotation parameter is always fed element-wise. Anything not recognised (a typealias, an enum, a
+ * generic) yields null so the caller falls back instead of guessing.
+ */
+internal fun constTypeHintFromTypeText(typeText: String?): ConstTypeHint? {
+  var text = typeText?.trim()?.removeSuffix("?")?.trim() ?: return null
+  if (text.endsWith(">")) {
+    val open = text.indexOf('<')
+    if (open <= 0) return null
+    if (text.take(open).substringAfterLast('.') != "Array") return null
+    text = text.substring(open + 1, text.length - 1).removePrefix("out ").trim()
+  }
+  val simpleName = text.substringAfterLast('.').removeSuffix("?").trim()
+  ConstTypeHint.bySimpleName(simpleName)?.let {
+    return it
+  }
+  return when (simpleName) {
+    "BooleanArray" -> ConstTypeHint.BOOLEAN
+    "ByteArray" -> ConstTypeHint.BYTE
+    "ShortArray" -> ConstTypeHint.SHORT
+    "IntArray" -> ConstTypeHint.INT
+    "LongArray" -> ConstTypeHint.LONG
+    "FloatArray" -> ConstTypeHint.FLOAT
+    "DoubleArray" -> ConstTypeHint.DOUBLE
+    "CharArray" -> ConstTypeHint.CHAR
+    else -> null
+  }
+}
+
+/** FIR counterpart of [constTypeHintFromTypeText], for annotations coming from dependencies. */
+internal fun constTypeHintFromConeType(type: ConeKotlinType): ConstTypeHint? {
+  val classId = (type as? ConeClassLikeType)?.lookupTag?.classId ?: return null
+  val fqName = classId.asFqNameString()
+  if (fqName == "kotlin.Array") {
+    val elementType =
+        (type.typeArguments.firstOrNull() as? ConeKotlinTypeProjection)?.type ?: return null
+    return constTypeHintFromConeType(elementType)
+  }
+  return constTypeHintFromTypeText(fqName.takeIf { it.startsWith("kotlin.") })
+}
+
+class JvmAbiGenService(session: FirSession, state: AbiGenState) :
+    FirExtensionSessionComponent(session) {
+  companion object {
+    fun getFactory(): Factory {
+      return Factory { JvmAbiGenService(it, AbiGenState()) }
+    }
+  }
+
+  val state: AbiGenState = state
+}
+
+class AbiGenState {
+  val missingConstants: MutableMap<ClassId, Set<String>> = mutableMapOf()
+
+  /**
+   * Declared type of each synthesised constant, keyed by [constHintKey], recovered from the
+   * annotation parameter it is passed to. Absent means the type could not be established.
+   */
+  val constantTypeHints: MutableMap<String, ConstTypeHint> = mutableMapOf()
+
+  /** Constants whose usages disagreed about the type; treated the same as having no hint. */
+  val ambiguousConstantTypeHints: MutableSet<String> = mutableSetOf()
+
+  /** Every constant synthesised during this compilation. See [AbiGenRepairLog]. */
+  val fabricatedConstants: MutableList<FabricatedConstant> = mutableListOf()
+  // Track methods from internal interfaces that need to be generated for classes
+  // Key: owning class's ClassId, Value: List of interface method details
+  val internalInterfaceMethods: MutableMap<ClassId, MutableList<InterfaceMethodInfo>> =
+      mutableMapOf()
+}
+
+val FirSession.jvmAbiGenService: JvmAbiGenService by FirSession.sessionComponentAccessor()
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/KosabiClassUsageCollector.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/KosabiClassUsageCollector.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/KosabiClassUsageCollector.kt
@@ -0,0 +1,312 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("OPT_IN_USAGE_ERROR")
+@file:OptIn(
+    com.facebook.DirectDeclarationsAccessCompat::class,
+)
+
+package com.facebook
+
+import java.io.BufferedWriter
+import java.io.File
+import java.io.FileWriter
+import java.net.URI
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.config.CompilerConfigurationKey
+import org.jetbrains.kotlin.fir.FirElement
+import org.jetbrains.kotlin.fir.FirSession
+import org.jetbrains.kotlin.fir.declarations.FirAnonymousObject
+import org.jetbrains.kotlin.fir.declarations.FirClassLikeDeclaration
+import org.jetbrains.kotlin.fir.declarations.FirDeclarationOrigin
+import org.jetbrains.kotlin.fir.declarations.FirEnumEntry
+import org.jetbrains.kotlin.fir.declarations.FirRegularClass
+import org.jetbrains.kotlin.fir.declarations.FirTypeAlias
+import org.jetbrains.kotlin.fir.declarations.utils.classId
+import org.jetbrains.kotlin.fir.declarations.utils.isConst
+import org.jetbrains.kotlin.fir.declarations.utils.sourceElement
+import org.jetbrains.kotlin.fir.expressions.FirQualifiedAccessExpression
+import org.jetbrains.kotlin.fir.expressions.FirResolvedQualifier
+import org.jetbrains.kotlin.fir.references.symbol
+import org.jetbrains.kotlin.fir.resolve.providers.symbolProvider
+import org.jetbrains.kotlin.fir.symbols.SymbolInternals
+import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
+import org.jetbrains.kotlin.fir.types.ConeErrorType
+import org.jetbrains.kotlin.fir.types.ConeKotlinType
+import org.jetbrains.kotlin.fir.types.classId
+import org.jetbrains.kotlin.fir.types.coneType
+import org.jetbrains.kotlin.fir.types.resolvedType
+import org.jetbrains.kotlin.fir.types.upperBoundIfFlexible
+import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitorVoid
+import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinarySourceElement
+import org.jetbrains.kotlin.name.ClassId
+
+private const val JAR_FILE_SEPARATOR = "!/"
+private const val STUBSGEN_STUBS_JAR = "stubgen_stubs.jar"
+
+/**
+ * Collects classpath class usage from a resolved FIR tree for dep file tracking.
+ *
+ * This replaces the DependencyTracker compiler plugin for kosabi's inner compilation session, since
+ * kosabi creates a separate project environment where the dep-tracker's FIR checker extensions are
+ * not registered, and kosabi skips the checker phase entirely.
+ *
+ * Instead, we walk the already-resolved FIR tree post-analysis and extract class usage from
+ * declaration-level type references (supertypes, return types, parameter types, property types,
+ * annotations, imports, and const val initializers).
+ */
+class KosabiClassUsageCollector {
+
+  private val uriUsages: MutableSet<URI> = mutableSetOf()
+  private val visitedClasses = mutableSetOf<String>()
+
+  /**
+   * Walk the resolved FIR tree and collect all referenced classpath classes. Writes results to the
+   * dep-tracker output path if available in the configuration.
+   */
+  fun collectAndDump(analysisResults: FirResultCompat, configuration: CompilerConfiguration) {
+    val outputPath = getDepTrackerOutputPath(configuration) ?: return
+
+    for (output in analysisResults.outputs) {
+      val session = output.session
+      for (firFile in output.fir) {
+        recordImports(firFile, session)
+        firFile.accept(ClassUsageVisitor(session))
+      }
+    }
+
+    dump(outputPath)
+  }
+
+  private fun recordImports(
+      firFile: org.jetbrains.kotlin.fir.declarations.FirFile,
+      session: FirSession,
+  ) {
+    for (firImport in firFile.imports) {
+      val fqName = firImport.importedFqName ?: continue
+      if (fqName.isRoot) continue
+      val classId = ClassId.topLevel(fqName)
+      @OptIn(SymbolInternals::class)
+      val symbol = session.symbolProvider.getClassLikeSymbolByClassId(classId) ?: continue
+      @OptIn(SymbolInternals::class) val firClass = symbol.fir
+      recordClassDeclaration(firClass, session)
+    }
+  }
+
+  @OptIn(SymbolInternals::class)
+  private fun recordType(type: ConeKotlinType, session: FirSession) {
+    if (type is ConeErrorType) return
+
+    val classId = type.upperBoundIfFlexible().classId ?: return
+
+    // Skip builtins and local classes
+    if (classId.isLocal) return
+    val pkg = classId.packageFqName.asString()
+    if (pkg.startsWith("kotlin") || pkg.startsWith("java")) return
+
+    val symbol = session.symbolProvider.getClassLikeSymbolByClassId(classId) ?: return
+    recordClassDeclaration(symbol.fir, session)
+  }
+
+  @OptIn(SymbolInternals::class)
+  private fun recordClassDeclaration(firClass: FirClassLikeDeclaration, session: FirSession) {
+    when (firClass) {
+      is FirRegularClass -> {
+        if (firClass.origin is FirDeclarationOrigin.BuiltIns) return
+        val className = firClass.symbol.classId.asSingleFqName().asString()
+        if (!visitedClasses.add(className)) return
+        firClass.sourceElement?.let(::recordSource)
+        firClass.superTypeRefs.forEach { recordType(it.coneType, session) }
+        firClass.annotations
+            .map { it.annotationTypeRef }
+            .forEach { recordType(it.coneType, session) }
+      }
+      is FirAnonymousObject -> {
+        firClass.superTypeRefs.forEach { recordType(it.coneType, session) }
+      }
+      is FirTypeAlias -> {
+        recordType(firClass.expandedTypeRef.coneType, session)
+      }
+      else -> {}
+    }
+  }
+
+  private fun recordSource(source: org.jetbrains.kotlin.descriptors.SourceElement) {
+    when (source) {
+      is KotlinJvmBinarySourceElement -> addFile(source.binaryClass.location)
+      is org.jetbrains.kotlin.load.kotlin.JvmPackagePartSource ->
+          source.knownJvmBinaryClass?.location?.let(::addFile)
+      is org.jetbrains.kotlin.load.java.sources.JavaSourceElement -> {
+        val javaElement = source.javaElement
+        if (
+            javaElement is org.jetbrains.kotlin.load.java.structure.impl.VirtualFileBoundJavaClass
+        ) {
+          javaElement.virtualFile?.path?.let(::addFile)
+        }
+      }
+    }
+  }
+
+  private fun addFile(path: String) {
+    if (
+        path.contains(JAR_FILE_SEPARATOR) &&
+            !path.split(JAR_FILE_SEPARATOR)[0].endsWith(STUBSGEN_STUBS_JAR)
+    ) {
+      uriUsages.add(URI("jar:file://$path"))
+    }
+  }
+
+  private fun dump(path: String) {
+    BufferedWriter(FileWriter(File(path), /* append= */ true)).use { writer ->
+      for (uri in uriUsages) {
+        writer.appendLine(uri.toString())
+      }
+    }
+  }
+
+  /**
+   * Visitor that walks expression trees to find class references. Used for visiting const val
+   * initializers and other expression contexts where types need to be tracked.
+   */
+  private inner class ExpressionUsageVisitor(private val session: FirSession) :
+      FirDefaultVisitorVoid() {
+    override fun visitElement(element: FirElement) {
+      element.acceptChildren(this)
+    }
+
+    override fun visitResolvedQualifier(resolvedQualifier: FirResolvedQualifier) {
+      val classId = resolvedQualifier.classId
+      if (classId != null) {
+        @OptIn(SymbolInternals::class)
+        val symbol = session.symbolProvider.getClassLikeSymbolByClassId(classId)
+        if (symbol != null) {
+          @OptIn(SymbolInternals::class) recordClassDeclaration(symbol.fir, session)
+        }
+      }
+      resolvedQualifier.acceptChildren(this)
+    }
+
+    override fun visitQualifiedAccessExpression(
+        qualifiedAccessExpression: FirQualifiedAccessExpression,
+    ) {
+      // Record the type of the expression itself
+      try {
+        recordType(qualifiedAccessExpression.resolvedType, session)
+      } catch (_: Exception) {
+        // resolvedType may throw on unresolved expressions
+      }
+      // Record the dispatch receiver type (e.g., B.Companion in B.bConst)
+      val calleeSymbol = qualifiedAccessExpression.calleeReference.symbol
+      if (calleeSymbol is FirCallableSymbol<*>) {
+        val dispatchClassId = calleeSymbol.callableId?.classId
+        if (dispatchClassId != null) {
+          @OptIn(SymbolInternals::class)
+          val classSymbol = session.symbolProvider.getClassLikeSymbolByClassId(dispatchClassId)
+          if (classSymbol != null) {
+            @OptIn(SymbolInternals::class) recordClassDeclaration(classSymbol.fir, session)
+          }
+        }
+      }
+      qualifiedAccessExpression.acceptChildren(this)
+    }
+  }
+
+  private inner class ClassUsageVisitor(private val session: FirSession) :
+      FirDefaultVisitorVoidCompat() {
+    override fun visitElement(element: FirElement) {
+      // Default: do not recurse into expressions/bodies
+    }
+
+    override fun visitFile(file: org.jetbrains.kotlin.fir.declarations.FirFile) {
+      for (declaration in file.declarations) {
+        declaration.accept(this)
+      }
+    }
+
+    override fun visitRegularClass(regularClass: FirRegularClass) {
+      for (superTypeRef in regularClass.superTypeRefs) {
+        recordType(superTypeRef.coneType, session)
+      }
+      for (annotation in regularClass.annotations) {
+        recordType(annotation.annotationTypeRef.coneType, session)
+      }
+      for (declaration in regularClass.declarations) {
+        declaration.accept(this)
+      }
+    }
+
+    override fun visitNamedFunctionCompat(simpleFunction: FirNamedFunctionCompat) {
+      recordType(simpleFunction.returnTypeRef.coneType, session)
+      for (valueParameter in simpleFunction.valueParameters) {
+        recordType(valueParameter.returnTypeRef.coneType, session)
+      }
+      for (annotation in simpleFunction.annotations) {
+        recordType(annotation.annotationTypeRef.coneType, session)
+      }
+    }
+
+    override fun visitProperty(property: org.jetbrains.kotlin.fir.declarations.FirProperty) {
+      recordType(property.returnTypeRef.coneType, session)
+      for (annotation in property.annotations) {
+        recordType(annotation.annotationTypeRef.coneType, session)
+      }
+      // Walk const val initializers — these are part of the ABI (inlined constants)
+      // and may reference classes not visible from declaration-level types alone.
+      // Example: const val x: Int = B.bConst  references B.Companion
+      if (property.isConst) {
+        property.initializer?.accept(ExpressionUsageVisitor(session))
+      }
+    }
+
+    override fun visitConstructor(
+        constructor: org.jetbrains.kotlin.fir.declarations.FirConstructor,
+    ) {
+      for (valueParameter in constructor.valueParameters) {
+        recordType(valueParameter.returnTypeRef.coneType, session)
+      }
+      for (annotation in constructor.annotations) {
+        recordType(annotation.annotationTypeRef.coneType, session)
+      }
+    }
+
+    override fun visitEnumEntry(enumEntry: FirEnumEntry) {
+      recordType(enumEntry.returnTypeRef.coneType, session)
+    }
+
+    override fun visitTypeAlias(typeAlias: FirTypeAlias) {
+      recordType(typeAlias.expandedTypeRef.coneType, session)
+    }
+  }
+
+  companion object {
+    /**
+     * Gets the dep-tracker output path from the compiler configuration. Uses reflection to access
+     * DependencyTrackerCommandLineProcessor.ARG_OUTPUT_PATH since the k2-jvm-abi-gen module does
+     * not have a direct dependency on the dep-tracker module.
+     */
+    @Suppress("SwallowedException")
+    private fun getDepTrackerOutputPath(configuration: CompilerConfiguration): String? {
+      return try {
+        val clpClass =
+            Class.forName(
+                "com.facebook.kotlin.compilerplugins.usedclasses.cli.DependencyTrackerCommandLineProcessor",
+            )
+        val companionField = clpClass.getDeclaredField("Companion")
+        val companion = companionField.get(null)
+        val method = companion.javaClass.getDeclaredMethod("getARG_OUTPUT_PATH")
+        @Suppress("UNCHECKED_CAST")
+        val key = method.invoke(companion) as CompilerConfigurationKey<String>
+        configuration.get(key)
+      } catch (_: Exception) {
+        null
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/common/Types.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/common/Types.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/common/Types.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+@file:Suppress("OPT_IN_USAGE_ERROR")
+@file:OptIn(
+    com.facebook.DeprecatedForRemovalCompilerApiCompat::class,
+)
+
+package com.facebook
+
+import org.jetbrains.kotlin.GeneratedDeclarationKey
+import org.jetbrains.kotlin.fir.types.ConeKotlinType
+import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
+import org.jetbrains.kotlin.ir.types.classFqName
+import org.jetbrains.kotlin.name.Name
+
+data object JvmAbiGenPlugin : GeneratedDeclarationKey()
+
+data class InterfaceMethodInfo(
+    val name: Name,
+    val returnType: ConeKotlinType,
+    val valueParameters: List<Pair<Name, ConeKotlinType>>,
+)
+
+internal data class MethodSignature(
+    val name: String,
+    val parameterTypes: List<String>,
+)
+
+internal fun IrSimpleFunction.methodSignature() = MethodSignature(
+    name.asString(),
+    valueParameters.map { it.type.classFqName?.asString() ?: it.type.toString() },
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/DependencyListCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/DependencyListCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/DependencyListCompat.kt
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.fir.DependencyListForCliModule
+import org.jetbrains.kotlin.fir.FirModuleData
+
+val DependencyListForCliModule.friendDependenciesCompat: List<FirModuleData>
+  get() = friendDependencies
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirCollectionLiteralCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirCollectionLiteralCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirCollectionLiteralCompat.kt
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+// FirArrayLiteral was renamed to FirCollectionLiteral in Kotlin 2.3.
+typealias FirCollectionLiteralCompat = org.jetbrains.kotlin.fir.expressions.FirArrayLiteral
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirDefaultVisitorVoidCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirDefaultVisitorVoidCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirDefaultVisitorVoidCompat.kt
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction
+import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitorVoid
+
+// In Kotlin 2.2 the visitor callback is visitSimpleFunction(FirSimpleFunction); in 2.3 it was
+// renamed to visitNamedFunction(FirNamedFunction). Bridge both to visitNamedFunctionCompat.
+abstract class FirDefaultVisitorVoidCompat : FirDefaultVisitorVoid() {
+  abstract fun visitNamedFunctionCompat(namedFunction: FirNamedFunctionCompat)
+
+  override fun visitSimpleFunction(simpleFunction: FirSimpleFunction) {
+    visitNamedFunctionCompat(simpleFunction)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirJvmSessionFactoryCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirJvmSessionFactoryCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirJvmSessionFactoryCompat.kt
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.config.languageVersionSettings
+import org.jetbrains.kotlin.fir.FirModuleData
+import org.jetbrains.kotlin.fir.FirSession
+import org.jetbrains.kotlin.fir.deserialization.ModuleDataProvider
+import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrar
+import org.jetbrains.kotlin.fir.java.FirProjectSessionProvider
+import org.jetbrains.kotlin.fir.session.FirJvmIncrementalCompilationSymbolProviders
+import org.jetbrains.kotlin.fir.session.FirJvmSessionFactory
+import org.jetbrains.kotlin.fir.session.FirSessionConfigurator
+import org.jetbrains.kotlin.fir.session.FirSharableJavaComponents
+import org.jetbrains.kotlin.fir.session.environment.AbstractProjectEnvironment
+import org.jetbrains.kotlin.fir.session.environment.AbstractProjectFileSearchScope
+import org.jetbrains.kotlin.load.kotlin.PackagePartProvider
+import org.jetbrains.kotlin.name.Name
+
+fun createLibrarySessionCompat(
+    rootModuleName: Name,
+    sessionProvider: FirProjectSessionProvider,
+    moduleDataProvider: ModuleDataProvider,
+    projectEnvironment: AbstractProjectEnvironment,
+    extensionRegistrars: List<FirExtensionRegistrar>,
+    librariesScope: AbstractProjectFileSearchScope,
+    packagePartProvider: PackagePartProvider,
+    languageVersionSettings: org.jetbrains.kotlin.config.LanguageVersionSettings,
+    predefinedJavaComponents: FirSharableJavaComponents?,
+): FirSession {
+  val sharedLibrarySession =
+      FirJvmSessionFactory.createSharedLibrarySession(
+          rootModuleName,
+          sessionProvider,
+          projectEnvironment,
+          extensionRegistrars,
+          librariesScope,
+          packagePartProvider,
+          languageVersionSettings,
+          predefinedJavaComponents,
+      )
+  return FirJvmSessionFactory.createLibrarySession(
+      sessionProvider,
+      sharedLibrarySession,
+      moduleDataProvider,
+      projectEnvironment,
+      extensionRegistrars,
+      librariesScope,
+      packagePartProvider,
+      languageVersionSettings,
+      predefinedJavaComponents,
+  )
+}
+
+fun createSourceSessionCompat(
+    moduleData: FirModuleData,
+    sessionProvider: FirProjectSessionProvider,
+    javaSourcesScope: AbstractProjectFileSearchScope,
+    projectEnvironment: org.jetbrains.kotlin.cli.jvm.compiler.VfsBasedProjectEnvironment,
+    createIncrementalCompilationSymbolProviders:
+        (FirSession) -> FirJvmIncrementalCompilationSymbolProviders?,
+    extensionRegistrars: List<FirExtensionRegistrar>,
+    configuration: CompilerConfiguration,
+    predefinedJavaComponents: FirSharableJavaComponents?,
+    needRegisterJavaElementFinder: Boolean,
+    init: FirSessionConfigurator.() -> Unit,
+): FirSession {
+  return FirJvmSessionFactory.createSourceSession(
+      moduleData,
+      sessionProvider,
+      javaSourcesScope,
+      projectEnvironment,
+      createIncrementalCompilationSymbolProviders,
+      extensionRegistrars,
+      configuration,
+      predefinedJavaComponents = predefinedJavaComponents,
+      needRegisterJavaElementFinder = needRegisterJavaElementFinder,
+      init = init,
+  )
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirNamedFunctionCopyCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirNamedFunctionCopyCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirNamedFunctionCopyCompat.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.fir.declarations.builder.FirSimpleFunctionBuilder
+import org.jetbrains.kotlin.fir.declarations.builder.buildSimpleFunctionCopy
+
+typealias FirNamedFunctionBuilderCompat = FirSimpleFunctionBuilder
+
+// buildSimpleFunctionCopy was renamed to buildNamedFunctionCopy in Kotlin 2.3.
+inline fun buildNamedFunctionCopyCompat(
+    original: FirNamedFunctionCompat,
+    init: FirNamedFunctionBuilderCompat.() -> Unit,
+): FirNamedFunctionCompat = buildSimpleFunctionCopy(original, init)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirResultCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirResultCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirResultCompat.kt
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+typealias FirResultCompat = org.jetbrains.kotlin.fir.pipeline.FirResult
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirSourceModuleDataCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirSourceModuleDataCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FirSourceModuleDataCompat.kt
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.fir.FirModuleData
+import org.jetbrains.kotlin.fir.FirSourceModuleData
+import org.jetbrains.kotlin.name.Name
+import org.jetbrains.kotlin.platform.TargetPlatform
+
+fun createSourceModuleData(
+    name: Name,
+    dependencies: List<FirModuleData>,
+    dependsOnDependencies: List<FirModuleData>,
+    friendDependencies: List<FirModuleData>,
+    platform: TargetPlatform,
+): FirModuleData {
+  return FirSourceModuleData(
+      name,
+      dependencies,
+      dependsOnDependencies,
+      friendDependencies,
+      platform,
+  )
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FrontendPipelineCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FrontendPipelineCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/FrontendPipelineCompat.kt
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress(
+    "PackageLocationMismatch",
+    "DEPRECATION",
+    "DEPRECATION_ERROR",
+)
+@file:OptIn(org.jetbrains.kotlin.cli.common.LegacyK2CliPipeline::class)
+
+package com.facebook
+
+import org.jetbrains.kotlin.cli.common.messages.MessageCollector
+import org.jetbrains.kotlin.cli.jvm.compiler.VfsBasedProjectEnvironment
+import org.jetbrains.kotlin.cli.jvm.compiler.createLibraryListForJvm
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.config.JVMConfigurationKeys
+import org.jetbrains.kotlin.config.languageVersionSettings
+import org.jetbrains.kotlin.diagnostics.DiagnosticReporterFactory
+import org.jetbrains.kotlin.diagnostics.impl.BaseDiagnosticsCollector
+import org.jetbrains.kotlin.fir.FirSession
+import org.jetbrains.kotlin.fir.declarations.FirFile
+import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction
+import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrar
+import org.jetbrains.kotlin.fir.java.FirProjectSessionProvider
+import org.jetbrains.kotlin.fir.pipeline.FirResult
+import org.jetbrains.kotlin.fir.pipeline.ModuleCompilerAnalyzedOutput
+import org.jetbrains.kotlin.fir.resolve.ScopeSession
+import org.jetbrains.kotlin.fir.session.FirJvmIncrementalCompilationSymbolProviders
+import org.jetbrains.kotlin.fir.session.FirSharableJavaComponents
+import org.jetbrains.kotlin.fir.session.IncrementalCompilationContext
+import org.jetbrains.kotlin.fir.session.createSymbolProviders
+import org.jetbrains.kotlin.fir.session.environment.AbstractProjectFileSearchScope
+import org.jetbrains.kotlin.fir.session.firCachesFactoryForCliMode
+import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitorVoid
+import org.jetbrains.kotlin.name.Name
+import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
+import org.jetbrains.kotlin.psi.KtFile
+
+/** Frontend analysis output wrapper. Renamed to AllModulesFrontendOutput in Kotlin 2.3. */
+typealias FrontendOutputCompat = FirResult
+
+/** Per-module frontend output element. Renamed to SingleModuleFrontendOutput in Kotlin 2.3. */
+typealias ModuleFrontendOutputCompat = ModuleCompilerAnalyzedOutput
+
+/** Source function declaration. Renamed to FirNamedFunction in Kotlin 2.3. */
+typealias FirNamedFunctionCompat = FirSimpleFunction
+
+fun moduleFrontendOutputCompat(
+    session: FirSession,
+    scopeSession: ScopeSession,
+    fir: List<FirFile>,
+): ModuleFrontendOutputCompat = ModuleCompilerAnalyzedOutput(session, scopeSession, fir)
+
+fun frontendOutputCompat(outputs: List<ModuleFrontendOutputCompat>): FrontendOutputCompat =
+    FirResult(outputs)
+
+/**
+ * FIR visitor base that bridges the function visit method renamed in Kotlin 2.3
+ * (visitSimpleFunction -> visitNamedFunction). Subclasses implement [visitNamedFunctionCompat].
+ */
+abstract class FirNamedFunctionVisitorCompat : FirDefaultVisitorVoid() {
+  final override fun visitSimpleFunction(simpleFunction: FirSimpleFunction) {
+    visitNamedFunctionCompat(simpleFunction)
+  }
+
+  abstract fun visitNamedFunctionCompat(function: FirNamedFunctionCompat)
+}
+
+/** createPendingReporter dropped its MessageCollector parameter in Kotlin 2.3. */
+fun createPendingReporterCompat(messageCollector: MessageCollector): BaseDiagnosticsCollector =
+    DiagnosticReporterFactory.createPendingReporter(messageCollector)
+
+/** ModuleCompilerOutput.generationState.factory was flattened to .factory in Kotlin 2.3. */
+val ModuleCompilerOutputCompat.classFileFactoryCompat
+  get() = generationState.factory
+
+/** RETAIN_OUTPUT_IN_MEMORY is required to read bytecode from memory before Kotlin 2.3. */
+fun CompilerConfiguration.retainOutputInMemoryCompat() {
+  put(JVMConfigurationKeys.RETAIN_OUTPUT_IN_MEMORY, true)
+}
+
+/**
+ * Prepares the FIR JVM session(s) for the given source files. Kotlin 2.3 replaced the manual
+ * session-construction pipeline with JvmFrontendPipelinePhase.prepareJvmSessions.
+ */
+fun prepareJvmSessionsCompat(
+    ktFiles: List<KtFile>,
+    rootModuleName: String,
+    friendPaths: List<String>,
+    librariesScope: AbstractProjectFileSearchScope,
+    configuration: CompilerConfiguration,
+    projectEnvironment: VfsBasedProjectEnvironment,
+    providerAndScopeForIncrementalCompilation: IncrementalCompilationContext?,
+): List<Pair<FirSession, List<KtFile>>> {
+  val libraryList = createLibraryListForJvm(rootModuleName, configuration, friendPaths)
+  val moduleName = Name.special("<$rootModuleName>")
+
+  val extensionRegistrars = FirExtensionRegistrar.getInstances(projectEnvironment.project)
+  val javaSourcesScope = projectEnvironment.getSearchScopeForProjectJavaSources()
+  val predefinedJavaComponents = FirSharableJavaComponents(firCachesFactoryForCliMode)
+
+  val sessionProvider = FirProjectSessionProvider()
+
+  createLibrarySessionCompat(
+      moduleName,
+      sessionProvider,
+      libraryList.moduleDataProvider,
+      projectEnvironment,
+      extensionRegistrars,
+      librariesScope,
+      projectEnvironment.getPackagePartProvider(librariesScope),
+      configuration.languageVersionSettings,
+      predefinedJavaComponents,
+  )
+
+  val platformModuleData = createSourceModuleData(
+      moduleName,
+      libraryList.regularDependencies,
+      libraryList.dependsOnDependencies,
+      libraryList.friendDependenciesCompat,
+      JvmPlatforms.unspecifiedJvmPlatform,
+  )
+
+  var incrementalSymbolProviders: FirJvmIncrementalCompilationSymbolProviders? = null
+  var incrementalSymbolProvidersInitialized = false
+
+  val session = createSourceSessionCompat(
+      platformModuleData,
+      sessionProvider,
+      javaSourcesScope,
+      projectEnvironment,
+      createIncrementalCompilationSymbolProviders = { firSession ->
+        if (incrementalSymbolProvidersInitialized) incrementalSymbolProviders
+        else {
+          incrementalSymbolProvidersInitialized = true
+          providerAndScopeForIncrementalCompilation
+              ?.createSymbolProviders(firSession, platformModuleData, projectEnvironment)
+              ?.also { incrementalSymbolProviders = it }
+        }
+      },
+      extensionRegistrars,
+      configuration,
+      predefinedJavaComponents = predefinedJavaComponents,
+      needRegisterJavaElementFinder = true,
+      init = {},
+  )
+
+  return listOf(session to ktFiles)
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/IrNonAbiStripper.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/IrNonAbiStripper.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/IrNonAbiStripper.kt
@@ -0,0 +1,633 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+@file:Suppress("OPT_IN_USAGE_ERROR")
+@file:OptIn(
+    com.facebook.DeprecatedForRemovalCompilerApiCompat::class,
+    com.facebook.DirectDeclarationsAccessCompat::class,
+)
+
+package com.facebook
+
+import com.facebook.buck.jvm.kotlin.compilerplugins.common.isStub
+import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
+import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
+import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder
+import org.jetbrains.kotlin.descriptors.ClassKind
+import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
+import org.jetbrains.kotlin.descriptors.Modality
+import org.jetbrains.kotlin.ir.IrBuiltIns
+import org.jetbrains.kotlin.ir.IrElement
+import org.jetbrains.kotlin.ir.IrStatement
+import org.jetbrains.kotlin.ir.builders.irCallConstructor
+import org.jetbrains.kotlin.ir.declarations.*
+import org.jetbrains.kotlin.ir.expressions.*
+import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
+import org.jetbrains.kotlin.ir.expressions.impl.IrReturnImpl
+import org.jetbrains.kotlin.ir.symbols.IrReturnTargetSymbol
+import org.jetbrains.kotlin.ir.symbols.UnsafeDuringIrConstructionAPI
+import org.jetbrains.kotlin.ir.types.*
+import org.jetbrains.kotlin.ir.util.constructors
+import org.jetbrains.kotlin.ir.util.kotlinFqName
+import org.jetbrains.kotlin.ir.util.parentAsClass
+import org.jetbrains.kotlin.ir.util.primaryConstructor
+import org.jetbrains.kotlin.name.Name
+import org.jetbrains.kotlin.psi.KtFile
+
+internal class NonAbiDeclarationsStrippingIrExtension(
+    private val sourceFiles: List<KtFile>,
+    private val repairLog: AbiGenRepairLog,
+) : IrGenerationExtension {
+
+  private fun shouldStripAnnotation(annotation: IrConstructorCall): Boolean {
+    val annotationClass = annotation.symbol.owner.parent as? IrClass ?: return false
+    val annotationFqName = annotationClass.kotlinFqName.asString()
+
+    // Keep @Throws annotation in IR to generate bytecode throws clause for Java interop.
+    // The JVM backend (FunctionCodegen.getThrownExceptions) reads @Throws from IR annotations
+    // to generate the method's throws clause. If we strip it here, Java code cannot catch
+    // checked exceptions because the throws clause won't be in bytecode.
+    // Note: K2 JVM backend writes @Throws to both throws clause AND RuntimeInvisibleAnnotations.
+    // We strip it from RuntimeInvisibleAnnotations via bytecode post-processing (see
+    // ThrowsAnnotationStripper) to match K1 behavior and prevent Safe Kotlin errors.
+    if (annotationFqName == "kotlin.jvm.Throws" || annotationFqName == "kotlin.Throws") {
+      return false
+    }
+
+    // Strip SOURCE retention annotations (not needed in ABI)
+    for (retentionAnnotation in annotationClass.annotations) {
+      val retentionClass = retentionAnnotation.symbol.owner.parent as? IrClass ?: continue
+      if (retentionClass.kotlinFqName.asString() == "kotlin.annotation.Retention") {
+        if (retentionAnnotation.valueArgumentsCount > 0) {
+          val arg = retentionAnnotation.getValueArgument(0)
+          if (arg is IrGetEnumValue && arg.symbol.owner.name.asString() == "SOURCE") {
+            return true
+          }
+        }
+      }
+    }
+    return false
+  }
+
+  // Check if an annotation contains error types in its arguments.
+  // Error types occur when K2 cannot resolve constants from source-only ABI dependencies.
+  // These annotations cause crashes during constant evaluation, so we strip them.
+  private fun hasErrorType(annotation: IrConstructorCall): Boolean {
+    for (i in 0 until annotation.valueArgumentsCount) {
+      val arg = annotation.getValueArgument(i)
+      if (arg != null && containsErrorType(arg)) {
+        return true
+      }
+    }
+    return false
+  }
+
+  // Recursively check if an IR expression contains error types
+  private fun containsErrorType(expression: IrExpression): Boolean {
+    // Check if the expression's type is an error type
+    if (expression.type is IrErrorType) {
+      return true
+    }
+
+    // For class references (like IOException::class in @Throws), check if the referenced type
+    // is an error type. This handles cases where @Throws has unresolved exception classes.
+    if (expression is IrClassReference && expression.classType is IrErrorType) {
+      return true
+    }
+
+    // For varargs (like @Throws(E1::class, E2::class)), check all elements
+    if (expression is IrVararg) {
+      for (element in expression.elements) {
+        if (element is IrExpression && containsErrorType(element)) {
+          return true
+        }
+      }
+    }
+
+    // Recursively check children
+    var hasError = false
+    expression.acceptChildren(
+        object : IrElementVisitorVoidCompat() {
+          override fun visitElement(element: IrElement) {
+            if (element is IrExpression && element.type is IrErrorType) {
+              hasError = true
+            }
+            // Also check class references in children
+            if (element is IrClassReference && element.classType is IrErrorType) {
+              hasError = true
+            }
+            element.acceptChildren(this, null)
+          }
+        },
+        null,
+    )
+    return hasError
+  }
+
+  private fun stripSourceRetentionAnnotations(moduleFragment: IrModuleFragment) {
+    moduleFragment.accept(
+        object : IrElementVisitorVoidCompat() {
+          override fun visitElement(element: IrElement) {
+            element.acceptChildren(this, null)
+          }
+
+          override fun visitClass(declaration: IrClass) {
+            declaration.annotations =
+                declaration.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            super.visitClass(declaration)
+          }
+
+          override fun visitSimpleFunction(declaration: IrSimpleFunction) {
+            declaration.annotations =
+                declaration.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            declaration.valueParameters.forEach { param ->
+              param.annotations =
+                  param.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            }
+            super.visitSimpleFunction(declaration)
+          }
+
+          override fun visitField(declaration: IrField) {
+            declaration.annotations =
+                declaration.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            super.visitField(declaration)
+          }
+
+          override fun visitProperty(declaration: IrProperty) {
+            declaration.annotations =
+                declaration.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            super.visitProperty(declaration)
+          }
+
+          override fun visitConstructor(declaration: IrConstructor) {
+            declaration.annotations =
+                declaration.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            declaration.valueParameters.forEach { param ->
+              param.annotations =
+                  param.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            }
+            super.visitConstructor(declaration)
+          }
+        },
+        null,
+    )
+  }
+
+  @OptIn(UnsafeDuringIrConstructionAPI::class)
+  override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
+    // Filter out files generated from stubs, similar to K1 implementation
+    val stubs = sourceFiles.filter { it.isStub() }
+    val stubPaths: Set<String> = stubs.map { it.viewProvider.virtualFile.path }.toSet()
+
+    // Remove IR files that were generated from stubs
+    moduleFragment.files.removeAll { irFile -> stubPaths.contains(irFile.fileEntry.name) }
+
+    // Remove IR files for plugin-generated declarations (e.g., "__GENERATED DECLARATIONS__")
+    // These files contain stub declarations generated by our
+    // MissingConstantDeclarationGenerationExtension
+    // for FIR resolution of missing constants and transitive dependencies. They're temporary
+    // artifacts
+    // used during FIR analysis and should not be included in the final bytecode.
+    // Note: This filtering preserves legitimate plugin-generated methods like Parcelize's
+    // describeContents()/writeToParcel() which are generated directly in the class.
+    moduleFragment.files.removeAll { irFile ->
+      irFile.fileEntry.name.contains("__GENERATED DECLARATIONS__") ||
+          irFile.fileEntry.name.contains("GENERATED_DECLARATIONS")
+    }
+
+    // Strip SOURCE retention annotations from all declarations.
+    // SOURCE retention annotations (like @IntDef from androidx.annotation) should not appear
+    // in bytecode, but K2 preserves them. K1 Kosabi naturally omits them because source stubs
+    // don't carry meta-annotations. We strip them here at the IR level where we can inspect
+    // the annotation class's @Retention policy.
+    stripSourceRetentionAnnotations(moduleFragment)
+
+    moduleFragment.transform(
+        NonAbiDeclarationsStrippingIrVisitor(
+            pluginContext.irFactory,
+            pluginContext.irBuiltIns,
+            pluginContext,
+            repairLog,
+        ),
+        null,
+    )
+  }
+}
+
+@OptIn(UnsafeDuringIrConstructionAPI::class)
+internal class NonAbiDeclarationsStrippingIrVisitor(
+    private val irFactory: IrFactory,
+    private val irBuiltins: IrBuiltIns,
+    private val pluginContext: IrPluginContext,
+    private val repairLog: AbiGenRepairLog,
+) : IrElementTransformerVoidCompat() {
+
+  override fun visitFile(declaration: IrFile): IrFile {
+    declaration.removeNonPublicApi()
+    return super.visitFile(declaration)
+  }
+
+  override fun visitDeclaration(declaration: IrDeclarationBase): IrStatement {
+    if (declaration is IrDeclarationContainer) {
+      declaration.removeNonPublicApi()
+    }
+    return super.visitDeclaration(declaration)
+  }
+
+  override fun visitClass(declaration: IrClass): IrStatement {
+    // Strip supertypes whose class file the ABI jar will not contain, since the reference would
+    // dangle. Internal supertypes are kept because source-only ABI is consumed within the same
+    // module, where internal types are accessible. Stripping them would cause Java consumers
+    // to see "incompatible types" errors when a public class implements an internal interface.
+    val strippedSupertypes =
+        declaration.superTypes.filter { superType ->
+          val superClass = superType.classOrNull?.owner ?: return@filter false
+          isClassAbsentFromAbi(superClass)
+        }
+
+    declaration.superTypes =
+        declaration.superTypes.filter { superType ->
+          val superClass = superType.classOrNull?.owner ?: return@filter true
+          !isClassAbsentFromAbi(superClass)
+        }
+
+    // For each stripped supertype that was an interface, convert fake override methods
+    // that implement that interface to real methods with stub bodies.
+    // This is needed because the JVM backend skips generating bytecode for fake overrides.
+    if (strippedSupertypes.isNotEmpty()) {
+      convertFakeOverridesFromStrippedSupertypes(declaration, strippedSupertypes)
+    }
+
+    // Also convert fake override methods that override non-public API methods.
+    // This handles cases like enum entry classes where the fake override methods
+    // override methods from the parent enum class that in turn implements a private interface.
+    convertPublicFakeOverridesOfNonPublicMethods(declaration)
+
+    return super.visitClass(declaration)
+  }
+
+  // Convert public fake override methods that ultimately override non-public methods.
+  // This handles enum entry classes where getFlavor/getName are fake overrides that
+  // override the parent enum class's abstract methods (which themselves implement
+  // a stripped private interface).
+  private fun convertPublicFakeOverridesOfNonPublicMethods(irClass: IrClass) {
+    for (decl in irClass.declarations) {
+      if (decl !is IrSimpleFunction) continue
+      if (!decl.isFakeOverride) continue
+      if (!decl.visibility.isPublicAPI) continue
+
+      // Materialize only when the declaring class is gone from the ABI. If it survives -- any
+      // nested private class does -- the fake override still resolves, and emitting a body here
+      // would add a method the library jar does not have.
+      val shouldMaterialize =
+          decl.overriddenSymbols.any { overriddenSymbol ->
+            val overriddenParent = overriddenSymbol.owner.parent as? IrClass
+            overriddenParent != null && isClassAbsentFromAbi(overriddenParent)
+          }
+
+      if (shouldMaterialize) {
+        materializeFakeOverride(decl)
+      }
+    }
+  }
+
+  // Convert fake override methods that came from stripped supertypes to real methods.
+  // The JVM backend skips generating bytecode for fake overrides (isFakeOverride = true),
+  // so when we strip a private interface from a public class, we need to convert the
+  // fake override methods that implemented that interface to real methods with stub bodies.
+  private fun convertFakeOverridesFromStrippedSupertypes(
+      irClass: IrClass,
+      strippedSupertypes: List<IrType>,
+  ) {
+    // Collect method signatures from stripped interfaces
+    val strippedInterfaceSignatures = mutableSetOf<MethodSignature>()
+    for (superType in strippedSupertypes) {
+      val superClass = superType.classOrNull?.owner ?: continue
+      if (superClass.kind != ClassKind.INTERFACE) continue
+      for (decl in superClass.declarations) {
+        if (decl is IrSimpleFunction && !decl.isFakeOverride) {
+          strippedInterfaceSignatures.add(decl.methodSignature())
+        }
+      }
+    }
+
+    if (strippedInterfaceSignatures.isEmpty()) return
+
+    // Materialize fake override methods matching stripped interface signatures
+    materializeFakeOverridesMatching(irClass, strippedInterfaceSignatures)
+
+    // For enum classes, also process enum entry classes
+    // Enum entry classes (correspondingClass) inherit methods from the enum class, and when
+    // a private interface is stripped from the enum class, those methods become orphaned
+    // fake overrides in the enum entry classes too.
+    if (irClass.kind == ClassKind.ENUM_CLASS) {
+      for (enumEntry in irClass.declarations.filterIsInstance<IrEnumEntry>()) {
+        val entryClass = enumEntry.correspondingClass ?: continue
+        materializeFakeOverridesMatching(entryClass, strippedInterfaceSignatures)
+      }
+    }
+  }
+
+  // Convert a fake override to a real method with a stub body.
+  private fun materializeFakeOverride(decl: IrSimpleFunction) {
+    decl.isFakeOverride = false
+    decl.modality = Modality.FINAL
+    decl.origin = IrDeclarationOrigin.DEFINED
+    if (decl.body == null) {
+      decl.body =
+          generateDefaultBody(decl.returnType, decl.symbol) ?: irFactory.createBlockBody(-1, -1)
+    }
+  }
+
+  // Find and materialize public fake override methods whose signature matches
+  // a method from a stripped interface.
+  private fun materializeFakeOverridesMatching(
+      irClass: IrClass,
+      signatures: Set<MethodSignature>,
+  ) {
+    for (decl in irClass.declarations) {
+      if (decl !is IrSimpleFunction) continue
+      if (!decl.isFakeOverride) continue
+      if (!decl.visibility.isPublicAPI) continue
+      if (decl.methodSignature() in signatures) {
+        materializeFakeOverride(decl)
+      }
+    }
+  }
+
+  // True when removeNonPublicApi will drop this class from the ABI, which is the only reason a
+  // supertype has to leave a supertype list. Only top-level private classes are dropped; a nested
+  // private class is kept, so a `private sealed class`/`sealed interface` and everything nested
+  // under it stays referenceable and must keep appearing as a supertype.
+  private fun isClassAbsentFromAbi(irClass: IrClass): Boolean {
+    var current: IrClass = irClass
+    while (true) {
+      if (current.visibility == DescriptorVisibilities.LOCAL) {
+        return true
+      }
+      val outer = current.parent as? IrClass
+      if (outer == null) {
+        return current.visibility == DescriptorVisibilities.PRIVATE
+      }
+      current = outer
+    }
+  }
+
+  override fun visitField(declaration: IrField): IrStatement {
+    // For fields with initializers containing function calls,
+    // replace the initializer with a default constant value.
+    // This handles cases like: const val X = (10 * TimeConstants.MS_PER_SECOND).toInt()
+    // where the initializer contains a function call that can't be evaluated at compile time
+    // in source-only ABI mode.
+    // We specifically check for IrCall to avoid replacing valid expressions like unary minus
+    // (-1).
+    val initializer = declaration.initializer
+    if (initializer != null) {
+      val expression = initializer.expression
+      if (containsFunctionCalls(expression)) {
+        // Replace with a default constant value based on the field type
+        val defaultExpressionBody = generateDefaultExpressionBody(declaration.type)
+        if (defaultExpressionBody != null) {
+          declaration.initializer = defaultExpressionBody
+          // For a non-const field this only affects the initializer, which is not part of the
+          // ABI. For a const val it rewrites the ConstantValue attribute consumers inline.
+          val ownerPrefix = (declaration.parent as? IrClass)?.kotlinFqName?.asString()?.plus(".")
+          repairLog.recordReplacedFieldInitializer(
+              (ownerPrefix ?: "") + declaration.name.asString(),
+              "initializer contained a call that source-only ABI cannot evaluate; " +
+                  "replaced with the default value for ${declaration.type.classFqName?.asString()}",
+          )
+        }
+      }
+    }
+    return super.visitField(declaration)
+  }
+
+  // Check if an expression tree contains any function calls
+  private fun containsFunctionCalls(expression: IrExpression): Boolean {
+    if (expression is IrCall) return true
+    var hasCall = false
+    expression.acceptChildren(
+        object : IrElementVisitorVoidCompat() {
+          override fun visitElement(element: IrElement) {
+            if (element is IrCall) hasCall = true
+            element.acceptChildren(this, null)
+          }
+        },
+        null,
+    )
+    return hasCall
+  }
+
+  // we shouldn't generate default values for constants becuase the values are getting inlined
+  // TODO: fix it: T235115614
+  private fun generateDefaultValue(type: IrType): IrExpression? {
+    val constructedType = type as? IrSimpleType ?: return null
+
+    // For primitive types, create a default constant value
+    // The code handles properties like val DEFAULT_SHADOW_COLOR: Int = Color.argb(128, 0, 0, 0)
+    // If we don't set a default value, compiler crashes because it expects a ConstExpression
+    // Primitives are matched by classifier (isInt/isLong/...) rather than by instance equality with
+    // irBuiltins: a value class deserialized from another module carries a non-canonical underlying
+    // primitive type that is not `==` to irBuiltins.longType, and matching it by instance used to
+    // drop through to the null branch -- storing ACONST_NULL into an unboxed primitive slot. The
+    // predicates are non-null-only, so a nullable primitive (a boxed, reference slot) still falls
+    // through to null, which is correct there.
+    var defaultValue: IrExpression? =
+        when {
+          constructedType.isInt() -> IrConstImpl.int(-1, -1, irBuiltins.intType, 0)
+          constructedType.isBoolean() -> IrConstImpl.boolean(-1, -1, irBuiltins.booleanType, false)
+          constructedType.isString() -> IrConstImpl.string(-1, -1, irBuiltins.stringType, "")
+          constructedType.isDouble() -> IrConstImpl.double(-1, -1, irBuiltins.doubleType, 0.0)
+          constructedType.isFloat() -> IrConstImpl.float(-1, -1, irBuiltins.floatType, 0.0f)
+          constructedType.isLong() -> IrConstImpl.long(-1, -1, irBuiltins.longType, 0L)
+          constructedType.isChar() -> IrConstImpl.char(-1, -1, irBuiltins.charType, '\u0000')
+          constructedType.isByte() -> IrConstImpl.byte(-1, -1, irBuiltins.byteType, 0)
+          constructedType.isShort() -> IrConstImpl.short(-1, -1, irBuiltins.shortType, 0)
+          else ->
+              // For value/inline classes (e.g. Compose's `Color`, which wraps `ULong`/`long`) a
+              // null default is wrong: the JVM slot is the unboxed primitive, so the
+              // compiler-generated `<fn>$default` method would emit ACONST_NULL into e.g. a `long`
+              // slot and fail bytecode verification ("Expected J, but found R"). Build a boxed
+              // default from the underlying primitive so inline-class lowering unboxes it to the
+              // correct primitive zero. Falls back to null for everything else.
+              generateInlineClassDefaultValue(constructedType)
+                  ?: IrConstImpl.constNull(
+                      -1,
+                      -1,
+                      constructedType.makeNullable(),
+                  ) // If we can't handle this type, return null
+        }
+
+    return defaultValue
+  }
+
+  // Build a default value for a non-null value/inline class over a primitive, whose `<fn>$default`
+  // slot is the *unboxed* primitive. Returns null (leaving the caller's ACONST_NULL fallback) for a
+  // non-value class or a nullable value class -- which is boxed, so its slot is a reference and
+  // null
+  // is correct.
+  //
+  // The underlying primitive is read from the class's inline-class representation, which survives
+  // deserialization even when the value class's constructor does not: a value class reached through
+  // a source-only-ABI dependency deserializes with zero constructors (e.g. WA
+  // `TranscriptionStatus`,
+  // `ctors=0`). When a constructor *is* materialized we invoke it, so inline-class lowering unboxes
+  // the call to the primitive zero (ICONST_0/LCONST_0). When it is not, we emit the underlying
+  // primitive directly -- the slot is already that primitive, so a bare zero verifies -- rather
+  // than
+  // dropping through to ACONST_NULL and failing bytecode verification ("Expected I, but found R").
+  private fun generateInlineClassDefaultValue(type: IrSimpleType): IrExpression? {
+    val irClass = type.classOrNull?.owner ?: return null
+    if (!irClass.isValue) return null
+    if (type.isNullable()) return null
+    val constructor = irClass.primaryConstructor ?: irClass.constructors.singleOrNull()
+    val underlyingType =
+        irClass.inlineClassRepresentation?.underlyingType
+            ?: constructor?.valueParameters?.singleOrNull()?.type
+            ?: return null
+    val underlyingDefault = generateDefaultValue(underlyingType) ?: return null
+    return if (constructor != null && constructor.valueParameters.size == 1) {
+      DeclarationIrBuilder(pluginContext, constructor.symbol)
+          .irCallConstructor(constructor.symbol, emptyList())
+          .apply { putValueArgument(0, underlyingDefault) }
+    } else {
+      underlyingDefault
+    }
+  }
+
+  private fun IrDeclarationContainer.removeNonPublicApi() {
+    // For inline/value classes, we need to keep the backing field even if it's private
+    val inlineClassBackingFieldName =
+        (this as? IrClass)?.inlineClassRepresentation?.underlyingPropertyName
+
+    this.declarations.filterIsInstance<IrProperty>().forEach { property ->
+      if (property.isDelegated) property.backingField = null
+    }
+
+    this.declarations.removeAll { declaration ->
+      // Keep constructors (needed for instantiation)
+      if (declaration is IrConstructor) return@removeAll false
+      // Keep companion objects (may contain public members)
+      if ((declaration as? IrClass)?.isCompanion == true) return@removeAll false
+
+      // Keep nested/inner classes even if private. They generate separate .class files
+      // referenced via the InnerClasses attribute, constant pool entries, and Kotlin
+      // @Metadata. Stripping the class but keeping these references causes javac to fail
+      // with "class file not found" errors. K1 Kosabi keeps them as stubs — their private
+      // members are stripped recursively and method bodies are stubbed by the visitor.
+      // Note: `this is IrClass` ensures this only applies to nested classes (parent is a
+      // class). Top-level private classes (parent is IrFile) are still stripped.
+      if (declaration is IrClass && this is IrClass) return@removeAll false
+
+      // Keep backing field/property of inline/value classes (required even if private)
+      if (declaration.isInlineClassBackingMember(inlineClassBackingFieldName))
+          return@removeAll false
+
+      if (declaration.isPropertyDelegateBackingField()) return@removeAll true
+
+      // Keep synthetic declarations (generated by compiler)
+      if (declaration.origin.isSynthetic) return@removeAll false
+
+      // Remove private/local members only (NOT internal - K1 kept internal in ABI)
+      val visibility = (declaration as? IrDeclarationWithVisibility)?.visibility
+      visibility == DescriptorVisibilities.PRIVATE ||
+          visibility == DescriptorVisibilities.PRIVATE_TO_THIS ||
+          visibility == DescriptorVisibilities.LOCAL
+    }
+  }
+
+  private fun IrDeclaration.isPropertyDelegateBackingField(): Boolean =
+      this is IrField &&
+          visibility == DescriptorVisibilities.PRIVATE &&
+          origin == IrDeclarationOrigin.PROPERTY_DELEGATE
+
+  private fun IrDeclaration.isInlineClassBackingMember(backingFieldName: Name?): Boolean {
+    if (backingFieldName == null) return false
+    return (this is IrField || this is IrProperty) &&
+        (this as IrDeclarationWithName).name == backingFieldName
+  }
+
+  private fun generateDefaultReturnStatement(
+      type: IrType,
+      symbol: IrReturnTargetSymbol,
+  ): IrReturn? {
+    val defaultValue = generateDefaultValue(type) ?: return null
+    return IrReturnImpl(-1, -1, irBuiltins.nothingType, symbol, defaultValue)
+  }
+
+  private fun generateDefaultBody(type: IrType, symbol: IrReturnTargetSymbol): IrBody? {
+    val returnStatement = generateDefaultReturnStatement(type, symbol) ?: return null
+    return irFactory.createBlockBody(-1, -1).apply { this.statements.add(returnStatement) }
+  }
+
+  private fun generateDefaultExpressionBody(type: IrType): IrExpressionBody? {
+    val defaultValue = generateDefaultValue(type) ?: return null
+    return irFactory.createExpressionBody(-1, -1, defaultValue)
+  }
+
+  // Replace each defaulted value parameter's default with a fabricated, type-correct default.
+  // For source-only ABI only the presence and type of a default matter, not its value. This
+  // turns a value-class-over-primitive default into a boxed constructor call, which inline-class
+  // lowering unboxes to the primitive zero, rather than the ACONST_NULL codegen would otherwise
+  // store into the synthetic `$default` overload's unboxed slot ("Expected I, but found R").
+  // Shared by visitSimpleFunction and visitConstructor -- the latter is where the WA
+  // TranscriptionViewModel.VmState `<init>$default` crash lived.
+  private fun regenerateDefaultParameterValues(function: IrFunction) {
+    function.valueParameters
+        .filter { it.defaultValue != null }
+        .forEach { parameter ->
+          generateDefaultExpressionBody(parameter.type)?.let { parameter.defaultValue = it }
+        }
+  }
+
+  override fun visitSimpleFunction(declaration: IrSimpleFunction): IrStatement {
+    if (!declaration.origin.isSynthetic) {
+      if (declaration.parent is IrProperty) {
+        // for properties we need to generate a default body
+        // otherwise we get a crash in the compiler
+        // handles properties likeval DEFAULT_SHADOW_COLOR: Int = Color.argb(128, 0, 0, 0)
+        // we shouldn't generate default values for constants becuase the values are getting
+        // inlined
+        // TODO: fix it: T235115614
+        val body = generateDefaultBody(declaration.returnType, declaration.symbol)
+        declaration.body = body ?: irFactory.createBlockBody(-1, -1)
+      } else {
+        declaration.body = irFactory.createBlockBody(-1, -1)
+      }
+      // handles default values in functions like fun foo(x: Int = Something.SomeValue)
+      regenerateDefaultParameterValues(declaration)
+    }
+    return super.visitSimpleFunction(declaration)
+  }
+
+  override fun visitConstructor(declaration: IrConstructor): IrStatement {
+    // A defaulted value-class-over-primitive constructor parameter reaches the synthetic
+    // `<init>$default` with an unboxed slot; regenerate its default as visitSimpleFunction does
+    // so the slot gets the unboxed primitive zero rather than ACONST_NULL. Bodies are left to the
+    // default traversal -- unlike 2.3.0, this compiler path needs no constructor body stubbing.
+    // Skip annotation classes: their constructor parameter defaults ARE the ABI (the
+    // `AnnotationDefault` attribute), so regenerating them drops the element default and breaks
+    // consumers ("annotation @X is missing a default value for the element ...").
+    if (declaration.parentAsClass.kind != ClassKind.ANNOTATION_CLASS) {
+      regenerateDefaultParameterValues(declaration)
+    }
+    return super.visitConstructor(declaration)
+  }
+
+  override fun visitAnonymousInitializer(
+      declaration: IrAnonymousInitializer,
+  ): IrStatement {
+    // we also need to strip bodies from init {} blocks
+    declaration.body = irFactory.createBlockBody(-1, -1)
+    return super.visitAnonymousInitializer(declaration)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/IrVisitorCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/IrVisitorCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/IrVisitorCompat.kt
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+typealias IrElementVisitorVoidCompat = org.jetbrains.kotlin.ir.visitors.IrVisitorVoid
+
+typealias IrElementTransformerVoidCompat = org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/MetadataVersionCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/MetadataVersionCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/MetadataVersionCompat.kt
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.metadata.deserialization.MetadataVersion
+
+fun currentMetadataVersionArray(): IntArray = MetadataVersion.INSTANCE.toArray()
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/OptInAnnotationsCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/OptInAnnotationsCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/OptInAnnotationsCompat.kt
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+@RequiresOptIn annotation class DeprecatedForRemovalCompilerApiCompat
+
+@RequiresOptIn annotation class DirectDeclarationsAccessCompat
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/PipelineCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/PipelineCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.2.0/PipelineCompat.kt
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress(
+    "PackageLocationMismatch",
+    "DEPRECATION",
+    "DEPRECATION_ERROR",
+    "TYPEALIAS_EXPANSION_DEPRECATION",
+    "TYPEALIAS_EXPANSION_DEPRECATION_ERROR",
+)
+@file:OptIn(org.jetbrains.kotlin.cli.common.LegacyK2CliPipeline::class)
+
+package com.facebook
+
+import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
+import org.jetbrains.kotlin.cli.common.messages.MessageCollector
+import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.ModuleCompilerEnvironment
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.ModuleCompilerIrBackendInput
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.ModuleCompilerOutput
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.convertToIrAndActualizeForJvm
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.createProjectEnvironment
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.generateCodeFromIr
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.diagnostics.impl.BaseDiagnosticsCollector
+import org.jetbrains.kotlin.fir.backend.jvm.JvmFir2IrExtensions
+import org.jetbrains.kotlin.fir.pipeline.FirResult
+
+@Suppress("DEPRECATION_ERROR")
+typealias ModuleCompilerEnvironmentCompat = ModuleCompilerEnvironment
+
+typealias ModuleCompilerIrBackendInputCompat = ModuleCompilerIrBackendInput
+
+@Suppress("DEPRECATION_ERROR")
+typealias ModuleCompilerOutputCompat = ModuleCompilerOutput
+
+fun FirResult.convertToIrAndActualizeForJvmCompat(
+    fir2IrExtensions: JvmFir2IrExtensions,
+    configuration: CompilerConfiguration,
+    diagnosticsReporter: BaseDiagnosticsCollector,
+    irGeneratorExtensions: Collection<IrGenerationExtension>,
+) = convertToIrAndActualizeForJvm(
+    fir2IrExtensions,
+    configuration,
+    diagnosticsReporter,
+    irGeneratorExtensions,
+)
+
+fun createProjectEnvironmentCompat(
+    configuration: CompilerConfiguration,
+    parentDisposable: org.jetbrains.kotlin.com.intellij.openapi.Disposable,
+    configFiles: EnvironmentConfigFiles,
+    messageCollector: MessageCollector,
+) = createProjectEnvironment(configuration, parentDisposable, configFiles, messageCollector)
+
+@Suppress("DEPRECATION_ERROR")
+fun generateCodeFromIrCompat(
+    irInput: ModuleCompilerIrBackendInputCompat,
+    environment: ModuleCompilerEnvironmentCompat,
+) = generateCodeFromIr(irInput, environment)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/DependencyListCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/DependencyListCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/DependencyListCompat.kt
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.fir.DependencyListForCliModule
+import org.jetbrains.kotlin.fir.FirModuleData
+
+val DependencyListForCliModule.friendDependenciesCompat: List<FirModuleData>
+  get() = friendDependencies
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirCollectionLiteralCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirCollectionLiteralCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirCollectionLiteralCompat.kt
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+// FirArrayLiteral was renamed to FirCollectionLiteral in Kotlin 2.3.
+typealias FirCollectionLiteralCompat = org.jetbrains.kotlin.fir.expressions.FirCollectionLiteral
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirDefaultVisitorVoidCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirDefaultVisitorVoidCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirDefaultVisitorVoidCompat.kt
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.fir.declarations.FirNamedFunction
+import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitorVoid
+
+// In Kotlin 2.2 the visitor callback is visitSimpleFunction(FirSimpleFunction); in 2.3 it was
+// renamed to visitNamedFunction(FirNamedFunction). Bridge both to visitNamedFunctionCompat.
+// FirNamedFunctionCompat is declared in FrontendPipelineCompat.kt (same package).
+abstract class FirDefaultVisitorVoidCompat : FirDefaultVisitorVoid() {
+  abstract fun visitNamedFunctionCompat(namedFunction: FirNamedFunctionCompat)
+
+  override fun visitNamedFunction(namedFunction: FirNamedFunction) {
+    visitNamedFunctionCompat(namedFunction)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirNamedFunctionCopyCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirNamedFunctionCopyCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirNamedFunctionCopyCompat.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.fir.declarations.builder.FirNamedFunctionBuilder
+import org.jetbrains.kotlin.fir.declarations.builder.buildNamedFunctionCopy
+
+typealias FirNamedFunctionBuilderCompat = FirNamedFunctionBuilder
+
+// buildSimpleFunctionCopy was renamed to buildNamedFunctionCopy in Kotlin 2.3.
+inline fun buildNamedFunctionCopyCompat(
+    original: FirNamedFunctionCompat,
+    init: FirNamedFunctionBuilderCompat.() -> Unit,
+): FirNamedFunctionCompat = buildNamedFunctionCopy(original, init)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirResultCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirResultCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirResultCompat.kt
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+typealias FirResultCompat = org.jetbrains.kotlin.fir.pipeline.AllModulesFrontendOutput
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirSourceModuleDataCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirSourceModuleDataCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FirSourceModuleDataCompat.kt
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.fir.FirModuleData
+import org.jetbrains.kotlin.fir.FirSourceModuleData
+import org.jetbrains.kotlin.name.Name
+import org.jetbrains.kotlin.platform.TargetPlatform
+
+fun createSourceModuleData(
+    name: Name,
+    dependencies: List<FirModuleData>,
+    dependsOnDependencies: List<FirModuleData>,
+    friendDependencies: List<FirModuleData>,
+    platform: TargetPlatform,
+): FirModuleData {
+  return FirSourceModuleData(
+      name,
+      dependencies,
+      dependsOnDependencies,
+      friendDependencies,
+      platform,
+  )
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FrontendPipelineCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FrontendPipelineCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/FrontendPipelineCompat.kt
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress(
+    "PackageLocationMismatch",
+    "DEPRECATION",
+    "DEPRECATION_ERROR",
+)
+
+package com.facebook
+
+import org.jetbrains.kotlin.cli.common.messages.MessageCollector
+import org.jetbrains.kotlin.cli.jvm.compiler.VfsBasedProjectEnvironment
+import org.jetbrains.kotlin.cli.jvm.compiler.createLibraryListForJvm
+import org.jetbrains.kotlin.cli.pipeline.jvm.JvmFrontendPipelinePhase
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.diagnostics.DiagnosticReporterFactory
+import org.jetbrains.kotlin.diagnostics.impl.BaseDiagnosticsCollector
+import org.jetbrains.kotlin.fir.FirSession
+import org.jetbrains.kotlin.fir.declarations.FirFile
+import org.jetbrains.kotlin.fir.declarations.FirNamedFunction
+import org.jetbrains.kotlin.fir.pipeline.AllModulesFrontendOutput
+import org.jetbrains.kotlin.fir.pipeline.SingleModuleFrontendOutput
+import org.jetbrains.kotlin.fir.resolve.ScopeSession
+import org.jetbrains.kotlin.fir.session.IncrementalCompilationContext
+import org.jetbrains.kotlin.fir.session.environment.AbstractProjectFileSearchScope
+import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitorVoid
+import org.jetbrains.kotlin.name.Name
+import org.jetbrains.kotlin.psi.KtFile
+import org.jetbrains.kotlin.resolve.multiplatform.hmppModuleName
+
+/** Frontend analysis output wrapper. Was FirResult before Kotlin 2.3. */
+typealias FrontendOutputCompat = AllModulesFrontendOutput
+
+/** Per-module frontend output element. Was ModuleCompilerAnalyzedOutput before Kotlin 2.3. */
+typealias ModuleFrontendOutputCompat = SingleModuleFrontendOutput
+
+/** Source function declaration. Was FirSimpleFunction before Kotlin 2.3. */
+typealias FirNamedFunctionCompat = FirNamedFunction
+
+fun moduleFrontendOutputCompat(
+    session: FirSession,
+    scopeSession: ScopeSession,
+    fir: List<FirFile>,
+): ModuleFrontendOutputCompat = SingleModuleFrontendOutput(session, scopeSession, fir)
+
+fun frontendOutputCompat(outputs: List<ModuleFrontendOutputCompat>): FrontendOutputCompat =
+    AllModulesFrontendOutput(outputs)
+
+/**
+ * FIR visitor base that bridges the function visit method renamed in Kotlin 2.3
+ * (visitSimpleFunction -> visitNamedFunction). Subclasses implement [visitNamedFunctionCompat].
+ */
+abstract class FirNamedFunctionVisitorCompat : FirDefaultVisitorVoid() {
+  final override fun visitNamedFunction(namedFunction: FirNamedFunction) {
+    visitNamedFunctionCompat(namedFunction)
+  }
+
+  abstract fun visitNamedFunctionCompat(function: FirNamedFunctionCompat)
+}
+
+/** createPendingReporter dropped its MessageCollector parameter in Kotlin 2.3. */
+fun createPendingReporterCompat(messageCollector: MessageCollector): BaseDiagnosticsCollector =
+    DiagnosticReporterFactory.createPendingReporter()
+
+/** ModuleCompilerOutput.generationState.factory was flattened to .factory in Kotlin 2.3. */
+val ModuleCompilerOutputCompat.classFileFactoryCompat
+  get() = factory
+
+/** RETAIN_OUTPUT_IN_MEMORY is no longer required in Kotlin 2.3. */
+fun CompilerConfiguration.retainOutputInMemoryCompat() {
+  // No-op: output is no longer retained in memory in Kotlin 2.3.
+}
+
+/**
+ * Prepares the FIR JVM session(s) for the given source files. Kotlin 2.3 replaced the manual
+ * session-construction pipeline with JvmFrontendPipelinePhase.prepareJvmSessions.
+ */
+fun prepareJvmSessionsCompat(
+    ktFiles: List<KtFile>,
+    rootModuleName: String,
+    friendPaths: List<String>,
+    librariesScope: AbstractProjectFileSearchScope,
+    configuration: CompilerConfiguration,
+    projectEnvironment: VfsBasedProjectEnvironment,
+    providerAndScopeForIncrementalCompilation: IncrementalCompilationContext?,
+): List<Pair<FirSession, List<KtFile>>> {
+  val libraryList = createLibraryListForJvm(rootModuleName, configuration, friendPaths)
+  return JvmFrontendPipelinePhase.prepareJvmSessions(
+          ktFiles,
+          Name.special("<$rootModuleName>"),
+          configuration,
+          projectEnvironment,
+          librariesScope,
+          libraryList,
+          isCommonSource = { false },
+          isScript = { false },
+          fileBelongsToModule = { file: KtFile, moduleName: String ->
+            file.hmppModuleName == moduleName
+          },
+          createProviderAndScopeForIncrementalCompilation = {
+            providerAndScopeForIncrementalCompilation
+          },
+      )
+      .map { (session, sources) -> session to sources }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/IrNonAbiStripper.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/IrNonAbiStripper.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/IrNonAbiStripper.kt
@@ -0,0 +1,825 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+@file:Suppress("OPT_IN_USAGE_ERROR")
+@file:OptIn(
+    com.facebook.DeprecatedForRemovalCompilerApiCompat::class,
+    com.facebook.DirectDeclarationsAccessCompat::class,
+)
+
+package com.facebook
+
+import com.facebook.buck.jvm.kotlin.compilerplugins.common.isStub
+import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
+import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
+import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder
+import org.jetbrains.kotlin.descriptors.ClassKind
+import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
+import org.jetbrains.kotlin.descriptors.Modality
+import org.jetbrains.kotlin.ir.IrBuiltIns
+import org.jetbrains.kotlin.ir.IrElement
+import org.jetbrains.kotlin.ir.IrStatement
+import org.jetbrains.kotlin.ir.builders.irCallConstructor
+import org.jetbrains.kotlin.ir.builders.irDelegatingConstructorCall
+import org.jetbrains.kotlin.ir.declarations.*
+import org.jetbrains.kotlin.ir.expressions.*
+import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
+import org.jetbrains.kotlin.ir.expressions.impl.IrGetValueImpl
+import org.jetbrains.kotlin.ir.expressions.impl.IrInstanceInitializerCallImpl
+import org.jetbrains.kotlin.ir.expressions.impl.IrReturnImpl
+import org.jetbrains.kotlin.ir.symbols.IrReturnTargetSymbol
+import org.jetbrains.kotlin.ir.symbols.UnsafeDuringIrConstructionAPI
+import org.jetbrains.kotlin.ir.types.*
+import org.jetbrains.kotlin.ir.util.constructors
+import org.jetbrains.kotlin.ir.util.kotlinFqName
+import org.jetbrains.kotlin.ir.util.parentAsClass
+import org.jetbrains.kotlin.ir.util.primaryConstructor
+import org.jetbrains.kotlin.name.Name
+import org.jetbrains.kotlin.psi.KtFile
+
+internal class NonAbiDeclarationsStrippingIrExtension(
+    private val sourceFiles: List<KtFile>,
+    private val repairLog: AbiGenRepairLog,
+) : IrGenerationExtension {
+
+  private fun shouldStripAnnotation(annotation: IrConstructorCall): Boolean {
+    val annotationClass = annotation.symbol.owner.parent as? IrClass ?: return false
+    val annotationFqName = annotationClass.kotlinFqName.asString()
+
+    // Keep @Throws annotation in IR to generate bytecode throws clause for Java interop.
+    // The JVM backend (FunctionCodegen.getThrownExceptions) reads @Throws from IR annotations
+    // to generate the method's throws clause. If we strip it here, Java code cannot catch
+    // checked exceptions because the throws clause won't be in bytecode.
+    // Note: K2 JVM backend writes @Throws to both throws clause AND RuntimeInvisibleAnnotations.
+    // We strip it from RuntimeInvisibleAnnotations via bytecode post-processing (see
+    // ThrowsAnnotationStripper) to match K1 behavior and prevent Safe Kotlin errors.
+    if (annotationFqName == "kotlin.jvm.Throws" || annotationFqName == "kotlin.Throws") {
+      return false
+    }
+
+    // Strip SOURCE retention annotations (not needed in ABI)
+    for (retentionAnnotation in annotationClass.annotations) {
+      val retentionClass = retentionAnnotation.symbol.owner.parent as? IrClass ?: continue
+      if (retentionClass.kotlinFqName.asString() == "kotlin.annotation.Retention") {
+        if (retentionAnnotation.valueArgumentsCount > 0) {
+          val arg = retentionAnnotation.getValueArgument(0)
+          if (arg is IrGetEnumValue && arg.symbol.owner.name.asString() == "SOURCE") {
+            return true
+          }
+        }
+      }
+    }
+    return false
+  }
+
+  // Check if an annotation contains error types in its arguments.
+  // Error types occur when K2 cannot resolve constants from source-only ABI dependencies.
+  // These annotations cause crashes during constant evaluation, so we strip them.
+  private fun hasErrorType(annotation: IrConstructorCall): Boolean {
+    for (i in 0 until annotation.valueArgumentsCount) {
+      val arg = annotation.getValueArgument(i)
+      if (arg != null && containsErrorType(arg)) {
+        return true
+      }
+    }
+    return false
+  }
+
+  // Recursively check if an IR expression contains error types
+  private fun containsErrorType(expression: IrExpression): Boolean {
+    // Check if the expression's type is an error type
+    if (expression.type is IrErrorType) {
+      return true
+    }
+
+    // For class references (like IOException::class in @Throws), check if the referenced type
+    // is an error type. This handles cases where @Throws has unresolved exception classes.
+    if (expression is IrClassReference && expression.classType is IrErrorType) {
+      return true
+    }
+
+    // For varargs (like @Throws(E1::class, E2::class)), check all elements
+    if (expression is IrVararg) {
+      for (element in expression.elements) {
+        if (element is IrExpression && containsErrorType(element)) {
+          return true
+        }
+      }
+    }
+
+    // Recursively check children
+    var hasError = false
+    expression.acceptChildren(
+        object : IrElementVisitorVoidCompat() {
+          override fun visitElement(element: IrElement) {
+            if (element is IrExpression && element.type is IrErrorType) {
+              hasError = true
+            }
+            // Also check class references in children
+            if (element is IrClassReference && element.classType is IrErrorType) {
+              hasError = true
+            }
+            element.acceptChildren(this, null)
+          }
+        },
+        null,
+    )
+    return hasError
+  }
+
+  private fun stripSourceRetentionAnnotations(moduleFragment: IrModuleFragment) {
+    moduleFragment.accept(
+        object : IrElementVisitorVoidCompat() {
+          override fun visitElement(element: IrElement) {
+            element.acceptChildren(this, null)
+          }
+
+          override fun visitClass(declaration: IrClass) {
+            declaration.annotations =
+                declaration.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            super.visitClass(declaration)
+          }
+
+          override fun visitSimpleFunction(declaration: IrSimpleFunction) {
+            declaration.annotations =
+                declaration.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            declaration.valueParameters.forEach { param ->
+              param.annotations =
+                  param.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            }
+            super.visitSimpleFunction(declaration)
+          }
+
+          override fun visitField(declaration: IrField) {
+            declaration.annotations =
+                declaration.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            super.visitField(declaration)
+          }
+
+          override fun visitProperty(declaration: IrProperty) {
+            declaration.annotations =
+                declaration.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            super.visitProperty(declaration)
+          }
+
+          override fun visitConstructor(declaration: IrConstructor) {
+            declaration.annotations =
+                declaration.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            declaration.valueParameters.forEach { param ->
+              param.annotations =
+                  param.annotations.filter { !shouldStripAnnotation(it) && !hasErrorType(it) }
+            }
+            super.visitConstructor(declaration)
+          }
+        },
+        null,
+    )
+  }
+
+  @OptIn(UnsafeDuringIrConstructionAPI::class)
+  override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
+    // Filter out files generated from stubs, similar to K1 implementation
+    val stubs = sourceFiles.filter { it.isStub() }
+    val stubPaths: Set<String> = stubs.map { it.viewProvider.virtualFile.path }.toSet()
+
+    // Remove IR files that were generated from stubs
+    moduleFragment.files.removeAll { irFile -> stubPaths.contains(irFile.fileEntry.name) }
+
+    // Remove IR files for plugin-generated declarations (e.g., "__GENERATED DECLARATIONS__")
+    // These files contain stub declarations generated by our
+    // MissingConstantDeclarationGenerationExtension
+    // for FIR resolution of missing constants and transitive dependencies. They're temporary
+    // artifacts
+    // used during FIR analysis and should not be included in the final bytecode.
+    // Note: This filtering preserves legitimate plugin-generated methods like Parcelize's
+    // describeContents()/writeToParcel() which are generated directly in the class.
+    moduleFragment.files.removeAll { irFile ->
+      irFile.fileEntry.name.contains("__GENERATED DECLARATIONS__") ||
+          irFile.fileEntry.name.contains("GENERATED_DECLARATIONS")
+    }
+
+    // Strip SOURCE retention annotations from all declarations.
+    // SOURCE retention annotations (like @IntDef from androidx.annotation) should not appear
+    // in bytecode, but K2 preserves them. K1 Kosabi naturally omits them because source stubs
+    // don't carry meta-annotations. We strip them here at the IR level where we can inspect
+    // the annotation class's @Retention policy.
+    stripSourceRetentionAnnotations(moduleFragment)
+
+    moduleFragment.transform(
+        NonAbiDeclarationsStrippingIrVisitor(
+            pluginContext.irFactory,
+            pluginContext.irBuiltIns,
+            pluginContext,
+            repairLog,
+        ),
+        null,
+    )
+  }
+}
+
+@OptIn(UnsafeDuringIrConstructionAPI::class)
+internal class NonAbiDeclarationsStrippingIrVisitor(
+    private val irFactory: IrFactory,
+    private val irBuiltins: IrBuiltIns,
+    private val pluginContext: IrPluginContext,
+    private val repairLog: AbiGenRepairLog,
+) : IrElementTransformerVoidCompat() {
+
+  override fun visitFile(declaration: IrFile): IrFile {
+    declaration.removeNonPublicApi()
+    return super.visitFile(declaration)
+  }
+
+  override fun visitDeclaration(declaration: IrDeclarationBase): IrStatement {
+    if (declaration is IrDeclarationContainer) {
+      declaration.removeNonPublicApi()
+    }
+    return super.visitDeclaration(declaration)
+  }
+
+  override fun visitClass(declaration: IrClass): IrStatement {
+    // Strip supertypes whose class file the ABI jar will not contain, since the reference would
+    // dangle. Internal supertypes are kept because source-only ABI is consumed within the same
+    // module, where internal types are accessible. Stripping them would cause Java consumers
+    // to see "incompatible types" errors when a public class implements an internal interface.
+    val strippedSupertypes =
+        declaration.superTypes.filter { superType ->
+          val superClass = superType.classOrNull?.owner ?: return@filter false
+          isClassAbsentFromAbi(superClass)
+        }
+
+    declaration.superTypes =
+        declaration.superTypes.filter { superType ->
+          val superClass = superType.classOrNull?.owner ?: return@filter true
+          !isClassAbsentFromAbi(superClass)
+        }
+
+    // For each stripped supertype that was an interface, convert fake override methods
+    // that implement that interface to real methods with stub bodies.
+    // This is needed because the JVM backend skips generating bytecode for fake overrides.
+    if (strippedSupertypes.isNotEmpty()) {
+      convertFakeOverridesFromStrippedSupertypes(declaration, strippedSupertypes)
+    }
+
+    // Also convert fake override methods that override non-public API methods.
+    // This handles cases like enum entry classes where the fake override methods
+    // override methods from the parent enum class that in turn implements a private interface.
+    convertPublicFakeOverridesOfNonPublicMethods(declaration)
+
+    return super.visitClass(declaration)
+  }
+
+  // Convert public fake override methods that ultimately override non-public methods.
+  // This handles enum entry classes where getFlavor/getName are fake overrides that
+  // override the parent enum class's abstract methods (which themselves implement
+  // a stripped private interface).
+  private fun convertPublicFakeOverridesOfNonPublicMethods(irClass: IrClass) {
+    for (decl in irClass.declarations) {
+      if (decl !is IrSimpleFunction) continue
+      if (!decl.isFakeOverride) continue
+      if (!decl.visibility.isPublicAPI) continue
+
+      // Materialize only when the declaring class is gone from the ABI. If it survives -- any
+      // nested private class does -- the fake override still resolves, and emitting a body here
+      // would add a method the library jar does not have.
+      val shouldMaterialize =
+          decl.overriddenSymbols.any { overriddenSymbol ->
+            val overriddenParent = overriddenSymbol.owner.parent as? IrClass
+            overriddenParent != null && isClassAbsentFromAbi(overriddenParent)
+          }
+
+      if (shouldMaterialize) {
+        materializeFakeOverride(decl)
+      }
+    }
+  }
+
+  // Convert fake override methods that came from stripped supertypes to real methods.
+  // The JVM backend skips generating bytecode for fake overrides (isFakeOverride = true),
+  // so when we strip a private interface from a public class, we need to convert the
+  // fake override methods that implemented that interface to real methods with stub bodies.
+  private fun convertFakeOverridesFromStrippedSupertypes(
+      irClass: IrClass,
+      strippedSupertypes: List<IrType>,
+  ) {
+    // Collect method signatures from stripped interfaces
+    val strippedInterfaceSignatures = mutableSetOf<MethodSignature>()
+    for (superType in strippedSupertypes) {
+      val superClass = superType.classOrNull?.owner ?: continue
+      if (superClass.kind != ClassKind.INTERFACE) continue
+      for (decl in superClass.declarations) {
+        if (decl is IrSimpleFunction && !decl.isFakeOverride) {
+          strippedInterfaceSignatures.add(decl.methodSignature())
+        }
+      }
+    }
+
+    if (strippedInterfaceSignatures.isEmpty()) return
+
+    // Materialize fake override methods matching stripped interface signatures
+    materializeFakeOverridesMatching(irClass, strippedInterfaceSignatures)
+
+    // For enum classes, also process enum entry classes
+    // Enum entry classes (correspondingClass) inherit methods from the enum class, and when
+    // a private interface is stripped from the enum class, those methods become orphaned
+    // fake overrides in the enum entry classes too.
+    if (irClass.kind == ClassKind.ENUM_CLASS) {
+      for (enumEntry in irClass.declarations.filterIsInstance<IrEnumEntry>()) {
+        val entryClass = enumEntry.correspondingClass ?: continue
+        materializeFakeOverridesMatching(entryClass, strippedInterfaceSignatures)
+      }
+    }
+  }
+
+  // Convert a fake override to a real method with a stub body.
+  private fun materializeFakeOverride(decl: IrSimpleFunction) {
+    decl.isFakeOverride = false
+    decl.modality = Modality.FINAL
+    decl.origin = IrDeclarationOrigin.DEFINED
+    if (decl.body == null) {
+      decl.body =
+          generateDefaultBody(decl.returnType, decl.symbol) ?: irFactory.createBlockBody(-1, -1)
+    }
+  }
+
+  // Find and materialize public fake override methods whose signature matches
+  // a method from a stripped interface.
+  private fun materializeFakeOverridesMatching(
+      irClass: IrClass,
+      signatures: Set<MethodSignature>,
+  ) {
+    for (decl in irClass.declarations) {
+      if (decl !is IrSimpleFunction) continue
+      if (!decl.isFakeOverride) continue
+      if (!decl.visibility.isPublicAPI) continue
+      if (decl.methodSignature() in signatures) {
+        materializeFakeOverride(decl)
+      }
+    }
+  }
+
+  // True when removeNonPublicApi will drop this class from the ABI, which is the only reason a
+  // supertype has to leave a supertype list. Only top-level private classes are dropped; a nested
+  // private class is kept, so a `private sealed class`/`sealed interface` and everything nested
+  // under it stays referenceable and must keep appearing as a supertype.
+  private fun isClassAbsentFromAbi(irClass: IrClass): Boolean {
+    var current: IrClass = irClass
+    while (true) {
+      if (current.visibility == DescriptorVisibilities.LOCAL) {
+        return true
+      }
+      val outer = current.parent as? IrClass
+      if (outer == null) {
+        return current.visibility == DescriptorVisibilities.PRIVATE
+      }
+      current = outer
+    }
+  }
+
+  override fun visitField(declaration: IrField): IrStatement {
+    // For fields with initializers containing function calls,
+    // replace the initializer with a default constant value.
+    // This handles cases like: const val X = (10 * TimeConstants.MS_PER_SECOND).toInt()
+    // where the initializer contains a function call that can't be evaluated at compile time
+    // in source-only ABI mode.
+    // We specifically check for IrCall to avoid replacing valid expressions like unary minus
+    // (-1).
+    val initializer = declaration.initializer
+    if (initializer != null) {
+      val expression = initializer.expression
+      if (containsFunctionCalls(expression)) {
+        // Replace with a default constant value based on the field type
+        val defaultExpressionBody = generateDefaultExpressionBody(declaration.type)
+        if (defaultExpressionBody != null) {
+          declaration.initializer = defaultExpressionBody
+          // For a non-const field this only affects the initializer, which is not part of the
+          // ABI. For a const val it rewrites the ConstantValue attribute consumers inline.
+          val ownerPrefix = (declaration.parent as? IrClass)?.kotlinFqName?.asString()?.plus(".")
+          repairLog.recordReplacedFieldInitializer(
+              (ownerPrefix ?: "") + declaration.name.asString(),
+              "initializer contained a call that source-only ABI cannot evaluate; " +
+                  "replaced with the default value for ${declaration.type.classFqName?.asString()}",
+          )
+        }
+      }
+    }
+    return super.visitField(declaration)
+  }
+
+  // Replace any parameter default value that still holds an IrErrorExpression (Kosabi's
+  // 'Default Stub'/'skipBodies' placeholders) with a safe constant. For source-only ABI only the
+  // presence of a default matters, not its value, and ExpressionCodegen cannot emit error nodes.
+  private fun sanitizeErrorDefaultValues(function: IrFunction) {
+    for (parameter in function.valueParameters) {
+      val default = parameter.defaultValue ?: continue
+      if (default.containsErrorExpression()) {
+        parameter.defaultValue =
+            generateDefaultExpressionBody(parameter.type)
+                ?: irFactory.createExpressionBody(
+                    -1,
+                    -1,
+                    IrConstImpl.constNull(-1, -1, parameter.type.makeNullable()),
+                )
+      }
+    }
+  }
+
+  // Check if a body still contains an IrErrorExpression (e.g. Kosabi's SKIP_BODIES
+  // 'skipBodies' placeholder), which the JVM backend cannot generate code for.
+  private fun IrBody.containsErrorExpression(): Boolean {
+    var hasError = false
+    acceptChildren(
+        object : IrElementVisitorVoidCompat() {
+          override fun visitElement(element: IrElement) {
+            if (element is IrErrorExpression) hasError = true
+            element.acceptChildren(this, null)
+          }
+        },
+        null,
+    )
+    return hasError
+  }
+
+  // Check if an expression tree contains any function calls
+  private fun containsFunctionCalls(expression: IrExpression): Boolean {
+    if (expression is IrCall) return true
+    var hasCall = false
+    expression.acceptChildren(
+        object : IrElementVisitorVoidCompat() {
+          override fun visitElement(element: IrElement) {
+            if (element is IrCall) hasCall = true
+            element.acceptChildren(this, null)
+          }
+        },
+        null,
+    )
+    return hasCall
+  }
+
+  // we shouldn't generate default values for constants becuase the values are getting inlined
+  // TODO: fix it: T235115614
+  private fun generateDefaultValue(type: IrType): IrExpression? {
+    val constructedType = type as? IrSimpleType ?: return null
+
+    // For primitive types, create a default constant value
+    // The code handles properties like val DEFAULT_SHADOW_COLOR: Int = Color.argb(128, 0, 0, 0)
+    // If we don't set a default value, compiler crashes because it expects a ConstExpression
+    // Primitives are matched by classifier (isInt/isLong/...) rather than by instance equality with
+    // irBuiltins: a value class deserialized from another module carries a non-canonical underlying
+    // primitive type that is not `==` to irBuiltins.longType, and matching it by instance used to
+    // drop through to the null branch -- storing ACONST_NULL into an unboxed primitive slot. The
+    // predicates are non-null-only, so a nullable primitive (a boxed, reference slot) still falls
+    // through to null, which is correct there.
+    var defaultValue: IrExpression? =
+        when {
+          constructedType.isInt() -> IrConstImpl.int(-1, -1, irBuiltins.intType, 0)
+          constructedType.isBoolean() -> IrConstImpl.boolean(-1, -1, irBuiltins.booleanType, false)
+          constructedType.isString() -> IrConstImpl.string(-1, -1, irBuiltins.stringType, "")
+          constructedType.isDouble() -> IrConstImpl.double(-1, -1, irBuiltins.doubleType, 0.0)
+          constructedType.isFloat() -> IrConstImpl.float(-1, -1, irBuiltins.floatType, 0.0f)
+          constructedType.isLong() -> IrConstImpl.long(-1, -1, irBuiltins.longType, 0L)
+          constructedType.isChar() -> IrConstImpl.char(-1, -1, irBuiltins.charType, '\u0000')
+          constructedType.isByte() -> IrConstImpl.byte(-1, -1, irBuiltins.byteType, 0)
+          constructedType.isShort() -> IrConstImpl.short(-1, -1, irBuiltins.shortType, 0)
+          else ->
+              // For value/inline classes (e.g. Compose's `Color`, which wraps `ULong`/`long`) a
+              // null default is wrong: the JVM slot is the unboxed primitive, so the
+              // compiler-generated `<fn>$default` method would emit ACONST_NULL into e.g. a `long`
+              // slot and fail bytecode verification ("Expected J, but found R"). Build a boxed
+              // default from the underlying primitive so inline-class lowering unboxes it to the
+              // correct primitive zero. Falls back to null for everything else.
+              generateInlineClassDefaultValue(constructedType)
+                  ?: IrConstImpl.constNull(
+                      -1,
+                      -1,
+                      constructedType.makeNullable(),
+                  ) // If we can't handle this type, return null
+        }
+
+    return defaultValue
+  }
+
+  // Build a default value for a non-null value/inline class over a primitive, whose `<fn>$default`
+  // slot is the *unboxed* primitive. Returns null (leaving the caller's ACONST_NULL fallback) for a
+  // non-value class or a nullable value class -- which is boxed, so its slot is a reference and
+  // null
+  // is correct.
+  //
+  // The underlying primitive is read from the class's inline-class representation, which survives
+  // deserialization even when the value class's constructor does not: a value class reached through
+  // a source-only-ABI dependency deserializes with zero constructors (e.g. WA
+  // `TranscriptionStatus`,
+  // `ctors=0`). When a constructor *is* materialized we invoke it, so inline-class lowering unboxes
+  // the call to the primitive zero (ICONST_0/LCONST_0). When it is not, we emit the underlying
+  // primitive directly -- the slot is already that primitive, so a bare zero verifies -- rather
+  // than
+  // dropping through to ACONST_NULL and failing bytecode verification ("Expected I, but found R").
+  private fun generateInlineClassDefaultValue(type: IrSimpleType): IrExpression? {
+    val irClass = type.classOrNull?.owner ?: return null
+    if (!irClass.isValue) return null
+    if (type.isNullable()) return null
+    val constructor = irClass.primaryConstructor ?: irClass.constructors.singleOrNull()
+    val underlyingType =
+        irClass.inlineClassRepresentation?.underlyingType
+            ?: constructor?.valueParameters?.singleOrNull()?.type
+            ?: return null
+    val underlyingDefault = generateDefaultValue(underlyingType) ?: return null
+    return if (constructor != null && constructor.valueParameters.size == 1) {
+      DeclarationIrBuilder(pluginContext, constructor.symbol)
+          .irCallConstructor(constructor.symbol, emptyList())
+          .apply { putValueArgument(0, underlyingDefault) }
+    } else {
+      underlyingDefault
+    }
+  }
+
+  private fun IrDeclarationContainer.removeNonPublicApi() {
+    // For inline/value classes, we need to keep the backing field even if it's private
+    val inlineClassBackingFieldName =
+        (this as? IrClass)?.inlineClassRepresentation?.underlyingPropertyName
+
+    this.declarations.filterIsInstance<IrProperty>().forEach { property ->
+      if (property.isDelegated) property.backingField = null
+    }
+
+    this.declarations.removeAll { declaration ->
+      // Keep constructors (needed for instantiation)
+      if (declaration is IrConstructor) return@removeAll false
+      // Keep companion objects (may contain public members)
+      if ((declaration as? IrClass)?.isCompanion == true) return@removeAll false
+
+      // Keep nested/inner classes even if private. They generate separate .class files
+      // referenced via the InnerClasses attribute, constant pool entries, and Kotlin
+      // @Metadata. Stripping the class but keeping these references causes javac to fail
+      // with "class file not found" errors. K1 Kosabi keeps them as stubs — their private
+      // members are stripped recursively and method bodies are stubbed by the visitor.
+      // Note: `this is IrClass` ensures this only applies to nested classes (parent is a
+      // class). Top-level private classes (parent is IrFile) are still stripped.
+      if (declaration is IrClass && this is IrClass) return@removeAll false
+
+      // Keep backing field/property of inline/value classes (required even if private)
+      if (declaration.isInlineClassBackingMember(inlineClassBackingFieldName))
+          return@removeAll false
+
+      if (declaration.isPropertyDelegateBackingField()) return@removeAll true
+
+      // Keep synthetic declarations (generated by compiler)
+      if (declaration.origin.isSynthetic) return@removeAll false
+
+      // Remove private/local members only (NOT internal - K1 kept internal in ABI)
+      val visibility = (declaration as? IrDeclarationWithVisibility)?.visibility
+      visibility == DescriptorVisibilities.PRIVATE ||
+          visibility == DescriptorVisibilities.PRIVATE_TO_THIS ||
+          visibility == DescriptorVisibilities.LOCAL
+    }
+  }
+
+  private fun IrDeclaration.isPropertyDelegateBackingField(): Boolean =
+      this is IrField &&
+          visibility == DescriptorVisibilities.PRIVATE &&
+          origin == IrDeclarationOrigin.PROPERTY_DELEGATE
+
+  private fun IrDeclaration.isInlineClassBackingMember(backingFieldName: Name?): Boolean {
+    if (backingFieldName == null) return false
+    return (this is IrField || this is IrProperty) &&
+        (this as IrDeclarationWithName).name == backingFieldName
+  }
+
+  private fun generateDefaultReturnStatement(
+      type: IrType,
+      symbol: IrReturnTargetSymbol,
+  ): IrReturn? {
+    val defaultValue = generateDefaultValue(type) ?: return null
+    return IrReturnImpl(-1, -1, irBuiltins.nothingType, symbol, defaultValue)
+  }
+
+  private fun generateDefaultBody(type: IrType, symbol: IrReturnTargetSymbol): IrBody? {
+    val returnStatement = generateDefaultReturnStatement(type, symbol) ?: return null
+    return irFactory.createBlockBody(-1, -1).apply { this.statements.add(returnStatement) }
+  }
+
+  private fun generateDefaultExpressionBody(type: IrType): IrExpressionBody? {
+    val defaultValue = generateDefaultValue(type) ?: return null
+    return irFactory.createExpressionBody(-1, -1, defaultValue)
+  }
+
+  // Replace each defaulted value parameter's default with a fabricated, type-correct default.
+  // For source-only ABI only the presence and type of a default matter, not its value. This
+  // turns a value-class-over-primitive default into a boxed constructor call, which inline-class
+  // lowering unboxes to the primitive zero, rather than the ACONST_NULL codegen would otherwise
+  // store into the synthetic `$default` overload's unboxed slot ("Expected I, but found R").
+  // Shared by visitSimpleFunction and visitConstructor -- the latter is where the WA
+  // TranscriptionViewModel.VmState `<init>$default` crash lived.
+  private fun regenerateDefaultParameterValues(function: IrFunction) {
+    function.valueParameters
+        .filter { it.defaultValue != null }
+        .forEach { parameter ->
+          generateDefaultExpressionBody(parameter.type)?.let { parameter.defaultValue = it }
+        }
+  }
+
+  override fun visitSimpleFunction(declaration: IrSimpleFunction): IrStatement {
+    if (!declaration.origin.isSynthetic) {
+      if (declaration.parent is IrProperty) {
+        // for properties we need to generate a default body
+        // otherwise we get a crash in the compiler
+        // handles properties likeval DEFAULT_SHADOW_COLOR: Int = Color.argb(128, 0, 0, 0)
+        // we shouldn't generate default values for constants becuase the values are getting
+        // inlined
+        // TODO: fix it: T235115614
+        val body = generateDefaultBody(declaration.returnType, declaration.symbol)
+        declaration.body = body ?: irFactory.createBlockBody(-1, -1)
+      } else {
+        declaration.body = irFactory.createBlockBody(-1, -1)
+      }
+      // handles default values in functions like fun foo(x: Int = Something.SomeValue)
+      regenerateDefaultParameterValues(declaration)
+    } else if (declaration.body?.containsErrorExpression() == true) {
+      // Synthetic dispatchers -- most commonly the `<fn>$default` overload generated for a
+      // function/data-class member with default parameters -- keep a when/IrErrorExpression
+      // body from Kosabi's SKIP_BODIES that ExpressionCodegen cannot emit ("Unexpected IR
+      // element ... ERROR_EXPR 'skipBodies'"). Only the signature matters for source-only ABI,
+      // so stub the body. Mirrors the FUNCTION_FOR_DEFAULT_PARAMETER handling in
+      // visitConstructor. Other synthetic functions (valid compiler-generated bodies) are left
+      // untouched.
+      declaration.body =
+          if (declaration.parent is IrProperty)
+              generateDefaultBody(declaration.returnType, declaration.symbol)
+                  ?: irFactory.createBlockBody(-1, -1)
+          else irFactory.createBlockBody(-1, -1)
+    }
+    sanitizeErrorDefaultValues(declaration)
+    return super.visitSimpleFunction(declaration)
+  }
+
+  override fun visitConstructor(declaration: IrConstructor): IrStatement {
+    // Kosabi generates source-only ABI with JVMConfigurationKeys.SKIP_BODIES=true, so fir2ir
+    // drops constructor bodies -- including the delegating constructor call. Two symptoms:
+    //  - The JVM backend's ExpressionCodegen throws "Function has no body" for a bodyless
+    //    constructor (e.g. an enum's primary constructor in Kotlin 2.3).
+    //  - The synthetic default-parameter constructor (origin FUNCTION_FOR_DEFAULT_PARAMETER,
+    //    the `<init>(..., int mask, DefaultConstructorMarker)` overload) reaches codegen with a
+    //    body that still holds Kosabi's `skipBodies` IrErrorExpression placeholders, which
+    //    ExpressionCodegen cannot emit.
+    // A stub body must still carry a delegating constructor call: an empty body compiles to a
+    // bare RETURN and the JVM verifier rejects a constructor that returns without first calling
+    // super()/this() ("Constructor must call super() or this() before return"). ABI jars are
+    // compile-classpath-only, so only a well-formed delegating call matters, not its arguments
+    // (see createSuperDelegatingConstructorBody). Ordinary constructors whose delegating call
+    // fir2ir still emits are left untouched by the default traversal.
+    //
+    // Inner classes need extra care: the JVM pipeline runs InnerClassesLowering, which asserts
+    // that every inner-class constructor body contains an IrDelegatingConstructorCall (it
+    // rewrites that call to thread the outer `this`). A bodyless inner constructor is skipped by
+    // that lowering but then fails codegen; an *empty* stub body makes the lowering run and trip
+    // its "Delegating constructor call expected" assertion. So for inner-class constructors whose
+    // stripped body is not well-formed for that lowering we synthesize a trivial delegation to the
+    // superclass constructor (see the predicate below for exactly which shapes qualify).
+    val parentClass = declaration.parentAsClass
+    // A defaulted value-class-over-primitive constructor parameter reaches the synthetic
+    // `<init>$default` with an unboxed slot; regenerate its default as visitSimpleFunction does
+    // so the slot gets the unboxed primitive zero rather than ACONST_NULL. Skip annotation classes:
+    // their constructor parameter defaults ARE the ABI (the `AnnotationDefault` attribute), so
+    // regenerating them drops the element default and breaks consumers ("annotation @X is missing a
+    // default value for the element ...").
+    if (parentClass.kind != ClassKind.ANNOTATION_CLASS) {
+      regenerateDefaultParameterValues(declaration)
+    }
+    sanitizeErrorDefaultValues(declaration)
+    if (parentClass.isInner) {
+      // A stripped inner-class constructor body is well-formed for InnerClassesLowering only if it
+      // has an IrInstanceInitializerCall (super-delegation) or an IrDelegatingConstructorCall to
+      // this same class (this()-delegation). The lowering treats a body WITHOUT an instance
+      // initializer as a this()-delegation and threads the outer instance onto the delegating
+      // call's dispatch receiver; for a super-delegation -- e.g. silverstonedgw's `private inner
+      // class InternalListener(..) : SomeInterface`, whose only supertype is an interface so it
+      // super-delegates to kotlin.Any -- that crashes with "no argument slot for the corresponding
+      // dispatch receiver parameter". Any other shape (no delegating call, or a super-delegation
+      // that lost its instance initializer) is replaced with a synthesized super-delegation.
+      val existingBody = declaration.body as? IrBlockBody
+      val isBodyWellFormed =
+          existingBody != null &&
+              existingBody.statements.any {
+                it is IrInstanceInitializerCall ||
+                    (it is IrDelegatingConstructorCall &&
+                        it.symbol.owner.parentAsClass == parentClass)
+              }
+      if (!isBodyWellFormed) {
+        declaration.body =
+            createSuperDelegatingConstructorBody(declaration) ?: irFactory.createBlockBody(-1, -1)
+      }
+      return super.visitConstructor(declaration)
+    }
+
+    if (
+        declaration.body == null ||
+            declaration.origin == IrDeclarationOrigin.FUNCTION_FOR_DEFAULT_PARAMETER
+    ) {
+      // SKIP_BODIES dropped the delegating constructor call for a bodyless constructor (e.g. a
+      // primary constructor whose body was stripped) and left the synthetic <init>$default overload
+      // holding skipBodies error expressions. An empty replacement body is a bare RETURN that the
+      // JVM verifier rejects, so synthesize a well-formed delegation. Value-class secondary
+      // constructors must delegate to their primary constructor; other constructors delegate to
+      // their superclass as above.
+      declaration.body =
+          if (parentClass.isValue && parentClass.primaryConstructor != declaration) {
+            createValueClassDelegatingConstructorBody(declaration)
+                ?: irFactory.createBlockBody(-1, -1)
+          } else {
+            createSuperDelegatingConstructorBody(declaration) ?: irFactory.createBlockBody(-1, -1)
+          }
+    }
+    return super.visitConstructor(declaration)
+  }
+
+  /**
+   * Builds a body that delegates a value-class secondary constructor to its primary constructor.
+   * Kotlin 2.3 lowers a super-delegating stub to a STATIC_INLINE_CLASS_CONSTRUCTOR containing an
+   * INSTANCE_INITIALIZER_CALL, which JVM codegen cannot emit. A this()-delegation lowers to the
+   * expected constructor-impl that returns the underlying value.
+   */
+  private fun createValueClassDelegatingConstructorBody(constructor: IrConstructor): IrBody? {
+    val primaryConstructor = constructor.parentAsClass.primaryConstructor ?: return null
+    val builder = DeclarationIrBuilder(pluginContext, constructor.symbol)
+    val delegatingCall = builder.irDelegatingConstructorCall(primaryConstructor)
+    primaryConstructor.valueParameters.forEachIndexed { index, parameter ->
+      val defaultArgument =
+          generateDefaultValue(parameter.type)
+              ?: IrConstImpl.constNull(-1, -1, parameter.type.makeNullable())
+      delegatingCall.putValueArgument(index, defaultArgument)
+    }
+    return irFactory.createBlockBody(-1, -1).apply { statements.add(delegatingCall) }
+  }
+
+  /**
+   * Builds a constructor body with a delegating call to the owner class's superclass constructor
+   * (defaulting to kotlin.Any) plus an instance-initializer. SKIP_BODIES stripped the original
+   * delegating call, so without this the stub would be a bare RETURN (rejected by the JVM verifier)
+   * and, for an inner class, InnerClassesLowering would have no delegating call to find and
+   * rewrite. When the superclass constructor takes value parameters, fabricated default constants
+   * are passed -- for a compile-classpath-only ABI stub the argument values are irrelevant, only a
+   * well-formed call is. Returns null only when the superclass has no usable constructor.
+   */
+  @OptIn(org.jetbrains.kotlin.DeprecatedForRemovalCompilerApi::class)
+  private fun createSuperDelegatingConstructorBody(constructor: IrConstructor): IrBody? {
+    val ownerClass = constructor.parentAsClass
+    val superClass =
+        ownerClass.superTypes
+            .mapNotNull { it.classOrNull?.owner }
+            .firstOrNull { it.kind == ClassKind.CLASS } ?: irBuiltins.anyClass.owner
+    val superConstructor = superClass.primaryConstructor ?: superClass.constructors.firstOrNull()
+    if (superConstructor == null) {
+      return null
+    }
+    val builder = DeclarationIrBuilder(pluginContext, constructor.symbol)
+    val delegatingCall = builder.irDelegatingConstructorCall(superConstructor)
+    // If the superclass is itself an inner class, its constructor is invoked on the enclosing
+    // instance, so the delegating call carries a dispatch-receiver slot for it.
+    // InnerClassesLowering only threads the outer `this` for this()-delegations (not
+    // super-delegations), so populate it here with the current inner class's enclosing `this`;
+    // otherwise codegen sees a null dispatch receiver ("Null argument ... kind:DispatchReceiver").
+    if (superClass.isInner) {
+      ownerClass.parentAsClass.thisReceiver?.let { outerThis ->
+        delegatingCall.dispatchReceiver = IrGetValueImpl(-1, -1, outerThis.type, outerThis.symbol)
+      }
+    }
+    // Pass fabricated default arguments for any superclass constructor value parameters. For a
+    // compile-classpath-only ABI stub the values are irrelevant; codegen only needs a well-formed
+    // delegating call (an arg-less one leaves null slots / trips assertions).
+    superConstructor.valueParameters.forEachIndexed { index, param ->
+      val defaultArg =
+          generateDefaultValue(param.type)
+              ?: IrConstImpl.constNull(-1, -1, param.type.makeNullable())
+      delegatingCall.putValueArgument(index, defaultArg)
+    }
+    // InnerClassesLowering distinguishes a super-delegation from a this()-delegation by whether
+    // the body contains an IrInstanceInitializerCall. Without one it treats this as a
+    // this()-delegation and sets the outer instance as the delegating call's dispatch receiver --
+    // which the superclass constructor (e.g. kotlin.Any) has no argument slot for, crashing with
+    // "no argument slot for the corresponding dispatch receiver parameter". Emitting the
+    // instance-initializer marks it as a super-delegation, so the lowering initializes the
+    // outer-this field instead of rewriting the delegating call.
+    val instanceInitializer =
+        IrInstanceInitializerCallImpl(-1, -1, ownerClass.symbol, irBuiltins.unitType)
+    return irFactory.createBlockBody(-1, -1).apply {
+      statements.add(delegatingCall)
+      statements.add(instanceInitializer)
+    }
+  }
+
+  override fun visitAnonymousInitializer(
+      declaration: IrAnonymousInitializer,
+  ): IrStatement {
+    // we also need to strip bodies from init {} blocks
+    declaration.body = irFactory.createBlockBody(-1, -1)
+    return super.visitAnonymousInitializer(declaration)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/IrVisitorCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/IrVisitorCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/IrVisitorCompat.kt
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+typealias IrElementVisitorVoidCompat = org.jetbrains.kotlin.ir.visitors.IrVisitorVoid
+
+typealias IrElementTransformerVoidCompat = org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/MetadataVersionCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/MetadataVersionCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/MetadataVersionCompat.kt
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.metadata.deserialization.MetadataVersion
+
+fun currentMetadataVersionArray(): IntArray = MetadataVersion.INSTANCE.toArray()
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/OptInAnnotationsCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/OptInAnnotationsCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/OptInAnnotationsCompat.kt
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook
+
+@RequiresOptIn annotation class DeprecatedForRemovalCompilerApiCompat
+
+@RequiresOptIn annotation class DirectDeclarationsAccessCompat
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/PipelineCompat.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/PipelineCompat.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compilercompat/2.3.0/PipelineCompat.kt
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress(
+    "PackageLocationMismatch",
+    "DEPRECATION",
+    "DEPRECATION_ERROR",
+    "TYPEALIAS_EXPANSION_DEPRECATION",
+    "TYPEALIAS_EXPANSION_DEPRECATION_ERROR",
+)
+@file:OptIn(org.jetbrains.kotlin.cli.common.LegacyK2CliPipeline::class)
+
+package com.facebook
+
+import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
+import org.jetbrains.kotlin.cli.common.messages.MessageCollector
+import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.ModuleCompilerEnvironment
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.ModuleCompilerIrBackendInput
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.convertToIrAndActualizeForJvm
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.createProjectEnvironment
+import org.jetbrains.kotlin.cli.jvm.compiler.legacy.pipeline.generateCodeFromIr
+import org.jetbrains.kotlin.codegen.state.GenerationState
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.diagnostics.impl.BaseDiagnosticsCollector
+import org.jetbrains.kotlin.fir.backend.jvm.JvmFir2IrExtensions
+import org.jetbrains.kotlin.fir.pipeline.AllModulesFrontendOutput
+
+@Suppress("DEPRECATION_ERROR")
+typealias ModuleCompilerEnvironmentCompat = ModuleCompilerEnvironment
+
+typealias ModuleCompilerIrBackendInputCompat = ModuleCompilerIrBackendInput
+
+// generateCodeFromIr returns GenerationState directly in Kotlin 2.3 (the
+// ModuleCompilerOutput wrapper was removed); .factory is exposed on it.
+typealias ModuleCompilerOutputCompat = GenerationState
+
+fun AllModulesFrontendOutput.convertToIrAndActualizeForJvmCompat(
+    fir2IrExtensions: JvmFir2IrExtensions,
+    configuration: CompilerConfiguration,
+    diagnosticsReporter: BaseDiagnosticsCollector,
+    irGeneratorExtensions: Collection<IrGenerationExtension>,
+) = convertToIrAndActualizeForJvm(
+    fir2IrExtensions,
+    configuration,
+    diagnosticsReporter,
+    irGeneratorExtensions,
+)
+
+fun createProjectEnvironmentCompat(
+    configuration: CompilerConfiguration,
+    parentDisposable: org.jetbrains.kotlin.com.intellij.openapi.Disposable,
+    configFiles: EnvironmentConfigFiles,
+    messageCollector: MessageCollector,
+) = createProjectEnvironment(configuration, parentDisposable, configFiles, messageCollector)
+
+@Suppress("DEPRECATION_ERROR")
+fun generateCodeFromIrCompat(
+    irInput: ModuleCompilerIrBackendInputCompat,
+    environment: ModuleCompilerEnvironmentCompat,
+) = generateCodeFromIr(irInput, environment)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ClassStabilityTransformer.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ClassStabilityTransformer.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ClassStabilityTransformer.kt
@@ -0,0 +1,466 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+@file:Suppress("OPT_IN_USAGE_ERROR")
+
+package com.facebook
+
+import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
+import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
+import org.jetbrains.kotlin.descriptors.ClassKind
+import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
+import org.jetbrains.kotlin.ir.IrElement
+import org.jetbrains.kotlin.ir.builders.irCallConstructor
+import org.jetbrains.kotlin.ir.declarations.IrClass
+import org.jetbrains.kotlin.ir.declarations.IrDeclaration
+import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
+import org.jetbrains.kotlin.ir.declarations.IrField
+import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
+import org.jetbrains.kotlin.ir.declarations.IrProperty
+import org.jetbrains.kotlin.ir.expressions.IrConst
+import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
+import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
+import org.jetbrains.kotlin.ir.symbols.UnsafeDuringIrConstructionAPI
+import org.jetbrains.kotlin.ir.types.IrSimpleType
+import org.jetbrains.kotlin.ir.types.IrType
+import org.jetbrains.kotlin.ir.types.classFqName
+import org.jetbrains.kotlin.ir.types.classOrNull
+import org.jetbrains.kotlin.ir.types.isBoolean
+import org.jetbrains.kotlin.ir.types.isByte
+import org.jetbrains.kotlin.ir.types.isChar
+import org.jetbrains.kotlin.ir.types.isDouble
+import org.jetbrains.kotlin.ir.types.isFloat
+import org.jetbrains.kotlin.ir.types.isInt
+import org.jetbrains.kotlin.ir.types.isLong
+import org.jetbrains.kotlin.ir.types.isNullable
+import org.jetbrains.kotlin.ir.types.isShort
+import org.jetbrains.kotlin.ir.types.isString
+import org.jetbrains.kotlin.ir.types.isUnit
+import org.jetbrains.kotlin.ir.types.makeNotNull
+import org.jetbrains.kotlin.ir.util.constructors
+import org.jetbrains.kotlin.ir.util.getAnnotation
+import org.jetbrains.kotlin.ir.util.isEnumClass
+import org.jetbrains.kotlin.ir.util.isEnumEntry
+import org.jetbrains.kotlin.ir.util.isFileClass
+import org.jetbrains.kotlin.ir.util.isInterface
+import org.jetbrains.kotlin.name.ClassId
+import org.jetbrains.kotlin.name.FqName
+import org.jetbrains.kotlin.name.Name
+
+/**
+ * Adds $stable static field and @StabilityInferred annotation to eligible classes.
+ *
+ * The Compose compiler adds $stable and @StabilityInferred to every eligible class so downstream
+ * modules can determine stability without re-analyzing fields. This emulation replicates both
+ * artifacts for source-only ABI.
+ *
+ * Eligible classes: public/internal, non-enum, non-interface, non-annotation, non-anonymous,
+ * non-expect, non-inner, non-file-class, non-companion, non-inline/value.
+ *
+ * Stability rules (simplified for ABI emulation):
+ * - val properties of stable types: stable
+ * - var properties (non-delegated): unstable
+ * - Primitives, String, Unit, enums, function types: stable
+ * - A class is no more stable than its superclass
+ * - Unrecognised types: conservatively not-known-stable
+ *
+ * The two outputs use different encodings. $stable carries StabilityBits: 0 when known stable,
+ * UNSTABLE.bitsForSlot(0) = 8 otherwise. @StabilityInferred(parameters) carries the type-parameter
+ * bitmask plus a known-stable high bit at (1 shl typeParameters.size).
+ */
+@OptIn(UnsafeDuringIrConstructionAPI::class)
+internal class ClassStabilityTransformer(private val pluginContext: IrPluginContext) {
+
+  companion object {
+    private val COMPOSER_CLASS_ID =
+        ClassId(FqName("androidx.compose.runtime"), Name.identifier("Composer"))
+    private val STABILITY_INFERRED_CLASS_ID =
+        ClassId(FqName("androidx.compose.runtime.internal"), Name.identifier("StabilityInferred"))
+    private val STABILITY_INFERRED_FQ_NAME = STABILITY_INFERRED_CLASS_ID.asSingleFqName()
+
+    // Known stable FQNs beyond primitives/String/Unit
+    private val KNOWN_STABLE_FQNS = setOf(
+        "kotlin.Pair",
+        "kotlin.Triple",
+        "kotlin.Result",
+        "kotlin.ranges.IntRange",
+        "kotlin.ranges.LongRange",
+        "kotlin.ranges.CharRange",
+        "kotlin.coroutines.CoroutineContext.Key",
+        "kotlinx.collections.immutable.ImmutableList",
+        "kotlinx.collections.immutable.ImmutableSet",
+        "kotlinx.collections.immutable.ImmutableMap",
+        "kotlinx.collections.immutable.ImmutableCollection",
+        "kotlinx.collections.immutable.PersistentList",
+        "kotlinx.collections.immutable.PersistentSet",
+        "kotlinx.collections.immutable.PersistentMap",
+        "dagger.Lazy",
+    )
+
+    // androidx StabilityBits: STABLE 0b000, UNSTABLE 0b100, bitsForSlot(n) = bits shl (1 + n*3).
+    // Written as the derivation rather than 8 so the slot-0 substitution stays visible.
+    private const val STABLE_BITS = 0
+    private const val UNSTABLE_BITS_SLOT0 = 0b100 shl 1
+  }
+
+  // Classes currently being analyzed (cycle detection)
+  private val analyzing = mutableSetOf<String>()
+
+  // Lazily resolved — null if compose-runtime is not on the classpath
+  private var stabilityInferredClass: IrClassSymbol? = null
+
+  // FQNs declared in the module under compilation. A superclass in this set has not had its
+  // @StabilityInferred attached yet (this transformer is what attaches it, and visit order does not
+  // follow the inheritance graph), so its stability must be recomputed rather than read back.
+  private val moduleClassFqns = mutableSetOf<String>()
+
+  fun transform(moduleFragment: IrModuleFragment) {
+    // No-op when Compose runtime is not on the classpath.
+    pluginContext.referenceClass(COMPOSER_CLASS_ID) ?: return
+    stabilityInferredClass = pluginContext.referenceClass(STABILITY_INFERRED_CLASS_ID)
+    // Carrying FQNs across fragments would route a compiled dependency down the recompute branch
+    // instead of the external-annotation one.
+    moduleClassFqns.clear()
+    moduleFragment.accept(ModuleClassCollector(), null)
+    moduleFragment.accept(StabilityVisitor(), null)
+  }
+
+  private inner class ModuleClassCollector : IrElementVisitorVoidCompat() {
+    override fun visitElement(element: IrElement) {
+      element.acceptChildren(this, null)
+    }
+
+    override fun visitClass(declaration: IrClass) {
+      declaration.classFqName()?.let { moduleClassFqns.add(it) }
+      super.visitClass(declaration)
+    }
+  }
+
+  private inner class StabilityVisitor : IrElementVisitorVoidCompat() {
+
+    override fun visitElement(element: IrElement) {
+      element.acceptChildren(this, null)
+    }
+
+    override fun visitClass(declaration: IrClass) {
+      if (shouldTransform(declaration)) {
+        addStabilityField(declaration)
+      }
+      // Visit nested classes
+      super.visitClass(declaration)
+    }
+  }
+
+  private fun shouldTransform(irClass: IrClass): Boolean {
+    // Skip enum classes and enum entries
+    if (irClass.isEnumClass || irClass.isEnumEntry) return false
+    // Skip interfaces
+    if (irClass.isInterface) return false
+    // Skip annotation classes
+    if (irClass.kind == ClassKind.ANNOTATION_CLASS) return false
+    // Skip anonymous objects
+    if (irClass.kind == ClassKind.OBJECT && irClass.name.isSpecial) return false
+    // Skip expect declarations
+    if (irClass.isExpect) return false
+    // Skip inner classes
+    if (irClass.isInner) return false
+    // Skip file classes (top-level function holders)
+    if (irClass.isFileClass) return false
+    // Skip companion objects
+    if (irClass.isCompanion) return false
+    // Skip inline/value classes
+    if (irClass.isValue) return false
+    // Only process public/internal classes
+    val vis = irClass.visibility
+    if (
+        vis != DescriptorVisibilities.PUBLIC &&
+            vis != DescriptorVisibilities.INTERNAL &&
+            vis != DescriptorVisibilities.PROTECTED
+    ) {
+      return false
+    }
+    return true
+  }
+
+  private fun addStabilityField(irClass: IrClass) {
+    val stability = computeStability(irClass)
+    val stableValue = if (stability.knownStable) STABLE_BITS else UNSTABLE_BITS_SLOT0
+
+    // Add static final $stable: Int field
+    val stableField =
+        pluginContext.irFactory.createField(
+            startOffset = -1,
+            endOffset = -1,
+            origin = IrDeclarationOrigin.DEFINED,
+            name = Name.identifier("\$stable"),
+            type = pluginContext.irBuiltIns.intType,
+            visibility = DescriptorVisibilities.PUBLIC,
+            symbol = org.jetbrains.kotlin.ir.symbols.impl.IrFieldSymbolImpl(),
+            isFinal = true,
+            isExternal = false,
+            isStatic = true,
+        )
+    stableField.parent = irClass
+    val constExpr = IrConstImpl.int(-1, -1, pluginContext.irBuiltIns.intType, stableValue)
+    stableField.initializer = pluginContext.irFactory.createExpressionBody(-1, -1, constExpr)
+    irClass.declarations.add(stableField)
+
+    // Not the same encoding as $stable: a bitmask over the class's type parameters, plus a high
+    // bit at (1 shl typeParameters.size) meaning "known stable regardless of its parameters".
+    // The `< 32` bound mirrors Compose exactly (ClassStabilityTransformer.kt:161 emits it,
+    // Stability.kt:246 reads it). At 31 params both sides use `1 shl 31` = Int.MIN_VALUE and
+    // compare with `and`, so the sign bit is correct; tightening to `< 31` would emit 0 here
+    // while the consumer still looks for that bit, silently losing "known stable".
+    val knownStableBit =
+        if (stability.knownStable && irClass.typeParameters.size < 32) {
+          1 shl irClass.typeParameters.size
+        } else {
+          0
+        }
+    addStabilityInferredAnnotation(irClass, stability.typeParamMask or knownStableBit)
+  }
+
+  private fun addStabilityInferredAnnotation(irClass: IrClass, parametersValue: Int) {
+    val annotationClass = stabilityInferredClass ?: return
+    val constructor = annotationClass.constructors.singleOrNull() ?: return
+    val annotation =
+        pluginContext.irBuiltIns.createIrBuilder(irClass.symbol).run {
+          irCallConstructor(constructor, emptyList()).apply {
+            putValueArgument(
+                0,
+                IrConstImpl.int(-1, -1, pluginContext.irBuiltIns.intType, parametersValue),
+            )
+          }
+        }
+    // Register via metadataDeclarationRegistrar so HAS_ANNOTATIONS is set in Kotlin metadata.
+    // Without it, consumers cannot see the emulated annotation and fold stability constants
+    // instead of deferring to runtime.
+    pluginContext.metadataDeclarationRegistrar.addMetadataVisibleAnnotationsToElement(
+        irClass,
+        annotation,
+    )
+  }
+
+  /** Type-parameter bitmask plus whether the class itself is known stable. */
+  private data class Stability(val typeParamMask: Int, val knownStable: Boolean)
+
+  // Deliberately conservative: an unrecognised member type yields not-known-stable, so consumers
+  // resolve stability at runtime rather than assume the wrong answer.
+  private fun computeStability(irClass: IrClass): Stability {
+    val classFqn = irClass.classFqName()
+    if (classFqn != null && analyzing.contains(classFqn)) {
+      // Cycle — do not claim knowledge we do not have.
+      return Stability(0, knownStable = false)
+    }
+    if (classFqn != null) analyzing.add(classFqn)
+
+    var mask = 0
+    var knownStable = true
+    for (declaration in irClass.declarations) {
+      when (declaration) {
+        is IrProperty -> {
+          if (declaration.isVar && declaration.isDelegated != true) {
+            if (classFqn != null) analyzing.remove(classFqn)
+            return Stability(0, knownStable = false)
+          }
+          // Only stored state counts. A computed getter has no backing field and is skipped,
+          // which is what the real StabilityInferencer does - it reaches members through
+          // `member.backingField?.let { ... }`.
+          val backingField = declaration.backingField
+          if (backingField != null) {
+            mask = mask or typeParamBits(backingField.type, irClass)
+            if (
+                !isStabilityDelegatedToTypeParam(backingField.type, irClass) &&
+                    !isKnownStableType(backingField.type)
+            ) {
+              knownStable = false
+            }
+          }
+        }
+        is IrField -> {
+          if (!declaration.isStatic) {
+            mask = mask or typeParamBits(declaration.type, irClass)
+            if (
+                !isStabilityDelegatedToTypeParam(declaration.type, irClass) &&
+                    !isKnownStableType(declaration.type)
+            ) {
+              knownStable = false
+            }
+          }
+        }
+        else -> {}
+      }
+    }
+
+    // A subclass holds every field its superclass declares, so it can be no more stable than that
+    // superclass. Skipping this let a class with no stored state of its own be called stable while
+    // the real compiler called it unstable — e.g. `object EmptyPainter : Painter()`, where all the
+    // mutable state lives in Painter. Over-asserting stability makes a consumer skip recomposition
+    // for a value that did change, so this is deliberately the pessimistic direction.
+    if (knownStable && !superclassKnownStable(irClass)) {
+      knownStable = false
+    }
+
+    if (classFqn != null) analyzing.remove(classFqn)
+    return Stability(mask, knownStable)
+  }
+
+  /**
+   * Whether [irClass]'s superclass permits it to be known stable. Interfaces and [Any] are ignored:
+   * neither contributes stored state.
+   */
+  private fun superclassKnownStable(irClass: IrClass): Boolean {
+    val superClass =
+        irClass.superTypes.mapNotNull { it.classOrNull?.owner }.firstOrNull { !it.isInterface }
+            ?: return true
+    val superFqn = superClass.classFqName() ?: return false
+    if (superFqn == "kotlin.Any") return true
+    if (superFqn in moduleClassFqns) {
+      return computeStability(superClass).knownStable
+    }
+    // Compiled dependency: trust its @StabilityInferred, and treat an absent one as unstable. A
+    // class outside a Compose-enabled compilation carries no stability information, and its private
+    // state may be stripped from the ABI jar, so its declarations cannot be inspected instead.
+    return externalClassKnownStable(superClass)
+  }
+
+  private fun externalClassKnownStable(irClass: IrClass): Boolean {
+    val annotation = irClass.getAnnotation(STABILITY_INFERRED_FQ_NAME) ?: return false
+    val parameters = (annotation.getValueArgument(0) as? IrConst)?.value as? Int ?: return false
+    val typeParamCount = irClass.typeParameters.size
+    if (typeParamCount >= 32) return false
+    return (parameters and (1 shl typeParamCount)) != 0
+  }
+
+  // True only when the type IS one of the class's own type parameters, e.g. `val value: T`. Such a
+  // member's stability is carried by its bit in the mask and resolved by the consumer, so it must
+  // not clear knownStable. A container that merely mentions T, e.g. `List<T>`, is not delegated:
+  // List is unstable whatever T is, and must clear knownStable.
+  private fun isStabilityDelegatedToTypeParam(type: IrType, irClass: IrClass): Boolean {
+    val classifier = (type as? IrSimpleType)?.classifier ?: return false
+    return irClass.typeParameters.any { classifier == it.symbol }
+  }
+
+  // Determine which type parameter bits are affected by a given type.
+  // Returns a bitmask where bit N is set if type parameter N of the class appears in the type.
+  private fun typeParamBits(type: IrType, irClass: IrClass): Int {
+    if (irClass.typeParameters.isEmpty()) return 0
+
+    // If the type is already known stable, no type param dependency
+    if (isKnownStableType(type)) return 0
+
+    // Check if the type IS a type parameter of this class
+    if (type is IrSimpleType) {
+      val classifier = type.classifier
+      for ((index, typeParam) in irClass.typeParameters.withIndex()) {
+        if (classifier == typeParam.symbol) {
+          return 1 shl index
+        }
+      }
+
+      // Recurse into type arguments
+      var bits = 0
+      for (arg in type.arguments) {
+        if (arg is org.jetbrains.kotlin.ir.types.IrTypeProjection) {
+          bits = bits or typeParamBits(arg.type, irClass)
+        }
+      }
+      return bits
+    }
+    return 0
+  }
+
+  // Check if a type is known stable (primitives, String, enums, function types, etc.)
+  private fun isKnownStableType(type: IrType): Boolean {
+    // Handle nullable — strip and check inner
+    if (type.isNullable()) {
+      return isKnownStableType(type.makeNotNull())
+    }
+
+    // Primitives
+    if (
+        type.isInt() ||
+            type.isLong() ||
+            type.isFloat() ||
+            type.isDouble() ||
+            type.isBoolean() ||
+            type.isByte() ||
+            type.isShort() ||
+            type.isChar()
+    ) {
+      return true
+    }
+    // String, Unit
+    if (type.isString() || type.isUnit()) return true
+
+    val fqn = type.classFqName?.asString() ?: return false
+
+    // Function types
+    if (fqn.startsWith("kotlin.Function") || fqn.startsWith("kotlin.reflect.KFunction")) {
+      return true
+    }
+
+    // Enums
+    val classSymbol = (type as? IrSimpleType)?.classOrNull
+    if (classSymbol != null) {
+      val owner = classSymbol.owner
+      if (owner.isEnumClass) return true
+    }
+
+    // Known stable types. The container-shaped ones are only as stable as their arguments:
+    // `Pair<String, MutableList<Int>>` matches on FQN alone but is not stable, and claiming it is
+    // makes a consumer skip a recomposition it needed. A star projection or a type-parameter
+    // argument is not known stable here either — that stability is carried by the type-parameter
+    // mask, which is a separate signal from this one.
+    if (fqn in KNOWN_STABLE_FQNS) {
+      return (type as? IrSimpleType)?.arguments.orEmpty().all {
+        it is org.jetbrains.kotlin.ir.types.IrTypeProjection && isKnownStableType(it.type)
+      }
+    }
+
+    // SDK types (java.*, kotlin.* excluding collections interfaces)
+    // Kotlin collections interfaces (List, Set, Map) are NOT stable — they're interfaces
+    if (
+        fqn == "kotlin.collections.List" ||
+            fqn == "kotlin.collections.Set" ||
+            fqn == "kotlin.collections.Map" ||
+            fqn == "kotlin.collections.MutableList" ||
+            fqn == "kotlin.collections.MutableSet" ||
+            fqn == "kotlin.collections.MutableMap" ||
+            fqn == "kotlin.collections.Collection" ||
+            fqn == "kotlin.collections.MutableCollection"
+    ) {
+      return false
+    }
+
+    return false
+  }
+
+  private fun IrClass.classFqName(): String? {
+    return this.classFqName?.asString()
+  }
+
+  private val IrClass.classFqName: FqName?
+    get() {
+      val segments = mutableListOf<String>()
+      var current: IrClass? = this
+      while (current != null) {
+        segments.add(0, current.name.asString())
+        current = current.parent as? IrClass
+      }
+      val packageFqName =
+          generateSequence(this.parent) { (it as? IrDeclaration)?.parent }
+              .filterIsInstance<org.jetbrains.kotlin.ir.declarations.IrPackageFragment>()
+              .firstOrNull()
+              ?.packageFqName ?: return null
+      return FqName(packageFqName.asString() + "." + segments.joinToString("."))
+    }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposableTypeRewriter.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposableTypeRewriter.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposableTypeRewriter.kt
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+@file:Suppress("OPT_IN_USAGE_ERROR")
+
+package com.facebook
+
+import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
+import org.jetbrains.kotlin.ir.IrElement
+import org.jetbrains.kotlin.ir.declarations.IrClass
+import org.jetbrains.kotlin.ir.declarations.IrConstructor
+import org.jetbrains.kotlin.ir.declarations.IrField
+import org.jetbrains.kotlin.ir.declarations.IrFunction
+import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
+import org.jetbrains.kotlin.ir.declarations.IrProperty
+import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
+import org.jetbrains.kotlin.ir.types.IrSimpleType
+import org.jetbrains.kotlin.ir.types.IrType
+import org.jetbrains.kotlin.ir.types.classFqName
+import org.jetbrains.kotlin.ir.types.classOrNull
+import org.jetbrains.kotlin.ir.types.defaultType
+import org.jetbrains.kotlin.ir.types.isMarkedNullable
+import org.jetbrains.kotlin.ir.types.makeNullable
+import org.jetbrains.kotlin.ir.types.typeWith
+import org.jetbrains.kotlin.ir.util.hasAnnotation
+import org.jetbrains.kotlin.name.ClassId
+import org.jetbrains.kotlin.name.FqName
+import org.jetbrains.kotlin.name.Name
+
+/**
+ * Rewrites @Composable function types in IR declarations.
+ *
+ * A @Composable (P1, P2, ..., Pn) -> R function type is represented in IR as FunctionN(P1, P2, ...,
+ * Pn, R) with a @Composable annotation on the type.
+ *
+ * The Compose compiler transforms this to Function(N + 1 + changedCount)(P1, ..., Pn, Composer,
+ * Int, ..., R).
+ *
+ * This rewriter applies that transformation to function types appearing in:
+ * - Value parameter types
+ * - Return types
+ * - Supertype declarations
+ *
+ * After rewriting, the @Composable annotation is removed from the type since the synthetic
+ * parameters now encode the composable nature.
+ */
+internal class ComposableTypeRewriter(private val pluginContext: IrPluginContext) {
+
+  companion object {
+    private val COMPOSABLE_FQ_NAME = FqName("androidx.compose.runtime.Composable")
+    private val COMPOSER_CLASS_ID =
+        ClassId(FqName("androidx.compose.runtime"), Name.identifier("Composer"))
+    private val FUNCTION_FQ_PREFIX = "kotlin.Function"
+
+    /**
+     * Under K2 the Compose plugin registers its own function-type *kinds*
+     * (ComposeFirExtensions.registerKinds), so a `@Composable (P..) -> R` is classified as the
+     * synthetic class `androidx.compose.runtime.internal.(K)ComposableFunctionN` and carries no
+     * `@Composable` annotation on the type itself. Only deserialized dependency metadata still uses
+     * the legacy `kotlin.FunctionN` + annotation form.
+     */
+    private const val COMPOSABLE_FUNCTION_FQ_PREFIX =
+        "androidx.compose.runtime.internal.ComposableFunction"
+    private const val K_COMPOSABLE_FUNCTION_FQ_PREFIX =
+        "androidx.compose.runtime.internal.KComposableFunction"
+
+    /** Each parameter uses 3 bits. 32 / 3 = 10 slots per Int. */
+    private const val SLOTS_PER_INT = 10
+  }
+
+  private val composerType: IrType? by lazy {
+    pluginContext.referenceClass(COMPOSER_CLASS_ID)?.defaultType?.makeNullable()
+  }
+
+  /** Run the type rewriting on the entire module. */
+  fun transform(moduleFragment: IrModuleFragment) {
+    val composerIrType = composerType ?: return
+    moduleFragment.accept(TypeRewriterVisitor(composerIrType), null)
+  }
+
+  private inner class TypeRewriterVisitor(
+      private val composerIrType: IrType,
+  ) : IrElementVisitorVoidCompat() {
+
+    override fun visitElement(element: IrElement) {
+      element.acceptChildren(this, null)
+    }
+
+    override fun visitSimpleFunction(declaration: IrSimpleFunction) {
+      rewriteFunctionSignatureTypes(declaration)
+      super.visitSimpleFunction(declaration)
+    }
+
+    /**
+     * Constructors need their own override: [IrConstructor] extends IrFunction but NOT
+     * IrSimpleFunction, so [visitSimpleFunction] never sees one. Without this, a `class Foo(val
+     * content: @Composable () -> Unit)` keeps ComposableFunction0 in its `<init>` descriptor while
+     * its generated getter is rewritten correctly -- and every consumer of the class calls a
+     * constructor.
+     */
+    override fun visitConstructor(declaration: IrConstructor) {
+      rewriteFunctionSignatureTypes(declaration)
+      super.visitConstructor(declaration)
+    }
+
+    override fun visitProperty(declaration: IrProperty) {
+      declaration.getter?.let { rewriteFunctionSignatureTypes(it) }
+      declaration.setter?.let { rewriteFunctionSignatureTypes(it) }
+      super.visitProperty(declaration)
+    }
+
+    /**
+     * Backing fields are not reached via [visitSimpleFunction] or [visitProperty] either. These are
+     * private and so do not affect consumers, but leaving the synthetic ComposableFunctionN type in
+     * the stub jar leaves a dangling reference to a class that exists only inside a Compose-enabled
+     * compilation.
+     */
+    override fun visitField(declaration: IrField) {
+      val rewritten = rewriteTypeIfComposable(declaration.type)
+      if (rewritten !== declaration.type) {
+        declaration.type = rewritten
+      }
+      super.visitField(declaration)
+    }
+
+    override fun visitClass(declaration: IrClass) {
+      // Rewrite @Composable function types in supertypes.
+      declaration.superTypes = declaration.superTypes.map { rewriteTypeIfComposable(it) }
+      super.visitClass(declaration)
+    }
+
+    /** Rewrite composable function types in a function's value parameters and return type. */
+    private fun rewriteFunctionSignatureTypes(function: IrFunction) {
+      // Rewrite parameter types.
+      for (param in function.valueParameters) {
+        val rewritten = rewriteTypeIfComposable(param.type)
+        if (rewritten !== param.type) {
+          param.type = rewritten
+        }
+      }
+
+      // Rewrite return type.
+      val rewrittenReturn = rewriteTypeIfComposable(function.returnType)
+      if (rewrittenReturn !== function.returnType) {
+        function.returnType = rewrittenReturn
+      }
+
+      // Rewrite extension receiver type.
+      function.extensionReceiverParameter?.let { ext ->
+        val rewritten = rewriteTypeIfComposable(ext.type)
+        if (rewritten !== ext.type) {
+          ext.type = rewritten
+        }
+      }
+    }
+
+    /**
+     * If [type] is a @Composable function type, rewrite it to include Composer + $changed params.
+     * Otherwise, recursively check type arguments for nested composable function types.
+     */
+    private fun rewriteTypeIfComposable(type: IrType): IrType {
+      if (type !is IrSimpleType) return type
+
+      // Check if this is a @Composable function type.
+      if (isComposableFunctionType(type)) {
+        return rewriteComposableFunctionType(type)
+      }
+
+      // Recursively rewrite type arguments (handles e.g. List<@Composable () -> Unit>).
+      var anyArgChanged = false
+      val rewrittenArgTypes =
+          type.arguments.map { arg ->
+            if (arg is org.jetbrains.kotlin.ir.types.IrTypeProjection) {
+              val rewritten = rewriteTypeIfComposable(arg.type)
+              if (rewritten !== arg.type) {
+                anyArgChanged = true
+                rewritten
+              } else {
+                arg.type
+              }
+            } else {
+              pluginContext.irBuiltIns.anyNType
+            }
+          }
+
+      if (anyArgChanged) {
+        return type.classOrNull?.typeWith(rewrittenArgTypes) ?: type
+      }
+
+      return type
+    }
+
+    /**
+     * Two representations reach IR: the K2 kind `(K)ComposableFunctionN` with no annotation
+     * (in-module source), and `kotlin.FunctionN` plus `@Composable` (read back from metadata).
+     */
+    private fun isComposableFunctionType(type: IrSimpleType): Boolean {
+      if (isSyntheticComposableFunction(type) || isKComposableFunction(type)) return true
+      if (!type.hasAnnotation(COMPOSABLE_FQ_NAME)) return false
+      val classFqn = type.classFqName?.asString() ?: return false
+      return classFqn.startsWith(FUNCTION_FQ_PREFIX)
+    }
+
+    /** The non-reflect Compose kind, `androidx.compose.runtime.internal.ComposableFunctionN`. */
+    private fun isSyntheticComposableFunction(type: IrSimpleType): Boolean =
+        hasNumberedPrefix(type, COMPOSABLE_FUNCTION_FQ_PREFIX)
+
+    /** The reflect Compose kind, `androidx.compose.runtime.internal.KComposableFunctionN`. */
+    private fun isKComposableFunction(type: IrSimpleType): Boolean =
+        hasNumberedPrefix(type, K_COMPOSABLE_FUNCTION_FQ_PREFIX)
+
+    /**
+     * These classes are synthetic (declared nowhere) and unbounded in arity, so match on prefix +
+     * an all-digit suffix rather than enumerating. The two prefixes are disjoint:
+     * `...internal.KComposableFunction0` does not start with `...internal.ComposableFunction`.
+     */
+    private fun hasNumberedPrefix(type: IrSimpleType, prefix: String): Boolean {
+      val fqn = type.classFqName?.asString() ?: return false
+      if (!fqn.startsWith(prefix)) return false
+      val suffix = fqn.substring(prefix.length)
+      return suffix.isNotEmpty() && suffix.all { it.isDigit() }
+    }
+
+    // Rewrite a @Composable function type.
+    //
+    // @Composable FunctionN(P1, ..., Pn, R) becomes
+    // Function(N + 1 + changedCount)(P1, ..., Pn, Composer, Int, ..., R)
+    //
+    // The @Composable annotation is removed (the synthetic params encode composability).
+    private fun rewriteComposableFunctionType(type: IrSimpleType): IrType {
+      val args = type.arguments
+      if (args.isEmpty()) return type
+
+      // FunctionN<P1, ..., Pn, R>: last type arg is the return type, rest are params.
+      val paramTypeArgs = args.dropLast(1)
+      val returnTypeArg = args.last()
+
+      // Number of user-visible params in the function type (no receivers in function types).
+      val userParamCount = paramTypeArgs.size
+
+      // $changed count: ceil((userParamCount + 1) / SLOTS_PER_INT), minimum 1.
+      val changedCount = maxOf(1, ceilDiv(userParamCount + 1, SLOTS_PER_INT))
+
+      // New arity: original params + Composer + changedCount Ints.
+      val newArity = userParamCount + 1 + changedCount
+
+      // Build new type arguments: [P1, ..., Pn, Composer, Int, ..., R]
+      // Recurse: a composable lambda nested inside another composable lambda's arguments is
+      // itself a composable function type and must be rewritten too. rewriteTypeIfComposable
+      // returns early on the composable branch, so this is the only place that reaches them.
+      val newTypeArgs = mutableListOf<IrType>()
+      for (arg in paramTypeArgs) {
+        newTypeArgs.add(rewriteTypeIfComposable(extractTypeFromArgument(arg)))
+      }
+      // Add Composer? type argument.
+      newTypeArgs.add(composerIrType)
+      // Add Int type arguments for $changed params.
+      repeat(changedCount) { newTypeArgs.add(pluginContext.irBuiltIns.intType) }
+      // Add return type.
+      newTypeArgs.add(rewriteTypeIfComposable(extractTypeFromArgument(returnTypeArg)))
+
+      // irBuiltIns.functionN/kFunctionN cannot fail, unlike referenceClass, whose `?: return type`
+      // silently left the type un-rewritten when the synthetic class was not in the symbol table.
+      val functionClass =
+          if (isKComposableFunction(type)) pluginContext.irBuiltIns.kFunctionN(newArity)
+          else pluginContext.irBuiltIns.functionN(newArity)
+
+      // typeWith() constructs NOT_SPECIFIED, so a declared-nullable type would come back non-null
+      // and be emitted @NotNull; Java interop and NullAway read those JVM annotations.
+      val rewritten = functionClass.typeWith(newTypeArgs)
+      return if (type.isMarkedNullable()) rewritten.makeNullable() else rewritten
+    }
+
+    private fun extractTypeFromArgument(
+        arg: org.jetbrains.kotlin.ir.types.IrTypeArgument,
+    ): IrType {
+      return when (arg) {
+        is org.jetbrains.kotlin.ir.types.IrTypeProjection -> arg.type
+        else -> pluginContext.irBuiltIns.anyNType
+      }
+    }
+  }
+}
+
+/** Integer ceiling division: ceil(a / b) for positive a, b. */
+private fun ceilDiv(a: Int, b: Int): Int = (a + b - 1) / b
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposeAbiEmulationExtension.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposeAbiEmulationExtension.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposeAbiEmulationExtension.kt
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
+import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
+import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
+
+/**
+ * IR generation extension for Compose ABI emulation.
+ *
+ * When enabled, this extension runs before the IR sanitizer during FIR-to-IR conversion. It
+ * emulates the Compose compiler plugin's effects on the ABI surface:
+ *
+ * 1. **ClassStabilityTransformer** — adds $stable field and @StabilityInferred annotation to
+ *    eligible classes (the P1 ClassStabilityTransformer equivalent)
+ * 2. **ComposerParamInjector** — adds $composer, $changed, $default parameters to @Composable
+ *    functions (the P4 ComposerParamTransformer equivalent)
+ * 3. **ComposableTypeRewriter** — rewrites @Composable function types in parameters, return types,
+ *    and supertypes to include the synthetic Composer and changed-bitmask type arguments
+ *
+ * These transforms run before the IR sanitizer so that Compose-emulated declarations are present
+ * when non-ABI content is stripped.
+ */
+internal class ComposeAbiEmulationExtension : IrGenerationExtension {
+
+  override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
+    // Pass 1: Add $stable field + @StabilityInferred to eligible classes.
+    ClassStabilityTransformer(pluginContext).transform(moduleFragment)
+
+    // Pass 2: Inject $composer, $changed, $default params into @Composable functions.
+    ComposerParamInjector(pluginContext).transform(moduleFragment)
+
+    // Pass 3: Rewrite @Composable function types in parameter types, return types, supertypes.
+    ComposableTypeRewriter(pluginContext).transform(moduleFragment)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposeAbiEmulationStage.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposeAbiEmulationStage.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposeAbiEmulationStage.kt
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
+
+/**
+ * Pipeline stage for Compose ABI emulation.
+ *
+ * Creates the [ComposeAbiEmulationExtension] which is registered as an [IrGenerationExtension]
+ * during FIR-to-IR conversion. The extension runs before the IR sanitizer so that any
+ * Compose-emulated declarations are present when non-ABI content is stripped.
+ */
+internal class ComposeAbiEmulationStage : AbiGenStage {
+  override val name = "ComposeAbiEmulation"
+
+  /** Create the IR generation extension to be registered during FIR-to-IR conversion. */
+  fun createExtension(): IrGenerationExtension {
+    return ComposeAbiEmulationExtension()
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposerParamInjector.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposerParamInjector.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/compose/ComposerParamInjector.kt
@@ -0,0 +1,316 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+@file:Suppress("OPT_IN_USAGE_ERROR")
+
+package com.facebook
+
+import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
+import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
+import org.jetbrains.kotlin.ir.IrElement
+import org.jetbrains.kotlin.ir.builders.irCallConstructor
+import org.jetbrains.kotlin.ir.declarations.IrClass
+import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
+import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
+import org.jetbrains.kotlin.ir.declarations.IrProperty
+import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
+import org.jetbrains.kotlin.ir.declarations.IrValueParameter
+import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
+import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
+import org.jetbrains.kotlin.ir.symbols.UnsafeDuringIrConstructionAPI
+import org.jetbrains.kotlin.ir.types.IrType
+import org.jetbrains.kotlin.ir.types.defaultType
+import org.jetbrains.kotlin.ir.types.makeNullable
+import org.jetbrains.kotlin.ir.util.constructors
+import org.jetbrains.kotlin.ir.util.hasAnnotation
+import org.jetbrains.kotlin.load.java.JvmAbi
+import org.jetbrains.kotlin.name.ClassId
+import org.jetbrains.kotlin.name.FqName
+import org.jetbrains.kotlin.name.Name
+
+/**
+ * Injects Compose synthetic parameters ($composer, $changed, $default) into @Composable functions.
+ *
+ * For every @Composable function (excluding constructors and expect functions), this adds:
+ * - `$composer: Composer?` — the Composer instance threaded through composable calls
+ * - `$changed: Int` (1 or more) — bitmask tracking parameter change state
+ * - `$default: Int` (0 or more) — bitmask for default parameter values, only on a concrete function
+ *   that has defaults
+ *
+ * Parameter counting follows the Compose compiler spec:
+ * - changedParamCount = max(1, ceil((realValueParams + thisParams) / SLOTS_PER_INT))
+ * - defaultParamCount = ceil(valueParams / BITS_PER_DEFAULT_INT), only if the function is concrete
+ *   and any param has a default
+ * - thisParams = count of dispatch receiver + extension receiver (context receivers are value
+ *   params)
+ */
+@OptIn(UnsafeDuringIrConstructionAPI::class)
+internal class ComposerParamInjector(private val pluginContext: IrPluginContext) {
+
+  companion object {
+    val COMPOSABLE_FQ_NAME = FqName("androidx.compose.runtime.Composable")
+    private val COMPOSER_CLASS_ID =
+        ClassId(FqName("androidx.compose.runtime"), Name.identifier("Composer"))
+    private val JVM_NAME_CLASS_ID = ClassId(FqName("kotlin.jvm"), Name.identifier("JvmName"))
+    private val JVM_NAME_FQ_NAME = FqName("kotlin.jvm.JvmName")
+
+    /** Each parameter uses 3 bits in the $changed bitmask. 32 / 3 = 10 slots per Int. */
+    private const val SLOTS_PER_INT = 10
+
+    /** Each $default Int can track 31 parameters (bit 31 is sign bit, unusable). */
+    private const val BITS_PER_DEFAULT_INT = 31
+  }
+
+  /** The Composer type, resolved lazily. Nullable if Compose runtime is not on classpath. */
+  private val composerType: IrType? by lazy {
+    pluginContext.referenceClass(COMPOSER_CLASS_ID)?.defaultType?.makeNullable()
+  }
+
+  private val jvmNameClass: IrClassSymbol? by lazy {
+    pluginContext.referenceClass(JVM_NAME_CLASS_ID)
+  }
+
+  /** Run the transform on the entire module. */
+  fun transform(moduleFragment: IrModuleFragment) {
+    val composerIrType = composerType ?: return // Compose runtime not on classpath; skip.
+    moduleFragment.accept(
+        ComposerParamVisitor(pluginContext, composerIrType),
+        null,
+    )
+    // This must run after every in-module composable has been transformed, so links between two
+    // transformed declarations are preserved while stale links to dependency declarations are not.
+    moduleFragment.accept(OverrideLinkRepairVisitor(), null)
+  }
+
+  private inner class ComposerParamVisitor(
+      private val pluginContext: IrPluginContext,
+      private val composerIrType: IrType,
+  ) : IrElementVisitorVoidCompat() {
+
+    override fun visitElement(element: IrElement) {
+      element.acceptChildren(this, null)
+    }
+
+    override fun visitSimpleFunction(declaration: IrSimpleFunction) {
+      if (shouldTransform(declaration)) {
+        injectParams(declaration)
+      }
+      // Continue visiting nested declarations (local functions inside composables).
+      super.visitSimpleFunction(declaration)
+    }
+
+    override fun visitClass(declaration: IrClass) {
+      // Visit class members.
+      super.visitClass(declaration)
+    }
+
+    override fun visitProperty(declaration: IrProperty) {
+      // Property getters can be @Composable.
+      declaration.getter?.let { getter ->
+        if (shouldTransform(getter)) {
+          injectParams(getter)
+        }
+      }
+      super.visitProperty(declaration)
+    }
+
+    /**
+     * Determine if a function should be transformed.
+     *
+     * Transform if:
+     * - Has @Composable annotation
+     * - Is not a constructor
+     * - Is not an expect declaration
+     */
+    private fun shouldTransform(function: IrSimpleFunction): Boolean {
+      if (!function.hasAnnotation(COMPOSABLE_FQ_NAME)) return false
+      if (function.isExpect) return false
+      // Idempotence guard. A @Composable property getter is reached TWICE: once explicitly via
+      // visitProperty below, and again when super.visitProperty descends into the getter as an
+      // IrSimpleFunction. Without this check the synthetic params are injected twice, producing
+      // (..., Composer, int, Composer, int) -- a descriptor no consumer can link against. Only
+      // fires when @Composable is on the getter rather than the property, which is why it is rare.
+      if (function.valueParameters.any { it.name.asString() == "\$composer" }) return false
+      return true
+    }
+
+    /**
+     * Inject $composer, $changed, and $default parameters into a @Composable function.
+     *
+     * Parameters are appended after all existing value parameters.
+     */
+    private fun injectParams(function: IrSimpleFunction) {
+      val existingValueParams = function.valueParameters
+
+      // Count "this" params: dispatch receiver + extension receiver.
+      // These contribute to $changed slot allocation but are not value parameters.
+      val thisParamCount =
+          (if (function.dispatchReceiverParameter != null) 1 else 0) +
+              (if (function.extensionReceiverParameter != null) 1 else 0)
+
+      val realValueParamCount = existingValueParams.size
+      val totalSlottedParams = realValueParamCount + thisParamCount
+
+      // Deliberately no "+1": the force bit shares int 0 with slots 0..9 rather than consuming a
+      // slot, and adding one emits a trailing `I` at every exact multiple of SLOTS_PER_INT.
+      val changedCount = maxOf(1, ceilDiv(totalSlottedParams, SLOTS_PER_INT))
+
+      // An abstract @Composable member gets no $default: Compose puts defaults handling in a
+      // nested ComposeDefaultImpls, so injecting it here adds a trailing `I` and changes the
+      // value-class mangled name, leaving a cross-target implementer overriding a signature the
+      // real ABI does not have. Keyed on having a body, not on modality, so bodiless fake
+      // overrides are treated alike.
+      val hasBody = function.body != null
+      val hasDefaults = existingValueParams.any { it.defaultValue != null }
+      val defaultCount =
+          if (hasDefaults && hasBody) ceilDiv(realValueParamCount, BITS_PER_DEFAULT_INT) else 0
+
+      // Build the new parameter list: existing + $composer + $changed[N] + $default[N]
+      val newParams = mutableListOf<IrValueParameter>()
+      newParams.addAll(existingValueParams)
+
+      var paramIndex = existingValueParams.size
+
+      // Add $composer: Composer?
+      newParams.add(
+          pluginContext.irFactory
+              .createValueParameter(
+                  startOffset = -1,
+                  endOffset = -1,
+                  origin = IrDeclarationOrigin.DEFINED,
+                  name = Name.identifier("\$composer"),
+                  type = composerIrType,
+                  isAssignable = false,
+                  symbol = org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl(),
+                  index = paramIndex,
+                  varargElementType = null,
+                  isCrossinline = false,
+                  isNoinline = false,
+                  isHidden = false,
+              )
+              .also { it.parent = function },
+      )
+      paramIndex++
+
+      // Add $changed, $changed1, $changed2, ...
+      for (i in 0 until changedCount) {
+        val name = if (i == 0) "\$changed" else "\$changed$i"
+        newParams.add(
+            pluginContext.irFactory
+                .createValueParameter(
+                    startOffset = -1,
+                    endOffset = -1,
+                    origin = IrDeclarationOrigin.DEFINED,
+                    name = Name.identifier(name),
+                    type = pluginContext.irBuiltIns.intType,
+                    isAssignable = false,
+                    symbol = org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl(),
+                    index = paramIndex,
+                    varargElementType = null,
+                    isCrossinline = false,
+                    isNoinline = false,
+                    isHidden = false,
+                )
+                .also { it.parent = function },
+        )
+        paramIndex++
+      }
+
+      // Add $default, $default1, $default2, ...
+      for (i in 0 until defaultCount) {
+        val name = if (i == 0) "\$default" else "\$default$i"
+        newParams.add(
+            pluginContext.irFactory
+                .createValueParameter(
+                    startOffset = -1,
+                    endOffset = -1,
+                    origin = IrDeclarationOrigin.DEFINED,
+                    name = Name.identifier(name),
+                    type = pluginContext.irBuiltIns.intType,
+                    isAssignable = false,
+                    symbol = org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl(),
+                    index = paramIndex,
+                    varargElementType = null,
+                    isCrossinline = false,
+                    isNoinline = false,
+                    isHidden = false,
+                )
+                .also { it.parent = function },
+        )
+        paramIndex++
+      }
+
+      function.valueParameters = newParams
+      stampAccessorJvmName(function)
+    }
+
+    // A @Composable PROPERTY ACCESSOR must keep the plain JVM name of the accessor.
+    //
+    // ComposerParamTransformer.copyWithComposerParam stamps @JvmName(getterName(property)) on every
+    // accessor it rewrites, and @JvmName suppresses both the value-class mangle and the $module
+    // suffix the JVM backend would otherwise apply. Injecting the synthetic params in place leaves
+    // neither suppressed, so the stub advertises a name the real jar does not have. Measured on
+    // MdsButton$Type:
+    //
+    //   real: getMinHeight(Composer, int)F
+    //   stub: getMinHeight-chRvn1I$fbandroid_java_com_facebook_mds_compose_button_button(
+    //             Composer, int)F
+    //
+    // A consumer compiled against the stub links the mangled name -> NoSuchMethodError. A
+    // @Composable FUNCTION has no corresponding property, gets no @JvmName from the real
+    // transformer either, and must keep both manglings -- which is why this is scoped to accessors.
+    private fun stampAccessorJvmName(function: IrSimpleFunction) {
+      val property = function.correspondingPropertySymbol?.owner ?: return
+      if (function.hasAnnotation(JVM_NAME_FQ_NAME)) return
+      val constructor = jvmNameClass?.constructors?.singleOrNull() ?: return
+      val propertyName = property.name.identifier
+      val accessorName =
+          if (property.setter == function) JvmAbi.setterName(propertyName)
+          else JvmAbi.getterName(propertyName)
+      val annotation =
+          pluginContext.irBuiltIns.createIrBuilder(function.symbol).run {
+            irCallConstructor(constructor, emptyList()).apply {
+              putValueArgument(
+                  0,
+                  IrConstImpl.string(-1, -1, pluginContext.irBuiltIns.stringType, accessorName),
+              )
+            }
+          }
+      function.annotations = function.annotations + annotation
+    }
+  }
+
+  /**
+   * Removes override links whose source-level dependency declarations lack Compose's synthetic
+   * parameters. The transformed JVM descriptor still matches the dependency's real Compose-lowered
+   * descriptor, so no bridge is needed to preserve the override in bytecode.
+   */
+  private inner class OverrideLinkRepairVisitor : IrElementVisitorVoidCompat() {
+    override fun visitElement(element: IrElement) {
+      element.acceptChildren(this, null)
+    }
+
+    override fun visitSimpleFunction(declaration: IrSimpleFunction) {
+      if (declaration.hasInjectedComposerParam() && declaration.overriddenSymbols.isNotEmpty()) {
+        declaration.overriddenSymbols =
+            declaration.overriddenSymbols.filter { it.owner.hasInjectedComposerParam() }
+      }
+      super.visitSimpleFunction(declaration)
+    }
+  }
+
+  private fun IrSimpleFunction.hasInjectedComposerParam(): Boolean = valueParameters.any {
+    it.name.asString() == "\$composer"
+  }
+}
+
+/** Integer ceiling division: ceil(a / b) for positive a, b. */
+private fun ceilDiv(a: Int, b: Int): Int = (a + b - 1) / b
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/parcelize/ParcelableCreatorEmulator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/parcelize/ParcelableCreatorEmulator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/parcelize/ParcelableCreatorEmulator.kt
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+@file:Suppress("OPT_IN_USAGE_ERROR")
+
+package com.facebook
+
+import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
+import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
+import org.jetbrains.kotlin.descriptors.Modality
+import org.jetbrains.kotlin.ir.IrElement
+import org.jetbrains.kotlin.ir.declarations.IrClass
+import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
+import org.jetbrains.kotlin.ir.declarations.IrField
+import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
+import org.jetbrains.kotlin.ir.declarations.IrProperty
+import org.jetbrains.kotlin.ir.symbols.UnsafeDuringIrConstructionAPI
+import org.jetbrains.kotlin.ir.symbols.impl.IrFieldSymbolImpl
+import org.jetbrains.kotlin.ir.types.starProjectedType
+import org.jetbrains.kotlin.ir.types.typeWith
+import org.jetbrains.kotlin.ir.util.companionObject
+import org.jetbrains.kotlin.ir.util.hasAnnotation
+import org.jetbrains.kotlin.ir.util.isInterface
+import org.jetbrains.kotlin.ir.visitors.IrVisitorVoid
+import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
+import org.jetbrains.kotlin.name.ClassId
+import org.jetbrains.kotlin.name.FqName
+import org.jetbrains.kotlin.name.Name
+
+internal class ParcelableCreatorEmulator(private val pluginContext: IrPluginContext) {
+
+  fun transform(moduleFragment: IrModuleFragment) {
+    val creatorClass = pluginContext.referenceClass(PARCELABLE_CREATOR_CLASS_ID) ?: return
+    moduleFragment.acceptChildrenVoid(
+        object : IrVisitorVoid() {
+          override fun visitElement(element: IrElement) {
+            element.acceptChildrenVoid(this)
+          }
+
+          override fun visitClass(declaration: IrClass) {
+            if (declaration.needsCreator()) {
+              declaration.addCreatorField(creatorClass.owner)
+            }
+            declaration.acceptChildrenVoid(this)
+          }
+        },
+    )
+  }
+
+  @OptIn(UnsafeDuringIrConstructionAPI::class)
+  private fun IrClass.needsCreator(): Boolean {
+    if (!hasAnnotation(PARCELIZE_FQ_NAME)) return false
+    if (isInterface || modality == Modality.ABSTRACT || modality == Modality.SEALED) return false
+    return !declaresCreator() && companionObject()?.declaresCreator() != true
+  }
+
+  @OptIn(UnsafeDuringIrConstructionAPI::class)
+  private fun IrClass.declaresCreator(): Boolean = declarations.any {
+    (it as? IrField)?.name == CREATOR_NAME ||
+        (it as? IrProperty)?.name == CREATOR_NAME ||
+        (it as? IrClass)?.name == CREATOR_NAME
+  }
+
+  @OptIn(UnsafeDuringIrConstructionAPI::class)
+  private fun IrClass.addCreatorField(creatorClass: IrClass) {
+    val field =
+        pluginContext.irFactory.createField(
+            startOffset = -1,
+            endOffset = -1,
+            origin = IrDeclarationOrigin.DEFINED,
+            name = CREATOR_NAME,
+            type = creatorClass.symbol.typeWith(symbol.starProjectedType),
+            visibility = DescriptorVisibilities.PUBLIC,
+            symbol = IrFieldSymbolImpl(),
+            isFinal = true,
+            isExternal = false,
+            isStatic = true,
+        )
+    field.parent = this
+    declarations.add(field)
+  }
+
+  private companion object {
+    val CREATOR_NAME = Name.identifier("CREATOR")
+    val PARCELIZE_FQ_NAME = FqName("kotlinx.parcelize.Parcelize")
+    val PARCELABLE_CREATOR_CLASS_ID =
+        ClassId(FqName("android.os"), FqName("Parcelable.Creator"), isLocal = false)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/parcelize/ParcelizeAbiEmulationExtension.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/parcelize/ParcelizeAbiEmulationExtension.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/parcelize/ParcelizeAbiEmulationExtension.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+
+package com.facebook
+
+import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
+import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
+import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
+
+internal class ParcelizeAbiEmulationExtension : IrGenerationExtension {
+
+  override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
+    ParcelableCreatorEmulator(pluginContext).transform(moduleFragment)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenContext.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenContext.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenContext.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+
+package com.facebook
+
+import java.io.File
+import org.jetbrains.kotlin.cli.common.messages.MessageCollector
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.psi.KtFile
+
+/**
+ * Context passed through the ABI generation pipeline stages.
+ *
+ * Populated progressively as the pipeline advances through phases:
+ * - firResult is set after FIR frontend analysis
+ * - irBackendInput is set after FIR-to-IR conversion
+ */
+class AbiGenContext(
+    val outputDir: File,
+    val messageCollector: MessageCollector,
+    val configuration: CompilerConfiguration,
+    val sourceFiles: List<KtFile>,
+    val firResult: FirResultCompat,
+) {
+  /** Set after FIR-to-IR conversion. */
+  var irBackendInput: ModuleCompilerIrBackendInputCompat? = null
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenPipeline.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenPipeline.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenPipeline.kt
@@ -0,0 +1,2302 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+@file:Suppress("OPT_IN_USAGE_ERROR")
+@file:OptIn(
+    com.facebook.DeprecatedForRemovalCompilerApiCompat::class,
+    com.facebook.DirectDeclarationsAccessCompat::class,
+)
+
+package com.facebook
+
+import com.facebook.kotlin.compilercompat.callableNameOrNullCompat
+import com.facebook.kotlin.compilercompat.packageNameOrNullCompat
+import java.io.File
+import java.util.jar.JarFile
+import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
+import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
+import org.jetbrains.kotlin.cli.common.messages.MessageCollector
+import org.jetbrains.kotlin.descriptors.ClassKind
+import org.jetbrains.kotlin.descriptors.Visibilities
+import org.jetbrains.kotlin.fir.FirElement
+import org.jetbrains.kotlin.fir.FirSession
+import org.jetbrains.kotlin.fir.backend.FirMetadataSource
+import org.jetbrains.kotlin.fir.declarations.FirCallableDeclaration
+import org.jetbrains.kotlin.fir.declarations.FirDeclaration
+import org.jetbrains.kotlin.fir.declarations.FirDeclarationOrigin
+import org.jetbrains.kotlin.fir.declarations.FirFile
+import org.jetbrains.kotlin.fir.declarations.FirFunction
+import org.jetbrains.kotlin.fir.declarations.FirProperty
+import org.jetbrains.kotlin.fir.declarations.FirRegularClass
+import org.jetbrains.kotlin.fir.declarations.utils.isConst
+import org.jetbrains.kotlin.fir.expressions.FirAnnotation
+import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
+import org.jetbrains.kotlin.fir.expressions.FirErrorExpression
+import org.jetbrains.kotlin.fir.expressions.FirGetClassCall
+import org.jetbrains.kotlin.fir.expressions.FirNamedArgumentExpression
+import org.jetbrains.kotlin.fir.expressions.FirQualifiedAccessExpression
+import org.jetbrains.kotlin.fir.expressions.FirVarargArgumentsExpression
+import org.jetbrains.kotlin.fir.expressions.FirWrappedArgumentExpression
+import org.jetbrains.kotlin.fir.expressions.impl.FirResolvedArgumentList
+import org.jetbrains.kotlin.fir.moduleData
+import org.jetbrains.kotlin.fir.references.FirErrorNamedReference
+import org.jetbrains.kotlin.fir.references.FirResolvedNamedReference
+import org.jetbrains.kotlin.fir.resolve.providers.symbolProvider
+import org.jetbrains.kotlin.fir.serialization.providedDeclarationsForMetadataService
+import org.jetbrains.kotlin.fir.symbols.SymbolInternals
+import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
+import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
+import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol
+import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
+import org.jetbrains.kotlin.fir.types.ConeErrorType
+import org.jetbrains.kotlin.fir.types.ConeKotlinType
+import org.jetbrains.kotlin.fir.types.ConeTypeProjection
+import org.jetbrains.kotlin.fir.types.coneType
+import org.jetbrains.kotlin.fir.types.constructType
+import org.jetbrains.kotlin.fir.types.resolvedType
+import org.jetbrains.kotlin.fir.types.type
+import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitorVoid
+import org.jetbrains.kotlin.ir.IrElement
+import org.jetbrains.kotlin.ir.declarations.IrClass
+import org.jetbrains.kotlin.ir.declarations.IrConstructor
+import org.jetbrains.kotlin.ir.declarations.IrDeclarationBase
+import org.jetbrains.kotlin.ir.declarations.IrFile
+import org.jetbrains.kotlin.ir.declarations.IrMetadataSourceOwner
+import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
+import org.jetbrains.kotlin.ir.declarations.IrProperty
+import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
+import org.jetbrains.kotlin.ir.util.kotlinFqName
+import org.jetbrains.kotlin.name.CallableId
+import org.jetbrains.kotlin.name.ClassId
+import org.jetbrains.kotlin.name.FqName
+import org.jetbrains.kotlin.psi.KtFile
+import org.jetbrains.org.objectweb.asm.AnnotationVisitor
+import org.jetbrains.org.objectweb.asm.ClassReader
+import org.jetbrains.org.objectweb.asm.ClassVisitor
+import org.jetbrains.org.objectweb.asm.ConstantDynamic
+import org.jetbrains.org.objectweb.asm.FieldVisitor
+import org.jetbrains.org.objectweb.asm.Handle
+import org.jetbrains.org.objectweb.asm.Label
+import org.jetbrains.org.objectweb.asm.MethodVisitor
+import org.jetbrains.org.objectweb.asm.ModuleVisitor
+import org.jetbrains.org.objectweb.asm.Opcodes
+import org.jetbrains.org.objectweb.asm.RecordComponentVisitor
+import org.jetbrains.org.objectweb.asm.Type
+import org.jetbrains.org.objectweb.asm.TypePath
+import org.jetbrains.org.objectweb.asm.signature.SignatureReader
+import org.jetbrains.org.objectweb.asm.signature.SignatureVisitor
+
+fun errorTypedApiPositions(
+    isProperty: Boolean,
+    returnTypeHasError: Boolean,
+    propertyTypeHasError: Boolean,
+    receiverHasError: Boolean,
+    contextParameterErrors: List<Boolean>,
+    valueParameterErrors: List<Boolean>,
+): List<String> = buildList {
+  if (isProperty) {
+    if (propertyTypeHasError) add("property type")
+  } else if (returnTypeHasError) {
+    add("return type")
+  }
+  if (receiverHasError) add("receiver")
+  contextParameterErrors.forEachIndexed { index, hasError ->
+    if (hasError) add("context parameter $index")
+  }
+  valueParameterErrors.forEachIndexed { index, hasError ->
+    if (hasError) add("parameter $index")
+  }
+}
+
+/**
+ * FIR metadata sanitization stage.
+ *
+ * Handles both pre-IR FIR tree cleanup and post-IR FIR metadata source cleanup:
+ * - Strip annotations with errors and fix property initializers (FIR tree, pre-IR, single pass)
+ * - Strip @Throws from FIR metadata sources (post-IR)
+ * - Strip annotations with errors from FIR metadata sources (post-IR)
+ * - Strip private supertypes + fake override conversion (post-IR)
+ */
+internal class FirMetadataSanitizerStage(private val repairLog: AbiGenRepairLog) : AbiGenStage {
+  override val name = "FirMetadataSanitizer"
+
+  /**
+   * Pre-IR: cleanup the FIR tree before FIR-to-IR conversion in a single pass.
+   *
+   * Combines two operations that both walk the FIR tree:
+   * 1. Strip ALL annotations that have error expressions in their arguments.
+   * 2. Fix property initializers containing error expressions (clear them).
+   */
+  fun cleanupFirTree(firResult: FirResultCompat) {
+    for (output in firResult.outputs) {
+      for (firFile in output.fir) {
+        firFile.accept(FirSanitizingVisitor())
+      }
+    }
+  }
+
+  /**
+   * Post-IR: cleanup FIR metadata sources attached to IR declarations in a single IR tree walk.
+   *
+   * Combines three operations that all walk the IR module visiting classes, functions, properties,
+   * and constructors to access FirMetadataSource:
+   * 1. Strip @Throws annotations with error types from FIR metadata sources.
+   * 2. Strip ALL annotations with error expressions from FIR metadata sources.
+   * 3. Strip PRIVATE supertypes from FIR metadata sources.
+   */
+  fun cleanupFirMetadataSources(moduleFragment: IrModuleFragment, session: FirSession) {
+    val THROWS_FQ_NAME = FqName("kotlin.jvm.Throws")
+    val THROWS_KOTLIN_FQ_NAME = FqName("kotlin.Throws")
+
+    moduleFragment.accept(
+        object : IrElementVisitorVoidCompat() {
+          override fun visitElement(element: IrElement) {
+            element.acceptChildren(this, null)
+          }
+
+          override fun visitFile(declaration: IrFile) {
+            degradeErrorTypedFileMemberTypes(declaration)
+            super.visitFile(declaration)
+          }
+
+          override fun visitClass(declaration: IrClass) {
+            stripThrowsAndErrorAnnotationsFromDeclaration(declaration)
+            stripPrivateSupertypesFromDeclaration(declaration)
+            stripErrorTypedPrivateMembersFromDeclaration(declaration)
+            super.visitClass(declaration)
+          }
+
+          override fun visitSimpleFunction(declaration: IrSimpleFunction) {
+            stripThrowsAndErrorAnnotationsFromDeclaration(declaration)
+            degradeErrorTypedMetadataSource(declaration, session)
+            super.visitSimpleFunction(declaration)
+          }
+
+          override fun visitProperty(declaration: IrProperty) {
+            stripThrowsAndErrorAnnotationsFromDeclaration(declaration)
+            degradeErrorTypedMetadataSource(declaration, session)
+            super.visitProperty(declaration)
+          }
+
+          override fun visitConstructor(declaration: IrConstructor) {
+            stripThrowsAndErrorAnnotationsFromDeclaration(declaration)
+            degradeErrorTypedMetadataSource(declaration, session)
+            super.visitConstructor(declaration)
+          }
+
+          private fun stripThrowsAndErrorAnnotationsFromDeclaration(
+              declaration: IrDeclarationBase,
+          ) {
+            val metadataSourceOwner = declaration as? IrMetadataSourceOwner ?: return
+            val metadataSource = metadataSourceOwner.metadata ?: return
+            val firMetadataSource = metadataSource as? FirMetadataSource ?: return
+
+            stripThrowsFromFirDeclaration(firMetadataSource.fir)
+            stripAnnotationsWithErrorsFromFirDeclaration(firMetadataSource.fir)
+          }
+
+          // Degrade error-typed NON-API (private/local) members of a class to `Any?` on the FIR
+          // metadata source. In source-only ABI, a private member with an inferred type that
+          // depends on an unresolvable dependency symbol (e.g.
+          // `private val x = Dep.getInstance()` or `private val y = setOf(Dep.CONST)`) gets an
+          // error return type, which FirElementSerializer.propertyProto cannot serialize into
+          // @Metadata ("Cannot serialize error type").
+          //
+          // The metadata serializer iterates the class member SYMBOLS
+          // (firClass.symbol.declarationSymbols), which can still include members that earlier IR
+          // stripping removed from firClass.declarations, so the return type has to be replaced on
+          // the symbols' FIR — not just on the declarations list.
+          //
+          // API members are deliberately left alone: they are part of the ABI, so degrading their
+          // type would produce an ABI that lies to consumers (metadata says `Any?` while the
+          // bytecode descriptor still says `error/NonExistentClass`), turning a loud build failure
+          // into a silent one. Those targets must fix the missing dependency / add an explicit
+          // type instead.
+          @OptIn(SymbolInternals::class)
+          private fun stripErrorTypedPrivateMembersFromDeclaration(declaration: IrClass) {
+            val metadataSourceOwner = declaration as? IrMetadataSourceOwner ?: return
+            val firMetadataSource = metadataSourceOwner.metadata as? FirMetadataSource ?: return
+            val firClass = firMetadataSource.fir as? FirRegularClass ?: return
+
+            // A member of a private/local class is not ABI surface even when it is declared
+            // public: no consumer can reference it, so degrading its unserializable type cannot
+            // make the ABI lie to anyone. This covers the common
+            // `private object Utils { fun get() = Dep.somethingUnresolvable() }` shape, where the
+            // member's own visibility is public but the enclosing object is private.
+            val classIsNonApi = isClassEffectivelyPrivate(declaration)
+
+            firClass.symbol.declarationSymbols.forEach { symbol ->
+              val decl = (symbol as? FirCallableSymbol<*>)?.fir ?: return@forEach
+              if (!classIsNonApi && !isNonApiVisibility(decl)) {
+                recordErrorTypedApiMember(firClass.symbol.classId.asString(), decl)
+                return@forEach
+              }
+              // The metadata serializer collects functions/constructors from the class member
+              // SCOPE, which references these same symbols' FIR. An error type in any position the
+              // serializer reads — the return type, a value parameter (e.g. a parameter typed by a
+              // nested enum of a stubbed dependency such as `CdsNavigationBar.Action`), or a
+              // property's accessors/backing field — crashes FirElementSerializer the same way, so
+              // degrade all of them to `Any?` here. The IR-visitor pass only reaches these via
+              // firClass.declarations, which can be missing members served only from the scope.
+              degradeErrorTypedPositions(decl, session)
+            }
+
+            // Belt-and-suspenders: also cover anything present only in firClass.declarations.
+            // Mirror the symbol loop's asymmetry - degrade non-API members, record API ones - so an
+            // error-typed API member reachable only via this path is not silently missed by
+            // Assertion 5. recordErrorTypedApiMember de-duplicates, so members served from both
+            // paths are recorded once.
+            firClass.declarations.forEach { decl ->
+              if (decl !is FirCallableDeclaration) return@forEach
+              if (!classIsNonApi && !isNonApiVisibility(decl)) {
+                recordErrorTypedApiMember(firClass.symbol.classId.asString(), decl)
+                return@forEach
+              }
+              degradeErrorTypedPositions(decl, session)
+            }
+          }
+
+          private fun degradeErrorTypedMetadataSource(
+              declaration: IrDeclarationBase,
+              session: FirSession,
+          ) {
+            val metadataSourceOwner = declaration as? IrMetadataSourceOwner ?: return
+            val firMetadataSource = metadataSourceOwner.metadata as? FirMetadataSource ?: return
+            val fir = firMetadataSource.fir as? FirCallableDeclaration ?: return
+            if (!isNonApiVisibility(fir)) return
+            degradeErrorTypedPositions(fir, session)
+          }
+
+          // The file facade's @Metadata is serialized by FirElementSerializer.packagePartProto,
+          // which iterates firFile.declarations. A private top-level member is deleted from the IR
+          // by the IR sanitizer before this pass runs, so visitSimpleFunction/visitProperty never
+          // reach it, yet the serializer still reads it from the FIR file and crashes on its error
+          // type (e.g. `private fun f() = Dep.unresolved()`).
+          private fun degradeErrorTypedFileMemberTypes(declaration: IrFile) {
+            val firFile = (declaration.metadata as? FirMetadataSource)?.fir as? FirFile ?: return
+            firFile.declarations.forEach { decl ->
+              if (decl !is FirCallableDeclaration) return@forEach
+              if (isNonApiVisibility(decl)) {
+                degradeErrorTypedPositions(decl, session)
+              } else {
+                recordErrorTypedApiMember(
+                    // Null callableId (2.3+) degrades to "<unknown>"; a legitimate
+                    // root package stays "". Version detail lives in the buckets
+                    // via packageNameOrNullCompat().
+                    decl.symbol.packageNameOrNullCompat() ?: "<unknown>",
+                    decl,
+                )
+              }
+            }
+          }
+
+          // Degrade every error-typed position the serializer reads for a callable, not just its
+          // own return type. propertyProto serializes the setter's value parameter whenever the
+          // accessors are non-default, which is the case for a delegated property
+          // (`private var x by AtomicReference(...)` with an unresolved `getValue`), so degrading
+          // only the property return type leaves the crash in place.
+          private fun degradeErrorTypedPositions(
+              decl: FirCallableDeclaration,
+              session: FirSession,
+          ) {
+            decl.receiverParameter?.let { receiver ->
+              if (
+                  runCatching { receiver.typeRef.coneType.containsErrorType() }.getOrDefault(true)
+              ) {
+                runCatching { receiver.replaceTypeRef(session.builtinTypes.nullableAnyType) }
+                    .onFailure { failure ->
+                      repairLog.recordFailedRepair(
+                          decl.symbol.callableId.toString(),
+                          "could not degrade unresolved receiver: " +
+                              "${failure.javaClass.simpleName}: ${failure.message}",
+                      )
+                    }
+              }
+            }
+            decl.contextParameters.forEachIndexed { index, parameter ->
+              if (hasErrorReturnType(parameter)) {
+                runCatching {
+                  parameter.replaceReturnTypeRef(session.builtinTypes.nullableAnyType)
+                }
+                    .onFailure { failure ->
+                      repairLog.recordFailedRepair(
+                          decl.symbol.callableId.toString(),
+                          "could not degrade unresolved context parameter $index: " +
+                              "${failure.javaClass.simpleName}: ${failure.message}",
+                      )
+                    }
+              }
+            }
+
+            if (decl is FirProperty) {
+              // The property declaration, getter return and setter value parameter describe the
+              // same JVM property type and must be degraded together. A delegated property's
+              // backing field has the delegate type instead, so handle it independently.
+              val accessorTypePositions =
+                  buildList<FirCallableDeclaration> {
+                    add(decl)
+                    decl.getter?.let { add(it) }
+                    decl.setter?.let { addAll(it.valueParameters) }
+                  }
+              if (accessorTypePositions.any { hasErrorReturnType(it) }) {
+                accessorTypePositions.forEach { replaceReturnTypeWithAny(it, session) }
+              }
+              decl.backingField?.let { degradeReturnTypeIfError(it, session) }
+              return
+            }
+            // A function's return type and each of its value parameters are independent, so they
+            // are degraded one by one to keep the degradation as narrow as possible.
+            degradeReturnTypeIfError(decl, session)
+            if (decl is FirFunction) {
+              decl.valueParameters.forEach { degradeReturnTypeIfError(it, session) }
+            }
+          }
+
+          private fun degradeReturnTypeIfError(
+              decl: FirCallableDeclaration,
+              session: FirSession,
+          ) {
+            if (!hasErrorReturnType(decl)) return
+            replaceReturnTypeWithAny(decl, session)
+          }
+
+          private fun replaceReturnTypeWithAny(
+              decl: FirCallableDeclaration,
+              session: FirSession,
+          ) {
+            runCatching { decl.replaceReturnTypeRef(session.builtinTypes.nullableAnyType) }
+                .onFailure { failure ->
+                  repairLog.recordFailedRepair(
+                      decl.symbol.callableId.toString(),
+                      "could not degrade unresolved type: " +
+                          "${failure.javaClass.simpleName}: ${failure.message}",
+                  )
+                }
+          }
+
+          // --- @Throws stripping helpers ---
+
+          private fun stripThrowsFromFirDeclaration(
+              declaration: org.jetbrains.kotlin.fir.declarations.FirDeclaration?,
+          ) {
+            if (declaration == null) return
+
+            try {
+              val annotationsField = declaration.javaClass.getDeclaredField("annotations")
+              annotationsField.isAccessible = true
+              val annotationsWrapper = annotationsField.get(declaration) ?: return
+
+              val listField = annotationsWrapper.javaClass.getDeclaredField("list")
+              listField.isAccessible = true
+              @Suppress("UNCHECKED_CAST")
+              val annotations =
+                  listField.get(annotationsWrapper) as? MutableList<FirAnnotation> ?: return
+
+              val toRemove = annotations.filter { annotation ->
+                hasErrorTypeInThrowsAnnotation(
+                    annotation,
+                    THROWS_FQ_NAME,
+                    THROWS_KOTLIN_FQ_NAME,
+                )
+              }
+
+              if (toRemove.isNotEmpty()) {
+                annotations.removeAll(toRemove)
+              }
+            } catch (_: Exception) {
+              // If reflection fails, skip this declaration
+            }
+          }
+
+          private fun hasErrorTypeInThrowsAnnotation(
+              annotation: FirAnnotation,
+              throwsFqName: FqName,
+              throwsKotlinFqName: FqName,
+          ): Boolean {
+            val annotationType = annotation.annotationTypeRef.coneType
+            val fqName =
+                (annotationType as? org.jetbrains.kotlin.fir.types.ConeClassLikeType)
+                    ?.lookupTag
+                    ?.classId
+                    ?.asSingleFqName()
+
+            if (fqName != throwsFqName && fqName != throwsKotlinFqName) {
+              return false
+            }
+
+            val annotationCall = annotation as? FirAnnotationCall ?: return false
+            val argumentList = annotationCall.argumentList
+            if (argumentList is FirResolvedArgumentList) {
+              for ((argument, _) in argumentList.mapping) {
+                if (hasErrorTypeInFirClassReference(argument)) {
+                  return true
+                }
+              }
+            }
+            return false
+          }
+
+          private fun hasErrorTypeInFirClassReference(element: FirElement): Boolean {
+            return when (element) {
+              is FirVarargArgumentsExpression ->
+                  element.arguments.any { hasErrorTypeInFirClassReference(it) }
+              is FirGetClassCall -> {
+                try {
+                  val argument = element.argument
+                  if (argument is FirQualifiedAccessExpression) {
+                    argument.resolvedType is ConeErrorType
+                  } else {
+                    element.resolvedType is ConeErrorType
+                  }
+                } catch (_: Exception) {
+                  false
+                }
+              }
+              is FirQualifiedAccessExpression -> {
+                try {
+                  element.resolvedType is ConeErrorType ||
+                      element.calleeReference is FirErrorNamedReference
+                } catch (_: Exception) {
+                  false
+                }
+              }
+              is FirErrorExpression -> true
+              else -> false
+            }
+          }
+
+          // --- Annotation error stripping helpers ---
+
+          private fun stripAnnotationsWithErrorsFromFirDeclaration(
+              declaration: org.jetbrains.kotlin.fir.declarations.FirDeclaration?,
+          ) {
+            if (declaration == null) return
+
+            try {
+              val annotationsField = declaration.javaClass.getDeclaredField("annotations")
+              annotationsField.isAccessible = true
+              val annotationsWrapper = annotationsField.get(declaration) ?: return
+
+              val listField = annotationsWrapper.javaClass.getDeclaredField("list")
+              listField.isAccessible = true
+              @Suppress("UNCHECKED_CAST")
+              val annotations =
+                  listField.get(annotationsWrapper) as? MutableList<FirAnnotation> ?: return
+
+              val toRemove = annotations.filter { annotation ->
+                hasErrorExpressionInFirAnnotation(annotation)
+              }
+
+              if (toRemove.isNotEmpty()) {
+                annotations.removeAll(toRemove)
+              }
+            } catch (_: Exception) {
+              // If reflection fails, skip this declaration
+            }
+          }
+
+          private fun hasErrorExpressionInFirAnnotation(annotation: FirAnnotation): Boolean {
+            val annotationCall = annotation as? FirAnnotationCall ?: return false
+            val argumentList = annotationCall.argumentList
+            if (argumentList is FirResolvedArgumentList) {
+              for ((argument, _) in argumentList.mapping) {
+                if (hasErrorExpressionInFirElement(argument)) {
+                  return true
+                }
+              }
+            }
+            return false
+          }
+
+          private fun hasErrorExpressionInFirElement(element: FirElement): Boolean {
+            return when (element) {
+              is FirErrorExpression -> true
+              is FirNamedArgumentExpression -> hasErrorExpressionInFirElement(element.expression)
+              is FirWrappedArgumentExpression -> hasErrorExpressionInFirElement(element.expression)
+              is FirVarargArgumentsExpression ->
+                  element.arguments.any { hasErrorExpressionInFirElement(it) }
+              is FirQualifiedAccessExpression -> {
+                try {
+                  element.resolvedType is ConeErrorType ||
+                      element.calleeReference is FirErrorNamedReference
+                } catch (_: Exception) {
+                  false
+                }
+              }
+              is FirGetClassCall -> {
+                try {
+                  val argument = element.argument
+                  if (argument is FirQualifiedAccessExpression) {
+                    argument.resolvedType is ConeErrorType
+                  } else {
+                    element.resolvedType is ConeErrorType
+                  }
+                } catch (_: Exception) {
+                  false
+                }
+              }
+              is org.jetbrains.kotlin.fir.expressions.FirFunctionCall -> {
+                try {
+                  element.resolvedType is ConeErrorType ||
+                      element.calleeReference is FirErrorNamedReference
+                } catch (_: Exception) {
+                  false
+                }
+              }
+              else -> false
+            }
+          }
+
+          // --- Private supertype stripping helpers ---
+
+          @OptIn(SymbolInternals::class)
+          private fun stripPrivateSupertypesFromDeclaration(declaration: IrClass) {
+            val metadataSourceOwner = declaration as? IrMetadataSourceOwner ?: return
+            val metadataSource = metadataSourceOwner.metadata ?: return
+            val firMetadataSource = metadataSource as? FirMetadataSource ?: return
+            val firClass = firMetadataSource.fir as? FirRegularClass ?: return
+
+            val strippedSupertypeClassIds = mutableSetOf<ClassId>()
+
+            try {
+              val superTypeRefsField = firClass.javaClass.getDeclaredField("superTypeRefs")
+              superTypeRefsField.isAccessible = true
+              val superTypeRefsValue = superTypeRefsField.get(firClass) ?: return
+
+              @Suppress("UNCHECKED_CAST")
+              val superTypeRefs: MutableList<org.jetbrains.kotlin.fir.types.FirTypeRef> =
+                  when (superTypeRefsValue) {
+                    is MutableList<*> ->
+                        superTypeRefsValue as MutableList<org.jetbrains.kotlin.fir.types.FirTypeRef>
+                    else -> {
+                      val listField =
+                          superTypeRefsValue.javaClass.declaredFields.find { it.name == "list" }
+                              ?: return
+                      listField.isAccessible = true
+                      listField.get(superTypeRefsValue)
+                          as? MutableList<org.jetbrains.kotlin.fir.types.FirTypeRef> ?: return
+                    }
+                  }
+
+              val toRemove = superTypeRefs.filter { typeRef ->
+                isPrivateSupertype(typeRef, firClass)
+              }
+
+              for (typeRef in toRemove) {
+                val classId = getPrivateClassIdFromTypeRef(typeRef)
+                if (classId != null) {
+                  strippedSupertypeClassIds.add(classId)
+                }
+              }
+
+              if (toRemove.isNotEmpty()) {
+                superTypeRefs.removeAll(toRemove)
+
+                for (classId in strippedSupertypeClassIds) {
+                  repairLog.recordStrippedSupertype(
+                      firClass.symbol.classId.asString(),
+                      "private supertype ${classId.asString()} removed from ABI",
+                  )
+                }
+
+                convertFirFakeOverridesFromStrippedPrivateSupertypes(
+                    firClass,
+                    strippedSupertypeClassIds,
+                )
+              }
+            } catch (e: Exception) {
+              repairLog.recordFailedRepair(
+                  firClass.symbol.classId.asString(),
+                  "could not strip private supertypes: ${e.javaClass.simpleName}: ${e.message}",
+              )
+            }
+          }
+
+          private fun getPrivateClassIdFromTypeRef(
+              typeRef: org.jetbrains.kotlin.fir.types.FirTypeRef,
+          ): ClassId? {
+            val coneType =
+                (typeRef as? org.jetbrains.kotlin.fir.types.FirResolvedTypeRef)?.coneType
+                    ?: return null
+            return (coneType as? org.jetbrains.kotlin.fir.types.ConeClassLikeType)
+                ?.lookupTag
+                ?.classId
+          }
+
+          @OptIn(SymbolInternals::class)
+          private fun convertFirFakeOverridesFromStrippedPrivateSupertypes(
+              firClass: FirRegularClass,
+              strippedSupertypeClassIds: Set<ClassId>,
+          ) {
+            if (strippedSupertypeClassIds.isEmpty()) return
+
+            val interfaceMethods = collectMethodsFromPrivateInterfaces(
+                firClass.moduleData.session,
+                strippedSupertypeClassIds,
+            )
+
+            if (interfaceMethods.isEmpty()) return
+
+            val existingMethodNames =
+                firClass.declarations
+                    .filterIsInstance<FirNamedFunctionCompat>()
+                    .map { it.name.asString() }
+                    .toSet()
+
+            for (interfaceMethod in interfaceMethods) {
+              val methodName = interfaceMethod.name.asString()
+              if (methodName in existingMethodNames) continue
+
+              val copiedMethod = copyPrivateInterfaceMethodToClass(interfaceMethod, firClass)
+              if (copiedMethod != null) {
+                (firClass.declarations as MutableList<FirDeclaration>).add(copiedMethod)
+                try {
+                  firClass.moduleData.session.providedDeclarationsForMetadataService
+                      .registerDeclaration(copiedMethod)
+                } catch (e: Exception) {
+                  repairLog.recordFailedRepair(
+                      "${firClass.symbol.classId.asString()}.$methodName",
+                      "could not register materialized interface method: " +
+                          "${e.javaClass.simpleName}: ${e.message}",
+                  )
+                }
+              } else {
+                repairLog.recordFailedRepair(
+                    "${firClass.symbol.classId.asString()}.$methodName",
+                    "could not copy method from stripped private interface",
+                )
+              }
+            }
+          }
+
+          @OptIn(SymbolInternals::class)
+          private fun copyPrivateInterfaceMethodToClass(
+              interfaceMethod: FirNamedFunctionCompat,
+              targetClass: FirRegularClass,
+          ): FirNamedFunctionCompat? {
+            return try {
+              val targetClassId = targetClass.symbol.classId
+              val newCallableId = CallableId(
+                  targetClassId.packageFqName,
+                  targetClassId.relativeClassName,
+                  interfaceMethod.name,
+              )
+              buildNamedFunctionCopyCompat(interfaceMethod) {
+                origin = FirDeclarationOrigin.Source
+                symbol = FirNamedFunctionSymbol(newCallableId)
+                dispatchReceiverType =
+                    targetClass.symbol.constructType(
+                        ConeTypeProjection.EMPTY_ARRAY,
+                        isMarkedNullable = false,
+                    )
+              }
+            } catch (e: Exception) {
+              null
+            }
+          }
+
+          @OptIn(SymbolInternals::class)
+          private fun collectMethodsFromPrivateInterfaces(
+              session: FirSession,
+              interfaceClassIds: Set<ClassId>,
+          ): List<FirNamedFunctionCompat> {
+            val methods = mutableListOf<FirNamedFunctionCompat>()
+            for (classId in interfaceClassIds) {
+              val classSymbol =
+                  session.symbolProvider.getClassLikeSymbolByClassId(classId) as? FirClassSymbol<*>
+                      ?: continue
+              val firClass = classSymbol.fir as? FirRegularClass ?: continue
+              if (firClass.classKind != ClassKind.INTERFACE) continue
+
+              for (decl in firClass.declarations) {
+                if (decl is FirNamedFunctionCompat) {
+                  val visibility = decl.status.visibility
+                  if (visibility == Visibilities.Public || visibility == Visibilities.Protected) {
+                    methods.add(decl)
+                  }
+                }
+              }
+            }
+            return methods
+          }
+
+          private fun isPrivateSupertype(
+              typeRef: org.jetbrains.kotlin.fir.types.FirTypeRef,
+              firClass: FirRegularClass,
+          ): Boolean {
+            try {
+              val coneType =
+                  (typeRef as? org.jetbrains.kotlin.fir.types.FirResolvedTypeRef)?.coneType
+                      ?: return false
+              val classId =
+                  (coneType as? org.jetbrains.kotlin.fir.types.ConeClassLikeType)
+                      ?.lookupTag
+                      ?.classId ?: return false
+
+              val session = firClass.moduleData.session
+              val classSymbol =
+                  session.symbolProvider.getClassLikeSymbolByClassId(classId) as? FirClassSymbol<*>
+                      ?: return false
+
+              if (classSymbol.resolvedStatus.visibility == Visibilities.Local) {
+                return true
+              }
+
+              // Only a top-level private class is dropped from the ABI; nested private classes
+              // are kept so their InnerClasses references resolve. So what matters is whether the
+              // outermost enclosing class is private, not whether any enclosing class is. Walk the
+              // classId chain by name -- which needs no symbol resolution -- and resolve only the
+              // outermost class. Resolving each intermediate enclosing symbol would let one that
+              // fails to resolve mask a top-level-private outermost class and leave the supertype
+              // dangling.
+              var outermostClassId = classId
+              while (outermostClassId.outerClassId != null) {
+                outermostClassId = outermostClassId.outerClassId!!
+              }
+
+              val outermost =
+                  if (outermostClassId == classId) {
+                    classSymbol
+                  } else {
+                    session.symbolProvider.getClassLikeSymbolByClassId(outermostClassId)
+                        as? FirClassSymbol<*> ?: return false
+                  }
+
+              return isClassPrivate(outermost)
+            } catch (e: Exception) {
+              return false
+            }
+          }
+
+          private fun isClassEffectivelyPrivate(irClass: IrClass): Boolean {
+            var current: IrClass? = irClass
+            while (current != null) {
+              if (
+                  current.visibility ==
+                      org.jetbrains.kotlin.descriptors.DescriptorVisibilities.PRIVATE ||
+                      current.visibility ==
+                          org.jetbrains.kotlin.descriptors.DescriptorVisibilities.LOCAL
+              ) {
+                return true
+              }
+              current = current.parent as? IrClass
+            }
+            return false
+          }
+
+          private fun isClassPrivate(classSymbol: FirClassSymbol<*>): Boolean {
+            val visibility = classSymbol.resolvedStatus.visibility
+            return visibility == Visibilities.Private || visibility == Visibilities.Local
+          }
+        },
+        null,
+    )
+  }
+
+  // --- Public utility methods ---
+
+  // Recursively check if a FIR element contains error expressions.
+  // Used by K2JvmAbiFirAnalysisHandlerExtension to check const val initializer resolvability.
+  @OptIn(SymbolInternals::class)
+  fun hasErrorExpressionRecursive(element: FirElement): Boolean {
+    return when (element) {
+      is FirErrorExpression -> true
+      is FirQualifiedAccessExpression -> {
+        try {
+          if (
+              element.resolvedType is ConeErrorType ||
+                  element.calleeReference is FirErrorNamedReference
+          ) {
+            return true
+          }
+
+          val calleeReference = element.calleeReference
+          if (calleeReference is FirResolvedNamedReference) {
+            val symbol = calleeReference.resolvedSymbol
+            if (symbol is FirPropertySymbol && symbol.isConst) {
+              val initializer = symbol.fir.initializer
+              if (initializer == null) {
+                return true
+              }
+              if (isConstValInitializerUnresolvable(initializer)) {
+                return true
+              }
+            }
+          }
+          false
+        } catch (_: Exception) {
+          false
+        }
+      }
+      else -> {
+        var hasError = false
+        element.acceptChildren(
+            object : FirDefaultVisitorVoid() {
+              override fun visitElement(childElement: FirElement) {
+                if (!hasError && hasErrorExpressionRecursive(childElement)) {
+                  hasError = true
+                }
+              }
+            },
+        )
+        hasError
+      }
+    }
+  }
+
+  private fun isConstValInitializerUnresolvable(initializer: FirElement): Boolean {
+    return when (initializer) {
+      is FirErrorExpression -> true
+      is org.jetbrains.kotlin.fir.expressions.FirFunctionCall -> {
+        try {
+          val calleeReference = initializer.calleeReference
+          if (calleeReference is FirResolvedNamedReference) {
+            val name = calleeReference.name.asString()
+            if (name == "TODO") {
+              return true
+            }
+          }
+          initializer.resolvedType is ConeErrorType
+        } catch (_: Exception) {
+          false
+        }
+      }
+      is FirQualifiedAccessExpression -> {
+        try {
+          initializer.resolvedType is ConeErrorType ||
+              initializer.calleeReference is FirErrorNamedReference
+        } catch (_: Exception) {
+          false
+        }
+      }
+      else -> false
+    }
+  }
+
+  // --- FIR tree sanitizing visitor for cleanupFirTree ---
+
+  // An API member with an unresolved type reaches the descriptor as `error/NonExistentClass`,
+  // which no consumer can link against. Degrading it would only move the lie from the descriptor
+  // into the metadata, so it is recorded for ValidationStage to report instead.
+  @OptIn(SymbolInternals::class)
+  private fun recordErrorTypedApiMember(owner: String, decl: FirCallableDeclaration) {
+    val member =
+        runCatching {
+          decl.symbol.callableNameOrNullCompat()?.asString()
+        }
+            .getOrNull() ?: "<unknown>"
+
+    val isProperty = decl is FirProperty
+    val propertyTypeHasError =
+        if (decl is FirProperty) {
+          // A property's declaration, getter return type and setter value parameter describe the
+          // same JVM type. The backing field is deliberately excluded: for a delegated property
+          // it has the delegate type and is stripped before consumer ABI emission.
+          buildList<FirCallableDeclaration> {
+                add(decl)
+                decl.getter?.let { add(it) }
+                decl.setter?.let { addAll(it.valueParameters) }
+              }
+              .any { hasErrorReturnType(it) }
+        } else {
+          false
+        }
+    val positions = errorTypedApiPositions(
+        isProperty = isProperty,
+        returnTypeHasError = !isProperty && hasErrorReturnType(decl),
+        propertyTypeHasError = propertyTypeHasError,
+        receiverHasError =
+            decl.receiverParameter?.let { receiver ->
+              runCatching { receiver.typeRef.coneType.containsErrorType() }.getOrDefault(true)
+            } ?: false,
+        contextParameterErrors = decl.contextParameters.map(::hasErrorReturnType),
+        valueParameterErrors =
+            if (decl is FirFunction) decl.valueParameters.map(::hasErrorReturnType)
+            else emptyList(),
+    )
+    positions.forEach { where ->
+      repairLog.recordErrorTypedApiMember(decl, owner, member, where)
+    }
+  }
+
+  // A type ref left in an unresolved/inconsistent state after failed inference can throw on
+  // coneType access; treat that as an error too.
+  private fun hasErrorReturnType(decl: FirCallableDeclaration): Boolean = runCatching {
+    decl.returnTypeRef.coneType.containsErrorType()
+  }
+      .getOrDefault(true)
+
+  // Detect error types anywhere in a type, including nested type arguments. Inference failures
+  // often leave the outer type resolved but a type argument as an error type
+  // (e.g. `private val x = AtomicReference(Dep.UNRESOLVED)` -> `AtomicReference<ERROR>`), which
+  // FirElementSerializer still cannot serialize.
+  private fun ConeKotlinType.containsErrorType(): Boolean {
+    if (this is ConeErrorType) return true
+    return typeArguments.any { projection -> projection.type?.containsErrorType() == true }
+  }
+
+  // Only non-API members may have an unserializable error type degraded to `Any?`: they are
+  // stripped from the ABI bytecode anyway, so metadata and bytecode stay consistent. Degrading an
+  // API member would make the ABI lie to consumers.
+  private fun isNonApiVisibility(decl: FirCallableDeclaration): Boolean {
+    val visibility = decl.status.visibility
+    return visibility == Visibilities.Private ||
+        visibility == Visibilities.PrivateToThis ||
+        visibility == Visibilities.Local
+  }
+
+  /**
+   * Single-pass visitor that sanitizes FIR tree:
+   * 1. Strips ALL annotations that have error expressions in their arguments.
+   * 2. Clears property initializers containing error expressions.
+   */
+  private inner class FirSanitizingVisitor : FirDefaultVisitorVoid() {
+    override fun visitElement(element: FirElement) {
+      if (element is org.jetbrains.kotlin.fir.declarations.FirDeclaration) {
+        stripAnnotationsWithErrors(element)
+      }
+      element.acceptChildren(this)
+    }
+
+    override fun visitProperty(property: org.jetbrains.kotlin.fir.declarations.FirProperty) {
+      val initializer = property.initializer
+      if (initializer != null && hasErrorExpressionRecursive(initializer)) {
+        val owner = property.symbol.callableId.toString()
+        try {
+          val initializerField = property.javaClass.getDeclaredField("initializer")
+          initializerField.isAccessible = true
+          initializerField.set(property, null)
+          // A const val that loses its initializer is emitted without a ConstantValue attribute,
+          // so consumers that constant-fold it fail during their own compile rather than here.
+          // That reasoning only applies to a constant a consumer can actually see, hence the
+          // visibility, which [ValidationStage] filters on.
+          repairLog.recordClearedPropertyInitializer(
+              owner,
+              if (property.isConst) "const val, no ConstantValue will be emitted"
+              else "val initializer discarded",
+              isConst = property.isConst,
+              consumerVisible =
+                  property.status.visibility != Visibilities.Private &&
+                      property.status.visibility != Visibilities.PrivateToThis &&
+                      property.status.visibility != Visibilities.Local,
+          )
+        } catch (e: Exception) {
+          repairLog.recordFailedRepair(
+              owner,
+              "could not clear unresolvable initializer: ${e.javaClass.simpleName}: ${e.message}",
+          )
+        }
+      }
+      super.visitProperty(property)
+    }
+
+    override fun visitRegularClass(regularClass: FirRegularClass) {
+      degradeErrorTypedNonApiMemberReturnTypes(regularClass)
+      super.visitRegularClass(regularClass)
+    }
+
+    // Degrade non-API (private/local) members whose (inferred) type resolved to an error type to
+    // `Any?`. Under source-only ABI, an inferred private member whose type flows through a stubbed
+    // dependency member can get a ConeErrorType (e.g. `private val x = Dep.factory(...)`,
+    // `private val y = AtomicReference(Dep.COMPANION_FIELD)`, or a SAM like
+    // `private val z = Dep.Listener { ... }` where the nested type is absent from the stub). Such a
+    // member is still serialized into JVM @Metadata (private members are kept when
+    // produceHeaderKlib=false), and FirElementSerializer crashes on the error type ("Cannot
+    // serialize error type ...").
+    //
+    // The metadata serializer collects non-static members from the class's UNSUBSTITUTED MEMBER
+    // SCOPE (FirElementSerializer.memberDeclarations -> processAllProperties/processAllFunctions),
+    // NOT from firClass.declarations. That scope is built during the frontend and references the
+    // same FirProperty/FirFunction instances that back firClass.declarations. Merely removing a
+    // member from firClass.declarations here does NOT remove it from the already-built scope, so
+    // the serializer still sees it (with its error type) and crashes. Instead we DEGRADE the return
+    // type on the shared FIR instance to `Any?`; because the scope references the same instance,
+    // the
+    // serializer then serializes `Any?` and succeeds. This is non-lossy: the member is
+    // private/local
+    // (not part of the ABI) and is stripped from IR/bytecode by the IR sanitizer and from @Metadata
+    // by PrivateMetadataStripper.
+    private fun degradeErrorTypedNonApiMemberReturnTypes(firClass: FirRegularClass) {
+      val session = firClass.moduleData.session
+      firClass.declarations.forEach { decl ->
+        if (
+            decl is FirCallableDeclaration && isNonApiVisibility(decl) && hasErrorReturnType(decl)
+        ) {
+          runCatching { decl.replaceReturnTypeRef(session.builtinTypes.nullableAnyType) }
+              .onFailure { failure ->
+                repairLog.recordFailedRepair(
+                    decl.symbol.callableId.toString(),
+                    "could not degrade unresolved pre-IR return type: " +
+                        "${failure.javaClass.simpleName}: ${failure.message}",
+                )
+              }
+        }
+      }
+    }
+
+    private fun findFieldInHierarchy(
+        clazz: Class<*>,
+        fieldName: String,
+    ): java.lang.reflect.Field? {
+      var current: Class<*>? = clazz
+      while (current != null) {
+        val field = current.declaredFields.find { it.name == fieldName }
+        if (field != null) return field
+        current = current.superclass
+      }
+      return null
+    }
+
+    private fun stripAnnotationsWithErrors(
+        declaration: org.jetbrains.kotlin.fir.declarations.FirDeclaration,
+    ) {
+      try {
+        val annotationsField = findFieldInHierarchy(declaration.javaClass, "annotations") ?: return
+        annotationsField.isAccessible = true
+        @Suppress("UNCHECKED_CAST")
+        val annotations =
+            annotationsField.get(declaration) as? MutableList<FirAnnotationCall> ?: return
+
+        val toRemove = annotations.filter { annotation ->
+          hasErrorExpressionInAnnotation(annotation)
+        }
+
+        if (toRemove.isNotEmpty()) {
+          annotations.removeAll(toRemove)
+        }
+      } catch (e: Exception) {
+        // If reflection fails, skip this declaration
+      }
+    }
+
+    private fun hasErrorExpressionInAnnotation(annotation: FirAnnotationCall): Boolean {
+      val argumentList = annotation.argumentList
+      if (argumentList is FirResolvedArgumentList) {
+        for ((argument, _) in argumentList.mapping) {
+          if (hasErrorExpression(argument)) {
+            return true
+          }
+        }
+      }
+      return false
+    }
+
+    @OptIn(SymbolInternals::class)
+    private fun hasErrorExpression(element: FirElement): Boolean {
+      return when (element) {
+        is FirErrorExpression -> true
+        is FirNamedArgumentExpression -> hasErrorExpression(element.expression)
+        is FirWrappedArgumentExpression -> hasErrorExpression(element.expression)
+        is org.jetbrains.kotlin.fir.expressions.FirSpreadArgumentExpression -> {
+          hasErrorExpression(element.expression)
+        }
+        is FirVarargArgumentsExpression -> {
+          element.arguments.any { hasErrorExpression(it) }
+        }
+        is FirQualifiedAccessExpression -> {
+          try {
+            if (
+                element.resolvedType is ConeErrorType ||
+                    element.calleeReference is FirErrorNamedReference
+            ) {
+              return true
+            }
+
+            val calleeRef = element.calleeReference
+            if (calleeRef is FirResolvedNamedReference) {
+              val symbol = calleeRef.resolvedSymbol
+              if (symbol is FirPropertySymbol) {
+                val prop = symbol.fir
+                if (prop.isConst) {
+                  val initializer = prop.initializer
+                  if (initializer == null || hasErrorExpression(initializer)) {
+                    return true
+                  }
+                  if (isTodoCall(initializer)) {
+                    return true
+                  }
+                  return false
+                }
+              }
+            }
+            false
+          } catch (_: Exception) {
+            true
+          }
+        }
+        is FirGetClassCall -> {
+          try {
+            val argument = element.argument
+            if (argument is FirQualifiedAccessExpression) {
+              argument.resolvedType is ConeErrorType
+            } else {
+              element.resolvedType is ConeErrorType
+            }
+          } catch (_: Exception) {
+            true
+          }
+        }
+        is FirCollectionLiteralCompat -> {
+          try {
+            element.argumentList.arguments.any { hasErrorExpression(it) }
+          } catch (_: Exception) {
+            true
+          }
+        }
+        is org.jetbrains.kotlin.fir.expressions.FirFunctionCall -> {
+          try {
+            element.resolvedType is ConeErrorType ||
+                element.calleeReference is FirErrorNamedReference
+          } catch (_: Exception) {
+            true
+          }
+        }
+        else -> false
+      }
+    }
+
+    private fun isTodoCall(element: FirElement): Boolean {
+      if (element !is org.jetbrains.kotlin.fir.expressions.FirFunctionCall) {
+        return false
+      }
+      val calleeRef = element.calleeReference
+      if (calleeRef is FirResolvedNamedReference) {
+        val name = calleeRef.name.asString()
+        return name == "TODO"
+      }
+      return false
+    }
+  }
+}
+
+/**
+ * IR sanitization stage.
+ *
+ * Wraps the NonAbiDeclarationsStrippingIrExtension which:
+ * - Removes stub source files from IR
+ * - Strips SOURCE retention annotations
+ * - Strips private declarations (removeNonPublicApi)
+ * - Strips private supertypes and converts fake overrides
+ * - Stubs method bodies
+ */
+internal class IrSanitizerStage(private val repairLog: AbiGenRepairLog) : AbiGenStage {
+  override val name = "IrSanitizer"
+
+  /** Create the IR generation extension to be registered during FIR-to-IR conversion. */
+  fun createExtension(sourceFiles: List<KtFile>): IrGenerationExtension {
+    return NonAbiDeclarationsStrippingIrExtension(sourceFiles, repairLog)
+  }
+}
+
+/**
+ * Bytecode sanitization stage.
+ *
+ * ASM-based post-processing of generated .class files:
+ * - Strip @Throws annotations from RuntimeInvisibleAnnotations
+ * - Strip private declarations from @Metadata annotation
+ */
+internal class BytecodeSanitizerStage : AbiGenStage {
+  override val name = "BytecodeSanitizer"
+
+  private val transformers = listOf(ThrowsAnnotationStripper(), PrivateMetadataStripper())
+
+  /** Transform class bytecode in-memory, applying all sanitization transformers. */
+  fun transform(bytes: ByteArray): ByteArray {
+    var result = bytes
+    for (transformer in transformers) {
+      val transformed = transformer.transform(result)
+      if (transformed != null) {
+        result = transformed
+      }
+    }
+    return result
+  }
+
+  /** Process all .class files in the output directory (disk-based). */
+  fun process(outputDir: File) {
+    outputDir
+        .walkTopDown()
+        .filter { it.extension == "class" }
+        .forEach { classFile ->
+          var bytes = classFile.readBytes()
+          var modified = false
+          for (transformer in transformers) {
+            val result = transformer.transform(bytes)
+            if (result != null) {
+              bytes = result
+              modified = true
+            }
+          }
+          if (modified) {
+            classFile.writeBytes(bytes)
+          }
+        }
+  }
+}
+
+internal data class AbiValidationInputs(
+    val outputFiles: List<AbiValidationOutputFile>,
+    val classpathRoots: List<File>,
+)
+
+internal class AbiValidationOutputFile(
+    val relativePath: String,
+    val bytes: ByteArray,
+)
+
+private data class EmittedTypeReference(
+    val owner: String,
+    val site: String,
+    val internalName: String,
+    val eligibleForStubOnlyDetection: Boolean,
+)
+
+private const val NON_EXISTENT_CLASS_INTERNAL_NAME = "error/NonExistentClass"
+
+/**
+ * Validation stage.
+ *
+ * Answers a single question: does the ABI about to be published differ from what a class-ABI build
+ * would have produced, in a way the jar itself cannot reveal?
+ *
+ * The failure mode this guards against is a *green* build that emits a subtly wrong ABI - a
+ * constant holding a placeholder instead of its real value, or a `const val` emitted with no
+ * `ConstantValue` attribute at all. Both produce well-formed bytecode, so nothing downstream of
+ * here can detect them; the only evidence is what the earlier stages recorded in [AbiGenRepairLog].
+ *
+ * Assertion 6 extends that to fabricated stub-only types. If stubgen fabricates a class to keep the
+ * producer compiling, but no emitted class and no non-stub classpath root actually ships that type,
+ * then any surviving descriptor that mentions it is a broken ABI even though the descriptor itself
+ * is well-formed. Same-package phantom classes are the motivating case.
+ *
+ * Rollout: [AbiRepairPolicy.OFF] is the default, so this stage emits nothing unless a target asks
+ * for it via `abiValidationMode`. Warnings are not a softer setting here - fbsource builds Kotlin
+ * with `-Werror`, so `warn` fails the compile just as `error` does. Enabling it repo-wide therefore
+ * has to wait until the repairs it names have been driven out, not the other way round.
+ *
+ * The cleared-initializer check carries that visibility filter (Assertion 2 below): a `private
+ * const val` is not part of any consumer's constant folding, so repairing one silently is not the
+ * defect this stage is looking for. [unsoundConstants] needs no equivalent filter - a fabricated
+ * constant only ever reaches that path as an annotation argument, which is by construction
+ * consumer-visible.
+ */
+internal class ValidationStage(private val repairLog: AbiGenRepairLog) : AbiGenStage {
+  override val name = "Validation"
+
+  fun validate(
+      moduleFragment: IrModuleFragment,
+      messageCollector: MessageCollector,
+      policy: AbiRepairPolicy,
+      inputs: AbiValidationInputs,
+  ) {
+    if (policy == AbiRepairPolicy.OFF) return
+
+    // Always emitted, including at zero, so that "no repairs happened" is distinguishable from
+    // "validation did not run" when aggregating across a build.
+    messageCollector.report(CompilerMessageSeverity.INFO, repairLog.counterLine())
+
+    val severity =
+        if (policy == AbiRepairPolicy.ERROR) CompilerMessageSeverity.ERROR
+        else CompilerMessageSeverity.WARNING
+
+    // The final class bytes are authoritative: source-stage repair bookkeeping and stub classpath
+    // candidates can both miss a literal error type that survives a transform or hides in metadata.
+    val emittedTypeReferences = collectEmittedTypeReferences(inputs.outputFiles)
+    for (reference in emittedTypeReferences) {
+      if (reference.internalName != NON_EXISTENT_CLASS_INTERNAL_NAME) continue
+      messageCollector.report(
+          CompilerMessageSeverity.ERROR,
+          "Kosabi ABI validation: `${reference.owner}` emits `${reference.site}` referencing " +
+              "literal `$NON_EXISTENT_CLASS_INTERNAL_NAME`. The final ABI bytecode contains an " +
+              "unresolved type and no consumer can link against it.",
+      )
+    }
+
+    // Assertion 1: every synthesised constant has a type consistent with a real declaration.
+    // Constants that reached ASSUMED_STRING have a fabricated type, not merely a fabricated value.
+    for (constant in repairLog.unsoundConstants()) {
+      messageCollector.report(
+          severity,
+          "Kosabi ABI validation: constant `${constant.classId}.${constant.name}` was emitted " +
+              "with an assumed type of `String`. Neither its type nor its value could be " +
+              "established, so if the real constant is not a String this ABI is wrong in a way " +
+              "that will not surface until a consumer compiles against it.",
+      )
+    }
+
+    // Assertion 2: no *consumer-visible* const val silently lost its ConstantValue attribute.
+    //
+    // The visibility filter is not a convenience. Every one of the 12 constants this assertion
+    // named on its first repo-wide run was a `private const val` initialised from a constant
+    // declared in another buck target. A private companion constant takes part in no consumer's
+    // constant folding, so the message's own justification - "consumers that constant-fold it fail
+    // during their own compile" - cannot apply to it. Reporting those is a false positive, and
+    // since `warn` is fatal under `-Werror` a false positive here is a broken build. What they do
+    // expose is real but narrower, and belongs to a different check: Kosabi's const resolver is
+    // source-local and cannot read a constant's value off a dependency's ABI.
+    for (cleared in repairLog.clearedPropertyInitializers) {
+      if (!cleared.isConst) continue
+      if (!cleared.consumerVisible) continue
+      messageCollector.report(
+          severity,
+          "Kosabi ABI validation: `${cleared.owner}` is a const val whose initializer could not " +
+              "be resolved and was discarded. It will be emitted without a ConstantValue " +
+              "attribute, so consumers that constant-fold it fail during their own compile.",
+      )
+    }
+
+    // Assertion 3: a repair that threw leaves the tree in an unknown state. Unlike a placeholder
+    // value there is no claim that can be made about the result at all, which makes this the first
+    // check that should be promoted to a hard error once the rate is known to be zero.
+    for (failure in repairLog.failedRepairs) {
+      messageCollector.report(
+          severity,
+          "Kosabi ABI validation: repair of `${failure.owner}` failed and was previously " +
+              "swallowed: ${failure.detail}. The emitted ABI cannot be trusted.",
+      )
+    }
+
+    // Assertion 4: no supertype survived that the ABI jar will not contain a class file for.
+    // Nested private classes are kept in the ABI, so only a top-level private supertype dangles.
+    // Unlike the checks above this one is verifiable from the module itself, so it is checked
+    // directly rather than trusted.
+    val leakedSupertypes = mutableListOf<String>()
+    moduleFragment.accept(
+        object : IrElementVisitorVoidCompat() {
+          override fun visitElement(element: IrElement) {
+            element.acceptChildren(this, null)
+          }
+
+          override fun visitClass(declaration: IrClass) {
+            for (superType in declaration.superTypes) {
+              val superClass =
+                  (superType as? org.jetbrains.kotlin.ir.types.IrSimpleType)?.classifier?.owner
+                      as? IrClass ?: continue
+              if (
+                  superClass.parent !is IrClass &&
+                      superClass.visibility ==
+                          org.jetbrains.kotlin.descriptors.DescriptorVisibilities.PRIVATE
+              ) {
+                leakedSupertypes.add(
+                    "${declaration.kotlinFqName.asString()} -> ${superClass.kotlinFqName.asString()}",
+                )
+              }
+            }
+            super.visitClass(declaration)
+          }
+        },
+        null,
+    )
+    for (leaked in leakedSupertypes) {
+      messageCollector.report(
+          severity,
+          "Kosabi ABI validation: dangling private supertype survived stripping: $leaked",
+      )
+    }
+
+    // Assertion 5: no consumer-visible member reached the descriptor with an unresolved type. A
+    // non-API member in that state is degraded to `Any?`; an API member cannot be, so it ships as
+    // `Lerror/NonExistentClass;` and no consumer can link against it.
+    for (m in repairLog.errorTypedApiMembers) {
+      messageCollector.report(
+          severity,
+          "Kosabi ABI validation: `${m.owner}.${m.member}` has an unresolved ${m.where}, so its " +
+              "descriptor was emitted with `error/NonExistentClass` and no consumer can link " +
+              "against it. The referenced type is not on the source-only ABI classpath. Add the " +
+              "target that provides it to this target's `source_only_abi_deps`, or declare that " +
+              "target `required_for_source_only_abi = True`.",
+      )
+    }
+
+    // Assertion 6: no descriptor in the emitted ABI may mention a stub-only class that is absent
+    // from both the emitted jar and the non-stub classpath. That pattern means stubgen preserved
+    // compilation by fabricating a class, but source-only ABI is about to publish a phantom type.
+    for (leak in
+        findStubOnlyDescriptorLeaks(
+            inputs,
+            emittedTypeReferences,
+            messageCollector,
+            severity,
+        )) {
+      messageCollector.report(
+          severity,
+          "Kosabi ABI validation: `${leak.owner}` emits `${leak.site}` with stub-only type " +
+              "`${leak.internalName.replace('/', '.')}`. Kosabi generated a stub for that class, " +
+              "but neither this ABI jar nor any non-stub classpath root provides it. This usually " +
+              "means stubgen fabricated a same-package phantom from an unresolved simple name. " +
+              "Add the real provider to THIS target's `source_only_abi_deps`, or fix the unresolved " +
+              "type so source-only ABI does not publish a phantom descriptor.",
+      )
+    }
+  }
+
+  private fun findStubOnlyDescriptorLeaks(
+      inputs: AbiValidationInputs,
+      emittedTypeReferences: Set<EmittedTypeReference>,
+      messageCollector: MessageCollector,
+      severity: CompilerMessageSeverity,
+  ): List<EmittedTypeReference> {
+    val (stubRoots, realRoots) = inputs.classpathRoots.partition { it.isStubClasspathRoot() }
+    if (stubRoots.isEmpty()) {
+      messageCollector.report(
+          severity,
+          "Kosabi ABI validation: same-package phantom detection could not complete because no " +
+              "stub classpath root (stubgen_stubs.jar / stubs.jar) was found.",
+      )
+      return emptyList()
+    }
+    val stubDeclaredClasses =
+        collectClassesFromClasspath(stubRoots, messageCollector, severity) ?: return emptyList()
+    if (stubDeclaredClasses.isEmpty()) return emptyList()
+
+    val emittedClasses =
+        inputs.outputFiles
+            .asSequence()
+            .filter { it.relativePath.endsWith(".class") }
+            .map { classNameFromRelativePath(it.relativePath) }
+            .toSet()
+
+    // Subtract the emitted classes first: a stub-declared class that this jar ships itself is never
+    // a phantom, and that subtraction needs no classpath I/O. Only if candidates survive do we pay
+    // to enumerate the (potentially large) non-stub classpath, keeping the added compile cost
+    // proportional to the number of stub-declared candidates rather than the whole classpath.
+    val stubOnlyCandidates = stubDeclaredClasses.filterTo(linkedSetOf()) { it !in emittedClasses }
+    if (stubOnlyCandidates.isEmpty()) return emptyList()
+
+    // Materialize the non-stub classpath once so each jar is opened at most one time; the phantom
+    // check below is then an O(1) set lookup per candidate rather than a jar reopen per candidate.
+    val realClasspathClasses =
+        collectClassesFromClasspath(realRoots, messageCollector, severity) ?: return emptyList()
+
+    val phantomClasses = stubOnlyCandidates.filterTo(linkedSetOf()) { it !in realClasspathClasses }
+    if (phantomClasses.isEmpty()) return emptyList()
+
+    // The shared walk also covers code/debug-only references for the literal NEC invariant.
+    // Preserve
+    // the existing phantom check's ABI-surface scope so implementation details cannot become new
+    // policy failures.
+    return emittedTypeReferences.filter { reference ->
+      reference.eligibleForStubOnlyDetection &&
+          reference.internalName.replace('/', '.') in phantomClasses
+    }
+  }
+
+  private fun collectEmittedTypeReferences(
+      outputFiles: List<AbiValidationOutputFile>,
+  ): Set<EmittedTypeReference> {
+    val references = linkedSetOf<EmittedTypeReference>()
+    outputFiles
+        .asSequence()
+        .filter { it.relativePath.endsWith(".class") }
+        .forEach { outputFile ->
+          val owner = classNameFromRelativePath(outputFile.relativePath)
+          ClassReader(outputFile.bytes)
+              .accept(
+                  object : ClassVisitor(Opcodes.ASM9) {
+                    override fun visit(
+                        version: Int,
+                        access: Int,
+                        name: String?,
+                        signature: String?,
+                        superName: String?,
+                        interfaces: Array<out String>?,
+                    ) {
+                      collectInternalName(
+                          references,
+                          owner,
+                          "class identity",
+                          name,
+                          eligibleForStubOnlyDetection = false,
+                      )
+                      collectInternalName(references, owner, "supertype", superName)
+                      interfaces.orEmpty().forEach { iface ->
+                        collectInternalName(references, owner, "interface", iface)
+                      }
+                      collectSignature(references, owner, "class signature", signature)
+                    }
+
+                    override fun visitModule(
+                        name: String?,
+                        access: Int,
+                        version: String?,
+                    ): ModuleVisitor =
+                        object : ModuleVisitor(Opcodes.ASM9) {
+                          override fun visitMainClass(mainClass: String?) {
+                            collectInternalName(
+                                references,
+                                owner,
+                                "module main class",
+                                mainClass,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                          }
+
+                          override fun visitUse(service: String?) {
+                            collectInternalName(
+                                references,
+                                owner,
+                                "module service",
+                                service,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                          }
+
+                          override fun visitProvide(
+                              service: String?,
+                              providers: Array<out String>?,
+                          ) {
+                            collectInternalName(
+                                references,
+                                owner,
+                                "module service",
+                                service,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                            providers.orEmpty().forEach { provider ->
+                              collectInternalName(
+                                  references,
+                                  owner,
+                                  "module service provider",
+                                  provider,
+                                  eligibleForStubOnlyDetection = false,
+                              )
+                            }
+                          }
+                        }
+
+                    override fun visitOuterClass(
+                        outerClassOwner: String?,
+                        name: String?,
+                        descriptor: String?,
+                    ) {
+                      collectInternalName(references, owner, "outer class", outerClassOwner)
+                      if (descriptor != null) {
+                        collectDescriptor(references, owner, "outer method", descriptor)
+                      }
+                    }
+
+                    override fun visitInnerClass(
+                        name: String?,
+                        outerName: String?,
+                        innerName: String?,
+                        access: Int,
+                    ) {
+                      collectInternalName(references, owner, "inner class", name)
+                      collectInternalName(references, owner, "inner class outer", outerName)
+                    }
+
+                    override fun visitNestHost(nestHost: String?) {
+                      collectInternalName(references, owner, "nest host", nestHost)
+                    }
+
+                    override fun visitNestMember(nestMember: String?) {
+                      collectInternalName(references, owner, "nest member", nestMember)
+                    }
+
+                    override fun visitPermittedSubclass(permittedSubclass: String?) {
+                      collectInternalName(
+                          references,
+                          owner,
+                          "permitted subclass",
+                          permittedSubclass,
+                      )
+                    }
+
+                    override fun visitRecordComponent(
+                        name: String,
+                        descriptor: String,
+                        signature: String?,
+                    ): RecordComponentVisitor {
+                      val site = "record component `$name`"
+                      collectDescriptor(references, owner, site, descriptor)
+                      collectTypeSignature(references, owner, "$site signature", signature)
+                      return object : RecordComponentVisitor(Opcodes.ASM9) {
+                        override fun visitAnnotation(
+                            descriptor: String,
+                            visible: Boolean,
+                        ): AnnotationVisitor = annotationVisitor(
+                            references,
+                            owner,
+                            "$site annotation",
+                            descriptor,
+                        )
+
+                        override fun visitTypeAnnotation(
+                            typeRef: Int,
+                            typePath: TypePath?,
+                            descriptor: String,
+                            visible: Boolean,
+                        ): AnnotationVisitor = annotationVisitor(
+                            references,
+                            owner,
+                            "$site type annotation",
+                            descriptor,
+                        )
+                      }
+                    }
+
+                    override fun visitAnnotation(
+                        descriptor: String,
+                        visible: Boolean,
+                    ): AnnotationVisitor =
+                        annotationVisitor(references, owner, "class annotation", descriptor)
+
+                    override fun visitTypeAnnotation(
+                        typeRef: Int,
+                        typePath: TypePath?,
+                        descriptor: String,
+                        visible: Boolean,
+                    ): AnnotationVisitor =
+                        annotationVisitor(references, owner, "class type annotation", descriptor)
+
+                    override fun visitField(
+                        access: Int,
+                        name: String,
+                        descriptor: String,
+                        signature: String?,
+                        value: Any?,
+                    ): FieldVisitor {
+                      val site = "field `$name`"
+                      collectDescriptor(references, owner, site, descriptor)
+                      collectTypeSignature(references, owner, "$site signature", signature)
+                      collectConstantValue(references, owner, "$site value", value)
+                      return object : FieldVisitor(Opcodes.ASM9) {
+                        override fun visitAnnotation(
+                            descriptor: String,
+                            visible: Boolean,
+                        ): AnnotationVisitor = annotationVisitor(
+                            references,
+                            owner,
+                            "$site annotation",
+                            descriptor,
+                        )
+
+                        override fun visitTypeAnnotation(
+                            typeRef: Int,
+                            typePath: TypePath?,
+                            descriptor: String,
+                            visible: Boolean,
+                        ): AnnotationVisitor = annotationVisitor(
+                            references,
+                            owner,
+                            "$site type annotation",
+                            descriptor,
+                        )
+                      }
+                    }
+
+                    override fun visitMethod(
+                        access: Int,
+                        name: String,
+                        descriptor: String,
+                        signature: String?,
+                        exceptions: Array<out String>?,
+                    ): MethodVisitor {
+                      val site = "method `$name$descriptor`"
+                      collectDescriptor(references, owner, site, descriptor)
+                      collectSignature(references, owner, "$site signature", signature)
+                      exceptions.orEmpty().forEach { exceptionInternalName ->
+                        collectInternalName(
+                            references,
+                            owner,
+                            "$site throws",
+                            exceptionInternalName,
+                        )
+                      }
+                      return object : MethodVisitor(Opcodes.ASM9) {
+                        override fun visitAnnotationDefault(): AnnotationVisitor =
+                            annotationValueVisitor(references, owner, "$site annotation default")
+
+                        override fun visitAnnotation(
+                            descriptor: String,
+                            visible: Boolean,
+                        ): AnnotationVisitor = annotationVisitor(
+                            references,
+                            owner,
+                            "$site annotation",
+                            descriptor,
+                        )
+
+                        override fun visitParameterAnnotation(
+                            parameter: Int,
+                            descriptor: String,
+                            visible: Boolean,
+                        ): AnnotationVisitor = annotationVisitor(
+                            references,
+                            owner,
+                            "$site parameter annotation",
+                            descriptor,
+                        )
+
+                        override fun visitTypeAnnotation(
+                            typeRef: Int,
+                            typePath: TypePath?,
+                            descriptor: String,
+                            visible: Boolean,
+                        ): AnnotationVisitor = annotationVisitor(
+                            references,
+                            owner,
+                            "$site type annotation",
+                            descriptor,
+                        )
+
+                        override fun visitInsnAnnotation(
+                            typeRef: Int,
+                            typePath: TypePath?,
+                            descriptor: String,
+                            visible: Boolean,
+                        ): AnnotationVisitor = annotationVisitor(
+                            references,
+                            owner,
+                            "$site instruction type annotation",
+                            descriptor,
+                            eligibleForStubOnlyDetection = false,
+                        )
+
+                        override fun visitTryCatchAnnotation(
+                            typeRef: Int,
+                            typePath: TypePath?,
+                            descriptor: String,
+                            visible: Boolean,
+                        ): AnnotationVisitor = annotationVisitor(
+                            references,
+                            owner,
+                            "$site try/catch type annotation",
+                            descriptor,
+                            eligibleForStubOnlyDetection = false,
+                        )
+
+                        override fun visitLocalVariableAnnotation(
+                            typeRef: Int,
+                            typePath: TypePath?,
+                            start: Array<out Label>?,
+                            end: Array<out Label>?,
+                            index: IntArray?,
+                            descriptor: String,
+                            visible: Boolean,
+                        ): AnnotationVisitor = annotationVisitor(
+                            references,
+                            owner,
+                            "$site local variable type annotation",
+                            descriptor,
+                            eligibleForStubOnlyDetection = false,
+                        )
+
+                        override fun visitTypeInsn(opcode: Int, type: String?) {
+                          collectInternalName(
+                              references,
+                              owner,
+                              "$site instruction",
+                              type,
+                              eligibleForStubOnlyDetection = false,
+                          )
+                        }
+
+                        override fun visitFieldInsn(
+                            opcode: Int,
+                            instructionOwner: String?,
+                            name: String?,
+                            descriptor: String?,
+                        ) {
+                          collectInternalName(
+                              references,
+                              owner,
+                              "$site field instruction owner",
+                              instructionOwner,
+                              eligibleForStubOnlyDetection = false,
+                          )
+                          if (descriptor != null) {
+                            collectDescriptor(
+                                references,
+                                owner,
+                                "$site field instruction",
+                                descriptor,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                          }
+                        }
+
+                        override fun visitMethodInsn(
+                            opcode: Int,
+                            instructionOwner: String?,
+                            name: String?,
+                            descriptor: String?,
+                            isInterface: Boolean,
+                        ) {
+                          collectInternalName(
+                              references,
+                              owner,
+                              "$site method instruction owner",
+                              instructionOwner,
+                              eligibleForStubOnlyDetection = false,
+                          )
+                          if (descriptor != null) {
+                            collectDescriptor(
+                                references,
+                                owner,
+                                "$site method instruction",
+                                descriptor,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                          }
+                        }
+
+                        override fun visitInvokeDynamicInsn(
+                            name: String?,
+                            descriptor: String?,
+                            bootstrapMethodHandle: Handle?,
+                            vararg bootstrapMethodArguments: Any?,
+                        ) {
+                          if (descriptor != null) {
+                            collectDescriptor(
+                                references,
+                                owner,
+                                "$site invokedynamic",
+                                descriptor,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                          }
+                          collectConstantValue(
+                              references,
+                              owner,
+                              "$site invokedynamic bootstrap",
+                              bootstrapMethodHandle,
+                              eligibleForStubOnlyDetection = false,
+                          )
+                          bootstrapMethodArguments.forEach { argument ->
+                            collectConstantValue(
+                                references,
+                                owner,
+                                "$site invokedynamic bootstrap argument",
+                                argument,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                          }
+                        }
+
+                        override fun visitLdcInsn(value: Any?) {
+                          collectConstantValue(
+                              references,
+                              owner,
+                              "$site constant",
+                              value,
+                              eligibleForStubOnlyDetection = false,
+                          )
+                        }
+
+                        override fun visitMultiANewArrayInsn(
+                            descriptor: String?,
+                            numDimensions: Int,
+                        ) {
+                          if (descriptor != null) {
+                            collectDescriptor(
+                                references,
+                                owner,
+                                "$site multi-dimensional array",
+                                descriptor,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                          }
+                        }
+
+                        override fun visitTryCatchBlock(
+                            start: Label?,
+                            end: Label?,
+                            handler: Label?,
+                            type: String?,
+                        ) {
+                          collectInternalName(
+                              references,
+                              owner,
+                              "$site catch type",
+                              type,
+                              eligibleForStubOnlyDetection = false,
+                          )
+                        }
+
+                        override fun visitLocalVariable(
+                            name: String?,
+                            descriptor: String?,
+                            signature: String?,
+                            start: Label?,
+                            end: Label?,
+                            index: Int,
+                        ) {
+                          if (descriptor != null) {
+                            collectDescriptor(
+                                references,
+                                owner,
+                                "$site local variable",
+                                descriptor,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                          }
+                          collectTypeSignature(
+                              references,
+                              owner,
+                              "$site local variable signature",
+                              signature,
+                              eligibleForStubOnlyDetection = false,
+                          )
+                        }
+
+                        override fun visitFrame(
+                            type: Int,
+                            numLocal: Int,
+                            local: Array<out Any>?,
+                            numStack: Int,
+                            stack: Array<out Any>?,
+                        ) {
+                          local.orEmpty().filterIsInstance<String>().forEach { internalName ->
+                            collectInternalName(
+                                references,
+                                owner,
+                                "$site stack map frame",
+                                internalName,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                          }
+                          stack.orEmpty().filterIsInstance<String>().forEach { internalName ->
+                            collectInternalName(
+                                references,
+                                owner,
+                                "$site stack map frame",
+                                internalName,
+                                eligibleForStubOnlyDetection = false,
+                            )
+                          }
+                        }
+                      }
+                    }
+                  },
+                  0,
+              )
+        }
+    return references
+  }
+
+  private fun collectDescriptor(
+      references: MutableSet<EmittedTypeReference>,
+      owner: String,
+      site: String,
+      descriptor: String,
+      eligibleForStubOnlyDetection: Boolean = true,
+  ) {
+    collectType(
+        references,
+        owner,
+        site,
+        Type.getType(descriptor),
+        eligibleForStubOnlyDetection,
+    )
+  }
+
+  private fun collectType(
+      references: MutableSet<EmittedTypeReference>,
+      owner: String,
+      site: String,
+      type: Type,
+      eligibleForStubOnlyDetection: Boolean = true,
+  ) {
+    when (type.sort) {
+      Type.ARRAY ->
+          collectType(references, owner, site, type.elementType, eligibleForStubOnlyDetection)
+      Type.OBJECT ->
+          collectInternalName(
+              references,
+              owner,
+              site,
+              type.internalName,
+              eligibleForStubOnlyDetection,
+          )
+      Type.METHOD -> {
+        type.argumentTypes.forEach { argumentType ->
+          collectType(references, owner, site, argumentType, eligibleForStubOnlyDetection)
+        }
+        collectType(references, owner, site, type.returnType, eligibleForStubOnlyDetection)
+      }
+    }
+  }
+
+  private fun collectInternalName(
+      references: MutableSet<EmittedTypeReference>,
+      owner: String,
+      site: String,
+      internalName: String?,
+      eligibleForStubOnlyDetection: Boolean = true,
+  ) {
+    if (internalName == null) return
+    if (internalName.startsWith("[")) {
+      collectDescriptor(references, owner, site, internalName, eligibleForStubOnlyDetection)
+    } else {
+      references.add(
+          EmittedTypeReference(owner, site, internalName, eligibleForStubOnlyDetection),
+      )
+    }
+  }
+
+  private fun collectConstantValue(
+      references: MutableSet<EmittedTypeReference>,
+      owner: String,
+      site: String,
+      value: Any?,
+      eligibleForStubOnlyDetection: Boolean = true,
+  ) {
+    when (value) {
+      is Type -> collectType(references, owner, site, value, eligibleForStubOnlyDetection)
+      is Handle -> {
+        collectInternalName(
+            references,
+            owner,
+            "$site owner",
+            value.owner,
+            eligibleForStubOnlyDetection,
+        )
+        collectDescriptor(
+            references,
+            owner,
+            site,
+            value.desc,
+            eligibleForStubOnlyDetection,
+        )
+      }
+      is ConstantDynamic -> {
+        collectDescriptor(
+            references,
+            owner,
+            site,
+            value.descriptor,
+            eligibleForStubOnlyDetection,
+        )
+        collectConstantValue(
+            references,
+            owner,
+            "$site bootstrap",
+            value.bootstrapMethod,
+            eligibleForStubOnlyDetection,
+        )
+        for (index in 0 until value.bootstrapMethodArgumentCount) {
+          collectConstantValue(
+              references,
+              owner,
+              "$site bootstrap argument",
+              value.getBootstrapMethodArgument(index),
+              eligibleForStubOnlyDetection,
+          )
+        }
+      }
+    }
+  }
+
+  private fun annotationVisitor(
+      references: MutableSet<EmittedTypeReference>,
+      owner: String,
+      site: String,
+      descriptor: String,
+      eligibleForStubOnlyDetection: Boolean = true,
+  ): AnnotationVisitor {
+    collectDescriptor(references, owner, site, descriptor, eligibleForStubOnlyDetection)
+    return annotationValueVisitor(references, owner, site, eligibleForStubOnlyDetection)
+  }
+
+  private fun annotationValueVisitor(
+      references: MutableSet<EmittedTypeReference>,
+      owner: String,
+      site: String,
+      eligibleForStubOnlyDetection: Boolean = true,
+  ): AnnotationVisitor =
+      object : AnnotationVisitor(Opcodes.ASM9) {
+        override fun visit(name: String?, value: Any?) {
+          collectConstantValue(references, owner, site, value, eligibleForStubOnlyDetection)
+        }
+
+        override fun visitEnum(name: String?, descriptor: String, value: String?) {
+          collectDescriptor(references, owner, site, descriptor, eligibleForStubOnlyDetection)
+        }
+
+        override fun visitAnnotation(
+            name: String?,
+            descriptor: String,
+        ): AnnotationVisitor = annotationVisitor(
+            references,
+            owner,
+            site,
+            descriptor,
+            eligibleForStubOnlyDetection,
+        )
+
+        override fun visitArray(name: String?): AnnotationVisitor =
+            annotationValueVisitor(references, owner, site, eligibleForStubOnlyDetection)
+      }
+
+  private fun collectSignature(
+      references: MutableSet<EmittedTypeReference>,
+      owner: String,
+      site: String,
+      signature: String?,
+      eligibleForStubOnlyDetection: Boolean = true,
+  ) {
+    if (signature == null) return
+    SignatureReader(signature)
+        .accept(signatureVisitor(references, owner, site, eligibleForStubOnlyDetection))
+  }
+
+  private fun collectTypeSignature(
+      references: MutableSet<EmittedTypeReference>,
+      owner: String,
+      site: String,
+      signature: String?,
+      eligibleForStubOnlyDetection: Boolean = true,
+  ) {
+    if (signature == null) return
+    SignatureReader(signature)
+        .acceptType(signatureVisitor(references, owner, site, eligibleForStubOnlyDetection))
+  }
+
+  private fun signatureVisitor(
+      references: MutableSet<EmittedTypeReference>,
+      owner: String,
+      site: String,
+      eligibleForStubOnlyDetection: Boolean = true,
+  ): SignatureVisitor =
+      object : SignatureVisitor(Opcodes.ASM9) {
+        private var currentClassInternalName: String? = null
+
+        override fun visitClassType(name: String?) {
+          currentClassInternalName = name
+          collectInternalName(references, owner, site, name, eligibleForStubOnlyDetection)
+        }
+
+        override fun visitInnerClassType(name: String?) {
+          val enclosing = currentClassInternalName
+          val nestedName =
+              when {
+                name == null -> null
+                enclosing == null -> name
+                else -> enclosing + "$" + name
+              }
+          currentClassInternalName = nestedName
+          collectInternalName(
+              references,
+              owner,
+              site,
+              nestedName,
+              eligibleForStubOnlyDetection,
+          )
+        }
+
+        override fun visitClassBound(): SignatureVisitor =
+            signatureVisitor(references, owner, site, eligibleForStubOnlyDetection)
+
+        override fun visitInterfaceBound(): SignatureVisitor =
+            signatureVisitor(references, owner, site, eligibleForStubOnlyDetection)
+
+        override fun visitSuperclass(): SignatureVisitor =
+            signatureVisitor(references, owner, site, eligibleForStubOnlyDetection)
+
+        override fun visitInterface(): SignatureVisitor =
+            signatureVisitor(references, owner, site, eligibleForStubOnlyDetection)
+
+        override fun visitParameterType(): SignatureVisitor =
+            signatureVisitor(references, owner, site, eligibleForStubOnlyDetection)
+
+        override fun visitReturnType(): SignatureVisitor =
+            signatureVisitor(references, owner, site, eligibleForStubOnlyDetection)
+
+        override fun visitExceptionType(): SignatureVisitor =
+            signatureVisitor(references, owner, site, eligibleForStubOnlyDetection)
+
+        override fun visitArrayType(): SignatureVisitor =
+            signatureVisitor(references, owner, site, eligibleForStubOnlyDetection)
+
+        override fun visitTypeArgument(wildcard: Char): SignatureVisitor =
+            signatureVisitor(references, owner, site, eligibleForStubOnlyDetection)
+      }
+
+  private fun classNameFromRelativePath(relativePath: String): String {
+    return relativePath.removeSuffix(".class").replace('/', '.')
+  }
+
+  private fun collectClassesFromClasspath(
+      classpathRoots: List<File>,
+      messageCollector: MessageCollector,
+      severity: CompilerMessageSeverity,
+  ): Set<String>? {
+    val classes = linkedSetOf<String>()
+    for (root in classpathRoots) {
+      try {
+        when {
+          root.isDirectory -> {
+            root
+                .walkTopDown()
+                .filter { it.isFile && it.extension == "class" }
+                .forEach { classFile ->
+                  val relativePath = classFile.relativeTo(root).invariantSeparatorsPath
+                  classes.add(classNameFromRelativePath(relativePath))
+                }
+          }
+          root.isFile && root.extension == "jar" -> {
+            JarFile(root).use { jarFile ->
+              jarFile
+                  .entries()
+                  .asSequence()
+                  .filter { entry -> !entry.isDirectory && entry.name.endsWith(".class") }
+                  .forEach { entry -> classes.add(classNameFromRelativePath(entry.name)) }
+            }
+          }
+        }
+      } catch (failure: Exception) {
+        messageCollector.report(
+            severity,
+            "Kosabi ABI validation: same-package phantom detection could not complete because " +
+                "classpath root `$root` could not be read: $failure",
+        )
+        return null
+      }
+    }
+    return classes
+  }
+
+  // KosabiStubgenStepsBuilder emits the stub classpath as `__%s_stubgen_stubs.jar`, or as the
+  // corresponding `__%s_stubgen_stubs` directory before packaging. `stubs.jar` stays an equality
+  // check: as a suffix it would also swallow `core-lambda-stubs.jar` and treat the Android lambda
+  // stubs as fabricated classes.
+  private fun File.isStubClasspathRoot(): Boolean =
+      (isDirectory && name.endsWith("stubgen_stubs")) ||
+          (isFile && (name.endsWith("stubgen_stubs.jar") || name == "stubs.jar"))
+}
+
+/**
+ * Pipeline runner that orchestrates the ABI generation stages in the correct order.
+ *
+ * The pipeline stages are:
+ * 1. FIR pre-IR cleanup (FirMetadataSanitizerStage.cleanupFirTree)
+ * 2. FIR-to-IR conversion with IR sanitizer extension
+ * 3. FIR metadata post-IR cleanup (FirMetadataSanitizerStage.cleanupFirMetadataSources)
+ * 4. Code generation + in-memory bytecode transforms + write to disk
+ * 5. Validation (ValidationStage.validate)
+ *
+ * Steps 2 and 4 are handled by the caller (K2JvmAbiFirAnalysisHandlerExtension) since they involve
+ * compiler infrastructure (FIR-to-IR conversion, code generation).
+ */
+internal class AbiGenPipeline(
+    /** Shared by every stage; the only record of repairs the emitted jar cannot reveal. */
+    val repairLog: AbiGenRepairLog = AbiGenRepairLog(),
+    val composeAbi: ComposeAbiEmulationStage = ComposeAbiEmulationStage(),
+    val bytecodeSanitizer: BytecodeSanitizerStage = BytecodeSanitizerStage(),
+) {
+  val firMetadataSanitizer: FirMetadataSanitizerStage = FirMetadataSanitizerStage(repairLog)
+  val irSanitizer: IrSanitizerStage = IrSanitizerStage(repairLog)
+  val validator: ValidationStage = ValidationStage(repairLog)
+
+  val stages: List<AbiGenStage>
+    get() = listOf(firMetadataSanitizer, composeAbi, irSanitizer, bytecodeSanitizer, validator)
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenRepairLog.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenRepairLog.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenRepairLog.kt
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+
+package com.facebook
+
+import java.util.IdentityHashMap
+
+/**
+ * How the ABI generator reacts when it has to emit content it knows is not faithful to the real
+ * declaration.
+ *
+ * `ERROR` is the only setting under which a green build implies a correct ABI.
+ *
+ * [WARN] is not a "keeps existing targets building" setting in this repository. fbsource compiles
+ * Kotlin with `-Werror`, so a `CompilerMessageSeverity.WARNING` terminates the compile exactly as
+ * [ERROR] would; the two differ only in the message text. Any rollout that treats warnings as the
+ * safe intermediate step will break every target that trips a repair.
+ */
+enum class AbiRepairPolicy {
+  OFF,
+  WARN,
+  ERROR;
+
+  companion object {
+    /**
+     * Absent or unrecognised values fall back to [OFF].
+     *
+     * The plugin cannot see whether the enclosing compile passes `-Werror`, so it cannot pick a
+     * non-fatal severity on its own. Reporting therefore has to be requested explicitly by whoever
+     * knows the target is prepared for it.
+     */
+    fun parse(value: String?): AbiRepairPolicy =
+        when (value?.lowercase()) {
+          "warn" -> WARN
+          "error",
+          "fail" -> ERROR
+          else -> OFF
+        }
+  }
+}
+
+/** Where the type of a fabricated constant came from. */
+enum class ConstTypeSource {
+  /** Taken from the declared type of the annotation parameter the constant is passed to. */
+  ANNOTATION_PARAMETER,
+  /**
+   * No type information was available anywhere, so `String` was assumed. Any non-`String` constant
+   * reaching this state produces an ABI whose type does not match the real declaration.
+   */
+  ASSUMED_STRING,
+}
+
+/**
+ * A constant that had to be synthesised because its declaring class was not on the source-only ABI
+ * classpath.
+ *
+ * The value is never recoverable in this situation - only the type sometimes is. See
+ * [AbiGenRepairLog].
+ */
+data class FabricatedConstant(
+    val classId: String,
+    val name: String,
+    val emittedType: String,
+    val typeSource: ConstTypeSource,
+)
+
+/**
+ * An initializer that was discarded because it could not be resolved.
+ *
+ * [isConst] and [consumerVisible] exist so [ValidationStage] can tell the defect it is looking for
+ * - a `const val` a consumer will constant-fold - from a `private const val`, which no consumer can
+ *   see and which therefore takes part in no consumer's constant folding. Both default to the
+ *   conservative answer for the record kinds that do not set them.
+ */
+data class DiscardedInitializer(
+    val owner: String,
+    val detail: String,
+    val isConst: Boolean = false,
+    val consumerVisible: Boolean = true,
+)
+
+/**
+ * A consumer-visible member whose signature did not resolve, so the emitted descriptor carries
+ * `error/NonExistentClass` in the slot named by [where].
+ *
+ * A non-API member in this state is degraded to `Any?`; an API member cannot be, because the
+ * descriptor IS the ABI. The only honest outcomes are to fail or to ship a stub no consumer can
+ * link against.
+ */
+data class ErrorTypedApiMember(val owner: String, val member: String, val where: String)
+
+/**
+ * Record of every place the ABI generator knowingly emitted something other than what the source
+ * says, plus every place a best-effort repair failed outright.
+ *
+ * Kosabi cannot see the value of a constant whose declaring target is absent from the source-only
+ * ABI classpath, so it substitutes a placeholder. That substitution is not detectable in the
+ * resulting jar - the bytecode is well formed, it just holds the wrong number. This log is the only
+ * signal that it happened, so nothing here may be dropped on the floor.
+ *
+ * One instance is shared by all pipeline stages for a single compilation.
+ */
+class AbiGenRepairLog {
+  val fabricatedConstants: MutableList<FabricatedConstant> = mutableListOf()
+  val clearedPropertyInitializers: MutableList<DiscardedInitializer> = mutableListOf()
+  val replacedFieldInitializers: MutableList<DiscardedInitializer> = mutableListOf()
+  val strippedSupertypes: MutableList<DiscardedInitializer> = mutableListOf()
+
+  /**
+   * Repairs that did not even complete - a reflective mutation threw, so the FIR tree is in
+   * whatever state the failure left it in. Previously these were swallowed by empty catch blocks.
+   */
+  val failedRepairs: MutableList<DiscardedInitializer> = mutableListOf()
+
+  private val errorTypedApiPositionsByDeclaration: IdentityHashMap<Any, MutableSet<String>> =
+      IdentityHashMap()
+
+  val errorTypedApiMembers: MutableList<ErrorTypedApiMember> = mutableListOf()
+
+  fun recordErrorTypedApiMember(
+      declarationIdentity: Any,
+      owner: String,
+      member: String,
+      where: String,
+  ) {
+    val positions =
+        errorTypedApiPositionsByDeclaration.getOrPut(declarationIdentity) { mutableSetOf() }
+    if (positions.add(where)) {
+      errorTypedApiMembers.add(ErrorTypedApiMember(owner, member, where))
+    }
+  }
+
+  fun recordFabricatedConstant(constant: FabricatedConstant) {
+    fabricatedConstants.add(constant)
+  }
+
+  fun recordClearedPropertyInitializer(
+      owner: String,
+      detail: String,
+      isConst: Boolean = false,
+      consumerVisible: Boolean = true,
+  ) {
+    clearedPropertyInitializers.add(
+        DiscardedInitializer(owner, detail, isConst, consumerVisible),
+    )
+  }
+
+  fun recordReplacedFieldInitializer(owner: String, detail: String) {
+    replacedFieldInitializers.add(DiscardedInitializer(owner, detail))
+  }
+
+  fun recordStrippedSupertype(owner: String, detail: String) {
+    strippedSupertypes.add(DiscardedInitializer(owner, detail))
+  }
+
+  fun recordFailedRepair(owner: String, detail: String) {
+    failedRepairs.add(DiscardedInitializer(owner, detail))
+  }
+
+  /**
+   * Count of repairs the generator actually performed. [errorTypedApiMembers] and [failedRepairs]
+   * are deliberately excluded: neither is a repair. An error-typed API member is left untouched by
+   * design (degrading it would move the lie from the descriptor into the metadata), and a failed
+   * repair is one that threw. Both are unresolved defects that [ValidationStage] reports on their
+   * own; do not fold them in here.
+   */
+  val totalRepairs: Int
+    get() =
+        fabricatedConstants.size +
+            clearedPropertyInitializers.size +
+            replacedFieldInitializers.size +
+            strippedSupertypes.size
+
+  /**
+   * Constants whose emitted type is known not to match the real declaration, or is only a guess.
+   * These are the ones that corrupt a consumer's constant folding rather than merely degrading it.
+   */
+  fun unsoundConstants(): List<FabricatedConstant> = fabricatedConstants.filter {
+    it.typeSource == ConstTypeSource.ASSUMED_STRING
+  }
+
+  /** Single machine-greppable line so the repair rate can be aggregated across a build. */
+  fun counterLine(): String =
+      "KOSABI_ABI_REPAIR_COUNTERS" +
+          " fabricated_constants=${fabricatedConstants.size}" +
+          " fabricated_constants_type_unknown=${unsoundConstants().size}" +
+          " cleared_property_initializers=${clearedPropertyInitializers.size}" +
+          " replaced_field_initializers=${replacedFieldInitializers.size}" +
+          " stripped_supertypes=${strippedSupertypes.size}" +
+          " error_typed_api_members=${errorTypedApiMembers.size}" +
+          " failed_repairs=${failedRepairs.size}"
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenStage.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenStage.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/k2-jvm-abi-gen/src/main/kotlin/pipeline/AbiGenStage.kt
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:SuppressWarnings("PackageLocationMismatch")
+
+package com.facebook
+
+/** A stage in the K2 Kosabi ABI generation pipeline. */
+interface AbiGenStage {
+  val name: String
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/BUCK
@@ -0,0 +1,96 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "kosabi-common",
+    srcs = glob(
+        ["**/*.kt"],
+        exclude = [
+            "plugin/**",
+            # The standalone CLI lives in its own library (`:stubsgen-cli-lib`) so that
+            # kotlin-compiler-embeddable stays a runtime dep of the binary rather than a
+            # provided_dep of this widely-consumed common library.
+            "cli/**",
+        ],
+    ),
+    labels = ["codegen_rule"],
+    provided_deps = [
+        "prelude//toolchains/android/third-party:kotlin-compiler",
+        "prelude//toolchains/android/third-party:kotlin-reflect",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:kotlin-stdlib",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common:common",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/common/stub:stub",
+    ],
+)
+
+buck_kotlin_library(
+    name = "stubsgen-k2-plugin",
+    srcs = glob(
+        [
+            "plugin/*.kt",
+        ],
+    ),
+    labels = ["codegen_rule"],
+    provided_deps = [
+        "prelude//toolchains/android/third-party:kotlin-compiler-embeddable",
+    ],
+    resources = glob(["plugin/resources/**"]),
+    resources_root = "plugin/resources",
+    tests = [
+        "fbsource//fbandroid/javatests/com/facebook/kotlin/compilerplugins/kosabi/integrationtest:integration-test",
+        "fbsource//fbandroid/javatests/com/facebook/kotlin/compilerplugins/kosabi/stubsgen:stubsgen",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "fbsource//fbandroid/java/com/facebook/kotlin/compilercompat:compilercompat",
+        "fbsource//fbandroid/java/com/facebook/kotlin/compilercompat:compilercompat_with_ka",
+    ],
+    exported_deps = [
+        ":kosabi-common",
+    ],
+)
+
+buck_java_binary(
+    name = "stubsgen_k2",
+    visibility = ["PUBLIC"],
+    deps = [":stubsgen-k2-plugin"],
+)
+
+# Standalone Kosabi stub generator that runs OUTSIDE kotlinc using a minimal, parse-only
+# PSI environment (see cli/StubsGenParseOnlyEnvironment.kt). It reuses StubsGenApiImpl
+# verbatim; the only extra runtime dependency is kotlin-compiler-embeddable, which provides
+# both the Kotlin PSI and the shaded IntelliJ `com.intellij.core.*` environment.
+buck_kotlin_library(
+    name = "stubsgen-cli-lib",
+    srcs = glob(["cli/**/*.kt"]),
+    labels = ["codegen_rule"],
+    visibility = ["PUBLIC"],
+    deps = [
+        ":kosabi-common",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/common:common",
+        "prelude//toolchains/android/third-party:kotlin-compiler-embeddable",
+        # Required at runtime: the shaded IntelliJ MockApplication in kotlin-compiler-embeddable
+        # spins up a coroutine scope during CoreApplicationEnvironment construction.
+        "prelude//toolchains/android/third-party:kotlinx-coroutines-core-jvm",
+    ],
+)
+
+buck_java_binary(
+    name = "stubsgen-cli",
+    main_class = "com.facebook.kotlin.compilerplugins.kosabi.stubsgen.cli.MainKt",
+    visibility = ["PUBLIC"],
+    deps = [":stubsgen-cli-lib"],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/Main.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/Main.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/Main.kt
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.cli
+
+import java.io.File
+import kotlin.system.exitProcess
+
+private const val USAGE =
+    """Usage: stubsgen-cli --sources <path>[,<path>...] [options]
+
+Runs Kosabi stub generation on a set of Kotlin sources using a minimal, parse-only
+PSI environment (no kotlinc / FIR / codegen / classpath index).
+
+Required:
+  --sources <path>[,<path>...]   Comma-separated .kt files and/or directories
+                                 (directories are searched recursively for .kt/.kts).
+
+At least one output must be given:
+  --stubs-out <dir>              Directory for generated .kt stubs.
+  --classes-out <dir>           Directory for generated .class (bytecode) stubs.
+
+Optional:
+  --classpath <path>[:<path>...] Path-separator-separated jars/dirs whose already-present
+                                 classes should NOT be stubbed. Default: empty.
+  --log <path>                   Write the stubsgen log to this file.
+
+Exit codes: 0 success, 1 generation failure, 2 usage error."""
+
+private const val EXIT_OK = 0
+private const val EXIT_FAILURE = 1
+private const val EXIT_USAGE = 2
+
+private class CliArgs(
+    val sources: List<File>,
+    val classpath: List<File>,
+    val stubsDumpDir: File?,
+    val stubsClassOutputDir: File?,
+    val logPath: String?,
+)
+
+private fun parseArgs(args: Array<String>): CliArgs? {
+  var sourcesArg: String? = null
+  var stubsOut: String? = null
+  var classesOut: String? = null
+  var classpathArg: String? = null
+  var logPath: String? = null
+
+  var i = 0
+  while (i < args.size) {
+    val key = args[i]
+    if (!key.startsWith("--")) {
+      System.err.println("Unexpected argument: $key")
+      return null
+    }
+    if (i + 1 >= args.size) {
+      System.err.println("Missing value for $key")
+      return null
+    }
+    val value = args[i + 1]
+    if (value.startsWith("--")) {
+      // The next token is another flag, not a value — report a clear error instead of
+      // silently consuming it (e.g. `--sources --stubs-out x`).
+      System.err.println("Missing value for $key")
+      return null
+    }
+    when (key) {
+      "--sources" -> sourcesArg = value
+      "--stubs-out" -> stubsOut = value
+      "--classes-out" -> classesOut = value
+      "--classpath" -> classpathArg = value
+      "--log" -> logPath = value
+      else -> {
+        System.err.println("Unknown flag: $key")
+        return null
+      }
+    }
+    i += 2
+  }
+
+  if (sourcesArg == null) {
+    System.err.println("Missing required --sources")
+    return null
+  }
+  val sources = collectSourceFiles(sourcesArg) ?: return null
+  if (sources.isEmpty()) {
+    System.err.println("No .kt/.kts sources found under: $sourcesArg")
+    return null
+  }
+
+  val stubsDumpDir = stubsOut?.let { File(it) }
+  val stubsClassOutputDir = classesOut?.let { File(it) }
+  if (stubsDumpDir == null && stubsClassOutputDir == null) {
+    System.err.println("At least one of --stubs-out / --classes-out is required")
+    return null
+  }
+
+  val classpath =
+      classpathArg?.split(File.pathSeparatorChar)?.filter { it.isNotBlank() }?.map { File(it) }
+          ?: emptyList()
+
+  return CliArgs(
+      sources = sources,
+      classpath = classpath,
+      stubsDumpDir = stubsDumpDir,
+      stubsClassOutputDir = stubsClassOutputDir,
+      logPath = logPath,
+  )
+}
+
+private fun collectSourceFiles(sourcesArg: String): List<File>? {
+  // --sources is comma-delimited; source paths must therefore not contain a literal comma.
+  val entries = sourcesArg.split(',').map { it.trim() }.filter { it.isNotEmpty() }
+
+  val collected = mutableListOf<File>()
+  for (entry in entries) {
+    val path = File(entry)
+    when {
+      path.isDirectory ->
+          collected += path.walkTopDown().filter { it.isFile && it.isKotlinSource() }
+      path.isFile && path.isKotlinSource() -> collected += path
+      path.isFile -> {
+        System.err.println("Not a Kotlin source (expected .kt/.kts): $entry")
+        return null
+      }
+      else -> {
+        System.err.println("Source path does not exist: $entry")
+        return null
+      }
+    }
+  }
+
+  return collected.sortedBy { it.absolutePath }
+}
+
+private fun File.isKotlinSource(): Boolean = extension == "kt" || extension == "kts"
+
+fun main(args: Array<String>) {
+  val parsed = parseArgs(args)
+  if (parsed == null) {
+    System.err.println()
+    System.err.println(USAGE)
+    exitProcess(EXIT_USAGE)
+  }
+
+  val exitCode =
+      try {
+        StubsGenCli.generate(
+            sourceFiles = parsed.sources,
+            classpath = parsed.classpath,
+            stubsDumpDir = parsed.stubsDumpDir,
+            stubsClassOutputDir = parsed.stubsClassOutputDir,
+            logPath = parsed.logPath,
+        )
+        EXIT_OK
+      } catch (t: Throwable) {
+        System.err.println("stubsgen-cli: stub generation failed")
+        t.printStackTrace()
+        EXIT_FAILURE
+      }
+
+  exitProcess(exitCode)
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/StubsGenCli.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/StubsGenCli.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/StubsGenCli.kt
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.cli
+
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators.StubsGenAPI // @oss-enable
+import com.facebook.kotlin.compilerplugins.kosabi.common.Logger
+// @oss-disable: import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators.meta_only.StubsGenApiImpl
+import java.io.File
+import org.jetbrains.kotlin.config.CompilerConfiguration
+
+object StubsGenCli {
+
+  fun generate(
+      sourceFiles: List<File>,
+      classpath: List<File>,
+      stubsDumpDir: File?,
+      stubsClassOutputDir: File?,
+      logPath: String? = null,
+  ) {
+    // Save/restore the process-global logger path so it doesn't leak across same-JVM callers
+    // (e.g. StandaloneCliCompareTest); the CLI path is unaffected since the process exits.
+    val prevLogPath = Logger.userDefinedPath
+    Logger.userDefinedPath = logPath
+    try {
+      StubsGenParseOnlyEnvironment().use { env ->
+        val ktFiles = env.parse(sourceFiles)
+        // configuration is unused by generateStubs; empty is fine.
+        StubsGenAPI( // @oss-enable
+        // @oss-disable: StubsGenApiImpl(
+            stubsDumpDir = stubsDumpDir,
+            stubsClassOutputDir = stubsClassOutputDir,
+            classPaths = classpath,
+            // @oss-disable: knownSources = ktFiles,
+        )
+            .generateStubs(ktFiles, CompilerConfiguration(), env.project)
+      }
+    } finally {
+      Logger.userDefinedPath = prevLogPath
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/StubsGenParseOnlyEnvironment.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/StubsGenParseOnlyEnvironment.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/cli/StubsGenParseOnlyEnvironment.kt
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+@file:Suppress("PackageLocationMismatch")
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.cli
+
+import com.facebook.kotlin.compilerplugins.common.createFakeKtFile
+import java.io.Closeable
+import java.io.File
+import org.jetbrains.kotlin.com.intellij.core.CoreApplicationEnvironment
+import org.jetbrains.kotlin.com.intellij.core.CoreProjectEnvironment
+import org.jetbrains.kotlin.com.intellij.lang.LanguageParserDefinitions
+import org.jetbrains.kotlin.com.intellij.openapi.Disposable
+import org.jetbrains.kotlin.com.intellij.openapi.project.Project
+import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer
+import org.jetbrains.kotlin.com.intellij.psi.PsiManager
+import org.jetbrains.kotlin.idea.KotlinLanguage
+import org.jetbrains.kotlin.parsing.KotlinParserDefinition
+import org.jetbrains.kotlin.psi.KtFile
+
+// Parse-only PSI env: avoids createForProduction's extension points + classpath index.
+class StubsGenParseOnlyEnvironment : Closeable {
+
+  private val disposable: Disposable = Disposer.newDisposable("StubsGenParseOnlyEnvironment")
+
+  init {
+    setupIdeaStandaloneProperties()
+  }
+
+  private val applicationEnvironment: CoreApplicationEnvironment =
+      CoreApplicationEnvironment(disposable)
+
+  private val projectEnvironment: CoreProjectEnvironment =
+      CoreProjectEnvironment(disposable, applicationEnvironment)
+
+  val project: Project = projectEnvironment.project
+
+  init {
+    // Guard against double-registration (a test JVM may already have a Kotlin parser).
+    if (LanguageParserDefinitions.INSTANCE.forLanguage(KotlinLanguage.INSTANCE) == null) {
+      applicationEnvironment.registerParserDefinition(KotlinParserDefinition())
+    }
+  }
+
+  fun parse(sourceFiles: List<File>): List<KtFile> = sourceFiles.map { file ->
+    // Strip leading BOM to match the in-kotlinc LoadTextUtil (readText does not).
+    val content = file.readText().removePrefix("﻿")
+    createFakeKtFile(
+        fileManager = PsiManager.getInstance(project),
+        virtualFilePath = file.path,
+        name = file.name,
+        content = content,
+    )
+  }
+
+  override fun close() {
+    Disposer.dispose(disposable)
+  }
+
+  private companion object {
+    private fun setupIdeaStandaloneProperties() {
+      setIfAbsent("idea.io.use.nio2", "true")
+      setIfAbsent("idea.ignore.disabled.plugins", "true")
+      // idea.home.path must point at an existing dir or PathManager throws; use the JVM temp dir.
+      setIfAbsent("idea.home.path", System.getProperty("java.io.tmpdir"))
+    }
+
+    private fun setIfAbsent(key: String, value: String) {
+      if (System.getProperty(key).isNullOrEmpty()) {
+        System.setProperty(key, value)
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/AnnotationStubsGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/AnnotationStubsGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/AnnotationStubsGenerator.kt
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.Logger
+import com.facebook.kotlin.compilerplugins.kosabi.common.filterDifferentOuterClassIn
+import com.facebook.kotlin.compilerplugins.kosabi.common.outerClassOnlyQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.calculateQualifierList
+import org.jetbrains.kotlin.psi.KtUserType
+import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
+
+/**
+ * Tuned stub type to Annotation Class
+ * 1. ClassDeclaration's AnnotationEntry
+ * 2. (TODO) function parameters
+ * 3. (TODO) primary constructor
+ */
+class AnnotationStubsGenerator : StubsGenerator {
+  override fun generateStubs(context: GenerationContext) {
+    val candidates =
+        context.importedTypes.filterDifferentOuterClassIn(context.declaredTypes).filterNot {
+          context.externalTypeReferences.contains(it.outerClassOnlyQualifier())
+        }
+    val modulePkg = context.packageName()?.split(".").orEmpty()
+
+    context.annotationEntries
+        .mapNotNull { it.typeReference?.getChildOfType<KtUserType>() }
+        .forEach { annotationType ->
+          val genFullQualifier = annotationType.calculateQualifierList()
+          val imp = context.resolveImportedType(candidates, genFullQualifier.first())
+
+          val pkg: String
+          val name: String
+          val inners: List<String>
+          if (imp != null) {
+            pkg = imp.pkgAsString()
+            name = imp.names.first()
+            inners = imp.names.drop(1) + genFullQualifier.drop(1)
+          } else {
+            // No import matches. A qualifier carrying its own package is written out in full; one
+            // that carries none names a type of the module's own package. Either way this only
+            // retypes a stub that already exists, so it cannot invent an annotation: an annotation
+            // left as a plain class is what makes the use site unresolvable.
+            val written = FullTypeQualifier(genFullQualifier)
+            val qualifier =
+                if (written.pkg.isEmpty() && modulePkg.isNotEmpty()) {
+                  FullTypeQualifier(modulePkg + genFullQualifier)
+                } else {
+                  written
+                }
+            if (qualifier.names.isEmpty()) return@forEach
+            pkg = qualifier.pkgAsString()
+            name = qualifier.names.first()
+            inners = qualifier.names.drop(1)
+          }
+
+          val stub =
+              context.stubsContainer.find(pkg, name, inners)
+                  ?: nestUnderStubbedOuter(context, pkg, name, inners)
+          if (stub != null) {
+            stub.type = KStub.Type.ANNOTATION
+          } else {
+            Logger.log(
+                """
+          |  [Warning] stub not found
+          |    - name: $pkg:$name
+          |    - inners: $inners
+        """
+                    .trimMargin(),
+            )
+          }
+        }
+  }
+
+  // A nested annotation written only as `@Outer.Inner`, same-package and unimported, reaches no
+  // other generator: there is no import for InnerClassStubsGenerator to walk, and
+  // SamePackageClassStubsGenerator counts the annotation's own referencedName as a known symbol, so
+  // nothing fabricates the inner. Nesting it is only safe when the outer is itself a stub: an outer
+  // that is stubbed is off the reduced classpath, so everything nested in it is too, and the inner
+  // cannot shadow a type that would otherwise resolve.
+  private fun nestUnderStubbedOuter(
+      context: GenerationContext,
+      pkg: String,
+      name: String,
+      inners: List<String>,
+  ): KStub? {
+    if (inners.isEmpty()) return null
+    var stubToEdit = context.stubsContainer.find(pkg, name) ?: return null
+    var innerPkg = "$pkg.$name"
+    for (innerName in inners) {
+      val innerStub =
+          stubToEdit.innerStubs.find { it.name == innerName }
+              ?: KStub(innerPkg, innerName).also { stubToEdit.innerStubs += it }
+      innerPkg = "$innerPkg.$innerName"
+      stubToEdit = innerStub
+    }
+    return stubToEdit
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/ClassLevelFunctionStubsGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/ClassLevelFunctionStubsGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/ClassLevelFunctionStubsGenerator.kt
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KFunStub
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+import java.util.Locale
+
+// This name should be unique
+const val TOP_LEVEL_DECLARATION_CLASS_LITERAL = "_kosabi_stub_top_level_declaration"
+
+/**
+ * [ClassLevelFunctionStubsGenerator] generates Class level function
+ *
+ * The current implementation only have the function name and body is "TODO"
+ */
+class ClassLevelFunctionStubsGenerator : StubsGenerator {
+
+  override fun generateStubs(context: GenerationContext) {
+    val classLevelFunctionImportsCandidate = context.importedDeclarations - context.declaredTypes
+    // A member import proven to name a class (an all-caps outer used as a type) is stubbed as a
+    // class elsewhere; stubbing it as a fun too would invent a bogus top-level declaration.
+    val stubbedFuns = classLevelFunctionImportsCandidate.filter {
+      it.isTopLevelDeclaration() && !context.isProvenClassImport(it)
+    }
+
+    stubbedFuns
+        .groupBy { it.pkg }
+        .filterKeys { pkg -> !context.pkgsInClasspath.contains(pkg) }
+        .forEach { (pkg, qualifiers) -> buildStub(pkg, qualifiers, context) }
+  }
+
+  private fun buildStub(
+      pkg: List<String>,
+      clazzList: List<FullTypeQualifier>,
+      context: GenerationContext,
+  ) {
+    val clazz = pkg.last() + TOP_LEVEL_DECLARATION_CLASS_LITERAL
+    val packageName = pkg.joinToString(".")
+    val className = createClassName(clazz)
+
+    val kStub = KStub(packageName, className).apply { type = KStub.Type.TOP_LEVEL_DECLARATION }
+
+    clazzList
+        .mapNotNull { it.member }
+        .forEach { kStub.funStubs.add(KFunStub(it, context.typeValueArgs[it] ?: 0)) }
+
+    context.stubsContainer.add(kStub)
+  }
+
+  private fun createClassName(clazz: String): String {
+    return capitalize(clazz)
+  }
+
+  private fun capitalize(name: String): String {
+    return name.replaceFirstChar { it.titlecase(Locale.US) }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/CtorStubsGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/CtorStubsGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/CtorStubsGenerator.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KCtorStub
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+
+class CtorStubsGenerator : StubsGenerator {
+
+  override fun generateStubs(context: GenerationContext) {
+    // TODO: Do not apply for SDK classes
+    updateClassCtor(context.stubsContainer.all(), context)
+  }
+
+  private fun updateClassCtor(stubs: Collection<KStub>, context: GenerationContext) {
+    for (stub in stubs) {
+      if (stub.ctor == null) {
+        updateCtorParams(stub, context)
+      }
+      updateClassCtor(stub.innerStubs, context)
+    }
+  }
+
+  private fun updateCtorParams(stub: KStub, context: GenerationContext) {
+    context.typeValueArgs[stub.name]?.let { stub.ctor = KCtorStub(it) }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/FullQualifiedClassStubsGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/FullQualifiedClassStubsGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/FullQualifiedClassStubsGenerator.kt
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.Logger
+import com.facebook.kotlin.compilerplugins.kosabi.common.filterDifferentOuterClassIn
+import com.facebook.kotlin.compilerplugins.kosabi.common.outerClassOnlyQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+
+class FullQualifiedClassStubsGenerator : StubsGenerator {
+
+  override fun generateStubs(context: GenerationContext) {
+    context.fullQualifierTypes
+        .filterDifferentOuterClassIn(context.declaredTypes)
+        .filterNot { context.externalTypeReferences.contains(it.outerClassOnlyQualifier()) }
+        .filter { it.pkg.isNotEmpty() && it.names.isNotEmpty() }
+        .forEach { qualifier ->
+          val pkg = qualifier.pkgAsString()
+          // create a root stub or register a new one
+          val stub =
+              context.stubsContainer.find(pkg, qualifier.names.first())
+                  ?: KStub(pkg, qualifier.names.first()).also { context.stubsContainer.add(it) }
+
+          var stubToEdit = stub
+          for (className in qualifier.names.drop(1)) {
+            val innerStub =
+                stubToEdit.innerStubs.find { it.name == className }
+                    ?: KStub(stubToEdit.pkg + ".${stubToEdit.name}", className).also { innerStub ->
+                      stubToEdit.innerStubs += innerStub
+                      Logger.log(
+                          """
+                      |  [Update stub]
+                      |    - name: ${stubToEdit.pkg}:${stubToEdit.name}
+                      |    - type: ${stubToEdit.type.name}
+                      |    - innerStub:
+                      |      - name: ${innerStub.pkg ?: ""}:${innerStub.name}
+                      |      - type: ${innerStub.type.name}
+                    """
+                              .trimMargin(),
+                      )
+                    }
+            stubToEdit = innerStub
+          }
+        }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/GenerationContext.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/GenerationContext.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/GenerationContext.kt
@@ -0,0 +1,423 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.parseClasspathFileClassesAndPackages
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.stub.container.StubsContainer
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.stub.container.StubsContainerImpl
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.calculateQualifierList
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.declaredTypes
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.toImportedClass
+import java.io.File
+import org.jetbrains.kotlin.com.intellij.psi.PsiElement
+import org.jetbrains.kotlin.lexer.KtTokens
+import org.jetbrains.kotlin.psi.KtAnnotationEntry
+import org.jetbrains.kotlin.psi.KtCallExpression
+import org.jetbrains.kotlin.psi.KtClass
+import org.jetbrains.kotlin.psi.KtClassBody
+import org.jetbrains.kotlin.psi.KtClassOrObject
+import org.jetbrains.kotlin.psi.KtDelegatedSuperTypeEntry
+import org.jetbrains.kotlin.psi.KtFile
+import org.jetbrains.kotlin.psi.KtNameReferenceExpression
+import org.jetbrains.kotlin.psi.KtNullableType
+import org.jetbrains.kotlin.psi.KtParameterList
+import org.jetbrains.kotlin.psi.KtSecondaryConstructor
+import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry
+import org.jetbrains.kotlin.psi.KtSuperTypeEntry
+import org.jetbrains.kotlin.psi.KtSuperTypeList
+import org.jetbrains.kotlin.psi.KtSuperTypeListEntry
+import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
+import org.jetbrains.kotlin.psi.KtTypeAlias
+import org.jetbrains.kotlin.psi.KtTypeParameter
+import org.jetbrains.kotlin.psi.KtTypeParameterListOwner
+import org.jetbrains.kotlin.psi.KtTypeReference
+import org.jetbrains.kotlin.psi.KtUserType
+import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
+import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
+import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
+
+class GenerationContext {
+  val projectFiles: Collection<KtFile>
+  val stubsContainer: StubsContainer
+  val importedDeclarations: Set<FullTypeQualifier>
+  val importedTypes: Set<FullTypeQualifier>
+
+  /**
+   * [importedTypes] split by the file that wrote the import. A usage must be attributed against its
+   * own file's imports: the pooled set resolves a simple name to whichever file imported it first,
+   * which is the wrong type as soon as two files import different types of the same name.
+   */
+  val importedTypesByFile: Map<KtFile, Set<FullTypeQualifier>>
+
+  /**
+   * This contains external types outside from the local source codes, etc: classpath, code
+   * generation
+   */
+  val externalTypeReferences: Set<FullTypeQualifier>
+  val knownGeneratedTypes: Set<FullTypeQualifier>
+  val pkgsInClasspath: Set<List<String>>
+  val interfaceTypes: List<KtUserType>
+  // Each entry is one multi-bound type parameter's bounds, in source order.
+  val multiBoundGroups: List<List<KtUserType>>
+  val annotationEntries: List<KtAnnotationEntry>
+  val declaredTypes: Set<FullTypeQualifier>
+  val fullQualifierTypes: Set<FullTypeQualifier>
+  val importAlias: Set<String>
+
+  /**
+   * Alias name -> the type `import a.B as Alias` names. An import's [FullTypeQualifier] carries the
+   * imported FQN, whose last name is always the real name `B`, so a usage written `Alias` matches
+   * no candidate by name and would otherwise resolve to nothing.
+   */
+  val importAliasQualifiers: Map<String, FullTypeQualifier>
+  val typeAliasSymbol: Set<String>
+  val parameterNames: Set<String>
+
+  // Element: (type simple name -> num of ctor args)
+  val typeValueArgs: Map<String, Int>
+  val usedUserTypes: Set<KtUserType>
+
+  constructor(
+      projectFiles: Collection<KtFile>,
+      classpath: List<File>,
+      knownGeneratedTypes: Set<FullTypeQualifier> = emptySet(),
+      lightweight: Boolean = true,
+  ) {
+    this.projectFiles = projectFiles
+    this.stubsContainer = StubsContainerImpl()
+    this.knownGeneratedTypes = knownGeneratedTypes
+
+    if (lightweight) {
+      this.externalTypeReferences = emptySet()
+      this.pkgsInClasspath = emptySet()
+      this.importedDeclarations = emptySet()
+      this.importedTypes = emptySet()
+      this.importedTypesByFile = emptyMap()
+      this.interfaceTypes = emptyList()
+      this.multiBoundGroups = emptyList()
+      this.annotationEntries = emptyList()
+      this.declaredTypes = emptySet()
+      this.typeValueArgs = emptyMap<String, Int>()
+      this.importAlias = emptySet()
+      this.importAliasQualifiers = emptyMap()
+      this.fullQualifierTypes = emptySet()
+      this.usedUserTypes = emptySet()
+      this.typeAliasSymbol = emptySet()
+      this.parameterNames = emptySet()
+    } else {
+      val importsByFile = projectFiles.associateWith { it.importList?.imports ?: emptyList() }
+      val importDirectives = importsByFile.values.flatten()
+      this.importedDeclarations = importDirectives.mapNotNull { it.toImportedClass() }.toSet()
+      this.importAlias = importDirectives.mapNotNull { it.aliasName }.toSet()
+      val rawImportedTypes = importedDeclarations.filterNot { it.isTopLevelDeclaration() }.toSet()
+      // `importedTypes` and `importedTypesByFile` are assigned after the traversal below: both
+      // gain the usage-proven class imports, which need the collected type usages.
+      this.importAliasQualifiers =
+          importDirectives
+              .mapNotNull { directive ->
+                directive.aliasName?.let { alias -> alias to directive.toImportedClass() }
+              }
+              .toMap()
+
+      val dataInClasspath: Pair<Set<FullTypeQualifier>, Set<List<String>>> =
+          parseClasspathFileClassesAndPackages(classpath)
+      externalTypeReferences = dataInClasspath.first + knownGeneratedTypes
+      pkgsInClasspath = dataInClasspath.second
+
+      // declaredTypes is a structural getChildrenOfType recursion (it intentionally excludes
+      // local/anonymous classes in function bodies), so it stays out of the single-pass DFS below.
+      this.declaredTypes = projectFiles.flatMap { it.declaredTypes() }.toSet()
+
+      // Single-pass PSI traversal: one DFS per file collects everything the generators need,
+      // replacing 9 separate whole-tree collectDescendantsOfType walks. Semantics are preserved
+      // 1:1 — same node sets, same filters, and typeValueArgs keeps its per-file
+      // superCall -> callExpr -> class ordering so the last-key-wins toMap is unchanged.
+      val annotations = mutableListOf<KtAnnotationEntry>()
+      val aliasNames = mutableSetOf<String>()
+      val paramNames = mutableSetOf<String>()
+      val usedTypes = mutableSetOf<KtUserType>()
+      val multiSegQualifiers = mutableListOf<List<String>>()
+      val interfaceUserTypes = mutableListOf<KtUserType>()
+      val multiBoundUserTypes = mutableListOf<List<KtUserType>>()
+      val typeValueArgPairs = mutableListOf<Pair<String, Int>>()
+      for (ktFile in projectFiles) {
+        val superCallPairs = mutableListOf<Pair<String, Int>>()
+        val callExprPairs = mutableListOf<Pair<String, Int>>()
+        val classCtorPairs = mutableListOf<Pair<String, Int>>()
+        ktFile.accept(
+            object : KtTreeVisitorVoid() {
+              override fun visitElement(element: PsiElement) {
+                if (element is KtAnnotationEntry) {
+                  annotations.add(element)
+                }
+                if (element is KtTypeAlias) {
+                  element.name?.let { aliasNames.add(it) }
+                }
+                if (element is KtTypeParameter) {
+                  element.name?.let { paramNames.add(it) }
+                }
+                if (element is KtUserType && element.calculateQualifierList().size == 1) {
+                  usedTypes.add(element)
+                }
+                if (element is KtTypeReference) {
+                  element.userTypeForQualifier()?.calculateQualifierList()?.let { qualifier ->
+                    if (qualifier.size >= 2) {
+                      multiSegQualifiers.add(qualifier)
+                    }
+                  }
+                }
+                if (element is KtClassOrObject) {
+                  interfaceUserTypes.addAll(
+                      element.getInterfaceTypes().mapNotNull { it.typeAsUserType },
+                  )
+                }
+                if (element is KtTypeParameterListOwner) {
+                  multiBoundUserTypes.addAll(element.multiBoundGroups())
+                }
+                if (element is KtSuperTypeCallEntry) {
+                  element.typeValueArgs()?.let { superCallPairs.add(it) }
+                }
+                if (element is KtCallExpression) {
+                  element.typeValueArgs()?.let { callExprPairs.add(it) }
+                }
+                if (element is KtClass) {
+                  element.typeValueArgsFromSuperSecondaryConstructor()?.let {
+                    classCtorPairs.add(it)
+                  }
+                }
+                super.visitElement(element)
+              }
+            },
+        )
+        typeValueArgPairs.addAll(superCallPairs)
+        typeValueArgPairs.addAll(callExprPairs)
+        typeValueArgPairs.addAll(classCtorPairs)
+      }
+
+      this.annotationEntries = annotations
+      this.typeAliasSymbol = aliasNames
+      this.parameterNames = paramNames
+      this.usedUserTypes = usedTypes
+      this.interfaceTypes = interfaceUserTypes
+      this.multiBoundGroups = multiBoundUserTypes
+      this.fullQualifierTypes =
+          multiSegQualifiers
+              .distinct()
+              .map { FullTypeQualifier(it) }
+              .filterNot { it.isSdkQualifier() }
+              .toSet()
+      // An all-caps simple name (`IABJSOTA`, `OTA`, `URI`) parses as a static-const member, so
+      // its import carries no class name and drops out of the raw type sets above. A member used
+      // in type position is really a class: promote those imports, module-wide and per file, so
+      // every consumer resolves the owner. A member never used as a type stays out (top-level
+      // consts and funs).
+      this.importedTypes = rawImportedTypes + promoteProvenClassImports(importedDeclarations)
+      this.importedTypesByFile = importsByFile.mapValues { (_, imports) ->
+        val quals = imports.mapNotNull { it.toImportedClass() }
+        quals.filterNot { it.isTopLevelDeclaration() }.toSet() + promoteProvenClassImports(quals)
+      }
+      // TODO: We might have multiple ctors for each type.
+      // For now we're just skipping to have one (the default)
+      this.typeValueArgs = typeValueArgPairs.toMap()
+    }
+  }
+
+  // This will handle the super call entry for the ctor params
+  private fun KtSuperTypeCallEntry.typeValueArgs(): Pair<String, Int>? {
+    typeAsUserType?.referencedName?.let {
+      return it to valueArguments.size
+    }
+    return null
+  }
+
+  // This will handle the call expression for the ctor params
+  private fun KtCallExpression.typeValueArgs(): Pair<String, Int>? {
+    (referenceExpression() as? KtNameReferenceExpression)?.getReferencedName()?.let {
+      return it to valueArguments.size
+    }
+    return null
+  }
+
+  // This will handle secondary constructor calls with super delegation call
+  private fun KtClass.typeValueArgsFromSuperSecondaryConstructor(): Pair<String, Int>? {
+    val superTypeList = this.getChildOfType<KtSuperTypeList>()
+    val superTypeCallEntry = superTypeList?.getChildOfType<KtSuperTypeCallEntry>()
+    val superTypeEntries = superTypeList?.getChildrenOfType<KtSuperTypeEntry>()
+
+    if (
+        superTypeList == null ||
+            superTypeEntries.isNullOrEmpty() ||
+            isInterface() ||
+            superTypeCallEntry != null
+    ) {
+      return null
+    }
+    val clazzBody = this.getChildOfType<KtClassBody>()
+    val superSecondaryConstructor = clazzBody?.getSecondaryConstructor()?.superConstructor()
+    if (superSecondaryConstructor?.isNotEmpty() == true) {
+      val referenceName = superTypeEntries.first().typeAsUserType?.referencedName
+      referenceName?.let {
+        return it to superSecondaryConstructor.first().getDelegationCall().valueArguments.size
+      }
+    }
+    return null
+  }
+
+  /**
+   * This filters out possible class candidate while supporting delegation
+   * 1. Class with default constructor at class body, assume first super type call entry is class
+   * 2. Class with constructor delegation call has callee "super"
+   */
+  private fun KtClassOrObject.getInterfaceTypes(): List<KtSuperTypeListEntry> {
+    val superTypeList = this.getChildOfType<KtSuperTypeList>()
+    val superTypeCallEntry = superTypeList?.getChildOfType<KtSuperTypeCallEntry>()
+    val superTypeEntries = superTypeList?.getChildrenOfType<KtSuperTypeEntry>()?.toMutableList()
+    val delegatedSuperTypeEntries =
+        superTypeList?.getChildrenOfType<KtDelegatedSuperTypeEntry>()?.toMutableList()
+    if (
+        superTypeList == null ||
+            (superTypeEntries.isNullOrEmpty() && delegatedSuperTypeEntries.isNullOrEmpty())
+    ) {
+      return emptyList()
+    }
+    // Skip class body check if KtClassOrObject declaration keyword is interface
+    if (isInterface()) {
+      return superTypeEntries.orEmpty() + delegatedSuperTypeEntries.orEmpty()
+    }
+    // Assume first superTypeEntry is class if secondary constructor existed without super
+    // type call entry
+    if (superTypeCallEntry == null && !superTypeEntries.isNullOrEmpty()) {
+      val clazzBody = this.getChildOfType<KtClassBody>()
+      val secondaryConstructors = clazzBody?.getSecondaryConstructor()
+      val hasDefaultConstructor = secondaryConstructors?.defaultConstructor()?.isNotEmpty() == true
+      val hasSuperDelegationCallExpression =
+          secondaryConstructors?.superConstructor()?.isNotEmpty() == true
+      if (hasDefaultConstructor || hasSuperDelegationCallExpression) {
+        superTypeEntries.removeFirstOrNull()
+      }
+    }
+    return superTypeEntries.orEmpty() + delegatedSuperTypeEntries.orEmpty()
+  }
+
+  private fun KtClassOrObject.isInterface(): Boolean =
+      getDeclarationKeyword() == KtTokens.INTERFACE_KEYWORD
+
+  private fun KtClassBody.getSecondaryConstructor(): List<KtSecondaryConstructor> =
+      getChildrenOfType<KtSecondaryConstructor>().toList()
+
+  private fun List<KtSecondaryConstructor>.defaultConstructor() = filter { secondaryConstructor ->
+    val emptyParameterList =
+        secondaryConstructor.getChildOfType<KtParameterList>()?.parameters?.isEmpty() == true
+    emptyParameterList && secondaryConstructor.hasImplicitDelegationCall()
+  }
+
+  private fun List<KtSecondaryConstructor>.superConstructor() = filter {
+    !it.hasImplicitDelegationCall() && it.getDelegationCall().calleeExpression?.isThis == false
+  }
+
+  /**
+   * The [KtUserType] directly under a [KtTypeReference], unwrapping a single nullable wrapper.
+   * Mirrors the former UserTypeUtil.getUserType used by collectMultiSegmentQualifiers.
+   *
+   * When non-nullable: KtTypeReference - KtUserType. When nullable: KtTypeReference -
+   * KtNullableType
+   * - KtUserType.
+   */
+  private fun KtTypeReference.userTypeForQualifier(): KtUserType? {
+    val nullableTypeWrapper = getChildOfType<KtNullableType>()
+    return (nullableTypeWrapper ?: this).getChildOfType<KtUserType>()
+  }
+
+  // Grouped rather than flattened: the consumer decides per parameter, from the first bound.
+  private fun KtTypeParameterListOwner.multiBoundGroups(): List<List<KtUserType>> {
+    val boundsByParameter = mutableMapOf<String, MutableList<KtTypeReference>>()
+    typeParameters.forEach { parameter ->
+      val name = parameter.name ?: return@forEach
+      parameter.extendsBound?.let { boundsByParameter.getOrPut(name) { mutableListOf() }.add(it) }
+    }
+    typeConstraints.forEach { constraint ->
+      val name = constraint.subjectTypeParameterName?.getReferencedName() ?: return@forEach
+      constraint.boundTypeReference?.let {
+        boundsByParameter.getOrPut(name) { mutableListOf() }.add(it)
+      }
+    }
+    return boundsByParameter.values
+        .filter { it.size > 1 }
+        .mapNotNull { bounds ->
+          val userTypes = bounds.map { it.userTypeForQualifier() }
+          // The consumer keys the whole-parameter decision off the source-order first bound.
+          // Compacting nulls away would shift a later bound into first position, so a first bound
+          // that doesn't resolve to a KtUserType (e.g. a function-type bound) drops the group.
+          if (userTypes.first() == null) null else userTypes.filterNotNull()
+        }
+        .filter { it.size > 1 }
+  }
+
+  /**
+   * A member-only import (`import a.b.OTA`) whose name is used in type position names a class: an
+   * all-caps simple name parses as a static-const member, so the import carries no class name until
+   * usage proves it. A member never used as a type stays a declaration (a top-level const or fun).
+   */
+  fun isProvenClassImport(imp: FullTypeQualifier): Boolean {
+    val name =
+        imp.member?.takeIf { imp.names.isEmpty() && it.first().isUpperCase() } ?: return false
+    return usedUserTypes.any { it.referencedName == name }
+  }
+
+  private fun promoteProvenClassImports(
+      quals: Collection<FullTypeQualifier>,
+  ): Set<FullTypeQualifier> =
+      quals
+          .mapNotNull { imp ->
+            imp.member
+                ?.takeIf { isProvenClassImport(imp) }
+                ?.let { name ->
+                  FullTypeQualifier.unsafeBuildQualifier(imp.segments, imp.pkg, listOf(name))
+                }
+          }
+          .toSet()
+
+  /**
+   * The candidate an unqualified [simpleName] refers to.
+   *
+   * `import a.B as Alias` binds `Alias` and does not bind `B`, so matching an import by the last
+   * name of its FQN is only correct for an import that carries no alias. An alias resolves to the
+   * type it names; every other name prefers an unaliased import and only then falls back to the
+   * historical last-name match, so a name that resolves today keeps resolving.
+   *
+   * An alias naming a type the caller's own filter excluded stays unresolved: [candidates] is the
+   * authority on what this pass may act on.
+   */
+  fun resolveImportedType(
+      candidates: Collection<FullTypeQualifier>,
+      simpleName: String,
+  ): FullTypeQualifier? {
+    importAliasQualifiers[simpleName]?.let { aliased ->
+      candidates
+          .find { it.segments == aliased.segments }
+          ?.let {
+            return it
+          }
+    }
+    val byLastName = candidates.filter { it.names.last() == simpleName }
+    return byLastName.firstOrNull { candidate ->
+      importAliasQualifiers.values.none { it.segments == candidate.segments }
+    } ?: byLastName.firstOrNull()
+  }
+
+  fun packageName(): String? {
+    return projectFiles
+        .map { it -> it.packageFqName.asString() }
+        .filter { it -> it.isNotEmpty() }
+        .firstOrNull()
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/GenericStubsGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/GenericStubsGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/GenericStubsGenerator.kt
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.Logger
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.calculateQualifierList
+import org.jetbrains.kotlin.psi.KtTypeArgumentList
+import org.jetbrains.kotlin.psi.KtUserType
+import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
+import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
+
+class GenericStubsGenerator : StubsGenerator {
+  override fun generateStubs(context: GenerationContext) {
+    val usedGenericTypes: List<KtUserType> =
+        context.projectFiles
+            .flatMap {
+              // find all the types in the project files
+              it.collectDescendantsOfType<KtUserType>()
+            }
+            // check if this is generic one
+            .filter { it.anyDescendantOfType<KtTypeArgumentList>() }
+            // Deduplication is per file: the same text in two files can name two different types,
+            // and each file's usage has to reach its own stub.
+            .distinctBy { it.containingKtFile to it.text }
+
+    // TODO: Do not apply for SDK classes
+    // A usage resolves against the imports of ITS OWN file. Pooling every file's imports attributes
+    // a simple name to whichever file imported it first, so two files importing different types of
+    // the same name give one stub both arities and leave the other bare.
+    val candidatesByFile =
+        context.importedTypesByFile.mapValues { (_, imports) -> imports - context.declaredTypes }
+    val pooledCandidates = context.importedTypes - context.declaredTypes
+    val modulePkg = context.packageName()?.split(".").orEmpty()
+
+    for (genType in usedGenericTypes) {
+      val candidates = candidatesByFile[genType.containingKtFile] ?: pooledCandidates
+      val genFullQualifier = genType.calculateQualifierList()
+      val imp =
+          context.resolveImportedType(candidates, genFullQualifier.first())
+              ?: when {
+                genFullQualifier.size > 1 -> FullTypeQualifier(genFullQualifier)
+                modulePkg.isNotEmpty() -> FullTypeQualifier(modulePkg + genFullQualifier)
+                else -> continue
+              }
+      val name = imp.names
+      // An all-caps simple name reads as a static-const member, so the qualifier carries no class
+      // name to look up.
+      if (name.isEmpty()) continue
+      val pkg = imp.pkgAsString()
+      val innerClassNames =
+          if (genFullQualifier == imp.segments) emptyList<String>()
+          else (name.drop(1) + genFullQualifier.drop(1))
+
+      val stub =
+          context.stubsContainer.find(
+              pkg,
+              name.first(),
+              // Case 1:
+              // name = com.A.B
+              // genFullQualifier = B
+              // Case 2:
+              // name = com.A
+              // genFullQualifier = A.B
+              innerClassNames,
+          )
+
+      if (stub != null) {
+        stub.genericTypes = genType.typeArguments.size
+      } else {
+        Logger.log(
+            """
+          |  [Warning] stub not found
+          |    - name: $pkg:${name.first()}
+          |    - inner class names: $innerClassNames
+        """
+                .trimMargin(),
+        )
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/InnerClassStubsGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/InnerClassStubsGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/InnerClassStubsGenerator.kt
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.Logger
+import com.facebook.kotlin.compilerplugins.kosabi.common.filterDifferentOuterClassIn
+import com.facebook.kotlin.compilerplugins.kosabi.common.outerClassOnlyQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.ClassReferenceUtil
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.UserTypeUtil
+
+class InnerClassStubsGenerator : StubsGenerator {
+
+  override fun generateStubs(context: GenerationContext) {
+    // Declarations like `A.B.C`
+    // UserType => val x: A.B.C = ...
+    // ClassReference => @Throws(A.B.C::class)
+    val typeNameSegments =
+        UserTypeUtil.collectMultiSegmentQualifiers(context) +
+            ClassReferenceUtil.collectMultiSegmentQualifiers(context)
+
+    // import: com.A.B
+    // usage: B
+    val candidatesWithComplexImport =
+        (context.importedTypes - context.declaredTypes).filter { it.names.size >= 2 }
+
+    // import: com.A
+    // usage: A.B
+    val candidatesWithComplexUsage =
+        typeNameSegments
+            .map { segment ->
+              // Here we have a match:
+              // imp:           com.foo.T1.T2
+              // segment:       T2.T3...
+              val imp: FullTypeQualifier? =
+                  context.resolveImportedType(context.importedTypes, segment.first())
+              if (imp == null) {
+                Logger.log("  [Warning] ImportedType matches $segment not found!")
+              }
+              imp to segment
+            }
+            .filter { (imp, _) -> imp != null }
+            .map { (imp, segment) -> FullTypeQualifier(imp!!.segments + segment.drop(1)) }
+
+    val candidatesToGenerateInnerClass =
+        (candidatesWithComplexImport + candidatesWithComplexUsage)
+            .filter { it.member == null }
+            .toSet()
+            // We don't want to stub types if they are declared in compilation context
+            .filterDifferentOuterClassIn(context.declaredTypes)
+            .filterNot { context.externalTypeReferences.contains(it.outerClassOnlyQualifier()) }
+
+    candidatesToGenerateInnerClass.forEach { qualifier ->
+      // We should process with:
+      // pkg    = com.foo
+      // name   = T1
+      // inners = T2.T3
+      val pkg = qualifier.pkgAsString()
+      val name = qualifier.names.first()
+      val inners = qualifier.names.drop(1)
+      val stub = context.stubsContainer.find(pkg, name)
+
+      stub?.let {
+        var stubToEdit = it
+        var innerQualifier = stub.name
+        for (qualifierPart in inners) {
+          // find or create and register
+          val innerStub =
+              stubToEdit.innerStubs.find { it.name == qualifierPart }
+                  ?: KStub(pkg + ".${innerQualifier}", qualifierPart).also { innerStub ->
+                    stubToEdit.innerStubs += innerStub
+                    Logger.log(
+                        """
+                      |  [Update stub]
+                      |    - name: ${stubToEdit.pkg}:${stubToEdit.name}
+                      |    - type: ${stubToEdit.type.name}
+                      |    - innerStub:
+                      |      - name: ${innerStub.pkg ?: ""}:${innerStub.name}
+                      |      - type: ${innerStub.type.name}
+                    """
+                            .trimMargin(),
+                    )
+                  }
+          innerQualifier = "${innerQualifier}.${qualifierPart}"
+          stubToEdit = innerStub
+        }
+      }
+          ?: Logger.log(
+              "  [Error] An error occurs to qualifier: $qualifier. We should have an outer $pkg:$name stub at this point",
+          )
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/InterfaceStubsGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/InterfaceStubsGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/InterfaceStubsGenerator.kt
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.Logger
+import com.facebook.kotlin.compilerplugins.kosabi.common.filterDifferentOuterClassIn
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.calculateQualifierList
+import org.jetbrains.kotlin.psi.KtUserType
+
+/** [InnerClassStubsGenerator] should be after [CtorStubsGenerator] in the generation pipeline. */
+class InterfaceStubsGenerator : StubsGenerator {
+  override fun generateStubs(context: GenerationContext) {
+    // A usage resolves against the imports of ITS OWN file. Pooling every file's imports attributes
+    // a simple name to whichever file imported it first, so when two files import different types
+    // of the same name the wrong stub is retyped and the real supertype is left a class.
+    val candidatesByFile =
+        context.importedTypesByFile.mapValues { (_, imports) ->
+          imports.filterDifferentOuterClassIn(context.declaredTypes)
+        }
+    val pooledCandidates = context.importedTypes.filterDifferentOuterClassIn(context.declaredTypes)
+    fun candidatesFor(type: KtUserType): List<FullTypeQualifier> =
+        candidatesByFile[type.containingKtFile] ?: pooledCandidates
+
+    // Every stubbed bound of a multi-bound type parameter is emitted as an interface. Kotlin
+    // permits at most one non-interface bound, so at most one bound of a group can be a class, and
+    // the rules stacked with this one require that bound to be written first and to be on the
+    // reduced classpath -- where it is the real type, is never stubbed, and holds the class slot on
+    // its own. Interface is therefore the sound kind for every bound this pass can reach.
+    //
+    // A stub is born a class and carries no ClassKind, so leaving stubbed bounds alone corrupts a
+    // group whose bounds are all off the classpath: kotlinc hands the single class slot to
+    // whichever stub comes first and discards the other class-kinded bounds, which moves the
+    // erasure of the parameter.
+    //
+    // A nested bound cannot be retyped either way -- its enclosing stub would stay a class whose
+    // InnerClasses entry then describes an interface member, which javac rejects -- and the
+    // decision is whole-group rather than per bound: on facecast's 36-bound clause, retyping the
+    // group's OTHER tails still broke resolution of the nested bound at position 13, and dropping
+    // any one earlier retype cleared it.
+    val multiBoundStubs =
+        context.multiBoundGroups
+            .filterNot { group -> group.any { nested(context, candidatesFor(it), it) } }
+            .flatMap { group -> group.filter { isStubbed(context, candidatesFor(it), it) } }
+
+    for (iType in context.interfaceTypes + multiBoundStubs) {
+      val qualifierList = iType.calculateQualifierList()
+      val imp = context.resolveImportedType(candidatesFor(iType), qualifierList.first())
+      var pkg: String
+      var name: String
+      var inners: List<String>
+
+      if (imp == null) {
+        // handle the case where full path is written in type ex. val x: a.b.A
+        if (qualifierList.size > 1) {
+          val fullTypeQualifier = FullTypeQualifier(qualifierList)
+          pkg = fullTypeQualifier.pkgAsString()
+          name = fullTypeQualifier.names.first()
+          inners = fullTypeQualifier.names.drop(1)
+        } else {
+          Logger.log(
+              """
+        |  [Warning] ImportTypes not found
+        |    - name: $qualifierList
+      """
+                  .trimMargin(),
+          )
+          continue
+        }
+      } else {
+        pkg = imp.pkgAsString()
+        name = imp.names.first()
+        inners = imp.names.drop(1) + qualifierList.drop(1)
+      }
+
+      val stub = context.stubsContainer.find(pkg, name, inners)
+      if (stub != null) {
+        stub.type = KStub.Type.INTERFACE
+      } else {
+        Logger.log(
+            """
+          |  [Warning] stub not found
+          |    - name: $pkg:$name
+          |    - inners: $inners
+        """
+                .trimMargin(),
+        )
+      }
+    }
+  }
+
+  // Retyping a nested stub would leave its enclosing stub a class whose InnerClasses entry
+  // describes an interface member, and javac rejects that pair while completing the outer.
+  private fun nested(
+      context: GenerationContext,
+      candidates: Collection<FullTypeQualifier>,
+      type: KtUserType,
+  ): Boolean {
+    val qualifierList = type.calculateQualifierList()
+    val imp = context.resolveImportedType(candidates, qualifierList.first())
+    return when {
+      imp != null ->
+          (imp.names.drop(1) + qualifierList.drop(1)).isNotEmpty() ||
+              imp.pkgAsString().isNestedOwner()
+      qualifierList.size > 1 ->
+          FullTypeQualifier(qualifierList).let {
+            it.names.drop(1).isNotEmpty() || it.pkgAsString().isNestedOwner()
+          }
+      else -> false
+    }
+  }
+
+  // A stub exists exactly when the type is off the reduced classpath. A bound that is not stubbed
+  // is the real type and already carries its own kind, so retyping it is neither needed nor safe.
+  private fun isStubbed(
+      context: GenerationContext,
+      candidates: Collection<FullTypeQualifier>,
+      first: KtUserType,
+  ): Boolean {
+    val qualifierList = first.calculateQualifierList()
+    val imp = context.resolveImportedType(candidates, qualifierList.first())
+    val pkg: String
+    val name: String
+    val inners: List<String>
+    if (imp != null) {
+      pkg = imp.pkgAsString()
+      name = imp.names.first()
+      inners = imp.names.drop(1) + qualifierList.drop(1)
+    } else if (qualifierList.size > 1) {
+      val full = FullTypeQualifier(qualifierList)
+      pkg = full.pkgAsString()
+      name = full.names.first()
+      inners = full.names.drop(1)
+    } else {
+      // A single segment with no import is either declared in this module -- never stubbed -- or
+      // a builtin, which is treated as stubbed because that only costs the retyping.
+      return context.declaredTypes.none { it.names.last() == qualifierList.first() }
+    }
+    return context.stubsContainer.find(pkg, name, inners) != null
+  }
+}
+
+// StubBytecodeRender.internalName treats an uppercase trailing package segment as an outer
+// class, so a stub owned by one renders as `Outer$Inner`.
+private fun String.isNestedOwner(): Boolean =
+    substringAfterLast('.').firstOrNull()?.isUpperCase() == true
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/PrimitiveStubsGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/PrimitiveStubsGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/PrimitiveStubsGenerator.kt
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.filterDifferentOuterClassIn
+import com.facebook.kotlin.compilerplugins.kosabi.common.outerClassOnlyQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+
+/**
+ * [PrimitiveStubsGenerator] generates OPEN CLASSES stubs for all alien classes.
+ *
+ * Alien Class = Class outside of Project Context.
+ */
+class PrimitiveStubsGenerator(private val postfixToSkip: String?) : StubsGenerator {
+
+  override fun generateStubs(context: GenerationContext) {
+    val imports: Set<FullTypeQualifier> = context.importedTypes
+
+    // We're creating simple stubs for everything we found not in classpaths
+    imports
+        .filterNot { it.pkgAsString().isSdkImport() }
+        .filterDifferentOuterClassIn(context.declaredTypes)
+        .filterNot { context.externalTypeReferences.contains(it.outerClassOnlyQualifier()) }
+        .map { imp -> imp.pkgAsString() to imp.names.first() }
+        .filterNot { (pkg, name) ->
+          postfixToSkip != null && pkg == context.packageName() && name.endsWith(postfixToSkip)
+        }
+        .forEach { (pkg, name) ->
+          if (name.first().isUpperCase() && context.stubsContainer.find(pkg, name) == null) {
+            context.stubsContainer.add(KStub(pkg, name))
+          }
+        }
+  }
+}
+
+private const val KOTLIN_STDLIB_PREFIX = "kotlin"
+private const val JAVA_STDLIB_PREFIX = "java"
+private const val JAVA_LANG_PREFIX = "java.lang"
+// `jdk.compiler` classes are loaded from JRT rather than `jvmClasspathRoots`. Generated stubs would
+// shadow the real classes and erase inherited member contracts used for JVM descriptor lowering.
+private val JDK_COMPILER_PACKAGE_PREFIXES = listOf(
+    "com.sun.source",
+    "com.sun.tools.javac",
+    "javax.annotation.processing",
+    "javax.lang.model",
+    "javax.tools",
+)
+
+// kotlin.Unit - is an SDK class
+// kotlinx.Parcelize - is not
+private fun isKotlinSdk(pkg: String): Boolean =
+    pkg == KOTLIN_STDLIB_PREFIX || pkg.startsWith("$KOTLIN_STDLIB_PREFIX.")
+
+private fun isJavaSdk(pkg: String): Boolean =
+    pkg == JAVA_STDLIB_PREFIX ||
+        pkg.startsWith("$JAVA_STDLIB_PREFIX.") ||
+        JDK_COMPILER_PACKAGE_PREFIXES.any { prefix ->
+          pkg == prefix || pkg.startsWith("$prefix.")
+        }
+
+private fun String.isSdkImport(): Boolean = isKotlinSdk(this) || isJavaSdk(this)
+
+fun FullTypeQualifier.isSdkQualifier(): Boolean {
+  val pkg = pkgAsString()
+  return isKotlinSdk(pkg) || isJavaSdk(pkg)
+}
+
+// Types that don't require imports (auto-imported)
+fun FullTypeQualifier.isAutoImported(): Boolean {
+  val pkgStr = pkgAsString()
+  // java.lang.* types are auto-imported
+  return pkgStr == JAVA_LANG_PREFIX || pkgStr.startsWith("$JAVA_LANG_PREFIX.")
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/SamePackageClassStubsGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/SamePackageClassStubsGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/SamePackageClassStubsGenerator.kt
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.PlainJavaLangTypes
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.PlainKTBuiltInTypes
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.PlainKTJavaTypeAlias
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util.PlainKTStdlibTypes
+import org.jetbrains.kotlin.psi.KtUserType
+import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
+
+// Generate stubs for all unknown classes that are not declared from the module, nor from imported
+// or class paths
+// This is to handle cases like we have dependent module that use same package name as the current
+// module. (Like a GraphQL model
+// In this case explicit import for usage of those classes are not needed)
+class SamePackageClassStubsGenerator : StubsGenerator {
+
+  override fun generateStubs(context: GenerationContext) {
+
+    val modulePkgName = context.packageName() ?: return
+    val allKnownSymbols = mutableSetOf<String>()
+
+    // Kotlin/Java built-in, stdlib types
+    val sdkInternalTypes = setOf(
+        PlainKTStdlibTypes,
+        PlainKTBuiltInTypes,
+        PlainKTJavaTypeAlias,
+        PlainJavaLangTypes,
+    )
+        .flatMap { it.all() }
+
+    allKnownSymbols.addAll(sdkInternalTypes)
+
+    // Imported types, declared types, and auto-imported external types from classpaths
+    // Only include auto-imported types (java.lang.*) from externalTypeReferences
+    // to avoid name collisions with non-auto-imported types that have the same simple name.
+    // Types like android.*, javax.*, etc. require explicit imports and should not be included here.
+    val autoImportedExternalTypes = context.externalTypeReferences.filter { it.isAutoImported() }
+    val generatedTypesInModulePackage =
+        context.knownGeneratedTypes.filter { it.pkgAsString() == modulePkgName }
+    // A qualifier that carries no package (`Outer.Inner`) and whose outer no import,
+    // declaration, or classpath entry owns names a nested type of the module's own
+    // package. FullQualifiedClassStubsGenerator drops it for having no package and
+    // InnerClassStubsGenerator can only reach it through an import, so nothing creates its outer:
+    // counting that outer as known here is what leaves the usage with no stub at all.
+    val nestedSamePackageQualifiers =
+        context.fullQualifierTypes.filter {
+          it.pkg.isEmpty() && it.member == null && it.names.size > 1
+        }
+    allKnownSymbols.addAll(
+        (context.importedTypes +
+                context.declaredTypes +
+                autoImportedExternalTypes +
+                generatedTypesInModulePackage +
+                (context.fullQualifierTypes - nestedSamePackageQualifiers.toSet()))
+            .flatMap { it.segments + it.names },
+    )
+    allKnownSymbols.addAll(nestedSamePackageQualifiers.flatMap { it.names.drop(1) })
+
+    // Alias & type parameter names
+    allKnownSymbols.addAll(context.typeAliasSymbol + context.importAlias + context.parameterNames)
+
+    // Annotations
+    allKnownSymbols.addAll(
+        context.annotationEntries
+            .mapNotNull { it.typeReference?.getChildOfType<KtUserType>() }
+            .mapNotNull { it.referencedName },
+    )
+
+    val maybeUnknownClasses =
+        context.usedUserTypes
+            .mapNotNull { userType -> userType.referencedName }
+            .toSet()
+            .filterNot { it -> allKnownSymbols.contains(it) }
+            .filter { it -> it.first().isUpperCase() }
+
+    maybeUnknownClasses.forEach { typeName ->
+      if (context.stubsContainer.find(modulePkgName, typeName) == null) {
+        context.stubsContainer.add(KStub(modulePkgName, typeName))
+      }
+    }
+
+    // The usage is `Outer.Inner`, so the outer stub fabricated above still has to own an Inner for
+    // the reference to resolve. Only outers fabricated here are nested into: an outer resolved any
+    // other way already has its own owner, and its nesting belongs to that owner's generator.
+    val fabricatedNames = maybeUnknownClasses.toSet()
+    nestedSamePackageQualifiers
+        .filter { it.names.first() in fabricatedNames }
+        .forEach { qualifier ->
+          var stubToEdit =
+              context.stubsContainer.find(modulePkgName, qualifier.names.first()) ?: return@forEach
+          var innerPkg = "$modulePkgName.${stubToEdit.name}"
+          for (innerName in qualifier.names.drop(1)) {
+            val innerStub =
+                stubToEdit.innerStubs.find { it.name == innerName }
+                    ?: KStub(innerPkg, innerName).also { stubToEdit.innerStubs += it }
+            innerPkg = "$innerPkg.$innerName"
+            stubToEdit = innerStub
+          }
+        }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/StubsGenAPI.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/StubsGenAPI.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/StubsGenAPI.kt
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+import com.facebook.buck.jvm.kotlin.compilerplugins.kosabi.common.stub.render.StubBytecodeRender
+import com.facebook.buck.jvm.kotlin.compilerplugins.kosabi.common.stub.render.StubBytecodeRender.supportBytecode
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.common.Logger
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.generateFakeKtFile
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.render.RenderedKStub
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.render.render
+import java.io.File
+import java.nio.file.Files
+import kotlin.collections.forEach
+import org.jetbrains.kotlin.com.intellij.openapi.project.Project
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.psi.KtFile
+
+open class StubsGenAPI(
+    private val stubsDumpDir: File? = null,
+    private val stubsClassOutputDir: File? = null,
+    private val classPaths: List<File>,
+) {
+
+  fun generateStubs(
+      knownSources: Collection<KtFile>,
+      configuration: CompilerConfiguration,
+      project: Project,
+  ): Collection<KtFile> {
+
+    // Why we have two rounds of `generateStubs` here?
+    //
+    // 1. [additionalSourcesGenerators] creates a set of additional sources ([KStub]s that we treat
+    // as real files)
+    // An additional source file is usually a complicated stub that is included in ABI.
+    //
+    // 2. If we run [additionalSourcesGenerators] as a part of [CustomStubsGenerator]
+    // we will need to run all the stubs that generate stub classes structure (primitive, ctor, ...)
+    // for types that we introduced during [additionalSourcesGenerators]
+    //   2a. or alternatively create all these stubs (but it's a lot of work)
+    //
+    // 3. So we call [additionalSourcesGenerators] with it's own [generationContext]
+    //   3a. Than dump context creating additional source files (similar to what AP usually does)
+    //   3b. Than run the second round  with extended [knownSources]
+    Logger.log("[Source files] ${knownSources.joinToString(", ") { it.name }}")
+    val additionalSrcStubsContext = GenerationContext(knownSources, classPaths, lightweight = true)
+    val additionalSrcStubs =
+        generateStubs(configureAdditionalSourcesGenerators(), additionalSrcStubsContext)
+    val additionalRenderedSrcStubs: List<RenderedKStub> = additionalSrcStubs.map {
+      RenderedKStub(it, it.render())
+    }
+    val additionalSrcs = additionalRenderedSrcStubs.map { generateFakeKtFile(project, it) }
+
+    val stubsGenerators: List<StubsGenerator> = listOf(
+        PrimitiveStubsGenerator(getPostfixToSkipForPrimitiveTypesGeneration()),
+        InnerClassStubsGenerator(),
+        FullQualifiedClassStubsGenerator(),
+        SamePackageClassStubsGenerator(),
+        CtorStubsGenerator(),
+        InterfaceStubsGenerator(),
+        GenericStubsGenerator(),
+        AnnotationStubsGenerator(),
+        ClassLevelFunctionStubsGenerator(),
+    )
+    val context = GenerationContext(
+        additionalSrcs + knownSources,
+        classPaths,
+        getKnownKspGeneratedTypes(),
+        lightweight = false,
+    )
+    val stubs = generateStubs(stubsGenerators + configureExtraGenerators(), context)
+    val enableBytecodeStub = stubsClassOutputDir != null
+    val renderedStubs: List<RenderedKStub> =
+        stubs
+            .filter { stub -> !enableBytecodeStub || !stub.supportBytecode() }
+            .map { RenderedKStub(it, it.render()) }
+    val stubFiles = renderedStubs.map { generateFakeKtFile(project, it) }
+
+    if (stubsDumpDir != null) {
+      val stubDir = stubsDumpDir
+      check(stubDir.exists() || stubDir.mkdirs()) {
+        "Could not generate package directory: $stubDir"
+      }
+
+      (additionalSrcs + stubFiles).forEach { file ->
+        File(stubsDumpDir, file.name).writeText(file.text)
+      }
+    }
+
+    if (stubsClassOutputDir != null) {
+      val stubClassDir = stubsClassOutputDir
+      check(stubClassDir.exists() || stubClassDir.mkdirs()) {
+        "Could not generate package directory: $stubClassDir"
+      }
+      stubs
+          .filter { stub -> stub.supportBytecode() }
+          .forEach { StubBytecodeRender.renderKStubBytecode(it, stubsClassOutputDir) }
+    }
+
+    return additionalSrcs + stubFiles
+  }
+
+  open fun configureExtraGenerators(): List<StubsGenerator> {
+    return emptyList()
+  }
+
+  open fun configureAdditionalSourcesGenerators(): List<StubsGenerator> {
+    return emptyList()
+  }
+
+  open fun getKnownKspGeneratedTypes(): Set<FullTypeQualifier> {
+    return emptySet()
+  }
+
+  open fun getPostfixToSkipForPrimitiveTypesGeneration(): String? {
+    return null
+  }
+
+  fun writeStubs(dir: File, stubs: Collection<RenderedKStub>) {
+    stubs.forEach { renderedStub ->
+      val relativeDir = renderedStub.stub.pkg?.replace(".", "/")
+      val targetDir = if (relativeDir.isNullOrEmpty()) dir else dir.resolve(relativeDir)
+      Files.createDirectories(targetDir.toPath())
+      val filename = "${renderedStub.stub.name}.kt"
+      File(targetDir, filename).writeText(renderedStub.render)
+    }
+  }
+
+  private fun generateStubs(
+      generators: List<StubsGenerator>,
+      context: GenerationContext,
+  ): Collection<KStub> {
+    generators.forEach { generator ->
+      Logger.log("[${generator.javaClass.simpleName}]")
+      generator.generateStubs(context)
+    }
+    return context.stubsContainer.all()
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/StubsGenerator.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/StubsGenerator.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/generators/StubsGenerator.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators
+
+interface StubsGenerator {
+  /**
+   * Called multiple times in order to create new code. Note that instances should not rely on being
+   * able to resolve [projectFiles] to descriptors. They should rather use the Psi APIs to parse
+   * files.
+   *
+   * In the first round code generators are called with the files from the project. In following
+   * rounds [projectFiles] represents files that were generated by code generators until no code
+   * generator produces any files anymore.
+   */
+  fun generateStubs(context: GenerationContext)
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenCommandLineProcessor.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenCommandLineProcessor.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenCommandLineProcessor.kt
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.plugin.stubsgen_k2
+
+import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption
+import org.jetbrains.kotlin.compiler.plugin.CliOption
+import org.jetbrains.kotlin.compiler.plugin.CliOptionProcessingException
+import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.config.CompilerConfigurationKey
+
+private const val stubsGenDirName = "stubsgen-dir"
+private const val stubsClassOutputDirName = "stubs-class-dir"
+private const val stubsGenLogEnabledName = "stubsgen-log-enabled"
+
+val stubsGenDirKey: CompilerConfigurationKey<String> =
+    CompilerConfigurationKey.create<String>("plugin $stubsGenDirName")
+
+val stubsClassOutputDirKey: CompilerConfigurationKey<String> =
+    CompilerConfigurationKey.create<String>("plugin $stubsClassOutputDirName")
+
+val stubsGenLogEnabledKey: CompilerConfigurationKey<String> =
+    CompilerConfigurationKey.create<String>("plugin $stubsGenLogEnabledName")
+
+@OptIn(org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi::class)
+class StubsCodegenCommandLineProcessor : CommandLineProcessor {
+  override val pluginId: String
+    get() = COMPILER_PLUGIN_ID
+
+  override val pluginOptions: Collection<AbstractCliOption>
+    get() = listOf(STUBS_GEN_DIR, STUBS_CLASS_OUTPUT_DIR, LOG_ENABLED)
+
+  override fun processOption(
+      option: AbstractCliOption,
+      value: String,
+      configuration: CompilerConfiguration,
+  ) {
+    when (option.optionName) {
+      stubsGenDirName -> configuration.put(stubsGenDirKey, value)
+      stubsClassOutputDirName -> configuration.put(stubsClassOutputDirKey, value)
+      stubsGenLogEnabledName -> configuration.put(stubsGenLogEnabledKey, value)
+      else -> throw CliOptionProcessingException("Unknown option: ${option.optionName}")
+    }
+  }
+
+  companion object {
+    const val COMPILER_PLUGIN_ID: String = "com.facebook.kotlin.compilerplugins.kosabi.stubsgen_k2"
+
+    val STUBS_GEN_DIR: CliOption = CliOption(
+        optionName = stubsGenDirName,
+        valueDescription = "<file-path>",
+        description = "Path to stubs directory.",
+        required = false,
+        allowMultipleOccurrences = false,
+    )
+    val STUBS_CLASS_OUTPUT_DIR: CliOption = CliOption(
+        optionName = stubsClassOutputDirName,
+        valueDescription = "<file-path>",
+        description = "Path to stubs class output directory.",
+        required = false,
+        allowMultipleOccurrences = false,
+    )
+
+    val LOG_ENABLED: CliOption = CliOption(
+        optionName = stubsGenLogEnabledName,
+        valueDescription = "<file-path>",
+        description = "Enable logger to write logs in file. local only",
+        required = false,
+        allowMultipleOccurrences = false,
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenCompilerPluginRegistrar.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenCompilerPluginRegistrar.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenCompilerPluginRegistrar.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.plugin.stubsgen_k2
+
+import com.facebook.kotlin.compilercompat.CompilerPluginRegistrarCompat
+import com.facebook.kotlin.compilerplugins.kosabi.common.Logger
+import java.io.File
+import org.jetbrains.kotlin.cli.jvm.config.jvmClasspathRoots
+import org.jetbrains.kotlin.config.CompilerConfiguration
+import org.jetbrains.kotlin.fir.extensions.FirAnalysisHandlerExtension
+
+@OptIn(org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi::class)
+class StubsCodegenCompilerPluginRegistrar : CompilerPluginRegistrarCompat() {
+
+  override val pluginIdCompat: String = "com.facebook.kotlin.compilerplugins.kosabi.stubsgen"
+
+  override fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration) {
+
+    val stubsGenDir: File = requireNotNull(configuration.get(stubsGenDirKey)?.let { File(it) })
+    val stubsClassOutputDir: File =
+        requireNotNull(configuration.get(stubsClassOutputDirKey)?.let { File(it) })
+
+    // Register logger path if set
+    Logger.userDefinedPath = configuration.get(stubsGenLogEnabledKey)
+    val classPaths = configuration.jvmClasspathRoots
+    Logger.log("[ClassPaths]\n")
+    classPaths.forEach { Logger.log(it.canonicalPath) }
+
+    FirAnalysisHandlerExtension.registerExtension(
+        StubsCodegenK2FirAnalysisHandlerExtension(
+            stubsDumpDir = stubsGenDir,
+            stubsClassOutputDir = stubsClassOutputDir,
+            classPaths = classPaths,
+        ),
+    )
+  }
+
+  override val supportsK2: Boolean
+    get() = true
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenK2FirAnalysisHandlerExtension.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenK2FirAnalysisHandlerExtension.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/StubsCodegenK2FirAnalysisHandlerExtension.kt
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.plugin.stubsgen_k2
+
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators.StubsGenAPI // @oss-enable
+import com.facebook.kotlin.compilercompat.FirAnalysisHandlerExtensionCompat
+// @oss-disable: import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators.meta_only.StubsGenApiImpl
+import java.io.File
+import org.jetbrains.kotlin.cli.common.config.kotlinSourceRoots
+import org.jetbrains.kotlin.cli.jvm.compiler.createSourceFilesFromSourceRoots
+import org.jetbrains.kotlin.com.intellij.openapi.project.Project
+import org.jetbrains.kotlin.config.CompilerConfiguration
+
+@SuppressWarnings("PackageLocationMismatch")
+class StubsCodegenK2FirAnalysisHandlerExtension(
+    private val stubsDumpDir: File,
+    private val stubsClassOutputDir: File,
+    private val classPaths: List<File>,
+) : FirAnalysisHandlerExtensionCompat() {
+
+  override fun isApplicable(configuration: CompilerConfiguration): Boolean {
+    return true
+  }
+
+  override fun doAnalysis(project: Project, configuration: CompilerConfiguration): Boolean {
+    // Use the compiler's canonical source collection, which recognizes Kotlin sources by file
+    // type (including .kts) and reports an error for missing source roots. Mirrors the approach
+    // used by K2JvmAbiFirAnalysisHandlerExtension and replaces the deprecated
+    // KotlinCoreEnvironment-based K1 source lookup.
+    val ktFiles =
+        createSourceFilesFromSourceRoots(configuration, project, configuration.kotlinSourceRoots)
+    StubsGenAPI( // @oss-enable
+    // @oss-disable: StubsGenApiImpl(
+        stubsDumpDir,
+        stubsClassOutputDir,
+        classPaths,
+        // @oss-disable: ktFiles,
+    )
+        .generateStubs(ktFiles, configuration, project)
+
+    throw RuntimeException("Terminating compilation. We're done with Stubgen.")
+
+    return true
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
@@ -0,0 +1,1 @@
+com.facebook.kotlin.compilerplugins.kosabi.stubsgen.plugin.stubsgen_k2.StubsCodegenCommandLineProcessor
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/plugin/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
@@ -0,0 +1,1 @@
+com.facebook.kotlin.compilerplugins.kosabi.stubsgen.plugin.stubsgen_k2.StubsCodegenCompilerPluginRegistrar
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/stub/container/StubsContainer.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/stub/container/StubsContainer.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/stub/container/StubsContainer.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.stub.container
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+
+interface StubsContainer {
+  /**
+   * @return
+   * - null - if [StubsContainer] doesn't contain a relevant stub.
+   * - A found [KStub] otherwise.
+   *
+   * Usage: find("com.facebook", "Outer", "Inner", "InnerInner")
+   */
+  fun find(pkg: String, className: String, innerClassNames: List<String> = emptyList()): KStub?
+
+  /**
+   * Adds a [stub] into [StubsContainer].
+   *
+   * Use [add] to add Outer classes stubs. To add an Inner class, [find] an Outer stub first.
+   *
+   * Methods expects that [StubsContainer] doesn't contain a [KStub] with the same qualifier.
+   */
+  fun add(stub: KStub)
+
+  fun all(): Collection<KStub>
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/stub/container/StubsContainerImpl.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/stub/container/StubsContainerImpl.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/stub/container/StubsContainerImpl.kt
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.stub.container
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.Logger
+import com.facebook.kotlin.compilerplugins.kosabi.common.stub.model.KStub
+
+class StubsContainerImpl : StubsContainer {
+  private val stubs: MutableMap<String, KStub> = mutableMapOf()
+
+  override fun find(pkg: String, className: String, innerClassNames: List<String>): KStub? {
+    var outerStub: KStub = stubs["$pkg:$className"] ?: return null
+    if (innerClassNames.isEmpty()) return outerStub
+
+    // TODO: fix a non-optimal lookup
+    innerClassNames.forEach { innerName ->
+      outerStub = outerStub.innerStubs.find { it.name == innerName } ?: return null
+    }
+
+    return outerStub
+  }
+
+  override fun add(stub: KStub) {
+    if (stubs.contains(stub.fqn)) {
+      Logger.log("  [Error] Stubs container already contains ${stub.fqn}")
+    }
+    Logger.log(
+        """
+      |  [New stub]
+      |    - name: ${stub.fqn}
+      |    - type: ${stub.type.name}
+    """
+            .trimMargin(),
+    )
+    stubs[stub.fqn] = stub
+  }
+
+  override fun all(): Collection<KStub> = stubs.values
+}
+
+private val KStub.fqn: String
+  get() = "$pkg:$name"
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/FTQCollection.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/FTQCollection.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/FTQCollection.kt
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+interface FTQCollection {
+  /**
+   * Returns all FullTypeQualifier objects in this collection.
+   *
+   * @return A collection of FullTypeQualifier objects
+   */
+  fun all(): Collection<String>
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/JavaLangTypes.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/JavaLangTypes.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/JavaLangTypes.kt
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+// https://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html
+object PlainJavaLangTypes : FTQCollection {
+  /**
+   * Returns the simple names of all types in this collection.
+   *
+   * @return A collection of simple type names defined in this class
+   */
+  override fun all(): Collection<String> {
+    return listOf(
+        "Appendable",
+        "AutoCloseable",
+        "CharSequence",
+        "Cloneable",
+        "Comparable",
+        "Iterable",
+        "Readable",
+        "Runnable",
+        "Boolean",
+        "Byte",
+        "Character",
+        "Class",
+        "ClassLoader",
+        "ClassValue",
+        "Compiler",
+        "Double",
+        "Enum",
+        "Float",
+        "InheritableThreadLocal",
+        "Integer",
+        "Long",
+        "Math",
+        "Number",
+        "Object",
+        "Package",
+        "Process",
+        "ProcessBuilder",
+        "Runtime",
+        "RuntimePermission",
+        "SecurityManager",
+        "Short",
+        "StackTraceElement",
+        "StrictMath",
+        "String",
+        "StringBuffer",
+        "StringBuilder",
+        "System",
+        "Thread",
+        "ThreadGroup",
+        "ThreadLocal",
+        "Throwable",
+        "Void",
+        "Deprecated",
+        "FunctionalInterface",
+        "Override",
+        "SafeVarargs",
+        "SuppressWarnings",
+        "ArithmeticException",
+        "ArrayIndexOutOfBoundsException",
+        "ArrayStoreException",
+        "ClassCastException",
+        "ClassNotFoundException",
+        "CloneNotSupportedException",
+        "EnumConstantNotPresentException",
+        "Exception",
+        "IllegalAccessException",
+        "IllegalArgumentException",
+        "IllegalMonitorStateException",
+        "IllegalStateException",
+        "IllegalThreadStateException",
+        "IndexOutOfBoundsException",
+        "InstantiationException",
+        "InterruptedException",
+        "NegativeArraySizeException",
+        "NoSuchFieldException",
+        "NoSuchMethodException",
+        "NullPointerException",
+        "NumberFormatException",
+        "ReflectiveOperationException",
+        "RuntimeException",
+        "SecurityException",
+        "StringIndexOutOfBoundsException",
+        "TypeNotPresentException",
+        "UnsupportedOperationException",
+        "AbstractMethodError",
+        "AssertionError",
+        "BootstrapMethodError",
+        "ClassCircularityError",
+        "ClassFormatError",
+        "Error",
+        "ExceptionInInitializerError",
+        "IllegalAccessError",
+        "IncompatibleClassChangeError",
+        "InstantiationError",
+        "InternalError",
+        "LinkageError",
+        "NoClassDefFoundError",
+        "NoSuchFieldError",
+        "NoSuchMethodError",
+        "OutOfMemoryError",
+        "StackOverflowError",
+        "ThreadDeath",
+        "UnknownError",
+        "UnsatisfiedLinkError",
+        "UnsupportedClassVersionError",
+        "VerifyError",
+        "VirtualMachineError",
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTBuiltInTypes.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTBuiltInTypes.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTBuiltInTypes.kt
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+// created by parsing types contained in kotlin/core/builtins
+// https://github.com/JetBrains/kotlin/tree/master/core/builtins
+object PlainKTBuiltInTypes : FTQCollection {
+  /**
+   * Returns the simple names of all types in this collection.
+   *
+   * @return A collection of simple type names defined in this class
+   */
+  override fun all(): Collection<String> {
+    return listOf(
+        "Comparable",
+        "CharSequence",
+        "Iterator",
+        "MutableIterator",
+        "ListIterator",
+        "MutableListIterator",
+        "Iterable",
+        "MutableIterable",
+        "Collection",
+        "MutableCollection",
+        "List",
+        "MutableList",
+        "Set",
+        "MutableSet",
+        "Map",
+        "MutableMap",
+        "String",
+        "Enum",
+        "Nothing",
+        "Array",
+        "Any",
+        "Throwable",
+        "ByteArray",
+        "CharArray",
+        "ShortArray",
+        "IntArray",
+        "LongArray",
+        "FloatArray",
+        "DoubleArray",
+        "BooleanArray",
+        "Annotation",
+        "Boolean",
+        "Byte",
+        "Short",
+        "Int",
+        "Long",
+        "Float",
+        "Double",
+        "Number",
+        "Char",
+        "Unit",
+        "Function",
+        "AnnotationTarget",
+        "AnnotationRetention",
+        "Target",
+        "Retention",
+        "Repeatable",
+        "MustBeDocumented",
+        "Deprecated",
+        "DeprecatedSinceKotlin",
+        "ReplaceWith",
+        "DeprecationLevel",
+        "ExtensionFunctionType",
+        "ContextFunctionTypeParams",
+        "ParameterName",
+        "Suppress",
+        "UnsafeVariance",
+        "SinceKotlin",
+        "DslMarker",
+        "PublishedApi",
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTJavaTypeAlias.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTJavaTypeAlias.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTJavaTypeAlias.kt
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+// Kotlin type alias that's not from java.lang
+// https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/jvm/runtime/kotlin/TypeAliases.kt
+object PlainKTJavaTypeAlias : FTQCollection {
+  /**
+   * Returns all FullTypeQualifier objects in this collection.
+   *
+   * @return A collection of all FullTypeQualifier vals defined in this class
+   */
+  override fun all(): Collection<String> {
+    return listOf(
+        "NoSuchElementException",
+        "ConcurrentModificationException",
+        "Comparator",
+        "RandomAccess",
+        "ArrayList",
+        "LinkedHashMap",
+        "HashMap",
+        "LinkedHashSet",
+        "HashSet",
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTStdlibTypes.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTStdlibTypes.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KTStdlibTypes.kt
@@ -0,0 +1,568 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+// created by parsing types contained in kotlin/libraries/stdlib,
+// https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
+
+object PlainKTStdlibTypes : FTQCollection {
+  /**
+   * Returns the simple names of all types in this collection.
+   *
+   * @return A collection of simple type names defined in this class
+   */
+  override fun all(): Collection<String> {
+    return listOf(
+        "EnumEntries",
+        "EnumEntriesList",
+        "Iterable",
+        "MutableIterable",
+        "Collection",
+        "MutableCollection",
+        "List",
+        "MutableList",
+        "Set",
+        "MutableSet",
+        "Map",
+        "MutableMap",
+        "PlatformThreadLocalRandom",
+        "PathWalkOption",
+        "ExperimentalPathApi",
+        "OnErrorResult",
+        "CopyActionResult",
+        "FileVisitorBuilder",
+        "FileVisitorBuilderImpl",
+        "FileVisitorImpl",
+        "CopyActionContext",
+        "PathRelativizer",
+        "DefaultCopyActionContext",
+        "ExceptionsCollector",
+        "IllegalFileNameException",
+        "PathTreeWalk",
+        "PathNode",
+        "LinkFollowing",
+        "DirectoryEntriesReader",
+        "UByteArray",
+        "ULongRange",
+        "ULongProgression",
+        "ULongProgressionIterator",
+        "UInt",
+        "UIntRange",
+        "UIntProgression",
+        "UIntProgressionIterator",
+        "ExperimentalUnsignedTypes",
+        "UByte",
+        "UShort",
+        "ULongArray",
+        "ULong",
+        "UIntArray",
+        "UShortArray",
+        "Ctor",
+        "JsArrayView",
+        "JsSetView",
+        "JsMapView",
+        "JsObject",
+        "DefaultConstructorMarker",
+        "JsIntrinsic",
+        "Metadata",
+        "FunctionAdapter",
+        "IrLinkageError",
+        "DoNotIntrinsify",
+        "JsFun",
+        "JsGenerator",
+        "JsImplicitExport",
+        "ArrayBuffer",
+        "Float64Array",
+        "Float32Array",
+        "Int32Array",
+        "String",
+        "Enum",
+        "Throwable",
+        "ByteArray",
+        "CharArray",
+        "ShortArray",
+        "IntArray",
+        "LongArray",
+        "FloatArray",
+        "DoubleArray",
+        "BooleanArray",
+        "Boolean",
+        "Byte",
+        "Short",
+        "Int",
+        "Long",
+        "Float",
+        "Double",
+        "Char",
+        "Letter",
+        "Digit",
+        "OtherLowercase",
+        "Category",
+        "Console",
+        "Volatile",
+        "Synchronized",
+        "Error",
+        "Exception",
+        "RuntimeException",
+        "IllegalArgumentException",
+        "IllegalStateException",
+        "IndexOutOfBoundsException",
+        "ConcurrentModificationException",
+        "UnsupportedOperationException",
+        "NumberFormatException",
+        "NullPointerException",
+        "ClassCastException",
+        "AssertionError",
+        "NoSuchElementException",
+        "ArithmeticException",
+        "NoWhenBranchMatchedException",
+        "UninitializedPropertyAccessException",
+        "JsPolyfill",
+        "RegExp",
+        "RegExpMatch",
+        "JsMath",
+        "ExceptionTraceBuilder",
+        "Date",
+        "Json",
+        "KType",
+        "KFunction",
+        "ExperimentalAssociatedObjects",
+        "AssociatedObjectKey",
+        "KProperty",
+        "KMutableProperty",
+        "KProperty0",
+        "KMutableProperty0",
+        "KProperty1",
+        "KMutableProperty1",
+        "KProperty2",
+        "KMutableProperty2",
+        "KCallable",
+        "KClass",
+        "JsClass",
+        "EnumEntriesSerializationProxy",
+        "DefaultTimeSource",
+        "MonotonicTimeSource",
+        "Process",
+        "HrTimeSource",
+        "PerformanceTimeSource",
+        "DateNowTimeSource",
+        "GlobalPerformance",
+        "Performance",
+        "DurationUnit",
+        "Comparator",
+        "BaseOutput",
+        "NodeJsOutput",
+        "OutputToConsoleLog",
+        "BufferedOutput",
+        "BufferedOutputToConsoleLog",
+        "Promise",
+        "JsReadonlyArray",
+        "JsArray",
+        "JsReadonlySet",
+        "JsSet",
+        "JsReadonlyMap",
+        "JsMap",
+        "CancellationException",
+        "JsIterationStep",
+        "JsIterator",
+        "GeneratorCoroutineImpl",
+        "SafeContinuation",
+        "CoroutineImpl",
+        "CompletedContinuation",
+        "InterceptedCoroutine",
+        "RegexOption",
+        "MatchGroup",
+        "Regex",
+        "Appendable",
+        "CharacterCodingException",
+        "StringBuilder",
+        "CharCategory",
+        "RandomAccess",
+        "HashSet",
+        "AbstractMutableMap",
+        "HashMapKeysDefault",
+        "HashMapValuesDefault",
+        "LinkedHashMap",
+        "AbstractMutableSet",
+        "HashMap",
+        "LinkedHashSet",
+        "JsRawArray",
+        "InternalStringMap",
+        "InternalHashMap",
+        "AbstractMutableList",
+        "ArrayList",
+        "AbstractMutableCollection",
+        "InternalStringLinkedMap",
+        "InternalMap",
+        "HashMapKeys",
+        "HashMapValues",
+        "HashMapEntrySetBase",
+        "HashMapEntrySet",
+        "AutoCloseable",
+        "ConstrainedOnceSequence",
+        "Serializable",
+        "JsName",
+        "JsFileName",
+        "JsModule",
+        "JsNonModule",
+        "JsQualifier",
+        "JsExport",
+        "EagerInitialization",
+        "JsExternalInheritorsOnly",
+        "JsExternalArgument",
+        "JsStatic",
+        "AtomicReference",
+        "Dynamic",
+        "JsAny",
+        "JsString",
+        "JsReference",
+        "JsBigInt",
+        "JsException",
+        "JsBoolean",
+        "JsNumber",
+        "Nothing",
+        "Array",
+        "Any",
+        "WasiErrorCode",
+        "WasiError",
+        "OutOfMemoryError",
+        "WasmImport",
+        "WasmExport",
+        "MemoryAllocator",
+        "ScopedMemoryAllocator",
+        "UnsafeWasmMemoryApi",
+        "Pointer",
+        "BitSet",
+        "ObsoleteNativeApi",
+        "TypeCastException",
+        "JvmOverloads",
+        "JvmStatic",
+        "JvmName",
+        "JvmMultifileClass",
+        "JvmPackageName",
+        "JvmSynthetic",
+        "Throws",
+        "ImplicitlyActualizedByJvmDeclaration",
+        "JvmField",
+        "JvmSuppressWildcards",
+        "JvmWildcard",
+        "JvmInline",
+        "JvmRecord",
+        "Transient",
+        "Strictfp",
+        "JvmSerializableLambda",
+        "KotlinReflectionNotSupportedError",
+        "FunctionN",
+        "Function0",
+        "Function1",
+        "Function2",
+        "Function3",
+        "Function4",
+        "Function5",
+        "Function6",
+        "Function7",
+        "Function8",
+        "Function9",
+        "Function10",
+        "Function11",
+        "Function12",
+        "Function13",
+        "Function14",
+        "Function15",
+        "Function16",
+        "Function17",
+        "Function18",
+        "Function19",
+        "Function20",
+        "Function21",
+        "Function22",
+        "PurelyImplements",
+        "KotlinNullPointerException",
+        "Constants",
+        "SynchronizedLazyImpl",
+        "SafePublicationLazyImpl",
+        "KParameter",
+        "KAnnotatedElement",
+        "KVisibility",
+        "KDeclarationContainer",
+        "TypeImpl",
+        "TypeVariableImpl",
+        "GenericArrayTypeImpl",
+        "WildcardTypeImpl",
+        "ParameterizedTypeImpl",
+        "FileSystemException",
+        "FileAlreadyExistsException",
+        "AccessDeniedException",
+        "NoSuchFileException",
+        "LinesSequence",
+        "DecodeInputStream",
+        "EncodeOutputStream",
+        "OnErrorAction",
+        "TerminateException",
+        "FileWalkDirection",
+        "FileTreeWalk",
+        "FilePathComponents",
+        "LineReader",
+        "ExposingBufferByteArrayOutputStream",
+        "JvmDefault",
+        "JvmDefaultWithoutCompatibility",
+        "JvmDefaultWithCompatibility",
+        "CharDirectionality",
+        "FlagEnum",
+        "MatcherMatchResult",
+        "SystemProperties",
+        "Charsets",
+        "ScreenFloatValueRegEx",
+        "AbstractPlatformRandom",
+        "FallbackThreadLocalRandom",
+        "PlatformRandom",
+        "KotlinRandom",
+        "ListBuilder",
+        "SerializedCollection",
+        "MapBuilder",
+        "MapBuilderKeys",
+        "MapBuilderValues",
+        "AbstractMapBuilderEntrySet",
+        "MapBuilderEntries",
+        "SerializedMap",
+        "SetBuilder",
+        "ExperimentalJsFileName",
+        "ExperimentalJsExport",
+        "ExperimentalJsStatic",
+        "ExperimentalJsReflectionCreateInstance",
+        "ExperimentalJsCollectionsApi",
+        "ReadAfterEOFException",
+        "KotlinNothingValueException",
+        "ObsoleteWorkersApi",
+        "FreezingIsDeprecated",
+        "SpecialToken",
+        "Lexer",
+        "Quantifier",
+        "NamedGroup",
+        "UnicodeCategory",
+        "UnicodeCategoryScope",
+        "AbstractCharClass",
+        "JointSet",
+        "CharSet",
+        "SimpleSet",
+        "AbstractSet",
+        "FixedLengthQuantifierSet",
+        "ReluctantFixedLengthQuantifierSet",
+        "EmptySet",
+        "LowSurrogateCharSet",
+        "HighSurrogateCharSet",
+        "ReluctantLeafQuantifierSet",
+        "PossessiveFixedLengthQuantifierSet",
+        "RangeSet",
+        "PossessiveGroupQuantifierSet",
+        "SequenceSet",
+        "FSet",
+        "FinalSet",
+        "NonCapFSet",
+        "AheadFSet",
+        "BehindFSet",
+        "AtomicFSet",
+        "SingleSet",
+        "WordBoundarySet",
+        "DecomposedCharSet",
+        "LookAroundSet",
+        "HangulDecomposedCharSet",
+        "QuantifierSet",
+        "LeafSet",
+        "DotQuantifierSet",
+        "PositiveLookAheadSet",
+        "NegativeLookAheadSet",
+        "NonCapturingJointSet",
+        "PositiveLookBehindSet",
+        "NegativeLookBehindSet",
+        "LeafQuantifierSet",
+        "EOLSet",
+        "UnifiedQuantifierSet",
+        "PreviousMatchSet",
+        "DotSet",
+        "AtomicJointSet",
+        "EOISet",
+        "PossessiveLeafQuantifierSet",
+        "SupplementaryRangeSet",
+        "CompositeRangeSet",
+        "SOLSet",
+        "GroupQuantifierSet",
+        "SurrogateRangeSet",
+        "BackReferenceSet",
+        "ReluctantGroupQuantifierSet",
+        "MatchResultImpl",
+        "CharClass",
+        "Pattern",
+        "AbstractLineTerminator",
+        "PatternSyntaxException",
+        "Iterator",
+        "MutableIterator",
+        "ListIterator",
+        "MutableListIterator",
+        "CharProgression",
+        "IntProgression",
+        "LongProgression",
+        "CharRange",
+        "IntRange",
+        "LongRange",
+        "ComparableRange",
+        "ComparableOpenEndRange",
+        "ClosedFloatingPointRange",
+        "ClosedDoubleRange",
+        "OpenEndDoubleRange",
+        "ClosedFloatRange",
+        "OpenEndFloatRange",
+        "CharProgressionIterator",
+        "IntProgressionIterator",
+        "LongProgressionIterator",
+        "ClosedRange",
+        "OpenEndRange",
+        "ExperimentalTypeInference",
+        "ExperimentalObjCRefinement",
+        "ExperimentalObjCName",
+        "ExperimentalNativeApi",
+        "ReversedComparator",
+        "NaturalOrderComparator",
+        "ReverseOrderComparator",
+        "DeepRecursiveFunction",
+        "DeepRecursiveScope",
+        "DeepRecursiveScopeImpl",
+        "Result",
+        "Lazy",
+        "LazyThreadSafetyMode",
+        "UnsafeLazyImpl",
+        "InitializedLazyImpl",
+        "Pair",
+        "Triple",
+        "NotImplementedError",
+        "KotlinVersion",
+        "KotlinVersionCurrentValue",
+        "Effect",
+        "ConditionalEffect",
+        "SimpleEffect",
+        "Returns",
+        "ReturnsNotNull",
+        "CallsInPlace",
+        "ExperimentalContracts",
+        "ContractBuilder",
+        "InvocationKind",
+        "KTypeProjection",
+        "KClassifier",
+        "KTypeParameter",
+        "KVariance",
+        "Base64",
+        "ExperimentalEncodingApi",
+        "TimedValue",
+        "AbstractLongTimeSource",
+        "AbstractDoubleTimeSource",
+        "TestTimeSource",
+        "TimeSource",
+        "ValueTimeMarkReading",
+        "TimeMark",
+        "ComparableTimeMark",
+        "AdjustedTimeMark",
+        "ExperimentalTime",
+        "Duration",
+        "WasExperimental",
+        "BuilderInference",
+        "OverloadResolutionByLambdaReturnType",
+        "ThreadLocal",
+        "SharedImmutable",
+        "CName",
+        "ObjCName",
+        "HidesFromObjC",
+        "HiddenFromObjC",
+        "RefinesInSwift",
+        "ShouldRefineInSwift",
+        "ExperimentalMultiplatform",
+        "OptionalExpectation",
+        "RequiresOptIn",
+        "OptIn",
+        "ExperimentalSubclassOptIn",
+        "SubclassOptInRequired",
+        "ConsistentCopyVisibility",
+        "ExposedCopyVisibility",
+        "ExperimentalStdlibApi",
+        "Delegates",
+        "NotNullVar",
+        "ObservableProperty",
+        "ReadOnlyProperty",
+        "ReadWriteProperty",
+        "PropertyDelegateProvider",
+        "ContinuationInterceptor",
+        "AbstractCoroutineContextElement",
+        "AbstractCoroutineContextKey",
+        "EmptyCoroutineContext",
+        "CombinedContext",
+        "CoroutineSingletons",
+        "CoroutineContext",
+        "Continuation",
+        "RestrictsSuspension",
+        "DelimitedRangesSequence",
+        "MatchGroupCollection",
+        "MatchNamedGroupCollection",
+        "MatchResult",
+        "HexFormat",
+        "Typography",
+        "XorWowRandom",
+        "Random",
+        "IndexingIterator",
+        "AbstractList",
+        "EmptyIterator",
+        "EmptyList",
+        "ArrayAsCollection",
+        "AbstractMap",
+        "State",
+        "AbstractIterator",
+        "AbstractCollection",
+        "IndexingIterable",
+        "ReversedListReadOnly",
+        "ReversedList",
+        "ByteIterator",
+        "CharIterator",
+        "ShortIterator",
+        "IntIterator",
+        "LongIterator",
+        "FloatIterator",
+        "DoubleIterator",
+        "BooleanIterator",
+        "IndexedValue",
+        "EmptySequence",
+        "FilteringSequence",
+        "TransformingSequence",
+        "TransformingIndexedSequence",
+        "IndexingSequence",
+        "MergingSequence",
+        "FlatteningSequence",
+        "DropTakeSequence",
+        "SubSequence",
+        "TakeSequence",
+        "TakeWhileSequence",
+        "DropSequence",
+        "DropWhileSequence",
+        "DistinctSequence",
+        "DistinctIterator",
+        "GeneratorSequence",
+        "SequenceScope",
+        "SequenceBuilderIterator",
+        "EmptyMap",
+        "MovingSubList",
+        "RingBuffer",
+        "MapWithDefault",
+        "MutableMapWithDefault",
+        "MapWithDefaultImpl",
+        "MutableMapWithDefaultImpl",
+        "ArrayDeque",
+        "Grouping",
+        "Sequence",
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtClassLiteralExpressionExt.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtClassLiteralExpressionExt.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtClassLiteralExpressionExt.kt
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators.GenerationContext
+import org.jetbrains.kotlin.com.intellij.psi.PsiElement
+import org.jetbrains.kotlin.psi.KtClassLiteralExpression
+import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
+import org.jetbrains.kotlin.psi.KtExpression
+import org.jetbrains.kotlin.psi.KtNameReferenceExpression
+import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
+
+/**
+ * Class reference is a Kotlin reflection, it is presented in KtClassLiteralExpression
+ * KtClassLiteralExpression could be:
+ * - SomeClass::class
+ * - SomeClass.SomeName::class
+ * - java.io.IOException::class
+ */
+object ClassReferenceUtil {
+
+  fun collectMultiSegmentQualifiers(context: GenerationContext): List<List<String>> {
+    return context.projectFiles
+        .flatMap { it.collectDescendantsOfType<KtClassLiteralExpression>() }
+        .mapNotNull { it.lhs }
+        .map { it.calculateQualifiers() }
+        .filter { it.isNotEmpty() }
+        .filter { FullTypeQualifier(it)?.isTopLevelDeclaration() == false }
+        .distinct()
+        .toList()
+  }
+}
+
+/**
+ * This function decodes the KtDotQualifiedExpression and visit its child accordingly to get the
+ * qualifiers.
+ *
+ * KtDotQualifiedExpression: Outer.A.SomeException
+ * - selector: SomeException
+ * - receiver: Outer.A (KtDotQualifiedExpression)
+ * - reversedQualifiers: ["SomeException"]
+ *
+ * KtDotQualifiedExpression: Outer.A
+ * - selector: A
+ * - receiver: Outer
+ * - ["SomeException", "A", "Outer"]
+ *
+ * result.reversed(): ["Outer", "A", "SomeException"]
+ */
+private fun PsiElement.calculateQualifiers(): List<String> {
+  val reversedQualifiers: MutableList<String> = mutableListOf()
+  if (this is KtDotQualifiedExpression) {
+    var dotQualifiedVisitor: KtDotQualifiedExpression? = this
+    while (dotQualifiedVisitor != null) {
+      dotQualifiedVisitor.selectorExpression?.getReferencedName()?.let {
+        reversedQualifiers.add(it)
+      }
+      val receiver = dotQualifiedVisitor.receiverExpression
+      dotQualifiedVisitor =
+          if (receiver is KtDotQualifiedExpression) {
+            receiver
+          } else {
+            receiver.getReferencedName()?.let { reversedQualifiers.add(it) }
+            null
+          }
+    }
+  }
+  return reversedQualifiers.reversed()
+}
+
+private fun KtExpression.getReferencedName(): String? =
+    if (this is KtNameReferenceExpression) {
+      getReferencedName()
+    } else {
+      null
+    }
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtFileExt.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtFileExt.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtFileExt.kt
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import org.jetbrains.kotlin.psi.KtClassBody
+import org.jetbrains.kotlin.psi.KtClassOrObject
+import org.jetbrains.kotlin.psi.KtFile
+import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
+import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
+
+fun KtFile.declaredTypes(): List<FullTypeQualifier> {
+  val pkg = packageFqName.pathSegments().map { it.asString() }
+  return getChildrenOfType<KtClassOrObject>().flatMap { it.declaredTypes(pkg) }
+}
+
+fun KtClassOrObject.declaredTypes(prefix: List<String>): List<FullTypeQualifier> {
+  // TODO: log the name == null cases (likely anonymous classes)
+  val theName = name ?: return emptyList()
+  val inners = getChildOfType<KtClassBody>()?.getChildrenOfType<KtClassOrObject>() ?: emptyArray()
+  val qualifier = FullTypeQualifier(prefix + listOf(theName))
+  return listOf(qualifier) + inners.flatMap { it.declaredTypes(qualifier.segments) }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtImportDirectiveExt.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtImportDirectiveExt.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtImportDirectiveExt.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+import com.facebook.kotlin.compilerplugins.kosabi.common.FullTypeQualifier
+import java.lang.RuntimeException
+import org.jetbrains.kotlin.psi.KtImportDirective
+
+fun KtImportDirective.toImportedClass(): FullTypeQualifier {
+  // TODO: support multi-import cases
+  // "import a.b.c.*
+
+  // TODO: verify all cases where `importPath == null`
+  // every case should be a separate `when` statement branch
+  val importFq =
+      importPath?.fqName
+          ?: throw RuntimeException("For some reason importPath is null for[${this.text}].")
+
+  val segments = importFq.pathSegments().map { it.asString() }
+  return FullTypeQualifier(segments)
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtUserTypeExt.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtUserTypeExt.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/KtUserTypeExt.kt
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+import org.jetbrains.kotlin.psi.KtUserType
+
+/**
+ * For a used type
+ *
+ * KtType(Outer.Mid.Inner) -> List(Outer, Mid, Inner)
+ */
+fun KtUserType.calculateQualifierList(): List<String> {
+  val outer: MutableList<String> = mutableListOf()
+
+  var type: KtUserType? = this
+  while (type != null) {
+    type.referencedName?.let { outer += it }
+    type = type.qualifier
+  }
+
+  return outer.reversed()
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/PrimitiveTypeUtil.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/PrimitiveTypeUtil.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/PrimitiveTypeUtil.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+import org.jetbrains.kotlin.com.intellij.psi.PsiElement
+import org.jetbrains.kotlin.lexer.KtTokens
+import org.jetbrains.kotlin.psi.KtConstantExpression
+import org.jetbrains.kotlin.psi.KtPrefixExpression
+import org.jetbrains.kotlin.psi.KtStringTemplateExpression
+import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
+import org.jetbrains.kotlin.psi.psiUtil.isNull
+
+// Primitive Data Types:
+// - Int, Short, Long, Float...
+// - Char, String
+// - Boolean
+fun PsiElement.isPrimitiveDataType(): Boolean =
+    isConstantLiteral() || isStringLiteral() || isNegativeConstantLiteral()
+
+fun PsiElement.isConstantLiteral(): Boolean = this is KtConstantExpression
+
+fun PsiElement.isStringLiteral(): Boolean = this is KtStringTemplateExpression
+
+fun PsiElement.isNegativeConstantLiteral(): Boolean =
+    if (this is KtPrefixExpression) {
+      operationToken == KtTokens.MINUS && getChildOfType<KtConstantExpression>()?.isNull() == false
+    } else {
+      false
+    }
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/UserTypeUtil.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/UserTypeUtil.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/kosabi/stubsgen/util/UserTypeUtil.kt
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.kotlin.compilerplugins.kosabi.stubsgen.util
+
+import com.facebook.kotlin.compilerplugins.kosabi.stubsgen.generators.GenerationContext
+import org.jetbrains.kotlin.psi.KtNullableType
+import org.jetbrains.kotlin.psi.KtTypeReference
+import org.jetbrains.kotlin.psi.KtUserType
+import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
+import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
+
+object UserTypeUtil {
+  /**
+   * Multi-segment qualifier:
+   * - com.company.project.Type.Inner
+   * - com.Type
+   * - Type.Inner
+   *
+   * Single segment qualifiers:
+   * - Type
+   */
+  fun collectMultiSegmentQualifiers(context: GenerationContext): List<List<String>> {
+    return collectUserTypeQualifiers(context).filter { it.size >= 2 }
+  }
+
+  private fun collectUserTypeQualifiers(context: GenerationContext): List<List<String>> {
+    return context.projectFiles
+        .flatMap { it.collectDescendantsOfType<KtTypeReference>() }
+        .mapNotNull { it.getUserType() }
+        .map { it.calculateQualifierList() }
+        .distinct()
+  }
+
+  /**
+   * When type is non-nullable: KtTypeReference \- KtUserType
+   *
+   * When type is nullable: KtTypeReference \- KtNullableType \- KtUserType
+   */
+  private fun KtTypeReference.getUserType(): KtUserType? {
+    val nullableTypeWrapper = getChildOfType<KtNullableType>()
+    return (nullableTypeWrapper ?: this).getChildOfType<KtUserType>()
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses/BUCK
@@ -0,0 +1,16 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "usedclasses",
+    srcs = glob(["**/*.kt"]),
+    labels = ["codegen_rule"],
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses:usedclasses",
+    ],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses/ClassUsageMerger.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses/ClassUsageMerger.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/compilerplugins/usedclasses/ClassUsageMerger.kt
@@ -0,0 +1,41 @@
+@file:JvmName("ClassUsageMerger")
+
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under both the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree and the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree.
+ */
+
+package com.facebook.buck.jvm.kotlin.compilerplugins.usedclasses
+
+import java.nio.file.Path
+
+fun mergeClassUsageMaps(
+    prevClassUsages: Map<Path, Set<Path>>,
+    currentClassUsages: Map<Path, Set<Path>>,
+): Map<Path, Set<Path>> {
+  if (prevClassUsages.isEmpty()) {
+    return currentClassUsages
+  }
+  if (currentClassUsages.isEmpty()) {
+    return prevClassUsages
+  }
+
+  val mergedClassUsageMap: MutableMap<Path, MutableSet<Path>> =
+      HashMap(prevClassUsages.mapValues { (_, set) -> set.toMutableSet() })
+
+  for ((jarPath, classPathMap) in currentClassUsages) {
+    if (!mergedClassUsageMap.containsKey(jarPath)) {
+      mergedClassUsageMap[jarPath] = classPathMap.toMutableSet()
+      continue
+    }
+
+    val mergedClassPathEntry = mergedClassUsageMap.getValue(jarPath)
+    mergedClassPathEntry.addAll(classPathMap)
+  }
+
+  return mergedClassUsageMap
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "kotlinc",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/build/execution/context:context",
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/core:core",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics:analytics",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental:incremental",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/util:util",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/Kotlinc.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/Kotlinc.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/Kotlinc.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.kotlinc;
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.core.BuildTargetValue;
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDLoggingContext;
+import com.facebook.buck.jvm.kotlin.kotlinc.incremental.KotlincMode;
+import com.facebook.buck.jvm.kotlin.util.KotlinUnarchiverKt;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSortedSet;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Optional;
+
+/** Interface for a kotlin compiler. */
+public interface Kotlinc {
+
+  int buildWithClasspath(
+      IsolatedExecutionContext context,
+      BuildTargetValue invokingRule,
+      ImmutableList<String> options,
+      ImmutableList<AbsPath> kotlinHomeLibraries,
+      ImmutableSortedSet<RelPath> kotlinSourceFilePaths,
+      Path pathToSrcsList,
+      Optional<Path> workingDirectory,
+      AbsPath ruleCellRoot,
+      KotlincMode mode,
+      KotlinCDLoggingContext kotlinCDLoggingContext)
+      throws InterruptedException;
+
+  String getDescription(
+      ImmutableList<String> options,
+      ImmutableSortedSet<RelPath> kotlinSourceFilePaths,
+      Path pathToSrcsList);
+
+  String getShortName();
+
+  default ImmutableList<Path> getExpandedSourcePaths(
+      AbsPath ruleCellRoot,
+      ImmutableSet<RelPath> kotlinSourceFilePaths,
+      Optional<Path> workingDirectory)
+      throws IOException {
+
+    return KotlinUnarchiverKt.getExpandedSourcePaths(
+        ruleCellRoot, kotlinSourceFilePaths, workingDirectory);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/BUCK
@@ -0,0 +1,20 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "incremental",
+    srcs = glob(["**/*.kt"]),
+    extra_kotlinc_arguments = ["-Xopt-in=kotlin.ExperimentalStdlibApi"],
+    labels = ["codegen_rule"],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/ClasspathChanges.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/ClasspathChanges.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/ClasspathChanges.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.kotlinc.incremental
+
+import java.io.File
+
+/**
+ * Changes to the classpath of the KotlinC action, or information to compute them later by the
+ * Kotlin incremental compiler
+ */
+sealed interface ClasspathChanges {
+
+  val classpathSnapshotFiles: List<File>
+
+  /**
+   * Classpath has changes (additions, modifications, or removals). The Kotlin incremental compiler
+   * computes affected sources.
+   */
+  data class ToBeComputedByIncrementalCompiler(override val classpathSnapshotFiles: List<File>) :
+      ClasspathChanges
+
+  data class NoChanges(override val classpathSnapshotFiles: List<File>) : ClasspathChanges
+
+  @Deprecated("For testing only, will be removed.")
+  data object Unknown : ClasspathChanges {
+    override val classpathSnapshotFiles: List<File> = emptyList()
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/KotlinSourceChanges.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/KotlinSourceChanges.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/KotlinSourceChanges.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.kotlinc.incremental
+
+import com.facebook.buck.core.filesystems.AbsPath
+
+/** A hierarchy representing source files changes for incremental compilation */
+sealed interface KotlinSourceChanges {
+  /**
+   * A marker object stating that the API consumer is not capable of calculating source file
+   * changes.
+   */
+  data object ToBeCalculated : KotlinSourceChanges
+
+  /**
+   * A class containing [modifiedFiles] and [removedFiles] calculated from source file changes by
+   * the API consumer.
+   */
+  data class Known(val addedAndModifiedFiles: List<AbsPath>, val removedFiles: List<AbsPath>) :
+      KotlinSourceChanges
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/KotlincMode.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/KotlincMode.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/KotlincMode.kt
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.kotlinc.incremental
+
+import com.facebook.buck.core.filesystems.AbsPath
+
+sealed interface KotlincMode {
+
+  data object NonIncremental : KotlincMode
+
+  data class Incremental(
+      val rootProjectDir: AbsPath,
+      val buildDir: AbsPath,
+      val kotlicWorkingDir: AbsPath,
+      val kotlinSourceChanges: KotlinSourceChanges,
+      val classpathChanges: ClasspathChanges,
+      val kotlinClassUsageFile: AbsPath?,
+      val rebuildReason: RebuildReason?,
+  ) : KotlincMode
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/RebuildReason.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/RebuildReason.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/kotlinc/incremental/RebuildReason.kt
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.kotlinc.incremental
+
+enum class RebuildReason(val message: String) {
+  NO_LAST_BUILD_CONFIGURATION("Last build configuration not found"),
+  BUILD_CONFIGURATION_CHANGED("Build configuration has been changed"),
+  NO_LAST_DEP_FILE("dep-file.txt not found"),
+  NO_LAST_USED_JARS("used-jars.json not found"),
+  NO_JVM_ABI_WORKING_DIR("jvm_abi_gen_working_dir not found"),
+  KOTLIN_COMPILER_PLUGIN_CHANGED("Kotlin compiler plugin has been changed"),
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/BUCK
@@ -0,0 +1,33 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+# KSP2 is not available on pre Kotlin 2.0 versions, which are still used by AOSP builds
+NO_OP_FILES = ["Ksp2StepNoOp.kt"]
+
+buck_kotlin_library(
+    name = "ksp",
+    srcs = glob(["**/*.kt"]),
+    extra_kotlinc_arguments = ["-Xopt-in=kotlin.ExperimentalStdlibApi"],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/command/kotlin:language-version",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/core:core",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/analytics:analytics",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental:incremental",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps/common:common",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:kotlinx-coroutines-core-jvm",
+        "prelude//toolchains/android/third-party:symbol-processing-aa-embeddable",
+        "prelude//toolchains/android/third-party:symbol-processing-api",
+        "prelude//toolchains/android/third-party:symbol-processing-common-deps",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/BuckKsp2Logger.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/BuckKsp2Logger.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/BuckKsp2Logger.kt
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.ksp
+
+import com.facebook.buck.core.util.log.Logger
+import com.google.devtools.ksp.processing.KSPLogger
+import com.google.devtools.ksp.symbol.FileLocation
+import com.google.devtools.ksp.symbol.KSNode
+import com.google.devtools.ksp.symbol.NonExistLocation
+import java.io.PrintStream
+import java.util.logging.Level
+
+/**
+ * A logger for KSP that logs to Buck's logging system. Similar to [KotlincStep]'s
+ * [BuckKotlinLogger], and KSP1's [MessageCollectorBasedKSPLogger]
+ */
+class BuckKsp2Logger(private val stdErr: PrintStream) : KSPLogger {
+
+  override fun logging(message: String, symbol: KSNode?) {
+    if (!LOG.isDebugEnabled) return
+    LOG.debug(convertMessage(message, symbol))
+  }
+
+  override fun info(message: String, symbol: KSNode?) {
+    if (!LOG.isLoggable(Level.INFO)) return
+    LOG.info(convertMessage(message, symbol))
+  }
+
+  override fun warn(message: String, symbol: KSNode?) {
+    if (!LOG.isLoggable(Level.WARNING)) return
+    stdErr.println(convertMessage(message, symbol))
+  }
+
+  override fun error(message: String, symbol: KSNode?) {
+    if (!LOG.isLoggable(Level.SEVERE)) return
+    stdErr.println(convertMessage(message, symbol))
+  }
+
+  override fun exception(e: Throwable) {
+    if (!LOG.isLoggable(Level.SEVERE)) return
+    stdErr.println("$LOGGING_PREFIX${e.stackTraceToString()}")
+  }
+
+  private fun convertMessage(message: String, symbol: KSNode?): String =
+      when (val location = symbol?.location) {
+        is FileLocation -> "$LOGGING_PREFIX${location.filePath}:${location.lineNumber}: $message"
+        is NonExistLocation,
+        null -> "$LOGGING_PREFIX$message"
+      }
+
+  companion object {
+    private val LOG: Logger = Logger.get(BuckKsp2Logger::class.java)
+    private const val LOGGING_PREFIX: String = "[ksp2] "
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Factory.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Factory.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Factory.kt
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.ksp
+
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersion
+import com.facebook.buck.jvm.kotlin.cd.analytics.ClasspathChangesParam
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDLoggingContext
+import com.facebook.buck.jvm.kotlin.cd.analytics.ModeParam
+import com.facebook.buck.jvm.kotlin.cd.analytics.StepParam
+import com.facebook.buck.jvm.kotlin.ksp.incremental.Ksp2Mode
+
+internal fun KotlinCDLoggingContext(
+    languageVersion: LanguageVersion,
+    ksp2Mode: Ksp2Mode,
+    durationMs: Long? = null,
+): KotlinCDLoggingContext = KotlinCDLoggingContext(
+    step = StepParam.KSP2,
+    languageVersion = languageVersion,
+    mode = ModeParam(ksp2Mode),
+)
+    .apply {
+      this.durationMs = durationMs
+      (ksp2Mode as? Ksp2Mode.Incremental)?.reprocessReason?.message?.let { message ->
+        addExtras(
+            "KotlinCDLoggingContextFactory",
+            "Non-incremental processing will be performed: $message",
+        )
+      }
+    }
+
+private fun ModeParam(ksp2Mode: Ksp2Mode) =
+    when (ksp2Mode) {
+      is Ksp2Mode.NonIncremental -> ModeParam.NonIncremental
+      is Ksp2Mode.Incremental -> {
+        ModeParam.Incremental(
+            ClasspathChangesParam.UNKNOWN,
+            ksp2Mode.modifiedSources.toSet(),
+            ksp2Mode.removedSources.toSet(),
+        )
+      }
+    }
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/FilteringClassLoader.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/FilteringClassLoader.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/FilteringClassLoader.kt
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.ksp
+
+/**
+ * This class loader selectively routes classes from an allowlist to a specific class loader and
+ * everything else to another class loader. This can be used to isolate some loaded classes from
+ * most of the classes already loaded by the parent JVM, while letting others (in our case, the
+ * tracing agent classes) get reused.
+ */
+class FilteringClassLoader(
+    private val allowlistedParent: ClassLoader,
+    private val blocklistedParent: ClassLoader,
+    private vararg val allowlist: String,
+) : ClassLoader(allowlistedParent) {
+  override fun loadClass(name: String, resolve: Boolean): Class<*> {
+    if (allowlist.any { name.startsWith(it) }) {
+      return allowlistedParent.loadClass(name)
+    }
+
+    return blocklistedParent.loadClass(name)
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Ksp2NoOpDetector.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Ksp2NoOpDetector.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Ksp2NoOpDetector.kt
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.ksp
+
+import com.google.devtools.ksp.processing.CodeGenerator
+import com.google.devtools.ksp.processing.Resolver
+import com.google.devtools.ksp.processing.SymbolProcessor
+import com.google.devtools.ksp.processing.SymbolProcessorProvider
+import com.google.devtools.ksp.symbol.KSAnnotated
+
+/**
+ * Counts the files each native KSP processor generates, so that a processor attached to a target
+ * but generating nothing for it becomes visible.
+ *
+ * `CodeGenerator.generatedFile` is shared by every processor in an invocation and holds only files
+ * whose output streams are still open, which KSP closes at each round boundary. Output is therefore
+ * attributable only as a delta taken around each call and summed - exact because KSP runs
+ * processors sequentially: `process()` per round, then `finish()` once after the last round.
+ *
+ * Processors running under the javax adapter are not counted. They emit a placeholder file to force
+ * a final processing round, and do so precisely when a round generated nothing, so for them
+ * "generated no files" is not observable this way. They are left uncounted rather than counted
+ * wrongly.
+ *
+ * Zero is evidence of a no-op only under non-incremental processing: a processor with nothing to do
+ * in an incremental round legitimately generates nothing.
+ */
+class Ksp2NoOpDetector {
+
+  private val generatedCounts = mutableMapOf<String, Int>()
+
+  /** Files generated per native provider class name. A provider whose processor never ran is 0. */
+  val countsByProcessor: Map<String, Int>
+    get() = generatedCounts.toMap()
+
+  fun wrap(providers: List<SymbolProcessorProvider>): List<SymbolProcessorProvider> =
+      providers.map { provider ->
+        SymbolProcessorProvider { environment ->
+          val processor = provider.create(environment)
+          if (isAdapterProcessor(processor)) {
+            processor
+          } else {
+            val name = provider::class.java.name
+            // Seed the entry so a provider whose processor never generates is distinguishable from
+            // one that was never attached. That distinction is the point of this class.
+            generatedCounts.putIfAbsent(name, 0)
+            Counting(processor, name, environment.codeGenerator)
+          }
+        }
+      }
+
+  /** Matched by name: the adapter is loaded from the per-target processor classloader. */
+  private fun isAdapterProcessor(processor: SymbolProcessor): Boolean =
+      generateSequence<Class<*>>(processor::class.java) { it.superclass }
+          .any { it.name == ADAPTER_BASE_CLASS }
+
+  private inner class Counting(
+      private val delegate: SymbolProcessor,
+      private val name: String,
+      private val codeGenerator: CodeGenerator,
+  ) : SymbolProcessor by delegate {
+
+    override fun process(resolver: Resolver): List<KSAnnotated> = counted {
+      delegate.process(resolver)
+    }
+
+    override fun finish() {
+      counted { delegate.finish() }
+    }
+
+    private fun <T> counted(call: () -> T): T {
+      val before = codeGenerator.generatedFile.size
+      return call().also {
+        generatedCounts[name] =
+            generatedCounts.getValue(name) + (codeGenerator.generatedFile.size - before)
+      }
+    }
+  }
+
+  private companion object {
+    /**
+     * Matched against processor superclasses by name: the adapter lives on the per-target processor
+     * classloader, so it cannot be referenced directly. Pinned to the real class by
+     * `AdapterBaseClassFqnTest` in fbandroid and to the same-named fixture by
+     * `Ksp2NoOpDetectorTest` — update all three together on a rename or move.
+     */
+    const val ADAPTER_BASE_CLASS = "com.facebook.kotlin.ksp.kspadapter.SymbolProcessorBase"
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Ksp2Step.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Ksp2Step.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/Ksp2Step.kt
@@ -0,0 +1,378 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.ksp
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.core.util.log.Logger
+import com.facebook.buck.io.file.GlobPatternMatcher
+import com.facebook.buck.jvm.cd.command.kotlin.LanguageVersion
+import com.facebook.buck.jvm.core.BuildTargetValue
+import com.facebook.buck.jvm.java.CompilerOutputPaths
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDAnalytics
+import com.facebook.buck.jvm.kotlin.cd.analytics.KotlinCDLoggingContext
+import com.facebook.buck.jvm.kotlin.ksp.incremental.Ksp2Mode
+import com.facebook.buck.jvm.kotlin.util.getExpandedSourcePaths
+import com.facebook.buck.step.StepExecutionResult
+import com.facebook.buck.step.StepExecutionResults
+import com.facebook.buck.step.isolatedsteps.IsolatedStep
+import com.facebook.buck.util.CapturingPrintStream
+import com.google.common.base.Joiner
+import com.google.common.collect.ImmutableList
+import com.google.common.collect.ImmutableSortedSet
+import com.google.common.collect.Iterables
+import com.google.devtools.ksp.impl.KotlinSymbolProcessing
+import com.google.devtools.ksp.processing.KSPJvmConfig
+import com.google.devtools.ksp.processing.SymbolProcessorProvider
+import java.io.File
+import java.io.IOException
+import java.io.PrintStream
+import java.net.URLClassLoader
+import java.nio.charset.StandardCharsets
+import java.nio.file.Path
+import java.util.Optional
+import java.util.ServiceLoader
+import kotlin.time.measureTimedValue
+
+class Ksp2Step(
+    private val invokingRule: BuildTargetValue,
+    private val outputPaths: CompilerOutputPaths,
+    private val rootPath: AbsPath,
+    private val shouldTrackClassUsage: Boolean,
+    private val allClasspaths: ImmutableList<AbsPath>,
+    private val kotlinPluginGeneratedOutFullPath: String,
+    private val annotationProcessorParams: ImmutableSortedSet<String>,
+    private val sourceFilePaths: ImmutableSortedSet<RelPath>,
+    private val kspDepFilePath: RelPath,
+    private val moduleName: String,
+    private val kspProcessorsClasspathList: List<String>,
+    private val kspClassesOutput: RelPath,
+    private val kspKotlinOutput: RelPath,
+    private val kspJavaOutput: RelPath,
+    private val kspOutputBaseDir: RelPath,
+    private val jvmTarget: Optional<String>,
+    private val languageVersion: LanguageVersion,
+    private val jvmDefaultMode: String,
+    private val javaBinary: Optional<String>,
+    private val kotlinCDAnalytics: KotlinCDAnalytics,
+    private val ksp2Mode: Ksp2Mode,
+) : IsolatedStep {
+
+  private val noOpDetector = Ksp2NoOpDetector()
+
+  @Throws(IOException::class, InterruptedException::class)
+  override fun executeIsolatedStep(context: IsolatedExecutionContext): StepExecutionResult {
+    CapturingPrintStream().use { stderr ->
+      try {
+        val (exitCode, elapsed) = measureTimedValue { executeKsp2(stderr, context) }
+        val durationMs = elapsed.inWholeMilliseconds
+        // Same shape KotlincStep already emits, so the two steps are greppable together.
+        LOG.info(
+            "KOTLINCD_STEP_DURATION|%s|%s|%d|%d",
+            invokingRule.fullyQualifiedName,
+            this::class.java.simpleName,
+            durationMs,
+            sourceFilePaths.size,
+        )
+        kotlinCDAnalytics.log(
+            KotlinCDLoggingContext(languageVersion, ksp2Mode, durationMs).apply {
+              addExtras(
+                  this@Ksp2Step::class.java.simpleName,
+                  "Ksp2 step duration: $durationMs ms",
+              )
+              val counts = noOpDetector.countsByProcessor
+              if (
+                  shouldRecordProcessorCounts(
+                      exitCode == KotlinSymbolProcessing.ExitCode.OK,
+                      counts.isNotEmpty(),
+                      ksp2Mode,
+                  )
+              ) {
+                addExtras(
+                    PROCESSOR_OUTPUT_EXTRAS_KEY,
+                    counts.entries.joinToString(",") { "${it.key}=${it.value}" },
+                )
+              }
+            },
+        )
+        return when (exitCode) {
+          KotlinSymbolProcessing.ExitCode.OK -> StepExecutionResults.SUCCESS
+          KotlinSymbolProcessing.ExitCode.PROCESSING_ERROR ->
+              StepExecutionResult(
+                  StepExecutionResults.ERROR_EXIT_CODE,
+                  Optional.of(stderr.getContentsAsString(StandardCharsets.UTF_8)),
+              )
+        }
+      } catch (e: LinkageError) {
+        return StepExecutionResult(
+            StepExecutionResults.ERROR_EXIT_CODE,
+            Optional.of(
+                "${stderr.getContentsAsString(StandardCharsets.UTF_8)}\n${e.stackTraceToString()}For URLClassLoader LinkError similar to P1626402598, try adding affected class to FilteringClassLoader's allowlist. See D63143327",
+            ),
+        )
+      } catch (e: Throwable) {
+        return StepExecutionResult(
+            StepExecutionResults.ERROR_EXIT_CODE,
+            Optional.of(
+                "${stderr.getContentsAsString(StandardCharsets.UTF_8)}\n${e.stackTraceToString()}",
+            ),
+        )
+      }
+    }
+  }
+
+  private fun executeKsp2(
+      stdErr: PrintStream,
+      context: IsolatedExecutionContext,
+  ): KotlinSymbolProcessing.ExitCode {
+    val logger = BuckKsp2Logger(stdErr)
+
+    // Load processors
+    val processorClassloader: ClassLoader = URLClassLoader(
+        kspProcessorsClasspathList.map { File(it).toURI().toURL() }.toTypedArray(),
+        filteringClassLoader,
+    )
+    val processorProviders =
+        ServiceLoader.load(
+                processorClassloader.loadClass(
+                    "com.google.devtools.ksp.processing.SymbolProcessorProvider",
+                ),
+                processorClassloader,
+            )
+            .toList() as List<SymbolProcessorProvider>
+
+    // Build processor options
+    val apOptions = getApOptions()
+
+    // Expand source paths
+    val sourceFilePathsExpanded = getExpandedSourcePathsOrThrow(
+        ruleCellRoot = context.ruleCellRoot,
+        kotlinSourceFilePaths = sourceFilePaths,
+        ignoredPathMatcher =
+            if (invokingRule.isSourceOnlyAbi) GlobPatternMatcher.of("**/kosabi_stub.android.**.kt")
+            else null,
+        workingDirectory = Optional.of(outputPaths.workingDirectory.getPath()),
+        invokingRule = invokingRule,
+        logger = logger,
+    )
+    val sourceFilePathsResolved = sourceFilePathsExpanded.map { rootPath.resolve(it).toFile() }
+
+    // Build KSP config
+    val kspConfig =
+        KSPJvmConfig.Builder()
+            .apply {
+              // All configurations happen here. See [KSPConfig] for all available options.
+              projectBaseDir = rootPath.toFile()
+              classOutputDir = rootPath.resolve(kspClassesOutput).toFile()
+              kotlinOutputDir = rootPath.resolve(kspKotlinOutput).toFile()
+              javaOutputDir = rootPath.resolve(kspJavaOutput).toFile()
+              resourceOutputDir = rootPath.resolve(kspClassesOutput).toFile()
+              outputBaseDir = rootPath.resolve(kspOutputBaseDir).toFile()
+              processorOptions = apOptions
+              moduleName = this@Ksp2Step.moduleName
+              jvmTarget = this@Ksp2Step.jvmTarget.orElse("1.8")
+              sourceRoots = sourceFilePathsResolved
+              javaSourceRoots = sourceFilePathsResolved
+              languageVersion = this@Ksp2Step.languageVersion.value
+              apiVersion = this@Ksp2Step.languageVersion.value
+              libraries = allClasspaths.map { it.toFile() }
+              jvmDefaultMode = this@Ksp2Step.jvmDefaultMode
+              resolveJdkHome(this@Ksp2Step.javaBinary)?.let { jdkHome = it }
+
+              when (ksp2Mode) {
+                is Ksp2Mode.NonIncremental -> {
+                  cachesDir = rootPath.resolve(ksp2Mode.kspCachesOutput).toFile()
+                }
+                is Ksp2Mode.Incremental -> {
+                  incremental = true
+                  cachesDir = ksp2Mode.cachesDir.toFile()
+                  incrementalLog = ksp2Mode.incrementalLog
+                  modifiedSources = ksp2Mode.modifiedSources.map { it.toFile() }
+                  removedSources = ksp2Mode.removedSources.map { it.toFile() }
+                  changedClasses = ksp2Mode.changedClasses
+                }
+              }
+            }
+            .build()
+
+    logger.info(
+        """Running KSP2 with
+              |processors: ${processorProviders.joinToString(", ") { it::class.java.name }}
+              |KSPJvmConfig: [
+              |  projectBaseDir = ${kspConfig.projectBaseDir}
+              |  classOutputDir = ${kspConfig.classOutputDir}
+              |  kotlinOutputDir = ${kspConfig.kotlinOutputDir}
+              |  javaOutputDir = ${kspConfig.javaOutputDir}
+              |  resourceOutputDir = ${kspConfig.resourceOutputDir}
+              |  cachesDir = ${kspConfig.cachesDir}
+              |  outputBaseDir = ${kspConfig.outputBaseDir}
+              |  processorOptions = [
+              |    ${kspConfig.processorOptions.map { it.key + "=" + it.value }.joinToString(",\n    ")}]
+              |  moduleName = ${kspConfig.moduleName}
+              |  jvmTarget = ${kspConfig.jvmTarget}
+              |  sourceRoots = ${kspConfig.sourceRoots}
+              |  javaSourceRoots = ${kspConfig.javaSourceRoots}
+              |  languageVersion = ${kspConfig.languageVersion}
+              |  apiVersion = ${kspConfig.apiVersion}
+              |  libraries = ${kspConfig.libraries}
+              |  jvmDefaultMode = ${kspConfig.jvmDefaultMode}
+              |  jdkHome = ${kspConfig.jdkHome}
+              |  incremental = ${kspConfig.incremental}
+              |  incrementalLog = ${kspConfig.incrementalLog}
+              |  modifiedSources = ${kspConfig.modifiedSources.joinToString()}
+              |  removedSources = ${kspConfig.removedSources.joinToString()}
+              |  changedClasses = ${kspConfig.changedClasses.joinToString()}
+              |]"""
+            .trimMargin(),
+    )
+    // Run!
+    val kotlinSymbolProcessing =
+        KotlinSymbolProcessing(kspConfig, noOpDetector.wrap(processorProviders), logger)
+    return kotlinSymbolProcessing.execute()
+  }
+
+  private fun getApOptions(): MutableMap<String, String> {
+    val apOptions = mutableMapOf<String, String>()
+
+    // KSP needs the full classpath in order to resolve resources
+    val allClasspath =
+        Joiner.on(File.pathSeparator)
+            .join(Iterables.transform(allClasspaths) { path: AbsPath -> path.getPath().toString() })
+    apOptions["cp"] = allClasspath.replace(',', '-')
+
+    if (shouldTrackClassUsage) {
+      apOptions["fileAccessHistoryReportFile"] = rootPath.resolve(kspDepFilePath).toString()
+    }
+
+    if (invokingRule.isSourceOnlyAbi) {
+      apOptions["com.facebook.buck.kotlin.generating_abi"] = "true"
+    }
+
+    for (param: String in annotationProcessorParams) {
+      val paramAndValue = param.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
+      check(paramAndValue.size == 2)
+      apOptions[paramAndValue[0]] = paramAndValue[1]
+    }
+
+    apOptions["com.facebook.buck.kotlin.ksp_generated_out_path"] = kotlinPluginGeneratedOutFullPath
+    return apOptions
+  }
+
+  override fun getIsolatedStepDescription(context: IsolatedExecutionContext): String {
+    return "Running ksp2 for $moduleName"
+  }
+
+  override fun getShortName(): String {
+    return "ksp2"
+  }
+
+  private fun getExpandedSourcePathsOrThrow(
+      ruleCellRoot: AbsPath,
+      kotlinSourceFilePaths: ImmutableSortedSet<RelPath>,
+      ignoredPathMatcher: GlobPatternMatcher?,
+      workingDirectory: Optional<Path>,
+      invokingRule: BuildTargetValue,
+      logger: BuckKsp2Logger,
+  ) =
+      try {
+        getExpandedSourcePaths(ruleCellRoot, kotlinSourceFilePaths, workingDirectory).filterNot {
+            path: Path ->
+          ignoredPathMatcher?.matches(path) ?: false
+        }
+      } catch (exception: IOException) {
+        logger.exception(exception)
+        throw RuntimeException(
+            "Unable to expand sources for ${invokingRule.fullyQualifiedName} into $workingDirectory",
+        )
+      }
+
+  companion object {
+    private val LOG: Logger = Logger.get(Ksp2Step::class.java)
+
+    private const val PROCESSOR_OUTPUT_EXTRAS_KEY = "ksp2_processor_generated_files"
+
+    /**
+     * Telemetry records only successful non-incremental runs that produced counts: an aborted run
+     * leaves never-ran processors reading zero, and in an incremental round a zero mixes genuine
+     * no-ops with legitimately idle processors.
+     */
+    fun shouldRecordProcessorCounts(
+        succeeded: Boolean,
+        hasCounts: Boolean,
+        ksp2Mode: Ksp2Mode,
+    ): Boolean = succeeded && hasCounts && ksp2Mode is Ksp2Mode.NonIncremental
+
+    private val jdkHomeCache = java.util.concurrent.ConcurrentHashMap<String, File>()
+    private val JAVA_HOME_REGEX = Regex("""java\.home\s*=\s*(.+)""")
+
+    /**
+     * Resolves the JDK home directory from the declared java binary input.
+     *
+     * KSP2 needs jdkHome to resolve JDK types (java.lang.AutoCloseable, etc.) for JVM targets.
+     * Android targets use android.jar instead and do not need jdkHome — returns null when
+     * javaBinary is absent so callers can skip setting jdkHome (KSP2 defaults to
+     * System.getProperty("java.home")).
+     *
+     * Similar to compile_kotlin.py's _get_jdk_home() which uses jdk_locator, this invokes the java
+     * binary with -XshowSettings:properties to discover java.home at action time. The java binary
+     * is a declared Buck2 input (from java_toolchain.java), making this hermetic.
+     *
+     * Result is cached per java binary path (subprocess runs at most once per distinct binary).
+     */
+    private fun resolveJdkHome(javaBinary: Optional<String>): File? {
+      val binary = javaBinary.filter { it.isNotEmpty() }.orElse(null) ?: return null
+      return jdkHomeCache.computeIfAbsent(binary) { resolveJdkHomeUncached(it) }
+    }
+
+    private fun resolveJdkHomeUncached(binary: String): File {
+      val process =
+          ProcessBuilder(binary, "-XshowSettings:properties", "-version")
+              .redirectErrorStream(true)
+              .start()
+      // Drain the pipe in a background thread to avoid deadlock: the process can
+      // write more than the OS pipe buffer (~64KB), blocking if no one reads.
+      // Meanwhile waitFor() provides the timeout guarantee.
+      val outputFuture =
+          java.util.concurrent.CompletableFuture.supplyAsync {
+            process.inputStream.bufferedReader().readText()
+          }
+      val completed = process.waitFor(60, java.util.concurrent.TimeUnit.SECONDS)
+      if (!completed) {
+        process.destroyForcibly()
+        throw RuntimeException("Timed out resolving JDK home from java binary: $binary")
+      }
+      val exitCode = process.exitValue()
+      val output = outputFuture.get()
+      if (exitCode != 0) {
+        throw RuntimeException(
+            "java binary exited with code $exitCode: $binary\n" + "Output: ${output.take(500)}",
+        )
+      }
+      val match = JAVA_HOME_REGEX.find(output)
+      val path =
+          match?.groupValues?.get(1)?.trim()
+              ?: throw RuntimeException(
+                  "Could not parse java.home from java binary output: $binary\n" +
+                      "Output (first 500 chars): ${output.take(500)}",
+              )
+      return File(path)
+    }
+
+    private val filteringClassLoader = FilteringClassLoader(
+        this::class.java.classLoader,
+        ClassLoader.getPlatformClassLoader(),
+        "com.google.devtools.ksp.",
+        "kotlin.",
+        "ksp.",
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/BUCK
@@ -0,0 +1,19 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "incremental",
+    srcs = glob(["**/*.kt"]),
+    labels = ["codegen_rule"],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/Ksp2Mode.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/Ksp2Mode.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/Ksp2Mode.kt
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.ksp.incremental
+
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.core.filesystems.RelPath
+
+sealed interface Ksp2Mode {
+
+  data class NonIncremental(val kspCachesOutput: RelPath) : Ksp2Mode
+
+  data class Incremental(
+      val cachesDir: AbsPath,
+      val incrementalLog: Boolean,
+      val modifiedSources: List<AbsPath>,
+      val removedSources: List<AbsPath>,
+      val changedClasses: List<String>,
+      val reprocessReason: ReprocessReason?,
+  ) : Ksp2Mode
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/ReprocessReason.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/ReprocessReason.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/ksp/incremental/ReprocessReason.kt
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.ksp.incremental
+
+enum class ReprocessReason(val message: String) {
+  CLASSPATH_CHANGED("Incremental processing after classpath change is not supported yet"),
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/BUCK
@@ -0,0 +1,17 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "plugin-loader",
+    srcs = ["PluginLoader.java"],
+    resources = [
+        "dep-tracker.jar",
+    ],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin:",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/PluginLoader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/PluginLoader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/PluginLoader.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.plugin;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+
+public class PluginLoader {
+
+  private static final String DEP_TRACKER_KOTLINC_PLUGIN_JAR_RESOURCE_PATH = "dep-tracker.jar";
+
+  public static final File DEP_TRACKER_KOTLINC_PLUGIN_JAR_PATH = extractDepTrackerPlugin();
+
+  private static File extractDepTrackerPlugin() {
+    try {
+      return doExtractDepTrackerPlugin();
+    } catch (URISyntaxException | IOException | NullPointerException e) {
+      throw new RuntimeException("Failed to extract kotlinc plugin jar", e);
+    }
+  }
+
+  private static File doExtractDepTrackerPlugin() throws URISyntaxException, IOException {
+    URL resource = PluginLoader.class.getResource(DEP_TRACKER_KOTLINC_PLUGIN_JAR_RESOURCE_PATH);
+    if (resource == null) {
+      throw new RuntimeException("Could not find dep-tracker kotlinc plugin jar");
+    }
+    if ("file".equals(resource.getProtocol())) {
+      return new File(resource.toURI());
+    }
+    // TODO: This Extraction technique will be deprecated as we will provide dep-tracker dependency
+    //   with a 3p buck rule, same as Kosabi and Nullsafe.
+    try (InputStream in =
+        PluginLoader.class.getResourceAsStream(DEP_TRACKER_KOTLINC_PLUGIN_JAR_RESOURCE_PATH)) {
+      File plugin = File.createTempFile("dep-tracker", ".jar");
+      plugin.deleteOnExit();
+      Files.copy(in, Paths.get(plugin.toURI()), StandardCopyOption.REPLACE_EXISTING);
+      return plugin;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/dep-tracker.jar b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/dep-tracker.jar
new file mode 100644
Binary files /dev/null and b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/plugin/dep-tracker.jar differ
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/util/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/util/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/util/BUCK
@@ -0,0 +1,26 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "util",
+    srcs = glob(
+        ["**/*.kt"],
+    ),
+    extra_kotlinc_arguments = ["-Xopt-in=kotlin.ExperimentalStdlibApi"],
+    labels = ["codegen_rule"],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/...",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/core:core",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/src/com/facebook/buck/util/unarchive:unarchive",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/util/KotlinUnarchiver.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/util/KotlinUnarchiver.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/jvm/kotlin/util/KotlinUnarchiver.kt
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.jvm.kotlin.util
+
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.jvm.java.JavaPaths
+import com.facebook.buck.util.unarchive.Unzip
+import com.google.common.collect.ImmutableList
+import com.google.common.collect.ImmutableSet
+import java.io.IOException
+import java.nio.file.Path
+import java.util.Optional
+
+@Throws(IOException::class)
+fun getExpandedSourcePaths(
+    ruleCellRoot: AbsPath,
+    kotlinSourceFilePaths: ImmutableSet<RelPath>,
+    workingDirectory: Optional<Path>,
+): ImmutableList<Path> {
+  // Add sources file or sources list to command
+
+  val sources = ImmutableList.builder<Path>()
+  for (path in kotlinSourceFilePaths) {
+    val pathString = path.toString()
+    if (pathString.endsWith(".kt") || pathString.endsWith(".kts") || pathString.endsWith(".java")) {
+      sources.add(path.path)
+    } else if (pathString.endsWith(JavaPaths.SRC_ZIP) || pathString.endsWith(JavaPaths.SRC_JAR)) {
+      // For a Zip of .java files, create a JavaFileObject for each .java entry.
+      val zipPaths: ImmutableList<Path> =
+          Unzip.extractArchive(
+              ruleCellRoot,
+              ruleCellRoot.resolve(path).path,
+              ruleCellRoot.resolve(workingDirectory.orElse(path.path)).path,
+          )
+      sources.addAll(
+          zipPaths
+              .stream()
+              .filter { input: Path ->
+                (input.toString().endsWith(".kt") ||
+                    input.toString().endsWith(".kts") ||
+                    input.toString().endsWith(".java"))
+              }
+              .iterator(),
+      )
+    }
+  }
+  return sources.build()
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/BUCK
@@ -0,0 +1,24 @@
+load(
+    "@prelude//toolchains/android/tools:build_rules.bzl",
+    "buck_kotlin_library",
+)
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "step",
+    srcs = glob(
+        [
+            "*.java",
+            "*.kt",
+        ],
+    ),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/util:process_executor",
+    ],
+    exported_deps = [],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/StepExecutionResult.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/StepExecutionResult.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/StepExecutionResult.kt
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step
+
+import java.util.Optional
+
+/** Exit code, command and stderr info from the executed step */
+data class StepExecutionResult(
+    val exitCode: Int,
+    val stderr: Optional<String>,
+    val cause: Optional<Exception>,
+) {
+  constructor(
+      exitCode: Int,
+      stderr: Optional<String>,
+  ) : this(exitCode, stderr, Optional.empty<Exception>())
+
+  val isSuccess: Boolean
+    get() = exitCode == StepExecutionResults.SUCCESS_EXIT_CODE
+
+  val errorMessage: String
+    get() {
+      return cause
+          .map<String>(Throwable::message)
+          .or(this::stderr)
+          .orElse(String.format("<failed with exit code %s>", exitCode))
+    }
+
+  companion object {
+    /** Creates `StepExecutionResult` from `exitCode` */
+    @JvmStatic
+    fun of(exitCode: Int): StepExecutionResult {
+      return StepExecutionResult(
+          exitCode,
+          if (exitCode == 0) Optional.empty() else Optional.of("Failed to execute isolated step."),
+          Optional.empty(),
+      )
+    }
+
+    /** Creates `StepExecutionResult` from `exception` */
+    @JvmStatic
+    fun of(exception: Throwable): StepExecutionResult {
+      return StepExecutionResult(
+          StepExecutionResults.ERROR_EXIT_CODE,
+          Optional.of("Failed to execute isolated step."),
+          Optional.ofNullable(exception.cause as Exception?),
+      )
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/StepExecutionResults.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/StepExecutionResults.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/StepExecutionResults.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step;
+
+/** A collection of common StepExecutionResult constants. */
+public class StepExecutionResults {
+  // NB: These constants cannot live in StepExecutionResult, as referencing subclass in
+  // static initializer may cause deadlock during classloading.
+
+  public static final int SUCCESS_EXIT_CODE = 0;
+  public static final int ERROR_EXIT_CODE = 3;
+
+  public static final StepExecutionResult SUCCESS = StepExecutionResult.of(SUCCESS_EXIT_CODE);
+  public static final StepExecutionResult ERROR = StepExecutionResult.of(ERROR_EXIT_CODE);
+
+  private StepExecutionResults() {} // Utility class. Do not instantiate.
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "isolatedsteps",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/...",
+        "prelude//toolchains/android/test/com/facebook/buck/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/util/json:json",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/build/execution/context:context",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/step:step",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/IsolatedStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/IsolatedStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/IsolatedStep.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps;
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.step.StepExecutionResult;
+import java.io.IOException;
+
+/**
+ * Isolated step - build rule's step that is isolated from the buck core data structures as an
+ * action graph.
+ */
+public interface IsolatedStep {
+
+  /**
+   * @return a short name/description for the command, such as "javac". Should fit on one line.
+   */
+  String getShortName();
+
+  StepExecutionResult executeIsolatedStep(IsolatedExecutionContext context)
+      throws IOException, InterruptedException;
+
+  String getIsolatedStepDescription(IsolatedExecutionContext context);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/IsolatedStepsRunner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/IsolatedStepsRunner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/IsolatedStepsRunner.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps;
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.step.StepExecutionResult;
+import com.facebook.buck.step.StepExecutionResults;
+import com.google.common.collect.ImmutableList;
+import java.io.IOException;
+
+/** Step runner that executes the steps the given {@link IsolatedStep}s. */
+public class IsolatedStepsRunner {
+
+  private static final Logger LOG = Logger.get(IsolatedStepsRunner.class);
+
+  private IsolatedStepsRunner() {}
+
+  /**
+   * Executes the given {@link IsolatedStep} instances with the given {@link
+   * IsolatedExecutionContext} and throws {@link StepFailedException} if it occurred during the
+   * execution of any steps.
+   */
+  public static StepExecutionResult execute(
+      ImmutableList<IsolatedStep> steps, IsolatedExecutionContext executionContext)
+      throws StepFailedException {
+    try {
+      for (IsolatedStep step : steps) {
+        runStep(executionContext, step);
+        rethrowIgnoredInterruptedException(step);
+      }
+      return StepExecutionResults.SUCCESS;
+    } catch (InterruptedException e) {
+      // Just return an error code.
+    }
+    return StepExecutionResults.ERROR;
+  }
+
+  /**
+   * Executes the given {@link IsolatedStep} instances with the given {@link
+   * IsolatedExecutionContext} and handles {@link StepFailedException} (log it with an error level).
+   *
+   * <p>The difference from this method and {@link #execute} is that this method logs and do not
+   * propagate {@link StepFailedException} in case it occurred.
+   */
+  public static StepExecutionResult executeWithDefaultExceptionHandling(
+      ImmutableList<IsolatedStep> steps, IsolatedExecutionContext executionContext) {
+    try {
+      return execute(steps, executionContext);
+    } catch (StepFailedException e) {
+      if (!executionContext.getVerbosity().isSilent()) {
+        LOG.warn(e, "Failed to execute isolated steps");
+      }
+      return StepExecutionResult.of(e);
+    }
+  }
+
+  private static void runStep(IsolatedExecutionContext context, IsolatedStep step)
+      throws InterruptedException, StepFailedException {
+    StepExecutionResult executionResult = StepExecutionResults.ERROR;
+    try {
+      executionResult = step.executeIsolatedStep(context);
+    } catch (IOException | RuntimeException e) {
+      throw StepFailedException.createForFailingStepWithException(
+          step, descriptionForStep(step, context), e);
+    }
+    if (!executionResult.isSuccess()) {
+      throw StepFailedException.createForFailingIsolatedStepWithExitCode(
+          step, descriptionForStep(step, context), executionResult);
+    }
+  }
+
+  private static String descriptionForStep(IsolatedStep step, IsolatedExecutionContext context) {
+    return context.getVerbosity().shouldPrintCommand()
+        ? step.getIsolatedStepDescription(context)
+        : step.getShortName();
+  }
+
+  private static void rethrowIgnoredInterruptedException(IsolatedStep step)
+      throws InterruptedException {
+    // Check for interruptions that may have been ignored by step.
+    if (Thread.interrupted()) {
+      Thread.currentThread().interrupt();
+      throw new InterruptedException(
+          "Thread was interrupted inside the executed step: " + step.getShortName());
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/StepFailedException.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/StepFailedException.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/StepFailedException.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps;
+
+import com.facebook.buck.step.StepExecutionResult;
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Optional;
+import java.util.OptionalInt;
+
+public class StepFailedException extends Exception {
+
+  @VisibleForTesting static final int KEEP_FIRST_CHARS = 4 * 80;
+
+  private final IsolatedStep step;
+  private final String description;
+  private final OptionalInt exitCode;
+
+  /** Callers should use {@link #createForFailingIsolatedStepWithExitCode} unless in a unit test. */
+  private StepFailedException(
+      Throwable cause, IsolatedStep step, String description, OptionalInt exitCode) {
+    super(cause);
+    this.step = step;
+    this.description = description;
+    this.exitCode = exitCode;
+  }
+
+  @Override
+  public String getMessage() {
+    return getCause().getMessage() + System.lineSeparator() + "  " + getContext();
+  }
+
+  /** Creates a StepFailedException based on a StepExecutionResult. */
+  public static StepFailedException createForFailingIsolatedStepWithExitCode(
+      IsolatedStep step, String descriptionForStep, StepExecutionResult executionResult) {
+    StringBuilder errorMessage = new StringBuilder();
+    errorMessage.append(String.format("Failed to execute isolated step <%s>", step.getShortName()));
+    Optional<String> stderr = executionResult.getStderr();
+    if (stderr.isPresent()) {
+      String error = stderr.get();
+      errorMessage.append(System.lineSeparator()).append(error);
+    }
+    return new StepFailedException(
+        getException(executionResult, errorMessage.toString()),
+        step,
+        descriptionForStep,
+        OptionalInt.of(executionResult.getExitCode()));
+  }
+
+  private static RuntimeException getException(
+      StepExecutionResult executionResult, String errorMessage) {
+    Optional<Exception> executionResultCause = executionResult.getCause();
+    if (executionResultCause.isPresent()) {
+      Exception cause = executionResultCause.get();
+      return new RuntimeException(errorMessage, cause);
+    }
+    return new RuntimeException(errorMessage);
+  }
+
+  public static StepFailedException createForFailingStepWithException(
+      IsolatedStep step, String descriptionForStep, Throwable throwable) {
+    return new StepFailedException(throwable, step, descriptionForStep, OptionalInt.empty());
+  }
+
+  public IsolatedStep getStep() {
+    return step;
+  }
+
+  public OptionalInt getExitCode() {
+    return exitCode;
+  }
+
+  private String getContext() {
+    return String.format("When running <%s>.", description);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/AbstractIsolatedExecutionStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/AbstractIsolatedExecutionStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/AbstractIsolatedExecutionStep.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps.common;
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.step.StepExecutionResult;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import java.io.IOException;
+
+/**
+ * Abstract implementation of {@link IsolatedStep} that takes the description as a constructor
+ * parameter and requires only the implementation of {@link
+ * #executeIsolatedStep(IsolatedExecutionContext)}. This facilitates the creation of an anonymous
+ * implementation of {@link IsolatedStep}.
+ */
+public abstract class AbstractIsolatedExecutionStep implements IsolatedStep {
+
+  private final String description;
+
+  public AbstractIsolatedExecutionStep(String description) {
+    this.description = description;
+  }
+
+  @Override
+  public abstract StepExecutionResult executeIsolatedStep(IsolatedExecutionContext context)
+      throws IOException, InterruptedException;
+
+  @Override
+  public String getShortName() {
+    return description;
+  }
+
+  @Override
+  public String getIsolatedStepDescription(IsolatedExecutionContext context) {
+    return description;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/BUCK
@@ -0,0 +1,30 @@
+load(
+    "@prelude//toolchains/android/tools:build_rules.bzl",
+    "buck_kotlin_library",
+)
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_kotlin_library(
+    name = "common",
+    srcs = glob([
+        "*.java",
+        "*.kt",
+    ]),
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/...",
+        "prelude//toolchains/android/test/com/facebook/buck/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps:isolatedsteps",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/CopyIsolatedStep.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/CopyIsolatedStep.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/CopyIsolatedStep.kt
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps.common
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.io.filesystem.CopySourceMode
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils
+import com.facebook.buck.step.StepExecutionResult
+import com.facebook.buck.step.StepExecutionResults
+import com.facebook.buck.step.isolatedsteps.IsolatedStep
+import java.io.File
+import java.io.IOException
+import java.nio.file.Path
+import java.util.StringJoiner
+
+/** Copy IsolatedStep */
+data class CopyIsolatedStep(
+    val source: Path,
+    val destination: Path,
+    val copySourceMode: CopySourceMode,
+) : IsolatedStep {
+  override fun getShortName(): String {
+    return "cp"
+  }
+
+  override fun getIsolatedStepDescription(context: IsolatedExecutionContext): String {
+    val args = StringJoiner(" ")
+    args.add("cp")
+    when (copySourceMode) {
+      CopySourceMode.FILE -> args.add(source.toString())
+      CopySourceMode.DIRECTORY_AND_CONTENTS -> {
+        args.add("-R")
+        args.add(source.toString())
+      }
+      CopySourceMode.DIRECTORY_CONTENTS_ONLY -> {
+        args.add("-R")
+
+        // BSD and GNU cp have different behaviors with -R:
+        // http://jondavidjohn.com/blog/2012/09/linux-vs-osx-the-cp-command
+        //
+        // To work around this, we use "sourceDir/*" as the source to
+        // copy in this mode.
+
+        // N.B., on Windows, java.nio.AbstractPath does not resolve *
+        // as a path, causing InvalidPathException. Since this is purely a
+        // description, manually create the source argument.
+        args.add(source.toString() + File.separator + "*")
+      }
+    }
+    args.add(destination.toString())
+    return args.toString()
+  }
+
+  @Throws(IOException::class)
+  override fun executeIsolatedStep(context: IsolatedExecutionContext): StepExecutionResult {
+    ProjectFilesystemUtils.copy(context.ruleCellRoot, source, destination, copySourceMode)
+    return StepExecutionResults.SUCCESS
+  }
+
+  companion object {
+    @JvmStatic
+    fun of(source: Path, destination: Path, copySourceMode: CopySourceMode): CopyIsolatedStep {
+      return CopyIsolatedStep(source, destination, copySourceMode)
+    }
+
+    /** Creates a CopyStep which copies a single file from 'source' to 'destination'. */
+    fun forFile(source: Path, destination: Path): CopyIsolatedStep {
+      return CopyIsolatedStep(source, destination, CopySourceMode.FILE)
+    }
+
+    /** Creates a CopyStep which copies a single file from 'source' to 'destination'. */
+    fun forFile(source: RelPath, destination: RelPath): CopyIsolatedStep {
+      return forFile(source.path, destination.path)
+    }
+
+    /** Creates a CopyStep which recursively copies a directory from 'source' to 'destination'. */
+    @JvmStatic
+    fun forDirectory(
+        source: Path,
+        destination: Path,
+        copySourceMode: CopySourceMode,
+    ): CopyIsolatedStep {
+      return CopyIsolatedStep(source, destination, copySourceMode)
+    }
+
+    /** Creates a CopyStep which recursively copies a directory from 'source' to 'destination'. */
+    @JvmStatic
+    fun forDirectory(
+        source: RelPath,
+        destination: RelPath,
+        copySourceMode: CopySourceMode,
+    ): CopyIsolatedStep {
+      return forDirectory(source.path, destination.path, copySourceMode)
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/MakeCleanDirectoryIsolatedStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/MakeCleanDirectoryIsolatedStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/MakeCleanDirectoryIsolatedStep.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps.common;
+
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+
+/**
+ * Deletes the directory, if it exists, before creating it. {@link MakeCleanDirectoryIsolatedStep}
+ * is preferable to {@link MkdirIsolatedStep} if the directory may contain many generated files and
+ * we want to avoid the case where it could accidentally include generated files from a previous run
+ * in Buck.
+ *
+ * <p>For example, for a directory of {@code .class} files, if the user deletes a {@code .java} file
+ * that generated one of the {@code .class} files, the {@code .class} file corresponding to the
+ * deleted {@code .java} file should no longer be there when {@code javac} is run again.
+ */
+public final class MakeCleanDirectoryIsolatedStep {
+
+  public static ImmutableList<IsolatedStep> of(RelPath path) {
+    return ImmutableList.of(
+        new RmIsolatedStep(path, true, ImmutableSet.of()), new MkdirIsolatedStep(path));
+  }
+
+  private MakeCleanDirectoryIsolatedStep() {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/MkdirIsolatedStep.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/MkdirIsolatedStep.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/MkdirIsolatedStep.kt
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps.common
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils
+import com.facebook.buck.step.StepExecutionResult
+import com.facebook.buck.step.StepExecutionResults
+import com.facebook.buck.step.isolatedsteps.IsolatedStep
+import com.facebook.buck.util.Escaper
+import java.io.IOException
+import java.nio.file.Files
+
+/** Command that runs equivalent command of `mkdir -p` on the specified directory. */
+data class MkdirIsolatedStep(val dirPath: RelPath) : IsolatedStep {
+  @Throws(IOException::class)
+  override fun executeIsolatedStep(context: IsolatedExecutionContext): StepExecutionResult {
+    Files.createDirectories(
+        ProjectFilesystemUtils.getPathForRelativePath(context.ruleCellRoot, dirPath.path),
+    )
+    return StepExecutionResults.SUCCESS
+  }
+
+  override fun getIsolatedStepDescription(context: IsolatedExecutionContext): String {
+    return String.format("mkdir -p %s", Escaper.escapeAsShellString(dirPath.toString()))
+  }
+
+  override fun getShortName(): String {
+    return "mkdir"
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/RmIsolatedStep.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/RmIsolatedStep.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/RmIsolatedStep.kt
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps.common
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.io.file.MostFiles
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils
+import com.facebook.buck.step.StepExecutionResult
+import com.facebook.buck.step.StepExecutionResults
+import com.facebook.buck.step.isolatedsteps.IsolatedStep
+import com.google.common.base.Preconditions
+import com.google.common.collect.ImmutableSet
+import java.io.IOException
+import java.nio.file.Files
+import java.util.StringJoiner
+
+/** Removes a path if it exists. */
+data class RmIsolatedStep(
+    val path: RelPath,
+    val isRecursive: Boolean,
+    val excludedPaths: ImmutableSet<RelPath>,
+) : IsolatedStep {
+  override fun getShortName(): String {
+    return "rm"
+  }
+
+  @Throws(IOException::class)
+  override fun executeIsolatedStep(context: IsolatedExecutionContext): StepExecutionResult {
+    val absolutePath = getAbsPath(context)
+
+    if (isRecursive) {
+      // Delete a folder recursively
+      MostFiles.deleteRecursivelyIfExists(absolutePath, getAbsoluteExcludedPaths(context))
+    } else {
+      // Delete a single file
+      Preconditions.checkState(
+          excludedPaths.isEmpty(),
+          "Excluded paths only valid for recursive steps",
+      )
+      Files.deleteIfExists(absolutePath.path)
+    }
+    return StepExecutionResults.SUCCESS
+  }
+
+  private fun getAbsPath(context: IsolatedExecutionContext): AbsPath {
+    return convertRelPathToAbsPath(context, path)
+  }
+
+  private fun convertRelPathToAbsPath(
+      context: IsolatedExecutionContext,
+      relPath: RelPath,
+  ): AbsPath {
+    return ProjectFilesystemUtils.getAbsPathForRelativePath(context.ruleCellRoot, relPath)
+  }
+
+  private fun getAbsoluteExcludedPaths(context: IsolatedExecutionContext): ImmutableSet<AbsPath> {
+    val excludedRelPaths = excludedPaths
+    if (excludedRelPaths.isEmpty()) {
+      // Avoid calls to .stream() and creation of new sets as almost all steps will not have
+      // any excluded paths
+      return ImmutableSet.of()
+    }
+
+    return excludedRelPaths
+        .stream()
+        .map { relPath: RelPath -> convertRelPathToAbsPath(context, relPath) }
+        .collect(ImmutableSet.toImmutableSet())
+  }
+
+  override fun getIsolatedStepDescription(context: IsolatedExecutionContext): String {
+    val args = StringJoiner(" ")
+    args.add("rm")
+    args.add("-f")
+
+    if (isRecursive) {
+      args.add("-r")
+    }
+
+    args.add(getAbsPath(context).toString())
+
+    if (!excludedPaths.isEmpty()) {
+      args.add("(with excluded paths)")
+    }
+
+    return args.toString()
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/SymlinkIsolatedStep.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/SymlinkIsolatedStep.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/SymlinkIsolatedStep.kt
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps.common
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext
+import com.facebook.buck.core.filesystems.RelPath
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils
+import com.facebook.buck.step.StepExecutionResult
+import com.facebook.buck.step.StepExecutionResults
+import com.facebook.buck.step.isolatedsteps.IsolatedStep
+import java.io.IOException
+
+/** Creates a symlink from a desired path to an existing path. */
+data class SymlinkIsolatedStep(val existingPath: RelPath, val desiredPath: RelPath) : IsolatedStep {
+  override fun getShortName(): String {
+    return "symlink_file"
+  }
+
+  @Throws(IOException::class)
+  override fun executeIsolatedStep(context: IsolatedExecutionContext): StepExecutionResult {
+    val ruleCellRoot = context.ruleCellRoot
+
+    val existingAbsPath =
+        ProjectFilesystemUtils.getAbsPathForRelativePath(ruleCellRoot, existingPath)
+    val desiredAbsPath = ProjectFilesystemUtils.getAbsPathForRelativePath(ruleCellRoot, desiredPath)
+
+    ProjectFilesystemUtils.createSymLink(
+        ruleCellRoot,
+        desiredAbsPath.path,
+        existingAbsPath.path, /* force */
+        true,
+    )
+
+    return StepExecutionResults.SUCCESS
+  }
+
+  override fun getIsolatedStepDescription(context: IsolatedExecutionContext): String {
+    val ruleCellRoot = context.ruleCellRoot
+    return java.lang.String.join(
+        " ",
+        "ln",
+        "-f",
+        "-s",
+        ProjectFilesystemUtils.getAbsPathForRelativePath(ruleCellRoot, existingPath).toString(),
+        ProjectFilesystemUtils.getAbsPathForRelativePath(ruleCellRoot, desiredPath).toString(),
+    )
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/ZipIsolatedStep.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/ZipIsolatedStep.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/common/ZipIsolatedStep.kt
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps.common
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext
+import com.facebook.buck.core.filesystems.AbsPath
+import com.facebook.buck.io.file.PathMatcher
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils
+import com.facebook.buck.step.StepExecutionResult
+import com.facebook.buck.step.StepExecutionResults
+import com.facebook.buck.step.isolatedsteps.IsolatedStep
+import com.facebook.buck.util.zip.CustomZipEntryWithPath
+import com.facebook.buck.util.zip.Zip
+import com.facebook.buck.util.zip.ZipCompressionLevel
+import com.facebook.buck.util.zip.ZipOutputStreams
+import com.facebook.buck.util.zip.ZipOutputStreams.HandleDuplicates
+import com.google.common.collect.ImmutableSet
+import java.io.BufferedOutputStream
+import java.io.IOException
+import java.nio.file.Path
+import java.util.TreeMap
+
+/**
+ * Creates or updates a zip archive.
+ *
+ * Note that paths added to the archive are always relative to the working directory.<br></br> For
+ * example, if you're in `/dir` and you add `file.txt`, you get an archive containing just the file.
+ * If you were in `/` and added `dir/file.txt`, you would get an archive containing the file within
+ * a directory.
+ */
+data class ZipIsolatedStep(
+    val rootPath: AbsPath,
+    val pathToZipFile: Path,
+    val ignoredPaths: ImmutableSet<PathMatcher>,
+    val paths: ImmutableSet<Path>,
+    val junkPaths: Boolean,
+    val compressionLevel: ZipCompressionLevel,
+    val baseDir: Path,
+) : IsolatedStep {
+  @Throws(IOException::class, InterruptedException::class)
+  override fun executeIsolatedStep(context: IsolatedExecutionContext): StepExecutionResult {
+    // Delete any stale zip file from a previous interrupted build.
+    // This can happen when ctrl+c interrupts a build mid-execution.
+    if (ProjectFilesystemUtils.exists(rootPath, pathToZipFile)) {
+      ProjectFilesystemUtils.deleteFileAtPath(rootPath, pathToZipFile)
+    }
+
+    val entries: Map<String, CustomZipEntryWithPath> = TreeMap()
+
+    BufferedOutputStream(ProjectFilesystemUtils.newFileOutputStream(rootPath, pathToZipFile)).use {
+        baseOut ->
+      ZipOutputStreams.newOutputStream(baseOut, HandleDuplicates.THROW_EXCEPTION).use { out ->
+        /* TODO: Make this logic to avoid using exceptions.
+         * If walking the file directory throws, then an empty jar file is still created.
+         */
+        Zip.walkBaseDirectoryToCreateEntries(
+            rootPath,
+            entries,
+            baseDir,
+            ignoredPaths,
+            paths,
+            junkPaths,
+            compressionLevel,
+        )
+        Zip.writeEntriesToZip(rootPath, out, entries)
+      }
+    }
+    return StepExecutionResults.SUCCESS
+  }
+
+  override fun getIsolatedStepDescription(context: IsolatedExecutionContext): String {
+    val args = StringBuilder("zip ")
+
+    // Don't add extra fields, neither do the Android tools.
+    args.append("-X ")
+
+    // recurse
+    args.append("-r ")
+
+    // compression level
+    args.append("-").append(compressionLevel).append(" ")
+
+    // junk paths
+    if (junkPaths) {
+      args.append("-j ")
+    }
+
+    // destination archive
+    args.append(pathToZipFile).append(" ")
+
+    // files to add to archive
+    if (paths.isEmpty()) {
+      // Add the contents of workingDirectory to archive.
+      args.append("-i* ")
+      args.append(". ")
+    } else {
+      // Add specified paths, relative to workingDirectory.
+      for (path in paths) {
+        args.append(path).append(" ")
+      }
+    }
+
+    return args.toString()
+  }
+
+  override fun getShortName(): String {
+    return "zip"
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/BUCK
@@ -0,0 +1,28 @@
+load(
+    "@prelude//toolchains/android/tools:build_rules.bzl",
+    "buck_java_library",
+)
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "java",
+    srcs = glob(["*.java"]),
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/...",
+        "prelude//toolchains/android/test/com/facebook/buck/...",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:support",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps:isolatedsteps",
+        "prelude//toolchains/android/src/com/facebook/buck/step/isolatedsteps/common:common",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/JarDirectoryStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/JarDirectoryStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/JarDirectoryStep.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps.java;
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.jvm.java.JarParameters;
+import com.facebook.buck.step.StepExecutionResult;
+import com.facebook.buck.step.StepExecutionResults;
+import com.facebook.buck.step.isolatedsteps.IsolatedStep;
+import com.facebook.buck.util.zip.JarBuilder;
+import com.google.common.base.MoreObjects;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/** Creates a JAR file from a collection of directories/ZIP/JAR files. */
+public class JarDirectoryStep implements IsolatedStep {
+
+  private final JarParameters parameters;
+
+  private final ImmutableSet<AbsPath> extraEntriesToJar;
+
+  /**
+   * Creates a JAR from the specified entries (most often, classpath entries).
+   *
+   * <p>If an entry is a directory, then its files are traversed and added to the generated JAR.
+   *
+   * <p>If an entry is a file, then it is assumed to be a ZIP/JAR file, and its entries will be read
+   * and copied to the generated JAR. @Param parameters the parameters that describe how to create
+   * the jar.
+   */
+  public JarDirectoryStep(JarParameters parameters, ImmutableSet<AbsPath> extraEntriesToJar) {
+    this.parameters = parameters;
+    this.extraEntriesToJar = extraEntriesToJar;
+  }
+
+  public JarDirectoryStep(JarParameters parameters) {
+    this(parameters, ImmutableSet.of());
+  }
+
+  @Override
+  public String getShortName() {
+    return "jar";
+  }
+
+  @Override
+  public String getIsolatedStepDescription(IsolatedExecutionContext context) {
+    Optional<RelPath> manifestFile = parameters.getManifestFile();
+    return String.join(
+        " ",
+        "jar",
+        manifestFile.map(ignore -> "cfm").orElse("cf"),
+        parameters.getJarPath().toString(),
+        manifestFile.map(RelPath::toString).orElse(""),
+        parameters.getEntriesToJar().stream()
+            .map(RelPath::toString)
+            .collect(Collectors.joining(" ")));
+  }
+
+  @Override
+  public StepExecutionResult executeIsolatedStep(IsolatedExecutionContext context)
+      throws IOException {
+    AbsPath root = context.getRuleCellRoot();
+    new JarBuilder()
+        .setEntriesToJar(extraEntriesToJar.stream())
+        .setEntriesToJar(parameters.getEntriesToJar().stream().map(root::resolve))
+        .setOverrideEntriesToJar(parameters.getOverrideEntriesToJar().stream().map(root::resolve))
+        .setMainClass(parameters.getMainClass().orElse(null))
+        .setManifestFile(
+            parameters.getManifestFile().map(root::resolve).map(AbsPath::getPath).orElse(null))
+        .setShouldMergeManifests(parameters.getMergeManifests())
+        .setShouldHashEntries(parameters.getHashEntries())
+        .setRemoveEntryPredicate(parameters.getRemoveEntryPredicate())
+        .createJarFile(root.resolve(parameters.getJarPath()).getPath());
+
+    return StepExecutionResults.SUCCESS;
+  }
+
+  @Override
+  public String toString() {
+    return MoreObjects.toStringHelper(this).add("parameters", parameters).toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/MakeMissingOutputsStep.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/MakeMissingOutputsStep.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/step/isolatedsteps/java/MakeMissingOutputsStep.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.step.isolatedsteps.java;
+
+import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext;
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.step.StepExecutionResult;
+import com.facebook.buck.step.StepExecutionResults;
+import com.facebook.buck.step.isolatedsteps.common.AbstractIsolatedExecutionStep;
+import java.io.IOException;
+
+/** Make Missing Output directories step. */
+public class MakeMissingOutputsStep extends AbstractIsolatedExecutionStep {
+
+  private final RelPath annotationsPath;
+
+  public MakeMissingOutputsStep(RelPath annotationsPath) {
+    super("make_missing_outputs");
+    this.annotationsPath = annotationsPath;
+  }
+
+  @Override
+  public StepExecutionResult executeIsolatedStep(IsolatedExecutionContext context)
+      throws IOException {
+    AbsPath root = context.getRuleCellRoot();
+    if (!ProjectFilesystemUtils.exists(root, annotationsPath.getPath())) {
+      ProjectFilesystemUtils.mkdirs(root, annotationsPath.getPath());
+    }
+    return StepExecutionResults.SUCCESS;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/test/result/type/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/result/type/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/result/type/BUCK
@@ -0,0 +1,20 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "type",
+    srcs = glob(["*.java"]),
+    # This target gets pulled in by ideabuck, which can't move to Java 11 yet, so explicitly target 8.
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [],  # This list is to remain empty. See src/com/facebook/buck/testrunner/BUCK.
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/test/result/type/ResultType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/result/type/ResultType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/result/type/ResultType.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.test.result.type;
+
+/** The kind of result */
+public enum ResultType {
+
+  // First, three different reasons why the tests weren't even attempted:
+
+  /**
+   * The test was not run because the user chose to run tests with the --dry-run flag, which caused
+   * the test runner to print out the names of tests that *would* have run without actually running
+   * them.
+   */
+  DRY_RUN,
+  /** The test was not run because it was excluded by the user */
+  EXCLUDED,
+  /**
+   * The test was not run because it was excluded in source code, such as with JUnit's {@link
+   * org.junit.Ignore} annotation or TestNG's {@link org.testng.annotations.Test#enabled()} field.
+   */
+  DISABLED,
+
+  // Then, three different outcomes when the tests were attempted:
+
+  /**
+   * The test was attempted but did not run to completion. It was aborted because a
+   * precondition/assumption of the test failed, see {@link org.junit.Assume}.
+   */
+  ASSUMPTION_VIOLATION,
+  /**
+   * The test ran, but it failed with either an assertion error or an unexpected uncaught exception.
+   * Note that JUnit3 distinguishes between these outcomes (FAILURE and ERROR), while JUnit4 does
+   * not.
+   */
+  FAILURE,
+  /** The test ran successfully. */
+  SUCCESS
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "selectors",
+    srcs = glob(["*.java"]),
+    required_for_source_only_abi = True,
+    # This target is pulled in by testrunner, which needs to compile against Java 8.
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/test/selectors:selectors",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [],  # This list is to remain empty. See src/com/facebook/buck/testrunner/BUCK.
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/Nullable.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/Nullable.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/Nullable.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.test.selectors;
+
+/**
+ * Defining @Nullable locally here because we cannot import javax.annotation.Nullable; according to
+ * comment in src/com/facebook/buck/test/selectors/BUCK
+ */
+public @interface Nullable {}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/PatternTestSelector.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/PatternTestSelector.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/PatternTestSelector.java
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.test.selectors;
+
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+/**
+ * A {@link TestDescription} will match if this selector's class-part is a substring of the {@link
+ * TestDescription}'s full class-name, or if this selector's class-name, when interpreted as a
+ * java.util.regex regular-expression, matches the {@link TestDescription}'s full class-name.
+ *
+ * <p>(The same rules apply for the method-name as well. If this selector's class-part or
+ * method-part are null, all class-names or method-names will match.)
+ */
+public class PatternTestSelector implements TestSelector {
+
+  static final PatternTestSelector INCLUDE_EVERYTHING = new PatternTestSelector(true, null, null);
+  static final PatternTestSelector EXCLUDE_EVERYTHING = new PatternTestSelector(false, null, null);
+
+  private final boolean inclusive;
+  @Nullable private final Pattern classPattern;
+  @Nullable private final Pattern methodPattern;
+
+  private PatternTestSelector(
+      boolean inclusive, @Nullable Pattern classPattern, @Nullable Pattern methodPattern) {
+    this.inclusive = inclusive;
+    this.classPattern = classPattern;
+    this.methodPattern = methodPattern;
+  }
+
+  /**
+   * Build a {@link PatternTestSelector} from the given String. Selector strings should be of the
+   * form "[is-exclusive][class-part]#[method-part]". If "[is-exclusive]" is a "!" then this
+   * selector will exclude tests, otherwise it will include tests.
+   *
+   * <p>If the class-part (or method-part) are omitted, then all classes or methods will match.
+   * Consequently "#" means "include everything" and "!#" means "exclude everything".
+   *
+   * <p>If the selector string doesn't contain a "#" at all, it is interpreted as a class-part.
+   *
+   * @param rawSelectorString An unparsed selector string.
+   */
+  public static TestSelector buildFromSelectorString(String rawSelectorString) {
+    if (rawSelectorString == null || rawSelectorString.isEmpty()) {
+      throw new RuntimeException("Cannot build from a null or empty string!");
+    }
+
+    boolean isInclusive = true;
+    String remainder;
+    if (rawSelectorString.charAt(0) == '!') {
+      isInclusive = false;
+      remainder = rawSelectorString.substring(1);
+    } else {
+      remainder = rawSelectorString;
+    }
+    // Reuse universal inclusion
+    if (remainder.equals("#")) {
+      return isInclusive ? INCLUDE_EVERYTHING : EXCLUDE_EVERYTHING;
+    }
+
+    Pattern classPattern;
+    Pattern methodPattern = null;
+    // we only apply splitting once. parameterized tests can have parameterization names that
+    // contains the symbol "#" in its method. e.g ClassTest#methodTest[Param#name]. So we should
+    // only split on the first "#" as class names cannot contain that symbol.
+    String[] parts = remainder.split("#", 2);
+
+    try {
+      if (parts.length == 1) {
+        // "com.example.Test", "com.example.Test#"
+        classPattern = getPatternOrNull(parts[0]);
+      } else {
+        if (parts[1].startsWith("#")) {
+          throw new TestSelectorParseException(
+              String.format("Invalid method pattern ## in %s", rawSelectorString));
+        }
+        // "com.example.Test#testX", "#testX", "#"
+        classPattern = getPatternOrNull(parts[0]);
+        methodPattern = getPatternOrNull(parts[1]);
+      }
+    } catch (PatternSyntaxException e) {
+      throw new TestSelectorParseException(
+          String.format("Regular expression error in '%s': %s", rawSelectorString, e.getMessage()));
+    }
+
+    return new PatternTestSelector(isInclusive, classPattern, methodPattern);
+  }
+
+  @Override
+  public String getRawSelector() {
+    StringBuilder builder = new StringBuilder();
+    if (!inclusive) {
+      builder.append('!');
+    }
+    if (classPattern != null) {
+      builder.append(classPattern);
+    }
+    builder.append('#');
+    if (methodPattern != null) {
+      builder.append(methodPattern);
+    }
+    return builder.toString();
+  }
+
+  @Nullable
+  private static Pattern getPatternOrNull(String string) {
+    if (string.isEmpty()) {
+      return null;
+    } else {
+      if (!string.endsWith("$")) {
+        string = string + "$";
+      }
+      return Pattern.compile(string);
+    }
+  }
+
+  @Override
+  public String getExplanation() {
+    if (isMatchAnyClass() && isMatchAnyMethod()) {
+      return isInclusive() ? "include everything else" : "exclude everything else";
+    }
+    return String.format(
+        "%s class:%s method:%s",
+        isInclusive() ? "include" : "exclude",
+        isMatchAnyClass() ? "<any>" : classPattern,
+        isMatchAnyMethod() ? "<any>" : methodPattern);
+  }
+
+  @Override
+  public boolean isInclusive() {
+    return inclusive;
+  }
+
+  @Override
+  public boolean isMatchAnyClass() {
+    return classPattern == null;
+  }
+
+  @Override
+  public boolean isMatchAnyMethod() {
+    return methodPattern == null;
+  }
+
+  @Override
+  public boolean matches(TestDescription description) {
+    return matchesClassName(description.getClassName())
+        && matchesMethodName(description.getMethodName());
+  }
+
+  @Override
+  public boolean matchesClassName(String className) {
+    if (classPattern == null || className == null) {
+      return true;
+    }
+    return classPattern.matcher(className).find();
+  }
+
+  @Override
+  public boolean containsClassPath(String classPath) {
+    if (classPattern == null) {
+      return true;
+    }
+    // Find occurrence of "\$" in the pattern, which indicates a nested class
+    String[] outerInnerPatterns = classPattern.toString().split("\\\\\\$");
+    if (outerInnerPatterns.length == 2) {
+      // If we have an outer class, we should ensure that we are treating the outer class pattern as
+      // matching the end of the classpath, so add a "$"
+      // e.g: pattern of "Foo\$Bar" means it should only match outer classpaths of "Foo", not "FooF"
+      outerInnerPatterns[0] += "$";
+    }
+    return Pattern.compile(outerInnerPatterns[0]).matcher(classPath).find();
+  }
+
+  private boolean matchesMethodName(String methodName) {
+    if (methodPattern == null || methodName == null) {
+      return true;
+    }
+    return methodPattern.matcher(methodName).find();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/SimpleTestSelector.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/SimpleTestSelector.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/SimpleTestSelector.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.test.selectors;
+
+import java.util.Objects;
+
+/**
+ * A {@link TestDescription} will match if this selector's class-part is identical to the
+ * TestDescriptions class name (same for the method name).
+ */
+public class SimpleTestSelector implements TestSelector {
+  private final @Nullable String className;
+  private final @Nullable String methodName;
+
+  public SimpleTestSelector(@Nullable String className, @Nullable String methodName) {
+    this.className = className;
+    this.methodName = methodName;
+  }
+
+  @Override
+  public String getRawSelector() {
+    // This method is effectively used by Buck to plumb the args passed to the '-f' option into
+    // the --test-selectors option that is passed to the junit test runner.
+    // The Simple selector is intended to be only used by whoever directly calls the junit runner.
+    throw new UnsupportedOperationException("SimpleTestSelector does not have a raw selector.");
+  }
+
+  @Override
+  public String getExplanation() {
+    return String.format(
+        "class:%s method:%s",
+        isMatchAnyClass() ? "<any>" : className, isMatchAnyMethod() ? "<any>" : methodName);
+  }
+
+  @Override
+  public boolean isInclusive() {
+    return true;
+  }
+
+  @Override
+  public boolean isMatchAnyClass() {
+    return className == null;
+  }
+
+  @Override
+  public boolean isMatchAnyMethod() {
+    return methodName == null;
+  }
+
+  @Override
+  public boolean matches(TestDescription description) {
+    return matchesClassName(description.getClassName())
+        && matchesMethodName(description.getMethodName());
+  }
+
+  @Override
+  public boolean matchesClassName(String thatClassName) {
+    if (className == null) {
+      return true;
+    }
+    return Objects.equals(this.className, thatClassName);
+  }
+
+  @Override
+  public boolean containsClassPath(String classPath) {
+    // classpath of com.example.A should match selectors matching com.example.A and
+    // com.example.A.Inner
+    if (className == null) {
+      return true;
+    }
+    return className.startsWith(classPath);
+  }
+
+  private boolean matchesMethodName(String thatMethodName) {
+    if (methodName == null) {
+      return true;
+    }
+    return Objects.equals(this.methodName, thatMethodName);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestDescription.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestDescription.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestDescription.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.test.selectors;
+
+import java.util.Objects;
+
+/**
+ * A non-JUnit specific way of describing a test-method inside a test-class. This meants that the
+ * test-selectors code does not need a dependency on JUnit.
+ */
+public class TestDescription {
+
+  private final String className;
+  private final String methodName;
+
+  public TestDescription(String className, String methodName) {
+    this.className = className;
+    this.methodName = methodName;
+  }
+
+  public String getClassName() {
+    return className;
+  }
+
+  public String getMethodName() {
+    return methodName;
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (!(obj instanceof TestDescription)) {
+      return false;
+    }
+    TestDescription other = (TestDescription) obj;
+    return Objects.equals(this.className, other.className)
+        && Objects.equals(this.methodName, other.methodName);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(this.className, this.methodName);
+  }
+
+  @Override
+  public String toString() {
+    return String.format("%s.%s", this.className, this.methodName);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelector.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelector.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelector.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.test.selectors;
+
+/**
+ * A way of matching a test-method in a test-class, and saying whether or not to include any matches
+ * in a test run.
+ */
+public interface TestSelector {
+  String getRawSelector();
+
+  String getExplanation();
+
+  boolean isInclusive();
+
+  boolean isMatchAnyClass();
+
+  boolean isMatchAnyMethod();
+
+  /**
+   * Whether this {@link TestSelector} matches the given {@link TestDescription}. A class or method
+   * name being null in the {@link TestDescription} means that it will match anything.
+   *
+   * @param description the {@link TestDescription} to match
+   * @return true if this selector matches the given {@link TestDescription}
+   */
+  boolean matches(TestDescription description);
+
+  /**
+   * @return true if the given className matches this selector
+   */
+  boolean matchesClassName(String className);
+
+  /**
+   * @return true if the given classpath may be required by any classes that matches this selector
+   */
+  boolean containsClassPath(String classPath);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelectorList.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelectorList.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelectorList.java
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.test.selectors;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * A collection of {@link PatternTestSelector} instances which, as a group, can decide whether or
+ * not to include a given {@link TestDescription}.
+ */
+public class TestSelectorList {
+
+  public static final TestSelectorList EMPTY = TestSelectorList.builder().build();
+
+  /**
+   * Test selector strings are parsed in two places: (i) by "buck test" when it is first run, to
+   * validate that the selectors make sense; and (ii) by the JUnitStep's JUnitRunner, which is what
+   * actually does the test selecting.
+   *
+   * <p>We keep a list of the raw selectors used to build out List of TestSelectors so that they can
+   * be passed from (i) to (ii). This is expensive in that it wastes time re-parsing selectors, but
+   * it means that if the input is an "@/tmp/long-list-of-tests.txt" then re-using that terse
+   * argument keeps the "JUnitSteps" Junit java command line nice and short.
+   */
+  private final List<TestSelector> testSelectors;
+
+  private final boolean defaultIsInclusive;
+
+  private TestSelectorList(List<TestSelector> testSelectors, boolean defaultIsInclusive) {
+    this.testSelectors = testSelectors;
+    this.defaultIsInclusive = defaultIsInclusive;
+  }
+
+  private TestSelector defaultSelector() {
+    return defaultIsInclusive
+        ? PatternTestSelector.INCLUDE_EVERYTHING
+        : PatternTestSelector.EXCLUDE_EVERYTHING;
+  }
+
+  public TestSelector findSelector(TestDescription description) {
+    for (TestSelector testSelector : testSelectors) {
+      if (testSelector.matches(description)) {
+        return testSelector;
+      }
+    }
+    return defaultSelector();
+  }
+
+  public boolean isIncluded(TestDescription description) {
+    return findSelector(description).isInclusive();
+  }
+
+  /**
+   * Returns true if it is *possible* for the given classname to include tests.
+   *
+   * <p>Before we go through the hassle of loading a class, confirm that it's possible for it to run
+   * tests.
+   */
+  public boolean possiblyIncludesClassName(String className) {
+    for (TestSelector testSelector : testSelectors) {
+      if (testSelector.containsClassPath(className)) {
+        if (testSelector.isInclusive()) {
+          return true;
+        }
+        if (testSelector.isMatchAnyMethod()) {
+          return false;
+        }
+      }
+    }
+    return defaultSelector().isInclusive();
+  }
+
+  public List<String> getExplanation() {
+    List<String> lines = new ArrayList<>();
+    for (TestSelector testSelector : testSelectors) {
+      lines.add(testSelector.getExplanation());
+    }
+    lines.add(defaultSelector().getExplanation());
+    return lines;
+  }
+
+  public List<String> getRawSelectors() {
+    List<String> rawSelectors = new ArrayList<>();
+    for (TestSelector testSelector : testSelectors) {
+      String rawSelector = testSelector.getRawSelector();
+      rawSelectors.add(rawSelector);
+    }
+    return rawSelectors;
+  }
+
+  public boolean isEmpty() {
+    return testSelectors.isEmpty();
+  }
+
+  public static TestSelectorList empty() {
+    return EMPTY;
+  }
+
+  public static Builder builder() {
+    return new Builder();
+  }
+
+  /**
+   * Build a new {@link TestSelectorList} from a list of strings, each of which is parsed by {@link
+   * PatternTestSelector}.
+   *
+   * <p>If any of the selectors is an inclusive selector, everything else will be excluded.
+   * Conversely, if all of the selectors are exclusive, then everything else will be included by
+   * default.
+   */
+  public static class Builder {
+
+    private final List<TestSelector> testSelectors;
+
+    protected Builder() {
+      testSelectors = new ArrayList<>();
+    }
+
+    private Builder addRawSelector(String rawSelector) {
+      if (rawSelector.charAt(0) == ':') {
+        try {
+          String pathString = rawSelector.substring(1);
+          if (pathString.isEmpty()) {
+            throw new TestSelectorParseException("Doesn't mention a path!");
+          }
+          File file = new File(pathString);
+          loadFromFile(file);
+        } catch (TestSelectorParseException | IOException e) {
+          String message =
+              String.format("Error with test-selector '%s': %s", rawSelector, e.getMessage());
+          throw new RuntimeException(message, e);
+        }
+        return this;
+      } else {
+        TestSelector testSelector = PatternTestSelector.buildFromSelectorString(rawSelector);
+        this.testSelectors.add(testSelector);
+      }
+      return this;
+    }
+
+    public Builder addRawSelectors(String... rawSelectors) {
+      return addRawSelectors(Arrays.asList(rawSelectors));
+    }
+
+    public Builder addRawSelectors(Collection<String> rawTestSelectors) {
+      rawTestSelectors.forEach(this::addRawSelector);
+      return this;
+    }
+
+    public Builder addSimpleTestSelector(String simpleSelector) {
+      // Parameterized tests can have parameterization names that contains ","s, which conflicts
+      // with the character we chose for dividing class and method names. We should split on only
+      // the first ",", which is guaranteed to be the class to method splitter, as the class name
+      // cannot contain these characters
+      String[] selectorParts = simpleSelector.split(",", 2);
+      String className = selectorParts[0];
+      String methodName = selectorParts[1];
+      this.testSelectors.add(new SimpleTestSelector(className, methodName));
+      return this;
+    }
+
+    public Builder addBase64EncodedTestSelector(String b64Selector) {
+      String[] selectorParts = b64Selector.split(",");
+      if (selectorParts.length != 2) {
+        throw new IllegalArgumentException();
+      }
+      String className = selectorParts[0];
+      String methodName = selectorParts[1];
+      Base64.Decoder decoder = Base64.getDecoder();
+      String decodedClassName = new String(decoder.decode(className), StandardCharsets.UTF_8);
+      String decodedMethodName = new String(decoder.decode(methodName), StandardCharsets.UTF_8);
+      this.testSelectors.add(new SimpleTestSelector(decodedClassName, decodedMethodName));
+      return this;
+    }
+
+    Builder loadFromFile(File file) throws IOException {
+      try (FileReader tempReader = new FileReader(file);
+          BufferedReader in = new BufferedReader(tempReader)) {
+        String line;
+        int lineNumber = 1;
+
+        while ((line = in.readLine()) != null) {
+          try {
+            addRawSelector(line.trim());
+            lineNumber++;
+          } catch (TestSelectorParseException e) {
+            String message =
+                String.format("Test selector error in %s at line %d", file, lineNumber);
+            throw new TestSelectorParseException(message, e);
+          }
+        }
+      } catch (IOException e) {
+        throw e;
+      }
+      return this;
+    }
+
+    public TestSelectorList build() {
+      boolean defaultIsInclusive = true;
+      List<TestSelector> selectorsToUse = new ArrayList<>();
+      for (TestSelector testSelector : testSelectors) {
+        // Default to being inclusive only if all selectors are *exclusive*.
+        defaultIsInclusive = defaultIsInclusive && !testSelector.isInclusive();
+        // If a selector is universal (matches every class and method), no need to look further
+        if (testSelector.isMatchAnyClass() && testSelector.isMatchAnyMethod()) {
+          defaultIsInclusive = testSelector.isInclusive();
+          break;
+        }
+        selectorsToUse.add(testSelector);
+      }
+      return new TestSelectorList(selectorsToUse, defaultIsInclusive);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelectorParseException.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelectorParseException.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/test/selectors/TestSelectorParseException.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.test.selectors;
+
+/** Errors specific to parsing test selectors. */
+public class TestSelectorParseException extends RuntimeException {
+  public TestSelectorParseException(String message) {
+    super(message);
+  }
+
+  public TestSelectorParseException(String message, Exception cause) {
+    super(message, cause);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/BUCK
@@ -0,0 +1,32 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "testresultsoutput",
+    srcs = [
+        "TestResultsOutputEvent.java",
+        "TestResultsOutputSender.java",
+    ],
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/testresultsoutput:testresultsoutput",
+    ],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/testrunner:instrumentation",
+        "prelude//toolchains/android/src/com/facebook/buck/testrunner:junit",
+        "prelude//toolchains/android/src/com/facebook/buck/testrunner:timeout",
+        "prelude//toolchains/android/test/com/facebook/buck/testresultsoutput:testresultsoutput",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:testrunner",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:tpx_timeout_buffer_manager_test",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:jackson-core",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/TestResultsOutputEvent.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/TestResultsOutputEvent.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/TestResultsOutputEvent.java
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testresultsoutput;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonGenerator;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.Optional;
+
+/**
+ * TestResultsOutputEvent implements the following thrift schema.
+ * https://www.internalfb.com/code/fbsource/[8bed6a02e7ed]/fbcode/testinfra/if/test_result_output_spec.thrift
+ *
+ * <p>It keeps and serializes events pertaining to the execution of test cases and replicates
+ * instead of using the thrift structs directly to avoid the need for a dependency on fbcode.
+ */
+public class TestResultsOutputEvent {
+  private static final JsonFactory jsonFactory = new JsonFactory();
+
+  /** Represents a test event, which can be either a start or finish event. */
+  public static class TestEvent {
+    public StartEvent start;
+    public FinishEvent finish;
+  }
+
+  /** Represents a start event for a test. */
+  public static class StartEvent {
+    public String name;
+
+    /** The time at which the test started, in milliseconds since Unix epoch. */
+    public Long startedTime;
+
+    /**
+     * Creates a new start event with the given name and started time.
+     *
+     * @param name the name of the test
+     * @param startedTime the time at which the test started, in milliseconds since Unix epoch
+     */
+    public StartEvent(String name, long startedTime) {
+      this.name = name;
+      this.startedTime = startedTime;
+    }
+
+    /**
+     * Serializes this start event to a JSON byte array.
+     *
+     * @return the JSON byte array
+     * @throws IOException if there is an error serializing the event
+     */
+    public byte[] toJsonBytes() throws IOException {
+      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+      try (JsonGenerator generator = jsonFactory.createGenerator(outputStream)) {
+        generator.writeStartObject();
+        generator.writeObjectFieldStart("start");
+        generator.writeStringField("name", name);
+        generator.writeNumberField("started_time", startedTime);
+        generator.writeEndObject();
+        generator.writeEndObject();
+      }
+      return outputStream.toByteArray();
+    }
+  }
+
+  /** Status of a run failure. */
+  public enum RunFailureStatus {
+    TIMEOUT(1),
+    FATAL(2),
+    INFRA_FAILURE(3);
+
+    private final int value;
+
+    RunFailureStatus(int value) {
+      this.value = value;
+    }
+
+    public int getValue() {
+      return value;
+    }
+  }
+
+  /** Represents a run failure event (not specific to any test case). */
+  public static class RunFailureEvent {
+    public RunFailureStatus status;
+    public long time;
+    public String details;
+    public String stacktrace;
+
+    /**
+     * Creates a new run failure event with the given parameters.
+     *
+     * @param status the status of the run failure (TIMEOUT or FATAL)
+     * @param time the time the failure occurred, in milliseconds since Unix epoch
+     * @param details human-readable description of the failure
+     * @param stacktrace optional stack trace (can be null)
+     */
+    public RunFailureEvent(RunFailureStatus status, long time, String details, String stacktrace) {
+      this.status = status;
+      this.time = time;
+      this.details = details;
+      this.stacktrace = stacktrace;
+    }
+
+    /**
+     * Serializes this run failure event to a JSON byte array.
+     *
+     * @return the JSON byte array
+     * @throws IOException if there is an error serializing the event
+     */
+    public byte[] toJsonBytes() throws IOException {
+      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+      try (JsonGenerator generator = jsonFactory.createGenerator(outputStream)) {
+        generator.writeStartObject();
+        generator.writeObjectFieldStart("run_failure");
+        generator.writeNumberField("status", status.getValue());
+        generator.writeNumberField("time", time);
+        generator.writeStringField("details", details);
+        if (stacktrace != null) {
+          generator.writeStringField("stacktrace", stacktrace);
+        }
+        generator.writeEndObject();
+        generator.writeEndObject();
+      }
+      return outputStream.toByteArray();
+    }
+  }
+
+  /** Represents the status of a test. */
+  public enum TestStatus {
+    PASS(0),
+    FAIL(1),
+    SKIP(2),
+    OMIT(4);
+
+    private final int value;
+
+    /**
+     * Creates a new test status with the given value.
+     *
+     * @param value the integer value of the status
+     */
+    TestStatus(int value) {
+      this.value = value;
+    }
+
+    /**
+     * Returns the integer value of the status.
+     *
+     * @return the integer value of the status
+     */
+    public int getValue() {
+      return value;
+    }
+  };
+
+  /** Represents a finish event for a test. */
+  public static class FinishEvent {
+    public String name;
+    public TestStatus status;
+
+    /** The time at which the test ended, in milliseconds since Unix epoch. */
+    public long endedTime;
+
+    /** The duration of the test, in milliseconds since the start of the test. */
+    public long duration;
+
+    /** A message associated with the test result, or null if there is no message. */
+    public String message;
+
+    /**
+     * Creates a new finish event with the given parameters.
+     *
+     * @param name the name of the test
+     * @param status the status of the test
+     * @param endedTime the time at which the test ended, in milliseconds since Unix epoch
+     * @param duration the duration of the test, in milliseconds since the start of the test
+     * @param message a message associated with the test result, or null if there is no message
+     */
+    public FinishEvent(
+        String name, TestStatus status, long endedTime, long duration, Optional<String> message) {
+      this.name = name;
+      this.status = status;
+      this.endedTime = endedTime;
+      this.duration = duration;
+      this.message = message.orElse(null);
+    }
+
+    /**
+     * Serializes this finish event to a JSON byte array.
+     *
+     * @return the JSON byte array
+     * @throws IOException if there is an error serializing the event
+     */
+    public byte[] toJsonBytes() throws IOException {
+      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+      try (JsonGenerator generator = jsonFactory.createGenerator(outputStream)) {
+        generator.writeStartObject();
+        generator.writeObjectFieldStart("finish");
+        generator.writeStringField("name", name);
+        generator.writeNumberField("status", status.getValue());
+        generator.writeNumberField("duration", duration);
+        if (message != null) {
+          generator.writeStringField("message", message);
+        }
+        generator.writeNumberField("ended_time", endedTime);
+        generator.writeEndObject();
+        generator.writeEndObject();
+      }
+      return outputStream.toByteArray();
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/TestResultsOutputSender.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/TestResultsOutputSender.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testresultsoutput/TestResultsOutputSender.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testresultsoutput;
+
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent.FinishEvent;
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent.RunFailureEvent;
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent.RunFailureStatus;
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent.StartEvent;
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent.TestStatus;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Optional;
+
+/**
+ * TestResultsOutputSender provides an interface for serializing test_result_output_spec.thrift Test
+ * Events.
+ */
+public class TestResultsOutputSender implements AutoCloseable {
+  private static final String TEST_RESULTS_OUTPUT_FILE_ENV_NAME = "TEST_RESULTS_OUTPUT_FILE";
+  private final FileOutputStream fileOutputStream;
+
+  /**
+   * Constructor for TestResultsOutputSender.
+   *
+   * @param fileOutputStream The FileOutputStream to write to.
+   */
+  public TestResultsOutputSender(FileOutputStream fileOutputStream) {
+    this.fileOutputStream = fileOutputStream;
+  }
+
+  @Override
+  public void close() throws IOException {
+    this.fileOutputStream.close();
+  }
+
+  /**
+   * Returns a TestResultsOutputSender object if the default environment variable is set.
+   *
+   * @return An optional TestResultsOutputSender object.
+   */
+  public static Optional<TestResultsOutputSender> fromDefaultEnvName() {
+    return fromEnvName(TEST_RESULTS_OUTPUT_FILE_ENV_NAME);
+  }
+
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  private static String getEnvValue(String envName) {
+    return System.getenv(envName);
+  }
+
+  /**
+   * Returns a TestResultsOutputSender object if the given environment variable is set.
+   *
+   * @param envName The name of the environment variable to check.
+   * @return An optional TestResultsOutputSender object.
+   */
+  public static Optional<TestResultsOutputSender> fromEnvName(String envName) {
+    return fromFilePath(getEnvValue(envName));
+  }
+
+  /**
+   * Creates a TestResultsOutputSender object from a file path.
+   *
+   * @param testResultsOutputFile The file path to create the TestResultsOutputSender from.
+   * @return An optional TestResultsOutputSender object.
+   */
+  public static Optional<TestResultsOutputSender> fromFilePath(String testResultsOutputFile) {
+    if (testResultsOutputFile == null) {
+      return Optional.empty();
+    }
+
+    try {
+      FileOutputStream fileOutputStream = new FileOutputStream(testResultsOutputFile);
+
+      TestResultsOutputSender testResultsOutputSender =
+          new TestResultsOutputSender(fileOutputStream);
+
+      return Optional.of(testResultsOutputSender);
+    } catch (FileNotFoundException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  /**
+   * Sends a test start event to the output file.
+   *
+   * @param name The name of the test.
+   * @param startedTime The time the test started, in milliseconds since Unix epoch.
+   */
+  public void sendTestStart(String name, long startedTime) {
+    StartEvent startEvent = new StartEvent(name, startedTime);
+
+    byte[] serialized;
+    try {
+      serialized = startEvent.toJsonBytes();
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+
+    try {
+      this.fileOutputStream.write(serialized);
+      this.fileOutputStream.write("\n".getBytes());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  /**
+   * Sends a test finish event to the output file.
+   *
+   * @param name The name of the test.
+   * @param status The status of the test.
+   * @param endedTime The time the test ended.
+   * @param duration The duration of the test.
+   * @param message An optional message associated with the test.
+   */
+  public void sendTestFinish(
+      String name, TestStatus status, long endedTime, long duration, Optional<String> message) {
+
+    FinishEvent finishEvent = new FinishEvent(name, status, endedTime, duration, message);
+
+    byte[] serialized;
+    try {
+      serialized = finishEvent.toJsonBytes();
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+
+    try {
+      this.fileOutputStream.write(serialized);
+      this.fileOutputStream.write("\n".getBytes());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  /**
+   * Sends a run failure event to the output file.
+   *
+   * @param status The status of the run failure (TIMEOUT or FATAL).
+   * @param time The time the failure occurred, in milliseconds since Unix epoch.
+   * @param details Human-readable description of the failure.
+   * @param stacktrace Optional stack trace (can be null).
+   */
+  public void sendRunFailure(
+      RunFailureStatus status, long time, String details, String stacktrace) {
+    RunFailureEvent event = new RunFailureEvent(status, time, details, stacktrace);
+
+    try {
+      byte[] serialized = event.toJsonBytes();
+      this.fileOutputStream.write(serialized);
+      this.fileOutputStream.write("\n".getBytes());
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BUCK
@@ -0,0 +1,300 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library", "buck_kotlin_library")
+load("@prelude//toolchains/android/tools/build_rules:fb_native.bzl", "fb_native")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "base",
+    srcs = [
+        "BaseRunner.java",
+        "CheckDependency.java",
+        "TestResult.java",
+        "TestXmlEscaper.java",
+    ],
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:junit_runner_test",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:testrunner",
+    ],
+    visibility = [
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:junit_runner_test",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:testrunner",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/test/result/type:type",
+        "prelude//toolchains/android/src/com/facebook/buck/test/selectors:selectors",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
+
+buck_kotlin_library(
+    name = "timeout",
+    srcs = [
+        "ThreadDumpUtils.kt",
+        "TpxTimeoutBufferManager.kt",
+    ],
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:tpx_timeout_buffer_manager_test",
+    ],
+    visibility = [
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:tpx_timeout_buffer_manager_test",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/testresultsoutput:testresultsoutput",
+    ],
+)
+
+fb_native.kotlin_library(
+    name = "per_test_coverage_base",
+    srcs = [
+        "BasePerTestCoverageRunListener.kt",
+        "PerTestCoverageExtension.kt",
+        "PerTestCoverageExtensionManager.kt",
+    ],
+    # Uses fb_native.kotlin_library (not buck_kotlin_library) with kotlin-stdlib in provided_deps:
+    # both consumers (prelude :junit, fbandroid :instrumentation) already package kotlin-stdlib at
+    # different Buck target paths, and shipping ours too breaks Android APK D8 dexing with
+    # duplicate types. Keep the bootstrap Kotlin toolchain in sync with buck_kotlin_library so tests
+    # that override the Java compiler mode don't analyze this target with mismatched Kotlin/Java
+    # compiler modes. The source also hand-rolls JSON instead of using jackson-core for the same
+    # reason.
+    _kotlin_toolchain = "toolchains//:kotlin_bootstrap",
+    provided_deps = [
+        "prelude//toolchains/android/third-party:kotlin-stdlib",
+    ],
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:per_test_coverage_base_test",
+    ],
+    visibility = [
+        "fbsource//fbandroid/java/com/facebook/testing/instrumentation/...",
+        "fbsource//fbandroid/java/com/facebook/testing/robolectric/resourceusage:resourceusage",
+        "fbsource//fbandroid/javatests/com/facebook/testing/instrumentation/...",
+        "prelude//toolchains/android/src/com/facebook/buck/testrunner:junit",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:per_test_coverage_base_test",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:per_test_coverage_listener_test",
+    ],
+    deps = [
+        "prelude//toolchains/android/third-party:junit",
+    ],
+)
+
+buck_kotlin_library(
+    name = "junit",
+    srcs = [
+        "BuckBlockJUnit4ClassRunner.java",
+        "JUnitMain.java",
+        "JUnitOptions.java",
+        "JUnitRunner.java",
+        "JUnitSupport.java",
+        "JUnitTpxStandardOutputListener.java",
+        "JavaUtilLoggingHelper.java",
+        "JulLogFormatter.java",
+        "JupiterMain.java",
+        "JupiterRunner.java",
+        "PerTestJUnitCoverageRunListener.kt",
+        "RobolectricTimeoutEnforcingRunListener.kt",
+        "SameThreadFailOnTimeout.java",
+        "SkipTestCondition.java",
+        "StandardOutputRecorder.java",
+        "TestRecorder.java",
+        "TpxStandardOutputTestListener.java",
+    ],
+    resources = glob(["META-INF/**/*"]),
+    resources_root = ".",
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:junit_runner_test",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:per_test_coverage_listener_test",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:testrunner",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:tpx_timeout_buffer_manager_test",
+    ],
+    visibility = [
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:junit_runner_test",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:per_test_coverage_listener_test",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:testrunner",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:tpx_timeout_buffer_manager_test",
+    ],
+    # IMPORTANT! This library limits itself to types that are available in both the JDK and Android
+    # Java API. The objective is to limit the set of files added to the ClassLoader that runs the
+    # test, as not to interfere with the results of the test.
+    deps = [
+        ":base",
+        ":per_test_coverage_base",
+        ":timeout",
+        # This is loaded by reflection. Joy.
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/runner:runner",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log/appendablelogrecord:appendablelogrecord",
+        "prelude//toolchains/android/src/com/facebook/buck/test/result/type:type",
+        "prelude//toolchains/android/src/com/facebook/buck/test/selectors:selectors",
+        "prelude//toolchains/android/src/com/facebook/buck/testresultsoutput:testresultsoutput",
+        "prelude//toolchains/android/third-party:jackson-core",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:junit",
+        "prelude//toolchains/android/third-party:junit-jupiter-engine",
+        "prelude//toolchains/android/third-party:junit-platform-launcher",
+        "prelude//toolchains/android/third-party:kotlin-stdlib",
+    ],
+)
+
+buck_kotlin_library(
+    name = "instrumentation",
+    srcs = [
+        "BuckXmlTestRunListener.java",
+        "CrashAnalyzer.java",
+        "CrashCapturer.java",
+        "DeviceRunner.java",
+        "InstrumentationMain.java",
+        "InstrumentationTestRunner.java",
+        "InstrumentationTimeoutEnforcingRunListener.kt",
+        "InstrumentationTpxStandardOutputTestListener.java",
+        "RunShellCommand.java",
+        "TpxStandardOutputTestListener.java",
+        "reportlayer/LogExtractorReportLayer.java",
+        "reportlayer/PerfettoReportLayer.java",
+        "reportlayer/ReportLayer.java",
+        "reportlayer/TombstonesReportLayer.java",
+        "reportlayer/VideoRecordingReportLayer.java",
+    ],
+    required_for_source_only_abi = True,
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:testrunner",
+    ],
+    visibility = [
+        "fbsource//fbandroid/instrumentation_tests/com/meta/instrumentation/host/...",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:testrunner",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/android:helpers",
+        "prelude//toolchains/android/src/com/facebook/buck/android:utils_api",
+        "prelude//toolchains/android/src/com/facebook/buck/testresultsoutput:testresultsoutput",
+        "prelude//toolchains/android/src/com/facebook/buck/util/escaper:bash",
+        "prelude//toolchains/android/third-party:ddmlib",
+        ":timeout",
+    ],
+)
+
+buck_java_library(
+    name = "instrumentation_for_clout",
+    srcs = [
+        "InstrumentationMainForClout.java",
+        "InstrumentationTestRunnerForClout.java",
+        "RunShellCommand.java",
+    ],
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = [
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:testrunner",
+    ],
+    deps = [
+        ":instrumentation",
+    ],
+)
+
+buck_java_library(
+    name = "testng",
+    srcs = [
+        "TestNGMain.java",
+        "TestNGRunner.java",
+    ],
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = [],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/test/result/type:type",
+        "prelude//toolchains/android/src/com/facebook/buck/test/selectors:selectors",
+        "prelude//toolchains/android/third-party:guice",
+        "prelude//toolchains/android/third-party:jsr305",
+        "prelude//toolchains/android/third-party:testng",
+        ":base",
+    ],
+)
+
+# Vanilla Java test runner binary without Android instrumentation
+buck_java_binary(
+    name = "testrunner-bin",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/test/result/type:type",
+        "prelude//toolchains/android/src/com/facebook/buck/test/selectors:selectors",
+        ":junit",
+        ":testng",
+    ],
+)
+
+# Android test runner binary with instrumentation support
+buck_java_binary(
+    name = "testrunner-bin-android",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/test/result/type:type",
+        "prelude//toolchains/android/src/com/facebook/buck/test/selectors:selectors",
+        ":instrumentation",
+        ":instrumentation_for_clout",
+        ":junit",
+        ":testng",
+    ],
+)
+
+# Strip out classes we don't want automatically added to the classpath for
+# tests, leaving just the extra buck classes.
+# This version is for vanilla Java tests.
+fb_native.zip_file(
+    name = "testrunner-bin-fixed",
+    out = "testrunner-bin-fixed.jar",
+    entries_to_exclude = [
+        "^(?!com/facebook/buck/|META-INF/services/org.junit.jupiter|com/fasterxml/jackson/core|kotlin/).*",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    zip_srcs = [
+        ":testrunner-bin",
+    ],
+)
+
+# Strip out classes we don't want automatically added to the classpath for
+# tests, leaving just the extra buck classes.
+# This version includes Android instrumentation support.
+fb_native.zip_file(
+    name = "testrunner-bin-android-fixed",
+    out = "testrunner-bin-android-fixed.jar",
+    entries_to_exclude = [
+        "^(?!com/facebook/buck/|META-INF/services/org.junit.jupiter|com/fasterxml/jackson/core|kotlin/).*",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    zip_srcs = [
+        ":testrunner-bin-android",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BasePerTestCoverageRunListener.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BasePerTestCoverageRunListener.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BasePerTestCoverageRunListener.kt
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner
+
+import java.io.BufferedWriter
+import java.io.Closeable
+import java.io.File
+import java.io.FileOutputStream
+import java.io.FileWriter
+import java.io.PrintWriter
+import java.security.MessageDigest
+import org.junit.runner.Description
+import org.junit.runner.Result
+import org.junit.runner.notification.RunListener
+
+/**
+ * Base class for per-test JaCoCo coverage `RunListener`s.
+ *
+ * Owns the shared lifecycle: setup and teardown dumps are attributed to the synthetic "main" row,
+ * each test gets its own `.exec` file, and `manifest.jsonl` maps TPX test names to exec files.
+ * Subclasses provide the [CoverageAgent], optional setup/teardown filename suffix, and any
+ * cross-process error reporting.
+ */
+abstract class BasePerTestCoverageRunListener(
+    protected val outputDir: File,
+    protected val agent: CoverageAgent,
+) : RunListener(), Closeable {
+
+  /** Abstraction over JaCoCo's runtime agent for testability. */
+  interface CoverageAgent {
+    fun reset()
+
+    fun dumpAndReset(): ByteArray?
+  }
+
+  /** First coverage error encountered, if any. Checked by the runner after test execution. */
+  var coverageError: Exception? = null
+    protected set
+
+  private val manifest: PrintWriter
+  private var runSuffix: String = ""
+
+  init {
+    check(outputDir.mkdirs() || outputDir.isDirectory) {
+      "Failed to create per-test coverage output directory: $outputDir"
+    }
+    manifest = PrintWriter(BufferedWriter(FileWriter(File(outputDir, "manifest.jsonl"))), true)
+  }
+
+  override fun testRunStarted(description: Description?) {
+    runSuffix = nextRunSuffix(description)
+    // Snapshot probes accumulated before any individual @Test ran (framework boot, class loading,
+    // static initializers, Application.onCreate on Android). Attributed to the synthetic "main"
+    // TPX row. Without this, the next testStarted's reset() would silently wipe them.
+    dumpExec(testName = "main", baseFileName = "_setup$runSuffix")
+  }
+
+  /**
+   * Suffix appended to `_setup` / `_teardown` filenames. JVM overrides to disambiguate multiple
+   * `jUnitCore.run()` invocations; Android uses the default single-run filenames.
+   */
+  protected open fun nextRunSuffix(description: Description?): String = ""
+
+  override fun testStarted(description: Description) {
+    try {
+      agent.reset()
+    } catch (e: Exception) {
+      recordCoverageError("reset for ${description.displayName}", e)
+    }
+  }
+
+  override fun testFinished(description: Description) {
+    val testName = coverageTestName(description) ?: return
+    dumpExec(testName = testName, baseFileName = testName)
+  }
+
+  /** TPX-format name shared with coverage extensions and `manifest.jsonl`. */
+  protected fun coverageTestName(description: Description): String? {
+    val className = description.className ?: return null
+    val methodName = description.methodName ?: return null
+    return "$methodName ($className)"
+  }
+
+  override fun testRunFinished(result: Result?) {
+    // Probes that fire AFTER the last testFinished (framework teardown, deferred class loading) —
+    // same bundle-level attribution as setup.
+    // Do NOT close() the manifest here: the JVM runner reuses one listener instance across
+    // multiple jUnitCore.run() invocations, so testRunFinished fires per class. Closing the
+    // writer after the first class would silently drop later writes. Owners call close() once
+    // after all classes are done.
+    dumpExec(testName = "main", baseFileName = "_teardown$runSuffix")
+  }
+
+  override fun close() {
+    manifest.close()
+  }
+
+  protected fun dumpExec(testName: String, baseFileName: String) {
+    try {
+      val execData = agent.dumpAndReset() ?: return
+      if (execData.isEmpty()) return
+
+      val fileName = boundedFileName(baseFileName, ".exec")
+      val execFile = File(outputDir, fileName)
+      FileOutputStream(execFile).use { fos -> fos.write(execData) }
+
+      // Hand-rolled JSON to avoid a jackson-core dep that would duplicate fbandroid's on the APK.
+      val jsonLine =
+          "{\"test_name\":\"${escapeJsonString(testName)}\"," +
+              "\"exec_file\":\"${escapeJsonString(fileName)}\"}"
+
+      synchronized(manifest) { manifest.println(jsonLine) }
+    } catch (e: Exception) {
+      recordCoverageError("dump for $testName", e)
+    }
+  }
+
+  private fun recordCoverageError(context: String, e: Exception) {
+    if (coverageError != null) return
+    coverageError = e
+    onFirstCoverageError(context, e)
+  }
+
+  /**
+   * Called after the first coverage error is stored. Android overrides this to write a sentinel
+   * file; JVM callers can read [coverageError] directly.
+   */
+  protected open fun onFirstCoverageError(context: String, e: Exception) {}
+
+  companion object {
+    private val INVALID_FILENAME_CHARS = Regex("[/\\\\:*?\"<>| ]")
+
+    /** Max bytes in a single path component on the filesystems we run on (Linux `NAME_MAX`). */
+    private const val NAME_MAX_BYTES = 255
+
+    fun sanitizeFileName(name: String): String = name.replace(INVALID_FILENAME_CHARS, "_")
+
+    /**
+     * Sanitized `<name><suffix>` filename bounded to [NAME_MAX_BYTES]. Per-test names (descriptive
+     * method name + FQCN) routinely exceed the filesystem's per-component limit; without bounding,
+     * the `.exec` write fails with `ENAMETOOLONG`, which the runner surfaces as an INFRA_FAILURE
+     * for the whole bundle. Over-budget names fall back to a hash of the full name — short and
+     * collision-free across tests. The chosen name is recorded in `manifest.jsonl`, so the daemon
+     * reads whatever this returns — no cross-process agreement on the exact string is required.
+     */
+    fun boundedFileName(name: String, suffix: String): String {
+      val sanitized = sanitizeFileName(name)
+      val base =
+          if (utf8Len(sanitized) + utf8Len(suffix) <= NAME_MAX_BYTES) sanitized else hashHex(name)
+      return base + suffix
+    }
+
+    private fun utf8Len(s: String): Int = s.toByteArray(Charsets.UTF_8).size
+
+    /** First 64 bits of SHA-256 as 16 hex chars; keeps over-long names collision-free. */
+    private fun hashHex(s: String): String =
+        MessageDigest.getInstance("SHA-256")
+            .digest(s.toByteArray(Charsets.UTF_8))
+            .take(8)
+            .joinToString("") { "%02x".format(it.toInt() and 0xff) }
+
+    private fun escapeJsonString(s: String): String {
+      val sb = StringBuilder(s.length + 2)
+      for (c in s) {
+        when {
+          c == '"' -> sb.append("\\\"")
+          c == '\\' -> sb.append("\\\\")
+          c == '\n' -> sb.append("\\n")
+          c == '\r' -> sb.append("\\r")
+          c == '\t' -> sb.append("\\t")
+          c.code < 0x20 -> sb.append("\\u%04x".format(c.code))
+          else -> sb.append(c)
+        }
+      }
+      return sb.toString()
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BaseRunner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BaseRunner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BaseRunner.java
@@ -0,0 +1,325 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.test.selectors.TestSelectorList;
+import com.facebook.buck.util.environment.Platform;
+import com.facebook.buck.util.environment.PlatformType;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter; // NOPMD can't depend on Guava
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/** Base class for both the JUnit and TestNG runners. */
+public abstract class BaseRunner {
+  protected static final String ENCODING = "UTF-8";
+  // This is to be extended when introducing new information into the result .xml file and allow
+  // consumers of that information to understand whether the testrunner they're using supports the
+  // new features.
+  protected static final String[] RUNNER_CAPABILITIES = {"simple_test_selector"};
+
+  /**
+   * Flag indicating whether strings coming from external sources should be processed to remove
+   * carriage return characters (\r).
+   *
+   * <p>This is necessary for XML processing since XML specification consider \n as a line separator
+   * and XML transformers can represent \r characters in various ways.
+   */
+  private static final boolean NEED_TO_REMOVE_CR =
+      Platform.detect().getType() == PlatformType.WINDOWS;
+
+  private static String removeCRIfNeeded(String text) {
+    if (NEED_TO_REMOVE_CR) {
+      return text.replace("\r\n", "\n").replace('\r', '\n');
+    }
+    return text;
+  }
+
+  protected File outputDirectory;
+  protected List<String> testClassNames;
+  protected long defaultTestTimeoutMillis;
+  protected TestSelectorList testSelectorList;
+  protected boolean isDryRun;
+  protected boolean shouldExplainTestSelectors;
+
+  private final TestXmlEscaper attributeEscaper = TestXmlEscaper.ATTRIBUTE_ESCAPER;
+  private final TestXmlEscaper contentEscaper = TestXmlEscaper.CONTENT_ESCAPER;
+
+  public abstract void run() throws Throwable;
+
+  /**
+   * The test result file is written as XML to avoid introducing a dependency on JSON (see class
+   * overview).
+   */
+  protected void writeResult(String testClassName, List<TestResult> results)
+      throws IOException, ParserConfigurationException, TransformerException {
+    // XML writer logic taken from:
+    // http://www.genedavis.com/library/xml/java_dom_xml_creation.jsp
+
+    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+    Document doc = docBuilder.newDocument();
+    doc.setXmlVersion("1.1");
+
+    Element root = doc.createElement("testcase");
+    root.setAttribute("name", testClassName);
+    root.setAttribute("runner_capabilities", getRunnerCapabilities());
+    root.setAttribute("testprotocol", "1.0");
+    doc.appendChild(root);
+
+    for (TestResult result : results) {
+      Element test = doc.createElement("test");
+
+      // suite attribute
+      test.setAttribute(
+          "suite",
+          (result.testMethodName == null && result.testClassName.equals("null"))
+              ? testClassName
+              : result.testClassName);
+
+      // name attribute
+      test.setAttribute("name", result.testMethodName);
+
+      // success attribute
+      boolean isSuccess = result.isSuccess();
+      test.setAttribute("success", Boolean.toString(isSuccess));
+
+      // type attribute
+      test.setAttribute("type", result.type.toString());
+
+      // time attribute
+      long runTime = result.runTime;
+      test.setAttribute("time", String.valueOf(runTime));
+
+      // Include failure details, if appropriate.
+      Throwable failure = result.failure;
+      if (failure != null) {
+        String stacktrace = stackTraceToString(failure);
+        test.setAttribute("stacktrace", attributeEscaper.escape(stacktrace));
+      }
+
+      // stdout, if non-empty.
+      if (result.stdOut != null) {
+        Element stdOutEl = doc.createElement("stdout");
+        stdOutEl.appendChild(
+            doc.createTextNode(contentEscaper.escape(removeCRIfNeeded(result.stdOut))));
+        test.appendChild(stdOutEl);
+      }
+
+      // stderr, if non-empty.
+      if (result.stdErr != null) {
+        Element stdErrEl = doc.createElement("stderr");
+        stdErrEl.appendChild(
+            doc.createTextNode(contentEscaper.escape(removeCRIfNeeded(result.stdErr))));
+        test.appendChild(stdErrEl);
+      }
+
+      root.appendChild(test);
+    }
+
+    // Create an XML transformer that pretty-prints with a 2-space indent.
+    // The transformer factory uses a system property to find the class to use. We need to default
+    // to the system default since we have the user's classpath and they may not have everything set
+    // up for the XSLT transform to work.
+    String vendor = System.getProperty("java.vm.vendor");
+    String factoryClass;
+    if ("IBM Corporation".equals(vendor)) {
+      // Used in the IBM JDK --- from
+      // https://www.ibm.com/support/knowledgecenter/SSYKE2_8.0.0/com.ibm.java.aix.80.doc/user/xml/using_xml.html
+      factoryClass = "com.ibm.xtq.xslt.jaxp.compiler.TransformerFactoryImpl";
+    } else {
+      // Used in the OpenJDK and the Oracle JDK.
+      factoryClass = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
+    }
+    // When we get this far, we're exiting, so no need to reset the property.
+    System.setProperty("javax.xml.transform.TransformerFactory", factoryClass);
+    TransformerFactory transformerFactory = TransformerFactory.newInstance();
+    Transformer trans = transformerFactory.newTransformer();
+    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
+    trans.setOutputProperty(OutputKeys.INDENT, "yes");
+    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
+
+    // Write the result to a file.
+    String testSelectorSuffix = "";
+    if (!testSelectorList.isEmpty()) {
+      testSelectorSuffix += ".test_selectors";
+    }
+    if (isDryRun) {
+      testSelectorSuffix += ".dry_run";
+    }
+    OutputStream output;
+    if (outputDirectory != null) {
+      File outputFile = new File(outputDirectory, testClassName + testSelectorSuffix + ".xml");
+      output = new BufferedOutputStream(new FileOutputStream(outputFile));
+    } else {
+      output = System.out;
+    }
+    StreamResult streamResult = new StreamResult(output);
+    DOMSource source = new DOMSource(doc);
+    trans.transform(source, streamResult);
+    if (outputDirectory != null) {
+      output.close();
+    }
+  }
+
+  private static String getRunnerCapabilities() {
+    StringBuilder result = new StringBuilder();
+    int capsLen = RUNNER_CAPABILITIES.length;
+    for (int i = 0; i < capsLen; i++) {
+      String capability = RUNNER_CAPABILITIES[i];
+      result.append(capability);
+      if (i != capsLen - 1) {
+        result.append(',');
+      }
+    }
+    return result.toString();
+  }
+
+  protected String stackTraceToString(Throwable exc) {
+    StringWriter writer = new StringWriter();
+    exc.printStackTrace(new PrintWriter(writer, /* autoFlush */ true)); // NOPMD no Guava
+    return writer.toString();
+  }
+
+  /**
+   * Expected arguments are:
+   *
+   * <ul>
+   *   <li>(string) output directory
+   *   <li>(long) default timeout in milliseconds (0 for no timeout)
+   *   <li>(string) newline separated list of test selectors
+   *   <li>(string...) fully-qualified names of test classes
+   * </ul>
+   */
+  protected void parseArgs(String... args) {
+    File outputDirectory = null;
+    long defaultTestTimeoutMillis = 0;
+    TestSelectorList.Builder testSelectorListBuilder = TestSelectorList.builder();
+    boolean isDryRun = false;
+    boolean shouldExplainTestSelectors = false;
+
+    List<String> testClassNames = new ArrayList<>();
+
+    for (int i = 0; i < args.length; i++) {
+      switch (args[i]) {
+        case "--default-test-timeout":
+          defaultTestTimeoutMillis = Long.parseLong(args[++i]);
+          break;
+        case "--test-selectors":
+          List<String> rawSelectors = Arrays.asList(args[++i].split("\n"));
+          testSelectorListBuilder.addRawSelectors(rawSelectors);
+          break;
+        case "--simple-test-selector":
+          try {
+            testSelectorListBuilder.addSimpleTestSelector(args[++i]);
+          } catch (IllegalArgumentException e) {
+            System.err.print("--simple-test-selector takes 2 args: [suite] and [method name].");
+            System.exit(1);
+          }
+          break;
+        case "--b64-test-selector":
+          try {
+            testSelectorListBuilder.addBase64EncodedTestSelector(args[++i]);
+          } catch (IllegalArgumentException e) {
+            System.err.print("--b64-test-selector takes 2 args: [suite] and [method name].");
+            System.exit(1);
+          }
+          break;
+        case "--explain-test-selectors":
+          shouldExplainTestSelectors = true;
+          break;
+        case "--dry-run":
+          isDryRun = true;
+          break;
+        case "--output":
+          outputDirectory = new File(args[++i]);
+          if (!outputDirectory.exists() && !outputDirectory.mkdirs()) {
+            System.err.printf(
+                "The output directory did not exist and failed to create it: %s\n",
+                outputDirectory);
+            System.exit(1);
+          }
+          break;
+        case "--test-class-names-file":
+          File testClassNamesFile = new File(args[++i]);
+          if (!testClassNamesFile.exists()) {
+            System.err.printf("The test class names files did not exist: %s\n", testClassNamesFile);
+            System.exit(1);
+          }
+          try {
+            testClassNames.addAll(Files.readAllLines(testClassNamesFile.toPath()));
+          } catch (IOException e) {
+            throw new RuntimeException(e);
+          }
+          break;
+        default:
+          testClassNames.add(args[i]);
+      }
+    }
+
+    if (testClassNames.isEmpty()) {
+      System.err.println("Must specify at least one test.");
+      System.exit(1);
+    }
+
+    this.outputDirectory = outputDirectory;
+    this.defaultTestTimeoutMillis = defaultTestTimeoutMillis;
+    this.isDryRun = isDryRun;
+    this.testClassNames = testClassNames;
+    this.testSelectorList = testSelectorListBuilder.build();
+    if (!testSelectorList.isEmpty() && !shouldExplainTestSelectors) {
+      // Don't bother class-loading any classes that aren't possible, according to test selectors
+      testClassNames.removeIf(name -> !testSelectorList.possiblyIncludesClassName(name));
+    }
+    this.shouldExplainTestSelectors = shouldExplainTestSelectors;
+  }
+
+  protected void runAndExit() {
+    int exitCode;
+
+    // Run the tests.
+    try {
+      run();
+
+      // We're using a successful exit code regardless of test outcome since JUnitRunner
+      // is designed to execute all tests and produce a report of success or failure.  We've done
+      // that successfully if we've gotten here.
+      exitCode = 0;
+    } catch (Throwable e) {
+      e.printStackTrace();
+      // We're using a failed exit code here because something in the test runner crashed. We can't
+      // tell whether there were still tests left to be run, so it's safest if we fail.
+      exitCode = 1;
+    }
+
+    // Explicitly exit to force the test runner to complete even if tests have sloppily left
+    // behind non-daemon threads that would have otherwise forced the process to wait and
+    // eventually timeout.
+    System.exit(exitCode);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BuckBlockJUnit4ClassRunner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BuckBlockJUnit4ClassRunner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BuckBlockJUnit4ClassRunner.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.Timeout;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.model.FrameworkField;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.InitializationError;
+import org.junit.runners.model.Statement;
+import org.junit.runners.model.TestClass;
+
+/**
+ * JUnit-4-compatible test class runner that supports the concept of a "default timeout." If the
+ * value of {@code defaultTestTimeoutMillis} passed to the constructor is non-zero, then it will be
+ * used in place of {@link Test#timeout()} if {@link Test#timeout()} returns zero.
+ *
+ * <p>The superclass, {@link BlockJUnit4ClassRunner}, was introduced in JUnit 4.5 as a published API
+ * that was designed to be extended.
+ *
+ * <p>This runner also creates Descriptions that allow JUnitRunner to filter which test-methods to
+ * run and should be forced into the test code path whenever test-selectors are in use.
+ */
+public class BuckBlockJUnit4ClassRunner extends BlockJUnit4ClassRunner {
+
+  private final ThreadLocal<ExecutorService> executor =
+      new ThreadLocal<ExecutorService>() {
+        @Override
+        protected ExecutorService initialValue() {
+          return Executors.newSingleThreadExecutor(
+              r -> {
+                Thread newThread = Executors.defaultThreadFactory().newThread(r);
+                newThread.setName(BuckBlockJUnit4ClassRunner.class.getSimpleName());
+                return newThread;
+              });
+        }
+      };
+
+  private final long defaultTestTimeoutMillis;
+
+  public BuckBlockJUnit4ClassRunner(Class<?> klass, long defaultTestTimeoutMillis)
+      throws InitializationError {
+    super(klass);
+    this.defaultTestTimeoutMillis = defaultTestTimeoutMillis;
+  }
+
+  @Override
+  protected Object createTest() throws Exception {
+    // Pushing tests onto threads because the test timeout has been set is Unexpected Behaviour. It
+    // causes things like the SingleThreadGuard in jmock2 to get most upset because the test is
+    // being run on a thread different from the one it was created on. Work around this by creating
+    // the test on the same thread we will be timing it out on.
+    // See https://github.com/junit-team/junit/issues/686 for more context.
+    Callable<Object> maker = () -> BuckBlockJUnit4ClassRunner.super.createTest();
+
+    Future<Object> createdTest = executor.get().submit(maker);
+    return createdTest.get();
+  }
+
+  private boolean isNeedingCustomTimeout() {
+    return defaultTestTimeoutMillis <= 0 || hasTimeoutRule(getTestClass());
+  }
+
+  private long getTimeout(FrameworkMethod method) {
+    // Check to see if the method has declared a timeout on the @Test annotation. If that's present
+    // and set, then let JUnit handle the timeout for us, which (counter-intuitively) means letting
+    // the test run indefinitely.
+    Test annotation = method.getMethod().getAnnotation(Test.class);
+    if (annotation != null) {
+      long timeout = annotation.timeout();
+      if (timeout != 0) { // 0 represents the default timeout
+        return Long.MAX_VALUE;
+      }
+    }
+
+    if (!isNeedingCustomTimeout()) {
+      return defaultTestTimeoutMillis;
+    }
+    return Long.MAX_VALUE;
+  }
+
+  /**
+   * Override the default timeout behavior so that when no timeout is specified in the {@link Test}
+   * annotation, the timeout specified by the constructor will be used (if it has been set).
+   */
+  @Override
+  protected Statement methodBlock(FrameworkMethod method) {
+    Statement statement = super.methodBlock(method);
+
+    // If the test class has a Timeout @Rule, then that should supersede the default timeout. The
+    // same applies if it has a timeout value for the @Test annotation.
+
+    long timeout = getTimeout(method);
+
+    return new SameThreadFailOnTimeout(executor.get(), timeout, testName(method), statement);
+  }
+
+  /**
+   * @return {@code true} if the test class has any fields annotated with {@code Rule} whose type is
+   *     {@link Timeout}.
+   */
+  static boolean hasTimeoutRule(TestClass testClass) {
+    // Many protected convenience methods in BlockJUnit4ClassRunner that are available in JUnit 4.11
+    // such as getTestRules(Object) were not public until
+    // https://github.com/junit-team/junit/commit/8782efa08abf5d47afdc16740678661443706740,
+    // which appears to be JUnit 4.9. Because we allow users to use JUnit 4.7, we need to include a
+    // custom implementation that is backwards compatible to JUnit 4.7.
+    List<FrameworkField> fields = testClass.getAnnotatedFields(Rule.class);
+    for (FrameworkField field : fields) {
+      if (field.getField().getType().equals(Timeout.class)) {
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  /** Override default init error collector so that class without any test methods will pass */
+  @Override
+  protected void collectInitializationErrors(List<Throwable> errors) {
+    if (!computeTestMethods().isEmpty()) {
+      super.collectInitializationErrors(errors);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BuckXmlTestRunListener.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BuckXmlTestRunListener.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/BuckXmlTestRunListener.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.ddmlib.testrunner.XmlTestRunListener;
+import com.facebook.buck.android.exopackage.AdbUtils;
+import com.facebook.buck.android.exopackage.AndroidDevice;
+import java.io.File;
+import java.io.IOException;
+import java.util.Map;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
+
+public class BuckXmlTestRunListener extends XmlTestRunListener {
+
+  protected static final String TEST_RESULT_FILE = "test_result.xml";
+  private String mRunFailureMessage = null;
+  private File mReportDir;
+  private AndroidDevice mAndroidDevice;
+  private AdbUtils mAdbUtils;
+
+  BuckXmlTestRunListener(AndroidDevice androidDevice, AdbUtils adbUtils) {
+    mAndroidDevice = androidDevice;
+    mAdbUtils = adbUtils;
+  }
+
+  @Override
+  public void setReportDir(File file) {
+    super.setReportDir(file);
+    mReportDir = file;
+  }
+
+  @Override
+  public void testRunStarted(String runName, int testCount) {
+    super.testRunStarted(runName, testCount);
+  }
+
+  @Override
+  public void testRunFailed(String errorMessage) {
+    mRunFailureMessage = errorMessage;
+  }
+
+  @Override
+  public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) {
+    super.testRunEnded(elapsedTime, runMetrics);
+    addMainTestResult();
+  }
+
+  @Override
+  public void testFailed(TestIdentifier test, String trace) {
+    if (mAndroidDevice != null && mAdbUtils != null && CrashCapturer.deviceHasCrashLogs(trace)) {
+      trace = CrashCapturer.addDeviceLogcatTrace(mAndroidDevice, mAdbUtils, trace);
+    }
+    super.testFailed(test, trace);
+  }
+
+  /** Adds one more XML element to the test_result.xml tracking the result of the whole process. */
+  private void addMainTestResult() {
+    try {
+      File resultFile = getResultFile(mReportDir);
+
+      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
+      Document doc = docBuilder.parse(resultFile);
+
+      Node testsuite = doc.getElementsByTagName("testsuite").item(0);
+      if (mRunFailureMessage != null) {
+        Element failureNode = doc.createElement("failure");
+        failureNode.setTextContent(mRunFailureMessage);
+        testsuite.appendChild(failureNode);
+
+        TransformerFactory transformerFactory = TransformerFactory.newInstance();
+        Transformer transformer = transformerFactory.newTransformer();
+        DOMSource source = new DOMSource(doc);
+        StreamResult result = new StreamResult(resultFile);
+        transformer.transform(source, result);
+      }
+
+    } catch (IOException | ParserConfigurationException | SAXException | TransformerException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  /**
+   * Creates a {@link File} where the report will be created. Instead of creating a temp file,
+   * create a file with the devices serial number, so it's possible to refer back to it afterwards.
+   *
+   * @param reportDir the root directory of the report.
+   * @return a file
+   * @throws IOException
+   */
+  @Override
+  protected File getResultFile(File reportDir) {
+    return new File(reportDir, TEST_RESULT_FILE);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CheckDependency.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CheckDependency.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CheckDependency.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import java.lang.annotation.Annotation;
+import java.util.Optional;
+
+class CheckDependency {
+
+  private CheckDependency() {
+    // Utility class.
+  }
+
+  /**
+   * Validate the presence of the class or execute {@code System.exit(1)} if not.
+   *
+   * @param classToLoad name of the class that is required for the execution to continue.
+   */
+  public static void requiresClass(String name, String classToLoad) {
+    try {
+      Class.forName(classToLoad);
+    } catch (ClassNotFoundException e) {
+      System.err.println(
+          "Unable to locate " + name + " on the classpath. Please add as a test dependency.");
+      System.exit(1);
+    }
+  }
+
+  /**
+   * @param classToLoad name of the class that should be loaded.
+   * @return Optional containing a reference to the class if it exists, otherwise {@code
+   *     Optional.empty()}
+   */
+  public static Optional<Class<?>> optionalClass(String classToLoad) {
+    try {
+      return Optional.ofNullable(Class.forName(classToLoad));
+    } catch (ClassNotFoundException e) {
+      return Optional.empty();
+    }
+  }
+
+  /**
+   * @param annotationName name of the optional annotation.
+   * @return Optional containing a reference to the annotation class if it exists, otherwise {@code
+   *     Optional.empty()}
+   */
+  @SuppressWarnings("unchecked")
+  public static Optional<Class<? extends Annotation>> optionalAnnotation(String annotationName) {
+    return optionalClass(annotationName)
+        .filter(Class::isAnnotation)
+        .map(ann -> (Class<? extends Annotation>) ann);
+  }
+
+  /**
+   * @param className name of the class that should have its presence checked.
+   * @return true if the class is present in the classpath.
+   */
+  public static boolean classPresent(String className) {
+    return optionalClass(className).isPresent();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CrashAnalyzer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CrashAnalyzer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CrashAnalyzer.java
@@ -0,0 +1,370 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Analyzes crash information from logcat output to detect specific crash types and provide enhanced
+ * crash reporting.
+ */
+public class CrashAnalyzer {
+
+  /** Defines a crash type with its detection pattern and message. */
+  private static class CrashType {
+    final Pattern pattern;
+    final String detectionMessage;
+    final boolean isSignal;
+
+    CrashType(Pattern pattern, String detectionMessage, boolean isSignal) {
+      this.pattern = pattern;
+      this.detectionMessage = detectionMessage;
+      this.isSignal = isSignal;
+    }
+  }
+
+  private static final CrashType[] CRASH_TYPES = {
+    new CrashType(
+        Pattern.compile("java\\.lang\\.OutOfMemoryError:.*"),
+        "Out of memory error detected",
+        false),
+    new CrashType(
+        Pattern.compile("java\\.lang\\.StackOverflowError"),
+        "Stack overflow error detected",
+        false),
+    new CrashType(
+        Pattern.compile("java\\.lang\\.NullPointerException"),
+        "Null pointer exception detected",
+        false),
+    new CrashType(
+        Pattern.compile(
+            "java\\.lang\\.IndexOutOfBoundsException|java\\.lang\\.ArrayIndexOutOfBoundsException"),
+        "Index out of bounds exception detected",
+        false),
+    new CrashType(
+        Pattern.compile("java\\.lang\\.IllegalStateException"),
+        "Illegal state exception detected",
+        false),
+    new CrashType(
+        Pattern.compile("(?i)Fatal signal 6|signal 6|SIGABRT|Abort"),
+        "SIGABRT signal detected",
+        true),
+    new CrashType(
+        // Match a real native-crash line (libc "Fatal signal 11 (SIGSEGV)" / debuggerd
+        // "signal 11 (SIGSEGV)") or a "Segmentation fault" report. The bare "SIGSEGV" token was
+        // intentionally removed: it matches any log line that merely mentions the word, e.g. the
+        // benign MessageExecutionMonitor warning "...risk of ART nterp stack-walk SIGSEGV..."
+        // (added
+        // by D109574690, fires ~hundreds of times per run), which produced false "native crash"
+        // verdicts. Real SIGSEGV crashes always carry "signal 11", so coverage is unaffected.
+        Pattern.compile("(?i)Fatal signal 11|signal 11|segmentation fault"),
+        "SIGSEGV signal detected (native crash)",
+        true),
+    new CrashType(
+        Pattern.compile("(?i)Fatal signal 4|signal 4|SIGILL|illegal instruction"),
+        "SIGILL signal detected (illegal instruction)",
+        true),
+    new CrashType(
+        Pattern.compile("(?i)Fatal signal 8|signal 8|SIGFPE|floating point exception"),
+        "SIGFPE signal detected (floating point exception)",
+        true),
+    new CrashType(
+        Pattern.compile("(?i)Fatal signal 7|signal 7|SIGBUS|bus error"),
+        "SIGBUS signal detected (bus error)",
+        true),
+    new CrashType(
+        Pattern.compile("java\\.lang\\.ClassNotFoundException"),
+        "Class not found exception detected",
+        false),
+  };
+
+  /**
+   * Analyzes logcat output for crash information and forwards it to stdout/stderr so the enhanced
+   * crash detection system can detect specific crash types.
+   *
+   * @param logcatOutput The raw logcat output to analyze
+   */
+  public void analyzeCrashInformation(String logcatOutput) {
+    if (logcatOutput == null || logcatOutput.trim().isEmpty()) {
+      return;
+    }
+
+    System.err.println("=== AIT CRASH ANALYSIS ===");
+    boolean crashDetected = false;
+
+    for (CrashType crashType : CRASH_TYPES) {
+      Matcher matcher = crashType.pattern.matcher(logcatOutput);
+      boolean matched;
+      if (crashType.isSignal) {
+        matched = matcher.find();
+      } else {
+        // A Java-exception token only indicates a crash when it is surfaced by the crash
+        // reporter, not when some component merely logs a caught exception (see
+        // isCrashContext). Scan every occurrence so a genuine crash later in the log is still
+        // found even when benign matches precede it.
+        matched = false;
+        while (matcher.find()) {
+          if (isCrashContext(logcatOutput, matcher.start())) {
+            matched = true;
+            break;
+          }
+        }
+      }
+      if (matched) {
+        crashDetected = true;
+        System.err.println("AIT_CRASH_DETECTION: " + crashType.detectionMessage);
+
+        if (crashType.isSignal) {
+          extractSignalStackTrace(logcatOutput, matcher);
+        } else {
+          extractExceptionStackTrace(logcatOutput, matcher);
+        }
+      }
+    }
+
+    if (!crashDetected) {
+      System.err.println("No crashes detected");
+    }
+    System.err.println("=== END AIT CRASH ANALYSIS ===");
+  }
+
+  /**
+   * Decides whether a matched Java-exception token represents an actual crash rather than a
+   * caught-and-logged exception. An uncaught exception that crashes the process is reported by the
+   * Android runtime's uncaught-exception handler (the "AndroidRuntime" tag / "FATAL EXCEPTION"
+   * header); a failure to load a test class is reported by the instrumentation "TestRunner". A
+   * token logged under any other tag is a component logging a caught exception, e.g. the benign
+   * lines that previously produced false "crash detected" verdicts on every run:
+   *
+   * <pre>
+   *   E QPLProvider: java.lang.IllegalStateException: No QPL instance provided
+   *   D CoverageInit: java.lang.ClassNotFoundException: com.facebook.coverage.e2e.CoverageSetup
+   * </pre>
+   *
+   * The check is on the matched line itself, which works for both brief ("E/AndroidRuntime(pid):")
+   * and threadtime ("... E AndroidRuntime:") logcat formats since the exception token shares the
+   * line with its tag.
+   *
+   * @param logcatOutput The raw logcat output
+   * @param matchStart Offset of the exception token match within {@code logcatOutput}
+   * @return true if the match is on a crash-reporter / test-runner line
+   */
+  private static boolean isCrashContext(String logcatOutput, int matchStart) {
+    int lineStart = logcatOutput.lastIndexOf('\n', matchStart) + 1;
+    int lineEnd = logcatOutput.indexOf('\n', matchStart);
+    if (lineEnd == -1) {
+      lineEnd = logcatOutput.length();
+    }
+    String line = logcatOutput.substring(lineStart, lineEnd);
+    return line.contains("AndroidRuntime")
+        || line.contains("FATAL EXCEPTION")
+        || line.contains("TestRunner");
+  }
+
+  /**
+   * Extracts Java exception details and stack trace location.
+   *
+   * @param logcatOutput The raw logcat output
+   * @param exceptionMatcher The matcher that found the Java exception
+   */
+  private void extractExceptionStackTrace(String logcatOutput, Matcher exceptionMatcher) {
+    // Extract the Java exception line
+    int matchStart = exceptionMatcher.start();
+    int lineStart = logcatOutput.lastIndexOf('\n', matchStart) + 1;
+    int lineEnd = logcatOutput.indexOf('\n', matchStart);
+    if (lineEnd == -1) {
+      lineEnd = logcatOutput.length();
+    }
+
+    String exceptionLine = logcatOutput.substring(lineStart, lineEnd).trim();
+    if (!exceptionLine.isEmpty()) {
+      System.err.println("Exception: " + exceptionLine);
+    }
+
+    // Look for the "at" stack trace line immediately following the exception
+    int nextLineStart = lineEnd + 1;
+    if (nextLineStart < logcatOutput.length()) {
+      int nextLineEnd = logcatOutput.indexOf('\n', nextLineStart);
+      if (nextLineEnd == -1) {
+        nextLineEnd = logcatOutput.length();
+      }
+
+      String nextLine = logcatOutput.substring(nextLineStart, nextLineEnd).trim();
+      // Check if the next line contains stack trace information starting with "at"
+      if (nextLine.contains("\tat ") || nextLine.trim().startsWith("at ")) {
+        System.err.println("Stack trace: " + nextLine.trim());
+      }
+    }
+  }
+
+  /**
+   * Extracts signal crash details and backtrace location.
+   *
+   * @param logcatOutput The raw logcat output
+   * @param signalMatcher The matcher that found the signal
+   */
+  private void extractSignalStackTrace(String logcatOutput, Matcher signalMatcher) {
+    // Extract the signal line
+    int matchStart = signalMatcher.start();
+    int lineStart = logcatOutput.lastIndexOf('\n', matchStart) + 1;
+    int lineEnd = logcatOutput.indexOf('\n', matchStart);
+    if (lineEnd == -1) {
+      lineEnd = logcatOutput.length();
+    }
+
+    String signalLine = logcatOutput.substring(lineStart, lineEnd).trim();
+    if (!signalLine.isEmpty()) {
+      System.err.println("Signal: " + signalLine);
+
+      // Determine which signal type this is
+      String signalType = determineSignalType(signalLine);
+
+      // Extract signal code information as potential root cause indicator
+      String signalCode = extractSignalCode(signalLine, signalType);
+      if (!signalCode.isEmpty()) {
+        System.err.println("ROOT CAUSE: " + signalCode);
+      }
+    }
+
+    // Look for additional signal information (like backtrace) in following lines
+    int nextLineStart = lineEnd + 1;
+    for (int i = 0; i < 5 && nextLineStart < logcatOutput.length(); i++) {
+      int nextLineEnd = logcatOutput.indexOf('\n', nextLineStart);
+      if (nextLineEnd == -1) {
+        nextLineEnd = logcatOutput.length();
+      }
+
+      String nextLine = logcatOutput.substring(nextLineStart, nextLineEnd).trim();
+      // Look for backtrace information or native crash details
+      if (nextLine.contains("backtrace:") || nextLine.contains("pc ") || nextLine.contains("#")) {
+        System.err.println("Backtrace: " + nextLine.trim());
+      }
+      nextLineStart = nextLineEnd + 1;
+    }
+  }
+
+  /**
+   * Determines the signal type from a signal line.
+   *
+   * @param signalLine The signal line from logcat
+   * @return The signal type (e.g., "SIGABRT", "SIGSEGV", "SIGILL", "SIGFPE", "SIGBUS"), or
+   *     "UNKNOWN" if not determinable
+   */
+  private String determineSignalType(String signalLine) {
+    String upperLine = signalLine.toUpperCase();
+
+    // Check for SIGABRT (signal 6)
+    if (upperLine.contains("SIGABRT")
+        || upperLine.matches(".*SIGNAL\\s+6\\b.*")
+        || upperLine.contains("ABORT")) {
+      return "SIGABRT";
+    }
+
+    // Check for SIGSEGV first (signal 11)
+    if (upperLine.contains("SIGSEGV")
+        || upperLine.matches(".*SIGNAL\\s+11\\b.*")
+        || upperLine.contains("SEGMENTATION")) {
+      return "SIGSEGV";
+    }
+
+    // Check for SIGILL (signal 4)
+    if (upperLine.contains("SIGILL")
+        || upperLine.matches(".*SIGNAL\\s+4\\b.*")
+        || upperLine.contains("ILLEGAL INSTRUCTION")) {
+      return "SIGILL";
+    }
+
+    // Check for SIGFPE (signal 8)
+    if (upperLine.contains("SIGFPE")
+        || upperLine.matches(".*SIGNAL\\s+8\\b.*")
+        || upperLine.contains("FLOATING POINT EXCEPTION")) {
+      return "SIGFPE";
+    }
+
+    // Check for SIGBUS (signal 7)
+    if (upperLine.contains("SIGBUS")
+        || upperLine.matches(".*SIGNAL\\s+7\\b.*")
+        || upperLine.contains("BUS ERROR")) {
+      return "SIGBUS";
+    }
+
+    return "UNKNOWN";
+  }
+
+  /**
+   * Extracts signal code information from a signal line to provide context about the signal origin.
+   *
+   * @param signalLine The signal line from logcat
+   * @param signalType The type of signal (e.g., "SIGABRT", "SIGSEGV", "SIGILL", "SIGFPE", "SIGBUS")
+   * @return A description of the signal code, or empty string if not determinable
+   */
+  private String extractSignalCode(String signalLine, String signalType) {
+    // Check signal-specific codes first
+    if ("SIGABRT".equals(signalType)) {
+      if (signalLine.contains("code -6") || signalLine.contains("SI_TKILL")) {
+        return "SIGABRT from abort() or assertion failure - check for Abort message in logs";
+      }
+    } else if ("SIGSEGV".equals(signalType)) {
+      if (signalLine.contains("code 1") && signalLine.contains("SEGV_MAPERR")) {
+        return "SIGSEGV due to invalid memory access (address not mapped)";
+      } else if (signalLine.contains("code 2") && signalLine.contains("SEGV_ACCERR")) {
+        return "SIGSEGV due to invalid permissions (access violation)";
+      }
+    } else if ("SIGILL".equals(signalType)) {
+      if (signalLine.contains("code 1") && signalLine.contains("ILL_ILLOPC")) {
+        return "SIGILL due to illegal opcode";
+      } else if (signalLine.contains("code 2") && signalLine.contains("ILL_ILLOPN")) {
+        return "SIGILL due to illegal operand";
+      } else if (signalLine.contains("code 3") && signalLine.contains("ILL_PRVOPC")) {
+        return "SIGILL due to privileged opcode";
+      }
+    } else if ("SIGFPE".equals(signalType)) {
+      if (signalLine.contains("code 1") && signalLine.contains("FPE_INTDIV")) {
+        return "SIGFPE due to integer divide by zero";
+      } else if (signalLine.contains("code 2") && signalLine.contains("FPE_INTOVF")) {
+        return "SIGFPE due to integer overflow";
+      } else if (signalLine.contains("code 3") && signalLine.contains("FPE_FLTDIV")) {
+        return "SIGFPE due to floating point divide by zero";
+      } else if (signalLine.contains("code 4") && signalLine.contains("FPE_FLTOVF")) {
+        return "SIGFPE due to floating point overflow";
+      } else if (signalLine.contains("code 5") && signalLine.contains("FPE_FLTUND")) {
+        return "SIGFPE due to floating point underflow";
+      } else if (signalLine.contains("code 6") && signalLine.contains("FPE_FLTRES")) {
+        return "SIGFPE due to floating point inexact result";
+      } else if (signalLine.contains("code 7") && signalLine.contains("FPE_FLTINV")) {
+        return "SIGFPE due to floating point invalid operation";
+      } else if (signalLine.contains("code 8") && signalLine.contains("FPE_FLTSUB")) {
+        return "SIGFPE due to subscript out of range";
+      }
+    } else if ("SIGBUS".equals(signalType)) {
+      if (signalLine.contains("code 1") && signalLine.contains("BUS_ADRALN")) {
+        return "SIGBUS due to invalid address alignment";
+      } else if (signalLine.contains("code 2") && signalLine.contains("BUS_ADRERR")) {
+        return "SIGBUS due to non-existent physical address";
+      } else if (signalLine.contains("code 3") && signalLine.contains("BUS_OBJERR")) {
+        return "SIGBUS due to object-specific hardware error";
+      }
+    }
+
+    // Generic signal codes that apply to any signal type
+    if (signalLine.contains("code 0") && signalLine.contains("SI_USER")) {
+      return signalType + " sent by user code (android.os.Process.sendSignal or kill command)";
+    } else if (signalLine.contains("SI_QUEUE")) {
+      return signalType + " sent via sigqueue()";
+    } else if (signalLine.contains("code -1")) {
+      return signalType + " from kernel";
+    }
+
+    // If we can't determine the code, return empty
+    return "";
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CrashCapturer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CrashCapturer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/CrashCapturer.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.android.exopackage.AdbUtils;
+import com.facebook.buck.android.exopackage.AndroidDevice;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Static methods to collect crash information from a device. */
+public class CrashCapturer {
+  /**
+   * Checks if the given trace string may contain crash trace information.
+   *
+   * @param trace the trace string to check
+   * @return true if the trace string ends with "Check device logcat for details", false otherwise
+   */
+  public static boolean deviceHasCrashLogs(String trace) {
+    return trace.endsWith("Check device logcat for details");
+  }
+
+  /**
+   * Adds device logcat trace lines to the given trace string.
+   *
+   * @param androidDevice the AndroidDevice to get logcat from
+   * @param adbUtils the AdbUtils instance for executing commands
+   * @param trace the trace string to add the logcat trace to
+   * @return the trace string with the added logcat trace
+   */
+  public static String addDeviceLogcatTrace(
+      AndroidDevice androidDevice, AdbUtils adbUtils, String trace) {
+    try {
+      // Wait a short time for debuggerd to (hopefully) write some info out.
+      Thread.sleep(1000);
+
+      // Execute logcat command using AdbUtils
+      String logcatOutput =
+          adbUtils.executeAdbShellCommand(
+              "logcat -d", androidDevice.getSerialNumber(), true /* ignoreFailure */);
+
+      // Process the logcat output
+      List<String> debugLines = new ArrayList<>();
+      boolean inDebuggerdDump = false;
+
+      String[] lines = logcatOutput.split("\n");
+      for (String line : lines) {
+        if (!line.contains("DEBUG")) {
+          continue;
+        }
+        if (line.contains("*** *** ***")) {
+          debugLines.clear();
+          inDebuggerdDump = true;
+        }
+        if (inDebuggerdDump) {
+          debugLines.add(line);
+        }
+      }
+
+      StringBuilder builder = new StringBuilder();
+      builder.append(trace);
+      if (debugLines.isEmpty()) {
+        builder.append("\nSearched logcat, but unable to find a crash.\n");
+      } else {
+        builder.append("\nFound a crash in logcat:\n\n");
+        for (String line : debugLines) {
+          builder.append(line).append('\n');
+        }
+      }
+      trace = builder.toString();
+    } catch (Exception e) {
+      // Is this too verbose?  Should we just ignore failure here?
+      // Logging isn't configured, unfortunately.
+      System.err.println("Warning: Failed to collect more info from logcat.");
+      e.printStackTrace();
+    }
+
+    return trace;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/DeviceRunner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/DeviceRunner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/DeviceRunner.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.android.exopackage.AdbUtils;
+import com.facebook.buck.android.exopackage.AndroidDevice;
+import com.facebook.buck.android.exopackage.AndroidDeviceImpl;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+
+public class DeviceRunner {
+
+  private static final String ADB_PATH = "ADB_PATH";
+  private static final String PWD = "PWD";
+
+  static class DeviceArgs {
+    final boolean autoRunOnConnectedDevice;
+    final String deviceSerial;
+    final String adbExecutablePath;
+
+    DeviceArgs(boolean autoRunOnConnectedDevice, String deviceSerial, String adbExecutablePath) {
+      this.autoRunOnConnectedDevice = autoRunOnConnectedDevice;
+      this.deviceSerial = deviceSerial;
+      this.adbExecutablePath = adbExecutablePath;
+    }
+  }
+
+  protected DeviceArgs deviceArgs;
+  protected final AdbUtils adbUtils;
+
+  DeviceRunner(DeviceArgs args) {
+    this.deviceArgs = args;
+    this.adbUtils = new AdbUtils(getAdbPath(), 0);
+  }
+
+  static DeviceArgs getDeviceArgs(String[] args) {
+    String adbExecutablePath = null;
+    boolean autoRunOnConnectedDevice = false;
+    for (int i = 0; i < args.length; i++) {
+      switch (args[i]) {
+        case "--adb-executable-path":
+          adbExecutablePath = args[++i];
+          break;
+        case "--auto-run-on-connected-device":
+          autoRunOnConnectedDevice = true;
+          break;
+      }
+    }
+
+    if (adbExecutablePath == null) {
+      System.err.println("Must pass --adb-executable-path argument.");
+      System.exit(1);
+    }
+
+    final String adbPath = System.getenv(ADB_PATH);
+    if (adbPath != null && !adbPath.isEmpty()) {
+      adbExecutablePath = Paths.get(adbPath).toAbsolutePath().toString();
+    }
+
+    String buckdeviceSerial = System.getProperty("buck.device.id");
+    String androidSerial = System.getenv("ANDROID_SERIAL");
+
+    String deviceSerial = null;
+
+    if (buckdeviceSerial != null) {
+      deviceSerial = buckdeviceSerial;
+    } else if (androidSerial != null) {
+      deviceSerial = androidSerial;
+    }
+
+    if (deviceSerial != null) {
+      // If a device serial was set, we use that instead of trying to auto connect.
+      // This behavior is in line with other android tools.
+      autoRunOnConnectedDevice = false;
+    }
+
+    if (deviceSerial == null && !autoRunOnConnectedDevice) {
+      System.err.println(
+          "Must pass buck.device.id system property, as this run is not configured to"
+              + " auto-connect to device.");
+      System.exit(1);
+    }
+
+    return new DeviceArgs(autoRunOnConnectedDevice, deviceSerial, adbExecutablePath);
+  }
+
+  /**
+   * Method that either returns the given string as-is, or if the given string begins with a '@',
+   * reads a single string from the specified file.
+   */
+  protected static String getArgValue(String input) throws IOException {
+    if (!input.startsWith("@")) {
+      return input;
+    }
+
+    Path inputPath = Paths.get(input.substring(1));
+    return new String(Files.readAllBytes(inputPath));
+  }
+
+  /**
+   * Returns an {@link AndroidDevice} for the configured device. Uses {@link AdbUtils} for device
+   * discovery — no ddmlib dependency.
+   */
+  @Nullable
+  AndroidDevice getAndroidDevice(boolean autoRunOnConnectedDevice, String deviceSerial) {
+    if (autoRunOnConnectedDevice) {
+      List<AndroidDevice> devices = adbUtils.getDevices();
+      if (devices.isEmpty()) {
+        String hostname = null;
+        try {
+          hostname = InetAddress.getLocalHost().getHostName();
+        } catch (Exception _e) {
+          // no op
+        }
+        System.err.println(
+            String.format(
+                "Found 0 device %s-- please connect a device.",
+                hostname == null ? "" : String.format("on %s ", hostname)));
+        System.exit(1);
+        return null;
+      }
+      return devices.get(0);
+    } else {
+      if (deviceSerial == null) {
+        System.err.println("Unable to get device/emulator: no serial provided");
+        System.exit(1);
+        return null;
+      }
+      return new AndroidDeviceImpl(deviceSerial, adbUtils);
+    }
+  }
+
+  protected String getAdbPath() {
+    return deviceArgs.adbExecutablePath;
+  }
+
+  /** We minimize external dependencies, but we'd like to have {@link javax.annotation.Nullable}. */
+  @interface Nullable {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationMain.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+public class InstrumentationMain {
+
+  private InstrumentationMain() {
+    // Launcher class.
+  }
+
+  public static void main(String[] args) {
+    // Suppress verbose ADB command logging in CI test context to avoid
+    // filling details_short with infrastructure noise instead of test output.
+    java.util.logging.Logger.getLogger("com.facebook.buck.android.exopackage")
+        .setLevel(java.util.logging.Level.WARNING);
+    try {
+      InstrumentationTestRunner.fromArgs(args).run();
+    } catch (Throwable e) {
+      e.printStackTrace();
+    } finally {
+      // Explicitly exit to force the test runner to complete even if tests have sloppily left
+      // behind non-daemon threads that would have otherwise forced the process to wait and
+      // eventually timeout.
+      //
+      // Separately, we're using a successful exit code regardless of test outcome since the runner
+      // is designed to execute all tests and produce a report of success or failure.  We've done
+      // that successfully if we've gotten here.
+      System.exit(0);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationMainForClout.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationMainForClout.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationMainForClout.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+public class InstrumentationMainForClout {
+
+  private InstrumentationMainForClout() {
+    // Launcher class.
+  }
+
+  public static void main(String[] args) {
+    try {
+      InstrumentationTestRunnerForClout.fromArgs(args).run();
+    } catch (Throwable e) {
+      e.printStackTrace();
+    } finally {
+      // Explicitly exit to force the test runner to complete even if tests have sloppily left
+      // behind non-daemon threads that would have otherwise forced the process to wait and
+      // eventually timeout.
+      //
+      // Separately, we're using a successful exit code regardless of test outcome since the runner
+      // is designed to execute all tests and produce a report of success or failure.  We've done
+      // that successfully if we've gotten here.
+      System.exit(0);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTestRunner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTestRunner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTestRunner.java
@@ -0,0 +1,1557 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.android.ddmlib.AndroidDebugBridge;
+import com.android.ddmlib.IDevice;
+import com.android.ddmlib.MultiLineReceiver;
+import com.android.ddmlib.testrunner.ITestRunListener;
+import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.facebook.buck.android.exopackage.AdbUtils;
+import com.facebook.buck.android.exopackage.AndroidDevice;
+import com.facebook.buck.android.exopackage.AndroidDeviceImpl;
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent.RunFailureStatus;
+import com.facebook.buck.testresultsoutput.TestResultsOutputSender;
+import com.facebook.buck.testrunner.reportlayer.LogExtractorReportLayer;
+import com.facebook.buck.testrunner.reportlayer.PerfettoReportLayer;
+import com.facebook.buck.testrunner.reportlayer.ReportLayer;
+import com.facebook.buck.testrunner.reportlayer.TombstonesReportLayer;
+import com.facebook.buck.testrunner.reportlayer.VideoRecordingReportLayer;
+import com.facebook.buck.util.escaper.BashEscaper;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileVisitOption;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import java.util.stream.Stream;
+
+/** Logcat buffers that can be collected from the device */
+enum LogcatBuffer {
+  MAIN("main"),
+  SYSTEM("system"),
+  RADIO("radio"),
+  EVENTS("events"),
+  CRASH("crash"),
+  DEFAULT("default"),
+  ALL("all");
+
+  private String cliArgument;
+
+  LogcatBuffer(String cliArgument) {
+    this.cliArgument = cliArgument;
+  }
+
+  public String getCliArgument() {
+    return this.cliArgument;
+  }
+}
+
+public class InstrumentationTestRunner extends DeviceRunner {
+
+  private static final String TEST_RESULT_ARTIFACTS_ENV = "TEST_RESULT_ARTIFACTS_DIR";
+  private static final String TEST_RESULT_DIMENSIONS_ENV = "TEST_RESULT_DIMENSIONS_FILE";
+  private static final String TEST_RESULT_APP_SCOPED_ARTIFACTS_ENV =
+      "TEST_RESULT_APP_SCOPED_ARTIFACTS_DIR";
+  private static final String TEST_RESULT_ARTIFACTS_ANNOTATIONS_ENV =
+      "TEST_RESULT_ARTIFACT_ANNOTATIONS_DIR";
+  private static final String TEST_RESULT_APP_SCOPED_ARTIFACTS_ANNOTATIONS_ENV =
+      "TEST_RESULT_APP_SCOPED_ARTIFACT_ANNOTATIONS_DIR";
+  private static final String FORWARDABLE_ENV_PREFIX = "AIT_";
+
+  private static final long ADB_CONNECT_TIMEOUT_MS = 30000;
+  private static final long ADB_CONNECT_TIME_STEP_MS = ADB_CONNECT_TIMEOUT_MS / 10;
+
+  /** Env var gate for per-test JaCoCo coverage. */
+  static final String PER_TEST_COVERAGE_ENABLED_ENV = "PER_TEST_COVERAGE_ENABLED";
+
+  /** Host env var set by the coverage wrapper to the pull destination for per-test artifacts. */
+  static final String PER_TEST_COVERAGE_DIR_ENV = "PER_TEST_COVERAGE_DIR";
+
+  /** Instrumentation arg read by the on-device per-test coverage listener. */
+  static final String PER_TEST_COVERAGE_DIR_ARG = "PER_TEST_COVERAGE_DIR";
+
+  private static final String PER_TEST_COVERAGE_SUBDIR = "per_test_coverage";
+
+  /** Env var to enable per-test timeout enforcement. */
+  static final String PER_TEST_TIMEOUT_ENABLED_ENV = "ANDROID_PER_TEST_TIMEOUT_ENABLED";
+
+  /** Env var to enable proactive target-level timeout stack traces. */
+  static final String PROACTIVE_TIMEOUT_ENABLED_ENV = "ANDROID_PROACTIVE_TIMEOUT_ENABLED";
+
+  /** Env var to set the timeout multiplier for long-running tests. */
+  static final String PER_TEST_TIMEOUT_MULTIPLIER_ENV = "ANDROID_PER_TEST_TIMEOUT_MULTIPLIER";
+
+  /**
+   * Env var controlling how a per-test artifact staging failure is handled. When set to "true", a
+   * staging failure aborts the run. Otherwise staging is best-effort: the failure is logged and the
+   * run continues without per-test artifact collection for that directory (needed for displayless
+   * emulator images that boot without external storage).
+   */
+  static final String FAIL_ON_ARTIFACT_STAGING_ERROR_ENV = "ANDROID_FAIL_ON_ARTIFACT_STAGING_ERROR";
+
+  private static final String INSTRUMENTATION_TEST_DEFAULT_ARTIFACTS_DIR_TEMPLATE =
+      "/sdcard/test_result/%s/%s/";
+  private static final String INSTRUMENTATION_TEST_DEFAULT_ARTIFACTS_FILE_TEMPLATE =
+      "/sdcard/test_result/%s_%s";
+  private static final String INSTRUMENTATION_TEST_APP_SCOPED_API_30_PLUS_ARTIFACTS_DIR_TEMPLATE =
+      "/sdcard/Android/data/%s/files/Download/test_result/%s/";
+  private static final String INSTRUMENTATION_TEST_APP_SCOPED_API_34_PLUS_ARTIFACTS_DIR_TEMPLATE =
+      "/storage/emulated/0/Android/media/%s/test_result/%s/";
+  private static final String PRE_TEST_SETUP_SCRIPT = "PRE_TEST_SETUP_SCRIPT";
+  private static final String APEXES_TO_INSTALL = "APEXES_TO_INSTALL";
+  // On-device root where exopackage artifacts live, keyed by package name; matches the on-device
+  // ExopackageDexLoader convention.
+  private static final String EXOPACKAGE_INSTALL_ROOT = "/data/local/tmp/exopackage";
+
+  private final String packageName;
+  private final String targetPackageName;
+  private final String testRunner;
+  private final File outputDirectory;
+  private final String exopackageLocalPath;
+  @Nullable private final String exopackageSecondaryDexLocalPath;
+  private final boolean attemptUninstallApkUnderTest;
+  private final boolean attemptUninstallInstrumentationApk;
+  private final Map<String, String> extraInstrumentationArguments;
+  private final String extraInstrumentationTestListener;
+  private final Map<String, String> extraFilesToPull;
+  private final Map<String, String> extraDirsToPull;
+  private final boolean debug;
+  private final boolean codeCoverage;
+  private final boolean isSelfInstrumenting;
+  private final List<LogcatBuffer> collectedLogcatBuffers;
+  private final boolean clearPackageData;
+  private final boolean disableAnimations;
+  @Nullable private final String instrumentationApkPath;
+  @Nullable private final String apkUnderTestPath;
+  @Nullable private final String codeCoverageOutputFile;
+  @Nullable private final String apkUnderTestExopackageLocalPath;
+  private final String preTestSetupScript;
+  private final List<String> apexesToInstall;
+
+  @Nullable private final Integer userId;
+
+  /** Prefix for secondary user storage paths */
+  private static final String SECONDARY_USER_STORAGE_PREFIX = "/data/media/";
+
+  private static final String SDCARD_PATH = "/sdcard";
+  private static final String STORAGE_EMULATED_PATH = "/storage/emulated/0";
+  private static final String STORAGE_EMULATED_PREFIX = "/storage/emulated/";
+
+  private final CrashAnalyzer crashAnalyzer = new CrashAnalyzer();
+  private List<ReportLayer> reportLayers = new ArrayList<>();
+
+  protected final AndroidDevice androidDevice;
+  private volatile boolean testRunFailed = false;
+
+  /**
+   * Resolves a device path for the current user. For secondary users, paths like /sdcard and
+   * /storage/emulated/0 are translated to /data/media/{userId}.
+   *
+   * <p>Also handles paths that already contain a user-specific storage path prefix (e.g.,
+   * /storage/emulated/10) by translating them to the current user's storage path.
+   *
+   * @param path The original device path
+   * @return The resolved path appropriate for the current user
+   */
+  private String resolvePathForUser(String path) {
+    if (userId == null || userId == 0) {
+      return path;
+    }
+
+    String userStoragePath = SECONDARY_USER_STORAGE_PREFIX + userId;
+
+    if (path.startsWith(SDCARD_PATH)) {
+      return userStoragePath + path.substring(SDCARD_PATH.length());
+    }
+
+    // Handle /storage/emulated/0 specifically (primary user path)
+    if (path.startsWith(STORAGE_EMULATED_PATH)) {
+      return userStoragePath + path.substring(STORAGE_EMULATED_PATH.length());
+    }
+
+    // Handle /storage/emulated/{other_user_id} paths (e.g., /storage/emulated/10)
+    if (path.startsWith(STORAGE_EMULATED_PREFIX)) {
+      // Find the end of the user ID portion
+      int userIdEndIndex = path.indexOf('/', STORAGE_EMULATED_PREFIX.length());
+      if (userIdEndIndex == -1) {
+        // Path is just /storage/emulated/{userId} with no trailing content
+        return userStoragePath;
+      }
+      // Extract the rest of the path after /storage/emulated/{userId}
+      String remainingPath = path.substring(userIdEndIndex);
+      return userStoragePath + remainingPath;
+    }
+
+    return path;
+  }
+
+  public InstrumentationTestRunner(
+      DeviceArgs deviceArgs,
+      String packageName,
+      String targetPackageName,
+      String testRunner,
+      File outputDirectory,
+      String instrumentationApkPath,
+      String apkUnderTestPath,
+      String exopackageLocalPath,
+      String apkUnderTestExopackageLocalPath,
+      String exopackageSecondaryDexLocalPath,
+      boolean attemptUninstallApkUnderTest,
+      boolean attemptUninstallInstrumentationApk,
+      boolean debug,
+      boolean codeCoverage,
+      String codeCoverageOutputFile,
+      boolean isSelfInstrumenting,
+      Map<String, String> extraInstrumentationArguments,
+      String extraInstrumentationTestListener,
+      Map<String, String> extraFilesToPull,
+      Map<String, String> extraDirsToPull,
+      boolean clearPackageData,
+      boolean disableAnimations,
+      String preTestSetupScript,
+      List<String> apexesToInstall,
+      @Nullable Integer userId) {
+    super(deviceArgs);
+    this.packageName = packageName;
+    this.targetPackageName = targetPackageName;
+    this.testRunner = testRunner;
+    this.outputDirectory = outputDirectory;
+    this.instrumentationApkPath = instrumentationApkPath;
+    this.apkUnderTestPath = apkUnderTestPath;
+    this.exopackageLocalPath = exopackageLocalPath;
+    this.apkUnderTestExopackageLocalPath = apkUnderTestExopackageLocalPath;
+    this.exopackageSecondaryDexLocalPath = exopackageSecondaryDexLocalPath;
+    this.attemptUninstallApkUnderTest = attemptUninstallApkUnderTest;
+    this.attemptUninstallInstrumentationApk = attemptUninstallInstrumentationApk;
+    this.codeCoverageOutputFile = codeCoverageOutputFile;
+    this.extraInstrumentationArguments = extraInstrumentationArguments;
+    this.extraInstrumentationTestListener = extraInstrumentationTestListener;
+    this.extraFilesToPull = extraFilesToPull;
+    this.extraDirsToPull = extraDirsToPull;
+    this.isSelfInstrumenting = isSelfInstrumenting;
+    this.debug = debug;
+    this.codeCoverage = codeCoverage;
+    this.collectedLogcatBuffers =
+        Arrays.asList(LogcatBuffer.CRASH, LogcatBuffer.SYSTEM, LogcatBuffer.MAIN);
+    this.clearPackageData = clearPackageData;
+    this.disableAnimations = disableAnimations;
+    this.preTestSetupScript = preTestSetupScript;
+    this.apexesToInstall = apexesToInstall;
+    this.userId = userId;
+    this.androidDevice = initializeAndroidDevice();
+  }
+
+  protected static class ArgsParser {
+    private final Map<String, String> environment;
+    File outputDirectory = null;
+    DeviceArgs deviceArgs = null;
+    String apkUnderTestPath = null;
+    String packageName = null;
+    String targetPackageName = null;
+    String testRunner = null;
+    String instrumentationApkPath = null;
+    String codeCoverageOutputFile = null;
+    String exopackageLocalPath = null;
+    String apkUnderTestExopackageLocalPath = null;
+    String exopackageSecondaryDexLocalPath = null;
+    String extraInstrumentationTestListener = null;
+    boolean attemptUninstallApkUnderTest = false;
+    boolean attemptUninstallInstrumentationApk = false;
+    boolean debug = false;
+    boolean codeCoverage = false;
+    boolean isSelfInstrumenting = false;
+    boolean clearPackageData = false;
+    boolean disableAnimations = false;
+    boolean collectTombstones = false;
+    boolean recordVideo = false;
+    boolean collectPerfetto = false;
+    Map<String, String> extraInstrumentationArguments = new HashMap<String, String>();
+    Map<String, String> extraFilesToPull = new HashMap<String, String>();
+    Map<String, String> extraDirsToPull = new HashMap<String, String>();
+    Map<String, String> logExtractors = new HashMap<String, String>();
+    String preTestSetupScript = null;
+    List<String> extraApksToInstall = new ArrayList<>();
+    @Nullable Integer userId = null;
+
+    ArgsParser() {
+      this(System.getenv());
+    }
+
+    ArgsParser(Map<String, String> environment) {
+      this.environment = environment;
+    }
+
+    @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+    void fromArgs(String... args) throws IOException {
+
+      for (int i = 0; i < args.length; i++) {
+        switch (args[i]) {
+          case "--test-package-name":
+            packageName = getArgValue(args[++i]);
+            break;
+          case "--target-package-name":
+            targetPackageName = getArgValue(args[++i]);
+            break;
+          case "--test-runner":
+            testRunner = getArgValue(args[++i]);
+            break;
+          case "--output":
+            outputDirectory = new File(args[++i]);
+            if (!outputDirectory.exists() && !outputDirectory.mkdirs()) {
+              System.err.printf(
+                  "The output directory did not exist and failed to create it: %s\n",
+                  outputDirectory);
+              System.exit(1);
+            }
+            break;
+          case "--extra-instrumentation-test-listener":
+            extraInstrumentationTestListener = args[++i];
+            break;
+          case "--apk-under-test-path":
+            apkUnderTestPath = args[++i];
+            break;
+          case "--instrumentation-apk-path":
+            instrumentationApkPath = args[++i];
+            break;
+          case "--exopackage-local-dir":
+            exopackageLocalPath = args[++i];
+            break;
+          case "--apk-under-test-exopackage-local-dir":
+            apkUnderTestExopackageLocalPath = args[++i];
+            break;
+          case "--exopackage-secondary-dex-local-dir":
+            exopackageSecondaryDexLocalPath = args[++i];
+            break;
+          case "--attempt-uninstall":
+            attemptUninstallApkUnderTest = true;
+            attemptUninstallInstrumentationApk = true;
+            break;
+          case "--attempt-uninstall-apk-under-test":
+            attemptUninstallApkUnderTest = true;
+            break;
+          case "--attempt-uninstall-instrumentation-apk":
+            attemptUninstallInstrumentationApk = true;
+            break;
+          case "--debug":
+            debug = true;
+            break;
+          case "--code-coverage":
+            codeCoverage = true;
+            break;
+          case "--code-coverage-output-file":
+            codeCoverageOutputFile = args[++i];
+            break;
+          case "--is-self-instrumenting":
+            isSelfInstrumenting = true;
+            break;
+          case "--extra-instrumentation-argument":
+            String rawArg = args[++i];
+            String[] extraArguments = rawArg.split("=", 2);
+            if (extraArguments.length != 2) {
+              System.err.printf("Not a valid extra arguments argument: %s\n", rawArg);
+              System.exit(1);
+            }
+            extraInstrumentationArguments.put(extraArguments[0], extraArguments[1]);
+            break;
+          case "--extra-file-to-pull":
+            // Format is --extra-file-to-pull /source/path/in/device.txt=/destination/path.txt
+            // Pulls contents of source file into destination file.
+            // Expects both parts of the argument to be files.
+            // Expects destination directory to exist.
+            {
+              String raw = args[++i];
+              String[] parts = raw.split("=", 2);
+              if (parts.length != 2) {
+                System.err.printf("Not a valid file to pull: %s\n", raw);
+                System.exit(1);
+              }
+              extraFilesToPull.put(parts[0], parts[1]);
+              break;
+            }
+          case "--extra-dir-to-pull":
+            // Format is --extra-dir-to-pull /device/source=/directory/destination
+            // Pulls all files from source into destination directory.
+            // Expects both parts of the argument to be directories.
+            // Creates destination directory if it doesn't exist.
+            // Creates clean source directory before the test run.
+            {
+              String raw = args[++i];
+              String[] parts = raw.split("=", 2);
+              if (parts.length != 2) {
+                System.err.printf("Not a valid dir to pull: %s\n", raw);
+                System.exit(1);
+              }
+              extraDirsToPull.put(parts[0], parts[1]);
+              break;
+            }
+          case "--clear-package-data":
+            clearPackageData = true;
+            break;
+          case "--disable-animations":
+            disableAnimations = true;
+            break;
+          case TombstonesReportLayer.ARG:
+            collectTombstones = true;
+            break;
+          case VideoRecordingReportLayer.ARG:
+            recordVideo = true;
+            break;
+          case PerfettoReportLayer.ARG:
+            collectPerfetto = true;
+            break;
+          case LogExtractorReportLayer.ARG:
+            String logExtractorArg = args[++i];
+            String[] logExtractorArgSplit = logExtractorArg.split("=", 2);
+            if (logExtractorArgSplit.length != 2) {
+              System.err.printf("Not a valid log extractor argument: %s\n", logExtractorArg);
+              System.exit(1);
+            }
+            logExtractors.put(logExtractorArgSplit[0], logExtractorArgSplit[1]);
+            break;
+          case "--user":
+            if (i + 1 >= args.length) {
+              System.err.println("--user requires a user ID argument");
+              System.exit(1);
+            }
+            String userIdArg = args[++i];
+            try {
+              userId = Integer.parseInt(userIdArg);
+              if (userId < 0) {
+                System.err.printf("Invalid user ID: %s\n", userIdArg);
+                System.exit(1);
+              }
+            } catch (NumberFormatException e) {
+              System.err.printf("Invalid user ID: %s\n", userIdArg);
+              System.exit(1);
+            }
+            break;
+        }
+      }
+
+      if (packageName == null) {
+        System.err.println("Must pass --test-package-name argument.");
+        System.exit(1);
+      }
+
+      if (targetPackageName == null) {
+        System.err.println("Must pass --target-package-name argument.");
+        System.exit(1);
+      }
+
+      if (testRunner == null) {
+        System.err.println("Must pass --test-runner argument.");
+        System.exit(1);
+      }
+
+      if (outputDirectory == null) {
+        System.err.println("Must pass --output argument.");
+        System.exit(1);
+      }
+
+      // Process env-based setup - using package name to uniquify the folders
+      // and avoid concurrency problems
+
+      String testArtifactsPath = environment.get(TEST_RESULT_ARTIFACTS_ENV);
+      if (testArtifactsPath != null) {
+        String devicePath =
+            String.format(
+                INSTRUMENTATION_TEST_DEFAULT_ARTIFACTS_DIR_TEMPLATE, "artifacts", packageName);
+        extraDirsToPull.put(devicePath, testArtifactsPath);
+        extraInstrumentationArguments.put(TEST_RESULT_ARTIFACTS_ENV, devicePath);
+      }
+
+      String testArtifactAnnotationsPath = environment.get(TEST_RESULT_ARTIFACTS_ANNOTATIONS_ENV);
+      if (testArtifactAnnotationsPath != null) {
+        String devicePath =
+            String.format(
+                INSTRUMENTATION_TEST_DEFAULT_ARTIFACTS_DIR_TEMPLATE,
+                "artifact_annotations",
+                packageName);
+        extraDirsToPull.put(devicePath, testArtifactAnnotationsPath);
+        extraInstrumentationArguments.put(TEST_RESULT_ARTIFACTS_ANNOTATIONS_ENV, devicePath);
+      }
+
+      String preTestSetupEnv = environment.get(PRE_TEST_SETUP_SCRIPT);
+      if (preTestSetupEnv != null) {
+        this.preTestSetupScript = preTestSetupEnv;
+      }
+
+      String extraApksToInstall = environment.get(APEXES_TO_INSTALL);
+      if (extraApksToInstall != null) {
+        this.extraApksToInstall = Arrays.asList(extraApksToInstall.split(","));
+      }
+
+      deviceArgs = getDeviceArgs(args);
+    }
+  }
+
+  public String getPackageName() {
+    return packageName;
+  }
+
+  public boolean hasTestRunFailed() {
+    return this.testRunFailed;
+  }
+
+  public void addReportLayer(ReportLayer reportLayer) {
+    reportLayers.add(reportLayer);
+  }
+
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  public static InstrumentationTestRunner fromArgs(String... args) throws IOException {
+    ArgsParser argsParser = new ArgsParser();
+    argsParser.fromArgs(args);
+    InstrumentationTestRunner runner =
+        new InstrumentationTestRunner(
+            argsParser.deviceArgs,
+            argsParser.packageName,
+            argsParser.targetPackageName,
+            argsParser.testRunner,
+            argsParser.outputDirectory,
+            argsParser.instrumentationApkPath,
+            argsParser.apkUnderTestPath,
+            argsParser.exopackageLocalPath,
+            argsParser.apkUnderTestExopackageLocalPath,
+            argsParser.exopackageSecondaryDexLocalPath,
+            argsParser.attemptUninstallApkUnderTest,
+            argsParser.attemptUninstallInstrumentationApk,
+            argsParser.debug,
+            argsParser.codeCoverage,
+            argsParser.codeCoverageOutputFile,
+            argsParser.isSelfInstrumenting,
+            argsParser.extraInstrumentationArguments,
+            argsParser.extraInstrumentationTestListener,
+            argsParser.extraFilesToPull,
+            argsParser.extraDirsToPull,
+            argsParser.clearPackageData,
+            argsParser.disableAnimations,
+            argsParser.preTestSetupScript,
+            argsParser.extraApksToInstall,
+            argsParser.userId);
+    if (argsParser.recordVideo) {
+      runner.addReportLayer(new VideoRecordingReportLayer(runner));
+    }
+    runner.addReportLayer(new TombstonesReportLayer(runner, argsParser.collectTombstones));
+    if (argsParser.collectPerfetto) {
+      runner.addReportLayer(new PerfettoReportLayer(runner));
+    }
+    if (!argsParser.logExtractors.isEmpty()) {
+      runner.addReportLayer(new LogExtractorReportLayer(runner, argsParser.logExtractors));
+    }
+    return runner;
+  }
+
+  private static class AnimationScales {
+    public final float windowAnimationScale;
+    public final float transitionAnimationScale;
+    public final float animatorDurationScale;
+
+    public AnimationScales(
+        float windowAnimationScale, float transitionAnimationScale, float animatorDurationScale) {
+      this.windowAnimationScale = windowAnimationScale;
+      this.transitionAnimationScale = transitionAnimationScale;
+      this.animatorDurationScale = animatorDurationScale;
+    }
+  }
+
+  protected void installPackage(String path, String packageName) throws Throwable {
+    // When running as secondary user, install for all users so the APK is available
+    // to the secondary user context
+    String userTarget = (this.userId != null && this.userId > 0) ? "all" : null;
+    androidDevice.installApkOnDevice(
+        new File(path),
+        false,
+        false,
+        true,
+        false,
+        userTarget,
+        /* allowFastDeploy= */ false,
+        packageName);
+  }
+
+  /**
+   * Execute adb shell command using AndroidDevice and AdbUtils.
+   *
+   * @param command the shell command to execute
+   * @return the output of the shell command
+   * @throws Exception if command execution fails
+   */
+  protected String executeAdbShellCommand(String command) throws Exception {
+    return adbUtils.executeAdbShellCommand(command, androidDevice.getSerialNumber(), false);
+  }
+
+  protected AndroidDevice initializeAndroidDevice() {
+    String deviceSerial = deviceArgs.deviceSerial;
+
+    // Validate device selection arguments
+    if (deviceSerial == null && !deviceArgs.autoRunOnConnectedDevice) {
+      throw new IllegalArgumentException(
+          "Either deviceSerial must be provided or autoRunOnConnectedDevice must be enabled");
+    }
+
+    AndroidDevice device = null;
+
+    // If both deviceSerial and autoRunOnConnectedDevice are specified, deviceSerial takes
+    // precedence
+    if (deviceSerial == null && deviceArgs.autoRunOnConnectedDevice) {
+      List<AndroidDevice> devices = this.adbUtils.getDevices();
+      if (!devices.isEmpty()) {
+        // TODO: If more than one device is attached, we currently select the first one.
+        // Consider warning the user or providing a way to specify which device to use.
+        device = devices.get(0);
+      }
+    } else if (deviceSerial != null) {
+      // For TCP-connected devices (e.g., emulators at host:port), ensure the ADB server
+      // knows about the device before we proceed. ADB servers don't auto-discover TCP
+      // devices — "adb connect" must be called first.
+      if (isTcpDevice(deviceSerial)) {
+        boolean found = false;
+        for (AndroidDevice d : this.adbUtils.getDevices()) {
+          if (d.getSerialNumber().equals(deviceSerial)) {
+            found = true;
+            break;
+          }
+        }
+        if (!found) {
+          System.err.println("Device " + deviceSerial + " not found, attempting adb connect...");
+          connectTcpDevice(deviceSerial);
+          long start = System.currentTimeMillis();
+          while (!found) {
+            long timeLeft = start + ADB_CONNECT_TIMEOUT_MS - System.currentTimeMillis();
+            if (timeLeft <= 0) {
+              break;
+            }
+            try {
+              Thread.sleep(ADB_CONNECT_TIME_STEP_MS);
+            } catch (InterruptedException e) {
+              Thread.currentThread().interrupt();
+              break;
+            }
+            for (AndroidDevice d : this.adbUtils.getDevices()) {
+              if (d.getSerialNumber().equals(deviceSerial)) {
+                found = true;
+                break;
+              }
+            }
+          }
+          if (!found) {
+            System.err.println(
+                "Warning: Device "
+                    + deviceSerial
+                    + " not found after adb connect, proceeding anyway");
+          }
+        }
+      }
+      device = new AndroidDeviceImpl(deviceSerial, this.adbUtils);
+    }
+
+    if (device == null) {
+      throw new RuntimeException("Failed to initialize AndroidDevice");
+    }
+
+    return device;
+  }
+
+  /**
+   * Resolves a ddmlib {@link IDevice} for the given serial number. This is needed solely because
+   * {@link RemoteAndroidTestRunner} requires an {@link IDevice} to execute {@code am instrument}.
+   * All other device interactions use {@link AndroidDevice} via {@link AdbUtils}.
+   */
+  protected IDevice resolveIDevice(String serial) throws InterruptedException {
+    AndroidDebugBridge.initIfNeeded(/* clientSupport */ false);
+    AndroidDebugBridge adb = AndroidDebugBridge.createBridge(getAdbPath(), false);
+    if (adb == null) {
+      System.err.println("Failed to connect to adb. Make sure adb server is running.");
+      System.exit(1);
+      return null;
+    }
+
+    long start = System.currentTimeMillis();
+    while (!adb.isConnected() || !adb.hasInitialDeviceList()) {
+      long timeLeft = start + ADB_CONNECT_TIMEOUT_MS - System.currentTimeMillis();
+      if (timeLeft <= 0) {
+        break;
+      }
+      Thread.sleep(ADB_CONNECT_TIME_STEP_MS);
+    }
+
+    if (!adb.isConnected() || !adb.hasInitialDeviceList()) {
+      System.err.println("Unable to set up adb.");
+      System.exit(1);
+      return null;
+    }
+
+    for (IDevice device : adb.getDevices()) {
+      if (device.getSerialNumber().equals(serial)) {
+        return device;
+      }
+    }
+
+    System.err.printf("Unable to find device with serial %s via ddmlib%n", serial);
+    System.exit(1);
+    return null;
+  }
+
+  /**
+   * Returns true if the serial looks like a TCP-connected device (host:port format), which is
+   * typical for emulators connected via {@code adb connect}.
+   */
+  private static boolean isTcpDevice(String serial) {
+    return serial != null && serial.contains(":");
+  }
+
+  /**
+   * Runs {@code adb connect <serial>} to ensure the ADB server knows about a TCP-connected device
+   * (e.g., an emulator).
+   */
+  private void connectTcpDevice(String serial) {
+    try {
+      String result = adbUtils.executeAdbCommand("connect " + serial, null, true);
+      System.err.println("adb connect " + serial + ": " + result.trim());
+    } catch (Exception e) {
+      System.err.println("Failed to run adb connect " + serial + ": " + e.getMessage());
+    }
+  }
+
+  @SuppressWarnings({"PMD.BlacklistedSystemGetenv", "PMD.BlacklistedDefaultProcessMethod"})
+  public void run() throws Throwable {
+    // Proactive timeout: start the timer as early as possible since TPX_TIMEOUT_SEC counts from
+    // process start. ADB setup (APK install, directory creation) can consume significant time,
+    // so placing this after setup would cause the timer to fire too late.
+    Optional<TestResultsOutputSender> testResultsOutputSender =
+        TestResultsOutputSender.fromDefaultEnvName();
+    TpxTimeoutBufferManager tpxTimeoutBufferManager = null;
+    if (testResultsOutputSender.isPresent()
+        && "true".equals(System.getenv(PROACTIVE_TIMEOUT_ENABLED_ENV))) {
+      ScheduledExecutorService watchdogExecutor = Executors.newScheduledThreadPool(1);
+      tpxTimeoutBufferManager =
+          TpxTimeoutBufferManager.create(testResultsOutputSender.get(), watchdogExecutor);
+    }
+
+    // Resolve a ddmlib IDevice solely for RemoteAndroidTestRunner compatibility.
+    // All other device interactions use this.androidDevice (AdbUtils-based).
+    IDevice iDevice = resolveIDevice(androidDevice.getSerialNumber());
+
+    if (this.instrumentationApkPath != null) {
+      if (this.apkUnderTestPath != null) {
+        // Install both APKs in parallel to improve performance
+        ExecutorService executor = Executors.newFixedThreadPool(2);
+        try {
+          Future<Void> instrumentationFuture =
+              executor.submit(
+                  () -> {
+                    try {
+                      installPackage(this.instrumentationApkPath, this.packageName);
+                      return null;
+                    } catch (Throwable t) {
+                      throw new RuntimeException("Failed to install instrumentation APK", t);
+                    }
+                  });
+
+          Future<Void> apkUnderTestFuture =
+              executor.submit(
+                  () -> {
+                    try {
+                      installPackage(this.apkUnderTestPath, this.targetPackageName);
+                      return null;
+                    } catch (Throwable t) {
+                      throw new RuntimeException("Failed to install APK under test", t);
+                    }
+                  });
+
+          // Wait for both installations to complete and handle any exceptions
+          try {
+            instrumentationFuture.get();
+            apkUnderTestFuture.get();
+          } catch (ExecutionException e) {
+            throw e.getCause();
+          }
+        } finally {
+          executor.shutdown();
+          executor.awaitTermination(60, TimeUnit.SECONDS);
+        }
+      } else {
+        // Single APK installation (no APK under test)
+        installPackage(this.instrumentationApkPath, this.packageName);
+      }
+    }
+
+    if (this.exopackageLocalPath != null) {
+      Path localBase = Paths.get(exopackageLocalPath);
+      syncExopackageDir(localBase);
+    }
+
+    if (this.apkUnderTestExopackageLocalPath != null) {
+      Path localBase = Paths.get(apkUnderTestExopackageLocalPath);
+      syncExopackageDir(localBase);
+    }
+
+    if (this.exopackageSecondaryDexLocalPath != null) {
+      pushExopackageSecondaryDex(Paths.get(this.exopackageSecondaryDexLocalPath), this.packageName);
+    }
+
+    String appScopedStorageDeviceArtifactsPath =
+        getAppScopedStoragePath(packageName, targetPackageName, isSelfInstrumenting, "artifacts");
+    if (appScopedStorageDeviceArtifactsPath != null) {
+      String testArtifactsPath = getenv(TEST_RESULT_ARTIFACTS_ENV);
+      if (testArtifactsPath != null) {
+        extraDirsToPull.put(appScopedStorageDeviceArtifactsPath, testArtifactsPath);
+        extraInstrumentationArguments.put(
+            TEST_RESULT_APP_SCOPED_ARTIFACTS_ENV, appScopedStorageDeviceArtifactsPath);
+      }
+    }
+
+    String testDimensionsPath = getenv(TEST_RESULT_DIMENSIONS_ENV);
+    if (testDimensionsPath != null) {
+      String appScopedStorageDeviceDimensionsPath =
+          getAppScopedStoragePath(
+              packageName, targetPackageName, isSelfInstrumenting, "dimensions", "dimensions.tsv");
+      if (appScopedStorageDeviceDimensionsPath != null) {
+        extraFilesToPull.put(appScopedStorageDeviceDimensionsPath, testDimensionsPath);
+        extraInstrumentationArguments.put(
+            TEST_RESULT_DIMENSIONS_ENV, appScopedStorageDeviceDimensionsPath);
+      } else {
+        String devicePath =
+            String.format(
+                INSTRUMENTATION_TEST_DEFAULT_ARTIFACTS_FILE_TEMPLATE,
+                packageName,
+                "dimensions.tsv");
+        extraFilesToPull.put(devicePath, testDimensionsPath);
+        extraInstrumentationArguments.put(TEST_RESULT_DIMENSIONS_ENV, devicePath);
+      }
+    }
+
+    // Install the extra APEXes before the preTestSetupScript.
+    // If installation requires reboot, such as if you are sideloading an APEX that doesn't support
+    // rebootless updating per https://source.android.com/docs/core/ota/apex#installing-an-apex,
+    // that can be added in preTestSetupScript, e.g.
+    // arvr/projects/codec_avatar/prod/pre_test_setup_script_with_apex.sh.
+    if (this.apexesToInstall != null && !this.apexesToInstall.isEmpty()) {
+      System.err.println(String.format("Installing %d APEX(es)...", this.apexesToInstall.size()));
+
+      // Prepare device for APEX installation once before the loop
+      final boolean softRebootAvailable = androidDevice.prepareForApexInstallation();
+
+      for (int i = 0; i < this.apexesToInstall.size(); i++) {
+        final String apexPath = this.apexesToInstall.get(i);
+        final boolean isLast = (i == this.apexesToInstall.size() - 1);
+
+        System.err.println(
+            String.format(
+                "Installing APEX %d/%d: %s...", i + 1, this.apexesToInstall.size(), apexPath));
+        androidDevice.installApexOnDevice(
+            new File(apexPath), false, isLast, softRebootAvailable, true);
+      }
+
+      System.err.println(
+          String.format("All %d APEX(es) installed successfully.", this.apexesToInstall.size()));
+    }
+
+    if (this.preTestSetupScript != null) {
+      System.err.println("Running pre test setup: " + this.preTestSetupScript);
+      try {
+        Process process =
+            new ProcessBuilder()
+                .command(Arrays.asList(this.preTestSetupScript))
+                .inheritIO()
+                .start();
+        System.err.println("Executing pre test setup process: " + this.preTestSetupScript);
+        boolean completedInTime = process.waitFor(15, TimeUnit.MINUTES);
+        if (completedInTime != true) {
+          throw new RuntimeException("Pre-test setup script timed out");
+        }
+        int exitCode = process.exitValue();
+        if (exitCode != 0) {
+          throw new RuntimeException("Pre-test setup script failed with exit code: " + exitCode);
+        }
+      } catch (IOException | InterruptedException e) {
+        throw new RuntimeException("An error occurred while running the pre-test setup script", e);
+      }
+      System.err.println("Pre test setup completed: " + this.preTestSetupScript);
+    }
+
+    String appScopedStorageDeviceAnnotationsPath =
+        getAppScopedStoragePath(
+            packageName, targetPackageName, isSelfInstrumenting, "artifact_annotations");
+    if (appScopedStorageDeviceAnnotationsPath != null) {
+      String testArtifactAnnotationsPath = System.getenv(TEST_RESULT_ARTIFACTS_ANNOTATIONS_ENV);
+      if (testArtifactAnnotationsPath != null) {
+        extraDirsToPull.put(appScopedStorageDeviceAnnotationsPath, testArtifactAnnotationsPath);
+        extraInstrumentationArguments.put(
+            TEST_RESULT_APP_SCOPED_ARTIFACTS_ANNOTATIONS_ENV,
+            appScopedStorageDeviceAnnotationsPath);
+      }
+    }
+
+    String hostPerTestCoverageDir = setUpPerTestCoveragePull();
+
+    if (this.clearPackageData) {
+      executeAdbShellCommand("pm clear " + this.packageName);
+      executeAdbShellCommand("pm clear " + this.targetPackageName);
+    }
+
+    AnimationScales originalWindowAnimationScales = null;
+
+    if (this.disableAnimations) {
+      originalWindowAnimationScales = getAnimationScales();
+      setAnimationScales(new AnimationScales(0f, 0f, 0f));
+    }
+
+    // Increase logcat buffer size to 16MB.
+    executeAdbShellCommand("logcat -G 16M");
+
+    // Clear logcat logs prior to test run
+    executeAdbShellCommand("logcat -c");
+
+    // Clean up + stage output directories before the run.
+    //
+    // Cleanup is mandatory: a stale directory left over from a prior run could pollute results, so
+    // a failed cleanup always aborts the run.
+    //
+    // Staging (creating the dir) is best-effort by default: some displayless/emulator images boot
+    // without external storage (no MediaProvider -> /sdcard unmounted), and that must not abort the
+    // entire test run. On such a device the failure is logged and the run continues; per-test
+    // artifacts for that dir just won't be collected. Set ANDROID_FAIL_ON_ARTIFACT_STAGING_ERROR to
+    // "true" to make a staging failure abort the run instead.
+    boolean failOnArtifactStagingError = "true".equals(getenv(FAIL_ON_ARTIFACT_STAGING_ERROR_ENV));
+    for (final String devicePath : this.extraDirsToPull.keySet()) {
+      String resolvedPath = resolvePathForUser(devicePath);
+      String output = executeAdbShellCommand("rm -fr " + resolvedPath);
+
+      if (directoryExists(resolvedPath)) {
+        System.err.printf(
+            "Failed to clean up directory %s due to error: %s\n", resolvedPath, output);
+        System.exit(1);
+      }
+
+      try {
+        output = executeAdbShellCommand("mkdir -p " + resolvedPath);
+        if (!directoryExists(resolvedPath)) {
+          throw new RuntimeException(String.format("mkdir did not create directory: %s", output));
+        }
+      } catch (Exception e) {
+        if (failOnArtifactStagingError) {
+          System.err.printf(
+              "Failed to create directory %s due to error: %s\n", resolvedPath, e.getMessage());
+          System.exit(1);
+        }
+        System.err.printf(
+            "Warning: could not stage artifact directory %s; external storage may be"
+                + " unavailable on this device (e.g. a displayless emulator without"
+                + " MediaProvider). Continuing without per-test artifact collection for this"
+                + " dir. Error: %s\n",
+            resolvedPath, e.getMessage());
+      }
+    }
+
+    for (ReportLayer layer : this.reportLayers) {
+      layer.initialize();
+    }
+
+    try {
+      RemoteAndroidTestRunner runner =
+          new RemoteAndroidTestRunner(this.packageName, this.testRunner, iDevice);
+
+      for (Map.Entry<String, String> entry : this.extraInstrumentationArguments.entrySet()) {
+        runner.addInstrumentationArg(
+            entry.getKey(), BashEscaper.BASH_ESCAPER.apply(entry.getValue()));
+      }
+
+      // Set prefixed env vars as instrumentation args without the prefix.
+      for (Map.Entry<String, String> entry : getenv().entrySet()) {
+        if (entry.getKey().startsWith(FORWARDABLE_ENV_PREFIX)) {
+          runner.addInstrumentationArg(
+              entry.getKey().substring(FORWARDABLE_ENV_PREFIX.length()),
+              BashEscaper.BASH_ESCAPER.apply(entry.getValue()));
+        }
+      }
+
+      if (debug) {
+        runner.setDebug(true);
+      }
+
+      String coverageTempDir = getenv("COVERAGE_COLLECTION_TMPDIR");
+      boolean useJaCoCoCoverage = getenv("USE_JACOCO_COVERAGE") != null;
+      if (codeCoverage || (useJaCoCoCoverage && coverageTempDir != null)) {
+        runner.setCoverage(true);
+      }
+      ITestRunListener extraListener = null;
+      if (this.extraInstrumentationTestListener != null) {
+        Class<?> clazz = Class.forName(this.extraInstrumentationTestListener);
+        Constructor<?>[] ctors = clazz.getDeclaredConstructors();
+        ctors[0].setAccessible(true);
+        extraListener = (ITestRunListener) ctors[0].newInstance(deviceArgs.deviceSerial, runner);
+        if (extraListener == null) {
+          System.err.printf("Failed to construct %s\n", this.extraInstrumentationTestListener);
+          System.exit(1);
+        }
+      }
+
+      BuckXmlTestRunListener buckXmlListener = new BuckXmlTestRunListener(androidDevice, adbUtils);
+      ITestRunListener trimLineListener =
+          new ITestRunListener() {
+            /**
+             * Before the actual run starts (and after the InstrumentationResultsParser is created),
+             * we need to do some reflection magic to make RemoteAndroidTestRunner not trim
+             * indentation from lines.
+             */
+            @Override
+            public void testRunStarted(String runName, int testCount) {
+              setTrimLine(runner, false);
+            }
+
+            @Override
+            public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) {}
+
+            @Override
+            public void testRunFailed(String errorMessage) {
+              System.err.println("Test Run Failed: " + errorMessage);
+              testRunFailed = true;
+            }
+
+            @Override
+            public void testStarted(TestIdentifier test) {}
+
+            @Override
+            public void testFailed(TestIdentifier test, String trace) {}
+
+            @Override
+            public void testAssumptionFailure(TestIdentifier test, String trace) {}
+
+            @Override
+            public void testIgnored(TestIdentifier test) {}
+
+            @Override
+            public void testEnded(TestIdentifier test, Map<String, String> testMetrics) {}
+
+            @Override
+            public void testRunStopped(long elapsedTime) {}
+          };
+
+      buckXmlListener.setReportDir(this.outputDirectory);
+
+      List<ITestRunListener> listeners = new ArrayList<ITestRunListener>();
+      if (extraListener != null) {
+        listeners.add(extraListener);
+      }
+      listeners.add(trimLineListener);
+      listeners.add(buckXmlListener);
+
+      // Determine the result listener for timeout enforcement.
+      ITestRunListener resultListener = buckXmlListener;
+
+      if (testResultsOutputSender.isPresent()) {
+        InstrumentationTpxStandardOutputTestListener tpxListener =
+            new InstrumentationTpxStandardOutputTestListener(
+                testResultsOutputSender.get(), androidDevice, adbUtils);
+        listeners.add(tpxListener);
+        resultListener = tpxListener;
+      }
+
+      if ("true".equals(System.getenv(PER_TEST_TIMEOUT_ENABLED_ENV))) {
+        listeners.add(new InstrumentationTimeoutEnforcingRunListener(resultListener));
+      }
+
+      if (this.userId != null) {
+        runner.addInstrumentationArg("user", this.userId.toString());
+      }
+      runner.run(listeners);
+
+      // All tests completed normally — mark as completed so proactive timer is a no-op
+      if (tpxTimeoutBufferManager != null) {
+        tpxTimeoutBufferManager.markCompleted();
+      }
+
+      if (this.disableAnimations) {
+        setAnimationScales(originalWindowAnimationScales);
+      }
+
+      if (this.codeCoverageOutputFile != null || (useJaCoCoCoverage && coverageTempDir != null)) {
+        String destCovFileInHost = this.codeCoverageOutputFile;
+
+        if (coverageTempDir != null) {
+          (new File(coverageTempDir)).mkdirs();
+          destCovFileInHost = coverageTempDir + "/target-package-coverage.ec";
+        }
+
+        String covFileInEmu = "/data/data/" + this.targetPackageName + "/files/coverage.ec";
+        String covFileInSdcard = resolvePathForUser("/sdcard/coverage.ec");
+        String cpOutput =
+            executeAdbShellCommand("su root cp " + covFileInEmu + " " + covFileInSdcard);
+
+        System.out.println(cpOutput);
+        pullFile(covFileInSdcard, destCovFileInHost);
+
+        String coverageParser = getenv("COVERAGE_PARSER");
+        if (coverageParser != null) {
+
+          ArrayList<String> cmd_args =
+              new ArrayList<String>(Arrays.asList(coverageParser.split(" ")));
+
+          System.out.println("coverge parser command: " + String.join(" ", cmd_args));
+
+          ProcessBuilder coverageParserProcessBuilder = new ProcessBuilder().command(cmd_args);
+
+          coverageParserProcessBuilder.inheritIO();
+
+          Process coverageParserProcess = coverageParserProcessBuilder.start();
+          coverageParserProcess.waitFor();
+        }
+      }
+      for (Map.Entry<String, String> entry : this.extraFilesToPull.entrySet()) {
+        String resolvedPath = resolvePathForUser(entry.getKey());
+        pullFile(resolvedPath, entry.getValue());
+      }
+      for (Map.Entry<String, String> entry : this.extraDirsToPull.entrySet()) {
+        String resolvedPath = resolvePathForUser(entry.getKey());
+        pullDir(resolvedPath, entry.getValue());
+      }
+
+      maybeEmitPerTestCoverageInfraFailure(hostPerTestCoverageDir, testResultsOutputSender);
+
+    } finally {
+      this.collectAdbLogs();
+
+      // Restore logcat buffer size to default.
+      executeAdbShellCommand("logcat -G 256K");
+
+      for (ReportLayer layer : this.reportLayers) {
+        layer.report();
+      }
+      if (this.attemptUninstallInstrumentationApk) {
+        try {
+          androidDevice.uninstallPackage(this.packageName);
+        } catch (Exception e) {
+          System.err.printf("Failed to uninstall instrumentation package: %s\n", e);
+        }
+      }
+      if (this.attemptUninstallApkUnderTest) {
+        try {
+          androidDevice.uninstallPackage(this.targetPackageName);
+        } catch (Exception e) {
+          System.err.printf("Failed to uninstall target package: %s\n", e);
+        }
+      }
+    }
+  }
+
+  public Process exec(String command) throws IOException {
+    return Runtime.getRuntime().exec(command);
+  }
+
+  @Nullable
+  private String setUpPerTestCoveragePull() {
+    if (!"true".equals(getenv(PER_TEST_COVERAGE_ENABLED_ENV))) {
+      return null;
+    }
+
+    String devicePerTestCoveragePath =
+        getAppScopedStoragePath(
+            packageName, targetPackageName, isSelfInstrumenting, PER_TEST_COVERAGE_SUBDIR);
+    if (devicePerTestCoveragePath == null) {
+      devicePerTestCoveragePath =
+          String.format(
+              INSTRUMENTATION_TEST_DEFAULT_ARTIFACTS_DIR_TEMPLATE,
+              PER_TEST_COVERAGE_SUBDIR,
+              packageName);
+    }
+    String hostPerTestCoverageDir = getHostPerTestCoverageDir();
+    if (hostPerTestCoverageDir != null) {
+      extraDirsToPull.put(devicePerTestCoveragePath, hostPerTestCoverageDir);
+      extraInstrumentationArguments.put(PER_TEST_COVERAGE_DIR_ARG, devicePerTestCoveragePath);
+    }
+    return hostPerTestCoverageDir;
+  }
+
+  @Nullable
+  private String getHostPerTestCoverageDir() {
+    String hostPerTestCoverageDir = getenv(PER_TEST_COVERAGE_DIR_ENV);
+    if (hostPerTestCoverageDir != null && !hostPerTestCoverageDir.isEmpty()) {
+      return hostPerTestCoverageDir;
+    }
+
+    String testArtifactsPath = getenv(TEST_RESULT_ARTIFACTS_ENV);
+    if (testArtifactsPath == null || testArtifactsPath.isEmpty()) {
+      return null;
+    }
+    return Paths.get(testArtifactsPath, PER_TEST_COVERAGE_SUBDIR).toString();
+  }
+
+  // Pairs with PerTestAndroidCoverageRunListener#onFirstCoverageError, which writes
+  // "coverage_error.txt" inside the per-test coverage output dir on the first agent-side failure.
+  // Without this signal a silently-broken agent looks identical to a successful run with zero
+  // probes (empty manifest.jsonl) — surfacing it as INFRA_FAILURE makes the next regression
+  // visible in test results instead of waiting for someone to notice missing per-test artifacts.
+  private static void maybeEmitPerTestCoverageInfraFailure(
+      String hostPerTestCoverageDir, Optional<TestResultsOutputSender> sender) {
+    if (hostPerTestCoverageDir == null || !sender.isPresent()) {
+      return;
+    }
+    Path sentinel = Paths.get(hostPerTestCoverageDir, "coverage_error.txt");
+    if (!Files.exists(sentinel)) {
+      return;
+    }
+    try {
+      String contents = new String(Files.readAllBytes(sentinel), StandardCharsets.UTF_8);
+      int newline = contents.indexOf('\n');
+      String firstLine = (newline >= 0) ? contents.substring(0, newline) : contents;
+      sender
+          .get()
+          .sendRunFailure(
+              RunFailureStatus.INFRA_FAILURE,
+              System.currentTimeMillis(),
+              "Per-test coverage collection failed: " + firstLine,
+              contents);
+    } catch (IOException e) {
+      System.err.printf("Failed to read per-test coverage error sentinel: %s\n", e);
+    }
+  }
+
+  @Nullable
+  private String getDeviceLogcatOutputForBuffer(LogcatBuffer buffer) {
+    String adbCommand = String.format("logcat -d -b \"%s\"", buffer.getCliArgument());
+
+    try {
+      return adbUtils.executeAdbShellCommand(adbCommand, androidDevice.getSerialNumber(), true);
+    } catch (Exception e) {
+      System.err.printf("Encountered an error attempting to pull logcat output %s\n", e);
+      return null;
+    }
+  }
+
+  /**
+   * create TRA path for logcat buffer
+   *
+   * @param bufferName name of the buffer
+   * @return path to the tra
+   * @throws IOException when fail to create the path
+   */
+  public Path createPathForLogcatBuffer(String bufferName) throws IOException {
+    return this.createTRALogcatLog(
+        String.format("Logcat `%s` Buffer Output", bufferName),
+        String.format("logcat_%s_buffer_logs", bufferName));
+  }
+
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  private void collectAdbLogs() {
+    try {
+      StringBuilder allLogOutput = new StringBuilder();
+
+      for (LogcatBuffer buffer : this.collectedLogcatBuffers) {
+        String bufferName = buffer.getCliArgument();
+        Path traPath = this.createPathForLogcatBuffer(bufferName);
+        if (traPath == null) {
+          return;
+        }
+        String logOutput = getDeviceLogcatOutputForBuffer(buffer);
+        if (logOutput == null) {
+          continue;
+        }
+
+        // Accumulate all log output for crash analysis
+        allLogOutput.append("=== ").append(bufferName.toUpperCase()).append(" BUFFER ===\n");
+        allLogOutput.append(logOutput).append("\n");
+
+        try (FileWriter logWriter = new FileWriter(traPath.toString())) {
+          logWriter.write(logOutput);
+        }
+      }
+
+      // Analyze all collected logcat output for crash information
+      crashAnalyzer.analyzeCrashInformation(allLogOutput.toString());
+
+    } catch (IOException e) {
+      e.printStackTrace(System.err);
+      System.err.printf("Failed to write logs from buffer failed with error: %s\n", e);
+    }
+  }
+
+  /**
+   * create TRA
+   *
+   * @param type TRA type
+   * @param description description of to be created TRA
+   * @param name name of the TRA
+   * @return Path of the created TRA, null if the creation is not successful
+   * @throws IOException the exception may throw from file writing.
+   */
+  public Path createTRA(String type, String description, String name) throws IOException {
+    // create the annotation file
+    String annotationTemplate =
+        String.format("{\"type\": {\"%s\": {}}, \"description\": \"%s\"}", type, description);
+    return createTRA(annotationTemplate, name);
+  }
+
+  public Path createTRALogcatLog(String description, String name) throws IOException {
+    // Use Logcat type(id = 4 https://fburl.com/code/8xzvasdf)
+    String annotationTemplate =
+        String.format(
+            "{\"type\": {\"formatted_log\": {\"log_source\": 4}}, \"description\": \"%s\"}",
+            description);
+    return createTRA(annotationTemplate, name);
+  }
+
+  public Path createTRAPlainTextLog(String description, String name) throws IOException {
+    // Use PLAIN_TEXT type(id = 5 https://fburl.com/code/8xzvasdf)
+    String annotationTemplate =
+        String.format(
+            "{\"type\": {\"formatted_log\": {\"log_source\": 5}}, \"description\": \"%s\"}",
+            description);
+    return createTRA(annotationTemplate, name);
+  }
+
+  private Path createTRA(String annotationTemplate, String name) throws IOException {
+    /// get TRA directories
+    String testArtifactsPath = getenv(TEST_RESULT_ARTIFACTS_ENV);
+    String testArtifactsAnnotationsPath = getenv(TEST_RESULT_ARTIFACTS_ANNOTATIONS_ENV);
+    if (testArtifactsPath == null || testArtifactsAnnotationsPath == null) {
+      System.out.printf("The environment variables for TRA were not provided.\n");
+      return null;
+    }
+    Path annotationsPath =
+        Paths.get(testArtifactsAnnotationsPath, String.format("%s.annotation", name));
+    Files.write(annotationsPath, annotationTemplate.getBytes(StandardCharsets.UTF_8));
+
+    // create the artifact file
+    return Paths.get(testArtifactsPath, name);
+  }
+
+  /**
+   * Pulls file directory from the device to local directory.
+   *
+   * @param sourceDir the dir of the source
+   * @param destinationDir the dir of the destination
+   * @throws Exception exceptions may throw from file operations
+   */
+  public void pullDir(String sourceDir, String destinationDir) throws Exception {
+    if (!directoryExists(sourceDir)) {
+      // source dir or one of its parents doesn't exist, nothing to pull.
+      System.err.printf("Failed to locate source directory: %s\n", sourceDir);
+      return;
+    }
+    File destinationDirFile = new File(destinationDir);
+    if (!destinationDirFile.exists()) {
+      destinationDirFile.mkdirs();
+    }
+    String sourceDirWithContents = sourceDir.endsWith("/") ? sourceDir + "." : sourceDir + "/.";
+    transferFile("pull", sourceDirWithContents, destinationDir);
+  }
+
+  // push single file
+  public void pushFileWithSyncService(String local, String remote) throws Exception {
+    pushFile(local, remote);
+  }
+
+  // pull single file
+  public void pullFileWithSyncService(String remote, String local) throws Exception {
+    pullFile(remote, local);
+  }
+
+  // Java has no setenv(), so this is needed to be able to overwrite env vars in tests
+  // the lint suggests to use EnvVariablesProvider, but the
+  // compiler cannot find it
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  protected String getenv(String env) {
+    return System.getenv(env);
+  }
+
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  protected Map<String, String> getenv() {
+    return System.getenv();
+  }
+
+  public boolean directoryExists(final String dirPath) throws Exception {
+    String output =
+        adbUtils.executeAdbShellCommand(
+            String.format("test -d %s && echo exists", dirPath),
+            androidDevice.getSerialNumber(),
+            true);
+    return output.contains("exists");
+  }
+
+  /**
+   * Execute adb shell command. Public wrapper around executeAdbShellCommand for use by report
+   * layers in other packages.
+   */
+  public String runShellCommand(String command) throws Exception {
+    return executeAdbShellCommand(command);
+  }
+
+  protected void transferFile(String operation, String source, String destination)
+      throws Exception {
+    adbUtils.executeAdbCommand(
+        operation + " " + source + " " + destination, androidDevice.getSerialNumber(), false);
+  }
+
+  private void pullFile(String remotePath, String localPath) throws Exception {
+    transferFile("pull", remotePath, localPath);
+  }
+
+  private void pushFile(String localPath, String remotePath) throws Exception {
+    transferFile("push", localPath, remotePath);
+  }
+
+  @FunctionalInterface
+  protected interface FilePusher {
+    void pushFile(String localPath, String remotePath) throws Exception;
+  }
+
+  /** Copy all local files to the remote device location */
+  protected void syncExopackageDir(Path localBase) throws Exception {
+    syncExopackageDir(localBase, this::pushFile);
+  }
+
+  /** Copy all local files to the remote device location (static version for testing) */
+  protected static void syncExopackageDir(Path localBase, FilePusher pusher) throws Exception {
+    String metadataContents = new String(Files.readAllBytes(localBase.resolve("metadata.txt")));
+    Path remoteBase = Paths.get(metadataContents.trim());
+    // TODO: speed this up by checking for already installed items
+    // TODO: speed this up by only installing ABI-compatible shared-objects
+    pushTree(localBase, remoteBase, pusher);
+  }
+
+  /** Pushes every file under {@code localBase} to {@code remoteBase}, preserving relative paths. */
+  protected static void pushTree(Path localBase, Path remoteBase, FilePusher pusher)
+      throws Exception {
+    try (Stream<Path> paths = Files.walk(localBase, FileVisitOption.FOLLOW_LINKS)) {
+      Iterable<Path> localFiles = () -> paths.filter(p -> !Files.isDirectory(p)).iterator();
+      for (Path p : localFiles) {
+        Path localSuffix = localBase.relativize(p);
+        Path fullRemotePath = remoteBase.resolve(localSuffix);
+        // Remote path is always a unix path
+        pusher.pushFile(p.toString(), fullRemotePath.toString().replace('\\', '/'));
+      }
+    }
+  }
+
+  /**
+   * Push exopackage secondary-dex artifacts to
+   * /data/local/tmp/exopackage/&lt;packageName&gt;/secondary-dex so the on-device
+   * ExopackageDexLoader installs them before the test runner's Application init. Unlike {@link
+   * #syncExopackageDir}, the remote base is derived from the package name, so the buck rule can
+   * pass the build's secondary-dex dir directly without a remote-base metadata file.
+   */
+  protected void pushExopackageSecondaryDex(Path localDir, String packageName) throws Exception {
+    Path remoteBase = Paths.get(EXOPACKAGE_INSTALL_ROOT + "/" + packageName + "/secondary-dex");
+    pushTree(localDir, remoteBase, this::pushFile);
+  }
+
+  private String getAppScopedStoragePath(
+      String packageName,
+      String targetPackageName,
+      boolean isSelfInstrumenting,
+      String folderName,
+      String fileName) {
+    String basePath =
+        getAppScopedStoragePath(packageName, targetPackageName, isSelfInstrumenting, folderName);
+    if (basePath == null) {
+      return null;
+    }
+    return Paths.get(basePath, fileName).toString();
+  }
+
+  private String getAppScopedStoragePath(
+      String packageName,
+      String targetPackageName,
+      boolean isSelfInstrumenting,
+      String folderName) {
+    int sdkVersion = getSdkVersion();
+    // App Scoped Storage was introduced in Android 11
+    if (sdkVersion == -1 || sdkVersion < 30) {
+      return null;
+    }
+
+    String artifactsDirTemplate =
+        INSTRUMENTATION_TEST_APP_SCOPED_API_30_PLUS_ARTIFACTS_DIR_TEMPLATE;
+    if (sdkVersion >= 33) {
+      artifactsDirTemplate = INSTRUMENTATION_TEST_APP_SCOPED_API_34_PLUS_ARTIFACTS_DIR_TEMPLATE;
+    }
+
+    String devicePathPackage = packageName;
+    if (!isSelfInstrumenting && targetPackageName != null) {
+      devicePathPackage = targetPackageName;
+    }
+
+    return String.format(artifactsDirTemplate, devicePathPackage, folderName);
+  }
+
+  private int getSdkVersion() {
+    try {
+      String sdk = androidDevice.getProperty("ro.build.version.sdk");
+      return Integer.parseInt(sdk);
+    } catch (NumberFormatException e) {
+      System.err.printf("Unable to determine SDK version for device: %s\n", e);
+    } catch (Exception e) {
+      System.err.printf("Unable to get SDK version property: %s\n", e);
+    }
+    return -1;
+  }
+
+  private AnimationScales getAnimationScales() throws Exception {
+    Function<String, Float> converter =
+        s -> {
+          if (s == null || "null".equals(s.trim())) {
+            return 0.0f;
+          }
+          return Float.parseFloat(s);
+        };
+    float windowAnimationScale =
+        converter.apply(executeAdbShellCommand("settings get global window_animation_scale"));
+    float transitionAnimationScale =
+        converter.apply(executeAdbShellCommand("settings get global transition_animation_scale"));
+    float animatorDurationScale =
+        converter.apply(executeAdbShellCommand("settings get global animator_duration_scale"));
+
+    return new AnimationScales(
+        windowAnimationScale, transitionAnimationScale, animatorDurationScale);
+  }
+
+  private void setAnimationScales(AnimationScales animationScales) throws Exception {
+    executeAdbShellCommand(
+        "settings put global window_animation_scale " + animationScales.windowAnimationScale);
+    executeAdbShellCommand(
+        "settings put global transition_animation_scale "
+            + animationScales.transitionAnimationScale);
+    executeAdbShellCommand(
+        "settings put global animator_duration_scale " + animationScales.animatorDurationScale);
+  }
+
+  // VisibleForTesting
+  static void setTrimLine(RemoteAndroidTestRunner runner, boolean value) {
+    try {
+      Field mParserField = RemoteAndroidTestRunner.class.getDeclaredField("mParser");
+      mParserField.setAccessible(true);
+      MultiLineReceiver multiLineReceiver = (MultiLineReceiver) mParserField.get(runner);
+      multiLineReceiver.setTrimLine(value);
+    } catch (NoSuchFieldException | IllegalAccessException e) {
+      throw new RuntimeException(e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTestRunnerForClout.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTestRunnerForClout.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTestRunnerForClout.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.testrunner.reportlayer.PerfettoReportLayer;
+import com.facebook.buck.testrunner.reportlayer.TombstonesReportLayer;
+import com.facebook.buck.testrunner.reportlayer.VideoRecordingReportLayer;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+public class InstrumentationTestRunnerForClout extends InstrumentationTestRunner {
+
+  private static final String ANDROID_HOME = "ANDROID_HOME";
+  private static final String CLOUT_ORIG_ADB_PATH = "/platform-tools/adb.orig";
+
+  public InstrumentationTestRunnerForClout(
+      DeviceArgs deviceArgs,
+      String packageName,
+      String targetPackageName,
+      String testRunner,
+      File outputDirectory,
+      String instrumentationApkPath,
+      String apkUnderTestPath,
+      String exopackageLocalPath,
+      String apkUnderTestExopackageLocalPath,
+      String exopackageSecondaryDexLocalPath,
+      boolean attemptUninstallApkUnderTest,
+      boolean attemptUninstallInstrumentationApk,
+      boolean debug,
+      boolean codeCoverage,
+      String codeCoverageOutputFile,
+      boolean isSelfInstrumenting,
+      Map<String, String> extraInstrumentationArguments,
+      String extraInstrumentationTestListener,
+      Map<String, String> extraFilesToPull,
+      Map<String, String> extraDirsToPull,
+      boolean clearPackageData,
+      boolean disableAnimations,
+      String preTestSetupScript,
+      List<String> extraApksToInstall,
+      @Nullable Integer userId) {
+    super(
+        deviceArgs,
+        packageName,
+        targetPackageName,
+        testRunner,
+        outputDirectory,
+        instrumentationApkPath,
+        apkUnderTestPath,
+        exopackageLocalPath,
+        apkUnderTestExopackageLocalPath,
+        exopackageSecondaryDexLocalPath,
+        attemptUninstallApkUnderTest,
+        attemptUninstallInstrumentationApk,
+        debug,
+        codeCoverage,
+        codeCoverageOutputFile,
+        isSelfInstrumenting,
+        extraInstrumentationArguments,
+        extraInstrumentationTestListener,
+        extraFilesToPull,
+        extraDirsToPull,
+        clearPackageData,
+        disableAnimations,
+        preTestSetupScript,
+        extraApksToInstall,
+        userId);
+  }
+
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  public static InstrumentationTestRunnerForClout fromArgs(String... args) throws IOException {
+    ArgsParser argsParser = new ArgsParser();
+    argsParser.fromArgs(args);
+    DeviceArgs deviceArgs = getDeviceArgs(args);
+    InstrumentationTestRunnerForClout runner =
+        new InstrumentationTestRunnerForClout(
+            deviceArgs,
+            argsParser.packageName,
+            argsParser.targetPackageName,
+            argsParser.testRunner,
+            argsParser.outputDirectory,
+            argsParser.instrumentationApkPath,
+            argsParser.apkUnderTestPath,
+            argsParser.exopackageLocalPath,
+            argsParser.apkUnderTestExopackageLocalPath,
+            argsParser.exopackageSecondaryDexLocalPath,
+            argsParser.attemptUninstallApkUnderTest,
+            argsParser.attemptUninstallInstrumentationApk,
+            argsParser.debug,
+            argsParser.codeCoverage,
+            argsParser.codeCoverageOutputFile,
+            argsParser.isSelfInstrumenting,
+            argsParser.extraInstrumentationArguments,
+            argsParser.extraInstrumentationTestListener,
+            argsParser.extraFilesToPull,
+            argsParser.extraDirsToPull,
+            argsParser.clearPackageData,
+            argsParser.disableAnimations,
+            argsParser.preTestSetupScript,
+            argsParser.extraApksToInstall,
+            argsParser.userId);
+    if (argsParser.recordVideo) {
+      runner.addReportLayer(new VideoRecordingReportLayer(runner));
+    }
+    runner.addReportLayer(new TombstonesReportLayer(runner, argsParser.collectTombstones));
+    if (argsParser.collectPerfetto) {
+      runner.addReportLayer(new PerfettoReportLayer(runner));
+    }
+    return runner;
+  }
+
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  private String getAndroidHome() {
+    if (System.getenv().containsKey(ANDROID_HOME)) {
+      return System.getenv(ANDROID_HOME);
+    } else {
+      return null;
+    }
+  }
+
+  @Override
+  protected String getAdbPath() {
+    String androidHome = getAndroidHome();
+    if (androidHome != null) {
+      // clout overrwrote adb to some custom script, this script hangs test runner.
+      // we are reverting it therefore to the original adb binary for test runner.
+      return androidHome + CLOUT_ORIG_ADB_PATH;
+    } else {
+      throw new RuntimeException("Could not find ANDROID_HOME env variable");
+    }
+  }
+
+  @Override
+  protected void installPackage(String path, String packageName) throws Throwable {
+    RunShellCommand.run(getAdbPath(), "install " + path);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTimeoutEnforcingRunListener.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTimeoutEnforcingRunListener.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTimeoutEnforcingRunListener.kt
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner
+
+import com.android.ddmlib.testrunner.ITestRunListener
+import com.android.ddmlib.testrunner.TestIdentifier
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.Executors
+import java.util.concurrent.ScheduledFuture
+import java.util.concurrent.TimeUnit
+
+/**
+ * An ITestRunListener that enforces timeouts for instrumentation tests and reports failures to an
+ * XML listener.
+ *
+ * This listener monitors test execution and forcibly terminates tests that exceed the configured
+ * timeout period. When a test times out, it notifies the XML listener via testFailed/testEnded
+ * callbacks and then calls System.exit(1) to terminate the JVM.
+ *
+ * The timeout is configured via environment variables defined in [InstrumentationTestRunner].
+ */
+class InstrumentationTimeoutEnforcingRunListener(private val xmlListener: ITestRunListener) :
+    ITestRunListener {
+
+  companion object {
+    /** Default timeout in milliseconds (60 seconds). */
+    private const val DEFAULT_TIMEOUT_MS = 60 * 1000L
+  }
+
+  private val watchdogExecutor = Executors.newSingleThreadScheduledExecutor()
+  private val activeTimeouts: MutableMap<TestIdentifier, ScheduledFuture<*>> = ConcurrentHashMap()
+
+  override fun testStarted(test: TestIdentifier) {
+    val timeoutMs = getTimeout()
+
+    // Schedule timeout task
+    val timeoutTask =
+        watchdogExecutor.schedule(
+            { handleTimeout(test, timeoutMs) },
+            timeoutMs,
+            TimeUnit.MILLISECONDS,
+        )
+
+    activeTimeouts[test] = timeoutTask
+  }
+
+  override fun testEnded(test: TestIdentifier, testMetrics: MutableMap<String, String>) {
+    cancelExecution(test)
+  }
+
+  override fun testFailed(test: TestIdentifier, trace: String) {
+    cancelExecution(test)
+  }
+
+  override fun testAssumptionFailure(test: TestIdentifier, trace: String) {
+    cancelExecution(test)
+  }
+
+  override fun testIgnored(test: TestIdentifier) {
+    cancelExecution(test)
+  }
+
+  override fun testRunStarted(runName: String, testCount: Int) {}
+
+  override fun testRunFailed(errorMessage: String) {
+    shutdown()
+  }
+
+  override fun testRunEnded(elapsedTime: Long, runMetrics: MutableMap<String, String>) {
+    shutdown()
+  }
+
+  override fun testRunStopped(elapsedTime: Long) {
+    shutdown()
+  }
+
+  private fun cancelExecution(test: TestIdentifier) {
+    activeTimeouts.remove(test)?.cancel(false)
+  }
+
+  private fun getTimeout(): Long {
+    val buckMultiplierEnv = System.getenv("ANDROID_PER_TEST_TIMEOUT_MULTIPLIER")
+    val multiplier = buckMultiplierEnv?.toIntOrNull()?.coerceAtLeast(1) ?: 1
+
+    return DEFAULT_TIMEOUT_MS * multiplier
+  }
+
+  /** Handles a test timeout by notifying the XML listener and forcibly terminating the JVM. */
+  private fun handleTimeout(test: TestIdentifier, timeoutMs: Long) {
+    activeTimeouts.remove(test) ?: return
+
+    val message =
+        "Test timed out after ${timeoutMs}ms. " +
+            "If your test needs to run longer than ${timeoutMs / 1000} seconds, add the tpx long_running or glacial tag in the labels section of the BUCK target. " +
+            "See https://fb.workplace.com/groups/android.testing.fyi/permalink/2679204925789466/ for more details"
+    System.err.println(message)
+
+    // Notify the XML listener about the failure
+    try {
+      xmlListener.testFailed(test, message)
+      xmlListener.testEnded(test, mutableMapOf())
+      xmlListener.testRunEnded(0, mutableMapOf())
+    } catch (e: Exception) {
+      System.err.println("Failed to notify XML listener: ${e.message}")
+    }
+
+    printThreadDump()
+
+    // This is necessary because instrumentation tests may not respond to thread interruption
+    System.exit(1)
+  }
+
+  /** Prints a thread dump to help diagnose what the test was doing when it timed out. */
+  private fun printThreadDump() {
+    System.err.println("\n=== Thread Dump ===")
+    Thread.getAllStackTraces().forEach { (thread, stackTrace) ->
+      System.err.println("Thread: ${thread.name} (${thread.state})")
+      stackTrace.forEach { element -> System.err.println("  at $element") }
+      System.err.println()
+    }
+  }
+
+  /** Shuts down the watchdog executor when testing is complete. */
+  private fun shutdown() {
+    watchdogExecutor.shutdownNow()
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTpxStandardOutputTestListener.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTpxStandardOutputTestListener.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/InstrumentationTpxStandardOutputTestListener.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.android.ddmlib.testrunner.ITestRunListener;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.facebook.buck.android.exopackage.AdbUtils;
+import com.facebook.buck.android.exopackage.AndroidDevice;
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent.RunFailureStatus;
+import com.facebook.buck.testresultsoutput.TestResultsOutputSender;
+import java.util.Map;
+
+/**
+ * InstrumentationTpxStandardOutputTestListener is a test event listener for Android Instrumentation
+ * Test for the TPX Standard Output format.
+ *
+ * <p>It implements the ITestRunListener interface, which is best documented here:
+ * https://developer.android.com/reference/androidx/test/orchestrator/listeners/result/ITestRunListener
+ *
+ * <p>The sequence of calls copied from the above link, where [ ] indicates optional calls:
+ *
+ * <p>testRunStarted testStarted [testFailed] [testAssumptionFailure] [testIgnored] testEnded ....
+ * [testRunFailed] testRunEnded
+ */
+public class InstrumentationTpxStandardOutputTestListener implements ITestRunListener {
+  private final TpxStandardOutputTestListener listener;
+  private final TestResultsOutputSender sender;
+  private final AndroidDevice mAndroidDevice;
+  private final AdbUtils mAdbUtils;
+
+  public InstrumentationTpxStandardOutputTestListener(
+      TestResultsOutputSender sender, AndroidDevice androidDevice, AdbUtils adbUtils) {
+    this.sender = sender;
+    this.listener = new TpxStandardOutputTestListener(sender);
+    this.mAndroidDevice = androidDevice;
+    this.mAdbUtils = adbUtils;
+  }
+
+  /**
+   * Gets the full test name for a test identifier.
+   *
+   * @param test the test identifier to get the name for
+   * @return the full test name
+   */
+  private static String getFullTestName(TestIdentifier test) {
+    return String.format("%s (%s)", test.getTestName(), test.getClassName());
+  }
+
+  /**
+   * Reports the start of an individual test case.
+   *
+   * @param test identifies the test
+   */
+  @Override
+  public void testStarted(TestIdentifier test) {
+    listener.testStarted(getFullTestName(test));
+  }
+
+  /**
+   * Reports the failure of a individual test case.
+   *
+   * <p>Will be called between testStarted and testEnded.
+   *
+   * @param test identifies the test
+   * @param trace stack trace of failure
+   */
+  @Override
+  public void testFailed(TestIdentifier test, String trace) {
+    if (mAndroidDevice != null && mAdbUtils != null && CrashCapturer.deviceHasCrashLogs(trace)) {
+      trace = CrashCapturer.addDeviceLogcatTrace(mAndroidDevice, mAdbUtils, trace);
+    }
+
+    listener.testFailed(getFullTestName(test), trace);
+  }
+
+  /**
+   * Called when an atomic test flags that it assumes a condition that is false
+   *
+   * @param test identifies the test
+   * @param trace stack trace of failure
+   */
+  @Override
+  public void testAssumptionFailure(TestIdentifier test, String trace) {
+    listener.testAssumptionFailure(getFullTestName(test), trace);
+  }
+
+  /**
+   * Called when a test will not be run, generally because a test method is annotated with
+   * org.junit.Ignore.
+   *
+   * @param test identifies the test
+   */
+  @Override
+  public void testIgnored(TestIdentifier test) {
+    listener.testIgnored(getFullTestName(test));
+  }
+
+  /**
+   * Reports the execution end of an individual test case.
+   *
+   * <p>If {@link #testFailed} was not invoked, this test passed. Also returns any key/value metrics
+   * which may have been emitted during the test case's execution.
+   *
+   * @param test identifies the test
+   * @param testMetrics a {@link Map} of the metrics emitted
+   */
+  @Override
+  public void testEnded(TestIdentifier test, Map<String, String> testMetrics) {
+    listener.testFinished(getFullTestName(test));
+  }
+
+  /**
+   * Reports test run failed to complete due to a fatal error.
+   *
+   * @param errorMessage {@link String} describing reason for run failure.
+   */
+  @Override
+  public void testRunFailed(String errorMessage) {
+    // Enhance error message with device logs if available
+    String enhancedMessage = errorMessage;
+    if (mAndroidDevice != null
+        && mAdbUtils != null
+        && CrashCapturer.deviceHasCrashLogs(errorMessage)) {
+      enhancedMessage = CrashCapturer.addDeviceLogcatTrace(mAndroidDevice, mAdbUtils, errorMessage);
+    }
+
+    sender.sendRunFailure(
+        RunFailureStatus.FATAL,
+        System.currentTimeMillis(),
+        enhancedMessage,
+        null); // stacktrace is embedded in the message
+  }
+
+  /**
+   * Reports the start of a test run.
+   *
+   * @param runName the test run name
+   * @param testCount total number of tests in test run
+   */
+  @Override
+  public void testRunStarted(String runName, int testCount) {}
+
+  /**
+   * Reports end of test run.
+   *
+   * @param elapsedTime device reported elapsed time, in milliseconds
+   * @param runMetrics key-value pairs reported at the end of a test run
+   */
+  @Override
+  public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) {}
+
+  /**
+   * Reports test run stopped before completion due to a user request.
+   *
+   * <p>Deprecated and not currently used.
+   *
+   * @param elapsedTime device reported elapsed time, in milliseconds
+   */
+  @Override
+  public void testRunStopped(long elapsedTime) {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitMain.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import static com.facebook.buck.testrunner.CheckDependency.requiresClass;
+
+/**
+ * Launcher for JUnit.
+ *
+ * <p>Expected arguments are:
+ *
+ * <ul>
+ *   <li>(string) output directory
+ *   <li>(long) default timeout in milliseconds (0 for no timeout)
+ *   <li>(string) newline separated list of test selectors
+ *   <li>(string...) fully-qualified names of test classes
+ * </ul>
+ *
+ * <p>IMPORTANT! This class limits itself to types that are available in both the JDK and Android
+ * Java API. The objective is to limit the set of files added to the ClassLoader that runs the test,
+ * as not to interfere with the results of the test.
+ */
+public class JUnitMain {
+
+  private JUnitMain() {
+    // Launcher class.
+  }
+
+  public static void main(String[] args) {
+    // Ensure that both junit and hamcrest are on the classpath
+    requiresClass("junit", "org.junit.Test");
+    requiresClass("hamcrest", "org.hamcrest.Description");
+
+    JUnitRunner runner = new JUnitRunner();
+    runner.parseArgs(args);
+    runner.runAndExit();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitOptions.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitOptions.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitOptions.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.test.selectors.TestSelectorList;
+import java.util.Optional;
+import java.util.logging.Level;
+
+/**
+ * Model representing parsed execution arguments.
+ *
+ * <p>Parsed output level defined by the property {@code #STD_OUT_LOG_LEVEL_PROPERTY}.
+ *
+ * @see #STD_OUT_LOG_LEVEL_PROPERTY
+ * @see #STD_ERR_LOG_LEVEL_PROPERTY
+ * @see System#getProperty(String)
+ */
+public class JUnitOptions {
+
+  static final String STD_OUT_LOG_LEVEL_PROPERTY = "com.facebook.buck.stdOutLogLevel";
+  static final String STD_ERR_LOG_LEVEL_PROPERTY = "com.facebook.buck.stdErrLogLevel";
+
+  private boolean dryRun;
+  private boolean shouldExplainTestSelectors;
+  private long defaultTestTimeoutMillis;
+  private TestSelectorList testSelectorList;
+  private Optional<Level> stdOutLogLevel = Optional.empty();
+  private Optional<Level> stdErrLogLevel = Optional.empty();
+
+  private JUnitOptions() {}
+
+  private JUnitOptions(JUnitOptions options) {
+    this.dryRun = options.dryRun;
+    this.shouldExplainTestSelectors = options.shouldExplainTestSelectors;
+    this.defaultTestTimeoutMillis = options.defaultTestTimeoutMillis;
+    this.testSelectorList = options.testSelectorList;
+    this.stdOutLogLevel =
+        Optional.ofNullable(System.getProperty(STD_OUT_LOG_LEVEL_PROPERTY)).map(Level::parse);
+    this.stdErrLogLevel =
+        Optional.ofNullable(System.getProperty(STD_ERR_LOG_LEVEL_PROPERTY)).map(Level::parse);
+  }
+
+  public TestSelectorList getTestSelectorList() {
+    return testSelectorList;
+  }
+
+  public boolean isDryRun() {
+    return dryRun;
+  }
+
+  public boolean isShouldExplainTestSelectors() {
+    return shouldExplainTestSelectors;
+  }
+
+  public long getDefaultTestTimeoutMillis() {
+    return defaultTestTimeoutMillis;
+  }
+
+  public Optional<Level> getStdErrLogLevel() {
+    return stdErrLogLevel;
+  }
+
+  public Optional<Level> getStdOutLogLevel() {
+    return stdOutLogLevel;
+  }
+
+  /**
+   * @return New instance of a builder for {@link JUnitOptions}
+   */
+  public static Builder builder() {
+    return new Builder();
+  }
+
+  /** Builder class for {@link JUnitOptions} */
+  public static class Builder {
+
+    private JUnitOptions base = new JUnitOptions();
+
+    public Builder testSelectorList(TestSelectorList testSelectorList) {
+      base.testSelectorList = testSelectorList;
+      return this;
+    }
+
+    public Builder dryRun(boolean dryRun) {
+      base.dryRun = dryRun;
+      return this;
+    }
+
+    public Builder shouldExplainTestSelectors(boolean shouldExplainTestSelectors) {
+      base.shouldExplainTestSelectors = shouldExplainTestSelectors;
+      return this;
+    }
+
+    public Builder defaultTestTimeoutMillis(long defaultTestTimeoutMillis) {
+      base.defaultTestTimeoutMillis = defaultTestTimeoutMillis;
+      return this;
+    }
+
+    public JUnitOptions build() {
+      return new JUnitOptions(base);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitRunner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitRunner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitRunner.java
@@ -0,0 +1,704 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.test.result.type.ResultType;
+import com.facebook.buck.test.selectors.TestDescription;
+import com.facebook.buck.test.selectors.TestSelector;
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent;
+import com.facebook.buck.testresultsoutput.TestResultsOutputSender;
+import com.facebook.buck.testrunner.JavaUtilLoggingHelper.LogHandlers;
+import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.logging.Level;
+import javax.annotation.Nullable;
+import junit.framework.TestCase;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.experimental.runners.Enclosed;
+import org.junit.internal.builders.AllDefaultPossibilitiesBuilder;
+import org.junit.internal.builders.JUnit4Builder;
+import org.junit.runner.Computer;
+import org.junit.runner.Description;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Request;
+import org.junit.runner.Result;
+import org.junit.runner.RunWith;
+import org.junit.runner.Runner;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunListener;
+import org.junit.runners.ParentRunner;
+import org.junit.runners.model.RunnerBuilder;
+
+/**
+ * Class that runs a set of JUnit tests and writes the results to a directory.
+ *
+ * <p>IMPORTANT! This class limits itself to types that are available in both the JDK and Android
+ * Java API. The objective is to limit the set of files added to the ClassLoader that runs the test,
+ * as not to interfere with the results of the test.
+ */
+public final class JUnitRunner extends BaseRunner {
+
+  static final String JUL_DEBUG_LOGS_HEADER = "====DEBUG LOGS====\n\n";
+  static final String JUL_ERROR_LOGS_HEADER = "====ERROR LOGS====\n\n";
+
+  static final String SETUP_CRASH_MESSAGE_PREFIX =
+      "The test suite crashed during setup before any test could run, so no per-case results were"
+          + " produced. Reported as a fatal run failure (not skipped). Check the suite for an"
+          + " exception in class initialization, a @BeforeClass method, or (for Robolectric) the"
+          + " sandbox/SDK configuration (e.g. target_sdk_levels). The originating failure"
+          + " follows:\n\n";
+
+  private static final String STD_OUT_LOG_LEVEL_PROPERTY = "com.facebook.buck.stdOutLogLevel";
+  private static final String STD_ERR_LOG_LEVEL_PROPERTY = "com.facebook.buck.stdErrLogLevel";
+
+  private static final boolean JUNIT_RUN_TESTS_IN_NESTED_CLASSES_ENABLED;
+
+  static {
+    String prop = System.getProperty("junit.run_tests_in_nested_classes");
+    JUNIT_RUN_TESTS_IN_NESTED_CLASSES_ENABLED = "enabled".equals(prop);
+  }
+
+  public JUnitRunner() {}
+
+  @Override
+  public void run() throws Throwable {
+    setupLogging();
+    Level stdOutLogLevel = Level.INFO;
+    Level stdErrLogLevel = Level.WARNING;
+
+    String unparsedStdOutLogLevel = System.getProperty(STD_OUT_LOG_LEVEL_PROPERTY);
+    String unparsedStdErrLogLevel = System.getProperty(STD_ERR_LOG_LEVEL_PROPERTY);
+
+    if (unparsedStdOutLogLevel != null) {
+      stdOutLogLevel = Level.parse(unparsedStdOutLogLevel);
+    }
+
+    if (unparsedStdErrLogLevel != null) {
+      stdErrLogLevel = Level.parse(unparsedStdErrLogLevel);
+    }
+
+    // TPX sets the env var that enables the Standard Output format
+    Optional<TestResultsOutputSender> testResultsOutputSender =
+        TestResultsOutputSender.fromDefaultEnvName();
+
+    // Per-test coverage: collect per-test-method JaCoCo coverage if enabled
+    PerTestJUnitCoverageRunListener perTestCoverageListener = null;
+    String perTestCoverageDir = System.getenv("PER_TEST_COVERAGE_DIR");
+    if (perTestCoverageDir != null) {
+      try {
+        perTestCoverageListener = new PerTestJUnitCoverageRunListener(new File(perTestCoverageDir));
+      } catch (Exception e) {
+        // JaCoCo agent not available — report as infra failure via TPX
+        reportRunFailure(
+            testResultsOutputSender,
+            TestResultsOutputEvent.RunFailureStatus.INFRA_FAILURE,
+            "Per-test coverage requested but JaCoCo agent is not available: " + e.getMessage(),
+            null);
+      }
+    }
+
+    // Shared watchdog executor for timeout enforcement (per-test and target-level)
+    ScheduledExecutorService watchdogExecutor = Executors.newScheduledThreadPool(1);
+
+    // Proactive timeout: capture thread dump before RE's SIGKILL
+    TpxTimeoutBufferManager tpxTimeoutBufferManager = null;
+    if (testResultsOutputSender.isPresent()
+        && "true".equals(System.getProperty("android.proactive.timeout.enabled"))) {
+      tpxTimeoutBufferManager =
+          TpxTimeoutBufferManager.create(testResultsOutputSender.get(), watchdogExecutor);
+    }
+
+    for (String className : testClassNames) {
+      Class<?> testClass = Class.forName(className);
+      Class<?>[] testClasses;
+      if (JUNIT_RUN_TESTS_IN_NESTED_CLASSES_ENABLED) {
+        testClasses = collectTestClasses(testClass);
+      } else {
+        testClasses = new Class<?>[] {testClass};
+      }
+
+      List<TestResult> results = new ArrayList<>();
+      RecordingFilter filter = new RecordingFilter();
+      if (mightBeATestClass(testClass)) {
+        JUnitCore jUnitCore = new JUnitCore();
+        Runner suite = new Computer().getSuite(createRunnerBuilder(), testClasses);
+        Request request = Request.runner(suite);
+        request = request.filterWith(filter);
+
+        JUnitTpxStandardOutputListener tpxListener = null;
+        if (testResultsOutputSender.isPresent()) {
+          tpxListener = new JUnitTpxStandardOutputListener(testResultsOutputSender.get());
+          jUnitCore.addListener(tpxListener);
+
+          if (isRobolectricTest(suite)
+              && "true".equals(System.getProperty("android.per.test.timeout.enabled"))) {
+            RobolectricTimeoutEnforcingRunListener timeoutListener =
+                new RobolectricTimeoutEnforcingRunListener(
+                    testResultsOutputSender.get(), watchdogExecutor);
+            jUnitCore.addListener(timeoutListener);
+          }
+        } else {
+          jUnitCore.addListener(new TestListener(results, stdOutLogLevel, stdErrLogLevel));
+        }
+
+        if (perTestCoverageListener != null) {
+          jUnitCore.addListener(perTestCoverageListener);
+        }
+
+        jUnitCore.run(request);
+
+        // Report filtered-out tests (e.g., @Ignore) to TPX output so they're not retried
+        if (tpxListener != null) {
+          for (TestResult filteredTest : filter.filteredOut) {
+            if (filteredTest.type == ResultType.DISABLED) {
+              String testName =
+                  JUnitTpxStandardOutputListener.getFullTestName(
+                      filteredTest.testMethodName, filteredTest.testClassName);
+              tpxListener.reportOmittedTest(testName, "Test disabled (@Ignore annotation)");
+            }
+          }
+        }
+
+        // On a setup crash the selected cases produce no result and TPX records them as SKIPPED,
+        // outside autopilot's FAILED+FATAL filter. Report the run as FATAL rather than synthesizing
+        // per-case results for cases that never ran (which would break the TPX/runner contract).
+        if (tpxListener != null && !isDryRun) {
+          List<String> setupFailureTraces = tpxListener.getUnpairedFailureTraces();
+          if (!setupFailureTraces.isEmpty()) {
+            String trace = String.join("\n\n", setupFailureTraces);
+            reportRunFailure(
+                testResultsOutputSender,
+                TestResultsOutputEvent.RunFailureStatus.FATAL,
+                SETUP_CRASH_MESSAGE_PREFIX + trace,
+                trace);
+          }
+        }
+      }
+      // Combine the results with the tests we filtered out
+      List<TestResult> actualResults = combineResults(results, filter.filteredOut);
+      writeResult(className, actualResults);
+
+      // if there is a failure in the list, we should fail entirely.
+      results.stream()
+          .filter(r -> r.type == ResultType.DRY_RUN && r.failure != null)
+          .findFirst()
+          .ifPresent(
+              result -> {
+                System.err.printf(
+                    "Failed to list tests for class %s.%n%s",
+                    className, stackTraceToString(result.failure));
+                System.exit(1);
+              });
+    }
+
+    if (perTestCoverageListener != null) {
+      perTestCoverageListener.close();
+      if (perTestCoverageListener.getCoverageError() != null) {
+        reportRunFailure(
+            testResultsOutputSender,
+            TestResultsOutputEvent.RunFailureStatus.INFRA_FAILURE,
+            "Per-test coverage collection failed: "
+                + perTestCoverageListener.getCoverageError().getMessage(),
+            null);
+      }
+    }
+
+    // All test classes completed normally — mark as completed so shutdown hook is a no-op
+    if (tpxTimeoutBufferManager != null) {
+      tpxTimeoutBufferManager.markCompleted();
+    }
+  }
+
+  private static void reportRunFailure(
+      Optional<TestResultsOutputSender> sender,
+      TestResultsOutputEvent.RunFailureStatus status,
+      String message,
+      String stacktrace) {
+    if (sender.isPresent()) {
+      sender.get().sendRunFailure(status, System.currentTimeMillis(), message, stacktrace);
+    }
+  }
+
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  private void setupLogging() {
+    // Check if we have robolectric logging to setup
+    // get it as a resource to avoid loading the class
+    // and risking any errors in static initialization
+    boolean hasRobolectricInClassPath =
+        getClass().getClassLoader().getResource("org/robolectric/shadows/ShadowLog.class") != null;
+
+    if (hasRobolectricInClassPath && System.getProperty("robolectric.logging") == null) {
+      String configuredTestArtifacts = System.getenv("TEST_RESULT_ARTIFACTS_DIR");
+      if (configuredTestArtifacts != null) {
+        File testArtifactsDir = new File(configuredTestArtifacts);
+        if (!testArtifactsDir.mkdirs() && !testArtifactsDir.exists()) {
+          System.err.println(
+              "Failed to create test artifacts directory: " + testArtifactsDir.getAbsolutePath());
+        }
+
+        String robolectricLogLocation =
+            new File(testArtifactsDir, "robolectric-logs.txt").getAbsolutePath();
+        System.setProperty("robolectric.logging", robolectricLogLocation);
+      }
+      String configuredTestAnnotations = System.getenv("TEST_RESULT_ARTIFACT_ANNOTATIONS_DIR");
+      if (configuredTestAnnotations != null) {
+        File artifactAnnotationsDir = new File(configuredTestAnnotations);
+        if (!artifactAnnotationsDir.mkdirs() && !artifactAnnotationsDir.exists()) {
+          System.err.println(
+              "Failed to create artifact annotations directory: "
+                  + artifactAnnotationsDir.getAbsolutePath());
+        }
+
+        try (BufferedWriter writer =
+            new BufferedWriter(
+                new FileWriter(
+                    new File(artifactAnnotationsDir, "robolectric-logs.txt.annotation")))) {
+
+          writer.write("{\"type\": {\"generic_text_log\": {}}}");
+        } catch (IOException unused) {
+          // do nothing
+        }
+      }
+    }
+  }
+
+  private static Class<?>[] collectTestClasses(Class<?> testClass) {
+    ArrayList<Class<?>> classes = new ArrayList<>();
+    for (Class<?> cls : testClass.getDeclaredClasses()) {
+      int modifiers = cls.getModifiers();
+      if (!Modifier.isStatic(modifiers)) {
+        continue;
+      }
+      if (!Modifier.isPublic(modifiers)) {
+        continue;
+      }
+      if (cls.isAnnotationPresent(RunWith.class)
+          && cls.getAnnotation(RunWith.class).value() != Enclosed.class) {
+        continue;
+      }
+      if (mightBeATestClass(cls)) {
+        classes.add(cls);
+      }
+    }
+    classes.add(testClass);
+    return classes.toArray(new Class<?>[0]);
+  }
+
+  /** Guessing whether or not a class is a test class is an imperfect art form. */
+  private static boolean mightBeATestClass(Class<?> klass) {
+    if (klass.getAnnotation(RunWith.class) != null) {
+      return true; // If the class is explicitly marked with @RunWith, it's a test class.
+    }
+    // Since no RunWith annotation, using standard runner, which requires
+    // test classes to be non-abstract/non-interface
+    int klassModifiers = klass.getModifiers();
+    if (Modifier.isInterface(klassModifiers) || Modifier.isAbstract(klassModifiers)) {
+      return false;
+    }
+
+    // Classes that extend junit.framework.TestCase are JUnit3-style test classes.
+    if (TestCase.class.isAssignableFrom(klass)) {
+      return true;
+    }
+
+    // Since no RunWith annotation, using standard runner, which requires
+    // test classes to have exactly one public constructor (that has no args).
+    // Classes may have (non-public) constructors (with or without args).
+    boolean foundPublicNoArgConstructor = false;
+    for (Constructor<?> c : klass.getConstructors()) {
+      if (Modifier.isPublic(c.getModifiers())) {
+        if (c.getParameterCount() != 0) {
+          return false;
+        }
+        foundPublicNoArgConstructor = true;
+      }
+    }
+    if (!foundPublicNoArgConstructor) {
+      return false;
+    }
+    // If the class has a JUnit4 @Test-annotated method, it's a test class.
+    boolean hasAtLeastOneTest = false;
+    for (Method m : klass.getMethods()) {
+      if (Modifier.isPublic(m.getModifiers())
+          && m.getParameters().length == 0
+          && m.getAnnotation(Test.class) != null) {
+        hasAtLeastOneTest = true;
+        break;
+      }
+    }
+    return hasAtLeastOneTest;
+  }
+
+  /**
+   * This method filters a list of test results prior to writing results to a file. null is returned
+   * to indicate "don't write anything", which is different to writing a file containing 0 results.
+   *
+   * <p>JUnit handles classes-without-tests in different ways. If you are not using the
+   * org.junit.runner.Request.filterWith facility then JUnit ignores classes-without-tests. However,
+   * if you are using a filter then a class-without-tests will cause a NoTestsRemainException to be
+   * thrown, which is propagated back as an error.
+   */
+  static List<TestResult> combineResults(
+      List<TestResult> results, List<TestResult> filteredResults) {
+    List<TestResult> combined = new ArrayList<>(filteredResults);
+    if (!isSingleResultCausedByNoTestsRemainException(results)) {
+      combined.addAll(results);
+    }
+    return combined;
+  }
+
+  /**
+   * JUnit doesn't normally consider encountering a testless class an error. However, when using
+   * org.junit.runner.manipulation.Filter, testless classes *are* considered an error, throwing
+   * org.junit.runner.manipulation.NoTestsRemainException.
+   *
+   * <p>If we are using test-selectors then it's possible we will run a test class but never run any
+   * of its test methods, because they'd all get filtered out. When this happens, the results will
+   * contain a single failure containing the error from the NoTestsRemainException.
+   *
+   * <p>However, there is another reason why the test class may have a single failure -- if the
+   * class fails to instantiate, then it doesn't get far enough to detect whether or not there were
+   * any tests. In that case, JUnit4 returns a single failure result with the testMethodName set to
+   * "initializationError".
+   *
+   * <p>(NB: we can't decide at the class level whether we need to run a test class or not; we can
+   * only run the test class and all its test methods and handle the erroneous exception JUnit
+   * throws if no test-methods were actually run.)
+   */
+  private static boolean isSingleResultCausedByNoTestsRemainException(List<TestResult> results) {
+    if (results.size() != 1) {
+      return false;
+    }
+    TestResult singleResult = results.get(0);
+    return !singleResult.isSuccess()
+        && "initializationError".equals(singleResult.testMethodName)
+        && "org.junit.runner.manipulation.Filter".equals(singleResult.testClassName);
+  }
+
+  /**
+   * Creates an {@link AllDefaultPossibilitiesBuilder} that returns our custom {@link
+   * BuckBlockJUnit4ClassRunner} when a {@link JUnit4Builder} is requested. This ensures that JUnit
+   * 4 tests are executed using our runner whereas other types of tests are run with whatever JUnit
+   * thinks is best.
+   */
+  private RunnerBuilder createRunnerBuilder() {
+    JUnit4Builder jUnit4RunnerBuilder =
+        new JUnit4Builder() {
+          @Override
+          public Runner runnerForClass(Class<?> testClass) throws Throwable {
+            return new BuckBlockJUnit4ClassRunner(testClass, defaultTestTimeoutMillis);
+          }
+        };
+
+    return new AllDefaultPossibilitiesBuilder() {
+      @Override
+      protected JUnit4Builder junit4Builder() {
+        return jUnit4RunnerBuilder;
+      }
+    };
+  }
+
+  /** Checks if a test class is a Robolectric test by examining its runner tree. */
+  private boolean isRobolectricTest(Runner runner) {
+    try {
+      Class<?> robolectricTestRunner = Class.forName("org.robolectric.RobolectricTestRunner");
+      Class<?> suiteRunner = Class.forName("org.junit.runners.Suite");
+      return isRunnerOfTypeOrSuiteOfType(runner, robolectricTestRunner, suiteRunner);
+    } catch (ClassNotFoundException e) {
+      return false;
+    }
+  }
+
+  static boolean isRunnerOfTypeOrSuiteOfType(
+      Runner runner, Class<?> runnerType, Class<?> suiteType) {
+    if (runnerType.isAssignableFrom(runner.getClass())) {
+      return true;
+    }
+
+    if (!suiteType.isAssignableFrom(runner.getClass())) {
+      return false;
+    }
+
+    try {
+      Method getChildrenMethod = ParentRunner.class.getDeclaredMethod("getChildren");
+      getChildrenMethod.setAccessible(true);
+      List<?> children = (List<?>) getChildrenMethod.invoke(runner);
+
+      if (children.isEmpty()) {
+        return false;
+      }
+
+      for (Object child : children) {
+        if (!(child instanceof Runner)
+            || !isRunnerOfTypeOrSuiteOfType((Runner) child, runnerType, suiteType)) {
+          return false;
+        }
+      }
+      return true;
+    } catch (ReflectiveOperationException e) {
+      return false;
+    }
+  }
+
+  /**
+   * Creates RunListener that will prepare individual result for each test and store it to results
+   * list afterwards.
+   */
+  private class TestListener extends RunListener {
+    private final List<TestResult> results;
+    private final Level stdErrLogLevel;
+    private final Level stdOutLogLevel;
+    @Nullable private PrintStream originalOut, originalErr, stdOutStream, stdErrStream;
+    @Nullable private ByteArrayOutputStream rawStdOutBytes, rawStdErrBytes;
+    @Nullable private ByteArrayOutputStream julLogBytes, julErrLogBytes;
+    @Nullable private LogHandlers logHandlers;
+    @Nullable private Result result;
+    @Nullable private RunListener resultListener;
+    @Nullable private Failure assumptionFailure;
+
+    // To help give a reasonable (though imprecise) guess at the runtime for unpaired failures
+    private final long startTime = System.currentTimeMillis();
+
+    TestListener(List<TestResult> results, Level stdOutLogLevel, Level stdErrLogLevel) {
+      this.results = results;
+      this.stdOutLogLevel = stdOutLogLevel;
+      this.stdErrLogLevel = stdErrLogLevel;
+    }
+
+    @Override
+    public void testStarted(Description description) throws Exception {
+      // Create an intermediate stdout/stderr to capture any debugging statements (usually in the
+      // form of System.out.println) the developer is using to debug the test.
+      originalOut = System.out;
+      originalErr = System.err;
+      rawStdOutBytes = new ByteArrayOutputStream();
+      rawStdErrBytes = new ByteArrayOutputStream();
+      julLogBytes = new ByteArrayOutputStream();
+      julErrLogBytes = new ByteArrayOutputStream();
+      stdOutStream = new PrintStream(rawStdOutBytes, true /* autoFlush */, ENCODING);
+      stdErrStream = new PrintStream(rawStdErrBytes, true /* autoFlush */, ENCODING);
+      System.setOut(stdOutStream);
+      System.setErr(stdErrStream);
+
+      // Set up logging handlers
+      logHandlers =
+          JavaUtilLoggingHelper.setupLogging(
+              julLogBytes, julErrLogBytes, stdOutLogLevel, stdErrLogLevel);
+
+      // Prepare single-test result.
+      result = new Result();
+      resultListener = result.createListener();
+      resultListener.testRunStarted(description);
+      resultListener.testStarted(description);
+    }
+
+    @Override
+    public void testFinished(Description description) throws Exception {
+      // Shutdown single-test result.
+      resultListener.testFinished(description);
+      resultListener.testRunFinished(result);
+      resultListener = null;
+
+      // Restore the original stdout/stderr.
+      System.setOut(originalOut);
+      System.setErr(originalErr);
+
+      // Clean up logging handlers
+      JavaUtilLoggingHelper.cleanupLogging(logHandlers);
+      logHandlers = null;
+
+      // Get the stdout/stderr written during the test as strings.
+      stdOutStream.flush();
+      stdErrStream.flush();
+
+      int numFailures = result.getFailureCount();
+      String className = description.getClassName();
+      String methodName = description.getMethodName();
+
+      Failure failure;
+      ResultType type;
+      if (assumptionFailure != null) {
+        failure = assumptionFailure;
+        type = ResultType.ASSUMPTION_VIOLATION;
+        // Clear the assumption-failure field before the next test result appears.
+        assumptionFailure = null;
+      } else if (isDryRun) {
+        if ("org.junit.runner.manipulation.Filter".equals(className)
+            && "initializationError".equals(methodName)) {
+          return; // don't record errors from failed class initialization during dry run
+        }
+        failure = numFailures == 0 ? null : result.getFailures().get(0);
+        if (failure != null
+            && stackTraceToString(failure.getException()).contains("No runnable methods")
+            && "initializationError".equals(methodName)) {
+          return; // don't record errors if there is no runnable
+        }
+        type = ResultType.DRY_RUN;
+      } else if (numFailures == 0) {
+        failure = null;
+        type = ResultType.SUCCESS;
+      } else {
+        failure = result.getFailures().get(0);
+        type = ResultType.FAILURE;
+      }
+
+      StringBuilder stdOut = new StringBuilder();
+      stdOut.append(rawStdOutBytes.toString(ENCODING));
+      if (type == ResultType.FAILURE && julLogBytes.size() > 0) {
+        stdOut.append('\n');
+        stdOut.append(JUL_DEBUG_LOGS_HEADER);
+        stdOut.append(julLogBytes.toString(ENCODING));
+      }
+      StringBuilder stdErr = new StringBuilder();
+      stdErr.append(rawStdErrBytes.toString(ENCODING));
+      if (type == ResultType.FAILURE && julErrLogBytes.size() > 0) {
+        stdErr.append('\n');
+        stdErr.append(JUL_ERROR_LOGS_HEADER);
+        stdErr.append(julErrLogBytes.toString(ENCODING));
+      }
+
+      results.add(
+          new TestResult(
+              className,
+              methodName,
+              result.getRunTime(),
+              type,
+              failure == null ? null : failure.getException(),
+              stdOut.length() == 0 ? null : stdOut.toString(),
+              stdErr.length() == 0 ? null : stdErr.toString()));
+    }
+
+    @Override
+    public void testRunFinished(Result runResult) {
+      if (resultListener != null) {
+        // testStarted was called for latest test, but not the testFinished
+        // report all failures as unbounded
+        for (Failure failure : result.getFailures()) {
+          recordUnpairedResult(failure, ResultType.FAILURE);
+        }
+      }
+    }
+
+    /**
+     * The regular listener we created from the singular result, in this class, will not by default
+     * treat assumption failures as regular failures, and will not store them. As a consequence, we
+     * store them ourselves!
+     *
+     * <p>We store the assumption-failure in a temporary field, which we'll make sure we clear each
+     * time we write results.
+     */
+    @Override
+    public void testAssumptionFailure(Failure failure) {
+      assumptionFailure = failure;
+      if (resultListener == null) {
+        recordUnpairedResult(failure, ResultType.ASSUMPTION_VIOLATION);
+      } else {
+        // Left in only to help catch future bugs -- right now this does nothing.
+        resultListener.testAssumptionFailure(failure);
+      }
+    }
+
+    @Override
+    public void testFailure(Failure failure) throws Exception {
+      if (resultListener == null) {
+        recordUnpairedResult(failure, ResultType.FAILURE);
+      } else {
+        resultListener.testFailure(failure);
+      }
+    }
+
+    @Override
+    public void testIgnored(Description description) throws Exception {
+      if (resultListener != null) {
+        resultListener.testIgnored(description);
+      }
+    }
+
+    /**
+     * It's possible to encounter a Failure/Skip before we've started any tests (and therefore
+     * before testStarted() has been called). The known example is a @BeforeClass that throws an
+     * exception, but there may be others.
+     *
+     * <p>Recording these unexpected failures helps us propagate failures back up to the "buck test"
+     * process.
+     */
+    private void recordUnpairedResult(Failure failure, ResultType resultType) {
+      long runtime = System.currentTimeMillis() - startTime;
+      Description description = failure.getDescription();
+      results.add(
+          new TestResult(
+              description.getClassName(),
+              description.getMethodName(),
+              runtime,
+              resultType,
+              failure.getException(),
+              null,
+              null));
+    }
+  }
+
+  /** A JUnit Filter that records the tests it filters out. */
+  private class RecordingFilter extends Filter {
+    static final String FILTER_DESCRIPTION = "TestSelectorList-filter";
+
+    List<TestResult> filteredOut = new ArrayList<>();
+
+    @Override
+    public boolean shouldRun(Description description) {
+      String methodName = description.getMethodName();
+      if (methodName == null) {
+        // JUnit will give us an org.junit.runner.Description like this for the
+        // test class
+        // itself.  It's easier for our filtering to make decisions just at the method level,
+        // however, so just always return true here.
+        return true;
+      }
+      String className = description.getClassName();
+      TestDescription testDescription = new TestDescription(className, methodName);
+      TestSelector matchingSelector = testSelectorList.findSelector(testDescription);
+      if (!matchingSelector.isInclusive()) {
+        if (shouldExplainTestSelectors) {
+          String reason = "Excluded by filter: " + matchingSelector.getExplanation();
+          filteredOut.add(TestResult.forExcluded(className, methodName, reason));
+        }
+        return false;
+      }
+      if (description.getAnnotation(Ignore.class) != null) {
+        filteredOut.add(TestResult.forDisabled(className, methodName));
+        return false;
+      }
+      if (isDryRun) {
+        filteredOut.add(TestResult.forDryRun(className, methodName));
+        return false;
+      }
+      return true;
+    }
+
+    @Override
+    public String describe() {
+      return FILTER_DESCRIPTION;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitSupport.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitSupport.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitSupport.java
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import static com.facebook.buck.testrunner.CheckDependency.optionalAnnotation;
+import static com.facebook.buck.testrunner.CheckDependency.optionalClass;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.List;
+import java.util.Optional;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.junit.platform.commons.util.ReflectionUtils;
+
+/** Validate the presence of JUnit APIs. */
+class JUnitSupport {
+
+  private static final JUnit4ApiSupport JUNIT4_API = new JUnit4ApiSupport();
+  private static final JupiterApiSupport JUPITER_API = new JupiterApiSupport();
+
+  static JUnit4ApiSupport junit4Api() {
+    return JUNIT4_API;
+  }
+
+  static JupiterApiSupport jupiterApi() {
+    return JUPITER_API;
+  }
+
+  /** Validates if a JUnit Engine is present and if a given class it's compatible. */
+  interface ApiSupport extends Predicate<Class<?>> {
+
+    /**
+     * @return true if the API is present into the classpath, false otherwise.
+     */
+    boolean enabled();
+
+    /**
+     * @return true if the element is disabled.
+     */
+    boolean disabled(AnnotatedElement element);
+
+    /**
+     * @param clazz Class or Method to be verified.
+     * @return true if it's a valid class or method that represents a unit test.
+     */
+    @Override
+    default boolean test(Class<?> clazz) {
+      return enabled() && isTestClass(clazz);
+    }
+
+    /**
+     * @param clazz Class or Method to be verified.
+     * @return true if it's a valid class or method that represents a unit test.
+     */
+    boolean isTestClass(Class<?> clazz);
+
+    /**
+     * @param throwable to be checked
+     * @return true if the error has internal Assumption as its super class.
+     */
+    boolean isAssumption(Throwable throwable);
+  }
+
+  /**
+   * Validate if Jupiter API is present and if a class is a valid candidate to be a test class.
+   *
+   * <p>It checks for Optional annotations such as ParameterizedTest, without failing. The
+   * implementation use Optional classes and annotations to prevent {@link ClassNotFoundException}
+   * in case the API is not available.
+   */
+  static class JupiterApiSupport implements ApiSupport {
+
+    static final Optional<Class<? extends Annotation>> NESTED_ANN =
+        optionalAnnotation("org.junit.jupiter.api.Nested");
+    static final Optional<Class<? extends Annotation>> DISABLED_ANN =
+        optionalAnnotation("org.junit.jupiter.api.Disabled");
+    static final Optional<Class<?>> ASSUMPTION_EXCEPTION_CLASS =
+        optionalClass("org.opentest4j.TestAbortedException");
+
+    static final List<Class<? extends Annotation>> METHOD_ANNOTATIONS;
+
+    static {
+      METHOD_ANNOTATIONS =
+          Stream.of(
+                  optionalAnnotation("org.junit.jupiter.api.Test"),
+                  optionalAnnotation("org.junit.jupiter.api.TestFactory"),
+                  optionalAnnotation("org.junit.jupiter.api.RepeatedTest"),
+                  optionalAnnotation("org.junit.jupiter.params.ParameterizedTest"))
+              .filter(Optional::isPresent)
+              .map(Optional::get)
+              .collect(Collectors.toList());
+    }
+
+    @Override
+    public boolean enabled() {
+      return NESTED_ANN.isPresent();
+    }
+
+    @Override
+    public boolean disabled(AnnotatedElement element) {
+      return DISABLED_ANN.filter(element::isAnnotationPresent).isPresent();
+    }
+
+    @Override
+    public boolean isTestClass(Class<?> clazz) {
+      List<Method> testMethods = ReflectionUtils.findMethods(clazz, this::isTestMethod);
+      if (!testMethods.isEmpty()) {
+        return true;
+      }
+      for (Class<?> nestedClass : clazz.getDeclaredClasses()) {
+        if (NESTED_ANN.filter(nestedClass::isAnnotationPresent).isPresent() && test(nestedClass)) {
+          return true;
+        }
+      }
+      return false;
+    }
+
+    @Override
+    public boolean isAssumption(Throwable throwable) {
+      return throwable != null
+          && ASSUMPTION_EXCEPTION_CLASS
+              .filter(testCase -> testCase.isAssignableFrom(throwable.getClass()))
+              .isPresent();
+    }
+
+    private boolean isTestMethod(Method m) {
+      return ReflectionUtils.isNotPrivate(m)
+          && METHOD_ANNOTATIONS.stream().anyMatch(m::isAnnotationPresent);
+    }
+  }
+
+  /**
+   * Backward compatibility with JUnitRunner.mightBeATestClass
+   *
+   * <p>Validate if JUnit4 API is present and if a class is a valid candidate to be a test class.
+   * The implementation use Optional classes and annotations to prevent {@link
+   * ClassNotFoundException} in case the API is not available.
+   */
+  static class JUnit4ApiSupport implements ApiSupport {
+
+    static final Optional<Class<? extends Annotation>> IGNORE_ANN =
+        optionalAnnotation("org.junit.Ignore");
+    static final Optional<Class<? extends Annotation>> TEST_ANN =
+        optionalAnnotation("org.junit.Test");
+    static final Optional<Class<? extends Annotation>> RUN_WITH_ANN =
+        optionalAnnotation("org.junit.runner.RunWith");
+    static final Optional<Class<?>> TEST_CASE_CLASS = optionalClass("junit.framework.TestCase");
+    static final Optional<Class<?>> ASSUMPTION_EXCEPTION_CLASS =
+        optionalClass("org.junit.internal.AssumptionViolatedException");
+
+    @Override
+    public boolean enabled() {
+      return TEST_ANN.isPresent();
+    }
+
+    @Override
+    public boolean disabled(AnnotatedElement element) {
+      return IGNORE_ANN.filter(element::isAnnotationPresent).isPresent();
+    }
+
+    @Override
+    public boolean isTestClass(Class<?> clazz) {
+      if (RUN_WITH_ANN.filter(clazz::isAnnotationPresent).isPresent()) {
+        return true;
+      }
+      // Since no RunWith annotation, using standard runner, which requires
+      // test classes to be non-abstract/non-interface
+      int klassModifiers = clazz.getModifiers();
+      if (Modifier.isInterface(klassModifiers) || Modifier.isAbstract(klassModifiers)) {
+        return false;
+      }
+
+      // Classes that extend junit.framework.TestCase are JUnit3-style test classes.
+      if (TEST_CASE_CLASS.filter(testCase -> testCase.isAssignableFrom(clazz)).isPresent()) {
+        return true;
+      }
+
+      // Since no RunWith annotation, using standard runner, which requires
+      // test classes to have exactly one public constructor (that has no args).
+      // Classes may have (non-public) constructors (with or without args).
+      boolean foundPublicNoArgConstructor = false;
+      for (Constructor<?> c : clazz.getConstructors()) {
+        if (Modifier.isPublic(c.getModifiers())) {
+          if (c.getParameterCount() != 0) {
+            return false;
+          }
+          foundPublicNoArgConstructor = true;
+        }
+      }
+      if (!foundPublicNoArgConstructor) {
+        return false;
+      }
+      // If the class has a JUnit4 @Test-annotated method, it's a test class.
+      boolean hasAtLeastOneTest = false;
+      for (Method m : clazz.getMethods()) {
+        if (isTestMethod(m)) {
+          hasAtLeastOneTest = true;
+          break;
+        }
+      }
+      return hasAtLeastOneTest;
+    }
+
+    private boolean isTestMethod(Method m) {
+      return Modifier.isPublic(m.getModifiers())
+          && m.getParameterCount() == 0
+          && TEST_ANN.filter(m::isAnnotationPresent).isPresent();
+    }
+
+    @Override
+    public boolean isAssumption(Throwable throwable) {
+      return throwable != null
+          && ASSUMPTION_EXCEPTION_CLASS
+              .filter(testCase -> testCase.isAssignableFrom(throwable.getClass()))
+              .isPresent();
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitTpxStandardOutputListener.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitTpxStandardOutputListener.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JUnitTpxStandardOutputListener.java
@@ -0,0 +1,397 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.testresultsoutput.TestResultsOutputSender;
+import com.facebook.buck.testrunner.JavaUtilLoggingHelper.LogHandlers;
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonGenerator;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.logging.Level;
+import org.junit.runner.Description;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunListener;
+
+/**
+ * Extends org.junit.runner.notification.RunListener. Meant to be registered with RunNotifier to be
+ * notified of events that occurred during a test run.
+ */
+public class JUnitTpxStandardOutputListener extends RunListener {
+  private final TpxStandardOutputTestListener listener;
+  private final Level stdOutLogLevel = Level.INFO;
+  private final Level stdErrLogLevel = Level.WARNING;
+
+  /**
+   * Class to hold logging state for each test. This allows tests to run in parallel without sharing
+   * logging state.
+   */
+  private static class TestLogState {
+    private ByteArrayOutputStream julLogBytes;
+    private ByteArrayOutputStream julErrLogBytes;
+    private LogHandlers logHandlers;
+    private StandardOutputRecorder stdoutRecorder;
+    private StandardOutputRecorder stderrRecorder;
+
+    public TestLogState() {
+      this.julLogBytes = new ByteArrayOutputStream();
+      this.julErrLogBytes = new ByteArrayOutputStream();
+    }
+
+    public ByteArrayOutputStream getJulLogBytes() {
+      return julLogBytes;
+    }
+
+    public ByteArrayOutputStream getJulErrLogBytes() {
+      return julErrLogBytes;
+    }
+
+    public void setLogHandlers(LogHandlers logHandlers) {
+      this.logHandlers = logHandlers;
+    }
+
+    public LogHandlers getLogHandlers() {
+      return logHandlers;
+    }
+
+    public void setStdoutRecorder(StandardOutputRecorder stdoutRecorder) {
+      this.stdoutRecorder = stdoutRecorder;
+    }
+
+    public StandardOutputRecorder getStdoutRecorder() {
+      return stdoutRecorder;
+    }
+
+    public void setStderrRecorder(StandardOutputRecorder stderrRecorder) {
+      this.stderrRecorder = stderrRecorder;
+    }
+
+    public StandardOutputRecorder getStderrRecorder() {
+      return stderrRecorder;
+    }
+  }
+
+  // Map to store per-test logging state using test description as key.
+  // Uses ConcurrentHashMap to support parallel test execution.
+  private final Map<String, TestLogState> testLogStates = new ConcurrentHashMap<>();
+
+  public JUnitTpxStandardOutputListener(TestResultsOutputSender sender) {
+    this.listener = new TpxStandardOutputTestListener(sender);
+  }
+
+  /**
+   * Gets the full test name for a org.junit.runner.Description
+   *
+   * @param test the Description to get the name for
+   * @return the full test name
+   */
+  private static String getFullTestName(Description description) {
+    return getFullTestName(description.getMethodName(), description.getClassName());
+  }
+
+  /**
+   * Gets the full test name from method and class names.
+   *
+   * @param methodName the test method name
+   * @param className the test class name
+   * @return the full test name in format "methodName (className)"
+   */
+  static String getFullTestName(String methodName, String className) {
+    return String.format("%s (%s)", methodName, className);
+  }
+
+  /**
+   * Checks if a description represents the NoTestsRemainException error that occurs when all tests
+   * in a class are filtered out (e.g., when TPX retries only @Ignore tests). These errors should be
+   * ignored and not reported to TPX.
+   *
+   * @param description the test description to check
+   * @return true if this is a NoTestsRemainException error, false otherwise
+   */
+  private static boolean isNoTestsRemainError(Description description) {
+    return "initializationError".equals(description.getMethodName())
+        && "org.junit.runner.manipulation.Filter".equals(description.getClassName());
+  }
+
+  /**
+   * Called when an atomic test is about to be started.
+   *
+   * @param description the description of the test that is about to be run (generally a class and
+   *     method name)
+   */
+  @Override
+  public void testStarted(Description description) {
+    if (isNoTestsRemainError(description)) {
+      return;
+    }
+
+    String testName = getFullTestName(description);
+
+    // Create new test log state for this test
+    TestLogState testLogState = new TestLogState();
+
+    // Set up logging handlers
+    LogHandlers logHandlers =
+        JavaUtilLoggingHelper.setupLogging(
+            testLogState.getJulLogBytes(),
+            testLogState.getJulErrLogBytes(),
+            this.stdOutLogLevel,
+            this.stdErrLogLevel);
+
+    testLogState.setLogHandlers(logHandlers);
+
+    // Start capturing stdout/stderr for per-test artifacts
+    try {
+      testLogState.setStdoutRecorder(StandardOutputRecorder.stdOut(this.stdOutLogLevel).record());
+      testLogState.setStderrRecorder(StandardOutputRecorder.stdErr(this.stdErrLogLevel).record());
+    } catch (IOException e) {
+      // Log warning but continue - artifact capture is best-effort
+      System.err.println("Warning: Failed to set up stdout/stderr capture: " + e.getMessage());
+    }
+
+    // Store the test log state in the map
+    testLogStates.put(testName, testLogState);
+
+    listener.testStarted(testName);
+  }
+
+  /**
+   * Called when an atomic test fails, or when a listener throws an exception.
+   *
+   * <p>In the case of a failure of an atomic test, this method will be called with the same {@code
+   * Description} passed to {@link #testStarted(Description)}, from the same thread that called
+   * {@link #testStarted(Description)}.
+   *
+   * <p>In the case of a listener throwing an exception, this will be called with a {@code
+   * Description} of {@link Description#TEST_MECHANISM}, and may be called on an arbitrary thread.
+   *
+   * @param failure describes the test that failed and the exception that was thrown
+   */
+  @Override
+  public void testFailure(Failure failure) {
+    Description description = failure.getDescription();
+    if (isNoTestsRemainError(description)) {
+      return;
+    }
+    listener.testFailed(getFullTestName(description), failure.getTrace());
+  }
+
+  /**
+   * Called when an atomic test flags that it assumes a condition that is false
+   *
+   * @param failure describes the test that failed and the {@link
+   *     org.junit.AssumptionViolatedException} that was thrown
+   */
+  @Override
+  public void testAssumptionFailure(Failure failure) {
+    listener.testAssumptionFailure(getFullTestName(failure.getDescription()), failure.getTrace());
+  }
+
+  /**
+   * Called when a test will not be run, generally because a test method is annotated with {@link
+   * org.junit.Ignore}.
+   *
+   * @param description describes the test that will not be run
+   */
+  @Override
+  public void testIgnored(Description description) {
+    listener.testIgnored(getFullTestName(description));
+  }
+
+  /**
+   * Called when an atomic test has finished, whether the test succeeds or fails.
+   *
+   * @param description the description of the test that just ran
+   */
+  @Override
+  public void testFinished(Description description) {
+    if (isNoTestsRemainError(description)) {
+      return;
+    }
+
+    String testName = getFullTestName(description);
+
+    // Get the test log state from the map
+    TestLogState testLogState = testLogStates.get(testName);
+
+    if (testLogState != null) {
+      // Complete stdout/stderr capture
+      if (testLogState.getStdoutRecorder() != null) {
+        testLogState.getStdoutRecorder().complete();
+      }
+      if (testLogState.getStderrRecorder() != null) {
+        testLogState.getStderrRecorder().complete();
+      }
+
+      // Get the captured output (direct prints followed by JUL framework logs under a
+      // "====DEBUG LOGS====" / "====ERROR LOGS====" header). Computed once and shared between the
+      // per-test artifact files and the inline per-test result below.
+      String stdout =
+          testLogState.getStdoutRecorder() != null
+              ? testLogState.getStdoutRecorder().toString(true, "====DEBUG LOGS====\n")
+              : null;
+      String stderr =
+          testLogState.getStderrRecorder() != null
+              ? testLogState.getStderrRecorder().toString(true, "====ERROR LOGS====\n")
+              : null;
+
+      // Write per-test artifacts if directories are available
+      String artifactsDir = System.getenv("TEST_RESULT_ARTIFACTS_DIR");
+      String annotationsDir = System.getenv("TEST_RESULT_ARTIFACT_ANNOTATIONS_DIR");
+
+      if (artifactsDir != null && annotationsDir != null) {
+        // Use the same test name format as TPX: "methodName (className)"
+        String testCaseName = getFullTestName(description);
+        writePerTestArtifacts(stdout, stderr, artifactsDir, annotationsDir, testCaseName);
+      }
+
+      // Surface this test's own stdout/stderr inline in the per-test result so it is visible in
+      // the terminal (e.g. next to the failure stack trace).
+      String inlineOutput = buildInlineOutput(stdout, stderr);
+      if (inlineOutput != null) {
+        listener.appendTestOutput(testName, inlineOutput);
+      }
+
+      // Clean up logging handlers
+      JavaUtilLoggingHelper.cleanupLogging(testLogState.getLogHandlers());
+
+      // Remove the test log state from the map
+      testLogStates.remove(testName);
+    }
+
+    listener.testFinished(testName);
+  }
+
+  /**
+   * Writes per-test stdout/stderr artifacts and their annotation files. Each captured stream
+   * contains the direct prints (System.out/System.err) followed by java.util.logging (JUL) messages
+   * under a "====DEBUG LOGS====" / "====ERROR LOGS====" header, helping developers distinguish test
+   * output from framework logs.
+   *
+   * @param stdout the captured stdout, or null if there was none
+   * @param stderr the captured stderr, or null if there was none
+   * @param artifactsDir directory where artifact files should be written
+   * @param annotationsDir directory where annotation files should be written
+   * @param testCaseName the test case name in format "methodName (className)"
+   */
+  private void writePerTestArtifacts(
+      String stdout,
+      String stderr,
+      String artifactsDir,
+      String annotationsDir,
+      String testCaseName) {
+    // Sanitize test name for use in filenames to avoid collisions between tests.
+    // JUnit artifacts are written to a shared directory and TPX collects them at the end,
+    // so we need unique filenames to preserve each test's output.
+    // The test_case annotation associates each artifact with its specific test.
+    String safeTestName =
+        testCaseName.replace(" ", "_").replace("(", "").replace(")", "").replace("/", "_");
+
+    // Write stdout artifact
+    if (stdout != null) {
+      String filename = "Test Stdout " + safeTestName;
+      writeArtifactWithAnnotation(artifactsDir, annotationsDir, filename, stdout, testCaseName);
+    }
+
+    // Write stderr artifact
+    if (stderr != null) {
+      String filename = "Test Stderr " + safeTestName;
+      writeArtifactWithAnnotation(artifactsDir, annotationsDir, filename, stderr, testCaseName);
+    }
+  }
+
+  /**
+   * Builds a string combining this test's captured stdout and stderr (each including the direct
+   * prints and the JUL framework logs) for inline display in the per-test result, under "====TEST
+   * STDOUT====" / "====TEST STDERR====" headers.
+   *
+   * @param stdout the captured stdout, or null if there was none
+   * @param stderr the captured stderr, or null if there was none
+   * @return the combined output, or null if the test produced no output
+   */
+  private static String buildInlineOutput(String stdout, String stderr) {
+    StringBuilder sb = new StringBuilder();
+    if (stdout != null) {
+      sb.append("====TEST STDOUT====\n").append(stdout);
+    }
+    if (stderr != null) {
+      if (sb.length() > 0) {
+        sb.append('\n');
+      }
+      sb.append("====TEST STDERR====\n").append(stderr);
+    }
+    return sb.length() == 0 ? null : sb.toString();
+  }
+
+  /**
+   * Writes an artifact file and its corresponding annotation file.
+   *
+   * @param artifactsDir directory where the artifact file should be written
+   * @param annotationsDir directory where the annotation file should be written
+   * @param filename name of the artifact file (annotation will have .annotation appended)
+   * @param content content to write to the artifact file
+   * @param testCaseName the test case name in format "methodName (className)" for annotation
+   */
+  private void writeArtifactWithAnnotation(
+      String artifactsDir,
+      String annotationsDir,
+      String filename,
+      String content,
+      String testCaseName) {
+    try {
+      // Write artifact file
+      Path artifactPath = Paths.get(artifactsDir, filename);
+      Files.write(artifactPath, content.getBytes(StandardCharsets.UTF_8));
+
+      // Write annotation file with test_case field using Jackson core
+      StringWriter stringWriter = new StringWriter();
+      try (JsonGenerator gen = new JsonFactory().createGenerator(stringWriter)) {
+        gen.writeStartObject();
+        gen.writeObjectFieldStart("type");
+        gen.writeObjectFieldStart("generic_text_log");
+        gen.writeEndObject();
+        gen.writeEndObject();
+        gen.writeStringField("test_case", testCaseName);
+        gen.writeEndObject();
+      }
+      String annotationJson = stringWriter.toString();
+      Path annotationPath = Paths.get(annotationsDir, filename + ".annotation");
+      Files.write(annotationPath, annotationJson.getBytes(StandardCharsets.UTF_8));
+    } catch (IOException e) {
+      // Log warning but don't fail the test - artifact writing is best-effort
+      System.err.println(
+          "Warning: Failed to write test artifact '" + filename + "': " + e.getMessage());
+    }
+  }
+
+  /**
+   * Reports an omitted test (e.g., @Ignore) to TPX with OMIT status so it won't be retried.
+   *
+   * @param testName the full test name in format "methodName (className)"
+   * @param reason the reason the test was omitted
+   */
+  public void reportOmittedTest(String testName, String reason) {
+    listener.testOmitted(testName, reason);
+  }
+
+  /** Traces of failures that arrived without a matching testStarted (suite setup crashes). */
+  public List<String> getUnpairedFailureTraces() {
+    return listener.getUnpairedFailureTraces();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JavaUtilLoggingHelper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JavaUtilLoggingHelper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JavaUtilLoggingHelper.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import java.io.ByteArrayOutputStream;
+import java.io.OutputStream;
+import java.util.logging.Formatter;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.Logger;
+import java.util.logging.StreamHandler;
+
+/** Helper class for Java Util Logging functionality used in test runners. */
+public class JavaUtilLoggingHelper {
+
+  /** Container class for log handlers. */
+  public static class LogHandlers {
+    private final Handler stdOutHandler;
+    private final Handler stdErrHandler;
+
+    public LogHandlers(Handler stdOutHandler, Handler stdErrHandler) {
+      this.stdOutHandler = stdOutHandler;
+      this.stdErrHandler = stdErrHandler;
+    }
+
+    public Handler getStdOutHandler() {
+      return stdOutHandler;
+    }
+
+    public Handler getStdErrHandler() {
+      return stdErrHandler;
+    }
+  }
+
+  /**
+   * Sets up logging handlers for capturing log output.
+   *
+   * @param julLogBytes ByteArrayOutputStream to capture standard log output
+   * @param julErrLogBytes ByteArrayOutputStream to capture error log output
+   * @param stdOutLogLevel Level for standard output logging
+   * @param stdErrLogLevel Level for error output logging
+   * @return A LogHandlers object containing the created handlers
+   */
+  public static LogHandlers setupLogging(
+      ByteArrayOutputStream julLogBytes,
+      ByteArrayOutputStream julErrLogBytes,
+      Level stdOutLogLevel,
+      Level stdErrLogLevel) {
+
+    // Listen to any java.util.logging messages reported by the test and write them to
+    // julLogBytes / julErrLogBytes.
+    Logger rootLogger = LogManager.getLogManager().getLogger("");
+
+    if (rootLogger != null) {
+      rootLogger.setLevel(Level.FINE);
+    }
+
+    JulLogFormatter formatter = new JulLogFormatter();
+    Handler julLogHandler = addStreamHandler(rootLogger, julLogBytes, formatter, stdOutLogLevel);
+    Handler julErrLogHandler =
+        addStreamHandler(rootLogger, julErrLogBytes, formatter, stdErrLogLevel);
+
+    return new LogHandlers(julLogHandler, julErrLogHandler);
+  }
+
+  /**
+   * Adds a stream handler to the logger.
+   *
+   * @param rootLogger The logger to add the handler to
+   * @param stream The output stream to write to
+   * @param formatter The formatter to use
+   * @param level The log level
+   * @return The created handler
+   */
+  public static Handler addStreamHandler(
+      Logger rootLogger, OutputStream stream, Formatter formatter, Level level) {
+    Handler result;
+    if (rootLogger != null) {
+      result = new StreamHandler(stream, formatter);
+      result.setLevel(level);
+      rootLogger.addHandler(result);
+    } else {
+      result = null;
+    }
+    return result;
+  }
+
+  /**
+   * Flushes and removes a log handler from the logger.
+   *
+   * @param rootLogger The logger to remove the handler from
+   * @param handler The handler to flush and remove
+   */
+  public static void flushAndRemoveLogHandler(Logger rootLogger, Handler handler) {
+    if (handler != null) {
+      handler.flush();
+    }
+    if (rootLogger != null && handler != null) {
+      rootLogger.removeHandler(handler);
+    }
+  }
+
+  /**
+   * Cleans up logging handlers.
+   *
+   * @param handlers The LogHandlers object containing the handlers to clean up
+   */
+  public static void cleanupLogging(LogHandlers handlers) {
+    Logger rootLogger = LogManager.getLogManager().getLogger("");
+
+    flushAndRemoveLogHandler(rootLogger, handlers.getStdOutHandler());
+    flushAndRemoveLogHandler(rootLogger, handlers.getStdErrHandler());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JulLogFormatter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JulLogFormatter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JulLogFormatter.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.core.util.log.appendablelogrecord.AppendableLogRecord;
+import java.io.PrintWriter; // NOPMD can't depend on Guava
+import java.io.StringWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.logging.Formatter;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+
+public class JulLogFormatter extends Formatter {
+  private static final int ERROR_LEVEL = Level.SEVERE.intValue();
+  private static final int WARN_LEVEL = Level.WARNING.intValue();
+  private static final int INFO_LEVEL = Level.INFO.intValue();
+  private static final int DEBUG_LEVEL = Level.FINE.intValue();
+  private static final int VERBOSE_LEVEL = Level.FINER.intValue();
+  private static final DateTimeFormatter DATE_FORMAT =
+      DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.US)
+          .withZone(ZoneId.systemDefault());
+
+  @Override
+  public String format(LogRecord record) {
+    long timeMillis = record.getMillis();
+    Instant instant = Instant.ofEpochMilli(timeMillis);
+    String timestamp = DATE_FORMAT.format(instant);
+
+    // We explicitly don't use String.format here because this code is very
+    // performance-critical: http://stackoverflow.com/a/1281651
+    long tid = record.getThreadID();
+    StringBuilder sb =
+        new StringBuilder("[")
+            .append(timestamp)
+            .append("]")
+            .append(formatRecordLevel(record.getLevel()))
+            .append("[tid:");
+    // Zero-pad on the left. We're currently assuming we have less than 100 threads.
+    if (tid < 10) {
+      sb.append("0").append(tid);
+    } else {
+      sb.append(tid);
+    }
+    sb.append("][").append(record.getLoggerName()).append("] ");
+    if (record instanceof AppendableLogRecord) {
+      ((AppendableLogRecord) record).appendFormattedMessage(sb);
+    } else {
+      sb.append(formatMessage(record));
+    }
+    sb.append("\n");
+    Throwable t = record.getThrown();
+    if (t != null) {
+      // Closing a StringWriter has no effect, so we don't need to do it in a
+      // try-with-resources (but oddly, it throws IOException, so we couldn't
+      // use it in a try-with-resources if we wanted to).
+      StringWriter sw = new StringWriter();
+      try (PrintWriter pw = new PrintWriter(sw)) { // NOPMD can't depend on Guava
+        t.printStackTrace(pw);
+        sb.append(sw).append("\n");
+      }
+    }
+    return sb.toString();
+  }
+
+  private static String formatRecordLevel(Level level) {
+    int l = level.intValue();
+    if (l == ERROR_LEVEL) {
+      return "[error]";
+    } else if (l == WARN_LEVEL) {
+      return "[warn ]";
+    } else if (l == INFO_LEVEL) {
+      return "[info ]";
+    } else if (l == DEBUG_LEVEL) {
+      return "[debug]";
+    } else if (l == VERBOSE_LEVEL) {
+      return "[vrbos]";
+    } else {
+      // We don't expect this to happen, so meh, let's use String.format for simplicity.
+      return String.format("[%-5d]", l);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JupiterMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JupiterMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JupiterMain.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import static com.facebook.buck.testrunner.CheckDependency.classPresent;
+import static com.facebook.buck.testrunner.CheckDependency.requiresClass;
+
+/**
+ * Launcher for JUnit Jupiter (Junit5).
+ *
+ * @see JUnitMain
+ */
+public class JupiterMain {
+
+  private JupiterMain() {
+    // Launcher class.
+  }
+
+  /**
+   * JUnit5 (Jupiter) will require its engine and launcher to be present into the classpath. In case
+   * JUnit4 is also present it will require its vintage-engine to be present into the classpath.
+   *
+   * @param args runner arguments.
+   */
+  public static void main(String[] args) {
+    // Requires Jupiter (JUnit5) engine + platform + launcher
+    requiresClass("junit-jupiter-api", "org.junit.jupiter.api.Test");
+    requiresClass("junit-jupiter-engine", "org.junit.jupiter.engine.JupiterTestEngine");
+    requiresClass("junit-jupiter-platform", "org.junit.platform.engine.TestEngine");
+    requiresClass(
+        "junit-platform-launcher", "org.junit.platform.launcher.LauncherDiscoveryRequest");
+    // If JUnit4 api is also present, it will require Vintage Engine to run
+    if (classPresent("org.junit.Test")) {
+      requiresClass("junit-vintage-engine", "org.junit.vintage.engine.VintageTestEngine");
+    }
+
+    JupiterRunner runner = new JupiterRunner();
+    runner.parseArgs(args);
+    runner.runAndExit();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JupiterRunner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JupiterRunner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/JupiterRunner.java
@@ -0,0 +1,676 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import static com.facebook.buck.testrunner.JUnitSupport.junit4Api;
+import static com.facebook.buck.testrunner.JUnitSupport.jupiterApi;
+
+import com.facebook.buck.test.result.type.ResultType;
+import com.facebook.buck.test.selectors.TestDescription;
+import com.facebook.buck.test.selectors.TestSelector;
+import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.engine.config.JupiterConfiguration;
+import org.junit.jupiter.engine.descriptor.JupiterTestDescriptor;
+import org.junit.jupiter.engine.descriptor.TestFactoryTestDescriptor;
+import org.junit.jupiter.engine.execution.JupiterEngineExecutionContext;
+import org.junit.platform.commons.util.ReflectionUtils;
+import org.junit.platform.engine.EngineExecutionListener;
+import org.junit.platform.engine.FilterResult;
+import org.junit.platform.engine.TestDescriptor;
+import org.junit.platform.engine.TestExecutionResult;
+import org.junit.platform.engine.TestExecutionResult.Status;
+import org.junit.platform.engine.TestSource;
+import org.junit.platform.engine.UniqueId;
+import org.junit.platform.engine.UniqueId.Segment;
+import org.junit.platform.engine.discovery.DiscoverySelectors;
+import org.junit.platform.engine.support.descriptor.ClassSource;
+import org.junit.platform.engine.support.descriptor.MethodSource;
+import org.junit.platform.launcher.Launcher;
+import org.junit.platform.launcher.LauncherDiscoveryRequest;
+import org.junit.platform.launcher.PostDiscoveryFilter;
+import org.junit.platform.launcher.TestExecutionListener;
+import org.junit.platform.launcher.TestIdentifier;
+import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
+import org.junit.platform.launcher.core.LauncherFactory;
+
+/**
+ * Class that runs a set of JUnit tests, (supports JUnit4 and JUnit5 tests). The result of each test
+ * class is saved to the specified directory.
+ *
+ * <p>The intent of this class is to be backward compatible with JUnit4, as also maintain the same
+ * report format that buck does use. Once the confidence that all the projects does run perfectly
+ * with this new runner, the JUnitRunner should be replaced by this.
+ *
+ * @see JUnitRunner
+ */
+public final class JupiterRunner extends BaseRunner {
+
+  public static final String EXTENSIONS_AUTODETECTION_ENABLED =
+      "junit.jupiter.extensions.autodetection.enabled";
+
+  private final Launcher launcher;
+
+  JupiterRunner() {
+    this(LauncherFactory.create());
+  }
+
+  JupiterRunner(Launcher launcher) {
+    this.launcher = launcher;
+  }
+
+  JUnitOptions getOptions() {
+    return JUnitOptions.builder()
+        .testSelectorList(testSelectorList)
+        .dryRun(isDryRun)
+        .defaultTestTimeoutMillis(defaultTestTimeoutMillis)
+        .shouldExplainTestSelectors(shouldExplainTestSelectors)
+        .build();
+  }
+
+  @Override
+  public void run() throws Throwable {
+    JUnitOptions options = getOptions();
+    for (String className : testClassNames) {
+      writeResult(className, runTest(options, Class.forName(className)));
+    }
+  }
+
+  private List<TestResult> runTest(JUnitOptions options, Class<?> testClass) {
+
+    TestAnalyzer testAnalyzer = new TestAnalyzer();
+    RecordingListener recordingListener = new RecordingListener(options, testAnalyzer);
+    RecordingFilter recordingFilter =
+        new RecordingFilter(options, testAnalyzer)
+            // Register this filter as a SkipSelector for methods
+            .registerAsSkipFilter();
+
+    if (testAnalyzer.isEnabled(testClass)) {
+      LauncherDiscoveryRequest request = testRequest(testClass, recordingFilter);
+      launcher.execute(request, new TestExecutionListener[] {recordingListener});
+    }
+    // Combine the results with the tests we filtered out
+    return combineResults(recordingListener.getTestResults(), recordingFilter.getFilteredOut());
+  }
+
+  private LauncherDiscoveryRequest testRequest(
+      Class<?> testClass, org.junit.platform.engine.Filter<?> filter) {
+    return LauncherDiscoveryRequestBuilder.request()
+        .filters(filter)
+        .selectors(DiscoverySelectors.selectClass(testClass))
+        // enable discovery of SkipTestCondition
+        .configurationParameter(EXTENSIONS_AUTODETECTION_ENABLED, Boolean.TRUE.toString())
+        .build();
+  }
+
+  /**
+   * This method filters a list of test results prior to writing results to a file. null is returned
+   * to indicate "don't write anything", which is different to writing a file containing 0 results.
+   *
+   * <p>JUnit handles classes-without-tests in different ways. If you are not using the
+   * org.junit.runner.Request.filterWith facility then JUnit ignores classes-without-tests. However,
+   * if you are using a filter then a class-without-tests will cause a NoTestsRemainException to be
+   * thrown, which is propagated back as an error.
+   */
+  List<TestResult> combineResults(List<TestResult> results, List<TestResult> filteredResults) {
+    if (!isSingleResultCausedByNoTestsRemainException(results)) {
+      List<TestResult> combined = new ArrayList<>(filteredResults.size() + results.size());
+      combined.addAll(filteredResults);
+      combined.addAll(results);
+      return combined;
+    }
+    return new ArrayList<>(filteredResults);
+  }
+
+  /**
+   * JUnit doesn't normally consider encountering a testless class an error. However, when using
+   * org.junit.runner.manipulation.Filter, testless classes *are* considered an error, throwing
+   * org.junit.runner.manipulation.NoTestsRemainException.
+   *
+   * <p>If we are using test-selectors then it's possible we will run a test class but never run any
+   * of its test methods, because they'd all get filtered out. When this happens, the results will
+   * contain a single failure containing the error from the NoTestsRemainException.
+   *
+   * <p>However, there is another reason why the test class may have a single failure -- if the
+   * class fails to instantiate, then it doesn't get far enough to detect whether or not there were
+   * any tests. In that case, JUnit4 returns a single failure result with the testMethodName set to
+   * "initializationError".
+   *
+   * <p>(NB: we can't decide at the class level whether we need to run a test class or not; we can
+   * only run the test class and all its test methods and handle the erroneous exception JUnit
+   * throws if no test-methods were actually run.)
+   */
+  private boolean isSingleResultCausedByNoTestsRemainException(List<TestResult> results) {
+    if (results.size() != 1) {
+      return false;
+    }
+    TestResult singleResult = results.get(0);
+    return !singleResult.isSuccess()
+        && "initializationError".equals(singleResult.testMethodName)
+        && "org.junit.runner.manipulation.Filter".equals(singleResult.testClassName);
+  }
+
+  /**
+   * Filter to verify if a {@code TestSelector} is provided and record results for disabled or tests
+   * that were excluded.
+   *
+   * <p>Implementation based on the JUnitRunner
+   *
+   * @see TestSelector
+   */
+  static class RecordingFilter implements PostDiscoveryFilter {
+
+    private final JUnitOptions options;
+    private final TestAnalyzer testAnalyzer;
+    private final List<TestResult> filteredOut = new ArrayList<>();
+
+    RecordingFilter(JUnitOptions options, TestAnalyzer testAnalyzer) {
+      this.options = options;
+      this.testAnalyzer = testAnalyzer;
+    }
+
+    public RecordingFilter registerAsSkipFilter() {
+      SkipTestCondition.useSkipFilter(this::shouldSkip);
+      return this;
+    }
+
+    public List<TestResult> getFilteredOut() {
+      return filteredOut;
+    }
+
+    @Override
+    public FilterResult apply(TestDescriptor test) {
+      // validate current node
+      if (shouldExecute(test)) {
+        // apply nested filter to lazy dynamic execution
+        applyLazyFilter(test);
+        return FilterResult.included(null);
+      }
+      // return only one JUnit4 JUnitParams
+      testAnalyzer.clearJUnitParamsNestedRunners(test);
+      return FilterResult.excluded(null);
+    }
+
+    /**
+     * TestFactory methods behave differently from Parametrized and uses a internal
+     * DynamicTestFilter, so we have to wrap it to collect dry-run and other cases.
+     *
+     * @see FilterableTestFactory
+     */
+    private void applyLazyFilter(TestDescriptor parent) {
+      // lookup for nested @TestFactory containers to apply lazy-filter evaluation
+      parent.getChildren().stream()
+          // look for DynamicTest factory
+          .filter(child -> child instanceof TestFactoryTestDescriptor)
+          .map(TestFactoryTestDescriptor.class::cast)
+          // collect so we can modify the list at the parent
+          .collect(Collectors.toList())
+          .forEach(
+              test -> {
+                parent.removeChild(test);
+                parent.addChild(FilterableTestFactory.to(test, this::shouldExecute));
+              });
+    }
+
+    boolean shouldExecute(TestDescriptor test) {
+      return testAnalyzer
+          .getDescription(test)
+          .map(
+              desc -> {
+                // Ignore if the entire class is disabled
+                if (testAnalyzer.isClassDisabled(test.getSource())) {
+                  return false;
+                }
+                // @ParametrizedTest and @TestFactory will be skipped by the SkipSelector
+                if (excludedBySelector(desc)) {
+                  // to keep compatibility with junit4 runner
+                  return false;
+                }
+                if (testAnalyzer.isDisabled(test.getSource())) {
+                  disable(desc);
+                  return false;
+                }
+                if (options.isDryRun()) {
+                  dryRun(desc);
+                  return false;
+                }
+                return true;
+              })
+          // do not exclude empty descriptors, that might be test containers
+          .orElse(true);
+    }
+
+    boolean shouldSkip(ExtensionContext context) {
+      return testAnalyzer.getDescription(context).map(this::shouldSkip).orElse(false);
+    }
+
+    private boolean shouldSkip(TestDescription desc) {
+      if (excludedBySelector(desc)) {
+        return true;
+      }
+      if (options.isDryRun()) {
+        dryRun(desc);
+        return true;
+      }
+      return false;
+    }
+
+    private boolean excludedBySelector(TestDescription desc) {
+      TestSelector selector = options.getTestSelectorList().findSelector(desc);
+      if (selector.isInclusive()) {
+        return false;
+      }
+      exclude(desc, selector.getExplanation());
+      return true;
+    }
+
+    private void exclude(TestDescription desc, String reason) {
+      if (options.isShouldExplainTestSelectors()) {
+        filteredOut.add(
+            TestResult.forExcluded(
+                desc.getClassName(), desc.getMethodName(), "Excluded by filter: " + reason));
+      }
+    }
+
+    private void dryRun(TestDescription desc) {
+      filteredOut.add(TestResult.forDryRun(desc.getClassName(), desc.getMethodName()));
+    }
+
+    private void disable(TestDescription desc) {
+      filteredOut.add(TestResult.forDisabled(desc.getClassName(), desc.getMethodName()));
+    }
+  }
+
+  /** Wrapper to do lazy evaluation in DynamicTests (@TestFactory methods). */
+  static class FilterableTestFactory extends TestFactoryTestDescriptor {
+
+    private static final Field CONFIGURATION = configurationField();
+
+    static Field configurationField() {
+      try {
+        return ReflectionUtils.makeAccessible(
+            JupiterTestDescriptor.class.getDeclaredField("configuration"));
+      } catch (NoSuchFieldException e) {
+        throw new IllegalStateException("failed to get configuration field", e);
+      }
+    }
+
+    static FilterableTestFactory to(
+        TestFactoryTestDescriptor test, Predicate<TestDescriptor> filter) {
+      JupiterConfiguration configuration =
+          ReflectionUtils.tryToReadFieldValue(CONFIGURATION, test)
+              .toOptional()
+              .map(JupiterConfiguration.class::cast)
+              .orElse(null);
+      return new FilterableTestFactory(test, configuration, filter);
+    }
+
+    private final Predicate<TestDescriptor> filter;
+
+    FilterableTestFactory(
+        TestFactoryTestDescriptor test,
+        JupiterConfiguration configuration,
+        Predicate<TestDescriptor> filter) {
+      super(test.getUniqueId(), test.getTestClass(), test.getTestMethod(), configuration);
+      this.filter = filter;
+    }
+
+    @Override
+    protected void invokeTestMethod(
+        JupiterEngineExecutionContext context, DynamicTestExecutor dynamicTestExecutor) {
+      super.invokeTestMethod(
+          context,
+          new DynamicTestExecutor() {
+            @Override
+            public void execute(TestDescriptor test) {
+              if (filter.test(test)) {
+                dynamicTestExecutor.execute(test);
+              }
+            }
+
+            @Override
+            public Future<?> execute(
+                TestDescriptor test, EngineExecutionListener executionListener) {
+              if (filter.test(test)) {
+                return dynamicTestExecutor.execute(test, executionListener);
+              }
+              return CompletableFuture.completedFuture(null);
+            }
+
+            @Override
+            public void awaitFinished() throws InterruptedException {
+              dynamicTestExecutor.awaitFinished();
+            }
+          });
+    }
+  }
+
+  /**
+   * Listener responsible for record all test executions.
+   *
+   * <p>Implementation based on the JUnitRunner
+   *
+   * @see TestResult
+   */
+  static class RecordingListener implements TestExecutionListener {
+
+    private final JUnitOptions options;
+    private final TestAnalyzer testAnalyzer;
+    private final List<TestResult> testResults = new ArrayList<>();
+    private final long startTime = System.currentTimeMillis();
+
+    private TestRecorder testRecorder;
+
+    public RecordingListener(JUnitOptions options, TestAnalyzer testAnalyzer) {
+      this.options = options;
+      this.testAnalyzer = testAnalyzer;
+    }
+
+    public List<TestResult> getTestResults() {
+      return testResults;
+    }
+
+    @Override
+    public void executionStarted(TestIdentifier test) {
+      if (test.isTest()) {
+        // record only leaf/tests
+        testRecorder = new TestRecorder(options).record();
+      }
+    }
+
+    @Override
+    public void executionFinished(TestIdentifier test, TestExecutionResult result) {
+      if (testRecorder != null) {
+        recordResult(test, result, testRecorder.complete());
+        testRecorder = null;
+      } else if (!test.isTest()) {
+        if (result.getStatus() != TestExecutionResult.Status.SUCCESSFUL) {
+          recordUnpairedResult(test, result.getThrowable());
+        }
+      }
+    }
+
+    private void recordResult(
+        TestIdentifier test, TestExecutionResult result, TestRecorder output) {
+      testAnalyzer
+          .getDescription(test)
+          .ifPresent(description -> recordResult(description, result, output));
+    }
+
+    private void recordResult(
+        TestDescription description, TestExecutionResult result, TestRecorder output) {
+
+      ResultType type = getResultType(result.getStatus(), result.getThrowable());
+      boolean shouldAppendLog = (type != ResultType.SUCCESS);
+
+      testResults.add(
+          new TestResult(
+              description.getClassName(),
+              description.getMethodName(),
+              output.getDuration(),
+              type,
+              result.getThrowable().orElse(null),
+              output.standardOutputAsString(shouldAppendLog),
+              output.standardErrorAsString(shouldAppendLog)));
+    }
+
+    /**
+     * It's possible to encounter a Failure/Skip before we've started any tests (and therefore
+     * before testStarted() has been called). The known example is a @BeforeClass that throws an
+     * exception, but there may be others.
+     *
+     * <p>Recording these unexpected failures helps us propagate failures back up to the "buck test"
+     * process.
+     */
+    private void recordUnpairedResult(TestIdentifier test, Optional<Throwable> failure) {
+      testAnalyzer
+          .getDescription(test)
+          .ifPresent(description -> recordUnpairedResult(description, failure));
+    }
+
+    private void recordUnpairedResult(TestDescription description, Optional<Throwable> failure) {
+      testResults.add(
+          new TestResult(
+              description.getClassName(),
+              description.getMethodName(),
+              System.currentTimeMillis() - startTime,
+              getResultType(null, failure),
+              failure.orElse(null),
+              null,
+              null));
+    }
+
+    private ResultType getResultType(Status status, Optional<Throwable> failure) {
+      if (status == TestExecutionResult.Status.SUCCESSFUL) {
+        return ResultType.SUCCESS;
+      }
+      return isAssumption(failure) ? ResultType.ASSUMPTION_VIOLATION : ResultType.FAILURE;
+    }
+
+    private boolean isAssumption(final Optional<Throwable> failure) {
+      return jupiterApi().isAssumption(failure.orElse(null))
+          || junit4Api().isAssumption(failure.orElse(null));
+    }
+  }
+
+  /**
+   * Normalize several all elements from the JUnit graph into a simple TestDescriptor. Important to
+   * keep compatibility with <code>test_type=junit</code> report.
+   */
+  static class TestAnalyzer {
+
+    Optional<TestDescription> getDescription(ExtensionContext context) {
+      return ReflectionUtils.findMethod(context.getClass(), "getTestDescriptor")
+          .map(method -> ReflectionUtils.invokeMethod(method, context))
+          .map(TestDescriptor.class::cast)
+          .flatMap(this::getDescription);
+    }
+
+    Optional<TestDescription> getDescription(TestIdentifier test) {
+      String id = test.getUniqueId();
+      String displayName = test.getDisplayName();
+      return getClassName(test.getSource())
+          .map(
+              className -> {
+                String methodName = getMethodNameWithParams(id, displayName, test.getSource());
+                return new TestDescription(className, methodName);
+              });
+    }
+
+    Optional<TestDescription> getDescription(TestDescriptor test) {
+      // tests are leafs, no children
+      String id = test.getUniqueId().toString();
+      String displayName = test.getDisplayName();
+      Optional<TestSource> source = test.getSource();
+      // For vintage "pl.pragmatists.JUnitParams", we return the parent descriptor (method)
+      // to preserve same behavior of test_type="junit"
+      Optional<TestDescription> junitParamsDescription = getJUnitParamsTestDescription(test);
+      if (junitParamsDescription.isPresent()) {
+        return junitParamsDescription;
+      }
+      // @TestFactory will not be marked as type=test
+      if (test.isTest()) {
+        return getClassName(source)
+            .map(
+                className -> {
+                  String methodName = getMethodNameWithParams(id, displayName, source);
+                  return new TestDescription(className, methodName);
+                });
+      }
+      return Optional.empty();
+    }
+
+    /**
+     * When running Vintage "pl.pragmatists.JUnitParams", we have to emulate the same behavior of
+     * <code>buck test --dry-run</code> for test_type="junit" which it returns the parent method
+     * name and not each individual parameters that will be used
+     */
+    void clearJUnitParamsNestedRunners(TestDescriptor test) {
+      getJUnitParamsTestDescription(test)
+          .ifPresent(
+              desc ->
+                  test.getChildren().stream()
+                      .collect(Collectors.toList())
+                      .forEach(test::removeChild));
+    }
+
+    private Optional<TestDescription> getJUnitParamsTestDescription(TestDescriptor test) {
+      if (!isJUnitParamsMethod(test)) {
+        return Optional.empty();
+      }
+      Optional<String> runnerName = getSegmentValue(test, "runner");
+      Optional<String> testName = getSegmentValue(test, "test");
+      if (runnerName.isPresent() && testName.isPresent()) {
+        return Optional.of(new TestDescription(runnerName.get(), testName.get()));
+      }
+      return Optional.empty();
+    }
+
+    private Optional<String> getSegmentValue(TestDescriptor test, String type) {
+      return test.getUniqueId().getSegments().stream()
+          .filter(segment -> type.equals(segment.getType()))
+          .map(Segment::getValue)
+          .findFirst();
+    }
+
+    private Optional<String> getClassName(Optional<TestSource> source) {
+      TestSource testSource = source.orElse(null);
+      if (testSource instanceof MethodSource) {
+        return Optional.ofNullable(((MethodSource) testSource).getClassName());
+      } else if (testSource instanceof ClassSource) {
+        return Optional.ofNullable(((ClassSource) testSource).getClassName());
+      }
+      return Optional.empty();
+    }
+
+    String getMethodNameWithParams(String id, String displayName, Optional<TestSource> source) {
+      if (isVintageEngine(id)) {
+        return displayName;
+      }
+      // JUnit5 has paramTypes in the name
+      String name = getTestSourceName(displayName, source);
+      // displayName will be the parameter values
+      if (isDynamicOrParameterized(id)) {
+        return name + "[" + displayName + "]";
+      }
+      return name;
+    }
+
+    private String getTestSourceName(String displayName, Optional<TestSource> testSource) {
+      TestSource source = testSource.orElse(null);
+      if (source instanceof MethodSource) {
+        MethodSource methodSource = (MethodSource) source;
+        String name = methodSource.getMethodName();
+        String paramTypes = methodSource.getMethodParameterTypes();
+        if (paramTypes == null || paramTypes.isEmpty()) {
+          return name;
+        }
+        return name + "(" + paramTypes.replaceAll(" ", "") + ")";
+      }
+      return displayName;
+    }
+
+    private boolean isVintageEngine(UniqueId id) {
+      return isVintageEngine(id.toString());
+    }
+
+    /**
+     * @param id Test id
+     * @return if the test engine is from the Vintage JUnit4 Engine
+     */
+    private boolean isVintageEngine(String id) {
+      return id.contains("[engine:junit-vintage]");
+    }
+
+    /**
+     * @param id Test id
+     * @return if the test is a ParametrizedTest or from a TestFactory
+     */
+    private boolean isDynamicOrParameterized(String id) {
+      // junixsocket-selftest-2.4.0-jar-with-dependencies that is packing and old version
+      // because of that we can't use the identifier.getUniqueIdObject().getLastSegment().getType()
+      // dynamic-test: tests produced by @TestFactory
+      return id.contains("[dynamic-test:")
+          // test-template-invocation: tests produced by @ParametrizedTest
+          || id.contains("[test-template-invocation:");
+    }
+
+    private boolean isJUnitParamsMethod(TestDescriptor test) {
+      UniqueId uniqueId = test.getUniqueId();
+      if (!isVintageEngine(uniqueId)) {
+        return false;
+      }
+      boolean hasNoSource = !test.getSource().isPresent();
+      boolean hasJunitParamsTest =
+          !test.getChildren().isEmpty()
+              && test.getChildren().stream().allMatch(this::isJunitParamsTest);
+      return hasNoSource && hasJunitParamsTest;
+    }
+
+    private boolean isJunitParamsTest(TestDescriptor test) {
+      if (test.isTest()) {
+        // JUnitParams will have children with ClassSource only
+        // ParametrizedTests will be MethodSource
+        return test.getChildren().isEmpty()
+            && test.getSource().filter(source -> source instanceof ClassSource).isPresent();
+      }
+      return false;
+    }
+
+    public boolean isEnabled(Class<?> testClass) {
+      return isTest(testClass) && !isDisabled(testClass);
+    }
+
+    private boolean isClassDisabled(Optional<TestSource> source) {
+      return source.map(this::isClassDisabled).orElse(false);
+    }
+
+    private boolean isDisabled(Optional<TestSource> source) {
+      return source.map(this::isDisabled).orElse(false);
+    }
+
+    private boolean isClassDisabled(TestSource source) {
+      if (source instanceof MethodSource) {
+        return isDisabled(((MethodSource) source).getJavaClass());
+      }
+      if (source instanceof ClassSource) {
+        return isDisabled(((ClassSource) source).getJavaClass());
+      }
+      return false;
+    }
+
+    private boolean isDisabled(TestSource source) {
+      if (isClassDisabled(source)) {
+        return true;
+      }
+      if (source instanceof MethodSource) {
+        return isDisabled(((MethodSource) source).getJavaMethod());
+      }
+      return false;
+    }
+
+    private boolean isDisabled(AnnotatedElement element) {
+      return jupiterApi().disabled(element) || junit4Api().disabled(element);
+    }
+
+    private boolean isTest(Class<?> testClass) {
+      return jupiterApi().test(testClass) || junit4Api().test(testClass);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/META-INF/services/org.junit.jupiter.api.extension.Extension b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/META-INF/services/org.junit.jupiter.api.extension.Extension
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/META-INF/services/org.junit.jupiter.api.extension.Extension
@@ -0,0 +1,1 @@
+com.facebook.buck.testrunner.SkipTestCondition
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestCoverageExtension.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestCoverageExtension.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestCoverageExtension.kt
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner
+
+import java.io.Closeable
+import java.io.File
+
+/** Optional coverage collector discovered by [PerTestCoverageExtensionManager]. */
+interface PerTestCoverageExtension : Closeable {
+  fun initialize(outputDir: File)
+
+  fun testStarted(testName: String) {}
+
+  fun testFinished(testName: String) {}
+
+  override fun close() {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestCoverageExtensionManager.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestCoverageExtensionManager.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestCoverageExtensionManager.kt
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner
+
+import java.io.File
+import java.util.ServiceLoader
+import java.util.concurrent.ConcurrentHashMap
+
+/** Manages discovery and lifecycle callbacks for optional per-test coverage extensions. */
+class PerTestCoverageExtensionManager(
+    private val extensions: List<PerTestCoverageExtension>,
+) : PerTestCoverageExtension {
+
+  private val reportedFailures = ConcurrentHashMap.newKeySet<String>()
+
+  override fun initialize(outputDir: File) {
+    extensions.forEach { extension ->
+      runExtension(extension, "initialization") { extension.initialize(outputDir) }
+    }
+  }
+
+  override fun testStarted(testName: String) {
+    extensions.forEach { extension ->
+      runExtension(extension, "test start for $testName") { extension.testStarted(testName) }
+    }
+  }
+
+  override fun testFinished(testName: String) {
+    extensions.forEach { extension ->
+      runExtension(extension, "test finish for $testName") { extension.testFinished(testName) }
+    }
+  }
+
+  override fun close() {
+    extensions.asReversed().forEach { extension ->
+      runExtension(extension, "close") { extension.close() }
+    }
+  }
+
+  private inline fun runExtension(
+      extension: PerTestCoverageExtension,
+      context: String,
+      block: () -> Unit,
+  ) {
+    try {
+      block()
+    } catch (failure: Throwable) {
+      if (isFatal(failure)) throw failure
+      if (reportedFailures.add(extension.javaClass.name)) {
+        logFailure(extension.javaClass.name, context, failure)
+      }
+    }
+  }
+
+  companion object {
+    fun load(): PerTestCoverageExtensionManager =
+        try {
+          load(ServiceLoader.load(PerTestCoverageExtension::class.java).iterator())
+        } catch (failure: Throwable) {
+          if (isFatal(failure)) throw failure
+          logFailure(
+              PerTestCoverageExtension::class.java.name,
+              "provider discovery",
+              failure,
+          )
+          PerTestCoverageExtensionManager(emptyList())
+        }
+
+    internal fun load(
+        providers: Iterator<PerTestCoverageExtension>,
+    ): PerTestCoverageExtensionManager {
+      val extensions = ArrayList<PerTestCoverageExtension>()
+      while (true) {
+        try {
+          if (!providers.hasNext()) break
+          extensions.add(providers.next())
+        } catch (failure: Throwable) {
+          if (isFatal(failure)) throw failure
+          logFailure(
+              PerTestCoverageExtension::class.java.name,
+              "provider discovery",
+              failure,
+          )
+        }
+      }
+      return PerTestCoverageExtensionManager(extensions)
+    }
+
+    private fun logFailure(
+        extensionName: String,
+        context: String,
+        failure: Throwable,
+    ) {
+      System.err.println(
+          "Per-test coverage extension $extensionName failed during $context; " +
+              "continuing primary coverage without failing the test run.",
+      )
+      failure.printStackTrace(System.err)
+    }
+
+    private fun isFatal(failure: Throwable): Boolean =
+        failure is VirtualMachineError || failure is ThreadDeath
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestJUnitCoverageRunListener.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestJUnitCoverageRunListener.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/PerTestJUnitCoverageRunListener.kt
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner
+
+import java.io.File
+import org.junit.runner.Description
+
+/**
+ * Per-test JaCoCo coverage `RunListener` for fbcode JVM (JUnit/Jupiter) tests.
+ *
+ * Reads the JaCoCo runtime agent via reflection on `org.jacoco.agent.rt.RT`. If the agent isn't on
+ * the classpath (non-coverage builds), construction throws and the runner skips registration.
+ *
+ * Shared lifecycle (testRunStarted → `_setup`, testStarted → reset, testFinished → per-test dump,
+ * testRunFinished → `_teardown`) lives in [BasePerTestCoverageRunListener]. Output format
+ * (`{sanitized_test_name}.exec` files plus `manifest.jsonl`) is documented there.
+ *
+ * Activation: Set the `PER_TEST_COVERAGE_DIR` environment variable to the output directory.
+ */
+class PerTestJUnitCoverageRunListener
+@JvmOverloads
+constructor(
+    outputDir: File,
+    agent: CoverageAgent = ReflectiveCoverageAgent(),
+    private val extensionManager: PerTestCoverageExtensionManager =
+        PerTestCoverageExtensionManager.load(),
+) : BasePerTestCoverageRunListener(outputDir, agent) {
+
+  init {
+    extensionManager.initialize(outputDir)
+  }
+
+  /** Default implementation that calls JaCoCo's `RT.getAgent()` via reflection. */
+  class ReflectiveCoverageAgent : CoverageAgent {
+    private val jacocoAgent: Any
+    private val resetMethod: java.lang.reflect.Method
+    private val getExecDataMethod: java.lang.reflect.Method
+
+    init {
+      val rtClass = Class.forName("org.jacoco.agent.rt.RT")
+      jacocoAgent =
+          rtClass.getMethod("getAgent").invoke(null)
+              ?: throw IllegalStateException("JaCoCo agent returned null from RT.getAgent()")
+      resetMethod = jacocoAgent::class.java.getMethod("reset")
+      getExecDataMethod =
+          jacocoAgent::class.java.getMethod("getExecutionData", Boolean::class.javaPrimitiveType)
+    }
+
+    override fun reset() {
+      resetMethod.invoke(jacocoAgent)
+    }
+
+    override fun dumpAndReset(): ByteArray? {
+      return getExecDataMethod.invoke(jacocoAgent, true) as? ByteArray
+    }
+  }
+
+  // Per-testRun discriminator. JUnitRunner reuses one listener across multiple
+  // jUnitCore.run() invocations (one per test class), and the suite's `description.displayName`
+  // is the JUnit default "classes" for every invocation — so we tack on a counter to guarantee
+  // unique setup/teardown exec filenames per run, otherwise they overwrite each other.
+  private var runCount = 0
+
+  override fun nextRunSuffix(description: Description?): String {
+    runCount += 1
+    val base = sanitizeFileName(description?.displayName ?: "anon")
+    return "_${base}_$runCount"
+  }
+
+  override fun testStarted(description: Description) {
+    super.testStarted(description)
+    val testName = coverageTestName(description) ?: return
+    extensionManager.testStarted(testName)
+  }
+
+  override fun testFinished(description: Description) {
+    val testName = coverageTestName(description)
+    if (testName != null) {
+      extensionManager.testFinished(testName)
+    }
+    super.testFinished(description)
+  }
+
+  override fun close() {
+    extensionManager.close()
+    super.close()
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/RobolectricTimeoutEnforcingRunListener.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/RobolectricTimeoutEnforcingRunListener.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/RobolectricTimeoutEnforcingRunListener.kt
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner
+
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent.TestStatus
+import com.facebook.buck.testresultsoutput.TestResultsOutputSender
+import java.util.Optional
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.Executors
+import java.util.concurrent.ScheduledExecutorService
+import java.util.concurrent.ScheduledFuture
+import java.util.concurrent.TimeUnit
+import org.junit.runner.Description
+import org.junit.runner.notification.Failure
+import org.junit.runner.notification.RunListener
+
+/**
+ * A RunListener that enforces timeouts for Robolectric tests.
+ *
+ * This listener monitors test execution and forcibly terminates tests that exceed the configured
+ * timeout period. It uses System.exit(1) to ensure timeout enforcement
+ *
+ * Note: This listener assumes it's being used only for Robolectric tests with TPX output enabled.
+ */
+class RobolectricTimeoutEnforcingRunListener
+@JvmOverloads
+constructor(
+    private val testResultsOutputSender: TestResultsOutputSender,
+    private val watchdogExecutor: ScheduledExecutorService = Executors.newScheduledThreadPool(1),
+) : RunListener() {
+  private val activeTimeouts: MutableMap<Description, TestExecution> = ConcurrentHashMap()
+
+  override fun testStarted(description: Description) {
+    val startTime = System.currentTimeMillis()
+
+    val timeoutMs = getTimeout()
+
+    // Schedule timeout task
+    val timeoutTask =
+        watchdogExecutor.schedule(
+            { handleTimeout(description, timeoutMs) },
+            timeoutMs,
+            TimeUnit.MILLISECONDS,
+        )
+
+    activeTimeouts[description] = TestExecution(timeoutTask, startTime)
+  }
+
+  override fun testFinished(description: Description) {
+    cancelExecution(description)
+  }
+
+  override fun testFailure(failure: Failure) {
+    cancelExecution(failure.description)
+  }
+
+  override fun testAssumptionFailure(failure: Failure) {
+    cancelExecution(failure.description)
+  }
+
+  override fun testIgnored(description: Description) {
+    cancelExecution(description)
+  }
+
+  private fun cancelExecution(description: Description) {
+    val execution = activeTimeouts.remove(description)
+    execution?.timeoutTask?.cancel(false)
+  }
+
+  private fun getTimeout(): Long {
+    // Default timeout is 60 seconds
+    val defaultTimeout = 60 * 1000L
+
+    val buckMultiplierProperty = System.getProperty("android.per.test.timeout.multiplier")
+    val multiplier = buckMultiplierProperty?.toIntOrNull()?.coerceAtLeast(1) ?: 1
+
+    return defaultTimeout * multiplier
+  }
+
+  /** Handles a test timeout by writing a TPX event and forcibly terminating the JVM. */
+  private fun handleTimeout(description: Description, timeoutMs: Long) {
+    val execution = activeTimeouts[description] ?: return
+
+    val threadDump = ThreadDumpUtils.capture()
+    writeTimeoutEvent(description, execution.startTime, timeoutMs, threadDump)
+
+    // This is necessary because Robolectric tests may not respond to thread interruption
+    System.exit(1)
+  }
+
+  /** Writes a timeout event to the TPX output file. */
+  private fun writeTimeoutEvent(
+      description: Description,
+      startTime: Long,
+      timeoutMs: Long,
+      threadDump: String,
+  ) {
+    try {
+      val testName = "${description.methodName} (${description.className})"
+      val endedTime = System.currentTimeMillis()
+      val duration = endedTime - startTime
+
+      val timeoutMessage =
+          "Test timed out after ${timeoutMs}ms. " +
+              "If your test needs to run longer than ${timeoutMs / 1000} seconds, add the tpx long_running or glacial tag in the labels section of the BUCK target. " +
+              "See https://fb.workplace.com/groups/android.testing.fyi/permalink/2679204925789466/ for more details" +
+              "\n\n=== Thread Dump ===\n$threadDump"
+
+      // Write finish event with failure
+      testResultsOutputSender.sendTestFinish(
+          testName,
+          TestStatus.FAIL,
+          endedTime,
+          duration,
+          Optional.of(timeoutMessage),
+      )
+    } catch (e: Exception) {
+      System.err.println("Failed to write TPX timeout event: ${e.message}")
+      e.printStackTrace()
+    }
+  }
+
+  /** Shuts down the watchdog executor when testing is complete. */
+  fun shutdown() {
+    watchdogExecutor.shutdownNow()
+  }
+
+  /** Internal class to track test execution state. */
+  private data class TestExecution(val timeoutTask: ScheduledFuture<*>, val startTime: Long)
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/RunShellCommand.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/RunShellCommand.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/RunShellCommand.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+/** class for running shell commands through bash. */
+public class RunShellCommand {
+
+  /** runs command and args through bash. */
+  public static String run(String commandAndArgs) {
+    try {
+      System.out.println("RunShellCommand. Command:  >" + commandAndArgs + "<");
+      Process process =
+          new ProcessBuilder(new String[] {"bash", "-c", commandAndArgs})
+              .redirectErrorStream(true)
+              .start();
+
+      String out = inputStreamToString(process.getInputStream());
+      int exitValue = process.waitFor();
+      if (!commandAndArgs.contains("logcat")) {
+        System.out.println("RunShellCommand. Output: >" + out + "<");
+      }
+      if (exitValue != 0) {
+        throw new RuntimeException(
+            "command failed! exitValue: " + exitValue + ", for command >" + commandAndArgs + "<");
+      }
+      return out;
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    } catch (InterruptedException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  public static String run(String command, String args) {
+    return run(command + " " + args);
+  }
+
+  private static String inputStreamToString(InputStream inputStream) throws IOException {
+    StringBuilder stringBuilder = new StringBuilder();
+    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
+    String line;
+    while ((line = bufferedReader.readLine()) != null) {
+      stringBuilder.append(line).append("\n");
+    }
+    bufferedReader.close();
+    return stringBuilder.toString();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/SameThreadFailOnTimeout.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/SameThreadFailOnTimeout.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/SameThreadFailOnTimeout.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import org.junit.runners.model.Statement;
+
+class SameThreadFailOnTimeout extends Statement {
+  private final ExecutorService executor;
+  private final long timeout;
+  private final String testName;
+  private final Callable<Throwable> callable;
+
+  public SameThreadFailOnTimeout(
+      ExecutorService executor, long timeout, String testName, Statement next) {
+    this.executor = executor;
+    this.timeout = timeout;
+    this.testName = testName;
+    this.callable =
+        () -> {
+          try {
+            next.evaluate();
+            return null;
+          } catch (Throwable throwable) {
+            return throwable;
+          }
+        };
+  }
+
+  @Override
+  public void evaluate() throws Throwable {
+    Future<Throwable> submitted = executor.submit(callable);
+    try {
+      Throwable result = submitted.get(timeout, TimeUnit.MILLISECONDS);
+      if (result == null) {
+        return;
+      }
+      if (result instanceof TimeoutException) {
+        throw new Exception("A timeout occurred inside of the test case", result);
+      }
+      throw result;
+    } catch (TimeoutException e) {
+      System.err.printf("Dumping threads for timed-out test %s:%n", testName);
+      for (Map.Entry<Thread, StackTraceElement[]> t : Thread.getAllStackTraces().entrySet()) {
+        Thread thread = t.getKey();
+        System.err.printf("\"%s\" #%d%n", thread.getName(), thread.getId());
+        System.err.printf("\tjava.lang.Thread.State: %s%n", thread.getState());
+        for (StackTraceElement element : t.getValue()) {
+          System.err.printf("\t\t at %s%n", element);
+        }
+      }
+
+      submitted.cancel(true);
+
+      // The default timeout doesn't indicate which test was running.
+      String message = String.format("test %s timed out after %d milliseconds", testName, timeout);
+
+      throw new Exception(message);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/SkipTestCondition.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/SkipTestCondition.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/SkipTestCondition.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import java.util.Optional;
+import java.util.function.Predicate;
+import org.junit.jupiter.api.extension.ConditionEvaluationResult;
+import org.junit.jupiter.api.extension.ExecutionCondition;
+import org.junit.jupiter.api.extension.ExtensionContext;
+
+/**
+ * To be registered as an extension at <code>
+ * "META-INF/services/org.junit.jupiter.api.extension.Extension"</code>
+ */
+public class SkipTestCondition implements ExecutionCondition {
+
+  private static Predicate<ExtensionContext> SKIP_FILTER;
+
+  static void useSkipFilter(Predicate<ExtensionContext> filter) {
+    SKIP_FILTER = filter;
+  }
+
+  static Predicate<ExtensionContext> getSkipFilter() {
+    return Optional.ofNullable(SKIP_FILTER).orElse(c -> false);
+  }
+
+  /**
+   * @param context execution context.
+   * @return enabled or disabled if the execution is a dry-run.
+   */
+  @Override
+  public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
+    if (isTestExecution(context) && shouldSkip(context)) {
+      return ConditionEvaluationResult.disabled("skip");
+    }
+    return ConditionEvaluationResult.enabled(null);
+  }
+
+  private boolean isTestExecution(ExtensionContext context) {
+    return "MethodExtensionContext".equals(context.getClass().getSimpleName());
+  }
+
+  private boolean shouldSkip(ExtensionContext context) {
+    return getSkipFilter().test(context);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/StandardOutputRecorder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/StandardOutputRecorder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/StandardOutputRecorder.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.StringJoiner;
+import java.util.function.Consumer;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.StreamHandler;
+
+/**
+ * Attach a buffered {@code PrintStream} and {@code StreamHandler} to the standards output ( {@code
+ * System#setOut}, {@code System#setErr} ) and release once it's complete.
+ *
+ * @see #stdOut(Level)
+ * @see #stdErr(Level)
+ */
+class StandardOutputRecorder {
+
+  private static final String ENCODING = "UTF-8";
+  private static final String NEWLINE = "\n";
+  private static final JulLogFormatter FORMATTER = new JulLogFormatter();
+
+  private final Level logLevel;
+  private final PrintStream originalOutput;
+  private final Consumer<PrintStream> outputRouter;
+  private PrintStream outputStream;
+  private ByteArrayOutputStream outputBuffer, logBuffer;
+  private Handler logHandler;
+
+  public static StandardOutputRecorder stdOut(Level logLevel) {
+    try {
+      return new StandardOutputRecorder(logLevel, System.out, System::setOut);
+    } catch (Exception e) {
+      throw new RuntimeException("failed to capture IO", e);
+    }
+  }
+
+  public static StandardOutputRecorder stdErr(Level logLevel) {
+    try {
+      return new StandardOutputRecorder(logLevel, System.err, System::setErr);
+    } catch (Exception e) {
+      throw new RuntimeException("failed to capture IO", e);
+    }
+  }
+
+  StandardOutputRecorder(
+      Level logLevel, PrintStream originalOut, Consumer<PrintStream> outputRouter) {
+    this.logLevel = logLevel;
+    this.outputRouter = outputRouter;
+    this.originalOutput = originalOut;
+    this.outputBuffer = new ByteArrayOutputStream();
+    this.logBuffer = new ByteArrayOutputStream();
+  }
+
+  private java.util.logging.Logger getLogger() {
+    return LogManager.getLogManager().getLogger("");
+  }
+
+  /**
+   * Create new PrintStream and Logger Handler to deviate output to buffers.
+   *
+   * @return Current instance
+   * @throws IOException In case it is not possible to create a new PrintStream
+   */
+  public StandardOutputRecorder record() throws IOException {
+    // Create an intermediate stdout/stderr to capture any debugging statements (usually in the
+    // form of System.out.println) the developer is using to debug the test.
+    outputStream = new PrintStream(outputBuffer, true, ENCODING);
+    outputRouter.accept(outputStream);
+    // Listen to any java.util.logging messages reported by the test and write them to logBuffer
+    java.util.logging.Logger logger = getLogger();
+    if (logger != null) {
+      logger.setLevel(Level.FINE);
+      logHandler = new StreamHandler(logBuffer, FORMATTER);
+      logHandler.setLevel(logLevel);
+      logger.addHandler(logHandler);
+    }
+    return this;
+  }
+
+  /**
+   * Flush the recorded output to the buffers and restore original streams.
+   *
+   * @return Current instance
+   */
+  public StandardOutputRecorder complete() {
+    // Restore the original stdout/stderr.
+    outputRouter.accept(originalOutput);
+    // Flush any debug logs and remove the handlers.
+    if (logHandler != null) {
+      logHandler.flush();
+      java.util.logging.Logger logger = getLogger();
+      if (logger != null) {
+        logger.removeHandler(logHandler);
+      }
+      logHandler = null;
+    }
+    // Get the stdout/stderr written during the test as strings.
+    if (outputStream != null) {
+      outputStream.flush();
+      outputStream = null;
+    }
+    return this;
+  }
+
+  /**
+   * @param appendLog If the required string should contain the recorded logs or just the standard
+   *     output.
+   * @param logHeader Header separating std output from the logger output.
+   * @return std output
+   */
+  public String toString(boolean appendLog, String logHeader) {
+    try {
+      String log = logBuffer.toString(ENCODING);
+      String output = outputBuffer.toString(ENCODING);
+      if (appendLog && !log.isEmpty()) {
+        return new StringJoiner("").add(output).add(NEWLINE).add(logHeader).add(log).toString();
+      }
+      return output.isEmpty() ? null : output;
+    } catch (IOException e) {
+      throw new IllegalStateException("failed to encode output", e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestNGMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestNGMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestNGMain.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+/**
+ * Launcher for TestNG.
+ *
+ * <p>Expected arguments are:
+ *
+ * <ul>
+ *   <li>(string) output directory
+ *   <li>(long) default timeout in milliseconds (0 for no timeout)
+ *   <li>(string) newline separated list of test selectors
+ *   <li>(string...) fully-qualified names of test classes
+ * </ul>
+ *
+ * <p>IMPORTANT! This class limits itself to types that are available in both the JDK and Android
+ * Java API. The objective is to limit the set of files added to the ClassLoader that runs the test,
+ * as not to interfere with the results of the test.
+ */
+public class TestNGMain {
+
+  private TestNGMain() {
+    // Launcher class.
+  }
+
+  public static void main(String[] args) {
+    // Ensure that both testng and hamcrest are on the classpath
+    CheckDependency.requiresClass("testng", "org.testng.TestNG");
+    CheckDependency.requiresClass("hamcrest", "org.hamcrest.Description");
+
+    TestNGRunner runner = new TestNGRunner();
+    runner.parseArgs(args);
+    runner.runAndExit();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestNGRunner.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestNGRunner.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestNGRunner.java
@@ -0,0 +1,369 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.test.result.type.ResultType;
+import com.facebook.buck.test.selectors.TestDescription;
+import com.facebook.buck.test.selectors.TestSelector;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.annotation.Nullable;
+import org.testng.IAnnotationTransformer;
+import org.testng.IClass;
+import org.testng.IConfigurationListener;
+import org.testng.IReporter;
+import org.testng.ITestContext;
+import org.testng.ITestListener;
+import org.testng.ITestResult;
+import org.testng.TestNG;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterGroups;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.AfterSuite;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeGroups;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.BeforeSuite;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Factory;
+import org.testng.annotations.Guice;
+import org.testng.annotations.ITestAnnotation;
+import org.testng.annotations.Test;
+import org.testng.reporters.EmailableReporter;
+import org.testng.reporters.FailedReporter;
+import org.testng.reporters.JUnitReportReporter;
+import org.testng.reporters.SuiteHTMLReporter;
+import org.testng.reporters.XMLReporter;
+
+/** Class that runs a set of TestNG tests and writes the results to a directory. */
+public final class TestNGRunner extends BaseRunner {
+  private static final boolean TESTNG_ALT_TEST_NAME_GEN_ENABLED;
+
+  static {
+    String prop = System.getProperty("testng.alt_test_name_gen");
+    TESTNG_ALT_TEST_NAME_GEN_ENABLED = "enabled".equals(prop);
+  }
+
+  @Override
+  public void run() throws Throwable {
+    for (String className : testClassNames) {
+
+      Class<?> testClass = Class.forName(className);
+
+      List<TestResult> results;
+      if (!mightBeATestClass(testClass)) {
+        results = Collections.emptyList();
+      } else {
+        results = new ArrayList<>();
+        TestNG testng = new TestNG();
+        testng.setUseDefaultListeners(false);
+        testng.addListener(new FilteringAnnotationTransformer(results, testClass.getName()));
+        testng.setTestClasses(new Class<?>[] {testClass});
+        testng.addListener(new TestListener(results));
+        // use default TestNG reporters ...
+        testng.addListener(new SuiteHTMLReporter());
+        testng.addListener((IReporter) new FailedReporter());
+        testng.addListener(new XMLReporter());
+        testng.addListener(new EmailableReporter());
+        // ... except this replaces JUnitReportReporter ...
+        testng.addListener(new JUnitReportReporterWithMethodParameters());
+        // ... and we can't access TestNG verbosity, so we remove VerboseReporter
+        testng.run();
+      }
+
+      writeResult(className, results);
+    }
+  }
+
+  /** Guessing whether or not a class is a test class is an imperfect art form. */
+  private boolean mightBeATestClass(Class<?> klass) {
+    int klassModifiers = klass.getModifiers();
+    // Test classes must be public, non-abstract, non-interface
+    if (!Modifier.isPublic(klassModifiers)
+        || Modifier.isInterface(klassModifiers)
+        || Modifier.isAbstract(klassModifiers)) {
+      return false;
+    }
+    // Test classes must either have a public, no-arg constructor, or have a constructor that
+    // initializes using dependency injection, via the org.testng.annotations.Guice annotation on
+    // the class and the com.google.inject.Inject or javax.inject.Inject annotation on the
+    // constructor.
+    boolean foundPublicNoArgConstructor = false;
+    boolean foundInjectedConstructor = false;
+    boolean hasGuiceAnnotation = klass.getAnnotationsByType(Guice.class).length > 0;
+    for (Constructor<?> c : klass.getConstructors()) {
+      if (Modifier.isPublic(c.getModifiers())) {
+        if (c.getParameterCount() == 0) {
+          foundPublicNoArgConstructor = true;
+        }
+        if (hasGuiceAnnotation
+            && (c.getAnnotationsByType(com.google.inject.Inject.class).length > 0
+                || c.getAnnotationsByType(javax.inject.Inject.class).length > 0)) {
+          foundInjectedConstructor = true;
+        }
+      }
+    }
+    if (!foundPublicNoArgConstructor && !foundInjectedConstructor) {
+      return false;
+    }
+    // Test classes must have at least one public test method (or something that generates tests)
+    boolean hasAtLeastOneTestMethod = false;
+    for (Method m : klass.getMethods()) {
+      if (Modifier.isPublic(m.getModifiers()) && m.getAnnotation(Test.class) != null) {
+        hasAtLeastOneTestMethod = true;
+      }
+      if (Modifier.isPublic(m.getModifiers()) && m.getAnnotation(Factory.class) != null) {
+        hasAtLeastOneTestMethod = true; // technically, not *quite* true, but close enough
+      }
+    }
+    return hasAtLeastOneTestMethod;
+  }
+
+  private static String getTestMethodNameWithParameters(ITestResult iTestResult) {
+    return getTestMethodNameWithParameters(iTestResult, -1);
+  }
+
+  /** Compute the "full name" of a test method, including its parameters, if any. */
+  private static String getTestMethodNameWithParameters(ITestResult iTestResult, int count) {
+    Object[] parameters = iTestResult.getParameters();
+    String name = iTestResult.getName();
+
+    if (parameters == null || parameters.length == 0) {
+      return name;
+    }
+
+    StringBuilder builder = new StringBuilder(name);
+
+    if (TESTNG_ALT_TEST_NAME_GEN_ENABLED && count >= 0) {
+      builder.append(" [").append(count).append("]");
+    } else {
+      builder
+          .append(" (")
+          .append(
+              Arrays.stream(parameters)
+                  .map(
+                      parameter -> {
+                        try {
+                          return String.valueOf(parameter);
+                        } catch (Exception e) {
+                          return "Unstringable object";
+                        }
+                      })
+                  .collect(Collectors.joining(", ")))
+          .append(")");
+    }
+
+    return builder.toString();
+  }
+
+  public class FilteringAnnotationTransformer implements IAnnotationTransformer {
+    final List<TestResult> results;
+    private String testClassName;
+
+    FilteringAnnotationTransformer(List<TestResult> results, String testClassName) {
+      this.results = results;
+      this.testClassName = testClassName;
+    }
+
+    @Override
+    @SuppressWarnings("rawtypes")
+    public void transform(
+        ITestAnnotation annotation,
+        Class testClass,
+        Constructor testConstructor,
+        Method testMethod) {
+      if (testMethod == null) {
+        return;
+      }
+      if (hasConfigurationAnnotation(testMethod)) {
+        transformConfiguration(annotation);
+      } else {
+        transformTest(annotation, testMethod);
+      }
+    }
+
+    private void transformConfiguration(ITestAnnotation annotation) {
+      if (isDryRun) {
+        annotation.setEnabled(false);
+      }
+    }
+
+    private void transformTest(ITestAnnotation annotation, Method testMethod) {
+      String methodName = testMethod.getName();
+      TestDescription description = new TestDescription(testClassName, methodName);
+      TestSelector matchingSelector = testSelectorList.findSelector(description);
+      if (!matchingSelector.isInclusive()) {
+        // For tests that have been filtered out, record it now and don't run it
+        if (shouldExplainTestSelectors) {
+          String reason = "Excluded by filter: " + matchingSelector.getExplanation();
+          results.add(TestResult.forExcluded(testClassName, methodName, reason));
+        }
+        annotation.setEnabled(false);
+      } else if (!annotation.getEnabled()) {
+        // on a dry run, have to record it now -- since it doesn't run, listener can't do it
+        results.add(TestResult.forDisabled(testClassName, methodName));
+      } else if (isDryRun) {
+        // on a dry run, record it now and don't run it
+        results.add(TestResult.forDryRun(testClassName, methodName));
+        annotation.setEnabled(false);
+      }
+    }
+
+    private boolean hasConfigurationAnnotation(Method testMethod) {
+      return Stream.of(
+              BeforeSuite.class,
+              AfterSuite.class,
+              BeforeTest.class,
+              AfterTest.class,
+              BeforeGroups.class,
+              AfterGroups.class,
+              BeforeClass.class,
+              AfterClass.class,
+              BeforeMethod.class,
+              AfterMethod.class)
+          .anyMatch(testMethod::isAnnotationPresent);
+    }
+  }
+
+  private static class TestListener implements ITestListener, IConfigurationListener {
+    private final List<TestResult> results;
+    private boolean mustRestoreStdoutAndStderr;
+    private PrintStream originalOut, originalErr, stdOutStream, stdErrStream;
+    private ByteArrayOutputStream rawStdOutBytes, rawStdErrBytes;
+    private Map<IClass, Throwable> failedConfigurationTestClasses = new HashMap<>();
+    private Map<String, Integer> testNameCounts = new HashMap<>();
+
+    public TestListener(List<TestResult> results) {
+      this.results = results;
+    }
+
+    @Override
+    public void onTestStart(ITestResult result) {}
+
+    @Override
+    public void onTestSuccess(ITestResult result) {
+      recordResult(result, ResultType.SUCCESS, result.getThrowable());
+    }
+
+    @Override
+    public void onTestSkipped(ITestResult result) {
+      @Nullable Throwable throwable = failedConfigurationTestClasses.get(result.getTestClass());
+      if (throwable == null) {
+        recordResult(result, ResultType.ASSUMPTION_VIOLATION, result.getThrowable());
+      } else {
+        recordResult(result, ResultType.FAILURE, throwable);
+      }
+    }
+
+    @Override
+    public void onTestFailure(ITestResult result) {
+      recordResult(result, ResultType.FAILURE, result.getThrowable());
+    }
+
+    @Override
+    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
+      recordResult(result, ResultType.FAILURE, result.getThrowable());
+    }
+
+    @Override
+    public void onStart(ITestContext context) {
+      // Create an intermediate stdout/stderr to capture any debugging statements (usually in the
+      // form of System.out.println) the developer is using to debug the test.
+      originalOut = System.out;
+      originalErr = System.err;
+      rawStdOutBytes = new ByteArrayOutputStream();
+      rawStdErrBytes = new ByteArrayOutputStream();
+      stdOutStream = streamToPrintStream(rawStdOutBytes, System.out);
+      stdErrStream = streamToPrintStream(rawStdErrBytes, System.err);
+      System.setOut(stdOutStream);
+      System.setErr(stdErrStream);
+      mustRestoreStdoutAndStderr = true;
+    }
+
+    @Override
+    public void onFinish(ITestContext context) {
+      if (mustRestoreStdoutAndStderr) {
+        // Restore the original stdout/stderr.
+        System.setOut(originalOut);
+        System.setErr(originalErr);
+
+        // Get the stdout/stderr written during the test as strings.
+        stdOutStream.flush();
+        stdErrStream.flush();
+        mustRestoreStdoutAndStderr = false;
+      }
+    }
+
+    private void recordResult(ITestResult result, ResultType type, Throwable failure) {
+      String stdOut = streamToString(rawStdOutBytes);
+      String stdErr = streamToString(rawStdErrBytes);
+
+      String className = result.getTestClass().getName();
+      String name = result.getName();
+      testNameCounts.putIfAbsent(name, 0);
+      // Get index by each test method
+      int count = testNameCounts.get(name);
+      String methodName = getTestMethodNameWithParameters(result, count);
+      testNameCounts.put(name, count + 1);
+
+      long runTimeMillis = result.getEndMillis() - result.getStartMillis();
+      results.add(
+          new TestResult(className, methodName, runTimeMillis, type, failure, stdOut, stdErr));
+    }
+
+    private String streamToString(ByteArrayOutputStream str) {
+      try {
+        return str.size() == 0 ? null : str.toString(ENCODING);
+      } catch (UnsupportedEncodingException e) {
+        return null;
+      }
+    }
+
+    private PrintStream streamToPrintStream(ByteArrayOutputStream str, PrintStream fallback) {
+      try {
+        return new PrintStream(str, true /* autoFlush */, ENCODING);
+      } catch (UnsupportedEncodingException e) {
+        return fallback;
+      }
+    }
+
+    @Override
+    public void onConfigurationSuccess(ITestResult iTestResult) {}
+
+    @Override
+    public void onConfigurationFailure(ITestResult iTestResult) {
+      failedConfigurationTestClasses.put(iTestResult.getTestClass(), iTestResult.getThrowable());
+    }
+
+    @Override
+    public void onConfigurationSkip(ITestResult iTestResult) {}
+  }
+
+  private static class JUnitReportReporterWithMethodParameters extends JUnitReportReporter {
+    @Override
+    public String getTestName(ITestResult result) {
+      return getTestMethodNameWithParameters(result);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestRecorder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestRecorder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestRecorder.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import java.io.IOException;
+import java.util.logging.Level;
+
+/** Record a test execution, saving the standard outputs and duration. */
+class TestRecorder {
+
+  private static final String DEBUG_LOGS_HEADER = "====DEBUG LOGS====\n\n";
+  private static final String ERROR_LOGS_HEADER = "====ERROR LOGS====\n\n";
+
+  private final StandardOutputRecorder stdOut;
+  private final StandardOutputRecorder stdErr;
+  private long startTime;
+  private long endTime;
+
+  TestRecorder(JUnitOptions options) {
+    this.stdOut = StandardOutputRecorder.stdOut(options.getStdOutLogLevel().orElse(Level.INFO));
+    this.stdErr = StandardOutputRecorder.stdErr(options.getStdErrLogLevel().orElse(Level.WARNING));
+  }
+
+  /**
+   * Initialize and start recording standard outputs.
+   *
+   * @return Current instance.
+   */
+  public TestRecorder record() {
+    try {
+      startTime = System.currentTimeMillis();
+      stdOut.record();
+      stdErr.record();
+    } catch (IOException e) {
+      throw new IllegalStateException("failed to record standard output", e);
+    }
+    return this;
+  }
+
+  public TestRecorder complete() {
+    endTime = System.currentTimeMillis();
+    stdOut.complete();
+    stdErr.complete();
+    return this;
+  }
+
+  public long getDuration() {
+    return Math.max(endTime - startTime, -1);
+  }
+
+  /**
+   * Format standard output and log captured during the recording time.
+   *
+   * @param appendLog to indicate the output should append log content as well.
+   * @return recorded standard output.
+   */
+  public String standardOutputAsString(boolean appendLog) {
+    return stdOut.toString(appendLog, DEBUG_LOGS_HEADER);
+  }
+
+  /**
+   * Format standard error output and log captured during the recording time.
+   *
+   * @param appendLog to indicate the output should append log content as well.
+   * @return recorded standard error output.
+   */
+  public String standardErrorAsString(boolean appendLog) {
+    return stdErr.toString(appendLog, ERROR_LOGS_HEADER);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestResult.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestResult.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestResult.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.test.result.type.ResultType;
+import javax.annotation.Nullable;
+
+/**
+ * Result of an individual test method in JUnit. Similar to {@link org.junit.runner.Result}, except
+ * that it always corresponds to exactly one test method.
+ */
+final class TestResult {
+  final String testClassName;
+  final String testMethodName;
+  final long runTime;
+  final ResultType type;
+  final @Nullable Throwable failure;
+  final @Nullable String stdOut;
+  final @Nullable String stdErr;
+
+  public TestResult(
+      String testClassName,
+      String testMethodName,
+      long runTime,
+      ResultType type,
+      @Nullable Throwable failure,
+      @Nullable String stdOut,
+      @Nullable String stdErr) {
+    this.testClassName = testClassName;
+    this.testMethodName = testMethodName;
+    this.runTime = runTime;
+    this.type = type;
+    this.failure = failure;
+    this.stdOut = stdOut;
+    this.stdErr = stdErr;
+  }
+
+  public static TestResult forDryRun(String testClassName, String testMethodName) {
+    return new TestResult(testClassName, testMethodName, 0, ResultType.DRY_RUN, null, null, null);
+  }
+
+  public static TestResult forExcluded(String testClassName, String testMethodName, String reason) {
+    return new TestResult(
+        testClassName, testMethodName, 0, ResultType.EXCLUDED, null, reason, null);
+  }
+
+  public static TestResult forDisabled(String testClassName, String testMethodName) {
+    return new TestResult(testClassName, testMethodName, 0, ResultType.DISABLED, null, null, null);
+  }
+
+  public boolean isSuccess() {
+    return type == ResultType.SUCCESS;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestXmlEscaper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestXmlEscaper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TestXmlEscaper.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+/**
+ * An XML escaper that replaces invalid xml characters with valid ones. The behaviour is intended to
+ * match that of guava's XmlEscapers
+ */
+public abstract class TestXmlEscaper {
+
+  /**
+   * @param str a string to perform XML escape over
+   * @return the escaped string
+   */
+  // Nullable (but no annotation to avoid extra dependencies)
+  public final String escape(String /* Nullable */ str) {
+    if (str == null) {
+      return null;
+    }
+    StringBuilder sb = new StringBuilder(str.length());
+
+    for (int i = 0; i < str.length(); i++) {
+      sb.append(escapeChar(str.charAt(i)));
+    }
+    return sb.toString();
+  }
+
+  protected abstract String escapeChar(char c);
+
+  public static final TestXmlEscaper CONTENT_ESCAPER = new ContentEscaper();
+  public static final TestXmlEscaper ATTRIBUTE_ESCAPER = new AttributeEscaper();
+
+  private static final char MIN_ASCII_CONTROL_CHAR = 0x00;
+  private static final char MAX_ASCII_CONTROL_CHAR = 0x1F;
+
+  private static final String UNICODE_REPLACE = Character.toString('\uFFFD');
+
+  private static class ContentEscaper extends TestXmlEscaper {
+
+    @Override
+    protected String escapeChar(char c) {
+      if (c > '\uFFFD' || c < Character.MIN_VALUE) {
+        return UNICODE_REPLACE;
+      }
+
+      /*
+       * Except for \n, \t, and \r, all ASCII control characters are replaced with the Unicode
+       * replacement character.
+       *
+       */
+      if (c >= MIN_ASCII_CONTROL_CHAR
+          && c <= MAX_ASCII_CONTROL_CHAR
+          && c != '\t'
+          && c != '\n'
+          && c != '\r') {
+        return UNICODE_REPLACE;
+      }
+
+      if (c == '&') {
+        return "&amp;";
+      }
+      if (c == '<') {
+        return "&lt;";
+      }
+      if (c == '>') {
+        return "&gt;";
+      }
+
+      return Character.toString(c);
+    }
+  }
+
+  private static class AttributeEscaper extends ContentEscaper {
+
+    @Override
+    protected String escapeChar(char c) {
+      String replaced = super.escapeChar(c);
+
+      if (replaced.length() != 1 || replaced.charAt(0) != c) {
+        return replaced;
+      }
+
+      if (c == '\'') {
+        return "&apos;";
+      }
+      if (c == '"') {
+        return "&quot;";
+      }
+      if (c == '\t') {
+        return "&#x9;";
+      }
+      if (c == '\n') {
+        return "&#xA;";
+      }
+      if (c == '\r') {
+        return "&#xD;";
+      }
+      return Character.toString(c);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/ThreadDumpUtils.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/ThreadDumpUtils.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/ThreadDumpUtils.kt
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner
+
+/** Utility for capturing JVM thread dumps for timeout diagnostics. */
+object ThreadDumpUtils {
+
+  /** Captures a thread dump of all live threads and returns it as a string. */
+  @JvmStatic
+  fun capture(): String {
+    val sb = StringBuilder()
+    Thread.getAllStackTraces().forEach { (thread, stackTrace) ->
+      sb.appendLine("Thread: ${thread.name} (${thread.state})")
+      stackTrace.forEach { element -> sb.appendLine("  at $element") }
+      sb.appendLine()
+    }
+    return sb.toString()
+  }
+
+  /** Prints a thread dump to stderr for log visibility. */
+  @JvmStatic
+  fun print() {
+    System.err.println("\n=== Thread Dump ===")
+    System.err.println(capture())
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TpxStandardOutputTestListener.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TpxStandardOutputTestListener.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TpxStandardOutputTestListener.java
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner;
+
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent.TestStatus;
+import com.facebook.buck.testresultsoutput.TestResultsOutputSender;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * TpxStandardOutputTestListener sends test results to the TPX standard output format. Meant to be
+ * shared between different Java test runners that may need to implement specific interfaces.
+ */
+public class TpxStandardOutputTestListener {
+  private final TestResultsOutputSender sender;
+
+  private Map<String, TestIdentifierStatus> testIdentifierStatuses = new HashMap<>();
+  private Set<String> finishedTests = new HashSet<>();
+
+  // Traces of failures reported without a matching testStarted (suite setup crashes).
+  private final List<String> unpairedFailureTraces = new ArrayList<>();
+
+  private class TestIdentifierStatus {
+    private long startTime;
+    private String trace;
+    private TestStatus status;
+
+    public TestIdentifierStatus(long startTime) {
+      this.startTime = startTime;
+    }
+
+    public void setFailed(String trace) {
+      this.status = TestStatus.FAIL;
+      this.trace = trace;
+    }
+
+    public void setSkipped(String trace) {
+      this.status = TestStatus.SKIP;
+      this.trace = trace;
+    }
+
+    public void setOmitted(String trace) {
+      this.status = TestStatus.OMIT;
+      this.trace = trace;
+    }
+  }
+
+  public TpxStandardOutputTestListener(TestResultsOutputSender sender) {
+    this.sender = sender;
+  }
+
+  /**
+   * Registers a test identifier with the listener.
+   *
+   * @param identifier the test identifier to register
+   * @param startedTime the time the test started, in milliseconds since Unix epoch
+   */
+  private void registerTest(String identifier, long startedTime) {
+    testIdentifierStatuses.put(identifier, new TestIdentifierStatus(startedTime));
+  }
+
+  /**
+   * Sends a test start event to the TestResultsOutputSender.
+   *
+   * @param identifier the test identifier to send the start event for
+   * @param startedTime the time the test started, in milliseconds since Unix epoch
+   */
+  private void sendTestStart(String identifier, long startedTime) {
+    sender.sendTestStart(identifier, startedTime);
+  }
+
+  /**
+   * Reports the start of an individual test case.
+   *
+   * @param test identifies the test
+   */
+  public void testStarted(String identifier) {
+    if (testIdentifierStatuses.containsKey(identifier)) {
+      return;
+    }
+    long startedTime = System.currentTimeMillis();
+    registerTest(identifier, startedTime);
+    sendTestStart(identifier, startedTime);
+  }
+
+  /**
+   * Reports the failure of a individual test case.
+   *
+   * <p>Will be called between testStarted and testEnded.
+   *
+   * @param test identifies the test
+   * @param trace stack trace of failure
+   */
+  public void testFailed(String identifier, String trace) {
+    TestIdentifierStatus status = testIdentifierStatuses.get(identifier);
+    if (status == null) {
+      // No matching testStarted means the suite crashed during setup. Capture the trace instead of
+      // throwing, which would evict this listener from JUnit's RunNotifier and drop the failure.
+      unpairedFailureTraces.add(trace);
+      return;
+    }
+
+    status.setFailed(trace);
+  }
+
+  /** Traces of failures that arrived without a matching testStarted (suite setup crashes). */
+  public List<String> getUnpairedFailureTraces() {
+    return Collections.unmodifiableList(unpairedFailureTraces);
+  }
+
+  /**
+   * Called when an atomic test flags that it assumes a condition that is false
+   *
+   * @param test identifies the test
+   * @param trace stack trace of failure
+   */
+  public void testAssumptionFailure(String identifier, String trace) {
+    TestIdentifierStatus status = testIdentifierStatuses.get(identifier);
+    if (status == null) {
+      throw new IllegalStateException("testAssumptionFailure called without testStarted");
+    }
+
+    status.setSkipped(trace);
+  }
+
+  /**
+   * Called when a test will not be run, generally because a test method is annotated with
+   * org.junit.Ignore.
+   *
+   * @param test identifies the test
+   */
+  public void testIgnored(String identifier) {
+    String reason =
+        "Test ignored, generally because the test method is annotated with org.junit.Ignore";
+    TestIdentifierStatus status = testIdentifierStatuses.get(identifier);
+    if (status == null) {
+      // Android instrumentation and JUnit may call testIgnored() without testStarted()
+      // for DISABLED_ prefixed tests and @Ignore annotated tests. Synthesize a complete
+      // start/finish sequence rather than crashing the entire test run.
+      testOmitted(identifier, reason);
+      return;
+    }
+
+    status.setOmitted(reason);
+  }
+
+  /**
+   * Reports that a test was omitted (e.g., @Ignore annotation). Unlike testIgnored(), this method
+   * handles tests that were filtered out before reaching the listener and creates a complete
+   * start/finish sequence with OMIT status so TPX knows not to retry them.
+   *
+   * @param identifier the test identifier
+   * @param reason the reason the test was omitted
+   */
+  public void testOmitted(String identifier, String reason) {
+    long currentTime = System.currentTimeMillis();
+    sender.sendTestStart(identifier, currentTime);
+    sender.sendTestFinish(identifier, TestStatus.OMIT, currentTime, 0, Optional.of(reason));
+  }
+
+  /**
+   * Appends captured stdout/stderr to the test's result message so it is surfaced inline alongside
+   * the failure trace (e.g. in the terminal when running {@code buck test}). The output is
+   * attributed to this specific test, so it does not duplicate across tests the way raw
+   * process-level output did. No-op if the test is unknown or the output is empty.
+   *
+   * <p>Must be called before {@link #testFinished(String)} so the appended output is included in
+   * the finish event.
+   *
+   * @param identifier identifies the test
+   * @param output the captured output to append to the test's message
+   */
+  public void appendTestOutput(String identifier, String output) {
+    if (output == null || output.isEmpty()) {
+      return;
+    }
+    TestIdentifierStatus status = testIdentifierStatuses.get(identifier);
+    if (status == null) {
+      return;
+    }
+    if (status.trace == null || status.trace.isEmpty()) {
+      status.trace = output;
+    } else {
+      status.trace = status.trace + "\n\n" + output;
+    }
+  }
+
+  /**
+   * Reports the execution end of an individual test case.
+   *
+   * <p>If {@link #testFailed} was not invoked, this test passed. Also returns any key/value metrics
+   * which may have been emitted during the test case's execution.
+   *
+   * @param test identifies the test
+   * @param testMetrics a {@link Map} of the metrics emitted
+   */
+  public void testFinished(String identifier) {
+    long endedTime = System.currentTimeMillis();
+    TestIdentifierStatus testIdentifierStatus = testIdentifierStatuses.remove(identifier);
+    if (testIdentifierStatus == null) {
+      if (finishedTests.contains(identifier)) {
+        return;
+      }
+      throw new IllegalStateException("testEnded called without testStarted for: " + identifier);
+    }
+    finishedTests.add(identifier);
+
+    long duration = endedTime - testIdentifierStatus.startTime;
+    TestStatus resultStatus = TestStatus.PASS;
+    if (testIdentifierStatus.status != null) {
+      resultStatus = testIdentifierStatus.status;
+    }
+
+    sender.sendTestFinish(
+        identifier,
+        resultStatus,
+        endedTime,
+        duration,
+        Optional.ofNullable(testIdentifierStatus.trace));
+  }
+
+  /**
+   * Reports test run failed to complete due to a fatal error.
+   *
+   * @param errorMessage {@link String} describing reason for run failure.
+   */
+  public void testRunFailed(String errorMessage) {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TpxTimeoutBufferManager.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TpxTimeoutBufferManager.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/TpxTimeoutBufferManager.kt
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner
+
+import com.facebook.buck.testresultsoutput.TestResultsOutputEvent.RunFailureStatus
+import com.facebook.buck.testresultsoutput.TestResultsOutputSender
+import java.util.concurrent.ScheduledExecutorService
+import java.util.concurrent.ScheduledFuture
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicBoolean
+
+/**
+ * Writes timeout diagnostics (thread dumps, run failure events) to the TPX output file ~5 seconds
+ * before the action timeout, ensuring they are captured before RE's SIGKILL.
+ *
+ * Reads `TPX_TIMEOUT_SEC` from the environment and schedules a timer for `(TPX_TIMEOUT_SEC - 5)`
+ * seconds. When the timer fires, it captures a thread dump and writes a TIMEOUT run failure event.
+ * The [markCompleted] method cancels the timer on normal exit.
+ */
+class TpxTimeoutBufferManager
+private constructor(
+    private val sender: TestResultsOutputSender,
+) {
+
+  private val completed = AtomicBoolean(false)
+  private var timerFuture: ScheduledFuture<*>? = null
+  private var scheduler: ScheduledExecutorService? = null
+
+  /** Marks the run as completed so the proactive timer does not fire. */
+  fun markCompleted() {
+    completed.set(true)
+    timerFuture?.cancel(false)
+    scheduler?.shutdown()
+  }
+
+  private fun startProactiveTimer(tpxTimeoutSec: Long, scheduler: ScheduledExecutorService) {
+    this.scheduler = scheduler
+    val effectiveTimeout = tpxTimeoutSec - PROACTIVE_TIMEOUT_BUFFER_SEC
+    if (effectiveTimeout <= 0) {
+      return
+    }
+    timerFuture =
+        scheduler.schedule(
+            {
+              if (completed.compareAndSet(false, true)) {
+                handleTimeout()
+              }
+            },
+            effectiveTimeout,
+            TimeUnit.SECONDS,
+        )
+  }
+
+  private fun handleTimeout() {
+    val threadDump = ThreadDumpUtils.capture()
+    val now = System.currentTimeMillis()
+
+    // Report run failure with TIMEOUT status.
+    try {
+      sender.sendRunFailure(RunFailureStatus.TIMEOUT, now, "Test target timed out", null)
+    } catch (e: Exception) {
+      System.err.println("Failed to report run failure: ${e.message}")
+    }
+
+    // Write thread dump directly to fd 2, bypassing StandardOutputRecorder which may have
+    // intercepted System.err. TPX includes process stderr in the timeout message on the main
+    // test, so this is how the thread dump reaches the diagnostics page.
+    java.io.FileOutputStream(java.io.FileDescriptor.err).use { fos ->
+      val realStderr = java.io.PrintStream(fos)
+      realStderr.println("\n=== Thread Dump at Timeout ===")
+      realStderr.println(threadDump)
+      realStderr.flush()
+    }
+
+    scheduler?.shutdown()
+  }
+
+  companion object {
+    private const val PROACTIVE_TIMEOUT_BUFFER_SEC = 5L
+    private const val TPX_TIMEOUT_ENV_VAR = "TPX_TIMEOUT_SEC"
+
+    /**
+     * Creates a manager and starts a proactive timeout timer if `TPX_TIMEOUT_SEC` is set in the
+     * environment and the effective timeout is positive.
+     */
+    @JvmStatic
+    fun create(
+        sender: TestResultsOutputSender,
+        scheduler: ScheduledExecutorService,
+    ): TpxTimeoutBufferManager {
+      val manager = TpxTimeoutBufferManager(sender)
+      val tpxTimeoutSec = System.getenv(TPX_TIMEOUT_ENV_VAR)?.toLongOrNull()
+      if (tpxTimeoutSec != null) {
+        manager.startProactiveTimer(tpxTimeoutSec, scheduler)
+      }
+      return manager
+    }
+
+    /**
+     * Creates a manager with an explicit timeout value.
+     *
+     * @param tpxTimeoutSec the total action timeout in seconds.
+     * @param scheduler the executor used to schedule the proactive timer.
+     */
+    @JvmStatic
+    fun create(
+        sender: TestResultsOutputSender,
+        tpxTimeoutSec: Long,
+        scheduler: ScheduledExecutorService,
+    ): TpxTimeoutBufferManager {
+      val manager = TpxTimeoutBufferManager(sender)
+      manager.startProactiveTimer(tpxTimeoutSec, scheduler)
+      return manager
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/LogExtractorReportLayer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/LogExtractorReportLayer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/LogExtractorReportLayer.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner.reportlayer;
+
+import com.facebook.buck.testrunner.InstrumentationTestRunner;
+import java.io.File;
+import java.io.FileWriter;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Scanner;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/** report layer to extract logs to separate tra by regex matching */
+public class LogExtractorReportLayer extends ReportLayer {
+
+  public static final String ARG = "--log-extractor";
+
+  /** config for each extractor */
+  protected static class ExtractorConfig {
+    private final String traName;
+    private final String traDescription;
+    private final String regex;
+
+    public ExtractorConfig(String traName, String traDescription, String regex) {
+      this.traName = traName;
+      this.traDescription = traDescription;
+      this.regex = regex;
+    }
+
+    public String getTraName() {
+      return traName;
+    }
+
+    public String getTraDescription() {
+      return traDescription;
+    }
+
+    public String getRegex() {
+      return regex;
+    }
+  }
+
+  private final List<ExtractorConfig> extractors = new ArrayList<ExtractorConfig>();
+
+  public LogExtractorReportLayer(
+      InstrumentationTestRunner runner, Map<String, String> logExtractors) {
+    super(runner);
+    for (Map.Entry<String, String> entry : logExtractors.entrySet()) {
+      String name = entry.getKey();
+      String regex = entry.getValue();
+      this.extractors.add(new ExtractorConfig(name, name, regex));
+    }
+  }
+
+  @Override
+  public void initialize() {
+    // nothing needed.
+  }
+
+  @Override
+  public void report() {
+    try {
+      Path logcatMainBufferTraPath = this.runner.createPathForLogcatBuffer("main");
+      String logcatMainBufferFile = logcatMainBufferTraPath.toString();
+      for (ExtractorConfig extractorConfig : extractors) {
+        Path traPath =
+            this.runner.createTRAPlainTextLog(
+                extractorConfig.traName, extractorConfig.traDescription);
+        Pattern pattern = Pattern.compile(extractorConfig.regex);
+
+        FileWriter writer = new FileWriter(traPath.toFile());
+        Scanner scanner = new Scanner(new File(logcatMainBufferFile));
+        while (scanner.hasNextLine()) {
+          String line = scanner.nextLine();
+          Matcher matcher = pattern.matcher(line);
+          if (matcher.find()) {
+            writer.write(line + "\n");
+          }
+        }
+        scanner.close();
+        writer.close();
+      }
+    } catch (Exception e) {
+      e.printStackTrace(System.err);
+      System.err.println("fail to extract log: " + e.getMessage());
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/PerfettoReportLayer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/PerfettoReportLayer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/PerfettoReportLayer.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner.reportlayer;
+
+import com.facebook.buck.testrunner.InstrumentationTestRunner;
+import java.io.File;
+import java.io.FileWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/** Report layer to collect Perfetto system traces during instrumentation tests. */
+public class PerfettoReportLayer extends ReportLayer {
+
+  public static final String ARG = "--collect-perfetto";
+
+  private static final String PERFETTO_TRACE_DEVICE_DIR = "/data/misc/perfetto-traces/";
+  private static final String PERFETTO_TRACE_FILENAME = "ait_perfetto_trace.perfetto-trace";
+  private static final String PERFETTO_CONFIG_DEVICE_PATH = "/data/local/tmp/perfetto_config.txt";
+  private static final Pattern PID_PATTERN = Pattern.compile("\\d+");
+
+  // Default Perfetto config: ftrace events (sched, cpu freq/idle, wakeup),
+  // process_stats, sys_stats, 64KB buffer with RING_BUFFER, 600s max duration, 100MB max file size
+  private static final String PERFETTO_CONFIG =
+      "buffers { size_kb: 65536 fill_policy: RING_BUFFER } "
+          + "data_sources { config { name: \"linux.ftrace\" "
+          + "ftrace_config { ftrace_events: \"sched/sched_switch\" "
+          + "ftrace_events: \"power/cpu_frequency\" "
+          + "ftrace_events: \"power/cpu_idle\" "
+          + "ftrace_events: \"sched/sched_wakeup\" } } } "
+          + "data_sources { config { name: \"linux.process_stats\" } } "
+          + "data_sources { config { name: \"linux.sys_stats\" } } "
+          + "duration_ms: 600000 "
+          + "max_file_size_bytes: 104857600";
+
+  private String perfettoPid = null;
+
+  public PerfettoReportLayer(InstrumentationTestRunner runner) {
+    super(runner);
+  }
+
+  @Override
+  public void initialize() {
+    try {
+      String tracePath = PERFETTO_TRACE_DEVICE_DIR + PERFETTO_TRACE_FILENAME;
+
+      // Clean up any existing trace file
+      this.runner.runShellCommand("rm -f " + tracePath);
+
+      // Check if perfetto binary is available on the device
+      try {
+        this.runner.runShellCommand("which perfetto");
+      } catch (Exception e) {
+        System.err.println(
+            "PerfettoReportLayer: 'perfetto' binary not found on device. "
+                + "Perfetto tracing will not be available. Error: "
+                + e.getMessage());
+        return;
+      }
+
+      // Write perfetto config to a local temp file, then push it to the device.
+      // This avoids using echo with pipes through adb shell, which can be
+      // unreliable due to argument splitting in AdbUtils.
+      String configPath = PERFETTO_CONFIG_DEVICE_PATH;
+      File localConfigFile = File.createTempFile("perfetto-config-", ".txt");
+      try {
+        try (FileWriter writer = new FileWriter(localConfigFile)) {
+          writer.write(PERFETTO_CONFIG);
+        }
+        this.runner.pushFileWithSyncService(localConfigFile.getAbsolutePath(), configPath);
+      } finally {
+        localConfigFile.delete();
+      }
+
+      String startCmd =
+          String.format("perfetto --txt --background --config %s --out %s", configPath, tracePath);
+      String output = this.runner.runShellCommand(startCmd);
+
+      // Extract PID from perfetto output.
+      // perfetto --background returns the PID in different formats depending on version:
+      //   - "[NNN]" (older versions)
+      //   - "NNN" (plain number, newer versions)
+      if (output != null) {
+        Matcher matcher = PID_PATTERN.matcher(output.trim());
+        if (matcher.find()) {
+          perfettoPid = matcher.group();
+        }
+      }
+
+      if (perfettoPid != null) {
+        System.out.printf("PerfettoReportLayer: Perfetto started with PID: %s%n", perfettoPid);
+      } else {
+        System.err.println(
+            "PerfettoReportLayer: Warning: Could not determine Perfetto PID from output: "
+                + output);
+      }
+    } catch (Exception e) {
+      System.err.printf("PerfettoReportLayer: Failed to start Perfetto tracing: %s%n", e);
+    }
+  }
+
+  @Override
+  public void report() {
+    String tracePath = PERFETTO_TRACE_DEVICE_DIR + PERFETTO_TRACE_FILENAME;
+    try {
+      // Stop perfetto gracefully via SIGTERM
+      if (perfettoPid != null) {
+        this.runner.runShellCommand("kill -TERM " + perfettoPid);
+        // Wait for perfetto to flush and finalize the trace
+        Thread.sleep(3000);
+      } else {
+        return;
+      }
+
+      // Check if trace file exists on device
+      try {
+        String lsOutput = this.runner.runShellCommand("ls -la " + tracePath);
+        System.out.printf("PerfettoReportLayer: Trace file on device: %s%n", lsOutput);
+      } catch (Exception e) {
+        System.err.printf(
+            "PerfettoReportLayer: Trace file not found on device at %s: %s%n", tracePath, e);
+        return;
+      }
+
+      Path artifact =
+          this.runner.createTRA("generic_blob", "Perfetto trace", PERFETTO_TRACE_FILENAME);
+      if (artifact == null) {
+        System.err.println(
+            "PerfettoReportLayer: Cannot report Perfetto trace: TRA directory not configured");
+        return;
+      }
+
+      this.runner.pullFileWithSyncService(tracePath, artifact.toString());
+
+      if (!Files.exists(artifact) || Files.size(artifact) == 0) {
+        System.err.println(
+            "PerfettoReportLayer: Warning: Perfetto trace file is empty or missing after pull");
+      } else {
+        System.out.printf(
+            "PerfettoReportLayer: Successfully collected Perfetto trace (%d bytes)%n",
+            Files.size(artifact));
+      }
+    } catch (Exception e) {
+      System.err.printf("PerfettoReportLayer: Failed to collect Perfetto trace: %s%n", e);
+    } finally {
+      // Clean up trace and config from device
+      try {
+        this.runner.runShellCommand("rm -f " + tracePath);
+        this.runner.runShellCommand("rm -f " + PERFETTO_CONFIG_DEVICE_PATH);
+      } catch (Exception e) {
+        System.err.printf("PerfettoReportLayer: Failed to clean up device files: %s%n", e);
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/ReportLayer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/ReportLayer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/ReportLayer.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner.reportlayer;
+
+import com.facebook.buck.testrunner.InstrumentationTestRunner;
+
+/**
+ * base class for report layers for InstrumentationTestRunner. report layers like video recording,
+ * tombstone reporting will use it as base class
+ */
+public abstract class ReportLayer {
+  protected final InstrumentationTestRunner runner;
+
+  public ReportLayer(InstrumentationTestRunner runner) {
+    this.runner = runner;
+  }
+
+  /*
+  initialize the report layer
+   */
+  public abstract void initialize();
+
+  /*
+  do the actual reporting
+   */
+  public abstract void report();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/TombstonesReportLayer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/TombstonesReportLayer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/TombstonesReportLayer.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner.reportlayer;
+
+import com.facebook.buck.testrunner.InstrumentationTestRunner;
+import java.net.URI;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.HashMap;
+import java.util.Iterator;
+
+/** report layer to collect tombstones to TRA after tests finish */
+public class TombstonesReportLayer extends ReportLayer {
+
+  private static final String TOMBSTONE_REMOTE_PATH = "/data/tombstones/";
+
+  public static final String ARG = "--collect-tombstones";
+
+  private final boolean collectAlways;
+
+  public TombstonesReportLayer(InstrumentationTestRunner runner, boolean collectAlways) {
+    super(runner);
+    this.collectAlways = collectAlways;
+  }
+
+  @Override
+  public void initialize() {}
+
+  @Override
+  public void report() {
+    if (this.collectAlways || this.runner.hasTestRunFailed()) {
+      try {
+        this.collectTombstones();
+      } catch (Exception e) {
+        System.err.printf("Failed to collect tombstones with error: %s\n", e);
+      }
+    }
+  }
+
+  private void collectTombstones() throws Exception {
+    if (!this.runner.directoryExists(TOMBSTONE_REMOTE_PATH)) {
+      return;
+    }
+    // get the tombstones from the device
+    Path tmp = Files.createTempDirectory("ait-tombstones-");
+    if (!Files.exists(tmp)) {
+      Files.createDirectory(tmp);
+    }
+    this.runner.pullDir(TOMBSTONE_REMOTE_PATH, tmp.toString());
+
+    // check whether the dir is empty
+    if (Files.list(tmp).count() == 0) {
+      return;
+    }
+
+    Path artifact_path =
+        this.runner.createTRA("generic_blob", "Zip file with all tombstones", "tombstones.zip");
+    if (null == artifact_path) {
+      // we cannot report to TRA, because the dir is not known. So skip it.
+      return;
+    }
+
+    // pack them into a zip
+    URI uri = URI.create("jar:" + artifact_path.toUri());
+    HashMap<String, String> env = new HashMap<>();
+    env.put("create", "true");
+    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
+      Iterator<Path> tombstones = Files.walk(tmp).filter(Files::isRegularFile).iterator();
+      while (tombstones.hasNext()) {
+        Path path = tombstones.next();
+        Path target = zipfs.getPath(tmp.relativize(path).toString());
+        if (null != target.getParent()) {
+          Files.createDirectory(target.getParent());
+        }
+        Files.copy(path, target, StandardCopyOption.REPLACE_EXISTING);
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/VideoRecordingReportLayer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/VideoRecordingReportLayer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/testrunner/reportlayer/VideoRecordingReportLayer.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.testrunner.reportlayer;
+
+import com.facebook.buck.testrunner.InstrumentationTestRunner;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.util.regex.Pattern;
+
+/**
+ * report layer to start a process to record video of tests before they run and collect the video as
+ * TRA after tests finish
+ */
+public class VideoRecordingReportLayer extends ReportLayer {
+
+  private static final String VIDEO_RECORDING_STORAGE_PATH =
+      "/sdcard/test_result/video_recordings/";
+  private static final String VIDEO_RECORDING_SCRIPT_NAME = "test-video-record.sh";
+  private static final String VIDEO_RECORDING_FILE_NAME = "test-video-record.mp4";
+
+  public static final String ARG = "--record-video";
+
+  private Process videoRecordingProcess;
+
+  public VideoRecordingReportLayer(InstrumentationTestRunner runner) {
+    super(runner);
+  }
+
+  @Override
+  public void initialize() {
+    this.videoRecordingProcess = this.startVideoRecording();
+  }
+
+  @Override
+  public void report() {
+    this.collectVideoRecording();
+  }
+
+  private String getVideoRecordingStoragePath() {
+    return String.format(VIDEO_RECORDING_STORAGE_PATH, this.runner.getPackageName());
+  }
+
+  private Process startVideoRecording() {
+    try {
+      File scriptFile = File.createTempFile("video-recording-", ".sh");
+      FileWriter scriptFileWriter = new FileWriter(scriptFile);
+      // create local script file
+      scriptFileWriter.write(
+          String.join(
+              "\n",
+              "exec 2>&1  # merge stdout and stderr",
+              "set -xue",
+              String.format(
+                  "screenrecord --verbose --bugreport %s &",
+                  String.format(
+                      "%s/%s", this.getVideoRecordingStoragePath(), VIDEO_RECORDING_FILE_NAME)),
+              "pid=$!  # screenrecord pid",
+              "read  # wait for stopword (any input)",
+              "kill -INT $pid  # request screenrecord to stop gracefully",
+              "wait $pid"));
+      scriptFile.deleteOnExit();
+      scriptFileWriter.close();
+      // push script to device
+      String remoteScriptPath =
+          String.format("%s/%s", this.getVideoRecordingStoragePath(), VIDEO_RECORDING_SCRIPT_NAME);
+      this.runner.pushFileWithSyncService(scriptFile.getAbsolutePath(), remoteScriptPath);
+      // start recording process via runner.exec() so it can be mocked in tests
+      String command = String.format("adb shell sh %s", remoteScriptPath);
+      return this.runner.exec(command);
+    } catch (Exception e) {
+      System.err.printf("Failed to start video recording process with error: %s\n", e);
+      return null;
+    }
+  }
+
+  private void collectVideoRecording() {
+    try {
+      // stop video recording
+      videoRecordingProcess.getOutputStream().write("STOP".getBytes());
+      videoRecordingProcess.getOutputStream().write(System.lineSeparator().getBytes());
+      videoRecordingProcess.getOutputStream().flush();
+      StringBuilder output = new StringBuilder();
+      try (InputStream is = videoRecordingProcess.getInputStream()) {
+        byte[] allOutput = readAllBytes(is);
+        output.append(new String(allOutput));
+      } catch (IOException e) {
+        output.append("IOError: ");
+        output.append(e.getMessage());
+        output.append("\n");
+      }
+      int exitCode = videoRecordingProcess.waitFor();
+      if (exitCode != 0) {
+        // check whether screenrecord terminated before we tried to kill it. We don't want to throw
+        // an error in that case.
+        Pattern noProcessKilled = Pattern.compile("kill: \\d+: No such process");
+        if (!noProcessKilled.matcher(output).find()) {
+          throw new Exception(
+              String.format(
+                  "Failed to stop video recording process with exit code %d, Output: %s",
+                  exitCode, output.toString()));
+        }
+      }
+      // pull file to TRA
+      Path video_artifact =
+          this.runner.createTRA(
+              "video_recording_test_artifact", "video recording", VIDEO_RECORDING_FILE_NAME);
+      if (null == video_artifact) {
+        throw new Exception("Failed to create TRA for video recording");
+      }
+      this.runner.pullFileWithSyncService(
+          String.format("%s/%s", this.getVideoRecordingStoragePath(), VIDEO_RECORDING_FILE_NAME),
+          video_artifact.toString());
+    } catch (Exception e) {
+      System.err.printf("Failed to collect video recording process with error: %s", e);
+    }
+  }
+
+  private static byte[] readAllBytes(InputStream inputStream) throws IOException {
+    final int bufLen = 1024;
+    byte[] buf = new byte[bufLen];
+    int readLen;
+
+    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+
+    while ((readLen = inputStream.read(buf, 0, bufLen)) != -1) {
+      outputStream.write(buf, 0, readLen);
+    }
+
+    return outputStream.toByteArray();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/AbstractMemoizer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/AbstractMemoizer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/AbstractMemoizer.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import com.facebook.buck.util.function.ThrowingSupplier;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import javax.annotation.Nullable;
+
+/** A Generic memoizer capable of memoizing Exceptions */
+class AbstractMemoizer<T, E extends Exception> {
+
+  @Nullable private volatile T value = null;
+  @Nullable private volatile E exception = null;
+
+  /**
+   * Get the value and memoize the result. Constructs the value if it hasn't been memoized before,
+   * or if the previously memoized value has been collected.
+   *
+   * @param delegate delegate for constructing the value
+   * @return the value
+   */
+  public T get(ThrowingSupplier<T, E> delegate, Class<E> exceptionClass) throws E {
+    if (value == null && exception == null) {
+      synchronized (this) {
+        if (value == null) {
+          try {
+            T t = Preconditions.checkNotNull(delegate.get());
+            value = t;
+            return t;
+          } catch (Exception e) {
+            if (exceptionClass.isInstance(e)) {
+              exception = exceptionClass.cast(e);
+              Throwables.throwIfInstanceOf(e, exceptionClass);
+            }
+            Throwables.throwIfUnchecked(e);
+            throw new IllegalStateException(e);
+          }
+        }
+      }
+    }
+    if (value != null) {
+      return value;
+    }
+    throw exception;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/BUCK
@@ -0,0 +1,67 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library", "buck_kotlin_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+THROWING_PRINT_WRITER_SRCS = [
+    "ThrowingPrintWriter.java",
+]
+
+buck_java_library(
+    name = "throwing_print_writer",
+    srcs = THROWING_PRINT_WRITER_SRCS,
+    visibility = ["PUBLIC"],
+)
+
+PROCESS_EXECUTOR_SRCS = [
+    "CapturingPrintStream.java",
+    "Console.java",
+    "Threads.java",
+    "Verbosity.java",
+]
+
+buck_kotlin_library(
+    name = "process_executor",
+    srcs = PROCESS_EXECUTOR_SRCS,
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/util:util",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+        ":util",
+    ],
+)
+
+buck_java_library(
+    name = "util",
+    srcs = glob(
+        ["*.java"],
+        exclude = PROCESS_EXECUTOR_SRCS + THROWING_PRINT_WRITER_SRCS,
+    ),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/util:util",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/fatjar:fat_jar_utils",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/src/com/facebook/buck/util/escaper:bash",
+        "prelude//toolchains/android/src/com/facebook/buck/util/escaper:quoter",
+        "prelude//toolchains/android/src/com/facebook/buck/util/escaper:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/util/function:function",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jackson-annotations",
+        "prelude//toolchains/android/third-party:jackson-databind",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/BuckConstant.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/BuckConstant.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/BuckConstant.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+public class BuckConstant {
+
+  public static final String DEFAULT_BUCK_OUT_DIR_NAME = "buck-out";
+  private static final Path BUCK_OUTPUT_PATH_DEFAULT =
+      Paths.get(System.getProperty("buck.base_buck_out_dir", DEFAULT_BUCK_OUT_DIR_NAME));
+
+  private BuckConstant() {}
+
+  /** The relative path to the directory where Buck will generate its files. */
+  public static Path getBuckOutputPath() {
+    return BUCK_OUTPUT_PATH_DEFAULT;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/CapturingPrintStream.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/CapturingPrintStream.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/CapturingPrintStream.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
+
+public class CapturingPrintStream extends PrintStream {
+
+  private final ByteArrayOutputStream byteArrayOutputStream;
+
+  public CapturingPrintStream() {
+    this(new ByteArrayOutputStream());
+  }
+
+  private CapturingPrintStream(ByteArrayOutputStream byteArrayOutputStream) {
+    super(byteArrayOutputStream);
+    this.byteArrayOutputStream = byteArrayOutputStream;
+  }
+
+  public String getContentsAsString(Charset charset) {
+    try {
+      return byteArrayOutputStream.toString(charset.name());
+    } catch (UnsupportedEncodingException e) {
+      throw new RuntimeException(e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ClassLoaderCache.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ClassLoaderCache.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ClassLoaderCache.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+
+/**
+ * Maintain a cache mapping class paths to class loaders that load from these class paths. The class
+ * loaders remain active until ClassLoaderCache itself is unloaded.
+ */
+public final class ClassLoaderCache implements AutoCloseable {
+  private static final Logger LOG = Logger.get(ClassLoaderCache.class);
+
+  private final Map<ClassLoader, Map<ImmutableList<URL>, ClassLoader>> cache = new HashMap<>();
+
+  private int referenceCount = 1;
+
+  private synchronized Map<ImmutableList<URL>, ClassLoader> getCacheForParent(
+      @Nullable ClassLoader parentClassLoader) {
+    Map<ImmutableList<URL>, ClassLoader> cacheForParent = cache.get(parentClassLoader);
+
+    if (cacheForParent == null) {
+      cacheForParent = new HashMap<>();
+      cache.put(parentClassLoader, cacheForParent);
+    }
+
+    return cacheForParent;
+  }
+
+  public synchronized ClassLoader getClassLoaderForClassPath(
+      @Nullable ClassLoader parentClassLoader, ImmutableList<URL> classPath) {
+
+    Map<ImmutableList<URL>, ClassLoader> cacheForParent = getCacheForParent(parentClassLoader);
+
+    ClassLoader classLoader = cacheForParent.get(classPath);
+    if (classLoader == null) {
+      LOG.info(
+          "Encountered cache miss for parent: %s and classpath:%s", parentClassLoader, classPath);
+      URL[] urls = classPath.toArray(new URL[0]);
+      classLoader = new CachedURLClassLoader(urls, parentClassLoader);
+      cacheForParent.put(classPath, classLoader);
+    }
+
+    return classLoader;
+  }
+
+  @VisibleForTesting
+  public synchronized void injectClassLoader(
+      @Nullable ClassLoader parentClassLoader,
+      ImmutableList<URL> classPath,
+      ClassLoader injectedClassLoader) {
+    Map<ImmutableList<URL>, ClassLoader> cacheForParent = getCacheForParent(parentClassLoader);
+
+    cacheForParent.put(classPath, injectedClassLoader);
+  }
+
+  public synchronized ClassLoaderCache addRef() {
+    referenceCount += 1;
+    return this;
+  }
+
+  @Override
+  public synchronized void close() throws IOException {
+    if (referenceCount > 1) {
+      referenceCount -= 1;
+      return;
+    }
+
+    Optional<IOException> caughtEx = Optional.empty();
+
+    for (Map<ImmutableList<URL>, ClassLoader> cacheForParent : cache.values()) {
+      for (ClassLoader cl : cacheForParent.values()) {
+        try {
+          if (cl instanceof CachedURLClassLoader) {
+            ((CachedURLClassLoader) cl).reallyClose();
+          }
+        } catch (IOException ex) {
+          if (caughtEx.isPresent()) {
+            caughtEx.get().addSuppressed(ex);
+          } else {
+            caughtEx = Optional.of(ex);
+          }
+        }
+      }
+    }
+
+    if (caughtEx.isPresent()) {
+      throw caughtEx.get();
+    }
+  }
+
+  private static class CachedURLClassLoader extends URLClassLoader {
+    public CachedURLClassLoader(URL[] urls, @Nullable ClassLoader parent) {
+      super(urls, parent);
+    }
+
+    @Override
+    public void close() {
+      // Do nothing; only the cache can close this ClassLoader
+    }
+
+    private void reallyClose() throws IOException {
+      super.close();
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Console.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Console.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Console.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.google.common.io.ByteStreams;
+import java.io.PrintStream;
+
+public class Console {
+
+  private static final Logger LOG = Logger.get(Console.class);
+
+  private final Verbosity verbosity;
+  private final PrintStream stdOut;
+  private final PrintStream stdErr;
+
+  private static final PrintStream NULL_PRINT_STREAM =
+      new PrintStream(ByteStreams.nullOutputStream());
+  private static final Console NULL_CONSOLE =
+      new Console(Verbosity.SILENT, NULL_PRINT_STREAM, NULL_PRINT_STREAM);
+
+  /** Returns a {@link Console} that simply discards written bytes. */
+  public static Console createNullConsole() {
+    return NULL_CONSOLE;
+  }
+
+  public Console(Verbosity verbosity, PrintStream stdOut, PrintStream stdErr) {
+    this.verbosity = verbosity;
+    this.stdOut = stdOut;
+    this.stdErr = stdErr;
+  }
+
+  public Verbosity getVerbosity() {
+    return verbosity;
+  }
+
+  public PrintStream getStdOut() {
+    return stdOut;
+  }
+
+  public PrintStream getStdErr() {
+    return stdErr;
+  }
+
+  /** Prints an error message to stderr. */
+  public void printErrorText(String message) {
+    LOG.warn("Build error: %s", message);
+    stdErr.println(message);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Escaper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Escaper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Escaper.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import com.facebook.buck.jvm.java.fatjar.WindowsCreateProcessEscape;
+import com.facebook.buck.util.environment.Platform;
+import com.facebook.buck.util.escaper.BashEscaper;
+import com.google.common.base.CharMatcher;
+import java.util.function.Function;
+
+public final class Escaper {
+
+  /** Utility class: do not instantiate. */
+  private Escaper() {}
+
+  /** The quoting style to use when escaping. */
+  public enum Quoter {
+    SINGLE {
+      @Override
+      public String quote(String str) {
+        return '\'' + str.replace("'", "'\\''") + '\'';
+      }
+    },
+    DOUBLE {
+      @Override
+      public String quote(String str) {
+        return '"' + str.replace("\"", "\\\"") + '"';
+      }
+    },
+    DOUBLE_WINDOWS_JAVAC {
+      @Override
+      public String quote(String str) {
+        return '"' + str.replace("\\", "\\\\") + '"';
+      }
+    },
+    ;
+
+    /**
+     * @return the string with this quoting style applied.
+     */
+    public abstract String quote(String str);
+  }
+
+  /**
+   * Escapes the special characters identified the {@link CharMatcher}, using single quotes.
+   *
+   * @param matcher identifies characters to be escaped
+   * @param str string to quote
+   * @return possibly quoted string
+   */
+  public static String escape(Quoter quoter, CharMatcher matcher, String str) {
+    if (matcher.matchesAnyOf(str) || str.isEmpty()) {
+      return quoter.quote(str);
+    } else {
+      return str;
+    }
+  }
+
+  /**
+   * @return a escaper function using the given quote style and escaping characters determined by
+   *     the given matcher.
+   */
+  public static Function<String, String> escaper(Quoter quoter, CharMatcher matcher) {
+    return input -> escape(quoter, matcher, input);
+  }
+
+  public static Function<String, String> javacEscaper() {
+    if (Platform.detect() == Platform.WINDOWS) {
+      return Escaper.escaper(
+          Quoter.DOUBLE_WINDOWS_JAVAC, CharMatcher.anyOf("#'").or(CharMatcher.whitespace()));
+    } else {
+      return Escaper.escaper(
+          Escaper.Quoter.DOUBLE, CharMatcher.anyOf("#\"'").or(CharMatcher.whitespace()));
+    }
+  }
+
+  /**
+   * Bash quoting {@link com.google.common.base.Function Function} which can be passed to {@link
+   * com.google.common.collect.Iterables#transform Iterables.transform()}.
+   */
+  public static final Function<String, String> BASH_ESCAPER = BashEscaper.BASH_ESCAPER;
+
+  /**
+   * CreateProcess (Windows) quoting {@link com.google.common.base.Function Function} which can be
+   * passed to {@link com.google.common.collect.Iterables#transform Iterables.transform()}.
+   */
+  public static final Function<String, String> CREATE_PROCESS_ESCAPER =
+      WindowsCreateProcessEscape::quote;
+
+  /**
+   * Platform-aware shell quoting {@link com.google.common.base.Function Function} which can be
+   * passed to {@link com.google.common.collect.Iterables#transform Iterables.transform()}
+   * TODO(sdwilsh): get proper cmd.EXE escaping implemented on Windows
+   */
+  public static final Function<String, String> SHELL_ESCAPER =
+      Platform.detect() == Platform.WINDOWS ? CREATE_PROCESS_ESCAPER : BASH_ESCAPER;
+
+  /**
+   * Quotes a string to be passed to the shell, if necessary. This works for the appropriate shell
+   * regardless of the platform it is run on.
+   *
+   * @param str string to escape
+   * @return possibly escaped string
+   */
+  public static String escapeAsShellString(String str) {
+    return SHELL_ESCAPER.apply(str);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ExitCode.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ExitCode.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ExitCode.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import com.fasterxml.jackson.annotation.JsonValue;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * ExitCode class defines Buck binary protocol, i.e. exit codes that Buck can report to a running
+ * shell. In addition to exit codes defined below, we have to honor following conventions.
+ *
+ * <p>Buck bootstrapper must conform to the protocol, i.e. properly implement FATAL_BOOTSTRAP
+ *
+ * <p>Exit codes for interrupts do follow POSIX convention, i.e. 128 + SIGNAL_CODE, i.e SIGINT is
+ * returned as 128 + 2 = 130
+ *
+ * <p>Exit codes 1-9 are reserved for non-fatal errors, like build errors
+ *
+ * <p>Exit codes 10-19 are reserved for fatal errors, like unexpected runtime exceptions
+ *
+ * <p>Binary protocol is open to extension but closed to modification.
+ */
+public enum ExitCode {
+  // Success 0
+
+  /** Buck command completed successfully */
+  SUCCESS(0),
+
+  // Non-fatal generic errors 1-9
+
+  /** Build resulted in user-specific error */
+  BUILD_ERROR(1),
+  /** Buck daemon is busy processing another command */
+  BUSY(2),
+  /** User supplied incorrect command line options */
+  COMMANDLINE_ERROR(3),
+  /** There is nothing to build or evaluate for the command */
+  NOTHING_TO_DO(4),
+  /** There was build file parsing or graph construction error */
+  PARSE_ERROR(5),
+  /** Running a binary or installing binary to a device has failed */
+  RUN_ERROR(6),
+
+  // Fatal errors 10-19
+
+  /** Generic Buck-internal non-recoverable error */
+  FATAL_GENERIC(10),
+  /** Non-recoverable error in Buck bootstrapper */
+  FATAL_BOOTSTRAP(11),
+  /** Non-recoverable OutOfMemory error */
+  FATAL_OOM(12),
+  /** Non-recoverable generic I/0 error */
+  FATAL_IO(13),
+  /** No space on device */
+  FATAL_DISK_FULL(14),
+
+  /** Indicates that the buck fix script returned a non-zero exit */
+  FIX_FAILED(16),
+
+  // Other non-fatal errors 20 - 127
+
+  /** Test run had user-specific test errors */
+  TEST_ERROR(32),
+  /** There was no tests found to run */
+  TEST_NOTHING(64),
+
+  // Signal processors 128+
+
+  /** Command was interrupted (Ctrl + C) */
+  SIGNAL_INTERRUPT(130);
+
+  private final int code;
+
+  ExitCode(int code) {
+    this.code = code;
+  }
+
+  /**
+   * @return integer value of the exit code
+   */
+  @JsonValue
+  public int getCode() {
+    return code;
+  }
+
+  /**
+   * @return true if error is Buck internal non-recoverable failure
+   */
+  public boolean isFatal() {
+    return code >= 10 && code < 20;
+  }
+
+  static final ImmutableMap<Integer, ExitCode> EXIT_CODE_MAPPING =
+      ImmutableMap.of(
+          0,
+          ExitCode.SUCCESS,
+          32,
+          ExitCode.TEST_ERROR,
+          42,
+          ExitCode.TEST_ERROR,
+          64,
+          ExitCode.TEST_NOTHING,
+          70,
+          ExitCode.TEST_ERROR);
+
+  /**
+   * Map integer value received from custom toolchain subcall to one of appropriate ExitCode values.
+   * This function is for backwards compatibility only, please construct ExitCode directly instead
+   */
+  public static ExitCode map(int code) {
+    return EXIT_CODE_MAPPING.getOrDefault(code, ExitCode.BUILD_ERROR);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Memoizer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Memoizer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Memoizer.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import com.facebook.buck.util.function.ThrowingSupplier;
+import java.util.function.Supplier;
+
+/**
+ * Memoizes a value, supporting passing in a supplier when getting the value, unlike {@link
+ * MoreSuppliers.MemoizingSupplier}.
+ */
+public class Memoizer<T> extends AbstractMemoizer<T, RuntimeException> {
+
+  public T get(Supplier<T> delegate) {
+    return get(ThrowingSupplier.fromSupplier(delegate), RuntimeException.class);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/MoreSuppliers.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/MoreSuppliers.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/MoreSuppliers.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+import java.io.IOException;
+import java.util.Objects;
+import java.util.function.Supplier;
+
+public final class MoreSuppliers {
+  private MoreSuppliers() {}
+
+  /**
+   * Returns a supplier which caches the instance retrieved during the first call to {@code get()}
+   * and returns that value on subsequent calls to {@code get()}.
+   *
+   * <p>Unlike Guava's {@link
+   * com.google.common.base.Suppliers#memoize(com.google.common.base.Supplier)}, this version
+   * removes the reference to the underlying Supplier once the value is computed. This frees up
+   * memory used in lambda captures, at the cost of causing the supplier to be not Serializable.
+   */
+  public static <T> Supplier<T> memoize(Supplier<T> delegate) {
+    return (delegate instanceof MemoizingSupplier) ? delegate : new MemoizingSupplier<T>(delegate);
+  }
+
+  @JsonSerialize(using = MemoizingSupplierSerializer.class)
+  private static class MemoizingSupplier<T> extends Memoizer<T> implements Supplier<T> {
+    private final Supplier<T> delegate;
+
+    public MemoizingSupplier(Supplier<T> delegate) {
+      this.delegate = Objects.requireNonNull(delegate);
+    }
+
+    @Override
+    public T get() {
+      return get(delegate);
+    }
+  }
+
+  /**
+   * Custom serializer for Jackson because buck deserializer creates {@link
+   * com.google.common.base.Suppliers}.NonSerializableMemoizingSupplier from MemoizingSupplier and
+   * it's useful in tests to have both serialized into the same thing with Jackson.
+   */
+  static class MemoizingSupplierSerializer<T> extends StdSerializer<MemoizingSupplier<T>> {
+
+    @SuppressWarnings("unchecked")
+    public MemoizingSupplierSerializer() {
+      super((Class<MemoizingSupplier<T>>) (Class<?>) MemoizingSupplier.class);
+    }
+
+    @Override
+    public void serialize(
+        MemoizingSupplier<T> value, JsonGenerator gen, SerializerProvider provider)
+        throws IOException {
+      gen.writeStartObject();
+      gen.writeObjectField("instance", value.get());
+      gen.writeEndObject();
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/NamedTemporaryFile.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/NamedTemporaryFile.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/NamedTemporaryFile.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import com.facebook.buck.core.util.log.Logger;
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.FileAttribute;
+import java.util.function.Supplier;
+
+/** Creates a temporary file that is deleted when this object is closed. */
+public class NamedTemporaryFile implements Closeable, Supplier<Path> {
+  private static final Logger LOG = Logger.get(NamedTemporaryFile.class);
+
+  private final Path tempPath;
+
+  public NamedTemporaryFile(String prefix, String suffix, FileAttribute<?>... attrs)
+      throws IOException {
+    tempPath = Files.createTempFile(prefix, suffix, attrs);
+  }
+
+  @Override
+  public Path get() {
+    return tempPath;
+  }
+
+  @Override
+  public synchronized void close() {
+    if (Files.exists(tempPath)) {
+      try {
+        Files.delete(tempPath);
+      } catch (IOException e) {
+        LOG.warn(e, "Cannot delete time file: %s", tempPath);
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/PatternsMatcher.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/PatternsMatcher.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/PatternsMatcher.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import com.google.common.collect.ImmutableCollection;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Maps;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Helper class that keeps a list of compiled patterns and provides a method to check whether a
+ * string matches at least one of them.
+ */
+public class PatternsMatcher {
+
+  /** A pattern which patches any string */
+  public static final PatternsMatcher ANY = new PatternsMatcher(ImmutableSet.of(), true);
+
+  /** A pattern which matches no string */
+  public static final PatternsMatcher NONE = new PatternsMatcher(ImmutableSet.of(), false);
+
+  private final ImmutableSet<Pattern> patterns;
+
+  /** True is like having a pattern {@code .*} in the pattern set */
+  private final boolean matchesAny;
+
+  private PatternsMatcher(ImmutableSet<Pattern> patterns, boolean matchesAny) {
+    this.patterns = patterns;
+    this.matchesAny = matchesAny;
+  }
+
+  public PatternsMatcher(ImmutableCollection<String> rawPatterns) {
+    this(rawPatterns.stream().map(Pattern::compile).collect(ImmutableSet.toImmutableSet()), false);
+  }
+
+  public PatternsMatcher(ImmutableSet<Pattern> compiledPatterns) {
+    this(compiledPatterns, false);
+  }
+
+  /**
+   * @return true if the given string matches some of the patterns
+   */
+  public boolean matches(String string) {
+    return match(string, true);
+  }
+
+  /**
+   * @return true if a substring of the given string matches some of the patterns or there are no
+   *     patterns
+   */
+  public boolean substringMatches(String string) {
+    return match(string, false);
+  }
+
+  private boolean match(String string, boolean fullMatch) {
+    if (matchesAny) {
+      return true;
+    }
+    for (Pattern pattern : patterns) {
+      Matcher matcher = pattern.matcher(string);
+      if (fullMatch ? matcher.matches() : matcher.find()) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  /**
+   * @return true if this pattern matches any string
+   */
+  public boolean isMatchesAny() {
+    return matchesAny;
+  }
+
+  /**
+   * @return true if no string matches this pattern
+   */
+  public boolean isMatchesNone() {
+    return !matchesAny && patterns.isEmpty();
+  }
+
+  /**
+   * @return a view of the given map where all non-matching keys are removed.
+   */
+  public <V> Map<String, V> filterMatchingMapKeys(Map<String, V> entries) {
+    if (matchesAny) {
+      return entries;
+    }
+
+    return Maps.filterEntries(entries, entry -> matches(entry.getKey()));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Threads.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Threads.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Threads.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import com.facebook.buck.core.util.log.Logger;
+import com.google.common.base.Throwables;
+
+public class Threads {
+
+  private static final Logger LOG = Logger.get(Threads.class);
+
+  /** Utility class: do not instantiate. */
+  private Threads() {}
+
+  public static Thread namedThread(String name, Runnable runnable) {
+    Thread newThread = new Thread(runnable);
+    newThread.setName(name);
+    return newThread;
+  }
+
+  public static void interruptCurrentThread() {
+    LOG.warn(
+        "Current thread interrupted at this location: "
+            + Throwables.getStackTraceAsString(new Throwable()));
+    Thread.currentThread().interrupt();
+  }
+
+  public static void interruptThread(Thread thread) {
+    LOG.warn(
+        "Thread interrupted at this location: "
+            + Throwables.getStackTraceAsString(new Throwable()));
+    thread.interrupt();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ThrowingPrintWriter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ThrowingPrintWriter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ThrowingPrintWriter.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.nio.charset.Charset;
+
+/**
+ * A (partial) replacement for {@link java.io.PrintWriter} with methods that throw {@link
+ * IOException}. {@link java.io.PrintWriter} explicitly does not throw, and that can catch people
+ * off guard.
+ *
+ * <p>Only the methods that were in use in Buck at the time this class was written have been
+ * implemented (including primitive overloads to prevent accidental inefficiencies later). Feel free
+ * to add more methods, but please don't go beyond what {@link java.io.PrintWriter} itself has.
+ */
+public class ThrowingPrintWriter extends OutputStreamWriter {
+  public ThrowingPrintWriter(OutputStream out) {
+    super(out);
+  }
+
+  public ThrowingPrintWriter(OutputStream out, Charset cs) {
+    super(out, cs);
+  }
+
+  public ThrowingPrintWriter printf(String format, Object... args) throws IOException {
+    return format(format, args);
+  }
+
+  public ThrowingPrintWriter format(String format, Object... args) throws IOException {
+    write(String.format(format, args));
+
+    return this;
+  }
+
+  public void println(boolean b) throws IOException {
+    println(Boolean.toString(b));
+  }
+
+  public void println(char c) throws IOException {
+    println(Character.toString(c));
+  }
+
+  public void println(int i) throws IOException {
+    println(Integer.toString(i));
+  }
+
+  public void println(long l) throws IOException {
+    println(Long.toString(l));
+  }
+
+  public void println(float f) throws IOException {
+    println(Float.toString(f));
+  }
+
+  public void println(double d) throws IOException {
+    println(Double.toString(d));
+  }
+
+  public void println(char[] x) throws IOException {
+    write(x);
+    println();
+  }
+
+  public void println(Object o) throws IOException {
+    println(String.valueOf(o));
+  }
+
+  public void println(String str) throws IOException {
+    write(str);
+    println();
+  }
+
+  public void println() throws IOException {
+    write(System.lineSeparator());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Verbosity.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Verbosity.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/Verbosity.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+/**
+ * An indication of how verbose Buck should be. Enum values are in order from least to most verbose.
+ */
+public enum Verbosity {
+  // TODO(mbolin): Consider introducing more Verbosity levels that affect the Java Logger
+  // setting.
+
+  /** Do not print anything to the console. */
+  SILENT(0),
+
+  /** Prints out the bare minimum required information, such as errors from build steps. */
+  STANDARD_INFORMATION(1),
+
+  /** Print extra output from generated binaries and tests being run, but nothing else. */
+  BINARY_OUTPUTS(2),
+
+  /** Print the command being executed, but do not print its output. */
+  COMMANDS(3),
+
+  /** Commands plus the output from some select commands of interest. */
+  COMMANDS_AND_SPECIAL_OUTPUT(4),
+
+  /** Print the command being executed followed by its output. */
+  COMMANDS_AND_OUTPUT(5),
+
+  /**
+   * If the command being executed has its own {@code --verbose} option or equivalent, it should be
+   * used.
+   */
+  ALL(100),
+  ;
+
+  private final int level;
+
+  Verbosity(int level) {
+    this.level = level;
+  }
+
+  public boolean isSilent() {
+    return level <= SILENT.level;
+  }
+
+  public boolean shouldPrintStandardInformation() {
+    return level >= STANDARD_INFORMATION.level;
+  }
+
+  public boolean shouldPrintBinaryRunInformation() {
+    return level >= BINARY_OUTPUTS.level;
+  }
+
+  public boolean shouldPrintCommand() {
+    return level >= COMMANDS.level;
+  }
+
+  public boolean shouldPrintSelectCommandOutput() {
+    return level >= COMMANDS_AND_SPECIAL_OUTPUT.level;
+  }
+
+  public boolean shouldPrintOutput() {
+    return level >= COMMANDS_AND_OUTPUT.level;
+  }
+
+  /**
+   * @return {@code true} if the command being executed should use its own {@code --verbose}
+   *     argument (or equivalent) for this Verbosity level
+   */
+  public boolean shouldUseVerbosityFlagIfAvailable() {
+    return this == ALL;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ZipFileTraversal.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ZipFileTraversal.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/ZipFileTraversal.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Enumeration;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+public abstract class ZipFileTraversal {
+  private final Path file;
+
+  public ZipFileTraversal(Path file) {
+    this.file = file;
+  }
+
+  public abstract void visit(ZipFile zipFile, ZipEntry zipEntry) throws IOException;
+
+  public final void traverse() throws IOException {
+    try (ZipFile zipFile = new ZipFile(file.toFile())) {
+      Enumeration<? extends ZipEntry> entries = zipFile.entries();
+      while (entries.hasMoreElements()) {
+        ZipEntry entry = entries.nextElement();
+        visit(zipFile, entry);
+      }
+    } catch (IllegalArgumentException e) { // help debugging a "MALFORMED" error
+      throw new IllegalArgumentException("zipfile traverse exception on file:" + file, e);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/BUCK
@@ -0,0 +1,50 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+PLATFORM_SRCS = [
+    "Platform.java",
+    "PlatformType.java",
+]
+
+buck_java_library(
+    name = "platform",
+    srcs = PLATFORM_SRCS,
+    # This target is pulled in by testrunner, which needs to compile against Java 8.
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = [
+        "PUBLIC",
+    ],
+    # This library is deep in the dependency tree, keep its dependency list small.
+    deps = [],
+)
+
+buck_java_library(
+    name = "environment",
+    srcs = glob(
+        ["*.java"],
+        exclude = PLATFORM_SRCS,
+    ),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/util/environment:environment",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/util:process_executor",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jackson-annotations",
+        "prelude//toolchains/android/third-party:jackson-databind",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/EnvVariablesProvider.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/EnvVariablesProvider.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/EnvVariablesProvider.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.environment;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+import java.util.Objects;
+
+/** Provides access system environment variables of the current process. */
+public class EnvVariablesProvider {
+
+  @SuppressWarnings("PMD.BlacklistedSystemGetenv")
+  public static ImmutableMap<String, String> getSystemEnv() {
+    if (Platform.detect().getType() == PlatformType.WINDOWS) {
+      return System.getenv().entrySet().stream()
+          .collect(ImmutableMap.toImmutableMap(e -> e.getKey().toUpperCase(), Map.Entry::getValue));
+    } else {
+      return ImmutableMap.copyOf(System.getenv());
+    }
+  }
+
+  public static String getRequiredEnvVar(String key) {
+    return Objects.requireNonNull(
+        getSystemEnv().get(key), String.format("%S must be set in environment", key));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/Platform.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/Platform.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/Platform.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.environment;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Properties;
+
+/**
+ * Platform on which Buck is currently running. Limited to the OS kind, e.g. Windows or a kind of
+ * Unix (MACOS, LINUX, ...).
+ */
+public enum Platform {
+  LINUX("Linux", "linux", "linux", PlatformType.UNIX),
+  MACOS("Mac OS X", "darwin", "osx", PlatformType.UNIX),
+  WINDOWS("Windows", "windows", "windows", PlatformType.WINDOWS),
+  FREEBSD("FreeBSD", "freebsd", "freebsd", PlatformType.UNIX),
+  UNKNOWN("Unknown", "unknown", "unknown", PlatformType.UNKNOWN);
+
+  private final String autoconfName;
+  private final String canonicalName;
+  private final String platformName;
+  private final PlatformType platformType;
+
+  Platform(
+      String platformName, String autoconfName, String canonicalName, PlatformType platformType) {
+    this.platformName = platformName;
+    this.autoconfName = autoconfName;
+    this.canonicalName = canonicalName;
+    this.platformType = platformType;
+  }
+
+  /**
+   * @return platform name as used in autoconf target tuples
+   */
+  public String getAutoconfName() {
+    return autoconfName;
+  }
+
+  public PlatformType getType() {
+    return platformType;
+  }
+
+  public String getCanonicalName() {
+    return canonicalName;
+  }
+
+  /**
+   * Return a path to a special file which accepts reads (always returning EOF) and writes (accepts
+   * and immediately discards written data). E.g {@code /dev/null} on Unix and {@code NUL} on
+   * Windows.
+   */
+  public Path getNullDevicePath() {
+    if (getType().isUnix()) {
+      // This should be a valid path on any Unix/POSIX-conforming system.
+      // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap10.html
+      return Paths.get("/dev/null");
+    } else if (getType().isWindows()) {
+      // MS docs on special filenames.  The file named `NUL` or even `NUL.ext` is a blackhole.
+      // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
+      return Paths.get("NUL");
+    }
+    throw new IllegalStateException(
+        "don't know null special file for OS: " + System.getProperty("os.name"));
+  }
+
+  private static final Platform HOST_PLATFORM = detect(System.getProperties());
+
+  private static Platform detect(Properties properties) {
+    String platformName = properties.getProperty("os.name");
+    if (platformName == null) {
+      return UNKNOWN;
+    }
+
+    for (Platform platform : values()) {
+      if (platformName.startsWith(platform.platformName)) {
+        return platform;
+      }
+    }
+    return UNKNOWN;
+  }
+
+  public static Platform detect() {
+    return HOST_PLATFORM;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/PlatformType.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/PlatformType.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/environment/PlatformType.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.environment;
+
+/**
+ * The type of the {@link Platform}, in only a very general sense: Windows, Unix, etc.
+ *
+ * <p>See boolean functions like {@link #isUnix()}, {@link #isWindows()}, ... for slightly easier
+ * syntax: {@code if (Platform.detect().getType().isUnix()) ...}
+ */
+public enum PlatformType {
+  UNKNOWN,
+  UNIX,
+  WINDOWS,
+  ;
+
+  /**
+   * Whether this is {@link PlatformType#UNIX}. Makes for slightly easier syntax: {@code if
+   * (Platform.detect().getType().isUnix()) { ... } }
+   */
+  public boolean isUnix() {
+    return this == UNIX;
+  }
+
+  public boolean isWindows() {
+    return this == WINDOWS;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/BUCK
@@ -0,0 +1,46 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "quoter",
+    srcs = ["Quoter.java"],
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = ["PUBLIC"],
+    deps = [],
+)
+
+buck_java_library(
+    name = "utils",
+    srcs = ["EscaperUtils.java"],
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+        ":quoter",
+    ],
+)
+
+buck_java_library(
+    name = "bash",
+    srcs = ["BashEscaper.java"],
+    # @oss-disable[end= ]: source = "8",
+    # @oss-disable[end= ]: target = "8",
+    source = "11", # @oss-enable
+    target = "11", # @oss-enable
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+        ":quoter",
+        ":utils",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/BashEscaper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/BashEscaper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/BashEscaper.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.escaper;
+
+import com.google.common.base.CharMatcher;
+import java.util.function.Function;
+
+/** Utils for escaping bash */
+public class BashEscaper {
+  public static final CharMatcher BASH_SPECIAL_CHARS =
+      CharMatcher.anyOf("<>|!?*[]$\\(){}\"'`&;=").or(CharMatcher.whitespace());
+
+  public static final Function<String, String> BASH_ESCAPER =
+      EscaperUtils.escaper(Quoter.SINGLE, BASH_SPECIAL_CHARS);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/EscaperUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/EscaperUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/EscaperUtils.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.escaper;
+
+import com.google.common.base.CharMatcher;
+import java.util.function.Function;
+
+/** Utility functions used for escaping */
+public class EscaperUtils {
+  /**
+   * Escapes the special characters identified the {@link CharMatcher}, using single quotes.
+   *
+   * @param matcher identifies characters to be escaped
+   * @param str string to quote
+   * @return possibly quoted string
+   */
+  public static String escape(Quoter quoter, CharMatcher matcher, String str) {
+    if (matcher.matchesAnyOf(str) || str.isEmpty()) {
+      return quoter.quote(str);
+    } else {
+      return str;
+    }
+  }
+
+  /**
+   * @return a escaper function using the given quote style and escaping characters determined by
+   *     the given matcher.
+   */
+  public static Function<String, String> escaper(Quoter quoter, CharMatcher matcher) {
+    return input -> escape(quoter, matcher, input);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/Quoter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/Quoter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/escaper/Quoter.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.escaper;
+
+import java.util.Collections;
+
+/** The quoting style to use when escaping. */
+public enum Quoter {
+  SINGLE {
+    @Override
+    public String quote(String str) {
+      return '\'' + str.replace("'", "'\\''") + '\'';
+    }
+  },
+  DOUBLE {
+    @Override
+    public String quote(String str) {
+      return '"' + str.replace("\"", "\\\"") + '"';
+    }
+  },
+  DOUBLE_WINDOWS_JAVAC {
+    @Override
+    public String quote(String str) {
+      return '"' + str.replace("\\", "\\\\") + '"';
+    }
+  },
+  DOUBLE_WINDOWS_ARGFILE {
+    @Override
+    public String quote(String str) {
+      // Implementation of proper Windows quoting from:
+      // https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way
+      StringBuilder builder = new StringBuilder();
+      builder.append('"');
+      for (int i = 0; ; ++i) {
+        int numBackslashes = 0;
+        while (i < str.length() && str.charAt(i) == '\\') {
+          ++i;
+          ++numBackslashes;
+        }
+
+        if (i == str.length()) {
+          builder.append(String.join("", Collections.nCopies(2 * numBackslashes, "\\")));
+          break;
+        }
+
+        char ch = str.charAt(i);
+        if (ch == '"') {
+          builder.append(String.join("", Collections.nCopies(2 * numBackslashes + 1, "\\")));
+          builder.append(ch);
+        } else {
+          builder.append(String.join("", Collections.nCopies(numBackslashes, "\\")));
+          builder.append(ch);
+        }
+      }
+      builder.append('"');
+      return builder.toString();
+    }
+  };
+
+  /**
+   * @return the string with this quoting style applied.
+   */
+  public abstract String quote(String str);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/function/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/function/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/function/BUCK
@@ -0,0 +1,15 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "function",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/function/ThrowingSupplier.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/function/ThrowingSupplier.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/function/ThrowingSupplier.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.function;
+
+import com.google.common.base.Throwables;
+import java.util.function.Supplier;
+
+/** This version of {@code Supplier<T>} can throw an exception. */
+@FunctionalInterface
+public interface ThrowingSupplier<T, E extends Exception> {
+  T get() throws E;
+
+  /** Returns a Supplier that will wrap any thrown exception in a RuntimeException. */
+  default Supplier<T> asSupplier() {
+    return () -> {
+      try {
+        return get();
+      } catch (Exception e) {
+        Throwables.throwIfUnchecked(e);
+        throw new RuntimeException(e);
+      }
+    };
+  }
+
+  /** Returns a {@link ThrowingSupplier} from a {@link Supplier} */
+  static <T, E extends Exception> ThrowingSupplier<T, E> fromSupplier(Supplier<T> supplier) {
+    return () -> supplier.get();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/io/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/io/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/io/BUCK
@@ -0,0 +1,13 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "io",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/io/IoUtil.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/io/IoUtil.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/io/IoUtil.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.io;
+
+import java.io.Closeable;
+import java.io.IOException;
+
+/** IO utilities. */
+public class IoUtil {
+  /** Like {@link java.util.function.Function} but allows throwing {@link IOException}. */
+  public interface IoFunction<A, B> {
+    /** Apply the function. */
+    B apply(A a) throws IOException;
+  }
+
+  /** Apply a function to just opened output stream; close the stream if function fails. */
+  public static <I extends Closeable, R> R mapJustOpened(I justOpened, IoFunction<I, R> f)
+      throws IOException {
+    try {
+      return f.apply(justOpened);
+    } catch (Throwable e) {
+      try {
+        justOpened.close();
+      } catch (Throwable ignore) {
+        // ignore
+      }
+      // original exception is more important, and generally close should not throw
+      throw e;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/json/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/json/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/json/BUCK
@@ -0,0 +1,31 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "json",
+    srcs = glob(["*.java"]),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/util/json:json",
+    ],
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/third-party:jackson-datatype-guava",
+        "prelude//toolchains/android/third-party:jackson-datatype-jdk8",
+        "prelude//toolchains/android/third-party:jackson-module-kotlin",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/third-party:jackson-annotations",
+        "prelude//toolchains/android/third-party:jackson-databind",
+        "prelude//toolchains/android/third-party:kotlin-reflect",
+        "prelude//toolchains/android/third-party:kotlin-stdlib",
+        "prelude//toolchains/android/third-party:protobuf",
+        "prelude//toolchains/android/third-party:protobuf-util",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/json/ObjectMappers.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/json/ObjectMappers.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/json/ObjectMappers.java
@@ -0,0 +1,291 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.json;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.filesystems.RelPath;
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.core.type.WritableTypeId;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.KeyDeserializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectReader;
+import com.fasterxml.jackson.databind.ObjectWriter;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.deser.std.FromStringDeserializer;
+import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
+import com.fasterxml.jackson.datatype.guava.GuavaModule;
+import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
+import com.fasterxml.jackson.module.kotlin.KotlinModule;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public class ObjectMappers {
+
+  // It's important to re-use these objects for perf:
+  // https://github.com/FasterXML/jackson-docs/wiki/Presentation:-Jackson-Performance
+  public static final ObjectReader READER;
+  public static final ObjectWriter WRITER;
+
+  /** ObjectReader that deserializes objects that had type information preserved */
+  public static final ObjectReader READER_WITH_TYPE;
+
+  /** ObjectWrite that serializes objects along with their type information */
+  public static final ObjectWriter WRITER_WITH_TYPE;
+
+  /** ObjectReader that interns custom objects on serialization, like UnconfiguredBuildTarget */
+  public static final ObjectReader READER_INTERNED;
+
+  public static <T> T readValue(Path file, Class<T> clazz) throws IOException {
+    try (JsonParser parser = createParser(file)) {
+      return READER.readValue(parser, clazz);
+    }
+  }
+
+  public static <T> T readValue(Path file, TypeReference<T> clazz) throws IOException {
+    try (JsonParser parser = createParser(file)) {
+      return READER.readValue(parser, clazz);
+    }
+  }
+
+  public static <T> T readValue(String json, Class<T> clazz) throws IOException {
+    try (JsonParser parser = createParser(json)) {
+      return READER.readValue(parser, clazz);
+    }
+  }
+
+  public static <T> T readValue(String json, TypeReference<T> clazz) throws IOException {
+    try (JsonParser parser = createParser(json)) {
+      return READER.readValue(parser, clazz);
+    }
+  }
+
+  public static JsonParser createParser(Path path) throws IOException {
+    return jsonFactory.createParser(new BufferedInputStream(Files.newInputStream(path)));
+  }
+
+  public static JsonParser createParser(String json) throws IOException {
+    return jsonFactory.createParser(json);
+  }
+
+  public static JsonParser createParser(byte[] json) throws IOException {
+    return jsonFactory.createParser(json);
+  }
+
+  public static JsonParser createParser(InputStream stream) throws IOException {
+    return jsonFactory.createParser(stream);
+  }
+
+  public static JsonParser createParser(Reader reader) throws IOException {
+    return jsonFactory.createParser(reader);
+  }
+
+  public static JsonGenerator createGenerator(OutputStream stream) throws IOException {
+    return jsonFactory.createGenerator(stream);
+  }
+
+  public static <T> T convertValue(Map<String, Object> map, Class<T> clazz) {
+    return mapper.convertValue(map, clazz);
+  }
+
+  public static <T> Function<T, String> toJsonFunction() {
+    return input -> {
+      try {
+        return WRITER.writeValueAsString(input);
+      } catch (JsonProcessingException e) {
+        throw new RuntimeException("Failed to serialize to json: " + input, e);
+      }
+    };
+  }
+
+  public static <T> Function<String, T> fromJsonFunction(Class<T> type) {
+    return input -> {
+      try {
+        return readValue(input, type);
+      } catch (IOException e) {
+        throw new RuntimeException("Failed to read from json: " + input, e);
+      }
+    };
+  }
+
+  // This is mutable, and doesn't share a cache with the rest of Buck.
+  // All uses of it should be removed.
+  // Any new code should instead use READER or WRITER.
+  public static ObjectMapper legacyCreate() {
+    return create();
+  }
+
+  /**
+   * Creates an {@link ObjectMapper} that allows to use objects without fields.
+   *
+   * @see SerializationFeature#FAIL_ON_EMPTY_BEANS
+   */
+  public static ObjectMapper createWithEmptyBeansPermitted() {
+    ObjectMapper objectMapper = create();
+    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+    return objectMapper;
+  }
+
+  // Callers must not modify (i.e. reconfigure) this ObjectMapper.
+  private static final ObjectMapper mapper;
+  private static final ObjectMapper mapper_interned;
+
+  // Callers must not modify (i.e. reconfigure) this JsonFactory.
+  private static final JsonFactory jsonFactory;
+
+  static {
+    mapper = create_without_type();
+    mapper_interned = create_without_type_interned();
+    READER = mapper.reader();
+    READER_INTERNED = mapper_interned.reader();
+    WRITER = mapper.writer();
+    jsonFactory = mapper.getFactory();
+    ObjectMapper mapper_with_type = create_with_type();
+    READER_WITH_TYPE = mapper_with_type.reader();
+    WRITER_WITH_TYPE = mapper_with_type.writer();
+  }
+
+  private static ObjectMapper create() {
+    ObjectMapper mapper = new ObjectMapper();
+    // Disable automatic flush() after mapper.write() call, because it is usually unnecessary,
+    // and it makes BufferedOutputStreams to be useless
+    mapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
+    mapper.setSerializationInclusion(Include.NON_ABSENT);
+    mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
+    // Add support for serializing Guava collections.
+    mapper.registerModule(new GuavaModule());
+    mapper.registerModule(new Jdk8Module());
+    mapper.registerModule(new KotlinModule.Builder().build());
+
+    // With some version of Jackson JDK8 module, it starts to serialize Path objects using
+    // getURI() function, this results for serialized paths to be absolute paths with 'file:///'
+    // prefix. That does not work well with custom filesystems that Buck uses. Following hack
+    // restores legacy behavior to serialize Paths using toString().
+    SimpleModule pathModule = new SimpleModule("PathToString");
+
+    /**
+     * Custom Path serializer that serializes using {@link Object#toString()} method and also
+     * translates all {@link Path} implementations to use generic base type
+     */
+    class PathSerializer<P> extends ToStringSerializer {
+      private final Class<P> clazz;
+
+      public PathSerializer(Class<P> clazz) {
+        super(clazz);
+        this.clazz = clazz;
+      }
+
+      @Override
+      public void serializeWithType(
+          Object value, JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer)
+          throws IOException {
+        WritableTypeId typeIdDef =
+            typeSer.writeTypePrefix(g, typeSer.typeId(value, clazz, JsonToken.VALUE_STRING));
+        serialize(value, g, provider);
+        typeSer.writeTypeSuffix(g, typeIdDef);
+      }
+    }
+
+    pathModule.addSerializer(Path.class, new PathSerializer<>(Path.class));
+    pathModule.addSerializer(AbsPath.class, new PathSerializer<>(AbsPath.class));
+    pathModule.addSerializer(RelPath.class, new PathSerializer<>(RelPath.class));
+
+    /** Deserializer for Path-like objects. */
+    class PathDeserializer<P> extends FromStringDeserializer<P> {
+
+      private final Function<String, P> get;
+      private final Supplier<P> empty;
+
+      public PathDeserializer(Class<P> clazz, Function<String, P> get, Supplier<P> empty) {
+        super(clazz);
+        this.get = get;
+        this.empty = empty;
+      }
+
+      @Override
+      protected P _deserialize(String value, DeserializationContext ctxt) {
+        return get.apply(value);
+      }
+
+      @Override
+      protected P _deserializeFromEmptyString(DeserializationContext ctxt) {
+        // by default it returns null but we want empty Path
+        return getEmptyValue(ctxt);
+      }
+
+      @Override
+      public P getEmptyValue(DeserializationContext ctxt) {
+        return empty.get();
+      }
+    }
+
+    /** Class to deserialize {@link Path} when it's present as a key in a map. */
+    class PathKeyDeserializer extends KeyDeserializer {
+
+      @Override
+      public Path deserializeKey(String key, DeserializationContext context) {
+        return Paths.get(key);
+      }
+    }
+
+    pathModule.addDeserializer(
+        Path.class, new PathDeserializer<>(Path.class, Paths::get, () -> Paths.get("")));
+    pathModule.addKeyDeserializer(Path.class, new PathKeyDeserializer());
+    pathModule.addDeserializer(
+        AbsPath.class, new PathDeserializer<>(AbsPath.class, AbsPath::get, () -> AbsPath.get("")));
+    pathModule.addDeserializer(
+        RelPath.class, new PathDeserializer<>(RelPath.class, RelPath::get, () -> RelPath.get("")));
+    mapper.registerModule(pathModule);
+
+    return mapper;
+  }
+
+  private static ObjectMapper create_without_type() {
+    ObjectMapper mapper = create();
+    return addCustomModules(mapper, false);
+  }
+
+  private static ObjectMapper create_without_type_interned() {
+    ObjectMapper mapper = create();
+    return addCustomModules(mapper, true);
+  }
+
+  private static ObjectMapper addCustomModules(ObjectMapper mapper, boolean intern) {
+    SimpleModule buildTargetModule = new SimpleModule("BuildTarget");
+    mapper.registerModule(buildTargetModule);
+    return mapper;
+  }
+
+  private static ObjectMapper create_with_type() {
+    ObjectMapper objectMapper = create();
+    return objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator());
+  }
+
+  private ObjectMappers() {}
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/BUCK
@@ -0,0 +1,25 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+# Includes stripped-down versions of types that Infer recognizes, so that we can use Infer on
+# code that must be very light on dependencies.
+buck_java_library(
+    name = "liteinfersupport",
+    srcs = glob(["*.java"]),
+    required_for_source_only_abi = True,
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source:source",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/source/api:api",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/fatjar:fat-jar-main",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/lang/model:model",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/adapter:adapter",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/plugin/api:api",
+    ],
+    deps = [
+        # This module is intended for use in dependency-constrained environments. Don't take deps.
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/Nullable.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/Nullable.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/Nullable.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.liteinfersupport;
+
+/**
+ * Some projects like FatJar is going to be embedded in many targets, it cannot have external
+ * dependencies, but we'd like to have {@link javax.annotation.Nullable} and {@link
+ * com.google.common.base.Preconditions#checkNotNull} anyway, so we define these here.
+ */
+public @interface Nullable {}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/PropagatesNullable.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/PropagatesNullable.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/liteinfersupport/PropagatesNullable.java
@@ -0,0 +1,13 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.liteinfersupport;
+
+public @interface PropagatesNullable {}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/BUCK
@@ -0,0 +1,20 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "nio",
+    srcs = glob(["*.java"]),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/util/nio:nio",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/version/utils:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/ByteBufferUnmapper.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/ByteBufferUnmapper.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/ByteBufferUnmapper.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.nio;
+
+import com.facebook.buck.jvm.java.version.utils.JavaVersionUtils;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.nio.ByteBuffer;
+
+/** Class to unmap ByteBuffer on any Java version. Supports try with resources. */
+public class ByteBufferUnmapper {
+  private static final Unmapper unmapper =
+      JavaVersionUtils.getMajorVersion() < 9 ? new UnmapperBeforeJava9() : new UnmapperAfterJava9();
+
+  private ByteBufferUnmapper() {}
+
+  /** Static method to unmap a ByteBuffer. */
+  public static void unmap(ByteBuffer buffer) {
+    if (!buffer.isDirect()) {
+      return;
+    }
+    try {
+      unmapper.unmap(buffer);
+    } catch (Exception e) {
+      throw new Error(e);
+    }
+  }
+
+  private interface Unmapper {
+    void unmap(ByteBuffer buffer) throws Exception;
+  }
+
+  private static class UnmapperAfterJava9 implements Unmapper {
+    private static final Object unsafe;
+    private static final Method invokeCleaner;
+
+    static {
+      try {
+        Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
+        Field unsafeField = unsafeClass.getDeclaredField("theUnsafe");
+        unsafeField.setAccessible(true);
+        unsafe = unsafeField.get(null);
+        invokeCleaner = unsafeClass.getMethod("invokeCleaner", ByteBuffer.class);
+      } catch (Exception e) {
+        throw new Error(e);
+      }
+    }
+
+    @Override
+    public void unmap(ByteBuffer buffer) throws Exception {
+      invokeCleaner.invoke(unsafe, buffer);
+    }
+  }
+
+  private static class UnmapperBeforeJava9 implements Unmapper {
+    private static final Method clean;
+
+    static {
+      try {
+        clean = Class.forName("sun.misc.Cleaner").getMethod("clean");
+        clean.setAccessible(true);
+      } catch (Exception e) {
+        throw new Error(e);
+      }
+    }
+
+    @Override
+    public void unmap(ByteBuffer buffer) throws Exception {
+      Method cleaner = buffer.getClass().getMethod("cleaner");
+      cleaner.setAccessible(true);
+      clean.invoke(cleaner.invoke(buffer));
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/LargeByteBuffer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/LargeByteBuffer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/LargeByteBuffer.java
@@ -0,0 +1,332 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.nio;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+
+/** Provides a ByteBuffer-like object for dealing with very large files. */
+public class LargeByteBuffer {
+  public static LargeByteBuffer with(MappableByteBufferHolder byteBufferHolder) throws IOException {
+    return new LargeByteBuffer(byteBufferHolder);
+  }
+
+  public static LargeByteBuffer withBytes(byte[] bytes) throws IOException {
+    return withByteBuffer(ByteBuffer.wrap(bytes));
+  }
+
+  public static LargeByteBuffer withByteBuffer(ByteBuffer buffer) throws IOException {
+    return withByteBuffer(buffer, Integer.MAX_VALUE);
+  }
+
+  public static LargeByteBuffer withByteBuffer(ByteBuffer buffer, int maxBufferSize)
+      throws IOException {
+    return new LargeByteBuffer(
+        new MappableByteBufferHolder(buffer.limit(), maxBufferSize) {
+          @Override
+          protected ByteBuffer map(long start, int length) throws IOException {
+            assert start > 0;
+            assert length > 0;
+            assert start + length <= buffer.limit();
+
+            return buffer.position((int) start).slice().limit(length);
+          }
+        });
+  }
+
+  public static Scoped withFileChannel(FileChannel fileChannel) throws IOException {
+    return withFileChannel(fileChannel, Integer.MAX_VALUE);
+  }
+
+  public static Scoped withFileChannel(FileChannel fileChannel, int maxBufferSize)
+      throws IOException {
+    return withFileChannel(fileChannel, maxBufferSize, FileChannel.MapMode.READ_WRITE);
+  }
+
+  public static Scoped withReadOnlyFileChannel(FileChannel fileChannel) throws IOException {
+    return withReadOnlyFileChannel(fileChannel, Integer.MAX_VALUE);
+  }
+
+  public static Scoped withReadOnlyFileChannel(FileChannel fileChannel, int maxBufferSize)
+      throws IOException {
+    return withFileChannel(fileChannel, maxBufferSize, FileChannel.MapMode.READ_ONLY);
+  }
+
+  private static Scoped withFileChannel(
+      FileChannel fileChannel, int maxBufferSize, FileChannel.MapMode mode) throws IOException {
+    return new Scoped(
+        new MappableByteBufferHolder(fileChannel.size(), maxBufferSize) {
+          @Override
+          protected ByteBuffer map(long start, int length) throws IOException {
+            return fileChannel.map(mode, start, length);
+          }
+        });
+  }
+
+  /** Scoped LargeByteBuffer. You must call close() when finished. */
+  public static final class Scoped extends LargeByteBuffer implements AutoCloseable {
+    private Scoped(MappableByteBufferHolder byteBufferHolder) throws IOException {
+      super(byteBufferHolder);
+    }
+
+    /** Closes the MappableByteBufferHolder's underlying ByteBuffer. */
+    @Override
+    public void close() {
+      byteBufferHolder.releaseByteBufferMemory();
+    }
+  }
+
+  /** The class that can hand us temporary ByteBuffers to work on. */
+  final MappableByteBufferHolder byteBufferHolder;
+
+  /** The offset in the overall byteBufferHolder that this slice represents. */
+  private final long sliceOffset;
+
+  /** The current position of the buffer, zero-indexed to the original buffer. */
+  private long position;
+
+  /** The end of this slice of data, zero-indexed to the original buffer. */
+  private long limit;
+
+  @VisibleForTesting
+  LargeByteBuffer(MappableByteBufferHolder byteBufferHolder) throws IOException {
+    this(byteBufferHolder, 0);
+  }
+
+  LargeByteBuffer(MappableByteBufferHolder byteBufferHolder, long sliceOffset) throws IOException {
+    this.byteBufferHolder = byteBufferHolder;
+    this.sliceOffset = sliceOffset;
+    this.position = sliceOffset;
+    this.limit = byteBufferHolder.getSize();
+
+    if (sliceOffset < 0) {
+      throw new IOException("Trying to slice outside the bounds of the data");
+    }
+  }
+
+  /** See ByteBuffer#order. */
+  public void order(ByteOrder byteOrder) {
+    byteBufferHolder.order(byteOrder);
+  }
+
+  /** See ByteBuffer#order. */
+  public ByteOrder order() {
+    return byteBufferHolder.order();
+  }
+
+  /** See ByteBuffer#position. */
+  public long position() {
+    return position - sliceOffset;
+  }
+
+  /** See ByteBuffer#position. */
+  public LargeByteBuffer position(long newPosition) {
+    position = newPosition + sliceOffset;
+    return this;
+  }
+
+  /** See ByteBuffer#limit. */
+  public long limit() {
+    return limit - sliceOffset;
+  }
+
+  /** See ByteBuffer#limit. */
+  public LargeByteBuffer limit(long newLimit) {
+    limit = newLimit + sliceOffset;
+    return this;
+  }
+
+  /** See ByteBuffer#remaining. */
+  public long remaining() {
+    return limit - position;
+  }
+
+  /** See ByteBuffer#hasRemaining. */
+  public boolean hasRemaining() {
+    return remaining() > 0;
+  }
+
+  /** See ByteBuffer#remaining. */
+  public LargeByteBuffer rewind() {
+    return position(0);
+  }
+
+  /** See ByteBuffer#slice. */
+  public LargeByteBuffer duplicate() throws IOException {
+    return new LargeByteBuffer(byteBufferHolder, sliceOffset).position(position()).limit(limit());
+  }
+
+  /** See ByteBuffer#slice. */
+  public LargeByteBuffer slice() throws IOException {
+    return slice(0);
+  }
+
+  /** Helper for slicing with a given offset. */
+  public LargeByteBuffer slice(long offset) throws IOException {
+    return new LargeByteBuffer(byteBufferHolder, position + offset);
+  }
+
+  /** Helper for slicing with a given offset and limit. */
+  public LargeByteBuffer slice(long offset, long limit) throws IOException {
+    return new LargeByteBuffer(byteBufferHolder, position + offset).limit(limit);
+  }
+
+  /**
+   * Checks that the MappableByteBufferHolder has all of the requested data in memory, updates the
+   * current position to reflect that the data about to be read has been read, and returns the index
+   * in the ByteBuffer to read the data at.
+   */
+  private int checkWindowGetIndexAndAdvance(long size) throws IOException {
+    byteBufferHolder.updateWindow(position, size);
+    int result = byteBufferHolder.getRelativeIndex(position);
+    position += size;
+    return result;
+  }
+
+  /**
+   * Checks that the MappableByteBufferHolder has all of the requested data in memory and returns
+   * the index in the ByteBuffer to read the data at.
+   */
+  private int checkWindowAndGetIndex(long index, long size) throws IOException {
+    byteBufferHolder.updateWindow(index + sliceOffset, size);
+    return byteBufferHolder.getRelativeIndex(index + sliceOffset);
+  }
+
+  // ==== byte ====
+
+  /** See ByteBuffer#get. */
+  public byte get() throws IOException {
+    int bufferIndex = checkWindowGetIndexAndAdvance(1);
+    return byteBufferHolder.getByteBuffer().get(bufferIndex);
+  }
+
+  public byte get(long index) throws IOException {
+    int bufferIndex = checkWindowAndGetIndex(index, 1);
+    return byteBufferHolder.getByteBuffer().get(bufferIndex);
+  }
+
+  /** See ByteBuffer#put. */
+  public LargeByteBuffer put(byte value) throws IOException {
+    int bufferIndex = checkWindowGetIndexAndAdvance(1);
+    byteBufferHolder.getByteBuffer().put(bufferIndex, value);
+    return this;
+  }
+
+  /** See ByteBuffer#put. */
+  public LargeByteBuffer put(long index, byte value) throws IOException {
+    int bufferIndex = checkWindowAndGetIndex(index, 1);
+    byteBufferHolder.getByteBuffer().put(bufferIndex, value);
+    return this;
+  }
+
+  // ==== byte[] ====
+
+  /** See ByteBuffer#get. */
+  public LargeByteBuffer get(byte[] dst) throws IOException {
+    int bufferIndex = checkWindowGetIndexAndAdvance(dst.length);
+    byteBufferHolder.getByteBuffer().position(bufferIndex).get(dst);
+    return this;
+  }
+
+  /** See ByteBuffer#put. */
+  public LargeByteBuffer put(byte[] value) throws IOException {
+    int bufferIndex = checkWindowGetIndexAndAdvance(value.length);
+    byteBufferHolder.getByteBuffer().duplicate().position(bufferIndex).put(value);
+    return this;
+  }
+
+  // ==== short ====
+
+  /** See ByteBuffer#getShort. */
+  public short getShort() throws IOException {
+    int bufferIndex = checkWindowGetIndexAndAdvance(2);
+    return byteBufferHolder.getByteBuffer().getShort(bufferIndex);
+  }
+
+  /** See ByteBuffer#getShort. */
+  public short getShort(long index) throws IOException {
+    int bufferIndex = checkWindowAndGetIndex(index, 2);
+    return byteBufferHolder.getByteBuffer().getShort(bufferIndex);
+  }
+
+  /** See ByteBuffer#putShort. */
+  public LargeByteBuffer putShort(short value) throws IOException {
+    int bufferIndex = checkWindowGetIndexAndAdvance(2);
+    byteBufferHolder.getByteBuffer().putShort(bufferIndex, value);
+    return this;
+  }
+
+  /** See ByteBuffer#putShort. */
+  public LargeByteBuffer putShort(long index, short value) throws IOException {
+    int bufferIndex = checkWindowAndGetIndex(index, 2);
+    byteBufferHolder.getByteBuffer().putShort(bufferIndex, value);
+    return this;
+  }
+
+  // ==== int ====
+
+  /** See ByteBuffer#getInt. */
+  public int getInt() throws IOException {
+    int bufferIndex = checkWindowGetIndexAndAdvance(4);
+    return byteBufferHolder.getByteBuffer().getInt(bufferIndex);
+  }
+
+  /** See ByteBuffer#getInt. */
+  public int getInt(long index) throws IOException {
+    int bufferIndex = checkWindowAndGetIndex(index, 4);
+    return byteBufferHolder.getByteBuffer().getInt(bufferIndex);
+  }
+
+  /** See ByteBuffer#putShort. */
+  public LargeByteBuffer putInt(int value) throws IOException {
+    int bufferIndex = checkWindowGetIndexAndAdvance(4);
+    byteBufferHolder.getByteBuffer().putInt(bufferIndex, value);
+    return this;
+  }
+
+  /** See ByteBuffer#putInt. */
+  public LargeByteBuffer putInt(long index, int value) throws IOException {
+    int bufferIndex = checkWindowAndGetIndex(index, 4);
+    byteBufferHolder.getByteBuffer().putInt(bufferIndex, value);
+    return this;
+  }
+
+  // ==== long ====
+
+  /** See ByteBuffer#getLong. */
+  public long getLong() throws IOException {
+    int bufferIndex = checkWindowGetIndexAndAdvance(8);
+    return byteBufferHolder.getByteBuffer().getLong(bufferIndex);
+  }
+
+  /** See ByteBuffer#getLong. */
+  public long getLong(long index) throws IOException {
+    int bufferIndex = checkWindowAndGetIndex(index, 8);
+    return byteBufferHolder.getByteBuffer().getLong(bufferIndex);
+  }
+
+  /** See ByteBuffer#putLong. */
+  public LargeByteBuffer putLong(long value) throws IOException {
+    int bufferIndex = checkWindowGetIndexAndAdvance(8);
+    byteBufferHolder.getByteBuffer().putLong(bufferIndex, value);
+    return this;
+  }
+
+  /** See ByteBuffer#putInt. */
+  public LargeByteBuffer putLong(long index, long value) throws IOException {
+    int bufferIndex = checkWindowAndGetIndex(index, 8);
+    byteBufferHolder.getByteBuffer().putLong(bufferIndex, value);
+    return this;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/MappableByteBufferHolder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/MappableByteBufferHolder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/nio/MappableByteBufferHolder.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.nio;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+/** Helper class that actually maintains the underlying ByteBuffer for LargeByteBuffer. */
+abstract class MappableByteBufferHolder {
+  private final long size;
+  private final int maxBufferSize;
+
+  private long windowStart = -1;
+  private long windowEnd = -1;
+  private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
+  private ByteBuffer byteBuffer = null;
+
+  MappableByteBufferHolder(long size, int maxBufferSize) throws IOException {
+    this.size = size;
+    this.maxBufferSize = maxBufferSize;
+
+    // If the file is small enough to be mapped all at once, go ahead and do it.
+    if (size <= maxBufferSize) {
+      mapByteBuffer(0, (int) size);
+    }
+  }
+
+  /** Implement this to actually build the new ByteBuffer as it moves. */
+  protected abstract ByteBuffer map(long start, int length) throws IOException;
+
+  public long getSize() {
+    return size;
+  }
+
+  /** Sets the order on the current ByteBuffer and retains it for all future ones. */
+  public void order(ByteOrder byteOrder) {
+    this.byteOrder = byteOrder;
+    if (byteBuffer != null) {
+      byteBuffer.order(byteOrder);
+    }
+  }
+
+  /** Gets the order used for all underlying ByteBuffers. */
+  public ByteOrder order() {
+    return this.byteOrder;
+  }
+
+  /** Releases the ByteBuffer memory if it is allocated. */
+  public void releaseByteBufferMemory() {
+    if (byteBuffer != null) {
+      ByteBufferUnmapper.unmap(byteBuffer);
+      byteBuffer = null;
+    }
+  }
+
+  /** Recreates the ByteBuffer, mapping it to a new window of the data. */
+  private void mapByteBuffer(long start, int length) throws IOException {
+    // Release the old data to prevent memory leaks;
+    releaseByteBufferMemory();
+
+    // Update the window and rebuild the buffer objects.
+    windowStart = start;
+    windowEnd = start + length;
+    byteBuffer = map(start, length);
+
+    // Restore the byte order.
+    if (byteOrder != null) {
+      byteBuffer.order(byteOrder);
+    }
+  }
+
+  /** Checks that the current ByteBuffer window contains the requested data. */
+  public void updateWindow(long start, long length) throws IOException {
+    if (length > maxBufferSize) {
+      throw new IllegalArgumentException(
+          String.format(
+              "SlidingFileLargeByteBuffer working data exceeds maximum buffer size (%s bytes)",
+              maxBufferSize));
+    }
+
+    long end = start + length;
+
+    // If the window already contains everything we need, then don't update it.
+    if (start >= windowStart && end <= windowEnd) {
+      return;
+    }
+
+    if (start < 0 || end > size) {
+      throw new IndexOutOfBoundsException(
+          String.format(
+              "Tried to create window from %s to %s (only %s bytes available)", start, end, size));
+    }
+
+    // If we're here, then the entire file can't be mapped into memory.
+    // Create a new window, at maximum size, centered around the start point.
+    long newStart = start;
+
+    // Make sure the window is within the bounds of the underlying file.
+    if (newStart < 0) {
+      newStart = 0;
+    } else if (newStart + maxBufferSize > size) {
+      newStart = size - maxBufferSize;
+    }
+
+    mapByteBuffer(newStart, maxBufferSize);
+  }
+
+  /** Gets the relative index to use with the ByteBuffer for a given position. */
+  public int getRelativeIndex(long index) {
+    return (int) (index - windowStart);
+  }
+
+  public ByteBuffer getByteBuffer() {
+    return byteBuffer;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/perf/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/perf/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/perf/BUCK
@@ -0,0 +1,18 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "perf",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/util:process_executor",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/perf/PerfStatsTracking.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/perf/PerfStatsTracking.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/perf/PerfStatsTracking.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.perf;
+
+import com.google.common.collect.ImmutableMap;
+import java.lang.management.GarbageCollectorMXBean;
+import java.lang.management.ManagementFactory;
+import java.lang.management.MemoryPoolMXBean;
+import java.lang.management.MemoryType;
+import java.util.Map;
+
+/** Periodically probes for process-wide perf-related metrics. */
+public class PerfStatsTracking {
+
+  /**
+   * Creates {@link MemoryPerfStatsEvent} using the current env state (used/free memory values, GC
+   * time spend so far and so on )
+   */
+  public static MemoryPerfStatsEvent getMemoryPerfStatsEvent() {
+    long freeMemoryBytes = Runtime.getRuntime().freeMemory();
+    long totalMemoryBytes = Runtime.getRuntime().totalMemory();
+    long maxMemoryBytes = Runtime.getRuntime().maxMemory();
+
+    long totalGcTimeMs = 0;
+    for (GarbageCollectorMXBean gcMxBean : ManagementFactory.getGarbageCollectorMXBeans()) {
+      long collectionTimeMs = gcMxBean.getCollectionTime();
+      if (collectionTimeMs == -1) {
+        // Gc collection time is not supported on this JVM.
+        totalGcTimeMs = -1;
+        break;
+      }
+      totalGcTimeMs += collectionTimeMs;
+    }
+
+    ImmutableMap.Builder<String, Long> currentMemoryBytesUsageByPool = ImmutableMap.builder();
+    for (MemoryPoolMXBean memoryPoolBean : ManagementFactory.getMemoryPoolMXBeans()) {
+      String name = memoryPoolBean.getName();
+      MemoryType type = memoryPoolBean.getType();
+      long currentlyUsedBytes = memoryPoolBean.getUsage().getUsed();
+      currentMemoryBytesUsageByPool.put(name + "(" + type + ")", currentlyUsedBytes);
+    }
+
+    return new MemoryPerfStatsEvent(
+        freeMemoryBytes,
+        totalMemoryBytes,
+        maxMemoryBytes,
+        totalGcTimeMs,
+        currentMemoryBytesUsageByPool.build());
+  }
+
+  /** Performance event that tracks current memory usage of Buck */
+  public static class MemoryPerfStatsEvent {
+
+    private final long freeMemoryBytes;
+    private final long totalMemoryBytes;
+    private final long maxMemoryBytes;
+    private final long timeSpentInGcMs;
+    private final Map<String, Long> currentMemoryBytesUsageByPool;
+
+    /**
+     * Construct a new memory performance tracking object
+     *
+     * @param freeMemoryBytes Memory in bytes available for JVM to use for new allocations
+     * @param totalMemoryBytes Memory in bytes that JVM allocated at the moment, both used and
+     *     unused
+     * @param maxMemoryBytes Maximum amount of memory in bytes that JVM can allocate (-Xmx
+     *     parameter)
+     * @param timeSpentInGcMs Total amount of milliseconds spent doing garbage collection till now
+     * @param currentMemoryBytesUsageByPool A map of JVM memory pool name to the amount of memory
+     *     used by that pool
+     */
+    public MemoryPerfStatsEvent(
+        long freeMemoryBytes,
+        long totalMemoryBytes,
+        long maxMemoryBytes,
+        long timeSpentInGcMs,
+        Map<String, Long> currentMemoryBytesUsageByPool) {
+      this.freeMemoryBytes = freeMemoryBytes;
+      this.totalMemoryBytes = totalMemoryBytes;
+      this.maxMemoryBytes = maxMemoryBytes;
+      this.timeSpentInGcMs = timeSpentInGcMs;
+      this.currentMemoryBytesUsageByPool = currentMemoryBytesUsageByPool;
+    }
+
+    /**
+     * @return Memory in bytes available for JVM to use for new allocations
+     */
+    public long getFreeMemoryBytes() {
+      return freeMemoryBytes;
+    }
+
+    /**
+     * @return Memory in bytes that JVM allocated at the moment, both used and unused
+     */
+    public long getTotalMemoryBytes() {
+      return totalMemoryBytes;
+    }
+
+    /**
+     * @return Maximum amount of memory in bytes that JVM can allocate (-Xmx parameter)
+     */
+    public long getMaxMemoryBytes() {
+      return maxMemoryBytes;
+    }
+
+    /**
+     * @return Total amount of milliseconds spent doing garbage collection till now
+     */
+    public long getTimeSpentInGcMs() {
+      return timeSpentInGcMs;
+    }
+
+    /**
+     * @return A map of JVM memory pool name to the amount of memory used by that pool
+     */
+    public Map<String, Long> getCurrentMemoryBytesUsageByPool() {
+      return currentMemoryBytesUsageByPool;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/relativepathmap/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/relativepathmap/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/relativepathmap/BUCK
@@ -0,0 +1,17 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "relativepathmap",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/relativepathmap/RelativePathMapUtils.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/relativepathmap/RelativePathMapUtils.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/relativepathmap/RelativePathMapUtils.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.relativepathmap;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Map;
+
+/** Utilities method related to process relative path maps */
+public class RelativePathMapUtils {
+
+  /** Adds path to relative map */
+  public static void addPathToRelativePathMap(
+      AbsPath rootPath,
+      Map<Path, AbsPath> relativePathMap,
+      Path basePath,
+      AbsPath absolutePath,
+      Path relativePath)
+      throws IOException {
+    if (Files.isDirectory(absolutePath.getPath())) {
+      ImmutableSet<Path> files =
+          ProjectFilesystemUtils.getFilesUnderPath(
+              rootPath,
+              absolutePath.getPath(),
+              ProjectFilesystemUtils.getDefaultVisitOptions(),
+              ProjectFilesystemUtils.getEmptyIgnoreFilter());
+      for (Path file : files) {
+        AbsPath absoluteFilePath = rootPath.resolve(file).normalize();
+        addToRelativePathMap(
+            relativePathMap, basePath.relativize(absoluteFilePath.getPath()), absoluteFilePath);
+      }
+    } else {
+      addToRelativePathMap(relativePathMap, relativePath, absolutePath);
+    }
+  }
+
+  private static void addToRelativePathMap(
+      Map<Path, AbsPath> relativePathMap, Path pathRelativeToBaseDir, AbsPath absoluteFilePath) {
+    relativePathMap.compute(
+        pathRelativeToBaseDir,
+        (ignored, current) -> {
+          if (current != null) {
+            throw new RuntimeException(
+                String.format(
+                    "The file '%s' appears twice in the hierarchy",
+                    pathRelativeToBaseDir.getFileName()));
+          }
+          return absoluteFilePath;
+        });
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "unarchive",
+    srcs = glob(["*.java"]),
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/util/environment:platform",
+        "prelude//toolchains/android/third-party:commons-compress",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:zstd-jni",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/DirectoryCreator.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/DirectoryCreator.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/DirectoryCreator.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.unarchive;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Simple class that creates directories, but keeps track of what it has created to ensure that it
+ * does not create directories more than once. This is useful when extracting archives that may or
+ * may not have duplicate entries, or to just ensure that a directory always exists before writing
+ * out a new file
+ */
+public class DirectoryCreator {
+
+  private final AbsPath projectRoot;
+  private final Set<Path> existing = new HashSet<>();
+
+  /**
+   * Creates an instance of {@link DirectoryCreator}
+   *
+   * @param projectRoot The root path to operate on
+   */
+  public DirectoryCreator(AbsPath projectRoot) {
+    this.projectRoot = projectRoot;
+    this.existing.add(projectRoot.getPath());
+  }
+
+  /**
+   * Get the set of directories that were either created by this class, or manually specified in
+   * {@link DirectoryCreator#recordPath(Path)}
+   *
+   * @return Set of directories
+   */
+  public Set<Path> recordedDirectories() {
+    return existing;
+  }
+
+  /**
+   * Ensure that we record that a path was created. This can be useful if for some reason a
+   * directory is created externally, but the list of created directories is pulled from an instance
+   * of {@link DirectoryCreator}
+   */
+  public void recordPath(Path target) {
+    existing.add(target);
+  }
+
+  public AbsPath getProjectRoot() {
+    return projectRoot;
+  }
+
+  /**
+   * Create a directory and all of its parents
+   *
+   * @param target The path where a directory should exist
+   * @throws IOException If the directory could not be created
+   */
+  public void mkdirs(Path target) throws IOException {
+    if (existing.contains(target)) {
+      return;
+    }
+    ProjectFilesystemUtils.mkdirs(projectRoot, target);
+    while (target != null) {
+      existing.add(target);
+      target = target.getParent();
+    }
+  }
+
+  /**
+   * Force a directory to be created. This will delete existing files (not directories) if they
+   * share the name of the directory, including parent paths
+   *
+   * @param target The path where a directory should exist
+   * @throws IOException The directory could not be created, or files that needed to be removed
+   *     could not be removed
+   */
+  public void forcefullyCreateDirs(Path target) throws IOException {
+    if (existing.contains(target)) {
+      return;
+    }
+    if (ProjectFilesystemUtils.exists(projectRoot, target)) {
+      if (!ProjectFilesystemUtils.isDirectory(projectRoot, target)) {
+        ProjectFilesystemUtils.deleteFileAtPath(projectRoot, target);
+        mkdirs(target);
+      }
+    } else {
+      if (target.getParent() != null) {
+        forcefullyCreateDirs(target.getParent());
+      }
+      mkdirs(target);
+    }
+    existing.add(target);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/Unzip.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/Unzip.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unarchive/Unzip.java
@@ -0,0 +1,277 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.unarchive;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.file.MorePosixFilePermissions;
+import com.facebook.buck.io.file.MostFiles;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.io.ByteStreams;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.attribute.PosixFilePermission;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.TreeMap;
+import java.util.stream.Stream;
+import java.util.zip.ZipError;
+import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
+import org.apache.commons.compress.archivers.zip.ZipFile;
+
+/** A simple utility class that extracts zip files */
+public class Unzip {
+
+  private static void writeZipContents(
+      ZipFile zip, ZipArchiveEntry entry, AbsPath root, Path target) throws IOException {
+    // Write file
+    try (InputStream is = zip.getInputStream(entry)) {
+      if (entry.isUnixSymlink()) {
+        ProjectFilesystemUtils.createSymLink(
+            root,
+            target,
+            ProjectFilesystemUtils.getPath(
+                root, new String(ByteStreams.toByteArray(is), StandardCharsets.UTF_8)),
+            /* force */ true);
+      } else {
+        try (OutputStream out = ProjectFilesystemUtils.newFileOutputStream(root, target)) {
+          ByteStreams.copy(is, out);
+        }
+      }
+    }
+
+    Path filePath = root.resolve(target).getPath();
+    File file = filePath.toFile();
+
+    // restore mtime for the file
+    file.setLastModified(entry.getTime());
+
+    // TODO(simons): Implement what the comment below says we should do.
+    //
+    // Sets the file permissions of the output file given the information in {@code entry}'s
+    // extra data field. According to the docs at
+    // http://www.opensource.apple.com/source/zip/zip-6/unzip/unzip/proginfo/extra.fld there
+    // are two extensions that might support file permissions: Acorn and ASi UNIX. We shall
+    // assume that inputs are not from an Acorn SparkFS. The relevant section from the docs:
+    //
+    // <pre>
+    //    The following is the layout of the ASi extra block for Unix.  The
+    //    local-header and central-header versions are identical.
+    //    (Last Revision 19960916)
+    //
+    //    Value         Size        Description
+    //    -----         ----        -----------
+    //   (Unix3) 0x756e        Short       tag for this extra block type ("nu")
+    //   TSize         Short       total data size for this block
+    //   CRC           Long        CRC-32 of the remaining data
+    //   Mode          Short       file permissions
+    //   SizDev        Long        symlink'd size OR major/minor dev num
+    //   UID           Short       user ID
+    //   GID           Short       group ID
+    //   (var.)        variable    symbolic link filename
+    //
+    //   Mode is the standard Unix st_mode field from struct stat, containing
+    //   user/group/other permissions, setuid/setgid and symlink info, etc.
+    // </pre>
+    //
+    // From the stat man page, we see that the following mask values are defined for the file
+    // permissions component of the st_mode field:
+    //
+    // <pre>
+    //   S_ISUID   0004000   set-user-ID bit
+    //   S_ISGID   0002000   set-group-ID bit (see below)
+    //   S_ISVTX   0001000   sticky bit (see below)
+    //
+    //   S_IRWXU     00700   mask for file owner permissions
+    //
+    //   S_IRUSR     00400   owner has read permission
+    //   S_IWUSR     00200   owner has write permission
+    //   S_IXUSR     00100   owner has execute permission
+    //
+    //   S_IRWXG     00070   mask for group permissions
+    //   S_IRGRP     00040   group has read permission
+    //   S_IWGRP     00020   group has write permission
+    //   S_IXGRP     00010   group has execute permission
+    //
+    //   S_IRWXO     00007   mask for permissions for others
+    //   (not in group)
+    //   S_IROTH     00004   others have read permission
+    //   S_IWOTH     00002   others have write permission
+    //   S_IXOTH     00001   others have execute permission
+    // </pre>
+    //
+    // For the sake of our own sanity, we're going to assume that no-one is using symlinks,
+    // but we'll check and throw if they are.
+    //
+    // Before we do anything, we should check the header ID. Pfft!
+    //
+    // Having jumped through all these hoops, it turns out that InfoZIP's "unzip" store the
+    // values in the external file attributes of a zip entry (found in the zip's central
+    // directory) assuming that the OS creating the zip was one of an enormous list that
+    // includes UNIX but not Windows, it first searches for the extra fields, and if not found
+    // falls through to a code path that supports MS-DOS and which stores the UNIX file
+    // attributes in the upper 16 bits of the external attributes field.
+    //
+    // We'll support neither approach fully, but we encode whether this file was executable
+    // via storing 0100 in the fields that are typically used by zip implementations to store
+    // POSIX permissions. If we find it was executable, use the platform independent java
+    // interface to make this unpacked file executable.
+
+    Set<PosixFilePermission> permissions =
+        MorePosixFilePermissions.fromMode(entry.getExternalAttributes() >> 16);
+    if (permissions.contains(PosixFilePermission.OWNER_EXECUTE)
+        && file.getCanonicalFile().exists()) {
+      MostFiles.makeExecutable(filePath);
+    }
+  }
+
+  private static boolean isTopLevel(Path path, SortedMap<Path, ZipArchiveEntry> pathMap) {
+    for (Path p = path.getParent(); p != null; p = p.getParent()) {
+      if (pathMap.containsKey(p)) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  private static void fillIntermediatePaths(Path path, SortedMap<Path, ZipArchiveEntry> pathMap) {
+    for (Path p = path.getParent(); p != null; p = p.getParent()) {
+      if (pathMap.containsKey(p)) {
+        break;
+      }
+      pathMap.put(p, new ZipArchiveEntry(p + "/"));
+    }
+  }
+
+  private static void extractFile(
+      ImmutableSet.Builder<Path> filesWritten,
+      ZipFile zip,
+      DirectoryCreator creator,
+      Path target,
+      ZipArchiveEntry entry)
+      throws IOException {
+    AbsPath root = creator.getProjectRoot();
+    if (ProjectFilesystemUtils.isFile(
+        root, target, LinkOption.NOFOLLOW_LINKS)) { // NOPMD for clarity pass
+    } else if (ProjectFilesystemUtils.exists(root, target, LinkOption.NOFOLLOW_LINKS)) {
+      ProjectFilesystemUtils.deleteRecursivelyIfExists(root, target);
+    } else if (target.getParent() != null) {
+      creator.forcefullyCreateDirs(target.getParent());
+    }
+    filesWritten.add(target);
+    writeZipContents(zip, entry, root, target);
+  }
+
+  private static void extractDirectory(DirectoryCreator creator, Path target) throws IOException {
+    AbsPath root = creator.getProjectRoot();
+    if (ProjectFilesystemUtils.isDirectory(root, target, LinkOption.NOFOLLOW_LINKS)) {
+      // Directory already exists, no action needed
+    } else if (ProjectFilesystemUtils.exists(root, target, LinkOption.NOFOLLOW_LINKS)) {
+      ProjectFilesystemUtils.deleteFileAtPath(root, target);
+      creator.mkdirs(target);
+    } else {
+      creator.forcefullyCreateDirs(target);
+    }
+  }
+
+  /**
+   * Get a listing of all files in a zip file
+   *
+   * @param zip The zip file to scan
+   * @param relativePath The relative path where the extraction will be rooted
+   * @return The list of paths in {@code zip} sorted by path so dirs come before contents.
+   */
+  private static SortedMap<Path, ZipArchiveEntry> getZipFilePaths(ZipFile zip, Path relativePath) {
+    SortedMap<Path, ZipArchiveEntry> pathMap = new TreeMap<>();
+    for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) {
+      String entryName = entry.getName();
+      Path target = relativePath.resolve(entryName).normalize();
+      pathMap.put(target, entry);
+    }
+    return pathMap;
+  }
+
+  public static ImmutableList<Path> extractArchive(
+      AbsPath extractedPath, Path archiveFile, Path relativePath) throws IOException {
+
+    // We want to remove stale contents of directories listed in {@code archiveFile}, but avoid
+    // deleting and
+    // re-creating any directories that already exist. We *also* want to avoid a full recursive
+    // scan of listed directories, since that's almost as slow as deleting. So we preprocess the
+    // contents of {@code archiveFile} and then scan the existing filesystem to remove stale
+    // artifacts.
+
+    ImmutableSet.Builder<Path> filesWritten = ImmutableSet.builder();
+    try (ZipFile zip = new ZipFile(archiveFile.toFile())) {
+      SortedMap<Path, ZipArchiveEntry> pathMap;
+      pathMap = getZipFilePaths(zip, relativePath);
+      // A zip file isn't required to list intermediate paths (e.g., it can contain "foo/" and
+      // "foo/bar/baz"), but we need to know not to delete those intermediates, so fill them in.
+      for (SortedMap.Entry<Path, ZipArchiveEntry> p : new ArrayList<>(pathMap.entrySet())) {
+        if (!isTopLevel(p.getKey(), pathMap)) {
+          fillIntermediatePaths(p.getKey(), pathMap);
+        }
+      }
+
+      DirectoryCreator creator = new DirectoryCreator(extractedPath);
+
+      for (SortedMap.Entry<Path, ZipArchiveEntry> p : pathMap.entrySet()) {
+        Path target = p.getKey();
+        ZipArchiveEntry entry = p.getValue();
+        if (entry.isDirectory()) {
+          extractDirectory(creator, target);
+        } else {
+          extractFile(filesWritten, zip, creator, target, entry);
+        }
+      }
+    }
+    return filesWritten.build().asList();
+  }
+
+  /**
+   * Gets a set of files that are contained in an archive
+   *
+   * @param archiveAbsolutePath The absolute path to the archive
+   * @return A set of files (not directories) that are contained in the zip file
+   * @throws IOException If there is an error reading the archive
+   */
+  public static ImmutableSet<Path> getZipMembers(Path archiveAbsolutePath) throws IOException {
+    try (FileSystem zipFs = FileSystems.newFileSystem(archiveAbsolutePath, (ClassLoader) null)) {
+      Path root = Iterables.getOnlyElement(zipFs.getRootDirectories());
+      try (Stream<Path> paths = Files.walk(root)) {
+        return paths
+            .filter(path -> !Files.isDirectory(path))
+            .map(root::relativize)
+            .map(path -> Paths.get(path.toString())) // Clear the filesystem from the path
+            .collect(ImmutableSet.toImmutableSet());
+      }
+    } catch (ZipError error) {
+      // For some reason the zip filesystem support throws an error when an IOException would do
+      // just as well.
+      throw new IOException(
+          String.format("Could not read %s because of %s", archiveAbsolutePath, error.toString()),
+          error);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unit/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unit/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unit/BUCK
@@ -0,0 +1,19 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "unit",
+    srcs = glob(["*.java"]),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/util/unit:unit",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+    ],
+    exported_deps = [],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unit/SizeUnit.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unit/SizeUnit.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/unit/SizeUnit.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.unit;
+
+import java.math.BigDecimal;
+
+public enum SizeUnit {
+  BYTES(0, "bytes"),
+  KILOBYTES(1, "Kbytes"),
+  MEGABYTES(2, "Mbytes"),
+  GIGABYTES(3, "Gbytes"),
+  TERABYTES(4, "Tbytes");
+
+  private final int ordinal;
+  private final String abbreviation;
+
+  SizeUnit(int ordinal, String abbreviation) {
+    this.ordinal = ordinal;
+    this.abbreviation = abbreviation;
+  }
+
+  public int getOrdinal() {
+    return ordinal;
+  }
+
+  public String getAbbreviation() {
+    return abbreviation;
+  }
+
+  private static long multiplyByByteOrderOfMagnitude(double size, int magnitude) {
+    if (magnitude == 0) {
+      return (long) size;
+    } else if (magnitude > 0) {
+      return BigDecimal.valueOf(size).multiply(BigDecimal.valueOf(1024).pow(magnitude)).longValue();
+    } else {
+      return BigDecimal.valueOf(size)
+          .divide(BigDecimal.valueOf(1024).pow(-1 * magnitude))
+          .longValue();
+    }
+  }
+
+  public long toBytes(double size) {
+    return multiplyByByteOrderOfMagnitude(size, getOrdinal() - BYTES.getOrdinal());
+  }
+
+  public long toKilobytes(double size) {
+    return multiplyByByteOrderOfMagnitude(size, getOrdinal() - KILOBYTES.getOrdinal());
+  }
+
+  public long toMegabytes(double size) {
+    return multiplyByByteOrderOfMagnitude(size, getOrdinal() - MEGABYTES.getOrdinal());
+  }
+
+  public long toGigabytes(double size) {
+    return multiplyByByteOrderOfMagnitude(size, getOrdinal() - GIGABYTES.getOrdinal());
+  }
+
+  public long toTerabytes(double size) {
+    return multiplyByByteOrderOfMagnitude(size, getOrdinal() - TERABYTES.getOrdinal());
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/xml/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/xml/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/xml/BUCK
@@ -0,0 +1,19 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "xml",
+    srcs = glob(["*.java"]),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/util/xml:xml",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/xml/XmlDomParser.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/xml/XmlDomParser.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/xml/XmlDomParser.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.xml;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+public class XmlDomParser {
+
+  /** Utility class: do not instantiate. */
+  private XmlDomParser() {}
+
+  public static Document parse(Path xml) throws IOException, SAXException {
+    try (InputStream is = Files.newInputStream(xml)) {
+      return parse(is);
+    }
+  }
+
+  public static Document parse(String xmlContents) throws IOException, SAXException {
+    return parse(new ByteArrayInputStream(xmlContents.getBytes(StandardCharsets.UTF_8)));
+  }
+
+  public static Document parse(InputStream stream) throws IOException, SAXException {
+    return parse(new InputSource(stream), /* namespaceAware */ false);
+  }
+
+  public static Document parse(InputSource xml, boolean namespaceAware)
+      throws IOException, SAXException {
+    DocumentBuilder docBuilder;
+    try {
+      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+      if (namespaceAware) {
+        factory.setNamespaceAware(namespaceAware);
+      }
+      docBuilder = factory.newDocumentBuilder();
+    } catch (ParserConfigurationException e) {
+      throw new RuntimeException(e);
+    }
+
+    return docBuilder.parse(xml);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/AppendableCentralDirectory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/AppendableCentralDirectory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/AppendableCentralDirectory.java
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static com.facebook.buck.util.zip.ByteIo.readInt;
+import static com.facebook.buck.util.zip.ByteIo.readLong;
+import static com.facebook.buck.util.zip.ByteIo.readShort;
+import static com.facebook.buck.util.zip.ByteIo.readUnsignedInt;
+import static java.nio.file.StandardOpenOption.READ;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.nio.channels.SeekableByteChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.zip.ZipEntry;
+
+/**
+ * Load existing Central Directory header information, such as offset position and previous list of
+ * files. It's used to support append operations by preserving header of previous files.
+ */
+public class AppendableCentralDirectory extends CentralDirectory {
+
+  /** END Header fields, used to locate the ZIP Central Directory. */
+  static class Header {
+
+    private final int count;
+    private final long size;
+    private final long offset;
+
+    Header(int count, long size, long offset) {
+      this.count = count;
+      this.size = size;
+      this.offset = offset;
+    }
+
+    int getCount() {
+      return count;
+    }
+
+    long getSize() {
+      return size;
+    }
+
+    long getOffset() {
+      return offset;
+    }
+
+    boolean isValid() {
+      return offset >= 0 && size > 0 && count > 0;
+    }
+
+    boolean isZip64() {
+      return isZip64MagicVal(offset) || isZip64MagicVal(size) || isZip64MagicCount(count);
+    }
+  }
+
+  static Header readHeader(SeekableByteChannel file) throws IOException {
+    final long fileSize = file.size();
+    // Central Directory header will be on the last 64kb of the file
+    final int headerSize = (int) Math.min(fileSize, ZipConstants.END_MAXLEN);
+    final long headerPosition = fileSize - headerSize;
+    // not enough data or invalid
+    if (fileSize >= headerSize) {
+      final ByteBuffer headerBuffer = ByteBuffer.allocate(headerSize);
+      // position channel to read the last block of the file.
+      file.position(headerPosition);
+      file.read(headerBuffer);
+
+      final byte[] buffer = headerBuffer.array();
+      final int bufferSize = headerBuffer.rewind().remaining();
+
+      // scan the block backwards for ENDSIG header signature
+      for (int pos = bufferSize - ZipEntry.ENDHDR; pos >= 0; pos--) {
+        if (readInt(buffer, pos) == ZipEntry.ENDSIG) {
+          // Offset of the start of the central directory.
+          final Header header =
+              new Header(
+                  readShort(buffer, pos + ZipEntry.ENDTOT),
+                  readUnsignedInt(buffer, pos + ZipEntry.ENDSIZ),
+                  readUnsignedInt(buffer, pos + ZipEntry.ENDOFF));
+          // if theres no zip64 magic values.
+          if (header.isZip64()) {
+            int end64Pos = pos - ZipConstants.ZIP64_LOCHDR;
+            // check if zip64 signature is available
+            if (end64Pos <= 0 || readInt(buffer, end64Pos) != ZipConstants.ZIP64_LOCSIG) {
+              return header;
+            }
+            // read zip64 offset in the file
+            long end64Offset = readLong(buffer, end64Pos + ZipConstants.ZIP64_LOCOFF);
+            // has to be a position within the tail.
+            if (end64Offset < headerPosition || end64Offset > fileSize) {
+              return header;
+            }
+            // recalculate offset inside the buffer
+            end64Pos = (int) (end64Offset - headerPosition);
+            // if the position is ENDSIG
+            if (readInt(buffer, end64Pos) == ZipConstants.ZIP64_ENDSIG) {
+              final Header header64 =
+                  new Header(
+                      (int) readLong(buffer, end64Pos + ZipConstants.ZIP64_ENDTOT),
+                      readLong(buffer, end64Pos + ZipConstants.ZIP64_ENDSIZ),
+                      readLong(buffer, end64Pos + ZipConstants.ZIP64_ENDOFF));
+              if (header64.isValid()) {
+                return header64;
+              }
+            }
+          }
+          return header;
+        }
+      }
+    }
+    return null;
+  }
+
+  /**
+   * @param src file to load the header information
+   * @return Central directory with preloaded files (CENSIG list)
+   * @throws IOException In case it fails to read the src information.
+   */
+  public static AppendableCentralDirectory readCentralDirectory(Path src) throws IOException {
+    try (final SeekableByteChannel file = Files.newByteChannel(src, READ)) {
+      final Header header = readHeader(file);
+      // found valid offset, load header, so it can be appended with new entries.
+      if (header != null && header.isValid()) {
+        final ByteBuffer buffer = ByteBuffer.allocate((int) header.getSize());
+        file.position(header.getOffset());
+        file.read(buffer);
+        return new AppendableCentralDirectory(header.getCount(), header.getOffset(), buffer);
+      }
+    }
+    return new AppendableCentralDirectory();
+  }
+
+  private final int entryCount;
+  private final long entryOffset;
+  private final ByteBuffer header;
+
+  AppendableCentralDirectory() {
+    this(0, 0, ByteBuffer.allocate(0));
+  }
+
+  AppendableCentralDirectory(
+      final int entryCount, final long entryOffset, final ByteBuffer header) {
+    this.entryCount = entryCount;
+    this.entryOffset = entryOffset;
+    this.header = header;
+  }
+
+  /**
+   * @return Number of entries current available in the zip central directory.
+   */
+  public int getEntryCount() {
+    return entryCount;
+  }
+
+  /** Position of bytes where the files in the zip ended and the header start. */
+  public long getEntryOffset() {
+    return entryOffset;
+  }
+
+  /**
+   * Prepend previous list of files in the zip.
+   *
+   * @return Total bytes prepended.
+   */
+  @Override
+  protected long beforeWrite(OutputStream out) throws IOException {
+    int headerSize = header.capacity();
+    if (headerSize > 0) {
+      out.write(header.array(), 0, headerSize);
+    }
+    return headerSize;
+  }
+
+  /**
+   * @return Number of files previous present in the zip.
+   */
+  @Override
+  protected int beforeEntries() {
+    return entryCount;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/AppendingZipOutputStreamImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/AppendingZipOutputStreamImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/AppendingZipOutputStreamImpl.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+/**
+ * A drop-in replacement for (@link java.util.zip.ZipOutStream} that supports the ability to set a
+ * compression level and allows multiple entries with the same name.
+ *
+ * <p><a href="https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html">
+ * https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html </a> <a
+ * href="http://www.pkware.com/documents/casestudies/APPNOTE.TXT">
+ * http://www.pkware.com/documents/casestudies/APPNOTE.TXT </a>
+ */
+class AppendingZipOutputStreamImpl implements CustomZipOutputStream.Impl {
+
+  private final OutputStream delegate;
+  private final boolean throwExceptionsOnDuplicate;
+  private final List<EntryAccounting> entries = new LinkedList<>();
+  private final Set<String> seenNames = new HashSet<>();
+
+  private long currentOffset;
+
+  @Nullable private EntryAccounting currentEntry = null;
+
+  public AppendingZipOutputStreamImpl(OutputStream stream, boolean throwExceptionsOnDuplicate) {
+    this.delegate = stream;
+    this.throwExceptionsOnDuplicate = throwExceptionsOnDuplicate;
+  }
+
+  @Override
+  public void actuallyWrite(byte[] b, int off, int len) throws IOException {
+    Objects.requireNonNull(currentEntry);
+    currentEntry.write(delegate, b, off, len);
+  }
+
+  @Override
+  public void actuallyPutNextEntry(ZipEntry entry) throws IOException {
+    if (throwExceptionsOnDuplicate && hasEntry(entry.getName())) {
+      // Same exception as ZipOutputStream.
+      throw new ZipException("duplicate entry: " + entry.getName());
+    }
+    currentEntry = new EntryAccounting(entry, currentOffset);
+    currentOffset += currentEntry.writeLocalFileHeader(delegate);
+    addEntry(currentEntry);
+  }
+
+  protected boolean hasEntry(String name) {
+    return seenNames.contains(name);
+  }
+
+  protected void addEntry(EntryAccounting entry) {
+    seenNames.add(entry.getName());
+    entries.add(entry);
+  }
+
+  protected long getCurrentOffset() {
+    return currentOffset;
+  }
+
+  protected void setCurrentOffset(long currentOffset) {
+    this.currentOffset = currentOffset;
+  }
+
+  @Override
+  public void actuallyCloseEntry() throws IOException {
+    if (currentEntry == null) {
+      return; // no-op
+    }
+    currentOffset += currentEntry.finish(delegate);
+    currentEntry = null;
+  }
+
+  @Override
+  public void actuallyClose() throws IOException {
+    getCentralDirectory().writeCentralDirectory(delegate, currentOffset, entries);
+    delegate.close();
+  }
+
+  protected @Nonnull CentralDirectory getCentralDirectory() {
+    return new CentralDirectory();
+  }
+
+  protected OutputStream getDelegate() {
+    return delegate;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/BUCK
@@ -0,0 +1,154 @@
+load(
+    "@prelude//toolchains/android/tools:build_rules.bzl",
+    "buck_java_binary",
+    "buck_java_library",
+    "buck_kotlin_library",
+    "buck_prebuilt_artifact",
+    "buck_prebuilt_jar",
+)
+load("@prelude//toolchains/android/tools/build_rules:fb_native.bzl", "fb_native")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+JAR_BUILDER_MAIN_SRCS = [
+    "JarBuilderMain.java",
+]
+
+ZIP_SCRUBBER_SRCS = [
+    "ZipScrubber.java",
+    "ZipConstants.java",
+]
+
+buck_kotlin_library(
+    name = "zip",
+    srcs = glob(
+        [
+            "*.java",
+            "*.kt",
+        ],
+        exclude = JAR_BUILDER_MAIN_SRCS + ZIP_SCRUBBER_SRCS,
+    ),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/util/zip:zip",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/util/log:log",
+        "prelude//toolchains/android/src/com/facebook/buck/io/file:file",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/src/com/facebook/buck/util/function:function",
+        "prelude//toolchains/android/src/com/facebook/buck/util/io:io",
+        "prelude//toolchains/android/src/com/facebook/buck/util/unarchive:unarchive",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:jsr305",
+    ],
+    exported_deps = [
+        ":zip_scrubber_lib",
+    ],
+)
+
+buck_java_library(
+    name = "zip_scrubber_lib",
+    srcs = ZIP_SCRUBBER_SRCS,
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/nio:nio",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
+
+fb_native.alias(
+    name = "zip_scrubber",
+    actual = ":zip_scrubber_prebuilt",
+    visibility = ["PUBLIC"],
+)
+
+# This is a prebuilt jar so that it can be part of the buck2 bootstrap toolchain.
+# To rebuild the jar, do:
+# `buck build prelude//toolchains/android/src/com/facebook/buck/util/zip:zip_scrubber_main --out xplat/toolchains/android/sdk/src/com/facebook/buck/util/zip/zip_scrubber_main.jar`
+buck_prebuilt_jar(
+    name = "zip_scrubber_prebuilt",
+    _dex_toolchain = "toolchains//:empty_dex",
+    binary_jar = ":zip_scrubber_main.jar",
+    should_generate_snapshot = False,
+    visibility = ["PUBLIC"],
+)
+
+# To rebuild the jar and upload it to CAS, do:
+# buck build prelude//toolchains/android/src/com/facebook/buck/util/zip:zip_scrubber_main --show-simple-output | xargs frecli --use-case android_build_infra_tools cas upload-blob
+buck_prebuilt_artifact(
+    name = "zip_scrubber_main.jar",
+    # @oss-disable[end= ]: cas_digest = "9cec24a193a236fc5acdaff4fae66769f22c56af19c1e9204affad545d0ec7ab:10388458",
+    oss_sha1 = "23c85d8db2958ad502c1cd1eb3bbcd1342c37c7d",
+    oss_url = "https://github.com/facebook/buck2/releases/download/androidToolchain%2F2025-04-03/zip_scrubber_main.jar",
+)
+
+buck_java_binary(
+    name = "zip_scrubber_main",
+    main_class = "com.facebook.buck.util.zip.ZipScrubber",
+    visibility = ["PUBLIC"],
+    deps = [":zip_scrubber_lib"],
+)
+
+buck_java_library(
+    name = "jar_builder_main_lib",
+    srcs = JAR_BUILDER_MAIN_SRCS,
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/core/filesystems:filesystems",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java:remove_classes_patterns_matcher",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/function:function",
+        "prelude//toolchains/android/third-party:args4j",
+        "prelude//toolchains/android/third-party:guava",
+        ":zip",
+    ],
+)
+
+fb_native.alias(
+    name = "jar_builder",
+    actual = ":jar_builder_prebuilt",
+    visibility = ["PUBLIC"],
+)
+
+# This is a prebuilt jar so that it can be part of the buck2 bootstrap toolchain.
+buck_prebuilt_jar(
+    name = "jar_builder_prebuilt",
+    _dex_toolchain = "toolchains//:empty_dex",
+    binary_jar = ":jar_builder_main.jar",
+    should_generate_snapshot = False,
+    visibility = ["PUBLIC"],
+)
+
+# To rebuild the jar and upload it to CAS, do:
+# buck build prelude//toolchains/android/src/com/facebook/buck/util/zip:jar_builder_main --show-simple-output | xargs frecli --use-case android_build_infra_tools cas upload-blob
+buck_prebuilt_artifact(
+    name = "jar_builder_main.jar",
+    # @oss-disable[end= ]: cas_digest = "73149775903042a6a323255a7b40862323c8afc35afd582c4b8861ff77d8fbe9:23604183",
+    oss_sha1 = "18f839ebb58babae4ae35900ef33cdf065d0cbc5",
+    oss_url = "https://github.com/facebook/buck2/releases/download/androidToolchain%2F2025-04-03/jar_builder_main.jar",
+)
+
+buck_java_binary(
+    name = "jar_builder_main",
+    main_class = "com.facebook.buck.util.zip.JarBuilderMain",
+    deps = [
+        ":jar_builder_main_lib",
+    ],
+)
+
+buck_java_binary(
+    name = "jar_diff",
+    main_class = "com.facebook.buck.util.zip.JarDiff",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":jar_builder_main_lib",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/BestCompressionGZIPOutputStream.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/BestCompressionGZIPOutputStream.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/BestCompressionGZIPOutputStream.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.zip.GZIPOutputStream;
+
+public class BestCompressionGZIPOutputStream extends GZIPOutputStream {
+
+  public BestCompressionGZIPOutputStream(OutputStream out, boolean syncFlush) throws IOException {
+    super(out, syncFlush);
+    def.setLevel(9);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ByteIo.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ByteIo.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ByteIo.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/** Zip implementation assume bytes to be in Intel (little-endian) byte order. */
+class ByteIo {
+
+  private ByteIo() {
+    // utility class.
+  }
+
+  public static int readShort(byte[] b, int off) {
+    return (b[off] & 0xff) | ((b[off + 1] & 0xff) << 8);
+  }
+
+  public static int readInt(byte[] b, int off) {
+    return (int) readUnsignedInt(b, off);
+  }
+
+  public static long readUnsignedInt(byte[] b, int off) {
+    return (readShort(b, off) | ((long) readShort(b, off + 2) << 16)) & 0xffffffffL;
+  }
+
+  public static long readLong(byte[] b, int off) {
+    return readUnsignedInt(b, off) | (readUnsignedInt(b, off + 4) << 32);
+  }
+
+  public static long writeShort(OutputStream out, int value) throws IOException {
+    out.write((value & 0xff));
+    out.write(((value >>> 8) & 0xff));
+    return 2;
+  }
+
+  protected static long writeInt(OutputStream out, long value) throws IOException {
+    out.write((int) (value & 0xff));
+    out.write((int) ((value >>> 8) & 0xff));
+    out.write((int) ((value >>> 16) & 0xff));
+    out.write((int) ((value >>> 24) & 0xff));
+    return 4;
+  }
+
+  protected static long writeLong(OutputStream out, long value) throws IOException {
+    out.write((int) (value & 0xff));
+    out.write((int) ((value >>> 8) & 0xff));
+    out.write((int) ((value >>> 16) & 0xff));
+    out.write((int) ((value >>> 24) & 0xff));
+    out.write((int) ((value >>> 32) & 0xff));
+    out.write((int) ((value >>> 40) & 0xff));
+    out.write((int) ((value >>> 48) & 0xff));
+    out.write((int) ((value >>> 56) & 0xff));
+    return 8;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectory.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectory.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectory.java
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static com.facebook.buck.util.zip.ByteIo.writeInt;
+import static com.facebook.buck.util.zip.ByteIo.writeLong;
+import static com.facebook.buck.util.zip.ByteIo.writeShort;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.zip.ZipEntry;
+
+/**
+ * Each zip file has a "central directory" at the end of the archive, which provides the indexes
+ * required for fast random access to the contents of the zip. This class models that.
+ *
+ * <p>The central directory consists of a series of "file headers", describing each entry in the
+ * zip, and a "end of central directory" signature containing book keeping information.
+ */
+public class CentralDirectory {
+
+  /** Execute before the central directory is created and return number of bytes prepended. */
+  protected long beforeWrite(OutputStream out) throws IOException {
+    return 0;
+  }
+
+  /**
+   * Execute before the central directory is created and return number of entries added. Will be
+   * used as offset number of entries.
+   */
+  protected int beforeEntries() {
+    return 0;
+  }
+
+  /**
+   * Write the entire central directory, including the file headers and the end of central directory
+   * signature.
+   *
+   * @param out The stream to output to.
+   * @param startOffset The number of bytes offset within the zip file that this starts at.
+   * @param entries The entries that are contained within the zip.
+   * @throws IOException Should something go awry.
+   */
+  public void writeCentralDirectory(
+      final OutputStream out, final long startOffset, final Iterable<EntryAccounting> entries)
+      throws IOException {
+
+    long size = beforeWrite(out);
+    int entryCount = beforeEntries();
+
+    for (EntryAccounting entry : entries) {
+      entryCount++;
+      size += writeCentralDirectoryFileHeader(out, entry);
+    }
+
+    boolean useZip64 = false;
+
+    useZip64 =
+        isZip64MagicVal(startOffset) || isZip64MagicVal(size) || isZip64MagicCount(entryCount);
+
+    if (useZip64) {
+      // Zip64 end of central directory record.
+      writeInt(out, ZipConstants.ZIP64_ENDSIG);
+      writeLong(out, ZipConstants.ZIP64_ENDHDR - 12);
+      // Version made by.
+      writeShort(out, 45);
+      // Version needed to extract.
+      writeShort(out, 45);
+      // Number of this disk.
+      writeInt(out, 0);
+      // Number of the disk with the start of the central directory.
+      writeInt(out, 0);
+      // Total number of entries in the central directory on this disk.
+      writeLong(out, entryCount);
+      // Total number of entries in the central directory.
+      writeLong(out, entryCount);
+      // Size of the central directory.
+      writeLong(out, size);
+      // Offset of start of central directory.
+      writeLong(out, startOffset);
+
+      // Zip64 end of central directory locator.
+      writeInt(out, ZipConstants.ZIP64_LOCSIG);
+      // number of the disk with the start of the zip64 end of central directory.
+      writeInt(out, 0);
+      // relative offset of the zip64 end of central directory record.
+      writeLong(out, startOffset + size);
+      // total number of disks.
+      writeInt(out, 1);
+    }
+
+    // End of central directory record.
+    writeInt(out, ZipEntry.ENDSIG);
+    // Number of this disk (with end of central directory)
+    writeShort(out, 0);
+    // Number of disk on which central directory starts.
+    writeShort(out, 0);
+    // Number of central directory entries in this disk.
+    writeShort(out, zip64MagicCount(entryCount));
+    // Number of central directory entries.
+    writeShort(out, zip64MagicCount(entryCount));
+    // Size of the central directory in bytes.
+    writeInt(out, zip64MagicVal(size));
+    // Offset of the start of the central directory.
+    writeInt(out, zip64MagicVal(startOffset));
+    // Size of the comment (we don't have one)
+    writeShort(out, 0);
+  }
+
+  /** Each entry requires a description of that entry to be contained in the central directory. */
+  private long writeCentralDirectoryFileHeader(OutputStream out, EntryAccounting entry)
+      throws IOException {
+    int zip64DataLength = 0;
+    if (isZip64MagicVal(entry.getSize())) {
+      zip64DataLength += 8;
+    }
+    if (isZip64MagicVal(entry.getCompressedSize())) {
+      zip64DataLength += 8;
+    }
+    if (isZip64MagicVal(entry.getOffset())) {
+      zip64DataLength += 8;
+    }
+
+    int extraDataLength = 0;
+    boolean useZip64 = zip64DataLength > 0;
+    if (useZip64) {
+      extraDataLength = zip64DataLength + 4;
+    } else {
+      extraDataLength = 0;
+    }
+
+    long size = 0;
+    size += writeInt(out, ZipEntry.CENSIG);
+    // version made by.
+    size += writeShort(out, entry.getRequiredExtractVersion(useZip64));
+    // version to extract with.
+    size += writeShort(out, entry.getRequiredExtractVersion(useZip64));
+    size += writeShort(out, entry.getFlags());
+    // Compression.
+    size += writeShort(out, entry.getCompressionMethod());
+    // Modification time.
+    size += writeInt(out, entry.getTime());
+    size += writeInt(out, entry.getCrc());
+    size += writeInt(out, zip64MagicVal(entry.getCompressedSize()));
+    size += writeInt(out, zip64MagicVal(entry.getSize()));
+
+    byte[] nameBytes = entry.getName().getBytes(StandardCharsets.UTF_8);
+    long externalAttributes = entry.getExternalAttributes();
+    // Length of name.
+    size += writeShort(out, nameBytes.length);
+    // Length of extra data.
+    size += writeShort(out, extraDataLength);
+    // Length of file comment.
+    size += writeShort(out, 0);
+    // Disk on which file starts.
+    size += writeShort(out, 0);
+    // internal file attributes (unknown)
+    size += writeShort(out, 0);
+    // external file attributes
+    size += writeInt(out, externalAttributes);
+    // Offset of local file header.
+    size += writeInt(out, zip64MagicVal(entry.getOffset()));
+    out.write(nameBytes);
+    size += nameBytes.length;
+
+    if (useZip64) {
+      size += writeShort(out, ZipConstants.ZIP64_EXTID);
+      size += writeShort(out, zip64DataLength);
+      if (isZip64MagicVal(entry.getSize())) {
+        size += writeLong(out, entry.getSize());
+      }
+      if (isZip64MagicVal(entry.getCompressedSize())) {
+        size += writeLong(out, entry.getCompressedSize());
+      }
+      if (isZip64MagicVal(entry.getOffset())) {
+        size += writeLong(out, entry.getOffset());
+      }
+    }
+    return size;
+  }
+
+  static boolean isZip64MagicVal(long value) {
+    return value >= ZipConstants.ZIP64_MAGICVAL;
+  }
+
+  static long zip64MagicVal(long value) {
+    return Math.min(value, ZipConstants.ZIP64_MAGICVAL);
+  }
+
+  static boolean isZip64MagicCount(int value) {
+    return value >= ZipConstants.ZIP64_MAGICCOUNT;
+  }
+
+  static int zip64MagicCount(int value) {
+    return Math.min(value, ZipConstants.ZIP64_MAGICCOUNT);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryFileHeader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryFileHeader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryFileHeader.java
@@ -0,0 +1,224 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static com.facebook.buck.util.zip.ByteIo.readInt;
+import static com.facebook.buck.util.zip.ByteIo.readLong;
+import static com.facebook.buck.util.zip.ByteIo.readShort;
+import static com.facebook.buck.util.zip.ByteIo.readUnsignedInt;
+import static com.facebook.buck.util.zip.CentralDirectory.isZip64MagicVal;
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.util.zip.ZipEntry.CENCOM;
+import static java.util.zip.ZipEntry.CENEXT;
+import static java.util.zip.ZipEntry.CENHDR;
+import static java.util.zip.ZipEntry.CENLEN;
+import static java.util.zip.ZipEntry.CENNAM;
+import static java.util.zip.ZipEntry.CENOFF;
+import static java.util.zip.ZipEntry.CENSIG;
+import static java.util.zip.ZipEntry.CENSIZ;
+
+import java.util.Objects;
+
+/**
+ * Class that represents a Central Directory File Header in a ZIP archive. It provides methods to
+ * read and parse the header data from a byte array. Reading Header Data: Parsing Header Fields: The
+ * class parses the header fields, including the file name, compressed size, uncompressed size, and
+ * offset. Providing Accessors: The class provides accessor methods for the parsed header fields,
+ * allowing users to retrieve the values.
+ */
+public class CentralDirectoryFileHeader {
+
+  private int headerOffset;
+  private String name = "";
+  private long compressedSize;
+  private long uncompressedSize;
+  private long offset;
+
+  private int nameSize;
+  private int extraSize;
+  private int commSize;
+
+  /**
+   * Read a CENHDR header from a byte array in a given offset.
+   *
+   * @param buffer Byte array which contains the header.
+   * @param headerOffset Offset of the location of the header in the buffer.
+   * @return true if the buffer contains a header and it could be read, otherwise false.
+   */
+  boolean read(final byte[] buffer, int headerOffset) {
+
+    final int headerLimit = headerOffset + CENHDR;
+
+    if (headerLimit >= buffer.length || readInt(buffer, headerOffset) != CENSIG) {
+      // no more CD Files
+      return false;
+    }
+
+    this.headerOffset = headerOffset;
+    this.compressedSize = readUnsignedInt(buffer, headerOffset + CENSIZ);
+    this.uncompressedSize = readUnsignedInt(buffer, headerOffset + CENLEN);
+    this.offset = readUnsignedInt(buffer, headerOffset + CENOFF);
+    this.nameSize = readShort(buffer, headerOffset + CENNAM);
+    this.extraSize = readShort(buffer, headerOffset + CENEXT);
+    this.commSize = readShort(buffer, headerOffset + CENCOM);
+
+    if (headerLimit + this.nameSize <= buffer.length) {
+      this.name = new String(buffer, headerLimit, this.nameSize, UTF_8);
+    }
+
+    // zip64
+    if (isZip64()) {
+
+      int fieldsOffset = headerLimit + this.nameSize;
+      int fieldsLimit = fieldsOffset + this.extraSize;
+
+      while (fieldsOffset + 4 < fieldsLimit) {
+
+        int extraFieldsTag = readShort(buffer, fieldsOffset);
+        int extraFieldsSize = readShort(buffer, fieldsOffset + 2);
+
+        fieldsOffset += 4;
+
+        if (fieldsOffset + extraFieldsSize > fieldsLimit) {
+          // invalid extra fields
+          return false;
+        }
+
+        if (extraFieldsTag == ZipConstants.ZIP64_EXTID) {
+          if (isZip64MagicVal(this.uncompressedSize)) {
+            if (extraFieldsSize < 8 || fieldsOffset + 8 > fieldsLimit) {
+              return false;
+            }
+            this.uncompressedSize = readLong(buffer, fieldsOffset);
+            extraFieldsSize -= 8;
+            fieldsOffset += 8;
+          }
+          if (isZip64MagicVal(this.compressedSize)) {
+            if (extraFieldsSize < 8 || fieldsOffset + 8 > fieldsLimit) {
+              return false;
+            }
+            this.compressedSize = readLong(buffer, fieldsOffset);
+            extraFieldsSize -= 8;
+            fieldsOffset += 8;
+          }
+          if (isZip64MagicVal(this.offset)) {
+            if (extraFieldsSize < 8 || fieldsOffset + 8 > fieldsLimit) {
+              return false;
+            }
+            this.offset = readLong(buffer, fieldsOffset);
+          }
+          break;
+        } else {
+          // skip to next extra field group
+          fieldsOffset += extraFieldsSize;
+        }
+      }
+    }
+    return true;
+  }
+
+  boolean isZip64() {
+    return isZip64MagicVal(compressedSize)
+        || isZip64MagicVal(uncompressedSize)
+        || isZip64MagicVal(offset);
+  }
+
+  int headerSize() {
+    return CENHDR + nameSize + extraSize + commSize;
+  }
+
+  int nextOffset() {
+    return headerOffset + headerSize();
+  }
+
+  /**
+   * @return File name entry.
+   */
+  public String getName() {
+    return name;
+  }
+
+  /**
+   * @return Offset of which LOC + Data is located.
+   */
+  public long getOffset() {
+    return offset;
+  }
+
+  /**
+   * @return compressed size in bytes.
+   */
+  public long getCompressedSize() {
+    return compressedSize;
+  }
+
+  /**
+   * @return Uncompressed size in bytes.
+   */
+  public long getUncompressedSize() {
+    return uncompressedSize;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) {
+      return true;
+    }
+    if (o == null || getClass() != o.getClass()) {
+      return false;
+    }
+    final CentralDirectoryFileHeader that = (CentralDirectoryFileHeader) o;
+    return headerOffset == that.headerOffset
+        && compressedSize == that.compressedSize
+        && uncompressedSize == that.uncompressedSize
+        && offset == that.offset
+        && nameSize == that.nameSize
+        && extraSize == that.extraSize
+        && commSize == that.commSize
+        && Objects.equals(name, that.name);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(
+        headerOffset,
+        name,
+        compressedSize,
+        uncompressedSize,
+        offset,
+        nameSize,
+        extraSize,
+        commSize);
+  }
+
+  @Override
+  public String toString() {
+    return "CentralDirectoryFileHeader{"
+        + "headerOffset="
+        + headerOffset
+        + ", name='"
+        + name
+        + '\''
+        + ", compressedSize="
+        + compressedSize
+        + ", uncompressedSize="
+        + uncompressedSize
+        + ", offset="
+        + offset
+        + ", nameSize="
+        + nameSize
+        + ", extraSize="
+        + extraSize
+        + ", commSize="
+        + commSize
+        + '}';
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryHeader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryHeader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryHeader.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static java.util.Collections.emptyList;
+import static java.util.Optional.ofNullable;
+
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * END Header fields, used to locate the ZIP Central Directory. Load existing Central Directory
+ * header information, such as offset position and previous list of files. It's used to support
+ * append operations by preserving header of previous files.
+ */
+public class CentralDirectoryHeader extends CentralDirectory {
+
+  private final Path path;
+  private final int count;
+  private final long size;
+  private final long offset;
+
+  private List<CentralDirectoryFileHeader> files;
+
+  public CentralDirectoryHeader(Path path) {
+    this(path, 0, 0, 0);
+  }
+
+  public CentralDirectoryHeader(Path path, int count, long size, long offset) {
+    this.path = path;
+    this.count = count;
+    this.size = size;
+    this.offset = offset;
+    this.files = emptyList();
+  }
+
+  public Path getPath() {
+    return path;
+  }
+
+  public List<CentralDirectoryFileHeader> getFiles() {
+    return files;
+  }
+
+  public int getCount() {
+    return count;
+  }
+
+  public long getSize() {
+    return size;
+  }
+
+  public long getOffset() {
+    return offset;
+  }
+
+  void setFiles(List<CentralDirectoryFileHeader> files) {
+    this.files = ofNullable(files).orElseGet(Collections::emptyList);
+  }
+
+  boolean isValid() {
+    return offset >= 0 && size > 0 && count > 0;
+  }
+
+  boolean isZip64() {
+    return isZip64MagicVal(offset) || isZip64MagicVal(size) || isZip64MagicCount(count);
+  }
+
+  @Override
+  public String toString() {
+    return "CentralDirectoryHeader{"
+        + "path="
+        + path
+        + ", count="
+        + count
+        + ", size="
+        + size
+        + ", offset="
+        + offset
+        + ", files="
+        + files.size()
+        + '}';
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryReader.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryReader.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CentralDirectoryReader.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static com.facebook.buck.util.zip.ByteIo.*;
+import static java.lang.Math.toIntExact;
+import static java.nio.file.StandardOpenOption.READ;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.SeekableByteChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.zip.ZipEntry;
+
+/**
+ * Utility class designed to read and parse the central directory of a ZIP file. The central
+ * directory is a critical component of a ZIP file, containing metadata about the files within the
+ * archive. The class parses the central directory header, extracting essential information such as
+ * the number of files, total size, and offset.
+ */
+public class CentralDirectoryReader {
+
+  /**
+   * @param src file to load the header information
+   * @return Central directory with preloaded files (CENSIG list)
+   * @throws IOException In case it fails to read the src information.
+   * @see #readCentralDirectory(Path, boolean)
+   */
+  public CentralDirectoryHeader readCentralDirectory(final Path src) throws IOException {
+    return readCentralDirectory(src, true);
+  }
+
+  /**
+   * @param src file to load the header information
+   * @param readFiles If it should parse CD in order to load file headers.
+   * @return Central directory with preloaded files (CENSIG list)
+   * @throws IOException In case it fails to read the src information.
+   */
+  public CentralDirectoryHeader readCentralDirectory(final Path src, final boolean readFiles)
+      throws IOException {
+    if (Files.exists(src)) {
+      try (final SeekableByteChannel byteChannel = Files.newByteChannel(src, READ)) {
+
+        final long fileSize = byteChannel.size();
+        // Central Directory header will be on the last 64kb of the file
+        final int headerSize = (int) Math.min(fileSize, ZipConstants.END_MAXLEN);
+        final long headerOffset = fileSize - headerSize;
+
+        // not enough data or invalid
+        if (fileSize >= headerSize) {
+
+          final ByteBuffer headerBuffer = readBytes(byteChannel, headerOffset, headerSize);
+          final CentralDirectoryHeader header =
+              readCentralDirectory(src, headerBuffer.rewind(), headerOffset);
+
+          if (header != null && header.isValid()) {
+            if (readFiles) {
+              final ByteBuffer centralDirectoryBuffer =
+                  readBytes(byteChannel, header.getOffset(), header.getSize());
+              header.setFiles(readFileHeaders(centralDirectoryBuffer.rewind(), header.getCount()));
+            }
+            return header;
+          }
+        }
+      }
+    }
+    return new CentralDirectoryHeader(src);
+  }
+
+  /**
+   * @param src Path to zip to read its Central Directory
+   * @param headerBuffer Buffer containing Central Directory headers.
+   * @param bufferOffset position at the file which the buffer is positioned.
+   * @return Central Directory Header
+   * @throws IOException In case it fails to read the header.
+   */
+  private CentralDirectoryHeader readCentralDirectory(
+      final Path src, final ByteBuffer headerBuffer, final long bufferOffset) throws IOException {
+    // position channel to read the last block of the file.
+    final byte[] buffer = headerBuffer.array();
+    final int bufferSize = headerBuffer.remaining();
+    final long totalSize = bufferOffset + bufferSize;
+    // scan the block backwards for ENDSIG header signature
+    for (int pos = bufferSize - ZipEntry.ENDHDR; pos >= 0; pos--) {
+      if (readInt(buffer, pos) == ZipEntry.ENDSIG) {
+        // Offset of the start of the central directory.
+        final CentralDirectoryHeader header =
+            new CentralDirectoryHeader(
+                src,
+                readShort(buffer, pos + ZipEntry.ENDTOT),
+                readUnsignedInt(buffer, pos + ZipEntry.ENDSIZ),
+                readUnsignedInt(buffer, pos + ZipEntry.ENDOFF));
+        // if theres no zip64 magic values.
+        if (header.isZip64()) {
+          int end64Pos = pos - ZipConstants.ZIP64_LOCHDR;
+          // check if zip64 signature is available
+          if (end64Pos <= 0 || readInt(buffer, end64Pos) != ZipConstants.ZIP64_LOCSIG) {
+            return header;
+          }
+          // read zip64 offset in the file
+          long end64Offset = readLong(buffer, end64Pos + ZipConstants.ZIP64_LOCOFF);
+          // has to be a position within the tail.
+          if (end64Offset < bufferOffset || end64Offset > totalSize) {
+            return header;
+          }
+          // recalculate offset inside the buffer
+          end64Pos = (int) (end64Offset - bufferOffset);
+          // if the position is ENDSIG
+          if (readInt(buffer, end64Pos) == ZipConstants.ZIP64_ENDSIG) {
+            final CentralDirectoryHeader header64 =
+                new CentralDirectoryHeader(
+                    src,
+                    toIntExact(readLong(buffer, end64Pos + ZipConstants.ZIP64_ENDTOT)),
+                    readLong(buffer, end64Pos + ZipConstants.ZIP64_ENDSIZ),
+                    readLong(buffer, end64Pos + ZipConstants.ZIP64_ENDOFF));
+            if (header64.isValid()) {
+              return header64;
+            }
+          }
+        }
+        return header;
+      }
+    }
+    return null;
+  }
+
+  /**
+   * Read all CDFile headers within the buffer.
+   *
+   * @param buffer Buffer that contains all Central Directory headers.
+   * @param expectedSize Expected number of file headers, obtained from EOCD
+   * @return All File headers.
+   */
+  private List<CentralDirectoryFileHeader> readFileHeaders(
+      final ByteBuffer buffer, final int expectedSize) {
+
+    final byte[] bytes = buffer.array();
+    final List<CentralDirectoryFileHeader> files = new ArrayList<>(expectedSize);
+
+    // verify is a header CDFile header block is available
+    int offset = 0;
+    while (files.size() < expectedSize) {
+      final CentralDirectoryFileHeader file = new CentralDirectoryFileHeader();
+      if (!file.read(bytes, offset)) {
+        break;
+      }
+      files.add(file);
+      offset = file.nextOffset();
+    }
+    return files;
+  }
+
+  /**
+   * Reads a specified number of bytes from a seek-able channel at a given offset and returns them
+   * as a ByteBuffer.
+   */
+  private ByteBuffer readBytes(SeekableByteChannel byteChannel, long offset, long size)
+      throws IOException {
+    final ByteBuffer buffer = ByteBuffer.allocate(toIntExact(size));
+    byteChannel.position(offset);
+    // try to fill the buffer
+    while (buffer.hasRemaining()) {
+      if (byteChannel.read(buffer) <= 0) {
+        break;
+      }
+    }
+    // buffer not fully read
+    if (buffer.hasRemaining()) {
+      throw new IOException(String.format("failed to read %s bytes at offset %s", size, offset));
+    }
+    return buffer;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ConcatJarBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ConcatJarBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ConcatJarBuilder.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static java.util.Optional.ofNullable;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Class designed to create a new JAR file by concatenating the contents of multiple existing JAR
+ * files. It extends the JarBuilder class and provides additional functionality for handling merging
+ * logic of resource files.
+ */
+public class ConcatJarBuilder extends JarBuilder {
+
+  private final List<AbsPath> entriesToJar = new LinkedList<>();
+  private final List<AbsPath> overrideEntriesToJar = new LinkedList<>();
+
+  /**
+   * Creates a new JAR file at the specified output path by concatenating the contents of multiple
+   * input JAR files.
+   */
+  protected CustomJarOutputStream getJarOutputStream(final Path appendJar, final Path outputFile)
+      throws IOException {
+
+    final ConcatenateJars concatenateJars =
+        new ConcatenateJars().removeEntries(getRemoveEntryPredicate());
+
+    ofNullable(appendJar)
+        .map(Path::toAbsolutePath)
+        .map(AbsPath::of)
+        .ifPresent(concatenateJars::addJar);
+
+    entriesToJar.forEach(concatenateJars::addJar);
+    overrideEntriesToJar.forEach(concatenateJars::addJarOverride);
+
+    return concatenateJars.appendableOutputStream(outputFile);
+  }
+
+  @Override
+  public JarBuilder setEntriesToJar(final Iterable<AbsPath> entries) {
+    final List<AbsPath> jars = toList(entries);
+    entriesToJar.addAll(jars);
+    return super.setEntriesToJar(jars);
+  }
+
+  @Override
+  public JarBuilder setOverrideEntriesToJar(final Iterable<AbsPath> entries) {
+    final List<AbsPath> jars = toList(entries);
+    overrideEntriesToJar.addAll(jars);
+    return super.setOverrideEntriesToJar(jars);
+  }
+
+  private List<AbsPath> toList(Iterable<AbsPath> entries) {
+    // An Iterable might be iterable only once, so we convert it to a list.
+    final List<AbsPath> jars = new ArrayList<>();
+    entries.forEach(jars::add);
+    return jars;
+  }
+
+  /** All concatenated jars are read only, and are already written into the final jar. */
+  protected JarEntryContainer toJarEntryContainer(final Path jar) {
+    return JarEntryContainer.readOnlyJar(jar);
+  }
+
+  /**
+   * Make addToEntries parallel, given it won't write to the output, add just update entries with
+   * new offset.
+   */
+  protected void addToEntries(
+      final Collection<JarEntrySupplier> sortedEntries,
+      final List<JarEntryContainer> sourceContainers)
+      throws IOException {
+
+    final List<JarEntrySupplier> collectedEntries =
+        sourceContainers.parallelStream()
+            .flatMap(
+                c -> {
+                  try {
+                    return c.stream();
+                  } catch (IOException e) {
+                    throw new UncheckedIOException(e);
+                  }
+                })
+            .collect(Collectors.toList());
+
+    sortedEntries.addAll(collectedEntries);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ConcatenateJars.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ConcatenateJars.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ConcatenateJars.java
@@ -0,0 +1,361 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static java.nio.file.StandardOpenOption.APPEND;
+import static java.nio.file.StandardOpenOption.CREATE;
+import static java.nio.file.StandardOpenOption.READ;
+import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
+import static java.nio.file.StandardOpenOption.WRITE;
+import static java.util.Comparator.comparing;
+import static java.util.Objects.requireNonNull;
+import static java.util.stream.Collectors.partitioningBy;
+import static java.util.stream.Collectors.toList;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.channels.FileChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Predicate;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.stream.Stream;
+
+/**
+ * This class directly copies compressed data blocks from multiple JAR files and merges them into a
+ * single JAR. A new Central Directory is created with updated relative offsets to reference the
+ * combined content.
+ *
+ * <p>Advantages:
+ *
+ * <ul>
+ *   <li>Significantly faster: Avoids the overhead of decompressing, merging, and recompressing JAR
+ *       files in memory.
+ *   <li>Preserves compression: Maintains original compression levels for optimal storage
+ *       efficiency.
+ * </ul>
+ *
+ * <p>Important:
+ *
+ * <p>Duplicate entries: If a class or resource exists in multiple input JARs, the last occurrence
+ * will be retained in the final output JAR.
+ */
+public class ConcatenateJars {
+
+  public static final Predicate<? super CustomZipEntry> DONT_EXCLUDE = (name) -> false;
+
+  /**
+   * Represents a JAR file that has been relocated to a new offset in a larger archive. It contains
+   * information about the original JAR file, its updated offset, and its relocated entries.
+   */
+  static class RelocatedJar {
+
+    private final AbsPath jar;
+    private final CentralDirectoryHeader header;
+    private final long relocatedOffset;
+    private final List<EntryAccounting> relocatedEntries;
+
+    RelocatedJar(
+        final AbsPath jar,
+        final CentralDirectoryHeader header,
+        final long relocatedOffset,
+        final List<EntryAccounting> relocatedEntries) {
+      this.jar = jar;
+      this.header = header;
+      this.relocatedOffset = relocatedOffset;
+      this.relocatedEntries = relocatedEntries;
+    }
+
+    @Override
+    public String toString() {
+      return Objects.toString(path());
+    }
+
+    AbsPath jar() {
+      return jar;
+    }
+
+    Path path() {
+      return jar.getPath();
+    }
+
+    CentralDirectoryHeader header() {
+      return requireNonNull(header);
+    }
+
+    long dataSize() {
+      return header.getOffset();
+    }
+
+    long relocatedOffset() {
+      return relocatedOffset;
+    }
+
+    Stream<EntryAccounting> entries() {
+      return relocatedEntries.stream();
+    }
+  }
+
+  private final CentralDirectoryReader directoryReader = new CentralDirectoryReader();
+
+  private final Set<AbsPath> jars = new LinkedHashSet<>();
+  private final Set<AbsPath> overrideJars = new LinkedHashSet<>();
+
+  private boolean sortEntries = true;
+  private boolean discardDirectories = true;
+  private Predicate<? super CustomZipEntry> removeEntries = DONT_EXCLUDE;
+
+  /**
+   * Filter used to discard entries from the final merged index.
+   *
+   * @param excludeEntries predicate that test if an entry should be excluded.
+   * @return this builder instance for method chaining
+   */
+  public ConcatenateJars removeEntries(Predicate<? super CustomZipEntry> removeEntries) {
+    this.removeEntries = removeEntries != null ? removeEntries : DONT_EXCLUDE;
+    return this;
+  }
+
+  /**
+   * Adds a JAR file to the list of JARs to be concatenated.
+   *
+   * @param jar the path to the JAR file to add
+   * @return this builder instance for method chaining
+   * @see #addJarOverride(AbsPath)
+   */
+  public ConcatenateJars addJar(final AbsPath jar) {
+    this.jars.add(jar);
+    return this;
+  }
+
+  /**
+   * Adds a JAR file to the list of override JARs to be concatenated.
+   *
+   * @param jar the path to the JAR file to add
+   * @return this builder instance for method chaining
+   * @see #addJar(AbsPath)
+   */
+  public ConcatenateJars addJarOverride(final AbsPath jar) {
+    this.overrideJars.add(jar);
+    return this;
+  }
+
+  /**
+   * If true, keep compatibility with JarBuilder entry orders.
+   *
+   * @param sortEntries If entries should be sorted to preserve natural order.
+   */
+  public void setSortEntries(final boolean sortEntries) {
+    this.sortEntries = sortEntries;
+  }
+
+  /**
+   * If true, keep compatibility with JarBuilder entries.
+   *
+   * @param discardDirectories If entries that are directories should be discarded.
+   */
+  public void setDiscardDirectories(final boolean discardDirectories) {
+    this.discardDirectories = discardDirectories;
+  }
+
+  /**
+   * @param output Location of the final jar.
+   * @return JAR OutputStream which all jars already concatenated, which can be used to add new
+   *     entries.
+   * @throws IOException In case it fail to concatenate jars.
+   */
+  public CustomJarOutputStream appendableOutputStream(final Path output) throws IOException {
+    // read and process relocated jars
+    final List<RelocatedJar> relocatedJars = relocateJars();
+
+    // concat all data segments of all jars
+    final long currentOffset = transferJars(relocatedJars, output);
+
+    // create an appendable outputStream with buffer
+    final AppendingZipOutputStreamImpl appendStream = newAppendStream(output);
+
+    // partition jars and override jars
+    final Map<Boolean, List<RelocatedJar>> overridePartition =
+        relocatedJars.stream().collect(partitioningBy(this::isOverride));
+    final Stream<EntryAccounting> entries =
+        overridePartition.get(Boolean.FALSE).stream().flatMap(RelocatedJar::entries);
+    final Stream<EntryAccounting> overrideEntries =
+        overridePartition.get(Boolean.TRUE).stream().flatMap(RelocatedJar::entries);
+
+    if (sortEntries) {
+      // backward compatibility with JarBuilder ordering, which select the first occurrency
+      entries
+          .sorted(comparing(EntryAccounting::getName))
+          .filter(entry -> !appendStream.hasEntry(entry.getName()))
+          .filter(this::shouldSkipEntry)
+          .forEach(appendStream::addEntry);
+    } else {
+      entries.filter(this::shouldSkipEntry).forEach(appendStream::addEntry);
+    }
+    // add entries that override at the end
+    overrideEntries.filter(this::shouldSkipEntry).forEach(appendStream::addEntry);
+    // reposition the current offset
+    appendStream.setCurrentOffset(currentOffset);
+    // return stream that will allow
+    return new CustomJarOutputStream(appendStream);
+  }
+
+  private boolean shouldSkipEntry(final EntryAccounting entry) {
+    final CustomZipEntry zipEntry = new CustomZipEntry(entry.getName());
+    return !removeEntries.test(zipEntry);
+  }
+
+  private boolean isOverride(final RelocatedJar relocatedJar) {
+    return overrideJars.contains(relocatedJar.jar());
+  }
+
+  private AppendingZipOutputStreamImpl newAppendStream(final Path output) throws IOException {
+    return new AppendingZipOutputStreamImpl(
+        new BufferedOutputStream(Files.newOutputStream(output, APPEND, WRITE)), false);
+  }
+
+  /**
+   * Relocates a collection of JAR files to new offsets. Will concatenate jars and override jars
+   * respecting its order.
+   *
+   * @return a list of relocated JAR files with their updated offsets and entries
+   */
+  private List<RelocatedJar> relocateJars() {
+    final AtomicLong currentOffset = new AtomicLong();
+    return Stream.concat(jars.stream(), overrideJars.stream())
+        .map(
+            jar -> {
+              final CentralDirectoryHeader header = readCentralDirectory(jar);
+              final long relocatedOffset = currentOffset.getAndAdd(header.getOffset());
+              final List<EntryAccounting> relocatedEntries =
+                  relocateEntries(header, relocatedOffset);
+
+              return new RelocatedJar(jar, header, relocatedOffset, relocatedEntries);
+            })
+        .collect(toList());
+  }
+
+  /**
+   * Reads the central directory header of a JAR file.
+   *
+   * @param jar the absolute path to the JAR file
+   * @return the central directory header of the JAR file
+   * @throws UncheckedIOException if an I/O error occurs while reading the JAR file
+   */
+  private CentralDirectoryHeader readCentralDirectory(final AbsPath jar) {
+    try {
+      return directoryReader.readCentralDirectory(jar.getPath());
+    } catch (IOException e) {
+      throw new UncheckedIOException("failed to read JAR header of " + jar.getPath(), e);
+    }
+  }
+
+  /**
+   * Relocates the entries of a JAR file to a new offset.
+   *
+   * @param header the central directory header of the JAR file
+   * @param relocatedOffset the new offset to relocate the entries to
+   * @return a list of entries with the updated offsets
+   */
+  private List<EntryAccounting> relocateEntries(
+      final CentralDirectoryHeader header, final long relocatedOffset) {
+    try (final JarFile jar = new JarFile(header.getPath().toFile(), false)) {
+
+      final List<EntryAccounting> entries = new ArrayList<>(header.getCount());
+
+      for (final CentralDirectoryFileHeader file : header.getFiles()) {
+        // JarBuilder will exclude directories and recreate it
+        if (discardDirectories && file.getName().endsWith("/")) {
+          continue;
+        }
+        final JarEntry entry = jar.getJarEntry(file.getName());
+        // add entry again to recompute the new offset
+        entries.add(new EntryAccounting(new JarEntry(entry), relocatedOffset + file.getOffset()));
+      }
+
+      return entries;
+    } catch (IOException e) {
+      throw new UncheckedIOException("failed to relocate jar " + header.getPath(), e);
+    }
+  }
+
+  /**
+   * Transfers the contents of a collection of relocated JAR files to a single output file.
+   *
+   * @param relocatedJars an iterable collection of relocated JAR files to transfer
+   * @param output the path to the output file
+   * @return the total number of bytes transferred
+   * @throws IOException if an I/O error occurs during the transfer
+   */
+  private long transferJars(final Iterable<RelocatedJar> relocatedJars, final Path output)
+      throws IOException {
+    try (final FileChannel outputChannel =
+        FileChannel.open(output, CREATE, TRUNCATE_EXISTING, WRITE)) {
+
+      outputChannel.truncate(0);
+      outputChannel.position(0);
+
+      long written = 0;
+      for (RelocatedJar relocatedJar : relocatedJars) {
+        try (FileChannel inputChannel = FileChannel.open(relocatedJar.jar().getPath(), READ)) {
+
+          if (written != relocatedJar.relocatedOffset()) {
+            throw new IOException(
+                String.format(
+                    "current position %s is different from relocated offset (%s) at %s",
+                    written, relocatedJar.relocatedOffset(), relocatedJar.path()));
+          }
+
+          final long dataSize = relocatedJar.dataSize();
+          final long transferred = transferTo(inputChannel, dataSize, outputChannel);
+
+          if (transferred != dataSize) {
+            throw new IOException(
+                String.format(
+                    "failed to transfer %s bytes from %s",
+                    dataSize - transferred, relocatedJar.path()));
+          }
+          written += transferred;
+        }
+      }
+      return written;
+    }
+  }
+
+  /**
+   * Transfers data from an input file channel to an output file channel.
+   *
+   * @param inputChannel the input file channel to read from
+   * @param size the total number of bytes to transfer
+   * @param outputChannel the output file channel to write to
+   * @return the total number of bytes transferred
+   * @throws IOException if an I/O error occurs during the transfer
+   */
+  private long transferTo(
+      final FileChannel inputChannel, final long size, final FileChannel outputChannel)
+      throws IOException {
+    long written = 0;
+    while (written < size) {
+      final long transferred = inputChannel.transferTo(written, size - written, outputChannel);
+      if (transferred > 0) {
+        written += transferred;
+      } else {
+        break;
+      }
+    }
+    return written;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomJarOutputStream.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomJarOutputStream.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomJarOutputStream.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import com.google.common.hash.HashFunction;
+import com.google.common.hash.Hasher;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.jar.JarFile;
+import java.util.zip.ZipEntry;
+import javax.annotation.Nullable;
+
+/** Extension of {@link CustomZipOutputStream} with jar-specific functionality. */
+public class CustomJarOutputStream extends CustomZipOutputStream {
+  public static final String DIGEST_ATTRIBUTE_NAME = "Murmur3-128-Digest";
+  private final HashingImpl impl;
+
+  public CustomJarOutputStream(Impl impl) {
+    this(new HashingImpl(impl));
+  }
+
+  private CustomJarOutputStream(HashingImpl impl) {
+    super(impl);
+    this.impl = impl;
+  }
+
+  public DeterministicManifest getManifest() {
+    return impl.getManifest();
+  }
+
+  public void setEntryHashingEnabled(boolean shouldHashEntries) {
+    impl.setEntryHashingEnabled(shouldHashEntries);
+  }
+
+  public void writeManifest() throws IOException {
+    impl.writeManifest();
+  }
+
+  private static class HashingImpl extends OutputStream implements Impl {
+    private static final HashFunction HASH_FUNCTION = Hashing.murmur3_128();
+
+    private final Impl inner;
+    private final DeterministicManifest manifest = new DeterministicManifest();
+    private boolean shouldHashEntries = false;
+    private boolean manifestWritten = false;
+
+    @Nullable private ZipEntry currentEntry;
+    @Nullable private Hasher hasher;
+
+    HashingImpl(Impl inner) {
+      this.inner = inner;
+    }
+
+    public DeterministicManifest getManifest() {
+      return manifest;
+    }
+
+    public void setEntryHashingEnabled(boolean shouldHashEntries) {
+      this.shouldHashEntries = shouldHashEntries;
+    }
+
+    @Override
+    public void actuallyPutNextEntry(ZipEntry entry) throws IOException {
+      inner.actuallyPutNextEntry(entry);
+
+      if (shouldHashEntries && !entry.isDirectory() && hasher == null) {
+        hasher = HASH_FUNCTION.newHasher();
+      }
+
+      currentEntry = entry;
+    }
+
+    @Override
+    public void actuallyWrite(byte[] b, int off, int len) throws IOException {
+      inner.actuallyWrite(b, off, len);
+
+      if (hasher != null) {
+        hasher.putBytes(b, off, len);
+      }
+    }
+
+    @Override
+    public void actuallyCloseEntry() throws IOException {
+      inner.actuallyCloseEntry();
+
+      if (hasher != null) {
+        if (manifestWritten) {
+          throw new IllegalStateException(
+              "Attempted to write an entry with hashing enabled after the manifest was written.");
+        }
+        manifest.setEntryAttribute(
+            currentEntry.getName(), DIGEST_ATTRIBUTE_NAME, hasher.hash().toString());
+        hasher = null;
+      }
+
+      currentEntry = null;
+    }
+
+    @Override
+    public void actuallyClose() throws IOException {
+      shouldHashEntries = false;
+      writeManifest();
+
+      inner.actuallyClose();
+    }
+
+    protected void writeManifest() throws IOException {
+      if (shouldHashEntries || manifestWritten) {
+        return;
+      }
+
+      inner.actuallyPutNextEntry(new CustomZipEntry(JarFile.MANIFEST_NAME));
+      try {
+        manifest.write(this);
+      } finally {
+        inner.actuallyCloseEntry();
+      }
+
+      manifestWritten = true;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+      actuallyWrite(b, off, len);
+    }
+
+    @Override
+    public void write(int b) {
+      throw new UnsupportedOperationException();
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipEntry.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipEntry.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipEntry.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static java.util.zip.Deflater.BEST_COMPRESSION;
+import static java.util.zip.Deflater.NO_COMPRESSION;
+
+import com.google.common.base.Preconditions;
+import java.io.File;
+import java.nio.file.Path;
+import java.util.zip.Deflater;
+import java.util.zip.ZipEntry;
+
+public class CustomZipEntry extends ZipEntry {
+
+  private int compressionLevel = Deflater.DEFAULT_COMPRESSION;
+  private long externalAttributes = 0;
+  private boolean rawCopy = false;
+
+  public CustomZipEntry(ZipEntry other) {
+    super(other);
+    setDefaultMethodAndTimeIfUnset();
+  }
+
+  public CustomZipEntry(String name) {
+    super(name);
+    setDefaultMethodAndTimeIfUnset();
+  }
+
+  public CustomZipEntry(Path path, boolean isDirectory) {
+    this(path.toString().replace(File.separatorChar, '/') + (isDirectory ? "/" : ""));
+  }
+
+  public CustomZipEntry(Path path) {
+    this(path, false);
+  }
+
+  private void setDefaultMethodAndTimeIfUnset() {
+    if (getMethod() == -1) {
+      setMethod(DEFLATED);
+    }
+    if (getTime() == -1) {
+      setFakeTime();
+    }
+  }
+
+  public void setFakeTime() {
+    setTime(ZipConstants.getFakeTime());
+  }
+
+  public void setCompressionLevel(int compressionLevel) {
+    Preconditions.checkArgument(
+        compressionLevel >= NO_COMPRESSION && compressionLevel <= BEST_COMPRESSION);
+    this.compressionLevel = compressionLevel;
+
+    // We need to update the underlying method declared
+    setMethod(compressionLevel == NO_COMPRESSION ? STORED : DEFLATED);
+
+    // Reset the various fields that need to be updated.
+    setCrc(0);
+    setSize(0);
+    setCompressedSize(0);
+  }
+
+  public int getCompressionLevel() {
+    return compressionLevel;
+  }
+
+  public long getExternalAttributes() {
+    return externalAttributes;
+  }
+
+  public void setExternalAttributes(long externalAttributes) {
+    this.externalAttributes = externalAttributes;
+  }
+
+  /**
+   * Marks this entry for raw copy mode. When set, the data written to the zip output stream is
+   * treated as pre-compressed bytes — no CRC computation or deflation is performed. The caller must
+   * set CRC, size, and compressedSize on this entry before writing.
+   */
+  public void setRawCopy(boolean rawCopy) {
+    this.rawCopy = rawCopy;
+  }
+
+  public boolean isRawCopy() {
+    return rawCopy;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipEntryWithPath.kt b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipEntryWithPath.kt
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipEntryWithPath.kt
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip
+
+import java.nio.file.Path
+import java.util.Optional
+
+data class CustomZipEntryWithPath(val entry: CustomZipEntry, val path: Optional<Path>)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipOutputStream.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipOutputStream.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/CustomZipOutputStream.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import com.google.common.base.Preconditions;
+import com.google.common.io.ByteStreams;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+
+/**
+ * An implementation of an {@link OutputStream} that will zip output. Note that, just as with {@link
+ * java.util.zip.ZipOutputStream}, no implementation of this is thread-safe.
+ */
+public class CustomZipOutputStream extends OutputStream {
+
+  protected interface Impl {
+    /**
+     * Called by {@link CustomZipOutputStream#putNextEntry(ZipEntry)} and used by impls to put the
+     * next entry into the zip file. It is guaranteed that the {@code entry} won't be null and the
+     * stream will be open. It is also guaranteed that there's no current entry open.
+     *
+     * @param entry The {@link ZipEntry} to write.
+     */
+    void actuallyPutNextEntry(ZipEntry entry) throws IOException;
+
+    /**
+     * Called by {@link CustomZipOutputStream#close()} and used by impls to close the delegate
+     * stream. This method will be called at most once in the lifecycle of the
+     * CustomZipOutputStream.
+     */
+    void actuallyCloseEntry() throws IOException;
+
+    /**
+     * Called by {@link CustomZipOutputStream#write(byte[], int, int)} only once it is known that
+     * the stream has not been closed, and that a {@link ZipEntry} has already been put on the
+     * stream and not closed.
+     */
+    void actuallyWrite(byte[] b, int off, int len) throws IOException;
+
+    void actuallyClose() throws IOException;
+  }
+
+  private final Impl impl;
+
+  private State state;
+  private boolean entryOpen;
+
+  protected CustomZipOutputStream(Impl impl) {
+    this.impl = impl;
+    this.state = State.CLEAN;
+  }
+
+  public final void putNextEntry(ZipEntry entry) throws IOException {
+    Preconditions.checkState(state != State.CLOSED, "Stream has been closed.");
+
+    state = State.OPEN;
+    closeEntry();
+    validateEntry(entry);
+    impl.actuallyPutNextEntry(entry);
+    entryOpen = true;
+  }
+
+  private void validateEntry(ZipEntry entry) {
+    if (entry.getMethod() == ZipEntry.STORED) {
+      Preconditions.checkState(
+          entry.getCompressedSize() == entry.getSize(),
+          "STORED entry where compressed != uncompressed size");
+    }
+  }
+
+  public final void closeEntry() throws IOException {
+    Preconditions.checkState(state != State.CLOSED, "Stream has been closed");
+    if (!entryOpen) {
+      return; // As ZipOutputStream does.
+    }
+
+    entryOpen = false;
+    impl.actuallyCloseEntry();
+  }
+
+  @Override
+  public final void write(byte[] b, int off, int len) throws IOException {
+    Preconditions.checkState(state != State.CLOSED, "Stream has been closed.");
+    if (!entryOpen) {
+      // Same exception as Java's ZipOutputStream.
+      throw new ZipException("no current ZIP entry");
+    }
+
+    impl.actuallyWrite(b, off, len);
+  }
+
+  // javadocs taken from OutputStream and amended to make it clear what we're doing here.
+  /**
+   * Writes the specified byte to this output stream. Specifically one byte is written to the output
+   * stream. The byte to be written is the eight low-order bits of the argument <code>b</code>. The
+   * 24 high-order bits of <code>b</code> are ignored.
+   *
+   * @param b the <code>byte</code>.
+   * @exception IOException if an I/O error occurs. In particular, an <code>IOException</code> may
+   *     be thrown if the output stream has been closed.
+   */
+  @Override
+  public void write(int b) throws IOException {
+    byte[] buf = new byte[1];
+    buf[0] = (byte) (b & 0xff);
+    write(buf, 0, 1);
+  }
+
+  public void writeEntry(String name, InputStream contents) throws IOException {
+    try {
+      putNextEntry(new CustomZipEntry(name));
+      ByteStreams.copy(contents, this);
+      closeEntry();
+    } finally {
+      contents.close();
+    }
+  }
+
+  @Override
+  public final void close() throws IOException {
+    if (state == State.CLOSED) {
+      return; // no-op to call close again.
+    }
+
+    try {
+      closeEntry();
+      impl.actuallyClose();
+    } finally {
+      state = State.CLOSED;
+    }
+  }
+
+  /**
+   * State of a {@link CustomZipOutputStream}. Certain operations are only available when the stream
+   * is in a particular state.
+   */
+  private enum State {
+    CLEAN, // Open but no data written.
+    OPEN, // Open and data written.
+    CLOSED, // Just as it says on the tin.
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DeterministicManifest.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DeterministicManifest.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DeterministicManifest.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Comparator;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+
+/**
+ * A manifest implementation whose formatted output is deterministic given the same input (entries
+ * and attributes are sorted). The JDK implementation in {@code java.util.Manifest} does not have
+ * this property.
+ */
+public class DeterministicManifest extends Manifest {
+  private static final String NEW_LINE = "\r\n"; // For some reason JAR manifests use CRLF
+  private static final String NEW_LINE_AND_SPACE = "\r\n ";
+  private static final int MAX_LINE_LENGTH = 72;
+  private static final int NEW_LINE_LENGTH = NEW_LINE.length();
+
+  public DeterministicManifest() {}
+
+  public DeterministicManifest(InputStream is) throws IOException {
+    super(is);
+  }
+
+  public DeterministicManifest(Manifest man) {
+    super(man);
+  }
+
+  public void setEntryAttribute(String entryName, String key, String value) {
+    Attributes attributes = getAttributes(entryName);
+    if (attributes == null) {
+      attributes = new Attributes();
+      getEntries().put(entryName, attributes);
+    }
+
+    attributes.putValue(key, value);
+  }
+
+  public void setManifestAttribute(String key, String value) {
+    getMainAttributes().putValue(key, value);
+  }
+
+  public boolean hasEntries() {
+    return !getEntries().isEmpty();
+  }
+
+  @Override
+  public void write(OutputStream out) throws IOException {
+    writeAttributes(getMainAttributes(), out);
+
+    List<String> sortedEntryNames =
+        getEntries().keySet().stream().sorted().collect(Collectors.toList());
+
+    for (String entryName : sortedEntryNames) {
+      writeEntry(entryName, out);
+    }
+  }
+
+  private void writeEntry(String entryName, OutputStream out) throws IOException {
+    writeKeyValue("Name", entryName, out);
+
+    writeAttributes(getAttributes(entryName), out);
+  }
+
+  private void writeAttributes(Attributes attributes, OutputStream out) throws IOException {
+    List<Attributes.Name> sortedNames =
+        attributes.keySet().stream()
+            .map(a -> (Attributes.Name) a)
+            .sorted(Comparator.comparing(Attributes.Name::toString))
+            .collect(Collectors.toList());
+
+    for (Attributes.Name name : sortedNames) {
+      writeKeyValue(name.toString(), attributes.getValue(name), out);
+    }
+
+    writeLine(out);
+  }
+
+  private void writeKeyValue(String key, String value, OutputStream out) throws IOException {
+    StringBuilder builder = new StringBuilder();
+
+    builder.append(key);
+    builder.append(": ");
+    builder.append(value);
+    builder.append(NEW_LINE);
+
+    // Manifest files expect each line to be no longer than 72 characters (including line
+    // endings), and continuation lines start with a single space.
+    int start = 0;
+    while (builder.length() - start > MAX_LINE_LENGTH) {
+      builder.insert(start + MAX_LINE_LENGTH - NEW_LINE_LENGTH, NEW_LINE_AND_SPACE);
+      start += MAX_LINE_LENGTH;
+    }
+
+    out.write(builder.toString().getBytes(StandardCharsets.UTF_8));
+  }
+
+  private void writeLine(OutputStream out) throws IOException {
+    out.write(NEW_LINE.getBytes(StandardCharsets.UTF_8));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DeterministicZipBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DeterministicZipBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DeterministicZipBuilder.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import com.google.common.io.ByteStreams;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.zip.CRC32;
+
+public class DeterministicZipBuilder implements Closeable {
+  // TODO(cjhopman): Should this buffer the entries and then sort them by name? We may have to
+  // buffer them on disk to keep memory use sensible.
+  private final CustomZipOutputStream output;
+
+  public DeterministicZipBuilder(Path path) throws IOException {
+    this.output = ZipOutputStreams.newOutputStream(path);
+  }
+
+  public void addEntry(
+      InputStream data,
+      long dataLength,
+      long crc,
+      String name,
+      int compressionLevel,
+      boolean isDirectory)
+      throws IOException {
+    CustomZipEntry outputEntry = new CustomZipEntry(Paths.get(name), isDirectory);
+    outputEntry.setCompressionLevel(compressionLevel);
+    outputEntry.setCrc(crc);
+    if (compressionLevel == 0) {
+      outputEntry.setCompressedSize(dataLength);
+    }
+    outputEntry.setSize(dataLength);
+    output.putNextEntry(outputEntry);
+    ByteStreams.copy(data, output);
+    output.closeEntry();
+  }
+
+  public void addEntry(byte[] data, String name, int compressionLevel) throws IOException {
+    CustomZipEntry outputEntry = new CustomZipEntry(Paths.get(name));
+    outputEntry.setCompressionLevel(compressionLevel);
+    CRC32 crc = new CRC32();
+    crc.update(data);
+    outputEntry.setCrc(crc.getValue());
+    if (compressionLevel == 0) {
+      outputEntry.setCompressedSize(data.length);
+    }
+    outputEntry.setSize(data.length);
+    output.putNextEntry(outputEntry);
+    output.write(data);
+    output.closeEntry();
+  }
+
+  /**
+   * Adds a pre-compressed entry to the zip. The data is written directly without decompression or
+   * re-compression. The caller must provide the original entry's CRC, uncompressed size, compressed
+   * size, and compression method.
+   */
+  public void addRawEntry(
+      InputStream compressedData,
+      long compressedSize,
+      long uncompressedSize,
+      long crc,
+      int method,
+      String name)
+      throws IOException {
+    CustomZipEntry outputEntry = new CustomZipEntry(Paths.get(name));
+    outputEntry.setMethod(method);
+    outputEntry.setCrc(crc);
+    outputEntry.setSize(uncompressedSize);
+    outputEntry.setCompressedSize(compressedSize);
+    outputEntry.setRawCopy(true);
+    output.putNextEntry(outputEntry);
+    ByteStreams.copy(compressedData, output);
+    output.closeEntry();
+  }
+
+  @Override
+  public void close() throws IOException {
+    output.close();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DirectoryJarBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DirectoryJarBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DirectoryJarBuilder.java
@@ -0,0 +1,284 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static java.nio.file.Files.isDirectory;
+import static java.util.Collections.emptyList;
+import static java.util.Comparator.comparingLong;
+import static java.util.concurrent.CompletableFuture.completedFuture;
+import static java.util.concurrent.CompletableFuture.supplyAsync;
+import static java.util.stream.Collectors.partitioningBy;
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Stream.concat;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.util.zip.DirectoryJarEntryContainer.FileJarEntry;
+import com.google.common.annotations.VisibleForTesting;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeSet;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Supplier;
+import java.util.stream.Stream;
+
+/**
+ * Compress a list of directories into jars, leveraging multiple threads to maximize compression
+ * efficiency. Automatically computes the optimal number of threads based on the number of files and
+ * total byte size.
+ * <li>Asynchronously compresses groups of evenly distributed files.
+ * <li>Returns a list of temporary compressed JAR files.
+ *
+ * @see #buildJars(List)
+ * @see #computeParallelism(DirectoryJarEntryContainer)
+ * @see #buildJar(JarPartition)
+ */
+public class DirectoryJarBuilder {
+
+  /** Minimum number of bytes, to be compressed that justify another thread to split the work. */
+  static final int MIN_BYTES_PER_THREAD = 1024 * 1024;
+
+  static final int MAX_PARALLEL_THREADS =
+      Math.max(1, Runtime.getRuntime().availableProcessors() - 1);
+
+  private final Supplier<JarBuilder> builderSupplier;
+
+  private int parallelism = -1;
+
+  @VisibleForTesting
+  DirectoryJarBuilder() {
+    this(JarBuilder::new);
+  }
+
+  /**
+   * @param builderSupplier Factory method that creates the {@link JarBuilder} to be used for each
+   *     compression operation.
+   */
+  public DirectoryJarBuilder(final Supplier<JarBuilder> builderSupplier) {
+    this.builderSupplier = builderSupplier;
+  }
+
+  /**
+   * Specify the parallelism level to use as threads/partitions when compressing files. Will be
+   * considered by {@link #computeParallelism(DirectoryJarEntryContainer)} when evaluating
+   * parallelism for {@link #buildJars(Stream)}
+   *
+   * @param parallelism Number of groups/threads to be used by the {@link #buildJars(Stream)}
+   *     algorithm.
+   * @return Itself to use chain methods.
+   */
+  public DirectoryJarBuilder withParallelism(final int parallelism) {
+    this.parallelism = parallelism;
+    return this;
+  }
+
+  /**
+   * From a list of paths, partitions them into files and directories, then asynchronously
+   * compresses the directories in JAR files. The compressed JARs and the other files are returned
+   * as a single list.
+   *
+   * @see DirectoryJarEntryContainer
+   */
+  public CompletableFuture<List<AbsPath>> buildJars(final List<AbsPath> paths) {
+    // split into files and directories
+    final Map<Boolean, List<AbsPath>> partition =
+        paths.stream().collect(partitioningBy(p -> isDirectory(p.getPath())));
+
+    final List<AbsPath> files = partition.getOrDefault(Boolean.FALSE, emptyList());
+    final List<AbsPath> directories = partition.getOrDefault(Boolean.TRUE, emptyList());
+
+    // nothing to compress
+    if (directories.isEmpty()) {
+      return completedFuture(paths);
+    }
+    // compress directories asynchronously
+    final CompletableFuture<List<AbsPath>> futureJars =
+        buildJars(directories.stream().map(DirectoryJarEntryContainer::new));
+    // concatenate the compressed jars with the other files
+    return futureJars.thenApply(jars -> concat(jars.stream(), files.stream()).collect(toList()));
+  }
+
+  /**
+   * Executes parallel compression of the files by grouping them based on the computed parallelism
+   * level. This method utilizes the {@link #computeParallelism(DirectoryJarEntryContainer)} to
+   * determine the optimal number of groups, and then creates a {@link JarBuilder} for each group to
+   * generate a temporary compressed file.
+   *
+   * @param directories List of directories containing files to be compressed.
+   * @return Future to a list of compressed temporary jar files.
+   * @see #buildJar(JarPartition)
+   */
+  private CompletableFuture<List<AbsPath>> buildJars(
+      final Stream<DirectoryJarEntryContainer> directories) {
+    // for each container, split it in partitions for parallelism
+    final Collection<JarPartition> partitions =
+        directories.flatMap(this::createPartitions).collect(toList());
+    // compress each partition in parallel
+    final List<CompletableFuture<AbsPath>> futureJars =
+        partitions.stream()
+            .map(partition -> supplyAsync(() -> buildJar(partition)))
+            .collect(toList());
+    // convert to a single future to a list of paths
+    return CompletableFuture.allOf(futureJars.toArray(CompletableFuture<?>[]::new))
+        .thenApply((v) -> futureJars.stream().map(CompletableFuture::join).collect(toList()));
+  }
+
+  /**
+   * Partition the file list into N groups with approximately similar total bytes, to optimize
+   * parallel compression by balancing thread workload and maximizing compression throughput.
+   */
+  private Stream<JarPartition> createPartitions(final DirectoryJarEntryContainer directory) {
+    // file partitions ordered by its total byte size
+    final TreeSet<JarPartition> partitions = new TreeSet<>(JarPartition::compareSize);
+    // generate the computed number of partitions
+    Stream.generate(JarPartition::new)
+        .limit(computeParallelism(directory))
+        .forEach(partitions::add);
+    // sort the files by size in descending order
+    directory.getEntries().stream()
+        .sorted(comparingLong(FileJarEntry::getFileSize).reversed())
+        // distribute them evenly across partitions
+        .forEach(entry -> partitions.add(partitions.pollFirst().add(entry)));
+    // discard empty partitions
+    return partitions.stream().filter(JarPartition::hasFiles);
+  }
+
+  /**
+   * Calculates the optimal number of threads to use for processing a list of files. It will
+   * consider:
+   * <li>Total number of files.
+   * <li>Total number of bytes, divided by the average bytes per thread (@link
+   *     #AVG_BYTES_PER_THREAD).
+   *
+   *     <p>Evaluate the number of files and the number of threads to process group of files, given
+   *     the group size of {@value #MIN_BYTES_PER_THREAD} bytes.
+   *
+   *     <p>In cases where there are fewer files than available cores or insufficient bytes to
+   *     justify multiple threads, the method limits the result to the smallest value. Limiting the
+   *     number of threads to {@link #MAX_PARALLEL_THREADS}, unless specified by {@link
+   *     #parallelism}.
+   *
+   *     <p>For example, if there are 10 files but their combined size is less than 1 MB, using
+   *     multiple threads would introduce more overhead than benefits.
+   *
+   *     <p>Ceil the number of threads based on the total bytes and the minimum bytes per thread, so
+   *     it will add one thread for the remaining bytes. It doesn't use Math.ceil(double) because it
+   *     looses precision. Example: 9223372036853727744L / 1mb = 8796093022207 with remainder 512,
+   *     however when converting to double the remainder is not preserved given precision.
+   *
+   * @return The optimal number of threads required to process the given amount of files and bytes,
+   *     or the given value at {@link #parallelism}. (Within the limits 1 and {@link
+   *     #MAX_PARALLEL_THREADS})
+   */
+  private int computeParallelism(final DirectoryJarEntryContainer container) {
+    // predefined number of threads
+    if (parallelism > 0) {
+      return parallelism;
+    }
+    // compute number of bytes to be compressed
+    final long totalBytes =
+        Math.max(1, container.getEntries().stream().mapToLong(FileJarEntry::getFileSize).sum());
+    // calculate number of threads needed to process total of bytes
+    final long numberOfThreads =
+        (totalBytes / MIN_BYTES_PER_THREAD) + Math.min(totalBytes % MIN_BYTES_PER_THREAD, 1);
+    // truncate values into the boundaries [1, MAX_PARALLEL_THREADS]
+    return Math.toIntExact(Math.max(1, Math.min(numberOfThreads, MAX_PARALLEL_THREADS)));
+  }
+
+  private AbsPath buildJar(final JarPartition partition) {
+    try {
+      final AbsPath file = newTemporaryJarFile();
+      final JarBuilder builder = builderSupplier.get();
+      partition.forEach(builder::addEntry);
+      builder.createJarFile(file.getPath());
+      return file;
+    } catch (IOException e) {
+      throw new UncheckedIOException(e);
+    }
+  }
+
+  /** Creates a temporary file that will be deleted after the JVM exits. */
+  private AbsPath newTemporaryJarFile() throws IOException {
+    final Path temp = Files.createTempFile("parallel-", ".jar").toAbsolutePath();
+    temp.toFile().deleteOnExit();
+    return AbsPath.of(temp);
+  }
+
+  /**
+   * Represents a partition of a JAR file, containing a collection of files/entries and their total
+   * size in bytes.
+   */
+  static class JarPartition implements Iterable<FileJarEntry> {
+
+    /**
+     * Compares two JarPartition instances based on their total size.
+     *
+     * @param a the first JarPartition instance
+     * @param b the second JarPartition instance
+     * @return 1 if a's total size is greater than b's, -1 otherwise
+     */
+    static int compareSize(final JarPartition a, final JarPartition b) {
+      return a.totalSize > b.totalSize ? 1 : -1;
+    }
+
+    /** The total size of all files in this partition. */
+    private long totalSize;
+
+    /** The list of files in this partition. */
+    private final List<FileJarEntry> files = new LinkedList<>();
+
+    /**
+     * Adds a file to this partition and updates the total size.
+     *
+     * @param file the file to add
+     * @return this JarPartition instance
+     */
+    JarPartition add(FileJarEntry file) {
+      this.files.add(file);
+      this.totalSize += file.getFileSize();
+      return this;
+    }
+
+    /**
+     * Returns the list of files in this partition.
+     *
+     * @return the list of files
+     */
+    List<FileJarEntry> entries() {
+      return files;
+    }
+
+    /**
+     * Checks if this partition contains any files.
+     *
+     * @return true if this partition has files, false otherwise
+     */
+    boolean hasFiles() {
+      return !entries().isEmpty();
+    }
+
+    @Override
+    public Iterator<FileJarEntry> iterator() {
+      return files.iterator();
+    }
+
+    @Override
+    public String toString() {
+      return "JarPartition{ files=" + files.size() + ", totalSize=" + totalSize + "}";
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DirectoryJarEntryContainer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DirectoryJarEntryContainer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/DirectoryJarEntryContainer.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static com.google.common.base.Suppliers.memoize;
+import static java.util.Comparator.comparing;
+import static java.util.stream.Collectors.toList;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.file.MorePaths;
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.facebook.buck.util.function.ThrowingSupplier;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.nio.file.FileVisitOption;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Supplier;
+import java.util.jar.Manifest;
+import java.util.stream.Stream;
+import javax.annotation.Nullable;
+
+/**
+ * Provides all files and directories recursively contained in a given directory as entries to be
+ * added to a jar.
+ */
+class DirectoryJarEntryContainer implements JarEntryContainer {
+
+  private final Path directory;
+
+  private Supplier<List<FileJarEntry>> entriesSupplier;
+
+  DirectoryJarEntryContainer(AbsPath absPath) {
+    this(absPath.getPath());
+  }
+
+  DirectoryJarEntryContainer(Path directory) {
+    this.directory = directory;
+  }
+
+  @Nullable
+  @Override
+  public Manifest getManifest() throws IOException {
+    Path manifestPath = directory.resolve("META-INF").resolve("MANIFEST.MF");
+
+    if (!Files.isRegularFile(manifestPath)) {
+      return null;
+    }
+
+    try (InputStream manifestStream = Files.newInputStream(manifestPath)) {
+      return new Manifest(manifestStream);
+    }
+  }
+
+  public List<FileJarEntry> getEntries() {
+    return getEntriesSupplier().get();
+  }
+
+  @Override
+  public Stream<JarEntrySupplier> stream() {
+    return getEntries().stream().map(JarEntrySupplier.class::cast);
+  }
+
+  @Override
+  public void close() {
+    entriesSupplier = null;
+  }
+
+  private Supplier<List<FileJarEntry>> getEntriesSupplier() {
+    Supplier<List<FileJarEntry>> localSupplier = entriesSupplier;
+    if (localSupplier == null) {
+      entriesSupplier =
+          localSupplier =
+              memoize(
+                  () -> {
+                    try (Stream<Path> directoryStream =
+                        Files.walk(directory, FileVisitOption.FOLLOW_LINKS)) {
+                      return directoryStream
+                          .map(this::createFileJarEntry)
+                          .filter(Objects::nonNull)
+                          .sorted(comparing(FileJarEntry::getName))
+                          .collect(toList());
+                    } catch (IOException e) {
+                      throw new UncheckedIOException(e);
+                    }
+                  });
+    }
+    return localSupplier;
+  }
+
+  private FileJarEntry createFileJarEntry(final Path path) {
+    final String relativePath =
+        PathFormatter.pathWithUnixSeparators(MorePaths.relativize(directory, path));
+    if (relativePath.isEmpty()) {
+      return null;
+    }
+    return FileJarEntry.of(relativePath, path);
+  }
+
+  /**
+   * Represents a JAR entry that originates from a file. The entry name is relative to its
+   * container.
+   */
+  static class FileJarEntry extends JarEntrySupplier {
+
+    static FileJarEntry of(final String entryName, final Path file) {
+      try {
+        final boolean directory = Files.isDirectory(file);
+        final long fileSize = directory ? 0 : Files.size(file);
+        return new FileJarEntry(entryName, file, fileSize, directory);
+      } catch (IOException e) {
+        throw new UncheckedIOException(e);
+      }
+    }
+
+    private final Path file;
+    private final long fileSize;
+    private final boolean directory;
+
+    public FileJarEntry(
+        final String entryName, final Path file, final long fileSize, final boolean directory) {
+      super(new CustomZipEntry(directory ? entryName + '/' : entryName), null);
+      this.file = file;
+      this.fileSize = fileSize;
+      this.directory = directory;
+    }
+
+    public long getFileSize() {
+      return fileSize;
+    }
+
+    public boolean isDirectory() {
+      return directory;
+    }
+
+    String getName() {
+      return getEntry().getName();
+    }
+
+    @Override
+    public ThrowingSupplier<InputStream, IOException> getInputStreamSupplier() {
+      if (file == null || directory) {
+        return () -> null;
+      }
+      return () -> Files.newInputStream(file);
+    }
+
+    @Override
+    public boolean equals(Object o) {
+      if (this == o) {
+        return true;
+      }
+      if (o == null || getClass() != o.getClass()) {
+        return false;
+      }
+      final FileJarEntry that = (FileJarEntry) o;
+      return Objects.equals(getName(), that.getName());
+    }
+
+    @Override
+    public int hashCode() {
+      return Objects.hash(getName());
+    }
+
+    @Override
+    public String toString() {
+      return getName();
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/EntryAccounting.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/EntryAccounting.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/EntryAccounting.java
@@ -0,0 +1,430 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import com.google.common.hash.Hasher;
+import com.google.common.hash.Hashing;
+import com.google.common.io.CountingOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Calendar;
+import java.util.Locale;
+import java.util.zip.Deflater;
+import java.util.zip.ZipEntry;
+
+/**
+ * A wrapper containing the {@link ZipEntry} and additional book keeping information required to
+ * write the entry to a zip file.
+ */
+class EntryAccounting {
+
+  private static final ThreadLocal<Calendar> CALENDAR =
+      new ThreadLocal<Calendar>() {
+        @Override
+        protected Calendar initialValue() {
+          // We explicitly use the US locale to get a Gregorian calendar (zip file timestamps
+          // are encoded using the year, month, date, etc. in the Gregorian calendar).
+          return Calendar.getInstance(Locale.US);
+        }
+      };
+
+  private static final int DATA_DESCRIPTOR_FLAG = 1 << 3;
+  private static final int UTF8_NAMES_FLAG = 1 << 11;
+
+  private final ZipEntry entry;
+  private final Method method;
+  private Hasher crc = Hashing.crc32().newHasher();
+  private LazyDeflate deflater = new LazyDeflate();
+  private long offset;
+  private long length = 0;
+  private long externalAttributes = 0;
+
+  /**
+   * General purpose bit flag: Bit 00: encrypted file Bit 01: compression option Bit 02: compression
+   * option Bit 03: data descriptor Bit 04: enhanced deflation Bit 05: compressed patched data Bit
+   * 06: strong encryption Bit 07-10: unused Bit 11: language encoding Bit 12: reserved Bit 13: mask
+   * header values Bit 14-15: reserved
+   *
+   * <p>The important one is bit 3: the data descriptor. Defaults to indicate that names are stored
+   * as UTF8.
+   */
+  private int flags = UTF8_NAMES_FLAG;
+
+  public EntryAccounting(ZipEntry entry, long currentOffset) {
+    this.entry = entry;
+    this.offset = currentOffset;
+
+    if (entry instanceof CustomZipEntry && ((CustomZipEntry) entry).isRawCopy()) {
+      this.method = Method.RAW_COPY;
+    } else {
+      this.method = Method.detect(entry.getMethod());
+    }
+
+    if (entry.getTime() == -1) {
+      entry.setTime(System.currentTimeMillis());
+    }
+
+    if (entry instanceof CustomZipEntry) {
+      if (method != Method.RAW_COPY) {
+        deflater.setCompressionLevel(((CustomZipEntry) entry).getCompressionLevel());
+      }
+      externalAttributes = ((CustomZipEntry) entry).getExternalAttributes();
+    }
+  }
+
+  /**
+   * @return The time of the entry in DOS format.
+   */
+  public long getTime() {
+    // Calendar objects aren't thread-safe, but they're quite expensive to create, so we'll re-use
+    // them per thread.
+    Calendar instance = CALENDAR.get();
+    instance.setTimeInMillis(entry.getTime());
+
+    int year = instance.get(Calendar.YEAR);
+
+    // The DOS epoch begins in 1980. If the year is before that, then default to the start of the
+    // epoch (the 1st day of the 1st month)
+    if (year < 1980) {
+      return ZipConstants.DOS_FAKE_TIME;
+    }
+    return (year - 1980) << 25
+        | (instance.get(Calendar.MONTH) + 1) << 21
+        | instance.get(Calendar.DAY_OF_MONTH) << 16
+        | instance.get(Calendar.HOUR_OF_DAY) << 11
+        | instance.get(Calendar.MINUTE) << 5
+        | instance.get(Calendar.SECOND) >> 1;
+  }
+
+  /** Visible for test only */
+  ZipEntry getEntry() {
+    return entry;
+  }
+
+  public String getName() {
+    return entry.getName();
+  }
+
+  public long getSize() {
+    return entry.getSize();
+  }
+
+  public long getCompressedSize() {
+    return entry.getCompressedSize();
+  }
+
+  public int getFlags() {
+    return flags;
+  }
+
+  public long getOffset() {
+    return offset;
+  }
+
+  public void setOffset(long offset) {
+    this.offset = offset;
+  }
+
+  public long getCrc() {
+    return entry.getCrc();
+  }
+
+  public int getCompressionMethod() {
+    return method.compressionMethod;
+  }
+
+  public int getRequiredExtractVersion(boolean useZip64) {
+    int requiredExtractVersion;
+    if (useZip64) {
+      requiredExtractVersion = 45;
+    } else {
+      requiredExtractVersion = method.requiredVersion;
+    }
+    // Set the creator system indicator if we have UNIX-style file attributes.
+    // http://forensicswiki.org/wiki/Zip#External_file_attributes
+    if (externalAttributes >= (1 << 16)) {
+      requiredExtractVersion |= (3 << 8);
+    }
+    return requiredExtractVersion;
+  }
+
+  public long getExternalAttributes() {
+    return externalAttributes;
+  }
+
+  public long writeLocalFileHeader(OutputStream out) throws IOException {
+    if (method == Method.DEFLATE && entry instanceof CustomZipEntry) {
+      // See http://www.pkware.com/documents/casestudies/APPNOTE.TXT (section 4.4.4)
+      // Essentially, we're about to set bits 1 and 2 to indicate to tools such as zipinfo which
+      // level of compression we're using. If we've not set a compression level, then we're using
+      // the default one, which is right. It turns out. For your viewing pleasure:
+      //
+      // +----------+-------+-------+
+      // | Level    | Bit 1 | Bit 2 |
+      // +----------+-------+-------+
+      // | Fastest  |   0   |   1   |
+      // | Normal   |   0   |   0   |
+      // | Best     |   1   |   0   |
+      // +----------+-------+-------+
+      int level = ((CustomZipEntry) entry).getCompressionLevel();
+      switch (level) {
+        case Deflater.BEST_COMPRESSION:
+          flags |= (1 << 1);
+          break;
+
+        case Deflater.BEST_SPEED:
+          flags |= (1 << 2);
+          break;
+      }
+    }
+
+    if (requiresDataDescriptor()) {
+      flags |= DATA_DESCRIPTOR_FLAG;
+    }
+
+    CountingOutputStream stream = new CountingOutputStream(out);
+    ByteIo.writeInt(stream, ZipEntry.LOCSIG);
+
+    boolean useZip64;
+    useZip64 = !requiresDataDescriptor() && entry.getSize() >= ZipConstants.ZIP64_MAGICVAL;
+
+    ByteIo.writeShort(stream, getRequiredExtractVersion(useZip64));
+    ByteIo.writeShort(stream, flags);
+    ByteIo.writeShort(stream, getCompressionMethod());
+    ByteIo.writeInt(stream, getTime());
+
+    // If we don't know the size or CRC of the data in advance (such as when in deflate mode),
+    // we write zeros now, and append the actual values (the data descriptor) after the entry
+    // bytes has been fully written.
+    if (requiresDataDescriptor()) {
+      ByteIo.writeInt(stream, 0);
+      ByteIo.writeInt(stream, 0);
+      ByteIo.writeInt(stream, 0);
+    } else {
+      ByteIo.writeInt(stream, entry.getCrc());
+      if (entry.getSize() >= ZipConstants.ZIP64_MAGICVAL) {
+        ByteIo.writeInt(stream, ZipConstants.ZIP64_MAGICVAL);
+        ByteIo.writeInt(stream, ZipConstants.ZIP64_MAGICVAL);
+      } else {
+        ByteIo.writeInt(stream, entry.getCompressedSize());
+        ByteIo.writeInt(stream, entry.getSize());
+      }
+    }
+
+    byte[] nameBytes = entry.getName().getBytes(StandardCharsets.UTF_8);
+    ByteIo.writeShort(stream, nameBytes.length);
+    ByteIo.writeShort(stream, useZip64 ? ZipConstants.ZIP64_LOCHDR : 0);
+    stream.write(nameBytes);
+    if (useZip64) {
+      ByteIo.writeShort(stream, ZipConstants.ZIP64_EXTID);
+      ByteIo.writeShort(stream, 16);
+      ByteIo.writeLong(stream, entry.getSize());
+      ByteIo.writeLong(stream, entry.getCompressedSize());
+    }
+
+    return stream.getCount();
+  }
+
+  private long writeDataDescriptor(OutputStream rawOut) throws IOException {
+    if (!requiresDataDescriptor()) {
+      return 0;
+    }
+
+    CountingOutputStream out = new CountingOutputStream(rawOut);
+    ByteIo.writeInt(out, ZipEntry.EXTSIG);
+    ByteIo.writeInt(out, getCrc());
+    if (getCompressedSize() >= ZipConstants.ZIP64_MAGICVAL
+        || getSize() >= ZipConstants.ZIP64_MAGICVAL) {
+      ByteIo.writeLong(out, getCompressedSize());
+      ByteIo.writeLong(out, getSize());
+    } else {
+      ByteIo.writeInt(out, getCompressedSize());
+      ByteIo.writeInt(out, getSize());
+    }
+    return out.getCount();
+  }
+
+  public void write(OutputStream out, byte[] b) throws IOException {
+    write(out, b, 0, b.length);
+  }
+
+  public void write(OutputStream out, byte[] b, int off, int len) throws IOException {
+    if (len == 0) {
+      return;
+    }
+
+    if (method == Method.RAW_COPY) {
+      // Raw copy: write pre-compressed bytes directly, skip CRC and deflation.
+      out.write(b, off, len);
+      length += len;
+    } else {
+      updateCrc(b, off, len);
+
+      if (method == Method.STORE) {
+        out.write(b, off, len);
+        length += len;
+      } else if (method == Method.DEFLATE) {
+        deflater.write(out, b, off, len);
+      }
+    }
+  }
+
+  /**
+   * Finish the entry and return the total number of compressed bytes written (not counting the
+   * local file header, but counting the data descriptor if present). Must be called exactly once.
+   */
+  public long finish(OutputStream out) throws IOException {
+    if (method == Method.STORE) {
+      checkState(
+          entry.getSize() == length && entry.getCompressedSize() == length,
+          "Number of bytes written differs from what is specified in the entry.");
+      checkState(
+          entry.getCrc() == calculateCrc(),
+          "CRC of bytes written differs from what is specified in the entry.");
+    } else if (method == Method.DEFLATE) {
+      deflater.finish(out);
+      entry.setSize(deflater.getBytesRead());
+      entry.setCompressedSize(deflater.getBytesWritten());
+      entry.setCrc(calculateCrc());
+    } else if (method == Method.RAW_COPY) {
+      // Raw copy: sizes and CRC are already set on the entry by the caller.
+      // Verify the number of compressed bytes written matches compressedSize.
+      checkState(
+          entry.getCompressedSize() == length,
+          "Number of raw bytes written (%s) differs from compressedSize (%s).",
+          length,
+          entry.getCompressedSize());
+    }
+
+    // write the data descriptor if required
+    long dataDescriptorLength = writeDataDescriptor(out);
+
+    // regardless of the method used, end the deflater to free native resources.
+    deflater.end();
+
+    return entry.getCompressedSize() + dataDescriptorLength;
+  }
+
+  private boolean requiresDataDescriptor() {
+    return method == Method.DEFLATE;
+    // RAW_COPY does not need a data descriptor — CRC and sizes are known upfront.
+  }
+
+  private void updateCrc(byte[] b, int off, int len) {
+    crc = crc.putBytes(b, off, len);
+  }
+
+  private long calculateCrc() {
+    return crc.hash().padToLong();
+  }
+
+  private enum Method {
+    DEFLATE(20, 8),
+    STORE(10, 0),
+    RAW_COPY(20, 8),
+    ;
+
+    private final int requiredVersion;
+    private final int compressionMethod;
+
+    Method(int requiredVersion, int compressionMethod) {
+      this.requiredVersion = requiredVersion;
+      this.compressionMethod = compressionMethod;
+    }
+
+    public static Method detect(int fromZipMethod) {
+      switch (fromZipMethod) {
+        case -1:
+          return DEFLATE;
+        case ZipEntry.DEFLATED:
+          return DEFLATE;
+        case ZipEntry.STORED:
+          return STORE;
+        default:
+          throw new IllegalArgumentException("Cannot determine zip method from: " + fromZipMethod);
+      }
+    }
+  }
+
+  /**
+   * A lazy initialization wrapper around Deflater for compressing data. The
+   * java.util.zip.Deflater.DeflaterZStreamRef is expensive to initialize, and is not always used if
+   * dealing with directories or read-only entries.
+   */
+  static class LazyDeflate {
+
+    private static final int DEFAULT_BUFFER_SIZE = 8192;
+
+    private byte[] buffer;
+    private Deflater deflater;
+    private int compressionLevel = Deflater.DEFAULT_COMPRESSION;
+
+    void setCompressionLevel(int compressionLevel) {
+      this.compressionLevel = compressionLevel;
+    }
+
+    long getBytesWritten() {
+      return deflater == null ? 0 : deflater.getBytesWritten();
+    }
+
+    long getBytesRead() {
+      return deflater == null ? 0 : deflater.getBytesRead();
+    }
+
+    /** Writes data to the output stream. */
+    void write(OutputStream out, byte[] bytes, int off, int len) throws IOException {
+      initializeIfNeeded();
+      deflater.setInput(bytes, off, len);
+      while (!deflater.needsInput()) {
+        deflate(out);
+      }
+    }
+
+    /** Finishes the compression process. */
+    void finish(OutputStream out) throws IOException {
+      initializeIfNeeded();
+      deflater.finish();
+      while (!deflater.finished()) {
+        deflate(out);
+      }
+    }
+
+    /** Compress data to the output stream. */
+    private int deflate(OutputStream out) throws IOException {
+      initializeIfNeeded();
+      final int written = deflater.deflate(buffer, 0, buffer.length);
+      if (written > 0) {
+        out.write(buffer, 0, written);
+      }
+      return written;
+    }
+
+    /** Initializes the deflater if necessary. */
+    private void initializeIfNeeded() {
+      if (deflater == null) {
+        buffer = new byte[DEFAULT_BUFFER_SIZE];
+        deflater = new Deflater(compressionLevel, true);
+      }
+    }
+
+    /** Ends the compression process and releases resources. */
+    void end() {
+      if (deflater != null) {
+        deflater.end();
+        deflater = null;
+        buffer = null;
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/IncrementalJarOutputStreamImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/IncrementalJarOutputStreamImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/IncrementalJarOutputStreamImpl.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static java.nio.file.StandardOpenOption.CREATE;
+import static java.nio.file.StandardOpenOption.READ;
+import static java.nio.file.StandardOpenOption.WRITE;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.channels.Channels;
+import java.nio.channels.FileChannel;
+import java.nio.file.Path;
+import javax.annotation.Nonnull;
+
+/**
+ * Alternative implementation to dependency packing, instead of copying several jars which is slow,
+ * make use of a previous packed jar with immutable dependencies and append on top of it.
+ *
+ * @see AppendableCentralDirectory
+ */
+public class IncrementalJarOutputStreamImpl extends AppendingZipOutputStreamImpl {
+
+  /**
+   * Create a copy of a jar copying previous existing files and loading Central Directory to execute
+   * append operation.
+   *
+   * @see AppendableCentralDirectory
+   */
+  public static IncrementalJarOutputStreamImpl createIncrementalJar(Path src, Path dst)
+      throws IOException {
+
+    final AppendableCentralDirectory centralDirectory =
+        AppendableCentralDirectory.readCentralDirectory(src);
+
+    try (final FileChannel srcChannel = FileChannel.open(src, READ)) {
+      final FileChannel dstChannel = FileChannel.open(dst, CREATE, WRITE);
+
+      // copy the block of files that exists in the input jar
+      // transferFrom may not transfer all requested bytes in a single call,
+      // so we need to loop until all bytes are transferred
+      long bytesToTransfer = centralDirectory.getEntryOffset();
+      long position = 0;
+      while (position < bytesToTransfer) {
+        long transferred =
+            dstChannel.transferFrom(srcChannel, position, bytesToTransfer - position);
+        if (transferred == 0) {
+          throw new IOException(
+              "Failed to transfer bytes from source jar: transferred 0 bytes at position "
+                  + position
+                  + " of "
+                  + bytesToTransfer);
+        }
+        position += transferred;
+      }
+      dstChannel.position(centralDirectory.getEntryOffset());
+
+      return new IncrementalJarOutputStreamImpl(
+          Channels.newOutputStream(dstChannel), centralDirectory);
+    }
+  }
+
+  private final AppendableCentralDirectory appendableDirectory;
+
+  IncrementalJarOutputStreamImpl(OutputStream stream) {
+    this(stream, new AppendableCentralDirectory());
+  }
+
+  public IncrementalJarOutputStreamImpl(
+      final OutputStream outputStream, final AppendableCentralDirectory appendableDirectory) {
+    super(outputStream, false);
+    this.appendableDirectory = appendableDirectory;
+    setCurrentOffset(appendableDirectory.getEntryOffset());
+  }
+
+  @Nonnull
+  @Override
+  protected CentralDirectory getCentralDirectory() {
+    return appendableDirectory;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarBuilder.java
@@ -0,0 +1,531 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static com.facebook.buck.util.zip.ZipOutputStreams.HandleDuplicates.APPEND_TO_ZIP;
+import static com.facebook.buck.util.zip.ZipOutputStreams.appendJarOutputStream;
+import static com.facebook.buck.util.zip.ZipOutputStreams.newJarOutputStream;
+import static java.util.Comparator.comparing;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.io.ByteStreams;
+import com.google.common.io.CharStreams;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.jar.Attributes;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import javax.annotation.Nullable;
+
+public class JarBuilder {
+
+  private static final Predicate<? super CustomZipEntry> NO_FILTER = entry -> false;
+
+  private interface ResourceMergeStrategy {
+    byte[] merge(Set<String> files);
+
+    static final ResourceMergeStrategy JOIN_MERGE_STRATEGY =
+        new ResourceMergeStrategy() {
+          private Joiner joiner = Joiner.on("\n");
+
+          @Override
+          public byte[] merge(Set<String> files) {
+            return joiner.join(files).getBytes();
+          }
+        };
+
+    /**
+     * Property files in Spring have unique keys, some of them containing comma-seprated lists.
+     * These lists have to be merged together.
+     */
+    static final ResourceMergeStrategy PROPERTIES_MERGE_STRATEGY =
+        new ResourceMergeStrategy() {
+          @Override
+          public byte[] merge(Set<String> files) {
+            Properties mergedProps = new Properties();
+            for (String file : files) {
+              Properties props = new Properties();
+              try {
+                props.load(new StringReader(file));
+                for (String propName : props.stringPropertyNames()) {
+                  String values = props.getProperty(propName);
+                  String mergedValues = mergedProps.getProperty(propName);
+                  mergedProps.setProperty(
+                      propName, mergedValues == null ? values : mergedValues + "," + values);
+                }
+              } catch (IOException ex) {
+                throw new RuntimeException(
+                    String.format("Unable to merge properties for file %s", file), ex);
+              }
+            }
+            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+            try {
+              mergedProps.store(byteArrayOutputStream, "");
+              return byteArrayOutputStream.toByteArray();
+            } catch (IOException ex) {
+              throw new RuntimeException("Unable to merge properties", ex);
+            }
+          }
+        };
+  }
+
+  private enum MergeableResource implements Predicate<String>, ResourceMergeStrategy {
+    SERVICES("META-INF/services/", ResourceMergeStrategy.JOIN_MERGE_STRATEGY),
+    SPRING_SCHEMAS("META-INF/spring.schemas", ResourceMergeStrategy.JOIN_MERGE_STRATEGY),
+    SPRING_HANDLERS("META-INF/spring.handlers", ResourceMergeStrategy.JOIN_MERGE_STRATEGY),
+    SPRING_FACTORIES("META-INF/spring.factories", ResourceMergeStrategy.PROPERTIES_MERGE_STRATEGY),
+    SPRING_TOOLING("META-INF/spring.tooling", ResourceMergeStrategy.JOIN_MERGE_STRATEGY);
+
+    private final Predicate<String> predicate;
+    private final ResourceMergeStrategy mergeStrategy;
+
+    MergeableResource(String pathPrefix, ResourceMergeStrategy mergeStrategy) {
+      this.predicate = entryName -> entryName.startsWith(pathPrefix) && !entryName.endsWith("/");
+      this.mergeStrategy = mergeStrategy;
+    }
+
+    @Override
+    public boolean test(String entryName) {
+      return predicate.test(entryName);
+    }
+
+    public static boolean check(String entryName) {
+      return MergeableResource.fromFileName(entryName) != null;
+    }
+
+    public static MergeableResource fromFileName(String entryName) {
+      return Arrays.stream(MergeableResource.values())
+          .filter(mergeableResource -> mergeableResource.predicate.test(entryName))
+          .findAny()
+          .orElse(null);
+    }
+
+    @Override
+    public byte[] merge(Set<String> files) {
+      return mergeStrategy.merge(files);
+    }
+  }
+
+  public interface Observer {
+
+    Observer IGNORING = (jarFile, entrySupplier) -> {};
+
+    void onDuplicateEntry(String jarFile, JarEntrySupplier entrySupplier);
+  }
+
+  private Observer observer = Observer.IGNORING;
+  @Nullable private Path outputFile;
+  @Nullable private String mainClass;
+  private boolean shouldMergeManifests;
+  private boolean shouldHashEntries;
+  private Path appendJar;
+  private Predicate<? super CustomZipEntry> removeEntryPredicate = NO_FILTER;
+  private List<Path> manifestFiles = List.of();
+  private final List<JarEntryContainer> sourceContainers = new ArrayList<>();
+  private final List<JarEntryContainer> overrideSourceContainers = new ArrayList<>();
+  private final Set<String> alreadyAddedEntries = new HashSet<>();
+  private final Map<String, Set<String>> mergeableResources = new HashMap<>();
+  private final List<JarEntrySupplier> additionalEntries = new ArrayList<>();
+
+  protected Path getAppendJar() {
+    return appendJar;
+  }
+
+  protected Predicate<? super CustomZipEntry> getRemoveEntryPredicate() {
+    return removeEntryPredicate;
+  }
+
+  protected List<JarEntryContainer> getSourceContainers() {
+    return sourceContainers;
+  }
+
+  protected List<JarEntryContainer> getOverrideSourceContainers() {
+    return overrideSourceContainers;
+  }
+
+  public JarBuilder setObserver(Observer observer) {
+    this.observer = observer;
+    return this;
+  }
+
+  public JarBuilder setOverrideEntriesToJar(Stream<AbsPath> entriesToJar) {
+    return setOverrideEntriesToJar(entriesToJar::iterator);
+  }
+
+  public JarBuilder setOverrideEntriesToJar(Iterable<AbsPath> entriesToJar) {
+    return addToSourceContainers(entriesToJar, overrideSourceContainers);
+  }
+
+  public JarBuilder setEntriesToJar(Stream<AbsPath> entriesToJar) {
+    return setEntriesToJar(entriesToJar::iterator);
+  }
+
+  public JarBuilder setEntriesToJar(Iterable<AbsPath> entriesToJar) {
+    return addToSourceContainers(entriesToJar, sourceContainers);
+  }
+
+  private JarBuilder addToSourceContainers(
+      Iterable<AbsPath> entriesToJar, List<JarEntryContainer> sourceContainers) {
+    StreamSupport.stream(entriesToJar.spliterator(), false)
+        .map(AbsPath::getPath)
+        .map(this::toJarEntryContainer)
+        .forEach(sourceContainers::add);
+
+    return this;
+  }
+
+  protected JarEntryContainer toJarEntryContainer(Path jar) {
+    return JarEntryContainer.of(jar);
+  }
+
+  public JarBuilder addEntry(JarEntrySupplier supplier) {
+    sourceContainers.add(new SingletonJarEntryContainer(supplier));
+    return this;
+  }
+
+  public JarBuilder addEntries(List<JarEntrySupplier> suppliers) {
+    for (JarEntrySupplier supplier : suppliers) {
+      addEntry(supplier);
+    }
+    return this;
+  }
+
+  public JarBuilder addEntryContainer(JarEntryContainer container) {
+    sourceContainers.add(container);
+    return this;
+  }
+
+  public JarBuilder setMainClass(String mainClass) {
+    this.mainClass = mainClass;
+    return this;
+  }
+
+  public JarBuilder setManifestFile(@Nullable Path manifestFile) {
+    if (manifestFile != null) {
+      return setManifestFiles(List.of(manifestFile));
+    }
+    return setManifestFiles(List.of());
+  }
+
+  public JarBuilder setManifestFiles(final List<Path> manifestFiles) {
+    this.manifestFiles =
+        manifestFiles.stream()
+            .peek(
+                manifestFile ->
+                    Preconditions.checkArgument(manifestFile == null || manifestFile.isAbsolute()))
+            .collect(Collectors.toList());
+    return this;
+  }
+
+  public JarBuilder setShouldMergeManifests(boolean shouldMergeManifests) {
+    this.shouldMergeManifests = shouldMergeManifests;
+    return this;
+  }
+
+  public JarBuilder setShouldHashEntries(boolean shouldHashEntries) {
+    this.shouldHashEntries = shouldHashEntries;
+    return this;
+  }
+
+  public JarBuilder setAppendJar(@Nullable Path appendJar) {
+    this.appendJar = appendJar;
+    return this;
+  }
+
+  public JarBuilder setRemoveEntryPredicate(
+      @Nullable Predicate<? super CustomZipEntry> removeEntryPredicate) {
+    this.removeEntryPredicate = removeEntryPredicate != null ? removeEntryPredicate : NO_FILTER;
+    return this;
+  }
+
+  public void createJarFile(Path outputFile) throws IOException {
+    Preconditions.checkArgument(outputFile.isAbsolute());
+    try (CustomJarOutputStream jar = getJarOutputStream(appendJar, outputFile)) {
+      createJarFile(outputFile, jar);
+    }
+  }
+
+  protected void createJarFile(Path outputFile, CustomJarOutputStream jar) throws IOException {
+
+    if (appendJar != null && Files.exists(appendJar)) {
+      addEntriesFromJar(appendJar, sourceContainers);
+    }
+
+    jar.setEntryHashingEnabled(shouldHashEntries);
+    this.outputFile = outputFile;
+
+    // Write the manifest first.
+    writeManifest(jar);
+
+    // Sort entries across all suppliers
+    List<JarEntrySupplier> sortedEntries = new ArrayList<>();
+    addToEntries(sortedEntries, sourceContainers);
+    sortedEntries.sort(comparing(supplier -> supplier.getEntry().getName()));
+
+    // add override entries
+    addToEntries(sortedEntries, overrideSourceContainers);
+
+    addEntriesToJar(sortedEntries, jar);
+
+    addMergeableResources(jar);
+
+    if (mainClass != null && !classPresent(mainClass)) {
+      throw new RuntimeException(String.format("ERROR: Main class %s does not exist.", mainClass));
+    }
+
+    // Clean up any open file handles that we may have
+    closeSourceContainers(sourceContainers);
+    closeSourceContainers(overrideSourceContainers);
+  }
+
+  protected CustomJarOutputStream getJarOutputStream(final Path appendJar, final Path outputFile)
+      throws IOException {
+    if (appendJar != null) {
+      return appendJarOutputStream(appendJar, outputFile);
+    }
+    return newJarOutputStream(outputFile, APPEND_TO_ZIP);
+  }
+
+  private void addEntriesFromJar(final Path jar, List<JarEntryContainer> sourceContainers)
+      throws IOException {
+    // read jar that does not allow copies of its entries
+    final JarEntryContainer appendJarContainer =
+        JarEntryContainer.readOnlyJar(jar.toAbsolutePath());
+    // should be the first container
+    sourceContainers.add(0, appendJarContainer);
+    // mark all entries as existing already
+    appendJarContainer.stream()
+        .map(entry -> entry.getEntry().getName())
+        .forEach(alreadyAddedEntries::add);
+  }
+
+  private void addToEntries(
+      List<JarEntrySupplier> sortedEntries, List<JarEntryContainer> sourceContainers)
+      throws IOException {
+    for (JarEntryContainer sourceContainer : sourceContainers) {
+      sourceContainer.stream().forEach(sortedEntries::add);
+    }
+  }
+
+  private void closeSourceContainers(List<JarEntryContainer> sourceContainers) throws IOException {
+    for (JarEntryContainer sourceContainer : sourceContainers) {
+      sourceContainer.close();
+    }
+  }
+
+  private void addMergeableResources(CustomJarOutputStream jar) throws IOException {
+    for (String entryName : mergeableResources.keySet()) {
+      CustomZipEntry entry = new CustomZipEntry(entryName);
+      jar.putNextEntry(entry);
+      Set<String> files = mergeableResources.get(entryName);
+      jar.write(MergeableResource.fromFileName(entryName).merge(files));
+      jar.closeEntry();
+    }
+  }
+
+  private void writeManifest(CustomJarOutputStream jar) throws IOException {
+    mkdirs("META-INF/", jar);
+
+    final DeterministicManifest manifest = jar.getManifest();
+    final JarManifestMerger manifestMerger = JarManifestMerger.get();
+
+    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
+
+    if (shouldMergeManifests) {
+      for (JarEntryContainer sourceContainer : sourceContainers) {
+        manifestMerger.merge(manifest, sourceContainer.getManifest());
+      }
+    }
+
+    // Even if not merging manifests, we should include the one the user gave us. We do this last
+    // so that values from the user overwrite values from merged manifests.
+    for (Path manifestFile : manifestFiles) {
+      try (InputStream stream = Files.newInputStream(manifestFile)) {
+        manifestMerger.merge(manifest, new Manifest(stream));
+      }
+    }
+
+    // We may have merged manifests and over-written the user-supplied main class. Add it back.
+    if (mainClass != null) {
+      manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass);
+    }
+
+    jar.writeManifest();
+  }
+
+  private boolean classPresent(String className) {
+    String classPath = classNameToPath(className);
+
+    return alreadyAddedEntries.contains(classPath);
+  }
+
+  private String classNameToPath(String className) {
+    return className.replace('.', '/') + ".class";
+  }
+
+  public static String pathToClassName(String relativePath) {
+    String entry = relativePath;
+    if (relativePath.contains(".class")) {
+      entry = relativePath.replace('/', '.').replace(".class", "");
+    }
+    return entry;
+  }
+
+  private void addEntriesToJar(Iterable<JarEntrySupplier> entries, CustomJarOutputStream jar)
+      throws IOException {
+    for (JarEntrySupplier entrySupplier : entries) {
+      addEntryToJar(entrySupplier, jar);
+    }
+  }
+
+  private void addEntryToJar(JarEntrySupplier entrySupplier, CustomJarOutputStream jar)
+      throws IOException {
+    CustomZipEntry entry = entrySupplier.getEntry();
+    String entryName = entry.getName();
+
+    // We already read the manifest. No need to read it again
+    if (JarFile.MANIFEST_NAME.equals(entryName)) {
+      return;
+    }
+
+    // Ignore source directories to avoid adding directories for removed classes.
+    // mkdirs() below will create the ones that are really needed.
+    if (entry.isDirectory()) {
+      return;
+    }
+
+    // Check if the entry belongs to the blocklist and it should be excluded from the Jar.
+    if (removeEntryPredicate.test(entry)) {
+      return;
+    }
+
+    mkdirs(getParentDir(entryName), jar);
+
+    // We're in the process of merging a bunch of different jar files. These typically contain
+    // just ".class" files and the manifest, but they can also include things like license files
+    // from third party libraries and config files. We should include those license files within
+    // the jar we're creating. Extracting them is left as an exercise for the consumer of the
+    // jar.  Because we don't know which files are important, the only ones we skip are
+    // duplicate class files.
+    if (!isDuplicateAllowed(entryName) && !alreadyAddedEntries.add(entryName)) {
+      if (!entryName.endsWith("/")) {
+        observer.onDuplicateEntry(String.valueOf(outputFile), entrySupplier);
+      }
+      return;
+    }
+
+    // Collect all mergeable resources together for later merging and addition to the output jar
+    if (MergeableResource.check(entryName)) {
+      try (InputStream entryInputStream =
+          Objects.requireNonNull(entrySupplier.getInputStreamSupplier().get())) {
+        Set<String> existingResources =
+            mergeableResources.computeIfAbsent(entryName, (m) -> new LinkedHashSet<>());
+        existingResources.add(
+            CharStreams.toString(new InputStreamReader(entryInputStream, StandardCharsets.UTF_8))
+                .trim());
+      }
+      return;
+    }
+
+    if (!entrySupplier.isReadOnly()) {
+      jar.putNextEntry(entry);
+      try (InputStream entryInputStream = entrySupplier.getInputStreamSupplier().get()) {
+        if (entryInputStream != null) {
+          // Null stream means a directory
+          ByteStreams.copy(entryInputStream, jar);
+        }
+      }
+      jar.closeEntry();
+    }
+  }
+
+  private void mkdirs(String name, CustomJarOutputStream jar) throws IOException {
+    if (name.isEmpty()) {
+      return;
+    }
+
+    Preconditions.checkArgument(name.endsWith("/"));
+    if (alreadyAddedEntries.contains(name)) {
+      return;
+    }
+
+    String parent = getParentDir(name);
+    mkdirs(parent, jar);
+
+    jar.putNextEntry(new CustomZipEntry(name));
+    jar.closeEntry();
+    alreadyAddedEntries.add(name);
+  }
+
+  private String getParentDir(String name) {
+    int length = name.lastIndexOf('/') + 1;
+    if (length == name.length()) {
+      length = name.lastIndexOf('/', length - 2) + 1;
+    }
+    return name.substring(0, length);
+  }
+
+  private boolean isDuplicateAllowed(String name) {
+    return MergeableResource.check(name);
+  }
+
+  private static class SingletonJarEntryContainer implements JarEntryContainer {
+
+    private final JarEntrySupplier supplier;
+
+    @Nullable private Manifest manifest;
+
+    private SingletonJarEntryContainer(JarEntrySupplier supplier) {
+      this.supplier = supplier;
+    }
+
+    @Nullable
+    @Override
+    public Manifest getManifest() throws IOException {
+      if (manifest == null && supplier.getEntry().getName().equals(JarFile.MANIFEST_NAME)) {
+        try (InputStream manifestStream = supplier.getInputStreamSupplier().get()) {
+          manifest = new Manifest(manifestStream);
+        }
+      }
+      return manifest;
+    }
+
+    @Override
+    public Stream<JarEntrySupplier> stream() {
+      return Stream.of(supplier);
+    }
+
+    @Override
+    public void close() {}
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarBuilderMain.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarBuilderMain.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarBuilderMain.java
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Optional.ofNullable;
+import static java.util.stream.Collectors.toList;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.jvm.java.RemoveClassesPatternsMatcher;
+import com.facebook.buck.util.PatternsMatcher;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Predicate;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Main entry point for executing {@link JarBuilder} calls. */
+public class JarBuilderMain {
+
+  @Option(name = "--output", required = true)
+  private String output;
+
+  @Option(name = "--entries-to-jar")
+  private String entriesToJarFilePath;
+
+  @Option(name = "--override-entries-to-jar")
+  private String overrideEntriesToJarFilePath;
+
+  @Option(name = "--class-files", usage = "Format: <name>:<path>")
+  private List<String> classFiles;
+
+  @Option(name = "--blocklist-patterns")
+  private String blocklistPatternsFilePath;
+
+  @Option(name = "--blocklist-patterns-matcher")
+  private String blocklistPatternsMatcher;
+
+  @Option(name = "--main-class")
+  private String mainClass;
+
+  @Option(name = "--manifest-file")
+  private List<String> manifestFiles = new ArrayList<>();
+
+  @Option(name = "--merge-manifests")
+  private boolean mergeManifests = false;
+
+  @Option(name = "--hash-entries")
+  private boolean hashEntries = false;
+
+  @Option(name = "--append-jar")
+  private String appendJar;
+
+  @Option(name = "--concat-jars")
+  private boolean concatJars = false;
+
+  public static void main(String[] args) throws IOException {
+    System.exit(run(args));
+  }
+
+  /** Prevent {@link System#exit(int)} execution so it can be used in unit tests. */
+  @VisibleForTesting
+  static int run(String... args) throws IOException {
+    JarBuilderMain jarBuilderMain = new JarBuilderMain();
+    CmdLineParser parser = new CmdLineParser(jarBuilderMain);
+    try {
+      parser.parseArgument(args);
+      jarBuilderMain.build();
+    } catch (CmdLineException e) {
+      System.err.println(e.getMessage());
+      parser.printUsage(System.err);
+      return 1;
+    }
+    return 0;
+  }
+
+  private void build() throws IOException {
+
+    final AbsPath root = AbsPath.of(Paths.get(".").normalize().toAbsolutePath());
+    final Path outputFile = root.resolve(output).getPath();
+    final List<AbsPath> entriesToJar = readEntriesToJar(root, entriesToJarFilePath);
+    final List<AbsPath> overrideEntriesToJar = readEntriesToJar(root, overrideEntriesToJarFilePath);
+    final JarBuilder jarBuilder = concatJars ? new ConcatJarBuilder() : new JarBuilder();
+    final List<JarEntrySupplier> classFileEntries;
+    if (classFiles != null) {
+      classFileEntries =
+          classFiles.stream()
+              .map(
+                  (classFile) -> {
+                    // Parse and add additional class files. For example:
+                    // --class-files module-info.class:/tmp/foo.class
+                    // will add /tmp/foo.class to the jar with name "module-info.class"
+                    String[] parts = classFile.split(":", 2);
+                    if (parts.length != 2) {
+                      throw new IllegalArgumentException(
+                          "Expected --class-files format: <name>:<path>");
+                    }
+                    return new JarEntrySupplier(
+                        new CustomZipEntry(parts[0]),
+                        () -> Files.newInputStream(Path.of(parts[1])));
+                  })
+              .collect(Collectors.toList());
+    } else {
+      classFileEntries = new ArrayList<>();
+    }
+
+    jarBuilder
+        .setMainClass(mainClass)
+        .setManifestFiles(getManifestFiles(root, manifestFiles))
+        .setShouldMergeManifests(mergeManifests)
+        .setShouldHashEntries(hashEntries)
+        .setAppendJar(ofNullable(appendJar).map(Path::of).orElse(null))
+        .setRemoveEntryPredicate(getRemoveEntryPredicate())
+        .setEntriesToJar(getEntriesToJar(entriesToJar, concatJars))
+        .setOverrideEntriesToJar(overrideEntriesToJar)
+        .addEntries(classFileEntries)
+        .createJarFile(outputFile);
+  }
+
+  private List<AbsPath> getEntriesToJar(List<AbsPath> entriesToJar, boolean concatJars) {
+    if (!concatJars) {
+      return entriesToJar;
+    }
+    return new DirectoryJarBuilder(
+            () -> new JarBuilder().setRemoveEntryPredicate(getRemoveEntryPredicate()))
+        .buildJars(entriesToJar)
+        .join();
+  }
+
+  private Predicate<? super CustomZipEntry> getRemoveEntryPredicate() {
+    if (blocklistPatternsFilePath == null) {
+      return null;
+    }
+    checkState(
+        blocklistPatternsMatcher != null,
+        "Must specify `--blocklist-patterns-matcher` if `--blocklist-patterns` is set!");
+    try {
+      final ImmutableSet<Pattern> blocklistPatterns =
+          readNonEmptyLines(blocklistPatternsFilePath)
+              .map(Pattern::compile)
+              .collect(ImmutableSet.toImmutableSet());
+
+      if ("substring".equals(blocklistPatternsMatcher)) {
+        return entry -> new PatternsMatcher(blocklistPatterns).substringMatches(entry.getName());
+      } else if ("remove_classes_patterns_matcher".equals(blocklistPatternsMatcher)) {
+        return new RemoveClassesPatternsMatcher(blocklistPatterns, true);
+      }
+      throw new RuntimeException(
+          "`--blocklist-patterns-matcher` must be either `substring` or"
+              + " `remove_classes_patterns_matcher`");
+    } catch (IOException e) {
+      throw new RuntimeException(
+          String.format("failed to read blocklistPatternsFilePath: %s", blocklistPatternsFilePath),
+          e);
+    }
+  }
+
+  private List<Path> getManifestFiles(final AbsPath root, final List<String> files) {
+    return files.stream().map(file -> root.resolve(file).getPath()).collect(toList());
+  }
+
+  private List<AbsPath> readEntriesToJar(final AbsPath root, final String path) throws IOException {
+    if (path == null) {
+      return List.of();
+    }
+    return readNonEmptyLines(path).map(root::resolve).collect(toList());
+  }
+
+  private Stream<String> readNonEmptyLines(final String path) throws IOException {
+    return Files.readAllLines(Paths.get(path)).stream()
+        .map(String::trim)
+        .filter(Predicate.not(String::isEmpty));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarDiff.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarDiff.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarDiff.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static java.util.stream.Collectors.toCollection;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.stream.Stream;
+
+/**
+ * A utility class for comparing the contents of two JAR files. Compares the contents of two JAR
+ * files. Detects entries that exist only in one jar. Validate the content of binary files, and
+ * property files. It will exclude property comments since they might have built dates that differ.
+ */
+public class JarDiff {
+
+  private static final String INNER_JAR = "inner.jar";
+  private static final byte[] BUFFER = new byte[8096];
+  private static final byte[] OTHER_BUFFER = new byte[8096];
+
+  /**
+   * @param args command-line arguments (two JAR file paths)
+   * @throws IOException if an I/O error occurs
+   */
+  public static void main(String[] args) throws IOException {
+    if (args.length == 2) {
+      new JarDiff().diff(Path.of(args[0]), Path.of(args[1]));
+    } else {
+      System.out.println("requires 2 jar paths");
+    }
+  }
+
+  private void diff(Path path, Path otherPath) throws IOException {
+    try (final JarFile jar = new JarFile(path.toFile(), true);
+        final JarFile otherJar = new JarFile(otherPath.toFile(), true); ) {
+      final Set<String> names = entryNames(jar);
+      final Set<String> otherNames = entryNames(otherJar);
+
+      final Set<String> commonNames = common(otherNames, names);
+      final Set<String> uniqueNames = unique(names, otherNames);
+      final Set<String> otherUniqueNames = unique(otherNames, names);
+
+      System.out.printf(
+          "evaluating %s entries of [%s, %s] %n",
+          commonNames.size(), path.getFileName(), otherPath.getFileName());
+
+      uniqueNames.forEach(
+          name -> System.out.printf("- [%s] has unique entry: %s %n", path.getFileName(), name));
+      otherUniqueNames.forEach(
+          name ->
+              System.out.printf("- [%s] has unique entry: %s %n", otherPath.getFileName(), name));
+
+      commonNames.stream()
+          .map(
+              name -> {
+                if (INNER_JAR.equals(name)) {
+                  return null;
+                }
+                if (isPropertyFile(name) || name.startsWith("META-INF/services/")) {
+                  return compareText(name, jar, otherJar);
+                }
+                return compareBytes(name, jar, otherJar);
+              })
+          .filter(Objects::nonNull)
+          .forEach(System.out::println);
+
+      if (commonNames.contains(INNER_JAR)) {
+        diff(extractInnerJar(jar), extractInnerJar(otherJar));
+      }
+    }
+  }
+
+  private Path extractInnerJar(final JarFile jar) throws IOException {
+    final Path tempFile =
+        Files.createTempFile(Path.of(jar.getName()).getFileName() + "-", "-" + INNER_JAR);
+    try (final InputStream input = jar.getInputStream(jar.getJarEntry(INNER_JAR));
+        final OutputStream output = Files.newOutputStream(tempFile); ) {
+      input.transferTo(output);
+    }
+    return tempFile;
+  }
+
+  private boolean isPropertyFile(String name) {
+    return Stream.of(".properties", ".MF", ".factories").anyMatch(name::endsWith);
+  }
+
+  private String compareBytes(String name, JarFile jar, JarFile otherJar) {
+    try (final InputStream in = jar.getInputStream(jar.getJarEntry(name));
+        final InputStream otherIn = otherJar.getInputStream(otherJar.getJarEntry(name)); ) {
+
+      long totalSize = 0;
+      long otherTotalSize = 0;
+
+      while (true) {
+
+        int read = in.readNBytes(BUFFER, 0, BUFFER.length);
+        int otherRead = otherIn.readNBytes(OTHER_BUFFER, 0, OTHER_BUFFER.length);
+
+        totalSize += Math.max(0, read);
+        otherTotalSize += Math.max(0, otherRead);
+
+        if (read != otherRead) {
+          return String.format(
+              "! %s has byte difference at %s", name, Math.min(totalSize, otherTotalSize));
+        }
+        if (read > 0) {
+          for (int i = 0; i < read; i++) {
+            if (BUFFER[i] != OTHER_BUFFER[i]) {
+              return String.format("! %s has byte difference at %s", name, (totalSize - read) + i);
+            }
+          }
+        } else {
+          break;
+        }
+      }
+    } catch (IOException e) {
+      throw new UncheckedIOException(e);
+    }
+    // both are similar
+    return null;
+  }
+
+  private String compareText(String name, JarFile jar, JarFile otherJar) {
+    try (final InputStream in = jar.getInputStream(jar.getJarEntry(name));
+        final InputStream otherIn = otherJar.getInputStream(otherJar.getJarEntry(name)); ) {
+
+      final Iterator<String> lines = textLines(in);
+      final Iterator<String> otherLines = textLines(otherIn);
+
+      while (lines.hasNext() && otherLines.hasNext()) {
+        String line = lines.next();
+        String otherLine = otherLines.next();
+        if (!line.equals(otherLine)) {
+          return String.format(
+              "! %s has difference in lines \"%s\" <> \"%s\"", name, line, otherLine);
+        }
+      }
+      if (lines.hasNext()) {
+        return String.format("! %s has difference in line \"%s\"", name, lines.next());
+      }
+      if (otherLines.hasNext()) {
+        return String.format("! %s has difference in line \"%s\"", name, otherLines.next());
+      }
+
+    } catch (IOException e) {
+      throw new UncheckedIOException(e);
+    }
+    return null;
+  }
+
+  private Iterator<String> textLines(InputStream inputStream) {
+    return new BufferedReader(new InputStreamReader(inputStream))
+        .lines()
+        .map(String::trim)
+        .filter(s -> !s.isEmpty())
+        // ignore comment lines
+        .filter(s -> Stream.of("!", "#").noneMatch(s::startsWith))
+        .iterator();
+  }
+
+  private Set<String> common(Set<String> names, Set<String> universe) {
+    return names.stream().filter(universe::contains).collect(toCollection(TreeSet::new));
+  }
+
+  private Set<String> unique(Set<String> names, Set<String> universe) {
+    return names.stream()
+        .filter(name -> !universe.contains(name))
+        .collect(toCollection(TreeSet::new));
+  }
+
+  private Set<String> entryNames(JarFile jar) {
+    return jar.stream()
+        .filter(e -> !e.isDirectory())
+        .map(JarEntry::getName)
+        .collect(toCollection(LinkedHashSet::new));
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarEntryContainer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarEntryContainer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarEntryContainer.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.jar.Manifest;
+import java.util.stream.Stream;
+import javax.annotation.Nullable;
+
+/**
+ * Represents a container for entries to be added to a jar file by @{link JarBuilder}. Examples
+ * include a directory tree or another jar file.
+ */
+public interface JarEntryContainer extends AutoCloseable {
+
+  /**
+   * @param source Path to a jar file
+   * @return Container which all the entries are not copyable
+   * @see JarEntrySupplier#isReadOnly()
+   */
+  static JarEntryContainer readOnlyJar(Path source) {
+    // Assume a zip or jar file.
+    if (!Files.isRegularFile(source)) {
+      throw new IllegalStateException("Must be a jar file: " + source);
+    }
+    return new ZipFileJarEntryContainer(source, true);
+  }
+
+  static JarEntryContainer of(Path source) {
+    Preconditions.checkArgument(source.isAbsolute());
+
+    if (Files.isDirectory(source)) {
+      return new DirectoryJarEntryContainer(source);
+    } else if (Files.isRegularFile(source)) {
+      // Assume a zip or jar file.
+      return new ZipFileJarEntryContainer(source);
+    } else {
+      throw new IllegalStateException("Must be a file or directory: " + source);
+    }
+  }
+
+  @Nullable
+  Manifest getManifest() throws IOException;
+
+  Stream<JarEntrySupplier> stream() throws IOException;
+
+  @Override
+  void close() throws IOException;
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarEntrySupplier.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarEntrySupplier.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarEntrySupplier.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import com.facebook.buck.util.function.ThrowingSupplier;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Encapsulates a file or directory to be added as a single entry to a jar by {@link JarBuilder}.
+ */
+public class JarEntrySupplier {
+  private final CustomZipEntry entry;
+  private final ThrowingSupplier<InputStream, IOException> inputStreamSupplier;
+  private final boolean readOnly;
+
+  public JarEntrySupplier(
+      CustomZipEntry entry, ThrowingSupplier<InputStream, IOException> inputStreamSupplier) {
+    this(entry, false, inputStreamSupplier);
+  }
+
+  public JarEntrySupplier(
+      CustomZipEntry entry,
+      boolean readOnly,
+      ThrowingSupplier<InputStream, IOException> inputStreamSupplier) {
+    this.entry = entry;
+    this.readOnly = readOnly;
+    this.inputStreamSupplier = inputStreamSupplier;
+  }
+
+  public CustomZipEntry getEntry() {
+    return entry;
+  }
+
+  public ThrowingSupplier<InputStream, IOException> getInputStreamSupplier() {
+    return inputStreamSupplier;
+  }
+
+  public boolean isReadOnly() {
+    return readOnly;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarManifestMerger.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarManifestMerger.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/JarManifestMerger.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import javax.annotation.Nullable;
+
+/**
+ * Registry for manifest attribute mergers. Provides a way to look up the appropriate merger for a
+ * given attribute name. If no specific merger is registered for an attribute, the default merger is
+ * used.
+ */
+public class JarManifestMerger {
+
+  private static final JarManifestMerger INSTANCE = new JarManifestMerger();
+
+  public static JarManifestMerger get() {
+    return INSTANCE;
+  }
+
+  private static final ManifestAttributeMerger DEFAULT_MERGER =
+      (existingValue, newValue) -> newValue;
+
+  private final Map<String, ManifestAttributeMerger> attributeMergers =
+      new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+
+  private JarManifestMerger() {
+    register("Multi-Release", new MultiReleaseManifestAttributeMerger());
+  }
+
+  protected void register(String attributeName, ManifestAttributeMerger merger) {
+    attributeMergers.put(attributeName, merger);
+  }
+
+  /**
+   * Merge entries from two Manifests together. Attributes are merged using the appropriate {@link
+   * ManifestAttributeMerger} for each attribute.
+   *
+   * @param into The Manifest to modify.
+   * @param from The Manifest to copy from.
+   */
+  public void merge(Manifest into, Manifest from) {
+    if (into == null) {
+      throw new IllegalArgumentException("into manifest cannot be null");
+    }
+    if (from == null) {
+      return;
+    }
+    mergeAttributes(into.getMainAttributes(), from.getMainAttributes());
+
+    final Map<String, Attributes> entries = from.getEntries();
+    if (entries != null) {
+      entries.forEach(
+          (key, value) ->
+              mergeAttributes(
+                  into.getEntries().computeIfAbsent(key, k -> new Attributes()), value));
+    }
+  }
+
+  private void mergeAttributes(Attributes target, Attributes source) {
+    if (source == null || target == null) {
+      return;
+    }
+    source.forEach((key, value) -> target.put(key, getMerger(key).merge(target.get(key), value)));
+  }
+
+  private ManifestAttributeMerger getMerger(final Object attributeKey) {
+    return attributeMergers.getOrDefault(String.valueOf(attributeKey), DEFAULT_MERGER);
+  }
+
+  /**
+   * Merger for the Multi-Release manifest attribute. If any jar has Multi-Release set to "true",
+   * the final merged manifest will have Multi-Release as "true", regardless of subsequent jars
+   * having it as "false".
+   */
+  static class MultiReleaseManifestAttributeMerger implements ManifestAttributeMerger {
+
+    @Override
+    public Object merge(@Nullable Object existingValue, Object newValue) {
+      if ("true".equalsIgnoreCase(String.valueOf(existingValue))) {
+        return existingValue;
+      }
+      return newValue;
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ManifestAttributeMerger.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ManifestAttributeMerger.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ManifestAttributeMerger.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import javax.annotation.Nullable;
+
+/**
+ * Strategy interface for merging manifest attribute values. Implementations define how to compute
+ * the final value when merging attributes from multiple manifests.
+ */
+@FunctionalInterface
+public interface ManifestAttributeMerger {
+
+  /**
+   * Computes the merged value for a manifest attribute.
+   *
+   * @param existingValue The current value in the target manifest, or null if not present.
+   * @param newValue The incoming value from the source manifest.
+   * @return The merged value to use in the target manifest.
+   */
+  Object merge(@Nullable Object existingValue, Object newValue);
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/OverwritingZipOutputStreamImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/OverwritingZipOutputStreamImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/OverwritingZipOutputStreamImpl.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import com.google.common.hash.Hashing;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import javax.annotation.Nullable;
+
+/**
+ * An implementation of an {@link OutputStream} for zip files that allows newer entries to overwrite
+ * or refresh previously written entries.
+ *
+ * <p>This class works by spooling the bytes of each entry to a temporary holding file named after
+ * the name of the {@link ZipEntry} being stored. Once the stream is closed, these files are spooled
+ * off disk and written to the OutputStream given to the constructor.
+ */
+public class OverwritingZipOutputStreamImpl implements CustomZipOutputStream.Impl {
+  // Attempt to maintain ordering of files that are added.
+  private final Map<File, EntryAccounting> entries = new LinkedHashMap<>();
+  private final File scratchDir;
+  private final OutputStream delegate;
+  @Nullable private EntryAccounting currentEntry;
+
+  /** Place-holder for bytes. */
+  @Nullable private OutputStream currentOutput;
+
+  public OverwritingZipOutputStreamImpl(OutputStream out) {
+    this.delegate = out;
+
+    try {
+      scratchDir = Files.createTempDirectory("overwritingzip").toFile();
+      // Reading the source, it seems like the temp dir isn't scheduled for deletion. We will delete
+      // the directory when we close the stream, but if that method is never called, we'd leave
+      // cruft on the FS. It's not foolproof, but try and avoid that.
+      scratchDir.deleteOnExit();
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @Override
+  public void actuallyPutNextEntry(ZipEntry entry) throws IOException {
+    // We calculate the actual offset when closing the stream, so 0 is fine.
+    currentEntry = new EntryAccounting(entry, /* currentOffset */ 0);
+
+    long md5 = Hashing.md5().hashUnencodedChars(entry.getName()).asLong();
+    String name = String.valueOf(md5);
+
+    File file = new File(scratchDir, name);
+    entries.put(file, currentEntry);
+    if (file.exists() && !file.delete()) {
+      throw new ZipException("Unable to delete existing file: " + entry.getName());
+    }
+    currentOutput = new BufferedOutputStream(new FileOutputStream(file));
+  }
+
+  @Override
+  public void actuallyCloseEntry() throws IOException {
+    // We'll close the entry once we have the ultimate output stream and know the entry's location
+    // within the generated zip.
+    if (currentOutput != null) {
+      currentOutput.close();
+    }
+    currentOutput = null;
+    currentEntry = null;
+  }
+
+  @Override
+  public void actuallyWrite(byte[] b, int off, int len) throws IOException {
+    Objects.requireNonNull(currentEntry);
+    Objects.requireNonNull(currentOutput);
+    currentEntry.write(currentOutput, b, off, len);
+  }
+
+  @Override
+  public void actuallyClose() throws IOException {
+    long currentOffset = 0;
+
+    for (Map.Entry<File, EntryAccounting> mapEntry : entries.entrySet()) {
+      EntryAccounting entry = mapEntry.getValue();
+      entry.setOffset(currentOffset);
+      currentOffset += entry.writeLocalFileHeader(delegate);
+
+      Files.copy(mapEntry.getKey().toPath(), delegate);
+
+      currentOffset += entry.finish(delegate);
+    }
+
+    new CentralDirectory().writeCentralDirectory(delegate, currentOffset, entries.values());
+
+    delegate.close();
+
+    // Ideally we'd just do this, but that introduces some nasty circular references. *sigh* Instead
+    // we'll do this the tedious way by hand.
+    // MostFiles.deleteRecursively(scratchDir.toPath());
+
+    SimpleFileVisitor<Path> visitor =
+        new SimpleFileVisitor<Path>() {
+          @Override
+          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+              throws IOException {
+            Files.delete(file);
+            return FileVisitResult.CONTINUE;
+          }
+
+          @Override
+          public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
+            if (exc == null) {
+              Files.delete(dir);
+              return FileVisitResult.CONTINUE;
+            }
+            throw exc;
+          }
+        };
+    Files.walkFileTree(scratchDir.toPath(), visitor);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/RepackZipEntries.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/RepackZipEntries.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/RepackZipEntries.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import com.google.common.io.ByteStreams;
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+/** Class for repacking ZIP archives. */
+public class RepackZipEntries {
+  /**
+   * A command that creates a copy of a ZIP archive, making sure that certain user-specified entries
+   * are packed with a certain compression level.
+   *
+   * <p>Can be used, for instance, to force the resources.arsc file in an Android .apk to be
+   * compressed.
+   */
+  public static void repack(
+      Path inputFile,
+      Path outputFile,
+      ImmutableSet<String> entries,
+      ZipCompressionLevel compressionLevel)
+      throws IOException {
+    try (ZipInputStream in =
+            new ZipInputStream(new BufferedInputStream(Files.newInputStream(inputFile)));
+        CustomZipOutputStream out = ZipOutputStreams.newOutputStream(outputFile)) {
+      for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
+        CustomZipEntry customEntry = new CustomZipEntry(entry);
+        if (entries.contains(customEntry.getName())) {
+          customEntry.setCompressionLevel(compressionLevel.getValue());
+        }
+
+        InputStream toUse;
+        // If we're using STORED files, we must pre-calculate the CRC.
+        if (customEntry.getMethod() == ZipEntry.STORED) {
+          try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
+            ByteStreams.copy(in, bos);
+            byte[] bytes = bos.toByteArray();
+            customEntry.setCrc(Hashing.crc32().hashBytes(bytes).padToLong());
+            customEntry.setSize(bytes.length);
+            customEntry.setCompressedSize(bytes.length);
+            toUse = new ByteArrayInputStream(bytes);
+          }
+        } else {
+          toUse = in;
+        }
+
+        out.putNextEntry(customEntry);
+        ByteStreams.copy(toUse, out);
+        out.closeEntry();
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/SimpleZipOutputStreamImpl.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/SimpleZipOutputStreamImpl.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/SimpleZipOutputStreamImpl.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.zip.ZipEntry;
+import javax.annotation.Nullable;
+
+/**
+ * An implementation of {@link CustomZipOutputStream.Impl} that doesn't perform any checks around
+ * duplicate entries.
+ */
+class SimpleZipOutputStreamImpl implements CustomZipOutputStream.Impl {
+
+  private final OutputStream delegate;
+  private long currentOffset = 0;
+  private List<EntryAccounting> entries = new LinkedList<>();
+  @Nullable private EntryAccounting currentEntry = null;
+
+  public SimpleZipOutputStreamImpl(OutputStream stream) {
+    this.delegate = stream;
+  }
+
+  @Override
+  public void actuallyWrite(byte[] b, int off, int len) throws IOException {
+    Objects.requireNonNull(currentEntry).write(delegate, b, off, len);
+  }
+
+  @Override
+  public void actuallyPutNextEntry(ZipEntry entry) throws IOException {
+    currentEntry = new EntryAccounting(entry, currentOffset);
+    entries.add(currentEntry);
+    currentOffset += currentEntry.writeLocalFileHeader(delegate);
+  }
+
+  @Override
+  public void actuallyCloseEntry() throws IOException {
+    if (currentEntry == null) {
+      return; // no-op
+    }
+    currentOffset += currentEntry.finish(delegate);
+    currentEntry = null;
+  }
+
+  @Override
+  public void actuallyClose() throws IOException {
+    new CentralDirectory().writeCentralDirectory(delegate, currentOffset, entries);
+    delegate.close();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/Zip.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/Zip.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/Zip.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.core.util.log.Logger;
+import com.facebook.buck.io.file.PathMatcher;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import com.google.common.io.ByteSource;
+import com.google.common.io.ByteStreams;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.DirectoryStream;
+import java.nio.file.FileVisitResult;
+import java.nio.file.FileVisitor;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.zip.ZipEntry;
+
+public class Zip {
+  private static final Logger LOG = Logger.get(Zip.class);
+
+  private Zip() {}
+
+  /**
+   * Takes a sequence of paths relative to the project root and writes a zip file to {@code out}
+   * with the contents and structure that matches that of the specified paths.
+   */
+  public static void create(AbsPath rootPath, Collection<Path> pathsToIncludeInZip, Path out)
+      throws IOException {
+    try (CustomZipOutputStream zip = ZipOutputStreams.newOutputStream(out)) {
+      for (Path path : pathsToIncludeInZip) {
+
+        boolean isDirectory = ProjectFilesystemUtils.isDirectory(rootPath, path);
+        CustomZipEntry entry = new CustomZipEntry(path, isDirectory);
+
+        // We want deterministic ZIPs, so avoid mtimes.
+        entry.setFakeTime();
+
+        entry.setExternalAttributes(getFileAttributesForZipEntry(rootPath, path));
+
+        zip.putNextEntry(entry);
+        if (!isDirectory) {
+          try (InputStream input = ProjectFilesystemUtils.newFileInputStream(rootPath, path)) {
+            ByteStreams.copy(input, zip);
+          }
+        }
+        zip.closeEntry();
+      }
+    }
+  }
+
+  /** Walks the file tree rooted in baseDirectory to create zip entries */
+  public static void walkBaseDirectoryToCreateEntries(
+      AbsPath rootPath,
+      Map<String, CustomZipEntryWithPath> entries,
+      Path baseDir,
+      ImmutableSet<PathMatcher> ignoredPaths,
+      ImmutableSet<Path> paths,
+      boolean junkPaths,
+      ZipCompressionLevel compressionLevel)
+      throws IOException {
+    // Since filesystem traversals can be non-deterministic, sort the entries we find into
+    // a tree map before writing them out.
+    FileVisitor<Path> pathFileVisitor =
+        new SimpleFileVisitor<Path>() {
+          private boolean isSkipFile(Path file) {
+            return !paths.isEmpty() && !paths.contains(file);
+          }
+
+          private String getEntryName(Path path) {
+            Path relativePath = junkPaths ? path.getFileName() : baseDir.relativize(path);
+            return PathFormatter.pathWithUnixSeparators(relativePath);
+          }
+
+          private CustomZipEntry getZipEntry(String entryName, Path path, BasicFileAttributes attr)
+              throws IOException {
+            boolean isDirectory = ProjectFilesystemUtils.isDirectory(rootPath, path);
+            if (isDirectory) {
+              entryName += "/";
+            }
+
+            CustomZipEntry entry = new CustomZipEntry(entryName);
+            // We want deterministic ZIPs, so avoid mtimes.
+            entry.setFakeTime();
+            entry.setCompressionLevel(
+                isDirectory ? ZipCompressionLevel.NONE.getValue() : compressionLevel.getValue());
+            // If we're using STORED files, we must manually set the CRC, size, and compressed size.
+            if (entry.getMethod() == ZipEntry.STORED && !isDirectory) {
+              entry.setSize(attr.size());
+              entry.setCompressedSize(attr.size());
+              entry.setCrc(
+                  new ByteSource() {
+                    @Override
+                    public InputStream openStream() throws IOException {
+                      return ProjectFilesystemUtils.newFileInputStream(rootPath, path);
+                    }
+                  }.hash(Hashing.crc32()).padToLong());
+            }
+
+            long externalAttributes = getFileAttributesForZipEntry(rootPath, path);
+            LOG.verbose(
+                "Setting mode for entry %s path %s to 0x%08X", entryName, path, externalAttributes);
+            entry.setExternalAttributes(externalAttributes);
+            return entry;
+          }
+
+          @Override
+          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+              throws IOException {
+            if (!file.equals(baseDir) && !isSkipFile(file)) {
+              CustomZipEntry entry = getZipEntry(getEntryName(file), file, attrs);
+              entries.put(entry.getName(), new CustomZipEntryWithPath(entry, Optional.of(file)));
+            }
+            return FileVisitResult.CONTINUE;
+          }
+
+          @Override
+          public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
+              throws IOException {
+            if (!dir.equals(baseDir) && !isSkipFile(dir)) {
+              CustomZipEntry entry = getZipEntry(getEntryName(dir), dir, attrs);
+              entries.put(entry.getName(), new CustomZipEntryWithPath(entry, Optional.empty()));
+            }
+            return FileVisitResult.CONTINUE;
+          }
+        };
+
+    DirectoryStream.Filter<? super Path> ignoreFilter =
+        ProjectFilesystemUtils.getIgnoreFilter(rootPath, true, ignoredPaths);
+    ProjectFilesystemUtils.walkRelativeFileTree(
+        rootPath,
+        baseDir,
+        ProjectFilesystemUtils.getDefaultVisitOptions(),
+        pathFileVisitor,
+        ignoreFilter);
+  }
+
+  /** Writes entries to zipOut stream. */
+  public static void writeEntriesToZip(
+      AbsPath rootPath, CustomZipOutputStream zipOut, Map<String, CustomZipEntryWithPath> entries)
+      throws IOException {
+    // Write the entries out using the iteration order of the tree map above.
+    for (CustomZipEntryWithPath entry : entries.values()) {
+      zipOut.putNextEntry(entry.getEntry());
+      if (entry.getPath().isPresent()) {
+        try (InputStream input =
+            ProjectFilesystemUtils.newFileInputStream(rootPath, entry.getPath().get())) {
+          ByteStreams.copy(input, zipOut);
+        }
+      }
+      zipOut.closeEntry();
+    }
+  }
+
+  /**
+   * @return a list of all entry names in a zip archive.
+   */
+  public static ImmutableList<String> getAllZipEntries(Path archiveAbsolutePath)
+      throws IOException {
+    try (java.util.zip.ZipFile zip = new java.util.zip.ZipFile(archiveAbsolutePath.toFile())) {
+      return Collections.list(zip.entries()).stream()
+          .map(ZipEntry::getName)
+          .collect(ImmutableList.toImmutableList());
+    }
+  }
+
+  private static long getFileAttributesForZipEntry(AbsPath rootPath, Path path) throws IOException {
+    return ProjectFilesystemUtils.getPosixFileModes(rootPath, path) << 16;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipCompressionLevel.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipCompressionLevel.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipCompressionLevel.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+public enum ZipCompressionLevel {
+  NONE(0),
+  MIN(1),
+  DEFAULT(6),
+  MAX(9),
+  ;
+
+  private final int value;
+
+  ZipCompressionLevel(int value) {
+    this.value = value;
+  }
+
+  public int getValue() {
+    return value;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipConstants.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipConstants.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipConstants.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import java.util.Calendar;
+import java.util.zip.ZipEntry;
+
+public class ZipConstants {
+
+  static final long END_MAXLEN = 0xFFFF + ZipEntry.ENDHDR; // header max size ~64k
+
+  static final long ZIP64_ENDSIG = 0x06064b50L;
+  static final long ZIP64_LOCSIG = 0x07064b50L;
+  static final int ZIP64_LOCOFF = 8; // zip64 end offset
+  static final int ZIP64_LOCHDR = 20;
+  static final int ZIP64_ENDTOT = 32; // total number of entries
+  static final int ZIP64_ENDSIZ = 40; // central directory size in bytes
+  static final int ZIP64_ENDOFF = 48; // offset of first CEN header
+  static final int ZIP64_ENDHDR = 56;
+  static final int ZIP64_EXTID = 0x0001;
+
+  static final int ZIP64_MAGICCOUNT = 0xFFFF;
+  static final long ZIP64_MAGICVAL = 0xFFFFFFFFL;
+
+  // The fake time we use: 12:00:00 AM February 1, 1985
+  public static final int DOS_FAKE_TIME = 172032000;
+
+  private ZipConstants() {}
+
+  /**
+   * {@link java.util.zip.ZipEntry#setTime(long)} is timezone-sensitive. Use this value instead of a
+   * hardcoded constant to produce timzeone-agnostic .zip files.
+   *
+   * @return time in milliseconds that represents a fixed date in the current timezone.
+   */
+  public static long getFakeTime() {
+    // Using any timestamp before 1980 (which is supposedly the earliest time supported by the .zip
+    // format) causes files created by JRE 1.7 to be different than JRE 1.8. This is because 1.8
+    // actually supports setting timestamps to earlier than 1980, whereas 1.7 rounds up to 1980.
+    // We also need to resort to the deprecated date constructor as the ZipEntry uses deprecated
+    // Date methods that depend on the current timezone.
+    // Finally 1980.01.01 doesn't work across all timezones across Java 1.7 and 1.8. Fun times.
+    Calendar c = Calendar.getInstance();
+    c.set(1985, Calendar.FEBRUARY, 1, 0, 0, 0);
+    return c.getTimeInMillis();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipFileJarEntryContainer.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipFileJarEntryContainer.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipFileJarEntryContainer.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+import java.util.stream.Stream;
+import java.util.zip.ZipEntry;
+import javax.annotation.Nullable;
+
+/** Provides all entries of a given zip or jar file, so they can be added to another jar. */
+class ZipFileJarEntryContainer implements JarEntryContainer {
+
+  private final Path jarFilePath;
+  private final boolean readOnly;
+  @Nullable private JarFile jar;
+
+  public ZipFileJarEntryContainer(Path jarFilePath) {
+    this(jarFilePath, false);
+  }
+
+  public ZipFileJarEntryContainer(Path jarFilePath, boolean readOnly) {
+    this.jarFilePath = jarFilePath;
+    this.readOnly = readOnly;
+  }
+
+  @Nullable
+  @Override
+  public Manifest getManifest() throws IOException {
+    return getJarFile().getManifest();
+  }
+
+  @Override
+  public Stream<JarEntrySupplier> stream() throws IOException {
+    return getJarFile().stream()
+        .map(
+            entry ->
+                new JarEntrySupplier(
+                    makeCustomEntry(entry), readOnly, () -> getJarFile().getInputStream(entry)));
+  }
+
+  @Override
+  public void close() throws IOException {
+    if (jar != null) {
+      jar.close();
+      jar = null;
+    }
+  }
+
+  private JarFile getJarFile() throws IOException {
+    if (jar == null) {
+      try {
+        File jarFile = jarFilePath.toFile();
+        jar = new JarFile(jarFile);
+      } catch (IOException e) {
+        throw new IOException("Failed to process ZipFile " + jarFilePath, e);
+      }
+    }
+
+    return jar;
+  }
+
+  private static CustomZipEntry makeCustomEntry(ZipEntry entry) {
+    CustomZipEntry wrappedEntry = new CustomZipEntry(entry);
+
+    // For deflated entries, the act of re-"putting" this entry means we're re-compressing
+    // the data that we've just uncompressed.  Due to various environmental issues (e.g. a
+    // newer version of zlib, changed compression settings), we may end up with a different
+    // compressed size.  This causes an issue in java's `java.util.zip.ZipOutputStream`
+    // implementation, as it only updates the compressed size field if one of `crc`,
+    // `compressedSize`, or `size` is -1.  When we copy the entry as-is, none of these are
+    // -1, and we may end up with an incorrect compressed size, in which case, we'll get an
+    // exception.  So, for deflated entries, reset the compressed size to -1 (as the
+    // ZipEntry(String) would).
+    // See https://github.com/spearce/buck/commit/8338c1c3d4a546f577eed0c9941d9f1c2ba0a1b7.
+    if (wrappedEntry.getMethod() == ZipEntry.DEFLATED) {
+      wrappedEntry.setCompressedSize(-1);
+    }
+
+    return wrappedEntry;
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipOutputStreams.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipOutputStreams.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipOutputStreams.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import com.facebook.buck.util.io.IoUtil;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+public class ZipOutputStreams {
+
+  /** The size of the BufferedOutputStream used to wrap the underlying file. */
+  private static final int FILE_BUFFER_SIZE = 512 * 1024;
+
+  private ZipOutputStreams() {
+    // factory class
+  }
+
+  /**
+   * Create a new {@link CustomZipOutputStream} that outputs to the given {@code zipFile}. Note that
+   * the parent directory of the {@code zipFile} must exist already. The returned stream will throw
+   * an exception should duplicate entries be added.
+   *
+   * @param zipFile The file to write to.
+   */
+  public static CustomZipOutputStream newOutputStream(Path zipFile) throws IOException {
+    return IoUtil.mapJustOpened(
+        Files.newOutputStream(zipFile),
+        s -> newOutputStream(new BufferedOutputStream(s, FILE_BUFFER_SIZE)));
+  }
+
+  /**
+   * Create a new {@link CustomZipOutputStream} that will by default act in the same way as {@link
+   * java.util.zip.ZipOutputStream}, notably by throwing an exception if duplicate entries are
+   * added.
+   *
+   * @param out The output stream to write to.
+   */
+  public static CustomZipOutputStream newOutputStream(OutputStream out) {
+    return newOutputStream(out, HandleDuplicates.THROW_EXCEPTION);
+  }
+
+  public static CustomJarOutputStream newJarOutputStream(OutputStream out) {
+    return newJarOutputStream(out, HandleDuplicates.THROW_EXCEPTION);
+  }
+
+  /**
+   * Create a new {@link CustomZipOutputStream} that handles duplicate entries in the way dictated
+   * by {@code mode}.
+   *
+   * @param zipFile The file to write to.
+   * @param mode How to handle duplicate entries.
+   */
+  public static CustomZipOutputStream newOutputStream(Path zipFile, HandleDuplicates mode)
+      throws IOException {
+    return IoUtil.mapJustOpened(
+        Files.newOutputStream(zipFile),
+        s -> newOutputStream(new BufferedOutputStream(s, FILE_BUFFER_SIZE), mode));
+  }
+
+  /** Open jar output stream. */
+  public static CustomJarOutputStream newJarOutputStream(Path jarFile, HandleDuplicates mode)
+      throws IOException {
+    return IoUtil.mapJustOpened(
+        Files.newOutputStream(jarFile),
+        s -> newJarOutputStream(new BufferedOutputStream(s, FILE_BUFFER_SIZE), mode));
+  }
+
+  /** Open jar output stream that will to append entries on top of an input jar. */
+  public static CustomJarOutputStream appendJarOutputStream(Path inputJar, Path outputJar)
+      throws IOException {
+
+    final IncrementalJarOutputStreamImpl incrementalJar =
+        IncrementalJarOutputStreamImpl.createIncrementalJar(inputJar, outputJar);
+
+    return IoUtil.mapJustOpened(
+        incrementalJar.getDelegate(), s -> new CustomJarOutputStream(incrementalJar));
+  }
+
+  /**
+   * Create a new {@link CustomZipOutputStream} that handles duplicate entries in the way dictated
+   * by {@code mode}.
+   *
+   * @param out The output stream to write to.
+   * @param mode How to handle duplicate entries.
+   */
+  public static CustomZipOutputStream newOutputStream(OutputStream out, HandleDuplicates mode) {
+    return new CustomZipOutputStream(newImpl(out, mode));
+  }
+
+  public static CustomJarOutputStream newJarOutputStream(OutputStream out, HandleDuplicates mode) {
+    return new CustomJarOutputStream(newImpl(out, mode));
+  }
+
+  public static CustomZipOutputStream newSimpleOutputStream(OutputStream out) {
+    return new CustomZipOutputStream(new SimpleZipOutputStreamImpl(out));
+  }
+
+  protected static CustomZipOutputStream.Impl newImpl(OutputStream out, HandleDuplicates mode) {
+    CustomZipOutputStream.Impl impl;
+    switch (mode) {
+      case APPEND_TO_ZIP:
+      case THROW_EXCEPTION:
+        impl = new AppendingZipOutputStreamImpl(out, mode == HandleDuplicates.THROW_EXCEPTION);
+        break;
+      case OVERWRITE_EXISTING:
+        impl = new OverwritingZipOutputStreamImpl(out);
+        break;
+      default:
+        throw new RuntimeException(
+            String.format("Unable to determine which zip output mode to use: %s", mode));
+    }
+
+    return impl;
+  }
+
+  public enum HandleDuplicates {
+    /** Duplicate entries are simply appended to the zip. */
+    APPEND_TO_ZIP,
+    /** An exception should be thrown if a duplicate entry is added to a zip. */
+    THROW_EXCEPTION,
+    /** A duplicate entry overwrites an existing entry with the same name. */
+    OVERWRITE_EXISTING
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipScrubber.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipScrubber.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/ZipScrubber.java
@@ -0,0 +1,300 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip;
+
+import static java.nio.file.StandardOpenOption.CREATE_NEW;
+
+import com.facebook.buck.util.nio.LargeByteBuffer;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+import org.kohsuke.args4j.Argument;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+
+/** Tool to eliminate non-deterministic or problematic bits of zip files. */
+public class ZipScrubber {
+  private ZipScrubber() {}
+
+  private static final String USAGE =
+      "usage: ZipScrubber [--paths-to-scrub <PATHS_TO_SCRUB_FILE] input_file"
+          + " [scrubbed_file_output]";
+  private static final long ZIP64_ENDCDL = 0x07064b50L;
+  private static final int ZIP64_ENDCDL_OFFSET = -20;
+
+  private static final int ZIP64_ENDTOT = 32; // 32 = 4 + 8 + 2 + 2 + 4 + 4 + 8
+  private static final int ZIP64_ENDOFF = 48; // 48 = 4 + 8 + 2 + 2 + 4 + 4 + 8 + 8 + 8
+
+  private static final int EXTENDED_TIMESTAMP_ID = 0x5455;
+  private static final int EXTENDED_ZIP64_ID = 0x0001;
+
+  private static void check(boolean expression, String msg) throws IOException {
+    if (!expression) {
+      throw new IOException(msg);
+    }
+  }
+
+  public static void scrubZip(Path zipPath) throws IOException {
+    try (FileChannel channel =
+        FileChannel.open(zipPath, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
+      try (LargeByteBuffer.Scoped buffer = LargeByteBuffer.withFileChannel(channel)) {
+        scrubZipBuffer(buffer);
+      }
+    }
+  }
+
+  @VisibleForTesting
+  static void scrubZipBuffer(LargeByteBuffer map) throws IOException {
+    map.order(ByteOrder.LITTLE_ENDIAN);
+
+    // Search backwards from the end of the ZIP file, searching for the EOCD signature, which
+    // designates the start of the EOCD.
+    long eocdOffset = map.limit() - ZipEntry.ENDHDR;
+    while (map.getInt(eocdOffset) != ZipEntry.ENDSIG) {
+      eocdOffset--;
+    }
+
+    long cdEntries, cdOffset;
+    // ZIP64 files can be identified by a separate ZIP64 EOCD section with a magic value.
+    // See https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT for more details.
+    final boolean isZip64 =
+        eocdOffset + ZIP64_ENDCDL_OFFSET >= 0
+            && map.getLong(eocdOffset + ZIP64_ENDCDL_OFFSET) == ZIP64_ENDCDL;
+
+    if (isZip64) {
+      // This is a ZIP64 format, and we need to look for fields in the ZIP64 EOCD.
+      long zip64eocdOffset = map.getLong(eocdOffset + ZIP64_ENDCDL_OFFSET + 8);
+      cdEntries = map.getLong(zip64eocdOffset + ZIP64_ENDTOT);
+      cdOffset = map.getLong(zip64eocdOffset + ZIP64_ENDOFF);
+
+    } else {
+      // This is a ZIP32, and we can use the normal places for fields.
+      cdEntries = Short.toUnsignedLong(map.getShort(eocdOffset + ZipEntry.ENDTOT));
+      cdOffset = Integer.toUnsignedLong(map.getInt(eocdOffset + ZipEntry.ENDOFF));
+    }
+
+    ArrayList<Long> localHeaderOffsets = new ArrayList<>();
+
+    // Go through each CD file entry and scrub them.
+    for (long idx = 0; idx < cdEntries; idx++) {
+      LargeByteBuffer entry = map.slice(cdOffset);
+      check(entry.getInt(0) == ZipEntry.CENSIG, "expected central directory header signature");
+
+      entry.putInt(ZipEntry.CENTIM, ZipConstants.DOS_FAKE_TIME);
+
+      int filenameLength = entry.getShort(ZipEntry.CENNAM);
+      int extrasLength = entry.getShort(ZipEntry.CENEXT);
+      int commentLength = entry.getShort(ZipEntry.CENCOM);
+
+      long compressedSize = Integer.toUnsignedLong(entry.getInt(ZipEntry.CENSIZ));
+      long originalSize = Integer.toUnsignedLong(entry.getInt(ZipEntry.CENLEN));
+
+      // Slice out the extra fields
+      LargeByteBuffer extras =
+          entry.position(ZipEntry.CENHDR + filenameLength).slice(0, extrasLength);
+
+      // Keep track of the local headers for later...
+      long headerOffset = Integer.toUnsignedLong(entry.getInt(ZipEntry.CENOFF));
+      localHeaderOffsets.add(
+          getLocalHeaderOffset(extras, isZip64, compressedSize, originalSize, headerOffset));
+
+      scrubExtraFields(extras.position(0));
+
+      cdOffset += ZipEntry.CENHDR + filenameLength + extrasLength + commentLength;
+    }
+
+    // Go back through the local headers spread around the archive and scrub them.
+    for (long localHeaderOffset : localHeaderOffsets) {
+      scrubLocalEntry(map.slice(localHeaderOffset));
+    }
+  }
+
+  private static long getLocalHeaderOffset(
+      LargeByteBuffer extras,
+      boolean isZip64,
+      long compressedSize,
+      long originalSize,
+      long headerOffset)
+      throws IOException {
+    if (isZip64) {
+      /*
+       * The ZIP64 extra is made up of:  (from ZIP spec section 4.5.3)
+       *   - ID (1)                   2 bytes
+       *   - Extra Data Size          2 bytes
+       *   - Original Size            8 bytes
+       *   - Compressed Size          8 bytes
+       *   - Relative Header Offset   8 bytes
+       *     ...
+       *
+       * The Original Size and Compressed Size are only in the extra if the value in the CD record
+       * is 0xffffffff. So we need to check those sizes, and if they're there, skip them.
+       */
+      while (extras.position() < extras.limit() - 4) {
+        int id = extras.getShort();
+        int size = extras.getShort() & 0xFFFF;
+        if (id == EXTENDED_ZIP64_ID) {
+          int offset = 0;
+          if (originalSize == 0xffffffffL) {
+            offset += 8;
+          }
+          if (compressedSize == 0xffffffffL) {
+            offset += 8;
+          }
+          if (headerOffset == 0xffffffffL) {
+            return extras.getLong(extras.position() + offset);
+          } else {
+            return headerOffset;
+          }
+        }
+
+        // Skip this extra.
+        extras.position(extras.position() + size);
+      }
+    }
+
+    return headerOffset;
+  }
+
+  private static void scrubLocalEntry(LargeByteBuffer entry) throws IOException {
+    check(entry.getInt(0) == ZipEntry.LOCSIG, "expected local header signature");
+    entry.putInt(ZipEntry.LOCTIM, ZipConstants.DOS_FAKE_TIME);
+    scrubExtraFields(
+        entry.slice(
+            ZipEntry.LOCHDR + entry.getShort(ZipEntry.LOCNAM), entry.getShort(ZipEntry.LOCEXT)));
+  }
+
+  private static void scrubExtraFields(LargeByteBuffer data) throws IOException {
+    // See http://mdfs.net/Docs/Comp/Archiving/Zip/ExtraField for structure of extra fields.
+    //
+    // Additionally, tools like zipalign inject zero values for padding, which seem to violate
+    // the official zip spec.
+    // zipalign README:
+    // https://android.googlesource.com/platform/build/+/refs/tags/android-10.0.0_r33/tools/zipalign/README.txt
+    // zipalign padding:
+    // https://android.googlesource.com/platform/build/+/refs/tags/android-10.0.0_r33/tools/zipalign/ZipEntry.cpp#200
+
+    final long end = data.limit();
+
+    while (data.position() < end) {
+      if (end - data.position() < 4) {
+        // Check that all padding bytes are zero.
+        int padding = 0;
+        while (data.position() != end) {
+          padding = (padding << 8) | (data.get() & 0xFF);
+        }
+        if (padding != 0) {
+          throw new IllegalStateException("Non-zero padding " + padding);
+        }
+        break;
+      }
+
+      int id = data.getShort();
+      int size = Short.toUnsignedInt(data.getShort());
+
+      if (id == EXTENDED_TIMESTAMP_ID) {
+        // 1 byte flag
+        // 0-3 4-byte unix timestamps
+        data.get(); // ignore flags
+        size -= 1;
+        while (size > 0) {
+          data.putInt((int) (ZipConstants.getFakeTime() / 1000));
+          size -= 4;
+        }
+      } else {
+        if (id == 0 && size != 0) {
+          // Padding should be length zero.
+          throw new IllegalStateException("Non-zero length padding " + size);
+        }
+        if (data.position() + size >= end) {
+          break;
+        }
+        data.position(data.position() + size);
+      }
+    }
+  }
+
+  @Option(name = "--paths-to-scrub")
+  private Path pathsToScrubFile;
+
+  @Option(name = "--create-if-not-present")
+  private boolean createIfNotPresent;
+
+  @Argument private List<String> arguments = new ArrayList<>();
+
+  public static void main(String[] args) throws IOException {
+    ZipScrubber main = new ZipScrubber();
+    CmdLineParser parser = new CmdLineParser(main);
+    try {
+      parser.parseArgument(args);
+      main.run();
+      System.exit(0);
+    } catch (CmdLineException e) {
+      System.err.println(e.getMessage());
+      parser.printUsage(System.err);
+      System.exit(1);
+    }
+  }
+
+  public void run() throws IOException {
+    Preconditions.checkState(pathsToScrubFile != null || !arguments.isEmpty(), USAGE);
+    Preconditions.checkState(
+        arguments.isEmpty() || arguments.size() == 1 || arguments.size() == 2, USAGE);
+    if (pathsToScrubFile != null) {
+      List<Path> pathsToScrub =
+          Files.readAllLines(pathsToScrubFile).stream()
+              .map(Paths::get)
+              .collect(Collectors.toList());
+      for (Path pathToScrub : pathsToScrub) {
+        if (!Files.exists(pathToScrub)) {
+          Preconditions.checkState(
+              createIfNotPresent, "%s does not exist so cannot be scrubbed!", pathToScrub);
+          createEmptyZip(pathToScrub);
+        }
+
+        Preconditions.checkState(pathToScrub.toFile().setWritable(true));
+        scrubZip(pathToScrub);
+      }
+    }
+
+    if (!arguments.isEmpty()) {
+      Path inputZip = Paths.get(arguments.get(0));
+      Preconditions.checkState(
+          Files.exists(inputZip), "%s does not exist so cannot be scrubbed!", inputZip);
+
+      Path scrubbedZip = inputZip;
+      // Scrub in place if no output path
+      if (arguments.size() == 2) {
+        scrubbedZip = Paths.get(arguments.get(1));
+        Files.copy(inputZip, scrubbedZip);
+      }
+      Preconditions.checkState(scrubbedZip.toFile().setWritable(true));
+      scrubZip(scrubbedZip);
+    }
+  }
+
+  private static void createEmptyZip(Path zipPath) throws IOException {
+    ZipOutputStream zipOutputStream =
+        new ZipOutputStream(Files.newOutputStream(zipPath, CREATE_NEW));
+    zipOutputStream.close();
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "collect",
+    srcs = glob(["*.java"]),
+    tests = [
+        "prelude//toolchains/android/test/com/facebook/buck/util/zip/collect:collect",
+    ],
+    visibility = ["PUBLIC"],
+    deps = [
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem:filesystem",
+        "prelude//toolchains/android/src/com/facebook/buck/io/filesystem/impl:utils",
+        "prelude//toolchains/android/src/com/facebook/buck/io/pathformat:pathformat",
+        "prelude//toolchains/android/src/com/facebook/buck/util:util",
+        "prelude//toolchains/android/src/com/facebook/buck/util/unarchive:unarchive",
+        "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip",
+        "prelude//toolchains/android/third-party:guava",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/FileZipEntrySource.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/FileZipEntrySource.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/FileZipEntrySource.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip.collect;
+
+import java.nio.file.Path;
+import java.util.Objects;
+
+/** A file source for an entry in a zip file. */
+public class FileZipEntrySource implements ZipEntrySource {
+
+  private final Path sourceFilePath;
+  private final String entryName;
+
+  public FileZipEntrySource(Path sourceFilePath, String entryName) {
+    this.sourceFilePath = sourceFilePath;
+    this.entryName = entryName;
+  }
+
+  @Override
+  public Path getSourceFilePath() {
+    return sourceFilePath;
+  }
+
+  @Override
+  public String getEntryName() {
+    return entryName;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) {
+      return true;
+    }
+    if (o == null || getClass() != o.getClass()) {
+      return false;
+    }
+    FileZipEntrySource that = (FileZipEntrySource) o;
+    return Objects.equals(sourceFilePath, that.sourceFilePath)
+        && Objects.equals(entryName, that.entryName);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(sourceFilePath, entryName);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/OnDuplicateEntry.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/OnDuplicateEntry.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/OnDuplicateEntry.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip.collect;
+
+/** Action to take when a duplicate entry is encountered when building a zip file. */
+public enum OnDuplicateEntry {
+  /** Fail fast. */
+  FAIL,
+  /** An entry is overwritten. Last entry wins. */
+  OVERWRITE,
+  /** All entries are stored in the archive including the duplicates. */
+  APPEND,
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySource.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySource.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySource.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip.collect;
+
+import java.nio.file.Path;
+
+/** Represents source for an entry in a zip file. */
+public interface ZipEntrySource {
+
+  /**
+   * Location of a file where source is located. Data for the entry can be located in a part of a
+   * file.
+   */
+  Path getSourceFilePath();
+
+  /** The name of the destination entry. */
+  String getEntryName();
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollection.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollection.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollection.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip.collect;
+
+import com.google.common.collect.ImmutableList;
+import java.util.Objects;
+
+/**
+ * A set of sources to store as entries in a zip file. A source entry can be either a file or an
+ * entry from another zip file.
+ */
+public class ZipEntrySourceCollection {
+
+  private final ImmutableList<ZipEntrySource> sources;
+
+  public ZipEntrySourceCollection(ImmutableList<ZipEntrySource> sources) {
+    this.sources = sources;
+  }
+
+  public ImmutableList<ZipEntrySource> getSources() {
+    return sources;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) {
+      return true;
+    }
+    if (o == null || getClass() != o.getClass()) {
+      return false;
+    }
+    ZipEntrySourceCollection that = (ZipEntrySourceCollection) o;
+    return Objects.equals(sources, that.sources);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(sources);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollectionBuilder.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollectionBuilder.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollectionBuilder.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip.collect;
+
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.facebook.buck.util.PatternsMatcher;
+import com.facebook.buck.util.zip.Zip;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.LinkedHashMultimap;
+import com.google.common.collect.Multimap;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+
+/**
+ * A builder for {@link ZipEntrySourceCollection} that allows to build a collection using provided
+ * source files as well as source zip files.
+ */
+public class ZipEntrySourceCollectionBuilder {
+  private final PatternsMatcher excludedEntriesMatcher;
+  private final OnDuplicateEntry onDuplicateEntryAction;
+  private final Function<ZipEntrySource, Void> onDuplicateEntryHandler;
+  private final Multimap<String, ZipEntrySource> entryNameToEntry;
+
+  public ZipEntrySourceCollectionBuilder(
+      ImmutableSet<Pattern> entriesToExclude, OnDuplicateEntry onDuplicateEntryAction) {
+    this.excludedEntriesMatcher = new PatternsMatcher(entriesToExclude);
+    this.onDuplicateEntryAction = onDuplicateEntryAction;
+    this.onDuplicateEntryHandler = createDuplicateEntryHandler();
+    this.entryNameToEntry = LinkedHashMultimap.create();
+  }
+
+  /** Add the given file as a source for an entry with the provided name. */
+  public void addFile(String entryName, Path sourceFilePath) {
+    entryName = PathFormatter.pathWithUnixSeparators(entryName);
+    if (excludedEntriesMatcher.matches(entryName)) {
+      return;
+    }
+    ZipEntrySource entrySource = new FileZipEntrySource(sourceFilePath, entryName);
+    Collection<ZipEntrySource> oldEntries = entryNameToEntry.get(entrySource.getEntryName());
+    if (oldEntries.isEmpty()) {
+      entryNameToEntry.put(entrySource.getEntryName(), entrySource);
+    } else {
+      onDuplicateEntryHandler.apply(entrySource);
+    }
+  }
+
+  /**
+   * Add all entries of a given zip file to the collection (excluding entries that match {@link
+   * #excludedEntriesMatcher}.
+   */
+  public void addZipFile(Path zipFilePath) throws IOException {
+    ImmutableList<String> zipEntries = Zip.getAllZipEntries(zipFilePath);
+    for (int i = 0; i < zipEntries.size(); ++i) {
+      String entryName = zipEntries.get(i);
+      if (excludedEntriesMatcher.matches(entryName)) {
+        continue;
+      }
+      ZipEntrySource entrySource = new ZipEntrySourceFromZip(zipFilePath, entryName, i);
+      Collection<ZipEntrySource> oldEntries = entryNameToEntry.get(entryName);
+      if (oldEntries.isEmpty()) {
+        entryNameToEntry.put(entryName, entrySource);
+      } else {
+        onDuplicateEntryHandler.apply(entrySource);
+      }
+    }
+  }
+
+  public ZipEntrySourceCollection build() {
+    ArrayList<ZipEntrySource> allEntries = new ArrayList<ZipEntrySource>(entryNameToEntry.values());
+    Collections.sort(
+        allEntries,
+        new Comparator<ZipEntrySource>() {
+          @Override
+          public int compare(ZipEntrySource z1, ZipEntrySource z2) {
+            return z1.getEntryName().compareTo(z2.getEntryName());
+          }
+        });
+    return new ZipEntrySourceCollection(ImmutableList.copyOf(allEntries));
+  }
+
+  private Function<ZipEntrySource, Void> createDuplicateEntryHandler() {
+    switch (onDuplicateEntryAction) {
+      case FAIL:
+        return (entry) -> {
+          Collection<ZipEntrySource> oldEntries = entryNameToEntry.get(entry.getEntryName());
+          throw new RuntimeException(
+              String.format(
+                  "Duplicate entry \"%s\" is coming from %s and %s",
+                  entry.getEntryName(),
+                  Iterables.getOnlyElement(oldEntries).getSourceFilePath(),
+                  entry.getSourceFilePath()));
+        };
+      case APPEND:
+        return (entry) -> {
+          entryNameToEntry.put(entry.getEntryName(), entry);
+          return null;
+        };
+      case OVERWRITE:
+        return (entry) -> {
+          entryNameToEntry.removeAll(entry.getEntryName());
+          entryNameToEntry.put(entry.getEntryName(), entry);
+          return null;
+        };
+      default:
+        throw new IllegalArgumentException("Unknown action: " + onDuplicateEntryAction);
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollectionWriter.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollectionWriter.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceCollectionWriter.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip.collect;
+
+import com.facebook.buck.core.filesystems.AbsPath;
+import com.facebook.buck.io.file.MorePosixFilePermissions;
+import com.facebook.buck.io.filesystem.impl.ProjectFilesystemUtils;
+import com.facebook.buck.io.pathformat.PathFormatter;
+import com.facebook.buck.util.zip.CustomZipEntry;
+import com.facebook.buck.util.zip.CustomZipOutputStream;
+import com.facebook.buck.util.zip.ZipOutputStreams;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.Multimap;
+import com.google.common.io.ByteStreams;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.attribute.PosixFilePermission;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+/** Writes a {@link ZipEntrySourceCollection} to a zip file. */
+public class ZipEntrySourceCollectionWriter {
+
+  private final AbsPath rootPath;
+  private final boolean hardcodePermissions;
+
+  public ZipEntrySourceCollectionWriter(AbsPath rootPath, boolean hardcodePermissions) {
+    this.rootPath = rootPath;
+    this.hardcodePermissions = hardcodePermissions;
+  }
+
+  /** Creates a zip archive in a given file by copying all entries listed in the collection. */
+  public void copyToZip(ZipEntrySourceCollection collection, Path outputFile) throws IOException {
+    // For every source archive contains list of entries and their positions to include when
+    // copying.
+    Map<Path, Multimap<String, Integer>> sourceArchiveEntries = new HashMap<>();
+    collection.getSources().stream()
+        .filter(ZipEntrySourceFromZip.class::isInstance)
+        .map(ZipEntrySourceFromZip.class::cast)
+        .forEach(
+            entry ->
+                sourceArchiveEntries
+                    .compute(
+                        entry.getSourceFilePath(),
+                        (k, v) -> (v == null ? HashMultimap.create() : v))
+                    .put(entry.getEntryName(), entry.getEntryPosition()));
+
+    Set<Path> seenFiles = new HashSet<>();
+    try (OutputStream baseOut = ProjectFilesystemUtils.newFileOutputStream(rootPath, outputFile);
+        CustomZipOutputStream zip = ZipOutputStreams.newSimpleOutputStream(baseOut)) {
+      for (ZipEntrySource entrySource : collection.getSources()) {
+        if (!seenFiles.add(entrySource.getSourceFilePath())) {
+          continue;
+        }
+        Path sourceFilePath = entrySource.getSourceFilePath();
+        String entryName = entrySource.getEntryName();
+        if (entrySource instanceof FileZipEntrySource) {
+          addDirectoryEntries(zip, seenFiles, entryName);
+          copyFile(zip, entryName, sourceFilePath);
+        } else if (entrySource instanceof ZipEntrySourceFromZip) {
+          copyZip(
+              zip,
+              sourceFilePath,
+              seenFiles,
+              sourceArchiveEntries.getOrDefault(sourceFilePath, HashMultimap.create()));
+        }
+      }
+    }
+  }
+
+  /**
+   * For a given entry name adds entries for all parent directories unless they are already added.
+   */
+  private void addDirectoryEntries(CustomZipOutputStream out, Set<Path> seenFiles, String entryName)
+      throws IOException {
+    Path entryPath = ProjectFilesystemUtils.getPath(rootPath, entryName).getParent();
+    if (entryPath == null) {
+      return;
+    }
+    Deque<Path> directoriesToAdd = new ArrayDeque<>(entryPath.getNameCount());
+    while (entryPath != null && seenFiles.add(entryPath)) {
+      directoriesToAdd.push(entryPath);
+      entryPath = entryPath.getParent();
+    }
+    while (!directoriesToAdd.isEmpty()) {
+      Path currentPath = directoriesToAdd.pop();
+      CustomZipEntry entry =
+          new CustomZipEntry(PathFormatter.pathWithUnixSeparators(currentPath) + "/");
+      entry.setFakeTime();
+      out.putNextEntry(entry);
+      out.closeEntry();
+    }
+  }
+
+  private void copyFile(CustomZipOutputStream out, String entryName, Path from) throws IOException {
+    CustomZipEntry entry = new CustomZipEntry(entryName);
+    entry.setFakeTime();
+    entry.setExternalAttributes(getFileAttributesForZipEntry(from));
+
+    out.putNextEntry(entry);
+    try (InputStream input = ProjectFilesystemUtils.newFileInputStream(rootPath, from)) {
+      ByteStreams.copy(input, out);
+    }
+    out.closeEntry();
+  }
+
+  public long getFileAttributesForZipEntry(Path path) throws IOException {
+    long permissions;
+    if (this.hardcodePermissions) {
+      /*
+       * Goal:
+       *   We need consistent unix permissions for all zip entries, because we want the zip file to be a byte-for-byte match across different execution platforms.
+       * Problem #1:
+       *   On Windows, there are no unix permissions to be retrieved, all we can do is guess.
+       * Problem #2:
+       *   Even across flavors of Unix, RE makes all inputs read-only, so permissions can vary.
+       * Solution:
+       *   The only truly reliable way to get consistent permissions is to force the same one for all zip entries.
+       */
+      permissions =
+          MorePosixFilePermissions.toMode(
+              Set.of(
+                  PosixFilePermission.OWNER_WRITE,
+                  PosixFilePermission.OWNER_READ,
+                  PosixFilePermission.GROUP_READ,
+                  PosixFilePermission.OTHERS_READ)); // i.e. 0644
+      return permissions << 16;
+    } else {
+      permissions = ProjectFilesystemUtils.getPosixFileModes(rootPath, path);
+    }
+    return permissions << 16;
+  }
+
+  private static void copyZip(
+      CustomZipOutputStream out,
+      Path from,
+      Set<Path> seenFiles,
+      Multimap<String, Integer> allowedEntries)
+      throws IOException {
+    try (ZipInputStream in =
+        new ZipInputStream(new BufferedInputStream(Files.newInputStream(from)))) {
+      int position = 0;
+      for (ZipEntry entry = in.getNextEntry();
+          entry != null;
+          entry = in.getNextEntry(), position++) {
+        if (!allowedEntries.containsKey(entry.getName())) {
+          continue;
+        }
+        if (!allowedEntries.get(entry.getName()).contains(position)) {
+          continue;
+        }
+        if (entry.isDirectory()) {
+          seenFiles.add(Paths.get(entry.getName()));
+        }
+        CustomZipEntry customEntry = new CustomZipEntry(entry);
+        customEntry.setFakeTime();
+        out.putNextEntry(customEntry);
+        ByteStreams.copy(in, out);
+        out.closeEntry();
+      }
+    }
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceFromZip.java b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceFromZip.java
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/util/zip/collect/ZipEntrySourceFromZip.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+package com.facebook.buck.util.zip.collect;
+
+import java.nio.file.Path;
+import java.util.Objects;
+
+/** A source for a zip file entry that represents an entry for another zip file. */
+public class ZipEntrySourceFromZip implements ZipEntrySource {
+
+  private final Path sourceFilePath;
+  private final String entryName;
+  private final int entryPosition;
+
+  public ZipEntrySourceFromZip(Path sourceFilePath, String entryName, int entryPosition) {
+    this.sourceFilePath = sourceFilePath;
+    this.entryName = entryName;
+    this.entryPosition = entryPosition;
+  }
+
+  /** Path to the source zip file. */
+  @Override
+  public Path getSourceFilePath() {
+    return sourceFilePath;
+  }
+
+  /** The name of the entry */
+  @Override
+  public String getEntryName() {
+    return entryName;
+  }
+
+  /** Position of the entry in the list of entries. */
+  public int getEntryPosition() {
+    return entryPosition;
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(entryPosition, entryName, sourceFilePath);
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (obj == null || getClass() != obj.getClass()) {
+      return false;
+    }
+    final ZipEntrySourceFromZip other = (ZipEntrySourceFromZip) obj;
+    return entryPosition == other.entryPosition
+        && Objects.equals(entryName, other.entryName)
+        && Objects.equals(sourceFilePath, other.sourceFilePath);
+  }
+}
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/workertool/resources/proto/BUCK b/buck2/prelude/toolchains/android/src/com/facebook/buck/workertool/resources/proto/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/workertool/resources/proto/BUCK
@@ -0,0 +1,21 @@
+load("@prelude//toolchains/android/tools:protobuf.bzl", "protobuf_src_gen")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+protobuf_src_gen(
+    name = "worker-model",
+    srcs = [
+        "worker.proto",
+    ],
+    proto_path = [],
+    deps = [
+        "prelude//toolchains/android/third-party:jakarta.annotation-api",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/third-party:protobuf",
+        "prelude//toolchains/android/third-party:remote-apis",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/src/com/facebook/buck/workertool/resources/proto/worker.proto b/buck2/prelude/toolchains/android/src/com/facebook/buck/workertool/resources/proto/worker.proto
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/src/com/facebook/buck/workertool/resources/proto/worker.proto
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+// This file is synced from fbcode/buck2/app/buck2_worker_proto/worker.proto
+// To update run xplat/toolchains/android/sdk/scripts/sync_proto.sh
+
+syntax = "proto3";
+
+option java_multiple_files = true;
+option java_package = "com.facebook.buck.worker.model";
+option java_outer_classname = "WorkerProto";
+
+package worker;
+
+message ExecuteCommand {
+  message EnvironmentEntry {
+    bytes key = 1;
+    bytes value = 2;
+  }
+
+  repeated bytes argv = 1;
+  repeated EnvironmentEntry env = 2;
+  uint64 timeout_s = 3;
+}
+
+message ExecuteResponse {
+  int32 exit_code = 1;
+  string stderr = 2;
+  uint64 timed_out_after_s = 3;
+}
+
+message ExecuteCancel {}
+
+message ExecuteEvent {
+  oneof data {
+    ExecuteCommand command = 1;
+    ExecuteCancel cancel = 2;
+  }
+}
+
+service Worker {
+  // TODO(ctolliday) delete once workers switch to Exec
+  rpc Execute(ExecuteCommand) returns (ExecuteResponse) {};
+
+  rpc Exec(stream ExecuteEvent) returns (ExecuteResponse) {};
+}
diff --git a/buck2/prelude/toolchains/android/third-party/BUCK b/buck2/prelude/toolchains/android/third-party/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/third-party/BUCK
@@ -0,0 +1,1356 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_binary", "buck_java_library", "third_party_exe", "third_party_jar")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+# === Begin: aapt2-proto
+
+third_party_jar(
+    name = "aapt2-proto-prebuilt",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/android/tools/build/aapt2-proto:aapt2-proto",
+    sha1 = "605bc2d642e5812469ff0333df1b65ead289ccd8",
+    url = "mvn:https://maven.google.com:com.android.tools.build:aapt2-proto:jar:8.7.3-12006047",
+)
+
+buck_java_library(
+    name = "aapt2-proto",
+    visibility = ["PUBLIC"],
+    exported_deps = [
+        ":aapt2-proto-prebuilt",
+        ":protobuf",
+    ],
+)
+# ===   End: aapt2-proto
+
+# === Begin: android
+
+third_party_jar(
+    name = "android-annotations",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/android/tools/annotations:annotations",
+    sha1 = "1946e7f75bc1615b4abfc0f83899934dfcbdf1fc",
+    url = "mvn:https://maven.google.com:com.android.tools:annotations:jar:31.7.3",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "sdklib",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/android/tools/sdklib:sdklib",
+    sha1 = "0adb7cac2ab282100e2b8b6d66b997a69ed06adf",
+    url = "mvn:https://maven.google.com:com.android.tools:sdklib:jar:31.7.3",
+    visibility = [
+        "prelude//toolchains/android/third-party/aosp:aosp",
+    ],
+)
+
+buck_java_library(
+    name = "tools-sdk-common",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/aapt:merge_android_resource_sources",
+        "prelude//toolchains/android/src/com/facebook/buck/android/manifest:manifest",
+        "prelude//toolchains/android/test/com/facebook/buck/android:testutil",
+        "prelude//toolchains/android/test/com/facebook/buck/android/manifest:manifest",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java:java",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java:testutil",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi:abi",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/java/abi:testutil",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin:kotlin",
+        "prelude//toolchains/android/test/com/facebook/buck/testrunner:testrunner",
+        "prelude//toolchains/android/test/com/facebook/buck/testutil:testutil_test",
+        "prelude//toolchains/android/test/com/facebook/buck/testutil/integration:util",
+        "prelude//toolchains/android/test/com/facebook/buck/util:util",
+        "prelude//toolchains/android/test/com/facebook/buck/util/xml:xml",
+    ],
+    deps = [
+        ":layoutlib-api",
+        ":sdklib",
+    ],
+    exported_deps = [
+        ":android-common",
+        ":sdk-common",
+    ],
+)
+
+third_party_jar(
+    name = "android-common",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/android/tools/common:common",
+    sha1 = "c3df7b51ee1a72acf051e0e5efbeb8023fb4ea57",
+    url = "mvn:https://maven.google.com:com.android.tools:common:jar:31.7.3",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "sdk-common",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/android/tools/sdk-common:sdk-common",
+    sha1 = "d17c3d28724a5f3e90a5ae053714627b740ff80c",
+    url = "mvn:https://maven.google.com:com.android.tools:sdk-common:jar:31.7.3",
+    visibility = [
+        "prelude//toolchains/android/third-party/aosp:aosp",
+    ],
+    deps = [":guava"],
+)
+
+third_party_jar(
+    name = "layoutlib-api",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/android/tools/layoutlib/layoutlib-api:layoutlib-api",
+    sha1 = "6abada4555fa60825ea5f353443a7e561445c4f0",
+    url = "mvn:https://maven.google.com:com.android.tools.layoutlib:layoutlib-api:jar:31.7.3",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/aapt:merge_android_resource_sources",
+    ],
+)
+
+third_party_jar(
+    name = "ddmlib",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/android/tools/ddms/ddmlib:ddmlib",
+    sha1 = "525b44de6936a7c487095652f014d0bfc84bb9ad",
+    url = "mvn:https://maven.google.com:com.android.tools.ddms:ddmlib:jar:31.7.3",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":android-common",
+        ":guava",
+        ":kxml2",
+        ":protobuf",
+    ],
+)
+
+third_party_jar(
+    name = "manifest-merger",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/android/tools/build/manifest-merger:manifest-merger",
+    sha1 = "0d0489e76e4eb785336317add6b65d57b928a429",
+    url = "mvn:com.android.tools.build:manifest-merger:jar:31.7.3",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/manifest:manifest",
+        "prelude//toolchains/android/third-party:manifest-merger",
+        "prelude//toolchains/android/third-party/aosp:aosp",
+    ],
+)
+# ===   End: android
+
+# === Begin: args4j
+
+third_party_jar(
+    name = "args4j",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/args4j/args4j:args4j__toolchain",
+    sha1 = "244f60c057d72a785227c0562d3560f42a7ea54b",
+    url = "mvn:args4j:args4j:jar:2.37",
+    visibility = ["PUBLIC"],
+)
+# ===   End: args4j
+
+# === Begin: asm
+
+buck_java_library(
+    name = "asm",
+    visibility = ["PUBLIC"],
+    exported_deps = [
+        ":asm-jar",
+        ":asm-tree",
+        ":asm-util",
+    ],
+)
+
+third_party_jar(
+    name = "asm-jar",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/ow2/asm/asm:asm__toolchain",
+    sha1 = "073d7b3086e14beb604ced229c302feff6449723",
+    url = "mvn:org.ow2.asm:asm:jar:9.7",
+)
+
+third_party_jar(
+    name = "asm-tree",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/ow2/asm/asm-tree:asm-tree__toolchain",
+    sha1 = "e446a17b175bfb733b87c5c2560ccb4e57d69f1a",
+    url = "mvn:org.ow2.asm:asm-tree:jar:9.7",
+)
+
+third_party_jar(
+    name = "asm-util",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/ow2/asm/asm-util:asm-util__toolchain",
+    sha1 = "c0655519f24d92af2202cb681cd7c1569df6ead6",
+    url = "mvn:org.ow2.asm:asm-util:jar:9.7",
+)
+# ===   End: asm
+
+# === Begin: bundletool
+
+third_party_jar(
+    name = "bundletool-prebuilt",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/android/tools/build/bundletool:bundletool__toolchain",
+    sha1 = "88e6c67d315e7d2a860bb00b1bd93914f2c4fd33",
+    url = "mvn:https://maven.google.com:com.android.tools.build:bundletool:jar:1.16.0",
+)
+
+buck_java_library(
+    name = "bundletool",
+    visibility = ["PUBLIC"],
+    exported_deps = [
+        ":aapt2-proto",
+        ":bundletool-prebuilt",
+        ":dagger",
+        ":guava",
+        ":jsr330",
+        ":protobuf",
+        ":protobuf-util",
+    ],
+)
+# ===   End: bundletool
+
+# === Begin: commons-compress
+
+third_party_jar(
+    name = "commons-compress",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/apache/commons/commons-compress:commons-compress",
+    sha1 = "659feffdd12280201c8aacb8f7be94f9a883c824",
+    url = "mvn:org.apache.commons:commons-compress:jar:1.26.0",
+    visibility = ["PUBLIC"],
+)
+# ===   End: commons-compress
+
+# === Begin: dagger
+
+third_party_jar(
+    name = "dagger",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/dagger/dagger:dagger",
+    sha1 = "75786d67abe43cac5b61f39a6101276184e708f8",
+    url = "mvn:com.google.dagger:dagger:jar:2.51",
+    visibility = [":bundletool"],
+)
+# ===   End: dagger
+
+# === Begin: dd-plist
+
+third_party_jar(
+    name = "dd-plist",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/googlecode/plist/dd-plist:dd-plist",
+    sha1 = "617d08cc6e9c800e4b77266087cc9294b6d87e11",
+    url = "mvn:com.googlecode.plist:dd-plist:jar:1.28",
+    visibility = ["PUBLIC"],
+)
+# ===   End: dd-plist
+
+# === Begin: diffutils
+
+third_party_jar(
+    name = "diffutils",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/googlecode/java-diff-utils/diffutils:diffutils",
+    sha1 = "7e060dd5b19431e6d198e91ff670644372f60fbd",
+    url = "mvn:com.googlecode.java-diff-utils:diffutils:jar:1.3.0",
+    visibility = ["PUBLIC"],
+)
+# ===   End: diffutils
+
+# === Begin: grpc
+
+buck_java_library(
+    name = "remote-apis",
+    srcs = [],
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/installer/proto:installer-model",
+        "prelude//toolchains/android/src/com/facebook/buck/workertool/resources/proto:worker-model",
+    ],
+    exported_deps = [
+        ":grpc-api",
+        ":grpc-context",
+        ":grpc-core",
+        ":grpc-protobuf",
+        ":grpc-protobuf-lite",
+        ":grpc-stub",
+        ":gson",
+        ":guava",
+        ":jakarta.annotation-api",
+        ":opencensus-api",
+        ":opencensus-contrib-grpc-metrics",
+        ":protobuf",
+        ":protobuf-util",
+    ],
+)
+
+buck_java_library(
+    name = "grpc-api",
+    deps = [":perfmark-api"],
+    exported_deps = [":grpc-api-jar"],
+)
+
+third_party_jar(
+    name = "grpc-api-jar",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/grpc-api:grpc-api__toolchain",
+    sha1 = "2b21b84ab14f632b01281ef2d616a3ed96588f17",
+    url = "mvn:io.grpc:grpc-api:jar:1.24.0",
+)
+
+third_party_jar(
+    name = "grpc-context",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/grpc-context:grpc-context__toolchain",
+    sha1 = "abfd83c3b1a8a0fbc12db3529a339b693056f496",
+    url = "mvn:io.grpc:grpc-context:jar:1.24.0",
+)
+
+third_party_jar(
+    name = "grpc-core",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/grpc-core:grpc-core__toolchain",
+    sha1 = "efa08ef8d3d1de2a05fbb9b4c34ad6a053176206",
+    url = "mvn:io.grpc:grpc-core:jar:1.24.0",
+)
+
+third_party_jar(
+    name = "grpc-netty-shaded",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/grpc-netty-shaded:grpc-netty-shaded",
+    sha1 = "b93f11824ee89d1283801dce8145bc54e1b8e94e",
+    url = "mvn:io.grpc:grpc-netty-shaded:jar:1.24.0",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/installer:installer_server",
+    ],
+)
+
+third_party_jar(
+    name = "grpc-netty",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/grpc-netty:grpc-netty__toolchain",
+    sha1 = "07a9669aa35f447d5181edc1b4f4e887128c045b",
+    url = "mvn:io.grpc:grpc-netty:jar:1.24.0",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc:workertool_grpc",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/cd/workertool/grpc:workertool_grpc",
+    ],
+)
+
+third_party_jar(
+    name = "grpc-protobuf",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/grpc-protobuf:grpc-protobuf__toolchain",
+    sha1 = "b584bf5e69fa8794a9184c1cf66d4c690f21cbc4",
+    url = "mvn:io.grpc:grpc-protobuf:jar:1.24.0",
+)
+
+third_party_jar(
+    name = "grpc-protobuf-lite",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/grpc-protobuf-lite:grpc-protobuf-lite__toolchain",
+    sha1 = "be683c469b7652dc130d2304bdb32379816a4ccc",
+    url = "mvn:io.grpc:grpc-protobuf-lite:jar:1.24.0",
+)
+
+third_party_jar(
+    name = "grpc-stub",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/grpc-stub:grpc-stub__toolchain",
+    sha1 = "7bd32e6bed0389b4d547ac617840c5ebd54768fd",
+    url = "mvn:io.grpc:grpc-stub:jar:1.24.0",
+)
+
+third_party_jar(
+    name = "perfmark-api",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/perfmark/perfmark-api:perfmark-api",
+    sha1 = "f86f575a41b091786a4b027cd9c0c1d2e3fc1c01",
+    url = "mvn:io.perfmark:perfmark-api:jar:0.27.0",
+)
+# ===   End: grpc
+
+# === Begin: gson
+
+third_party_jar(
+    name = "gson",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/code/gson/gson:gson",
+    sha1 = "b3add478d4382b78ea20b1671390a858002feb6c",
+    url = "mvn:com.google.code.gson:gson:jar:2.10.1",
+    # Do not used this.
+    # Use Jackson instead.
+    # Jackson keeps a hot cache of serializers and deserializers as a useful optimization.
+    # Plus consistency across the codebase is nice.
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/bundle:bundle",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool:main_lib",
+        "prelude//toolchains/android/third-party/aosp:aosp",  # Sad transitive deps are sad
+        ":remote-apis",  # Legacy caller which should probably use Jackson
+    ],
+)
+# ===   End: gson
+
+# === Begin: guava
+
+third_party_jar(
+    name = "guava-jar",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/guava/guava:guava-jre__toolchain",
+    sha1 = "e264781dadc4967e5292f3c4d05f1d153631f7b4",
+    url = "mvn:com.google.guava:guava:jar:33.2.0-jre",
+    visibility = ["PUBLIC"],
+)
+
+buck_java_library(
+    name = "guava",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":j2objc-annotations",
+    ],
+    exported_deps = [
+        ":failureaccess",
+        ":guava-jar",
+        ":jsr305",
+        ":listenablefuture",
+    ],
+)
+
+third_party_jar(
+    name = "failureaccess",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/guava/failureaccess:failureaccess__toolchain",
+    sha1 = "c4a06a64e650562f30b7bf9aaec1bfed43aca12b",
+    url = "mvn:com.google.guava:failureaccess:jar:1.0.2",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "listenablefuture",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/guava/listenablefuture:listenablefuture__toolchain",
+    sha1 = "c949a840a6acbc5268d088e47b04177bf90b3cad",
+    url = "mvn:com.google.guava:listenablefuture:jar:1.0",
+    visibility = ["PUBLIC"],
+)
+# ===   End: guava
+
+# === Begin: guice
+
+third_party_jar(
+    name = "guice",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/inject/guice:guice",
+    sha1 = "da25056c694c54ba16e78e4fc35f17fc60f0d1b4",
+    url = "mvn:com.google.inject:guice:jar:5.1.0",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/testrunner:testng",
+    ],
+    deps = [
+        ":jsr330",
+    ],
+)
+# ===   End: guice
+
+# === Begin: hamcrest
+
+third_party_jar(
+    name = "hamcrest",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/hamcrest/hamcrest:hamcrest",
+    sha1 = "1820c0968dba3a11a1b30669bb1f01978a91dedc",
+    url = "mvn:org.hamcrest:hamcrest:jar:2.2",
+    visibility = [
+        "fbsource//xplat/toolchains/android/sdk/third-party/...",
+        "prelude//toolchains/android/src/...",
+        "prelude//toolchains/android/test/...",
+    ],
+)
+# ===   End: hamcrest
+
+# === Begin: infer-annotations
+
+third_party_jar(
+    name = "infer-annotations",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/facebook/infer/annotation/infer-annotation:infer-annotation__toolchain",
+    sha1 = "27539793fe93ed7d92b6376281c16cda8278ab2f",
+    url = "mvn:com.facebook.infer.annotation:infer-annotation:jar:0.18.0",
+    visibility = ["PUBLIC"],
+)
+# ===   End: infer-annotations
+
+# === Begin: io.netty
+
+buck_java_library(
+    name = "netty",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/cd/workertool/grpc:workertool_grpc",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/cd/workertool/grpc:workertool_grpc",
+    ],
+    exported_deps = [
+        ":netty-buffer",
+        ":netty-codec",
+        ":netty-codec-http",
+        ":netty-codec-http2",
+        ":netty-common",
+        ":netty-handler",
+        ":netty-transport",
+        ":netty-transport-classes-epoll",
+        ":netty-transport-classes-kqueue",
+        ":netty-transport-native-epoll",
+        ":netty-transport-native-epoll-linux-aarch_64",
+        ":netty-transport-native-epoll-linux-x86_64",
+        ":netty-transport-native-kqueue",
+        ":netty-transport-native-kqueue-osx-aarch_64",
+        ":netty-transport-native-kqueue-osx-x86_64",
+        ":netty-transport-native-unix-common",
+    ],
+)
+
+third_party_jar(
+    name = "netty-buffer",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-buffer:netty-buffer",
+    sha1 = "39b05d2d4027971bf99111a9be1d7035a116bb55",
+    url = "mvn:io.netty:netty-buffer:jar:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-codec",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-codec:netty-codec",
+    sha1 = "9c3c71e7cf3b8ce3bfc9fa52a524b9ca7ddf259c",
+    url = "mvn:io.netty:netty-codec:jar:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-codec-http",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-codec-http:netty-codec-http",
+    sha1 = "992623e7d8f2d96e41faf1687bb963f5433e3517",
+    url = "mvn:io.netty:netty-codec-http:jar:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-codec-http2",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-codec-http2:netty-codec-http2",
+    sha1 = "cbf1a430ea44dbdedbcde16b185cbb95f28d72c7",
+    url = "mvn:io.netty:netty-codec-http2:jar:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-common",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-common:netty-common",
+    sha1 = "847f942381145de23f21c836d05b0677474271d3",
+    url = "mvn:io.netty:netty-common:jar:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-handler",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-handler:netty-handler",
+    sha1 = "4c0acdb8bb73647ebb3847ac2d503d53d72c02b4",
+    url = "mvn:io.netty:netty-handler:jar:4.1.100.Final",
+    visibility = [
+        ":grpc-netty-shaded",
+    ],
+)
+
+third_party_jar(
+    name = "netty-tcnative",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-tcnative-boringssl-static:netty-tcnative-boringssl-static",
+    sha1 = "185980556f9f083b5339825f19c9641c6c879417",
+    url = "mvn:io.netty:netty-tcnative-boringssl-static:jar:2.0.25.Final",
+    visibility = [
+        ":grpc-netty-shaded",
+    ],
+)
+
+third_party_jar(
+    name = "netty-transport",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-transport:netty-transport",
+    sha1 = "6620fbfb47667a5eb6050e35c7b4c88000bcd77f",
+    url = "mvn:io.netty:netty-transport:jar:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-transport-classes-epoll",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-transport-classes-epoll:netty-transport-classes-epoll",
+    sha1 = "78489936ca1d91483e34a31d04a3b0812386eb39",
+    url = "mvn:io.netty:netty-transport-classes-epoll:jar:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-transport-classes-kqueue",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-transport-classes-kqueue:netty-transport-classes-kqueue",
+    sha1 = "a32c1b13b82bfd7f09d4ea4836257d48056f0fe2",
+    url = "mvn:io.netty:netty-transport-classes-kqueue:jar:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-transport-native-epoll",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-transport-native-epoll:netty-transport-native-epoll",
+    sha1 = "cf3c3ef7cb7b30b58385d824dbaf85f5f72da221",
+    url = "mvn:io.netty:netty-transport-native-epoll:jar:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-transport-native-epoll-linux-aarch_64",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-transport-native-epoll:netty-transport-native-epoll-linux-aarch_64",
+    sha1 = "22c3fe045620e6e05002ed1999d276dc4176a7a4",
+    url = "mvn:io.netty:netty-transport-native-epoll:jar:linux-aarch_64:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-transport-native-epoll-linux-x86_64",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-transport-native-epoll:netty-transport-native-epoll-linux-x86_64",
+    sha1 = "d83003b8eac838e4bc3f7662a22f9f2d879c0fe4",
+    url = "mvn:io.netty:netty-transport-native-epoll:jar:linux-x86_64:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-transport-native-kqueue",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-transport-native-kqueue:netty-transport-native-kqueue",
+    sha1 = "ae88188265e417b5c7b27cb880ecec2bd7dd8a35",
+    url = "mvn:io.netty:netty-transport-native-kqueue:jar:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-transport-native-kqueue-osx-aarch_64",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-transport-native-kqueue:netty-transport-native-kqueue-osx-aarch_64",
+    sha1 = "2d75a8e80a75def2b61bac1ea5f66d184f5069f0",
+    url = "mvn:io.netty:netty-transport-native-kqueue:jar:osx-aarch_64:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-transport-native-kqueue-osx-x86_64",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-transport-native-kqueue:netty-transport-native-kqueue-osx-x86_64",
+    sha1 = "135c3a560a4fb84b0e2084f376610347483e2e8a",
+    url = "mvn:io.netty:netty-transport-native-kqueue:jar:osx-x86_64:4.1.100.Final",
+)
+
+third_party_jar(
+    name = "netty-transport-native-unix-common",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/netty/netty-transport-native-unix-common:netty-transport-native-unix-common",
+    sha1 = "648ff5571022dbfa6789122e3872477bbf67fa7b",
+    url = "mvn:io.netty:netty-transport-native-unix-common:jar:4.1.100.Final",
+)
+# ===   End: io.netty
+
+# === Begin: j2objc
+
+third_party_jar(
+    name = "j2objc-annotations",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/j2objc/j2objc-annotations:j2objc-annotations__toolchain",
+    sha1 = "7399e65dd7e9ff3404f4535b2f017093bdb134c7",
+    url = "mvn:com.google.j2objc:j2objc-annotations:jar:3.0.0",
+    visibility = ["PUBLIC"],
+)
+# ===   End: j2objc
+
+# === Begin: jackson
+
+third_party_jar(
+    name = "jackson-annotations",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/fasterxml/jackson/core/jackson-annotations:jackson-annotations__toolchain",
+    sha1 = "9bddcc56af9d90f902ef5dba7348102cd12b04e2",
+    url = "mvn:com.fasterxml.jackson.core:jackson-annotations:jar:2.18.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "jackson-core",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/fasterxml/jackson/core/jackson-core:jackson-core__toolchain",
+    sha1 = "65e8ead7de5d8f7a53e296c363bea3182f21f925",
+    url = "mvn:com.fasterxml.jackson.core:jackson-core:jar:2.18.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "jackson-datatype-jdk8",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/fasterxml/jackson/datatype/jackson-datatype-jdk8:jackson-datatype-jdk8",
+    sha1 = "2046c6ad99a59b5bccf840021f5b3dcf2890acc2",
+    url = "mvn:com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.18.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "jackson-datatype-guava",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/fasterxml/jackson/datatype/jackson-datatype-guava:jackson-datatype-guava__toolchain",
+    sha1 = "731e354fcae2bc14cb6a4deeef9c7e5ea620a11f",
+    url = "mvn:com.fasterxml.jackson.datatype:jackson-datatype-guava:jar:2.18.0",
+    visibility = ["PUBLIC"],
+)
+
+buck_java_library(
+    name = "jackson-databind",
+    visibility = ["PUBLIC"],
+    exported_deps = [
+        # If ObjectMapper.writeValue() is used, then
+        # com.fasterxml.jackson.core.ObjectCodec needs to be accessible.
+        ":jackson-core",
+        ":jackson-databind-jar",
+    ],
+)
+
+third_party_jar(
+    name = "jackson-databind-jar",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/fasterxml/jackson/core/jackson-databind:jackson-databind__toolchain",
+    sha1 = "8dba1f789a75fc30b59303574fe2b269afa4d3bc",
+    url = "mvn:com.fasterxml.jackson.core:jackson-databind:jar:2.18.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "jackson-module-kotlin",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/fasterxml/jackson/module/jackson-module-kotlin:jackson-module-kotlin",
+    sha1 = "ef6ff9000dd9b28246e9346151127638d91398fa",
+    url = "mvn:com.fasterxml.jackson.module:jackson-module-kotlin:jar:2.18.0",
+    visibility = ["PUBLIC"],
+)
+# ===   End: jackson
+
+# === Begin: jakarta.annotation-api
+
+third_party_jar(
+    name = "jakarta.annotation-api",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/jakarta/annotation/jakarta.annotation-api:jakarta.annotation-api__toolchain",
+    sha1 = "a858ec3f0ebd2b8d855c1ddded2cde9b381b0517",
+    url = "mvn:jakarta.annotation:jakarta.annotation-api:jar:1.3.4",
+    visibility = ["PUBLIC"],
+)
+# ===   End: jakarta.annotation-api
+
+# === Begin: jimfs
+
+third_party_jar(
+    name = "jimfs",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/jimfs/jimfs:jimfs",
+    sha1 = "93096472c3654a761c40c8e5d4ad82a7c1a0fd54",
+    url = "mvn:com.google.jimfs:jimfs:jar:1.3.0",
+    visibility = [
+        "prelude//toolchains/android/src/...",
+        "prelude//toolchains/android/test/...",
+    ],
+)
+# ===   End: jimfs
+
+# === Begin: jna
+
+third_party_jar(
+    name = "jna",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/net/java/dev/jna/jna:jna__toolchain",
+    sha1 = "1200e7ebeedbe0d10062093f32925a912020e747",
+    url = "mvn:net.java.dev.jna:jna:jar:5.13.0",
+    visibility = ["prelude//toolchains/android/src/com/facebook/buck/io/windowsfs:windowsfs"],
+)
+# ===   End: jna
+
+# === Begin: jsr
+
+third_party_jar(
+    name = "jsr305",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/code/findbugs/jsr305:jsr305__toolchain",
+    sha1 = "25ea2e8b0c338a877313bd4672d3fe056ea78f0d",
+    url = "mvn:com.google.code.findbugs:jsr305:jar:3.0.2",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "jsr330",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/javax/inject/javax.inject:javax.inject",
+    sha1 = "6975da39a7040257bd51d21a231b76c915872d38",
+    url = "mvn:javax.inject:javax.inject:jar:1",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/bundle:bundle",
+        ":bundletool",
+        ":guice",
+    ],
+)
+# ===   End: jsr
+
+# === Begin: junit
+
+third_party_jar(
+    name = "junit",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/junit/junit:junit",
+    sha1 = "8ac9e16d933b6fb43bc7f576336b8f4d7eb5ba12",
+    url = "mvn:junit:junit:jar:4.13.2",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/...",
+        "prelude//toolchains/android/src/com/facebook/buck/testrunner:junit",
+        "prelude//toolchains/android/test/com/facebook/buck/...",
+    ],
+    deps = [
+        ":hamcrest",
+    ],
+)
+
+common_visibility = [
+    "prelude//toolchains/android/src/com/facebook/buck/testrunner:junit",
+]
+
+third_party_jar(
+    name = "junit-jupiter-api",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/junit/jupiter/junit-jupiter-api:junit-jupiter-api",
+    sha1 = "4c21029217adf07e4c0d0c5e192b6bf610c94bdc",
+    url = "mvn:org.junit.jupiter:junit-jupiter-api:jar:5.8.2",
+    deps = [
+        ":apiguardian-api",
+        ":junit-platform-commons",
+        ":opentest4j",
+    ],
+)
+
+third_party_jar(
+    name = "junit-jupiter-engine",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/junit/jupiter/junit-jupiter-engine:junit-jupiter-engine",
+    sha1 = "c598b4328d2f397194d11df3b1648d68d7d990e3",
+    url = "mvn:org.junit.jupiter:junit-jupiter-engine:jar:5.8.2",
+    visibility = common_visibility,
+    deps = [
+        ":apiguardian-api",
+        ":junit-jupiter-api",
+        ":junit-platform-engine",
+    ],
+)
+
+third_party_jar(
+    name = "junit-platform-commons",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/junit/platform/junit-platform-commons:junit-platform-commons",
+    sha1 = "32c8b8617c1342376fd5af2053da6410d8866861",
+    url = "mvn:org.junit.platform:junit-platform-commons:jar:1.8.2",
+    visibility = common_visibility,
+    deps = [
+        ":apiguardian-api",
+    ],
+)
+
+third_party_jar(
+    name = "junit-platform-engine",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/junit/platform/junit-platform-engine:junit-platform-engine",
+    sha1 = "b737de09f19864bd136805c84df7999a142fec29",
+    url = "mvn:org.junit.platform:junit-platform-engine:jar:1.8.2",
+    visibility = common_visibility,
+    deps = [
+        ":apiguardian-api",
+        ":junit-platform-commons",
+        ":opentest4j",
+    ],
+)
+
+third_party_jar(
+    name = "junit-platform-launcher",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/junit/platform/junit-platform-launcher:junit-platform-launcher",
+    sha1 = "c334fcee82b81311ab5c426ec2d52d467c8d0b28",
+    url = "mvn:org.junit.platform:junit-platform-launcher:jar:1.8.2",
+    visibility = common_visibility,
+    deps = [
+        ":junit-platform-engine",
+        ":opentest4j",
+    ],
+)
+# ===   End: junit
+
+# === Begin: kotlin
+
+third_party_jar(
+    name = "kotlin-annotations",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/jetbrains/annotations:annotations__toolchain",
+    sha1 = "919f0dfe192fb4e063e7dacadee7f8bb9a2672a9",
+    url = "mvn:org.jetbrains:annotations:jar:13.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "kotlin-stdlib",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:kotlin-stdlib__toolchain",
+    sha1 = "fdfc65fbc42fda253a26f61dac3c0aca335fae96",
+    url = "mvn:org.jetbrains.kotlin:kotlin-stdlib:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "classic_kotlin-stdlib",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/jetbrains/kotlin/kotlin-stdlib:kotlin-stdlib__toolchain",
+    sha1 = "fdfc65fbc42fda253a26f61dac3c0aca335fae96",
+    url = "mvn:org.jetbrains.kotlin:kotlin-stdlib:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "jvm-abi-gen",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:jvm-abi-gen",
+    sha1 = "de3025160a9b2a158fb400a03677167a0ff31144",
+    url = "mvn:org.jetbrains.kotlin:jvm-abi-gen:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+# We need to figure out how to handle JAR patches
+third_party_jar(
+    name = "kotlin-compiler-embeddable",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:kotlin-compiler-embeddable__toolchain",
+    sha1 = "8cfa2b049a4006d94474296df4abd9b50f288821",
+    url = "mvn:org.jetbrains.kotlin:kotlin-compiler-embeddable:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "classic_kotlin-compiler-embeddable",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/jetbrains/kotlin/kotlin-compiler-embeddable:kotlin-compiler-embeddable__toolchain",
+    sha1 = "8cfa2b049a4006d94474296df4abd9b50f288821",
+    url = "mvn:org.jetbrains.kotlin:kotlin-compiler-embeddable:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+alias(
+    name = "kotlin-compiler",
+    actual = ":kotlin-compiler-embeddable",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "trove",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/jetbrains/intellij/deps/trove4j:trove4j",
+    sha1 = "3afb14d5f9ceb459d724e907a21145e8ff394f02",
+    url = "mvn:org.jetbrains.intellij.deps:trove4j:jar:1.0.20200330",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "kotlin-reflect",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:kotlin-reflect__toolchain",
+    sha1 = "4258f471b10f4fce1b1c000b59495b7413e1af9a",
+    url = "mvn:org.jetbrains.kotlin:kotlin-reflect:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "classic_kotlin-reflect",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/jetbrains/kotlin/kotlin-reflect:kotlin-reflect__toolchain",
+    sha1 = "4258f471b10f4fce1b1c000b59495b7413e1af9a",
+    url = "mvn:org.jetbrains.kotlin:kotlin-reflect:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "kotlin-script-runtime",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:kotlin-script-runtime",
+    sha1 = "87c92e866fcd68680966a3005a2992e1ab8ec6ad",
+    url = "mvn:org.jetbrains.kotlin:kotlin-script-runtime:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "classic_kotlin-script-runtime",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/jetbrains/kotlin/kotlin-script-runtime:kotlin-script-runtime",
+    sha1 = "87c92e866fcd68680966a3005a2992e1ab8ec6ad",
+    url = "mvn:org.jetbrains.kotlin:kotlin-script-runtime:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "kotlin-annotation-processing-embeddable",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:kotlin-annotation-processing-embeddable",
+    sha1 = "944a8b045adf3b81f32c5843229a90d3792dc7d8",
+    url = "mvn:org.jetbrains.kotlin:kotlin-annotation-processing-embeddable:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "classic_kotlin-annotation-processing-embeddable",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/jetbrains/kotlin/kotlin-annotation-processing-embeddable:kotlin-annotation-processing-embeddable",
+    sha1 = "944a8b045adf3b81f32c5843229a90d3792dc7d8",
+    url = "mvn:org.jetbrains.kotlin:kotlin-annotation-processing-embeddable:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "kotlin-build-tools-api",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:kotlin-build-tools-api__toolchain",
+    sha1 = "ceaa386345f22c861908058ffcddbeb23bcde8f4",
+    url = "mvn:org.jetbrains.kotlin:kotlin-build-tools-api:jar:2.2.0",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools:buildtools",
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/buildtools/snapshot:cp_snapshot_generator_lib",
+        "prelude//toolchains/android/test/com/facebook/buck/jvm/kotlin/buildtools:buildtools",
+    ],
+)
+
+# We need to figure out how to handle JAR patches
+third_party_jar(
+    name = "kotlin-build-tools-impl",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:kotlin-build-tools-impl__toolchain",
+    sha1 = "14270b99947f8344e8ae36e907a05c8e92f57d85",
+    url = "mvn:org.jetbrains.kotlin:kotlin-build-tools-impl:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "kotlin-daemon-client",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:kotlin-daemon-client",
+    sha1 = "77ce7a4cac28c2be4423f2999ff0455ca36ea36f",
+    url = "mvn:org.jetbrains.kotlin:kotlin-daemon-client:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "kotlin-metadata-jvm",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:kotlin-metadata-jvm__toolchain",
+    sha1 = "5f061327c06ab653e26e022c28e6d431d29205b9",
+    url = "mvn:org.jetbrains.kotlin:kotlin-metadata-jvm:jar:2.2.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "kotlin-poet",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/squareup/kotlinpoet:kotlinpoet",
+    sha1 = "2df03e8b2afdb98dda7b6b0753cd5d9b12b40031",
+    url = "mvn:com.squareup:kotlinpoet-jvm:jar:1.16.0",
+    visibility = ["PUBLIC"],
+)
+
+buck_java_binary(
+    name = "classic_kotlin-compiler-binary",
+    main_class = "org.jetbrains.kotlin.cli.jvm.K2JVMCompiler",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":classic_kotlin-compiler-embeddable",
+        ":classic_kotlin-reflect",
+        ":classic_kotlin-script-runtime",
+        ":classic_kotlin-stdlib",
+        ":guava-jar",
+        ":kotlin-annotations",
+        ":kotlinx-coroutines-core-jvm",
+        ":trove",
+    ],
+)
+
+buck_java_binary(
+    name = "kotlin-compiler-binary",
+    main_class = "org.jetbrains.kotlin.cli.jvm.K2JVMCompiler",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":guava-jar",
+        ":kotlin-annotations",
+        ":kotlin-compiler-embeddable",
+        ":kotlin-reflect",
+        ":kotlin-script-runtime",
+        ":kotlin-stdlib",
+        ":kotlinx-coroutines-core-jvm",
+        ":trove",
+    ],
+)
+
+# ===   End: kotlin
+
+# === Begin: kotlinx
+
+buck_java_library(
+    name = "kotlinx-metadata-jvm",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi/kotlin:kotlin",
+        ":d8",
+    ],
+    exported_deps = [
+        ":kotlin-stdlib",
+        ":kotlinx-metadata-jvm-jar",
+    ],
+)
+
+third_party_jar(
+    name = "kotlinx-coroutines-core-jvm",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/jetbrains/kotlinx/kotlinx-coroutines-core-jvm:kotlinx-coroutines-core-jvm__toolchain",
+    sha1 = "9beade4c1c1569e4f36cbd2c37e02e3e41502601",
+    url = "mvn:org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:jar:1.9.0",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "kotlinx-metadata-jvm-jar",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/jetbrains/kotlinx/kotlinx-metadata-jvm:kotlinx-metadata-jvm__toolchain",
+    sha1 = "babbf7cbcd7083709bf27ee5e19dd558d2dea39b",
+    url = "mvn:org.jetbrains.kotlinx:kotlinx-metadata-jvm:jar:0.7.0",
+)
+# ===   End: kotlinx
+
+# === Begin: ksp
+
+third_party_jar(
+    name = "symbol-processing-aa-embeddable",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:symbol-processing-aa-embeddable__toolchain",
+    sha1 = "12b29cfe8a24588854a083828ac17a040f03b8ff",
+    url = "mvn:com.google.devtools.ksp:symbol-processing-aa-embeddable:jar:2.2.0-2.0.2",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "symbol-processing-api",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:symbol-processing-api",
+    sha1 = "6a7c41da95b72d99ee1277c80951a9160db1f1a5",
+    url = "mvn:com.google.devtools.ksp:symbol-processing-api:jar:2.2.0-2.0.2",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "symbol-processing-common-deps",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/kotlincd:symbol-processing-common-deps",
+    sha1 = "c15826465823bce080cc1693daef699366be0951",
+    url = "mvn:com.google.devtools.ksp:symbol-processing-common-deps:jar:2.2.0-2.0.2",
+    visibility = ["PUBLIC"],
+)
+# ===   End: ksp
+
+# === Begin: kxml2
+
+third_party_jar(
+    name = "kxml2",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/net/sf/kxml/kxml2:kxml2",
+    sha1 = "ccbc77a5fd907ef863c29f3596c6f54ffa4e9442",
+    url = "mvn:net.sf.kxml:kxml2:jar:2.3.0",
+    visibility = ["PUBLIC"],
+)
+# ===   End: kxml2
+
+# === Begin: okhttp
+
+third_party_jar(
+    name = "okhttp",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/squareup/okhttp3/okhttp:okhttp",
+    sha1 = "cd63657ac15770ed1420647154c9f44645533bef",
+    url = "mvn:com.squareup.okhttp3:okhttp:jar:4.10.0",
+    visibility = [
+        "prelude//toolchains/android/src/...",
+        "prelude//toolchains/android/test/...",
+    ],
+)
+# ===   End: okhttp
+
+# === Begin: okio
+
+third_party_jar(
+    name = "okio",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/squareup/okio/okio:okio",
+    sha1 = "fca77ce5f3ce6fa8a65738a31e34b87ccd289f71",
+    url = "mvn:com.squareup.okio:okio:jar:1.17.6",
+    visibility = [
+        "prelude//toolchains/android/src/...",
+        "prelude//toolchains/android/test/...",
+    ],
+)
+# ===   End: okio
+
+# === Begin: opencensus
+
+third_party_jar(
+    name = "opencensus-api",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/opencensus/opencensus-api:opencensus-api__toolchain",
+    sha1 = "f974451b19007ce820f433311ce8adb88e2b7d2c",
+    url = "mvn:io.opencensus:opencensus-api:jar:0.24.0",
+    visibility = [
+        ":remote-apis",
+    ],
+)
+
+third_party_jar(
+    name = "opencensus-contrib-grpc-metrics",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/opencensus/opencensus-contrib-grpc-metrics:opencensus-contrib-grpc-metrics__toolchain",
+    sha1 = "ed76d8b99fb674478efa0c4c028ea9545ba1815f",
+    url = "mvn:io.opencensus:opencensus-contrib-grpc-metrics:jar:0.24.0",
+    visibility = [
+        ":remote-apis",
+    ],
+)
+# ===   End: opencensus
+
+# === Begin: protobuf
+
+third_party_jar(
+    name = "protobuf",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/protobuf/protobuf-java:protobuf-java__toolchain",
+    sha1 = "5ae5c9ec39930ae9b5a61b32b93288818ec05ec1",
+    url = "mvn:com.google.protobuf:protobuf-java:jar:3.25.5",
+    visibility = ["PUBLIC"],
+)
+
+third_party_jar(
+    name = "protobuf-util",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/protobuf/protobuf-java-util:protobuf-java-util__toolchain",
+    sha1 = "38cc5ce479603e36466feda2a9f1dfdb2210ef00",
+    url = "mvn:com.google.protobuf:protobuf-java-util:jar:3.25.5",
+    visibility = ["PUBLIC"],
+)
+
+third_party_exe(
+    name = "protoc-linux-x86_64",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/protobuf/protoc:protoc-linux-x86_64",
+    sha1 = "9065c462198f65a0f5ab4945023dac99288cf24f",
+    target_compatible_with = select({
+        "DEFAULT": ["ovr_config//cpu:x86_64"],
+        "ovr_config//os:macos": [],
+        "ovr_config//os:windows": [],
+    }),
+    url = "mvn:com.google.protobuf:protoc:exe:linux-x86_64:3.25.6",
+    visibility = ["PUBLIC"],
+)
+
+third_party_exe(
+    name = "protoc-osx-x86_64",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/protobuf/protoc:protoc-osx-x86_64",
+    sha1 = "a57fab7d37d8824034cc67325f81de24d0f36b6a",
+    url = "mvn:com.google.protobuf:protoc:exe:osx-x86_64:3.25.6",
+    visibility = ["PUBLIC"],
+)
+
+third_party_exe(
+    name = "protoc-windows-x86_64",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/google/protobuf/protoc:protoc-windows-x86_64",
+    sha1 = "d9bbbb5a88fc7fdcb41ff717028461f8e6b5b958",
+    url = "mvn:com.google.protobuf:protoc:exe:windows-x86_64:3.25.6",
+    visibility = ["PUBLIC"],
+)
+
+third_party_exe(
+    name = "protoc-gen-grpc-java-linux-x86_64",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/protoc-gen-grpc-java:protoc-gen-grpc-java-linux-x86_64",
+    sha1 = "3c8950cae9d5b4bed363f71118fb54bfddafcd2a",
+    url = "mvn:io.grpc:protoc-gen-grpc-java:exe:linux-x86_64:1.10.1",
+    visibility = ["PUBLIC"],
+)
+
+third_party_exe(
+    name = "protoc-gen-grpc-java-osx-x86_64",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/protoc-gen-grpc-java:protoc-gen-grpc-java-osx-x86_64",
+    sha1 = "8c37e3794df02dcb2dcc7547266119bc09d3aeae",
+    url = "mvn:io.grpc:protoc-gen-grpc-java:exe:osx-x86_64:1.10.1",
+    visibility = ["PUBLIC"],
+)
+
+third_party_exe(
+    name = "protoc-gen-grpc-java-windows-x86_64",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/io/grpc/protoc-gen-grpc-java:protoc-gen-grpc-java-windows-x86_64",
+    sha1 = "b5692a8df52f6aef24c7181f94240ef52b7060fb",
+    url = "mvn:io.grpc:protoc-gen-grpc-java:exe:windows-x86_64:1.10.1",
+    visibility = ["PUBLIC"],
+)
+# ===   End: protobuf
+
+# === Begin: testng
+
+third_party_jar(
+    name = "testng",
+    # @oss-disable[end= ]: internal_alias = "fbcode//third-party-java/org/testng/testng:testng",
+    sha1 = "6673f647a35826fb01ff3129edc241d88bd27b88",
+    url = "mvn:org.testng:testng:jar:7.5.1",
+    visibility = ["PUBLIC"],
+)
+# ===   End: testng
+
+# === Begin: zstd-jni
+
+third_party_jar(
+    name = "zstd-jni",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/github/luben/zstd-jni:zstd-jni__toolchain",
+    sha1 = "b4fea046fcd925681fa10c61be99da059f4f745a",
+    url = "mvn:com.github.luben:zstd-jni:jar:1.5.7-17",
+    visibility = [
+        "prelude//toolchains/android/src/...",
+        "prelude//toolchains/android/test/...",
+    ],
+)
+# ===   End: zstd-jni
+
+# === Begin: xz
+
+third_party_jar(
+    name = "xz",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/tukaani/xz:xz",
+    sha1 = "1ea4bec1a921180164852c65006d928617bd2caf",
+    url = "mvn:org.tukaani:xz:jar:1.9",
+    visibility = [
+        "prelude//toolchains/android/src/...",
+        "prelude//toolchains/android/test/...",
+    ],
+)
+# ===   End: xz
+
+# === Begin: apiguardian
+
+third_party_jar(
+    name = "apiguardian-api",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/apiguardian/apiguardian-api:apiguardian-api",
+    sha1 = "a231e0d844d2721b0fa1b238006d15c6ded6842a",
+    url = "mvn:org.apiguardian:apiguardian-api:jar:1.1.2",
+    visibility = ["PUBLIC"],
+)
+# ===   End: apiguardian
+
+# === Begin: opentest4j
+
+third_party_jar(
+    name = "opentest4j",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/opentest4j/opentest4j:opentest4j",
+    sha1 = "28c11eb91f9b6d8e200631d46e20a7f407f2a046",
+    url = "mvn:org.opentest4j:opentest4j:jar:1.2.0",
+    visibility = ["PUBLIC"],
+)
+# ===   End: opentest4j
+
+# === Begin: bytebuddy
+
+third_party_jar(
+    name = "byte-buddy",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/net/bytebuddy/byte-buddy:byte-buddy",
+    sha1 = "635c873fadd853c084f84fdc3cbd58c5dd8537f9",
+    url = "mvn:net.bytebuddy:byte-buddy:jar:1.15.10",
+    visibility = [
+        "fbsource//xplat/toolchains/android/sdk/third-party/...",
+        "prelude//toolchains/android/test/...",
+    ],
+)
+
+third_party_jar(
+    name = "byte-buddy-agent",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/net/bytebuddy/byte-buddy-agent:byte-buddy-agent",
+    sha1 = "0e8eb255b2c378b9a6c7341e7b0e12f0a5636377",
+    url = "mvn:net.bytebuddy:byte-buddy-agent:jar:1.15.10",
+    visibility = [
+        "fbsource//xplat/toolchains/android/sdk/third-party/...",
+        "prelude//toolchains/android/test/...",
+    ],
+)
+# ===   End: bytebuddy
+
+# === Begin: mockito
+
+third_party_jar(
+    name = "mockito",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/mockito/mockito-core:mockito-core",
+    sha1 = "a32f446f38acf636363c5693db6498047731b9e0",
+    url = "mvn:org.mockito:mockito-core:jar:5.20.0",
+    visibility = [
+        "PUBLIC",
+    ],
+    deps = [
+        ":byte-buddy",
+        ":byte-buddy-agent",
+        ":objenesis",
+    ],
+)
+
+third_party_jar(
+    name = "mockito-kotlin",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/mockito/kotlin/mockito-kotlin:mockito-kotlin",
+    sha1 = "6c89533c7c38b1600ceea37b806cba3d9619c1ac",
+    url = "mvn:org.mockito.kotlin:mockito-kotlin:jar:6.1.0",
+    visibility = ["PUBLIC"],
+    deps = [
+        ":kotlin-reflect",
+        ":mockito",
+    ],
+)
+# ===   End: mockito
+
+# === Begin: objenesis
+
+third_party_jar(
+    name = "objenesis",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/org/objenesis/objenesis:objenesis",
+    sha1 = "1049c09f1de4331e8193e579448d0916d75b7631",
+    url = "mvn:org.objenesis:objenesis:jar:3.3",
+    visibility = [
+        "fbsource//xplat/toolchains/android/sdk/third-party/...",
+        "prelude//toolchains/android/test/...",
+    ],
+)
+# ===   End: objenesis
+
+# === Begin: system-rules
+
+third_party_jar(
+    name = "system-rules",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/system-rules:system-rules",
+    sha1 = "cb9e42b003d0668f6445505c0f81dd9a244a05d5",
+    url = "mvn:com.github.stefanbirkner:system-rules:jar:1.16.1",
+    visibility = ["PUBLIC"],
+)
+
+# === End: system-rules
+
+# === Begin: third party libraries with internal patching
+third_party_jar(
+    name = "d8",
+    # @oss-disable[end= ]: internal_alias = "fbsource//xplat/toolchains/android/sdk/third-party/java/d8:d8",
+    sha1 = "3d41953fbdda2adf1a75baee10851cd9de7c1b24",
+    url = "https://github.com/facebook/buck2/releases/download/androidToolchain%2F2025-04-03/d8_dexer_patched.jar",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/dex:d8_executable_main",
+        "prelude//toolchains/android/src/com/facebook/buck/android/dex:dex",
+        "prelude//toolchains/android/src/com/facebook/buck/android/dex:multi_dex_executable_main",
+    ],
+)
+# ===   end: third party libraries with internal patching
diff --git a/buck2/prelude/toolchains/android/third-party/aosp/BUCK b/buck2/prelude/toolchains/android/third-party/aosp/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/third-party/aosp/BUCK
@@ -0,0 +1,35 @@
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library", "third_party_jar")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+buck_java_library(
+    name = "aosp",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/manifest:manifest",
+        "prelude//toolchains/android/src/com/facebook/buck/cli/bootstrapper:bootstrapper_lib",
+    ],
+    exported_deps = [
+        "prelude//toolchains/android/third-party:android-annotations",
+        "prelude//toolchains/android/third-party:android-common",
+        "prelude//toolchains/android/third-party:gson",
+        "prelude//toolchains/android/third-party:guava",
+        "prelude//toolchains/android/third-party:kotlin-stdlib",
+        "prelude//toolchains/android/third-party:manifest-merger",
+        "prelude//toolchains/android/third-party:sdk-common",
+        "prelude//toolchains/android/third-party:sdklib",
+    ],
+)
+
+third_party_jar(
+    name = "apksig",
+    # @oss-disable[end= ]: internal_alias = "fbsource//third-party/java/com/android/tools/build/apksig:apksig",
+    sha1 = "d51ecbc4a5b7a2c7832586a4dde18f61d92810a4",
+    url = "mvn:https://maven.google.com:com.android.tools.build:apksig:jar:8.4.0",
+    visibility = [
+        "prelude//toolchains/android/src/com/facebook/buck/android/apk:apk",
+        "prelude//toolchains/android/src/com/facebook/buck/android/bundle:bundle",
+    ],
+)
diff --git a/buck2/prelude/toolchains/android/tools/build_rules.bzl b/buck2/prelude/toolchains/android/tools/build_rules.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/tools/build_rules.bzl
@@ -0,0 +1,342 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Module containing java macros."""
+
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load("@prelude//:native.bzl", "native")
+# @oss-disable[end= ]: load("@prelude//android/meta_only:android_build_tools_cas_artifact.bzl", "android_build_tools_cas_artifact")
+load("@prelude//toolchains/android/tools/build_rules:fb_native.bzl", "fb_native")
+load("@prelude//toolchains/android/tools/build_rules:utils.bzl", "add_os_labels")
+load("@prelude//utils:selects.bzl", "selects")
+
+SIGNED_JAR_BLOCKLIST = [
+    "META-INF/.*\\.DSA",
+    "META-INF/.*\\.SF",
+    "META-INF/.*\\.RSA",
+]
+
+OPEN_JDK_COMPILER_ARGS = [
+    "--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
+    "--add-exports=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED",
+    "--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED",
+    "--add-exports=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED",
+    "--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED",
+    "--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED",
+    "--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED",
+    "--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED",
+    "--add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",
+    "--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
+    "--add-opens=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED",
+    "--add-opens=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED",
+    "--add-opens=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED",
+    "--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
+]
+
+_RUN_AS_BUNDLE_LABEL = "run_as_bundle"
+
+_FDB_DEBUG_LABEL = "fdb:target:android"
+
+def _maybe_add_java_version(**kwargs):
+    if "source" not in kwargs and "target" not in kwargs and "java_version" not in kwargs:
+        kwargs["java_version"] = "11"
+    return kwargs
+
+def _add_labels(**kwargs):
+    if "labels" not in kwargs:
+        kwargs["labels"] = []
+    kwargs["labels"] += ["wrapped_with_buck_java_rules", "pfh:Infra"]
+    return kwargs
+
+def _set_buck2_java_toolchain(**kwargs):
+    # Default to the bootstrap toolchain, but let callers opt into a different one (e.g. a
+    # non-bootstrap toolchain when the binary packages native code, which the bootstrap fat-jar
+    # tooling does not support).
+    if "_java_toolchain" not in kwargs:
+        kwargs["_java_toolchain"] = "toolchains//:java_bootstrap"
+    return kwargs
+
+def _set_buck2_kotlin_toolchain(**kwargs):
+    kwargs["_kotlin_toolchain"] = "toolchains//:kotlin_bootstrap"
+    return kwargs
+
+def _set_buck2_dex_toolchain(**kwargs):
+    # Override dex toolchain to avoid dependency cycles in unconfigured graph
+    dex_toolchain = kwargs.pop("_dex_toolchain", None)
+    kwargs["_dex_toolchain"] = dex_toolchain or select({
+        "DEFAULT": "toolchains//:empty_dex",
+        "config//os/constraints:android": "toolchains//:dex",
+    })
+    return kwargs
+
+def _set_versioned_java_srcs(**kwargs):
+    if not kwargs.pop("versioned_java_srcs", False):
+        return kwargs
+    java_version = select({
+        "DEFAULT": native.read_config("java", "buck2_java_version", "21"),
+        # @oss-disable[end= ]: "fbsource//third-party/toolchains/jdk:constraint-value-version-11": "11",
+        # @oss-disable[end= ]: "fbsource//third-party/toolchains/jdk:constraint-value-version-17": "17",
+        # @oss-disable[end= ]: "fbsource//third-party/toolchains/jdk:constraint-value-version-21": "21",
+    })
+    versioned_srcs = selects.apply(
+        java_version,
+        lambda value: kwargs.get("srcs", []) + native.glob(["java{}/*.java".format(value)]),
+    )
+    kwargs["srcs"] = versioned_srcs
+    return kwargs
+
+def _add_kotlin_deps(**kwargs):
+    kwargs["deps"] = kwargs.pop("deps", []) + [
+        "prelude//toolchains/android/third-party:kotlin-annotations",
+        "prelude//toolchains/android/third-party:kotlin-stdlib",
+    ]
+    return kwargs
+
+def buck_kotlin_library(name, **kwargs):
+    kwargs = _maybe_add_java_version(**kwargs)
+    kwargs = _set_buck2_java_toolchain(**kwargs)
+    kwargs = _set_buck2_kotlin_toolchain(**kwargs)
+    kwargs = _set_buck2_dex_toolchain(**kwargs)
+    kwargs = _add_kotlin_deps(**kwargs)
+    return fb_native.kotlin_library(name = name, **kwargs)
+
+def buck_java_library(name, **kwargs):
+    kwargs = _add_labels(**kwargs)
+    kwargs = _maybe_add_java_version(**kwargs)
+    kwargs = _set_buck2_java_toolchain(**kwargs)
+    kwargs = _set_buck2_dex_toolchain(**kwargs)
+    kwargs = _set_versioned_java_srcs(**kwargs)
+    return fb_native.java_library(name = name, **kwargs)
+
+def buck_java_binary(name, **kwargs):
+    kwargs = _add_labels(**kwargs)
+    kwargs = _set_buck2_java_toolchain(**kwargs)
+    java_args = kwargs["java_args_for_run_info"] if "java_args_for_run_info" in kwargs else []
+
+    # Directs the VM to refrain from setting the file descriptor limit to the default maximum.
+    # https://stackoverflow.com/a/16535804/5208808
+    java_args += ["-XX:-MaxFDLimit", "-Xss2m"]
+    kwargs["java_args_for_run_info"] = java_args
+    return fb_native.java_binary(name = name, **kwargs)
+
+def _toolchain_prebuilt_jar(name, **kwargs):
+    kwargs = _add_labels(**kwargs)
+    kwargs = _set_buck2_dex_toolchain(**kwargs)
+    if kwargs.pop("should_generate_snapshot", True) == False:
+        kwargs["_prebuilt_jar_toolchain"] = "toolchains//:prebuilt_jar_bootstrap_no_snapshot"
+    else:
+        kwargs["_prebuilt_jar_toolchain"] = "toolchains//:prebuilt_jar_bootstrap"
+    return fb_native.prebuilt_jar(name = name, **kwargs)
+
+def _oss_remote_file_with_wrapper(name, ext, url, sha1, **kwargs):
+    remote_file_target_name = name + "_" + ext
+    if ext == "jar":
+        _toolchain_prebuilt_jar(name = name, binary_jar = ":" + remote_file_target_name, **kwargs)
+    elif ext == "aar":
+        fb_native.android_prebuilt_aar(name = name, aar = ":" + remote_file_target_name, **kwargs)
+    elif ext == "exe":
+        fb_native.alias(name = name, actual = ":" + remote_file_target_name, **kwargs)
+
+    fb_native.remote_file(
+        name = remote_file_target_name,
+        out = name + "." + ext,
+        sha1 = sha1,
+        url = url,
+        type = "executable" if ext == "exe" else "data",
+    )
+
+def _buck_remote_file_with_wrapper(
+    name,
+    ext,
+    url,
+    sha1,
+    # @oss-disable[end= ]: internal_alias,
+    **kwargs,
+):
+    if not is_full_meta_repo():
+        return _oss_remote_file_with_wrapper(name, ext, url, sha1, **kwargs)
+    # @oss-disable[end= ]: else:
+        # @oss-disable: # deps are managed by Artificer internally - only relevant for OSS builds.
+        # @oss-disable[end= ]: kwargs.pop("deps", None)
+        # @oss-disable[end= ]: return native.alias(name = name, actual = internal_alias, **kwargs)
+        fail() # @oss-enable
+
+def third_party_jar(
+    name,
+    url,
+    sha1,
+    # @oss-disable[end= ]: internal_alias,
+    **kwargs,
+):
+    return _buck_remote_file_with_wrapper(
+        name,
+        "jar",
+        url,
+        sha1,
+        # @oss-disable[end= ]: internal_alias,
+        **kwargs,
+    )
+
+def third_party_aar(
+    name,
+    url,
+    sha1,
+    # @oss-disable[end= ]: internal_alias,
+    **kwargs,
+):
+    return _buck_remote_file_with_wrapper(
+        name,
+        "aar",
+        url,
+        sha1,
+        # @oss-disable[end= ]: internal_alias,
+        **kwargs,
+    )
+
+def third_party_exe(
+    name,
+    url,
+    sha1,
+    # @oss-disable[end= ]: internal_alias,
+    **kwargs,
+):
+    return _buck_remote_file_with_wrapper(
+        name,
+        "exe",
+        url,
+        sha1,
+        # @oss-disable[end= ]: internal_alias,
+        **kwargs,
+    )
+
+def buck_prebuilt_jar(name, **kwargs):
+    return _toolchain_prebuilt_jar(name = name, **kwargs)
+
+def _shallow_dict_copy_without_key(table, key_to_omit):
+    """Returns a shallow copy of dict with key_to_omit omitted."""
+    return {key: table[key] for key in table if key != key_to_omit}
+
+def buck_kotlin_test(**kwargs):
+    extra_labels = [_RUN_AS_BUNDLE_LABEL, _FDB_DEBUG_LABEL]
+
+    kwargs = _add_labels(**kwargs)
+    kwargs = add_os_labels(**kwargs)
+    kwargs["labels"] += extra_labels
+
+    kwargs = _add_kotlin_deps(**kwargs)
+    kwargs = _maybe_add_java_version(**kwargs)
+
+    fb_native.kotlin_test(**kwargs)
+
+def buck_java_test(name, vm_args = None, run_test_separately = False, **kwargs):
+    """java_test wrapper that provides sensible defaults for buck tests.
+
+    Args:
+      name: name
+      vm_args: vm_args
+      run_test_separately: run_test_separately
+      **kwargs: kwargs
+    """
+
+    extra_labels = [_RUN_AS_BUNDLE_LABEL, _FDB_DEBUG_LABEL]
+
+    # Windows command line is short and running a bundle with many tests can cause problems
+    # We fix this by running bundles of max 100 tests
+    if native.host_info().os.is_windows:
+        extra_labels.append("tpx:experimental-shard-size-for-bundle=100")
+
+    if run_test_separately:
+        extra_labels.append("serialize")
+
+    if "deps" in kwargs:
+        deps = kwargs["deps"]
+        kwargs = _shallow_dict_copy_without_key(kwargs, "deps")
+    else:
+        deps = []
+
+    if "env" in kwargs:
+        env = kwargs["env"]
+        kwargs = _shallow_dict_copy_without_key(kwargs, "env")
+    else:
+        env = {}
+
+    kwargs = _maybe_add_java_version(**kwargs)
+    kwargs = _add_labels(**kwargs)
+    kwargs = add_os_labels(**kwargs)
+    kwargs["labels"] += extra_labels
+
+    fb_native.java_test(
+        name = name,
+        deps = deps
+        + [
+            # When actually running Buck, the launcher script loads the bootstrapper,
+            # and the bootstrapper loads the rest of Buck. For unit tests, which don't
+            # run Buck, we have to add a direct dependency on the bootstrapper in case
+            # they exercise code that uses it.
+            "prelude//toolchains/android/src/com/facebook/buck/cli/bootstrapper:bootstrapper_lib",
+        ],
+        vm_args = [
+            # Don't use the system-installed JNA; extract it from the local jar.
+            "-Djna.nosys=true",
+            # Add -Dsun.zip.disableMemoryMapping=true to work around a JDK issue
+            # related to modifying JAR/ZIP files that have been loaded into memory:
+            #
+            # http://bugs.sun.com/view_bug.do?bug_id=7129299
+            #
+            # This has been observed to cause a problem in integration tests such as
+            # CachedTestIntegrationTest where `buck build //:test` is run repeatedly
+            # such that a corresponding `test.jar` file is overwritten several times.
+            # The CompiledClassFileFinder in JavaTestRule creates a java.util.zip.ZipFile
+            # to enumerate the zip entries in order to find the set of .class files
+            # in `test.jar`. This interleaving of reads and writes appears to match
+            # the conditions to trigger the issue reported on bugs.sun.com.
+            #
+            # Currently, we do not set this flag in bin/buck_common, as Buck does not
+            # normally modify the contents of buck-out after they are loaded into
+            # memory. However, we may need to use this flag when running buckd where
+            # references to zip files may be long-lived.
+            #
+            # Finally, note that when you specify this flag,
+            # `System.getProperty("sun.zip.disableMemoryMapping")` will return `null`
+            # even though you have specified the flag correctly. Apparently sun.misc.VM
+            # (http://www.docjar.com/html/api/sun/misc/VM.java.html) saves the property
+            # internally, but removes it from the set of system properties that are
+            # publicly accessible.
+            "-Dsun.zip.disableMemoryMapping=true",
+        ]
+        + (vm_args or []),
+        env = env,
+        run_test_separately = run_test_separately,
+        **kwargs,
+    )
+
+def standard_java_test(name, run_test_separately = False, vm_args = None, labels = None, with_test_data = False, **kwargs):
+    test_srcs = native.glob(["*Test.java"])
+
+    if len(test_srcs) > 0:
+        buck_java_test(
+            name = name,
+            srcs = test_srcs,
+            resources = native.glob(["testdata/**"]) if with_test_data else [],
+            vm_args = vm_args,
+            run_test_separately = run_test_separately,
+            labels = (labels or []) + ["buck2_run_from_cell_root"],
+            **kwargs,
+        )
+
+def buck_prebuilt_artifact(
+    # @oss-disable[end= ]: cas_digest,
+    oss_url = None,
+    oss_sha1 = None,
+    **kwargs,
+):
+    if (not is_full_meta_repo()) and oss_url:
+        return fb_native.remote_file(sha1 = oss_sha1, url = oss_url, **kwargs)
+    # @oss-disable[end= ]: else:
+        # @oss-disable[end= ]: return android_build_tools_cas_artifact(digest = cas_digest, **kwargs)
+        fail() # @oss-enable
diff --git a/buck2/prelude/toolchains/android/tools/build_rules/fb_native.bzl b/buck2/prelude/toolchains/android/tools/build_rules/fb_native.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/tools/build_rules/fb_native.bzl
@@ -0,0 +1,12 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# @oss-disable[end= ]: load("@fbsource//tools/build_defs:fb_native_wrapper.bzl", _fb_native = "fb_native")
+load("@prelude//:native.bzl", _fb_native = "native") # @oss-enable
+
+fb_native = _fb_native
diff --git a/buck2/prelude/toolchains/android/tools/build_rules/utils.bzl b/buck2/prelude/toolchains/android/tools/build_rules/utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/tools/build_rules/utils.bzl
@@ -0,0 +1,26 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:is_full_meta_repo.bzl", "is_full_meta_repo")
+load("@prelude//:native.bzl", "native")
+
+def add_os_labels(**kwargs):
+    if "labels" not in kwargs:
+        kwargs["labels"] = []
+
+    if native.host_info().os.is_macos:
+        kwargs["labels"] += ["tpx:platform:macos"]
+    if native.host_info().os.is_linux:
+        kwargs["labels"] += ["tpx:platform:linux"]
+    if native.host_info().os.is_windows:
+        kwargs["labels"] += ["tpx:platform:windows"]
+
+    if not is_full_meta_repo():
+        kwargs["labels"] += ["tpx:is_oss_build"]
+
+    return kwargs
diff --git a/buck2/prelude/toolchains/android/tools/build_rules/worker.bzl b/buck2/prelude/toolchains/android/tools/build_rules/worker.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/tools/build_rules/worker.bzl
@@ -0,0 +1,97 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load("@prelude//java:java_toolchain.bzl", "JavaToolchainInfo", "unsafe_memory_access_jvm_args")
+load("@prelude//toolchains/android/tools:build_rules.bzl", "OPEN_JDK_COMPILER_ARGS")
+
+def _jvm_arg_name_is_specified(arg_name: str, existing_jvm_args: list[str]) -> bool:
+    for existing_jvm_arg in existing_jvm_args:
+        if existing_jvm_arg.startswith(arg_name):
+            return True
+
+    return False
+
+def _get_jvm_args_for_worker(ctx, java_toolchain: JavaToolchainInfo):
+    jvm_args = ctx.attrs.jvm_args
+    if not "-XX:-MaxFDLimit" in jvm_args:
+        jvm_args.insert(0, "-XX:-MaxFDLimit")
+    if not _jvm_arg_name_is_specified("-Dfile.encoding", jvm_args):
+        jvm_args.insert(0, "-Dfile.encoding=UTF-8")
+    if not _jvm_arg_name_is_specified("-XX:CompressedClassSpaceSize", jvm_args):
+        jvm_args.insert(0, "-XX:CompressedClassSpaceSize=2g")
+
+    # Pre-size JIT code cache and metaspace to reduce warmup overhead on cold workers.
+    # kotlincd loads the Kotlin compiler, KSP framework, and annotation processors,
+    # which generates significant JIT-compiled code. Default code cache (240MB) can
+    # fill with 16 concurrent compilations, causing eviction and re-compilation.
+    # Default metaspace (~20MB) triggers repeated full GC as classes are loaded.
+    if not _jvm_arg_name_is_specified("-XX:ReservedCodeCacheSize", jvm_args):
+        jvm_args.insert(0, "-XX:ReservedCodeCacheSize=512m")
+    if not _jvm_arg_name_is_specified("-XX:MetaspaceSize", jvm_args):
+        jvm_args.insert(0, "-XX:MetaspaceSize=256m")
+
+    # Allow JVM compiler daemon to access internal jdk.compiler APIs
+    jvm_args.extend(OPEN_JDK_COMPILER_ARGS)
+    jvm_args.append("--add-opens=java.base/java.util=ALL-UNNAMED")
+
+    jvm_args.extend(unsafe_memory_access_jvm_args(java_toolchain.java_runtime_version))
+
+    return jvm_args
+
+def _get_args_for_worker(ctx):
+    java_toolchain = ctx.attrs._java_toolchain[JavaToolchainInfo]
+    args = cmd_args()
+    args.add(java_toolchain.java[RunInfo])
+    args.add(_get_jvm_args_for_worker(ctx, java_toolchain))
+    args.add([
+        "-cp",
+        ctx.attrs.exe,
+        "-jar",
+        ctx.attrs.class_loader_bootstrapper,
+        ctx.attrs.main_class,
+    ])
+
+    return args
+
+def _worker_impl(ctx):
+    args = _get_args_for_worker(ctx)
+    return [
+        DefaultInfo(),
+        WorkerInfo(
+            exe = RunInfo(args),
+            env = {
+                "BUCK_CLASSPATH": ctx.attrs.exe,
+                "JAVACD_ABSOLUTE_PATHS_ARE_RELATIVE_TO_CWD": "1",
+            },
+        ),
+    ]
+
+worker = rule(
+    impl = _worker_impl,
+    attrs = {
+        "class_loader_bootstrapper": attrs.source(default = "prelude//toolchains/android/src/com/facebook/buck/cli/bootstrapper:bootstrapper"),
+        "concurrency": attrs.option(attrs.int(), default = None),
+        "exe": attrs.source(),
+        "jvm_args": attrs.list(attrs.string(), default = []),
+        "main_class": attrs.string(),
+        "_java_toolchain": toolchains_common.java_bootstrap(),
+    },
+)
+
+remote_worker = rule(
+    impl = _worker_impl,
+    attrs = {
+        "class_loader_bootstrapper": attrs.source(default = "prelude//toolchains/android/src/com/facebook/buck/cli/bootstrapper:bootstrapper"),
+        "concurrency": attrs.option(attrs.int(), default = None),
+        "exe": attrs.source(),
+        "jvm_args": attrs.list(attrs.string(), default = []),
+        "main_class": attrs.string(),
+        "_java_toolchain": toolchains_common.java_bootstrap(),
+    },
+)
diff --git a/buck2/prelude/toolchains/android/tools/protobuf.bzl b/buck2/prelude/toolchains/android/tools/protobuf.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/tools/protobuf.bzl
@@ -0,0 +1,56 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:native.bzl", "native")
+load("@prelude//toolchains/android/tools:build_rules.bzl", "buck_java_library")
+
+def protobuf_src_gen(name, srcs, proto_path = [], deps = [], exported_deps = []):
+    common_args = [
+        "--java_opt=annotate_code",
+        "--proto_path=$SRCDIR",
+        "--java_out=$OUT --grpc-java_out=$OUT $SRCS".format(name, name),
+    ] + ["--proto_path={}".format(path) for path in proto_path]
+
+    command = [
+        "mkdir $OUT",
+        "&& $(exe prelude//toolchains/android/tools/protobuf:protoc)",
+        "--plugin=protoc-gen-grpc-java=$(location_exec prelude//toolchains/android/tools/protobuf:gen-grpc)",
+    ] + common_args
+
+    command_exe = [
+        "mkdir $OUT",
+        "&& copy $(location_exec prelude//toolchains/android/tools/protobuf:gen-grpc-windows) $TMP\\gen-grpc",
+        "&& $(exe prelude//toolchains/android/tools/protobuf:protoc)",
+        "--plugin=protoc-gen-grpc-java=$TMP\\gen-grpc",
+    ] + common_args
+
+    genrule_name = name + "-src-gen"
+    native.genrule(
+        name = genrule_name,
+        srcs = srcs,
+        out = name,
+        cmd = " ".join(command),
+        cmd_exe = " ".join(command_exe),
+        exec_compatible_with = ["ovr_config//cpu:x86_64"],
+    )
+
+    zip_rule_name = name + ".src.zip"
+    native.zip_file(
+        name = zip_rule_name,
+        srcs = [":" + genrule_name],
+        entries_to_exclude = [".*\\.pb\\.meta"],
+        out = name + ".src.zip",
+    )
+
+    buck_java_library(
+        name = name,
+        srcs = [":" + zip_rule_name],
+        visibility = ["PUBLIC"],
+        deps = deps,
+        exported_deps = exported_deps,
+    )
diff --git a/buck2/prelude/toolchains/android/tools/protobuf/BUCK b/buck2/prelude/toolchains/android/tools/protobuf/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/android/tools/protobuf/BUCK
@@ -0,0 +1,34 @@
+# @oss-disable[end= ]: load("@fbsource//tools/build_defs:default_platform_defs.bzl", "get_host_target_platform")
+load("@prelude//toolchains/android/tools/build_rules:fb_native.bzl", "fb_native")
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("android_devxx")
+
+source_listing()
+
+fb_native.command_alias(
+    name = "protoc",
+    # @oss-disable[end= ]: default_target_platform = get_host_target_platform(use_minimal_xcode = False),
+    platform_exe = {
+        "linux": "prelude//toolchains/android/third-party:protoc-linux-x86_64",
+        "macos": "prelude//toolchains/android/third-party:protoc-osx-x86_64",
+        "windows": "prelude//toolchains/android/third-party:protoc-windows-x86_64",
+    },
+    visibility = ["PUBLIC"],
+)
+
+fb_native.command_alias(
+    name = "gen-grpc",
+    # @oss-disable[end= ]: default_target_platform = get_host_target_platform(use_minimal_xcode = False),
+    platform_exe = {
+        "linux": "prelude//toolchains/android/third-party:protoc-gen-grpc-java-linux-x86_64",
+        "macos": "prelude//toolchains/android/third-party:protoc-gen-grpc-java-osx-x86_64",
+    },
+    visibility = ["PUBLIC"],
+)
+
+fb_native.alias(
+    name = "gen-grpc-windows",
+    actual = "prelude//toolchains/android/third-party:protoc-gen-grpc-java-windows-x86_64",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/BUCK b/buck2/prelude/toolchains/apple/xcode_version_checker/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/apple/xcode_version_checker/BUCK
@@ -0,0 +1,12 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+export_file(
+    name = "xcode_version_checker",
+    labels = ["buck2-only"],
+    mode = "reference",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/Makefile b/buck2/prelude/toolchains/apple/xcode_version_checker/Makefile
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/apple/xcode_version_checker/Makefile
@@ -0,0 +1,29 @@
+CFLAGS = -x objective-c -lobjc -fobjc-arc -fobjc-weak -O3 -Wall
+
+.PHONY: all clean test
+
+xcode_version_checker: xcode_version_checker.x86_64 xcode_version_checker.arm64
+	lipo -create -output xcode_version_checker xcode_version_checker.x86_64 xcode_version_checker.arm64
+xcode_version_checker.x86_64: src/xcode_version_checker.m src/xcode_version_checks.m
+	$(CC) $(CFLAGS) src/xcode_version_checker.m src/xcode_version_checks.m -o xcode_version_checker.x86_64 -target x86_64-apple-macos
+xcode_version_checker.arm64: src/xcode_version_checker.m src/xcode_version_checks.m
+	$(CC) $(CFLAGS) src/xcode_version_checker.m src/xcode_version_checks.m -o xcode_version_checker.arm64 -target arm64-apple-macos
+
+all: xcode_version_checker test
+
+test: xcode_version_tester xcode_exec_tester
+	./xcode_version_tester $(abspath test/Xcode_14.2.0_14C18_fb_version.plist)
+	./xcode_exec_tester "/usr/bin/true"
+	./xcode_exec_tester "/bin/bash" "-c" "! /usr/bin/false"
+
+xcode_version_tester: src/xcode_version_tester.m src/xcode_version_checks.m
+	$(CC) $(CFLAGS) src/xcode_version_tester.m src/xcode_version_checks.m -o xcode_version_tester
+
+xcode_exec_tester: src/xcode_exec_tester.m src/xcode_version_checks.m
+	$(CC) $(CFLAGS) src/xcode_exec_tester.m src/xcode_version_checks.m -o xcode_exec_tester
+
+clean:
+	rm -f xcode_version_checker.x86_64
+	rm -f xcode_version_checker.arm64
+	rm -f xcode_version_tester
+	rm -f xcode_exec_tester
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/README b/buck2/prelude/toolchains/apple/xcode_version_checker/README
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/apple/xcode_version_checker/README
@@ -0,0 +1,8 @@
+- Run `make` to compile the `xcode_version_checker` binary.
+- Run `make all` to compile the `xcode_version_checker` binary and run all tests.
+- Run `make test` to just run tests.
+- Run `make clean` to delete tests and intermediate binaries.
+
+We cannot include this as part of the toolchain because of
+bootstrapping issues: i.e., compiling it requires an
+`apple_toolchain` but its needed to define an `apple_toolchain`.
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/defs.bzl b/buck2/prelude/toolchains/apple/xcode_version_checker/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/apple/xcode_version_checker/defs.bzl
@@ -0,0 +1,40 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:native.bzl", _native = "native")
+
+def xcode_command_alias(name, xcode_version = None, xcode_product_build = None, **kwargs):
+    xcode_version_specified = xcode_version and len(xcode_version) > 0
+    xcode_product_build_specified = xcode_product_build and len(xcode_product_build) > 0
+
+    if not xcode_version_specified and not xcode_product_build_specified:
+        fail("Must specify either Xcode version or Xcode product build")
+    if xcode_version_specified and xcode_product_build_specified:
+        fail("Must specify only one of Xcode version or Xcode product build but not both")
+
+    version_args = ["-n", xcode_version] if xcode_version_specified else ["-b", xcode_product_build]
+    original_args = kwargs.pop("args", [])
+    all_args = version_args + original_args
+
+    env = kwargs.pop("env", {})
+    xcode_cache_seed = read_root_config("apple", "xcode_cache_seed", None)
+    if xcode_cache_seed:
+        # It's possible that Mac RE does not distinguish between Xcode versions,
+        # in which case we can reset the caches by setting a unique env var.
+        # Since the env var is part of the cache key, that means that any actions
+        # depending on selected Xcode will get recomputed.
+        env["BUCK2_XCODE_CACHE_SEED"] = xcode_cache_seed
+
+    # This setup means that all `xcode_command_alias()` would effectively become:
+    #   xcode_version_checker VERSION ORIGINAL_COMMAND ORIGINAL_COMMAND_ARGS
+    # `xcode_version_checker` will check the currently selected Xcode and
+    # if it matches, it will then execute `ORIGINAL_COMMAND`
+    # passing `ORIGINAL_COMMAND_ARGS`.
+    _native.command_alias(
+        name = name, exe = "prelude//toolchains/apple/xcode_version_checker:xcode_version_checker", args = all_args, env = env, visibility = ["PUBLIC"], **kwargs
+    )
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_exec_tester.m b/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_exec_tester.m
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_exec_tester.m
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+#import <Foundation/Foundation.h>
+#import <unistd.h>
+
+#import "xcode_version_checks.h"
+
+int main(int argc, char const* argv[]) {
+  @autoreleasepool {
+    const int numberOfArgs = argc - 1;
+    if (numberOfArgs < 1) {
+      fprintf(
+          stderr, "Expected at least one arguments: executable, aborting...\n");
+      return 1;
+    }
+
+    execTool(argv + 1, argc - 1);
+    // `execTool` should never return, if it did, it means it failed to `execve`
+    return 1;
+  }
+}
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checker.m b/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checker.m
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checker.m
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+#import <Foundation/Foundation.h>
+#import <unistd.h>
+
+#import "xcode_version_checks.h"
+
+int main(int argc, char const* argv[]) {
+  @autoreleasepool {
+    // This executable gets called with the following arguments:
+    // - Version format (argv[1]) (`-n` for short version, `-b` for product
+    // build)
+    // - Expected Xcode version (argv[2])
+    // - Executable (argv[3])
+    // - Args to forward executable
+    //
+    // For example, it will be something like:
+    //   xcode_version_checker -n 13.4
+    //   /var/db/xcode_select_link/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
+    //   -c file.c -o file.o
+
+    // TODO(T128745718): We need to figure out the fastest way to implement this
+    // forwarder. There are multiple options with varying tradeoffs and we need
+    // to make decisions along the following axes:
+    // - Plist parsing vs memory comparison
+    // - Embedding of expected plist data
+    // - Hashing vs full comparison
+    //
+    // I believe it's important to focus on max performance given this will be
+    // running for _every_ tool invocation which will amount to millions of
+    // executions per _day_.
+
+    const int numberOfArgs = argc - 1;
+    if (numberOfArgs < 3) {
+      fprintf(
+          stderr,
+          "Expected at least three arguments: version format, Xcode version and executable, aborting...\n");
+      return 1;
+    }
+
+    NSString* expectedVersion = [[NSString alloc] initWithUTF8String:argv[2]];
+    const char* versionFormat = argv[1];
+    if (strcmp(versionFormat, "-n") == 0) {
+      if (!checkXcodeShortVersionMatch(expectedVersion)) {
+        return 1;
+      }
+    } else if (strcmp(versionFormat, "-b") == 0) {
+      if (!checkXcodeProductBuildMatch(expectedVersion)) {
+        return 1;
+      }
+    } else {
+      fprintf(
+          stderr,
+          "Found unknown version format `%s`, expected version `%s`, aborting...\n",
+          argv[1],
+          expectedVersion.UTF8String);
+      return 1;
+    }
+
+    const int stripArgsCount = 3; // executable + version
+    execTool(argv + stripArgsCount, argc - stripArgsCount);
+    // `execTool` should never return, if it did, it means it failed to `execve`
+    return 1;
+  }
+}
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checks.h b/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checks.h
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checks.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+#pragma once
+
+#import <Foundation/Foundation.h>
+
+BOOL checkVersionsMatch(NSString* shortVersion, NSString* expectedShortVersion);
+void execTool(char const* arguments[], int argumentsCount);
+BOOL checkPlistValueMatch(
+    NSString* plistPath,
+    NSString* plistKey,
+    NSString* expectedValue,
+    BOOL (*comparator)(NSString* value, NSString* expectedValue),
+    BOOL logComparisonFailure);
+
+BOOL checkProductBuildVersionMatch(
+    NSString* productBuild,
+    NSString* expectedProductBuild);
+BOOL checkVersionPlistProductBuildMatch(
+    NSString* plistPath,
+    NSString* expectedProductBuild,
+    BOOL logComparisonFailure);
+BOOL checkXcodeProductBuildMatch(NSString* expectedProductBuild);
+
+BOOL checkVersionPlistShortVersionMatch(
+    NSString* plistPath,
+    NSString* expectedShortVersion,
+    BOOL logComparisonFailure);
+BOOL checkXcodeShortVersionMatch(NSString* expectedShortVersion);
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checks.m b/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checks.m
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_checks.m
@@ -0,0 +1,213 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+#import "xcode_version_checks.h"
+
+#import <crt_externs.h>
+#import <stdlib.h>
+
+extern char** environ;
+
+static BOOL IsInsideRemoteExecutionWorker(void) {
+  // TODO: Remove dependence on ACTION_DIGEST, once D41872225 lands
+  return getenv("INSIDE_RE_WORKER") != NULL || getenv("ACTION_DIGEST") != NULL;
+}
+
+static NSUInteger effectiveVersionComponentsCount(
+    NSArray<NSString*>* versionComponents) {
+  NSUInteger zeroTrailingComponentsCount = 0;
+  for (NSInteger i = [versionComponents count]; i > 0; --i) {
+    NSString* component = [versionComponents objectAtIndex:(i - 1)];
+    if ([component isEqual:@"0"]) {
+      zeroTrailingComponentsCount++;
+    }
+  }
+
+  // Ignore trailing zero components, e.g.,, treat "14.0.0" as "14"
+  return [versionComponents count] - zeroTrailingComponentsCount;
+}
+
+// Looks for _exact_ match for versions up to all components specified in
+// `expectedShortVersion`
+BOOL checkVersionsMatch(
+    NSString* shortVersion,
+    NSString* expectedShortVersion) {
+  NSArray<NSString*>* expectedShortVersionComponents =
+      [expectedShortVersion componentsSeparatedByString:@"."];
+  NSArray<NSString*>* shortVersionComponents =
+      [shortVersion componentsSeparatedByString:@"."];
+
+  NSUInteger shortVersionComponentsCount =
+      effectiveVersionComponentsCount(shortVersionComponents);
+  NSUInteger expectedShortVersionComponentsCount =
+      effectiveVersionComponentsCount(expectedShortVersionComponents);
+  if (shortVersionComponentsCount < expectedShortVersionComponentsCount) {
+    return NO;
+  }
+
+  for (NSUInteger i = 0; i < expectedShortVersionComponentsCount; ++i) {
+    NSString* expectedComponent =
+        [expectedShortVersionComponents objectAtIndex:i];
+    NSString* actualComponent = [shortVersionComponents objectAtIndex:i];
+    if (![expectedComponent isEqual:actualComponent]) {
+      return NO;
+    }
+  }
+
+  return YES;
+}
+
+BOOL checkPlistValueMatch(
+    NSString* plistPath,
+    NSString* plistKey,
+    NSString* expectedValue,
+    BOOL (*comparator)(NSString* value, NSString* expectedValue),
+    BOOL logComparisonFailure) {
+  NSURL* xcodePlistUrl = [NSURL fileURLWithPath:plistPath];
+  NSError* xcodePlistError = nil;
+  NSData* xcodePlistData = [NSData dataWithContentsOfURL:xcodePlistUrl
+                                                 options:0
+                                                   error:&xcodePlistError];
+  if (xcodePlistData == nil) {
+    fprintf(
+        stderr,
+        "Failed to read Xcode plist file: %s\n",
+        (xcodePlistError.description.UTF8String ?: ""));
+    return NO;
+  }
+
+  NSError* plistError = nil;
+  id xcodePlist =
+      [NSPropertyListSerialization propertyListWithData:xcodePlistData
+                                                options:NSPropertyListImmutable
+                                                 format:nil
+                                                  error:&plistError];
+  if (xcodePlist == nil) {
+    fprintf(
+        stderr,
+        "Failed to parse Xcode plist file: %s\n",
+        (plistError.description.UTF8String ?: ""));
+    return NO;
+  }
+
+  if (![xcodePlist isKindOfClass:[NSDictionary class]]) {
+    fprintf(stderr, "Plist is not a dictionary\n");
+    return NO;
+  }
+
+  NSDictionary* xcodePlistDict = (NSDictionary*)xcodePlist;
+  NSString* value = xcodePlistDict[plistKey];
+  if (![value isKindOfClass:[NSString class]]) {
+    fprintf(stderr, "Version is not of type string\n");
+    return NO;
+  }
+
+  BOOL comparisonResult = comparator(value, expectedValue);
+  if (!comparisonResult && logComparisonFailure) {
+    fprintf(
+        stderr,
+        "Found unexpected Xcode version, expected %s but found %s, aborting...\n",
+        expectedValue.UTF8String,
+        value.UTF8String);
+    if (IsInsideRemoteExecutionWorker()) {
+      fprintf(
+          stderr,
+          "This error was generated inside an RE worker. To debug, check the following:\n"
+          "1) The command being executed\n"
+          "2) The subplatform property of the RE action\n"
+          "3) The execution platform constraints\n"
+          "4) The Xcode installed on the particular worker\n");
+    } else {
+      fprintf(
+          stderr,
+          "This error was generated when running locally. To debug, check the following:\n"
+          "1) The command being executed\n"
+          "2) The selected Xcode version\n"
+          "3) Did you select a different Xcode _after_ a buck2 daemon was launched?\n"
+          "4) The execution platform constraints\n"
+          "5) The tools specified for the `apple_toolchain()`\n");
+    }
+  }
+
+  return comparisonResult;
+}
+
+BOOL checkProductBuildVersionMatch(
+    NSString* productBuild,
+    NSString* expectedProductBuild) {
+  if (productBuild == expectedProductBuild) {
+    return YES;
+  }
+
+  if (productBuild == nil || expectedProductBuild == nil) {
+    // `caseInsensitiveCompare:` is declared taking non-null, so guard against
+    return NO;
+  }
+
+  NSComparisonResult cmpResult =
+      [productBuild caseInsensitiveCompare:expectedProductBuild];
+  return (cmpResult == NSOrderedSame);
+}
+
+BOOL checkVersionPlistProductBuildMatch(
+    NSString* plistPath,
+    NSString* expectedProductBuild,
+    BOOL logComparisonFailure) {
+  return checkPlistValueMatch(
+      plistPath,
+      @"ProductBuildVersion",
+      expectedProductBuild,
+      checkProductBuildVersionMatch,
+      logComparisonFailure);
+}
+
+NSString* const VERSION_PLIST_PATH =
+    @"/var/db/xcode_select_link/../version.plist";
+BOOL checkXcodeProductBuildMatch(NSString* expectedProductBuild) {
+  return checkVersionPlistProductBuildMatch(
+      VERSION_PLIST_PATH,
+      expectedProductBuild,
+      /* logComparisonFailure = */ YES);
+}
+
+BOOL checkVersionPlistShortVersionMatch(
+    NSString* plistPath,
+    NSString* expectedShortVersion,
+    BOOL logComparisonFailure) {
+  return checkPlistValueMatch(
+      plistPath,
+      @"CFBundleShortVersionString",
+      expectedShortVersion,
+      checkVersionsMatch,
+      logComparisonFailure);
+}
+
+BOOL checkXcodeShortVersionMatch(NSString* expectedShortVersion) {
+  return checkVersionPlistShortVersionMatch(
+      VERSION_PLIST_PATH,
+      expectedShortVersion,
+      /* logComparisonFailure = */ YES);
+}
+
+void execTool(char const* arguments[], int argumentsCount) {
+  int execArgvSize = argumentsCount + 1 /* NULL terminator */;
+  char** execArgv = malloc(
+      sizeof(char*) *
+      execArgvSize); // no need to free() as either we execve() or exit
+  memcpy(execArgv, arguments, argumentsCount * sizeof(char*));
+  execArgv[execArgvSize - 1] = NULL;
+  execve(arguments[0], execArgv, environ);
+  // execve() never returns on success, so we must have failed if we're here
+  fprintf(
+      stderr,
+      "Failed to execve(), errno %d, description: %s\n",
+      errno,
+      strerror(errno));
+}
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_tester.m b/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_tester.m
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/apple/xcode_version_checker/src/xcode_version_tester.m
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is dual-licensed under either the MIT license found in the
+ * LICENSE-MIT file in the root directory of this source tree or the Apache
+ * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+ * of this source tree. You may select, at your option, one of the
+ * above-listed licenses.
+ */
+
+#import <Foundation/Foundation.h>
+
+#import "xcode_version_checks.h"
+
+typedef struct {
+  NSString* actualVersion;
+  NSString* expectedVersion;
+  BOOL versionsMatch;
+} version_check;
+
+typedef struct {
+  NSString* actualBuild;
+  NSString* expectedBuild;
+  BOOL versionsMatch;
+} build_check;
+
+typedef struct {
+  NSString* plistPath;
+  BOOL (*plistFunction)(
+      NSString* plistPath,
+      NSString* expectedValue,
+      BOOL logComparisonFailure);
+  NSString* expectedValue;
+  BOOL versionsMatch;
+} plist_check;
+
+int main(int argc, char const* argv[]) {
+  @autoreleasepool {
+    version_check checks[] = {
+        {
+            .actualVersion = @"14",
+            .expectedVersion = @"14",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14.2",
+            .expectedVersion = @"14.2",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14.2",
+            .expectedVersion = @"14",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14.2.1",
+            .expectedVersion = @"14.2",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"13",
+            .expectedVersion = @"14",
+            .versionsMatch = NO,
+        },
+        {
+            .actualVersion = @"15",
+            .expectedVersion = @"14",
+            .versionsMatch = NO,
+        },
+        {
+            .actualVersion = @"14.2.1",
+            .expectedVersion = @"14.2.1",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14.2.3",
+            .expectedVersion = @"14.2.2",
+            .versionsMatch = NO,
+        },
+        {
+            .actualVersion = @"14.2.1",
+            .expectedVersion = @"14.2.2",
+            .versionsMatch = NO,
+        },
+        {
+            .actualVersion = @"14.3",
+            .expectedVersion = @"14.2",
+            .versionsMatch = NO,
+        },
+        {
+            .actualVersion = @"14.1",
+            .expectedVersion = @"14.2",
+            .versionsMatch = NO,
+        },
+        {
+            .actualVersion = @"14",
+            .expectedVersion = @"14.0",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14.0",
+            .expectedVersion = @"14",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14.0.0",
+            .expectedVersion = @"14.0",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14.0",
+            .expectedVersion = @"14.0.0",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14.0.0.0",
+            .expectedVersion = @"14",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14",
+            .expectedVersion = @"14.0.0.0",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14.1.0",
+            .expectedVersion = @"14.1",
+            .versionsMatch = YES,
+        },
+        {
+            .actualVersion = @"14.1",
+            .expectedVersion = @"14.1.0",
+            .versionsMatch = YES,
+        },
+    };
+
+    for (NSUInteger i = 0; i < sizeof(checks) / sizeof(*checks); ++i) {
+      version_check check = checks[i];
+      if (checkVersionsMatch(check.actualVersion, check.expectedVersion) !=
+          check.versionsMatch) {
+        fprintf(
+            stderr,
+            "Version checked failed, version: `%s`, expected: `%s`, expected match result: %d...\n",
+            check.actualVersion.UTF8String,
+            check.expectedVersion.UTF8String,
+            check.versionsMatch);
+        return 1;
+      }
+    }
+
+    const int numberOfArgs = argc - 1;
+    if (numberOfArgs < 1) {
+      fprintf(stderr, "Expected path to Info.plist as first argument...\n");
+      return 1;
+    }
+
+    NSString* versionPlistPath = [[NSString alloc] initWithUTF8String:argv[1]];
+    plist_check plist_checks[] = {
+        {
+            .plistPath = versionPlistPath,
+            .plistFunction = checkVersionPlistShortVersionMatch,
+            .expectedValue = @"14.2",
+            .versionsMatch = YES,
+        },
+        {
+            .plistPath = versionPlistPath,
+            .plistFunction = checkVersionPlistShortVersionMatch,
+            .expectedValue = @"14.3",
+            .versionsMatch = NO,
+        },
+        {
+            .plistPath = versionPlistPath,
+            .plistFunction = checkVersionPlistProductBuildMatch,
+            .expectedValue = @"14C18",
+            .versionsMatch = YES,
+        },
+        {
+            .plistPath = versionPlistPath,
+            .plistFunction = checkVersionPlistProductBuildMatch,
+            .expectedValue = @"14B5033e",
+            .versionsMatch = NO,
+        },
+    };
+
+    for (NSUInteger i = 0; i < sizeof(plist_checks) / sizeof(*plist_checks);
+         ++i) {
+      plist_check check = plist_checks[i];
+      if (check.plistFunction(
+              check.plistPath,
+              check.expectedValue,
+              /* logComparisonFailure = */ NO) != check.versionsMatch) {
+        fprintf(
+            stderr,
+            "Version check failed, plist path: `%s`, expected value: `%s`, expected match result: %d...\n",
+            check.plistPath.UTF8String,
+            check.expectedValue.UTF8String,
+            check.versionsMatch);
+        return 1;
+      }
+    }
+
+    build_check build_checks[] = {
+        {
+            .actualBuild = @"14e222b",
+            .expectedBuild = @"14E222b",
+            .versionsMatch = YES,
+        },
+        {
+            .actualBuild = @"14e300b'",
+            .expectedBuild = @"14e222b",
+            .versionsMatch = NO,
+        },
+    };
+
+    for (NSUInteger i = 0; i < sizeof(build_checks) / sizeof(*build_checks);
+         ++i) {
+      build_check check = build_checks[i];
+      if (checkProductBuildVersionMatch(
+              check.actualBuild, check.expectedBuild) != check.versionsMatch) {
+        fprintf(
+            stderr,
+            "Build check failed, build: `%s`, expected: `%s`, expected match result: %d...\n",
+            check.actualBuild.UTF8String,
+            check.expectedBuild.UTF8String,
+            check.versionsMatch);
+        return 1;
+      }
+    }
+
+    return 0;
+  }
+}
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/test/Xcode_14.2.0_14C18_fb_version.plist b/buck2/prelude/toolchains/apple/xcode_version_checker/test/Xcode_14.2.0_14C18_fb_version.plist
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/apple/xcode_version_checker/test/Xcode_14.2.0_14C18_fb_version.plist
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>BuildVersion</key>
+	<string>49</string>
+	<key>CFBundleShortVersionString</key>
+	<string>14.2</string>
+	<key>CFBundleVersion</key>
+	<string>21534</string>
+	<key>ProductBuildVersion</key>
+	<string>14C18</string>
+	<key>ProjectName</key>
+	<string>IDEFrameworks</string>
+	<key>SourceVersion</key>
+	<string>21534000000000000</string>
+</dict>
+</plist>
diff --git a/buck2/prelude/toolchains/apple/xcode_version_checker/xcode_version_checker b/buck2/prelude/toolchains/apple/xcode_version_checker/xcode_version_checker
new file mode 100644
Binary files /dev/null and b/buck2/prelude/toolchains/apple/xcode_version_checker/xcode_version_checker differ
diff --git a/buck2/prelude/toolchains/conan/BUCK b/buck2/prelude/toolchains/conan/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/BUCK
@@ -0,0 +1,63 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+export_file(
+    name = "buckler",
+    src = "buckler/conanfile.py",
+    visibility = ["PUBLIC"],
+)
+
+python_bootstrap_library(
+    name = "conan_common",
+    srcs = ["conan_common.py"],
+)
+
+python_bootstrap_binary(
+    name = "conan_generate",
+    main = "conan_generate.py",
+    visibility = ["PUBLIC"],
+    deps = [":conan_common"],
+)
+
+python_bootstrap_binary(
+    name = "conan_init",
+    main = "conan_init.py",
+    visibility = ["PUBLIC"],
+    deps = [":conan_common"],
+)
+
+python_bootstrap_binary(
+    name = "conan_lock",
+    main = "conan_lock.py",
+    visibility = ["PUBLIC"],
+    deps = [":conan_common"],
+)
+
+python_bootstrap_binary(
+    name = "conan_package",
+    main = "conan_package.py",
+    visibility = ["PUBLIC"],
+    deps = [":conan_common"],
+)
+
+python_bootstrap_binary(
+    name = "conan_package_extract",
+    main = "conan_package_extract.py",
+    visibility = ["PUBLIC"],
+)
+
+python_bootstrap_binary(
+    name = "conan_update",
+    main = "conan_update.py",
+    visibility = ["PUBLIC"],
+)
+
+python_bootstrap_binary(
+    name = "lock_generate",
+    main = "lock_generate.py",
+    visibility = ["PUBLIC"],
+    deps = [":conan_common"],
+)
diff --git a/buck2/prelude/toolchains/conan/buckler/conanfile.py b/buck2/prelude/toolchains/conan/buckler/conanfile.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/buckler/conanfile.py
@@ -0,0 +1,252 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import collections
+import os
+import re
+
+from conans import ConanFile
+from conans.model import Generator
+
+
+def _rel_to_root(rootpath, path):
+    """Make the given path relative to the given root path."""
+    return os.path.relpath(path, rootpath)
+
+
+def _map_rel_to_root(rootpath, paths):
+    """Make all given paths relative to the given root path."""
+    return [_rel_to_root(rootpath, p) for p in paths]
+
+
+_LibraryFiles = collections.namedtuple("_LibraryFiles", ["static", "shared"])
+
+
+def _find_libs(rootpath, lib_paths, lib_names):
+    """Collect static and shared library files for the given library names.
+
+    Searches for library files under the given library search paths.
+    Retains order as defined in the given library names in case it matters for
+    linking order.
+    """
+    result = collections.OrderedDict(
+        (name, _LibraryFiles([], [])) for name in lib_names
+    )
+
+    name_pattern = "(?P<name>{})".format("|".join(lib_names))
+    ext_pattern = (
+        "(?:(?P<static>a|lib)|(?P<shared>so(?:\\.\\d+(?:\\.\\d+)?)?|dylib|dll))"
+    )
+    regex = re.compile("lib{}.{}".format(name_pattern, ext_pattern))
+
+    files = (
+        os.path.join(libdir, filepath)
+        for libdir in lib_paths
+        for filepath in os.listdir(os.path.join(rootpath, libdir))
+        if os.path.isfile(os.path.join(rootpath, libdir, filepath))
+    )
+
+    for filepath in files:
+        m = regex.match(os.path.basename(filepath))
+        if m:
+            name = m.group("name")
+            # TODO[AH] Can we distinguish static and static-pic libs?
+            if m.group("static"):
+                result[name].static.append(filepath)
+            elif m.group("shared"):
+                result[name].shared.append(filepath)
+
+    return result
+
+
+class _Requirement(collections.namedtuple("_Requirement", ["package", "component"])):
+    """Represents a Conan requirement.
+
+    Requirements can be
+    * a relative reference to a component of the current package - `package` None, `component` set,
+    * an absolute reference to a package - `package` set, `component` None, or
+    * an absolute reference to another package's component - `package` set, `component` set.
+    """
+
+    @classmethod
+    def parse(cls, requirement):
+        """Parse a Conan requirement.
+
+        These take the form
+        * `somecomponent` for a relative component reference,
+        * `somepackage::somepackage` for an absolute package reference, or
+        * `somepackage::somecomponent` for an absolute component reference.
+        """
+        if "::" in requirement:
+            package, component = requirement.split("::", 1)
+            if package == component:
+                return cls(package, None)
+            else:
+                return cls(package, component)
+        else:
+            return cls(None, requirement)
+
+    def to_name(self, current_package):
+        """Generate the Buck2 target name for a requirement."""
+        package = self.package or current_package
+        component = self.component or package
+        return "_component_{}_{}".format(package, component)
+
+    def to_label(self, current_package):
+        """Generate the Buck2 label for a requirement.
+
+        Relative requirements use the given current package's name to refer directly to the component target.
+        Absolute requirements refer to the package target or sub-target.
+        """
+        if self.package and self.component:
+            return ":{}[{}]".format(self.package, self.component)
+        elif self.package:
+            return ":{}".format(self.package)
+        else:
+            return ":{}".format(self.to_name(current_package))
+
+
+class _BucklerDepCppComponent(object):
+    """A Conan package component or the package itself if it has no components.
+
+    You can learn more about Conan package components [here][conan-components].
+
+    [conan-components]: https://docs.conan.io/en/1.53/creating_packages/package_information.html#using-components
+    """
+
+    def __init__(self, package_name, component_info):
+        self.package_name = package_name
+        self.component_name = component_info.name
+        self.rootpath = component_info.rootpath
+        rootpath = self.rootpath
+
+        self.defines = component_info.defines
+        self.cflags = component_info.cflags
+        self.cppflags = component_info.cppflags
+
+        self.include_paths = _map_rel_to_root(rootpath, component_info.include_paths)
+
+        lib_paths = _map_rel_to_root(rootpath, component_info.lib_paths)
+        self.libs = _find_libs(rootpath, lib_paths, component_info.libs)
+        self.system_libs = component_info.system_libs
+
+        self.requires = [_Requirement.parse(req) for req in component_info.requires]
+
+    def generate(self):
+        """Generate Buck2 target definitions for the component."""
+        name = _Requirement(None, self.component_name).to_name(self.package_name)
+        deps = [req.to_label(self.package_name) for req in self.requires]
+        return """\
+
+conan_component(
+    name = {name!r},
+    defines = {defines!r},
+    cflags = {cflags!r},
+    cppflags = {cppflags!r},
+    include_paths = {include_paths!r},
+    libs = {libs!r},
+    static_libs = {static_libs!r},
+    shared_libs = {shared_libs!r},
+    system_libs = {system_libs!r},
+    deps = {deps!r},
+    package = {package!r},
+)
+""".format(
+            name=name,
+            defines=self.defines,
+            cflags=self.cflags,
+            cppflags=self.cppflags,
+            include_paths=self.include_paths,
+            libs=list(self.libs.keys()),
+            static_libs={
+                name: sorted(libs.static)
+                for name, libs in self.libs.items()
+                if libs.static
+            },
+            shared_libs={
+                name: sorted(libs.shared)
+                for name, libs in self.libs.items()
+                if libs.shared
+            },
+            system_libs=self.system_libs,
+            deps=deps,
+            package=":_package_" + self.package_name,
+        )
+
+
+class _BucklerDepCpp(object):
+    """A Conan package."""
+
+    def __init__(self, dep_name, dep_cpp_info, public=False):
+        self.name = dep_name
+        self.public = public
+        self.rootpath = dep_cpp_info.rootpath
+        if dep_cpp_info.components:
+            self.components = collections.OrderedDict(
+                (name, _BucklerDepCppComponent(dep_name, component_info))
+                for (name, component_info) in dep_cpp_info.components.items()
+            )
+        else:
+            self.components = collections.OrderedDict(
+                [(dep_name, _BucklerDepCppComponent(dep_name, dep_cpp_info))]
+            )
+
+    def generate(self):
+        """Generate Buck2 target definitions for the package and its components."""
+        result = """\
+
+conan_dep(
+    name = {name!r},
+    components = {components!r},
+    visibility = {visibility!r},
+)
+""".format(
+            name=self.name,
+            components={
+                name: _Requirement(None, name).to_label(self.name)
+                for name in self.components.keys()
+            },
+            visibility=["PUBLIC"] if self.public else [],
+        )
+
+        for component in self.components.values():
+            result += component.generate()
+
+        return result
+
+
+class BucklerGenerator(Generator):
+    @property
+    def filename(self):
+        return "conan-imports.bzl"
+
+    @property
+    def content(self):
+        result = ""
+
+        for dep_name, dep_cpp_info in self.deps_build_info.dependencies:
+            direct_dep = dep_name in self.conanfile.requires
+            buckler_dep = _BucklerDepCpp(dep_name, dep_cpp_info, public=direct_dep)
+            result += buckler_dep.generate()
+
+        return result
+
+
+class Buckler(ConanFile):
+    name = "buckler"
+    version = "0.1"
+    description = """\
+Buckler - Conan extension for Buck2
+
+This package provides a
+- [Generator][generator] to import Conan built packages into Buck2.
+
+[generator]: https://docs.conan.io/en/latest/reference/generators.html#generators-reference
+"""
+    url = "https://github.com/facebookincubator/buck2"
+    license = "Apache-2.0"
diff --git a/buck2/prelude/toolchains/conan/conan_common.py b/buck2/prelude/toolchains/conan/conan_common.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/conan_common.py
@@ -0,0 +1,185 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import os
+import shutil
+import subprocess
+
+
+def _none(s):
+    if not s or s == "_":
+        return None
+    else:
+        return s
+
+
+def parse_reference(ref):
+    """Parse a Conan package reference.
+
+    These take the shape `name/version@channel/name#revision`.
+    Omitted values or `_` are read as `None`.
+    """
+    name = None
+    version = None
+    user = None
+    channel = None
+    revision = None
+
+    if "#" in ref:
+        ref, revision = ref.split("#", 1)
+
+    if "@" in ref:
+        ref, user_channel = ref.split("@", 1)
+        if "/" in user_channel:
+            user, channel = user_channel.split("/", 1)
+        else:
+            user = user_channel
+
+    if "/" in ref:
+        name, version = ref.split("/", 1)
+    else:
+        name = ref
+
+    return _none(name), _none(version), _none(user), _none(channel), _none(revision)
+
+
+CONAN_DIR = ".conan"
+GENERATORS_DIR = "generators"
+STORE_DIR = "data"
+PACKAGE_DIR = "package"
+
+
+def conan_dir(user_home):
+    """Conan folder under the Conen user home."""
+    return os.path.join(user_home, CONAN_DIR)
+
+
+def generators_dir(user_home):
+    """Custom generators folder under the Conen user home."""
+    return os.path.join(conan_dir(user_home), "generators")
+
+
+def store_dir(user_home):
+    """Store folder under the Conen user home."""
+    return os.path.join(conan_dir(user_home), "data")
+
+
+def reference_subtree(name, version, user, channel):
+    """Package base directory subtree under the Conan store folder."""
+    return os.path.join(name or "_", version or "_", user or "_", channel or "_")
+
+
+def package_subtree(package_id):
+    """Package directory subtree under the package base directory."""
+    return os.path.join(PACKAGE_DIR, package_id)
+
+
+def reference_dir(user_home, name, version, user, channel):
+    """Package base directory under the Conan store folder."""
+    return os.path.join(
+        store_dir(user_home), reference_subtree(name, version, user, channel)
+    )
+
+
+def package_dir(user_home, name, version, user, channel, package_id):
+    """Package directory under the Conan store folder."""
+    return os.path.join(
+        reference_dir(user_home, name, version, user, channel),
+        package_subtree(package_id),
+    )
+
+
+def _copytree(src, dst):
+    """Recursively copy the source directory tree to the destination.
+
+    Copies symbolic links and ignores dangling symbolic links.
+    """
+    shutil.copytree(src, dst, symlinks=True, ignore_dangling_symlinks=True)
+
+
+def install_user_home(user_home, base_user_home):
+    """Copy the given base user-home to the current user-home."""
+    src = base_user_home
+    dst = user_home
+    _copytree(src, dst)
+
+
+def install_generator(user_home, generator_file):
+    """Copy the given custom generator into the generators path.
+
+    Note, this will overwrite any pre-existing generators.
+    """
+    src = generator_file
+    dstdir = generators_dir(user_home)
+    dst = os.path.join(dstdir, "conanfile.py")
+    os.makedirs(dstdir, exist_ok=True)
+    shutil.copyfile(src, dst)
+
+
+def install_reference(user_home, reference, path):
+    """Copy the cache directory of a given package reference into the store."""
+    name, version, user, channel, _ = parse_reference(reference)
+    src = path
+    dst = reference_dir(user_home, name, version, user, channel)
+    _copytree(src, dst)
+
+
+def extract_reference(user_home, reference, output):
+    """Copy the cache directory of the given package reference out of the store."""
+    name, version, user, channel, _ = parse_reference(reference)
+    src = reference_dir(user_home, name, version, user, channel)
+    dst = output
+    _copytree(src, dst)
+
+
+def extract_package(user_home, reference, package_id, output):
+    """Copy the package directory of the given package out of the store."""
+    name, version, user, channel, _ = parse_reference(reference)
+    src = package_dir(user_home, name, version, user, channel, package_id)
+    dst = output
+    _copytree(src, dst)
+
+
+def conan_env(user_home=None, trace_log=None):
+    """Generate environment variables needed to invoke Conan."""
+    env = dict(os.environ)
+
+    if user_home is not None:
+        # Set the Conan base directory.
+        env["CONAN_USER_HOME"] = os.path.abspath(user_home)
+
+    if trace_log is not None:
+        # Enable Conan debug trace.
+        env["CONAN_TRACE_FILE"] = os.path.abspath(trace_log)
+
+    # TODO[AH] Enable Conan revisions for reproducibility
+    # Enable Conan revisions for reproducibility
+    # env["CONAN_REVISIONS_ENABLED"] = "1"
+
+    # Prevent over-allocation.
+    # TODO[AH] Support parallelized package builds and set an appropriate action
+    #   weight using the `weight` parameter to `ctx.actions.run`.
+    #   Note that not all Conan packages respect the `CONAN_CPU_COUNT` setting.
+    env["CONAN_CPU_COUNT"] = "1"
+
+    # Prevent interactive prompts.
+    env["CONAN_NON_INTERACTIVE"] = "1"
+
+    # Print every `self.run` invocation.
+    # TODO[AH] Remove this debug output.
+    env["CONAN_PRINT_RUN_COMMANDS"] = "1"
+
+    # Disable the short paths feature on Windows.
+    # TODO[AH] Enable if needed with a hermetic short path.
+    env["CONAN_USER_HOME_SHORT"] = "None"
+
+    return env
+
+
+def run_conan(conan, *args, env=None):
+    return subprocess.check_call([conan] + list(args), env=env or {})
diff --git a/buck2/prelude/toolchains/conan/conan_generate.py b/buck2/prelude/toolchains/conan/conan_generate.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/conan_generate.py
@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import os
+import shutil
+
+import conan_common
+
+
+def conan_install(
+    conan,
+    conanfile,
+    lockfile,
+    install_folder,
+    output_folder,
+    user_home,
+    manifests,
+    install_info,
+    trace_log,
+):
+    env = conan_common.conan_env(user_home=user_home, trace_log=trace_log)
+
+    args = ["install"]
+    args.extend(["--build", "missing"])
+    args.extend(["--generator", "BucklerGenerator"])
+    args.extend(["--lockfile", lockfile])
+    args.extend(["--install-folder", install_folder])
+    args.extend(["--output-folder", output_folder])
+    args.extend(["--manifests", manifests])
+    args.extend(["--json", install_info])
+    args.append(conanfile)
+
+    conan_common.run_conan(conan, *args, env=env)
+
+
+def extract_generated(install_folder, targets_out):
+    src = os.path.join(install_folder, "conan-imports.bzl")
+    dst = targets_out
+    shutil.copy(src, dst)
+
+
+def main():
+    parser = argparse.ArgumentParser(
+        prog="conan_generate",
+        description="Generate Buck2 imports of Conan built packages.",
+    )
+    parser.add_argument(
+        "--conan",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Conan executable.",
+    )
+    parser.add_argument(
+        "--conan-init",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to the base Conan user-home.",
+    )
+    parser.add_argument(
+        "--buckler",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Buckler generator.",
+    )
+    parser.add_argument(
+        "--install-folder",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to install directory to place generator files into.",
+    )
+    parser.add_argument(
+        "--output-folder",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to the root output folder for generated and built files.",
+    )
+    parser.add_argument(
+        "--user-home",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to the Conan base directory.",
+    )
+    parser.add_argument(
+        "--manifests",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Write dependency manifests into this directory.",
+    )
+    parser.add_argument(
+        "--install-info",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Write install information JSON file to this location.",
+    )
+    parser.add_argument(
+        "--trace-file",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Write Conan trace log to this file.",
+    )
+    parser.add_argument(
+        "--conanfile",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Conanfile.",
+    )
+    parser.add_argument(
+        "--lockfile",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Conan lock-file.",
+    )
+    parser.add_argument(
+        "--targets-out",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Write the generated targets to this file.",
+    )
+    args = parser.parse_args()
+
+    conan_common.install_user_home(args.user_home, args.conan_init)
+    conan_common.install_generator(args.user_home, args.buckler)
+
+    os.mkdir(args.install_folder)
+    os.mkdir(args.output_folder)
+    os.mkdir(args.manifests)
+
+    conan_install(
+        args.conan,
+        args.conanfile,
+        args.lockfile,
+        args.install_folder,
+        args.output_folder,
+        args.user_home,
+        args.manifests,
+        args.install_info,
+        args.trace_file,
+    )
+    extract_generated(args.install_folder, args.targets_out)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/toolchains/conan/conan_init.py b/buck2/prelude/toolchains/conan/conan_init.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/conan_init.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+
+import conan_common
+
+
+def conan_profile(conan, user_home, trace_log):
+    env = conan_common.conan_env(user_home=user_home, trace_log=trace_log)
+
+    # TODO[AH] Allow users to define additional remotes.
+    remotes = [
+        ("conancenter", "https://center.conan.io"),
+    ]
+
+    for name, url in remotes:
+        conan_common.run_conan(conan, "remote", "add", "-f", name, url, env=env)
+
+
+def main():
+    parser = argparse.ArgumentParser(
+        prog="conan_init", description="Initialise a Conan home directory."
+    )
+    parser.add_argument(
+        "--conan",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Conan executable.",
+    )
+    parser.add_argument(
+        "--user-home",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to the Conan base directory.",
+    )
+    parser.add_argument(
+        "--trace-file",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Write Conan trace log to this file.",
+    )
+    args = parser.parse_args()
+
+    conan_profile(args.conan, args.user_home, args.trace_file)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/toolchains/conan/conan_lock.py b/buck2/prelude/toolchains/conan/conan_lock.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/conan_lock.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+
+import conan_common
+
+
+def conan_lock(conan, profile, conanfile, lockfile_out, lockfile, user_home, trace_log):
+    env = conan_common.conan_env(user_home=user_home, trace_log=trace_log)
+
+    args = ["lock", "create"]
+    args.extend(["--profile", profile])
+    args.extend(["--build", "missing"])
+    if lockfile:
+        args.extend(["--lockfile", lockfile])
+    args.extend(["--lockfile-out", lockfile_out])
+    args.append(conanfile)
+
+    conan_common.run_conan(conan, *args, env=env)
+
+
+def main():
+    parser = argparse.ArgumentParser(
+        prog="conan_lock", description="Generate a Conan lock-file."
+    )
+    parser.add_argument(
+        "--conan",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Conan executable.",
+    )
+    parser.add_argument(
+        "--conan-init",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to the base Conan user-home.",
+    )
+    parser.add_argument(
+        "--profile",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Conan profile.",
+    )
+    parser.add_argument(
+        "--user-home",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to the Conan base directory.",
+    )
+    parser.add_argument(
+        "--trace-file",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Write Conan trace log to this file.",
+    )
+    parser.add_argument(
+        "--conanfile",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Conanfile.",
+    )
+    parser.add_argument(
+        "--lockfile-out",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the lock-file to generate.",
+    )
+    parser.add_argument(
+        "--lockfile",
+        metavar="FILE",
+        type=str,
+        required=False,
+        help="Path to an existing Conan lock-file to base resolution on.",
+    )
+    args = parser.parse_args()
+
+    conan_common.install_user_home(args.user_home, args.conan_init)
+
+    conan_lock(
+        args.conan,
+        args.profile,
+        args.conanfile,
+        args.lockfile_out,
+        args.lockfile,
+        args.user_home,
+        args.trace_file,
+    )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/toolchains/conan/conan_package.py b/buck2/prelude/toolchains/conan/conan_package.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/conan_package.py
@@ -0,0 +1,243 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+import os
+
+import conan_common
+
+
+def conan_install(
+    conan,
+    reference,
+    lockfile,
+    options,
+    install_folder,
+    output_folder,
+    user_home,
+    manifests,
+    install_info,
+    trace_log,
+):
+    env = conan_common.conan_env(user_home=user_home, trace_log=trace_log)
+
+    args = ["install"]
+    args.extend(["--build", "missing"])
+    args.extend(["--lockfile", lockfile])
+    args.extend(["--install-folder", install_folder])
+    args.extend(["--output-folder", output_folder])
+    args.extend(["--manifests", manifests])
+    args.extend(["--json", install_info])
+    args.append(reference.split("#")[0] + "@")
+
+    conan_common.run_conan(conan, *args, env=env)
+
+
+def verify_build_and_cached_deps(install_info, package, deps):
+    """Verify that the package was built and dependencies were cached."""
+    with open(install_info, "r") as f:
+        info = json.load(f)
+    package_parsed = conan_common.parse_reference(package)
+    deps_parsed = {conan_common.parse_reference(dep) for dep in deps}
+    for installed in info["installed"]:
+        recipe_id = installed["recipe"]["id"]
+        ref = conan_common.parse_reference(recipe_id)
+        is_package = ref == package_parsed
+        is_dep = ref in deps_parsed
+
+        if not is_package and not is_dep:
+            raise RuntimeError(
+                "Unexpected installed package found: {}".format(recipe_id)
+            )
+
+        recipe_downloaded = installed["recipe"]["downloaded"]
+        if is_package and not recipe_downloaded:
+            raise RuntimeError("Cached package to build detected: {}".format(recipe_id))
+        elif is_dep and recipe_downloaded:
+            raise RuntimeError("Downloaded dependency detected: {}".format(recipe_id))
+
+        for package in installed["packages"]:
+            package_id = package["id"]
+            package_downloaded = package["downloaded"]
+            package_built = package["built"]
+            if is_package and not (package_downloaded or package_built):
+                raise RuntimeError(
+                    "Cached package to build detected: {}-{}".format(
+                        recipe_id, package_id
+                    )
+                )
+            elif is_dep and (recipe_downloaded or package_built):
+                raise RuntimeError(
+                    "Downloaded or built dependency detected: {}-{}".format(
+                        recipe_id, package_id
+                    )
+                )
+
+
+def main():
+    parser = argparse.ArgumentParser(
+        prog="conan_package", description="Build a Conan package."
+    )
+    parser.add_argument(
+        "--conan",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Conan executable.",
+    )
+    parser.add_argument(
+        "--conan-init",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to the base Conan user-home.",
+    )
+    parser.add_argument(
+        "--lockfile",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Conan lockfile.",
+    )
+    parser.add_argument(
+        "--reference",
+        metavar="STRING",
+        type=str,
+        required=True,
+        help="Reference of the Conan package to build.",
+    )
+    parser.add_argument(
+        "--package-id",
+        metavar="STRING",
+        type=str,
+        required=True,
+        help="Package ID of the Conan package to build.",
+    )
+    parser.add_argument(
+        "--option",
+        metavar="STRING",
+        type=str,
+        required=False,
+        action="append",
+        help="Conan options for the package to build.",
+    )
+    parser.add_argument(
+        "--install-folder",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to install directory to place generator files into.",
+    )
+    parser.add_argument(
+        "--output-folder",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to the root output folder for generated and built files.",
+    )
+    parser.add_argument(
+        "--user-home",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to the Conan base directory used for Conan's cache.",
+    )
+    parser.add_argument(
+        "--manifests",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Write dependency manifests into this directory.",
+    )
+    parser.add_argument(
+        "--install-info",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Write install information JSON file to this location.",
+    )
+    parser.add_argument(
+        "--trace-file",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Write Conan trace log to this file.",
+    )
+    parser.add_argument(
+        "--cache-out",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Copy the package's cache directory to this path.",
+    )
+    parser.add_argument(
+        "--package-out",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Copy the package directory to this path.",
+    )
+    parser.add_argument(
+        "--dep-reference",
+        metavar="STRING",
+        type=str,
+        required=False,
+        action="append",
+        default=[],
+        help="Conan package dependency reference. All --dep-* arguments must align.",
+    )
+    parser.add_argument(
+        "--dep-cache-out",
+        metavar="PATH",
+        type=str,
+        required=False,
+        action="append",
+        default=[],
+        help="Conan package dependency cache output directory. All --dep-* arguments must align.",
+    )
+    # TODO[AH] Remove unused `--manifests` and `--verify` flags and outputs.
+    # TODO[AH] Should we enable the `--no-imports` flag?
+    # TODO[AH] Handle packages that are build requirements and set
+    #   `--build-require` in that case.
+    args = parser.parse_args()
+
+    conan_common.install_user_home(args.user_home, args.conan_init)
+    assert len(args.dep_reference) == len(args.dep_cache_out), (
+        "Mismatching dependency arguments."
+    )
+    for ref, cache_out in zip(args.dep_reference, args.dep_cache_out):
+        conan_common.install_reference(args.user_home, ref, cache_out)
+
+    os.mkdir(args.install_folder)
+    os.mkdir(args.output_folder)
+    os.mkdir(args.manifests)
+
+    conan = args.conan
+    conan_install(
+        conan,
+        args.reference,
+        args.lockfile,
+        args.option,
+        args.install_folder,
+        args.output_folder,
+        args.user_home,
+        args.manifests,
+        args.install_info,
+        args.trace_file,
+    )
+    verify_build_and_cached_deps(args.install_info, args.reference, args.dep_reference)
+    conan_common.extract_reference(args.user_home, args.reference, args.cache_out)
+    conan_common.extract_package(
+        args.user_home, args.reference, args.package_id, args.package_out
+    )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/toolchains/conan/conan_package_extract.py b/buck2/prelude/toolchains/conan/conan_package_extract.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/conan_package_extract.py
@@ -0,0 +1,86 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import os
+import shutil
+
+
+def extract_file(package, src, dst):
+    os.makedirs(os.path.dirname(dst), exist_ok=True)
+    shutil.copyfile(os.path.join(package, src), dst)
+
+
+def extract_directory(package, src, dst):
+    os.makedirs(os.path.dirname(dst), exist_ok=True)
+    shutil.copytree(os.path.join(package, src), dst)
+
+
+def main():
+    parser = argparse.ArgumentParser(
+        prog="conan_package_extract",
+        description="Extract outputs from a Conan package.",
+    )
+    parser.add_argument(
+        "--package",
+        metavar="PATH",
+        type=str,
+        required=True,
+        help="Path to the package output directory.",
+    )
+    parser.add_argument(
+        "--file-from",
+        metavar="PATH",
+        type=str,
+        required=False,
+        action="append",
+        default=[],
+        help="File to extract. All --file-* arguments must align.",
+    )
+    parser.add_argument(
+        "--file-to",
+        metavar="PATH",
+        type=str,
+        required=False,
+        action="append",
+        default=[],
+        help="Destination to extract the file to. All --file-* arguments must align.",
+    )
+    parser.add_argument(
+        "--directory-from",
+        metavar="PATH",
+        type=str,
+        required=False,
+        action="append",
+        default=[],
+        help="Directory to extract. All --directory-* arguments must align.",
+    )
+    parser.add_argument(
+        "--directory-to",
+        metavar="PATH",
+        type=str,
+        required=False,
+        action="append",
+        default=[],
+        help="Destination to extract the directory to. All --directory-* arguments must align.",
+    )
+    args = parser.parse_args()
+
+    assert len(args.file_from) == len(args.file_to), "Mismatching file arguments."
+    assert len(args.directory_from) == len(args.directory_to), (
+        "Mismatching directory arguments."
+    )
+    for src, dst in zip(args.file_from, args.file_to):
+        extract_file(args.package, src, dst)
+    for src, dst in zip(args.directory_from, args.directory_to):
+        extract_directory(args.package, src, dst)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/toolchains/conan/conan_update.py b/buck2/prelude/toolchains/conan/conan_update.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/conan_update.py
@@ -0,0 +1,119 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import os
+import shutil
+import subprocess
+
+
+def find_root():
+    """Find the repository root using `buck2 root`."""
+    # TODO[AH] This assumes that buck2 is in PATH when executing the script via `buck2 run`.
+    #   Consider making the name/path `buck2` configurable via an environment variable.
+    return subprocess.check_output(["buck2", "root"], text=True).strip()
+
+
+def write_lockfile(lockfile, lockfile_out):
+    os.makedirs(os.path.dirname(lockfile_out), exist_ok=True)
+    shutil.copy(lockfile, lockfile_out)
+
+
+def write_targets(update_label, lock_generate, conan_generate, targets_out):
+    header = """\
+# {at}generated
+# Update using `buck2 run {update_label}`
+
+load(
+    "@prelude//toolchains/conan:defs.bzl",
+    "conan_component",
+    "conan_dep",
+    "conan_package",
+)
+""".format(at="@", update_label=update_label)
+    os.makedirs(os.path.dirname(targets_out), exist_ok=True)
+    with open(targets_out, "w") as outf:
+        outf.write(header)
+        with open(lock_generate, "r") as inf:
+            for x in inf:
+                outf.write(x)
+        with open(conan_generate, "r") as inf:
+            for x in inf:
+                outf.write(x)
+
+
+def main():
+    parser = argparse.ArgumentParser(
+        prog="conan_update",
+        description="Update the Conan lock-file and the Buck2 package imports.",
+    )
+    parser.add_argument(
+        "--update-label",
+        metavar="LABEL",
+        type=str,
+        required=True,
+        help="The label to the target to run this program.",
+    )
+    parser.add_argument(
+        "--lockfile",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the lockfile to copy to the repository.",
+    )
+    parser.add_argument(
+        "--lock-targets",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the targets file generated from the lock file.",
+    )
+    parser.add_argument(
+        "--conan-targets",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the targets file generated by Buckler.",
+    )
+    parser.add_argument(
+        "--conanfile",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Path to the Conanfile.",
+    )
+    parser.add_argument(
+        "--lockfile-out",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Name of the Conan lock-file to generate, relative to the Conanfile.",
+    )
+    parser.add_argument(
+        "--targets-out",
+        metavar="FILE",
+        type=str,
+        required=True,
+        help="Name of the Starlark file to generate, relative to the Conanfile.",
+    )
+    args = parser.parse_args()
+
+    root = find_root()
+    conanfile = os.path.join(root, args.conanfile)
+    package = os.path.dirname(conanfile)
+
+    lockfile_out = os.path.join(package, args.lockfile_out)
+    targets_out = os.path.join(package, args.targets_out)
+
+    write_lockfile(args.lockfile, lockfile_out)
+    write_targets(args.update_label, args.lock_targets, args.conan_targets, targets_out)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/toolchains/conan/defs.bzl b/buck2/prelude/toolchains/conan/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/defs.bzl
@@ -0,0 +1,826 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Conan C/C++ Package Manager Toolchain.
+
+Provides a toolchain and rules to use the [Conan package manager][conan] to
+manage and install third-party C/C++ dependencies. Only works with Conan 1.61.1
+(not Conan 2).
+
+[conan]: https://docs.conan.io/en/latest/introduction.html
+
+## Usage
+
+### Toolchain
+
+First you must define a Conan toolchain, profile, and user-home in the
+top-level package of the `toolchains` cell, i.e. `toolchains//:`. For example:
+
+```
+load("@prelude//toolchains/conan:defs.bzl", "conan_init", "conan_profile", "system_conan_toolchain")
+
+system_conan_toolchain(
+    name = "conan",
+    conan_path = "conan",
+    visibility = ["PUBLIC"],
+)
+
+conan_profile(
+    name = "conan-profile",
+    arch = "x86_64",
+    os = "Linux" ,
+    build_type = "Release",
+    compiler = "gcc",
+    compiler_version = "11.3",
+    compiler_libcxx = "libstdc++",
+)
+
+conan_init(
+    name = "conan-init",
+    profile = ":conan-profile",
+    visibility = ["PUBLIC"],
+)
+```
+
+### Packages
+
+Then you must define your project dependencies in a `conanfile.txt`. E.g.
+
+```
+[requires]
+zlib/1.2.13
+```
+
+Then you must define targets to generate and update the Conan integration
+targets. E.g.
+
+```
+load(
+    "@prelude//toolchains/conan:defs.bzl",
+    "conan_generate",
+    "conan_lock",
+    "conan_update",
+    "lock_generate",
+)
+
+conan_lock(
+    name = "lock",
+    conanfile = "conanfile.txt",
+    visibility = ["//cpp/conan/import:"],
+)
+
+lock_generate(
+    name = "lock-generate",
+    lockfile = ":lock",
+)
+
+conan_generate(
+    name = "conan-generate",
+    conanfile = "conanfile.txt",
+    lockfile = ":lock",
+)
+
+conan_update(
+    name = "update",
+    lockfile = ":lock",
+    lock_generate = ":lock-generate",
+    conan_generate = ":conan-generate",
+    conanfile = "conanfile.txt",
+    lockfile_name = "conan.lock",
+    targets_name = "conan/BUCK",
+)
+```
+
+On first use, or whenever you change a Conan dependency or the toolchain
+configuration you must regenerate the import targets. For example:
+
+```
+$ buck2 run //:update
+```
+
+Then you can depend on Conan provided packages defined in the generated file,
+configured with the `targets_name` attribute to `conan_update`. For example:
+
+```
+cxx_binary(
+    name = "main",
+    srcs = ["main.cpp"],
+    deps = ["//conan:zlib"],
+)
+```
+
+Note, only packages that are declared as direct dependencies in the
+`conanfile.txt` will have public visibility. If you wish to depend on a package
+that was a transitive dependency and is currently private, then you must first
+add it to the `conanfile.txt` and update the import targets.
+
+### Example
+
+See `examples/prelude/cpp/conan` in the Buck2 source repository for a full
+working example.
+
+## Motivation
+
+Buck2 has the ability to build C/C++ libraries natively. However, some C/C++
+projects have complex build systems and are difficult to migrate to a native
+Buck2 build. Other programming languages often have established standard
+package managers and such dependencies can be imported into a Buck2 project
+with the help of that package manager. This module provides such an integration
+for C/C++ with the help of the Conan package manager.
+
+Conan offers a relatively large [community package set][conan-center] and is
+compatible with Linux, MacOS, and Windows. It also allows for sufficient
+control to support an integration into Buck2, supports toolchain configuration
+and cross-compilation, and provides a Python extension API.
+
+[conan-center]: https://conan.io/center/
+
+## Design Goals
+
+The Buck2 integration of Conan should fulfill the following design goals:
+
+* The overall build should be controlled by Buck2:
+
+    Which packages are built at which point, which compiler toolchain and
+    configuration is used, where build artifacts are stored, and where
+    dependencies are looked up.
+
+    This enables the use of Buck2's own incremental build and caching
+    functionality. It also enables cross-platform and cross-compilation with
+    the help of Buck2's platforms and toolchains.
+
+* Conan should provide transitive dependencies:
+
+    The user should only have to declare the projects direct third-party C/C++
+    dependencies. The transitive dependency graph, package versions, package
+    downloads, and their build definitions - all these should be provided by
+    Conan.
+
+## Integration
+
+Conan provides a number of control and integration points that are relevant to
+the Buck2 integration:
+
+* Conanfile
+
+    A file `conanfile.txt` defines the direct dependencies of the project. This
+    file is provided by the user, and used by the integration and Conan.
+
+* Lockfile
+
+    Conan generates a lockfile which contains the set of transitive
+    dependencies, their precise versions, and their inter-dependencies. The
+    integration parses this file to generate build targets for individual Conan
+    packages to build in dependency order.
+
+* Command-Line
+
+    Conan's command-line interface can be used to request a build or fetch of
+    an individual package in the context of a given lockfile. Conan will build
+    only this package, provided that the package's dependencies have been built
+    before and are available in Conan's cache directory. The integration uses
+    this capability to build Conan packages in separate Buck2 build actions.
+
+* Install Location
+
+    Conan stores build artifacts and other data underneath the Conan home
+    directory, which is configurable with the `CONAN_USER_HOME` environment
+    variable. Package dependencies, newly built packages, and other resources
+    must be available under this path. The integration configures a Conan home
+    directory under Buck2's output directory and copies needed dependencies
+    into place before the build and extracts relevant build results into
+    dedicated output paths after the build.
+
+* Profiles
+
+    Conan profiles can configure the operating system and architecture to
+    target or build on, the compiler and its version, and other tools and
+    settings. The integration uses profiles to expose Buck2's own cxx toolchain
+    and other configuration to Conan.
+
+* Generators
+
+    Conan is designed to integrate with other build systems, this is a
+    necessity in the C/C++ ecosystem, as there is no single standard build
+    system used by all projects. Conan generators can access package metadata,
+    such as exposed libraries or header files, and can generate files to be
+    read by another build system to import Conan built packages. Buckler is a
+    Conan generator that creates Buck2 targets that import Conan built packages
+    and can be depended upon by native Buck2 C/C++ targets.
+
+"""
+
+# TODO[AH] May prelude modules load the top-level prelude?
+#   This module defines a macro that calls prebuilt_cxx_library,
+#   which is provided by the prelude. Alternatively, we could change the
+#   prelude to make prebuilt_cxx_library directly importable, or replace the
+#   macro by a custom rule that directly constricuts the relevant providers.
+load("@prelude//:prelude.bzl", "native")
+load("@prelude//cxx:cxx_toolchain_types.bzl", "CxxToolchainInfo")
+load("@prelude//utils:utils.bzl", "flatten")
+
+ConanInitInfo = provider(fields = ["profile", "user_home"])
+ConanLockInfo = provider(fields = ["lockfile"])
+ConanPackageInfo = provider(fields = ["reference", "package_id", "cache_out", "package_out", "cache_tset"])
+ConanProfileInfo = provider(fields = ["config", "inputs"])
+ConanToolchainInfo = provider(fields = ["conan"])
+
+def _project_conan_package_dep(value: (str, Artifact)) -> cmd_args:
+    """Generate dependency flags for conan_package.py"""
+    return cmd_args(["--dep-reference", value[0], "--dep-cache-out", value[1]])
+
+ConanPackageCacheTSet = transitive_set(
+    args_projections = {
+        "dep-flags": _project_conan_package_dep,
+    },
+)
+
+def _conan_package_extract_impl(ctx: AnalysisContext) -> list[Provider]:
+    conan_package_extract = ctx.attrs._conan_package_extract[RunInfo]
+
+    cmd = cmd_args([conan_package_extract])
+    sub_targets = {}
+
+    for filename in ctx.attrs.files:
+        output = ctx.actions.declare_output(filename, has_content_based_path = False)
+        cmd.add(["--file-from", filename, "--file-to", output.as_output()])
+        if filename in sub_targets:
+            fail("File-name collision: " + filename)
+        sub_targets[filename] = [DefaultInfo(default_outputs = [output])]
+
+    i = 0
+    for dirname in ctx.attrs.directories:
+        # Some packages provide overlapping include directories, e.g.
+        # `include`, and `include/jemalloc`. Such overlapping directories
+        # cannot both be passed to `prebuilt_cxx_library`'s `include_dirs`.
+        # This adds a counter prefix to avoid the overlap.
+        prefix = str(i) + "/"
+        i += 1
+        output = ctx.actions.declare_output(prefix + dirname, has_content_based_path = False)
+        cmd.add(["--directory-from", dirname, "--directory-to", output.as_output()])
+        if dirname in sub_targets:
+            fail("Directory-name collision: " + dirname)
+        sub_targets[dirname] = [DefaultInfo(default_outputs = [output])]
+
+    cmd.add(["--package", ctx.attrs.package[ConanPackageInfo].package_out])
+    ctx.actions.run(cmd, category = "conan_extract")
+
+    return [DefaultInfo(default_outputs = [], sub_targets = sub_targets)]
+
+_conan_package_extract = rule(
+    impl = _conan_package_extract_impl,
+    attrs = {
+        "directories": attrs.list(attrs.string(), doc = "Directories to extract from the package."),
+        "files": attrs.list(attrs.string(), doc = "Files to extract from the package."),
+        "package": attrs.dep(providers = [ConanPackageInfo], doc = "The Conan package directory to extract files from."),
+        "_conan_package_extract": attrs.dep(providers = [RunInfo], default = "prelude//toolchains/conan:conan_package_extract"),
+    },
+    doc = "Extract files and directories from Conan package directory.",
+)
+
+def conan_component(
+    name: str,
+    defines: list[str],
+    cflags: list[str],
+    cppflags: list[str],
+    include_paths: list[str],
+    libs: list[str],
+    static_libs: dict[str, list[str]],
+    shared_libs: dict[str, list[str]],
+    system_libs: list[str],
+    deps: list[str],
+    package: str,
+):
+    """Import a Conan package component.
+
+    Extracts the relevant files from the Conan package directory and exposes
+    them as a target that can be depended on by native Buck2 C/C++ targets such
+    as `cxx_library`.
+    """
+
+    extract_name = name + "_extract"
+    extract_tpl = ":" + extract_name + "[{}]"
+    extract_include_paths = [extract_tpl.format(p) for p in include_paths]
+    extract_shared_libs = {name: [extract_tpl.format(lib) for lib in libs] for name, libs in shared_libs.items()}
+    extract_static_libs = {name: [extract_tpl.format(lib) for lib in libs] for name, libs in static_libs.items()}
+
+    _conan_package_extract(
+        name = extract_name,
+        package = package,
+        files = flatten(static_libs.values() + shared_libs.values()),
+        directories = include_paths,
+    )
+
+    # [Note: Conan exported_deps] We cannot distinguish private and public
+    # dependencies based on the information exposed by Conan. We default to
+    # public dependencies, to avoid having to manually specify public
+    # dependencies when headers need to be reexported.
+
+    if len(libs) == 0:
+        native.prebuilt_cxx_library(
+            name = name,
+            exported_deps = deps,  # See [Note: Conan exported_deps]
+            header_dirs = extract_include_paths,
+            exported_preprocessor_flags = ["-D" + d for d in defines],
+            exported_lang_preprocessor_flags = {
+                "c": cflags,
+                "cxx": cppflags,
+            },
+            exported_post_linker_flags = ["-l" + lib for lib in system_libs],
+        )
+    elif len(libs) == 1:
+        lib = libs[0]
+        if lib in shared_libs:
+            shared_lib = extract_shared_libs[lib][0]
+        else:
+            shared_lib = None
+        if lib in static_libs:
+            static_lib = extract_static_libs[lib][0]
+        else:
+            static_lib = None
+        native.prebuilt_cxx_library(
+            name = name,
+            exported_deps = deps,  # See [Note: Conan exported_deps]
+            header_dirs = extract_include_paths,
+            exported_preprocessor_flags = ["-D" + d for d in defines],
+            exported_lang_preprocessor_flags = {
+                "c": cflags,
+                "cxx": cppflags,
+            },
+            exported_post_linker_flags = ["-l" + lib for lib in system_libs],
+            shared_lib = shared_lib,
+            static_lib = static_lib,
+            # TODO[AH] Can we set static_pic_lib, some libs seem to end on _pic?
+            # TODO[AH] Do we need supports_merged_linking?
+            # TODO[AH] Do we need supports_shared_library_interface?
+        )
+    else:
+        # TODO[AH] Implement prebuilt_cxx_library_group.
+        fail("Support for package components with multiple libraries is not yet implemented.")
+        # "contacts": attrs.list(attrs.string(), default = []),
+        # "deps": attrs.list(attrs.dep(), default = []),
+        # "exported_deps": attrs.list(attrs.dep(), default = []),
+        # "exported_preprocessor_flags": attrs.list(attrs.string(), default = []),
+        # "import_libs": attrs.dict(key = attrs.string(), value = attrs.source(), sorted = False, default = {}),
+        # "include_dirs": attrs.list(attrs.source(), default = []),
+        # "include_in_android_merge_map_output": attrs.bool(),
+        # "labels": attrs.list(attrs.string(), default = []),
+        # "licenses": attrs.list(attrs.source(), default = []),
+        # "provided_shared_libs": attrs.dict(key = attrs.string(), value = attrs.source(), sorted = False, default = {}),
+        # "shared_libs": attrs.dict(key = attrs.string(), value = attrs.source(), sorted = False, default = {}),
+        # "shared_link": attrs.list(attrs.string(), default = []),
+        # "static_libs": attrs.list(attrs.source(), default = []),
+        # "static_link": attrs.list(attrs.string(), default = []),
+        # "static_pic_libs": attrs.list(attrs.source(), default = []),
+        # "static_pic_link": attrs.list(attrs.string(), default = []),
+        # "supported_platforms_regex": attrs.option(attrs.regex(), default = None),
+        # "within_view": attrs.option(attrs.list(attrs.string())),
+
+def _conan_cxx_libraries_impl(ctx: AnalysisContext) -> list[Provider]:
+    default_info = DefaultInfo(
+        default_outputs = ctx.attrs.main[DefaultInfo].default_outputs + flatten([c[DefaultInfo].default_outputs for c in ctx.attrs.components.values()]),
+        sub_targets = {n: c.providers for n, c in ctx.attrs.components.items()},
+    )
+    providers = [p for p in ctx.attrs.main.providers if type(p) != "DefaultInfo"]
+    providers.append(default_info)
+    return providers
+
+_conan_cxx_libraries = rule(
+    impl = _conan_cxx_libraries_impl,
+    attrs = {
+        "components": attrs.dict(key = attrs.string(), value = attrs.dep(), doc = "The package's components."),
+        "main": attrs.dep(doc = "The main package target, depends on all components."),
+    },
+    doc = "Helper rule to bundle Conan package components into a single target.",
+)
+
+def conan_dep(name: str, components: dict[str, str], **kwargs):
+    """Bundle Conan package components into a single target.
+
+    The target itself represents the entire Conan package, including its
+    sub-components, if any. The individual components are exposed as sub-targets,
+    e.g. `:openssl` represents the entire openssl package, while `:openssl[crypto]`
+    represents only the `crypto` component.
+    """
+    native.cxx_library(
+        name = "_bundle_" + name,
+        exported_deps = components.values(),
+    )
+    _conan_cxx_libraries(name = name, main = ":_bundle_" + name, components = components, **kwargs)
+
+def _conan_generate_impl(ctx: AnalysisContext) -> list[Provider]:
+    conan_toolchain = ctx.attrs._conan_toolchain[ConanToolchainInfo]
+    conan_init = ctx.attrs._conan_init[ConanInitInfo]
+    conan_generate = ctx.attrs._conan_generate[RunInfo]
+
+    install_folder = ctx.actions.declare_output("install-folder", has_content_based_path = False)
+    output_folder = ctx.actions.declare_output("output-folder", has_content_based_path = False)
+    user_home = ctx.actions.declare_output("user-home", has_content_based_path = False)
+    manifests = ctx.actions.declare_output("manifests", has_content_based_path = False)
+    install_info = ctx.actions.declare_output("install-info.json", has_content_based_path = False)
+    trace_log = ctx.actions.declare_output("trace.log", has_content_based_path = False)
+    targets_out = ctx.actions.declare_output(ctx.label.name + ".bzl", has_content_based_path = False)
+
+    cmd = cmd_args(
+        [conan_generate]
+        + ["--conan", conan_toolchain.conan]
+        + ["--conan-init", conan_init.user_home]
+        + ["--buckler", ctx.attrs._buckler]
+        + ["--install-folder", install_folder.as_output()]
+        + ["--output-folder", output_folder.as_output()]
+        + ["--user-home", user_home.as_output()]
+        + ["--manifests", manifests.as_output()]
+        + ["--install-info", install_info.as_output()]
+        + ["--trace-file", trace_log.as_output()]
+        + ["--conanfile", ctx.attrs.conanfile]
+        + ["--lockfile", ctx.attrs.lockfile]
+        + ["--targets-out", targets_out.as_output()],
+        hidden = [
+            conan_init.profile.config,  # The profile is inlined in the lockfile.
+            conan_init.profile.inputs,
+        ],
+    )
+    ctx.actions.run(cmd, category = "conan_build")
+
+    return [
+        DefaultInfo(
+            default_outputs = [targets_out],
+            other_outputs = [
+                install_folder,
+                output_folder,
+                user_home,
+                manifests,
+                install_info,
+                trace_log,
+            ],
+        ),
+    ]
+
+conan_generate = rule(
+    impl = _conan_generate_impl,
+    attrs = {
+        "conanfile": attrs.source(doc = "The conanfile defining the project dependencies."),
+        "lockfile": attrs.source(doc = "The Conan lockfile pinning the package versions."),
+        "_buckler": attrs.source(default = "prelude//toolchains/conan:buckler"),
+        "_conan_generate": attrs.dep(providers = [RunInfo], default = "prelude//toolchains/conan:conan_generate"),
+        "_conan_init": attrs.dep(providers = [ConanInitInfo], default = "toolchains//:conan-init"),
+        "_conan_toolchain": attrs.default_only(attrs.toolchain_dep(default = "toolchains//:conan", providers = [ConanToolchainInfo])),
+    },
+    doc = "Generate Buck2 import targets for Conan packages using the Buckler generator.",
+)
+
+def _conan_init_impl(ctx: AnalysisContext) -> list[Provider]:
+    conan_toolchain = ctx.attrs._conan_toolchain[ConanToolchainInfo]
+    conan_init = ctx.attrs._conan_init[RunInfo]
+
+    user_home = ctx.actions.declare_output("user-home", has_content_based_path = False)
+    trace_log = ctx.actions.declare_output("trace.log", has_content_based_path = False)
+
+    cmd = cmd_args(
+        [conan_init] + ["--conan", conan_toolchain.conan] + ["--user-home", user_home.as_output()] + ["--trace-file", trace_log.as_output()],
+    )
+    ctx.actions.run(cmd, category = "conan_init")
+
+    return [
+        ConanInitInfo(
+            user_home = user_home,
+            profile = ctx.attrs.profile[ConanProfileInfo],
+        ),
+        DefaultInfo(
+            default_outputs = [
+                user_home,
+                trace_log,
+            ]
+        ),
+    ]
+
+conan_init = rule(
+    impl = _conan_init_impl,
+    attrs = {
+        # TODO[AH] Define separate profiles for
+        #   the target platform (`--profile:build`) and
+        #   exec platform (`--profile:host`).
+        #   This will be needed for cross-compilation.
+        "profile": attrs.dep(providers = [ConanProfileInfo], doc = "The Conan profile to use."),
+        "_conan_init": attrs.dep(providers = [RunInfo], default = "prelude//toolchains/conan:conan_init"),
+        "_conan_toolchain": attrs.default_only(attrs.toolchain_dep(default = "toolchains//:conan", providers = [ConanToolchainInfo])),
+    },
+    doc = "Generate a Conan user-home directory.",
+)
+
+def _conan_lock_impl(ctx: AnalysisContext) -> list[Provider]:
+    conan_toolchain = ctx.attrs._conan_toolchain[ConanToolchainInfo]
+    conan_init = ctx.attrs._conan_init[ConanInitInfo]
+    conan_lock = ctx.attrs._conan_lock[RunInfo]
+
+    lockfile_out = ctx.actions.declare_output("conan.lock", has_content_based_path = False)
+    user_home = ctx.actions.declare_output("user-home", has_content_based_path = False)
+    trace_log = ctx.actions.declare_output("trace.log", has_content_based_path = False)
+
+    cmd = cmd_args(
+        [conan_lock]
+        + ["--conan", conan_toolchain.conan]
+        + ["--conan-init", conan_init.user_home]
+        + ["--profile", conan_init.profile.config]
+        + ["--user-home", user_home.as_output()]
+        + ["--trace-file", trace_log.as_output()]
+        + ["--conanfile", ctx.attrs.conanfile]
+        + ["--lockfile-out", lockfile_out.as_output()]
+        + (["--lockfile", ctx.attrs.lockfile] if ctx.attrs.lockfile else []),
+        hidden = conan_init.profile.inputs,
+    )
+    ctx.actions.run(cmd, category = "conan_lock")
+
+    return [
+        ConanLockInfo(
+            lockfile = lockfile_out,
+        ),
+        DefaultInfo(
+            default_outputs = [lockfile_out],
+            other_outputs = [user_home, trace_log],
+        ),
+    ]
+
+conan_lock = rule(
+    impl = _conan_lock_impl,
+    attrs = {
+        "conanfile": attrs.source(doc = "The conanfile defining the project dependencies."),
+        "lockfile": attrs.option(attrs.source(doc = "A pre-existing lockfile to base the dependency resolution on."), default = None),
+        "_conan_init": attrs.dep(providers = [ConanInitInfo], default = "toolchains//:conan-init"),
+        "_conan_lock": attrs.dep(providers = [RunInfo], default = "prelude//toolchains/conan:conan_lock"),
+        "_conan_toolchain": attrs.default_only(attrs.toolchain_dep(default = "toolchains//:conan", providers = [ConanToolchainInfo])),
+    },
+    doc = "Generate a Conan lock-file.",
+)
+
+def _conan_package_impl(ctx: AnalysisContext) -> list[Provider]:
+    conan_toolchain = ctx.attrs._conan_toolchain[ConanToolchainInfo]
+    conan_init = ctx.attrs._conan_init[ConanInitInfo]
+    conan_package = ctx.attrs._conan_package[RunInfo]
+
+    install_folder = ctx.actions.declare_output("install-folder", has_content_based_path = False)
+    output_folder = ctx.actions.declare_output("output-folder", has_content_based_path = False)
+    user_home = ctx.actions.declare_output("user-home", has_content_based_path = False)
+    manifests = ctx.actions.declare_output("manifests", has_content_based_path = False)
+    install_info = ctx.actions.declare_output("install-info.json", has_content_based_path = False)
+    trace_log = ctx.actions.declare_output("trace.log", has_content_based_path = False)
+    cache_out = ctx.actions.declare_output("cache-out", has_content_based_path = False)
+    package_out = ctx.actions.declare_output("package", has_content_based_path = False)
+
+    cmd = cmd_args(
+        [conan_package]
+        + ["--conan", conan_toolchain.conan]
+        + ["--conan-init", conan_init.user_home]
+        + ["--lockfile", ctx.attrs.lockfile]
+        + ["--reference", ctx.attrs.reference]
+        + ["--package-id", ctx.attrs.package_id]
+        + ["--install-folder", install_folder.as_output()]
+        + ["--output-folder", output_folder.as_output()]
+        + ["--user-home", user_home.as_output()]
+        + ["--manifests", manifests.as_output()]
+        + ["--install-info", install_info.as_output()]
+        + ["--trace-file", trace_log.as_output()]
+        + ["--cache-out", cache_out.as_output()]
+        + ["--package-out", package_out.as_output()],
+        hidden = [
+            conan_init.profile.config,  # The profile is inlined in the lockfile.
+            conan_init.profile.inputs,
+        ],
+    )
+
+    # TODO[AH] Do we need to separate deps and build_deps?
+    #   This may become necessary for cross-compilation support.
+    deps = ctx.actions.tset(
+        ConanPackageCacheTSet,
+        children = [dep[ConanPackageInfo].cache_tset for dep in ctx.attrs.deps + ctx.attrs.build_deps],
+    )
+    cmd.add(deps.project_as_args("dep-flags"))
+
+    ctx.actions.run(cmd, category = "conan_build")
+
+    return [
+        ConanPackageInfo(
+            reference = ctx.attrs.reference,
+            package_id = ctx.attrs.package_id,
+            cache_out = cache_out,
+            package_out = package_out,
+            cache_tset = ctx.actions.tset(ConanPackageCacheTSet, value = (ctx.attrs.reference, cache_out), children = [deps]),
+        ),
+        DefaultInfo(
+            default_outputs = [package_out],
+            other_outputs = [
+                install_folder,
+                output_folder,
+                user_home,
+                manifests,
+                install_info,
+                trace_log,
+                cache_out,
+            ],
+        ),
+    ]
+
+conan_package = rule(
+    impl = _conan_package_impl,
+    attrs = {
+        "build_deps": attrs.list(attrs.dep(providers = [ConanPackageInfo], doc = "Conan build dependencies.")),
+        "deps": attrs.list(attrs.dep(providers = [ConanPackageInfo], doc = "Conan package dependencies.")),
+        "lockfile": attrs.source(doc = "The Conan lockfile defining the package and its dependencies."),
+        "package_id": attrs.string(doc = "The Conan package-id."),
+        "reference": attrs.string(doc = "The Conan package reference <name>/<version>#<revision>."),
+        "_conan_init": attrs.dep(providers = [ConanInitInfo], default = "toolchains//:conan-init"),
+        "_conan_package": attrs.dep(providers = [RunInfo], default = "prelude//toolchains/conan:conan_package"),
+        "_conan_toolchain": attrs.default_only(attrs.toolchain_dep(default = "toolchains//:conan", providers = [ConanToolchainInfo])),
+    },
+    doc = "Build a single Conan package.",
+)
+
+def _profile_env_var(name, value) -> cmd_args:
+    # TODO[AH] Do we need `quote = "shell"` here?
+    #   Setting it causes Buck2 to escape the `$PROFILE_DIR` prefix set in the
+    #   very end which causes failures in Conan package builds.
+    return cmd_args([name, cmd_args(value, delimiter = " ")], delimiter = "=")
+
+def _make_wrapper_script(ctx, name, tool):
+    wrapper = ctx.actions.declare_output(name, has_content_based_path = False)
+    return ctx.actions.write(
+        wrapper,
+        cmd_args([
+            "#!/bin/sh",
+            '_SCRIPTDIR=`dirname "$0"`',
+            cmd_args(
+                "exec",
+                tool,
+                '"$@"',
+                delimiter = " ",
+                relative_to = (wrapper, 1),
+                absolute_prefix = '"$_SCRIPTDIR"/',
+            ),
+        ]),
+        allow_args = True,
+        is_executable = True,
+    )
+
+def _profile_env_tool(ctx, name, tool):
+    """Create a wrapper script and assign it to the profile variable.
+
+    Conan configures the build tools it invokes through environment variables.
+    Some build tools don't accept full command-lines in the environment
+    variables configuring the compiler. E.g. CMake expects `CC` to contain the
+    compiler alone, not a command-line such as `zig cc`. This first creates a
+    wrapper script around the provided tool to avoid build failures with tools
+    that configured as full command lines.
+    """
+    wrapper, inputs = _make_wrapper_script(ctx, name, tool)
+    return cmd_args(_profile_env_var(name, wrapper), hidden = [tool, inputs])
+
+def _conan_profile_impl(ctx: AnalysisContext) -> list[Provider]:
+    cxx = ctx.attrs._cxx_toolchain[CxxToolchainInfo]
+
+    content = []
+
+    content.append("[settings]")
+    content.append(cmd_args(ctx.attrs.arch, format = "arch={}"))
+    content.append(cmd_args(ctx.attrs.os, format = "os={}"))
+    content.append(cmd_args(ctx.attrs.build_type, format = "build_type={}"))
+
+    # TODO[AH] Auto-generate the compiler setting based on the toolchain.
+    #   Needs a translation of the supported C++ compiler types to compiler setting.
+    content.append(cmd_args(ctx.attrs.compiler, format = "compiler={}"))
+    content.append(cmd_args(ctx.attrs.compiler_version, format = "compiler.version={}"))
+    content.append(cmd_args(ctx.attrs.compiler_libcxx, format = "compiler.libcxx={}"))
+
+    content.append("")
+    content.append("[env]")
+    content.append(_profile_env_var("CMAKE_FIND_ROOT_PATH", ""))
+
+    # TODO[AH] Define CMAKE_SYSROOT if needed.
+    # TODO[AH] Define target CHOST for cross-compilation
+    content.append(_profile_env_tool(ctx, "AR", cxx.linker_info.archiver))
+    if cxx.as_compiler_info:
+        content.append(_profile_env_tool(ctx, "AS", cxx.as_compiler_info.compiler))
+        # TODO[AH] Use asm_compiler_info for Windows
+
+    if cxx.binary_utilities_info:
+        if cxx.binary_utilities_info.nm:
+            content.append(_profile_env_tool(ctx, "NM", cxx.binary_utilities_info.nm))
+        if cxx.binary_utilities_info.ranlib:
+            content.append(_profile_env_tool(ctx, "RANLIB", cxx.binary_utilities_info.ranlib))
+        if cxx.binary_utilities_info.strip:
+            content.append(_profile_env_tool(ctx, "STRIP", cxx.binary_utilities_info.strip))
+    if cxx.c_compiler_info:
+        content.append(_profile_env_tool(ctx, "CC", cxx.c_compiler_info.compiler))
+        content.append(_profile_env_var("CFLAGS", cxx.c_compiler_info.compiler_flags))
+    if cxx.cxx_compiler_info:
+        content.append(_profile_env_tool(ctx, "CXX", cxx.cxx_compiler_info.compiler))
+        content.append(_profile_env_var("CXXFLAGS", cxx.cxx_compiler_info.compiler_flags))
+
+    output = ctx.actions.declare_output(ctx.label.name, has_content_based_path = False)
+    content = cmd_args(
+        content,
+        relative_to = (output, 1),
+        absolute_prefix = "$PROFILE_DIR/",
+    )
+    _, args_inputs = ctx.actions.write(output, content, allow_args = True)
+
+    return [
+        DefaultInfo(default_outputs = [output]),
+        ConanProfileInfo(config = output, inputs = cmd_args(content, hidden = args_inputs)),
+    ]
+
+conan_profile = rule(
+    impl = _conan_profile_impl,
+    attrs = {
+        "arch": attrs.string(doc = "The target architecture"),
+        "build_type": attrs.string(doc = "The Conan build-type, e.g. Release or Debug"),
+        "compiler": attrs.string(doc = "The name of the C/C++ compiler, e.g. gcc, clang, or Visual Studio."),
+        "compiler_libcxx": attrs.string(doc = "The C++ standard library, e.g. libstdc++, or libc++"),
+        "compiler_version": attrs.string(doc = "The version of the C/C++ compiler, e.g. 12.2 for gcc, 15 for clang, or 17 for Visual Studio."),
+        "os": attrs.string(doc = "The target operating system"),
+        "_cxx_toolchain": attrs.default_only(attrs.toolchain_dep(default = "toolchains//:cxx", providers = [CxxToolchainInfo])),
+    },
+    doc = "Defines a Conan profile.",
+)
+
+def _conan_update_impl(ctx: AnalysisContext) -> list[Provider]:
+    conan_update = ctx.attrs._conan_update[RunInfo]
+
+    cmd = cmd_args(
+        [conan_update]
+        + ["--update-label", str(ctx.label.raw_target())]
+        + ["--lockfile", ctx.attrs.lockfile]
+        + ["--lock-targets", ctx.attrs.lock_generate]
+        + ["--conan-targets", ctx.attrs.conan_generate]
+        + ["--conanfile", ctx.attrs.conanfile]
+        + ["--lockfile-out", ctx.attrs.lockfile_name]
+        + ["--targets-out", ctx.attrs.targets_name],
+    )
+
+    return [
+        DefaultInfo(default_outputs = []),
+        RunInfo(args = [cmd]),
+    ]
+
+conan_update = rule(
+    impl = _conan_update_impl,
+    attrs = {
+        "conan_generate": attrs.source(doc = "The targets generated by Buckler."),
+        "conanfile": attrs.source(doc = "The Conanfile."),
+        "lock_generate": attrs.source(doc = "The targets generated from the Conan lockfile."),
+        "lockfile": attrs.source(doc = "The generated Conan lockfile."),
+        "lockfile_name": attrs.string(doc = "Generate a lockfile with this name next to the Conanfile."),
+        "targets_name": attrs.string(doc = "Generate a TARGETS file with this name next to the Conanfile."),
+        "_conan_update": attrs.dep(providers = [RunInfo], default = "prelude//toolchains/conan:conan_update"),
+    },
+    doc = "Defines a runnable target that will update the Conan lockfile and import targets.",
+)
+
+def _lock_generate_impl(ctx: AnalysisContext) -> list[Provider]:
+    lock_generate = ctx.attrs._lock_generate[RunInfo]
+
+    targets_out = ctx.actions.declare_output(ctx.label.name + ".bzl", has_content_based_path = False)
+
+    cmd = cmd_args(
+        [lock_generate]
+        + ["--lockfile", ctx.attrs.lockfile]
+        + ["--lockfile-label", str(ctx.attrs.lockfile.owner.raw_target())]
+        + ["--targets-out", targets_out.as_output()],
+    )
+    ctx.actions.run(cmd, category = "conan_generate")
+
+    return [
+        DefaultInfo(
+            default_outputs = [targets_out],
+        ),
+    ]
+
+lock_generate = rule(
+    impl = _lock_generate_impl,
+    attrs = {
+        "lockfile": attrs.source(doc = "The Conan lockfile defining the package and its dependencies."),
+        "_lock_generate": attrs.dep(providers = [RunInfo], default = "prelude//toolchains/conan:lock_generate"),
+    },
+    doc = "Generate targets to build individual Conan packages in dependency order based on a Conan lock-file.",
+)
+
+def _system_conan_toolchain_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        ConanToolchainInfo(
+            conan = RunInfo(args = [ctx.attrs.conan_path]),
+        ),
+    ]
+
+system_conan_toolchain = rule(
+    impl = _system_conan_toolchain_impl,
+    attrs = {
+        "conan_path": attrs.string(doc = "Path to the Conan executable."),
+    },
+    is_toolchain_rule = True,
+    doc = "Uses a globally installed Conan executable.",
+)
diff --git a/buck2/prelude/toolchains/conan/lock_generate.py b/buck2/prelude/toolchains/conan/lock_generate.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/conan/lock_generate.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import json
+
+import conan_common
+
+
+def parse_lockfile(lockfile):
+    """Parse Conan lockfile into a package collection."""
+    with open(lockfile) as f:
+        data = json.load(f)
+
+    assert data["version"] == "0.4", "Unsupported Conan lockfile version"
+    graph = data["graph_lock"]
+    # TODO[AH] Enable Conan revisions for reproducibility
+    # assert graph["revisions_enabled"] == True, "Enable revisions for reproducibility"
+    nodes = graph["nodes"]
+
+    pkgs = {}
+    for key, item in nodes.items():
+        if key == "0":
+            # Skip the root package, it just bundles all dependencies.
+            continue
+        ref = item["ref"]
+        name, _, _, _, _ = conan_common.parse_reference(ref)
+        package_id = item["package_id"]
+        options = item["options"]
+        requires = item.get("requires", [])
+        build_requires = item.get("build_requires", [])
+        # context = item["context"]  # TODO[AH] Do we need this?
+        pkgs[key] = {
+            "name": name,
+            "reference": ref,
+            "package_id": package_id,
+            "options": options,
+            "requires": requires,
+            "build_requires": build_requires,
+        }
+
+    return pkgs
+
+
+def generate_targets(lockfile_label, pkgs, targets_out):
+    """Write Buck2 targets for the packages to bzl_out."""
+    package_template = """\
+
+conan_package(
+    name = {name!r},
+    lockfile = {lockfile!r},
+    reference = {reference!r},
+    package_id = {package_id!r},
+    deps = {deps!r},
+    build_deps = {build_deps!r},
+)
+"""
+    with open(targets_out, "w") as f:
+        for pkg in pkgs.values():
+            name = "_package_" + pkg["name"]
+            reference = pkg["reference"]
+            package_id = pkg["package_id"]
+            deps = [":_package_" + pkgs[key]["name"] for key in pkg["requires"]]
+            build_deps = [
+                ":_package_" + pkgs[key]["name"] for key in pkg["build_requires"]
+            ]
+            f.write(
+                package_template.format(
+                    name=name,
+                    # TODO[AH] Remove that lockfile and generate a minimal one in the rule.
+                    #   Using the full lock file means that any change to the set
+                    #   of Conan packages will require a rebuild of all Conan
+                    #   packages. Generating minimal lock files with only the
+                    #   required information per package will only invalidate those
+                    #   packages that were affected by a change. Note, the lock
+                    #   file also contains the Conan profile, which defines the
+                    #   Buck2 provided C/C++ toolchain. This information would need
+                    #   to be included in a minimal lockfile.
+                    lockfile=lockfile_label,
+                    reference=reference,
+                    package_id=package_id,
+                    deps=deps,
+                    build_deps=build_deps,
+                )
+            )
+
+
+def main():
+    parser = argparse.ArgumentParser(
+        prog="lock_generate",
+        description="Generate Buck2 build targets for Conan packages.",
+    )
+    parser.add_argument(
+        "--lockfile",
+        metavar="FILE",
+        type=str,
+        required=False,
+        help="Path to the Conan lock-file.",
+    )
+    parser.add_argument(
+        "--lockfile-label",
+        metavar="LABEL",
+        type=str,
+        required=False,
+        help="Buck2 label for the Conan lock-file.",
+    )
+    parser.add_argument(
+        "--targets-out",
+        metavar="FILE",
+        type=str,
+        required=False,
+        help="Write the generated targets to this file.",
+    )
+    args = parser.parse_args()
+
+    pkgs = parse_lockfile(args.lockfile)
+    generate_targets(args.lockfile_label, pkgs, args.targets_out)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/toolchains/csharp.bzl b/buck2/prelude/toolchains/csharp.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/csharp.bzl
@@ -0,0 +1,53 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//csharp:toolchain.bzl", "CSharpToolchainInfo")
+
+def _system_csharp_toolchain_impl(ctx):
+    if not host_info().os.is_windows:
+        fail("csharp toolchain only supported on windows for now")
+
+    return [
+        DefaultInfo(),
+        CSharpToolchainInfo(
+            csc = RunInfo(args = ctx.attrs.csc),
+            framework_dirs = {
+                "net35": "C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v3.5\\Profile\\Client",
+                "net40": "C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.0",
+                "net45": "C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.5",
+                "net46": "C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.6",
+            },
+        ),
+    ]
+
+system_csharp_toolchain = rule(
+    impl = _system_csharp_toolchain_impl,
+    doc = """A C# toolchain that invokes the system C# compiler `csc.exe` using the current environment path.
+    This toolchain requires the Microsoft provided .NET Framework SDKs (3.5, 4.0, 4.5, 4.6). By default these
+    Framework SDKs should be installed at their default location, however this can be customized by changing
+    the parameters passed to `system_chsarp_toolchain`.
+
+    The `csc` and `framework_dir` attributes can be buck targets if you would like to check the C# redist bits
+    into your repo.
+
+    Usage:
+  system_csharp_toolchain(
+      name = "csharp",
+      csc = "csc.exe",
+      visibility = ["PUBLIC"],
+  )""",
+    attrs = {
+        "csc": attrs.string(default = "csc.exe", doc = "Executable name or a path to the C# compiler frequently referred to as csc.exe"),
+        "framework_dirs": attrs.dict(
+            key = attrs.string(),
+            value = attrs.one_of(attrs.source(), attrs.string()),
+            doc = "Dictionary of .NET framework assembly directories, where each key is a supported value in `framework_ver` and the value is a path to a directory containing .net assemblies such as System.dll matching the given framework version",
+        ),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/cxx.bzl b/buck2/prelude/toolchains/cxx.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/cxx.bzl
@@ -0,0 +1,306 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "BinaryUtilitiesInfo",
+    "CCompilerInfo",
+    "CvtresCompilerInfo",
+    "CxxCompilerInfo",
+    "CxxInternalTools",
+    "CxxPlatformInfo",
+    "CxxToolchainInfo",
+    "DepTrackingMode",
+    "LinkerInfo",
+    "LinkerType",
+    "PicBehavior",
+    "RcCompilerInfo",
+    "RuntimeDependencyHandling",
+    "ShlibInterfacesMode",
+)
+load("@prelude//cxx:cxx_utility.bzl", "cxx_toolchain_allow_cache_upload_args")
+load("@prelude//cxx:headers.bzl", "HeaderMode")
+load("@prelude//cxx:linker.bzl", "is_pdb_generated")
+load("@prelude//decls:common.bzl", "buck")
+load("@prelude//linking:link_info.bzl", "LinkOrdering", "LinkStyle")
+load("@prelude//linking:lto.bzl", "LtoMode")
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+
+CxxToolsInfo = provider(
+    fields = {
+        "archiver": provider_field(typing.Any, default = None),
+        "archiver_type": provider_field(typing.Any, default = None),
+        "asm_compiler": provider_field(typing.Any, default = None),
+        "asm_compiler_type": provider_field(typing.Any, default = None),
+        "compiler": provider_field(typing.Any, default = None),
+        "compiler_type": provider_field(typing.Any, default = None),
+        "cvtres_compiler": provider_field(typing.Any, default = None),
+        "cxx_compiler": provider_field(typing.Any, default = None),
+        "linker": provider_field(typing.Any, default = None),
+        "linker_type": LinkerType,
+        "rc_compiler": provider_field(typing.Any, default = None),
+    },
+)
+
+def _legacy_equivalent_cxx_tools_info_windows(ctx: AnalysisContext, default_toolchain: CxxToolsInfo) -> CxxToolsInfo:
+    return CxxToolsInfo(
+        compiler = default_toolchain.compiler if ctx.attrs.compiler == None or ctx.attrs.compiler == "cl.exe" else ctx.attrs.compiler,
+        compiler_type = default_toolchain.compiler_type if ctx.attrs.compiler_type == None else ctx.attrs.compiler_type,
+        cxx_compiler = default_toolchain.cxx_compiler if ctx.attrs.compiler == None or ctx.attrs.compiler == "cl.exe" else ctx.attrs.compiler,
+        asm_compiler = default_toolchain.asm_compiler,
+        asm_compiler_type = default_toolchain.asm_compiler_type,
+        rc_compiler = default_toolchain.rc_compiler if ctx.attrs.rc_compiler == None or ctx.attrs.rc_compiler == "rc.exe" else ctx.attrs.rc_compiler,
+        cvtres_compiler = default_toolchain.cvtres_compiler
+        if ctx.attrs.cvtres_compiler == None or ctx.attrs.cvtres_compiler == "cvtres.exe"
+        else ctx.attrs.cvtres_compiler,
+        archiver = default_toolchain.archiver if ctx.attrs.archiver == None else ctx.attrs.archiver,
+        archiver_type = default_toolchain.archiver_type,
+        linker = default_toolchain.linker if ctx.attrs.linker == None or ctx.attrs.linker == "link.exe" else ctx.attrs.linker,
+        linker_type = default_toolchain.linker_type,
+    )
+
+def _legacy_equivalent_cxx_tools_info_non_windows(ctx: AnalysisContext, default_toolchain: CxxToolsInfo) -> CxxToolsInfo:
+    return CxxToolsInfo(
+        compiler = default_toolchain.compiler if ctx.attrs.compiler == None else ctx.attrs.compiler,
+        compiler_type = default_toolchain.compiler_type if ctx.attrs.compiler_type == None else ctx.attrs.compiler_type,
+        cxx_compiler = default_toolchain.cxx_compiler if ctx.attrs.cxx_compiler == None else ctx.attrs.cxx_compiler,
+        asm_compiler = default_toolchain.asm_compiler if ctx.attrs.compiler == None else ctx.attrs.compiler,
+        asm_compiler_type = default_toolchain.asm_compiler_type if ctx.attrs.compiler_type == None else ctx.attrs.compiler_type,
+        rc_compiler = default_toolchain.rc_compiler if ctx.attrs.rc_compiler == None else ctx.attrs.rc_compiler,
+        cvtres_compiler = default_toolchain.cvtres_compiler if ctx.attrs.cvtres_compiler == None else ctx.attrs.cvtres_compiler,
+        archiver = default_toolchain.archiver if ctx.attrs.archiver == None else ctx.attrs.archiver,
+        archiver_type = default_toolchain.archiver_type,
+        linker = default_toolchain.linker if ctx.attrs.linker == None else ctx.attrs.linker,
+        linker_type = default_toolchain.linker_type,
+    )
+
+def _system_cxx_toolchain_impl(ctx: AnalysisContext):
+    """
+    A very simple toolchain that is hardcoded to the current environment.
+    """
+
+    os = ctx.attrs._target_os_type[OsLookup].os.value
+    arch_name = ctx.attrs._target_os_type[OsLookup].cpu
+    cxx_tools_info = ctx.attrs._cxx_tools_info[CxxToolsInfo]
+    cxx_tools_info = (
+        _legacy_equivalent_cxx_tools_info_windows(ctx, cxx_tools_info)
+        if os == "windows"
+        else _legacy_equivalent_cxx_tools_info_non_windows(ctx, cxx_tools_info)
+    )
+    target_name = os
+    if arch_name:
+        target_name += "-" + arch_name
+    return _cxx_toolchain_from_cxx_tools_info(ctx, cxx_tools_info, target_name)
+
+def _cxx_tools_info_toolchain_impl(ctx: AnalysisContext):
+    return _cxx_toolchain_from_cxx_tools_info(ctx, ctx.attrs.cxx_tools_info[CxxToolsInfo])
+
+def _cxx_toolchain_from_cxx_tools_info(ctx: AnalysisContext, cxx_tools_info: CxxToolsInfo, target_name = "x86_64"):
+    os = ctx.attrs._target_os_type[OsLookup].os
+    archiver_supports_argfiles = os != Os("macos")
+    # Not when the linker is given (as cabal-buck2's toolchain gives it): it
+    # is then the one to use as it is, lld or not.
+    linker_given = getattr(ctx.attrs, "linker", None) != None
+    additional_linker_flags = ["-fuse-ld=lld"] if os == Os("linux") and not linker_given and cxx_tools_info.linker != "g++" and cxx_tools_info.cxx_compiler != "g++" else []
+
+    linker_type = cxx_tools_info.linker_type
+    if os == Os("windows"):
+        binary_extension = "exe"
+        object_file_extension = "obj"
+        static_library_extension = "lib"
+        shared_library_name_default_prefix = ""
+        shared_library_name_format = "{}.dll"
+        shared_library_versioned_name_format = "{}.dll"
+        pic_behavior = PicBehavior("not_supported")
+    else:
+        binary_extension = ""
+        object_file_extension = "o"
+        static_library_extension = "a"
+        shared_library_name_default_prefix = "lib"
+        shared_library_name_format = "{}.so"
+        shared_library_versioned_name_format = "{}.so.{}"
+
+        if os == Os("macos"):
+            pic_behavior = PicBehavior("always_enabled")
+        else:
+            pic_behavior = PicBehavior("supported")
+
+    if cxx_tools_info.compiler_type == "clang":
+        llvm_link = RunInfo(args = ["llvm-link"])
+    else:
+        llvm_link = None
+
+    supports_two_phase_compilation = False
+    if hasattr(ctx.attrs, "supports_two_phase_compilation"):
+        supports_two_phase_compilation = ctx.attrs.supports_two_phase_compilation
+
+    if cxx_tools_info.compiler_type == "clang" or cxx_tools_info.compiler_type == "clang_cl" or cxx_tools_info.compiler_type == "clang_windows":
+        cpp_dep_tracking_mode = DepTrackingMode("show_headers")
+    elif cxx_tools_info.compiler_type == "windows":
+        cpp_dep_tracking_mode = DepTrackingMode("show_includes")
+    elif cxx_tools_info.compiler_type == "gcc":
+        cpp_dep_tracking_mode = DepTrackingMode("makefile")
+    else:
+        cpp_dep_tracking_mode = DepTrackingMode("none")
+
+    return [
+        DefaultInfo(),
+        CxxToolchainInfo(
+            internal_tools = ctx.attrs.internal_tools[CxxInternalTools],
+            linker_info = LinkerInfo(
+                linker = _run_info(cxx_tools_info.linker),
+                linker_flags = additional_linker_flags + ctx.attrs.link_flags,
+                post_linker_flags = ctx.attrs.post_link_flags,
+                archiver = _run_info(cxx_tools_info.archiver),
+                archiver_type = cxx_tools_info.archiver_type,
+                archiver_supports_argfiles = archiver_supports_argfiles,
+                generate_linker_maps = False,
+                lto_mode = LtoMode("none"),
+                type = linker_type,
+                link_binaries_locally = True,
+                link_libraries_locally = True,
+                archive_objects_locally = True,
+                use_archiver_flags = True,
+                static_dep_runtime_ld_flags = [],
+                static_pic_dep_runtime_ld_flags = [],
+                shared_dep_runtime_ld_flags = [],
+                independent_shlib_interface_linker_flags = [],
+                shlib_interfaces = ShlibInterfacesMode("disabled"),
+                link_style = LinkStyle(ctx.attrs.link_style),
+                link_weight = 1,
+                binary_extension = binary_extension,
+                object_file_extension = object_file_extension,
+                shared_library_name_default_prefix = shared_library_name_default_prefix,
+                shared_library_name_format = shared_library_name_format,
+                shared_library_versioned_name_format = shared_library_versioned_name_format,
+                static_library_extension = static_library_extension,
+                force_full_hybrid_if_capable = False,
+                is_pdb_generated = is_pdb_generated(linker_type, ctx.attrs.link_flags),
+                link_ordering = ctx.attrs.link_ordering,
+            ),
+            bolt_enabled = False,
+            binary_utilities_info = BinaryUtilitiesInfo(
+                nm = RunInfo(args = ["nm"]),
+                objcopy = RunInfo(args = ["objcopy"]),
+                objdump = RunInfo(args = ["objdump"]),
+                ranlib = RunInfo(args = ["ranlib"]),
+                strip = RunInfo(args = ["strip"]),
+                dwp = None,
+            ),
+            cxx_compiler_info = CxxCompilerInfo(
+                allow_cache_upload = ctx.attrs.cxx_compiler_allow_cache_upload,
+                compiler = _run_info(cxx_tools_info.cxx_compiler),
+                preprocessor_flags = [],
+                compiler_flags = ctx.attrs.cxx_flags,
+                compiler_type = cxx_tools_info.compiler_type,
+                supports_two_phase_compilation = supports_two_phase_compilation,
+                supports_content_based_paths = ctx.attrs.supports_content_based_paths,
+            ),
+            c_compiler_info = CCompilerInfo(
+                allow_cache_upload = ctx.attrs.c_compiler_allow_cache_upload,
+                compiler = _run_info(cxx_tools_info.compiler),
+                preprocessor_flags = [],
+                compiler_flags = ctx.attrs.c_flags,
+                compiler_type = cxx_tools_info.compiler_type,
+                supports_content_based_paths = ctx.attrs.supports_content_based_paths,
+            ),
+            as_compiler_info = CCompilerInfo(
+                compiler = _run_info(cxx_tools_info.compiler),
+                compiler_type = cxx_tools_info.compiler_type,
+                supports_content_based_paths = ctx.attrs.supports_content_based_paths,
+            ),
+            asm_compiler_info = CCompilerInfo(
+                compiler = _run_info(cxx_tools_info.asm_compiler),
+                compiler_type = cxx_tools_info.asm_compiler_type,
+            ),
+            cvtres_compiler_info = CvtresCompilerInfo(
+                compiler = _run_info(cxx_tools_info.cvtres_compiler),
+                preprocessor_flags = [],
+                compiler_flags = ctx.attrs.cvtres_flags,
+                compiler_type = cxx_tools_info.compiler_type,
+            ),
+            rc_compiler_info = RcCompilerInfo(
+                compiler = _run_info(cxx_tools_info.rc_compiler),
+                preprocessor_flags = [],
+                compiler_flags = ctx.attrs.rc_flags,
+                compiler_type = cxx_tools_info.compiler_type,
+            ),
+            header_mode = HeaderMode("symlink_tree_only"),
+            cpp_dep_tracking_mode = cpp_dep_tracking_mode,
+            pic_behavior = pic_behavior,
+            llvm_link = llvm_link,
+            use_dep_files = True,
+            runtime_dependency_handling = RuntimeDependencyHandling("no_symlink"),
+        ),
+        CxxPlatformInfo(name = target_name),
+    ]
+
+def _run_info(args):
+    return None if args == None else RunInfo(args = [args])
+
+system_cxx_toolchain = rule(
+    impl = _system_cxx_toolchain_impl,
+    attrs = {
+        "archiver": attrs.option(attrs.string(), default = None),
+        "c_flags": attrs.list(attrs.arg(), default = []),
+        "compiler": attrs.option(attrs.string(), default = None),
+        "compiler_type": attrs.option(attrs.string(), default = None),  # One of the supported C++ compiler types.
+        "cpp_dep_tracking_mode": attrs.string(default = "makefile"),
+        "cvtres_compiler": attrs.option(attrs.string(), default = None),
+        "cvtres_flags": attrs.list(attrs.arg(), default = []),
+        "cxx_compiler": attrs.option(attrs.string(), default = None),
+        "cxx_flags": attrs.list(attrs.arg(), default = []),
+        "internal_tools": attrs.default_only(attrs.exec_dep(providers = [CxxInternalTools], default = "prelude//cxx/tools:internal_tools")),
+        "link_flags": attrs.list(attrs.arg(), default = []),
+        "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),
+        "link_style": attrs.string(default = "shared"),
+        "linker": attrs.option(attrs.string(), default = None),
+        "post_link_flags": attrs.list(attrs.arg(), default = []),
+        "rc_compiler": attrs.option(attrs.string(), default = None),
+        "rc_flags": attrs.list(attrs.arg(), default = []),
+        "supports_content_based_paths": attrs.bool(default = False),
+        "_cxx_tools_info": attrs.exec_dep(
+            providers = [CxxToolsInfo],
+            default = "prelude//toolchains/msvc:msvc_tools" if host_info().os.is_windows else "prelude//toolchains/cxx/clang:path_clang_tools",
+        ),
+        "_target_os_type": buck.target_os_type_arg(),
+    } | cxx_toolchain_allow_cache_upload_args(),
+    is_toolchain_rule = True,
+)
+
+cxx_tools_info_toolchain = rule(
+    impl = _cxx_tools_info_toolchain_impl,
+    attrs = {
+        "c_flags": attrs.list(attrs.arg(), default = []),
+        "cpp_dep_tracking_mode": attrs.string(default = "makefile"),
+        "cvtres_flags": attrs.list(attrs.arg(), default = []),
+        "cxx_flags": attrs.list(attrs.arg(), default = []),
+        "cxx_tools_info": attrs.exec_dep(
+            providers = [CxxToolsInfo],
+            default = select({
+                "DEFAULT": "prelude//toolchains/cxx/clang:path_clang_tools",
+                "config//os:windows": "prelude//toolchains/msvc:msvc_tools",
+            }),
+        ),
+        "internal_tools": attrs.exec_dep(providers = [CxxInternalTools], default = "prelude//cxx/tools:internal_tools"),
+        "link_flags": attrs.list(attrs.arg(), default = []),
+        "link_ordering": attrs.option(attrs.enum(LinkOrdering.values()), default = None),
+        "link_style": attrs.enum(
+            LinkStyle.values(),
+            default = "shared",
+            doc = """
+            The default value of the `link_style` attribute for rules that use this toolchain.
+            """,
+        ),
+        "post_link_flags": attrs.list(attrs.arg(), default = []),
+        "rc_flags": attrs.list(attrs.arg(), default = []),
+        "supports_content_based_paths": attrs.bool(default = False),
+        "_target_os_type": buck.target_os_type_arg(),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/cxx/clang/BUCK b/buck2/prelude/toolchains/cxx/clang/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/cxx/clang/BUCK
@@ -0,0 +1,11 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load(":tools.bzl", "path_clang_tools")
+
+oncall("build_infra")
+
+source_listing()
+
+path_clang_tools(
+    name = "path_clang_tools",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/toolchains/cxx/clang/tools.bzl b/buck2/prelude/toolchains/cxx/clang/tools.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/cxx/clang/tools.bzl
@@ -0,0 +1,40 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerType")
+load("@prelude//toolchains:cxx.bzl", "CxxToolsInfo")
+
+def _path_clang_tools_impl(ctx) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        CxxToolsInfo(
+            compiler = "clang",
+            compiler_type = "clang",
+            cxx_compiler = "clang++",
+            asm_compiler = "clang",
+            asm_compiler_type = "clang",
+            rc_compiler = None,
+            cvtres_compiler = None,
+            archiver = "ar",
+            archiver_type = "gnu",
+            linker = "clang++",
+            linker_type = LinkerType(ctx.attrs.linker_type),
+        ),
+    ]
+
+path_clang_tools = rule(
+    impl = _path_clang_tools_impl,
+    attrs = {
+        "linker_type": attrs.string(
+            default = select({
+                "DEFAULT": "gnu",
+                "config//os:macos": "darwin",
+            })
+        ),
+    },
+)
diff --git a/buck2/prelude/toolchains/cxx/zig/defs.bzl b/buck2/prelude/toolchains/cxx/zig/defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/cxx/zig/defs.bzl
@@ -0,0 +1,461 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Self-contained C/C++ toolchain based on zig cc.
+
+Most C/C++ compiler toolchains will depend on a system wide installation of
+libc and other standard libraries. This means that the build outputs may vary
+from system to system and that advanced use-cases, like cross-compilation,
+require installation of special system packages.
+
+The zig cc compiler is based on clang and comes bundled with the standard
+library sources and supports on-the-fly cross-compilation, making it easier to
+define a reproducible build setup and cross-compilation use-cases.
+
+Further details on zig cc are available [here][zig-cc-announcement]. Note, at
+the time of writing this is still experimental. If this is a problem for your
+use-case then you may wish to rely on a system toolchain or define your own.
+
+The toolchain is not fully hermetic as it still relies on system tools like nm.
+It only works on Linux, and to a limited extent on MacOS.
+
+[zig-cc-announcement]: https://andrewkelley.me/post/zig-cc-powerful-drop-in-replacement-gcc-clang.html
+
+## Examples
+
+To automatically fetch a distribution suitable for the host-platform configure
+the toolchain like so:
+
+`toolchains//BUILD`
+```bzl
+load("@prelude//toolchains/cxx/zig:defs.bzl", "download_zig_distribution", "cxx_zig_toolchain")
+
+download_zig_distribution(
+    name = "zig",
+    version = "0.9.1",
+)
+
+cxx_zig_toolchain(
+    name = "cxx",
+    distribution = ":zig",
+    visibility = ["PUBLIC"],
+)
+```
+
+To define toolchains for multiple platforms and configure cross-compilation you
+can configure the toolchain like so:
+
+```bzl
+load("@prelude//toolchains/cxx/zig:defs.bzl", "download_zig_distribution", "cxx_zig_toolchain")
+
+download_zig_distribution(
+    name = "zig-x86_64-linux",
+    version = "0.9.1",
+    arch = "x86_64",
+    os = "linux",
+)
+
+download_zig_distribution(
+    name = "zig-x86_64-macos",
+    version = "0.9.1",
+    arch = "x86_64",
+    os = "macos",
+)
+
+download_zig_distribution(
+    name = "zig-x86_64-windows",
+    version = "0.9.1",
+    arch = "x86_64",
+    os = "windows",
+)
+
+alias(
+    name = "zig",
+    actual = select({
+        "@prelude//os:linux": ":zig-x86_64-linux",
+        "@prelude//os:macos": ":zig-x86_64-macos",
+        "@prelude//os:windows": ":zig-x86_64-windows",
+    }),
+)
+
+cxx_zig_toolchain(
+    name = "cxx",
+    distribution = ":zig",
+    target = select({
+        "@prelude//os:linux": "x86_64-linux-gnu",
+        "@prelude//os:macos": "x86_64-macos-gnu",
+        "@prelude//os:windows": "x86_64-windows-gnu",
+    }),
+    visibility = ["PUBLIC"],
+)
+```
+"""
+
+load(
+    "@prelude//cxx:cxx_toolchain_types.bzl",
+    "BinaryUtilitiesInfo",
+    "CCompilerInfo",
+    "CxxCompilerInfo",
+    "CxxInternalTools",
+    "LinkerInfo",
+    "LinkerType",
+    "ShlibInterfacesMode",
+    "StripFlagsInfo",
+    "cxx_toolchain_infos",
+)
+load(
+    "@prelude//cxx:headers.bzl",
+    "HeaderMode",
+)
+load(
+    "@prelude//cxx:linker.bzl",
+    "is_pdb_generated",
+)
+load(
+    "@prelude//linking:link_info.bzl",
+    "LinkStyle",
+)
+load(
+    "@prelude//os_lookup:defs.bzl",
+    "ScriptLanguage",
+)
+load(
+    "@prelude//utils:cmd_script.bzl",
+    "cmd_script",
+)
+load(
+    ":releases.bzl",
+    "releases",
+)
+
+ZigReleaseInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "version": provider_field(typing.Any, default = None),
+        "url": provider_field(typing.Any, default = None),
+        "sha256": provider_field(typing.Any, default = None),
+    },
+)
+
+def _get_zig_release(version: str, platform: str) -> ZigReleaseInfo:
+    if not version in releases:
+        fail(
+            "Unknown zig release version '{}'. Available versions: {}".format(
+                version,
+                ", ".join(releases.keys()),
+            )
+        )
+    zig_version = releases[version]
+    if not platform in zig_version:
+        fail(
+            "Unsupported platform '{}'. Supported platforms: {}".format(
+                platform,
+                ", ".join(zig_version.keys()),
+            )
+        )
+    zig_platform = zig_version[platform]
+    return ZigReleaseInfo(
+        version = zig_version.get("version", version),
+        url = zig_platform["tarball"],
+        sha256 = zig_platform["shasum"],
+    )
+
+ZigDistributionInfo = provider(
+    # @unsorted-dict-items
+    fields = {
+        "version": provider_field(typing.Any, default = None),
+        "arch": provider_field(typing.Any, default = None),
+        "os": provider_field(typing.Any, default = None),
+    },
+)
+
+def _zig_distribution_impl(ctx: AnalysisContext) -> list[Provider]:
+    dst = ctx.actions.declare_output("zig", has_content_based_path = False)
+    path_tpl = "{}/" + ctx.attrs.prefix + "/zig" + ctx.attrs.suffix
+    src = cmd_args(ctx.attrs.dist[DefaultInfo].default_outputs[0], format = path_tpl)
+    ctx.actions.run(
+        ["ln", "-sf", cmd_args(src, relative_to = (dst, 1)), dst.as_output()],
+        category = "cp_compiler",
+    )
+
+    compiler = cmd_args(
+        [dst],
+        hidden = [
+            ctx.attrs.dist[DefaultInfo].default_outputs,
+            ctx.attrs.dist[DefaultInfo].other_outputs,
+        ],
+    )
+
+    return [
+        ctx.attrs.dist[DefaultInfo],
+        RunInfo(args = compiler),
+        ZigDistributionInfo(
+            version = ctx.attrs.version,
+            arch = ctx.attrs.arch,
+            os = ctx.attrs.os,
+        ),
+    ]
+
+zig_distribution = rule(
+    impl = _zig_distribution_impl,
+    attrs = {
+        "arch": attrs.string(),
+        "dist": attrs.dep(providers = [DefaultInfo]),
+        "os": attrs.string(),
+        "prefix": attrs.string(),
+        "suffix": attrs.string(default = ""),
+        "version": attrs.string(),
+    },
+)
+
+def _http_archive_impl(ctx: AnalysisContext) -> list[Provider]:
+    url = ctx.attrs.urls[0]
+    if url.endswith(".tar.xz"):
+        ext = "tar.xz"
+        flags = ["tar", "xJf"]
+    elif url.endswith(".zip"):
+        flags = ["unzip"]
+        ext = "zip"
+    else:
+        fail("Unknown archive type in URL '{}'".format(url))
+
+    # Download archive.
+    archive = ctx.actions.declare_output("archive." + ext, has_content_based_path = False)
+    ctx.actions.download_file(archive.as_output(), url, sha256 = ctx.attrs.sha256)
+
+    # Unpack archive to output directory.
+    output = ctx.actions.declare_output(ctx.label.name, has_content_based_path = False)
+    script, _ = ctx.actions.write(
+        "unpack.sh",
+        [
+            cmd_args(output, format = "mkdir -p {}"),
+            cmd_args(output, format = "cd {}"),
+            cmd_args(flags, archive, delimiter = " ", relative_to = output),
+        ],
+        is_executable = True,
+        allow_args = True,
+        has_content_based_path = False,
+    )
+    ctx.actions.run(
+        cmd_args(["/bin/sh", script], hidden = [archive, output.as_output()]),
+        category = "http_archive",
+    )
+
+    return [DefaultInfo(default_output = output)]
+
+# TODO Switch to http_archive once that supports zip download.
+#   See https://github.com/facebook/buck2/issues/21
+_http_archive = rule(
+    impl = _http_archive_impl,
+    attrs = {
+        "sha256": attrs.string(default = ""),
+        "urls": attrs.list(attrs.string(), default = []),
+    },
+)
+
+def _host_arch() -> str:
+    arch = host_info().arch
+    if arch.is_x86_64:
+        return "x86_64"
+    elif host_info().arch.is_aarch64:
+        return "aarch64"
+    elif host_info().arch.is_arm:
+        return "armv7a"
+    elif host_info().arch.is_i386:
+        return "i386"
+    elif host_info().arch.is_i386:
+        return "i386"
+    else:
+        fail("Unsupported host architecture.")
+
+def _host_os() -> str:
+    os = host_info().os
+    if os.is_freebsd:
+        return "freebsd"
+    elif os.is_linux:
+        return "linux"
+    elif os.is_macos:
+        return "macos"
+    elif os.is_windows:
+        return "windows"
+    else:
+        fail("Unsupported host os.")
+
+def download_zig_distribution(name: str, version: str, arch: [None, str] = None, os: [None, str] = None):
+    if arch == None:
+        arch = _host_arch()
+    if os == None:
+        os = _host_os()
+    archive_name = name + "-archive"
+    release = _get_zig_release(version, "{}-{}".format(arch, os))
+    _http_archive(
+        name = archive_name,
+        urls = [release.url],
+        sha256 = release.sha256,
+    )
+    zig_distribution(
+        name = name,
+        dist = ":" + archive_name,
+        prefix = "zig-{}-{}-{}/".format(os, arch, release.version),
+        suffix = ".exe" if os == "windows" else "",
+        version = release.version,
+        arch = arch,
+        os = os,
+    )
+
+def _get_linker_type(os: str) -> LinkerType:
+    if os == "linux":
+        return LinkerType("gnu")
+    elif os == "macos" or os == "freebsd":
+        # TODO[AH] return "darwin".
+        #   The cc rules emit linker flags on MacOS that are not supported by Zig's linker.
+        #   Declaring the linker as GNU style is not entirely correct, however it works better than
+        #   declaring Darwin style at this point. See https://github.com/facebook/buck2/issues/470
+        return LinkerType("gnu")
+    elif os == "windows":
+        return LinkerType("windows")
+    else:
+        fail("Cannot determine linker type: Unknown OS '{}'".format(os))
+
+def _cxx_zig_toolchain_impl(ctx: AnalysisContext) -> list[Provider]:
+    dist = ctx.attrs.distribution[ZigDistributionInfo]
+    zig = ctx.attrs.distribution[RunInfo]
+    target = ["-target", ctx.attrs.target] if ctx.attrs.target else []
+    zig_cc = cmd_script(
+        actions = ctx.actions,
+        name = "zig_cc",
+        cmd = cmd_args(zig, "cc"),
+        language = ScriptLanguage("bat" if dist.os == "windows" else "sh"),
+    )
+    zig_cxx = cmd_script(
+        actions = ctx.actions,
+        name = "zig_cxx",
+        cmd = cmd_args(zig, "c++"),
+        language = ScriptLanguage("bat" if dist.os == "windows" else "sh"),
+    )
+    zig_ar = cmd_script(
+        actions = ctx.actions,
+        name = "zig_ar",
+        cmd = cmd_args(zig, "ar"),
+        language = ScriptLanguage("bat" if dist.os == "windows" else "sh"),
+    )
+    zig_ranlib = cmd_script(
+        actions = ctx.actions,
+        name = "zig_ranlib",
+        cmd = cmd_args(zig, "ranlib"),
+        language = ScriptLanguage("bat" if dist.os == "windows" else "sh"),
+    )
+    return [ctx.attrs.distribution[DefaultInfo]] + cxx_toolchain_infos(
+        internal_tools = ctx.attrs._cxx_internal_tools[CxxInternalTools],
+        platform_name = dist.arch,
+        c_compiler_info = CCompilerInfo(
+            compiler = RunInfo(args = cmd_args(zig_cc)),
+            compiler_type = "clang",
+            compiler_flags = cmd_args(target, ctx.attrs.c_compiler_flags),
+            # preprocessor = None,
+            # preprocessor_type = None,
+            preprocessor_flags = cmd_args(ctx.attrs.c_preprocessor_flags),
+            # dep_files_processor = None,
+        ),
+        cxx_compiler_info = CxxCompilerInfo(
+            compiler = RunInfo(args = cmd_args(zig_cxx)),
+            compiler_type = "clang",
+            compiler_flags = cmd_args(target, ctx.attrs.cxx_compiler_flags),
+            # preprocessor = None,
+            # preprocessor_type = None,
+            preprocessor_flags = cmd_args(ctx.attrs.cxx_preprocessor_flags),
+            # dep_files_processor = None,
+        ),
+        linker_info = LinkerInfo(
+            archiver = RunInfo(args = cmd_args(zig_ar)),
+            archiver_type = "gnu",
+            archiver_supports_argfiles = True,
+            # archive_contents = None,
+            archive_objects_locally = False,
+            binary_extension = "",
+            generate_linker_maps = False,
+            link_binaries_locally = False,
+            link_libraries_locally = False,
+            link_style = LinkStyle(ctx.attrs.link_style),
+            link_weight = 1,
+            # link_ordering = None,
+            linker = RunInfo(args = cmd_args(zig_cxx)),
+            linker_flags = cmd_args(target, ctx.attrs.linker_flags),
+            # lto_mode = None,  # TODO support LTO
+            object_file_extension = "o",
+            # mk_shlib_intf = None,  # not needed if shlib_interfaces = "disabled"
+            shlib_interfaces = ShlibInterfacesMode("disabled"),
+            shared_dep_runtime_ld_flags = ctx.attrs.shared_dep_runtime_ld_flags,
+            shared_library_name_default_prefix = "lib",
+            shared_library_name_format = "{}.so",
+            shared_library_versioned_name_format = "{}.so.{}",
+            static_dep_runtime_ld_flags = ctx.attrs.static_dep_runtime_ld_flags,
+            static_library_extension = "a",
+            static_pic_dep_runtime_ld_flags = ctx.attrs.static_pic_dep_runtime_ld_flags,
+            # requires_archives = None,
+            # requires_objects = None,
+            # supports_distributed_thinlto = None,
+            independent_shlib_interface_linker_flags = ctx.attrs.shared_library_interface_flags,
+            type = _get_linker_type(dist.os),
+            use_archiver_flags = True,
+            is_pdb_generated = is_pdb_generated(_get_linker_type(dist.os), ctx.attrs.linker_flags),
+        ),
+        binary_utilities_info = BinaryUtilitiesInfo(
+            dwp = None,
+            nm = RunInfo(args = ["nm"]),  # not included in the zig distribution.
+            objcopy = RunInfo(args = ["objcopy"]),  # not included in the zig distribution.
+            ranlib = RunInfo(args = cmd_args(zig_ranlib)),
+            strip = RunInfo(args = ["strip"]),  # not included in the zig distribution.
+        ),
+        header_mode = HeaderMode("symlink_tree_only"),  # header map modes require mk_hmap
+        # headers_as_raw_headers_mode = None,
+        # asm_compiler_info = None,
+        # as_compiler_info = None,
+        # hip_compiler_info = None,
+        # cuda_compiler_info = None,
+        # mk_hmap = None,
+        # use_distributed_thinlto = False,
+        # use_dep_files = False,  # requires dep_files_processor
+        strip_flags_info = StripFlagsInfo(
+            strip_debug_flags = ctx.attrs.strip_debug_flags,
+            strip_non_global_flags = ctx.attrs.strip_non_global_flags,
+            strip_all_flags = ctx.attrs.strip_all_flags,
+        ),
+        # dist_lto_tools_info: [DistLtoToolsInfo, None] = None,
+        # split_debug_mode = SplitDebugMode("none"),
+        # bolt_enabled = False,
+    )
+
+cxx_zig_toolchain = rule(
+    impl = _cxx_zig_toolchain_impl,
+    attrs = {
+        "c_compiler_flags": attrs.list(attrs.arg(), default = []),
+        "c_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+        "cxx_compiler_flags": attrs.list(attrs.arg(), default = []),
+        "cxx_preprocessor_flags": attrs.list(attrs.arg(), default = []),
+        "distribution": attrs.exec_dep(providers = [RunInfo, ZigDistributionInfo]),
+        "link_style": attrs.enum(
+            LinkStyle.values(),
+            default = "static",
+            doc = """
+            The default value of the `link_style` attribute for rules that use this toolchain.
+            """,
+        ),
+        "linker_flags": attrs.list(attrs.arg(), default = []),
+        "shared_dep_runtime_ld_flags": attrs.list(attrs.arg(), default = []),
+        "shared_library_interface_flags": attrs.list(attrs.string(), default = []),
+        "static_dep_runtime_ld_flags": attrs.list(attrs.arg(), default = []),
+        "static_pic_dep_runtime_ld_flags": attrs.list(attrs.arg(), default = []),
+        "strip_all_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "strip_debug_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "strip_non_global_flags": attrs.option(attrs.list(attrs.arg()), default = None),
+        "target": attrs.option(attrs.string(), default = None),
+        "_cxx_internal_tools": attrs.default_only(attrs.dep(providers = [CxxInternalTools], default = "prelude//cxx/tools:internal_tools")),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/cxx/zig/releases.bzl b/buck2/prelude/toolchains/cxx/zig/releases.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/cxx/zig/releases.bzl
@@ -0,0 +1,1105 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Update with
+#   python3 -c 'import json, requests; print(json.dumps(requests.get("https://ziglang.org/download/index.json").json(), indent=4))'
+releases = {
+    "0.1.1": {
+        "date": "2017-10-17",
+        "docs": "https://ziglang.org/documentation/0.1.1/",
+        "notes": "https://ziglang.org/download/0.1.1/release-notes.html",
+        "src": {
+            "shasum": "ffca0cfb263485287e19cc997b08701fcd5f24b700345bcdc3dd8074f5a104e0",
+            "size": "1659716",
+            "tarball": "https://ziglang.org/download/0.1.1/zig-0.1.1.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "6fc88bef531af7e567fe30bf60da1487b86833cbee84c7a2f3e317030aa5b660",
+            "size": "19757776",
+            "tarball": "https://ziglang.org/download/0.1.1/zig-win64-0.1.1.zip",
+        },
+    },
+    "0.10.0": {
+        "aarch64-linux": {
+            "shasum": "09ef50c8be73380799804169197820ee78760723b0430fa823f56ed42b06ea0f",
+            "size": "40387688",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-linux-aarch64-0.10.0.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "02f7a7839b6a1e127eeae22ea72c87603fb7298c58bc35822a951479d53c7557",
+            "size": "40602664",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-macos-aarch64-0.10.0.tar.xz",
+        },
+        "aarch64-windows": {
+            "shasum": "1bbda8d123d44f3ae4fa90d0da04b1e9093c3f9ddae3429a4abece1e1c0bf19a",
+            "size": "69332389",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-windows-aarch64-0.10.0.zip",
+        },
+        "armv7a-linux": {
+            "shasum": "7201b2e89cd7cc2dde95d39485fd7d5641ba67dc6a9a58c036cb4c308d2e82de",
+            "size": "50805936",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-linux-armv7a-0.10.0.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "c13dc70c4ff4c09f749adc0d473cbd3942991dd4d1bd2d860fbf257d8c1bbabf",
+            "size": "45625516",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-bootstrap-0.10.0.tar.xz",
+        },
+        "date": "2022-10-31",
+        "docs": "https://ziglang.org/documentation/0.10.0/",
+        "i386-linux": {
+            "shasum": "dac8134f1328c50269f3e50b334298ec7916cb3b0ef76927703ddd1c96fd0115",
+            "size": "48451732",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-linux-i386-0.10.0.tar.xz",
+        },
+        "notes": "https://ziglang.org/download/0.10.0/release-notes.html",
+        "riscv64-linux": {
+            "shasum": "2a126f3401a7a7efc4b454f0a85c133db1af5a9dfee117f172213b7cbd47bfba",
+            "size": "42272968",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-linux-riscv64-0.10.0.tar.xz",
+        },
+        "src": {
+            "shasum": "d8409f7aafc624770dcd050c8fa7e62578be8e6a10956bca3c86e8531c64c136",
+            "size": "14530912",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-0.10.0.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.10.0/std/",
+        "x86_64-freebsd": {
+            "shasum": "dd77afa2a8676afbf39f7d6068eda81b0723afd728642adaac43cb2106253d65",
+            "size": "44056504",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-freebsd-x86_64-0.10.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "631ec7bcb649cd6795abe40df044d2473b59b44e10be689c15632a0458ddea55",
+            "size": "44142400",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-linux-x86_64-0.10.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "3a22cb6c4749884156a94ea9b60f3a28cf4e098a69f08c18fbca81c733ebfeda",
+            "size": "45175104",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-macos-x86_64-0.10.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "a66e2ff555c6e48781de1bcb0662ef28ee4b88af3af2a577f7b1950e430897ee",
+            "size": "73181558",
+            "tarball": "https://ziglang.org/download/0.10.0/zig-windows-x86_64-0.10.0.zip",
+        },
+    },
+    "0.10.1": {
+        "aarch64-linux": {
+            "shasum": "db0761664f5f22aa5bbd7442a1617dd696c076d5717ddefcc9d8b95278f71f5d",
+            "size": "40321280",
+            "tarball": "https://ziglang.org/download/0.10.1/zig-linux-aarch64-0.10.1.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "b9b00477ec5fa1f1b89f35a7d2a58688e019910ab80a65eac2a7417162737656",
+            "size": "40517896",
+            "tarball": "https://ziglang.org/download/0.10.1/zig-macos-aarch64-0.10.1.tar.xz",
+        },
+        "aarch64-windows": {
+            "shasum": "ece93b0d77b2ab03c40db99ef7ccbc63e0b6bd658af12b97898960f621305428",
+            "size": "69417459",
+            "tarball": "https://ziglang.org/download/0.10.1/zig-windows-aarch64-0.10.1.zip",
+        },
+        "bootstrap": {
+            "shasum": "9f5781210b9be8f832553d160851635780f9bd71816065351ab29cfd8968f5e9",
+            "size": "43971816",
+            "tarball": "https://ziglang.org/download/0.10.1/zig-bootstrap-0.10.1.tar.xz",
+        },
+        "date": "2023-01-19",
+        "docs": "https://ziglang.org/documentation/0.10.1/",
+        "i386-linux": {
+            "shasum": "8c710ca5966b127b0ee3efba7310601ee57aab3dd6052a082ebc446c5efb2316",
+            "size": "48367388",
+            "tarball": "https://ziglang.org/download/0.10.1/zig-linux-i386-0.10.1.tar.xz",
+        },
+        "notes": "https://ziglang.org/download/0.10.1/release-notes.html",
+        "riscv64-linux": {
+            "shasum": "9db5b59a5112b8beb995094ba800e88b0060e9cf7cfadf4dc3e666c9010dc77b",
+            "size": "42196008",
+            "tarball": "https://ziglang.org/download/0.10.1/zig-linux-riscv64-0.10.1.tar.xz",
+        },
+        "src": {
+            "shasum": "69459bc804333df077d441ef052ffa143d53012b655a51f04cfef1414c04168c",
+            "size": "15143112",
+            "tarball": "https://ziglang.org/download/0.10.1/zig-0.10.1.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.10.1/std/",
+        "x86_64-linux": {
+            "shasum": "6699f0e7293081b42428f32c9d9c983854094bd15fee5489f12c4cf4518cc380",
+            "size": "44085596",
+            "tarball": "https://ziglang.org/download/0.10.1/zig-linux-x86_64-0.10.1.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "02483550b89d2a3070c2ed003357fd6e6a3059707b8ee3fbc0c67f83ca898437",
+            "size": "45119596",
+            "tarball": "https://ziglang.org/download/0.10.1/zig-macos-x86_64-0.10.1.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "5768004e5e274c7969c3892e891596e51c5df2b422d798865471e05049988125",
+            "size": "73259729",
+            "tarball": "https://ziglang.org/download/0.10.1/zig-windows-x86_64-0.10.1.zip",
+        },
+    },
+    "0.11.0": {
+        "aarch64-linux": {
+            "shasum": "956eb095d8ba44ac6ebd27f7c9956e47d92937c103bf754745d0a39cdaa5d4c6",
+            "size": "41492432",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-linux-aarch64-0.11.0.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "c6ebf927bb13a707d74267474a9f553274e64906fd21bf1c75a20bde8cadf7b2",
+            "size": "43855096",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-macos-aarch64-0.11.0.tar.xz",
+        },
+        "aarch64-windows": {
+            "shasum": "5d4bd13db5ecb0ddc749231e00f125c1d31087d708e9ff9b45c4f4e13e48c661",
+            "size": "73883137",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-windows-aarch64-0.11.0.zip",
+        },
+        "armv7a-linux": {
+            "shasum": "aebe8bbeca39f13f9b7304465f9aee01ab005d243836bd40f4ec808093dccc9b",
+            "size": "42240664",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-linux-armv7a-0.11.0.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "38dd9e17433c7ce5687c48fa0a757462cbfcbe75d9d5087d14ebbe00efd21fdc",
+            "size": "43227592",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-bootstrap-0.11.0.tar.xz",
+        },
+        "date": "2023-08-04",
+        "docs": "https://ziglang.org/documentation/0.11.0/",
+        "notes": "https://ziglang.org/download/0.11.0/release-notes.html",
+        "powerpc-linux": {
+            "shasum": "70a5f9668a66fb2a91a7c3488b15bcb568e1f9f44b95cd10075c138ad8c42864",
+            "size": "44539972",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-linux-powerpc-0.11.0.tar.xz",
+        },
+        "powerpc64le-linux": {
+            "shasum": "75260e87325e820a278cf9e74f130c7b3d84c0b5197afb2e3c85eff3fcedd48d",
+            "size": "44656184",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-linux-powerpc64le-0.11.0.tar.xz",
+        },
+        "riscv64-linux": {
+            "shasum": "24a478937eddb507e96d60bd4da00de9092b3f0920190eb45c4c99c946b00ed5",
+            "size": "43532324",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-linux-riscv64-0.11.0.tar.xz",
+        },
+        "src": {
+            "shasum": "72014e700e50c0d3528cef3adf80b76b26ab27730133e8202716a187a799e951",
+            "size": "15275316",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-0.11.0.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.11.0/std/",
+        "x86-linux": {
+            "shasum": "7b0dc3e0e070ae0e0d2240b1892af6a1f9faac3516cae24e57f7a0e7b04662a8",
+            "size": "49824456",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-linux-x86-0.11.0.tar.xz",
+        },
+        "x86-windows": {
+            "shasum": "e72b362897f28c671633e650aa05289f2e62b154efcca977094456c8dac3aefa",
+            "size": "81576961",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-windows-x86-0.11.0.zip",
+        },
+        "x86_64-freebsd": {
+            "shasum": "ea430327f9178377b79264a1d492868dcff056cd76d43a6fb00719203749e958",
+            "size": "46432140",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-freebsd-x86_64-0.11.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "2d00e789fec4f71790a6e7bf83ff91d564943c5ee843c5fd966efc474b423047",
+            "size": "44961892",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-linux-x86_64-0.11.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "1c1c6b9a906b42baae73656e24e108fd8444bb50b6e8fd03e9e7a3f8b5f05686",
+            "size": "47189164",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-macos-x86_64-0.11.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "142caa3b804d86b4752556c9b6b039b7517a08afa3af842645c7e2dcd125f652",
+            "size": "77216743",
+            "tarball": "https://ziglang.org/download/0.11.0/zig-windows-x86_64-0.11.0.zip",
+        },
+    },
+    "0.12.0": {
+        "aarch64-linux": {
+            "shasum": "754f1029484079b7e0ca3b913a0a2f2a6afd5a28990cb224fe8845e72f09de63",
+            "size": "41849060",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-linux-aarch64-0.12.0.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "294e224c14fd0822cfb15a35cf39aa14bd9967867999bf8bdfe3db7ddec2a27f",
+            "size": "43447724",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-macos-aarch64-0.12.0.tar.xz",
+        },
+        "aarch64-windows": {
+            "shasum": "04c6b92689241ca7a8a59b5f12d2ca2820c09d5043c3c4808b7e93e41c7bf97b",
+            "size": "72976876",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-windows-aarch64-0.12.0.zip",
+        },
+        "armv7a-linux": {
+            "shasum": "b48221f4c64416d257f0f9f77d8727dccf7de92aeabe59744ee6e70d650a97bc",
+            "size": "42638808",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-linux-armv7a-0.12.0.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "3efc643d56421fa68072af94d5512cb71c61acf1c32512f77c0b4590bff63187",
+            "size": "45527312",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-bootstrap-0.12.0.tar.xz",
+        },
+        "date": "2024-04-20",
+        "docs": "https://ziglang.org/documentation/0.12.0/",
+        "notes": "https://ziglang.org/download/0.12.0/release-notes.html",
+        "powerpc64le-linux": {
+            "shasum": "9218beecfb9250e9eff863f58f987dca7077e3258dd263c40269086127f9679b",
+            "size": "45216736",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-linux-powerpc64le-0.12.0.tar.xz",
+        },
+        "riscv64-linux": {
+            "shasum": "bb2d1a78b01595a9c00ffd2e12ab46e32f8b6798f76aec643ff78e5b4f5c5afd",
+            "size": "43917444",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-linux-riscv64-0.12.0.tar.xz",
+        },
+        "src": {
+            "shasum": "a6744ef84b6716f976dad923075b2f54dc4f785f200ae6c8ea07997bd9d9bd9a",
+            "size": "17099152",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-0.12.0.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.12.0/std/",
+        "x86-linux": {
+            "shasum": "fb752fceb88749a80d625a6efdb23bea8208962b5150d6d14c92d20efda629a5",
+            "size": "50498940",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-linux-x86-0.12.0.tar.xz",
+        },
+        "x86-windows": {
+            "shasum": "497dc9fd415cadf948872f137d6cc0870507488f79db9547b8f2adb73cda9981",
+            "size": "80950440",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-windows-x86-0.12.0.zip",
+        },
+        "x86_64-freebsd": {
+            "shasum": "bd49957d1157850b337ee1cf3c00af83585cff98e1ebc3c524a267e7422a2d7b",
+            "size": "45578364",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-freebsd-x86_64-0.12.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "c7ae866b8a76a568e2d5cfd31fe89cdb629bdd161fdd5018b29a4a0a17045cad",
+            "size": "45480516",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-linux-x86_64-0.12.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "4d411bf413e7667821324da248e8589278180dbc197f4f282b7dbb599a689311",
+            "size": "47185720",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-macos-x86_64-0.12.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "2199eb4c2000ddb1fba85ba78f1fcf9c1fb8b3e57658f6a627a8e513131893f5",
+            "size": "76442958",
+            "tarball": "https://ziglang.org/download/0.12.0/zig-windows-x86_64-0.12.0.zip",
+        },
+    },
+    "0.12.1": {
+        "aarch64-linux": {
+            "shasum": "27d4fef393e8d8b5f3b1d19f4dd43bfdb469b4ed17bbc4c2283c1b1fe650ef7f",
+            "size": "41867324",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-linux-aarch64-0.12.1.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "6587860dbbc070e1ee069e1a3d18ced83b7ba7a80bf67b2c57caf7c9ce5208b1",
+            "size": "43451512",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-macos-aarch64-0.12.1.tar.xz",
+        },
+        "aarch64-windows": {
+            "shasum": "e1286114a11be4695a6ad5cf0ba6a0e5f489bb3b029a5237de93598133f0c13a",
+            "size": "72998386",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-windows-aarch64-0.12.1.zip",
+        },
+        "armv7a-linux": {
+            "shasum": "27493c922fd1454137ed6cbe6b6bec00352838fcd32e6e74f4f9187011816157",
+            "size": "42665508",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-linux-armv7a-0.12.1.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "e533e2cb6ef60edda0ae3f2ca5c6504557db6e985e3c3a80159beb32279ed341",
+            "size": "45542004",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-bootstrap-0.12.1.tar.xz",
+        },
+        "date": "2024-06-08",
+        "docs": "https://ziglang.org/documentation/0.12.1/",
+        "powerpc64le-linux": {
+            "shasum": "462d6f10350f3c5d6fc4c9d6cfdede93d69d0103af026889a15f65c5de791d39",
+            "size": "45227716",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-linux-powerpc64le-0.12.1.tar.xz",
+        },
+        "riscv64-linux": {
+            "shasum": "463511a863acc16911cff6801de97623e6de296aab7b15dcda5f6fd078b400b5",
+            "size": "43932908",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-linux-riscv64-0.12.1.tar.xz",
+        },
+        "src": {
+            "shasum": "cca0bf5686fe1a15405bd535661811fac7663f81664d2204ea4590ce49a6e9ba",
+            "size": "17110932",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-0.12.1.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.12.1/std/",
+        "x86-linux": {
+            "shasum": "c36ac019ca0fc3167e50d17e2affd3d072a06c519761737d0639adfdf2dcfddd",
+            "size": "50555428",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-linux-x86-0.12.1.tar.xz",
+        },
+        "x86-windows": {
+            "shasum": "4f0cc9258527e7b8bcf742772b3069122086a5cd857b38a1c08002462ac81f80",
+            "size": "80979711",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-windows-x86-0.12.1.zip",
+        },
+        "x86_64-freebsd": {
+            "shasum": "30eaa28fa7bc21d01f88528d75ae4b392ae4970406675d5ac712a4937a605123",
+            "size": "45590080",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-freebsd-x86_64-0.12.1.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "8860fc9725c2d9297a63008f853e9b11e3c5a2441217f99c1e3104cc6fa4a443",
+            "size": "45512024",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-linux-x86_64-0.12.1.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "68f309c6e431d56eb42648d7fe86e8028a23464d401a467831e27c26f1a8d9c9",
+            "size": "47202232",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-macos-x86_64-0.12.1.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "52459b147c2de4d7c28f6b1a4b3d571c114e96836bf8e31c953a7d2f5e94251c",
+            "size": "76470574",
+            "tarball": "https://ziglang.org/download/0.12.1/zig-windows-x86_64-0.12.1.zip",
+        },
+    },
+    "0.13.0": {
+        "aarch64-linux": {
+            "shasum": "041ac42323837eb5624068acd8b00cd5777dac4cf91179e8dad7a7e90dd0c556",
+            "size": "43090688",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-linux-aarch64-0.13.0.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "46fae219656545dfaf4dce12fb4e8685cec5b51d721beee9389ab4194d43394c",
+            "size": "44892040",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-macos-aarch64-0.13.0.tar.xz",
+        },
+        "aarch64-windows": {
+            "shasum": "95ff88427af7ba2b4f312f45d2377ce7a033e5e3c620c8caaa396a9aba20efda",
+            "size": "75119033",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-windows-aarch64-0.13.0.zip",
+        },
+        "armv7a-linux": {
+            "shasum": "4b0550239c2cd884cc03ddeb2b9934708f4b073ad59a96fccbfe09f7e4f54233",
+            "size": "43998916",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-linux-armv7a-0.13.0.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "cd446c084b5da7bc42e8ad9b4e1c910a957f2bf3f82bcc02888102cd0827c139",
+            "size": "46440356",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-bootstrap-0.13.0.tar.xz",
+        },
+        "date": "2024-06-07",
+        "docs": "https://ziglang.org/documentation/0.13.0/",
+        "notes": "https://ziglang.org/download/0.13.0/release-notes.html",
+        "powerpc64le-linux": {
+            "shasum": "6a467622448e830e8f85d20cabed151498af2b0a62f87b8c083b2fe127e60417",
+            "size": "46574596",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-linux-powerpc64le-0.13.0.tar.xz",
+        },
+        "riscv64-linux": {
+            "shasum": "9f7f3c685894ff80f43eaf3cad1598f4844ac46f4308374237c7f912f7907bb3",
+            "size": "45540956",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-linux-riscv64-0.13.0.tar.xz",
+        },
+        "src": {
+            "shasum": "06c73596beeccb71cc073805bdb9c0e05764128f16478fa53bf17dfabc1d4318",
+            "size": "17220728",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-0.13.0.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.13.0/std/",
+        "x86-linux": {
+            "shasum": "876159cc1e15efb571e61843b39a2327f8925951d48b9a7a03048c36f72180f7",
+            "size": "52062336",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-linux-x86-0.13.0.tar.xz",
+        },
+        "x86-windows": {
+            "shasum": "eb3d533c3cf868bff7e74455dc005d18fd836c42e50b27106b31e9fec6dffc4a",
+            "size": "83274739",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-windows-x86-0.13.0.zip",
+        },
+        "x86_64-freebsd": {
+            "shasum": "adc1ffc9be56533b2f1c7191f9e435ad55db00414ff2829d951ef63d95aaad8c",
+            "size": "47177744",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-freebsd-x86_64-0.13.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "d45312e61ebcc48032b77bc4cf7fd6915c11fa16e4aad116b66c9468211230ea",
+            "size": "47082308",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-linux-x86_64-0.13.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "8b06ed1091b2269b700b3b07f8e3be3b833000841bae5aa6a09b1a8b4773effd",
+            "size": "48857012",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-macos-x86_64-0.13.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "d859994725ef9402381e557c60bb57497215682e355204d754ee3df75ee3c158",
+            "size": "79163968",
+            "tarball": "https://ziglang.org/download/0.13.0/zig-windows-x86_64-0.13.0.zip",
+        },
+    },
+    "0.14.0": {
+        "aarch64-linux": {
+            "shasum": "ab64e3ea277f6fc5f3d723dcd95d9ce1ab282c8ed0f431b4de880d30df891e4f",
+            "size": "44922728",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-linux-aarch64-0.14.0.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "b71e4b7c4b4be9953657877f7f9e6f7ee89114c716da7c070f4a238220e95d7e",
+            "size": "45902412",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-macos-aarch64-0.14.0.tar.xz",
+        },
+        "aarch64-windows": {
+            "shasum": "03e984383ebb8f85293557cfa9f48ee8698e7c400239570c9ff1aef3bffaf046",
+            "size": "78113283",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-windows-aarch64-0.14.0.zip",
+        },
+        "armv7a-linux": {
+            "shasum": "a67dbfa9bdf769228ec994f2098698c619f930883ca5ef638f50eee2d7788d10",
+            "size": "46112980",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-linux-armv7a-0.14.0.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "bf3fcb22be0b83f4791748adb567d3304779d66d7bf9b1bd557ef6c2e0232807",
+            "size": "48029040",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-bootstrap-0.14.0.tar.xz",
+        },
+        "date": "2025-03-05",
+        "docs": "https://ziglang.org/documentation/0.14.0/",
+        "loongarch64-linux": {
+            "shasum": "31a2f07df55f8f528b92d540db9aae6c0b38643c34dc1ac33a0111d855e996ae",
+            "size": "45821860",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-linux-loongarch64-0.14.0.tar.xz",
+        },
+        "notes": "https://ziglang.org/download/0.14.0/release-notes.html",
+        "powerpc64le-linux": {
+            "shasum": "3eabd60876ebc2748de8eb57b4b8cfa78861ba9bf7c6dd83f4e3e1d271d7c45e",
+            "size": "48707620",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-linux-powerpc64le-0.14.0.tar.xz",
+        },
+        "riscv64-linux": {
+            "shasum": "a2b14d3de326d3fd095548ef38bf5a67b15dadd62fbcc90836d63cc4355f8ef7",
+            "size": "48069188",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-linux-riscv64-0.14.0.tar.xz",
+        },
+        "src": {
+            "shasum": "c76638c03eb204c4432ae092f6fa07c208567e110fbd4d862d131a7332584046",
+            "size": "17772188",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-0.14.0.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.14.0/std/",
+        "x86-linux": {
+            "shasum": "55d1ba21de5109686ffa675b9cc1dd66930093c202995a637ce3e397816e4c08",
+            "size": "51621460",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-linux-x86-0.14.0.tar.xz",
+        },
+        "x86-windows": {
+            "shasum": "1a867d808cf4fa9184358395d94441390b6b24ee8d00d356ca11ea7cbfd3a4ec",
+            "size": "83970029",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-windows-x86-0.14.0.zip",
+        },
+        "x86_64-linux": {
+            "shasum": "473ec26806133cf4d1918caf1a410f8403a13d979726a9045b421b685031a982",
+            "size": "49091960",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-linux-x86_64-0.14.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "685816166f21f0b8d6fc7aa6a36e91396dcd82ca6556dfbe3e329deffc01fec3",
+            "size": "51039964",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-macos-x86_64-0.14.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "f53e5f9011ba20bbc3e0e6d0a9441b31eb227a97bac0e7d24172f1b8b27b4371",
+            "size": "82219809",
+            "tarball": "https://ziglang.org/download/0.14.0/zig-windows-x86_64-0.14.0.zip",
+        },
+    },
+    "0.2.0": {
+        "date": "2018-03-15",
+        "docs": "https://ziglang.org/documentation/0.2.0/",
+        "notes": "https://ziglang.org/download/0.2.0/release-notes.html",
+        "src": {
+            "shasum": "29c9beb172737f4d5019b88ceae829ae8bc6512fb4386cfbf895ae2b42aa6965",
+            "size": "1940832",
+            "tarball": "https://ziglang.org/download/0.2.0/zig-0.2.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "209c6fb745d42474c0a73d6f291c7ae3a38b6a1b6b641eea285a7f840cc1a890",
+            "size": "22551928",
+            "tarball": "https://ziglang.org/download/0.2.0/zig-linux-x86_64-0.2.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "4f8a2979941a1f081ec8e545cca0b72608c0db1c5a3fd377a94db40649dcd3d4",
+            "size": "21076274",
+            "tarball": "https://ziglang.org/download/0.2.0/zig-win64-0.2.0.zip",
+        },
+    },
+    "0.3.0": {
+        "date": "2018-09-28",
+        "docs": "https://ziglang.org/documentation/0.3.0/",
+        "notes": "https://ziglang.org/download/0.3.0/release-notes.html",
+        "src": {
+            "shasum": "d70af604f3a8622f3393d93abb3e056bf60351e32d121e6fa4fe03d8d41e1f5a",
+            "size": "2335592",
+            "tarball": "https://ziglang.org/download/0.3.0/zig-0.3.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "b378d0aae30cb54f28494e7bc4efbc9bfb6326f47bfb302e8b5287af777b2f3c",
+            "size": "25209304",
+            "tarball": "https://ziglang.org/download/0.3.0/zig-linux-x86_64-0.3.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "19dec1f1943ab7be26823376d466f7e456143deb34e17502778a949034dc2e7e",
+            "size": "23712696",
+            "tarball": "https://ziglang.org/download/0.3.0/zig-macos-x86_64-0.3.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "bb568c03950958f8bb3472139c3ab5ed74547c8c694ab50f404c202faf51baf4",
+            "size": "22524425",
+            "tarball": "https://ziglang.org/download/0.3.0/zig-windows-x86_64-0.3.0.zip",
+        },
+    },
+    "0.4.0": {
+        "date": "2019-04-08",
+        "docs": "https://ziglang.org/documentation/0.4.0/",
+        "notes": "https://ziglang.org/download/0.4.0/release-notes.html",
+        "src": {
+            "shasum": "fec1f3f6b359a3d942e0a7f9157b3b30cde83927627a0e1ea95c54de3c526cfc",
+            "size": "5348776",
+            "tarball": "https://ziglang.org/download/0.4.0/zig-0.4.0.tar.xz",
+        },
+        "x86_64-freebsd": {
+            "shasum": "3d557c91ac36d8262eb1733bb5f261c95944f9b635e43386e3d00a3272818c30",
+            "size": "27269672",
+            "tarball": "https://ziglang.org/download/0.4.0/zig-freebsd-x86_64-0.4.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "fb1954e2fb556a01f8079a08130e88f70084e08978ff853bb2b1986d8c39d84e",
+            "size": "32876100",
+            "tarball": "https://ziglang.org/download/0.4.0/zig-linux-x86_64-0.4.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "67c932982484d017c5111e54af9f33f15e8e05c6bc5346a55e04052159c964a8",
+            "size": "30841504",
+            "tarball": "https://ziglang.org/download/0.4.0/zig-macos-x86_64-0.4.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "fbc3dd205e064c263063f69f600bedb18e3d0aa2efa747a63ef6cafb6d73f127",
+            "size": "35800101",
+            "tarball": "https://ziglang.org/download/0.4.0/zig-windows-x86_64-0.4.0.zip",
+        },
+    },
+    "0.5.0": {
+        "date": "2019-09-30",
+        "docs": "https://ziglang.org/documentation/0.5.0/",
+        "notes": "https://ziglang.org/download/0.5.0/release-notes.html",
+        "src": {
+            "shasum": "55ae16960f152bcb9cf98b4f8570902d0e559a141abf927f0d3555b7cc838a31",
+            "size": "10956132",
+            "tarball": "https://ziglang.org/download/0.5.0/zig-0.5.0.tar.xz",
+        },
+        "x86_64-freebsd": {
+            "shasum": "9e1f4d36c3d584c0aa01f20eb4cd0a0eef3eee5af23e483b8414de55feab6ab6",
+            "size": "33650744",
+            "tarball": "https://ziglang.org/download/0.5.0/zig-freebsd-x86_64-0.5.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "43e8f8a8b8556edd373ddf9c1ef3ca6cf852d4d09fe07d5736d12fefedd2b4f7",
+            "size": "40895068",
+            "tarball": "https://ziglang.org/download/0.5.0/zig-linux-x86_64-0.5.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "28702cc05745c7c0bd450487d5f4091bf0a1ad279b35eb9a640ce3e3a15b300d",
+            "size": "37898664",
+            "tarball": "https://ziglang.org/download/0.5.0/zig-macos-x86_64-0.5.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "58141323db8d84a5af62746be5f9140bc161ee760ef33dc91a887bf9ac021976",
+            "size": "44871804",
+            "tarball": "https://ziglang.org/download/0.5.0/zig-windows-x86_64-0.5.0.zip",
+        },
+    },
+    "0.6.0": {
+        "aarch64-linux": {
+            "shasum": "e7520efd42cfa02be48c2e430d08fe1f3cbb999d21d9f0d3ffd0febb976b2f41",
+            "size": "37090044",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-linux-aarch64-0.6.0.tar.xz",
+        },
+        "armv6kz-linux": {
+            "shasum": "36b6493b3fed43eb1f0000e765798ad31a6bb7d7fd3f553ac1c3761dbc919b82",
+            "size": "39133452",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-linux-armv6kz-0.6.0.tar.xz",
+        },
+        "armv7a-linux": {
+            "shasum": "946969abe357def95ca9cbbfcebfcf2d90cf967bcd3f48ee87662e32d91d8f35",
+            "size": "39143748",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-linux-armv7a-0.6.0.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "5e0e4dc878b3dd0c1852a442b174f0732e8c07869a8fcd226b71a93b89b381ab",
+            "size": "38469948",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-bootstrap-0.6.0.tar.xz",
+        },
+        "date": "2020-04-13",
+        "docs": "https://ziglang.org/documentation/0.6.0/",
+        "i386-linux": {
+            "shasum": "a97a2f9ae21575743cdd763c1917d49400d83fc562ef64582b18bade43eb24ce",
+            "size": "44877640",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-linux-i386-0.6.0.tar.xz",
+        },
+        "i386-windows": {
+            "shasum": "3b0a02618743e92175990dc6d1a787bb95ff62c4cda016f1c14c7786f575f8ca",
+            "size": "60446431",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-windows-i386-0.6.0.zip",
+        },
+        "notes": "https://ziglang.org/download/0.6.0/release-notes.html",
+        "riscv64-linux": {
+            "shasum": "68ddee43f7503c8ae5f26a921f3602c34719a02ed2241f528c0b8b888cc14b38",
+            "size": "41993144",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-linux-riscv64-0.6.0.tar.xz",
+        },
+        "src": {
+            "shasum": "5d167dc19354282dd35dd17b38e99e1763713b9be8a4ba9e9e69284e059e7204",
+            "size": "10349552",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-0.6.0.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.6.0/std/",
+        "x86_64-freebsd": {
+            "shasum": "190ff79c1eb56805a315d7c7a51082e32f62926250c0702b36760c225e1634a3",
+            "size": "36974604",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-freebsd-x86_64-0.6.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "08fd3c757963630645441c2772362e9c2294020c44f14fce1b89f45de0dc1253",
+            "size": "44766320",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-linux-x86_64-0.6.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "17270360e87ddc49f737e760047b2fac49f1570a824a306119b1194ac4093895",
+            "size": "42573184",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-macos-x86_64-0.6.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "c3b897832523e1026e10b2d8d55d7f895185c0a27a63681f3a23219c3f1c38f4",
+            "size": "49065511",
+            "tarball": "https://ziglang.org/download/0.6.0/zig-windows-x86_64-0.6.0.zip",
+        },
+    },
+    "0.7.0": {
+        "aarch64-linux": {
+            "shasum": "f89933bac87d44be82325754ff88423020c81c7032a6fc41cfeb81e982eeab9b",
+            "size": "33096140",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-linux-aarch64-0.7.0.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "338238035734db74ea4f30e500a4893bf741d38305c10952d5e39fa05bdb057d",
+            "size": "33739424",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-macos-aarch64-0.7.0.tar.xz",
+        },
+        "armv7a-linux": {
+            "shasum": "011c267e25a96ee160505a560c441daa045359a9d50e13ab1bada9d75c95db2d",
+            "size": "35157584",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-linux-armv7a-0.7.0.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "f073beaf5c53c8c57c0d374cbfcb332ef92ad703173edba0d9e0f2ed28401b72",
+            "size": "40200436",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-bootstrap-0.7.0.tar.xz",
+        },
+        "date": "2020-11-08",
+        "docs": "https://ziglang.org/documentation/0.7.0/",
+        "i386-linux": {
+            "shasum": "4bb2072cd363bcb1cbeb4872ff5cbc1f683b02d0cc1f90c46e3ea7422ce53222",
+            "size": "38530596",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-linux-i386-0.7.0.tar.xz",
+        },
+        "i386-windows": {
+            "shasum": "b1e520aacbfbd645ff3521b3eb4d44166d9a0288b8725e4b001f8b50a425eb2e",
+            "size": "53390517",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-windows-i386-0.7.0.zip",
+        },
+        "notes": "https://ziglang.org/download/0.7.0/release-notes.html",
+        "riscv64-linux": {
+            "shasum": "40dff81faa6f232ac40abbf88b9371f3cc932b6e09c423b94387c9ea580cb7be",
+            "size": "36759992",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-linux-riscv64-0.7.0.tar.xz",
+        },
+        "src": {
+            "shasum": "0efd2cf6c3b05723db80e9cf193bc55150bba84ca41f855a90f53fc756445f83",
+            "size": "10683920",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-0.7.0.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.7.0/std/",
+        "x86_64-freebsd": {
+            "shasum": "a0c926272ee4ae720034b4a6a1dc98399d76156dd84182554740f0ca8a41fc99",
+            "size": "34798992",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-freebsd-x86_64-0.7.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "e619b1c6094c095b932767f527aee2507f847ea981513ff8a08aab0fd730e0ac",
+            "size": "37154432",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-linux-x86_64-0.7.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "94063f9a311cbbf7a2e0a12295e09437182cf950f18cb0eb30ea9893f3677f24",
+            "size": "35258328",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-macos-x86_64-0.7.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "965f56c0a36f9cda2125e3a348bc654f7f155e2804c3667d231775ec228f8553",
+            "size": "53943784",
+            "tarball": "https://ziglang.org/download/0.7.0/zig-windows-x86_64-0.7.0.zip",
+        },
+    },
+    "0.7.1": {
+        "aarch64-linux": {
+            "shasum": "48ec90eba407e4587ddef7eecef25fec7e13587eb98e3b83c5f2f5fff2a5cbe7",
+            "size": "33780552",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-linux-aarch64-0.7.1.tar.xz",
+        },
+        "armv7a-linux": {
+            "shasum": "5a0662e07b4c4968665e1f97558f8591f6facec45d2e0ff5715e661743107ceb",
+            "size": "35813504",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-linux-armv7a-0.7.1.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "040f27c1fae4b0cac0a2782aecdb691f6a2f8e89db6a6ed35024c31c304fd9b2",
+            "size": "40232612",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-bootstrap-0.7.1.tar.xz",
+        },
+        "date": "2020-12-13",
+        "docs": "https://ziglang.org/documentation/0.7.1/",
+        "i386-linux": {
+            "shasum": "4882e052e5f83690bd0334bb4fc1702b5403cb3a3d2aa63fd7d6043d8afecba3",
+            "size": "39230912",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-linux-i386-0.7.1.tar.xz",
+        },
+        "i386-windows": {
+            "shasum": "a1b9a7421e13153e07fd2e2c93ff29aad64d83105b8fcdafa633dbe689caf1c0",
+            "size": "54374983",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-windows-i386-0.7.1.zip",
+        },
+        "notes": "https://ziglang.org/download/0.7.1/release-notes.html",
+        "riscv64-linux": {
+            "shasum": "187294bfd35983348c3fe042901b42e67e7e36ab7f77a5f969d21c0051f4d21f",
+            "size": "37454812",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-linux-riscv64-0.7.1.tar.xz",
+        },
+        "src": {
+            "shasum": "2db3b944ab368d955b48743d9f7c963b8f96de1a441ba5a35e197237cc6dae44",
+            "size": "10711824",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-0.7.1.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.7.1/std/",
+        "x86_64-freebsd": {
+            "shasum": "e73c1dca35791a3183fdd5ecde0443ebbe180942efceafe651886034fb8def09",
+            "size": "39066808",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-freebsd-x86_64-0.7.1.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "18c7b9b200600f8bcde1cd8d7f1f578cbc3676241ce36d771937ce19a8159b8d",
+            "size": "37848176",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-linux-x86_64-0.7.1.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "845cb17562978af0cf67e3993f4e33330525eaf01ead9386df9105111e3bc519",
+            "size": "36211076",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-macos-x86_64-0.7.1.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "4818a8a65b4672bc52c0ae7f14d014e0eb8caf10f12c0745176820384cea296a",
+            "size": "54909997",
+            "tarball": "https://ziglang.org/download/0.7.1/zig-windows-x86_64-0.7.1.zip",
+        },
+    },
+    "0.8.0": {
+        "aarch64-linux": {
+            "shasum": "ee204ca2c2037952cf3f8b10c609373a08a291efa4af7b3c73be0f2b27720470",
+            "size": "37575428",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-linux-aarch64-0.8.0.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "b32d13f66d0e1ff740b3326d66a469ee6baddbd7211fa111c066d3bd57683111",
+            "size": "35292180",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-macos-aarch64-0.8.0.tar.xz",
+        },
+        "armv7a-linux": {
+            "shasum": "d00b8bd97b79f45d6f5da956983bafeaa082e6c2ae8c6e1c6d4faa22fa29b320",
+            "size": "38884212",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-linux-armv7a-0.8.0.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "10600bc9c01f92e343f40d6ecc0ad05d67d27c3e382bce75524c0639cd8ca178",
+            "size": "43574248",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-bootstrap-0.8.0.tar.xz",
+        },
+        "date": "2021-06-04",
+        "docs": "https://ziglang.org/documentation/0.8.0/",
+        "i386-linux": {
+            "shasum": "96e43ee6ed81c3c63401f456bd1c58ee6d42373a43cb324f5cf4974ca0998865",
+            "size": "42136032",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-linux-i386-0.8.0.tar.xz",
+        },
+        "i386-windows": {
+            "shasum": "b6ec9aa6cd6f3872fcb30d43ff411802d82008a0c4142ee49e208a09b2c1c5fe",
+            "size": "61507213",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-windows-i386-0.8.0.zip",
+        },
+        "notes": "https://ziglang.org/download/0.8.0/release-notes.html",
+        "riscv64-linux": {
+            "shasum": "75997527a78cdab64c40c43d9df39c01c4cdb557bb3992a869838371a204cfea",
+            "size": "40016268",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-linux-riscv64-0.8.0.tar.xz",
+        },
+        "src": {
+            "shasum": "03a828d00c06b2e3bb8b7ff706997fd76bf32503b08d759756155b6e8c981e77",
+            "size": "12614896",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-0.8.0.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.8.0/std/",
+        "x86_64-freebsd": {
+            "shasum": "0d3ccc436c8c0f50fd55462f72f8492d98723c7218ffc2a8a1831967d81b4bdc",
+            "size": "39125332",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-freebsd-x86_64-0.8.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "502625d3da3ae595c5f44a809a87714320b7a40e6dff4a895b5fa7df3391d01e",
+            "size": "41211184",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-linux-x86_64-0.8.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "279f9360b5cb23103f0395dc4d3d0d30626e699b1b4be55e98fd985b62bc6fbe",
+            "size": "39969312",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-macos-x86_64-0.8.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "8580fbbf3afb72e9b495c7f8aeac752a03475ae0bbcf5d787f3775c7e1f4f807",
+            "size": "61766193",
+            "tarball": "https://ziglang.org/download/0.8.0/zig-windows-x86_64-0.8.0.zip",
+        },
+    },
+    "0.8.1": {
+        "aarch64-linux": {
+            "shasum": "2166dc9f2d8df387e8b4122883bb979d739281e1ff3f3d5483fec3a23b957510",
+            "size": "37605932",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-linux-aarch64-0.8.1.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "5351297e3b8408213514b29c0a938002c5cf9f97eee28c2f32920e1227fd8423",
+            "size": "35340712",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-macos-aarch64-0.8.1.tar.xz",
+        },
+        "armv7a-linux": {
+            "shasum": "5ba58141805e2519f38cf8e715933cbf059f4f3dade92c71838cce341045de05",
+            "size": "39185876",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-linux-armv7a-0.8.1.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "fa1239247f830ecd51c42537043f5220e4d1dfefdc54356fa419616a0efb3902",
+            "size": "43613464",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-bootstrap-0.8.1.tar.xz",
+        },
+        "date": "2021-09-06",
+        "docs": "https://ziglang.org/documentation/0.8.1/",
+        "i386-linux": {
+            "shasum": "2f3e84f30492b5f1c5f97cecc0166f07a8a8d50c5f85dbb3a6ef2a4ee6f915e6",
+            "size": "44782932",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-linux-i386-0.8.1.tar.xz",
+        },
+        "i386-windows": {
+            "shasum": "099605051eb0452a947c8eab8fbbc7e43833c8376d267e94e41131c289a1c535",
+            "size": "64152358",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-windows-i386-0.8.1.zip",
+        },
+        "notes": "https://ziglang.org/download/0.8.1/release-notes.html",
+        "riscv64-linux": {
+            "shasum": "4adfaf147b025917c03367462fe5018aaa9edbc6439ef9cd0da2b074ae960554",
+            "size": "41234480",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-linux-riscv64-0.8.1.tar.xz",
+        },
+        "src": {
+            "shasum": "8c428e14a0a89cb7a15a6768424a37442292858cdb695e2eb503fa3c7bf47f1a",
+            "size": "12650228",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-0.8.1.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.8.1/std/",
+        "x86_64-freebsd": {
+            "shasum": "fc4f6478bcf3a9fce1b8ef677a91694f476dd35be6d6c9c4f44a8b76eedbe176",
+            "size": "39150924",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-freebsd-x86_64-0.8.1.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "6c032fc61b5d77a3f3cf781730fa549f8f059ffdb3b3f6ad1c2994d2b2d87983",
+            "size": "41250060",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-linux-x86_64-0.8.1.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "16b0e1defe4c1807f2e128f72863124bffdd906cefb21043c34b673bf85cd57f",
+            "size": "39946200",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-macos-x86_64-0.8.1.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "43573db14cd238f7111d6bdf37492d363f11ecd1eba802567a172f277d003926",
+            "size": "61897838",
+            "tarball": "https://ziglang.org/download/0.8.1/zig-windows-x86_64-0.8.1.zip",
+        },
+    },
+    "0.9.0": {
+        "aarch64-linux": {
+            "shasum": "1524fedfdbade2dbc9bae1ed98ad38fa7f2114c9a3e94da0d652573c75efbc5a",
+            "size": "40008396",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-linux-aarch64-0.9.0.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "3991c70594d61d09fb4b316157a7c1d87b1d4ec159e7a5ecd11169ff74cad832",
+            "size": "39013392",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-macos-aarch64-0.9.0.tar.xz",
+        },
+        "aarch64-windows": {
+            "shasum": "f9018725e3fb2e8992b17c67034726971156eb190685018a9ac8c3a9f7a22340",
+            "size": "61461921",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-windows-aarch64-0.9.0.zip",
+        },
+        "armv7a-linux": {
+            "shasum": "50225dee6e6448a63ee96383a34d9fe3bba34ae8da1a0c8619bde2cdfc1df87d",
+            "size": "41196876",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-linux-armv7a-0.9.0.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "16b0bdf0bc0a5ed1e0950e08481413d806192e06443a512347526647b2baeabc",
+            "size": "42557736",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-bootstrap-0.9.0.tar.xz",
+        },
+        "date": "2021-12-20",
+        "docs": "https://ziglang.org/documentation/0.9.0/",
+        "i386-linux": {
+            "shasum": "b0dcf688349268c883292acdd55eaa3c13d73b9146e4b990fad95b84a2ac528b",
+            "size": "47408656",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-linux-i386-0.9.0.tar.xz",
+        },
+        "i386-windows": {
+            "shasum": "bb839434afc75092015cf4c33319d31463c18512bc01dd719aedf5dcbc368466",
+            "size": "67946715",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-windows-i386-0.9.0.zip",
+        },
+        "notes": "https://ziglang.org/download/0.9.0/release-notes.html",
+        "riscv64-linux": {
+            "shasum": "85466de07504767ed37f59782672ad41bbdf43d6480fafd07f45543278b07620",
+            "size": "44171420",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-linux-riscv64-0.9.0.tar.xz",
+        },
+        "src": {
+            "shasum": "cd1be83b12f8269cc5965e59877b49fdd8fa638efb6995ac61eb4cea36a2e381",
+            "size": "13928772",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-0.9.0.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.9.0/std/",
+        "x86_64-freebsd": {
+            "shasum": "c95afe679b7cc4110dc2ecd3606c83a699718b7a958d6627f74c20886333e194",
+            "size": "41293236",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-freebsd-x86_64-0.9.0.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "5c55344a877d557fb1b28939785474eb7f4f2f327aab55293998f501f7869fa6",
+            "size": "43420796",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-linux-x86_64-0.9.0.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "c5280eeec4d6e5ea5ce5b448dc9a7c4bdd85ecfed4c1b96aa0835e48b36eccf0",
+            "size": "43764596",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-macos-x86_64-0.9.0.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "084ea2646850aaf068234b0f1a92b914ed629be47075e835f8a67d55c21d880e",
+            "size": "65045849",
+            "tarball": "https://ziglang.org/download/0.9.0/zig-windows-x86_64-0.9.0.zip",
+        },
+    },
+    "0.9.1": {
+        "aarch64-linux": {
+            "shasum": "5d99a39cded1870a3fa95d4de4ce68ac2610cca440336cfd252ffdddc2b90e66",
+            "size": "37034860",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-linux-aarch64-0.9.1.tar.xz",
+        },
+        "aarch64-macos": {
+            "shasum": "8c473082b4f0f819f1da05de2dbd0c1e891dff7d85d2c12b6ee876887d438287",
+            "size": "38995640",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-macos-aarch64-0.9.1.tar.xz",
+        },
+        "aarch64-windows": {
+            "shasum": "621bf95f54dc3ff71466c5faae67479419951d7489e40e87fd26d195825fb842",
+            "size": "61478151",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-windows-aarch64-0.9.1.zip",
+        },
+        "armv7a-linux": {
+            "shasum": "6de64456cb4757a555816611ea697f86fba7681d8da3e1863fa726a417de49be",
+            "size": "37974652",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-linux-armv7a-0.9.1.tar.xz",
+        },
+        "bootstrap": {
+            "shasum": "0a8e221c71860d8975c15662b3ed3bd863e81c4fe383455a596e5e0e490d6109",
+            "size": "42488812",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-bootstrap-0.9.1.tar.xz",
+        },
+        "date": "2022-02-14",
+        "docs": "https://ziglang.org/documentation/0.9.1/",
+        "i386-linux": {
+            "shasum": "e776844fecd2e62fc40d94718891057a1dbca1816ff6013369e9a38c874374ca",
+            "size": "44969172",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-linux-i386-0.9.1.tar.xz",
+        },
+        "i386-windows": {
+            "shasum": "74a640ed459914b96bcc572183a8db687bed0af08c30d2ea2f8eba03ae930f69",
+            "size": "67929868",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-windows-i386-0.9.1.zip",
+        },
+        "notes": "https://ziglang.org/download/0.9.1/release-notes.html",
+        "riscv64-linux": {
+            "shasum": "208dea53662c2c52777bd9e3076115d2126a4f71aed7f2ff3b8fe224dc3881aa",
+            "size": "39390868",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-linux-riscv64-0.9.1.tar.xz",
+        },
+        "src": {
+            "shasum": "38cf4e84481f5facc766ba72783e7462e08d6d29a5d47e3b75c8ee3142485210",
+            "size": "13940828",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-0.9.1.tar.xz",
+        },
+        "stdDocs": "https://ziglang.org/documentation/0.9.1/std/",
+        "x86_64-freebsd": {
+            "shasum": "4e06009bd3ede34b72757eec1b5b291b30aa0d5046dadd16ecb6b34a02411254",
+            "size": "39028848",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-freebsd-x86_64-0.9.1.tar.xz",
+        },
+        "x86_64-linux": {
+            "shasum": "be8da632c1d3273f766b69244d80669fe4f5e27798654681d77c992f17c237d7",
+            "size": "41011464",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-linux-x86_64-0.9.1.tar.xz",
+        },
+        "x86_64-macos": {
+            "shasum": "2d94984972d67292b55c1eb1c00de46580e9916575d083003546e9a01166754c",
+            "size": "43713044",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-macos-x86_64-0.9.1.tar.xz",
+        },
+        "x86_64-windows": {
+            "shasum": "443da53387d6ae8ba6bac4b3b90e9fef4ecbe545e1c5fa3a89485c36f5c0e3a2",
+            "size": "65047697",
+            "tarball": "https://ziglang.org/download/0.9.1/zig-windows-x86_64-0.9.1.zip",
+        },
+    },
+}
diff --git a/buck2/prelude/toolchains/demo.bzl b/buck2/prelude/toolchains/demo.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/demo.bzl
@@ -0,0 +1,282 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android/tools:jdk_system_image.bzl", "jdk_system_image")
+load("@prelude//tests:test_toolchain.bzl", "noop_test_toolchain")
+load("@prelude//toolchains:android.bzl", "android_sdk_tools", "system_android_aidl_toolchain", "system_android_toolchain")
+load("@prelude//toolchains:cxx.bzl", "system_cxx_toolchain")
+load("@prelude//toolchains:dex.bzl", "system_dex_toolchain", "system_noop_dex_toolchain")
+load("@prelude//toolchains:erlang.bzl", "system_erlang_toolchain")
+load("@prelude//toolchains:genrule.bzl", "system_genrule_toolchain")
+load("@prelude//toolchains:haskell.bzl", "system_haskell_toolchain")
+load(
+    "@prelude//toolchains:java.bzl",
+    "java_test_toolchain",
+    "javacd_toolchain",
+    "system_java_bootstrap_toolchain",
+    "system_java_lib",
+    "system_java_tool",
+    "system_prebuilt_jar_bootstrap_toolchain",
+)
+load("@prelude//toolchains:kotlin.bzl", "kotlincd_toolchain", "system_kotlin_bootstrap_toolchain")
+load("@prelude//toolchains:ocaml.bzl", "system_ocaml_toolchain")
+load(
+    "@prelude//toolchains:python.bzl",
+    "remote_python_toolchain",
+    "system_python_bootstrap_toolchain",
+    "system_python_wheel_toolchain",
+)
+load("@prelude//toolchains:remote_test_execution.bzl", "remote_test_execution_toolchain")
+load("@prelude//toolchains:rust.bzl", "system_rust_toolchain")
+load("@prelude//toolchains:zip_file.bzl", "zip_file_toolchain")
+load("@prelude//toolchains/go:system_go_bootstrap_toolchain.bzl", "system_go_bootstrap_toolchain")
+load("@prelude//toolchains/go:system_go_toolchain.bzl", "system_go_toolchain")
+
+def _hack_impl(ctx):
+    return ctx.attrs.actual.providers
+
+android_hack_alias = rule(
+    impl = _hack_impl,
+    attrs = {
+        "actual": attrs.toolchain_dep(),
+    },
+)
+
+def system_demo_toolchains():
+    """
+    All the default toolchains, suitable for a quick demo or early prototyping.
+    Most real projects should copy/paste the implementation to configure them.
+    """
+    android_sdk_tools(
+        name = "android_sdk_tools",
+        visibility = ["PUBLIC"],
+    )
+
+    system_android_aidl_toolchain(
+        name = "android_aidl",
+        android_sdk_tools_target = ":android_sdk_tools",
+        visibility = ["PUBLIC"],
+    )
+
+    jdk_system_image(
+        name = "jdk_system_image",
+        core_for_system_modules_jar = ":android_sdk_tools[core-for-system-modules.jar]",
+    )
+
+    system_android_toolchain(
+        name = "android",
+        android_sdk_tools_target = ":android_sdk_tools",
+        jdk_system_image = ":jdk_system_image",
+        visibility = ["PUBLIC"],
+    )
+
+    android_hack_alias(
+        name = "android-hack",
+        actual = ":cxx",
+        visibility = ["PUBLIC"],
+    )
+
+    system_cxx_toolchain(
+        name = "cxx",
+        linker = "g++",
+        visibility = ["PUBLIC"],
+    )
+
+    system_dex_toolchain(
+        name = "dex",
+        android_sdk_tools_target = ":android_sdk_tools",
+        visibility = ["PUBLIC"],
+    )
+
+    system_noop_dex_toolchain(
+        name = "empty_dex",
+        visibility = ["PUBLIC"],
+    )
+
+    system_genrule_toolchain(
+        name = "genrule",
+        visibility = ["PUBLIC"],
+    )
+
+    system_go_toolchain(
+        name = "go",
+        visibility = ["PUBLIC"],
+    )
+
+    system_go_bootstrap_toolchain(
+        name = "go_bootstrap",
+        visibility = ["PUBLIC"],
+    )
+
+    javacd_toolchain(
+        name = "java",
+        java = ":java_tool",
+        javac = ":javac_tool",
+        jar = ":jar_tool",
+        jlink = ":jlink_tool",
+        jmod = ":jmod_tool",
+        jrt_fs_jar = ":jrt_fs_jar",
+        visibility = ["PUBLIC"],
+    )
+
+    system_java_bootstrap_toolchain(
+        name = "java_bootstrap",
+        java = ":java_tool",
+        javac = ":javac_tool",
+        jlink = ":jlink_tool",
+        jmod = ":jmod_tool",
+        jrt_fs_jar = ":jrt_fs_jar",
+        visibility = ["PUBLIC"],
+    )
+
+    javacd_toolchain(
+        name = "java_for_android",
+        java = ":java_tool",
+        javac = ":javac_tool",
+        jar = ":jar_tool",
+        jlink = ":jlink_tool",
+        jmod = ":jmod_tool",
+        jrt_fs_jar = ":jrt_fs_jar",
+        visibility = ["PUBLIC"],
+    )
+
+    javacd_toolchain(
+        name = "java_for_host_test",
+        java = ":java_tool",
+        javac = ":javac_tool",
+        java_for_tests = ":java_tool",
+        jar = ":jar_tool",
+        jlink = ":jlink_tool",
+        jmod = ":jmod_tool",
+        jrt_fs_jar = ":jrt_fs_jar",
+        visibility = ["PUBLIC"],
+    )
+
+    java_test_toolchain(
+        name = "java_test",
+        visibility = [
+            "PUBLIC",
+        ],
+    )
+
+    java_home = read_root_config("java", "java_home", "/usr/local/java-runtime/impl/17")
+    system_java_tool(
+        name = "java_tool",
+        tool_name = java_home + "/bin/java",
+        visibility = ["PUBLIC"],
+    )
+
+    system_java_tool(
+        name = "javac_tool",
+        tool_name = java_home + "/bin/javac",
+        visibility = ["PUBLIC"],
+    )
+
+    system_java_tool(
+        name = "jar_tool",
+        tool_name = java_home + "/bin/jar",
+        visibility = ["PUBLIC"],
+    )
+
+    system_java_tool(
+        name = "jlink_tool",
+        tool_name = java_home + "/bin/jlink",
+        visibility = ["PUBLIC"],
+    )
+
+    system_java_tool(
+        name = "jmod_tool",
+        tool_name = java_home + "/bin/jmod",
+        visibility = ["PUBLIC"],
+    )
+
+    system_java_lib(
+        name = "jrt_fs_jar",
+        jar = java_home + "/lib/jrt-fs.jar",
+    )
+
+    kotlincd_toolchain(
+        name = "kotlin",
+        visibility = ["PUBLIC"],
+    )
+
+    system_kotlin_bootstrap_toolchain(
+        name = "kotlin_bootstrap",
+        visibility = ["PUBLIC"],
+    )
+
+    kotlincd_toolchain(
+        name = "kotlin_for_android",
+        visibility = ["PUBLIC"],
+    )
+
+    system_ocaml_toolchain(
+        name = "ocaml",
+        visibility = ["PUBLIC"],
+    )
+
+    # TODO(ianc) Make this not a bootstrap toolchain
+    system_prebuilt_jar_bootstrap_toolchain(
+        name = "prebuilt_jar",
+        java = ":java_tool",
+        visibility = ["PUBLIC"],
+    )
+
+    system_prebuilt_jar_bootstrap_toolchain(
+        name = "prebuilt_jar_bootstrap",
+        java = ":java_tool",
+        visibility = ["PUBLIC"],
+    )
+
+    system_prebuilt_jar_bootstrap_toolchain(
+        name = "prebuilt_jar_bootstrap_no_snapshot",
+        java = ":java_tool",
+        visibility = ["PUBLIC"],
+    )
+
+    remote_python_toolchain(
+        name = "python",
+        bootstrap = False,
+        visibility = ["PUBLIC"],
+    )
+
+    system_python_bootstrap_toolchain(
+        name = "python_bootstrap",
+        visibility = ["PUBLIC"],
+    )
+
+    system_python_wheel_toolchain(
+        name = "python_wheel",
+        visibility = ["PUBLIC"],
+    )
+
+    system_rust_toolchain(
+        name = "rust",
+        default_edition = "2021",
+        visibility = ["PUBLIC"],
+    )
+
+    remote_test_execution_toolchain(
+        name = "remote_test_execution",
+        visibility = ["PUBLIC"],
+    )
+
+    noop_test_toolchain(
+        name = "test",
+        visibility = ["PUBLIC"],
+    )
+
+    zip_file_toolchain(
+        name = "zip_file",
+        visibility = ["PUBLIC"],
+    )
+
+    system_erlang_toolchain(
+        name = "erlang-default",
+        visibility = ["PUBLIC"],
+    )
diff --git a/buck2/prelude/toolchains/dex.bzl b/buck2/prelude/toolchains/dex.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/dex.bzl
@@ -0,0 +1,41 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:dex_toolchain.bzl", "DexToolchainInfo")
+
+def system_noop_dex_toolchain(name, visibility = None):
+    _dex_toolchain_rule(
+        name = name,
+        visibility = visibility,
+    )
+
+def system_dex_toolchain(name, android_sdk_tools_target, visibility = None):
+    _dex_toolchain_rule(
+        name = name,
+        android_jar = "{}[android.jar]".format(android_sdk_tools_target),
+        d8_command_binary = "prelude//toolchains/android/src/com/facebook/buck/android/dex:run_d8_binary",
+        visibility = visibility,
+    )
+
+def _dex_toolchain_rule_impl(ctx):
+    return [
+        DefaultInfo(),
+        DexToolchainInfo(
+            android_jar = ctx.attrs.android_jar,
+            d8_command = ctx.attrs.d8_command_binary,
+        ),
+    ]
+
+_dex_toolchain_rule = rule(
+    attrs = {
+        "android_jar": attrs.option(attrs.source(), default = None),
+        "d8_command_binary": attrs.option(attrs.dep(providers = [RunInfo]), default = None),
+    },
+    impl = _dex_toolchain_rule_impl,
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/erlang.bzl b/buck2/prelude/toolchains/erlang.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/erlang.bzl
@@ -0,0 +1,48 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//erlang:erlang_erts.bzl", "erlang_erts")
+load("@prelude//erlang:erlang_info.bzl", "ErlangOTPBinariesInfo")
+load("@prelude//erlang:erlang_toolchain.bzl", "erlang_toolchain")
+
+def _system_erlang_binary_impl(_ctx):
+    return [
+        DefaultInfo(),
+        ErlangOTPBinariesInfo(
+            erl = cmd_args("erl"),
+            erlc = cmd_args("erlc"),
+            escript = cmd_args("escript"),
+        ),
+    ]
+
+system_erlang_binary = rule(
+    impl = _system_erlang_binary_impl,
+    attrs = {},
+    is_toolchain_rule = True,
+)
+
+def system_erlang_toolchain(name, visibility):
+    system_erlang_binary(
+        name = "{}-binaries".format(name),
+        visibility = visibility,
+    )
+
+    erlang_erts(
+        name = "{}-erts".format(name),
+        otp_binaries = ":{}-binaries".format(name),
+        visibility = visibility,
+    )
+
+    erlang_toolchain(
+        name = name,
+        erts_toolchain_info = ":{}-erts".format(name),
+        otp_binaries = ":{}-binaries".format(name),
+        parse_transforms = [],
+        parse_transforms_filters = {},
+        visibility = ["PUBLIC"],
+    )
diff --git a/buck2/prelude/toolchains/execution_host.bzl b/buck2/prelude/toolchains/execution_host.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/execution_host.bzl
@@ -0,0 +1,13 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:host.bzl", "HostOSTypes")
+
+_ExecutionHostOSTypes = HostOSTypes + ["fat"]  # Fat toolchains are compatible on multiple OSes.
+
+ExecutionHostOSType = enum(*_ExecutionHostOSTypes)
diff --git a/buck2/prelude/toolchains/genrule.bzl b/buck2/prelude/toolchains/genrule.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/genrule.bzl
@@ -0,0 +1,23 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:genrule_toolchain.bzl", "GenruleToolchainInfo")
+
+def _system_genrule_toolchain_impl(_ctx):
+    return [
+        DefaultInfo(),
+        GenruleToolchainInfo(
+            zip_scrubber = None,
+        ),
+    ]
+
+system_genrule_toolchain = rule(
+    impl = _system_genrule_toolchain_impl,
+    attrs = {},
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/go.bzl b/buck2/prelude/toolchains/go.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/go.bzl
@@ -0,0 +1,16 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//toolchains/go:system_go_bootstrap_toolchain.bzl", _system_go_bootstrap_toolchain = "system_go_bootstrap_toolchain")
+load("@prelude//toolchains/go:system_go_toolchain.bzl", _system_go_toolchain = "system_go_toolchain")
+
+# deprecated: use `@prelude///toolchains/go:system_go_bootstrap_toolchain.bzl` instead
+system_go_bootstrap_toolchain = _system_go_bootstrap_toolchain
+
+# deprecated: use `@prelude///toolchains/go:system_go_toolchain.bzl` instead
+system_go_toolchain = _system_go_toolchain
diff --git a/buck2/prelude/toolchains/go/go_bootstrap_toolchain.bzl b/buck2/prelude/toolchains/go/go_bootstrap_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/go/go_bootstrap_toolchain.bzl
@@ -0,0 +1,55 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//go_bootstrap:go_bootstrap.bzl", "GoBootstrapDistrInfo", "GoBootstrapToolchainInfo")
+
+def _go_bootstrap_toolchain_impl(ctx):
+    go_bootstrap_distr = ctx.attrs.go_bootstrap_distr[GoBootstrapDistrInfo]
+    return [
+        DefaultInfo(),
+        GoBootstrapToolchainInfo(
+            go_wrapper = ctx.attrs.go_wrapper[RunInfo],
+            go = go_bootstrap_distr.bin_go,
+            env_go_arch = ctx.attrs.env_go_arch,
+            env_go_os = ctx.attrs.env_go_os,
+            env_go_root = go_bootstrap_distr.go_root,
+        ),
+    ]
+
+go_bootstrap_toolchain = rule(
+    impl = _go_bootstrap_toolchain_impl,
+    is_toolchain_rule = True,
+    attrs = {
+        "env_go_arch": attrs.string(),
+        "env_go_os": attrs.string(),
+        "go_bootstrap_distr": attrs.exec_dep(providers = [GoBootstrapDistrInfo]),
+        "go_wrapper": attrs.exec_dep(providers = [RunInfo], default = "prelude//go_bootstrap/tools:go_wrapper_py"),
+    },
+)
+
+def _go_bootstrap_distr_impl(ctx):
+    go_os, go_arch = ctx.attrs.go_os_arch
+    suffix = ".exe" if go_os == "windows" else ""
+    go_platform = go_os + "_" + go_arch
+    bin_prefix = "bin/{}".format(go_platform) if ctx.attrs.multiplatform else "bin"
+    return [
+        DefaultInfo(),
+        GoBootstrapDistrInfo(
+            bin_go = RunInfo(ctx.attrs.go_root.project(bin_prefix + "/go" + suffix)),
+            go_root = ctx.attrs.go_root,
+        ),
+    ]
+
+go_bootstrap_distr = rule(
+    impl = _go_bootstrap_distr_impl,
+    attrs = {
+        "go_os_arch": attrs.tuple(attrs.string(), attrs.string()),
+        "go_root": attrs.source(allow_directory = True),
+        "multiplatform": attrs.bool(default = False),
+    },
+)
diff --git a/buck2/prelude/toolchains/go/go_toolchain.bzl b/buck2/prelude/toolchains/go/go_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/go/go_toolchain.bzl
@@ -0,0 +1,147 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//go:toolchain.bzl", "GoDistrInfo", "GoToolchainInfo", "parse_go_version")
+
+def _go_toolchain_impl(ctx):
+    # Note: It makes sense to make GoDirstrInfo an attribute of GoToolchainInfo.
+    # That's a breaking change, so we'll need to notify oss users.
+    go_distr = ctx.attrs.go_distr[GoDistrInfo]
+
+    # `buck2 run` executes the `go` subtarget on the invoking machine, so it is
+    # only offered where the target-configured pair exists; the exec-configured
+    # pair is built for wherever build actions run.
+    sub_targets = {}
+    if ctx.attrs.run_go_distr != None:
+        run_go_distr = ctx.attrs.run_go_distr[GoDistrInfo]
+        sub_targets["go"] = [
+            RunInfo(
+                cmd_args(
+                    ctx.attrs.run_go_wrapper[RunInfo],
+                    ["--go", run_go_distr.bin_go],
+                    ["--goroot", run_go_distr.go_root],
+                    ["--default-goarch", ctx.attrs.env_go_arch],
+                    ["--default-goos", ctx.attrs.env_go_os],
+                    "--",
+                )
+            ),
+        ]
+    return [
+        DefaultInfo(sub_targets = sub_targets),
+        GoToolchainInfo(
+            allow_cache_upload = ctx.attrs.allow_cache_upload,
+            assembler = go_distr.tool_asm,
+            assembler_flags = ctx.attrs.assembler_flags,
+            cxx_compiler_flags = ctx.attrs.cxx_compiler_flags,
+            cgo = go_distr.tool_cgo,
+            compiler = go_distr.tool_compile,
+            compiler_flags = ctx.attrs.compiler_flags,
+            pkg_analyzer = ctx.attrs.pkg_analyzer[RunInfo],
+            gen_embedcfg = ctx.attrs.gen_embedcfg[RunInfo],
+            external_linker_flags = ctx.attrs.external_linker_flags,
+            go_wrapper = ctx.attrs.go_wrapper[RunInfo],
+            cover = go_distr.tool_cover,
+            go = go_distr.bin_go,
+            env_go_arch = ctx.attrs.env_go_arch,
+            env_go_os = ctx.attrs.env_go_os,
+            env_go_arm = ctx.attrs.env_go_arm,
+            env_go_root = go_distr.go_root,
+            env_go_debug = ctx.attrs.env_go_debug,
+            env_go_experiment = ctx.attrs.env_go_experiment,
+            linker = go_distr.tool_link,
+            linker_flags = ctx.attrs.linker_flags,
+            packer = ctx.attrs.tool_pack[RunInfo],
+            build_tags = ctx.attrs.build_tags,
+            asan = ctx.attrs.asan,
+            race = ctx.attrs.race,
+            fuzz = ctx.attrs.fuzz,
+            version = go_distr.version,
+        ),
+    ]
+
+_go_toolchain = rule(
+    impl = _go_toolchain_impl,
+    is_toolchain_rule = True,
+    attrs = {
+        "allow_cache_upload": attrs.option(attrs.bool(), default = None),
+        "asan": attrs.bool(default = False),
+        "assembler_flags": attrs.list(attrs.arg(), default = []),
+        "build_tags": attrs.list(attrs.string(), default = []),
+        "compiler_flags": attrs.list(attrs.arg(), default = []),
+        "cxx_compiler_flags": attrs.list(attrs.arg(), default = []),
+        "env_go_arch": attrs.string(),
+        "env_go_arm": attrs.option(attrs.string(), default = None),
+        "env_go_debug": attrs.dict(attrs.string(), attrs.string(), default = {}),
+        "env_go_experiment": attrs.list(attrs.string(), default = []),
+        "env_go_os": attrs.string(),
+        "external_linker_flags": attrs.list(attrs.arg(), default = []),
+        "fuzz": attrs.bool(default = False),
+        "gen_embedcfg": attrs.exec_dep(providers = [RunInfo], default = "prelude//go/tools:gen_embedcfg"),
+        "go_distr": attrs.exec_dep(providers = [GoDistrInfo]),
+        "go_wrapper": attrs.exec_dep(providers = [RunInfo]),
+        "linker_flags": attrs.list(attrs.arg(), default = []),
+        "pkg_analyzer": attrs.exec_dep(providers = [RunInfo], default = "prelude//go/tools:pkg_analyzer"),
+        "race": attrs.bool(default = False),
+        # Target-configured duals of `go_distr` and `go_wrapper` for the `go`
+        # subtarget, which `buck2 run` executes on the invoking machine rather
+        # than on the execution platform.
+        "run_go_distr": attrs.option(attrs.dep(providers = [GoDistrInfo])),
+        "run_go_wrapper": attrs.option(attrs.dep(providers = [RunInfo])),
+        "tool_pack": attrs.exec_dep(providers = [RunInfo], default = "prelude//go/tools:tool_pack"),
+    },
+)
+
+def go_toolchain(go_distr, go_wrapper = "prelude//go/tools:go_wrapper", run_go = True, **kwargs):
+    """
+    Go toolchain backed by a `go_distr`.
+
+    Build actions use `go_distr` and `go_wrapper` configured for the execution
+    platform. The `go` subtarget (`buck2 run <toolchain>[go] -- ...`) runs on
+    the invoking machine, so it uses them configured for the target platform.
+    `run_go` (a bool or a `select` of bools) opts target platforms out of the
+    subtarget, for a `go_distr` that is not compatible with every target
+    platform the toolchain supports.
+    """
+    _go_toolchain(
+        go_distr = go_distr,
+        go_wrapper = go_wrapper,
+        run_go_distr = select_map(run_go, lambda enabled: go_distr if enabled else None),
+        run_go_wrapper = select_map(run_go, lambda enabled: go_wrapper if enabled else None),
+        **kwargs,
+    )
+
+def _go_distr_impl(ctx):
+    go_root = ctx.attrs.go_root
+    go_os, go_arch = ctx.attrs.go_os_arch
+    suffix = ".exe" if go_os == "windows" else ""
+    go_platform = "{}_{}".format(go_os, go_arch)
+    tool_prefix = "pkg/tool/" + go_platform
+    bin_prefix = "bin/{}".format(go_platform) if ctx.attrs.multiplatform else "bin"
+    return [
+        DefaultInfo(),
+        GoDistrInfo(
+            bin_go = RunInfo(go_root.project(bin_prefix + "/go" + suffix)),
+            go_root = go_root,
+            tool_asm = RunInfo(go_root.project(tool_prefix + "/asm" + suffix)),
+            tool_compile = RunInfo(go_root.project(tool_prefix + "/compile" + suffix)),
+            tool_cover = RunInfo(go_root.project(tool_prefix + "/cover" + suffix)),
+            tool_cgo = RunInfo(go_root.project(tool_prefix + "/cgo" + suffix)),
+            tool_link = RunInfo(go_root.project(tool_prefix + "/link" + suffix)),
+            version = parse_go_version(ctx.attrs.version),
+        ),
+    ]
+
+go_distr = rule(
+    impl = _go_distr_impl,
+    attrs = {
+        "go_os_arch": attrs.tuple(attrs.string(), attrs.string()),
+        "go_root": attrs.source(allow_directory = True),
+        "multiplatform": attrs.bool(default = False),
+        "version": attrs.string(),
+    },
+)
diff --git a/buck2/prelude/toolchains/go/system_go_bootstrap_toolchain.bzl b/buck2/prelude/toolchains/go/system_go_bootstrap_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/go/system_go_bootstrap_toolchain.bzl
@@ -0,0 +1,63 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//go_bootstrap:go_bootstrap.bzl", "GoBootstrapToolchainInfo")
+load("@prelude//os_lookup:defs.bzl", "ScriptLanguage")
+load("@prelude//utils:cmd_script.bzl", "cmd_script")
+
+def go_platform() -> (str, str):
+    arch = host_info().arch
+    if arch.is_aarch64:
+        go_arch = "arm64"
+    elif arch.is_x86_64:
+        go_arch = "amd64"
+    else:
+        fail("Unsupported go arch: {}".format(arch))
+
+    os = host_info().os
+    if os.is_macos:
+        go_os = "darwin"
+    elif os.is_linux:
+        go_os = "linux"
+    elif os.is_windows:
+        go_os = "windows"
+    else:
+        fail("Unsupported go os: {}".format(os))
+
+    return go_os, go_arch
+
+def _system_go_bootstrap_toolchain_impl(ctx):
+    go_os, go_arch = go_platform()
+
+    script_language = ScriptLanguage("bat" if go_os == "windows" else "sh")
+    go = "go.exe" if go_os == "windows" else "go"
+
+    go_cmd = cmd_script(ctx.actions, "go", cmd_args(go), script_language)
+
+    return [
+        DefaultInfo(),
+        GoBootstrapToolchainInfo(
+            env_go_arch = go_arch,
+            env_go_os = go_os,
+            go = RunInfo(go_cmd),
+            go_wrapper = ctx.attrs.go_wrapper[RunInfo],
+        ),
+    ]
+
+system_go_bootstrap_toolchain = rule(
+    impl = _system_go_bootstrap_toolchain_impl,
+    doc = """Example system go toolchain rules (WIP). Usage:
+  system_go_bootstrap_toolchain(
+      name = "go_bootstrap",
+      visibility = ["PUBLIC"],
+  )""",
+    attrs = {
+        "go_wrapper": attrs.default_only(attrs.dep(providers = [RunInfo], default = "prelude//go_bootstrap/tools:go_wrapper_py")),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/go/system_go_toolchain.bzl b/buck2/prelude/toolchains/go/system_go_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/go/system_go_toolchain.bzl
@@ -0,0 +1,98 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//go:toolchain.bzl", "GoToolchainInfo")
+load("@prelude//os_lookup:defs.bzl", "ScriptLanguage")
+load("@prelude//utils:cmd_script.bzl", "cmd_script")
+
+def go_platform() -> (str, str):
+    arch = host_info().arch
+    if arch.is_aarch64:
+        go_arch = "arm64"
+    elif arch.is_x86_64:
+        go_arch = "amd64"
+    else:
+        fail("Unsupported go arch: {}".format(arch))
+
+    os = host_info().os
+    if os.is_macos:
+        go_os = "darwin"
+    elif os.is_linux:
+        go_os = "linux"
+    elif os.is_windows:
+        go_os = "windows"
+    else:
+        fail("Unsupported go os: {}".format(os))
+
+    return go_os, go_arch
+
+def _system_go_toolchain_impl(ctx):
+    go_os, go_arch = go_platform()
+
+    script_language = ScriptLanguage("bat" if go_os == "windows" else "sh")
+    go = "go.exe" if go_os == "windows" else "go"
+
+    go_root = ctx.actions.declare_output("goroot", dir = True, has_content_based_path = True)
+
+    # HACK: We need a physical artifact for GOROOT to project individual source files.
+    # Since we don't know the user's GOROOT location at analysis time, we copy it
+    # at build time. A symlink won't work because .project() requires a real directory.
+    # We use a Go binary for the copy as it's more portable than shell scripts.
+    ctx.actions.run([ctx.attrs.copy_goroot[RunInfo], "-o", go_root.as_output()], category = "go_copy_goroot")
+
+    suffix = ".exe" if go_os == "windows" else ""
+    tool_prefix = "pkg/tool/{}_{}".format(go_os, go_arch)
+
+    return [
+        DefaultInfo(
+            sub_targets = {
+                "go": [
+                    RunInfo(go),
+                ]
+            }
+        ),
+        GoToolchainInfo(
+            allow_cache_upload = ctx.attrs.allow_cache_upload,
+            assembler = RunInfo(cmd_script(ctx.actions, "asm", cmd_args(go, "tool", "asm"), script_language)),
+            cgo = RunInfo(go_root.project(tool_prefix + "/cgo" + suffix)),
+            pkg_analyzer = ctx.attrs.pkg_analyzer[RunInfo],
+            gen_embedcfg = ctx.attrs.gen_embedcfg[RunInfo],
+            compiler = RunInfo(cmd_script(ctx.actions, "compile", cmd_args(go, "tool", "compile"), script_language)),
+            cover = RunInfo(cmd_script(ctx.actions, "cover", cmd_args(go, "tool", "cover"), script_language)),
+            env_go_arch = go_arch,
+            env_go_os = go_os,
+            env_go_root = go_root,
+            external_linker_flags = [],
+            go = RunInfo(cmd_script(ctx.actions, "go", cmd_args(go), script_language)),
+            go_wrapper = ctx.attrs.go_wrapper[RunInfo],
+            linker = RunInfo(cmd_script(ctx.actions, "link", cmd_args(go, "tool", "link"), script_language)),
+            packer = RunInfo(cmd_script(ctx.actions, "pack", cmd_args(go, "tool", "pack"), script_language)),
+            build_tags = [],
+            linker_flags = [],
+            assembler_flags = [],
+            compiler_flags = [],
+            version = None,  # we are unable to run `go version` during analysis time
+        ),
+    ]
+
+system_go_toolchain = rule(
+    impl = _system_go_toolchain_impl,
+    doc = """Example system go toolchain rules (WIP). Usage:
+  system_go_toolchain(
+      name = "go",
+      visibility = ["PUBLIC"],
+  )""",
+    attrs = {
+        "allow_cache_upload": attrs.option(attrs.bool(), default = None),
+        "copy_goroot": attrs.default_only(attrs.dep(providers = [RunInfo], default = "prelude//go/tools:copy_goroot")),
+        "gen_embedcfg": attrs.default_only(attrs.dep(providers = [RunInfo], default = "prelude//go/tools:gen_embedcfg")),
+        "go_wrapper": attrs.default_only(attrs.dep(providers = [RunInfo], default = "prelude//go/tools:go_wrapper")),
+        "pkg_analyzer": attrs.default_only(attrs.dep(providers = [RunInfo], default = "prelude//go/tools:pkg_analyzer")),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/haskell.bzl b/buck2/prelude/toolchains/haskell.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/haskell.bzl
@@ -0,0 +1,38 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//haskell:toolchain.bzl", "HaskellPlatformInfo", "HaskellToolchainInfo", "print_libdir")
+
+def _system_haskell_toolchain(ctx: AnalysisContext) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        HaskellToolchainInfo(
+            compiler = ctx.attrs.compiler,
+            packager = ctx.attrs.packager,
+            linker = ctx.attrs.compiler,
+            libdir = print_libdir(ctx.actions, "libdir", ctx.attrs.compiler, {}),
+            haddock = "haddock",
+            compiler_flags = [],
+            linker_flags = [],
+            ghc_version = ctx.attrs.ghc_version,
+        ),
+        HaskellPlatformInfo(
+            name = host_info().arch,
+        ),
+    ]
+
+system_haskell_toolchain = rule(
+    impl = _system_haskell_toolchain,
+    attrs = {
+        "compiler": attrs.string(default = "ghc"),
+        "packager": attrs.string(default = "ghc-pkg"),
+        # The version of `compiler`, as `ghc --numeric-version` prints it.
+        "ghc_version": attrs.string(),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/java.bzl b/buck2/prelude/toolchains/java.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/java.bzl
@@ -0,0 +1,241 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:paths.bzl", "paths")
+load(
+    "@prelude//java:java_toolchain.bzl",
+    "AbiGenerationMode",
+    "JavaPlatformInfo",
+    "JavaTestToolchainInfo",
+    "JavaToolchainInfo",
+    "JavacProtocol",
+    "PrebuiltJarToolchainInfo",
+)
+load("@prelude//tests:test_listing.bzl", "TestListingInfo")
+
+def _system_java_tool_impl(ctx):
+    return [
+        DefaultInfo(),
+        RunInfo([ctx.attrs.tool_name]),
+    ]
+
+system_java_tool = rule(
+    impl = _system_java_tool_impl,
+    attrs = {
+        "tool_name": attrs.string(),
+    },
+)
+
+def _system_java_lib_impl(ctx):
+    output = ctx.actions.declare_output(paths.basename(ctx.attrs.jar), has_content_based_path = False)
+    ctx.actions.run(cmd_args(["ln", "-s", ctx.attrs.jar, output.as_output()]), category = "{}_symlink".format(ctx.attrs.name))
+    return [DefaultInfo(default_output = output)]
+
+system_java_lib = rule(
+    impl = _system_java_lib_impl,
+    attrs = {
+        "jar": attrs.string(),
+    },
+)
+
+def system_prebuilt_jar_bootstrap_toolchain(name, java, visibility = None):
+    kwargs = {}
+
+    _prebuilt_jar_toolchain_rule(name = name, java = java, visibility = visibility, **kwargs)
+
+def _prebuilt_jar_toolchain_rule_impl(ctx):
+    return [
+        DefaultInfo(),
+        PrebuiltJarToolchainInfo(
+            class_abi_generator = None,
+            cp_snapshot_generator = None,
+            global_code_config = {},
+            is_bootstrap_toolchain = True,
+            java = ctx.attrs.java,
+        ),
+    ]
+
+_prebuilt_jar_toolchain_rule = rule(
+    attrs = {
+        # this just goes into the RunInfo of the result, so it's target, not exec
+        "java": attrs.dep(providers = [RunInfo]),
+    },
+    impl = _prebuilt_jar_toolchain_rule_impl,
+    is_toolchain_rule = True,
+)
+
+def javacd_toolchain(name, java, javac, jar, jlink, jmod, jrt_fs_jar, java_for_tests = None, visibility = None):
+    _java_toolchain(
+        name = name,
+        visibility = visibility,
+        java = java,
+        jar = jar,
+        java_for_tests = java_for_tests,
+        is_bootstrap_toolchain = False,
+        class_abi_generator = "prelude//toolchains/android/src/com/facebook/buck/jvm/java/abi:api-stubber",
+        class_loader_bootstrapper = "prelude//toolchains/android/src/com/facebook/buck/cli/bootstrapper:bootstrapper",
+        fat_jar_main_class_lib = "prelude//toolchains/android/src/com/facebook/buck/jvm/java/fatjar:fat-jar-main-binary",
+        javac = javac,
+        javacd = "prelude//toolchains/android/src/com/facebook/buck/jvm/java/stepsbuilder/javacd/main:javacd_tool",
+        javac_protocol = "javacd",
+        javacd_main_class = "com.facebook.buck.jvm.java.stepsbuilder.javacd.main.JavaCDMain",
+        jlink = jlink,
+        jmod = jmod,
+        jrt_fs_jar = jrt_fs_jar,
+    )
+
+def system_java_bootstrap_toolchain(name, java, javac, jlink, jmod, jrt_fs_jar, visibility = None):
+    _java_toolchain(
+        name = name,
+        visibility = visibility,
+        java = java,
+        is_bootstrap_toolchain = True,
+        javac = javac,
+        javac_protocol = "classic",
+        jlink = jlink,
+        jmod = jmod,
+        jrt_fs_jar = jrt_fs_jar,
+    )
+
+def _java_toolchain_impl(ctx):
+    return [
+        DefaultInfo(),
+        JavaPlatformInfo(
+            name = ctx.attrs.name,
+        ),
+        JavaToolchainInfo(
+            # TODO(navidq) make this configurable via buck config
+            abi_generation_mode = AbiGenerationMode("none"),
+            compile_and_package = ctx.attrs.compile_and_package,
+            class_abi_generator = ctx.attrs.class_abi_generator,
+            class_loader_bootstrapper = ctx.attrs.class_loader_bootstrapper,
+            cp_snapshot_generator = None,
+            dep_files = None,
+            fat_jar_main_class_lib = ctx.attrs.fat_jar_main_class_lib,
+            gen_class_to_source_map = ctx.attrs.gen_class_to_source_map,
+            gen_class_to_source_map_include_sourceless_compiled_packages = ctx.attrs.gen_class_to_source_map_include_sourceless_compiled_packages,
+            gen_class_to_source_map_debuginfo = None,
+            fat_jar = ctx.attrs.fat_jar,
+            is_bootstrap_toolchain = ctx.attrs.is_bootstrap_toolchain,
+            jar = ctx.attrs.jar[RunInfo] if ctx.attrs.jar else None,
+            java = ctx.attrs.java,
+            java_for_tests = ctx.attrs.java_for_tests[RunInfo] if ctx.attrs.java_for_tests else ctx.attrs.java[RunInfo],
+            javac = ctx.attrs.javac,
+            javacd = ctx.attrs.javacd,
+            javac_protocol = ctx.attrs.javac_protocol,
+            javacd_jvm_args = [],
+            javacd_jvm_args_target = [],
+            javacd_main_class = ctx.attrs.javacd_main_class,
+            jar_builder = RunInfo(cmd_args([ctx.attrs.java[RunInfo], "-jar", ctx.attrs.jar_builder])),
+            jlink = ctx.attrs.jlink,
+            jmod = ctx.attrs.jmod,
+            jrt_fs_jar = ctx.attrs.jrt_fs_jar,
+            src_root_elements = [],
+            src_root_prefixes = [],
+            track_class_usage = False,
+            zip_scrubber = RunInfo(cmd_args([ctx.attrs.java[RunInfo], "-jar", ctx.attrs.zip_scrubber])),
+            nullsafe = None,
+            nullsafe_extra_args = [],
+            nullsafe_signatures = None,
+            semanticdb_javac = None,
+            semanticdb_sourceroot = None,
+            global_code_config = {},
+            merge_class_to_source_maps = ctx.attrs.merge_class_to_source_maps,
+            source_level = ctx.attrs.source_level,
+            target_level = ctx.attrs.target_level,
+        ),
+    ]
+
+_java_toolchain = rule(
+    impl = _java_toolchain_impl,
+    is_toolchain_rule = True,
+    attrs = {
+        "class_abi_generator": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "class_loader_bootstrapper": attrs.option(attrs.source(), default = None),
+        "compile_and_package": attrs.exec_dep(
+            default = "prelude//java/tools:compile_and_package",
+            providers = [RunInfo],
+        ),
+        "fat_jar": attrs.exec_dep(
+            default = "prelude//java/tools:fat_jar",
+            providers = [RunInfo],
+        ),
+        "fat_jar_main_class_lib": attrs.option(attrs.source(), default = None),
+        "gen_class_to_source_map": attrs.exec_dep(
+            default = "prelude//java/tools:gen_class_to_source_map",
+            providers = [RunInfo],
+        ),
+        "gen_class_to_source_map_include_sourceless_compiled_packages": attrs.list(
+            attrs.string(),
+            default = [
+                "androidx.databinding",
+            ],
+        ),
+        "is_bootstrap_toolchain": attrs.bool(default = False),
+        "jar": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "jar_builder": attrs.source(default = "prelude//toolchains/android/src/com/facebook/buck/util/zip:jar_builder"),
+        "java": attrs.exec_dep(providers = [RunInfo]),
+        "java_for_tests": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "javac": attrs.option(attrs.one_of(attrs.exec_dep(), attrs.source(), attrs.string()), default = None),
+        "javac_protocol": attrs.enum(JavacProtocol.values()),
+        "javacd": attrs.option(attrs.source(), default = None),
+        "javacd_main_class": attrs.option(attrs.string(), default = None),
+        "jlink": attrs.exec_dep(providers = [RunInfo]),
+        "jmod": attrs.exec_dep(providers = [RunInfo]),
+        "jrt_fs_jar": attrs.source(),
+        "merge_class_to_source_maps": attrs.exec_dep(
+            default = "prelude//java/tools:merge_class_to_source_maps",
+            providers = [RunInfo],
+        ),
+        "source_level": attrs.string(default = "8"),
+        "target_level": attrs.string(default = "8"),
+        "zip_scrubber": attrs.source(default = "prelude//toolchains/android/src/com/facebook/buck/util/zip:zip_scrubber"),
+    },
+)
+
+def java_test_toolchain(name, **kwargs):
+    kwargs["test_runner_library_jar"] = "prelude//toolchains/android/src/com/facebook/buck/testrunner:testrunner-bin-fixed"
+    kwargs["junit_test_runner_main_class_args"] = ["com.facebook.buck.jvm.java.runner.FileClassPathRunner", "com.facebook.buck.testrunner.JUnitMain"]
+    kwargs["junit5_test_runner_main_class_args"] = ["com.facebook.buck.jvm.java.runner.FileClassPathRunner", "com.facebook.buck.testrunner.JupiterMain"]
+    kwargs["testng_test_runner_main_class_args"] = ["com.facebook.buck.jvm.java.runner.FileClassPathRunner", "com.facebook.buck.testrunner.TestNGMain"]
+    kwargs["list_class_names"] = "prelude//java/tools:list_class_names"
+
+    _java_test_toolchain_rule(name = name, **kwargs)
+
+def _java_test_toolchain_rule_impl(ctx):
+    return [
+        DefaultInfo(),
+        JavaTestToolchainInfo(
+            junit5_test_runner_main_class_args = ctx.attrs.junit5_test_runner_main_class_args,
+            junit_test_runner_main_class_args = ctx.attrs.junit_test_runner_main_class_args,
+            jvm_args = ctx.attrs.jvm_args,
+            list_class_names = ctx.attrs.list_class_names,
+            test_runner_library_jar = ctx.attrs.test_runner_library_jar,
+            testng_test_runner_main_class_args = ctx.attrs.testng_test_runner_main_class_args,
+        ),
+        TestListingInfo(
+            list_tests = ctx.attrs.list_tests,
+        ),
+    ]
+
+_java_test_toolchain_rule = rule(
+    impl = _java_test_toolchain_rule_impl,
+    attrs = {
+        "junit5_test_runner_main_class_args": attrs.list(attrs.string()),
+        "junit_test_runner_main_class_args": attrs.list(attrs.string()),
+        "jvm_args": attrs.list(
+            attrs.string(),
+            default = [],
+        ),
+        "list_class_names": attrs.exec_dep(providers = [RunInfo]),
+        "list_tests": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "test_runner_library_jar": attrs.source(),
+        "testng_test_runner_main_class_args": attrs.list(attrs.string()),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/kotlin.bzl b/buck2/prelude/toolchains/kotlin.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/kotlin.bzl
@@ -0,0 +1,122 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//java:java_toolchain.bzl", "DepFiles")
+load("@prelude//kotlin:kotlin_toolchain.bzl", "KotlinToolchainInfo", "KotlincProtocol")
+
+def kotlincd_toolchain(name, java_binary_for_kotlincd = None, visibility = None):
+    _kotlin_toolchain_rule(
+        java_binary_for_kotlincd = java_binary_for_kotlincd,
+        name = name,
+        annotation_processing_jar = "prelude//toolchains/android/third-party:kotlin-annotation-processing-embeddable",
+        class_loader_bootstrapper = "prelude//toolchains/android/src/com/facebook/buck/cli/bootstrapper:bootstrapper",
+        compile_kotlin = "prelude//kotlin/tools/compile_kotlin:compile_kotlin",
+        dep_files = "none",
+        kapt_base64_encoder = "prelude//kotlin/tools/kapt_base64_encoder:kapt_base64_encoder",
+        kotlin_stdlib = "prelude//toolchains/android/third-party:kotlin-stdlib",
+        kotlin_version = "2.2.0",
+        kotlin_home_libraries = [
+            "prelude//toolchains/android/third-party:kotlin-annotations",
+            "prelude//toolchains/android/third-party:kotlin-build-tools-impl",
+            "prelude//toolchains/android/third-party:kotlin-daemon-client",
+            "prelude//toolchains/android/third-party:kotlin-compiler-embeddable",
+            "prelude//toolchains/android/third-party:kotlin-reflect",
+            "prelude//toolchains/android/third-party:kotlin-script-runtime",
+            "prelude//toolchains/android/third-party:kotlin-stdlib",
+            "prelude//toolchains/android/third-party:trove",
+            "prelude//toolchains/android/third-party:kotlinx-coroutines-core-jvm",
+        ],
+        kotlinc = "prelude//toolchains/android/third-party:kotlin-compiler-binary",
+        kotlincd = "prelude//toolchains/android/src/com/facebook/buck/jvm/kotlin/cd/workertool:kotlincd_tool-main",
+        kotlinc_protocol = "kotlincd",
+        kotlincd_main_class = "com.facebook.buck.jvm.kotlin.cd.workertool.KotlinCDMain",
+        visibility = visibility,
+    )
+
+def system_kotlin_bootstrap_toolchain(name, visibility = None):
+    _kotlin_toolchain_rule(
+        name = name,
+        annotation_processing_jar = "prelude//toolchains/android/third-party:kotlin-annotation-processing-embeddable",
+        compile_kotlin = "prelude//kotlin/tools/compile_kotlin:compile_kotlin",
+        dep_files = "none",
+        kapt_base64_encoder = "prelude//kotlin/tools/kapt_base64_encoder:kapt_base64_encoder",
+        kotlin_stdlib = "prelude//toolchains/android/third-party:kotlin-stdlib",
+        kotlin_version = read_config("kotlin", "kotlin_version", "2.0.0"),
+        kotlinc = "prelude//toolchains/android/third-party:kotlin-compiler-binary",
+        kotlinc_protocol = "classic",
+        visibility = visibility,
+    )
+
+def _kotlin_toolchain_rule_impl(ctx):
+    return [
+        DefaultInfo(),
+        KotlinToolchainInfo(
+            annotation_processing_jar = ctx.attrs.annotation_processing_jar,
+            class_loader_bootstrapper = ctx.attrs.class_loader_bootstrapper,
+            compile_kotlin = ctx.attrs.compile_kotlin,
+            dep_files = DepFiles(ctx.attrs.dep_files),
+            kapt_base64_encoder = ctx.attrs.kapt_base64_encoder,
+            kotlinc = ctx.attrs.kotlinc,
+            kotlincd = ctx.attrs.kotlincd,
+            kotlin_stdlib = ctx.attrs.kotlin_stdlib,
+            kotlin_version = ctx.attrs.kotlin_version,
+            kotlin_home_libraries = ctx.attrs.kotlin_home_libraries,
+            enable_incremental_compilation = ctx.attrs.enable_incremental_compilation or False,
+            java_binary_for_kotlincd = ctx.attrs.java_binary_for_kotlincd,
+            ksp2_enable_incremental_processing = ctx.attrs.ksp2_enable_incremental_processing or False,
+            kotlinc_protocol = ctx.attrs.kotlinc_protocol,
+            kosabi_stubs_gen_k2_plugin = ctx.attrs.kosabi_stubs_gen_k2_plugin,
+            kosabi_applicability_plugin = ctx.attrs.kosabi_applicability_plugin,
+            jvm_abi_gen_plugin = ctx.attrs.jvm_abi_gen_plugin,
+            kotlincd_debug_port = ctx.attrs.kotlincd_debug_port,
+            kotlincd_debug_target = ctx.attrs.kotlincd_debug_target,
+            kotlincd_jvm_args = ctx.attrs.kotlincd_jvm_args,
+            kotlincd_jvm_args_target = ctx.attrs.kotlincd_jvm_args_target,
+            kotlincd_main_class = ctx.attrs.kotlincd_main_class,
+            kotlincd_worker = ctx.attrs.kotlincd_worker,
+            track_class_usage_plugin = ctx.attrs.track_class_usage_plugin,
+            track_files_which_skipped_compilation = ctx.attrs.track_files_which_skipped_compilation or False,
+            kotlin_error_handler = None,
+            kosabi_jvm_abi_gen_k2_plugin = ctx.attrs.kosabi_jvm_abi_gen_k2_plugin,
+            semanticdb_kotlinc = None,
+            semanticdb_sourceroot = None,
+        ),
+    ]
+
+_kotlin_toolchain_rule = rule(
+    attrs = {
+        "annotation_processing_jar": attrs.dep(),
+        "class_loader_bootstrapper": attrs.option(attrs.source(), default = None),
+        "compile_kotlin": attrs.dep(providers = [RunInfo]),
+        "dep_files": attrs.enum(["none", "per_class", "per_jar"], default = "none"),
+        "enable_incremental_compilation": attrs.option(attrs.bool(), default = None),
+        "java_binary_for_kotlincd": attrs.option(attrs.dep(providers = [RunInfo]), default = None),
+        "jvm_abi_gen_plugin": attrs.option(attrs.source(), default = None),
+        "kapt_base64_encoder": attrs.dep(providers = [RunInfo]),
+        "kosabi_applicability_plugin": attrs.option(attrs.source(), default = None),
+        "kosabi_jvm_abi_gen_k2_plugin": attrs.option(attrs.source(), default = None),
+        "kosabi_stubs_gen_k2_plugin": attrs.option(attrs.source(), default = None),
+        "kotlin_home_libraries": attrs.list(attrs.source(), default = []),
+        "kotlin_stdlib": attrs.dep(),
+        "kotlin_version": attrs.string(),
+        "kotlinc": attrs.dep(providers = [RunInfo]),
+        "kotlinc_protocol": attrs.enum(KotlincProtocol.values(), default = "classic"),
+        "kotlincd": attrs.option(attrs.dep(providers = [RunInfo]), default = None),
+        "kotlincd_debug_port": attrs.option(attrs.int(), default = None),
+        "kotlincd_debug_target": attrs.option(attrs.label(), default = None),
+        "kotlincd_jvm_args": attrs.list(attrs.string(), default = []),
+        "kotlincd_jvm_args_target": attrs.list(attrs.label(), default = []),
+        "kotlincd_main_class": attrs.option(attrs.string(), default = None),
+        "kotlincd_worker": attrs.option(attrs.dep(), default = None),
+        "ksp2_enable_incremental_processing": attrs.option(attrs.bool(), default = None),
+        "track_class_usage_plugin": attrs.option(attrs.source(), default = None),
+        "track_files_which_skipped_compilation": attrs.option(attrs.bool(), default = None),
+    },
+    impl = _kotlin_toolchain_rule_impl,
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/msvc/BUCK b/buck2/prelude/toolchains/msvc/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/msvc/BUCK
@@ -0,0 +1,24 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+load(":tools.bzl", "find_msvc_tools")
+
+oncall("build_infra")
+
+source_listing()
+
+python_bootstrap_binary(
+    name = "vswhere",
+    main = "vswhere.py",
+    visibility = ["PUBLIC"],
+)
+
+python_bootstrap_binary(
+    name = "run_msvc_tool",
+    main = "run_msvc_tool.py",
+    visibility = ["PUBLIC"],
+)
+
+find_msvc_tools(
+    name = "msvc_tools",
+    target_compatible_with = ["config//os:windows"],
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/toolchains/msvc/run_msvc_tool.py b/buck2/prelude/toolchains/msvc/run_msvc_tool.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/msvc/run_msvc_tool.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import json
+import os
+import subprocess
+import sys
+from typing import NamedTuple
+
+
+class Tool(NamedTuple):
+    # Path of the executable
+    exe: str
+    # Paths to prepend onto $LIB
+    LIB: list[str]
+    # Paths to prepend onto $PATH
+    PATH: list[str]
+    # Paths to prepend onto $INCLUDE
+    INCLUDE: list[str]
+
+
+def prepend_env(env, key, entries):
+    entries = ";".join(entries)
+    if key in env:
+        env[key] = entries + ";" + env[key]
+    else:
+        env[key] = entries
+
+
+def main():
+    tool_json, arguments = sys.argv[1], sys.argv[2:]
+    with open(tool_json, encoding="utf-8") as f:
+        tool = Tool(**json.load(f))
+
+    env = os.environ.copy()
+    prepend_env(env, "LIB", tool.LIB)
+    prepend_env(env, "PATH", tool.PATH)
+    prepend_env(env, "INCLUDE", tool.INCLUDE)
+
+    if tool.exe is None:
+        print("Tool not found", file=sys.stderr)
+        sys.exit(1)
+    else:
+        completed_process = subprocess.run([tool.exe, *arguments], env=env)
+        sys.exit(completed_process.returncode)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/toolchains/msvc/tools.bzl b/buck2/prelude/toolchains/msvc/tools.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/msvc/tools.bzl
@@ -0,0 +1,189 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cxx:cxx_toolchain_types.bzl", "LinkerType")
+load("@prelude//os_lookup:defs.bzl", "ScriptLanguage")
+load("@prelude//toolchains:cxx.bzl", "CxxToolsInfo")
+load("@prelude//utils:cmd_script.bzl", "cmd_script")
+
+def _find_msvc_tools_impl(ctx: AnalysisContext) -> list[Provider]:
+    cl_exe_json = ctx.actions.declare_output("cl.exe.json", has_content_based_path = False)
+    cvtres_exe_json = ctx.actions.declare_output("cvtres.exe.json", has_content_based_path = False)
+    lib_exe_json = ctx.actions.declare_output("lib.exe.json", has_content_based_path = False)
+    ml64_exe_json = ctx.actions.declare_output("ml64.exe.json", has_content_based_path = False)
+    link_exe_json = ctx.actions.declare_output("link.exe.json", has_content_based_path = False)
+    rc_exe_json = ctx.actions.declare_output("rc.exe.json", has_content_based_path = False)
+
+    cmd = [
+        ctx.attrs.vswhere[RunInfo],
+        cmd_args("--cl=", cl_exe_json.as_output(), delimiter = ""),
+        cmd_args("--cvtres=", cvtres_exe_json.as_output(), delimiter = ""),
+        cmd_args("--lib=", lib_exe_json.as_output(), delimiter = ""),
+        cmd_args("--ml64=", ml64_exe_json.as_output(), delimiter = ""),
+        cmd_args("--link=", link_exe_json.as_output(), delimiter = ""),
+        cmd_args("--rc=", rc_exe_json.as_output(), delimiter = ""),
+    ]
+
+    ctx.actions.run(
+        cmd,
+        category = "vswhere",
+        local_only = True,
+    )
+
+    run_msvc_tool = ctx.attrs.run_msvc_tool[RunInfo]
+    if ctx.attrs.use_path_compilers:
+        cl_exe_script = "cl.exe"
+        ml64_exe_script = "ml64.exe"
+        rc_exe_script = "rc.exe"
+        cvtres_exe_script = "cvtres.exe"
+    else:
+        cl_exe_script = cmd_script(
+            actions = ctx.actions,
+            name = "cl",
+            cmd = cmd_args(run_msvc_tool, cl_exe_json),
+            language = ScriptLanguage("bat"),
+        )
+        cvtres_exe_script = cmd_script(
+            actions = ctx.actions,
+            name = "cvtres",
+            cmd = cmd_args(run_msvc_tool, cvtres_exe_json),
+            language = ScriptLanguage("bat"),
+        )
+        ml64_exe_script = cmd_script(
+            actions = ctx.actions,
+            name = "ml64",
+            cmd = cmd_args(run_msvc_tool, ml64_exe_json),
+            language = ScriptLanguage("bat"),
+        )
+        rc_exe_script = cmd_script(
+            actions = ctx.actions,
+            name = "rc",
+            cmd = cmd_args(run_msvc_tool, rc_exe_json),
+            language = ScriptLanguage("bat"),
+        )
+
+    if ctx.attrs.use_path_linkers:
+        lib_exe_script = "lib.exe"
+        link_exe_script = "link.exe"
+    else:
+        lib_exe_script = cmd_script(
+            actions = ctx.actions,
+            name = "lib",
+            cmd = cmd_args(run_msvc_tool, lib_exe_json),
+            language = ScriptLanguage("bat"),
+        )
+        link_exe_script = cmd_script(
+            actions = ctx.actions,
+            name = "link",
+            cmd = cmd_args(run_msvc_tool, link_exe_json),
+            language = ScriptLanguage("bat"),
+        )
+
+    return [
+        # Supports `buck2 run prelude//toolchains/msvc:msvc_tools[cl.exe]`
+        # and `buck2 build prelude//toolchains/msvc:msvc_tools[cl.exe][json]`
+        DefaultInfo(
+            sub_targets = {
+                "cl.exe": [
+                    RunInfo(args = [cl_exe_script]),
+                    DefaultInfo(
+                        sub_targets = {
+                            "json": [DefaultInfo(default_output = cl_exe_json)],
+                        }
+                    ),
+                ],
+                "cvtres.exe": [
+                    RunInfo(args = [cvtres_exe_script]),
+                    DefaultInfo(
+                        sub_targets = {
+                            "json": [DefaultInfo(default_output = cvtres_exe_json)],
+                        }
+                    ),
+                ],
+                "lib.exe": [
+                    RunInfo(args = [lib_exe_script]),
+                    DefaultInfo(
+                        sub_targets = {
+                            "json": [DefaultInfo(default_output = lib_exe_json)],
+                        }
+                    ),
+                ],
+                "link.exe": [
+                    RunInfo(args = [link_exe_script]),
+                    DefaultInfo(
+                        sub_targets = {
+                            "json": [DefaultInfo(default_output = link_exe_json)],
+                        }
+                    ),
+                ],
+                "ml64.exe": [
+                    RunInfo(args = [ml64_exe_script]),
+                    DefaultInfo(
+                        sub_targets = {
+                            "json": [DefaultInfo(default_output = ml64_exe_json)],
+                        }
+                    ),
+                ],
+                "rc.exe": [
+                    RunInfo(args = [rc_exe_script]),
+                    DefaultInfo(
+                        sub_targets = {
+                            "json": [DefaultInfo(default_output = rc_exe_json)],
+                        }
+                    ),
+                ],
+            }
+        ),
+        CxxToolsInfo(
+            compiler = cl_exe_script,
+            compiler_type = "windows",
+            cxx_compiler = cl_exe_script,
+            asm_compiler = ml64_exe_script,
+            asm_compiler_type = "windows_ml64",
+            rc_compiler = rc_exe_script,
+            cvtres_compiler = cvtres_exe_script,
+            archiver = lib_exe_script,
+            archiver_type = "windows",
+            linker = _windows_linker_wrapper(ctx, link_exe_script),
+            linker_type = LinkerType("windows"),
+        ),
+    ]
+
+def _windows_linker_wrapper(ctx: AnalysisContext, linker: [cmd_args, str]) -> cmd_args:
+    # Linkers pretty much all support @file.txt argument syntax to insert
+    # arguments from the given text file, usually formatted one argument per
+    # line.
+    #
+    # - GNU ld: https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html
+    # - lld is command line compatible with GNU ld
+    # - MSVC link.exe: https://learn.microsoft.com/en-us/cpp/build/reference/linking?view=msvc-170#link-command-files
+    #
+    # However, there is inconsistency in whether they support nesting of @file
+    # arguments inside of another @file.
+    #
+    # We wrap the linker to flatten @file arguments down to 1 level of nesting.
+    return cmd_script(
+        actions = ctx.actions,
+        name = "windows_linker",
+        cmd = cmd_args(
+            ctx.attrs.linker_wrapper[RunInfo],
+            linker,
+        ),
+        language = ScriptLanguage("bat"),
+    )
+
+find_msvc_tools = rule(
+    impl = _find_msvc_tools_impl,
+    attrs = {
+        "linker_wrapper": attrs.default_only(attrs.exec_dep(providers = [RunInfo], default = "prelude//cxx/tools:linker_wrapper")),
+        "run_msvc_tool": attrs.default_only(attrs.dep(providers = [RunInfo], default = "prelude//toolchains/msvc:run_msvc_tool")),
+        "use_path_compilers": attrs.bool(default = False),
+        "use_path_linkers": attrs.bool(default = False),
+        "vswhere": attrs.default_only(attrs.dep(providers = [RunInfo], default = "prelude//toolchains/msvc:vswhere")),
+    },
+)
diff --git a/buck2/prelude/toolchains/msvc/vswhere.py b/buck2/prelude/toolchains/msvc/vswhere.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/msvc/vswhere.py
@@ -0,0 +1,333 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Translated from the Rust `cc` crate's windows_registry.rs.
+# https://github.com/rust-lang/cc-rs/blob/1.0.79/src/windows_registry.rs
+
+import argparse
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import winreg
+from pathlib import Path
+from typing import IO, NamedTuple
+
+VC_EXE_NAMES = ["cl.exe", "cvtres.exe", "lib.exe", "ml64.exe", "link.exe"]
+UCRT_EXE_NAMES = ["rc.exe"]
+
+
+class OutputJsonFiles(NamedTuple):
+    # We write a Tool instance as JSON into each of these files.
+    cl: IO[str]
+    cvtres: IO[str]
+    lib: IO[str]
+    ml64: IO[str]
+    link: IO[str]
+    rc: IO[str]
+
+
+class Tool(NamedTuple):
+    exe: Path
+    LIB: list[Path] = []
+    PATH: list[Path] = []
+    INCLUDE: list[Path] = []
+
+
+def find_in_path(executable, is_optional=False):
+    which = shutil.which(executable)
+    if which is None:
+        if is_optional:
+            return None
+        else:
+            print(f"{executable} not found in $PATH", file=sys.stderr)
+            sys.exit(1)
+    return Tool(which)
+
+
+def find_with_vswhere_exe():
+    program_files = os.environ.get("ProgramFiles(x86)")
+    if program_files is None:
+        program_files = os.environ.get("ProgramFiles")
+    if program_files is None:
+        print(
+            "expected a %ProgramFiles(x86)% or %ProgramFiles% environment variable",
+            file=sys.stderr,
+        )
+        sys.exit(1)
+
+    vswhere_exe = (
+        Path(program_files) / "Microsoft Visual Studio" / "Installer" / "vswhere.exe"
+    )
+    vswhere_json = subprocess.check_output(
+        [
+            vswhere_exe,
+            "-products",
+            "*",
+            "-requires",
+            "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
+            "-format",
+            "json",
+            "-utf8",
+            "-nologo",
+        ],
+        encoding="utf-8",
+    )
+
+    vswhere_json = json.loads(vswhere_json)
+
+    # Sort by MSVC version, newest to oldest.
+    # Version is a sequence of 16-bit integers.
+    # Example: "17.6.33829.357"
+    vswhere_json.sort(
+        key=lambda vs: [int(n) for n in vs["installationVersion"].split(".")],
+        reverse=True,
+    )
+
+    for vs_instance in list(vswhere_json):
+        installation_path = Path(vs_instance["installationPath"])
+
+        # Tools version is different from the one above: "14.36.32532"
+        version_file = (
+            installation_path
+            / "VC"
+            / "Auxiliary"
+            / "Build"
+            / "Microsoft.VCToolsVersion.default.txt"
+        )
+        vc_tools_version = version_file.read_text(encoding="utf-8").strip()
+
+        tools_path = installation_path / "VC" / "Tools" / "MSVC" / vc_tools_version
+        bin_path = tools_path / "bin" / "HostX64" / "x64"
+        lib_path = tools_path / "lib" / "x64"
+        include_path = tools_path / "include"
+
+        vc_exe_paths = [bin_path / exe for exe in VC_EXE_NAMES]
+
+        if not all(exe.exists() for exe in vc_exe_paths):
+            continue
+
+        PATH = [bin_path]
+        LIB = [lib_path]
+        INCLUDE = [include_path]
+
+        ucrt, ucrt_version = get_ucrt_dir()
+        if ucrt and ucrt_version:
+            ucrt_bin_path = ucrt / "bin" / ucrt_version / "x64"
+            PATH.append(ucrt_bin_path)
+            LIB.append(ucrt / "lib" / ucrt_version / "ucrt" / "x64")
+            INCLUDE.append(ucrt / "include" / ucrt_version / "ucrt")
+
+            ucrt_exe_paths = [ucrt_bin_path / exe for exe in UCRT_EXE_NAMES]
+            ucrt_exe_paths = [exe if exe.exists() else None for exe in ucrt_exe_paths]
+        else:
+            ucrt_exe_paths = [None for exe in UCRT_EXE_NAMES]
+
+        sdk, sdk_version = get_sdk10_dir()
+        if sdk and sdk_version:
+            PATH.append(sdk / "bin" / "x64")
+            LIB.append(sdk / "lib" / sdk_version / "um" / "x64")
+            INCLUDE.append(sdk / "include" / sdk_version / "um")
+            INCLUDE.append(sdk / "include" / sdk_version / "cppwinrt")
+            INCLUDE.append(sdk / "include" / sdk_version / "winrt")
+            INCLUDE.append(sdk / "include" / sdk_version / "shared")
+
+        return [
+            Tool(exe=exe, LIB=LIB, PATH=PATH, INCLUDE=INCLUDE)
+            for exe in vc_exe_paths + ucrt_exe_paths
+        ]
+
+    print(
+        "vswhere.exe did not find a suitable MSVC toolchain containing "
+        + ", ".join(VC_EXE_NAMES),
+        file=sys.stderr,
+    )
+    sys.exit(1)
+
+
+# To find the Universal CRT we look in a specific registry key for where all the
+# Universal CRTs are located and then sort them asciibetically to find the
+# newest version. While this sort of sorting isn't ideal, it is what vcvars does
+# so that's good enough for us.
+#
+# Returns a pair of (root, version) for the ucrt dir if found.
+def get_ucrt_dir():
+    registry = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
+    key_name = "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots"
+    registry_key = winreg.OpenKey(registry, key_name)
+    kits_root = Path(winreg.QueryValueEx(registry_key, "KitsRoot10")[0])
+
+    available_versions = [
+        entry.name
+        for entry in kits_root.joinpath("lib").iterdir()
+        if entry.name.startswith("10.") and entry.joinpath("ucrt").is_dir()
+    ]
+
+    max_version = max(available_versions) if available_versions else None
+    return kits_root, max_version
+
+
+# Vcvars finds the correct version of the Windows 10 SDK by looking for the
+# include `um\Windows.h` because sometimes a given version will only have UCRT
+# bits without the rest of the SDK. Since we only care about libraries and not
+# includes, we instead look for `um\x64\kernel32.lib`. Since the 32-bit and
+# 64-bit libraries are always installed together we only need to bother checking
+# x64, making this code a tiny bit simpler. Like we do for the Universal CRT, we
+# sort the possibilities asciibetically to find the newest one as that is what
+# vcvars does. Before doing that, we check the "WindowsSdkDir" and
+# "WindowsSDKVersion" environment variables set by vcvars to use the environment
+# sdk version if one is already configured.
+#
+# Returns a pair of (root, version).
+def get_sdk10_dir():
+    windows_sdk_dir = os.environ.get("WindowsSdkDir")
+    windows_sdk_version = os.environ.get("WindowsSDKVersion")
+    if windows_sdk_dir is not None and windows_sdk_version is not None:
+        return Path(windows_sdk_dir), windows_sdk_version.removesuffix("\\")
+
+    registry = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
+    key_name = "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v10.0"
+    registry_key = winreg.OpenKey(
+        registry, key_name, access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY
+    )
+    installation_folder = Path(
+        winreg.QueryValueEx(registry_key, "InstallationFolder")[0]
+    )
+
+    available_versions = [
+        entry.name
+        for entry in installation_folder.joinpath("lib").iterdir()
+        if entry.joinpath("um", "x64", "kernel32.lib").is_file()
+    ]
+
+    max_version = max(available_versions) if available_versions else None
+    return installation_folder, max_version
+
+
+def write_tool_json(out, tool):
+    j = json.dumps(
+        tool._asdict(),
+        indent=4,
+        default=lambda path: str(path),
+    )
+    out.write(j)
+
+
+# for use with the ewdk to grab the environment strings
+def get_ewdk_env(ewdkdir: Path):
+    """
+    Inspiration taken from the following:
+    http://pythonwise.blogspot.fr/2010/04/sourcing-shell-script.html (Miki Tebeka)
+    http://stackoverflow.com/questions/3503719/#comment28061110_3505826 (ahal)
+    """
+
+    # We need to write the script that will make the important variables available
+    with tempfile.NamedTemporaryFile(
+        prefix="VcVarsExtract", suffix=".bat", mode="w", delete=False
+    ) as tmp:
+        print("@echo off", file=tmp)
+        print("call %* > NUL", file=tmp)
+        print("set", file=tmp)
+
+    env_script = ewdkdir / "BuildEnv" / "SetupBuildEnv.cmd"
+    cmd = [tmp.name, env_script, "amd64"]
+    output = subprocess.check_output(cmd).decode("utf-8")
+
+    env = {}
+    for line in output.split("\r\n"):
+        if line and "=" in line:
+            first, second = line.split("=", 1)
+            env[first] = second
+
+    return env
+
+
+def find_with_ewdk(ewdkdir: Path):
+    env = get_ewdk_env(ewdkdir)
+
+    installation_path = Path(env["VSINSTALLDIR"])
+    vc_tools_version = env["VCToolsVersion"]
+    tools_path = installation_path / "VC" / "Tools" / "MSVC" / vc_tools_version
+    bin_path = tools_path / "bin" / "HostX64" / "x64"
+    lib_path = tools_path / "lib" / "x64"
+    include_path = tools_path / "include"
+
+    PATH = [bin_path]
+    LIB = [lib_path]
+    INCLUDE = [include_path]
+
+    ucrt = Path(env["UCRTContentRoot"])
+    ucrt_version = env.get("Version_Number")
+
+    vc_exe_paths = [bin_path / exe for exe in VC_EXE_NAMES]
+
+    if ucrt_version:
+        ucrt_bin_path = ucrt / "bin" / ucrt_version / "x64"
+        PATH.append(ucrt_bin_path)
+        LIB.append(ucrt / "lib" / ucrt_version / "ucrt" / "x64")
+        INCLUDE.append(ucrt / "include" / ucrt_version / "ucrt")
+
+        ucrt_exe_paths = [ucrt_bin_path / exe for exe in UCRT_EXE_NAMES]
+        ucrt_exe_paths = [exe if exe.exists() else None for exe in ucrt_exe_paths]
+    else:
+        ucrt_exe_paths = [None for exe in UCRT_EXE_NAMES]
+
+    sdk = Path(env["WindowsSdkDir"])
+    sdk_version = ucrt_version
+    if sdk_version:
+        PATH.append(sdk / "bin" / "x64")
+        LIB.append(sdk / "lib" / sdk_version / "um" / "x64")
+        INCLUDE.append(sdk / "include" / sdk_version / "um")
+        INCLUDE.append(sdk / "include" / sdk_version / "cppwinrt")
+        INCLUDE.append(sdk / "include" / sdk_version / "winrt")
+        INCLUDE.append(sdk / "include" / sdk_version / "shared")
+
+    return [
+        Tool(exe=bin_path / exe, LIB=LIB, PATH=PATH, INCLUDE=INCLUDE)
+        for exe in vc_exe_paths + ucrt_exe_paths
+    ]
+
+
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--cl", type=argparse.FileType("w"), required=True)
+    parser.add_argument("--cvtres", type=argparse.FileType("w"), required=True)
+    parser.add_argument("--lib", type=argparse.FileType("w"), required=True)
+    parser.add_argument("--ml64", type=argparse.FileType("w"), required=True)
+    parser.add_argument("--link", type=argparse.FileType("w"), required=True)
+    parser.add_argument("--rc", type=argparse.FileType("w"), required=True)
+    output = OutputJsonFiles(**vars(parser.parse_args()))
+
+    # If vcvars has been run, it puts these tools onto $PATH.
+    if "VCINSTALLDIR" in os.environ:
+        cl_exe, cvtres_exe, lib_exe, ml64_exe, link_exe = (
+            find_in_path(exe) for exe in VC_EXE_NAMES
+        )
+        rc_exe = find_in_path("rc.exe", is_optional=True)
+    elif "EWDKDIR" in os.environ:
+        cl_exe, cvtres_exe, lib_exe, ml64_exe, link_exe, rc_exe = find_with_ewdk(
+            Path(os.environ["EWDKDIR"])
+        )
+    else:
+        cl_exe, cvtres_exe, lib_exe, ml64_exe, link_exe, rc_exe = (
+            find_with_vswhere_exe()
+        )
+
+    write_tool_json(output.cl, cl_exe)
+    write_tool_json(output.cvtres, cvtres_exe)
+    write_tool_json(output.lib, lib_exe)
+    write_tool_json(output.ml64, ml64_exe)
+    write_tool_json(output.link, link_exe)
+    write_tool_json(output.rc, rc_exe)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/toolchains/no_toolchain.bzl b/buck2/prelude/toolchains/no_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/no_toolchain.bzl
@@ -0,0 +1,18 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _no_toolchain(_ctx: AnalysisContext) -> list[Provider]:
+    return [DefaultInfo()]
+
+# no_toolchain doesn't return any *ToolchainInfo providers
+# it's useful when a toolchain is optional, e.q. CxxToolchain for Python and Go rules.
+no_toolchain = rule(
+    impl = _no_toolchain,
+    attrs = {},
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/ocaml.bzl b/buck2/prelude/toolchains/ocaml.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/ocaml.bzl
@@ -0,0 +1,73 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    "@prelude//ocaml:ocaml_toolchain_types.bzl",
+    "OCamlPlatformInfo",
+    "OCamlToolchainInfo",
+)
+load("@prelude//os_lookup:defs.bzl", "Os", "OsLookup")
+
+_EXEC_OS_TYPE = attrs.default_only(attrs.exec_dep(default = "prelude//os_lookup/targets:os_lookup"))
+
+def _system_ocaml_toolchain_impl(ctx):
+    """
+    A very simple toolchain that is hardcoded to the current environment.
+    """
+
+    runtime_dep_link_flags = ["-ldl", "-lpthread"]
+    exec_os = ctx.attrs._exec_os_type[OsLookup].os
+    if exec_os == Os("macos"):
+        runtime_dep_link_flags.extend(["-L/opt/homebrew/lib", "-lzstd"])
+    elif exec_os == Os("linux"):
+        # OCaml 5.3's runtime archive uses zstd for marshalled data. Linux
+        # finds the system library without an explicit -L flag.
+        runtime_dep_link_flags.append("-lzstd")
+
+    return [
+        DefaultInfo(),
+        OCamlToolchainInfo(
+            ocaml_compiler = RunInfo(args = ["ocamlopt.opt"]),
+            # "Partial linking" (via `ocamlopt.opt -output-obj`) emits calls to
+            # `ld -r -o`. If not `None`, this is the `ld` that will be invoked;
+            # the default is to use whatever `ld` is in the environment. See
+            # [Note: What is `binutils_ld`?] in `providers.bzl`.
+            binutils_ld = None,
+            # `ocamlopt.opt` makes calls to `as`. If this config parameter is
+            # `None` those calls will resolve to whatever `as` is in the
+            # environment. If not `None` then the provided value will be what's
+            # invoked.
+            binutils_as = None,
+            dep_tool = RunInfo(args = ["ocamldep.opt"]),
+            yacc_compiler = RunInfo(args = ["ocamlyacc"]),
+            interop_includes = None,
+            menhir_compiler = RunInfo(args = ["menhir"]),
+            lex_compiler = RunInfo(args = ["ocamllex.opt"]),
+            libc = None,
+            ocaml_bytecode_compiler = RunInfo(args = ["ocamlc.opt"]),
+            # `ocamldebug` is bytecode intended to be run by `ocamlrun`. There
+            # is no "debugger" executable (but then `debug` is not referenced by
+            # the ocaml build rules) so `None` will do for this.
+            debug = None,
+            warnings_flags = "-4-29-35-41-42-44-45-48-50-58-70",
+            ocaml_compiler_flags = [],  # e.g. "-opaque"
+            ocamlc_flags = [],
+            ocamlopt_flags = [],
+            runtime_dep_link_flags = runtime_dep_link_flags,
+            runtime_dep_link_extras = [],
+        ),
+        OCamlPlatformInfo(name = "x86_64"),
+    ]
+
+system_ocaml_toolchain = rule(
+    impl = _system_ocaml_toolchain_impl,
+    attrs = {
+        "_exec_os_type": _EXEC_OS_TYPE,
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/python.bzl b/buck2/prelude/toolchains/python.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/python.bzl
@@ -0,0 +1,299 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:prelude.bzl", "native")
+load(
+    "@prelude//os_lookup:defs.bzl",
+    "Os",
+    "OsLookup",
+)
+load(
+    "@prelude//python:python_wheel_toolchain.bzl",
+    "PythonWheelToolchainInfo",
+)
+load(
+    "@prelude//python:toolchain.bzl",
+    "PythonPlatformInfo",
+    "PythonToolchainInfo",
+)
+load(
+    "@prelude//python_bootstrap:python_bootstrap.bzl",
+    "PythonBootstrapToolchainInfo",
+)
+
+def _system_python_wheel_toolchain_impl(ctx):
+    return [
+        DefaultInfo(),
+        PythonWheelToolchainInfo(
+            abi = ctx.attrs.abi,
+            platform = ctx.attrs.platform,
+            python = ctx.attrs.python,
+        ),
+    ]
+
+system_python_wheel_toolchain = rule(
+    impl = _system_python_wheel_toolchain_impl,
+    attrs = {
+        "abi": attrs.string(default = "none"),
+        "platform": attrs.string(default = "linux_x86_64"),
+        "python": attrs.string(default = "py3"),
+    },
+    is_toolchain_rule = True,
+)
+
+_INTERPRETER = select({
+    "DEFAULT": "python3",
+    "config//os:windows": "python.exe",
+})
+
+_EXEC_OS_TYPE = attrs.default_only(attrs.exec_dep(default = "prelude//os_lookup/targets:os_lookup"))
+
+def _interpreter_for_os(os: Os) -> str:
+    return "python.exe" if os == Os("windows") else "python3"
+
+def _system_python_bootstrap_toolchain_impl(ctx):
+    # the interpreter name needs to be selected based on the exec platform, not the target
+    interpreter = ctx.attrs.interpreter or _interpreter_for_os(ctx.attrs._exec_os_type[OsLookup].os)
+    return [
+        DefaultInfo(),
+        PythonBootstrapToolchainInfo(interpreter = interpreter),
+    ]
+
+def _python_bootstrap_toolchain_impl(ctx):
+    return [
+        DefaultInfo(),
+        PythonBootstrapToolchainInfo(interpreter = ctx.attrs.interpreter[RunInfo].args),
+    ]
+
+# Creates a new bootstrap toolchain using Python that is installed on your system.
+# You may use it in your toolchain cell as follows:
+#
+# ```bzl
+# load("@prelude//toolchains:python.bzl", "system_python_bootstrap_toolchain")
+#
+# system_python_bootstrap_toolchain(
+#     name = "python_bootstrap", # the default name rules look for
+#     visibility = ["PUBLIC"],
+# )
+# ```
+system_python_bootstrap_toolchain = rule(
+    impl = _system_python_bootstrap_toolchain_impl,
+    attrs = {
+        "interpreter": attrs.option(attrs.string(), default = None),
+        "_exec_os_type": _EXEC_OS_TYPE,
+    },
+    is_toolchain_rule = True,
+)
+
+python_bootstrap_toolchain = rule(
+    impl = _python_bootstrap_toolchain_impl,
+    attrs = {
+        "interpreter": attrs.dep(providers = [RunInfo]),
+    },
+    is_toolchain_rule = True,
+    doc = """
+        A bootstrap toolchain using the provided interpreter.
+
+        If you want to use whatever's available on $PATH, use `system_python_bootstrap_toolchain`.
+    """,
+)
+
+def _system_python_toolchain_impl(ctx):
+    """
+    A very simple toolchain that is hardcoded to the current environment.
+    """
+
+    # the "host" (exec platform) interpreter needs to be selected based on the exec platform
+    host_interpreter = ctx.attrs.host_interpreter or _interpreter_for_os(ctx.attrs._exec_os_type[OsLookup].os)
+
+    return [
+        DefaultInfo(),
+        PythonToolchainInfo(
+            binary_linker_flags = ctx.attrs.binary_linker_flags,
+            linker_flags = ctx.attrs.linker_flags,
+            host_interpreter = RunInfo(args = [host_interpreter]),
+            interpreter = RunInfo(args = [ctx.attrs.interpreter]),
+            compile = RunInfo(args = ["echo", "COMPILEINFO"]),
+            package_style = "inplace",
+            pex_extension = ctx.attrs.pex_extension,
+            native_link_strategy = "separate",
+            type_checker = ctx.attrs.type_checker[RunInfo] if ctx.attrs.type_checker != None else None,
+        ),
+        PythonPlatformInfo(name = "x86_64"),
+    ]
+
+system_python_toolchain = rule(
+    impl = _system_python_toolchain_impl,
+    attrs = {
+        "binary_linker_flags": attrs.default_only(attrs.list(attrs.arg(), default = [])),
+        "host_interpreter": attrs.option(
+            attrs.string(),
+            default = None,
+            doc = "Interpreter to run actions on the exec platform. Defaults to the usual interpreter name for the exec platform.",
+        ),
+        "interpreter": attrs.string(default = _INTERPRETER),
+        "linker_flags": attrs.default_only(attrs.list(attrs.arg(), default = [])),
+        "pex_extension": attrs.string(default = ".pex"),
+        "type_checker": attrs.option(
+            attrs.exec_dep(providers = [RunInfo]),
+            default = None,
+            doc = "See `PythonToolchainInfo.type_checker` for the executable contract.",
+        ),
+        "_exec_os_type": _EXEC_OS_TYPE,
+    },
+    is_toolchain_rule = True,
+)
+
+def python_toolchain_impl(ctx) -> list[Provider]:
+    return [
+        DefaultInfo(),
+        PythonToolchainInfo(
+            interpreter = ctx.attrs.interpreter[RunInfo],
+            host_interpreter = ctx.attrs.host_interpreter[RunInfo],
+            compile = ctx.attrs.compile[DefaultInfo].default_outputs[0],
+            package_style = "inplace",
+            native_link_strategy = "separate",
+            linker_flags = [],
+            binary_linker_flags = [],
+            extension_linker_flags = ctx.attrs.extension_linker_flags,
+            type_checker = ctx.attrs.type_checker[RunInfo] if ctx.attrs.type_checker != None else None,
+        ),
+        PythonPlatformInfo(name = "x86_64"),
+    ]
+
+_python_toolchain = rule(
+    impl = python_toolchain_impl,
+    attrs = {
+        "compile": attrs.default_only(attrs.exec_dep(default = "prelude//python/tools:compile.py")),
+        "extension_linker_flags": attrs.list(attrs.arg()),
+        "host_interpreter": attrs.exec_dep(
+            providers = [RunInfo],
+            doc = """
+            Interpreter used to run build-time actions, such as compiling bytecode. Typically the
+            same label as `interpreter` (as defaulted by the python_toolchain wrapper macro), but
+            uses a separate attr to transition to exec configuration.
+            """,
+        ),
+        "interpreter": attrs.dep(providers = [RunInfo]),
+        "type_checker": attrs.option(
+            attrs.exec_dep(providers = [RunInfo]),
+            default = None,
+            doc = "See `PythonToolchainInfo.type_checker` for the executable contract.",
+        ),
+    },
+    is_toolchain_rule = True,
+    doc = "A Python toolchain that can build Python extensions, given an interpreter and the extra linker flags to use with it. See `remote_python_toolchain` for a toolchain that configures the interpreter and linker flags for you.",
+)
+
+def python_toolchain(name: str, interpreter, host_interpreter = None, **kwargs) -> None:
+    """
+    A Python toolchain that can build Python extensions, given an interpreter and
+    the extra linker flags to use with it. See `remote_python_toolchain` for a
+    toolchain that configures the interpreter and linker flags for you.
+    """
+    _python_toolchain(name = name, interpreter = interpreter, host_interpreter = interpreter if host_interpreter == None else host_interpreter, **kwargs)
+
+# archives for 3.13
+# update this by running `prelude//python/tools:discover_python_archives.sh`
+CPYTHON_ARCHIVE = {
+    "linux": {
+        "arm64": {
+            "sha256": "829d615905b5ae8c50353f2ceb3d6665793442d4cbc64503bc9b27b5b9f6fb8a",
+            "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20250807/cpython-3.13.6+20250807-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz",
+        },
+        "x86_64": {
+            "sha256": "e3e280d4b1ead63de6ebc9816de71792fc8c71b7a6a999ea82f937047beba037",
+            "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20250807/cpython-3.13.6+20250807-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz",
+        },
+    },
+    "macos": {
+        "arm64": {
+            "sha256": "c57e48145722a87e34a50a2c31d6b11f0830e62e26d759c11b6606a6a80e6243",
+            "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20250807/cpython-3.13.6+20250807-aarch64-apple-darwin-install_only_stripped.tar.gz",
+        },
+        "x86_64": {
+            "sha256": "7caed8ea779dcc5d091955628455823cb0e91587703d8b6f7dd285fb2b44d1e0",
+            "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20250807/cpython-3.13.6+20250807-x86_64-apple-darwin-install_only_stripped.tar.gz",
+        },
+    },
+    "windows": {
+        "arm64": {
+            "sha256": "a24c09048d1c20ed01e58e7e59a5e43b79cb7a9f36c067fc24e17649e4301d54",
+            "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20250807/cpython-3.13.6+20250807-aarch64-pc-windows-msvc-install_only_stripped.tar.gz",
+        },
+        "x86_64": {
+            "sha256": "0de6eb2cb66211967874b0fb47cfc0299102e8a805f5319e108121e314083066",
+            "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20250807/cpython-3.13.6+20250807-x86_64-pc-windows-msvc-install_only_stripped.tar.gz",
+        },
+    },
+}
+
+def remote_python_toolchain(
+    name: str, visibility: list[str], cpython_urls: dict[str, dict[str, dict[str, str]]] = CPYTHON_ARCHIVE, bootstrap: bool = True, **kwargs
+) -> None:
+    """
+    Sets up a Python toolchain by using a pre-built CPython installation, downloaded from the [python-build-standalone project](https://github.com/astral-sh/python-build-standalone).
+
+    If `bootstrap` is set to `True`, this will also set up a bootstrap toolchain using the same interpreter.
+    Other arguments, including `type_checker`, are forwarded to `python_toolchain`.
+    """
+
+    native.http_archive(
+        name = "cpython_archive",
+        urls = [
+            select({
+                "prelude//os:{}".format(os): select({"prelude//cpu:{}".format(cpu): archive["url"] for cpu, archive in value.items()})
+                for os, value in cpython_urls.items()
+            })
+        ],
+        sha256 = select({
+            "prelude//os:{}".format(os): select({"prelude//cpu:{}".format(cpu): archive["sha256"] for cpu, archive in value.items()})
+            for os, value in cpython_urls.items()
+        }),
+        strip_prefix = "python",
+        sub_targets = {
+            "include": [
+                select({"DEFAULT": "include/python3.13", "prelude//os:windows": "include"}),
+            ],
+            "lib": [select({"DEFAULT": "lib", "prelude//os:windows": "libs"})],
+            "python": [
+                select({"DEFAULT": "bin/python", "prelude//os:windows": "python.exe"}),
+            ],
+        },
+    )
+    native.command_alias(
+        name = "cpython",
+        exe = ":cpython_archive[python]",
+        visibility = visibility,
+        resources = [":cpython_archive"],
+    )
+
+    if bootstrap:
+        python_bootstrap_toolchain(
+            name = "{}_bootstrap".format(name),
+            visibility = visibility,
+            interpreter = ":cpython",
+        )
+
+    native.genrule(
+        name = "libpython_symbols",
+        out = "linker_args",
+        # TODO: is this necessary on Windows?
+        cmd = '$(exe_target prelude//python/tools:gather_libpython_symbols) "$OUT"',
+    )
+
+    python_toolchain(
+        name = name,
+        visibility = visibility,
+        interpreter = ":cpython",
+        extension_linker_flags = select({
+            "DEFAULT": ["-L$(location :cpython_archive[lib])", "@$(location :libpython_symbols)"],
+            "prelude//os:windows": ["/LIBPATH:$(location :cpython_archive[lib])"],
+        }),
+        **kwargs,
+    )
diff --git a/buck2/prelude/toolchains/remote_test_execution.bzl b/buck2/prelude/toolchains/remote_test_execution.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/remote_test_execution.bzl
@@ -0,0 +1,41 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:re_test_common.bzl", "re_test_common")
+load("@prelude//tests:remote_test_execution_toolchain.bzl", "RemoteTestExecutionToolchainInfo")
+load("@prelude//utils:utils.bzl", "map_val")
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    default_profile = map_val(ctx.attrs.profiles.get, ctx.attrs.default_profile)
+    if ctx.attrs.default_run_as_bundle != None:
+        default_run_as_bundle = ctx.attrs.default_run_as_bundle
+    else:
+        default_run_as_bundle = bool(default_profile)
+
+    return [
+        DefaultInfo(),
+        RemoteTestExecutionToolchainInfo(
+            default_profile = default_profile,
+            default_run_as_bundle = default_run_as_bundle,
+            profiles = ctx.attrs.profiles,
+        ),
+    ]
+
+remote_test_execution_toolchain = rule(
+    impl = _impl,
+    is_toolchain_rule = True,
+    attrs = {
+        "default_profile": attrs.option(attrs.string(), default = None),
+        "default_run_as_bundle": attrs.option(attrs.bool(), default = None),
+        "profiles": attrs.dict(
+            key = attrs.string(),
+            value = attrs.option(re_test_common.opts_for_tests_arg()),
+            default = {},
+        ),
+    },
+)
diff --git a/buck2/prelude/toolchains/rust.bzl b/buck2/prelude/toolchains/rust.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/rust.bzl
@@ -0,0 +1,80 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//rust:rust_toolchain.bzl", "PanicRuntime", "RustToolchainInfo")
+
+_DEFAULT_TRIPLE = select({
+    "prelude//os:linux": select({
+        "prelude//cpu:arm64": "aarch64-unknown-linux-gnu",
+        "prelude//cpu:riscv64": "riscv64gc-unknown-linux-gnu",
+        "prelude//cpu:x86_64": "x86_64-unknown-linux-gnu",
+    }),
+    "prelude//os:macos": select({
+        "prelude//cpu:arm64": "aarch64-apple-darwin",
+        "prelude//cpu:x86_64": "x86_64-apple-darwin",
+    }),
+    "prelude//os:windows": select({
+        "prelude//cpu:arm64": select({
+            # Rustup's default ABI for the host on Windows is MSVC, not GNU.
+            # When you do `rustup install stable` that's the one you get. It
+            # makes you opt in to GNU by `rustup install stable-gnu`.
+            "DEFAULT": "aarch64-pc-windows-msvc",
+            "prelude//abi:gnu": "aarch64-pc-windows-gnu",
+            "prelude//abi:msvc": "aarch64-pc-windows-msvc",
+        }),
+        "prelude//cpu:x86_64": select({
+            "DEFAULT": "x86_64-pc-windows-msvc",
+            "prelude//abi:gnu": "x86_64-pc-windows-gnu",
+            "prelude//abi:msvc": "x86_64-pc-windows-msvc",
+        }),
+    }),
+})
+
+def _system_rust_toolchain_impl(ctx):
+    return [
+        DefaultInfo(),
+        RustToolchainInfo(
+            allow_lints = ctx.attrs.allow_lints,
+            clippy_driver = RunInfo(args = ["clippy-driver"]),
+            clippy_toml = ctx.attrs.clippy_toml[DefaultInfo].default_outputs[0] if ctx.attrs.clippy_toml else None,
+            compiler = RunInfo(args = ["rustc"]),
+            default_edition = ctx.attrs.default_edition,
+            panic_runtime = PanicRuntime("unwind"),
+            deny_lints = ctx.attrs.deny_lints,
+            doctests = ctx.attrs.doctests,
+            nightly_features = ctx.attrs.nightly_features,
+            report_unused_deps = ctx.attrs.report_unused_deps,
+            rustc_binary_flags = ctx.attrs.rustc_binary_flags,
+            rustc_flags = ctx.attrs.rustc_flags,
+            rustc_target_triple = ctx.attrs.rustc_target_triple,
+            rustc_test_flags = ctx.attrs.rustc_test_flags,
+            rustdoc = RunInfo(args = ["rustdoc"]),
+            rustdoc_flags = ctx.attrs.rustdoc_flags,
+            warn_lints = ctx.attrs.warn_lints,
+        ),
+    ]
+
+system_rust_toolchain = rule(
+    impl = _system_rust_toolchain_impl,
+    attrs = {
+        "allow_lints": attrs.list(attrs.string(), default = []),
+        "clippy_toml": attrs.option(attrs.dep(providers = [DefaultInfo]), default = None),
+        "default_edition": attrs.option(attrs.string(), default = None),
+        "deny_lints": attrs.list(attrs.string(), default = []),
+        "doctests": attrs.bool(default = False),
+        "nightly_features": attrs.bool(default = True),
+        "report_unused_deps": attrs.bool(default = False),
+        "rustc_binary_flags": attrs.list(attrs.arg(), default = []),
+        "rustc_flags": attrs.list(attrs.arg(), default = []),
+        "rustc_target_triple": attrs.string(default = _DEFAULT_TRIPLE),
+        "rustc_test_flags": attrs.list(attrs.arg(), default = []),
+        "rustdoc_flags": attrs.list(attrs.arg(), default = []),
+        "warn_lints": attrs.list(attrs.string(), default = []),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/toolchains/zip_file.bzl b/buck2/prelude/toolchains/zip_file.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/toolchains/zip_file.bzl
@@ -0,0 +1,30 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//zip_file:zip_file_toolchain.bzl", "ZipFileToolchainInfo")
+
+def zip_file_toolchain(name, **kwargs):
+    kwargs["create_zip"] = "prelude//toolchains/android/src/com/facebook/buck/features/zip/rules/utils:zip_binary"
+
+    _zip_file_toolchain_rule(name = name, **kwargs)
+
+def _zip_file_toolchain_rule_impl(ctx):
+    return [
+        DefaultInfo(),
+        ZipFileToolchainInfo(
+            create_zip = ctx.attrs.create_zip[RunInfo],
+        ),
+    ]
+
+_zip_file_toolchain_rule = rule(
+    attrs = {
+        "create_zip": attrs.dep(providers = [RunInfo]),
+    },
+    impl = _zip_file_toolchain_rule_impl,
+    is_toolchain_rule = True,
+)
diff --git a/buck2/prelude/tools/audit_providers_universe.bxl b/buck2/prelude/tools/audit_providers_universe.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/tools/audit_providers_universe.bxl
@@ -0,0 +1,19 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _impl(ctx):
+    ts = ctx.target_universe(ctx.cli_args.universe).lookup(ctx.cli_args.target)
+    ctx.output.print(pstr({t: a.providers() for t, a in ctx.analysis(ts).items()}))
+
+run = bxl_main(
+    impl = _impl,
+    cli_args = {
+        "target": cli_args.target_label(),
+        "universe": cli_args.target_label(),
+    },
+)
diff --git a/buck2/prelude/transitions/constraint_override_registry.bzl b/buck2/prelude/transitions/constraint_override_registry.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/transitions/constraint_override_registry.bzl
@@ -0,0 +1,24 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+ConstraintOverrideRegistryInfo = provider(
+    fields = {"refs": provider_field(struct)},
+)
+
+def constraint_override_refs() -> dict[str, str]:
+    overrides = read_root_config("buck2", "platforms", "") + "," + read_root_config("buck2", "constraints", "")
+    return {override.strip(): override.strip() for override in overrides.split(",") if override.strip()}
+
+def _constraint_override_registry_impl(ctx: AnalysisContext) -> list[Provider]:
+    return [DefaultInfo(), ConstraintOverrideRegistryInfo(refs = struct(**ctx.attrs.refs))]
+
+constraint_override_registry = rule(
+    impl = _constraint_override_registry_impl,
+    attrs = {"refs": attrs.dict(attrs.string(), attrs.dep())},
+    is_configuration_rule = True,
+)
diff --git a/buck2/prelude/transitions/constraint_overrides.bzl b/buck2/prelude/transitions/constraint_overrides.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/transitions/constraint_overrides.bzl
@@ -0,0 +1,229 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cfg/modifier:name.bzl", "cfg_name")
+# NOTE: At the moment, target platforms and constraint values can't be propagated via build rule
+#       attributes all the way to configuration transitions. The reason is that the transition
+#       function is invoked before the rule, so any PlatformInfo and ConstraintValueInfo providers
+#       present in the rule attributes aren't resolved at this time.
+#
+#       Because of this, the list of possible target platforms and constraint values is encoded
+#       here in the form of config settings with lists of comma-separated elements. Specifically,
+#       the configuration transition relies on the following config settings:
+#
+#           * buck2.platforms
+#           * buck2.constraints
+#           * buck2.passthrough_constraints
+#
+#       buck2.platforms and buck2.constraints list all possible target platforms and constraint
+#       values, and buck2.passthrough_constraints lists constraint settings to preserve when
+#       applying the configuration transition. The use of read_config avoids hard-coding these
+#       repo-specific configuration rules into the prelude.
+load("@prelude//python:transitions.bzl", "python_transitions")
+load("@prelude//transitions:constraint_override_registry.bzl", "ConstraintOverrideRegistryInfo", "constraint_override_refs")
+
+_config = struct(
+    passthrough_constraints = read_root_config("buck2", "passthrough_constraints", ""),
+    split = lambda values: [value.strip() for value in values.split(",") if value.strip()],
+)
+
+def _passthrough_constraints() -> list[str]:
+    return _config.split(_config.passthrough_constraints)
+
+def _check(target: str) -> str:
+    """
+    Checks that a build target is fully qualified.
+
+    Because of the context in which the transition function is invoked, it can't make use of
+    certain functions that are only available in a build file context. These functions include
+    package_name and get_cell_name. For this reason all build targets must be fully qualified, in
+    the format cell//package:name, so that they may be used for look-up in refs.
+
+    Args:
+        target  Build  target.
+
+    Returns:
+        Fully qualified build target.
+    """
+    message = "Build target must be fully qualified, expected format cell//package:name but received: {target}".format(
+        target = target,
+    )
+    if target.count("//") != 1:
+        fail(message)
+    cell, path = target.split("//")
+    if len(cell) == 0:
+        fail(message)
+    if path.count(":") != 1:
+        fail(message)
+    package, name = path.split(":")
+    return "{cell}//{package}:{name}".format(cell = cell, package = package, name = name)
+
+def _resolve(refs: struct, attrs: struct) -> dict[str, PlatformInfo | list[ConstraintValueInfo] | None]:
+    """
+    Validates and prepares arguments for business logic in constraint_overrides.apply, which
+    implements the transition function.
+
+    All target platforms and constraint values present in attrs must also be present in refs, which
+    contains the list of all possible target platforms and constraint values. If they're not, the
+    configuration transition fails with an error message saying the override is not supported.
+
+    Args:
+
+        refs   struct containing the list of all possible target platforms and constraint values,
+               stored as a mapping from build targets to configured target labels with PlatformInfo
+               and ConstraintValueInfo providers.
+        attrs  Struct containing the platform_override and constraint_overrides arguments to the
+               build rule to which the configuration transition is being applied.
+
+    Returns:
+        dict containing key-value arguments to passy to constraint_overrides.apply.
+    """
+    args = {}
+
+    # Resolve target platform override.
+    override = None
+    if hasattr(attrs, "platform_override") and attrs.platform_override != None:
+        override = _check(attrs.platform_override)
+    args["platform"] = None
+    if override:
+        if not hasattr(refs, override):
+            fail(
+                "Target platform override not supported: {override}".format(
+                    override = override,
+                )
+            )
+        ref = getattr(refs, override)
+        args["platform"] = ref[PlatformInfo]
+
+    # Resolve constraint value overrides.
+    overrides = []
+    if hasattr(attrs, "constraint_overrides") and attrs.constraint_overrides != None:
+        overrides = [_check(override) for override in attrs.constraint_overrides if override != None]
+    args["constraints"] = []
+    for override in overrides:
+        if not hasattr(refs, override):
+            fail(
+                "Constraint value override not supported: {override}".format(
+                    override = override,
+                )
+            )
+        ref = getattr(refs, override)
+        args["constraints"].append(ref[ConstraintValueInfo])
+
+    return args
+
+def _apply(old_platform: PlatformInfo, *, platform: PlatformInfo | None = None, constraints: list[ConstraintValueInfo] = []) -> PlatformInfo:
+    """
+    Applies the business logic to implement the constraint_overrides configuration transition.
+
+    The outgoing target platform is constructed by:
+
+        1. Initializing it from old_platform, if platform is None, or from platform if not None;
+        2. Applying the constraint values in old_platform whose constraint settings match any of
+           those listed in buck2.passthrough_constraints; and
+        3. Applying the constraint values present in constraints.
+
+    If platform is None the constraint values in old_platform are preserved unless overridden by
+    constraint values in constraints. If platform is not None the constraint values in old_platform
+    are discarded unless:
+
+        * Their constraint settings are listed in buck2.passthrough_constraints; and
+        * They're not overridden by a constraint value in constraints.
+
+    Args:
+
+        old_platform  Incoming target platform. This is the target platform prior to the
+                      configuration transition.
+        platform      Target platform to use as a basis for the outgoing target platform. If None,
+                      old_platform is used instead.
+        constraints   List of constraint values to apply to the target platform. These constraint
+                      values are applied on top of either old_platform or platform.
+
+    Returns:
+        Outgoing target platform.
+    """
+
+    # Store passthrough constraint values.
+    old_constraints = {str(setting): constraint for setting, constraint in old_platform.configuration.constraints.items()}
+    old_constraints = [old_constraints[setting] for setting in _passthrough_constraints() if setting in old_constraints]
+
+    # Switch target platform.
+    platform = platform or old_platform
+
+    # Add passthrough constraint values and apply constraint value overrides.
+    new_constraints = {label: constraint for label, constraint in platform.configuration.constraints.items()}
+    for constraint in old_constraints:
+        new_constraints[constraint.setting.label] = constraint
+    for constraint in constraints:
+        new_constraints[constraint.setting.label] = constraint
+
+    new_cfg = ConfigurationInfo(
+        constraints = new_constraints,
+        values = platform.configuration.values,
+    )
+
+    label = platform.label
+    if constraints:
+        label = cfg_name(new_cfg)
+
+    new_platform = PlatformInfo(
+        label = label,
+        configuration = new_cfg,
+    )
+    return new_platform
+
+def _impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:
+    if hasattr(refs, "_constraint_override_registry"):
+        refs = refs._constraint_override_registry[ConstraintOverrideRegistryInfo].refs
+    args = _resolve(refs, attrs)
+    if args["platform"] == None and not args["constraints"]:
+        return platform
+    return _apply(platform, **args)
+
+# Chain the override impl with python specific transitions.
+# We do this here because the constraint_override transition relies on autogenerated refs
+# Its easier to add the opt-by-default specific ones here than vice-versa
+def _python_impl(platform: PlatformInfo, refs: struct, attrs: struct) -> PlatformInfo:
+    # @oss-disable[end= ]: platform = python_transitions.transition_opt_by_default_impl(platform, refs, attrs)
+    return _impl(platform, refs, attrs)
+
+_refs = constraint_override_refs()
+# Registry dependencies enforce visibility, unlike direct transition refs.
+_registry = read_root_config("buck2", "constraint_override_registry", "")
+_transition_refs = {"_constraint_override_registry": _registry} if _registry else _refs
+_python_refs = {k: v for k, v in _transition_refs.items()}
+# @oss-disable[end= ]: _python_refs.update(python_transitions.refs())
+
+_attributes = {
+    "constraint_overrides": attrs.list(attrs.option(attrs.string()), default = []),
+    "platform_override": attrs.option(attrs.string(), default = None),
+}
+
+_python_attributes = {k: v for k, v in _attributes.items()}
+# @oss-disable[end= ]: _python_attributes.update(python_transitions.attrs())
+
+_transition = transition(
+    impl = _impl,
+    refs = _transition_refs,
+    attrs = _attributes.keys(),
+)
+
+_python_transition = transition(
+    impl = _python_impl,
+    refs = _python_refs,
+    attrs = _python_attributes.keys(),
+)
+
+constraint_overrides = struct(
+    refs = _refs,
+    resolve = _resolve,
+    apply = _apply,
+    transition = _transition,
+    attributes = _attributes,
+    python_transition = _python_transition,
+)
diff --git a/buck2/prelude/transitions/utils.bzl b/buck2/prelude/transitions/utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/transitions/utils.bzl
@@ -0,0 +1,67 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//cfg/modifier:name.bzl", "cfg_name")
+
+def _filtered_platform_constraints(platform: PlatformInfo, constraint_settings_labels_to_remove: list[TargetLabel]) -> dict[TargetLabel, ConstraintValueInfo]:
+    return {
+        constraint_setting_label: constraint_setting_value
+        for (constraint_setting_label, constraint_setting_value) in platform.configuration.constraints.items()
+        if constraint_setting_label not in constraint_settings_labels_to_remove
+    }
+
+def _get_constraint_value(platform: PlatformInfo, constraint: ConstraintSettingInfo) -> [None, ConstraintValueInfo]:
+    return platform.configuration.constraints.get(constraint.label)
+
+def _modify_constraints_transition_impl(ctx: AnalysisContext) -> list[Provider]:
+    add = [dep[ConstraintValueInfo] for dep in ctx.attrs.add]
+    remove = [dep[ConstraintValueInfo] for dep in ctx.attrs.remove]
+
+    def tr_impl(platform: PlatformInfo) -> PlatformInfo:
+        new_constraints = dict(platform.configuration.constraints)
+
+        for constraint in remove:
+            new_constraints.pop(constraint.setting.label, None)
+        for constraint in add:
+            new_constraints[constraint.setting.label] = constraint
+        if new_constraints == platform.configuration.constraints:
+            return platform
+
+        configuration = ConfigurationInfo(
+            constraints = new_constraints,
+            values = platform.configuration.values,
+        )
+
+        # Named by its constraints, as the configurations that modifiers make
+        # are, so that it is the same configuration however it is reached.
+        return PlatformInfo(
+            label = cfg_name(configuration),
+            configuration = configuration,
+        )
+
+    return [
+        DefaultInfo(),
+        TransitionInfo(
+            impl = tr_impl,
+        ),
+    ]
+
+_modify_constraints_transition = rule(
+    impl = _modify_constraints_transition_impl,
+    attrs = {
+        "add": attrs.list(attrs.dep(), default = []),
+        "remove": attrs.list(attrs.dep(), default = []),
+    },
+    is_configuration_rule = True,
+)
+
+transition_utils = struct(
+    filtered_platform_constraints = _filtered_platform_constraints,
+    get_constraint_value = _get_constraint_value,
+    modify_constraints_transition = _modify_constraints_transition,
+)
diff --git a/buck2/prelude/unix/providers.bzl b/buck2/prelude/unix/providers.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/unix/providers.bzl
@@ -0,0 +1,54 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifacts.bzl", "ArtifactExt")
+load("@prelude//linking:shared_libraries.bzl", "SharedLibraries")
+load("@prelude//python:manifest.bzl", "ManifestInfo")
+load("@prelude//python:python.bzl", "PythonLibraryInfo")
+
+# Provider representing components that can be added to a "unix" env (e.g.
+# binaries in `bin/`, native libs in `lib/`, and Python modules under
+# `lib/python*/site-packages`).
+UnixEnv = record(
+    label = field(Label),
+    # Third-party builds to install into the env (non-transitive).
+    third_party_builds = field(list[ArtifactExt], []),
+    # Python libraries to install (non-transitive).
+    python_libs = field(list[PythonLibraryInfo], []),
+    # Native libs to install (non-transitive).
+    native_libs = field(list[SharedLibraries], []),
+    # Binaries to install.
+    binaries = field(list[ManifestInfo], []),
+    # Raw paths to install.
+    paths = field(list[(str, ArtifactExt)], []),
+    patterns = field(list[(str, ArtifactExt, str)], []),
+)
+
+UnixEnvTSet = transitive_set()
+
+UnixEnvInfo = provider(
+    fields = dict(
+        _tset = provider_field(UnixEnvTSet),
+    ),
+)
+
+def create_unix_env_info(actions: AnalysisActions, env: UnixEnv | None = None, children: list[UnixEnvInfo] = [], deps: list[Dependency] = []) -> UnixEnvInfo:
+    all_children = []
+    for child in children:
+        all_children.append(child._tset)
+    for dep in deps:
+        child = dep.get(UnixEnvInfo)
+        if child != None:
+            all_children.append(child._tset)
+    kwargs = {}
+    if env != None:
+        kwargs["value"] = env
+    kwargs["children"] = all_children
+    return UnixEnvInfo(
+        _tset = actions.tset(UnixEnvTSet, **kwargs),
+    )
diff --git a/buck2/prelude/user/all.bzl b/buck2/prelude/user/all.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/user/all.bzl
@@ -0,0 +1,33 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//android/user:android_emulators.bzl", _android_emulators_spec = "registration_spec")
+load("@prelude//cxx/user:cxx_toolchain_override.bzl", _cxx_toolchain_override_spec = "cxx_toolchain_override_registration_spec")
+load("@prelude//cxx/user:link_group_map.bzl", _link_group_map_spec = "registration_spec")
+load("@prelude//http_archive:extract_archive.bzl", _extract_archive_spec = "registration_spec")
+load("@prelude//ide_integrations/xcode:xcode_files.bzl", _xcode_files_spec = "registration_spec")
+load(":cxx_headers_bundle.bzl", _cxx_headers_bundle_spec = "registration_spec")
+load(":write_file.bzl", _write_file_spec = "registration_spec")
+
+_all_specs = [
+    _extract_archive_spec,
+    _android_emulators_spec,
+    _link_group_map_spec,
+    _cxx_headers_bundle_spec,
+    _cxx_toolchain_override_spec,
+    _write_file_spec,
+    _xcode_files_spec,
+]
+
+rules = {
+    s.name: rule(impl = s.impl, attrs = s.attrs, doc = s.doc, is_toolchain_rule = s.is_toolchain_rule, **{k: v for k, v in {"cfg": s.cfg}.items() if v != None})
+    for s in _all_specs
+}
+
+# The rules are accessed by doing module.name, so we have to put them on the correct module.
+load_symbols(rules)
diff --git a/buck2/prelude/user/cxx_headers_bundle.bzl b/buck2/prelude/user/cxx_headers_bundle.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/user/cxx_headers_bundle.bzl
@@ -0,0 +1,70 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//:artifacts.bzl", "ArtifactGroupInfo")
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//cxx:preprocessor.bzl", "CPreprocessorInfo", "cxx_merge_cpreprocessors")
+load("@prelude//decls:common.bzl", "buck")
+load("@prelude//utils:expect.bzl", "expect")
+load(":rule_spec.bzl", "RuleRegistrationSpec")
+
+def _headers(ctx: AnalysisContext, deps: list[Dependency]) -> dict[str, Artifact]:
+    headers = {}
+
+    pp_info = cxx_merge_cpreprocessors(ctx.actions, [], [d[CPreprocessorInfo] for d in deps])
+    for pps in pp_info.set.traverse():
+        for pp in pps:
+            for hdr in pp.headers:
+                headers[paths.join(hdr.namespace, hdr.name)] = hdr.artifact
+
+    return headers
+
+def _impl(ctx: AnalysisContext) -> list[Provider]:
+    headers = _headers(ctx, ctx.attrs.deps)
+    if ctx.attrs.limit != None:
+        expect(
+            len(headers) <= ctx.attrs.limit,
+            "Expected at most {} headers, but transitively pulled in {}",
+            ctx.attrs.limit,
+            len(headers),
+        )
+    output = ctx.actions.symlinked_dir(ctx.label.name, headers, has_content_based_path = False)
+    artifacts = [output.project(name, hide_prefix = True) for name in headers]
+    return [
+        ArtifactGroupInfo(artifacts = artifacts),
+        DefaultInfo(default_outputs = [output]),
+    ]
+
+registration_spec = RuleRegistrationSpec(
+    name = "cxx_headers_bundle",
+    doc = """
+        Bundles transitive exported C/C++ headers from C/C++ libraries, allowing
+        them to e.g. be consumed via the `resources`s parameter in other rules.
+        The headers maintain their `#include` paths, as defined by the C/C++
+        libraries that export them.
+    """,
+    impl = _impl,
+    attrs = buck.labels_arg()
+    | buck.contacts_arg()
+    | {
+        "deps": attrs.list(
+            attrs.dep(providers = [CPreprocessorInfo]),
+            default = [],
+            doc = """
+                Bundle the exported C/C++ headers from these (transitive) deps.
+            """,
+        ),
+        "limit": attrs.option(
+            attrs.int(),
+            default = None,
+            doc = """
+                Enforce that we don't bundle more than this number of headers.
+            """,
+        ),
+    },
+)
diff --git a/buck2/prelude/user/rule_spec.bzl b/buck2/prelude/user/rule_spec.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/user/rule_spec.bzl
@@ -0,0 +1,17 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+RuleRegistrationSpec = record(
+    name = field(str),
+    impl = field(typing.Callable),
+    attrs = field(dict[str, Attr]),
+    # TODO(nga): should be `transition | None`, but `transition` does not work as type.
+    cfg = field(typing.Any | None, None),
+    is_toolchain_rule = field(bool, False),
+    doc = field(str, ""),
+)
diff --git a/buck2/prelude/user/write_file.bzl b/buck2/prelude/user/write_file.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/user/write_file.bzl
@@ -0,0 +1,63 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:common.bzl", "buck")
+load("@prelude//decls:core_rules.bzl", "core_args")
+load(":rule_spec.bzl", "RuleRegistrationSpec")
+
+_NL = {
+    "unix": "\n",
+    "windows": "\r\n",
+}
+
+def _impl(ctx: AnalysisContext):
+    # Figure out the type of newlines we're using.
+    newline_type = ctx.attrs.newline
+    if newline_type == "auto":
+        newline_type = ctx.attrs._auto_newline
+
+    # Join lines with newline.
+    newline = _NL[newline_type]
+    content = "".join([line + newline for line in ctx.attrs.content])
+
+    output = ctx.actions.write(
+        ctx.attrs.out,
+        content,
+        is_executable = ctx.attrs.is_executable,
+        has_content_based_path = ctx.attrs.has_content_based_path,
+    )
+
+    providers = [DefaultInfo(default_output = output)]
+
+    if ctx.attrs.is_executable:
+        providers.append(RunInfo(cmd_args(output)))
+
+    return providers
+
+registration_spec = RuleRegistrationSpec(
+    name = "write_file",
+    impl = _impl,
+    attrs = buck.labels_arg()
+    | buck.contacts_arg()
+    | core_args.has_content_based_path_attr()
+    | {
+        # API based on https://github.com/bazelbuild/bazel-skylib/blob/main/docs/write_file_doc.md.
+        "content": attrs.list(attrs.string(), default = []),
+        "is_executable": attrs.bool(default = False),
+        "newline": attrs.enum(["auto", "unix", "windows"], default = "auto"),
+        "out": attrs.string(),
+        "_auto_newline": attrs.default_only(
+            attrs.string(
+                default = select({
+                    "DEFAULT": "unix",
+                    "config//os:windows": "windows",
+                }),
+            ),
+        ),
+    },
+)
diff --git a/buck2/prelude/utils/actions.bzl b/buck2/prelude/utils/actions.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/actions.bzl
@@ -0,0 +1,14 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+ActionExecutionAttributes = record(
+    full_hybrid = field(bool, default = False),
+    local_only = field(bool, default = False),
+    prefer_local = field(bool, default = False),
+    prefer_remote = field(bool, default = False),
+)
diff --git a/buck2/prelude/utils/argfile.bzl b/buck2/prelude/utils/argfile.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/argfile.bzl
@@ -0,0 +1,73 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:arglike.bzl", "ArgLike")
+
+# Create an argument file.
+# Return `cmd_args` which is single string containing `@path/to/argfile`.
+# Returned `cmd_args` contains given files as hidden artifacts.
+def at_argfile(
+    *,
+    # ctx.actions
+    actions,
+    # name of the argument file
+    name: str | Artifact,
+    # the arguments to write to the argument file
+    args,
+    # pass to `ctx.actions.write`
+    allow_args: bool = False,
+    has_content_based_path: bool = False,
+) -> cmd_args:
+    if allow_args:
+        args_file, _ = actions.write(name, args, allow_args = True, with_inputs = True, has_content_based_path = has_content_based_path)
+    else:
+        args_file = actions.write(name, args, with_inputs = True, has_content_based_path = has_content_based_path)
+    return cmd_args(args_file, format = "@{}", hidden = args)
+
+# An argsfile that renders as its path and also carries the artifacts
+# referenced by `args`, the flags written into it.
+#
+# TODO(jtbraun): if "associated artifacts" ever become inheritable/transitive,
+# attaching `args` to `argsfile` would be a better solution.
+def argsfile_with_artifacts(argsfile: Artifact, args: ArgLike) -> cmd_args:
+    return cmd_args(argsfile, hidden = args)
+
+# Write arguments to a file and return an `argsfile_with_artifacts()` cmd_args
+# value pairing the file with everything its contents reference.
+def mk_argsfile(
+    *,
+    actions: AnalysisActions,
+    name: str | Artifact,
+    args: ArgLike,
+    has_content_based_path: bool = False,
+) -> cmd_args:
+    # Write actions may spill additional file artifacts out to the side for
+    # certain string macros, which are returned in `macro_files`. These have to be
+    # carried forward to consumers, just as `args` is.
+    argsfile, macro_files = actions.write(name, args, allow_args = True, has_content_based_path = has_content_based_path)
+    return argsfile_with_artifacts(argsfile, [args] + macro_files)
+
+# Write arguments to a file, and return the file path as `cmd_args`
+# with args attached as hidden artifacts.
+def argfile(
+    *,
+    # ctx.actions
+    actions,
+    # name of the argument file
+    name: str | Artifact,
+    # the arguments to write to the argument file
+    args,
+    # pass to `ctx.actions.write`
+    allow_args: bool = False,
+    has_content_based_path: bool = False,
+) -> cmd_args:
+    if allow_args:
+        args_file, _ = actions.write(name, args, allow_args = True, with_inputs = True, has_content_based_path = has_content_based_path)
+    else:
+        args_file = actions.write(name, args, with_inputs = True, has_content_based_path = has_content_based_path)
+    return cmd_args(args_file, hidden = args)
diff --git a/buck2/prelude/utils/arglike.bzl b/buck2/prelude/utils/arglike.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/arglike.bzl
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Command-line argument-like. For example, a string, or an artifact.
+# Precise list is defined in `ValueAsCommandLineLike::as_command_line`.
+# Defining as Any, but can be defined as union type,
+# but that might be expensive to check at runtime.
+# In the future we will have compiler-time only types,
+# and this type could be refined.
+ArgLike = typing.Any
diff --git a/buck2/prelude/utils/buckconfig.bzl b/buck2/prelude/utils/buckconfig.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/buckconfig.bzl
@@ -0,0 +1,284 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Provides macros for working with .buckconfig."""
+
+load(":expect.bzl", "expect")
+load(":lazy.bzl", "lazy")
+
+def _decode_raw_word(val: str, start: int, delimiter: str | None = None) -> (int, str):
+    """
+    Read characters up to the given delimiter in a string supporting and
+    stripping quoting (i.e. `"`) and escape characters (i.e. `\\`).
+
+    Args:
+      val: Input string to evaluate.
+      start: Where to start in the input string.
+      delimiter: An optional character to terminate at.  If omitted will
+                 continue to the end of the string.
+    """
+
+    quotes = ['"', "'"]
+    word = ""
+    current_quote_char = None
+    escaped = False
+    idx = -1
+
+    for idx in range(start, len(val)):
+        c = val[idx]
+
+        if current_quote_char == None and c == delimiter:
+            break
+
+        if current_quote_char == None and c in quotes:  # quote start
+            current_quote_char = c
+        elif c == current_quote_char and not escaped:  # quote end
+            current_quote_char = None
+        elif c == "\\" and not escaped:  # handle escape char
+            expect(
+                current_quote_char != None,
+                "escape char outside of quotes at char %d in: %s" % (idx + 1, val),
+            )
+            escaped = True
+        else:
+            word += c
+            escaped = False
+
+    expect(current_quote_char == None, "quote not closed in: %s" % val)
+
+    return idx, word
+
+def _next_word(val: str, start: int, delimiter: str | None) -> int:
+    """
+    Advance past delimiter characters.
+    """
+
+    for idx in range(start, len(val)):
+        c = val[idx]
+        if c != delimiter:
+            return idx
+
+    return -1
+
+# Below are some utilities to log and track `read_config` calls
+# You can enable this with `-c buckconfig.log=<a single key>`, ex. `-c buckconfig.log=build.use_limited_hybrid`.
+# To print in json, use `-c buckconfig.log_json=build.use_limited_hybrid`.
+# This will print a stacktrace on stderr for every `read_config` call of `build.use_limited_hybrid`.
+# Would recommend piping the stderr to file because otherwise printing to stderr can be slow and hard to read.
+# You can also print a record for all keys with `-c buckconfig.log_all_in_json=true`. This prints all `read_config` calls
+# without stacktraces, where each entry is a JSON that includes the cell, section, and key.
+# NOTE: even without stacktraces, log all mode is extremely slow and memory hungry, often 20-40x slower and more
+# memory hungry than the equivalent run without, so only use it on small graphs or when absolutely necessary.
+
+def _buck_config_log_keys(json: bool) -> set[(str, str)]:
+    log_section_and_key = read_root_config("buckconfig", "log_json" if json else "log")
+    if not log_section_and_key:
+        return set()
+
+    # Unfortunately, due to buckconfigs allowing `.`, it's possible to have multiple
+    # ambiguous section/key for a single buckconfig, so check for that here.
+    result = set()
+    splits = log_section_and_key.split(".")
+    for i in range(1, len(splits)):
+        section = ".".join(splits[:i])
+        key = ".".join(splits[i:])
+        result.add((section, key))
+    return result
+
+_BUCKCONFIG_LOG_KEYS = _buck_config_log_keys(json = False)
+_BUCKCONFIG_LOG_JSON_KEYS = _buck_config_log_keys(json = True)
+_BUCKCONFIG_LOG_ALL = read_root_config("buckconfig", "log_all_in_json") in ("True", "true")
+LOG_BUCKCONFIGS = bool(_BUCKCONFIG_LOG_KEYS or _BUCKCONFIG_LOG_JSON_KEYS or _BUCKCONFIG_LOG_ALL)
+
+# optional fields
+_BUCKCONFIG_LOG_CALLSTACK = read_root_config("buckconfig", "log_callstack") in ("True", "true")
+_BUCKCONFIG_LOG_VALUE = read_root_config("buckconfig", "log_value") in ("True", "true")
+
+def _log_read_config(read_func, section: str, key: str, default = None):
+    value = read_func(section, key, default)
+
+    maybe_value_dict = {"value": value} if _BUCKCONFIG_LOG_VALUE else {}
+    maybe_callstack_dict = {"call_stack": call_stack()} if _BUCKCONFIG_LOG_CALLSTACK else {}
+    if _BUCKCONFIG_LOG_ALL:
+        output = {
+            "starlark_log_all_buckconfigs": {
+                "cell": get_cell_name(),
+                "key": key,
+                "section": section,
+            }
+            | maybe_value_dict
+            | maybe_callstack_dict,
+        }
+
+        # This only prints if buckconfig is set
+        # buildifier: disable=print
+        print(json.encode(output))
+
+    if _BUCKCONFIG_LOG_JSON_KEYS:
+        if (section, key) in _BUCKCONFIG_LOG_JSON_KEYS:
+            output = {
+                "starlark_log_buckconfig": {
+                    "call_stack": call_stack(),
+                    "cell": get_cell_name(),
+                }
+                | maybe_value_dict,
+            }
+
+            # This only prints if buckconfig is set
+            # buildifier: disable=print
+            print(json.encode(output))
+
+    if _BUCKCONFIG_LOG_KEYS:
+        if (section, key) in _BUCKCONFIG_LOG_KEYS:
+            # This only prints if buckconfig is set
+            # Need to do everything in one print statement because otherwise lines from parallel print
+            # invocations at load time will get interlaced
+            # buildifier: disable=print
+            print("========starlark_log_buckconfig========\n{}\n".format(call_stack()))
+
+    return value
+
+read_config_with_logging = partial(_log_read_config, read_config)
+read_root_config_with_logging = partial(_log_read_config, read_root_config)
+
+_read_config = read_config_with_logging if LOG_BUCKCONFIGS else read_config
+_read_root_config = read_root_config_with_logging if LOG_BUCKCONFIGS else read_root_config
+
+def read(section: str, field: str, default: str | Select | None = None, root_cell: bool = False, logging: bool = True) -> str | Select | None:
+    """Read a `string` from `.buckconfig`."""
+    if logging:
+        read_config_func = _read_root_config if root_cell else _read_config
+    else:
+        read_config_func = read_root_config if root_cell else read_config
+    return read_config_func(section, field, default)
+
+# Alias for `read` that's explicit about the type being returned.
+read_string = read
+
+def read_choice(
+    section: str, field: str, choices: typing.Iterable, default: str | Select | None = None, required: bool = True, root_cell: bool = False
+) -> str | None:
+    """Read a string from `.buckconfig` that must be one `choices`."""
+
+    val = read(section, field, root_cell = root_cell)
+    if val != None:
+        if val in choices:
+            return val
+        else:
+            fail(
+                "`{}:{}`: must be one of ({}), but was {}".format(section, field, ", ".join(choices), repr(val)),
+            )
+    elif default != None:
+        return default
+    elif not required:
+        return None
+    else:
+        fail("`{}:{}`: no value set".format(section, field))
+
+def read_bool(
+    section: str, field: str, default: bool | Select | None = None, required: bool = True, root_cell: bool = False, logging: bool = True
+) -> bool | Select | None:
+    """Read a `boolean` from `.buckconfig`."""
+
+    # Treat the empty string as "unset".  This allows the user to "override" a
+    # previous setting by "clearing" it out.
+    val = read(section, field, root_cell = root_cell, logging = logging)
+    if val != None and val != "":
+        # Fast-path string check
+        if val == "True" or val == "true":
+            return True
+        elif val == "False" or val == "false":
+            return False
+
+        # Else fall back to lower casing
+        if val.lower() == "true":
+            return True
+        elif val.lower() == "false":
+            return False
+        else:
+            fail(
+                "`{}:{}`: cannot coerce {!r} to bool".format(section, field, val),
+            )
+    elif default != None:
+        return default
+    elif not required:
+        return None
+    else:
+        fail("`{}:{}`: no value set".format(section, field))
+
+def read_int(section: str, field: str, default: int | Select | None = None, required: bool = True, root_cell: bool = False) -> int | Select | None:
+    """Read an `int` from `.buckconfig`."""
+
+    val = read(section, field, root_cell = root_cell)
+    if val != None:
+        if val.isdigit():
+            return int(val)
+        else:
+            fail(
+                "`{}:{}`: cannot coerce {!r} to int".format(section, field, val),
+            )
+    elif default != None:
+        return default
+    elif not required:
+        return None
+    else:
+        fail("`{}:{}`: no value set".format(section, field))
+
+def read_list(
+    section: str, field: str, delimiter: str | None = ",", default: typing.Iterable | Select | None = None, required: bool = True, root_cell = False
+) -> typing.Iterable | Select | None:
+    """Read a `list` from `.buckconfig`."""
+    val = read(section, field, root_cell = root_cell)
+    if val != None:
+        quotes = ["\\", '"', "'"]
+        if lazy.is_any(lambda x: x in val, quotes):
+            words = []
+            idx = 0
+            for _ in range(len(val)):
+                idx = _next_word(val, idx, delimiter)
+                if idx == -1:
+                    break
+                idx, word = _decode_raw_word(val, idx, delimiter)
+                words.append(word.strip())
+                if idx == -1 or idx >= len(val) - 1:
+                    break
+            return words
+        else:
+            return [v.strip() for v in val.split(delimiter) if v]
+    elif default != None:
+        return default
+    elif not required:
+        return None
+    else:
+        fail("`{}:{}`: no value set".format(section, field))
+
+def resolve_alias(alias: str) -> str:
+    """Resolves an alias into a target (recursively). `fail`s if the alias does
+    not exist.
+
+    Args:
+        alias (str): The alias or target to resolve.
+
+    Returns:
+        The target pointed to by the alias (or the input if the caller lied
+        to us and `alias` is a target)
+    """
+    if "//" in alias:
+        return alias
+
+    # Starlark doesn't have while loops or allow recursion, so if we want to
+    # resolve aliases that we find we need to iterate somehow
+    for _ in range(1000):
+        # TODO: set root_cell to true when all aliases come from root cell?
+        target = read("alias", alias, root_cell = False)
+        expect(target != None, "Alias {} does not exist".format(alias))
+        if "//" in target:
+            return target
+        else:
+            alias = target
+    fail("This should never happen - either the alias exists or it doesn't")
diff --git a/buck2/prelude/utils/build_graph_pattern.bzl b/buck2/prelude/utils/build_graph_pattern.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/build_graph_pattern.bzl
@@ -0,0 +1,42 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+_BuildGraphPatternKind = enum(
+    "root",
+    "root/...",
+    "first_order_deps",
+)
+
+BuildGraphInfo = record(
+    root = Label,
+    first_order_deps = set[Label],
+)
+
+def new_build_graph_info(ctx: AnalysisContext, deps: list[Dependency]) -> BuildGraphInfo:
+    return BuildGraphInfo(
+        root = ctx.label,
+        first_order_deps = set([dep.label for dep in deps]),
+    )
+
+BuildGraphPattern = record(
+    matches = field(typing.Callable[[Label, BuildGraphInfo], bool]),
+)
+
+def parse_build_graph_pattern(pattern: str) -> BuildGraphPattern:
+    kind = _BuildGraphPatternKind(pattern)
+
+    def matches(label: Label, info: BuildGraphInfo) -> bool:
+        if kind == _BuildGraphPatternKind("root"):
+            return label == info.root
+        elif kind == _BuildGraphPatternKind("first_order_deps"):
+            return label in info.first_order_deps
+        elif kind == _BuildGraphPatternKind("root/..."):
+            return label.package.startswith(info.root.package)
+        return False
+
+    return BuildGraphPattern(matches = matches)
diff --git a/buck2/prelude/utils/build_target_pattern.bzl b/buck2/prelude/utils/build_target_pattern.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/build_target_pattern.bzl
@@ -0,0 +1,154 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+ROOT_SYMBOL = "//"
+_TARGET_SYMBOL = ":"
+_RECURSIVE_SYMBOL = "..."
+_PATH_SYMBOL = "/"
+
+# https://www.internalfb.com/intern/staticdocs/buck2/docs/concepts/build_target/
+# Anchors are needed here to ensure every character in "name" is valid
+_NAME_REGEX_PATTERN = "^[A-Za-z0-9_/.=,@~+-]+$"
+_NAME_REGEX = regex(_NAME_REGEX_PATTERN)
+
+_BuildTargetPatternKind = enum(
+    "single",
+    "package",
+    "recursive",
+)
+
+BuildTargetPattern = record(
+    kind = field(_BuildTargetPatternKind),
+    cell = field([str, None], None),
+    path = field(str),
+    name = field([str, None], None),
+    matches = field(typing.Callable),
+    as_string = field(typing.Callable),
+    # Exists purely for optimisation purposes.
+    # Matching pattern inside a loop for many targets creates huge amount of
+    # unnecessary string allocations that we can avoid
+    _path_with_path_symbol = field(str),
+)
+
+BuildTargetPatternParseResult = record(
+    build_target_pattern = field([BuildTargetPattern, None], None),
+    error = field([str, None], default = None),
+)
+
+def try_parse_build_target_pattern(pattern: str) -> BuildTargetPatternParseResult:
+    """
+    This function try to parse build target pattern. If parse fails, it will return the error message.
+    """
+    if not (len(pattern) >= len(ROOT_SYMBOL) + 1):
+        err_msg = "Invalid build target pattern, pattern too short: {}".format(pattern)
+        return BuildTargetPatternParseResult(error = err_msg)
+
+    root_position = pattern.find(ROOT_SYMBOL)
+    if not (root_position >= 0):
+        err_msg = "Invalid build target pattern, pattern should started with `{}` or a cell name followed by `{}`: ".format(ROOT_SYMBOL, ROOT_SYMBOL, pattern)
+        return BuildTargetPatternParseResult(error = err_msg)
+
+    cell = None
+    if root_position > 0:
+        cell = pattern[0:root_position]
+
+    name = None
+    if pattern.endswith(_TARGET_SYMBOL):
+        kind = _BuildTargetPatternKind("package")
+        end_of_path_position = len(pattern) - 1
+    elif pattern.endswith(_RECURSIVE_SYMBOL):
+        kind = _BuildTargetPatternKind("recursive")
+        end_of_path_position = len(pattern) - len(_RECURSIVE_SYMBOL) - 1
+        if not (pattern[end_of_path_position] == _PATH_SYMBOL):
+            err_msg = "Invalid build target pattern, `{}` should be preceded by a `{}`: {}".format(_RECURSIVE_SYMBOL, _PATH_SYMBOL, pattern)
+            return BuildTargetPatternParseResult(error = err_msg)
+    else:
+        kind = _BuildTargetPatternKind("single")
+        end_of_path_position = pattern.rfind(_TARGET_SYMBOL)
+        if end_of_path_position < 0:
+            # Pattern does not have a target delimiter and thus a target name
+            # Assume target name to be the same as the last component of the package
+            end_of_path_position = len(pattern)
+            start_of_package = pattern.rfind(_PATH_SYMBOL)
+            name = pattern[start_of_package + len(_PATH_SYMBOL) :]
+        elif end_of_path_position < root_position:
+            err_msg = "Invalid build target pattern, cell name should not contain `{}`: {}".format(_PATH_SYMBOL, pattern)
+            return BuildTargetPatternParseResult(error = err_msg)
+        else:
+            name = pattern[end_of_path_position + len(_TARGET_SYMBOL) :]
+
+        valid_name = _NAME_REGEX.match(name)
+        if not valid_name:
+            err_msg = "Invalid build target pattern, target name `{}` contains invalid characters. Valid characters are `{}`.".format(name, _NAME_REGEX_PATTERN)
+            return BuildTargetPatternParseResult(error = err_msg)
+
+    start_of_path_position = root_position + len(ROOT_SYMBOL)
+
+    if not (pattern[start_of_path_position] != _PATH_SYMBOL):
+        err_msg = "Invalid build target pattern, path cannot start with `{}`: {}".format(_PATH_SYMBOL, pattern)
+        return BuildTargetPatternParseResult(error = err_msg)
+
+    path = pattern[start_of_path_position:end_of_path_position]
+    if not (path.find(ROOT_SYMBOL) < 0):
+        err_msg = "Invalid build target pattern, `{}` can only appear once: {}".format(ROOT_SYMBOL, pattern)
+        return BuildTargetPatternParseResult(error = err_msg)
+    if not (path.find(_RECURSIVE_SYMBOL) < 0):
+        err_msg = "Invalid build target pattern, `{}` can only appear once: {}".format(_RECURSIVE_SYMBOL, pattern)
+        return BuildTargetPatternParseResult(error = err_msg)
+    if not (path.find(_TARGET_SYMBOL) < 0):
+        err_msg = "Invalid build target pattern, `{}` can only appear once: {}".format(_TARGET_SYMBOL, pattern)
+        return BuildTargetPatternParseResult(error = err_msg)
+    if not (len(path) == 0 or path[-1:] != _PATH_SYMBOL):
+        err_msg = "Invalid build target pattern, path cannot end with `{}`: {}".format(_PATH_SYMBOL, pattern)
+        return BuildTargetPatternParseResult(error = err_msg)
+
+    # buildifier: disable=uninitialized - self is initialized
+    def matches(label: [Label, TargetLabel]) -> bool:
+        if self.cell and self.cell != label.cell:
+            return False
+
+        if self.kind == _BuildTargetPatternKind("single"):
+            return self.path == label.package and self.name == label.name
+        elif self.kind == _BuildTargetPatternKind("package"):
+            return self.path == label.package
+        elif self.kind == _BuildTargetPatternKind("recursive"):
+            path_pattern_length = len(self.path)
+            if path_pattern_length == 0:
+                # This is a recursive pattern of the cell: cell//...
+                return True
+            elif len(label.package) > path_pattern_length:
+                # pattern cell//package/... matches label cell//package/subpackage:target
+                return label.package.startswith(self._path_with_path_symbol)
+            else:
+                return self.path == label.package
+        else:
+            fail("Unknown build target pattern kind.")
+
+    # buildifier: disable=uninitialized - self is initialized
+    def as_string() -> str:
+        normalized_cell = self.cell if self.cell else ""
+        if self.kind == _BuildTargetPatternKind("single"):
+            return "{}//{}:{}".format(normalized_cell, self.path, self.name)
+        elif self.kind == _BuildTargetPatternKind("package"):
+            return "{}//{}:".format(normalized_cell, self.path)
+        elif self.kind == _BuildTargetPatternKind("recursive"):
+            return "{}//{}...".format(normalized_cell, self._path_with_path_symbol)
+        else:
+            fail("Unknown build target pattern kind.")
+
+    self = BuildTargetPattern(
+        kind = kind, cell = cell, path = path, name = name, matches = matches, as_string = as_string, _path_with_path_symbol = path + _PATH_SYMBOL if path else ""
+    )
+
+    return BuildTargetPatternParseResult(build_target_pattern = self)
+
+def parse_build_target_pattern(pattern: str) -> BuildTargetPattern:
+    parse_res = try_parse_build_target_pattern(pattern)
+    if parse_res.error != None:
+        fail(parse_res.error)
+    return parse_res.build_target_pattern
diff --git a/buck2/prelude/utils/clear_platform.bzl b/buck2/prelude/utils/clear_platform.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/clear_platform.bzl
@@ -0,0 +1,25 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# We don't want e.g. Apple simulator and Android emulator targets to be configured differently and handled as a different resource broker by buck2 core.
+# By clearing the platform we make sure there is only a single configured target for each resource broker which manages resources of certain type.
+def _transition_impl(platform: PlatformInfo, refs: struct) -> PlatformInfo:
+    # buildifier: disable=unused-variable
+    _ = (platform, refs)
+    return PlatformInfo(
+        label = "empty_platform",
+        configuration = ConfigurationInfo(
+            constraints = {},
+            values = {},
+        ),
+    )
+
+clear_platform_transition = transition(
+    impl = _transition_impl,
+    refs = {},
+)
diff --git a/buck2/prelude/utils/cmd_script.bzl b/buck2/prelude/utils/cmd_script.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/cmd_script.bzl
@@ -0,0 +1,62 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//os_lookup:defs.bzl", "ScriptLanguage")
+
+# Takes a cmd_args containing an executable and zero or more arguments to that
+# executable, and bundles it together into a script that is callable as a single
+# argument.
+#
+# For example in the Rust rules we have a `linker` + `linker_flags` that we want
+# to pass to rustc as a single "-Clinker={}" argument.
+#
+#     linker_cmd = cmd_args(linker_info.linker, ctx.attrs.linker_flags)
+#     linker_wrapper = cmd_script(
+#         actions = actions,
+#         name = "linker_wrapper",
+#         cmd = linker_cmd,
+#         language = ctx.attrs._exec_os_type[OsLookup].script,
+#     )
+#     return cmd_args(linker_wrapper, format = "-Clinker={}")
+#
+def cmd_script(
+    actions: AnalysisActions,
+    name: str,
+    cmd: cmd_args,
+    language: ScriptLanguage = ScriptLanguage("sh"),
+    quote: str | None = "shell",
+    has_content_based_path: bool = False,
+) -> cmd_args:
+    cmd_kwargs = {} if quote == None else {"quote": quote}
+    shell_quoted = cmd_args(cmd, **cmd_kwargs)
+
+    if language == ScriptLanguage("sh"):
+        wrapper, _ = actions.write(
+            actions.declare_output("{}.sh".format(name), has_content_based_path = has_content_based_path),
+            [
+                "#!/usr/bin/env bash",
+                cmd_args(cmd_args(shell_quoted, delimiter = " \\\n"), format = '{} "$@"\n'),
+            ],
+            is_executable = True,
+            allow_args = True,
+            has_content_based_path = has_content_based_path,
+        )
+    elif language == ScriptLanguage("bat"):
+        wrapper, _ = actions.write(
+            actions.declare_output("{}.bat".format(name), has_content_based_path = has_content_based_path),
+            [
+                "@echo off",
+                cmd_args(cmd_args(shell_quoted, delimiter = "^\n "), format = "{} %*\n"),
+            ],
+            allow_args = True,
+            has_content_based_path = has_content_based_path,
+        )
+    else:
+        fail(language)
+
+    return cmd_args(wrapper, hidden = cmd)
diff --git a/buck2/prelude/utils/dicts.bzl b/buck2/prelude/utils/dicts.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/dicts.bzl
@@ -0,0 +1,25 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:expect.bzl", "expect")
+
+_DEFAULT_FMT = 'found different values for key "{}": {} != {}'
+
+def update_x(dst: dict[typing.Any, typing.Any], k: typing.Any, v: typing.Any, fmt = _DEFAULT_FMT):
+    p = dst.setdefault(k, v)
+    expect(p == v, fmt, k, p, v)
+
+def merge_x(dst: dict[typing.Any, typing.Any], src: dict[typing.Any, typing.Any], fmt = _DEFAULT_FMT):
+    for k, v in src.items():
+        update_x(dst, k, v, fmt = fmt)
+
+def flatten_x(ds: list[dict[typing.Any, typing.Any]], fmt = _DEFAULT_FMT) -> dict[typing.Any, typing.Any]:
+    out = {}
+    for d in ds:
+        merge_x(out, d, fmt = fmt)
+    return out
diff --git a/buck2/prelude/utils/directory_fold.bzl b/buck2/prelude/utils/directory_fold.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/directory_fold.bzl
@@ -0,0 +1,64 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# Given a list of files, return a tree structure with the shape:
+#
+# type Tree = dict[component, None | Tree]
+#
+# Where None indicates a file, and a Tree indicates a directory.
+def _build_tree(files):
+    tree = {}
+    for file in files:
+        map = tree
+
+        # For every python file, starting from distillery, figure out every subdirectory and add it to the map　if it's not there already
+        components = file.split("/")
+        for directory_chunk in components[:-1]:
+            map = map.setdefault(directory_chunk, {})
+        map[components[-1]] = None
+
+    return tree
+
+def _reduce_tree(path, tree, directory):
+    files = []
+    dirs = []
+    for k, v in tree.items():
+        path2 = path + ("/" if path else "") + k
+        if v == None:
+            files.append(path2)
+        else:
+            dirs.append(_reduce_tree(path2, v, directory))
+    return directory(path, dirs, files)
+
+# Given a list of files, perform a reduction on the tree structure.
+# The `directory` argument is a function that takes a path, a list of subdirectory results, and a list of files.
+# For example, given the paths `foo/bar.txt` and `foo/baz.txt` it would be called thusly:
+#
+# directory("", [directory("foo", [], ["foo/bar.txt", "foo/baz.txt"])], [])
+def directory_fold(files, directory):
+    return _reduce_tree("", _build_tree(files), directory)
+
+def _test_tree_functions():
+    input = ["foo/bar/baz.txt", "foo/bar.txt", "foo.txt", "foo/bar/quux.txt", "foo/baz/quux.txt"]
+    output = {
+        "foo": {
+            "bar": {"baz.txt": None, "quux.txt": None},
+            "bar.txt": None,
+            "baz": {"quux.txt": None},
+        },
+        "foo.txt": None,
+    }
+    result = _build_tree(input)
+    if result != output:
+        fail("_build_tree(), unexpected output. Wanted `{output}`, got `{tree}`".format(output = output, result = result))
+
+    original = directory_fold(input, lambda _name, dirs, files: files + [x for xs in dirs for x in xs])
+    if sorted(original) != sorted(input):
+        fail("_directory_fold(), unexpected output. Wanted `{input}`, got `{original}`".format(input = input, original = original))
+
+_test_tree_functions()
diff --git a/buck2/prelude/utils/expect.bzl b/buck2/prelude/utils/expect.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/expect.bzl
@@ -0,0 +1,146 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Provides macros for stating program invariant expectations.
+
+It is a good practice to enforce program invariants in code, so that all
+assumptions are explicit and execution fails fast and with clear message in
+case any one of them is violated.
+"""
+
+load(
+    "@prelude//utils:type_defs.bzl",
+    "is_bool",
+    "is_collection",
+    "is_dict",
+    "is_list",
+    "is_number",
+    "is_string",
+    "is_struct",
+)
+
+def expect(condition: typing.Any, message: str = "condition not expected", *format_args):
+    """Fails if provided condition is not truthy.
+
+    Args:
+      condition: condition that is expected to be truthy
+      message: an optional error message to display in case provided condition
+        is not truthy
+      format_args: optional arguments to format the error message with
+    """
+    if not condition:
+        formatted_message = message.format(*format_args)
+        fail(formatted_message)
+
+def expect_equal(left: typing.Any, right: typing.Any, message: str | None = None, *format_args):
+    if left != right:
+        if message == None:
+            msg = "Expected values to be equal, but got '{}' and '{}' instead.".format(left, right)
+            fail(msg)
+        else:
+            formatted_message = message.format(*format_args)
+            fail(formatted_message)
+
+def expect_non_none(val, msg: str = "unexpected none", *fmt_args, **fmt_kwargs):
+    """
+    Require the given value not be `None`.
+    """
+    if val == None:
+        fail(msg.format(*fmt_args, **fmt_kwargs))
+    return val
+
+def expect_type(name: str, check: typing.Callable[[typing.Any], bool], desc: str, val: typing.Any):
+    """Fails if check(val) if not truthy. name, desc are used for the error message.
+
+    Usually you shouldn't need to directly use this, and prefer the expect_* family of functions
+    defined in the same file.
+
+    Args:
+      name: the name of the attribute we're checking
+      check: a function implementing an invariant check
+      desc: a description of what we expected to see
+      val: the value we're checking
+
+    See the below functions, like expect_string, for usage examples.
+    """
+    expect(check(val), 'Buck target requires "{}" to be a {}', name, desc)
+
+def expect_string(name, val):
+    expect_type(name, is_string, "string", val)
+
+def expect_string_starts_with(name, val, prefix):
+    expect_type(name, is_string, "string", val)
+    expect(val.startswith(prefix), 'Buck target requires "{}" to start with "{}', name, prefix)
+
+def expect_number(name, val):
+    expect_type(name, is_number, "number", val)
+
+def expect_bool(name, val):
+    expect_type(name, is_bool, "bool", val)
+
+def expect_list(name, val):
+    expect_type(name, is_list, "list", val)
+
+def expect_list_of(sub_expect, name, val):
+    """Check that all items in val satisfy sub_expect
+
+    See expect_list_of_strings for an example.
+    """
+    expect_list(name, val)
+    for i, val in enumerate(val):
+        sub_expect("{}[{}] (value: {})".format(name, i, val), val)
+
+def expect_list_of_strings(name, val):
+    expect_list_of(expect_string, name, val)
+
+def expect_dict(name, val):
+    expect_type(name, is_dict, "dict", val)
+
+def expect_dict_of(key_expect, value_expect, name, val):
+    """Verify that all key-value pairs of val satisfy key_expect and value_expect respectively"""
+    expect_dict(name, val)
+    for key, val in val.items():
+        key_expect("Key '{}' in {}".format(key, name), key)
+        value_expect("{}[{}] (value={})".format(name, repr(key), val), val)
+
+def expect_collection(name, val):
+    expect_type(name, is_collection, "collection", val)
+
+def expect_contains(name, val, options):
+    """Verify that val is in options."""
+    expect(val in options, "{name} (value: {val}) not in {options}".format(name = name, val = val, options = options))
+
+def expect_contains_all(name, val, options):
+    """Verify all items in val are in the options."""
+
+    expect_collection(name, val)
+    for index, val in enumerate(val):
+        expect_contains("{name}[{index}]".format(name = name, index = index), val, options)
+
+def expect_struct(name: str, val: struct):
+    expect_type(name, is_struct, "struct", val)
+
+# You'll likely want to import this struct for convenience, instead of each method separately
+expects = struct(
+    expect = expect,
+    type = expect_type,
+    string = expect_string,
+    string_starts_with = expect_string_starts_with,
+    number = expect_number,
+    bool = expect_bool,
+    list = expect_list,
+    list_of = expect_list_of,
+    list_of_strings = expect_list_of_strings,
+    dict = expect_dict,
+    dict_of = expect_dict_of,
+    collection = expect_collection,
+    contains = expect_contains,
+    contains_all = expect_contains_all,
+    equal = expect_equal,
+    struct = expect_struct,
+)
diff --git a/buck2/prelude/utils/glob_defs.bzl b/buck2/prelude/utils/glob_defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/glob_defs.bzl
@@ -0,0 +1,142 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Provides utility macros for working with globs."""
+
+load("@prelude//:paths.bzl", "paths")
+load("@prelude//utils:buckconfig.bzl", "read_bool")
+
+DISABLE_STRICT_GLOB_CHECKING = read_bool("build_defs", "disable_strict_glob_checking", False)
+
+def _subdir_glob(glob_specs, exclude = None, prefix = ""):
+    """Returns a dict of sub-directory relative paths to full paths.
+
+    The subdir_glob() function is useful for defining header maps for C/C++
+    libraries which should be relative the given sub-directory.
+    Given a list of tuples, the form of (relative-sub-directory, glob-pattern),
+    it returns a dict of sub-directory relative paths to full paths.
+
+    Please refer to native.glob() for explanations and examples of the pattern.
+
+    Args:
+      glob_specs: The array of tuples in form of
+        (relative-sub-directory, glob-pattern inside relative-sub-directory).
+        type: List[Tuple[str, str]]
+      exclude: A list of patterns to identify files that should be removed
+        from the set specified by the first argument. Defaults to [].
+        type: Optional[List[str]]
+      prefix: If is not None, prepends it to each key in the dictionary.
+        Defaults to None.
+        type: Optional[str]
+
+    Returns:
+      A dict of sub-directory relative paths to full paths.
+    """
+    if exclude == None:
+        exclude = []
+
+    results = []
+
+    for dirpath, glob_pattern in glob_specs:
+        results.append(
+            _single_subdir_glob(dirpath, glob_pattern, exclude, prefix),
+        )
+
+    return _merge_maps(*results)
+
+subdir_glob = _subdir_glob
+
+def _merge_maps(*file_maps):
+    result = {}
+    for file_map in file_maps:
+        for key in file_map:
+            if key in result and result[key] != file_map[key]:
+                fail(
+                    "Conflicting files in file search paths. " + '"%s" maps to both "%s" and "%s".' % (key, result[key], file_map[key]),
+                )
+
+            result[key] = file_map[key]
+
+    return result
+
+def _single_subdir_glob(dirpath, glob_pattern, exclude = None, prefix = None, strict = False):
+    if exclude == None:
+        exclude = []
+    results = {}
+    glob_func = (lambda *args, **kwargs: strict_glob(called_by_subdir_glob = True, *args, **kwargs)) if strict else glob
+    files = glob_func([paths.join(dirpath, glob_pattern)], exclude = exclude)
+    for f in files:
+        if dirpath:
+            key = f[len(dirpath) + 1 :]
+        else:
+            key = f
+        if prefix:
+            key = paths.join(prefix, key)
+        results[key] = f
+
+    return results
+
+# Using a flat list will trigger build errors on Android.
+# cxx_library will generate an apple_library on iOS, a cxx_library on Android.
+# Those rules have different behaviors. Using a map will make the behavior consistent.
+#
+def glob_private_headers(glob_patterns, exclude = []):
+    result = {}
+    headers = glob(glob_patterns, exclude = exclude)
+    for header in headers:
+        result[paths.basename(header)] = header
+    return result
+
+def strict_glob(include, called_by_subdir_glob = False, **kwargs):
+    """Has the same API as glob(), but will fail() if any entry in include fails to match."""
+    if DISABLE_STRICT_GLOB_CHECKING:
+        return glob(include, **kwargs)
+
+    has_glob_pattern = False
+    all_results = []
+    for entry in include:
+        has_glob_pattern = has_glob_pattern or "*" in entry
+
+        result = glob([entry], **kwargs)
+        if len(result) == 0:
+            fail("Strict glob failed to match files for glob pattern: " + entry)
+        all_results.extend(result)
+
+    # Dedupe.
+    if len(include) > 1:
+        all_results = list(set(all_results))
+
+    for entry in kwargs.get("exclude", []):
+        has_glob_pattern = has_glob_pattern or "*" in entry
+
+    # When called by subdir_glob, we pass each entry individually, meaning we won't observe the
+    # other entries with "*" when processing a single entry that may not have it.
+    if not called_by_subdir_glob and not has_glob_pattern:
+        fail("Using a strict glob without a single '*'. Use a literal list instead of globbing.")
+
+    return all_results
+
+def strict_subdir_glob(include, exclude = None, prefix = ""):
+    """
+    A version of subdir_glob that fails if any of the glob_specs fail to match an entry after taking
+    exclude into consideration.
+    """
+    if DISABLE_STRICT_GLOB_CHECKING:
+        return _subdir_glob(include, exclude, prefix)
+
+    if exclude == None:
+        exclude = []
+
+    results = []
+
+    for dirpath, glob_pattern in include:
+        results.append(
+            _single_subdir_glob(dirpath, glob_pattern, exclude, prefix, strict = True),
+        )
+
+    return _merge_maps(*results)
diff --git a/buck2/prelude/utils/graph_utils.bzl b/buck2/prelude/utils/graph_utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/graph_utils.bzl
@@ -0,0 +1,294 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:expect.bzl", "expect")
+
+def pre_order_traversal(
+    graph: dict[typing.Any, list[typing.Any]],
+    node_formatter: typing.Callable[[typing.Any], str] = str,
+    edge_explainer: typing.Callable[[typing.Any, typing.Any], list[str]] = lambda _src, _dest: ["Unknown"],
+) -> list[typing.Any]:
+    """
+    Perform a pre-order (topologically sorted) traversal of `graph` and return the ordered nodes
+    """
+
+    # A repeated dep is counted once per occurrence here and decremented once per occurrence below,
+    # so it needs no deduplication (Kahn's algorithm works correctly for multigraphs).
+    in_degrees = {node: 0 for node in graph}
+    for _node, deps in graph.items():
+        for dep in deps:
+            in_degrees[dep] += 1
+
+    queue = []
+
+    for node, in_degree in in_degrees.items():
+        if in_degree == 0:
+            queue.append(node)
+
+    ordered = []
+
+    for _ in range(len(in_degrees)):
+        if len(queue) == 0:
+            fail_cycle(graph, node_formatter, edge_explainer)
+
+        node = queue.pop()
+        ordered.append(node)
+
+        for dep in graph[node]:
+            in_degrees[dep] -= 1
+            if in_degrees[dep] == 0:
+                queue.append(dep)
+
+    expect(not queue, "finished before processing nodes: {}".format([node_formatter(node) for node in queue]))
+    expect(len(ordered) == len(graph), "missing or duplicate nodes in sort")
+
+    return ordered
+
+def post_order_traversal(
+    graph: dict[typing.Any, list[typing.Any]],
+    node_formatter: typing.Callable[[typing.Any], str] = str,
+    edge_explainer: typing.Callable[[typing.Any, typing.Any], list[str]] = lambda _src, _dest: ["Unknown"],
+) -> list[typing.Any]:
+    """
+    Performs a post-order traversal of `graph`.
+    """
+
+    out_degrees = {}
+    rdeps = {node: [] for node in graph}
+    for node, deps in graph.items():
+        deps = dedupe(deps)
+        out_degrees[node] = len(deps)
+        for dep in deps:
+            rdeps[dep].append(node)
+
+    queue = [node for node, out_degree in out_degrees.items() if out_degree == 0]
+
+    ordered = []
+
+    for _ in range(len(out_degrees)):
+        if len(queue) == 0:
+            fail_cycle(graph, node_formatter, edge_explainer)
+
+        node = queue.pop()
+        ordered.append(node)
+
+        for dep in rdeps[node]:
+            out_degrees[dep] -= 1
+            if out_degrees[dep] == 0:
+                queue.append(dep)
+
+    expect(not queue, "finished before processing nodes: {}".format([node_formatter(node) for node in queue]))
+    expect(len(ordered) == len(graph), "missing or duplicate nodes in sort")
+
+    return ordered
+
+def fail_cycle(
+    graph: dict[typing.Any, list[typing.Any]],
+    node_formatter: typing.Callable[[typing.Any], str],
+    edge_explainer: typing.Callable[[typing.Any, typing.Any], list[str]],
+) -> typing.Never:
+    cycle = find_cycle(graph)
+    if cycle:
+        errors = []
+        for i, c in enumerate(cycle):
+            indented_number = (" -> " if i > 0 else "    ") + "" * (3 - len(str(i))) + str(i + 1) + ": "
+            edge_explanation = ""
+            if i > 0:
+                edge_explanation = "\n" + " " * 9 + "Reason for edge:"
+                edge_explanation += "".join(["\n" + " " * 11 + e for e in edge_explainer(cycle[i - 1], c)])
+            errors.append(indented_number + node_formatter(c) + edge_explanation)
+        fail(
+            "cycle detected between the following targets:\n    {}\n\ncycle details:\n{}\n\n".format(
+                "\n -> ".join(
+                    [node_formatter(c) for c in cycle],
+                ),
+                "\n\n".join(errors),
+            ),
+        )
+
+    fail("expected cycle, but found none")
+
+def find_cycle(graph: dict[typing.Any, list[typing.Any]]) -> list[typing.Any] | None:
+    visited = {}
+    OUTPUT = 1
+    VISIT = 2
+    current_parents = []
+    work = [(VISIT, n) for n in graph.keys()]
+    for _ in range(2000000000):
+        if not work:
+            break
+        kind, node = work.pop()
+        if kind == VISIT:
+            if node not in visited:
+                visited[node] = True
+                current_parents.append(node)
+
+                work.append((OUTPUT, node))
+                for dep in graph[node]:
+                    if dep in current_parents:
+                        return current_parents + [dep]
+                    if dep not in visited:
+                        work.append((VISIT, dep))
+        else:
+            current_parents.pop()
+
+    return None
+
+def post_order_traversal_by(roots: typing.Iterable, get_nodes_to_traverse_func) -> list[typing.Any]:
+    """
+    Returns the post-order sorted list of the nodes in the traversal.
+
+    This implementation simply performs a dfs. We maintain a work stack here.
+    When visiting a node, we first add an item to the work stack to output that
+    node, and then add items to visit all the children. While a work item for a
+    child will not be added if it has already been visited, if there's an item in
+    the stack for that child it will still be added. When popping the visit, if
+    the node had been visited, it's ignored. This ensures that a node's children are
+    all visited before we output that node.
+    """
+    ordered = []
+    visited = {}
+    OUTPUT = 1
+    VISIT = 2
+    queue = [(VISIT, n) for n in roots]
+    for _ in range(2000000000):
+        if not queue:
+            break
+
+        kind, node = queue.pop()
+        if kind == VISIT:
+            if not node in visited:
+                queue.append((OUTPUT, node))
+                for dep in get_nodes_to_traverse_func(node):
+                    if dep not in visited:
+                        queue.append((VISIT, dep))
+        else:
+            visited[node] = True
+            ordered.append(node)
+    return ordered
+
+def pre_order_traversal_by(roots: typing.Iterable, get_nodes_to_traverse_func) -> list[typing.Any]:
+    """
+    Returns a topological sorted list of the nodes from a pre-order traversal.
+
+    Note this gives a different order from `pre_order_traversal` above (to simplify the implementation).
+    """
+    ordered = post_order_traversal_by(roots, get_nodes_to_traverse_func)
+    return ordered[::-1]
+
+def depth_first_traversal(graph_nodes: dict[typing.Any, list[typing.Any]], roots: typing.Iterable) -> list[typing.Any]:
+    """
+    Like `depth_first_traversal_by` but the nodes are stored in the graph.
+    """
+
+    def lookup(x):
+        return graph_nodes[x]
+
+    return depth_first_traversal_by(graph_nodes, roots, lookup)
+
+# With following graph
+#
+#          A
+#        /   \
+#      B      C
+#     / \    / \
+#    D   E  F   G
+#
+# preorder-left-to-right starting from A will go to left leg first
+#                       A-B-D-E-C-F-G
+#
+# preorder-right-to-left starting from A will go to right leg first
+#                       A-C-G-F-B-E-D
+#
+GraphTraversal = enum(
+    "preorder-right-to-left",
+    "preorder-left-to-right",
+)
+
+def depth_first_traversal_by(
+    graph_nodes: [dict[typing.Any, typing.Any], None],
+    roots: typing.Iterable,
+    get_nodes_to_traverse_func: typing.Callable,
+    traversal: GraphTraversal = GraphTraversal("preorder-right-to-left"),
+    node_formatter: typing.Callable[[typing.Any], str] = str,
+) -> list[typing.Any]:
+    """
+    Performs a depth first traversal of `graph_nodes`, beginning
+    with the `roots` and queuing the nodes returned by `get_nodes_to_traverse_func`.
+    Returns a list of all visisted nodes.
+
+    get_nodes_to_traverse_func(node: '_a') -> ['_a']:
+
+    Starlark does not offer while loops, so this implementation
+    must make use of a for loop.
+    """
+
+    # Note, this relies on the Starlark guarantee that set() returns values in the order they were first added.
+    visited = set(roots)
+    stride = -1 if traversal == GraphTraversal("preorder-left-to-right") else 1
+    stack = reversed(visited) if stride < 0 else list(visited)
+
+    for _ in range(len(graph_nodes) if graph_nodes else 2000000000):
+        if not stack:
+            break
+        node = stack.pop()
+        if graph_nodes and node not in graph_nodes:
+            fail("Expected node {} in graph nodes".format(node_formatter(node)))
+        nodes_to_visit = get_nodes_to_traverse_func(node)
+        if nodes_to_visit:
+            # This is supposed to be equivalent to `for node in nodes_to_visit[::stride]:`
+            # Unfortunately, Starlark allocates new arrays for slices.
+            #
+            # Deriving the indexes via `range()` helps alleviate the memory
+            # usage of this function.
+            range_traversal = range(len(nodes_to_visit) - 1, -1, -1) if stride == -1 else range(len(nodes_to_visit))
+            for i in range_traversal:
+                node = nodes_to_visit[i]
+                if node not in visited:
+                    visited.add(node)
+                    stack.append(node)
+
+    expect(not stack, "Expected to be done with graph traversal stack.")
+
+    return list(visited)
+
+# To support migration from a tset-based link strategy, we are trying to match buck's internal tset
+# traversal logic here.  Look for implementation of TopologicalTransitiveSetIteratorGen
+def rust_matching_topological_traversal(
+    graph_nodes: [dict[typing.Any, typing.Any], None], roots: typing.Iterable, get_nodes_to_traverse_func: typing.Callable
+) -> list[typing.Any]:
+    counts = {}
+
+    for label in depth_first_traversal_by(graph_nodes, roots, get_nodes_to_traverse_func, GraphTraversal("preorder-right-to-left")):
+        for dep in get_nodes_to_traverse_func(label):
+            if dep in counts:
+                counts[dep] += 1
+            else:
+                counts[dep] = 1
+
+    # some of the targets in roots might be transitive deps of others, we only put those that are true roots
+    # in the stack at this point
+    stack = [root_target for root_target in roots if not root_target in counts]
+    true_roots = len(stack)
+
+    result = []
+    for _ in range(2000000000):
+        if not stack:
+            break
+        next = stack.pop()
+        result.append(next)
+        deps = get_nodes_to_traverse_func(next)
+        for child in deps[::-1]:  # reverse order ensures we put things on the stack in the same order as rust's tset traversal
+            counts[child] -= 1
+            if counts[child] == 0:
+                stack.append(child)
+
+    if len(result) != true_roots + len(counts):
+        fail()  # fail_cycle
+
+    return result
diff --git a/buck2/prelude/utils/host.bzl b/buck2/prelude/utils/host.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/host.bzl
@@ -0,0 +1,27 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+HostOSTypes = ["linux", "macos", "windows"]
+
+HostOSType = enum(*HostOSTypes)
+
+def _compute_get_host_os() -> HostOSType:
+    info = host_info()
+    if info.os.is_linux:
+        return HostOSType("linux")
+    elif info.os.is_macos:
+        return HostOSType("macos")
+    elif info.os.is_windows:
+        return HostOSType("windows")
+    else:
+        fail("Unknown host OS")
+
+_HOST_OS = _compute_get_host_os()
+
+def get_host_os() -> HostOSType:
+    return _HOST_OS
diff --git a/buck2/prelude/utils/label_provider.bzl b/buck2/prelude/utils/label_provider.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/label_provider.bzl
@@ -0,0 +1,17 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+LabelInfo = provider(
+    fields = {
+        # List of labels for the target
+        "labels": provider_field(
+            typing.Any,
+            default = None,
+        ),
+    },
+)
diff --git a/buck2/prelude/utils/lazy.bzl b/buck2/prelude/utils/lazy.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/lazy.bzl
@@ -0,0 +1,55 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _is_any(predicate: typing.Callable, iterable: typing.Iterable) -> bool:
+    """
+    This expression lazily iterates the container with 0 new allocations.
+    In the event that the iterable is empty, it will return False.
+
+    For scenarios like this:
+
+    _ = any([i % 2 == 0 for i in range(100000)])
+
+    The list comprehension would lead to a new list of 100000 booleans,
+    and would only end-up checking 1. Replacing it with:
+
+    _ = is_any(lambda i: i % 2 == 0, range(100000))
+
+    would lead to 0 new allocations.
+    """
+    for i in iterable:
+        if predicate(i):
+            return True
+
+    return False
+
+def _is_all(predicate: typing.Callable, iterable: typing.Iterable) -> bool:
+    """
+    This expression lazily iterates the container with 0 new allocations.
+    In the event that the iterable is empty, it will return False.
+
+    For scenarios like this:
+
+    _ = all([i % 2 == 0 for i in range(100000)])
+
+    The list comprehension would lead to a list of 100000 booleans.
+    Replacing it with:
+
+    _ = is_all(lambda i: i % 2 == 0, range(100000))
+
+    would lead to 0 new allocations.
+    """
+    for i in iterable:
+        if not predicate(i):
+            return False
+    return True
+
+lazy = struct(
+    is_any = _is_any,
+    is_all = _is_all,
+)
diff --git a/buck2/prelude/utils/materialization_test.bzl b/buck2/prelude/utils/materialization_test.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/materialization_test.bzl
@@ -0,0 +1,32 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def materialization_test(artifacts: list[Artifact]) -> Provider:
+    """
+    Produce a ExternalRunnerTestInfo that just checks we can materialize the
+    target.
+    """
+
+    # This legitimately looks at host_info because a few lines later it
+    # specifically requires local execution. If we had better support for test
+    # execution platfroms this wouldn't be necessary, but that's where we are
+    # today.
+    if host_info().os.is_windows:
+        command = ["cmd.exe", "/v:off", "/c", "exit 0"]
+    else:
+        command = ["true"]
+
+    return ExternalRunnerTestInfo(
+        type = "custom",
+        command = [cmd_args(command, hidden = artifacts)],
+        # Force it to run locally and thus force materialization.
+        default_executor = CommandExecutorConfig(
+            local_enabled = True,
+            remote_enabled = False,
+        ),
+    )
diff --git a/buck2/prelude/utils/pick.bzl b/buck2/prelude/utils/pick.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/pick.bzl
@@ -0,0 +1,25 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def pick(override, underlying):
+    return cmd_args(override) if override != None else underlying
+
+def pick_bin(override, underlying):
+    return override[RunInfo] if override != None else underlying
+
+def pick_dep(override, underlying):
+    return pick_raw(override, underlying)
+
+def pick_raw(override, underlying):
+    return override if override != None else underlying
+
+def pick_and_add(override, additional, underlying):
+    flags = [pick(override, underlying)]
+    if additional:
+        flags.append(additional)
+    return cmd_args(flags)
diff --git a/buck2/prelude/utils/selects.bzl b/buck2/prelude/utils/selects.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/selects.bzl
@@ -0,0 +1,61 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//utils:type_defs.bzl", "type_utils")
+
+def _apply(obj, function):
+    """
+    Runs select_map(obj, function, recurse=True)
+    """
+    return select_map(obj, function, recurse = True)
+
+def _tie_n_impl_inner(objs, pvals, val):
+    return _tie_n_impl(objs[1:], pvals + [val])
+
+def _tie_n_impl(objs, pvals):
+    if not objs:
+        return tuple(pvals)
+
+    return select_map(
+        objs[0],
+        partial(_tie_n_impl_inner, objs, pvals),
+        recurse = True,
+    )
+
+def _tie_n(*objs):
+    """
+    Combine separate select objects into a single select with all values of
+    the select "tied" into n-tuples.
+
+    Arguments:
+        objs: Objects which may be behind (possible nested) `select`s.
+
+    Returns: A `select` resolving to an n-tuple of the passed in object
+    """
+    return _tie_n_impl(objs, [])
+
+def _apply_n_inner(func, vals):
+    return func(*vals)
+
+def _apply_n(objs, func):
+    """
+    Return a new `select` formed by applying the given function to all possible
+    combinations of the given select objects.
+    """
+    return select_map(
+        _tie_n(*objs),
+        # Unpack n-tuple and call user-supplied function.
+        partial(_apply_n_inner, func),
+        recurse = True,
+    )
+
+selects = struct(
+    apply = _apply,
+    apply_n = _apply_n,
+    is_select = type_utils.is_select,
+)
diff --git a/buck2/prelude/utils/set.bzl b/buck2/prelude/utils/set.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/set.bzl
@@ -0,0 +1,87 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# A set is useful when the `dedupe` builtin is not applicable. Dedupe looks at
+# identity of the value (some kind of pointer) rather than equality, so for
+# example doesn't eliminate duplicates of the same string value obtained from
+# different places:
+#
+#     things = ["huh", "huh"]
+#     expect(len(dedupe(things)) == 2)
+#
+#     huh = "huh"
+#     things = [huh, huh]
+#     expect(len(dedupe(things)) == 1)
+#
+# In contrast a set compares its entries for equality, not identity, and will
+# never contain one entry equal to another entry.
+#
+# Example usage:
+#
+#     things = set()
+#     for x in somewhere:
+#         things.add(x)
+#     return things.list()
+
+# Name the record `set_record` to enable users to use `set` to initialize a set.
+set_record = record(
+    _entries = field(dict),
+    list = field(typing.Callable),
+    # Adds the value to the set, returning whether the value existed in the set
+    add = field(typing.Callable),
+    # Removes the value if the value is in the set, returning whether the value existed in the set
+    remove = field(typing.Callable),
+    # Adds the values to the set, returning the values that were added
+    update = field(typing.Callable),
+    # Returns whether the value is in the set
+    contains = field(typing.Callable),
+    size = field(typing.Callable),
+)
+
+# For typing a set, you may use `set_type` or `set_record.type`, the former is
+# encouraged to avoid leaking the underlying implementation.
+set_type = set_record
+
+def set(initial_entries: list[typing.Any] = []) -> set_type:
+    def set_list():
+        return self._entries.keys()
+
+    def set_add(v: typing.Any) -> bool:
+        if self.contains(v):
+            return False
+        self._entries[v] = None
+        return True
+
+    def set_contains(v: typing.Any) -> bool:
+        return v in self._entries
+
+    def set_remove(v: typing.Any) -> bool:
+        if self.contains(v):
+            self._entries.pop(v)
+            return True
+        return False
+
+    def set_update(values: list[typing.Any]) -> list[typing.Any]:
+        return filter(None, [v for v in values if self.add(v)])
+
+    def set_size() -> int:
+        return len(self._entries)
+
+    self = set_record(
+        _entries = {},
+        list = set_list,
+        add = set_add,
+        remove = set_remove,
+        update = set_update,
+        contains = set_contains,
+        size = set_size,
+    )
+
+    self.update(initial_entries)
+
+    return self
diff --git a/buck2/prelude/utils/source_listing.bzl b/buck2/prelude/utils/source_listing.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/source_listing.bzl
@@ -0,0 +1,17 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":source_listing_impl.bzl", "SourceListingInfoAlias", "empty_source_listing_impl", "source_listing_impl")
+
+SourceListingInfo = SourceListingInfoAlias
+
+def source_listing(exclude = None):
+    source_listing_impl(exclude = exclude or [])
+
+def empty_source_listing():
+    empty_source_listing_impl()
diff --git a/buck2/prelude/utils/source_listing_impl.bzl b/buck2/prelude/utils/source_listing_impl.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/source_listing_impl.bzl
@@ -0,0 +1,59 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+SourceListingInfo = provider(
+    fields = {
+        "sources": dict[str, Artifact],
+    }
+)
+
+SourceListingInfoAlias = SourceListingInfo
+
+def _impl(ctx):
+    sources = {}
+    for d in ctx.attrs.deps:
+        package = ctx.label.package
+        if package != "":
+            package += "/"
+        rel_loc = d.label.package.removeprefix(package)
+        sources.update({rel_loc + "/" + p: art for p, art in d[SourceListingInfo].sources.items()})
+
+    for s in ctx.attrs.srcs:
+        sources[s.short_path] = s
+    return [DefaultInfo(), SourceListingInfo(sources = sources)]
+
+# This rule acts sort of like a `filegroup`, except that 1) it returns all the
+# source artifacts unchanged, and 2) it reports the location of all artifacts
+# relative to the current package. We use this for gathering listings of the
+# source files for bundled cells.
+_source_listing = rule(
+    impl = _impl,
+    attrs = {
+        "deps": attrs.list(attrs.dep()),
+        "srcs": attrs.list(attrs.source()),
+    },
+)
+
+def source_listing_impl(exclude: list[str]):
+    package = package_name()
+    if package != "":
+        package += "/"
+    _source_listing(
+        name = "source_listing",
+        srcs = glob(["**/*", "**/.*"], exclude = exclude),
+        deps = ["//" + package + s + ":source_listing" for s in __internal__.sub_packages()],
+        visibility = ["PUBLIC"],
+    )
+
+def empty_source_listing_impl():
+    _source_listing(
+        name = "source_listing",
+        srcs = [],
+        deps = [],
+        visibility = ["PUBLIC"],
+    )
diff --git a/buck2/prelude/utils/strings.bzl b/buck2/prelude/utils/strings.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/strings.bzl
@@ -0,0 +1,18 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def strip_prefix(prefix: str, s: str) -> [str, None]:
+    """
+    If the string `s` starts with `prefix`, return the result of stripping the
+    latter from the former.  Return `None` otherwise.
+    """
+
+    if s.startswith(prefix):
+        return s[len(prefix) :]
+
+    return None
diff --git a/buck2/prelude/utils/type_defs.bzl b/buck2/prelude/utils/type_defs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/type_defs.bzl
@@ -0,0 +1,182 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+"""Provides macros for queries type information."""
+
+_SELECT_TYPE = type(select({"DEFAULT": []}))
+
+def is_select(thing):
+    return type(thing) == _SELECT_TYPE
+
+def is_unicode(arg):
+    """Checks if provided instance has a unicode type.
+
+    Args:
+      arg: An instance to check. type: Any
+
+    Returns:
+      True for unicode instances, False otherwise. rtype: bool
+    """
+    return hasattr(arg, "encode")
+
+_STRING_TYPE = type("")
+
+def is_string(arg):
+    """Checks if provided instance has a string type.
+
+    Args:
+      arg: An instance to check. type: Any
+
+    Returns:
+      True for string instances, False otherwise. rtype: bool
+    """
+    return type(arg) == _STRING_TYPE
+
+_LIST_TYPE = type([])
+
+def is_list(arg):
+    """Checks if provided instance has a list type.
+
+    Args:
+      arg: An instance to check. type: Any
+
+    Returns:
+      True for list instances, False otherwise. rtype: bool
+    """
+    return type(arg) == _LIST_TYPE
+
+_DICT_TYPE = type({})
+
+def is_dict(arg):
+    """Checks if provided instance has a dict type.
+
+    Args:
+      arg: An instance to check. type: Any
+
+    Returns:
+      True for dict instances, False otherwise. rtype: bool
+    """
+    return type(arg) == _DICT_TYPE
+
+_SET_TYPE = type(set())
+
+def is_set(arg):
+    """Checks if provided instance has a set type.
+
+    Args:
+      arg: An instance to check. type: Any
+
+    Returns:
+      True for set instances, False otherwise. rtype: bool
+    """
+    return type(arg) == _SET_TYPE
+
+_TUPLE_TYPE = type(())
+
+def is_tuple(arg):
+    """Checks if provided instance has a tuple type.
+
+    Args:
+      arg: An instance to check. type: Any
+
+    Returns:
+      True for tuple instances, False otherwise. rtype: bool
+    """
+    return type(arg) == _TUPLE_TYPE
+
+def is_collection(arg):
+    """Checks if provided instance is a collection subtype.
+
+    This will either be a dict, list, or tuple.
+    """
+    return is_dict(arg) or is_list(arg) or is_tuple(arg)
+
+_BOOL_TYPE = type(True)
+
+def is_bool(arg):
+    """Checks if provided instance is a boolean value.
+
+    Args:
+      arg: An instance of check. type: Any
+
+    Returns:
+      True for boolean values, False otherwise. rtype: bool
+    """
+    return type(arg) == _BOOL_TYPE
+
+_NUMBER_TYPE = type(1)
+
+def is_number(arg):
+    """Checks if provided instance is a number value.
+
+    Args:
+      arg: An instance of check. type: Any
+
+    Returns:
+      True for number values, False otherwise. rtype: bool
+    """
+    return type(arg) == _NUMBER_TYPE
+
+_STRUCT_TYPE = type(struct())  # Starlark returns the same type for all structs
+
+def is_struct(arg):
+    """Checks if provided instance is a struct value.
+
+    Args:
+      arg: An instance to check. type: Any
+
+    Returns:
+      True for struct values, False otherwise. rtype: bool
+    """
+    return type(arg) == _STRUCT_TYPE
+
+def _func():
+    pass
+
+_FUNCTION_TYPE = type(_func)
+
+def is_function(args):
+    """Checks if provided instance is a function value.
+
+    Args:
+      arg: An instance to check. type: Any
+
+    Returns:
+      True for function values, False otherwise. rtype: function
+    """
+    return type(args) == _FUNCTION_TYPE
+
+_RECORD = record()
+_RECORD_TYPE = type(_RECORD())
+
+def is_record(obj):
+    """Checks if provided instance is a record value.
+
+    Args:
+      arg: An instance to check. type: Any
+
+    Returns:
+      True for record values, False otherwise. rtype: bool
+    """
+    return type(obj) == _RECORD_TYPE
+
+type_utils = struct(
+    is_bool = is_bool,
+    is_number = is_number,
+    is_string = is_string,
+    is_unicode = is_unicode,
+    is_list = is_list,
+    is_dict = is_dict,
+    is_set = is_set,
+    is_tuple = is_tuple,
+    is_collection = is_collection,
+    is_select = is_select,
+    is_struct = is_struct,
+    is_function = is_function,
+    is_record = is_record,
+)
diff --git a/buck2/prelude/utils/utils.bzl b/buck2/prelude/utils/utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/utils/utils.bzl
@@ -0,0 +1,87 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+# General utilities shared between multiple rules.
+
+load("@prelude//utils:expect.bzl", "expect")
+
+def as_output(artifact: Artifact | OutputArtifact) -> OutputArtifact:
+    """
+    Convert an Artifact or OutputArtifact to an OutputArtifact.
+    Useful when a function needs to accept either type.
+    """
+    if isinstance(artifact, OutputArtifact):
+        return artifact
+    else:
+        return artifact.as_output()
+
+def value_or(x: [None, typing.Any], default: typing.Any) -> typing.Any:
+    return default if x == None else x
+
+def values_or(*xs: typing.Any | None) -> typing.Any | None:
+    for x in xs:
+        if x != None:
+            return x
+    return None
+
+# Flatten a list of lists into a list
+def flatten(xss: list[list[typing.Any]]) -> list[typing.Any]:
+    return [x for xs in xss for x in xs]
+
+# Flatten a list of dicts into a dict
+def flatten_dict(xss: list[dict[typing.Any, typing.Any]]) -> dict[typing.Any, typing.Any]:
+    return {k: v for xs in xss for k, v in xs.items()}
+
+def from_named_set(srcs: [dict[str, Artifact | Dependency], list[Artifact | Dependency]]) -> dict[str, Artifact | Dependency]:
+    """
+    Normalize parameters of optionally named sources to a dictionary mapping
+    names to sources, deriving the name from the short path when it's not
+    explicitly provided.
+    """
+
+    if type(srcs) == type([]):
+        srcs_dict = {}
+        for src in srcs:
+            if isinstance(src, Artifact):
+                name = src.short_path
+            else:
+                # If the src is a `dependency`, use the short path of the
+                # default output.
+                expect(
+                    len(src[DefaultInfo].default_outputs) == 1,
+                    "expected exactly one default output from {} ({})".format(src, src[DefaultInfo].default_outputs),
+                )
+                [artifact] = src[DefaultInfo].default_outputs
+                name = artifact.short_path
+            srcs_dict[name] = src
+        return srcs_dict
+    else:
+        return srcs
+
+def map_idx(key: typing.Any, vals: list[typing.Any]) -> list[typing.Any]:
+    return [x[key] for x in vals]
+
+def filter_and_map_idx(key: typing.Any, vals: list[typing.Any]) -> list[typing.Any]:
+    return [x[key] for x in vals if key in x]
+
+def idx(x: [typing.Any, None], key: typing.Any) -> [typing.Any, None]:
+    return x[key] if x != None else None
+
+def dedupe_by_value(vals: list[typing.Any]) -> list[typing.Any]:
+    return list(set(vals))
+
+def map_val(func: typing.Callable[[typing.Any], typing.Any], val: [typing.Any, None]) -> [typing.Any, None]:
+    """
+    If `val` if `None`, return `None`, else apply `func` to `val` and return the
+    result.
+    """
+
+    if val == None:
+        return None
+
+    return func(val)
diff --git a/buck2/prelude/validation/audit_results.bxl b/buck2/prelude/validation/audit_results.bxl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/validation/audit_results.bxl
@@ -0,0 +1,151 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+def _get_results(lazy: bxl.LazyContext, modifiers, targets, take: list[str] | None) -> dict[Label, list[ValidationSpec]]:
+    results = lazy.join_all([lazy.configured_target_node(target, modifiers = modifiers).catch() for target in targets]).resolve()
+
+    analysis_promises = []
+    for result in results:
+        if not result.is_ok():
+            continue
+        analysis_promises.append(lazy.analysis(result.unwrap()).catch())
+
+    info = {}
+    for analysis_result in lazy.join_all(analysis_promises).resolve():
+        if not analysis_result.is_ok():
+            continue
+
+        providers = analysis_result.unwrap().providers()
+        validation_info = providers.get(ValidationInfo)
+        if not validation_info:
+            info[analysis_result.unwrap().as_dependency().label] = []
+            continue
+
+        specs = []
+        for spec in validation_info.validations:
+            if take and spec.name not in take:
+                continue
+
+            specs.append(spec)
+
+        info[analysis_result.unwrap().as_dependency().label] = specs
+
+    return info
+
+def _impl(ctx: bxl.Context):
+    if ctx.cli_args.transitive:
+        targets = ctx.target_universe(ctx.cli_args.targets).universe_target_set()
+    else:
+        targets = ctx.cli_args.targets
+
+    target_to_specs = _get_results(
+        lazy = ctx.lazy,
+        modifiers = ctx.modifiers,
+        targets = targets,
+        take = ctx.cli_args.take,
+    )
+
+    info = {}
+    for target, specs in target_to_specs.items():
+        ensured = {spec.name: ctx.output.ensure(spec.validation_result) for spec in specs}
+        if ensured or not ctx.cli_args.trim:
+            info[target] = ensured
+
+    # We chose to print to stdout because we run into an issue with
+    # the ctx.bxl_actions().actions.write_json() API
+    #
+    # The goal is to output something into a file which looks like this:
+    # {
+    #   "cell//some:target": {
+    #      "spec_name": "path/to/materialized/output.json"
+    #
+    # Unfortuantely, if we use the actions.write_json() API, it requires us to pass
+    # `with_inputs = True` so we can be sure that we materialize the the paths to validation
+    # outputs with the JSON.
+    #
+    # Unfortunately, `ensured_artifact_group` has a limited API that doesn't allow us to
+    # only print a subset of the targets. While you can loop thru them, there is no way .owner
+    # API, you'd have to guess based on filepath.
+    #
+    # As a result, we ensure the artifacts as we iterate so we can get the materialized absolute
+    # path and not run into an invariant where you are not allowed to freeze EnsuredArtifacts.
+    ctx.output.print_json(info)
+
+def _find_and_dump_failures_impl(bxl_ctx: bxl.Context, target_to_results: dict[Label, dict[str, ArtifactValue]], output: OutputArtifact):
+    output_results = {}
+    for target, results in target_to_results.items():
+        target_res = {}
+        for name, artifact_value in results.items():
+            content = artifact_value.read_json()["data"]
+            if content["status"] == "failure":
+                target_res[name] = content["message"]
+
+        if target_res:
+            output_results[target] = target_res
+
+    bxl_ctx.bxl_actions().actions.write_json(output, output_results, pretty = True)
+    return [DefaultInfo()]
+
+_find_and_dump_failures = bxl.dynamic_actions(
+    impl = _find_and_dump_failures_impl,
+    attrs = {
+        "output": dynattrs.output(),
+        "target_to_results": dynattrs.dict(Label, dynattrs.dict(str, dynattrs.artifact_value())),
+    },
+)
+
+def _dump_failures_impl(ctx: bxl.Context):
+    if ctx.cli_args.transitive:
+        targets = ctx.target_universe(ctx.cli_args.targets).universe_target_set()
+    else:
+        targets = ctx.cli_args.targets
+
+    target_to_specs = _get_results(
+        lazy = ctx.lazy,
+        modifiers = ctx.modifiers,
+        targets = targets,
+        take = ctx.cli_args.take,
+    )
+
+    input = {}
+    for target, specs in target_to_specs.items():
+        for spec in specs:
+            input.setdefault(target, {})[spec.name] = spec.validation_result
+
+    actions = ctx.bxl_actions().actions
+    out = actions.declare_output("results.json", has_content_based_path = False)
+    actions.dynamic_output_new(
+        _find_and_dump_failures(
+            target_to_results = input,
+            output = out.as_output(),
+        ),
+    )
+    ctx.output.print(ctx.output.ensure(out).abs_path())
+
+BASE_ARGS = {
+    # Filter specific validation specs.
+    "take": cli_args.list(cli_args.string(), default = []),
+    "targets": cli_args.target_expr(),
+    "transitive": cli_args.bool(False),
+}
+
+dump_failures = bxl_main(
+    impl = _dump_failures_impl,
+    cli_args = BASE_ARGS,
+)
+
+main = bxl_main(
+    impl = _impl,
+    cli_args = BASE_ARGS
+    | {
+        "trim": cli_args.bool(
+            default = True,
+            doc = "By default, targets with no validations will be stripped from the output.",
+        ),
+    },
+)
diff --git a/buck2/prelude/validation_deps.bzl b/buck2/prelude/validation_deps.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/validation_deps.bzl
@@ -0,0 +1,19 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+VALIDATION_DEPS_ATTR_NAME = "validation_deps"
+VALIDATION_DEPS_ATTR_TYPE = attrs.set(attrs.dep(), sorted = True, default = [])
+
+def get_validation_deps_outputs(ctx: AnalysisContext) -> list[Artifact]:
+    artifacts = []
+    if hasattr(ctx.attrs, VALIDATION_DEPS_ATTR_NAME):
+        validation_deps = getattr(ctx.attrs, VALIDATION_DEPS_ATTR_NAME)
+        for dep in validation_deps:
+            default_info = dep[DefaultInfo]
+            artifacts += default_info.default_outputs
+    return artifacts
diff --git a/buck2/prelude/windows/tools/BUCK b/buck2/prelude/windows/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/windows/tools/BUCK
@@ -0,0 +1,19 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+prelude = native
+
+prelude.export_file(
+    name = "msvc_hermetic_exec.bat",
+    src = "msvc_hermetic_exec.bat",
+    has_content_based_path = True,
+)
+
+prelude.command_alias(
+    name = "msvc_hermetic_exec",
+    exe = ":msvc_hermetic_exec.bat",
+    visibility = ["PUBLIC"],
+)
diff --git a/buck2/prelude/windows/tools/msvc_hermetic_exec.bat b/buck2/prelude/windows/tools/msvc_hermetic_exec.bat
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/windows/tools/msvc_hermetic_exec.bat
@@ -0,0 +1,10 @@
+@REM Copyright (c) Meta Platforms, Inc. and affiliates.
+@REM
+@REM This source code is dual-licensed under either the MIT license found in the
+@REM LICENSE-MIT file in the root directory of this source tree or the Apache
+@REM License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+@REM of this source tree. You may select, at your option, one of the
+@REM above-listed licenses.
+
+@echo off
+%* /nologo "/d1trimfile:%cd%\" "/d2trimfile:%cd%\" "/experimental:deterministic" "/pathmap:%cd%\="
diff --git a/buck2/prelude/xplugins/attrs.bzl b/buck2/prelude/xplugins/attrs.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/xplugins/attrs.bzl
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(":types.bzl", "XPluginsManifestInfo")
+
+_DEBUG_ARTIFACTS_ATTR = {"xplugins_debug_artifacts": attrs.option(attrs.dep(providers = [XPluginsManifestInfo]), default = None)}
+
+xplugins_common = struct(
+    debug_artifacts_arg = _DEBUG_ARTIFACTS_ATTR,
+)
diff --git a/buck2/prelude/xplugins/debug_artifacts.bzl b/buck2/prelude/xplugins/debug_artifacts.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/xplugins/debug_artifacts.bzl
@@ -0,0 +1,90 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    ":types.bzl",
+    "XPluginsDebugArtifactsEntry",
+    "XPluginsDebugArtifactsInfo",
+    "XPluginsDebugArtifactsTSet",
+    "XPluginsFunctionMappingManifestInfo",
+    "XPluginsManifestInfo",
+)
+
+def xplugins_get_debug_artifacts_info(ctx: AnalysisContext, deps: list[Dependency]) -> XPluginsDebugArtifactsInfo | None:
+    children = []
+    for dep in deps:
+        info = dep.get(XPluginsDebugArtifactsInfo)
+        if info:
+            children.append(info.tset)
+    value = None
+
+    # We don't expose this on apple_bundle because it should be propagated from the binary.
+    manifest_dep = getattr(ctx.attrs, "xplugins_debug_artifacts", None)
+    manifest_info = manifest_dep.get(XPluginsManifestInfo) if manifest_dep else None
+    if manifest_info:
+        value = XPluginsDebugArtifactsEntry(
+            target = ctx.label,
+            manifest_info = manifest_info,
+        )
+    if value or children:
+        tset = ctx.actions.tset(
+            XPluginsDebugArtifactsTSet,
+            value = value,
+            children = children,
+        )
+        return XPluginsDebugArtifactsInfo(tset = tset)
+    return None
+
+def xplugins_get_function_mapping_manifest_info(
+    actions: AnalysisActions, app_target: Label | None, info: XPluginsDebugArtifactsInfo | None
+) -> XPluginsFunctionMappingManifestInfo:
+    if not info:
+        info = XPluginsDebugArtifactsInfo(tset = actions.tset(XPluginsDebugArtifactsTSet))
+
+    function_mappings = []
+    function_mapping_artifacts = []
+    function_mapping_targets = []
+
+    for entry in info.tset.traverse():
+        if entry:
+            function_mapping_artifacts.append(entry.manifest_info.function_mapping)
+            function_mapping_targets.append(entry.target)
+            function_mappings.append({
+                "path": entry.manifest_info.function_mapping,
+                "target": entry.target,
+            })
+
+    if app_target != None and app_target not in function_mapping_targets:
+        fail("App target {} is not listed in the XPlugins function mappings: {}".format(app_target, function_mapping_targets))
+
+    function_mapping_manifest_file = actions.write_json(
+        "function_mapping_manifest.json",
+        {
+            "app_target": app_target,
+            "mappings": function_mappings,
+        },
+        has_content_based_path = False,
+        pretty = True,
+    ).with_associated_artifacts(function_mapping_artifacts)
+
+    return XPluginsFunctionMappingManifestInfo(
+        manifest = function_mapping_manifest_file,
+    )
+
+def xplugins_get_debug_artifacts_subtargets(info: XPluginsFunctionMappingManifestInfo) -> list[Provider]:
+    return [
+        DefaultInfo(
+            sub_targets = {
+                "function_mapping_manifest": [
+                    DefaultInfo(
+                        default_output = info.manifest,
+                    ),
+                ],
+            },
+        ),
+    ]
diff --git a/buck2/prelude/xplugins/types.bzl b/buck2/prelude/xplugins/types.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/xplugins/types.bzl
@@ -0,0 +1,63 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+XPluginsManifestInfo = provider(
+    fields = {
+        "function_mapping": provider_field(Artifact),
+        "manifest": provider_field(Artifact),
+    }
+)
+
+XPluginsDebugArtifactsEntry = record(
+    target = field(Label),
+    manifest_info = field(XPluginsManifestInfo),
+)
+
+XPluginsDebugArtifactsTSet = transitive_set()
+
+XPluginsDebugArtifactsInfo = provider(
+    fields = {
+        "tset": provider_field(XPluginsDebugArtifactsTSet),
+    }
+)
+
+XPluginsFunctionMappingManifestInfo = provider(
+    fields = {
+        "manifest": provider_field(Artifact),
+    }
+)
+
+XPluginsPluginUsageInfo = provider(
+    fields = {
+        "target": provider_field(Label),
+        "usage_info": provider_field(Artifact),
+    }
+)
+
+XPluginsSocketUsageInfo = provider(
+    fields = {
+        "target": provider_field(Label),
+        "usage_info": provider_field(Artifact),
+    }
+)
+
+def _get_artifacts(values: list[XPluginsPluginUsageInfo | XPluginsSocketUsageInfo]) -> list[Artifact]:
+    return [v.usage_info for v in values]
+
+XPluginsUsageInfoSet = transitive_set(
+    args_projections = {
+        "artifacts": _get_artifacts,
+    },
+)
+
+XPluginsUsageInfo = provider(
+    fields = {
+        "plugin_info_tset": provider_field(XPluginsUsageInfoSet),
+        "socket_info_tset": provider_field(XPluginsUsageInfoSet),
+    }
+)
diff --git a/buck2/prelude/xplugins/utils.bzl b/buck2/prelude/xplugins/utils.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/xplugins/utils.bzl
@@ -0,0 +1,38 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load(
+    ":types.bzl",
+    "XPluginsPluginUsageInfo",
+    "XPluginsSocketUsageInfo",
+    "XPluginsUsageInfo",
+    "XPluginsUsageInfoSet",
+)
+
+def get_xplugins_usage_info(actions: AnalysisActions, all_deps: list[Dependency]) -> XPluginsUsageInfo | None:
+    plugin_manifests = [d[XPluginsPluginUsageInfo] for d in all_deps if XPluginsPluginUsageInfo in d]
+    socket_manifests = [d[XPluginsSocketUsageInfo] for d in all_deps if XPluginsSocketUsageInfo in d]
+    usage_infos = [d[XPluginsUsageInfo] for d in all_deps if XPluginsUsageInfo in d]
+
+    if plugin_manifests or socket_manifests or usage_infos:
+        plugin_info_tset = actions.tset(
+            XPluginsUsageInfoSet,
+            value = plugin_manifests,
+            children = [u.plugin_info_tset for u in usage_infos],
+        )
+        socket_info_tset = actions.tset(
+            XPluginsUsageInfoSet,
+            value = socket_manifests,
+            children = [u.socket_info_tset for u in usage_infos],
+        )
+        return XPluginsUsageInfo(
+            plugin_info_tset = plugin_info_tset,
+            socket_info_tset = socket_info_tset,
+        )
+    else:
+        return None
diff --git a/buck2/prelude/zip_file/tools/BUCK b/buck2/prelude/zip_file/tools/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/zip_file/tools/BUCK
@@ -0,0 +1,20 @@
+load("@prelude//utils:source_listing.bzl", "source_listing")
+
+oncall("build_infra")
+
+source_listing()
+
+python_bootstrap_binary(
+    name = "unzip",
+    main = "unzip.py",
+    visibility = ["PUBLIC"],
+)
+
+# Type checking target for Python tool scripts
+python_library(
+    name = "scripts-typing",
+    srcs = [
+        "unzip.py",
+    ],
+    typing = True,
+)
diff --git a/buck2/prelude/zip_file/tools/unzip.py b/buck2/prelude/zip_file/tools/unzip.py
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/zip_file/tools/unzip.py
@@ -0,0 +1,75 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+import argparse
+import os
+import stat
+import sys
+import zipfile
+
+
+def _parse_args():
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--src", required=True, help="File to extract")
+    parser.add_argument("--dst", required=True, help="Output directory")
+
+    return parser.parse_args()
+
+
+def do_unzip(archive, output_dir):
+    with zipfile.ZipFile(archive) as z:
+        # First extract non-symlinks so that when symlinks are created in the next step
+        # symlink type (whether it's a file or a directory which is important for Windows platform)
+        # is automatically detected for non-broken symlinks (see documentation for `os.symlink` function).
+        # That way we don't need to pass `target_is_directory` argument to `os.symlink` function.
+        for info in (i for i in z.infolist() if not _is_symlink(i)):
+            z.extract(info, path=output_dir)
+            if _is_executable(info):
+                os.chmod(
+                    os.path.join(output_dir, info.filename),
+                    _file_attributes(info) | stat.S_IXUSR,
+                )
+        for info in (i for i in z.infolist() if _is_symlink(i)):
+            symlink_path = os.path.join(output_dir, info.filename)
+            symlink_dst = z.read(info).decode("utf-8")
+            if os.path.isabs(symlink_dst):
+                raise RuntimeError(
+                    f"Symlink `{info.filename}` -> `{symlink_dst}` points to absolute path which is prohibited."
+                )
+            output_dir_relative_symlink_dst = os.path.normpath(
+                os.path.join(os.path.dirname(info.filename), symlink_dst)
+            )
+            if output_dir_relative_symlink_dst.startswith(os.pardir):
+                raise RuntimeError(
+                    f"Symlink `{info.filename}` -> `{symlink_dst}` (normalized destination path relative to archive output directory is `{output_dir_relative_symlink_dst}`) points outside of archive output directory which is prohibited."
+                )
+            os.symlink(symlink_dst, symlink_path)
+
+
+def _file_attributes(zip_info):
+    # Those are stored in upper bits
+    return zip_info.external_attr >> 16
+
+
+def _is_symlink(zip_info):
+    return stat.S_ISLNK(_file_attributes(zip_info))
+
+
+def _is_executable(zip_info):
+    return stat.S_IMODE(_file_attributes(zip_info)) & stat.S_IXUSR
+
+
+def main():
+    args = _parse_args()
+    print("Source zip is: {}".format(args.src), file=sys.stderr)
+    print("Output destination is: {}".format(args.dst), file=sys.stderr)
+    do_unzip(args.src, args.dst)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/buck2/prelude/zip_file/zip_file.bzl b/buck2/prelude/zip_file/zip_file.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/zip_file/zip_file.bzl
@@ -0,0 +1,76 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+load("@prelude//decls:toolchains_common.bzl", "toolchains_common")
+load(":zip_file_toolchain.bzl", "ZipFileToolchainInfo")
+
+def _zip_file_impl(ctx: AnalysisContext) -> list[Provider]:
+    """
+     zip_file() rule implementation
+
+    Args:
+        ctx: rule analysis context
+    Returns:
+        list of created providers
+    """
+
+    zip_file_toolchain = ctx.attrs._zip_file_toolchain[ZipFileToolchainInfo]
+    create_zip_tool = zip_file_toolchain.create_zip
+
+    zip_output_name = ctx.attrs.out if ctx.attrs.out else "{}.zip".format(ctx.label.name)
+    output = ctx.actions.declare_output(zip_output_name, has_content_based_path = True)
+
+    on_duplicate_entry = ctx.attrs.on_duplicate_entry
+    entries_to_exclude = ctx.attrs.entries_to_exclude
+    hardcode_permissions_for_deterministic_output = ctx.attrs.hardcode_permissions_for_deterministic_output
+    zip_srcs = ctx.attrs.zip_srcs
+    srcs = ctx.attrs.srcs
+
+    create_zip_cmd = [
+        create_zip_tool,
+        "--output_path",
+        output.as_output(),
+        "--on_duplicate_entry",
+        on_duplicate_entry if on_duplicate_entry else "overwrite",
+    ]
+
+    if srcs:
+        # add artifact and is_source flag pair
+        srcs_file_cmd = cmd_args(
+            [[src, src.short_path, str(src.is_source)] for src in srcs],
+        )
+        entries_file = ctx.actions.write("entries", srcs_file_cmd, has_content_based_path = True)
+
+        create_zip_cmd.append("--entries_file")
+        create_zip_cmd.append(entries_file)
+        create_zip_cmd.append(cmd_args(hidden = srcs))
+
+    if zip_srcs:
+        create_zip_cmd.append("--zip_sources")
+        create_zip_cmd.append(zip_srcs)
+
+    if entries_to_exclude:
+        create_zip_cmd.append("--entries_to_exclude")
+        create_zip_cmd.append(entries_to_exclude)
+
+    if hardcode_permissions_for_deterministic_output:
+        create_zip_cmd.append("--hardcode_permissions_for_deterministic_output")
+
+    ctx.actions.run(cmd_args(create_zip_cmd), category = "zip")
+
+    return [DefaultInfo(default_output = output)]
+
+implemented_rules = {
+    "zip_file": _zip_file_impl,
+}
+
+extra_attributes = {
+    "zip_file": {
+        "_zip_file_toolchain": toolchains_common.zip_file(),
+    },
+}
diff --git a/buck2/prelude/zip_file/zip_file_toolchain.bzl b/buck2/prelude/zip_file/zip_file_toolchain.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/prelude/zip_file/zip_file_toolchain.bzl
@@ -0,0 +1,14 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is dual-licensed under either the MIT license found in the
+# LICENSE-MIT file in the root directory of this source tree or the Apache
+# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
+# of this source tree. You may select, at your option, one of the
+# above-listed licenses.
+
+ZipFileToolchainInfo = provider(
+    doc = "ZipFile toolchain info",
+    fields = {
+        "create_zip": provider_field(typing.Any, default = None),
+    },
+)
diff --git a/buck2/run_test.sh b/buck2/run_test.sh
new file mode 100644
--- /dev/null
+++ b/buck2/run_test.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# Runs a test binary in the given directory. `cabal test` runs a test-suite
+# in its package's directory, and some tests rely on that.
+#
+# Invoked as: run_test.sh <cwd> <binary> [args...]
+set -eu
+
+# The binary's path is relative to the directory that this script starts
+# in, not to $cwd, so the script makes it absolute before it changes
+# directory.
+absolute() {
+  case "$1" in
+    /*) echo "$1" ;;
+    *) echo "$PWD/$1" ;;
+  esac
+}
+
+cwd=$1
+bin=$(absolute "$2")
+shift 2
+
+cd "$cwd"
+exec "$bin" "$@"
diff --git a/buck2/template/.buckconfig b/buck2/template/.buckconfig
new file mode 100644
--- /dev/null
+++ b/buck2/template/.buckconfig
@@ -0,0 +1,55 @@
+# Build-wide configuration. Note that settings local to your build
+# should go into `.buckconfig.local` which is typically not a tracked
+# file.
+
+[cells]
+  root = .
+  prelude = buck2/prelude
+  toolchains = buck2/toolchains
+  third-party-haskell = third-party/haskell
+  none = none
+
+[cell_aliases]
+  config = prelude
+  ovr_config = prelude
+  fbcode = none
+  fbsource = none
+  buck = none
+
+[parser]
+  target_platform_detector_spec = target:root//...->prelude//platforms:default \
+    target:prelude//...->prelude//platforms:default \
+    target:toolchains//...->prelude//platforms:default \
+    target:third-party-haskell//...->prelude//platforms:default
+
+[build]
+  execution_platforms = root//buck2/platforms:exec
+
+# Things that affect how Haskell code is built.
+[haskell]
+  # Extra flags
+  #
+  # You can add extra flags to compiles and links for the whole
+  # build. These flags will come early on the command line, so they
+  # will be overriden by target-specific flags.
+  #
+  #   compiler_flags = -I/opt/homebrew/include
+  #   linker_flags = -L/opt/homebrew/lib -L/opt/zlib/lib
+
+  # Per-module compilation
+  #
+  # See "Per-module compilation" in buck2/README.md for details.
+  #
+  # Use per-module for all targets:
+  #
+  #   compile_granularity = module
+  #
+  # By default per-module compiles use the persistent worker. To disable it:
+  #
+  #   per_module_worker = none
+  #
+  # Configure the persistent worker (see buck2/README.md):
+  #
+  #   per_module_worker_rts_options = -A64m -n4m -qn8 -I5
+  #   per_module_worker_sessions = 8
+  #   per_module_worker_session_mode = make
diff --git a/buck2/template/PACKAGE b/buck2/template/PACKAGE
new file mode 100644
--- /dev/null
+++ b/buck2/template/PACKAGE
@@ -0,0 +1,8 @@
+load("//buck2:cfg_constructor_if_standalone.bzl", "cfg_constructor_if_standalone", "dev_modifiers_if_standalone")
+load("@prelude//cfg/modifier/set_cfg_modifiers.bzl", "set_cfg_modifiers")
+
+cfg_constructor_if_standalone()
+
+set_cfg_modifiers(
+    cfg_modifiers = dev_modifiers_if_standalone(),
+)
diff --git a/buck2/thrift.bzl b/buck2/thrift.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/thrift.bzl
@@ -0,0 +1,356 @@
+load("//buck2:haskell.bzl", "haskell_library")
+load("//cabal-buck2:packages.bzl", "PACKAGES")
+
+# A rule for running the (buck2-built) Thrift compiler over a .thrift file.
+#
+# Unlike hsc2hs/alex/happy, the compiler here is itself a buck2 target
+# (//compiler:thrift-compiler), not an external frozen tool - so we
+# depend on it as a normal exec_dep and let buck2 build it as part of the
+# action's inputs, instead of hardcoding a path anywhere.
+#
+# The compiler can emit more than one output file per input (e.g. separate
+# Types.hs/Service.hs/Client.hs for a .thrift file that defines a service),
+# and the exact set depends on the input's contents, so it always writes
+# into a directory (`gen-hs2/...` by default) rather than a fixed file.
+# `outs`, if given, additionally names known files within that directory
+# (as plain module paths, e.g. "Foo/Types.hs" - not gen-hs2-prefixed) and
+# exposes each as its own sub-target artifact (via ctx.actions.copy_file()
+# - the same primitive export_file.bzl uses), so a caller who already
+# knows what a .thrift file generates can put them directly into a
+# haskell_library()'s `srcs` *dict*, keyed by module name:
+#
+#   thrift_compile(
+#       name = "gen-foo",
+#       thrift_file = "if/Foo.thrift",
+#       outs = ["Foo/Types.hs"],
+#   )
+#   haskell_library(
+#       srcs = {"Foo.Types": ":gen-foo[Foo/Types.hs]"},
+#       ...
+#   )
+#
+# The dict form (module name -> source) is what haskell_library() wants
+# here, rather than a plain list: with a list, each module's name (for
+# the package db, so cross-target `import`s of it resolve) is derived from
+# its source artifact's own path, and a bare copy of the whole gen-hs2/
+# directory would derive "gen.gen-hs2.Foo.Types" instead of "Foo.Types".
+# (thrift_srcs()/thrift_library() below do the path -> module name
+# conversion for `outs` entries themselves; see _module_name().)
+
+# thrift-compiler's default --gen-prefix; every caller in this repo relies
+# on the default, so `outs` entries are resolved as GEN_PREFIX + "/" + out
+# within the raw output directory.
+_GEN_PREFIX = "gen-hs2"
+
+# thrift-compiler resolves *every* relative filename it's given - the main
+# INPUT included, not just `include` statements inside a .thrift file -
+# against --include-dir (Thrift.Compiler.OptParse.optsIncludePath, default
+# "."; see also Thrift.Compiler.parseThriftFileE: `baseDir </> path`, and
+# FilePath.(</>) only ignores baseDir when `path` is already absolute).
+#
+# A directory named directly on the command line (a plain "-I
+# some/dir" string, or a glob'd filegroup covering "everything in this
+# package") is a bad fit for that: a plain path can't tell "this cell
+# built standalone" apart from "this cell built nested inside another
+# project at a different filesystem depth", and a glob'd directory
+# isn't hermetic - remote execution materializes only an action's
+# *declared* inputs, not whatever real files happen to sit next to the
+# main one in the source tree (which is also what made a shared
+# "thrift" symlink inside both lib/ and tests/ - see thrift/BUCK at
+# the cell root - actively break: Buck2 saw one input (a glob covering
+# the symlink itself) wanting it to be a leaf/symlink, and another
+# input (an explicit thrift_file reference reached *through* it)
+# wanting the same path to be a real directory, and refused to merge
+# the two).
+#
+# So instead: every file an `include` statement might ever need is reached
+# through `deps` - other thrift_srcs_export()/thrift_library() targets,
+# whose own .thrift files (and *their* deps, transitively - see
+# ThriftSrcsInfo below) get merged into one fresh directory via
+# ctx.actions.symlinked_dir() before running the compiler *from inside
+# it*, relying on the "." default to do the resolving. That directory is
+# a completely ordinary derived artifact, so RE ships it (and the real
+# files it points at) to the worker like any other action input - nothing
+# about it depends on where this cell happens to sit in a checkout.
+_RUN_SCRIPT = '''
+set -eu
+root="$(pwd)"
+compiler="$root/$1"
+src_dir="$root/$2"
+out="$root/$3"
+name="$4"
+shift 4
+cd "$src_dir"
+exec "$compiler" "$name" -o "$out" "$@"
+'''
+
+# Propagated by thrift_srcs_export() (and hence by thrift_library(), which
+# always creates one) and consumed by thrift_compile() - a transitive set
+# of {relative include path: source artifact} dicts, one per target in the
+# `deps` chain, so a target only has to list its own *direct* thrift deps
+# and still gets the full transitive closure of `include`able files (a
+# depends on b depends on c: a's `deps = ["//:b"]` is enough, a's own
+# thrift_compile() actions see c's files too, without a needing to know c
+# exists). `.traverse()` yields each node's own dict; thrift_compile()
+# merges them all together.
+ThriftSrcsTSet = transitive_set()
+
+ThriftSrcsInfo = provider(fields = {"tset": provider_field(typing.Any)})
+
+def _thrift_srcs_export_impl(ctx: AnalysisContext) -> list[Provider]:
+    children = [dep[ThriftSrcsInfo].tset for dep in ctx.attrs.deps]
+    tset = ctx.actions.tset(ThriftSrcsTSet, value = ctx.attrs.srcs, children = children)
+
+    # A plain merged directory of just this target's *own* direct srcs
+    # (not the transitive closure - thrift_compile() does that merge
+    # itself via the tset above), for anything wanting the raw files
+    # directly rather than through thrift_compile() - e.g. `buck2 build`
+    # on this target alone to inspect what it exports.
+    out = ctx.actions.symlinked_dir("thrift-srcs", ctx.attrs.srcs)
+
+    return [DefaultInfo(default_output = out), ThriftSrcsInfo(tset = tset)]
+
+# Exports a set of .thrift source files (`srcs`, keyed by the relative
+# path an `include` statement elsewhere would name them by) for other
+# thrift_srcs_export()/thrift_library() targets to depend on - directly
+# creating one of these by hand is only needed for raw sources with no
+# Haskell compile of their own at this location (e.g. hsthrift/BUCK's
+# thrift/annotation/*.thrift, reused - and independently compiled - by
+# several different packages); thrift_library() below always creates one
+# implicitly, named after itself, for its own `thrift_files`.
+thrift_srcs_export = rule(
+    impl = _thrift_srcs_export_impl,
+    attrs = {
+        "deps": attrs.list(attrs.dep(providers = [ThriftSrcsInfo]), default = []),
+        "srcs": attrs.dict(attrs.string(), attrs.source(), default = {}),
+    },
+)
+
+# The thrift-compiler package's executable, wherever the project has it (see
+# cabal-buck2/packages.bzl): hsthrift's own compiler, which is "compiler" when
+# hsthrift is built on its own and "hsthrift/compiler" within another project.
+_THRIFT_COMPILER = "//" + PACKAGES["thrift-compiler"] + ":thrift-compiler"
+
+def _thrift_compile_impl(ctx: AnalysisContext) -> list[Provider]:
+    out = ctx.actions.declare_output(ctx.attrs.out, dir = True)
+
+    srcs = {}
+    for dep in ctx.attrs.deps:
+        for group in dep[ThriftSrcsInfo].tset.traverse():
+            srcs.update(group)
+    srcs[ctx.attrs.thrift_name] = ctx.attrs.thrift_file
+    src_dir = ctx.actions.symlinked_dir(ctx.attrs.out + "-src", srcs)
+
+    cmd = cmd_args(
+        "bash",
+        "-c",
+        _RUN_SCRIPT,
+        "bash",
+        ctx.attrs.compiler[RunInfo],
+        src_dir,
+        out.as_output(),
+        ctx.attrs.thrift_name,
+        # Every consumer here wants Haskell output, so --hs is unconditional
+        # rather than something every caller has to remember to pass.
+        "--hs",
+        ctx.attrs.flags,
+    )
+    ctx.actions.run(cmd, category = "thrift_compile")
+
+    sub_targets = {
+        clean_path: [DefaultInfo(default_output = ctx.actions.copy_file(
+            clean_path,
+            out.project(_GEN_PREFIX + "/" + clean_path),
+        ))]
+        for clean_path in ctx.attrs.outs
+    }
+    return [DefaultInfo(default_output = out, sub_targets = sub_targets)]
+
+# `flags` are extra thrift-compiler flags beyond --hs (which is always
+# added - see _thrift_compile_impl) - e.g. ["--use-int"]. `deps` are
+# thrift_srcs_export()/thrift_library() targets providing every file this
+# one's `include`/`hs_include` statements need, transitively - see
+# ThriftSrcsInfo above and this file's own top comment for why that's a
+# `deps` edge rather than a `-I DIR` flag or a glob'd directory.
+# `thrift_name` is the relative path *this* file itself is known as
+# (matching how some other file's `include` statement would name it, if
+# any does - purely cosmetic otherwise). `out` names the output
+# directory; the compiler writes into `out/gen-hs2/...` (or wherever
+# `--gen-prefix` in `flags` says) by default.
+thrift_compile = rule(
+    impl = _thrift_compile_impl,
+    attrs = {
+        "compiler": attrs.exec_dep(providers = [RunInfo], default = _THRIFT_COMPILER),
+        "deps": attrs.list(attrs.dep(providers = [ThriftSrcsInfo]), default = []),
+        "flags": attrs.list(attrs.string(), default = []),
+        "out": attrs.string(default = "gen"),
+        "outs": attrs.list(attrs.string(), default = []),
+        "thrift_file": attrs.source(),
+        "thrift_name": attrs.string(),
+    },
+)
+
+def _thrift_stem(thrift_file):
+    # thrift_file may be a plain path ("if/Foo.thrift") or a target label
+    # referencing an exported file in another package
+    # ("//other/pkg:Foo.thrift") - strip both a leading "//pkg:" and any
+    # directory components to get a name usable as (part of) a target name.
+    base = thrift_file.split(":")[-1].split("/")[-1]
+    return base[:-len(".thrift")] if base.endswith(".thrift") else base
+
+def _thrift_name(thrift_file, full_paths = False):
+    # The relative path thrift_file is known as inside the assembled
+    # directory (see thrift_compile's own comment) - matching how some
+    # other file's `include` statement would name it, so that statement
+    # resolves once merged into the same directory. A cross-package label
+    # ("//other/pkg:Foo.thrift") has no such path to reuse - nothing in
+    # this repo ever `include`s a file referenced that way (it's always
+    # *itself* the main file being compiled, via export_file), so its
+    # in-sandbox name only has to be a valid one, not any particular one.
+    if "//" in thrift_file or thrift_file.startswith(":"):
+        return _thrift_stem(thrift_file) + ".thrift"
+
+    # Two real, incompatible conventions exist for a plain relative path:
+    # hsthrift's own .thrift files `include` each other by a path relative
+    # to whichever package they live in (e.g. "if/Foo.thrift", no package
+    # prefix - inherited from the Makefile era, where the compiler's cwd
+    # was set to that package directly); Glean's own .thrift files
+    # `include` each other by the *full* repo-root-relative path instead
+    # (e.g. "glean/config/service.thrift"). full_paths picks which one a
+    # given thrift_srcs()/thrift_library() caller's files use - it can't
+    # be auto-detected, since both are just plain strings. `True` means
+    # that path is this package's own directory in the project; that's
+    # only right when the project is where the .thrift files' includes
+    # start from, so a project that is a subdirectory of another one (hsthrift
+    # within Glean) gives the package's directory as the includes name it
+    # instead, e.g. full_paths = "thrift/annotation".
+    if full_paths:
+        prefix = native.package_name() if full_paths == True else full_paths
+        return prefix + "/" + thrift_file
+    return thrift_file
+
+def _module_name(path):
+    # "Foo/Bar/Types.hs" -> "Foo.Bar.Types": the module name a Haskell
+    # source at that (module-derived) path declares, which is what the
+    # dict form of a haskell_*() rule's `srcs` is keyed by.
+    base = path[:path.rindex(".")] if "." in path.split("/")[-1] else path
+    return base.replace("/", ".")
+
+def _thrift_compile_all(name, thrift_files, thrift_flags, thrift_file_flags, deps, srcs, full_paths):
+    # Shared by thrift_srcs() and thrift_library() below: declares one
+    # thrift_compile() per thrift_files entry (each one's own `deps`
+    # pointing back at `name`'s own collector target, so every file in
+    # this same call automatically sees every *other* file in it as a
+    # potential `include` target, with no per-file bookkeeping needed -
+    # e.g. tests/if/A.thrift including B/C/D/E.thrift, all declared in the
+    # same thrift_files dict, just works), and returns the resulting srcs
+    # dict for a haskell_*() target.
+    # `srcs` is either a list of hand-written sources, whose module names
+    # are derived from their paths, or a dict keyed by module name already.
+    all_srcs = dict(srcs) if type(srcs) == type({}) else {_module_name(s): s for s in srcs}
+    for thrift_file, outs in thrift_files.items():
+        gen_name = name + "-thrift-" + _thrift_stem(thrift_file)
+        thrift_compile(
+            name = gen_name,
+            thrift_file = thrift_file,
+            thrift_name = _thrift_name(thrift_file, full_paths),
+            flags = thrift_file_flags.get(thrift_file, thrift_flags),
+            deps = deps,
+            outs = outs,
+            exec_compatible_with = ["root//buck2/constraints:opt"],
+        )
+        for out in outs:
+            all_srcs[_module_name(out)] = ":{}[{}]".format(gen_name, out)
+    return all_srcs
+
+# Lower-level than thrift_library() below: creates the same per-file
+# thrift_compile() sub-targets and a `name + "-thrift"` collector (see
+# thrift_srcs_export()) other targets' `deps` can reference, but returns
+# the resulting srcs dict directly instead of also creating a
+# haskell_library() - for haskell_test()/haskell_binary() callers, which
+# own their own top-level target name already (thrift_library() would
+# collide with it - see thrift_library()'s own comment for why its
+# collector uses the *bare* name instead).
+#
+#   haskell_test(
+#       name = "foo",
+#       srcs = thrift_srcs(
+#           name = "foo",
+#           thrift_files = {"if/Foo.thrift": ["Foo/Types.hs"]},
+#           deps = ["//:annotations"],
+#       ),
+#       ...
+#   )
+def thrift_srcs(
+        name,
+        thrift_files = {},
+        thrift_flags = [],
+        thrift_file_flags = {},
+        deps = [],
+        srcs = {},
+        visibility = ["PUBLIC"],
+        full_paths = False):
+    collector = name + "-thrift"
+    thrift_srcs_export(
+        name = collector,
+        srcs = {_thrift_name(f, full_paths): f for f in thrift_files},
+        deps = deps,
+        visibility = visibility,
+    )
+    return _thrift_compile_all(name, thrift_files, thrift_flags, thrift_file_flags, [":" + collector], srcs, full_paths)
+
+# The usual entry point: compiles `thrift_files` (mapping each .thrift
+# file to the list of Haskell files it generates - module paths, same as
+# any other srcs entry, not gen-hs2-prefixed) and declares a
+# `name + "-hs2"` haskell_library() from the result, plus a thrift_srcs_
+# export() at the *bare* `name` other thrift_library()/thrift_srcs() call
+# sites can put in their own `deps` - matching @fbcode_macros's own
+# thrift_library() wrapper (buck2/fbcode_macros/build_defs/thrift_library.
+# bzl), which already has this exact `deps`/`hs2_deps` split for the
+# (Thrift-generated-code-only) targets gen-schema declares.
+#
+# `deps` are other thrift_library() targets (referenced by their own bare
+# `name`) whose .thrift files these thrift_files may `include`, resolved
+# transitively (see ThriftSrcsInfo) - the generated Haskell code almost
+# always ends up importing from them too (e.g. a struct field typed with
+# an included file's own type), so `deps` feeds the -hs2 library's own
+# `deps` as well (via `d + "-hs2"`), not just the thrift_compile()
+# actions. `hs2_deps` are for anything the -hs2 library needs that has no
+# thrift component of its own (fb-util, containers, ...).
+#
+#   thrift_library(
+#       name = "foo",
+#       thrift_files = {"if/Foo.thrift": ["Foo/Types.hs"]},
+#       deps = ["//:annotations"],
+#       hs2_deps = ["//common/util:fb-util"],
+#   )
+#
+# is equivalent to declaring a thrift_compile() per .thrift file, adding
+# {"Foo/Types.hs": ":<gen-target>[Foo/Types.hs]", ...} to srcs by hand,
+# and writing the haskell_library() out explicitly, as hsthrift/lib/BUCK
+# originally did for gen-rpc-options/gen-application-exception.
+def thrift_library(
+        name,
+        thrift_files = {},
+        thrift_flags = [],
+        thrift_file_flags = {},
+        deps = [],
+        hs2_deps = [],
+        srcs = {},
+        visibility = ["PUBLIC"],
+        full_paths = False,
+        **haskell_kwargs):
+    thrift_srcs_export(
+        name = name,
+        srcs = {_thrift_name(f, full_paths): f for f in thrift_files},
+        deps = deps,
+        visibility = visibility,
+    )
+    all_srcs = _thrift_compile_all(name, thrift_files, thrift_flags, thrift_file_flags, [":" + name], srcs, full_paths)
+    haskell_library(
+        name = name + "-hs2",
+        srcs = all_srcs,
+        deps = [d + "-hs2" for d in deps] + hs2_deps,
+        visibility = visibility,
+        **haskell_kwargs
+    )
diff --git a/buck2/toolchains/BUCK b/buck2/toolchains/BUCK
new file mode 100644
--- /dev/null
+++ b/buck2/toolchains/BUCK
@@ -0,0 +1,6 @@
+load(":defaults.bzl", "default_haskell_toolchain", "default_toolchains")
+
+# Defaults for other toolchains
+default_toolchains()
+
+default_haskell_toolchain(name = "haskell")
diff --git a/buck2/toolchains/defaults.bzl b/buck2/toolchains/defaults.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/toolchains/defaults.bzl
@@ -0,0 +1,154 @@
+load("@third-party-haskell//:tools.bzl", "CC", "CC_FINGERPRINT", "CC_TYPE", "CXX", "GHC", "GHC_DYNAMIC", "GHC_FINGERPRINT", "GHC_PKG", "GHC_VERSION", "HADDOCK", "HSC2HS", "LINKER")
+load("@prelude//haskell:per_module_worker.bzl", "toolchain_per_module_worker")
+load("@prelude//tests:test_toolchain.bzl", "noop_test_toolchain")
+load("@prelude//toolchains:cxx.bzl", "system_cxx_toolchain")
+load("@prelude//toolchains:genrule.bzl", "system_genrule_toolchain")
+load("@prelude//toolchains:python.bzl", "system_python_bootstrap_toolchain")
+load("@prelude//toolchains:remote_test_execution.bzl", "remote_test_execution_toolchain")
+load(":haskell.bzl", "haskell_toolchain")
+
+# Whether actions upload their results to the remote action cache, if there
+# is one, when they say nothing about it (see `cabal buck2 --cache`).
+_DEFAULT_ALLOW_CACHE_UPLOAD = read_root_config("buck2", "default_allow_cache_upload", "false").lower() == "true"
+
+# The Haskell toolchain for a project set up by `cabal buck2`. A project can
+# define its own toolchains cell and call this, overriding any attribute of
+# haskell_toolchain(), e.g. to use a compiler that it builds itself.
+#
+# The tools are those of the GHC that `cabal buck2` configured the project
+# with, by the symlinks to them that it renews each time it runs
+# (third-party/haskell/toolchain/, relative to the project root, where build
+# actions run). Not by their names on the PATH: that would be the PATH of the
+# buck2 daemon, which is that of the shell it started in, and goes on being
+# that after the shell's tools change (a different Nix shell, say), until the
+# daemon restarts.
+def default_haskell_toolchain(name, **kwargs):
+    kwargs.setdefault("compiler", GHC)
+    kwargs.setdefault("packager", GHC_PKG)
+    kwargs.setdefault("haddock", HADDOCK)
+    kwargs.setdefault("hsc2hs", HSC2HS)
+    # Flags for every compile and link, from the project's buckconfig (a
+    # machine-local .buckconfig.local, usually: see the README). buck2 runs
+    # actions with a clean environment, so the -L and -I directories that a
+    # shell sets up (LIBRARY_PATH, CPATH, a Nix or Homebrew shell's flags)
+    # don't reach GHC any other way. The root cell's config, not this
+    # cell's: the project's .buckconfig is at the root, and read_config()
+    # here would read the toolchains cell's own (nonexistent) one.
+    kwargs.setdefault("compiler_flags", read_root_config("haskell", "compiler_flags", "").split())
+    kwargs.setdefault("linker_flags", read_root_config("haskell", "linker_flags", "").split())
+    # How targets that don't set compile_granularity are compiled, from the
+    # project's buckconfig: "target" (the default) or "module".
+    kwargs.setdefault("compile_granularity", read_root_config("haskell", "compile_granularity", "") or "target")
+    # See prelude/haskell/per_module_worker.bzl.
+    kwargs.setdefault("per_module_worker", toolchain_per_module_worker())
+    # GHC_DYNAMIC is what `ghc --info` says of the configured GHC
+    # (`("GHC Dynamic", ...)`), so it follows a change of GHC too.
+    kwargs.setdefault("dynamic_ghc", GHC_DYNAMIC)
+    kwargs.setdefault("ghc_version", GHC_VERSION)
+    # Under asan, GHC's own process needs the ASAN runtime already loaded
+    # before Template Haskell dlopen's an asan-instrumented dependency
+    # mid-compile (confirmed empirically - see buck2/prelude/haskell/
+    # toolchain.bzl's own comment on `compile_env`, and buck2.md). The
+    # runtime here must match whichever compiler actually produces this
+    # project's cxx_library .so's - the C++ compiler of the C/C++ toolchain
+    # (CXX: see default_toolchains() below), not the linker; mixing
+    # compile/link drivers is fine, but the ASAN runtime ABI must match the
+    # *compiler*. `compile_env`'s values are shell-evaluated at build-action
+    # time (see haskell/compile.bzl), so this asks the compiler where its
+    # runtime is on the machine doing the build. Only correct while CXX is
+    # clang: for gcc the runtime is `libasan.so`
+    # (`g++ -print-file-name=libasan.so`).
+    # CABAL_BUCK2_GHC and CABAL_BUCK2_CC are not read by anything: they are
+    # there so that fingerprints of the GHC installation and of the C toolchain
+    # (GHC_FINGERPRINT and CC_FINGERPRINT, see third-party/haskell/tools.bzl)
+    # are part of every compile and link action, and so of its cache key.
+    # `compiler` above is only the path of a symlink, the same wherever GHC is
+    # installed, and the files of the installations aren't tracked by buck2.
+    # GHC runs the C compiler to preprocess a module that uses CPP, and to
+    # link.
+    kwargs.setdefault("compile_env", select({
+        "root//buck2/constraints:asan": {
+            "CABAL_BUCK2_GHC": GHC_FINGERPRINT,
+            "CABAL_BUCK2_CC": CC_FINGERPRINT,
+            "LD_PRELOAD": "$(" + CXX + " -print-file-name=libclang_rt.asan-x86_64.so)",
+            # This preload leaks into every subprocess GHC spawns while
+            # compiling (not just the dlopen'd .so's it's actually for) -
+            # including plain system tools like `ld`/`bash`/`gcc` that
+            # aren't written to be leak-clean under a leak-checking
+            # allocator and were never meant to be instrumented at all.
+            # Disable leak detection for this incidental, build-tooling-
+            # wide preload; the C++ code we actually care about checking
+            # still gets real leak detection when the *final executable*
+            # itself is linked with -fsanitize=address (see haskell.bzl's
+            # _ASAN_LINKER_FLAGS), which is a separate, unaffected setting.
+            "ASAN_OPTIONS": "detect_leaks=0",
+        },
+        "DEFAULT": {"CABAL_BUCK2_GHC": GHC_FINGERPRINT, "CABAL_BUCK2_CC": CC_FINGERPRINT},
+    }))
+    kwargs.setdefault("link_env", {"CABAL_BUCK2_GHC": GHC_FINGERPRINT, "CABAL_BUCK2_CC": CC_FINGERPRINT})
+    kwargs.setdefault("visibility", ["PUBLIC"])
+    haskell_toolchain(name = name, **kwargs)
+
+# The toolchains besides Haskell's that the rules of a project set up by
+# `cabal buck2` use. The project's C and C++ compiler flags (`c_flags`,
+# `cxx_flags`: e.g. its language standard and target CPU) are the C/C++
+# toolchain's.
+#
+# The C and C++ compilers are those `cabal buck2` chose (see
+# Distribution.Client.Buck2.Toolchain in cabal-buck2): the C compiler the user
+# gave Cabal for `gcc` (`--with-gcc`, or `gcc-location:` in the
+# `program-locations` of the project file) and the C++ compiler of the same
+# name next to it, else GHC's if it has absolute paths for them (a GHC built
+# by Nix), else clang and clang++, linking with g++. Like GHC (see
+# default_haskell_toolchain()), by their symlinks under
+# third-party/haskell/toolchain/. Each is in a directory named by the
+# fingerprint of the C toolchain (CC_FINGERPRINT), so that the fingerprint is
+# part of the command of every action that runs one, and so of its key: buck2
+# doesn't track the files of the tools, and the paths of the symlinks are the
+# same wherever the tools are installed.
+def default_toolchains(c_flags = [], cxx_flags = []):
+    system_cxx_toolchain(
+        name = "cxx",
+        c_flags = c_flags,
+        cxx_flags = cxx_flags,
+        compiler = CC,
+        cxx_compiler = CXX,
+        compiler_type = CC_TYPE,
+        linker = LINKER,
+        # Unlike most actions, C and C++ compiles don't leave uploading to
+        # `buck2.default_allow_cache_upload`: they upload only if the toolchain
+        # (or the target) says so. So the toolchain follows that config.
+        c_compiler_allow_cache_upload = _DEFAULT_ALLOW_CACHE_UPLOAD,
+        cxx_compiler_allow_cache_upload = _DEFAULT_ALLOW_CACHE_UPLOAD,
+        visibility = ["PUBLIC"],
+    )
+
+    # The C++ toolchain's default names this in an arm of a select() that is
+    # never chosen (see _cxx_toolchain() in decls/toolchains_common.bzl), so
+    # it only has to exist: for queries of the unconfigured graph (uquery),
+    # which follow every arm.
+    native.alias(
+        name = "cxx_no_default_deps",
+        actual = ":cxx",
+        visibility = ["PUBLIC"],
+    )
+
+    system_genrule_toolchain(
+        name = "genrule",
+        visibility = ["PUBLIC"],
+    )
+
+    system_python_bootstrap_toolchain(
+        name = "python_bootstrap",
+        visibility = ["PUBLIC"],
+    )
+
+    remote_test_execution_toolchain(
+        name = "remote_test_execution",
+        visibility = ["PUBLIC"],
+    )
+
+    noop_test_toolchain(
+        name = "test",
+        visibility = ["PUBLIC"],
+    )
diff --git a/buck2/toolchains/haskell.bzl b/buck2/toolchains/haskell.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/toolchains/haskell.bzl
@@ -0,0 +1,96 @@
+load("@prelude//haskell:toolchain.bzl", "HaskellPlatformInfo", "HaskellToolchainInfo", "per_module_worker_info", "print_libdir")
+load("@prelude//haskell:per_module_worker.bzl", "build_per_module_worker", "per_module_worker_rts_options", "per_module_worker_session_mode", "per_module_worker_sessions")
+
+def _tool(tool):
+    if isinstance(tool, Dependency):
+        return tool[RunInfo]
+    return tool
+
+def _haskell_toolchain_impl(ctx):
+    compiler = _tool(ctx.attrs.compiler)
+    worker = _worker(ctx, compiler)
+    sessions = int(ctx.attrs.per_module_worker_sessions) if ctx.attrs.per_module_worker_sessions else None
+    session_mode = ctx.attrs.per_module_worker_session_mode or None
+    return [
+        DefaultInfo(),
+        HaskellToolchainInfo(
+            compile_granularity = ctx.attrs.compile_granularity,
+            compiler = compiler,
+            packager = _tool(ctx.attrs.packager),
+            linker = compiler,
+            haddock = _tool(ctx.attrs.haddock),
+            hsc2hs = _tool(ctx.attrs.hsc2hs),
+            compiler_flags = ctx.attrs.compiler_flags,
+            linker_flags = ctx.attrs.linker_flags,
+            compile_env = ctx.attrs.compile_env,
+            link_env = ctx.attrs.link_env,
+            dynamic_ghc = ctx.attrs.dynamic_ghc,
+            ghc_version = ctx.attrs.ghc_version,
+            libdir = print_libdir(ctx.actions, "libdir", compiler, ctx.attrs.compile_env),
+            # The WorkerInfo is made once, here, so that every target names
+            # the same worker. buck2 starts a process for each distinct
+            # worker.
+            per_module_shared_worker = per_module_worker_info(worker, ctx.attrs.compile_env, ctx.attrs.per_module_worker_rts_options, sessions, session_mode) if worker != None else None,
+            per_module_worker_rts_options = ctx.attrs.per_module_worker_rts_options,
+            per_module_worker_sessions = sessions,
+            per_module_worker_session_mode = session_mode,
+            per_module_deps = ctx.attrs.per_module_deps[RunInfo] if ctx.attrs.per_module_deps else None,
+            per_module_compile = ctx.attrs.per_module_compile[RunInfo] if ctx.attrs.per_module_compile else None,
+        ),
+        HaskellPlatformInfo(name = host_info().arch),
+    ]
+
+# The toolchain's persistent worker, or None if it has none (see
+# prelude/haskell/per_module_worker.bzl). It is the toolchain's
+# `per_module_worker_program` if that is set. Otherwise the toolchain builds
+# the worker itself, with its own compiler, from the sources in the prelude.
+def _worker(ctx, compiler):
+    if ctx.attrs.per_module_worker == "none":
+        return None
+    if ctx.attrs.per_module_worker_program:
+        return ctx.attrs.per_module_worker_program[RunInfo]
+    srcs = ctx.attrs._per_module_worker_srcs[DefaultInfo].default_outputs[0]
+    return build_per_module_worker(ctx.actions, compiler, ctx.attrs.compile_env, srcs, ctx.attrs.dynamic_ghc)
+
+# A tool is either the name of a program on $PATH, or a target that builds it.
+def _tool_attr(default):
+    return attrs.one_of(attrs.exec_dep(providers = [RunInfo]), attrs.string(), default = default)
+
+haskell_toolchain = rule(
+    impl = _haskell_toolchain_impl,
+    attrs = {
+        "compiler": _tool_attr("ghc"),
+        "packager": _tool_attr("ghc-pkg"),
+        "haddock": _tool_attr("haddock"),
+        "hsc2hs": _tool_attr("hsc2hs"),
+        "compiler_flags": attrs.list(attrs.string(), default = []),
+        "linker_flags": attrs.list(attrs.string(), default = []),
+        "compile_env": attrs.dict(attrs.string(), attrs.string(), default = {}),
+        "link_env": attrs.dict(attrs.string(), attrs.string(), default = {}),
+        # Whether the `compiler` above is itself dynamically linked.
+        # We need to know this because it affects how Template Haskell
+        # code needs to be compiled. It can be found by running `ghc
+        # --info`: look for the "GHC Dynamic" value.
+        "dynamic_ghc": attrs.bool(default = True),
+        # The version of the `compiler` above, as `ghc --numeric-version`
+        # prints it (see HaskellToolchainInfo).
+        "ghc_version": attrs.string(),
+        # See HaskellToolchainInfo.
+        "compile_granularity": attrs.enum(["target", "module"], default = "target"),
+        "per_module_worker": attrs.enum(["builtin", "none"], default = "builtin"),
+        "per_module_worker_rts_options": attrs.list(attrs.string(), default = per_module_worker_rts_options()),
+        # An empty string means that the worker uses its own default, since
+        # `attrs.option` can't default to a value.
+        "per_module_worker_sessions": attrs.string(default = per_module_worker_sessions()),
+        "per_module_worker_session_mode": attrs.string(default = per_module_worker_session_mode()),
+        # The worker, if the toolchain's GHC can't build it (see
+        # prelude/haskell/per_module_worker.bzl).
+        "per_module_worker_program": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "_per_module_worker_srcs": attrs.dep(default = "prelude//haskell/tools:worker-srcs"),
+        # The tools of the per-module compiles, if the prelude's can't be
+        # used (see per_module_deps in prelude/haskell/toolchain.bzl).
+        "per_module_deps": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+        "per_module_compile": attrs.option(attrs.exec_dep(providers = [RunInfo]), default = None),
+    },
+    is_toolchain_rule = True,
+)
diff --git a/buck2/variant.bzl b/buck2/variant.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/variant.bzl
@@ -0,0 +1,16 @@
+# A target as another configuration builds it: `actual`, through the
+# incoming transition of the variant (a build of the RTS for another of its
+# ways, say).
+
+def _variant_impl(ctx: AnalysisContext) -> list[Provider]:
+    return ctx.attrs.actual.providers
+
+_variant = rule(
+    impl = _variant_impl,
+    attrs = {"actual": attrs.dep()},
+    supports_incoming_transition = True,
+)
+
+def variant(name, actual, transition, **kwargs):
+    """`actual`, configured by `transition` (a transition target)."""
+    _variant(name = name, actual = actual, incoming_transition = transition, **kwargs)
diff --git a/buck2/version.bzl b/buck2/version.bzl
new file mode 100644
--- /dev/null
+++ b/buck2/version.bzl
@@ -0,0 +1,4 @@
+# The release of cabal-buck2 that this checkout of haskell-buck2 is for: there
+# is a branch of the same name for each release. cabal-buck2 checks it, and so
+# does the build spec of each package it generates.
+CABAL_BUCK2_VERSION = "0.6.0.0"
diff --git a/cabal-buck2.cabal b/cabal-buck2.cabal
--- a/cabal-buck2.cabal
+++ b/cabal-buck2.cabal
@@ -1,13 +1,14 @@
 cabal-version:      3.8
 name:               cabal-buck2
-version:            0.5.0.0
+version:            0.6.0.0
 
 -- To ship a new version:
 --   - bump the version above
 --   - update the changelog & README
---   - push the changes to the A.B branch of cabal-buck2
+--   - push the changes to the master branch of cabal-buck2
 --   - create a branch A.B.C.D on haskell-buck2
 --   - push an update to `version.bzl` for A.B.C.D on that branch
+--   - update the buck2 submodule to that branch (the sdist includes it)
 --   - cabal install locally, and check it on a local repo
 --   - wait for CI on cabal-buck2
 --   - cabal sdist, cabal upload, check the candidate
@@ -45,6 +46,134 @@
   test/fixtures/**/PACKAGE
   test/fixtures/**/*.txt
 
+-- The buck2 support code (the haskell-buck2 submodule in buck2/), which
+-- `cabal buck2` copies into a project that doesn't have a buck2/ directory.
+-- Its tests, its CI and documentation images aren't needed, and neither are
+-- the tests of the prelude's Android tooling, which are most of its size.
+--
+-- A wildcard has to have an extension, so there is a pattern for each kind
+-- of file. The data-files test (in test/Main.hs) checks that the patterns
+-- match the files of the submodule, apart from those left out.
+data-files:
+  buck2/**/*.CommandLineProcessor
+  buck2/**/*.CompilerPluginRegistrar
+  buck2/**/*.ExperimentConfigService
+  buck2/**/*.Extension
+  buck2/**/*.KotlinCDLogger
+  buck2/**/*.bat
+  buck2/**/*.broken_json
+  buck2/*.bzl
+  buck2/platforms/**/*.bzl
+  buck2/prelude/**/*.bzl
+  buck2/toolchains/**/*.bzl
+  buck2/**/*.config
+  buck2/**/*.cpp
+  buck2/**/*.erl
+  buck2/**/*.exe
+  buck2/**/*.go
+  buck2/**/*.hrl
+  buck2/**/*.in
+  buck2/prelude/**/*.json
+  buck2/**/*.m
+  buck2/**/*.mobileprovision
+  buck2/**/*.props
+  buck2/**/*.proto
+  buck2/**/*.pyi
+  buck2/**/*.rs
+  buck2/**/*.src
+  buck2/**/*.template
+  buck2/**/*.yaml
+  buck2/**/HelloWorld
+  buck2/**/LICENSE
+  buck2/**/LICENSE-APACHE
+  buck2/**/LICENSE-MIT
+  buck2/**/Makefile
+  buck2/**/README
+  buck2/**/hmaptool
+  buck2/**/xcode_version_checker
+  buck2/*.sh
+  buck2/BUCK
+  buck2/README.md
+  buck2/constraints/**/BUCK
+  buck2/platforms/**/BUCK
+  buck2/prelude/**/*.bxl
+  buck2/prelude/**/*.c
+  buck2/prelude/**/*.h
+  buck2/prelude/**/*.hs
+  buck2/prelude/**/*.md
+  buck2/prelude/.buckconfig
+  buck2/prelude/BUCK
+  buck2/prelude/abi/**/BUCK
+  buck2/prelude/android/**/*.java
+  buck2/prelude/android/**/*.py
+  buck2/prelude/android/**/BUCK
+  buck2/prelude/apple/**/*.plist
+  buck2/prelude/apple/**/*.py
+  buck2/prelude/apple/**/BUCK
+  buck2/prelude/build_mode/**/BUCK
+  buck2/prelude/cfg/**/BUCK
+  buck2/prelude/cpu/**/BUCK
+  buck2/prelude/cxx/**/*.py
+  buck2/prelude/cxx/**/*.sh
+  buck2/prelude/cxx/**/BUCK
+  buck2/prelude/erlang/**/*.sh
+  buck2/prelude/erlang/**/BUCK
+  buck2/prelude/git/**/*.py
+  buck2/prelude/git/**/BUCK
+  buck2/prelude/go/**/BUCK
+  buck2/prelude/go_bootstrap/**/*.py
+  buck2/prelude/go_bootstrap/**/BUCK
+  buck2/prelude/haskell/**/*.py
+  buck2/prelude/haskell/**/BUCK
+  buck2/prelude/http_archive/**/BUCK
+  buck2/prelude/ide_integrations/**/*.py
+  buck2/prelude/ide_integrations/**/BUCK
+  buck2/prelude/java/**/*.py
+  buck2/prelude/java/**/BUCK
+  buck2/prelude/js/**/*.py
+  buck2/prelude/js/**/BUCK
+  buck2/prelude/julia/**/*.py
+  buck2/prelude/julia/**/BUCK
+  buck2/prelude/kotlin/**/*.java
+  buck2/prelude/kotlin/**/*.py
+  buck2/prelude/kotlin/**/BUCK
+  buck2/prelude/os/**/BUCK
+  buck2/prelude/os_lookup/**/BUCK
+  buck2/prelude/platforms/**/BUCK
+  buck2/prelude/python/**/*.py
+  buck2/prelude/python/**/*.sh
+  buck2/prelude/python/**/BUCK
+  buck2/prelude/runtime/**/BUCK
+  buck2/prelude/rust/**/*.py
+  buck2/prelude/rust/**/BUCK
+  buck2/prelude/test/**/*.py
+  buck2/prelude/test/**/BUCK
+  buck2/prelude/third-party/**/*.py
+  buck2/prelude/third-party/**/BUCK
+  buck2/prelude/toolchains/android/BUCK
+  buck2/prelude/toolchains/android/android/**/*.java
+  buck2/prelude/toolchains/android/android/**/BUCK
+  buck2/prelude/toolchains/android/config/**/BUCK
+  buck2/prelude/toolchains/android/src/**/*.jar
+  buck2/prelude/toolchains/android/src/**/*.java
+  buck2/prelude/toolchains/android/src/**/*.kt
+  buck2/prelude/toolchains/android/src/**/BUCK
+  buck2/prelude/toolchains/android/third-party/**/BUCK
+  buck2/prelude/toolchains/android/tools/**/BUCK
+  buck2/prelude/toolchains/apple/**/*.plist
+  buck2/prelude/toolchains/apple/**/BUCK
+  buck2/prelude/toolchains/conan/**/*.py
+  buck2/prelude/toolchains/conan/**/BUCK
+  buck2/prelude/toolchains/cxx/**/BUCK
+  buck2/prelude/toolchains/msvc/**/*.py
+  buck2/prelude/toolchains/msvc/**/BUCK
+  buck2/prelude/windows/**/BUCK
+  buck2/prelude/zip_file/**/*.py
+  buck2/prelude/zip_file/**/BUCK
+  buck2/template/**/PACKAGE
+  buck2/template/.buckconfig
+  buck2/toolchains/**/BUCK
+
 homepage:            https://github.com/simonmar/cabal-buck2
 bug-reports:         https://github.com/simonmar/cabal-buck2/issues
 
@@ -74,6 +203,7 @@
     Distribution.Client.Buck2.Setup
     Distribution.Client.Buck2.Spec
     Distribution.Client.Buck2.Starlark
+    Distribution.Client.Buck2.Toolchain
     Distribution.Client.Buck2.Unpack
     Distribution.Client.Buck2.Version
     Distribution.Client.Buck2.Write
@@ -84,14 +214,14 @@
   build-depends:
     , async         >=2.2.6 && <2.3
     , base          >=4.17 && <4.24
-    , bytestring    >=0.11.5 && <0.12
+    , bytestring    >=0.11.5 && <0.13
     , Cabal         ==3.18.*
     , Cabal-syntax  ==3.18.*
     , cabal-install ==3.18.1.0
     , cabal-install-solver ==3.18.*
-    , containers    >=0.6.7 && <0.7
+    , containers    >=0.6.7 && <0.9
     , directory     >=1.3.8 && <1.4
-    , filepath      ==1.4.*
+    , filepath      >=1.4 && <1.6
     , process       >=1.6 && <1.7
     , stm           >=2.5.1 && <2.6
 
@@ -122,10 +252,10 @@
   build-tool-depends: cabal-buck2:cabal-buck2
   build-depends:
     , base          >=4.17 && <4.24
-    , bytestring    >=0.11.5 && <0.12
+    , bytestring    >=0.11.5 && <0.13
     , Cabal
     , cabal-buck2
-    , containers    >=0.6.7 && <0.7
+    , containers    >=0.6.7 && <0.9
     , directory
     , filepath
     , process
diff --git a/changelog.md b/changelog.md
--- a/changelog.md
+++ b/changelog.md
@@ -1,3 +1,65 @@
+# 0.6.0.0
+
+  * For `cabal-install` version 3.18
+  * **New features**
+    * There is now support for per-module compilation using a GHC
+      worker. For details see the section on "Per-module compilation" in
+      the README.
+    * The Buck2 support code now comes with `cabal-buck2` and is
+      unpacked into `buck2/` automatically if it doesn't exist. The
+      contents of `buck2/` will be upgraded if you switch to a newer
+      version of `cabal-buck2` later. A git checkout of haskell-buck2
+      in `buck2/` still works as before.
+    * A package's `data-files` are now found by `getDataFileName` when
+      its code runs in the buck2 build. This includes the data files of
+      the packages it depends on that buck2 builds. Haskell rules have a
+      `data_dirs` attribute for this, and `cabal-buck2/packages.bzl` has
+      `DATA_PACKAGES`.
+    * `--source-deps` supports cabal.project `source-repository-package`s.
+    * A project's `cabal-buck2.bzl` can give `DEFAULTS` for the generated
+      targets, for every package or for one package, as well as
+      `OVERRIDES` for individual components
+      (see https://github.com/simonmar/cabal-buck2/issues/18).
+    * A test-suite, benchmark or executable that only runs a tool of its
+      `build-tool-depends` can say so with
+      `x-buck2-ignore-build-tool-depends` and
+      `x-buck2-run-tool-depends`, so that buck2 builds the tool once
+      rather than again for the execution platform
+      (see https://github.com/simonmar/haskell-buck2/issues/62).
+    * A component can list the libraries whose code its Template Haskell
+      splices run in `x-buck2-splice-depends`, so that buck2
+      can compile a Template Haskell module without waiting for the rest
+      of its libraries to be linked.
+  * **Changes**
+    * `cabal buck2 --cache` writes its settings to `.buckconfig.local`
+      rather than `.buckconfig`, which is usually committed. A block that
+      an earlier version wrote to `.buckconfig` is moved out the next time
+      `--cache` or `--no-cache` is given.
+    * The way the C/C++ compiler is chosen has changed. Previously it
+      always defaulted to `clang`/`clang++` because those are the Buck2
+      toolchain defaults. Now we use the `--with-gcc` option to Cabal if
+      supplied, or GHC's "C compiler command" if it uses an absolute path,
+      or otherwise the `clang`/`clang++` default as before.
+    * The path to GHC, its tools and the C/C++ compilers are now fixed
+      when you run `cabal buck2` rather than being found via `PATH`
+      (see https://github.com/simonmar/haskell-buck2/issues/29)
+  * **Fixes**
+    * An executable with `enable_profiling = True` now links its libraries'
+      profiled archives whatever the build mode, rather than their
+      non-profiled shared libraries in a dev build
+      (see https://github.com/simonmar/haskell-buck2/issues/30)
+    * The mode flags (-O etc.) now come before the package-specific
+      flags (from `ghc-options` etc.) on the GHC command line.
+    * C and C++ targets are rebuilt when `cabal buck2` finds a different
+      C toolchain, with or without an action cache: the C tools are now run
+      from a directory named by the C toolchain's fingerprint
+      (`third-party/haskell/toolchain/<role>/<fingerprint>/`).
+    * What is compiled against a library sees only the headers in its
+      `install-includes`, as it would with the library installed by Cabal.
+      Previously it saw all of the `include-dirs` of a library with C or
+      C++ sources, and none of those of other libraries. A library's
+      own C, C++ and Haskell code still sees all of them.
+
 # 0.5.0.0
 
   * For `cabal-install` version 3.18
diff --git a/src/Distribution/Client/Buck2/Cache.hs b/src/Distribution/Client/Buck2/Cache.hs
--- a/src/Distribution/Client/Buck2/Cache.hs
+++ b/src/Distribution/Client/Buck2/Cache.hs
@@ -5,9 +5,12 @@
 -- Nothing is run remotely: the cache server (anything that speaks the Bazel
 -- remote execution API's action cache and CAS, such as @bazel-remote@) only
 -- stores results. Turning this on adds a block to the project's
--- @.buckconfig@ (see 'cacheBlock'); the buck2 support code reads
--- @[cabal_buck2] cache@ from it to enable the cache in its execution platform
--- and C\/C++ toolchain.
+-- @.buckconfig.local@ (see 'cacheBlock'), which buck2 reads after
+-- @.buckconfig@: the cache is a setting of this checkout, not of the project,
+-- and @.buckconfig@ is usually committed. The buck2 support code reads
+-- @[cabal_buck2] cache@ from it to enable the cache in its execution platform,
+-- and @buck2.default_allow_cache_upload@ to have the C and C++ compiles and
+-- shared-library links uploaded.
 module Distribution.Client.Buck2.Cache
   ( CacheSetting (..)
   , cacheSetting
@@ -19,16 +22,16 @@
 import Distribution.Client.Compat.Prelude
 import Prelude ()
 
-import System.Directory (doesFileExist)
+import System.Directory (doesFileExist, removeFile)
 import System.FilePath ((</>))
 
 import Distribution.Simple.Flag (flagToMaybe, fromFlagOrDefault)
-import Distribution.Simple.Utils (die', notice)
+import Distribution.Simple.Utils (notice)
 
 import Distribution.Client.Buck2.Flags (Buck2Flags (..))
 
 data CacheSetting
-  = -- | Leave .buckconfig as it is.
+  = -- | Leave the buckconfig files as they are.
     CacheUnchanged
   | CacheOn String
   | CacheOff
@@ -45,27 +48,37 @@
     (Nothing, True) -> Right CacheOff
     (Nothing, False) -> Right CacheUnchanged
 
--- | Add, change or remove the cache's block of @.buckconfig@.
+-- | Add, change or remove the cache's block of @.buckconfig.local@ (which is
+-- created for it, if there isn't one, and removed again if nothing else is
+-- left in it). An earlier version put the block in @.buckconfig@: it is
+-- removed from there.
 configureCache :: Verbosity -> FilePath -> CacheSetting -> IO ()
 configureCache _ _ CacheUnchanged = return ()
 configureCache verbosity projectRoot setting = do
-  let path = projectRoot </> ".buckconfig"
-  exists <- doesFileExist path
-  unless exists $ die' verbosity (path ++ " doesn't exist")
-  old <- readFile path
-  let new = spliceBlock (case setting of CacheOn address -> Just (cacheBlock address); _ -> Nothing) old
-  when (new /= old) $ do
-    length old `seq` writeFile path new
+  movedOut <- spliceFile (projectRoot </> ".buckconfig") Nothing
+  changed <- spliceFile (projectRoot </> ".buckconfig.local") (case setting of CacheOn address -> Just (cacheBlock address); _ -> Nothing)
+  when (movedOut || changed) $
     notice verbosity $
       unlines
         [ case setting of
-            CacheOn address -> "cabal buck2: using the action cache at " ++ address ++ " (see .buckconfig)"
+            CacheOn address -> "cabal buck2: using the action cache at " ++ address ++ " (see .buckconfig.local)"
             _ -> "cabal buck2: no longer using an action cache"
         , "cabal buck2: run `buck2 kill` now: a running buck2 daemon keeps using the old settings"
         , "(with a cache address but half of the new settings it retries connecting for ~45s on every build)"
         ]
+  where
+    -- Whether the file changed.
+    spliceFile path block = do
+      exists <- doesFileExist path
+      old <- if exists then readFile path else return ""
+      let new = spliceBlock block old
+      if new == old
+        then return False
+        else do
+          length old `seq` if all isSpace new then removeFile path else writeFile path new
+          return True
 
--- | The lines @cabal buck2 --cache=ADDRESS@ puts in @.buckconfig@, without the
+-- | The lines @cabal buck2 --cache=ADDRESS@ puts in @.buckconfig.local@, without the
 -- markers. @default_allow_cache_upload@ is needed because most actions of
 -- the prelude don't opt in to having their results uploaded, and
 -- @engine_address@ because buck2 won't connect to the cache without it, even
diff --git a/src/Distribution/Client/Buck2/Configure.hs b/src/Distribution/Client/Buck2/Configure.hs
--- a/src/Distribution/Client/Buck2/Configure.hs
+++ b/src/Distribution/Client/Buck2/Configure.hs
@@ -8,8 +8,9 @@
 import Prelude ()
 
 import qualified Data.Map as Map
+import qualified Data.Map.Strict as Map.Strict
 
-import Control.Concurrent (getNumCapabilities, setNumCapabilities)
+import Control.Concurrent (MVar, getNumCapabilities, modifyMVar, newMVar, setNumCapabilities)
 import Control.Concurrent.STM
   ( atomically
   , modifyTVar'
@@ -45,8 +46,9 @@
 import Distribution.Simple.PackageIndex (InstalledPackageIndex)
 import qualified Distribution.Simple.PackageIndex as PackageIndex
 import Distribution.Simple.Program.Builtin (builtinPrograms)
-import Distribution.Simple.Program.Db (prependProgramSearchPathNoLogging, restoreProgramDb, updateProgram, userSpecifyArgss)
-import Distribution.Simple.Program.Types (ProgramLocation (FoundOnSystem), ConfiguredProgram (programVersion), simpleConfiguredProgram)
+import Distribution.Simple.Program.Db (ProgramDb, configureAllKnownPrograms, configuredPrograms, modifyProgramSearchPath, prependProgramSearchPathNoLogging, restoreProgramDb, updateConfiguredProgs, updateProgram, userSpecifyArgss)
+import Distribution.Simple.Program.Find (ProgramSearchPathEntry (ProgramSearchPathDefault, ProgramSearchPathDir))
+import Distribution.Simple.Program.Types (ProgramLocation (FoundOnSystem), ConfiguredProgram (programMonitorFiles, programOverrideEnv, programVersion), simpleConfiguredProgram)
 import Distribution.Simple.Register (generateRegistrationInfo)
 import qualified Distribution.Simple.Setup as Cabal
 import Distribution.Simple.Program (defaultProgramDb)
@@ -57,6 +59,7 @@
   , componentNameCLBIs
   , distPrefLBI
   , relocatable
+  , withPrograms
   )
 import Distribution.Types.UnitId (UnitId)
 import Distribution.Types.UnqualComponentName (unUnqualComponentName)
@@ -64,7 +67,8 @@
 import Distribution.Verbosity (defaultVerbosityHandles)
 
 import System.Directory (canonicalizePath)
-import System.FilePath ((</>))
+import System.Environment (lookupEnv)
+import System.FilePath (splitSearchPath, (</>))
 
 import Distribution.Client.Buck2.LocalPackages (DependencyMode, builtLocalElabs, componentNamesFor, isBuiltLocally, packageSourceDir, planElab)
 import Distribution.Client.Buck2.Schedule (runDependencyGraph)
@@ -105,9 +109,12 @@
   -> ElaboratedInstallPlan
   -> ElaboratedSharedConfig
   -> InstalledPackageIndex
+  -> [FilePath]
+  -- ^ The directories of the @PATH@.
+  -> ProgramsCache
   -> ElaboratedConfiguredPackage
   -> IO LocalBuildInfo
-localBuildInfoFor verbosity mode distDirLayout plan shared ipi elab = do
+localBuildInfoFor verbosity mode distDirLayout plan shared ipi pathDirs programs elab = do
   -- Real Cabal's own 'InLibrary.configure' falls back to *searching* the
   -- working directory for a @<pkgname>.cabal@ file whenever
   -- 'Cabal.configCabalFilePath' isn't set (see its own use of
@@ -140,19 +147,12 @@
       -- top-level @configure@, which 'InLibrary.configure' skips - so
       -- without this the 'LocalBuildInfo' wouldn't have them, unlike one
       -- from a real @Setup configure@.
-      --
-      -- A tool that buck2 is going to build doesn't exist yet when the
-      -- component is configured, but Cabal wants to know that it is there
-      -- and of a version that suits: it is told so (the tool is put on the
-      -- @PATH@ of the compile actions that use it by buck2).
-      progDb =
-        foldr updateProgram userProgDb builtTools
       userProgDb =
-        userSpecifyArgss (Map.toList (elabProgramArgs elab)) $
+        userSpecifyArgss programArgs $
           prependProgramSearchPathNoLogging
-            (elabExeDependencyPaths elab ++ elabProgramPathExtra elab)
+            extraPaths
             []
-            (restoreProgramDb builtinPrograms (pkgConfigCompilerProgs shared))
+            (withPathDirs pathDirs (restoreProgramDb builtinPrograms (pkgConfigCompilerProgs shared)))
       builtTools =
         [ (simpleConfiguredProgram name (FoundOnSystem name)){programVersion = Just (packageVersion depElab)}
         | uid <- elabOrderExeDependencies elab
@@ -161,6 +161,19 @@
         , Just (CExeName exe) <- [elabComponentName depElab]
         , let name = unUnqualComponentName exe
         ]
+      extraPaths = elabExeDependencyPaths elab ++ elabProgramPathExtra elab
+      programArgs = Map.toList (elabProgramArgs elab)
+  configured <- configureProgramsOnce verbosity programs (extraPaths, programArgs) userProgDb
+  -- A tool that buck2 is going to build (an alex built from source, say)
+  -- doesn't exist yet when the component is configured. Cabal still wants to
+  -- know that the tool is there and that its version is suitable, so we tell
+  -- it the tool has been found, with the version of the package that buck2
+  -- will build it from. buck2 later puts the tool on the @PATH@ of the
+  -- compile actions that use it.
+  --
+  -- This is done after 'configureProgramsOnce', rather than before, because
+  -- each component has its own built tools, and they don't need searching for.
+  let progDb = foldr updateProgram configured builtTools
       buildType = PD.buildType (elabPkgDescription elab)
       inputs =
         InLibrary.libraryConfigureInputsFromElabPackage
@@ -260,6 +273,8 @@
           | elab <- builtLocalElabs mode plan
           ]
 
+  pathDirs <- maybe [] splitSearchPath <$> lookupEnv "PATH"
+  programs <- newMVar Map.empty
   indexVar <- newTVarIO installedIndex
   componentLBIsVar <- newTVarIO Map.empty
 
@@ -267,13 +282,74 @@
     let elab = localElabs Map.! uid
         pkgDesc = elabPkgDescription elab
     idx <- readTVarIO indexVar
-    lbi <- localBuildInfoFor verbosity mode distDirLayout plan shared idx elab
+    lbi <- withoutSearchState =<< localBuildInfoFor verbosity mode distDirLayout plan shared idx pathDirs programs elab
     for_ (componentNamesFor elab pkgDesc) $ \cname -> do
       mipi <- libraryInstalledPackageInfo verbosity lbi pkgDesc cname
       for_ mipi $ \ipi -> atomically $ modifyTVar' indexVar (PackageIndex.insert ipi)
       atomically $ modifyTVar' componentLBIsVar (Map.insert (packageName pkgDesc, cname) lbi)
 
   readTVarIO componentLBIsVar
+
+-- | The program db sets @PATH@ for all of its programs. We switch it from using
+-- @ProgramSearchPathDefault@, which re-does the lookup for every program, to
+-- using an explicit list of directories which we already know.
+-- 
+-- The primary reason for this is memory: re-reading @PATH@ every time leaves
+-- us with many copies of it in memory, significantly increasing allocation on
+-- large projects.
+withPathDirs :: [FilePath] -> ProgramDb -> ProgramDb
+withPathDirs pathDirs = modifyProgramSearchPath (concatMap expand)
+  where
+    expand ProgramSearchPathDefault = map ProgramSearchPathDir pathDirs
+    expand entry = [entry]
+
+-- | A cache of 'ProgramDb's whose programs have all been configured, shared by
+-- every component that this run of @cabal buck2@ configures (see
+-- 'configureProgramsOnce'). Each entry is keyed by the extra search path and
+-- the user-specified program arguments that the 'ProgramDb' was made with,
+-- since those are the only parts of it that differ between components.
+type ProgramsCache = MVar (Map ([FilePath], [(String, [String])]) ProgramDb)
+
+-- | Configure every program that a 'ProgramDb' knows about, reusing an
+-- earlier result from the cache when there is one.
+--
+-- Without this, Cabal's configure would configure the programs separately
+-- for each component. For every known program, it searches the @PATH@ and
+-- then runs the program to find out its version. In a project with many
+-- components that adds up to a lot of processes, and nearly all of the work
+-- is repeated: the result depends only on the extra search path and the
+-- program arguments, and almost every component has the same ones. So the
+-- programs are configured once for each distinct key, and the other
+-- components get the cached result.
+--
+-- The cache stays locked while a 'ProgramDb' is being configured. That way,
+-- when several components that need the same configuration are configured
+-- concurrently, the first one does the work and the others wait for its
+-- result, rather than all configuring it at the same time. The cost is that
+-- components with different keys can't configure their programs in
+-- parallel either, but there are very few distinct keys.
+configureProgramsOnce :: Verbosity -> ProgramsCache -> ([FilePath], [(String, [String])]) -> ProgramDb -> IO ProgramDb
+configureProgramsOnce verbosity cache key progDb =
+  modifyMVar cache $ \dbs -> case Map.lookup key dbs of
+    Just db -> return (dbs, db)
+    Nothing -> do
+      db <- configureAllKnownPrograms verbosity progDb
+      return (Map.insert key db dbs, db)
+
+-- | The 'LocalBuildInfo' without what each configured program keeps of its
+-- search: the @PATH@ it was found on, as an environment override, and every
+-- place it was looked for, as files to monitor. @cabal buck2@ uses neither,
+-- and each program has its own copy, made when the component is configured:
+-- with the @PATH@ of a large development shell, that comes to tens of
+-- megabytes for every component, all kept until the build is generated.
+withoutSearchState :: LocalBuildInfo -> IO LocalBuildInfo
+withoutSearchState lbi = do
+  let progs = updateConfiguredProgs (Map.Strict.map forget) (withPrograms lbi)
+      forget prog = prog{programOverrideEnv = [], programMonitorFiles = []}
+  -- Forced now, or the new 'LocalBuildInfo' would keep the old programs
+  -- until something looked at them.
+  _ <- evaluate (length (configuredPrograms progs))
+  evaluate lbi{withPrograms = progs}
 
 -- | How many jobs a parallel strategy allows to run at once: @-j@ with no
 -- number means one per processor, @-jsem N@ is treated as @-jN@.
diff --git a/src/Distribution/Client/Buck2/Fingerprint.hs b/src/Distribution/Client/Buck2/Fingerprint.hs
--- a/src/Distribution/Client/Buck2/Fingerprint.hs
+++ b/src/Distribution/Client/Buck2/Fingerprint.hs
@@ -87,17 +87,24 @@
 --
 -- It is made from what the tools report about themselves, so it identifies
 -- the versions in use and not the files: the C compiler @GHC@ is configured
--- with (@gcc@, normally) together with @cc@, @c++@, @g++@ and @ld@, the C
--- library, and the C++ standard library the compiler would link.
-ccFingerprint :: Compiler -> IO String
-ccFingerprint compiler = do
+-- with (@gcc@, normally) together with @cc@, @c++@, @g++@ and @ld@, the tools
+-- that buck2 runs for C and C++ (see "Distribution.Client.Buck2.Toolchain"),
+-- the C library, and the C++ standard library the compiler would link.
+ccFingerprint
+  :: Compiler
+  -> [(String, FilePath)]
+  -- ^ The tools that buck2 runs, by role (which, unlike their paths, are the
+  -- same wherever they are installed).
+  -> IO String
+ccFingerprint compiler buck2Tools = do
   let ghcCC = Map.findWithDefault "gcc" "C compiler command" (compilerProperties compiler)
       tools = ordNubOn id [ghcCC, "cc", "c++", "g++", "ld"]
   versions <- mapM (\t -> (,) t <$> firstLine ["--version"] t) tools
+  buck2Versions <- mapM (\(role, t) -> (,) role <$> firstLine ["--version"] t) buck2Tools
   target <- firstLine ["-dumpmachine"] "cc"
   libc <- firstLine ["--version"] "ldd"
   libcxx <- stdlibName
-  return (ccFingerprintOf ([("target", target), ("libc", libc), ("libstdc++", libcxx)] ++ versions))
+  return (ccFingerprintOf ([("target", target), ("libc", libc), ("libstdc++", libcxx)] ++ versions ++ buck2Versions))
   where
     firstLine args cmd = do
       r <- try (readProcessWithExitCode cmd args "")
diff --git a/src/Distribution/Client/Buck2/Flags.hs b/src/Distribution/Client/Buck2/Flags.hs
--- a/src/Distribution/Client/Buck2/Flags.hs
+++ b/src/Distribution/Client/Buck2/Flags.hs
@@ -31,14 +31,14 @@
   [ option
       []
       ["cache"]
-      "Use the remote action cache at ADDRESS (grpc://host:port), only to look up and store results: nothing is run remotely. Written to .buckconfig; later runs keep using it."
+      "Use the remote action cache at ADDRESS (grpc://host:port), only to look up and store results: nothing is run remotely. Written to .buckconfig.local; later runs keep using it."
       buck2CacheAddress
       (\v f -> f{buck2CacheAddress = v})
       (reqArg "ADDRESS" (succeedReadE toFlag) flagToList)
   , option
       []
       ["no-cache"]
-      "Stop using a remote action cache (removes what --cache added to .buckconfig)."
+      "Stop using a remote action cache (removes what --cache added to .buckconfig.local)."
       buck2NoCache
       (\v f -> f{buck2NoCache = v})
       trueArg
diff --git a/src/Distribution/Client/Buck2/Generate.hs b/src/Distribution/Client/Buck2/Generate.hs
--- a/src/Distribution/Client/Buck2/Generate.hs
+++ b/src/Distribution/Client/Buck2/Generate.hs
@@ -50,6 +50,7 @@
   , TestSuite (testInterface, testName)
   , TestSuiteInterface (..)
   , buildToolDepends
+  , customFieldsBI
   , asmOptions
   , asmSources
   , autogenModules
@@ -71,6 +72,7 @@
   , hcOptions
   , hsSourceDirs
   , includeDirs
+  , installIncludes
   , libExposed
   , otherModules
   , buildType
@@ -91,6 +93,7 @@
 import Distribution.Types.ComponentName (ComponentName)
 import Distribution.Types.Dependency (depLibraries, depPkgName)
 import Distribution.Types.ExeDependency (ExeDependency (..))
+import Distribution.Types.UnqualComponentName (UnqualComponentName)
 import Distribution.Simple.LocalBuildInfo (buildDir)
 import Distribution.Types.BuildType (BuildType (Custom, Configure))
 import Distribution.Types.ModuleReexport (ModuleReexport (..))
@@ -98,7 +101,7 @@
 import Distribution.Types.PackageName (PackageName, unPackageName)
 import Distribution.Types.PkgconfigDependency (PkgconfigDependency (..))
 import Distribution.Types.PkgconfigName (unPkgconfigName)
-import Distribution.Types.UnqualComponentName (unUnqualComponentName)
+import Distribution.Types.UnqualComponentName (unUnqualComponentName, unqualComponentNameToPackageName)
 import Distribution.Utils.Path (getSymbolicPath)
 
 import Distribution.Simple.Build.Macros (generateCabalMacrosHeader)
@@ -325,6 +328,8 @@
           skip (kindName kind ++ " " ++ targetName ++ " (build-type: Custom needs its Setup.hs to be run, unless --enable-custom-setup)")
       | unsupported : _ <- unsupportedSources bi =
           skip (kindName kind ++ " " ++ targetName ++ " (" ++ unsupported ++ " aren't supported)")
+      | Left problem <- buck2Fields kind bi =
+          skip (kindName kind ++ " " ++ targetName ++ " (" ++ problem ++ ")")
       | otherwise =
           case [(dp, ln) | d <- targetBuildDepends bi, let dp = depPkgName d, ln <- NES.toList (depLibraries d), (dp, ln) `Set.member` skippedLibs] of
             ((dp, ln) : _) ->
@@ -525,7 +530,15 @@
     , scDeps = map specDep (libraryDeps bi)
     , scReexports = []
     , scHiddenModules = []
-    , scBuildTools = mapMaybe buildToolSpec (ordNub [(pn, exe) | ExeDependency pn exe _ <- buildToolDepends bi])
+    , scBuildTools = mapMaybe buildToolSpec (ordNub [tool | tool <- declaredBuildTools bi, tool `notElem` ignoredBuildTools fields])
+    , scSpliceDepends = map specDep <$> spliceDepends fields
+    , -- Without x-buck2-run-tool-depends, a component runs with all of its
+      -- build-tool-depends on PATH, as it does with cabal test, cabal bench
+      -- and cabal run.
+      scRunTools =
+        if kind == Library
+          then []
+          else mapMaybe buildToolSpec (ordNub (fromMaybe (declaredBuildTools bi) (runTools fields)))
     , scCSources = map getSymbolicPath (cSources bi)
     , scCxxSources = map getSymbolicPath (cxxSources bi)
     , scCmmSources = map getSymbolicPath (cmmSources bi)
@@ -534,12 +547,16 @@
     , scCcOptions = ccOptions bi
     , scCxxOptions = cxxOptions bi
     , scIncludeDirs = map getSymbolicPath (includeDirs bi)
+    , scInstallIncludes = [(getSymbolicPath h, IncludeNotInPackage) | kind == Library, h <- installIncludes bi]
     , scExposed = True
     , scHscOptions = []
     , scGeneratedIncludeDirs = []
     , scPkgconfig = ordNub [unPkgconfigName n | PkgconfigDependency n _ <- pkgconfigDepends bi]
     }
   where
+    -- ifNotOnSkippedLib skips a component whose fields can't be read, so
+    -- the error case can't happen here.
+    fields = either (const (Buck2Fields [] Nothing Nothing)) id (buck2Fields kind bi)
     -- A tool that's neither built by this project nor resolved to a real
     -- external binary can't be put on PATH by buck2: dropped, silently -
     -- most build-tool-depends are Setup.hs-time tools nothing needs on PATH.
@@ -550,6 +567,82 @@
         | otherwise -> Nothing
       where
         n = unUnqualComponentName exe
+
+-- | The dependencies that a component declares in cabal-buck2's special
+-- Cabal extension fields.
+data Buck2Fields = Buck2Fields
+  { ignoredBuildTools :: [(PackageName, UnqualComponentName)]
+  -- ^ The tools in @x-buck2-ignore-build-tool-depends@. Theses are tools that were
+  -- listed in in @build-tool-depends@, but which aren't truly needed for the build.
+  , runTools :: Maybe [(PackageName, UnqualComponentName)]
+  -- ^ The tools in @x-buck2-run-tool-depends@, which the component needs on
+  -- @PATH@ when it runs. This is 'Nothing' if the component doesn't have
+  -- the field, and an empty list if the field is empty.
+  , spliceDepends :: Maybe [(PackageName, LibraryName)]
+  -- ^ The libraries in @x-buck2-splice-depends@, whose code the
+  -- component's Template Haskell splices run. This is 'Nothing' if the
+  -- component doesn't have the field, and an empty list if the field is
+  -- empty.
+  }
+
+-- | Reads a component's 'Buck2Fields'.
+--
+-- Each field is a comma-separated list, written as in the Cabal field that
+-- it refines.
+--
+-- The result is an
+-- error message if a field can't be parsed, if
+-- @x-buck2-ignore-build-tool-depends@ lists a tool that
+-- @build-tool-depends@ doesn't, if a library has
+-- @x-buck2-run-tool-depends@, or if @x-buck2-splice-depends@
+-- lists a library that @build-depends@ doesn't.
+buck2Fields :: ComponentKind -> BuildInfo -> Either String Buck2Fields
+buck2Fields kind bi = do
+  ignored <- fromMaybe [] <$> field ignoreField tool
+  runtime <- field runField tool
+  splice <- fmap (map internal . concat) <$> field spliceField library
+  case [t | t <- ignored, t `notElem` declaredBuildTools bi] of
+    t : _ -> Left (ignoreField ++ " lists " ++ toolName t ++ ", which build-tool-depends doesn't")
+    [] -> pure ()
+  when (kind == Library && isJust runtime) $
+    Left (runField ++ " is only for components that run")
+  -- A library in x-buck2-splice-depends must also be in build-depends,
+  -- which is what makes the component depend on it and link it.
+  case [l | l <- fromMaybe [] splice, l `notElem` libraryDeps bi] of
+    l : _ -> Left (spliceField ++ " lists " ++ libName l ++ ", which build-depends doesn't")
+    [] -> pure ()
+  pure (Buck2Fields ignored runtime splice)
+  where
+    ignoreField = "x-buck2-ignore-build-tool-depends"
+    runField = "x-buck2-run-tool-depends"
+    spliceField = "x-buck2-splice-depends"
+    -- The items that a field lists, or Nothing if the component doesn't
+    -- have the field.
+    field name item = case [value | (key, value) <- customFieldsBI bi, map toLower key == name] of
+      [] -> Right Nothing
+      values -> Just . concat <$> traverse (traverse (parsed name item) . items) values
+    items = filter (not . null) . map (dropWhile isSpace . dropWhileEnd isSpace) . splitOnCommas
+    splitOnCommas s = case break (== ',') s of
+      (item, _ : rest) -> item : splitOnCommas rest
+      (item, []) -> [item]
+    parsed name item s = either (\err -> Left (name ++ ": can't read " ++ show s ++ ": " ++ err)) (Right . item) (eitherParsec s)
+    tool (ExeDependency pn exe _) = (pn, exe)
+    library d = [(depPkgName d, ln) | ln <- NES.toList (depLibraries d)]
+    -- Before cabal-version 3.4, build-depends may name one of the package's
+    -- own sublibraries without the package's name, and Cabal reads it as
+    -- that sublibrary. A name here is read the same way.
+    internal l@(pn, LMainLibName)
+      | l `notElem` libraryDeps bi
+      , d : _ <- [d | d@(_, LSubLibName n) <- libraryDeps bi, unqualComponentNameToPackageName n == pn] =
+          d
+    internal l = l
+    toolName (pn, exe) = prettyShow pn ++ ":" ++ prettyShow exe
+    libName (pn, LMainLibName) = prettyShow pn
+    libName (pn, LSubLibName n) = prettyShow pn ++ ":" ++ prettyShow n
+
+-- | The tools listed by a component's @build-tool-depends@ lists.
+declaredBuildTools :: BuildInfo -> [(PackageName, UnqualComponentName)]
+declaredBuildTools bi = [(pn, exe) | ExeDependency pn exe _ <- buildToolDepends bi]
 
 -- | The project-supplied GHC options (see 'ghcProgramArgs') for a
 -- package. Cabal gives every component of a package the same ones (they
diff --git a/src/Distribution/Client/Buck2/LocalPackages.hs b/src/Distribution/Client/Buck2/LocalPackages.hs
--- a/src/Distribution/Client/Buck2/LocalPackages.hs
+++ b/src/Distribution/Client/Buck2/LocalPackages.hs
@@ -19,6 +19,7 @@
   , localToolTargets
   , localBuildTools
   , wantedBuildTools
+  , packagesWithData
   , projectTestOptions
   ) where
 
@@ -159,14 +160,18 @@
     DependenciesFromSource
   deriving (Eq)
 
--- | Real on-disk source directory for any package buck2 builds from
--- source - a genuinely local one (always 'LocalUnpackedPackage') or an
--- inplace non-local one, resolved the same way
--- 'Distribution.Client.ProjectPlanning.Types.dataDirEnvVarForPackage'
--- does for the same 'BuildInplaceOnly' case: a plain source checkout
--- uses its own path directly, anything fetched as a tarball\/repo was
--- already unpacked to 'distUnpackedSrcDirectory' to be built inplace in
--- the first place.
+-- | The directory on disk that holds the source of a package that buck2
+-- builds from source. For a package that is local to the project, that is
+-- always a 'LocalUnpackedPackage' directory. Any other package was unpacked
+-- from its tarball to 'distUnpackedSrcDirectory' (see
+-- "Distribution.Client.Buck2.Unpack").
+--
+-- That includes a @source-repository-package@. Its location holds the path
+-- of the sdist tarball that cabal made from the checkout, not the path of the
+-- checkout, so it was unpacked like any other tarball. Beware that
+-- 'Distribution.Client.ProjectPlanning.Types.dataDirEnvVarForPackage' in
+-- cabal-install uses that path as if it were the checkout directory, so it
+-- isn't a good model to follow here.
 packageSourceDir :: Verbosity -> DistDirLayout -> ElaboratedConfiguredPackage -> IO FilePath
 packageSourceDir verbosity distDirLayout elab = case elabPkgSourceLocation elab of
   LocalUnpackedPackage dir -> return dir
@@ -174,8 +179,8 @@
   LocalTarballPackage{} -> return unpackedPath
   RemoteTarballPackage{} -> return unpackedPath
   RepoTarballPackage{} -> return unpackedPath
-  RemoteSourceRepoPackage _ (Just localCheckout) -> return localCheckout
-  RemoteSourceRepoPackage{} -> unsupported
+  RemoteSourceRepoPackage _ (Just _) -> return unpackedPath
+  RemoteSourceRepoPackage _ Nothing -> unsupported
   where
     unpackedPath = distUnpackedSrcDirectory distDirLayout (elabPkgSourceId elab)
     unsupported =
@@ -231,16 +236,22 @@
   return (InstallPlan.new (InstallPlan.planIndepGoals plan) (Graph.fromDistinctList (map fst pkgs)), Map.keysSet translated)
   where
     translate pkg = case pkg of
-      InstallPlan.Configured elab
-        | isBuiltLocally mode elab
-        , PD.buildType desc == PD.Custom -> do
-            dir <- packageSourceDir verbosity distDirLayout elab
-            hasConfigure <- doesFileExist (dir </> "configure")
-            let buildType = if hasConfigure then PD.Configure else PD.Simple
-            return (InstallPlan.Configured elab{elabPkgDescription = desc{PD.buildTypeRaw = Just buildType}}, Just (packageId elab, buildType))
-        where
-          desc = elabPkgDescription elab
-      _ -> return (pkg, Nothing)
+      InstallPlan.Configured elab -> translateElab InstallPlan.Configured elab
+      -- With --source-deps, a dependency that an earlier build put in the
+      -- cabal store is in the plan as installed. buck2 still builds it from
+      -- source, so it has to be translated too.
+      InstallPlan.Installed elab -> translateElab InstallPlan.Installed elab
+      InstallPlan.PreExisting{} -> return (pkg, Nothing)
+    translateElab con elab
+      | isBuiltLocally mode elab
+      , PD.buildType desc == PD.Custom = do
+          dir <- packageSourceDir verbosity distDirLayout elab
+          hasConfigure <- doesFileExist (dir </> "configure")
+          let buildType = if hasConfigure then PD.Configure else PD.Simple
+          return (con elab{elabPkgDescription = desc{PD.buildTypeRaw = Just buildType}}, Just (packageId elab, buildType))
+      | otherwise = return (con elab, Nothing)
+      where
+        desc = elabPkgDescription elab
 
 -- | Every package buck2 builds from source. Per-component elaboration gives
 -- each such package one 'ElaboratedConfiguredPackage' per component, all
@@ -373,6 +384,44 @@
     , comp <- PD.pkgBuildableComponents (bpDescription pkg)
     , ExeDependency pn exeName _ <- PD.buildToolDepends (componentBuildInfo comp)
     ]
+
+-- | Which packages' data-files each package built from source may need.
+--
+-- The result maps the name of each package to the packages that have
+-- @data-files:@, out of that package itself and all the packages it depends
+-- on, directly or indirectly, that are also built from source. Code from any
+-- of those packages can end up running in one of this package's components,
+-- and its @Paths_\<pkg\>@ module needs to be told where its data-files are.
+-- Packages with no data-files are left out.
+--
+-- This only applies to locally-built packages: prebuilt packages are
+-- assumed to have their data-files installed where their
+-- @Paths_\<pkg\>@ modules already look.
+--
+-- This works per package rather than per component, so a library is also
+-- given the data-files of a package that only its test-suite depends on.
+-- That does no harm: at worst a compile gets an environment variable, and an
+-- input, that it doesn't use.
+packagesWithData :: [BuiltPackage] -> Map String [String]
+packagesWithData pkgs =
+  Map.fromList
+    [ (prettyShow name, wanted)
+    | name <- Map.keys descriptions
+    , let wanted = [prettyShow dep | dep <- Set.toList (reachable Set.empty [name]), hasData dep]
+    , not (null wanted)
+    ]
+  where
+    descriptions = Map.fromList [(packageName (bpDescription pkg), bpDescription pkg) | pkg <- pkgs]
+    hasData name = maybe False (not . null . PD.dataFiles) (Map.lookup name descriptions)
+    reachable seen [] = seen
+    reachable seen (name : rest) = case Map.lookup name descriptions of
+      Just desc | not (Set.member name seen) -> reachable (Set.insert name seen) (dependencies desc ++ rest)
+      _ -> reachable seen rest
+    dependencies desc =
+      [ depPkgName dep
+      | comp <- PD.pkgBuildableComponents desc
+      , dep <- PD.targetBuildDepends (componentBuildInfo comp)
+      ]
 
 -- | The project's @test-options:@ for each test-suite that has any - only
 -- the elaborated package knows them (they aren't part of the @.cabal@ file
diff --git a/src/Distribution/Client/Buck2/Prebuilt.hs b/src/Distribution/Client/Buck2/Prebuilt.hs
--- a/src/Distribution/Client/Buck2/Prebuilt.hs
+++ b/src/Distribution/Client/Buck2/Prebuilt.hs
@@ -5,6 +5,9 @@
 --
 --  * @third-party/haskell/ghc-bin@: symlink to the GHC bin dir
 --
+--  * @third-party/haskell/toolchain@: symlinks to the tools the toolchains
+--    run (see "Distribution.Client.Buck2.Toolchain")
+--
 --  * @third-party/haskell/ghc-<version>@: a symlink to the GHC lib dir
 --
 --  * @third-party/haskell/cabal-store@: symlink to the Cabal store
@@ -39,13 +42,16 @@
 import System.Directory
   ( createDirectoryIfMissing
   , createFileLink
+  , doesDirectoryExist
   , doesFileExist
   , doesPathExist
+  , listDirectory
   , removeDirectoryRecursive
   , removeFile
   )
 import System.FilePath
-  ( isAbsolute
+  ( dropTrailingPathSeparator
+  , isAbsolute
   , isPathSeparator
   , joinPath
   , makeRelative
@@ -105,6 +111,7 @@
 import Distribution.Types.UnqualComponentName (UnqualComponentName, unUnqualComponentName)
 
 import Distribution.Client.Buck2.Fingerprint (ccFingerprint, ghcFingerprint)
+import Distribution.Client.Buck2.Toolchain (Toolchain (..), findToolchain, linkToolchain)
 import Distribution.Client.Buck2.LocalPackages (ToolTarget (..), planElab)
 import Distribution.Client.Buck2.Version (cabalBuck2Version)
 import Distribution.Client.Buck2.Starlark
@@ -157,8 +164,11 @@
   -- ^ Every @pkg:exe@ named in any local component's own
   -- @build-tool-depends:@, across the whole project - see this
   -- function's own return-value haddock above.
+  -> Map String FilePath
+  -- ^ The program locations the user gave, by program name (see
+  -- 'findToolchain').
   -> IO (Set String, [InstalledPackageInfo])
-generatePrebuilt verbosity projectRoot cabalDirLayout shared depsPlan neededUnits toolTargets localTools wantedBuildTools = do
+generatePrebuilt verbosity projectRoot cabalDirLayout shared depsPlan neededUnits toolTargets localTools wantedBuildTools userProgPaths = do
   ghcProg <-
     maybe (die' verbosity "cabal buck2: no 'ghc' program configured for this project - internal error.") return $
       lookupProgram ghcProgram (pkgConfigCompilerProgs shared)
@@ -185,7 +195,7 @@
           , rpPicByDefault = case pkgConfigPlatform shared of
               Platform _ OSX -> True
               _ -> False
-          , rpExternal = []
+          , rpExternal = Map.empty
           }
 
   createDirectoryIfMissing True targetDir
@@ -229,7 +239,7 @@
   -- say, in which every package is in a store path of its own), they are
   -- reached through a symlink for each directory.
   let external = externalDirs paths (map (takeDirectory . snd) (concatMap libraryFiles packages))
-      paths' = paths{rpExternal = external}
+      paths' = paths{rpExternal = Map.fromList external}
   removeStaleExternal (targetDir </> externalDirName)
   unless (null external) $ do
     notice verbosity $ "cabal buck2: linking " ++ show (length external) ++ " library director" ++ (if length external == 1 then "y" else "ies") ++ " outside GHC's libdir and the cabal store"
@@ -249,9 +259,11 @@
   notice verbosity "cabal buck2: generating third-party/haskell/BUCK"
   writeBuckFile targetDir paths' packages buildToolPaths localTools
 
+  toolchain <- findToolchain verbosity userProgPaths (pkgConfigCompilerProgs shared) compiler
   fingerprint <- ghcFingerprint compiler globalDB
-  ccPrint <- ccFingerprint compiler
-  writeToolsFile targetDir ghcVersionStr fingerprint ccPrint ghcDynamic toolTargets alexPath happyPath
+  ccPrint <- ccFingerprint compiler [("buck2 " ++ role, path) | (role, path) <- [("cc", tcCc toolchain), ("c++", tcCxx toolchain), ("linker", tcLinker toolchain)]]
+  toolPaths <- linkToolchain (targetDir </> "toolchain") "third-party/haskell/toolchain" ccPrint toolchain
+  writeToolsFile targetDir ghcVersionStr fingerprint ccPrint ghcDynamic toolPaths (tcCcType toolchain) toolTargets alexPath happyPath
 
   return (Map.keysSet buildToolPaths, map rpInfo packages)
 
@@ -269,7 +281,7 @@
   -- ^ The extension of a shared library, without the dot: @so@, or @dylib@ on macos.
   , rpPicByDefault :: Bool
   -- ^ Whether GHC's code is always position-independent (as on macOS).
-  , rpExternal :: [(FilePath, FilePath)]
+  , rpExternal :: Map FilePath FilePath
   -- ^ Directories that are neither under GHC's libdir nor the cabal store,
   -- and the symlinks (relative to @third-party\/haskell@) to them, which
   -- they are reached through. See 'externalDirs'.
@@ -295,6 +307,9 @@
   -- ^ Absolute paths, like 'rpProfiledLibs' and 'rpSharedLibs'.
   , rpProfiledLibs :: [FilePath]
   , rpSharedLibs :: [(String, FilePath)]
+  , rpRuntimeSharedLibs :: [(String, FilePath)]
+  -- ^ Shared libraries that an executable needs at run time, but that
+  -- we shouldn't explicitly link: the RTS for example.
   }
 
 -- | Every library file found for the package, and what to call it.
@@ -302,7 +317,7 @@
 libraryFiles p =
   [("static", f) | f <- rpStaticLibs p]
     ++ [("profiled", f) | f <- rpProfiledLibs p]
-    ++ [("shared", f) | (_, f) <- rpSharedLibs p]
+    ++ [("shared", f) | (_, f) <- rpSharedLibs p ++ rpRuntimeSharedLibs p]
 
 confPath :: FilePath -> FilePath -> PkgDbKind -> UnitId -> FilePath
 confPath globalRootAbs storeDB kind uid = case kind of
@@ -361,7 +376,14 @@
             if isRts
               then return []
               else findSharedLibs paths ipi
-          return $ Just (ResolvedPackage ipi uid dbKind staticLibs profiledLibs sharedLibs)
+          -- An executable linked against the RTS's shared library still has
+          -- to find it when it runs, so the RTS's shared libraries (one for
+          -- each way) are runtime_shared_libs instead.
+          runtimeSharedLibs <-
+            if isRts
+              then findWaySharedLibs paths ipi
+              else return []
+          return $ Just (ResolvedPackage ipi uid dbKind staticLibs profiledLibs sharedLibs runtimeSharedLibs)
 
 -- | Resolve each candidate filename against @dirs@ in turn, keeping only
 -- the ones that actually exist on disk (unlike gen-haskell-prebuilt.py's
@@ -394,6 +416,22 @@
       mpath <- findOne paths dirs soname
       return ((,) soname <$> mpath)
 
+-- | The shared libraries of every way of each of the package's libraries:
+-- @libHSrts-1.0.3_thr-ghc9.12.4.so@ as well as @libHSrts-1.0.3-ghc9.12.4.so@,
+-- for example.
+findWaySharedLibs :: RepoPaths -> InstalledPackageInfo -> IO [(String, FilePath)]
+findWaySharedLibs paths ipi = do
+  found <- for (ordNub (libraryDynDirs ipi ++ libraryDirs ipi)) $ \dir -> do
+    exists <- doesDirectoryExist dir
+    files <- if exists then listDirectory dir else return []
+    return [(f, dir </> f) | f <- sort files, any (isWayOf f) (hsLibraries ipi)]
+  return (nubBy ((==) `on` fst) (concat found))
+  where
+    suffix = "-ghc" ++ rpGhcVersion paths <.> rpDllExtension paths
+    isWayOf file stem = case stripPrefix ("lib" ++ stem) file of
+      Just rest -> rest == suffix || ("_" `isPrefixOf` rest && suffix `isSuffixOf` rest)
+      Nothing -> False
+
 -- | @.conf@ files use @${pkgroot}@ (the directory containing the package
 -- db) as a portable stand-in for their own absolute location - GHC's own
 -- @ghc-pkg@ expands this when it serves package info, but reading the
@@ -510,6 +548,7 @@
         ++ [("profiled_static_libs", strList profiled) | not (null profiled)]
         ++ [("pic_profiled_static_libs", strList profiled) | not (null profiled)]
         ++ [("shared_libs", VDict [(soname, str sopath) | (soname, abs') <- rpSharedLibs p, Just sopath <- [toRepoRelative paths abs']])]
+        ++ [("runtime_shared_libs", VDict runtime) | not (null runtime)]
         ++ [("cxx_header_dirs", strList headerDirs) | not (null headerDirs)]
         ++ [("exported_linker_flags", strList extraLinkerFlags) | not (null extraLinkerFlags)]
         ++ [("deps", strList depTargets) | not (null depTargets)]
@@ -518,6 +557,7 @@
   where
     info = rpInfo p
     rel = mapMaybe (toRepoRelative paths)
+    runtime = [(soname, str sopath) | (soname, abs') <- rpRuntimeSharedLibs p, Just sopath <- [toRepoRelative paths abs']]
     profiled = rel (rpProfiledLibs p)
     globalDbRel = ("ghc-" ++ rpGhcVersion paths) </> "package.conf.d"
     headerDirs = mapMaybe (toRepoRelative paths) (includeDirs info)
@@ -548,7 +588,7 @@
   | otherwise =
       relTo (rpGlobalRootAbs paths) ("ghc-" ++ rpGhcVersion paths) path
         <|> relTo (rpStoreRootAbs paths) "cabal-store" path
-        <|> listToMaybe (mapMaybe (\(dir, link) -> relTo dir link path) (rpExternal paths))
+        <|> listToMaybe [r | dir <- ancestors path, Just link <- [Map.lookup dir (rpExternal paths)], Just r <- [relTo dir link path]]
 
 -- | The directory of the symlinks to the 'externalDirs'.
 externalDirName :: FilePath
@@ -578,8 +618,9 @@
 externalDirs paths dirs = [(dir, externalDirName </> linkName dir) | dir <- sort maximal]
   where
     outside = ordNub [d | d <- map normalise dirs, isAbsolute d, isNothing (relTo (rpGlobalRootAbs paths) "" d <|> relTo (rpStoreRootAbs paths) "" d)]
-    maximal = [d | d <- outside, not (any (`isProperAncestor` d) outside)]
-    isProperAncestor a d = a /= d && makeRelative a d /= d
+    -- With a set, as there can be thousands of them.
+    outsideSet = Set.fromList outside
+    maximal = [d | d <- outside, not (any (`Set.member` outsideSet) (drop 1 (ancestors d)))]
     linkName dir = takeFileName dir ++ "-" ++ take 12 (showMD5 (md5 (BS8.pack dir)))
 
 -- | Remove the symlinks that an earlier run made.
@@ -588,6 +629,12 @@
   exists <- doesPathExist dir
   when exists $ removeDirectoryRecursive dir
 
+-- | The path and each directory above it, normalised, nearest first.
+ancestors :: FilePath -> [FilePath]
+ancestors = go . dropTrailingPathSeparator . normalise
+  where
+    go p = p : (let up = takeDirectory p in if up == p then [] else go up)
+
 relTo :: FilePath -> FilePath -> FilePath -> Maybe FilePath
 relTo root repoRelPrefix path =
   let r = makeRelative root path
@@ -653,10 +700,10 @@
 inStore :: Maybe FilePath -> Bool
 inStore = maybe False ("cabal-store" `isPrefixOf`)
 
-writeToolsFile :: FilePath -> String -> String -> String -> Bool -> Map String ToolTarget -> Maybe FilePath -> Maybe FilePath -> IO ()
-writeToolsFile targetDir ghcVersionStr fingerprint ccPrint ghcDynamic toolTargets alexPath happyPath =
+writeToolsFile :: FilePath -> String -> String -> String -> Bool -> [(String, FilePath)] -> String -> Map String ToolTarget -> Maybe FilePath -> Maybe FilePath -> IO ()
+writeToolsFile targetDir ghcVersionStr fingerprint ccPrint ghcDynamic toolPaths ccType toolTargets alexPath happyPath =
   writeFile (targetDir </> "tools.bzl") $
-    unlines
+    unlines $
       [ "# @generated by `cabal buck2` - do not edit by hand."
       , "# Re-run `cabal buck2` to update."
       , ""
@@ -670,16 +717,23 @@
       , "GHC_BIN_DIR = \"third-party/haskell/ghc-bin\""
       , "GHC_DYNAMIC = " ++ (if ghcDynamic then "True" else "False")
       , ""
-      , "ALEX = " ++ show ("third-party/haskell/" ++ fromMaybe "missing" alexPath)
-      , "HAPPY = " ++ show ("third-party/haskell/" ++ fromMaybe "missing" happyPath)
-      , ""
-      , "# If buck2 builds them, the targets of the tools and of their data files."
-      , "ALEX_TARGET = " ++ starlarkMaybe (toolLabel <$> Map.lookup "alex" toolTargets)
-      , "ALEX_DATA = " ++ starlarkMaybe (snd <$> (Map.lookup "alex" toolTargets >>= toolData))
-      , "ALEX_DATA_ENV = " ++ starlarkMaybe (fst <$> (Map.lookup "alex" toolTargets >>= toolData))
-      , "HAPPY_TARGET = " ++ starlarkMaybe (toolLabel <$> Map.lookup "happy" toolTargets)
-      , "HAPPY_DATA = " ++ starlarkMaybe (snd <$> (Map.lookup "happy" toolTargets >>= toolData))
-      , "HAPPY_DATA_ENV = " ++ starlarkMaybe (fst <$> (Map.lookup "happy" toolTargets >>= toolData))
+      , "# The tools the toolchains run, by their symlinks under toolchain/ (or,"
+      , "# for one that `cabal buck2` didn't find, its name on the PATH)."
       ]
+      ++ [map toUpper (map (\c -> if c == '-' then '_' else c) role) ++ " = " ++ show path | (role, path) <- toolPaths]
+      ++ [ "# clang or gcc: the kind of C and C++ compiler that CC and CXX are."
+         , "CC_TYPE = " ++ show ccType
+         , ""
+         , "ALEX = " ++ show ("third-party/haskell/" ++ fromMaybe "missing" alexPath)
+         , "HAPPY = " ++ show ("third-party/haskell/" ++ fromMaybe "missing" happyPath)
+         , ""
+         , "# If buck2 builds them, the targets of the tools and of their data files."
+         , "ALEX_TARGET = " ++ starlarkMaybe (toolLabel <$> Map.lookup "alex" toolTargets)
+         , "ALEX_DATA = " ++ starlarkMaybe (snd <$> (Map.lookup "alex" toolTargets >>= toolData))
+         , "ALEX_DATA_ENV = " ++ starlarkMaybe (fst <$> (Map.lookup "alex" toolTargets >>= toolData))
+         , "HAPPY_TARGET = " ++ starlarkMaybe (toolLabel <$> Map.lookup "happy" toolTargets)
+         , "HAPPY_DATA = " ++ starlarkMaybe (snd <$> (Map.lookup "happy" toolTargets >>= toolData))
+         , "HAPPY_DATA_ENV = " ++ starlarkMaybe (fst <$> (Map.lookup "happy" toolTargets >>= toolData))
+         ]
   where
     starlarkMaybe = maybe "None" show
diff --git a/src/Distribution/Client/Buck2/Setup.hs b/src/Distribution/Client/Buck2/Setup.hs
--- a/src/Distribution/Client/Buck2/Setup.hs
+++ b/src/Distribution/Client/Buck2/Setup.hs
@@ -1,55 +1,131 @@
 -- | Set up the project for building with @buck2@
 module Distribution.Client.Buck2.Setup
-  ( checkBuck2Prelude
+  ( ensureBuck2Dir
   , ensureBuckconfigAndPackage
   ) where
 
 import Distribution.Client.Compat.Prelude
 import Prelude ()
 
+import qualified Data.ByteString.Char8 as BS
 import Data.List (stripPrefix)
-import System.Directory (doesDirectoryExist, doesFileExist)
+import System.Directory
+  ( copyFile
+  , createDirectory
+  , doesDirectoryExist
+  , doesFileExist
+  , getPermissions
+  , listDirectory
+  , removeDirectoryRecursive
+  , renameDirectory
+  , setOwnerExecutable
+  , setPermissions
+  )
 import System.FilePath ((</>))
+import System.IO (IOMode (ReadMode), withBinaryFile)
 
 import Distribution.Simple.Utils (die', notice)
 
 import Distribution.Client.Buck2.Version (cabalBuck2Version)
 
+import Paths_cabal_buck2 (getDataDir)
 
--- | Check that the @buck2@ support code is at @buck2\/@, and that it is for
--- this release of @cabal-buck2@: the files it generates are only understood by
--- the same release of it, which is a branch of that name.
-checkBuck2Prelude :: Verbosity -> FilePath -> IO ()
-checkBuck2Prelude verbosity projectRoot = do
+
+-- | Make sure that the @buck2@ support code for this release of @cabal-buck2@
+-- is at @buck2\/@. The files that @cabal-buck2@ generates are only understood
+-- by the support code of the same release.
+--
+-- If there is no @buck2\/@, this copies the support code that was installed
+-- with @cabal-buck2@ into the project. A @buck2\/@ that was copied like this
+-- is replaced when a different release of @cabal-buck2@ runs. Any other
+-- @buck2\/@ (a git checkout of haskell-buck2, for example) is left alone, and
+-- it is an error if it is for a different release.
+ensureBuck2Dir :: Verbosity -> FilePath -> IO ()
+ensureBuck2Dir verbosity projectRoot = do
   exists <- doesDirectoryExist buck2Dir
-  unless exists $
+  if not exists
+    then unpackBuck2Dir verbosity buck2Dir
+    else do
+      found <- readBuck2Version buck2Dir
+      unpacked <- doesFileExist (buck2Dir </> unpackedMarker)
+      case found of
+        Just v | v == cabalBuck2Version -> return ()
+        _ | unpacked -> do
+              notice verbosity $ "cabal buck2: replacing buck2/, which is for " ++ maybe "no release" ("cabal-buck2 " ++) found ++ ", with the copy for cabal-buck2 " ++ cabalBuck2Version
+              removeDirectoryRecursive buck2Dir
+              unpackBuck2Dir verbosity buck2Dir
+        _ ->
+          die' verbosity $
+            unlines
+              [ "The 'buck2/' directory is not for this release of cabal-buck2."
+              , ""
+              , "This is cabal-buck2 " ++ cabalBuck2Version ++ ", and buck2/ is for " ++ maybe "no release (it is from an earlier one)" ("cabal-buck2 " ++) found ++ "."
+              , ""
+              , "cabal-buck2 " ++ cabalBuck2Version ++ " needs the " ++ cabalBuck2Version ++ " branch of https://github.com/simonmar/haskell-buck2. If buck2/ is a git checkout, switch it with:"
+              , ""
+              , "    git -C buck2 fetch && git -C buck2 checkout " ++ cabalBuck2Version
+              , ""
+              , "Or remove buck2/, and 'cabal buck2' will put the copy that comes with it there instead."
+              ]
+  where
+    buck2Dir = projectRoot </> "buck2"
+
+-- | The file in @buck2\/@ that says 'unpackBuck2Dir' made it.
+unpackedMarker :: FilePath
+unpackedMarker = ".cabal-buck2-unpacked"
+
+-- | Copy the support code that was installed with @cabal-buck2@ (its data
+-- files) to @dest@. It is copied to a temporary directory first and then
+-- renamed, so that a copy that fails part of the way doesn't leave a
+-- @buck2\/@ behind.
+unpackBuck2Dir :: Verbosity -> FilePath -> IO ()
+unpackBuck2Dir verbosity dest = do
+  src <- (</> "buck2") <$> getDataDir
+  installed <- doesFileExist (src </> "version.bzl")
+  unless installed $
     die' verbosity $
       unlines
-        [ "No 'buck2/' directory found in the project root."
+        [ "No 'buck2/' directory found in the project root, and the copy of it that should have been installed with cabal-buck2 is missing (from " ++ src ++ ")."
         , "Clone the buck2 prelude and support scripts with:"
         , ""
         , "    git clone --branch " ++ cabalBuck2Version ++ " https://github.com/simonmar/haskell-buck2 buck2"
         , ""
         , "then re-run 'cabal buck2'."
         ]
-  found <- readBuck2Version buck2Dir
-  case found of
-    Just v | v == cabalBuck2Version -> return ()
-    _ ->
-      die' verbosity $
-        unlines
-          [ "The 'buck2/' directory is not for this release of cabal-buck2."
-          , ""
-          , "This is cabal-buck2 " ++ cabalBuck2Version ++ ", and buck2/ is for " ++ maybe "no release (it is from an earlier one)" ("cabal-buck2 " ++) found ++ "."
-          , ""
-          , "cabal-buck2 " ++ cabalBuck2Version ++ " needs the " ++ cabalBuck2Version ++ " branch of https://github.com/simonmar/haskell-buck2. If buck2/ is a git checkout, switch it with:"
-          , ""
-          , "    git -C buck2 fetch && git -C buck2 checkout " ++ cabalBuck2Version
-          , ""
-          , "or use the cabal-buck2 release that matches the buck2/ you have."
-          ]
-  where
-    buck2Dir = projectRoot </> "buck2"
+  let tmp = dest ++ ".unpacking"
+  tmpExists <- doesDirectoryExist tmp
+  when tmpExists $ removeDirectoryRecursive tmp
+  copyTree src tmp
+  writeFile (tmp </> unpackedMarker) $
+    unlines
+      [ "cabal-buck2 copied this directory from its own installed copy of the buck2"
+      , "support code. When a different release of cabal-buck2 runs, it replaces the"
+      , "directory with its own copy. To keep the directory as it is, delete this file."
+      ]
+  renameDirectory tmp dest
+  notice verbosity $ "cabal buck2: created " ++ dest ++ " (from " ++ src ++ ")"
+
+-- | Copy the directory tree at @from@ to @to@. Cabal installs data files
+-- without their executable permission, so a file that starts with @#!@ is made
+-- executable again. When @cabal-buck2@ runs from its source tree (with @cabal
+-- run@, say), the data files are in the haskell-buck2 submodule, whose @.git@
+-- file must not be copied.
+copyTree :: FilePath -> FilePath -> IO ()
+copyTree from to = do
+  createDirectory to
+  names <- listDirectory from
+  for_ (filter (/= ".git") names) $ \name -> do
+    let src = from </> name
+        dst = to </> name
+    isDir <- doesDirectoryExist src
+    if isDir
+      then copyTree src dst
+      else do
+        copyFile src dst
+        script <- withBinaryFile dst ReadMode $ \h -> (== BS.pack "#!") <$> BS.hGet h 2
+        when script $ do
+          perms <- getPermissions dst
+          setPermissions dst (setOwnerExecutable True perms)
 
 -- | The release of @cabal-buck2@ that a checkout of @haskell-buck2@ is for,
 -- from its @version.bzl@ (@CABAL_BUCK2_VERSION = "..."@).
diff --git a/src/Distribution/Client/Buck2/Spec.hs b/src/Distribution/Client/Buck2/Spec.hs
--- a/src/Distribution/Client/Buck2/Spec.hs
+++ b/src/Distribution/Client/Buck2/Spec.hs
@@ -7,6 +7,7 @@
   , ComponentKind (..)
   , kindName
   , SpecComponent (..)
+  , InstallInclude (..)
   , Src (..)
   , SpecDep (..)
   , SpecReexport (..)
@@ -82,6 +83,14 @@
   -- ^ Of a library: the modules that its package doesn't expose (Cabal's
   -- @other-modules@).
   , scBuildTools :: [SpecBuildTool]
+  -- ^ The tools the component needs to be built.
+  , scSpliceDepends :: Maybe [SpecDep]
+  -- ^ The libraries whose code the component's Template Haskell splices
+  -- run. This is Nothing if the component doesn't say which libraries they
+  -- are.
+  , scRunTools :: [SpecBuildTool]
+  -- ^ The tools that the component needs on @PATH@ when it runs. A library
+  -- has none.
   , scCSources :: [FilePath]
   , scCcOptions :: [String]
   , scCxxSources :: [FilePath]
@@ -90,6 +99,11 @@
   , scAsmSources :: [FilePath]
   , scAsmOptions :: [String]
   , scIncludeDirs :: [FilePath]
+  , scInstallIncludes :: [(FilePath, InstallInclude)]
+  -- ^ Of a library: the headers that its package makes available to what
+  -- is compiled against it (Cabal's @install-includes@). Each is a path in
+  -- the package's include directory, with where the header is. Where it is
+  -- is found by "Distribution.Client.Buck2.Write".
   , scExposed :: Bool
   -- ^ Of a library: whether its package is exposed (Cabal's @exposed@).
   , scHscOptions :: [String]
@@ -109,6 +123,15 @@
 -- the package's @Setup.hs@ would have generated, which the project must
 -- provide (@--enable-custom-setup@).
 data Src = SrcFile FilePath | SrcAutogen String | SrcProvided
+
+-- | Where one of a library's @install-includes@ is.
+data InstallInclude
+  = -- | A file of the package, relative to its directory.
+    IncludeInPackage FilePath
+  | -- | Not a file of the package. It is presumably one of the headers that
+    -- the package's @configure@ script generated (see
+    -- 'scGeneratedIncludeDirs').
+    IncludeNotInPackage
 
 -- | A library a component depends on.
 data SpecDep = SpecDep
diff --git a/src/Distribution/Client/Buck2/Toolchain.hs b/src/Distribution/Client/Buck2/Toolchain.hs
new file mode 100644
--- /dev/null
+++ b/src/Distribution/Client/Buck2/Toolchain.hs
@@ -0,0 +1,237 @@
+-- | The tools that the buck2 toolchains run: GHC and the tools that come
+-- with it, and the C and C++ compilers.
+--
+-- buck2 runs them from the PATH of its daemon, which is that of the shell
+-- the daemon started in, and not the one @cabal buck2@ was last run in: after
+-- a change of tools (a different Nix shell, say), it would go on running the
+-- old ones. So each is found here, when @cabal buck2@ runs, and reached
+-- through a symlink under @third-party\/haskell\/toolchain@ that each run
+-- renews. The symlinks, rather than the paths they point at, are what the
+-- toolchains run, so that the commands of the build actions, and so the keys
+-- of the action cache, don't depend on where the tools are installed: the
+-- fingerprints of the toolchains (see "Distribution.Client.Buck2.Fingerprint")
+-- are what tells different tools apart. The C tools' symlinks are in a
+-- directory named by the C toolchain's fingerprint, which so is part of the
+-- command of every action that runs one (see 'linkToolchain'); GHC's
+-- fingerprint is given to its actions in their environment instead (see
+-- @buck2\/toolchains\/defaults.bzl@).
+module Distribution.Client.Buck2.Toolchain
+  ( Toolchain (..)
+  , findToolchain
+  , chooseCompilers
+  , cxxCompilerFor
+  , linkToolchain
+  ) where
+
+import Distribution.Client.Compat.Prelude
+import Prelude ()
+
+import Control.Exception (try)
+import Control.Monad (mfilter)
+import Data.List (isInfixOf, stripPrefix)
+import qualified Data.Map as Map
+
+import System.Directory
+  ( canonicalizePath
+  , createDirectoryIfMissing
+  , createFileLink
+  , doesFileExist
+  , findExecutable
+  , listDirectory
+  , makeAbsolute
+  , removePathForcibly
+  )
+import System.FilePath (hasTrailingPathSeparator, isAbsolute, takeDirectory, takeFileName, (</>))
+import System.Process (readProcessWithExitCode)
+
+import Distribution.Simple.Compiler (Compiler (compilerProperties))
+import Distribution.Simple.Program.Builtin (ghcPkgProgram, ghcProgram, haddockProgram, hsc2hsProgram)
+import Distribution.Simple.Program.Db (ProgramDb, lookupProgram)
+import Distribution.Simple.Program.Types (Program (programName), programPath)
+import Distribution.Simple.Utils (die')
+
+-- | Each tool, by its role: the absolute path that was found for it, or, if
+-- none was, the name to look for on the PATH when the build runs.
+data Toolchain = Toolchain
+  { tcGhc :: FilePath
+  , tcGhcPkg :: FilePath
+  , tcHsc2hs :: FilePath
+  , tcHaddock :: FilePath
+  , tcCc :: FilePath
+  , tcCxx :: FilePath
+  , tcLinker :: FilePath
+  -- ^ The C++ compiler that links C and C++ code (not Haskell, which GHC
+  -- links).
+  , tcCcType :: String
+  -- ^ What kind of compiler 'tcCc' and 'tcCxx' are, as buck2 knows them:
+  -- @clang@ or @gcc@.
+  }
+
+-- | Find the tools of the project's toolchain.
+--
+-- GHC is the configured one, by the file its path leads to through any
+-- symlinks: ghcup's @~\/.ghcup\/bin\/ghc@, say, is a symlink that @ghcup set@
+-- points at another GHC. (Cabal finds GHC's tools the same way.) GHC's own
+-- tools are those Cabal found for it (next to it, normally), unless the user
+-- gave others (@--with-hsc2hs@, say, or @hsc2hs-location:@ in
+-- @program-locations@).
+--
+-- For the C and C++ compilers, see 'chooseCompilers'.
+findToolchain
+  :: Verbosity
+  -> Map String FilePath
+  -- ^ The program locations the user gave (@--with-PROG@, or the
+  -- @program-locations@ of the project file), by program name.
+  -> ProgramDb
+  -- ^ The compiler's configured programs.
+  -> Compiler
+  -> IO Toolchain
+findToolchain verbosity userPaths progdb compiler = do
+  ghc <- maybe (die' verbosity "cabal buck2: no 'ghc' program configured for this project - internal error.") canonicalizePath (configured ghcProgram)
+  ghcPkg <- haskellTool ghcPkgProgram ("ghc-pkg-" ++ ghcVersion)
+  hsc2hs <- haskellTool hsc2hsProgram ("hsc2hs-" ++ ghcVersion)
+  haddock <- haskellTool haddockProgram "haddock"
+  -- Cabal has a g++ program, but no way for the user to give its location
+  -- (no --with-g++, and g++-location isn't a valid field name), so the C++
+  -- compiler that goes with the user's C compiler is found by its name.
+  userCxx <- case Map.lookup "g++" userPaths <|> (Map.lookup "gcc" userPaths >>= cxxCompilerFor) of
+    Nothing -> return Nothing
+    Just c -> do
+      path <- resolve c
+      exists <- if isAbsolute path then doesFileExist path else return False
+      return (if exists then Just path else Nothing)
+  let (ccChoice, cxxChoice, linkerChoice) = chooseCompilers (Map.lookup "gcc" userPaths) userCxx (prop "C compiler command") (prop "C++ compiler command")
+  cc <- resolve ccChoice
+  cxx <- resolve cxxChoice
+  linker <- resolve linkerChoice
+  ccType <- compilerType cc
+  return
+    Toolchain
+      { tcGhc = ghc
+      , tcGhcPkg = ghcPkg
+      , tcHsc2hs = hsc2hs
+      , tcHaddock = haddock
+      , tcCc = cc
+      , tcCxx = cxx
+      , tcLinker = linker
+      , tcCcType = ccType
+      }
+  where
+    prop k = Map.lookup k (compilerProperties compiler)
+    ghcVersion = fromMaybe "" (prop "Project version")
+    configured prog = programPath <$> lookupProgram prog progdb
+    -- The user's location for the tool, else Cabal's, else the name it was
+    -- looked for by before (on the PATH, when the build runs).
+    haskellTool prog fallback = case Map.lookup (programName prog) userPaths of
+      Just path -> resolve path
+      Nothing -> return (fromMaybe fallback (configured prog))
+    -- A name without a directory is looked for on the PATH, as Cabal does.
+    -- If it isn't found, it is left to be looked for when the build runs:
+    -- a tool that a project never uses (a C++ compiler, say) is no reason
+    -- for `cabal buck2` to fail.
+    resolve path
+      | isAbsolute path = return path
+      | any (`elem` "/\\") path || hasTrailingPathSeparator path = makeAbsolute path
+      | otherwise = fromMaybe path <$> findExecutable path
+
+-- | Which C compiler, C++ compiler and linker to use, given the user's C
+-- compiler and the C++ compiler that goes with it (see 'cxxCompilerFor'), and
+-- the C and C++ compilers that GHC is configured with (what @ghc --info@
+-- reports). A name without a directory is looked for on the PATH.
+--
+--  * The user's, if they gave one (@--with-gcc@, or @gcc-location:@ in
+--    @program-locations@): the same that Cabal uses for the C of the packages
+--    it builds.
+--
+--  * Otherwise, GHC's, if it is an absolute path, which it is for a GHC
+--    built by Nix: a toolchain that goes with the GHC, and which changes with
+--    it.
+--
+--  * Otherwise clang, and clang++, linking with g++. GHC's are then names to
+--    look for on the PATH (@gcc@, normally), and these are what the C and C++
+--    of a project has always been built with.
+--
+-- The linker is the C++ compiler when it is the user's or GHC's, and g++
+-- otherwise.
+chooseCompilers
+  :: Maybe FilePath
+  -- ^ The user's @gcc@.
+  -> Maybe FilePath
+  -- ^ The C++ compiler that goes with the user's @gcc@.
+  -> Maybe FilePath
+  -- ^ GHC's C compiler.
+  -> Maybe FilePath
+  -- ^ GHC's C++ compiler.
+  -> (FilePath, FilePath, FilePath)
+chooseCompilers userCc userCxx ghcCc ghcCxx = (cc, cxx, linker)
+  where
+    cc = fromMaybe "clang" (userCc <|> mfilter isAbsolute ghcCc)
+    (cxx, linker) = case userCxx <|> mfilter isAbsolute ghcCxx of
+      Just c -> (c, c)
+      Nothing -> ("clang++", "g++")
+
+-- | The C++ compiler that goes with a C compiler, by the usual names: @gcc@
+-- and @g++@, @clang@ and @clang++@, @cc@ and @c++@ (with any prefix or
+-- version: @x86_64-linux-gnu-gcc-13@, @clang-18@), in the same directory.
+cxxCompilerFor :: FilePath -> Maybe FilePath
+cxxCompilerFor cc = inDir <$> cxxName (takeFileName cc)
+  where
+    inDir name
+      | takeFileName cc == cc = name
+      | otherwise = takeDirectory cc </> name
+    cxxName name
+      | name == "cc" = Just "c++"
+      | otherwise = replaceFirst "clang" "clang++" name <|> replaceFirst "gcc" "g++" name
+    replaceFirst _ _ [] = Nothing
+    replaceFirst old new str@(c : rest)
+      | Just after <- stripPrefix old str =
+          if "++" `isPrefixOf` after then Nothing else Just (new ++ after)
+      | otherwise = (c :) <$> replaceFirst old new rest
+
+-- | Whether a C compiler is clang or gcc, by what it says it is: @gcc@ is
+-- clang on macOS, and @cc@ either.
+compilerType :: FilePath -> IO String
+compilerType cc = do
+  r <- try (readProcessWithExitCode cc ["--version"] "")
+  return $ case r :: Either SomeException (ExitCode, String, String) of
+    Right (_, out, _) | "clang" `isInfixOf` map toLower out -> "clang"
+    _ -> "gcc"
+
+-- | Point the symlinks under @dir@ (@third-party\/haskell\/toolchain@) at the
+-- tools, and return the paths, relative to the project root, that the
+-- toolchains are to run them by, by role. The symlink to each of GHC's tools
+-- is @dir\/\<role\>\/\<name\>@, and to each C tool
+-- @dir\/\<role\>\/\<fingerprint\>\/\<name\>@, with the C toolchain's
+-- fingerprint: buck2 runs the C tools from a toolchain that knows nothing of
+-- fingerprints, so it is in their paths, rather than in the environment of
+-- the actions as GHC's is. Each has the tool's own file name, which some tools
+-- act on (clang is a C++ compiler as clang++ or c++, say). A tool that wasn't
+-- found is left to be looked for on the PATH by its name.
+linkToolchain :: FilePath -> FilePath -> String -> Toolchain -> IO [(String, FilePath)]
+linkToolchain dir dirRel ccPrint tc =
+  traverse
+    link
+    [ ("ghc", [], tcGhc tc)
+    , ("ghc-pkg", [], tcGhcPkg tc)
+    , ("hsc2hs", [], tcHsc2hs tc)
+    , ("haddock", [], tcHaddock tc)
+    , ("cc", [ccPrint], tcCc tc)
+    , ("cxx", [ccPrint], tcCxx tc)
+    , ("linker", [ccPrint], tcLinker tc)
+    ]
+  where
+    link (role, subdirs, path)
+      | isAbsolute path = do
+          let roleDir = dir </> role
+              linkDir = foldl' (</>) roleDir subdirs
+              name = takeFileName path
+          createDirectoryIfMissing True roleDir
+          -- The symlink of an earlier run, and the tool of one if it had
+          -- another name (dangling, maybe: 'doesPathExist' would say it
+          -- isn't there), or the directory of another fingerprint.
+          olds <- listDirectory roleDir
+          for_ olds $ \o -> removePathForcibly (roleDir </> o)
+          createDirectoryIfMissing True linkDir
+          createFileLink path (linkDir </> name)
+          return (role, intercalate "/" ([dirRel, role] ++ subdirs ++ [name]))
+      | otherwise = return (role, path)
diff --git a/src/Distribution/Client/Buck2/Unpack.hs b/src/Distribution/Client/Buck2/Unpack.hs
--- a/src/Distribution/Client/Buck2/Unpack.hs
+++ b/src/Distribution/Client/Buck2/Unpack.hs
@@ -7,11 +7,12 @@
 import Distribution.Client.Compat.Prelude
 import Prelude ()
 
-import System.Directory (doesDirectoryExist, doesFileExist, renameDirectory)
+import System.Directory (doesDirectoryExist, doesFileExist, removeDirectoryRecursive, renameDirectory)
 import System.FilePath ((<.>), (</>))
 
 import Distribution.Client.DistDirLayout (DistDirLayout (..))
 import Distribution.Client.FetchUtils (fetchPackage)
+import Distribution.Client.HashValue (readFileHashValue, showHashValue)
 import Distribution.Client.ProjectPlanning
   ( ElaboratedConfiguredPackage (..)
   , ElaboratedSharedConfig
@@ -24,13 +25,21 @@
 import Distribution.Package (PackageId, packageId, packageName)
 import Distribution.Simple.Utils (createDirectoryIfMissingVerbose, die', info, writeFileAtomic)
 
+import qualified Data.ByteString as BS
+import qualified Data.ByteString.Char8 as BS8
 import qualified Data.ByteString.Lazy as LBS
 
 -- | Fetch (if not already downloaded) and unpack the source of each given
 -- package to where an inplace build of it would find it (under
--- 'distUnpackedSrcDirectory'). Packages whose source isn't a tarball (a
--- user-managed local directory, a source-repository checkout) need no
--- unpacking and are left alone.
+-- 'distUnpackedSrcDirectory').
+--
+-- A @source-repository-package@ is unpacked from a tarball too. Cabal clones
+-- the repository, makes an sdist tarball of the package in the checkout, and
+-- builds from that tarball rather than from the checkout itself, so we do the
+-- same.
+--
+-- A package in a user-managed local directory needs no unpacking and is left
+-- alone.
 unpackInplaceSources
   :: Verbosity
   -> DistDirLayout
@@ -46,6 +55,7 @@
           LocalTarballPackage tarball -> return (Just tarball)
           loc@RemoteTarballPackage{} -> fetched repoctx loc
           loc@RepoTarballPackage{} -> fetched repoctx loc
+          loc@RemoteSourceRepoPackage{} -> fetched repoctx loc
           _ -> return Nothing
         for_ mtarball $ \tarball ->
           unpackTarball
@@ -61,11 +71,23 @@
       return $ case loc' of
         RemoteTarballPackage _ tarball -> Just tarball
         RepoTarballPackage _ _ tarball -> Just tarball
+        RemoteSourceRepoPackage _ tarball -> Just tarball
         _ -> Nothing
 
--- | Unpack a package's tarball to 'distUnpackedSrcDirectory', unless that's
--- already been done. If the index has a newer revision of the @.cabal@ file
--- than the tarball, that's the one used.
+-- | Unpack a package's tarball to 'distUnpackedSrcDirectory', unless that
+-- tarball has already been unpacked there. If the index has a newer revision of
+-- the @.cabal@ file than the tarball, that's the one used.
+--
+-- To tell whether the tarball has already been unpacked, we record its hash in
+-- a stamp file when we unpack it. Checking that the directory exists isn't
+-- enough. The directory is named after the package's version, and when the
+-- @tag:@ of a @source-repository-package@ changes, the version usually
+-- doesn't. So the directory would still be there, with the source of the old
+-- tag in it. When the hash doesn't match, we delete the directory and unpack
+-- the new tarball.
+--
+-- This relies on cabal making the same tarball each time from the same
+-- checkout, which it does: its sdist tarballs are reproducible.
 unpackTarball
   :: Verbosity
   -> DistDirLayout
@@ -78,8 +100,15 @@
 unpackTarball verbosity distDirLayout tarball pkgid cabalFileOverride buildDir = do
   let srcdir = distUnpackedSrcDirectory distDirLayout pkgid
       srcrootdir = distUnpackedSrcRootDirectory distDirLayout
+      stamp = srcdir </> "cabal-buck2" </> "tarball-sha256"
+  hash <- showHashValue <$> readFileHashValue tarball
   exists <- doesDirectoryExist srcdir
-  unless exists $ do
+  stampExists <- doesFileExist stamp
+  unpacked <- if stampExists then (== hash) <$> readStamp stamp else return False
+  unless unpacked $ do
+    when exists $ do
+      info verbosity $ "Removing " ++ srcdir ++ ", which isn't unpacked from " ++ tarball
+      removeDirectoryRecursive srcdir
     createDirectoryIfMissingVerbose verbosity True srcrootdir
     info verbosity $ "Extracting " ++ tarball ++ " to " ++ srcrootdir ++ "..."
     Tar.extractTarGzFile srcrootdir (prettyShow pkgid) tarball
@@ -97,4 +126,16 @@
     -- tarball: move it to where the build directory is.
     let shippedDist = srcdir </> "dist"
     shippedDistExists <- doesDirectoryExist shippedDist
-    when shippedDistExists $ renameDirectory shippedDist buildDir
+    when shippedDistExists $ do
+      -- If the package is being unpacked again (because its tarball
+      -- changed), the build directory has the old tarball's @dist@ in it.
+      -- 'renameDirectory' won't replace a directory that isn't empty, so
+      -- remove it first.
+      buildDirExists <- doesDirectoryExist buildDir
+      when buildDirExists $ removeDirectoryRecursive buildDir
+      renameDirectory shippedDist buildDir
+
+    createDirectoryIfMissingVerbose verbosity True (srcdir </> "cabal-buck2")
+    writeFileAtomic stamp (LBS.fromStrict (BS8.pack hash))
+  where
+    readStamp path = BS8.unpack <$> BS.readFile path
diff --git a/src/Distribution/Client/Buck2/Write.hs b/src/Distribution/Client/Buck2/Write.hs
--- a/src/Distribution/Client/Buck2/Write.hs
+++ b/src/Distribution/Client/Buck2/Write.hs
@@ -8,7 +8,7 @@
 
 import Data.List (stripPrefix)
 import System.Directory (createDirectoryIfMissing, doesFileExist)
-import System.FilePath (takeDirectory, takeFileName, (</>))
+import System.FilePath (isRelative, normalise, takeDirectory, takeFileName, (</>))
 
 import qualified Data.Map as Map
 import qualified Data.Set as Set
@@ -27,7 +27,7 @@
 import Distribution.Simple.Utils (die', notice, warn)
 
 import Distribution.Client.Buck2.Generate
-import Distribution.Client.Buck2.LocalPackages (BuiltPackage (..), rootRelativeDir)
+import Distribution.Client.Buck2.LocalPackages (BuiltPackage (..), packagesWithData, rootRelativeDir)
 import Distribution.Client.Buck2.Spec
 import Distribution.Client.Buck2.Starlark
 import Distribution.Client.Buck2.Version (cabalBuck2Version)
@@ -99,38 +99,70 @@
 -- the paths of its own directory. Nothing in a package's @BUCK.cabal.bzl@ is
 -- relative to the project, so only this file changes when a package moves.
 --
+-- It also records, in @DATA_PACKAGES@, which packages' data-files each
+-- package needs (see 'packagesWithData'), so that @buck2\/cabal.bzl@ can set
+-- the @\<pkg\>_datadir@ environment variables that tell their @Paths_\<pkg\>@
+-- modules where the files are.
+--
 -- It also passes on the project's own customisation of the generated
--- targets: the @OVERRIDES@ of a @cabal-buck2.bzl@ in the project root, if
--- there is one (see @buck2\/cabal.bzl@).
+-- targets, which is the @OVERRIDES@ and @DEFAULTS@ of a @cabal-buck2.bzl@ in
+-- the project root (see @buck2\/cabal.bzl@). Each of them is @{}@ if the
+-- project doesn't define it.
 writePackagesFile :: Verbosity -> FilePath -> [BuiltPackage] -> IO ()
 writePackagesFile verbosity projectRoot pkgs = do
   createDirectoryIfMissing True (takeDirectory path)
-  hasOverrides <- doesFileExist (projectRoot </> "cabal-buck2.bzl")
-  writeFile path (contents hasOverrides)
+  let projectFile = projectRoot </> "cabal-buck2.bzl"
+  hasProjectFile <- doesFileExist projectFile
+  defined <- if hasProjectFile then projectBindings <$> readFile projectFile else return []
+  writeFile path (contents defined)
   notice verbosity $ "cabal buck2: generated cabal-buck2" </> "packages.bzl" ++ " (" ++ show (length pkgs) ++ " package(s))"
   where
     path = projectRoot </> "cabal-buck2" </> "packages.bzl"
-    contents hasOverrides =
+    contents defined =
       unlines
         ( [ "# @generated by `cabal buck2` - do not edit by hand."
-          , "# Re-run `cabal buck2` after adding, removing or moving a package, or"
-          , "# adding or removing cabal-buck2.bzl."
+          , "# Re-run `cabal buck2` after adding, removing or moving a package, or after"
+          , "# adding or removing cabal-buck2.bzl or its OVERRIDES or DEFAULTS."
           , "#"
           , "# The directory of each package that this project builds, from the root of"
-          , "# the project, and the project's overrides of the generated targets. See"
+          , "# the project, the packages whose data files each one needs, and the"
+          , "# project's overrides and defaults for the generated targets. See"
           , "# buck2/cabal.bzl."
           , ""
           ]
-            ++ ["load(\"//:cabal-buck2.bzl\", _OVERRIDES = \"OVERRIDES\")" | hasOverrides]
-            ++ ["", "OVERRIDES = " ++ (if hasOverrides then "_OVERRIDES" else "{}"), ""]
+            ++ [ "load(\"//:cabal-buck2.bzl\", " ++ intercalate ", " ["_" ++ name ++ " = \"" ++ name ++ "\"" | name <- defined] ++ ")"
+               | not (null defined)
+               ]
+            ++ [""]
+            ++ [name ++ " = " ++ (if name `elem` defined then "_" ++ name else "{}") | name <- projectBindingNames]
+            ++ [""]
         )
         ++ renderBinding "PACKAGES" (VDict (Map.toList packages))
+        ++ "\n"
+        ++ renderBinding "DATA_PACKAGES" (VDict (Map.toList (strList <$> packagesWithData pkgs)))
     packages =
       Map.fromList
         [ (prettyShow (packageName (bpDescription pkg)), str (rootRelativeDir projectRoot (bpDir pkg)))
         | pkg <- pkgs
         ]
 
+-- | The names that a project's @cabal-buck2.bzl@ can define for
+-- @packages.bzl@ to pass on.
+projectBindingNames :: [String]
+projectBindingNames = ["OVERRIDES", "DEFAULTS"]
+
+-- | The names out of 'projectBindingNames' that the contents of a
+-- @cabal-buck2.bzl@ define. Starlark can't load a name from a file that
+-- doesn't define it, so this has to be found out before @packages.bzl@ is
+-- written. A name counts as defined when a line starts with an assignment to
+-- it, such as @DEFAULTS = {@.
+projectBindings :: String -> [String]
+projectBindings contents = [name | name <- projectBindingNames, any (assigns name) (lines contents)]
+  where
+    assigns name line = case dropWhile (== ' ') <$> stripPrefix name line of
+      Just ('=' : rest) -> take 1 rest /= "="
+      _ -> False
+
 withoutPrefix :: String -> String
 withoutPrefix = fromMaybe <*> stripPrefix "cabal buck2: "
 
@@ -142,7 +174,8 @@
   traverse_ (notice verbosity) (ptNotes targets)
   when (ptComponentCount targets == 0) $
     warn verbosity $ "cabal buck2: no buck2 targets generated for package " ++ prettyShow pkgName
-  writeFile bzlPath (renderGeneratedBzl pkgName (ptSpec targets))
+  spec <- withInstallIncludes pkgDir (ptSpec targets)
+  writeFile bzlPath (renderGeneratedBzl pkgName spec)
   buckExists <- doesFileExist buckPath
   unless buckExists $ writeFile buckPath renderBuckWrapper
   writeAutogenBuck pkgDir pkgName targets
@@ -154,6 +187,28 @@
       ++ " component(s))"
       ++ (if buckExists then "" else ", created " ++ (rootRelativeDir projectRoot pkgDir </> "BUCK"))
 
+-- | The spec, with where each of its libraries' install-includes is.
+withInstallIncludes :: FilePath -> BuildSpec -> IO BuildSpec
+withInstallIncludes pkgDir spec = do
+  components <- for (specComponents spec) $ \c -> do
+    installs <- for (scInstallIncludes c) $ \(header, _) -> (,) header <$> installIncludeSource pkgDir c header
+    return c{scInstallIncludes = installs}
+  return spec{specComponents = components}
+
+-- | Where one of a library's install-includes is. Cabal looks for it in the
+-- package's directory and then in each of its relative include directories.
+-- In each of those, it looks in the source directory and then in the build
+-- directory, where a configure script generates headers. This looks only
+-- in the source directories. A header that isn't there is left to the
+-- directories of generated headers.
+installIncludeSource :: FilePath -> SpecComponent -> FilePath -> IO InstallInclude
+installIncludeSource pkgDir c header = do
+  let dirs = "." : filter isRelative (scIncludeDirs c)
+  found <- filterM (\dir -> doesFileExist (pkgDir </> dir </> header)) dirs
+  return $ case found of
+    dir : _ -> IncludeInPackage (normalise (dir </> header))
+    [] -> IncludeNotInPackage
+
 -- | Generate an @export_file()@ rule for each autogen file, so that
 -- the files can be easily referenced from somewhere else, including
 -- subdirs.
@@ -237,6 +292,10 @@
       ++ valuesField "reexports" (map reexportValue (scReexports c))
       ++ listField "hidden_modules" (scHiddenModules c)
       ++ valuesField "build_tools" (map buildToolValue (scBuildTools c))
+      ++ valuesField "run_tools" (map buildToolValue (scRunTools c))
+      -- The field is written even when it's empty, because an empty list says
+      -- that the splices run no library's code.
+      ++ [("splice_depends", VList (map depValue deps)) | Just deps <- [scSpliceDepends c]]
       ++ listField "c_sources" (scCSources c)
       ++ listField "cc_options" (scCcOptions c)
       ++ listField "cxx_sources" (scCxxSources c)
@@ -245,10 +304,18 @@
       ++ listField "asm_sources" (scAsmSources c)
       ++ listField "asm_options" (scAsmOptions c)
       ++ listField "include_dirs" (scIncludeDirs c)
+      ++ valuesField "install_includes" (map installIncludeValue (scInstallIncludes c))
       ++ [("exposed", VBool False) | not (scExposed c)]
       ++ listField "hsc_options" (scHscOptions c)
       ++ listField "generated_include_dirs" (scGeneratedIncludeDirs c)
       ++ listField "pkgconfig" (scPkgconfig c)
+
+installIncludeValue :: (FilePath, InstallInclude) -> Value
+installIncludeValue (header, source) =
+  VDict $
+    ("path", str header) : case source of
+      IncludeInPackage file -> [("src", str file)]
+      IncludeNotInPackage -> []
 
 srcValue :: Src -> Value
 srcValue (SrcFile path) = str path
diff --git a/src/Distribution/Client/CmdBuck2.hs b/src/Distribution/Client/CmdBuck2.hs
--- a/src/Distribution/Client/CmdBuck2.hs
+++ b/src/Distribution/Client/CmdBuck2.hs
@@ -36,6 +36,7 @@
 import Distribution.Client.Compat.Prelude
 import Prelude ()
 
+import qualified Data.Map as Map
 import qualified Data.Set as Set
 
 import Distribution.Client.DistDirLayout (DistDirLayout (distProjectRootDirectory))
@@ -45,7 +46,8 @@
   , defaultNixStyleFlags
   , nixStyleOptions
   )
-import Distribution.Client.ProjectConfig (ProjectConfig (..), ProjectConfigShared (..))
+import Distribution.Client.ProjectConfig (PackageConfig (..), ProjectConfig (..), ProjectConfigShared (..))
+import Distribution.Client.ProjectConfig.Types (MapLast (getMapLast))
 import Distribution.Client.ProjectOrchestration
 import Distribution.Client.Targets (UserConstraint (..), UserConstraintScope (..))
 import Distribution.Solver.Types.ConstraintSource (ConstraintSource (ConstraintSourceUnknown))
@@ -84,7 +86,7 @@
   )
 import Distribution.Client.Buck2.Prebuilt (generatePrebuilt)
 import Distribution.Client.Buck2.Setup
-  ( checkBuck2Prelude
+  ( ensureBuck2Dir
   , ensureBuckconfigAndPackage
   )
 import Distribution.Client.Buck2.Write (writeAllPackages)
@@ -130,6 +132,14 @@
       )
     release = alterVersion (take 2) cabalVersion
 
+-- | The program locations that the user gave (@--with-PROG@, or the
+-- @program-locations@ of the project file), by program name: for the local
+-- packages, else for all of them.
+userProgramPaths :: ProjectConfig -> Map String FilePath
+userProgramPaths config =
+  getMapLast (packageConfigProgramPaths (projectConfigLocalPackages config))
+    `Map.union` getMapLast (packageConfigProgramPaths (projectConfigAllPackages config))
+
 -- | Implement @cabal buck2@
 buck2Action :: NixStyleFlags Buck2Flags -> [String] -> GlobalFlags -> IO ()
 buck2Action flags extraArgs globalFlags = do
@@ -145,7 +155,7 @@
         ScriptContext path exemeta -> updateContextAndWriteProjectFile ctx path exemeta
 
       let projectRoot = distProjectRootDirectory (distDirLayout baseCtx)
-      checkBuck2Prelude verbosity projectRoot
+      ensureBuck2Dir verbosity projectRoot
 
       builtCtx <- buildDependencies verbosity mode baseCtx targetSelectors
       (plan, customSetups) <-
@@ -170,6 +180,7 @@
           (localToolTargets projectRoot localPkgs)
           (localBuildTools projectRoot localPkgs)
           (wantedBuildTools localPkgs)
+          (userProgramPaths (projectConfig baseCtx))
 
       -- 'generatePrebuilt' already found and parsed every real @.conf@
       -- file of the resolved dependency closure.
diff --git a/test/Main.hs b/test/Main.hs
--- a/test/Main.hs
+++ b/test/Main.hs
@@ -4,16 +4,20 @@
 module Main (main) where
 
 import Control.Exception (SomeException, bracket, displayException, try)
-import Control.Monad (forM_, unless, when)
-import Data.List (isInfixOf, nub)
+import Control.Monad (forM, forM_, unless, when)
+import Data.List (isInfixOf, isPrefixOf, nub)
 import Data.Maybe (fromMaybe)
 import qualified Data.ByteString.Char8 as BS8
 import qualified Data.Map as Map
+import qualified Data.Set as Set
 import System.Directory
   ( copyFile
   , createDirectoryIfMissing
   , doesDirectoryExist
   , doesFileExist
+  , doesPathExist
+  , executable
+  , getPermissions
   , removeFile
   , findExecutable
   , getTemporaryDirectory
@@ -25,13 +29,19 @@
 import System.Exit (ExitCode (..), exitFailure)
 import System.FilePath ((</>))
 import System.IO (hPutStrLn, stderr)
-import System.Process (CreateProcess (..), callProcess, getCurrentPid, proc, readCreateProcessWithExitCode)
+import System.Process (CreateProcess (..), callProcess, getCurrentPid, proc, readCreateProcessWithExitCode, readProcess)
 
 import Distribution.Client.Buck2.Cache (cacheBlock, spliceBlock)
 import Distribution.Client.Buck2.Fingerprint (ccFingerprintOf, fingerprintOf)
 import Distribution.Client.Buck2.Prebuilt (RepoPaths (..), externalDirs, prebuiltLinkerFlags, toRepoRelative)
+import Distribution.Client.Buck2.Toolchain (chooseCompilers, cxxCompilerFor)
 import Distribution.Client.Buck2.Version (cabalBuck2Version)
 import Distribution.InstalledPackageInfo (InstalledPackageInfo (..), emptyInstalledPackageInfo)
+import Distribution.PackageDescription (dataFiles, packageDescription, specVersion)
+import Distribution.Simple.Glob (matchDirFileGlob)
+import Distribution.Simple.PackageDescription (readGenericPackageDescription)
+import Distribution.Utils.Path (getSymbolicPath, makeSymbolicPath)
+import Distribution.Verbosity (defaultVerbosityHandles, mkVerbosity, silent)
 
 main :: IO ()
 main = do
@@ -53,7 +63,7 @@
     exitFailure
 
 unitTests :: [(String, IO ())]
-unitTests = [("fingerprint", fingerprint), ("cc-fingerprint", ccFingerprint), ("splice-block", spliceBlockTest), ("external-dirs", externalDirsTest), ("linker-flags", linkerFlagsTest)]
+unitTests = [("fingerprint", fingerprint), ("cc-fingerprint", ccFingerprint), ("splice-block", spliceBlockTest), ("external-dirs", externalDirsTest), ("linker-flags", linkerFlagsTest), ("choose-compilers", chooseCompilersTest), ("data-files", dataFilesTest)]
 
 runUnitTest :: (String, IO ()) -> IO Bool
 runUnitTest (name, test) = do
@@ -74,11 +84,15 @@
   , ("custom-setup", customSetup)
   , ("reexports", reexports)
   , ("buck2-version", buck2Version)
+  , ("buck2-unpack", buck2Unpack)
   , ("project-overrides", projectOverrides)
   , ("pkgconfig", pkgconfig)
+  , ("install-includes", installIncludes)
   , ("project-overrides", projectOverrides)
   , ("same-name", sameName)
   , ("normalise-paths", normalisePaths)
+  , ("run-tools", runTools)
+  , ("splice-depends", spliceDepends)
   ]
 
 -- | A library and an executable with the same name in one package, and
@@ -100,6 +114,101 @@
   assertContains "user/BUCK.cabal.bzl" "'exe': 'tool-exe'" userBzl
   assertContains "user/BUCK.cabal.bzl" "'package': 'tool'" userBzl
 
+-- | Check that we handle @x-buck2-ignore-build-tool-depends@ and
+-- @x-buck2-run-tool-depends@ correctly for a test suite. 
+runTools :: Project -> IO ()
+runTools project = do
+  original <- readIn project cabalFile
+  let with = withFields project cabalFile original ["--enable-tests"]
+      tool = "  build-tool-depends: exe-pkg:exe-pkg-exe\n"
+
+  -- Without either field, the executable is both a build tool and a run
+  -- tool, because cabal test puts build-tool-depends on the test's PATH.
+  _ <- with testStanza tool
+  plain <- readIn project bzl
+  assertContains bzl "'build_tools'" plain
+  assertContains bzl "'run_tools'" plain
+
+  -- With both fields, the executable is only a run tool.
+  (_, _) <- with testStanza (tool ++ "  x-buck2-ignore-build-tool-depends: exe-pkg:exe-pkg-exe\n  x-buck2-run-tool-depends: exe-pkg:exe-pkg-exe\n")
+  fields <- readIn project bzl
+  assertNotContains bzl "'build_tools'" fields
+  assertContains bzl "'run_tools': [\n                {\n                    'exe': 'exe-pkg-exe',\n                    'package': 'exe-pkg',\n                },\n            ]" fields
+
+  -- An empty x-buck2-run-tool-depends means that the test runs no tools.
+  _ <- with testStanza (tool ++ "  x-buck2-run-tool-depends:\n")
+  empty <- readIn project bzl
+  assertContains bzl "'build_tools'" empty
+  assertNotContains bzl "'run_tools'" empty
+
+  -- cabal-buck2 rejects fields that it can't use. Its output wraps the
+  -- message, so these checks compare words rather than lines.
+  (_, unlisted) <- with testStanza "  x-buck2-ignore-build-tool-depends: exe-pkg:exe-pkg-exe\n"
+  assertContains "output" "skipping test-suite exe-pkg-test (x-buck2-ignore-build-tool-depends lists exe-pkg:exe-pkg-exe, which build-tool-depends doesn't)" (unwords (words unlisted))
+
+  (_, library) <- with "library\n" "  x-buck2-run-tool-depends: exe-pkg:exe-pkg-exe\n"
+  assertContains "output" "skipping library exe-pkg (x-buck2-run-tool-depends is only for components that run)" (unwords (words library))
+  where
+    cabalFile = "exe-pkg" </> "exe-pkg.cabal"
+    bzl = "exe-pkg" </> "BUCK.cabal.bzl"
+    testStanza = "test-suite exe-pkg-test\n"
+
+-- | A library's @x-buck2-splice-depends@ field becomes its
+-- @splice_depends@ in the build spec, even when the field is
+-- empty. Without the field, the spec has no @splice_depends@. A
+-- field that lists a library that @build-depends@ doesn't is an error.
+spliceDepends :: Project -> IO ()
+spliceDepends project = do
+  original <- readIn project cabalFile
+  let with = withFields project cabalFile original [] stanza
+
+  _ <- with ""
+  plain <- readIn project bzl
+  assertNotContains bzl "'splice_depends'" plain
+
+  _ <- with "  x-buck2-splice-depends: lib-pkg\n"
+  listed <- readIn project bzl
+  assertContains bzl "'splice_depends': [\n                {\n                    'package': 'lib-pkg',\n                },\n            ]" listed
+
+  _ <- with "  x-buck2-splice-depends:\n"
+  empty <- readIn project bzl
+  assertContains bzl "'splice_depends': []" empty
+
+  -- The output wraps the message, so the check compares words rather than
+  -- lines.
+  (_, notDep) <- with "  x-buck2-splice-depends: stm\n"
+  assertContains "output" "skipping library exe-pkg (x-buck2-splice-depends lists stm, which build-depends doesn't)" (unwords (words notDep))
+
+  -- Before cabal-version 3.4 (exe-pkg's is 2.4), build-depends may name a
+  -- sublibrary of the package without the package's name, and so may the
+  -- field.
+  let (before, after) = breakOn "lib-pkg\n" original
+      withHelpers = before ++ "lib-pkg, helpers\n" ++ drop (length "lib-pkg\n") after ++ "\nlibrary helpers\n  build-depends: base\n  default-language: Haskell2010\n"
+  _ <- withFields project cabalFile withHelpers [] stanza "  x-buck2-splice-depends: helpers\n"
+  sublib <- readIn project bzl
+  assertContains bzl "'splice_depends': [\n                {\n                    'package': 'exe-pkg',\n                    'library': 'helpers',\n                },\n            ]" sublib
+  where
+    cabalFile = "exe-pkg" </> "exe-pkg.cabal"
+    bzl = "exe-pkg" </> "BUCK.cabal.bzl"
+    stanza = "library\n"
+
+-- | Runs cabal-buck2 with the package's .cabal file set to @original@,
+-- with @fields@ added at the start of @stanza@.
+withFields :: Project -> FilePath -> String -> [String] -> String -> String -> IO (ExitCode, String)
+withFields project cabalFile original args stanza fields = do
+  let (before, after) = breakOn stanza original
+  writeFile (projectDir project </> cabalFile) (before ++ stanza ++ fields ++ drop (length stanza) after)
+  runBuck2 project args
+
+-- | The text before the first occurrence of @needle@, and the rest.
+breakOn :: String -> String -> (String, String)
+breakOn needle = go ""
+  where
+    go acc rest@(c : cs)
+      | needle `isPrefixOf` rest = (reverse acc, rest)
+      | otherwise = go (c : acc) cs
+    go acc [] = (reverse acc, [])
+
 -- | Paths written with a @.\/@ prefix, in cabal.project and in the file
 -- patterns of a package: buck2 accepts neither in a label nor in a glob.
 normalisePaths :: Project -> IO ()
@@ -142,7 +251,10 @@
       "disabled-stanzas" -> "basic"
       "cache-config" -> "basic"
       "buck2-version" -> "basic"
+      "buck2-unpack" -> "basic"
       "project-overrides" -> "basic"
+      "run-tools" -> "basic"
+      "splice-depends" -> "basic"
       _ -> name
     setup dir = do
       cleanup dir
@@ -257,6 +369,28 @@
   assertDiffers "linker" fp (ccFingerprintOf (changed "ld" "GNU ld 2.43"))
   assertDiffers "target" fp (ccFingerprintOf (changed "target" "aarch64-linux-gnu"))
 
+-- | The C compiler, C++ compiler and linker for buck2: the user's, else GHC's
+-- if it has absolute paths for them (Nix), else clang, linking with g++.
+chooseCompilersTest :: IO ()
+chooseCompilersTest = do
+  let choose uc ux gc gx = let (c, x, l) = chooseCompilers uc ux gc gx in unwords [c, x, l]
+      nixCc = "/nix/store/aaa-gcc-wrapper/bin/cc"
+      nixCxx = "/nix/store/aaa-gcc-wrapper/bin/c++"
+  assertEqual "GHC's are names" "clang clang++ g++" (choose Nothing Nothing (Just "gcc") (Just "g++"))
+  assertEqual "GHC doesn't say" "clang clang++ g++" (choose Nothing Nothing Nothing Nothing)
+  assertEqual "GHC's are absolute" (unwords [nixCc, nixCxx, nixCxx]) (choose Nothing Nothing (Just nixCc) (Just nixCxx))
+  assertEqual "the user's" "clang clang++ clang++" (choose (Just "clang") (Just "clang++") (Just nixCc) (Just nixCxx))
+  assertEqual "the user's C compiler only" (unwords ["clang", nixCxx, nixCxx]) (choose (Just "clang") Nothing (Just nixCc) (Just nixCxx))
+  -- The C++ compiler that goes with the user's C compiler.
+  let cxxFor cc = fromMaybe "none" (cxxCompilerFor cc)
+  assertEqual "gcc" "g++" (cxxFor "gcc")
+  assertEqual "clang" "clang++" (cxxFor "clang")
+  assertEqual "cc" "/usr/bin/c++" (cxxFor "/usr/bin/cc")
+  assertEqual "versioned clang" "/usr/bin/clang++-18" (cxxFor "/usr/bin/clang-18")
+  assertEqual "prefixed gcc" "x86_64-linux-gnu-g++-13" (cxxFor "x86_64-linux-gnu-gcc-13")
+  assertEqual "already C++" "none" (cxxFor "clang++")
+  assertEqual "unknown" "none" (cxxFor "icx")
+
 -- | Adding, changing and removing the block that @--cache@ puts in a config
 -- file, without touching anything else in it.
 spliceBlockTest :: IO ()
@@ -302,6 +436,14 @@
   tools <- readIn project toolsPath
   assertContains toolsPath "GHC_FINGERPRINT = \"" tools
   assertContains toolsPath "CC_FINGERPRINT = \"" tools
+  -- The C tools are run from a directory named by that fingerprint, so that
+  -- it is part of the commands that run them. (Those that were found: one
+  -- that wasn't, such as clang where it isn't installed, is run by its name.)
+  let ccPrint = [takeWhile (/= '"') (drop (length "CC_FINGERPRINT = \"") l) | l <- lines tools, "CC_FINGERPRINT = " `isPrefixOf` l]
+  forM_ ccPrint $ \fp ->
+    forM_ [("CC", "cc"), ("CXX", "cxx"), ("LINKER", "linker")] $ \(var, role) ->
+      forM_ [l | l <- lines tools, (var ++ " = ") `isPrefixOf` l, ("/toolchain/" ++ role ++ "/") `isInfixOf` l] $
+        assertContains toolsPath ("/toolchain/" ++ role ++ "/" ++ fp ++ "/")
   _ <- buck2 project ["--enable-tests", "--enable-benchmarks", "-f+loud"]
   tools' <- readIn project toolsPath
   assertEqual "tools.bzl after a second run" tools tools'
@@ -444,6 +586,9 @@
   -- Where it is, is in packages.bzl, with the packages of the project.
   packages <- readIn project ("cabal-buck2" </> "packages.bzl")
   assertContains "cabal-buck2/packages.bzl" "'dep': 'dist-newstyle/src/dep-1.0'," packages
+  -- dep has data-files, so dep needs them, and so does app, which depends on
+  -- dep and so may run dep's code.
+  assertContains "cabal-buck2/packages.bzl" "DATA_PACKAGES = {\n    'app': [\n        'dep',\n    ],\n    'dep': [\n        'dep',\n    ],\n}" packages
   -- Its data files are recorded, for the tools that read them.
   assertContains depBzlPath "'data/*.txt'" depBzl
   -- hsc2hs is told what it is compiling for.
@@ -519,6 +664,21 @@
   -- and for buck2 to run pkg-config for the C sources there are.
   spec "'pkgconfig': [\n                'foo',\n            ]" bzl
 
+-- | Each of a library's install-includes is in the spec with the file that
+-- Cabal would install, found as Cabal finds it: in the package's directory
+-- first, and then in its include-dirs.
+installIncludes :: Project -> IO ()
+installIncludes project = do
+  _ <- buck2 project []
+  bzl <- readIn project ("lib" </> "BUCK.cabal.bzl")
+  let spec = assertContains "lib/BUCK.cabal.bzl"
+  spec "{\n                    'path': 'inc.h',\n                    'src': 'include/inc.h',\n                }" bzl
+  spec "{\n                    'path': 'top.h',\n                    'src': 'top.h',\n                }" bzl
+  spec "{\n                    'path': 'sub/nested.h',\n                    'src': 'include/sub/nested.h',\n                }" bzl
+  -- A header that isn't in the package has no file. What is compiled
+  -- against the library looks for it in the directories of generated headers.
+  spec "{\n                    'path': 'generated.h',\n                }" bzl
+
 -- | The checkout of haskell-buck2 has to be for this release of cabal-buck2:
 -- if it is not, or doesn't say, the error says which branch is needed.
 buck2Version :: Project -> IO ()
@@ -541,6 +701,40 @@
   _ <- buck2 project []
   return ()
 
+-- | A project without a buck2/ directory gets a copy of the one that was
+-- installed with cabal-buck2. That copy is replaced when a different release
+-- of cabal-buck2 runs.
+--
+-- The test does nothing when buck2 runs it (see BUCK), because then the data
+-- files of cabal-buck2 don't include the support code. In this project,
+-- buck2/ is a buck2 package of its own and buck2/prelude is a separate cell,
+-- and the glob that collects the data files of the root package doesn't look
+-- inside either of them.
+buck2Unpack :: Project -> IO ()
+buck2Unpack project = do
+  dataDir <- lookupEnv "cabal_buck2_datadir"
+  available <- maybe (return True) (\d -> doesFileExist (d </> "buck2" </> "version.bzl")) dataDir
+  when available $ buck2UnpackTest project
+
+buck2UnpackTest :: Project -> IO ()
+buck2UnpackTest project = do
+  let dir = projectDir project </> "buck2"
+      checkVersion what = do
+        version <- readIn project ("buck2" </> "version.bzl")
+        assertContains what ("CABAL_BUCK2_VERSION = \"" ++ cabalBuck2Version ++ "\"") version
+  removeDirectoryRecursive dir
+  _ <- buck2 project []
+  checkVersion "unpacked buck2/version.bzl"
+  isExe <- executable <$> getPermissions (dir </> "run_test.sh")
+  unless isExe $ failure "buck2/run_test.sh was unpacked without its executable permission"
+
+  writeBuck2Version (projectDir project) "0.0.0.1"
+  writeFile (dir </> "stale") ""
+  _ <- buck2 project []
+  checkVersion "replaced buck2/version.bzl"
+  stale <- doesFileExist (dir </> "stale")
+  when stale $ failure "buck2/ for another release was not replaced"
+
 -- | A package with a @Custom@ build type needs its @Setup.hs@ to be run, which
 -- is not done: it, and what depends on it, can't be built.
 customSetup :: Project -> IO ()
@@ -569,52 +763,100 @@
   appBzl <- readIn project ("app" </> "BUCK.cabal.bzl")
   assertContains "app BUCK.cabal.bzl" "'kind': 'executable'" appBzl
 
--- | A project's @cabal-buck2.bzl@, with its overrides of the generated
--- targets, is loaded by @packages.bzl@, and an empty set of overrides is
--- given there if there is none.
+  -- A build without --source-deps puts custom-dep in the store, so the plan
+  -- has it as installed. With --source-deps it must still be translated.
+  _ <- buck2 project ["--enable-custom-setup"]
+  fromStore <- buck2 project ["--source-deps", "--enable-custom-setup"]
+  assertContains "warning" "custom-dep-0.1 as if it had build-type: Simple" fromStore
+  assertNotContains "output" "skipping" fromStore
+
+-- | A project's @cabal-buck2.bzl@, with its overrides and defaults for the
+-- generated targets, is loaded by @packages.bzl@. Whichever of them the
+-- project doesn't define is given there as empty.
 projectOverrides :: Project -> IO ()
 projectOverrides project = do
+  let packagesWith bzl = do
+        writeFile (projectDir project </> "cabal-buck2.bzl") bzl
+        _ <- buck2 project []
+        readIn project ("cabal-buck2" </> "packages.bzl")
   _ <- buck2 project []
   without <- readIn project ("cabal-buck2" </> "packages.bzl")
   assertContains "packages.bzl" "OVERRIDES = {}" without
+  assertContains "packages.bzl" "DEFAULTS = {}" without
   assertNotContains "packages.bzl" "cabal-buck2.bzl\"" without
 
-  writeFile (projectDir project </> "cabal-buck2.bzl") "OVERRIDES = {}\n"
-  _ <- buck2 project []
-  with <- readIn project ("cabal-buck2" </> "packages.bzl")
-  assertContains "packages.bzl" "load(\"//:cabal-buck2.bzl\", _OVERRIDES = \"OVERRIDES\")" with
-  assertContains "packages.bzl" "OVERRIDES = _OVERRIDES" with
+  overrides <- packagesWith "OVERRIDES = {}\n"
+  assertContains "packages.bzl" "load(\"//:cabal-buck2.bzl\", _OVERRIDES = \"OVERRIDES\")" overrides
+  assertContains "packages.bzl" "OVERRIDES = _OVERRIDES" overrides
+  assertContains "packages.bzl" "DEFAULTS = {}" overrides
 
+  -- A comparison, or a name that only starts with DEFAULTS, isn't a
+  -- definition of it.
+  defaults <- packagesWith "DEFAULTS = {\"*\": {}}\nDEFAULTS == {}\nDEFAULTS_X = {}\n"
+  assertContains "packages.bzl" "load(\"//:cabal-buck2.bzl\", _DEFAULTS = \"DEFAULTS\")" defaults
+  assertContains "packages.bzl" "DEFAULTS = _DEFAULTS" defaults
+  assertContains "packages.bzl" "OVERRIDES = {}" defaults
+
+  both <- packagesWith "DEFAULTS={}\nOVERRIDES = {}\n"
+  assertContains "packages.bzl" "load(\"//:cabal-buck2.bzl\", _OVERRIDES = \"OVERRIDES\", _DEFAULTS = \"DEFAULTS\")" both
+
 -- | @--cache=ADDRESS@ adds the cache's settings to @.buckconfig@, which are
 -- kept by later runs without the flag, and @--no-cache@ removes.
 cacheConfig :: Project -> IO ()
 cacheConfig project = do
   let buckconfig = ".buckconfig"
+      local = ".buckconfig.local"
+      localPath = projectDir project </> local
       block = "# >>> cabal buck2: cache"
   before <- readIn project buckconfig
   assertNotContains buckconfig block before
+  localBefore <- doesFileExist localPath
+  when localBefore $ failure (local ++ " exists before --cache")
 
+  -- The block goes in .buckconfig.local, which is created for it; the
+  -- project's .buckconfig is left alone.
   out <- buck2 project ["--cache=grpc://127.0.0.1:9092"]
   -- A running buck2 daemon would keep the old settings.
   assertContains "notice" "buck2 kill" out
-  withCache <- readIn project buckconfig
-  assertContains buckconfig "[cabal_buck2]\n  cache = true" withCache
-  assertContains buckconfig "default_allow_cache_upload = true" withCache
-  assertContains buckconfig "action_cache_address = grpc://127.0.0.1:9092" withCache
-  assertContains buckconfig "tls = false" withCache
-  -- What was there is kept.
-  assertContains buckconfig (take 40 before) withCache
+  withCache <- readIn project local
+  assertContains local "[cabal_buck2]\n  cache = true" withCache
+  assertContains local "default_allow_cache_upload = true" withCache
+  assertContains local "action_cache_address = grpc://127.0.0.1:9092" withCache
+  assertContains local "tls = false" withCache
+  afterOn <- readIn project buckconfig
+  assertEqual "the .buckconfig after --cache" before afterOn
 
   -- Later runs leave it alone.
   _ <- buck2 project []
-  again <- readIn project buckconfig
+  again <- readIn project local
   assertEqual "after a run without --cache" withCache again
 
-  -- Removing it restores the original file.
+  -- Removing it removes the file it was the only thing in.
   _ <- buck2 project ["--no-cache"]
-  without <- readIn project buckconfig
-  assertEqual "after --no-cache" before without
+  localAfter <- doesFileExist localPath
+  when localAfter $ failure (local ++ " left behind by --no-cache")
 
+  -- What else is in .buckconfig.local is kept.
+  let mine = "[haskell]\n  compiler_flags = -Wall\n"
+  writeFile localPath mine
+  _ <- buck2 project ["--cache=grpc://127.0.0.1:9092"]
+  mixed <- readIn project local
+  assertContains local mine mixed
+  assertContains local block mixed
+  _ <- buck2 project ["--no-cache"]
+  mineAgain <- readIn project local
+  assertEqual "after --no-cache" mine mineAgain
+  removeFile localPath
+
+  -- A block that an earlier version put in .buckconfig is moved out.
+  writeFile (projectDir project </> buckconfig) (spliceBlock (Just (cacheBlock "grpc://127.0.0.1:9092")) before)
+  _ <- buck2 project ["--cache=grpc://127.0.0.1:9092"]
+  moved <- readIn project buckconfig
+  assertEqual "the .buckconfig after moving the block out" before moved
+  movedTo <- readIn project local
+  assertContains local "action_cache_address = grpc://127.0.0.1:9092" movedTo
+  _ <- buck2 project ["--no-cache"]
+
   -- Mistakes are reported.
   (badCode, badOut) <- runBuck2 project ["--cache=http://example.org"]
   when (badCode == ExitSuccess) $ failure "--cache=http://... was accepted"
@@ -668,9 +910,62 @@
 
 -- | Libraries outside GHC's libdir and the cabal store (as in a Nix
 -- @ghcWithPackages@) are reached through a symlink for each directory.
+-- | The data-files of cabal-buck2.cabal are the files of the haskell-buck2
+-- submodule (buck2/) that cabal-buck2 copies into a project. They should be
+-- all of the submodule's files apart from those that 'notShipped' leaves out.
+-- When this fails because of a new file in the submodule, the file probably
+-- needs a pattern of its own: a pattern can't match every kind of file.
+--
+-- It also checks that every executable file that is shipped starts with @#!@,
+-- because that is how the copy in a project gets its executable permission
+-- back (Cabal installs data files without it).
+--
+-- This needs the git checkout of the submodule, so it does nothing in an
+-- unpacked sdist.
+dataFilesTest :: IO ()
+dataFilesTest = do
+  checkout <- (&&) <$> doesFileExist "cabal-buck2.cabal" <*> doesPathExist ("buck2" </> ".git")
+  when checkout $ do
+    gpd <- readGenericPackageDescription verbosity Nothing (makeSymbolicPath "cabal-buck2.cabal")
+    let pd = packageDescription gpd
+    matched <- concat <$> mapM (matchDirFileGlob verbosity (specVersion pd) Nothing) (dataFiles pd)
+    -- Each line is "<mode> <object> <stage>\t<path>".
+    entries <- map (break (== '\t')) . lines <$> readProcess "git" ["-C", "buck2", "ls-files", "--stage"] ""
+    let tracked = [(path, takeWhile (/= ' ') mode) | (mode, _ : path) <- entries, not (notShipped path)]
+        expected = Set.fromList ["buck2" </> path | (path, _) <- tracked]
+        shipped = Set.fromList (map getSymbolicPath matched)
+        unmatched = Set.toList (expected `Set.difference` shipped)
+        unwanted = Set.toList (shipped `Set.difference` expected)
+    unless (null unmatched) $ failure ("files of buck2/ that no data-files pattern matches:\n" ++ unlines unmatched)
+    unless (null unwanted) $ failure ("data-files that should be left out:\n" ++ unlines unwanted)
+    scripts <- forM [path | (path, "100755") <- tracked, path `notElem` notScripts] $ \path -> do
+      start <- BS8.take 2 <$> BS8.readFile ("buck2" </> path)
+      return (path, start == BS8.pack "#!")
+    let noShebang = [path | (path, False) <- scripts]
+    unless (null noShebang) $ failure ("executable files of buck2/ that don't start with #!:\n" ++ unlines noShebang)
+  where
+    verbosity = mkVerbosity defaultVerbosityHandles silent
+    notShipped path =
+      -- The buck2 build doesn't use the cabal.project and the cabal package
+      -- of haskell-buck2's persistent worker. Those are only for working on
+      -- the worker with cabal.
+      path `elem` ["flake.nix", "flake.lock", "perf-chart.svg", "CLAUDE.md", "cabal.project", ".gitignore", "prelude/.gitignore", "prelude/toolchains/apple/xcode_version_checker/.gitignore", "prelude/haskell/tools/worker/.gitignore", "prelude/haskell/tools/worker/buck2-ghc-worker.cabal"]
+        || any (`isPrefixOf` path) ["tests/", ".github/", "prelude/toolchains/android/test/", "prelude/ide_integrations/visual_studio/assets/"]
+    -- These are executable in git, but nothing that builds Haskell runs them.
+    -- The Python ones are the main modules of python_bootstrap_binary
+    -- targets, which run them with the Python interpreter. The others are
+    -- used only when building or testing Java or Apple code.
+    notScripts =
+      [ "prelude/apple/tools/selective_debugging/test_resources/HelloWorld"
+      , "prelude/git/tools/git_fetch.py"
+      , "prelude/rust/tools/buildscript_run.py"
+      , "prelude/toolchains/android/src/com/facebook/buck/testrunner/BaseRunner.java"
+      , "prelude/toolchains/apple/xcode_version_checker/xcode_version_checker"
+      ]
+
 externalDirsTest :: IO ()
 externalDirsTest = do
-  let paths = RepoPaths{rpGhcVersion = "9.6.7", rpGlobalRootAbs = "/ghc/lib", rpStoreRootAbs = "/home/u/.cabal/store/ghc-9.6.7", rpStoreDbRel = "package.db", rpExternal = [], rpDllExtension = "so", rpPicByDefault = False}
+  let paths = RepoPaths{rpGhcVersion = "9.6.7", rpGlobalRootAbs = "/ghc/lib", rpStoreRootAbs = "/home/u/.cabal/store/ghc-9.6.7", rpStoreDbRel = "package.db", rpExternal = Map.empty, rpDllExtension = "so", rpPicByDefault = False}
       aeson = "/nix/store/aaa-aeson-lib-aeson-2.2.5.1/lib/x86_64-linux-ghc-9.6.7"
       text = "/nix/store/bbb-text-lib-text-2.1.4/lib/x86_64-linux-ghc-9.6.7"
       dirs =
@@ -690,7 +985,7 @@
   let names = map snd linked
   check "links are in external/" True (all (\n -> take 9 n == "external/") names)
   check "the links are different" 2 (length (nub names))
-  let paths' = paths{rpExternal = linked}
+  let paths' = paths{rpExternal = Map.fromList linked}
       aesonLink = fromMaybe (error "no link for aeson") (lookup aeson linked)
   check "a library in a linked directory" (Just (aesonLink ++ "/aeson-2.2.5.1-X/libHSaeson-2.2.5.1-X.a")) (toRepoRelative paths' (aeson ++ "/aeson-2.2.5.1-X/libHSaeson-2.2.5.1-X.a"))
   check "a library under GHC's libdir" (Just "ghc-9.6.7/x86_64-linux-ghc-9.6.7/base-4.18.3.0/libHSbase.a") (toRepoRelative paths' "/ghc/lib/x86_64-linux-ghc-9.6.7/base-4.18.3.0/libHSbase.a")
diff --git a/test/fixtures/custom-setup/dep/custom-dep-0.1/Setup.hs b/test/fixtures/custom-setup/dep/custom-dep-0.1/Setup.hs
--- a/test/fixtures/custom-setup/dep/custom-dep-0.1/Setup.hs
+++ b/test/fixtures/custom-setup/dep/custom-dep-0.1/Setup.hs
@@ -1,4 +1,15 @@
 import Distribution.Simple
+import System.Directory (createDirectoryIfMissing)
 
+-- This generates Custom.Generated, the module that autogen-modules lists, so
+-- that cabal can build the package into the store. With --enable-custom-setup,
+-- cabal buck2 doesn't run this file, so the project has to provide the module.
 main :: IO ()
-main = defaultMain
+main =
+  defaultMainWithHooks
+    simpleUserHooks
+      { preBuild = \args flags -> do
+          createDirectoryIfMissing True "Custom"
+          writeFile "Custom/Generated.hs" "module Custom.Generated where\n"
+          preBuild simpleUserHooks args flags
+      }
diff --git a/test/fixtures/custom-setup/dep/custom-dep-0.1/custom-dep.cabal b/test/fixtures/custom-setup/dep/custom-dep-0.1/custom-dep.cabal
--- a/test/fixtures/custom-setup/dep/custom-dep-0.1/custom-dep.cabal
+++ b/test/fixtures/custom-setup/dep/custom-dep-0.1/custom-dep.cabal
@@ -4,11 +4,11 @@
 build-type:    Custom
 
 custom-setup
-  setup-depends: base, Cabal
+  setup-depends: base, Cabal, directory
 
 library
   exposed-modules:  Custom.Dep, Custom.Generated
-  -- What a real Setup.hs would generate.
+  -- Setup.hs generates this module.
   autogen-modules:  Custom.Generated
   build-depends:    base
   default-language: Haskell2010
diff --git a/test/fixtures/install-includes/.buckconfig b/test/fixtures/install-includes/.buckconfig
new file mode 100644
--- /dev/null
+++ b/test/fixtures/install-includes/.buckconfig
@@ -0,0 +1,4 @@
+# Placeholder: this test only checks `cabal buck2`'s generated files, it
+# never actually invokes a real buck2 binary, so this doesn't need to be
+# a functional buck2 config - it only needs to exist so that
+# `ensureBuckconfigAndPackage` sees it's already there and leaves it alone.
diff --git a/test/fixtures/install-includes/PACKAGE b/test/fixtures/install-includes/PACKAGE
new file mode 100644
--- /dev/null
+++ b/test/fixtures/install-includes/PACKAGE
@@ -0,0 +1,1 @@
+# Placeholder - see .buckconfig.
diff --git a/test/fixtures/install-includes/buck2/.gitkeep b/test/fixtures/install-includes/buck2/.gitkeep
new file mode 100644
--- /dev/null
+++ b/test/fixtures/install-includes/buck2/.gitkeep
diff --git a/test/fixtures/install-includes/cabal.project b/test/fixtures/install-includes/cabal.project
new file mode 100644
--- /dev/null
+++ b/test/fixtures/install-includes/cabal.project
@@ -0,0 +1,3 @@
+packages: lib
+
+active-repositories: :none
diff --git a/test/fixtures/install-includes/lib/L.hs b/test/fixtures/install-includes/lib/L.hs
new file mode 100644
--- /dev/null
+++ b/test/fixtures/install-includes/lib/L.hs
@@ -0,0 +1,1 @@
+module L where
diff --git a/test/fixtures/install-includes/lib/include/inc.h b/test/fixtures/install-includes/lib/include/inc.h
new file mode 100644
--- /dev/null
+++ b/test/fixtures/install-includes/lib/include/inc.h
@@ -0,0 +1,1 @@
+/* include/inc.h, for the test of install-includes. */
diff --git a/test/fixtures/install-includes/lib/include/sub/nested.h b/test/fixtures/install-includes/lib/include/sub/nested.h
new file mode 100644
--- /dev/null
+++ b/test/fixtures/install-includes/lib/include/sub/nested.h
@@ -0,0 +1,1 @@
+/* include/sub/nested.h, for the test of install-includes. */
diff --git a/test/fixtures/install-includes/lib/include/top.h b/test/fixtures/install-includes/lib/include/top.h
new file mode 100644
--- /dev/null
+++ b/test/fixtures/install-includes/lib/include/top.h
@@ -0,0 +1,1 @@
+/* include/top.h, for the test of install-includes. */
diff --git a/test/fixtures/install-includes/lib/lib.cabal b/test/fixtures/install-includes/lib/lib.cabal
new file mode 100644
--- /dev/null
+++ b/test/fixtures/install-includes/lib/lib.cabal
@@ -0,0 +1,15 @@
+cabal-version:     3.0
+name:              lib
+version:           0.1
+build-type:        Simple
+
+library
+  exposed-modules:   L
+  build-depends:     base
+  include-dirs:      include
+  -- inc.h and sub/nested.h are in include/. top.h is in both the package's
+  -- directory and include/, and Cabal installs the one in the package's
+  -- directory. generated.h isn't in the package: a configure script would
+  -- have generated it.
+  install-includes:  inc.h, top.h, sub/nested.h, generated.h
+  default-language:  Haskell2010
diff --git a/test/fixtures/install-includes/lib/top.h b/test/fixtures/install-includes/lib/top.h
new file mode 100644
--- /dev/null
+++ b/test/fixtures/install-includes/lib/top.h
@@ -0,0 +1,1 @@
+/* top.h, for the test of install-includes. */
